Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(refactoring): one model switch for helper naming and code drafts (#3329)

Raghav Chamadiya342046ff05d0
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 401bac750..660309137 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -437,7 +437,7 @@ get_execution_flows(entry_point="src/cli/main.py::main", max_depth=4)
Turns one refactoring plan from `get_health(include=["refactoring"])` into generated code and a unified diff, grounded on the plan and the source spans it names. Extract Class results include an LCOM4 before-and-after check. It calls the repo's configured LLM provider, and caches by content hash so an unchanged plan never regenerates.
-Adding the tool to the surface is the opt-in step. Generation then runs unless `.repowise/config.yaml` sets `refactoring.llm.enabled: false`, in which case the plan is returned with `generation.available: false` and `reason: "disabled"`. With no provider configured it returns `error: "no_provider"`.
+Adding the tool to the surface is the opt-in step. Generation then runs only when `.repowise/config.yaml` sets `refactoring.llm.enabled: true` (off by default); otherwise the plan is returned with `generation.available: false` and `reason: "disabled"`. With no provider configured it returns `error: "no_provider"`.
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
diff --git a/docs/architecture/refactoring.md b/docs/architecture/refactoring.md
index cdeac2653..757b23532 100644
--- a/docs/architecture/refactoring.md
+++ b/docs/architecture/refactoring.md
@@ -89,7 +89,7 @@ PUT /api/repos/{repo_id}/refactoring/settings
`llm/enrich.py` gathers source spans, builds the prompt, calls the provider, runs the
per-type self-check and caches results under the repo's `.repowise` directory by a
hash of plan, source and model. `llm_enrichment_enabled` treats an unset
-`refactoring.llm.enabled` as on. `build_enrichment_provider` resolves the top-level
-`provider`/`model` from config, or the first provider with a key in the environment
-or `.repowise/.env`. The MCP tool (`tool_refactoring.py`) is registered
-`default=False`.
+`refactoring.llm.enabled` as off. The REST endpoint and MCP tool resolve the
+provider with `get_chat_provider_instance` (`server/provider_config.py`), the
+resolver chat uses; the CLI uses `resolve_provider`, as page generation does. The
+MCP tool (`tool_refactoring.py`) is registered `default=False`.
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index be7c27e10..07765791c 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -136,10 +136,12 @@ after production files.
## Code generation
-Code generation is **on by default** but only runs when you ask for it, and it
-needs an LLM API key. It never runs during indexing. Set
-`refactoring.llm.enabled: false` to turn it off for the dashboard and MCP. The CLI
-flag is itself an explicit request and does not read that setting.
+Code generation is **off by default**, only runs when you ask for it, and never
+runs during indexing. Turn it on with the code-generation switch on the repo
+Settings page or in an open plan, or with `refactoring.llm.enabled: true`. The
+switch names the provider and model it will use, so there is nothing else to
+configure. The CLI flag is itself an explicit request and does not read that
+setting.
You can ask from three places:
@@ -158,10 +160,10 @@ remaining function's complexity dropped. Results are cached by a hash of plan,
source and model, so an unchanged plan is not paid for twice. Nothing is applied
to your files.
-It uses the repository's configured `provider` and `model`, or the first provider
-whose API key is set. With generation disabled, the MCP tool returns the plan with
-`generation.available: false` and the REST endpoint returns `403`. With no key, MCP
-returns `error: "no_provider"`.
+The CLI uses the provider configured for page generation; the web and MCP use the
+chat model. With generation disabled, the MCP tool returns the plan with
+`generation.available: false` and the REST endpoint returns `403`. With no key,
+MCP returns `error: "no_provider"`.
## Configuration
@@ -174,7 +176,7 @@ refactoring:
disabled: [] # e.g. [move_method, split_file]
min_confidence: medium # low | medium | high; unset keeps every plan
llm:
- enabled: true # code generation; set false to disable
+ enabled: false # code generation; set true to enable
```
Detector names are the snake-case plan types: `extract_class`, `extract_method`,
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index e516e7288..bf166d208 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -453,8 +453,8 @@ deployment with no local checkout:
recorded are servable, and `.git`/`.repowise` paths are refused),
`POST /api/repos/{id}/preflight`,
`POST /api/repos/{id}/refactoring/{suggestion_id}/generate-code`
- (`404` without an accessible checkout, `403` when `refactoring.llm.enabled`
- is false)
+ (`404` without an accessible checkout, `403` unless `refactoring.llm.enabled`
+ is true)
- validate the path at registration: `POST /api/repos` rejects a `local_path`
that is not an existing git directory with a `422` body
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 934e87f33..317c2ac80 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -597,15 +597,13 @@ refactoring:
disabled: [] # e.g. [move_method] to silence one detector
min_confidence: null # low | medium | high (confidence floor; null = no floor)
llm:
- enabled: true # code generation, on by default; set false to disable
- provider: null # falls back to the repo's configured LLM provider
- model: null # falls back to the repo's configured model
+ enabled: false # code generation, off by default; uses chat's provider and model
```
- The deterministic layer is **zero-LLM** and runs in the `init` / `update`
- health pass. Code generation is the only part that calls a provider: it is on
- by default but never runs during indexing, only on an explicit request (set
- `llm.enabled: false` to disable it).
+ health pass. Code generation is the only part that calls a provider: it is off
+ by default and never runs during indexing, only on an explicit request (set
+ `llm.enabled: true` to enable it).
- `enabled: false` skips the whole deterministic detector pass; `detectors.disabled`
silences named detectors (`extract_class`, `split_file`, ...) while the rest run.
- `min_confidence` is a floor applied when the plans are detected, so a plan below it
diff --git a/packages/api-client/src/refactoring.ts b/packages/api-client/src/refactoring.ts
index 9db163d43..79a6851aa 100644
--- a/packages/api-client/src/refactoring.ts
+++ b/packages/api-client/src/refactoring.ts
@@ -27,6 +27,7 @@ export type {
RefactoringTriageStatus,
};
+/** The code-generation switch and the provider/model chat resolves (read-only). */
export interface RefactoringSettings {
enabled: boolean;
provider: string | null;
@@ -111,11 +112,12 @@ export async function getRefactoringSettings(repoId: string): Promise<Refactorin
return apiGet<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`);
}
+/** Write `refactoring.llm.enabled`, the only writable setting. */
export async function updateRefactoringSettings(
repoId: string,
- settings: RefactoringSettings,
+ enabled: boolean,
): Promise<RefactoringSettings> {
- return apiPut<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`, settings);
+ return apiPut<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`, { enabled });
}
// ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py
index 1d7cdbd8a..6b5756e11 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py
@@ -14,7 +14,6 @@ from __future__ import annotations
from .enrich import (
EnrichmentResult,
SourceSpan,
- build_enrichment_provider,
enrich_suggestion,
llm_enrichment_enabled,
)
@@ -22,7 +21,6 @@ from .enrich import (
__all__ = [
"EnrichmentResult",
"SourceSpan",
- "build_enrichment_provider",
"enrich_suggestion",
"llm_enrichment_enabled",
]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index 882cded95..57c1762f0 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -110,76 +110,22 @@ class EnrichmentResult:
# ---------------------------------------------------------------------------
-# Config gate + provider resolution (server / MCP surfaces)
+# Config gate (server / MCP surfaces). The provider itself is resolved by the
+# caller through the same path chat and page generation use.
# ---------------------------------------------------------------------------
def llm_enrichment_enabled(config: dict[str, Any]) -> bool:
"""Whether code generation is enabled for this repo (``refactoring.llm.enabled``).
- Enabled unless the repo explicitly turns it off — an unset key means on.
- Code generation never runs during indexing and only ever fires on an
- explicit request (a button click / CLI flag / MCP call), and the web + MCP
- surfaces both require a local checkout (they 404 without one), so defaulting
- on simply makes the local-``serve`` experience work without a config trip;
- a repo can still set ``refactoring.llm.enabled: false`` to disable it.
+ Off unless the repo turns it on: generation sends source to a model, so it
+ waits for an explicit yes in config or from the settings toggle.
"""
refactoring = config.get("refactoring")
- if not isinstance(refactoring, dict):
- return True
- llm = refactoring.get("llm")
+ llm = refactoring.get("llm") if isinstance(refactoring, dict) else None
if not isinstance(llm, dict):
- return True
- return bool(llm.get("enabled", True))
-
-
-def build_enrichment_provider(
- repo_path: Path,
- *,
- provider_name: str | None = None,
- model: str | None = None,
-) -> BaseProvider:
- """Resolve a provider for server/MCP enrichment from repo config + env.
-
- Mirrors the CLI resolver in spirit (config provider/model, key from env)
- but lives in core so the server and MCP layers don't depend on the CLI.
- Reads ``.repowise/config.yaml`` for provider/model and the per-repo
- ``.repowise/.env`` (without mutating ``os.environ``) plus the process env
- for the API key. Raises ``ValueError`` when no provider/key can be found.
- """
- import os
-
- from repowise.core.providers import get_provider
- from repowise.core.providers.llm.registry import (
- PROVIDER_AUTODETECT_ORDER,
- provider_credentials_present,
- provider_kwargs,
- )
- from repowise.core.repo_config import load_repo_config, load_repo_env
-
- cfg = load_repo_config(repo_path)
- repo_env = load_repo_env(repo_path)
-
- def _env(name: str) -> str | None:
- return os.environ.get(name) or repo_env.get(name)
-
- name = provider_name or cfg.get("provider")
- chosen_model = model or cfg.get("model")
-
- # Auto-detect from whichever key is present when the config names none.
- if name is None:
- name = next(
- (c for c in PROVIDER_AUTODETECT_ORDER if provider_credentials_present(c, _env)),
- None,
- )
- if name is None:
- raise ValueError(
- "No LLM provider configured for refactoring enrichment. Set "
- "'provider' in .repowise/config.yaml or an API key env var."
- )
-
- kwargs = provider_kwargs(name, model=chosen_model, repo_path=repo_path, getenv=_env)
- return get_provider(name, **kwargs)
+ return False
+ return bool(llm.get("enabled", False))
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
index fbeb830e8..99751af93 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
@@ -41,22 +41,21 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)
source spans it references. For Extract Class the result carries an LCOM4
before/after self-check.
- On unless the repo sets ``refactoring.llm.enabled: false`` in
- ``.repowise/config.yaml``, which returns the plan with generation marked
- unavailable. Uses the repo's configured
- provider/model (BYO key) and caches by a content hash, so an unchanged plan
- never regenerates.
+ Off unless the repo sets ``refactoring.llm.enabled: true`` in
+ ``.repowise/config.yaml``; while off it returns the plan with generation
+ marked unavailable. Uses the provider/model chat uses (BYO key) and caches
+ by a content hash, so an unchanged plan never regenerates.
Args:
suggestion_id: The ``id`` of a plan from ``get_health(... "refactoring")``.
repo: Repo alias / id / path.
"""
from repowise.core.analysis.health.refactoring.llm import (
- build_enrichment_provider,
enrich_suggestion,
llm_enrichment_enabled,
)
from repowise.core.repo_config import load_repo_config
+ from repowise.server.provider_config import get_chat_provider_instance
if repo == "all":
return _unsupported_repo_all("generate_refactoring_code")
@@ -114,7 +113,7 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)
}
try:
- provider = build_enrichment_provider(repo_path)
+ provider = get_chat_provider_instance(repo_path=repo_path, repo_id=repository.id)
except ValueError as exc:
return {"error": "no_provider", "detail": str(exc), "_meta": meta}
diff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.py
index 462e3b406..35eeb7dbe 100644
--- a/packages/server/src/repowise/server/provider_config.py
+++ b/packages/server/src/repowise/server/provider_config.py
@@ -237,6 +237,14 @@ def _get_base_url_for_provider(
return None
+def _provider_configured(provider_id: str, repo_env: dict[str, str] | None = None) -> bool:
+ """Whether chat can build ``provider_id``: it needs no key or has one."""
+ catalog = _CATALOG_BY_ID.get(provider_id)
+ if catalog is None:
+ return False
+ return not catalog["requires_key"] or bool(_get_key_for_provider(provider_id, repo_env))
+
+
def _resolve_active_for_repo(
repo_id: str | None,
repo_cfg: dict[str, Any],
@@ -285,7 +293,7 @@ def _resolve_active_for_repo(
# 5. Auto-detect
for p in PROVIDER_CATALOG:
- if _get_key_for_provider(p["id"], repo_env) or not p["requires_key"]:
+ if _provider_configured(p["id"], repo_env):
return _with_default(p["id"], None)
return None, None
@@ -307,8 +315,7 @@ def list_provider_status(
providers = []
for p in PROVIDER_CATALOG:
- has_key = bool(_get_key_for_provider(p["id"], repo_env))
- configured = has_key or not p["requires_key"]
+ configured = _provider_configured(p["id"], repo_env)
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.
@@ -363,6 +370,19 @@ def get_active_provider(
return _resolve_active_for_repo(repo_id, repo_cfg, repo_env)
+def get_configured_active_provider(
+ repo_id: str | None = None,
+ repo_path: str | Path | None = None,
+) -> tuple[str | None, str | None]:
+ """Like :func:`get_active_provider`, but ``(None, None)`` when the resolved
+ provider still needs a key, so a caller can show setup instead of a 400."""
+ repo_cfg, repo_env = _load_repo_context(repo_path)
+ provider_id, model = _resolve_active_for_repo(repo_id, repo_cfg, repo_env)
+ if provider_id is None or not _provider_configured(provider_id, repo_env):
+ return None, None
+ return provider_id, model
+
+
def set_active_provider(
provider_id: str,
model: str | None = None,
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 7bec70c37..e6e0f1cad 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -223,29 +223,33 @@ async def get_refactoring_plan_page(
class RefactoringSettings(BaseModel):
- """The opt-in code-generation switches, mirrored from ``refactoring.llm``."""
+ """The code-generation switch plus the model it will use.
+
+ ``provider`` / ``model`` are read-only: they come from the same resolver
+ chat uses, so the user configures a model once. Never carries a key.
+ """
enabled: bool = False
provider: str | None = None
model: str | None = None
-def _read_refactoring_settings(config: dict[str, Any]) -> RefactoringSettings:
- """Project ``refactoring.llm`` out of a loaded config, tolerant of shape.
+class RefactoringSettingsUpdate(BaseModel):
+ """The one writable field, ``refactoring.llm.enabled``."""
- ``enabled`` defaults to ``True`` when unset, matching
- :func:`llm_enrichment_enabled` — an untouched repo shows the toggle on.
- """
- refactoring = config.get("refactoring")
- llm = refactoring.get("llm") if isinstance(refactoring, dict) else None
- if not isinstance(llm, dict):
- return RefactoringSettings(enabled=True)
- provider = llm.get("provider")
- model = llm.get("model")
+ enabled: bool
+
+
+def _read_refactoring_settings(
+ config: dict[str, Any], repo_id: str, repo_path: Path
+) -> RefactoringSettings:
+ """The switch from ``config`` plus the model chat would build, or none."""
+ from repowise.core.analysis.health.refactoring.llm import llm_enrichment_enabled
+ from repowise.server.provider_config import get_configured_active_provider
+
+ provider, model = get_configured_active_provider(repo_id=repo_id, repo_path=repo_path)
return RefactoringSettings(
- enabled=bool(llm.get("enabled", True)),
- provider=provider if isinstance(provider, str) and provider else None,
- model=model if isinstance(model, str) and model else None,
+ enabled=llm_enrichment_enabled(config), provider=provider, model=model
)
@@ -451,24 +455,22 @@ async def get_refactoring_settings(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
) -> RefactoringSettings:
- """Current ``refactoring.llm`` settings for the repo (enabled + provider/model)."""
+ """Whether code generation is on for the repo, and the provider/model it uses."""
from repowise.core.repo_config import load_repo_config
repo_path = await _local_repo_path(session, repo_id)
- return _read_refactoring_settings(load_repo_config(repo_path))
+ return _read_refactoring_settings(load_repo_config(repo_path), repo_id, repo_path)
@router.put("/{repo_id}/refactoring/settings", response_model=RefactoringSettings)
async def update_refactoring_settings(
repo_id: str,
- body: RefactoringSettings,
+ body: RefactoringSettingsUpdate,
session: AsyncSession = Depends(get_db_session),
) -> RefactoringSettings:
- """Persist the ``refactoring.llm`` block to the repo's ``.repowise/config.yaml``.
+ """Write ``refactoring.llm.enabled`` to the repo's ``.repowise/config.yaml``.
- Round-trips through the loaded config so unrelated keys are preserved, then
- writes only the ``refactoring.llm.{enabled,provider,model}`` sub-tree. A
- blank provider/model clears that key rather than writing an empty string.
+ Round-trips through the loaded config so unrelated keys are preserved.
"""
from repowise.core.repo_config import load_repo_config, save_repo_config
@@ -483,21 +485,10 @@ async def update_refactoring_settings(
if not isinstance(llm, dict):
llm = {}
refactoring["llm"] = llm
-
- llm["enabled"] = bool(body.enabled)
- provider = (body.provider or "").strip()
- model = (body.model or "").strip()
- if provider:
- llm["provider"] = provider
- else:
- llm.pop("provider", None)
- if model:
- llm["model"] = model
- else:
- llm.pop("model", None)
+ llm["enabled"] = body.enabled
save_repo_config(repo_path, config)
- return _read_refactoring_settings(config)
+ return _read_refactoring_settings(config, repo_id, repo_path)
@router.get("/{repo_id}/refactoring/{suggestion_id}", response_model=RefactoringPlanResponse)
@@ -558,7 +549,7 @@ async def update_refactoring_plan_status(
class GenerateCodeRequest(BaseModel):
- """Optional per-call overrides for the enrichment provider/model."""
+ """Optional per-call provider/model overrides, as chat accepts."""
provider: str | None = None
model: str | None = None
@@ -594,17 +585,18 @@ async def generate_refactoring_code(
) -> GenerateCodeResponse:
"""Generate the refactored code + a unified diff for one plan, on demand.
- Strictly opt-in: returns 403 unless ``refactoring.llm.enabled`` is set in the
- repo's ``.repowise/config.yaml``. Needs the working tree on disk (it reads
- the plan's real source spans), so this is a local-``serve`` capability, not a
- hosted one — it returns 404 when the repo has no accessible checkout.
+ Opt-in: returns 403 unless ``refactoring.llm.enabled`` is true in the repo's
+ ``.repowise/config.yaml``. The provider resolves exactly as chat's does.
+ Needs the working tree on disk (it reads the plan's real source spans), so
+ this is a local-``serve`` capability, not a hosted one — it returns 404 when
+ the repo has no accessible checkout.
"""
from repowise.core.analysis.health.refactoring.llm import (
- build_enrichment_provider,
enrich_suggestion,
llm_enrichment_enabled,
)
from repowise.core.repo_config import load_repo_config
+ from repowise.server.provider_config import get_chat_provider_instance
repo = await crud.get_repository(session, repo_id)
if repo is None or not repo.local_path:
@@ -630,8 +622,11 @@ async def generate_refactoring_code(
body = body or GenerateCodeRequest()
try:
- provider = build_enrichment_provider(
- repo_path, provider_name=body.provider, model=body.model
+ 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:
raise HTTPException(status_code=400, detail=str(exc)) from exc
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 864433d97..18c543533 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1677,7 +1677,7 @@ export interface FixVerify {
basis: "measured" | "inferred" | "unknown";
}
-/** Optional per-call overrides for the enrichment provider/model. */
+/** Optional per-call provider/model overrides, as chat accepts. */
export interface GenerateCodeRequest {
provider?: string | null;
model?: string | null;
@@ -2789,13 +2789,23 @@ export interface RefactoringRollupResponse {
directive?: Record<string, unknown>;
}
-/** The opt-in code-generation switches, mirrored from ``refactoring.llm``. */
+/**
+ * The code-generation switch plus the model it will use.
+ *
+ * ``provider`` / ``model`` are read-only: they come from the same resolver
+ * chat uses, so the user configures a model once. Never carries a key.
+ */
export interface RefactoringSettings {
enabled?: boolean;
provider?: string | null;
model?: string | null;
}
+/** The one writable field, ``refactoring.llm.enabled``. */
+export interface RefactoringSettingsUpdate {
+ enabled: boolean;
+}
+
/** Same shape and vocabulary as health finding triage — one triage system. */
export interface RefactoringStatusUpdate {
/** open | acknowledged | resolved | false_positive */
diff --git a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx
index 7e0fee4db..7d7ff475f 100644
--- a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx
+++ b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx
@@ -270,3 +270,53 @@ describe("RefactoringDrawer validation", () => {
expect(toggle.textContent).not.toContain("guarding");
});
});
+
+describe("RefactoringDrawer code generation", () => {
+ const modelSetting = {
+ value: { enabled: false, provider: "anthropic", model: "claude-test" },
+ onToggle: async () => {},
+ };
+
+ it("offers the model switch while generation is off", () => {
+ render(
+ <RefactoringDrawer plan={PLAN} open onOpenChange={() => {}} modelSetting={modelSetting} />,
+ );
+ expect(screen.getByRole("switch", { name: /name helpers and draft code/ })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Generate code" })).toBeNull();
+ });
+
+ it("shows the action, not the switch, once generation is on", () => {
+ render(
+ <RefactoringDrawer
+ plan={PLAN}
+ open
+ onOpenChange={() => {}}
+ modelSetting={modelSetting}
+ onGenerateCode={async () => {
+ throw new Error("not called");
+ }}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "Generate code" })).toBeTruthy();
+ expect(screen.queryByRole("switch")).toBeNull();
+ });
+});
+
+describe("RefactoringDrawer with no model configured", () => {
+ it("shows the setup hint, not a generate action", () => {
+ render(
+ <RefactoringDrawer
+ plan={PLAN}
+ open
+ onOpenChange={() => {}}
+ modelSetting={{
+ value: { enabled: true, provider: null, model: null },
+ onToggle: async () => {},
+ setupHref: "/repos/r1/settings#provider",
+ }}
+ />,
+ );
+ expect(screen.getByRole("link", { name: "Set one up" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Generate code" })).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsx b/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsx
new file mode 100644
index 000000000..39709f776
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/refactoring-model-toggle.test.tsx
@@ -0,0 +1,57 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+import { RefactoringModelToggle } from "../../src/refactoring/refactoring-settings-card";
+
+const LABEL = "Use your configured model to name helpers and draft code";
+
+describe("RefactoringModelToggle", () => {
+ it("names the provider and model chat resolves", () => {
+ render(
+ <RefactoringModelToggle
+ value={{ enabled: false, provider: "anthropic", model: "claude-test" }}
+ onToggle={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("switch", { name: LABEL })).toHaveAttribute("aria-checked", "false");
+ expect(screen.getByText("anthropic")).toBeInTheDocument();
+ expect(screen.getByText("claude-test")).toBeInTheDocument();
+ expect(screen.queryByText("No model configured.", { exact: false })).toBeNull();
+ });
+
+ it("links to setup when no model is configured", () => {
+ render(
+ <RefactoringModelToggle
+ value={{ enabled: false, provider: null, model: null }}
+ onToggle={vi.fn()}
+ setupHref="/repos/r1/settings#provider"
+ />,
+ );
+ expect(screen.getByText("No model configured.", { exact: false })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Set one up" })).toHaveAttribute(
+ "href",
+ "/repos/r1/settings#provider",
+ );
+ });
+
+ it("writes the switch and rolls back when the write fails", async () => {
+ const onToggle = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("x"));
+ render(
+ <RefactoringModelToggle
+ value={{ enabled: false, provider: "anthropic", model: null }}
+ onToggle={onToggle}
+ />,
+ );
+ const toggle = screen.getByRole("switch", { name: LABEL });
+
+ fireEvent.click(toggle);
+ expect(onToggle).toHaveBeenLastCalledWith(true);
+ await waitFor(() => expect(toggle).toHaveAttribute("aria-checked", "true"));
+ await waitFor(() => expect(toggle).not.toBeDisabled());
+
+ fireEvent.click(toggle);
+ expect(onToggle).toHaveBeenLastCalledWith(false);
+ await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument());
+ expect(toggle).toHaveAttribute("aria-checked", "true");
+ });
+});
diff --git a/packages/ui/src/refactoring/refactoring-drawer.tsx b/packages/ui/src/refactoring/refactoring-drawer.tsx
index 0342b1db8..726f1b7f6 100644
--- a/packages/ui/src/refactoring/refactoring-drawer.tsx
+++ b/packages/ui/src/refactoring/refactoring-drawer.tsx
@@ -28,6 +28,7 @@ import { Skeleton, SkeletonRegion } from "../ui/skeleton";
import { formatNumber } from "../lib/format";
import { PlanComparison } from "./plan-comparison";
import { GenerateCodePanel } from "./generate-code-panel";
+import { RefactoringModelToggle, type RefactoringModelToggleProps } from "./refactoring-settings-card";
import { PriorityExplanation } from "./priority-explanation";
import { ValidationSummary } from "./validation-summary";
import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
@@ -51,6 +52,8 @@ export interface RefactoringDrawerProps {
/** Opt-in LLM code generation. Omit to hide the section entirely. */
onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
settingsHref?: string | undefined;
+ /** The code-generation switch, offered in place of the action while it is off. */
+ modelSetting?: RefactoringModelToggleProps | undefined;
fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
}
@@ -64,6 +67,7 @@ export function RefactoringDrawer({
onAiPrompt,
onGenerateCode,
settingsHref,
+ modelSetting,
fileHref,
}: RefactoringDrawerProps) {
return (
@@ -82,6 +86,7 @@ export function RefactoringDrawer({
onAiPrompt={onAiPrompt}
onGenerateCode={onGenerateCode}
settingsHref={settingsHref}
+ modelSetting={modelSetting}
fileHref={fileHref}
contextSlot={contextSlot}
/>
@@ -115,6 +120,7 @@ function DrawerBody({
onAiPrompt,
onGenerateCode,
settingsHref,
+ modelSetting,
fileHref,
contextSlot,
}: {
@@ -122,6 +128,7 @@ function DrawerBody({
onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
settingsHref?: string | undefined;
+ modelSetting?: RefactoringModelToggleProps | undefined;
fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
contextSlot?: ReactNode;
}) {
@@ -198,6 +205,10 @@ function DrawerBody({
</div>
<GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />
</section>
+ ) : modelSetting ? (
+ <section className="border-t border-[var(--color-border-default)] pt-4">
+ <RefactoringModelToggle {...modelSetting} />
+ </section>
) : null}
{wins.length > 0 ? (
diff --git a/packages/ui/src/refactoring/refactoring-settings-card.tsx b/packages/ui/src/refactoring/refactoring-settings-card.tsx
index 671dd8eb4..68cfbe61f 100644
--- a/packages/ui/src/refactoring/refactoring-settings-card.tsx
+++ b/packages/ui/src/refactoring/refactoring-settings-card.tsx
@@ -1,87 +1,128 @@
"use client";
import * as React from "react";
-import { Check, TriangleAlert, Wand2 } from "lucide-react";
+import { TriangleAlert } from "lucide-react";
import { Spinner } from "../ui/spinner";
import { Switch } from "../ui/switch";
-import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { toFriendlyMessage } from "../lib/errors";
export interface RefactoringSettingsValue {
enabled: boolean;
+ /** The provider chat resolves for this repo; null when none is configured. */
provider: string | null;
model: string | null;
}
+export interface RefactoringModelToggleProps {
+ value: RefactoringSettingsValue;
+ /** Persist `refactoring.llm.enabled`. Host owns the API call. */
+ onToggle: (enabled: boolean) => Promise<void>;
+ /** Where the user configures a model, shown when none is configured. */
+ setupHref?: string | undefined;
+}
+
+/**
+ * The one code-generation switch. It reuses the model chat uses, so the line
+ * under it names that model rather than offering a second picker. Autosaves,
+ * and rolls back if the write fails.
+ */
+export function RefactoringModelToggle({ value, onToggle, setupHref }: RefactoringModelToggleProps) {
+ const id = React.useId();
+ const [enabled, setEnabled] = React.useState(value.enabled);
+ const [saving, setSaving] = React.useState(false);
+ const [error, setError] = React.useState<string | null>(null);
+
+ React.useEffect(() => setEnabled(value.enabled), [value.enabled]);
+
+ const change = async (next: boolean) => {
+ setEnabled(next);
+ setSaving(true);
+ setError(null);
+ try {
+ await onToggle(next);
+ } catch (err) {
+ setEnabled(!next);
+ setError(toFriendlyMessage(err, "Could not save the setting."));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <div className="space-y-1.5">
+ <div className="flex items-start justify-between gap-4">
+ <Label htmlFor={id} className="text-sm font-medium text-[var(--color-text-primary)]">
+ Use your configured model to name helpers and draft code
+ </Label>
+ <Switch
+ id={id}
+ checked={enabled}
+ disabled={saving}
+ onCheckedChange={(next) => void change(Boolean(next))}
+ />
+ </div>
+ <p className="max-w-prose text-xs text-[var(--color-text-tertiary)]">
+ {value.provider ? (
+ <>
+ Uses <span className="text-[var(--color-text-secondary)]">{value.provider}</span>
+ {value.model ? (
+ <>
+ {" · "}
+ <span className="font-mono text-[var(--color-text-secondary)]">{value.model}</span>
+ </>
+ ) : null}
+ , the same model as chat. Drafts are shown for review and never applied.
+ </>
+ ) : (
+ <>
+ No model configured.{" "}
+ {setupHref ? (
+ <a
+ href={setupHref}
+ className="text-[var(--color-accent-primary)] underline-offset-2 hover:underline"
+ >
+ Set one up
+ </a>
+ ) : null}
+ </>
+ )}
+ </p>
+ {error ? (
+ <p role="alert" className="flex items-start gap-2 text-xs text-[var(--color-error)]">
+ <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {error}
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
export interface RefactoringSettingsCardProps {
- /** Current persisted settings, or null while loading. */
+ /** Current settings, or null while loading. */
value: RefactoringSettingsValue | null;
- /** Persist the new settings. Host owns the API call. */
- onSave: (value: RefactoringSettingsValue) => Promise<void>;
+ onToggle: (enabled: boolean) => Promise<void>;
+ setupHref?: string | undefined;
/** True while the initial settings load is in flight. */
loading?: boolean;
/** Set when settings are unavailable (e.g. no local checkout on this server). */
unavailableReason?: string | null;
}
-type SaveState = "idle" | "saving" | "saved" | "error";
-
/**
- * The opt-in code-generation switch (`refactoring.llm`). A toggle plus optional
- * provider/model overrides, written to the repo's config. Presentation only —
- * the host wires `onSave` to the settings endpoint — so the hosted frontend can
- * reuse it unchanged.
+ * The settings-page home of {@link RefactoringModelToggle}, with its loading
+ * and unavailable states. Presentation only, so the hosted frontend can reuse it.
*/
export function RefactoringSettingsCard({
value,
- onSave,
+ onToggle,
+ setupHref,
loading = false,
unavailableReason = null,
}: RefactoringSettingsCardProps) {
- const [enabled, setEnabled] = React.useState(false);
- const [provider, setProvider] = React.useState("");
- const [model, setModel] = React.useState("");
- const [save, setSave] = React.useState<SaveState>("idle");
- const [error, setError] = React.useState<string | null>(null);
-
- // Seed the form from the persisted value once it arrives / changes.
- React.useEffect(() => {
- if (!value) return;
- setEnabled(value.enabled);
- setProvider(value.provider ?? "");
- setModel(value.model ?? "");
- }, [value]);
-
- const dirty =
- value !== null &&
- (enabled !== value.enabled ||
- provider !== (value.provider ?? "") ||
- model !== (value.model ?? ""));
-
- const persist = React.useCallback(async () => {
- setSave("saving");
- setError(null);
- try {
- await onSave({
- enabled,
- provider: provider.trim() || null,
- model: model.trim() || null,
- });
- setSave("saved");
- window.setTimeout(() => setSave("idle"), 1800);
- } catch (err) {
- setSave("error");
- setError(toFriendlyMessage(err, "Could not save settings."));
- }
- }, [enabled, provider, model, onSave]);
-
if (unavailableReason) {
- return (
- <p className="text-sm text-[var(--color-text-tertiary)]">{unavailableReason}</p>
- );
+ return <p className="text-sm text-[var(--color-text-tertiary)]">{unavailableReason}</p>;
}
-
if (loading || value === null) {
return (
<div className="flex items-center gap-2 text-sm text-[var(--color-text-secondary)]">
@@ -90,81 +131,5 @@ export function RefactoringSettingsCard({
</div>
);
}
-
- return (
- <div className="space-y-4">
- <div className="flex items-start justify-between gap-4">
- <div className="space-y-0.5">
- <div className="flex items-center gap-2">
- <Wand2 className="h-4 w-4 text-[var(--color-accent-primary)]" />
- <Label htmlFor="refactoring-llm-enabled" className="text-sm font-medium">
- Generate code from plans
- </Label>
- </div>
- <p className="max-w-prose text-xs text-[var(--color-text-tertiary)]">
- Let the Refactoring tab turn a deterministic plan into a reviewable diff using your
- configured model. Off by default; never runs during indexing. Suggestion only — no
- auto-apply.
- </p>
- </div>
- <Switch
- id="refactoring-llm-enabled"
- checked={enabled}
- onCheckedChange={(next) => setEnabled(Boolean(next))}
- />
- </div>
-
- {enabled ? (
- <div className="grid gap-3 sm:grid-cols-2">
- <div className="space-y-1.5">
- <Label htmlFor="refactoring-llm-provider" className="text-xs text-[var(--color-text-secondary)]">
- Provider <span className="text-[var(--color-text-tertiary)]">(optional)</span>
- </Label>
- <Input
- id="refactoring-llm-provider"
- value={provider}
- onChange={(e) => setProvider(e.target.value)}
- placeholder="repo default (e.g. anthropic)"
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="refactoring-llm-model" className="text-xs text-[var(--color-text-secondary)]">
- Model <span className="text-[var(--color-text-tertiary)]">(optional)</span>
- </Label>
- <Input
- id="refactoring-llm-model"
- value={model}
- onChange={(e) => setModel(e.target.value)}
- placeholder="repo default"
- />
- </div>
- </div>
- ) : null}
-
- {error ? (
- <div className="flex items-start gap-2 text-xs text-[var(--color-error)]">
- <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
- {error}
- </div>
- ) : null}
-
- <div className="flex items-center gap-3">
- <button
- type="button"
- onClick={persist}
- disabled={!dirty || save === "saving"}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--color-accent-primary)] px-3.5 py-2 text-sm font-semibold text-[var(--color-bg-surface)] transition-opacity hover:opacity-90 disabled:opacity-50"
- >
- {save === "saving" ? <Spinner /> : null}
- Save
- </button>
- {save === "saved" ? (
- <span className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-success)]">
- <Check className="h-3.5 w-3.5" />
- Saved
- </span>
- ) : null}
- </div>
- </div>
- );
+ return <RefactoringModelToggle value={value} onToggle={onToggle} setupHref={setupHref} />;
}
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index c928356d7..47902b6e1 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -60,11 +60,13 @@ import {
getRefactoringOpportunity,
getRefactoringPlan,
getRefactoringSettings,
+ updateRefactoringSettings,
updateRefactoringOpportunityStatus,
type RefactoringSettings,
} from "@/lib/api/refactoring";
import { getFileContent } from "@/lib/api/files";
import { getRelatedWork, relatedWorkHref } from "@/lib/api/related-work";
+import { providerSetupHref } from "@/lib/utils/page-href";
const TYPE_VALUES = ["all", "structural", ...TYPE_ORDER] as const;
type TypeFilter = (typeof TYPE_VALUES)[number];
@@ -211,20 +213,36 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
[repoId, mutate],
);
- // Opt-in code generation. Enabled only when the repo's config turns it on (a
- // local-`serve` capability); the settings call 404s on hosted backends, which
- // simply leaves the action hidden.
- const { data: settings } = useSWR<RefactoringSettings>(
+ // Opt-in code generation (a local-`serve` capability). The action shows only
+ // when the switch is on and a model resolves; otherwise the plan drawer shows
+ // the switch, with a setup link when no model is configured. The settings
+ // call 404s on hosted backends, which hides both.
+ const { data: settings, mutate: mutateSettings } = useSWR<RefactoringSettings>(
`refactoring-settings:${repoId}`,
() => getRefactoringSettings(repoId),
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
const onGenerateCode = useMemo(
() =>
- settings?.enabled
+ settings?.enabled && settings.provider
? (plan: RefactoringPlan) => generateRefactoringCode(repoId, plan.id)
: undefined,
- [settings?.enabled, repoId],
+ [settings?.enabled, settings?.provider, repoId],
+ );
+ const modelSetting = useMemo(
+ () =>
+ settings
+ ? {
+ value: settings,
+ onToggle: async (enabled: boolean) => {
+ await mutateSettings(await updateRefactoringSettings(repoId, enabled), {
+ revalidate: false,
+ });
+ },
+ setupHref: providerSetupHref(repoId),
+ }
+ : undefined,
+ [settings, mutateSettings, repoId],
);
const facetCounts = data?.facets?.lead_type ?? {};
@@ -388,6 +406,7 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
onAiPrompt={(plan) => setPromptFor({ kind: "plan", value: plan })}
onGenerateCode={onGenerateCode}
settingsHref={`${prefix}/settings`}
+ modelSetting={modelSetting}
fileHref={fileHref}
/>
diff --git a/packages/web/src/components/repos/refactoring-settings-section.tsx b/packages/web/src/components/repos/refactoring-settings-section.tsx
index 7ec5ada79..d0d598b10 100644
--- a/packages/web/src/components/repos/refactoring-settings-section.tsx
+++ b/packages/web/src/components/repos/refactoring-settings-section.tsx
@@ -1,22 +1,20 @@
"use client";
import useSWR from "swr";
-import {
- RefactoringSettingsCard,
- type RefactoringSettingsValue,
-} from "@repowise-dev/ui/refactoring";
+import { RefactoringSettingsCard } from "@repowise-dev/ui/refactoring";
import {
getRefactoringSettings,
updateRefactoringSettings,
type RefactoringSettings,
} from "@/lib/api/refactoring";
import { ApiClientError } from "@/lib/api/client";
+import { providerSetupHref } from "@/lib/utils/page-href";
/**
- * Repo settings → code-generation toggle. Reads/writes the `refactoring.llm`
- * block in the repo's config. The endpoint is a local-`serve` capability, so a
- * 404 (no accessible checkout, e.g. hosted) renders a quiet unavailable note
- * rather than an error.
+ * Repo settings → code-generation toggle. Writes `refactoring.llm.enabled` and
+ * shows the provider/model chat resolves, which generation reuses. The endpoint
+ * is a local-`serve` capability, so a 404 (no accessible checkout, e.g. hosted)
+ * renders a quiet unavailable note rather than an error.
*/
export function RefactoringSettingsSection({ repoId }: { repoId: string }) {
const { data, error, isLoading, mutate } = useSWR<RefactoringSettings>(
@@ -32,15 +30,16 @@ export function RefactoringSettingsSection({ repoId }: { repoId: string }) {
? "Could not load code-generation settings."
: null;
- const onSave = async (value: RefactoringSettingsValue) => {
- const saved = await updateRefactoringSettings(repoId, value);
+ const onToggle = async (enabled: boolean) => {
+ const saved = await updateRefactoringSettings(repoId, enabled);
await mutate(saved, { revalidate: false });
};
return (
<RefactoringSettingsCard
value={data ?? null}
- onSave={onSave}
+ onToggle={onToggle}
+ setupHref={providerSetupHref(repoId)}
loading={isLoading}
unavailableReason={unavailable}
/>
diff --git a/packages/web/src/lib/utils/page-href.ts b/packages/web/src/lib/utils/page-href.ts
index 07b31b239..a5b145157 100644
--- a/packages/web/src/lib/utils/page-href.ts
+++ b/packages/web/src/lib/utils/page-href.ts
@@ -11,6 +11,11 @@ const FILE_PAGE_PREFIX = filePageId("");
* inside the docs SPA (`/docs?page=`) instead of the standalone wiki route,
* so navigation keeps the tree/reading context.
*/
+/** Where a repo's LLM provider and model are set up. */
+export function providerSetupHref(repoId: string): string {
+ return `/repos/${repoId}/settings#provider`;
+}
+
export function pageHref(repoId: string, pageId: string): string {
const prefix = `/repos/${repoId}`;
if (pageId.startsWith(FILE_PAGE_PREFIX)) {
diff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.py
index dc10fcf37..e63c73707 100644
--- a/tests/unit/health/test_refactoring_enrich.py
+++ b/tests/unit/health/test_refactoring_enrich.py
@@ -21,7 +21,6 @@ from repowise.core.analysis.health.refactoring.llm.enrich import (
_extract_diff,
_gather_spans,
_validate_extract_method,
- build_enrichment_provider,
)
from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
from repowise.core.providers.llm.base import GeneratedResponse
@@ -387,59 +386,11 @@ async def test_self_check_skipped_for_non_extract_class(tmp_path: Path) -> None:
def test_llm_enrichment_enabled_gate() -> None:
assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": True}}}) is True
- # Only an explicit false disables it; an unset key defaults on (the local
- # serve experience works without a config trip).
+ # Off unless the repo turns it on: generation sends source to a model.
assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": False}}}) is False
- assert llm_enrichment_enabled({"refactoring": {}}) is True
- assert llm_enrichment_enabled({}) is True
-
-
-def test_build_enrichment_provider_auto_detects_kimi(tmp_path, monkeypatch) -> None:
- for key in (
- "ANTHROPIC_API_KEY",
- "OPENAI_API_KEY",
- "OPENROUTER_API_KEY",
- "DEEPSEEK_API_KEY",
- "GEMINI_API_KEY",
- "GOOGLE_API_KEY",
- "OLLAMA_BASE_URL",
- "LITELLM_API_KEY",
- ):
- monkeypatch.delenv(key, raising=False)
- monkeypatch.setenv("KIMI_API_KEY", "sk-kimi-test")
-
- captured = {}
-
- def fake_get_provider(name, **kwargs):
- captured["name"] = name
- captured["kwargs"] = kwargs
- return object()
-
- monkeypatch.setattr("repowise.core.providers.get_provider", fake_get_provider)
-
- provider = build_enrichment_provider(tmp_path)
-
- assert provider is not None
- assert captured == {
- "name": "kimi",
- "kwargs": {"api_key": "sk-kimi-test"},
- }
-
-
-def test_build_enrichment_provider_runs_a_repo_cwd_cli_in_the_repo(tmp_path, monkeypatch) -> None:
- """A configured agent CLI that works in the repo's directory is told which repo."""
- captured = {}
-
- def fake_get_provider(name, **kwargs):
- captured.update(kwargs, name=name)
- return object()
-
- monkeypatch.setattr("repowise.core.providers.get_provider", fake_get_provider)
-
- build_enrichment_provider(tmp_path, provider_name="codex_cli")
-
- assert captured["name"] == "codex_cli"
- assert captured["repo_path"] == tmp_path
+ assert llm_enrichment_enabled({"refactoring": {"llm": {}}}) is False
+ assert llm_enrichment_enabled({"refactoring": {}}) is False
+ assert llm_enrichment_enabled({}) is False
def test_validate_extract_method_detects_ccn_drop():
diff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.py
index 4bd29b889..c93888397 100644
--- a/tests/unit/server/mcp/test_refactoring.py
+++ b/tests/unit/server/mcp/test_refactoring.py
@@ -1,7 +1,8 @@
"""Unit tests for the generate_refactoring_code MCP tool (opt-in enrichment).
-Uses the ``mock`` provider (no API calls) and a real temp checkout so the tool
-can read the plan's source spans and honor the config gate.
+Stubs the shared chat resolver with a ``MockProvider`` (no API calls) and uses
+a real temp checkout so the tool can read the plan's source spans and honor the
+config gate.
"""
from __future__ import annotations
@@ -18,13 +19,13 @@ from repowise.core.persistence.models import Repository
_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
-async def _setup(factory, *, enabled: bool) -> tuple[Path, str]:
+async def _setup(factory, *, enabled: bool | None) -> tuple[Path, str]:
repo_dir = Path(tempfile.mkdtemp()) / "mcp-enrich"
(repo_dir / "pkg").mkdir(parents=True, exist_ok=True)
(repo_dir / ".repowise").mkdir(exist_ok=True)
- # enabled defaults on, so the disabled case writes an explicit false.
- cfg = "provider: mock\n"
- cfg += f"refactoring:\n llm:\n enabled: {'true' if enabled else 'false'}\n"
+ cfg = "provider: anthropic\n"
+ if enabled is not None:
+ cfg += f"refactoring:\n llm:\n enabled: {'true' if enabled else 'false'}\n"
(repo_dir / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
(repo_dir / "pkg" / "leaf.py").write_text(
"class GodClass:\n def a(self):\n return 1\n", encoding="utf-8"
@@ -81,9 +82,19 @@ def _mcp_globals(factory):
@pytest.mark.asyncio
-async def test_generate_code_happy_path(factory, _mcp_globals) -> None:
+async def test_generate_code_happy_path(factory, _mcp_globals, monkeypatch) -> None:
+ from repowise.core.providers.llm.mock import MockProvider
from repowise.server.mcp_server import generate_refactoring_code
+ calls: list[dict] = []
+
+ def fake_resolver(**kwargs):
+ calls.append(kwargs)
+ return MockProvider()
+
+ monkeypatch.setattr(
+ "repowise.server.provider_config.get_chat_provider_instance", fake_resolver
+ )
repo_dir, sid = await _setup(factory, enabled=True)
_mcp_globals._session_factory = factory
_mcp_globals._repo_path = str(repo_dir)
@@ -94,13 +105,16 @@ async def test_generate_code_happy_path(factory, _mcp_globals) -> None:
assert result["provider"] == "mock"
assert result["content"]
assert "_meta" in result
+ # The provider comes from the resolver chat uses, scoped to this repo.
+ assert calls == [{"repo_path": repo_dir, "repo_id": "r1"}]
@pytest.mark.asyncio
-async def test_generate_code_disabled(factory, _mcp_globals) -> None:
[email protected]("enabled", [False, None], ids=["explicit_false", "unset"])
+async def test_generate_code_disabled(factory, _mcp_globals, enabled) -> None:
from repowise.server.mcp_server import generate_refactoring_code
- repo_dir, sid = await _setup(factory, enabled=False)
+ repo_dir, sid = await _setup(factory, enabled=enabled)
_mcp_globals._session_factory = factory
_mcp_globals._repo_path = str(repo_dir)
diff --git a/tests/unit/server/test_provider_config.py b/tests/unit/server/test_provider_config.py
index a7adbe07b..cd7878b7b 100644
--- a/tests/unit/server/test_provider_config.py
+++ b/tests/unit/server/test_provider_config.py
@@ -372,3 +372,13 @@ def test_list_provider_status_never_returns_key_material(clean_env, tmp_path):
}
assert "key" not in provider
assert "api_key" not in provider
+
+
+def test_configured_active_provider_needs_the_key_chat_needs(clean_env, tmp_path):
+ """A configured provider without its key is reported as none, not as usable."""
+ repo = _make_repo(tmp_path / "repo", config="provider: anthropic\nmodel: claude-x\n")
+ assert pc.get_active_provider(repo_path=repo) == ("anthropic", "claude-x")
+ assert pc.get_configured_active_provider(repo_path=repo) == (None, None)
+
+ _make_repo(repo, env="ANTHROPIC_API_KEY=sk-ant-test\n")
+ assert pc.get_configured_active_provider(repo_path=repo) == ("anthropic", "claude-x")
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index 43686b70f..9accb6d93 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -585,14 +585,13 @@ async def test_min_confidence_filters(client: AsyncClient, app) -> None:
async def _seed_enrich_repo(client: AsyncClient, app, *, enabled: bool) -> tuple[str, str]:
"""A repo with a real checkout (config + one source file) and one plan.
- Uses the ``mock`` provider so ``build_enrichment_provider`` resolves a
- MockProvider with no API key. Returns ``(repo_id, suggestion_id)``."""
+ The provider is stubbed per test through the shared chat resolver.
+ Returns ``(repo_id, suggestion_id)``."""
repo_dir = Path(tempfile.mkdtemp()) / "enrich-repo"
(repo_dir / "pkg").mkdir(parents=True, exist_ok=True)
(repo_dir / ".git").mkdir(exist_ok=True)
(repo_dir / ".repowise").mkdir(exist_ok=True)
- # enabled defaults on, so the disabled case writes an explicit false.
- cfg = "provider: mock\n"
+ cfg = "provider: anthropic\n"
cfg += f"refactoring:\n llm:\n enabled: {'true' if enabled else 'false'}\n"
(repo_dir / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
(repo_dir / "pkg" / "leaf.py").write_text(
@@ -640,7 +639,24 @@ async def _seed_enrich_repo(client: AsyncClient, app, *, enabled: bool) -> tuple
return repo_id, suggestion_id
-async def test_generate_code_happy_path(client: AsyncClient, app) -> None:
+def _stub_chat_resolver(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
+ """Route the shared chat resolver to a MockProvider and record its calls."""
+ from repowise.core.providers.llm.mock import MockProvider
+
+ calls: list[dict] = []
+
+ def fake(**kwargs):
+ calls.append(kwargs)
+ return MockProvider()
+
+ monkeypatch.setattr("repowise.server.provider_config.get_chat_provider_instance", fake)
+ return calls
+
+
+async def test_generate_code_happy_path(
+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls = _stub_chat_resolver(monkeypatch)
repo_id, sid = await _seed_enrich_repo(client, app, enabled=True)
resp = await client.post(f"/api/repos/{repo_id}/refactoring/{sid}/generate-code", json={})
assert resp.status_code == 200
@@ -648,6 +664,10 @@ async def test_generate_code_happy_path(client: AsyncClient, app) -> None:
assert body["refactoring_type"] == "extract_class"
assert body["target_symbol"] == "GodClass"
assert body["provider"] == "mock"
+ # Generation asks the resolver chat uses, scoped to this repo, not its own.
+ assert len(calls) == 1
+ assert calls[0]["repo_id"] == repo_id
+ assert calls[0]["repo_path"].name == "enrich-repo"
assert body["content"] # the mock returned something
assert body["spans"] and body["spans"][0]["file"] == "pkg/leaf.py"
@@ -669,58 +689,67 @@ async def test_generate_code_unknown_id_404(client: AsyncClient, app) -> None:
# ---------------------------------------------------------------------------
-async def test_settings_default_enabled_when_unset(client: AsyncClient, app) -> None:
- """An untouched repo (no config) reads as enabled with no provider/model."""
+def _isolated_provider_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep the server-global provider store out of the user's home."""
+ monkeypatch.setenv("REPOWISE_CONFIG_DIR", str(tmp_path / "server-store"))
+
+
[email protected]("_isolated_provider_store")
+async def test_settings_default_off_when_unset(client: AsyncClient, app) -> None:
+ """An untouched repo reads as off; code generation waits for a yes."""
repo = await create_test_repo(client)
resp = await client.get(f"/api/repos/{repo['id']}/refactoring/settings")
assert resp.status_code == 200
- body = resp.json()
- assert body == {"enabled": True, "provider": None, "model": None}
+ assert resp.json()["enabled"] is False
-async def test_settings_put_round_trips_and_preserves_other_keys(client: AsyncClient, app) -> None:
[email protected]("_isolated_provider_store")
+async def test_settings_round_trip_shows_chat_model_and_no_secret(
+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch
+) -> None:
import yaml
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-secret-value")
repo = await create_test_repo(client)
repo_id = repo["id"]
- # Seed an unrelated key so we can assert the writer preserves it.
repo_dir = Path(repo["local_path"])
(repo_dir / ".repowise").mkdir(exist_ok=True)
- (repo_dir / ".repowise" / "config.yaml").write_text("provider: anthropic\n", encoding="utf-8")
-
- resp = await client.put(
- f"/api/repos/{repo_id}/refactoring/settings",
- json={"enabled": False, "provider": "openai", "model": "gpt-x"},
+ (repo_dir / ".repowise" / "config.yaml").write_text(
+ "provider: anthropic\nmodel: claude-test\n", encoding="utf-8"
)
+
+ resp = await client.put(f"/api/repos/{repo_id}/refactoring/settings", json={"enabled": True})
assert resp.status_code == 200
- assert resp.json() == {"enabled": False, "provider": "openai", "model": "gpt-x"}
+ expected = {"enabled": True, "provider": "anthropic", "model": "claude-test"}
+ assert resp.json() == expected
+ assert "sk-ant-secret-value" not in resp.text
- # GET reflects the write, and the unrelated top-level key survived.
got = await client.get(f"/api/repos/{repo_id}/refactoring/settings")
- assert got.json() == {"enabled": False, "provider": "openai", "model": "gpt-x"}
+ assert got.json() == expected
cfg = yaml.safe_load((repo_dir / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
+ # Only the switch is written; the model stays where chat reads it.
assert cfg["provider"] == "anthropic"
- assert cfg["refactoring"]["llm"] == {"enabled": False, "provider": "openai", "model": "gpt-x"}
+ assert cfg["refactoring"]["llm"] == {"enabled": True}
+ await client.put(f"/api/repos/{repo_id}/refactoring/settings", json={"enabled": False})
+ got = await client.get(f"/api/repos/{repo_id}/refactoring/settings")
+ assert got.json()["enabled"] is False
-async def test_settings_put_blank_provider_clears_key(client: AsyncClient, app) -> None:
- import yaml
[email protected]("_isolated_provider_store")
+async def test_settings_reports_no_provider_when_its_key_is_missing(
+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A provider chat could not build reads as none, so the UI offers setup."""
+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
repo = await create_test_repo(client)
- repo_id = repo["id"]
- await client.put(
- f"/api/repos/{repo_id}/refactoring/settings",
- json={"enabled": True, "provider": "openai", "model": "gpt-x"},
- )
- # Re-save with blank provider/model -> the keys are removed, not "".
- resp = await client.put(
- f"/api/repos/{repo_id}/refactoring/settings",
- json={"enabled": True, "provider": "", "model": " "},
- )
- assert resp.json() == {"enabled": True, "provider": None, "model": None}
repo_dir = Path(repo["local_path"])
- cfg = yaml.safe_load((repo_dir / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
- assert cfg["refactoring"]["llm"] == {"enabled": True}
+ (repo_dir / ".repowise").mkdir(exist_ok=True)
+ (repo_dir / ".repowise" / "config.yaml").write_text("provider: anthropic\n", encoding="utf-8")
+
+ resp = await client.get(f"/api/repos/{repo['id']}/refactoring/settings")
+ assert resp.json() == {"enabled": False, "provider": None, "model": None}
async def test_settings_unknown_repo_404(client: AsyncClient, app) -> None:
diff --git a/tests/unit/server/test_refactoring_plan_rank.py b/tests/unit/server/test_refactoring_plan_rank.py
index bc4e6407d..71bd42b67 100644
--- a/tests/unit/server/test_refactoring_plan_rank.py
+++ b/tests/unit/server/test_refactoring_plan_rank.py
@@ -215,7 +215,9 @@ async def test_one_plan_reads_its_stored_rank(
return _Generated(suggestion)
monkeypatch.setattr(llm, "llm_enrichment_enabled", lambda _config: True)
- monkeypatch.setattr(llm, "build_enrichment_provider", lambda *_a, **_k: object())
+ monkeypatch.setattr(
+ "repowise.server.provider_config.get_chat_provider_instance", lambda **_k: object()
+ )
monkeypatch.setattr(llm, "enrich_suggestion", enrich)
response = await client.post(f"/api/repos/{repo_id}/refactoring/{listed[0]['id']}/generate-code")
assert response.status_code == 200, response.text