Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(settings): split API Keys into Voice and Agents
rubenluetke10-beep5e8d4b546787
diff --git a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsxindex 8e47e7cade..f903076c0e 100644--- a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useState, type ReactNode } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { Check, ChevronRight, Loader2 } from "lucide-react";import { useT } from "@/i18n";@@ -7,7 +7,7 @@ import { BrandedSelect } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { Input } from "@/components/ui/input";-import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";+import { SettingsRow, SettingsSection } from "@/views/apikeys/settingsUi";import { fetchAgentAccounts } from "@/lib/agentAccountsApi";import { LiveSubscriptionAccount } from "./LiveSubscriptionAccount";import { useRestartApp } from "@/hooks/useRestartApp";@@ -83,13 +83,15 @@ export async function saveLiveProfile(profile: LiveProfileValue): Promise<void>const capitalize = (value: string) => value.charAt(0).toUpperCase() + value.slice(1);/**- * GPT-Live's own settings: the conversation voice and the thinking model that- * answers with tools. Rendered as two settings groups under the provider's- * connection group on the API Keys page, in the same row grammar as the rest- * of the Settings hub.+ * GPT-Live's own settings: how it is paid for (the ChatGPT subscription or an+ * OpenAI key), the conversation voice and the thinking model that answers with+ * tools — the Voice tab of the API Keys page, in the page's compact row+ * grammar.*/-export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode }: {+export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode, keyField }: {onSaved?: () => void;+ /** The API-key row, shown under the access choice while the key route is picked. */+ keyField?: ReactNode;onAuthModeChange?: (mode: LiveAuthMode, pending: boolean) => void;/** A dedicated provider row fixes its own access without changing the other row. */selectedAuthMode?: LiveAuthMode;@@ -254,51 +256,67 @@ export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode }: {// quiet line instead.const showSave = !ready || dirty;return (- <section aria-label="GPT-Live" className="flex flex-col gap-group" data-testid="live-profile">- <ProfileGroup title={t("live.billing_method")} aside={billingPending- ? <span className="text-sm text-muted-foreground">{t("live.billing_pending")}</span> : undefined}>- <SettingRow label={t("live.billing_method")} control={selectedAuthMode- ? <span className="text-base font-medium text-foreground">{subscription ? "GPT Subscription" : t("live.api_key_mode")}</span>- :- <BrandedSelect className="w-52" value={authMode} disabled={saving}- ariaLabel={t("live.billing_method")}- onValueChange={(mode) => update({ auth_mode: mode as LiveAuthMode })}- options={[- { value: "api_key", label: t("live.api_key_mode") },- { value: "chatgpt_subscription", label: t("live.subscription_mode") },- ]} />- } />- {subscription && !supportsSubscription ? <div role="status" className="flex flex-wrap items-center justify-between gap-3 px-5 py-4">- <p className="text-sm text-muted-foreground">{t("settings_view.wake_word.restart_required")}</p>- <Button disabled={restart.restarting} onClick={() => void restart.restart()}>{restart.buttonLabel}</Button>- </div> : null}- {subscription && supportsSubscription ? <div className="px-5 py-4">- <LiveSubscriptionAccount group={group} accountId={value.subscription_account_id ?? ""}- loading={accounts.isPending} disabled={saving}- voiceStatus={profile.data?.subscription?.account_id === accountId- ? profile.data.subscription.voice_status : "unverified"}- onAccountChange={(subscription_account_id) => update({ subscription_account_id })}- onConnected={() => {- void queryClient.invalidateQueries({ queryKey: ["live-subscription-accounts"] });- void queryClient.invalidateQueries({ queryKey: ["live-profile"] });- void queryClient.invalidateQueries({ queryKey: ["live-options", "chatgpt_subscription"] });- }} />- {accounts.isError ? <p role="alert" className="mt-2 text-sm text-destructive">{t("live.subscription_accounts_failed")}</p> : null}- </div> : null}- </ProfileGroup>- <ProfileGroup- title={t("live.conversation_heading")}- description={t("live.conversation_help")}+ <section aria-label="GPT-Live" className="flex flex-col gap-8" data-testid="live-profile">+ <SettingsSection+ title={t("live.billing_method")}+ headerAction={billingPending+ ? <span className="text-xs text-muted-foreground">{t("live.billing_pending")}</span>+ : ready && !dirty ? (+ <span data-testid="live-profile-saved" className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">+ <Check aria-hidden="true" className="h-3.5 w-3.5 text-accent" />+ {t("live.ready")}+ </span>+ ) : undefined}>- <SettingRow- label={t("live.voice_model")}- control={<span className="text-base font-medium text-foreground">{subscription ? "GPT-Live · ChatGPT" : "GPT-Live 1"}</span>}+ <SettingsRow+ title={t("live.billing_method")}+ description={t(subscription ? "live.subscription_billing" : "live.billing")}+ control={selectedAuthMode+ ? <span className="text-sm font-medium text-foreground">{subscription ? "GPT Subscription" : t("live.api_key_mode")}</span>+ : <BrandedSelect className="w-56" value={authMode} disabled={saving}+ ariaLabel={t("live.billing_method")}+ onValueChange={(mode) => update({ auth_mode: mode as LiveAuthMode })}+ options={[+ { value: "chatgpt_subscription", label: t("live.subscription_mode") },+ { value: "api_key", label: t("live.api_key_mode") },+ ]} />}/>- <SettingRow- label={t("live.voice")}+ {!subscription && keyField}+ {subscription && !supportsSubscription ? (+ <SettingsRow+ title={t("live.subscription_mode")}+ description={t("settings_view.wake_word.restart_required")}+ control={<Button size="sm" disabled={restart.restarting} onClick={() => void restart.restart()}>{restart.buttonLabel}</Button>}+ />+ ) : null}+ {subscription && supportsSubscription ? (+ <SettingsRow title={t("live.subscription_mode")}>+ <LiveSubscriptionAccount group={group} accountId={value.subscription_account_id ?? ""}+ loading={accounts.isPending} disabled={saving}+ voiceStatus={profile.data?.subscription?.account_id === accountId+ ? profile.data.subscription.voice_status : "unverified"}+ onAccountChange={(subscription_account_id) => update({ subscription_account_id })}+ onConnected={() => {+ void queryClient.invalidateQueries({ queryKey: ["live-subscription-accounts"] });+ void queryClient.invalidateQueries({ queryKey: ["live-profile"] });+ void queryClient.invalidateQueries({ queryKey: ["live-options", "chatgpt_subscription"] });+ }} />+ {accounts.isError ? <p role="alert" className="mt-2 text-xs text-destructive">{t("live.subscription_accounts_failed")}</p> : null}+ </SettingsRow>+ ) : null}+ </SettingsSection>++ <SettingsSection title={t("live.conversation_heading")}>+ <SettingsRow+ title={t("live.voice_model")}+ description={t("live.conversation_help")}+ control={<span className="text-sm font-medium text-foreground">{subscription ? "GPT-Live · ChatGPT" : "GPT-Live 1"}</span>}+ />+ <SettingsRow+ title={t("live.voice")}control={<BrandedSelect- className="w-52"+ className="w-56"value={voice}disabled={saving || (subscription && !options.data)}onValueChange={(selected) => choose(subscription ? { subscription_voice: selected } : { voice: selected })}@@ -310,117 +328,95 @@ export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode }: {/>}/>- </ProfileGroup>+ </SettingsSection>- <div className="flex flex-col gap-4">- <ProfileGroup- title={t("live.thinking_heading")}+ <SettingsSection title={t("live.thinking_heading")}>+ <SettingsRow+ title={t("live.thinking_model")}description={t(subscription ? "live.subscription_thinking_help" : "live.thinking_help")}- >- <SettingRow- label={t("live.thinking_model")}- control={- <BrandedSelect- className="w-52"- value={backendModel}- disabled={saving || (subscription && !options.data)}- onValueChange={chooseModel}- ariaLabel={t("live.thinking_model")}- placeholder={t("live.choose_model")}- searchPlaceholder={t("live.search_models")}- options={modelOptions}- />- }- />- <SettingRow- label={t("live.reasoning")}- control={- <BrandedSelect- className="w-52"- value={reasoningEffort}- disabled={saving}- onValueChange={(selected) => choose(subscription ? { subscription_reasoning_effort: selected } : { reasoning_effort: selected })}- ariaLabel={t("live.reasoning")}- options={efforts.map(- (effort) => ({- value: effort,- label: effort ? capitalize(effort) : t("live.model_default"),- }),- )}- />- }- />- {!subscription && <SettingRow- label={<label htmlFor="live-web-search">{t("live.web_search")}</label>}- hint={t("live.web_search_help")}- control={- <Switch- id="live-web-search"- checked={value.web_search}- disabled={saving}- onCheckedChange={(web_search) => choose({ web_search })}- aria-label={t("live.web_search")}- />- }- />}- <details className="group">- <summary className="flex cursor-pointer list-none items-center gap-2 px-5 py-4 text-base font-medium text-foreground transition-colors hover:bg-secondary [&::-webkit-details-marker]:hidden">- <ChevronRight- aria-hidden="true"- className="h-4 w-4 text-muted-foreground transition-transform group-open:rotate-90 motion-reduce:transition-none"- />- {t("live.prompts")}- </summary>- <div className="grid gap-4 px-5 pb-5 md:grid-cols-2">- <label className="space-y-1.5">- <span className="block text-sm font-medium text-muted-foreground">- {t("live.conversation_prompt")}- </span>- <Textarea- rows={3}- value={value.instructions}- onChange={(event) => update({ instructions: event.target.value })}- />- </label>- <label className="space-y-1.5">- <span className="block text-sm font-medium text-muted-foreground">- {t("live.backend_prompt")}- </span>- <Textarea- rows={3}- value={value.backend_instructions}- onChange={(event) =>- update({ backend_instructions: event.target.value })- }- />- </label>- {!subscription ? <label className="space-y-1.5 md:col-span-2">- <span className="block text-sm font-medium text-muted-foreground">- {t("live.custom_model")}- </span>- <Input- value={value.backend_model}- onChange={(event) => update({ backend_model: event.target.value })}- />- </label> : null}- </div>- </details>- </ProfileGroup>+ control={+ <BrandedSelect+ className="w-56"+ value={backendModel}+ disabled={saving || (subscription && !options.data)}+ onValueChange={chooseModel}+ ariaLabel={t("live.thinking_model")}+ placeholder={t("live.choose_model")}+ searchPlaceholder={t("live.search_models")}+ options={modelOptions}+ />+ }+ />+ <SettingsRow+ title={t("live.reasoning")}+ control={+ <BrandedSelect+ className="w-56"+ value={reasoningEffort}+ disabled={saving}+ onValueChange={(selected) => choose(subscription ? { subscription_reasoning_effort: selected } : { reasoning_effort: selected })}+ ariaLabel={t("live.reasoning")}+ options={efforts.map((effort) => ({+ value: effort,+ label: effort ? capitalize(effort) : t("live.model_default"),+ }))}+ />+ }+ />+ {!subscription && <SettingsRow+ title={<label htmlFor="live-web-search">{t("live.web_search")}</label>}+ description={t("live.web_search_help")}+ control={+ <Switch+ id="live-web-search"+ checked={value.web_search}+ disabled={saving}+ onCheckedChange={(web_search) => choose({ web_search })}+ aria-label={t("live.web_search")}+ />+ }+ />}+ <details className="group">+ <summary className="flex cursor-pointer list-none items-center gap-2 px-4 py-3 text-sm font-medium text-foreground transition-colors hover:bg-secondary/50 [&::-webkit-details-marker]:hidden">+ <ChevronRight+ aria-hidden="true"+ className="h-4 w-4 text-muted-foreground transition-transform group-open:rotate-90 motion-reduce:transition-none"+ />+ {t("live.prompts")}+ </summary>+ <div className="grid gap-4 px-4 pb-4 md:grid-cols-2">+ <label className="space-y-1.5">+ <span className="block text-xs font-medium text-muted-foreground">{t("live.conversation_prompt")}</span>+ <Textarea rows={3} value={value.instructions} onChange={(event) => update({ instructions: event.target.value })} />+ </label>+ <label className="space-y-1.5">+ <span className="block text-xs font-medium text-muted-foreground">{t("live.backend_prompt")}</span>+ <Textarea rows={3} value={value.backend_instructions} onChange={(event) => update({ backend_instructions: event.target.value })} />+ </label>+ {!subscription ? <label className="space-y-1.5 md:col-span-2">+ <span className="block text-xs font-medium text-muted-foreground">{t("live.custom_model")}</span>+ <Input value={value.backend_model} onChange={(event) => update({ backend_model: event.target.value })} />+ </label> : null}+ </div>+ </details>+ </SettingsSection>- <div className="flex flex-col gap-3 px-1">- {options.isError ? <p role="alert" className="text-sm text-destructive">{t("live.options_failed")}</p> : null}- {!subscription && !profile.data?.key_ready && (- <p role="status" className="text-sm text-warning">- {t("live.key_required")}- </p>- )}- <div className="flex flex-wrap items-center justify-between gap-3">- <div className="max-w-md space-y-1 text-sm text-muted-foreground">- <p>{t(subscription ? "live.subscription_billing" : "live.billing")}</p>- <p>{t("live.agents_separate")}</p>- </div>+ <div className="flex flex-col gap-3 px-1">+ {options.isError ? <p role="alert" className="text-xs text-destructive">{t("live.options_failed")}</p> : null}+ {!subscription && !profile.data?.key_ready && (+ <p role="status" className="text-xs text-warning">{t("live.key_required")}</p>+ )}+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="max-w-md text-xs text-muted-foreground">{t("live.agents_separate")}</p>+ <div className="flex items-center gap-2">+ {!subscription && sameCredentials && saved?.configured && !profile.data?.agent_configured && (+ <Button variant="outline" size="sm" disabled={saving} onClick={() => void useForAgents()}>+ {t("live.use_for_agents")}+ </Button>+ )}{showSave ? (<Button+ size="sm"disabled={saving || !backendModel.trim() || !credentialReady || !effortAvailable ||(subscription && (!options.data || options.isError || !models.some((model) => model.id === backendModel)))}onClick={() => void save()}@@ -428,38 +424,11 @@ export function LiveProfile({ onSaved, onAuthModeChange, selectedAuthMode }: {{saving && <Loader2 className="animate-spin" />}{ready ? t("live.save_changes") : t("live.save")}</Button>- ) : (- <span- data-testid="live-profile-saved"- className="inline-flex items-center gap-1.5 text-sm font-medium text-foreground"- >- {saving ? (- <Loader2 aria-hidden="true" className="h-4 w-4 animate-spin text-muted-foreground" />- ) : (- <Check aria-hidden="true" className="h-4 w-4 text-accent" />- )}- {t("live.ready")}- </span>- )}+ ) : null}</div>- {!subscription && sameCredentials && saved?.configured && !profile.data?.agent_configured && (- <div>- <Button variant="outline" size="sm" disabled={saving} onClick={() => void useForAgents()}>- {t("live.use_for_agents")}- </Button>- </div>- )}- {error && (- <p role="alert" className="text-sm text-destructive">- {error}- </p>- )}- {message && (- <p role="status" className="text-sm text-muted-foreground">- {message}- </p>- )}</div>+ {error && <p role="alert" className="text-xs text-destructive">{error}</p>}+ {message && <p role="status" className="text-xs text-muted-foreground">{message}</p>}</div></section>);diff --git a/jarvis/ui/web/frontend/src/components/providers/VoiceProviderSettings.tsx b/jarvis/ui/web/frontend/src/components/providers/VoiceProviderSettings.tsxdeleted file mode 100644index 6f3c02699a..0000000000--- a/jarvis/ui/web/frontend/src/components/providers/VoiceProviderSettings.tsx+++ /dev/null@@ -1,179 +0,0 @@-import { useCallback, useState } from "react";-import { Check, Radio } from "lucide-react";-import { LiveProfile, type LiveAuthMode } from "./LiveProfile";-import { ProviderCard } from "./ProviderTierSection";-import { ProviderLogo } from "./ProviderLogo";-import { Button } from "@/components/ui/button";-import { useVoiceMode } from "@/hooks/useVoiceMode";-import {- type ProviderDescriptor,- type ProviderTier,- type SectionHealth,- sectionHealthForSubject,-} from "@/hooks/useProviders";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";--export function VoiceProviderSettings({- providers,- loading,- error,- onChanged,- onActivateOptimistic,- health,- localMode,- onDisableLocalMode,-}: {- providers: ProviderDescriptor[];- loading: boolean;- error: string | null;- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- health?: SectionHealth;- localMode: boolean;- onDisableLocalMode: () => void;-}) {- const t = useT();- const runtime = useVoiceMode();- const [inspectedId, setInspectedId] = useState<string | null>(null);- const [liveAuthMode, setLiveAuthMode] = useState<LiveAuthMode | null>(null);- const [liveBillingPending, setLiveBillingPending] = useState(false);- const setLiveBilling = useCallback((mode: LiveAuthMode, pending: boolean) => {- setLiveAuthMode(mode);- setLiveBillingPending(pending);- }, []);- const choices = providers.filter(- (provider) =>- provider.tier === "realtime" &&- (!localMode || provider.billing === "local"),- );- const selected =- choices.find((provider) => provider.id === inspectedId) ??- choices.find((provider) => provider.active) ??- choices[0];- return (- <section- role="tabpanel"- aria-label={t("live.setup_title")}- className="space-y-5"- >- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h2 className="text-base font-semibold tracking-tight">- {t("live.setup_title")}- </h2>- <p className="mt-1 max-w-xl text-sm leading-relaxed text-muted-foreground">- {t("live.setup_description")}- </p>- </div>- <span className="inline-flex items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-xs text-muted-foreground">- <Radio className="h-3 w-3" />- {runtime.sessionActive ? t("live.call_active") : t("live.next_call")}- </span>- </div>- {runtime.sessionActive && runtime.activeSessionMode === "pipeline" && (- <p- role="status"- data-testid="voice-engine-runtime-status"- className="rounded-lg border border-warning/30 px-3 py-2 text-sm text-warning"- >- {t("live.pipeline_fallback")}- </p>- )}- {runtime.lastStartError && (- <p- role="alert"- className="rounded-lg border border-destructive/30 px-3 py-2 text-sm text-destructive"- >- {runtime.lastStartError.message}- </p>- )}- {loading && !choices.length && (- <p role="status" className="text-sm text-muted-foreground">- {t("live.loading")}- </p>- )}- {error && (- <div- role="alert"- className="flex items-center gap-3 text-sm text-destructive"- >- <span>{error}</span>- <Button variant="outline" onClick={onChanged}>- {t("common.retry")}- </Button>- </div>- )}- <div- role="group"- aria-label={t("live.provider_selection")}- className="grid grid-cols-2 gap-2 lg:grid-cols-4"- >- {choices.map((provider) => (- <button- key={provider.id}- type="button"- aria-pressed={selected?.id === provider.id}- onClick={() => setInspectedId(provider.id)}- className={cn(- "flex min-w-0 items-center gap-2.5 rounded-xl border p-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- selected?.id === provider.id- ? "border-foreground/30 bg-secondary"- : "border-border bg-card hover:bg-secondary/60",- )}- >- <ProviderLogo providerId={provider.id} label={provider.label} />- <span className="min-w-0 flex-1">- <span className="block truncate text-sm font-medium">- {provider.label}- </span>- <span className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">- {provider.active && <Check className="h-3 w-3" />}- {provider.active- ? t("live.active")- : provider.billing === "local"- ? t("live.local_provider")- : provider.configured- ? t("live.connected")- : t("live.connect")}- </span>- </span>- </button>- ))}- </div>- {selected && (- <div className="overflow-hidden rounded-xl border border-border bg-card">- <ProviderCard- key={selected.id}- descriptor={selected}- onChanged={onChanged}- onActivateOptimistic={onActivateOptimistic}- autoActivateOnSave={false}- hideCredentialControls={selected.configuration_surface === "live" && liveAuthMode !== "api_key"}- billingOverride={selected.configuration_surface === "live" && liveAuthMode- ? liveAuthMode === "chatgpt_subscription" ? "subscription" : "api" : undefined}- billingPending={selected.configuration_surface === "live" && liveBillingPending}- health={- selected.active- ? sectionHealthForSubject(health, selected.id)- : undefined- }- configuration={- selected.configuration_surface === "live" ? (- <LiveProfile onSaved={onChanged} onAuthModeChange={setLiveBilling} />- ) : undefined- }- />- </div>- )}- {localMode && !choices.length && (- <Button variant="outline" onClick={onDisableLocalMode}>- {t("live.show_cloud")}- </Button>- )}- <p className="text-xs leading-relaxed text-muted-foreground">- {t("live.agents_separate")}- </p>- </section>- );-}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.jsonindex 7a03015e59..af146c13be 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json@@ -1,6 +1,6 @@{"providers_page": {- "subtitle": "Verbinde jeden KI-Anbieter einmal – mit deinem Abo oder einem Schlüssel – und wähle, wofür {name} ihn nutzt.",+ "subtitle": "Die Live-Stimme läuft über OpenAI. Die Agenten laufen über jedes Abo oder jeden Schlüssel, den du hier verbindest.","checking": "Wird geprüft…","checked_now": "Gerade geprüft","checked_minutes": "Vor {0} Min. geprüft",@@ -96,6 +96,27 @@"restart_title": "Neu starten, um das Update abzuschließen","restart_desc": "Die neue Anbieter-Seite braucht einen Neustart des App-Hintergrunddienstes. Das dauert etwa zehn Sekunden.","restart_action": "Jetzt neu starten",+ "tab_voice": "Stimme",+ "tab_agents": "Agenten",+ "tab_more": "Mehr",+ "subscriptions_title": "Abos",+ "keys_title": "API-Keys",+ "authenticated": "Angemeldet",+ "authenticated_as": "Angemeldet · {0}",+ "not_installed": "Nicht installiert",+ "not_signed_in": "Nicht angemeldet",+ "account": "Konto",+ "agents_needs_login": "Melde dich zuerst an, um die Agenten darüber laufen zu lassen.",+ "agents_use_for": "Agenten über {0} laufen lassen",+ "runtime": "Laufzeit",+ "binary_path": "Programmpfad",+ "binary_path_hint": "Das Kommandozeilen-Tool hinter dieser Anmeldung.",+ "cli_check": "Prüfen",+ "cli_check_hint": "Findet das Tool und liest Version und Anmeldung.",+ "key_saved_short": "Schlüssel gespeichert",+ "key_missing_short": "Kein Schlüssel",+ "key_desc_short": "Ein Schlüssel für alles, was dieser Anbieter macht. Abrechnung pro Nutzung.",+ "separate_title": "Eigene Schlüssel","accounts_title": "Mehrere Anmeldungen pro Tool"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.jsonindex b110a89286..417a3763d3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json@@ -1,6 +1,6 @@{"providers_page": {- "subtitle": "Connect each AI company once — with your subscription or one key — and choose what {name} uses it for.",+ "subtitle": "The live voice runs on OpenAI. The agents run on any subscription or key you connect here.","checking": "Checking…","checked_now": "Checked just now","checked_minutes": "Checked {0} min ago",@@ -96,6 +96,27 @@"restart_title": "Restart to finish the update","restart_desc": "The new provider page needs the app's background service to restart once. It takes about ten seconds.","restart_action": "Restart now",+ "tab_voice": "Voice",+ "tab_agents": "Agents",+ "tab_more": "More",+ "subscriptions_title": "Subscriptions",+ "keys_title": "API keys",+ "authenticated": "Authenticated",+ "authenticated_as": "Authenticated · {0}",+ "not_installed": "Not installed",+ "not_signed_in": "Not signed in",+ "account": "Account",+ "agents_needs_login": "Sign in first to run the agents on it.",+ "agents_use_for": "Run the agents on {0}",+ "runtime": "Runtime",+ "binary_path": "Binary path",+ "binary_path_hint": "The command-line tool this sign-in runs.",+ "cli_check": "Check",+ "cli_check_hint": "Finds the tool, reads its version and sign-in.",+ "key_saved_short": "Key saved",+ "key_missing_short": "No key",+ "key_desc_short": "One key for everything this provider does. Billed per use.",+ "separate_title": "Separate keys","accounts_title": "Several sign-ins per tool"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.jsonindex 8ffcf7baf6..6e743c7fcf 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json@@ -1,6 +1,6 @@{"providers_page": {- "subtitle": "Conecta cada empresa de IA una sola vez — con tu suscripción o una clave — y elige para qué la usa {name}.",+ "subtitle": "La voz en directo funciona con OpenAI. Los agentes funcionan con cualquier suscripción o clave que conectes aquí.","checking": "Comprobando…","checked_now": "Comprobado ahora","checked_minutes": "Comprobado hace {0} min",@@ -96,6 +96,27 @@"restart_title": "Reinicia para terminar la actualización","restart_desc": "La nueva página de proveedores necesita reiniciar una vez el servicio de la app. Tarda unos diez segundos.","restart_action": "Reiniciar ahora",+ "tab_voice": "Voz",+ "tab_agents": "Agentes",+ "tab_more": "Más",+ "subscriptions_title": "Suscripciones",+ "keys_title": "Claves API",+ "authenticated": "Sesión iniciada",+ "authenticated_as": "Sesión iniciada · {0}",+ "not_installed": "No instalado",+ "not_signed_in": "Sin sesión iniciada",+ "account": "Cuenta",+ "agents_needs_login": "Inicia sesión primero para ejecutar los agentes con ella.",+ "agents_use_for": "Ejecutar los agentes con {0}",+ "runtime": "Ejecución",+ "binary_path": "Ruta del programa",+ "binary_path_hint": "La herramienta de línea de comandos de este inicio de sesión.",+ "cli_check": "Comprobar",+ "cli_check_hint": "Busca la herramienta y lee su versión y su sesión.",+ "key_saved_short": "Clave guardada",+ "key_missing_short": "Sin clave",+ "key_desc_short": "Una clave para todo lo que hace este proveedor. Se cobra por uso.",+ "separate_title": "Claves propias","accounts_title": "Varias sesiones por herramienta"}}diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsxindex 47f57a4e79..f6f48d2365 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.providers.test.tsx@@ -1,6 +1,6 @@/**- * The provider page: every company once, one key per company, and the jobs it- * powers switchable where they are shown.+ * The provider page: a Voice tab on OpenAI GPT-Live, and an Agents tab with the+ * subscription logins and the API keys as lists beside their settings.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";@@ -27,6 +27,10 @@ vi.mock("@/views/TelephonyView", () => ({ TelephonyPanel: () => null }));vi.mock("@/components/AgentAccountsPanel", () => ({ AgentAccountsPanel: () => null }));vi.mock("@/components/PromptWriterCard", () => ({ PromptWriterCard: () => null }));vi.mock("@/components/SubagentModelCard", () => ({ SubagentModelCard: () => null }));+// GPT-Live's own form has its own tests; here it only has to place the key row.+vi.mock("@/components/providers/LiveProfile", () => ({+ LiveProfile: ({ keyField }: { keyField?: React.ReactNode }) => <div data-testid="live-profile">{keyField}</div>,+}));import { _resetProvidersCacheForTests } from "@/hooks/useProviders";import { ApiKeysView } from "@/views/ApiKeysView";@@ -61,6 +65,7 @@ const AGENTS = {provider_slug: null, model_override: null, sub_model_override: "", model_resolved: null,mapping: [{ jarvis: "claude-api", label: "Claude", key_set: true, is_active_brain: false, billing: "subscription_or_api" },+ { jarvis: "openai", label: "OpenAI", key_set: false, is_active_brain: false, billing: "api" },{ jarvis: "gemini", label: "Google Gemini", key_set: true, is_active_brain: true, billing: "api" },],};@@ -116,25 +121,43 @@ function renderPage() {);}-describe("ApiKeysView — one entry per company", () => {- it("lists every company once, with how it is connected", async () => {+function openAgents() {+ fireEvent.click(screen.getByRole("tab", { name: "Agents" }));+}++beforeEach(() => {+ try {+ localStorage.removeItem("jarvis.apikeys.tab");+ } catch {+ /* no storage in this environment */+ }+});++describe("ApiKeysView — Voice", () => {+ it("opens on the voice tab with one OpenAI key row", async () => {renderPage();- const list = await screen.findByTestId("provider-family-list");- expect(within(list).getByTestId("provider-family-claude-api").textContent).toContain("Anthropic");- expect(within(list).getByTestId("provider-family-claude-api").textContent).toContain("[email protected]");- expect(within(list).getByTestId("provider-family-gemini").textContent).toContain("API key");+ const voice = await screen.findByTestId("apikeys-voice");+ expect(within(voice).getByTestId("voice-key")).toBeTruthy();});+});- it("opens on the company that carries the voice and tags what it powers", async () => {+describe("ApiKeysView — Agents", () => {+ it("lists the subscription logins with account and version", async () => {renderPage();- const detail = await screen.findByTestId("provider-family-detail-gemini");- expect(within(detail).getByTestId("provider-use-voice")).toBeTruthy();- expect(within(detail).getByTestId("provider-use-agents")).toBeTruthy();+ await screen.findByTestId("apikeys-voice");+ openAgents();+ const claude = await screen.findByTestId("subscription-claude_cli");+ expect(claude.textContent).toContain("Claude");+ expect(claude.textContent).toContain("[email protected] · Claude Max");+ expect(claude.textContent).toContain("v2.1.0");});it("saves one key for the whole company", async () => {renderPage();- fireEvent.click(await screen.findByTestId("provider-family-claude-api"));+ await screen.findByTestId("apikeys-voice");+ openAgents();+ const list = await screen.findByTestId("api-key-list");+ fireEvent.click(within(list).getByRole("button", { name: "Anthropic" }));const input = await screen.findByTestId("provider-key-input");fireEvent.change(input, { target: { value: "sk-ant-api03-test" } });fireEvent.click(screen.getByTestId("provider-key-save"));@@ -146,6 +169,10 @@ describe("ApiKeysView — one entry per company", () => {it("moves a feature with its own key back onto the main key", async () => {renderPage();+ await screen.findByTestId("apikeys-voice");+ openAgents();+ const list = await screen.findByTestId("api-key-list");+ fireEvent.click(within(list).getByRole("button", { name: "Google Gemini" }));const row = await screen.findByTestId("provider-separate-key-realtime_gemini_api_key");fireEvent.click(within(row).getByRole("button"));await waitFor(() =>@@ -153,22 +180,25 @@ describe("ApiKeysView — one entry per company", () => {);});- it("switches the agents onto another company in one click", async () => {+ it("runs the agents on a subscription with its switch", async () => {renderPage();- fireEvent.click(await screen.findByTestId("provider-family-claude-api"));- fireEvent.click(await screen.findByTestId("provider-agent-use-claude-api"));+ await screen.findByTestId("apikeys-voice");+ openAgents();+ const claude = await screen.findByTestId("subscription-claude_cli");+ fireEvent.click(within(claude).getByRole("switch"));await waitFor(() => {const post = calls.find((c) => c.url === "/api/jarvis-agent/switch");expect(post?.body).toMatchObject({ provider: "claude-api" });});});- it("shows the subscription sign-in with the account and the CLI behind it", async () => {+ it("shows the sign-in with the account and the binary behind it", async () => {renderPage();- fireEvent.click(await screen.findByTestId("provider-family-claude-api"));- const section = await screen.findByTestId("provider-subscription");- expect(section.textContent).toContain("[email protected]");- expect(section.textContent).toContain("2.1.0");- expect(within(section).getByTestId("provider-subscription-disconnect")).toBeTruthy();+ await screen.findByTestId("apikeys-voice");+ openAgents();+ const detail = await screen.findByTestId("subscription-detail-claude_cli");+ expect(detail.textContent).toContain("[email protected]");+ expect(within(detail).getByTestId("subscription-disconnect")).toBeTruthy();+ expect((within(detail).getByLabelText("Binary path") as HTMLInputElement).value).toBe("/usr/bin/claude");});});diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsxindex 436ca8ea59..d21e8ee6dc 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx@@ -3,7 +3,7 @@** Design (2026-06-09): the former standalone "Telephony" sidebar screen was* folded into the API-Keys view as another section (header + the existing- * status/credentials/scripts/calls cards), shown below the providers. These+ * status/credentials/scripts/calls cards), shown on the page's "More" tab. These* tests pin that the section header renders and that the embedded TelephonyPanel* loads and shows live telephony data from /api/telephony/*.*/@@ -149,6 +149,8 @@ describe("ApiKeysView — embedded Telephony tier", () => {it("renders the Telephony tier header inside the API-Keys view", async () => {installFetchMock(routes());renderView();+ // Telephony lives on the page's "More" tab.+ fireEvent.click(await screen.findByRole("tab", { name: "More" }));// English is the test-default locale; tier_telephony => "Telephony".await waitFor(() => expect(screen.getByText("Telephony")).toBeTruthy());@@ -157,6 +159,8 @@ describe("ApiKeysView — embedded Telephony tier", () => {it("loads live telephony status (Charon voice) from /api/telephony", async () => {installFetchMock(routes());renderView();+ // Telephony lives on the page's "More" tab.+ fireEvent.click(await screen.findByRole("tab", { name: "More" }));await waitFor(() => {expect(screen.getByTestId("status-tts-voice").textContent).toBe("Charon");@@ -169,6 +173,8 @@ describe("ApiKeysView — embedded Telephony tier", () => {it("offers a 'Setup script' button that navigates to the telephony-setup page", async () => {installFetchMock(routes());renderView();+ // Telephony lives on the page's "More" tab.+ fireEvent.click(await screen.findByRole("tab", { name: "More" }));const btn = await waitFor(() =>screen.getByRole("button", { name: /Setup script/i }),diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 7d8eab3fd1..00bbfaa4e0 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1,40 +1,60 @@import { useEffect, useState } from "react";-import { Bot, KeyRound, Loader2, Phone, RefreshCw } from "lucide-react";+import { Loader2, Phone, RefreshCw } from "lucide-react";import { PageHeader } from "@/components/layout/PageHeader";-import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";-import { SubagentModelCard, type SubagentStatus } from "@/components/SubagentModelCard";-import { PromptWriterCard } from "@/components/PromptWriterCard";-import { useTierHealth } from "@/components/providers/ProviderTierSection";+import { LiveProfile } from "@/components/providers/LiveProfile";import { Button } from "@/components/ui/button";import { TelephonyPanel } from "@/views/TelephonyView";import { WikiProviderCard } from "@/views/settings/WikiProviderCard";import { JarvisApiGroup } from "@/views/settings/JarvisApiGroup";import { TeamProxyGroup } from "@/views/settings/TeamProxyGroup";-import { ProvidersPanel } from "@/views/apikeys/ProvidersPanel";+import { AgentsTab } from "@/views/apikeys/AgentsTab";+import { KeyField } from "@/views/apikeys/KeyField";+import { SettingsSection } from "@/views/apikeys/settingsUi";import { useProviders, useSectionHealth } from "@/hooks/useProviders";import { useProviderFamilies } from "@/lib/providerFamilies";import { useLocaleChunk, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";++const TABS = ["voice", "agents", "more"] as const;+type Tab = (typeof TABS)[number];+const TAB_STORAGE_KEY = "jarvis.apikeys.tab";++function initialTab(): Tab {+ try {+ const saved = localStorage.getItem(TAB_STORAGE_KEY);+ if (saved && (TABS as readonly string[]).includes(saved)) return saved as Tab;+ } catch {+ // Private mode / no storage: open on the first tab.+ }+ return "voice";+}/**- * API Keys — every AI company once, each with one way to sign in and one key.+ * API Keys, in three parts behind one switch:*- * The page used to be split by feature (live voice, agents, the install key,- * advanced), so one company appeared on several tabs with several keys. Now- * a company is connected once — its subscription login or a single key that- * every feature reads — and its settings say what the assistant uses it for,- * with each job switchable where it is shown. Below the providers sit the- * settings that belong to no single company: the agents' model and accounts,- * the install's own key, and the optional integrations.+ * - Voice: the live voice runs on OpenAI GPT-Live — paid with the ChatGPT+ * subscription or one OpenAI key — with only its essential settings;+ * - Agents: the subscription logins and the API keys the background agents+ * can run on, each as a list beside the selected entry's settings;+ * - More: the install's own key and the optional integrations.*/export function ApiKeysView() {const t = useT();// The page's own strings load with it; nothing paints raw keys meanwhile.const stringsReady = useLocaleChunk("providers");- const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();+ const { providers, refetch } = useProviders();const families = useProviderFamilies();const { health } = useSectionHealth();- const tierHealth = useTierHealth(providers);- const refreshing = families.loading;+ const [tab, setTab] = useState<Tab>(initialTab);+ const choose = (next: Tab) => {+ setTab(next);+ try {+ localStorage.setItem(TAB_STORAGE_KEY, next);+ } catch {+ // Remembering the tab is a convenience; without storage it resets.+ }+ };if (!stringsReady) {return (@@ -48,7 +68,6 @@ export function ApiKeysView() {<div className="flex h-full min-h-0 flex-col" data-tour="apikeys-page"><div className="shrink-0 px-8"><PageHeader- icon={<KeyRound />}title={t("apikeys_view.title")}description={t("providers_page.subtitle")}actions={@@ -57,53 +76,122 @@ export function ApiKeysView() {variant="ghost"className="text-muted-foreground"data-testid="providers-refresh"- disabled={refreshing}+ disabled={families.loading}onClick={() => {refetch();void families.reload();}}>- {refreshing ? <Loader2 className="animate-spin" /> : <RefreshCw />}+ {families.loading ? <Loader2 className="animate-spin" /> : <RefreshCw />}<CheckedAgo at={families.checkedAt} /></Button>}/>+ <TabSwitch value={tab} onChange={choose} /></div><divdata-testid="api-keys-provider-scroll"- className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-8 pb-10 pt-2"+ className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-8 pb-10 pt-6">- <div className="profile-rise flex w-full flex-col gap-12">- <ProvidersPanel- data={families}- providers={providers}- providersLoading={loading}- providersError={error}- health={health}- realtimeHealth={tierHealth.realtime}- onProvidersChanged={refetch}- onActivateOptimistic={setActiveOptimistic}+ <div key={tab} role="tabpanel" id="apikeys-panel" aria-labelledby={`apikeys-tab-${tab}`} className="profile-rise w-full">+ {tab === "voice" && <VoiceTab data={families} onSaved={refetch} />}+ {tab === "agents" &&+ (families.error === "restart_required" ? (+ <RestartNeeded />+ ) : (+ <AgentsTab data={families} providers={providers} health={health} onProvidersChanged={refetch} />+ ))}+ {tab === "more" && <MoreTab />}+ </div>+ </div>+ </div>+ );+}++/** A segmented switch between the page's parts. */+function TabSwitch({ value, onChange }: { value: Tab; onChange: (tab: Tab) => void }) {+ const t = useT();+ return (+ <div+ role="tablist"+ aria-label={t("apikeys_view.title")}+ data-testid="api-keys-category-tabs"+ className="inline-flex rounded-lg border border-border/60 bg-card/40 p-0.5"+ >+ {TABS.map((tab) => (+ <button+ key={tab}+ type="button"+ role="tab"+ id={`apikeys-tab-${tab}`}+ aria-selected={value === tab}+ aria-controls="apikeys-panel"+ onClick={() => onChange(tab)}+ className={cn(+ "h-7 rounded-md px-3 text-sm font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ value === tab ? "bg-secondary text-foreground" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`providers_page.tab_${tab}`)}+ </button>+ ))}+ </div>+ );+}++/**+ * The live voice is OpenAI GPT-Live — the one live speech-to-speech model the+ * assistant runs — so this tab is that one provider: how it is paid for and+ * its essential settings.+ */+function VoiceTab({ data, onSaved }: { data: ReturnType<typeof useProviderFamilies>; onSaved: () => void }) {+ const openai = data.families?.find((family) => family.id === "openai");+ const slot = openai?.key_slot ?? "openai_api_key";+ return (+ <div data-testid="apikeys-voice" className="max-w-4xl">+ <LiveProfile+ onSaved={onSaved}+ keyField={+ <KeyField+ slot={slot}+ present={openai?.key_present ?? false}+ providerLabel="OpenAI"+ dashboardUrl={openai?.dashboard_url}+ onChanged={() => void data.reload()}+ testId="voice-key"/>- <AgentSettings />- <section className="flex flex-col gap-3">- <SectionTitle title={t("apikeys_view.jarvis_key_title")} description={t("apikeys_view.jarvis_key_desc")} />- <JarvisApiGroup />- </section>- <section className="flex flex-col gap-3">- <SectionTitle title={t("apikeys_view.advanced_title")} description={t("apikeys_view.advanced_desc")} />- <div className="space-y-4">- <TeamProxyGroup />- <TelephonySection />- <WikiProviderCard />- </div>- {/* Nominative-use trademark notice: provider and integration names- and logos belong to their owners and only identify what you- connect to (see TRADEMARK.md). */}- <p className="px-1 pt-2 text-sm text-muted-foreground">{t("apikeys_view.trademark_notice")}</p>+ }+ />+ </div>+ );+}++/** The install's own key and the optional integrations. */+function MoreTab() {+ const t = useT();+ return (+ <div className="flex max-w-4xl flex-col gap-10">+ <SettingsSection title={t("apikeys_view.jarvis_key_title")} plain>+ <JarvisApiGroup />+ </SettingsSection>+ <SettingsSection title={t("apikeys_view.advanced_title")} plain>+ <div className="space-y-4">+ <TeamProxyGroup />+ <section>+ <h3 className="mb-3 inline-flex items-center gap-2 text-sm font-medium text-muted-foreground">+ <Phone aria-hidden="true" className="h-4 w-4" /> {t("apikeys_view.tier_telephony")}+ </h3>+ <TelephonyPanel /></section>+ <WikiProviderCard /></div>- </div>+ </SettingsSection>+ {/* Nominative-use trademark notice: provider and integration names and+ logos belong to their owners and only identify what you connect to+ (see TRADEMARK.md). */}+ <p className="px-1 text-xs text-muted-foreground">{t("apikeys_view.trademark_notice")}</p></div>);}@@ -127,69 +215,48 @@ function CheckedAgo({ at }: { at: number | null }) {);}-function SectionTitle({ title, description }: { title: string; description: string }) {- return (- <div className="px-1">- <h2 className="text-lg font-semibold text-foreground-strong">{title}</h2>- <p className="mt-0.5 text-base text-muted-foreground">{description}</p>- </div>- );-}-/**- * Settings that belong to the agents rather than to one company: the model a- * worker runs, who writes the task briefs, and the several logins a person- * can hold per command-line tool.+ * The window runs a newer page than its backend: the bundle reloads on its+ * own after an update, the server does not. One sentence and one button,+ * instead of an error that suggests something is broken.*/-function AgentSettings() {+function RestartNeeded() {const t = useT();- const [status, setStatus] = useState<SubagentStatus | null>(null);- const reload = async () => {+ const pushToast = useEventStore((s) => s.pushToast);+ const [restarting, setRestarting] = useState(false);++ async function restart() {+ setRestarting(true);try {- const res = await fetch("/api/jarvis-agent/status", { cache: "no-store" });- if (res.ok) setStatus((await res.json()) as SubagentStatus);+ const response = await fetch("/api/settings/restart-app", { method: "POST" });+ if (response.status === 409) {+ pushToast("warning", t("topbar.restart_missions_running"));+ setRestarting(false);+ return;+ }+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ // The window closes and relaunches; the button stays busy until then.} catch (cause) {- // The model card simply stays hidden; the provider list above reports- // the same endpoint's failure.- console.debug("agent status unavailable", cause);+ pushToast("error", (cause as Error).message);+ setRestarting(false);}- };- useEffect(() => {- void reload();- const onChange = () => void reload();- window.addEventListener("jarvis:agent-switched", onChange);- return () => window.removeEventListener("jarvis:agent-switched", onChange);- }, []);+ }return (- <section data-testid="provider-agent-settings" className="flex flex-col gap-3">- <SectionTitle title={t("providers_page.agent_settings_title")} description={t("providers_page.agent_settings_desc")} />- <div className="grid gap-4 xl:grid-cols-2">- {status && <SubagentModelCard status={status} onSaved={() => void reload()} />}- <PromptWriterCard />+ <div+ role="status"+ data-testid="providers-restart-needed"+ className="flex items-center gap-4 rounded-xl border border-border/60 bg-card/40 px-4 py-3"+ >+ <RefreshCw aria-hidden="true" className="h-4 w-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-foreground">{t("providers_page.restart_title")}</p>+ <p className="mt-0.5 text-xs text-muted-foreground">{t("providers_page.restart_desc")}</p></div>- <div className="flex items-center gap-2 px-1 pt-2 text-sm font-medium text-muted-foreground">- <Bot aria-hidden="true" className="h-4 w-4" />- {t("providers_page.accounts_title")}- </div>- <AgentAccountsPanel />- </section>- );-}--/**- * Telephony: a labelled header above the embedded `TelephonyPanel`, which owns- * its data source (`/api/telephony/*`); the setup scripts and guide live on the- * dedicated TelephonySetupView, reached through the panel's "Setup script".- */-function TelephonySection() {- const t = useT();- return (- <section>- <h3 className="mb-3 inline-flex items-center gap-2 text-sm font-medium text-muted-foreground">- <Phone aria-hidden="true" className="h-4 w-4" /> {t("apikeys_view.tier_telephony")}- </h3>- <TelephonyPanel />- </section>+ <Button size="sm" disabled={restarting} onClick={() => void restart()}>+ {restarting && <Loader2 className="animate-spin" />}+ {t("providers_page.restart_action")}+ </Button>+ </div>);}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx b/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsxnew file mode 100644index 0000000000..3289b1eba1--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx@@ -0,0 +1,714 @@+import { useEffect, useMemo, useState, type ReactNode } from "react";+import { Check, FlaskConical, Loader2, LogIn, LogOut } from "lucide-react";+import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";+import { PromptWriterCard } from "@/components/PromptWriterCard";+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { ProviderTestControl } from "@/components/providers/ProviderTierSection";+import { SubagentModelCard, type SubagentStatus } from "@/components/SubagentModelCard";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import {+ codexLogout,+ deleteSecret,+ loginAntigravity,+ loginClaude,+ loginGrokBuild,+ logoutAntigravity,+ logoutClaude,+ logoutGrokBuild,+ setCodexBinaryPath,+ startCodexLogin,+ switchSubagentProvider,+ testAgentCli,+ type AgentCliTestResult,+ type ProviderDescriptor,+ type SectionHealth,+} from "@/hooks/useProviders";+import { useT } from "@/i18n";+import {+ pollUntilConnected,+ subscriptionStatusUrl,+ type AgentRowStatus,+ type ProviderFamily,+ type SubscriptionKind,+ type useProviderFamilies,+} from "@/lib/providerFamilies";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { KeyField } from "./KeyField";+import { familyState, type FamilyState } from "./providers/familyState";+import { DetailHeader, ListRow, MasterDetail, SettingsRow, SettingsSection } from "./settingsUi";++type FamiliesData = ReturnType<typeof useProviderFamilies>;++/** Each subscription login: its short name and the vendor CLI's own flows. */+const CLI: Record<+ SubscriptionKind,+ { name: string; login: () => Promise<void>; logout: () => Promise<void>; test: string; where: "browser" | "terminal" }+> = {+ codex: { name: "Codex", login: () => startCodexLogin(), logout: () => codexLogout(), test: "/api/codex/test", where: "browser" },+ claude_cli: { name: "Claude", login: loginClaude, logout: logoutClaude, test: "/api/claude/test", where: "terminal" },+ antigravity: { name: "Antigravity", login: loginAntigravity, logout: logoutAntigravity, test: "/api/antigravity/test", where: "browser" },+ grok_build: { name: "Grok", login: loginGrokBuild, logout: logoutGrokBuild, test: "/api/grok-build/test", where: "browser" },+};++/** "codex-cli 0.160.0" → "v0.160.0"; anything without a version number as given. */+export function shortVersion(raw: string | null | undefined): string | null {+ if (!raw) return null;+ const match = raw.match(/\d+\.\d+(?:\.\d+)?/);+ return match ? `v${match[0]}` : raw;+}++/**+ * Switch the agents' worker. One worker runs them at a time, so turning one+ * on turns the previous one off — the switches in both lists move together.+ */+function useAgentSwitch(onChanged: () => void | Promise<void>) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [switching, setSwitching] = useState<string | null>(null);++ async function use(row: AgentRowStatus, label: string) {+ if (row.is_active_brain || switching) return;+ setSwitching(row.jarvis);+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", { detail: { section: "subagents", provider: row.jarvis } }),+ );+ try {+ const result = await switchSubagentProvider(row.jarvis);+ pushToast(+ "success",+ t(result.restart_required ? "providers_page.agents_switched_restart" : "providers_page.agents_switched").replace("{0}", label),+ );+ window.dispatchEvent(new CustomEvent("jarvis:agent-switched"));+ await onChanged();+ } catch (cause) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", { detail: { section: "subagents", provider: row.jarvis } }),+ );+ pushToast("error", (cause as Error).message);+ } finally {+ setSwitching(null);+ }+ }++ return { switching, use };+}++/**+ * The Agents tab: which subscription or key runs the assistant's background+ * agents. Two lists in the same shape — the subscription logins, then the API+ * keys — each beside the selected entry's settings. The switch on a row is+ * "the agents run on this"; exactly one is on.+ */+export function AgentsTab({+ data,+ providers,+ health,+ onProvidersChanged,+}: {+ data: FamiliesData;+ providers: ProviderDescriptor[];+ health: Record<string, SectionHealth | undefined>;+ onProvidersChanged: () => void;+}) {+ const t = useT();+ const { families, subscriptions, agents, reload } = data;+ const refresh = async () => {+ onProvidersChanged();+ await reload();+ };+ const agentSwitch = useAgentSwitch(refresh);+ const states = useMemo<Record<string, FamilyState>>(() => {+ const ctx = { providers, subscriptions, agents, health };+ return Object.fromEntries((families ?? []).map((f) => [f.id, familyState(f, ctx)]));+ }, [families, providers, subscriptions, agents, health]);++ const rowsOf = (family: ProviderFamily) =>+ (agents?.mapping ?? []).filter((row) => family.agent_ids.includes(row.jarvis));+ const subscriptionFamilies = (families ?? []).filter((f) => f.subscription);+ // A key list entry is a company that can run the agents on a key, plus the+ // machine itself (agents on a local model need no key at all).+ const keyFamilies = (families ?? []).filter(+ (f) => rowsOf(f).some((row) => row.billing !== "subscription") && (f.key_slot || f.local),+ );++ return (+ <div className="flex flex-col gap-10">+ <SubscriptionsSection+ families={subscriptionFamilies}+ states={states}+ rowsOf={rowsOf}+ agentSwitch={agentSwitch}+ onChanged={refresh}+ />+ <ApiKeysSection+ families={keyFamilies}+ states={states}+ rowsOf={rowsOf}+ agentSwitch={agentSwitch}+ onChanged={refresh}+ />+ <AgentSettings />+ <SettingsSection title={t("providers_page.accounts_title")} plain>+ <AgentAccountsPanel />+ </SettingsSection>+ </div>+ );+}++type AgentSwitch = ReturnType<typeof useAgentSwitch>;++/** The worker row a subscription login runs the agents through. */+function subscriptionRow(_family: ProviderFamily, rows: AgentRowStatus[]): AgentRowStatus | undefined {+ return rows.find((row) => row.billing === "subscription" || row.billing === "subscription_or_api");+}++/** The worker row a company key runs the agents through. */+function keyRow(_family: ProviderFamily, rows: AgentRowStatus[]): AgentRowStatus | undefined {+ return rows.find((row) => row.billing === "api" || row.billing === "local") ?? rows.find((row) => row.billing === "subscription_or_api");+}++function SubscriptionsSection({+ families,+ states,+ rowsOf,+ agentSwitch,+ onChanged,+}: {+ families: ProviderFamily[];+ states: Record<string, FamilyState>;+ rowsOf: (family: ProviderFamily) => AgentRowStatus[];+ agentSwitch: AgentSwitch;+ onChanged: () => Promise<void>;+}) {+ const t = useT();+ const [selectedId, setSelectedId] = useState<string | null>(null);+ useEffect(() => {+ if (selectedId || !families.length) return;+ const active = families.find((f) => subscriptionRow(f, rowsOf(f))?.is_active_brain && states[f.id]?.subscriptionOn);+ setSelectedId((active ?? families.find((f) => states[f.id]?.subscriptionOn) ?? families[0]).id);+ }, [families, rowsOf, selectedId, states]);+ const selected = families.find((f) => f.id === selectedId) ?? null;++ return (+ <SettingsSection title={t("providers_page.subscriptions_title")} plain data-testid="agents-subscriptions">+ <MasterDetail+ testId="subscription-list"+ list={families.map((family) => {+ const state = states[family.id];+ const kind = family.subscription!.kind;+ const row = subscriptionRow(family, rowsOf(family));+ const on = Boolean(row?.is_active_brain && state?.subscriptionOn);+ return (+ <ListRow+ key={family.id}+ testId={`subscription-${kind}`}+ icon={<ProviderLogo providerId={family.subscription!.provider_id} label={CLI[kind].name} size="sm" className="h-5 w-5" />}+ name={CLI[kind].name}+ version={shortVersion(state?.subscription?.version)}+ status={subscriptionStatus(state, t)}+ dot={state?.failing ? "error" : null}+ selected={family.id === selectedId}+ dimmed={!state?.subscriptionOn}+ onSelect={() => setSelectedId(family.id)}+ trailing={+ <Switch+ checked={on}+ disabled={!row || !state?.subscriptionOn || on || agentSwitch.switching !== null}+ onCheckedChange={(checked) => checked && row && void agentSwitch.use(row, CLI[kind].name)}+ aria-label={t("providers_page.agents_use_for").replace("{0}", CLI[kind].name)}+ title={t("providers_page.agents_use_for").replace("{0}", CLI[kind].name)}+ />+ }+ />+ );+ })}+ detail={+ selected && states[selected.id] ? (+ <SubscriptionDetail+ key={selected.id}+ family={selected}+ state={states[selected.id]}+ row={subscriptionRow(selected, rowsOf(selected))}+ agentSwitch={agentSwitch}+ onChanged={onChanged}+ />+ ) : null+ }+ />+ </SettingsSection>+ );+}++function subscriptionStatus(state: FamilyState | undefined, t: (key: string) => string): string {+ if (!state?.subscription) return t("providers_page.subscription_unknown");+ if (state.subscriptionOn) {+ return state.account+ ? t("providers_page.authenticated_as").replace("{0}", state.account)+ : t("providers_page.authenticated");+ }+ if (!state.subscription.installed) return t("providers_page.not_installed");+ return t("providers_page.not_signed_in");+}++function SubscriptionDetail({+ family,+ state,+ row,+ agentSwitch,+ onChanged,+}: {+ family: ProviderFamily;+ state: FamilyState;+ row: AgentRowStatus | undefined;+ agentSwitch: AgentSwitch;+ onChanged: () => Promise<void>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const kind = family.subscription!.kind;+ const cli = CLI[kind];+ const status = state.subscription;+ const installed = status?.installed ?? false;+ const binary = status && "binary_path" in status ? status.binary_path ?? "" : "";+ const card = state.members.find((m) => m.id === family.subscription!.provider_id);+ const [pending, setPending] = useState<"login" | "waiting" | "logout" | null>(null);++ async function connect() {+ setPending("login");+ try {+ await cli.login();+ pushToast("info", t(cli.where === "browser" ? "providers_page.login_started_browser" : "providers_page.login_started_terminal"));+ setPending("waiting");+ await onChanged();+ if (await pollUntilConnected(subscriptionStatusUrl(kind), onChanged)) {+ pushToast("success", t("providers_page.login_done").replace("{0}", cli.name));+ }+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setPending(null);+ }+ }++ async function disconnect() {+ setPending("logout");+ try {+ await cli.logout();+ pushToast("info", t("providers_page.logout_done").replace("{0}", cli.name));+ await onChanged();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setPending(null);+ }+ }++ return (+ <div data-testid={`subscription-detail-${kind}`} className="space-y-6">+ <div className="space-y-2.5">+ <DetailHeader+ icon={<ProviderLogo providerId={family.subscription!.provider_id} label={cli.name} size="sm" className="h-5 w-5" />}+ name={cli.name}+ version={shortVersion(status?.version)}+ />+ <SettingsSectionCard>+ <SettingsRow+ title={t("providers_page.account")}+ status={+ pending === "waiting"+ ? t(cli.where === "browser" ? "providers_page.login_waiting_browser" : "providers_page.login_waiting_terminal")+ : !installed && status+ ? card?.install_hint || t("providers_page.subscription_install")+ : subscriptionStatus(state, t)+ }+ control={+ state.subscriptionOn ? (+ <Button size="sm" variant="outline" data-testid="subscription-disconnect" disabled={pending !== null} onClick={() => void disconnect()}>+ {pending === "logout" ? <Loader2 className="animate-spin" /> : <LogOut />}+ {t("providers_page.disconnect")}+ </Button>+ ) : (+ <Button size="sm" data-testid="subscription-connect" disabled={pending !== null || !installed} onClick={() => void connect()}>+ {pending ? <Loader2 className="animate-spin" /> : <LogIn />}+ {t("providers_page.connect")}+ </Button>+ )+ }+ />+ <UseForAgentsRow+ row={row}+ label={cli.name}+ ready={state.subscriptionOn}+ hint={t("providers_page.agents_needs_login")}+ agentSwitch={agentSwitch}+ />+ </SettingsSectionCard>+ </div>++ {installed && (+ <SettingsSection title={t("providers_page.runtime")}>+ <BinaryPathRow kind={kind} path={binary} onChanged={onChanged} />+ <SettingsRow+ title={t("providers_page.cli_check")}+ description={t("providers_page.cli_check_hint")}+ control={<CliTest endpoint={cli.test} onChanged={onChanged} />}+ />+ </SettingsSection>+ )}+ </div>+ );+}++/** A plain card (no section title) for the rows under a detail header. */+function SettingsSectionCard({ children }: { children: ReactNode }) {+ return (+ <div className="overflow-hidden rounded-xl border border-border/60 bg-card/40 [&>*+*]:border-t [&>*+*]:border-border/50">+ {children}+ </div>+ );+}++/** Where the CLI binary lives. Codex lets the user point at another one. */+function BinaryPathRow({ kind, path, onChanged }: { kind: SubscriptionKind; path: string; onChanged: () => Promise<void> }) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const editable = kind === "codex";+ const [draft, setDraft] = useState(path);+ useEffect(() => setDraft(path), [path]);++ async function commit() {+ const next = draft.trim();+ if (!editable || next === path) return;+ try {+ await setCodexBinaryPath(next);+ await onChanged();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ setDraft(path);+ }+ }++ return (+ <SettingsRow+ title={t("providers_page.binary_path")}+ description={t("providers_page.binary_path_hint")}+ control={+ <Input+ value={draft}+ readOnly={!editable}+ spellCheck={false}+ aria-label={t("providers_page.binary_path")}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => void commit()}+ onKeyDown={(event) => {+ if (event.key === "Enter") void commit();+ }}+ className={cn("h-8 font-mono text-sm sm:w-72", !editable && "text-muted-foreground")}+ />+ }+ />+ );+}++/** A live check of the CLI: found where, which version, signed in as whom. */+function CliTest({ endpoint, onChanged }: { endpoint: string; onChanged: () => Promise<void> }) {+ const t = useT();+ const [running, setRunning] = useState(false);+ const [result, setResult] = useState<AgentCliTestResult | null>(null);+ const [error, setError] = useState<string | null>(null);++ async function run() {+ setRunning(true);+ setError(null);+ try {+ setResult(await testAgentCli(endpoint));+ await onChanged();+ } catch (cause) {+ setResult(null);+ setError((cause as Error).message);+ } finally {+ setRunning(false);+ }+ }++ return (+ <span className="flex min-w-0 items-center gap-3">+ {(result || error) && (+ <span+ role="status"+ title={error ?? result?.message}+ className={cn("max-w-[16rem] truncate text-xs", error || (result && !result.ok) ? "text-destructive" : "text-muted-foreground")}+ >+ {error ?? result?.message}+ </span>+ )}+ <Button size="sm" variant="outline" disabled={running} onClick={() => void run()}>+ {running ? <Loader2 className="animate-spin" /> : <FlaskConical />}+ {t("providers_page.test")}+ </Button>+ </span>+ );+}++function UseForAgentsRow({+ row,+ label,+ ready,+ hint,+ agentSwitch,+}: {+ row: AgentRowStatus | undefined;+ label: string;+ ready: boolean;+ hint: string;+ agentSwitch: AgentSwitch;+}) {+ const t = useT();+ if (!row) return null;+ const active = row.is_active_brain && ready;+ return (+ <SettingsRow+ data-testid={`agent-use-row-${row.jarvis}`}+ title={t("providers_page.agents_title")}+ description={t("providers_page.agents_desc")}+ status={!ready ? hint : undefined}+ control={+ active ? (+ <span className="inline-flex items-center gap-1.5 text-sm font-medium text-foreground">+ <Check aria-hidden="true" className="h-4 w-4 text-accent" />+ {t("providers_page.in_use")}+ </span>+ ) : (+ <Button+ size="sm"+ variant="outline"+ data-testid={`provider-agent-use-${row.jarvis}`}+ disabled={!ready || agentSwitch.switching !== null}+ onClick={() => void agentSwitch.use(row, label)}+ >+ {agentSwitch.switching === row.jarvis && <Loader2 className="animate-spin" />}+ {t("providers_page.agents_use")}+ </Button>+ )+ }+ />+ );+}++function ApiKeysSection({+ families,+ states,+ rowsOf,+ agentSwitch,+ onChanged,+}: {+ families: ProviderFamily[];+ states: Record<string, FamilyState>;+ rowsOf: (family: ProviderFamily) => AgentRowStatus[];+ agentSwitch: AgentSwitch;+ onChanged: () => Promise<void>;+}) {+ const t = useT();+ const [selectedId, setSelectedId] = useState<string | null>(null);+ useEffect(() => {+ if (selectedId || !families.length) return;+ const active = families.find((f) => {+ const row = keyRow(f, rowsOf(f));+ return row?.is_active_brain && (f.key_present || f.local);+ });+ setSelectedId((active ?? families.find((f) => f.key_present) ?? families[0]).id);+ }, [families, rowsOf, selectedId]);+ const selected = families.find((f) => f.id === selectedId) ?? null;++ const keyStatus = (family: ProviderFamily) => {+ const state = states[family.id];+ if (family.local) return t("providers_page.status_local");+ if (family.key_present) return t("providers_page.key_saved_short");+ if (state?.viaProject) return t("providers_page.status_project");+ return t("providers_page.key_missing_short");+ };++ return (+ <SettingsSection title={t("providers_page.keys_title")} plain data-testid="agents-api-keys">+ <MasterDetail+ testId="api-key-list"+ list={families.map((family) => {+ const row = keyRow(family, rowsOf(family));+ const ready = family.local || family.key_present || Boolean(states[family.id]?.viaProject);+ const on = Boolean(row?.is_active_brain) && ready && !(row?.billing === "subscription_or_api" && states[family.id]?.subscriptionOn);+ return (+ <ListRow+ key={family.id}+ testId={`provider-family-${family.id}`}+ icon={<ProviderLogo providerId={family.logo_id} label={family.label} size="sm" className="h-5 w-5" />}+ name={family.label}+ status={keyStatus(family)}+ dot={states[family.id]?.failing ? "error" : null}+ selected={family.id === selectedId}+ dimmed={!ready}+ onSelect={() => setSelectedId(family.id)}+ trailing={+ <Switch+ checked={on}+ disabled={!row || !ready || on || agentSwitch.switching !== null}+ onCheckedChange={(checked) => checked && row && void agentSwitch.use(row, family.label)}+ aria-label={t("providers_page.agents_use_for").replace("{0}", family.label)}+ title={t("providers_page.agents_use_for").replace("{0}", family.label)}+ />+ }+ />+ );+ })}+ detail={+ selected && states[selected.id] ? (+ <KeyDetail+ key={selected.id}+ family={selected}+ state={states[selected.id]}+ rows={rowsOf(selected)}+ agentSwitch={agentSwitch}+ onChanged={onChanged}+ />+ ) : null+ }+ />+ </SettingsSection>+ );+}++const TEST_TIER_ORDER: ProviderDescriptor["tier"][] = ["brain", "realtime", "tts", "stt", "dictation"];++function KeyDetail({+ family,+ state,+ rows,+ agentSwitch,+ onChanged,+}: {+ family: ProviderFamily;+ state: FamilyState;+ rows: AgentRowStatus[];+ agentSwitch: AgentSwitch;+ onChanged: () => Promise<void>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [merging, setMerging] = useState<string | null>(null);+ const testCard = TEST_TIER_ORDER.map((tier) => state.members.find((m) => m.tier === tier && m.auth_mode === "api_key")).find(Boolean);+ const ready = family.key_present || state.viaProject || family.local;+ // The machine itself can run the agents on more than one local server.+ const workerRows = family.local ? rows.filter((row) => row.billing === "local") : [keyRow(family, rows)].filter(Boolean) as AgentRowStatus[];++ async function merge(slot: string) {+ setMerging(slot);+ try {+ await deleteSecret(slot);+ window.dispatchEvent(new CustomEvent("jarvis:secret-configured", { detail: { key: slot, action: "delete" } }));+ pushToast("info", t("providers_page.separate_merged_toast").replace("{0}", family.label));+ await onChanged();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setMerging(null);+ }+ }++ return (+ <div data-testid={`provider-family-detail-${family.id}`} className="space-y-6">+ <div className="space-y-2.5">+ <DetailHeader icon={<ProviderLogo providerId={family.logo_id} label={family.label} size="sm" className="h-5 w-5" />} name={family.label} />+ <SettingsSectionCard>+ {family.key_slot && (+ <KeyField+ slot={family.key_slot}+ present={family.key_present}+ providerLabel={family.label}+ dashboardUrl={family.dashboard_url}+ description={state.viaProject && !family.key_present ? t("providers_page.key_project_hint") : t("providers_page.key_desc_short")}+ onChanged={onChanged}+ />+ )}+ {workerRows.map((row) => (+ <UseForAgentsRow+ key={row.jarvis}+ row={row}+ label={family.local ? row.label ?? family.label : family.label}+ ready={ready && !(row.billing === "subscription_or_api" && state.subscriptionOn && !family.key_present)}+ hint={t("providers_page.agents_needs_key")}+ agentSwitch={agentSwitch}+ />+ ))}+ {family.key_present && testCard && (+ <SettingsRow+ title={t("providers_page.key_test_label")}+ description={t("providers_page.key_test_hint")}+ control={<ProviderTestControl providerId={testCard.id} providerLabel={testCard.label} section={testCard.tier} active={testCard.active} />}+ />+ )}+ </SettingsSectionCard>+ </div>++ {family.separate_keys.length > 0 && (+ <SettingsSection title={t("providers_page.separate_title")}>+ {family.separate_keys.map((entry) => (+ <SettingsRow+ key={entry.slot}+ data-testid={`provider-separate-key-${entry.slot}`}+ title={t(`providers_page.separate_${entry.surface}`)}+ description={t("providers_page.separate_hint")}+ control={+ <Button+ size="sm"+ variant="outline"+ disabled={merging !== null || !family.key_present}+ title={family.key_present ? undefined : t("providers_page.separate_needs_main")}+ onClick={() => void merge(entry.slot)}+ >+ {merging === entry.slot && <Loader2 className="animate-spin" />}+ {t("providers_page.separate_merge")}+ </Button>+ }+ />+ ))}+ </SettingsSection>+ )}+ </div>+ );+}++/**+ * Settings that belong to the agents rather than to one provider: the model+ * a worker thinks with and who writes the task briefs.+ */+function AgentSettings() {+ const t = useT();+ const [status, setStatus] = useState<SubagentStatus | null>(null);+ const reload = async () => {+ try {+ const res = await fetch("/api/jarvis-agent/status", { cache: "no-store" });+ if (res.ok) setStatus((await res.json()) as SubagentStatus);+ } catch (cause) {+ // The model card stays hidden; the lists above report the same+ // endpoint's failure.+ console.debug("agent status unavailable", cause);+ }+ };+ useEffect(() => {+ void reload();+ const onChange = () => void reload();+ window.addEventListener("jarvis:agent-switched", onChange);+ return () => window.removeEventListener("jarvis:agent-switched", onChange);+ }, []);++ return (+ <SettingsSection title={t("providers_page.agent_settings_title")} plain data-testid="provider-agent-settings">+ <div className="grid gap-4 xl:grid-cols-2">+ {status && <SubagentModelCard status={status} onSaved={() => void reload()} />}+ <PromptWriterCard />+ </div>+ </SettingsSection>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/KeyField.tsx b/jarvis/ui/web/frontend/src/views/apikeys/KeyField.tsxnew file mode 100644index 0000000000..05e33e5df4--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/KeyField.tsx@@ -0,0 +1,196 @@+import { useState } from "react";+import { AlertTriangle, ExternalLink, Eye, EyeOff, Loader2, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { deleteSecret, postSecret } from "@/hooks/useProviders";+import { useT } from "@/i18n";+import { keyMatchesSecret } from "@/lib/keyFormat";+import { openExternalUrl } from "@/lib/openExternal";+import { useEventStore } from "@/store/events";+import { SettingsRow } from "./settingsUi";++function announce(slot: string, action: "set" | "delete") {+ // Every mounted list and the health dots re-read. Only the slot NAME+ // travels, never a value.+ window.dispatchEvent(new CustomEvent("jarvis:secret-configured", { detail: { key: slot, action } }));+}++/**+ * One API key as one settings row. Saving always uses the "everywhere"+ * scope: the key becomes the company key, so every feature of that company+ * reads it. A saved key shows as saved, with Replace and Remove; an empty one+ * shows the field itself.+ */+export function KeyField({+ slot,+ present,+ providerLabel,+ dashboardUrl,+ title,+ description,+ onChanged,+ testId = "provider-key",+}: {+ slot: string;+ present: boolean;+ providerLabel: string;+ dashboardUrl?: string | null;+ title?: string;+ description?: string;+ onChanged?: () => void | Promise<void>;+ testId?: string;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [editing, setEditing] = useState(false);+ const [value, setValue] = useState("");+ const [reveal, setReveal] = useState(false);+ const [busy, setBusy] = useState<"save" | "delete" | null>(null);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const showInput = !present || editing;+ const format = value.trim() ? keyMatchesSecret(slot, value) : null;++ async function save() {+ const trimmed = value.trim();+ if (!trimmed) return;+ setBusy("save");+ try {+ await postSecret(slot, trimmed, "everywhere");+ setValue("");+ setEditing(false);+ setReveal(false);+ announce(slot, "set");+ pushToast("success", t("providers_page.key_saved_toast").replace("{0}", providerLabel));+ await onChanged?.();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setBusy(null);+ }+ }++ async function remove() {+ setBusy("delete");+ try {+ await deleteSecret(slot);+ announce(slot, "delete");+ pushToast("info", t("providers_page.key_removed_toast").replace("{0}", providerLabel));+ await onChanged?.();+ } catch (cause) {+ pushToast("error", (cause as Error).message);+ } finally {+ setBusy(null);+ setConfirmDelete(false);+ }+ }++ const getKey = dashboardUrl ? (+ <button+ type="button"+ onClick={() => void openExternalUrl(dashboardUrl)}+ className="inline-flex items-center gap-1 text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"+ >+ {t("providers_page.get_key")}+ <ExternalLink aria-hidden="true" className="h-3 w-3" />+ </button>+ ) : null;++ const control = showInput ? (+ <div className="flex w-full items-center gap-2 sm:w-auto">+ <div className="relative min-w-0 flex-1 sm:w-72 sm:flex-none">+ <Input+ type={reveal ? "text" : "password"}+ autoComplete="off"+ spellCheck={false}+ data-testid={`${testId}-input`}+ aria-label={title ?? t("providers_page.key_label")}+ placeholder={t("providers_page.key_placeholder").replace("{0}", providerLabel)}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") void save();+ if (event.key === "Escape" && present) {+ setEditing(false);+ setValue("");+ }+ }}+ className="h-8 pr-9 font-mono text-sm"+ />+ <button+ type="button"+ onClick={() => setReveal((on) => !on)}+ aria-label={t(reveal ? "providers_page.key_hide" : "providers_page.key_show")}+ className="absolute right-1 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center rounded text-muted-foreground hover:text-foreground"+ >+ {reveal ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}+ </button>+ </div>+ {editing && (+ <Button size="sm" variant="ghost" onClick={() => { setEditing(false); setValue(""); }}>+ {t("common.cancel")}+ </Button>+ )}+ <Button size="sm" data-testid={`${testId}-save`} disabled={!value.trim() || busy !== null} onClick={() => void save()}>+ {busy === "save" && <Loader2 className="animate-spin" />}+ {t("providers_page.key_save")}+ </Button>+ </div>+ ) : confirmDelete ? (+ <>+ <Button size="sm" variant="ghost" onClick={() => setConfirmDelete(false)}>+ {t("common.cancel")}+ </Button>+ <Button size="sm" variant="destructive" data-testid={`${testId}-remove-confirm`} disabled={busy !== null} onClick={() => void remove()}>+ {busy === "delete" && <Loader2 className="animate-spin" />}+ {t("providers_page.key_remove")}+ </Button>+ </>+ ) : (+ <>+ <Button size="sm" variant="outline" data-testid={`${testId}-replace`} onClick={() => setEditing(true)}>+ {t("providers_page.key_replace")}+ </Button>+ <Button+ size="icon"+ variant="ghost"+ className="h-8 w-8 text-muted-foreground"+ aria-label={t("providers_page.key_remove")}+ title={t("providers_page.key_remove")}+ data-testid={`${testId}-remove`}+ onClick={() => setConfirmDelete(true)}+ >+ <Trash2 />+ </Button>+ </>+ );++ return (+ <SettingsRow+ data-testid={testId}+ title={title ?? t("providers_page.key_label")}+ description={description}+ status={+ <span className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="inline-flex items-center gap-1.5">+ <span aria-hidden="true" className={present ? "h-1.5 w-1.5 rounded-full bg-success" : "h-1.5 w-1.5 rounded-full bg-border-strong"} />+ {confirmDelete+ ? t("providers_page.key_remove_confirm")+ : present+ ? t("providers_page.key_saved_hint")+ : t("providers_page.key_missing_hint")}+ </span>+ {getKey}+ {format && !format.match && format.detected && (+ <span role="status" className="inline-flex items-center gap-1 text-warning">+ <AlertTriangle aria-hidden="true" className="h-3.5 w-3.5" />+ {t("providers_page.key_format_warning")+ .replace("{0}", format.detected.label)+ .replace("{1}", providerLabel)}+ </span>+ )}+ </span>+ }+ control={control}+ />+ );+}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/ProvidersPanel.tsx b/jarvis/ui/web/frontend/src/views/apikeys/ProvidersPanel.tsxdeleted file mode 100644index 560f47e8d6..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/ProvidersPanel.tsx+++ /dev/null@@ -1,266 +0,0 @@-import { useEffect, useMemo, useState } from "react";-import { AlertCircle, Loader2, RefreshCw } from "lucide-react";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { Button } from "@/components/ui/button";-import {- PROVIDER_BACKEND_UNREACHABLE,- type ProviderDescriptor,- type ProviderTier,- type SectionHealth,-} from "@/hooks/useProviders";-import { useT } from "@/i18n";-import type { useProviderFamilies } from "@/lib/providerFamilies";-import { cn } from "@/lib/utils";-import { useEventStore } from "@/store/events";-import { FamilyDetail } from "./providers/FamilyDetail";-import { FamilyList } from "./providers/FamilyList";-import { familyState, type FamilyState, type FamilyUse } from "./providers/familyState";--type FamiliesData = ReturnType<typeof useProviderFamilies>;--/** The jobs the overview strip reports, each with the tier that answers it. */-const OVERVIEW: { use: FamilyUse; tier?: ProviderTier }[] = [- { use: "voice", tier: "realtime" },- { use: "agents" },- { use: "speech", tier: "tts" },- { use: "hearing", tier: "stt" },-];--/**- * The provider page body: what runs where, then every company in a list with- * the selected one's settings beside it.- */-export function ProvidersPanel({- data,- providers,- providersLoading,- providersError,- health,- realtimeHealth,- onProvidersChanged,- onActivateOptimistic,-}: {- data: FamiliesData;- providers: ProviderDescriptor[];- providersLoading: boolean;- providersError: string | null;- health: Record<string, SectionHealth | undefined>;- realtimeHealth?: SectionHealth;- onProvidersChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;-}) {- const t = useT();- const { families, subscriptions, agents, error, reload } = data;- const states = useMemo<Record<string, FamilyState>>(() => {- const ctx = { providers, subscriptions, agents, health };- return Object.fromEntries((families ?? []).map((f) => [f.id, familyState(f, ctx)]));- }, [families, providers, subscriptions, agents, health]);-- const [selectedId, setSelectedId] = useState<string | null>(null);- // First visit: open the company that carries the voice, else the first one- // that is connected — the page opens on something that is already set up.- useEffect(() => {- if (selectedId || !families?.length || !providers.length) return;- const pick =- families.find((f) => states[f.id]?.uses.includes("voice")) ??- families.find((f) => states[f.id]?.connected && !f.local) ??- families[0];- setSelectedId(pick.id);- }, [families, providers.length, selectedId, states]);-- const selected = families?.find((f) => f.id === selectedId) ?? null;- const refreshAll = async () => {- onProvidersChanged();- await reload();- };-- if (error === "restart_required" && !providersError) return <RestartNeeded />;-- if (providersError || error) {- return (- <div- role="alert"- className="flex items-start gap-2 rounded-xl border border-border bg-card px-5 py-4 text-sm text-destructive"- >- <AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0" />- <p className="min-w-0 flex-1">- {providersError === PROVIDER_BACKEND_UNREACHABLE- ? t("apikeys_view.backend_unavailable")- : t("providers_page.load_error")}- </p>- <Button variant="outline" size="sm" onClick={() => void refreshAll()}>- {t("common.retry")}- </Button>- </div>- );- }-- if (!families || (providersLoading && !providers.length)) {- return (- <div role="status" className="flex items-center gap-2 px-1 py-6 text-sm text-muted-foreground">- <Loader2 aria-hidden="true" className="h-4 w-4 animate-spin" />- {t("providers_page.loading")}- </div>- );- }-- return (- <div className="flex flex-col gap-group">- <Overview- families={families}- states={states}- providers={providers}- agents={agents}- onSelect={setSelectedId}- />-- <section aria-label={t("providers_page.list_label")} className="flex flex-col gap-3">- <div className="px-1">- <h2 className="text-lg font-semibold text-foreground-strong">{t("providers_page.list_title")}</h2>- <p className="mt-0.5 text-base text-muted-foreground">{t("providers_page.list_desc")}</p>- </div>- <div- data-testid="provider-master-detail"- className="grid overflow-clip rounded-xl border border-border md:grid-cols-[18rem_minmax(0,1fr)]"- >- <div className="border-b border-border bg-card md:border-b-0 md:border-r">- <div className="md:sticky md:top-0">- <FamilyList- families={families}- states={states}- selectedId={selectedId}- onSelect={setSelectedId}- />- </div>- </div>- <div className="min-w-0 p-6">- {selected && states[selected.id] && (- <FamilyDetail- key={selected.id}- family={selected}- state={states[selected.id]}- agents={agents}- realtimeHealth={realtimeHealth}- onChanged={refreshAll}- onProvidersChanged={onProvidersChanged}- onActivateOptimistic={onActivateOptimistic}- />- )}- </div>- </div>- </section>- </div>- );-}--/**- * The window runs a newer page than its backend: the bundle reloads on its- * own after an update, the server does not. One sentence and one button,- * instead of an error that suggests something is broken.- */-function RestartNeeded() {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const [restarting, setRestarting] = useState(false);-- async function restart() {- setRestarting(true);- try {- const response = await fetch("/api/settings/restart-app", { method: "POST" });- if (response.status === 409) {- pushToast("warning", t("topbar.restart_missions_running"));- setRestarting(false);- return;- }- if (!response.ok) throw new Error(`HTTP ${response.status}`);- // The window closes and relaunches; the button stays busy until then.- } catch (cause) {- pushToast("error", (cause as Error).message);- setRestarting(false);- }- }-- return (- <div- role="status"- data-testid="providers-restart-needed"- className="flex items-center gap-4 rounded-xl border border-border bg-card px-5 py-4"- >- <RefreshCw aria-hidden="true" className="h-5 w-5 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <p className="text-base font-medium text-foreground-strong">{t("providers_page.restart_title")}</p>- <p className="mt-0.5 text-sm text-muted-foreground">{t("providers_page.restart_desc")}</p>- </div>- <Button size="sm" disabled={restarting} onClick={() => void restart()}>- {restarting && <Loader2 className="animate-spin" />}- {t("providers_page.restart_action")}- </Button>- </div>- );-}--/**- * What runs where, in one row: the company behind each job right now. A click- * opens that company below, where the job can be moved.- */-function Overview({- families,- states,- providers,- agents,- onSelect,-}: {- families: NonNullable<FamiliesData["families"]>;- states: Record<string, FamilyState>;- providers: ProviderDescriptor[];- agents: FamiliesData["agents"];- onSelect: (id: string) => void;-}) {- const t = useT();- return (- <div- data-testid="provider-overview"- className="grid grid-cols-2 overflow-hidden rounded-xl border border-border bg-card lg:grid-cols-4"- >- {OVERVIEW.map(({ use, tier }, index) => {- const family = families.find((f) => states[f.id]?.uses.includes(use)) ?? null;- const detail =- use === "agents"- ? agents?.mapping.find((row) => row.is_active_brain)?.label ?? null- : providers.find((p) => p.tier === tier && p.active)?.label ?? null;- return (- <button- key={use}- type="button"- data-testid={`provider-overview-${use}`}- disabled={!family}- onClick={() => family && onSelect(family.id)}- className={cn(- "flex min-w-0 items-center gap-3 px-5 py-4 text-left transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",- family && "hover:bg-secondary",- index % 2 === 1 && "border-l border-border",- index >= 2 && "border-t border-border lg:border-t-0",- index === 2 && "lg:border-l",- )}- >- {family ? (- <ProviderLogo providerId={family.logo_id} label={family.label} />- ) : (- <span aria-hidden="true" className="h-9 w-9 shrink-0 rounded-md bg-secondary" />- )}- <span className="min-w-0">- <span className="block text-sm text-muted-foreground">{t(`providers_page.use_${use}_long`)}</span>- <span className="block truncate text-base font-medium text-foreground-strong">- {family?.label ?? t("providers_page.overview_none")}- </span>- {family && detail && detail !== family.label && (- <span className="block truncate text-sm text-muted-foreground">{detail}</span>- )}- </span>- </button>- );- })}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.subscription.test.tsx b/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.subscription.test.tsxdeleted file mode 100644index ffe2f15378..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.subscription.test.tsx+++ /dev/null@@ -1,290 +0,0 @@-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { afterEach, expect, it, vi } from "vitest";-import { RealtimeTab } from "./RealtimeTab";-import { liveProfileReady, type LiveAuthMode, type LiveProfileState } from "@/components/providers/LiveProfile";-import type { ProviderDescriptor } from "@/hooks/useProviders";--vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));-const voiceRuntime = vi.hoisted(() => ({ statusKnown: true, mode: "realtime", activeModel: "",- activeProvider: null as string | null, sessionActive: false, activeSessionProvider: "" }));-vi.mock("@/hooks/useVoiceMode", () => ({ useVoiceMode: () => voiceRuntime }));-vi.mock("@/components/RealtimeOptionsControl", () => ({ RealtimeOptionsControl: () => <div>Provider model options</div> }));-vi.mock("@/components/providers/ProviderTierSection", async (importOriginal) => ({- ...await importOriginal<typeof import("@/components/providers/ProviderTierSection")>(),- AuthWidget: () => <p>API credential editor</p>,- ProviderTestControl: () => <button>Paid API probe</button>,- Tag: () => null,-}));--const scrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollIntoView");--afterEach(() => {- cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks();- if (scrollIntoViewDescriptor) Object.defineProperty(HTMLElement.prototype, "scrollIntoView", scrollIntoViewDescriptor);- else Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");- voiceRuntime.activeProvider = null;- voiceRuntime.sessionActive = false;- voiceRuntime.activeSessionProvider = "";-});--function state(mode: LiveAuthMode): LiveProfileState {- return {- key_ready: mode === "api_key", active: true, agent_configured: true,- subscription: { account_id: "codex:default", account_connected: true, voice_status: "unverified" },- profile: {- auth_mode: mode, model: "gpt-live-1", voice: "gleam", backend_model: "api-model",- subscription_account_id: "", subscription_voice: "cove", subscription_backend_model: "subscription-model",- subscription_reasoning_effort: "medium", reasoning_effort: "high", web_search: true,- configured: true, instructions: "", backend_instructions: "",- },- };-}--function setup(mode: LiveAuthMode, options: {- keyReady?: boolean; subscriptionModel?: string; accountConnected?: boolean;- legacy?: boolean; saveFails?: boolean; includeGemini?: boolean;-} = {}) {- let current = state(mode);- current.key_ready = options.keyReady ?? current.key_ready;- current.profile.subscription_backend_model = options.subscriptionModel ?? current.profile.subscription_backend_model;- if (options.accountConnected === false) current.subscription!.account_connected = false;- if (options.legacy) {- delete current.profile.auth_mode;- delete current.profile.subscription_backend_model;- delete current.profile.subscription_account_id;- delete current.profile.subscription_voice;- delete current.profile.subscription_reasoning_effort;- delete current.subscription;- }- const writes: LiveProfileState["profile"][] = [];- const fetcher = vi.fn(async (url: string, init?: RequestInit) => {- if (init?.method === "PUT") {- const chosen = JSON.parse(String(init.body)) as LiveProfileState["profile"];- writes.push(chosen);- if (options.saveFails) return { ok: false, status: 409, json: async () => ({ detail: "Selection could not be saved" }) };- current = { ...current, profile: chosen };- }- const data = url === "/api/agent-accounts"- ? { platforms: [{ platform: "codex", active_account: "codex:default", accounts: [- { id: "codex:default", label: "My ChatGPT", connected: options.accountConnected !== false, mode: "subscription" },- ] }] }- : url.startsWith("/api/live/options")- ? { models: url.includes("chatgpt_subscription")- ? [{ id: "subscription-model", label: "Subscription model" }]- : [{ id: "api-model", label: "API model" }, { id: "cheap-api", label: "Cheaper API model" }],- voices: [url.includes("chatgpt_subscription") ? "cove" : "gleam"], efforts: ["", "medium", "high"] }- : url.includes("/realtime-options")- ? { models: [], voices: [], current_model: "", current_voice: "", preview_available: false }- : current;- return { ok: true, json: async () => data };- });- vi.stubGlobal("fetch", fetcher);- const provider: ProviderDescriptor = {- id: "openai-live", label: "OpenAI GPT-Live", tier: "realtime", auth_mode: "api_key", billing: "api",- active: true, configured: true, configuration_surface: "live", secret_keys: ["openai_api_key"],- secrets_set: {}, dashboard_url: null, login_cli: null, install_hint: null, credential_path_hint: null,- cli_installed: null, credential_help: null, signup_url: null, alt_credential: null,- };- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });- let suppliedProviders = [provider, ...(options.includeGemini ? [{ ...provider,- id: "gemini-live", label: "Gemini Live", configuration_surface: "provider" as const, active: false,- }] : [])];- let rendered: ReturnType<typeof render>;- const onActivateOptimistic = vi.fn((_tier: string, id: string) => {- suppliedProviders = suppliedProviders.map((entry) => ({ ...entry, active: entry.id === id }));- rendered.rerender(tree());- });- const tree = () => <QueryClientProvider client={client}><RealtimeTab providers={suppliedProviders} loading={false} error={null}- onChanged={vi.fn()} onActivateOptimistic={onActivateOptimistic} /></QueryClientProvider>;- rendered = render(tree());- return { client, writes, fetcher, onActivateOptimistic };-}--const subscriptionRow = () => screen.getByTestId("realtime-provider-openai-live-subscription");-const apiRow = () => screen.getByTestId("realtime-provider-openai-live");--it("places the exact GPT Subscription row above the independent API row", async () => {- const { client } = setup("api_key");- await screen.findByRole("combobox", { name: "live.thinking_model" });- const rows = within(screen.getByTestId("realtime-provider-list")).getAllByRole("button");- expect(rows.map((row) => row.dataset.testid)).toEqual([- "realtime-provider-openai-live-subscription", "realtime-provider-openai-live",- ]);- expect(within(subscriptionRow()).getByText("GPT Subscription")).toBeTruthy();- expect(within(subscriptionRow()).getByText("provider_billing.subscription")).toBeTruthy();- expect(within(apiRow()).getByText("provider_billing.api")).toBeTruthy();- expect(apiRow().dataset.active).toBe("true");- expect(subscriptionRow().dataset.active).toBe("false");- client.clear();-});--it("activates a complete subscription on its row click and switches back with the API row", async () => {- const { client, writes, onActivateOptimistic } = setup("api_key", { keyReady: true });- await screen.findByRole("combobox", { name: "live.thinking_model" });- fireEvent.click(subscriptionRow());- await waitFor(() => expect(subscriptionRow().dataset.active).toBe("true"));- expect(writes).toHaveLength(1);- expect(writes[0]).toMatchObject({ auth_mode: "chatgpt_subscription", subscription_backend_model: "subscription-model",- voice: "gleam", backend_model: "api-model", reasoning_effort: "high" });- expect(screen.queryByText("API credential editor")).toBeNull();- expect(screen.queryByRole("button", { name: "Paid API probe" })).toBeNull();- expect(screen.queryByRole("combobox", { name: "live.billing_method" })).toBeNull();- expect(apiRow().dataset.active).toBe("false");- expect(within(apiRow()).getByText("provider_billing.api")).toBeTruthy();- expect(within(screen.getByTestId("voice-now")).getByText("GPT Subscription")).toBeTruthy();- expect(onActivateOptimistic).not.toHaveBeenCalled();- fireEvent.click(apiRow());- await waitFor(() => expect(apiRow().dataset.active).toBe("true"));- expect(writes).toHaveLength(2);- expect(writes[1]).toMatchObject({ auth_mode: "api_key", backend_model: "api-model", voice: "gleam",- subscription_backend_model: "subscription-model", subscription_voice: "cove" });- await screen.findByRole("combobox", { name: "live.thinking_model" });- client.clear();-});--it("opens missing subscription model setup on click without changing the active API provider", async () => {- const scroll = vi.fn();- Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, value: scroll });- const { client, writes } = setup("api_key", { subscriptionModel: "" });- await screen.findByRole("combobox", { name: "live.thinking_model" });- expect(within(subscriptionRow()).getByText("live.subscription_model_required")).toBeTruthy();- expect(within(subscriptionRow()).queryByText("apikeys_view.state_missing")).toBeNull();- fireEvent.click(subscriptionRow());- await within(await screen.findByTestId("live-profile")).findByText("live.subscription_connected");- expect(document.activeElement).toBe(screen.getByTestId("realtime-provider-setup"));- expect(scroll).toHaveBeenCalledWith({ block: "start" });- fireEvent.click(subscriptionRow());- expect(scroll).toHaveBeenCalledTimes(2);- expect(screen.queryByRole("button", { name: "live.subscription_sign_in" })).toBeNull();- expect(writes).toHaveLength(0);- expect(subscriptionRow().getAttribute("aria-pressed")).toBe("true");- expect(subscriptionRow().dataset.active).toBe("false");- expect(apiRow().dataset.active).toBe("true");- expect((screen.getByRole("button", { name: "live.save" }) as HTMLButtonElement).disabled).toBe(true);- expect(screen.getByText("live.billing_pending")).toBeTruthy();- await waitFor(() => expect((screen.getByRole("combobox", { name: "live.thinking_model" }) as HTMLButtonElement).disabled).toBe(false));- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));- fireEvent.click(await screen.findByRole("option", { name: /Subscription model/ }));- expect(writes).toHaveLength(0);- fireEvent.click(screen.getByRole("button", { name: "live.save" }));- await screen.findByText("live.saved");- expect(writes[0]).toMatchObject({ auth_mode: "chatgpt_subscription", subscription_backend_model: "subscription-model" });- expect(subscriptionRow().dataset.active).toBe("true");- client.clear();-});--it("shows account sign-in for an incomplete subscription without falling back to the saved API key", async () => {- const { client, writes } = setup("api_key", { accountConnected: false });- await screen.findByRole("combobox", { name: "live.thinking_model" });- expect(within(subscriptionRow()).getByText("live.subscription_sign_in")).toBeTruthy();- expect(within(subscriptionRow()).queryByText("apikeys_view.state_missing")).toBeNull();- fireEvent.click(subscriptionRow());- await screen.findByRole("button", { name: "live.subscription_sign_in" });- expect(writes).toHaveLength(0);- expect(apiRow().dataset.active).toBe("true");- expect(screen.queryByRole("button", { name: "Paid API probe" })).toBeNull();- client.clear();-});--it("activates a saved subscription without any API key", async () => {- const { client, writes } = setup("api_key", { keyReady: false });- await screen.findByRole("combobox", { name: "live.thinking_model" });- fireEvent.click(subscriptionRow());- await waitFor(() => expect(subscriptionRow().dataset.active).toBe("true"));- expect(writes[0].auth_mode).toBe("chatgpt_subscription");- expect(screen.queryByText("live.key_required")).toBeNull();- client.clear();-});--it("preserves the active API row when a subscription activation fails", async () => {- const { client, writes, onActivateOptimistic } = setup("api_key", { saveFails: true });- await screen.findByRole("combobox", { name: "live.thinking_model" });- fireEvent.click(subscriptionRow());- await waitFor(() => expect(writes).toHaveLength(1));- await within(await screen.findByTestId("live-profile")).findByText("live.subscription_connected");- expect(apiRow().dataset.active).toBe("true");- expect(subscriptionRow().dataset.active).toBe("false");- expect(onActivateOptimistic).not.toHaveBeenCalled();- client.clear();-});--it("offers an explicit restart on an older backend and never submits an unsupported subscription profile", async () => {- const { client, writes, fetcher } = setup("api_key", { legacy: true });- await screen.findByRole("combobox", { name: "live.thinking_model" });- fireEvent.click(subscriptionRow());- await within(await screen.findByTestId("live-profile")).findByText("settings_view.wake_word.restart_required");- expect((screen.getByRole("button", { name: "live.save" }) as HTMLButtonElement).disabled).toBe(true);- expect(apiRow().dataset.active).toBe("true");- expect(writes).toHaveLength(0);- expect(fetcher.mock.calls.some(([url]) => url.includes("auth_mode=chatgpt_subscription"))).toBe(false);- fireEvent.click(screen.getByRole("button", { name: "taskbar_view.restart_now" }));- await waitFor(() => expect(fetcher.mock.calls.some(([url, init]) => url === "/api/settings/restart-app" && init?.method === "POST")).toBe(true));- client.clear();-});--it("keeps the original API save contract on an older backend", async () => {- const { client, writes } = setup("api_key", { legacy: true });- await screen.findByRole("combobox", { name: "live.thinking_model" });- fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));- fireEvent.click(await screen.findByRole("option", { name: /Cheaper API model/ }));- await waitFor(() => expect(writes).toHaveLength(1));- expect(writes[0]).toMatchObject({ backend_model: "cheap-api", voice: "gleam" });- expect(writes[0]).not.toHaveProperty("auth_mode");- await screen.findByText("live.saved");- client.clear();-});--it("preserves grouped settings for the saved subscription while the API row remains an API choice", async () => {- const { client } = setup("chatgpt_subscription");- await within(await screen.findByTestId("live-profile")).findByText("live.subscription_connected");- expect(screen.queryByText("API credential editor")).toBeNull();- expect(screen.queryByRole("button", { name: "Paid API probe" })).toBeNull();- expect(within(apiRow()).getByText("provider_billing.api")).toBeTruthy();- expect(within(screen.getByTestId("voice-now")).getByText("GPT Subscription")).toBeTruthy();- expect(within(screen.getByTestId("voice-now")).getByText("provider_billing.subscription")).toBeTruthy();- expect(screen.getByRole("region", { name: "live.conversation_heading" })).toBeTruthy();- expect(screen.getByRole("region", { name: "live.thinking_heading" })).toBeTruthy();- expect(screen.getByText("live.prompts").closest("details")).toBeTruthy();- expect(screen.getByTestId("live-profile-saved")).toBeTruthy();- client.clear();-});--it("checks both saved credential paths independently", () => {- const subscription = state("chatgpt_subscription");- expect(liveProfileReady(subscription)).toBe(true);- expect(liveProfileReady({ ...subscription, key_ready: true, subscription: undefined })).toBe(false);- expect(liveProfileReady({ ...subscription, profile: { ...subscription.profile, subscription_backend_model: "" } })).toBe(false);- const api = state("api_key");- expect(liveProfileReady(api)).toBe(true);- expect(liveProfileReady({ ...api, key_ready: false })).toBe(false);- expect(liveProfileReady(api, "chatgpt_subscription")).toBe(true);- expect(liveProfileReady({ ...subscription, key_ready: true }, "api_key")).toBe(true);-});--it.each([false, true])("keeps the actual API runtime in the header despite the saved subscription (running call=%s)", async (running) => {- voiceRuntime.activeProvider = running ? "openai-live-subscription" : "openai-live";- voiceRuntime.sessionActive = running;- voiceRuntime.activeSessionProvider = running ? "openai-live" : "";- const { client } = setup("chatgpt_subscription");- await within(await screen.findByTestId("live-profile")).findByText("live.subscription_connected");- expect(within(screen.getByTestId("voice-now")).getByText("OpenAI GPT-Live")).toBeTruthy();- expect(within(screen.getByTestId("voice-now")).getByText("provider_billing.api")).toBeTruthy();- expect(within(subscriptionRow()).getByText("provider_billing.subscription")).toBeTruthy();- client.clear();-});---it.each(["api_key", "chatgpt_subscription"] as const)("clears the %s Live row when Gemini becomes active before cached Live queries update", async (mode) => {- voiceRuntime.activeProvider = mode === "api_key" ? "openai-live" : "openai-live-subscription";- const { client, onActivateOptimistic } = setup(mode, { includeGemini: true });- await screen.findByRole("combobox", { name: "live.thinking_model" });- fireEvent.click(screen.getByTestId("realtime-provider-gemini-live"));- await waitFor(() => expect(onActivateOptimistic).toHaveBeenCalledWith("realtime", "gemini-live"));- expect(screen.getByTestId("realtime-provider-gemini-live").dataset.active).toBe("true");- expect(apiRow().dataset.active).toBe("false");- expect(subscriptionRow().dataset.active).toBe("false");- expect(screen.getByTestId("realtime-provider-list").querySelectorAll('[data-active="true"]')).toHaveLength(1);- expect(within(screen.getByTestId("voice-now")).getByText("Gemini Live")).toBeTruthy();- client.clear();-});diff --git a/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsx b/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsxdeleted file mode 100644index 8a87c6050e..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/RealtimeTab.tsx+++ /dev/null@@ -1,738 +0,0 @@-import { useEffect, useRef, useState } from "react";-import * as Dialog from "@radix-ui/react-dialog";-import { useQuery, useQueryClient } from "@tanstack/react-query";-import { AlertCircle, Check, Loader2, Radio, XCircle } from "lucide-react";-import {- LiveProfile,- liveProfileQuery,- liveProfileReady,- saveLiveProfile,- type LiveAuthMode,-} from "@/components/providers/LiveProfile";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import {- AuthWidget,- ProviderTestControl,- StatusBadge,- Tag,-} from "@/components/providers/ProviderTierSection";-import { RealtimeOptionsControl } from "@/components/RealtimeOptionsControl";-import { Button } from "@/components/ui/button";-import {- PROVIDER_BACKEND_UNREACHABLE,- type ProviderDescriptor,- type ProviderTier,- type SectionHealth,- sectionHealthForSubject,- switchRealtimeProvider,-} from "@/hooks/useProviders";-import { useVoiceMode } from "@/hooks/useVoiceMode";-import { useT } from "@/i18n";-import {- hasExperimentalConsent,- rememberExperimentalConsent,-} from "@/lib/experimentalConsent";-import {- realtimeTransportIssueKey,- requestRealtimeTransportOffer,-} from "@/lib/realtimeTransportIssue";-import { cn } from "@/lib/utils";-import { useEventStore } from "@/store/events";-import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";--type VoiceRuntime = ReturnType<typeof useVoiceMode>;--function liveMode(provider: ProviderDescriptor): LiveAuthMode | undefined {- if (provider.configuration_surface !== "live") return undefined;- return provider.id === "openai-live-subscription" ? "chatgpt_subscription" : "api_key";-}--/**- * The Realtime tab of the API Keys page. Realtime is the only voice engine- * this page offers; the three-step pipeline setup (speech-to-text, brain,- * text-to-speech) is gone from it.- *- * Top to bottom: what the voice runs on right now, the providers as one list- * where a click on a provider with a saved key makes it the voice, then the- * selected provider's own settings as plain groups (connection, model and- * voice or the GPT-Live profile, and a connection test).- *- * The provider list and the settings are separate on purpose: the previous- * layout named the provider twice (a chip, then a card header) and nested its- * settings four frames deep inside a 600 px dialog.- */-export function RealtimeTab({- providers,- loading,- error,- onChanged,- onActivateOptimistic,- health,- embedded = false,-}: {- providers: ProviderDescriptor[];- loading: boolean;- error: string | null;- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- /** Live health of the realtime tier's ACTIVE provider. */- health?: SectionHealth;- /**- * Shown inside one company's settings on the provider page: `providers` is- * that company's share of the realtime tier, the page above already says- * what the voice runs on, and the company key is edited once, above this- * section — so the "voice now" card, the list heading and the per-card key- * fields are left out.- */- embedded?: boolean;-}) {- const t = useT();- const voice = useVoiceMode();- const queryClient = useQueryClient();- const pushToast = useEventStore((s) => s.pushToast);- const rawChoices = providers.filter((provider) => provider.tier === "realtime");- const hasLiveSurface = rawChoices.some(- (provider) => provider.configuration_surface === "live",- );- const live = useQuery({ ...liveProfileQuery, enabled: hasLiveSurface });- const apiLive = rawChoices.find((provider) => provider.id === "openai-live" && provider.configuration_surface === "live");- const savedLiveId = live.data?.profile.auth_mode === "chatgpt_subscription" ? "openai-live-subscription" : "openai-live";- const runtimeLiveId = voice.activeProvider === "openai-live" || voice.activeProvider === "openai-live-subscription"- ? voice.activeProvider : undefined;- // Provider selection updates before the profile/runtime queries catch up.- // An active non-Live descriptor must clear both Live rows immediately.- const activeOtherId = rawChoices.find((provider) => provider.active && provider.configuration_surface !== "live")?.id- ?? rawChoices.find((provider) => provider.id === voice.activeProvider && provider.configuration_surface !== "live")?.id;- const activeLiveId = activeOtherId ? undefined- : live.data?.active ? savedLiveId : runtimeLiveId ?? (apiLive?.active ? "openai-live" : undefined);- // Two visible choices share one profile, but retain independent credentials,- // billing labels and saved model selections. The subscription comes first.- const choices = apiLive ? rawChoices.flatMap((provider): ProviderDescriptor[] => {- if (provider.id === "openai-live-subscription") return [];- if (provider.id !== apiLive.id) return [{ ...provider, active: provider.id === activeOtherId }];- return [{- ...provider, id: "openai-live-subscription", label: "GPT Subscription", billing: "subscription",- auth_mode: "codex", secret_keys: [], secrets_set: {}, secrets_effective: {},- active: activeLiveId === "openai-live-subscription", configured: liveProfileReady(live.data, "chatgpt_subscription"),- }, {- ...provider, billing: "api", active: activeLiveId === "openai-live",- configured: live.data ? liveProfileReady(live.data, "api_key") : provider.configured,- }];- }) : rawChoices;- const [inspectedId, setInspectedId] = useState<string | null>(null);- const [activatingId, setActivatingId] = useState<string | null>(null);- const setupRef = useRef<HTMLDivElement>(null);- const [setupFocusRequest, setSetupFocusRequest] = useState(0);- useEffect(() => {- if (!setupFocusRequest) return;- setupRef.current?.scrollIntoView?.({ block: "start" });- setupRef.current?.focus({ preventScroll: true });- }, [setupFocusRequest]);- // This transport uses an existing account, not the Codex CLI lifecycle.- // Never infer a missing installation from an absent CLI status object.- const subscriptionStatus = live.isError ? t("apikeys_view.load_error")- : !live.data ? t("live.loading")- : live.data.profile.auth_mode === undefined || !live.data.subscription- ? t("settings_view.wake_word.restart_required")- : !live.data.subscription.account_connected ? t("live.subscription_sign_in")- : !live.data.profile.subscription_backend_model?.trim()- ? t("live.subscription_model_required") : t("live.subscription_connected");- // The provider waiting for the experimental acknowledgement, with the flag- // its activation started with: a key saved a moment ago is still- // "unconfigured" in this descriptor, and dropping the flag here would let- // the confirmed dialog end in a silent no-op.- const [consentFor, setConsentFor] = useState<{- provider: ProviderDescriptor;- assumeConfigured: boolean;- } | null>(null);-- const active = choices.find((provider) => provider.active) ?? null;- const currentProviderId = voice.sessionActive ? voice.activeSessionProvider : activeOtherId ?? voice.activeProvider;- const currentProvider = choices.find((provider) => provider.id === currentProviderId) ?? active;- const selected =- choices.find((provider) => provider.id === inspectedId) ?? active ?? choices[0] ?? null;- const activeHealth = active ? sectionHealthForSubject(health, active.id) : undefined;-- /** Whether a click can switch to this provider without asking for anything.- * `assumeConfigured` covers the moment a key was just saved, before the- * provider list has refetched and still calls the provider unconfigured. */- function canSwitchTo(provider: ProviderDescriptor, assumeConfigured = false): boolean {- if (provider.active || activatingId) return false;- // GPT-Live saves its provider together with the thinking model, so it can- // only take over once that profile is complete.- if (provider.configuration_surface === "live") return liveProfileReady(live.data, liveMode(provider));- if (!provider.configured && !assumeConfigured) return false;- return true;- }-- async function activate(- provider: ProviderDescriptor,- { consented = false, assumeConfigured = false } = {},- ) {- if (!canSwitchTo(provider, assumeConfigured)) return;- // The experimental acknowledgement comes BEFORE the optimistic flip, so a- // declined dialog leaves nothing to roll back.- if (provider.experimental && !consented && !hasExperimentalConsent(provider.id)) {- setConsentFor({ provider, assumeConfigured });- return;- }- if (provider.configuration_surface !== "live") onActivateOptimistic("realtime", provider.id);- setActivatingId(provider.id);- try {- if (provider.configuration_surface === "live" && live.data) {- // Re-saving the stored profile is what selects GPT-Live; the backend- // writes the provider and `[voice].mode = "realtime"` together.- const mode = liveMode(provider)!;- const chosen = mode === "api_key" && live.data.profile.auth_mode === undefined- ? live.data.profile : { ...live.data.profile, auth_mode: mode };- await saveLiveProfile(chosen);- await queryClient.invalidateQueries({ queryKey: ["live-profile"] });- } else {- // The switch reconnects an OPEN call synchronously, and an- // offer-requiring transport cannot start without a browser offer, so- // ask for one before the POST (a transport that needs none ignores it).- requestRealtimeTransportOffer();- await switchRealtimeProvider(provider.id, provider.experimental === true);- // The provider switch never touches `[voice].mode`. This page offers- // no other engine, so picking a provider here also means "use it".- if (voice.mode !== "realtime") voice.setMode("realtime");- }- pushToast(- "success",- t("apikeys_view.switch_done_realtime").replace("{0}", provider.label),- );- window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));- onChanged();- } catch (cause) {- console.warn("realtime provider switch failed", provider.id, cause);- pushToast("error", (cause as Error).message);- // Roll the optimistic highlight back to the true active provider.- onChanged();- window.dispatchEvent(- new CustomEvent("jarvis:provider-switch-failed", {- detail: { section: "realtime", provider: provider.id },- }),- );- } finally {- setActivatingId(null);- }- }-- function select(provider: ProviderDescriptor) {- if (activatingId) return;- setInspectedId(provider.id);- if (liveMode(provider) === "chatgpt_subscription") setSetupFocusRequest((count) => count + 1);- // One click selects: the settings open below AND a provider whose key is- // already saved becomes the voice. Without a key it only opens, so the- // key field is on screen to paste into.- if (provider.active) {- // Already the provider; on an install still pinned to the pipeline- // engine the click means "use it", which only the engine switch can do.- if (voice.mode !== "realtime" && voice.realtimeAvailable) voice.setMode("realtime");- return;- }- void activate(provider);- }-- return (- <section- aria-label={t("apikeys_realtime.aria")}- data-testid="realtime-tab"- className="flex flex-col gap-group"- >- {!embedded && <VoiceNow active={currentProvider} activeHealth={currentProvider- ? sectionHealthForSubject(health, currentProvider.id) : undefined} voice={voice} />}-- {error && (- <div- role="alert"- className="flex items-start gap-2 rounded-xl border border-border bg-card px-5 py-4 text-sm text-destructive"- >- <AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0" />- <p className="min-w-0 flex-1">- {error === PROVIDER_BACKEND_UNREACHABLE- ? t("apikeys_view.backend_unavailable")- : `${t("apikeys_view.load_error")} (${error}).`}- </p>- <Button variant="outline" size="sm" onClick={onChanged}>- {t("common.retry")}- </Button>- </div>- )}-- <ProfileGroup- title={embedded ? t("providers_page.voice_choice_title") : t("apikeys_realtime.providers_title")}- description={embedded ? t("providers_page.voice_choice_desc") : t("apikeys_realtime.providers_desc")}- testId="realtime-provider-list"- >- {loading && !choices.length ? (- <div role="status" className="flex items-center gap-2 px-5 py-4 text-sm text-muted-foreground">- <Loader2 aria-hidden="true" className="h-4 w-4 animate-spin" />- {t("apikeys_realtime.loading")}- </div>- ) : (- choices.map((provider) => (- <ProviderRow- key={provider.id}- provider={provider}- statusLabel={liveMode(provider) === "chatgpt_subscription" ? subscriptionStatus : undefined}- selected={selected?.id === provider.id}- activating={activatingId === provider.id}- health={provider.active ? activeHealth : undefined}- onSelect={() => select(provider)}- />- ))- )}- </ProfileGroup>-- {selected && (- <div ref={setupRef} tabIndex={-1} data-testid="realtime-provider-setup" className="scroll-mt-4">- <ProviderSettings- key={selected.id}- provider={selected}- health={selected.active ? activeHealth : undefined}- activating={activatingId === selected.id}- canSwitch={canSwitchTo(selected)}- hideKeyFields={embedded}- onActivate={() => void activate(selected)}- // The first provider set up becomes the voice by itself; once one- // holds the voice, a new key never takes it over unasked.- onKeySaved={- active ? undefined : () => void activate(selected, { assumeConfigured: true })- }- onChanged={onChanged}- />- </div>- )}-- <ExperimentalConsentDialog- provider={consentFor?.provider ?? null}- onCancel={() => setConsentFor(null)}- onConfirm={() => {- const pending = consentFor;- setConsentFor(null);- if (!pending) return;- rememberExperimentalConsent(pending.provider.id);- void activate(pending.provider, {- consented: true,- assumeConfigured: pending.assumeConfigured,- });- }}- />- </section>- );-}--/**- * What the voice runs on right now — one card, one sentence of state. It also- * carries the one-click way back onto Realtime for an install that is still- * pinned to the retired pipeline engine, because this page no longer offers a- * switch between the two.- */-function VoiceNow({- active,- activeHealth,- voice,- billingOverride,-}: {- active: ProviderDescriptor | null;- activeHealth?: SectionHealth;- voice: VoiceRuntime;- billingOverride?: ProviderDescriptor["billing"];-}) {- const t = useT();- if (!voice.statusKnown) {- // A placeholder, never an invented "not set up": the status simply has- // not answered yet.- return (- <div- role="status"- aria-busy="true"- aria-label={t("apikeys_realtime.loading")}- className="flex items-center gap-4 rounded-xl border border-border bg-card px-5 py-4"- >- <span className="h-9 w-9 shrink-0 rounded-md bg-foreground/10" />- <span className="flex flex-1 flex-col gap-2">- <span className="h-3.5 w-40 rounded bg-foreground/10" />- <span className="h-3 w-24 rounded bg-foreground/10" />- </span>- </div>- );- }-- const realtimeOff = voice.mode !== "realtime";- const onBackupPath =- voice.sessionActive && voice.activeSessionMode === "pipeline" && !realtimeOff;- const offerBlocked =- !realtimeOff && voice.requiresWebRtcOffer && voice.transportOfferReady === false;- const offerDetail = !offerBlocked- ? ""- : voice.transportIssue- ? t(realtimeTransportIssueKey(voice.transportIssue))- : voice.transportOfferDetail;-- const title = realtimeOff- ? t("apikeys_realtime.state_off")- : active- ? active.label- : t("apikeys_realtime.state_none");- // A running call can still use the previous access, and a CLI can explicitly- // select either Live runtime. Prefer that truth over the saved next-call mode.- const runtimeProvider = voice.sessionActive ? voice.activeSessionProvider : voice.activeProvider;- const billing = active?.configuration_surface === "live" && runtimeProvider === "openai-live-subscription"- ? "subscription"- : active?.configuration_surface === "live" && runtimeProvider === "openai-live"- ? "api" : billingOverride ?? active?.billing;- const subtitle = realtimeOff- ? t(- voice.realtimeAvailable- ? "apikeys_realtime.off_hint"- : "apikeys_realtime.off_hint_unavailable",- )- : active- ? voice.activeModel || t(`provider_billing.${billing}`)- : t("apikeys_realtime.none_hint");-- const state: { tone: "accent" | "pulse" | "warn" | "error" | "quiet"; label: string } | null =- realtimeOff || !active- ? null- : voice.connecting- ? { tone: "pulse", label: t("apikeys_realtime.state_connecting") }- : voice.sessionActive && voice.activeSessionMode === "realtime"- ? { tone: "accent", label: t("apikeys_realtime.state_call") }- : onBackupPath- ? { tone: "warn", label: t("apikeys_realtime.state_backup") }- : activeHealth?.status === "error"- ? { tone: "error", label: t("apikeys_view.health_error") }- : { tone: "quiet", label: t("apikeys_realtime.state_ready") };-- const notes = [- onBackupPath ? { key: "backup", alert: false, text: t("live.pipeline_fallback") } : null,- !realtimeOff && voice.lastStartError- ? {- key: "start-error",- alert: true,- text: t("voice_state.connect_failed")- .replace("{0}", voice.lastStartError.provider || "?")- .replace("{1}", voice.lastStartError.message),- }- : null,- offerDetail ? { key: "offer", alert: true, text: offerDetail } : null,- ].filter((note): note is { key: string; alert: boolean; text: string } => note !== null);-- return (- <div- data-testid="voice-now"- className="divide-y divide-border overflow-hidden rounded-xl border border-border bg-card"- >- <div className="flex items-center gap-4 px-5 py-4">- {active && !realtimeOff ? (- <ProviderLogo providerId={active.id} label={active.label} />- ) : (- <span- aria-hidden="true"- className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary text-muted-foreground"- >- <Radio className="h-4 w-4" />- </span>- )}- <div className="min-w-0 flex-1">- <p className="truncate text-base font-semibold text-foreground-strong">{title}</p>- <p className="mt-0.5 text-sm text-muted-foreground">{subtitle}</p>- </div>- {realtimeOff && voice.realtimeAvailable && (- <Button- size="sm"- data-testid="voice-now-turn-on"- disabled={voice.isSaving}- onClick={() => voice.setMode("realtime")}- >- {voice.isSaving && <Loader2 className="animate-spin" />}- {t("apikeys_realtime.turn_on")}- </Button>- )}- {state && (- <span- data-testid="voice-now-state"- aria-live="polite"- className="inline-flex shrink-0 items-center gap-2 text-sm text-muted-foreground"- >- <span- aria-hidden="true"- className={cn(- "h-2 w-2 rounded-full",- state.tone === "accent" && "bg-accent",- state.tone === "pulse" && "animate-pulse bg-accent motion-reduce:animate-none",- state.tone === "warn" && "bg-warning",- state.tone === "error" && "bg-destructive",- state.tone === "quiet" && "bg-muted-foreground",- )}- />- <span className={cn(state.tone !== "quiet" && "font-medium text-foreground")}>- {state.label}- </span>- </span>- )}- </div>- {notes.map((note) => (- <p- key={note.key}- role={note.alert ? "alert" : "status"}- data-testid={`voice-now-note-${note.key}`}- className={cn(- "px-5 py-3 text-sm",- note.alert ? "text-destructive" : "text-warning",- )}- >- {note.text}- </p>- ))}- </div>- );-}--/** One provider in the list: a radio mark for "this is the voice", its state on the right. */-function ProviderRow({- provider,- billingOverride,- statusLabel,- selected,- activating,- health,- onSelect,-}: {- provider: ProviderDescriptor;- billingOverride?: ProviderDescriptor["billing"];- statusLabel?: string;- selected: boolean;- activating: boolean;- health?: SectionHealth;- onSelect: () => void;-}) {- const t = useT();- const broken = provider.active && health?.status === "error";- return (- <button- type="button"- aria-pressed={selected}- data-testid={`realtime-provider-${provider.id}`}- data-active={provider.active ? "true" : "false"}- onClick={onSelect}- className={cn(- "flex w-full items-center gap-4 px-5 py-3.5 text-left transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",- selected ? "bg-accent-soft" : "hover:bg-secondary",- )}- >- <span- aria-hidden="true"- className={cn(- "flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 transition-colors",- provider.active ? "border-accent" : "border-border-strong",- )}- >- {provider.active && <span className="h-2 w-2 rounded-full bg-accent" />}- </span>- <ProviderLogo providerId={provider.id} label={provider.label} />- <span className="min-w-0 flex-1">- <span className="flex min-w-0 items-center gap-2">- <span className="truncate text-base font-medium text-foreground">{provider.label}</span>- {provider.recommended && <Tag tone="accent">{t("apikeys_view.recommended")}</Tag>}- {provider.experimental && (- <Tag tone="neutral" title={t("apikeys_view.experimental_note")}>- {t("apikeys_view.experimental")}- </Tag>- )}- </span>- <span className="mt-0.5 block truncate text-sm text-muted-foreground">- {t(`provider_billing.${billingOverride ?? provider.billing}`)}- </span>- </span>- {activating ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-sm text-muted-foreground">- <Loader2 aria-hidden="true" className="h-3.5 w-3.5 animate-spin" />- {t("apikeys_view.provider_activating")}- </span>- ) : broken ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-sm font-medium text-destructive">- <span aria-hidden="true" className="h-2 w-2 rounded-full bg-destructive" />- {t("apikeys_view.health_error")}- </span>- ) : provider.active ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-sm font-medium text-foreground">- <Check aria-hidden="true" className="h-4 w-4 text-accent" />- {t("apikeys_realtime.active")}- </span>- ) : statusLabel ? (- <span title={statusLabel} className="inline-flex max-w-[45%] shrink-0 items-center gap-1.5 text-sm text-muted-foreground">- <span aria-hidden="true" className="h-2 w-2 shrink-0 rounded-full bg-muted-foreground" />- <span className="truncate">{statusLabel}</span>- </span>- ) : (- <StatusBadge descriptor={provider} />- )}- </button>- );-}--/**- * Everything that edits the selected provider, as plain settings groups: its- * connection (key, sign-in or local server) with a live test, then its model- * and voice — or, for GPT-Live, its own conversation and thinking groups.- */-function ProviderSettings({- provider,- health,- activating,- canSwitch,- hideKeyFields = false,- onActivate,- onKeySaved,- onChanged,-}: {- provider: ProviderDescriptor;- health?: SectionHealth;- activating: boolean;- canSwitch: boolean;- /** The company key is edited above (provider page); keep only local setup here. */- hideKeyFields?: boolean;- onActivate: () => void;- /** Called once a key was saved for a provider that had none. */- onKeySaved?: () => void;- onChanged: () => void;-}) {- const t = useT();- const isLive = provider.configuration_surface === "live";- const selectedAuthMode = liveMode(provider);- // The test and the key both belong to the API-key route; the key field- // alone moves up to the company section when this tab is embedded.- const showTest = !isLive || selectedAuthMode === "api_key";- const showCredentials = showTest && !(hideKeyFields && provider.auth_mode === "api_key");- const broken = provider.active && health?.status === "error";- const brokenDetail = health?.detail?.trim() || "";- const showOptions =- !isLive &&- (provider.configured ||- // Keep the pickers mounted through a transient busy probe so the group- // does not flicker while the provider is being checked.- provider.codex_status?.reason_code === "busy");-- return (- <div data-testid={`realtime-settings-${provider.id}`} className="flex flex-col gap-group">- {(showTest || broken) && <ProfileGroup- title={provider.label}- description={- isLive- ? t("apikeys_realtime.settings_desc_live")- : t(`provider_billing.${provider.billing}`)- }- aside={- canSwitch && !isLive ? (- <Button- size="sm"- variant="outline"- disabled={activating}- data-testid={`realtime-use-${provider.id}`}- onClick={onActivate}- >- {activating && <Loader2 className="animate-spin" />}- {t("apikeys_realtime.use_provider").replace("{0}", provider.label)}- </Button>- ) : undefined- }- >- {broken && (- <div- role="status"- data-testid={`realtime-health-error-${provider.id}`}- className="flex items-start gap-2 px-5 py-3 text-sm text-destructive"- >- <XCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0" />- <span className="min-w-0 break-words">- <span className="font-medium">{t("apikeys_view.health_error")}</span>- {brokenDetail ? ` — ${brokenDetail}` : ""}- </span>- </div>- )}- {showCredentials && <div className="px-5 py-4">- <AuthWidget descriptor={provider} onChanged={onChanged} onSavedActivate={onKeySaved} />- </div>}- {showOptions && (- <SettingRow- label={t("apikeys_realtime.model_voice")}- hint={t("apikeys_realtime.model_voice_hint")}- >- <div className="mt-3">- <RealtimeOptionsControl providerId={provider.id} healthActive={provider.active} />- </div>- </SettingRow>- )}- {showTest && <SettingRow- label={t("apikeys_realtime.test_label")}- hint={t("apikeys_realtime.test_hint")}- control={- <ProviderTestControl- providerId={provider.id}- providerLabel={provider.label}- section={provider.tier}- active={provider.active}- />- }- />}- </ProfileGroup>}-- {isLive && <LiveProfile onSaved={onChanged} selectedAuthMode={selectedAuthMode} />}- </div>- );-}--/**- * The once-per-provider acknowledgement before an experimental route becomes- * the voice. An in-app dialog, not `window.confirm`: the desktop WebView draws- * that as a raw "127.0.0.1 says" box that blocks the whole window.- */-function ExperimentalConsentDialog({- provider,- onCancel,- onConfirm,-}: {- provider: ProviderDescriptor | null;- onCancel: () => void;- onConfirm: () => void;-}) {- const t = useT();- const subscriptionOnly =- provider?.auth_mode === "codex" &&- provider.billing === "subscription" &&- provider.secret_keys.length === 0;- return (- <Dialog.Root open={provider !== null} onOpenChange={(open) => !open && onCancel()}>- <Dialog.Portal>- <Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/75 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none" />- <Dialog.Content- data-testid="realtime-consent-dialog"- className="fixed inset-0 z-[80] m-auto h-fit w-[min(440px,calc(100vw-32px))] rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-float outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 motion-reduce:animate-none"- >- <Dialog.Title className="text-base font-semibold text-foreground-strong">- {provider?.label}- </Dialog.Title>- <Dialog.Description className="mt-1.5 text-sm text-muted-foreground">- {t(- subscriptionOnly- ? "apikeys_view.experimental_subscription_consent"- : "apikeys_view.experimental_consent",- )}- </Dialog.Description>- <div className="mt-6 flex justify-end gap-2">- <Button type="button" variant="ghost" onClick={onCancel}>- {t("common.cancel")}- </Button>- <Button type="button" onClick={onConfirm}>- {t("common.yes")}- </Button>- </div>- </Dialog.Content>- </Dialog.Portal>- </Dialog.Root>- );-}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyDetail.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyDetail.tsxdeleted file mode 100644index 4d8091fd8d..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyDetail.tsx+++ /dev/null@@ -1,246 +0,0 @@-import { useState } from "react";-import { ArrowUpRight, Check, Loader2 } from "lucide-react";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { Button } from "@/components/ui/button";-import {- switchSubagentProvider,- type ProviderTier,- type SectionHealth,-} from "@/hooks/useProviders";-import { useT } from "@/i18n";-import type { AgentRowStatus, AgentStatus, ProviderFamily } from "@/lib/providerFamilies";-import { useEventStore } from "@/store/events";-import { RealtimeTab } from "@/views/apikeys/RealtimeTab";-import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";-import { familyStatusLine, type FamilyState } from "./familyState";-import { UseTag } from "./FamilyList";-import { KeySection } from "./KeySection";-import { SubscriptionSection } from "./SubscriptionSection";--/** Voice features configured in the voice section, shown here as facts. */-const VOICE_TIERS: { tier: ProviderTier; use: "speech" | "hearing" | "dictation" }[] = [- { tier: "tts", use: "speech" },- { tier: "stt", use: "hearing" },- { tier: "dictation", use: "dictation" },-];--/**- * Everything about one company, top to bottom in the order a person sets it- * up: sign in with the plan they pay for, or paste one key — then what the- * assistant uses the company for, each job switchable right where it is shown.- */-export function FamilyDetail({- family,- state,- agents,- realtimeHealth,- onChanged,- onProvidersChanged,- onActivateOptimistic,-}: {- family: ProviderFamily;- state: FamilyState;- agents: AgentStatus | null;- realtimeHealth?: SectionHealth;- onChanged: () => void | Promise<void>;- onProvidersChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;-}) {- const t = useT();- const setActiveSection = useEventStore((s) => s.setActiveSection);- const voiceCards = state.members.filter((m) => m.tier === "realtime");- const agentRows = (agents?.mapping ?? []).filter((row) => family.agent_ids.includes(row.jarvis));- const voiceFeatures = VOICE_TIERS.flatMap(({ tier, use }) =>- state.members.filter((m) => m.tier === tier).map((card) => ({ card, use })),- );-- return (- <div data-testid={`provider-family-detail-${family.id}`} className="flex flex-col gap-group">- <header className="flex items-center gap-4">- <ProviderLogo providerId={family.logo_id} label={family.label} className="h-11 w-11" />- <div className="min-w-0 flex-1">- <h2 className="truncate text-xl font-semibold text-foreground-strong">{family.label}</h2>- <p className="mt-0.5 truncate text-base text-muted-foreground">{familyStatusLine(family, state, t)}</p>- </div>- {state.uses.length > 0 && (- <div className="flex shrink-0 flex-wrap justify-end gap-1">- {state.uses.map((use) => (- <UseTag key={use} use={use} />- ))}- </div>- )}- </header>-- {state.failing && (- <p role="alert" className="rounded-xl border border-destructive/30 bg-destructive/10 px-5 py-3 text-sm text-destructive">- {state.failing}- </p>- )}-- {family.subscription && <SubscriptionSection family={family} state={state} onChanged={onChanged} />}-- {family.key_slot && <KeySection family={family} state={state} onChanged={onChanged} />}-- {voiceCards.length > 0 && (- <div data-testid="provider-voice">- <RealtimeTab- embedded- providers={voiceCards}- loading={false}- error={null}- onChanged={onProvidersChanged}- onActivateOptimistic={onActivateOptimistic}- health={realtimeHealth}- />- </div>- )}-- {agentRows.length > 0 && (- <AgentsSection family={family} state={state} rows={agentRows} onChanged={onChanged} />- )}-- {voiceFeatures.length > 0 && (- <ProfileGroup- title={t("providers_page.voice_features_title")}- description={t("providers_page.voice_features_desc")}- testId="provider-voice-features"- aside={- <Button- size="sm"- variant="ghost"- className="text-muted-foreground"- onClick={() => setActiveSection("voice-api-keys")}- >- {t("providers_page.voice_features_open")}- <ArrowUpRight />- </Button>- }- >- {voiceFeatures.map(({ card, use }) => (- <SettingRow- key={card.id}- label={card.label}- hint={t(`providers_page.use_${use}_long`)}- control={<InUse active={card.active} ready={card.configured} />}- />- ))}- </ProfileGroup>- )}- </div>- );-}--function InUse({ active, ready }: { active: boolean; ready: boolean }) {- const t = useT();- if (active) {- return (- <span className="inline-flex items-center gap-1.5 text-sm font-medium text-foreground">- <Check aria-hidden="true" className="h-4 w-4 text-accent" />- {t("providers_page.in_use")}- </span>- );- }- return (- <span className="text-sm text-muted-foreground">- {ready ? t("providers_page.available") : t("providers_page.not_ready")}- </span>- );-}--/**- * Which worker runs the assistant's background agents. Each of the company's- * worker routes is one row; the one in use says so, the others switch with- * one click once their sign-in or key is in place.- */-function AgentsSection({- family,- state,- rows,- onChanged,-}: {- family: ProviderFamily;- state: FamilyState;- rows: AgentRowStatus[];- onChanged: () => void | Promise<void>;-}) {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const [switching, setSwitching] = useState<string | null>(null);-- async function use(row: AgentRowStatus, label: string) {- setSwitching(row.jarvis);- window.dispatchEvent(- new CustomEvent("jarvis:provider-selection-pending", {- detail: { section: "subagents", provider: row.jarvis },- }),- );- try {- const result = await switchSubagentProvider(row.jarvis);- pushToast(- "success",- t(result.restart_required ? "providers_page.agents_switched_restart" : "providers_page.agents_switched")- .replace("{0}", label),- );- window.dispatchEvent(new CustomEvent("jarvis:agent-switched"));- await onChanged();- } catch (cause) {- window.dispatchEvent(- new CustomEvent("jarvis:provider-switch-failed", {- detail: { section: "subagents", provider: row.jarvis },- }),- );- pushToast("error", (cause as Error).message);- } finally {- setSwitching(null);- }- }-- return (- <ProfileGroup- title={t("providers_page.agents_title")}- description={t("providers_page.agents_desc")}- testId="provider-agents"- >- {rows.map((row) => {- const label = row.label ?? row.jarvis;- // A CLI row that can run on the plan login or a key reports which one- // it would use right now.- const billing =- row.billing === "subscription_or_api"- ? state.subscriptionOn- ? "subscription"- : "api"- : row.billing;- return (- <SettingRow- key={row.jarvis}- testId={`provider-agent-${row.jarvis}`}- label={label}- hint={- row.key_set- ? t(`provider_billing.${billing}`)- : t(family.subscription ? "providers_page.agents_needs_login_or_key" : "providers_page.agents_needs_key")- }- control={- row.is_active_brain ? (- <InUse active ready />- ) : (- <Button- size="sm"- variant="outline"- data-testid={`provider-agent-use-${row.jarvis}`}- disabled={!row.key_set || switching !== null}- onClick={() => void use(row, label)}- >- {switching === row.jarvis && <Loader2 className="animate-spin" />}- {t("providers_page.agents_use")}- </Button>- )- }- />- );- })}- </ProfileGroup>- );-}-diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyList.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyList.tsxdeleted file mode 100644index 43e38a57df..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/providers/FamilyList.tsx+++ /dev/null@@ -1,103 +0,0 @@-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { useT } from "@/i18n";-import type { ProviderFamily } from "@/lib/providerFamilies";-import { cn } from "@/lib/utils";-import { familyStatusLine, type FamilyState, type FamilyUse } from "./familyState";--/**- * The left column: every company once, its connection in one line, and a- * small tag for each job it powers right now — so the list itself answers- * "what runs where" before anything is opened.- */-export function FamilyList({- families,- states,- selectedId,- onSelect,-}: {- families: ProviderFamily[];- states: Record<string, FamilyState>;- selectedId: string | null;- onSelect: (id: string) => void;-}) {- const t = useT();- return (- <nav aria-label={t("providers_page.list_label")} data-testid="provider-family-list">- <ul className="flex flex-col gap-0.5 p-2">- {families.map((family) => {- const state = states[family.id];- if (!state) return null;- const selected = family.id === selectedId;- return (- <li key={family.id}>- <button- type="button"- data-testid={`provider-family-${family.id}`}- aria-current={selected ? "true" : undefined}- onClick={() => onSelect(family.id)}- className={cn(- "group flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- selected ? "bg-secondary" : "hover:bg-secondary/60",- )}- >- <ProviderLogo- providerId={family.logo_id}- label={family.label}- className={cn(!state.connected && !selected && "opacity-60")}- />- <span className="min-w-0 flex-1">- <span className="flex min-w-0 items-center gap-2">- <span- className={cn(- "truncate text-base font-medium",- state.connected ? "text-foreground-strong" : "text-muted-foreground",- )}- >- {family.label}- </span>- {state.failing && (- <span- role="status"- title={state.failing}- aria-label={t("providers_page.failing")}- className="h-2 w-2 shrink-0 rounded-full bg-destructive"- />- )}- </span>- <span- className={cn(- "mt-0.5 block truncate text-sm",- state.connected ? "text-muted-foreground" : "text-foreground-faint",- )}- >- {familyStatusLine(family, state, t)}- </span>- {state.uses.length > 0 && (- <span className="mt-1.5 flex flex-wrap gap-1">- {state.uses.map((use) => (- <UseTag key={use} use={use} />- ))}- </span>- )}- </span>- </button>- </li>- );- })}- </ul>- </nav>- );-}--export function UseTag({ use }: { use: FamilyUse }) {- const t = useT();- return (- <span- data-testid={`provider-use-${use}`}- className="inline-flex h-5 items-center rounded-md bg-accent-soft px-1.5 text-xs font-medium text-foreground"- >- {t(`providers_page.use_${use}`)}- </span>- );-}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/KeySection.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/KeySection.tsxdeleted file mode 100644index 65ab4345e6..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/providers/KeySection.tsx+++ /dev/null@@ -1,262 +0,0 @@-import { useState } from "react";-import { AlertTriangle, ExternalLink, Eye, EyeOff, Loader2, Trash2 } from "lucide-react";-import { ProviderTestControl } from "@/components/providers/ProviderTierSection";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { deleteSecret, postSecret, type ProviderDescriptor } from "@/hooks/useProviders";-import { useT } from "@/i18n";-import { keyMatchesSecret } from "@/lib/keyFormat";-import { openExternalUrl } from "@/lib/openExternal";-import type { ProviderFamily } from "@/lib/providerFamilies";-import { useEventStore } from "@/store/events";-import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";-import type { FamilyState } from "./familyState";--/** Which member card a key test runs against: the first keyed card, chat first. */-const TEST_TIER_ORDER: ProviderDescriptor["tier"][] = ["brain", "realtime", "tts", "stt", "dictation"];--function announce(slot: string, action: "set" | "delete") {- // Same signal the per-card forms send: every mounted list and the health- // dots re-read. Only the slot NAME travels, never a value.- window.dispatchEvent(new CustomEvent("jarvis:secret-configured", { detail: { key: slot, action } }));-}--/**- * One key for the whole company. Saving always uses the "everywhere" scope:- * the key becomes the family key, so live voice, agents, speech and every- * other feature of this company read it — the "one provider, one key" rule.- * A feature that still holds an older key of its own is listed underneath- * with a one-click way back onto the main key.- */-export function KeySection({- family,- state,- onChanged,-}: {- family: ProviderFamily;- state: FamilyState;- onChanged: () => void | Promise<void>;-}) {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const slot = family.key_slot!;- const [editing, setEditing] = useState(false);- const [value, setValue] = useState("");- const [reveal, setReveal] = useState(false);- const [busy, setBusy] = useState<"save" | "delete" | string | null>(null);- const [confirmDelete, setConfirmDelete] = useState(false);- const showInput = !family.key_present || editing;- const format = value.trim() ? keyMatchesSecret(slot, value) : null;- const testCard = TEST_TIER_ORDER.map((tier) =>- state.members.find((m) => m.tier === tier && m.auth_mode === "api_key"),- ).find(Boolean);-- async function save() {- const trimmed = value.trim();- if (!trimmed) return;- setBusy("save");- try {- await postSecret(slot, trimmed, "everywhere");- setValue("");- setEditing(false);- setReveal(false);- announce(slot, "set");- pushToast("success", t("providers_page.key_saved_toast").replace("{0}", family.label));- await onChanged();- } catch (cause) {- pushToast("error", (cause as Error).message);- } finally {- setBusy(null);- }- }-- async function remove(target: string, toast: string) {- setBusy(target === slot ? "delete" : target);- try {- await deleteSecret(target);- announce(target, "delete");- pushToast("info", toast);- await onChanged();- } catch (cause) {- pushToast("error", (cause as Error).message);- } finally {- setBusy(null);- setConfirmDelete(false);- }- }-- return (- <ProfileGroup- title={t("providers_page.key_title")}- description={t("providers_page.key_desc").replace("{0}", family.label)}- testId="provider-key"- aside={- family.dashboard_url ? (- <Button- size="sm"- variant="ghost"- className="text-muted-foreground"- onClick={() => void openExternalUrl(family.dashboard_url!)}- >- <ExternalLink />- {t("providers_page.get_key")}- </Button>- ) : undefined- }- >- <SettingRow- testId="provider-key-row"- label={- <span className="inline-flex items-center gap-2">- <span- aria-hidden="true"- className={family.key_present ? "h-2 w-2 rounded-full bg-success" : "h-2 w-2 rounded-full bg-border-strong"}- />- {t("providers_page.key_label")}- </span>- }- hint={- family.key_present- ? t("providers_page.key_saved_hint")- : state.viaProject- ? t("providers_page.key_project_hint")- : t("providers_page.key_missing_hint")- }- control={- family.key_present && !editing ? (- confirmDelete ? (- <>- <span className="text-sm text-muted-foreground">{t("providers_page.key_remove_confirm")}</span>- <Button size="sm" variant="ghost" onClick={() => setConfirmDelete(false)}>- {t("common.cancel")}- </Button>- <Button- size="sm"- variant="destructive"- data-testid="provider-key-remove-confirm"- disabled={busy !== null}- onClick={() => void remove(slot, t("providers_page.key_removed_toast").replace("{0}", family.label))}- >- {busy === "delete" && <Loader2 className="animate-spin" />}- {t("providers_page.key_remove")}- </Button>- </>- ) : (- <>- <Button size="sm" variant="outline" data-testid="provider-key-replace" onClick={() => setEditing(true)}>- {t("providers_page.key_replace")}- </Button>- <Button- size="icon"- variant="ghost"- className="h-8 w-8 text-muted-foreground"- aria-label={t("providers_page.key_remove")}- title={t("providers_page.key_remove")}- data-testid="provider-key-remove"- onClick={() => setConfirmDelete(true)}- >- <Trash2 />- </Button>- </>- )- ) : undefined- }- >- {showInput && (- <div className="mt-3 flex flex-col gap-2">- <div className="flex items-center gap-2">- <div className="relative min-w-0 flex-1">- <Input- type={reveal ? "text" : "password"}- autoComplete="off"- spellCheck={false}- data-testid="provider-key-input"- aria-label={t("providers_page.key_label")}- placeholder={t("providers_page.key_placeholder").replace("{0}", family.label)}- value={value}- onChange={(event) => setValue(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter") void save();- if (event.key === "Escape" && family.key_present) {- setEditing(false);- setValue("");- }- }}- className="pr-10 font-mono"- />- <button- type="button"- onClick={() => setReveal((on) => !on)}- aria-label={t(reveal ? "providers_page.key_hide" : "providers_page.key_show")}- className="absolute right-1 top-1/2 grid h-7 w-7 -translate-y-1/2 place-items-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground"- >- {reveal ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}- </button>- </div>- {editing && (- <Button size="sm" variant="ghost" onClick={() => { setEditing(false); setValue(""); }}>- {t("common.cancel")}- </Button>- )}- <Button- size="sm"- data-testid="provider-key-save"- disabled={!value.trim() || busy !== null}- onClick={() => void save()}- >- {busy === "save" && <Loader2 className="animate-spin" />}- {t("providers_page.key_save")}- </Button>- </div>- {format && !format.match && format.detected && (- <p role="status" className="flex items-start gap-1.5 text-sm text-warning">- <AlertTriangle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0" />- {t("providers_page.key_format_warning")- .replace("{0}", format.detected.label)- .replace("{1}", family.label)}- </p>- )}- </div>- )}- </SettingRow>-- {family.key_present && testCard && (- <SettingRow- label={t("providers_page.key_test_label")}- hint={t("providers_page.key_test_hint")}- control={- <ProviderTestControl- providerId={testCard.id}- providerLabel={testCard.label}- section={testCard.tier}- active={testCard.active}- />- }- />- )}-- {family.separate_keys.map((entry) => (- <SettingRow- key={entry.slot}- testId={`provider-separate-key-${entry.slot}`}- label={t(`providers_page.separate_${entry.surface}`)}- hint={t("providers_page.separate_hint")}- control={- <Button- size="sm"- variant="outline"- disabled={busy !== null || !family.key_present}- title={family.key_present ? undefined : t("providers_page.separate_needs_main")}- onClick={() =>- void remove(entry.slot, t("providers_page.separate_merged_toast").replace("{0}", family.label))- }- >- {busy === entry.slot && <Loader2 className="animate-spin" />}- {t("providers_page.separate_merge")}- </Button>- }- />- ))}- </ProfileGroup>- );-}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/providers/SubscriptionSection.tsx b/jarvis/ui/web/frontend/src/views/apikeys/providers/SubscriptionSection.tsxdeleted file mode 100644index 5231717f3a..0000000000--- a/jarvis/ui/web/frontend/src/views/apikeys/providers/SubscriptionSection.tsx+++ /dev/null@@ -1,213 +0,0 @@-import { useState } from "react";-import { FlaskConical, Loader2, LogIn, LogOut } from "lucide-react";-import { Button } from "@/components/ui/button";-import {- codexLogout,- loginAntigravity,- loginClaude,- loginGrokBuild,- logoutAntigravity,- logoutClaude,- logoutGrokBuild,- startCodexLogin,- testAgentCli,- type AgentCliTestResult,- type ProviderDescriptor,-} from "@/hooks/useProviders";-import { useT } from "@/i18n";-import {- pollUntilConnected,- subscriptionStatusUrl,- type ProviderFamily,- type SubscriptionKind,-} from "@/lib/providerFamilies";-import { cn } from "@/lib/utils";-import { useEventStore } from "@/store/events";-import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";-import type { FamilyState } from "./familyState";--/** The four subscription logins, each driven by the vendor's own CLI. */-const LOGIN: Record<- SubscriptionKind,- { login: () => Promise<void>; logout: () => Promise<void>; test: string; where: "browser" | "terminal" }-> = {- codex: { login: () => startCodexLogin(), logout: () => codexLogout(), test: "/api/codex/test", where: "browser" },- claude_cli: { login: loginClaude, logout: logoutClaude, test: "/api/claude/test", where: "terminal" },- antigravity: { login: loginAntigravity, logout: logoutAntigravity, test: "/api/antigravity/test", where: "browser" },- grok_build: { login: loginGrokBuild, logout: logoutGrokBuild, test: "/api/grok-build/test", where: "browser" },-};--/**- * Sign in with the plan the user already pays for. One row says whose plan is- * connected and offers the one next step (connect, finish, disconnect); a- * second row names the command-line tool behind it, the way a terminal user- * would check it, with a live test.- */-export function SubscriptionSection({- family,- state,- onChanged,-}: {- family: ProviderFamily;- state: FamilyState;- onChanged: () => void | Promise<void>;-}) {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const [pending, setPending] = useState<"login" | "logout" | "waiting" | null>(null);- const subscription = family.subscription!;- const flow = LOGIN[subscription.kind];- const status = state.subscription;- const card: ProviderDescriptor | undefined = state.members.find(- (m) => m.id === subscription.provider_id,- );- const installed = status?.installed ?? false;- const version = status?.version ?? null;- const binary = status && "binary_path" in status ? status.binary_path ?? null : null;-- async function connect() {- setPending("login");- try {- await flow.login();- pushToast(- "info",- t(flow.where === "browser" ? "providers_page.login_started_browser" : "providers_page.login_started_terminal"),- );- setPending("waiting");- await onChanged();- const ok = await pollUntilConnected(subscriptionStatusUrl(subscription.kind), onChanged);- if (ok) pushToast("success", t("providers_page.login_done").replace("{0}", family.label));- } catch (cause) {- pushToast("error", (cause as Error).message);- } finally {- setPending(null);- }- }-- async function disconnect() {- setPending("logout");- try {- await flow.logout();- pushToast("info", t("providers_page.logout_done").replace("{0}", family.label));- await onChanged();- } catch (cause) {- pushToast("error", (cause as Error).message);- } finally {- setPending(null);- }- }-- const hint = !status- ? t("providers_page.subscription_unknown")- : state.subscriptionOn- ? state.account- ? t("providers_page.subscription_signed_in").replace("{0}", state.account)- : status.message- : !installed- ? card?.install_hint || t("providers_page.subscription_install")- : pending === "waiting"- ? t(flow.where === "browser" ? "providers_page.login_waiting_browser" : "providers_page.login_waiting_terminal")- : t("providers_page.subscription_hint");-- return (- <ProfileGroup- title={t("providers_page.subscription_title")}- description={t("providers_page.subscription_desc").replace("{0}", family.label)}- testId="provider-subscription"- >- <SettingRow- label={- <span className="inline-flex items-center gap-2">- <span- aria-hidden="true"- className={cn(- "h-2 w-2 rounded-full",- state.subscriptionOn ? "bg-success" : "bg-border-strong",- )}- />- {subscription.label}- </span>- }- hint={hint}- control={- state.subscriptionOn ? (- <Button- size="sm"- variant="outline"- data-testid="provider-subscription-disconnect"- disabled={pending !== null}- onClick={() => void disconnect()}- >- {pending === "logout" ? <Loader2 className="animate-spin" /> : <LogOut />}- {t("providers_page.disconnect")}- </Button>- ) : (- <Button- size="sm"- data-testid="provider-subscription-connect"- disabled={pending !== null || !installed}- onClick={() => void connect()}- >- {pending === "login" || pending === "waiting" ? <Loader2 className="animate-spin" /> : <LogIn />}- {t("providers_page.connect")}- </Button>- )- }- />- {installed && (- <SettingRow- label={t("providers_page.cli_label")}- hint={- <span className="break-all">- {[version, binary].filter(Boolean).join(" · ") || t("providers_page.cli_found")}- </span>- }- control={<CliTest endpoint={flow.test} onChanged={onChanged} />}- />- )}- </ProfileGroup>- );-}--/** A live check of the CLI: found where, which version, signed in as whom. */-function CliTest({ endpoint, onChanged }: { endpoint: string; onChanged: () => void | Promise<void> }) {- const t = useT();- const [running, setRunning] = useState(false);- const [result, setResult] = useState<AgentCliTestResult | null>(null);- const [error, setError] = useState<string | null>(null);-- async function run() {- setRunning(true);- setError(null);- try {- setResult(await testAgentCli(endpoint));- await onChanged();- } catch (cause) {- setResult(null);- setError((cause as Error).message);- } finally {- setRunning(false);- }- }-- return (- <span className="flex items-center gap-3">- {(result || error) && (- <span- role="status"- title={error ?? result?.message}- className={cn(- "max-w-[16rem] truncate text-sm",- error || (result && !result.ok) ? "text-destructive" : "text-muted-foreground",- )}- >- {error ?? result?.message}- </span>- )}- <Button size="sm" variant="ghost" disabled={running} onClick={() => void run()}>- {running ? <Loader2 className="animate-spin" /> : <FlaskConical />}- {t("providers_page.test")}- </Button>- </span>- );-}diff --git a/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsx b/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsxnew file mode 100644index 0000000000..f1d9ce0039--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/apikeys/settingsUi.tsx@@ -0,0 +1,209 @@+import type { ComponentPropsWithoutRef, ReactNode } from "react";+import { cn } from "@/lib/utils";++/**+ * The compact settings grammar of the provider page.+ *+ * A section is a muted one-line title (with an optional action on the right)+ * above one card. A row inside the card is a title and a short explanation on+ * the left and its control on the right; on a narrow window the control drops+ * under the text. Explanations belong to rows, never to section titles.+ */+export function SettingsSection({+ title,+ icon,+ headerAction,+ plain = false,+ children,+ className,+ ...props+}: Omit<ComponentPropsWithoutRef<"section">, "title"> & {+ title: ReactNode;+ icon?: ReactNode;+ headerAction?: ReactNode;+ /** No card around the children (they bring their own surfaces). */+ plain?: boolean;+ children: ReactNode;+}) {+ return (+ <section {...props} className={cn("space-y-2.5", className)}>+ <div className="flex min-h-7 items-center justify-between gap-4 px-1">+ <h2 className="flex min-h-7 min-w-0 items-center gap-2 text-sm font-normal text-foreground/70">+ {icon}+ <span className="truncate">{title}</span>+ </h2>+ {headerAction ? <div className="flex min-w-7 shrink-0 items-center justify-end gap-1">{headerAction}</div> : null}+ </div>+ {plain ? children : <SettingsGroup>{children}</SettingsGroup>}+ </section>+ );+}++/** The card surface: rounded, hairline border, rows divided by hairlines. */+export function SettingsGroup({+ divided = true,+ className,+ ...props+}: ComponentPropsWithoutRef<"div"> & { divided?: boolean }) {+ return (+ <div+ {...props}+ className={cn(+ "relative overflow-hidden rounded-xl border border-border/60 bg-card/40 text-foreground",+ divided && "[&>*+*]:border-t [&>*+*]:border-border/50",+ className,+ )}+ />+ );+}++export function SettingsRow({+ title,+ description,+ status,+ control,+ children,+ className,+ ...props+}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {+ title: ReactNode;+ description?: ReactNode;+ /** A live state line under the description ("Authenticated as …"). */+ status?: ReactNode;+ control?: ReactNode;+ /** Full-width content under the row (an input, a list). */+ children?: ReactNode;+}) {+ return (+ <div {...props} data-slot="settings-row" className={cn("px-4 py-3", className)}>+ <div className="flex flex-col gap-3 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] sm:items-center sm:gap-8">+ <div className="min-w-0 space-y-1">+ <h3 className="flex min-h-5 items-center gap-1.5 text-sm font-medium text-foreground">{title}</h3>+ {description ? (+ <p className="max-w-xl text-xs leading-normal text-muted-foreground/80">{description}</p>+ ) : null}+ {status ? <div className="pt-0.5 text-xs text-muted-foreground">{status}</div> : null}+ </div>+ {control ? (+ <div className="flex w-full min-w-0 shrink-0 items-center gap-2 sm:w-auto sm:justify-end">+ {control}+ </div>+ ) : null}+ </div>+ {children ? <div className="pt-3">{children}</div> : null}+ </div>+ );+}++/**+ * A list beside the selected item's settings, inside one card. The list sits+ * on a slightly darker ground; both halves scroll on their own once the card+ * reaches its height.+ */+export function MasterDetail({+ list,+ detail,+ testId,+}: {+ list: ReactNode;+ detail: ReactNode;+ testId?: string;+}) {+ return (+ <SettingsGroup+ divided={false}+ data-testid={testId}+ className="md:grid md:h-[min(40rem,calc(100dvh-14rem))] md:min-h-[26rem] md:grid-cols-[17rem_minmax(0,1fr)]"+ >+ <div className="border-b border-border/60 bg-secondary/30 md:min-h-0 md:overflow-y-auto md:border-b-0 md:border-r scrollbar-jarvis">+ <div className="divide-y divide-border/50">{list}</div>+ </div>+ <div className="min-w-0 md:min-h-0 md:overflow-y-auto scrollbar-jarvis">+ <div className="space-y-6 p-4">{detail}</div>+ </div>+ </SettingsGroup>+ );+}++/** One entry of a `MasterDetail` list: mark, name, version, status, and a switch. */+export function ListRow({+ icon,+ name,+ version,+ status,+ dot,+ selected,+ dimmed,+ onSelect,+ trailing,+ testId,+}: {+ icon: ReactNode;+ name: string;+ version?: string | null;+ status: ReactNode;+ /** Only trouble gets a dot; a healthy row reads fine from its text. */+ dot?: "warning" | "error" | null;+ selected: boolean;+ dimmed: boolean;+ onSelect: () => void;+ trailing?: ReactNode;+ testId?: string;+}) {+ return (+ <div+ data-testid={testId}+ className={cn(+ "group flex min-h-[4.5rem] items-center gap-3 px-4 py-3 transition-colors",+ selected ? "bg-secondary" : "hover:bg-secondary/50",+ )}+ >+ <div+ className={cn(+ "relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",+ dimmed && !selected && "opacity-60 group-hover:opacity-100",+ )}+ >+ <button+ type="button"+ className="absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"+ onClick={onSelect}+ aria-label={name}+ aria-pressed={selected}+ />+ <span className="pointer-events-none mt-0.5 flex shrink-0">{icon}</span>+ <span className="pointer-events-none min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm font-medium text-foreground">{name}</span>+ {version ? <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">{version}</code> : null}+ </span>+ <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">+ {dot ? (+ <span className="flex h-[1.45em] shrink-0 items-center">+ <span+ aria-hidden="true"+ className={cn("h-1.5 w-1.5 rounded-full", dot === "error" ? "bg-destructive" : "bg-warning")}+ />+ </span>+ ) : null}+ <span className="line-clamp-2 [overflow-wrap:anywhere]">{status}</span>+ </span>+ </span>+ </div>+ {trailing ? <span className="flex h-5 shrink-0 items-center">{trailing}</span> : null}+ </div>+ );+}++/** The detail pane's title line: mark and name, and the version on the right. */+export function DetailHeader({ icon, name, version }: { icon: ReactNode; name: string; version?: string | null }) {+ return (+ <div className="flex min-h-7 items-center justify-between gap-4 px-1">+ <h2 className="flex min-w-0 items-center gap-2 text-sm font-normal text-foreground/70">+ {icon}+ <span className="truncate">{name}</span>+ </h2>+ {version ? <code className="truncate text-xs text-muted-foreground">{version}</code> : null}+ </div>+ );+}