Skip to content

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

feat(providers): per-provider credential help, billing badge, key-format hints

Ruben Lütke22e2e9db9ef4
diff --git a/jarvis/ui/web/frontend/src/components/AltCredentialNote.test.tsx b/jarvis/ui/web/frontend/src/components/AltCredentialNote.test.tsx
new file mode 100644
index 0000000000..9abc009106
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/AltCredentialNote.test.tsx
@@ -0,0 +1,30 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+
+import { AltCredentialNote } from "@/components/AltCredentialNote";
+import type { AltCredential } from "@/hooks/useProviders";
+
+afterEach(cleanup);
+
+const VERTEX: AltCredential = {
+ label: "Vertex AI (service account)",
+ billing: "api",
+ credential_help:
+ "Bill Gemini through a Google Cloud Vertex AI project instead of an AI Studio key.",
+ dashboard_url: "https://console.cloud.google.com/iam-admin/serviceaccounts",
+ credential_path_hint: "~/.config/jarvis/vertex-sa.json",
+};
+
+describe("AltCredentialNote", () => {
+ it("shows the alternative path's label and help", () => {
+ render(<AltCredentialNote alt={VERTEX} />);
+ expect(screen.getByText(/Alternative: Vertex AI/i)).toBeTruthy();
+ expect(screen.getByText(/instead of an AI Studio key/i)).toBeTruthy();
+ });
+
+ it("links to the alternative dashboard", () => {
+ render(<AltCredentialNote alt={VERTEX} />);
+ const link = screen.getByRole("link") as HTMLAnchorElement;
+ expect(link.href).toContain("cloud.google.com");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/AltCredentialNote.tsx b/jarvis/ui/web/frontend/src/components/AltCredentialNote.tsx
new file mode 100644
index 0000000000..030dd1ec81
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/AltCredentialNote.tsx
@@ -0,0 +1,39 @@
+import { ExternalLink, GitFork } from "lucide-react";
+import type { AltCredential } from "@/hooks/useProviders";
+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
+
+/**
+ * Renders a provider's ALTERNATIVE credential path. Gemini's AI-Studio-vs-Vertex
+ * split is the only one today: the primary key form sits above, and this note
+ * makes the Vertex route — a separate Google Cloud billing project — explicit
+ * so a user does not top up one account while Jarvis bills the other.
+ */
+export function AltCredentialNote({ alt }: { alt: AltCredential }) {
+ return (
+ <div className="rounded-md border border-dashed border-border bg-muted/20 p-2.5">
+ <div className="mb-1 flex items-center gap-1.5">
+ <GitFork className="h-3 w-3 text-muted-foreground" />
+ <span className="text-[11px] font-medium text-foreground">
+ Alternative: {alt.label}
+ </span>
+ <ProviderBillingBadge billing={alt.billing} />
+ </div>
+ <p className="text-[11px] leading-relaxed text-muted-foreground">{alt.credential_help}</p>
+ {alt.credential_path_hint && (
+ <p className="mt-1 font-mono text-[10px] text-muted-foreground/80">
+ {alt.credential_path_hint}
+ </p>
+ )}
+ {alt.dashboard_url && (
+ <a
+ href={alt.dashboard_url}
+ target="_blank"
+ rel="noreferrer"
+ className="mt-1 inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary"
+ >
+ <ExternalLink className="h-3 w-3" /> Set up {alt.label}
+ </a>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsx
new file mode 100644
index 0000000000..984ccff0f1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsx
@@ -0,0 +1,80 @@
+/**
+ * Component tests for ApiKeyForm's new help text + live key-format hint.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+
+import { ApiKeyForm } from "@/components/ApiKeyForm";
+
+afterEach(cleanup);
+
+describe("ApiKeyForm credential help", () => {
+ it("renders the plain-English credential help text", () => {
+ render(
+ <ApiKeyForm
+ secretKey="anthropic_api_key"
+ dashboardUrl="https://console.anthropic.com/settings/keys"
+ configured={false}
+ credentialHelp="Anthropic API key (starts with sk-ant-). Billed per token."
+ />,
+ );
+ expect(screen.getByText(/starts with sk-ant-/i)).toBeTruthy();
+ });
+});
+
+describe("ApiKeyForm 'get your key' link", () => {
+ it("links to the official dashboard while entering a key", () => {
+ render(
+ <ApiKeyForm
+ secretKey="anthropic_api_key"
+ dashboardUrl="https://console.anthropic.com/settings/keys"
+ configured={false}
+ />,
+ );
+ const link = screen.getByRole("link") as HTMLAnchorElement;
+ expect(link.href).toContain("console.anthropic.com");
+ });
+
+ it("keeps the dashboard link visible even when a key is already configured", () => {
+ render(
+ <ApiKeyForm
+ secretKey="anthropic_api_key"
+ dashboardUrl="https://console.anthropic.com/settings/keys"
+ configured={true}
+ />,
+ );
+ const link = screen.getByRole("link") as HTMLAnchorElement;
+ expect(link.href).toContain("console.anthropic.com");
+ });
+});
+
+describe("ApiKeyForm live key-format hint", () => {
+ it("warns when an Anthropic key is pasted into the OpenAI field", () => {
+ render(
+ <ApiKeyForm secretKey="openai_api_key" dashboardUrl={null} configured={false} />,
+ );
+ const input = screen.getByPlaceholderText(/openai_api_key/i);
+ fireEvent.change(input, { target: { value: "sk-ant-api03-wrong" } });
+ expect(screen.getByText(/anthropic/i)).toBeTruthy();
+ });
+
+ it("flags a Vertex service-account JSON in the AI-Studio Gemini field", () => {
+ render(
+ <ApiKeyForm secretKey="gemini_api_key" dashboardUrl={null} configured={false} />,
+ );
+ const input = screen.getByPlaceholderText(/gemini_api_key/i);
+ fireEvent.change(input, {
+ target: { value: '{"type":"service_account","project_id":"x"}' },
+ });
+ expect(screen.getByText(/vertex/i)).toBeTruthy();
+ });
+
+ it("does not warn for a correctly-formatted key", () => {
+ render(
+ <ApiKeyForm secretKey="openai_api_key" dashboardUrl={null} configured={false} />,
+ );
+ const input = screen.getByPlaceholderText(/openai_api_key/i);
+ fireEvent.change(input, { target: { value: "sk-proj-correct123" } });
+ expect(screen.queryByText(/expects a different key/i)).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx
index 4f4eb45013..5ee0230661 100644
--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx
+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx
@@ -1,7 +1,8 @@
import { useState } from "react";
-import { Eye, EyeOff, ExternalLink, Trash2 } from "lucide-react";
+import { AlertTriangle, Eye, EyeOff, ExternalLink, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { deleteSecret, postSecret } from "@/hooks/useProviders";
+import { keyMatchesSecret } from "@/lib/keyFormat";
import { useEventStore } from "@/store/events";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
@@ -10,6 +11,11 @@ interface ApiKeyFormProps {
secretKey: string;
dashboardUrl: string | null;
configured: boolean;
+ /**
+ * Plain-English "which key, and what for" shown above the input. Optional so
+ * existing call sites keep working; the provider catalog supplies it.
+ */
+ credentialHelp?: string | null;
onChanged?: () => void;
/**
* Wird aufgerufen, nachdem ein Key erfolgreich gespeichert wurde.
@@ -24,7 +30,7 @@ interface ApiKeyFormProps {
* vorhandenem Wert. Schreibt direkt nach POST /api/secrets/{key}; der Wert
* verlässt nach dem Submit das Frontend nie wieder (Read-Only-Flag im Backend).
*/
-export function ApiKeyForm({ secretKey, dashboardUrl, configured, onChanged, onSavedActivate }: ApiKeyFormProps) {
+export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp, onChanged, onSavedActivate }: ApiKeyFormProps) {
const t = useT();
const [value, setValue] = useState("");
const [pending, setPending] = useState(false);
@@ -32,6 +38,11 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, onChanged, onS
const [editing, setEditing] = useState(!configured);
const pushToast = useEventStore((s) => s.pushToast);
+ // Live, client-side format recognition — the entered value never leaves the
+ // browser to be classified (the 2026-06-22 AI-Studio-vs-Vertex mix-up). Only
+ // hints; never blocks the save.
+ const fmt = value.trim() ? keyMatchesSecret(secretKey, value) : null;
+
async function handleSave() {
const trimmed = value.trim();
if (!trimmed) return;
@@ -64,37 +75,57 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, onChanged, onS
}
}
+ // The "get your key" link to the provider's official dashboard. Shown in
+ // BOTH states \u2014 while entering a key AND once it's saved \u2014 so the official
+ // source is always one click away (rotating a key, checking quota, etc.).
+ const dashboardLink = dashboardUrl ? (
+ <a
+ href={dashboardUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary"
+ >
+ <ExternalLink className="h-3 w-3" /> Get your key here
+ </a>
+ ) : null;
+
if (configured && !editing) {
return (
- <div className="flex items-center gap-2">
- <code className="flex-1 truncate rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs text-muted-foreground">
- {"\u2022".repeat(20)}
- </code>
- <Button size="sm" variant="ghost" onClick={() => setEditing(true)}>
- Ersetzen
- </Button>
- <Button
- size="sm"
- variant="ghost"
- onClick={handleDelete}
- disabled={pending}
- className="text-destructive hover:text-destructive"
- >
- <Trash2 className="h-3.5 w-3.5" />
- </Button>
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <code className="flex-1 truncate rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs text-muted-foreground">
+ {"\u2022".repeat(20)}
+ </code>
+ <Button size="sm" variant="ghost" onClick={() => setEditing(true)}>
+ Replace
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={handleDelete}
+ disabled={pending}
+ className="text-destructive hover:text-destructive"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ {dashboardLink}
</div>
);
}
return (
<div className="space-y-2">
+ {credentialHelp && (
+ <p className="text-[11px] leading-relaxed text-muted-foreground">{credentialHelp}</p>
+ )}
<div className="flex gap-2">
<div className="relative flex-1">
<input
type={reveal ? "text" : "password"}
value={value}
onChange={(e) => setValue(e.target.value)}
- placeholder={`${secretKey} eingeben…`}
+ placeholder={`Enter ${secretKey}…`}
className={cn(
"w-full rounded-md border border-input bg-background px-3 py-1.5 pr-9 font-mono text-xs",
"focus:outline-none focus:ring-1 focus:ring-primary",
@@ -113,24 +144,26 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, onChanged, onS
</button>
</div>
<Button size="sm" onClick={handleSave} disabled={pending || !value.trim()}>
- {pending ? "…" : "Speichern"}
+ {pending ? "…" : "Save"}
</Button>
{configured && (
<Button size="sm" variant="ghost" onClick={() => setEditing(false)}>
- Abbrechen
+ Cancel
</Button>
)}
</div>
- {dashboardUrl && (
- <a
- href={dashboardUrl}
- target="_blank"
- rel="noreferrer"
- className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary"
- >
- <ExternalLink className="h-3 w-3" /> Open dashboard — generate key there
- </a>
+ {fmt && !fmt.match && fmt.detected && (
+ <p className="flex items-start gap-1 text-[11px] text-amber-500">
+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />
+ <span>
+ This looks like a {fmt.detected.label} — this field expects a different key.
+ </span>
+ </p>
+ )}
+ {fmt && fmt.match && fmt.detected?.note && (
+ <p className="text-[11px] text-muted-foreground">{fmt.detected.note}</p>
)}
+ {dashboardLink}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsx b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsx
new file mode 100644
index 0000000000..f6a8b202a9
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsx
@@ -0,0 +1,28 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+
+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
+
+afterEach(cleanup);
+
+describe("ProviderBillingBadge", () => {
+ it("labels an API provider as pay-per-token", () => {
+ render(<ProviderBillingBadge billing="api" />);
+ expect(screen.getByText(/per token/i)).toBeTruthy();
+ });
+
+ it("labels a subscription provider", () => {
+ render(<ProviderBillingBadge billing="subscription" />);
+ expect(screen.getByText(/subscription/i)).toBeTruthy();
+ });
+
+ it("labels the dual codex path as subscription or API key", () => {
+ render(<ProviderBillingBadge billing="subscription_or_api" />);
+ expect(screen.getByText(/subscription or api/i)).toBeTruthy();
+ });
+
+ it("labels a local provider", () => {
+ render(<ProviderBillingBadge billing="local" />);
+ expect(screen.getByText(/local/i)).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsx b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsx
new file mode 100644
index 0000000000..2774881357
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsx
@@ -0,0 +1,49 @@
+import { CreditCard, Laptop, Sparkles } from "lucide-react";
+import type { Billing } from "@/hooks/useProviders";
+import { cn } from "@/lib/utils";
+
+/**
+ * A small badge that tells the user HOW a provider is billed — the
+ * API-key-vs-subscription distinction they asked for. Driven by the backend's
+ * `billing` field (derived from auth_mode), never by a provider name.
+ */
+const META: Record<Billing, { label: string; icon: typeof CreditCard; className: string }> = {
+ api: {
+ label: "API · billed per token",
+ icon: CreditCard,
+ className: "border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400",
+ },
+ subscription: {
+ label: "Subscription login",
+ icon: Sparkles,
+ className: "border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400",
+ },
+ subscription_or_api: {
+ label: "Subscription or API key",
+ icon: Sparkles,
+ className: "border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400",
+ },
+ local: {
+ label: "Local · no key needed",
+ icon: Laptop,
+ className: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
+ },
+};
+
+export function ProviderBillingBadge({ billing, className }: { billing: Billing; className?: string }) {
+ const meta = META[billing];
+ if (!meta) return null;
+ const Icon = meta.icon;
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium",
+ meta.className,
+ className,
+ )}
+ >
+ <Icon className="h-3 w-3" />
+ {meta.label}
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx
index 51ca5c7429..c630d8cfb2 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx
@@ -1,8 +1,11 @@
import { useState } from "react";
-import { Brain, Check, Mic, Volume2 } from "lucide-react";
+import { Brain, Check, KeyRound, Mic, Volume2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";
import { ApiKeyForm } from "@/components/ApiKeyForm";
+import { AltCredentialNote } from "@/components/AltCredentialNote";
+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
+import { SubagentSection } from "@/components/SubagentSection";
import {
useProviders,
switchBrainProvider,
@@ -13,14 +16,14 @@ import {
} from "@/hooks/useProviders";
import type { StepProps } from "../OnboardingFlow";
-// One provider class per internal page — Brain first, then Voice, then Hearing.
-// Kept as a SINGLE flow step (no backend ONBOARDING_STEPS / parity change); the
-// paging lives inside this component so users see one class at a time instead of
-// a wall of every provider at once.
+// The provider classes, in the same order as the main Settings → API Keys view
+// (Brain first, then Voice, then Hearing). Rendered as stacked sections inside
+// one scroll container so the user can scroll through every class at once —
+// mirroring the real API-Keys section — instead of paging one class at a time.
const TIERS: { tier: ProviderTier; label: string; icon: JSX.Element }[] = [
- { tier: "brain", label: "Brain — reasoning", icon: <Brain className="h-5 w-5" /> },
- { tier: "tts", label: "Voice — text to speech", icon: <Volume2 className="h-5 w-5" /> },
- { tier: "stt", label: "Hearing — speech to text", icon: <Mic className="h-5 w-5" /> },
+ { tier: "brain", label: "Brain — reasoning", icon: <Brain className="h-3.5 w-3.5" /> },
+ { tier: "tts", label: "Voice — text to speech", icon: <Volume2 className="h-3.5 w-3.5" /> },
+ { tier: "stt", label: "Hearing — speech to text", icon: <Mic className="h-3.5 w-3.5" /> },
];
// Activate (select) a provider by its tier — mirrors the main Settings API-Keys
@@ -33,47 +36,72 @@ const SWITCH: Record<ProviderTier, (id: string) => Promise<unknown>> = {
export function ApiKeysStep({ goNext, skip }: StepProps) {
const t = useT();
- const { providers, loading, error, refetch } = useProviders();
- const [ti, setTi] = useState(0);
- const cur = TIERS[ti];
- const list = providers.filter((p) => p.tier === cur.tier);
- const isLastTier = ti >= TIERS.length - 1;
-
- const next = () => (isLastTier ? goNext() : setTi((i) => i + 1));
+ const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
- {cur.icon}
+ <KeyRound className="h-5 w-5" />
</div>
<div className="min-w-0">
- <h2 className="font-display text-lg font-semibold">{cur.label}</h2>
- <p className="text-xs text-muted-foreground">
- {t("onboarding.api_keys.body")} · {ti + 1}/{TIERS.length}
- </p>
+ <h2 className="font-display text-lg font-semibold">
+ {t("onboarding.api_keys.title")}
+ </h2>
+ <p className="text-xs text-muted-foreground">{t("onboarding.api_keys.body")}</p>
</div>
</div>
- {cur.tier === "brain" && (
- <p className="flex items-center gap-1.5 rounded-md bg-emerald-500/10 px-3 py-2 text-xs text-emerald-600">
- <Check className="h-3.5 w-3.5 shrink-0" />
- {t("onboarding.api_keys.works_now")}
- </p>
- )}
+ <p className="flex items-center gap-1.5 rounded-md bg-emerald-500/10 px-3 py-2 text-xs text-emerald-600">
+ <Check className="h-3.5 w-3.5 shrink-0" />
+ {t("onboarding.api_keys.works_now")}
+ </p>
{loading && <p className="text-xs text-muted-foreground">…</p>}
{error && (
<p className="text-xs text-amber-500">{t("onboarding.api_keys.body")}</p>
)}
- <div className="flex flex-col gap-3">
- {list.map((p) => (
- <ProviderRow key={p.id} provider={p} onChanged={refetch} />
- ))}
+ {/* One scroll container holding every provider class in order, so the user
+ scrolls from Brain through Voice, Hearing and the Subagent section —
+ the same content as Settings → API Keys, fitted into the modal. The
+ max-height keeps the onboarding card inside the viewport; only this
+ list scrolls. Symmetric px-2/py-1 (compensated by -mx-2 so the content
+ stays flush with the modal) gives the active card's ring-1 highlight
+ room on every side — overflow-y-auto also clips horizontally, so
+ without left padding the ring was cut off on the left edge. */}
+ <div className="-mx-2 max-h-[52vh] space-y-6 overflow-y-auto scrollbar-jarvis px-2 py-1">
+ {TIERS.map((meta) => {
+ const list = providers.filter(
+ (p) => p.tier === meta.tier && p.brain_switchable !== false,
+ );
+ if (!list.length) return null;
+ return (
+ <section key={meta.tier}>
+ <h3 className="mb-2 inline-flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-foreground">
+ {meta.icon} {meta.label}
+ </h3>
+ <div className="flex flex-col gap-3">
+ {list.map((p) => (
+ <ProviderRow
+ key={p.id}
+ provider={p}
+ onChanged={refetch}
+ onActivateOptimistic={setActiveOptimistic}
+ />
+ ))}
+ </div>
+ </section>
+ );
+ })}
+
+ {/* Subagent (Heavy-Task worker) — own data source (/api/openclaw/status),
+ rendered as a sibling section so the onboarding key step matches the
+ full Settings → API Keys layout. */}
+ <SubagentSection />
</div>
- <Button className="w-full" onClick={next}>
+ <Button className="w-full" onClick={goNext}>
{t("onboarding.nav.next")}
</Button>
<button className="text-xs text-muted-foreground underline" onClick={skip}>
@@ -86,9 +114,11 @@ export function ApiKeysStep({ goNext, skip }: StepProps) {
function ProviderRow({
provider,
onChanged,
+ onActivateOptimistic,
}: {
provider: ProviderDescriptor;
onChanged: () => void;
+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;
}) {
const [busy, setBusy] = useState(false);
@@ -102,13 +132,18 @@ function ProviderRow({
async function activate() {
if (provider.active || !usable || busy) return;
+ // Flip the highlight immediately so the switch feels instant — the backend
+ // call below rebuilds the provider and can take a few seconds. The refetch
+ // afterwards confirms server truth; on failure it rolls the highlight back.
+ onActivateOptimistic(provider.tier, provider.id);
setBusy(true);
try {
await SWITCH[provider.tier](provider.id);
onChanged();
} catch {
- // Activation failed (e.g. backend rejected) — leave the list as-is;
- // the status chip keeps reflecting the unchanged active provider.
+ // Activation failed (e.g. backend rejected) — refetch to roll the
+ // optimistic highlight back to the true active provider.
+ onChanged();
} finally {
setBusy(false);
}
@@ -138,6 +173,7 @@ function ProviderRow({
</button>
<StatusChip configured={provider.configured} active={provider.active} />
</div>
+ <ProviderBillingBadge billing={provider.billing} />
{provider.auth_mode === "api_key" &&
provider.secret_keys.map((k) => (
<ApiKeyForm
@@ -145,9 +181,13 @@ function ProviderRow({
secretKey={k}
dashboardUrl={provider.dashboard_url}
configured={Boolean(provider.secrets_set[k])}
+ credentialHelp={provider.credential_help}
onChanged={onChanged}
/>
))}
+ {provider.auth_mode === "api_key" && provider.alt_credential && (
+ <AltCredentialNote alt={provider.alt_credential} />
+ )}
{provider.auth_mode === "codex" && (
<p className="text-xs text-muted-foreground">
Sign in with the official Codex / ChatGPT login from Settings → API Keys.
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 01c537d7a1..696c004274 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -1,7 +1,22 @@
import { useCallback, useEffect, useState } from "react";
-export type AuthMode = "api_key" | "codex" | "none";
+export type AuthMode = "api_key" | "codex" | "antigravity" | "none";
export type ProviderTier = "brain" | "tts" | "stt";
+/** How using a provider is billed — mirror of provider_spec.Billing. */
+export type Billing = "api" | "subscription" | "subscription_or_api" | "local";
+
+/**
+ * An alternative credential path for the same provider — mirror of
+ * provider_spec.AltCredential. Gemini's AI-Studio-vs-Vertex split is the only
+ * one today; `null` for single-path providers.
+ */
+export interface AltCredential {
+ label: string;
+ billing: Billing;
+ credential_help: string;
+ dashboard_url: string | null;
+ credential_path_hint: string | null;
+}
export interface ProviderDescriptor {
id: string;
@@ -16,15 +31,29 @@ export interface ProviderDescriptor {
credential_path_hint: string | null;
configured: boolean;
active: boolean;
+ brain_switchable?: boolean;
cli_installed: boolean | null;
+ /** Plain-English "which key / subscription, and what for". */
+ credential_help: string | null;
+ /** Where to sign up for the account/subscription (distinct from dashboard_url). */
+ signup_url: string | null;
+ /** How using this provider is billed. */
+ billing: Billing;
+ /** Gemini's Vertex alternative; null for single-path providers. */
+ alt_credential: AltCredential | null;
/**
- * Codex only: whether an OpenAI API key usable by the Codex *brain* is
- * configured (codex_openai_api_key / openai_api_key / OPENAI_API_KEY). The
- * ChatGPT login alone cannot back a chat brain, so the brain "activate" radio
- * is gated on this rather than on the OAuth connection.
+ * Codex only: legacy credential readiness kept in /api/providers for older
+ * UI consumers. The current UI does not render Codex as a switchable Brain;
+ * Codex is connected and selected from the Subagent section.
*/
codex_brain_ready?: boolean;
codex_status?: CodexStatus;
+ /**
+ * Antigravity only: the honest Google CLI login snapshot (mirror of
+ * `GoogleCliAuthStatus.to_dict()`). Drives the OAuth connect/disconnect widget
+ * in the Subagent section. It is not switchable as the main Brain provider.
+ */
+ antigravity_status?: AntigravityStatus;
}
export interface CodexStatus {
@@ -34,7 +63,29 @@ export interface CodexStatus {
message: string;
version?: string | null;
accountLabel?: string | null;
+ account_label?: string | null;
+ user_email?: string | null;
binaryPath?: string | null;
+ binary_path?: string | null;
+ error?: string | null;
+}
+
+/**
+ * Mirror of `jarvis/google_cli/auth_service.py::GoogleCliAuthStatus.to_dict()`.
+ * The Google-subscription sibling of `CodexStatus`: whether the official
+ * `agy`/`gemini` CLI is installed and signed in with Google, plus the account
+ * email so the connected card can show whose subscription is billed.
+ */
+export interface AntigravityStatus {
+ installed: boolean;
+ connected: boolean;
+ mode: string; // "oauth-personal" | "api_key" | "unknown"
+ cli_kind: string | null; // "agy" | "gemini"
+ message: string;
+ version: string | null;
+ user_email: string | null;
+ binary_path: string;
+ error: string | null;
}
interface ProvidersResponse {
@@ -66,6 +117,21 @@ export function useProviders() {
}
}, []);
+ /**
+ * Optimistically flip the active provider within a tier, in-memory, BEFORE
+ * the backend switch resolves. The `/api/{brain,tts,stt}/switch` calls can
+ * take a few seconds — a TTS switch rebuilds the provider client and injects
+ * it into the live pipeline — and the UI used to update only after that call
+ * AND a full `/api/providers` refetch, so the "active" highlight lagged for
+ * seconds. Callers flip the highlight here on click, then run the switch and
+ * `refetch()` to confirm; on failure a `refetch()` restores server truth.
+ */
+ const setActiveOptimistic = useCallback((tier: ProviderTier, id: string) => {
+ setProviders((prev) =>
+ prev.map((p) => (p.tier === tier ? { ...p, active: p.id === id } : p)),
+ );
+ }, []);
+
useEffect(() => {
void refetch();
const onSecret = () => void refetch();
@@ -84,7 +150,7 @@ export function useProviders() {
};
}, [refetch]);
- return { providers, loading, error, refetch };
+ return { providers, loading, error, refetch, setActiveOptimistic };
}
export async function postSecret(key: string, value: string): Promise<void> {
@@ -130,6 +196,34 @@ export async function codexLogout(): Promise<void> {
}
}
+/**
+ * Starts the interactive "Sign in with Google" flow by driving the official
+ * `agy`/`gemini` CLI as a subprocess (POST /api/antigravity/login). The Google
+ * sibling of `startCodexLogin` — a 409 means no Google CLI is installed (the
+ * detail carries an install_command).
+ */
+export async function loginAntigravity(): Promise<void> {
+ const res = await fetch("/api/antigravity/login", { method: "POST" });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const detail = body.detail;
+ throw new Error(
+ typeof detail === "object" && detail?.message
+ ? detail.message
+ : detail ?? `HTTP ${res.status}`,
+ );
+ }
+}
+
+/** Disconnects the Google login (POST /api/antigravity/logout). */
+export async function logoutAntigravity(): Promise<void> {
+ const res = await fetch("/api/antigravity/logout", { method: "POST" });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+}
+
export async function setCodexBinaryPath(binaryPath: string): Promise<void> {
const res = await fetch("/api/codex/binary-path", {
method: "POST",
@@ -294,3 +388,80 @@ export async function testProvider(providerId: string): Promise<ProviderTestResu
return body as ProviderTestResult;
}
+// ── Per-provider model picker ───────────────────────────────────────────────
+// The brain provider's model list comes from its OWN /v1/models catalog (or
+// OpenRouter's public catalog), so a freshly released model shows up without any
+// code change. `source` is honest: "live" (just fetched) / "cache" (served from
+// a still-fresh prior fetch) / "static" (offline fallback — show a hint).
+
+export interface BrainModel {
+ id: string;
+ label: string;
+}
+
+export interface BrainModelsResult {
+ provider: string;
+ current_model: string;
+ models: BrainModel[];
+ source: "live" | "cache" | "static" | "curated";
+ fetched_at: number;
+ // What the picker writes: "model" (brain/stt/cartesia) or "voice" (most TTS).
+ selects?: "model" | "voice";
+}
+
+/** Lists the available models for a brain provider for the picker dropdown. */
+export async function getBrainProviderModels(
+ providerId: string,
+ refresh = false,
+): Promise<BrainModelsResult> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/models${refresh ? "?refresh=true" : ""}`,
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as BrainModelsResult;
+}
+
+export interface BrainModelProbe {
+ status: ProviderTestStatus;
+ detail: string;
+ latency_ms: number;
+ integration_ok: boolean;
+}
+
+export interface BrainModelSaveResult {
+ ok: boolean;
+ provider: string;
+ model: string;
+ persisted: boolean;
+ applied_live: boolean;
+ restart_required: boolean;
+ // Only brain providers run a live probe; TTS/STT save without one (null).
+ probe: BrainModelProbe | null;
+}
+
+/**
+ * Pins a brain provider's model and verifies it with a REAL 1-token probe.
+ * Empty `model` resets the provider to its frontier default. The selection is
+ * saved regardless of the probe outcome; `probe.status` reports the truth
+ * (ok / bad_key / no_credits / model_unavailable / …).
+ */
+export async function saveBrainProviderModel(
+ providerId: string,
+ model: string,
+ persist = true,
+): Promise<BrainModelSaveResult> {
+ const res = await fetch(`/api/providers/${encodeURIComponent(providerId)}/model`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model, persist }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as BrainModelSaveResult;
+}
+
diff --git a/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts b/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts
new file mode 100644
index 0000000000..b3dfa565c5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest";
+import { detectKeyFormat, expectedKindForSecret, keyMatchesSecret } from "./keyFormat";
+
+describe("detectKeyFormat", () => {
+ it("returns null for blank input", () => {
+ expect(detectKeyFormat("")).toBeNull();
+ expect(detectKeyFormat(" ")).toBeNull();
+ });
+
+ it("recognizes Google AI Studio keys (AIza / AQ.)", () => {
+ expect(detectKeyFormat("AIzaSyABCDEF1234567890")?.kind).toBe("google-aistudio");
+ expect(detectKeyFormat("AQ.Ab8RN6...rest")?.kind).toBe("google-aistudio");
+ });
+
+ it("recognizes a Vertex AI service-account JSON, not an AI Studio key", () => {
+ const sa = '{ "type": "service_account", "project_id": "x" }';
+ expect(detectKeyFormat(sa)?.kind).toBe("vertex-service-account");
+ });
+
+ it("distinguishes the sk- prefixes (anthropic / openrouter / openai)", () => {
+ expect(detectKeyFormat("sk-ant-api03-xyz")?.kind).toBe("anthropic");
+ expect(detectKeyFormat("sk-or-v1-xyz")?.kind).toBe("openrouter");
+ expect(detectKeyFormat("sk-proj-abc123")?.kind).toBe("openai");
+ });
+
+ it("recognizes xAI, Cartesia and Groq keys", () => {
+ expect(detectKeyFormat("xai-abc123")?.kind).toBe("xai");
+ expect(detectKeyFormat("sk_car_abc123")?.kind).toBe("cartesia");
+ expect(detectKeyFormat("gsk_abc123")?.kind).toBe("groq");
+ });
+
+ it("falls back to unknown for an unrecognized format", () => {
+ expect(detectKeyFormat("hello-world")?.kind).toBe("unknown");
+ });
+});
+
+describe("expectedKindForSecret", () => {
+ it("maps secret slots to the key kind they expect", () => {
+ expect(expectedKindForSecret("gemini_api_key")).toBe("google-aistudio");
+ expect(expectedKindForSecret("anthropic_api_key")).toBe("anthropic");
+ expect(expectedKindForSecret("openai_api_key")).toBe("openai");
+ expect(expectedKindForSecret("codex_openai_api_key")).toBe("openai");
+ expect(expectedKindForSecret("grok_api_key")).toBe("xai");
+ });
+
+ it("returns null for slots without a known key format", () => {
+ expect(expectedKindForSecret("google_tts_credentials_path")).toBeNull();
+ });
+});
+
+describe("keyMatchesSecret", () => {
+ it("confirms a matching key", () => {
+ expect(keyMatchesSecret("gemini_api_key", "AIzaSy123").match).toBe(true);
+ });
+
+ it("flags a Vertex JSON pasted into the AI-Studio Gemini field", () => {
+ const r = keyMatchesSecret("gemini_api_key", '{"type":"service_account"}');
+ expect(r.match).toBe(false);
+ expect(r.detected?.kind).toBe("vertex-service-account");
+ });
+
+ it("flags an Anthropic key pasted into the OpenAI field", () => {
+ const r = keyMatchesSecret("openai_api_key", "sk-ant-api03-xyz");
+ expect(r.match).toBe(false);
+ expect(r.detected?.kind).toBe("anthropic");
+ });
+
+ it("stays neutral (match=true) when the slot has no known format", () => {
+ expect(keyMatchesSecret("google_tts_credentials_path", "/path/to.json").match).toBe(true);
+ });
+
+ it("stays neutral for blank input", () => {
+ expect(keyMatchesSecret("gemini_api_key", "").match).toBe(true);
+ expect(keyMatchesSecret("gemini_api_key", " ").detected).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/keyFormat.ts b/jarvis/ui/web/frontend/src/lib/keyFormat.ts
new file mode 100644
index 0000000000..6a52f92d06
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/keyFormat.ts
@@ -0,0 +1,118 @@
+/**
+ * Client-side API-key format recognition.
+ *
+ * Pure, no network: the entered key is NEVER sent to the backend just to
+ * classify it (latency + it keeps the secret on the client until the user
+ * deliberately saves). The motivating case is the 2026-06-22 forensic — a user
+ * topped up a Google AI Studio key while Jarvis was wired to a Vertex AI
+ * service account. Surfacing "this looks like an AI Studio key" / "this is a
+ * Vertex service-account JSON, not an AI Studio key" at type-time prevents that
+ * whole class of mix-up. It only ever HINTS; it never blocks a save.
+ */
+
+export type KeyFormatKind =
+ | "google-aistudio"
+ | "vertex-service-account"
+ | "anthropic"
+ | "openai"
+ | "openrouter"
+ | "xai"
+ | "cartesia"
+ | "groq"
+ | "unknown";
+
+export interface KeyFormatHint {
+ kind: KeyFormatKind;
+ /** Short human label, e.g. "Google AI Studio key". */
+ label: string;
+ /** Optional contextual note (e.g. the AI-Studio-vs-Vertex clarification). */
+ note?: string;
+}
+
+/**
+ * Best-effort classification of a pasted credential by its shape. Returns
+ * `null` for blank input. Prefix order matters: the more specific `sk-ant-` /
+ * `sk-or-` must be tested before the generic `sk-` (OpenAI).
+ */
+export function detectKeyFormat(value: string): KeyFormatHint | null {
+ const v = value.trim();
+ if (!v) return null;
+
+ // Vertex AI service account = a JSON blob with "type": "service_account".
+ if (v.startsWith("{") && /"type"\s*:\s*"service_account"/.test(v)) {
+ return {
+ kind: "vertex-service-account",
+ label: "Vertex AI service account",
+ note: "This is a Vertex AI service-account file, not an AI Studio key — it bills a separate Google Cloud project.",
+ };
+ }
+ if (/^sk-ant-/.test(v)) return { kind: "anthropic", label: "Anthropic API key" };
+ if (/^sk-or-/.test(v)) return { kind: "openrouter", label: "OpenRouter API key" };
+ if (/^sk_car_/.test(v)) return { kind: "cartesia", label: "Cartesia API key" };
+ if (/^gsk_/.test(v)) return { kind: "groq", label: "Groq API key" };
+ if (/^xai-/.test(v)) return { kind: "xai", label: "xAI (Grok) API key" };
+ if (/^AIza/.test(v) || /^AQ\./.test(v)) {
+ return {
+ kind: "google-aistudio",
+ label: "Google AI Studio key",
+ note: "Looks like a Google AI Studio key — Jarvis uses it directly (Vertex stays off).",
+ };
+ }
+ if (/^sk-/.test(v)) return { kind: "openai", label: "OpenAI API key" };
+ return { kind: "unknown", label: "Unrecognized key format" };
+}
+
+/**
+ * The key kind a given Credential-Manager slot expects, or `null` when the slot
+ * has no recognizable format (e.g. a file path, a generic token). Used to warn
+ * on a mismatch (an Anthropic key pasted into the OpenAI field).
+ */
+export function expectedKindForSecret(secretKey: string): KeyFormatKind | null {
+ switch (secretKey) {
+ case "gemini_api_key":
+ return "google-aistudio";
+ case "anthropic_api_key":
+ return "anthropic";
+ case "openai_api_key":
+ case "codex_openai_api_key":
+ return "openai";
+ case "openrouter_api_key":
+ return "openrouter";
+ case "grok_api_key":
+ return "xai";
+ case "cartesia_api_key":
+ return "cartesia";
+ case "groq_api_key":
+ return "groq";
+ default:
+ return null;
+ }
+}
+
+export interface KeyMatchResult {
+ /** False only when we recognize the key AND it's the wrong kind for the slot. */
+ match: boolean;
+ /** The detected format of the entered value (null for blank input). */
+ detected: KeyFormatHint | null;
+ /** The format the slot expects (null when the slot has no known format). */
+ expected: KeyFormatKind | null;
+}
+
+/**
+ * Compares an entered value against the format its slot expects. Stays neutral
+ * (`match: true`) for blank input, for slots without a known format, and for
+ * an unrecognized but possibly-valid key — it only reports `match: false` when
+ * the value is confidently a DIFFERENT known provider's key (the actionable
+ * mistake). Never blocks; the UI shows this as a soft warning.
+ */
+export function keyMatchesSecret(secretKey: string, value: string): KeyMatchResult {
+ const detected = detectKeyFormat(value);
+ const expected = expectedKindForSecret(secretKey);
+ if (!detected || expected === null) {
+ return { match: true, detected, expected };
+ }
+ if (detected.kind === "unknown") {
+ return { match: true, detected, expected };
+ }
+ return { match: detected.kind === expected, detected, expected };
+}
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 259993ed83..8ca7e395dd 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -1,13 +1,18 @@
import { useState } from "react";
import { Brain, Check, Copy, KeyRound, LogIn, LogOut, Mic, Phone, PlugZap, Terminal, Volume2, Loader2, AlertCircle, XCircle } from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
+import { AltCredentialNote } from "@/components/AltCredentialNote";
import { ApiKeyForm } from "@/components/ApiKeyForm";
+import { BrainModelSelector } from "@/components/BrainModelSelector";
+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
import { SubagentSection } from "@/components/SubagentSection";
import { TelephonyPanel } from "@/views/TelephonyView";
import { WikiProviderCard } from "@/views/settings/WikiProviderCard";
import { Button } from "@/components/ui/button";
import {
codexLogout,
+ loginAntigravity,
+ logoutAntigravity,
type ProviderDescriptor,
type ProviderTestResult,
type ProviderTestStatus,
@@ -34,7 +39,7 @@ function makeTierMeta(t: (k: string) => string): Record<ProviderTier, { label: s
export function ApiKeysView() {
const t = useT();
const TIER_META = makeTierMeta(t);
- const { providers, loading, error, refetch } = useProviders();
+ const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();
return (
<div className="flex h-full flex-col">
@@ -64,10 +69,18 @@ export function ApiKeysView() {
{!loading && providers.length > 0 && (
<div className="mt-6 space-y-8">
{(Object.keys(TIER_META) as ProviderTier[]).map((tier) => {
- const tierProviders = providers.filter((p) => p.tier === tier);
+ const tierProviders = providers.filter(
+ (p) => p.tier === tier && p.brain_switchable !== false,
+ );
if (!tierProviders.length) return null;
return (
- <TierSection key={tier} tier={tier} providers={tierProviders} onChanged={refetch} />
+ <TierSection
+ key={tier}
+ tier={tier}
+ providers={tierProviders}
+ onChanged={refetch}
+ onActivateOptimistic={setActiveOptimistic}
+ />
);
})}
{/* Subagent (OpenClaw) — own data source (/api/openclaw/status),
@@ -112,10 +125,12 @@ function TierSection({
tier,
providers,
onChanged,
+ onActivateOptimistic,
}: {
tier: ProviderTier;
providers: ProviderDescriptor[];
onChanged: () => void;
+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;
}) {
const t = useT();
const meta = makeTierMeta(t)[tier];
@@ -133,6 +148,7 @@ function TierSection({
<ProviderCard
descriptor={p}
onChanged={onChanged}
+ onActivateOptimistic={onActivateOptimistic}
autoActivateOnSave={!tierHasActive}
/>
</li>
@@ -145,24 +161,31 @@ function TierSection({
function ProviderCard({
descriptor,
onChanged,
+ onActivateOptimistic,
autoActivateOnSave,
}: {
descriptor: ProviderDescriptor;
onChanged: () => void;
+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;
autoActivateOnSave: boolean;
}) {
const t = useT();
const [activating, setActivating] = useState(false);
const pushToast = useEventStore((s) => s.pushToast);
- // Codex IS a selectable brain like every other provider, but a chat brain
- // needs an OpenAI API key — the ChatGPT login cannot back one (it powers the
- // Codex *worker*). `codex_brain_ready` reflects whether any OpenAI key is
- // configured; the radio is gated on it so activation never silently fails.
+ // Codex is filtered out of the Brain tier (`brain_switchable=false`) and is
+ // selected from the Subagent section. This branch stays for older payloads or
+ // tests that still mount a Codex descriptor directly.
const isCodex = descriptor.auth_mode === "codex";
+ const isBrainSwitchable =
+ descriptor.tier !== "brain" || descriptor.brain_switchable !== false;
async function activate(assumeConfigured = false) {
if (descriptor.active) return;
+ if (!isBrainSwitchable) {
+ pushToast("warning", `${descriptor.label} is only available for Subagents.`);
+ return;
+ }
if (isCodex && !descriptor.codex_brain_ready) {
// The card is "connected" via OAuth, but a chat brain needs an OpenAI key.
// Guide honestly instead of switching and failing on the first turn.
@@ -174,10 +197,17 @@ function ProviderCard({
"warning",
descriptor.auth_mode === "codex"
? t("apikeys_codex.needs_codex_full").replace("{0}", descriptor.label)
- : t("apikeys_codex.needs_key_full").replace("{0}", descriptor.label),
+ : descriptor.auth_mode === "antigravity"
+ ? t("apikeys_antigravity.needs_login_full").replace("{0}", descriptor.label)
+ : t("apikeys_codex.needs_key_full").replace("{0}", descriptor.label),
);
return;
}
+ // Flip the highlight immediately so the switch feels instant — the backend
+ // call below can take a few seconds (a TTS switch rebuilds the provider and
+ // injects it into the live pipeline). The refetch on success / failure then
+ // reconciles with server truth.
+ onActivateOptimistic(descriptor.tier, descriptor.id);
setActivating(true);
try {
if (descriptor.tier === "brain") {
@@ -189,19 +219,21 @@ function ProviderCard({
const note = result.restart_required
? " (active from next voice start)"
: "";
- pushToast("success", `Voice-Output → ${descriptor.label}${note}`);
+ pushToast("success", `Voice output → ${descriptor.label}${note}`);
window.dispatchEvent(new CustomEvent("jarvis:tts-switched"));
} else {
const result = await switchSttProvider(descriptor.id);
const note = result.restart_required
? " (active from next voice start)"
: "";
- pushToast("success", `Voice-Input → ${descriptor.label}${note}`);
+ pushToast("success", `Voice input → ${descriptor.label}${note}`);
window.dispatchEvent(new CustomEvent("jarvis:stt-switched"));
}
onChanged();
} catch (e) {
pushToast("error", (e as Error).message);
+ // Roll the optimistic highlight back to the true active provider.
+ onChanged();
} finally {
setActivating(false);
}
@@ -216,6 +248,7 @@ function ProviderCard({
function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {
// Codex is connection-only — a card click must never trigger a brain switch.
if (isCodex) return;
+ if (!isBrainSwitchable) return;
const target = e.target as HTMLElement | null;
if (
target &&
@@ -246,18 +279,24 @@ function ProviderCard({
title={
descriptor.active
? t("apikeys_view.active_tooltip")
+ : !isBrainSwitchable
+ ? "Available for Subagents only"
: descriptor.configured
? t("apikeys_view.click_to_activate")
: descriptor.auth_mode === "codex"
? t("apikeys_view.needs_codex")
- : t("apikeys_view.needs_key")
+ : descriptor.auth_mode === "antigravity"
+ ? t("apikeys_view.needs_login")
+ : t("apikeys_view.needs_key")
}
className={cn(
"card-outline space-y-3 p-4 transition-colors",
descriptor.active
? "border-primary bg-primary/[0.06] ring-1 ring-primary/30"
: descriptor.configured
- ? "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]"
+ ? isBrainSwitchable
+ ? "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]"
+ : ""
: "opacity-95",
)}
>
@@ -271,9 +310,10 @@ function ProviderCard({
<code className="font-mono">{descriptor.id}</code>
{" · "}
<span>
- {descriptor.auth_mode === "api_key" && "API-Key-Auth"}
- {descriptor.auth_mode === "codex" && "ChatGPT/Codex-Login"}
- {descriptor.auth_mode === "none" && "Lokal — keine Auth"}
+ {descriptor.auth_mode === "api_key" && "API key auth"}
+ {descriptor.auth_mode === "codex" && "ChatGPT / Codex login"}
+ {descriptor.auth_mode === "antigravity" && "Google subscription login"}
+ {descriptor.auth_mode === "none" && "Local — no auth"}
</span>
</p>
</div>
@@ -286,7 +326,14 @@ function ProviderCard({
}
activating={activating}
onActivate={activate}
- disabled={isCodex && !descriptor.codex_brain_ready}
+ disabled={!isBrainSwitchable || (isCodex && !descriptor.codex_brain_ready)}
+ disabledReason={
+ !isBrainSwitchable
+ ? "Available for Subagents only"
+ : isCodex && !descriptor.codex_brain_ready
+ ? t("apikeys_codex.brain_needs_openai_key")
+ : undefined
+ }
/>
</div>
@@ -296,6 +343,24 @@ function ProviderCard({
onSavedActivate={handleSavedActivate}
/>
+ {!isBrainSwitchable && (
+ <p className="rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[11px] leading-relaxed text-amber-700">
+ Subagent only. This provider cannot be used as the main Brain or
+ Computer-Use planner because it does not receive screenshots.
+ </p>
+ )}
+
+ {/* Model / voice picker. Switchable brain providers
+ pick a model from their own live catalog. TTS/STT share a single global
+ [tts]/[stt] block, so the picker only appears on the ACTIVE one and sets
+ the voice (Grok/Gemini/OpenAI/Google) or model (Cartesia/STT). */}
+ {((descriptor.tier === "brain" && descriptor.configured && isBrainSwitchable) ||
+ ((descriptor.tier === "tts" || descriptor.tier === "stt") &&
+ descriptor.active &&
+ descriptor.configured)) && (
+ <BrainModelSelector providerId={descriptor.id} />
+ )}
+
<ProviderTestControl providerId={descriptor.id} />
</div>
);
@@ -415,6 +480,7 @@ function ActiveControl({
activating,
onActivate,
disabled = false,
+ disabledReason,
}: {
descriptor: ProviderDescriptor;
activating: boolean;
@@ -426,14 +492,15 @@ function ActiveControl({
* (warn-on-click) because their key field is right on the card.
*/
disabled?: boolean;
+ disabledReason?: string;
}) {
const labelTitle = descriptor.active
- ? "Dieser Provider ist aktiv"
+ ? "This provider is active"
: disabled
- ? "Erst einen OpenAI-API-Key setzen"
+ ? disabledReason ?? "Provider cannot be activated"
: descriptor.configured
- ? "Diesen Provider aktivieren"
- : "Erst API-Key setzen";
+ ? "Activate this provider"
+ : "Set an API key first";
return (
<label
@@ -463,7 +530,7 @@ function ActiveControl({
disabled={activating || disabled}
className="accent-primary"
/>
- {activating ? "Aktiviere…" : "Als aktiv"}
+ {activating ? "Activating…" : "Set active"}
</label>
);
}
@@ -477,31 +544,38 @@ function AuthWidget({
onChanged: () => void;
onSavedActivate?: () => void;
}) {
- if (descriptor.auth_mode === "none") {
- return (
- <p className="text-xs text-muted-foreground">
- Local provider — no credentials needed.
- </p>
- );
- }
-
- if (descriptor.auth_mode === "codex") {
- return <CodexAuthWidget descriptor={descriptor} onChanged={onChanged} />;
- }
-
- // api_key
return (
<div className="space-y-2">
- {descriptor.secret_keys.map((k) => (
- <ApiKeyForm
- key={k}
- secretKey={k}
- dashboardUrl={descriptor.dashboard_url}
- configured={Boolean(descriptor.secrets_set[k])}
- onChanged={onChanged}
- onSavedActivate={onSavedActivate}
- />
- ))}
+ <ProviderBillingBadge billing={descriptor.billing} />
+ {descriptor.auth_mode === "none" && (
+ <p className="text-xs text-muted-foreground">
+ Local provider — no credentials needed.
+ </p>
+ )}
+ {descriptor.auth_mode === "codex" && (
+ <CodexAuthWidget descriptor={descriptor} onChanged={onChanged} />
+ )}
+ {descriptor.auth_mode === "antigravity" && (
+ <AntigravityAuthWidget descriptor={descriptor} onChanged={onChanged} />
+ )}
+ {descriptor.auth_mode === "api_key" && (
+ <>
+ {descriptor.secret_keys.map((k) => (
+ <ApiKeyForm
+ key={k}
+ secretKey={k}
+ dashboardUrl={descriptor.dashboard_url}
+ configured={Boolean(descriptor.secrets_set[k])}
+ credentialHelp={descriptor.credential_help}
+ onChanged={onChanged}
+ onSavedActivate={onSavedActivate}
+ />
+ ))}
+ {descriptor.alt_credential && (
+ <AltCredentialNote alt={descriptor.alt_credential} />
+ )}
+ </>
+ )}
</div>
);
}
@@ -523,7 +597,7 @@ function CodexAuthWidget({
setPending("copy");
try {
await navigator.clipboard.writeText(installCommand);
- pushToast("success", "Installationsbefehl kopiert");
+ pushToast("success", "Install command copied");
} catch {
pushToast("warning", installCommand);
} finally {
@@ -590,7 +664,7 @@ function CodexAuthWidget({
className="ml-auto"
>
<LogOut className="h-3.5 w-3.5" />
- Trennen
+ Disconnect
</Button>
</div>
</div>
@@ -616,7 +690,7 @@ function CodexAuthWidget({
</code>
<Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>
{pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
- Befehl kopieren
+ Copy command
</Button>
</div>
)}
@@ -624,12 +698,12 @@ function CodexAuthWidget({
<div className="flex flex-wrap gap-2">
<Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}>
<LogIn className="h-3.5 w-3.5" />
- Mit ChatGPT verbinden
+ Connect with ChatGPT
</Button>
<Button size="sm" variant="outline" asChild>
<a href="https://help.openai.com/en/articles/11381614" target="_blank" rel="noreferrer">
<Terminal className="h-3.5 w-3.5" />
- Codex installieren
+ Install Codex
</a>
</Button>
</div>
@@ -638,18 +712,160 @@ function CodexAuthWidget({
);
}
+function AntigravityAuthWidget({
+ descriptor,
+ onChanged,
+}: {
+ descriptor: ProviderDescriptor;
+ onChanged: () => void;
+}) {
+ const t = useT();
+ const [pending, setPending] = useState<"login" | "logout" | "copy" | null>(null);
+ const pushToast = useEventStore((s) => s.pushToast);
+ const status = descriptor.antigravity_status;
+ const installCommand =
+ descriptor.install_hint ?? "curl -fsSL https://antigravity.google/cli/install.sh | bash";
+
+ async function handleCopy() {
+ setPending("copy");
+ try {
+ await navigator.clipboard.writeText(installCommand);
+ pushToast("success", "Install command copied");
+ } catch {
+ pushToast("warning", installCommand);
+ } finally {
+ setPending(null);
+ }
+ }
+
+ async function handleLogin() {
+ setPending("login");
+ try {
+ await loginAntigravity();
+ pushToast("info", t("apikeys_antigravity.login_started"));
+ // The Google CLI opens the browser "Sign in with Google" flow; it only
+ // completes once the user clicks through (seconds later). Poll a few times
+ // so the card flips to the compact "connected" state on its own once the
+ // on-disk creds appear — no manual refresh needed (mirror of Codex).
+ [1500, 4000, 8000, 15000, 25000].forEach((ms) =>
+ window.setTimeout(onChanged, ms),
+ );
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(null);
+ }
+ }
+
+ async function handleLogout() {
+ setPending("logout");
+ try {
+ await logoutAntigravity();
+ pushToast("info", t("apikeys_antigravity.disconnected"));
+ onChanged();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(null);
+ }
+ }
+
+ // Connected: collapse to a small "logged in" badge instead of the full card.
+ // The Google subscription bills the brain/subagent; no key field (OAuth-only).
+ if (status?.connected) {
+ return (
+ <div className="space-y-3">
+ <div
+ data-testid="antigravity-connected"
+ className="flex flex-wrap items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/[0.06] px-3 py-2 text-xs"
+ >
+ <Check className="h-3.5 w-3.5 shrink-0 text-emerald-500" />
+ <span className="min-w-0 break-words text-foreground">
+ {status.user_email
+ ? t("apikeys_antigravity.connected_as").replace("{0}", status.user_email)
+ : status.message || t("apikeys_antigravity.connected")}
+ </span>
+ {status.version && (
+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>
+ )}
+ <span className="chip-yellow">GOOGLE-LOGIN</span>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={handleLogout}
+ disabled={pending !== null}
+ className="ml-auto"
+ >
+ <LogOut className="h-3.5 w-3.5" />
+ Disconnect
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ // Not connected: status + (install hint) + the single "connect" action.
+ return (
+ <div className="space-y-3">
+ <div className="rounded-md border border-border bg-background/40 p-3 text-xs text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-2">
+ <span>{status?.message ?? t("apikeys_antigravity.status_loading")}</span>
+ {status?.version && (
+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>
+ )}
+ </div>
+ </div>
+
+ {!status?.installed && (
+ <div className="flex flex-wrap items-center gap-2">
+ <code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">
+ {installCommand}
+ </code>
+ <Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>
+ {pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
+ Copy command
+ </Button>
+ </div>
+ )}
+
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}>
+ <LogIn className="h-3.5 w-3.5" />
+ Connect with Google
+ </Button>
+ <Button size="sm" variant="outline" asChild>
+ <a href="https://antigravity.google" target="_blank" rel="noreferrer">
+ <Terminal className="h-3.5 w-3.5" />
+ Install Antigravity
+ </a>
+ </Button>
+ </div>
+ </div>
+ );
+}
+
function StatusBadge({ descriptor }: { descriptor: ProviderDescriptor }) {
- if (descriptor.active) return <span className="chip-yellow">aktiv</span>;
+ if (descriptor.active) return <span className="chip-yellow">active</span>;
if (descriptor.auth_mode === "codex") {
const status = descriptor.codex_status;
if (!status?.installed) {
- return <span className="rounded-full bg-destructive/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-destructive">fehlt</span>;
+ return <span className="rounded-full bg-destructive/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-destructive">missing</span>;
}
if (descriptor.configured) {
- return <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">eingerichtet</span>;
+ return <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">ready</span>;
+ }
+ return <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">not connected</span>;
+ }
+ if (descriptor.auth_mode === "antigravity") {
+ const status = descriptor.antigravity_status;
+ if (!status?.installed) {
+ return <span className="rounded-full bg-destructive/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-destructive">missing</span>;
+ }
+ if (status.connected) {
+ return <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">ready</span>;
}
- return <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">nicht verbunden</span>;
+ return <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">not connected</span>;
}
- if (descriptor.configured) return <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">eingerichtet</span>;
- return <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">offen</span>;
+ if (descriptor.configured) return <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">ready</span>;
+ return <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">open</span>;
}
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index f3ade43e5f..16ad5bb6f0 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -22,6 +22,7 @@ from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from jarvis.brain import provider_test as _provider_test
+from jarvis.brain.model_catalog import catalog_spec
from jarvis.codex_auth import CodexAuthService
from jarvis.core import config as cfg_mod
from jarvis.core.events import SecretConfigured
@@ -33,7 +34,7 @@ from jarvis.missions.worker_runtime.provider_map import (
)
from jarvis.setup.wizard import SECRETS as WIZARD_SECRETS
-from .provider_spec import PROVIDERS, ProviderSpec, get_spec
+from .provider_spec import PROVIDERS, ProviderSpec, get_spec, provider_billing
log = logging.getLogger(__name__)
@@ -108,6 +109,53 @@ class ProviderTestResponse(BaseModel):
integration_ok: bool = True
+# Per-provider model picker. ``CatalogSourceLiteral`` is the honest provenance of
+# the model list (live fetch vs. served-from-cache vs. offline static fallback) —
+# the UI must never present ``static`` as the live catalog.
+CatalogSourceLiteral = Literal["live", "cache", "static", "curated"]
+
+
+class BrainModelInfo(BaseModel):
+ id: str
+ label: str
+
+
+class BrainModelsResponse(BaseModel):
+ provider: str
+ current_model: str
+ models: list[BrainModelInfo]
+ source: CatalogSourceLiteral
+ fetched_at: float = 0.0
+ # What the picker writes: "model" (brain/stt/cartesia) or "voice" (most TTS).
+ selects: str = "model"
+
+
+class BrainModelBody(BaseModel):
+ # Empty string is meaningful: reset the provider to its frontier default.
+ model: str = Field(default="", max_length=200)
+ persist: bool = Field(default=True)
+
+
+class BrainModelProbe(BaseModel):
+ """Honest outcome of a real 1-token call against the *selected* model."""
+
+ status: ProviderTestStatusLiteral
+ detail: str = ""
+ latency_ms: float = 0.0
+ integration_ok: bool = True
+
+
+class BrainModelSaveResponse(BaseModel):
+ ok: bool
+ provider: str
+ model: str
+ persisted: bool
+ applied_live: bool
+ restart_required: bool
+ # Only brain providers run a live 1-token probe; TTS/STT save without one.
+ probe: BrainModelProbe | None = None
+
+
# ----------------------------------------------------------------------
# Helper
# ----------------------------------------------------------------------
@@ -151,14 +199,11 @@ def _cli_installed(spec: ProviderSpec) -> bool | None:
def _has_openai_brain_credential() -> bool:
- """True iff an OpenAI API key usable by the Codex *brain* is configured.
-
- Mirrors ``CodexBrain._ensure_client``: the dedicated codex slot, the general
- OpenAI provider key, or the ``OPENAI_API_KEY`` env fallback. The ChatGPT
- OAuth login is intentionally NOT counted — it powers the codex *subagent*
- (the CLI), not a chat-completions brain. Used to gate Codex-as-brain
- activation so the switch never "succeeds" on OAuth and then fails on the
- first turn.
+ """True iff an OpenAI API key usable by the legacy Codex brain is configured.
+
+ Codex is no longer switchable as the main Brain because Computer Use needs
+ screenshot-capable planning. This helper is kept for old payload fields and
+ defensive compatibility with the CodexBrain plugin.
"""
return bool(
cfg_mod.get_secret("codex_openai_api_key")
@@ -167,12 +212,11 @@ def _has_openai_brain_credential() -> bool:
def _codex_brain_usable() -> bool:
- """True iff Codex can serve as a brain: an OpenAI API key (the fast chat-API
- path) OR a ChatGPT login (the slow ``codex exec`` CLI path).
+ """Legacy readiness signal for Codex credentials.
- The CLI path is genuinely slow (~15-20 s per turn) and burns subscription
- tokens, but it IS a working brain (CodexBrain drives ``codex exec`` over the
- OAuth token). So the brain toggle unlocks on OAuth too, not only on a key.
+ The Brain switch rejects Codex earlier via ``brain_switchable=False``; Codex
+ belongs in the Subagent section. The value remains in ``/api/providers`` for
+ older UI consumers that still read ``codex_brain_ready``.
"""
if _has_openai_brain_credential():
return True
@@ -200,6 +244,11 @@ def _spec_to_payload(
codex_status = None
if spec.id == "codex":
codex_status = CodexAuthService(_codex_binary_path()).status().to_dict()
+ antigravity_status = None
+ if spec.id == "antigravity":
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ antigravity_status = GoogleCliAuthService().status().to_dict()
payload = {
"id": spec.id,
@@ -212,18 +261,42 @@ def _spec_to_payload(
"login_cli": list(spec.login_cli) if spec.login_cli else None,
"install_hint": spec.install_hint,
"credential_path_hint": spec.credential_path_hint,
- "configured": _is_credential_present(
- spec,
- _codex_binary_path() if spec.id == "codex" else None,
+ "brain_switchable": spec.brain_switchable,
+ # Plain-English help + how it is billed (api / subscription /
+ # subscription_or_api / local) so the UI explains "which key or
+ # subscription, and what for" without guessing.
+ "credential_help": spec.credential_help,
+ "signup_url": spec.signup_url,
+ "billing": provider_billing(spec),
+ # Gemini's AI-Studio-vs-Vertex split; None for single-path providers.
+ "alt_credential": (
+ {
+ "label": spec.alt_credential.label,
+ "billing": spec.alt_credential.billing,
+ "credential_help": spec.alt_credential.credential_help,
+ "dashboard_url": spec.alt_credential.dashboard_url,
+ "credential_path_hint": spec.alt_credential.credential_path_hint,
+ }
+ if spec.alt_credential is not None
+ else None
+ ),
+ "configured": (
+ bool(antigravity_status["connected"])
+ if antigravity_status is not None
+ else _is_credential_present(
+ spec,
+ _codex_binary_path() if spec.id == "codex" else None,
+ )
),
"active": active,
"cli_installed": _cli_installed(spec),
}
+ if antigravity_status is not None:
+ payload["antigravity_status"] = antigravity_status
if codex_status is not None:
payload["codex_status"] = codex_status
- # Codex IS a selectable brain. It works with an OpenAI API key (fast)
- # OR the ChatGPT login (slow codex-exec CLI path). The UI gates the brain
- # "activate" radio on this — unlocked for either credential.
+ # Back-compat only. Codex is not rendered as a switchable Brain anymore;
+ # the Subagent section owns its ChatGPT login and activation.
payload["codex_brain_ready"] = _codex_brain_usable()
return payload
@@ -392,6 +465,334 @@ async def test_provider_connection(
)
+# ----------------------------------------------------------------------
+# Per-provider model picker (live catalog + pin + honest probe)
+# ----------------------------------------------------------------------
+
+
+def _get_model_catalog(request: Request):
+ """Lazily build + stash a process-wide :class:`ModelCatalog` on app.state.
+
+ A singleton so the 6 h cache is shared across requests (and its asyncio lock
+ actually serialises concurrent fetches) instead of re-reading the cache file
+ per call.
+ """
+ cat = getattr(request.app.state, "model_catalog", None)
+ if cat is None:
+ from jarvis.brain.model_catalog import ModelCatalog
+
+ cat = ModelCatalog()
+ try:
+ request.app.state.model_catalog = cat
+ except Exception as exc: # noqa: BLE001 — detached app.state is not an error
+ log.debug("Could not stash model_catalog on app.state: %s", exc)
+ return cat
+
+
+def _current_brain_model(cfg: Any, provider: str) -> str:
+ """The model currently in effect for ``provider`` (override or frontier
+ default), so the picker can highlight the active selection."""
+ from jarvis.brain.manager import get_tier_default_model
+
+ pc = None
+ providers = getattr(getattr(cfg, "brain", None), "providers", None)
+ if isinstance(providers, dict):
+ pc = providers.get(provider)
+ model = getattr(pc, "model", None) if pc is not None else None
+ return model or get_tier_default_model("router", provider) or ""
+
+
+async def _probe_brain_model(
+ provider: str, model: str, *, timeout_s: float = 20.0
+) -> _provider_test.ProviderTestResult:
+ """Run a REAL 1-token call against the *specific* ``model`` and classify it.
+
+ Unlike :func:`provider_test.run_provider_test` (which probes the *configured*
+ model), this validates the model the user just selected — so a typo or a
+ model the key has no access to comes back as ``model_unavailable`` rather
+ than silently "saved but broken". Module-level so it is monkeypatchable.
+ """
+ from jarvis.brain.healthcheck import BrainHealthChecker
+ from jarvis.brain.provider_registry import BrainProviderRegistry
+
+ checker = BrainHealthChecker(BrainProviderRegistry())
+ hr = await checker.probe(provider, model, timeout_s=timeout_s)
+ if getattr(hr, "ok", False):
+ return _provider_test.ProviderTestResult(
+ provider, _provider_test.OK, "", getattr(hr, "duration_ms", 0.0)
+ )
+ err = getattr(hr, "error", None)
+ return _provider_test.ProviderTestResult(
+ provider,
+ _provider_test.classify_provider_error(err),
+ err or "",
+ getattr(hr, "duration_ms", 0.0),
+ )
+
+
+def _require_catalog_provider(provider_id: str):
+ """Validate that ``provider_id`` has a model/voice catalog.
+
+ Returns ``(spec, cat)`` (the provider spec + the catalog spec). 404 unknown
+ provider; 400 a provider with no catalog (e.g. faster-whisper is fine, but a
+ provider absent from PROVIDER_CATALOG is rejected).
+ """
+ spec = get_spec(provider_id)
+ if spec is None:
+ raise HTTPException(status_code=404, detail=f"Unbekannter Provider: {provider_id}")
+ cat = catalog_spec(provider_id)
+ if cat is None:
+ raise HTTPException(
+ status_code=400,
+ detail=f"'{provider_id}' bietet keine Modell-/Stimmen-Auswahl.",
+ )
+ return spec, cat
+
+
+def _cartesia_model(tts: Any) -> str:
+ """Read Cartesia's model from its own sub-table ``[tts.cartesia].model_id``.
+
+ Cartesia does NOT use the global ``[tts] model`` (which holds Gemini's TTS
+ model); reading that would show a nonsensical Gemini id on the Cartesia card.
+ """
+ if tts is None:
+ return ""
+ sub: Any = None
+ extra = getattr(tts, "model_extra", None)
+ if isinstance(extra, dict):
+ sub = extra.get("cartesia")
+ if sub is None:
+ sub = getattr(tts, "cartesia", None)
+ if isinstance(sub, dict):
+ return str(sub.get("model_id") or "")
+ return str(getattr(sub, "model_id", "") or "")
+
+
+def _current_selection(cfg: Any, provider_id: str, cat: Any) -> str:
+ """The value currently in effect for ``provider_id``'s picker (tier-aware).
+
+ Brain → the per-provider model; TTS → the global voice (``voice_de``) or model;
+ Cartesia → its own ``[tts.cartesia].model_id``; STT → the global ``stt.model``.
+ """
+ if cat.tier == "brain":
+ return _current_brain_model(cfg, provider_id)
+ if cat.tier == "tts":
+ tts = getattr(cfg, "tts", None)
+ if cat.selects == "voice":
+ return getattr(tts, "voice_de", "") or ""
+ if provider_id == "cartesia":
+ return _cartesia_model(tts) or "sonic-3.5"
+ return getattr(tts, "model", "") or ""
+ if cat.tier == "stt":
+ return getattr(getattr(cfg, "stt", None), "model", "") or ""
+ return ""
+
+
[email protected]("/providers/{provider_id}/models")
+async def list_brain_models(
+ provider_id: str, request: Request, refresh: bool = False
+) -> BrainModelsResponse:
+ """Return the model/voice catalog for ``provider_id`` for the picker dropdown.
+
+ Brain providers fetch their own live ``/v1/models`` (so a freshly released
+ model appears with no code change); TTS/STT return a curated voice/model list.
+ ``selects`` tells the UI whether it picks a model or a voice. ``source`` is
+ honest: ``live`` / ``cache`` / ``static`` / ``curated``.
+ """
+ _spec, cat = _require_catalog_provider(provider_id)
+ catalog = _get_model_catalog(request)
+ result = await catalog.list_models(provider_id, force_refresh=refresh)
+ cfg = _resolve_cfg(request)
+ current = _current_selection(cfg, provider_id, cat)
+ # Safety net: for a curated TTS/STT list, never echo a value that isn't in the
+ # list (e.g. a stale global value belonging to a different provider) — show the
+ # placeholder instead. Brain keeps its value (custom model ids are allowed).
+ if cat.tier != "brain" and current and current not in {m.id for m in result.models}:
+ current = ""
+ return BrainModelsResponse(
+ provider=provider_id,
+ current_model=current,
+ models=[BrainModelInfo(id=m.id, label=m.label) for m in result.models],
+ source=result.source,
+ fetched_at=result.fetched_at,
+ selects=result.selects,
+ )
+
+
+async def _apply_brain_model(
+ provider_id: str, model: str, body: BrainModelBody, request: Request, *, probe: bool
+) -> BrainModelSaveResponse:
+ """Persist + live-apply a brain provider's model, optionally probing it."""
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core.config_writer import set_brain_provider_model
+
+ set_brain_provider_model(provider_id, model=model)
+ persisted = True
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(
+ status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}"
+ ) from exc
+
+ brain = getattr(request.app.state, "brain", None)
+ applied_live = False
+ if brain is not None and hasattr(brain, "apply_provider_model"):
+ try:
+ applied_live = bool(brain.apply_provider_model(provider_id, model))
+ except Exception as exc: # noqa: BLE001
+ log.warning("Live model apply for %s failed: %s", provider_id, exc)
+ applied_live = False
+ restart_required = brain is None
+
+ probe_payload: BrainModelProbe | None = None
+ if probe:
+ cfg = _resolve_cfg(request)
+ probe_model = model or _current_brain_model(cfg, provider_id)
+ result = await _probe_brain_model(provider_id, probe_model)
+ probe_payload = BrainModelProbe(
+ status=result.status,
+ detail=result.detail,
+ latency_ms=round(result.latency_ms, 1),
+ integration_ok=result.status in _provider_test.INTEGRATION_OK_STATUSES,
+ )
+
+ await _emit(
+ request,
+ SecretConfigured(key=f"brain.providers.{provider_id}.model", action="set"),
+ )
+ return BrainModelSaveResponse(
+ ok=True, provider=provider_id, model=model, persisted=persisted,
+ applied_live=applied_live, restart_required=restart_required, probe=probe_payload,
+ )
+
+
+def _apply_tts_selection(
+ provider_id: str, value: str, selects: str, body: BrainModelBody, request: Request
+) -> BrainModelSaveResponse:
+ """Persist + live-apply a TTS voice/model (global ``[tts]`` block)."""
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core.config_writer import (
+ set_tts_cartesia_model,
+ set_tts_model,
+ set_tts_voice,
+ )
+
+ if selects == "voice":
+ set_tts_voice(value)
+ elif provider_id == "cartesia":
+ # Cartesia's model lives in its own [tts.cartesia] sub-table.
+ set_tts_cartesia_model(value)
+ else:
+ set_tts_model(value)
+ persisted = True
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(
+ status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}"
+ ) from exc
+
+ cfg = _resolve_cfg(request)
+ if cfg is not None and getattr(cfg, "tts", None) is not None:
+ try:
+ if selects == "voice":
+ cfg.tts.voice_de = value # type: ignore[attr-defined]
+ cfg.tts.voice_en = value # type: ignore[attr-defined]
+ elif provider_id == "cartesia":
+ extra = getattr(cfg.tts, "model_extra", None)
+ if isinstance(extra, dict):
+ sub = extra.get("cartesia")
+ if not isinstance(sub, dict):
+ sub = {}
+ extra["cartesia"] = sub
+ sub["model_id"] = value
+ else:
+ cfg.tts.model = value # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001 — frozen/detached cfg is not an error
+ log.debug("In-memory tts selection update skipped: %s", exc)
+
+ # Live-apply into the running SpeechPipeline (rebuild the TTS instance), so the
+ # next ``_speak()`` uses the new voice without a restart.
+ applied_live = False
+ pipeline = getattr(request.app.state, "speech_pipeline", None)
+ if pipeline is not None and hasattr(pipeline, "set_tts") and cfg is not None:
+ try:
+ from jarvis.plugins.tts import build_tts_from_config
+
+ pipeline.set_tts(build_tts_from_config(cfg.tts))
+ applied_live = True
+ except Exception as exc: # noqa: BLE001
+ log.error("TTS live re-apply for %s failed: %s", provider_id, exc, exc_info=True)
+
+ return BrainModelSaveResponse(
+ ok=True, provider=provider_id, model=value, persisted=persisted,
+ applied_live=applied_live, restart_required=not applied_live, probe=None,
+ )
+
+
+def _apply_stt_model(
+ provider_id: str, value: str, body: BrainModelBody, request: Request
+) -> BrainModelSaveResponse:
+ """Persist a STT model (global ``[stt] model``). Takes effect on voice restart."""
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core.config_writer import set_stt_model
+
+ set_stt_model(value)
+ persisted = True
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(
+ status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}"
+ ) from exc
+
+ cfg = _resolve_cfg(request)
+ if cfg is not None and getattr(cfg, "stt", None) is not None:
+ try:
+ cfg.stt.model = value # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001
+ log.debug("In-memory stt model update skipped: %s", exc)
+
+ return BrainModelSaveResponse(
+ ok=True, provider=provider_id, model=value, persisted=persisted,
+ applied_live=False, restart_required=True, probe=None,
+ )
+
+
[email protected]("/providers/{provider_id}/model")
+async def set_brain_model(
+ provider_id: str, body: BrainModelBody, request: Request
+) -> BrainModelSaveResponse:
+ """Pin a provider's model/voice, persist it, live-apply where possible.
+
+ - **Brain** (incl. Codex): ``[brain.providers.<id>].model`` + live-apply +
+ a real 1-token probe (skipped for Codex — the ChatGPT-login CLI path is slow
+ and ignores the model id anyway). Empty ``model`` resets to the frontier default.
+ - **TTS**: the global ``[tts]`` voice (``voice_de``/``voice_en``) or model
+ (Cartesia) + live re-apply into the running SpeechPipeline.
+ - **STT**: the global ``[stt] model`` (restart-required — the STT engine is
+ built once at pipeline boot).
+ """
+ spec, cat = _require_catalog_provider(provider_id)
+ value = body.model.strip()
+
+ if cat.tier == "brain":
+ # Codex / Antigravity probes would drive a slow subscription CLI (and
+ # bill a real call); skip the live probe for those OAuth-CLI providers.
+ do_probe = getattr(spec, "auth_mode", None) not in ("codex", "antigravity")
+ return await _apply_brain_model(provider_id, value, body, request, probe=do_probe)
+ if cat.tier == "tts":
+ return _apply_tts_selection(provider_id, value, cat.selects, body, request)
+ return _apply_stt_model(provider_id, value, body, request)
+
+
@router.get("/codex/status")
async def codex_status(request: Request) -> dict[str, Any]:
return CodexAuthService(_codex_binary_path(request)).status().to_dict()
@@ -485,6 +886,15 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
spec = get_spec(body.provider)
if spec is None:
raise HTTPException(status_code=404, detail=f"Unbekannter Provider: {body.provider}")
+ if spec.tier == "brain" and not spec.brain_switchable:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"{spec.label} is subagent-only in Jarvis. It cannot be used as "
+ "the main Brain provider because it cannot see Computer-Use "
+ "screenshots. Activate it in the Subagent section instead."
+ ),
+ )
cfg = _resolve_cfg(request)
profile_name = getattr(getattr(cfg, "profile", None), "name", "default")
@@ -514,12 +924,9 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
# 409 (Provider bekannt, aber Credentials fehlen) — Identifiability vor
# Konfiguration.
#
- # Codex-as-BRAIN is special: a chat-completions brain needs an OpenAI API
- # key. The ChatGPT subscription (OAuth) cannot back a chat endpoint — it
- # only powers the Codex *subagent*. Accept ANY OpenAI key CodexBrain can use
- # (codex_openai_api_key / openai_api_key / OPENAI_API_KEY), not just the
- # dedicated codex slot — so activation matches what the brain actually reads,
- # and never "succeeds" on OAuth alone and then fails on the first turn.
+ # Defensive legacy branch: Codex/Antigravity are rejected above as
+ # ``brain_switchable=False``. If that guard is ever relaxed, keep credential
+ # checks explicit instead of letting a switch succeed and fail on first turn.
if spec.id == "codex":
if not _codex_brain_usable():
raise HTTPException(
@@ -529,6 +936,19 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"run 'codex login' (ChatGPT subscription, slower CLI path)."
),
)
+ elif spec.id == "antigravity":
+ # OAuth-only: no API key. Gate on the Google CLI login being present,
+ # mirroring the codex branch (the CLI bills the Google subscription).
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ if not GoogleCliAuthService().status().connected:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "Antigravity isn't connected — sign in with Google (install "
+ "agy or the Gemini CLI and log in), then activate."
+ ),
+ )
elif not _is_credential_present(spec):
raise HTTPException(
status_code=409,
@@ -814,6 +1234,47 @@ async def subagent_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"restart_required": True,
}
+ # Antigravity (Google subscription) is a DIRECT worker over the OAuth Google
+ # CLI — no OpenClaw slug, no API key. Mirror of the codex branch: gate on the
+ # OAuth login being present, then persist the "antigravity" slug.
+ from jarvis.missions.worker_runtime.provider_map import (
+ ANTIGRAVITY_SUBAGENT_CANONICAL,
+ ANTIGRAVITY_SUBAGENT_SLUGS,
+ )
+
+ if provider in ANTIGRAVITY_SUBAGENT_SLUGS:
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ if not GoogleCliAuthService().status().connected:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "Antigravity is not connected — sign in with Google "
+ "(install agy or the Gemini CLI and log in), then activate."
+ ),
+ )
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core.config_writer import set_sub_jarvis_provider
+
+ set_sub_jarvis_provider(ANTIGRAVITY_SUBAGENT_CANONICAL)
+ persisted = True
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(
+ status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}"
+ ) from exc
+ _apply_sub_jarvis_in_memory(request, ANTIGRAVITY_SUBAGENT_CANONICAL)
+ await _emit(request, SecretConfigured(key="brain.sub_jarvis.provider", action="set"))
+ return {
+ "ok": True,
+ "active": ANTIGRAVITY_SUBAGENT_CANONICAL,
+ "persisted": persisted,
+ "restart_required": True,
+ }
+
if provider not in JARVIS_TO_OPENCLAW:
known = ", ".join(sorted(JARVIS_TO_OPENCLAW))
raise HTTPException(
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 07477b8931..9cfa0d0db6 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -13,6 +13,31 @@ from typing import Literal
AuthMode = Literal["api_key", "codex", "antigravity", "none"]
Tier = Literal["brain", "tts", "stt"]
+# How using a provider is billed. Derived from auth_mode (never branched on a
+# provider name — see provider_billing): an API key bills per token on an API
+# account; a subscription provider runs over an existing plan login; codex can
+# do either; a local provider needs no credential at all.
+Billing = Literal["api", "subscription", "subscription_or_api", "local"]
+
+
+@dataclass(frozen=True, slots=True)
+class AltCredential:
+ """An alternative credential path for the SAME provider.
+
+ Gemini is the motivating case (2026-06-22 forensic): the identical model is
+ reachable either via a Google AI Studio API key (pay-as-you-go) OR a Google
+ Cloud Vertex AI service account (a *separate* billing project). A user who
+ tops up one account while Jarvis is wired to the other gets a silent
+ "credits depleted" failure. The UI surfaces BOTH paths so the choice — and
+ its billing — is explicit. ``None`` (the default on ProviderSpec) means the
+ provider has a single credential path.
+ """
+
+ label: str
+ billing: Billing
+ credential_help: str
+ dashboard_url: str | None = None
+ credential_path_hint: str | None = None
@dataclass(frozen=True, slots=True)
@@ -26,15 +51,60 @@ class ProviderSpec:
login_cli: tuple[str, ...] | None = None
install_hint: str | None = None
credential_path_hint: str | None = None
+ brain_switchable: bool = True
+ # Plain-English "which key / subscription, and what it is for", shown under
+ # the provider's credential widget so the user does not have to guess.
+ credential_help: str | None = None
+ # Where to sign up for the account/subscription this provider bills against
+ # (distinct from dashboard_url, which is where you GENERATE the key). Mainly
+ # useful for the subscription providers; ``None`` for most API providers.
+ signup_url: str | None = None
+ # Alternative credential path (Gemini AI Studio vs Vertex). ``None`` =
+ # single path.
+ alt_credential: AltCredential | None = None
+
+
+def provider_billing(spec: ProviderSpec) -> Billing:
+ """How using *spec* is billed, derived purely from its ``auth_mode``.
+
+ Capability-driven, never name-branched (multi-provider mandate, AP-21):
+
+ * ``antigravity`` → ``"subscription"`` — runs over a Google subscription login.
+ * ``codex`` → ``"subscription_or_api"`` — a ChatGPT login OR an OpenAI key.
+ * ``none`` → ``"local"`` — no credential, runs on-device.
+ * everything else (``api_key``) → ``"api"`` — pay per token on an API account.
+ """
+ if spec.auth_mode == "antigravity":
+ return "subscription"
+ if spec.auth_mode == "codex":
+ return "subscription_or_api"
+ if spec.auth_mode == "none":
+ return "local"
+ return "api"
+
+
+# Gemini's alternative credential path: Google Cloud Vertex AI via a
+# service-account JSON. A SEPARATE billing project from an AI Studio key — the
+# 2026-06-22 forensic was a user topping up AI Studio while Jarvis was wired to
+# Vertex. Shared by the Gemini brain + Gemini TTS specs so both surface the
+# choice. (Vertex is wired for the TTS path today via [tts].use_vertex.)
+_GEMINI_VERTEX = AltCredential(
+ label="Vertex AI (service account)",
+ billing="api",
+ credential_help=(
+ "Bill Gemini through a Google Cloud Vertex AI project instead of an AI "
+ "Studio key — this is a SEPARATE billing account. Enable the Vertex AI "
+ "API, create a service account, download its JSON key, and point Jarvis "
+ "at the file. Use this for higher quota than the AI Studio preview cap. "
+ "Don't mix them up: topping up AI Studio does nothing if Jarvis is on "
+ "Vertex, and vice versa."
+ ),
+ dashboard_url="https://console.cloud.google.com/iam-admin/serviceaccounts",
+ credential_path_hint="~/.config/jarvis/vertex-sa.json",
+)
PROVIDERS: tuple[ProviderSpec, ...] = (
- # ── Brain: Subscription via externes CLI ──────────────────────────────
- # Direkt gegen Anthropic-API — OAuth-Token aus ~/.claude/.credentials.json
- # ODER manuell gepasteter anthropic_api_key. KEIN CLI-Spawn, kein Harness-
- # Roundtrip: reine POST-Requests wie bei jedem anderen LLM-Provider. Deshalb
- # `oauth_or_key` statt `api_key` — das Frontend rendert dafür zwei
- # getrennte Auth-Pfade (OAuth-Import-Button + API-Key-Formular).
# ── Brain: Klassischer API-Key ────────────────────────────────────────
ProviderSpec(
id="claude-api",
@@ -43,6 +113,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("anthropic_api_key",),
dashboard_url="https://console.anthropic.com/settings/keys",
+ credential_help=(
+ "Anthropic API key (starts with sk-ant-). Billed per token on your "
+ "Anthropic account. Powers the Claude brain."
+ ),
),
ProviderSpec(
id="openai",
@@ -51,6 +125,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("openai_api_key",),
dashboard_url="https://platform.openai.com/api-keys",
+ credential_help=(
+ "OpenAI API key (starts with sk-). Billed per token. Shared by the "
+ "GPT brain, Whisper STT and OpenAI TTS."
+ ),
),
ProviderSpec(
id="codex",
@@ -61,6 +139,13 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
dashboard_url="https://platform.openai.com/api-keys",
login_cli=("codex", "login"),
install_hint="npm i -g @openai/codex",
+ brain_switchable=False,
+ signup_url="https://chatgpt.com",
+ credential_help=(
+ "Run heavy subagent tasks over your ChatGPT subscription via the "
+ "Codex CLI — sign in below, no API key needed. Or paste an OpenAI "
+ "API key to bill per token instead."
+ ),
),
ProviderSpec(
id="openrouter",
@@ -69,6 +154,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("openrouter_api_key",),
dashboard_url="https://openrouter.ai/keys",
+ credential_help=(
+ "OpenRouter API key (starts with sk-or-). One key reaches many "
+ "models; billed per token on your OpenRouter account."
+ ),
),
# ── Brain: Google subscription via the official Antigravity/Gemini CLI ──
# OAuth-only (no API-key slot): we drive the official ``agy``/``gemini`` CLI
@@ -88,6 +177,13 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
login_cli=("agy",),
install_hint="Install Antigravity (agy) or sign in with the Gemini CLI",
credential_path_hint="~/.gemini/oauth_creds.json",
+ brain_switchable=False,
+ signup_url="https://antigravity.google",
+ credential_help=(
+ "Sign in with your Google account to run the brain over your Google "
+ "subscription via the Antigravity/Gemini CLI — no API key, billed to "
+ "your subscription, not per token."
+ ),
),
ProviderSpec(
id="gemini",
@@ -96,6 +192,12 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("gemini_api_key",),
dashboard_url="https://aistudio.google.com/app/apikey",
+ credential_help=(
+ "Google AI Studio API key (starts with AIza or AQ.). Pay-as-you-go "
+ "on your AI Studio project. For higher quota, use the Vertex AI "
+ "service-account path instead — it bills a different account."
+ ),
+ alt_credential=_GEMINI_VERTEX,
),
ProviderSpec(
id="grok",
@@ -104,6 +206,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("grok_api_key",),
dashboard_url="https://console.x.ai/",
+ credential_help=(
+ "xAI API key (starts with xai-). Billed per token. Shared by the "
+ "Grok brain and Grok Voice TTS."
+ ),
),
# Ollama-Provider 2026-04-21 entfernt — reine API-Provider-Chain.
# ── TTS ───────────────────────────────────────────────────────────────
@@ -114,6 +220,12 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("gemini_api_key",),
dashboard_url="https://aistudio.google.com/app/apikey",
+ credential_help=(
+ "Same Google AI Studio key as the Gemini brain (AIza/AQ.). Note: the "
+ "TTS preview model is hard-capped on AI Studio — switch to the Vertex "
+ "AI path for production quota."
+ ),
+ alt_credential=_GEMINI_VERTEX,
),
ProviderSpec(
id="google-neural2",
@@ -122,6 +234,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("google_tts_credentials_path",),
dashboard_url="https://console.cloud.google.com/apis/credentials",
+ credential_help=(
+ "Path to a Google Cloud service-account JSON with the Text-to-Speech "
+ "API enabled. Billed on the Cloud project."
+ ),
),
ProviderSpec(
id="openai-tts",
@@ -130,6 +246,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("openai_api_key",),
dashboard_url="https://platform.openai.com/api-keys",
+ credential_help=(
+ "Uses your OpenAI API key (shared with the GPT brain) — no separate "
+ "key to enter if OpenAI is already configured."
+ ),
),
ProviderSpec(
id="grok-voice",
@@ -138,6 +258,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("grok_api_key",),
dashboard_url="https://console.x.ai/",
+ credential_help=(
+ "Uses your xAI key (shared with the Grok brain). Voices: leo, rex, "
+ "sal, ara, eve."
+ ),
),
ProviderSpec(
id="cartesia",
@@ -146,6 +270,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("cartesia_api_key",),
dashboard_url="https://play.cartesia.ai/keys",
+ credential_help=(
+ "Cartesia API key (starts with sk_car_). Billed per token; "
+ "multilingual Sonic voices incl. German."
+ ),
),
# ── STT ───────────────────────────────────────────────────────────────
ProviderSpec(
@@ -155,6 +283,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("deepgram_api_key",),
dashboard_url="https://console.deepgram.com/",
+ credential_help=(
+ "Deepgram API key. Billed per minute of audio; fast hosted "
+ "speech-to-text."
+ ),
),
ProviderSpec(
id="groq-api",
@@ -163,6 +295,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("groq_api_key",),
dashboard_url="https://console.groq.com/keys",
+ credential_help=(
+ "Groq API key (starts with gsk_). Fast hosted Whisper "
+ "speech-to-text, billed per token."
+ ),
),
ProviderSpec(
id="openai-api",
@@ -171,6 +307,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="api_key",
secret_keys=("openai_api_key",),
dashboard_url="https://platform.openai.com/api-keys",
+ credential_help=(
+ "Uses your OpenAI API key (shared with the GPT brain) for Whisper "
+ "speech-to-text."
+ ),
),
ProviderSpec(
id="faster-whisper",
@@ -179,6 +319,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="none",
secret_keys=(),
dashboard_url=None,
+ credential_help=(
+ "Runs locally on your machine — no API key, no account. Needs the "
+ "[desktop] extra and a one-time model download."
+ ),
),
)
diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.py
index ba65730939..a1fb243890 100644
--- a/tests/integration/test_provider_routes.py
+++ b/tests/integration/test_provider_routes.py
@@ -123,6 +123,37 @@ def test_list_providers_returns_full_catalog(server_with_brain: WebServer, secre
assert "ollama-local" not in ids, "Ollama wurde 2026-04-21 entfernt"
+def test_list_providers_exposes_credential_help_and_billing(
+ server_with_brain: WebServer, secret_store: _InMemorySecretStore
+) -> None:
+ """The catalog carries the per-provider help text + how it is billed, so the
+ UI can explain 'which key / subscription, and what for' without guessing."""
+ with TestClient(server_with_brain.app) as client:
+ body = client.get("/api/providers").json()
+ by_id = {p["id"]: p for p in body["providers"]}
+ assert by_id["gemini"]["credential_help"]
+ assert by_id["gemini"]["billing"] == "api"
+ assert by_id["antigravity"]["billing"] == "subscription"
+ assert by_id["codex"]["billing"] == "subscription_or_api"
+ assert by_id["faster-whisper"]["billing"] == "local"
+
+
+def test_list_providers_exposes_gemini_vertex_alt_path(
+ server_with_brain: WebServer, secret_store: _InMemorySecretStore
+) -> None:
+ """Gemini surfaces the Vertex AI alternative so the user sees AI Studio vs
+ Vertex are different billing accounts (2026-06-22 forensic)."""
+ with TestClient(server_with_brain.app) as client:
+ body = client.get("/api/providers").json()
+ by_id = {p["id"]: p for p in body["providers"]}
+ alt = by_id["gemini"]["alt_credential"]
+ assert alt is not None
+ assert "vertex" in alt["label"].lower()
+ assert alt["billing"] == "api"
+ assert "cloud.google.com" in alt["dashboard_url"]
+ assert by_id["openai"]["alt_credential"] is None
+
+
def test_list_providers_marks_active_brain(server_with_brain: WebServer, secret_store: _InMemorySecretStore) -> None:
with TestClient(server_with_brain.app) as client:
body = client.get("/api/providers").json()
@@ -283,28 +314,22 @@ def test_brain_switch_rejects_provider_without_key(
assert fake.calls == []
-def test_brain_switch_codex_accepts_any_openai_key(
+def test_brain_switch_codex_rejected_as_subagent_only_even_with_openai_key(
server_with_brain: WebServer, secret_store: _InMemorySecretStore
) -> None:
- """Codex-as-brain activates with ANY OpenAI key CodexBrain can use.
-
- Here only the general ``openai_api_key`` is set (not the dedicated codex
- slot). CodexBrain falls back to it, so the switch must succeed — matching
- what the brain actually reads. The ChatGPT OAuth login alone is NOT enough
- for a chat brain (covered by the next test).
- """
+ """Codex remains subagent-only even if an OpenAI key is configured."""
secret_store.set("openai_api_key", "sk-openai-test-123")
fake: _FakeBrainManager = server_with_brain.app.state.brain
with TestClient(server_with_brain.app) as client:
resp = client.post("/api/brain/switch", json={"provider": "codex", "persist": True})
- assert resp.status_code == 200
- assert resp.json()["active"] == "codex"
- assert fake.calls == [("codex", True)]
+ assert resp.status_code == 409
+ assert "subagent-only" in resp.json()["detail"]
+ assert fake.calls == []
def _patch_codex_status(monkeypatch: pytest.MonkeyPatch, *, connected: bool) -> None:
"""Pin provider_routes.CodexAuthService to a connected/disconnected stub so
- the codex-brain tests don't depend on the dev machine's real `codex login`."""
+ Codex route tests don't depend on the dev machine's real `codex login`."""
class _Fake:
def __init__(self, binary_path: str | None = None) -> None:
@@ -322,7 +347,40 @@ def _patch_codex_status(monkeypatch: pytest.MonkeyPatch, *, connected: bool) ->
monkeypatch.setattr("jarvis.ui.web.provider_routes.CodexAuthService", _Fake)
-def test_brain_switch_codex_accepts_chatgpt_login(
+def _patch_antigravity_status(monkeypatch: pytest.MonkeyPatch, *, connected: bool) -> None:
+ class _Status:
+ def __init__(self) -> None:
+ self.installed = True
+ self.connected = connected
+ self.mode = "oauth-personal" if connected else "unknown"
+ self.cli_kind = "agy"
+ self.message = "connected" if connected else "not connected"
+ self.version = "1.0.0"
+ self.user_email = "[email protected]" if connected else None
+ self.binary_path = "agy"
+ self.error = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "installed": self.installed,
+ "connected": self.connected,
+ "mode": self.mode,
+ "cli_kind": self.cli_kind,
+ "message": self.message,
+ "version": self.version,
+ "user_email": self.user_email,
+ "binary_path": self.binary_path,
+ "error": self.error,
+ }
+
+ class _Fake:
+ def status(self) -> _Status:
+ return _Status()
+
+ monkeypatch.setattr("jarvis.google_cli.auth_service.GoogleCliAuthService", _Fake)
+
+
+def test_brain_switch_codex_rejected_as_subagent_only_even_with_chatgpt_login(
server_with_brain: WebServer,
secret_store: _InMemorySecretStore,
monkeypatch: pytest.MonkeyPatch,
@@ -333,9 +391,9 @@ def test_brain_switch_codex_accepts_chatgpt_login(
fake: _FakeBrainManager = server_with_brain.app.state.brain
with TestClient(server_with_brain.app) as client:
resp = client.post("/api/brain/switch", json={"provider": "codex", "persist": True})
- assert resp.status_code == 200
- assert resp.json()["active"] == "codex"
- assert fake.calls == [("codex", True)]
+ assert resp.status_code == 409
+ assert "subagent-only" in resp.json()["detail"]
+ assert fake.calls == []
def test_brain_switch_codex_rejected_without_any_auth(
@@ -349,11 +407,33 @@ def test_brain_switch_codex_rejected_without_any_auth(
with TestClient(server_with_brain.app) as client:
resp = client.post("/api/brain/switch", json={"provider": "codex"})
assert resp.status_code == 409
- assert "Codex can't be a brain yet" in resp.json()["detail"]
+ assert "subagent-only" in resp.json()["detail"]
# No silent switch — the manager must not have been called.
assert fake.calls == []
+def test_brain_switch_antigravity_rejected_as_subagent_only(
+ server_with_brain: WebServer,
+ secret_store: _InMemorySecretStore,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Antigravity is OAuth-connected but not selectable as the main brain.
+
+ It remains available through the dedicated subagent switch; the main-brain
+ endpoint must reject it before calling BrainManager.switch().
+ """
+ _patch_antigravity_status(monkeypatch, connected=True)
+ fake: _FakeBrainManager = server_with_brain.app.state.brain
+ fake._available.append("antigravity")
+
+ with TestClient(server_with_brain.app) as client:
+ resp = client.post("/api/brain/switch", json={"provider": "antigravity"})
+
+ assert resp.status_code == 409
+ assert "Subagent" in resp.json()["detail"]
+ assert fake.calls == []
+
+
def test_brain_switch_unknown_provider_returns_404(server_with_brain: WebServer, secret_store: _InMemorySecretStore) -> None:
with TestClient(server_with_brain.app) as client:
resp = client.post("/api/brain/switch", json={"provider": "nonexistent-provider"})
@@ -390,12 +470,7 @@ def test_brain_switch_codex_requires_api_key(
secret_store: _InMemorySecretStore,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """With NO credential (no key AND no ChatGPT login) -> 409, no switch.
-
- Codex-as-brain now also works over a ChatGPT login via the slow codex-exec
- CLI path (see ``test_brain_switch_codex_accepts_chatgpt_login``); here codex
- is pinned to disconnected so neither path is available.
- """
+ """Codex is rejected as main Brain before credential checks."""
_patch_codex_status(monkeypatch, connected=False)
fake: _FakeBrainManager = server_with_brain.app.state.brain
with TestClient(server_with_brain.app) as client:
@@ -407,16 +482,16 @@ def test_brain_switch_codex_requires_api_key(
def test_brain_switch_codex_with_api_key(
server_with_brain: WebServer, secret_store: _InMemorySecretStore
) -> None:
- """With the Codex key saved, codex activates as a first-class brain."""
+ """Even with a Codex key saved, Codex remains subagent-only."""
secret_store.set("codex_openai_api_key", "sk-codex-123")
fake: _FakeBrainManager = server_with_brain.app.state.brain
with TestClient(server_with_brain.app) as client:
resp = client.post(
"/api/brain/switch", json={"provider": "codex", "persist": False}
)
- assert resp.status_code == 200, resp.text
- assert resp.json()["active"] == "codex"
- assert fake.calls == [("codex", False)]
+ assert resp.status_code == 409, resp.text
+ assert "subagent-only" in resp.json()["detail"]
+ assert fake.calls == []
# ----------------------------------------------------------------------
diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.py
index 8b2e7250cf..8b81b3521c 100644
--- a/tests/unit/test_provider_spec.py
+++ b/tests/unit/test_provider_spec.py
@@ -9,9 +9,11 @@ from __future__ import annotations
from jarvis.setup.wizard import SECRETS
from jarvis.ui.web.provider_spec import (
PROVIDERS,
+ AltCredential,
ProviderSpec,
all_secret_keys,
get_spec,
+ provider_billing,
)
@@ -30,14 +32,20 @@ def test_every_secret_key_exists_in_wizard() -> None:
)
-def test_only_codex_uses_cli_login() -> None:
+def test_only_subscription_cli_providers_use_cli_login() -> None:
+ """A login CLI belongs to the subscription/login providers only. Codex logs
+ in via ``codex login``; Antigravity drives the bare ``agy`` binary (it has
+ no ``login`` subcommand). Every pure API-key / local provider has none."""
for spec in PROVIDERS:
- assert spec.auth_mode != "subscription_cli"
+ assert spec.auth_mode != "subscription_cli" # never the legacy literal
if spec.id == "codex":
assert spec.auth_mode == "codex"
assert spec.login_cli == ("codex", "login")
+ elif spec.id == "antigravity":
+ assert spec.auth_mode == "antigravity"
+ assert spec.login_cli == ("agy",)
else:
- assert spec.login_cli is None
+ assert spec.login_cli is None, f"{spec.id}: unexpected login_cli"
def test_api_key_specs_have_dashboard_url() -> None:
@@ -101,3 +109,72 @@ def test_provider_spec_is_frozen_dataclass() -> None:
except Exception:
return
raise AssertionError("ProviderSpec sollte frozen sein")
+
+
+# ── New: per-provider credential help + billing classification ───────────────
+
+
+def test_every_provider_has_credential_help() -> None:
+ """Each provider explains, in plain English, what credential it needs and
+ what it is for — the user-facing 'which key / subscription, and what for'."""
+ for spec in PROVIDERS:
+ assert spec.credential_help, f"{spec.id}: missing credential_help text"
+ assert spec.credential_help.strip() == spec.credential_help
+
+
+def test_provider_billing_is_derived_from_auth_mode() -> None:
+ """Billing is a pure function of auth_mode — never branched on a provider
+ name (multi-provider mandate). API-key → pay-per-token; antigravity →
+ subscription; codex → either; local → no credential."""
+ by_id = {spec.id: spec for spec in PROVIDERS}
+ assert provider_billing(by_id["claude-api"]) == "api"
+ assert provider_billing(by_id["gemini"]) == "api"
+ assert provider_billing(by_id["antigravity"]) == "subscription"
+ assert provider_billing(by_id["codex"]) == "subscription_or_api"
+ assert provider_billing(by_id["faster-whisper"]) == "local"
+
+
+def test_billing_covers_every_provider() -> None:
+ allowed = {"api", "subscription", "subscription_or_api", "local"}
+ for spec in PROVIDERS:
+ assert provider_billing(spec) in allowed, f"{spec.id}: unknown billing"
+
+
+def test_gemini_offers_both_aistudio_and_vertex() -> None:
+ """The Gemini brain + TTS must surface BOTH credential paths so a user does
+ not top up an AI-Studio key while Jarvis bills a Vertex service account
+ (the 2026-06-22 forensic). Primary path = AI Studio (API key); the
+ alt_credential = Vertex AI (service account, separate billing)."""
+ for pid in ("gemini", "gemini-flash-tts"):
+ spec = get_spec(pid)
+ assert spec is not None, pid
+ # Primary path is the AI-Studio API key.
+ assert spec.auth_mode == "api_key"
+ assert spec.dashboard_url and "aistudio.google.com" in spec.dashboard_url
+ # The Vertex path is offered as an explicit alternative.
+ assert spec.alt_credential is not None, f"{pid}: missing Vertex alt path"
+ alt = spec.alt_credential
+ assert "vertex" in alt.label.lower()
+ assert alt.billing == "api"
+ assert alt.credential_help
+ assert alt.dashboard_url and "cloud.google.com" in alt.dashboard_url
+
+
+def test_non_gemini_providers_have_no_alt_credential() -> None:
+ """Only Gemini has the AI-Studio-vs-Vertex split today; every other provider
+ keeps a single credential path (alt_credential is None)."""
+ for spec in PROVIDERS:
+ if spec.id in ("gemini", "gemini-flash-tts"):
+ continue
+ assert spec.alt_credential is None, f"{spec.id}: unexpected alt_credential"
+
+
+def test_alt_credential_is_frozen() -> None:
+ alt = AltCredential(
+ label="x", billing="api", credential_help="y", dashboard_url=None,
+ )
+ try:
+ alt.label = "mutated" # type: ignore[misc]
+ except Exception:
+ return
+ raise AssertionError("AltCredential should be frozen")