Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(optimus): microphone & permissions on every OS, with a mic picker, off switch and live test
Salman Qureshi8b8278006605
diff --git a/apps/desktop/src/api/devices.ts b/apps/desktop/src/api/devices.tsnew file mode 100644index 00000000..0e610c92--- /dev/null+++ b/apps/desktop/src/api/devices.ts@@ -0,0 +1,99 @@+/* ═══════════════════════════════════════════════════════════════+ Microphone and permissions of desktop plugins (Optimus): what the OS+ lets them use, which microphone they listen with, and a live test.+ The runtime answers only from the computer it runs on.+ ═══════════════════════════════════════════════════════════════ */++import { http } from "./client";+import { openStream } from "./stream";++export type PermissionState = "granted" | "not-asked" | "denied" | "restricted" | "limited" | "unavailable";+export type PermissionKind = "microphone" | "screen" | "accessibility" | "camera";++export interface DevicePermission {+ kind: PermissionKind;+ label: string;+ state: PermissionState;+ detail: string;+ /** Exactly what to do on this OS and version; empty when nothing is needed. */+ steps: string[];+ /** The OS can show its own prompt (macOS). */+ canRequest: boolean;+ canOpenSettings: boolean;+ /** Something uses it today (the camera row stays hidden until a plugin does). */+ used: boolean;+}++export interface DeviceReport {+ platform: "macos" | "windows" | "linux";+ permissions: DevicePermission[];+ microphones: {+ devices: Array<{ name: string; default: boolean }>;+ systemDefault: string | null;+ /** The owner's pick; null means the system default. */+ selected: string | null;+ selectedConnected: boolean;+ on: boolean;+ };+}++export interface DevicePlugin {+ id: string;+ name: string;+ report?: DeviceReport;+ error?: string;+}++export interface MicTestResult {+ device: string;+ peak: number;+ average: number;+ heard: boolean;+ silent: boolean;+ text: string;+ steps: string[];+}++const enc = encodeURIComponent;++export const devicesApi = {+ list: () => http.get<{ plugins: DevicePlugin[] }>("/api/devices"),+ request: (id: string, kind: PermissionKind, openSettings = false) =>+ http.post<{ report: DeviceReport }>(`/api/devices/${enc(id)}/request`, { kind, openSettings }).then((r) => r.report),+ select: (id: string, patch: { microphone?: string; microphoneOn?: boolean }) =>+ http.post<{ report: DeviceReport }>(`/api/devices/${enc(id)}/select`, patch).then((r) => r.report),+};++/**+ * Listen on the plugin's microphone for `seconds`: `onLevel` gets 0..1 about+ * every 80 ms, then the result (or the reason it couldn't listen). Returns a+ * function that stops listening early.+ */+export function testMicrophone(id: string, seconds: number, on: { level: (n: number) => void; done: (r: MicTestResult) => void; error: (message: string) => void }): () => void {+ let finished = false;+ const finish = () => {+ if (finished) return;+ finished = true;+ handle.close();+ };+ const handle = openStream(`/api/devices/${enc(id)}/test?seconds=${seconds}`, {+ onEvent: (event, data) => {+ if (finished) return;+ if (event === "level") on.level(Number((JSON.parse(data) as { level: number }).level) || 0);+ else if (event === "done") {+ on.done(JSON.parse(data) as MicTestResult);+ finish();+ } else if (event === "error") {+ on.error((JSON.parse(data) as { error: string }).error);+ finish();+ }+ },+ // One test per press: never reconnect (that would start another test).+ onClose: (reason) => {+ if (finished || reason === "closed") return;+ on.error(reason === "unauthorized" ? "Sign in to Mercury again." : "Lost the connection to Mercury during the test.");+ finish();+ },+ });+ return finish;+}diff --git a/apps/desktop/src/styles/tokens.css b/apps/desktop/src/styles/tokens.cssindex 8858697f..7a0b78bb 100644--- a/apps/desktop/src/styles/tokens.css+++ b/apps/desktop/src/styles/tokens.css@@ -22,6 +22,7 @@--blue: 37 99 235; /* #2563EB unread */--amber: 183 121 31; /* #B7791F */--red: 197 48 48; /* #C53030 */+ --ok: 26 158 110; /* #1A9E6E allowed / working: green whatever the tint */--glow: 26 158 110;color-scheme: light;}@@ -41,6 +42,7 @@--blue: 96 165 250; /* #60A5FA unread */--amber: 245 196 81; /* #F5C451 */--red: 255 107 107; /* #FF6B6B */+ --ok: 52 225 161; /* #34E1A1 */--glow: 52 225 161;color-scheme: dark;}diff --git a/apps/desktop/src/views/plugins/PluginDetail.tsx b/apps/desktop/src/views/plugins/PluginDetail.tsxindex 28eda8c8..bf209048 100644--- a/apps/desktop/src/views/plugins/PluginDetail.tsx+++ b/apps/desktop/src/views/plugins/PluginDetail.tsx@@ -7,6 +7,8 @@ import { Switch } from "~/components/ui/Switch";import { Badge, Mono, Spinner } from "~/components/ui/bits";import { ConfirmButton, IconTile } from "~/components/ui/kit";import { cx } from "~/lib/cx";+import { useUi } from "~/app/store";+import { PermissionSummary } from "~/views/settings/Devices";import { ChannelPanel } from "./ChannelPanel";import { applies, SettingField } from "./SettingField";import { needsSetup, setupKeys } from "./SetupFlow";@@ -147,6 +149,12 @@ export function PluginDetail({ id, onSetup, onChanged, onRemoved }: { id: string</Section>)}+ {p.permissions?.desktop && p.running && (+ <Section title="Microphone & permissions">+ <PermissionSummary pluginId={id} onOpen={() => useUi.getState().openSettings("voice")} />+ </Section>+ )}+<Section title="What it can do and reach"><div className="grid grid-cols-1 gap-3 sm:grid-cols-2"><Fact icon={<Wrench size={13} />} title={`${p.tools.length} tool${p.tools.length === 1 ? "" : "s"}${p.commands.length ? ` · ${p.commands.length} command${p.commands.length === 1 ? "" : "s"}` : ""}`}diff --git a/apps/desktop/src/views/settings/Devices.test.ts b/apps/desktop/src/views/settings/Devices.test.tsnew file mode 100644index 00000000..12089ff5--- /dev/null+++ b/apps/desktop/src/views/settings/Devices.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it, vi } from "vitest";+import type { StreamHandlers } from "~/api/stream";++/**+ * The microphone test: levels draw the meter (grey, green, orange), the+ * result arrives once, and a dropped connection never starts a second test.+ */++const streams: Array<{ path: string; handlers: StreamHandlers; closed: boolean }> = [];+vi.mock("~/api/stream", () => ({+ openStream: (path: string, handlers: StreamHandlers) => {+ const s = { path, handlers, closed: false };+ streams.push(s);+ return { close: () => { s.closed = true; handlers.onClose?.("closed"); }, get open() { return !s.closed; } };+ },+}));++const { testMicrophone } = await import("~/api/devices");+const { meterState, segmentTone } = await import("./Devices");++function run() {+ const seen = { levels: [] as number[], done: [] as unknown[], errors: [] as string[] };+ testMicrophone("optimus", 6, { level: (n) => seen.levels.push(n), done: (r) => seen.done.push(r), error: (m) => seen.errors.push(m) });+ return { seen, stream: streams[streams.length - 1] };+}++describe("microphone test", () => {+ it("asks the plugin's test route, passes levels on, and stops after the result", () => {+ const { seen, stream } = run();+ expect(stream.path).toBe("/api/devices/optimus/test?seconds=6");+ stream.handlers.onEvent("level", JSON.stringify({ level: 0.2 }));+ stream.handlers.onEvent("level", JSON.stringify({ level: 0.9 }));+ stream.handlers.onEvent("done", JSON.stringify({ heard: true, text: "works", steps: [] }));+ stream.handlers.onEvent("level", JSON.stringify({ level: 0.5 }));+ expect(seen.levels).toEqual([0.2, 0.9]);+ expect(seen.done).toHaveLength(1);+ expect(stream.closed).toBe(true);+ expect(seen.errors).toEqual([]);+ });++ it("shows the plugin's reason when it can't listen", () => {+ const { seen, stream } = run();+ stream.handlers.onEvent("error", JSON.stringify({ error: "macOS is blocking the microphone for Optimus." }));+ expect(seen.errors).toEqual(["macOS is blocking the microphone for Optimus."]);+ expect(stream.closed).toBe(true);+ });++ it("a dropped connection ends the test with a reason instead of reconnecting into a new one", () => {+ const { seen, stream } = run();+ stream.handlers.onClose?.("error");+ expect(seen.errors).toEqual(["Lost the connection to Mercury during the test."]);+ expect(stream.closed).toBe(true);+ });+});++describe("level meter", () => {+ it("reads idle, silent, speech and loud", () => {+ expect(meterState(0.5, false)).toBe("idle");+ expect(meterState(0, true)).toBe("silent");+ expect(meterState(Number.NaN, true)).toBe("silent");+ expect(meterState(0.3, true)).toBe("speech");+ expect(meterState(0.95, true)).toBe("loud");+ });++ it("lights green segments for speech and orange ones near the top", () => {+ expect(segmentTone(0, 0)).toBe("off");+ expect(segmentTone(0, 0.3)).toBe("ok");+ expect(segmentTone(10, 0.3)).toBe("off");+ expect(segmentTone(18, 1)).toBe("ok");+ expect(segmentTone(20, 1)).toBe("loud");+ expect(segmentTone(23, 2)).toBe("loud");+ });+});diff --git a/apps/desktop/src/views/settings/Devices.tsx b/apps/desktop/src/views/settings/Devices.tsxnew file mode 100644index 00000000..ea5db2e9--- /dev/null+++ b/apps/desktop/src/views/settings/Devices.tsx@@ -0,0 +1,398 @@+import { Check, ChevronDown, ExternalLink, Mic, MicOff, RefreshCw } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { devicesApi, testMicrophone, type DevicePermission, type DevicePlugin, type DeviceReport, type MicTestResult, type PermissionState } from "~/api/devices";+import { ApiError } from "~/api/client";+import * as api from "~/api/mercury";+import { Button } from "~/components/ui/Button";+import { Menu, MenuItem, MenuLabel, MenuSeparator } from "~/components/ui/Menu";+import { Switch } from "~/components/ui/Switch";+import { Badge, Spinner } from "~/components/ui/bits";+import { cx } from "~/lib/cx";+import { errorText } from "./Models";++/**+ * Microphone & permissions: for each plugin that uses this computer+ * (Optimus), what the OS lets it use, which microphone it listens with,+ * whether it may use one at all, and a live test.+ *+ * Every line comes from the plugin running on the OS in question, so the+ * steps name the real settings page on this OS and version. Coming back to+ * the app (after flipping a switch in System Settings) checks again.+ */++const TEST_SECONDS = 6;++export function DevicesCard() {+ const [plugins, setPlugins] = useState<DevicePlugin[] | null>(null);+ const [remote, setRemote] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const load = useCallback(async () => {+ try {+ const r = await devicesApi.list();+ setPlugins(r.plugins);+ setRemote(false);+ setError(null);+ } catch (e) {+ if (e instanceof ApiError && e.data.remote) setRemote(true);+ else setError(errorText(e));+ }+ }, []);++ useEffect(() => {+ void load();+ // Back from System Settings / Windows Settings: show the new state.+ const onFocus = () => void load();+ window.addEventListener("focus", onFocus);+ return () => window.removeEventListener("focus", onFocus);+ }, [load]);++ if (remote) {+ return (+ <Shell>+ <p className="text-sm text-ink3">This app is connected to Mercury on another computer. The microphone and permissions belong to that computer: open Mercury there to set them.</p>+ </Shell>+ );+ }+ if (error) return <Shell><p className="text-sm text-red">{error}</p></Shell>;+ if (!plugins) return <Shell><Spinner size={16} /></Shell>;+ if (plugins.length === 0) {+ return (+ <Shell>+ <p className="text-sm text-ink3">Optimus isn't running. Turn it on in Plugins to set up its microphone and permissions.</p>+ </Shell>+ );+ }+ return (+ <>+ {plugins.map((p) => (+ <PluginDevices key={p.id} plugin={p} multiple={plugins.length > 1} onChange={(report) => setPlugins((list) => list?.map((x) => (x.id === p.id ? { ...x, report } : x)) ?? null)} onReload={load} />+ ))}+ </>+ );+}++function Shell({ children, badge, title = "Microphone & permissions" }: { children: React.ReactNode; badge?: React.ReactNode; title?: string }) {+ return (+ <div className="flex flex-col gap-3 rounded-xl border border-line bg-surface p-4">+ <div className="flex items-center gap-2">+ <span className="text-base font-medium text-ink">{title}</span>+ {badge}+ </div>+ {children}+ </div>+ );+}++function PluginDevices({ plugin, multiple, onChange, onReload }: { plugin: DevicePlugin; multiple: boolean; onChange: (r: DeviceReport) => void; onReload: () => Promise<void> }) {+ const [updating, setUpdating] = useState(false);+ const title = multiple ? `${plugin.name}: microphone & permissions` : "Microphone & permissions";+ if (!plugin.report) {+ const outdated = /update it/i.test(plugin.error ?? "");+ return (+ <Shell title={title} badge={<Badge tone="amber">{outdated ? "update needed" : "unavailable"}</Badge>}>+ <p className="text-sm text-ink3">{plugin.error}</p>+ {outdated && (+ <div>+ <Button size="sm" variant="primary" disabled={updating} onClick={() => { setUpdating(true); void api.plugins.update(plugin.id).then(onReload).catch(() => {}).finally(() => setUpdating(false)); }}>+ {updating ? <Spinner size={13} /> : null} Update {plugin.name}+ </Button>+ </div>+ )}+ </Shell>+ );+ }+ const report = plugin.report;+ const shown = report.permissions.filter((p) => p.used);+ const needsYou = shown.some((p) => p.state !== "granted") || !report.microphones.on;+ return (+ <Shell title={title} badge={needsYou ? <Badge tone="amber">needs attention</Badge> : <Badge tone="accent">ready</Badge>}>+ <Microphone id={plugin.id} name={plugin.name} report={report} onChange={onChange} />+ <div className="flex flex-col divide-y divide-line rounded-lg border border-line">+ {shown.map((p) => <PermissionRow key={p.kind} id={plugin.id} platform={report.platform} p={p} onChange={onChange} />)}+ </div>+ <div className="flex justify-end">+ <Button size="sm" variant="ghost" onClick={() => void onReload()}><RefreshCw size={13} /> Recheck</Button>+ </div>+ </Shell>+ );+}++// ── Microphone: on/off, which one, test ─────────────────────────────++function Microphone({ id, name, report, onChange }: { id: string; name: string; report: DeviceReport; onChange: (r: DeviceReport) => void }) {+ const mics = report.microphones;+ const [busy, setBusy] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ const micPermission = report.permissions.find((p) => p.kind === "microphone");++ async function select(patch: { microphone?: string; microphoneOn?: boolean }) {+ setBusy(true);+ setProblem(null);+ try {+ onChange(await devicesApi.select(id, patch));+ } catch (e) {+ setProblem(errorText(e));+ } finally {+ setBusy(false);+ }+ }++ const current = mics.selected ?? mics.systemDefault;+ const label = mics.selected ? mics.selected : `System default${mics.systemDefault ? ` (${mics.systemDefault})` : ""}`;+ return (+ <div className="flex flex-col gap-3 rounded-lg border border-line bg-soft p-3">+ <div className="flex items-center gap-3">+ {mics.on ? <Mic size={16} className="text-ink2" /> : <MicOff size={16} className="text-ink4" />}+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium text-ink">Microphone</div>+ <div className="text-xs text-ink3">{mics.on ? `${name} listens with the microphone you pick here.` : `${name} won't open any microphone until you turn this on.`}</div>+ </div>+ <Switch checked={mics.on} disabled={busy} onCheckedChange={(v) => void select({ microphoneOn: v })} label="Let Optimus use the microphone" />+ </div>++ {mics.on && (+ <>+ <div className="flex items-center gap-2">+ <span className="w-20 shrink-0 text-xs text-ink3">Device</span>+ {mics.devices.length === 0 ? (+ <span className="text-sm text-amber">No microphone found on this computer.</span>+ ) : (+ <Menu+ trigger={+ <button disabled={busy} className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md border border-line bg-surface px-2.5 text-left text-sm text-ink hover:border-line-strong">+ <span className="min-w-0 flex-1 truncate">{label}</span>+ <ChevronDown size={14} className="shrink-0 text-ink3" />+ </button>+ }+ >+ <MenuItem selected={!mics.selected} onSelect={() => void select({ microphone: "" })} hint={mics.systemDefault ?? undefined}>System default</MenuItem>+ <MenuSeparator />+ <MenuLabel>Microphones on this computer</MenuLabel>+ {mics.devices.map((d) => (+ <MenuItem key={d.name} selected={mics.selected === d.name} onSelect={() => void select({ microphone: d.name })} hint={d.default ? "default" : undefined}>{d.name}</MenuItem>+ ))}+ </Menu>+ )}+ </div>+ {mics.selected && !mics.selectedConnected && (+ <p className="text-xs text-amber">"{mics.selected}" isn't connected right now, so {name} uses the system default{mics.systemDefault ? ` (${mics.systemDefault})` : ""} until it's back.</p>+ )}+ <MicTest id={id} device={current} blocked={micPermission ? micPermission.state !== "granted" : false} />+ </>+ )}+ {problem && <p className="text-xs text-red">{problem}</p>}+ </div>+ );+}++function MicTest({ id, device, blocked }: { id: string; device: string | null; blocked: boolean }) {+ const [running, setRunning] = useState(false);+ const [level, setLevel] = useState(0);+ const [result, setResult] = useState<MicTestResult | null>(null);+ const [problem, setProblem] = useState<string | null>(null);+ const [left, setLeft] = useState(0);+ const stop = useRef<(() => void) | null>(null);++ useEffect(() => () => stop.current?.(), []);+ useEffect(() => {+ if (!running) return;+ const started = Date.now();+ const t = setInterval(() => setLeft(Math.max(0, TEST_SECONDS - Math.floor((Date.now() - started) / 1000))), 250);+ return () => clearInterval(t);+ }, [running]);++ function start() {+ setResult(null);+ setProblem(null);+ setLevel(0);+ setLeft(TEST_SECONDS);+ setRunning(true);+ stop.current = testMicrophone(id, TEST_SECONDS, {+ level: setLevel,+ done: (r) => { setResult(r); setRunning(false); setLevel(0); },+ error: (m) => { setProblem(m); setRunning(false); setLevel(0); },+ });+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <span className="w-20 shrink-0 text-xs text-ink3">Level</span>+ <LevelMeter level={level} active={running} />+ <Button size="sm" variant={running ? "ghost" : "outline"} disabled={!device && !running} onClick={() => (running ? (stop.current?.(), setRunning(false), setLevel(0)) : start())}>+ {running ? `Stop (${left}s)` : "Test"}+ </Button>+ </div>+ {running && <p className="pl-[88px] text-xs text-ink3">Say a few words at your normal volume.</p>}+ {!running && blocked && !result && !problem && <p className="pl-[88px] text-xs text-amber">Allow the microphone below first: until then the test only hears silence.</p>}+ {result && (+ <div className="ml-[88px] flex flex-col gap-1.5">+ <p className={cx("text-xs", result.heard ? "text-ok" : "text-amber")}>{result.text}</p>+ {result.steps.length > 0 && <Steps steps={result.steps} />}+ </div>+ )}+ {problem && <p className="ml-[88px] text-xs text-red">{problem}</p>}+ </div>+ );+}++const SEGMENTS = 24;++/** What the meter says about a level: nothing while idle, then silent, speech or loud. */+export function meterState(level: number, active: boolean): "idle" | "silent" | "speech" | "loud" {+ if (!active) return "idle";+ if (!(level >= 0.03)) return "silent";+ return level > 0.85 ? "loud" : "speech";+}++/** Segment i of the meter at this level: off, green, or orange near the top. */+export function segmentTone(i: number, level: number): "off" | "ok" | "loud" {+ const lit = Math.round(Math.max(0, Math.min(1, Number.isFinite(level) ? level : 0)) * SEGMENTS);+ if (i >= lit) return "off";+ return i >= SEGMENTS * 0.8 ? "loud" : "ok";+}++/**+ * The live input level: grey while silent, green for speech, orange when it's+ * loud enough to distort. 24 segments, so small movements still show.+ */+export function LevelMeter({ level, active }: { level: number; active: boolean }) {+ const state = meterState(level, active);+ return (+ <div className="flex min-w-0 flex-1 items-center gap-2" role="meter" aria-label="Microphone level" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(level * 100)}>+ <div className="flex h-3 flex-1 items-center gap-[3px]">+ {Array.from({ length: SEGMENTS }, (_, i) => (+ <span+ key={i}+ className={cx(+ "h-full flex-1 rounded-[2px] transition-colors duration-75",+ { off: "bg-ink/[0.08]", ok: "bg-ok", loud: "bg-amber" }[segmentTone(i, level)],+ )}+ />+ ))}+ </div>+ <span className={cx("w-14 shrink-0 text-right text-xs", state === "speech" ? "text-ok" : state === "loud" ? "text-amber" : "text-ink4")}>+ {state === "idle" ? "" : state === "silent" ? "silent" : state === "loud" ? "loud" : "hearing"}+ </span>+ </div>+ );+}++// ── Permissions ─────────────────────────────────────────────────────++const DOT: Record<PermissionState, string> = {+ granted: "bg-ok",+ "not-asked": "bg-amber",+ limited: "bg-amber",+ denied: "bg-red",+ restricted: "bg-red",+ unavailable: "bg-red",+};++const WORD: Record<PermissionState, string> = {+ granted: "Allowed",+ "not-asked": "Not asked yet",+ limited: "Limited",+ denied: "Blocked",+ restricted: "Restricted",+ unavailable: "Unavailable",+};++const SETTINGS_NAME: Record<DeviceReport["platform"], string> = {+ macos: "Open System Settings",+ windows: "Open Windows Settings",+ linux: "Open settings",+};++function PermissionRow({ id, platform, p, onChange }: { id: string; platform: DeviceReport["platform"]; p: DevicePermission; onChange: (r: DeviceReport) => void }) {+ const [busy, setBusy] = useState<"allow" | "settings" | null>(null);+ const [problem, setProblem] = useState<string | null>(null);+ const [open, setOpen] = useState(p.state !== "granted");+ useEffect(() => { if (p.state !== "granted") setOpen(true); }, [p.state]);++ async function act(openSettings: boolean) {+ setBusy(openSettings ? "settings" : "allow");+ setProblem(null);+ try {+ onChange(await devicesApi.request(id, p.kind, openSettings));+ } catch (e) {+ setProblem(errorText(e));+ } finally {+ setBusy(null);+ }+ }++ const ok = p.state === "granted";+ return (+ <div className="flex flex-col gap-2 px-3 py-2.5">+ <button className="flex items-center gap-3 text-left" onClick={() => setOpen((v) => !v)} aria-expanded={open}>+ <span className={cx("h-2.5 w-2.5 shrink-0 rounded-full", DOT[p.state])} aria-hidden="true" />+ <span className="min-w-0 flex-1">+ <span className="block text-sm text-ink">{p.label}</span>+ {!open && <span className="block truncate text-xs text-ink3">{p.detail}</span>}+ </span>+ <span className={cx("shrink-0 text-xs", ok ? "text-ok" : p.state === "not-asked" || p.state === "limited" ? "text-amber" : "text-red")}>+ {ok && <Check size={12} className="mr-1 inline" />}{WORD[p.state]}+ </span>+ </button>+ {open && (+ <div className="flex flex-col gap-2 pl-[22px]">+ <p className="text-xs text-ink3">{p.detail}</p>+ {!ok && p.steps.length > 0 && <Steps steps={p.steps} />}+ {!ok && (p.canRequest || p.canOpenSettings) && (+ <div className="flex flex-wrap gap-2">+ {p.canRequest && (+ <Button size="sm" variant="primary" disabled={!!busy} onClick={() => void act(false)}>+ {busy === "allow" ? <Spinner size={13} /> : null} Allow+ </Button>+ )}+ {p.canOpenSettings && (+ <Button size="sm" variant={p.canRequest ? "ghost" : "primary"} disabled={!!busy} onClick={() => void act(true)}>+ {busy === "settings" ? <Spinner size={13} /> : <ExternalLink size={13} />} {SETTINGS_NAME[platform]}+ </Button>+ )}+ </div>+ )}+ {busy === "allow" && p.kind === "microphone" && platform === "macos" && <p className="text-xs text-ink3">Answer the macOS prompt for Optimus. It may appear behind this window.</p>}+ {problem && <p className="text-xs text-red">{problem}</p>}+ </div>+ )}+ </div>+ );+}++function Steps({ steps }: { steps: string[] }) {+ return (+ <ol className="flex list-decimal flex-col gap-1 pl-4 text-xs text-ink2 marker:text-ink4">+ {steps.map((s, i) => <li key={i} className="pl-1">{s}</li>)}+ </ol>+ );+}++/** One line per permission for the plugin's own page: dot, name, state. */+export function PermissionSummary({ pluginId, onOpen }: { pluginId: string; onOpen: () => void }) {+ const [report, setReport] = useState<DeviceReport | null>(null);+ useEffect(() => {+ let alive = true;+ void devicesApi.list().then((r) => { if (alive) setReport(r.plugins.find((p) => p.id === pluginId)?.report ?? null); }).catch(() => {});+ return () => { alive = false; };+ }, [pluginId]);+ if (!report) return null;+ const shown = report.permissions.filter((p) => p.used);+ return (+ <div className="flex flex-col gap-2 rounded-lg border border-line p-3">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5">+ {shown.map((p) => (+ <span key={p.kind} className="flex items-center gap-1.5 text-xs text-ink2">+ <span className={cx("h-2 w-2 rounded-full", DOT[p.state])} aria-hidden="true" />+ {p.label}+ <span className="text-ink4">{WORD[p.state].toLowerCase()}</span>+ </span>+ ))}+ {!report.microphones.on && <span className="flex items-center gap-1.5 text-xs text-ink2"><MicOff size={12} className="text-ink4" /> microphone off</span>}+ </div>+ <div><Button size="sm" variant="ghost" onClick={onOpen}>Microphone & permissions</Button></div>+ </div>+ );+}diff --git a/apps/desktop/src/views/settings/Voice.tsx b/apps/desktop/src/views/settings/Voice.tsxindex 8ecbe3b1..e74e41f2 100644--- a/apps/desktop/src/views/settings/Voice.tsx+++ b/apps/desktop/src/views/settings/Voice.tsx@@ -7,6 +7,7 @@ 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 { DevicesCard } from "./Devices";import { errorText } from "./Models";/**@@ -85,6 +86,8 @@ export function VoiceSettings({ onOpenModels }: { onOpenModels: () => void }) {return (<section className="flex flex-col gap-5">+ <DevicesCard />+<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>diff --git a/apps/desktop/tailwind.config.js b/apps/desktop/tailwind.config.jsindex 98fceb28..2874322f 100644--- a/apps/desktop/tailwind.config.js+++ b/apps/desktop/tailwind.config.js@@ -24,6 +24,7 @@ export default {blue: "rgb(var(--blue) / <alpha-value>)",amber: "rgb(var(--amber) / <alpha-value>)",red: "rgb(var(--red) / <alpha-value>)",+ ok: "rgb(var(--ok) / <alpha-value>)",white: "#ffffff",black: "#000000",},diff --git a/plugins/optimus/README.md b/plugins/optimus/README.mdindex 40c0677d..fc34fcfb 100644--- a/plugins/optimus/README.md+++ b/plugins/optimus/README.md@@ -17,9 +17,11 @@ Setup asks:Change any of it later in `/plugins optimus`.-- **macOS:** Optimus builds `Optimus.app` in its data folder and signs it with a certificate made on your Mac (no Apple account involved), then asks for two permissions in System Settings → Privacy & Security: **Accessibility** (mouse and keyboard) and **Screen Recording** (seeing the screen). The permissions survive updates. macOS asks you to confirm Screen Recording again about once a month.-- **Windows:** nothing to grant. Windows running as administrator (Task Manager, installers) can't be controlled yet.-- **Linux:** works fully on X11. On Wayland, screenshots go through the desktop's screen-sharing prompt, and input and the talk key reach only X11 apps for now (use chat, or the `listen` tool).+- **macOS:** Optimus builds `Optimus.app` in its data folder and signs it with a certificate made on your Mac (no Apple account involved), then asks for three permissions in System Settings → Privacy & Security: **Accessibility** (mouse and keyboard), **Screen Recording** (seeing the screen) and, if you talk to it, the **Microphone**. The permissions survive updates. macOS asks you to confirm Screen Recording again about once a month.+- **Windows:** Windows never asks per app. The microphone works when Settings → Privacy & security → Microphone has "Microphone access" and "Let desktop apps access your microphone" on (Windows 10: Settings → Privacy → Microphone, "Allow desktop apps…"). Windows running as administrator (Task Manager, installers) can't be controlled yet.+- **Linux:** works fully on X11. On Wayland, screenshots go through the desktop's screen-sharing prompt, and input and the talk key reach only X11 apps for now (use chat, or the `listen` tool). Linux has no microphone permission: Optimus reaches the microphone through PipeWire or PulseAudio in your desktop session.++**Microphone & permissions in Mercury Desktop** (Settings → AI → Voice) shows each of these for your OS with a green, amber or red dot, the exact steps to fix one that's off, an Allow button where the OS can prompt (macOS) and a button that opens the right settings page. Pick which microphone Optimus listens with, turn the microphone off for Optimus altogether, and press **Test** for a live level meter (grey when silent, green for speech, orange when loud). A blocked microphone is reported when a session starts, instead of Optimus hearing silence.## Talking to it@@ -30,7 +32,6 @@ Change any of it later in `/plugins optimus`.- **Saying "stop"** ("cancel", "ruko", "bas") halts every action and the task at once; **"bye"** does the same and ends the session. Silence for 60 seconds ends it too.- Links and details go to your Mercury chat. Approvals are asked out loud.- With speakers, the mic is muted while Mercury talks so it doesn't hear itself. With headphones, turn on "I use headphones" in `/plugins optimus` → 🎙 Voice to interrupt just by talking.-- macOS asks once for the **Microphone** for Optimus.## What it can dodiff --git a/plugins/optimus/companion/Cargo.lock b/plugins/optimus/companion/Cargo.lockindex 52f7e4b8..7e49c6d9 100644--- a/plugins/optimus/companion/Cargo.lock+++ b/plugins/optimus/companion/Cargo.lock@@ -1280,9 +1280,10 @@ dependencies = [[[package]]name = "mercury-optimus"-version = "0.5.0"+version = "0.5.1"dependencies = ["base64 0.22.1",+ "block2","core-foundation","core-graphics 0.24.0","cpal",@@ -1293,6 +1294,7 @@ dependencies = ["image","objc2","objc2-app-kit",+ "objc2-av-foundation","objc2-foundation","objc2-quartz-core","serde_json",diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.tomlindex c785242e..4fea7404 100644--- a/plugins/optimus/companion/Cargo.toml+++ b/plugins/optimus/companion/Cargo.toml@@ -1,6 +1,6 @@[package]name = "mercury-optimus"-version = "0.5.0"+version = "0.5.1"edition = "2024"rust-version = "1.94"description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps, voice)"@@ -31,6 +31,9 @@ objc2-foundation = { version = "0.3", features = ["NSString", "NSGeometry", "NSTobjc2-app-kit = { version = "0.3", features = ["objc2-core-graphics", "objc2-quartz-core", "NSApplication", "NSWindow", "NSPanel", "NSView", "NSColor", "NSTextField", "NSControl", "NSResponder", "NSGraphics", "NSFont", "NSText", "NSScreen", "NSRunningApplication"] }objc2-quartz-core = { version = "0.3", features = ["CALayer", "objc2-core-foundation"] }dispatch2 = "0.3"+# Microphone (and, later, camera) permission: ask and read it as Optimus.app.+objc2-av-foundation = { version = "0.3", default-features = false, features = ["std", "AVCaptureDevice", "AVMediaFormat", "block2"] }+block2 = "0.6"[target.'cfg(target_os = "linux")'.dependencies]x11rb = { version = "0.13", features = ["xfixes", "shape"] }@@ -39,7 +42,7 @@ x11rb = { version = "0.13", features = ["xfixes", "shape"] }wayland-sys = { version = "0.31", features = ["client", "dlopen"] }[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.61", features = ["Win32_UI_HiDpi", "Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader"] }+windows-sys = { version = "0.61", features = ["Win32_UI_HiDpi", "Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry"] }[profile.release]opt-level = 3diff --git a/plugins/optimus/companion/src/audio.rs b/plugins/optimus/companion/src/audio.rsindex c2d295bb..171be731 100644--- a/plugins/optimus/companion/src/audio.rs+++ b/plugins/optimus/companion/src/audio.rs@@ -1,7 +1,8 @@//! Microphone and speaker for listening mode (cpal, every OS).//!//! The voice links speak 16 kHz mono PCM16 in 60 ms frames (like a phone-//! call). Here the default input is mixed to mono and resampled to that, and+//! call). Here the owner's microphone (devices.rs: their pick, or the system+//! default) is mixed to mono and resampled to that, and//! link audio is resampled to the default output's rate and played.//!//! Without headphones the mic would hear Mercury's own voice; `Output`@@ -149,7 +150,7 @@ impl Audio {}}-/// Open the default microphone and speaker. The streams live on their own+/// Open the owner's microphone and the default speaker. The streams live on their own/// thread (they aren't Send on every OS) until the returned `Audio` is dropped.pub fn open() -> Result<Audio, String> {let (mic_tx, mic_rx) = mpsc::unbounded_channel::<Vec<i16>>();@@ -161,7 +162,10 @@ pub fn open() -> Result<Audio, String> {.spawn(move || {let host = cpal::default_host();let started = (|| -> Result<(cpal::Stream, cpal::Stream, Arc<Output>, String), String> {- let input = host.default_input_device().ok_or("no microphone found")?;+ let (input, note) = crate::devices::input_device()?;+ if let Some(n) = note {+ crate::core::log(n);+ }let output = host.default_output_device().ok_or("no speaker found")?;let in_cfg = input.default_input_config().map_err(|e| format!("microphone: {e}"))?;let out_cfg = output.default_output_config().map_err(|e| format!("speaker: {e}"))?;diff --git a/plugins/optimus/companion/src/core.rs b/plugins/optimus/companion/src/core.rsindex cd9eda36..52590520 100644--- a/plugins/optimus/companion/src/core.rs+++ b/plugins/optimus/companion/src/core.rs@@ -184,6 +184,25 @@ pub fn run(inbox: std::sync::mpsc::Receiver<Value>, send: impl Fn(Value) + Send});continue;}+ // The "Microphone & permissions" screen: not screen work, so not behind the ops lock.+ if name.starts_with("device_") {+ rt.spawn_blocking(move || {+ let r = match name.as_str() {+ "device_status" => Ok(crate::devices::status()),+ "device_request" => crate::devices::request(&args),+ "device_select" => crate::devices::select(&args),+ "device_test" if sh.session.lock().unwrap().is_some() => {+ Err("A voice session is using the microphone right now: its level shows in the call. Test again after it ends.".into())+ }+ "device_test" => crate::devices::mic_test(&args, |level| {+ sh.out.notify("mercury/device/level", json!({ "kind": "microphone", "level": level }));+ }),+ other => Err(format!("unknown device operation {other}")),+ };+ sh.out.op_result(id, r);+ });+ continue;+ }// In a voice session, say what's happening as it happens.if let Some(line) = narration(&name, &args) {if let Some(s) = shared.session.lock().unwrap().as_ref() {diff --git a/plugins/optimus/companion/src/devices.rs b/plugins/optimus/companion/src/devices.rsnew file mode 100644index 00000000..e0ed6522--- /dev/null+++ b/plugins/optimus/companion/src/devices.rs@@ -0,0 +1,941 @@+//! What the OS lets Optimus use, which microphone it listens with, and a+//! live microphone test, for Mercury's "Microphone & permissions" screen.+//!+//! Every platform answers in the same shape, but with its own facts: macOS+//! asks per app (Optimus.app) and can prompt; Windows has privacy switches+//! and never prompts a desktop app; Linux has no permission at all, only a+//! sound server that has to be reachable. Each entry carries the exact steps+//! for this OS and version, never a generic "check your settings".+//!+//! The owner's choices (which microphone, and whether Optimus may use it at+//! all) live in `<plugin data>/devices.json`, so they apply at once, without+//! restarting the plugin.++use std::path::PathBuf;+use std::time::{Duration, Instant};++use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};+use serde_json::{Value, json};++// ── The owner's choices ────────────────────────────────────────────────++pub struct Prefs {+ /// The microphone's name, or None for the system default.+ pub mic: Option<String>,+ /// Off: Optimus never opens a microphone.+ pub mic_on: bool,+}++fn data_dir() -> PathBuf {+ std::env::var_os("MERCURY_PLUGIN_DATA_DIR").map(PathBuf::from).unwrap_or_else(|| {+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).unwrap_or_else(|| ".".into());+ PathBuf::from(home).join(".mercury").join("optimus")+ })+}++fn prefs_path() -> PathBuf {+ data_dir().join("devices.json")+}++pub fn prefs() -> Prefs {+ let v: Value = std::fs::read_to_string(prefs_path()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}));+ Prefs {+ mic: v.get("microphone").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string),+ mic_on: v.get("microphoneOn").and_then(Value::as_bool).unwrap_or(true),+ }+}++/// Change what the owner picked: `microphone` (a name, or "" for the system default) and/or `microphoneOn`.+pub fn select(args: &Value) -> Result<Value, String> {+ let mut p = prefs();+ if let Some(m) = args.get("microphone") {+ let name = m.as_str().map(str::trim).unwrap_or("");+ if !name.is_empty() && !input_names().iter().any(|n| n == name) {+ return Err(format!("There's no microphone called \"{name}\" on this computer right now."));+ }+ p.mic = if name.is_empty() { None } else { Some(name.to_string()) };+ }+ if let Some(on) = args.get("microphoneOn").and_then(Value::as_bool) {+ p.mic_on = on;+ }+ let dir = data_dir();+ std::fs::create_dir_all(&dir).map_err(|e| format!("can't save the microphone choice: {e}"))?;+ let body = json!({ "microphone": p.mic.clone().unwrap_or_default(), "microphoneOn": p.mic_on });+ std::fs::write(prefs_path(), format!("{body}\n")).map_err(|e| format!("can't save the microphone choice: {e}"))?;+ Ok(status())+}++// ── Microphones ────────────────────────────────────────────────────────++fn input_names() -> Vec<String> {+ let host = cpal::default_host();+ let mut names: Vec<String> = host.input_devices().map(|it| it.filter_map(|d| d.name().ok()).collect()).unwrap_or_default();+ names.dedup();+ names+}++/// The microphone Optimus will open: the owner's pick if it's connected, else the system default.+/// The note says why it isn't the pick (unplugged), when that happens.+pub fn input_device() -> Result<(cpal::Device, Option<String>), String> {+ let host = cpal::default_host();+ let p = prefs();+ if let Some(want) = &p.mic {+ if let Some(d) = host.input_devices().ok().and_then(|mut it| it.find(|d| d.name().ok().as_deref() == Some(want.as_str()))) {+ return Ok((d, None));+ }+ let d = host.default_input_device().ok_or_else(no_microphone)?;+ let using = d.name().unwrap_or_else(|_| "the default microphone".into());+ return Ok((d, Some(format!("\"{want}\" isn't connected, so Optimus is using {using}."))));+ }+ Ok((host.default_input_device().ok_or_else(no_microphone)?, None))+}++fn no_microphone() -> String {+ if cfg!(target_os = "macos") {+ "This Mac has no microphone connected (or macOS hides it). Plug one in, or check System Settings → Sound → Input.".into()+ } else if cfg!(windows) {+ "Windows has no microphone enabled. Plug one in, or open Settings → System → Sound → Input and pick or enable a microphone.".into()+ } else {+ format!("No microphone found. {}", linux_audio_steps().join(" "))+ }+}++fn microphones() -> Value {+ let host = cpal::default_host();+ let default = host.default_input_device().and_then(|d| d.name().ok());+ let p = prefs();+ let list: Vec<Value> = input_names()+ .into_iter()+ .map(|n| json!({ "name": n, "default": default.as_deref() == Some(n.as_str()) }))+ .collect();+ let connected = p.mic.as_ref().map(|m| list.iter().any(|d| d["name"].as_str() == Some(m.as_str())));+ json!({+ "devices": list,+ "systemDefault": default,+ "selected": p.mic,+ "selectedConnected": connected.unwrap_or(true),+ "on": p.mic_on,+ })+}++// ── Status ─────────────────────────────────────────────────────────────++/// One permission, as the app shows it.+/// state: granted | not-asked | denied | restricted | limited | unavailable+fn entry(kind: &str, label: &str, state: &str, detail: String, steps: Vec<String>, can_request: bool, settings: Option<&str>, used: bool) -> Value {+ json!({+ "kind": kind,+ "label": label,+ "state": state,+ "detail": detail,+ "steps": steps,+ "canRequest": can_request,+ "canOpenSettings": settings.is_some(),+ "used": used,+ })+}++pub fn status() -> Value {+ json!({+ "platform": platform_name(),+ "permissions": permissions(),+ "microphones": microphones(),+ })+}++/// Ask for one permission (where the OS can ask), else open the right settings page.+pub fn request(args: &Value) -> Result<Value, String> {+ let kind = args.get("kind").and_then(Value::as_str).unwrap_or("");+ let open = args.get("openSettings").and_then(Value::as_bool).unwrap_or(false);+ platform_request(kind, open)?;+ Ok(status())+}++/// Ready to listen? Called before a voice session opens the microphone, so a+/// blocked microphone says so instead of delivering silence.+pub fn mic_ready() -> Result<(), String> {+ if !prefs().mic_on {+ return Err("The microphone is off for Optimus. Turn it on in Mercury → Settings → AI → Voice → Microphone.".into());+ }+ platform_mic_ready()+}++/// The microphone permission on macOS: granted | not-asked | denied | restricted.+#[cfg(target_os = "macos")]+pub fn mic_state() -> &'static str {+ use objc2_av_foundation::AVAuthorizationStatus as S;+ match os::auth(false) {+ S::Authorized => "granted",+ S::Denied => "denied",+ S::Restricted => "restricted",+ _ => "not-asked",+ }+}++#[cfg(target_os = "macos")]+pub fn ask_microphone() -> bool {+ os::ask_microphone()+}++// ── Microphone test ────────────────────────────────────────────────────++/// Listen for `seconds` on the chosen microphone (no speaker, no voice link),+/// reporting the level every 80 ms through `level`, then sum it up.+pub fn mic_test(args: &Value, level: impl Fn(f32)) -> Result<Value, String> {+ platform_mic_ready()?;+ let seconds = args.get("seconds").and_then(Value::as_f64).unwrap_or(5.0).clamp(1.0, 15.0);+ let (device, note) = input_device()?;+ let name = device.name().unwrap_or_else(|_| "microphone".into());+ let cfg = device.default_input_config().map_err(|e| format!("{name}: {e}"))?;+ let peak = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));+ let frames = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));+ let stream = {+ let peak = peak.clone();+ let frames = frames.clone();+ let channels = cfg.channels().max(1) as usize;+ let config: cpal::StreamConfig = cfg.config();+ let on_err = |e| crate::core::log(format!("mic test: {e}"));+ macro_rules! build {+ ($t:ty, $f:expr) => {+ device.build_input_stream(+ &config,+ move |data: &[$t], _| {+ let mut p = 0f32;+ for f in data.chunks(channels) {+ let m = (f.iter().map(|s| $f(*s)).sum::<f32>() / channels as f32).abs();+ if m > p {+ p = m;+ }+ }+ frames.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);+ if p > f32::from_bits(peak.load(std::sync::atomic::Ordering::Relaxed)) {+ peak.store(p.to_bits(), std::sync::atomic::Ordering::Relaxed);+ }+ },+ on_err,+ None,+ )+ };+ }+ match cfg.sample_format() {+ cpal::SampleFormat::F32 => build!(f32, |s: f32| s),+ cpal::SampleFormat::I16 => build!(i16, |s: i16| s as f32 / 32768.0),+ cpal::SampleFormat::U16 => build!(u16, |s: u16| (s as f32 - 32768.0) / 32768.0),+ cpal::SampleFormat::I32 => build!(i32, |s: i32| s as f32 / 2147483648.0),+ other => return Err(format!("{name} uses a sample format Optimus can't read ({other:?})")),+ }+ .map_err(|e| format!("{name}: {e}"))?+ };+ stream.play().map_err(|e| format!("{name}: {e}"))?;+ let until = Instant::now() + Duration::from_secs_f64(seconds);+ let mut loudest = 0f32;+ let mut sum = 0f32;+ let mut ticks = 0u32;+ while Instant::now() < until {+ std::thread::sleep(Duration::from_millis(80));+ let p = f32::from_bits(peak.swap(0, std::sync::atomic::Ordering::Relaxed));+ // The same scale as a voice session's level (peak × 3), so the meter reads alike.+ let l = (p * 3.0).min(1.0);+ level(l);+ loudest = loudest.max(p);+ sum += l;+ ticks += 1;+ }+ drop(stream);+ let got_audio = frames.load(std::sync::atomic::Ordering::Relaxed) > 0;+ let silent = loudest == 0.0;+ let heard = loudest > 0.02;+ let mut summary = if !got_audio {+ format!("{name} didn't send any sound at all.")+ } else if silent {+ format!("{name} sent pure silence: something is blocking or muting it.")+ } else if heard {+ format!("{name} works: Optimus heard you.")+ } else {+ format!("{name} is on, but very quiet: Optimus barely heard anything.")+ };+ if let Some(n) = ¬e {+ summary = format!("{n} {summary}");+ }+ let steps = if silent || !got_audio { silent_steps(&name) } else if !heard { quiet_steps(&name) } else { Vec::new() };+ Ok(json!({+ "device": name,+ "peak": (loudest * 3.0).min(1.0),+ "average": if ticks > 0 { sum / ticks as f32 } else { 0.0 },+ "heard": heard,+ "silent": silent || !got_audio,+ "text": summary,+ "steps": steps,+ }))+}++// ── macOS ──────────────────────────────────────────────────────────────++#[cfg(target_os = "macos")]+mod os {+ use super::*;+ use objc2_av_foundation::{AVAuthorizationStatus, AVCaptureDevice, AVMediaTypeAudio, AVMediaTypeVideo};+ use std::process::Command;++ pub const PANE_MIC: &str = "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone";+ pub const PANE_CAMERA: &str = "x-apple.systempreferences:com.apple.preference.security?Privacy_Camera";+ pub const PANE_SCREEN: &str = "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture";+ pub const PANE_AX: &str = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";++ #[link(name = "ApplicationServices", kind = "framework")]+ unsafe extern "C" {+ fn AXIsProcessTrusted() -> bool;+ }+ #[link(name = "CoreGraphics", kind = "framework")]+ unsafe extern "C" {+ fn CGPreflightScreenCaptureAccess() -> bool;+ }++ pub fn major() -> u32 {+ Command::new("sw_vers")+ .arg("-productVersion")+ .output()+ .ok()+ .and_then(|o| String::from_utf8(o.stdout).ok())+ .and_then(|v| v.trim().split('.').next().and_then(|m| m.parse().ok()))+ .unwrap_or(14)+ }++ /// "System Settings → Privacy & Security" on macOS 13+, "System Preferences → Security & Privacy → Privacy" before.+ pub fn privacy(list: &str) -> String {+ if major() >= 13 {+ format!("Open System Settings → Privacy & Security → {list}.")+ } else {+ format!("Open System Preferences → Security & Privacy → Privacy tab → {list} (click the lock to make changes).")+ }+ }++ pub fn screen_list() -> &'static str {+ if major() >= 15 { "Screen & System Audio Recording" } else { "Screen Recording" }+ }++ pub fn auth(video: bool) -> AVAuthorizationStatus {+ // SAFETY: plain class method calls with constants AVFoundation defines.+ unsafe {+ let media = if video { AVMediaTypeVideo } else { AVMediaTypeAudio };+ match media {+ Some(m) => AVCaptureDevice::authorizationStatusForMediaType(m),+ None => AVAuthorizationStatus::NotDetermined,+ }+ }+ }++ /// Show macOS's microphone prompt for Optimus and wait for the answer (up to a minute).+ pub fn ask_microphone() -> bool {+ let (tx, rx) = std::sync::mpsc::channel::<bool>();+ let block = block2::RcBlock::new(move |granted: objc2::runtime::Bool| {+ let _ = tx.send(granted.as_bool());+ });+ // SAFETY: AVMediaTypeAudio is AVFoundation's constant; the block outlives the call (RcBlock is retained by AVFoundation).+ unsafe {+ if let Some(m) = AVMediaTypeAudio {+ AVCaptureDevice::requestAccessForMediaType_completionHandler(m, &block);+ } else {+ return false;+ }+ }+ rx.recv_timeout(Duration::from_secs(60)).unwrap_or(false)+ }++ pub fn open(pane: &str) {+ let _ = Command::new("open").arg(pane).status();+ }++ pub fn mic_entry() -> Value {+ let list = "Microphone";+ match auth(false) {+ AVAuthorizationStatus::Authorized => entry("microphone", "Microphone", "granted", "Optimus may use the microphone.".into(), vec![], false, Some(PANE_MIC), true),+ AVAuthorizationStatus::Denied => entry(+ "microphone",+ "Microphone",+ "denied",+ "macOS is blocking the microphone for Optimus, so it hears only silence.".into(),+ vec![privacy(list), "Turn on Optimus.".into(), "Come back here and press Test: the bar should move when you speak.".into()],+ false,+ Some(PANE_MIC),+ true,+ ),+ AVAuthorizationStatus::Restricted => entry(+ "microphone",+ "Microphone",+ "restricted",+ "This Mac doesn't let apps ask for the microphone: a device-management profile or Screen Time restricts it.".into(),+ vec![+ if major() >= 13 { "Open System Settings → Screen Time → Content & Privacy → App Restrictions (or Privacy) and allow microphone changes." } else { "Open System Preferences → Screen Time → Content & Privacy → Apps and allow microphone changes." }.into(),+ "If this Mac is managed by an organisation, ask its administrator to allow the microphone for Optimus (bundle id sh.mercuryagent.optimus).".into(),+ ],+ false,+ Some(PANE_MIC),+ true,+ ),+ _ => entry(+ "microphone",+ "Microphone",+ "not-asked",+ "macOS hasn't asked you yet whether Optimus may use the microphone.".into(),+ vec!["Press Allow: macOS shows its prompt for Optimus. Choose Allow.".into()],+ true,+ Some(PANE_MIC),+ true,+ ),+ }+ }++ pub fn permissions() -> Vec<Value> {+ let (ax, screen) = unsafe { (AXIsProcessTrusted(), CGPreflightScreenCaptureAccess()) };+ let screen_list = screen_list();+ let camera = match auth(true) {+ AVAuthorizationStatus::Authorized => "granted",+ AVAuthorizationStatus::Denied => "denied",+ AVAuthorizationStatus::Restricted => "restricted",+ _ => "not-asked",+ };+ vec![+ mic_entry(),+ if screen {+ entry("screen", screen_list, "granted", "Optimus can see the screen.".into(), vec![], false, Some(PANE_SCREEN), true)+ } else {+ entry(+ "screen",+ screen_list,+ "denied",+ "Optimus can't see the screen until it's allowed.".into(),+ vec![+ "Press Allow: macOS adds Optimus to the list and opens it.".into(),+ privacy(screen_list),+ "Turn on Optimus. If macOS offers \"Quit & Reopen\", choose Later: Optimus restarts by itself the next time it's used.".into(),+ "macOS asks you to confirm this again about once a month.".into(),+ ],+ true,+ Some(PANE_SCREEN),+ true,+ )+ },+ if ax {+ entry("accessibility", "Accessibility", "granted", "Optimus can use the mouse and keyboard.".into(), vec![], false, Some(PANE_AX), true)+ } else {+ entry(+ "accessibility",+ "Accessibility",+ "denied",+ "Optimus can't use the mouse and keyboard until it's allowed.".into(),+ vec![+ "Press Allow: macOS adds Optimus to the list and opens it.".into(),+ privacy("Accessibility"),+ "Turn on Optimus.".into(),+ "Already on but still red? Select Optimus, remove it with the − button, then press Allow here again (an Optimus update can leave a stale entry).".into(),+ ],+ true,+ Some(PANE_AX),+ true,+ )+ },+ entry(+ "camera",+ "Camera",+ camera,+ "No Optimus feature uses the camera yet.".into(),+ if camera == "denied" { vec![privacy("Camera"), "Turn on the app that needs it.".into()] } else { vec![] },+ false,+ Some(PANE_CAMERA),+ false,+ ),+ ]+ }++ pub fn request(kind: &str, open_settings: bool) -> Result<(), String> {+ match kind {+ "microphone" => {+ if open_settings || auth(false) != AVAuthorizationStatus::NotDetermined {+ open(PANE_MIC);+ } else if !ask_microphone() {+ open(PANE_MIC);+ }+ }+ "screen" | "accessibility" => {+ // The existing request flow registers Optimus in the list, prompts once and opens the pane.+ let _ = crate::mac::permission_report(true);+ if open_settings {+ open(if kind == "screen" { PANE_SCREEN } else { PANE_AX });+ }+ }+ "camera" => open(PANE_CAMERA),+ other => return Err(format!("unknown permission {other}")),+ }+ Ok(())+ }++ pub fn mic_ready() -> Result<(), String> {+ match auth(false) {+ AVAuthorizationStatus::Authorized => Ok(()),+ AVAuthorizationStatus::NotDetermined => {+ if ask_microphone() {+ Ok(())+ } else {+ open(PANE_MIC);+ Err(format!("macOS didn't allow the microphone for Optimus. {} Turn on Optimus, then try again.", privacy("Microphone")))+ }+ }+ AVAuthorizationStatus::Restricted => Err("This Mac restricts the microphone (Screen Time or a device-management profile), so Optimus can't use it.".into()),+ _ => {+ open(PANE_MIC);+ Err(format!("macOS is blocking the microphone for Optimus. {} Turn on Optimus, then try again.", privacy("Microphone")))+ }+ }+ }++ pub fn silent_steps(name: &str) -> Vec<String> {+ let mut steps = Vec::new();+ if auth(false) != AVAuthorizationStatus::Authorized {+ steps.push(privacy("Microphone"));+ steps.push("Turn on Optimus.".into());+ }+ steps.push(format!(+ "{} pick {name} and speak: its Input level should move. If the Input volume slider is all the way left, drag it right.",+ if major() >= 13 { "Open System Settings → Sound → Input," } else { "Open System Preferences → Sound → Input," }+ ));+ steps.push("A headset or USB mic may have its own mute switch or button: check it's not muted.".into());+ steps+ }++ pub fn quiet_steps(name: &str) -> Vec<String> {+ vec![format!(+ "{} select {name} and drag the Input volume slider further right.",+ if major() >= 13 { "Open System Settings → Sound → Input," } else { "Open System Preferences → Sound → Input," }+ )]+ }+}++// ── Windows ────────────────────────────────────────────────────────────++#[cfg(windows)]+mod os {+ use super::*;+ use windows_sys::Win32::System::Registry::{HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RegGetValueW};++ const CONSENT: &str = r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore";++ fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(std::iter::once(0)).collect()+ }++ fn reg_string(root: HKEY, key: &str, value: &str) -> Option<String> {+ let (k, v) = (wide(key), wide(value));+ let mut buf = vec![0u16; 256];+ let mut len = (buf.len() * 2) as u32;+ // SAFETY: buffers are valid for the sizes passed.+ let r = unsafe { RegGetValueW(root, k.as_ptr(), v.as_ptr(), RRF_RT_REG_SZ, std::ptr::null_mut(), buf.as_mut_ptr().cast(), &mut len) };+ if r != 0 {+ return None;+ }+ let n = (len as usize / 2).saturating_sub(1);+ Some(String::from_utf16_lossy(&buf[..n.min(buf.len())]))+ }++ pub fn windows_11() -> bool {+ reg_string(HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber")+ .and_then(|b| b.trim().parse::<u32>().ok())+ .map(|b| b >= 22000)+ .unwrap_or(true)+ }++ /// The three switches that decide whether a desktop app may use a device:+ /// the device-wide one (admin), the per-user one, and "desktop apps".+ fn consent(cap: &str) -> (bool, bool, bool) {+ let deny = |root, key: String| reg_string(root, &key, "Value").map(|v| v.eq_ignore_ascii_case("Deny")).unwrap_or(false);+ (+ deny(HKEY_LOCAL_MACHINE, format!(r"SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\{cap}")),+ deny(HKEY_CURRENT_USER, format!(r"{CONSENT}\{cap}")),+ deny(HKEY_CURRENT_USER, format!(r"{CONSENT}\{cap}\NonPackaged")),+ )+ }++ fn device_steps(cap: &str, noun: &str, page: &str) -> Vec<String> {+ let (device_off, user_off, desktop_off) = consent(cap);+ let mut steps = Vec::new();+ if windows_11() {+ steps.push(format!("Open Settings → Privacy & security → {page}."));+ if device_off || user_off {+ steps.push(format!("Turn on \"{page} access\"{}.", if device_off { " (needs an administrator account)" } else { "" }));+ steps.push(format!("Turn on \"Let apps access your {noun}\"."));+ }+ if desktop_off || steps.len() == 1 {+ steps.push(format!("Scroll down and turn on \"Let desktop apps access your {noun}\" (Optimus is a desktop app, so it isn't listed by name)."));+ }+ } else {+ steps.push(format!("Open Settings → Privacy → {page}."));+ if device_off {+ steps.push(format!("Under \"Allow access to the {noun} on this device\", click Change and turn it on (needs an administrator account)."));+ }+ if user_off {+ steps.push(format!("Turn on \"Allow apps to access your {noun}\"."));+ }+ if desktop_off || steps.len() == 1 {+ steps.push(format!("Scroll down and turn on \"Allow desktop apps to access your {noun}\" (Optimus is a desktop app, so it isn't listed by name)."));+ }+ }+ steps+ }++ pub fn mic_entry() -> Value {+ let (a, b, c) = consent("microphone");+ if a || b || c {+ entry(+ "microphone",+ "Microphone",+ "denied",+ "Windows privacy settings block desktop apps, including Optimus, from the microphone.".into(),+ device_steps("microphone", "microphone", "Microphone"),+ false,+ Some("ms-settings:privacy-microphone"),+ true,+ )+ } else {+ entry("microphone", "Microphone", "granted", "Windows lets desktop apps, including Optimus, use the microphone. Windows never asks per app.".into(), vec![], false, Some("ms-settings:privacy-microphone"), true)+ }+ }++ pub fn permissions() -> Vec<Value> {+ let (a, b, c) = consent("webcam");+ let camera_off = a || b || c;+ vec![+ mic_entry(),+ entry("screen", "Screen", "granted", "Windows doesn't need a permission for Optimus to see the screen.".into(), vec![], false, None, true),+ entry(+ "accessibility",+ "Mouse and keyboard",+ "granted",+ "Optimus can use the mouse and keyboard. Windows of apps running as administrator (Task Manager, installers) ignore it unless Optimus also runs as administrator.".into(),+ vec![],+ false,+ None,+ true,+ ),+ entry(+ "camera",+ "Camera",+ if camera_off { "denied" } else { "granted" },+ "No Optimus feature uses the camera yet.".into(),+ if camera_off { device_steps("webcam", "camera", "Camera") } else { vec![] },+ false,+ Some("ms-settings:privacy-webcam"),+ false,+ ),+ ]+ }++ pub fn open(uri: &str) {+ let _ = std::process::Command::new("explorer.exe").arg(uri).status();+ }++ pub fn request(kind: &str, _open_settings: bool) -> Result<(), String> {+ match kind {+ // Windows never prompts a desktop app: the switches live in Settings.+ "microphone" => open("ms-settings:privacy-microphone"),+ "camera" => open("ms-settings:privacy-webcam"),+ "screen" | "accessibility" => {}+ other => return Err(format!("unknown permission {other}")),+ }+ Ok(())+ }++ pub fn mic_ready() -> Result<(), String> {+ let (a, b, c) = consent("microphone");+ if a || b || c {+ open("ms-settings:privacy-microphone");+ return Err(format!("Windows is blocking the microphone for desktop apps. {}", device_steps("microphone", "microphone", "Microphone").join(" ")));+ }+ Ok(())+ }++ pub fn silent_steps(name: &str) -> Vec<String> {+ let mut steps = Vec::new();+ let (a, b, c) = consent("microphone");+ if a || b || c {+ steps.extend(device_steps("microphone", "microphone", "Microphone"));+ }+ steps.push(format!(+ "Open Settings → System → Sound → Input, select {name} and speak: the level bar should move. Raise Input volume if it's at 0."+ ));+ steps.push(format!("Still silent? In the same page open {name}'s properties and make sure it isn't disabled, or pick another microphone above."));+ steps.push("A headset or USB mic may have its own mute switch or button: check it's not muted.".into());+ steps+ }++ pub fn quiet_steps(name: &str) -> Vec<String> {+ vec![format!("Open Settings → System → Sound → Input, select {name} and raise Input volume.")]+ }+}++// ── Linux ──────────────────────────────────────────────────────────────++#[cfg(target_os = "linux")]+mod os {+ use super::*;++ fn desktop() -> String {+ std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_lowercase()+ }++ pub fn wayland() -> bool {+ std::env::var("XDG_SESSION_TYPE").map(|s| s == "wayland").unwrap_or(false) || std::env::var_os("WAYLAND_DISPLAY").is_some()+ }++ /// Where the sound server listens: PipeWire, or PulseAudio (also what pipewire-pulse provides).+ fn sound_server() -> Option<&'static str> {+ if std::env::var_os("PULSE_SERVER").is_some() {+ return Some("PulseAudio");+ }+ let dir = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from)?;+ if dir.join("pipewire-0").exists() {+ Some("PipeWire")+ } else if dir.join("pulse").join("native").exists() {+ Some("PulseAudio")+ } else {+ None+ }+ }++ pub fn mic_entry() -> Value {+ if std::env::var_os("XDG_RUNTIME_DIR").is_none() {+ return entry(+ "microphone",+ "Microphone",+ "unavailable",+ "Optimus was started without your desktop session's details (XDG_RUNTIME_DIR), so it can't reach the sound server.".into(),+ vec![+ "Update Mercury: newer versions pass the session's audio details to plugins.".into(),+ "Then restart Mercury from a terminal inside your desktop session: mercury restart".into(),+ ],+ false,+ None,+ true,+ );+ }+ match sound_server() {+ Some(server) => entry(+ "microphone",+ "Microphone",+ "granted",+ format!("Linux doesn't ask apps for microphone permission. Optimus reaches it through {server}."),+ vec![],+ false,+ None,+ true,+ ),+ None => entry(+ "microphone",+ "Microphone",+ "unavailable",+ "No PipeWire or PulseAudio sound server is running in this session, so Optimus can only use raw ALSA devices.".into(),+ vec![+ "Start PipeWire: systemctl --user enable --now pipewire pipewire-pulse wireplumber".into(),+ "Or, on a PulseAudio system: pulseaudio --start".into(),+ "Then press Recheck.".into(),+ ],+ false,+ None,+ true,+ ),+ }+ }++ fn x11_session_steps() -> Vec<String> {+ let d = desktop();+ let session = if d.contains("gnome") || d.contains("ubuntu") {+ "\"GNOME on Xorg\" (Ubuntu: \"Ubuntu on Xorg\")"+ } else if d.contains("kde") {+ "\"Plasma (X11)\""+ } else {+ "an X11 (Xorg) session"+ };+ vec![+ "Log out.".into(),+ format!("On the login screen, click your name, then the gear (or session menu) in the corner, and choose {session}."),+ "Log in and press Recheck.".into(),+ ]+ }++ pub fn permissions() -> Vec<Value> {+ let w = wayland();+ vec![+ mic_entry(),+ if w {+ entry(+ "screen",+ "Screen",+ "limited",+ "Wayland: every screenshot goes through your desktop's screen-sharing prompt.".into(),+ x11_session_steps(),+ false,+ None,+ true,+ )+ } else {+ entry("screen", "Screen", "granted", "X11: Optimus can see the screen. Linux doesn't need a permission for it.".into(), vec![], false, None, true)+ },+ if w {+ entry(+ "accessibility",+ "Mouse and keyboard",+ "limited",+ "Wayland: Optimus can only click and type in X11 (XWayland) apps, not native Wayland ones.".into(),+ x11_session_steps(),+ false,+ None,+ true,+ )+ } else {+ entry("accessibility", "Mouse and keyboard", "granted", "X11: Optimus can use the mouse and keyboard.".into(), vec![], false, None, true)+ },+ entry("camera", "Camera", "granted", "Linux doesn't ask apps for camera permission. No Optimus feature uses the camera yet.".into(), vec![], false, None, false),+ ]+ }++ pub fn request(kind: &str, _open_settings: bool) -> Result<(), String> {+ match kind {+ "microphone" | "screen" | "accessibility" | "camera" => Ok(()),+ other => Err(format!("unknown permission {other}")),+ }+ }++ pub fn mic_ready() -> Result<(), String> {+ let e = mic_entry();+ if e["state"] == "granted" {+ return Ok(());+ }+ let steps: Vec<String> = e["steps"].as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect()).unwrap_or_default();+ Err(format!("{} {}", e["detail"].as_str().unwrap_or(""), steps.join(" ")))+ }++ pub fn audio_steps() -> Vec<String> {+ let d = desktop();+ let mut steps = Vec::new();+ if d.contains("gnome") || d.contains("ubuntu") || d.contains("unity") || d.contains("cinnamon") || d.contains("budgie") {+ steps.push("Open Settings → Sound → Input, choose the microphone and speak: the input level bar should move. Raise Volume and make sure it isn't muted.".into());+ } else if d.contains("kde") {+ steps.push("Open System Settings → Sound (Audio) → Input Devices, choose the microphone, unmute it and raise its volume.".into());+ } else if d.contains("xfce") || d.contains("lxqt") || d.contains("lxde") || d.contains("mate") {+ steps.push("Open PulseAudio Volume Control (pavucontrol) → Input Devices: unmute the microphone (speaker icon), raise its level, and click the ✓ to make it the fallback.".into());+ } else {+ steps.push("Open pavucontrol (PulseAudio Volume Control) → Input Devices: unmute the microphone, raise its level and set it as fallback.".into());+ }+ steps.push("Still silent? Run alsamixer in a terminal, press F4 (Capture), select the microphone and press Space so it shows CAPTURE, then raise it with ↑.".into());+ steps+ }++ pub fn silent_steps(_name: &str) -> Vec<String> {+ let mut steps = Vec::new();+ if mic_entry()["state"] != "granted" {+ steps.extend(mic_entry()["steps"].as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect::<Vec<_>>()).unwrap_or_default());+ }+ steps.extend(audio_steps());+ steps.push("A headset or USB mic may have its own mute switch or button: check it's not muted.".into());+ steps+ }++ pub fn quiet_steps(_name: &str) -> Vec<String> {+ audio_steps().into_iter().take(1).collect()+ }+}++#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]+mod os {+ use super::*;+ pub fn permissions() -> Vec<Value> {+ vec![]+ }+ pub fn request(_: &str, _: bool) -> Result<(), String> {+ Ok(())+ }+ pub fn mic_ready() -> Result<(), String> {+ Ok(())+ }+ pub fn silent_steps(_: &str) -> Vec<String> {+ vec![]+ }+ pub fn quiet_steps(_: &str) -> Vec<String> {+ vec![]+ }+}++fn platform_name() -> &'static str {+ if cfg!(target_os = "macos") {+ "macos"+ } else if cfg!(windows) {+ "windows"+ } else {+ "linux"+ }+}++fn permissions() -> Vec<Value> {+ os::permissions()+}++fn platform_request(kind: &str, open: bool) -> Result<(), String> {+ os::request(kind, open)+}++fn platform_mic_ready() -> Result<(), String> {+ os::mic_ready()+}++fn silent_steps(name: &str) -> Vec<String> {+ os::silent_steps(name)+}++fn quiet_steps(name: &str) -> Vec<String> {+ os::quiet_steps(name)+}++#[cfg(target_os = "linux")]+fn linux_audio_steps() -> Vec<String> {+ os::audio_steps()+}++#[cfg(not(target_os = "linux"))]+fn linux_audio_steps() -> Vec<String> {+ Vec::new()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn prefs_round_trip() {+ let dir = std::env::temp_dir().join(format!("optimus-devices-{}", std::process::id()));+ // SAFETY: tests in this module run on one thread for this variable.+ unsafe { std::env::set_var("MERCURY_PLUGIN_DATA_DIR", &dir) };+ assert!(prefs().mic_on, "on by default");+ assert!(prefs().mic.is_none(), "system default by default");+ select(&json!({ "microphoneOn": false })).unwrap();+ assert!(!prefs().mic_on);+ assert!(select(&json!({ "microphone": "No Such Microphone 9000" })).is_err(), "an unknown microphone is refused");+ select(&json!({ "microphone": "", "microphoneOn": true })).unwrap();+ assert!(prefs().mic_on && prefs().mic.is_none());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn status_shape() {+ let s = status();+ assert!(s["platform"].is_string());+ let perms = s["permissions"].as_array().unwrap();+ for kind in ["microphone", "screen", "accessibility", "camera"] {+ let p = perms.iter().find(|p| p["kind"] == kind).unwrap_or_else(|| panic!("{kind} missing"));+ assert!(["granted", "not-asked", "denied", "restricted", "limited", "unavailable"].contains(&p["state"].as_str().unwrap()));+ // Anything not granted says exactly what to do.+ if p["state"] != "granted" && p["kind"] != "camera" {+ assert!(!p["steps"].as_array().unwrap().is_empty() || p["canRequest"] == true, "{kind} has no steps");+ }+ }+ assert!(s["microphones"]["devices"].is_array());+ }+}diff --git a/plugins/optimus/companion/src/mac.rs b/plugins/optimus/companion/src/mac.rsindex f6656dfa..c2617118 100644--- a/plugins/optimus/companion/src/mac.rs+++ b/plugins/optimus/companion/src/mac.rs@@ -59,21 +59,29 @@ pub fn permission_report(request: bool) -> Value {} else if !screen {let _ = Command::new("open").arg(PANE_SCREEN).status();}+ // Talking needs the microphone: ask now, while the owner is setting up, not in the middle+ // of the first voice session (where a hidden prompt left Optimus hearing silence).+ if crate::core::voice_enabled() && crate::devices::mic_state() == "not-asked" {+ let _ = crate::devices::ask_microphone();+ }}+ let mic = crate::devices::mic_state();let mark = |b: bool| if b { "✅" } else { "❌" };let mut text = format!(- "macOS permissions for Optimus:\n{} Accessibility (mouse and keyboard)\n{} Screen Recording (see the screen)",+ "macOS permissions for Optimus:\n{} Accessibility (mouse and keyboard)\n{} Screen Recording (see the screen)\n{} Microphone (talking to Optimus){}",mark(ax),- mark(screen)+ mark(screen),+ mark(mic == "granted"),+ if mic == "not-asked" { ": not asked yet" } else { "" });- if !ax || !screen {+ if !ax || !screen || mic != "granted" {text.push_str("\nTo fix: System Settings → Privacy & Security, turn on \"Optimus\" under each one that's off. \If Screen Recording asks to quit and reopen, Optimus restarts by itself on its next use. \macOS asks to confirm Screen Recording again about once a month.",);}- json!({ "ready": ax && screen, "accessibility": ax, "screenRecording": screen, "text": text })+ json!({ "ready": ax && screen, "accessibility": ax, "screenRecording": screen, "microphone": mic, "text": text })}/// `optimus agent --socket <path>`: run the core for one connection, then exit.diff --git a/plugins/optimus/companion/src/main.rs b/plugins/optimus/companion/src/main.rsindex 455a1726..ed9e2873 100644--- a/plugins/optimus/companion/src/main.rs+++ b/plugins/optimus/companion/src/main.rs@@ -18,6 +18,7 @@mod audio;mod core;+mod devices;mod hotkey;mod links;#[cfg(target_os = "macos")]@@ -204,7 +205,7 @@ const TOOL_DESCRIPTIONS: [(&str, &str); 7] = [("act_consequential", "Same as act, for the step that commits something: submit a form, send a message or email, post, pay or buy, delete, install, change a setting. The owner approves it first, so say what it will do."),("open", "Open an app by name (\"Chrome\", \"Notes\", \"Freeform\"), a URL, or a file/folder path. Faster and more reliable than clicking through menus. If the app isn't installed, the reply lists what is. For drawing use Freeform (Mac), Paint (Windows) or a web canvas like https://excalidraw.com."),("windows", "List open windows (app and title), front first."),- ("permissions", "Check what the OS lets Optimus do (macOS: Accessibility and Screen Recording). With request=true, shows the system prompts and opens the right Settings page."),+ ("permissions", "Check what the OS lets Optimus do (macOS: Accessibility, Screen Recording and Microphone). With request=true, shows the system prompts and opens the right Settings page."),("listen", "Start a voice conversation on this computer right now (as if the owner pressed the talk key): Mercury listens through the microphone and answers out loud. Use when the owner asks to talk instead of type."),];@@ -354,6 +355,20 @@ fn main() {});}m if m.starts_with("mercury/channel/") => reply(&shell, &id, channel_request(m, ¶ms)),+ // Mercury's "Microphone & permissions" screen. Works with control off too: it's how the owner sets it up.+ "mercury/device/status" | "mercury/device/request" | "mercury/device/select" | "mercury/device/test" => {+ let sh = shell.clone();+ std::thread::spawn(move || {+ let (op, secs) = match method.as_str() {+ "mercury/device/status" => ("device_status", 20),+ "mercury/device/request" => ("device_request", 90),+ "mercury/device/select" => ("device_select", 20),+ _ => ("device_test", 40),+ };+ let r = sh.op(op, ¶ms, Duration::from_secs(secs));+ reply(&sh, &id, r);+ });+ }_ => reply(&shell, &id, Err(format!("unknown method {method}"))),}}diff --git a/plugins/optimus/companion/src/voice.rs b/plugins/optimus/companion/src/voice.rsindex d6dc48c9..d01c5969 100644--- a/plugins/optimus/companion/src/voice.rs+++ b/plugins/optimus/companion/src/voice.rs@@ -124,11 +124,19 @@ pub async fn press(sh: Arc<Shared>, from_tool: bool) -> Result<String, String> {return Err(why);}let instructions = decision.get("instructions").and_then(Value::as_str).unwrap_or("").to_string();+ // A blocked or switched-off microphone says so here; otherwise the OS hands over silence and nothing explains it.+ // (On macOS the first time this shows the system prompt and waits for the answer.)+ let ready = tokio::task::spawn_blocking(crate::devices::mic_ready).await.unwrap_or_else(|e| Err(e.to_string()));+ if let Err(reason) = ready {+ *sh.session.lock().unwrap() = None;+ sh.out.notify("mercury/call/ended", json!({ "callId": call_id, "direction": "incoming", "outcome": format!("failed: {reason}"), "durationSec": 0, "transcript": [] }));+ return Err(reason);+ }let audio = match audio::open() {Ok(a) => a,Err(e) => {*sh.session.lock().unwrap() = None;- let reason = format!("{e}{}", if cfg!(target_os = "macos") { " (allow Optimus under Privacy & Security → Microphone)" } else { "" });+ let reason = e;sh.out.notify("mercury/call/ended", json!({ "callId": call_id, "direction": "incoming", "outcome": format!("failed: {reason}"), "durationSec": 0, "transcript": [] }));return Err(reason);}diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.jsonindex bc89b309..3c326a57 100644--- a/plugins/optimus/mercury-plugin.template.json+++ b/plugins/optimus/mercury-plugin.template.json@@ -2,7 +2,7 @@"manifestVersion": 1,"id": "optimus","name": "Optimus",- "version": "0.5.0",+ "version": "0.5.1","description": "Mercury uses your computer like a person: sees the screen, moves the mouse, types and opens apps, by chat or out loud with a talk key. macOS, Windows and Linux. Asks before anything that submits, sends, pays or deletes.","kind": "out-of-process","author": "Cosmic Stack",@@ -56,7 +56,7 @@},{"name": "permissions",- "description": "Check what the OS lets Optimus do (macOS: Accessibility and Screen Recording). With request=true, shows the system prompts and opens the right Settings page.",+ "description": "Check what the OS lets Optimus do (macOS: Accessibility, Screen Recording and Microphone). With request=true, shows the system prompts and opens the right Settings page.","readOnly": true,"timeoutMs": 60000},diff --git a/src/plugins/device-feed.ts b/src/plugins/device-feed.tsnew file mode 100644index 00000000..99edf75e--- /dev/null+++ b/src/plugins/device-feed.ts@@ -0,0 +1,38 @@+/**+ * Live device readings from desktop plugins (`mercury/device/level`), for the+ * app's microphone test: the plugin measures, Mercury relays, the app draws+ * the meter. Nothing is kept; a reading nobody listens to is dropped.+ */++export interface DeviceLevel {+ plugin: string;+ kind: string;+ level: number;+ at: number;+}++type Listener = (ev: DeviceLevel) => void;++const listeners = new Set<Listener>();++export const deviceFeed = {+ /** A reading from plugin `plugin`; levels are clamped to 0..1. */+ level(plugin: string, params: unknown): void {+ const p = (params ?? {}) as Record<string, unknown>;+ const n = Number(p.level);+ const ev: DeviceLevel = {+ plugin,+ kind: typeof p.kind === 'string' ? p.kind.slice(0, 32) : 'microphone',+ level: Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 0,+ at: Date.now(),+ };+ for (const l of listeners) {+ try { l(ev); } catch { /* a listener's problem */ }+ }+ },++ subscribe(listener: Listener): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+ },+};diff --git a/src/plugins/manager.ts b/src/plugins/manager.tsindex c3a01363..3235b6b8 100644--- a/src/plugins/manager.ts+++ b/src/plugins/manager.ts@@ -543,6 +543,32 @@ export class PluginManager {}}+ // ── devices (the app's microphone and permissions screen) ────────────++ /** Plugins that use this computer (`permissions.desktop`) and are running. */+ devicePlugins(): Array<{ id: string; name: string }> {+ return [...this.running.entries()]+ .filter(([, r]) => r.manifest.permissions.desktop && r.runtime instanceof OutOfProcessRuntime)+ .map(([id, r]) => ({ id, name: r.manifest.name }));+ }++ /** `mercury/device/*` on a running desktop plugin. */+ async deviceRequest(id: string, method: 'status' | 'request' | 'select' | 'test', params: unknown, timeoutMs: number): Promise<unknown> {+ const run = this.running.get(id);+ if (!run) {+ if (!readState().plugins[id]) throw new Error(`Plugin "${id}" is not installed.`);+ throw new Error(`"${id}" is not running. Turn it on first.`);+ }+ if (!(run.runtime instanceof OutOfProcessRuntime)) throw new Error(`"${id}" doesn't use this computer's devices.`);+ try {+ return await run.runtime.deviceRequest(`mercury/device/${method}`, params, timeoutMs);+ } catch (err) {+ // Versions before the devices screen answer "unknown method".+ if (/unknown method/i.test((err as Error).message)) throw new Error(`This version of ${run.manifest.name} can't report devices yet. Update it: mercury plugins update ${id}`);+ throw err;+ }+ }+// ── channels (plugin API 1.1) ────────────────────────────────────────private liveChannel(id: string): PluginChannel {diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.tsindex 36a5c600..e1b560f9 100644--- a/src/plugins/runtime/out-of-process.ts+++ b/src/plugins/runtime/out-of-process.ts@@ -19,6 +19,7 @@ import { PLUGIN_API_VERSION, type PluginManifest } from '../types.js';import { currentPlatform } from '../store.js';import { PLUGIN_IMAGE_TYPES, publishTool, toolContent, unpublishPlugin } from '../tool-bridge.js';import type { PluginRuntime, RuntimeDeps } from './types.js';+import { deviceFeed } from '../device-feed.js';export const OUT_OF_PROCESS = {initTimeoutMs: 20_000,@@ -36,6 +37,20 @@ const MCP_PROTOCOL_VERSION = '2025-06-18';/** Environment variables passed through to plugin processes; nothing else leaks. */const PASS_ENV = ['PATH', 'HOME', 'USERPROFILE', 'SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'TZ', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMDATA', 'COMSPEC', 'PATHEXT', 'WINDIR'];+/**+ * Linux desktop-session addresses, passed only to plugins that use the desktop+ * (`permissions.desktop`): without them a plugin can't reach the screen (X11,+ * Wayland), the sound server (PipeWire, PulseAudio) or the session bus.+ */+const DESKTOP_ENV = ['DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'XDG_SESSION_TYPE', 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP', 'DESKTOP_SESSION', 'DBUS_SESSION_BUS_ADDRESS', 'PULSE_SERVER', 'PIPEWIRE_RUNTIME_DIR'];++/** The parts of Mercury's environment a plugin gets: the basics, plus the desktop session for desktop plugins. */+export function passedEnv(desktop: boolean, source: NodeJS.ProcessEnv = process.env): Record<string, string> {+ const env: Record<string, string> = {};+ for (const k of desktop ? [...PASS_ENV, ...DESKTOP_ENV] : PASS_ENV) if (source[k]) env[k] = source[k]!;+ return env;+}+interface Pending {resolve(value: unknown): void;reject(err: Error): void;@@ -93,8 +108,7 @@ export class OutOfProcessRuntime implements PluginRuntime {}private buildEnv(extra: Record<string, string>): Record<string, string> {- const env: Record<string, string> = {};- for (const k of PASS_ENV) if (process.env[k]) env[k] = process.env[k]!;+ const env = passedEnv(this.manifest.permissions.desktop === true);for (const [k, v] of Object.entries(this.deps.secrets)) if (v !== undefined) env[k] = v;env.MERCURY_PLUGIN_ID = this.manifest.id;env.MERCURY_PLUGIN_VERSION = this.manifest.version;@@ -243,6 +257,18 @@ export class OutOfProcessRuntime implements PluginRuntime {});}+ /**+ * The app's microphone and permissions screen (`mercury/device/*`), for+ * plugins that use the desktop. A plugin that doesn't know the method says+ * so; a timeout fails that call only.+ */+ deviceRequest(method: string, params: unknown, timeoutMs: number): Promise<unknown> {+ if (!method.startsWith('mercury/device/')) return Promise.reject(new Error(`not a device method: ${method}`));+ if (!this.manifest.permissions.desktop) return Promise.reject(new Error(`"${this.manifest.id}" doesn't use this computer's devices.`));+ if (!this.ready) return Promise.reject(new Error('the plugin process is not running'));+ return this.request(method, params, timeoutMs, undefined, false);+ }+/** Plugin API 1.1 channel notifications to the plugin (`mercury/call/*`). */channelNotify(method: string, params: unknown): void {if (method.startsWith('mercury/') && this.ready) this.notify(method, params);@@ -284,6 +310,8 @@ export class OutOfProcessRuntime implements PluginRuntime {if (msg.method) {if (msg.method === 'notifications/tools/list_changed' && this.ready) {this.refreshTools().catch((err) => this.deps.onError(`tools/list after change: ${(err as Error).message}`));+ } else if (msg.method === 'mercury/device/level' && this.manifest.permissions.desktop) {+ deviceFeed.level(this.manifest.id, msg.params);} else if (msg.method.startsWith('mercury/') && this.manifest.contributes.channel) {try {this.deps.onNotification?.(msg.method, msg.params);diff --git a/src/plugins/runtime/passed-env.test.ts b/src/plugins/runtime/passed-env.test.tsnew file mode 100644index 00000000..e00241bf--- /dev/null+++ b/src/plugins/runtime/passed-env.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { passedEnv } from './out-of-process.js';++/**+ * A plugin gets only the environment it needs. A desktop plugin (Optimus)+ * also gets the Linux session's addresses: without them it can't reach the+ * screen or the sound server, and its microphone hears nothing.+ */+describe('plugin environment', () => {+ const source = {+ PATH: '/usr/bin',+ HOME: '/home/a',+ XDG_RUNTIME_DIR: '/run/user/1000',+ DISPLAY: ':0',+ WAYLAND_DISPLAY: 'wayland-0',+ DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',+ PULSE_SERVER: 'unix:/run/user/1000/pulse/native',+ OPENAI_API_KEY: 'sk-secret',+ AWS_SECRET_ACCESS_KEY: 'nope',+ };++ it('a desktop plugin gets the session, the display and the sound server', () => {+ expect(passedEnv(true, source)).toEqual({+ PATH: '/usr/bin',+ HOME: '/home/a',+ XDG_RUNTIME_DIR: '/run/user/1000',+ DISPLAY: ':0',+ WAYLAND_DISPLAY: 'wayland-0',+ DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',+ PULSE_SERVER: 'unix:/run/user/1000/pulse/native',+ });+ });++ it('any other plugin gets only the basics, and no plugin gets secrets from the environment', () => {+ expect(passedEnv(false, source)).toEqual({ PATH: '/usr/bin', HOME: '/home/a' });+ });+});diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex bd31c3da..1cfb41af 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -35,6 +35,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['code.session', // POST /api/chat/send { programming, cwd } — per-session coding'chat.uploads', // attachments on messages + GET /api/chat/uploads/:month/:file'voice', // /api/voice, /api/voice/events, /api/voice/control (Optimus)+ 'devices', // /api/devices: desktop plugins' permissions, microphone choice and test'usage.history', // GET /api/usage/history?days= — tokens per local day'brain.people', // PATCH/merge persons, person checks, GET /api/brain/graph/v2'chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)diff --git a/src/web/api/devices-route.test.ts b/src/web/api/devices-route.test.tsnew file mode 100644index 00000000..b5b73a5c--- /dev/null+++ b/src/web/api/devices-route.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { deviceFeed } from '../../plugins/device-feed.js';++/**+ * The app's microphone and permissions screen talks to desktop plugins+ * through these routes. They act on the computer Mercury runs on, so a+ * request from anywhere else is refused.+ */++const mgr = {+ devicePlugins: vi.fn(() => [{ id: 'optimus', name: 'Optimus' }]),+ deviceRequest: vi.fn(),+};+vi.mock('../../plugins/manager.js', () => ({ getPluginManager: () => mgr }));++const { default: devices } = await import('./devices.js');++const LOCAL = { incoming: { socket: { remoteAddress: '127.0.0.1' } } };+const REMOTE = { incoming: { socket: { remoteAddress: '192.168.1.20' } } };++const post = (path: string, body: unknown, env = LOCAL) =>+ devices.request(path, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }, env);++beforeEach(() => {+ mgr.deviceRequest.mockReset();+});++describe('/api/devices', () => {+ it('reports every running desktop plugin', async () => {+ mgr.deviceRequest.mockResolvedValue({ platform: 'macos', permissions: [], microphones: { devices: [] } });+ const res = await devices.request('/api/devices', {}, LOCAL);+ expect(res.status).toBe(200);+ const body = (await res.json()) as { plugins: Array<{ id: string; report?: { platform: string } }> };+ expect(body.plugins).toEqual([{ id: 'optimus', name: 'Optimus', report: { platform: 'macos', permissions: [], microphones: { devices: [] } } }]);+ expect(mgr.deviceRequest).toHaveBeenCalledWith('optimus', 'status', {}, 20_000);+ });++ it('shows a plugin that can\'t report (an older version) with its reason instead of failing the page', async () => {+ mgr.deviceRequest.mockRejectedValue(new Error('This version of Optimus can\'t report devices yet. Update it: mercury plugins update optimus'));+ const body = (await (await devices.request('/api/devices', {}, LOCAL)).json()) as { plugins: Array<{ error?: string }> };+ expect(body.plugins[0].error).toMatch(/Update it/);+ });++ it('is refused from another computer, and says where to go instead', async () => {+ const res = await devices.request('/api/devices', {}, REMOTE);+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({ remote: true });+ expect((await post('/api/devices/optimus/select', { microphoneOn: false }, REMOTE)).status).toBe(403);+ expect(mgr.deviceRequest).not.toHaveBeenCalled();+ });++ it('asks for one known permission at a time', async () => {+ mgr.deviceRequest.mockResolvedValue({ ok: 1 });+ expect((await post('/api/devices/optimus/request', { kind: 'bluetooth' })).status).toBe(400);+ const res = await post('/api/devices/optimus/request', { kind: 'microphone', openSettings: true });+ expect(res.status).toBe(200);+ expect(mgr.deviceRequest).toHaveBeenCalledWith('optimus', 'request', { kind: 'microphone', openSettings: true }, 90_000);+ });++ it('passes on only the microphone choice and the on/off switch', async () => {+ mgr.deviceRequest.mockResolvedValue({});+ expect((await post('/api/devices/optimus/select', { volume: 3 })).status).toBe(400);+ await post('/api/devices/optimus/select', { microphone: 'USB Mic', microphoneOn: true, extra: 'x' });+ expect(mgr.deviceRequest).toHaveBeenCalledWith('optimus', 'select', { microphone: 'USB Mic', microphoneOn: true }, 20_000);+ });++ it('a stopped plugin is a conflict, not a server error', async () => {+ mgr.deviceRequest.mockRejectedValue(new Error('"optimus" is not running. Turn it on first.'));+ const res = await post('/api/devices/optimus/select', { microphoneOn: true });+ expect(res.status).toBe(409);+ });++ it('streams the test\'s levels for that plugin only, then the result', async () => {+ let finish: (v: unknown) => void = () => {};+ mgr.deviceRequest.mockImplementation(() => new Promise((r) => { finish = r; }));+ const res = await devices.request('/api/devices/optimus/test?seconds=99', {}, LOCAL);+ expect(res.headers.get('content-type')).toContain('text/event-stream');+ // Seconds are capped at 15.+ expect(mgr.deviceRequest).toHaveBeenCalledWith('optimus', 'test', { seconds: 15 }, 40_000);+ deviceFeed.level('optimus', { kind: 'microphone', level: 0.4 });+ deviceFeed.level('someone-else', { kind: 'microphone', level: 0.9 });+ deviceFeed.level('optimus', { kind: 'microphone', level: 7 });+ finish({ heard: true, text: 'USB Mic works: Optimus heard you.' });+ const text = await res.text();+ const levels = [...text.matchAll(/event: level\ndata: (.*)\n/g)].map((m) => JSON.parse(m[1]).level);+ expect(levels).toEqual([0.4, 1]);+ expect(text).toContain('event: done');+ expect(text).toContain('Optimus heard you');+ });++ it('ends the test stream with the plugin\'s reason when it can\'t listen', async () => {+ mgr.deviceRequest.mockRejectedValue(new Error('macOS is blocking the microphone for Optimus.'));+ const text = await (await devices.request('/api/devices/optimus/test', {}, LOCAL)).text();+ expect(text).toContain('event: error');+ expect(text).toContain('blocking the microphone');+ });+});diff --git a/src/web/api/devices.ts b/src/web/api/devices.tsnew file mode 100644index 00000000..32804ba5--- /dev/null+++ b/src/web/api/devices.ts@@ -0,0 +1,110 @@+/**+ * The app's "Microphone & permissions" screen: what the OS lets each desktop+ * plugin (Optimus) use, which microphone it listens with, and a live test.+ *+ * GET /api/devices every running desktop plugin's report+ * POST /api/devices/:id/request { kind, openSettings? }: ask the OS, or open its settings page+ * POST /api/devices/:id/select { microphone?, microphoneOn? }+ * GET /api/devices/:id/test?seconds=5 SSE: `level` {level, at} while listening, then `done` or `error`+ *+ * All of it is about the computer Mercury runs on and can open system+ * settings there, so it's accepted from this machine only.+ */+import { Hono, type Context } from 'hono';+import { isLoopbackRequest } from '../middleware.js';+import { getPluginManager } from '../../plugins/manager.js';+import { deviceFeed } from '../../plugins/device-feed.js';++const devices = new Hono();++const KINDS = ['microphone', 'screen', 'accessibility', 'camera'] as const;++function localOnly(c: Context): Response | null {+ if (isLoopbackRequest(c)) return null;+ return c.json({ error: 'Microphone and permissions are set on the computer Mercury runs on. Open Mercury there.', remote: true }, 403);+}++function fail(c: Context, err: unknown) {+ const message = err instanceof Error ? err.message : String(err);+ return c.json({ error: message }, /not installed|not running|can't report/i.test(message) ? 409 : 400);+}++devices.get('/api/devices', async (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ const mgr = getPluginManager();+ const plugins = await Promise.all(+ mgr.devicePlugins().map(async (p) => {+ try {+ return { ...p, report: await mgr.deviceRequest(p.id, 'status', {}, 20_000) };+ } catch (err) {+ return { ...p, error: (err as Error).message };+ }+ }),+ );+ return c.json({ plugins });+});++devices.post('/api/devices/:id/request', async (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ const body = (await c.req.json().catch(() => ({}))) as { kind?: unknown; openSettings?: unknown };+ if (!(KINDS as readonly unknown[]).includes(body.kind)) return c.json({ error: `kind must be one of ${KINDS.join(', ')}` }, 400);+ try {+ // macOS waits for the owner's answer to its prompt, so allow a minute and a half.+ return c.json({ report: await getPluginManager().deviceRequest(c.req.param('id'), 'request', { kind: body.kind, openSettings: body.openSettings === true }, 90_000) });+ } catch (err) {+ return fail(c, err);+ }+});++devices.post('/api/devices/:id/select', async (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ const body = (await c.req.json().catch(() => ({}))) as { microphone?: unknown; microphoneOn?: unknown };+ const params: Record<string, unknown> = {};+ if (typeof body.microphone === 'string') params.microphone = body.microphone.slice(0, 200);+ if (typeof body.microphoneOn === 'boolean') params.microphoneOn = body.microphoneOn;+ if (Object.keys(params).length === 0) return c.json({ error: 'Send microphone (a name, or "" for the system default) or microphoneOn.' }, 400);+ try {+ return c.json({ report: await getPluginManager().deviceRequest(c.req.param('id'), 'select', params, 20_000) });+ } catch (err) {+ return fail(c, err);+ }+});++devices.get('/api/devices/:id/test', (c) => {+ const denied = localOnly(c);+ if (denied) return denied;+ const id = c.req.param('id');+ const seconds = Math.max(1, Math.min(15, Number(c.req.query('seconds')) || 5));+ const stream = new ReadableStream({+ start(controller) {+ const encoder = new TextEncoder();+ let open = true;+ const send = (event: string, data: unknown) => {+ if (!open) return;+ try { controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)); } catch { /* client gone */ }+ };+ const close = () => {+ if (!open) return;+ open = false;+ unsubscribe();+ try { controller.close(); } catch { /* already closed */ }+ };+ const unsubscribe = deviceFeed.subscribe((ev) => {+ if (ev.plugin === id && ev.kind === 'microphone') send('level', { level: ev.level, at: ev.at });+ });+ c.req.raw.signal?.addEventListener('abort', close);+ getPluginManager()+ .deviceRequest(id, 'test', { seconds }, (seconds + 25) * 1000)+ .then((result) => send('done', result))+ .catch((err) => send('error', { error: (err as Error).message }))+ .finally(close);+ },+ cancel() {},+ });+ return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' } });+});++export default devices;diff --git a/src/web/server.ts b/src/web/server.tsindex 38ced3b1..41037821 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -31,6 +31,7 @@ import lifecycleRoutes, { setShutdownHandler } from './api/lifecycle.js';import mcpRoutes, { setMcpManager } from './api/mcp.js';import pluginRoutes from './api/plugins.js';import voiceRoutes from './api/voice.js';+import deviceRoutes from './api/devices.js';import { BoardManager } from '../core/board-manager.js';import { isBetterSqlite3Available } from '../memory/second-brain-db.js';@@ -117,6 +118,7 @@ app.route('/', lifecycleRoutes);app.route('/', mcpRoutes);app.route('/', pluginRoutes);app.route('/', voiceRoutes);+app.route('/', deviceRoutes);// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──app.get('/vendor/*', (c) => {