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(frontend): standardize the Control Key UX — find, explain, change
Ruben Lütkef1156331233f
diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.test.tsxindex 456f22ab12..7a709881bb 100644--- a/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx+++ b/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx@@ -86,7 +86,7 @@ describe("AuthGate", () => {vi.stubGlobal("fetch", fetchMock);render(<AuthGate><div>Application</div></AuthGate>);- const input = await screen.findByLabelText("Control key");+ const input = await screen.findByLabelText("Control Key");fireEvent.change(input, { target: { value: "control-secret" } });fireEvent.submit(input.closest("form")!);@@ -110,11 +110,22 @@ describe("AuthGate", () => {render(<AuthGate><div>Application</div></AuthGate>);- expect(await screen.findByLabelText("Control key")).toBeTruthy();+ expect(await screen.findByLabelText("Control Key")).toBeTruthy();expect(window.__JARVIS_TOKEN).toBeUndefined();expect(screen.queryByText("Application")).toBeNull();});+ it("tells the user where to find the Control Key on the lock screen", async () => {+ const fetchMock = vi.fn().mockResolvedValueOnce(response(401));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);++ expect(await screen.findByText("Where do I find the Control Key?")).toBeTruthy();+ expect(screen.getByText(/generated automatically for this Jarvis install/i)).toBeTruthy();+ expect(screen.getByText(/\.control_api_key/)).toBeTruthy();+ });+it("keeps the gate closed when the control key is rejected", async () => {const fetchMock = vi.fn()@@ -123,12 +134,12 @@ describe("AuthGate", () => {vi.stubGlobal("fetch", fetchMock);render(<AuthGate><div>Application</div></AuthGate>);- const input = await screen.findByLabelText("Control key");+ const input = await screen.findByLabelText("Control Key");fireEvent.change(input, { target: { value: "wrong" } });fireEvent.submit(input.closest("form")!);expect((await screen.findByRole("alert")).textContent).toBe(- "That control key was not accepted.",+ "That Control Key was not accepted.",);expect(screen.queryByText("Application")).toBeNull();});diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.tsxindex 77d3dc6e28..13c478d2f6 100644--- a/jarvis/ui/web/frontend/src/components/AuthGate.tsx+++ b/jarvis/ui/web/frontend/src/components/AuthGate.tsx@@ -175,6 +175,16 @@ export function AuthGate({ children }: AuthGateProps) {>{t(submitting ? "auth_gate.submitting" : "auth_gate.submit")}</button>++ <div className="mt-5 border-t border-border pt-4">+ <h2 className="text-xs font-medium">{t("auth_gate.where_title")}</h2>+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">+ {t("auth_gate.where_hint")}+ </p>+ <p className="mt-1.5 text-xs leading-relaxed text-muted-foreground">+ {t("auth_gate.where_hint_server")}+ </p>+ </div></form></main>);diff --git a/jarvis/ui/web/frontend/src/hooks/useJarvisApi.ts b/jarvis/ui/web/frontend/src/hooks/useJarvisApi.tsindex 3815c2d7d9..3c2c7123c4 100644--- a/jarvis/ui/web/frontend/src/hooks/useJarvisApi.ts+++ b/jarvis/ui/web/frontend/src/hooks/useJarvisApi.ts@@ -16,7 +16,7 @@ interface RotateResult {masked: string;}-/** Loads /api/control/api-key and exposes rotate(). Mirrors useAutostart. */+/** Loads /api/control/api-key and exposes rotate() + setKey(). Mirrors useAutostart. */export function useJarvisApi() {const [data, setData] = useState<ControlApiKey | null>(null);const [loading, setLoading] = useState(true);@@ -55,5 +55,23 @@ export function useJarvisApi() {return result;}, []);- return { data, loading, error, refetch, rotate };+ /**+ * Replace the key with a user-chosen value (PUT /api/control/api-key).+ * The response carries only the masked form; the clear value is what the+ * user just typed, so the local state can be updated without a refetch.+ */+ const setKey = useCallback(async (value: string): Promise<void> => {+ const res = await fetch("/api/control/api-key", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ value, confirm: true }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error(body.detail ?? `HTTP ${res.status}`);+ }+ setData({ key: value.trim(), masked: (body as { masked?: string }).masked ?? "…" });+ }, []);++ return { data, loading, error, refetch, rotate, setKey };}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 46231d56ae..798ea8f1c7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -8,7 +8,10 @@"submit": "Entsperren","submitting": "Wird geprüft…","invalid": "Dieser Control Key wurde nicht akzeptiert.",- "unavailable": "Jarvis ist nicht erreichbar. Versuch es erneut."+ "unavailable": "Jarvis ist nicht erreichbar. Versuch es erneut.",+ "where_title": "Wo finde ich den Control Key?",+ "where_hint": "Er wurde dir nie zugeschickt — er wird bei der Installation automatisch für diese Jarvis-Instanz erzeugt. Öffne Jarvis auf dem Computer, auf dem es installiert ist: Unter API-Keys → Zugang & Integrationen kannst du ihn anzeigen, kopieren oder durch einen eigenen ersetzen.",+ "where_hint_server": "Auf einem Server ohne Oberfläche steht er in der Datei .control_api_key im Jarvis-Datenordner."},"file_toast": {"show_in_folder": "Im Ordner zeigen",@@ -1109,17 +1112,30 @@"unavailable": "Benötigt einen OpenAI-Schlüssel. Es wird die Standard-Sprachausgabe verwendet."},"jarvis_api": {- "title": "{name} API",- "key_label": "API-Schlüssel",- "description": "Lokale Agenten (Codex, Claude Code) steuern {name} mit diesem Schlüssel über die Control-API — Einstellungen ändern, Provider oder Sprache wechseln — statt durch die Oberfläche zu klicken.",+ "title": "Control Key",+ "key_label": "Control Key",+ "description": "Der eine Schlüssel, der diese {name}-Installation schützt. Mit ihm entsperrst du {name} im Browser oder von einem anderen Gerät, und lokale Agenten (Codex, Claude Code) steuern {name} damit über die Control-API. Er wurde bei der Installation automatisch erzeugt — jede Installation hat ihren eigenen.","show": "Anzeigen","hide": "Verbergen","copy_button": "Kopieren",- "copied_toast": "API-Schlüssel in die Zwischenablage kopiert.",- "copy_failed_toast": "API-Schlüssel konnte nicht kopiert werden.",- "regenerate_button": "Schlüssel neu erzeugen",- "regenerated_toast": "Ein neuer API-Schlüssel wurde erzeugt. Aktualisiere jeden Agenten, der den alten verwendet hat.",- "usage_hint": "Sende ihn als Authorization: Bearer-Header an dein lokales {name} (/api/control). GET /api/control/allowlist listet alles auf, was du ändern kannst."+ "copied_toast": "Control Key in die Zwischenablage kopiert.",+ "copy_failed_toast": "Control Key konnte nicht kopiert werden.",+ "unlock_hint": "Der Sperrbildschirm im Browser fragt genau nach diesem Key.",+ "regenerate_button": "Zufälligen Key erzeugen",+ "regenerate_confirm_title": "Neuen Control Key erzeugen?",+ "regenerate_confirm_body": "Der aktuelle Key funktioniert dann sofort nirgendwo mehr. Jeder Browser, jedes Gerät und jeder Agent, der ihn noch nutzt, braucht den neuen Key.",+ "regenerate_confirm_button": "Neuen Key erzeugen",+ "regenerated_toast": "Ein neuer Control Key wurde erzeugt. Gib ihn an jedes Gerät und jeden Agenten weiter, die den alten verwendet haben.",+ "custom_button": "Eigenen Key festlegen",+ "custom_hint": "Wähle einen Key, den du dir merken kannst — er ersetzt den aktuellen sofort und überall. Mindestens 12 Zeichen; nur Buchstaben, Ziffern und . _ ~ - (keine Leerzeichen).",+ "custom_new_label": "Neuer Control Key",+ "custom_repeat_label": "Neuen Control Key wiederholen",+ "custom_too_short": "Mindestens 12 Zeichen erforderlich.",+ "custom_charset": "Nur Buchstaben, Ziffern und . _ ~ - sind erlaubt (keine Leerzeichen).",+ "custom_mismatch": "Die beiden Eingaben stimmen nicht überein.",+ "custom_submit": "Diesen Key festlegen",+ "custom_saved_toast": "Dein Control Key ist gesetzt. Er entsperrt {name} ab jetzt überall.",+ "usage_hint": "Für Agenten: als Authorization: Bearer-Header an dein lokales {name} senden (/api/control). GET /api/control/allowlist listet alles auf, was sich ändern lässt."},"save": "Speichern","saving": "Speichere…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 2e3596eb96..7659b55f58 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2,13 +2,16 @@"auth_gate": {"checking": "Checking access…","title": "Unlock Personal Jarvis",- "subtitle": "Enter the control key configured for this Jarvis instance.",- "control_key": "Control key",- "placeholder": "Paste your control key",+ "subtitle": "Enter the Control Key of this Jarvis instance.",+ "control_key": "Control Key",+ "placeholder": "Paste your Control Key","submit": "Unlock","submitting": "Checking…",- "invalid": "That control key was not accepted.",- "unavailable": "Could not reach Jarvis. Try again."+ "invalid": "That Control Key was not accepted.",+ "unavailable": "Could not reach Jarvis. Try again.",+ "where_title": "Where do I find the Control Key?",+ "where_hint": "It was never sent to you — it is generated automatically for this Jarvis install. Open Jarvis on the computer it is installed on: under API Keys → Access & Integrations you can show it, copy it, or replace it with one of your own.",+ "where_hint_server": "On a headless server it is stored in the .control_api_key file inside the Jarvis data folder."},"file_toast": {"show_in_folder": "Show in folder",@@ -1110,17 +1113,30 @@"unavailable": "Needs an OpenAI key. Using standard voice."},"jarvis_api": {- "title": "{name} API",- "key_label": "API key",- "description": "Local agents (Codex, Claude Code) use this key to drive {name} through the Control API — change settings, switch providers or language — instead of clicking the UI.",+ "title": "Control Key",+ "key_label": "Control Key",+ "description": "The one key that protects this {name} install. You enter it to unlock {name} in a browser or from another device, and local agents (Codex, Claude Code) use it to drive {name} through the Control API. It was generated automatically at install time — every install has its own.","show": "Show","hide": "Hide","copy_button": "Copy",- "copied_toast": "API key copied to clipboard.",- "copy_failed_toast": "Could not copy the API key.",- "regenerate_button": "Regenerate key",- "regenerated_toast": "A new API key was generated. Update any agent that used the old one.",- "usage_hint": "Send it as an Authorization: Bearer header to your local {name} (/api/control). GET /api/control/allowlist lists everything you can change."+ "copied_toast": "Control Key copied to clipboard.",+ "copy_failed_toast": "Could not copy the Control Key.",+ "unlock_hint": "The lock screen in the browser asks for exactly this key.",+ "regenerate_button": "Generate random key",+ "regenerate_confirm_title": "Generate a new Control Key?",+ "regenerate_confirm_body": "The current key stops working immediately — everywhere. Every browser, device, and agent still using it will need the new key.",+ "regenerate_confirm_button": "Generate new key",+ "regenerated_toast": "A new Control Key was generated. Hand it to every device and agent that used the old one.",+ "custom_button": "Choose my own key",+ "custom_hint": "Pick a key you can remember — it replaces the current one immediately, everywhere. At least 12 characters; letters, digits, and . _ ~ - only (no spaces).",+ "custom_new_label": "New Control Key",+ "custom_repeat_label": "Repeat new Control Key",+ "custom_too_short": "At least 12 characters are required.",+ "custom_charset": "Only letters, digits, and . _ ~ - are allowed (no spaces).",+ "custom_mismatch": "The two entries do not match.",+ "custom_submit": "Set this key",+ "custom_saved_toast": "Your Control Key is set. It now unlocks {name} everywhere.",+ "usage_hint": "For agents: send it as an Authorization: Bearer header to your local {name} (/api/control). GET /api/control/allowlist lists everything you can change."},"save": "Save changes","saving": "Saving…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f24c5d913a..3853dbe55e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2,13 +2,16 @@"auth_gate": {"checking": "Comprobando el acceso…","title": "Desbloquear Personal Jarvis",- "subtitle": "Introduce la clave de control configurada para esta instancia de Jarvis.",+ "subtitle": "Introduce la clave de control de esta instancia de Jarvis.","control_key": "Clave de control","placeholder": "Pega tu clave de control","submit": "Desbloquear","submitting": "Comprobando…","invalid": "La clave de control no ha sido aceptada.",- "unavailable": "No se pudo conectar con Jarvis. Inténtalo de nuevo."+ "unavailable": "No se pudo conectar con Jarvis. Inténtalo de nuevo.",+ "where_title": "¿Dónde encuentro la clave de control?",+ "where_hint": "Nunca se te envió — se genera automáticamente para esta instalación de Jarvis. Abre Jarvis en el ordenador donde está instalado: en Claves API → Acceso e integraciones puedes mostrarla, copiarla o sustituirla por una propia.",+ "where_hint_server": "En un servidor sin interfaz está en el archivo .control_api_key dentro de la carpeta de datos de Jarvis."},"file_toast": {"show_in_folder": "Mostrar en la carpeta",@@ -1109,17 +1112,30 @@"unavailable": "Necesita una clave de OpenAI. Se usa la voz estándar."},"jarvis_api": {- "title": "{name} API",- "key_label": "Clave de API",- "description": "Los agentes locales (Codex, Claude Code) usan esta clave para controlar {name} a través de la Control API — cambiar ajustes, proveedores o idioma — en lugar de hacer clic en la interfaz.",+ "title": "Clave de control",+ "key_label": "Clave de control",+ "description": "La única clave que protege esta instalación de {name}. Con ella desbloqueas {name} en un navegador o desde otro dispositivo, y los agentes locales (Codex, Claude Code) la usan para controlar {name} a través de la Control API. Se generó automáticamente al instalar — cada instalación tiene la suya.","show": "Mostrar","hide": "Ocultar","copy_button": "Copiar",- "copied_toast": "Clave de API copiada al portapapeles.",- "copy_failed_toast": "No se pudo copiar la clave de API.",- "regenerate_button": "Regenerar clave",- "regenerated_toast": "Se generó una nueva clave de API. Actualiza cualquier agente que usara la anterior.",- "usage_hint": "Envíala como cabecera Authorization: Bearer a tu {name} local (/api/control). GET /api/control/allowlist lista todo lo que puedes cambiar."+ "copied_toast": "Clave de control copiada al portapapeles.",+ "copy_failed_toast": "No se pudo copiar la clave de control.",+ "unlock_hint": "La pantalla de bloqueo del navegador pide exactamente esta clave.",+ "regenerate_button": "Generar clave aleatoria",+ "regenerate_confirm_title": "¿Generar una nueva clave de control?",+ "regenerate_confirm_body": "La clave actual dejará de funcionar de inmediato — en todas partes. Cada navegador, dispositivo y agente que aún la use necesitará la nueva.",+ "regenerate_confirm_button": "Generar nueva clave",+ "regenerated_toast": "Se generó una nueva clave de control. Entrégala a cada dispositivo y agente que usara la anterior.",+ "custom_button": "Elegir mi propia clave",+ "custom_hint": "Elige una clave que puedas recordar — sustituye a la actual de inmediato, en todas partes. Mínimo 12 caracteres; solo letras, dígitos y . _ ~ - (sin espacios).",+ "custom_new_label": "Nueva clave de control",+ "custom_repeat_label": "Repite la nueva clave de control",+ "custom_too_short": "Se requieren al menos 12 caracteres.",+ "custom_charset": "Solo se permiten letras, dígitos y . _ ~ - (sin espacios).",+ "custom_mismatch": "Las dos entradas no coinciden.",+ "custom_submit": "Establecer esta clave",+ "custom_saved_toast": "Tu clave de control está establecida. A partir de ahora desbloquea {name} en todas partes.",+ "usage_hint": "Para agentes: envíala como cabecera Authorization: Bearer a tu {name} local (/api/control). GET /api/control/allowlist lista todo lo que puedes cambiar."},"save": "Guardar","saving": "Guardando…",diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsxindex a0aeb28c7a..419b6aeb2d 100644--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx@@ -12,25 +12,26 @@ vi.mock("@/lib/clipboard", () => ({afterEach(() => vi.restoreAllMocks());+function stubKeyFetch() {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) }),+ );+}+describe("JarvisApiGroup", () => {- it("renders the 'Assistant API' heading and the masked key (full key hidden)", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) }),- );+ it("renders the 'Control Key' heading and the masked key (full key hidden)", async () => {+ stubKeyFetch();render(<JarvisApiGroup />);- expect(screen.getByText("Assistant API")).toBeTruthy();+ expect(screen.getByRole("heading", { name: "Control Key" })).toBeTruthy();await waitFor(() => expect(screen.getByText(MASKED)).toBeTruthy());// The clear key must NOT be on screen until the user reveals it.expect(screen.queryByText(KEY)).toBeNull();});it("reveals the full key when Show is clicked", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) }),- );+ stubKeyFetch();render(<JarvisApiGroup />);await waitFor(() => screen.getByText(MASKED));@@ -39,10 +40,7 @@ describe("JarvisApiGroup", () => {});it("copies the clear key via robustCopy", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) }),- );+ stubKeyFetch();render(<JarvisApiGroup />);await waitFor(() => screen.getByText(MASKED));@@ -50,7 +48,7 @@ describe("JarvisApiGroup", () => {await waitFor(() => expect(robustCopy).toHaveBeenCalledWith(KEY));});- it("rotates the key with confirm=true when Regenerate is clicked", async () => {+ it("rotates only after the confirmation dialog is accepted", async () => {const fetchMock = vi.fn().mockResolvedValueOnce({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) })@@ -62,8 +60,11 @@ describe("JarvisApiGroup", () => {render(<JarvisApiGroup />);await waitFor(() => screen.getByText(MASKED));- fireEvent.click(screen.getByRole("button", { name: /regenerate/i }));+ fireEvent.click(screen.getByRole("button", { name: /generate random key/i }));+ // Opening the dialog must NOT fire the request yet.+ expect(fetchMock.mock.calls.find(([, opts]) => opts?.method === "POST")).toBeUndefined();+ fireEvent.click(screen.getByRole("button", { name: /generate new key/i }));await waitFor(() => {const post = fetchMock.mock.calls.find(([, opts]) => opts?.method === "POST");expect(post).toBeTruthy();@@ -71,4 +72,56 @@ describe("JarvisApiGroup", () => {expect(JSON.parse(post?.[1]?.body as string)).toMatchObject({ confirm: true });});});++ it("sets a user-chosen key via PUT after both entries match", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ ok: true, masked: "…tery" }) });+ vi.stubGlobal("fetch", fetchMock);+ render(<JarvisApiGroup />);+ await waitFor(() => screen.getByText(MASKED));++ fireEvent.click(screen.getByRole("button", { name: /choose my own key/i }));+ fireEvent.change(screen.getByLabelText("New Control Key"), {+ target: { value: "correct-horse-battery" },+ });+ fireEvent.change(screen.getByLabelText("Repeat new Control Key"), {+ target: { value: "correct-horse-battery" },+ });+ fireEvent.click(screen.getByRole("button", { name: /set this key/i }));++ await waitFor(() => {+ const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");+ expect(put).toBeTruthy();+ expect(put?.[0]).toBe("/api/control/api-key");+ expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({+ value: "correct-horse-battery",+ confirm: true,+ });+ });+ });++ it("rejects a too-short custom key locally without any request", async () => {+ stubKeyFetch();+ render(<JarvisApiGroup />);+ await waitFor(() => screen.getByText(MASKED));+ const fetchMock = window.fetch as ReturnType<typeof vi.fn>;+ const callsBefore = fetchMock.mock.calls.length;++ fireEvent.click(screen.getByRole("button", { name: /choose my own key/i }));+ fireEvent.change(screen.getByLabelText("New Control Key"), {+ target: { value: "short" },+ });+ fireEvent.change(screen.getByLabelText("Repeat new Control Key"), {+ target: { value: "short" },+ });+ fireEvent.click(screen.getByRole("button", { name: /set this key/i }));++ await waitFor(() =>+ // Exact message: the form's hint text also mentions "At least 12 characters".+ expect(screen.getByText("At least 12 characters are required.")).toBeTruthy(),+ );+ expect(fetchMock.mock.calls.length).toBe(callsBefore);+ });});diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsxindex f0f2ecb5f0..3a9796bcff 100644--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx@@ -1,31 +1,65 @@-import { useState } from "react";-import { Copy, Eye, EyeOff, KeyRound, RefreshCw } from "lucide-react";+import { type FormEvent, useEffect, useState } from "react";+import {+ AlertTriangle,+ Copy,+ Eye,+ EyeOff,+ KeyRound,+ Loader2,+ PencilLine,+ RefreshCw,+} from "lucide-react";import { Button } from "@/components/ui/button";import { useJarvisApi } from "@/hooks/useJarvisApi";import { robustCopy } from "@/lib/clipboard";import { useEventStore } from "@/store/events";import { useT } from "@/i18n";-import { SettingsBlock } from "@/views/settings/SettingsBlock";+import {+ SettingsBlock,+ SettingsField,+ settingsInputCls,+} from "@/views/settings/SettingsBlock";++// Mirrors jarvis/core/control_key.py (MIN_CUSTOM_KEY_LENGTH / _CUSTOM_KEY_RE)+// so the form rejects locally what the backend would reject anyway.+const MIN_CUSTOM_KEY_LENGTH = 12;+const CUSTOM_KEY_RE = /^[A-Za-z0-9._~-]+$/;/**- * "Jarvis API" group inside the Settings view. Shows the per-user Control API- * key (masked by default, with a Show/Hide toggle), a one-click Copy, and a- * Regenerate button. The key authenticates the local Control API- * (``/api/control/*``) so local coding agents (Codex CLI, Claude Code) can drive- * Jarvis — change settings, switch providers, switch language — over HTTP- * instead of via Computer-Use. Reveal/rotate are loopback-permitted so this- * panel works before the user possesses the key.+ * "Control Key" group — the standardized home of the ONE key that protects a+ * Jarvis install. The same value unlocks the browser UI (the AuthGate lock+ * screen asks for exactly this key) and authenticates the local Control API+ * (``/api/control/*``) for local coding agents. Auto-generated per install;+ * this panel lets the user reveal/copy it, regenerate a random one (behind a+ * confirmation dialog — it invalidates the old key everywhere), or replace it+ * with a memorable key of their own. Reveal/change are session-permitted so+ * the panel works before the user possesses the key.*/export function JarvisApiGroup() {const t = useT();- const { data, loading, error, rotate } = useJarvisApi();+ const { data, loading, error, rotate, setKey } = useJarvisApi();const pushToast = useEventStore((s) => s.pushToast);const [revealed, setRevealed] = useState(false);const [busy, setBusy] = useState(false);+ const [confirmRotate, setConfirmRotate] = useState(false);+ const [formOpen, setFormOpen] = useState(false);+ const [newKey, setNewKey] = useState("");+ const [repeatKey, setRepeatKey] = useState("");+ const [formErrorKey, setFormErrorKey] = useState<string | null>(null);+ const [serverError, setServerError] = useState<string | null>(null);const key = data?.key ?? "";const display = revealed ? key : (data?.masked ?? "…");+ useEffect(() => {+ if (!confirmRotate) return;+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === "Escape") setConfirmRotate(false);+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [confirmRotate]);+async function onCopy() {if (!key) return;const ok = await robustCopy(key);@@ -42,6 +76,7 @@ export function JarvisApiGroup() {try {await rotate();setRevealed(false);+ setConfirmRotate(false);pushToast("success", t("settings_view.jarvis_api.regenerated_toast"));} catch (e) {pushToast("error", (e as Error).message);@@ -50,6 +85,44 @@ export function JarvisApiGroup() {}}+ function closeForm() {+ setFormOpen(false);+ setNewKey("");+ setRepeatKey("");+ setFormErrorKey(null);+ setServerError(null);+ }++ async function onSubmitCustomKey(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();+ const value = newKey.trim();+ setServerError(null);+ if (value.length < MIN_CUSTOM_KEY_LENGTH) {+ setFormErrorKey("settings_view.jarvis_api.custom_too_short");+ return;+ }+ if (!CUSTOM_KEY_RE.test(value)) {+ setFormErrorKey("settings_view.jarvis_api.custom_charset");+ return;+ }+ if (value !== repeatKey.trim()) {+ setFormErrorKey("settings_view.jarvis_api.custom_mismatch");+ return;+ }+ setFormErrorKey(null);+ setBusy(true);+ try {+ await setKey(value);+ setRevealed(false);+ closeForm();+ pushToast("success", t("settings_view.jarvis_api.custom_saved_toast"));+ } catch (e) {+ setServerError((e as Error).message);+ } finally {+ setBusy(false);+ }+ }+return (<SettingsBlockicon={KeyRound}@@ -83,18 +156,134 @@ export function JarvisApiGroup() {<Copy className="mr-1 h-3.5 w-3.5" />{t("settings_view.jarvis_api.copy_button")}</Button>- <Button size="sm" variant="ghost" disabled={busy || loading} onClick={onRotate}>+ </div>++ <p className="text-xs text-muted-foreground">+ {t("settings_view.jarvis_api.unlock_hint")}+ </p>++ <div className="flex items-center gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={busy || loading}+ onClick={() => {+ setServerError(null);+ setFormOpen((v) => !v);+ }}+ >+ <PencilLine className="mr-1 h-3.5 w-3.5" />+ {t("settings_view.jarvis_api.custom_button")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || loading}+ onClick={() => setConfirmRotate(true)}+ ><RefreshCw className="mr-1 h-3.5 w-3.5" />{t("settings_view.jarvis_api.regenerate_button")}</Button></div>+ {formOpen && (+ <form+ className="space-y-3 rounded-xl border border-border bg-background/60 p-4"+ onSubmit={onSubmitCustomKey}+ >+ <p className="text-xs text-muted-foreground">+ {t("settings_view.jarvis_api.custom_hint")}+ </p>+ <SettingsField label={t("settings_view.jarvis_api.custom_new_label")}>+ <input+ autoComplete="new-password"+ className={settingsInputCls}+ disabled={busy}+ onChange={(e) => setNewKey(e.target.value)}+ type="password"+ value={newKey}+ />+ </SettingsField>+ <SettingsField label={t("settings_view.jarvis_api.custom_repeat_label")}>+ <input+ autoComplete="new-password"+ className={settingsInputCls}+ disabled={busy}+ onChange={(e) => setRepeatKey(e.target.value)}+ type="password"+ value={repeatKey}+ />+ </SettingsField>+ {(formErrorKey || serverError) && (+ <p className="text-xs text-destructive" role="alert">+ {formErrorKey ? t(formErrorKey) : serverError}+ </p>+ )}+ <div className="flex justify-end gap-2">+ <Button size="sm" variant="ghost" type="button" disabled={busy} onClick={closeForm}>+ {t("common.cancel")}+ </Button>+ <Button size="sm" type="submit" disabled={busy || !newKey || !repeatKey}>+ {busy ? (+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />+ ) : (+ <KeyRound className="mr-1 h-3.5 w-3.5" />+ )}+ {t("settings_view.jarvis_api.custom_submit")}+ </Button>+ </div>+ </form>+ )}+<p className="text-xs text-muted-foreground">{t("settings_view.jarvis_api.usage_hint")}</p>{error && <p className="text-xs text-destructive">{error}</p>}</div>++ {confirmRotate && (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"+ onClick={(e) => {+ if (e.target === e.currentTarget) setConfirmRotate(false);+ }}+ >+ <div className="card-outline mx-4 w-full max-w-md rounded-xl border border-border bg-card p-5 shadow-2xl">+ <div className="flex items-start gap-3">+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-destructive/40 bg-destructive/10">+ <AlertTriangle className="h-5 w-5 text-destructive" />+ </div>+ <div className="min-w-0 flex-1">+ <h3 className="text-base font-semibold">+ {t("settings_view.jarvis_api.regenerate_confirm_title")}+ </h3>+ <p className="mt-1 text-sm text-muted-foreground">+ {t("settings_view.jarvis_api.regenerate_confirm_body")}+ </p>+ </div>+ </div>+ <div className="mt-5 flex justify-end gap-2">+ <Button+ variant="ghost"+ size="sm"+ disabled={busy}+ onClick={() => setConfirmRotate(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button variant="destructive" size="sm" disabled={busy} onClick={onRotate}>+ {busy ? (+ <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />+ ) : (+ <RefreshCw className="mr-1.5 h-4 w-4" />+ )}+ {t("settings_view.jarvis_api.regenerate_confirm_button")}+ </Button>+ </div>+ </div>+ </div>+ )}</SettingsBlock>);}