Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(settings): read provider, embedder and price facts from the server (#3172)
Raghav Chamadiya6e6d151976ce
diff --git a/packages/api-client/src/types/misc.ts b/packages/api-client/src/types/misc.tsindex 7838812a4..6fb315bb1 100644--- a/packages/api-client/src/types/misc.ts+++ b/packages/api-client/src/types/misc.ts@@ -35,12 +35,28 @@ export interface ProviderInfo {setup_hint?: string;}+export interface EmbedderInfo {+ id: string;+ /** Env vars a user sets to make the embedder usable. */+ env_vars?: string[];+ /** `false` for the keyless embedder, whose vectors carry no signal. */+ semantic?: boolean;+}+export interface ProvidersResponse {active: {provider: string | null;model: string | null;+ /** USD per 1K tokens for `model`; null when no model resolves. */+ input_cost_per_1k?: number | null;+ output_cost_per_1k?: number | null;+ /** The embedder this server runs with. */+ embedder?: string | null;};providers: ProviderInfo[];+ /** Registerable providers the catalog leaves out. */+ flag_only_providers?: string[];+ embedders?: EmbedderInfo[];}/** Result of a live provider smoke test. `ok: false` carries the reason indiff --git a/packages/cli/src/repowise/cli/cost_estimator/__init__.py b/packages/cli/src/repowise/cli/cost_estimator/__init__.pyindex e5c49d993..9f25de117 100644--- a/packages/cli/src/repowise/cli/cost_estimator/__init__.py+++ b/packages/cli/src/repowise/cli/cost_estimator/__init__.py@@ -10,16 +10,16 @@ from repowise.core.cost_estimator import (CostEstimate,CostRange,PageTypePlan,- _lookup_cost,build_generation_plan,estimate_cost,+ lookup_cost,)__all__ = ["CostEstimate","CostRange","PageTypePlan",- "_lookup_cost","build_generation_plan","estimate_cost",+ "lookup_cost",]diff --git a/packages/core/src/repowise/core/cost_estimator/__init__.py b/packages/core/src/repowise/core/cost_estimator/__init__.pyindex 52ef39d11..433d54f8e 100644--- a/packages/core/src/repowise/core/cost_estimator/__init__.py+++ b/packages/core/src/repowise/core/cost_estimator/__init__.py@@ -9,13 +9,14 @@ Public API kept stable for existing callers:- :func:`estimate_cost` — given plans + model, returns a:class:`CostEstimate` with a median + low/high range. Optionallycalibrated against ``.repowise/db.sqlite`` telemetry.-- :func:`_lookup_cost` — retained for the provider unit tests.+- :func:`lookup_cost` — per-1K rates for a model, ``None`` when unpriced;+ the server prices the active model with it."""from .approx import approximate_generation_planfrom .estimator import STRUCTURAL_PAGE_TYPES, estimate_costfrom .plans import build_generation_plan-from .pricing import _lookup_cost+from .pricing import lookup_costfrom .types import CostEstimate, CostRange, PageTypePlan__all__ = [@@ -23,8 +24,8 @@ __all__ = ["CostEstimate","CostRange","PageTypePlan",- "_lookup_cost","approximate_generation_plan","build_generation_plan","estimate_cost",+ "lookup_cost",]diff --git a/packages/core/src/repowise/core/cost_estimator/estimator.py b/packages/core/src/repowise/core/cost_estimator/estimator.pyindex b09ee79b2..488c29bb6 100644--- a/packages/core/src/repowise/core/cost_estimator/estimator.py+++ b/packages/core/src/repowise/core/cost_estimator/estimator.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom .calibration import load_telemetry_averagesfrom .heuristics import HEURISTIC_VARIANCE, heuristic_tokens-from .pricing import _lookup_cost+from .pricing import lookup_costfrom .types import CostEstimate, CostRange, PageTypePlan# Page types rendered from structure. They make no provider call, so they cost@@ -64,7 +64,8 @@ def estimate_cost(total_input += inp * plan.counttotal_output += out * plan.count- input_rate, output_rate = _lookup_cost(model_name)+ # An unpriced model is estimated as free; the CLI gate has always done so.+ input_rate, output_rate = lookup_cost(model_name) or (0.0, 0.0)median_cost = (total_input / 1000) * input_rate + (total_output / 1000) * output_rate# Tighter variance when telemetry calibrated us; wider for cold-start.diff --git a/packages/core/src/repowise/core/cost_estimator/pricing.py b/packages/core/src/repowise/core/cost_estimator/pricing.pyindex 09e3eb7ef..a405a11a3 100644--- a/packages/core/src/repowise/core/cost_estimator/pricing.py+++ b/packages/core/src/repowise/core/cost_estimator/pricing.py@@ -10,9 +10,8 @@ over-estimate on a re-run: safe direction, wrong number.The token count is not the missing piece: ``cached_tokens`` already flowsprovider -> ``GeneratedPage`` -> the ``pages`` table, and the run report-prints it. What is missing is a third rate (here, in-``generation/cost_tracker.py``, and in the TS mirror at-``packages/ui/src/dashboard/quick-actions.tsx``), plus splitting the+prints it. What is missing is a third rate (here and in+``generation/cost_tracker.py``), plus splitting thecached count out of ``input_tokens`` in the cost arithmetic. Worth doingwhen we report cost per re-index, where the discount is the whole story;not worth it to move a one-off init estimate by ~10%.@@ -54,7 +53,7 @@ _COST_TABLE_EXACT: dict[str, tuple[float, float]] = {# Prefix fallbacks for unknown variants. No `gpt-5.6` catch-all: the 5.6# variants are not one price tier, and an unpriced model reads as free here-# (``_lookup_cost`` falls through to (0.0, 0.0)), so a guess would be worse+# (the estimator prices a ``None`` from ``lookup_cost`` at zero), so a guess would be worse# than the miss it hides._COST_TABLE_PREFIX: dict[str, tuple[float, float]] = {"gpt-5.6-luna": (0.0002, 0.0012),@@ -87,8 +86,12 @@ _COST_TABLE_PREFIX: dict[str, tuple[float, float]] = {}-def _lookup_cost(model_name: str) -> tuple[float, float]:- """Return ``(input_rate, output_rate)`` per 1K tokens for *model_name*."""+def lookup_cost(model_name: str) -> tuple[float, float] | None:+ """Return ``(input_rate, output_rate)`` per 1K tokens for *model_name*.++ ``None`` when no entry matches: the model is unpriced, which is not the+ same as free (the explicit zero rows above).+ """lower = model_name.lower()# OpenRouter/LiteLLM slugs carry a routing prefix (`google/gemini-3.5-flash-lite`)# that hides the model from every entry below, which priced them at zero.@@ -98,7 +101,7 @@ def _lookup_cost(model_name: str) -> tuple[float, float]:if lower in _COST_TABLE_EXACT:return _COST_TABLE_EXACT[lower]best_prefix = ""- best_rates = (0.0, 0.0)+ best_rates: tuple[float, float] | None = Nonefor prefix, rates in _COST_TABLE_PREFIX.items():if lower.startswith(prefix) and len(prefix) > len(best_prefix):best_prefix = prefixdiff --git a/packages/core/src/repowise/core/providers/embedding/registry.py b/packages/core/src/repowise/core/providers/embedding/registry.pyindex 16191404b..91be91041 100644--- a/packages/core/src/repowise/core/providers/embedding/registry.py+++ b/packages/core/src/repowise/core/providers/embedding/registry.py@@ -33,6 +33,14 @@ _BUILTIN_EMBEDDERS: dict[str, tuple[str, str]] = {"mock": ("repowise.core.providers.embedding.base", "KeylessEmbedder"),}+#: What ``REPOWISE_EMBEDDER`` means when unset.+DEFAULT_EMBEDDER = "mock"++#: Built-ins whose vectors carry no signal (see ``KeylessEmbedder``).+KEYLESS_EMBEDDERS = frozenset(+ name for name, (_module, cls) in _BUILTIN_EMBEDDERS.items() if cls == "KeylessEmbedder"+)+_custom_embedders: dict[str, Callable[..., Embedder]] = {}diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex d219736ad..db7b8a59b 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -35,6 +35,7 @@ from repowise.core.persistence.search import FullTextSearchfrom repowise.core.providers.embedding import is_semantic_embedderfrom repowise.core.providers.embedding.base import KeylessEmbedderfrom repowise.core.providers.embedding.caching import CachingEmbedder+from repowise.core.providers.embedding.registry import DEFAULT_EMBEDDERfrom repowise.server import __version__from repowise.server.routers import (actions,@@ -121,7 +122,7 @@ def _build_embedder():openrouter — OpenRouterEmbedder via OPENROUTER_API_KEY env varedenai — EdenAIEmbedder via EDENAI_API_KEY env var"""- name = os.environ.get("REPOWISE_EMBEDDER", "mock").lower()+ name = os.environ.get("REPOWISE_EMBEDDER", DEFAULT_EMBEDDER).lower()if name == "ollama":from repowise.core.providers.embedding.ollama import OllamaEmbedderdiff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.pyindex f26ab8934..462e3b406 100644--- a/packages/server/src/repowise/server/provider_config.py+++ b/packages/server/src/repowise/server/provider_config.py@@ -29,6 +29,11 @@ import osfrom pathlib import Pathfrom typing import Any+from repowise.core.providers.embedding.registry import (+ DEFAULT_EMBEDDER,+ KEYLESS_EMBEDDERS,+ list_embedders,+)from repowise.core.providers.llm.specs import PROVIDER_SPECSlogger = logging.getLogger(__name__)@@ -57,6 +62,25 @@ PROVIDER_CATALOG: list[dict[str, Any]] = [_CATALOG_BY_ID = {p["id"]: p for p in PROVIDER_CATALOG}+FLAG_ONLY_PROVIDERS = [spec.name for spec in PROVIDER_SPECS.values() if spec.picker_rank is None]+++def _embedder_catalog() -> list[dict[str, Any]]:+ """Every registered embedder, read at call time so custom ones appear.++ A built-in embedder reads the same credentials as the LLM provider of the+ same name, so its env vars come from that spec; a custom one has none.+ The default comes first so the picker opens on it; the rest stay sorted.+ """+ return [+ {+ "id": name,+ "env_vars": list(spec.required_envs) if (spec := PROVIDER_SPECS.get(name)) else [],+ "semantic": name not in KEYLESS_EMBEDDERS,+ }+ for name in sorted(list_embedders(), key=lambda n: n != DEFAULT_EMBEDDER)+ ]+# ---------------------------------------------------------------------------# Config file I/O@@ -303,13 +327,30 @@ def list_provider_status(})+ # Deferred: the estimator package pulls in the generation pipeline.+ from repowise.core.cost_estimator import lookup_cost++ model = active_model or (+ _CATALOG_BY_ID.get(active_id, {}).get("default_model") if active_id else None+ )+ rates = lookup_cost(model) if model else None+ # An unpriced model on a local provider costs nothing; anywhere else it+ # is unknown, and null rates make the dashboard show no estimate.+ spec = PROVIDER_SPECS.get(active_id or "")+ if rates is None and model and spec is not None and spec.local:+ rates = (0.0, 0.0)+ input_rate, output_rate = rates or (None, None)return {"active": {"provider": active_id,- "model": active_model- or (_CATALOG_BY_ID.get(active_id, {}).get("default_model") if active_id else None),+ "model": model,+ "input_cost_per_1k": input_rate,+ "output_cost_per_1k": output_rate,+ "embedder": os.environ.get("REPOWISE_EMBEDDER", DEFAULT_EMBEDDER).lower(),},"providers": providers,+ "flag_only_providers": FLAG_ONLY_PROVIDERS,+ "embedders": _embedder_catalog(),}diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 5df76167c..7255e92d7 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -262,6 +262,7 @@ if TYPE_CHECKING:ActiveProviderSelection,CostGroupResponse,CostSummaryResponse,+ EmbedderEntry,OkResponse,ProviderEntry,ProviderStatusResponse,@@ -544,6 +545,7 @@ _EXPORTS: dict[str, tuple[str, ...]] = {"ActiveProviderSelection","CostGroupResponse","CostSummaryResponse",+ "EmbedderEntry","OkResponse","ProviderEntry","ProviderStatusResponse",@@ -716,6 +718,7 @@ __all__ = ["DocDriftResponse","DocDriftSummaryResponse","EgoGraphResponse",+ "EmbedderEntry","EpisodeCountsResponse","EpisodeDetail","EpisodeListResponse",diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.pyindex e753b204e..0ef2eb2bc 100644--- a/packages/server/src/repowise/server/schemas/ui_helpers.py+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py@@ -50,16 +50,34 @@ class ProviderEntry(BaseModel):setup_hint: str = ""+class EmbedderEntry(BaseModel):+ """One registered embedder, as the settings picker renders it."""++ id: str+ #: Env vars a user sets to make the embedder usable.+ env_vars: list[str] = []+ #: ``False`` for the keyless embedder, whose vectors carry no signal.+ semantic: bool = True++class ActiveProviderSelection(BaseModel):"""The provider/model this scope resolves to; ``None`` when unset."""provider: str | None = Nonemodel: str | None = None+ #: USD per 1K tokens for ``model``; ``None`` when no model resolves.+ input_cost_per_1k: float | None = None+ output_cost_per_1k: float | None = None+ #: The embedder this server runs with.+ embedder: str | None = Noneclass ProviderStatusResponse(BaseModel):active: ActiveProviderSelectionproviders: list[ProviderEntry] = []+ #: Registerable providers the catalog leaves out (picker_rank ``None``).+ flag_only_providers: list[str] = []+ embedders: list[EmbedderEntry] = []class ProviderValidationResponse(BaseModel):diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 62f0e4acc..4f6e5bd76 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -91,6 +91,9 @@ export interface ActionsResponse {export interface ActiveProviderSelection {provider?: string | null;model?: string | null;+ input_cost_per_1k?: number | null;+ output_cost_per_1k?: number | null;+ embedder?: string | null;}export interface AgentPromptResponse {@@ -1266,6 +1269,13 @@ export interface EgoGraphResponse {outbound_count: number;}+/** One registered embedder, as the settings picker renders it. */+export interface EmbedderEntry {+ id: string;+ env_vars?: string[];+ semantic?: boolean;+}+/*** Counts by tier and by kind, from a grouped read of the same filters.*@@ -2632,6 +2642,8 @@ export interface ProviderEntry {export interface ProviderStatusResponse {active: ActiveProviderSelection;providers?: ProviderEntry[];+ flag_only_providers?: string[];+ embedders?: EmbedderEntry[];}/**diff --git a/packages/ui/__tests__/dashboard/quick-actions.test.tsx b/packages/ui/__tests__/dashboard/quick-actions.test.tsxindex 32e93b331..111e7d379 100644--- a/packages/ui/__tests__/dashboard/quick-actions.test.tsx+++ b/packages/ui/__tests__/dashboard/quick-actions.test.tsx@@ -30,6 +30,26 @@ describe("QuickActions", () => {await waitFor(() => expect(onAction).toHaveBeenCalledWith("sync"));});+ it("prices the estimate with the rates it is given, and shows none without them", async () => {+ const { unmount } = render(+ <QuickActions+ onAction={vi.fn()}+ pageCount={100}+ modelName="some-model"+ costPer1k={{ input: 0.001, output: 0.005 }}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /Full Re-index/i }));+ // 100 pages * (3.5K in * $0.001 + 2.2K out * $0.005) = $1.45.+ expect(await screen.findByText(/1\.45/)).toBeInTheDocument();+ unmount();++ render(<QuickActions onAction={vi.fn()} pageCount={100} modelName="some-model" />);+ fireEvent.click(screen.getByRole("button", { name: /Full Re-index/i }));+ expect(await screen.findByText("Full Re-index", { selector: "h2" })).toBeInTheDocument();+ expect(screen.queryByText(/Estimated Cost/i)).not.toBeInTheDocument();+ });+it("renders activeJobSlot in place of the buttons when provided", () => {render(<QuickActionsdiff --git a/packages/ui/src/dashboard/quick-actions.tsx b/packages/ui/src/dashboard/quick-actions.tsxindex 495b0a843..5d20925a5 100644--- a/packages/ui/src/dashboard/quick-actions.tsx+++ b/packages/ui/src/dashboard/quick-actions.tsx@@ -18,56 +18,16 @@ import { formatNumber, formatCost, formatRelativeTime } from "../lib/format";const AVG_INPUT_TOKENS_PER_PAGE = 3500;const AVG_OUTPUT_TOKENS_PER_PAGE = 2200;-const COST_TABLE_EXACT: Record<string, [number, number]> = {- "gpt-5.4": [0.0025, 0.015],- "gpt-5.4-mini": [0.00075, 0.0045],- "gpt-5.4-nano": [0.0002, 0.00125],- "gpt-5.6-luna": [0.0002, 0.0012],- "gemini-3.1-pro-preview": [0.002, 0.012],- "gemini-3-flash-preview": [0.0005, 0.003],- "gemini-3.1-flash-lite-preview": [0.00025, 0.0015],- "claude-opus-4-6": [0.005, 0.025],- "claude-sonnet-4-6": [0.003, 0.015],- "claude-haiku-4-5": [0.001, 0.005],- "claude-haiku-5-5": [0.0001, 0.0005],- "deepseek-v4-flash": [0.00014, 0.00028],- "deepseek-v4-pro": [0.00174, 0.00348],-};--const COST_TABLE_PREFIX: [string, [number, number]][] = [- ["gpt-5.6-luna", [0.0002, 0.0012]],- ["gpt-5.4-nano", [0.0002, 0.00125]],- ["gpt-5.4-mini", [0.00075, 0.0045]],- ["gpt-5.4", [0.0025, 0.015]],- ["claude-opus", [0.005, 0.025]],- ["claude-sonnet", [0.003, 0.015]],- ["claude-haiku", [0.001, 0.005]],- ["claude", [0.003, 0.015]],- ["deepseek", [0.00014, 0.00028]],- ["gemini", [0.00025, 0.0015]],- ["llama", [0, 0]],- ["mock", [0, 0]],-];--function lookupCost(modelName: string): [number, number] {- const lower = modelName.toLowerCase();- if (lower in COST_TABLE_EXACT) return COST_TABLE_EXACT[lower]!;- let bestLen = 0;- let bestRates: [number, number] = [0, 0];- for (const [prefix, rates] of COST_TABLE_PREFIX) {- if (lower.startsWith(prefix) && prefix.length > bestLen) {- bestLen = prefix.length;- bestRates = rates;- }- }- return bestRates;+/** USD per 1K tokens, as the server prices the active model. */+export interface CostPer1k {+ input: number;+ output: number;}-function estimateCost(pageCount: number, modelName: string) {+function estimateCost(pageCount: number, rates: CostPer1k) {const inputTokens = pageCount * AVG_INPUT_TOKENS_PER_PAGE;const outputTokens = pageCount * AVG_OUTPUT_TOKENS_PER_PAGE;- const [inputRate, outputRate] = lookupCost(modelName);- const cost = (inputTokens / 1000) * inputRate + (outputTokens / 1000) * outputRate;+ const cost = (inputTokens / 1000) * rates.input + (outputTokens / 1000) * rates.output;return { inputTokens, outputTokens, cost };}@@ -133,6 +93,8 @@ export interface QuickActionsProps {/** Inputs for the cost-estimate panel inside the confirm dialog. */pageCount?: number;modelName?: string;+ /** The model's rates from the server; without them no estimate is shown. */+ costPer1k?: CostPer1k | null;/** When provided, replaces the buttons with the given node — typically a* rendered job-progress widget. Wrapper decides what to pass. */activeJobSlot?: ReactNode;@@ -156,6 +118,7 @@ export function QuickActions({lastResyncAt,pageCount = 0,modelName = "",+ costPer1k,activeJobSlot,variant = "row",}: QuickActionsProps) {@@ -165,11 +128,13 @@ export function QuickActions({const loading = loadingKey !== undefined ? loadingKey : internalLoading;const estimate = useMemo(() => {- if (!pendingAction || pendingAction.key === "dead-code" || pageCount <= 0) return null;+ if (!pendingAction || pendingAction.key === "dead-code" || pageCount <= 0 || !costPer1k) {+ return null;+ }const pages =pendingAction.key === "sync" ? Math.max(1, Math.ceil(pageCount * 0.1)) : pageCount;- return estimateCost(pages, modelName);- }, [pendingAction, pageCount, modelName]);+ return estimateCost(pages, costPer1k);+ }, [pendingAction, pageCount, costPer1k]);async function execute(action: QuickActionDef) {if (loadingKey === undefined) setInternalLoading(action.key);diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 2042781ca..1290b4caa 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -511,7 +511,7 @@"embedderLabel": "Embedder","embedderHint": "What semantic search is built from. The mock embedder disables it.","embedderAria": "Embedder",- "embedderOffNote": "Semantic search is off. Set <code>REPOWISE_EMBEDDER=gemini</code> or <code>REPOWISE_EMBEDDER=openai</code> on the server for real retrieval.",+ "embedderOffNote": "Semantic search is off. Pick another embedder above and set <code>REPOWISE_EMBEDDER</code> on the server for real retrieval.","embedderOnNote": "Set <code>{env}</code> on the server.","catalogUnavailable": "Could not load the provider list from the server, so only the saved provider is shown."}diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 768aee1e0..895bdbe5f 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -511,7 +511,7 @@"embedderLabel": "嵌入模型","embedderHint": "语义搜索基于它构建。mock 嵌入模型会禁用语义搜索。","embedderAria": "嵌入模型",- "embedderOffNote": "语义搜索已关闭。请在服务端设置 <code>REPOWISE_EMBEDDER=gemini</code> 或 <code>REPOWISE_EMBEDDER=openai</code> 以启用真实检索。",+ "embedderOffNote": "语义搜索已关闭。请在上方选择其他嵌入模型,并在服务端设置 <code>REPOWISE_EMBEDDER</code> 以启用真实检索。","embedderOnNote": "请在服务端设置 <code>{env}</code>。","catalogUnavailable": "无法从服务器加载提供商列表,因此只显示已保存的提供商。"}diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex c32ea3efa..d3ca09f42 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -88,6 +88,13 @@ export default async function OverviewPage({ params }: Props) {});}+ // Priced by the server; no rates means the dialog shows no estimate.+ const active = providers?.active;+ const costPer1k =+ active?.input_cost_per_1k != null && active.output_cost_per_1k != null+ ? { input: active.input_cost_per_1k, output: active.output_cost_per_1k }+ : null;+const header = (<RepoIdentityHeadername={repo.name}@@ -103,6 +110,7 @@ export default async function OverviewPage({ params }: Props) {repoName={repo.name}pageCount={sync.page_count || stats.file_count}modelName={providers?.active.model ?? sync.last_sync_model ?? ""}+ costPer1k={costPer1k}lastSyncAt={sync.last_sync_at}lastResyncAt={sync.last_resync_at}/>diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsxindex 2ef19894d..1b3951710 100644--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx@@ -6,6 +6,7 @@ import { toast } from "sonner";import {QuickActions as QuickActionsShell,DEFAULT_QUICK_ACTIONS,+ type CostPer1k,type QuickActionKey,} from "@repowise-dev/ui/dashboard/quick-actions";import { syncRepo, fullResyncRepo } from "@/lib/api/repos";@@ -20,6 +21,7 @@ interface Props {repoName?: string;pageCount?: number;modelName?: string;+ costPer1k?: CostPer1k | null;lastSyncAt?: string | null;lastResyncAt?: string | null;/** Button arrangement — see `QuickActionsProps.variant`. Overview passes@@ -37,6 +39,7 @@ export function QuickActionsWrapper({repoName,pageCount = 0,modelName = "",+ costPer1k,lastSyncAt,lastResyncAt,variant,@@ -165,6 +168,7 @@ export function QuickActionsWrapper({lastResyncAt={lastResyncAt}pageCount={pageCount}modelName={modelName}+ costPer1k={costPer1k}activeJobSlot={activeSlot}variant={variant}/>diff --git a/packages/web/src/components/settings/provider-section.test.tsx b/packages/web/src/components/settings/provider-section.test.tsxindex 26b96f86e..d272f4624 100644--- a/packages/web/src/components/settings/provider-section.test.tsx+++ b/packages/web/src/components/settings/provider-section.test.tsx@@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({getProviders: vi.fn(),getProvider: vi.fn(() => "gemini"),+ getEmbedder: vi.fn(() => "mock"),}));vi.mock("@/lib/api/providers", () => ({ getProviders: mocks.getProviders }));@@ -14,7 +15,7 @@ vi.mock("@/lib/config", () => ({config: {getProvider: mocks.getProvider,getModel: () => "",- getEmbedder: () => "mock",+ getEmbedder: mocks.getEmbedder,setProvider: vi.fn(),setModel: vi.fn(),setEmbedder: vi.fn(),@@ -98,6 +99,7 @@ describe("ProviderSection provider catalog", () => {{ id: "gemini", name: "Google Gemini", default_model: "gemini-3.5-flash-lite" },{ id: "codex_cli", name: "Codex CLI", default_model: "codex_cli/gpt-5.6-luna" },],+ flag_only_providers: ["mock"],});render(<ProviderSection />);@@ -192,3 +194,56 @@ describe("ProviderSection provider catalog", () => {expect(screen.getByText(/GEMINI_API_KEY/)).toBeTruthy();});});++describe("ProviderSection server defaults", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ Element.prototype.hasPointerCapture = vi.fn(() => false);+ Element.prototype.releasePointerCapture = vi.fn();+ Element.prototype.scrollIntoView = vi.fn();+ });++ it("shows the server's provider and embedder when nothing is saved", async () => {+ mocks.getProvider.mockReturnValue("");+ mocks.getEmbedder.mockReturnValue("");+ mocks.getProviders.mockResolvedValue({+ active: { provider: "openai", model: null, embedder: "gemini" },+ providers: [{ id: "openai", name: "OpenAI", default_model: "gpt-5.6-luna" }],+ embedders: [+ { id: "gemini", env_vars: ["GEMINI_API_KEY"], semantic: true },+ { id: "mock", env_vars: [], semantic: false },+ ],+ });++ render(<ProviderSection />);++ await waitFor(() =>+ expect(screen.getByRole("combobox", { name: "Provider" }).textContent).toContain("openai"),+ );+ expect(screen.getByRole("combobox", { name: "Embedder" }).textContent).toContain("gemini");+ expect(screen.getByText(/GEMINI_API_KEY/)).toBeTruthy();+ });++ it("offers the server's embedders and says when one carries no signal", async () => {+ mocks.getProvider.mockReturnValue("openai");+ mocks.getEmbedder.mockReturnValue("mock");+ mocks.getProviders.mockResolvedValue({+ active: { provider: "openai", model: null, embedder: "mock" },+ providers: [],+ embedders: [+ { id: "voyage", env_vars: [], semantic: true },+ { id: "mock", env_vars: [], semantic: false },+ ],+ });++ render(<ProviderSection />);++ expect(await screen.findByText(/Semantic search is off/)).toBeTruthy();+ fireEvent.keyDown(screen.getByRole("combobox", { name: "Embedder" }), {+ key: "Enter",+ code: "Enter",+ });+ await waitFor(() => expect(screen.queryAllByRole("option").length).toBeGreaterThan(0));+ expect(screen.queryAllByRole("option").map((o) => o.textContent)).toEqual(["voyage", "mock"]);+ });+});diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsxindex da316c304..fbe9f311f 100644--- a/packages/web/src/components/settings/provider-section.tsx+++ b/packages/web/src/components/settings/provider-section.tsx@@ -3,7 +3,7 @@import React, { useEffect, useRef, useState } from "react";import { config } from "@/lib/config";import { getProviders } from "@/lib/api/providers";-import type { ProviderInfo } from "@/lib/api/types";+import type { EmbedderInfo, ProviderInfo } from "@/lib/api/types";import { OverviewSection } from "@repowise-dev/ui/overview";import { Input } from "@repowise-dev/ui/ui/input";import {@@ -22,23 +22,6 @@ import {} from "@repowise-dev/ui/settings";import { useTranslations } from "next-intl";-const EMBEDDERS = ["mock", "gemini", "openai", "openrouter", "edenai", "ollama"] as const;--// Real, registerable providers the server catalog deliberately leaves out.-// `mock` is a keyless test provider (`KEYLESS_PROVIDERS` in the registry) that-// this page has always offered; it is flag-only, so it is absent from-// PROVIDER_CATALOG and would otherwise vanish the moment the catalog loads.-const FLAG_ONLY_PROVIDERS = ["mock"] as const;--const EMBEDDER_ENV_VARS: Record<string, string[]> = {- gemini: ["GEMINI_API_KEY"],- openai: ["OPENAI_API_KEY"],- openrouter: ["OPENROUTER_API_KEY"],- edenai: ["EDENAI_API_KEY"],- ollama: ["OLLAMA_BASE_URL"],- mock: [],-};-/*** Model and embedder defaults for init/sync triggered from the UI.*@@ -51,14 +34,17 @@ const EMBEDDER_ENV_VARS: Record<string, string[]> = {*/export function ProviderSection() {const t = useTranslations("settings");- const [provider, setProvider] = useState("gemini");+ // "" until a saved choice or the server's active one is known.+ const [provider, setProvider] = useState("");const [model, setModel] = useState("");- const [embedder, setEmbedder] = useState("mock");+ const [embedder, setEmbedder] = useState("");const [serverProvider, setServerProvider] = useState<string | null>(null);- // The server owns the catalog (it is derived from the provider specs), so- // this page keeps no copy of its own; until it loads, only the saved- // provider and the flag-only ones are offered.+ // The server owns the provider and embedder lists (derived from the core+ // registries), so this page keeps no copy; until they load, only the saved+ // choices are offered.const [catalog, setCatalog] = useState<ProviderInfo[]>([]);+ const [flagOnly, setFlagOnly] = useState<string[]>([]);+ const [embedders, setEmbedders] = useState<EmbedderInfo[]>([]);const [catalogFailed, setCatalogFailed] = useState(false);const [saveState, setSaveState] = useState<SaveState>("idle");@@ -70,10 +56,15 @@ export function ProviderSection() {setEmbedder(config.getEmbedder());let cancelled = false;void getProviders()- .then(({ active, providers: catalog }) => {+ .then(({ active, providers: catalog, flag_only_providers, embedders: embedderList }) => {if (cancelled) return;setServerProvider(active.provider);setCatalog((catalog ?? []).filter((entry) => entry.id));+ setFlagOnly(flag_only_providers ?? []);+ setEmbedders(embedderList ?? []);+ // Nothing saved: show what the server itself runs with.+ setProvider((saved) => saved || active.provider || "");+ setEmbedder((saved) => saved || active.embedder || "");}).catch((error: unknown) => {console.warn("[settings] Could not load the active server provider", error);@@ -119,11 +110,14 @@ export function ProviderSection() {// appear in it, and a saved provider the server has since stopped// advertising would leave a blank trigger with nothing to recover with.const providerOptions = [- ...new Set([...catalog.map((entry) => entry.id), ...FLAG_ONLY_PROVIDERS, provider]),- ];+ ...new Set([...catalog.map((entry) => entry.id), ...flagOnly, provider]),+ ].filter(Boolean);+ const embedderOptions = [+ ...new Set([...embedders.map((entry) => entry.id), embedder]),+ ].filter(Boolean);const providerInfo = catalog.find((entry) => entry.id === provider);- const embedderVars = EMBEDDER_ENV_VARS[embedder] ?? [];+ const embedderInfo = embedders.find((entry) => entry.id === embedder);return (<OverviewSection@@ -193,29 +187,29 @@ export function ProviderSection() {<SelectValue /></SelectTrigger><SelectContent>- {EMBEDDERS.map((e) => (+ {embedderOptions.map((e) => (<SelectItem key={e} value={e}>{e}</SelectItem>))}</SelectContent></Select>- {embedder === "mock" ? (+ {embedderInfo?.semantic === false ? (<EnvVarLinevars={[]}note={t.rich("provider.embedderOffNote", {code: (chunks) => <code className="font-mono text-[var(--color-text-secondary)]">{chunks}</code>,})}/>- ) : (+ ) : embedderInfo ? (<EnvVarLine- vars={embedderVars}+ vars={embedderInfo.env_vars ?? []}note={t.rich("provider.embedderOnNote", {code: (chunks) => <code className="font-mono text-[var(--color-text-secondary)]">{chunks}</code>,env: `REPOWISE_EMBEDDER=${embedder}`,})}/>- )}+ ) : null}</div></SettingsRow></SettingsRows>diff --git a/packages/web/src/lib/config.ts b/packages/web/src/lib/config.tsindex 9f6105f25..e8459b44a 100644--- a/packages/web/src/lib/config.ts+++ b/packages/web/src/lib/config.ts@@ -39,13 +39,14 @@ export const config = {getApiUrl: () => read(KEYS.apiUrl),setApiUrl: (v: string) => write(KEYS.apiUrl, v),- getProvider: () => read(KEYS.provider) || "litellm",+ /** "" when unset; the settings page then shows the server's active one. */+ getProvider: () => read(KEYS.provider),setProvider: (v: string) => write(KEYS.provider, v),getModel: () => read(KEYS.model),setModel: (v: string) => write(KEYS.model, v),- getEmbedder: () => read(KEYS.embedder) || "mock",+ getEmbedder: () => read(KEYS.embedder),setEmbedder: (v: string) => write(KEYS.embedder, v),/** Weekend-days preset id; "" means unset, which resolves to Sat/Sun. */diff --git a/tests/unit/cli/test_pricing_table_agreement.py b/tests/unit/cli/test_pricing_table_agreement.pyindex d621516f2..bdb4fd2ac 100644--- a/tests/unit/cli/test_pricing_table_agreement.py+++ b/tests/unit/cli/test_pricing_table_agreement.py@@ -22,7 +22,7 @@ from __future__ import annotationsimport pytest-from repowise.core.cost_estimator.pricing import _COST_TABLE_EXACT, _lookup_cost+from repowise.core.cost_estimator.pricing import _COST_TABLE_EXACT, lookup_costfrom repowise.core.generation.cost_tracker import _PRICING, get_model_pricing_SHARED_MODELS = sorted(set(_COST_TABLE_EXACT) & set(_PRICING))@@ -59,7 +59,7 @@ def test_the_two_tables_actually_overlap() -> None:@pytest.mark.parametrize("model", [_param(m) for m in _SHARED_MODELS])def test_estimate_and_live_counter_price_a_model_identically(model: str) -> None:"""Per-1K x 1000 must equal per-MTok, for both directions of the bill."""- est_input, est_output = _lookup_cost(model)+ est_input, est_output = lookup_cost(model)live = get_model_pricing(model)assert est_input * 1000 == pytest.approx(live["input"]), (diff --git a/tests/unit/server/test_provider_config.py b/tests/unit/server/test_provider_config.pyindex 33c03e785..a7adbe07b 100644--- a/tests/unit/server/test_provider_config.py+++ b/tests/unit/server/test_provider_config.py@@ -204,7 +204,7 @@ def test_list_provider_status_surfaces_custom_model(clean_env, tmp_path):status = pc.list_provider_status(repo_id="r1", repo_path=str(repo))- assert status["active"] == {"provider": "openai", "model": "gemma4"}+ assert (status["active"]["provider"], status["active"]["model"]) == ("openai", "gemma4")openai = next(p for p in status["providers"] if p["id"] == "openai")assert "gemma4" in openai["models"] # custom model is selectableassert openai["configured"] is True # key seen via repo .env@@ -315,6 +315,37 @@ def test_list_provider_status_carries_setup_facts_from_the_specs(clean_env, tmp_assert by_id["codex_cli"]["requires_key"] is Falseassert "codex login" in by_id["codex_cli"]["setup_hint"]assert "mock" not in by_id+ assert status["flag_only_providers"] == ["mock"]+++def test_list_provider_status_carries_the_embedder_registry(clean_env, tmp_path, monkeypatch):+ from repowise.core.providers.embedding import registry++ monkeypatch.setitem(registry._custom_embedders, "voyage", lambda **_kw: None)+ clean_env["REPOWISE_EMBEDDER"] = "Gemini"+ status = pc.list_provider_status()+ by_id = {e["id"]: e for e in status["embedders"]}++ assert set(by_id) == set(registry.list_embedders())+ assert status["embedders"][0]["id"] == registry.DEFAULT_EMBEDDER+ assert by_id["gemini"]["env_vars"] == ["GEMINI_API_KEY", "GOOGLE_API_KEY"]+ assert by_id["mock"] == {"id": "mock", "env_vars": [], "semantic": False}+ assert by_id["voyage"] == {"id": "voyage", "env_vars": [], "semantic": True}+ assert status["active"]["embedder"] == "gemini"+++def test_list_provider_status_prices_the_active_model(clean_env, tmp_path):+ from repowise.core.cost_estimator import lookup_cost++ def rates(provider, model):+ pc.set_active_provider(provider, model)+ active = pc.list_provider_status()["active"]+ return active["input_cost_per_1k"], active["output_cost_per_1k"]++ assert rates("openai", "gpt-5.4-mini") == lookup_cost("gpt-5.4-mini")+ # Unpriced is unknown, not free; a local model is free.+ assert rates("openai", "gpt-4o") == (None, None)+ assert rates("ollama", "qwen3.5:4b") == (0.0, 0.0)def test_list_provider_status_never_returns_key_material(clean_env, tmp_path):diff --git a/tests/unit/test_providers/test_claude_cli_provider.py b/tests/unit/test_providers/test_claude_cli_provider.pyindex b009a4fc3..43bf1b38a 100644--- a/tests/unit/test_providers/test_claude_cli_provider.py+++ b/tests/unit/test_providers/test_claude_cli_provider.py@@ -576,12 +576,12 @@ def test_registered_as_keyless_provider():def test_subscription_usage_is_priced_at_zero():"""A seat is not API spend; the bare `claude` prefixes would price it wrongly."""- from repowise.core.cost_estimator.pricing import _lookup_cost+ from repowise.core.cost_estimator.pricing import lookup_cost- assert _lookup_cost("claude_cli/claude-haiku-4-5") == (0.0, 0.0)- assert _lookup_cost("claude_cli/claude-opus-4-6") == (0.0, 0.0)+ assert lookup_cost("claude_cli/claude-haiku-4-5") == (0.0, 0.0)+ assert lookup_cost("claude_cli/claude-opus-4-6") == (0.0, 0.0)# The keyed API path is unaffected.- assert _lookup_cost("claude-haiku-4-5") != (0.0, 0.0)+ assert lookup_cost("claude-haiku-4-5") != (0.0, 0.0)def test_resolves_through_the_registry(claude_on_path):diff --git a/tests/unit/test_providers/test_cost_estimator.py b/tests/unit/test_providers/test_cost_estimator.pyindex cfd309e7b..8dbdaa4fd 100644--- a/tests/unit/test_providers/test_cost_estimator.py+++ b/tests/unit/test_providers/test_cost_estimator.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport pytest-from repowise.cli.cost_estimator import PageTypePlan, _lookup_cost, estimate_cost+from repowise.cli.cost_estimator import PageTypePlan, estimate_cost, lookup_costfrom repowise.cli.cost_estimator.heuristics import heuristic_tokens# ---------------------------------------------------------------------------@@ -19,8 +19,8 @@ from repowise.cli.cost_estimator.heuristics import heuristic_tokens("gpt-5.4-nano", 0.0002, 0.00125),("gpt-5.4-mini", 0.00075, 0.0045),("gpt-5.4", 0.0025, 0.015),- # The default. An unpriced model reads as free here (_lookup_cost- # falls through to (0.0, 0.0)), so this row is the guard.+ # The default. An unpriced model is estimated as free (lookup_cost+ # returns None), so this row is the guard.("gpt-5.6-luna", 0.0002, 0.0012),# Gemini("gemini-3.1-flash-lite-preview", 0.00025, 0.0015),@@ -39,7 +39,7 @@ from repowise.cli.cost_estimator.heuristics import heuristic_tokens],)def test_lookup_cost(model, expected_input, expected_output):- inp, out = _lookup_cost(model)+ inp, out = lookup_cost(model)assert inp == pytest.approx(expected_input, rel=1e-6)assert out == pytest.approx(expected_output, rel=1e-6)diff --git a/tests/unit/test_providers/test_provider_specs.py b/tests/unit/test_providers/test_provider_specs.pyindex fff2371e0..cd80fc3e4 100644--- a/tests/unit/test_providers/test_provider_specs.py+++ b/tests/unit/test_providers/test_provider_specs.py@@ -10,6 +10,7 @@ replaced drifted.from __future__ import annotationsimport ast+import reimport typesfrom pathlib import Path@@ -197,3 +198,49 @@ def test_the_guard_is_looking_at_real_sources():"""A glob that matched nothing, or a name set that emptied, passes vacuously."""assert len(_sources()) > 500assert {"claude_cli", "codex_cli", "opencode", "litellm", "openai"} <= _CHECKED+++# --- no provider or embedder lists in the web UI ----------------------------++#: A quoted provider/embedder name, or one used as an object key. The UI reads+#: these from ``/api/providers``; ``mock`` is checked here, unlike above.+_UI_NAME = re.compile(+ r"""["'](?P<q>{names})["']|^\s*(?P<k>{names})\s*:""".format(+ names="|".join(sorted(frozenset(PROVIDER_SPECS) | _EMBEDDERS, key=len, reverse=True))+ ),+ re.MULTILINE,+)+++def _ui_sources():+ return sorted(+ p+ for pkg in ("ui", "web", "api-client")+ for p in (_PACKAGES / pkg / "src").rglob("*.ts*")+ if p.suffix in {".ts", ".tsx"}+ and ".test." not in p.name+ and "__tests__" not in p.parts+ and "generated" not in p.parts+ )+++def test_no_ui_source_spells_a_provider_name():+ offenders = [+ f"{path.relative_to(_PACKAGES).as_posix()}:"+ f"{text.count(chr(10), 0, m.start()) + 1} {m.group('q') or m.group('k')!r}"+ for path in _ui_sources()+ for text in [path.read_text(encoding="utf-8")]+ for m in _UI_NAME.finditer(text)+ ]+ assert not offenders, f"provider names spelled in UI source; read /api/providers: {offenders}"+++ "snippet", ['x === "mock"', "['gemini', 'openai']", " ollama: [],", 'useState("litellm")']+)+def test_the_ui_guard_sees_each_shape(snippet):+ assert _UI_NAME.search(snippet)+++def test_the_ui_guard_is_looking_at_real_sources():+ assert len(_ui_sources()) > 200