Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(settings): run agents on several providers at once

rubenluetke10-beepd5c593a9a7ea
diff --git a/jarvis/agent_chat/agent_provider_prefs.py b/jarvis/agent_chat/agent_provider_prefs.py
new file mode 100644
index 0000000000..b4d8b16411
--- /dev/null
+++ b/jarvis/agent_chat/agent_provider_prefs.py
@@ -0,0 +1,131 @@
+"""Which providers and models the assistant's own agents may run on.
+
+The API Keys page turns providers on and off for the agents (any number at
+once — every connected seat is one more an agent can sit on) and hides
+models a person does not want offered. Three facts, one small JSON file in
+the user data folder:
+
+- ``disabled`` — catalog provider ids turned off for the agents. Absent
+ means on: connecting a provider is enough to offer it.
+- ``api_only`` — dual rows (one id for a subscription CLI AND an API key,
+ today ``claude-api``) the person set to run on the key instead of the
+ subscription.
+- ``hidden_models`` — per provider id, model ids left out of the pickers.
+
+Read on the agents' surface only (``surface="society"``): the coding panes
+and the front page's chat keep every seat they had.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import threading
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+#: The agents' surface; the only one these preferences narrow.
+AGENT_SURFACE = "society"
+
+_MAX_IDS = 256
+_MAX_ID_LEN = 200
+
+
+@dataclass(frozen=True)
+class AgentProviderPrefs:
+ disabled: frozenset[str] = frozenset()
+ api_only: frozenset[str] = frozenset()
+ hidden_models: dict[str, tuple[str, ...]] = field(default_factory=dict)
+
+ def enabled(self, provider_id: str) -> bool:
+ return provider_id not in self.disabled
+
+ def hidden(self, provider_id: str) -> tuple[str, ...]:
+ return self.hidden_models.get(provider_id, ())
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "disabled": sorted(self.disabled),
+ "api_only": sorted(self.api_only),
+ "hidden_models": {k: list(v) for k, v in sorted(self.hidden_models.items()) if v},
+ }
+
+
+_lock = threading.Lock()
+_cache: tuple[float, AgentProviderPrefs] | None = None
+
+
+def _path() -> Path:
+ from jarvis.core.paths import user_data_dir
+
+ return user_data_dir() / "agent_chat" / "agent_providers.json"
+
+
+def _ids(value: Any) -> list[str]:
+ if not isinstance(value, list):
+ return []
+ return [v for v in value if isinstance(v, str) and v and len(v) <= _MAX_ID_LEN][:_MAX_IDS]
+
+
+def parse(data: Any) -> AgentProviderPrefs:
+ """Tolerant of a hand-edited or older file: unknown shapes read as empty."""
+ if not isinstance(data, dict):
+ return AgentProviderPrefs()
+ raw_hidden = data.get("hidden_models")
+ hidden: dict[str, tuple[str, ...]] = {}
+ if isinstance(raw_hidden, dict):
+ for key, models in list(raw_hidden.items())[:_MAX_IDS]:
+ if isinstance(key, str) and key and len(key) <= _MAX_ID_LEN:
+ kept = tuple(dict.fromkeys(_ids(models)))
+ if kept:
+ hidden[key] = kept
+ return AgentProviderPrefs(
+ disabled=frozenset(_ids(data.get("disabled"))),
+ api_only=frozenset(_ids(data.get("api_only"))),
+ hidden_models=hidden,
+ )
+
+
+def load() -> AgentProviderPrefs:
+ """The saved preferences; re-read only when the file changed."""
+ global _cache
+ path = _path()
+ try:
+ mtime = path.stat().st_mtime
+ except FileNotFoundError: # never saved: every provider on, nothing hidden
+ return AgentProviderPrefs()
+ except OSError as exc:
+ logger.warning("agent providers: cannot stat {}: {}", path, exc)
+ return AgentProviderPrefs()
+ with _lock:
+ if _cache is not None and _cache[0] == mtime:
+ return _cache[1]
+ try:
+ prefs = parse(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError) as exc:
+ logger.warning("agent providers: unreadable {}: {}", path, exc)
+ return AgentProviderPrefs()
+ with _lock:
+ _cache = (mtime, prefs)
+ return prefs
+
+
+def save(prefs: AgentProviderPrefs) -> AgentProviderPrefs:
+ """Write atomically (tempfile + replace) and return what was stored."""
+ global _cache
+ path = _path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(prefs.to_dict(), indent=2), encoding="utf-8")
+ os.replace(tmp, path)
+ with _lock:
+ _cache = None
+ return prefs
+
+
+def forces_api(provider_id: str, surface: str) -> bool:
+ """Whether a dual row must run on its API key on ``surface``."""
+ return surface == AGENT_SURFACE and provider_id in load().api_only
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 82bba58361..1abd025d07 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -105,6 +105,12 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:
# is only reachable through a stale session or a hand-made request.
return api_runner if supports_api_runner(row.id) else "unknown"
if row.id == "claude-api":
+ # The API Keys page can set the agents' Claude to its key instead of
+ # the subscription; that choice narrows the agents' surface only.
+ from jarvis.agent_chat.agent_provider_prefs import forces_api
+
+ if forces_api(row.id, surface):
+ return api_runner
return "claude-cli" if _claude_cli_installed() else api_runner
if row.runner == "api":
return api_runner
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index a83b685270..fecea0f429 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -402,6 +402,11 @@ def _catalog_rows(
surface: str, live_models: dict[str, list[dict[str, Any]]]
) -> list[dict[str, Any]]:
"""The provider rows for ``surface`` with this machine's runner facts."""
+ from jarvis.agent_chat import agent_provider_prefs
+
+ # The agents' own seats carry the API Keys page's on/off and hidden
+ # models; their pickers filter on them. Other surfaces keep every seat.
+ prefs = agent_provider_prefs.load() if surface == agent_provider_prefs.AGENT_SURFACE else None
rows: list[dict[str, Any]] = []
for row in rows_for(surface):
d = row.to_dict()
@@ -432,6 +437,9 @@ def _catalog_rows(
# decided here, from the runner, so the box never offers a "/" list
# to a seat that would read it as plain text.
d["typeahead"] = list(typeahead.triggers_for(runner, surface))
+ if prefs is not None:
+ d["enabled"] = prefs.enabled(row.id)
+ d["hidden_models"] = list(prefs.hidden(row.id))
rows.append(d)
return rows
diff --git a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx
index 7daec1d497..d4cbf77f77 100644
--- a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx
@@ -53,8 +53,7 @@ it("requires an explicit thinking model and sends one coherent selection", async
);
const button = await screen.findByRole("button", { name: "live.save" });
expect((button as HTMLButtonElement).disabled).toBe(true);
- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));
- fireEvent.click(await screen.findByRole("option", { name: /Chosen/ }));
+ fireEvent.click(await screen.findByRole("radio", { name: /Chosen/ }));
fireEvent.click(button);
await waitFor(() => expect(requests).toHaveLength(1));
expect(requests[0]).toMatchObject({
@@ -87,13 +86,12 @@ it("recognizes a newly connected key without losing the user's model choice", as
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<QueryClientProvider client={client}><LiveProfile /></QueryClientProvider>);
const button = await screen.findByRole("button", { name: "live.save" });
- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));
- fireEvent.click(await screen.findByRole("option", { name: /Chosen/ }));
+ fireEvent.click(await screen.findByRole("radio", { name: /Chosen/ }));
expect((button as HTMLButtonElement).disabled).toBe(true);
keyReady = true;
fireEvent(window, new CustomEvent("jarvis:secret-configured"));
await waitFor(() => expect((button as HTMLButtonElement).disabled).toBe(false));
- expect(screen.getByRole("combobox", { name: "live.thinking_model" }).textContent).toContain("Chosen");
+ expect(screen.getByRole("radio", { name: /Chosen/ }).getAttribute("aria-checked")).toBe("true");
client.clear();
});
@@ -120,8 +118,7 @@ it("applies a new thinking model at once when Live is already set up", async ()
);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<QueryClientProvider client={client}><LiveProfile /></QueryClientProvider>);
- fireEvent.click(await screen.findByRole("combobox", { name: "live.thinking_model" }));
- fireEvent.click(await screen.findByRole("option", { name: /Cheap/ }));
+ fireEvent.click(await screen.findByRole("radio", { name: /Cheap/ }));
await waitFor(() => expect(requests).toHaveLength(1));
expect(requests[0]).toMatchObject({ backend_model: "cheap-model", configured: true });
client.clear();
@@ -168,8 +165,7 @@ function subscriptionSetup({ accountMode = "subscription", catalogFails = false,
}
async function selectSubscription() {
- fireEvent.click(await screen.findByRole("combobox", { name: "live.billing_method" }));
- fireEvent.click(await screen.findByRole("option", { name: "live.subscription_mode" }));
+ fireEvent.click(await screen.findByRole("radio", { name: "providers_page.access_subscription" }));
}
it("keeps hosted web search editable only for API mode and preserves its setting", async () => {
@@ -181,14 +177,12 @@ it("keeps hosted web search editable only for API mode and preserves its setting
await selectSubscription();
await screen.findByText("live.subscription_connected");
expect(screen.queryByRole("switch", { name: "live.web_search" })).toBeNull();
- await waitFor(() => expect((screen.getByRole("combobox", { name: "live.thinking_model" }) as HTMLButtonElement).disabled).toBe(false));
- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));
- fireEvent.click(await screen.findByRole("option", { name: /Subscription model/ }));
+ await waitFor(() => expect((screen.getByRole("radio", { name: /Subscription model/ }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(await screen.findByRole("radio", { name: /Subscription model/ }));
fireEvent.click(screen.getByRole("button", { name: "live.save" }));
await waitFor(() => expect(writes).toHaveLength(1));
expect(writes[0].web_search).toBe(false);
- fireEvent.click(screen.getByRole("combobox", { name: "live.billing_method" }));
- fireEvent.click(await screen.findByRole("option", { name: "live.api_key_mode" }));
+ fireEvent.click(screen.getByRole("radio", { name: "providers_page.access_api_key" }));
expect(screen.getByRole("switch", { name: "live.web_search" }).getAttribute("aria-checked")).toBe("false");
client.clear();
});
@@ -196,7 +190,7 @@ it("keeps hosted web search editable only for API mode and preserves its setting
it("opens a dedicated subscription row in its own mode without rewriting the stored API profile", async () => {
const { client, writes, onAuthModeChange } = subscriptionSetup({ selectedAuthMode: "chatgpt_subscription" });
await screen.findByText("live.subscription_connected");
- expect(screen.queryByRole("combobox", { name: "live.billing_method" })).toBeNull();
+ expect(screen.queryByRole("radiogroup", { name: "live.billing_method" })).toBeNull();
expect(screen.getByText("GPT Subscription")).toBeTruthy();
await waitFor(() => expect(screen.getByRole("combobox", { name: "live.voice" }).textContent).toContain("Cove"));
expect(onAuthModeChange).toHaveBeenLastCalledWith("chatgpt_subscription", true);
@@ -212,10 +206,9 @@ it("saves subscription voice without an API key and preserves the complete API s
expect(screen.getByText("live.subscription_voice_unverified")).toBeTruthy();
expect(screen.queryByText("live.key_required")).toBeNull();
expect(screen.queryByRole("button", { name: "live.use_for_agents" })).toBeNull();
- await waitFor(() => expect((screen.getByRole("combobox", { name: "live.thinking_model" }) as HTMLButtonElement).disabled).toBe(false));
- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));
- expect(screen.queryByRole("option", { name: /API model/ })).toBeNull();
- fireEvent.click(await screen.findByRole("option", { name: /Subscription model/ }));
+ await waitFor(() => expect((screen.getByRole("radio", { name: /Subscription model/ }) as HTMLButtonElement).disabled).toBe(false));
+ expect(screen.queryByRole("radio", { name: /API model/ })).toBeNull();
+ fireEvent.click(await screen.findByRole("radio", { name: /Subscription model/ }));
expect(writes).toHaveLength(0);
expect(onAuthModeChange).toHaveBeenLastCalledWith("chatgpt_subscription", true);
fireEvent.click(screen.getByRole("button", { name: "live.save" }));
@@ -228,10 +221,9 @@ it("saves subscription voice without an API key and preserves the complete API s
expect(fetcher.mock.calls.some(([path]) => path === "/api/live/options?auth_mode=chatgpt_subscription&account_id=codex%3Adefault")).toBe(true);
await screen.findByText("live.saved");
expect(onAuthModeChange).toHaveBeenLastCalledWith("chatgpt_subscription", false);
- fireEvent.click(screen.getByRole("combobox", { name: "live.billing_method" }));
- fireEvent.click(await screen.findByRole("option", { name: "live.api_key_mode" }));
+ fireEvent.click(screen.getByRole("radio", { name: "providers_page.access_api_key" }));
expect(screen.getByRole("combobox", { name: "live.voice" }).textContent).toContain("Gleam");
- expect(screen.getByRole("combobox", { name: "live.thinking_model" }).textContent).toContain("API model");
+ expect(screen.getByRole("radio", { name: /API model/ }).getAttribute("aria-checked")).toBe("true");
expect((screen.getByRole("button", { name: "live.save" }) as HTMLButtonElement).disabled).toBe(true);
expect(writes).toHaveLength(1);
client.clear();
@@ -251,9 +243,8 @@ it("does not treat a Codex API-key login as a ChatGPT subscription", async () =>
it("offers only the selected subscription model's advertised reasoning levels", async () => {
const { client, writes } = subscriptionSetup({ modelEfforts: ["low", "high", "max"] });
await selectSubscription();
- await waitFor(() => expect((screen.getByRole("combobox", { name: "live.thinking_model" }) as HTMLButtonElement).disabled).toBe(false));
- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));
- fireEvent.click(await screen.findByRole("option", { name: /Subscription model/ }));
+ await waitFor(() => expect((screen.getByRole("radio", { name: /Subscription model/ }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(await screen.findByRole("radio", { name: /Subscription model/ }));
expect(screen.getByRole("combobox", { name: "live.reasoning" }).textContent).toContain("live.model_default");
fireEvent.click(screen.getByRole("combobox", { name: "live.reasoning" }));
expect(screen.queryByRole("option", { name: "Medium" })).toBeNull();
@@ -270,9 +261,9 @@ it("keeps subscription selection when its catalog fails instead of using API opt
const { client, writes } = subscriptionSetup({ catalogFails: true });
await selectSubscription();
await screen.findByText("live.options_failed");
- expect((screen.getByRole("combobox", { name: "live.thinking_model" }) as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.queryByTestId("live-thinking-models")).toBeNull();
expect((screen.getByRole("button", { name: "live.save" }) as HTMLButtonElement).disabled).toBe(true);
- expect(screen.getByRole("combobox", { name: "live.billing_method" }).textContent).toContain("live.subscription_mode");
+ expect(screen.getByRole("radio", { name: "providers_page.access_subscription" }).getAttribute("aria-checked")).toBe("true");
expect(writes).toHaveLength(0);
client.clear();
});
diff --git a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx
index f903076c0e..1287ec5ccd 100644
--- a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx
@@ -7,7 +7,7 @@ import { BrandedSelect } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
-import { SettingsRow, SettingsSection } from "@/views/apikeys/settingsUi";
+import { ModelList, ModelListRow, Segmented, SettingsRow, SettingsSection } from "@/views/apikeys/settingsUi";
import { fetchAgentAccounts } from "@/lib/agentAccountsApi";
import { LiveSubscriptionAccount } from "./LiveSubscriptionAccount";
import { useRestartApp } from "@/hooks/useRestartApp";
@@ -269,16 +269,17 @@ export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode, keyFi
) : undefined}
>
<SettingsRow
- title={t("live.billing_method")}
+ title={t("providers_page.access_title")}
description={t(subscription ? "live.subscription_billing" : "live.billing")}
control={selectedAuthMode
? <span className="text-sm font-medium text-foreground">{subscription ? "GPT Subscription" : t("live.api_key_mode")}</span>
- : <BrandedSelect className="w-56" value={authMode} disabled={saving}
- ariaLabel={t("live.billing_method")}
- onValueChange={(mode) => update({ auth_mode: mode as LiveAuthMode })}
+ : <Segmented<LiveAuthMode> value={authMode} disabled={saving}
+ label={t("live.billing_method")}
+ testId="live-access"
+ onChange={(mode) => update({ auth_mode: mode })}
options={[
- { value: "chatgpt_subscription", label: t("live.subscription_mode") },
- { value: "api_key", label: t("live.api_key_mode") },
+ { value: "chatgpt_subscription", label: t("providers_page.access_subscription") },
+ { value: "api_key", label: t("providers_page.access_api_key") },
]} />}
/>
{!subscription && keyField}
@@ -330,23 +331,38 @@ export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode, keyFi
/>
</SettingsSection>
+ <SettingsSection title={t("live.thinking_model")} plain>
+ <div className="space-y-2.5">
+ <p className="px-1 text-xs text-muted-foreground/80">
+ {t(subscription ? "live.subscription_thinking_help" : "live.thinking_help")}
+ </p>
+ {modelOptions.length === 0 ? (
+ <div className="rounded-xl border border-border/60 bg-card/40 px-4 py-3 text-xs text-muted-foreground">
+ {options.isPending && options.fetchStatus !== "idle" ? t("live.loading") : t("live.choose_model")}
+ </div>
+ ) : (
+ <div role="radiogroup" aria-label={t("live.thinking_model")} data-testid="live-thinking-models">
+ <ModelList header={t("providers_page.thinking_pick")}>
+ {modelOptions.map((model) => (
+ <ModelListRow
+ key={model.value}
+ name={model.label}
+ id={model.hint || undefined}
+ selected={model.value === backendModel}
+ disabled={saving || (subscription && !options.data)}
+ onClick={() => chooseModel(model.value)}
+ control={model.value === backendModel
+ ? <Check aria-hidden="true" className="h-4 w-4 text-accent" />
+ : <span aria-hidden="true" className="h-4 w-4" />}
+ />
+ ))}
+ </ModelList>
+ </div>
+ )}
+ </div>
+ </SettingsSection>
+
<SettingsSection title={t("live.thinking_heading")}>
- <SettingsRow
- title={t("live.thinking_model")}
- description={t(subscription ? "live.subscription_thinking_help" : "live.thinking_help")}
- control={
- <BrandedSelect
- className="w-56"
- value={backendModel}
- disabled={saving || (subscription && !options.data)}
- onValueChange={chooseModel}
- ariaLabel={t("live.thinking_model")}
- placeholder={t("live.choose_model")}
- searchPlaceholder={t("live.search_models")}
- options={modelOptions}
- />
- }
- />
<SettingsRow
title={t("live.reasoning")}
control={
diff --git a/jarvis/ui/web/frontend/src/components/society/create/brainPicker.test.ts b/jarvis/ui/web/frontend/src/components/society/create/brainPicker.test.ts
index c1483473c4..ea69f47393 100644
--- a/jarvis/ui/web/frontend/src/components/society/create/brainPicker.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/create/brainPicker.test.ts
@@ -179,3 +179,34 @@ describe("brainSeats", () => {
expect(effortsFor(null, "pro")).toEqual([]);
});
});
+
+describe("brainSeats — the API Keys page's choices", () => {
+ it("leaves out a provider turned off for the agents", () => {
+ const seats = brainSeats(
+ [option({ id: "openai", label: "OpenAI", enabled: false }), option({ id: "gemini", label: "Google Gemini" })],
+ [],
+ );
+ expect(seats.map((s) => s.provider.id)).toEqual(["gemini"]);
+ });
+
+ it("leaves out hidden models, and the provider once every model is hidden", () => {
+ const seats = brainSeats(
+ [
+ option({ id: "openai", curated_models: [{ id: "a", label: "A" }, { id: "b", label: "B" }], hidden_models: ["a"] }),
+ option({ id: "gemini", label: "Google Gemini", curated_models: [{ id: "g", label: "G" }], hidden_models: ["g"] }),
+ ],
+ [],
+ );
+ expect(seats.map((s) => s.provider.id)).toEqual(["openai"]);
+ expect(seats[0].provider.curated_models.map((m) => m.id)).toEqual(["b"]);
+ });
+
+ it("hides models in a live list too", () => {
+ const seats = brainSeats(
+ [option({ id: "openai", hidden_models: ["old"] })],
+ [],
+ { openai: [{ id: "old", label: "Old" }, { id: "new", label: "New" }] },
+ );
+ expect(seats[0].provider.curated_models.map((m) => m.id)).toEqual(["new"]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/create/brainPicker.ts b/jarvis/ui/web/frontend/src/components/society/create/brainPicker.ts
index 0efc7a2309..6f2aec9c6a 100644
--- a/jarvis/ui/web/frontend/src/components/society/create/brainPicker.ts
+++ b/jarvis/ui/web/frontend/src/components/society/create/brainPicker.ts
@@ -61,15 +61,21 @@ export function brainSeats(
): BrainSeat[] {
const byId = new Map(society.map((r) => [r.id, r]));
return options
- .filter((o) => o.connected)
+ .filter((o) => o.connected && o.enabled !== false)
.filter((o) => !o.keyless || (liveModels[o.id]?.length ?? 0) > 0)
- .map((option) => {
+ .flatMap((option) => {
const live = liveModels[option.id];
- const provider = live?.length ? { ...option, curated_models: live } : option;
+ const listed = live?.length ? live : option.curated_models;
+ // Models hidden on the API Keys page stay out of the agents' pickers; a
+ // provider whose every model is hidden is not offered at all.
+ const hidden = new Set(option.hidden_models ?? []);
+ const models = hidden.size ? listed.filter((m) => !hidden.has(m.id)) : listed;
+ if (listed.length > 0 && models.length === 0) return [];
+ const provider = models !== option.curated_models ? { ...option, curated_models: models } : option;
const row = byId.get(provider.id);
const kind = kindOf(provider, row);
const accounts = kind === "subscription" ? (row?.accounts ?? []).filter((a) => a.connected) : [];
- return { provider, kind, accounts };
+ return [{ provider, kind, accounts }];
})
.filter((s) => s.kind !== "subscription" || s.accounts.length > 0 || known.has(s.provider.id))
.sort(
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json
index af146c13be..e1471a6049 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json
@@ -1,6 +1,6 @@
{
"providers_page": {
- "subtitle": "Die Live-Stimme läuft über OpenAI. Die Agenten laufen über jedes Abo oder jeden Schlüssel, den du hier verbindest.",
+ "subtitle": "Live-Gespräche laufen über OpenAI GPT-Live. Die Agenten laufen über jedes Abo und jeden Schlüssel, den du hier einschaltest.",
"checking": "Wird geprüft…",
"checked_now": "Gerade geprüft",
"checked_minutes": "Vor {0} Min. geprüft",
@@ -96,9 +96,8 @@
"restart_title": "Neu starten, um das Update abzuschließen",
"restart_desc": "Die neue Anbieter-Seite braucht einen Neustart des App-Hintergrunddienstes. Das dauert etwa zehn Sekunden.",
"restart_action": "Jetzt neu starten",
- "tab_voice": "Stimme",
+ "tab_voice": "Live-Gespräche",
"tab_agents": "Agenten",
- "tab_more": "Mehr",
"subscriptions_title": "Abos",
"keys_title": "API-Keys",
"authenticated": "Angemeldet",
@@ -117,6 +116,31 @@
"key_missing_short": "Kein Schlüssel",
"key_desc_short": "Ein Schlüssel für alles, was dieser Anbieter macht. Abrechnung pro Nutzung.",
"separate_title": "Eigene Schlüssel",
- "accounts_title": "Mehrere Anmeldungen pro Tool"
+ "accounts_title": "Mehrere Anmeldungen pro Tool" ,
+ "agent_providers_title": "Anbieter",
+ "access_title": "Zugang",
+ "access_desc": "Nutze dein Abo oder einen API-Schlüssel. Die Agenten laufen nur über den hier gewählten Zugang.",
+ "access_subscription": "Abo",
+ "access_api_key": "API-Schlüssel",
+ "access_local": "Dieser Computer",
+ "agents_needs_access": "Verbinde zuerst das Abo oder speichere einen Schlüssel.",
+ "local_title": "Auf diesem Computer",
+ "local_desc": "Die Agenten laufen mit lokalen Modellen. Kein Konto, kein Schlüssel, nichts verlässt diesen Computer.",
+ "default_title": "Standard für neue Aufgaben",
+ "default_desc": "Aufgaben, die {name} selbst abgibt, laufen hier. Jeder eingeschaltete Anbieter kann einen Agenten ausführen.",
+ "default_on": "Standard",
+ "default_make": "Als Standard",
+ "default_switched": "Neue Aufgaben laufen jetzt über {0}.",
+ "default_switched_restart": "Neue Aufgaben laufen nach dem nächsten Neustart über {0}.",
+ "models_title": "Modelle",
+ "models_count": "{0} von {1} Modellen für die Agenten",
+ "models_hide_all": "Alle aus",
+ "models_show_all": "Alle an",
+ "models_loading": "Modelle werden geladen…",
+ "models_none": "Dieser Anbieter nennt keine Modelle. Die Agenten nutzen sein Standardmodell.",
+ "models_reasoning": "Mit Denkstufen",
+ "thinking_pick": "Antwortet und nutzt Werkzeuge während eines Gesprächs",
+ "voice_ready": "Bereit",
+ "voice_not_ready": "Nicht eingerichtet"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json
index 417a3763d3..59053df64d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json
@@ -1,6 +1,6 @@
{
"providers_page": {
- "subtitle": "The live voice runs on OpenAI. The agents run on any subscription or key you connect here.",
+ "subtitle": "Live calls run on OpenAI GPT-Live. Agents run on every subscription or key you turn on here.",
"checking": "Checking…",
"checked_now": "Checked just now",
"checked_minutes": "Checked {0} min ago",
@@ -96,9 +96,8 @@
"restart_title": "Restart to finish the update",
"restart_desc": "The new provider page needs the app's background service to restart once. It takes about ten seconds.",
"restart_action": "Restart now",
- "tab_voice": "Voice",
+ "tab_voice": "Live calls",
"tab_agents": "Agents",
- "tab_more": "More",
"subscriptions_title": "Subscriptions",
"keys_title": "API keys",
"authenticated": "Authenticated",
@@ -117,6 +116,31 @@
"key_missing_short": "No key",
"key_desc_short": "One key for everything this provider does. Billed per use.",
"separate_title": "Separate keys",
- "accounts_title": "Several sign-ins per tool"
+ "accounts_title": "Several sign-ins per tool" ,
+ "agent_providers_title": "Providers",
+ "access_title": "Access",
+ "access_desc": "Use your subscription or an API key. The agents run only on the one picked here.",
+ "access_subscription": "Subscription",
+ "access_api_key": "API key",
+ "access_local": "This computer",
+ "agents_needs_access": "Connect the subscription or save a key first.",
+ "local_title": "On this computer",
+ "local_desc": "Agents run on local models. No account, no key, nothing leaves this computer.",
+ "default_title": "Default for new tasks",
+ "default_desc": "Tasks {name} hands off on its own go here. Every provider that is on can run an agent.",
+ "default_on": "Default",
+ "default_make": "Make default",
+ "default_switched": "New tasks now go to {0}.",
+ "default_switched_restart": "New tasks go to {0} after the next restart.",
+ "models_title": "Models",
+ "models_count": "{0} of {1} models offered to agents",
+ "models_hide_all": "Turn all off",
+ "models_show_all": "Turn all on",
+ "models_loading": "Loading models…",
+ "models_none": "This provider lists no models. Agents use its default model.",
+ "models_reasoning": "Reasoning",
+ "thinking_pick": "Answers and uses tools during a call",
+ "voice_ready": "Ready",
+ "voice_not_ready": "Not set up"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json
index 6e743c7fcf..ad427dbb3a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json
@@ -1,6 +1,6 @@
{
"providers_page": {
- "subtitle": "La voz en directo funciona con OpenAI. Los agentes funcionan con cualquier suscripción o clave que conectes aquí.",
+ "subtitle": "Las llamadas en directo funcionan con OpenAI GPT-Live. Los agentes funcionan con cada suscripción o clave que actives aquí.",
"checking": "Comprobando…",
"checked_now": "Comprobado ahora",
"checked_minutes": "Comprobado hace {0} min",
@@ -96,9 +96,8 @@
"restart_title": "Reinicia para terminar la actualización",
"restart_desc": "La nueva página de proveedores necesita reiniciar una vez el servicio de la app. Tarda unos diez segundos.",
"restart_action": "Reiniciar ahora",
- "tab_voice": "Voz",
+ "tab_voice": "Llamadas en directo",
"tab_agents": "Agentes",
- "tab_more": "Más",
"subscriptions_title": "Suscripciones",
"keys_title": "Claves API",
"authenticated": "Sesión iniciada",
@@ -117,6 +116,31 @@
"key_missing_short": "Sin clave",
"key_desc_short": "Una clave para todo lo que hace este proveedor. Se cobra por uso.",
"separate_title": "Claves propias",
- "accounts_title": "Varias sesiones por herramienta"
+ "accounts_title": "Varias sesiones por herramienta" ,
+ "agent_providers_title": "Proveedores",
+ "access_title": "Acceso",
+ "access_desc": "Usa tu suscripción o una clave API. Los agentes solo funcionan con el acceso elegido aquí.",
+ "access_subscription": "Suscripción",
+ "access_api_key": "Clave API",
+ "access_local": "Este ordenador",
+ "agents_needs_access": "Conecta primero la suscripción o guarda una clave.",
+ "local_title": "En este ordenador",
+ "local_desc": "Los agentes funcionan con modelos locales. Sin cuenta, sin clave, nada sale de este ordenador.",
+ "default_title": "Predeterminado para tareas nuevas",
+ "default_desc": "Las tareas que {name} delega por su cuenta van aquí. Cada proveedor activado puede ejecutar un agente.",
+ "default_on": "Predeterminado",
+ "default_make": "Hacer predeterminado",
+ "default_switched": "Las tareas nuevas ahora van a {0}.",
+ "default_switched_restart": "Las tareas nuevas irán a {0} tras el próximo reinicio.",
+ "models_title": "Modelos",
+ "models_count": "{0} de {1} modelos para los agentes",
+ "models_hide_all": "Desactivar todos",
+ "models_show_all": "Activar todos",
+ "models_loading": "Cargando modelos…",
+ "models_none": "Este proveedor no lista modelos. Los agentes usan su modelo predeterminado.",
+ "models_reasoning": "Razonamiento",
+ "thinking_pick": "Responde y usa herramientas durante una llamada",
+ "voice_ready": "Listo",
+ "voice_not_ready": "Sin configurar"
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index f9a7153b36..409423e3bf 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -61,6 +61,13 @@ export interface AgentChatProvider {
* Absent on an older backend: then nothing opens.
*/
typeahead?: string[];
+ /**
+ * The agents' surface only (`surface=society`): whether the API Keys page
+ * has this provider on for the agents, and the models it hid there.
+ * Absent elsewhere and on an older backend: on, nothing hidden.
+ */
+ enabled?: boolean;
+ hidden_models?: string[];
}
export interface AgentChatCatalog {
diff --git a/jarvis/ui/web/frontend/src/lib/agentProviderPrefs.ts b/jarvis/ui/web/frontend/src/lib/agentProviderPrefs.ts
new file mode 100644
index 0000000000..8d0a391d95
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/agentProviderPrefs.ts
@@ -0,0 +1,45 @@
+/**
+ * Which providers and models the assistant's agents may run on — mirror of
+ * `jarvis/agent_chat/agent_provider_prefs.py` (GET/PUT /api/society/provider-prefs).
+ *
+ * Every connected provider is on unless listed in `disabled`; a dual row in
+ * `api_only` runs on its key instead of the subscription; `hidden_models`
+ * leaves models out of the agents' pickers.
+ */
+export interface AgentProviderPrefs {
+ disabled: string[];
+ api_only: string[];
+ hidden_models: Record<string, string[]>;
+}
+
+export const EMPTY_AGENT_PROVIDER_PREFS: AgentProviderPrefs = { disabled: [], api_only: [], hidden_models: {} };
+
+export const AGENT_PROVIDER_PREFS_KEY = ["agent-provider-prefs"] as const;
+
+export async function fetchAgentProviderPrefs(): Promise<AgentProviderPrefs> {
+ const res = await fetch("/api/society/provider-prefs", { cache: "no-store" });
+ // An older backend has no such route: everything on, nothing hidden.
+ if (res.status === 404) return EMPTY_AGENT_PROVIDER_PREFS;
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return (await res.json()) as AgentProviderPrefs;
+}
+
+export async function saveAgentProviderPrefs(patch: Partial<AgentProviderPrefs>): Promise<AgentProviderPrefs> {
+ const res = await fetch("/api/society/provider-prefs", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(patch),
+ });
+ if (!res.ok) {
+ const detail = await res.json().catch(() => null);
+ throw new Error((detail && typeof detail.detail === "string" && detail.detail) || `HTTP ${res.status}`);
+ }
+ return (await res.json()) as AgentProviderPrefs;
+}
+
+/** `ids` added to (`on` = false) or taken out of (`on` = true) a list, order kept. */
+export function toggled(list: readonly string[], ids: readonly string[], on: boolean): string[] {
+ const drop = new Set(ids);
+ const kept = list.filter((id) => !drop.has(id));
+ return on ? kept : [...kept, ...ids];
+}
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx
index f6f48d2365..c729ad07eb 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx
@@ -1,6 +1,7 @@
/**
- * The provider page: a Voice tab on OpenAI GPT-Live, and an Agents tab with the
- * subscription logins and the API keys as lists beside their settings.
+ * The provider page: a Live calls tab on OpenAI GPT-Live, and an Agents tab
+ * with one entry per company — any number on at once, each reached by its
+ * subscription or its key — beside the selected company's settings.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
@@ -20,15 +21,12 @@ vi.mock("@/hooks/useVoiceMode", () => ({
// The sections below the providers own their data sources and have their own
// tests; here they only need to stay out of the way.
-vi.mock("@/views/settings/WikiProviderCard", () => ({ WikiProviderCard: () => null }));
-vi.mock("@/views/settings/JarvisApiGroup", () => ({ JarvisApiGroup: () => null }));
-vi.mock("@/views/settings/TeamProxyGroup", () => ({ TeamProxyGroup: () => null }));
-vi.mock("@/views/TelephonyView", () => ({ TelephonyPanel: () => null }));
vi.mock("@/components/AgentAccountsPanel", () => ({ AgentAccountsPanel: () => null }));
vi.mock("@/components/PromptWriterCard", () => ({ PromptWriterCard: () => null }));
vi.mock("@/components/SubagentModelCard", () => ({ SubagentModelCard: () => null }));
// GPT-Live's own form has its own tests; here it only has to place the key row.
-vi.mock("@/components/providers/LiveProfile", () => ({
+vi.mock("@/components/providers/LiveProfile", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/components/providers/LiveProfile")>()),
LiveProfile: ({ keyField }: { keyField?: React.ReactNode }) => <div data-testid="live-profile">{keyField}</div>,
}));
@@ -76,10 +74,33 @@ const CLAUDE_STATUS = {
version: "2.1.0", binary_path: "/usr/bin/claude",
};
+const CATALOG = {
+ providers: [
+ {
+ id: "claude-api", label: "Claude", family: "claude", runner: "claude-cli", models_source: "curated",
+ curated_models: [{ id: "opus", label: "Opus" }, { id: "sonnet", label: "Sonnet" }],
+ default_model: "", keyless: false, native_resume: true, effort_levels: [], default_effort: "",
+ permission_modes: [], default_permission_mode: "", cli_installed: true, enabled: true, hidden_models: [],
+ },
+ ],
+ default_cwd: "",
+ shell: "",
+};
+
+const LIVE = {
+ profile: {
+ auth_mode: "api_key", model: "gpt-live-1", voice: "gleam", backend_model: "", reasoning_effort: "medium",
+ web_search: true, instructions: "", backend_instructions: "", configured: false,
+ },
+ key_ready: false, active: false, agent_configured: false,
+};
+
let calls: { url: string; method: string; body: unknown }[] = [];
+let prefs: { disabled: string[]; api_only: string[]; hidden_models: Record<string, string[]> };
beforeEach(() => {
calls = [];
+ prefs = { disabled: [], api_only: [], hidden_models: {} };
_resetProvidersCacheForTests();
const routes: Record<string, unknown> = {
"/api/providers/families": { families: FAMILIES },
@@ -90,6 +111,9 @@ beforeEach(() => {
"/api/claude/status": CLAUDE_STATUS,
"/api/codex/status": null,
"/api/secrets/": { ok: true, key: "x", written: ["anthropic_api_key"] },
+ "/api/society/provider-prefs": prefs,
+ "/api/agent-chat/catalog": CATALOG,
+ "/api/live/profile": LIVE,
};
vi.stubGlobal(
"fetch",
@@ -133,31 +157,74 @@ beforeEach(() => {
}
});
-describe("ApiKeysView — Voice", () => {
- it("opens on the voice tab with one OpenAI key row", async () => {
+describe("ApiKeysView — Live calls", () => {
+ it("opens on live calls with GPT-Live in the list and one OpenAI key row", async () => {
renderPage();
const voice = await screen.findByTestId("apikeys-voice");
- expect(within(voice).getByTestId("voice-key")).toBeTruthy();
+ expect(within(voice).getByTestId("voice-provider-gpt-live").textContent).toContain("GPT-Live");
+ expect(await within(voice).findByTestId("voice-key")).toBeTruthy();
+ });
+
+ it("has only the two tabs", async () => {
+ renderPage();
+ await screen.findByTestId("apikeys-voice");
+ expect(screen.getAllByRole("tab").map((tab) => tab.textContent)).toEqual(["Live calls", "Agents"]);
});
});
describe("ApiKeysView — Agents", () => {
- it("lists the subscription logins with account and version", async () => {
+ it("lists each company once with its subscription account", async () => {
renderPage();
await screen.findByTestId("apikeys-voice");
openAgents();
- const claude = await screen.findByTestId("subscription-claude_cli");
- expect(claude.textContent).toContain("Claude");
+ const claude = await screen.findByTestId("agent-provider-claude-api");
+ expect(claude.textContent).toContain("Anthropic");
expect(claude.textContent).toContain("[email protected] · Claude Max");
expect(claude.textContent).toContain("v2.1.0");
+ expect(await screen.findByTestId("agent-provider-gemini")).toBeTruthy();
+ });
+
+ it("turns several companies on at once instead of switching between them", async () => {
+ Object.assign(prefs, { disabled: ["claude-api"], api_only: [] });
+ renderPage();
+ await screen.findByTestId("apikeys-voice");
+ openAgents();
+ const claude = await screen.findByTestId("agent-provider-claude-api");
+ const gemini = await screen.findByTestId("agent-provider-gemini");
+ await waitFor(() => expect(within(gemini).getByRole("switch").getAttribute("aria-checked")).toBe("true"));
+ await waitFor(() => expect((within(claude).getByRole("switch") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(within(claude).getByRole("switch"));
+ await waitFor(() => {
+ const put = calls.find((c) => c.method === "PUT" && c.url === "/api/society/provider-prefs");
+ expect(put?.body).toEqual({ disabled: [] });
+ });
+ // Gemini stays the default worker; turning Claude on never turns it off.
+ expect(calls.some((c) => c.url === "/api/jarvis-agent/switch")).toBe(false);
+ });
+
+ it("switches a company between its subscription and its key in one place", async () => {
+ renderPage();
+ await screen.findByTestId("apikeys-voice");
+ openAgents();
+ fireEvent.click(await screen.findByRole("button", { name: "Anthropic" }));
+ const access = await screen.findByTestId("agent-provider-access");
+ await waitFor(() =>
+ expect(within(access).getByRole("radio", { name: "Subscription" }).getAttribute("aria-checked")).toBe("true"),
+ );
+ expect(screen.queryByTestId("provider-key-input")).toBeNull();
+ fireEvent.click(within(access).getByRole("radio", { name: "API key" }));
+ await waitFor(() => {
+ const put = calls.find((c) => c.method === "PUT" && c.url === "/api/society/provider-prefs");
+ expect(put?.body).toEqual({ api_only: ["claude-api"], disabled: [] });
+ });
});
it("saves one key for the whole company", async () => {
+ Object.assign(prefs, { disabled: [], api_only: ["claude-api"] });
renderPage();
await screen.findByTestId("apikeys-voice");
openAgents();
- const list = await screen.findByTestId("api-key-list");
- fireEvent.click(within(list).getByRole("button", { name: "Anthropic" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Anthropic" }));
const input = await screen.findByTestId("provider-key-input");
fireEvent.change(input, { target: { value: "sk-ant-api03-test" } });
fireEvent.click(screen.getByTestId("provider-key-save"));
@@ -171,8 +238,7 @@ describe("ApiKeysView — Agents", () => {
renderPage();
await screen.findByTestId("apikeys-voice");
openAgents();
- const list = await screen.findByTestId("api-key-list");
- fireEvent.click(within(list).getByRole("button", { name: "Google Gemini" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Google Gemini" }));
const row = await screen.findByTestId("provider-separate-key-realtime_gemini_api_key");
fireEvent.click(within(row).getByRole("button"));
await waitFor(() =>
@@ -180,15 +246,19 @@ describe("ApiKeysView — Agents", () => {
);
});
- it("runs the agents on a subscription with its switch", async () => {
+ it("hides a model from the agents with its switch", async () => {
renderPage();
await screen.findByTestId("apikeys-voice");
openAgents();
- const claude = await screen.findByTestId("subscription-claude_cli");
- fireEvent.click(within(claude).getByRole("switch"));
+ fireEvent.click(await screen.findByRole("button", { name: "Anthropic" }));
+ const models = await screen.findByTestId("agent-models-claude-api");
+ await waitFor(() =>
+ expect((within(models).getByRole("switch", { name: "Sonnet" }) as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(within(models).getByRole("switch", { name: "Sonnet" }));
await waitFor(() => {
- const post = calls.find((c) => c.url === "/api/jarvis-agent/switch");
- expect(post?.body).toMatchObject({ provider: "claude-api" });
+ const put = calls.find((c) => c.method === "PUT" && c.url === "/api/society/provider-prefs");
+ expect(put?.body).toEqual({ hidden_models: { "claude-api": ["sonnet"] } });
});
});
@@ -196,8 +266,9 @@ describe("ApiKeysView — Agents", () => {
renderPage();
await screen.findByTestId("apikeys-voice");
openAgents();
- const detail = await screen.findByTestId("subscription-detail-claude_cli");
- expect(detail.textContent).toContain("[email protected]");
+ fireEvent.click(await screen.findByRole("button", { name: "Anthropic" }));
+ const detail = await screen.findByTestId("agent-provider-detail-claude-api");
+ await waitFor(() => expect(detail.textContent).toContain("[email protected]"));
expect(within(detail).getByTestId("subscription-disconnect")).toBeTruthy();
expect((within(detail).getByLabelText("Binary path") as HTMLInputElement).value).toBe("/usr/bin/claude");
});
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx
deleted file mode 100644
index d21e8ee6dc..0000000000
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * Component tests for the Telephony tier section embedded in ApiKeysView.
- *
- * Design (2026-06-09): the former standalone "Telephony" sidebar screen was
- * folded into the API-Keys view as another section (header + the existing
- * status/credentials/scripts/calls cards), shown on the page's "More" tab. These
- * tests pin that the section header renders and that the embedded TelephonyPanel
- * loads and shows live telephony data from /api/telephony/*.
- */
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { ApiKeysView } from "@/views/ApiKeysView";
-
-function renderView() {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- return render(
- <QueryClientProvider client={client}>
- <ApiKeysView />
- </QueryClientProvider>,
- );
-}
-import { useEventStore } from "@/store/events";
-
-// ApiKeysView now reads the live `[voice].mode` (for the Pipeline|Realtime
-// mode switch's "Active" badge only) via useVoiceMode, which needs a
-// QueryClientProvider. These tests render ApiKeysView standalone, so the
-// hook is mocked — the mode switch itself is exercised by
-// ApiKeysView.two-mode.test.tsx.
-vi.mock("@/hooks/useVoiceMode", () => ({
- useVoiceMode: () => ({
- mode: "pipeline",
- realtimeAvailable: false,
- setMode: vi.fn(),
- isLoading: false,
- isSaving: false,
- }),
-}));
-
-interface RouteResult {
- status?: number;
- body: unknown;
-}
-
-function installFetchMock(routes: Record<string, () => RouteResult>) {
- const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = String(input);
- const method = (init?.method ?? "GET").toUpperCase();
- const prefixes = Object.keys(routes).sort((a, b) => b.length - a.length);
- for (const prefix of prefixes) {
- if (url.startsWith(prefix)) {
- const { status = 200, body: resBody } = routes[prefix]();
- return {
- ok: status >= 200 && status < 300,
- status,
- statusText: status >= 200 && status < 300 ? "OK" : "ERR",
- json: async () => resBody,
- text: async () => JSON.stringify(resBody),
- } as Response;
- }
- }
- throw new Error(`unexpected fetch ${method} ${url}`);
- });
- (globalThis as unknown as { fetch: typeof fetch }).fetch =
- fetchMock as unknown as typeof fetch;
- Object.assign(navigator, {
- clipboard: { writeText: vi.fn(async () => undefined) },
- });
-}
-
-const GEMINI_BRAIN = {
- id: "gemini",
- label: "Google Gemini",
- tier: "brain",
- auth_mode: "api_key",
- secret_keys: ["gemini_api_key"],
- secrets_set: { gemini_api_key: true },
- dashboard_url: "https://aistudio.google.com/apikey",
- install_hint: null,
- credential_path_hint: null,
- configured: true,
- active: true,
-};
-
-const JARVIS_AGENT_EMPTY = {
- configured: true,
- enabled: false,
- binary_path: "",
- binary_detected: null,
- version_pin: null,
- time_cap_min: null,
- concurrency: null,
- state_dir_root: null,
- brain_primary: "gemini",
- provider_slug: null,
- model_override: null,
- model_resolved: null,
- mapping: [],
-};
-
-const TELEPHONY_STATUS_LIVE = {
- available: true,
- configured: true,
- enabled: true,
- account_sid_masked: "AC••••••cdef",
- phone_number: "+4930123456789",
- public_base_url: "https://jarvis.example.com",
- webhook_url: "https://jarvis.example.com/api/telephony/voice",
- auth_token_set: true,
- twilio_reachable: true,
- twilio_error: null,
- tts_provider: "gemini-flash-tts",
- tts_voice: "Charon",
- active_calls: 0,
- max_call_seconds: 600,
-};
-
-const TELEPHONY_CONFIG_LIVE = {
- enabled: true,
- account_sid: "AC0123456789abcdef0123456789abcdef",
- phone_number: "+4930123456789",
- public_base_url: "https://jarvis.example.com",
- greeting: "",
- language_code: "de-DE",
- fallback_mode: "media",
- max_call_seconds: 600,
- auth_token_set: true,
-};
-
-function routes(): Record<string, () => RouteResult> {
- return {
- "/api/providers": () => ({ body: { providers: [GEMINI_BRAIN] } }),
- "/api/providers/families": () => ({ body: { families: [] } }),
- "/api/jarvis-agent/status": () => ({ body: JARVIS_AGENT_EMPTY }),
- "/api/telephony/status": () => ({ body: TELEPHONY_STATUS_LIVE }),
- "/api/telephony/config": () => ({ body: TELEPHONY_CONFIG_LIVE }),
- "/api/telephony/scripts": () => ({ body: { scripts: [] } }),
- "/api/telephony/calls": () => ({ body: { calls: [] } }),
- };
-}
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-describe("ApiKeysView — embedded Telephony tier", () => {
- it("renders the Telephony tier header inside the API-Keys view", async () => {
- installFetchMock(routes());
- renderView();
- // Telephony lives on the page's "More" tab.
- fireEvent.click(await screen.findByRole("tab", { name: "More" }));
-
- // English is the test-default locale; tier_telephony => "Telephony".
- await waitFor(() => expect(screen.getByText("Telephony")).toBeTruthy());
- });
-
- it("loads live telephony status (Charon voice) from /api/telephony", async () => {
- installFetchMock(routes());
- renderView();
- // Telephony lives on the page's "More" tab.
- fireEvent.click(await screen.findByRole("tab", { name: "More" }));
-
- await waitFor(() => {
- expect(screen.getByTestId("status-tts-voice").textContent).toBe("Charon");
- });
- expect(screen.getByTestId("status-phone-number").textContent).toBe(
- "+4930123456789",
- );
- });
-
- it("offers a 'Setup script' button that navigates to the telephony-setup page", async () => {
- installFetchMock(routes());
- renderView();
- // Telephony lives on the page's "More" tab.
- fireEvent.click(await screen.findByRole("tab", { name: "More" }));
-
- const btn = await waitFor(() =>
- screen.getByRole("button", { name: /Setup script/i }),
- );
- fireEvent.click(btn);
- expect(useEventStore.getState().activeSection).toBe("telephony-setup");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 00bbfaa4e0..74614ca4f7 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -1,22 +1,20 @@
import { useEffect, useState } from "react";
-import { Loader2, Phone, RefreshCw } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { Check, Loader2, RefreshCw } from "lucide-react";
import { PageHeader } from "@/components/layout/PageHeader";
-import { LiveProfile } from "@/components/providers/LiveProfile";
+import { LiveProfile, liveProfileQuery, liveProfileReady } from "@/components/providers/LiveProfile";
+import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { Button } from "@/components/ui/button";
-import { TelephonyPanel } from "@/views/TelephonyView";
-import { WikiProviderCard } from "@/views/settings/WikiProviderCard";
-import { JarvisApiGroup } from "@/views/settings/JarvisApiGroup";
-import { TeamProxyGroup } from "@/views/settings/TeamProxyGroup";
import { AgentsTab } from "@/views/apikeys/AgentsTab";
import { KeyField } from "@/views/apikeys/KeyField";
-import { SettingsSection } from "@/views/apikeys/settingsUi";
+import { DetailHeader, ListRow, MasterDetail } from "@/views/apikeys/settingsUi";
import { useProviders, useSectionHealth } from "@/hooks/useProviders";
import { useProviderFamilies } from "@/lib/providerFamilies";
import { useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
-const TABS = ["voice", "agents", "more"] as const;
+const TABS = ["voice", "agents"] as const;
type Tab = (typeof TABS)[number];
const TAB_STORAGE_KEY = "jarvis.apikeys.tab";
@@ -31,13 +29,14 @@ function initialTab(): Tab {
}
/**
- * API Keys, in three parts behind one switch:
+ * API Keys, in two parts behind one centred switch, both as a provider list
+ * beside the selected provider's settings:
*
- * - Voice: the live voice runs on OpenAI GPT-Live — paid with the ChatGPT
- * subscription or one OpenAI key — with only its essential settings;
- * - Agents: the subscription logins and the API keys the background agents
- * can run on, each as a list beside the selected entry's settings;
- * - More: the install's own key and the optional integrations.
+ * - Live calls: the live voice runs on OpenAI GPT-Live — paid with the
+ * ChatGPT subscription or one OpenAI key — with its voice and the thinking
+ * model that answers with tools;
+ * - Agents: every company the assistant's agents can run on, any number of
+ * them on at once, each reached by its subscription or its API key.
*/
export function ApiKeysView() {
const t = useT();
@@ -87,7 +86,9 @@ export function ApiKeysView() {
</Button>
}
/>
- <TabSwitch value={tab} onChange={choose} />
+ <div className="flex justify-center">
+ <TabSwitch value={tab} onChange={choose} />
+ </div>
</div>
<div
@@ -102,7 +103,6 @@ export function ApiKeysView() {
) : (
<AgentsTab data={families} providers={providers} health={health} onProvidersChanged={refetch} />
))}
- {tab === "more" && <MoreTab />}
</div>
</div>
</div>
@@ -142,60 +142,65 @@ function TabSwitch({ value, onChange }: { value: Tab; onChange: (tab: Tab) => vo
}
/**
- * The live voice is OpenAI GPT-Live — the one live speech-to-speech model the
- * assistant runs — so this tab is that one provider: how it is paid for and
- * its essential settings.
+ * Live calls run on OpenAI GPT-Live — the one live speech-to-speech model the
+ * assistant runs — so the list holds that one provider, in the same list and
+ * detail layout as the Agents tab: how it is paid for, its voice and the
+ * thinking model that answers with tools.
*/
function VoiceTab({ data, onSaved }: { data: ReturnType<typeof useProviderFamilies>; onSaved: () => void }) {
+ const t = useT();
const openai = data.families?.find((family) => family.id === "openai");
const slot = openai?.key_slot ?? "openai_api_key";
+ const live = useQuery(liveProfileQuery);
+ const subscription = live.data?.profile.auth_mode === "chatgpt_subscription";
+ const ready = liveProfileReady(live.data);
+ const status = !live.data
+ ? t("live.loading")
+ : `${t(subscription ? "providers_page.access_subscription" : "providers_page.access_api_key")} · ${t(
+ ready ? "providers_page.voice_ready" : "providers_page.voice_not_ready",
+ )}`;
return (
- <div data-testid="apikeys-voice" className="max-w-4xl">
- <LiveProfile
- onSaved={onSaved}
- keyField={
- <KeyField
- slot={slot}
- present={openai?.key_present ?? false}
- providerLabel="OpenAI"
- dashboardUrl={openai?.dashboard_url}
- onChanged={() => void data.reload()}
- testId="voice-key"
+ <div data-testid="apikeys-voice">
+ <MasterDetail
+ testId="voice-provider-list"
+ list={
+ <ListRow
+ testId="voice-provider-gpt-live"
+ icon={<ProviderLogo providerId={openai?.logo_id ?? "openai"} label="OpenAI" size="sm" className="h-5 w-5" />}
+ name="GPT-Live"
+ status={status}
+ selected
+ dimmed={false}
+ onSelect={() => undefined}
+ trailing={ready ? <Check aria-label={t("providers_page.voice_ready")} className="h-4 w-4 text-accent" /> : null}
/>
}
+ detail={
+ <div className="space-y-2.5">
+ <DetailHeader
+ icon={<ProviderLogo providerId={openai?.logo_id ?? "openai"} label="OpenAI" size="sm" className="h-5 w-5" />}
+ name="GPT-Live · OpenAI"
+ />
+ <LiveProfile
+ onSaved={onSaved}
+ keyField={
+ <KeyField
+ slot={slot}
+ present={openai?.key_present ?? false}
+ providerLabel="OpenAI"
+ dashboardUrl={openai?.dashboard_url}
+ onChanged={() => void data.reload()}
+ testId="voice-key"
+ />
+ }
+ />
+ </div>
+ }
/>
</div>
);
}
-/** The install's own key and the optional integrations. */
-function MoreTab() {
- const t = useT();
- return (
- <div className="flex max-w-4xl flex-col gap-10">
- <SettingsSection title={t("apikeys_view.jarvis_key_title")} plain>
- <JarvisApiGroup />
- </SettingsSection>
- <SettingsSection title={t("apikeys_view.advanced_title")} plain>
- <div className="space-y-4">
- <TeamProxyGroup />
- <section>
- <h3 className="mb-3 inline-flex items-center gap-2 text-sm font-medium text-muted-foreground">
- <Phone aria-hidden="true" className="h-4 w-4" /> {t("apikeys_view.tier_telephony")}
- </h3>
- <TelephonyPanel />
- </section>
- <WikiProviderCard />
- </div>
- </SettingsSection>
- {/* Nominative-use trademark notice: provider and integration names and
- logos belong to their owners and only identify what you connect to
- (see TRADEMARK.md). */}
- <p className="px-1 text-xs text-muted-foreground">{t("apikeys_view.trademark_notice")}</p>
- </div>
- );
-}
-
/** "Checked 2 min ago", re-rendered every half minute. */
function CheckedAgo({ at }: { at: number | null }) {
const t = useT();
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx b/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx
index 3289b1eba1..43ca5dd408 100644
--- a/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, FlaskConical, Loader2, LogIn, LogOut } from "lucide-react";
import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";
import { PromptWriterCard } from "@/components/PromptWriterCard";
@@ -26,6 +27,15 @@ import {
type SectionHealth,
} from "@/hooks/useProviders";
import { useT } from "@/i18n";
+import { fetchAgentChatCatalog, fetchProviderModels, type CuratedModel } from "@/lib/agentChatApi";
+import {
+ AGENT_PROVIDER_PREFS_KEY,
+ EMPTY_AGENT_PROVIDER_PREFS,
+ fetchAgentProviderPrefs,
+ saveAgentProviderPrefs,
+ toggled,
+ type AgentProviderPrefs,
+} from "@/lib/agentProviderPrefs";
import {
pollUntilConnected,
subscriptionStatusUrl,
@@ -37,8 +47,18 @@ import {
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
import { KeyField } from "./KeyField";
+import { accessPatch, familyAccess, nextDefault, onPatch, withPatch, type Access, type FamilyAccess } from "./agentAccess";
import { familyState, type FamilyState } from "./providers/familyState";
-import { DetailHeader, ListRow, MasterDetail, SettingsRow, SettingsSection } from "./settingsUi";
+import {
+ DetailHeader,
+ ListRow,
+ MasterDetail,
+ ModelList,
+ ModelListRow,
+ Segmented,
+ SettingsRow,
+ SettingsSection,
+} from "./settingsUi";
type FamiliesData = ReturnType<typeof useProviderFamilies>;
@@ -60,47 +80,78 @@ export function shortVersion(raw: string | null | undefined): string | null {
return match ? `v${match[0]}` : raw;
}
+const SOCIETY_CATALOG_KEY = ["agent-chat", "catalog", "society"] as const;
+
/**
- * Switch the agents' worker. One worker runs them at a time, so turning one
- * on turns the previous one off — the switches in both lists move together.
+ * The agents' provider choices and the one action that changes them: save a
+ * patch, refresh every picker that reads them, and keep the default worker
+ * on a company that is still on.
*/
-function useAgentSwitch(onChanged: () => void | Promise<void>) {
+function useAgentProviders(entriesFor: (prefs: AgentProviderPrefs) => FamilyAccess[], primary: string, onChanged: () => Promise<void>) {
const t = useT();
+ const client = useQueryClient();
const pushToast = useEventStore((s) => s.pushToast);
- const [switching, setSwitching] = useState<string | null>(null);
-
- async function use(row: AgentRowStatus, label: string) {
- if (row.is_active_brain || switching) return;
- setSwitching(row.jarvis);
- window.dispatchEvent(
- new CustomEvent("jarvis:provider-selection-pending", { detail: { section: "subagents", provider: row.jarvis } }),
- );
+ const prefsQuery = useQuery({ queryKey: AGENT_PROVIDER_PREFS_KEY, queryFn: fetchAgentProviderPrefs, staleTime: 30_000 });
+ const prefs = prefsQuery.data ?? EMPTY_AGENT_PROVIDER_PREFS;
+ const [busy, setBusy] = useState<string | null>(null);
+
+ async function makeDefault(row: AgentRowStatus, label: string, quiet = false) {
+ window.dispatchEvent(new CustomEvent("jarvis:provider-selection-pending", { detail: { section: "subagents", provider: row.jarvis } }));
try {
const result = await switchSubagentProvider(row.jarvis);
- pushToast(
- "success",
- t(result.restart_required ? "providers_page.agents_switched_restart" : "providers_page.agents_switched").replace("{0}", label),
- );
+ if (!quiet || result.restart_required) {
+ pushToast(
+ "success",
+ t(result.restart_required ? "providers_page.default_switched_restart" : "providers_page.default_switched").replace("{0}", label),
+ );
+ }
window.dispatchEvent(new CustomEvent("jarvis:agent-switched"));
+ } catch (cause) {
+ window.dispatchEvent(new CustomEvent("jarvis:provider-switch-failed", { detail: { section: "subagents", provider: row.jarvis } }));
+ pushToast("error", (cause as Error).message);
+ }
+ }
+
+ async function save(familyId: string, patch: Partial<AgentProviderPrefs>) {
+ if (busy) return;
+ setBusy(familyId);
+ try {
+ const saved = await saveAgentProviderPrefs(patch);
+ client.setQueryData(AGENT_PROVIDER_PREFS_KEY, saved);
+ void client.invalidateQueries({ queryKey: SOCIETY_CATALOG_KEY });
+ void client.invalidateQueries({ queryKey: ["society", "providers"] });
+ const next = nextDefault(entriesFor(withPatch(prefs, saved)), primary, familyId);
+ if (next) await makeDefault(next, next.label ?? next.jarvis, true);
await onChanged();
} catch (cause) {
- window.dispatchEvent(
- new CustomEvent("jarvis:provider-switch-failed", { detail: { section: "subagents", provider: row.jarvis } }),
- );
pushToast("error", (cause as Error).message);
} finally {
- setSwitching(null);
+ setBusy(null);
+ }
+ }
+
+ async function chooseDefault(row: AgentRowStatus, label: string) {
+ if (busy) return;
+ setBusy(row.jarvis);
+ try {
+ await makeDefault(row, label);
+ await onChanged();
+ } finally {
+ setBusy(null);
}
}
- return { switching, use };
+ return { prefs, ready: prefsQuery.isSuccess, busy, save, chooseDefault };
}
+type AgentProviders = ReturnType<typeof useAgentProviders>;
+
/**
- * The Agents tab: which subscription or key runs the assistant's background
- * agents. Two lists in the same shape — the subscription logins, then the API
- * keys — each beside the selected entry's settings. The switch on a row is
- * "the agents run on this"; exactly one is on.
+ * The Agents tab: every company the assistant's agents can run on, as one
+ * list beside the selected company's settings. Any number of companies are
+ * on at once — each one connected is one more seat an agent can sit on.
+ * Inside a company the person picks how it is reached (subscription or API
+ * key) and which of its models the agents are offered.
*/
export function AgentsTab({
data,
@@ -119,37 +170,59 @@ export function AgentsTab({
onProvidersChanged();
await reload();
};
- const agentSwitch = useAgentSwitch(refresh);
const states = useMemo<Record<string, FamilyState>>(() => {
const ctx = { providers, subscriptions, agents, health };
return Object.fromEntries((families ?? []).map((f) => [f.id, familyState(f, ctx)]));
}, [families, providers, subscriptions, agents, health]);
+ const mapping = agents?.mapping ?? [];
+ // Companies that can run an agent, subscriptions first (a plan already paid
+ // for beats a metered key), this computer last.
+ const listed = useMemo(() => {
+ const rank = (f: ProviderFamily) => (f.local ? 2 : f.subscription ? 0 : 1);
+ return (families ?? [])
+ .filter((f) => mapping.some((row) => f.agent_ids.includes(row.jarvis)) && (f.subscription || f.key_slot || f.local))
+ .sort((a, b) => rank(a) - rank(b));
+ }, [families, mapping]);
+ const entriesFor = (prefs: AgentProviderPrefs) => listed.map((f) => familyAccess(f, mapping, prefs, states[f.id]));
+ const control = useAgentProviders(entriesFor, agents?.brain_primary ?? "", refresh);
+ const entries = entriesFor(control.prefs);
- const rowsOf = (family: ProviderFamily) =>
- (agents?.mapping ?? []).filter((row) => family.agent_ids.includes(row.jarvis));
- const subscriptionFamilies = (families ?? []).filter((f) => f.subscription);
- // A key list entry is a company that can run the agents on a key, plus the
- // machine itself (agents on a local model need no key at all).
- const keyFamilies = (families ?? []).filter(
- (f) => rowsOf(f).some((row) => row.billing !== "subscription") && (f.key_slot || f.local),
- );
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ useEffect(() => {
+ if (selectedId || !entries.length) return;
+ const primary = entries.find((fa) => fa.rows.some((row) => row.is_active_brain));
+ setSelectedId((primary ?? entries.find((fa) => fa.on) ?? entries[0]).family.id);
+ }, [entries, selectedId]);
+ const selected = entries.find((fa) => fa.family.id === selectedId) ?? null;
return (
- <div className="flex flex-col gap-10">
- <SubscriptionsSection
- families={subscriptionFamilies}
- states={states}
- rowsOf={rowsOf}
- agentSwitch={agentSwitch}
- onChanged={refresh}
- />
- <ApiKeysSection
- families={keyFamilies}
- states={states}
- rowsOf={rowsOf}
- agentSwitch={agentSwitch}
- onChanged={refresh}
- />
+ <div className="flex flex-col gap-10" data-testid="apikeys-agents">
+ <SettingsSection title={t("providers_page.agent_providers_title")} plain data-testid="agents-providers">
+ <MasterDetail
+ testId="agent-provider-list"
+ list={entries.map((fa) => (
+ <ProviderListRow
+ key={fa.family.id}
+ entry={fa}
+ state={states[fa.family.id]}
+ selected={fa.family.id === selectedId}
+ onSelect={() => setSelectedId(fa.family.id)}
+ control={control}
+ />
+ ))}
+ detail={
+ selected && states[selected.family.id] ? (
+ <ProviderDetail
+ key={selected.family.id}
+ entry={selected}
+ state={states[selected.family.id]}
+ control={control}
+ onChanged={refresh}
+ />
+ ) : null
+ }
+ />
+ </SettingsSection>
<AgentSettings />
<SettingsSection title={t("providers_page.accounts_title")} plain>
<AgentAccountsPanel />
@@ -158,121 +231,189 @@ export function AgentsTab({
);
}
-type AgentSwitch = ReturnType<typeof useAgentSwitch>;
+/** One entry per company, named and marked as the company, whichever access it uses. */
+function displayName(family: ProviderFamily): string {
+ return family.label;
+}
-/** The worker row a subscription login runs the agents through. */
-function subscriptionRow(_family: ProviderFamily, rows: AgentRowStatus[]): AgentRowStatus | undefined {
- return rows.find((row) => row.billing === "subscription" || row.billing === "subscription_or_api");
+function logoOf(family: ProviderFamily): string {
+ return family.logo_id;
+}
+
+/** The line under a company's name: how it is reached, or what it still needs. */
+function entryStatus(entry: FamilyAccess, state: FamilyState | undefined, t: (key: string) => string): string {
+ if (entry.access === "local") return t("providers_page.status_local");
+ if (entry.access === "subscription") {
+ if (!state?.subscription) return t("providers_page.subscription_unknown");
+ if (state.subscriptionOn) {
+ return state.account
+ ? t("providers_page.status_subscription_as").replace("{0}", state.account)
+ : t("providers_page.status_subscription");
+ }
+ if (!state.subscription.installed) return t("providers_page.not_installed");
+ return t("providers_page.not_signed_in");
+ }
+ if (entry.family.key_present) return t("providers_page.status_key");
+ if (state?.viaProject) return t("providers_page.status_project");
+ return t("providers_page.key_missing_short");
}
-/** The worker row a company key runs the agents through. */
-function keyRow(_family: ProviderFamily, rows: AgentRowStatus[]): AgentRowStatus | undefined {
- return rows.find((row) => row.billing === "api" || row.billing === "local") ?? rows.find((row) => row.billing === "subscription_or_api");
+function ProviderListRow({
+ entry,
+ state,
+ selected,
+ onSelect,
+ control,
+}: {
+ entry: FamilyAccess;
+ state: FamilyState | undefined;
+ selected: boolean;
+ onSelect: () => void;
+ control: AgentProviders;
+}) {
+ const t = useT();
+ const family = entry.family;
+ const name = displayName(family);
+ const label = t("providers_page.agents_use_for").replace("{0}", name);
+ return (
+ <ListRow
+ testId={`agent-provider-${family.id}`}
+ icon={<ProviderLogo providerId={logoOf(family)} label={name} size="sm" className="h-5 w-5" />}
+ name={name}
+ version={entry.access === "subscription" ? shortVersion(state?.subscription?.version) : null}
+ status={entryStatus(entry, state, t)}
+ dot={state?.failing ? "error" : null}
+ selected={selected}
+ dimmed={!entry.on}
+ onSelect={onSelect}
+ trailing={
+ <Switch
+ checked={entry.on}
+ disabled={!entry.ready || !control.ready || control.busy !== null}
+ onCheckedChange={(on) => void control.save(family.id, onPatch(entry, on, control.prefs))}
+ aria-label={label}
+ title={entry.ready ? label : t("providers_page.agents_needs_access")}
+ />
+ }
+ />
+ );
}
-function SubscriptionsSection({
- families,
- states,
- rowsOf,
- agentSwitch,
+function ProviderDetail({
+ entry,
+ state,
+ control,
onChanged,
}: {
- families: ProviderFamily[];
- states: Record<string, FamilyState>;
- rowsOf: (family: ProviderFamily) => AgentRowStatus[];
- agentSwitch: AgentSwitch;
+ entry: FamilyAccess;
+ state: FamilyState;
+ control: AgentProviders;
onChanged: () => Promise<void>;
}) {
const t = useT();
- const [selectedId, setSelectedId] = useState<string | null>(null);
- useEffect(() => {
- if (selectedId || !families.length) return;
- const active = families.find((f) => subscriptionRow(f, rowsOf(f))?.is_active_brain && states[f.id]?.subscriptionOn);
- setSelectedId((active ?? families.find((f) => states[f.id]?.subscriptionOn) ?? families[0]).id);
- }, [families, rowsOf, selectedId, states]);
- const selected = families.find((f) => f.id === selectedId) ?? null;
+ const family = entry.family;
+ const name = displayName(family);
+ const subscription = entry.access === "subscription";
+ const keyed = entry.access === "api_key";
+ const testCard = keyed
+ ? TEST_TIER_ORDER.map((tier) => state.members.find((m) => m.tier === tier && m.auth_mode === "api_key")).find(Boolean)
+ : undefined;
return (
- <SettingsSection title={t("providers_page.subscriptions_title")} plain data-testid="agents-subscriptions">
- <MasterDetail
- testId="subscription-list"
- list={families.map((family) => {
- const state = states[family.id];
- const kind = family.subscription!.kind;
- const row = subscriptionRow(family, rowsOf(family));
- const on = Boolean(row?.is_active_brain && state?.subscriptionOn);
- return (
- <ListRow
- key={family.id}
- testId={`subscription-${kind}`}
- icon={<ProviderLogo providerId={family.subscription!.provider_id} label={CLI[kind].name} size="sm" className="h-5 w-5" />}
- name={CLI[kind].name}
- version={shortVersion(state?.subscription?.version)}
- status={subscriptionStatus(state, t)}
- dot={state?.failing ? "error" : null}
- selected={family.id === selectedId}
- dimmed={!state?.subscriptionOn}
- onSelect={() => setSelectedId(family.id)}
- trailing={
- <Switch
- checked={on}
- disabled={!row || !state?.subscriptionOn || on || agentSwitch.switching !== null}
- onCheckedChange={(checked) => checked && row && void agentSwitch.use(row, CLI[kind].name)}
- aria-label={t("providers_page.agents_use_for").replace("{0}", CLI[kind].name)}
- title={t("providers_page.agents_use_for").replace("{0}", CLI[kind].name)}
+ <div data-testid={`agent-provider-detail-${family.id}`} className="space-y-6">
+ <div className="space-y-2.5">
+ <DetailHeader
+ icon={<ProviderLogo providerId={logoOf(family)} label={name} size="sm" className="h-5 w-5" />}
+ name={name}
+ version={subscription ? shortVersion(state.subscription?.version) : null}
+ />
+ <SettingsSectionCard>
+ {entry.choices.length > 1 && (
+ <SettingsRow
+ title={t("providers_page.access_title")}
+ description={t("providers_page.access_desc")}
+ control={
+ <Segmented<Access>
+ testId="agent-provider-access"
+ label={t("providers_page.access_title")}
+ value={entry.access}
+ disabled={!control.ready || control.busy !== null}
+ onChange={(access) => void control.save(family.id, accessPatch(entry, access, control.prefs))}
+ options={entry.choices.map((choice) => ({ value: choice, label: t(`providers_page.access_${choice}`) }))}
/>
}
/>
- );
- })}
- detail={
- selected && states[selected.id] ? (
- <SubscriptionDetail
- key={selected.id}
- family={selected}
- state={states[selected.id]}
- row={subscriptionRow(selected, rowsOf(selected))}
- agentSwitch={agentSwitch}
+ )}
+ {subscription && family.subscription && <SubscriptionAccountRow family={family} state={state} onChanged={onChanged} />}
+ {keyed && family.key_slot && (
+ <KeyField
+ slot={family.key_slot}
+ present={family.key_present}
+ providerLabel={family.label}
+ dashboardUrl={family.dashboard_url}
+ description={state.viaProject && !family.key_present ? t("providers_page.key_project_hint") : t("providers_page.key_desc_short")}
onChanged={onChanged}
/>
- ) : null
- }
- />
- </SettingsSection>
- );
-}
+ )}
+ {entry.access === "local" && (
+ <SettingsRow title={t("providers_page.local_title")} description={t("providers_page.local_desc")} />
+ )}
+ {entry.rows.map((row) => (
+ <DefaultRow
+ key={row.jarvis}
+ row={row}
+ label={family.local ? row.label ?? family.label : name}
+ entry={entry}
+ control={control}
+ />
+ ))}
+ {keyed && family.key_present && testCard && (
+ <SettingsRow
+ title={t("providers_page.key_test_label")}
+ description={t("providers_page.key_test_hint")}
+ control={<ProviderTestControl providerId={testCard.id} providerLabel={testCard.label} section={testCard.tier} active={testCard.active} />}
+ />
+ )}
+ </SettingsSectionCard>
+ </div>
-function subscriptionStatus(state: FamilyState | undefined, t: (key: string) => string): string {
- if (!state?.subscription) return t("providers_page.subscription_unknown");
- if (state.subscriptionOn) {
- return state.account
- ? t("providers_page.authenticated_as").replace("{0}", state.account)
- : t("providers_page.authenticated");
- }
- if (!state.subscription.installed) return t("providers_page.not_installed");
- return t("providers_page.not_signed_in");
+ {entry.rows.map((row) => (
+ <AgentModels
+ key={row.jarvis}
+ providerId={row.jarvis}
+ title={entry.rows.length > 1 ? `${t("providers_page.models_title")} · ${row.label ?? row.jarvis}` : t("providers_page.models_title")}
+ control={control}
+ familyId={family.id}
+ />
+ ))}
+
+ {subscription && family.subscription && state.subscription?.installed && (
+ <SettingsSection title={t("providers_page.runtime")}>
+ <BinaryPathRow
+ kind={family.subscription.kind}
+ path={"binary_path" in state.subscription ? state.subscription.binary_path ?? "" : ""}
+ onChanged={onChanged}
+ />
+ <SettingsRow
+ title={t("providers_page.cli_check")}
+ description={t("providers_page.cli_check_hint")}
+ control={<CliTest endpoint={CLI[family.subscription.kind].test} onChanged={onChanged} />}
+ />
+ </SettingsSection>
+ )}
+
+ {keyed && <SeparateKeys family={family} onChanged={onChanged} />}
+ </div>
+ );
}
-function SubscriptionDetail({
- family,
- state,
- row,
- agentSwitch,
- onChanged,
-}: {
- family: ProviderFamily;
- state: FamilyState;
- row: AgentRowStatus | undefined;
- agentSwitch: AgentSwitch;
- onChanged: () => Promise<void>;
-}) {
+function SubscriptionAccountRow({ family, state, onChanged }: { family: ProviderFamily; state: FamilyState; onChanged: () => Promise<void> }) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const kind = family.subscription!.kind;
const cli = CLI[kind];
const status = state.subscription;
const installed = status?.installed ?? false;
- const binary = status && "binary_path" in status ? status.binary_path ?? "" : "";
const card = state.members.find((m) => m.id === family.subscription!.provider_id);
const [pending, setPending] = useState<"login" | "waiting" | "logout" | null>(null);
@@ -306,59 +447,146 @@ function SubscriptionDetail({
}
}
+ const line = !state.subscription
+ ? t("providers_page.subscription_unknown")
+ : state.subscriptionOn
+ ? state.account
+ ? t("providers_page.authenticated_as").replace("{0}", state.account)
+ : t("providers_page.authenticated")
+ : !installed
+ ? card?.install_hint || t("providers_page.subscription_install")
+ : t("providers_page.not_signed_in");
+
return (
- <div data-testid={`subscription-detail-${kind}`} className="space-y-6">
- <div className="space-y-2.5">
- <DetailHeader
- icon={<ProviderLogo providerId={family.subscription!.provider_id} label={cli.name} size="sm" className="h-5 w-5" />}
- name={cli.name}
- version={shortVersion(status?.version)}
- />
- <SettingsSectionCard>
- <SettingsRow
- title={t("providers_page.account")}
- status={
- pending === "waiting"
- ? t(cli.where === "browser" ? "providers_page.login_waiting_browser" : "providers_page.login_waiting_terminal")
- : !installed && status
- ? card?.install_hint || t("providers_page.subscription_install")
- : subscriptionStatus(state, t)
- }
- control={
- state.subscriptionOn ? (
- <Button size="sm" variant="outline" data-testid="subscription-disconnect" disabled={pending !== null} onClick={() => void disconnect()}>
- {pending === "logout" ? <Loader2 className="animate-spin" /> : <LogOut />}
- {t("providers_page.disconnect")}
- </Button>
- ) : (
- <Button size="sm" data-testid="subscription-connect" disabled={pending !== null || !installed} onClick={() => void connect()}>
- {pending ? <Loader2 className="animate-spin" /> : <LogIn />}
- {t("providers_page.connect")}
- </Button>
- )
- }
- />
- <UseForAgentsRow
- row={row}
- label={cli.name}
- ready={state.subscriptionOn}
- hint={t("providers_page.agents_needs_login")}
- agentSwitch={agentSwitch}
- />
- </SettingsSectionCard>
- </div>
+ <SettingsRow
+ data-testid={`subscription-account-${kind}`}
+ title={t("providers_page.account")}
+ status={
+ pending === "waiting"
+ ? t(cli.where === "browser" ? "providers_page.login_waiting_browser" : "providers_page.login_waiting_terminal")
+ : line
+ }
+ control={
+ state.subscriptionOn ? (
+ <Button size="sm" variant="outline" data-testid="subscription-disconnect" disabled={pending !== null} onClick={() => void disconnect()}>
+ {pending === "logout" ? <Loader2 className="animate-spin" /> : <LogOut />}
+ {t("providers_page.disconnect")}
+ </Button>
+ ) : (
+ <Button size="sm" data-testid="subscription-connect" disabled={pending !== null || !installed} onClick={() => void connect()}>
+ {pending ? <Loader2 className="animate-spin" /> : <LogIn />}
+ {t("providers_page.connect")}
+ </Button>
+ )
+ }
+ />
+ );
+}
- {installed && (
- <SettingsSection title={t("providers_page.runtime")}>
- <BinaryPathRow kind={kind} path={binary} onChanged={onChanged} />
- <SettingsRow
- title={t("providers_page.cli_check")}
- description={t("providers_page.cli_check_hint")}
- control={<CliTest endpoint={cli.test} onChanged={onChanged} />}
- />
- </SettingsSection>
+/**
+ * Whether the tasks the assistant hands off by itself go here. Every company
+ * that is on can run an agent; one of them takes the tasks nobody assigned.
+ */
+function DefaultRow({ row, label, entry, control }: { row: AgentRowStatus; label: string; entry: FamilyAccess; control: AgentProviders }) {
+ const t = useT();
+ const isDefault = row.is_active_brain && entry.on;
+ return (
+ <SettingsRow
+ data-testid={`agent-default-row-${row.jarvis}`}
+ title={t("providers_page.default_title")}
+ description={t("providers_page.default_desc")}
+ status={!entry.ready ? t("providers_page.agents_needs_access") : undefined}
+ control={
+ isDefault ? (
+ <span className="inline-flex items-center gap-1.5 text-sm font-medium text-foreground">
+ <Check aria-hidden="true" className="h-4 w-4 text-accent" />
+ {t("providers_page.default_on")}
+ </span>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ data-testid={`agent-make-default-${row.jarvis}`}
+ disabled={!entry.on || control.busy !== null}
+ onClick={() => void control.chooseDefault(row, label)}
+ >
+ {control.busy === row.jarvis && <Loader2 className="animate-spin" />}
+ {t("providers_page.default_make")}
+ </Button>
+ )
+ }
+ />
+ );
+}
+
+/**
+ * The models a provider offers the agents, each with a switch: a model
+ * switched off is left out of every agent's model picker.
+ */
+function AgentModels({ providerId, title, control, familyId }: { providerId: string; title: string; control: AgentProviders; familyId: string }) {
+ const t = useT();
+ const catalog = useQuery({ queryKey: SOCIETY_CATALOG_KEY, queryFn: () => fetchAgentChatCatalog("society"), staleTime: 60_000 });
+ const row = catalog.data?.providers.find((p) => p.id === providerId);
+ const live = useQuery({
+ queryKey: ["society", "model-menu", "live", providerId],
+ queryFn: async (): Promise<CuratedModel[]> =>
+ (await fetchProviderModels(providerId)).map((model) => ({ id: model.id, label: model.label ?? model.name ?? model.id })),
+ enabled: row?.models_source === "live",
+ staleTime: 10 * 60_000,
+ retry: false,
+ });
+ if (!row) return null;
+ const models = [...new Map((row.models_source === "live" && live.data?.length ? live.data : row.curated_models)
+ .filter((model) => model.id)
+ .map((model) => [model.id, model])).values()];
+ const hidden = new Set(control.prefs.hidden_models[providerId] ?? []);
+ const shown = models.filter((model) => !hidden.has(model.id)).length;
+ const loading = row.models_source === "live" && live.isPending;
+ const setHidden = (ids: string[]) =>
+ void control.save(familyId, { hidden_models: { ...control.prefs.hidden_models, [providerId]: ids } });
+ const busy = !control.ready || control.busy !== null;
+
+ return (
+ <SettingsSection title={title} plain data-testid={`agent-models-${providerId}`}>
+ {models.length === 0 ? (
+ <div className="rounded-xl border border-border/60 bg-card/40 px-4 py-3 text-xs text-muted-foreground">
+ {loading ? t("providers_page.models_loading") : t("providers_page.models_none")}
+ </div>
+ ) : (
+ <ModelList
+ header={t("providers_page.models_count").replace("{0}", String(shown)).replace("{1}", String(models.length))}
+ action={
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7 text-xs"
+ disabled={busy}
+ onClick={() => setHidden(shown === 0 ? [] : models.map((model) => model.id))}
+ >
+ {shown === 0 ? t("providers_page.models_show_all") : t("providers_page.models_hide_all")}
+ </Button>
+ }
+ >
+ {models.map((model) => (
+ <ModelListRow
+ key={model.id}
+ name={model.label || model.id}
+ id={model.id}
+ note={model.note ?? (model.efforts?.length ? t("providers_page.models_reasoning") : null)}
+ muted={hidden.has(model.id)}
+ control={
+ <Switch
+ checked={!hidden.has(model.id)}
+ disabled={busy}
+ onCheckedChange={(on) => setHidden(toggled([...hidden], [model.id], on))}
+ aria-label={model.label || model.id}
+ />
+ }
+ />
+ ))}
+ </ModelList>
)}
- </div>
+ </SettingsSection>
);
}
@@ -453,154 +681,14 @@ function CliTest({ endpoint, onChanged }: { endpoint: string; onChanged: () => P
);
}
-function UseForAgentsRow({
- row,
- label,
- ready,
- hint,
- agentSwitch,
-}: {
- row: AgentRowStatus | undefined;
- label: string;
- ready: boolean;
- hint: string;
- agentSwitch: AgentSwitch;
-}) {
- const t = useT();
- if (!row) return null;
- const active = row.is_active_brain && ready;
- return (
- <SettingsRow
- data-testid={`agent-use-row-${row.jarvis}`}
- title={t("providers_page.agents_title")}
- description={t("providers_page.agents_desc")}
- status={!ready ? hint : undefined}
- control={
- active ? (
- <span className="inline-flex items-center gap-1.5 text-sm font-medium text-foreground">
- <Check aria-hidden="true" className="h-4 w-4 text-accent" />
- {t("providers_page.in_use")}
- </span>
- ) : (
- <Button
- size="sm"
- variant="outline"
- data-testid={`provider-agent-use-${row.jarvis}`}
- disabled={!ready || agentSwitch.switching !== null}
- onClick={() => void agentSwitch.use(row, label)}
- >
- {agentSwitch.switching === row.jarvis && <Loader2 className="animate-spin" />}
- {t("providers_page.agents_use")}
- </Button>
- )
- }
- />
- );
-}
-
-function ApiKeysSection({
- families,
- states,
- rowsOf,
- agentSwitch,
- onChanged,
-}: {
- families: ProviderFamily[];
- states: Record<string, FamilyState>;
- rowsOf: (family: ProviderFamily) => AgentRowStatus[];
- agentSwitch: AgentSwitch;
- onChanged: () => Promise<void>;
-}) {
- const t = useT();
- const [selectedId, setSelectedId] = useState<string | null>(null);
- useEffect(() => {
- if (selectedId || !families.length) return;
- const active = families.find((f) => {
- const row = keyRow(f, rowsOf(f));
- return row?.is_active_brain && (f.key_present || f.local);
- });
- setSelectedId((active ?? families.find((f) => f.key_present) ?? families[0]).id);
- }, [families, rowsOf, selectedId]);
- const selected = families.find((f) => f.id === selectedId) ?? null;
-
- const keyStatus = (family: ProviderFamily) => {
- const state = states[family.id];
- if (family.local) return t("providers_page.status_local");
- if (family.key_present) return t("providers_page.key_saved_short");
- if (state?.viaProject) return t("providers_page.status_project");
- return t("providers_page.key_missing_short");
- };
-
- return (
- <SettingsSection title={t("providers_page.keys_title")} plain data-testid="agents-api-keys">
- <MasterDetail
- testId="api-key-list"
- list={families.map((family) => {
- const row = keyRow(family, rowsOf(family));
- const ready = family.local || family.key_present || Boolean(states[family.id]?.viaProject);
- const on = Boolean(row?.is_active_brain) && ready && !(row?.billing === "subscription_or_api" && states[family.id]?.subscriptionOn);
- return (
- <ListRow
- key={family.id}
- testId={`provider-family-${family.id}`}
- icon={<ProviderLogo providerId={family.logo_id} label={family.label} size="sm" className="h-5 w-5" />}
- name={family.label}
- status={keyStatus(family)}
- dot={states[family.id]?.failing ? "error" : null}
- selected={family.id === selectedId}
- dimmed={!ready}
- onSelect={() => setSelectedId(family.id)}
- trailing={
- <Switch
- checked={on}
- disabled={!row || !ready || on || agentSwitch.switching !== null}
- onCheckedChange={(checked) => checked && row && void agentSwitch.use(row, family.label)}
- aria-label={t("providers_page.agents_use_for").replace("{0}", family.label)}
- title={t("providers_page.agents_use_for").replace("{0}", family.label)}
- />
- }
- />
- );
- })}
- detail={
- selected && states[selected.id] ? (
- <KeyDetail
- key={selected.id}
- family={selected}
- state={states[selected.id]}
- rows={rowsOf(selected)}
- agentSwitch={agentSwitch}
- onChanged={onChanged}
- />
- ) : null
- }
- />
- </SettingsSection>
- );
-}
-
const TEST_TIER_ORDER: ProviderDescriptor["tier"][] = ["brain", "realtime", "tts", "stt", "dictation"];
-function KeyDetail({
- family,
- state,
- rows,
- agentSwitch,
- onChanged,
-}: {
- family: ProviderFamily;
- state: FamilyState;
- rows: AgentRowStatus[];
- agentSwitch: AgentSwitch;
- onChanged: () => Promise<void>;
-}) {
+/** Features that still hold a key of their own, each with a way back onto the main key. */
+function SeparateKeys({ family, onChanged }: { family: ProviderFamily; onChanged: () => Promise<void> }) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const [merging, setMerging] = useState<string | null>(null);
- const testCard = TEST_TIER_ORDER.map((tier) => state.members.find((m) => m.tier === tier && m.auth_mode === "api_key")).find(Boolean);
- const ready = family.key_present || state.viaProject || family.local;
- // The machine itself can run the agents on more than one local server.
- const workerRows = family.local ? rows.filter((row) => row.billing === "local") : [keyRow(family, rows)].filter(Boolean) as AgentRowStatus[];
+ if (family.separate_keys.length === 0) return null;
async function merge(slot: string) {
setMerging(slot);
@@ -617,65 +705,28 @@ function KeyDetail({
}
return (
- <div data-testid={`provider-family-detail-${family.id}`} className="space-y-6">
- <div className="space-y-2.5">
- <DetailHeader icon={<ProviderLogo providerId={family.logo_id} label={family.label} size="sm" className="h-5 w-5" />} name={family.label} />
- <SettingsSectionCard>
- {family.key_slot && (
- <KeyField
- slot={family.key_slot}
- present={family.key_present}
- providerLabel={family.label}
- dashboardUrl={family.dashboard_url}
- description={state.viaProject && !family.key_present ? t("providers_page.key_project_hint") : t("providers_page.key_desc_short")}
- onChanged={onChanged}
- />
- )}
- {workerRows.map((row) => (
- <UseForAgentsRow
- key={row.jarvis}
- row={row}
- label={family.local ? row.label ?? family.label : family.label}
- ready={ready && !(row.billing === "subscription_or_api" && state.subscriptionOn && !family.key_present)}
- hint={t("providers_page.agents_needs_key")}
- agentSwitch={agentSwitch}
- />
- ))}
- {family.key_present && testCard && (
- <SettingsRow
- title={t("providers_page.key_test_label")}
- description={t("providers_page.key_test_hint")}
- control={<ProviderTestControl providerId={testCard.id} providerLabel={testCard.label} section={testCard.tier} active={testCard.active} />}
- />
- )}
- </SettingsSectionCard>
- </div>
-
- {family.separate_keys.length > 0 && (
- <SettingsSection title={t("providers_page.separate_title")}>
- {family.separate_keys.map((entry) => (
- <SettingsRow
- key={entry.slot}
- data-testid={`provider-separate-key-${entry.slot}`}
- title={t(`providers_page.separate_${entry.surface}`)}
- description={t("providers_page.separate_hint")}
- control={
- <Button
- size="sm"
- variant="outline"
- disabled={merging !== null || !family.key_present}
- title={family.key_present ? undefined : t("providers_page.separate_needs_main")}
- onClick={() => void merge(entry.slot)}
- >
- {merging === entry.slot && <Loader2 className="animate-spin" />}
- {t("providers_page.separate_merge")}
- </Button>
- }
- />
- ))}
- </SettingsSection>
- )}
- </div>
+ <SettingsSection title={t("providers_page.separate_title")}>
+ {family.separate_keys.map((entry) => (
+ <SettingsRow
+ key={entry.slot}
+ data-testid={`provider-separate-key-${entry.slot}`}
+ title={t(`providers_page.separate_${entry.surface}`)}
+ description={t("providers_page.separate_hint")}
+ control={
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={merging !== null || !family.key_present}
+ title={family.key_present ? undefined : t("providers_page.separate_needs_main")}
+ onClick={() => void merge(entry.slot)}
+ >
+ {merging === entry.slot && <Loader2 className="animate-spin" />}
+ {t("providers_page.separate_merge")}
+ </Button>
+ }
+ />
+ ))}
+ </SettingsSection>
);
}
@@ -691,7 +742,7 @@ function AgentSettings() {
const res = await fetch("/api/jarvis-agent/status", { cache: "no-store" });
if (res.ok) setStatus((await res.json()) as SubagentStatus);
} catch (cause) {
- // The model card stays hidden; the lists above report the same
+ // The model card stays hidden; the list above reports the same
// endpoint's failure.
console.debug("agent status unavailable", cause);
}
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/agentAccess.test.ts b/jarvis/ui/web/frontend/src/views/apikeys/agentAccess.test.ts
new file mode 100644
index 0000000000..32706a8903
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/apikeys/agentAccess.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from "vitest";
+
+import type { AgentProviderPrefs } from "@/lib/agentProviderPrefs";
+import type { AgentRowStatus, ProviderFamily } from "@/lib/providerFamilies";
+
+import { accessPatch, familyAccess, nextDefault, onPatch, withPatch } from "./agentAccess";
+import type { FamilyState } from "./providers/familyState";
+
+const NONE: AgentProviderPrefs = { disabled: [], api_only: [], hidden_models: {} };
+
+function family(over: Partial<ProviderFamily>): ProviderFamily {
+ return {
+ id: "openai", label: "OpenAI", logo_id: "openai", local: false, key_slot: "openai_api_key", key_present: true,
+ separate_keys: [], dashboard_url: null, signup_url: null,
+ subscription: { kind: "codex", provider_id: "openai-codex", label: "ChatGPT" },
+ provider_ids: [], hidden_ids: [], agent_ids: ["openai", "openai-codex"],
+ ...over,
+ };
+}
+
+function state(subscriptionOn: boolean): FamilyState {
+ return {
+ members: [], subscription: null, subscriptionOn, account: null, keyOn: true, viaProject: false,
+ connected: true, uses: [], canDo: [], failing: null,
+ };
+}
+
+const ROWS: AgentRowStatus[] = [
+ { jarvis: "openai", key_set: true, is_active_brain: false, billing: "api" },
+ { jarvis: "openai-codex", key_set: true, is_active_brain: true, billing: "subscription_or_api" },
+ { jarvis: "claude-api", key_set: true, is_active_brain: false, billing: "subscription_or_api" },
+ { jarvis: "ollama", key_set: true, keyless: true, is_active_brain: false, billing: "local" },
+ { jarvis: "local-openai", key_set: true, keyless: true, is_active_brain: false, billing: "local" },
+];
+
+const CLAUDE = family({
+ id: "claude-api", label: "Anthropic", key_slot: "anthropic_api_key",
+ subscription: { kind: "claude_cli", provider_id: "claude-cli", label: "Claude" }, agent_ids: ["claude-api", "claude-cli"],
+});
+const LOCAL = family({ id: "local", label: "This computer", local: true, key_slot: null, subscription: null, agent_ids: ["ollama", "local-openai"] });
+
+describe("familyAccess", () => {
+ it("uses a connected subscription first and is on by default", () => {
+ const fa = familyAccess(family({}), ROWS, NONE, state(true));
+ expect(fa.choices).toEqual(["subscription", "api_key"]);
+ expect(fa.access).toBe("subscription");
+ expect(fa.rows.map((r) => r.jarvis)).toEqual(["openai-codex"]);
+ expect(fa.on).toBe(true);
+ });
+
+ it("falls back to the key while the subscription is signed out", () => {
+ expect(familyAccess(family({}), ROWS, NONE, state(false)).access).toBe("api_key");
+ });
+
+ it("reads the picked access from which row is on", () => {
+ const fa = familyAccess(family({}), ROWS, { ...NONE, disabled: ["openai-codex"] }, state(true));
+ expect(fa.access).toBe("api_key");
+ expect(fa.on).toBe(true);
+ });
+
+ it("reads Claude's single row from api_only", () => {
+ expect(familyAccess(CLAUDE, ROWS, NONE, state(true)).access).toBe("subscription");
+ const keyed = familyAccess(CLAUDE, ROWS, { ...NONE, api_only: ["claude-api"] }, state(true));
+ expect(keyed.access).toBe("api_key");
+ expect(keyed.dual).toBe(true);
+ });
+
+ it("is off when the chosen access is not ready", () => {
+ const fa = familyAccess(family({ key_present: false }), ROWS, { ...NONE, disabled: ["openai-codex"] }, state(true));
+ expect(fa.access).toBe("api_key");
+ expect(fa.ready).toBe(false);
+ expect(fa.on).toBe(false);
+ });
+});
+
+describe("patches", () => {
+ it("turning a company off disables every row; on enables only the chosen one", () => {
+ const fa = familyAccess(family({}), ROWS, NONE, state(true));
+ expect(onPatch(fa, false, NONE)).toEqual({ disabled: ["openai-codex", "openai"] });
+ const off = { ...NONE, disabled: ["openai", "openai-codex", "grok"] };
+ expect(onPatch(familyAccess(family({}), ROWS, off, state(true)), true, off)).toEqual({ disabled: ["grok", "openai"] });
+ });
+
+ it("switching access disables the other row, or flips Claude's api_only", () => {
+ const fa = familyAccess(family({}), ROWS, NONE, state(true));
+ expect(accessPatch(fa, "api_key", NONE)).toEqual({ disabled: ["openai-codex"] });
+ const claude = familyAccess(CLAUDE, ROWS, NONE, state(true));
+ expect(accessPatch(claude, "api_key", NONE)).toEqual({ api_only: ["claude-api"], disabled: [] });
+ });
+
+ it("this computer turns its local rows on and off together", () => {
+ const fa = familyAccess(LOCAL, ROWS, NONE, undefined);
+ expect(fa.access).toBe("local");
+ expect(fa.rows.map((r) => r.jarvis)).toEqual(["ollama", "local-openai"]);
+ expect(onPatch(fa, false, NONE)).toEqual({ disabled: ["ollama", "local-openai"] });
+ });
+});
+
+describe("nextDefault", () => {
+ it("keeps the default while its company is on", () => {
+ const entries = [familyAccess(family({}), ROWS, NONE, state(true))];
+ expect(nextDefault(entries, "openai-codex")).toBeNull();
+ });
+
+ it("moves the default to the same company's other access first", () => {
+ const prefs = withPatch(NONE, { disabled: ["openai-codex"] });
+ const entries = [familyAccess(CLAUDE, ROWS, prefs, state(true)), familyAccess(family({}), ROWS, prefs, state(true))];
+ expect(nextDefault(entries, "openai-codex", "openai")?.jarvis).toBe("openai");
+ });
+
+ it("moves it to the first company still on when one is turned off", () => {
+ const prefs = withPatch(NONE, { disabled: ["openai", "openai-codex"] });
+ const entries = [familyAccess(family({}), ROWS, prefs, state(true)), familyAccess(CLAUDE, ROWS, prefs, state(true))];
+ expect(nextDefault(entries, "openai-codex", "openai")?.jarvis).toBe("claude-api");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/agentAccess.ts b/jarvis/ui/web/frontend/src/views/apikeys/agentAccess.ts
new file mode 100644
index 0000000000..d98986a9ee
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/apikeys/agentAccess.ts
@@ -0,0 +1,138 @@
+/**
+ * How one company reaches the assistant's agents, and what turning it on or
+ * off — or switching it between subscription and API key — saves.
+ *
+ * A company is one entry on the Agents tab. It may run the agents through a
+ * subscription login (a vendor CLI), an API key, or this computer. Several
+ * companies are on at once; inside one company exactly one access is used.
+ * The choices live in `AgentProviderPrefs` as worker-row ids:
+ *
+ * - two rows (OpenAI: `openai-codex` + `openai`): the access is the row that
+ * is not disabled, so a switch disables the other one;
+ * - one dual row (Claude: `claude-api` for both): the access is whether the
+ * row is in `api_only`;
+ * - this computer: every local row is on or off together.
+ *
+ * Pure: unit-tested with plain rows.
+ */
+import type { AgentProviderPrefs } from "@/lib/agentProviderPrefs";
+import { toggled } from "@/lib/agentProviderPrefs";
+import type { AgentRowStatus, ProviderFamily } from "@/lib/providerFamilies";
+import type { FamilyState } from "./providers/familyState";
+
+export type Access = "subscription" | "api_key" | "local";
+
+export interface FamilyAccess {
+ family: ProviderFamily;
+ /** The worker row a subscription login runs the agents through. */
+ subRow?: AgentRowStatus;
+ /** The worker row a company key runs the agents through. */
+ keyRow?: AgentRowStatus;
+ /** This computer's rows (Ollama, a local server). */
+ localRows: AgentRowStatus[];
+ /** One row serves both the subscription and the key. */
+ dual: boolean;
+ choices: Access[];
+ access: Access;
+ /** The rows the chosen access runs on (one, or every local row). */
+ rows: AgentRowStatus[];
+ /** The chosen access can run an agent right now. */
+ ready: boolean;
+ /** On for the agents: chosen, ready and not turned off. */
+ on: boolean;
+}
+
+function subscriptionRow(rows: AgentRowStatus[]): AgentRowStatus | undefined {
+ return rows.find((row) => row.billing === "subscription" || row.billing === "subscription_or_api");
+}
+
+function apiRow(rows: AgentRowStatus[]): AgentRowStatus | undefined {
+ return rows.find((row) => row.billing === "api") ?? rows.find((row) => row.billing === "subscription_or_api");
+}
+
+export function accessReady(access: Access, family: ProviderFamily, state: FamilyState | undefined): boolean {
+ if (access === "local") return true;
+ if (access === "subscription") return Boolean(state?.subscriptionOn);
+ return family.key_present || Boolean(state?.viaProject);
+}
+
+export function familyAccess(
+ family: ProviderFamily,
+ allRows: AgentRowStatus[],
+ prefs: AgentProviderPrefs,
+ state: FamilyState | undefined,
+): FamilyAccess {
+ const rows = allRows.filter((row) => family.agent_ids.includes(row.jarvis));
+ const localRows = family.local ? rows.filter((row) => row.billing === "local") : [];
+ const subRow = family.subscription ? subscriptionRow(rows) : undefined;
+ const keyRow = !family.local && family.key_slot ? apiRow(rows) : undefined;
+ const dual = Boolean(subRow && keyRow && subRow.jarvis === keyRow.jarvis);
+ const choices: Access[] = family.local
+ ? ["local"]
+ : [...(subRow ? (["subscription"] as const) : []), ...(keyRow ? (["api_key"] as const) : [])];
+ const disabled = new Set(prefs.disabled);
+
+ let access: Access = choices[0] ?? "api_key";
+ if (subRow && keyRow) {
+ if (dual) {
+ access = prefs.api_only.includes(keyRow.jarvis) ? "api_key" : "subscription";
+ } else {
+ const subOn = !disabled.has(subRow.jarvis);
+ const keyOn = !disabled.has(keyRow.jarvis);
+ if (subOn !== keyOn) access = subOn ? "subscription" : "api_key";
+ else if (state?.subscriptionOn) access = "subscription";
+ else access = accessReady("api_key", family, state) ? "api_key" : "subscription";
+ }
+ }
+
+ const chosen = access === "local" ? localRows : [access === "subscription" ? subRow : keyRow].filter(Boolean) as AgentRowStatus[];
+ const ready = chosen.length > 0 && accessReady(access, family, state);
+ const on = ready && chosen.some((row) => !disabled.has(row.jarvis));
+ return { family, subRow, keyRow, localRows, dual, choices, access, rows: chosen, ready, on };
+}
+
+function allIds(fa: FamilyAccess): string[] {
+ return [...new Set([fa.subRow, fa.keyRow, ...fa.localRows].filter(Boolean).map((row) => row!.jarvis))];
+}
+
+/** What turning the company on or off saves. */
+export function onPatch(fa: FamilyAccess, on: boolean, prefs: AgentProviderPrefs): Partial<AgentProviderPrefs> {
+ if (!on) return { disabled: toggled(prefs.disabled, allIds(fa), false) };
+ const chosen = fa.rows.map((row) => row.jarvis);
+ const others = allIds(fa).filter((id) => !chosen.includes(id));
+ return { disabled: toggled(toggled(prefs.disabled, others, false), chosen, true) };
+}
+
+/** What switching the company to `access` saves; the company is on afterwards. */
+export function accessPatch(fa: FamilyAccess, access: Access, prefs: AgentProviderPrefs): Partial<AgentProviderPrefs> {
+ if (fa.dual && fa.keyRow) {
+ const id = fa.keyRow.jarvis;
+ return {
+ api_only: toggled(prefs.api_only, [id], access !== "api_key"),
+ disabled: toggled(prefs.disabled, [id], true),
+ };
+ }
+ const target = access === "subscription" ? fa.subRow : fa.keyRow;
+ const other = access === "subscription" ? fa.keyRow : fa.subRow;
+ if (!target) return {};
+ return {
+ disabled: toggled(toggled(prefs.disabled, other ? [other.jarvis] : [], false), [target.jarvis], true),
+ };
+}
+
+/**
+ * Where the tasks the assistant hands off go once `entries` are saved: the
+ * current default while it is still on, else the first company that is on
+ * (`prefer` first — the one just changed), else nothing to change.
+ */
+export function nextDefault(entries: FamilyAccess[], current: string, prefer?: string): AgentRowStatus | null {
+ const live = entries.filter((fa) => fa.on).flatMap((fa) => fa.rows);
+ if (live.some((row) => row.jarvis === current)) return null;
+ const preferred = entries.find((fa) => fa.family.id === prefer && fa.on)?.rows[0];
+ return preferred ?? live[0] ?? null;
+}
+
+/** Saved prefs with `patch` applied, for computing the state that follows a save. */
+export function withPatch(prefs: AgentProviderPrefs, patch: Partial<AgentProviderPrefs>): AgentProviderPrefs {
+ return { ...prefs, ...patch };
+}
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsx b/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsx
index f1d9ce0039..594f347f9d 100644
--- a/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsx
+++ b/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsx
@@ -195,6 +195,135 @@ export function ListRow({
);
}
+/**
+ * A small segmented choice ("Subscription | API key"). Each option is a radio:
+ * exactly one is picked, and arrow keys are not needed for two or three.
+ */
+export function Segmented<T extends string>({
+ value,
+ options,
+ onChange,
+ label,
+ disabled,
+ testId,
+}: {
+ value: T;
+ options: { value: T; label: string; disabled?: boolean }[];
+ onChange: (value: T) => void;
+ label: string;
+ disabled?: boolean;
+ testId?: string;
+}) {
+ return (
+ <div
+ role="radiogroup"
+ aria-label={label}
+ data-testid={testId}
+ className="inline-flex shrink-0 rounded-lg border border-border/60 bg-card/40 p-0.5"
+ >
+ {options.map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={value === option.value}
+ disabled={disabled || option.disabled}
+ onClick={() => value !== option.value && onChange(option.value)}
+ className={cn(
+ "h-7 rounded-md px-3 text-sm font-medium transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
+ value === option.value ? "bg-secondary text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * A list of models inside a section card: name, id, a short note, and one
+ * control per row (a visibility switch, or the pick mark of a single choice).
+ * The header line carries a count and an optional bulk action.
+ */
+export function ModelList({
+ header,
+ action,
+ children,
+ testId,
+}: {
+ header: ReactNode;
+ action?: ReactNode;
+ children: ReactNode;
+ testId?: string;
+}) {
+ return (
+ <SettingsGroup divided={false} data-testid={testId}>
+ <div className="flex min-h-10 items-center justify-between gap-4 border-b border-border/50 px-4 py-2 text-xs text-muted-foreground">
+ <span>{header}</span>
+ {action}
+ </div>
+ <ul className="max-h-[22rem] overflow-y-auto py-1 scrollbar-jarvis">{children}</ul>
+ </SettingsGroup>
+ );
+}
+
+export function ModelListRow({
+ name,
+ id,
+ note,
+ control,
+ muted,
+ onClick,
+ selected,
+ disabled,
+}: {
+ name: string;
+ id?: string;
+ note?: string | null;
+ control: ReactNode;
+ muted?: boolean;
+ /** A single-choice list makes the whole row the hit target. */
+ onClick?: () => void;
+ selected?: boolean;
+ disabled?: boolean;
+}) {
+ const body = (
+ <>
+ <span className={cn("flex min-w-0 flex-1 items-baseline gap-2", muted && "opacity-60")}>
+ <span className="truncate text-sm text-foreground">{name}</span>
+ {id && id !== name ? <code className="truncate text-xs text-muted-foreground">{id}</code> : null}
+ </span>
+ {note ? <span className="hidden shrink-0 text-xs text-muted-foreground sm:inline">{note}</span> : null}
+ <span className="flex h-5 shrink-0 items-center">{control}</span>
+ </>
+ );
+ return (
+ <li>
+ {onClick ? (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={Boolean(selected)}
+ aria-label={name}
+ disabled={disabled}
+ onClick={onClick}
+ className={cn(
+ "flex w-full items-center gap-3 px-4 py-2 text-left transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-not-allowed",
+ selected ? "bg-secondary/70" : "hover:bg-secondary/40",
+ )}
+ >
+ {body}
+ </button>
+ ) : (
+ <div className="flex items-center gap-3 px-4 py-2">{body}</div>
+ )}
+ </li>
+ );
+}
+
/** The detail pane's title line: mark and name, and the version on the right. */
export function DetailHeader({ icon, name, version }: { icon: ReactNode; name: string; version?: string | null }) {
return (
diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx
deleted file mode 100644
index 2b8bc551a5..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx
+++ /dev/null
@@ -1,208 +0,0 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { JarvisApiGroup } from "./JarvisApiGroup";
-
-const KEY = "jctl_secretvalue1234";
-const MASKED = "jctl_…1234";
-
-const robustCopy = vi.fn().mockResolvedValue(true);
-vi.mock("@/lib/clipboard", () => ({
- robustCopy: (text: string) => robustCopy(text),
-}));
-
-afterEach(() => vi.restoreAllMocks());
-
-/** URL-aware fetch stub: the component now issues TWO mount-time GETs (the
- * key itself + the browser-lock state), so ordered `mockResolvedValueOnce`
- * chains would race. `extra` may claim a call (e.g. the rotate POST) first. */
-function stubKeyFetch(
- extra?: (url: string, opts?: RequestInit) => unknown,
- browserLockEnabled = false,
-) {
- const mock = vi.fn().mockImplementation(async (url: string, opts?: RequestInit) => {
- const custom = extra?.(url, opts);
- if (custom) return custom;
- if (url === "/api/settings/browser-login") {
- return { ok: true, json: async () => ({ enabled: browserLockEnabled }) };
- }
- return { ok: true, json: async () => ({ key: KEY, masked: MASKED }) };
- });
- vi.stubGlobal("fetch", mock);
- return mock;
-}
-
-describe("JarvisApiGroup", () => {
- it("renders the 'Control Key' heading and the masked key (full key hidden)", async () => {
- stubKeyFetch();
- render(<JarvisApiGroup />);
-
- expect(screen.getByRole("heading", { name: "Control Key" })).toBeTruthy();
- await waitFor(() => expect(screen.getByText(MASKED)).toBeTruthy());
- // The clear key must NOT be on screen until the user reveals it.
- expect(screen.queryByText(KEY)).toBeNull();
- });
-
- it("reveals the full key when Show is clicked", async () => {
- stubKeyFetch();
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
-
- fireEvent.click(screen.getByRole("button", { name: /show/i }));
- await waitFor(() => expect(screen.getByText(KEY)).toBeTruthy());
- });
-
- it("copies the clear key via robustCopy", async () => {
- stubKeyFetch();
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
-
- fireEvent.click(screen.getByRole("button", { name: /copy/i }));
- await waitFor(() => expect(robustCopy).toHaveBeenCalledWith(KEY));
- });
-
- it("rotates only after the confirmation dialog is accepted", async () => {
- const fetchMock = stubKeyFetch((_url, opts) =>
- opts?.method === "POST"
- ? {
- ok: true,
- json: async () => ({ ok: true, key: "jctl_rotated9999", masked: "jctl_…9999" }),
- }
- : undefined,
- );
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
-
- fireEvent.click(screen.getByRole("button", { name: /generate random key/i }));
- // Opening the dialog must NOT fire the request yet.
- expect(fetchMock.mock.calls.find(([, opts]) => opts?.method === "POST")).toBeUndefined();
-
- fireEvent.click(screen.getByRole("button", { name: /generate new key/i }));
- await waitFor(() => {
- const post = fetchMock.mock.calls.find(([, opts]) => opts?.method === "POST");
- expect(post).toBeTruthy();
- expect(post?.[0]).toBe("/api/control/api-key/rotate");
- expect(JSON.parse(post?.[1]?.body as string)).toMatchObject({ confirm: true });
- });
- });
-
- it("sets a user-chosen key via PUT after both entries match", async () => {
- const fetchMock = stubKeyFetch((url, opts) =>
- url === "/api/control/api-key" && opts?.method === "PUT"
- ? { ok: true, json: async () => ({ ok: true, masked: "…tery" }) }
- : undefined,
- );
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
-
- fireEvent.click(screen.getByRole("button", { name: /choose my own key/i }));
- fireEvent.change(screen.getByLabelText("New Control Key"), {
- target: { value: "correct-horse-battery" },
- });
- fireEvent.change(screen.getByLabelText("Repeat new Control Key"), {
- target: { value: "correct-horse-battery" },
- });
- fireEvent.click(screen.getByRole("button", { name: /set this key/i }));
-
- await waitFor(() => {
- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
- expect(put).toBeTruthy();
- expect(put?.[0]).toBe("/api/control/api-key");
- expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({
- value: "correct-horse-battery",
- confirm: true,
- });
- });
- });
-
- it("rejects a too-short custom key locally without any request", async () => {
- stubKeyFetch();
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
- const fetchMock = window.fetch as ReturnType<typeof vi.fn>;
- const callsBefore = fetchMock.mock.calls.length;
-
- fireEvent.click(screen.getByRole("button", { name: /choose my own key/i }));
- fireEvent.change(screen.getByLabelText("New Control Key"), {
- target: { value: "short" },
- });
- fireEvent.change(screen.getByLabelText("Repeat new Control Key"), {
- target: { value: "short" },
- });
- fireEvent.click(screen.getByRole("button", { name: /set this key/i }));
-
- await waitFor(() =>
- // Exact message: the form's hint text also mentions "At least 12 characters".
- expect(screen.getByText("At least 12 characters are required.")).toBeTruthy(),
- );
- expect(fetchMock.mock.calls.length).toBe(callsBefore);
- });
-
- it("turning the browser lock ON asks for confirmation before the PUT", async () => {
- const fetchMock = stubKeyFetch((url, opts) =>
- url === "/api/settings/browser-login" && opts?.method === "PUT"
- ? {
- ok: true,
- json: async () => ({
- ok: true,
- enabled: true,
- persisted: true,
- applied_live: true,
- session_minted: true,
- }),
- }
- : undefined,
- );
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
-
- fireEvent.click(screen.getByRole("switch"));
- // The dialog must appear WITHOUT any PUT having fired yet.
- expect(
- screen.getByRole("heading", { name: /require the control key in the browser\?/i }),
- ).toBeTruthy();
- expect(fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT")).toBeUndefined();
-
- fireEvent.click(screen.getByRole("button", { name: /require the key/i }));
- await waitFor(() => {
- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
- expect(put).toBeTruthy();
- expect(put?.[0]).toBe("/api/settings/browser-login");
- expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({ enabled: true });
- });
- });
-
- it("turning the browser lock OFF PUTs immediately, no dialog", async () => {
- const fetchMock = stubKeyFetch(
- (url, opts) =>
- url === "/api/settings/browser-login" && opts?.method === "PUT"
- ? {
- ok: true,
- json: async () => ({
- ok: true,
- enabled: false,
- persisted: true,
- applied_live: true,
- session_minted: false,
- }),
- }
- : undefined,
- true,
- );
- render(<JarvisApiGroup />);
- await waitFor(() => screen.getByText(MASKED));
- await waitFor(() =>
- expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe("true"),
- );
-
- fireEvent.click(screen.getByRole("switch"));
- await waitFor(() => {
- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
- expect(put).toBeTruthy();
- expect(put?.[0]).toBe("/api/settings/browser-login");
- expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({ enabled: false });
- });
- expect(
- screen.queryByRole("heading", { name: /require the control key in the browser\?/i }),
- ).toBeNull();
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
deleted file mode 100644
index b0e90aada4..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
+++ /dev/null
@@ -1,400 +0,0 @@
-import { type FormEvent, useEffect, useState } from "react";
-import {
- AlertTriangle,
- Copy,
- Eye,
- EyeOff,
- KeyRound,
- Loader2,
- Lock,
- PencilLine,
- RefreshCw,
-} from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Switch } from "@/components/ui/switch";
-import { useBrowserLock } from "@/hooks/useBrowserLock";
-import { useJarvisApi } from "@/hooks/useJarvisApi";
-import { robustCopy } from "@/lib/clipboard";
-import { useEventStore } from "@/store/events";
-import { useT } from "@/i18n";
-import {
- SettingsBlock,
- SettingsField,
- settingsInputCls,
-} from "@/views/settings/SettingsBlock";
-
-// Mirrors jarvis/core/control_key.py (MIN_CUSTOM_KEY_LENGTH / _CUSTOM_KEY_RE)
-// so the form rejects locally what the backend would reject anyway.
-const MIN_CUSTOM_KEY_LENGTH = 12;
-const CUSTOM_KEY_RE = /^[A-Za-z0-9._~-]+$/;
-
-/**
- * "Control Key" group — the standardized home of the ONE key that protects a
- * Jarvis install. The same value unlocks the browser UI (the AuthGate lock
- * screen asks for exactly this key) and authenticates the local Control API
- * (``/api/control/*``) for local coding agents. Auto-generated per install;
- * this panel lets the user reveal/copy it, regenerate a random one (behind a
- * confirmation dialog — it invalidates the old key everywhere), or replace it
- * with a memorable key of their own. Reveal/change are session-permitted so
- * the panel works before the user possesses the key.
- */
-export function JarvisApiGroup() {
- const t = useT();
- const { data, loading, error, rotate, setKey } = useJarvisApi();
- const browserLock = useBrowserLock();
- const pushToast = useEventStore((s) => s.pushToast);
- const [revealed, setRevealed] = useState(false);
- const [busy, setBusy] = useState(false);
- const [confirmRotate, setConfirmRotate] = useState(false);
- const [confirmLock, setConfirmLock] = useState(false);
- const [lockBusy, setLockBusy] = useState(false);
- const [formOpen, setFormOpen] = useState(false);
- const [newKey, setNewKey] = useState("");
- const [repeatKey, setRepeatKey] = useState("");
- const [formErrorKey, setFormErrorKey] = useState<string | null>(null);
- const [serverError, setServerError] = useState<string | null>(null);
-
- const key = data?.key ?? "";
- const display = revealed ? key : (data?.masked ?? "…");
-
- useEffect(() => {
- if (!confirmRotate && !confirmLock) return;
- const onKeyDown = (e: KeyboardEvent) => {
- if (e.key === "Escape") {
- setConfirmRotate(false);
- setConfirmLock(false);
- }
- };
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, [confirmRotate, confirmLock]);
-
- async function applyBrowserLock(next: boolean) {
- setLockBusy(true);
- try {
- await browserLock.setEnabled(next);
- setConfirmLock(false);
- pushToast(
- "success",
- next
- ? t("settings_view.jarvis_api.browser_lock_on_toast")
- : t("settings_view.jarvis_api.browser_lock_off_toast"),
- );
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setLockBusy(false);
- }
- }
-
- function onToggleBrowserLock(next: boolean) {
- if (next) {
- // Turning the lock ON means the key is needed from now on — make the
- // user consciously confirm (and ideally copy the key) first.
- setConfirmLock(true);
- return;
- }
- void applyBrowserLock(false);
- }
-
- async function onCopy() {
- if (!key) return;
- const ok = await robustCopy(key);
- pushToast(
- ok ? "success" : "error",
- ok
- ? t("settings_view.jarvis_api.copied_toast")
- : t("settings_view.jarvis_api.copy_failed_toast"),
- );
- }
-
- async function onRotate() {
- setBusy(true);
- try {
- await rotate();
- setRevealed(false);
- setConfirmRotate(false);
- pushToast("success", t("settings_view.jarvis_api.regenerated_toast"));
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setBusy(false);
- }
- }
-
- function closeForm() {
- setFormOpen(false);
- setNewKey("");
- setRepeatKey("");
- setFormErrorKey(null);
- setServerError(null);
- }
-
- async function onSubmitCustomKey(event: FormEvent<HTMLFormElement>) {
- event.preventDefault();
- const value = newKey.trim();
- setServerError(null);
- if (value.length < MIN_CUSTOM_KEY_LENGTH) {
- setFormErrorKey("settings_view.jarvis_api.custom_too_short");
- return;
- }
- if (!CUSTOM_KEY_RE.test(value)) {
- setFormErrorKey("settings_view.jarvis_api.custom_charset");
- return;
- }
- if (value !== repeatKey.trim()) {
- setFormErrorKey("settings_view.jarvis_api.custom_mismatch");
- return;
- }
- setFormErrorKey(null);
- setBusy(true);
- try {
- await setKey(value);
- setRevealed(false);
- closeForm();
- pushToast("success", t("settings_view.jarvis_api.custom_saved_toast"));
- } catch (e) {
- setServerError((e as Error).message);
- } finally {
- setBusy(false);
- }
- }
-
- return (
- <SettingsBlock
- icon={KeyRound}
- title={t("settings_view.jarvis_api.title")}
- description={t("settings_view.jarvis_api.description")}
- >
- <div className="space-y-3">
- <div className="flex items-center gap-2">
- <code className="min-w-0 flex-1 truncate rounded-lg bg-muted px-3 py-2 font-mono text-xs">
- {display}
- </code>
- <Button
- size="sm"
- variant="outline"
- disabled={loading || !key}
- onClick={() => setRevealed((v) => !v)}
- >
- {revealed ? (
- <>
- <EyeOff className="mr-1 h-3.5 w-3.5" />
- {t("settings_view.jarvis_api.hide")}
- </>
- ) : (
- <>
- <Eye className="mr-1 h-3.5 w-3.5" />
- {t("settings_view.jarvis_api.show")}
- </>
- )}
- </Button>
- <Button size="sm" variant="outline" disabled={loading || !key} onClick={onCopy}>
- <Copy className="mr-1 h-3.5 w-3.5" />
- {t("settings_view.jarvis_api.copy_button")}
- </Button>
- </div>
-
- <p className="text-xs text-muted-foreground">
- {t("settings_view.jarvis_api.unlock_hint")}
- </p>
-
- <div className="flex items-start gap-3 rounded-lg border border-border bg-card p-4">
- <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium">
- {t("settings_view.jarvis_api.browser_lock_title")}
- </div>
- <p className="mt-0.5 text-xs text-muted-foreground">
- {t("settings_view.jarvis_api.browser_lock_description")}
- </p>
- </div>
- <Switch
- checked={browserLock.enabled ?? false}
- disabled={browserLock.loading || lockBusy}
- aria-label={t("settings_view.jarvis_api.browser_lock_title")}
- onCheckedChange={onToggleBrowserLock}
- />
- </div>
-
- <div className="flex items-center gap-2">
- <Button
- size="sm"
- variant="outline"
- disabled={busy || loading}
- onClick={() => {
- setServerError(null);
- setFormOpen((v) => !v);
- }}
- >
- <PencilLine className="mr-1 h-3.5 w-3.5" />
- {t("settings_view.jarvis_api.custom_button")}
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={busy || loading}
- onClick={() => setConfirmRotate(true)}
- >
- <RefreshCw className="mr-1 h-3.5 w-3.5" />
- {t("settings_view.jarvis_api.regenerate_button")}
- </Button>
- </div>
-
- {formOpen && (
- <form
- className="space-y-3 rounded-xl border border-border bg-background p-4"
- onSubmit={onSubmitCustomKey}
- >
- <p className="text-xs text-muted-foreground">
- {t("settings_view.jarvis_api.custom_hint")}
- </p>
- <SettingsField label={t("settings_view.jarvis_api.custom_new_label")}>
- <input
- autoComplete="new-password"
- className={settingsInputCls}
- disabled={busy}
- onChange={(e) => setNewKey(e.target.value)}
- type="password"
- value={newKey}
- />
- </SettingsField>
- <SettingsField label={t("settings_view.jarvis_api.custom_repeat_label")}>
- <input
- autoComplete="new-password"
- className={settingsInputCls}
- disabled={busy}
- onChange={(e) => setRepeatKey(e.target.value)}
- type="password"
- value={repeatKey}
- />
- </SettingsField>
- {(formErrorKey || serverError) && (
- <p className="text-xs text-destructive" role="alert">
- {formErrorKey ? t(formErrorKey) : serverError}
- </p>
- )}
- <div className="flex justify-end gap-2">
- <Button size="sm" variant="ghost" type="button" disabled={busy} onClick={closeForm}>
- {t("common.cancel")}
- </Button>
- <Button size="sm" type="submit" disabled={busy || !newKey || !repeatKey}>
- {busy ? (
- <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
- ) : (
- <KeyRound className="mr-1 h-3.5 w-3.5" />
- )}
- {t("settings_view.jarvis_api.custom_submit")}
- </Button>
- </div>
- </form>
- )}
-
- <p className="text-xs text-muted-foreground">
- {t("settings_view.jarvis_api.usage_hint")}
- </p>
-
- {error && <p className="text-xs text-destructive">{error}</p>}
- </div>
-
- {confirmLock && (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 backdrop-blur-sm"
- onClick={(e) => {
- if (e.target === e.currentTarget) setConfirmLock(false);
- }}
- >
- <div className="mx-4 w-full max-w-md rounded-lg bg-popover shadow-float p-5">
- <div className="flex items-start gap-3">
- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary">
- <Lock className="h-5 w-5 text-muted-foreground" />
- </div>
- <div className="min-w-0 flex-1">
- <h3 className="text-base font-semibold">
- {t("settings_view.jarvis_api.browser_lock_confirm_title")}
- </h3>
- <p className="mt-1 text-sm text-muted-foreground">
- {t("settings_view.jarvis_api.browser_lock_confirm_body")}
- </p>
- </div>
- </div>
- <div className="mt-5 flex justify-end gap-2">
- <Button
- variant="ghost"
- size="sm"
- disabled={lockBusy}
- onClick={() => setConfirmLock(false)}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="outline"
- size="sm"
- disabled={lockBusy || !key}
- onClick={onCopy}
- >
- <Copy className="mr-1.5 h-4 w-4" />
- {t("settings_view.jarvis_api.copy_button")}
- </Button>
- <Button
- size="sm"
- disabled={lockBusy}
- onClick={() => void applyBrowserLock(true)}
- >
- {lockBusy ? (
- <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
- ) : (
- <Lock className="mr-1.5 h-4 w-4" />
- )}
- {t("settings_view.jarvis_api.browser_lock_confirm_button")}
- </Button>
- </div>
- </div>
- </div>
- )}
-
- {confirmRotate && (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 backdrop-blur-sm"
- onClick={(e) => {
- if (e.target === e.currentTarget) setConfirmRotate(false);
- }}
- >
- <div className="mx-4 w-full max-w-md rounded-lg bg-popover shadow-float p-5">
- <div className="flex items-start gap-3">
- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary">
- <AlertTriangle className="h-5 w-5 text-destructive" />
- </div>
- <div className="min-w-0 flex-1">
- <h3 className="text-base font-semibold">
- {t("settings_view.jarvis_api.regenerate_confirm_title")}
- </h3>
- <p className="mt-1 text-sm text-muted-foreground">
- {t("settings_view.jarvis_api.regenerate_confirm_body")}
- </p>
- </div>
- </div>
- <div className="mt-5 flex justify-end gap-2">
- <Button
- variant="ghost"
- size="sm"
- disabled={busy}
- onClick={() => setConfirmRotate(false)}
- >
- {t("common.cancel")}
- </Button>
- <Button variant="destructive" size="sm" disabled={busy} onClick={onRotate}>
- {busy ? (
- <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
- ) : (
- <RefreshCw className="mr-1.5 h-4 w-4" />
- )}
- {t("settings_view.jarvis_api.regenerate_confirm_button")}
- </Button>
- </div>
- </div>
- </div>
- )}
- </SettingsBlock>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
deleted file mode 100644
index 2732b7792e..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { useEffect, useState } from "react";
-import { Check, Loader2, Users } from "lucide-react";
-import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
-import { Switch } from "@/components/ui/switch";
-import { Button } from "@/components/ui/button";
-import {
- SettingsBlock,
- SettingsField,
- settingsInputCls,
-} from "@/views/settings/SettingsBlock";
-
-const TEAM_PROXY_ENDPOINT = "/api/settings/team-proxy";
-const TOKEN_SECRET_ENDPOINT = "/api/secrets/team_proxy_token";
-
-// Providers that CAN be routed through the key proxy today. The checkboxes pick
-// which to keep LOCAL/direct (the exception list) — e.g. local Whisper that
-// must never leave the machine.
-const PROXIABLE_PROVIDERS = [
- "claude-api",
- "openai",
- "openrouter",
- "gemini",
- "groq-api",
-] as const;
-
-interface TeamProxyState {
- enabled: boolean;
- url: string;
- local_providers: string[];
- token_configured: boolean;
-}
-
-/**
- * "Team Mode" group inside the Settings view (2026-06-20 team-proxy spec). One
- * global switch: when enabled with a proxy URL, every provider not in the
- * "keep local" list is routed through the shared key proxy using a per-user
- * token instead of a real vendor key. The token is a secret stored via the
- * normal /secrets route; the rest persists to [team_proxy] in jarvis.toml.
- */
-export function TeamProxyGroup() {
- const t = useT();
- const [enabled, setEnabled] = useState(false);
- const [url, setUrl] = useState("");
- const [local, setLocal] = useState<Set<string>>(new Set());
- const [token, setToken] = useState("");
- const [tokenConfigured, setTokenConfigured] = useState(false);
- const [saving, setSaving] = useState(false);
- const [saved, setSaved] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- let cancelled = false;
- void (async () => {
- try {
- const res = await fetch(TEAM_PROXY_ENDPOINT);
- if (!res.ok) return;
- const data: TeamProxyState = await res.json();
- if (cancelled) return;
- setEnabled(data.enabled);
- setUrl(data.url ?? "");
- setLocal(new Set(data.local_providers ?? []));
- setTokenConfigured(Boolean(data.token_configured));
- } catch {
- /* settings unreachable (headless) — leave defaults */
- }
- })();
- return () => {
- cancelled = true;
- };
- }, []);
-
- const toggleLocal = (provider: string) => {
- setLocal((prev) => {
- const next = new Set(prev);
- if (next.has(provider)) next.delete(provider);
- else next.add(provider);
- return next;
- });
- };
-
- const save = async () => {
- setSaving(true);
- setSaved(false);
- setError(null);
- try {
- // Persist the token first (only when the user typed a new one).
- if (token.trim()) {
- const tokRes = await fetch(TOKEN_SECRET_ENDPOINT, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ value: token.trim() }),
- });
- if (!tokRes.ok) throw new Error(`token ${tokRes.status}`);
- setTokenConfigured(true);
- setToken("");
- }
- const res = await fetch(TEAM_PROXY_ENDPOINT, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- enabled,
- url: url.trim(),
- local_providers: Array.from(local),
- }),
- });
- if (!res.ok) {
- const detail = await res.json().catch(() => ({}));
- throw new Error(detail?.detail ?? `settings ${res.status}`);
- }
- setSaved(true);
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- } finally {
- setSaving(false);
- }
- };
-
- return (
- <SettingsBlock
- icon={Users}
- title={t("settings_view.team_proxy.title")}
- description={t("settings_view.team_proxy.hint")}
- headerRight={
- <Switch
- checked={enabled}
- onCheckedChange={setEnabled}
- aria-label={t("settings_view.team_proxy.enable_label")}
- />
- }
- >
- <div className="space-y-4">
- {enabled && (
- <div className="space-y-4">
- <div className="grid gap-4 sm:grid-cols-2">
- <SettingsField label={t("settings_view.team_proxy.url_label")}>
- <input
- type="url"
- value={url}
- onChange={(e) => setUrl(e.target.value)}
- placeholder="https://keys.example.dev"
- className={settingsInputCls}
- />
- </SettingsField>
-
- <SettingsField label={t("settings_view.team_proxy.token_label")}>
- <input
- type="password"
- value={token}
- onChange={(e) => setToken(e.target.value)}
- placeholder={
- tokenConfigured
- ? t("settings_view.team_proxy.token_set_placeholder")
- : t("settings_view.team_proxy.token_placeholder")
- }
- className={settingsInputCls}
- />
- </SettingsField>
- </div>
-
- <div>
- <div className="mb-2 text-micro text-muted-foreground">
- {t("settings_view.team_proxy.local_label")}
- </div>
- <div className="flex flex-wrap gap-2">
- {PROXIABLE_PROVIDERS.map((p) => {
- const on = local.has(p);
- return (
- <button
- key={p}
- type="button"
- onClick={() => toggleLocal(p)}
- aria-pressed={on}
- className={cn(
- "inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs transition-colors",
- on
- ? "bg-secondary text-foreground-strong"
- : "border-border text-muted-foreground hover:text-foreground",
- )}
- >
- <span
- className={cn(
- "flex h-3.5 w-3.5 items-center justify-center rounded border",
- on
- ? "border-border-strong bg-primary text-primary-foreground"
- : "border-muted-foreground/50",
- )}
- >
- {on && <Check className="h-2.5 w-2.5" />}
- </span>
- {p}
- </button>
- );
- })}
- </div>
- </div>
- </div>
- )}
-
- <div className="flex items-center gap-3">
- <Button size="sm" onClick={() => void save()} disabled={saving}>
- {saving && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
- {saved && !saving && <Check className="mr-1 h-4 w-4" />}
- {t("settings_view.team_proxy.save")}
- </Button>
- {error && <span className="text-xs text-destructive">{error}</span>}
- </div>
- </div>
- </SettingsBlock>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/settings/WakeWordPanel.test.tsx b/jarvis/ui/web/frontend/src/views/settings/WakeWordPanel.test.tsx
index 95606fdf73..0a388f70bd 100644
--- a/jarvis/ui/web/frontend/src/views/settings/WakeWordPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/WakeWordPanel.test.tsx
@@ -53,9 +53,6 @@ vi.mock("@/views/settings/LanguagesGroup", () => ({
vi.mock("@/views/settings/AppSettingsGroup", () => ({
AppSettingsGroup: () => null,
}));
-vi.mock("@/views/settings/JarvisApiGroup", () => ({
- JarvisApiGroup: () => null,
-}));
// RealtimeVoiceGroup uses react-query (useVoiceMode) and needs a
// QueryClientProvider this test doesn't set up — silence it like the other
// sibling groups above, unrelated to wake-word.
diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
deleted file mode 100644
index 96badeb924..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
+++ /dev/null
@@ -1,255 +0,0 @@
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-// Identity translator so rendered text equals the i18n key (assert keys exactly).
-vi.mock("@/i18n", () => ({
- useT: () => (key: string) => key,
-}));
-
-// The toast store is only used for side effects here; stub it to a no-op.
-vi.mock("@/store/events", () => ({
- useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>
- selector({ pushToast: vi.fn() }),
-}));
-
-import { WikiProviderCard } from "./WikiProviderCard";
-
-// Object-shape fixture per the canonical backend: `available` rows carry
-// {provider, models[], kind, ready}; `resolved` states what the next run uses.
-const INITIAL = {
- provider: "",
- model: "",
- available: [
- {
- provider: "gemini",
- models: ["gemini-3-flash-preview", "gemini-3.1-pro-preview"],
- kind: "api",
- ready: true,
- },
- { provider: "openai", models: ["gpt-5.5"], kind: "api", ready: false },
- { provider: "codex", models: [], kind: "agent", ready: true },
- ],
- resolved: { provider: "gemini", model: "gemini-3-flash-preview", ready: true },
- brain_primary: "gemini",
-};
-
-// Per-provider live catalog served to BrainModelSelector (the model picker).
-const CATALOGS: Record<string, { id: string; label: string }[]> = {
- gemini: [
- { id: "gemini-3-flash-preview", label: "Gemini 3 Flash" },
- { id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro" },
- ],
- codex: [
- { id: "gpt-5.6-sol", label: "GPT-5.6 Sol" },
- { id: "gpt-5.5", label: "GPT-5.5" },
- ],
-};
-
-/**
- * URL-routing fetch stub: settings GET/PUT + the per-provider model catalog.
- * Returns the mock so tests can inspect recorded calls.
- */
-function stubFetch(overrides?: { state?: typeof INITIAL; putBody?: object }) {
- const state = overrides?.state ?? INITIAL;
- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
- if (url === "/api/settings/wiki-provider") {
- if (init?.method === "PUT") {
- const sent = JSON.parse(init.body as string);
- return {
- ok: true,
- json: async () =>
- overrides?.putBody ?? {
- ...state,
- provider: sent.provider,
- model: sent.model,
- persisted: true,
- applied_live: true,
- restart_required: false,
- },
- };
- }
- return { ok: true, json: async () => state };
- }
- const catalog = url.match(/^\/api\/providers\/([^/]+)\/models/);
- if (catalog) {
- const id = decodeURIComponent(catalog[1]);
- return {
- ok: true,
- json: async () => ({
- provider: id,
- current_model: "",
- models: CATALOGS[id] ?? [],
- source: "curated",
- fetched_at: 0,
- selects: "model",
- }),
- };
- }
- throw new Error(`unexpected fetch: ${url}`);
- });
- vi.stubGlobal("fetch", fetchMock);
- return fetchMock;
-}
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-describe("WikiProviderCard", () => {
- it("renders the Wiki tier label and the provider select once loaded", async () => {
- stubFetch();
- render(<WikiProviderCard />);
-
- expect(screen.getByText("wiki_provider.tier_label")).toBeDefined();
- await waitFor(() =>
- expect(screen.getByLabelText("wiki_provider.provider_label")).toBeDefined(),
- );
- });
-
- it("renders gracefully when the GET load fails", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false, status: 503 }));
- render(<WikiProviderCard />);
-
- // The tier header stays; the body shows the load-error line, no crash, no
- // provider select.
- expect(screen.getByText("wiki_provider.tier_label")).toBeDefined();
- await waitFor(() => expect(screen.getByText("wiki_provider.load_error")).toBeDefined());
- expect(screen.queryByLabelText("wiki_provider.provider_label")).toBeNull();
- });
-
- it("shows the how-it-works explainer with all three steps", async () => {
- stubFetch();
- render(<WikiProviderCard />);
-
- await screen.findByText("wiki_provider.how_title");
- expect(screen.getByText("wiki_provider.how_step1")).toBeDefined();
- expect(screen.getByText("wiki_provider.how_step2")).toBeDefined();
- expect(screen.getByText("wiki_provider.how_step3")).toBeDefined();
- expect(screen.getByText("wiki_provider.how_model_note")).toBeDefined();
- });
-
- it("shows what the next run actually uses (resolved line)", async () => {
- stubFetch();
- render(<WikiProviderCard />);
-
- await screen.findByText("wiki_provider.resolved_label");
- expect(screen.getByText(/gemini · gemini-3-flash-preview/)).toBeDefined();
- });
-
- it("warns when the resolved provider has no credentials", async () => {
- stubFetch({
- state: {
- ...INITIAL,
- provider: "openai",
- resolved: { provider: "openai", model: "gpt-5.5", ready: false },
- },
- });
- render(<WikiProviderCard />);
-
- await screen.findByText("wiki_provider.resolved_fallback_warning");
- });
-
- it("labels agent providers and keyless providers in the dropdown", async () => {
- stubFetch();
- render(<WikiProviderCard />);
-
- fireEvent.click(
- await screen.findByLabelText("wiki_provider.provider_label"),
- );
- expect(
- screen.getByText("codex — wiki_provider.option_agent_suffix"),
- ).toBeDefined();
- expect(
- screen.getByText("openai (wiki_provider.option_no_key)"),
- ).toBeDefined();
- });
-
- it('renders NO model dropdown while the provider is "same as brain"', async () => {
- stubFetch();
- render(<WikiProviderCard />);
-
- await screen.findByLabelText("wiki_provider.provider_label");
- // Static text instead of a pointless one-option dropdown.
- expect(screen.getByText("wiki_provider.model_follow_primary")).toBeDefined();
- expect(screen.queryByLabelText("apikeys_model.model_label")).toBeNull();
- });
-
- it("opens the catalog picker for a concrete provider and saves the pick", async () => {
- const fetchMock = stubFetch();
- render(<WikiProviderCard />);
-
- const providerSelect = await screen.findByLabelText(
- "wiki_provider.provider_label",
- );
-
- // Picking codex mounts the shared model picker fed by codex's catalog.
- fireEvent.click(providerSelect);
- const codexOption = (await screen.findAllByRole("option")).find(
- (option) => option.getAttribute("data-value") === "codex",
- );
- fireEvent.click(codexOption!);
- const trigger = await screen.findByLabelText("apikeys_model.model_label");
- fireEvent.click(trigger);
-
- // Codex's real lineup appears (the old tier-default list was empty).
- const row = await screen.findByText("GPT-5.6 Sol");
- fireEvent.click(row);
-
- await waitFor(() => {
- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
- expect(put).toBeTruthy();
- expect(put?.[0]).toBe("/api/settings/wiki-provider");
- expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({
- provider: "codex",
- model: "gpt-5.6-sol",
- });
- });
- });
-
- it("sends a PUT with the chosen provider when Apply is clicked", async () => {
- const fetchMock = stubFetch();
- render(<WikiProviderCard />);
-
- const providerSelect = await screen.findByLabelText(
- "wiki_provider.provider_label",
- );
-
- fireEvent.click(providerSelect);
- const geminiOption = (await screen.findAllByRole("option")).find(
- (option) => option.getAttribute("data-value") === "gemini",
- );
- fireEvent.click(geminiOption!);
- fireEvent.click(screen.getByRole("button", { name: "wiki_provider.apply" }));
-
- await waitFor(() => {
- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
- expect(put).toBeTruthy();
- expect(put?.[0]).toBe("/api/settings/wiki-provider");
- expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({
- provider: "gemini",
- model: "",
- });
- });
- });
-
- it("offers a reset back to the cheap default when a model is pinned", async () => {
- const fetchMock = stubFetch({
- state: { ...INITIAL, provider: "gemini", model: "gemini-3.1-pro-preview" },
- });
- render(<WikiProviderCard />);
-
- const reset = await screen.findByText("wiki_provider.model_reset");
- fireEvent.click(reset);
-
- await waitFor(() => {
- const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
- expect(put).toBeTruthy();
- expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({
- provider: "gemini",
- model: "",
- });
- });
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx
deleted file mode 100644
index 2759a934b3..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import { useState } from "react";
-import { BookOpen, ChevronDown, Info, Loader2 } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
-import { cn } from "@/lib/utils";
-import { BrainModelSelector } from "@/components/BrainModelSelector";
-import type { BrainModelSaveResult } from "@/hooks/useProviders";
-import { saveWikiProvider, useWikiProvider } from "@/hooks/useWikiProvider";
-import { useEventStore } from "@/store/events";
-import { useT } from "@/i18n";
-import { SettingsBlock, SettingsField, settingsInputCls } from "@/views/settings/SettingsBlock";
-
-// Empty string = "follow brain.primary" (provider) / "cheap default" (model).
-// We render it as a named option so the user can deliberately pick "Same as
-// brain" instead of guessing what blank does.
-const FOLLOW_PRIMARY = "";
-
-/**
- * "Wiki" tier card in the API-Keys & Providers screen. Lets the user pick the
- * dedicated Wiki-curator provider + (optional) model via
- * `GET/PUT /api/settings/wiki-provider`.
- *
- * The provider picker is fed by the endpoint's `available` matrix (agent
- * providers such as Codex are labelled, keyless ones flagged). The model pick
- * uses the shared searchable {@link BrainModelSelector} against the chosen
- * provider's live catalog (`GET /api/providers/{id}/models`) — the same picker
- * the Jarvis-Agent model pin uses, so e.g. Codex offers its real model lineup
- * instead of an empty tier-default list. Picking a model saves provider+model
- * in one PUT; the Apply button remains for provider-only changes.
- *
- * An empty provider/model is intentional and means "follow brain.primary" /
- * "use the cheap-fast model of the chosen provider". The `resolved` line below
- * the pickers states what the NEXT maintenance run will actually use (resolved
- * server-side by the same helper the runtime uses).
- */
-export function WikiProviderCard() {
- const t = useT();
- const { data, loading, error, refetch } = useWikiProvider();
- const pushToast = useEventStore((s) => s.pushToast);
-
- const [provider, setProvider] = useState<string | null>(null);
- const [model, setModel] = useState<string | null>(null);
- const [pending, setPending] = useState(false);
-
- // Controlled values fall back to the server state until the user edits them.
- const providerValue = provider ?? data?.provider ?? FOLLOW_PRIMARY;
- const modelValue = model ?? data?.model ?? FOLLOW_PRIMARY;
-
- // Shared save path: provider+model always travel together in one PUT, so the
- // Apply button, the model picker, and the reset link can never disagree.
- async function applySelection(nextProvider: string, nextModel: string) {
- const next = await saveWikiProvider(nextProvider, nextModel);
- // Reset local edits so the inputs re-sync to the server-resolved state.
- setProvider(null);
- setModel(null);
- void refetch();
- return next;
- }
-
- async function handleApply() {
- setPending(true);
- try {
- const next = await applySelection(providerValue, modelValue);
- pushToast(
- "success",
- next.provider
- ? `Wiki → ${next.provider}${next.model ? ` · ${next.model}` : ""}`
- : t("wiki_provider.follow_primary"),
- );
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setPending(false);
- }
- }
-
- // The model picker saves immediately (same UX as the Jarvis-Agent model pin):
- // returning the save result lets BrainModelSelector render its own toast.
- async function handleModelSave(m: string): Promise<BrainModelSaveResult> {
- const next = await applySelection(providerValue, m);
- return {
- ok: true,
- provider: next.provider,
- model: next.model,
- persisted: next.persisted ?? true,
- applied_live: next.applied_live ?? true,
- restart_required: next.restart_required ?? false,
- probe: null,
- };
- }
-
- async function handleModelReset() {
- setPending(true);
- try {
- await applySelection(providerValue, FOLLOW_PRIMARY);
- pushToast("success", t("wiki_provider.model_follow_primary"));
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setPending(false);
- }
- }
-
- // Picking a new provider invalidates the previously selected model (it may not
- // exist under the new provider), so we reset the model back to the cheap
- // default whenever the provider changes.
- function handleProviderChange(next: string) {
- setProvider(next);
- setModel(FOLLOW_PRIMARY);
- }
-
- function providerOptionLabel(p: { provider: string; kind?: string; ready?: boolean }) {
- let label = p.provider;
- if (p.kind === "agent") label += ` — ${t("wiki_provider.option_agent_suffix")}`;
- if (p.ready === false) label += ` (${t("wiki_provider.option_no_key")})`;
- return label;
- }
-
- const resolved = data?.resolved;
-
- return (
- <SettingsBlock
- icon={BookOpen}
- title={t("wiki_provider.tier_label")}
- description={t("wiki_provider.description")}
- >
- {loading && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" /> {t("wiki_provider.loading")}
- </div>
- )}
-
- {error && <p className="text-xs text-destructive">{t("wiki_provider.load_error")}</p>}
-
- {!loading && data && (
- <div className="space-y-4">
- {/* "How does this work?" — native <details>, the app's collapsible idiom. */}
- <details className="group rounded-md border border-border bg-muted px-3 py-2">
- <summary className="flex cursor-pointer select-none list-none items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden">
- <Info className="h-3.5 w-3.5 shrink-0" />
- {t("wiki_provider.how_title")}
- <ChevronDown className="h-3 w-3 shrink-0 transition-transform group-open:rotate-180" />
- </summary>
- <div className="mt-2 space-y-1.5 text-xs leading-relaxed text-muted-foreground">
- <p>{t("wiki_provider.how_intro")}</p>
- <ol className="list-decimal space-y-1 pl-4">
- <li>{t("wiki_provider.how_step1")}</li>
- <li>{t("wiki_provider.how_step2")}</li>
- <li>{t("wiki_provider.how_step3")}</li>
- </ol>
- <p>{t("wiki_provider.how_model_note")}</p>
- </div>
- </details>
-
- <div className="grid gap-4 sm:grid-cols-2">
- <SettingsField label={t("wiki_provider.provider_label")}>
- <BrandedSelect
- ariaLabel={t("wiki_provider.provider_label")}
- value={providerValue}
- onValueChange={handleProviderChange}
- className={settingsInputCls}
- options={[
- {
- value: FOLLOW_PRIMARY,
- label: t("wiki_provider.follow_primary"),
- },
- ...data.available
- .filter((item) => item.provider !== FOLLOW_PRIMARY)
- .map((item) => ({
- value: item.provider,
- label: providerOptionLabel(item),
- })),
- ]}
- />
- </SettingsField>
-
- {providerValue === FOLLOW_PRIMARY ? (
- // No concrete provider → there is no model list to pick from, so
- // no dead dropdown: a static line states what "empty" means.
- <SettingsField label={t("wiki_provider.model_label")}>
- <div className={cn(settingsInputCls, "flex items-center text-muted-foreground")}>
- {t("wiki_provider.model_follow_primary")}
- </div>
- </SettingsField>
- ) : (
- <div className="space-y-1.5">
- <BrainModelSelector
- providerId={providerValue}
- controlled
- currentModel={modelValue}
- headingLabel={t("wiki_provider.model_label")}
- placeholder={t("wiki_provider.model_follow_primary")}
- onSave={handleModelSave}
- />
- {modelValue !== FOLLOW_PRIMARY && (
- <button
- type="button"
- onClick={() => void handleModelReset()}
- disabled={pending}
- className="text-micro text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
- >
- {t("wiki_provider.model_reset")}
- </button>
- )}
- </div>
- )}
- </div>
-
- {/* Honest ground truth: what the next maintenance run will actually use. */}
- {resolved && resolved.provider && (
- <div className="space-y-1">
- <p className="text-micro text-muted-foreground">
- {t("wiki_provider.resolved_label")}{" "}
- <span className="font-mono text-foreground">
- {resolved.provider}
- {" · "}
- {resolved.model || t("wiki_provider.provider_default_model")}
- </span>
- </p>
- {resolved.ready === false && (
- <p className="text-micro text-foreground">
- {t("wiki_provider.resolved_fallback_warning")}
- </p>
- )}
- </div>
- )}
-
- <p className="text-micro text-muted-foreground">
- {t("wiki_provider.model_hint")}
- </p>
-
- <Button onClick={handleApply} disabled={pending} size="sm">
- {pending ? t("wiki_provider.applying") : t("wiki_provider.apply")}
- </Button>
- </div>
- )}
- </SettingsBlock>
- );
-}
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 89b9490a7c..c8f56393cb 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -726,6 +726,40 @@ async def apply_seed_proposals(body: ApplySeedsBody, request: Request) -> dict[s
# --------------------------------------------------------------- providers
+class ProviderPrefsBody(BaseModel):
+ """The agents' provider choices from the API Keys page (any field may be left out)."""
+
+ disabled: list[str] | None = Field(default=None, max_length=256)
+ api_only: list[str] | None = Field(default=None, max_length=256)
+ hidden_models: dict[str, list[str]] | None = None
+
+
[email protected]("/provider-prefs", summary="Which providers and models the agents may run on")
+async def get_provider_prefs() -> dict[str, Any]:
+ from jarvis.agent_chat import agent_provider_prefs
+
+ return agent_provider_prefs.load().to_dict()
+
+
[email protected]("/provider-prefs", summary="Turn providers and models on or off for the agents")
+async def put_provider_prefs(body: ProviderPrefsBody) -> dict[str, Any]:
+ """Merge the given fields into the saved choices; ids outside the
+ agents' catalog are refused so a typo cannot hide a seat for good."""
+ from jarvis.agent_chat import agent_provider_prefs
+ from jarvis.agent_chat.catalog import offers
+
+ current = agent_provider_prefs.load().to_dict()
+ patch = body.model_dump(exclude_none=True)
+ ids = set(patch.get("disabled", [])) | set(patch.get("api_only", [])) | set(
+ patch.get("hidden_models", {})
+ )
+ unknown = sorted(i for i in ids if not offers(agent_provider_prefs.AGENT_SURFACE, i))
+ if unknown:
+ raise HTTPException(422, f"Not an agent provider: {', '.join(unknown)}")
+ saved = agent_provider_prefs.save(agent_provider_prefs.parse({**current, **patch}))
+ return saved.to_dict()
+
+
class ModelBody(BaseModel):
provider: str = Field(min_length=1)
model: str = ""
diff --git a/tests/unit/agent_chat/test_agent_provider_prefs.py b/tests/unit/agent_chat/test_agent_provider_prefs.py
new file mode 100644
index 0000000000..3d277dd913
--- /dev/null
+++ b/tests/unit/agent_chat/test_agent_provider_prefs.py
@@ -0,0 +1,83 @@
+"""The agents' provider choices: several seats on at once, models hidden,
+Claude set to its key — and only the agents' surface narrowed by them."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agent_chat import agent_provider_prefs as prefs_mod
+from jarvis.agent_chat import service
+
+
[email protected](autouse=True)
+def data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+ monkeypatch.setattr(prefs_mod, "_cache", None)
+ return tmp_path
+
+
+def test_nothing_saved_means_every_provider_on() -> None:
+ prefs = prefs_mod.load()
+ assert prefs.enabled("claude-api")
+ assert prefs.enabled("openai-codex")
+ assert prefs.hidden("openai-codex") == ()
+
+
+def test_saved_choices_round_trip() -> None:
+ prefs_mod.save(
+ prefs_mod.parse(
+ {
+ "disabled": ["grok-build"],
+ "api_only": ["claude-api"],
+ "hidden_models": {"openai-codex": ["gpt-5.5", "gpt-5.5"], "empty": []},
+ }
+ )
+ )
+ prefs = prefs_mod.load()
+ assert not prefs.enabled("grok-build")
+ assert prefs.enabled("openai-codex")
+ assert prefs.hidden("openai-codex") == ("gpt-5.5",)
+ assert "empty" not in prefs.to_dict()["hidden_models"]
+
+
+def test_a_broken_file_reads_as_nothing_saved(data_dir: Path) -> None:
+ path = data_dir / "Jarvis" / "agent_chat" / "agent_providers.json"
+ path.parent.mkdir(parents=True)
+ path.write_text("{not json", encoding="utf-8")
+ assert prefs_mod.load() == prefs_mod.AgentProviderPrefs()
+ assert prefs_mod.parse(["disabled"]) == prefs_mod.AgentProviderPrefs()
+
+
+def test_claude_on_its_key_changes_the_agents_surface_only(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(service, "_claude_cli_installed", lambda: True)
+ assert service.resolve_runner("claude-api", surface="society") == "claude-cli"
+
+ prefs_mod.save(prefs_mod.parse({"api_only": ["claude-api"]}))
+
+ assert service.resolve_runner("claude-api", surface="society") not in ("claude-cli", "unknown")
+ assert service.resolve_runner("claude-api", surface="agent") == "claude-cli"
+
+
+def test_the_page_route_merges_and_refuses_unknown_ids() -> None:
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from jarvis.ui.web.society_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ client = TestClient(app)
+
+ assert client.get("/api/society/provider-prefs").json()["disabled"] == []
+ saved = client.put("/api/society/provider-prefs", json={"disabled": ["grok-build"]}).json()
+ assert saved["disabled"] == ["grok-build"]
+ merged = client.put(
+ "/api/society/provider-prefs", json={"hidden_models": {"openai-codex": ["gpt-5.5"]}}
+ ).json()
+ assert merged["disabled"] == ["grok-build"]
+ assert merged["hidden_models"] == {"openai-codex": ["gpt-5.5"]}
+ refused = client.put("/api/society/provider-prefs", json={"disabled": ["no-such-provider"]})
+ assert refused.status_code == 422
+ assert prefs_mod.load().disabled == frozenset({"grok-build"})