Skip to content

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

fix(agent-chat): do not paint API-key errors on coding CLI seats

rubenluetke10-beep51acf3f5826e
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index f1aac873a0..16f6a37084 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -3,6 +3,7 @@
Prefix ``/api/agent-chat``:
GET /catalog?surface= provider rows + effort + permission ladders
+ GET /provider-health?surface= which of those rows actually answer
GET /sessions?surface= newest first; ``surface`` narrows to one chat
POST /sessions create (provider, model, effort, cwd,
permission_mode, surface)
@@ -27,8 +28,9 @@ from __future__ import annotations
import asyncio
import logging
import os
+import time
from pathlib import Path
-from typing import Any, Literal
+from typing import Any, Final, Literal
from fastapi import (
APIRouter,
@@ -260,6 +262,216 @@ async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[
}
+# ------------------------------------------------------------- health
+
+
+class ProviderHealthRow(BaseModel):
+ """One row's live state, in the API-Keys screen's own vocabulary."""
+
+ provider: str
+ #: ok | needs_setup | error | unknown (jarvis.brain.section_health).
+ status: str = "unknown"
+ #: Machine-readable cause — "bad_key", "no_credits", "not_configured",
+ #: "timeout", … The UI turns it into a sentence; it is never shown raw.
+ reason: str = "unknown"
+ #: The provider's own words, for the tooltip and the log.
+ detail: str = ""
+
+
+class ProviderHealthResponse(BaseModel):
+ providers: list[ProviderHealthRow]
+ checked_at: float = 0.0
+ cached: bool = False
+
+
+#: How long one sweep stands. A key does not go bad between two clicks, and
+#: the sweep costs one real request per provider — 9 s to 16 s each on the
+#: maintainer's box (measured 2026-08-26), which is why nothing waits for it.
+_HEALTH_TTL_S: Final[float] = 300.0
+#: The whole sweep's ceiling. A provider still thinking when this runs out is
+#: reported ``unknown`` and draws no dot: a seat that cannot answer a one-token
+#: request inside this is not a seat someone should be told is fine, but
+#: neither is a slow network proof that a key is bad.
+_HEALTH_SWEEP_S: Final[float] = 20.0
+
+#: surface -> (checked_at, rows). Process-local, like every other short cache
+#: in the routes; a restart simply re-sweeps on first use.
+_health_cache: dict[str, tuple[float, list[ProviderHealthRow]]] = {}
+
+#: Vendor CLI runners. Their credential is a subscription login, not a key,
+#: so the API-Keys one-token probe is the wrong check: the dual Claude row
+#: is catalogued as ``claude-api``, and that probe hits Anthropic's endpoint
+#: and paints "Key rejected" on a Claude Code seat that is signed in.
+_CLI_RUNNERS: Final[frozenset[str]] = frozenset({"claude-cli", "codex-cli", "agy-cli", "grok-cli"})
+
+
+def _cli_auth_status(runner: str) -> Any | None:
+ """The vendor CLI's own login snapshot. ``None`` if ``runner`` is not a CLI."""
+ if runner == "claude-cli":
+ from jarvis.claude_auth import ClaudeAuthService
+
+ return ClaudeAuthService().status()
+ if runner == "codex-cli":
+ from jarvis.codex_auth import CodexAuthService
+
+ return CodexAuthService().status()
+ if runner == "agy-cli":
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ return GoogleCliAuthService().status()
+ if runner == "grok-cli":
+ from jarvis.grok_build_auth import GrokBuildAuthService
+
+ return GrokBuildAuthService().status()
+ return None
+
+
+def _cli_subscription_connected(runner: str, st: Any) -> bool:
+ """Whether ``st`` is a login this CLI seat can actually spend.
+
+ Claude and Grok Build report ``connected=True`` for a stored API key as
+ well; that key belongs to a different picker row. Antigravity's
+ ``api_key`` mode is the Gemini key, same split. Codex's ``connected``
+ is the CLI's own auth.json (ChatGPT login or a key the CLI itself
+ holds), which is what ``codex exec`` uses.
+ """
+ connected = bool(getattr(st, "connected", False))
+ mode = (getattr(st, "mode", None) or "").strip().lower()
+ if runner == "claude-cli":
+ return connected and mode == "subscription"
+ if runner == "grok-cli":
+ return connected and mode == "subscription"
+ if runner == "agy-cli":
+ return connected and mode == "oauth-personal"
+ return connected
+
+
+def _cli_login_snapshot(runner: str) -> tuple[str, str, str]:
+ """Login presence for a vendor CLI seat. Never a live API-key call.
+
+ Returns ``(status, reason, detail)``. A signed-in subscription is
+ ``ok``; anything else is ``needs_setup`` so the picker does not borrow
+ API-key words ("Key rejected") for a seat that has no key.
+ """
+ try:
+ st = _cli_auth_status(runner)
+ except Exception as exc: # noqa: BLE001 — one bad CLI must not lose the sweep
+ log.info("agent chat: CLI login check for %s failed: %s", runner, exc)
+ return (
+ "unknown",
+ "check_failed",
+ f"The check itself failed ({type(exc).__name__})",
+ )
+ if st is None:
+ return "unknown", "unknown_provider", f"{runner}: not a CLI seat"
+ connected = _cli_subscription_connected(runner, st)
+ detail = (getattr(st, "message", None) or "").strip() or (
+ f"{runner}: signed in" if connected else f"{runner}: not signed in"
+ )
+ if connected:
+ return "ok", "ok", detail
+ return "needs_setup", "not_configured", detail
+
+
+async def _one_provider_health(cfg: Any, provider_id: str, *, surface: str) -> ProviderHealthRow:
+ """One row, never raising: a broken check is ``unknown``, not a 500."""
+ runner = resolve_runner(provider_id, surface=surface)
+ if runner in _CLI_RUNNERS:
+ try:
+ status, reason, detail = await asyncio.to_thread(_cli_login_snapshot, runner)
+ except Exception as exc: # noqa: BLE001 — one bad row must not lose the sweep
+ log.info("agent chat: CLI health check for %s failed: %s", provider_id, exc)
+ return ProviderHealthRow(
+ provider=provider_id,
+ status="unknown",
+ reason="check_failed",
+ detail=f"The check itself failed ({type(exc).__name__})",
+ )
+ return ProviderHealthRow(provider=provider_id, status=status, reason=reason, detail=detail)
+
+ from jarvis.ui.web.provider_routes import provider_health
+
+ try:
+ health = await provider_health(cfg, provider_id, probe=True)
+ except TimeoutError:
+ return ProviderHealthRow(
+ provider=provider_id, status="unknown", reason="timeout", detail="No answer in time"
+ )
+ except Exception as exc: # noqa: BLE001 — one bad row must not lose the sweep
+ log.info("agent chat: health check for %s failed: %s", provider_id, exc)
+ return ProviderHealthRow(
+ provider=provider_id,
+ status="unknown",
+ reason="check_failed",
+ detail=f"The check itself failed ({type(exc).__name__})",
+ )
+ return ProviderHealthRow(
+ provider=provider_id,
+ status=health.status,
+ reason=health.reason,
+ detail=health.detail,
+ )
+
+
[email protected]("/provider-health")
+async def get_provider_health(
+ request: Request, surface: SurfaceName = "agent", refresh: bool = False
+) -> ProviderHealthResponse:
+ """Which of ``surface``'s rows actually answer right now.
+
+ The composer shows whether a provider is CONNECTED — a key is saved. That
+ is not the same as usable: a key can be revoked, an account can run out of
+ credits, an endpoint can be down. On the maintainer's own box on
+ 2026-08-26, four of nine connected rows were in one of those states, and
+ the picker offered all nine as if they were equal.
+
+ API / brain seats run the real one-token check the API-Keys screen's tab
+ dots use (``provider_routes.provider_health``). A vendor CLI seat does
+ not: it spends a subscription login, so this reports that login instead.
+ The dual Claude row is why the split exists — its catalog id is
+ ``claude-api``, and the API-Keys probe would otherwise paint "Key
+ rejected" on a Claude Code seat that is signed in.
+
+ Nothing waits for this: the composer paints from the catalog and folds
+ these in when they land. A row that does not finish inside the sweep
+ ceiling comes back ``unknown`` and is drawn exactly as it was before.
+ """
+ _service(request) # 503 like every other route when the chat is off
+ now = time.monotonic()
+ cached = _health_cache.get(surface)
+ if cached and not refresh and (now - cached[0]) < _HEALTH_TTL_S:
+ return ProviderHealthResponse(providers=cached[1], checked_at=cached[0], cached=True)
+
+ from jarvis.ui.web.provider_routes import _resolve_cfg
+
+ cfg = _resolve_cfg(request)
+ ids = [row.id for row in rows_for(surface)]
+ tasks = {
+ pid: asyncio.create_task(_one_provider_health(cfg, pid, surface=surface)) for pid in ids
+ }
+ try:
+ await asyncio.wait_for(
+ asyncio.gather(*tasks.values(), return_exceptions=True), timeout=_HEALTH_SWEEP_S
+ )
+ except TimeoutError:
+ log.info("agent chat: provider health sweep hit its %.0fs ceiling", _HEALTH_SWEEP_S)
+ rows: list[ProviderHealthRow] = []
+ for pid, task in tasks.items():
+ if task.done() and not task.cancelled():
+ exc = task.exception()
+ if exc is None:
+ rows.append(task.result())
+ continue
+ task.cancel()
+ rows.append(
+ ProviderHealthRow(
+ provider=pid, status="unknown", reason="timeout", detail="No answer in time"
+ )
+ )
+ _health_cache[surface] = (now, rows)
+ return ProviderHealthResponse(providers=rows, checked_at=now, cached=False)
+
+
# ------------------------------------------------------------------ sessions
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
index 4a153121d7..6aae52663b 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
@@ -92,6 +92,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
const backendOutdated = useAgentChat((s) => s.backendOutdated);
const connections = useAgentChat((s) => s.connections);
const liveModels = useAgentChat((s) => s.liveModels);
+ const health = useAgentChat((s) => s.health);
const draft = useAgentChat((s) => s.draft);
const activeSessionId = useAgentChat((s) => s.activeSessionId);
const timeline = useAgentChat((s) => s.timeline);
@@ -210,18 +211,54 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
const providerGroups = useMemo<ComboboxGroup[]>(() => {
const anyConnected = providers.some((p) => p.connected);
const shown = anyConnected ? providers.filter((p) => p.connected) : providers;
- const toOption = (p: ProviderOption): ComboboxOption => ({
- value: p.id,
- label: p.label,
- hint: p.connected
- ? undefined
- : p.cli_installed === false
- ? t("agent_chat.provider_not_installed")
- : t("agent_chat.provider_connect"),
- disabled: !p.connected,
- icon: <ProviderLogo providerId={p.id} label={p.label} size="sm" />,
- searchText: `${p.family} ${p.runner}`,
- });
+ const toOption = (p: ProviderOption): ComboboxOption => {
+ // A saved key is not a working one. The live sweep says which seats
+ // actually answered a real request; until it lands (or on a backend
+ // that has no such route) the row looks exactly as it did before.
+ // A coding CLI spends a subscription login, not a key — a leaked
+ // `bad_key` (the dual Claude row shares the Anthropic API id) must
+ // not paint "Key rejected" on that CLI.
+ const live = liveHealthFor(p, health[p.id]);
+ const broken = p.connected && live?.status === "error";
+ const working = p.connected && live?.status === "ok";
+ return {
+ value: p.id,
+ label: p.label,
+ hint: !p.connected
+ ? p.cli_installed === false
+ ? t("agent_chat.provider_not_installed")
+ : t("agent_chat.provider_connect")
+ : broken
+ ? healthReasonLabel(live?.reason ?? "", t)
+ : undefined,
+ // Still selectable when broken: a rate limit or a flat network passes,
+ // and refusing the click would strand someone whose account recovered
+ // a minute ago. The dot and the reason are the honest part.
+ disabled: !p.connected,
+ icon: (
+ <span className="relative inline-flex shrink-0">
+ <ProviderLogo providerId={p.id} label={p.label} size="sm" />
+ {(broken || working) && (
+ <span
+ data-testid={`provider-health-${p.id}`}
+ data-health={live?.status}
+ title={live?.detail || undefined}
+ aria-label={
+ broken
+ ? healthReasonLabel(live?.reason ?? "", t)
+ : t("agent_chat.provider_health_ok")
+ }
+ className={cn(
+ "absolute -bottom-0.5 -right-0.5 h-2 w-2 rounded-full ring-2 ring-popover",
+ broken ? "bg-destructive" : "bg-emerald-500",
+ )}
+ />
+ )}
+ </span>
+ ),
+ searchText: `${p.family} ${p.runner}`,
+ };
+ };
const labels: Record<ProviderKind, string> = {
cli: t("agent_chat.group_clis"),
api: t("agent_chat.group_api_keys"),
@@ -233,7 +270,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
if (rows.length) groups.push({ id: kind, label: labels[kind], options: rows.map(toOption) });
}
return groups;
- }, [providers, t]);
+ }, [providers, health, t]);
const modelList = useMemo(() => {
if (!provider) return [];
@@ -667,6 +704,33 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
* every row on the front page's chat resolves to. Reading it as a CLI put
* the whole list under the wrong heading there.
*/
+/**
+ * A health reason in the person's own words. The backend's `reason` is a
+ * machine token ("bad_key", "no_credits", …) from the same vocabulary the
+ * API-Keys screen uses; an unfamiliar one falls back to the general "not
+ * answering" rather than showing a word out of a log.
+ */
+export function healthReasonLabel(reason: string, t: (key: string) => string): string {
+ switch (reason) {
+ case "bad_key":
+ return t("agent_chat.provider_health_bad_key");
+ case "no_credits":
+ case "rate_limited":
+ return t("agent_chat.provider_health_no_credits");
+ case "unreachable":
+ return t("agent_chat.provider_health_unreachable");
+ case "timeout":
+ return t("agent_chat.provider_health_slow");
+ default:
+ return t("agent_chat.provider_health_error");
+ }
+}
+
+/** Reasons that only make sense for a stored API key. */
+export function isApiKeyHealthReason(reason: string): boolean {
+ return reason === "bad_key";
+}
+
export type ProviderKind = "cli" | "api" | "local";
export const PROVIDER_KINDS: readonly ProviderKind[] = ["cli", "api", "local"];
export function providerKind(p: { runner: string; keyless: boolean }): ProviderKind {
@@ -674,6 +738,15 @@ export function providerKind(p: { runner: string; keyless: boolean }): ProviderK
return isApiRunner(p.runner) ? "api" : "cli";
}
+function liveHealthFor(
+ p: { runner: string; keyless: boolean },
+ live: { status: string; reason: string; detail: string } | undefined,
+): { status: string; reason: string; detail: string } | undefined {
+ if (!live) return undefined;
+ if (providerKind(p) === "cli" && isApiKeyHealthReason(live.reason)) return undefined;
+ return live;
+}
+
/** One compact pick on the composer's bottom row — a pill-sized Combobox. */
function Pick({
testId,
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/providerHealth.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/providerHealth.test.tsx
new file mode 100644
index 0000000000..a952d5016a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/providerHealth.test.tsx
@@ -0,0 +1,296 @@
+/**
+ * The composer's live provider state.
+ *
+ * A saved key is not a working one. On the maintainer's own box on
+ * 2026-08-26 four of nine CONNECTED rows were unusable — an Anthropic key
+ * revoked (401), OpenAI and OpenRouter out of credit (429/402), Gemini not
+ * answering inside twenty seconds — and the picker offered all nine as
+ * equals. The chat then answered "I can't reach my provider" and the person
+ * had no way to see which seat to move to.
+ *
+ * So the picker carries the live sweep: a dot on the row and, when it is
+ * broken, the reason in plain words. These pin that the reason vocabulary is
+ * translated rather than echoed from a log, and that a row stays exactly as
+ * it was when nothing is known about it.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import {
+ AgentComposer,
+ healthReasonLabel,
+ isApiKeyHealthReason,
+} from "@/components/agentchat/AgentComposer";
+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";
+import { EMPTY_TIMELINE } from "@/components/agentchat/reduce";
+import { useAgentChatStore } from "@/store/agentChat";
+import { useEventStore } from "@/store/events";
+import type { AgentChatCatalog, ProviderHealth } from "@/lib/agentChatApi";
+
+/** The real dictionary, so a missing key shows up here rather than in the UI. */
+import de from "@/i18n/locales/de.json";
+import en from "@/i18n/locales/en.json";
+import es from "@/i18n/locales/es.json";
+
+function lookup(dict: Record<string, unknown>) {
+ return (key: string): string => {
+ const value = key.split(".").reduce<unknown>(
+ (node, part) => (node && typeof node === "object" ? (node as Record<string, unknown>)[part] : undefined),
+ dict,
+ );
+ if (typeof value !== "string") throw new Error(`missing translation: ${key}`);
+ return value;
+ };
+}
+
+describe("provider health reasons", () => {
+ it("says what is wrong in words, never the backend's token", () => {
+ const t = lookup(en);
+ expect(healthReasonLabel("bad_key", t)).toBe("Key rejected");
+ expect(healthReasonLabel("no_credits", t)).toBe("Out of credit");
+ expect(healthReasonLabel("rate_limited", t)).toBe("Out of credit");
+ expect(healthReasonLabel("unreachable", t)).toBe("Unreachable");
+ expect(healthReasonLabel("timeout", t)).toBe("Too slow");
+ });
+
+ it("falls back to a general sentence for a reason it has not met", () => {
+ const t = lookup(en);
+ // A future provider_test status must never leak a log word into the picker.
+ expect(healthReasonLabel("some_new_status", t)).toBe("Not answering");
+ expect(healthReasonLabel("", t)).toBe("Not answering");
+ });
+
+ it("treats only a rejected key as an API-key reason", () => {
+ expect(isApiKeyHealthReason("bad_key")).toBe(true);
+ expect(isApiKeyHealthReason("no_credits")).toBe(false);
+ expect(isApiKeyHealthReason("ok")).toBe(false);
+ });
+
+ it("is translated in every shipped locale", () => {
+ for (const dict of [de, en, es]) {
+ const t = lookup(dict as Record<string, unknown>);
+ for (const reason of ["bad_key", "no_credits", "unreachable", "timeout", "nonsense"]) {
+ expect(healthReasonLabel(reason, t).length).toBeGreaterThan(0);
+ }
+ expect(t("agent_chat.provider_health_ok").length).toBeGreaterThan(0);
+ }
+ });
+
+ it("keeps the three locales in step on every health key", () => {
+ const keys = Object.keys((de as Record<string, Record<string, unknown>>).agent_chat).filter((k) =>
+ k.startsWith("provider_health_"),
+ );
+ expect(keys.length).toBeGreaterThan(0);
+ for (const dict of [en, es]) {
+ const other = (dict as Record<string, Record<string, unknown>>).agent_chat;
+ for (const key of keys) expect(typeof other[key]).toBe("string");
+ }
+ });
+});
+
+
+// ── the dot on the row ────────────────────────────────────────────────────
+
+function row(id: string, label: string, runner: "brain" | "claude-cli" = "brain") {
+ return {
+ id,
+ label,
+ family: id,
+ runner,
+ models_source: runner === "claude-cli" ? ("curated" as const) : ("live" as const),
+ curated_models: [],
+ default_model: "",
+ keyless: false,
+ native_resume: false,
+ effort_levels: ["low", "high"],
+ default_effort: "high",
+ permission_modes: [{ id: "ask", label: "Ask before acting", description: "" }],
+ default_permission_mode: "ask",
+ cli_installed: runner === "claude-cli" ? true : null,
+ };
+}
+
+const CATALOG: AgentChatCatalog = {
+ default_cwd: "C:\work",
+ shell: "pwsh",
+ providers: [row("claude-api", "Anthropic Claude"), row("grok", "xAI Grok")],
+};
+
+function seed(health: Record<string, ProviderHealth>) {
+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });
+ useAgentChatStore.setState({
+ catalog: CATALOG,
+ connections: [
+ { jarvis: "claude-api", key_set: true, api_key_set: true, is_active_brain: true },
+ { jarvis: "grok", key_set: true, api_key_set: true, is_active_brain: false },
+ ],
+ catalogError: null,
+ backendOutdated: false,
+ liveModels: {},
+ health,
+ sessions: [],
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ draft: {
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ permissionMode: "ask",
+ buildMode: "ask",
+ cwd: "C:\work",
+ },
+ busy: false,
+ lastError: null,
+ loadCatalog: async () => {},
+ loadSessions: async () => {},
+ loadModels: async () => {},
+ loadHealth: async () => {},
+ } as never);
+}
+
+describe("the health dot in the provider picker", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 })));
+ });
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("marks a rejected key red and a working seat green, with the reason in words", async () => {
+ seed({
+ "claude-api": {
+ provider: "claude-api",
+ status: "error",
+ reason: "bad_key",
+ detail: "Claude (API-Key): 401 Unauthorized",
+ },
+ grok: { provider: "grok", status: "ok", reason: "ok", detail: "xAI Grok: ok" },
+ });
+ render(
+ <AgentChatStoreProvider store={useAgentChatStore}>
+ <AgentComposer />
+ </AgentChatStoreProvider>,
+ );
+ // The picked row's dot rides the closed pill too, so the state of the seat
+ // you are about to type on is visible without opening anything.
+ const onPill = screen.getByTestId("provider-health-claude-api");
+ expect(onPill.getAttribute("data-health")).toBe("error");
+
+ fireEvent.click(screen.getByTestId("composer-provider"));
+ await waitFor(() => expect(screen.getByTestId("provider-health-grok")).toBeTruthy());
+
+ const broken = screen.getAllByTestId("provider-health-claude-api");
+ expect(broken).toHaveLength(2); // the pill and the row
+ for (const dot of broken) {
+ expect(dot.getAttribute("data-health")).toBe("error");
+ expect(dot.className).toContain("bg-destructive");
+ // The provider's own words are the tooltip; the label is plain language.
+ expect(dot.getAttribute("title")).toContain("401");
+ expect(dot.getAttribute("aria-label")).toBe("Key rejected");
+ }
+
+ const working = screen.getByTestId("provider-health-grok");
+ expect(working.getAttribute("data-health")).toBe("ok");
+ expect(working.className).toContain("bg-emerald-500");
+ });
+
+ it("draws no dot at all before the sweep lands", async () => {
+ seed({});
+ render(
+ <AgentChatStoreProvider store={useAgentChatStore}>
+ <AgentComposer />
+ </AgentChatStoreProvider>,
+ );
+ fireEvent.click(screen.getByTestId("composer-provider"));
+ await waitFor(() => expect(screen.getByRole("listbox")).toBeTruthy());
+ expect(screen.queryByTestId("provider-health-claude-api")).toBeNull();
+ expect(screen.queryByTestId("provider-health-grok")).toBeNull();
+ });
+
+ it("keeps a broken row selectable — a rate limit passes, a refused click does not", async () => {
+ seed({
+ "claude-api": {
+ provider: "claude-api",
+ status: "error",
+ reason: "no_credits",
+ detail: "402",
+ },
+ });
+ render(
+ <AgentChatStoreProvider store={useAgentChatStore}>
+ <AgentComposer />
+ </AgentChatStoreProvider>,
+ );
+ fireEvent.click(screen.getByTestId("composer-provider"));
+ const option = await screen.findByRole("option", { name: /Anthropic Claude/ });
+ expect(option.getAttribute("aria-disabled")).not.toBe("true");
+ });
+
+ it("does not paint Key rejected on a coding CLI even if the sweep leaked a bad key", async () => {
+ // The dual Claude row keeps id `claude-api` when Claude Code answers. A
+ // backend that still probed the Anthropic key would send bad_key; the
+ // picker must not show that on a CLI seat.
+ const catalog: AgentChatCatalog = {
+ default_cwd: "C:\\work",
+ shell: "pwsh",
+ providers: [row("claude-api", "Anthropic Claude", "claude-cli"), row("grok", "xAI Grok")],
+ };
+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });
+ useAgentChatStore.setState({
+ catalog,
+ connections: [
+ {
+ jarvis: "claude-api",
+ key_set: true,
+ api_key_set: false,
+ oauth_connected: true,
+ is_active_brain: false,
+ },
+ { jarvis: "grok", key_set: true, api_key_set: true, is_active_brain: false },
+ ],
+ catalogError: null,
+ backendOutdated: false,
+ liveModels: {},
+ health: {
+ "claude-api": {
+ provider: "claude-api",
+ status: "error",
+ reason: "bad_key",
+ detail: "Claude (API-Key): 401 Unauthorized",
+ },
+ },
+ sessions: [],
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ draft: {
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ permissionMode: "ask",
+ buildMode: "ask",
+ cwd: "C:\\work",
+ },
+ busy: false,
+ lastError: null,
+ loadCatalog: async () => {},
+ loadSessions: async () => {},
+ loadModels: async () => {},
+ loadHealth: async () => {},
+ } as never);
+ render(
+ <AgentChatStoreProvider store={useAgentChatStore}>
+ <AgentComposer />
+ </AgentChatStoreProvider>,
+ );
+ expect(screen.queryByTestId("provider-health-claude-api")).toBeNull();
+ expect(screen.queryByText("Key rejected")).toBeNull();
+ fireEvent.click(screen.getByTestId("composer-provider"));
+ await waitFor(() => expect(screen.getByRole("listbox")).toBeTruthy());
+ expect(screen.queryByText("Key rejected")).toBeNull();
+ expect(screen.queryByTestId("provider-health-claude-api")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 201b7ba2c0..1ffcdb1e5a 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -96,6 +96,22 @@ export function isApiRunner(runner: string): boolean {
return runner === "api" || runner === "brain";
}
+/**
+ * One provider row's LIVE state, from `GET /api/agent-chat/provider-health`.
+ * `status` mirrors jarvis/brain/section_health.py — the same vocabulary the
+ * API-Keys tab dots use, so the two screens cannot disagree.
+ */
+export type ProviderHealthStatus = "ok" | "needs_setup" | "error" | "unknown";
+
+export interface ProviderHealth {
+ provider: string;
+ status: ProviderHealthStatus;
+ /** "bad_key" | "no_credits" | "timeout" | … — turned into a sentence by the UI. */
+ reason: string;
+ /** The provider's own words, for the tooltip. */
+ detail: string;
+}
+
export interface AgentConnectionRow {
jarvis: string;
label?: string;
@@ -135,6 +151,23 @@ export async function fetchAgentChatCatalog(surface?: AgentChatSurface): Promise
return json(await fetch(`/api/agent-chat/catalog${query}`), "catalog-failed");
}
+/**
+ * Which seats actually answer. Slow by nature — it makes one real request per
+ * provider — so callers fire it beside the catalog and never await it before
+ * painting. The backend caches a sweep for five minutes.
+ */
+export async function fetchProviderHealth(
+ surface: AgentChatSurface,
+ refresh = false,
+): Promise<ProviderHealth[]> {
+ const q = `surface=${encodeURIComponent(surface)}${refresh ? "&refresh=true" : ""}`;
+ const data = await json<{ providers?: ProviderHealth[] }>(
+ await fetch(`/api/agent-chat/provider-health?${q}`),
+ "provider-health-failed",
+ );
+ return Array.isArray(data.providers) ? data.providers : [];
+}
+
export async function fetchAgentConnections(): Promise<AgentConnectionRow[]> {
const data = await json<{ mapping?: AgentConnectionRow[] }>(
await fetch("/api/jarvis-agent/status"),
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index e238db8808..c63b58ac59 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -8,6 +8,7 @@ import {
fetchAgentChatCatalog,
fetchAgentChatSessions,
fetchAgentConnections,
+ fetchProviderHealth,
fetchProviderModels,
isApiRunner,
patchAgentChatSession,
@@ -23,6 +24,7 @@ import {
type ChatAttachment,
type CuratedModel,
type PatchSessionInput,
+ type ProviderHealth,
} from "@/lib/agentChatApi";
import { EMPTY_TIMELINE, reduceEvent, reduceEvents, type Timeline } from "@/components/agentchat/reduce";
@@ -100,6 +102,8 @@ export interface AgentChatStore {
backendOutdated: boolean;
/** Live model lists per provider id (the API-backed rows). */
liveModels: Record<string, CuratedModel[]>;
+ /** Live per-provider state, keyed by provider id; empty until the sweep lands. */
+ health: Record<string, ProviderHealth>;
sessions: AgentChatSession[];
activeSessionId: string | null;
activeSession: AgentChatSession | null;
@@ -113,6 +117,8 @@ export interface AgentChatStore {
loadSessions: () => Promise<void>;
loadModels: (providerId: string) => Promise<void>;
providerOptions: () => ProviderOption[];
+ /** Ask which seats actually answer. Never awaited by a render path. */
+ loadHealth: (refresh?: boolean) => Promise<void>;
providerById: (id: string) => ProviderOption | null;
setDraft: (patch: Partial<ComposerDraft>) => Promise<void>;
setPlan: (on: boolean) => Promise<void>;
@@ -281,6 +287,7 @@ export function createAgentChatStore(surface: AgentChatSurface) {
catalogError: null,
backendOutdated: false,
liveModels: {},
+ health: {},
sessions: [],
activeSessionId: null,
activeSession: null,
@@ -317,6 +324,10 @@ export function createAgentChatStore(surface: AgentChatSurface) {
})),
};
set({ catalog, connections, catalogError: null, backendOutdated });
+ // Deliberately not awaited: the sweep makes one real request per
+ // provider and can take seconds. The composer paints from the
+ // catalog now and the dots appear when the answers arrive.
+ void get().loadHealth();
// Settle the draft: an empty or unknown provider becomes the active
// sub-agent (else the first connected one); blank picks take the
// provider's defaults.
@@ -394,6 +405,19 @@ export function createAgentChatStore(surface: AgentChatSurface) {
}
},
+ loadHealth: async (refresh = false) => {
+ try {
+ const rows = await fetchProviderHealth(surface, refresh);
+ const health: Record<string, ProviderHealth> = {};
+ for (const row of rows) health[row.provider] = row;
+ set({ health });
+ } catch {
+ // A backend too old to know the route, or a sweep that failed: the
+ // composer simply shows no live state, which is what it did before.
+ // Never an error banner — nothing the person did went wrong.
+ }
+ },
+
providerOptions: () => {
const { catalog, connections } = get();
if (!catalog) return [];
diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.py
index 07d2576fea..f86316d2ac 100644
--- a/tests/unit/agent_chat/test_agent_chat_service.py
+++ b/tests/unit/agent_chat/test_agent_chat_service.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
import pytest
@@ -12,6 +13,7 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from jarvis.agent_chat import runner_api
+from jarvis.agent_chat.catalog import rows_for
from jarvis.agent_chat.service import AgentChatService, SessionBusy
from jarvis.agent_chat.store import AgentChatStore
from jarvis.core.protocols import BrainDelta, BrainRequest
@@ -30,7 +32,9 @@ class ScriptedBrain:
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
self.requests.append(req)
ScriptedBrain.seen.append(req)
- step = ScriptedBrain.script.pop(0) if ScriptedBrain.script else [BrainDelta(content="(done)")]
+ step = (
+ ScriptedBrain.script.pop(0) if ScriptedBrain.script else [BrainDelta(content="(done)")]
+ )
for d in step:
await asyncio.sleep(0)
yield d
@@ -42,7 +46,11 @@ class ScriptedBrain:
def scripted(monkeypatch: pytest.MonkeyPatch):
ScriptedBrain.script = []
ScriptedBrain.seen = []
- monkeypatch.setitem(runner_api.BRAIN_BY_PROVIDER, "fakeprov", ("tests.unit.agent_chat.test_agent_chat_service", "ScriptedBrain"))
+ monkeypatch.setitem(
+ runner_api.BRAIN_BY_PROVIDER,
+ "fakeprov",
+ ("tests.unit.agent_chat.test_agent_chat_service", "ScriptedBrain"),
+ )
# Catalog has no row for fakeprov; supports_api_runner() still says yes.
return ScriptedBrain
@@ -54,7 +62,9 @@ async def _drain(q: asyncio.Queue, until_kind: str, timeout: float = 5.0) -> lis
while True:
remaining = deadline - loop.time()
if remaining <= 0:
- raise AssertionError(f"timed out waiting for {until_kind}; got {[e['kind'] for e in out]}")
+ raise AssertionError(
+ f"timed out waiting for {until_kind}; got {[e['kind'] for e in out]}"
+ )
ev = await asyncio.wait_for(q.get(), timeout=remaining)
out.append(ev)
if ev["kind"] == until_kind:
@@ -81,7 +91,9 @@ def test_turn_streams_text_runs_a_tool_and_asks_for_approval(tmp_path: Path, scr
async def scenario() -> None:
store = AgentChatStore(":memory:")
svc = AgentChatService(store, assistant_name=lambda: "Testo")
- session = svc.create_session(provider="fakeprov", model="m", effort="high", cwd=str(tmp_path))
+ session = svc.create_session(
+ provider="fakeprov", model="m", effort="high", cwd=str(tmp_path)
+ )
q = svc.subscribe(session.session_id)
turn_id = await svc.send(session.session_id, "please write hello.txt")
with pytest.raises(SessionBusy):
@@ -151,7 +163,11 @@ def test_deny_feeds_a_denied_result_and_allow_always_flips_the_mode(tmp_path: Pa
def test_cancel_ends_the_turn(tmp_path: Path, scripted):
ScriptedBrain.script = [
- [BrainDelta(tool_call={"id": "c1", "name": "Write", "input": {"file_path": "a", "content": "b"}})],
+ [
+ BrainDelta(
+ tool_call={"id": "c1", "name": "Write", "input": {"file_path": "a", "content": "b"}}
+ )
+ ],
]
async def scenario() -> None:
@@ -180,7 +196,7 @@ def test_provider_error_is_reported_not_raised(tmp_path: Path, monkeypatch: pyte
monkeypatch.setitem(runner_api.BRAIN_BY_PROVIDER, "boomprov", (__name__, "Boom"))
import sys
- setattr(sys.modules[__name__], "Boom", Boom)
+ sys.modules[__name__].Boom = Boom
async def scenario() -> None:
svc = AgentChatService(AgentChatStore(":memory:"))
@@ -207,6 +223,180 @@ def _app(tmp_path: Path) -> FastAPI:
return app
+def test_provider_health_reports_each_row_and_caches_the_sweep(tmp_path: Path, monkeypatch):
+ """The picker's live state: which connected seats actually answer.
+
+ The sweep costs one real request per provider, so it must be cached and
+ must never lose the whole answer to one slow or raising provider.
+ """
+ import jarvis.ui.web.agent_chat_routes as routes
+
+ calls: list[str] = []
+
+ async def _fake(cfg, provider_id, *, probe=True):
+ calls.append(provider_id)
+ table = {
+ "claude-api": ("error", "bad_key", "Claude (API-Key): 401"),
+ "openrouter": ("error", "no_credits", "OpenRouter: 402"),
+ "grok": ("ok", "ok", "xAI Grok: ok"),
+ "nvidia": ("needs_setup", "not_configured", "NVIDIA NIM: not connected"),
+ }
+ if provider_id == "gemini":
+ raise RuntimeError("boom") # one bad row must not lose the sweep
+ status, reason, detail = table.get(provider_id, ("ok", "ok", f"{provider_id}: ok"))
+ return SimpleNamespace(status=status, reason=reason, detail=detail)
+
+ monkeypatch.setattr("jarvis.ui.web.provider_routes.provider_health", _fake, raising=False)
+ monkeypatch.setattr(routes, "_health_cache", {})
+
+ with TestClient(_app(tmp_path)) as client:
+ body = client.get("/api/agent-chat/provider-health?surface=jarvis").json()
+ rows = {r["provider"]: r for r in body["providers"]}
+ assert body["cached"] is False
+ # Every row of the surface is reported, none dropped.
+ assert set(rows) == {p.id for p in rows_for("jarvis")}
+ assert rows["claude-api"]["status"] == "error"
+ assert rows["claude-api"]["reason"] == "bad_key"
+ assert rows["openrouter"]["reason"] == "no_credits"
+ assert rows["grok"]["status"] == "ok"
+ assert rows["nvidia"]["status"] == "needs_setup"
+ # The raiser is "unknown" — never an error the person did, and never a
+ # 500 that would cost the other eight answers.
+ assert rows["gemini"]["status"] == "unknown"
+ assert rows["gemini"]["reason"] == "check_failed"
+
+ # Second call is served from the sweep, not from nine more requests.
+ swept = len(calls)
+ again = client.get("/api/agent-chat/provider-health?surface=jarvis").json()
+ assert again["cached"] is True and len(calls) == swept
+ # …unless the caller asks for a fresh one.
+ client.get("/api/agent-chat/provider-health?surface=jarvis&refresh=true")
+ assert len(calls) > swept
+
+
+class _CliStatus:
+ def __init__(self, connected: bool, mode: str, message: str = "") -> None:
+ self.connected = connected
+ self.mode = mode
+ self.message = message
+
+
+def test_cli_login_snapshot_ignores_a_stored_api_key_for_claude(monkeypatch):
+ """Claude Code spends the subscription. A stored Anthropic key is a
+ different seat — counting it as signed-in is how "Key rejected" landed
+ on the CLI row in the IDE picker.
+ """
+ import jarvis.ui.web.agent_chat_routes as routes
+
+ class _Svc:
+ def status(self) -> _CliStatus:
+ return _CliStatus(True, "api_key", "Connected via Anthropic API key.")
+
+ monkeypatch.setattr("jarvis.claude_auth.ClaudeAuthService", _Svc)
+ status, reason, detail = routes._cli_login_snapshot("claude-cli")
+ assert status == "needs_setup"
+ assert reason == "not_configured"
+ assert "API key" in detail
+
+
+def test_cli_login_snapshot_treats_a_claude_subscription_as_ok(monkeypatch):
+ import jarvis.ui.web.agent_chat_routes as routes
+
+ class _Svc:
+ def status(self) -> _CliStatus:
+ return _CliStatus(True, "subscription", "Connected via Claude Max ([email protected]).")
+
+ monkeypatch.setattr("jarvis.claude_auth.ClaudeAuthService", _Svc)
+ status, reason, detail = routes._cli_login_snapshot("claude-cli")
+ assert status == reason == "ok"
+ assert "Claude Max" in detail
+
+
+def test_cli_login_snapshot_codex_and_antigravity_use_the_cli_login(monkeypatch):
+ import jarvis.ui.web.agent_chat_routes as routes
+
+ class _Codex:
+ def status(self) -> _CliStatus:
+ return _CliStatus(True, "chatgpt", "Connected via ChatGPT.")
+
+ class _AgyOff:
+ def status(self) -> _CliStatus:
+ return _CliStatus(True, "api_key", "Connected via Gemini API key.")
+
+ monkeypatch.setattr("jarvis.codex_auth.CodexAuthService", _Codex)
+ monkeypatch.setattr("jarvis.google_cli.auth_service.GoogleCliAuthService", _AgyOff)
+ assert routes._cli_login_snapshot("codex-cli")[0] == "ok"
+ # A Gemini key is the other picker row, not the Antigravity CLI.
+ status, reason, _ = routes._cli_login_snapshot("agy-cli")
+ assert status == "needs_setup"
+ assert reason == "not_configured"
+
+
+def test_agent_surface_cli_health_does_not_probe_the_api_key(tmp_path: Path, monkeypatch):
+ """The IDE picker lists Claude Code under Coding CLIs.
+
+ Its catalog id is still ``claude-api``, so the API-Keys one-token probe
+ would report a revoked Anthropic key as "Key rejected" on that CLI row.
+ The sweep must ask the CLI login instead, and never call the key probe
+ for a CLI-resolved seat.
+ """
+ import jarvis.ui.web.agent_chat_routes as routes
+
+ api_calls: list[str] = []
+
+ async def _fake_api(cfg, provider_id, *, probe=True):
+ api_calls.append(provider_id)
+ return SimpleNamespace(status="error", reason="bad_key", detail=f"{provider_id}: 401")
+
+ monkeypatch.setattr("jarvis.ui.web.provider_routes.provider_health", _fake_api, raising=False)
+ monkeypatch.setattr(
+ routes,
+ "_cli_login_snapshot",
+ lambda runner: ("ok", "ok", f"{runner}: signed in"),
+ )
+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: True)
+ monkeypatch.setattr(routes, "_health_cache", {})
+
+ with TestClient(_app(tmp_path)) as client:
+ body = client.get("/api/agent-chat/provider-health?surface=agent").json()
+ rows = {r["provider"]: r for r in body["providers"]}
+ assert rows["claude-api"]["status"] == "ok"
+ assert rows["claude-api"]["reason"] == "ok"
+ assert "Key rejected" not in rows["claude-api"]["detail"]
+ assert "claude-api" not in api_calls
+ assert "openai-codex" not in api_calls
+ assert "antigravity" not in api_calls
+ # API-key rows on the same surface still use the key probe.
+ assert "openai" in api_calls
+ assert rows["openai"]["reason"] == "bad_key"
+
+
+def test_jarvis_surface_still_probes_the_claude_api_key(tmp_path: Path, monkeypatch):
+ """The front page has no CLI seats: Claude there is the Anthropic key."""
+ import jarvis.ui.web.agent_chat_routes as routes
+
+ api_calls: list[str] = []
+
+ async def _fake_api(cfg, provider_id, *, probe=True):
+ api_calls.append(provider_id)
+ return SimpleNamespace(status="error", reason="bad_key", detail="401")
+
+ monkeypatch.setattr("jarvis.ui.web.provider_routes.provider_health", _fake_api, raising=False)
+ monkeypatch.setattr(
+ routes,
+ "_cli_login_snapshot",
+ lambda runner: pytest.fail(f"CLI login checked on jarvis surface: {runner}"),
+ )
+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: True)
+ monkeypatch.setattr(routes, "_health_cache", {})
+
+ with TestClient(_app(tmp_path)) as client:
+ body = client.get("/api/agent-chat/provider-health?surface=jarvis").json()
+ rows = {r["provider"]: r for r in body["providers"]}
+ assert "claude-api" in api_calls
+ assert rows["claude-api"]["reason"] == "bad_key"
+
+
def test_the_jarvis_catalog_is_api_seats_only(tmp_path: Path):
"""What the front page's composer is handed: endpoints behind a key.
@@ -226,9 +416,8 @@ def test_the_jarvis_catalog_is_api_seats_only(tmp_path: Path):
assert all(p["cli_installed"] is None for p in rows.values())
# The IDE's chat is untouched: its CLI rows are still there.
- agent_rows = {
- p["id"]: p for p in client.get("/api/agent-chat/catalog?surface=agent").json()["providers"]
- }
+ agent_catalog = client.get("/api/agent-chat/catalog?surface=agent").json()
+ agent_rows = {p["id"]: p for p in agent_catalog["providers"]}
assert {"openai-codex", "antigravity", "grok-build"} <= set(agent_rows)
# And a CLI seat cannot be talked onto the front page by hand.
@@ -273,10 +462,14 @@ def _exercise_routes(client: TestClient, tmp_path: Path) -> None:
sid = created.json()["session_id"]
assert created.json()["cwd"] == str(tmp_path)
- bad = client.post("/api/agent-chat/sessions", json={"provider": "fakeprov", "cwd": "/no/such/dir"})
+ bad = client.post(
+ "/api/agent-chat/sessions", json={"provider": "fakeprov", "cwd": "/no/such/dir"}
+ )
assert bad.status_code == 400
- patched = client.patch(f"/api/agent-chat/sessions/{sid}", json={"title": "My chat", "effort": "low"})
+ patched = client.patch(
+ f"/api/agent-chat/sessions/{sid}", json={"title": "My chat", "effort": "low"}
+ )
assert patched.json()["title"] == "My chat" and patched.json()["effort"] == "low"
with client.websocket_connect(f"/api/agent-chat/sessions/{sid}/ws") as ws: