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(web): add a model in two clicks from the docs badge and chat (#4678)

Raghav Chamadiya20420932e40d
diff --git a/packages/api-client/src/providers.ts b/packages/api-client/src/providers.ts
index 11cc885b1..d20f79105 100644
--- a/packages/api-client/src/providers.ts
+++ b/packages/api-client/src/providers.ts
@@ -9,11 +9,18 @@ import type {
ProviderValidation,
} from "./types";
+/** `detect` also asks each agent CLI whether it is signed in, which fills
+ * `detected: "signed_in"`; it runs a short process per CLI, so only the
+ * surfaces that offer sources ask for it. */
export async function getProviders(
repoId?: string,
+ options: { detect?: boolean } = {},
): Promise<ProvidersResponse> {
- const qs = repoId ? `?repo_id=${encodeURIComponent(repoId)}` : "";
- return apiGet<ProvidersResponse>(`/api/providers${qs}`);
+ const params = new URLSearchParams();
+ if (repoId) params.set("repo_id", repoId);
+ if (options.detect) params.set("detect", "true");
+ const qs = params.toString();
+ return apiGet<ProvidersResponse>(`/api/providers${qs ? `?${qs}` : ""}`);
}
/** Set the provider and model (any id the provider accepts). With `repoId`
diff --git a/packages/api-client/src/repos.ts b/packages/api-client/src/repos.ts
index 98be5653f..eb6f1227e 100644
--- a/packages/api-client/src/repos.ts
+++ b/packages/api-client/src/repos.ts
@@ -68,12 +68,14 @@ export async function preflightIndex(
/** Cost + page counts for a generate selection, cascade fallout included.
* Heavy (rehydrates the graph and re-parses), so fetch it lazily — never on
- * every render. */
+ * every render. `provider` prices a provider the repo does not use yet. */
export async function generateEstimate(
repoId: string,
body: GenerateRequest,
+ options: { provider?: string } = {},
): Promise<GenerateEstimate> {
- return apiPost<GenerateEstimate>(`/api/repos/${repoId}/generate/estimate`, body);
+ const qs = options.provider ? `?provider=${encodeURIComponent(options.provider)}` : "";
+ return apiPost<GenerateEstimate>(`/api/repos/${repoId}/generate/estimate${qs}`, body);
}
/** Launch a scoped generate job (writes the selected pages with a model).
diff --git a/packages/api-client/src/types/misc.ts b/packages/api-client/src/types/misc.ts
index 8496e2c9d..39e9db9ae 100644
--- a/packages/api-client/src/types/misc.ts
+++ b/packages/api-client/src/types/misc.ts
@@ -33,10 +33,16 @@ export interface ProviderInfo {
accepts_base_url?: boolean;
/** Can point at a local OpenAI-compatible server (LM Studio) with no key. */
local_server?: boolean;
+ /** A model that runs on this machine (not an agent CLI). */
+ local_model?: boolean;
/** Env vars a user sets to make the provider usable. */
env_vars?: string[];
/** One line on how to install or set it up. */
setup_hint?: string;
+ /** What on this machine makes it usable: a signed-in agent CLI (only with
+ * `detect`), a key in the env or the repo's `.repowise/.env`, or a key
+ * stored on this server. */
+ detected?: "signed_in" | "env" | "saved" | null;
}
export interface EmbedderInfo {
diff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.py
index 4ca984529..0967cc189 100644
--- a/packages/server/src/repowise/server/provider_config.py
+++ b/packages/server/src/repowise/server/provider_config.py
@@ -25,6 +25,7 @@ import logging
import os
import threading
from collections.abc import Mapping
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -35,6 +36,7 @@ from repowise.core.providers.embedding.registry import (
list_embedders,
)
from repowise.core.providers.llm.resolve import (
+ GLOBAL_CONFIG_FILENAME,
UNSET,
LLMSelection,
global_config_path,
@@ -72,6 +74,8 @@ PROVIDER_CATALOG: list[dict[str, Any]] = [
"accepts_base_url": bool(spec.base_url_envs),
# Can point at a local OpenAI-compatible server and run with no key.
"local_server": spec.keyless_on_loopback,
+ # A model that runs on this machine (not an agent CLI).
+ "local_model": spec.local and not spec.agent,
# What a user sets to make it usable, and how to install it.
"env_vars": list(spec.required_envs),
"setup_hint": spec.setup_hint,
@@ -308,19 +312,72 @@ def resolve_for_repo(
)
+def _logged_in(identity: Any) -> bool:
+ """One CLI's login check; a check that breaks counts as not signed in."""
+ try:
+ return bool(identity.is_logged_in())
+ except Exception:
+ logger.debug("Login check for %s failed", identity.slug, exc_info=True)
+ return False
+
+
+def _signed_in_agent_providers() -> set[str]:
+ """Catalog providers whose agent CLI is installed and signed in here.
+
+ Each check is a short subprocess (the CLI's own login query), so they run
+ side by side.
+ """
+ from repowise.core.agents.identity import get_identity
+
+ agents = {
+ p["id"]: identity
+ for p in PROVIDER_CATALOG
+ if (agent := PROVIDER_SPECS[p["id"]].agent) and (identity := get_identity(agent))
+ }
+ if not agents:
+ return set()
+ with ThreadPoolExecutor(max_workers=len(agents)) as pool:
+ signed_in = list(pool.map(_logged_in, agents.values()))
+ return {name for name, ok in zip(agents, signed_in, strict=True) if ok}
+
+
+def _detected_source(
+ provider_id: str, repo_path: str | Path | None, signed_in: set[str] | None
+) -> str | None:
+ """What on this machine makes *provider_id* usable without setup.
+
+ ``signed_in``: its agent CLI is signed in (only checked when *signed_in*
+ is given). ``env``: a key in the process env or the repo's
+ ``.repowise/.env``. ``saved``: a key stored on this server.
+ """
+ if PROVIDER_SPECS[provider_id].agent:
+ return "signed_in" if signed_in is not None and provider_id in signed_in else None
+ if not _CATALOG_BY_ID[provider_id]["requires_key"]:
+ return None
+ source = resolve_api_key(provider_id, repo_path)[1]
+ if source is None:
+ return None
+ return "saved" if source == GLOBAL_CONFIG_FILENAME else "env"
+
+
def list_provider_status(
repo_id: str | None = None,
repo_path: str | Path | None = None,
+ *,
+ detect: bool = False,
) -> dict[str, Any]:
"""Return provider catalog + the active selection for the repo.
With ``repo_path`` the active provider/model/base URL are what that repo's
chat will use, each with the layer it came from (``provenance``). A
configured model missing from the static catalog is added to that
- provider's ``models`` so the picker can show it.
+ provider's ``models`` so the picker can show it. Each provider's
+ ``detected`` names a key found for it; with *detect* it also names a
+ signed-in agent CLI, which costs one subprocess per agent provider.
"""
selection = resolve_for_repo(repo_id, repo_path)
active_id, model = selection.provider, selection.model
+ signed_in = _signed_in_agent_providers() if detect else None
providers = []
for p in PROVIDER_CATALOG:
@@ -339,8 +396,10 @@ def list_provider_status(
"requires_key": p["requires_key"],
"accepts_base_url": p["accepts_base_url"],
"local_server": p["local_server"],
+ "local_model": p["local_model"],
"env_vars": p["env_vars"],
"setup_hint": p["setup_hint"],
+ "detected": _detected_source(p["id"], repo_path, signed_in),
}
)
diff --git a/packages/server/src/repowise/server/routers/_repo_pricing.py b/packages/server/src/repowise/server/routers/_repo_pricing.py
index 97186b6c1..012423bee 100644
--- a/packages/server/src/repowise/server/routers/_repo_pricing.py
+++ b/packages/server/src/repowise/server/routers/_repo_pricing.py
@@ -11,12 +11,15 @@ from pathlib import Path
from typing import Any
-def resolve_provider(repo_path: str) -> tuple[Any, str | None, str | None, str | None]:
+def resolve_provider(
+ repo_path: str, provider: str | None = None
+) -> tuple[Any, str | None, str | None, str | None]:
"""``(client, provider name, model name, error)`` for the repo's chat provider.
- A provider that fails to resolve is reported through ``error`` with a
- ``None`` client rather than raised: both callers still answer with a
- partial payload.
+ *provider* prices another provider with the key and model resolved for
+ the repo, before it is made the repo's choice. A provider that fails to
+ resolve is reported through ``error`` with a ``None`` client rather than
+ raised: both callers still answer with a partial payload.
"""
llm_client = None
provider_name: str | None = None
@@ -25,7 +28,7 @@ def resolve_provider(repo_path: str) -> tuple[Any, str | None, str | None, str |
try:
from repowise.server.provider_config import get_chat_provider_instance
- llm_client = get_chat_provider_instance(repo_path=repo_path)
+ llm_client = get_chat_provider_instance(repo_path=repo_path, provider_override=provider)
provider_name = getattr(llm_client, "provider_name", None)
model_name = getattr(llm_client, "model_name", None)
except Exception as exc:
diff --git a/packages/server/src/repowise/server/routers/providers.py b/packages/server/src/repowise/server/routers/providers.py
index 8a5419abd..7eebd7c5e 100644
--- a/packages/server/src/repowise/server/routers/providers.py
+++ b/packages/server/src/repowise/server/routers/providers.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import asyncio
+
from fastapi import APIRouter, Depends, HTTPException, Request
from repowise.core.persistence import crud
@@ -56,14 +58,19 @@ async def _repo_path_for(request: Request, repo_id: str | None) -> str | None:
@router.get("", response_model=ProviderStatusResponse)
-async def get_providers(request: Request, repo_id: str | None = None):
+async def get_providers(request: Request, repo_id: str | None = None, detect: bool = False):
"""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.
+ server-global default. ``?detect=true`` also asks each agent CLI whether
+ it is signed in (a short subprocess each), so it runs off the event loop.
"""
repo_path = await _repo_path_for(request, repo_id)
+ if detect:
+ return await asyncio.to_thread(
+ list_provider_status, repo_id=repo_id, repo_path=repo_path, detect=True
+ )
return list_provider_status(repo_id=repo_id, repo_path=repo_path)
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 7610820c0..41992f5d1 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -583,6 +583,7 @@ async def generate_estimate(
repo_id: str,
request: Request,
body: GenerateRequestBody,
+ provider: str | None = None,
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Cost + page counts for a generate selection, including cascade fallout.
@@ -590,7 +591,8 @@ async def generate_estimate(
Resolves the exact same scope the job would (rehydrating the graph and
re-parsing), so the returned page count and estimate match what a launched
job spends. Heavier than the pre-index preflight because it walks the real
- dependency graph rather than a file count.
+ dependency graph rather than a file count. ``?provider=`` prices a
+ provider the repo does not use yet, so a picker can show the cost first.
"""
repo = await _get_repo_or_404(session, repo_id)
@@ -613,8 +615,8 @@ async def generate_estimate(
gen_config = _build_generation_config(repo_path, job_config, wiki_style)
# Price with the repo's configured provider/model, if one resolves.
- _client, provider_name, model_name, provider_error = resolve_provider(str(repo_path))
- provider = {"name": provider_name, "model": model_name, "error": provider_error}
+ _client, provider_name, model_name, provider_error = resolve_provider(str(repo_path), provider)
+ priced_with = {"name": provider_name, "model": model_name, "error": provider_error}
session_factory = _resolve_repo_session_factory(request.app.state, repo_id)
state = _load_state(repo_path)
@@ -642,7 +644,7 @@ async def generate_estimate(
"pages_by_type": {},
"pages_to_mark_stale": 0,
"unknown_page_ids": [],
- "provider": provider,
+ "provider": priced_with,
"estimate": None,
"note": note,
}
@@ -664,7 +666,7 @@ async def generate_estimate(
"pages_by_type": pages_by_type,
"pages_to_mark_stale": len(plan.stale_ids),
"unknown_page_ids": list(plan.unknown_page_ids),
- "provider": provider,
+ "provider": priced_with,
"estimate": estimate,
}
diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.py
index aebaca478..b95acc787 100644
--- a/packages/server/src/repowise/server/schemas/ui_helpers.py
+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py
@@ -55,10 +55,16 @@ class ProviderEntry(BaseModel):
accepts_base_url: bool = False
#: Can point at a local OpenAI-compatible server (LM Studio) with no key.
local_server: bool = False
+ #: A model that runs on this machine (not an agent CLI).
+ local_model: bool = False
#: Env vars a user sets to make the provider usable.
env_vars: list[str] = []
#: One line on how to install or set it up.
setup_hint: str = ""
+ #: What on this machine makes it usable: ``signed_in`` (a signed-in agent
+ #: CLI, reported only for ``?detect=true``), ``env`` (a key in the process
+ #: env or the repo's ``.repowise/.env``) or ``saved`` (a key stored here).
+ detected: Literal["signed_in", "env", "saved"] | None = None
class EmbedderEntry(BaseModel):
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 40546aa35..764a42ee4 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -3435,8 +3435,10 @@ export interface ProviderEntry {
requires_key?: boolean;
accepts_base_url?: boolean;
local_server?: boolean;
+ local_model?: boolean;
env_vars?: string[];
setup_hint?: string;
+ detected?: "signed_in" | "env" | "saved" | null;
}
export interface ProviderModelEntry {
diff --git a/packages/ui/__tests__/docs/docs-mode-badge.test.tsx b/packages/ui/__tests__/docs/docs-mode-badge.test.tsx
index e9fcebe9f..1de387e2d 100644
--- a/packages/ui/__tests__/docs/docs-mode-badge.test.tsx
+++ b/packages/ui/__tests__/docs/docs-mode-badge.test.tsx
@@ -1,5 +1,5 @@
-import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
import { DocsModeBadge } from "../../src/docs/docs-mode-badge.js";
describe("DocsModeBadge", () => {
@@ -17,4 +17,16 @@ describe("DocsModeBadge", () => {
const { container } = render(<DocsModeBadge mode="llm" />);
expect(container).toBeEmptyDOMElement();
});
+
+ it("becomes the action that offers a model", () => {
+ const onAction = vi.fn();
+ render(<DocsModeBadge mode="deterministic" onAction={onAction} />);
+ fireEvent.click(screen.getByRole("button", { name: /Write with a model/ }));
+ expect(onAction).toHaveBeenCalledOnce();
+ });
+
+ it("offers no action once the wiki is written", () => {
+ const { container } = render(<DocsModeBadge mode="llm" onAction={vi.fn()} />);
+ expect(container).toBeEmptyDOMElement();
+ });
});
diff --git a/packages/ui/__tests__/settings/model-upgrade-sheet.test.tsx b/packages/ui/__tests__/settings/model-upgrade-sheet.test.tsx
new file mode 100644
index 000000000..98d81eb2e
--- /dev/null
+++ b/packages/ui/__tests__/settings/model-upgrade-sheet.test.tsx
@@ -0,0 +1,129 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import {
+ HOSTED_SOURCE_ID,
+ PASTE_SOURCE_ID,
+ defaultModelSource,
+ orderModelSources,
+ pasteKeyProviders,
+ type ModelSourceProvider,
+} from "../../src/settings/model-sources";
+import { ModelUpgradeSheet, type ModelUpgradeSheetProps } from "../../src/settings/model-upgrade-sheet";
+
+const CATALOG: ModelSourceProvider[] = [
+ { id: "gemini", name: "Google Gemini", requires_key: true, detected: null },
+ { id: "anthropic", name: "Anthropic", requires_key: true, detected: "saved" },
+ { id: "openai", name: "OpenAI", requires_key: true, detected: "env" },
+ { id: "ollama", name: "Ollama (Local)", requires_key: false, local_model: true, detected: null },
+ { id: "claude_cli", name: "Claude Code (Local CLI)", requires_key: false, detected: "signed_in" },
+ { id: "codex_cli", name: "Codex (Local CLI)", requires_key: false, detected: null },
+ { id: "litellm", name: "LiteLLM", requires_key: false, detected: null },
+];
+
+describe("orderModelSources", () => {
+ it("puts sign-ins, then keys, then the local model, paste and hosted last", () => {
+ const sources = orderModelSources(CATALOG);
+ expect(sources.map((s) => s.id)).toEqual([
+ "claude_cli",
+ "anthropic",
+ "openai",
+ "ollama",
+ PASTE_SOURCE_ID,
+ HOSTED_SOURCE_ID,
+ ]);
+ expect(sources.map((s) => s.kind)).toEqual(["cli", "key", "key", "local", "paste", "hosted"]);
+ expect(sources[0]).toMatchObject({ name: "Claude Code", providerId: "claude_cli" });
+ expect(sources[3]).toMatchObject({ name: "Ollama", detected: null });
+ });
+
+ it("leaves out providers with nothing set up", () => {
+ const ids = orderModelSources(CATALOG).map((s) => s.id);
+ expect(ids).not.toContain("gemini");
+ expect(ids).not.toContain("codex_cli");
+ expect(ids).not.toContain("litellm");
+ });
+
+ it("still offers paste and hosted with nothing detected", () => {
+ expect(orderModelSources([]).map((s) => s.id)).toEqual([PASTE_SOURCE_ID, HOSTED_SOURCE_ID]);
+ });
+});
+
+describe("defaultModelSource", () => {
+ const sources = orderModelSources(CATALOG);
+
+ it("keeps the repo's current provider when it is a row", () => {
+ expect(defaultModelSource(sources, "openai")).toBe("openai");
+ });
+
+ it("falls back to the first detected source", () => {
+ expect(defaultModelSource(sources, null)).toBe("claude_cli");
+ expect(defaultModelSource(sources, "gemini")).toBe("claude_cli");
+ });
+
+ it("never defaults to the local model or hosted on its own", () => {
+ const bare = orderModelSources([CATALOG[3]!]);
+ expect(defaultModelSource(bare, null)).toBe(PASTE_SOURCE_ID);
+ });
+});
+
+it("pasteKeyProviders offers every provider that takes a key", () => {
+ expect(pasteKeyProviders(CATALOG).map((p) => p.id)).toEqual(["gemini", "anthropic", "openai"]);
+});
+
+function renderSheet(overrides: Partial<ModelUpgradeSheetProps> = {}) {
+ const props: ModelUpgradeSheetProps = {
+ open: true,
+ onOpenChange: vi.fn(),
+ sources: orderModelSources(CATALOG),
+ selectedId: "claude_cli",
+ onSelect: vi.fn(),
+ keyProviders: [],
+ onAddKey: vi.fn(),
+ estimate: { pages: 46, costText: null, loading: false },
+ onWrite: vi.fn(),
+ hostedHref: "https://example.test/hosted",
+ ...overrides,
+ };
+ render(<ModelUpgradeSheet {...props} />);
+ return props;
+}
+
+describe("ModelUpgradeSheet", () => {
+ it("names a sign-in as a sign-in, never as free", () => {
+ renderSheet();
+ expect(screen.getByText("Uses your Claude Code sign-in.")).toBeInTheDocument();
+ expect(screen.getByText("46 pages to write")).toBeInTheDocument();
+ expect(screen.queryByText(/free/i)).toBeNull();
+ expect(screen.getByText("Found")).toBeInTheDocument();
+ expect(screen.getByText("In env")).toBeInTheDocument();
+ });
+
+ it("selects a source and writes with it", () => {
+ const props = renderSheet();
+ fireEvent.click(screen.getByRole("radio", { name: /OpenAI key/ }));
+ expect(props.onSelect).toHaveBeenCalledWith("openai");
+ fireEvent.click(screen.getByRole("button", { name: "Write the docs" }));
+ expect(props.onWrite).toHaveBeenCalled();
+ });
+
+ it("shows the key's price before anything runs", () => {
+ renderSheet({ selectedId: "openai", estimate: { pages: 46, costText: "$0.42", loading: false } });
+ expect(screen.getByText(/About \$0\.42 with this key/)).toBeInTheDocument();
+ });
+
+ it("links out for hosted instead of offering it as a radio", () => {
+ renderSheet();
+ expect(screen.getAllByRole("radio")).toHaveLength(5);
+ const hosted = screen.getByRole("link", { name: /Hosted repowise/ });
+ expect(hosted).toHaveAttribute("href", "https://example.test/hosted");
+ });
+
+ it("expands the key entry for Paste a key and waits for a key", () => {
+ renderSheet({
+ selectedId: PASTE_SOURCE_ID,
+ keyProviders: [{ id: "anthropic", name: "Anthropic", models: [], default_model: "", configured: false }],
+ });
+ expect(screen.getByLabelText("Anthropic API key")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Write the docs" })).toBeDisabled();
+ });
+});
diff --git a/packages/ui/src/docs/docs-mode-badge.tsx b/packages/ui/src/docs/docs-mode-badge.tsx
index d8e34b3ee..e8fc62509 100644
--- a/packages/ui/src/docs/docs-mode-badge.tsx
+++ b/packages/ui/src/docs/docs-mode-badge.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Cog } from "lucide-react";
+import { Cog, Sparkles } from "lucide-react";
import { cn } from "../lib/cn";
/** How a repo's wiki stands, from the repos API `docs_mode`. `deterministic`
@@ -8,29 +8,63 @@ import { cn } from "../lib/cn";
* a model has written every one of them. */
export type DocsMode = "none" | "deterministic" | "llm";
+const TITLE =
+ "The subsystem pages are still generated from code structure. Write them with a model for the how and why.";
+
+const CHIP = cn(
+ "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider",
+ "border-[var(--color-info)]/35 bg-[var(--color-info)]/10 text-[var(--color-info)]",
+);
+
/** A small chip for a repo header, shown only while the subsystem pages are
* unwritten. A fully written wiki (`llm`) and an undocumented repo (`none`)
* both render nothing: a badge every repo carries says nothing, so the header
- * stays quiet unless there is prose still to write. */
+ * stays quiet unless there is prose still to write. With `onAction` the chip
+ * becomes a button that offers a model (`actionLabel`). */
export function DocsModeBadge({
mode,
className,
+ onAction,
+ label = "Subsystem pages unwritten",
+ actionLabel = "Write with a model",
+ title = TITLE,
}: {
mode: DocsMode;
className?: string;
+ onAction?: () => void;
+ label?: string;
+ actionLabel?: string;
+ /** Hover text. */
+ title?: string;
}) {
if (mode !== "deterministic") return null;
+ if (!onAction) {
+ return (
+ <span title={title} className={cn(CHIP, className)}>
+ <Cog className="h-2.5 w-2.5" />
+ {label}
+ </span>
+ );
+ }
return (
- <span
- title="The subsystem pages are still generated from code structure. Write them with a model for the how and why."
+ <button
+ type="button"
+ title={title}
+ onClick={onAction}
className={cn(
- "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider",
- "border-[var(--color-info)]/35 bg-[var(--color-info)]/10 text-[var(--color-info)]",
+ "group inline-flex items-center gap-2 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-model)]",
className,
)}
>
- <Cog className="h-2.5 w-2.5" />
- Subsystem pages unwritten
- </span>
+ {/* Phones keep only the action: the chip's wording is in the title. */}
+ <span className={cn(CHIP, "hidden sm:inline-flex")}>
+ <Cog className="h-2.5 w-2.5" />
+ {label}
+ </span>
+ <span className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-model)] group-hover:underline">
+ <Sparkles aria-hidden className="h-3 w-3" />
+ {actionLabel}
+ </span>
+ </button>
);
}
diff --git a/packages/ui/src/settings/index.ts b/packages/ui/src/settings/index.ts
index bf082ea09..5e681460a 100644
--- a/packages/ui/src/settings/index.ts
+++ b/packages/ui/src/settings/index.ts
@@ -2,3 +2,5 @@ export * from "./general-form";
export * from "./provider-settings";
export * from "./settings-primitives";
export * from "./model-combobox";
+export * from "./model-sources";
+export * from "./model-upgrade-sheet";
diff --git a/packages/ui/src/settings/model-sources.ts b/packages/ui/src/settings/model-sources.ts
new file mode 100644
index 000000000..911c7373f
--- /dev/null
+++ b/packages/ui/src/settings/model-sources.ts
@@ -0,0 +1,112 @@
+/** What on this machine makes a provider usable, from the providers API
+ * `detected`: a signed-in agent CLI, a key in the env or the repo's
+ * `.repowise/.env`, or a key stored on the server. */
+export type ModelSourceDetection = "signed_in" | "env" | "saved";
+
+/** The provider fields the source list reads. */
+export interface ModelSourceProvider {
+ id: string;
+ name: string;
+ requires_key?: boolean;
+ /** A model that runs on this machine (not an agent CLI). */
+ local_model?: boolean;
+ detected?: ModelSourceDetection | null;
+}
+
+export type ModelSourceKind = "cli" | "key" | "local" | "paste" | "hosted";
+
+/** One row of the model upgrade sheet. `id` is the provider id for the
+ * provider rows, and `PASTE_SOURCE_ID` / `HOSTED_SOURCE_ID` for the two
+ * fixed rows. */
+export interface ModelSource {
+ id: string;
+ kind: ModelSourceKind;
+ /** The provider this row makes the repo's choice; null for paste and hosted. */
+ providerId: string | null;
+ /** Display name without the catalog's "(Local CLI)" suffix. */
+ name: string;
+ detected: ModelSourceDetection | null;
+}
+
+export const PASTE_SOURCE_ID = "paste";
+export const HOSTED_SOURCE_ID = "hosted";
+
+/** "Claude Code (Local CLI)" -> "Claude Code", "Ollama (Local)" -> "Ollama". */
+function shortName(name: string): string {
+ return name.replace(/\s*\((?:Local CLI|Local)\)\s*$/, "");
+}
+
+function providerSource(
+ provider: ModelSourceProvider,
+ kind: ModelSourceKind,
+): ModelSource {
+ return {
+ id: provider.id,
+ kind,
+ providerId: provider.id,
+ name: shortName(provider.name),
+ detected: provider.detected ?? null,
+ };
+}
+
+const PASTE_SOURCE: ModelSource = {
+ id: PASTE_SOURCE_ID,
+ kind: "paste",
+ providerId: null,
+ name: "",
+ detected: null,
+};
+
+const HOSTED_SOURCE: ModelSource = {
+ id: HOSTED_SOURCE_ID,
+ kind: "hosted",
+ providerId: null,
+ name: "",
+ detected: null,
+};
+
+/**
+ * The sheet's rows, in order: signed-in agent CLIs, then providers with a key
+ * already on this machine (catalog order within each), then the local model,
+ * then "Paste a key", then hosted. The local model is the first catalog
+ * provider flagged `local_model`; other keyless providers (proxies, local
+ * OpenAI-compatible servers) stay in Settings, where their endpoint is set. Providers with nothing set up are left out;
+ * Settings lists every provider.
+ */
+export function orderModelSources(providers: readonly ModelSourceProvider[]): ModelSource[] {
+ const signedIn = providers
+ .filter((p) => p.detected === "signed_in")
+ .map((p) => providerSource(p, "cli"));
+ const keyed = providers
+ .filter((p) => p.detected === "env" || p.detected === "saved")
+ .map((p) => providerSource(p, "key"));
+ const local = providers.find((p) => p.local_model === true);
+ return [
+ ...signedIn,
+ ...keyed,
+ ...(local ? [providerSource(local, "local")] : []),
+ PASTE_SOURCE,
+ HOSTED_SOURCE,
+ ];
+}
+
+/**
+ * The row selected when the sheet opens: the repo's current provider when it
+ * is one of the rows, else the first detected source, else "Paste a key".
+ * Never the local model on its own (it may not be running) and never hosted.
+ */
+export function defaultModelSource(
+ sources: readonly ModelSource[],
+ activeProvider: string | null | undefined,
+): string {
+ const active = activeProvider
+ ? sources.find((s) => s.providerId === activeProvider)
+ : undefined;
+ if (active) return active.id;
+ return sources.find((s) => s.detected !== null)?.id ?? PASTE_SOURCE_ID;
+}
+
+/** Providers "Paste a key" offers: every one that takes an API key. */
+export function pasteKeyProviders<P extends ModelSourceProvider>(providers: readonly P[]): P[] {
+ return providers.filter((p) => p.requires_key !== false);
+}
diff --git a/packages/ui/src/settings/model-upgrade-sheet.tsx b/packages/ui/src/settings/model-upgrade-sheet.tsx
new file mode 100644
index 000000000..82b7c1216
--- /dev/null
+++ b/packages/ui/src/settings/model-upgrade-sheet.tsx
@@ -0,0 +1,384 @@
+"use client";
+
+import { useEffect, useId, useState } from "react";
+import { ArrowUpRight } from "lucide-react";
+import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
+import { Spinner } from "../ui/spinner";
+import { cn } from "../lib/cn";
+import {
+ ProviderKeyEntry,
+ type ProviderOption,
+ type ProviderSettingsLabels,
+} from "./provider-settings";
+import { PASTE_SOURCE_ID, type ModelSource, type ModelSourceDetection } from "./model-sources";
+
+export interface ModelUpgradeSheetLabels {
+ eyebrow: string;
+ title: string;
+ description: string;
+ close: string;
+ sourcesLabel: string;
+ cliSource: (name: string) => string;
+ keySource: (name: string) => string;
+ localSource: (name: string) => string;
+ pasteSource: string;
+ hostedSource: string;
+ hostedNote: string;
+ hostedAction: string;
+ detected: Record<ModelSourceDetection, string>;
+ pasteProvider: string;
+ pages: (count: number) => string;
+ counting: string;
+ signedInNote: (name: string) => string;
+ costNote: (cost: string) => string;
+ pricing: string;
+ keyNote: string;
+ localNote: string;
+ pasteNote: string;
+ write: string;
+ sameAs: string;
+}
+
+export const DEFAULT_MODEL_UPGRADE_SHEET_LABELS: ModelUpgradeSheetLabels = {
+ eyebrow: "Add a model",
+ title: "Write this documentation with a model",
+ description:
+ "Pages that explain how and why, chat in this dashboard, and written answers for your agent.",
+ close: "Close",
+ sourcesLabel: "Where the model comes from",
+ cliSource: (name) => `${name} sign-in`,
+ keySource: (name) => `${name} key`,
+ localSource: (name) => `Local model (${name})`,
+ pasteSource: "Paste a key",
+ hostedSource: "Hosted repowise",
+ hostedNote: "model included, no key",
+ hostedAction: "See plans",
+ detected: { signed_in: "Found", env: "In env", saved: "Saved" },
+ pasteProvider: "Provider",
+ pages: (count) => `${count} ${count === 1 ? "page" : "pages"} to write`,
+ counting: "Counting pages",
+ signedInNote: (name) => `Uses your ${name} sign-in.`,
+ costNote: (cost) => `About ${cost} with this key, shown before anything runs.`,
+ pricing: "Pricing with this key",
+ keyNote: "The price shows before anything runs.",
+ localNote: "Runs on your machine. Start Ollama first.",
+ pasteNote: "With a key, the price shows here first.",
+ write: "Write the docs",
+ sameAs: "Same as",
+};
+
+export interface ModelUpgradeEstimate {
+ /** Pages the run writes; null until counted. */
+ pages: number | null;
+ /** Formatted price for the selected key source; null when unpriced. */
+ costText: string | null;
+ loading: boolean;
+}
+
+export interface ModelUpgradeSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Rows in display order (see `orderModelSources`). */
+ sources: ModelSource[];
+ /** The source list is still loading. */
+ loading?: boolean;
+ selectedId: string;
+ onSelect: (id: string) => void;
+ /** Providers "Paste a key" offers. */
+ keyProviders: ProviderOption[];
+ /** Saves a pasted key; reject to keep the draft. */
+ onAddKey: (providerId: string, apiKey: string) => Promise<void> | void;
+ estimate: ModelUpgradeEstimate;
+ onWrite: () => void;
+ writing?: boolean;
+ /** Where the hosted row links to (opens in a new tab). */
+ hostedHref: string;
+ labels?: Partial<ModelUpgradeSheetLabels>;
+ /** Wording for the pasted-key field. */
+ keyLabels?: Partial<ProviderSettingsLabels>;
+}
+
+/**
+ * One sheet that adds a model to a repo indexed without one: what a model
+ * adds, where it can come from on this machine, what the run costs, and the
+ * action that writes the docs. Data and callbacks only; the host sets the
+ * provider and runs generation. Plum (`--color-model`) is its only accent.
+ */
+export function ModelUpgradeSheet({
+ open,
+ onOpenChange,
+ labels: labelOverrides,
+ ...props
+}: ModelUpgradeSheetProps) {
+ const labels = { ...DEFAULT_MODEL_UPGRADE_SHEET_LABELS, ...labelOverrides };
+ const selected = props.sources.find((s) => s.id === props.selectedId);
+ const canWrite = Boolean(selected?.providerId) && !props.writing && !props.loading;
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ closeLabel={labels.close}
+ aria-describedby={undefined}
+ // Full width on a phone, a side sheet from `sm` up.
+ className="w-full gap-3 overflow-y-auto p-4 sm:w-[380px] sm:p-5"
+ >
+ <SheetHeading labels={labels} />
+ <SourceList {...props} labels={labels} />
+ <EstimateBlock selected={selected} estimate={props.estimate} labels={labels} />
+ <button
+ type="button"
+ onClick={props.onWrite}
+ disabled={!canWrite}
+ className={cn(
+ "inline-flex h-9 items-center justify-center gap-2 rounded-md px-4 text-sm font-semibold transition-colors",
+ "bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)]",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-model)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-bg-surface)]",
+ "disabled:pointer-events-none disabled:opacity-50",
+ )}
+ >
+ {props.writing && <Spinner size="sm" />}
+ {labels.write}
+ </button>
+ <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ {labels.sameAs} <span className="font-mono">repowise generate</span>
+ </p>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function SheetHeading({ labels }: { labels: ModelUpgradeSheetLabels }) {
+ return (
+ <div className="space-y-1.5 pr-8">
+ <p className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-model)]">
+ {labels.eyebrow}
+ </p>
+ <SheetTitle className="text-[15px] font-semibold leading-snug">{labels.title}</SheetTitle>
+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {labels.description}
+ </p>
+ </div>
+ );
+}
+
+type SourceListProps = Omit<ModelUpgradeSheetProps, "open" | "onOpenChange" | "labels"> & {
+ labels: ModelUpgradeSheetLabels;
+};
+
+function SourceList({ labels, ...props }: SourceListProps) {
+ const name = useId();
+ if (props.loading) {
+ return (
+ <div className="flex justify-center py-6">
+ <Spinner size="sm" />
+ </div>
+ );
+ }
+ const choices = props.sources.filter((s) => s.kind !== "hosted");
+ const hosted = props.sources.some((s) => s.kind === "hosted");
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div role="radiogroup" aria-label={labels.sourcesLabel} className="flex flex-col gap-1.5">
+ {choices.map((source) => (
+ <SourceRow
+ key={source.id}
+ name={name}
+ source={source}
+ checked={source.id === props.selectedId}
+ onSelect={props.onSelect}
+ labels={labels}
+ />
+ ))}
+ </div>
+ {props.selectedId === PASTE_SOURCE_ID && (
+ <PasteKey
+ providers={props.keyProviders}
+ onAddKey={props.onAddKey}
+ labels={labels}
+ {...(props.keyLabels ? { keyLabels: props.keyLabels } : {})}
+ />
+ )}
+ {hosted && <HostedRow href={props.hostedHref} labels={labels} />}
+ </div>
+ );
+}
+
+const ROW =
+ "grid grid-cols-[14px_minmax(0,1fr)_auto] items-center gap-2.5 rounded-md border px-3 py-2 text-[13px] transition-colors";
+
+function sourceLabel(source: ModelSource, labels: ModelUpgradeSheetLabels): string {
+ if (source.kind === "cli") return labels.cliSource(source.name);
+ if (source.kind === "key") return labels.keySource(source.name);
+ if (source.kind === "local") return labels.localSource(source.name);
+ return labels.pasteSource;
+}
+
+function SourceRow({
+ name,
+ source,
+ checked,
+ onSelect,
+ labels,
+}: {
+ name: string;
+ source: ModelSource;
+ checked: boolean;
+ onSelect: (id: string) => void;
+ labels: ModelUpgradeSheetLabels;
+}) {
+ return (
+ <label
+ className={cn(
+ ROW,
+ "cursor-pointer bg-[var(--color-bg-elevated)] has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-[var(--color-model)]",
+ checked
+ ? "border-[var(--color-model)]"
+ : "border-[var(--color-border-default)] hover:border-[var(--color-border-hover)]",
+ )}
+ >
+ <input
+ type="radio"
+ name={name}
+ value={source.id}
+ checked={checked}
+ onChange={() => onSelect(source.id)}
+ className="sr-only"
+ />
+ <span
+ aria-hidden
+ className={cn(
+ "h-3 w-3 rounded-full",
+ checked
+ ? "border-4 border-[var(--color-model)]"
+ : "border-[1.5px] border-[var(--color-border-hover)]",
+ )}
+ />
+ <span className="min-w-0 truncate text-[var(--color-text-primary)]">
+ {sourceLabel(source, labels)}
+ </span>
+ {source.detected ? (
+ <span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {labels.detected[source.detected]}
+ </span>
+ ) : (
+ <span aria-hidden />
+ )}
+ </label>
+ );
+}
+
+function HostedRow({ href, labels }: { href: string; labels: ModelUpgradeSheetLabels }) {
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(
+ ROW,
+ "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] hover:border-[var(--color-border-hover)]",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-model)]",
+ )}
+ >
+ <ArrowUpRight aria-hidden className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <span className="min-w-0 text-[var(--color-text-primary)]">
+ {labels.hostedSource}{" "}
+ <span className="text-[var(--color-text-tertiary)]">{labels.hostedNote}</span>
+ </span>
+ <span className="text-[11px] font-medium text-[var(--color-model)]">{labels.hostedAction}</span>
+ </a>
+ );
+}
+
+function PasteKey({
+ providers,
+ onAddKey,
+ labels,
+ keyLabels,
+}: {
+ providers: ProviderOption[];
+ onAddKey: ModelUpgradeSheetProps["onAddKey"];
+ labels: ModelUpgradeSheetLabels;
+ keyLabels?: Partial<ProviderSettingsLabels>;
+}) {
+ const selectId = useId();
+ const [providerId, setProviderId] = useState(providers[0]?.id ?? "");
+ useEffect(() => {
+ if (!providers.some((p) => p.id === providerId)) setProviderId(providers[0]?.id ?? "");
+ }, [providers, providerId]);
+ const provider = providers.find((p) => p.id === providerId);
+ if (!provider) return null;
+ return (
+ <div className="rounded-md border border-[var(--color-border-default)] p-3">
+ <label
+ htmlFor={selectId}
+ className="mb-1.5 block text-[11px] font-medium text-[var(--color-text-secondary)]"
+ >
+ {labels.pasteProvider}
+ </label>
+ <select
+ id={selectId}
+ value={providerId}
+ onChange={(e) => setProviderId(e.target.value)}
+ className="h-8 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-2 text-xs text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-model)]"
+ >
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.name}
+ </option>
+ ))}
+ </select>
+ <ProviderKeyEntry
+ key={provider.id}
+ provider={provider}
+ onAddKey={onAddKey}
+ {...(keyLabels ? { labels: keyLabels } : {})}
+ />
+ </div>
+ );
+}
+
+function estimateNote(
+ selected: ModelSource | undefined,
+ estimate: ModelUpgradeEstimate,
+ labels: ModelUpgradeSheetLabels,
+): string | null {
+ switch (selected?.kind) {
+ case "cli":
+ return labels.signedInNote(selected.name);
+ case "key":
+ if (estimate.costText) return labels.costNote(estimate.costText);
+ return estimate.loading ? labels.pricing : labels.keyNote;
+ case "local":
+ return labels.localNote;
+ case "paste":
+ return labels.pasteNote;
+ default:
+ return null;
+ }
+}
+
+function EstimateBlock({
+ selected,
+ estimate,
+ labels,
+}: {
+ selected: ModelSource | undefined;
+ estimate: ModelUpgradeEstimate;
+ labels: ModelUpgradeSheetLabels;
+}) {
+ const note = estimateNote(selected, estimate, labels);
+ const count =
+ estimate.pages != null ? labels.pages(estimate.pages) : estimate.loading ? labels.counting : null;
+ return (
+ <div
+ aria-live="polite"
+ className="space-y-1 border-t border-[var(--color-border-default)] pt-3 text-xs text-[var(--color-text-secondary)]"
+ >
+ {count && (
+ <p className="font-mono text-[11.5px] text-[var(--color-text-primary)]">{count}</p>
+ )}
+ {note && <p>{note}</p>}
+ </div>
+ );
+}
diff --git a/packages/ui/src/settings/provider-settings.tsx b/packages/ui/src/settings/provider-settings.tsx
index 721456b0d..e0c451e0d 100644
--- a/packages/ui/src/settings/provider-settings.tsx
+++ b/packages/ui/src/settings/provider-settings.tsx
@@ -540,6 +540,22 @@ function KeyEditor({
);
}
+/** One provider's key field on its own, for a surface that offers a key
+ * without the full provider list. Escape and the close button clear it. */
+export function ProviderKeyEntry({
+ provider,
+ onAddKey,
+ labels: labelOverrides,
+}: {
+ provider: ProviderOption;
+ onAddKey: ProviderSettingsProps["onAddKey"];
+ labels?: Partial<ProviderSettingsLabels>;
+}) {
+ const keys = useKeyEditor(provider.id, onAddKey, () => undefined);
+ const labels = { ...DEFAULT_PROVIDER_SETTINGS_LABELS, ...labelOverrides };
+ return <KeyEditor provider={provider} keys={keys} labels={labels} />;
+}
+
function ValidationLine({
validation,
labels,
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index c79460de0..dc62d34c0 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -1310,7 +1310,42 @@
"filesDescription": "Every file, grouped into the communities it depends on most, with a band for each strong link between communities. Hover or select a file to see exactly what it imports and what imports it."
}
},
+ "modelUpgrade": {
+ "eyebrow": "Add a model",
+ "title": "Write this documentation with a model",
+ "description": "Pages that explain how and why, chat in this dashboard, and written answers for your agent.",
+ "close": "Close",
+ "sourcesLabel": "Where the model comes from",
+ "cliSource": "{name} sign-in",
+ "keySource": "{name} key",
+ "localSource": "Local model ({name})",
+ "pasteSource": "Paste a key",
+ "hostedSource": "Hosted repowise",
+ "hostedNote": "model included, no key",
+ "hostedAction": "See plans",
+ "detected": {
+ "signedIn": "Found",
+ "env": "In env",
+ "saved": "Saved"
+ },
+ "pasteProvider": "Provider",
+ "pages": "{count, plural, one {# page to write} other {# pages to write}}",
+ "counting": "Counting pages",
+ "signedInNote": "Uses your {name} sign-in.",
+ "costNote": "About {cost} with this key, shown before anything runs.",
+ "pricing": "Pricing with this key",
+ "keyNote": "The price shows before anything runs.",
+ "localNote": "Runs on your machine. Start Ollama first.",
+ "pasteNote": "With a key, the price shows here first.",
+ "write": "Write the docs",
+ "sameAs": "Same as",
+ "startFailed": "Couldn't start writing the docs",
+ "badgeLabel": "Subsystem pages unwritten",
+ "badgeAction": "Write with a model",
+ "badgeTitle": "The subsystem pages are still generated from code structure. Write them with a model for the how and why."
+ },
"chat": {
+ "addModel": "Add a model",
"noProvider": "No chat provider is configured. Add an API key in <link>settings</link> to start asking questions.",
"noProviderShort": "No chat provider is configured. Add an API key in <link>settings</link>.",
"unverifiedFigure": "Not found in this turn's tool results",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index cad8b2003..8d83fd866 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -1310,7 +1310,42 @@
"filesDescription": "每个文件按它最依赖的社区分组,社区之间的每条强连接用一条带表示。把鼠标悬停或选中某个文件,即可看到它导入了什么、又被谁导入。"
}
},
+ "modelUpgrade": {
+ "eyebrow": "添加模型",
+ "title": "用模型撰写这份文档",
+ "description": "讲清原理与缘由的页面、在此仪表盘中对话,以及为你的智能体写好的回答。",
+ "close": "关闭",
+ "sourcesLabel": "模型来源",
+ "cliSource": "{name} 登录",
+ "keySource": "{name} 密钥",
+ "localSource": "本地模型({name})",
+ "pasteSource": "粘贴密钥",
+ "hostedSource": "托管版 repowise",
+ "hostedNote": "已含模型,无需密钥",
+ "hostedAction": "查看方案",
+ "detected": {
+ "signedIn": "已找到",
+ "env": "环境变量中",
+ "saved": "已保存"
+ },
+ "pasteProvider": "提供商",
+ "pages": "{count, plural, other {需撰写 # 个页面}}",
+ "counting": "正在统计页面",
+ "signedInNote": "使用你的 {name} 登录。",
+ "costNote": "使用此密钥约需 {cost},运行前会先显示。",
+ "pricing": "正在按此密钥估价",
+ "keyNote": "运行前会先显示价格。",
+ "localNote": "在你的机器上运行。请先启动 Ollama。",
+ "pasteNote": "有了密钥,价格会先在这里显示。",
+ "write": "撰写文档",
+ "sameAs": "等同于",
+ "startFailed": "无法开始撰写文档",
+ "badgeLabel": "子系统页面未撰写",
+ "badgeAction": "用模型撰写",
+ "badgeTitle": "子系统页面仍由代码结构生成。用模型撰写,讲清原理与缘由。"
+ },
"chat": {
+ "addModel": "添加模型",
"noProvider": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥,然后就可以开始提问了。",
"noProviderShort": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥。",
"unverifiedFigure": "未在本轮工具结果中找到",
diff --git a/packages/web/src/components/chat/chat-interface.test.tsx b/packages/web/src/components/chat/chat-interface.test.tsx
index 9738678e9..8b7892ea8 100644
--- a/packages/web/src/components/chat/chat-interface.test.tsx
+++ b/packages/web/src/components/chat/chat-interface.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import React from "react";
-import { render, waitFor } from "@testing-library/react";
+import { fireEvent, render, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ChatInterface } from "./chat-interface";
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
compare: null as string | null,
activeConversation: null as string | null,
shellProps: null as Record<string, unknown> | null,
+ openSheet: vi.fn(),
}));
vi.mock("next/navigation", () => ({
@@ -31,6 +32,9 @@ vi.mock("next/navigation", () => ({
vi.mock("swr", () => ({ default: () => ({ data: undefined }) }));
vi.mock("next/link", () => ({ default: ({ children }: { children: React.ReactNode }) => <>{children}</> }));
vi.mock("@repowise-dev/ui/chat/chat-interface", () => ({ ChatInterface: (props: Record<string, unknown>) => { mocks.shellProps = props; return <div />; } }));
+vi.mock("@/components/model-upgrade/model-upgrade", () => ({
+ useModelUpgrade: () => ({ openSheet: mocks.openSheet, sheet: <div data-testid="model-sheet" /> }),
+}));
vi.mock("./model-selector", () => ({ ModelSelector: () => <div /> }));
vi.mock("./conversation-history", () => ({ ConversationHistory: () => <div /> }));
vi.mock("./repository-chat-provider", () => ({
@@ -132,4 +136,13 @@ describe("chat route conversation lifecycle", () => {
source: "static",
});
});
+
+ it("offers a model from the no-provider state, with the sheet mounted beside the composer", async () => {
+ const { container } = render(<ChatInterface repoId="r1" />);
+ await waitFor(() => expect(mocks.shellProps).not.toBeNull());
+ expect(container.querySelector('[data-testid="model-sheet"]')).not.toBeNull();
+ const reason = render(mocks.shellProps?.sendDisabledReason as React.ReactElement);
+ fireEvent.click(reason.getByRole("button", { name: "Add a model" }));
+ expect(mocks.openSheet).toHaveBeenCalledOnce();
+ });
});
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index 77099ab48..8f98273c1 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -2,7 +2,6 @@
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import useSWR from "swr";
-import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { ChatInterface as ChatInterfaceShell } from "@repowise-dev/ui/chat/chat-interface";
import { getArtifactSourceTarget, useChatDraft } from "@repowise-dev/ui/chat";
@@ -14,6 +13,8 @@ import { ModelSelector } from "./model-selector";
import { ConversationHistory } from "./conversation-history";
import { useRepositoryChat } from "./repository-chat-provider";
import { useTranslations } from "next-intl";
+import { NoProviderReason } from "./no-provider-reason";
+import { useModelUpgrade } from "@/components/model-upgrade/model-upgrade";
interface ChatInterfaceProps {
repoId: string;
@@ -79,6 +80,9 @@ export function ChatInterface({
() => getProviders(repoId),
{ revalidateOnFocus: false },
);
+ // Mounted here, not in the composer's reason: the reason unmounts as soon
+ // as a provider is set, and the run's confirm and progress must outlive it.
+ const upgrade = useModelUpgrade(repoId);
const anyConfigured =
providers === undefined || providers.providers.some((p) => p.configured);
@@ -214,20 +218,7 @@ export function ChatInterface({
artifactOverrides={artifactOverrides}
unverifiedFigureCopy={{ flag: t("unverifiedFigure"), note: t("unverifiedFiguresNote") }}
sendDisabled={!anyConfigured}
- sendDisabledReason={
- <span>
- {t.rich("noProvider", {
- link: (chunks) => (
- <Link
- href="/settings"
- className="text-[var(--color-accent-primary)] hover:underline"
- >
- {chunks}
- </Link>
- ),
- })}
- </span>
- }
+ sendDisabledReason={<NoProviderReason message="noProvider" onAddModel={upgrade.openSheet} />}
historySlot={
<div className="lg:hidden">
<ConversationHistory
@@ -240,6 +231,7 @@ export function ChatInterface({
}
/>
</div>
+ {upgrade.sheet}
</div>
);
}
diff --git a/packages/web/src/components/chat/no-provider-reason.tsx b/packages/web/src/components/chat/no-provider-reason.tsx
new file mode 100644
index 000000000..36fe7a391
--- /dev/null
+++ b/packages/web/src/components/chat/no-provider-reason.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import Link from "next/link";
+import { useTranslations } from "next-intl";
+
+/** The composer's no-provider state: "Add a model" opens the model sheet
+ * (mounted by the chat surface, so it outlives this reason), and the
+ * Settings link stays as the longer way round. */
+export function NoProviderReason({
+ message,
+ onAddModel,
+}: {
+ /** `noProvider` on the full chat page, `noProviderShort` in the dock. */
+ message: "noProvider" | "noProviderShort";
+ onAddModel: () => void;
+}) {
+ const t = useTranslations("chat");
+ return (
+ <span>
+ <button
+ type="button"
+ onClick={onAddModel}
+ className="mr-2 inline-flex items-center rounded-md bg-[var(--color-model)] px-2 py-0.5 text-xs font-semibold text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-model)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-bg-surface)]"
+ >
+ {t("addModel")}
+ </button>
+ {t.rich(message, {
+ link: (chunks) => (
+ <Link
+ href="/settings"
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ {chunks}
+ </Link>
+ ),
+ })}
+ </span>
+ );
+}
diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsx
index 5014d11f6..dc0d6ed77 100644
--- a/packages/web/src/components/chat/repository-chat-dock.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.tsx
@@ -1,7 +1,6 @@
"use client";
import useSWR from "swr";
-import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { CHAT_SHORTCUT_HINT, ChatDock, getArtifactSourceTarget } from "@repowise-dev/ui/chat";
@@ -14,6 +13,8 @@ import { useRepositoryChat } from "./repository-chat-provider";
import { useChatDockHidden } from "./use-chat-dock-hidden";
import { config, setChatDockHidden } from "@/lib/config";
import { useTranslations } from "next-intl";
+import { NoProviderReason } from "./no-provider-reason";
+import { useModelUpgrade } from "@/components/model-upgrade/model-upgrade";
// Sigma's worst-case bottom-right stack is ~197px tall (layout status plus
// five controls and spacing). Keep a small measured clearance above it.
@@ -75,6 +76,8 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
() => getProviders(chat.repoId),
{ revalidateOnFocus: false },
);
+ // Outside the composer's reason, which unmounts once a provider is set.
+ const upgrade = useModelUpgrade(chat.repoId);
const anyConfigured =
providers === undefined || providers.providers.some((provider) => provider.configured);
const collisionInset = getRepositoryDockCollisionInset(
@@ -83,6 +86,7 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
);
return (
+ <>
<ChatDock
storageKey={`repowise:chat-dock:${chat.repoId}:${chat.conversationId ?? "new"}`}
repoId={chat.repoId}
@@ -122,20 +126,7 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
onDismiss={() => setChatDockHidden(true)}
unverifiedFigureCopy={{ flag: t("unverifiedFigure"), note: t("unverifiedFiguresNote") }}
sendDisabled={!anyConfigured}
- sendDisabledReason={
- <span>
- {t.rich("noProviderShort", {
- link: (chunks) => (
- <Link
- href="/settings"
- className="text-[var(--color-accent-primary)] hover:underline"
- >
- {chunks}
- </Link>
- ),
- })}
- </span>
- }
+ sendDisabledReason={<NoProviderReason message="noProviderShort" onAddModel={upgrade.openSheet} />}
modelSelectorSlot={<ModelSelector repoId={chat.repoId} activeProvider={chat.selectedProvider} activeModel={chat.selectedModel} onSelect={chat.selectModel} />}
historySlot={
<ConversationHistory
@@ -146,5 +137,7 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
/>
}
/>
+ {upgrade.sheet}
+ </>
);
}
diff --git a/packages/web/src/components/docs/bulk-generate-button.tsx b/packages/web/src/components/docs/bulk-generate-button.tsx
index 6dd775ca8..571deb2ea 100644
--- a/packages/web/src/components/docs/bulk-generate-button.tsx
+++ b/packages/web/src/components/docs/bulk-generate-button.tsx
@@ -2,14 +2,8 @@
import { Sparkles } from "lucide-react";
import { Button } from "@repowise-dev/ui/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@repowise-dev/ui/ui/dialog";
-import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
import { BulkGenerateConfirm } from "./bulk-generate-confirm";
+import { BulkGenerateProgress } from "./bulk-generate-progress";
import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";
import { useTranslations } from "next-intl";
@@ -49,33 +43,10 @@ export function BulkGenerateButton({
title={t("bulk.title")}
/>
- <Dialog
- open={bulk.jobId != null}
- onOpenChange={(v) => {
- if (!v) bulk.clearJob();
- }}
- >
- <DialogContent className="sm:max-w-md">
- <DialogHeader>
- <DialogTitle>{t("bulk.writing")}</DialogTitle>
- </DialogHeader>
- {bulk.jobId != null && (
- <GenerationProgressWrapper
- key={bulk.jobId}
- jobId={bulk.jobId}
- onDone={(outcome) => {
- bulk.settle(outcome);
- onGenerated?.();
- }}
- onRetry={() => {
- bulk.clearJob();
- bulk.open();
- }}
- onDismiss={bulk.clearJob}
- />
- )}
- </DialogContent>
- </Dialog>
+ <BulkGenerateProgress
+ flow={bulk}
+ {...(onGenerated ? { onGenerated } : {})}
+ />
</>
);
}
diff --git a/packages/web/src/components/docs/bulk-generate-progress.tsx b/packages/web/src/components/docs/bulk-generate-progress.tsx
new file mode 100644
index 000000000..117f321a6
--- /dev/null
+++ b/packages/web/src/components/docs/bulk-generate-progress.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@repowise-dev/ui/ui/dialog";
+import { GenerationProgressWrapper } from "@/components/jobs/generation-progress-wrapper";
+import { type useBulkGenerate } from "@/lib/hooks/use-bulk-generate";
+import { useTranslations } from "next-intl";
+
+/** The progress dialog of a `useBulkGenerate` run: open while its job is
+ * watched, retry reopens the confirm. */
+export function BulkGenerateProgress({
+ flow,
+ onGenerated,
+}: {
+ flow: ReturnType<typeof useBulkGenerate>;
+ /** Called once a run completes so the host can refresh what it shows. */
+ onGenerated?: () => void;
+}) {
+ const t = useTranslations("docs");
+ return (
+ <Dialog
+ open={flow.jobId != null}
+ onOpenChange={(v) => {
+ if (!v) flow.clearJob();
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t("bulk.writing")}</DialogTitle>
+ </DialogHeader>
+ {flow.jobId != null && (
+ <GenerationProgressWrapper
+ key={flow.jobId}
+ jobId={flow.jobId}
+ onDone={(outcome) => {
+ flow.settle(outcome);
+ onGenerated?.();
+ }}
+ onRetry={() => {
+ flow.clearJob();
+ flow.open();
+ }}
+ onDismiss={flow.clearJob}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/web/src/components/layout/repo-breadcrumb.tsx b/packages/web/src/components/layout/repo-breadcrumb.tsx
index fcdf0f5ac..67158a2a9 100644
--- a/packages/web/src/components/layout/repo-breadcrumb.tsx
+++ b/packages/web/src/components/layout/repo-breadcrumb.tsx
@@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
-import { usePathname } from "next/navigation";
+import { usePathname, useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { MessageSquare } from "lucide-react";
import { Breadcrumb } from "@repowise-dev/ui/shared/breadcrumb";
@@ -10,6 +10,7 @@ import { DocsModeBadge, type DocsMode } from "@repowise-dev/ui/docs/docs-mode-ba
import { getRepoBreadcrumbSegmentLabel, SEGMENT_MESSAGE_KEYS } from "./repo-breadcrumb-label";
import { showsRouteBreadcrumb } from "./repo-breadcrumb-route";
import { commitsViewHref } from "@/lib/changes";
+import { useModelUpgrade } from "@/components/model-upgrade/model-upgrade";
export function RepoBreadcrumb({
repoName,
@@ -65,7 +66,7 @@ export function RepoBreadcrumb({
<div className="flex items-center justify-between gap-3 px-4 sm:px-6 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
{showCrumbs ? <Breadcrumb segments={segments} LinkComponent={Link} /> : <span />}
<div className="flex shrink-0 items-center gap-3">
- {showBadge && <DocsModeBadge mode={docsMode} />}
+ {showBadge && <DocsModeAction repoId={repoId} docsMode={docsMode} />}
{!onChatPage && (
<Link
href={`/repos/${repoId}/chat`}
@@ -79,3 +80,23 @@ export function RepoBreadcrumb({
</div>
);
}
+
+/** The docs-mode chip as the way in to a model: it opens the model sheet,
+ * and a finished run refreshes the layout so the chip retires. */
+function DocsModeAction({ repoId, docsMode }: { repoId: string; docsMode: DocsMode }) {
+ const t = useTranslations("modelUpgrade");
+ const router = useRouter();
+ const upgrade = useModelUpgrade(repoId, { onGenerated: () => router.refresh() });
+ return (
+ <>
+ <DocsModeBadge
+ mode={docsMode}
+ onAction={upgrade.openSheet}
+ label={t("badgeLabel")}
+ actionLabel={t("badgeAction")}
+ title={t("badgeTitle")}
+ />
+ {upgrade.sheet}
+ </>
+ );
+}
diff --git a/packages/web/src/components/model-upgrade/model-upgrade.test.tsx b/packages/web/src/components/model-upgrade/model-upgrade.test.tsx
new file mode 100644
index 000000000..beaba028a
--- /dev/null
+++ b/packages/web/src/components/model-upgrade/model-upgrade.test.tsx
@@ -0,0 +1,160 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { SWRConfig } from "swr";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RepoBreadcrumb } from "@/components/layout/repo-breadcrumb";
+import { NoProviderReason } from "@/components/chat/no-provider-reason";
+import { useModelUpgrade } from "./model-upgrade";
+
+const mocks = vi.hoisted(() => ({
+ getProviders: vi.fn(),
+ setActiveProvider: vi.fn(),
+ addProviderKey: vi.fn(),
+ generateEstimate: vi.fn(),
+ generatePages: vi.fn(),
+ refresh: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => "/repos/r1/docs",
+ useRouter: () => ({ refresh: mocks.refresh, push: vi.fn(), replace: vi.fn() }),
+}));
+vi.mock("next/link", () => ({
+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+vi.mock("@/lib/api/providers", () => ({
+ getProviders: mocks.getProviders,
+ setActiveProvider: mocks.setActiveProvider,
+ addProviderKey: mocks.addProviderKey,
+}));
+vi.mock("@/lib/api/repos", () => ({
+ generateEstimate: mocks.generateEstimate,
+ generatePages: mocks.generatePages,
+}));
+vi.mock("@/components/jobs/generation-progress-wrapper", () => ({
+ GenerationProgressWrapper: ({ jobId }: { jobId: string }) => <div>progress {jobId}</div>,
+}));
+
+const PROVIDERS = {
+ active: { provider: null, model: null },
+ providers: [
+ { id: "openai", name: "OpenAI", models: [], default_model: "", configured: true, requires_key: true, detected: "env" },
+ { id: "ollama", name: "Ollama (Local)", models: [], default_model: "", configured: true, requires_key: false, local_model: true, detected: null },
+ { id: "claude_cli", name: "Claude Code (Local CLI)", models: [], default_model: "", configured: true, requires_key: false, detected: "signed_in" },
+ ],
+};
+
+function estimate(provider: string | null, cost: number | null) {
+ return {
+ total_pages: 46,
+ pages_by_type: {},
+ pages_to_mark_stale: 0,
+ unknown_page_ids: [],
+ provider: { name: provider, model: provider ? "m" : null, error: null },
+ estimate:
+ cost == null
+ ? null
+ : {
+ estimated_cost_usd: cost,
+ cost_low_usd: null,
+ cost_high_usd: null,
+ estimated_input_tokens: 1,
+ estimated_output_tokens: 1,
+ is_calibrated: false,
+ },
+ };
+}
+
+/** The chat surfaces' wiring: the sheet lives beside the composer and the
+ * no-provider reason only opens it. */
+function ChatHarness({ message }: { message: "noProvider" | "noProviderShort" }) {
+ const upgrade = useModelUpgrade("r1");
+ return (
+ <>
+ <NoProviderReason message={message} onAddModel={upgrade.openSheet} />
+ {upgrade.sheet}
+ </>
+ );
+}
+
+function renderFresh(ui: React.ReactElement) {
+ return render(<SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>{ui}</SWRConfig>);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getProviders.mockResolvedValue(PROVIDERS);
+ mocks.setActiveProvider.mockResolvedValue(PROVIDERS);
+ mocks.generateEstimate.mockImplementation(
+ async (_repo: string, _body: unknown, options: { provider?: string } = {}) =>
+ estimate(options.provider ?? null, options.provider ? 0.42 : null),
+ );
+ mocks.generatePages.mockResolvedValue({ job_id: "j1", stream_token: "t" });
+});
+afterEach(cleanup);
+
+describe("ways in to the model sheet", () => {
+ it("the docs-mode badge opens it, and only then detects sources", async () => {
+ renderFresh(<RepoBreadcrumb repoName="orbit-api" docsMode="deterministic" />);
+ expect(mocks.getProviders).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: /Write with a model/ }));
+
+ expect(await screen.findByText("Write this documentation with a model")).toBeTruthy();
+ expect(mocks.getProviders).toHaveBeenCalledWith("r1", { detect: true });
+ expect(await screen.findByText("Uses your Claude Code sign-in.")).toBeTruthy();
+ });
+
+ it("the chat no-provider state opens it and keeps the settings link", async () => {
+ renderFresh(<ChatHarness message="noProvider" />);
+ expect(screen.getByRole("link", { name: "settings" }).getAttribute("href")).toBe("/settings");
+
+ fireEvent.click(screen.getByRole("button", { name: "Add a model" }));
+
+ expect(await screen.findByText("Write this documentation with a model")).toBeTruthy();
+ });
+});
+
+describe("writing the docs", () => {
+ async function openSheet() {
+ renderFresh(<ChatHarness message="noProviderShort" />);
+ fireEvent.click(screen.getByRole("button", { name: "Add a model" }));
+ await screen.findByText("46 pages to write");
+ }
+
+ it("a sign-in sets the repo's provider and starts right away", async () => {
+ await openSheet();
+ fireEvent.click(screen.getByRole("button", { name: "Write the docs" }));
+
+ await waitFor(() =>
+ expect(mocks.generatePages).toHaveBeenCalledWith("r1", {
+ selection: { kind: "unwritten" },
+ cascade: "none",
+ }),
+ );
+ expect(mocks.setActiveProvider).toHaveBeenCalledWith("claude_cli", undefined, "r1");
+ expect(await screen.findByText("progress j1")).toBeTruthy();
+ });
+
+ it("a key shows its price in the sheet, then confirms before it runs", async () => {
+ await openSheet();
+ fireEvent.click(screen.getByRole("radio", { name: /OpenAI key/ }));
+ expect(await screen.findByText(/About \$0\.42 with this key/)).toBeTruthy();
+ expect(mocks.generateEstimate).toHaveBeenCalledWith(
+ "r1",
+ { selection: { kind: "unwritten" }, cascade: "none" },
+ { provider: "openai" },
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Write the docs" }));
+
+ await waitFor(() => expect(mocks.setActiveProvider).toHaveBeenCalledWith("openai", undefined, "r1"));
+ // The shared confirm dialog opens; nothing runs until it is confirmed.
+ await waitFor(() => expect(screen.getByRole("dialog")).toBeTruthy());
+ expect(mocks.generatePages).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/web/src/components/model-upgrade/model-upgrade.tsx b/packages/web/src/components/model-upgrade/model-upgrade.tsx
new file mode 100644
index 000000000..a4d4ddb76
--- /dev/null
+++ b/packages/web/src/components/model-upgrade/model-upgrade.tsx
@@ -0,0 +1,231 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import useSWR, { useSWRConfig } from "swr";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+import {
+ ModelUpgradeSheet,
+ type ModelUpgradeSheetLabels,
+} from "@repowise-dev/ui/settings/model-upgrade-sheet";
+import {
+ defaultModelSource,
+ orderModelSources,
+ pasteKeyProviders,
+ type ModelSource,
+} from "@repowise-dev/ui/settings";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { BulkGenerateConfirm } from "@/components/docs/bulk-generate-confirm";
+import { BulkGenerateProgress } from "@/components/docs/bulk-generate-progress";
+import { useProviderFormLabels } from "@/components/settings/use-provider-form-labels";
+import { addProviderKey, getProviders, setActiveProvider } from "@/lib/api/providers";
+import { generateEstimate } from "@/lib/api/repos";
+import { formatEstimateCost } from "@/lib/generate-format";
+import { hostedLink } from "@/lib/hosted";
+import { useBulkGenerate } from "@/lib/hooks/use-bulk-generate";
+
+/** The same pages the docs header's bulk action writes. */
+const UNWRITTEN = { selection: { kind: "unwritten" as const }, cascade: "none" as const };
+
+function useSheetLabels(): Partial<ModelUpgradeSheetLabels> {
+ const t = useTranslations("modelUpgrade");
+ return useMemo(
+ () => ({
+ eyebrow: t("eyebrow"),
+ title: t("title"),
+ description: t("description"),
+ close: t("close"),
+ sourcesLabel: t("sourcesLabel"),
+ cliSource: (name) => t("cliSource", { name }),
+ keySource: (name) => t("keySource", { name }),
+ localSource: (name) => t("localSource", { name }),
+ pasteSource: t("pasteSource"),
+ hostedSource: t("hostedSource"),
+ hostedNote: t("hostedNote"),
+ hostedAction: t("hostedAction"),
+ detected: {
+ signed_in: t("detected.signedIn"),
+ env: t("detected.env"),
+ saved: t("detected.saved"),
+ },
+ pasteProvider: t("pasteProvider"),
+ pages: (count) => t("pages", { count }),
+ counting: t("counting"),
+ signedInNote: (name) => t("signedInNote", { name }),
+ costNote: (cost) => t("costNote", { cost }),
+ pricing: t("pricing"),
+ keyNote: t("keyNote"),
+ localNote: t("localNote"),
+ pasteNote: t("pasteNote"),
+ write: t("write"),
+ sameAs: t("sameAs"),
+ }),
+ [t],
+ );
+}
+
+/** Every cached providers list (Settings, chat, this sheet) after a change. */
+function useRefreshProviders() {
+ const { mutate } = useSWRConfig();
+ return () =>
+ mutate(
+ (key) =>
+ key === "/api/providers" ||
+ (Array.isArray(key) && key[0] === "/api/providers") ||
+ (typeof key === "string" && key.startsWith("providers:")),
+ );
+}
+
+/** Sources detected on this machine, fetched only while the sheet is open:
+ * detection asks each agent CLI whether it is signed in. A failed fetch
+ * still offers "Paste a key" and hosted. */
+function useModelSources(repoId: string, open: boolean) {
+ const { data, isLoading } = useSWR(
+ open ? ["/api/providers", repoId, "detect"] : null,
+ () => getProviders(repoId, { detect: true }),
+ { revalidateOnFocus: false },
+ );
+ const providers = useMemo(() => data?.providers ?? [], [data]);
+ const sources = useMemo(() => orderModelSources(providers), [providers]);
+ return {
+ sources,
+ keyProviders: useMemo(() => pasteKeyProviders(providers), [providers]),
+ activeProvider: data?.active.provider ?? null,
+ loading: isLoading,
+ };
+}
+
+/** Page count, priced with the selected key's provider when there is one.
+ * The page count does not depend on the provider, so the last one counted
+ * stays up while another source is priced. */
+function useSheetEstimate(repoId: string, open: boolean, source: ModelSource | undefined) {
+ const priced = source?.kind === "key" ? source.providerId : null;
+ const { data, isLoading } = useSWR(
+ open ? ["model-upgrade-estimate", repoId, priced] : null,
+ () => generateEstimate(repoId, UNWRITTEN, priced ? { provider: priced } : {}),
+ { revalidateOnFocus: false },
+ );
+ // Per open: a count from an earlier open may be out of date.
+ const lastPages = useRef<number | null>(null);
+ if (!open) lastPages.current = null;
+ else if (data) lastPages.current = data.total_pages;
+ // The request named the provider, so a priced estimate is that provider's.
+ return {
+ pages: lastPages.current,
+ costText: priced != null && data ? formatEstimateCost(data.estimate) : null,
+ loading: isLoading,
+ };
+}
+
+/**
+ * The model upgrade sheet for one repo, with the run it starts. "Write the
+ * docs" makes the chosen source the repo's provider (its
+ * `.repowise/config.yaml`, which the CLI reads too), then runs the docs
+ * header's bulk generate flow: a key source confirms its price first, a
+ * sign-in or local model starts right away. The confirm and progress dialogs
+ * stay mounted after the sheet closes.
+ */
+export function ModelUpgrade({
+ repoId,
+ open,
+ onOpenChange,
+ onGenerated,
+}: {
+ repoId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Called once a run completes so the host can refresh what it shows. */
+ onGenerated?: () => void;
+}) {
+ const ts = useTranslations("settings");
+ const t = useTranslations("modelUpgrade");
+ const labels = useSheetLabels();
+ const keyLabels = useProviderFormLabels(true);
+ const refreshProviders = useRefreshProviders();
+ const bulk = useBulkGenerate(repoId);
+ const { sources, keyProviders, activeProvider, loading } = useModelSources(repoId, open);
+
+ // null until the user picks: the default follows the detected sources.
+ const [picked, setPicked] = useState<string | null>(null);
+ const selectedId = picked ?? defaultModelSource(sources, activeProvider);
+ const selected = sources.find((s) => s.id === selectedId);
+ const estimate = useSheetEstimate(repoId, open, selected);
+ const [writing, setWriting] = useState(false);
+
+ function changeOpen(next: boolean) {
+ if (!next) setPicked(null);
+ onOpenChange(next);
+ }
+
+ async function addKey(providerId: string, key: string) {
+ try {
+ await addProviderKey(providerId, key, repoId);
+ } catch (e) {
+ toast.error(ts("providerPanel.keySaveFailed"), { description: toFriendlyMessage(e) });
+ throw e;
+ }
+ await refreshProviders();
+ setPicked(providerId);
+ }
+
+ async function write() {
+ const source = selected;
+ const providerId = source?.providerId;
+ if (!source || !providerId) return;
+ setWriting(true);
+ try {
+ // The repo's current provider keeps its chosen model.
+ if (providerId !== activeProvider) {
+ await setActiveProvider(providerId, undefined, repoId);
+ await refreshProviders();
+ }
+ changeOpen(false);
+ if (source.kind === "key") bulk.open();
+ else await bulk.confirm();
+ } catch (e) {
+ toast.error(t("startFailed"), { description: toFriendlyMessage(e) });
+ } finally {
+ setWriting(false);
+ }
+ }
+
+ return (
+ <>
+ <ModelUpgradeSheet
+ open={open}
+ onOpenChange={changeOpen}
+ sources={sources}
+ loading={loading}
+ selectedId={selectedId}
+ onSelect={setPicked}
+ keyProviders={keyProviders}
+ onAddKey={addKey}
+ estimate={estimate}
+ onWrite={() => void write()}
+ writing={writing}
+ hostedHref={hostedLink("model_sheet", "keys")}
+ labels={labels}
+ keyLabels={keyLabels}
+ />
+ <BulkGenerateConfirm flow={bulk} repoId={repoId} title={t("title")} />
+ <BulkGenerateProgress flow={bulk} {...(onGenerated ? { onGenerated } : {})} />
+ </>
+ );
+}
+
+/**
+ * Open the model upgrade sheet from anywhere in a repo: render `sheet` once
+ * and call `openSheet` from a button. Nothing is fetched until it opens.
+ */
+export function useModelUpgrade(repoId: string, options: { onGenerated?: () => void } = {}) {
+ const [open, setOpen] = useState(false);
+ const sheet = (
+ <ModelUpgrade
+ repoId={repoId}
+ open={open}
+ onOpenChange={setOpen}
+ {...(options.onGenerated ? { onGenerated: options.onGenerated } : {})}
+ />
+ );
+ return { openSheet: () => setOpen(true), sheet };
+}
diff --git a/tests/unit/server/test_generate.py b/tests/unit/server/test_generate.py
index 003d4af29..e491113d6 100644
--- a/tests/unit/server/test_generate.py
+++ b/tests/unit/server/test_generate.py
@@ -243,6 +243,27 @@ async def test_generate_estimate_no_pages(client: AsyncClient) -> None:
assert body["provider"]["error"] is not None
+async def test_generate_estimate_prices_a_provider_override(client: AsyncClient) -> None:
+ """``?provider=`` prices a provider the repo has not chosen yet."""
+ repo = await create_test_repo(client)
+ llm = SimpleNamespace(provider_name="anthropic", model_name="claude-haiku-4-5")
+ with patch(
+ "repowise.server.provider_config.get_chat_provider_instance", return_value=llm
+ ) as build:
+ resp = await client.post(
+ f"/api/repos/{repo['id']}/generate/estimate?provider=anthropic",
+ json={"selection": {"kind": "unwritten"}},
+ )
+ assert resp.status_code == 200, resp.text
+ assert build.call_args.kwargs["provider_override"] == "anthropic"
+ assert resp.json()["provider"] == {
+ "name": "anthropic",
+ "model": "claude-haiku-4-5",
+ "error": None,
+ }
+
+
# ---------------------------------------------------------------------------
# generate job execution (shared core engine)
# ---------------------------------------------------------------------------
diff --git a/tests/unit/server/test_provider_config.py b/tests/unit/server/test_provider_config.py
index 528e0e497..2abe89a1c 100644
--- a/tests/unit/server/test_provider_config.py
+++ b/tests/unit/server/test_provider_config.py
@@ -318,6 +318,53 @@ def test_list_provider_status_carries_setup_facts_from_the_specs(clean_env, tmp_
assert status["flag_only_providers"] == ["mock"]
+def test_list_provider_status_names_where_a_key_was_found(clean_env, tmp_path):
+ repo = _make_repo(tmp_path / "repo", env="OPENAI_API_KEY=sk-from-repo-env\n")
+ clean_env["GEMINI_API_KEY"] = "from-process-env"
+ pc.set_api_key("anthropic", "sk-ant-stored")
+
+ by_id = {p["id"]: p for p in pc.list_provider_status(repo_path=str(repo))["providers"]}
+
+ assert by_id["openai"]["detected"] == "env"
+ assert by_id["gemini"]["detected"] == "env"
+ assert by_id["anthropic"]["detected"] == "saved"
+ assert by_id["deepseek"]["detected"] is None
+ # Keyless providers name nothing; agent CLIs only when asked to detect.
+ assert by_id["ollama"]["detected"] is None
+ assert by_id["claude_cli"]["detected"] is None
+
+
+def test_detect_names_signed_in_agent_clis(clean_env, monkeypatch):
+ from repowise.core.agents.identity import AgentIdentity
+
+ calls: list[str] = []
+
+ def is_logged_in(self):
+ calls.append(self.slug)
+ return self.slug == "claude_code"
+
+ monkeypatch.setattr(AgentIdentity, "is_logged_in", is_logged_in)
+
+ assert {p["detected"] for p in pc.list_provider_status()["providers"]} == {None}
+ assert calls == []
+
+ by_id = {p["id"]: p for p in pc.list_provider_status(detect=True)["providers"]}
+ assert by_id["claude_cli"]["detected"] == "signed_in"
+ assert by_id["codex_cli"]["detected"] is None
+ assert "codex" in calls
+
+
+def test_a_broken_login_check_counts_as_not_signed_in(clean_env, monkeypatch):
+ from repowise.core.agents.identity import AgentIdentity
+
+ def is_logged_in(self):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(AgentIdentity, "is_logged_in", is_logged_in)
+ by_id = {p["id"]: p for p in pc.list_provider_status(detect=True)["providers"]}
+ assert by_id["claude_cli"]["detected"] is None
+
+
def test_list_provider_status_carries_the_embedder_registry(clean_env, tmp_path, monkeypatch):
from repowise.core.providers.embedding import registry
@@ -369,8 +416,10 @@ def test_list_provider_status_never_returns_key_material(clean_env, tmp_path):
"requires_key",
"accepts_base_url",
"local_server",
+ "local_model",
"env_vars",
"setup_hint",
+ "detected",
}
assert "key" not in provider
assert "api_key" not in provider
diff --git a/tests/unit/server/test_provider_key_endpoint.py b/tests/unit/server/test_provider_key_endpoint.py
index 802ede41f..b7d5d2a70 100644
--- a/tests/unit/server/test_provider_key_endpoint.py
+++ b/tests/unit/server/test_provider_key_endpoint.py
@@ -235,3 +235,20 @@ async def test_patch_active_rejects_a_non_http_base_url(client: AsyncClient) ->
)
assert resp.status_code == 400
assert "http" in resp.json()["detail"]
+
+
+async def test_detect_query_reports_signed_in_agent_clis(client: AsyncClient, monkeypatch) -> None:
+ from repowise.core.agents.identity import AgentIdentity
+
+ monkeypatch.setattr(AgentIdentity, "is_logged_in", lambda self: self.slug == "codex")
+
+ plain = (await client.get("/api/providers")).json()
+ detected = (await client.get("/api/providers?detect=true")).json()
+
+ def by_id(body):
+ return {p["id"]: p["detected"] for p in body["providers"]}
+
+ assert by_id(plain)["codex_cli"] is None
+ assert by_id(detected)["codex_cli"] == "signed_in"
+ assert by_id(detected)["claude_cli"] is None