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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(settings): rebuild API Keys as one entry per provider
rubenluetke10-beepad3d46fcf7f3
diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.local-mode.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.local-mode.test.tsxdeleted file mode 100644index 41aaffc64d..0000000000--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.local-mode.test.tsx+++ /dev/null@@ -1,159 +0,0 @@-/**- * Local Mode on the Subagents tab.- *- * This tab was the one place the switch did not reach, which made the whole- * feature look unreliable: a keyless install turned Local Mode on, saw the- * provider tiers filter correctly, then opened the tab that picks the WORKER —- * the one decision a local-only install cares most about — and got the full- * wall of hosted accounts back. These tests pin that it filters here too, and- * that it filters the subscription-login cards as well, not only the API column.- */-import { cleanup, render, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";--vi.mock("@/i18n", () => ({- useT: () => (key: string) => key,-}));--vi.mock("@/store/events", () => ({- useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>- selector({ pushToast: vi.fn() }),-}));--import { setLocalMode } from "@/lib/localMode";-import { JarvisAgentSection } from "./JarvisAgentSection";--function row(- jarvis: string,- billing: string,- {- active = false,- keyless = false,- label = `${jarvis} card`,- }: { active?: boolean; keyless?: boolean; label?: string } = {},-) {- return {- jarvis,- worker_slug: jarvis,- env_var: `${jarvis.toUpperCase()}_API_KEY`,- env_fallback: null,- key_set: keyless,- api_key_set: false,- dedicated_key_set: false,- shared_key_set: false,- oauth_connected: false,- credential_source: "none",- secret_key: keyless ? null : `jarvis_agent_${jarvis}_api_key`,- dashboard_url: null,- credential_help: null,- is_active_brain: active,- keyless,- // A distinct label per row: the raw slug also appears in card body copy, so- // querying by it would match more than the card title.- label,- billing,- };-}--const STATUS = {- configured: true,- enabled: true,- binary_path: "openclaw",- binary_detected: null,- version_pin: null,- time_cap_min: null,- concurrency: null,- state_dir_root: null,- brain_primary: "ollama",- provider_slug: "ollama",- model_override: null,- sub_model_override: null,- model_resolved: null,- mapping: [- row("openai", "api"),- row("gemini", "api"),- row("claude-api", "subscription_or_api"),- row("openai-codex", "subscription_or_api"),- row("ollama", "local", { keyless: true }),- row("local-openai", "local", { keyless: true }),- ],-};--function mockFetch(status: unknown = STATUS) {- return vi.fn().mockImplementation(async (url: string) => {- const u = String(url);- if (u.includes("/api/jarvis-agent/status")) {- return { ok: true, json: async () => status };- }- return { ok: true, json: async () => ({}) };- });-}--afterEach(() => {- cleanup();- vi.restoreAllMocks();- setLocalMode(false);- window.localStorage.clear();-});--describe("JarvisAgentSection — Local Mode", () => {- it("shows every worker while Local Mode is off", async () => {- vi.stubGlobal("fetch", mockFetch());- render(<JarvisAgentSection />);-- expect((await screen.findAllByText("openai card")).length).toBeGreaterThan(0);- expect(screen.getAllByText("ollama card").length).toBeGreaterThan(0);- expect(screen.queryByTestId("local-mode-notice")).toBeNull();- });-- it("keeps only own-hardware workers when Local Mode is on", async () => {- setLocalMode(true);- vi.stubGlobal("fetch", mockFetch());- render(<JarvisAgentSection />);-- expect((await screen.findAllByText("ollama card")).length).toBeGreaterThan(0);- expect(screen.getAllByText("local-openai card").length).toBeGreaterThan(0);- expect(screen.queryAllByText("openai card")).toHaveLength(0);- expect(screen.queryAllByText("gemini card")).toHaveLength(0);- });-- it("filters the subscription-login cards too, not just the API column", async () => {- setLocalMode(true);- vi.stubGlobal("fetch", mockFetch());- render(<JarvisAgentSection />);-- await screen.findAllByText("ollama card");- // The three dual-billed / subscription connection cards render their own- // headings; none of them survives a filter that means "own hardware only".- expect(screen.queryByText("Subscription logins")).toBeNull();- expect(screen.queryByText("API keys")).toBeNull();- });-- it("explains the shorter list and counts what it hid", async () => {- setLocalMode(true);- vi.stubGlobal("fetch", mockFetch());- render(<JarvisAgentSection />);-- const notice = await screen.findByTestId("local-mode-notice");- // openai, gemini, claude-api, openai-codex — four hosted workers.- expect(notice.getAttribute("data-hidden-count")).toBe("4");- });-- it("never hides the worker that is actually active", async () => {- setLocalMode(true);- const status = {- ...STATUS,- mapping: [- row("openai", "api", { active: true }),- row("gemini", "api"),- row("ollama", "local", { keyless: true }),- ],- };- vi.stubGlobal("fetch", mockFetch(status));- render(<JarvisAgentSection />);-- await waitFor(() => expect(screen.getByText("ollama card")).toBeTruthy());- expect(screen.getAllByText("openai card").length).toBeGreaterThan(0);- expect(screen.queryAllByText("gemini card")).toHaveLength(0);- });-});diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsxdeleted file mode 100644index 3ef40055c9..0000000000--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx+++ /dev/null@@ -1,174 +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,-}));--vi.mock("@/store/events", () => ({- useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>- selector({ pushToast: vi.fn() }),-}));--import { JarvisAgentSection } from "./JarvisAgentSection";--const STATUS = {- configured: true,- enabled: true,- binary_path: "openclaw",- binary_detected: "/usr/bin/openclaw",- version_pin: null,- time_cap_min: null,- concurrency: null,- state_dir_root: null,- brain_primary: "claude-api",- provider_slug: "claude-cli",- model_override: null,- sub_model_override: "claude-sonnet-4-6",- model_resolved: "claude-cli/claude-sonnet-4-6",- mapping: [],-};--const MODELS = {- provider: "claude-api",- current_model: "claude-sonnet-4-6",- models: [- { id: "claude-opus-4-8", label: "Claude Opus 4.8" },- { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" },- ],- source: "static",- fetched_at: 0,- selects: "model",-};--const OPENAI_AGENT_ROW = {- jarvis: "openai",- worker_slug: "openai",- env_var: "OPENAI_API_KEY",- env_fallback: null,- key_set: false,- api_key_set: false,- dedicated_key_set: false,- shared_key_set: false,- oauth_connected: false,- credential_source: "none",- secret_key: "jarvis_agent_openai_api_key",- dashboard_url: "https://platform.openai.com/api-keys",- credential_help: "Dedicated Jarvis-Agent key.",- is_active_brain: false,- billing: "api",-};--function mockFetch() {- return vi.fn().mockImplementation(async (url: string) => {- const u = String(url);- if (u.includes("/api/jarvis-agent/status")) return { ok: true, json: async () => STATUS };- if (u.includes("/models")) return { ok: true, json: async () => MODELS };- if (u.includes("/api/jarvis-agent/model")) {- return {- ok: true,- json: async () => ({- ok: true,- model: "claude-opus-4-8",- persisted: true,- restart_required: true,- }),- };- }- return { ok: true, json: async () => ({}) };- });-}--afterEach(() => {- cleanup();- vi.restoreAllMocks();-});--describe("JarvisAgentSection — dedicated subagent LLM dropdown", () => {- it("opens a model dropdown for the active subagent provider", async () => {- vi.stubGlobal("fetch", mockFetch());- render(<JarvisAgentSection />);- const trigger = (await screen.findByLabelText(- "apikeys_model.model_label",- )) as HTMLElement;- fireEvent.click(trigger);- expect(await screen.findByText("claude-opus-4-8")).toBeTruthy();- });-- it("saves a picked model via POST /api/jarvis-agent/model", async () => {- const fetchMock = mockFetch();- vi.stubGlobal("fetch", fetchMock);- render(<JarvisAgentSection />);- const trigger = (await screen.findByLabelText(- "apikeys_model.model_label",- )) as HTMLElement;- fireEvent.click(trigger);- fireEvent.click(await screen.findByText("claude-opus-4-8"));-- await waitFor(() => {- const post = fetchMock.mock.calls.find(- (c) =>- String(c[0]).includes("/api/jarvis-agent/model") &&- (c[1] as RequestInit | undefined)?.method === "POST",- );- expect(post).toBeDefined();- expect(JSON.parse((post![1] as RequestInit).body as string).model).toBe(- "claude-opus-4-8",- );- });- });-- it("makes a worker the active one on a single click of its row", async () => {- const status = {- ...STATUS,- mapping: [{ ...OPENAI_AGENT_ROW, key_set: true, dedicated_key_set: true }],- };- const fetchMock = vi.fn().mockImplementation(async (url: string, init?: RequestInit) => {- const u = String(url);- if (u.includes("/api/jarvis-agent/status")) return { ok: true, json: async () => status };- if (u.includes("/api/jarvis-agent/switch")) {- return { ok: true, json: async () => ({ ok: true, provider: "openai", restart_required: false }) };- }- void init;- return { ok: true, json: async () => ({}) };- });- vi.stubGlobal("fetch", fetchMock);-- render(<JarvisAgentSection />);- const title = await screen.findByText("OpenAI");- // A real double click is click, click, dblclick — the first click already- // selected the row, the rest is ignored: exactly one switch.- fireEvent.click(title);- fireEvent.click(title, { detail: 2 });- fireEvent.doubleClick(title);-- await waitFor(() =>- expect(- fetchMock.mock.calls.filter((c) => String(c[0]).includes("/api/jarvis-agent/switch")),- ).toHaveLength(1),- );- });-- it("renders a dedicated API-key input on the Jarvis-Agents card", async () => {- const status = { ...STATUS, mapping: [OPENAI_AGENT_ROW] };- vi.stubGlobal(- "fetch",- vi.fn().mockImplementation(async (url: string) => {- if (String(url).includes("/api/jarvis-agent/status")) {- return { ok: true, json: async () => status };- }- return { ok: true, json: async () => ({}) };- }),- );-- render(<JarvisAgentSection />);-- // The key field lives in the row body, which opens on click (the active- // worker opens by itself; this fixture's row is not the active one).- fireEvent.click(await screen.findByText("OpenAI"));- expect(- await screen.findByLabelText("Enter jarvis_agent_openai_api_key"),- ).toBeTruthy();- });-});diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxdeleted file mode 100644index 3899cf1fa1..0000000000--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ /dev/null@@ -1,1765 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";-import { Bot, ChevronDown, FlaskConical, Frame, HardDrive, KeyRound, Lock, LogIn, LogOut, Terminal, type LucideIcon } from "lucide-react";-import { agentBrandNow, useAgentBrand } from "@/lib/agentBrand";-import { PromptWriterCard } from "@/components/PromptWriterCard";-import { cn } from "@/lib/utils";-import { useT } from "@/i18n";-import { useEventStore } from "@/store/events";-import {- codexLogout,- loginAntigravity,- loginClaude,- loginGrokBuild,- logoutAntigravity,- logoutClaude,- logoutGrokBuild,- saveSubagentModel,- startCodexLogin,- switchSubagentProvider,- testAgentCli,- useProviders,- type AgentCliTestResult,- type AntigravityStatus,- type Billing,- type ClaudeStatus,- type CodexStatus,- type GrokBuildStatus,-} from "@/hooks/useProviders";-import { BrainModelSelector } from "@/components/BrainModelSelector";-import { ApiKeyForm } from "@/components/ApiKeyForm";-import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";-import { Button } from "@/components/ui/button";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { useRowGestures } from "@/components/providers/rowGestures";-import {- LocalModeNotice,- LocalModelDownloadPanel,- StateChip,-} from "@/components/providers/ProviderTierSection";-import { filterForLocalMode, useLocalMode } from "@/lib/localMode";--/**- * Subagent tier for the API-Keys view.- *- * Visually a sibling of the provider tiers in `ApiKeysView`: the same row- * anatomy (brand mark · name · state · detail, the Use control on the right,- * one editor body open at a time), in three groups — own hardware, coding- * CLIs, API keys — so the three ways a worker is powered never mix. Each API- * row carries its own scoped key field. Legacy shared Brain credentials remain- * a visible compatibility fallback, never the only configuration path.- *- * Data source is `GET /api/jarvis-agent/status`; the switch posts to- * `POST /api/jarvis-agent/switch` (3-layer persist). This is its own section- * rather than a fourth `ProviderTier` because the status payload differs.- * The endpoint path and the JSON keys below are the server contract; the- * user-facing UI brands the agent system with the wake-word-derived assistant- * name ("Ruben" -> "Ruben-Agent") via agentBrand — never a hardcoded name.- */--interface SubagentMappingRow {- jarvis: string;- /** Server contract: the worker-harness provider slug (e.g. "google"). */- worker_slug: string;- env_var: string;- env_fallback: string | null;- key_set: boolean;- api_key_set: boolean;- dedicated_key_set: boolean;- shared_key_set: boolean;- oauth_connected: boolean;- credential_source: string;- secret_key: string | null;- dashboard_url: string | null;- credential_help: string | null;- is_active_brain: boolean;- /** Runs on the user's own hardware and has no credential at all. Such a card- * is ready the moment it exists — asking it for a key locked a local-only- * install out of picking any worker. */- keyless?: boolean;- /** The card's own display name from the provider spec, so the picker stops- * showing raw ids ("local-openai") next to proper labels ("xAI Grok"). */- label?: string | null;- /** How this subagent is billed — "api" (per token) / "subscription" /- * "subscription_or_api". Drives the billing badge so the API-vs-subscription- * distinction is visible right on the subagent cards. */- billing: Billing;-}--interface SubagentStatus {- configured: boolean;- enabled: boolean;- binary_path: string;- binary_detected: string | null;- version_pin: string | null;- time_cap_min: number | null;- concurrency: number | null;- state_dir_root: string | null;- brain_primary: string;- provider_slug: string | null;- model_override: string | null;- /** The dedicated subagent LLM pin ([brain.sub_jarvis].model); empty/null- * means "the active provider's deep model" (shown via model_resolved). */- sub_model_override: string | null;- model_resolved: string | null;- mapping: SubagentMappingRow[];-}--// Human-readable card titles for the known sub-agent providers; falls back to-// the raw jarvis slug for anything not listed.-const PROVIDER_LABELS: Record<string, string> = {- gemini: "Google Gemini",- "claude-api": "Anthropic Claude",- openai: "OpenAI",- openrouter: "OpenRouter",- grok: "xAI Grok",- nvidia: "NVIDIA NIM",- // Codex is a direct worker (ChatGPT subscription / OpenAI key), not a- // Jarvis-Agent-routed provider — surfaced as its own selectable subagent row.- "openai-codex": "OpenAI Codex",- // Antigravity drives the Google subscription CLI as a direct worker (OAuth, no- // API key), the Google sibling of Codex.- antigravity: "Antigravity (Google subscription)",- "grok-build": "Grok Build",-};--/**- * The disclosure key of a row. Claude is the one slug that renders TWICE —- * a subscription row and an API-key row — so its key carries which of the two- * the live auth mode belongs to; every other slug is its own key.- */-function rowId(slug: string, claudeMode?: string | null): string {- if (slug !== "claude-api") return slug;- return claudeMode === "api_key" ? "claude-api:api" : "claude-api:sub";-}--/**- * Poll a CLI status endpoint after starting an external login flow, refreshing- * the section on each tick, until it reports `connected` or a timeout.- *- * Why: external CLI logins (Codex `codex login`, Antigravity Google sign-in)- * complete in a SEPARATE browser/console window AFTER the POST returns, so a- * single immediate refetch always reads the still-disconnected state. Without- * this poll the card stays "open" / locked until the user manually reloads —- * the exact "I connected Codex but can't select it" symptom.- */-async function pollStatusUntilConnected(- statusUrl: string,- onTick: () => void | Promise<void>,- {- maxMs = 120_000,- intervalMs = 2_500,- isReady,- }: {- maxMs?: number;- intervalMs?: number;- isReady?: (data: { connected?: boolean; mode?: string }) => boolean;- } = {},-): Promise<boolean> {- const ready = isReady ?? ((data) => Boolean(data?.connected));- const deadline = Date.now() + maxMs;- while (Date.now() < deadline) {- await new Promise((r) => setTimeout(r, intervalMs));- await onTick();- try {- const res = await fetch(statusUrl);- if (res.ok) {- const data = await res.json();- if (ready(data)) return true;- }- } catch {- // transient (app restarting / network blip) — keep polling- }- }- return false;-}--export function JarvisAgentSection({- hideHeader = false,-}: {- /** Suppress the section header — used inside the API-Keys "Subagents" tab,- * whose category hero already shows the title (avoids a double label). */- hideHeader?: boolean;-} = {}) {- const t = useT();- const [bridge, setBridge] = useState<SubagentStatus | null>(null);- const [codexStatus, setCodexStatus] = useState<CodexStatus | null>(null);- const [antigravityStatus, setAntigravityStatus] =- useState<AntigravityStatus | null>(null);- const [claudeStatus, setClaudeStatus] = useState<ClaudeStatus | null>(null);- const [grokBuildStatus, setGrokBuildStatus] = useState<GrokBuildStatus | null>(null);- const [error, setError] = useState<string | null>(null);- // The same per-machine view preference the provider tiers read. The subagent- // tier used to ignore it, which made Local Mode look broken exactly where a- // keyless install most needs it: this is the tab that picks the worker.- const { localMode, setLocalMode } = useLocalMode();- // One row open at a time, the active worker by default. Anchored once, on- // the first status that arrives: re-opening on every refetch would yank the- // list under the pointer the moment a switch lands.- const [openRow, setOpenRow] = useState<string | null>(null);- const openRowAnchored = useRef(false);- const toggleRow = (id: string) => setOpenRow((cur) => (cur === id ? null : id));-- // Re-fetch on brain-switch / subagent-switch / secret-set so the active- // provider highlight + the per-provider "Key gesetzt" badges track live.- const reload = useCallback(async () => {- try {- const [res, codexRes, antigravityRes, claudeRes, grokBuildRes] = await Promise.all([- fetch("/api/jarvis-agent/status"),- fetch("/api/codex/status").catch(() => null),- fetch("/api/antigravity/status").catch(() => null),- fetch("/api/claude/status").catch(() => null),- fetch("/api/grok-build/status").catch(() => null),- ]);- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const data: SubagentStatus = await res.json();- setBridge(data);- const codexData: CodexStatus | null = codexRes?.ok ? await codexRes.json() : null;- setCodexStatus(codexData);- if (antigravityRes?.ok) {- setAntigravityStatus(await antigravityRes.json());- } else {- setAntigravityStatus(null);- }- const claudeData: ClaudeStatus | null = claudeRes?.ok ? await claudeRes.json() : null;- setClaudeStatus(claudeData);- if (grokBuildRes?.ok) {- setGrokBuildStatus(await grokBuildRes.json());- } else {- setGrokBuildStatus(null);- }- if (!openRowAnchored.current) {- openRowAnchored.current = true;- const active = data.mapping.find((r) => r.is_active_brain);- setOpenRow(- active- ? rowId(active.jarvis, active.jarvis === "claude-api" ? claudeData?.mode : undefined)- : null,- );- }- setError(null);- } catch (e) {- setError((e as Error).message);- }- }, []);-- useEffect(() => {- void reload();- const onChange = () => void reload();- window.addEventListener("jarvis:brain-switched", onChange);- window.addEventListener("jarvis:agent-switched", onChange);- window.addEventListener("jarvis:secret-configured", onChange);- return () => {- window.removeEventListener("jarvis:brain-switched", onChange);- window.removeEventListener("jarvis:agent-switched", onChange);- window.removeEventListener("jarvis:secret-configured", onChange);- };- }, [reload]);-- if (error) {- return (- <section>- {!hideHeader && <SectionHeader label={t("apikeys_view.tier_subagent")} />}- <p className="text-xs text-destructive">Status unavailable: {error}</p>- </section>- );- }-- if (!bridge) return null;-- // Codex + Antigravity are subscription logins (OAuth) rendered as their own- // connection cards; their "Set active" control now lives ON those cards, so- // exclude them from the generic provider list to avoid a duplicate card per- // CLI (the confusing "no select button on the subscription" the user hit).- // Local Mode applies to EVERY card on this tab, including the three- // subscription-login cards below — a keyless install has no ChatGPT plan- // either, and hiding only the API column would have been a half-answer.- // Same rule as the provider tiers: own-hardware cards stay, plus whichever- // card is the ACTIVE worker, so the tab can always show what is running.- const isActiveRow = (r: SubagentMappingRow) => r.is_active_brain;- const { visible: localVisibleRows, hiddenCount: hiddenByLocalMode } =- filterForLocalMode(bridge.mapping, localMode, isActiveRow);- const shown = new Set(localVisibleRows.map((r) => r.jarvis));- const inLocalMode = (r: SubagentMappingRow | undefined) =>- r && shown.has(r.jarvis) ? r : undefined;-- const codexRow = inLocalMode(- bridge.mapping.find((r) => r.jarvis === "openai-codex"),- );- const antigravityRow = inLocalMode(- bridge.mapping.find((r) => r.jarvis === "antigravity"),- );- // Claude is dual-billed (Claude Max subscription OR Anthropic API key) — it- // gets its own connection card showing the signed-in account, like Codex /- // Antigravity, so exclude it from the generic per-key provider list too.- const claudeRow = inLocalMode(- bridge.mapping.find((r) => r.jarvis === "claude-api"),- );- const grokBuildRow = inLocalMode(- bridge.mapping.find((r) => r.jarvis === "grok-build"),- );- const providerRows = localVisibleRows.filter(- (r) =>- r.jarvis !== "openai-codex" &&- r.jarvis !== "antigravity" &&- r.jarvis !== "claude-api" &&- r.jarvis !== "grok-build",- );- // Split the generic providers by access type so each lands in the right- // group. Splitting on the backend `billing` field keeps a future provider in- // the correct group instead of the wrong one (AP-21: gate on capability,- // never a provider name).- //- // Own-hardware workers get their OWN group rather than riding along in the- // subscription column. They were landing there because the split was- // "anything that is not billed per token", which put Ollama under a heading- // that reads "sign in with an account" — the opposite of what a keyless card- // is. Three access types, three headings.- const localProviderRows = providerRows.filter((r) => r.billing === "local");- const subProviderRows = providerRows.filter(- (r) => r.billing !== "api" && r.billing !== "local",- );- const apiProviderRows = providerRows.filter((r) => r.billing === "api");- const hasSubscriptionColumn =- Boolean(codexRow || antigravityRow || claudeRow || grokBuildRow) ||- subProviderRows.length > 0;- const hasApiColumn = Boolean(claudeRow) || apiProviderRows.length > 0;-- const disclosure = (id: string) => ({- expanded: openRow === id,- onToggle: () => toggleRow(id),- });-- return (- <section className="space-y-4">- {!hideHeader && <SectionHeader label={t("apikeys_view.tier_subagent")} />}-- {localMode && hiddenByLocalMode > 0 && (- <LocalModeNotice- hiddenCount={hiddenByLocalMode}- keptActiveHosted={localVisibleRows.some(- (r) => isActiveRow(r) && r.billing !== "local",- )}- onDisable={() => setLocalMode(false)}- />- )}-- <BridgeStatusStrip status={bridge} />-- {/* The model pin sits right under the status line — it is the setting- users come back for, so it must not hide below the worker rows. */}- <SubagentModelCard status={bridge} onSaved={reload} />-- {/* Who writes the Agentic-IDE briefs. Sits next to the model pin because- it is the same kind of decision — which model does work on the user's- behalf — and because the groups below are exactly the choice it is- about: a coding CLI you are signed in to, or an API key. */}- <PromptWriterCard />-- {/* Three groups, three lists: the three ways a worker is powered never- mix, and each heading says what the rows under it need. Own-hardware- workers lead — they are the group with no account and no bill behind- them, and putting them first is what makes this tab usable at all on- an install that entered no credentials. */}- {localProviderRows.length > 0 && (- <AgentGroup- icon={HardDrive}- title="On your own hardware"- hint="no account, no key"- testId="agent-group-local"- >- {localProviderRows.map((row) => (- <SubagentProviderCard- key={row.jarvis}- row={row}- onSwitched={reload}- {...disclosure(row.jarvis)}- />- ))}- </AgentGroup>- )}-- {hasSubscriptionColumn && (- <AgentGroup- icon={Terminal}- title="Coding CLIs"- hint="sign in with a subscription — no key"- testId="agent-group-clis"- tourId="apikeys-subscriptions"- >- {codexRow && (- <CodexConnectionCard- status={codexStatus}- row={codexRow}- onChanged={reload}- {...disclosure("openai-codex")}- />- )}- {antigravityRow && (- <AntigravityConnectionCard- status={antigravityStatus}- row={antigravityRow}- onChanged={reload}- {...disclosure("antigravity")}- />- )}- {claudeRow && (- <ClaudeConnectionCard- status={claudeStatus}- row={claudeRow}- onChanged={reload}- {...disclosure("claude-api:sub")}- />- )}- {grokBuildRow && (- <GrokBuildConnectionCard- status={grokBuildStatus}- row={grokBuildRow}- onChanged={reload}- {...disclosure("grok-build")}- />- )}- {subProviderRows.map((row) => (- <SubagentProviderCard- key={row.jarvis}- row={row}- onSwitched={reload}- {...disclosure(row.jarvis)}- />- ))}- </AgentGroup>- )}-- {hasApiColumn && (- <AgentGroup- icon={KeyRound}- title="API keys"- hint="billed per token · a dedicated key per worker; shared Brain keys stay a fallback"- testId="agent-group-api"- >- {claudeRow && (- <ClaudeApiCard- status={claudeStatus}- row={claudeRow}- onChanged={reload}- {...disclosure("claude-api:api")}- />- )}- {apiProviderRows.map((row) => (- <SubagentProviderCard- key={row.jarvis}- row={row}- onSwitched={reload}- {...disclosure(row.jarvis)}- />- ))}- </AgentGroup>- )}-- {/* Below the groups rather than inside one: this is a second axis.- The rows above answer "which provider powers the agent"; this answers- "which of YOUR seats on that provider", and a panel holding two Claude- Max logins does not belong in a list of one-login-per-provider rows. */}- <AgentAccountsPanel />- </section>- );-}--/**- * The dedicated subagent LLM model pin. Mirrors the Wiki card's- * "model (optional)" pattern: empty means the active provider's deep- * (frontier) model — shown in the hint via `model_resolved` — and a concrete- * id overrides it for every heavy-task worker spawn.- */-/**- * The dedicated subagent LLM model pin — the SAME dropdown as the brain cards,- * showing the active subagent provider's catalog (``brain_primary``) and saving- * through the subagent endpoint (POST /api/subagent/model) instead of the- * per-provider model route. Empty selection = the provider's deep/frontier model- * (shown in the hint via ``model_resolved``).- */-function SubagentModelCard({- status,- onSaved,-}: {- status: SubagentStatus;- onSaved: () => void;-}) {- const t = useT();- // The subagent worker slug → the catalog provider id (Codex's worker slug- // "openai-codex" maps to the catalog's "codex"; all others match 1:1).- const catalogProvider =- status.brain_primary === "openai-codex"- ? "codex"- : status.brain_primary === "grok-build"- ? "grok-build"- : status.brain_primary;- // Whether the ACTIVE worker's server can be told to download a model. Read- // off the provider catalog rather than a provider name, so a second local- // server type that ships a puller lights this up on its own (AP-21).- const { providers } = useProviders();- const pullable = providers.find(- (p) => p.id === catalogProvider && p.supports_model_pull,- );- return (- <div className="space-y-3 rounded-surface border border-border bg-card p-3.5">- <p className="text-xs leading-relaxed text-muted-foreground">- {t("subagent_model.description")}- </p>- {catalogProvider ? (- <BrainModelSelector- providerId={catalogProvider}- currentModel={status.sub_model_override ?? ""}- healthSection="subagents"- healthActive- onSave={async (model) => {- const r = await saveSubagentModel(model);- window.dispatchEvent(new Event("jarvis:agent-switched"));- onSaved();- return {- ok: true,- provider: status.brain_primary,- model,- persisted: r.persisted,- applied_live: false,- restart_required: r.restart_required,- probe: null,- };- }}- />- ) : (- <p className="text-xs text-muted-foreground">{t("subagent_model.model_hint")}</p>- )}- <p className="text-xs text-muted-foreground">- {t("subagent_model.model_hint")}- {status.model_resolved ? ` (${status.model_resolved})` : ""}- </p>-- {/* The download panel, for a worker whose server can be told to fetch a- model. Without it this tab dead-ended a local-only install: the picker- above lists what the server HOLDS, so on a fresh Ollama it is empty,- and the one screen that could fix that was three tabs away under- Brain. Same panel, same endpoints — the capability flag decides. */}- {pullable && <LocalModelDownloadPanel descriptor={pullable} onChanged={onSaved} />}- </div>- );-}--function SectionHeader({ label }: { label: string }) {- return (- <h3 className="mb-3 inline-flex items-center gap-2 text-micro text-muted-foreground">- <Bot className="h-3.5 w-3.5" /> {label}- </h3>- );-}--/**- * The bridge status — one line, not a box. A status dot + plain-language- * state, then the read-only worker / model / limits as dim text separated by- * middots, and the one action (open the run visuals) on the right. Engine- * internals (binary path etc.) are reduced to "installed" / "not installed";- * the concrete path is developer noise and is not surfaced.- */-function BridgeStatusStrip({ status }: { status: SubagentStatus }) {- const t = useT();- const activeRow = status.mapping.find((row) => row.is_active_brain);- const live = Boolean(activeRow?.key_set);- const worker = PROVIDER_LABELS[status.brain_primary] ?? status.brain_primary;- const model = status.model_resolved ?? status.sub_model_override ?? null;- /*- * The one place in this section that talks to another one.- *- * This strip describes the worker that RUNS; whatever it drew ends up in the- * run archive, and until now the only way to that picture was to remember the- * filename and go looking for it in Outputs. `requestVisual` hands the stage a- * target and moves the app there in a single state update — see- * VisualStageRequest in store/events.ts for why the section is asked rather- * than reached into.- */- const requestVisual = useEventStore((s) => s.requestVisual);-- return (- <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5 py-1 text-xs">- <span className="inline-flex shrink-0 items-center gap-2">- <span- aria-hidden="true"- className={cn(- "h-[7px] w-[7px] shrink-0 rounded-full",- live- ? "bg-muted-foreground"- : "bg-foreground",- )}- />- <span className="font-medium text-foreground">- {live ? "Agent provider configured" : "Agent provider needs setup"}- </span>- </span>- <span aria-hidden="true" className="text-border">·</span>- <span className="min-w-0 truncate text-muted-foreground">- {live ? "Credential or subscription available" : "Add a key or connect a login"}- {" · worker "}- <span className="font-medium text-foreground">{worker}</span>- {model && (- <>- {" · "}- <span className="font-mono">{model}</span>- </>- )}- {status.time_cap_min !== null && (- <>{` · ${status.time_cap_min} min · max ${status.concurrency} parallel`}</>- )}- {status.version_pin && (- <>- {" · pin "}- <span className="font-mono">{status.version_pin}</span>- </>- )}- </span>- <button- type="button"- onClick={() => requestVisual()}- data-testid="agent-show-visuals"- title={t("visualization.open_from_agent_hint")}- className="ml-auto inline-flex shrink-0 items-center gap-1.5 rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <Frame className="h-3.5 w-3.5" aria-hidden />- {t("visualization.open_from_agent")}- </button>- </div>- );-}--/**- * One of the three worker groups — own hardware, coding CLIs, API keys — as a- * kicker line over its own bordered list. Three headings, three lists, no- * colour-coding: the grouping IS the distinction the old violet/sky/emerald- * stripes tried to draw, and it reads without a legend.- */-function AgentGroup({- icon: Icon,- title,- hint,- testId,- tourId,- children,-}: {- icon: LucideIcon;- title: string;- hint: string;- testId?: string;- /** A stable hook for the first-run guide (`data-tour`). */- tourId?: string;- children: React.ReactNode;-}) {- return (- <div data-testid={testId} data-tour={tourId} className="space-y-2">- <div className="flex min-w-0 items-center gap-2 px-0.5 text-xs">- <Icon aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-primary" />- <span className="font-display text-meta font-semibold tracking-tight">{title}</span>- <span aria-hidden="true" className="text-border">·</span>- <span className="truncate text-muted-foreground">{hint}</span>- </div>- <ul className="divide-y divide-border overflow-hidden rounded-surface border border-border bg-card">- {children}- </ul>- </div>- );-}--/**- * The one shared row every worker is built from — the same anatomy as the- * provider rows on the other tabs, so the whole screen reads as one list- * system: logo · name · state · one-line detail on the left, the action and- * the Use control on the right, a chevron when there is a body to open.- *- * The body (key field, install hint, CLI test) mounts only while open; the- * section opens one row at a time, the active worker by default.- */-function AgentRow({- label,- slug,- title,- state,- subtitle,- actions,- body,- active = false,- expanded = false,- onToggle,- onActivate,- tooltip,- testId,-}: {- label: string;- /** Worker slug driving the brand mark (the shared ProviderLogo family map). */- slug?: string;- title: React.ReactNode;- /** The row's state word. "active" draws no chip (the edge rule and the Use- * control say it); anything else is a dot + word beside the name. */- state: "active" | AgentState;- subtitle?: React.ReactNode;- /** Header-right controls: Connect / Disconnect and the Use radio. */- actions?: React.ReactNode;- /** Editor body under the row; absent means the row has nothing to open. */- body?: React.ReactNode;- active?: boolean;- expanded?: boolean;- onToggle?: () => void;- /** Click action: make this the worker (the Use control's path). Absent- * when a click must not switch — the row is active, or lacks its key. */- onActivate?: () => void;- /** Native hover tooltip for the row header. */- tooltip?: string;- testId?: string;-}) {- const collapsible = Boolean(body && onToggle);- // One click selects the row: the body opens AND this becomes the worker —- // the same path as the Use control (see rowGestures.ts).- const rowGestures = useRowGestures({- expanded,- onToggle: collapsible ? onToggle : undefined,- onActivate,- });-- return (- <li- data-testid={testId}- data-expanded={expanded ? "true" : "false"}- className={cn(- "relative",- // Said once, at the edge: a 3 px gold rule and a faint wash mark the- // worker that runs, instead of a gold frame plus glow plus chip.- active &&- "bg-primary/[0.035] before:absolute before:inset-y-2 before:left-0 before:w-[3px] before:rounded-r before:bg-foreground/70",- )}- >- <div- role={collapsible ? "button" : undefined}- tabIndex={collapsible ? 0 : undefined}- aria-expanded={collapsible ? expanded : undefined}- onClick={rowGestures.onClick}- onKeyDown={(e) => {- if (!collapsible || e.target !== e.currentTarget) return;- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- rowGestures.select();- }- }}- title={tooltip}- className={cn(- "flex items-center gap-3 px-3.5 py-3 outline-none",- collapsible &&- "cursor-pointer hover:bg-secondary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",- )}- >- <ProviderLogo providerId={slug ?? label} label={label} />- <div className="min-w-0 flex-1">- <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">- <span className="truncate font-display text-sm font-semibold tracking-tight">- {title}- </span>- {/* The active row says so on its left edge and in the Use control;- the other two states are a dot and a word beside the name. */}- {state !== "active" && (- <StateChip tone={state.tone} title={state.title}>- {state.label}- </StateChip>- )}- </div>- {subtitle && (- <p className="mt-0.5 truncate text-xs text-muted-foreground">{subtitle}</p>- )}- </div>- {actions && (- <div- data-agent-card-control- className="flex shrink-0 items-center gap-2"- onClick={(e) => e.stopPropagation()}- >- {actions}- </div>- )}- {collapsible && (- <ChevronDown- aria-hidden="true"- className={cn(- "h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none",- expanded && "rotate-180",- )}- />- )}- </div>- {body && expanded && (- <div- data-agent-card-control- className="space-y-3 border-t border-border bg-background px-3.5 pb-3.5 pl-[3.75rem] pt-3"- >- {body}- </div>- )}- </li>- );-}--/** A small amber hint line (install / locked) shown inside a row body. */-function CardHint({- icon: Icon,- children,-}: {- icon: LucideIcon;- children: React.ReactNode;-}) {- return (- <p className="flex items-start gap-1.5 text-xs text-foreground">- <Icon className="mt-0.5 h-3 w-3 shrink-0" />- <span>{children}</span>- </p>- );-}--/** Connect (primary) action shared by the CLI-login rows. */-function ConnectButton({- onClick,- disabled,-}: {- onClick: () => void;- disabled?: boolean;-}) {- return (- <Button size="sm" onClick={onClick} disabled={disabled} className="h-7 gap-1.5 rounded-control px-2.5 text-xs">- <LogIn className="h-3.5 w-3.5" />- Connect- </Button>- );-}--/** Disconnect (quiet) action shared by the CLI-login rows. */-function DisconnectButton({- onClick,- disabled,-}: {- onClick: () => void;- disabled?: boolean;-}) {- return (- <Button- size="sm"- variant="ghost"- onClick={onClick}- disabled={disabled}- className="h-7 gap-1.5 rounded-control px-2 text-xs text-muted-foreground hover:text-foreground"- >- <LogOut className="h-3.5 w-3.5" />- Disconnect- </Button>- );-}--/**- * "Test" button + inline result shared by the CLI rows.- *- * POSTs the row's live-test endpoint (the backend re-augments PATH, clears- * the version caches, and spawns the real binary), then reports found /- * not-found with the binary path, version and login state. A miss lists the- * PATH directories that were searched — making "installed in the shell but- * invisible to the app" (the macOS GUI-PATH trap) diagnosable on the row.- */-function CliTestControl({- endpoint,- onChanged,-}: {- endpoint: string;- onChanged?: () => void | Promise<void>;-}) {- const [running, setRunning] = useState(false);- const [result, setResult] = useState<AgentCliTestResult | null>(null);- const [error, setError] = useState<string | null>(null);-- async function run() {- setRunning(true);- setError(null);- try {- setResult(await testAgentCli(endpoint));- // The test may have just discovered a freshly-installed CLI (PATH was- // re-augmented) — refresh the section so the row state follows.- await onChanged?.();- } catch (e) {- setResult(null);- setError((e as Error).message);- } finally {- setRunning(false);- }- }-- return (- <div className="space-y-2 border-t border-border pt-2.5" data-agent-card-control>- <div className="flex flex-wrap items-center justify-between gap-2">- <Button- size="sm"- variant="ghost"- onClick={run}- disabled={running}- className="h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"- >- <FlaskConical className={cn("h-3.5 w-3.5", running && "animate-pulse")} />- {running ? "Testing…" : "Test"}- </Button>- {result && !error && (- <span- className={cn(- "inline-flex items-center gap-1.5 text-xs",- result.ok ? "text-muted-foreground" : "text-foreground",- )}- >- <span- aria-hidden="true"- className={cn("h-[7px] w-[7px] rounded-full", result.ok ? "bg-muted-foreground" : "bg-foreground")}- />- {result.message}- </span>- )}- {error && <span className="text-xs text-destructive">Test failed: {error}</span>}- </div>- {result && !error && result.installed && (- <p className="text-xs leading-relaxed text-muted-foreground">- {result.binary_path && (- <>- Binary: <code className="break-all">{result.binary_path}</code>- <br />- </>- )}- {result.version && <>Version: {result.version} · </>}- Login: {result.connected ? `connected (${result.auth_mode})` : "not connected"}- {result.account ? ` · ${result.account}` : ""}- </p>- )}- {result && !error && !result.installed && result.searched_path.length > 0 && (- <details className="text-xs text-muted-foreground">- <summary className="cursor-pointer select-none">- Searched {result.searched_path.length} PATH directories- </summary>- <ul className="mt-1 max-h-32 overflow-y-auto">- {result.searched_path.map((p) => (- <li key={p} className="break-all">- {p}- </li>- ))}- </ul>- </details>- )}- </div>- );-}--/**- * The honest state vocabulary of a worker row. Each word says exactly what- * the app KNOWS: a CLI that reports its login is "connected" (green); a key- * that is merely stored is "key saved" (grey, not green — nothing has proven- * it answers); "no key" / "not installed" name the missing piece. The old- * "ready" for a stored key claimed more than anyone had checked.- */-interface AgentState {- label: string;- tone: "ready" | "neutral" | "missing";- title?: string;-}-const STATE_CONNECTED: AgentState = { label: "connected", tone: "ready" };-const STATE_NOT_CONNECTED: AgentState = { label: "not connected", tone: "neutral" };-const STATE_NOT_INSTALLED: AgentState = { label: "not installed", tone: "missing" };-const STATE_KEY_SAVED: AgentState = {- label: "key saved",- tone: "neutral",- title: "A key is stored. Whether it works is proven only by a run.",-};-const STATE_SHARED_KEY: AgentState = {- label: "shared key",- tone: "neutral",- title: "No dedicated key — the shared Brain key is used as a fallback.",-};-const STATE_NO_KEY: AgentState = { label: "no key", tone: "neutral" };-const STATE_LOCAL: AgentState = { label: "no key needed", tone: "neutral" };--/** The expand/collapse plumbing every row card receives from the section. */-interface RowDisclosure {- expanded: boolean;- onToggle: () => void;-}--function CodexConnectionCard({- status,- row,- onChanged,- expanded,- onToggle,-}: {- status: CodexStatus | null;- row: SubagentMappingRow | undefined;- onChanged: () => void | Promise<void>;-} & RowDisclosure) {- const pushToast = useEventStore((s) => s.pushToast);- const [pending, setPending] = useState(false);- const { activating, activate, clickActivates } = useSubagentActivate(row, onChanged);- const connected = Boolean(status?.connected);- const installed = status?.installed ?? false;- const isActive = Boolean(row?.is_active_brain);- const email =- status?.user_email ??- status?.account_label ??- status?.accountLabel ??- null;- const detail = connected- ? `Connected as ${email}`- : status?.message || "Connected via ChatGPT"- : status?.message || "ChatGPT login not connected";-- async function connect() {- setPending(true);- try {- await startCodexLogin();- pushToast("info", "Codex login started — finish it in the browser window");- await onChanged();- // The login finishes asynchronously in the spawned console/browser, so- // poll until the CLI reports connected; then the row flips to selectable- // on its own — no manual reload needed.- void pollStatusUntilConnected("/api/codex/status", onChanged).then((ok) => {- if (ok) pushToast("success", `Codex connected — now selectable as a ${agentBrandNow()}`);- });- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- async function disconnect() {- setPending(true);- try {- await codexLogout();- pushToast("info", "Codex login disconnected");- await onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- const selectable = connected || (installed && Boolean(row?.api_key_set));- return (- <AgentRow- testId="agent-row-openai-codex"- onActivate={clickActivates ? () => void activate() : undefined}- label="OpenAI Codex"- slug={row?.jarvis}- title="OpenAI Codex"- active={isActive}- expanded={expanded}- onToggle={onToggle}- state={- isActive- ? "active"- : connected- ? STATE_CONNECTED- : !installed- ? STATE_NOT_INSTALLED- : row?.api_key_set- ? STATE_KEY_SAVED- : STATE_NOT_CONNECTED- }- subtitle={detail}- actions={- <>- {connected ? (- <DisconnectButton onClick={disconnect} disabled={pending} />- ) : (- <ConnectButton onClick={connect} disabled={pending || !installed} />- )}- {/* When connected, the same Use control as every other row — so- this subscription login is selectable right here. */}- {selectable && row && (- <SubagentActiveControl- row={row}- activating={activating}- onActivate={activate}- />- )}- </>- }- body={- <>- {/* The OpenAI key is the ALTERNATIVE way in (per-token billing), not- a requirement of the ChatGPT login. Showing it unconditionally on- this subscription row read as "the subscription needs an OpenAI- API key" (user report 2026-07-17), so render it only while the- login is absent — or when a key is actually stored, so it stays- replaceable/deletable. */}- {row?.secret_key && (!connected || row.dedicated_key_set) && (- <ApiKeyForm- secretKey={row.secret_key}- dashboardUrl={row.dashboard_url}- configured={row.dedicated_key_set}- effectiveConfigured={row.shared_key_set}- credentialHelp={row.credential_help}- onChanged={onChanged}- />- )}- {!installed && (- <CardHint icon={Terminal}>Install Codex before activating it.</CardHint>- )}- <CliTestControl endpoint="/api/codex/test" onChanged={onChanged} />- </>- }- />- );-}--function AntigravityConnectionCard({- status,- row,- onChanged,- expanded,- onToggle,-}: {- status: AntigravityStatus | null;- row: SubagentMappingRow | undefined;- onChanged: () => void | Promise<void>;-} & RowDisclosure) {- const pushToast = useEventStore((s) => s.pushToast);- const brand = useAgentBrand();- const [pending, setPending] = useState(false);- const { activating, activate, clickActivates } = useSubagentActivate(row, onChanged);- const connected = Boolean(status?.connected && status.mode === "oauth-personal");- const installed = status?.installed ?? false;- const apiKeyReady = Boolean(installed && row?.api_key_set);- // `/api/jarvis-agent/status.key_set` is the canonical readiness decision.- // Keep the independent live status gate as defense against two parallel- // responses straddling an install/uninstall. A Gemini key alone belongs to- // the separate Google Gemini row and must never make this CLI row ready.- const usable = Boolean(installed && row?.key_set);- const isActive = Boolean(usable && row?.is_active_brain);- const detail = connected- ? status?.user_email- ? `Connected as ${status.user_email}`- : status?.message || "Connected"- : apiKeyReady- ? `Gemini ${brand} API key ready (billed per token)`- : status?.message || "Google login not connected";-- async function connect() {- setPending(true);- try {- await loginAntigravity();- pushToast("info", "Google login started — finish it in the browser window");- await onChanged();- // Same as Codex: the Google sign-in completes asynchronously, so poll- // until agy reports connected and the row unlocks on its own.- void pollStatusUntilConnected("/api/antigravity/status", onChanged).then((ok) => {- if (ok) {- pushToast("success", `Antigravity connected — now selectable as a ${agentBrandNow()}`);- }- });- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- async function disconnect() {- setPending(true);- try {- await logoutAntigravity();- pushToast("info", "Google login disconnected");- await onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- return (- <AgentRow- testId="agent-row-antigravity"- onActivate={clickActivates ? () => void activate() : undefined}- label="Antigravity"- slug={row?.jarvis}- title="Antigravity"- active={isActive}- expanded={expanded}- onToggle={onToggle}- state={- isActive- ? "active"- : connected- ? STATE_CONNECTED- : !installed- ? STATE_NOT_INSTALLED- : apiKeyReady- ? STATE_KEY_SAVED- : STATE_NOT_CONNECTED- }- subtitle={detail}- actions={- <>- {connected ? (- <DisconnectButton onClick={disconnect} disabled={pending} />- ) : (- <ConnectButton onClick={connect} disabled={pending || !installed} />- )}- {usable && row && (- <SubagentActiveControl- row={row}- activating={activating}- onActivate={activate}- />- )}- </>- }- body={- <>- {!installed && (- <CardHint icon={Terminal}>- Install Antigravity or the Gemini CLI before connecting.- </CardHint>- )}- <CliTestControl endpoint="/api/antigravity/test" onChanged={onChanged} />- </>- }- />- );-}--function GrokBuildConnectionCard({- status,- row,- onChanged,- expanded,- onToggle,-}: {- status: GrokBuildStatus | null;- row: SubagentMappingRow | undefined;- onChanged: () => void | Promise<void>;-} & RowDisclosure) {- const pushToast = useEventStore((s) => s.pushToast);- const [pending, setPending] = useState(false);- const { activating, activate, clickActivates } = useSubagentActivate(row, onChanged);- const connected = Boolean(status?.connected && status.mode === "subscription");- const installed = status?.installed ?? false;- const usable = Boolean(installed && row?.key_set);- const isActive = Boolean(usable && row?.is_active_brain);- const detail = connected- ? status?.user_email- ? `Connected as ${status.user_email}`- : status?.message || "Connected via SuperGrok / X Premium+"- : status?.message || "Grok Build login not connected";-- async function connect() {- setPending(true);- try {- await loginGrokBuild();- pushToast("info", "Grok Build login started — finish it in the browser window");- await onChanged();- void pollStatusUntilConnected("/api/grok-build/status", onChanged, {- isReady: (data) =>- Boolean(data?.connected && data?.mode === "subscription"),- }).then((ok) => {- if (ok) {- pushToast("success", `Grok Build connected — now selectable as a ${agentBrandNow()}`);- }- });- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- async function disconnect() {- setPending(true);- try {- await logoutGrokBuild();- pushToast("info", "Grok Build login disconnected");- await onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- return (- <AgentRow- testId="agent-row-grok-build"- onActivate={clickActivates ? () => void activate() : undefined}- label="Grok Build"- slug={row?.jarvis}- title="Grok Build"- active={isActive}- expanded={expanded}- onToggle={onToggle}- state={- isActive- ? "active"- : connected- ? STATE_CONNECTED- : !installed- ? STATE_NOT_INSTALLED- : STATE_NOT_CONNECTED- }- subtitle={detail}- actions={- <>- {connected ? (- <DisconnectButton onClick={disconnect} disabled={pending} />- ) : (- <ConnectButton onClick={connect} disabled={pending || !installed} />- )}- {usable && row && (- <SubagentActiveControl- row={row}- activating={activating}- onActivate={activate}- />- )}- </>- }- body={- <>- {!installed && (- <CardHint icon={Terminal}>- {status?.message || "Install Grok Build before connecting."}- </CardHint>- )}- <CliTestControl endpoint="/api/grok-build/test" onChanged={onChanged} />- </>- }- />- );-}--function ClaudeConnectionCard({- status,- row,- onChanged,- expanded,- onToggle,-}: {- status: ClaudeStatus | null;- row: SubagentMappingRow | undefined;- onChanged: () => void | Promise<void>;-} & RowDisclosure) {- const pushToast = useEventStore((s) => s.pushToast);- const [pending, setPending] = useState(false);- const { activating, activate, clickActivates } = useSubagentActivate(row, onChanged);- const connected = Boolean(status?.connected && status.mode === "subscription");- const installed = status?.installed ?? false;- // Claude has ONE subagent slug (claude-api) reached by EITHER the Claude Max- // OAuth login OR an Anthropic API key — split into two sibling rows (mirror- // of Codex/OpenAI + Antigravity/Gemini). This subscription row lights up only- // when claude-api is the active worker AND it is running over the OAuth login- // (mode != "api_key"); the API key row owns the api_key mode. So exactly one- // of the two ever shows "active".- const isActive = Boolean(row?.is_active_brain) && status?.mode === "subscription";- // A subscription login shows the signed-in account + tier ("Connected as- // ruben@… · Claude Max"); not connected shows how to sign in. The API-key- // alternative lives on its own row in the API-keys group.- const detail = connected- ? status?.user_email- ? `Connected as ${status.user_email}${- status.account_label ? ` · ${status.account_label}` : ""- }`- : status?.message || "Connected"- : status?.message || "Claude login not connected";-- async function connect() {- setPending(true);- try {- await loginClaude();- pushToast("info", "Claude login started — finish it in the terminal window");- await onChanged();- // The sign-in finishes asynchronously in the spawned console, so poll- // until the CLI reports connected; the row then unlocks on its own.- void pollStatusUntilConnected("/api/claude/status", onChanged).then((ok) => {- if (ok) pushToast("success", `Claude connected — now selectable as a ${agentBrandNow()}`);- });- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- async function disconnect() {- setPending(true);- try {- await logoutClaude();- pushToast("info", "Claude subscription disconnected");- await onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(false);- }- }-- return (- <AgentRow- testId="agent-row-claude-subscription"- onActivate={clickActivates ? () => void activate() : undefined}- label="Anthropic Claude"- slug={row?.jarvis}- title="Anthropic Claude"- active={isActive}- expanded={expanded}- onToggle={onToggle}- state={- isActive- ? "active"- : connected- ? STATE_CONNECTED- : !installed- ? STATE_NOT_INSTALLED- : STATE_NOT_CONNECTED- }- subtitle={detail}- actions={- <>- {connected ? (- <DisconnectButton onClick={disconnect} disabled={pending} />- ) : (- <ConnectButton onClick={connect} disabled={pending || !installed} />- )}- {connected && row && (- <SubagentActiveControl- row={row}- active={isActive}- activating={activating}- onActivate={activate}- />- )}- </>- }- body={- <>- {!installed && (- <CardHint icon={Terminal}>Install the Claude CLI before connecting.</CardHint>- )}- <CliTestControl endpoint="/api/claude/test" onChanged={onChanged} />- </>- }- />- );-}--/**- * The Anthropic Claude (API) row — the per-token sibling of the subscription- * row above, built to behave EXACTLY like the OpenAI / Google Gemini subagent- * rows (`SubagentProviderCard`). The dedicated key is entered here; the row- * reflects whether it is set (`row.api_key_set`) and lets the user pick- * Claude-on-the-key as the heavy-task worker — locked with a pointer until the- * key exists, exactly like OpenAI/Gemini.- *- * Claude has ONE subagent slug (claude-api) reached by either auth, so this row- * and the subscription row both drive `useSubagentActivate(row)`. To keep only- * one of the two lit, "active" here means claude-api is the active worker AND it- * is running over the API key (status mode === "api_key"); the subscription row- * owns every other mode.- */-function ClaudeApiCard({- status,- row,- onChanged,- expanded,- onToggle,-}: {- status: ClaudeStatus | null;- row: SubagentMappingRow | undefined;- onChanged: () => void | Promise<void>;-} & RowDisclosure) {- const { activating, activate, clickActivates } = useSubagentActivate(row, onChanged);- const brand = useAgentBrand();- // OAuth unlocks the subscription sibling only. This API row reflects an- // actual API key, so a Claude Max login cannot paint it falsely ready.- const keySet = Boolean(row?.api_key_set);- const isActive = Boolean(row?.is_active_brain) && status?.mode === "api_key";-- return (- <AgentRow- testId="agent-row-claude-api"- onActivate={clickActivates ? () => void activate() : undefined}- label="Anthropic Claude"- slug={row?.jarvis}- title="Anthropic Claude"- active={isActive}- expanded={expanded}- onToggle={onToggle}- tooltip={- isActive- ? `This ${brand} provider is active`- : keySet- ? `Click to make this the ${brand} provider`- : `Save a dedicated Claude ${brand} key first`- }- state={isActive ? "active" : keySet ? STATE_KEY_SAVED : STATE_NO_KEY}- subtitle="API key · billed per token"- actions={- row && (- <SubagentActiveControl- row={row}- active={isActive}- activating={activating}- onActivate={activate}- />- )- }- body={- <>- {row?.secret_key && (- <ApiKeyForm- secretKey={row.secret_key}- dashboardUrl={row.dashboard_url}- configured={row.dedicated_key_set}- effectiveConfigured={row.shared_key_set}- credentialHelp={row.credential_help}- onChanged={onChanged}- />- )}- {!keySet && (- <CardHint icon={Lock}>- Locked — save a dedicated <strong>Claude API key</strong> above.- </CardHint>- )}- </>- }- />- );-}--/**- * Shared "activate this subagent provider" action (POST /api/subagent/switch,- * 3-layer persist). Used by the generic provider rows AND the CLI-login rows,- * so every selectable row behaves identically.- */-function useSubagentActivate(- row: SubagentMappingRow | undefined,- onSwitched: () => void | Promise<void>,-) {- const [activating, setActivating] = useState(false);- const pushToast = useEventStore((s) => s.pushToast);-- const activate = useCallback(async () => {- if (!row || row.is_active_brain || activating) return;- const label = PROVIDER_LABELS[row.jarvis] ?? row.jarvis;- if (!row.key_set) {- pushToast(- "warning",- row.jarvis === "openai-codex"- ? `${label}: connect the ChatGPT login first.`- : row.jarvis === "antigravity"- ? `${label}: connect the Google login first.`- : `${label}: save a key on its ${agentBrandNow()} card first.`,- );- return;- }- setActivating(true);- window.dispatchEvent(- new CustomEvent("jarvis:provider-selection-pending", {- detail: { section: "subagents", provider: row.jarvis },- }),- );- try {- const result = await switchSubagentProvider(row.jarvis);- const note = result.restart_required ? " (active from next restart)" : "";- pushToast("success", `${agentBrandNow()} → ${label}${note}`);- window.dispatchEvent(new CustomEvent("jarvis:agent-switched"));- await onSwitched();- } catch (e) {- window.dispatchEvent(- new CustomEvent("jarvis:provider-switch-failed", {- detail: { section: "subagents", provider: row.jarvis },- }),- );- pushToast("error", (e as Error).message);- } finally {- setActivating(false);- }- }, [row, activating, pushToast, onSwitched]);-- // Whether a click on the row may switch SILENTLY: a row without its key- // would only answer with the "save a key first" warning above, and the- // click that opened it was there to add that key. The active row and an- // in-flight switch are excluded too.- const clickActivates = Boolean(row?.key_set) && !row?.is_active_brain && !activating;-- return { activating, activate, clickActivates };-}--/**- * One sub-agent-capable provider as a row. The Use control switches the- * heavy-task subagent provider via `POST /api/subagent/switch` (3-layer- * persist); the key itself lives in the row body. A provider with no key- * cannot be activated (warning toast instead of a silent no-op).- */-function SubagentProviderCard({- row,- onSwitched,- expanded,- onToggle,-}: {- row: SubagentMappingRow;- onSwitched: () => void | Promise<void>;-} & RowDisclosure) {- const label = row.label ?? PROVIDER_LABELS[row.jarvis] ?? row.jarvis;- const brand = useAgentBrand();- const { activating, activate, clickActivates } = useSubagentActivate(row, onSwitched);-- return (- <AgentRow- testId={`agent-row-${row.jarvis}`}- onActivate={clickActivates ? () => void activate() : undefined}- label={label}- slug={row.jarvis}- title={label}- active={row.is_active_brain}- expanded={expanded}- onToggle={onToggle}- tooltip={- row.is_active_brain- ? `This ${brand} provider is active`- : row.key_set- ? `Click to make this the ${brand} provider`- : "Set an API key first"- }- // A keyless row has no key to wait for: it is ready as soon as it is- // listed, and every credential line below has to say so.- state={- row.is_active_brain- ? "active"- : row.keyless- ? STATE_LOCAL- : row.dedicated_key_set- ? STATE_KEY_SAVED- : row.shared_key_set- ? STATE_SHARED_KEY- : STATE_NO_KEY- }- subtitle={- row.keyless- ? "Runs on this machine — no key needed"- : row.dedicated_key_set- ? `Dedicated ${brand} key configured`- : row.shared_key_set- ? "Using the shared Brain key as a compatibility fallback"- : `Set a dedicated key for this ${brand}`- }- actions={- <SubagentActiveControl- row={row}- activating={activating}- onActivate={activate}- />- }- body={- row.secret_key || row.credential_help || !row.key_set ? (- <>- {/* The shared family key already serves this row (the runtime- falls back to it), so an empty box here asked for a second- key nobody needs — same "covered" state as the tier cards. */}- {row.secret_key && (- <ApiKeyForm- secretKey={row.secret_key}- dashboardUrl={row.dashboard_url}- configured={row.dedicated_key_set}- effectiveConfigured={row.shared_key_set}- credentialHelp={row.credential_help}- onChanged={onSwitched}- />- )}- {row.keyless && row.credential_help && (- <p className="text-xs leading-relaxed text-muted-foreground">- {row.credential_help}- </p>- )}- {!row.key_set && (- <CardHint icon={Lock}>- Locked — save a dedicated <strong>{label}</strong> key on this row.- </CardHint>- )}- </>- ) : undefined- }- />- );-}--/**- * The Use control, mirroring `ActiveControl` on the provider rows: visually a- * state word ("Active") or a quiet action ("Set active"), semantically still a- * radio in the `active-subagent` group so browsers, screen readers and the- * tests keep native single-select. Source of truth stays `row.is_active_brain`- * from `/api/jarvis-agent/status`; the radio reflects the server state and is- * not held locally. It is NOT disabled when the key is missing — `activate()`- * routes a warning toast so every click gets a reaction.- */-function SubagentActiveControl({- row,- activating,- onActivate,- active,-}: {- row: SubagentMappingRow;- activating: boolean;- onActivate: () => void;- /**- * Explicit active state, overriding `row.is_active_brain`. The two Claude- * rows share ONE slug (claude-api), so the raw row flag would light BOTH- * radios at once. Each Claude row passes its mode-split flag here so only the- * row matching the live auth (subscription vs API key) shows "Active". Other- * rows omit it and fall back to the row flag.- */- active?: boolean;-}) {- const brand = useAgentBrand();- const isActive = active ?? row.is_active_brain;- const labelTitle = isActive- ? `This ${brand} provider is active`- : row.key_set- ? `Click to make this the ${brand} provider`- : "Set an API key first";-- return (- <label- onClick={(e) => e.stopPropagation()}- onDoubleClick={(e) => e.stopPropagation()}- className={cn(- "inline-flex h-7 shrink-0 cursor-pointer select-none items-center gap-2 whitespace-nowrap rounded-control px-2.5 text-xs transition-colors focus-within:ring-2 focus-within:ring-ring",- isActive- ? "font-medium text-foreground"- : row.key_set- ? "border border-border bg-background text-muted-foreground hover:border-primary/50 hover:text-foreground"- : "border border-dashed border-border text-muted-foreground hover:text-foreground",- )}- title={labelTitle}- >- <input- type="radio"- name="active-subagent"- checked={isActive}- onChange={() => onActivate()}- disabled={activating}- className="sr-only"- />- {isActive && (- <span- aria-hidden="true"- className={cn(- "h-[7px] w-[7px] rounded-full bg-foreground/70",- activating && "animate-pulse motion-reduce:animate-none",- )}- />- )}- {activating ? "Activating…" : isActive ? "Active" : "Set active"}- </label>- );-}diff --git a/jarvis/ui/web/frontend/src/components/SubagentModelCard.test.tsx b/jarvis/ui/web/frontend/src/components/SubagentModelCard.test.tsxnew file mode 100644index 0000000000..3f50b40150--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/SubagentModelCard.test.tsx@@ -0,0 +1,97 @@+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,+}));++vi.mock("@/store/events", () => ({+ useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>+ selector({ pushToast: vi.fn() }),+}));++import { SubagentModelCard, type SubagentStatus } from "./SubagentModelCard";++const STATUS: SubagentStatus = {+ configured: true,+ enabled: true,+ binary_path: "openclaw",+ binary_detected: "/usr/bin/openclaw",+ version_pin: null,+ time_cap_min: null,+ concurrency: null,+ state_dir_root: null,+ brain_primary: "claude-api",+ provider_slug: "claude-cli",+ model_override: null,+ sub_model_override: "claude-sonnet-4-6",+ model_resolved: "claude-cli/claude-sonnet-4-6",+ mapping: [],+};++const MODELS = {+ provider: "claude-api",+ current_model: "claude-sonnet-4-6",+ models: [+ { id: "claude-opus-4-8", label: "Claude Opus 4.8" },+ { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" },+ ],+ source: "static",+ fetched_at: 0,+ selects: "model",+};++function mockFetch() {+ return vi.fn().mockImplementation(async (url: string) => {+ const u = String(url);+ if (u.includes("/api/jarvis-agent/status")) return { ok: true, json: async () => STATUS };+ if (u.includes("/models")) return { ok: true, json: async () => MODELS };+ if (u.includes("/api/jarvis-agent/model")) {+ return {+ ok: true,+ json: async () => ({+ ok: true,+ model: "claude-opus-4-8",+ persisted: true,+ restart_required: true,+ }),+ };+ }+ return { ok: true, json: async () => ({}) };+ });+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("SubagentModelCard — the agents' model dropdown", () => {+ it("opens a model dropdown for the active worker's provider", async () => {+ vi.stubGlobal("fetch", mockFetch());+ render(<SubagentModelCard status={STATUS} onSaved={() => undefined} />);+ const trigger = (await screen.findByLabelText("apikeys_model.model_label")) as HTMLElement;+ fireEvent.click(trigger);+ expect(await screen.findByText("claude-opus-4-8")).toBeTruthy();+ });++ it("saves a picked model via POST /api/jarvis-agent/model", async () => {+ const fetchMock = mockFetch();+ vi.stubGlobal("fetch", fetchMock);+ render(<SubagentModelCard status={STATUS} onSaved={() => undefined} />);+ const trigger = (await screen.findByLabelText("apikeys_model.model_label")) as HTMLElement;+ fireEvent.click(trigger);+ fireEvent.click(await screen.findByText("claude-opus-4-8"));++ await waitFor(() => {+ const post = fetchMock.mock.calls.find(+ (c) =>+ String(c[0]).includes("/api/jarvis-agent/model") &&+ (c[1] as RequestInit | undefined)?.method === "POST",+ );+ expect(post).toBeDefined();+ expect(JSON.parse((post![1] as RequestInit).body as string).model).toBe("claude-opus-4-8");+ });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/SubagentModelCard.tsx b/jarvis/ui/web/frontend/src/components/SubagentModelCard.tsxnew file mode 100644index 0000000000..7993605fd6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/SubagentModelCard.tsx@@ -0,0 +1,128 @@+import { BrainModelSelector } from "@/components/BrainModelSelector";+import { LocalModelDownloadPanel } from "@/components/providers/ProviderTierSection";+import { saveSubagentModel, useProviders, type Billing } from "@/hooks/useProviders";+import { useT } from "@/i18n";++/** Mirror of `GET /api/jarvis-agent/status` — the agents' worker bridge. */+export interface SubagentMappingRow {+ jarvis: string;+ /** Server contract: the worker-harness provider slug (e.g. "google"). */+ worker_slug: string;+ env_var: string;+ env_fallback: string | null;+ key_set: boolean;+ api_key_set: boolean;+ dedicated_key_set: boolean;+ shared_key_set: boolean;+ oauth_connected: boolean;+ credential_source: string;+ secret_key: string | null;+ dashboard_url: string | null;+ credential_help: string | null;+ is_active_brain: boolean;+ /** Runs on the user's own hardware and has no credential at all. Such a card+ * is ready the moment it exists — asking it for a key locked a local-only+ * install out of picking any worker. */+ keyless?: boolean;+ /** The card's own display name from the provider spec, so the picker stops+ * showing raw ids ("local-openai") next to proper labels ("xAI Grok"). */+ label?: string | null;+ /** How this subagent is billed — "api" (per token) / "subscription" /+ * "subscription_or_api". Drives the billing badge so the API-vs-subscription+ * distinction is visible right on the subagent cards. */+ billing: Billing;+}++export interface SubagentStatus {+ configured: boolean;+ enabled: boolean;+ binary_path: string;+ binary_detected: string | null;+ version_pin: string | null;+ time_cap_min: number | null;+ concurrency: number | null;+ state_dir_root: string | null;+ brain_primary: string;+ provider_slug: string | null;+ model_override: string | null;+ /** The dedicated subagent LLM pin ([brain.sub_jarvis].model); empty/null+ * means "the active provider's deep model" (shown via model_resolved). */+ sub_model_override: string | null;+ model_resolved: string | null;+ mapping: SubagentMappingRow[];+}++/**+ * The dedicated subagent LLM model pin — the SAME dropdown as the brain cards,+ * showing the active subagent provider's catalog (``brain_primary``) and saving+ * through the subagent endpoint (POST /api/subagent/model) instead of the+ * per-provider model route. Empty selection = the provider's deep/frontier model+ * (shown in the hint via ``model_resolved``).+ */+export function SubagentModelCard({+ status,+ onSaved,+}: {+ status: SubagentStatus;+ onSaved: () => void;+}) {+ const t = useT();+ // The subagent worker slug → the catalog provider id (Codex's worker slug+ // "openai-codex" maps to the catalog's "codex"; all others match 1:1).+ const catalogProvider =+ status.brain_primary === "openai-codex"+ ? "codex"+ : status.brain_primary === "grok-build"+ ? "grok-build"+ : status.brain_primary;+ // Whether the ACTIVE worker's server can be told to download a model. Read+ // off the provider catalog rather than a provider name, so a second local+ // server type that ships a puller lights this up on its own (AP-21).+ const { providers } = useProviders();+ const pullable = providers.find(+ (p) => p.id === catalogProvider && p.supports_model_pull,+ );+ return (+ <div className="space-y-3 rounded-surface border border-border bg-card p-3.5">+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("subagent_model.description")}+ </p>+ {catalogProvider ? (+ <BrainModelSelector+ providerId={catalogProvider}+ currentModel={status.sub_model_override ?? ""}+ healthSection="subagents"+ healthActive+ onSave={async (model) => {+ const r = await saveSubagentModel(model);+ window.dispatchEvent(new Event("jarvis:agent-switched"));+ onSaved();+ return {+ ok: true,+ provider: status.brain_primary,+ model,+ persisted: r.persisted,+ applied_live: false,+ restart_required: r.restart_required,+ probe: null,+ };+ }}+ />+ ) : (+ <p className="text-xs text-muted-foreground">{t("subagent_model.model_hint")}</p>+ )}+ <p className="text-xs text-muted-foreground">+ {t("subagent_model.model_hint")}+ {status.model_resolved ? ` (${status.model_resolved})` : ""}+ </p>++ {/* The download panel, for a worker whose server can be told to fetch a+ model. Without it this tab dead-ended a local-only install: the picker+ above lists what the server HOLDS, so on a fresh Ollama it is empty,+ and the one screen that could fix that was three tabs away under+ Brain. Same panel, same endpoints — the capability flag decides. */}+ {pullable && <LocalModelDownloadPanel descriptor={pullable} onChanged={onSaved} />}+ </div>+ );+}+diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.tsindex 3bb1605f97..4595936f56 100644--- a/jarvis/ui/web/frontend/src/i18n/index.ts+++ b/jarvis/ui/web/frontend/src/i18n/index.ts@@ -104,7 +104,8 @@ export type LocaleChunk =| "society"| "computers"| "onboarding"- | "appshot_editor";+ | "appshot_editor"+ | "providers";const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknown>>> = {marketplace: {@@ -139,6 +140,12 @@ const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknowde: () => import("./locales/appshot_editor/de.json"),es: () => import("./locales/appshot_editor/es.json"),},+ // The provider page (Settings → API Keys).+ providers: {+ en: () => import("./locales/providers/en.json"),+ de: () => import("./locales/providers/de.json"),+ es: () => import("./locales/providers/es.json"),+ },};const EXTRA: Record<UiLanguage, Record<string, unknown>[]> = { en: [], de: [], es: [] };diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.jsonnew file mode 100644index 0000000000..7a03015e59--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json@@ -0,0 +1,101 @@+{+ "providers_page": {+ "subtitle": "Verbinde jeden KI-Anbieter einmal – mit deinem Abo oder einem Schlüssel – und wähle, wofür {name} ihn nutzt.",+ "checking": "Wird geprüft…",+ "checked_now": "Gerade geprüft",+ "checked_minutes": "Vor {0} Min. geprüft",+ "loading": "Anbieter werden geladen…",+ "load_error": "Die Anbieter konnten nicht geladen werden. Läuft das Backend?",+ "list_label": "KI-Anbieter",+ "list_title": "Anbieter",+ "list_desc": "Eine Anmeldung oder ein Schlüssel pro Anbieter reicht für alle Funktionen.",+ "overview_none": "Nicht eingerichtet",+ "failing": "Eine Funktion dieses Anbieters schlägt fehl",+ "status_local": "Kein Konto und kein Schlüssel nötig",+ "status_both": "Abo und API-Key",+ "status_subscription": "Abo verbunden",+ "status_subscription_as": "Abo · {0}",+ "status_key": "API-Key",+ "status_project": "Google-Cloud-Projekt",+ "status_none": "Nicht verbunden",+ "use_voice": "Stimme",+ "use_agents": "Agenten",+ "use_speech": "Sprechen",+ "use_hearing": "Hören",+ "use_dictation": "Diktat",+ "use_voice_long": "Live-Stimme",+ "use_agents_long": "Agenten",+ "use_speech_long": "Gesprochene Antworten",+ "use_hearing_long": "Spracherkennung",+ "use_dictation_long": "Diktat-Feinschliff",+ "in_use": "Aktiv",+ "available": "Verfügbar",+ "not_ready": "Nicht eingerichtet",+ "subscription_title": "Abo",+ "subscription_desc": "Nutze das {0}-Abo, das du schon bezahlst. Kein Schlüssel, keine Abrechnung pro Nutzung.",+ "subscription_unknown": "Anmeldung wird geprüft…",+ "subscription_signed_in": "Angemeldet als {0}",+ "subscription_install": "Installiere zuerst das Kommandozeilen-Tool, dann verbinden.",+ "subscription_hint": "Nicht verbunden. „Verbinden“ öffnet die offizielle Anmeldung.",+ "login_started_browser": "Anmeldung gestartet – schließe sie im Browserfenster ab.",+ "login_started_terminal": "Anmeldung gestartet – schließe sie im Terminalfenster ab.",+ "login_waiting_browser": "Warte darauf, dass du die Anmeldung im Browser abschließt…",+ "login_waiting_terminal": "Warte darauf, dass du die Anmeldung im Terminal abschließt…",+ "login_done": "{0} verbunden.",+ "logout_done": "{0} getrennt.",+ "connect": "Verbinden",+ "disconnect": "Trennen",+ "cli_label": "Kommandozeilen-Tool",+ "cli_found": "Installiert",+ "test": "Testen",+ "key_title": "API-Key",+ "key_desc": "Ein {0}-Schlüssel für alles: Live-Stimme, Agenten, Sprache und den Rest. Abrechnung pro Nutzung.",+ "get_key": "Schlüssel holen",+ "key_label": "API-Key",+ "key_saved_hint": "Auf diesem Computer gespeichert. Alle Funktionen dieses Anbieters nutzen ihn.",+ "key_project_hint": "Über dein Google-Cloud-Projekt angemeldet – kein Schlüssel nötig. Ein Schlüssel hier hat Vorrang.",+ "key_missing_hint": "Kein Schlüssel gespeichert.",+ "key_placeholder": "{0}-Schlüssel einfügen",+ "key_show": "Schlüssel zeigen",+ "key_hide": "Schlüssel verbergen",+ "key_save": "Speichern",+ "key_replace": "Ersetzen",+ "key_remove": "Schlüssel entfernen",+ "key_remove_confirm": "Alle Funktionen mit diesem Schlüssel hören auf.",+ "key_saved_toast": "{0}-Schlüssel für alle Funktionen gespeichert.",+ "key_removed_toast": "{0}-Schlüssel entfernt.",+ "key_format_warning": "Das sieht aus wie ein {0}, nicht wie ein {1}-Schlüssel.",+ "key_test_label": "Schlüssel prüfen",+ "key_test_hint": "Schickt eine kurze Anfrage mit diesem Schlüssel.",+ "separate_agents": "Agenten nutzen einen eigenen Schlüssel",+ "separate_live_voice": "Live-Stimme nutzt einen eigenen Schlüssel",+ "separate_codex": "Codex nutzt einen eigenen Schlüssel",+ "separate_other": "Eine Funktion nutzt einen eigenen Schlüssel",+ "separate_hint": "Früher nur für diese Funktion gespeichert. Stell sie auf den Schlüssel oben um, damit es bei einem bleibt.",+ "separate_merge": "Hauptschlüssel nutzen",+ "separate_needs_main": "Speichere zuerst einen Hauptschlüssel.",+ "separate_merged_toast": "Läuft jetzt über den {0}-Hauptschlüssel.",+ "voice_choice_title": "Live-Stimme",+ "voice_choice_desc": "Wähle, über welchen Weg du mit {name} bei diesem Anbieter sprichst.",+ "agents_title": "Agenten",+ "agents_desc": "Der Worker, der die Hintergrundaufgaben von {name} erledigt.",+ "agents_use": "Für Agenten nutzen",+ "agents_needs_key": "Speichere oben einen Schlüssel, um ihn zu nutzen.",+ "agents_needs_login_or_key": "Verbinde oben das Abo oder speichere einen Schlüssel, um ihn zu nutzen.",+ "agents_switched": "Agenten laufen jetzt über {0}.",+ "agents_switched_restart": "Agenten laufen nach dem nächsten Neustart über {0}.",+ "voice_features_title": "Sprachfunktionen",+ "voice_features_desc": "Werden in den Spracheinstellungen gewählt. Hier siehst du, was dieser Anbieter antreibt.",+ "voice_features_open": "Spracheinstellungen",+ "local_models_title": "Modelle auf diesem Computer",+ "local_models_desc": "Lade die Modelle herunter, die ohne Konto laufen, starte und wähle sie.",+ "local_models_hint": "Ollama, ein lokaler Server und die Stimme auf dem Gerät.",+ "local_models_open": "Öffnen",+ "agent_settings_title": "Agenten-Einstellungen",+ "agent_settings_desc": "Mit welchem Modell die Agenten denken und wer ihre Aufgaben formuliert – egal, welcher Anbieter sie ausführt.",+ "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",+ "accounts_title": "Mehrere Anmeldungen pro Tool"+ }+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.jsonnew file mode 100644index 0000000000..b110a89286--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json@@ -0,0 +1,101 @@+{+ "providers_page": {+ "subtitle": "Connect each AI company once — with your subscription or one key — and choose what {name} uses it for.",+ "checking": "Checking…",+ "checked_now": "Checked just now",+ "checked_minutes": "Checked {0} min ago",+ "loading": "Loading your providers…",+ "load_error": "The providers could not be loaded. Is the backend running?",+ "list_label": "AI providers",+ "list_title": "Providers",+ "list_desc": "One sign-in or one key per company covers every feature.",+ "overview_none": "Not set up",+ "failing": "A feature on this provider is failing",+ "status_local": "No account or key needed",+ "status_both": "Subscription and API key",+ "status_subscription": "Subscription connected",+ "status_subscription_as": "Subscription · {0}",+ "status_key": "API key",+ "status_project": "Google Cloud project",+ "status_none": "Not connected",+ "use_voice": "Voice",+ "use_agents": "Agents",+ "use_speech": "Speech",+ "use_hearing": "Hearing",+ "use_dictation": "Dictation",+ "use_voice_long": "Live voice",+ "use_agents_long": "Agents",+ "use_speech_long": "Spoken replies",+ "use_hearing_long": "Speech recognition",+ "use_dictation_long": "Dictation clean-up",+ "in_use": "In use",+ "available": "Available",+ "not_ready": "Not set up",+ "subscription_title": "Subscription",+ "subscription_desc": "Use the {0} plan you already pay for. No key, no per-token bill.",+ "subscription_unknown": "Checking the sign-in…",+ "subscription_signed_in": "Signed in as {0}",+ "subscription_install": "Install the command-line tool first, then connect.",+ "subscription_hint": "Not connected. Connecting opens the official sign-in.",+ "login_started_browser": "Sign-in started — finish it in the browser window.",+ "login_started_terminal": "Sign-in started — finish it in the terminal window.",+ "login_waiting_browser": "Waiting for you to finish the sign-in in the browser…",+ "login_waiting_terminal": "Waiting for you to finish the sign-in in the terminal…",+ "login_done": "{0} connected.",+ "logout_done": "{0} disconnected.",+ "connect": "Connect",+ "disconnect": "Disconnect",+ "cli_label": "Command-line tool",+ "cli_found": "Installed",+ "test": "Test",+ "key_title": "API key",+ "key_desc": "One {0} key for everything: live voice, agents, speech and the rest. Billed per use.",+ "get_key": "Get a key",+ "key_label": "API key",+ "key_saved_hint": "Saved on this computer. Every feature of this provider uses it.",+ "key_project_hint": "Signed in through your Google Cloud project — no key needed. A key here takes over.",+ "key_missing_hint": "No key saved.",+ "key_placeholder": "Paste your {0} key",+ "key_show": "Show key",+ "key_hide": "Hide key",+ "key_save": "Save",+ "key_replace": "Replace",+ "key_remove": "Remove key",+ "key_remove_confirm": "Every feature using this key stops.",+ "key_saved_toast": "{0} key saved for every feature.",+ "key_removed_toast": "{0} key removed.",+ "key_format_warning": "This looks like a {0}, not a {1} key.",+ "key_test_label": "Check the key",+ "key_test_hint": "Sends one short request with this key.",+ "separate_agents": "Agents use their own key",+ "separate_live_voice": "Live voice uses its own key",+ "separate_codex": "Codex uses its own key",+ "separate_other": "A feature uses its own key",+ "separate_hint": "Saved earlier for this feature only. Switch it to the key above to keep one key.",+ "separate_merge": "Use the main key",+ "separate_needs_main": "Save a main key first.",+ "separate_merged_toast": "Now on the main {0} key.",+ "voice_choice_title": "Live voice",+ "voice_choice_desc": "Pick the voice route to talk to {name} over this provider.",+ "agents_title": "Agents",+ "agents_desc": "The worker that runs {name}'s background tasks.",+ "agents_use": "Use for agents",+ "agents_needs_key": "Save a key above to use it.",+ "agents_needs_login_or_key": "Connect the subscription or save a key above to use it.",+ "agents_switched": "Agents now run on {0}.",+ "agents_switched_restart": "Agents run on {0} after the next restart.",+ "voice_features_title": "Speech features",+ "voice_features_desc": "Chosen in the voice settings. Shown here so you can see what this provider powers.",+ "voice_features_open": "Voice settings",+ "local_models_title": "Models on this computer",+ "local_models_desc": "Download, run and pick the models that work without any account.",+ "local_models_hint": "Ollama, a local server and the on-device voice.",+ "local_models_open": "Open",+ "agent_settings_title": "Agent settings",+ "agent_settings_desc": "The model the agents think with and who writes their task briefs — for whichever provider runs them.",+ "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",+ "accounts_title": "Several sign-ins per tool"+ }+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.jsonnew file mode 100644index 0000000000..8ffcf7baf6--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json@@ -0,0 +1,101 @@+{+ "providers_page": {+ "subtitle": "Conecta cada empresa de IA una sola vez — con tu suscripción o una clave — y elige para qué la usa {name}.",+ "checking": "Comprobando…",+ "checked_now": "Comprobado ahora",+ "checked_minutes": "Comprobado hace {0} min",+ "loading": "Cargando tus proveedores…",+ "load_error": "No se pudieron cargar los proveedores. ¿Está en marcha el backend?",+ "list_label": "Proveedores de IA",+ "list_title": "Proveedores",+ "list_desc": "Un inicio de sesión o una clave por empresa cubre todas las funciones.",+ "overview_none": "Sin configurar",+ "failing": "Una función de este proveedor está fallando",+ "status_local": "No hace falta cuenta ni clave",+ "status_both": "Suscripción y clave API",+ "status_subscription": "Suscripción conectada",+ "status_subscription_as": "Suscripción · {0}",+ "status_key": "Clave API",+ "status_project": "Proyecto de Google Cloud",+ "status_none": "Sin conectar",+ "use_voice": "Voz",+ "use_agents": "Agentes",+ "use_speech": "Habla",+ "use_hearing": "Escucha",+ "use_dictation": "Dictado",+ "use_voice_long": "Voz en directo",+ "use_agents_long": "Agentes",+ "use_speech_long": "Respuestas habladas",+ "use_hearing_long": "Reconocimiento de voz",+ "use_dictation_long": "Pulido del dictado",+ "in_use": "En uso",+ "available": "Disponible",+ "not_ready": "Sin configurar",+ "subscription_title": "Suscripción",+ "subscription_desc": "Usa el plan de {0} que ya pagas. Sin clave y sin cobro por uso.",+ "subscription_unknown": "Comprobando el inicio de sesión…",+ "subscription_signed_in": "Sesión iniciada como {0}",+ "subscription_install": "Instala primero la herramienta de línea de comandos y luego conecta.",+ "subscription_hint": "Sin conectar. Conectar abre el inicio de sesión oficial.",+ "login_started_browser": "Inicio de sesión en marcha — termínalo en la ventana del navegador.",+ "login_started_terminal": "Inicio de sesión en marcha — termínalo en la ventana del terminal.",+ "login_waiting_browser": "Esperando a que termines el inicio de sesión en el navegador…",+ "login_waiting_terminal": "Esperando a que termines el inicio de sesión en el terminal…",+ "login_done": "{0} conectado.",+ "logout_done": "{0} desconectado.",+ "connect": "Conectar",+ "disconnect": "Desconectar",+ "cli_label": "Herramienta de línea de comandos",+ "cli_found": "Instalada",+ "test": "Probar",+ "key_title": "Clave API",+ "key_desc": "Una clave de {0} para todo: voz en directo, agentes, habla y lo demás. Se cobra por uso.",+ "get_key": "Obtener una clave",+ "key_label": "Clave API",+ "key_saved_hint": "Guardada en este ordenador. Todas las funciones de este proveedor la usan.",+ "key_project_hint": "Conectado mediante tu proyecto de Google Cloud — no hace falta clave. Una clave aquí tiene prioridad.",+ "key_missing_hint": "No hay ninguna clave guardada.",+ "key_placeholder": "Pega tu clave de {0}",+ "key_show": "Mostrar clave",+ "key_hide": "Ocultar clave",+ "key_save": "Guardar",+ "key_replace": "Reemplazar",+ "key_remove": "Quitar clave",+ "key_remove_confirm": "Todas las funciones que usan esta clave se detienen.",+ "key_saved_toast": "Clave de {0} guardada para todas las funciones.",+ "key_removed_toast": "Clave de {0} eliminada.",+ "key_format_warning": "Parece una {0}, no una clave de {1}.",+ "key_test_label": "Comprobar la clave",+ "key_test_hint": "Envía una petición corta con esta clave.",+ "separate_agents": "Los agentes usan su propia clave",+ "separate_live_voice": "La voz en directo usa su propia clave",+ "separate_codex": "Codex usa su propia clave",+ "separate_other": "Una función usa su propia clave",+ "separate_hint": "Se guardó antes solo para esta función. Pásala a la clave de arriba para tener una sola.",+ "separate_merge": "Usar la clave principal",+ "separate_needs_main": "Guarda primero una clave principal.",+ "separate_merged_toast": "Ahora usa la clave principal de {0}.",+ "voice_choice_title": "Voz en directo",+ "voice_choice_desc": "Elige la vía para hablar con {name} a través de este proveedor.",+ "agents_title": "Agentes",+ "agents_desc": "El trabajador que ejecuta las tareas en segundo plano de {name}.",+ "agents_use": "Usar para agentes",+ "agents_needs_key": "Guarda una clave arriba para usarlo.",+ "agents_needs_login_or_key": "Conecta la suscripción o guarda una clave arriba para usarlo.",+ "agents_switched": "Los agentes ahora usan {0}.",+ "agents_switched_restart": "Los agentes usarán {0} tras el próximo reinicio.",+ "voice_features_title": "Funciones de voz",+ "voice_features_desc": "Se eligen en los ajustes de voz. Aquí ves qué funciones hace este proveedor.",+ "voice_features_open": "Ajustes de voz",+ "local_models_title": "Modelos en este ordenador",+ "local_models_desc": "Descarga, ejecuta y elige los modelos que funcionan sin cuenta.",+ "local_models_hint": "Ollama, un servidor local y la voz en el dispositivo.",+ "local_models_open": "Abrir",+ "agent_settings_title": "Ajustes de los agentes",+ "agent_settings_desc": "El modelo con el que piensan los agentes y quién redacta sus tareas — sea cual sea el proveedor que los ejecuta.",+ "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",+ "accounts_title": "Varias sesiones por herramienta"+ }+}diff --git a/jarvis/ui/web/frontend/src/lib/providerFamilies.ts b/jarvis/ui/web/frontend/src/lib/providerFamilies.tsnew file mode 100644index 0000000000..c276370835--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/providerFamilies.ts@@ -0,0 +1,198 @@+import { useCallback, useEffect, useRef, useState } from "react";+import type {+ AntigravityStatus,+ Billing,+ ClaudeStatus,+ CodexStatus,+ GrokBuildStatus,+} from "@/hooks/useProviders";++/**+ * The provider catalog grouped by company — mirror of+ * `jarvis/ui/web/provider_families.py::build_families()`.+ *+ * The API Keys page shows each company once: its subscription login, the one+ * key that serves every feature, and the features it powers. Membership comes+ * from the backend (derived from the catalog), never from a list kept here.+ */+export type SubscriptionKind = "claude_cli" | "codex" | "antigravity" | "grok_build";++export interface ProviderFamily {+ id: string;+ label: string;+ /** The provider id whose brand mark stands for the company. */+ logo_id: string;+ /** The machine itself: no account, no key. */+ local: boolean;+ /** The one key slot every feature of the company reads first; null = keyless. */+ key_slot: string | null;+ key_present: boolean;+ /** Features that still hold their own different key instead of the main one. */+ separate_keys: { slot: string; surface: "agents" | "live_voice" | "codex" | "other" }[];+ dashboard_url: string | null;+ signup_url: string | null;+ subscription: { kind: SubscriptionKind; provider_id: string; label: string } | null;+ /** Member cards of `/api/providers`. */+ provider_ids: string[];+ /** Withdrawn cards that still run an existing selection (health names them). */+ hidden_ids: string[];+ /** Member rows of `/api/jarvis-agent/status`. */+ agent_ids: string[];+}++/** One worker row of `/api/jarvis-agent/status` (the fields this page reads). */+export interface AgentRowStatus {+ jarvis: string;+ label?: string | null;+ key_set: boolean;+ keyless?: boolean;+ is_active_brain: boolean;+ billing: Billing;+}++export interface AgentStatus {+ brain_primary: string;+ mapping: AgentRowStatus[];+}++export type SubscriptionStatus = CodexStatus | ClaudeStatus | AntigravityStatus | GrokBuildStatus;++const SUBSCRIPTION_STATUS_URL: Record<SubscriptionKind, string> = {+ codex: "/api/codex/status",+ claude_cli: "/api/claude/status",+ antigravity: "/api/antigravity/status",+ grok_build: "/api/grok-build/status",+};++export function subscriptionStatusUrl(kind: SubscriptionKind): string {+ return SUBSCRIPTION_STATUS_URL[kind];+}++/**+ * Whether a subscription login is what powers the CLI right now. Each CLI can+ * also run on an API key; that mode is the key section's business, so it does+ * not count as "subscription connected" here.+ */+export function subscriptionConnected(status: SubscriptionStatus | null | undefined): boolean {+ return Boolean(status?.connected) && status?.mode !== "api_key";+}++/** The signed-in account and plan, as one short line ("ruben@… · Claude Max"). */+export function subscriptionAccount(status: SubscriptionStatus | null | undefined): string | null {+ if (!status) return null;+ const email = status.user_email ?? null;+ const plan = "account_label" in status ? status.account_label ?? null : null;+ // Codex reports a generic login label, not a plan; only Claude names one.+ const showPlan = plan && "subscription_type" in status;+ return [email, showPlan ? plan : null].filter(Boolean).join(" · ") || null;+}++const REFRESH_EVENTS = [+ "jarvis:secret-configured",+ "jarvis:brain-switched",+ "jarvis:agent-switched",+ "jarvis:realtime-switched",+ "jarvis:provider-tested",+] as const;++/**+ * Everything the page needs besides `/api/providers`: the families, the four+ * subscription logins and the agent worker rows, loaded together and reloaded+ * on the same app events the provider list listens to.+ */+export function useProviderFamilies() {+ const [families, setFamilies] = useState<ProviderFamily[] | null>(null);+ const [subscriptions, setSubscriptions] = useState<+ Partial<Record<SubscriptionKind, SubscriptionStatus | null>>+ >({});+ const [agents, setAgents] = useState<AgentStatus | null>(null);+ const [error, setError] = useState<"restart_required" | "families_unavailable" | null>(null);+ const [checkedAt, setCheckedAt] = useState<number | null>(null);+ const [loading, setLoading] = useState(false);+ const seq = useRef(0);++ const reload = useCallback(async () => {+ const mine = ++seq.current;+ setLoading(true);+ const json = async <T,>(url: string): Promise<T | null> => {+ try {+ const res = await fetch(url, { cache: "no-store" });+ return res.ok ? ((await res.json()) as T) : null;+ } catch {+ // One unreachable status endpoint must not blank the page; its+ // section shows "unknown" instead.+ return null;+ }+ };+ // The family list alone reports WHY it is missing: a 404 means the running+ // backend predates the endpoint (the bundle updated without a restart).+ const familyRequest = async (): Promise<{ families: ProviderFamily[] } | "missing" | null> => {+ try {+ const res = await fetch("/api/providers/families", { cache: "no-store" });+ if (res.status === 404) return "missing";+ return res.ok ? ((await res.json()) as { families: ProviderFamily[] }) : null;+ } catch {+ return null;+ }+ };+ const kinds = Object.keys(SUBSCRIPTION_STATUS_URL) as SubscriptionKind[];+ const [familyData, agentData, ...statuses] = await Promise.all([+ familyRequest(),+ json<AgentStatus>("/api/jarvis-agent/status"),+ ...kinds.map((kind) => json<SubscriptionStatus>(SUBSCRIPTION_STATUS_URL[kind])),+ ]);+ if (mine !== seq.current) return;+ if (familyData && familyData !== "missing") {+ setFamilies(familyData.families);+ setError(null);+ } else {+ setError(familyData === "missing" ? "restart_required" : "families_unavailable");+ }+ setAgents(agentData);+ setSubscriptions(Object.fromEntries(kinds.map((kind, i) => [kind, statuses[i]])));+ setCheckedAt(Date.now());+ setLoading(false);+ }, []);++ useEffect(() => {+ void reload();+ let timer: number | undefined;+ // Several events land together after one save or switch; one reload.+ const onChange = () => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => void reload(), 250);+ };+ for (const name of REFRESH_EVENTS) window.addEventListener(name, onChange);+ return () => {+ window.clearTimeout(timer);+ for (const name of REFRESH_EVENTS) window.removeEventListener(name, onChange);+ };+ }, [reload]);++ return { families, subscriptions, agents, error, checkedAt, loading, reload };+}++/**+ * Poll a subscription status endpoint after a login was started, until it+ * reports connected or the time runs out. A CLI login finishes in its own+ * browser or console window AFTER the request returned, so one refetch always+ * reads the old state.+ */+export async function pollUntilConnected(+ url: string,+ onTick: () => void | Promise<void>,+ { maxMs = 120_000, intervalMs = 2_500 }: { maxMs?: number; intervalMs?: number } = {},+): Promise<boolean> {+ const deadline = Date.now() + maxMs;+ while (Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, intervalMs));+ await onTick();+ try {+ const res = await fetch(url, { cache: "no-store" });+ if (res.ok && subscriptionConnected((await res.json()) as SubscriptionStatus)) return true;+ } catch {+ // The app may be restarting; keep polling until the deadline.+ }+ }+ return false;+}diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsxnew file mode 100644index 0000000000..47f57a4e79--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx@@ -0,0 +1,174 @@+/**+ * The provider page: every company once, one key per company, and the jobs it+ * powers switchable where they are shown.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++vi.mock("@/hooks/useVoiceMode", () => ({+ useVoiceMode: () => ({+ mode: "realtime",+ realtimeAvailable: true,+ statusKnown: true,+ setMode: vi.fn(),+ isLoading: false,+ isSaving: false,+ sessionActive: false,+ }),+}));++// 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 }));++import { _resetProvidersCacheForTests } from "@/hooks/useProviders";+import { ApiKeysView } from "@/views/ApiKeysView";++const PROVIDERS = [+ { id: "claude-api", label: "Claude (API-Key)", tier: "brain", auth_mode: "api_key", secret_keys: ["anthropic_api_key"], secrets_set: {}, configured: false, active: false, billing: "api" },+ { id: "claude-cli", label: "Claude (Anthropic subscription)", tier: "brain", auth_mode: "claude_cli", secret_keys: [], secrets_set: {}, configured: true, active: false, billing: "subscription" },+ { id: "gemini", label: "Google Gemini", tier: "brain", auth_mode: "api_key", secret_keys: ["gemini_api_key"], secrets_set: { gemini_api_key: true }, configured: true, active: false, billing: "api" },+ { id: "gemini-live", label: "Gemini Live", tier: "realtime", auth_mode: "api_key", secret_keys: ["realtime_gemini_api_key"], secrets_set: {}, configured: true, active: true, billing: "api" },+].map((p) => ({ dashboard_url: null, login_cli: null, install_hint: null, credential_path_hint: null, cli_installed: null, credential_help: null, signup_url: null, alt_credential: null, ...p }));++const FAMILIES = [+ {+ id: "claude-api", label: "Anthropic", logo_id: "claude-api", local: false,+ key_slot: "anthropic_api_key", key_present: false, separate_keys: [],+ dashboard_url: "https://console.anthropic.com/settings/keys", signup_url: null,+ subscription: { kind: "claude_cli", provider_id: "claude-cli", label: "Claude (Anthropic subscription)" },+ provider_ids: ["claude-api", "claude-cli"], hidden_ids: [], agent_ids: ["claude-api", "claude-cli"],+ },+ {+ id: "gemini", label: "Google Gemini", logo_id: "gemini", local: false,+ key_slot: "gemini_api_key", key_present: true,+ separate_keys: [{ slot: "realtime_gemini_api_key", surface: "live_voice" }],+ dashboard_url: null, signup_url: null, subscription: null,+ provider_ids: ["gemini", "gemini-live"], hidden_ids: [], agent_ids: ["gemini", "gemini-live"],+ },+];++const AGENTS = {+ configured: true, enabled: true, 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, sub_model_override: "", model_resolved: null,+ mapping: [+ { jarvis: "claude-api", label: "Claude", key_set: true, is_active_brain: false, billing: "subscription_or_api" },+ { jarvis: "gemini", label: "Google Gemini", key_set: true, is_active_brain: true, billing: "api" },+ ],+};++const CLAUDE_STATUS = {+ installed: true, connected: true, mode: "subscription", message: "Connected",+ user_email: "[email protected]", account_label: "Claude Max", subscription_type: "max",+ version: "2.1.0", binary_path: "/usr/bin/claude",+};++let calls: { url: string; method: string; body: unknown }[] = [];++beforeEach(() => {+ calls = [];+ _resetProvidersCacheForTests();+ const routes: Record<string, unknown> = {+ "/api/providers/families": { families: FAMILIES },+ "/api/providers/section-health": { sections: {}, checked_at: 0, cached: false },+ "/api/providers": { providers: PROVIDERS },+ "/api/jarvis-agent/status": AGENTS,+ "/api/jarvis-agent/switch": { ok: true },+ "/api/claude/status": CLAUDE_STATUS,+ "/api/codex/status": null,+ "/api/secrets/": { ok: true, key: "x", written: ["anthropic_api_key"] },+ };+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : null });+ const match = Object.keys(routes)+ .sort((a, b) => b.length - a.length)+ .find((prefix) => url.startsWith(prefix));+ const body = match ? routes[match] : {};+ const ok = body !== null;+ return { ok, status: ok ? 200 : 404, json: async () => body ?? {}, text: async () => "" } as Response;+ }),+ );+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++function renderPage() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={client}>+ <ApiKeysView />+ </QueryClientProvider>,+ );+}++describe("ApiKeysView — one entry per company", () => {+ it("lists every company once, with how it is connected", async () => {+ renderPage();+ const list = await screen.findByTestId("provider-family-list");+ expect(within(list).getByTestId("provider-family-claude-api").textContent).toContain("Anthropic");+ expect(within(list).getByTestId("provider-family-claude-api").textContent).toContain("[email protected]");+ expect(within(list).getByTestId("provider-family-gemini").textContent).toContain("API key");+ });++ it("opens on the company that carries the voice and tags what it powers", async () => {+ renderPage();+ const detail = await screen.findByTestId("provider-family-detail-gemini");+ expect(within(detail).getByTestId("provider-use-voice")).toBeTruthy();+ expect(within(detail).getByTestId("provider-use-agents")).toBeTruthy();+ });++ it("saves one key for the whole company", async () => {+ renderPage();+ fireEvent.click(await screen.findByTestId("provider-family-claude-api"));+ const input = await screen.findByTestId("provider-key-input");+ fireEvent.change(input, { target: { value: "sk-ant-api03-test" } });+ fireEvent.click(screen.getByTestId("provider-key-save"));+ await waitFor(() => {+ const save = calls.find((c) => c.method === "POST" && c.url === "/api/secrets/anthropic_api_key");+ expect(save?.body).toEqual({ value: "sk-ant-api03-test", scope: "everywhere" });+ });+ });++ it("moves a feature with its own key back onto the main key", async () => {+ renderPage();+ const row = await screen.findByTestId("provider-separate-key-realtime_gemini_api_key");+ fireEvent.click(within(row).getByRole("button"));+ await waitFor(() =>+ expect(calls.some((c) => c.method === "DELETE" && c.url === "/api/secrets/realtime_gemini_api_key")).toBe(true),+ );+ });++ it("switches the agents onto another company in one click", async () => {+ renderPage();+ fireEvent.click(await screen.findByTestId("provider-family-claude-api"));+ fireEvent.click(await screen.findByTestId("provider-agent-use-claude-api"));+ await waitFor(() => {+ const post = calls.find((c) => c.url === "/api/jarvis-agent/switch");+ expect(post?.body).toMatchObject({ provider: "claude-api" });+ });+ });++ it("shows the subscription sign-in with the account and the CLI behind it", async () => {+ renderPage();+ fireEvent.click(await screen.findByTestId("provider-family-claude-api"));+ const section = await screen.findByTestId("provider-subscription");+ expect(section.textContent).toContain("[email protected]");+ expect(section.textContent).toContain("2.1.0");+ expect(within(section).getByTestId("provider-subscription-disconnect")).toBeTruthy();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsxindex d2e44077c3..436ca8ea59 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx@@ -2,8 +2,8 @@* 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 tier section (header + the existing- * status/credentials/scripts/calls cards), shown after the Subagent tier. These+ * folded into the API-Keys view as another section (header + the existing+ * status/credentials/scripts/calls cards), shown below the providers. These* tests pin that the section header renders and that the embedded TelephonyPanel* loads and shows live telephony data from /api/telephony/*.*/@@ -131,6 +131,7 @@ const TELEPHONY_CONFIG_LIVE = {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 }),@@ -148,8 +149,6 @@ describe("ApiKeysView — embedded Telephony tier", () => {it("renders the Telephony tier header inside the API-Keys view", async () => {installFetchMock(routes());renderView();- // Telephony now lives in the de-emphasized "Advanced" tab; open it first.- fireEvent.click(screen.getByRole("tab", { name: /advanced/i }));// English is the test-default locale; tier_telephony => "Telephony".await waitFor(() => expect(screen.getByText("Telephony")).toBeTruthy());@@ -158,8 +157,6 @@ describe("ApiKeysView — embedded Telephony tier", () => {it("loads live telephony status (Charon voice) from /api/telephony", async () => {installFetchMock(routes());renderView();- // Telephony now lives in the de-emphasized "Advanced" tab; open it first.- fireEvent.click(screen.getByRole("tab", { name: /advanced/i }));await waitFor(() => {expect(screen.getByTestId("status-tts-voice").textContent).toBe("Charon");@@ -172,8 +169,6 @@ describe("ApiKeysView — embedded Telephony tier", () => {it("offers a 'Setup script' button that navigates to the telephony-setup page", async () => {installFetchMock(routes());renderView();- // Telephony now lives in the de-emphasized "Advanced" tab; open it first.- fireEvent.click(screen.getByRole("tab", { name: /advanced/i }));const btn = await waitFor(() =>screen.getByRole("button", { name: /Setup script/i }),diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 747e21554e..7d8eab3fd1 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1,60 +1,48 @@import { useEffect, useState } from "react";-import { Bot, KeyRound, Phone, Radio, SlidersHorizontal } from "lucide-react";+import { Bot, KeyRound, Loader2, Phone, RefreshCw } from "lucide-react";import { PageHeader } from "@/components/layout/PageHeader";-import { JarvisAgentSection } from "@/components/JarvisAgentSection";+import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";+import { SubagentModelCard, type SubagentStatus } from "@/components/SubagentModelCard";+import { PromptWriterCard } from "@/components/PromptWriterCard";+import { useTierHealth } from "@/components/providers/ProviderTierSection";+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 { RealtimeTab } from "@/views/apikeys/RealtimeTab";-import { useTierHealth, type LucideIcon } from "@/components/providers/ProviderTierSection";-import { type SectionHealth, useProviders } from "@/hooks/useProviders";-import {- APIKEYS_TAB_EVENT,- API_KEYS_TABS,- type ApiKeysTab,- clearApiKeysTabRequest,- requestedApiKeysTab,-} from "@/lib/apiKeysTab";-import { cn } from "@/lib/utils";-import { useT } from "@/i18n";--/** A tab another part of the app asked for, or the page's first tab. */-function resolveTab(wanted: string | null): ApiKeysTab {- return API_KEYS_TABS.includes(wanted as ApiKeysTab) ? (wanted as ApiKeysTab) : "realtime";-}+import { ProvidersPanel } from "@/views/apikeys/ProvidersPanel";+import { useProviders, useSectionHealth } from "@/hooks/useProviders";+import { useProviderFamilies } from "@/lib/providerFamilies";+import { useLocaleChunk, useT } from "@/i18n";/**- * API Keys — the realtime voice, the agents, the install's own key and the- * optional integrations, one tab each.+ * API Keys — every AI company once, each with one way to sign in and one key.*- * Realtime is the only voice engine this page sets up. The Pipeline|Realtime- * switch, the Brain / Voice Output / Voice Input / Wording tabs and the Local- * Mode toggle are gone: speech-to-text and the dictation wording pass are- * configured in the voice section, where dictation lives.+ * The page used to be split by feature (live voice, agents, the install key,+ * advanced), so one company appeared on several tabs with several keys. Now+ * a company is connected once — its subscription login or a single key that+ * every feature reads — and its settings say what the assistant uses it for,+ * with each job switchable where it is shown. Below the providers sit the+ * settings that belong to no single company: the agents' model and accounts,+ * the install's own key, and the optional integrations.*/export function ApiKeysView() {const t = useT();+ // The page's own strings load with it; nothing paints raw keys meanwhile.+ const stringsReady = useLocaleChunk("providers");const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();- // Per-tab health (amber = still to set up, red = set up but failing a live- // check), re-bound to the provider that is actually active.- const health = useTierHealth(providers);- const [active, setActive] = useState<ApiKeysTab>(() => resolveTab(requestedApiKeysTab()));-- // The first-run guide may ask for a tab after the page mounted (it loads- // lazily); a request stays in force until the user picks a tab themselves.- useEffect(() => {- const onRequest = (event: Event) => {- setActive(resolveTab((event as CustomEvent<string | null>).detail));- };- window.addEventListener(APIKEYS_TAB_EVENT, onRequest);- return () => window.removeEventListener(APIKEYS_TAB_EVENT, onRequest);- }, []);+ const families = useProviderFamilies();+ const { health } = useSectionHealth();+ const tierHealth = useTierHealth(providers);+ const refreshing = families.loading;- const selectTab = (key: ApiKeysTab) => {- clearApiKeysTabRequest();- setActive(key);- };+ if (!stringsReady) {+ return (+ <div role="status" aria-busy="true" className="flex h-full items-center justify-center">+ <Loader2 aria-hidden="true" className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ );+ }return (<div className="flex h-full min-h-0 flex-col" data-tour="apikeys-page">@@ -62,155 +50,86 @@ export function ApiKeysView() {<PageHeadericon={<KeyRound />}title={t("apikeys_view.title")}- description={t("apikeys_view.subtitle")}- tabs={<CategoryTabs active={active} onSelect={selectTab} health={health} />}+ description={t("providers_page.subtitle")}+ actions={+ <Button+ size="sm"+ variant="ghost"+ className="text-muted-foreground"+ data-testid="providers-refresh"+ disabled={refreshing}+ onClick={() => {+ refetch();+ void families.reload();+ }}+ >+ {refreshing ? <Loader2 className="animate-spin" /> : <RefreshCw />}+ <CheckedAgo at={families.checkedAt} />+ </Button>+ }/></div><divdata-testid="api-keys-provider-scroll"- className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-8 pb-10 pt-6"+ className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-8 pb-10 pt-2">- {/* The key re-runs the rise animation on a tab change. */}- <div- key={active}- role="tabpanel"- id="apikeys-panel"- aria-labelledby={`apikeys-tab-${active}`}- className="profile-rise w-full max-w-page"- >- {active === "realtime" && (- <RealtimeTab- providers={providers}- loading={loading}- error={error}- onChanged={refetch}- onActivateOptimistic={setActiveOptimistic}- health={health.realtime}- />- )}- {active === "subagents" && <SubagentCategory />}- {active === "jarvis-key" && <JarvisKeyCategory />}- {active === "advanced" && <AdvancedCategory />}+ <div className="profile-rise flex w-full flex-col gap-12">+ <ProvidersPanel+ data={families}+ providers={providers}+ providersLoading={loading}+ providersError={error}+ health={health}+ realtimeHealth={tierHealth.realtime}+ onProvidersChanged={refetch}+ onActivateOptimistic={setActiveOptimistic}+ />+ <AgentSettings />+ <section className="flex flex-col gap-3">+ <SectionTitle title={t("apikeys_view.jarvis_key_title")} description={t("apikeys_view.jarvis_key_desc")} />+ <JarvisApiGroup />+ </section>+ <section className="flex flex-col gap-3">+ <SectionTitle title={t("apikeys_view.advanced_title")} description={t("apikeys_view.advanced_desc")} />+ <div className="space-y-4">+ <TeamProxyGroup />+ <TelephonySection />+ <WikiProviderCard />+ </div>+ {/* 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 pt-2 text-sm text-muted-foreground">{t("apikeys_view.trademark_notice")}</p>+ </section></div></div></div>);}-/**- * Underline tabs on the header's rule, in the shared tab-bar look. A tab whose- * section needs attention swaps its icon for a status dot: red for "set up but- * not working", amber for "still to set up". Healthy tabs stay silent, so a- * dot always means "look here".- */-function CategoryTabs({- active,- onSelect,- health,-}: {- active: ApiKeysTab;- onSelect: (key: ApiKeysTab) => void;- /** Per-tab health rollup keyed by tab; absent keys render no dot. */- health: Record<string, SectionHealth>;-}) {+/** "Checked 2 min ago", re-rendered every half minute. */+function CheckedAgo({ at }: { at: number | null }) {const t = useT();- const meta: Record<ApiKeysTab, { label: string; icon: LucideIcon }> = {- realtime: { label: t("apikeys_view.tab_realtime"), icon: Radio },- subagents: { label: t("apikeys_view.tab_subagents"), icon: Bot },- "jarvis-key": { label: t("apikeys_view.tab_jarvis_key"), icon: KeyRound },- advanced: { label: t("apikeys_view.tab_advanced"), icon: SlidersHorizontal },- };- return (- <div- role="tablist"- data-testid="api-keys-category-tabs"- className="flex items-center gap-6 overflow-x-auto border-b border-border scrollbar-jarvis"- >- {API_KEYS_TABS.map((key) => (- <TabButton- key={key}- id={`apikeys-tab-${key}`}- icon={meta[key].icon}- label={meta[key].label}- selected={active === key}- onClick={() => onSelect(key)}- health={health[key]}- />- ))}- </div>- );-}--function TabButton({- id,- icon: Icon,- label,- selected,- onClick,- health,-}: {- id: string;- icon: LucideIcon;- label: string;- selected: boolean;- onClick: () => void;- health?: SectionHealth;-}) {- const t = useT();- const indicator =- health?.status === "error"- ? "error"- : health?.status === "needs_setup"- ? "needs_setup"- : null;- const statusLabel =- indicator === "error"- ? t("apikeys_view.health_error")- : indicator === "needs_setup"- ? t("apikeys_view.health_needs_setup")- : "";- // Tooltip: the plain-language status plus the backend's one-line detail- // (e.g. "OpenAI GPT-Live: out of credit"), so hovering says what is wrong.- const title = indicator ? [statusLabel, health?.detail].filter(Boolean).join(" — ") : undefined;+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), 30_000);+ return () => window.clearInterval(timer);+ }, []);+ if (at === null) return <>{t("providers_page.checking")}</>;+ const minutes = Math.floor(Math.max(0, now - at) / 60_000);return (- <button- type="button"- role="tab"- id={id}- aria-selected={selected}- aria-controls="apikeys-panel"- onClick={onClick}- title={title}- className={cn(- "relative -mb-px inline-flex h-10 shrink-0 items-center gap-2 whitespace-nowrap border-b-2 text-base font-medium transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",- selected- ? "border-accent text-foreground-strong"- : "border-transparent text-muted-foreground hover:text-foreground",- )}- >- {indicator ? (- <span- aria-hidden="true"- className={cn(- "h-2 w-2 shrink-0 rounded-full",- indicator === "error" ? "bg-destructive" : "bg-warning",- )}- />- ) : (- <Icon aria-hidden="true" className="h-4 w-4 opacity-80" />- )}- {label}- {indicator && <span className="sr-only">{` (${statusLabel})`}</span>}- </button>+ <>+ {minutes < 1+ ? t("providers_page.checked_now")+ : t("providers_page.checked_minutes").replace("{0}", String(minutes))}+ </>);}-/** The heading every non-voice tab opens with, in the settings-group grammar. */-function TabIntro({ title, description }: { title: string; description: string }) {+function SectionTitle({ title, description }: { title: string; description: string }) {return (- <div className="mb-4 px-1">+ <div className="px-1"><h2 className="text-lg font-semibold text-foreground-strong">{title}</h2><p className="mt-0.5 text-base text-muted-foreground">{description}</p></div>@@ -218,59 +137,43 @@ function TabIntro({ title, description }: { title: string; description: string }}/**- * The agents tab — the heavy-task worker selection. `JarvisAgentSection` owns- * its own data source (/api/jarvis-agent/status) and rows.+ * Settings that belong to the agents rather than to one company: the model a+ * worker runs, who writes the task briefs, and the several logins a person+ * can hold per command-line tool.*/-function SubagentCategory() {+function AgentSettings() {const t = useT();- return (- <div>- <TabIntro- title={t("apikeys_view.cat_subagents_title")}- description={t("apikeys_view.cat_subagents_desc")}- />- <JarvisAgentSection hideHeader />- </div>- );-}--/**- * The "<Name> Key" tab — the per-install Control Key that unlocks the browser- * UI and authenticates local agents, named after the configured wake word via- * the i18n `{name}` token, so the tab the lock screen points at carries the- * name the user knows their assistant by.- */-function JarvisKeyCategory() {- const t = useT();- return (- <div>- <TabIntro title={t("apikeys_view.jarvis_key_title")} description={t("apikeys_view.jarvis_key_desc")} />- <JarvisApiGroup />- </div>- );-}+ const [status, setStatus] = useState<SubagentStatus | null>(null);+ const reload = async () => {+ try {+ 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 simply stays hidden; the provider list above reports+ // the same endpoint's failure.+ console.debug("agent status unavailable", cause);+ }+ };+ useEffect(() => {+ void reload();+ const onChange = () => void reload();+ window.addEventListener("jarvis:agent-switched", onChange);+ return () => window.removeEventListener("jarvis:agent-switched", onChange);+ }, []);-/**- * Optional integrations: the team key proxy, telephony and the knowledge-Wiki- * provider. Each block keeps its own labelled header.- */-function AdvancedCategory() {- const t = useT();return (- <div>- <TabIntro title={t("apikeys_view.advanced_title")} description={t("apikeys_view.advanced_desc")} />- <div className="space-y-4">- <TeamProxyGroup />- <TelephonySection />- <WikiProviderCard />- {/* 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="pt-2 text-sm text-muted-foreground">- {t("apikeys_view.trademark_notice")}- </p>+ <section data-testid="provider-agent-settings" className="flex flex-col gap-3">+ <SectionTitle title={t("providers_page.agent_settings_title")} description={t("providers_page.agent_settings_desc")} />+ <div className="grid gap-4 xl:grid-cols-2">+ {status && <SubagentModelCard status={status} onSaved={() => void reload()} />}+ <PromptWriterCard /></div>- </div>+ <div className="flex items-center gap-2 px-1 pt-2 text-sm font-medium text-muted-foreground">+ <Bot aria-hidden="true" className="h-4 w-4" />+ {t("providers_page.accounts_title")}+ </div>+ <AgentAccountsPanel />+ </section>);}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/ProvidersPanel.tsx b/jarvis/ui/web/frontend/src/views/apikeys/ProvidersPanel.tsxnew file mode 100644index 0000000000..560f47e8d6--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/ProvidersPanel.tsx@@ -0,0 +1,266 @@+import { useEffect, useMemo, useState } from "react";+import { AlertCircle, Loader2, RefreshCw } from "lucide-react";+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { Button } from "@/components/ui/button";+import {+ PROVIDER_BACKEND_UNREACHABLE,+ type ProviderDescriptor,+ type ProviderTier,+ type SectionHealth,+} from "@/hooks/useProviders";+import { useT } from "@/i18n";+import type { useProviderFamilies } from "@/lib/providerFamilies";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { FamilyDetail } from "./providers/FamilyDetail";+import { FamilyList } from "./providers/FamilyList";+import { familyState, type FamilyState, type FamilyUse } from "./providers/familyState";++type FamiliesData = ReturnType<typeof useProviderFamilies>;++/** The jobs the overview strip reports, each with the tier that answers it. */+const OVERVIEW: { use: FamilyUse; tier?: ProviderTier }[] = [+ { use: "voice", tier: "realtime" },+ { use: "agents" },+ { use: "speech", tier: "tts" },+ { use: "hearing", tier: "stt" },+];++/**+ * The provider page body: what runs where, then every company in a list with+ * the selected one's settings beside it.+ */+export function ProvidersPanel({+ data,+ providers,+ providersLoading,+ providersError,+ health,+ realtimeHealth,+ onProvidersChanged,+ onActivateOptimistic,+}: {+ data: FamiliesData;+ providers: ProviderDescriptor[];+ providersLoading: boolean;+ providersError: string | null;+ health: Record<string, SectionHealth | undefined>;+ realtimeHealth?: SectionHealth;+ onProvidersChanged: () => void;+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;+}) {+ const t = useT();+ const { families, subscriptions, agents, error, reload } = data;+ 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 [selectedId, setSelectedId] = useState<string | null>(null);+ // First visit: open the company that carries the voice, else the first one+ // that is connected — the page opens on something that is already set up.+ useEffect(() => {+ if (selectedId || !families?.length || !providers.length) return;+ const pick =+ families.find((f) => states[f.id]?.uses.includes("voice")) ??+ families.find((f) => states[f.id]?.connected && !f.local) ??+ families[0];+ setSelectedId(pick.id);+ }, [families, providers.length, selectedId, states]);++ const selected = families?.find((f) => f.id === selectedId) ?? null;+ const refreshAll = async () => {+ onProvidersChanged();+ await reload();+ };++ if (error === "restart_required" && !providersError) return <RestartNeeded />;++ if (providersError || error) {+ return (+ <div+ role="alert"+ className="flex items-start gap-2 rounded-xl border border-border bg-card px-5 py-4 text-sm text-destructive"+ >+ <AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0" />+ <p className="min-w-0 flex-1">+ {providersError === PROVIDER_BACKEND_UNREACHABLE+ ? t("apikeys_view.backend_unavailable")+ : t("providers_page.load_error")}+ </p>+ <Button variant="outline" size="sm" onClick={() => void refreshAll()}>+ {t("common.retry")}+ </Button>+ </div>+ );+ }++ if (!families || (providersLoading && !providers.length)) {+ return (+ <div role="status" className="flex items-center gap-2 px-1 py-6 text-sm text-muted-foreground">+ <Loader2 aria-hidden="true" className="h-4 w-4 animate-spin" />+ {t("providers_page.loading")}+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-group">+ <Overview+ families={families}+ states={states}+ providers={providers}+ agents={agents}+ onSelect={setSelectedId}+ />++ <section aria-label={t("providers_page.list_label")} className="flex flex-col gap-3">+ <div className="px-1">+ <h2 className="text-lg font-semibold text-foreground-strong">{t("providers_page.list_title")}</h2>+ <p className="mt-0.5 text-base text-muted-foreground">{t("providers_page.list_desc")}</p>+ </div>+ <div+ data-testid="provider-master-detail"+ className="grid overflow-clip rounded-xl border border-border md:grid-cols-[18rem_minmax(0,1fr)]"+ >+ <div className="border-b border-border bg-card md:border-b-0 md:border-r">+ <div className="md:sticky md:top-0">+ <FamilyList+ families={families}+ states={states}+ selectedId={selectedId}+ onSelect={setSelectedId}+ />+ </div>+ </div>+ <div className="min-w-0 p-6">+ {selected && states[selected.id] && (+ <FamilyDetail+ key={selected.id}+ family={selected}+ state={states[selected.id]}+ agents={agents}+ realtimeHealth={realtimeHealth}+ onChanged={refreshAll}+ onProvidersChanged={onProvidersChanged}+ onActivateOptimistic={onActivateOptimistic}+ />+ )}+ </div>+ </div>+ </section>+ </div>+ );+}++/**+ * The window runs a newer page than its backend: the bundle reloads on its+ * own after an update, the server does not. One sentence and one button,+ * instead of an error that suggests something is broken.+ */+function RestartNeeded() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [restarting, setRestarting] = useState(false);++ async function restart() {+ setRestarting(true);+ try {+ const response = await fetch("/api/settings/restart-app", { method: "POST" });+ if (response.status === 409) {+ pushToast("warning", t("topbar.restart_missions_running"));+ setRestarting(false);+ return;+ }+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ // The window closes and relaunches; the button stays busy until then.+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ setRestarting(false);+ }+ }++ return (+ <div+ role="status"+ data-testid="providers-restart-needed"+ className="flex items-center gap-4 rounded-xl border border-border bg-card px-5 py-4"+ >+ <RefreshCw aria-hidden="true" className="h-5 w-5 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <p className="text-base font-medium text-foreground-strong">{t("providers_page.restart_title")}</p>+ <p className="mt-0.5 text-sm text-muted-foreground">{t("providers_page.restart_desc")}</p>+ </div>+ <Button size="sm" disabled={restarting} onClick={() => void restart()}>+ {restarting && <Loader2 className="animate-spin" />}+ {t("providers_page.restart_action")}+ </Button>+ </div>+ );+}++/**+ * What runs where, in one row: the company behind each job right now. A click+ * opens that company below, where the job can be moved.+ */+function Overview({+ families,+ states,+ providers,+ agents,+ onSelect,+}: {+ families: NonNullable<FamiliesData["families"]>;+ states: Record<string, FamilyState>;+ providers: ProviderDescriptor[];+ agents: FamiliesData["agents"];+ onSelect: (id: string) => void;+}) {+ const t = useT();+ return (+ <div+ data-testid="provider-overview"+ className="grid grid-cols-2 overflow-hidden rounded-xl border border-border bg-card lg:grid-cols-4"+ >+ {OVERVIEW.map(({ use, tier }, index) => {+ const family = families.find((f) => states[f.id]?.uses.includes(use)) ?? null;+ const detail =+ use === "agents"+ ? agents?.mapping.find((row) => row.is_active_brain)?.label ?? null+ : providers.find((p) => p.tier === tier && p.active)?.label ?? null;+ return (+ <button+ key={use}+ type="button"+ data-testid={`provider-overview-${use}`}+ disabled={!family}+ onClick={() => family && onSelect(family.id)}+ className={cn(+ "flex min-w-0 items-center gap-3 px-5 py-4 text-left transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ family && "hover:bg-secondary",+ index % 2 === 1 && "border-l border-border",+ index >= 2 && "border-t border-border lg:border-t-0",+ index === 2 && "lg:border-l",+ )}+ >+ {family ? (+ <ProviderLogo providerId={family.logo_id} label={family.label} />+ ) : (+ <span aria-hidden="true" className="h-9 w-9 shrink-0 rounded-md bg-secondary" />+ )}+ <span className="min-w-0">+ <span className="block text-sm text-muted-foreground">{t(`providers_page.use_${use}_long`)}</span>+ <span className="block truncate text-base font-medium text-foreground-strong">+ {family?.label ?? t("providers_page.overview_none")}+ </span>+ {family && detail && detail !== family.label && (+ <span className="block truncate text-sm text-muted-foreground">{detail}</span>+ )}+ </span>+ </button>+ );+ })}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsx b/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsxindex d2d231865f..8a87c6050e 100644--- a/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsx+++ b/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsx@@ -68,6 +68,7 @@ export function RealtimeTab({onChanged,onActivateOptimistic,health,+ embedded = false,}: {providers: ProviderDescriptor[];loading: boolean;@@ -76,6 +77,14 @@ export function RealtimeTab({onActivateOptimistic: (tier: ProviderTier, id: string) => void;/** Live health of the realtime tier's ACTIVE provider. */health?: SectionHealth;+ /**+ * Shown inside one company's settings on the provider page: `providers` is+ * that company's share of the realtime tier, the page above already says+ * what the voice runs on, and the company key is edited once, above this+ * section — so the "voice now" card, the list heading and the per-card key+ * fields are left out.+ */+ embedded?: boolean;}) {const t = useT();const voice = useVoiceMode();@@ -231,8 +240,8 @@ export function RealtimeTab({data-testid="realtime-tab"className="flex flex-col gap-group">- <VoiceNow active={currentProvider} activeHealth={currentProvider- ? sectionHealthForSubject(health, currentProvider.id) : undefined} voice={voice} />+ {!embedded && <VoiceNow active={currentProvider} activeHealth={currentProvider+ ? sectionHealthForSubject(health, currentProvider.id) : undefined} voice={voice} />}{error && (<div@@ -252,8 +261,8 @@ export function RealtimeTab({)}<ProfileGroup- title={t("apikeys_realtime.providers_title")}- description={t("apikeys_realtime.providers_desc")}+ title={embedded ? t("providers_page.voice_choice_title") : t("apikeys_realtime.providers_title")}+ description={embedded ? t("providers_page.voice_choice_desc") : t("apikeys_realtime.providers_desc")}testId="realtime-provider-list">{loading && !choices.length ? (@@ -284,6 +293,7 @@ export function RealtimeTab({health={selected.active ? activeHealth : undefined}activating={activatingId === selected.id}canSwitch={canSwitchTo(selected)}+ hideKeyFields={embedded}onActivate={() => void activate(selected)}// The first provider set up becomes the voice by itself; once one// holds the voice, a new key never takes it over unasked.@@ -575,6 +585,7 @@ function ProviderSettings({health,activating,canSwitch,+ hideKeyFields = false,onActivate,onKeySaved,onChanged,@@ -583,6 +594,8 @@ function ProviderSettings({health?: SectionHealth;activating: boolean;canSwitch: boolean;+ /** The company key is edited above (provider page); keep only local setup here. */+ hideKeyFields?: boolean;onActivate: () => void;/** Called once a key was saved for a provider that had none. */onKeySaved?: () => void;@@ -591,7 +604,10 @@ function ProviderSettings({const t = useT();const isLive = provider.configuration_surface === "live";const selectedAuthMode = liveMode(provider);- const showCredentials = !isLive || selectedAuthMode === "api_key";+ // The test and the key both belong to the API-key route; the key field+ // alone moves up to the company section when this tab is embedded.+ const showTest = !isLive || selectedAuthMode === "api_key";+ const showCredentials = showTest && !(hideKeyFields && provider.auth_mode === "api_key");const broken = provider.active && health?.status === "error";const brokenDetail = health?.detail?.trim() || "";const showOptions =@@ -603,7 +619,7 @@ function ProviderSettings({return (<div data-testid={`realtime-settings-${provider.id}`} className="flex flex-col gap-group">- {(showCredentials || broken) && <ProfileGroup+ {(showTest || broken) && <ProfileGrouptitle={provider.label}description={isLive@@ -651,7 +667,7 @@ function ProviderSettings({</div></SettingRow>)}- {showCredentials && <SettingRow+ {showTest && <SettingRowlabel={t("apikeys_realtime.test_label")}hint={t("apikeys_realtime.test_hint")}control={diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyDetail.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyDetail.tsxnew file mode 100644index 0000000000..4d8091fd8d--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyDetail.tsx@@ -0,0 +1,246 @@+import { useState } from "react";+import { ArrowUpRight, Check, Loader2 } from "lucide-react";+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { Button } from "@/components/ui/button";+import {+ switchSubagentProvider,+ type ProviderTier,+ type SectionHealth,+} from "@/hooks/useProviders";+import { useT } from "@/i18n";+import type { AgentRowStatus, AgentStatus, ProviderFamily } from "@/lib/providerFamilies";+import { useEventStore } from "@/store/events";+import { RealtimeTab } from "@/views/apikeys/RealtimeTab";+import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";+import { familyStatusLine, type FamilyState } from "./familyState";+import { UseTag } from "./FamilyList";+import { KeySection } from "./KeySection";+import { SubscriptionSection } from "./SubscriptionSection";++/** Voice features configured in the voice section, shown here as facts. */+const VOICE_TIERS: { tier: ProviderTier; use: "speech" | "hearing" | "dictation" }[] = [+ { tier: "tts", use: "speech" },+ { tier: "stt", use: "hearing" },+ { tier: "dictation", use: "dictation" },+];++/**+ * Everything about one company, top to bottom in the order a person sets it+ * up: sign in with the plan they pay for, or paste one key — then what the+ * assistant uses the company for, each job switchable right where it is shown.+ */+export function FamilyDetail({+ family,+ state,+ agents,+ realtimeHealth,+ onChanged,+ onProvidersChanged,+ onActivateOptimistic,+}: {+ family: ProviderFamily;+ state: FamilyState;+ agents: AgentStatus | null;+ realtimeHealth?: SectionHealth;+ onChanged: () => void | Promise<void>;+ onProvidersChanged: () => void;+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;+}) {+ const t = useT();+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const voiceCards = state.members.filter((m) => m.tier === "realtime");+ const agentRows = (agents?.mapping ?? []).filter((row) => family.agent_ids.includes(row.jarvis));+ const voiceFeatures = VOICE_TIERS.flatMap(({ tier, use }) =>+ state.members.filter((m) => m.tier === tier).map((card) => ({ card, use })),+ );++ return (+ <div data-testid={`provider-family-detail-${family.id}`} className="flex flex-col gap-group">+ <header className="flex items-center gap-4">+ <ProviderLogo providerId={family.logo_id} label={family.label} className="h-11 w-11" />+ <div className="min-w-0 flex-1">+ <h2 className="truncate text-xl font-semibold text-foreground-strong">{family.label}</h2>+ <p className="mt-0.5 truncate text-base text-muted-foreground">{familyStatusLine(family, state, t)}</p>+ </div>+ {state.uses.length > 0 && (+ <div className="flex shrink-0 flex-wrap justify-end gap-1">+ {state.uses.map((use) => (+ <UseTag key={use} use={use} />+ ))}+ </div>+ )}+ </header>++ {state.failing && (+ <p role="alert" className="rounded-xl border border-destructive/30 bg-destructive/10 px-5 py-3 text-sm text-destructive">+ {state.failing}+ </p>+ )}++ {family.subscription && <SubscriptionSection family={family} state={state} onChanged={onChanged} />}++ {family.key_slot && <KeySection family={family} state={state} onChanged={onChanged} />}++ {voiceCards.length > 0 && (+ <div data-testid="provider-voice">+ <RealtimeTab+ embedded+ providers={voiceCards}+ loading={false}+ error={null}+ onChanged={onProvidersChanged}+ onActivateOptimistic={onActivateOptimistic}+ health={realtimeHealth}+ />+ </div>+ )}++ {agentRows.length > 0 && (+ <AgentsSection family={family} state={state} rows={agentRows} onChanged={onChanged} />+ )}++ {voiceFeatures.length > 0 && (+ <ProfileGroup+ title={t("providers_page.voice_features_title")}+ description={t("providers_page.voice_features_desc")}+ testId="provider-voice-features"+ aside={+ <Button+ size="sm"+ variant="ghost"+ className="text-muted-foreground"+ onClick={() => setActiveSection("voice-api-keys")}+ >+ {t("providers_page.voice_features_open")}+ <ArrowUpRight />+ </Button>+ }+ >+ {voiceFeatures.map(({ card, use }) => (+ <SettingRow+ key={card.id}+ label={card.label}+ hint={t(`providers_page.use_${use}_long`)}+ control={<InUse active={card.active} ready={card.configured} />}+ />+ ))}+ </ProfileGroup>+ )}+ </div>+ );+}++function InUse({ active, ready }: { active: boolean; ready: boolean }) {+ const t = useT();+ if (active) {+ return (+ <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>+ );+ }+ return (+ <span className="text-sm text-muted-foreground">+ {ready ? t("providers_page.available") : t("providers_page.not_ready")}+ </span>+ );+}++/**+ * Which worker runs the assistant's background agents. Each of the company's+ * worker routes is one row; the one in use says so, the others switch with+ * one click once their sign-in or key is in place.+ */+function AgentsSection({+ family,+ state,+ rows,+ onChanged,+}: {+ family: ProviderFamily;+ state: FamilyState;+ rows: AgentRowStatus[];+ onChanged: () => void | Promise<void>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [switching, setSwitching] = useState<string | null>(null);++ async function use(row: AgentRowStatus, label: string) {+ setSwitching(row.jarvis);+ 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),+ );+ window.dispatchEvent(new CustomEvent("jarvis:agent-switched"));+ 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);+ }+ }++ return (+ <ProfileGroup+ title={t("providers_page.agents_title")}+ description={t("providers_page.agents_desc")}+ testId="provider-agents"+ >+ {rows.map((row) => {+ const label = row.label ?? row.jarvis;+ // A CLI row that can run on the plan login or a key reports which one+ // it would use right now.+ const billing =+ row.billing === "subscription_or_api"+ ? state.subscriptionOn+ ? "subscription"+ : "api"+ : row.billing;+ return (+ <SettingRow+ key={row.jarvis}+ testId={`provider-agent-${row.jarvis}`}+ label={label}+ hint={+ row.key_set+ ? t(`provider_billing.${billing}`)+ : t(family.subscription ? "providers_page.agents_needs_login_or_key" : "providers_page.agents_needs_key")+ }+ control={+ row.is_active_brain ? (+ <InUse active ready />+ ) : (+ <Button+ size="sm"+ variant="outline"+ data-testid={`provider-agent-use-${row.jarvis}`}+ disabled={!row.key_set || switching !== null}+ onClick={() => void use(row, label)}+ >+ {switching === row.jarvis && <Loader2 className="animate-spin" />}+ {t("providers_page.agents_use")}+ </Button>+ )+ }+ />+ );+ })}+ </ProfileGroup>+ );+}+diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyList.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyList.tsxnew file mode 100644index 0000000000..43e38a57df--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyList.tsx@@ -0,0 +1,103 @@+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { useT } from "@/i18n";+import type { ProviderFamily } from "@/lib/providerFamilies";+import { cn } from "@/lib/utils";+import { familyStatusLine, type FamilyState, type FamilyUse } from "./familyState";++/**+ * The left column: every company once, its connection in one line, and a+ * small tag for each job it powers right now — so the list itself answers+ * "what runs where" before anything is opened.+ */+export function FamilyList({+ families,+ states,+ selectedId,+ onSelect,+}: {+ families: ProviderFamily[];+ states: Record<string, FamilyState>;+ selectedId: string | null;+ onSelect: (id: string) => void;+}) {+ const t = useT();+ return (+ <nav aria-label={t("providers_page.list_label")} data-testid="provider-family-list">+ <ul className="flex flex-col gap-0.5 p-2">+ {families.map((family) => {+ const state = states[family.id];+ if (!state) return null;+ const selected = family.id === selectedId;+ return (+ <li key={family.id}>+ <button+ type="button"+ data-testid={`provider-family-${family.id}`}+ aria-current={selected ? "true" : undefined}+ onClick={() => onSelect(family.id)}+ className={cn(+ "group flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "bg-secondary" : "hover:bg-secondary/60",+ )}+ >+ <ProviderLogo+ providerId={family.logo_id}+ label={family.label}+ className={cn(!state.connected && !selected && "opacity-60")}+ />+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-2">+ <span+ className={cn(+ "truncate text-base font-medium",+ state.connected ? "text-foreground-strong" : "text-muted-foreground",+ )}+ >+ {family.label}+ </span>+ {state.failing && (+ <span+ role="status"+ title={state.failing}+ aria-label={t("providers_page.failing")}+ className="h-2 w-2 shrink-0 rounded-full bg-destructive"+ />+ )}+ </span>+ <span+ className={cn(+ "mt-0.5 block truncate text-sm",+ state.connected ? "text-muted-foreground" : "text-foreground-faint",+ )}+ >+ {familyStatusLine(family, state, t)}+ </span>+ {state.uses.length > 0 && (+ <span className="mt-1.5 flex flex-wrap gap-1">+ {state.uses.map((use) => (+ <UseTag key={use} use={use} />+ ))}+ </span>+ )}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </nav>+ );+}++export function UseTag({ use }: { use: FamilyUse }) {+ const t = useT();+ return (+ <span+ data-testid={`provider-use-${use}`}+ className="inline-flex h-5 items-center rounded-md bg-accent-soft px-1.5 text-xs font-medium text-foreground"+ >+ {t(`providers_page.use_${use}`)}+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/KeySection.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/KeySection.tsxnew file mode 100644index 0000000000..65ab4345e6--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/providers/KeySection.tsx@@ -0,0 +1,262 @@+import { useState } from "react";+import { AlertTriangle, ExternalLink, Eye, EyeOff, Loader2, Trash2 } from "lucide-react";+import { ProviderTestControl } from "@/components/providers/ProviderTierSection";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { deleteSecret, postSecret, type ProviderDescriptor } from "@/hooks/useProviders";+import { useT } from "@/i18n";+import { keyMatchesSecret } from "@/lib/keyFormat";+import { openExternalUrl } from "@/lib/openExternal";+import type { ProviderFamily } from "@/lib/providerFamilies";+import { useEventStore } from "@/store/events";+import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";+import type { FamilyState } from "./familyState";++/** Which member card a key test runs against: the first keyed card, chat first. */+const TEST_TIER_ORDER: ProviderDescriptor["tier"][] = ["brain", "realtime", "tts", "stt", "dictation"];++function announce(slot: string, action: "set" | "delete") {+ // Same signal the per-card forms send: every mounted list and the health+ // dots re-read. Only the slot NAME travels, never a value.+ window.dispatchEvent(new CustomEvent("jarvis:secret-configured", { detail: { key: slot, action } }));+}++/**+ * One key for the whole company. Saving always uses the "everywhere" scope:+ * the key becomes the family key, so live voice, agents, speech and every+ * other feature of this company read it — the "one provider, one key" rule.+ * A feature that still holds an older key of its own is listed underneath+ * with a one-click way back onto the main key.+ */+export function KeySection({+ family,+ state,+ onChanged,+}: {+ family: ProviderFamily;+ state: FamilyState;+ onChanged: () => void | Promise<void>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const slot = family.key_slot!;+ const [editing, setEditing] = useState(false);+ const [value, setValue] = useState("");+ const [reveal, setReveal] = useState(false);+ const [busy, setBusy] = useState<"save" | "delete" | string | null>(null);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const showInput = !family.key_present || editing;+ const format = value.trim() ? keyMatchesSecret(slot, value) : null;+ const testCard = TEST_TIER_ORDER.map((tier) =>+ state.members.find((m) => m.tier === tier && m.auth_mode === "api_key"),+ ).find(Boolean);++ async function save() {+ const trimmed = value.trim();+ if (!trimmed) return;+ setBusy("save");+ try {+ await postSecret(slot, trimmed, "everywhere");+ setValue("");+ setEditing(false);+ setReveal(false);+ announce(slot, "set");+ pushToast("success", t("providers_page.key_saved_toast").replace("{0}", family.label));+ await onChanged();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setBusy(null);+ }+ }++ async function remove(target: string, toast: string) {+ setBusy(target === slot ? "delete" : target);+ try {+ await deleteSecret(target);+ announce(target, "delete");+ pushToast("info", toast);+ await onChanged();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setBusy(null);+ setConfirmDelete(false);+ }+ }++ return (+ <ProfileGroup+ title={t("providers_page.key_title")}+ description={t("providers_page.key_desc").replace("{0}", family.label)}+ testId="provider-key"+ aside={+ family.dashboard_url ? (+ <Button+ size="sm"+ variant="ghost"+ className="text-muted-foreground"+ onClick={() => void openExternalUrl(family.dashboard_url!)}+ >+ <ExternalLink />+ {t("providers_page.get_key")}+ </Button>+ ) : undefined+ }+ >+ <SettingRow+ testId="provider-key-row"+ label={+ <span className="inline-flex items-center gap-2">+ <span+ aria-hidden="true"+ className={family.key_present ? "h-2 w-2 rounded-full bg-success" : "h-2 w-2 rounded-full bg-border-strong"}+ />+ {t("providers_page.key_label")}+ </span>+ }+ hint={+ family.key_present+ ? t("providers_page.key_saved_hint")+ : state.viaProject+ ? t("providers_page.key_project_hint")+ : t("providers_page.key_missing_hint")+ }+ control={+ family.key_present && !editing ? (+ confirmDelete ? (+ <>+ <span className="text-sm text-muted-foreground">{t("providers_page.key_remove_confirm")}</span>+ <Button size="sm" variant="ghost" onClick={() => setConfirmDelete(false)}>+ {t("common.cancel")}+ </Button>+ <Button+ size="sm"+ variant="destructive"+ data-testid="provider-key-remove-confirm"+ disabled={busy !== null}+ onClick={() => void remove(slot, t("providers_page.key_removed_toast").replace("{0}", family.label))}+ >+ {busy === "delete" && <Loader2 className="animate-spin" />}+ {t("providers_page.key_remove")}+ </Button>+ </>+ ) : (+ <>+ <Button size="sm" variant="outline" data-testid="provider-key-replace" onClick={() => setEditing(true)}>+ {t("providers_page.key_replace")}+ </Button>+ <Button+ size="icon"+ variant="ghost"+ className="h-8 w-8 text-muted-foreground"+ aria-label={t("providers_page.key_remove")}+ title={t("providers_page.key_remove")}+ data-testid="provider-key-remove"+ onClick={() => setConfirmDelete(true)}+ >+ <Trash2 />+ </Button>+ </>+ )+ ) : undefined+ }+ >+ {showInput && (+ <div className="mt-3 flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <div className="relative min-w-0 flex-1">+ <Input+ type={reveal ? "text" : "password"}+ autoComplete="off"+ spellCheck={false}+ data-testid="provider-key-input"+ aria-label={t("providers_page.key_label")}+ placeholder={t("providers_page.key_placeholder").replace("{0}", family.label)}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") void save();+ if (event.key === "Escape" && family.key_present) {+ setEditing(false);+ setValue("");+ }+ }}+ className="pr-10 font-mono"+ />+ <button+ type="button"+ onClick={() => setReveal((on) => !on)}+ aria-label={t(reveal ? "providers_page.key_hide" : "providers_page.key_show")}+ className="absolute right-1 top-1/2 grid h-7 w-7 -translate-y-1/2 place-items-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground"+ >+ {reveal ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}+ </button>+ </div>+ {editing && (+ <Button size="sm" variant="ghost" onClick={() => { setEditing(false); setValue(""); }}>+ {t("common.cancel")}+ </Button>+ )}+ <Button+ size="sm"+ data-testid="provider-key-save"+ disabled={!value.trim() || busy !== null}+ onClick={() => void save()}+ >+ {busy === "save" && <Loader2 className="animate-spin" />}+ {t("providers_page.key_save")}+ </Button>+ </div>+ {format && !format.match && format.detected && (+ <p role="status" className="flex items-start gap-1.5 text-sm text-warning">+ <AlertTriangle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0" />+ {t("providers_page.key_format_warning")+ .replace("{0}", format.detected.label)+ .replace("{1}", family.label)}+ </p>+ )}+ </div>+ )}+ </SettingRow>++ {family.key_present && testCard && (+ <SettingRow+ label={t("providers_page.key_test_label")}+ hint={t("providers_page.key_test_hint")}+ control={+ <ProviderTestControl+ providerId={testCard.id}+ providerLabel={testCard.label}+ section={testCard.tier}+ active={testCard.active}+ />+ }+ />+ )}++ {family.separate_keys.map((entry) => (+ <SettingRow+ key={entry.slot}+ testId={`provider-separate-key-${entry.slot}`}+ label={t(`providers_page.separate_${entry.surface}`)}+ hint={t("providers_page.separate_hint")}+ control={+ <Button+ size="sm"+ variant="outline"+ disabled={busy !== null || !family.key_present}+ title={family.key_present ? undefined : t("providers_page.separate_needs_main")}+ onClick={() =>+ void remove(entry.slot, t("providers_page.separate_merged_toast").replace("{0}", family.label))+ }+ >+ {busy === entry.slot && <Loader2 className="animate-spin" />}+ {t("providers_page.separate_merge")}+ </Button>+ }+ />+ ))}+ </ProfileGroup>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/SubscriptionSection.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/SubscriptionSection.tsxnew file mode 100644index 0000000000..5231717f3a--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/providers/SubscriptionSection.tsx@@ -0,0 +1,213 @@+import { useState } from "react";+import { FlaskConical, Loader2, LogIn, LogOut } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ codexLogout,+ loginAntigravity,+ loginClaude,+ loginGrokBuild,+ logoutAntigravity,+ logoutClaude,+ logoutGrokBuild,+ startCodexLogin,+ testAgentCli,+ type AgentCliTestResult,+ type ProviderDescriptor,+} from "@/hooks/useProviders";+import { useT } from "@/i18n";+import {+ pollUntilConnected,+ subscriptionStatusUrl,+ type ProviderFamily,+ type SubscriptionKind,+} from "@/lib/providerFamilies";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";+import type { FamilyState } from "./familyState";++/** The four subscription logins, each driven by the vendor's own CLI. */+const LOGIN: Record<+ SubscriptionKind,+ { login: () => Promise<void>; logout: () => Promise<void>; test: string; where: "browser" | "terminal" }+> = {+ codex: { login: () => startCodexLogin(), logout: () => codexLogout(), test: "/api/codex/test", where: "browser" },+ claude_cli: { login: loginClaude, logout: logoutClaude, test: "/api/claude/test", where: "terminal" },+ antigravity: { login: loginAntigravity, logout: logoutAntigravity, test: "/api/antigravity/test", where: "browser" },+ grok_build: { login: loginGrokBuild, logout: logoutGrokBuild, test: "/api/grok-build/test", where: "browser" },+};++/**+ * Sign in with the plan the user already pays for. One row says whose plan is+ * connected and offers the one next step (connect, finish, disconnect); a+ * second row names the command-line tool behind it, the way a terminal user+ * would check it, with a live test.+ */+export function SubscriptionSection({+ family,+ state,+ onChanged,+}: {+ family: ProviderFamily;+ state: FamilyState;+ onChanged: () => void | Promise<void>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [pending, setPending] = useState<"login" | "logout" | "waiting" | null>(null);+ const subscription = family.subscription!;+ const flow = LOGIN[subscription.kind];+ const status = state.subscription;+ const card: ProviderDescriptor | undefined = state.members.find(+ (m) => m.id === subscription.provider_id,+ );+ const installed = status?.installed ?? false;+ const version = status?.version ?? null;+ const binary = status && "binary_path" in status ? status.binary_path ?? null : null;++ async function connect() {+ setPending("login");+ try {+ await flow.login();+ pushToast(+ "info",+ t(flow.where === "browser" ? "providers_page.login_started_browser" : "providers_page.login_started_terminal"),+ );+ setPending("waiting");+ await onChanged();+ const ok = await pollUntilConnected(subscriptionStatusUrl(subscription.kind), onChanged);+ if (ok) pushToast("success", t("providers_page.login_done").replace("{0}", family.label));+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setPending(null);+ }+ }++ async function disconnect() {+ setPending("logout");+ try {+ await flow.logout();+ pushToast("info", t("providers_page.logout_done").replace("{0}", family.label));+ await onChanged();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setPending(null);+ }+ }++ const hint = !status+ ? t("providers_page.subscription_unknown")+ : state.subscriptionOn+ ? state.account+ ? t("providers_page.subscription_signed_in").replace("{0}", state.account)+ : status.message+ : !installed+ ? card?.install_hint || t("providers_page.subscription_install")+ : pending === "waiting"+ ? t(flow.where === "browser" ? "providers_page.login_waiting_browser" : "providers_page.login_waiting_terminal")+ : t("providers_page.subscription_hint");++ return (+ <ProfileGroup+ title={t("providers_page.subscription_title")}+ description={t("providers_page.subscription_desc").replace("{0}", family.label)}+ testId="provider-subscription"+ >+ <SettingRow+ label={+ <span className="inline-flex items-center gap-2">+ <span+ aria-hidden="true"+ className={cn(+ "h-2 w-2 rounded-full",+ state.subscriptionOn ? "bg-success" : "bg-border-strong",+ )}+ />+ {subscription.label}+ </span>+ }+ hint={hint}+ control={+ state.subscriptionOn ? (+ <Button+ size="sm"+ variant="outline"+ data-testid="provider-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="provider-subscription-connect"+ disabled={pending !== null || !installed}+ onClick={() => void connect()}+ >+ {pending === "login" || pending === "waiting" ? <Loader2 className="animate-spin" /> : <LogIn />}+ {t("providers_page.connect")}+ </Button>+ )+ }+ />+ {installed && (+ <SettingRow+ label={t("providers_page.cli_label")}+ hint={+ <span className="break-all">+ {[version, binary].filter(Boolean).join(" · ") || t("providers_page.cli_found")}+ </span>+ }+ control={<CliTest endpoint={flow.test} onChanged={onChanged} />}+ />+ )}+ </ProfileGroup>+ );+}++/** A live check of the CLI: found where, which version, signed in as whom. */+function CliTest({ endpoint, onChanged }: { endpoint: string; onChanged: () => void | Promise<void> }) {+ const t = useT();+ const [running, setRunning] = useState(false);+ const [result, setResult] = useState<AgentCliTestResult | null>(null);+ const [error, setError] = useState<string | null>(null);++ async function run() {+ setRunning(true);+ setError(null);+ try {+ setResult(await testAgentCli(endpoint));+ await onChanged();+ } catch (cause) {+ setResult(null);+ setError((cause as Error).message);+ } finally {+ setRunning(false);+ }+ }++ return (+ <span className="flex items-center gap-3">+ {(result || error) && (+ <span+ role="status"+ title={error ?? result?.message}+ className={cn(+ "max-w-[16rem] truncate text-sm",+ error || (result && !result.ok) ? "text-destructive" : "text-muted-foreground",+ )}+ >+ {error ?? result?.message}+ </span>+ )}+ <Button size="sm" variant="ghost" disabled={running} onClick={() => void run()}>+ {running ? <Loader2 className="animate-spin" /> : <FlaskConical />}+ {t("providers_page.test")}+ </Button>+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/familyState.test.ts b/jarvis/ui/web/frontend/src/views/apikeys/providers/familyState.test.tsnew file mode 100644index 0000000000..c4d1535b86--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/providers/familyState.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from "vitest";+import type { ProviderDescriptor, SectionHealth } from "@/hooks/useProviders";+import type { AgentStatus, ProviderFamily } from "@/lib/providerFamilies";+import { familyState, familyStatusLine, type FamilyContext } from "./familyState";++const t = (key: string) => key;++function family(overrides: Partial<ProviderFamily> = {}): ProviderFamily {+ return {+ id: "openai",+ label: "OpenAI",+ logo_id: "openai",+ local: false,+ key_slot: "openai_api_key",+ key_present: false,+ separate_keys: [],+ dashboard_url: null,+ signup_url: null,+ subscription: { kind: "codex", provider_id: "codex", label: "OpenAI Codex" },+ provider_ids: ["openai", "codex", "openai-live", "openai-api"],+ hidden_ids: ["openai-live-subscription"],+ agent_ids: ["openai", "openai-codex"],+ ...overrides,+ };+}++function card(id: string, tier: ProviderDescriptor["tier"], extra: Partial<ProviderDescriptor> = {}) {+ return { id, label: id, tier, active: false, configured: true, ...extra } as ProviderDescriptor;+}++function ctx(overrides: Partial<FamilyContext> = {}): FamilyContext {+ return {+ providers: [card("openai-live", "realtime"), card("openai-api", "stt"), card("gemini-live", "realtime")],+ subscriptions: {},+ agents: null,+ health: {},+ ...overrides,+ };+}++const agents = (active: string): AgentStatus => ({+ brain_primary: active,+ mapping: [+ { jarvis: "openai-codex", key_set: true, is_active_brain: active === "openai-codex", billing: "subscription_or_api" },+ { jarvis: "gemini", key_set: true, is_active_brain: active === "gemini", billing: "api" },+ ],+});++describe("familyState", () => {+ it("takes only the company's own cards", () => {+ const state = familyState(family(), ctx());+ expect(state.members.map((m) => m.id)).toEqual(["openai-live", "openai-api"]);+ });++ it("reports a subscription login as connected, but not a CLI running on a key", () => {+ const signedIn = familyState(+ family(),+ ctx({ subscriptions: { codex: { installed: true, connected: true, mode: "chatgpt", message: "", user_email: "[email protected]" } } }),+ );+ expect(signedIn.subscriptionOn).toBe(true);+ expect(signedIn.account).toBe("[email protected]");+ expect(signedIn.connected).toBe(true);++ const onKey = familyState(+ family(),+ ctx({ subscriptions: { codex: { installed: true, connected: true, mode: "api_key", message: "" } } }),+ );+ expect(onKey.subscriptionOn).toBe(false);+ expect(onKey.connected).toBe(false);+ });++ it("lists the jobs it powers and the jobs it could take over", () => {+ const state = familyState(+ family({ key_present: true }),+ ctx({+ providers: [card("openai-live", "realtime", { active: true }), card("openai-api", "stt")],+ agents: agents("openai-codex"),+ }),+ );+ expect(state.uses).toEqual(["voice", "agents"]);+ expect(state.canDo).toEqual(["voice", "agents", "hearing"]);+ });++ it("puts a failure on the company whose member is failing, matching hidden cards too", () => {+ const health: Record<string, SectionHealth> = {+ realtime: { status: "error", reason: "quota", detail: "GPT-Live: out of credit", subject_id: "openai-live-subscription" },+ };+ const state = familyState(+ family({ key_present: true }),+ ctx({ providers: [card("openai-live", "realtime", { active: true })], health }),+ );+ expect(state.failing).toBe("GPT-Live: out of credit");+ });++ it("never blames a company for another company's failure", () => {+ const health: Record<string, SectionHealth> = {+ realtime: { status: "error", reason: "quota", detail: "Gemini Live: out of credit", subject_id: "gemini-live" },+ };+ const state = familyState(+ family({ key_present: true }),+ ctx({ providers: [card("openai-live", "realtime", { active: true })], health }),+ );+ expect(state.failing).toBeNull();+ });++ it("counts a Cloud-project sign-in as connected without a key", () => {+ const vertex = family({+ id: "vertex",+ subscription: null,+ provider_ids: ["vertex"],+ agent_ids: ["vertex"],+ hidden_ids: [],+ });+ const state = familyState(+ vertex,+ ctx({ providers: [card("vertex", "brain", { credential_note: "Signed in through the project." })] }),+ );+ expect(state.viaProject).toBe(true);+ expect(state.connected).toBe(true);+ expect(familyStatusLine(vertex, state, t)).toBe("providers_page.status_project");+ });+});++describe("familyStatusLine", () => {+ it("names exactly what is connected", () => {+ const f = family({ key_present: true });+ const both = familyState(+ f,+ ctx({ subscriptions: { codex: { installed: true, connected: true, mode: "chatgpt", message: "" } } }),+ );+ expect(familyStatusLine(f, both, t)).toBe("providers_page.status_both");+ expect(familyStatusLine(family(), familyState(family(), ctx()), t)).toBe("providers_page.status_none");+ const local = family({ id: "local", local: true, key_slot: null, subscription: null });+ expect(familyStatusLine(local, familyState(local, ctx()), t)).toBe("providers_page.status_local");+ });+});diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/familyState.ts b/jarvis/ui/web/frontend/src/views/apikeys/providers/familyState.tsnew file mode 100644index 0000000000..d1735f1b44--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/providers/familyState.ts@@ -0,0 +1,126 @@+import type { ProviderDescriptor, SectionHealth } from "@/hooks/useProviders";+import {+ subscriptionAccount,+ subscriptionConnected,+ type AgentStatus,+ type ProviderFamily,+ type SubscriptionKind,+ type SubscriptionStatus,+} from "@/lib/providerFamilies";++/** The jobs a company can do for the assistant, in the order the page lists them. */+export const FAMILY_USES = ["voice", "agents", "speech", "hearing", "dictation"] as const;+export type FamilyUse = (typeof FAMILY_USES)[number];++/** Which provider tier answers for each job (agents come from the worker rows). */+const USE_TIER: Record<Exclude<FamilyUse, "agents">, ProviderDescriptor["tier"]> = {+ voice: "realtime",+ speech: "tts",+ hearing: "stt",+ dictation: "dictation",+};++/** Section-health keys whose failing subject points at a member of a family. */+const HEALTH_SECTIONS: Record<FamilyUse, string> = {+ voice: "realtime",+ agents: "subagents",+ speech: "tts",+ hearing: "stt",+ dictation: "dictation",+};++export interface FamilyState {+ members: ProviderDescriptor[];+ subscription: SubscriptionStatus | null;+ /** The subscription login is what powers the CLI right now. */+ subscriptionOn: boolean;+ /** "ruben@… · Claude Max", when the login reports it. */+ account: string | null;+ keyOn: boolean;+ /** Authenticated without a key (a Google Cloud project). */+ viaProject: boolean;+ /** Ready to use for at least one job. */+ connected: boolean;+ /** Jobs this company powers right now. */+ uses: FamilyUse[];+ /** Jobs this company could take over (it has a member card for them). */+ canDo: FamilyUse[];+ /** A job it powers is failing its real calls; the backend's one-line reason. */+ failing: string | null;+}++export interface FamilyContext {+ providers: ProviderDescriptor[];+ subscriptions: Partial<Record<SubscriptionKind, SubscriptionStatus | null>>;+ agents: AgentStatus | null;+ health: Record<string, SectionHealth | undefined>;+}++export function familyState(family: ProviderFamily, ctx: FamilyContext): FamilyState {+ const members = ctx.providers.filter((p) => family.provider_ids.includes(p.id));+ const subscription = family.subscription ? ctx.subscriptions[family.subscription.kind] ?? null : null;+ const subscriptionOn = subscriptionConnected(subscription);+ const viaProject =+ !family.key_present && members.some((m) => Boolean(m.credential_note) && m.configured);+ const agentRows = (ctx.agents?.mapping ?? []).filter((row) => family.agent_ids.includes(row.jarvis));++ const uses: FamilyUse[] = [];+ const canDo: FamilyUse[] = [];+ for (const use of FAMILY_USES) {+ if (use === "agents") {+ if (agentRows.length) canDo.push(use);+ if (agentRows.some((row) => row.is_active_brain)) uses.push(use);+ continue;+ }+ const tier = USE_TIER[use];+ const cards = members.filter((m) => m.tier === tier);+ if (cards.length) canDo.push(use);+ if (cards.some((m) => m.active)) uses.push(use);+ }++ const memberIds = new Set([...family.provider_ids, ...family.hidden_ids, ...family.agent_ids]);+ let failing: string | null = null;+ for (const use of uses) {+ const entry = ctx.health[HEALTH_SECTIONS[use]];+ if (entry?.status === "error" && entry.subject_id && memberIds.has(entry.subject_id)) {+ failing = entry.detail || entry.reason;+ break;+ }+ }++ return {+ members,+ subscription,+ subscriptionOn,+ account: subscriptionOn ? subscriptionAccount(subscription) : null,+ keyOn: family.key_present,+ viaProject,+ connected: subscriptionOn || family.key_present || viaProject || family.local,+ uses,+ canDo,+ failing,+ };+}++/**+ * The one status line under a company's name. `t` is the page translator;+ * every branch says exactly what is known, never more.+ */+export function familyStatusLine(+ family: ProviderFamily,+ state: FamilyState,+ t: (key: string) => string,+): string {+ if (family.local) return t("providers_page.status_local");+ if (state.subscriptionOn && state.keyOn) {+ return t("providers_page.status_both");+ }+ if (state.subscriptionOn) {+ return state.account+ ? t("providers_page.status_subscription_as").replace("{0}", state.account)+ : t("providers_page.status_subscription");+ }+ if (state.keyOn) return t("providers_page.status_key");+ if (state.viaProject) return t("providers_page.status_project");+ return t("providers_page.status_none");+}diff --git a/jarvis/ui/web/provider_families.py b/jarvis/ui/web/provider_families.pyindex 348f215410..adfde9b77b 100644--- a/jarvis/ui/web/provider_families.py+++ b/jarvis/ui/web/provider_families.py@@ -83,6 +83,9 @@ class _Family:id: strlabel: strspecs: list[ProviderSpec] = field(default_factory=list)+ # Withdrawn cards still running an existing selection: no row on the page,+ # but health and "in use" reports name them, so they map to the company.+ hidden: list[str] = field(default_factory=list)def family_of(spec: ProviderSpec) -> str:@@ -101,14 +104,20 @@ def family_of(spec: ProviderSpec) -> str:def _group() -> list[_Family]:families: dict[str, _Family] = {}+ hidden: list[ProviderSpec] = []for spec in PROVIDERS:if spec.hidden:+ hidden.append(spec)continuefid = family_of(spec)family = families.get(fid)if family is None:family = families[fid] = _Family(id=fid, label=_FAMILY_LABELS.get(fid, spec.label))family.specs.append(spec)+ for spec in hidden:+ owner = families.get(family_of(spec))+ if owner is not None:+ owner.hidden.append(spec.id)def rank(family: _Family) -> tuple[int, int]:if family.id == LOCAL_FAMILY:@@ -211,6 +220,7 @@ def build_families("signup_url": _first(family, "signup_url", None),"subscription": _subscription(family),"provider_ids": provider_ids,+ "hidden_ids": list(family.hidden),"agent_ids": list(dict.fromkeys(agent_ids)),})