Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(chat): inherit per-repo provider/model/key from init config (#434)
Raghav Chamadiya0653820efe84
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.pyindex d909a6e84..fab4e0e13 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py@@ -265,11 +265,14 @@ def save_full_state_and_config(if kg is not None:save_knowledge_graph_json(repo_path, kg)+ from repowise.cli.providers.embedders import resolve_embedding_model+save_config(repo_path,provider.provider_name,provider.model_name,embedder_name_resolved,+ embedding_model=resolve_embedding_model(embedder_name_resolved),exclude_patterns=exclude_patterns if exclude_patterns else None,commit_limit=resolved_commit_limit if commit_limit is not None else None,reasoning=resolved_reasoning,diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex 151b42be3..db23f396f 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -349,11 +349,14 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt# Persist provider/model config per-repo when doing full generationif not index_only and provider is not None:+ from repowise.cli.providers.embedders import resolve_embedding_model+save_config(repo.path,provider.provider_name,provider.model_name,ctx.embedder_name_resolved,+ embedding_model=resolve_embedding_model(ctx.embedder_name_resolved),exclude_patterns=ctx.exclude_patterns if ctx.exclude_patterns else None,commit_limit=ctx.resolved_commit_limit,reasoning=ctx.resolved_reasoning,diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.pyindex 60da54ceb..861b463bf 100644--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py@@ -189,6 +189,13 @@ def _load_local_provider_config() -> None:if embedder and embedder != "mock" and not os.environ.get("REPOWISE_EMBEDDER"):os.environ["REPOWISE_EMBEDDER"] = str(embedder)+ # 4) Embedding model from config — without this the server rebuilds the+ # embedder with a provider default (e.g. text-embedding-3-small) that+ # mismatches the indexed vectors, degrading chat/search retrieval (#426).+ embedding_model = cfg.get("embedding_model")+ if embedding_model and not os.environ.get("REPOWISE_EMBEDDING_MODEL"):+ os.environ["REPOWISE_EMBEDDING_MODEL"] = str(embedding_model)+def _is_port_free(host: str, port: int) -> bool:"""Return True if *port* can be bound on *host* right now."""diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 5283b83db..30c90247d 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -505,6 +505,7 @@ def save_config(model: str,embedder: str,*,+ embedding_model: str | None = None,exclude_patterns: list[str] | None = None,commit_limit: int | None = None,reasoning: str | None = None,@@ -512,6 +513,11 @@ def save_config("""Write provider/model/embedder (and optionally exclude_patterns) to ``.repowise/config.yaml``.Performs a round-trip load so existing keys are preserved.++ ``embedding_model`` is persisted so ``repowise serve`` can rebuild the same+ embedder used at init time — without it the server silently falls back to a+ provider default (e.g. ``text-embedding-3-small``), which mismatches the+ indexed vectors and breaks chat/search retrieval (issue #426)."""ensure_repowise_dir(repo_path)config_path = get_repowise_dir(repo_path) / CONFIG_FILENAME@@ -521,6 +527,8 @@ def save_config(existing["provider"] = providerexisting["model"] = modelexisting["embedder"] = embedder+ if embedding_model:+ existing["embedding_model"] = embedding_modelif exclude_patterns is not None:existing["exclude_patterns"] = exclude_patternsif commit_limit is not None:@@ -538,6 +546,8 @@ def save_config(except ImportError:# Fallback: write simple key-value format (lists not supported)lines = [f"provider: {provider}", f"model: {model}", f"embedder: {embedder}"]+ if embedding_model:+ lines.append(f"embedding_model: {embedding_model}")if reasoning is not None:lines.append(f"reasoning: {resolve_reasoning(reasoning)}")config_path.write_text("\n".join(lines) + "\n", encoding="utf-8")diff --git a/packages/cli/src/repowise/cli/providers/embedders.py b/packages/cli/src/repowise/cli/providers/embedders.pyindex 42b8ad5fd..ee51bbef6 100644--- a/packages/cli/src/repowise/cli/providers/embedders.py+++ b/packages/cli/src/repowise/cli/providers/embedders.py@@ -28,6 +28,21 @@ def _embedder_kwargs(embedder_name: str) -> dict[str, Any]:return kwargs+def resolve_embedding_model(embedder_name: str) -> str | None:+ """Return the configured embedding model for *embedder_name*, if any.++ Mirrors the precedence in :func:`_embedder_kwargs` so the value persisted+ to ``config.yaml`` at init time is exactly what the embedder would build+ with. Returns ``None`` when no model is configured (the embedder then uses+ its own default), which keeps ``config.yaml`` free of empty keys.+ """+ if embedder_name == "ollama":+ return os.environ.get("OLLAMA_EMBEDDING_MODEL") or os.environ.get(+ "REPOWISE_EMBEDDING_MODEL"+ )+ return os.environ.get("REPOWISE_EMBEDDING_MODEL")++def resolve_embedder(embedder_flag: str | None) -> str:"""Auto-detect embedder from env vars, or use the flag value."""if embedder_flag:diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.pyindex bfb1a67eb..8b73ef8bf 100644--- a/packages/core/src/repowise/core/repo_config.py+++ b/packages/core/src/repowise/core/repo_config.py@@ -46,3 +46,56 @@ def _read_flat_scalar(text: str, key: str) -> str | None:if separator and current_key.strip() == key:return value.split("#", 1)[0].strip().strip("'\"")return None+++def load_repo_env(repo_path: Path | str) -> dict[str, str]:+ """Parse ``.repowise/.env`` into a dict **without** mutating ``os.environ``.++ The CLI's ``load_dotenv`` merges the file into the live process+ environment, which is correct for ``repowise update`` (one repo per+ process) but unsafe for a long-lived ``repowise serve`` that fields+ requests for many repos in a workspace — one repo's keys would leak into+ every other repo's resolution. This pure reader lets the server resolve a+ provider per-repo from that repo's own ``.env`` instead.++ Accepts the same syntax as ``load_dotenv``: ``export KEY=value``, quoted+ values, and whitespace-delimited inline comments.+ """+ env_file = get_repowise_dir(repo_path) / ".env"+ if not env_file.exists():+ return {}++ result: dict[str, str] = {}+ try:+ text = env_file.read_text(encoding="utf-8")+ except OSError:+ return {}++ for raw_line in text.splitlines():+ line = raw_line.strip()+ if not line or line.startswith("#"):+ continue+ if line.startswith("export "):+ line = line[len("export ") :].lstrip()+ if "=" not in line:+ continue+ key, _, raw_value = line.partition("=")+ key = key.strip()+ raw_value = raw_value.strip()+ # Strip whitespace-delimited inline comments (keep '#' inside URLs).+ hash_idx = raw_value.find(" #")+ if hash_idx == -1:+ hash_idx = raw_value.find("\t#")+ if hash_idx >= 0:+ raw_value = raw_value[:hash_idx].rstrip()+ value = _strip_quotes(raw_value)+ if key and value:+ result[key] = value+ return result+++def _strip_quotes(value: str) -> str:+ """Strip one pair of matching surrounding single or double quotes."""+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):+ return value[1:-1]+ return valuediff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex b35191db8..9e539fffd 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -75,6 +75,11 @@ def _build_embedder():from repowise.core.providers.embedding.gemini import GeminiEmbedderdims = int(os.environ.get("REPOWISE_EMBEDDING_DIMS", "768"))+ # Honour the indexed embedding model so serve doesn't silently rebuild+ # the embedder with a different default than init used (issue #426).+ model = os.environ.get("REPOWISE_EMBEDDING_MODEL")+ if model:+ return GeminiEmbedder(model=model, output_dimensionality=dims)return GeminiEmbedder(output_dimensionality=dims)if name == "openai":from repowise.core.providers.embedding.openai import OpenAIEmbedder@@ -184,12 +189,12 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:app.state.workspace_config = Noneapp.state.workspace_root = Noneapp.state.cross_repo_enricher = None- app.state.workspace_sessions = {} # repo_id → session_factory- app.state.workspace_engines = [] # engines to dispose on shutdown+ app.state.workspace_sessions = {} # repo_id → session_factory+ app.state.workspace_engines = [] # engines to dispose on shutdown# Per-repo FTS instances keyed by repo_id, used by the search router# to fan out across every workspace repo (single-repo FTS lives on# app.state.fts and stays as the primary).- app.state.workspace_fts = {} # repo_id → FullTextSearch+ app.state.workspace_fts = {} # repo_id → FullTextSearch# repo_id → vector store (LanceDB-backed) for per-repo semantic search.# Populated lazily by the search router on first use, then cached.app.state.workspace_vector_stores = {} # repo_id → VectorStorediff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex e9d183308..5060faed3 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -278,7 +278,10 @@ async def execute_job(try:from repowise.server.provider_config import get_chat_provider_instance- llm_client = get_chat_provider_instance()+ # Pass the repo path so the job reuses the provider/model/key the+ # repo was configured with (``.repowise/config.yaml`` + ``.env``)+ # rather than the server-global default.+ llm_client = get_chat_provider_instance(repo_path=repo_path)except Exception as exc:logger.warning("no_provider_configured", error=str(exc))# Continue without LLM — ingestion + analysis still workdiff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.pyindex 228fe2b75..5506272e6 100644--- a/packages/server/src/repowise/server/provider_config.py+++ b/packages/server/src/repowise/server/provider_config.py@@ -112,9 +112,13 @@ def _load_config() -> dict[str, Any]:def _save_config(config: dict[str, Any]) -> None:+ # Write-then-rename so a concurrent reader (or a second writer racing on+ # the read-modify-write) never sees a half-written file or a truncated one.path = _config_path()path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(json.dumps(config, indent=2), encoding="utf-8")+ tmp = path.with_suffix(f"{path.suffix}.tmp.{os.getpid()}")+ tmp.write_text(json.dumps(config, indent=2), encoding="utf-8")+ os.replace(tmp, path)# ---------------------------------------------------------------------------@@ -122,75 +126,177 @@ def _save_config(config: dict[str, Any]) -> None:# ----------------------------------------------------------------------------def _get_key_for_provider(provider_id: str) -> str | None:- """Get API key: env var takes precedence, then stored config."""+_BASE_URL_ENV_VARS = {+ "anthropic": ["ANTHROPIC_BASE_URL"],+ "openai": ["OPENAI_BASE_URL"],+ "gemini": ["GEMINI_BASE_URL"],+ "ollama": ["OLLAMA_BASE_URL"],+ "deepseek": ["DEEPSEEK_BASE_URL"],+ "litellm": ["LITELLM_BASE_URL", "LITELLM_API_BASE"],+}+++def _load_repo_context(repo_path: str | Path | None) -> tuple[dict[str, Any], dict[str, str]]:+ """Load a repo's ``config.yaml`` dict and ``.env`` dict for resolution.++ Returns ``({}, {})`` when no path is given so callers can resolve the+ server-global configuration unchanged. The ``.env`` is read into a plain+ dict (never ``os.environ``) so per-request, per-repo resolution can't leak+ one repo's keys into another's in a long-lived workspace server.+ """+ if repo_path is None:+ return {}, {}+ from repowise.core.repo_config import load_repo_config, load_repo_env++ try:+ cfg = load_repo_config(repo_path)+ except Exception:+ cfg = {}+ try:+ env = load_repo_env(repo_path)+ except Exception:+ env = {}+ return cfg, env+++def _get_key_for_provider(provider_id: str, repo_env: dict[str, str] | None = None) -> str | None:+ """Resolve an API key: process env > repo ``.env`` > stored server config.++ ``repo_env`` is the target repo's ``.repowise/.env`` (parsed, not applied+ to ``os.environ``). Honouring it is what makes chat use the same key the+ user supplied at ``repowise init`` time, even in workspace mode where the+ server never loads any single repo's ``.env`` into its own environment.+ """catalog = _CATALOG_BY_ID.get(provider_id)if not catalog:return None- # Check env vars firstfor env_key in catalog.get("env_keys", []):val = os.environ.get(env_key)if val:return val+ if repo_env:+ for env_key in catalog.get("env_keys", []):+ val = repo_env.get(env_key)+ if val:+ return val- # Check stored configconfig = _load_config()keys = config.get("keys", {})return keys.get(provider_id)-def _get_base_url_for_provider(provider_id: str) -> str | None:- """Resolve a provider base_url from environment variables."""- env_map = {- "anthropic": ["ANTHROPIC_BASE_URL"],- "openai": ["OPENAI_BASE_URL"],- "gemini": ["GEMINI_BASE_URL"],- "ollama": ["OLLAMA_BASE_URL"],- "deepseek": ["DEEPSEEK_BASE_URL"],- "litellm": ["LITELLM_BASE_URL", "LITELLM_API_BASE"],- }- for env_var in env_map.get(provider_id, []):+def _get_base_url_for_provider(+ provider_id: str,+ repo_env: dict[str, str] | None = None,+ repo_cfg: dict[str, Any] | None = None,+) -> str | None:+ """Resolve a provider base_url: process env > repo ``.env`` > repo config.++ Mirrors the CLI's resolution (``cli/helpers.resolve_provider``) so a+ local LiteLLM/OpenAI-compatible endpoint configured at init is reused by+ chat. The repo ``config.yaml`` may carry it under a per-provider section,+ e.g. ``openai: {base_url: http://localhost:4000/v1}``.+ """+ env_vars = _BASE_URL_ENV_VARS.get(provider_id, [])+ for env_var in env_vars:val = os.environ.get(env_var)if val:return val+ if repo_env:+ for env_var in env_vars:+ val = repo_env.get(env_var)+ if val:+ return val+ if repo_cfg:+ section = repo_cfg.get(provider_id)+ if isinstance(section, dict) and section.get("base_url"):+ return str(section["base_url"])return None-def list_provider_status() -> dict[str, Any]:- """Return the full provider status including active selection."""+def _resolve_active_for_repo(+ repo_id: str | None,+ repo_cfg: dict[str, Any],+ repo_env: dict[str, str] | None = None,+) -> tuple[str | None, str | None]:+ """Resolve the (provider, model) for a repo's chat, most specific first.++ Precedence:+ 1. Per-repo UI selection persisted under ``repos[repo_id]`` — an+ explicit override the user made for *this* repo. Stored per-repo so+ selecting a model for one repo never shadows another's config (the+ original bug behind issue #426).+ 2. The repo's own ``config.yaml`` (``provider`` + ``model``) written by+ ``repowise init`` — the seamless default.+ 3. The server-global ``active_provider`` (legacy single-repo UI state).+ 4. ``REPOWISE_PROVIDER`` / ``REPOWISE_MODEL`` env vars.+ 5. Auto-detect the first provider with a usable key.+ """config = _load_config()- active_id = config.get("active_provider")- active_model = config.get("active_model")-- # Honour the repo's configured provider/model (``.repowise/config.yaml``,- # surfaced as env vars by ``repowise serve``) when nothing has been- # explicitly selected through the UI/config file yet.- if not active_id:- env_provider = os.environ.get("REPOWISE_PROVIDER")- if env_provider and env_provider in _CATALOG_BY_ID:- active_id = env_provider- active_model = os.environ.get("REPOWISE_MODEL") or _CATALOG_BY_ID[- env_provider- ]["default_model"]-- # Auto-detect active if still unset- if not active_id:- for p in PROVIDER_CATALOG:- if _get_key_for_provider(p["id"]) or not p["requires_key"]:- active_id = p["id"]- active_model = p["default_model"]- break++ def _with_default(pid: str | None, model: str | None) -> tuple[str | None, str | None]:+ if pid and not model:+ model = _CATALOG_BY_ID.get(pid, {}).get("default_model")+ return pid, model++ # 1. Per-repo persisted selection+ if repo_id:+ repos = config.get("repos") or {}+ sel = repos.get(repo_id)+ if isinstance(sel, dict) and sel.get("provider") in _CATALOG_BY_ID:+ return _with_default(sel["provider"], sel.get("model"))++ # 2. Repo config.yaml+ cfg_provider = repo_cfg.get("provider")+ if cfg_provider in _CATALOG_BY_ID:+ return _with_default(cfg_provider, repo_cfg.get("model"))++ # 3. Server-global active selection+ if config.get("active_provider") in _CATALOG_BY_ID:+ return _with_default(config["active_provider"], config.get("active_model"))++ # 4. Environment+ env_provider = os.environ.get("REPOWISE_PROVIDER")+ if env_provider in _CATALOG_BY_ID:+ return _with_default(env_provider, os.environ.get("REPOWISE_MODEL"))++ # 5. Auto-detect+ for p in PROVIDER_CATALOG:+ if _get_key_for_provider(p["id"], repo_env) or not p["requires_key"]:+ return _with_default(p["id"], None)++ return None, None+++def list_provider_status(+ repo_id: str | None = None,+ repo_path: str | Path | None = None,+) -> dict[str, Any]:+ """Return provider catalog + the active selection for ``repo_id``.++ When ``repo_path`` is given the active provider/model reflect that repo's+ own configuration (so the UI's model picker shows what chat will actually+ use), and a custom configured model not present in the static catalog is+ surfaced in that provider's ``models`` list so it's selectable.+ """+ repo_cfg, repo_env = _load_repo_context(repo_path)+ active_id, active_model = _resolve_active_for_repo(repo_id, repo_cfg, repo_env)providers = []for p in PROVIDER_CATALOG:- has_key = bool(_get_key_for_provider(p["id"]))+ has_key = bool(_get_key_for_provider(p["id"], repo_env))configured = has_key or not p["requires_key"]+ models = list(p["models"])+ # Surface a configured-but-not-cataloged model (e.g. a local LiteLLM+ # alias like ``gemma4``) so the picker can display the active choice.+ if p["id"] == active_id and active_model and active_model not in models:+ models.append(active_model)providers.append({"id": p["id"],"name": p["name"],- "models": p["models"],+ "models": models,"default_model": p["default_model"],"configured": configured,}@@ -206,20 +312,36 @@ def list_provider_status() -> dict[str, Any]:}-def get_active_provider() -> tuple[str | None, str | None]:- """Return (provider_id, model) for the currently active provider."""- status = list_provider_status()- active = status["active"]- return active["provider"], active["model"]+def get_active_provider(+ repo_id: str | None = None,+ repo_path: str | Path | None = None,+) -> tuple[str | None, str | None]:+ """Return (provider_id, model) for the active provider, optionally per-repo."""+ repo_cfg, repo_env = _load_repo_context(repo_path)+ return _resolve_active_for_repo(repo_id, repo_cfg, repo_env)++def set_active_provider(+ provider_id: str,+ model: str | None = None,+ repo_id: str | None = None,+) -> None:+ """Persist the active provider/model selection.-def set_active_provider(provider_id: str, model: str | None = None) -> None:- """Set the active provider and model. Persists to config file."""+ With ``repo_id`` the selection is scoped to that repo (under ``repos``),+ so it overrides only that repo's chat and never shadows other repos in a+ workspace. Without it, the legacy server-global selection is set.+ """if provider_id not in _CATALOG_BY_ID:raise ValueError(f"Unknown provider: {provider_id}")+ resolved_model = model or _CATALOG_BY_ID[provider_id]["default_model"]config = _load_config()- config["active_provider"] = provider_id- config["active_model"] = model or _CATALOG_BY_ID[provider_id]["default_model"]+ if repo_id:+ repos = config.setdefault("repos", {})+ repos[repo_id] = {"provider": provider_id, "model": resolved_model}+ else:+ config["active_provider"] = provider_id+ config["active_model"] = resolved_model_save_config(config)@@ -236,19 +358,45 @@ def set_api_key(provider_id: str, key: str | None) -> None:_save_config(config)-def get_chat_provider_instance():- """Create a provider instance for chat using the active config.+def get_chat_provider_instance(+ repo_path: str | Path | None = None,+ repo_id: str | None = None,+ provider_override: str | None = None,+ model_override: str | None = None,+):+ """Create a chat provider instance, resolved for a specific repo.++ Resolution draws on the target repo's ``.repowise/config.yaml`` and+ ``.repowise/.env`` (provider, model, API key, base_url) so chat uses the+ exact configuration set at ``repowise init`` — without the server having+ to load any repo's ``.env`` into its own process environment. An explicit+ ``provider_override``/``model_override`` (a per-request UI choice) wins.Returns a provider that implements both BaseProvider and ChatProvider."""from repowise.core.providers.llm.registry import get_provider- provider_id, model = get_active_provider()+ repo_cfg, repo_env = _load_repo_context(repo_path)++ if provider_override:+ if provider_override not in _CATALOG_BY_ID:+ raise ValueError(f"Unknown provider: {provider_override}")+ provider_id = provider_override+ model = model_override+ # Inherit the repo's configured model when overriding only the+ # provider and that provider matches what init configured.+ if not model and repo_cfg.get("provider") == provider_id:+ model = repo_cfg.get("model")+ if not model:+ model = _CATALOG_BY_ID[provider_id]["default_model"]+ else:+ provider_id, model = _resolve_active_for_repo(repo_id, repo_cfg, repo_env)+if not provider_id:raise ValueError("No active provider configured. Set an API key first.")- api_key = _get_key_for_provider(provider_id)- base_url = _get_base_url_for_provider(provider_id)+ api_key = _get_key_for_provider(provider_id, repo_env)+ base_url = _get_base_url_for_provider(provider_id, repo_env, repo_cfg)catalog = _CATALOG_BY_ID[provider_id]kwargs: dict[str, Any] = {"model": model or catalog["default_model"]}diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 2ea16f2b7..c6d29b3ab 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -6,9 +6,9 @@ import jsonimport loggingfrom typing import Any+from fastapi import APIRouter, Depends, HTTPException, Requestfrom starlette.responses import StreamingResponse-from fastapi import APIRouter, Depends, HTTPException, Requestfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.providers.llm.base import ChatProvider, ProviderError@@ -22,7 +22,7 @@ from repowise.server.deps import (resolve_request_session_factory,verify_api_key,)-from repowise.server.provider_config import get_chat_provider_instance, set_active_provider+from repowise.server.provider_config import get_chat_provider_instancefrom repowise.server.schemas import (ChatMessageResponse,ChatRequest,@@ -84,15 +84,22 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# Resolve reporepo_name, repo_path = await _get_repo_info(factory, repo_id)- # Resolve provider (optional per-request override)- if body.provider:- try:- set_active_provider(body.provider, body.model)- except ValueError as exc:- raise HTTPException(400, str(exc)) from exc-+ # Resolve provider. A per-request override (the UI model picker) applies to+ # THIS request only and is not persisted — an explicit selection is+ # persisted separately via PATCH /api/providers/active (scoped per-repo).+ # Absent an override, the provider/model/key/base_url are taken from the+ # repo's own ``.repowise/config.yaml`` + ``.env`` (what ``repowise init``+ # configured), so chat matches ``repowise update`` seamlessly.try:- provider = get_chat_provider_instance()+ provider = get_chat_provider_instance(+ repo_path=repo_path,+ repo_id=repo_id,+ provider_override=body.provider,+ model_override=body.model,+ )+ except ValueError as exc:+ # Unknown provider override, or no provider resolvable at all.+ raise HTTPException(400, str(exc)) from excexcept Exception as exc:raise HTTPException(422, f"No chat provider available: {exc}") from excdiff --git a/packages/server/src/repowise/server/routers/providers.py b/packages/server/src/repowise/server/routers/providers.pyindex 9bf4ad11d..bf2389559 100644--- a/packages/server/src/repowise/server/routers/providers.py+++ b/packages/server/src/repowise/server/routers/providers.py@@ -2,8 +2,11 @@from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPException-from repowise.server.deps import verify_api_key+from fastapi import APIRouter, Depends, HTTPException, Request++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.server.deps import resolve_request_session_factory, verify_api_keyfrom repowise.server.provider_config import (list_provider_status,set_active_provider,@@ -18,20 +21,46 @@ router = APIRouter()+async def _repo_path_for(request: Request, repo_id: str | None) -> str | None:+ """Best-effort lookup of a repo's on-disk path from its id.++ Lets the providers endpoint report the active provider/model that *this*+ repo's chat will actually use. Returns ``None`` (server-global resolution)+ when no ``repo_id`` is given or the repo can't be found.+ """+ if not repo_id:+ return None+ try:+ factory = resolve_request_session_factory(request)+ async with get_session(factory) as session:+ repo = await crud.get_repository(session, repo_id)+ return repo.local_path if repo else None+ except Exception:+ # Best-effort: fall back to server-global resolution rather than 500.+ return None++@router.get("")-async def get_providers():- """List all providers with their status and active selection."""- return list_provider_status()+async def get_providers(request: Request, repo_id: str | None = None):+ """List all providers with their status and active selection.++ Pass ``?repo_id=`` so the active selection reflects that repo's own+ ``.repowise/config.yaml`` (and any per-repo UI override) instead of the+ server-global default.+ """+ repo_path = await _repo_path_for(request, repo_id)+ return list_provider_status(repo_id=repo_id, repo_path=repo_path)@router.patch("/active")-async def set_active(body: SetActiveProviderRequest):- """Set the active provider and model."""+async def set_active(body: SetActiveProviderRequest, request: Request):+ """Set the active provider and model (per-repo when ``repo_id`` is given)."""try:- set_active_provider(body.provider, body.model)+ set_active_provider(body.provider, body.model, repo_id=body.repo_id)except ValueError as exc:raise HTTPException(400, str(exc)) from exc- return list_provider_status()+ repo_path = await _repo_path_for(request, body.repo_id)+ return list_provider_status(repo_id=body.repo_id, repo_path=repo_path)@router.post("/{provider_id}/key", status_code=204)diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.pyindex bb2fc6948..42cbedb5f 100644--- a/packages/server/src/repowise/server/schemas/ui_helpers.py+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py@@ -13,6 +13,9 @@ class WebhookResponse(BaseModel):class SetActiveProviderRequest(BaseModel):provider: strmodel: str | None = None+ # When set, the selection is scoped to this repo (so picking a model for+ # one repo never shadows another in a workspace). Omit for the global default.+ repo_id: str | None = Noneclass SetApiKeyRequest(BaseModel):diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsxindex 54421b50f..5d3b17ddf 100644--- a/packages/web/src/components/chat/chat-interface.tsx+++ b/packages/web/src/components/chat/chat-interface.tsx@@ -30,7 +30,7 @@ export function ChatInterface({ repoId, repoName }: ChatInterfaceProps) {error={error}onSend={(text) => sendMessage(text)}onCancel={reset}- modelSelectorSlot={<ModelSelector />}+ modelSelectorSlot={<ModelSelector repoId={repoId} />}historySlot={<ConversationHistoryrepoId={repoId}diff --git a/packages/web/src/components/chat/model-selector.tsx b/packages/web/src/components/chat/model-selector.tsxindex e38b1f5a6..47e66e66f 100644--- a/packages/web/src/components/chat/model-selector.tsx+++ b/packages/web/src/components/chat/model-selector.tsx@@ -3,7 +3,7 @@import { ModelSelector as ModelSelectorShell } from "@repowise-dev/ui/chat/model-selector";import { useProviders } from "@/lib/hooks/use-providers";-export function ModelSelector() {+export function ModelSelector({ repoId }: { repoId?: string }) {const {providers,activeProvider,@@ -11,7 +11,7 @@ export function ModelSelector() {isLoading,activate,saveKey,- } = useProviders();+ } = useProviders(repoId);return (<ModelSelectorShelldiff --git a/packages/web/src/lib/api/providers.ts b/packages/web/src/lib/api/providers.tsindex d1e8989bd..2bd3a6dee 100644--- a/packages/web/src/lib/api/providers.ts+++ b/packages/web/src/lib/api/providers.ts@@ -5,17 +5,22 @@import { apiGet, apiPatch, apiPost, apiDelete } from "./client";import type { ProvidersResponse } from "./types";-export async function getProviders(): Promise<ProvidersResponse> {- return apiGet<ProvidersResponse>("/api/providers");+export async function getProviders(+ repoId?: string,+): Promise<ProvidersResponse> {+ const qs = repoId ? `?repo_id=${encodeURIComponent(repoId)}` : "";+ return apiGet<ProvidersResponse>(`/api/providers${qs}`);}export async function setActiveProvider(provider: string,model?: string,+ repoId?: string,): Promise<ProvidersResponse> {return apiPatch<ProvidersResponse>("/api/providers/active", {provider,model: model ?? null,+ repo_id: repoId ?? null,});}diff --git a/packages/web/src/lib/hooks/use-providers.ts b/packages/web/src/lib/hooks/use-providers.tsindex d5d12c714..133320060 100644--- a/packages/web/src/lib/hooks/use-providers.ts+++ b/packages/web/src/lib/hooks/use-providers.ts@@ -9,10 +9,10 @@ import {} from "@/lib/api/providers";import type { ProvidersResponse } from "@/lib/api/types";-export function useProviders() {+export function useProviders(repoId?: string) {const { data, mutate, isLoading } = useSWR<ProvidersResponse>(- "/api/providers",- getProviders,+ repoId ? ["/api/providers", repoId] : "/api/providers",+ () => getProviders(repoId),{ revalidateOnFocus: false },);@@ -20,7 +20,7 @@ export function useProviders() {const activeModel = data?.active.model ?? null;async function activate(providerId: string, model?: string) {- await setActiveProvider(providerId, model);+ await setActiveProvider(providerId, model, repoId);await mutate();}diff --git a/tests/unit/server/test_provider_config.py b/tests/unit/server/test_provider_config.pynew file mode 100644index 000000000..70d5abb81--- /dev/null+++ b/tests/unit/server/test_provider_config.py@@ -0,0 +1,191 @@+"""Per-repo chat provider resolution (issue #426).++The web-UI chat must use the provider/model/API-key/base-url that+``repowise init`` wrote to each repo's ``.repowise/config.yaml`` ++``.repowise/.env`` — the same configuration ``repowise update`` already+honours — instead of falling back to a hardcoded catalog default. Selecting a+model for one repo must not shadow another repo in a workspace.+"""++from __future__ import annotations++import textwrap+from pathlib import Path++import pytest++from repowise.server import provider_config as pc+++def clean_env(monkeypatch, tmp_path):+ """Replace ``os.environ`` with a minimal dict and isolate the config file.++ The dev machine often has real ``*_API_KEY`` vars exported, which would+ otherwise leak into auto-detection and make these assertions flaky.+ """+ env: dict[str, str] = {"REPOWISE_CONFIG_DIR": str(tmp_path / "server")}+ monkeypatch.setattr(pc.os, "environ", env)+ return env+++def _make_repo(root: Path, *, config: str = "", env: str = "") -> Path:+ """Create a repo dir with ``.repowise/config.yaml`` and ``.repowise/.env``."""+ rw = root / ".repowise"+ rw.mkdir(parents=True, exist_ok=True)+ if config:+ (rw / "config.yaml").write_text(textwrap.dedent(config), encoding="utf-8")+ if env:+ (rw / ".env").write_text(textwrap.dedent(env), encoding="utf-8")+ return root+++# ---------------------------------------------------------------------------+# The reported bug: repo config.yaml model is ignored, default is used.+# ---------------------------------------------------------------------------+++def test_repo_config_model_used_without_ui_selection(clean_env, tmp_path):+ repo = _make_repo(+ tmp_path / "repo",+ config="""+ provider: openai+ model: gemma4+ embedder: openai+ """,+ env="OPENAI_API_KEY=admin\nOPENAI_BASE_URL=http://localhost:4000/v1\n",+ )++ provider, model = pc.get_active_provider(repo_id="r1", repo_path=str(repo))+ assert provider == "openai"+ assert model == "gemma4" # not the catalog default gpt-5.4-nano+++def test_get_chat_provider_passes_repo_key_model_and_base_url(clean_env, tmp_path, monkeypatch):+ repo = _make_repo(+ tmp_path / "repo",+ config="""+ provider: openai+ model: gemma4+ embedder: openai+ """,+ env="OPENAI_API_KEY=admin\nOPENAI_BASE_URL=http://localhost:4000/v1\n",+ )++ captured: dict = {}++ def fake_get_provider(provider_id, **kwargs):+ captured["provider_id"] = provider_id+ captured.update(kwargs)+ return object()++ monkeypatch.setattr("repowise.core.providers.llm.registry.get_provider", fake_get_provider)++ pc.get_chat_provider_instance(repo_path=str(repo), repo_id="r1")++ assert captured["provider_id"] == "openai"+ assert captured["model"] == "gemma4"+ assert captured["api_key"] == "admin" # from .repowise/.env+ assert captured["base_url"] == "http://localhost:4000/v1"+++# ---------------------------------------------------------------------------+# Precedence + no cross-repo shadowing.+# ---------------------------------------------------------------------------+++def test_per_repo_selection_does_not_shadow_other_repo(clean_env, tmp_path):+ repo_a = _make_repo(+ tmp_path / "a",+ config="provider: openai\nmodel: gemma4\nembedder: openai\n",+ env="OPENAI_API_KEY=admin\n",+ )+ repo_b = _make_repo(+ tmp_path / "b",+ config="provider: openai\nmodel: codellama\nembedder: openai\n",+ env="OPENAI_API_KEY=admin\n",+ )++ # User picks a different model for repo A via the UI.+ pc.set_active_provider("openai", "gpt-5.4", repo_id="ra")++ a_provider, a_model = pc.get_active_provider(repo_id="ra", repo_path=str(repo_a))+ b_provider, b_model = pc.get_active_provider(repo_id="rb", repo_path=str(repo_b))++ assert (a_provider, a_model) == ("openai", "gpt-5.4") # A's override+ assert (b_provider, b_model) == ("openai", "codellama") # B untouched+++def test_request_override_beats_repo_config(clean_env, tmp_path, monkeypatch):+ repo = _make_repo(+ tmp_path / "repo",+ config="provider: openai\nmodel: gemma4\nembedder: openai\n",+ env="OPENAI_API_KEY=admin\nANTHROPIC_API_KEY=sk-ant\n",+ )++ captured: dict = {}+ monkeypatch.setattr(+ "repowise.core.providers.llm.registry.get_provider",+ lambda provider_id, **kw: captured.update({"id": provider_id, **kw}) or object(),+ )++ pc.get_chat_provider_instance(+ repo_path=str(repo),+ repo_id="r1",+ provider_override="anthropic",+ model_override="claude-opus-4-6",+ )++ assert captured["id"] == "anthropic"+ assert captured["model"] == "claude-opus-4-6"+++# ---------------------------------------------------------------------------+# Status surfaces the configured (possibly custom) model for the picker.+# ---------------------------------------------------------------------------+++def test_list_provider_status_surfaces_custom_model(clean_env, tmp_path):+ repo = _make_repo(+ tmp_path / "repo",+ config="provider: openai\nmodel: gemma4\nembedder: openai\n",+ env="OPENAI_API_KEY=admin\n",+ )++ status = pc.list_provider_status(repo_id="r1", repo_path=str(repo))++ assert status["active"] == {"provider": "openai", "model": "gemma4"}+ openai = next(p for p in status["providers"] if p["id"] == "openai")+ assert "gemma4" in openai["models"] # custom model is selectable+ assert openai["configured"] is True # key seen via repo .env+++def test_repo_env_key_enables_autodetect(clean_env, tmp_path):+ # No provider in config — only a key in the repo .env. Auto-detect should+ # still find it (without the server holding the key in its own environ).+ repo = _make_repo(+ tmp_path / "repo",+ config="embedder: openai\n",+ env="OPENAI_API_KEY=admin\n",+ )++ provider, _ = pc.get_active_provider(repo_id="r1", repo_path=str(repo))+ assert provider == "openai"+++def test_unknown_provider_override_raises(clean_env, tmp_path):+ repo = _make_repo(+ tmp_path / "repo",+ config="provider: openai\nmodel: gemma4\nembedder: openai\n",+ env="OPENAI_API_KEY=admin\n",+ )+ with pytest.raises(ValueError, match="Unknown provider"):+ pc.get_chat_provider_instance(repo_path=str(repo), repo_id="r1", provider_override="bogus")+++def test_global_selection_used_when_repo_has_no_config(clean_env, tmp_path):+ repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")+ pc.set_active_provider("anthropic", "claude-sonnet-4-6") # global default++ provider, model = pc.get_active_provider(repo_id="r1", repo_path=str(repo))+ assert (provider, model) == ("anthropic", "claude-sonnet-4-6")