Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Settings: API keys in plain sections, one key row everywhere (#3692)

Milind Soni14067581e48a
diff --git a/apps/docs/content/docs/security/analytics.mdx b/apps/docs/content/docs/security/analytics.mdx
index 34ae7b1e8f..e2a41b21dc 100644
--- a/apps/docs/content/docs/security/analytics.mdx
+++ b/apps/docs/content/docs/security/analytics.mdx
@@ -150,8 +150,8 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `team_imported` | You import a team | `members`: count; `source`: `library`, `file`, `github`, `organization`, `scout`; `mode`: `add`, `project`; `format`: `team`, `package`, `backup` |
| `team_scouted` | The app suggests a team for a project folder | `signals`: count |
| `bot_created` | You create a bot with New bot, or from a ready-made bot in Templates | `source`: `blank` (New bot), `template` (a starting role), `preset`; `template`: starting role, only when `source` is `template` |
-| `api_key_saved` | You save a key in Settings → API keys, in the Screen panel, on the X card in Apps, from a bot's request in a chat, or by adding an OpenAI-compatible server | `provider`: key provider; `via`: `settings`, `computer_panel`, `apps`, `chat_request`; `result`: `ok` (the provider accepted it), `rejected` (the provider refused it), `unverified` (saved, not checked), `error` (not saved) |
-| `api_key_removed` | You clear a key of your own in Settings → API keys, the Screen panel or the X card in Apps | `provider`: key provider; `via`: `settings`, `computer_panel`, `apps` |
+| `api_key_saved` | You save a key in Settings → API keys, in the Screen panel, in the model picker, on the X card in Apps, from a bot's request in a chat, or by adding an OpenAI-compatible server | `provider`: key provider; `via`: `settings`, `computer_panel`, `model_picker`, `apps`, `chat_request`; `result`: `ok` (the provider accepted it), `rejected` (the provider refused it), `unverified` (saved, not checked), `error` (not saved) |
+| `api_key_removed` | You clear a key of your own in Settings → API keys, the Screen panel, the model picker or the X card in Apps | `provider`: key provider; `via`: `settings`, `computer_panel`, `model_picker`, `apps` |
| `engine_signed_in` | You finish signing in to an engine inside the app | `engine`: `claude`, `codex`, `grok`; `method`: `code`, `device_code`, `browser` |
| `connector_connect` | A Connect you started in Connected apps ends | `app`: app; `result`: `connected` (the account it added works), `failed` or `expired` (that account failed or expired), `timed_out` (neither within two minutes) |
| `app_snapshot` | Once a day, as described above | The properties in the snapshot table |
diff --git a/docs/analytics.md b/docs/analytics.md
index c1e9ee9382..e0548745c9 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -146,8 +146,8 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `team_imported` | You import a team | `members`: count; `source`: `library`, `file`, `github`, `organization`, `scout`; `mode`: `add`, `project`; `format`: `team`, `package`, `backup` |
| `team_scouted` | The app suggests a team for a project folder | `signals`: count |
| `bot_created` | You create a bot with New bot, or from a ready-made bot in Templates | `source`: `blank` (New bot), `template` (a starting role), `preset`; `template`: starting role, only when `source` is `template` |
-| `api_key_saved` | You save a key in Settings → API keys, in the Screen panel, on the X card in Apps, from a bot's request in a chat, or by adding an OpenAI-compatible server | `provider`: key provider; `via`: `settings`, `computer_panel`, `apps`, `chat_request`; `result`: `ok` (the provider accepted it), `rejected` (the provider refused it), `unverified` (saved, not checked), `error` (not saved) |
-| `api_key_removed` | You clear a key of your own in Settings → API keys, the Screen panel or the X card in Apps | `provider`: key provider; `via`: `settings`, `computer_panel`, `apps` |
+| `api_key_saved` | You save a key in Settings → API keys, in the Screen panel, in the model picker, on the X card in Apps, from a bot's request in a chat, or by adding an OpenAI-compatible server | `provider`: key provider; `via`: `settings`, `computer_panel`, `model_picker`, `apps`, `chat_request`; `result`: `ok` (the provider accepted it), `rejected` (the provider refused it), `unverified` (saved, not checked), `error` (not saved) |
+| `api_key_removed` | You clear a key of your own in Settings → API keys, the Screen panel, the model picker or the X card in Apps | `provider`: key provider; `via`: `settings`, `computer_panel`, `model_picker`, `apps` |
| `engine_signed_in` | You finish signing in to an engine inside the app | `engine`: `claude`, `codex`, `grok`; `method`: `code`, `device_code`, `browser` |
| `connector_connect` | A Connect you started in Connected apps ends | `app`: app; `result`: `connected` (the account it added works), `failed` or `expired` (that account failed or expired), `timed_out` (neither within two minutes) |
| `app_snapshot` | Once a day, as described above | The properties in the snapshot table |
diff --git a/docs/verification/engines.md b/docs/verification/engines.md
index 50ef3e52e7..d07c0ca576 100644
--- a/docs/verification/engines.md
+++ b/docs/verification/engines.md
@@ -52,7 +52,7 @@ prove real OAuth login or native Windows execution.
## Groq API setup
```sh
-pnpm exec vitest run server/drivers/groq.test.ts server/provider-key-check.test.ts server/config.test.ts server/openai-tools.e2e.test.ts src/components/ApiKeys.test.ts src/state/store.test.ts
+pnpm exec vitest run server/drivers/groq.test.ts server/provider-key-check.test.ts server/config.test.ts server/openai-tools.e2e.test.ts src/components/keys/key-catalog.test.ts src/components/keys/KeyRow.test.ts src/state/store.test.ts
```
These fixtures use disposable data and local HTTP providers. They check the
@@ -61,8 +61,8 @@ usage, tool approval/denial/cancellation, and clearing the key. They never call
Groq or verify a real account's quota, model access, or inference.
For a renderer check, use an isolated server with a synthetic Groq endpoint.
-Open **Settings → API keys**, paste its fixture key, and check that **Test**
-reports catalog reachability without claiming chat authentication. Select a
+Open **Settings → API keys**, paste its fixture key and save it, and check that
+the row reports catalog reachability without claiming chat authentication. Select a
Groq model in the bot's picker, send a fixture turn, then clear the key and
confirm the engine is unavailable. Never use the live app or a real key for
this recipe.
@@ -70,7 +70,7 @@ this recipe.
## Meta Muse: Model API and Muse Code
```sh
-pnpm exec vitest run server/drivers/meta.test.ts server/drivers/muse-code.test.ts server/provider-key-check.test.ts server/config.test.ts server/openai-tools.e2e.test.ts src/components/ApiKeys.test.ts src/state/store.test.ts
+pnpm exec vitest run server/drivers/meta.test.ts server/drivers/muse-code.test.ts server/provider-key-check.test.ts server/config.test.ts server/openai-tools.e2e.test.ts src/components/keys/key-catalog.test.ts src/components/keys/KeyRow.test.ts src/state/store.test.ts
```
The Meta Model API fixtures use a local HTTP provider: preset endpoint,
diff --git a/docs/verification/evidence/api-keys/after-advanced-dark.jpg b/docs/verification/evidence/api-keys/after-advanced-dark.jpg
new file mode 100644
index 0000000000..49c8c3fdb8
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-advanced-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-boat-panel-dark.jpg b/docs/verification/evidence/api-keys/after-boat-panel-dark.jpg
new file mode 100644
index 0000000000..0fc720bb9e
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-boat-panel-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-boat-saved-dark.jpg b/docs/verification/evidence/api-keys/after-boat-saved-dark.jpg
new file mode 100644
index 0000000000..df3d4e320b
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-boat-saved-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-keys-dark.jpg b/docs/verification/evidence/api-keys/after-keys-dark.jpg
new file mode 100644
index 0000000000..439479c753
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-keys-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-keys-light.jpg b/docs/verification/evidence/api-keys/after-keys-light.jpg
new file mode 100644
index 0000000000..0f3076b8d8
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-keys-light.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-keys-search-dark.jpg b/docs/verification/evidence/api-keys/after-keys-search-dark.jpg
new file mode 100644
index 0000000000..d94cb22137
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-keys-search-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-keys-sections-dark.jpg b/docs/verification/evidence/api-keys/after-keys-sections-dark.jpg
new file mode 100644
index 0000000000..c2cb0b1046
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-keys-sections-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-keys-sections-light.jpg b/docs/verification/evidence/api-keys/after-keys-sections-light.jpg
new file mode 100644
index 0000000000..82dfe4f3b3
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-keys-sections-light.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-live-landing-dark.jpg b/docs/verification/evidence/api-keys/after-live-landing-dark.jpg
new file mode 100644
index 0000000000..d9a0aaefc5
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-live-landing-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/after-live-notice-dark.jpg b/docs/verification/evidence/api-keys/after-live-notice-dark.jpg
new file mode 100644
index 0000000000..f54796869d
Binary files /dev/null and b/docs/verification/evidence/api-keys/after-live-notice-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/before-boat-panel-dark.jpg b/docs/verification/evidence/api-keys/before-boat-panel-dark.jpg
new file mode 100644
index 0000000000..3dcc499e54
Binary files /dev/null and b/docs/verification/evidence/api-keys/before-boat-panel-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/before-boat-saved-dark.jpg b/docs/verification/evidence/api-keys/before-boat-saved-dark.jpg
new file mode 100644
index 0000000000..2711313737
Binary files /dev/null and b/docs/verification/evidence/api-keys/before-boat-saved-dark.jpg differ
diff --git a/docs/verification/evidence/api-keys/before-keys-dark.jpg b/docs/verification/evidence/api-keys/before-keys-dark.jpg
new file mode 100644
index 0000000000..f18afb55ce
Binary files /dev/null and b/docs/verification/evidence/api-keys/before-keys-dark.jpg differ
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 6f5226c42c..cdd9bd72ec 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -40,7 +40,7 @@ export const AREA_CHECKS = {
* process), with the Electron node tests, which compare their own copy of some
* strings with every catalog. Docs tests: every test that reads the docs. */
export const VITEST_SUBSETS = {
- "locale-tests": { part: "locale tests", files: ["src/", "scripts/generate-locale.test.mjs"], shards: 2, nodeTests: true },
+ "locale-tests": { part: "locale tests", files: ["src/", "scripts/generate-locale.test.mjs", "scripts/testing/key-readback.e2e.test.ts"], shards: 2, nodeTests: true },
"docs-tests": {
part: "docs tests",
files: ["scripts/testing/analytics-docs.test.ts", "server/model-providers-docs.test.ts", "src/locales/vocabulary.test.ts"],
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index 38e6545f73..a4e448bfad 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -164,7 +164,7 @@ describe("CI outputs", () => {
expect(out.jobs).toEqual(["vitest"]);
expect(out.vitest_matrix.include).toEqual([1, 2].map((shard) => ({
os: "ubuntu-latest", part: `locale tests ${shard}/2`, shard, shards: 2,
- files: "src/ scripts/generate-locale.test.mjs", e2e: "all", node_tests: shard === 1,
+ files: "src/ scripts/generate-locale.test.mjs scripts/testing/key-readback.e2e.test.ts", e2e: "all", node_tests: shard === 1,
})));
expect(ciOutputs(selectCiScope(["src/locales/de.json", "src/App.tsx"]), PR).vitest_matrix).toEqual(vitestMatrix(["ubuntu-latest"]));
});
diff --git a/scripts/testing/control-omb-ui.e2e.test.ts b/scripts/testing/control-omb-ui.e2e.test.ts
index 453d401772..aa54a76db5 100644
--- a/scripts/testing/control-omb-ui.e2e.test.ts
+++ b/scripts/testing/control-omb-ui.e2e.test.ts
@@ -152,7 +152,7 @@ describe("control-omb ui drives the real renderer", () => {
expect(launched.child.exitCode).toBe(0);
}, LAUNCH_TIMEOUT_MS + 90_000);
- run("saves a key on Enter, checks it once saved, and keeps a refused or failed draft", async () => {
+ run("saves a key on Enter, checks it once saved, shows it masked, and keeps a refused or failed draft", async () => {
launched = await launch([]);
const { info } = launched;
await fixtureApi(info.url)("PUT", "/api/config", {
@@ -160,10 +160,12 @@ describe("control-omb ui drives the real renderer", () => {
});
const evaluate = async (js: string) => (await ui("eval", info.ui, "--js", js)).result;
const click = (name: string) => ui("click", info.ui, "--name", name);
- const input = `document.querySelector('input[aria-label="OpenAI-compatible API key"]')`;
- const testButton = `[...${input}.closest('[data-api-key-row]').querySelectorAll('button')].find(b => b.textContent === 'Test')`;
- const verdict = () => evaluate(`${input}.closest('[data-api-key-row]').querySelector('[role="status"]')?.textContent`);
- const rowText = () => evaluate(`${input}.closest('[data-api-key-row]').textContent`);
+ const row = `document.querySelector('[data-api-key-row="openaiCompat"]')`;
+ const input = `${row}?.querySelector('[data-key-input]')`;
+ const verdict = () => evaluate(`${row}.querySelector('[role="status"]')?.textContent`);
+ const rowText = () => evaluate(`${row}.textContent`);
+ const masked = () => evaluate(`${row}.querySelector('[data-key-masked]')?.textContent ?? null`);
+ const replace = () => evaluate(`${row}.querySelector('[data-key-replace]').click(); true`);
const type = async (text: string) => {
await click("OpenAI-compatible API key");
await evaluate(`${input}.select(); true`);
@@ -197,21 +199,23 @@ describe("control-omb ui drives the real renderer", () => {
tab?.click();
return Boolean(tab);
})()`), { timeout: 10_000 }).toBe(true);
- // The shared OpenAI-compatible key lives under "Other", open once a key is saved.
- await expect.poll(() => evaluate(`document.querySelector('[data-api-key-row="openaiCompat"]') !== null`), { timeout: 10_000 }).toBe(true);
- await evaluate(`document.querySelector('[data-api-keys-other]').open = true; true`);
+ // The servers section opens on its own, because a key is saved there.
+ await expect.poll(masked, { timeout: 10_000 }).toContain("••••••••-key");
- await expect.poll(() => evaluate(`${testButton}?.disabled ?? null`), { timeout: 10_000 }).toBe(false);
- await click("Test");
+ await expect.poll(() => evaluate(`${row}.querySelector('[data-key-check]')?.disabled ?? null`), { timeout: 10_000 }).toBe(false);
+ await evaluate(`${row}.querySelector('[data-key-check]').click(); true`);
await expect.poll(() => evaluate("window.keyTests")).toEqual([{ provider: "openaiCompat" }]);
await expect.poll(verdict).toBe("Saved key: Model catalog reachable: fixture-model. Authentication and chat not verified.");
+ await replace();
await type(" fixture-draft-key ");
await enter();
- await expect.poll(() => evaluate(`${input}?.value ?? null`), { timeout: 10_000 }).toBe("");
+ await expect.poll(() => evaluate(`${input} ?? null`), { timeout: 10_000 }).toBe(null);
+ await expect.poll(masked, { timeout: 10_000 }).toContain("••••••••-key");
await expect.poll(() => evaluate("window.keyTests")).toEqual([{ provider: "openaiCompat" }, { provider: "openaiCompat" }]);
expect(await evaluate("window.keySaves")).toBe(1);
+ await replace();
await type("not a key at all");
await enter();
await expect.poll(rowText, { timeout: 10_000 }).toContain("That doesn't look like an API key");
@@ -222,12 +226,12 @@ describe("control-omb ui drives the real renderer", () => {
await type("fixture-replacement-key");
await evaluate("window.rejectKeySave = true");
await enter();
- await expect.poll(rowText, { timeout: 10_000 }).toContain("Fixture save rejected");
+ await expect.poll(rowText, { timeout: 10_000 }).toContain("Didn't work: Fixture save rejected");
await expect.poll(() => evaluate(`${input}?.value ?? null`), { timeout: 10_000 }).toBe("fixture-replacement-key");
await evaluate("window.rejectKeySave = false");
await click("OpenAI-compatible API key");
await enter();
- await expect.poll(() => evaluate(`${input}?.value ?? null`), { timeout: 10_000 }).toBe("");
+ await expect.poll(() => evaluate(`${input} ?? null`), { timeout: 10_000 }).toBe(null);
await expect.poll(() => evaluate("window.keyTests.length")).toBe(3);
await expect.poll(verdict).toBe("Saved key: Model catalog reachable: fixture-model. Authentication and chat not verified.");
await waitForExit(launched.child, { signal: "SIGINT", graceMs: 30_000 });
diff --git a/scripts/testing/key-readback.e2e.test.ts b/scripts/testing/key-readback.e2e.test.ts
new file mode 100644
index 0000000000..e2ba9f678f
--- /dev/null
+++ b/scripts/testing/key-readback.e2e.test.ts
@@ -0,0 +1,125 @@
+// Every credential on the keys page, saved through a real server the way its row saves it, read back from GET
+// /api/config and shown masked. The services that check a key before it is kept (Boat, Composio, ElevenLabs, Fish Audio
+// and the decision models) answer from one loopback stand-in, so nothing leaves this machine.
+import { spawn, type ChildProcess } from "node:child_process";
+import { randomBytes } from "node:crypto";
+import { closeSync, openSync, readFileSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+import { launchVerificationServer, verificationServerArgs, verificationServerEnvironment, type VerificationServer } from "../control-omb.ts";
+import { waitForExit } from "../../server/testing/cleanup.ts";
+import { hostTimeout } from "../../server/testing/host-timeout.ts";
+
+const view = vi.hoisted(() => ({ config: {} as Record<string, unknown> }));
+vi.mock("@/state/store", async (original) => {
+ const store = await original<typeof import("@/state/store")>();
+ return { ...store, useStore: () => ({ state: { ...store.initialState, config: view.config, instances: [] }, dispatch: () => {} }) };
+});
+const { KEY_CATALOG, savedState } = await import("@/components/keys/key-catalog");
+const { KeyCatalogRow } = await import("@/components/keys/KeysPage");
+const { setLocale } = await import("@/lib/i18n");
+
+const ROOT = new URL("../..", import.meta.url);
+const ACCOUNT_ID = "0123456789abcdef0123456789abcdef";
+const PREFIX: Record<string, string> = { box: "boat_", composio: "ak_", elevenlabs: "sk_" };
+const EXTRA_PATCH: Record<string, (key: string) => Record<string, unknown>> = {
+ workersAi: (key) => ({ decider: { workersAiToken: key, workersAiAccountId: ACCOUNT_ID } }),
+ imageCustom: (key) => ({ imageGen: { customApiKey: key } }),
+};
+
+let stub: Server;
+let fixture: VerificationServer;
+let server: ChildProcess;
+const stubCalls: string[] = [];
+
+async function call(method: string, path: string, body?: unknown) {
+ const response = await fetch(`${fixture.info.url}${path}`, {
+ method, headers: { "content-type": "application/json", origin: fixture.info.url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),
+ });
+ return { status: response.status, body: await response.json() as Record<string, unknown> };
+}
+
+beforeAll(async () => {
+ stub = createServer(async (req, res) => {
+ const url = req.url ?? "";
+ req.resume();
+ stubCalls.push(`${req.method} ${url.split("?")[0]}`);
+ const reply = (status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
+ if (url.startsWith("/sandboxes")) return reply(200, { ok: true, sandboxes: [], pageInfo: { nextCursor: null } });
+ if (url.startsWith("/composio/tool_router/session")) {
+ return reply(201, { session_id: "trs_readback", mcp: { type: "http", url: "https://app.composio.dev/tool_router/v3/trs_readback/mcp" }, config: { user_id: "openmausbot_readback" } });
+ }
+ if (url.startsWith("/eleven/voices")) return reply(200, { voices: [] });
+ if (url.startsWith("/fish/model")) return reply(200, { items: [], total: 0 });
+ return reply(404, { error: "not in the stand-in" });
+ });
+ await new Promise<void>((resolve) => stub.listen(0, "127.0.0.1", resolve));
+ const origin = `http://127.0.0.1:${(stub.address() as AddressInfo).port}`;
+
+ fixture = await launchVerificationServer();
+ await waitForExit(fixture.child, { signal: "SIGTERM" });
+ const configFile = join(fixture.info.dataDir, "config.json");
+ const decider = { baseUrl: `${origin}/jev`, openrouterBaseUrl: `${origin}/openrouter`, workersAiBaseUrl: `${origin}/cf` };
+ writeFileSync(configFile, JSON.stringify({ ...JSON.parse(readFileSync(configFile, "utf8")), decider }));
+ const env = {
+ ...verificationServerEnvironment({}, fixture.info.dataDir, Number(new URL(fixture.info.url).port)),
+ OMB_BOAT_API: origin, OMB_COMPOSIO_API: `${origin}/composio`, OMB_COMPOSIO_TOOLKITS_API: `${origin}/composio`,
+ OMB_ELEVENLABS_API: `${origin}/eleven`, OMB_FISH_AUDIO_API: `${origin}/fish`,
+ };
+ const log = openSync(fixture.info.logPath, "a", 0o600);
+ server = spawn(process.execPath, verificationServerArgs(env), { cwd: fileURLToPath(ROOT), env, stdio: ["ignore", log, log] });
+ closeSync(log);
+ const deadline = Date.now() + 30_000;
+ while (Date.now() < deadline) {
+ try { if ((await fetch(`${fixture.info.url}/api/health`, { signal: AbortSignal.timeout(1_000) })).ok) return; } catch {}
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ throw new Error(`the server with the stand-in did not start; see ${fixture.info.logPath}`);
+}, hostTimeout(90_000));
+
+afterAll(async () => {
+ if (server) await waitForExit(server, { signal: "SIGTERM" });
+ await fixture?.close();
+ await new Promise<void>((resolve) => stub ? stub.close(() => resolve()) : resolve());
+});
+
+const saveds = KEY_CATALOG.filter((entry) => entry.target || EXTRA_PATCH[entry.id]);
+
+it("saves every kind of credential, reads it back and shows it masked to its last four, then removes it", async () => {
+ setLocale("en");
+ expect(saveds.map((entry) => entry.id)).toEqual([
+ "openai", "anthropic", "xai", "openrouter", "mistral", "cerebras", "groq", "meta", "deepseek", "opencodeGo", "openaiCompat",
+ "liveKey", "elevenlabs", "fishAudio", "box", "composio", "treg", "jev", "openrouterHelper", "workersAi", "imageOpenai", "imageCustom",
+ ]);
+ for (const storage of ["", "?secretStorage=external"]) {
+ for (const entry of saveds) {
+ if (storage && !entry.target?.slot) continue;
+ const key = `${PREFIX[entry.id] ?? "fx-"}${entry.id}-${randomBytes(6).toString("hex")}`;
+ const last4 = key.slice(-4);
+ const patch = (value: string) => entry.target ? entry.target.patch(value, true) : EXTRA_PATCH[entry.id]!(value);
+ const saved = await call("PUT", `/api/config${storage}`, patch(key));
+ expect(saved.status, `${entry.id}${storage}: ${JSON.stringify(saved.body)}`).toBe(200);
+
+ const config = (await call("GET", "/api/config")).body;
+ expect(savedState(entry, config as never), `${entry.id}${storage}`).toEqual({ configured: true, last4 });
+ expect(JSON.stringify(config), entry.id).not.toContain(key);
+ view.config = config;
+ const html = renderToStaticMarkup(createElement(KeyCatalogRow, { entry }));
+ expect(html, entry.id).toContain(`••••••••${last4}`);
+ expect(html, entry.id).toMatch(/>(Connected|Saved)</);
+ expect(html, entry.id).not.toContain(key);
+
+ expect((await call("PUT", `/api/config${storage}`, patch(""))).status, `${entry.id}${storage} removed`).toBe(200);
+ expect(savedState(entry, (await call("GET", "/api/config")).body as never), `${entry.id}${storage} removed`).toEqual({ configured: false });
+ }
+ }
+ expect(stubCalls).toEqual(expect.arrayContaining([
+ "GET /sandboxes", "POST /composio/tool_router/session", "GET /eleven/voices", "GET /fish/model", "POST /jev/v1/systemone", "POST /alpha/decisions",
+ ]));
+}, hostTimeout(180_000));
diff --git a/server/boat-included.e2e.test.ts b/server/boat-included.e2e.test.ts
index 50a7ba198b..5141463f0c 100644
--- a/server/boat-included.e2e.test.ts
+++ b/server/boat-included.e2e.test.ts
@@ -128,7 +128,7 @@ it("once they are gone, the own key wins; clearing it falls back to the included
writeFileSync(journal, JSON.stringify({ version: 1, requests: [] }));
const added = await api("PUT", "/api/config", { box: { token: OWN } });
expect(added.status, JSON.stringify(added.body)).toBe(200);
- expect(added.body.box).toEqual({ configured: true });
+ expect(added.body.box).toEqual({ configured: true, last4: OWN.slice(-4) });
const cleared = await api("PUT", "/api/config", { box: { token: "" } });
expect(cleared.status, JSON.stringify(cleared.body)).toBe(200);
expect(cleared.body.box).toEqual({ configured: true, included: true });
diff --git a/server/index.test.ts b/server/index.test.ts
index 455d0405cc..4990a37999 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -8114,7 +8114,7 @@ describe("harness HTTP API", () => {
const rotated = await api("PUT", "/api/config", { box: { token: " box_route_rotated " } });
expect(rotated.status).toBe(200);
- expect(rotated.body.box).toEqual({ configured: true });
+ expect(rotated.body.box).toEqual({ configured: true, last4: "ated" });
expect(JSON.stringify(rotated.body)).not.toContain("box_route_rotated");
expect((await api("POST", "/api/computers/boxes/bx_23456789/delete", { confirmName: name })).status).toBe(202);
@@ -8151,7 +8151,7 @@ describe("harness HTTP API", () => {
managedBoatRejectedTokens.delete("Bearer box_route_rotated");
const rotated = await api("PUT", "/api/config", { box: { token: "box_route_rotated" } });
expect(rotated.status).toBe(200);
- expect(rotated.body.box).toEqual({ configured: true });
+ expect(rotated.body.box).toEqual({ configured: true, last4: "ated" });
if (provisioned) {
const journal = readFileSync(join(home, ".openmausbot", "box-create-requests.json"), "utf8");
expect(journal).toContain(managedBoatCreateId);
@@ -11693,7 +11693,7 @@ describe("harness HTTP API", () => {
});
expect(saved.status).toBe(200);
expect(saved.body.composio).toEqual({ configured: true, mode: "self-hosted" });
- expect(saved.body.opencodeGo).toEqual({ configured: true, providerKeys: [] });
+ expect(saved.body.opencodeGo).toEqual({ configured: true, last4: "rnal", providerKeys: [] });
expect(saved.body.profile).toEqual({ name: "External Store", email: "", aboutMe: "" });
expect(JSON.stringify(saved.body)).not.toContain("ak_good");
@@ -12272,11 +12272,11 @@ describe("harness HTTP API", () => {
it("stores OpenCode Go credentials as a configured-only status", async () => {
const put = await api("PUT", "/api/config", { opencodeGo: { apiKey: "opencode-secret" } });
expect(put.status).toBe(200);
- expect(put.body.opencodeGo).toEqual({ configured: true, providerKeys: [] });
+ expect(put.body.opencodeGo).toEqual({ configured: true, last4: "cret", providerKeys: [] });
expect(JSON.stringify(put.body)).not.toContain("opencode-secret");
const after = await api("GET", "/api/config");
- expect(after.body.opencodeGo).toEqual({ configured: true, providerKeys: [] });
+ expect(after.body.opencodeGo).toEqual({ configured: true, last4: "cret", providerKeys: [] });
expect(JSON.stringify(after.body)).not.toContain("opencode-secret");
});
diff --git a/server/index.ts b/server/index.ts
index ac530bbb91..7ec06dbcc0 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -93,7 +93,7 @@ import { applyHoldDirective, classifyHoldDirective, heldMemberLine, rememberHeld
import { createPersonStop } from "./host/person-stop.ts";
import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";
import { pickComputer } from "./computer-selection.ts";
-import * as boat from "./boat.ts";
+import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";
import { cloudComputerRpc } from "./cloud-computer-tools.ts";
import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";
import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";
@@ -12121,15 +12121,15 @@ function configStatus() {
const eventLogMaxBytes = threadEventLogMaxBytes(cfg);
const eventLogRetentionDays = threadEventLogRetentionDays(cfg);
return {
- xai: { configured: Boolean(cfg.xai?.key) },
- mistral: { configured: Boolean(cfg.mistral?.key) },
- cerebras: { configured: Boolean(cfg.cerebras?.key) },
- groq: { configured: Boolean(cfg.groq?.key) },
- meta: { configured: Boolean(cfg.meta?.key) }, deepseek: { configured: Boolean(cfg.deepseek?.key) },
- xResearch: xResearchStatus(), treg: { configured: Boolean(cfg.treg?.key?.trim()) },
- anthropic: { configured: Boolean(cfg.anthropic?.key), everyClaudeBot: cfg.anthropic?.everyClaudeBot !== false },
- openai: { configured: Boolean(cfg.openai?.key) },
- openrouter: { configured: Boolean(cfg.openrouter?.key) },
+ xai: keyStatus(cfg.xai?.key),
+ mistral: keyStatus(cfg.mistral?.key),
+ cerebras: keyStatus(cfg.cerebras?.key),
+ groq: keyStatus(cfg.groq?.key),
+ meta: keyStatus(cfg.meta?.key), deepseek: keyStatus(cfg.deepseek?.key),
+ xResearch: xResearchStatus(), treg: keyStatus(cfg.treg?.key),
+ anthropic: { ...keyStatus(cfg.anthropic?.key), everyClaudeBot: cfg.anthropic?.everyClaudeBot !== false },
+ openai: keyStatus(cfg.openai?.key),
+ openrouter: keyStatus(cfg.openrouter?.key),
fleet: { available: fleetAvailable(fleetSocketPath()) },
edition: editionForSettings(editionStatus()),
budgets: {
@@ -12139,17 +12139,17 @@ function configStatus() {
billing: { currency: cfg.billing?.currency ?? "USD", prices: cfg.billing?.prices ?? {} },
decisions: { retentionDays: decisionRetentionDays(cfg.decisions?.retentionDays) },
safetyFloor: { enabled: safetyFloorOn() },
- openaiCompat: { configured: Boolean(cfg.openaiCompat?.key), url: cfg.openaiCompat?.url ?? "" },
+ openaiCompat: { ...keyStatus(cfg.openaiCompat?.key), url: cfg.openaiCompat?.url ?? "" },
composio: {
- configured: composio.configured(cfg),
- mode: composio.connectionMode(cfg),
+ ...(composio.connectionMode(cfg) === "self-hosted" ? keyHint(cfg.composio?.apiKey) : {}),
+ configured: composio.configured(cfg), mode: composio.connectionMode(cfg),
},
- box: boat.describeBoatAccount(cfg),
+ box: { ...boat.describeBoatAccount(cfg), ...(boat.boatAccount(cfg)?.included ? {} : keyHint(cfg.box?.token)) },
vps: { configured: Boolean(vpsSshAlias(cfg)), sshAlias: vpsSshAlias(cfg) ?? "" },
- opencodeGo: { configured: Boolean(cfg.opencodeGo?.apiKey), providerKeys: Object.keys(openCodeProviderKeys(cfg)) },
+ opencodeGo: { ...keyStatus(cfg.opencodeGo?.apiKey), providerKeys: Object.keys(openCodeProviderKeys(cfg)) },
tts: tts.describeVoice(cfg),
decider: describeDecider(cfg), helpers: describeHelpers(cfg),
- imageGen: avatarImageStatus(cfg),
+ imageGen: avatarImageStatus(cfg), savedKeys: nestedKeyStatus(cfg),
live: liveSettingsFor(cfg),
profile: CLOUD_TEAM ? NOBODY_PROFILE : { name: cfg.profile?.name ?? "", email: cfg.profile?.email ?? "", aboutMe: cfg.profile?.aboutMe ?? "", ...(cfg.profile?.avatarUrl ? { avatarUrl: cfg.profile.avatarUrl } : {}) },
managedPolicy: managedPolicy.summary(),
@@ -12207,7 +12207,7 @@ function configForAccess(status: ReturnType<typeof configStatus>, admin: boolean
if (admin) return CLOUD_TEAM ? { ...status, profile } : status;
// Client sessions get configured-or-not only: no SSH alias, email, browser partition id or sign-in list.
return {
- ...status,
+ ...withoutKeyHints(status),
edition: { edition: status.edition.edition, features: status.edition.features },
signIn: { admins: [], members: [] },
vps: { configured: status.vps.configured, sshAlias: "" },
diff --git a/server/key-hint.test.ts b/server/key-hint.test.ts
new file mode 100644
index 0000000000..b48b104d25
--- /dev/null
+++ b/server/key-hint.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { keyHint, keyStatus, withoutKeyHints } from "./key-hint.ts";
+
+describe("a saved key's hint", () => {
+ it("is the last four characters of a key long enough to spare them, and nothing for a short one", () => {
+ expect(keyHint("sk-proj-abcdefgh1234")).toEqual({ last4: "1234" });
+ expect(keyHint(" sk-proj-abcdefgh1234\n")).toEqual({ last4: "1234" });
+ expect(keyHint("short-key")).toEqual({});
+ expect(keyStatus("")).toEqual({ configured: false });
+ expect(keyStatus(undefined)).toEqual({ configured: false });
+ });
+
+ it("comes off everything a client session is sent, at any depth", () => {
+ const status = {
+ openai: { configured: true, last4: "a1b2" },
+ savedKeys: { ttsKey: { configured: true, last4: "c3d4" } },
+ list: [{ configured: true, last4: "e5f6" }],
+ vps: { configured: true, sshAlias: "host" },
+ };
+ expect(withoutKeyHints(status)).toEqual({
+ openai: { configured: true },
+ savedKeys: { ttsKey: { configured: true } },
+ list: [{ configured: true }],
+ vps: { configured: true, sshAlias: "host" },
+ });
+ expect(status.openai.last4).toBe("a1b2");
+ });
+});
diff --git a/server/key-hint.ts b/server/key-hint.ts
new file mode 100644
index 0000000000..f94608356d
--- /dev/null
+++ b/server/key-hint.ts
@@ -0,0 +1,33 @@
+import type { AppConfig } from "./config.ts";
+
+/** Security: a hint is the last four characters of a key long enough that four reveal nothing useful, and only admins
+ * receive one; withoutKeyHints() takes every hint off what a client session is sent. */
+const HINT_MIN_LENGTH = 12;
+
+export function keyHint(secret: string | undefined | null): { last4?: string } {
+ const value = secret?.trim() ?? "";
+ return value.length >= HINT_MIN_LENGTH ? { last4: value.slice(-4) } : {};
+}
+
+export function keyStatus(secret: string | undefined | null): { configured: boolean; last4?: string } {
+ return { configured: Boolean(secret?.trim()), ...keyHint(secret) };
+}
+
+export function nestedKeyStatus(cfg: AppConfig) {
+ return {
+ ttsKey: keyStatus(cfg.tts?.key),
+ fishAudioKey: keyStatus(cfg.tts?.fishKey),
+ jevApiKey: keyStatus(cfg.decider?.key),
+ openrouterDeciderKey: keyStatus(cfg.decider?.openrouterKey),
+ workersAiToken: keyStatus(cfg.decider?.workersAiToken),
+ openaiImageApiKey: keyStatus(cfg.imageGen?.key),
+ customImageApiKey: keyStatus(cfg.imageGen?.customApiKey),
+ openaiLiveKey: keyStatus(cfg.live?.key),
+ };
+}
+
+export function withoutKeyHints<T>(status: T): T {
+ if (Array.isArray(status)) return status.map(withoutKeyHints) as T;
+ if (!status || typeof status !== "object") return status;
+ return Object.fromEntries(Object.entries(status).flatMap(([name, value]) => name === "last4" ? [] : [[name, withoutKeyHints(value)]])) as T;
+}
diff --git a/server/remote-sessions.test.ts b/server/remote-sessions.test.ts
index ca40c65c19..deadc1fc4b 100644
--- a/server/remote-sessions.test.ts
+++ b/server/remote-sessions.test.ts
@@ -499,13 +499,19 @@ describe("pairing", () => {
return opened;
}
expect((await call("/api/config", { method: "PUT", body: JSON.stringify({ opencodeGo: { providerKeys: { VENICE_API_KEY: "venice-fixture-key" } } }) })).status).toBe(200);
+ expect((await call("/api/config", { method: "PUT", body: JSON.stringify({ openai: { key: "sk-proj-fixture-hint-a1b2" }, live: { key: "sk-proj-fixture-live-b2c3" } }) })).status).toBe(200);
function expectClientConfig(config: any) {
+ expect(config.openai).toEqual({ configured: true });
+ expect(config.savedKeys.openaiLiveKey).toEqual({ configured: true });
+ expect(JSON.stringify(config)).not.toContain("last4");
expect(config.opencodeGo).toEqual({ configured: false, providerKeys: [] });
expect(config.profile).toEqual({ name: "Updated fixture", email: "" });
expect(config.vps).toEqual({ configured: true, sshAlias: "" });
expect(config.browserProfiles).toEqual([{ id: "fixture", name: "Fixture browser" }]);
}
function expectAdminConfig(config: any) {
+ expect(config.openai).toEqual({ configured: true, last4: "a1b2" });
+ expect(config.savedKeys.openaiLiveKey).toEqual({ configured: true, last4: "b2c3" });
expect(config.opencodeGo).toEqual({ configured: false, providerKeys: ["VENICE_API_KEY"] });
expect(config.profile).toEqual({ name: "Updated fixture", email: "[email protected]", aboutMe: "" });
expect(config.vps).toEqual({ configured: true, sshAlias: "fixture-private-host" });
diff --git a/server/x-research.e2e.test.ts b/server/x-research.e2e.test.ts
index afcb0b402c..d8bcddaaf3 100644
--- a/server/x-research.e2e.test.ts
+++ b/server/x-research.e2e.test.ts
@@ -113,7 +113,7 @@ it("shows no research tools without a treg key or a Cloud plan, even to a bot sw
}, { plan: false, ownKey: false }), 90_000);
it("with the person's own treg key, every bot has the tools by default and calls go straight to treg, never the relay", async () => withFixture(async (f) => {
- expect((await f.api("/api/config", undefined, "GET")).treg).toEqual({ configured: true });
+ expect((await f.api("/api/config", undefined, "GET")).treg).toEqual({ configured: true, last4: OWN_KEY.slice(-4) });
expect(await f.status()).toEqual({ using: "own", ownKey: true, included: false });
expect(await f.api("/api/keys/test", { provider: "treg" })).toEqual({ ok: true, check: "treg", balanceUsd: 4.25 });
const bot = await f.newBot("Own key");
diff --git a/src/components/ApiKeys.test.ts b/src/components/ApiKeys.test.ts
deleted file mode 100644
index 872d75d702..0000000000
--- a/src/components/ApiKeys.test.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import { createElement } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { StoreProvider } from "@/state/store";
-import * as store from "@/state/store";
-import { AnthropicEveryClaudeBot, ApiKeyRow, desktopCredentialSlot, looksLikeKey, OpenAiCompatUrl, OpenCodeProviderKeys, tregVerdict } from "./ApiKeys";
-
-afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
-
-const render = (element: React.ReactElement) => {
- vi.stubGlobal("window", {});
- return renderToStaticMarkup(createElement(StoreProvider, null, element));
-};
-
-describe("provider key rows", () => {
- it("describes a stored key as configured without claiming an authenticated connection", () => {
- vi.spyOn(store, "useStore").mockReturnValue({
- state: { ...store.initialState, config: {
- ...store.initialState.config, openaiCompat: { configured: true, url: "https://openrouter.ai/api/v1" },
- } as store.ConfigStatus },
- dispatch: vi.fn(),
- flushBotPatches: vi.fn(),
- refreshInstances: vi.fn(),
- refreshModels: vi.fn(),
- });
- const html = render(createElement(ApiKeyRow, { section: "openaiCompat", testProvider: "openaiCompat" }));
- expect(html).toContain("Configured");
- expect(html).not.toContain("Connected");
- expect(html).not.toContain("authenticated");
- expect(html).toContain(">Test<");
- expect(html).toContain('value=""');
- });
-
- it("renders the provider rows write-only, with the provider's own console linked", () => {
- const anthropic = render(createElement(ApiKeyRow, { section: "anthropic", testProvider: "anthropic" }));
- expect(anthropic).toContain("Anthropic API key");
- expect(anthropic).toContain('type="password"');
- expect(anthropic).toContain("sk-ant-…");
- expect(anthropic).toContain('aria-label="About Anthropic API key"');
- expect(anthropic).not.toContain("Connected");
- expect(anthropic).not.toContain(">Test<");
-
- const compat = render(createElement(ApiKeyRow, { section: "openaiCompat", testProvider: "openaiCompat" }));
- expect(compat).toContain("OpenAI-compatible API key");
- expect(compat).toContain("Paste the server&#x27;s API key");
- expect(render(createElement(ApiKeyRow, { section: "openai", testProvider: "openai" }))).toContain("OpenAI API key");
- expect(render(createElement(ApiKeyRow, { section: "openrouter", testProvider: "openrouter" }))).toContain("sk-or-v1-…");
-
- expect(render(createElement(ApiKeyRow, { section: "xai", testProvider: "xai" }))).toContain("xAI API key");
- const groq = render(createElement(ApiKeyRow, { section: "groq", testProvider: "groq" }));
- expect(groq).toContain("Groq API key");
- expect(groq).toContain('type="password"');
- expect(groq).toContain('value=""');
- expect(groq).not.toContain("Connected");
- expect(groq).not.toContain(">Test<");
- const meta = render(createElement(ApiKeyRow, { section: "meta", testProvider: "meta" }));
- expect(meta).toContain("Meta Model API key");
- expect(meta).toContain("LLM|…");
- expect(meta).toContain('type="password"');
- });
-
- it("saves on paste instead of a Save button, and keeps key effects in view", () => {
- const anthropic = render(createElement(ApiKeyRow, { section: "anthropic", testProvider: "anthropic" }));
- expect(anthropic).not.toContain(">Save<");
- const openai = render(createElement(ApiKeyRow, { section: "openai", testProvider: "openai" }));
- expect(openai).toContain("Codex doesn&#x27;t use this key");
- });
-
- it("shows Cloud Pro's included computers as included, not as a saved key the person could clear", () => {
- const withBox = (box: store.ConfigStatus["box"]) => vi.spyOn(store, "useStore").mockReturnValue({
- state: { ...store.initialState, config: { ...store.initialState.config, box } as store.ConfigStatus },
- dispatch: vi.fn(),
- flushBotPatches: vi.fn(),
- refreshInstances: vi.fn(),
- refreshModels: vi.fn(),
- });
- withBox({ configured: true, included: true });
- const included = render(createElement(ApiKeyRow, { section: "box" }));
- expect(included).toContain("Included with your Cloud plan");
- expect(included).not.toContain("Configured");
- expect(included).toContain('placeholder="Paste your Boat API key"');
- expect(included).not.toContain("Remove the saved key");
-
- withBox({ configured: true });
- const own = render(createElement(ApiKeyRow, { section: "box" }));
- expect(own).toContain("Configured");
- expect(own).not.toContain("Included with your Cloud plan");
- });
-
- it("warns about per-token billing only while the Anthropic key runs every Claude bot", () => {
- const withAnthropic = (everyClaudeBot: boolean) => vi.spyOn(store, "useStore").mockReturnValue({
- state: { ...store.initialState, config: { ...store.initialState.config, anthropic: { configured: true, everyClaudeBot } } as store.ConfigStatus },
- dispatch: vi.fn(),
- flushBotPatches: vi.fn(),
- refreshInstances: vi.fn(),
- refreshModels: vi.fn(),
- });
- withAnthropic(false);
- const off = render(createElement(AnthropicEveryClaudeBot));
- expect(off).toContain("Use this key for every Claude bot");
- expect(off).toContain("Signed-in Claude bots stay on their plan");
- expect(off).not.toContain("instead of a Claude login");
- withAnthropic(true);
- expect(render(createElement(AnthropicEveryClaudeBot))).toContain("instead of a Claude login");
- });
-
- it("refuses pasted text that is not a key", () => {
- expect(looksLikeKey("sk-proj-abc123_DEF")).toBe(true);
- expect(looksLikeKey("The mascots are ready")).toBe(false);
- expect(looksLikeKey("sk-abc\n")).toBe(false);
- });
-
- it("lists the keys saved for OpenCode's other providers by name, with a way to add and remove one", () => {
- const withKeys = (providerKeys: string[] | undefined) => vi.spyOn(store, "useStore").mockReturnValue({
- state: { ...store.initialState, config: { ...store.initialState.config, opencodeGo: { configured: false, providerKeys } } as store.ConfigStatus },
- dispatch: vi.fn(),
- flushBotPatches: vi.fn(),
- refreshInstances: vi.fn(),
- refreshModels: vi.fn(),
- });
- withKeys(["GROQ_API_KEY", "VENICE_API_KEY"]);
- const saved = render(createElement(OpenCodeProviderKeys));
- expect(saved).toContain("Keys for other OpenCode providers");
- expect(saved).toMatch(/<details[^>]*open=""/);
- for (const name of ["GROQ_API_KEY", "VENICE_API_KEY"]) {
- expect(saved).toContain(`data-opencode-provider-key="${name}"`);
- expect(saved).toContain(`aria-label="Remove ${name}"`);
- }
- expect(saved).toContain('placeholder="VENICE_API_KEY"');
- expect(saved).toContain('aria-label="Key name"');
- expect(saved).toMatch(/<input type="password"[^>]*aria-label="Key"/);
-
- withKeys(undefined);
- const none = render(createElement(OpenCodeProviderKeys));
- expect(none).not.toMatch(/<details[^>]*open=""/);
- expect(none).not.toContain("data-opencode-provider-key=");
- expect(none).toContain("such as VENICE_API_KEY for Venice");
- });
-
- it("offers the base URL as a setting next to the key", () => {
- const html = render(createElement(OpenAiCompatUrl));
- expect(html).toContain("OpenAI-compatible base URL");
- expect(html).toContain('placeholder="https://api.groq.com/openai/v1"');
- expect(html).toContain("localhost:11434/v1");
- });
-});
-
-
-describe("the treg key row", () => {
- it("is write-only and shows where to get a key, under the field", () => {
- const html = render(createElement(ApiKeyRow, { section: "treg", testProvider: "treg" }));
- expect(html).toContain("treg key");
- expect(html).toContain('type="password"');
- expect(html).toContain('value=""');
- expect(html).toMatch(/<a href="https:\/\/treg\.to"[^>]*>Get a key at treg\.to/);
- });
-
- it("says treg is working with the balance, or names the exact problem", () => {
- expect(tregVerdict({ ok: true, check: "treg", balanceUsd: 4.25 } as never)).toBe("treg is working ✓ Balance: $4.25.");
- expect(tregVerdict({ ok: true })).toBe("treg is working ✓");
- expect(tregVerdict({ ok: false, message: "treg rejected this key. Copy it again from treg.to." })).toBe("treg rejected this key. Copy it again from treg.to.");
- });
-});
-
-describe("desktop credential slots", () => {
- it("saves the desktop-held keys in the encrypted store, so Clear removes them there too", () => {
- expect(desktopCredentialSlot("treg")).toBe("tregApiKey");
- expect(desktopCredentialSlot("box")).toBe("boxToken");
- expect(desktopCredentialSlot("openai")).toBeUndefined();
- });
-});
diff --git a/src/components/ApiKeys.tsx b/src/components/ApiKeys.tsx
deleted file mode 100644
index 4532bbd373..0000000000
--- a/src/components/ApiKeys.tsx
+++ /dev/null
@@ -1,723 +0,0 @@
-// Security: secrets are write-only; GET /api/config returns configured flags, never values.
-import { useEffect, useId, useRef, useState } from "react";
-import { Check, CircleHelp, ExternalLink, Loader2, TriangleAlert } from "lucide-react";
-import { api, useStore, type ConfigStatus } from "@/state/store";
-import { cn } from "@/lib/cn";
-import { useMenuMotion } from "./MenuMotion";
-import { t } from "@/lib/i18n";
-import type { LocaleKey } from "@/locales";
-import { SECTION_PROVIDER, type KeyResult, type KeyVia } from "@/lib/analytics-allowlist";
-import { keyRemoved, keySaved, keySaveFailure, keyTestResult, savedKeyResult } from "@/lib/product-events";
-
-export type ConfigSection = "composio" | "box" | "opencodeGo" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "xai" | "mistral" | "cerebras" | "groq" | "meta" | "treg" | "deepseek";
-export type TestableProvider = "anthropic" | "openai" | "openrouter" | "openaiCompat" | "xai" | "mistral" | "cerebras" | "groq" | "meta" | "treg";
-
-const SECTIONS: Record<
- ConfigSection,
- {
- body: (value: string, firstKey: boolean) => unknown;
- flag: (config: ConfigStatus) => boolean;
- included?: (config: ConfigStatus) => boolean;
- }
-> = {
- composio: {
- body: (v) => ({ composio: { apiKey: v } }),
- // Only a project key of the person's own: the managed connection has its own "ready" line and nothing to clear.
- flag: (c) => c.composio.configured && (c.composio.mode ?? "self-hosted") === "self-hosted",
- },
- box: {
- body: (v) => ({ box: { token: v } }),
- flag: (c) => c.box.configured && c.box.included !== true,
- included: (c) => c.box.included === true,
- },
- opencodeGo: { body: (v) => ({ opencodeGo: { apiKey: v } }), flag: (c) => c.opencodeGo?.configured ?? false },
- anthropic: {
- body: (v, firstKey) => ({ anthropic: { key: v, ...(firstKey && v ? { everyClaudeBot: false } : {}) } }),
- flag: (c) => c.anthropic?.configured ?? false,
- },
- openai: { body: (v) => ({ openai: { key: v } }), flag: (c) => c.openai?.configured ?? false },
- openrouter: { body: (v) => ({ openrouter: { key: v } }), flag: (c) => c.openrouter?.configured ?? false },
- openaiCompat: { body: (v) => ({ openaiCompat: { key: v } }), flag: (c) => c.openaiCompat?.configured ?? false },
- mistral: { body: (v) => ({ mistral: { key: v } }), flag: (c) => c.mistral?.configured ?? false },
- cerebras: { body: (v) => ({ cerebras: { key: v } }), flag: (c) => c.cerebras?.configured ?? false },
- groq: { body: (v) => ({ groq: { key: v } }), flag: (c) => c.groq?.configured ?? false },
- meta: { body: (v) => ({ meta: { key: v } }), flag: (c) => c.meta?.configured ?? false },
- deepseek: { body: (v) => ({ deepseek: { key: v } }), flag: (c) => c.deepseek?.configured ?? false },
- xai: { body: (v) => ({ xai: { key: v } }), flag: (c) => c.xai?.configured ?? false },
- treg: { body: (v) => ({ treg: { key: v } }), flag: (c) => c.treg?.configured ?? false },
-};
-
-// Provider keys have no desktop-shell slot yet; they go to the server's own 0600 config. A secret the desktop's boot
-// migration moves into its encrypted store must save here, so Clear removes the stored copy too.
-const ELECTRON_CREDENTIAL: Partial<Record<ConfigSection, "composioApiKey" | "boxToken" | "opencodeGoApiKey" | "tregApiKey">> = {
- composio: "composioApiKey",
- box: "boxToken",
- opencodeGo: "opencodeGoApiKey",
- treg: "tregApiKey",
-};
-
-/** The desktop shell's encrypted slot for a section, if it has one. */
-export function desktopCredentialSlot(section: ConfigSection) {
- return ELECTRON_CREDENTIAL[section];
-}
-
-/** Saves one credential where this app keeps it ("" removes it): the desktop's encrypted store when the section has a
- * slot there, else the server's own config, which on a Cloud home stays outside every bot's box. */
-export function saveCredential(section: ConfigSection, value: string, firstKey: boolean): Promise<ConfigStatus> {
- const electronSlot = desktopCredentialSlot(section);
- return window.ogb?.setCredential && electronSlot
- ? window.ogb.setCredential(electronSlot, value)
- : api("/api/config", { method: "PUT", body: JSON.stringify(SECTIONS[section].body(value, firstKey)) });
-}
-
-const CREDENTIALS: Record<
- ConfigSection,
- {
- labelKey: LocaleKey;
- placeholder?: string;
- placeholderKey?: LocaleKey;
- descriptionKey: LocaleKey;
- href: string;
- linkLabelKey: LocaleKey;
- optional: boolean;
- warningKey?: LocaleKey;
- noteKey?: LocaleKey;
- /** The "get a key" link shows under the field, not only in the help popover. */
- showLink?: boolean;
- }
-> = {
- composio: {
- labelKey: "keys.composio.label",
- placeholder: "ak_…",
- descriptionKey: "keys.composio.desc",
- href: "https://dashboard.composio.dev",
- linkLabelKey: "keys.composio.link",
- optional: true,
- },
- box: {
- labelKey: "keys.boat.label",
- placeholderKey: "keys.boat.placeholder",
- descriptionKey: "keys.boat.desc",
- href: "https://docs.boat.dev/api-keys",
- linkLabelKey: "keys.boat.link",
- optional: true,
- warningKey: "keys.boat.warning",
- },
- opencodeGo: {
- labelKey: "keys.opencode.label",
- placeholderKey: "keys.opencode.placeholder",
- descriptionKey: "keys.opencode.desc",
- href: "https://opencode.ai/docs/providers/",
- linkLabelKey: "keys.opencode.link",
- optional: true,
- },
- anthropic: {
- labelKey: "keys.anthropic.label",
- placeholder: "sk-ant-…",
- descriptionKey: "keys.anthropic.desc",
- href: "https://console.anthropic.com/settings/keys",
- linkLabelKey: "keys.anthropic.link",
- optional: true,
- },
- openai: {
- labelKey: "keys.openai.label",
- placeholder: "sk-…",
- descriptionKey: "keys.openai.desc",
- href: "https://platform.openai.com/api-keys",
- linkLabelKey: "keys.openai.link",
- optional: true,
- noteKey: "keys.openai.note",
- },
- openrouter: {
- labelKey: "keys.openrouter.label",
- placeholder: "sk-or-v1-…",
- descriptionKey: "keys.openrouter.desc",
- href: "https://openrouter.ai/keys",
- linkLabelKey: "keys.openrouter.link",
- optional: true,
- },
- openaiCompat: {
- labelKey: "keys.openaiCompat.label",
- placeholderKey: "keys.openaiCompat.placeholder",
- descriptionKey: "keys.openaiCompat.desc",
- href: "https://platform.openai.com/docs/api-reference",
- linkLabelKey: "keys.openaiCompat.link",
- optional: true,
- },
- mistral: {
- labelKey: "keys.mistral.label",
- placeholderKey: "keys.mistral.placeholder",
- descriptionKey: "keys.mistral.desc",
- href: "https://console.mistral.ai/api-keys",
- linkLabelKey: "keys.mistral.link",
- optional: true,
- },
- cerebras: {
- labelKey: "keys.cerebras.label",
- placeholder: "csk-…",
- descriptionKey: "keys.cerebras.desc",
- href: "https://cloud.cerebras.ai/",
- linkLabelKey: "keys.cerebras.link",
- optional: true,
- },
- groq: {
- labelKey: "keys.groq.label",
- placeholder: "gsk_…",
- descriptionKey: "keys.groq.desc",
- href: "https://console.groq.com/docs/overview",
- linkLabelKey: "keys.groq.link",
- optional: true,
- },
- meta: {
- labelKey: "keys.meta.label",
- placeholder: "LLM|…",
- descriptionKey: "keys.meta.desc",
- href: "https://dev.meta.ai/docs/authentication",
- linkLabelKey: "keys.meta.link",
- optional: true,
- },
- deepseek: {
- labelKey: "keys.deepseek.label",
- placeholder: "sk-…",
- descriptionKey: "keys.deepseek.desc",
- href: "https://platform.deepseek.com/api_keys",
- linkLabelKey: "keys.deepseek.link",
- optional: true,
- },
- xai: {
- labelKey: "keys.xai.label",
- placeholder: "xai-…",
- descriptionKey: "keys.xai.desc",
- href: "https://console.x.ai",
- linkLabelKey: "keys.xai.link",
- optional: true,
- },
- treg: {
- labelKey: "keys.treg.label",
- placeholderKey: "keys.treg.placeholder",
- descriptionKey: "keys.treg.desc",
- href: "https://treg.to",
- linkLabelKey: "keys.treg.link",
- optional: true,
- showLink: true,
- },
-};
-
-/** The catalog is read when a row renders, not when this module loads. */
-function credentialCopy(section: ConfigSection) {
- const entry = CREDENTIALS[section];
- return {
- ...entry,
- label: t(entry.labelKey),
- placeholder: entry.placeholderKey ? t(entry.placeholderKey) : entry.placeholder ?? "",
- description: t(entry.descriptionKey),
- linkLabel: t(entry.linkLabelKey),
- warning: entry.warningKey ? t(entry.warningKey) : undefined,
- note: entry.noteKey ? t(entry.noteKey) : undefined,
- };
-}
-
-function CredentialHelp({ section }: { section: ConfigSection }) {
- const credential = credentialCopy(section);
- const [open, setOpen] = useState(false);
- const motion = useMenuMotion(open);
- const rootRef = useRef<HTMLDivElement>(null);
- const buttonRef = useRef<HTMLButtonElement>(null);
- const popoverId = useId();
-
- useEffect(() => {
- if (!open) return;
-
- const closeOnOutsideClick = (event: PointerEvent) => {
- if (event.target instanceof Node && !rootRef.current?.contains(event.target)) setOpen(false);
- };
- const closeOnEscape = (event: KeyboardEvent) => {
- if (event.key !== "Escape") return;
- setOpen(false);
- buttonRef.current?.focus();
- };
-
- document.addEventListener("pointerdown", closeOnOutsideClick);
- document.addEventListener("keydown", closeOnEscape);
- return () => {
- document.removeEventListener("pointerdown", closeOnOutsideClick);
- document.removeEventListener("keydown", closeOnEscape);
- };
- }, [open]);
-
- return (
- <div ref={rootRef} className="relative ml-auto">
- <button
- ref={buttonRef}
- type="button"
- aria-label={t("keys.aboutAria", { label: credential.label })}
- aria-expanded={open}
- aria-controls={popoverId}
- onClick={() => setOpen((current) => !current)}
- className="cursor-pointer flex size-6 items-center justify-center rounded-md text-ink-secondary outline-none transition-colors hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent/70"
- >
- <CircleHelp size={14} aria-hidden="true" />
- </button>
- {motion.shown && (
- <div
- id={popoverId}
- role="group"
- aria-label={t("keys.helpAria", { label: credential.label })}
- className={cn("absolute right-0 z-30 mt-1.5 w-[270px] rounded-xl border border-hairline bg-panel p-3 text-left shadow-2xl", motion.className)} {...motion.exitProps}
- >
- <div className="text-[12px] leading-[1.45] text-ink-secondary">{credential.description}</div>
- <a
- href={credential.href}
- target="_blank"
- rel="noopener noreferrer"
- onClick={() => setOpen(false)}
- className="mt-2.5 flex items-center gap-1.5 text-[12px] font-medium text-accent hover:underline focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/70"
- >
- {credential.linkLabel}
- <ExternalLink size={12} aria-hidden="true" />
- </a>
- </div>
- )}
- </div>
- );
-}
-
-/** "treg is working ✓" with the team's balance, or the exact problem the server's check named. */
-export function tregVerdict(result: { ok?: unknown; balanceUsd?: unknown; message?: unknown }): string {
- if (result.ok !== true) return typeof result.message === "string" && result.message ? result.message : t("keys.testUnexpected", { status: "?" });
- const balance = typeof result.balanceUsd === "number" ? ` ${t("keys.treg.balance", { balance: `$${result.balanceUsd.toFixed(2)}` })}` : "";
- return `${t("keys.treg.working")}${balance}`;
-}
-
-export function looksLikeKey(value: string): boolean {
- return value.length > 0 && !/\s/.test(value);
-}
-
-export function ApiKeyRow({
- section,
- onSaved,
- testProvider,
- via = "settings",
-}: {
- section: ConfigSection;
- onSaved?: (configured: boolean) => void;
- testProvider?: TestableProvider;
- via?: KeyVia;
-}) {
- const { state, dispatch } = useStore();
- const [value, setValue] = useState("");
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [testing, setTesting] = useState(false);
- const [verdict, setVerdict] = useState<string | null>(null);
- const testGeneration = useRef(0);
- // A ref, not the state: blur and Enter can both fire before a re-render.
- const savingRef = useRef(false);
- const saveAfterPaste = useRef(false);
-
- const configured = state.config ? SECTIONS[section].flag(state.config) : false;
- const included = state.config ? SECTIONS[section].included?.(state.config) === true : false;
- const clearing = !value.trim() && configured;
- const credential = credentialCopy(section);
-
- const test = async (): Promise<KeyResult> => {
- if (!testProvider) return "unverified";
- setTesting(true);
- setVerdict(null);
- const generation = ++testGeneration.current;
- try {
- const result = await api("/api/keys/test", { method: "POST", body: JSON.stringify({ provider: testProvider }) });
- if (generation !== testGeneration.current) return keyTestResult(result);
- if (result.check === "treg") {
- setVerdict(tregVerdict(result));
- return keyTestResult(result);
- }
- const outcome = result.ok
- ? result.check === "authentication"
- ? result.freeTier === true ? `${t("keys.testAuthenticated")}\n${t("keys.testFreeTier")}` : t("keys.testAuthenticated")
- : result.models?.length ? t("keys.testCatalog", { models: result.models.join(", ") }) : t("keys.testCatalogNoModels")
- : result.reason === "rejected" ? t("keys.testRejected")
- : result.reason === "unreachable" ? t("keys.testUnreachable")
- : t("keys.testUnexpected", { status: String(result.status ?? "?") });
- setVerdict(`${t("keys.testSaved")} ${outcome}`);
- return keyTestResult(result);
- } catch (cause) {
- if (generation === testGeneration.current) setVerdict(cause instanceof Error ? cause.message : String(cause));
- return keyTestResult(null);
- } finally {
- if (generation === testGeneration.current) setTesting(false);
- }
- };
-
- const save = (remove = false) => {
- const next = remove ? "" : value.trim();
- if (savingRef.current || (!remove && !next)) return;
- if (!remove && !looksLikeKey(next)) {
- setError(t("keys.notAKey"));
- return;
- }
- savingRef.current = true;
- setSaving(true);
- setError(null);
- testGeneration.current++;
- setVerdict(null);
- saveCredential(section, next, !configured)
- .then((status: ConfigStatus) => {
- dispatch({ type: "configStatus", config: status });
- setValue("");
- const nowConfigured = SECTIONS[section].flag(status);
- onSaved?.(nowConfigured);
- const provider = SECTION_PROVIDER[section];
- if (!next) {
- if (configured) keyRemoved(provider, via);
- } else if (testProvider && nowConfigured) void test().then((result) => keySaved(provider, via, result));
- else keySaved(provider, via, savedKeyResult(provider));
- })
- .catch((e) => {
- setError(e.message);
- if (next) keySaved(SECTION_PROVIDER[section], via, keySaveFailure(e));
- })
- .finally(() => { savingRef.current = false; setSaving(false); });
- };
-
- useEffect(() => {
- if (!saveAfterPaste.current) return;
- saveAfterPaste.current = false;
- save();
- });
-
- return (
- <div data-api-key-row={section}>
- <div className="mb-1.5 flex items-center gap-2 text-[13px] text-ink-secondary">
- <span className={cn("size-1.5 rounded-full", configured || included ? "bg-success" : "bg-raised-hover")} />
- <span>{credential.label}</span>
- {credential.optional && (
- <span className="rounded bg-control px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-ink-secondary">
- {t("keys.optional")}
- </span>
- )}
- {configured && <span className="text-[11px] text-ink-secondary">{t("keys.configured")}</span>}
- {included && <span className="text-[11px] text-ink-secondary">{t("keys.includedWithCloudPro")}</span>}
- <CredentialHelp section={section} />
- </div>
- <div className="flex gap-2">
- <div className="relative w-full">
- <input
- type="password"
- value={value}
- onChange={(e) => { testGeneration.current++; setVerdict(null); setError(null); setValue(e.target.value); }}
- onPaste={() => { saveAfterPaste.current = true; }}
- onBlur={() => save()}
- disabled={saving}
- onKeyDown={(e) => e.key === "Enter" && save()}
- placeholder={configured ? t("keys.replace") : credential.placeholder}
- aria-label={credential.label}
- autoComplete="off"
- className="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 pr-8 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"
- />
- {(saving || testing) && (
- <Loader2 size={13} aria-hidden="true" className="absolute right-2.5 top-1/2 -translate-y-1/2 animate-spin text-ink-secondary" />
- )}
- </div>
- {clearing && (
- <button
- type="button"
- onClick={() => save(true)}
- disabled={saving}
- className="cursor-pointer flex w-[72px] shrink-0 items-center justify-center rounded-lg bg-control py-2 text-[13px] text-danger hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50"
- title={t("keys.removeKey")}
- >
- {t("keys.clear")}
- </button>
- )}
- {testProvider && clearing && (
- <button
- type="button"
- onClick={() => void test()}
- disabled={testing || saving}
- className="cursor-pointer flex shrink-0 items-center justify-center rounded-lg border border-hairline/40 px-3 py-2 text-[13px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:cursor-not-allowed disabled:opacity-50"
- >
- {testing ? t("keys.testing") : t("keys.test")}
- </button>
- )}
- </div>
- {credential.warning && (
- <div className="mt-1.5 flex gap-1.5 text-[12px] leading-[1.4] text-warning">
- <TriangleAlert size={13} className="mt-px shrink-0" aria-hidden="true" />
- <span>{credential.warning}</span>
- </div>
- )}
- {credential.note && <p className="mt-1.5 text-[12px] leading-[1.4] text-ink-secondary">{credential.note}</p>}
- {credential.showLink && (
- <a href={credential.href} target="_blank" rel="noopener noreferrer" className="mt-1.5 inline-flex items-center gap-1 text-[12px] font-medium text-accent-text hover:underline">
- {credential.linkLabel}
- <ExternalLink size={11} aria-hidden="true" />
- </a>
- )}
- {error && <div className="mt-1 text-[12px] text-danger">{error}</div>}
- {verdict && <div role="status" className="mt-1 whitespace-pre-line text-[12px] text-ink-secondary">{verdict}</div>}
- </div>
- );
-}
-
-/** Security: write-only; the server returns names, never keys, and hands the keys to OpenCode alone. */
-export function OpenCodeProviderKeys() {
- const { state, dispatch } = useStore();
- const names = state.config?.opencodeGo?.providerKeys ?? [];
- const [name, setName] = useState("");
- const [key, setKey] = useState("");
- const [adding, setAdding] = useState(false);
- const [removing, setRemoving] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const busy = adding || removing !== null;
-
- const put = (target: string, value: string) =>
- api("/api/config", { method: "PUT", body: JSON.stringify({ opencodeGo: { providerKeys: { [target]: value } } }) })
- .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }));
-
- const add = () => {
- const target = name.trim().toUpperCase();
- const value = key.trim();
- if (busy || !target || !value) return;
- if (!looksLikeKey(value)) {
- setError(t("keys.notAKey"));
- return;
- }
- setAdding(true);
- setError(null);
- put(target, value)
- .then(() => { setName(""); setKey(""); })
- .catch((e) => setError(e.message))
- .finally(() => setAdding(false));
- };
-
- const remove = (target: string) => {
- if (busy) return;
- setRemoving(target);
- setError(null);
- put(target, "")
- .catch((e) => setError(e.message))
- .finally(() => setRemoving(null));
- };
-
- return (
- <details data-opencode-provider-keys className="rounded-lg border border-hairline/40 bg-inset px-3 py-2" open={names.length > 0}>
- <summary className="cursor-pointer text-[13px] text-ink-secondary">{t("keys.opencode.otherProviders.title")}</summary>
- <div className="mt-3 flex flex-col gap-2">
- <p className="text-[12px] leading-relaxed text-ink-secondary">{t("keys.opencode.otherProviders.hint")}</p>
- {names.map((saved) => (
- <div key={saved} data-opencode-provider-key={saved} className="flex items-center gap-2">
- <span className="size-1.5 shrink-0 rounded-full bg-success" />
- <code className="min-w-0 flex-1 truncate font-mono text-[12px] text-ink">{saved}</code>
- <span className="text-[11px] text-ink-secondary">{t("keys.configured")}</span>
- <button
- type="button"
- onClick={() => remove(saved)}
- disabled={busy}
- aria-label={t("keys.opencode.otherProviders.removeAria", { name: saved })}
- className="cursor-pointer flex w-[72px] shrink-0 items-center justify-center rounded-lg bg-control py-1.5 text-[13px] text-danger hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50"
- >
- {removing === saved ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.clear")}
- </button>
- </div>
- ))}
- <div className="flex gap-2">
- <input
- type="text"
- value={name}
- onChange={(e) => { setError(null); setName(e.target.value); }}
- onKeyDown={(e) => e.key === "Enter" && add()}
- disabled={busy}
- placeholder="VENICE_API_KEY"
- aria-label={t("keys.opencode.otherProviders.name")}
- autoComplete="off"
- spellCheck={false}
- className="w-[44%] min-w-0 rounded-lg border border-hairline/40 bg-panel px-3 py-2 font-mono text-[12px] uppercase text-ink placeholder:normal-case placeholder:text-ink-secondary focus:outline-none"
- />
- <input
- type="password"
- value={key}
- onChange={(e) => { setError(null); setKey(e.target.value); }}
- onKeyDown={(e) => e.key === "Enter" && add()}
- disabled={busy}
- placeholder={t("keys.opencode.otherProviders.keyPlaceholder")}
- aria-label={t("keys.opencode.otherProviders.key")}
- autoComplete="off"
- className="w-full min-w-0 rounded-lg border border-hairline/40 bg-panel px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"
- />
- <button
- type="button"
- onClick={add}
- disabled={busy || !name.trim() || !key.trim()}
- className="cursor-pointer flex w-[72px] shrink-0 items-center justify-center gap-1.5 rounded-lg bg-control py-2 text-[13px] text-ink hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50"
- >
- {adding ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : <><Check size={13} aria-hidden="true" />{t("common.save")}</>}
- </button>
- </div>
- {error && <div role="alert" className="text-[12px] text-danger">{error}</div>}
- </div>
- </details>
- );
-}
-
-export function AnthropicEveryClaudeBot() {
- const { state, dispatch } = useStore();
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
- if (!state.config?.anthropic?.configured) return null;
- const on = state.config.anthropic.everyClaudeBot === true;
- const toggle = () => {
- if (saving) return;
- setSaving(true);
- setError(null);
- api("/api/config", { method: "PUT", body: JSON.stringify({ anthropic: { everyClaudeBot: !on } }) })
- .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))
- .catch((e) => setError(e.message))
- .finally(() => setSaving(false));
- };
- return (
- <div data-anthropic-every-claude-bot className="-mt-2">
- <label className="flex cursor-pointer items-start gap-2 text-[13px] text-ink">
- <input type="checkbox" checked={on} disabled={saving} onChange={toggle} className="mt-0.5 accent-accent" />
- <span>
- {t("keys.anthropic.everyBot")}
- <span className="block text-[12px] leading-[1.4] text-ink-secondary">
- {on ? t("keys.anthropic.everyBotOn") : t("keys.anthropic.everyBotOff")}
- </span>
- </span>
- </label>
- {on && (
- <div className="mt-1.5 flex gap-1.5 text-[12px] leading-[1.4] text-warning">
- <TriangleAlert size={13} className="mt-px shrink-0" aria-hidden="true" />
- <span>{t("keys.anthropic.warning")}</span>
- </div>
- )}
- {error && <div className="mt-1 text-[12px] text-danger">{error}</div>}
- </div>
- );
-}
-
-/** Non-secret Docker-over-SSH target. Keys and passwords stay with SSH. */
-export function VpsConnection() {
- const { state, dispatch } = useStore();
- const [alias, setAlias] = useState("");
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const configured = Boolean(state.config?.vps?.configured);
-
- useEffect(() => {
- setAlias(state.config?.vps?.sshAlias ?? "");
- }, [state.config?.vps?.sshAlias]);
-
- const save = () => {
- if (saving || (!alias.trim() && !configured)) return;
- setSaving(true);
- setError(null);
- api("/api/config", {
- method: "PUT",
- body: JSON.stringify({ vps: { sshAlias: alias.trim() } }),
- })
- .then((status: ConfigStatus) => {
- dispatch({ type: "configStatus", config: status });
- setAlias(status.vps?.sshAlias ?? "");
- })
- .catch((e) => setError(e.message))
- .finally(() => setSaving(false));
- };
-
- return (
- <div>
- <div className="mb-1.5 flex items-center gap-2 text-[13px] text-ink-secondary">
- <span className={cn("size-1.5 rounded-full", configured ? "bg-success" : "bg-raised-hover")} />
- <span>{t("keys.vps.label")}</span>
- <span className="rounded bg-control px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-ink-secondary">
- {t("keys.optional")}
- </span>
- {configured && <span className="text-[11px] text-success">{t("keys.connected")}</span>}
- </div>
- <div className="mb-1.5 text-[12px] leading-relaxed text-ink-secondary">
- {t("keys.vps.descBefore")}
- <a
- href="https://github.com/milind-soni/OpenMausBot/blob/main/docs/byo-vps.md"
- target="_blank"
- rel="noopener noreferrer"
- className="text-accent hover:underline"
- >
- {t("keys.vps.descLink")}
- </a>
- {t("keys.vps.descAfter")}
- </div>
- <div className="flex gap-2">
- <input
- type="text"
- value={alias}
- onChange={(e) => setAlias(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && save()}
- placeholder="my-vps"
- aria-label={t("keys.vps.aria")}
- autoComplete="off"
- className="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"
- />
- <button
- onClick={save}
- disabled={saving || (!alias.trim() && !configured)}
- className={cn(
- "cursor-pointer flex w-[72px] shrink-0 items-center justify-center gap-1.5 rounded-lg py-2 text-[13px]",
- !alias.trim() && configured ? "bg-control text-danger hover:bg-raised-hover" : "bg-control text-ink hover:bg-raised-hover",
- "disabled:cursor-not-allowed disabled:opacity-50",
- )}
- title={!alias.trim() && configured ? t("keys.vps.removeAlias") : t("common.save")}
- >
- {saving ? <Loader2 size={13} className="animate-spin" /> : !alias.trim() && configured ? t("keys.clear") : <><Check size={13} />{t("common.save")}</>}
- </button>
- </div>
- {error && <div className="mt-1 text-[12px] text-danger">{error}</div>}
- </div>
- );
-}
-
-export function OpenAiCompatUrl() {
- const { state, dispatch } = useStore();
- const saved = state.config?.openaiCompat?.url ?? "";
- const [value, setValue] = useState(saved);
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const savingRef = useRef(false);
- useEffect(() => { setValue(saved); }, [saved]);
- const dirty = value.trim() !== saved;
-
- const save = () => {
- if (savingRef.current || !dirty) return;
- savingRef.current = true;
- setSaving(true);
- setError(null);
- api("/api/config", { method: "PUT", body: JSON.stringify({ openaiCompat: { url: value.trim() } }) })
- .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))
- .catch((e) => setError(e.message))
- .finally(() => { savingRef.current = false; setSaving(false); });
- };
-
- return (
- <div>
- <div className="mb-1.5 text-[13px] text-ink-secondary">{t("keys.openaiCompat.url")}</div>
- <div className="relative">
- <input
- type="url"
- value={value}
- onChange={(e) => setValue(e.target.value)}
- onBlur={save}
- onKeyDown={(e) => e.key === "Enter" && save()}
- placeholder="https://api.groq.com/openai/v1"
- aria-label={t("keys.openaiCompat.url")}
- spellCheck={false}
- className="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 pr-8 font-mono text-[12px] text-ink placeholder:text-ink-secondary focus:outline-none"
- />
- {saving && (
- <Loader2 size={13} aria-hidden="true" className="absolute right-2.5 top-1/2 -translate-y-1/2 animate-spin text-ink-secondary" />
- )}
- </div>
- <p className="mt-1 text-[12px] leading-relaxed text-ink-secondary">{t("keys.openaiCompat.urlHint")}</p>
- {error && <div className="mt-1 text-[12px] text-danger">{error}</div>}
- </div>
- );
-}
diff --git a/src/components/CloudEngineSignIn.tsx b/src/components/CloudEngineSignIn.tsx
index 8123594f8e..f04d4713ce 100644
--- a/src/components/CloudEngineSignIn.tsx
+++ b/src/components/CloudEngineSignIn.tsx
@@ -14,6 +14,7 @@ import { t } from "@/lib/i18n";
import type { MausMotion, MausState } from "@/lib/mascot";
import { withViewTransition } from "@/components/onboarding/view-transition";
import { useStore, type InstanceInfo } from "@/state/store";
+import { openKeySettings } from "./keys/key-focus";
type Choice = "claude" | "codex" | "grok";
type ChoiceKind = "claudeAgent" | "codex" | "grokAgent";
@@ -126,7 +127,7 @@ export function cloudEngineChoices(engines: CloudEngineChoices, { handing = fals
<div data-cloud-choice="api-key" className="animate-rise mt-4 flex flex-col items-center text-center" style={staggerIndex(4 + choices.length)}>
<button
type="button"
- onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}
+ onClick={() => dispatch(openKeySettings())}
className="group inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-[14px] font-medium text-ink transition-[background-color,transform] duration-150 ease-out hover:bg-raised/60 active:scale-[0.97]"
>
<KeyRound size={15} aria-hidden="true" className="text-ink-secondary" />
diff --git a/src/components/ComputerPanel.simple.test.ts b/src/components/ComputerPanel.simple.test.ts
index 2011e72a37..f57c4a9a5a 100644
--- a/src/components/ComputerPanel.simple.test.ts
+++ b/src/components/ComputerPanel.simple.test.ts
@@ -22,7 +22,7 @@ const fixture = vi.hoisted(() => {
index: 0,
own: 0,
seed: {} as Record<string, unknown>,
- config: {} as FeatureFlagConfig & { cloudHome?: boolean; box?: { configured: boolean } },
+ config: {} as FeatureFlagConfig & { cloudHome?: boolean; box?: { configured: boolean; last4?: string } },
instances: [] as InstanceInfo[],
android: false,
dispatch: (() => {}) as (...args: unknown[]) => void,
@@ -104,7 +104,7 @@ const { ComputerPanel } = await import("./ComputerPanel");
const { ComputerFilesPane } = await import("./ComputerFilesPane");
const { CloudBackendPicker } = await import("./CloudBackendPicker");
const { LocalComputerAutoWarning } = await import("./LocalComputerAutoWarning");
-const { ApiKeyRow } = await import("./ApiKeys");
+const { KeyRow } = await import("./keys/KeyRow");
afterAll(() => vi.unstubAllGlobals());
@@ -430,8 +430,23 @@ describe("Where the bot works", () => {
it("saves a Boat key pasted into the panel as one from the Computer panel", () => {
fixture.config = { ...fixture.config, box: { configured: false } };
fixture.seed = { phase: "unconfigured", resolved: { botId: "scout", threadId: "thread-scout", computer: "cloud", cloudBackend: "box" } };
- const rows = render(makeBot({ computer: "cloud" })).nodes.filter((node) => node.type === ApiKeyRow);
- expect(rows.map((node) => ({ section: node.props.section, via: node.props.via }))).toEqual([{ section: "box", via: "computer_panel" }]);
+ const rows = render(makeBot({ computer: "cloud" })).nodes.filter((node) => node.type === KeyRow);
+ expect(rows.map((node) => ({ id: node.props.id, via: node.props.via }))).toEqual([{ id: "box", via: "computer_panel" }]);
+ });
+
+ it("keeps a Boat key saved in the panel in view, masked and connected, after the panel moves on", () => {
+ fixture.config = { ...fixture.config, box: { configured: false } };
+ fixture.seed = { phase: "unconfigured", resolved: { botId: "scout", threadId: "thread-scout", computer: "cloud", cloudBackend: "box" } };
+ const before = render(makeBot({ computer: "cloud" }));
+ const saved = before.nodes.find((node) => node.type === KeyRow)!.props.onSaved as (configured: boolean) => void;
+ saved(true);
+ fixture.values[phaseIndex] = "checking";
+ fixture.config = { ...fixture.config, box: { configured: true, last4: "c3d4" } };
+ const after = render(makeBot({ computer: "cloud" }));
+ expect(after.nodes.filter((node) => node.type === KeyRow).map((node) => node.props.id)).toEqual(["box"]);
+ expect(after.html).toContain("••••••••c3d4");
+ expect(after.html).toContain(">Connected<");
+ expect(after.html).toContain("data-key-replace");
});
it("dispatches exactly what the Advanced picker dispatches for each place", () => {
diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx
index b8277f9090..61fc730be6 100644
--- a/src/components/ComputerPanel.tsx
+++ b/src/components/ComputerPanel.tsx
@@ -11,7 +11,7 @@ import { setAdvancedMode, useAdvancedMode } from "@/lib/interface-mode";
import { ComputerFilesPane } from "./ComputerFilesPane";
import { effectivePlace, isComputerPlace, placeLabelKey, placeOffered } from "@/lib/place";
import type { CloudBackend } from "../../shared/wire";
-import { ApiKeyRow } from "./ApiKeys";
+import { KeyRow } from "./keys/KeyRow"; import { openKeySettings } from "./keys/key-focus";
import { cn } from "@/lib/cn";
import { useCaptionChrome } from "@/components/DesktopCapabilities";
import { usePageVisible } from "@/lib/page-visible";
@@ -266,6 +266,7 @@ export function ComputerPanel({
const browserEnabled = builtInBrowserEnabled(state.config) && bot.browser !== false
&& (browserAvailableHere || state.config?.browserEngine?.installable === true);
const [retry, setRetry] = useState(0);
+ const [boatKeyShown, setBoatKeyShown] = useState(false);
// Auto is the server's decision: never guess host-vs-cloud from desktop capabilities.
useEffect(() => {
if (livePlace !== "auto" || !computerSelectionPersisted) return;
@@ -1045,9 +1046,7 @@ export function ComputerPanel({
dispatch({ type: "toggleAppSettings", open: true });
};
- const openConnectionSettings = () => {
- dispatch({ type: "toggleAppSettings", open: true, section: "connections" });
- };
+ const openConnectionSettings = () => dispatch(openKeySettings("vps"));
const browserCanTurnOn = browserAvailableHere || state.config?.browserEngine?.installable === true;
const [browserTurningOn, setBrowserTurningOn] = useState(false);
@@ -1521,11 +1520,10 @@ export function ComputerPanel({
{errorText}
</div>
)}
- {phase === "unconfigured" && cloudView.action?.id === "add-boat-key" && (
- <div className="mt-3 rounded-xl bg-card p-4">
- <ApiKeyRow
- section="box" via="computer_panel"
- onSaved={(configured) => configured && setRetry((n) => n + 1)}
+ {(boatKeyShown || (phase === "unconfigured" && cloudView.action?.id === "add-boat-key")) && (
+ <div data-boat-key className="mt-3 rounded-xl bg-card py-1.5">
+ <KeyRow id="box" via="computer_panel"
+ onSaved={(configured) => { setBoatKeyShown(true); if (configured) setRetry((n) => n + 1); }}
/>
</div>
)}
diff --git a/src/components/DecisionModelSettings.tsx b/src/components/DecisionModelSettings.tsx
index b43e11aa6c..2edf41ec03 100644
--- a/src/components/DecisionModelSettings.tsx
+++ b/src/components/DecisionModelSettings.tsx
@@ -8,6 +8,7 @@ import type { LocaleKey } from "@/locales";
import { Card, SettingRow, Switch } from "./SettingsPrimitives";
import { Select } from "./Select";
import { WorkersAiKeyCard } from "./WorkersAiKeyCard";
+import { openKeySettings } from "./keys/key-focus";
const KEY_URL = { jev: "https://typesafe.ai", openrouter: "https://openrouter.ai/keys" } as const;
/** The room decision budget in server/decider/room-routing.ts; slower falls back to the lead. */
@@ -280,7 +281,7 @@ export function DecisionModelSettings() {
<button
type="button"
data-testid="decider-manage-keys"
- onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}
+ onClick={() => dispatch(openKeySettings("openrouter"))}
className="cursor-pointer text-accent hover:underline"
>
{t("decider.openrouter.key.manageLink")}
diff --git a/src/components/EngineSetup.grok.test.ts b/src/components/EngineSetup.grok.test.ts
index 82f8cf30a9..7f51439c53 100644
--- a/src/components/EngineSetup.grok.test.ts
+++ b/src/components/EngineSetup.grok.test.ts
@@ -77,22 +77,23 @@ describe("Grok cannot run here: an xAI key instead", () => {
it.each([
["a server's page in a browser", undefined, false],
["My Cloud in the desktop app's window", desktop, true],
- ] as const)("says so in one line with one action on %s", (_where, ogb, cloudHome) => {
+ ] as const)("says so in one line, with the xAI key's own field right there on %s", (_where, ogb, cloudHome) => {
const html = render(missing, ogb, cloudHome);
expect(grokKeyInstead(missing, cloudHome)).toBe(true);
expect(html).toContain("data-engine-setup-key-instead");
expect(html).toContain(NOT_INSTALLED);
- expect(html.match(/<button/g)).toHaveLength(1);
- expect(html).toContain("Add xAI key");
+ expect(html).toContain('data-key-row="xai"');
+ expect(html).toMatch(/<input[^>]*placeholder="xai-…"[^>]*aria-label="xAI API key"/);
+ expect(html.match(/data-key-save=/g)).toHaveLength(1);
expect(html).not.toContain(CURL);
expect(html).not.toContain("Set up Grok");
expect(html).not.toContain("Terminal");
});
- it("opens Settings → API keys", () => {
+ it("takes the key in place instead of sending the person to Settings", () => {
render(missing, undefined);
- host.querySelector("button")!.click();
- expect(dispatch).toHaveBeenCalledExactlyOnceWith({ type: "toggleAppSettings", open: true, section: "connections" });
+ expect(host.querySelector('[data-key-row="xai"] [data-key-input]')).not.toBeNull();
+ expect(dispatch).not.toHaveBeenCalled();
});
it("has no button on a paired desktop, whose Settings hide the keys", () => {
diff --git a/src/components/EngineSetup.test.ts b/src/components/EngineSetup.test.ts
index 4345c46952..549331221c 100644
--- a/src/components/EngineSetup.test.ts
+++ b/src/components/EngineSetup.test.ts
@@ -122,7 +122,7 @@ describe("engines set up with a key in Settings", () => {
expect(missing).not.toContain("needs an API key");
const keyless = renderToStaticMarkup(createElement(StoreProvider, null, createElement(EngineSetup, { instance: dsh({ state: "available", authenticated: false, version: "0.2.1" }) })));
expect(keyless).toContain("DeepSeek Harness needs an API key");
- expect(keyless).toContain("Open API keys");
+ expect(keyless).toContain('data-key-row="deepseek"');
expect(keyless).not.toContain("Terminal");
// No key is saved, so nothing was rejected.
expect(keyless).not.toContain("rejected the saved key");
@@ -258,22 +258,29 @@ describe("API-key engine setup", () => {
return renderToStaticMarkup(createElement(StoreProvider, null, createElement(EngineSetup, { instance: engine })));
};
- it("sends a missing key to Settings → API keys, not to a config file", () => {
+ it("takes a missing key in place, in the same key row as Settings, not in a config file", () => {
const html = render(keyEngine("grok", { state: "unavailable", reason: "No xAI API key — open Settings → API keys." }));
expect(html).toContain("data-engine-setup-api-key");
expect(html).toContain("Grok (API) needs an API key");
- expect(html).toContain("Open API keys");
+ expect(html).toContain("Paste it here. It saves and checks itself");
+ expect(html).toContain('data-key-row="xai"');
+ expect(html).not.toContain("Open API keys");
expect(html).not.toContain("config.json");
});
- it("says so when the provider rejected the saved key", () => {
+ it("says so in the key row when the provider rejected the saved key", () => {
const html = render(keyEngine("grok", { state: "available", authenticated: false, reason: "The provider rejected this key." }));
expect(html).toContain("data-engine-setup-api-key");
- expect(html).toContain("The provider rejected the saved key.");
- expect(html).toContain("Open API keys");
+ expect(html).toContain("Didn&#x27;t work: The provider rejected this key.");
expect(render(keyEngine("grok", { state: "unavailable" }))).not.toContain("rejected");
});
+ it("still sends an engine with no key row of its own to Settings → API keys", () => {
+ const html = render(keyEngine("openai-compat", { state: "unavailable" }));
+ expect(html).toContain("Open API keys");
+ expect(html).not.toContain("data-key-row");
+ });
+
it("has no button on a remote client, whose settings hide the keys", () => {
const html = render(keyEngine("openai-compat", { state: "unavailable" }), { platform: "darwin", remoteClient: { active: true } });
expect(html).toContain("on the computer running OpenMausBot");
diff --git a/src/components/EngineSetup.tsx b/src/components/EngineSetup.tsx
index 34a149c057..6bcbe8a09b 100644
--- a/src/components/EngineSetup.tsx
+++ b/src/components/EngineSetup.tsx
@@ -7,6 +7,9 @@ import { copyText } from "@/lib/copy-text";
import { DEVICE_SIGN_IN_COPY, DeviceSignIn, deviceSignInProvider } from "./DeviceSignIn";
import { ClaudeSignIn } from "./ClaudeSignIn";
import { RefreshEngines } from "./EngineLibrary";
+import { keyEntry, keyForInstance, type KeyId } from "./keys/key-catalog";
+import { openKeySettings } from "./keys/key-focus";
+import { KeyRow, SavedKeyLine } from "./keys/KeyRow";
type Platform = "darwin" | "win32" | "linux";
@@ -406,8 +409,25 @@ function apiKeySetup(instance: InstanceInfo): boolean {
return instance.snapshot.authenticated === false;
}
+function inlineKey(instance: InstanceInfo): KeyId | undefined {
+ const key = keyForInstance(instance.instanceId);
+ return key && keyEntry(key).kind === "key" && key !== "openaiCompat" ? key : undefined;
+}
+
+export const openKeysFor = (instance?: InstanceInfo) =>
+ openKeySettings(instance ? keyForInstance(instance.instanceId) ?? (instance.driverKind === "openai-compat" ? "openaiCompat" : undefined) : undefined);
+
+export function ApiKeyHint({ instance }: { instance: InstanceInfo }) {
+ const key = window.ogb?.remoteClient?.active === true ? undefined : inlineKey(instance);
+ return (
+ <>
+ <div className="mt-0.5 text-[12px] leading-4 text-ink-tertiary">{t("model.apiKeyHint")}</div>
+ {key && <SavedKeyLine id={key} />}
+ </>
+ );
+}
+
function GrokKeyInstead({ className, unframed }: { className?: string; unframed: boolean }) {
- const { dispatch } = useStore();
const remote = window.ogb?.remoteClient?.active === true;
return (
<div data-engine-setup-key-instead className={cn(!unframed && "rounded-xl border border-hairline/40 bg-control/30 p-3", className)}>
@@ -417,16 +437,7 @@ function GrokKeyInstead({ className, unframed }: { className?: string; unframed:
</span>
<p className="min-w-0 text-[13px] leading-relaxed text-ink">{t("engineSetup.grok.notInstalled")}</p>
</div>
- {!remote && (
- <button
- type="button"
- onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}
- className="mt-3 flex items-center gap-1.5 rounded-lg bg-raised px-3 py-1.5 text-[13px] font-medium text-ink hover:bg-raised-hover"
- >
- <KeyRound size={13} aria-hidden="true" />
- {t("engineSetup.grok.addKey")}
- </button>
- )}
+ {!remote && <KeyRow id="xai" bare via="model_picker" className="mt-2 px-0 pb-0" />}
</div>
);
}
@@ -434,9 +445,10 @@ function GrokKeyInstead({ className, unframed }: { className?: string; unframed:
function ApiKeyEngineSetup({ instance, className, unframed, configured = false }: { instance: InstanceInfo; className?: string; unframed: boolean; configured?: boolean }) {
const { dispatch } = useStore();
const remote = window.ogb?.remoteClient?.active === true;
+ const inline = remote ? undefined : inlineKey(instance);
const copy = configured
- ? { title: "engineSetup.apiKey.configuredTitle", description: remote ? "engineSetup.apiKey.configuredRemote" : "engineSetup.apiKey.configuredDescription", action: "engineSetup.apiKey.change" } as const
- : { title: "engineSetup.apiKey.title", description: remote ? "engineSetup.apiKey.remote" : "engineSetup.apiKey.description", action: "engineSetup.apiKey.open" } as const;
+ ? { title: "engineSetup.apiKey.configuredTitle", description: remote ? "engineSetup.apiKey.configuredRemote" : inline ? null : "engineSetup.apiKey.configuredDescription", action: "engineSetup.apiKey.change" } as const
+ : { title: "engineSetup.apiKey.title", description: remote ? "engineSetup.apiKey.remote" : inline ? "engineSetup.apiKey.inline" : "engineSetup.apiKey.description", action: "engineSetup.apiKey.open" } as const;
return (
<div data-engine-setup-api-key={configured ? "configured" : ""} className={cn(!unframed && "rounded-xl border border-hairline/40 bg-control/30 p-3", className)}>
<div className="flex items-start gap-2.5">
@@ -445,18 +457,18 @@ function ApiKeyEngineSetup({ instance, className, unframed, configured = false }
</span>
<div className="min-w-0">
<div className="text-[13px] font-semibold text-ink">{t(copy.title, { name: instance.displayName })}</div>
- <p className="mt-0.5 text-[12px] leading-relaxed text-ink-secondary">{t(copy.description)}</p>
+ {copy.description && <p className="mt-0.5 text-[12px] leading-relaxed text-ink-secondary">{t(copy.description)}</p>}
</div>
</div>
{/* An API-only engine is available only with a saved key, so unauthenticated means rejected.
A key engine with its own CLI (DeepSeek Harness) is unauthenticated simply when no key is saved yet. */}
- {isApiKeyEngine(instance) && needsSignIn(instance) && (
+ {!inline && isApiKeyEngine(instance) && needsSignIn(instance) && (
<p role="alert" className="mt-2 text-[12px] leading-relaxed text-danger">{t("engineSetup.apiKey.rejected")}</p>
)}
- {!remote && (
+ {inline ? <KeyRow id={inline} bare via="model_picker" rejected={isApiKeyEngine(instance) && needsSignIn(instance)} className="mt-2 px-0 pb-0" /> : !remote && (
<button
type="button"
- onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}
+ onClick={() => dispatch(openKeysFor(instance))}
className="mt-3 flex items-center gap-1.5 rounded-lg bg-raised px-3 py-1.5 text-[13px] font-medium text-ink hover:bg-raised-hover"
>
<KeyRound size={13} aria-hidden="true" />
diff --git a/src/components/EnginesSettings.test.ts b/src/components/EnginesSettings.test.ts
index 7da6d3cf51..0825da888e 100644
--- a/src/components/EnginesSettings.test.ts
+++ b/src/components/EnginesSettings.test.ts
@@ -6,7 +6,7 @@ import { EnginesSettings } from "./EnginesSettings";
import { accountActions } from "./EngineAccounts";
import { AntigravityFreeSpace, formatDiskSize } from "./AntigravityFreeSpace";
-const fixture = vi.hoisted(() => ({ instances: [] as InstanceInfo[], bots: [] as Bot[] }));
+const fixture = vi.hoisted(() => ({ instances: [] as InstanceInfo[], bots: [] as Bot[], config: undefined as Record<string, unknown> | undefined }));
vi.mock("@/state/store", async (importOriginal) => ({
...await importOriginal<typeof import("@/state/store")>(),
useStore: () => ({ state: fixture, refreshInstances: async () => {}, refreshModels: async () => {} }),
@@ -231,7 +231,7 @@ describe("Settings → Engines → setup cards", () => {
expect(renderToStaticMarkup(createElement(EnginesSettings))).not.toContain("Sign in with Google");
});
- it("keeps an API-key engine listed after its key is saved and links to changing the key", () => {
+ it("keeps an API-key engine listed after its key is saved, with the key masked and Replace beside it", () => {
vi.stubGlobal("window", {});
vi.stubGlobal("navigator", { userAgent: "Linux" });
fixture.bots = [];
@@ -242,25 +242,29 @@ describe("Settings → Engines → setup cards", () => {
fixture.instances = [openai({ state: "unavailable", reason: "No API key" })];
const before = renderToStaticMarkup(createElement(EnginesSettings));
expect(before).toContain("OpenAI needs an API key");
- expect(before).toContain("Open API keys");
- expect(before).not.toContain("Change key");
+ expect(before).toContain('data-key-row="openai"');
+ expect(before).toContain('placeholder="sk-…"');
+ expect(before).not.toContain("data-key-replace");
fixture.instances = [openai({ state: "available", authenticated: true, version: null })];
+ fixture.config = { openai: { configured: true, last4: "a1b2" } };
const saved = renderToStaticMarkup(createElement(EnginesSettings));
expect(saved).toContain('data-engine-card="openai"');
expect(saved).toContain('data-engine-setup-api-key="configured"');
expect(saved).toContain("OpenAI uses your API key");
- expect(saved).toContain("Change key");
+ expect(saved).toContain("••••••••a1b2");
+ expect(saved).toContain("data-key-replace");
expect(saved).not.toContain("OpenAI needs an API key");
vi.stubGlobal("window", { ogb: { remoteClient: { active: true } } });
const remote = renderToStaticMarkup(createElement(EnginesSettings));
expect(remote).toContain("open Settings → API keys on the computer running OpenMausBot");
- expect(remote).not.toContain("Change key");
+ expect(remote).not.toContain("data-key-row");
vi.stubGlobal("window", {});
fixture.instances = [{ ...openai({ state: "available", authenticated: true, version: null }), managed: { organizationId: "org", organizationName: "Acme" } }];
- expect(renderToStaticMarkup(createElement(EnginesSettings))).not.toContain("Change key");
+ expect(renderToStaticMarkup(createElement(EnginesSettings))).not.toContain("data-key-row");
+ fixture.config = undefined;
});
});
diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsx
index 5297be5298..9ab87a35b9 100644
--- a/src/components/LiveCallSettings.tsx
+++ b/src/components/LiveCallSettings.tsx
@@ -6,6 +6,7 @@ import { liveDisclosure } from "@/lib/call-mode";
import { api, useStore, type ConfigStatus } from "@/state/store";
import type { LiveSettings } from "../../shared/wire";
import { LiveKeySetup } from "./LiveKeySetup";
+import { KeysLink } from "./keys/KeysLink";
import { Select } from "./Select";
const IDLE_CHOICES = [1, 2, 3, 5, 10, 15, 30, 60];
@@ -116,7 +117,7 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
</span>
</div>
{live.keySource !== "live" && (
- <div className="-mt-2 text-[12px] text-ink-tertiary">{t(live.keySource === "openai" ? "call.live.keyFromApiKeys" : "call.live.needsKey")}</div>
+ <div className="-mt-2 text-[12px] text-ink-tertiary">{t(live.keySource === "openai" ? "call.live.keyFromApiKeys" : "call.live.needsKey")} <KeysLink id="openai" purpose="liveCalls" /></div>
)}
{changingKey && <LiveKeySetup compact onSaved={() => setChangingKey(false)} />}
<div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true })} {t("call.live.cost")}</div>
diff --git a/src/components/LiveKeyNeeded.test.ts b/src/components/LiveKeyNeeded.test.ts
index 6d35cf953c..36966e7fe6 100644
--- a/src/components/LiveKeyNeeded.test.ts
+++ b/src/components/LiveKeyNeeded.test.ts
@@ -6,7 +6,8 @@ const f = vi.hoisted(() => ({ dispatch: vi.fn(), dismiss: vi.fn(), cloudHome: fa
vi.mock("react", async (original) => ({ ...await original<typeof import("react")>(), useId: () => "live-key-title" }));
vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: { cloudHome: f.cloudHome } }, dispatch: f.dispatch }) }));
vi.mock("@/lib/live-call-media", () => ({ dismissLiveNotice: f.dismiss }));
-import { LiveKeyNeeded, OPEN_API_KEYS } from "./LiveKeyNeeded";
+import { LiveKeyNeeded } from "./LiveKeyNeeded";
+import { finishKeyFocus, useKeyFocus } from "./keys/key-focus";
beforeEach(() => {
vi.clearAllMocks();
@@ -28,11 +29,14 @@ it("says one plain thing, names OpenAI, and offers only the way to Settings →
expect(renderToStaticMarkup(createElement(LiveKeyNeeded))).toContain("The OpenAI key stays in the Cloud.");
});
-it("opens Settings at API keys and puts the prompt away", () => {
+it("opens Settings at the OpenAI key in Voice and calls, and puts the prompt away", () => {
const button = nodes(LiveKeyNeeded()).find((node) => node.type === "button");
expect(button).toBeTruthy();
button!.props.onClick!();
- expect(OPEN_API_KEYS).toEqual({ type: "toggleAppSettings", open: true, section: "connections" });
- expect(f.dispatch).toHaveBeenCalledExactlyOnceWith(OPEN_API_KEYS);
+ expect(f.dispatch).toHaveBeenCalledExactlyOnceWith({ type: "toggleAppSettings", open: true, section: "connections" });
+ let request: ReturnType<typeof useKeyFocus> = null;
+ renderToStaticMarkup(createElement(() => { request = useKeyFocus(); return null; }));
+ expect(request).toMatchObject({ id: "openai", row: "liveCalls" });
+ finishKeyFocus(request!);
expect(f.dismiss).toHaveBeenCalledOnce();
});
diff --git a/src/components/LiveKeyNeeded.tsx b/src/components/LiveKeyNeeded.tsx
index e0852b5d26..b3cb47e034 100644
--- a/src/components/LiveKeyNeeded.tsx
+++ b/src/components/LiveKeyNeeded.tsx
@@ -4,9 +4,8 @@ import { KeyRound } from "lucide-react";
import { liveDisclosure } from "@/lib/call-mode";
import { dismissLiveNotice } from "@/lib/live-call-media";
import { t } from "@/lib/i18n";
-import { useStore, type Action } from "@/state/store";
-
-export const OPEN_API_KEYS = { type: "toggleAppSettings", open: true, section: "connections" } as const satisfies Action;
+import { useStore } from "@/state/store";
+import { openKeySettings } from "./keys/key-focus";
export function LiveKeyNeeded() {
const { state, dispatch } = useStore();
@@ -16,7 +15,7 @@ export function LiveKeyNeeded() {
<KeyRound size={16} className="mt-0.5 shrink-0 text-ink-secondary" aria-hidden="true" />
<h2 id={titleId} className="text-[14px] font-medium leading-[1.4] text-ink">{t("call.live.needsKey")}</h2>
</div>
- <button type="button" className="ui-button ui-button-primary self-start" onClick={() => { dismissLiveNotice(); dispatch(OPEN_API_KEYS); }}>{t("call.live.openApiKeys")}</button>
+ <button type="button" className="ui-button ui-button-primary self-start" onClick={() => { dismissLiveNotice(); dispatch(openKeySettings("openai", "liveCalls")); }}>{t("call.live.openApiKeys")}</button>
<p className="text-[12px] leading-[1.45] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true })} {t("call.live.cost")}</p>
</section>;
}
diff --git a/src/components/LocalComputerSection.tsx b/src/components/LocalComputerSection.tsx
index d06800db4c..8df57e7392 100644
--- a/src/components/LocalComputerSection.tsx
+++ b/src/components/LocalComputerSection.tsx
@@ -20,7 +20,7 @@ import { MacLocalControl } from "./MacLocalControl";
import { Select } from "./Select";
import { cn } from "@/lib/cn";
import { useStore } from "@/state/store";
-import { VpsComputersCard } from "./VpsComputersCard";
+import { VpsComputersCard } from "./VpsComputersCard"; import { KeysLink } from "./keys/KeysLink";
type Action = "pull" | "run" | "start" | "stop" | "remove" | "recreate";
@@ -380,7 +380,7 @@ export function CloudComputersCard({
{configured === true
? t("vm.cloud.includesOrphans")
: configured === false
- ? t("vm.cloud.needsKey")
+ ? <>{t("vm.cloud.needsKey")} <KeysLink id="box" /></>
: t("vm.cloud.refreshHint")}
</div>
<button
diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsx
index f721fc00dd..471ef44531 100644
--- a/src/components/ModelPicker.tsx
+++ b/src/components/ModelPicker.tsx
@@ -11,7 +11,7 @@ import { pickerPlacement, type PickerPlacement } from "@/lib/picker-placement";
import { isTypeaheadKey, TYPEAHEAD_RESET_MS, typeaheadMatch, typeaheadText, type Typeahead } from "@/lib/menu-keys";
import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";
import { InstanceProviderMark } from "./ProviderIcons";
-import { EngineSetup, EngineUpdateNotice, needsCli, needsSignIn } from "./EngineSetup";
+import { ApiKeyHint, EngineSetup, EngineUpdateNotice, needsCli, needsSignIn, openKeysFor } from "./EngineSetup";
import { ConfirmDialog } from "./ConfirmDialog";
import { ChatGptPlanStatus } from "./ChatGptPlanStatus";
import { approvalModeFor, modelSwitchNeedsAsk } from "../../shared/approval-mode";
@@ -441,7 +441,7 @@ export function ModelPicker({
const openApiKeys = () => {
close(false);
- dispatch({ type: "toggleAppSettings", open: true, section: "connections" });
+ dispatch(openKeysFor(railInstance));
};
const openEngines = () => {
close(false);
@@ -872,7 +872,7 @@ export function ModelPicker({
<ChatGptPlanStatus key={railInstance.instanceId} instanceId={railInstance.instanceId} />
)}
{railInstance.access === "api"
- ? <div className="mt-0.5 text-[12px] leading-4 text-ink-tertiary">{t("model.apiKeyHint")}</div>
+ ? <ApiKeyHint instance={railInstance} />
: pane === "custom" && <div className="mt-0.5 text-[12px] leading-4 text-ink-tertiary">{t("model.localHint")}</div>}
</div>
diff --git a/src/components/NoEngines.tsx b/src/components/NoEngines.tsx
index c7b9671670..b89151a396 100644
--- a/src/components/NoEngines.tsx
+++ b/src/components/NoEngines.tsx
@@ -8,6 +8,7 @@ import { WindowDragStrip } from "@/components/DesktopCapabilities";
import { splitEngineRail } from "@/lib/engine-rail";
import { t } from "@/lib/i18n";
import { brand } from "../lib/brand";
+import { openKeySettings } from "./keys/key-focus";
export function NoEngines() {
const { state, dispatch, refreshInstances } = useStore();
@@ -80,7 +81,7 @@ export function NoEngines() {
<button
type="button"
data-no-engines-api-keys
- onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}
+ onClick={() => dispatch(openKeySettings())}
className="flex items-center gap-3 rounded-xl border border-hairline/40 bg-card p-3.5 text-left hover:bg-control/40"
>
<KeyRound size={16} className="shrink-0 text-ink-secondary" />
diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.ts
index 0ea6806fee..92bf8c2615 100644
--- a/src/components/OpenAiCompatServers.test.ts
+++ b/src/components/OpenAiCompatServers.test.ts
@@ -40,13 +40,12 @@ function render(instances: store.InstanceInfo[]) {
}
describe("other OpenAI-compatible servers", () => {
- it("lists only servers added here, by name and base URL, and opens when there are any", () => {
+ it("lists only servers added here, by name and base URL", () => {
const html = render([
instance("openaiCompat", "Other (OpenAI-compatible)"),
instance("openai", "OpenAI", { url: "https://api.openai.com/v1" }),
instance("openai-compat-1", "Zhipu", { url: "https://open.bigmodel.cn/api/paas/v4" }),
]);
- expect(html).toMatch(/<details[^>]*open=""/);
expect(html).toContain("Zhipu");
expect(html).toContain("https://open.bigmodel.cn/api/paas/v4");
expect(html).toContain('aria-label="Remove Zhipu"');
@@ -54,9 +53,8 @@ describe("other OpenAI-compatible servers", () => {
expect(html).not.toContain('aria-label="Remove OpenAI"');
});
- it("stays closed and says so when none are added", () => {
+ it("says so when none are added", () => {
const html = render([instance("openaiCompat", "Other (OpenAI-compatible)")]);
- expect(html).not.toMatch(/<details[^>]*open=""/);
expect(html).toContain("No other servers yet.");
});
diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsx
index 96264a7ee7..53f9f64f7e 100644
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@ -4,28 +4,19 @@ import { api, useStore, type InstanceInfo } from "@/state/store";
import { t } from "@/lib/i18n";
import { keySaved } from "@/lib/product-events";
import { addedServers } from "@/lib/openai-compat-endpoints";
-import { ApiKeyRow, OpenAiCompatUrl } from "./ApiKeys";
+import { cn } from "@/lib/cn";
+import { KEY_FIELD } from "./keys/KeyRow";
export function modelIds(text: string): string[] {
return [...new Set(text.split(/[,,、\s]+/).map((id) => id.trim()).filter(Boolean))];
}
-const INPUT = "w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[12px] text-ink placeholder:text-ink-secondary focus:outline-none";
-const ICON_BUTTON = "shrink-0 rounded-md px-2 py-1 text-ink-secondary hover:bg-inset hover:text-ink disabled:opacity-50";
+const INPUT = cn(KEY_FIELD, "font-sans");
+const ICON_BUTTON = "ui-icon-button shrink-0 hover:text-ink";
export function OtherOpenAiCompatServers() {
const { state } = useStore();
- const added = addedServers(state.instances);
- return (
- <details data-api-keys-other className="rounded-lg border border-hairline/40 bg-inset px-3 py-2" open={Boolean(state.config?.openaiCompat?.configured) || added.length > 0}>
- <summary className="cursor-pointer text-[13px] text-ink-secondary">{t("keys.other.title")}</summary>
- <div className="mt-3 flex flex-col gap-4">
- <ApiKeyRow section="openaiCompat" testProvider="openaiCompat" />
- <OpenAiCompatUrl />
- <AddedServers servers={added} />
- </div>
- </details>
- );
+ return <AddedServers servers={addedServers(state.instances)} />;
}
function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: string }> }) {
@@ -65,12 +56,12 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin
);
return (
- <div>
- <div className="mb-1.5 text-[13px] text-ink-secondary">{t("apiInstances.title")}</div>
- <p className="mb-2 text-[12px] leading-relaxed text-ink-secondary">{t("apiInstances.subtitle")}</p>
- {servers.length === 0 && <p className="text-[12px] text-ink-secondary">{t("apiInstances.empty")}</p>}
+ <div data-api-keys-other>
+ <div className="mb-0.5 text-[13px] leading-[18px] text-ink">{t("apiInstances.title")}</div>
+ <p className="mb-2 text-[12px] leading-4 text-ink-secondary">{t("apiInstances.subtitle")}</p>
+ {servers.length === 0 && <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.empty")}</p>}
{servers.map((server) => (
- <div key={server.instanceId} className="mb-1.5 flex items-center justify-between gap-2 rounded-lg border border-hairline/40 bg-inset px-3 py-2">
+ <div key={server.instanceId} className="mb-1.5 flex items-center justify-between gap-2 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5">
<div className="min-w-0">
<div className="truncate text-[12px] text-ink">{server.displayName}</div>
{server.url && <div className="truncate font-mono text-[11px] text-ink-secondary">{server.url}</div>}
@@ -101,17 +92,17 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin
<input value={name} onChange={(e) => setName(e.target.value)} placeholder={t("apiInstances.name")} aria-label={t("apiInstances.name")}
spellCheck={false} disabled={busy !== null} className={INPUT} />
<input type="url" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://api.example.com/v1" aria-label={t("apiInstances.url")}
- spellCheck={false} disabled={busy !== null} className={`${INPUT} font-mono`} />
+ spellCheck={false} disabled={busy !== null} className={cn(INPUT, "font-mono")} />
<input type="password" value={key} onChange={(e) => setKey(e.target.value)} placeholder={t("apiInstances.key")} aria-label={t("apiInstances.key")}
- autoComplete="off" disabled={busy !== null} className={`${INPUT} font-mono`} />
+ autoComplete="off" disabled={busy !== null} className={cn(INPUT, "font-mono")} />
<input value={models} onChange={(e) => setModels(e.target.value)} placeholder={t("apiInstances.models")} aria-label={t("apiInstances.models")}
- spellCheck={false} disabled={busy !== null} className={`${INPUT} font-mono`} />
- <p className="text-[11px] leading-relaxed text-ink-secondary">{t("apiInstances.modelsHint")}</p>
+ spellCheck={false} disabled={busy !== null} className={cn(INPUT, "font-mono")} />
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.modelsHint")}</p>
<button
type="button"
onClick={add}
disabled={busy !== null || !ready}
- className="inline-flex items-center gap-1.5 self-start rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink hover:bg-inset disabled:opacity-50"
+ className="ui-button self-start"
>
{busy === "add" ? <Loader2 size={12} aria-hidden="true" className="animate-spin" /> : <Plus size={12} aria-hidden="true" />}
{busy === "add" ? t("apiInstances.adding") : t("apiInstances.add")}
@@ -132,7 +123,7 @@ export function lmStudioBaseUrl(port: string): string | null {
return `http://127.0.0.1:${value}/v1`;
}
-export function LmStudioServer() {
+export function LmStudioServer({ heading = true }: { heading?: boolean } = {}) {
const { state, dispatch, refreshInstances } = useStore();
const added = addedServers(state.instances);
const [port, setPort] = useState("1234");
@@ -169,11 +160,11 @@ export function LmStudioServer() {
};
return (
- <div className="rounded-lg border border-hairline/40 bg-inset px-3 py-2">
- <div className="text-[13px] text-ink">{t("lmStudio.title")}</div>
- <p className="mt-1 text-[12px] leading-relaxed text-ink-secondary">{t("lmStudio.desc")}</p>
+ <div className={cn(heading && "rounded-lg border border-hairline/40 bg-inset px-3 py-2")}>
+ {heading && <div className="text-[13px] text-ink">{t("lmStudio.title")}</div>}
+ <p className={cn("text-[12px] leading-4 text-ink-secondary", heading && "mt-1")}>{t("lmStudio.desc")}</p>
<div className="mt-2 flex flex-col gap-1.5">
- <label className="text-[12px] text-ink-secondary">
+ <label className="flex flex-col gap-1 text-[12px] leading-4 text-ink-secondary">
{t("lmStudio.port")}
<input
inputMode="numeric"
@@ -182,7 +173,7 @@ export function LmStudioServer() {
aria-label={t("lmStudio.port")}
spellCheck={false}
disabled={busy}
- className={`${INPUT} mt-1 font-mono`}
+ className={cn(INPUT, "font-mono")}
/>
</label>
<input
@@ -193,15 +184,15 @@ export function LmStudioServer() {
aria-label={t("lmStudio.token")}
autoComplete="off"
disabled={busy}
- className={`${INPUT} font-mono`}
+ className={cn(INPUT, "font-mono")}
/>
- <p className="text-[11px] leading-relaxed text-ink-secondary">{t("lmStudio.tokenHint")}</p>
- {url && <p className="truncate font-mono text-[11px] text-ink-secondary">{url}</p>}
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("lmStudio.tokenHint")}</p>
+ {url && <p className="truncate font-mono text-[12px] leading-4 text-ink-secondary">{url}</p>}
<button
type="button"
onClick={add}
disabled={busy || !url || present}
- className="inline-flex items-center gap-1.5 self-start rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink hover:bg-inset disabled:opacity-50"
+ className="ui-button self-start"
>
{busy ? <Loader2 size={12} aria-hidden="true" className="animate-spin" /> : <Plus size={12} aria-hidden="true" />}
{busy ? t("lmStudio.adding") : t("lmStudio.add")}
diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx
index 8eb186f687..7ab5c5d88c 100644
--- a/src/components/PluginsPanel.tsx
+++ b/src/components/PluginsPanel.tsx
@@ -32,6 +32,7 @@ import { HighLevelCard } from "./HighLevelCard";
import { X_CARD_SEARCH, XCard } from "./XCard";
import { mergeCompleteConnectorStatus, mergeCurrentConnectorStatus, onlyLatestConnectorResponses } from "@/lib/connector-status-merge";
import { openBotSettings } from "./bot-panel/panel-link";
+import { openKeySettings } from "./keys/key-focus";
import { ServiceIcon, type ToolkitCard } from "./ServiceIcon";
export { ServiceIcon, type ToolkitCard } from "./ServiceIcon";
@@ -638,10 +639,7 @@ export function PluginsPanel() {
setupNotice.tone === "info" && "text-ink",
remoteClient && "hidden",
)}
- onClick={() => {
- close();
- dispatch({ type: "toggleAppSettings", open: true, section: "connections" });
- }}
+ onClick={() => { close(); dispatch(openKeySettings("composio")); }}
>
{t("connectors.openSettings")}
</button>
diff --git a/src/components/SettingsModal.keys.dom.test.ts b/src/components/SettingsModal.keys.dom.test.ts
new file mode 100644
index 0000000000..ac4cced842
--- /dev/null
+++ b/src/components/SettingsModal.keys.dom.test.ts
@@ -0,0 +1,125 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import type { AppSettingsSection } from "@/state/store";
+
+const fx = vi.hoisted(() => ({
+ section: "engines" as AppSettingsSection,
+ advanced: false,
+ config: {} as Record<string, unknown>,
+ listeners: new Set<() => void>(),
+ dispatch: vi.fn(),
+ api: vi.fn(),
+}));
+const { marker } = vi.hoisted(() => ({ marker: (name: string) => () => `MARKER:${name};` }));
+
+vi.mock("@/state/store", async (original) => {
+ const actual = await original<typeof import("@/state/store")>();
+ const { useSyncExternalStore } = await import("react");
+ const subscribe = (listener: () => void) => { fx.listeners.add(listener); return () => { fx.listeners.delete(listener); }; };
+ let snapshot = { section: fx.section, config: fx.config };
+ const read = () => snapshot.section === fx.section && snapshot.config === fx.config ? snapshot : (snapshot = { section: fx.section, config: fx.config });
+ return {
+ ...actual,
+ api: (...args: unknown[]) => fx.api(...args),
+ useStore: () => {
+ const { section, config } = useSyncExternalStore(subscribe, read);
+ return { state: { ...actual.initialState, appSettingsSection: section, config, instances: [], bots: [] }, dispatch: fx.dispatch };
+ },
+ };
+});
+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => fx.advanced, setAdvancedMode: vi.fn() }));
+vi.mock("@/lib/analytics", () => ({ analyticsEnabled: () => false, setAnalyticsEnabled: vi.fn(), track: vi.fn() }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => null }));
+vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({ capabilities: {} }) }));
+vi.mock("./EnginesSettings", () => ({ EnginesSettings: marker("engines") }));
+vi.mock("./DecisionModelSettings", () => ({ DecisionModelSettings: marker("decisionModel") }));
+vi.mock("./RemoteComputerSection", () => ({ RemoteComputerSection: marker("companion") }));
+vi.mock("./CustomDomainSettings", () => ({ CustomDomainSettings: () => null }));
+vi.mock("./CompanionSection", () => ({ CompanionSection: () => null }));
+vi.mock("./ServerPairingCard", () => ({ ServerPairingCard: () => null }));
+vi.mock("./ConnectedWorkspacesSettings", () => ({ ConnectedWorkspacesSettings: marker("desktopWorkspaces") }));
+vi.mock("./LocalComputerSection", () => ({ LocalComputerSection: marker("computer") }));
+vi.mock("./CloudAccountSettings", () => ({ CloudAccountSettings: marker("cloudAccount") }));
+vi.mock("./OrganizationSettings", () => ({ OrganizationSettings: marker("organization") }));
+vi.mock("./PeopleSection", () => ({ PeopleSection: marker("people") }));
+vi.mock("./ActivitySection", () => ({ ActivitySection: marker("activity") }));
+vi.mock("./UsageSection", () => ({ UsageSection: marker("usage") }));
+vi.mock("./ImportSettings", () => ({ ImportSettings: marker("import") }));
+vi.mock("./LoginsSettings", () => ({ LoginsSettings: marker("logins") }));
+vi.mock("./BrowserSettingsRows", () => ({ BuiltInBrowserRow: marker("browser") }));
+
+const { SettingsModal } = await import("./SettingsModal");
+
+let host: HTMLDivElement;
+let root: Root;
+
+function publish() {
+ for (const listener of Array.from(fx.listeners)) listener();
+}
+
+const search = () => host.querySelector<HTMLInputElement>("[data-settings-search]")!;
+const result = (id: string) => host.querySelector<HTMLButtonElement>(`[data-settings-key-result="${id}"]`);
+const row = (id: string) => host.querySelector<HTMLElement>(`[data-key-row="${id}"]`)!;
+
+function type(value: string) {
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(search(), value);
+ search().dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+beforeEach(() => {
+ setLocale("en");
+ fx.section = "engines";
+ fx.config = { composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" } };
+ fx.dispatch.mockReset();
+ fx.dispatch.mockImplementation((action: { type: string; section?: AppSettingsSection; config?: Record<string, unknown> }) => {
+ if (action.type === "toggleAppSettings" && action.section) fx.section = action.section;
+ if (action.type === "configStatus") fx.config = action.config!;
+ publish();
+ });
+ vi.stubGlobal("ogb", undefined);
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+ vi.unstubAllGlobals();
+});
+
+describe("searching Settings for a key", () => {
+ it.each([false, true])("lists it by name and section and lands on its row, focused (Advanced: %s)", async (advanced) => {
+ fx.advanced = advanced;
+ flushSync(() => root.render(createElement(SettingsModal)));
+ type("fish");
+ const found = result("fishAudio")!;
+ expect(found.textContent).toBe("Fish Audio API key · Voice and calls");
+ flushSync(() => found.click());
+ expect(search().value).toBe("");
+ expect(fx.section).toBe("connections");
+ const input = () => row("fishAudio").querySelector<HTMLInputElement>("[data-key-input]");
+ await vi.waitFor(() => expect(document.activeElement).toBe(input()));
+ expect(row("fishAudio").hasAttribute("data-key-highlight")).toBe(true);
+ expect(row("fishAudio").closest("[hidden]")).toBeNull();
+ });
+
+ it("names the OpenAI key twice: once for models, once for live calls", () => {
+ flushSync(() => root.render(createElement(SettingsModal)));
+ type("openai");
+ expect(result("openai")!.textContent).toBe("OpenAI API key · AI providers");
+ expect(result("liveCalls")!.textContent).toBe("OpenAI key · Voice and calls");
+ });
+
+ it("says plainly when nothing matches", () => {
+ flushSync(() => root.render(createElement(SettingsModal)));
+ type("zzzz");
+ expect(host.textContent).toContain("Nothing matches “zzzz”");
+ expect(host.querySelector("[data-settings-key-result]")).toBeNull();
+ });
+});
diff --git a/src/components/SettingsModal.search.test.ts b/src/components/SettingsModal.search.test.ts
index 9b93816a3e..894a47321a 100644
--- a/src/components/SettingsModal.search.test.ts
+++ b/src/components/SettingsModal.search.test.ts
@@ -5,7 +5,8 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { setLocale } from "@/lib/i18n";
-const fixture = vi.hoisted(() => ({ dispatch: vi.fn() }));
+const fixture = vi.hoisted(() => ({ dispatch: vi.fn(), scrolled: [] as Element[] }));
+vi.mock("@/lib/scroll-within", () => ({ scrollWithin: (_scroller: unknown, target: Element) => { fixture.scrolled.push(target); }, scrollParent: () => null }));
vi.mock("@/state/store", async (importOriginal) => ({
...await importOriginal<typeof import("@/state/store")>(),
api: vi.fn(async () => ({})),
@@ -29,7 +30,7 @@ for (const [path, name] of [
let host: HTMLDivElement;
let root: Root;
-const scrolled: Element[] = [];
+const scrolled = fixture.scrolled;
beforeAll(() => {
HTMLElement.prototype.checkVisibility ??= () => true;
@@ -40,7 +41,6 @@ beforeEach(async () => {
setLocale("en");
scrolled.length = 0;
vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 404 })));
- Element.prototype.scrollIntoView = vi.fn(function (this: Element) { scrolled.push(this); });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
diff --git a/src/components/SettingsModal.simple.test.ts b/src/components/SettingsModal.simple.test.ts
index 3640da9453..cf03c18254 100644
--- a/src/components/SettingsModal.simple.test.ts
+++ b/src/components/SettingsModal.simple.test.ts
@@ -47,13 +47,7 @@ const { marker } = vi.hoisted(() => ({
}));
vi.mock("./EnginesSettings", () => ({ EnginesSettings: marker("engines") }));
vi.mock("./DecisionModelSettings", () => ({ DecisionModelSettings: marker("decisionModel") }));
-vi.mock("./ApiKeys", () => ({
- ApiKeyRow: marker("apiKey"),
- AnthropicEveryClaudeBot: marker("anthropicEvery"),
- OpenAiCompatUrl: marker("compatUrl"),
- OpenCodeProviderKeys: marker("opencodeProviderKeys"),
- VpsConnection: marker("vps"),
-}));
+vi.mock("./keys/KeysPage", () => ({ KeysPage: marker("apiKey") }));
vi.mock("./RemoteComputerSection", () => ({ RemoteComputerSection: marker("companion") }));
vi.mock("./CustomDomainSettings", () => ({ CustomDomainSettings: () => null }));
vi.mock("./CompanionSection", () => ({ CompanionSection: () => null }));
@@ -298,16 +292,16 @@ describe("Settings in Simple mode", () => {
else expect(markers(html)).toContain(content);
});
- it("scrolls a later section of a stacked page into view, and starts a page at its top", () => {
- const scrollIntoView = vi.fn();
- const querySelector = vi.fn(() => ({ scrollIntoView }));
- const scroller = { scrollTop: 320, querySelector };
+ it("scrolls a later section of a stacked page to the top of the scroller alone, and starts a page at its top", () => {
+ const block = { getBoundingClientRect: () => ({ top: 500 }) };
+ const querySelector = vi.fn(() => block);
+ const scroller = { scrollTop: 320, clientHeight: 600, getBoundingClientRect: () => ({ top: 100 }), querySelector };
revealSettingsBlock(scroller, "connections", 1);
expect(querySelector).toHaveBeenCalledWith('[data-settings-block="connections"]');
- expect(scrollIntoView).toHaveBeenCalledWith({ block: "start" });
+ expect(scroller.scrollTop).toBe(720);
revealSettingsBlock(scroller, "engines", 0);
expect(scroller.scrollTop).toBe(0);
- expect(scrollIntoView).toHaveBeenCalledTimes(1);
+ expect(querySelector).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 1a358afa58..04492d617a 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -4,13 +4,14 @@ import { useStore, type AppSettingsSection } from "@/state/store";
import { skillsLibraryEnabled } from "@/lib/feature-flags";
import { type LocaleKey } from "@/locales";
import { t } from "@/lib/i18n";
-import { AnthropicEveryClaudeBot, ApiKeyRow, OpenCodeProviderKeys, VpsConnection } from "./ApiKeys";
+import { KeysPage } from "./keys/KeysPage";
+import { KEY_CATALOG, keyMatches, keySection, type KeyEntry } from "./keys/key-catalog";
+import { openKeySettings, useKeyFocus } from "./keys/key-focus";
import { AnalyticsRow } from "./AnalyticsRow";
import { UpdatesConsentRow } from "./UpdatesConsent";
import { OpenAtLoginRow } from "./OpenAtLoginRow";
import { DefaultBotSidebarRow } from "./DefaultBotControls";
import { DiagnosticsRow } from "./DiagnosticsRow";
-import { LmStudioServer, OtherOpenAiCompatServers } from "./OpenAiCompatServers";
import { DecisionModelSettings } from "./DecisionModelSettings";
import { EnginesSettings } from "./EnginesSettings";
import { LocalComputerSection } from "./LocalComputerSection";
@@ -49,6 +50,7 @@ import { WorkspaceBackupSettings } from "./WorkspaceBackupSettings";
import { CompanyBackupSettings } from "./CompanyBackupSettings";
import { ImportSettings } from "./ImportSettings";
import { cn } from "@/lib/cn";
+import { scrollWithin } from "@/lib/scroll-within";
import { glassPopupFrameStyle } from "@/lib/glass-popup";
import { NotificationRows } from "./NotificationSettingsRows";
import { useAdvancedMode } from "@/lib/interface-mode";
@@ -133,12 +135,13 @@ export function simpleSettingsPages(available: ReadonlySet<AppSettingsSection>,
}
export function revealSettingsBlock(
- scroller: { scrollTop: number; querySelector: (selector: string) => { scrollIntoView?: (options: ScrollIntoViewOptions) => void } | null },
+ scroller: Parameters<typeof scrollWithin>[0] & { querySelector: (selector: string) => Parameters<typeof scrollWithin>[1] | null },
section: AppSettingsSection,
indexInPage: number,
): void {
if (indexInPage <= 0) { scroller.scrollTop = 0; return; }
- scroller.querySelector(`[data-settings-block="${section}"]`)?.scrollIntoView?.({ block: "start" });
+ const block = scroller.querySelector(`[data-settings-block="${section}"]`);
+ if (block) scrollWithin(scroller, block);
}
function simplePageMatches(page: SimpleSettingsPage, query: string): boolean {
@@ -152,9 +155,16 @@ function simplePageMatches(page: SimpleSettingsPage, query: string): boolean {
export function sectionMatches(section: (typeof SECTIONS)[number], query: string): boolean {
if (!query) return true;
+ if (section.id === "connections" && KEY_CATALOG.some((entry) => keyMatches(entry, query))) return true;
return [t(section.labelKey), ...section.keywords].some((part) => part.toLowerCase().includes(query));
}
+export function keySearchResults(query: string): KeyEntry[] {
+ return query ? KEY_CATALOG.filter((entry) => keyMatches(entry, query)).slice(0, 8) : [];
+}
+
+export const openKeyResult = (entry: KeyEntry) => entry.uses ? openKeySettings(entry.uses, entry.id) : openKeySettings(entry.id);
+
export function SettingsModal() {
const { state, dispatch } = useStore();
const advanced = useAdvancedMode();
@@ -201,6 +211,8 @@ export function SettingsModal() {
}, [dispatch, nextVisibleSection]);
const [folds, setFolds] = useState<Partial<Record<SimpleDisclosureId, boolean>>>({});
+ const keyFocus = useKeyFocus();
+ useEffect(() => { if (keyFocus) setFolds((current) => current["ai-keys"] ? current : { ...current, "ai-keys": true }); }, [keyFocus]);
const disclose: Disclose = (id) => {
const open = q !== "" || (folds[id] ?? SIMPLE_FOLDED[requested] === id);
return { id, open, onToggle: () => setFolds((current) => ({ ...current, [id]: !open })) };
@@ -208,6 +220,13 @@ export function SettingsModal() {
const [looks, setLooks] = useState(false);
const [reveal, setReveal] = useState<string | null>(null);
const advancedMatches = advanced || !q ? [] : SIMPLE_ADVANCED_ONLY.filter((key) => t(key).toLowerCase().includes(q));
+ const keyResults = remoteActive || !availableSections.some((entry) => entry.id === "connections") ? [] : keySearchResults(q);
+ const keyResultButtons = (className: string) => keyResults.map((entry) => (
+ <button key={entry.id} type="button" data-settings-key-result={entry.id} className={className}
+ onClick={() => { setQuery(""); setLooks(false); dispatch(openKeyResult(entry)); }}>
+ <span>{t(entry.labelKey)} <span className="text-ink-secondary">· {t(keySection(entry).titleKey)}</span></span>
+ </button>
+ ));
const sectionIndex = currentPage?.sections.indexOf(section) ?? 0;
const revealBlock = !advanced && requested === "remote" ? "remote" : section;
@@ -216,7 +235,8 @@ export function SettingsModal() {
}, [advanced, revealBlock, section, sectionIndex]);
useEffect(() => {
if (!reveal) return;
- scrollRef.current?.querySelector(`[data-settings-block="${reveal}"]`)?.scrollIntoView?.({ block: "start" });
+ const block = scrollRef.current?.querySelector(`[data-settings-block="${reveal}"]`);
+ if (scrollRef.current && block) scrollWithin(scrollRef.current, block);
setReveal(null);
}, [reveal]);
@@ -361,51 +381,7 @@ export function SettingsModal() {
case "experimental":
return <ExperimentalFeaturesRow />;
case "connections":
- return (
- <Card
- title={t("settings.connections.title")}
- subtitle={t("settings.connections.subtitle")}
- >
- <div className="flex flex-col gap-4">
- {state.config?.composio.mode === "managed" ? (
- <div className="rounded-lg border border-success/25 bg-success/10 px-3 py-2 text-[13px] text-success">
- {t("settings.connections.ready")}
- </div>
- ) : null}
- <div className="text-[12px] font-medium uppercase tracking-wide text-ink-secondary">{t("keys.providers.title")}</div>
- <p className="-mt-3 text-[12px] leading-relaxed text-ink-secondary">{t("keys.providers.subtitle")}</p>
- <ApiKeyRow section="openai" testProvider="openai" />
- <ApiKeyRow section="anthropic" testProvider="anthropic" />
- <AnthropicEveryClaudeBot />
- <ApiKeyRow section="xai" testProvider="xai" />
- <ApiKeyRow section="openrouter" testProvider="openrouter" />
- <ApiKeyRow section="mistral" testProvider="mistral" />
- <ApiKeyRow section="cerebras" testProvider="cerebras" />
- <ApiKeyRow section="groq" testProvider="groq" />
- <ApiKeyRow section="meta" testProvider="meta" />
- <ApiKeyRow section="deepseek" />
- <LmStudioServer />
- <OtherOpenAiCompatServers />
- <div className="pt-2 text-[12px] font-medium uppercase tracking-wide text-ink-secondary">{t("keys.integrations.title")}</div>
- <ApiKeyRow section="treg" testProvider="treg" /><ApiKeyRow section="box" />
- <VpsConnection />
- <ApiKeyRow section="opencodeGo" />
- {state.config?.cloudHome !== true && (
- <p className="-mt-2 text-[12px] leading-relaxed text-ink-secondary">
- {t("keys.opencode.providersHint").split("{command}").flatMap((part, index) =>
- index === 0 ? [part] : [<code key={index} className="font-mono">opencode auth login</code>, part])}
- </p>
- )}
- <OpenCodeProviderKeys />
- <details className="rounded-lg border border-hairline/40 bg-inset px-3 py-2">
- <summary className="cursor-pointer text-[13px] text-ink-secondary">{t("settings.connections.selfHost")}</summary>
- <div className="mt-3">
- <ApiKeyRow section="composio" />
- </div>
- </details>
- </div>
- </Card>
- );
+ return <KeysPage />;
case "decisionModel": return <DecisionModelSettings />;
case "engines": return <EnginesSettings />;
case "backups": return <><WorkspaceBackupSettings /><CompanyBackupSettings /></>;
@@ -494,7 +470,7 @@ export function SettingsModal() {
"mb-2 flex h-8 shrink-0 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] text-[13px] focus-within:ring-2 focus-within:ring-focus/60",
"w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none",
)}
- {visiblePages.length === 0 && advancedMatches.length === 0 && (
+ {visiblePages.length === 0 && advancedMatches.length === 0 && keyResults.length === 0 && (
<div className="px-[9px] py-3 text-[13px] leading-[18px] text-ink-secondary">{t("settings.noMatch", { query: query.trim() })}</div>
)}
{visiblePages.map((page) => {
@@ -528,6 +504,7 @@ export function SettingsModal() {
<span>{t(key)} <span className="text-ink-secondary">· {t("settings.simple.advanced")}</span></span>
</button>
))}
+ {keyResultButtons("flex min-h-8 shrink-0 cursor-pointer items-center rounded-lg px-[9px] py-1.5 text-left text-[13px] leading-[18px] text-ink transition-colors hover:bg-ink/[0.06] motion-reduce:transition-none")}
</nav>
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
@@ -637,6 +614,7 @@ export function SettingsModal() {
</div>
);
})}
+ {keyResultButtons("cursor-pointer flex min-h-9 items-center rounded-lg px-2.5 py-2 text-left text-[13px] text-ink transition-colors hover:bg-control/50 motion-reduce:transition-none")}
</nav>
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
diff --git a/src/components/VoiceSettings.tsx b/src/components/VoiceSettings.tsx
index fa0abce733..51454d132c 100644
--- a/src/components/VoiceSettings.tsx
+++ b/src/components/VoiceSettings.tsx
@@ -21,6 +21,7 @@ import { voiceKeyDraftValue, type VoiceKeyDraft } from "@/lib/voice-key-draft";
import { VoicePicker, type PickerVoice } from "./VoicePicker";
import { Select } from "./Select";
import { Switch } from "./SettingsPrimitives";
+import { KeysLink } from "./keys/KeysLink";
const SAMPLE = "Morning. Overnight the tests went green, and I left two notes for you in the thread.";
const FISH_MODELS = [
@@ -401,7 +402,7 @@ export function VoiceSettings({
{provider === "xai" && (
<p className="mt-4 text-[13px] text-ink-secondary">
- {hostConfigured ? t("voice.grok.ready") : t("voice.grok.missingKey")}
+ {hostConfigured ? t("voice.grok.ready") : <>{t("voice.grok.missingKey")} <KeysLink id="xai" /></>}
</p>
)}
diff --git a/src/components/VpsComputersCard.tsx b/src/components/VpsComputersCard.tsx
index 890a135aed..12a52ea6ac 100644
--- a/src/components/VpsComputersCard.tsx
+++ b/src/components/VpsComputersCard.tsx
@@ -2,6 +2,7 @@ import { AlertTriangle, Loader2, RefreshCw, Server, Trash2 } from "lucide-react"
import { t } from "@/lib/i18n";
import { cn } from "@/lib/cn";
import { Card } from "./SettingsPrimitives";
+import { KeysLink } from "./keys/KeysLink";
import {
computerStateLabel,
vpsComputerInventoryStateKind,
@@ -41,7 +42,7 @@ export function VpsComputersCard({
{configured === true
? t("vm.vps.sshHost", { alias: aliases.join(", ") || t("vm.vps.configuredFallback") })
: configured === false
- ? t("vm.vps.needsAlias")
+ ? <>{t("vm.vps.needsAlias")} <KeysLink id="vps" /></>
: t("vm.vps.refreshHint")}
</div>
<button
diff --git a/src/components/XCard.tsx b/src/components/XCard.tsx
index a8167fc305..6cf777476d 100644
--- a/src/components/XCard.tsx
+++ b/src/components/XCard.tsx
@@ -6,7 +6,7 @@ import { activeLocale, t } from "@/lib/i18n";
import { xResearchAction } from "@/lib/cloud-plan";
import { keyRemoved, keySaved, keySaveFailure, keyTestResult } from "@/lib/product-events";
import { isXConnectorStatus, type XConnectorStatus, type XIncludedUsage } from "../../shared/x-connector";
-import { looksLikeKey, saveCredential, tregVerdict } from "./ApiKeys";
+import { looksLikeKey, saveCredential, tregVerdict } from "./keys/key-save";
import { useCloudPlan } from "./ProIntroduction";
const TREG_URL = "https://treg.to";
diff --git a/src/components/bot-settings/AccessSection.tsx b/src/components/bot-settings/AccessSection.tsx
index 1f3f1d7b2a..82127973c5 100644
--- a/src/components/bot-settings/AccessSection.tsx
+++ b/src/components/bot-settings/AccessSection.tsx
@@ -27,6 +27,8 @@ import {
type ConnectorVerb,
} from "@/lib/connector-grants";
import { inputCls } from "./field";
+import { openKeySettings } from "../keys/key-focus";
+import { KeysLink } from "../keys/KeysLink";
import type { ConnectorScope, ConnectorScopes } from "../../../shared/connector-scopes";
import type { useBotSettingsDerived } from "./useBotSettingsDerived";
@@ -482,7 +484,7 @@ function ResearchCard({ bot, patch }: { bot: Bot; patch: (patch: { xResearch: bo
<div className="text-[15px] font-medium text-ink">{t("research.title")}</div>
<div className="mt-0.5 text-[13px] text-ink-secondary">{line}</div>
{!available && !connecting && (
- <button type="button" className="ui-button mt-2" onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}>
+ <button type="button" className="ui-button mt-2" onClick={() => dispatch(openKeySettings("treg"))}>
{t("research.openKeys")}
</button>
)}
@@ -557,7 +559,7 @@ export function VpsAliasField({ bot }: { bot: Bot }) {
<div className="mt-0.5 text-[12px] text-ink-secondary">
{defaultAlias
? t("botAccess.cloud.serverDefault", { alias: defaultAlias })
- : t("botAccess.cloud.serverNoDefault")}
+ : t("botAccess.cloud.serverNoDefault")} <KeysLink id="vps" />
</div>
<form
className="mt-2 flex items-center gap-2"
diff --git a/src/components/keys/KeyPanels.tsx b/src/components/keys/KeyPanels.tsx
new file mode 100644
index 0000000000..b99c12cad4
--- /dev/null
+++ b/src/components/keys/KeyPanels.tsx
@@ -0,0 +1,246 @@
+import { useEffect, useRef, useState } from "react";
+import { Loader2, TriangleAlert } from "lucide-react";
+import { api, useStore, type ConfigStatus } from "@/state/store";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { Switch } from "../SettingsPrimitives";
+import { KEY_FIELD } from "./KeyRow";
+import { cleanKey, looksLikeKey } from "./key-save";
+
+/** Security: write-only; the server returns names, never keys, and hands the keys to OpenCode alone. */
+export function OpenCodeProviderKeys() {
+ const { state, dispatch } = useStore();
+ const names = state.config?.opencodeGo?.providerKeys ?? [];
+ const [name, setName] = useState("");
+ const [key, setKey] = useState("");
+ const [adding, setAdding] = useState(false);
+ const [removing, setRemoving] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const busy = adding || removing !== null;
+
+ const put = (target: string, value: string) =>
+ api("/api/config", { method: "PUT", body: JSON.stringify({ opencodeGo: { providerKeys: { [target]: value } } }) })
+ .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }));
+
+ const add = () => {
+ const target = name.trim().toUpperCase();
+ const value = cleanKey(key);
+ if (busy || !target || !value) return;
+ if (!looksLikeKey(value)) {
+ setError(t("keys.notAKey"));
+ return;
+ }
+ setAdding(true);
+ setError(null);
+ put(target, value)
+ .then(() => { setName(""); setKey(""); })
+ .catch((e) => setError(e.message))
+ .finally(() => setAdding(false));
+ };
+
+ const remove = (target: string) => {
+ if (busy) return;
+ setRemoving(target);
+ setError(null);
+ put(target, "")
+ .catch((e) => setError(e.message))
+ .finally(() => setRemoving(null));
+ };
+
+ return (
+ <div data-opencode-provider-keys className="flex flex-col gap-2">
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.opencode.otherProviders.hint")}</p>
+ {state.config?.cloudHome !== true && (
+ <p className="text-[12px] leading-4 text-ink-secondary">
+ {t("keys.opencode.providersHint").split("{command}").flatMap((part, index) =>
+ index === 0 ? [part] : [<code key={index} className="font-mono">opencode auth login</code>, part])}
+ </p>
+ )}
+ {names.map((saved) => (
+ <div key={saved} data-opencode-provider-key={saved} className="flex flex-wrap items-center gap-2">
+ <span className={cn(KEY_FIELD, "block flex-1 truncate text-ink")}>{saved}</span>
+ <button
+ type="button"
+ onClick={() => remove(saved)}
+ disabled={busy}
+ aria-label={t("keys.opencode.otherProviders.removeAria", { name: saved })}
+ className="ui-button shrink-0"
+ >
+ {removing === saved ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.row.remove")}
+ </button>
+ </div>
+ ))}
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => { setError(null); setName(e.target.value); }}
+ onKeyDown={(e) => e.key === "Enter" && add()}
+ disabled={busy}
+ placeholder="VENICE_API_KEY"
+ aria-label={t("keys.opencode.otherProviders.name")}
+ autoComplete="off"
+ spellCheck={false}
+ className={cn(KEY_FIELD, "w-auto min-w-[min(100%,10rem)] flex-1 uppercase placeholder:normal-case")}
+ />
+ <input
+ type="password"
+ value={key}
+ onChange={(e) => { setError(null); setKey(e.target.value); }}
+ onKeyDown={(e) => e.key === "Enter" && add()}
+ disabled={busy}
+ placeholder={t("keys.opencode.otherProviders.keyPlaceholder")}
+ aria-label={t("keys.opencode.otherProviders.key")}
+ autoComplete="off"
+ className={cn(KEY_FIELD, "w-auto min-w-[min(100%,10rem)] flex-1")}
+ />
+ <button type="button" onClick={add} disabled={busy || !name.trim() || !key.trim()} className="ui-button ui-button-primary shrink-0">
+ {adding ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("common.save")}
+ </button>
+ </div>
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}
+ </div>
+ );
+}
+
+export function AnthropicEveryClaudeBot() {
+ const { state, dispatch } = useStore();
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ if (!state.config?.anthropic?.configured) return null;
+ const on = state.config.anthropic.everyClaudeBot === true;
+ const toggle = () => {
+ if (saving) return;
+ setSaving(true);
+ setError(null);
+ api("/api/config", { method: "PUT", body: JSON.stringify({ anthropic: { everyClaudeBot: !on } }) })
+ .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))
+ .catch((e) => setError(e.message))
+ .finally(() => setSaving(false));
+ };
+ return (
+ <div data-anthropic-every-claude-bot className="flex flex-col gap-1.5">
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] leading-[18px] text-ink">{t("keys.anthropic.everyBot")}</div>
+ <div className="text-[12px] leading-4 text-ink-secondary">{on ? t("keys.anthropic.everyBotOn") : t("keys.anthropic.everyBotOff")}</div>
+ </div>
+ <Switch checked={on} disabled={saving} onClick={toggle} aria-label={t("keys.anthropic.everyBot")} />
+ </div>
+ {on && (
+ <p className="flex gap-1.5 text-[12px] leading-4 text-warning">
+ <TriangleAlert size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{t("keys.anthropic.warning")}</span>
+ </p>
+ )}
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}
+ </div>
+ );
+}
+
+/** Non-secret Docker-over-SSH target. Keys and passwords stay with SSH. */
+export function VpsConnection() {
+ const { state, dispatch } = useStore();
+ const [alias, setAlias] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const configured = Boolean(state.config?.vps?.configured);
+ const clearing = !alias.trim() && configured;
+
+ useEffect(() => {
+ setAlias(state.config?.vps?.sshAlias ?? "");
+ }, [state.config?.vps?.sshAlias]);
+
+ const save = () => {
+ if (saving || (!alias.trim() && !configured)) return;
+ setSaving(true);
+ setError(null);
+ api("/api/config", { method: "PUT", body: JSON.stringify({ vps: { sshAlias: alias.trim() } }) })
+ .then((status: ConfigStatus) => {
+ dispatch({ type: "configStatus", config: status });
+ setAlias(status.vps?.sshAlias ?? "");
+ })
+ .catch((e) => setError(e.message))
+ .finally(() => setSaving(false));
+ };
+
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="text-[12px] leading-4 text-ink-secondary">
+ {t("keys.vps.descBefore")}
+ <a href="https://github.com/milind-soni/OpenMausBot/blob/main/docs/byo-vps.md" target="_blank" rel="noopener noreferrer" className="text-accent-text hover:underline">
+ {t("keys.vps.descLink")}
+ </a>
+ {t("keys.vps.descAfter")}
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ type="text"
+ data-key-input
+ value={alias}
+ onChange={(e) => setAlias(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && save()}
+ placeholder="my-vps"
+ aria-label={t("keys.vps.aria")}
+ autoComplete="off"
+ spellCheck={false}
+ className={cn(KEY_FIELD, "w-auto min-w-[min(100%,12rem)] flex-1")}
+ />
+ <button
+ type="button"
+ onClick={save}
+ disabled={saving || (!alias.trim() && !configured) || alias.trim() === (state.config?.vps?.sshAlias ?? "")}
+ className={cn("ui-button shrink-0", !clearing && "ui-button-primary")}
+ title={clearing ? t("keys.vps.removeAlias") : undefined}
+ >
+ {saving ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : clearing ? t("keys.row.remove") : t("common.save")}
+ </button>
+ </div>
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}
+ </div>
+ );
+}
+
+export function OpenAiCompatUrl() {
+ const { state, dispatch } = useStore();
+ const saved = state.config?.openaiCompat?.url ?? "";
+ const [value, setValue] = useState(saved);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const savingRef = useRef(false);
+ useEffect(() => { setValue(saved); }, [saved]);
+ const dirty = value.trim() !== saved;
+
+ const save = () => {
+ if (savingRef.current || !dirty) return;
+ savingRef.current = true;
+ setSaving(true);
+ setError(null);
+ api("/api/config", { method: "PUT", body: JSON.stringify({ openaiCompat: { url: value.trim() } }) })
+ .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))
+ .catch((e) => setError(e.message))
+ .finally(() => { savingRef.current = false; setSaving(false); });
+ };
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="text-[13px] leading-[18px] text-ink">{t("keys.openaiCompat.url")}</div>
+ <div className="relative">
+ <input
+ type="url"
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onBlur={save}
+ onKeyDown={(e) => e.key === "Enter" && save()}
+ placeholder="https://api.groq.com/openai/v1"
+ aria-label={t("keys.openaiCompat.url")}
+ spellCheck={false}
+ className={cn(KEY_FIELD, "pr-8")}
+ />
+ {saving && <Loader2 size={13} aria-hidden="true" className="absolute right-2.5 top-1/2 -translate-y-1/2 animate-spin text-ink-secondary" />}
+ </div>
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.openaiCompat.urlHint")}</p>
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}
+ </div>
+ );
+}
diff --git a/src/components/ApiKeys.analytics.test.ts b/src/components/keys/KeyRow.analytics.test.ts
similarity index 71%
rename from src/components/ApiKeys.analytics.test.ts
rename to src/components/keys/KeyRow.analytics.test.ts
index df971db568..e41137f582 100644
--- a/src/components/ApiKeys.analytics.test.ts
+++ b/src/components/keys/KeyRow.analytics.test.ts
@@ -17,6 +17,7 @@ vi.mock("react", async (original) => ({
}];
},
useEffect: () => {},
+ useId: () => "row",
useRef: (current: unknown) => {
const index = fixture.refIndex++;
fixture.refs[index] ??= { current };
@@ -25,35 +26,33 @@ vi.mock("react", async (original) => ({
}));
vi.mock("@/state/store", async (original) => {
const store = await original<typeof import("@/state/store")>();
- return { ...store, api: fixture.api, useStore: () => ({ state: { ...store.initialState, config: fixture.config }, dispatch: fixture.dispatch }) };
+ return { ...store, api: fixture.api, useStore: () => ({ state: { ...store.initialState, config: fixture.config, instances: [] }, dispatch: fixture.dispatch }) };
});
vi.mock("@/lib/analytics", () => ({ track: fixture.track }));
const { ApiError } = await import("@/state/store");
-const { ApiKeyRow } = await import("./ApiKeys");
+const { KeyRow } = await import("./KeyRow");
-type Props = { children?: ReactNode; type?: string; onChange?: (event: { target: { value: string } }) => void; onKeyDown?: (event: { key: string }) => void; onBlur?: () => void; onClick?: () => void };
+type Props = { children?: ReactNode; type?: string; onChange?: (event: { target: { value: string } }) => void; onKeyDown?: (event: { key: string; preventDefault: () => void }) => void; onClick?: () => void; "data-key-remove"?: boolean };
function nodes(tree: ReactNode): Array<ReactElement<Props>> {
return Children.toArray(tree).flatMap((child) => isValidElement<Props>(child) ? [child, ...nodes(child.props.children)] : []);
}
-function render(props: Parameters<typeof ApiKeyRow>[0]) {
+function render(props: Parameters<typeof KeyRow>[0]) {
fixture.index = 0;
fixture.refIndex = 0;
- return nodes(ApiKeyRow(props));
+ return nodes(KeyRow(props));
}
const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };
const input = (tree: Array<ReactElement<Props>>) => tree.find((node) => node.type === "input")!;
-async function paste(props: Parameters<typeof ApiKeyRow>[0], { blurToo = false } = {}) {
+async function enterKey(props: Parameters<typeof KeyRow>[0]) {
input(render(props)).props.onChange!({ target: { value: KEY } });
- const typed = input(render(props));
- typed.props.onKeyDown!({ key: "Enter" });
- if (blurToo) typed.props.onBlur!();
+ input(render(props)).props.onKeyDown!({ key: "Enter", preventDefault: () => {} });
await flush();
}
function expectNoKeyIn(calls: unknown) {
const sent = JSON.stringify(calls);
- for (const fragment of [KEY, KEY.slice(0, 6), KEY.slice(-6), String(KEY.length), "SECRET"]) expect(sent).not.toContain(fragment);
+ for (const fragment of [KEY, KEY.slice(0, 6), KEY.slice(-6), KEY.slice(-4), String(KEY.length), "SECRET"]) expect(sent).not.toContain(fragment);
}
beforeEach(() => {
@@ -62,6 +61,7 @@ beforeEach(() => {
fixture.refs = [];
fixture.config = { anthropic: { configured: false }, box: { configured: false } };
vi.stubGlobal("window", {});
+ vi.stubGlobal("document", { activeElement: null });
});
afterEach(() => vi.unstubAllGlobals());
@@ -71,8 +71,8 @@ describe("a key saved in Settings → API keys", () => {
["rejected", { ok: false, reason: "rejected" }],
["unverified", { ok: false, reason: "unreachable" }],
])("reports one save whose result is the key test's verdict (%s), and never the key", async (result, verdict) => {
- fixture.api.mockResolvedValueOnce({ ...fixture.config, anthropic: { configured: true } }).mockResolvedValueOnce(verdict);
- await paste({ section: "anthropic", testProvider: "anthropic" }, { blurToo: true });
+ fixture.api.mockResolvedValueOnce({ ...fixture.config, anthropic: { configured: true, last4: KEY.slice(-4) } }).mockResolvedValueOnce(verdict);
+ await enterKey({ id: "anthropic" });
expect(fixture.api.mock.calls.map(([path]) => path)).toEqual(["/api/config", "/api/keys/test"]);
expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "anthropic", via: "settings", result }]]);
expectNoKeyIn(fixture.track.mock.calls);
@@ -81,8 +81,7 @@ describe("a key saved in Settings → API keys", () => {
it("still reports the verdict when typing again made the row stop showing it", async () => {
let answer!: (value: unknown) => void;
fixture.api.mockResolvedValueOnce({ anthropic: { configured: true } }).mockReturnValueOnce(new Promise((resolve) => { answer = resolve; }));
- await paste({ section: "anthropic", testProvider: "anthropic" });
- input(render({ section: "anthropic", testProvider: "anthropic" })).props.onChange!({ target: { value: "x" } });
+ await enterKey({ id: "anthropic" });
answer({ ok: true });
await flush();
expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "anthropic", via: "settings", result: "ok" }]]);
@@ -90,7 +89,7 @@ describe("a key saved in Settings → API keys", () => {
it("reports a refused save as an error even when the server's words echo the key", async () => {
fixture.api.mockRejectedValueOnce(new ApiError(`Invalid key ${KEY}`, 400, { error: `Invalid key ${KEY}` }));
- await paste({ section: "anthropic", testProvider: "anthropic" });
+ await enterKey({ id: "anthropic" });
expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "anthropic", via: "settings", result: "error" }]]);
expectNoKeyIn(fixture.track.mock.calls);
});
@@ -98,7 +97,7 @@ describe("a key saved in Settings → API keys", () => {
it("reports a Boat key boat.dev refused over the desktop bridge as rejected, from the Computer panel", async () => {
const setCredential = vi.fn().mockRejectedValue(new Error(`Error invoking remote method 'credential:set': KeyRejected: That doesn't look like a Boat API key: ${KEY.slice(0, 12)}`));
vi.stubGlobal("window", { ogb: { setCredential } });
- await paste({ section: "box", via: "computer_panel" });
+ await enterKey({ id: "box", via: "computer_panel" });
expect(setCredential).toHaveBeenCalledWith("boxToken", KEY);
expect(fixture.api).not.toHaveBeenCalled();
expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "boat", via: "computer_panel", result: "rejected" }]]);
@@ -107,38 +106,45 @@ describe("a key saved in Settings → API keys", () => {
it("reports a Boat key the server checked as ok, without testing it again", async () => {
fixture.api.mockResolvedValueOnce({ box: { configured: true } });
- await paste({ section: "box" });
+ await enterKey({ id: "box" });
expect(fixture.api).toHaveBeenCalledOnce();
expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "boat", via: "settings", result: "ok" }]]);
});
- it("reports a cleared key as removed, once, and a failed clear not at all", async () => {
- fixture.config = { anthropic: { configured: true } };
+ it("saves an xAI key through the desktop's encrypted store, so Remove clears the stored copy too", async () => {
+ const setCredential = vi.fn().mockResolvedValue({ xai: { configured: true } });
+ vi.stubGlobal("window", { ogb: { setCredential } });
+ fixture.api.mockResolvedValue({ ok: true });
+ await enterKey({ id: "xai" });
+ expect(setCredential).toHaveBeenCalledWith("xaiApiKey", KEY);
+ expect(fixture.api.mock.calls.map(([path]) => path)).toEqual(["/api/keys/test"]);
+ });
+
+ it("reports a removed key as removed, once, and a failed remove not at all", async () => {
+ fixture.config = { anthropic: { configured: true, last4: "6789" } };
fixture.api.mockRejectedValueOnce(new ApiError("busy", 409, { error: "busy" })).mockResolvedValueOnce({ anthropic: { configured: false } });
- const clear = () => render({ section: "anthropic", testProvider: "anthropic" }).find((node) => node.type === "button" && JSON.stringify(node.props.children).includes("Clear"))!;
- clear().props.onClick!();
+ const remove = () => render({ id: "anthropic" }).find((node) => node.type === "button" && node.props["data-key-remove"])!;
+ remove().props.onClick!();
await flush();
expect(fixture.track).not.toHaveBeenCalled();
- clear().props.onClick!();
- clear().props.onClick!();
+ remove().props.onClick!();
+ remove().props.onClick!();
await flush();
expect(fixture.api).toHaveBeenCalledTimes(2);
expect(fixture.track.mock.calls).toEqual([["api_key_removed", { provider: "anthropic", via: "settings" }]]);
});
- it("offers Clear for a Composio project key of the person's own, and none for the managed connection", async () => {
- const row = () => render({ section: "composio" });
- const clear = () => row().find((node) => node.type === "button" && JSON.stringify(node.props.children).includes("Clear"));
+ it("offers Remove for a Composio project key of the person's own, and none for the managed connection", async () => {
+ const remove = () => render({ id: "composio" }).find((node) => node.type === "button" && node.props["data-key-remove"]);
fixture.config = { composio: { configured: true, mode: "managed" } };
- expect(clear()).toBeUndefined();
- expect(JSON.stringify(row().map((node) => node.props.children))).not.toContain("Configured");
+ expect(remove()).toBeUndefined();
fixture.config = { composio: { configured: true, mode: "self-hosted" } };
fixture.api.mockResolvedValue({ composio: { configured: true, mode: "managed" } });
- clear()!.props.onClick!();
+ remove()!.props.onClick!();
await flush();
expect(fixture.api).toHaveBeenCalledOnce();
expect(fixture.track.mock.calls).toEqual([["api_key_removed", { provider: "composio", via: "settings" }]]);
fixture.config = { composio: { configured: true, mode: "managed" } };
- expect(clear()).toBeUndefined();
+ expect(remove()).toBeUndefined();
});
});
diff --git a/src/components/keys/KeyRow.test.ts b/src/components/keys/KeyRow.test.ts
new file mode 100644
index 0000000000..5ebabaca03
--- /dev/null
+++ b/src/components/keys/KeyRow.test.ts
@@ -0,0 +1,136 @@
+import { createElement, type ComponentProps } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import type { ConfigStatus, InstanceInfo } from "@/state/store";
+
+const fixture = vi.hoisted(() => ({ config: {} as Partial<ConfigStatus>, instances: [] as InstanceInfo[] }));
+vi.mock("@/state/store", async (original) => {
+ const store = await original<typeof import("@/state/store")>();
+ return { ...store, useStore: () => ({ state: { ...store.initialState, config: fixture.config, instances: fixture.instances }, dispatch: vi.fn() }) };
+});
+
+const { KeyRow } = await import("./KeyRow");
+const { cleanKey, looksLikeKey, tregVerdict } = await import("./key-save");
+
+beforeEach(() => {
+ fixture.config = {};
+ fixture.instances = [];
+ vi.stubGlobal("window", {});
+ setLocale("en");
+});
+afterEach(() => vi.unstubAllGlobals());
+
+const render = (props: ComponentProps<typeof KeyRow>) => renderToStaticMarkup(createElement(KeyRow, props));
+
+describe("an empty key row", () => {
+ it("is a calm field with the key's shape, show and hide, one Save and where to get a key", () => {
+ const html = render({ id: "anthropic" });
+ expect(html).toContain("Anthropic API key");
+ expect(html).toContain("Claude models, billed per token");
+ expect(html).toMatch(/<input[^>]*type="password"[^>]*placeholder="sk-ant-…"[^>]*aria-label="Anthropic API key"[^>]*value=""/);
+ expect(html).toContain('aria-label="Show key"');
+ expect(html.match(/data-key-save=/g)).toHaveLength(1);
+ expect(html).toMatch(/data-key-save="true"[^>]*disabled=""/);
+ expect(html).toMatch(/<a href="https:\/\/console\.anthropic\.com\/settings\/keys"[^>]*>Get a key/);
+ expect(html).not.toContain("Connected");
+ expect(html).not.toContain("data-key-masked");
+ });
+
+ it("keeps a key's warning in view before it is added", () => {
+ expect(render({ id: "box" })).toContain("Boat is a paid service after its trial.");
+ expect(render({ id: "openai" })).toContain("Codex doesn&#x27;t use this key");
+ });
+});
+
+describe("a saved key", () => {
+ it("shows the key masked to its last four, Connected with a check, and Replace and Remove beside it", () => {
+ fixture.config = { anthropic: { configured: true, last4: "a1b2" } };
+ const html = render({ id: "anthropic" });
+ expect(html).toContain("••••••••a1b2");
+ expect(html).toContain("Anthropic API key is saved and ends in a1b2");
+ expect(html).toContain(">Connected<");
+ expect(html).toContain("data-key-replace");
+ expect(html).toContain("data-key-remove");
+ expect(html).not.toContain("<input");
+ expect(html).toContain('data-key-state="saved"');
+ });
+
+ it("says Saved, not Connected, for a key nothing can test", () => {
+ fixture.config = { deepseek: { configured: true, last4: "9z9z" } };
+ const html = render({ id: "deepseek" });
+ expect(html).toContain(">Saved<");
+ expect(html).not.toContain(">Connected<");
+ expect(html).toContain("••••••••9z9z");
+ });
+
+ it("masks a saved key it has no hint for, never showing an empty field", () => {
+ fixture.config = { treg: { configured: true } };
+ const html = render({ id: "treg" });
+ expect(html).toMatch(/<span aria-hidden="true">••••••••<\/span>/);
+ expect(html).not.toContain("<input");
+ });
+
+ it("reads the keys kept inside other settings back from savedKeys", () => {
+ fixture.config = { savedKeys: { ttsKey: { configured: true, last4: "11aa" }, openaiLiveKey: { configured: true, last4: "22bb" } } };
+ expect(render({ id: "elevenlabs" })).toContain("••••••••11aa");
+ expect(render({ id: "liveKey" })).toContain("••••••••22bb");
+ expect(render({ id: "jev" })).toContain("<input");
+ });
+
+ it("marks a key its provider has since rejected as not working, keeping it in view to replace", () => {
+ fixture.config = { openai: { configured: true, last4: "a1b2" } };
+ fixture.instances = [{ instanceId: "openai", driverKind: "openai-compat", displayName: "OpenAI", access: "api",
+ snapshot: { state: "available", authenticated: false }, models: { default: "m", options: [] } } as unknown as InstanceInfo];
+ const html = render({ id: "openai" });
+ expect(html).toContain(">Didn&#x27;t work<");
+ expect(html).toContain("Didn&#x27;t work: The provider rejected this key.");
+ expect(html).toContain("••••••••a1b2");
+ expect(html).toContain("data-key-replace");
+ });
+});
+
+describe("a key that comes with the Cloud plan", () => {
+ it("says it is included and offers the person's own key only on request", () => {
+ fixture.config = { box: { configured: true, included: true } };
+ const html = render({ id: "box" });
+ expect(html).toContain("Included with your Cloud plan");
+ expect(html).toContain("Use your own key");
+ expect(html).not.toContain("<input");
+ expect(html).not.toContain("data-key-remove");
+ });
+});
+
+describe("a row that uses another row's key", () => {
+ it("shows the OpenAI key under its own name in Voice and calls, without a second Remove", () => {
+ fixture.config = { openai: { configured: true, last4: "a1b2" } };
+ const html = render({ id: "openai", row: "liveCalls" });
+ expect(html).toContain('data-key-row="liveCalls"');
+ expect(html).not.toContain("data-api-key-row");
+ expect(html).toContain("OpenAI key");
+ expect(html).toContain("Live calls use the same key as OpenAI&#x27;s models");
+ expect(html).toContain("••••••••a1b2");
+ expect(html).toContain("data-key-replace");
+ expect(html).not.toContain("data-key-remove");
+ });
+});
+
+describe("what a pasted key goes through", () => {
+ it("drops the spaces, line breaks, quotes and invisible characters a copy brings along", () => {
+ expect(cleanKey(" sk-proj-abc123\n")).toBe("sk-proj-abc123");
+ expect(cleanKey('"sk-proj-abc123"')).toBe("sk-proj-abc123");
+ expect(cleanKey("​sk-proj-abc123")).toBe("sk-proj-abc123");
+ });
+
+ it("refuses text that is not a key", () => {
+ expect(looksLikeKey("sk-proj-abc123_DEF")).toBe(true);
+ expect(looksLikeKey("The mascots are ready")).toBe(false);
+ expect(looksLikeKey("sk-abc\n")).toBe(false);
+ });
+
+ it("says treg is working with the balance, or names the exact problem", () => {
+ expect(tregVerdict({ ok: true, check: "treg", balanceUsd: 4.25 } as never)).toBe("treg is working ✓ Balance: $4.25.");
+ expect(tregVerdict({ ok: true })).toBe("treg is working ✓");
+ expect(tregVerdict({ ok: false, message: "treg rejected this key. Copy it again from treg.to." })).toBe("treg rejected this key. Copy it again from treg.to.");
+ });
+});
diff --git a/src/components/keys/KeyRow.tsx b/src/components/keys/KeyRow.tsx
new file mode 100644
index 0000000000..67a4739c7c
--- /dev/null
+++ b/src/components/keys/KeyRow.tsx
@@ -0,0 +1,377 @@
+import { useEffect, useId, useRef, useState, type ReactNode } from "react";
+import { Check, CircleAlert, ExternalLink, Eye, EyeOff, Loader2, TriangleAlert } from "lucide-react";
+import { useStore } from "@/state/store";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import type { KeyResult, KeyVia } from "@/lib/analytics-allowlist";
+import { keyRemoved, keySaved, keySaveFailure, savedKeyResult } from "@/lib/product-events";
+import { InstanceProviderMark } from "../ProviderIcons";
+import { keyEntry, keyForInstance, looksLikeOtherKey, savedState, type KeyEntry, type KeyId, type SavedState } from "./key-catalog";
+import { checkKey, cleanKey, looksLikeKey, saveKey } from "./key-save";
+
+export const KEY_FIELD = "h-8 w-full min-w-0 rounded-lg border border-hairline/60 bg-inset px-3 font-mono text-[13px] leading-8 text-ink placeholder:text-ink-tertiary focus:outline-none focus-visible:ring-2 focus-visible:ring-focus/60 disabled:opacity-60";
+export const KEY_ROW = "group flex scroll-mt-24 flex-col gap-2 rounded-[10px] px-4 py-2.5 transition-[background-color,box-shadow] duration-500 data-[key-highlight]:bg-accent/10 data-[key-highlight]:ring-1 data-[key-highlight]:ring-accent/40 motion-reduce:transition-none";
+const MASK = "••••••••";
+
+export function KeyMarkIcon({ entry }: { entry: KeyEntry }) {
+ const { mark } = entry;
+ if ("icon" in mark) {
+ const Icon = mark.icon;
+ return <Icon size={16} aria-hidden="true" className="shrink-0 text-ink-tertiary transition-colors group-hover:text-ink-secondary group-focus-within:text-ink-secondary" />;
+ }
+ return <InstanceProviderMark instance={{ driverKind: mark.driverKind, ...(mark.preset ? { icon: { kind: "preset", preset: mark.preset } } : {}) }} size={16} subtle />;
+}
+
+export type KeyStatus = { tone: "busy" | "ok" | "bad"; text: string } | null;
+
+export function KeyStatusChip({ status }: { status: KeyStatus }) {
+ return (
+ <span aria-live="polite" className="flex min-h-5 shrink-0 items-center gap-1 text-[12px] leading-5 text-ink-secondary">
+ {status?.tone === "busy" && <Loader2 size={12} aria-hidden="true" className="animate-spin" />}
+ {status?.tone === "ok" && <Check size={13} aria-hidden="true" className="text-success" />}
+ {status?.tone === "bad" && <CircleAlert size={13} aria-hidden="true" className="text-danger" />}
+ {status && <span className={cn(status.tone === "bad" && "text-danger")}>{status.text}</span>}
+ </span>
+ );
+}
+
+export function MaskedKey({ saved, label }: { saved: SavedState; label: string }) {
+ return (
+ <span data-key-masked className={cn(KEY_FIELD, "block min-w-[min(100%,12rem)] flex-1 select-none truncate text-ink-secondary")}>
+ <span aria-hidden="true">{MASK}{saved.last4 ?? ""}</span>
+ <span className="sr-only">{saved.last4 ? t("keys.row.endsIn", { label, last4: saved.last4 }) : t("keys.row.savedKey", { label })}</span>
+ </span>
+ );
+}
+
+export function SavedKeyLine({ id }: { id: KeyId }) {
+ const { state } = useStore();
+ const entry = keyEntry(id);
+ const saved = savedState(entry, state.config);
+ if (!saved.configured) return null;
+ const label = t(entry.labelKey);
+ return (
+ <div data-key-summary={id} className="mt-1 flex min-w-0 items-center gap-1.5 text-[12px] leading-4 text-ink-secondary">
+ <Check size={13} aria-hidden="true" className="shrink-0 text-success" />
+ <span className="shrink-0">{entry.target?.test || entry.target?.verifiedOnSave ? t("keys.connected") : t("common.saved")}</span>
+ <span aria-hidden="true" className="truncate font-mono">{MASK}{saved.last4 ?? ""}</span>
+ <span className="sr-only">{saved.last4 ? t("keys.row.endsIn", { label, last4: saved.last4 }) : t("keys.row.savedKey", { label })}</span>
+ </div>
+ );
+}
+
+export function RowHeading({ entry, status, titleId }: { entry: KeyEntry; status: KeyStatus; titleId?: string }) {
+ return (
+ <div className="flex items-start gap-3">
+ <span className="flex size-5 shrink-0 items-center justify-center"><KeyMarkIcon entry={entry} /></span>
+ <div className="min-w-0 flex-1">
+ <div id={titleId} className="text-[14px] leading-5 text-ink">{t(entry.labelKey)}</div>
+ <div className="text-[13px] leading-[18px] text-ink-secondary">{t(entry.purposeKey)}</div>
+ </div>
+ <KeyStatusChip status={status} />
+ </div>
+ );
+}
+
+function errorText(cause: unknown): string {
+ return cause instanceof Error ? cause.message.replace(/^Error invoking remote method '[^']*': (?:\w+: )?/, "") : String(cause);
+}
+
+export function KeyRow({
+ id,
+ row: rowId,
+ via = "settings",
+ onSaved,
+ bare = false,
+ rejected: rejectedHere,
+ className,
+ children,
+}: {
+ id: KeyId;
+ row?: KeyId;
+ via?: KeyVia;
+ onSaved?: (configured: boolean) => void;
+ bare?: boolean;
+ rejected?: boolean;
+ className?: string;
+ children?: ReactNode;
+}) {
+ const { state, dispatch } = useStore();
+ const titleId = useId();
+ const [draft, setDraft] = useState("");
+ const [shown, setShown] = useState(false);
+ const [replacing, setReplacing] = useState(false);
+ const [ownKey, setOwnKey] = useState(false);
+ const [busy, setBusy] = useState<"saving" | "checking" | "removing" | null>(null);
+ const [problem, setProblem] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [verdict, setVerdict] = useState<string | null>(null);
+ const [works, setWorks] = useState(false);
+ const busyRef = useRef(false);
+ const generation = useRef(0);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const replaceRef = useRef<HTMLButtonElement>(null);
+ const focusAfter = useRef<"input" | "replace" | null>(null);
+
+ useEffect(() => {
+ const goal = focusAfter.current;
+ if (!goal) return;
+ focusAfter.current = null;
+ (goal === "input" ? inputRef.current : replaceRef.current)?.focus();
+ });
+
+ const entry = keyEntry(id);
+ const row = rowId ? keyEntry(rowId) : entry;
+ const target = entry.target;
+ if (!target) throw new Error(`${id} is not saved by a key row`);
+ const pointer = row.id !== entry.id;
+ const label = t(entry.labelKey);
+ const saved = savedState(entry, state.config);
+ const engineRejected = (state.instances ?? []).some((instance) => instance.access === "api" && keyForInstance(instance.instanceId) === entry.id
+ && instance.snapshot.state === "available" && instance.snapshot.authenticated === false);
+ const rejected = !works && (rejectedHere ?? (saved.configured && engineRejected));
+ const failure = problem ?? (rejected && !busy ? t("keys.testRejected") : null);
+ const editing = !saved.configured || replacing;
+ const fieldShown = editing && (!saved.included || saved.configured || ownKey);
+ const other = fieldShown && draft ? looksLikeOtherKey(row, draft) : null;
+
+ const status: KeyStatus = busy === "saving" ? { tone: "busy", text: t("keys.row.saving") }
+ : busy === "removing" ? { tone: "busy", text: t("keys.row.removing") }
+ : busy === "checking" ? { tone: "busy", text: t("common.checking") }
+ : failure && (saved.configured || !fieldShown) ? { tone: "bad", text: t("keys.row.didntWork") }
+ : saved.configured ? { tone: "ok", text: target.test || target.verifiedOnSave || works ? t("keys.connected") : t("common.saved") }
+ : saved.included ? { tone: "ok", text: t("keys.includedWithCloudPro") }
+ : null;
+
+ const runCheck = async (): Promise<KeyResult> => {
+ if (!target.test) return "unverified";
+ const mine = ++generation.current;
+ setBusy("checking");
+ try {
+ const check = await checkKey(target.test);
+ if (mine === generation.current) {
+ setWorks(check.ok);
+ setVerdict(check.ok ? check.text : null);
+ setProblem(check.ok ? null : check.text);
+ }
+ return check.result;
+ } catch (cause) {
+ if (mine === generation.current) setProblem(errorText(cause));
+ return "unverified";
+ }
+ };
+
+ const save = async (raw: string) => {
+ const value = cleanKey(raw);
+ if (busyRef.current || !value) return;
+ if (!looksLikeKey(value)) {
+ setNotice(t("keys.notAKey"));
+ return;
+ }
+ busyRef.current = true;
+ generation.current += 1;
+ const hadFocus = document.activeElement === inputRef.current;
+ setBusy("saving");
+ setProblem(null);
+ setNotice(null);
+ setVerdict(null);
+ setWorks(false);
+ try {
+ const status = await saveKey(target, value, !saved.configured);
+ dispatch({ type: "configStatus", config: status });
+ const now = target.saved(status);
+ setDraft("");
+ setShown(false);
+ setReplacing(false);
+ setOwnKey(false);
+ if (hadFocus) focusAfter.current = now.configured ? "replace" : "input";
+ if (!now.configured) setProblem(t("keys.row.notKept"));
+ onSaved?.(now.configured);
+ keySaved(target.analytics, via, now.configured && target.test ? await runCheck() : savedKeyResult(target.analytics));
+ } catch (cause) {
+ setProblem(errorText(cause));
+ keySaved(target.analytics, via, keySaveFailure(cause));
+ } finally {
+ busyRef.current = false;
+ setBusy(null);
+ }
+ };
+
+ const recheck = async () => {
+ if (busyRef.current) return;
+ busyRef.current = true;
+ setVerdict(null);
+ setProblem(null);
+ try {
+ await runCheck();
+ } finally {
+ busyRef.current = false;
+ setBusy(null);
+ }
+ };
+
+ const remove = async () => {
+ if (busyRef.current) return;
+ busyRef.current = true;
+ generation.current += 1;
+ setBusy("removing");
+ setProblem(null);
+ setVerdict(null);
+ setWorks(false);
+ try {
+ const status = await saveKey(target, "", false);
+ dispatch({ type: "configStatus", config: status });
+ setReplacing(false);
+ setDraft("");
+ onSaved?.(target.saved(status).configured);
+ keyRemoved(target.analytics, via);
+ } catch (cause) {
+ setProblem(errorText(cause));
+ } finally {
+ busyRef.current = false;
+ setBusy(null);
+ }
+ };
+
+ const startReplace = () => {
+ setReplacing(true);
+ setProblem(null);
+ setVerdict(null);
+ focusAfter.current = "input";
+ };
+
+ const cancelReplace = () => {
+ setReplacing(false);
+ setDraft("");
+ setNotice(null);
+ focusAfter.current = "replace";
+ };
+
+ const field = (
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative min-w-[min(100%,12rem)] flex-1">
+ <input
+ ref={inputRef}
+ data-key-input
+ type={shown ? "text" : "password"}
+ value={draft}
+ onChange={(event) => { setDraft(event.target.value); setNotice(null); setProblem(null); }}
+ onPaste={(event) => {
+ const pasted = cleanKey(event.clipboardData.getData("text"));
+ if (!pasted) return;
+ event.preventDefault();
+ setDraft(pasted);
+ setNotice(null);
+ setProblem(null);
+ if (looksLikeKey(pasted) && !looksLikeOtherKey(row, pasted)) void save(pasted);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void save(draft);
+ } else if (event.key === "Escape" && replacing) {
+ event.preventDefault();
+ event.stopPropagation();
+ cancelReplace();
+ }
+ }}
+ disabled={busy === "saving"}
+ placeholder={replacing ? t("keys.row.newKey") : target.placeholderKey ? t(target.placeholderKey) : target.placeholder}
+ aria-label={label}
+ autoComplete="off"
+ spellCheck={false}
+ className={cn(KEY_FIELD, "pr-9")}
+ />
+ <button
+ type="button"
+ onClick={() => setShown((current) => !current)}
+ aria-label={shown ? t("keys.row.hide") : t("keys.row.show")}
+ aria-pressed={shown}
+ className="absolute right-0.5 top-1/2 flex size-7 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md text-ink-tertiary transition-colors hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus/60"
+ >
+ {shown ? <EyeOff size={14} aria-hidden="true" /> : <Eye size={14} aria-hidden="true" />}
+ </button>
+ </div>
+ <span className="flex shrink-0 items-center gap-2">
+ <button type="button" data-key-save className="ui-button ui-button-primary" disabled={!draft.trim() || busy !== null} onClick={() => void save(draft)}>
+ {t("common.save")}
+ </button>
+ {replacing && <button type="button" className="ui-button" onClick={cancelReplace}>{t("common.cancel")}</button>}
+ </span>
+ </div>
+ );
+
+ const masked = (
+ <div className="flex flex-wrap items-center gap-2">
+ <MaskedKey saved={saved} label={label} />
+ <span className="flex shrink-0 items-center gap-2">
+ <button ref={replaceRef} type="button" data-key-replace className="ui-button" disabled={busy !== null} onClick={startReplace}>{t("keys.row.replace")}</button>
+ {!pointer && <button type="button" data-key-remove className="ui-button" disabled={busy !== null} onClick={() => void remove()}>{t("keys.row.remove")}</button>}
+ </span>
+ </div>
+ );
+
+ const warning = target.warningKey && fieldShown ? t(target.warningKey) : null;
+ const note = target.noteKey && fieldShown && !pointer ? t(target.noteKey) : null;
+
+ return (
+ <div
+ data-key-row={row.id}
+ data-api-key-row={pointer ? undefined : entry.id}
+ data-key-state={saved.configured ? "saved" : saved.included ? "included" : "empty"}
+ aria-labelledby={bare ? undefined : titleId}
+ role="group"
+ className={cn(KEY_ROW, className)}
+ >
+ {bare ? status && <KeyStatusChip status={status} /> : <RowHeading entry={row} status={status} titleId={titleId} />}
+ <div className={cn("flex flex-col gap-2", !bare && "pl-8")}>
+ {fieldShown ? field : saved.configured ? masked : (
+ <div>
+ <button type="button" data-key-own className="ui-button" onClick={() => { setOwnKey(true); focusAfter.current = "input"; }}>{t("keys.row.useOwn")}</button>
+ </div>
+ )}
+ {(notice || failure || other || warning || note || verdict || (fieldShown && target.href) || (!fieldShown && saved.configured && target.test)) && (
+ <div className="flex flex-col gap-1.5 text-[12px] leading-4">
+ {notice && <p role="alert" className="text-danger">{notice}</p>}
+ {failure && (
+ <p role="alert" className="flex gap-1.5 text-danger">
+ <CircleAlert size={13} aria-hidden="true" className="mt-px shrink-0" />
+ <span>{t("keys.row.failed", { reason: failure })}</span>
+ </p>
+ )}
+ {other && (
+ <p className="flex gap-1.5 text-warning">
+ <TriangleAlert size={13} aria-hidden="true" className="mt-px shrink-0" />
+ <span>{t("keys.row.looksLike", { label: t(other.labelKey) })}</span>
+ </p>
+ )}
+ {warning && (
+ <p className="flex gap-1.5 text-warning">
+ <TriangleAlert size={13} aria-hidden="true" className="mt-px shrink-0" />
+ <span>{warning}</span>
+ </p>
+ )}
+ {note && <p className="text-ink-secondary">{note}</p>}
+ {verdict && <p role="status" className="whitespace-pre-line text-ink-secondary">{verdict}</p>}
+ {(fieldShown && target.href) || (!fieldShown && saved.configured && target.test) ? (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1">
+ {fieldShown && target.href && (
+ <a href={target.href} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 font-medium text-accent-text hover:underline">
+ {t("keys.row.getKey")}
+ <ExternalLink size={11} aria-hidden="true" />
+ </a>
+ )}
+ {!fieldShown && saved.configured && target.test && (
+ <button type="button" data-key-check className="cursor-pointer text-ink-secondary hover:text-ink hover:underline disabled:opacity-50" disabled={busy !== null} onClick={() => void recheck()}>
+ {t("common.checkAgain")}
+ </button>
+ )}
+ </div>
+ ) : null}
+ </div>
+ )}
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/keys/KeysLink.tsx b/src/components/keys/KeysLink.tsx
new file mode 100644
index 0000000000..c8b5dd5bed
--- /dev/null
+++ b/src/components/keys/KeysLink.tsx
@@ -0,0 +1,15 @@
+import { useStore } from "@/state/store";
+import { t } from "@/lib/i18n";
+import type { KeyId } from "./key-catalog";
+import { openKeySettings } from "./key-focus";
+
+export function KeysLink({ id, purpose }: { id: KeyId; purpose?: KeyId }) {
+ const { dispatch } = useStore();
+ if (typeof window !== "undefined" && window.ogb?.remoteClient?.active === true) return null;
+ return (
+ <button type="button" data-keys-link={purpose ?? id} onClick={() => dispatch(openKeySettings(id, purpose))}
+ className="cursor-pointer font-medium text-accent-text hover:underline">
+ {t("keys.openPage")}
+ </button>
+ );
+}
diff --git a/src/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.ts
new file mode 100644
index 0000000000..e90353b8bb
--- /dev/null
+++ b/src/components/keys/KeysPage.dom.test.ts
@@ -0,0 +1,171 @@
+// @vitest-environment happy-dom
+import { createElement, Fragment } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+
+const fx = vi.hoisted(() => ({
+ config: {} as Record<string, unknown>,
+ listeners: new Set<() => void>(),
+ api: vi.fn(),
+ dispatch: vi.fn(),
+}));
+vi.mock("@/state/store", async (original) => {
+ const actual = await original<typeof import("@/state/store")>();
+ const { useSyncExternalStore } = await import("react");
+ const subscribe = (listener: () => void) => { fx.listeners.add(listener); return () => { fx.listeners.delete(listener); }; };
+ return {
+ ...actual,
+ api: (...args: unknown[]) => fx.api(...args),
+ useStore: () => {
+ const config = useSyncExternalStore(subscribe, () => fx.config);
+ return { state: { ...actual.initialState, config, instances: [] }, dispatch: fx.dispatch };
+ },
+ };
+});
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("@/lib/live-call-media", () => ({ dismissLiveNotice: vi.fn() }));
+
+const { KeysPage } = await import("./KeysPage");
+const { LiveKeyNeeded } = await import("../LiveKeyNeeded");
+const { openKeySettings } = await import("./key-focus");
+
+let host: HTMLDivElement;
+let root: Root;
+
+function setConfig(config: Record<string, unknown>) {
+ fx.config = config;
+ for (const listener of Array.from(fx.listeners)) listener();
+}
+
+const render = (...children: Array<() => ReturnType<typeof createElement>>) =>
+ flushSync(() => root.render(createElement(Fragment, null, ...children.map((child) => child()))));
+const page = () => render(() => createElement(KeysPage, { key: "page" }));
+const row = (id: string) => host.querySelector<HTMLElement>(`[data-key-row="${id}"]`);
+const rowsShown = () => [...host.querySelectorAll<HTMLElement>("[data-key-row]")].filter((element) => !element.closest("[hidden]")).map((element) => element.dataset.keyRow);
+const section = (id: string) => host.querySelector<HTMLElement>(`[data-keys-section="${id}"]`)!;
+const expanded = (id: string) => section(id).querySelector("button[aria-expanded]")!.getAttribute("aria-expanded");
+
+function type(input: HTMLInputElement, value: string) {
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+function paste(input: HTMLInputElement, text: string) {
+ const event = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "clipboardData", { value: { getData: () => text } });
+ flushSync(() => input.dispatchEvent(event));
+}
+
+beforeEach(() => {
+ setLocale("en");
+ fx.api.mockReset();
+ fx.dispatch.mockReset();
+ fx.dispatch.mockImplementation((action: { type: string; config?: Record<string, unknown> }) => {
+ if (action.type === "configStatus") setConfig(action.config!);
+ });
+ fx.config = { composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" } };
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+describe("the keys page", () => {
+ it("groups the keys into plain sections, AI providers open first", () => {
+ page();
+ expect([...host.querySelectorAll<HTMLElement>("[data-keys-section]")].map((element) => element.dataset.keysSection))
+ .toEqual(["ai", "servers", "voice", "computers", "apps", "helpers"]);
+ expect(section("ai").textContent).toContain("AI providers");
+ expect(expanded("ai")).toBe("true");
+ expect(expanded("voice")).toBe("false");
+ expect(rowsShown()).toContain("openai");
+ expect(rowsShown()).not.toContain("elevenlabs");
+ });
+
+ it("opens a section that holds a saved key, and counts what is connected", () => {
+ setConfig({ ...fx.config, box: { configured: true, last4: "c3d4" } });
+ page();
+ expect(expanded("computers")).toBe("true");
+ expect(section("computers").textContent).toContain("1 connected");
+ });
+
+ it("filters rows live by name, purpose and section, and says so when nothing matches", () => {
+ page();
+ const search = host.querySelector<HTMLInputElement>("[data-keys-search]")!;
+ type(search, "fish");
+ expect(rowsShown()).toEqual(["fishAudio"]);
+ type(search, "Computers and browser");
+ expect(rowsShown()).toEqual(["box", "vps", "onePassword"]);
+ type(search, "research");
+ expect(rowsShown()).toEqual(["treg"]);
+ type(search, "zzz");
+ expect(rowsShown()).toEqual([]);
+ expect(host.querySelector("[data-keys-empty]")!.textContent).toBe("No keys match “zzz”.");
+ });
+
+ it("lands the live-call notice's button on the OpenAI row in Voice and calls, focused and lit", async () => {
+ render(() => createElement(LiveKeyNeeded, { key: "notice" }), () => createElement(KeysPage, { key: "page" }));
+ expect(expanded("voice")).toBe("false");
+ const button = [...host.querySelectorAll("button")].find((candidate) => candidate.textContent === "Open API keys")!;
+ flushSync(() => button.click());
+ expect(fx.dispatch).toHaveBeenCalledWith({ type: "toggleAppSettings", open: true, section: "connections" });
+ const live = () => row("liveCalls")!.querySelector<HTMLInputElement>("[data-key-input]")!;
+ await vi.waitFor(() => expect(document.activeElement).toBe(live()));
+ expect(expanded("voice")).toBe("true");
+ expect(row("liveCalls")!.hasAttribute("data-key-highlight")).toBe(true);
+ expect(live().getAttribute("aria-label")).toBe("OpenAI API key");
+ expect(row("liveCalls")!.textContent).toContain("Live calls use the same key as OpenAI's models");
+ });
+
+ it("clears a search that would hide the row a link asks for", async () => {
+ page();
+ type(host.querySelector<HTMLInputElement>("[data-keys-search]")!, "fish");
+ flushSync(() => { openKeySettings("box"); });
+ await vi.waitFor(() => expect(document.activeElement).toBe(row("box")!.querySelector("[data-key-input]")));
+ expect(host.querySelector<HTMLInputElement>("[data-keys-search]")!.value).toBe("");
+ });
+
+ it("warns, and saves nothing, when a pasted key looks like another provider's", () => {
+ page();
+ const input = row("openai")!.querySelector<HTMLInputElement>("[data-key-input]")!;
+ paste(input, " sk-ant-api03-abcdefghijklmnop\n");
+ expect(row("openai")!.textContent).toContain("That looks like the Anthropic API key, not this one.");
+ expect(input.value).toBe("sk-ant-api03-abcdefghijklmnop");
+ expect(fx.api).not.toHaveBeenCalled();
+ });
+
+ it("saves a pasted key, reads it back masked with a check, and keeps it in view when a later check rejects it", async () => {
+ fx.api.mockImplementation(async (path: string) => path === "/api/config"
+ ? { ...fx.config, openai: { configured: true, last4: "a1b2" } }
+ : { ok: false, reason: "rejected" });
+ page();
+ paste(row("openai")!.querySelector<HTMLInputElement>("[data-key-input]")!, "sk-proj-abcdefghijklmnopa1b2");
+ await vi.waitFor(() => expect(row("openai")!.textContent).toContain("Didn't work: The provider rejected this key."));
+ expect(fx.api.mock.calls.map(([path]) => path)).toEqual(["/api/config", "/api/keys/test"]);
+ expect(JSON.parse(fx.api.mock.calls[0]![1].body)).toEqual({ openai: { key: "sk-proj-abcdefghijklmnopa1b2" } });
+ const masked = row("openai")!.querySelector("[data-key-masked]")!;
+ expect(masked.textContent).toContain("••••••••a1b2");
+ expect(row("openai")!.querySelector("[data-key-input]")).toBeNull();
+ expect(row("openai")!.querySelector("[data-key-replace]")).not.toBeNull();
+ });
+
+ it("confirms a key the server checked on save as Connected", async () => {
+ fx.api.mockImplementation(async () => ({ ...fx.config, box: { configured: true, last4: "c3d4" } }));
+ setConfig({ ...fx.config });
+ page();
+ flushSync(() => section("computers").querySelector<HTMLButtonElement>("button[aria-expanded]")!.click());
+ const input = row("box")!.querySelector<HTMLInputElement>("[data-key-input]")!;
+ type(input, "boat_dummy_fixture_key_c3d4");
+ flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
+ await vi.waitFor(() => expect(row("box")!.querySelector("[data-key-masked]")?.textContent).toContain("••••••••c3d4"));
+ expect(row("box")!.textContent).toContain("Connected");
+ expect(fx.api).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsx
new file mode 100644
index 0000000000..7a671b47fe
--- /dev/null
+++ b/src/components/keys/KeysPage.tsx
@@ -0,0 +1,191 @@
+import { useEffect, useId, useRef, useState, type ReactNode } from "react";
+import { ChevronRight, Search } from "lucide-react";
+import { useStore, type ConfigStatus } from "@/state/store";
+import { cn } from "@/lib/cn";
+import { scrollParent, scrollWithin } from "@/lib/scroll-within";
+import { t } from "@/lib/i18n";
+import { LmStudioServer, OtherOpenAiCompatServers } from "../OpenAiCompatServers";
+import { KEY_CATALOG, KEY_SECTIONS, keyMatches, savedState, type KeyEntry, type KeyId, type KeySectionId } from "./key-catalog";
+import { finishKeyFocus, useKeyFocus, type KeyFocusRequest } from "./key-focus";
+import { AnthropicEveryClaudeBot, OpenAiCompatUrl, OpenCodeProviderKeys, VpsConnection } from "./KeyPanels";
+import { KEY_ROW, KeyRow, MaskedKey, RowHeading, type KeyStatus } from "./KeyRow";
+
+const CARD = "rounded-xl bg-card in-data-[settings-look=simple]:rounded-[12px] in-data-[settings-look=simple]:border-[0.5px] in-data-[settings-look=simple]:border-(--settings-edge) in-data-[settings-look=simple]:bg-menu";
+const HIGHLIGHT_MS = 1600;
+
+const PANELS: Partial<Record<KeyId, () => ReactNode>> = {
+ opencodeProviders: () => <OpenCodeProviderKeys />,
+ lmStudio: () => <LmStudioServer heading={false} />,
+ vps: () => <VpsConnection />,
+};
+
+const EXTRAS: Partial<Record<KeyId, () => ReactNode>> = {
+ anthropic: () => <AnthropicEveryClaudeBot />,
+ openaiCompat: () => <><OpenAiCompatUrl /><OtherOpenAiCompatServers /></>,
+};
+
+function connected(entry: KeyEntry, config: ConfigStatus | null | undefined): boolean {
+ if (entry.kind === "uses") return false;
+ const saved = savedState(entry, config);
+ return saved.configured || saved.included === true;
+}
+
+function PanelRow({ entry }: { entry: KeyEntry }) {
+ const { state } = useStore();
+ const titleId = useId();
+ const saved = savedState(entry, state.config);
+ const status: KeyStatus = saved.configured ? { tone: "ok", text: t("keys.connected") } : null;
+ return (
+ <div data-key-row={entry.id} role="group" aria-labelledby={titleId} className={KEY_ROW}>
+ <RowHeading entry={entry} status={status} titleId={titleId} />
+ <div className="flex flex-col gap-2 pl-8">{PANELS[entry.id]?.()}</div>
+ </div>
+ );
+}
+
+function ElsewhereRow({ entry }: { entry: KeyEntry }) {
+ const { state, dispatch } = useStore();
+ const titleId = useId();
+ const opens = entry.opens;
+ const saved = savedState(entry, state.config);
+ const status: KeyStatus = saved.configured ? { tone: "ok", text: t("keys.connected") } : null;
+ return (
+ <div data-key-row={entry.id} role="group" aria-labelledby={titleId} className={KEY_ROW}>
+ <RowHeading entry={entry} status={status} titleId={titleId} />
+ <div className="flex flex-col gap-2 pl-8">
+ {saved.configured && <div className="flex"><MaskedKey saved={saved} label={t(entry.labelKey)} /></div>}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ {entry.whereKey && <span className="min-w-0 flex-1 text-[12px] leading-4 text-ink-secondary">{t(entry.whereKey)}</span>}
+ {opens && (
+ <button type="button" data-key-open className="ui-button shrink-0" onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: opens })}>
+ {t("keys.row.open")}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function KeyCatalogRow({ entry }: { entry: KeyEntry }) {
+ if (entry.kind === "uses" && entry.uses) return <KeyRow id={entry.uses} row={entry.id} />;
+ if (entry.kind === "panel") return <PanelRow entry={entry} />;
+ if (entry.kind === "elsewhere") return <ElsewhereRow entry={entry} />;
+ return <KeyRow id={entry.id}>{EXTRAS[entry.id]?.()}</KeyRow>;
+}
+
+function KeySection({ id, rows, open, onToggle }: { id: KeySectionId; rows: KeyEntry[]; open: boolean; onToggle: () => void }) {
+ const { state } = useStore();
+ const section = KEY_SECTIONS.find((candidate) => candidate.id === id)!;
+ const headId = useId();
+ const bodyId = useId();
+ const count = rows.filter((entry) => connected(entry, state.config)).length;
+ return (
+ <section data-keys-section={id} aria-labelledby={headId} className={CARD}>
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={bodyId}
+ onClick={onToggle}
+ className="flex w-full cursor-pointer items-center gap-3 rounded-[inherit] px-4 py-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus/60"
+ >
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span id={headId} className="text-[14px] font-medium leading-5 text-ink">{t(section.titleKey)}</span>
+ <span className="text-[13px] leading-[18px] text-ink-secondary">{t(section.purposeKey)}</span>
+ </span>
+ {count > 0 && <span className="shrink-0 text-[12px] leading-4 text-ink-secondary">{t("keys.section.connected", { count })}</span>}
+ <ChevronRight size={14} aria-hidden="true" className={cn("shrink-0 text-ink-secondary transition-transform motion-reduce:transition-none", open && "rotate-90")} />
+ </button>
+ <div id={bodyId} hidden={!open} className="flex flex-col gap-0.5 border-t border-hairline/40 px-1 py-1.5 in-data-[settings-look=simple]:border-t-[0.5px] in-data-[settings-look=simple]:border-(--settings-edge)">
+ {rows.map((entry) => <KeyCatalogRow key={entry.id} entry={entry} />)}
+ </div>
+ </section>
+ );
+}
+
+function landOn(page: HTMLElement | null, request: KeyFocusRequest, section: KeySectionId): boolean {
+ const row = request.row ? page?.querySelector<HTMLElement>(`[data-key-row="${request.row}"]`) : page?.querySelector<HTMLElement>(`[data-keys-section="${section}"]`);
+ if (!row || row.closest("[hidden]")) return false;
+ const scroller = scrollParent(row);
+ if (scroller) scrollWithin(scroller, row, request.row ? "center" : "start", 16);
+ if (!request.row) return true;
+ row.querySelector<HTMLElement>("[data-key-input], [data-key-replace], [data-key-own], [data-key-open], input, button")?.focus({ preventScroll: true });
+ row.setAttribute("data-key-highlight", "");
+ window.setTimeout(() => row.removeAttribute("data-key-highlight"), HIGHLIGHT_MS);
+ return true;
+}
+
+export function KeysPage() {
+ const { state } = useStore();
+ const [query, setQuery] = useState("");
+ const [open, setOpen] = useState<ReadonlySet<KeySectionId>>(() => new Set(
+ KEY_SECTIONS.filter((section) => section.id === "ai" || KEY_CATALOG.some((entry) => entry.section === section.id && connected(entry, state.config)))
+ .map((section) => section.id),
+ ));
+ const pageRef = useRef<HTMLDivElement>(null);
+ const focus = useKeyFocus();
+ const q = query.trim().toLowerCase();
+
+ useEffect(() => {
+ if (!focus) return;
+ const section = KEY_CATALOG.find((entry) => entry.id === focus.row)?.section ?? "ai";
+ setQuery("");
+ setOpen((current) => current.has(section) ? current : new Set([...current, section]));
+ let frame = 0;
+ let tries = 0;
+ const attempt = () => {
+ if (landOn(pageRef.current, focus, section) || ++tries > 60) finishKeyFocus(focus);
+ else frame = window.requestAnimationFrame(attempt);
+ };
+ frame = window.requestAnimationFrame(attempt);
+ return () => window.cancelAnimationFrame(frame);
+ }, [focus]);
+
+ const rows = KEY_CATALOG.filter((entry) => keyMatches(entry, q));
+ const sections = KEY_SECTIONS.flatMap((section) => {
+ const own = rows.filter((entry) => entry.section === section.id);
+ return own.length > 0 ? [{ id: section.id, rows: own }] : [];
+ });
+
+ return (
+ <div ref={pageRef} data-keys-page className="flex flex-col gap-4">
+ <p className="text-[13px] leading-[18px] text-ink-secondary">{t("settings.connections.subtitle")}</p>
+ <div className="flex h-8 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] focus-within:ring-2 focus-within:ring-focus/60">
+ <Search size={15} aria-hidden="true" className="shrink-0 text-ink-secondary" />
+ <input
+ data-keys-search
+ type="text"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Escape" || !query) return;
+ event.preventDefault();
+ event.stopPropagation();
+ setQuery("");
+ }}
+ placeholder={t("keys.search.placeholder")}
+ aria-label={t("keys.search.aria")}
+ autoComplete="off"
+ spellCheck={false}
+ className="w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"
+ />
+ </div>
+ {sections.length === 0 ? (
+ <p data-keys-empty className="px-1 text-[13px] leading-[18px] text-ink-secondary">{t("keys.search.none", { query: query.trim() })}</p>
+ ) : sections.map(({ id, rows: sectionRows }) => (
+ <KeySection
+ key={id}
+ id={id}
+ rows={sectionRows}
+ open={q !== "" || open.has(id)}
+ onToggle={() => setOpen((current) => {
+ const next = new Set(current);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ })}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/src/components/keys/key-catalog.test.ts b/src/components/keys/key-catalog.test.ts
new file mode 100644
index 0000000000..9790c2864e
--- /dev/null
+++ b/src/components/keys/key-catalog.test.ts
@@ -0,0 +1,131 @@
+import { readFileSync } from "node:fs";
+import { beforeEach, describe, expect, it } from "vitest";
+import { setLocale, t } from "@/lib/i18n";
+import type { ConfigStatus } from "@/state/store";
+import { WORKSPACE_CREDENTIAL_ENV } from "../../../server/credential-env.ts";
+import { CREDENTIAL_TARGETS } from "../../../shared/credential-request";
+import { KEY_CATALOG, KEY_SECTIONS, keyEntry, keyForInstance, keyMatches, looksLikeOtherKey, savedState, type KeyId } from "./key-catalog";
+
+const NOT_A_PERSONS_KEY: Record<string, string> = {
+ OMB_ANTHROPIC_API_URL: "the address the Anthropic key goes to, set by a hosted install",
+ OMB_HOSTED_MODEL_TOKEN: "a hosted install's model token",
+ OMB_HOSTED_MODELS: "a hosted install's model list",
+ OMB_COMPOSIO_BROKER_TOKEN: "MausBot Cloud's connected-apps broker",
+ OMB_CLOUD_BOAT_TOKEN: "MausBot Cloud's included computers",
+ OMB_CLOUD_VOICE_TOKEN: "MausBot Cloud's included voice",
+ OMB_CLOUD_DECIDER_TOKEN: "MausBot Cloud's included decisions",
+ OMB_CLOUD_AI_TOKEN: "MausBot Cloud's included AI",
+ OMB_CLOUD_X_TOKEN: "MausBot Cloud's included X research",
+ OMB_CLOUD_CONNECTED_APPS_GRANT: "MausBot Cloud's connected apps",
+ OMB_BROWSER_CONNECTION: "the app's own browser, not a credential",
+ OMB_USER_DATA: "the app's own data folder, not a credential",
+ OMB_BOAT_API: "the Boat address, not a credential",
+};
+
+const electron = (file: string) => readFileSync(new URL(`../../../electron/${file}`, import.meta.url), "utf8");
+
+beforeEach(() => setLocale("en"));
+
+describe("every credential has one home on the keys page", () => {
+ it("files each workspace credential under exactly one row, in one section", () => {
+ for (const env of WORKSPACE_CREDENTIAL_ENV) {
+ const rows = KEY_CATALOG.filter((entry) => entry.env.includes(env)).map((entry) => entry.id);
+ if (env in NOT_A_PERSONS_KEY) expect(rows, env).toEqual([]);
+ else expect(rows, env).toHaveLength(1);
+ }
+ for (const entry of KEY_CATALOG) expect(KEY_SECTIONS.map((section) => section.id)).toContain(entry.section);
+ expect(new Set(KEY_CATALOG.map((entry) => entry.id)).size).toBe(KEY_CATALOG.length);
+ });
+
+ it("covers every key the desktop keeps in its encrypted store, saving the ones with a row through that store", () => {
+ const stored = [...electron("workspace-credentials.mjs").matchAll(/name: "(\w+)", env: "(\w+)"/g)].map(([, name, env]) => ({ name: name!, env: env! }));
+ const patched = [...electron("credential-patch.mjs").matchAll(/^ {2}(\w+): \(value\) =>/gm)].map(([, name]) => name!);
+ expect(stored.length).toBeGreaterThan(10);
+ for (const { name, env } of stored) {
+ const home = KEY_CATALOG.find((entry) => entry.env.includes(env));
+ expect(home, name).toBeDefined();
+ if (home?.target) expect(home.target.slot, name).toBe(name);
+ }
+ const homed = (name: string) => KEY_CATALOG.some((entry) => entry.target?.slot === name)
+ || stored.some((row) => row.name === name && KEY_CATALOG.some((entry) => entry.env.includes(row.env)));
+ for (const name of patched) expect(homed(name), name).toBe(true);
+ });
+
+ it("covers every credential a bot can ask for in a chat", () => {
+ const homes: Record<keyof typeof CREDENTIAL_TARGETS, KeyId> = {
+ xaiApiKey: "xai", boxToken: "box", opencodeGoApiKey: "opencodeGo", ttsKey: "elevenlabs", fishAudioKey: "fishAudio",
+ openaiImageApiKey: "imageOpenai", onePasswordToken: "onePassword",
+ };
+ expect(Object.keys(homes).sort()).toEqual(Object.keys(CREDENTIAL_TARGETS).sort());
+ for (const [name, id] of Object.entries(homes)) {
+ const entry = keyEntry(id);
+ if (entry.target) expect(entry.target.slot, name).toBe(name);
+ else expect(entry.opens, name).toBe("logins");
+ }
+ });
+
+ it("names each section plainly and says what each row is for in one line", () => {
+ expect(KEY_SECTIONS.map((section) => t(section.titleKey))).toEqual([
+ "AI providers", "Your own model servers", "Voice and calls", "Computers and browser", "Apps and tools", "Helpers and pictures",
+ ]);
+ for (const entry of KEY_CATALOG) {
+ const purpose = t(entry.purposeKey);
+ expect(purpose, entry.id).not.toBe(entry.purposeKey);
+ expect(purpose, entry.id).not.toContain("\n");
+ expect(purpose.length, entry.id).toBeLessThanOrEqual(80);
+ }
+ for (const section of KEY_SECTIONS) expect(KEY_CATALOG.some((entry) => entry.section === section.id), section.id).toBe(true);
+ });
+
+ it("keeps the OpenAI key once: live calls point at it instead of holding a copy", () => {
+ const live = keyEntry("liveCalls");
+ expect(live).toMatchObject({ section: "voice", kind: "uses", uses: "openai" });
+ expect(live.target).toBeUndefined();
+ expect(live.env).toEqual([]);
+ const config = { openai: { configured: true, last4: "a1b2" } } as ConfigStatus;
+ expect(savedState(live, config)).toEqual({ configured: true, last4: "a1b2" });
+ expect(t(live.labelKey)).toBe("OpenAI key");
+ expect(t(keyEntry("openai").labelKey)).toBe("OpenAI API key");
+ });
+});
+
+describe("searching the keys", () => {
+ const found = (query: string) => KEY_CATALOG.filter((entry) => keyMatches(entry, query)).map((entry) => entry.id);
+
+ it("matches a provider's name, what the key is for, and its section's title", () => {
+ expect(found("fish")).toEqual(["fishAudio"]);
+ expect(found("ElevenLabs")).toEqual(["elevenlabs"]);
+ expect(found("Computers and browser")).toEqual(["box", "vps", "onePassword"]);
+ expect(found("voice")).toEqual(expect.arrayContaining(["liveCalls", "liveKey", "elevenlabs", "fishAudio"]));
+ expect(found("openai")).toEqual(expect.arrayContaining(["openai", "liveCalls", "liveKey", "imageOpenai"]));
+ expect(found("gmail")).toEqual(["composio"]);
+ expect(found("no such key anywhere")).toEqual([]);
+ });
+});
+
+describe("a key pasted into the wrong row", () => {
+ it("names the provider the key belongs to", () => {
+ expect(looksLikeOtherKey(keyEntry("openai"), "sk-ant-api03-abcdefghijkl")?.id).toBe("anthropic");
+ expect(looksLikeOtherKey(keyEntry("box"), "sk-proj-abcdefghijkl")?.id).toBe("openai");
+ expect(looksLikeOtherKey(keyEntry("liveCalls"), "gsk_abcdefghijkl")?.id).toBe("groq");
+ expect(looksLikeOtherKey(keyEntry("composio"), "boat_abcdefghijkl")?.id).toBe("box");
+ });
+
+ it("stays quiet for the row's own key and for keys with no telling shape", () => {
+ expect(looksLikeOtherKey(keyEntry("openai"), "sk-proj-abcdefghijkl")).toBeNull();
+ expect(looksLikeOtherKey(keyEntry("imageOpenai"), "sk-proj-abcdefghijkl")).toBeNull();
+ expect(looksLikeOtherKey(keyEntry("deepseek"), "sk-plain-legacy-shaped-key")).toBeNull();
+ expect(looksLikeOtherKey(keyEntry("mistral"), "a-key-with-no-prefix")).toBeNull();
+ expect(looksLikeOtherKey(keyEntry("openai"), "")).toBeNull();
+ });
+});
+
+describe("engines that run on a key", () => {
+ it("find the row that holds their key", () => {
+ expect(keyForInstance("claudeApi")).toBe("anthropic");
+ expect(keyForInstance("xaiApi")).toBe("xai");
+ expect(keyForInstance("deepseek")).toBe("deepseek");
+ expect(keyForInstance("claude")).toBeUndefined();
+ expect(keyForInstance(undefined)).toBeUndefined();
+ });
+});
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
new file mode 100644
index 0000000000..ea0d4da2ed
--- /dev/null
+++ b/src/components/keys/key-catalog.ts
@@ -0,0 +1,219 @@
+import { AudioLines, Blocks, Fingerprint, Image, LockKeyhole, Monitor, Phone, Search, Server, Zap, type LucideIcon } from "lucide-react";
+import type { AppSettingsSection, ConfigStatus } from "@/state/store";
+import type { SavedKey } from "@/state/config-status";
+import type { KeyProvider } from "@/lib/analytics-allowlist";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import type { ProviderIconPreset } from "../../../shared/provider-icon";
+
+export type KeySectionId = "ai" | "servers" | "voice" | "computers" | "apps" | "helpers";
+
+export const KEY_SECTIONS: ReadonlyArray<{ id: KeySectionId; titleKey: LocaleKey; purposeKey: LocaleKey }> = [
+ { id: "ai", titleKey: "keys.section.ai", purposeKey: "keys.section.ai.purpose" },
+ { id: "servers", titleKey: "keys.section.servers", purposeKey: "keys.section.servers.purpose" },
+ { id: "voice", titleKey: "keys.section.voice", purposeKey: "keys.section.voice.purpose" },
+ { id: "computers", titleKey: "keys.section.computers", purposeKey: "keys.section.computers.purpose" },
+ { id: "apps", titleKey: "keys.section.apps", purposeKey: "keys.section.apps.purpose" },
+ { id: "helpers", titleKey: "keys.section.helpers", purposeKey: "keys.section.helpers.purpose" },
+];
+
+export type TestableProvider = "anthropic" | "openai" | "openrouter" | "openaiCompat" | "xai" | "mistral" | "cerebras" | "groq" | "meta" | "treg";
+
+export type DesktopSlot = Parameters<NonNullable<NonNullable<Window["ogb"]>["setCredential"]>>[0];
+
+export interface SavedState { configured: boolean; last4?: string; included?: boolean }
+
+export interface KeyTarget {
+ patch: (value: string, firstKey: boolean) => Record<string, unknown>;
+ slot?: DesktopSlot;
+ saved: (config: ConfigStatus) => SavedState;
+ placeholder: string;
+ placeholderKey?: LocaleKey;
+ href?: string;
+ test?: TestableProvider;
+ verifiedOnSave?: boolean;
+ analytics: KeyProvider;
+ shape?: RegExp;
+ warningKey?: LocaleKey;
+ noteKey?: LocaleKey;
+}
+
+export type KeyId =
+ | "openai" | "anthropic" | "xai" | "openrouter" | "mistral" | "cerebras" | "groq" | "meta" | "deepseek" | "opencodeGo" | "opencodeProviders"
+ | "lmStudio" | "openaiCompat" | "liveCalls" | "liveKey" | "elevenlabs" | "fishAudio" | "box" | "vps" | "onePassword" | "composio" | "treg"
+ | "jev" | "openrouterHelper" | "workersAi" | "imageOpenai" | "imageCustom";
+
+export type KeyMark = { driverKind: string; preset?: ProviderIconPreset } | { icon: LucideIcon };
+
+export interface KeyEntry {
+ id: KeyId;
+ section: KeySectionId;
+ labelKey: LocaleKey;
+ purposeKey: LocaleKey;
+ name: string;
+ env: readonly string[];
+ words: readonly string[];
+ mark: KeyMark;
+ kind: "key" | "uses" | "panel" | "elsewhere";
+ target?: KeyTarget;
+ uses?: KeyId;
+ opens?: AppSettingsSection;
+ whereKey?: LocaleKey;
+ status?: (config: ConfigStatus) => SavedState;
+}
+
+function flag(saved: SavedKey | undefined): SavedState {
+ return { configured: saved?.configured === true, ...(saved?.configured && saved.last4 ? { last4: saved.last4 } : {}) };
+}
+
+type TopLevelKey = "openai" | "openrouter" | "xai" | "mistral" | "cerebras" | "groq" | "meta" | "deepseek" | "treg";
+
+function providerKey(name: TopLevelKey, rest: Omit<KeyTarget, "patch" | "saved">): KeyTarget {
+ return { patch: (value) => ({ [name]: { key: value } }), saved: (config) => flag(config[name]), ...rest };
+}
+
+const OPENAI_SHAPE = /^sk-(proj|svcacct|admin)-/;
+const provider = (driverKind: string, preset?: ProviderIconPreset): KeyMark => ({ driverKind, ...(preset ? { preset } : {}) });
+
+export const KEY_CATALOG: readonly KeyEntry[] = [
+ { id: "openai", section: "ai", labelKey: "keys.openai.label", purposeKey: "keys.purpose.openai", name: "OpenAI", env: ["OMB_OPENAI_API_KEY"],
+ words: ["openai", "chatgpt", "gpt", "live calls"], mark: provider("openai-compat", "openai"), kind: "key",
+ target: providerKey("openai", { placeholder: "sk-…", href: "https://platform.openai.com/api-keys", test: "openai", analytics: "openai", shape: OPENAI_SHAPE, noteKey: "keys.openai.note" }) },
+ { id: "anthropic", section: "ai", labelKey: "keys.anthropic.label", purposeKey: "keys.purpose.anthropic", name: "Anthropic", env: ["OMB_ANTHROPIC_API_KEY"],
+ words: ["anthropic", "claude"], mark: provider("claudeAgent", "anthropic"), kind: "key",
+ target: { patch: (value, firstKey) => ({ anthropic: { key: value, ...(firstKey && value ? { everyClaudeBot: false } : {}) } }), saved: (config) => flag(config.anthropic),
+ placeholder: "sk-ant-…", href: "https://console.anthropic.com/settings/keys", test: "anthropic", analytics: "anthropic", shape: /^sk-ant-/ } },
+ { id: "xai", section: "ai", labelKey: "keys.xai.label", purposeKey: "keys.purpose.xai", name: "xAI", env: ["XAI_API_KEY"],
+ words: ["xai", "grok", "pictures", "images"], mark: provider("grok", "xai"), kind: "key",
+ target: providerKey("xai", { slot: "xaiApiKey", placeholder: "xai-…", href: "https://console.x.ai", test: "xai", analytics: "xai", shape: /^xai-/ }) },
+ { id: "openrouter", section: "ai", labelKey: "keys.openrouter.label", purposeKey: "keys.purpose.openrouter", name: "OpenRouter", env: ["OMB_OPENROUTER_API_KEY"],
+ words: ["openrouter", "router", "models"], mark: provider("openai-compat", "openrouter"), kind: "key",
+ target: providerKey("openrouter", { placeholder: "sk-or-v1-…", href: "https://openrouter.ai/keys", test: "openrouter", analytics: "openrouter", shape: /^sk-or-/ }) },
+ { id: "mistral", section: "ai", labelKey: "keys.mistral.label", purposeKey: "keys.purpose.mistral", name: "Mistral", env: ["MISTRAL_API_KEY"],
+ words: ["mistral"], mark: provider("mistral", "mistral"), kind: "key",
+ target: providerKey("mistral", { placeholder: "…", placeholderKey: "keys.mistral.placeholder", href: "https://console.mistral.ai/api-keys", test: "mistral", analytics: "mistral" }) },
+ { id: "cerebras", section: "ai", labelKey: "keys.cerebras.label", purposeKey: "keys.purpose.cerebras", name: "Cerebras", env: ["CEREBRAS_API_KEY"],
+ words: ["cerebras", "fast"], mark: provider("cerebras"), kind: "key",
+ target: providerKey("cerebras", { placeholder: "csk-…", href: "https://cloud.cerebras.ai/", test: "cerebras", analytics: "cerebras", shape: /^csk-/ }) },
+ { id: "groq", section: "ai", labelKey: "keys.groq.label", purposeKey: "keys.purpose.groq", name: "Groq", env: ["OMB_GROQ_API_KEY"],
+ words: ["groq", "fast"], mark: provider("groq"), kind: "key",
+ target: providerKey("groq", { placeholder: "gsk_…", href: "https://console.groq.com/keys", test: "groq", analytics: "groq", shape: /^gsk_/ }) },
+ { id: "meta", section: "ai", labelKey: "keys.meta.label", purposeKey: "keys.purpose.meta", name: "Meta", env: ["OMB_META_API_KEY"],
+ words: ["meta", "muse", "llama"], mark: provider("meta", "meta"), kind: "key",
+ target: providerKey("meta", { placeholder: "LLM|…", href: "https://dev.meta.ai/docs/authentication", test: "meta", analytics: "meta", shape: /^LLM\|/ }) },
+ { id: "deepseek", section: "ai", labelKey: "keys.deepseek.label", purposeKey: "keys.purpose.deepseek", name: "DeepSeek", env: ["OMB_DEEPSEEK_API_KEY"],
+ words: ["deepseek", "dsh", "harness"], mark: provider("deepseekAgent", "deepseek"), kind: "key",
+ target: providerKey("deepseek", { placeholder: "sk-…", href: "https://platform.deepseek.com/api_keys", analytics: "deepseek" }) },
+ { id: "opencodeGo", section: "ai", labelKey: "keys.opencode.label", purposeKey: "keys.purpose.opencodeGo", name: "OpenCode", env: ["OPENCODE_API_KEY"],
+ words: ["opencode", "zen", "go"], mark: provider("opencodeGo"), kind: "key",
+ target: { patch: (value) => ({ opencodeGo: { apiKey: value } }), slot: "opencodeGoApiKey", saved: (config) => flag(config.opencodeGo),
+ placeholder: "…", placeholderKey: "keys.opencode.placeholder", href: "https://opencode.ai/docs/providers/", analytics: "opencode_go" } },
+ { id: "opencodeProviders", section: "ai", labelKey: "keys.opencode.otherProviders.title", purposeKey: "keys.purpose.opencodeProviders", name: "OpenCode", env: [],
+ words: ["opencode", "venice", "providers", "provider keys"], mark: provider("opencodeGo"), kind: "panel",
+ status: (config) => ({ configured: (config.opencodeGo?.providerKeys?.length ?? 0) > 0 }) },
+ { id: "lmStudio", section: "servers", labelKey: "lmStudio.title", purposeKey: "keys.purpose.lmStudio", name: "LM Studio", env: [],
+ words: ["lm studio", "lmstudio", "llm studio", "local", "bionic"], mark: { icon: Server }, kind: "panel" },
+ { id: "openaiCompat", section: "servers", labelKey: "keys.openaiCompat.label", purposeKey: "keys.purpose.openaiCompat", name: "OpenAI-compatible", env: ["OPENAI_COMPAT_API_KEY", "OPENAI_COMPAT_URL"],
+ words: ["openai-compatible", "openai compatible", "ollama", "together", "base url", "server", "endpoint"], mark: { icon: Server }, kind: "key",
+ target: { patch: (value) => ({ openaiCompat: { key: value } }), saved: (config) => flag(config.openaiCompat), placeholder: "…", placeholderKey: "keys.openaiCompat.placeholder",
+ href: "https://platform.openai.com/docs/api-reference", test: "openaiCompat", analytics: "openai_compat" } },
+ { id: "liveCalls", section: "voice", labelKey: "call.live.key", purposeKey: "keys.purpose.liveCalls", name: "OpenAI", env: [],
+ words: ["openai", "live calls", "calls", "voice", "talk", "gpt-live"], mark: { icon: Phone }, kind: "uses", uses: "openai" },
+ { id: "liveKey", section: "voice", labelKey: "keys.label.liveKey", purposeKey: "keys.purpose.liveKey", name: "OpenAI", env: ["OMB_OPENAI_LIVE_KEY"],
+ words: ["openai", "live calls", "calls", "voice", "gpt-live"], mark: { icon: Phone }, kind: "key",
+ target: { patch: (value) => ({ live: { key: value } }), slot: "openaiLiveKey",
+ saved: (config) => flag(config.savedKeys?.openaiLiveKey ?? { configured: config.live?.keySource === "live" }),
+ placeholder: "sk-…", href: "https://platform.openai.com/api-keys", analytics: "openai_live", shape: OPENAI_SHAPE } },
+ { id: "elevenlabs", section: "voice", labelKey: "keys.label.elevenlabs", purposeKey: "keys.purpose.elevenlabs", name: "ElevenLabs", env: ["OMB_TTS_KEY"],
+ words: ["elevenlabs", "eleven labs", "voice", "voices", "speech", "tts"], mark: { icon: AudioLines }, kind: "key",
+ target: { patch: (value) => ({ tts: { key: value } }), slot: "ttsKey", verifiedOnSave: true,
+ saved: (config) => ({ ...flag(config.savedKeys?.ttsKey ?? { configured: config.tts?.provider === "elevenlabs" && config.tts.configured && !config.tts.included }),
+ ...(config.tts?.included ? { included: true } : {}) }),
+ placeholder: "sk_…", href: "https://elevenlabs.io/app/settings/api-keys", analytics: "elevenlabs", shape: /^sk_/ } },
+ { id: "fishAudio", section: "voice", labelKey: "keys.label.fishAudio", purposeKey: "keys.purpose.fishAudio", name: "Fish Audio", env: ["OMB_FISH_AUDIO_API_KEY"],
+ words: ["fish", "fish audio", "voice", "voices", "speech", "tts"], mark: { icon: AudioLines }, kind: "key",
+ target: { patch: (value) => ({ tts: { fishKey: value } }), slot: "fishAudioKey", verifiedOnSave: true,
+ saved: (config) => flag(config.savedKeys?.fishAudioKey ?? { configured: config.tts?.provider === "fish" && config.tts.configured }),
+ placeholder: "…", placeholderKey: "voice.fish.keyPlaceholder", href: "https://fish.audio/app/api-keys/", analytics: "fish_audio" } },
+ { id: "box", section: "computers", labelKey: "keys.boat.label", purposeKey: "keys.purpose.box", name: "boat.dev", env: ["BOX_TOKEN"],
+ words: ["boat", "box", "cloud desktop", "cloud computer", "computer", "sandbox"], mark: { icon: Monitor }, kind: "key",
+ target: { patch: (value) => ({ box: { token: value } }), slot: "boxToken", verifiedOnSave: true,
+ saved: (config) => ({ ...flag(config.box?.included ? undefined : config.box), ...(config.box?.included ? { included: true } : {}) }),
+ placeholder: "boat_…", href: "https://docs.boat.dev/api-keys", analytics: "boat", shape: /^(boat|box)_/, warningKey: "keys.boat.warning" } },
+ { id: "vps", section: "computers", labelKey: "keys.vps.label", purposeKey: "keys.purpose.vps", name: "VPS", env: [],
+ words: ["vps", "ssh", "server", "self-hosted", "computer", "docker"], mark: { icon: Server }, kind: "panel",
+ status: (config) => ({ configured: config.vps?.configured === true }) },
+ { id: "onePassword", section: "computers", labelKey: "settings.logins.onePassword.title", purposeKey: "keys.purpose.onePassword", name: "1Password", env: [],
+ words: ["1password", "one password", "logins", "passwords", "vault", "service account"], mark: { icon: LockKeyhole }, kind: "elsewhere",
+ opens: "logins", whereKey: "keys.where.logins" },
+ { id: "composio", section: "apps", labelKey: "keys.composio.label", purposeKey: "keys.purpose.composio", name: "Composio", env: ["COMPOSIO_API_KEY"],
+ words: ["composio", "connected apps", "apps", "gmail", "slack", "github", "notion", "self-host"], mark: { icon: Blocks }, kind: "key",
+ target: { patch: (value) => ({ composio: { apiKey: value } }), slot: "composioApiKey", verifiedOnSave: true,
+ saved: (config) => ({ ...flag((config.composio?.mode ?? "self-hosted") === "self-hosted" ? config.composio : undefined),
+ ...(config.composio?.mode === "managed" ? { included: true } : {}) }),
+ placeholder: "ak_…", href: "https://dashboard.composio.dev", analytics: "composio", shape: /^ak_/ } },
+ { id: "treg", section: "apps", labelKey: "keys.treg.label", purposeKey: "keys.purpose.treg", name: "treg", env: ["OMB_TREG_KEY"],
+ words: ["treg", "research", "x", "twitter", "companies", "people", "funding", "news"], mark: { icon: Search }, kind: "key",
+ target: { ...providerKey("treg", { slot: "tregApiKey", placeholder: "…", placeholderKey: "keys.treg.placeholder", href: "https://treg.to", test: "treg", analytics: "treg" }),
+ saved: (config) => ({ ...flag(config.treg), ...(config.xResearch?.included && !config.treg?.configured ? { included: true } : {}) }) } },
+ { id: "jev", section: "helpers", labelKey: "decider.key.label", purposeKey: "keys.purpose.jev", name: "Jev", env: ["OMB_JEV_API_KEY"],
+ words: ["jev", "typesafe", "decisions", "extraction", "helper", "rooms"], mark: { icon: Zap }, kind: "key",
+ target: { patch: (value) => ({ decider: { key: value } }), slot: "jevApiKey", verifiedOnSave: true,
+ saved: (config) => ({ ...flag(config.savedKeys?.jevApiKey ?? { configured: config.helpers?.own.jev === true }), ...(config.decider?.included ? { included: true } : {}) }),
+ placeholder: "…", placeholderKey: "decider.key.placeholder", href: "https://typesafe.ai", analytics: "jev" } },
+ { id: "openrouterHelper", section: "helpers", labelKey: "keys.label.openrouterHelper", purposeKey: "keys.purpose.openrouterHelper", name: "OpenRouter", env: ["OMB_OPENROUTER_DECIDER_KEY"],
+ words: ["openrouter", "decisions", "helper"], mark: provider("openai-compat", "openrouter"), kind: "key",
+ target: { patch: (value) => ({ decider: { openrouterKey: value } }), slot: "openrouterDeciderKey", verifiedOnSave: true,
+ saved: (config) => flag(config.savedKeys?.openrouterDeciderKey ?? { configured: config.helpers?.own.openrouter === true }),
+ placeholder: "sk-or-v1-…", href: "https://openrouter.ai/keys", analytics: "openrouter_decider", shape: /^sk-or-/ } },
+ { id: "workersAi", section: "helpers", labelKey: "decider.workersAi.title", purposeKey: "keys.purpose.workersAi", name: "Cloudflare", env: ["OMB_WORKERS_AI_TOKEN"],
+ words: ["cloudflare", "workers ai", "clef", "clairic", "decisions", "helper"], mark: { icon: Zap }, kind: "elsewhere",
+ opens: "decisionModel", whereKey: "keys.where.decisions",
+ status: (config) => flag(config.savedKeys?.workersAiToken ?? { configured: config.helpers?.own.workersAi === true }) },
+ { id: "imageOpenai", section: "helpers", labelKey: "keys.label.imageOpenai", purposeKey: "keys.purpose.imageOpenai", name: "OpenAI", env: ["OMB_OPENAI_IMAGE_KEY"],
+ words: ["openai", "image", "images", "pictures", "avatar", "gpt image"], mark: { icon: Image }, kind: "key",
+ target: { patch: (value) => ({ imageGen: { key: value } }), slot: "openaiImageApiKey",
+ saved: (config) => flag(config.savedKeys?.openaiImageApiKey ?? { configured: config.imageGen?.openaiConfigured === true }),
+ placeholder: "sk-…", href: "https://platform.openai.com/api-keys", analytics: "openai_image", shape: OPENAI_SHAPE } },
+ { id: "imageCustom", section: "helpers", labelKey: "keys.label.imageCustom", purposeKey: "keys.purpose.imageCustom", name: "Custom", env: ["OMB_CUSTOM_IMAGE_KEY"],
+ words: ["image", "images", "pictures", "avatar", "custom"], mark: { icon: Fingerprint }, kind: "elsewhere", whereKey: "keys.where.pictures",
+ status: (config) => flag(config.savedKeys?.customImageApiKey ?? { configured: config.imageGen?.customKeyConfigured === true }) },
+];
+
+export function keyEntry(id: KeyId): KeyEntry {
+ const entry = KEY_CATALOG.find((candidate) => candidate.id === id);
+ if (!entry) throw new Error(`no key ${id}`);
+ return entry;
+}
+
+export function keySection(entry: KeyEntry) {
+ return KEY_SECTIONS.find((section) => section.id === entry.section)!;
+}
+
+export function savedState(entry: KeyEntry, config: ConfigStatus | null | undefined): SavedState {
+ if (!config) return { configured: false };
+ if (entry.uses) return savedState(keyEntry(entry.uses), config);
+ return entry.target?.saved(config) ?? entry.status?.(config) ?? { configured: false };
+}
+
+export function keyMatches(entry: KeyEntry, query: string): boolean {
+ const q = query.trim().toLowerCase();
+ if (!q) return true;
+ return [t(entry.labelKey), t(entry.purposeKey), t(keySection(entry).titleKey), entry.name, ...entry.words].some((part) => part.toLowerCase().includes(q));
+}
+
+export function looksLikeOtherKey(entry: KeyEntry, value: string): KeyEntry | null {
+ const key = value.trim();
+ const own = entry.uses ? keyEntry(entry.uses) : entry;
+ if (!key || own.target?.shape?.test(key)) return null;
+ return KEY_CATALOG.find((other) => other.name !== own.name && other.target?.shape?.test(key)) ?? null;
+}
+
+const INSTANCE_KEYS: Readonly<Record<string, KeyId>> = {
+ openai: "openai", claudeApi: "anthropic", xaiApi: "xai", grok: "xai", openrouter: "openrouter", mistral: "mistral", cerebras: "cerebras",
+ groq: "groq", meta: "meta", deepseek: "deepseek", opencodeGo: "opencodeGo", openaiCompat: "openaiCompat",
+};
+
+export function keyForInstance(instanceId: string | undefined): KeyId | undefined {
+ return instanceId ? INSTANCE_KEYS[instanceId] : undefined;
+}
diff --git a/src/components/keys/key-focus.ts b/src/components/keys/key-focus.ts
new file mode 100644
index 0000000000..c2d424033c
--- /dev/null
+++ b/src/components/keys/key-focus.ts
@@ -0,0 +1,42 @@
+import { useSyncExternalStore } from "react";
+import type { Action } from "@/state/store";
+import type { KeyId } from "./key-catalog";
+
+/** A named open of the keys page: `row` is where it lands, the key's own row or a row in another section that uses it.
+ * Every request is a new object, so following the same link again lands there again. */
+export interface KeyFocusRequest { id?: KeyId; row?: KeyId; nonce: number }
+
+const OPEN_KEYS = { type: "toggleAppSettings", open: true, section: "connections" } as const satisfies Action;
+
+let latest: KeyFocusRequest | null = null;
+let nonce = 0;
+const watchers = new Set<() => void>();
+
+function publish(next: KeyFocusRequest | null) {
+ latest = next;
+ for (const watch of Array.from(watchers)) watch();
+}
+
+/** The action that opens Settings on the keys page, at the row for `id` (or, with `purpose`, the row of that name that
+ * uses the key): its section opens, the row scrolls into view, its field takes focus and the row lights up briefly.
+ * With no key it opens the page at its first section. */
+export function openKeySettings(id?: KeyId, purpose?: KeyId): typeof OPEN_KEYS {
+ nonce += 1;
+ publish(id ? { id, row: purpose ?? id, nonce } : { nonce });
+ return OPEN_KEYS;
+}
+
+export function finishKeyFocus(request: KeyFocusRequest) {
+ if (latest?.nonce === request.nonce) publish(null);
+}
+
+function subscribe(watch: () => void) {
+ watchers.add(watch);
+ return () => { watchers.delete(watch); };
+}
+
+const snapshot = () => latest;
+
+export function useKeyFocus(): KeyFocusRequest | null {
+ return useSyncExternalStore(subscribe, snapshot, snapshot);
+}
diff --git a/src/components/keys/key-save.ts b/src/components/keys/key-save.ts
new file mode 100644
index 0000000000..f0db6763d2
--- /dev/null
+++ b/src/components/keys/key-save.ts
@@ -0,0 +1,56 @@
+// Security: secrets are write-only; GET /api/config returns configured flags and, for admins, the last four characters.
+import { api, type ConfigStatus } from "@/state/store";
+import { t } from "@/lib/i18n";
+import { keyTestResult } from "@/lib/product-events";
+import type { KeyResult } from "@/lib/analytics-allowlist";
+import { keyEntry, type KeyId, type KeyTarget, type TestableProvider } from "./key-catalog";
+
+/** Saves one credential where this app keeps it ("" removes it): the desktop's encrypted store when the key has a slot
+ * there, so Remove also clears the stored copy its boot migration made, else the server's own config, which on a Cloud
+ * home stays outside every bot's box. */
+export function saveKey(target: KeyTarget, value: string, firstKey: boolean): Promise<ConfigStatus> {
+ return window.ogb?.setCredential && target.slot
+ ? window.ogb.setCredential(target.slot, value)
+ : api("/api/config", { method: "PUT", body: JSON.stringify(target.patch(value, firstKey)) });
+}
+
+export function saveCredential(id: KeyId, value: string, firstKey: boolean): Promise<ConfigStatus> {
+ const target = keyEntry(id).target;
+ if (!target) return Promise.reject(new Error(`${id} has no key of its own`));
+ return saveKey(target, value, firstKey);
+}
+
+export function looksLikeKey(value: string): boolean {
+ return value.length > 0 && !/\s/.test(value);
+}
+
+export function cleanKey(text: string): string {
+ const trimmed = text.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
+ const quoted = /^(["'`])(.*)\1$/s.exec(trimmed);
+ return (quoted ? quoted[2]! : trimmed).trim();
+}
+
+/** "treg is working ✓" with the team's balance, or the exact problem the server's check named. */
+export function tregVerdict(result: { ok?: unknown; balanceUsd?: unknown; message?: unknown }): string {
+ if (result.ok !== true) return typeof result.message === "string" && result.message ? result.message : t("keys.testUnexpected", { status: "?" });
+ const balance = typeof result.balanceUsd === "number" ? ` ${t("keys.treg.balance", { balance: `$${result.balanceUsd.toFixed(2)}` })}` : "";
+ return `${t("keys.treg.working")}${balance}`;
+}
+
+export interface KeyCheck { result: KeyResult; ok: boolean; text: string }
+
+export async function checkKey(provider: TestableProvider): Promise<KeyCheck> {
+ const answer = await api("/api/keys/test", { method: "POST", body: JSON.stringify({ provider }) });
+ const result = keyTestResult(answer);
+ if (answer.check === "treg") return { result, ok: answer.ok === true, text: tregVerdict(answer) };
+ if (!answer.ok) {
+ const text = answer.reason === "rejected" ? t("keys.testRejected")
+ : answer.reason === "unreachable" ? t("keys.testUnreachable")
+ : t("keys.testUnexpected", { status: String(answer.status ?? "?") });
+ return { result, ok: false, text };
+ }
+ const outcome = answer.check === "authentication"
+ ? answer.freeTier === true ? `${t("keys.testAuthenticated")}\n${t("keys.testFreeTier")}` : t("keys.testAuthenticated")
+ : answer.models?.length ? t("keys.testCatalog", { models: answer.models.join(", ") }) : t("keys.testCatalogNoModels");
+ return { result, ok: true, text: `${t("keys.testSaved")} ${outcome}` };
+}
diff --git a/src/lib/analytics-allowlist.test.ts b/src/lib/analytics-allowlist.test.ts
index 716f7b1b16..0f7435a413 100644
--- a/src/lib/analytics-allowlist.test.ts
+++ b/src/lib/analytics-allowlist.test.ts
@@ -1,13 +1,13 @@
import { describe, expect, it } from "vitest";
-import type { ConfigSection } from "@/components/ApiKeys";
+import { KEY_CATALOG } from "@/components/keys/key-catalog";
import { BOT_ROLES } from "@/lib/bot-roles";
import { BUILT_IN_INSTANCE_DRIVERS } from "@/lib/built-in-instances";
import { CURATED_CONNECTOR_SLUGS } from "../../shared/connector-curated";
import { CREDENTIAL_TARGETS } from "../../shared/credential-request";
import { TOOL_SCOPE_SUPPORT } from "../../shared/tool-scope-support";
import {
- allow, APP, BOT_TEMPLATE, credentialProvider, ENGINE, engineForDriver, engineSlug, KEY_PROVIDER, SECTION_PROVIDER,
+ allow, APP, BOT_TEMPLATE, credentialProvider, ENGINE, engineForDriver, engineSlug, KEY_PROVIDER,
} from "./analytics-allowlist";
const HOSTILE = [
@@ -73,15 +73,14 @@ describe("app, role and key lists", () => {
});
it("names a provider for every Settings key row", () => {
- const rows = {
- composio: "composio", box: "boat", opencodeGo: "opencode_go", anthropic: "anthropic", openai: "openai",
- openrouter: "openrouter", openaiCompat: "openai_compat", xai: "xai", mistral: "mistral", cerebras: "cerebras",
- groq: "groq", meta: "meta", treg: "treg", deepseek: "deepseek",
- } satisfies Record<ConfigSection, string>;
- for (const [section, provider] of Object.entries(rows)) {
- expect(SECTION_PROVIDER[section as ConfigSection]).toBe(provider);
- expect(KEY_PROVIDER).toContain(provider);
- }
+ const rows = Object.fromEntries(KEY_CATALOG.flatMap((entry) => entry.target ? [[entry.id, entry.target.analytics]] : []));
+ expect(rows).toEqual({
+ openai: "openai", anthropic: "anthropic", xai: "xai", openrouter: "openrouter", mistral: "mistral", cerebras: "cerebras", groq: "groq",
+ meta: "meta", deepseek: "deepseek", opencodeGo: "opencode_go", openaiCompat: "openai_compat", liveKey: "openai_live",
+ elevenlabs: "elevenlabs", fishAudio: "fish_audio", box: "boat", composio: "composio", treg: "treg", jev: "jev",
+ openrouterHelper: "openrouter_decider", imageOpenai: "openai_image",
+ });
+ for (const provider of Object.values(rows)) expect(KEY_PROVIDER).toContain(provider);
});
it("names a provider for every credential a bot can ask for in chat, and nothing else", () => {
diff --git a/src/lib/analytics-allowlist.ts b/src/lib/analytics-allowlist.ts
index eca38b45cc..0c1aeabae9 100644
--- a/src/lib/analytics-allowlist.ts
+++ b/src/lib/analytics-allowlist.ts
@@ -19,12 +19,6 @@ export const KEY_PROVIDER = [
] as const;
export type KeyProvider = (typeof KEY_PROVIDER)[number];
-export const SECTION_PROVIDER = {
- composio: "composio", box: "boat", opencodeGo: "opencode_go", anthropic: "anthropic", openai: "openai",
- openrouter: "openrouter", openaiCompat: "openai_compat", xai: "xai", mistral: "mistral", cerebras: "cerebras",
- groq: "groq", meta: "meta", treg: "treg", deepseek: "deepseek",
-} as const satisfies Record<string, KeyProvider>;
-
const CREDENTIAL_PROVIDER = new Map<string, KeyProvider>(Object.entries({
boxToken: "boat", xaiApiKey: "xai", opencodeGoApiKey: "opencode_go", ttsKey: "elevenlabs", fishAudioKey: "fish_audio",
openaiImageApiKey: "openai_image", onePasswordToken: "onepassword",
@@ -68,7 +62,7 @@ export const APP: readonly string[] = CURATED_CONNECTOR_SLUGS;
export const BOT_TEMPLATE: readonly string[] = BOT_ROLES.map((role) => role.id);
export const CLOUD_TIER = ["starter", "personal", "pro", "max"] as const;
-export const KEY_VIA = ["settings", "computer_panel", "chat_request", "apps"] as const;
+export const KEY_VIA = ["settings", "computer_panel", "chat_request", "apps", "model_picker"] as const;
export type KeyVia = (typeof KEY_VIA)[number];
export const KEY_RESULT = ["ok", "rejected", "unverified", "error"] as const;
export type KeyResult = (typeof KEY_RESULT)[number];
diff --git a/src/lib/place-view.ts b/src/lib/place-view.ts
index 7cc6875c2c..2f51b1d68b 100644
--- a/src/lib/place-view.ts
+++ b/src/lib/place-view.ts
@@ -8,6 +8,7 @@ import { writeComputerPanelView } from "@/lib/computer-panel-view";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { openBotSettings } from "@/components/bot-panel/panel-link";
+import { openKeySettings } from "@/components/keys/key-focus";
import type { Action, Bot, ConfigStatus, InstanceInfo } from "@/state/store";
import type { LocaleKey } from "@/locales";
import {
@@ -114,7 +115,7 @@ export function openPlaceAction(
target: { botId: string; threadId?: string; place?: Place },
dispatch: (action: Action) => void,
): boolean {
- const appSettings = (section: "engines" | "computer" | "connections" | "cloudAccount") =>
+ const appSettings = (section: "engines" | "computer" | "cloudAccount") =>
dispatch({ type: "toggleAppSettings", open: true, section });
switch (id) {
case "choose-model": openBotSettings(dispatch, "model", { botId: target.botId }); return true;
@@ -122,7 +123,7 @@ export function openPlaceAction(
case "change-routine": openBotSettings(dispatch, "routines", { botId: target.botId }); return true;
case "sign-in": appSettings("engines"); return true;
case "manage-computers": appSettings("computer"); return true;
- case "add-boat-key": appSettings("connections"); return true;
+ case "add-boat-key": dispatch(openKeySettings("box")); return true;
case "open-vm-settings":
window.sessionStorage?.setItem("openmausbot.settings.section", "computer");
appSettings("computer");
diff --git a/src/lib/scroll-within.ts b/src/lib/scroll-within.ts
new file mode 100644
index 0000000000..e3144992be
--- /dev/null
+++ b/src/lib/scroll-within.ts
@@ -0,0 +1,21 @@
+type Box = { getBoundingClientRect(): { top: number } };
+
+/** Moves `scroller` alone so `target` sits at its top or centre. Element.scrollIntoView would also scroll every
+ * overflow-hidden ancestor, sliding a dialog's frame and its header out of view. */
+export function scrollWithin(
+ scroller: Box & { scrollTop: number; clientHeight: number },
+ target: Box & { offsetHeight?: number },
+ block: "start" | "center" = "start",
+ margin = 0,
+): void {
+ const top = target.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
+ scroller.scrollTop = Math.max(0, block === "center" ? top - (scroller.clientHeight - (target.offsetHeight ?? 0)) / 2 : top - margin);
+}
+
+export function scrollParent(element: Element): HTMLElement | null {
+ for (let node = element.parentElement; node; node = node.parentElement) {
+ const overflow = getComputedStyle(node).overflowY;
+ if ((overflow === "auto" || overflow === "scroll") && node.scrollHeight > node.clientHeight) return node;
+ }
+ return null;
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index a689c9367f..47fc32e3f7 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -6618,5 +6618,75 @@
"chat.setupCard.data": "Data, spreadsheets and reports",
"composer.setupRequest.placeholder": "Tell {name} what you'd like help with",
"composer.setupRequest.waiting": "{name} is ready to be set up",
- "composer.setupRequest.cancel": "Stop setting up {name}"
+ "composer.setupRequest.cancel": "Stop setting up {name}",
+ "keys.section.ai": "AI providers",
+ "keys.section.ai.purpose": "Keys for the models your bots run on.",
+ "keys.section.servers": "Your own model servers",
+ "keys.section.servers.purpose": "LM Studio and servers that speak the OpenAI API.",
+ "keys.section.voice": "Voice and calls",
+ "keys.section.voice.purpose": "Voices for spoken replies and live calls.",
+ "keys.section.computers": "Computers and browser",
+ "keys.section.computers.purpose": "Cloud desktops, your own server and website logins.",
+ "keys.section.apps": "Apps and tools",
+ "keys.section.apps.purpose": "Connected apps and research.",
+ "keys.section.helpers": "Helpers and pictures",
+ "keys.section.helpers.purpose": "Small models that sort things for your bots, and avatar pictures.",
+ "keys.section.connected": "{count} connected",
+ "keys.purpose.openai": "OpenAI's models and live calls",
+ "keys.purpose.anthropic": "Claude models, billed per token",
+ "keys.purpose.xai": "Grok models and xAI pictures",
+ "keys.purpose.openrouter": "Hundreds of models through one key",
+ "keys.purpose.mistral": "Models served by Mistral AI",
+ "keys.purpose.cerebras": "Open models on very fast chips",
+ "keys.purpose.groq": "Open models served fast by Groq",
+ "keys.purpose.meta": "Meta's Muse models",
+ "keys.purpose.deepseek": "The DeepSeek Harness engine",
+ "keys.purpose.opencodeGo": "OpenCode Zen and Go",
+ "keys.purpose.opencodeProviders": "Any other provider OpenCode supports",
+ "keys.purpose.lmStudio": "Models from the LM Studio app",
+ "keys.purpose.openaiCompat": "Ollama, Together or any server that speaks the OpenAI API",
+ "keys.purpose.liveCalls": "Live calls use the same key as OpenAI's models",
+ "keys.purpose.liveKey": "Optional. Live calls use it instead of your OpenAI key",
+ "keys.purpose.elevenlabs": "Voices for spoken replies and calls",
+ "keys.purpose.fishAudio": "Fish Audio voices for spoken replies and calls",
+ "keys.purpose.box": "Cloud desktops your bots can use",
+ "keys.purpose.vps": "Your own Linux server, reached over SSH",
+ "keys.purpose.onePassword": "Website logins your bots can use",
+ "keys.purpose.composio": "Gmail, Slack, GitHub and more through your own Composio project",
+ "keys.purpose.treg": "Research on X, companies and people",
+ "keys.purpose.jev": "Fast decisions and reading for your bots",
+ "keys.purpose.openrouterHelper": "Fast decisions through OpenRouter",
+ "keys.purpose.workersAi": "Free decisions and reading on Cloudflare",
+ "keys.purpose.imageOpenai": "Pictures for your bots' avatars",
+ "keys.purpose.imageCustom": "A picture service of your own",
+ "keys.label.liveKey": "Separate key for live calls",
+ "keys.label.elevenlabs": "ElevenLabs API key",
+ "keys.label.fishAudio": "Fish Audio API key",
+ "keys.label.openrouterHelper": "OpenRouter key for decisions",
+ "keys.label.imageOpenai": "OpenAI key for pictures",
+ "keys.label.imageCustom": "Custom picture service key",
+ "keys.where.logins": "Set up in Logins.",
+ "keys.where.decisions": "Set up with its account ID under Decision and extraction.",
+ "keys.where.pictures": "Set up in a bot's picture maker, with the service's address and model.",
+ "keys.row.saving": "Saving…",
+ "keys.row.removing": "Removing…",
+ "keys.row.didntWork": "Didn't work",
+ "keys.row.failed": "Didn't work: {reason}",
+ "keys.row.looksLike": "That looks like the {label}, not this one.",
+ "keys.row.notKept": "The key didn't stay saved. Try again.",
+ "keys.row.newKey": "Paste the new key",
+ "keys.row.show": "Show key",
+ "keys.row.hide": "Hide key",
+ "keys.row.replace": "Replace",
+ "keys.row.remove": "Remove",
+ "keys.row.useOwn": "Use your own key",
+ "keys.row.getKey": "Get a key",
+ "keys.row.endsIn": "{label} is saved and ends in {last4}",
+ "keys.row.savedKey": "{label} is saved",
+ "keys.row.open": "Open",
+ "keys.search.placeholder": "Search keys",
+ "keys.search.aria": "Search API keys",
+ "keys.search.none": "No keys match “{query}”.",
+ "keys.openPage": "Open API keys",
+ "engineSetup.apiKey.inline": "Paste it here. It saves and checks itself, and the models show up here."
}
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index d96fd9c946..c065a8d418 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -3,24 +3,29 @@ import type { EffortLevel, LiveSettings } from "../../shared/wire";
import type { OnboardingStatus } from "@/lib/onboarding";
import type { ModelSelection } from "./store";
+/** A saved credential: whether it is set and, for admins, its last four characters. The key itself never comes back. */
+export interface SavedKey { configured: boolean; last4?: string }
+
+export type NestedKeyName = "ttsKey" | "fishAudioKey" | "jevApiKey" | "openrouterDeciderKey" | "workersAiToken" | "openaiImageApiKey" | "customImageApiKey" | "openaiLiveKey";
+
/** GET /api/config — configured flags only; secrets are never echoed. */
export interface ConfigStatus {
- xai?: { configured: boolean };
- mistral?: { configured: boolean };
- cerebras?: { configured: boolean };
- groq?: { configured: boolean };
- deepseek?: { configured: boolean };
- meta?: { configured: boolean };
+ xai?: SavedKey;
+ mistral?: SavedKey;
+ cerebras?: SavedKey;
+ groq?: SavedKey;
+ deepseek?: SavedKey;
+ meta?: SavedKey;
/** X research comes with MausBot Cloud plans: `included` while this server holds the plan's relay credential;
* `unavailable` when the Admin said no to this desktop's paid sign-in. */
xResearch?: { included: boolean; unavailable?: boolean };
/** The person's own treg key for research: configured or not, never the key. */
- treg?: { configured: boolean };
+ treg?: SavedKey;
/** `everyClaudeBot`: the key runs every Claude bot, not only "Claude (API key)". */
- anthropic?: { configured: boolean; everyClaudeBot?: boolean };
- openai?: { configured: boolean };
- openrouter?: { configured: boolean };
- openaiCompat?: { configured: boolean; url?: string };
+ anthropic?: SavedKey & { everyClaudeBot?: boolean };
+ openai?: SavedKey;
+ openrouter?: SavedKey;
+ openaiCompat?: SavedKey & { url?: string };
/** what this server is entitled to; Settings shows only what works here.
* `license` reaches admins only, and only while the key is inside its
* warning window or grace period. */
@@ -33,9 +38,9 @@ export interface ConfigStatus {
fleet?: { available: boolean };
budgets?: { monthlyUsd?: number; warnAtPercent?: number };
billing?: { currency?: string; prices?: Record<string, { inputPerMillion: number; outputPerMillion: number; cachedInputPerMillion?: number }> };
- composio: { configured: boolean; mode?: "managed" | "self-hosted" | "unavailable" };
+ composio: SavedKey & { mode?: "managed" | "self-hosted" | "unavailable" };
/** `included`: cloud computers come with Cloud Pro, no key is saved. */
- box: { configured: boolean; included?: boolean };
+ box: SavedKey & { included?: boolean };
vps: { configured: boolean; sshAlias: string };
rooms: { turnTimeoutMinutes: number };
/** Per-call ceiling (minutes) for a bot's MCP tools. Absent from servers
@@ -50,7 +55,7 @@ export interface ConfigStatus {
localVm: { mode: "shared" | "per-bot" | "pool"; maxInstances: number; idleTimeoutMinutes?: number };
/** `providerKeys`: names of the keys saved for OpenCode's other
* providers, never the keys. */
- opencodeGo?: { configured: boolean; providerKeys?: string[] };
+ opencodeGo?: SavedKey & { providerKeys?: string[] };
/** Voice. `configured` = the engine has what it needs (an ElevenLabs or
* Fish Audio key, or a Chatterbox server address); `ready` = that AND a voice, which is
* what it takes to actually speak. The key itself is never echoed back;
@@ -92,6 +97,8 @@ export interface ConfigStatus {
};
/** Live calls (OpenAI GPT-Live): configured-or-not, never the key. */
live?: LiveSettings;
+ /** Keys kept inside another setting (voice, decisions, pictures, live calls), by their desktop credential name. */
+ savedKeys?: Partial<Record<NestedKeyName, SavedKey>>;
/** Shared write-only credential for on-demand GPT Image avatars. */
imageGen?: {
configured: boolean;
diff --git a/src/state/store.test.ts b/src/state/store.test.ts
index a4fe2d8d7d..463fc178b6 100644
--- a/src/state/store.test.ts
+++ b/src/state/store.test.ts
@@ -1041,6 +1041,17 @@ describe("config status frames", () => {
expect(status.anthropic).toEqual({ configured: true, everyClaudeBot: false });
});
+ it("keeps every saved key's hint through a live config update, so a masked key never empties", () => {
+ const status = configStatusFromFrame({
+ openai: { configured: true, last4: "a1b2" },
+ box: { configured: true, last4: "c3d4" },
+ savedKeys: { ttsKey: { configured: true, last4: "e5f6" }, openaiLiveKey: { configured: false } },
+ } as ConfigStatusFrame);
+ expect(status.openai).toEqual({ configured: true, last4: "a1b2" });
+ expect(status.box).toEqual({ configured: true, last4: "c3d4" });
+ expect(status.savedKeys).toEqual({ ttsKey: { configured: true, last4: "e5f6" }, openaiLiveKey: { configured: false } });
+ });
+
it("keeps thread capacity and room timeout with the existing config fields", () => {
expect(
configStatusFromFrame({
diff --git a/src/state/store.tsx b/src/state/store.tsx
index d26f85bdeb..8d4a621830 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -440,7 +440,7 @@ export type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicyS
// A section left out here is wiped from state.config whenever a config frame lands.
export type ConfigStatusFrame = Pick<
ConfigStatus,
- "xai" | "mistral" | "cerebras" | "groq" | "meta" | "deepseek" | "xResearch" | "treg" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "profile" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team"
+ "xai" | "mistral" | "cerebras" | "groq" | "meta" | "deepseek" | "xResearch" | "treg" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team"
>;
export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus {
@@ -468,7 +468,7 @@ export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus {
tts: frame.tts,
decider: frame.decider, helpers: frame.helpers,
imageGen: frame.imageGen,
- live: frame.live,
+ live: frame.live, savedKeys: frame.savedKeys,
profile: frame.profile,
language: frame.language,
features: frame.features,