Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(desktop): Models and Voice settings; connect a model on first run

Salman Qureshi3db2a6d3e25d
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 6193b417..d147e6d3 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -38,7 +38,7 @@ export function normalizeBaseUrl(raw: string): string {
}
export class ApiError extends Error {
- constructor(message: string, public readonly status: number, public readonly retryAfterSeconds: number | null = null) {
+ constructor(message: string, public readonly status: number, public readonly retryAfterSeconds: number | null = null, public readonly data: Record<string, unknown> = {}) {
super(message);
this.name = "ApiError";
}
@@ -59,9 +59,9 @@ export async function request<T>(path: string, init: RequestInit = {}): Promise<
throw new ApiError("Unauthorized", 401);
}
if (!res.ok) {
- const body = (await res.json().catch(() => ({}))) as { error?: string };
+ const body = (await res.json().catch(() => ({}))) as { error?: string } & Record<string, unknown>;
const retry = res.headers.get("Retry-After");
- throw new ApiError(body.error || `Request failed (${res.status})`, res.status, retry ? Number(retry) : null);
+ throw new ApiError(body.error || `Request failed (${res.status})`, res.status, retry ? Number(retry) : null, body);
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
diff --git a/apps/desktop/src/api/models.test.ts b/apps/desktop/src/api/models.test.ts
new file mode 100644
index 00000000..a97e0723
--- /dev/null
+++ b/apps/desktop/src/api/models.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { fieldApplies, type VoiceField } from "./models";
+import { filterModels } from "~/components/ModelPicker";
+
+describe("voice fields", () => {
+ const f = (when: VoiceField["when"]): VoiceField => ({ key: "k", type: "string", when });
+ it("shows a field only for the engine it belongs to", () => {
+ expect(fieldApplies(f({ voiceEngine: ["elevenlabs"], mode: ["voice", "both"] }), { voiceEngine: "elevenlabs", mode: "both" })).toBe(true);
+ expect(fieldApplies(f({ voiceEngine: ["elevenlabs"] }), { voiceEngine: "openai" })).toBe(false);
+ });
+ it("any of several conditions is enough (a key shared by STT and TTS)", () => {
+ const shared = f([{ voiceEngine: "mercury", sttProvider: "deepgram" }, { voiceEngine: "mercury", ttsProvider: "deepgram" }]);
+ expect(fieldApplies(shared, { voiceEngine: "mercury", sttProvider: "assemblyai", ttsProvider: "deepgram" })).toBe(true);
+ expect(fieldApplies(shared, { voiceEngine: "mercury", sttProvider: "assemblyai", ttsProvider: "cartesia" })).toBe(false);
+ });
+ it("no condition means always", () => expect(fieldApplies(f(undefined), {})).toBe(true));
+});
+
+describe("model search", () => {
+ const models = ["openai/gpt-5", "anthropic/claude-sonnet-4.6", "anthropic/claude-opus-4.6", "gpt-4o-mini", "google/gemini-2.5-pro"];
+ it("matches every word in any order", () => {
+ expect(filterModels(models, "claude opus")).toEqual(["anthropic/claude-opus-4.6"]);
+ expect(filterModels(models, "4.6 anthropic")).toHaveLength(2);
+ });
+ it("puts ids that start with the query first", () => {
+ expect(filterModels(models, "gpt")[0]).toBe("gpt-4o-mini");
+ });
+ it("an empty query lists everything", () => expect(filterModels(models, " ")).toEqual(models));
+});
diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.ts
new file mode 100644
index 00000000..91abe1e7
--- /dev/null
+++ b/apps/desktop/src/api/models.ts
@@ -0,0 +1,108 @@
+import { http } from "./client";
+import type { PluginItem } from "./types";
+
+/** Model providers and gateways (GET/POST /api/providers*), voice key checks, and Optimus voice settings. */
+
+export type ProviderKind = "cloud" | "gateway" | "local" | "account";
+
+export interface ProviderInfo {
+ id: string;
+ label: string;
+ kind: ProviderKind;
+ blurb: string;
+ needsKey: boolean;
+ needsBaseUrl: boolean;
+ signInOnly: boolean;
+ keyUrl: string | null;
+ keyHint: string | null;
+ /** Masked: "sk-a••••b3c4". Never send it back. */
+ apiKey: string;
+ hasKey: boolean;
+ baseUrl: string;
+ model: string;
+ enabled: boolean;
+ configured: boolean;
+ isDefault: boolean;
+ recommended: boolean;
+}
+
+export interface ProviderSettings {
+ providers: ProviderInfo[];
+ default: { provider: string; model: string };
+ roles: { learning: string | null; crew: string | null };
+ setupRequired: boolean;
+}
+
+export type CheckField = "apiKey" | "baseUrl";
+export interface ProviderCheck {
+ ok: boolean;
+ models?: string[];
+ recommendedModel?: string;
+ error?: string;
+ field?: CheckField;
+ ms?: number;
+}
+
+export interface SaveResult {
+ success: boolean;
+ provider?: ProviderInfo;
+ applied: boolean;
+ restarting?: boolean;
+ restartRequired?: boolean;
+ error?: string;
+}
+
+export interface VoiceCheck {
+ ok: boolean;
+ verified: boolean;
+ message: string;
+ voices?: Array<{ id: string; name: string }>;
+ models?: string[];
+}
+
+export type VoiceVendor = "elevenlabs" | "deepgram" | "assemblyai" | "cartesia" | "gemini" | "qwen" | "azure" | "sarvam" | "minimax";
+
+/** Optimus settings, with the fields the voice screen needs (when, options, labels). */
+export interface VoiceField {
+ key: string;
+ type: "string" | "number" | "boolean" | "enum" | "secret";
+ label?: string;
+ description?: string;
+ options?: string[];
+ optionLabels?: Record<string, string>;
+ examples?: string[];
+ value?: unknown;
+ isSet?: boolean;
+ required?: boolean;
+ group?: string;
+ when?: Record<string, string | string[]> | Array<Record<string, string | string[]>>;
+}
+export type VoicePlugin = Omit<PluginItem, "settings"> & { settings?: VoiceField[]; settingGroups?: Array<{ id: string; label: string; description?: string; ready: boolean }>; missing?: Array<{ key: string; needs: string; fix: string }> };
+
+const enc = encodeURIComponent;
+
+export const modelsApi = {
+ settings: () => http.get<ProviderSettings>("/api/providers/settings"),
+ /** Live check of what's typed (unsaved). An omitted key means "the saved one". */
+ check: (id: string, draft: { apiKey?: string; baseUrl?: string }) => http.post<ProviderCheck>(`/api/providers/${enc(id)}/check`, draft),
+ save: (id: string, patch: { apiKey?: string; baseUrl?: string; model?: string; enabled?: boolean }) => http.post<SaveResult>(`/api/providers/${enc(id)}`, patch),
+ forget: (id: string) => http.delete<SaveResult>(`/api/providers/${enc(id)}/key`),
+ roles: (body: { default?: { provider: string; model?: string }; learning?: string | null; crew?: string | null }) => http.put<SaveResult>("/api/providers/roles", body),
+};
+
+export const voiceApi = {
+ check: (vendor: VoiceVendor, key?: string, endpoint?: string) => http.post<VoiceCheck>("/api/voice/check", { vendor, key, endpoint }),
+ /** null when Optimus (which carries voice) isn't installed. */
+ plugin: () => http.get<{ plugin: VoicePlugin | null }>("/api/plugins/optimus").then((r) => r.plugin),
+ set: (key: string, value: unknown) => http.post<{ ok: boolean }>("/api/plugins/optimus/settings", { key, value }),
+};
+
+/** Does a plugin field apply, given the current values? (Mirrors the runtime's `whenMatches`.) */
+export function fieldApplies(f: VoiceField, values: Record<string, unknown>): boolean {
+ if (!f.when) return true;
+ const conds = Array.isArray(f.when) ? f.when : [f.when];
+ return conds.some((c) => Object.entries(c).every(([k, want]) => {
+ const v = String(values[k]);
+ return Array.isArray(want) ? want.includes(v) : v === String(want);
+ }));
+}
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 57680131..c8744be4 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -8,6 +8,8 @@ export interface HealthInfo {
features?: string[];
state: string;
booting: boolean;
+ /** No model provider yet: the runtime is up only so one can be connected (first run). */
+ setupRequired?: boolean;
}
export interface DeviceSummary {
diff --git a/apps/desktop/src/app/App.tsx b/apps/desktop/src/app/App.tsx
index c325342f..93e2dfb9 100644
--- a/apps/desktop/src/app/App.tsx
+++ b/apps/desktop/src/app/App.tsx
@@ -3,6 +3,7 @@ import { TooltipProvider } from "~/components/ui/Tooltip";
import { useConnections, type Connection } from "~/shell/connections";
import { useRuntime } from "~/shell/useRuntime";
import { Onboarding } from "~/shell/Onboarding";
+import { FirstModel } from "~/shell/FirstModel";
import { Workspace } from "~/layout/Workspace";
import { Wordmark } from "~/components/Logo";
import { Button } from "~/components/ui/Button";
@@ -13,7 +14,8 @@ import { useRuntimeState } from "./store";
/**
* What fills the window:
* - no connection chosen → first run;
- * - a connection → bring it up, then the workspace.
+ * - a connection → bring it up, then the workspace;
+ * - a fresh Mercury with no model yet → connect one first.
*/
export function App() {
return (
@@ -46,6 +48,7 @@ function Connected({ connection, onSwitch }: { connection: Connection; onSwitch:
useEffect(() => { setConnected(status.phase === "ready"); }, [status.phase, setConnected]);
+ if (status.phase === "ready" && status.health.setupRequired) return <FirstModel onReady={retry} onSwitch={onSwitch} />;
if (status.phase === "ready") return <Workspace connection={connection} health={status.health} onSwitchConnection={onSwitch} />;
return (
diff --git a/apps/desktop/src/components/ModelPicker.tsx b/apps/desktop/src/components/ModelPicker.tsx
new file mode 100644
index 00000000..803c6f52
--- /dev/null
+++ b/apps/desktop/src/components/ModelPicker.tsx
@@ -0,0 +1,117 @@
+import { Check, ChevronsUpDown, Search } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { cx } from "~/lib/cx";
+import { Spinner } from "~/components/ui/bits";
+
+/**
+ * A searchable menu of models. Takes every model a provider offers (hundreds
+ * on a gateway), filters as you type, and still lets you use an id that
+ * isn't listed ("Use “my-model”"). Arrow keys and Enter work.
+ */
+export function ModelPicker({ value, models, onChange, recommended, loading, disabled, placeholder = "Choose a model", id }: {
+ value: string;
+ models: string[];
+ onChange: (model: string) => void;
+ recommended?: string;
+ loading?: boolean;
+ disabled?: boolean;
+ placeholder?: string;
+ id?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [cursor, setCursor] = useState(0);
+ const root = useRef<HTMLDivElement>(null);
+ const list = useRef<HTMLDivElement>(null);
+
+ const shown = useMemo(() => filterModels(models, query), [models, query]);
+ const custom = query.trim() && !models.includes(query.trim()) && !/\s/.test(query.trim()) ? query.trim() : null;
+ const rows = custom ? [...shown, custom] : shown;
+
+ useEffect(() => {
+ if (!open) return;
+ const close = (e: MouseEvent) => { if (!root.current?.contains(e.target as Node)) setOpen(false); };
+ window.addEventListener("mousedown", close);
+ return () => window.removeEventListener("mousedown", close);
+ }, [open]);
+ useEffect(() => { setCursor(0); }, [query, open]);
+ useEffect(() => { list.current?.querySelector<HTMLElement>(`[data-i="${cursor}"]`)?.scrollIntoView({ block: "nearest" }); }, [cursor]);
+
+ function pick(m: string) {
+ onChange(m);
+ setOpen(false);
+ setQuery("");
+ }
+
+ return (
+ <div ref={root} className="relative">
+ <button
+ id={id}
+ type="button"
+ disabled={disabled}
+ onClick={() => setOpen((o) => !o)}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ className="flex h-9 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-left text-sm text-ink transition-colors hover:border-ink/25 disabled:opacity-50"
+ >
+ <span className={cx("min-w-0 flex-1 truncate font-mono text-[12.5px]", !value && "font-sans text-sm text-ink4")}>{value || placeholder}</span>
+ {value && value === recommended && <span className="shrink-0 rounded-full bg-accent/15 px-1.5 text-2xs text-accent">recommended</span>}
+ {loading ? <Spinner size={12} /> : <ChevronsUpDown size={14} className="shrink-0 text-ink4" />}
+ </button>
+ {open && (
+ <div className="absolute left-0 right-0 top-[calc(100%+4px)] z-50 overflow-hidden rounded-lg border border-line bg-surface shadow-xl">
+ <div className="flex items-center gap-2 border-b border-line px-3">
+ <Search size={13} className="text-ink4" />
+ <input
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "ArrowDown") { e.preventDefault(); setCursor((c) => Math.min(rows.length - 1, c + 1)); }
+ else if (e.key === "ArrowUp") { e.preventDefault(); setCursor((c) => Math.max(0, c - 1)); }
+ else if (e.key === "Enter") { e.preventDefault(); const r = rows[cursor]; if (r) pick(r); }
+ else if (e.key === "Escape") { e.preventDefault(); setOpen(false); }
+ }}
+ placeholder={models.length ? `Search ${models.length} models` : "Type a model id"}
+ className="h-9 flex-1 bg-transparent text-sm text-ink placeholder:text-ink4"
+ aria-label="Search models"
+ spellCheck={false}
+ autoCapitalize="off"
+ />
+ </div>
+ <div ref={list} role="listbox" className="max-h-[280px] overflow-y-auto p-1">
+ {rows.length === 0 && <div className="px-3 py-3 text-xs text-ink4">{loading ? "Loading models…" : "No models match."}</div>}
+ {rows.map((m, i) => {
+ const isCustom = m === custom && i === rows.length - 1;
+ return (
+ <button
+ key={`${m}-${i}`}
+ type="button"
+ data-i={i}
+ role="option"
+ aria-selected={m === value}
+ onMouseEnter={() => setCursor(i)}
+ onClick={() => pick(m)}
+ className={cx("flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left", i === cursor ? "bg-ink/[0.07]" : "")}
+ >
+ <Check size={13} className={cx("shrink-0 text-accent", m === value ? "opacity-100" : "opacity-0")} />
+ <span className={cx("min-w-0 flex-1 truncate font-mono text-[12.5px] text-ink", isCustom && "font-sans text-sm text-ink2")}>{isCustom ? `Use “${m}”` : m}</span>
+ {m === recommended && !isCustom && <span className="shrink-0 text-2xs text-accent">recommended</span>}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Every word must appear (in any order); ids that start with the query rank first. */
+export function filterModels(models: string[], query: string): string[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return models;
+ const words = q.split(/[\s/:]+/).filter(Boolean);
+ const hits = models.filter((m) => { const l = m.toLowerCase(); return words.every((w) => l.includes(w)); });
+ return hits.sort((a, b) => Number(!a.toLowerCase().startsWith(q)) - Number(!b.toLowerCase().startsWith(q)));
+}
diff --git a/apps/desktop/src/shell/FirstModel.tsx b/apps/desktop/src/shell/FirstModel.tsx
new file mode 100644
index 00000000..33b12cd7
--- /dev/null
+++ b/apps/desktop/src/shell/FirstModel.tsx
@@ -0,0 +1,88 @@
+import { ArrowLeft, CheckCircle2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { modelsApi, type ProviderInfo, type ProviderSettings } from "~/api/models";
+import { Wordmark } from "~/components/Logo";
+import { Badge, Spinner } from "~/components/ui/bits";
+import { IconTile } from "~/components/ui/kit";
+import { ProviderEditor, errorText } from "~/views/settings/Models";
+
+/**
+ * First run, after Mercury is installed: it can't think until a model is
+ * connected. A few good starting points, everything else one click away;
+ * the key is tested live before it's saved, then Mercury restarts with it.
+ */
+const FEATURED = ["aimlapi", "openai", "anthropic", "ollamaLocal"];
+
+export function FirstModel({ onReady, onSwitch }: { onReady: () => void; onSwitch: () => void }) {
+ const [data, setData] = useState<ProviderSettings | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [picked, setPicked] = useState<ProviderInfo | null>(null);
+ const [all, setAll] = useState(false);
+ const [starting, setStarting] = useState<string | null>(null);
+
+ useEffect(() => { modelsApi.settings().then(setData).catch((e) => setError(errorText(e))); }, []);
+ // After the restart, reconnect; the workspace takes over once Mercury is up.
+ useEffect(() => {
+ if (!starting) return;
+ const t = setTimeout(onReady, 6000);
+ return () => clearTimeout(t);
+ }, [starting, onReady]);
+
+ const choices = (data?.providers ?? []).filter((p) => !p.signInOnly);
+ const featured = FEATURED.map((id) => choices.find((p) => p.id === id)).filter(Boolean) as ProviderInfo[];
+ const others = choices.filter((p) => !FEATURED.includes(p.id));
+
+ return (
+ <div className="flex h-full flex-col overflow-y-auto bg-bg" data-tauri-drag-region>
+ <div className="mx-auto flex w-full max-w-[640px] flex-1 flex-col justify-center gap-6 px-8 py-10">
+ <div className="flex flex-col items-center gap-1 text-center">
+ <Wordmark width={200} breathe={!!starting} />
+ <p className="mt-1 text-sm text-ink3">{starting ? `Starting Mercury with ${starting}…` : "Connect a model so Mercury can think. You can add more, and change it any time, in Settings → Models."}</p>
+ </div>
+
+ {starting && <div className="flex justify-center text-ink3"><Spinner size={18} /></div>}
+ {error && !starting && <p className="text-center text-sm text-red">Couldn't reach Mercury: {error}</p>}
+ {!data && !error && <div className="flex justify-center text-ink3"><Spinner size={18} /></div>}
+
+ {data && !starting && !picked && (
+ <div className="flex flex-col gap-2">
+ {featured.map((p) => <Choice key={p.id} p={p} onPick={() => setPicked(p)} />)}
+ {all && others.map((p) => <Choice key={p.id} p={p} onPick={() => setPicked(p)} />)}
+ {!all && <button className="self-center text-xs text-ink3 hover:text-ink hover:underline" onClick={() => setAll(true)}>More providers ({others.length})</button>}
+ </div>
+ )}
+
+ {data && !starting && picked && (
+ <div className="flex flex-col gap-4 rounded-xl border border-line bg-surface p-5">
+ <div className="flex items-center gap-3">
+ <button onClick={() => setPicked(null)} className="rounded-md p-1 text-ink3 hover:bg-ink/[0.06] hover:text-ink" aria-label="Back"><ArrowLeft size={16} /></button>
+ <IconTile id={picked.id} label={picked.label} size={30} />
+ <div>
+ <div className="text-base font-medium text-ink">{picked.label}</div>
+ <div className="text-xs text-ink3">{picked.blurb}</div>
+ </div>
+ </div>
+ <ProviderEditor provider={picked} offerDefault={false} saveLabel="Connect and start"
+ onSaved={(r) => { if (r.restarting || r.applied || r.restartRequired) setStarting(picked.label); }} />
+ </div>
+ )}
+
+ <button className="self-center text-xs text-ink4 hover:text-ink2 hover:underline" onClick={onSwitch}>Use another connection</button>
+ </div>
+ </div>
+ );
+}
+
+function Choice({ p, onPick }: { p: ProviderInfo; onPick: () => void }) {
+ return (
+ <button onClick={onPick} className="flex items-center gap-3 rounded-xl border border-line bg-surface px-4 py-3 text-left transition-colors hover:border-ink/25">
+ <IconTile id={p.id} label={p.label} size={34} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2"><span className="text-base text-ink">{p.label}</span>{p.recommended && <Badge tone="cyan">recommended</Badge>}{p.kind === "local" && <Badge>free</Badge>}</div>
+ <div className="text-xs text-ink3">{p.blurb}</div>
+ </div>
+ {p.configured && <CheckCircle2 size={16} className="text-accent" />}
+ <span className={p.recommended ? "rounded-md bg-accent px-2.5 py-1 text-xs font-medium text-on-accent" : "rounded-md border border-line px-2.5 py-1 text-xs text-ink2"}>Choose</span>
+ </button>
+ );
+}
diff --git a/apps/desktop/src/views/settings/Models.tsx b/apps/desktop/src/views/settings/Models.tsx
new file mode 100644
index 00000000..57212cfa
--- /dev/null
+++ b/apps/desktop/src/views/settings/Models.tsx
@@ -0,0 +1,393 @@
+import { CheckCircle2, ExternalLink, KeyRound, Plug, Power, RefreshCw, TriangleAlert } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { ApiError } from "~/api/client";
+import { modelsApi, type CheckField, type ProviderCheck, type ProviderInfo, type ProviderKind, type ProviderSettings, type SaveResult } from "~/api/models";
+import { ModelPicker } from "~/components/ModelPicker";
+import { Button } from "~/components/ui/Button";
+import { Dialog } from "~/components/ui/Dialog";
+import { Field, Input } from "~/components/ui/Input";
+import { Badge, Spinner } from "~/components/ui/bits";
+import { ConfirmButton, IconTile } from "~/components/ui/kit";
+import { desktop } from "~/shell/tauri";
+import { cx } from "~/lib/cx";
+
+/**
+ * Models: which providers and gateways Mercury can use, and which model does
+ * which job. Every key is checked live before it's saved (the check also
+ * fetches every model the key can use, for the menu), saves apply to the
+ * running Mercury at once, and keys are never shown back in full.
+ */
+
+const KIND_TITLE: Record<ProviderKind, { title: string; hint: string }> = {
+ gateway: { title: "Gateways", hint: "One key, models from many labs." },
+ cloud: { title: "Model labs", hint: "A key from the company that makes the model." },
+ local: { title: "On this computer", hint: "Free and private; runs on your machine." },
+ account: { title: "Subscriptions", hint: "Use a plan you already pay for." },
+};
+const KIND_ORDER: ProviderKind[] = ["gateway", "cloud", "local", "account"];
+
+export function ModelsSettings() {
+ const [data, setData] = useState<ProviderSettings | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [editing, setEditing] = useState<ProviderInfo | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ try { setData(await modelsApi.settings()); setError(null); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }
+ }, []);
+ useEffect(() => { void load(); }, [load]);
+
+ function saved(r: SaveResult, what: string) {
+ setNotice(r.restarting ? `${what}. Mercury is restarting with it…` : r.restartRequired ? `${what}. Restart Mercury to use it (this Mercury is too old to apply it live).` : `${what}. In use from the next message.`);
+ void load();
+ }
+
+ if (error) return <p className="text-sm text-red">Couldn't load providers: {error}</p>;
+ if (!data) return <Spinner size={16} />;
+
+ const connected = data.providers.filter((p) => p.configured);
+ const rest = data.providers.filter((p) => !p.configured);
+
+ return (
+ <section className="flex flex-col gap-6">
+ {notice && (
+ <div className="flex items-center gap-2 rounded-lg border border-accent/30 bg-accent/[0.06] px-3 py-2 text-sm text-ink2">
+ <CheckCircle2 size={15} className="shrink-0 text-accent" />{notice}
+ </div>
+ )}
+
+ {connected.length === 0
+ ? <EmptyState />
+ : <Defaults data={data} onSaved={(r) => saved(r, "Saved")} />}
+
+ {connected.length > 0 && (
+ <div className="flex flex-col gap-2">
+ <SectionTitle title="Connected" hint="Mercury falls back to these, in order, if the default can't answer." />
+ <div className="overflow-hidden rounded-lg border border-line bg-surface">
+ {connected.map((p) => (
+ <ProviderRow key={p.id} p={p} onEdit={() => setEditing(p)}
+ onOff={() => void modelsApi.save(p.id, { enabled: false }).then((r) => saved(r, `${p.label} turned off`)).catch((e) => setNotice(errorText(e)))}
+ onForget={() => void modelsApi.forget(p.id).then((r) => saved(r, `${p.label} key removed`)).catch((e) => setNotice(errorText(e)))} />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {KIND_ORDER.map((kind) => {
+ const list = rest.filter((p) => p.kind === kind);
+ if (!list.length) return null;
+ return (
+ <div key={kind} className="flex flex-col gap-2">
+ <SectionTitle title={connected.length ? `Add · ${KIND_TITLE[kind].title}` : KIND_TITLE[kind].title} hint={KIND_TITLE[kind].hint} />
+ <div className="overflow-hidden rounded-lg border border-line bg-surface">
+ {list.map((p) => <ProviderRow key={p.id} p={p} onEdit={() => setEditing(p)} />)}
+ </div>
+ </div>
+ );
+ })}
+
+ <Dialog open={!!editing} onOpenChange={(o) => { if (!o) setEditing(null); }} title={editing ? (editing.configured ? `${editing.label}` : `Connect ${editing.label}`) : ""} description={editing?.blurb} width={520}>
+ {editing && (
+ <ProviderEditor provider={editing} offerDefault={!editing.isDefault}
+ onSaved={(r) => { setEditing(null); saved(r, `${editing.label} saved`); }} onCancel={() => setEditing(null)} />
+ )}
+ </Dialog>
+ </section>
+ );
+}
+
+function SectionTitle({ title, hint }: { title: string; hint?: string }) {
+ return (
+ <div className="flex items-baseline gap-2">
+ <h2 className="text-sm font-medium text-ink">{title}</h2>
+ {hint && <span className="text-xs text-ink4">{hint}</span>}
+ </div>
+ );
+}
+
+function EmptyState() {
+ return (
+ <div className="flex items-start gap-3 rounded-lg border border-amber/40 bg-amber/[0.06] px-4 py-3">
+ <TriangleAlert size={16} className="mt-0.5 shrink-0 text-amber" />
+ <div className="text-sm text-ink2">
+ <div className="font-medium text-ink">No model connected yet</div>
+ Mercury needs at least one. A gateway like AI/ML API gives you models from every major lab on one key; Ollama runs free models on this computer.
+ </div>
+ </div>
+ );
+}
+
+function ProviderRow({ p, onEdit, onOff, onForget }: { p: ProviderInfo; onEdit: () => void; onOff?: () => void; onForget?: () => void }) {
+ return (
+ <div className="flex items-center gap-3 border-b border-line px-4 py-3 last:border-b-0">
+ <IconTile id={p.id} label={p.label} size={34} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-base text-ink">{p.label}</span>
+ {p.isDefault && p.configured && <Badge tone="accent">default</Badge>}
+ {p.recommended && !p.configured && <Badge tone="cyan">recommended</Badge>}
+ {!p.configured && p.hasKey && <Badge tone="amber">off</Badge>}
+ </div>
+ <div className="truncate text-xs text-ink3">
+ {p.configured ? <span className="font-mono">{p.model}{p.hasKey ? ` · ${p.apiKey}` : ""}</span> : p.blurb}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {p.configured ? (
+ <>
+ <Button size="sm" variant="outline" onClick={onEdit}>Edit</Button>
+ {onOff && !p.isDefault && <Button size="sm" variant="ghost" icon onClick={onOff} aria-label={`Turn off ${p.label}`} title="Turn off"><Power size={14} /></Button>}
+ {onForget && p.hasKey && <ConfirmButton size="sm" variant="ghost" confirmLabel="Remove key?" onConfirm={onForget}>Remove</ConfirmButton>}
+ </>
+ ) : (
+ <Button size="sm" variant={p.recommended ? "primary" : "outline"} onClick={onEdit}><Plug size={13} /> {p.hasKey ? "Turn on" : "Connect"}</Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ── Defaults: which model does which job ─────────────────────────────────────
+
+function Defaults({ data, onSaved }: { data: ProviderSettings; onSaved: (r: SaveResult) => void }) {
+ const connected = data.providers.filter((p) => p.configured);
+ const [provider, setProvider] = useState(data.default.provider);
+ const [model, setModel] = useState(data.default.model);
+ const catalog = useCatalog(provider);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => { setProvider(data.default.provider); setModel(data.default.model); }, [data.default.provider, data.default.model]);
+
+ const changed = provider !== data.default.provider || model !== data.default.model;
+ async function save(kind: string, body: Parameters<typeof modelsApi.roles>[0]) {
+ setBusy(kind);
+ setError(null);
+ try { onSaved(await modelsApi.roles(body)); } catch (e) { setError(errorText(e)); } finally { setBusy(null); }
+ }
+
+ return (
+ <div className="flex flex-col gap-4 rounded-xl border border-line bg-surface p-4">
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline justify-between">
+ <span className="text-base font-medium text-ink">Chat and tasks</span>
+ <span className="text-xs text-ink4">The default for chats, code, sub-agents and bots</span>
+ </div>
+ <div className="grid grid-cols-[minmax(0,200px)_minmax(0,1fr)] gap-2">
+ <Select value={provider} onChange={(v) => { setProvider(v); setModel(data.providers.find((p) => p.id === v)?.model ?? ""); }} options={connected.map((p) => ({ value: p.id, label: p.label }))} label="Default provider" />
+ <ModelPicker value={model} models={catalog.models} recommended={catalog.recommended} loading={catalog.loading} onChange={setModel} />
+ </div>
+ {catalog.error && <p className="text-xs text-amber">Couldn't list models: {catalog.error} You can still type a model id.</p>}
+ {changed && (
+ <div className="flex justify-end gap-2">
+ <Button size="sm" variant="ghost" onClick={() => { setProvider(data.default.provider); setModel(data.default.model); }}>Undo</Button>
+ <Button size="sm" variant="primary" loading={busy === "default"} disabled={!model} onClick={() => void save("default", { default: { provider, model } })}>Make default</Button>
+ </div>
+ )}
+ </div>
+
+ <div className="h-px bg-line" />
+
+ <RoleRow title="Learning about you" hint="Reads conversations to update your memory. Strict JSON work: a capable mid-size model learns best."
+ value={data.roles.learning} connected={connected} busy={busy === "learning"} onChange={(v) => void save("learning", { learning: v })} />
+ <RoleRow title="Bot crews" hint="The model fleet crews run on. Something cheaper saves money on long-running bots."
+ value={data.roles.crew} connected={connected} busy={busy === "crew"} onChange={(v) => void save("crew", { crew: v })} />
+ <p className="text-xs text-ink4">Voice has its own settings, under Voice.</p>
+ {error && <p className="text-sm text-red">{error}</p>}
+ </div>
+ );
+}
+
+function RoleRow({ title, hint, value, connected, busy, onChange }: { title: string; hint: string; value: string | null; connected: ProviderInfo[]; busy: boolean; onChange: (v: string | null) => void }) {
+ return (
+ <div className="flex items-center gap-4">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-ink">{title}</div>
+ <div className="text-xs text-ink3">{hint}</div>
+ </div>
+ <div className="flex w-[220px] shrink-0 items-center gap-2">
+ {busy && <Spinner size={12} />}
+ <Select value={value ?? ""} onChange={(v) => onChange(v || null)} label={title}
+ options={[{ value: "", label: "Same as chat" }, ...connected.map((p) => ({ value: p.id, label: `${p.label} · ${p.model}` }))]} />
+ </div>
+ </div>
+ );
+}
+
+function Select({ value, onChange, options, label }: { value: string; onChange: (v: string) => void; options: Array<{ value: string; label: string }>; label: string }) {
+ return (
+ <select value={value} onChange={(e) => onChange(e.target.value)} aria-label={label}
+ className="h-9 w-full min-w-0 truncate rounded-md border border-line bg-surface px-2.5 text-sm text-ink hover:border-ink/25">
+ {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
+ </select>
+ );
+}
+
+/** Models a connected provider offers, fetched once per provider with its saved key. */
+function useCatalog(provider: string): { models: string[]; recommended?: string; loading: boolean; error: string | null } {
+ const [state, setState] = useState<{ provider: string; models: string[]; recommended?: string; loading: boolean; error: string | null }>({ provider, models: [], loading: true, error: null });
+ useEffect(() => {
+ let live = true;
+ setState({ provider, models: [], loading: true, error: null });
+ modelsApi.check(provider, {}).then((r) => {
+ if (live) setState({ provider, models: r.models ?? [], recommended: r.recommendedModel, loading: false, error: r.ok ? null : r.error ?? "unknown error" });
+ }).catch((e) => { if (live) setState({ provider, models: [], loading: false, error: errorText(e) }); });
+ return () => { live = false; };
+ }, [provider]);
+ return state;
+}
+
+// ── One provider: key, address, test, model ──────────────────────────────────
+
+type CheckState = { status: "idle" } | { status: "checking" } | ({ status: "done" } & ProviderCheck);
+
+/**
+ * Connect or edit one provider. The key is tested live (and the model list
+ * fetched) before anything is saved; a key that fails says which field is
+ * wrong. Leaving the key empty keeps the saved one.
+ */
+export function ProviderEditor({ provider: p, offerDefault, defaultOn = false, onSaved, onCancel, saveLabel }: {
+ provider: ProviderInfo;
+ offerDefault: boolean;
+ defaultOn?: boolean;
+ onSaved: (r: SaveResult) => void;
+ onCancel?: () => void;
+ saveLabel?: string;
+}) {
+ const showKey = !p.signInOnly && (p.needsKey || p.kind === "gateway" || p.hasKey);
+ const showUrl = !p.signInOnly && (p.needsBaseUrl || p.kind === "local" || p.kind === "gateway" && p.id !== "aimlapi" && p.id !== "atlascloud");
+ const [key, setKey] = useState("");
+ const [baseUrl, setBaseUrl] = useState(p.baseUrl);
+ const [model, setModel] = useState(p.model);
+ const [makeDefault, setMakeDefault] = useState(defaultOn || p.isDefault);
+ const [check, setCheck] = useState<CheckState>({ status: "idle" });
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<{ message: string; field?: string } | null>(null);
+
+ const draft = useMemo(() => ({ apiKey: key.trim() || undefined, baseUrl: baseUrl.trim() !== p.baseUrl ? baseUrl.trim() : undefined }), [key, baseUrl, p.baseUrl]);
+ const credentialsChanged = !!draft.apiKey || draft.baseUrl !== undefined;
+ const canCheckNow = p.signInOnly ? p.configured : !(p.needsKey && !p.hasKey && !draft.apiKey) && !(p.needsBaseUrl && !baseUrl.trim());
+
+ async function runCheck(): Promise<ProviderCheck | null> {
+ setCheck({ status: "checking" });
+ setSaveError(null);
+ try {
+ const r = await modelsApi.check(p.id, draft);
+ setCheck({ status: "done", ...r });
+ if (r.ok && r.models?.length && (!model || !r.models.includes(model))) setModel(r.recommendedModel || r.models[0]);
+ return r;
+ } catch (e) {
+ const r: ProviderCheck = { ok: false, error: errorText(e) };
+ setCheck({ status: "done", ...r });
+ return r;
+ }
+ }
+
+ // Already connected: load its model list straight away with the saved key.
+ useEffect(() => { if (p.configured) void runCheck(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ // A new key or address needs a new test: the last result was for different credentials.
+ const typed = useRef(false);
+ useEffect(() => {
+ if (!typed.current) { typed.current = true; return; }
+ setCheck((c) => (c.status === "done" ? { status: "idle" } : c));
+ }, [key, baseUrl]);
+
+ async function save() {
+ setSaveError(null);
+ // Never save credentials that haven't passed a live check.
+ if (credentialsChanged || !p.configured) {
+ const ok = check.status === "done" && check.ok ? check : await runCheck();
+ if (!ok?.ok) return;
+ }
+ if (!model.trim()) { setSaveError({ message: "Pick a model.", field: "model" }); return; }
+ setSaving(true);
+ try {
+ let r = await modelsApi.save(p.id, { ...draft, model: model.trim(), enabled: true });
+ if (makeDefault && offerDefault && !r.restarting) r = { ...r, ...(await modelsApi.roles({ default: { provider: p.id, model: model.trim() } })) };
+ onSaved(r);
+ } catch (e) {
+ const field = e instanceof ApiError ? (e.data.field as string | undefined) : undefined;
+ setSaveError({ message: errorText(e), field });
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ const fieldError = (f: CheckField | "model") => (check.status === "done" && !check.ok && check.field === f ? check.error : saveError?.field === f ? saveError.message : undefined);
+ const generalError = check.status === "done" && !check.ok && !check.field ? check.error : saveError && !saveError.field ? saveError.message : undefined;
+
+ return (
+ <form className="flex flex-col gap-4" onSubmit={(e) => { e.preventDefault(); void save(); }}>
+ {p.signInOnly && (
+ <div className="rounded-lg border border-line bg-soft px-3 py-2.5 text-sm text-ink2">
+ {p.configured
+ ? <>Signed in. Pick the model to use below.</>
+ : <>{p.label} signs in with your account instead of a key. On the computer running Mercury, run <code className="rounded bg-ink/[0.06] px-1 font-mono text-xs">mercury doctor</code> and choose {p.label}, then come back here.</>}
+ </div>
+ )}
+
+ {showKey && (
+ <Field label={p.needsKey ? "API key" : "API key (optional)"} htmlFor={`key-${p.id}`}
+ hint={p.hasKey ? `Saved: ${p.apiKey}. Leave empty to keep it.` : p.needsKey ? "Stored on the computer running Mercury, never shown again in full." : "Only if your gateway asks for one."}>
+ <div className="flex gap-2">
+ <Input id={`key-${p.id}`} type="password" mono autoComplete="off" value={key} onChange={(e) => setKey(e.target.value)}
+ placeholder={p.hasKey ? "Keep the saved key" : p.keyHint ?? "Paste your key"} aria-invalid={!!fieldError("apiKey")} className={cx(fieldError("apiKey") && "border-red/60")} />
+ {p.keyUrl && (
+ <Button type="button" size="md" variant="ghost" onClick={() => void desktop.openExternal(p.keyUrl!)} title="Get a key"><KeyRound size={14} /> Get a key <ExternalLink size={12} /></Button>
+ )}
+ </div>
+ {fieldError("apiKey") && <p className="text-xs text-red">{fieldError("apiKey")}</p>}
+ </Field>
+ )}
+
+ {showUrl && (
+ <Field label={p.needsBaseUrl ? "Base URL" : "Address"} htmlFor={`url-${p.id}`}
+ hint={p.kind === "local" ? `Where ${p.label} listens. Start it first, then test.` : p.needsBaseUrl ? "The endpoint's /v1 URL, e.g. https://openrouter.ai/api/v1" : undefined}>
+ <Input id={`url-${p.id}`} mono value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="https://…/v1"
+ aria-invalid={!!fieldError("baseUrl")} className={cx(fieldError("baseUrl") && "border-red/60")} />
+ {fieldError("baseUrl") && <p className="text-xs text-red">{fieldError("baseUrl")}</p>}
+ </Field>
+ )}
+
+ {(!p.signInOnly || p.configured) && (
+ <div className="flex items-center gap-2">
+ <Button type="button" size="sm" variant="outline" loading={check.status === "checking"} disabled={!canCheckNow} onClick={() => void runCheck()}>
+ <RefreshCw size={13} /> {check.status === "done" && check.ok ? "Test again" : "Test connection"}
+ </Button>
+ {check.status === "done" && check.ok && (
+ <span className="flex items-center gap-1.5 text-xs text-accent"><CheckCircle2 size={13} /> Connected{check.ms !== undefined ? ` in ${check.ms} ms` : ""} · {check.models?.length ?? 0} models</span>
+ )}
+ {check.status === "idle" && credentialsChanged && <span className="text-xs text-ink4">Tested before saving.</span>}
+ </div>
+ )}
+ {generalError && <p className="rounded-md border border-red/30 bg-red/[0.05] px-3 py-2 text-xs text-red">{generalError}</p>}
+
+ {(!p.signInOnly || p.configured) && (
+ <Field label="Model" htmlFor={`model-${p.id}`} hint={check.status === "done" && check.ok ? "Every model this key can use. Type to search, or enter any id." : "Test the connection to list models, or type an id."}>
+ <ModelPicker id={`model-${p.id}`} value={model} onChange={setModel} models={check.status === "done" ? check.models ?? [] : []}
+ recommended={check.status === "done" ? check.recommendedModel : undefined} loading={check.status === "checking"} />
+ {fieldError("model") && <p className="text-xs text-red">{fieldError("model")}</p>}
+ </Field>
+ )}
+
+ {offerDefault && (!p.signInOnly || p.configured) && (
+ <label className="flex items-center gap-2 text-sm text-ink2">
+ <input type="checkbox" checked={makeDefault} onChange={(e) => setMakeDefault(e.target.checked)} className="accent-[var(--accent,#1A9E6E)]" />
+ Use as the default for chat and tasks
+ </label>
+ )}
+
+ {(!p.signInOnly || p.configured) && (
+ <div className="flex justify-end gap-2">
+ {onCancel && <Button type="button" variant="ghost" onClick={onCancel}>Cancel</Button>}
+ <Button type="submit" variant="primary" loading={saving || (check.status === "checking" && saving)} disabled={saving || check.status === "checking" || !canCheckNow}>
+ {saveLabel ?? (p.configured ? "Save" : "Connect")}
+ </Button>
+ </div>
+ )}
+ </form>
+ );
+}
+
+export function errorText(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}
diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsx
index 6b63cd4a..9996ca57 100644
--- a/apps/desktop/src/views/settings/SettingsView.tsx
+++ b/apps/desktop/src/views/settings/SettingsView.tsx
@@ -1,4 +1,4 @@
-import { Activity, Info, PanelBottom, Palette, Power, Server, Smartphone, UserRound } from "lucide-react";
+import { Activity, Boxes, Info, Mic, PanelBottom, Palette, Power, Server, Smartphone, UserRound } from "lucide-react";
import { useEffect, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
@@ -14,16 +14,20 @@ import { AddRemote } from "~/shell/AddRemote";
import { StateOrb } from "~/components/indicators/StateOrb";
import { Analytics } from "./Analytics";
import { Profile } from "./Profile";
+import { ModelsSettings } from "./Models";
+import { VoiceSettings } from "./Voice";
import { isVisible, orderedIds, useContributions, type ContributionArea } from "~/extensions/registry";
/**
* Settings: a section list on the left, one section on the right. Most-used
* first (Appearance), plain labels, every control explains itself in one line.
*/
-type Section = "profile" | "appearance" | "statusbar" | "analytics" | "connections" | "devices" | "startup" | "about";
+type Section = "profile" | "models" | "voice" | "appearance" | "statusbar" | "analytics" | "connections" | "devices" | "startup" | "about";
const SECTIONS: Array<{ id: Section; label: string; icon: typeof Palette }> = [
{ id: "profile", label: "Profile", icon: UserRound },
+ { id: "models", label: "Models", icon: Boxes },
+ { id: "voice", label: "Voice", icon: Mic },
{ id: "appearance", label: "Appearance", icon: Palette },
{ id: "statusbar", label: "Status bar", icon: PanelBottom },
{ id: "analytics", label: "Analytics", icon: Activity },
@@ -55,6 +59,8 @@ export function SettingsView({ connection, health, onSwitchConnection }: { conne
<div className={cx("mx-auto flex flex-col gap-6 px-8 py-8", section === "analytics" ? "max-w-[960px]" : "max-w-[680px]")}>
<h1 className="text-xl font-semibold tracking-tight text-ink">{SECTIONS.find((s) => s.id === section)?.label}</h1>
{section === "profile" && <Profile />}
+ {section === "models" && <ModelsSettings />}
+ {section === "voice" && <VoiceSettings onOpenModels={() => setSection("models")} />}
{section === "appearance" && <Appearance />}
{section === "statusbar" && <StatusBarSettings />}
{section === "analytics" && <Analytics />}
diff --git a/apps/desktop/src/views/settings/Voice.tsx b/apps/desktop/src/views/settings/Voice.tsx
new file mode 100644
index 00000000..8ecbe3b1
--- /dev/null
+++ b/apps/desktop/src/views/settings/Voice.tsx
@@ -0,0 +1,295 @@
+import { CheckCircle2, CircleAlert, ExternalLink, Mic } from "lucide-react";
+import { useCallback, useEffect, useState } from "react";
+import { fieldApplies, modelsApi, voiceApi, type ProviderSettings, type VoiceCheck, type VoiceField, type VoicePlugin, type VoiceVendor } from "~/api/models";
+import { useUi } from "~/app/store";
+import { Button } from "~/components/ui/Button";
+import { Input } from "~/components/ui/Input";
+import { Switch } from "~/components/ui/Switch";
+import { Badge, Spinner } from "~/components/ui/bits";
+import { cx } from "~/lib/cx";
+import { errorText } from "./Models";
+
+/**
+ * Voice: who listens and who speaks when you talk to Mercury. Lives in the
+ * Optimus plugin's settings; this screen shows only what applies to the
+ * chosen engine. Keys are tested against the vendor before they're saved,
+ * and voice/model menus fill from the vendor when it can list them.
+ */
+
+const VENDOR_OF: Record<string, VoiceVendor> = {
+ geminiKey: "gemini", elevenlabsKey: "elevenlabs", azureKey: "azure", qwenKey: "qwen", deepgramKey: "deepgram",
+ assemblyaiKey: "assemblyai", sarvamKey: "sarvam", cartesiaKey: "cartesia", minimaxKey: "minimax",
+};
+/** Engines that think and speak with a Mercury model provider's key (set under Models). */
+const ENGINE_PROVIDER: Record<string, { id: string; label: string }> = { openai: { id: "openai", label: "OpenAI" }, grok: { id: "grok", label: "Grok (xAI)" } };
+const HOW = ["mode", "hotkey", "muteHotkey"];
+const BEHAVIOUR = ["bargeIn", "thinkingSound", "idleStopSeconds", "maxSessionMinutes"];
+
+export function VoiceSettings({ onOpenModels }: { onOpenModels: () => void }) {
+ const [plugin, setPlugin] = useState<VoicePlugin | null | undefined>(undefined);
+ const [providers, setProviders] = useState<ProviderSettings | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** Voices / models a key check returned, by vendor, for the menus. */
+ const [lists, setLists] = useState<Partial<Record<VoiceVendor, VoiceCheck>>>({});
+ const setView = useUi((s) => s.setView);
+
+ const load = useCallback(async () => {
+ try {
+ const [pl, pr] = await Promise.all([voiceApi.plugin().catch(() => null), modelsApi.settings().catch(() => null)]);
+ setPlugin(pl);
+ setProviders(pr);
+ } catch (e) { setError(errorText(e)); }
+ }, []);
+ useEffect(() => { void load(); }, [load]);
+
+ const fields = plugin?.settings ?? [];
+ const values = Object.fromEntries(fields.map((f) => [f.key, f.value])) as Record<string, unknown>;
+ const engine = String(values.voiceEngine ?? "");
+
+ // Fill voice and model menus from keys that are already saved.
+ useEffect(() => {
+ for (const f of fields) {
+ const vendor = VENDOR_OF[f.key];
+ if (!vendor || !f.isSet || lists[vendor] || !fieldApplies(f, values) || !["elevenlabs", "cartesia", "gemini"].includes(vendor)) continue;
+ void voiceApi.check(vendor, undefined, String(values.azureEndpoint ?? "")).then((r) => setLists((l) => ({ ...l, [vendor]: r }))).catch(() => {});
+ }
+ }, [plugin]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ async function set(key: string, value: unknown) {
+ await voiceApi.set(key, value);
+ await load();
+ }
+
+ if (error) return <p className="text-sm text-red">{error}</p>;
+ if (plugin === undefined) return <Spinner size={16} />;
+ if (!plugin || !plugin.installedVersion) {
+ return (
+ <div className="flex items-start gap-3 rounded-xl border border-line bg-surface p-5">
+ <Mic size={18} className="mt-0.5 text-ink3" />
+ <div className="flex flex-1 flex-col gap-2">
+ <div className="text-base text-ink">Voice comes with the Optimus plugin</div>
+ <p className="text-sm text-ink3">Install Optimus to talk to Mercury out loud: a hotkey, live voice, and Mercury controlling your computer when you ask.</p>
+ <div><Button size="sm" variant="primary" onClick={() => setView("plugins")}>Open Plugins</Button></div>
+ </div>
+ </div>
+ );
+ }
+
+ const byKey = new Map(fields.map((f) => [f.key, f]));
+ const applies = (k: string) => { const f = byKey.get(k); return !!f && fieldApplies(f, values); };
+ const engineField = byKey.get("voiceEngine");
+ const engineFields = fields.filter((f) => f.group === "voice" && f.key !== "voiceEngine" && !BEHAVIOUR.includes(f.key) && fieldApplies(f, values));
+ const group = plugin.settingGroups?.find((g) => g.id === "voice");
+ const usesProvider = ENGINE_PROVIDER[engine];
+ const provider = usesProvider ? providers?.providers.find((p) => p.id === usesProvider.id) : undefined;
+
+ return (
+ <section className="flex flex-col gap-5">
+ <Card title="How you talk to Mercury">
+ {HOW.filter(applies).map((k) => <FieldRow key={k} f={byKey.get(k)!} onSave={set} lists={lists} values={values} />)}
+ </Card>
+
+ {engineField && applies("voiceEngine") && (
+ <Card title="Voice engine" badge={group ? (group.ready ? <Badge tone="accent">ready</Badge> : <Badge tone="amber">needs setup</Badge>) : null}
+ hint="Who listens and speaks. OpenAI is the most natural; “Mercury” lets your own model think, with separate speech services.">
+ <div className="grid grid-cols-2 gap-2">
+ {(engineField.options ?? []).map((o) => (
+ <button key={o} onClick={() => void set("voiceEngine", o)} aria-pressed={engine === o}
+ className={cx("rounded-lg border px-3 py-2.5 text-left transition-colors", engine === o ? "border-accent/60 bg-accent/[0.07]" : "border-line hover:border-ink/25")}>
+ <div className="text-sm font-medium text-ink">{ENGINE_NAMES[o] ?? o}</div>
+ {engineField.optionLabels?.[o] && <div className="mt-0.5 line-clamp-2 text-xs text-ink3">{stripName(engineField.optionLabels[o])}</div>}
+ </button>
+ ))}
+ </div>
+ </Card>
+ )}
+
+ {applies("voiceEngine") && (
+ <Card title={`${ENGINE_NAMES[engine] ?? engine} settings`}>
+ {usesProvider && (
+ <div className="flex items-center gap-3 rounded-lg border border-line bg-soft px-3 py-2.5">
+ {provider?.configured ? <CheckCircle2 size={15} className="text-accent" /> : <CircleAlert size={15} className="text-amber" />}
+ <div className="min-w-0 flex-1 text-sm text-ink2">
+ {provider?.configured ? <>Uses your <span className="text-ink">{usesProvider.label}</span> key from Models.</> : <>Needs an <span className="text-ink">{usesProvider.label}</span> key. Add it under Models; voice uses the same one.</>}
+ </div>
+ <Button size="sm" variant={provider?.configured ? "ghost" : "primary"} onClick={onOpenModels}>{provider?.configured ? "Change" : "Add key"}</Button>
+ </div>
+ )}
+ {engineFields.map((f) => <FieldRow key={f.key} f={f} onSave={set} lists={lists} values={values} onChecked={(v, r) => setLists((l) => ({ ...l, [v]: r }))} />)}
+ {engineFields.length === 0 && !usesProvider && <p className="text-sm text-ink3">Nothing else to set.</p>}
+ </Card>
+ )}
+
+ {BEHAVIOUR.some(applies) && (
+ <Card title="Behaviour">
+ {BEHAVIOUR.filter(applies).map((k) => <FieldRow key={k} f={byKey.get(k)!} onSave={set} lists={lists} values={values} />)}
+ </Card>
+ )}
+ </section>
+ );
+}
+
+const ENGINE_NAMES: Record<string, string> = { openai: "OpenAI", gemini: "Gemini", grok: "Grok", elevenlabs: "ElevenLabs", azure: "Azure OpenAI", qwen: "Qwen", mercury: "Mercury + speech services" };
+
+/** "OpenAI: the most natural…" → "the most natural…" (the card already shows the name). */
+function stripName(label: string): string {
+ return label.replace(/^[^:]{1,40}:\s*/, "");
+}
+
+function Card({ title, hint, badge, children }: { title: string; hint?: string; badge?: React.ReactNode; children: React.ReactNode }) {
+ return (
+ <div className="flex flex-col gap-3 rounded-xl border border-line bg-surface p-4">
+ <div>
+ <div className="flex items-center gap-2"><span className="text-base font-medium text-ink">{title}</span>{badge}</div>
+ {hint && <p className="mt-0.5 text-xs text-ink3">{hint}</p>}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+function humanize(key: string): string {
+ return key.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
+}
+
+/** Which vendor list fills a free-text field's menu. */
+function listFor(key: string, values: Record<string, unknown>, lists: Partial<Record<VoiceVendor, VoiceCheck>>): Array<{ value: string; label: string }> | null {
+ const voices = (v: VoiceVendor) => lists[v]?.voices?.map((x) => ({ value: x.id, label: x.name })) ?? null;
+ if (key === "elevenlabsVoice") return voices("elevenlabs");
+ if (key === "ttsVoice") return values.ttsProvider === "elevenlabs" ? voices("elevenlabs") : values.ttsProvider === "cartesia" ? voices("cartesia") : null;
+ if (key === "geminiModel") return lists.gemini?.models?.map((m) => ({ value: m, label: m })) ?? null;
+ return null;
+}
+
+function FieldRow({ f, onSave, lists, values, onChecked }: {
+ f: VoiceField;
+ onSave: (key: string, value: unknown) => Promise<void>;
+ lists: Partial<Record<VoiceVendor, VoiceCheck>>;
+ values: Record<string, unknown>;
+ onChecked?: (vendor: VoiceVendor, r: VoiceCheck) => void;
+}) {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const label = f.label ?? humanize(f.key);
+ async function save(v: unknown) {
+ setBusy(true);
+ setError(null);
+ try { await onSave(f.key, v); } catch (e) { setError(errorText(e)); } finally { setBusy(false); }
+ }
+
+ if (f.type === "secret") return <SecretRow f={f} label={label} vendor={VENDOR_OF[f.key]} endpoint={String(values.azureEndpoint ?? "")} onSave={(v) => onSave(f.key, v)} onChecked={onChecked} />;
+
+ let control: React.ReactNode;
+ if (f.type === "boolean") {
+ control = <Switch checked={!!f.value} onCheckedChange={(v) => void save(v)} disabled={busy} />;
+ } else if (f.type === "enum") {
+ control = (
+ <select value={String(f.value ?? "")} onChange={(e) => void save(e.target.value)} disabled={busy} aria-label={label}
+ className="h-9 w-[240px] rounded-md border border-line bg-surface px-2.5 text-sm text-ink">
+ {(f.options ?? []).map((o) => <option key={o} value={o}>{f.optionLabels?.[o] ? `${o}: ${stripName(f.optionLabels[o]).slice(0, 60)}` : o}</option>)}
+ </select>
+ );
+ } else {
+ const menu = listFor(f.key, values, lists);
+ control = menu && menu.length
+ ? (
+ <select value={String(f.value ?? "")} onChange={(e) => void save(e.target.value)} disabled={busy} aria-label={label}
+ className="h-9 w-[240px] rounded-md border border-line bg-surface px-2.5 text-sm text-ink">
+ {!menu.some((m) => m.value === f.value) && <option value={String(f.value ?? "")}>{String(f.value ?? "Default")}</option>}
+ {menu.map((m) => <option key={m.value} value={m.value}>{m.label}</option>)}
+ </select>
+ )
+ : <TextSetting f={f} label={label} busy={busy} onSave={save} />;
+ }
+ return (
+ <div className="flex items-center gap-4">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-ink">{label}</div>
+ {f.description && <div className="line-clamp-2 text-xs text-ink3">{f.description}</div>}
+ {error && <div className="text-xs text-red">{error}</div>}
+ </div>
+ <div className="flex shrink-0 items-center gap-2">{busy && <Spinner size={12} />}{control}</div>
+ </div>
+ );
+}
+
+function TextSetting({ f, label, busy, onSave }: { f: VoiceField; label: string; busy: boolean; onSave: (v: unknown) => Promise<void> }) {
+ const [v, setV] = useState(String(f.value ?? ""));
+ useEffect(() => { setV(String(f.value ?? "")); }, [f.value]);
+ const commit = () => {
+ if (v === String(f.value ?? "")) return;
+ if (f.type === "number") { const n = Number(v); if (!Number.isFinite(n) || n < 0) { setV(String(f.value ?? "")); return; } void onSave(n); }
+ else void onSave(v.trim());
+ };
+ const listId = f.examples?.length ? `ex-${f.key}` : undefined;
+ return (
+ <>
+ <Input value={v} onChange={(e) => setV(e.target.value)} onBlur={commit} onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); }}
+ type={f.type === "number" ? "number" : "text"} disabled={busy} aria-label={label} list={listId} className="w-[240px]" placeholder="Default" mono={f.type !== "number"} />
+ {listId && <datalist id={listId}>{f.examples!.map((x) => <option key={x} value={x} />)}</datalist>}
+ </>
+ );
+}
+
+/** A voice key: test it against the vendor, then save. Leaving it empty and testing checks the saved key. */
+function SecretRow({ f, label, vendor, endpoint, onSave, onChecked }: { f: VoiceField; label: string; vendor?: VoiceVendor; endpoint: string; onSave: (v: string) => Promise<void>; onChecked?: (vendor: VoiceVendor, r: VoiceCheck) => void }) {
+ const [key, setKey] = useState("");
+ const [result, setResult] = useState<VoiceCheck | null>(null);
+ const [busy, setBusy] = useState<"test" | "save" | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ async function test(): Promise<VoiceCheck | null> {
+ if (!vendor) return { ok: true, verified: false, message: "" };
+ setBusy("test");
+ setError(null);
+ try {
+ const r = await voiceApi.check(vendor, key.trim() || undefined, endpoint);
+ setResult(r);
+ if (r.ok) onChecked?.(vendor, r);
+ return r;
+ } catch (e) { setError(errorText(e)); return null; } finally { setBusy(null); }
+ }
+ async function save() {
+ const r = result && key ? result : await test();
+ if (!r?.ok) return;
+ setBusy("save");
+ try { await onSave(key.trim()); setKey(""); } catch (e) { setError(errorText(e)); } finally { setBusy(null); }
+ }
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-ink">{label}</span>
+ {f.isSet ? <Badge tone="accent">saved</Badge> : f.required ? <Badge tone="amber">required</Badge> : null}
+ </div>
+ <div className="flex gap-2">
+ <Input type="password" mono autoComplete="off" value={key} onChange={(e) => { setKey(e.target.value); setResult(null); }}
+ placeholder={f.isSet ? "Saved. Paste a new key to replace it" : "Paste the key"} aria-label={label} />
+ <Button size="md" variant="outline" loading={busy === "test"} disabled={!key.trim() && !f.isSet} onClick={() => void test()}>Test</Button>
+ <Button size="md" variant="primary" loading={busy === "save"} disabled={!key.trim()} onClick={() => void save()}>Save</Button>
+ </div>
+ {result && (
+ <p className={cx("flex items-center gap-1.5 text-xs", result.ok ? (result.verified ? "text-accent" : "text-ink3") : "text-red")}>
+ {result.ok ? <CheckCircle2 size={12} /> : <CircleAlert size={12} />}{result.message}
+ </p>
+ )}
+ {error && <p className="text-xs text-red">{error}</p>}
+ {f.description && <p className="text-2xs text-ink4">{f.description} {vendor && <VendorLink vendor={vendor} />}</p>}
+ </div>
+ );
+}
+
+const KEY_PAGES: Partial<Record<VoiceVendor, string>> = {
+ elevenlabs: "https://elevenlabs.io/app/settings/api-keys", deepgram: "https://console.deepgram.com", assemblyai: "https://www.assemblyai.com/app/api-keys",
+ cartesia: "https://play.cartesia.ai/keys", gemini: "https://aistudio.google.com/apikey", sarvam: "https://dashboard.sarvam.ai",
+};
+
+function VendorLink({ vendor }: { vendor: VoiceVendor }) {
+ const url = KEY_PAGES[vendor];
+ if (!url) return null;
+ return (
+ <button type="button" className="inline-flex items-center gap-0.5 text-accent hover:underline" onClick={() => void import("~/shell/tauri").then(({ desktop }) => desktop.openExternal(url))}>
+ Get a key <ExternalLink size={10} />
+ </button>
+ );
+}