Skip to content

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

feat(talk): hold ⌃⌥Space in any app to talk to MausBot (#3764)

Omkar Satpute25e79dd60892
diff --git a/docs/superpowers/plans/2026-10-27-talk-shortcut.md b/docs/superpowers/plans/2026-10-27-talk-shortcut.md
new file mode 100644
index 0000000000..03bc46c450
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-talk-shortcut.md
@@ -0,0 +1,881 @@
+# Talk Shortcut Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** On macOS, hold ⌃⌥Space in any app, speak, let go of ⌃⌥, and the words go to MausBot's "Quick asks" chat on this Mac's server while a small box that never takes focus shows the live words and then the reply.
+
+**Architecture:** `globalShortcut` sees the press; the existing speech helper sees the release (`--finish-on-release`, polling `CGEventSource.flagsState`). Small injected-dependency modules in Electron main do the rest: `talk-keys` (presets), `talk-shortcut` (registration and call presence), `talk-server` (find MausBot, keep the Quick asks chat, send, follow `/api/events`), `talk-panel` (the non-activating box), `talk-session` (the ask state machine). `speech.mjs` gains sinks so main can own a speech session without a window.
+
+**Tech Stack:** Electron ^43.5.0 main (ESM `.mjs`, preload `.cjs`), Swift helper (`swiftc`), Node `node:test` for `electron/*.node-test.mjs`, vitest (+ happy-dom) for `electron/*.test.mjs`, `server/`, `src/`; React settings row.
+
+**Spec:** `docs/superpowers/specs/2026-10-27-talk-shortcut-design.md`
+
+## Global Constraints
+
+- macOS only. Elsewhere nothing registers, `state().available` is false and the Settings row is hidden. A desktop running as a remote client of another computer (`desktopRemoteAccess`) has no local server: unavailable too.
+- Keys, exactly: `ctrl-opt-space` → `Control+Alt+Space`, release `control,option`, label `⌃⌥Space` (default); `ctrl-shift-space` → `Control+Shift+Space`, `control,shift`, `⌃⇧Space`; `opt-shift-space` → `Alt+Shift+Space`, `option,shift`, `⌥⇧Space`.
+- `desktop-prefs.json` gains `talkShortcut` (absent = on), `talkKey`, `quickAsks` (per server). Only fields that were set are written.
+- Asks always go to this computer's own server, never the Cloud or team page the window shows. The chat is titled exactly `Quick asks`, created on first use with `select: false`, reused, recreated when gone.
+- The box never takes focus and never raises the MausBot window: `type:"panel"`, `focusable:false`, `showInactive()`, never `show()`/`focus()`.
+- Timings: reply box hides 12 s after it settles unless the pointer is over it; no answer in 120 s → "Still working · Open chat"; reply text is plain, at most 400 characters.
+- Copy fixed by the spec: `Talk to MausBot from any app`, `Hold {key}, speak, let go`, `{key} is used by another app`, `Voice is in use in MausBot`, `Open MausBot to talk`, `Still working · Open chat`. Settings strings go in `src/locales/en.json` only (other languages fall back; `pnpm i18n:check` must pass). The box's own copy is English in v1: main has no locale catalogs.
+- New bridge keys (`talkShortcut`, `callActive`) stay out of `REMOTE_SAFE`; their IPC is `localOnly` (`call:active`: `localOrHome`, see Task 8).
+- No new dependencies. Modules under `node --test` never import `electron`: inject it.
+- AGENTS.md: comments only for what code cannot say (OS/Electron facts, public contracts, security invariants). No narration.
+- Never push. One commit per task.
+
+## Review Focus
+
+- A tap let go before any word is heard (the recognizer then reports `recognition-error` with nothing heard): the box closes silently, never an error. Pinned in Task 7.
+- A second ask while MausBot is still answering the first in the same chat: each box shows its own answer; the first turn's deltas and `turn.completed` never end the second box. Pinned in Task 5.
+- The Quick asks chat was deleted, or two presses race on first use: exactly one new chat, and the chat open in the MausBot window never switches. Pinned in Tasks 1 and 5.
+- The page reloads or its renderer crashes during a call: afterwards the shortcut works again instead of saying "Voice is in use" forever. Pinned in Tasks 4 and 9.
+- A reply with markup or Markdown (`<img src=x onerror=…>`, `**bold**`, links): shown as plain text, never parsed as HTML. Pinned in Task 6.
+
+---
+
+## File Structure
+
+| File | Responsibility |
+| --- | --- |
+| `server/routes/tasks.ts` (modify) | `POST /api/bots/:id/tasks` accepts `select: false` |
+| `electron/resources/speech-helper.swift` (modify) | `--finish-on-release <mods>`, `--release-check <mods> <flags>` |
+| `electron/speech.mjs` (modify) | sinks, owner-scoped stop/finish, `speechBusy()`, `finishOnRelease` option |
+| `electron/talk-keys.mjs` (new) | the three presets |
+| `electron/desktop-prefs.mjs`, `.d.mts` (modify) | talk prefs, Quick asks chat per server, injectable store |
+| `electron/talk-shortcut.mjs`, `.d.mts` (new) | register/unregister with prefs; call presence |
+| `electron/talk-server.mjs`, `.d.mts` (new) | find MausBot, Quick asks chat, SSE reading, reply tracking, ask |
+| `electron/talk-panel.mjs`, `electron/talk-panel-preload.cjs` (new) | the box window, its `data:` page, `isTalkPanel` |
+| `electron/talk-session.mjs` (new) | the ask state machine |
+| `electron/main.mjs`, `electron/preload.cjs`, `src/types/ogb.d.ts` (modify) | wiring, `appWindows()`, IPC, bridge |
+| `src/lib/call-presence.ts`, `src/components/LiveCallHost.tsx` | tell main when a call runs |
+| `src/components/TalkShortcutRow.tsx`, `SettingsModal.tsx`, `src/locales/en.json` | Settings → General row |
+| `docs/verification/talk-shortcut.md`, `docs/verification/README.md` | verification recipe |
+
+---
+
+### Task 1: Create a chat without selecting it
+
+`POST /api/bots/:id/tasks` always passes `activate = true` (`server/routes/tasks.ts:194` → `server/store.ts:2205`), so creating Quick asks would switch the chat the MausBot window shows.
+
+**Files:**
+- Modify: `server/routes/tasks.ts:162-198`
+- Test: `server/task-select.test.ts` (new)
+
+**Interfaces:**
+- Produces: `POST /api/bots/:id/tasks` body `{ title?: string, select?: boolean, … }`; `select: false` creates without selecting; non-boolean `select` → 400 `{ error: "select must be a boolean" }`. Response unchanged: 201 `{ bot, task }`.
+
+- [ ] **Step 1: Write the failing test** (`launchVerificationServer` from `scripts/control-omb.ts`, same `api()` helper as `server/bot-projects-api.test.ts:12-21`, `beforeAll` 90 s timeout)
+
+```ts
+it("creates a chat without switching the bot's open chat when select is false", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Select fixture" })).body.bot;
+ const created = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Quick asks", select: false });
+ expect(created.status).toBe(201);
+ expect(created.body.task.title).toBe("Quick asks");
+ const after = (await api("GET", "/api/bots?messages=0")).body.bots.find((b: any) => b.id === bot.id);
+ expect(after.threadId).toBe(bot.threadId);
+ expect(after.tasks.map((t: any) => t.threadId)).toContain(created.body.task.threadId);
+});
+it("still selects a new chat by default", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Default select" })).body.bot;
+ const created = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Picked" });
+ expect((await api("GET", "/api/bots?messages=0")).body.bots.find((b: any) => b.id === bot.id).threadId).toBe(created.body.task.threadId);
+});
+it("refuses a select that is not a boolean", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Bad select" })).body.bot;
+ expect(await api("POST", `/api/bots/${bot.id}/tasks`, { select: "no" })).toEqual({ status: 400, body: { error: "select must be a boolean" } });
+});
+```
+
+- [ ] **Step 2: Run it to see it fail**
+
+Run: `pnpm exec vitest run server/task-select.test.ts`
+Expected: FAIL on the first test (`after.threadId` equals the new chat) and the third (201 instead of 400).
+
+- [ ] **Step 3: Implement** — validate `body.select` right after the body-object check; pass `body.select !== false` as `createTask`'s third argument at line 194.
+
+- [ ] **Step 4: Run it to see it pass**
+
+Run: `pnpm exec vitest run server/task-select.test.ts`
+Expected: PASS (3 tests).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add server/routes/tasks.ts server/task-select.test.ts
+git commit -m "feat(server): create a chat without selecting it"
+```
+
+---
+
+### Task 2: The speech helper finishes when the keys are let go
+
+**Files:**
+- Modify: `electron/resources/speech-helper.swift` (header comment 1-13, imports 14-16, after `finishFile` 48-52, finish timer 72-82)
+- Test: `electron/speech-helper-release.node-test.mjs` (new)
+
+**Interfaces:**
+- Produces (CLI): `--finish-on-release <mods>` where `<mods>` is a comma list of `control`, `option`, `shift`, `command`; an invalid list fails at start with `{"error":"bad-modifiers"}`. `--release-check <mods> <rawFlags>` prints `{"released":true|false}` and exits 0 before anything touches Speech or the microphone; bad mods → `{"error":"bad-modifiers"}`, exit 1.
+
+- [ ] **Step 1: Write the failing test** (skipped unless macOS with `xcrun --find swiftc`; compiles single-arch `-Onone` into a temp dir and runs the loose binary, which is fine because `--release-check` exits before any TCC-protected call)
+
+```js
+const CONTROL = 0x40000, OPTION = 0x80000, SHIFT = 0x20000, COMMAND = 0x100000;
+test("the helper finishes when any of the chosen modifiers is let go", { skip: !swiftc && "needs macOS with swiftc" }, () => {
+ // build bin from new URL("./resources/speech-helper.swift", import.meta.url) with xcrun swiftc -Onone, timeout 180_000
+ const check = (mods, flags) => JSON.parse(execFileSync(bin, ["--release-check", mods, String(flags)], { encoding: "utf8", timeout: 10_000 }));
+ assert.deepEqual(check("control,option", CONTROL | OPTION), { released: false });
+ assert.deepEqual(check("control,option", CONTROL | OPTION | SHIFT), { released: false });
+ assert.deepEqual(check("control,option", CONTROL), { released: true });
+ assert.deepEqual(check("control,option", 0), { released: true });
+ assert.deepEqual(check("option,shift", OPTION | SHIFT), { released: false });
+ assert.deepEqual(check("option,shift", SHIFT | COMMAND), { released: true });
+ const bad = spawnSync(bin, ["--release-check", "control,hyper", "0"], { encoding: "utf8", timeout: 10_000 });
+ assert.equal(bad.status, 1);
+ assert.deepEqual(JSON.parse(bad.stdout), { error: "bad-modifiers" });
+});
+```
+
+- [ ] **Step 2: Run it to see it fail**
+
+Run: `node --test electron/speech-helper-release.node-test.mjs`
+Expected: FAIL (`--release-check` unknown: the helper goes on to ask for speech authorization and is killed or times out after 10 s).
+
+- [ ] **Step 3: Implement in `speech-helper.swift`**
+ - `import CoreGraphics`.
+ - `func releaseModifiers(_ list: String) -> CGEventFlags?` — map names to `.maskControl`, `.maskAlternate`, `.maskShift`, `.maskCommand`; nil for an empty list or any unknown name.
+ - `func released(_ required: CGEventFlags, _ current: CGEventFlags) -> Bool` — `!current.contains(required)`.
+ - `--release-check` handled right after these, before the stop/finish timers and `requestAuthorization`.
+ - `let finishOnRelease: CGEventFlags?` from `--finish-on-release` (absent → nil; invalid → `fail("bad-modifiers")`).
+ - The finish timer's guard becomes: finish file exists **or** `finishOnRelease.map { released($0, CGEventSource.flagsState(.combinedSessionState)) } == true`, still requiring `finishHandler`, so a release before the audio engine exists finishes on a later tick.
+ - One header line documenting `--finish-on-release`.
+
+- [ ] **Step 4: Run it to see it pass**
+
+Run: `node --test electron/speech-helper-release.node-test.mjs && node electron/build-speech-helper.mjs`
+Expected: PASS, and the universal build still links.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add electron/resources/speech-helper.swift electron/speech-helper-release.node-test.mjs
+git commit -m "feat(speech): finish recognition when the talk keys are let go"
+```
+
+---
+
+### Task 3: Speech sessions main can own
+
+`speech.mjs` imports `app` from `electron` (line 15), so its tests live in the existing vitest file `electron/speech.test.mjs` (which mocks `electron` and `node:child_process`), not a node-test.
+
+**Files:**
+- Modify: `electron/speech.mjs` (whole file: `child`, `sendEnd`, `startSpeech` 49-169, `stopSpeech` 171-178, `finishSpeech` 180-185)
+- Test: `electron/speech.test.mjs` (fixture records `args`; new tests in the darwin-only `describe`)
+
+**Interfaces:**
+- Produces:
+ - `startSpeech(target, options = {})` — `target` is a `BrowserWindow` (has `webContents`: unchanged behaviour) or a `SpeechSink` `{ transcript(line), end(info), replaced() }`. `options`: `{ endpointMs?: number, finishOnRelease?: string[] }`; known names only, deduplicated, joined with `,`; none left → flag omitted.
+ - A session replaced by another `startSpeech` calls the old target's `replaced()` (a window's is a no-op) and never its `end`.
+ - `stopSpeech(owner?)`, `finishSpeech(owner?)` — `owner` omitted (`undefined`): the current session, as today; otherwise only when the current session was started by that same window or sink (`null` matches nothing).
+ - `speechBusy(): boolean` — a session is running.
+
+- [ ] **Step 1: Write the failing tests**
+
+```js
+const sinkOf = () => {
+ const heard = { lines: [], ends: [], replaced: 0 };
+ return { heard, sink: { transcript: line => heard.lines.push(line), end: info => heard.ends.push(info), replaced: () => { heard.replaced += 1; } } };
+};
+const flag = (session, name) => session.args.includes(name) ? session.args[session.args.indexOf(name) + 1] : undefined;
+
+it("delivers a sink's session to the sink and tells the helper which keys end it", () => {
+ const { heard, sink } = sinkOf();
+ startSpeech(sink, { finishOnRelease: ["control", "option"] });
+ const session = fixture.launches.at(-1);
+ expect(flag(session, "--finish-on-release")).toBe("control,option");
+ expect(speechBusy()).toBe(true);
+ emit(session, { text: "what's on today", partial: false });
+ session.proc.emit("close", 0);
+ expect(heard.lines).toEqual([{ text: "what's on today", partial: false }]);
+ expect(heard.ends).toEqual([{ code: 0, reason: "completed" }]);
+ expect(speechBusy()).toBe(false);
+});
+it("tells a replaced sink, and never ends it", () => {
+ const { heard, sink } = sinkOf();
+ startSpeech(sink);
+ const first = fixture.launches.at(-1);
+ launch();
+ expect(heard.replaced).toBe(1);
+ first.proc.emit("close", 0);
+ expect(heard.ends).toEqual([]);
+});
+it("a page's stop or finish never touches a session it did not start", () => {
+ const { sink } = sinkOf();
+ startSpeech(sink);
+ const session = fixture.launches.at(-1);
+ const page = { isDestroyed: () => false, webContents: { send: () => {} } };
+ stopSpeech(page); finishSpeech(page); stopSpeech(null);
+ expect(existsSync(session.stop)).toBe(false);
+ expect(existsSync(session.finish)).toBe(false);
+ finishSpeech(sink); expect(existsSync(session.finish)).toBe(true);
+ stopSpeech(sink); expect(existsSync(session.stop)).toBe(true);
+ expect(speechBusy()).toBe(false);
+});
+it("passes only known release modifiers", () => {
+ startSpeech(sinkOf().sink, { finishOnRelease: ["control", "hyper", "control"] });
+ expect(flag(fixture.launches.at(-1), "--finish-on-release")).toBe("control");
+ startSpeech(sinkOf().sink, { finishOnRelease: ["hyper"] });
+ expect(fixture.launches.at(-1).args).not.toContain("--finish-on-release");
+});
+```
+
+- [ ] **Step 2: Run to see them fail**
+
+Run: `pnpm exec vitest run electron/speech.test.mjs`
+Expected: the four new tests FAIL (`speechBusy` is not exported); the four existing ones PASS.
+
+- [ ] **Step 3: Implement** — normalise the target once into `{ owner, transcript, end, replaced }` (a window's `transcript`/`end` send `speech:transcript`/`speech:end` when not destroyed; `replaced` is a no-op); keep it on the session record; every existing `child === speechSession` guard stays. In `startSpeech`, capture the running session before `stopSpeech()` and call its `replaced()` after.
+
+- [ ] **Step 4: Run to see them pass**
+
+Run: `pnpm exec vitest run electron/speech.test.mjs`
+Expected: PASS (8 tests on macOS; skipped elsewhere, as today).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add electron/speech.mjs electron/speech.test.mjs
+git commit -m "feat(speech): sessions owned by a sink, scoped stop and speechBusy"
+```
+
+---
+
+### Task 4: The setting, its keys, and registration
+
+**Files:**
+- Create: `electron/talk-keys.mjs`, `electron/talk-shortcut.mjs`, `electron/talk-shortcut.d.mts`
+- Modify: `electron/desktop-prefs.mjs` (`parse` 37-49, `createDesktopPrefs` 52-102, `registerDesktopPrefs` 113-116), `electron/desktop-prefs.d.mts` (`DesktopPrefs`, `registerDesktopPrefs` options)
+- Test: `electron/desktop-prefs.node-test.mjs` (add), `electron/talk-shortcut.node-test.mjs` (new)
+
+**Interfaces:**
+- Produces (`talk-keys.mjs`): `TALK_KEYS` (frozen `{ [id]: { accelerator, release, label } }`, values in Global Constraints, in that order), `DEFAULT_TALK_KEY = "ctrl-opt-space"`, `isTalkKey(id: unknown): boolean` (own keys only), `talkKey(id): { accelerator, release, label }` (default for anything else).
+- Produces (`DesktopPrefs`): `talkShortcut(): boolean` (true until set), `setTalkShortcut(enabled: boolean): void` (only `true` is on), `talkKey(): TalkKeyId`, `setTalkKey(id: unknown): boolean`, `quickAsksChat(server: string): { botId, threadId } | null`, `setQuickAsksChat(server: string, chat: { botId, threadId }): void`. Stored as `quickAsks: { [server]: { botId, threadId } }`; ids match `/^[\w-]{1,128}$/`, anything else is dropped on read. `registerDesktopPrefs({ prefs?: DesktopPrefs, … })` uses the given store instead of making one.
+- Produces (`talk-shortcut.mjs`):
+ - `createTalkShortcut({ globalShortcut, prefs, available: () => boolean, onPress: () => void })` → `{ state(): TalkShortcutState, set(change: { enabled?, key? }): TalkShortcutState, releaseModifiers(): string[], close(): void }`. `TalkShortcutState = { available, enabled, key, keys: [{ id, label }], taken }`; `taken`: on, but `register` returned false.
+ - `createCallPresence()` → `{ set(sender, active: boolean): void, active(): boolean }`; a sender stops counting on its `destroyed`, `render-process-gone` or `did-navigate`, with at most one listener per event per sender.
+- Produces (`talk-shortcut.d.mts`): `TalkKeyId`, `TalkShortcutState`, `TalkShortcutChange`, `TalkShortcutBridge { state(): Promise<TalkShortcutState>; set(change: TalkShortcutChange): Promise<TalkShortcutState> }`, and declarations for both factories.
+
+- [ ] **Step 1: Write the failing prefs tests** (`desktop-prefs.node-test.mjs`)
+
+```js
+test("the talk shortcut is on with ⌃⌥Space until changed, and the choice survives a restart", () => {
+ let saved = null;
+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+ assert.equal(prefs.talkShortcut(), true);
+ assert.equal(prefs.talkKey(), "ctrl-opt-space");
+ prefs.setTalkShortcut(false);
+ assert.equal(prefs.setTalkKey("opt-shift-space"), true);
+ for (const key of ["cmd-space", "__proto__", "toString", 7]) assert.equal(prefs.setTalkKey(key), false);
+ const restarted = createDesktopPrefs({ read: () => saved, write: () => {} });
+ assert.equal(restarted.talkShortcut(), false);
+ assert.equal(restarted.talkKey(), "opt-shift-space");
+ const junk = createDesktopPrefs({ read: () => ({ talkShortcut: "off", talkKey: "toString" }), write: () => {} });
+ assert.equal(junk.talkShortcut(), true);
+ assert.equal(junk.talkKey(), "ctrl-opt-space");
+});
+test("each server keeps its own Quick asks chat; nothing malformed is read back", () => {
+ let saved = null;
+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+ prefs.setQuickAsksChat("/Users/a/.openmausbot", { botId: "bot-1", threadId: "t-1" });
+ assert.deepEqual(createDesktopPrefs({ read: () => saved, write: () => {} }).quickAsksChat("/Users/a/.openmausbot"), { botId: "bot-1", threadId: "t-1" });
+ assert.equal(prefs.quickAsksChat("/Users/a/.openmausbot-aprs"), null);
+ const broken = createDesktopPrefs({ read: () => ({ quickAsks: { a: { botId: "../x", threadId: "t" }, b: "t-1", c: { botId: "b", threadId: "t", extra: 1 } } }), write: () => {} });
+ assert.equal(broken.quickAsksChat("a"), null);
+ assert.equal(broken.quickAsksChat("b"), null);
+ assert.deepEqual(broken.quickAsksChat("c"), { botId: "b", threadId: "t" });
+});
+test("registerDesktopPrefs works on the store main hands it", async () => {
+ const prefs = createDesktopPrefs({ read: () => null, write: () => {} });
+ const handlers = new Map();
+ registerDesktopPrefs({ prefs, ipcMain: { handle: (c, h) => handlers.set(c, h), on: () => {} }, read: () => null, write: () => {},
+ page: () => "local", cloudOffered: async () => false });
+ await handlers.get("desktop-analytics:set")({}, false);
+ assert.equal(prefs.analytics(), false);
+});
+```
+
+- [ ] **Step 2: Write the failing shortcut tests** (`talk-shortcut.node-test.mjs`; `memoryPrefs()` is a real `createDesktopPrefs` over an in-memory record: `let saved = null; createDesktopPrefs({ read: () => saved, write: v => { saved = structuredClone(v); } })`)
+
+```js
+const fakeShortcuts = (taken = []) => {
+ const registered = new Map();
+ return { registered, register: (accelerator, fn) => !taken.includes(accelerator) && Boolean(registered.set(accelerator, fn)),
+ unregister: accelerator => { registered.delete(accelerator); } };
+};
+const KEYS = [{ id: "ctrl-opt-space", label: "⌃⌥Space" }, { id: "ctrl-shift-space", label: "⌃⇧Space" }, { id: "opt-shift-space", label: "⌥⇧Space" }];
+
+test("registers the saved key when on; a press reaches onPress", () => {
+ const shortcuts = fakeShortcuts(); let presses = 0;
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs: memoryPrefs(), available: () => true, onPress: () => { presses += 1; } });
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Alt+Space"]);
+ shortcuts.registered.get("Control+Alt+Space")();
+ assert.equal(presses, 1);
+ assert.deepEqual(talk.state(), { available: true, enabled: true, key: "ctrl-opt-space", keys: KEYS, taken: false });
+ assert.deepEqual(talk.releaseModifiers(), ["control", "option"]);
+});
+test("a key another app holds is reported, and another key can be chosen", () => {
+ const shortcuts = fakeShortcuts(["Control+Alt+Space"]); const prefs = memoryPrefs();
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs, available: () => true, onPress: () => {} });
+ assert.equal(talk.state().taken, true);
+ assert.deepEqual(talk.set({ key: "ctrl-shift-space" }), { available: true, enabled: true, key: "ctrl-shift-space", keys: KEYS, taken: false });
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Shift+Space"]);
+ assert.deepEqual(talk.releaseModifiers(), ["control", "shift"]);
+ assert.equal(prefs.talkKey(), "ctrl-shift-space");
+});
+test("off lets the key go, on takes it again, close lets it go"); // set({enabled:false}) → registered empty, prefs.talkShortcut() false; set({enabled:true}) → ["Control+Alt+Space"]; close() → empty
+test("an unknown key changes nothing"); // set({ key: "cmd-space" }) → registered still ["Control+Alt+Space"], prefs.talkKey() "ctrl-opt-space"
+test("where Apple speech is unavailable nothing registers and nothing changes"); // available: () => false → registered empty; set({enabled:false}) → prefs.talkShortcut() true; state().available false
+test("a reported call blocks until it ends, its page navigates, or its renderer goes away", () => {
+ const presence = createCallPresence(), page = Object.assign(new EventEmitter(), { id: 1 });
+ presence.set(page, true); assert.equal(presence.active(), true);
+ presence.set(page, false); assert.equal(presence.active(), false);
+ for (const event of ["did-navigate", "render-process-gone", "destroyed"]) {
+ presence.set(page, true); page.emit(event); assert.equal(presence.active(), false, event);
+ }
+ for (let i = 0; i < 5; i += 1) presence.set(page, true);
+ assert.ok(page.listenerCount("destroyed") <= 1);
+});
+```
+
+- [ ] **Step 3: Run to see them fail**
+
+Run: `node --test electron/desktop-prefs.node-test.mjs electron/talk-shortcut.node-test.mjs`
+Expected: FAIL (`prefs.talkShortcut is not a function`; `talk-shortcut.mjs` missing).
+
+- [ ] **Step 4: Implement** the three modules and the `.d.mts` changes. `set()` saves to prefs first, then unregisters the registered accelerator (if any) and registers the current one when enabled and available; `taken` is recomputed on each registration. `talk-shortcut.d.mts` comments: `available` (false hides the setting), `taken` (on, but another app holds the key).
+
+- [ ] **Step 5: Run to see them pass**
+
+Run: `node --test electron/desktop-prefs.node-test.mjs electron/talk-shortcut.node-test.mjs`
+Expected: PASS (existing prefs tests unchanged; the file written by `setAnalytics(false)` is still exactly `{ seen: [], shown: {}, analytics: false }`).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add electron/talk-keys.mjs electron/talk-shortcut.mjs electron/talk-shortcut.d.mts electron/talk-shortcut.node-test.mjs electron/desktop-prefs.mjs electron/desktop-prefs.d.mts electron/desktop-prefs.node-test.mjs
+git commit -m "feat(talk): the talk shortcut setting, its keys and registration"
+```
+
+---
+
+### Task 5: Talk to this computer's server
+
+**Files:**
+- Create: `electron/talk-server.mjs`, `electron/talk-server.d.mts`
+- Test: `electron/talk-server.node-test.mjs` (new, fake `request`), `server/talk-server.e2e.test.ts` (new, real fixture as the packaged desktop calls it)
+
+**Interfaces:**
+- Consumes: `select: false` (Task 1); prefs `quickAsksChat`/`setQuickAsksChat` (Task 4).
+- Produces:
+ - `QUICK_ASKS_TITLE = "Quick asks"`; `class TalkServerError extends Error` with `code: "server-down" | "no-mausbot" | "refused" | "lost"`.
+ - `findMausBot(bots)` → the bot with `defaultBot` and an empty `defaultBot.person`, else the first `chiefOfStaff` bot that is not `hidden`, else `null`.
+ - `readFrames(body: ReadableStream<Uint8Array>, onFrame: (frame: object) => void): Promise<void>` — SSE: frames end at a blank line, `data:` lines joined, `:` comments and unparsable JSON skipped.
+ - `createReplyTracker({ threadId, sendId })` → `(frame) => TalkUpdate | null`, `TalkUpdate = { kind: "thinking" } | { kind: "reply", text } | { kind: "needs-you" } | { kind: "done", ok, text }`.
+ - `createTalkServer({ request: (route, init?) => Promise<Response>, prefs, serverKey: () => string })` → `{ prepare(): Promise<TalkChat>, ask({ chat, text, sendId, signal, onUpdate }): Promise<"done" | "needs-you" | "failed"> }`, `TalkChat = { botId, threadId }`.
+
+Tracker rules (the algorithm the tests do not fully determine): frames for other threads, and every frame before `{ kind: "message", message: { role: "user", sendId } }` with this ask's `sendId`, return null; that frame returns `thinking`. After it: `runtime` `content.delta` (`streamKind: "assistant_text"`) appends to a buffer that restarts when `itemId` changes → `reply` with the buffer; `runtime` `item.completed` (`itemType: "assistant_text"`) and a `message` with `role: "bot", kind: "text"` replace the shown text → `reply`; a `message` with `role: "bot", kind: "options"` whose `card` is not `answered`, `dismissed` or `expired`, or a `runtime` `request.opened` → `needs-you`; `runtime` `turn.completed` → `done` with its `ok` and the last shown text.
+
+`prepare()`: `GET /api/bots?messages=0` (a rejected request or non-2xx → `server-down`; no MausBot → `no-mausbot`); reuse `prefs.quickAsksChat(serverKey())` when its `botId` is MausBot's and MausBot's `tasks` still list its `threadId`; else `POST /api/bots/:id/tasks` with exactly `{ title: QUICK_ASKS_TITLE, select: false }`, save and return it. One prepare in flight at a time: a second call while one runs gets the same promise.
+
+`ask()`: `GET /api/events?screens=off` first; wait for its `{ kind: "hello" }` frame; then `POST /api/bots/:botId/messages` with exactly `{ text, threadId, sendId }` (non-2xx → `refused`). Resolve on `done` (`"failed"` when `ok` is false and the text is empty) or `needs-you`; the stream ending first → `lost`; `signal` aborting → reject with `signal.reason` and cancel the stream. `content-type: application/json` on both POSTs.
+
+- [ ] **Step 1: Write the failing unit tests** (frame builders: `userMessage(threadId, sendId)`, `delta(threadId, itemId, text)`, `botText(threadId, text)`, `card(threadId, cardFields)` (a `role: "bot", kind: "options"` message), `opened(threadId)`, `completed(threadId, ok)`. `fakeServer({ bots, saved = null, sendStatus = 202 })` returns `{ talk, calls, saves, events }`: `talk = createTalkServer({ request, serverKey: () => "server-a", prefs: { quickAsksChat: () => saved, setQuickAsksChat: (server, chat) => saves.push([server, chat]) } })`; `request` answers `GET /api/bots?messages=0` with `{ bots }`, `POST …/tasks` with 201 `{ task: { threadId: "t-new", title: "Quick asks" } }`, `GET /api/events?screens=off` with a `ReadableStream` the test drives through `events.push(frame)` / `events.end()`, `POST …/messages` with `sendStatus`; `calls` records `[method, route, parsedBody]`. `flush = () => new Promise(r => setImmediate(r))`)
+
+```js
+test("findMausBot picks this computer's MausBot, else the Chief of Staff", () => {
+ const mine = { id: "m", defaultBot: {} }, member = { id: "p", defaultBot: { person: "[email protected]" } }, chief = { id: "c", chiefOfStaff: true };
+ assert.equal(findMausBot([member, chief, mine]).id, "m");
+ assert.equal(findMausBot([member, chief]).id, "c");
+ assert.equal(findMausBot([{ id: "x" }, { ...chief, hidden: true }]), null);
+});
+test("prepare reuses the saved Quick asks chat while MausBot still has it"); // saved {botId:"m",threadId:"t1"}, tasks [{threadId:"t1"}] → returns saved; no POST in calls
+test("prepare makes a Quick asks chat without selecting it when the saved one is gone, and keeps it", async () => {
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }], saved: { botId: "m", threadId: "t-gone" } });
+ assert.deepEqual(await server.talk.prepare(), { botId: "m", threadId: "t-new" });
+ assert.deepEqual(server.calls.at(-1), ["POST", "/api/bots/m/tasks", { title: "Quick asks", select: false }]);
+ assert.deepEqual(server.saves, [["server-a", { botId: "m", threadId: "t-new" }]]);
+});
+test("two prepares at once make one chat"); // Promise.all([prepare(), prepare()]) → one POST
+test("prepare says why it cannot ask"); // request rejects → code "server-down"; 503 → "server-down"; bots [] → "no-mausbot"
+test("the reply tracker follows only this ask", () => {
+ const track = createReplyTracker({ threadId: "t1", sendId: "s1" });
+ for (const early of [delta("t1", "i0", "old answer"), completed("t1", true), userMessage("t1", "s0"), userMessage("t2", "s1")]) assert.equal(track(early), null);
+ assert.deepEqual(track(userMessage("t1", "s1")), { kind: "thinking" });
+ assert.deepEqual(track(delta("t1", "i1", "Let me ")), { kind: "reply", text: "Let me " });
+ assert.deepEqual(track(delta("t1", "i1", "check")), { kind: "reply", text: "Let me check" });
+ assert.deepEqual(track(delta("t1", "i2", "You have")), { kind: "reply", text: "You have" });
+ assert.deepEqual(track(botText("t1", "You have two meetings.")), { kind: "reply", text: "You have two meetings." });
+ assert.equal(track(delta("t2", "i9", "elsewhere")), null);
+ assert.deepEqual(track(completed("t1", true)), { kind: "done", ok: true, text: "You have two meetings." });
+});
+test("a waiting card or an opened request means MausBot needs the person", () => {
+ const track = createReplyTracker({ threadId: "t1", sendId: "s1" });
+ track(userMessage("t1", "s1"));
+ assert.equal(track(card("t1", { answered: "Allow" })), null);
+ assert.deepEqual(track(card("t1", {})), { kind: "needs-you" });
+ assert.deepEqual(track(opened("t1")), { kind: "needs-you" });
+});
+test("ask listens before it sends, posts to the Quick asks chat, and ends with the turn", async () => {
+ const server = fakeServer({ bots: [] });
+ const updates = [];
+ const asking = server.talk.ask({ chat: { botId: "m", threadId: "t1" }, text: "hi", sendId: "s1", signal: new AbortController().signal, onUpdate: u => updates.push(u) });
+ await flush();
+ assert.deepEqual(server.calls.map(c => c[1]), ["/api/events?screens=off"]);
+ server.events.push({ kind: "hello", cursor: "s:1", resumed: false });
+ await flush();
+ assert.deepEqual(server.calls[1], ["POST", "/api/bots/m/messages", { text: "hi", threadId: "t1", sendId: "s1" }]);
+ for (const frame of [userMessage("t1", "s1"), botText("t1", "Hello"), completed("t1", true)]) server.events.push(frame);
+ assert.equal(await asking, "done");
+ assert.deepEqual(updates.map(u => u.kind), ["thinking", "reply", "done"]);
+});
+test("a refused send, a lost stream, a failed turn and an abort"); // sendStatus 409 → rejects code "refused"; events.end() after thinking → "lost"; completed ok:false with nothing shown → resolves "failed"; card → resolves "needs-you"; controller.abort() → rejects { name: "AbortError" }
+test("readFrames joins frames split across chunks and skips heartbeats and junk", async () => {
+ const chunks = [": heartbeat\n\n", "id: s:1\ndata: {\"kind\":\"he", "llo\"}\n\ndata: not json\n\n", "data: {\"kind\":\"x\"}\n\n"];
+ const frames = [];
+ await readFrames(ReadableStream.from(chunks.map(c => new TextEncoder().encode(c))), f => frames.push(f));
+ assert.deepEqual(frames, [{ kind: "hello" }, { kind: "x" }]);
+});
+```
+
+- [ ] **Step 2: Write the failing fixture test** (`server/talk-server.e2e.test.ts`; launch with `OMB_TEST_DESKTOP_OWNER_TOKEN: owner` and send `x-openmausbot-desktop-owner` on every request, as `server/chat-pages.e2e.test.ts:54-56` does, so it runs the packaged desktop's path)
+
+```ts
+it("asks MausBot in its own Quick asks chat, as the desktop app does, and follows the reply to the end", async () => {
+ let saved: TalkChat | null = null;
+ const talk = createTalkServer({ request, serverKey: () => "fixture", prefs: { quickAsksChat: () => saved, setQuickAsksChat: (_s, chat) => { saved = chat; } } });
+ const before = (await (await request("/api/bots?messages=0")).json()).bots.find((b: any) => b.defaultBot);
+ const chat = await talk.prepare();
+ expect(chat.botId).toBe(before.id);
+ const updates: TalkUpdate[] = [];
+ expect(await talk.ask({ chat, text: "What can you do?", sendId: randomUUID(), signal: AbortSignal.timeout(60_000), onUpdate: u => updates.push(u) })).toBe("done");
+ expect(updates[0]).toEqual({ kind: "thinking" });
+ expect(updates.at(-1)).toMatchObject({ kind: "done", ok: true, text: expect.stringContaining("hello from fake claude") });
+ const after = (await (await request("/api/bots?messages=0")).json()).bots.find((b: any) => b.id === chat.botId);
+ expect(after.threadId).toBe(before.threadId);
+ expect(after.tasks.find((t: any) => t.threadId === chat.threadId).title).toBe(QUICK_ASKS_TITLE);
+ expect(await talk.prepare()).toEqual(chat);
+}, 90_000);
+```
+
+- [ ] **Step 3: Run to see them fail**
+
+Run: `node --test electron/talk-server.node-test.mjs && pnpm exec vitest run server/talk-server.e2e.test.ts`
+Expected: FAIL (`talk-server.mjs` missing).
+
+- [ ] **Step 4: Implement** `talk-server.mjs` and its `.d.mts`.
+
+- [ ] **Step 5: Run to see them pass**
+
+Run: `node --test electron/talk-server.node-test.mjs && pnpm exec vitest run server/talk-server.e2e.test.ts && pnpm typecheck`
+Expected: PASS. If the fixture shows a wire shape the unit fakes assumed wrongly (the hello frame, `sendId` on the echoed user message, delta `itemId`), fix the fakes and the module, not the fixture test.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add electron/talk-server.mjs electron/talk-server.d.mts electron/talk-server.node-test.mjs server/talk-server.e2e.test.ts
+git commit -m "feat(talk): find MausBot, keep the Quick asks chat and follow the reply"
+```
+
+---
+
+### Task 6: The box
+
+**Files:**
+- Create: `electron/talk-panel.mjs`, `electron/talk-panel-preload.cjs`
+- Test: `electron/talk-panel.node-test.mjs` (new; `harness({ cursor, workArea })` builds a fake `BrowserWindow` class (each instance in `made`) recording `options`, `url`, `bounds` and `calls` (`setAlwaysOnTop`, `setVisibleOnAllWorkspaces`, `show`, `focus`, `showInactive`), whose `webContents` is an `EventEmitter` with `scripts`, `executeJavaScript` resolving `96`, and `setWindowOpenHandler`; a fake `screen` answering `cursor` and `workArea`; `opened`/`dismissed` arrays from `onOpen`/`onDismiss`. `pick(object, keys)` copies the named keys; `flush = () => new Promise(r => setImmediate(r))`)
+
+**Interfaces:**
+- Produces:
+ - `TALK_PANEL = { width: 400, margin: 24, minHeight: 56, maxHeight: 240, fadeMs: 180 }` (frozen).
+ - `TALK_LABELS` (frozen): `listening: "Listening…"`, `sending: "Sending to MausBot…"`, `thinking: "MausBot is thinking…"`, `reply: "MausBot"`, `"needs-you": "MausBot needs you · Open chat"`, `"still-working": "Still working · Open chat"`, `error: ""`.
+ - `TalkView = { state: "listening" | "sending" | "thinking" | "reply" | "needs-you" | "still-working" | "error", text: string }`.
+ - `talkPanelBounds(workArea, height)` → `{ x, y, width, height }`: centred, `margin` above the work area's bottom, height clamped to `[minHeight, maxHeight]`.
+ - `replyPreview(text, limit = 400): string` — drop Markdown heading marks, list markers, `**`/`__`/`*`/`_` emphasis, backticks and fences; `[label](url)` → `label`; collapse whitespace; over `limit`, cut at the last space before it and add `…`.
+ - `talkPanelHtml(iconBase64): string` — the page.
+ - `isTalkPanel(win): boolean`.
+ - `createTalkPanel({ BrowserWindow, screen, iconPath, onOpen, onDismiss })` → `{ render(view: TalkView): void, close(): void, hovered(): boolean }`.
+
+Window (first `render` after creation or after `close`): `new BrowserWindow({ type: "panel", ...talkPanelBounds(workArea of screen.getDisplayNearestPoint(screen.getCursorScreenPoint()), TALK_PANEL.minHeight), frame: false, transparent: true, backgroundColor: "#00000000", focusable: false, skipTaskbar: true, hasShadow: false, resizable: false, movable: false, minimizable: false, maximizable: false, fullscreenable: false, show: false, acceptFirstMouse: true, hiddenInMissionControl: true, webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false, spellcheck: false, preload } })`; then `excludedFromShownWindowsMenu = true`, `setAlwaysOnTop(true, "screen-saver")`, `setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, skipTransformProcessType: true })`, deny `setWindowOpenHandler`, `preventDefault` on `will-navigate`, load `data:text/html;charset=utf-8,` + the page. `acceptFirstMouse` is the Electron/macOS fact that lets a click on an inactive window reach the page: say so in a one-line comment. `skipTransformProcessType` keeps the Dock icon: same.
+
+Rendering: `render(view)` keeps the latest view; once the page has loaded, run `render(<JSON of { state, text: replyPreview(view.text) }>)` in the page; its return value is the card's height in px; `setBounds(talkPanelBounds(workArea, height))`; the first sized render calls `showInactive()`. `close()` runs `fadeOut()` in a loaded page and destroys the window `fadeMs` later (at once if not loaded); the next `render` makes a new window. `hovered()`: `screen.getCursorScreenPoint()` inside the window's bounds; false with no window. `ipc-message` on this window's `webContents`: `talk-panel:open` → `onOpen()`, `talk-panel:dismiss` → `onDismiss()`, anything else ignored.
+
+Page: CSP `default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'`; dark card from the default skin's tokens (`--color-panel #111111` at 96%, border `#ffffff16`, radius 16 px, ink `#fcfcfc`, secondary `#fcfcfcbf`, accent `#1084fe` pulse ring on the mascot while listening, warning `#ff9800` for needs-you, danger `#ff5667` for error), `-apple-system` 13 px, the app icon (`electron/resources/app-icon.png`, as the splash inlines it) at 28 px, label from `TALK_LABELS`, text in a `role="status"` line written with `textContent` only, "Let go to send" while listening with no words yet, a × button (`stopPropagation` → `talk.dismiss()`), the card's click → `talk.open()`, a 160 ms opacity fade, `prefers-reduced-motion` respected. Preload: `contextBridge.exposeInMainWorld("talk", { open, dismiss })` over `ipcRenderer.send("talk-panel:open" | "talk-panel:dismiss")`, nothing else.
+
+- [ ] **Step 1: Write the failing tests**
+
+```js
+test("talkPanelBounds sits the box bottom-centre of the work area, clamped", () => {
+ assert.deepEqual(talkPanelBounds({ x: 0, y: 25, width: 1440, height: 875 }, 72), { x: 520, y: 804, width: 400, height: 72 });
+ assert.deepEqual(talkPanelBounds({ x: 1440, y: 0, width: 1920, height: 1050 }, 500), { x: 2200, y: 786, width: 400, height: 240 });
+ assert.equal(talkPanelBounds({ x: 0, y: 0, width: 800, height: 600 }, 10).height, 56);
+});
+test("the box is a non-activating panel on every Space, shown without focus on the display under the pointer", async () => {
+ const { panel, made } = harness({ cursor: { x: 2000, y: 500 }, workArea: { x: 1440, y: 25, width: 1440, height: 875 } });
+ panel.render({ state: "listening", text: "" });
+ const win = made[0];
+ assert.deepEqual(pick(win.options, ["type", "focusable", "transparent", "frame", "skipTaskbar", "hasShadow", "resizable", "show", "acceptFirstMouse", "hiddenInMissionControl"]),
+ { type: "panel", focusable: false, transparent: true, frame: false, skipTaskbar: true, hasShadow: false, resizable: false, show: false, acceptFirstMouse: true, hiddenInMissionControl: true });
+ assert.deepEqual(win.calls.filter(c => c[0] !== "setBounds"), [["setAlwaysOnTop", true, "screen-saver"], ["setVisibleOnAllWorkspaces", true, { visibleOnFullScreen: true, skipTransformProcessType: true }]]);
+ assert.ok(win.url.startsWith("data:text/html"));
+ win.webContents.emit("did-finish-load");
+ await flush();
+ assert.match(win.webContents.scripts[0], /^render\(\{"state":"listening","text":""\}\)$/);
+ assert.deepEqual(win.bounds, { x: 1960, y: 780, width: 400, height: 96 });
+ assert.deepEqual(win.calls.map(c => c[0]).filter(n => ["show", "focus", "showInactive"].includes(n)), ["showInactive"]);
+});
+test("the page shows reply text as plain text, never HTML", () => {
+ assert.equal(replyPreview("## Today\n\n- **Standup** at 10\n- [Lunch](https://x.test) with `Sam`"), "Today Standup at 10 Lunch with Sam");
+ assert.equal(replyPreview("<img src=x onerror=alert(1)>"), "<img src=x onerror=alert(1)>");
+ const cut = replyPreview("word ".repeat(120));
+ assert.ok(cut.length <= 401 && cut.endsWith("…") && !cut.endsWith(" …") && !cut.includes("wor…"));
+ const html = talkPanelHtml("AAAA");
+ assert.match(html, /default-src 'none'/);
+ assert.match(html, /textContent/);
+ assert.doesNotMatch(html, /innerHTML|insertAdjacentHTML|outerHTML|https?:\/\//);
+});
+test("the page's bridge is open and dismiss, and they count only from this box", async () => {
+ const preload = readFileSync(new URL("./talk-panel-preload.cjs", import.meta.url), "utf8");
+ assert.deepEqual([...preload.matchAll(/ipcRenderer\.(\w+)\("([^"]+)"/g)].map(m => [m[1], m[2]]), [["send", "talk-panel:open"], ["send", "talk-panel:dismiss"]]);
+ const { panel, made, opened, dismissed } = harness();
+ panel.render({ state: "reply", text: "Hi" });
+ made[0].webContents.emit("ipc-message", {}, "talk-panel:open");
+ made[0].webContents.emit("ipc-message", {}, "talk-panel:other");
+ made[0].webContents.emit("ipc-message", {}, "talk-panel:dismiss");
+ assert.deepEqual([opened.length, dismissed.length], [1, 1]);
+});
+test("navigation and new windows are refused"); // will-navigate event.defaultPrevented true; openHandler() → { action: "deny" }
+test("close fades, then destroys; the next render makes a new box; hovered follows the pointer"); // mock.timers: close() → scripts.at(-1) "fadeOut()"; tick(179) not destroyed; tick(1) destroyed; render → made.length 2; cursor inside bounds → hovered() true, outside → false
+test("isTalkPanel tells the box from app windows"); // isTalkPanel(made[0]) true; isTalkPanel({}) false
+```
+
+- [ ] **Step 2: Run to see them fail**
+
+Run: `node --test electron/talk-panel.node-test.mjs`
+Expected: FAIL (`talk-panel.mjs` missing).
+
+- [ ] **Step 3: Implement** `talk-panel.mjs` and `talk-panel-preload.cjs`.
+
+- [ ] **Step 4: Run to see them pass**
+
+Run: `node --test electron/talk-panel.node-test.mjs`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add electron/talk-panel.mjs electron/talk-panel-preload.cjs electron/talk-panel.node-test.mjs
+git commit -m "feat(talk): the floating box that never takes focus"
+```
+
+---
+
+### Task 7: One ask, from press to reply
+
+**Files:**
+- Create: `electron/talk-session.mjs`
+- Test: `electron/talk-session.node-test.mjs` (new; `mock.timers.enable({ apis: ["setTimeout"] })` per test and `mock.timers.reset()` after, `flush = () => new Promise(r => setImmediate(r))`, `pick(object, keys)` copies the named keys)
+
+**Interfaces:**
+- Consumes: `speech` `{ start(sink, { finishOnRelease }), stop(sink) }` (Task 3 via main); `server` `{ prepare, ask }` and `TalkServerError` codes (Task 5); `panel` `{ render(view), close(), hovered() }` and `TalkView` (Task 6).
+- Produces:
+ - `TALK_TIMING = { replyHideMs: 12_000, noticeHideMs: 4_000, stillWorkingMs: 120_000, hoverRecheckMs: 500 }` (frozen).
+ - `TALK_TEXT` (frozen): `busy: "Voice is in use in MausBot"`, `serverDown: "Open MausBot to talk"`, `permission: "Talking needs Microphone + Speech Recognition access — System Settings → Privacy & Security."`, `dictationOff: "Turn on Dictation in System Settings → Keyboard, then try again."`, `unavailable: "Talking couldn't start. Try again."`, `failed: "MausBot couldn't take that · Open chat"`.
+ - `createTalkSession({ speech, server, panel, voiceInUse: () => boolean, release: () => string[], openChat: (chat: TalkChat | null) => void, newSendId = randomUUID })` → `{ press(), open(), dismiss(), close() }`.
+
+| Phase | `press()` | `open()` | `dismiss()` / `close()` |
+| --- | --- | --- | --- |
+| idle | `voiceInUse()` → error `busy`, hide in `noticeHideMs`; else render `listening ""`, `speech.start(sink, { finishOnRelease: release() })`, start `server.prepare()` | — | — |
+| listening | ignored | `speech.stop(sink)`, `openChat(null)`, close box | `speech.stop(sink)`, close box |
+| sending, thinking | ignored | abort ask, `openChat(chat)`, close box | abort ask, close box |
+| reply, needs-you, still-working, error | abort ask, close box, start a new ask as from idle | abort ask, `openChat(chat ?? null)`, close box | abort ask, close box |
+
+Each press makes a new sink and `AbortController`; callbacks from an older one are ignored. Sink: `transcript(line)` → render `listening` with `line.text`; `replaced()` → close box; `end(info)`: reason `speech-not-authorized`, `mic-failed` or `recognizer-unavailable` → error `permission`; `dictation-disabled` → `dictationOff`; `helper-build-failed`, `helper-start-failed` or `unsupported-platform` → `unavailable` (these three hide in `noticeHideMs`); otherwise nothing heard → close box silently; otherwise render `sending` with the words and ask. `prepare()` failing (`server-down`, `no-mausbot`) while listening stops speech and shows `serverDown`; at send time it shows the same. The ask: `thinking` → render `thinking` with the words; `reply` → render `reply`; `done` → render `reply`, hide in `replyHideMs`; `needs-you` → render `needs-you` with the last reply text, hide in `replyHideMs`; `"failed"` or `refused` → error `failed`, hide in `replyHideMs`; `lost`, or `stillWorkingMs` after sending with no outcome → abort, render `still-working` with the last reply text, hide in `replyHideMs`. Hiding: when the timer fires and `panel.hovered()`, check again every `hoverRecheckMs`.
+
+- [ ] **Step 1: Write the failing tests**
+
+```js
+const CHAT = { botId: "m", threadId: "t1" };
+function harness({ busy = false, prepare = async () => CHAT, ask } = {}) {
+ const h = { views: [], closed: 0, hovered: false, starts: [], stops: [], opened: [], asks: [], sink: null };
+ h.session = createTalkSession({
+ speech: { start: (sink, options) => { h.sink = sink; h.starts.push(options); }, stop: sink => h.stops.push(sink === h.sink) },
+ server: { prepare, ask: ask ?? (async input => { h.asks.push(input); input.onUpdate({ kind: "thinking" }); input.onUpdate({ kind: "reply", text: "Hi" }); input.onUpdate({ kind: "done", ok: true, text: "Hi" }); return "done"; }) },
+ panel: { render: view => h.views.push(view), close: () => { h.closed += 1; }, hovered: () => h.hovered },
+ voiceInUse: () => busy, release: () => ["control", "option"], openChat: chat => h.opened.push(chat), newSendId: () => "send-1",
+ });
+ return h;
+}
+const say = (h, text) => h.sink.transcript({ text, partial: true });
+const release = (h, info = { code: 0, reason: "completed" }) => h.sink.end(info);
+
+test("a press listens with the key's release modifiers and shows the live words", () => {
+ const h = harness(); h.session.press(); say(h, "what's on");
+ assert.deepEqual(h.starts, [{ finishOnRelease: ["control", "option"] }]);
+ assert.deepEqual(h.views, [{ state: "listening", text: "" }, { state: "listening", text: "what's on" }]);
+});
+test("letting go sends the words to the Quick asks chat and shows the reply, which hides 12 s later", async () => {
+ const h = harness(); h.session.press(); say(h, "what's on my calendar"); release(h); await flush();
+ assert.deepEqual(pick(h.asks[0], ["chat", "text", "sendId"]), { chat: CHAT, text: "what's on my calendar", sendId: "send-1" });
+ assert.deepEqual([...new Set(h.views.map(v => v.state))], ["listening", "sending", "thinking", "reply"]);
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi" });
+ mock.timers.tick(11_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+test("a reply under the pointer stays until the pointer leaves"); // hovered = true; tick(12_000) closed 0; hovered = false; tick(500) closed 1
+test("presses while listening, sending or thinking are ignored"); // ask pending forever: press ×2 while listening, release, press while sending → starts.length 1
+test("a press while a reply shows closes it and starts a new ask"); // ask stays open after a reply update: press → its signal.aborted true, closed 1, starts.length 2, views.at(-1) listening ""
+test("voice in use refuses without listening", () => {
+ const h = harness({ busy: true }); h.session.press();
+ assert.deepEqual(h.starts, []);
+ assert.deepEqual(h.views, [{ state: "error", text: "Voice is in use in MausBot" }]);
+ mock.timers.tick(4_000); assert.equal(h.closed, 1);
+});
+test("an empty transcript closes silently, even when the recognizer reports an error", async () => {
+ for (const info of [{ code: 0, reason: "completed" }, { code: 1, reason: "recognition-error" }, { code: 1, reason: "helper-exited" }]) {
+ const h = harness(); h.session.press(); release(h, info); await flush();
+ assert.equal(h.closed, 1, info.reason); assert.equal(h.asks.length, 0);
+ assert.ok(h.views.every(v => v.state === "listening"), info.reason);
+ }
+});
+test("words heard before a recognizer error are still sent"); // say "remind me", release {code:1, reason:"recognition-error"} → asks[0].text "remind me"
+test("permission and setup problems say what to fix"); // speech-not-authorized → TALK_TEXT.permission; dictation-disabled → dictationOff; helper-start-failed → unavailable; each hides after 4 s
+test("the server not running says Open MausBot to talk and stops listening", async () => {
+ const h = harness({ prepare: async () => { throw new TalkServerError("server-down"); } });
+ h.session.press(); await flush();
+ assert.deepEqual(h.stops, [true]);
+ assert.deepEqual(h.views.at(-1), { state: "error", text: "Open MausBot to talk" });
+ mock.timers.tick(4_000); assert.equal(h.closed, 1);
+});
+test("needs-you shows and hides like a reply"); // ask: onUpdate reply "Checking", needs-you, resolve "needs-you" → views.at(-1) { state: "needs-you", text: "Checking" }; tick(12_000) closed 1
+test("no answer in 120 s shows Still working · Open chat", async () => {
+ let signal; const h = harness({ ask: async input => { signal = input.signal; input.onUpdate({ kind: "thinking" }); return new Promise(() => {}); } });
+ h.session.press(); say(h, "book a table"); release(h); await flush();
+ mock.timers.tick(119_999); assert.notEqual(h.views.at(-1).state, "still-working");
+ mock.timers.tick(1);
+ assert.deepEqual(h.views.at(-1), { state: "still-working", text: "" });
+ assert.equal(signal.aborted, true);
+ mock.timers.tick(12_000); assert.equal(h.closed, 1);
+});
+test("a lost stream shows Still working; a refused send shows the failure"); // ask rejects TalkServerError("lost") → still-working; TalkServerError("refused") → { state: "error", text: TALK_TEXT.failed }
+test("replaced while listening closes the box and nothing is sent"); // sink.replaced() → closed 1; then release(h) after say → asks.length 0
+test("clicking the box opens the chat; before the chat is known it only brings MausBot forward"); // open() while listening → opened [null], stops [true], closed 1; after a reply → opened [CHAT]
+test("dismissing while listening cancels capture"); // dismiss() → stops [true], closed 1
+```
+
+- [ ] **Step 2: Run to see them fail**
+
+Run: `node --test electron/talk-session.node-test.mjs`
+Expected: FAIL (`talk-session.mjs` missing).
+
+- [ ] **Step 3: Implement** `createTalkSession` to the table above.
+
+- [ ] **Step 4: Run to see them pass**
+
+Run: `node --test electron/talk-session.node-test.mjs`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add electron/talk-session.mjs electron/talk-session.node-test.mjs
+git commit -m "feat(talk): one ask from press to reply"
+```
+
+---
+
+### Task 8: Wire it into the desktop app
+
+**Files:**
+- Modify: `electron/main.mjs` (electron import line 1, speech import line 11, the 12 `BrowserWindow.getAllWindows()` sites at 139, 269, 359, 945, 952, 1544, 1550, 1826, 2905, 3068, 3198, 3204; speech IPC 2477-2491; prefs at 3066; `before-quit` 3222), `electron/preload.cjs` (`HOME_PAGE` line 43, speech block 162-174), `src/types/ogb.d.ts` (after `speechFinish`, ~261)
+- Test: `electron/talk-main.node-test.mjs` (new, reads `main.mjs` and `preload.cjs` source like `electron/local-only-hoist.node-test.mjs`), `electron/preload.node-test.mjs` (add)
+
+**Interfaces:**
+- Consumes: everything from Tasks 3-7.
+- Produces: `window.ogb.talkShortcut?: TalkShortcutBridge` (this computer's page only) and `window.ogb.callActive?(active: boolean): Promise<void>` (this computer's page and My Cloud's own page). IPC `talk-shortcut:state`, `talk-shortcut:set` (`localOnly`), `call:active` (`localOrHome`: a Live call on My Cloud's page holds the microphone too; the worst a page can do with it is block the shortcut).
+
+Wiring in `main.mjs`:
+- `function appWindows() { return BrowserWindow.getAllWindows().filter((win) => !isTalkPanel(win)); }` (a hoisted declaration near the top) replaces every `BrowserWindow.getAllWindows()` call.
+- `speech:stop` and `speech:finish` call `stopSpeech(BrowserWindow.fromWebContents(event.sender))` / `finishSpeech(…)`, so a page never stops the talk box's session.
+- Next to the speech IPC: `const callPresence = createCallPresence();`, `let talkShortcut = null, talkSession = null;`, the three handlers (`talk-shortcut:set` passes only boolean `enabled` and string `key` through).
+- In `whenReady`, at 3066: `const desktopPrefs = createDesktopPrefs(jsonFile(path.join(app.getPath("userData"), "desktop-prefs.json")));` passed as `prefs` to `registerDesktopPrefs`; then the panel (`createTalkPanel({ BrowserWindow, screen, iconPath: APP_ICON, onOpen: () => talkSession.open(), onDismiss: () => talkSession.dismiss() })`), `talkShortcut = createTalkShortcut({ globalShortcut, prefs: desktopPrefs, available: () => nativeActions.appleSpeech && !desktopRemoteAccess, onPress: () => talkSession.press() })` and `talkSession = createTalkSession({ speech: { start: startSpeech, stop: stopSpeech }, server: createTalkServer({ request: talkRequest, prefs: desktopPrefs, serverKey: () => (app.isPackaged ? runningDataDir : DEV_URL) ?? "local" }), panel, voiceInUse: () => speechBusy() || callPresence.active(), release: () => talkShortcut.releaseModifiers(), openChat: chat => (chat ? queueChatLink(`openmausbot://thread/${chat.threadId}?bot=${chat.botId}`) : revealForLink()) })`.
+- `talkRequest(route, init)`: packaged → `localServerRequest(route, init)` (owner header; rejects while the server is down); dev → `fetch(new URL(route, DEV_URL), init)`, through Vite's `/api` proxy to `pnpm dev:server`, because dev never starts the server itself (`serverReady = !app.isPackaged`, line 313).
+- `before-quit`, first lines: `talkSession?.close(); talkShortcut?.close();`.
+
+- [ ] **Step 1: Write the failing tests**
+
+```js
+// talk-main.node-test.mjs
+test("every list of the app's windows leaves the talk box out", () => {
+ assert.equal(main.match(/BrowserWindow\.getAllWindows\(\)/g).length, 1);
+ assert.match(main, /function appWindows\(\) \{\s*return BrowserWindow\.getAllWindows\(\)\.filter\(\(win\) => !isTalkPanel\(win\)\);/);
+});
+test("the talk setting answers only this computer's page; a call can be reported from My Cloud's page too", () => {
+ for (const channel of ["talk-shortcut:state", "talk-shortcut:set"]) assert.match(main, new RegExp(`ipcMain\\.handle\\("${channel}", localOnly\\("${channel}"`));
+ assert.match(main, /ipcMain\.handle\("call:active", localOrHome\("call:active"/);
+ const list = name => preload.match(new RegExp(`const ${name} = (?:new Set\\()?\\[([^\\]]*)\\]`))[1];
+ assert.doesNotMatch(list("REMOTE_SAFE"), /talkShortcut|callActive/);
+ assert.match(list("HOME_PAGE"), /"callActive"/);
+ assert.doesNotMatch(list("HOME_PAGE"), /talkShortcut/);
+});
+test("a page's speech stop and finish touch only the session that page started", () => {
+ assert.match(main, /stopSpeech\(BrowserWindow\.fromWebContents\(event\.sender\)\)/);
+ assert.match(main, /finishSpeech\(BrowserWindow\.fromWebContents\(event\.sender\)\)/);
+});
+// preload.node-test.mjs
+test("the talk bridge asks main over its own channels with only what it understands", async () => {
+ const before = invocations.length;
+ await exposed.api.talkShortcut.state();
+ await exposed.api.talkShortcut.set({ enabled: false, key: "ctrl-shift-space", extra: "x" });
+ await exposed.api.callActive(true);
+ await exposed.api.callActive("yes");
+ assert.deepEqual(invocations.slice(before), [["talk-shortcut:state"], ["talk-shortcut:set", { enabled: false, key: "ctrl-shift-space" }], ["call:active", true], ["call:active", false]]);
+});
+```
+
+- [ ] **Step 2: Run to see them fail**
+
+Run: `node --test electron/talk-main.node-test.mjs electron/preload.node-test.mjs`
+Expected: FAIL (12 `getAllWindows` sites; no talk channels; no `talkShortcut` in the bridge).
+
+- [ ] **Step 3: Implement** the wiring above, the preload keys (`talkShortcut: { state, set }`, `callActive`; `"callActive"` added to `HOME_PAGE`), and `ogb.d.ts`: `talkShortcut?: import("../../electron/talk-shortcut.mjs").TalkShortcutBridge;` with a doc comment "This computer's page only: Settings → General's talk shortcut." and `callActive?(active: boolean): Promise<void>;` with "A call holds the microphone, so the talk shortcut waits."
+
+- [ ] **Step 4: Run the checks**
+
+Run: `node --test electron/talk-main.node-test.mjs electron/preload.node-test.mjs electron/local-only-hoist.node-test.mjs && pnpm typecheck && pnpm lint`
+Expected: PASS, no type or lint errors.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add electron/main.mjs electron/preload.cjs src/types/ogb.d.ts electron/talk-main.node-test.mjs electron/preload.node-test.mjs
+git commit -m "feat(talk): wire the talk shortcut into the desktop app"
+```
+
+---
+
+### Task 9: Settings row and call presence
+
+**Files:**
+- Create: `src/lib/call-presence.ts`, `src/components/TalkShortcutRow.tsx`
+- Modify: `src/components/LiveCallHost.tsx` (call the hook), `src/components/SettingsModal.tsx` (General keywords line 85; render `<TalkShortcutRow />` right after `<DefaultBotSidebarRow />` at ~671), `src/locales/en.json` (beside `settings.analytics.*`, ~1228)
+- Test: `src/lib/call-presence.test.ts`, `src/components/TalkShortcutRow.test.ts` (happy-dom, `createRoot` + `act`, with `settle`/`show`/`click` helpers as `src/components/UpdatesConsent.test.ts:14-27`; `toggle()` is `button[aria-label="Talk to MausBot from any app"]`; `bridge = { state: vi.fn(async () => current), set: vi.fn(async change => (current = { ...current, ...change })) }` on `window.ogb.talkShortcut`)
+
+**Interfaces:**
+- Consumes: `window.ogb.talkShortcut`, `window.ogb.callActive` (Task 8); `useOnCall`, `startCall`, `endCall` (`src/lib/call.ts`); `useLiveMedia`, `isLiveCallRunning`, `LiveMediaPhase` (`src/lib/live-call-media.ts`).
+- Produces: `callInProgress(onCall: string | null, phase: LiveMediaPhase): boolean`; `useReportCallPresence(): void` (reports on mount and on every change, so a reloaded page clears a stale `true`); `TalkShortcutRow()`.
+- Strings: `settings.talk.title` "Talk to MausBot from any app", `settings.talk.subtitle` "Hold {key}, speak, let go. MausBot answers in a small box at the bottom of the screen; click it to open the chat.", `settings.talk.aria` "Talk to MausBot from any app", `settings.talk.keyAria` "Talk shortcut", `settings.talk.taken` "{key} is used by another app. Pick another shortcut.". Keywords: `"talk"`, `"voice"`, `"shortcut"`, `"hotkey"`, `"hold to talk"`, `"push to talk"`, `"quick asks"`.
+- Row: hidden without the bridge or when `!state.available`; `SettingRow` with the `Switch`; when on, a `Select size="sm"` of `state.keys` (labels) in the row's `message`, and under it `role="alert"` `settings.talk.taken` when `state.taken`; each change shows the state `set()` returns.
+
+- [ ] **Step 1: Write the failing tests**
+
+```ts
+// call-presence.test.ts
+it("a turn call or a running Live call is a call", () => {
+ expect(callInProgress(null, "idle")).toBe(false);
+ expect(callInProgress("bot-1", "idle")).toBe(true);
+ for (const phase of ["starting", "live", "ending"] as const) expect(callInProgress(null, phase)).toBe(true);
+ for (const phase of ["ended", "failed"] as const) expect(callInProgress(null, phase)).toBe(false);
+});
+it("tells main when a call starts and ends, and says none on mount", async () => {
+ const callActive = vi.fn(async () => {});
+ (window as any).ogb = { callActive };
+ await act(async () => { root.render(createElement(() => { useReportCallPresence(); return null; })); });
+ await act(async () => { startCall("bot-1"); });
+ await act(async () => { endCall("bot-1"); });
+ expect(callActive.mock.calls).toEqual([[false], [true], [false]]);
+});
+// TalkShortcutRow.test.ts — base state { available: true, enabled: true, key: "ctrl-opt-space", keys: KEYS, taken: false }
+it("is not shown without the bridge or where Apple speech is unavailable"); // no ogb → host empty; available:false → host empty
+it("shows the switch on with the key in its subtitle, and turns it off", async () => {
+ await show();
+ expect(host.textContent).toContain("Talk to MausBot from any app");
+ expect(host.textContent).toContain("Hold ⌃⌥Space, speak, let go");
+ await click(toggle());
+ expect(bridge.set).toHaveBeenCalledWith({ enabled: false });
+ expect(toggle().getAttribute("aria-checked")).toBe("false");
+ expect(host.querySelector("select")).toBeNull();
+});
+it("changes the key and says so"); // change select to "ctrl-shift-space" → set({ key: "ctrl-shift-space" }); text contains "Hold ⌃⇧Space"
+it("says when another app holds the key"); // taken: true → [role=alert] text "⌃⌥Space is used by another app. Pick another shortcut."
+```
+
+- [ ] **Step 2: Run to see them fail**
+
+Run: `pnpm exec vitest run src/lib/call-presence.test.ts src/components/TalkShortcutRow.test.ts`
+Expected: FAIL (modules missing).
+
+- [ ] **Step 3: Implement** the hook (call it in `LiveCallHost`), the row, its placement and keywords, and the strings.
+
+- [ ] **Step 4: Run to see them pass**
+
+Run: `pnpm exec vitest run src/lib/call-presence.test.ts src/components/TalkShortcutRow.test.ts src/locales && pnpm i18n:check && pnpm typecheck && pnpm lint`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add src/lib/call-presence.ts src/lib/call-presence.test.ts src/components/TalkShortcutRow.tsx src/components/TalkShortcutRow.test.ts src/components/LiveCallHost.tsx src/components/SettingsModal.tsx src/locales/en.json
+git commit -m "feat(talk): Settings row, and calls tell main they hold the microphone"
+```
+
+---
+
+### Task 10: Verification recipe and the whole check
+
+**Files:**
+- Create: `docs/verification/talk-shortcut.md`
+- Modify: `docs/verification/README.md` (a paragraph after the local-environments one, ~line 111: the recipe checks hold-to-talk, the box and the Quick asks chat by hand on a packaged side-by-side build; the control surface cannot drive a global shortcut or the microphone, so it is not in the map)
+
+**Interfaces:**
+- Consumes: everything above.
+
+`talk-shortcut.md` sections (in this repo's recipe style, see `docs/verification/local-environments.md`):
+1. **Floor: automated checks** — `node --test electron/talk-*.node-test.mjs electron/desktop-prefs.node-test.mjs electron/preload.node-test.mjs electron/speech-helper-release.node-test.mjs`; `pnpm exec vitest run electron/speech.test.mjs server/task-select.test.ts server/talk-server.e2e.test.ts src/lib/call-presence.test.ts src/components/TalkShortcutRow.test.ts --maxWorkers=1`; `pnpm typecheck && pnpm lint && pnpm i18n:check`. What they prove and what they do not (the real hotkey, the microphone, focus, Spaces).
+2. **Setup** — a packaged build of the branch installed beside, never over, the installed OpenMausBot (maintainers: the OMB2 side-by-side build), launched with `OMB_DATA_DIR=$HOME/.openmausbot-test` unless the check needs real bots; only one running app may hold the key. Composer dictation used once first so Microphone and Speech Recognition are granted.
+3. **By hand**, each with its expected result:
+ - Settings → General shows the row, on, "Hold ⌃⌥Space, speak, let go".
+ - In Safari's address bar: hold ⌃⌥, tap Space, say "what can you do", let go of ⌃⌥. Live words, then the reply, bottom-centre of that display. `osascript -e 'tell application "System Events" to name of first application process whose frontmost is true'` prints `Safari` before and after; the caret still blinks in Safari; the MausBot window stays behind.
+ - The box hides 12 s after the reply; with the pointer on it, it stays until the pointer leaves.
+ - Clicking it brings MausBot forward on the "Quick asks" chat; the chat open before the ask had not changed until then.
+ - In a full-screen app and on another Space, the box shows there.
+ - Tap and let go without speaking: the box closes, no error.
+ - During a voice call, and while composer dictation is on: "Voice is in use in MausBot"; the call or dictation carries on.
+ - Delete the Quick asks chat, ask again: a new Quick asks chat.
+ - Switch to ⌃⇧Space: ⌃⌥Space does nothing in MausBot any more; ⌃⇧Space works and ends on letting go of ⌃ or ⇧.
+ - Turn it off: the key does nothing.
+ - With System Settings → Keyboard → Keyboard Shortcuts → Input Sources → "Select next source in Input menu" on (⌃⌥Space): note whether Settings shows "⌃⌥Space is used by another app" or the press never arrives; either way ⌃⇧Space must work.
+ - Dev loop: `pnpm dev:server`, `pnpm dev`, `pnpm dev:desktop`: an ask reaches the dev server through Vite's `/api` proxy.
+
+- [ ] **Step 1: Write the recipe and the README paragraph.**
+
+- [ ] **Step 2: Run the whole check**
+
+Run: `pnpm typecheck && pnpm lint && pnpm i18n:check && pnpm test:electron && pnpm exec vitest run electron/speech.test.mjs server/task-select.test.ts server/talk-server.e2e.test.ts src/lib/call-presence.test.ts src/components/TalkShortcutRow.test.ts src/components/UpdatesConsent.test.ts src/components/AppNotices.test.ts --maxWorkers=1`
+Expected: all PASS.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add docs/verification/talk-shortcut.md docs/verification/README.md
+git commit -m "docs(verification): talk shortcut recipe"
+```
+
+---
+
+## Self-review
+
+- **Spec coverage.** Key via `globalShortcut` + helper release (Tasks 2, 4); repeat presses ignored, press during a reply starts anew (7); registration failure shown in Settings (4, 9); speech sinks, `speechBusy`, `replaced()` (3); `call:active` and refusal during calls or dictation (4, 7, 8, 9); the box, its window flags, `data:` page with strict CSP, `open()`/`dismiss()` only, states, 12 s hide unless hovered, click opens the chat, panel skipped by every window list (6, 7, 8); local server, MausBot lookup, owner header, send with `sendId`, SSE follow, needs-you, 120 s, empty transcript, server down (5, 7, 8); prefs, Settings row, hidden without Apple speech, not in `REMOTE_SAFE` (4, 8, 9); Quick asks chat created, reused, recreated, per server (1, 4, 5); testing section (all tasks, 10). Dev reaching the dev server (8, 10).
+- **Deviations from the spec, on purpose.** The ask posts `threadId` (the spec's `{text, sendId}` would land in MausBot's selected chat, `server/routes/bot-messages.ts:202`, against the Quick asks decision). Speech sink tests live in vitest `electron/speech.test.mjs`, not a node-test, because `speech.mjs` imports Electron's `app`. `call:active` is `localOrHome`, not `localOnly`, so a Live call on My Cloud's page also blocks the shortcut. The box's copy is English in v1.
+- **Types.** `TalkView`, `TalkChat`, `TalkUpdate`, `TalkShortcutState`, `TalkKeyId` and every factory name are spelled the same in each task's Interfaces and tests.
+- **Left open to the implementer.** Exact page markup and CSS within the tokens given; the Swift parsing style.
diff --git a/docs/superpowers/specs/2026-10-27-talk-shortcut-design.md b/docs/superpowers/specs/2026-10-27-talk-shortcut-design.md
new file mode 100644
index 0000000000..c2a2a9a6ec
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-27-talk-shortcut-design.md
@@ -0,0 +1,144 @@
+# Talk shortcut: hold a key, talk to MausBot from any app
+
+Date: 2026-10-27 · Branch: `feat/talk-shortcut` · Idea source: Atticus's hold-to-talk box (SaarthurR/atticus-mac, MIT). We take the idea, not the code.
+
+## Why
+
+Asking MausBot something means switching to the app, finding the chat and
+typing. Holding a key from wherever you are, saying it and letting go is the
+fastest way in. MausBot is the orchestrator, so it is the right place for a
+quick ask to land.
+
+## Goals
+
+- macOS: hold ⌃⌥Space from any app, speak, release ⌃⌥ to send.
+- A small floating box near the bottom of the screen shows the live words, then
+ MausBot's reply. It never takes focus and never brings the MausBot window
+ forward.
+- Clicking the box opens that chat in MausBot.
+- On/off in Settings → General.
+
+## Non-goals (v1)
+
+- Windows and Linux (no speech recogniser there today; the setting is hidden).
+- Typing into the box (it cannot take focus by design).
+- Choosing another bot or a free-form key (three presets only).
+- Reading the reply aloud.
+- Asking from the phone apps.
+
+## Anti-goals
+
+- Stealing focus or Esc from the app the person is in.
+- Breaking a call or composer dictation that is using the microphone.
+- A box that lingers or piles up.
+
+## Design
+
+### Key: press via `globalShortcut`, release via the speech helper
+
+Electron's `globalShortcut` registers `Control+Alt+Space` (Carbon hotkey, no
+permission needed) but cannot see a key go up. The existing speech helper
+already finishes recognition when its finish file appears. Add
+`--finish-on-release control,option`: the helper's finish timer also finishes
+when `CGEventSource.flagsState(.combinedSessionState)` no longer holds both
+modifiers. So: hold ⌃⌥, tap or hold Space, speak, let go of ⌃⌥. A release
+before the helper is ready still finishes (the timer keeps polling).
+
+Repeat presses while a session is active are ignored. A press while a reply is
+showing dismisses the box and starts a new ask. If another app owns the
+shortcut, registration fails and Settings shows "⌃⌥Space is used by another
+app".
+
+### Speech (`electron/speech.mjs`)
+
+`startSpeech` takes a sink (`{transcript(line), end(info), replaced()}`) as well
+as a window; window callers are unchanged. New `speechBusy()`. The speech
+helper is not the only thing that holds the mic: Live calls use
+`getUserMedia`, and voice calls stop the helper while the bot speaks. So the
+renderer also tells main when any call starts and ends (`call:active` IPC), and
+the talk shortcut refuses during a call or while composer dictation is on: the
+box says "Voice is in use in MausBot" and nothing starts. If the renderer starts
+speech while the talk box is listening, the talk sink's `replaced()` closes the
+box.
+
+### The box (`electron/talk-panel.mjs`)
+
+Created lazily per ask and destroyed after it fades: `type:"panel"`,
+frameless, transparent, `focusable:false`, `skipTaskbar`, always on top at
+`screen-saver` level, visible on all Spaces and over full-screen apps,
+`showInactive()`, bottom-centre of the display under the cursor. It loads a
+`data:` URL page (inline CSS, strict CSP) with a tiny preload exposing only
+`open()` and `dismiss()`. Main pushes state:
+
+`listening (live words) → sending → thinking → reply (first ~400 chars, plain
+text) → done` or `needs-you` (an approval or question card) or `error`.
+
+The box takes the light or dark of the app's skin as last painted (Settings →
+Appearance → Theme), macOS's appearance only until a page has painted one. It
+stays on the display it opened on. The box hides 12 s after the reply unless the
+pointer is over it. Clicking it
+opens `openmausbot://thread/<threadId>?bot=<botId>` and shows the main window.
+Places that treat every window as the main one (`activate`, single-instance,
+`activateExistingWindow`, window-all-closed, the capabilities broadcast) skip
+the panel.
+
+### Sending (Electron main)
+
+Asks always go to the MausBot on this Mac's own server, even when the window is
+showing a Team Cloud (my call for v1). Once this Mac's bots moved to My Cloud
+(home is My Cloud, or this Mac's copy is frozen) the shortcut is unavailable and
+its key free, until home is this Mac again; a frozen server's 409 `moved` says
+"MausBot lives on My Cloud now — talk to it there".
+
+`GET /api/bots?messages=0` → MausBot (`defaultBot` without `person`, else the
+Chief of Staff). `POST /api/bots/:id/messages {text, sendId}` with the desktop
+owner header (`localServerRequest`). Follow the reply on `GET
+/api/events?screens=off` for that thread: assistant deltas update the box, the
+final bot message wins, `turn.completed` ends it, a request card switches to
+"needs you". No reply in 120 s shows "Still working · Open chat". An empty
+transcript closes the box silently. If the local server is not running, the box
+says "Open MausBot to talk"; while it is still starting, "MausBot is still
+starting. Try again in a moment."; with no MausBot, "Set up MausBot first, then
+try again." Speech problems use the composer's words: only a refused permission
+asks for access, a microphone or recognizer failure says "Talking couldn't
+start. Try again."
+
+### Settings
+
+`desktop-prefs.json` gets `talkShortcut: boolean` (default `true` on macOS),
+`talkKey: "ctrl-opt-space" | "ctrl-shift-space" | "opt-shift-space"` and the
+Quick asks chat id. Settings → General gets a switch: "Talk to MausBot from any
+app · hold ⌃⌥Space, speak, let go" with the key picker under it. Hidden where
+Apple speech is unavailable, on a remote client and while home is My Cloud. Not
+in `REMOTE_SAFE`.
+
+## Testing
+
+- `electron/*.node-test.mjs`: shortcut registers and unregisters with the pref;
+ a busy speech session refuses; the sink path receives transcript and end; the
+ replaced callback fires; the panel state machine (listening → reply → hide,
+ needs-you, empty transcript, server down, timeout) against a fake server and
+ fake SSE.
+- Swift: release detection by injecting the flags reader (a flag that pretends
+ the keys were released).
+- By hand on a Mac (OMB2 side-by-side build): hold, speak, release from Safari;
+ the box never takes focus; a call in progress blocks it; the reply lands in
+ MausBot's chat.
+
+## Decisions
+
+- Omkar, 2026-10-27: asks land in one dedicated MausBot chat, "Quick asks",
+ created on first use and reused (follow-ups keep context; asks never mix into
+ work running in another chat). If it was deleted, a new one is made. Its id is
+ kept in desktop prefs per server.
+- Omkar, 2026-10-27: default key ⌃⌥Space. macOS uses ⌃⌥Space for "Select next
+ source in Input menu", which clashes for people with two keyboard layouts, so
+ Settings offers ⌃⌥Space, ⌃⇧Space and ⌥⇧Space (⌥⌘Space is the Finder search window). Release detection follows the
+ chosen key's modifiers. This replaces the "no remapping" non-goal.
+- My calls: always the local server in v1; calls and composer dictation block
+ the shortcut.
+
+## Left to the builder
+
+Box visuals (follow the app's tokens and mascot), exact copy, panel size, how
+dev mode reaches the dev server.
diff --git a/docs/verification/README.md b/docs/verification/README.md
index eb6a073db6..2892dd3f5d 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -112,6 +112,11 @@ creating, switching between and recovering named local environments by hand on
a packaged desktop install; the control surface cannot drive it, so it is not
in the map above.
+The [talk shortcut recipe](talk-shortcut.md) checks hold-to-talk from any app, the
+reply box and the Quick asks chat by hand on a packaged side-by-side build; the
+control surface cannot drive a global shortcut or the microphone, so it is not
+in the map above.
+
The [move to My Cloud fixture](cloud-send.md) runs this computer's server and a
Cloud home with the desktop's own wiring between them, and runs and checks the
one-time move as main does.
diff --git a/docs/verification/evidence/talk-shortcut/dark-error.png b/docs/verification/evidence/talk-shortcut/dark-error.png
new file mode 100644
index 0000000000..1c70700063
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-error.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-listening-words.png b/docs/verification/evidence/talk-shortcut/dark-listening-words.png
new file mode 100644
index 0000000000..8c32d1ece2
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-listening-words.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-listening.png b/docs/verification/evidence/talk-shortcut/dark-listening.png
new file mode 100644
index 0000000000..2075f475ad
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-listening.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-needs-you.png b/docs/verification/evidence/talk-shortcut/dark-needs-you.png
new file mode 100644
index 0000000000..e565778f78
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-needs-you.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-reply-long.png b/docs/verification/evidence/talk-shortcut/dark-reply-long.png
new file mode 100644
index 0000000000..665e33e82b
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-reply-long.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-reply-wide.png b/docs/verification/evidence/talk-shortcut/dark-reply-wide.png
new file mode 100644
index 0000000000..d2140cdb57
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-reply-wide.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-reply.png b/docs/verification/evidence/talk-shortcut/dark-reply.png
new file mode 100644
index 0000000000..f10a534883
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-reply.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-sending.png b/docs/verification/evidence/talk-shortcut/dark-sending.png
new file mode 100644
index 0000000000..fb884bcbee
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-sending.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-still-working.png b/docs/verification/evidence/talk-shortcut/dark-still-working.png
new file mode 100644
index 0000000000..350d45a91d
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-still-working.png differ
diff --git a/docs/verification/evidence/talk-shortcut/dark-thinking.png b/docs/verification/evidence/talk-shortcut/dark-thinking.png
new file mode 100644
index 0000000000..335215e580
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/dark-thinking.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-error.png b/docs/verification/evidence/talk-shortcut/light-error.png
new file mode 100644
index 0000000000..13c945fcb4
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-error.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-listening-words.png b/docs/verification/evidence/talk-shortcut/light-listening-words.png
new file mode 100644
index 0000000000..e3f9bc0a40
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-listening-words.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-listening.png b/docs/verification/evidence/talk-shortcut/light-listening.png
new file mode 100644
index 0000000000..04ed757fe5
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-listening.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-needs-you.png b/docs/verification/evidence/talk-shortcut/light-needs-you.png
new file mode 100644
index 0000000000..c4e87774c3
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-needs-you.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-reply-long.png b/docs/verification/evidence/talk-shortcut/light-reply-long.png
new file mode 100644
index 0000000000..94ce054c80
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-reply-long.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-reply-wide.png b/docs/verification/evidence/talk-shortcut/light-reply-wide.png
new file mode 100644
index 0000000000..23d1d02dd4
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-reply-wide.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-reply.png b/docs/verification/evidence/talk-shortcut/light-reply.png
new file mode 100644
index 0000000000..3104af6784
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-reply.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-sending.png b/docs/verification/evidence/talk-shortcut/light-sending.png
new file mode 100644
index 0000000000..055c09af30
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-sending.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-still-working.png b/docs/verification/evidence/talk-shortcut/light-still-working.png
new file mode 100644
index 0000000000..2de5f8be20
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-still-working.png differ
diff --git a/docs/verification/evidence/talk-shortcut/light-thinking.png b/docs/verification/evidence/talk-shortcut/light-thinking.png
new file mode 100644
index 0000000000..38f55d3ba5
Binary files /dev/null and b/docs/verification/evidence/talk-shortcut/light-thinking.png differ
diff --git a/docs/verification/talk-shortcut.md b/docs/verification/talk-shortcut.md
new file mode 100644
index 0000000000..59e799091a
--- /dev/null
+++ b/docs/verification/talk-shortcut.md
@@ -0,0 +1,114 @@
+# Talk shortcut (hold to talk from any app)
+
+Hold ⌃⌥Space from any app, speak, let go. The words go to MausBot's "Quick asks"
+chat and a never-focused box at the bottom of the screen shows the reply.
+
+The real hotkey, the microphone, window focus and Spaces are macOS behavior:
+the control surface cannot drive them, so this is not in the map in
+[README](README.md). Verify them by hand on a packaged build, exactly as below.
+
+## Floor: automated checks
+
+```sh
+node --test electron/talk-*.node-test.mjs electron/home-window.node-test.mjs electron/desktop-prefs.node-test.mjs electron/preload.node-test.mjs electron/speech-helper-release.node-test.mjs
+pnpm exec vitest run electron/speech.test.mjs electron/skin-overlay.test.mjs server/task-select.test.ts server/talk-server.e2e.test.ts src/lib/call-presence.test.ts src/components/TalkShortcutRow.test.ts --maxWorkers=1
+pnpm typecheck && pnpm lint && pnpm i18n:check
+```
+
+They prove key parsing and registration, the key let go while home is My Cloud
+and taken back when home is this computer again, the press/release state machine
+with injected clocks and speech, the box's window flags, states, skin theme and
+pinned display, the local-server ask (thread, owner header, send id, SSE follow,
+needs-you, timeout, a 409 `moved`, a server still starting), preference storage,
+the Settings row, scoped speech stop, the call-presence signal and the quiet
+update waiting for a talk ask.
+They do not prove the real hotkey, the microphone, that the box never takes
+focus, that it shows over full-screen apps and other Spaces, or the release of
+⌃⌥ after speech (no unit test covers that release path).
+
+`docs/verification/evidence/talk-shortcut/` holds the box page rendered in
+headless Chrome for every state in the app's light and dark skins
+(`light-*.png`, `dark-*.png`). Regenerate them with:
+
+```sh
+node scripts/talk-box-evidence.mjs # Chrome path as an argument or CHROME= when not in /Applications
+```
+
+It renders at the box's own size: a 400 px wide viewport as tall as the card
+(56 to 240 px, the height `render()` returns, clamped as `talkPanelBounds`
+does) at 2x, with the 56 px mascot, reduced motion (a still listening ring) and
+a grey desktop behind the transparent page. Each skin is rendered with macOS's
+appearance emulated the other way round, so a light card on a dark macOS shows
+the box following the app's skin (`render({state, text, theme})`), not the
+media query. `reply-long` is a 400-character reply cut with an ellipsis;
+`reply-wide` is a reply of wide characters cut at ten lines, the tallest box.
+
+Rendering by hand instead: pass `theme`, or the page falls back to the media
+query, and Chrome's `--blink-settings=preferredColorScheme=0` is dark and `=1`
+light (the reverse of what it reads like); a `--window-size` wider than 400 px
+or taller than the card shows a box the app never draws.
+
+## Setup
+
+- A packaged build of the branch installed beside, never over, the installed
+ OpenMausBot (maintainers: the OMB2 side-by-side build). Never touch
+ `/Applications/OpenMausBot.app` or `~/.openmausbot`.
+- Launch with `OMB_DATA_DIR=$HOME/.openmausbot-test` unless the check needs real
+ bots. Only one running app may hold the key: quit any other MausBot first.
+- Use composer dictation once first so Microphone and Speech Recognition are
+ granted.
+
+## By hand
+
+1. **Settings row.** Settings → General shows "Talk to MausBot from any app",
+ on, "Hold ⌃⌥Space, speak, let go".
+2. **Hold, speak, release in another app.** In Safari's address bar: hold ⌃⌥,
+ tap Space, say "what can you do", let go of ⌃⌥ (not Space). Expect live
+ words, then the words send on the release (the path no unit test covers),
+ then the reply, bottom-centre of that display. `osascript -e 'tell
+ application "System Events" to name of first application process whose
+ frontmost is true'` prints `Safari` before and after; the caret still blinks
+ in Safari; the box never takes focus and the MausBot window never raises.
+3. **Hide timing.** The box hides 12 s after the reply; with the pointer on it,
+ it stays until the pointer leaves.
+4. **Click opens the chat.** Clicking it brings MausBot forward on the "Quick
+ asks" chat; the chat open before the ask had not changed until then.
+5. **Spaces and full screen.** In a full-screen app and on another Space, the
+ box shows there.
+6. **No speech.** Tap and let go without speaking: the box closes, no error.
+7. **Voice already in use.** During a voice call, and while composer dictation
+ is on: "Voice is in use in MausBot"; the call or dictation carries on.
+8. **Mic indicator off after every speech use (scoped speech stop).** Start and
+ stop composer dictation, take one push-to-talk call turn and one Live call
+ turn: after each, the orange microphone indicator in the menu bar is off.
+9. **Chat recreated.** Delete the Quick asks chat, ask again: a new Quick asks
+ chat.
+10. **Other key presets.** Switch to ⌃⇧Space: ⌃⌥Space does nothing in MausBot
+ any more; ⌃⇧Space works and ends on letting go of ⌃ or ⇧. Repeat for
+ ⌥⇧Space.
+11. **Off.** Turn it off: the key does nothing.
+12. **Second keyboard layout.** With a second input source enabled and System
+ Settings → Keyboard → Keyboard Shortcuts → Input Sources → "Select next
+ source in Input menu" on (⌃⌥Space): note whether Settings shows "⌃⌥Space is
+ used by another app" or the press never arrives or switches the layout;
+ either way the ⌃⇧Space and ⌥⇧Space presets must work.
+13. **Dev loop.** `pnpm dev:server`, `pnpm dev`, `pnpm dev:desktop`: an ask
+ reaches the dev server through Vite's `/api` proxy, both the POST and the
+ SSE stream (the reply arrives live, not only at the end).
+14. **Light and dark.** Settings → Appearance → Theme: Light, then Dark, then
+ System while switching macOS appearance. The box's colours, the warning and
+ error text and the card height follow the app's theme, not macOS's (Dark
+ with macOS light still gives a dark box; compare with the evidence PNGs).
+ Long replies stop at 400 characters with an ellipsis, and the card grows to
+ at most 240 px with its bottom edge showing (a Japanese reply is cut at ten
+ lines).
+15. **My Cloud home.** After moving this computer's bots to My Cloud (window on
+ My Cloud's page): ⌃⌥Space does nothing in MausBot and another app can take
+ it (`talk-shortcut:state` says unavailable, so no Settings row). Come home
+ to this computer again: the key works without a restart. A box still up
+ when the move froze this computer says "MausBot lives on My Cloud now —
+ talk to it there". A Quick asks chat link sent while My Cloud's page is
+ shown does reach it as `chat:open`, and My Cloud has no such chat; with the
+ key off there, no box makes one.
+16. **Server starting.** Quit, relaunch and press at once, before the window
+ loads: "MausBot is still starting. Try again in a moment."
diff --git a/electron/desktop-prefs.d.mts b/electron/desktop-prefs.d.mts
index 608a904cd6..7d3711cc68 100644
--- a/electron/desktop-prefs.d.mts
+++ b/electron/desktop-prefs.d.mts
@@ -43,11 +43,22 @@ export interface DesktopPrefs {
updatesConsent(): import("./updates-consent.mjs").UpdatesConsentRecord | null;
/** False, and nothing saved, for a record updates-consent.mjs would not read back. */
setUpdatesConsent(value: unknown): boolean;
+ /** True until switched off. */
+ talkShortcut(): boolean;
+ setTalkShortcut(enabled: boolean): void;
+ talkKey(): import("./talk-shortcut.mjs").TalkKeyId;
+ /** False, and nothing saved, for anything but a key id in talk-keys.mjs. */
+ setTalkKey(id: unknown): boolean;
+ /** The Quick asks chat made on this server (keyed by its data folder), null until one is saved. */
+ quickAsksChat(server: string): { botId: string; threadId: string } | null;
+ setQuickAsksChat(server: string, chat: { botId: string; threadId: string }): void;
}
type Files = Pick<typeof import("node:fs"), "readFileSync" | "writeFileSync" | "renameSync" | "rmSync">;
export declare function jsonFile(file: string, files?: Files): { read(): unknown; write(value: unknown): void };
export declare function createDesktopPrefs(options: { read(): unknown; write(value: unknown): void; now?: () => number }): DesktopPrefs;
export declare function registerDesktopPrefs(options: {
+ /** Used instead of making a store from read/write. */
+ prefs?: DesktopPrefs;
ipcMain: { handle(channel: string, handler: (event: unknown, ...args: unknown[]) => unknown): void; on(channel: string, listener: (event: { returnValue?: unknown }) => void): void };
read(): unknown;
write(value: unknown): void;
diff --git a/electron/desktop-prefs.mjs b/electron/desktop-prefs.mjs
index 55652d8f57..33c1752cb1 100644
--- a/electron/desktop-prefs.mjs
+++ b/electron/desktop-prefs.mjs
@@ -4,6 +4,7 @@ import { randomBytes } from "node:crypto";
import fs from "node:fs";
import { localDay } from "./cloud-trial-notice.mjs";
import { ONBOARDING_CLOUD_HINT, onboardingHints } from "./onboarding-record.mjs";
+import { DEFAULT_TALK_KEY, isTalkKey } from "./talk-keys.mjs";
import { createUpdatesConsent, parseUpdatesConsent, registerUpdatesConsent } from "./updates-consent.mjs";
import { accountFullName } from "./system-name.mjs";
@@ -15,6 +16,7 @@ const DAY = /^\d{4}-\d{2}-\d{2}$/;
/** A locale code such as "de" or "pt-br", or "" for following the system. */
const LANGUAGE = /^(?:[a-z]{2,3}(?:-[a-z0-9]{2,8}){0,2})?$/i;
const isLanguage = value => typeof value === "string" && value.length <= 24 && LANGUAGE.test(value);
+const CHAT_ID = /^[\w-]{1,128}$/;
const INSTALL_ID = /^[A-Za-z0-9_-]{22,64}$/;
/** Security: a write that fails (a full disk, a kill mid-write) leaves the last whole record, analytics opt-out included.
@@ -35,6 +37,9 @@ export function jsonFile(file, files = fs) {
};
}
+const parseChat = value => value && typeof value === "object" && typeof value.botId === "string" && typeof value.threadId === "string"
+ && CHAT_ID.test(value.botId) && CHAT_ID.test(value.threadId) ? { botId: value.botId, threadId: value.threadId } : null;
+
function parse(raw) {
const record = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
const seen = Array.isArray(record.seen) ? DESKTOP_NOTICES.filter(id => record.seen.includes(id)) : [];
@@ -43,10 +48,16 @@ function parse(raw) {
return typeof day === "string" && DAY.test(day) ? [[id, day]] : [];
}));
const updatesConsent = parseUpdatesConsent(record.updatesConsent);
+ const quickAsks = record.quickAsks && typeof record.quickAsks === "object" && !Array.isArray(record.quickAsks)
+ ? Object.fromEntries(Object.entries(record.quickAsks).flatMap(([server, chat]) => { const parsed = parseChat(chat); return parsed ? [[server, parsed]] : []; }))
+ : {};
return { seen, shown, ...(typeof record.analytics === "boolean" ? { analytics: record.analytics } : {}),
...(isLanguage(record.language) ? { language: record.language } : {}),
...(typeof record.installId === "string" && INSTALL_ID.test(record.installId) ? { installId: record.installId } : {}),
- ...(updatesConsent ? { updatesConsent } : {}) };
+ ...(updatesConsent ? { updatesConsent } : {}),
+ ...(typeof record.talkShortcut === "boolean" ? { talkShortcut: record.talkShortcut } : {}),
+ ...(isTalkKey(record.talkKey) ? { talkKey: record.talkKey } : {}),
+ ...(Object.keys(quickAsks).length ? { quickAsks } : {}) };
}
/** A record that cannot be written is still kept for this launch. */
@@ -97,6 +108,22 @@ export function createDesktopPrefs({ read, write, now = Date.now }) {
save({ ...current(), updatesConsent });
return true;
},
+ talkShortcut: () => current().talkShortcut ?? true,
+ setTalkShortcut(enabled) { save({ ...current(), talkShortcut: enabled === true }); },
+ talkKey: () => current().talkKey ?? DEFAULT_TALK_KEY,
+ setTalkKey(id) {
+ if (!isTalkKey(id)) return false;
+ if (current().talkKey !== id) save({ ...current(), talkKey: id });
+ return true;
+ },
+ quickAsksChat(server) {
+ const quickAsks = current().quickAsks;
+ return quickAsks && Object.hasOwn(quickAsks, server) ? { ...quickAsks[server] } : null;
+ },
+ setQuickAsksChat(server, chat) {
+ const parsed = typeof server === "string" ? parseChat(chat) : null;
+ if (parsed) save({ ...current(), quickAsks: { ...current().quickAsks, [server]: parsed } });
+ },
};
}
@@ -108,8 +135,8 @@ export function createDesktopPrefs({ read, write, now = Date.now }) {
* MausBot Cloud, asked once its Cloud sign-in is restored. `localConfig()`: This computer's own workspace's config.json.
* `languageChanged(language, sender)`: tells this desktop's other pages the language picked on one of them.
*/
-export function registerDesktopPrefs({ ipcMain, read, write, page, cloudOffered, cloudAccount, localConfig = () => null, languageChanged = () => {}, now = Date.now, systemName = accountFullName }) {
- let prefs = null;
+export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page, cloudOffered, cloudAccount, localConfig = () => null, languageChanged = () => {}, now = Date.now, systemName = accountFullName }) {
+ let prefs = given ?? null;
const store = () => prefs ??= createDesktopPrefs({ read, write, now });
const from = (channel, pages, handler) => (event, ...args) => {
const asking = page(event);
diff --git a/electron/desktop-prefs.node-test.mjs b/electron/desktop-prefs.node-test.mjs
index 941c4837dd..4af191a303 100644
--- a/electron/desktop-prefs.node-test.mjs
+++ b/electron/desktop-prefs.node-test.mjs
@@ -269,7 +269,7 @@ test("production wiring: main answers this computer's page, My Cloud's own page
const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8").replace(/\r\n/g, "\n");
assert.match(main, /for \(const port of DESKTOP_PORTS\)/, "main tries the ports this module names, in order");
assert.deepEqual([...DESKTOP_PORTS], [8799, 18799, 28799]);
- const start = main.indexOf(" updatesConsent = registerDesktopPrefs({"), end = main.indexOf("\n", main.indexOf("page:", start));
+ const start = main.indexOf(" const desktopPrefs = createDesktopPrefs("), end = main.indexOf("\n", main.indexOf("page:", start));
assert.ok(start >= 0 && end > start, "main.mjs registers the desktop prefs");
let options = null;
const localFrame = { url: `${LOCAL}/` }, serverFrame = { url: `${VPS}/` };
@@ -280,12 +280,12 @@ test("production wiring: main answers this computer's page, My Cloud's own page
const windows = [window("team"), window("home"), window("closed")];
let switched = async id => { calls.push(["switch", id]); }, loads = true;
const context = vm.createContext({
- registerDesktopPrefs: value => { options = value; }, jsonFile: file => ({ read: () => file, write: () => {} }), ipcMain: {}, updatesConsent: null, cloudAccount: "the client",
+ registerDesktopPrefs: value => { options = value; }, createDesktopPrefs: store => ({ store }), jsonFile: file => ({ read: () => file, write: () => {} }), ipcMain: {}, updatesConsent: null, cloudAccount: "the client",
path: { join: (...parts) => parts.join("/") }, app: { getPath: () => "/user-data" }, desktopDataDir: () => "/home/.openmausbot",
navigateMainWindow: async url => { calls.push(["navigate", url]); return loads; },
senderIsLocal: localOrigin.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed,
mainWindow: { webContents: contents }, environmentsState: { environments: [{ id: "vps", name: "VPS", origin: VPS }], activeId: "vps" },
- BrowserWindow: { getAllWindows: () => windows }, chromeRail: { send: (...told) => sent.push(["rail", ...told]) },
+ appWindows: () => windows, BrowserWindow: { getAllWindows: () => windows }, chromeRail: { send: (...told) => sent.push(["rail", ...told]) },
rendererOrigin: () => LOCAL, cloudAccountRestored: async () => calls.push("restored"), cloudOffersReady: async () => { calls.push("offers"); return true; },
cloudPageAsking: event => event.verifiedCloud ? "cloud" : null,
serverReady: true, LOCAL_ID: "local", switchEnvironment: id => switched(id),
@@ -293,7 +293,7 @@ test("production wiring: main answers this computer's page, My Cloud's own page
workspaceMenuAction: async action => { try { await action(); } catch { calls.push("dialog"); } },
});
vm.runInContext(main.slice(start, end), context);
- assert.equal(options.read(), "/user-data/desktop-prefs.json");
+ assert.equal(options.prefs.store.read(), "/user-data/desktop-prefs.json");
assert.equal(options.localConfig(), "/home/.openmausbot/config.json", "This computer's own workspace, whichever server the window shows");
assert.equal(options.page({ sender: { mainFrame: localFrame }, senderFrame: localFrame }), "local");
assert.equal(options.page({ sender: contents, senderFrame: serverFrame }), "server");
@@ -311,3 +311,40 @@ test("production wiring: main answers this computer's page, My Cloud's own page
assert.equal(await load(`${LOCAL}/ok`), true); assert.equal(await load(`${LOCAL}/fail`), false, "a failed load answers false, never throws");
assert.equal(await vm.runInNewContext(`${navigate}; navigateMainWindow`, { mainWindow: null })(`${LOCAL}/`), false, "no window");
});
+
+test("the talk shortcut is on with ⌃⌥Space until changed, and the choice survives a restart", () => {
+ let saved = null;
+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+ assert.equal(prefs.talkShortcut(), true);
+ assert.equal(prefs.talkKey(), "ctrl-opt-space");
+ prefs.setTalkShortcut(false);
+ assert.equal(prefs.setTalkKey("opt-shift-space"), true);
+ for (const key of ["cmd-space", "__proto__", "toString", 7]) assert.equal(prefs.setTalkKey(key), false);
+ const restarted = createDesktopPrefs({ read: () => saved, write: () => {} });
+ assert.equal(restarted.talkShortcut(), false);
+ assert.equal(restarted.talkKey(), "opt-shift-space");
+ const junk = createDesktopPrefs({ read: () => ({ talkShortcut: "off", talkKey: "toString" }), write: () => {} });
+ assert.equal(junk.talkShortcut(), true);
+ assert.equal(junk.talkKey(), "ctrl-opt-space");
+});
+
+test("each server keeps its own Quick asks chat; nothing malformed is read back", () => {
+ let saved = null;
+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+ prefs.setQuickAsksChat("/Users/a/.openmausbot", { botId: "bot-1", threadId: "t-1" });
+ assert.deepEqual(createDesktopPrefs({ read: () => saved, write: () => {} }).quickAsksChat("/Users/a/.openmausbot"), { botId: "bot-1", threadId: "t-1" });
+ assert.equal(prefs.quickAsksChat("/Users/a/.openmausbot-aprs"), null);
+ const broken = createDesktopPrefs({ read: () => ({ quickAsks: { a: { botId: "../x", threadId: "t" }, b: "t-1", c: { botId: "b", threadId: "t", extra: 1 } } }), write: () => {} });
+ assert.equal(broken.quickAsksChat("a"), null);
+ assert.equal(broken.quickAsksChat("b"), null);
+ assert.deepEqual(broken.quickAsksChat("c"), { botId: "b", threadId: "t" });
+});
+
+test("registerDesktopPrefs works on the store main hands it", async () => {
+ const prefs = createDesktopPrefs({ read: () => null, write: () => {} });
+ const handlers = new Map();
+ registerDesktopPrefs({ prefs, ipcMain: { handle: (c, h) => handlers.set(c, h), on: () => {} }, read: () => null, write: () => {},
+ page: () => "local", cloudOffered: async () => false });
+ await handlers.get("desktop-analytics:set")({}, false);
+ assert.equal(prefs.analytics(), false);
+});
diff --git a/electron/home-window.d.mts b/electron/home-window.d.mts
index 58c67b5476..e31d56f3ff 100644
--- a/electron/home-window.d.mts
+++ b/electron/home-window.d.mts
@@ -104,6 +104,8 @@ export function createHomeWindow(deps: {
splash?(): { status(text: string): void } | null;
lastInput?(): number;
publish?(view: HomeView): void;
+ /** Home as worked out changed: this computer, My Cloud (`origin`), or the sign-in screen. */
+ rehomed?(home: Home): void;
versionEveryMs?: number;
quietMs?: number;
now?(): number;
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 171a1f71e3..dc74482532 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -165,6 +165,7 @@ export function routeOf(url, origin) {
* splash?(): { status(text: string): void } | null,
* lastInput?(): number,
* publish?(view: unknown): void,
+ * rehomed?(home: { kind: string, origin?: string }): void,
* versionEveryMs?: number,
* quietMs?: number,
* now?(): number,
@@ -179,12 +180,13 @@ export function routeOf(url, origin) {
* `frozen()`: this computer's server's freeze marker. `splash()`: the startup screen while it is up. `remembered()`: the
* team or other Cloud shown last time, with its name and origin as saved; `remember(place)`: what to open next time;
* `left(name)`: the team shown is no longer this person's, so the window says so once; `drop(place)`: the Admin said so
- * (404 on its pairing), so the team (with that line) or the Cloud leaves the switcher now.
+ * (404 on its pairing), so the team (with that line) or the Cloud leaves the switcher now. `rehomed(home)`: home as worked
+ * out changed.
*/
export function createHomeWindow(deps) {
const { journal, frozen, account, restored = async () => {}, window, ensureWindow, localOrigin, cookieFetch, power, go, showLocal,
remembered = () => null, remember = () => {}, left = () => {}, drop = (place) => { if (place.kind === "team") left(place.name); remember(null); },
- splash = () => null, lastInput = () => 0, publish = () => {}, versionEveryMs = VERSION_EVERY_MS, quietMs = QUIET_MS,
+ splash = () => null, lastInput = () => 0, publish = () => {}, rehomed = () => {}, versionEveryMs = VERSION_EVERY_MS, quietMs = QUIET_MS,
now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, log = () => {} } = deps;
let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;
/** My Cloud asked for before the move made it home (`{ open }`), until its page loads or the person goes elsewhere;
@@ -215,7 +217,11 @@ export function createHomeWindow(deps) {
if (marker?.frozen) frozenCloud = typeof marker.cloud === "string" ? marker.cloud : true;
}
if (frozenCloud || awayIn(kept)) await restored();
+ const before = home;
home = homeOf({ journal: kept, frozenCloud, state: state() });
+ if (home.kind !== before.kind || home.origin !== before.origin) {
+ try { rehomed(home); } catch {}
+ }
return home;
}
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index 93d45d5aec..d57023d341 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -69,7 +69,7 @@ function world({ journal = done(), marker = null, state = connected(), power = n
/** Another Cloud of the person's own, answering at CLIENT; `gone`: the Admin's pairing says it is no longer theirs. */
client: { down: false, signedIn: true, version: "0.1.130", health: 200, gone: false, ...client },
went: [], calls: [], fetched: [], pairs: 0, teamPairs: [], ownPairs: [], wakes: 0, waking: [], splash: [], published: [], local: [], reloads: 0, signIns: [],
- remembered, remembers: [], left: [], dropped: [], redeemed: [],
+ remembered, remembers: [], left: [], dropped: [], redeemed: [], rehomes: [], rehomeThrows: false,
url, timers: [], intervals: [],
};
const timers = {
@@ -137,6 +137,7 @@ function world({ journal = done(), marker = null, state = connected(), power = n
splash: () => (splash ? { status: (text) => w.splash.push(text) } : null),
lastInput: () => w.typed,
publish: (view) => w.published.push(view),
+ rehomed: (home) => { w.rehomes.push(home); if (w.rehomeThrows) throw new Error("listener broke"); },
now: w.now,
timers,
});
@@ -392,6 +393,22 @@ test("My Cloud ending brings the window back to this computer's page", async ()
assert.equal(w.home.cloudOrigin(), null);
});
+test("a change of home is told once as it happens: My Cloud after the move, this computer when My Cloud ends", async () => {
+ const w = world();
+ w.rehomeThrows = true;
+ await w.home.show();
+ await w.home.show();
+ assert.deepEqual(w.rehomes, [{ kind: "cloud", origin: CLOUD }], "a listener that throws never stops the window");
+ assert.equal(w.home.cloudOrigin(), CLOUD);
+ w.state = connected({ hold: { until: 9 } });
+ await w.home.changed();
+ assert.deepEqual(w.rehomes, [{ kind: "cloud", origin: CLOUD }, { kind: "computer" }]);
+ const never = world({ journal: null, state: { status: "signed-out" } });
+ await never.home.show();
+ await never.home.refresh();
+ assert.deepEqual(never.rehomes, [], "no move: home stays this computer");
+});
+
test("only the main window's main frame counts, at My Cloud's origin for its page and this computer's for the screen", async () => {
const w = world();
await w.home.show();
diff --git a/electron/main.mjs b/electron/main.mjs
index 1ec7806fcc..9823b99496 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -1,4 +1,4 @@
-import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, ipcMain, Menu, nativeImage, Notification, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron";
+import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron";
import { createRequire } from "node:module";
import { randomBytes, randomUUID } from "node:crypto";
import fs from "node:fs";
@@ -8,7 +8,8 @@ import { fileURLToPath } from "node:url";
import { buildErrorPage, desktopViewerErrorPage } from "./error-pages.mjs";
import { startCua, stopCua, registerCuaIpc, requestComputerUse, setCuaStateListener, grantLocalComputer } from "./cua.mjs";
import { createAndroidDeviceController } from "./android-device.mjs";
-import { finishSpeech, startSpeech, stopSpeech } from "./speech.mjs";
+import { finishSpeech, speechBusy, startSpeech, stopSpeech } from "./speech.mjs";
+import { installTalk, isTalkPanel } from "./talk-main.mjs";
import { openBlankTerminal } from "./terminal-launch.mjs";
import { linuxDisablesGpu } from "./linux-gpu.mjs";
import { pasteMenuItem } from "./paste-menu-item.mjs";
@@ -96,7 +97,7 @@ import { CHECKOUT_SOURCES, cloudMenuSublabel, cloudTarget, createCloudAccountCli
import { installCloudPlanIpc } from "./cloud-plan-ipc.mjs";
import { cloudLinkOpensSheet, colorDotIcons, createCloudLook, createCloudReadyNotice, installCloudBuy, lookFile } from "./cloud-buy.mjs";
import { createTrialNotices } from "./cloud-trial-notice.mjs";
-import { DESKTOP_PORTS, jsonFile, registerDesktopPrefs } from "./desktop-prefs.mjs";
+import { createDesktopPrefs, DESKTOP_PORTS, jsonFile, registerDesktopPrefs } from "./desktop-prefs.mjs";
import { createDesktopIncludedX } from "./included-x.mjs"; import { createDesktopIncludedPages } from "./included-pages.mjs";
import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createCloudPowerGate, isCloudHomeEntry, myCloudOrigin, rememberedCloudHome, savedCloudHomeOrigin, signInCloudSession, withCloudHome } from "./cloud-home.mjs";
import { installCloudFiles } from "./cloud-sync-main.mjs";
@@ -138,8 +139,11 @@ let desktopViewerContextId = null;
let desktopWorkspaceManager = null;
let desktopWorkspaceOwner = null;
let pendingOrganizationEntry = takeOrganizationDeepLink(process.argv);
+function appWindows() {
+ return BrowserWindow.getAllWindows().filter((win) => !isTalkPanel(win));
+}
const cloudEntry = createCloudEntry({
- reveal: () => { if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows()); },
+ reveal: () => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); },
open: async () => {
let delivered = false;
await workspaceMenuAction(async () => { delivered = await openCloudEntry(); });
@@ -213,7 +217,7 @@ let openWindowForLink = null;
/** macOS open-url does not fire activate, so a link that finds no window opens one. */
function revealForLink() {
if (desktopTray?.show()) return;
- const appWindow = !startupScreen && mainWindow && !mainWindow.isDestroyed() ? [mainWindow] : BrowserWindow.getAllWindows();
+ const appWindow = !startupScreen && mainWindow && !mainWindow.isDestroyed() ? [mainWindow] : appWindows();
if (activateExistingWindow(appWindow)) return;
openWindowForLink?.();
}
@@ -303,7 +307,7 @@ const serverSupervisor = createServerSupervisor({
orgLibrary?.runtimeReady();
if (managedDesktop) void managedDesktop.refresh().catch(() => {});
routineWake.start();
- for (const win of BrowserWindow.getAllWindows()) {
+ for (const win of appWindows()) {
if (!serverUnavailableWindows.has(win) || activeRemote(environmentsState)) continue;
void win.loadURL(`http://127.0.0.1:${SERVER_PORT}`).then(() => {
serverUnavailableWindows.delete(win);
@@ -889,14 +893,14 @@ async function openCloudAdd(source) {
await cloudAccountRestored();
if (activeRemote(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID));
const win = mainWindow && !mainWindow.isDestroyed() ? mainWindow : createWindow({ deferNavigation: true });
- if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows());
+ if (!desktopTray?.show()) activateExistingWindow(appWindows());
const action = source === "app_howto" ? "cloud-add-howto" : "cloud-add";
if (!win.webContents.isLoadingMainFrame() && senderIsLocal({ sender: win.webContents })) win.webContents.send("app:open-settings", action);
else await win.loadURL(`${rendererOrigin()}/?desktop-settings=${action}`);
}
const announceCloudReady = createCloudReadyNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()),
sheetOpen: () => cloudBuy.sheetOpen(), name: () => cloudLook.current().name, shown: () => cloudAccount?.checkoutDone(),
- open: () => { if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows()); void workspaceMenuAction(() => (homeWindow.cloudOrigin() ? showHome({ place: "cloud" }) : connectCloudHome())); } });
+ open: () => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void workspaceMenuAction(() => (homeWindow.cloudOrigin() ? showHome({ place: "cloud" }) : connectCloudHome())); } });
function ensureManagedDesktop() {
if (managedDesktop) return managedDesktop;
@@ -1493,13 +1497,13 @@ async function openCloudSettings() {
if (!app.isPackaged || desktopRemoteAccess || !serverReady) return;
if (homeWindow.cloudOrigin()) {
await showHome({ place: "cloud" });
- if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows());
+ if (!desktopTray?.show()) activateExistingWindow(appWindows());
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send("app:open-settings", "cloud-settings");
return;
}
if (activeRemote(environmentsState)) persistEnvironments(withActive(environmentsState, LOCAL_ID));
const win = mainWindow && !mainWindow.isDestroyed() ? mainWindow : createWindow({ deferNavigation: true });
- if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows());
+ if (!desktopTray?.show()) activateExistingWindow(appWindows());
if (!win.webContents.isLoadingMainFrame() && senderIsLocal({ sender: win.webContents })) win.webContents.send("app:open-settings", "cloud-settings");
else await win.loadURL(`${rendererOrigin()}/?desktop-settings=cloud-settings`);
}
@@ -1779,7 +1783,7 @@ const organizationEntry = createOrganizationEntry({
function queueOrganizationEntry(link) {
if (!isOrganizationDeepLink(link)) return false;
pendingOrganizationEntry = true;
- if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows());
+ if (!desktopTray?.show()) activateExistingWindow(appWindows());
void deliverOrganizationEntry();
return true;
}
@@ -2340,7 +2344,7 @@ ipcMain.handle("desktop:skin", (event, skin) => {
if (!isKnownSkin(skin)) return false;
if (chromeRail.owns(event)) return true;
try {
- const { color } = skinChrome(skin);
+ talk.skin(skin); const { color } = skinChrome(skin);
const win = BrowserWindow.fromWebContents(event.sender) ?? mainWindow;
if (win && !win.isDestroyed()) {
try { win.setBackgroundColor(color); } catch {}
@@ -2432,21 +2436,8 @@ ipcMain.handle("desktop:relaunch", localOnly("desktop:relaunch", (event) => {
return true;
}));
-ipcMain.handle("speech:start", localOnly("speech:start", (event, options) => {
- const win = BrowserWindow.fromWebContents(event.sender);
- if (!win) return;
- if (!nativeActions.appleSpeech) {
- win.webContents.send("speech:end", { code: 2, reason: "unsupported-platform" });
- return;
- }
- startSpeech(win, options);
-}));
-ipcMain.handle("speech:stop", localOnly("speech:stop", () => {
- if (nativeActions.appleSpeech) stopSpeech();
-}));
-ipcMain.handle("speech:finish", localOnly("speech:finish", () => {
- if (nativeActions.appleSpeech) finishSpeech();
-}));
+const talk = installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions.appleSpeech,
+ speech: { start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy }, packaged: app.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog });
ipcMain.handle("companion:state", localOnly("companion:state", () => desktopCompanionState()));
function managedRemoteAccessRefusal() {
@@ -2679,7 +2670,7 @@ const oneHome = installOneHome({ ipcMain, cloudPage: cloudPageAsking, server: ()
const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, log: slog });
const homeWindow = createHomeWindow({ journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,
window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), ensureWindow: () => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); },
- localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, log: slog,
+ localOrigin: rendererOrigin, cookieFetch: (...args) => session.defaultSession.fetch(...args), power: cloudPower, splash: () => startupScreen, lastInput: oneHome.lastInput, rehomed: () => talk.homeChanged(), log: slog,
hosts: () => session.defaultSession, readyStore: jsonFile(path.join(app.getPath("userData"), "cloud-ready.json")),
remembered: homePlaces.remembered, remember: homePlaces.remember, left: homePlaces.left, drop: homePlaces.drop,
publish: view => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("home:state-changed", view); },
@@ -2712,7 +2703,7 @@ const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, acc
add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),
run: choice => (choice === "link" ? addServerFromClipboard() : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });
const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,
- open: id => { if (!desktopTray?.show()) activateExistingWindow(BrowserWindow.getAllWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });
+ open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });
// A place's colour (place-look.mjs): the Admin's for a Cloud, this app's for a server connected by hand; changed on the
// place's own page or from the window's rail, whatever that server runs.
installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => activeEnvironment(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),
@@ -2878,7 +2869,7 @@ async function broadcastDesktopCapabilities() {
desktopCapabilities({ remote, platform: process.platform, env: process.env, packaged: app.isPackaged, localConnection });
const local = build(false);
let redacted = null;
- for (const window of BrowserWindow.getAllWindows()) {
+ for (const window of appWindows()) {
if (window.isDestroyed()) continue;
let isLocal = false;
try {
@@ -3039,12 +3030,14 @@ app.whenReady().then(async () => {
registerCuaIpc();
androidDevice.registerIpc(ipcMain);
registerUpdaterIpc({ pageAllowed: updaterPageAllowed });
- updatesConsent = registerDesktopPrefs({ ipcMain, cloudAccount: () => cloudAccount, ...jsonFile(path.join(app.getPath("userData"), "desktop-prefs.json")), localConfig: jsonFile(path.join(desktopDataDir(), "config.json")).read, cloudOffered: () => cloudAccountRestored().then(cloudOffersReady),
+ const desktopPrefs = createDesktopPrefs(jsonFile(path.join(app.getPath("userData"), "desktop-prefs.json")));
+ updatesConsent = registerDesktopPrefs({ ipcMain, cloudAccount: () => cloudAccount, prefs: desktopPrefs, localConfig: jsonFile(path.join(desktopDataDir(), "config.json")).read, cloudOffered: () => cloudAccountRestored().then(cloudOffersReady),
languageChanged: (language, sender) => {
- for (const win of BrowserWindow.getAllWindows()) if (!win.isDestroyed() && win.webContents !== sender) win.webContents.send("desktop-language:changed", language);
+ for (const win of appWindows()) if (!win.isDestroyed() && win.webContents !== sender) win.webContents.send("desktop-language:changed", language);
chromeRail.send("desktop-language:changed", language);
},
page: event => senderIsLocal(event) ? "local" : cloudPageAsking(event) ?? (workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin()) ? "server" : null) });
+ talk.start({ globalShortcut, screen, prefs: desktopPrefs, remote: () => Boolean(desktopRemoteAccess), away: () => homeWindow.current().kind !== "computer", starting: () => !serverReady, localRequest: localServerRequest, dataDir: () => runningDataDir });
// Before the window, so the harness has the CUA descriptor on first render.
cuaReady =
!desktopRemoteAccess && (process.platform === "darwin" || process.platform === "linux" || process.platform === "win32")
@@ -3164,7 +3157,7 @@ app.whenReady().then(async () => {
return credentials;
}).finally(syncManagedComposioCredentials);
}
- startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => origin === homeWindow.cloudOrigin() && cloudPower.asleep(), busy: () => (oneHome.oneHome.busy() && "move") || (computerSharing?.busy() && "lending") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
+ startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => origin === homeWindow.cloudOrigin() && cloudPower.asleep(), busy: () => (oneHome.oneHome.busy() && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
refreshApplicationMenu();
openWindowForLink = () => {
if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: homeWindow.current().kind !== "computer" });
@@ -3172,13 +3165,13 @@ app.whenReady().then(async () => {
};
app.on("activate", () => {
if (desktopTray?.show()) return;
- if (BrowserWindow.getAllWindows().length === 0) openWindowForLink();
+ if (appWindows().length === 0) openWindowForLink();
});
}).finally(() => allWindowsClosedQuit.settleStartup());
const allWindowsClosedQuit = createAllWindowsClosedQuit({
app,
- allWindows: () => BrowserWindow.getAllWindows(), stayOpen: () => hiddenStart,
+ allWindows: () => appWindows(), stayOpen: () => hiddenStart,
});
// The embedded CUA daemon's async cleanup cannot run after the host exits, so the first quit waits for it (capped).
@@ -3197,6 +3190,7 @@ process.once("SIGINT", requestSignalQuit);
process.once("SIGTERM", requestSignalQuit);
app.on("before-quit", (e) => {
+ talk.close();
desktopShutdownStarted = true;
startupScreen?.dispose();
companyBackupSchedule?.close();
diff --git a/electron/organization-entry.node-test.mjs b/electron/organization-entry.node-test.mjs
index 05cabedd6d..7a6d418ae8 100644
--- a/electron/organization-entry.node-test.mjs
+++ b/electron/organization-entry.node-test.mjs
@@ -48,7 +48,7 @@ test("consuming a launch action prevents it replaying on a later restart without
test("desktop relaunch accepts every platform once, guards its sender, and preserves consumed arguments and normal shutdown", () => {
const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8");
- const source = main.slice(main.indexOf('ipcMain.handle("desktop:relaunch"'), main.indexOf('ipcMain.handle("speech:start"'))
+ const source = main.slice(main.indexOf('ipcMain.handle("desktop:relaunch"'), main.indexOf("const talk = installTalk("))
+ main.slice(main.indexOf("function requireMainWindowSender("), main.indexOf('ipcMain.handle("desktop-remote:state"'));
const argv = ["/fixture/OpenMausBot", "--fixture", "openmausbot://organization", "openmausbot://organization?ignored"];
takeOrganizationDeepLink(argv);
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 9a3f493ca7..ae918543af 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -63,7 +63,7 @@ if (typeof window !== "undefined") {
}
const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "cloudAdd", "cloudPlan", "cloudSendPage", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls"]);
/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */
-const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "onOpenAppSettings", "exportDiagnostics", "openLogsFolder", "openAtLogin"];
+const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "onOpenAppSettings", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];
function updaterOffered() {
try { return ipcRenderer.sendSync("update:offered") === true; } catch { return false; }
}
@@ -243,6 +243,14 @@ const bridge = {
ipcRenderer.on("speech:end", handler);
return () => ipcRenderer.removeListener("speech:end", handler);
},
+ talkShortcut: {
+ state: () => ipcRenderer.invoke("talk-shortcut:state"),
+ set: (change) => ipcRenderer.invoke("talk-shortcut:set", {
+ ...(typeof change?.enabled === "boolean" ? { enabled: change.enabled } : {}),
+ ...(typeof change?.key === "string" ? { key: change.key } : {}),
+ }),
+ },
+ callActive: (active) => ipcRenderer.invoke("call:active", active === true).then(() => undefined),
onOpenAppSettings: (cb) => {
appSettingsListeners.add(cb);
queueMicrotask(() => {
diff --git a/electron/preload.node-test.mjs b/electron/preload.node-test.mjs
index 0eb391e2c0..2dac7a6b13 100644
--- a/electron/preload.node-test.mjs
+++ b/electron/preload.node-test.mjs
@@ -74,6 +74,15 @@ test("browser control forwards a separate per-device capability, not the cloud g
]);
});
+test("the talk bridge asks main over its own channels with only what it understands", async () => {
+ const before = invocations.length;
+ await exposed.api.talkShortcut.state();
+ await exposed.api.talkShortcut.set({ enabled: false, key: "ctrl-shift-space", extra: "x" });
+ await exposed.api.callActive(true);
+ await exposed.api.callActive("yes");
+ assert.deepEqual(invocations.slice(before), [["talk-shortcut:state"], ["talk-shortcut:set", { enabled: false, key: "ctrl-shift-space" }], ["call:active", true], ["call:active", false]]);
+});
+
test("account prepare asks for the secure address over its own channel and sends nothing from the page", async () => {
const before = invocations.length;
await exposed.api.companionAccount.prepare({ endpoint: "https://evil.example.test" });
diff --git a/electron/resources/speech-helper.swift b/electron/resources/speech-helper.swift
index a5ce334915..9633beeedf 100644
--- a/electron/resources/speech-helper.swift
+++ b/electron/resources/speech-helper.swift
@@ -11,7 +11,11 @@
// request on silence by itself; it only produces `isFinal` after endAudio().
// Composer dictation omits this flag and keeps its existing press-to-stop
// behavior, while call mode opts into silence endpointing.
+//
+// `--finish-on-release control,option` finishes recognition once any of the
+// listed modifiers (control, option, shift, command) is no longer held.
import AVFoundation
+import CoreGraphics
import Foundation
import Speech
@@ -51,6 +55,42 @@ let finishFile: String? = {
return args[index + 1]
}()
+func releaseModifiers(_ list: String) -> CGEventFlags? {
+ var flags = CGEventFlags()
+ for name in list.split(separator: ",", omittingEmptySubsequences: false) {
+ switch name {
+ case "control": flags.insert(.maskControl)
+ case "option": flags.insert(.maskAlternate)
+ case "shift": flags.insert(.maskShift)
+ case "command": flags.insert(.maskCommand)
+ default: return nil
+ }
+ }
+ return flags.isEmpty ? nil : flags
+}
+
+func released(_ required: CGEventFlags, _ current: CGEventFlags) -> Bool {
+ !current.contains(required)
+}
+
+if let index = CommandLine.arguments.firstIndex(of: "--release-check") {
+ let args = CommandLine.arguments
+ guard index + 2 < args.count, let required = releaseModifiers(args[index + 1]),
+ let raw = UInt64(args[index + 2])
+ else { fail("bad-modifiers") }
+ emit(["released": released(required, CGEventFlags(rawValue: raw))])
+ exit(0)
+}
+
+let finishOnRelease: CGEventFlags? = {
+ let args = CommandLine.arguments
+ guard let index = args.firstIndex(of: "--finish-on-release") else { return nil }
+ guard index + 1 < args.count, let flags = releaseModifiers(args[index + 1]) else {
+ fail("bad-modifiers")
+ }
+ return flags
+}()
+
// LaunchServices gives the helper the bundle identity TCC needs, but it also
// means the parent cannot terminate it by killing the `open -W` process. A
// per-session stop marker keeps intentional mute/hang-up deterministic.
@@ -70,11 +110,14 @@ if let stopFile {
// if an unusually fast key release beats authorization/setup.
var finishHandler: (() -> Void)?
var finishTimer: DispatchSourceTimer?
-if let finishFile {
+if finishFile != nil || finishOnRelease != nil {
let timer = DispatchSource.makeTimerSource(queue: .global(qos: .userInitiated))
timer.schedule(deadline: .now() + .milliseconds(50), repeating: .milliseconds(50))
timer.setEventHandler {
- guard FileManager.default.fileExists(atPath: finishFile), let finish = finishHandler else { return }
+ let finishRequested =
+ finishFile.map { FileManager.default.fileExists(atPath: $0) } == true
+ || finishOnRelease.map { released($0, CGEventSource.flagsState(.combinedSessionState)) } == true
+ guard finishRequested, let finish = finishHandler else { return }
timer.cancel()
finish()
}
diff --git a/electron/skin-overlay.cjs b/electron/skin-overlay.cjs
index fc68395dc3..8e44935e1b 100644
--- a/electron/skin-overlay.cjs
+++ b/electron/skin-overlay.cjs
@@ -26,4 +26,11 @@ function isKnownSkin(skin) {
return Object.hasOwn(SKIN_CHROME, skin);
}
-module.exports = { SKIN_CHROME, DEFAULT_SKIN, skinChrome, isKnownSkin };
+/** A light skin: its page colour is nearer white than black. */
+function skinIsLight(skin) {
+ const hex = skinChrome(skin).color;
+ const [r, g, b] = [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16));
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 127.5;
+}
+
+module.exports = { SKIN_CHROME, DEFAULT_SKIN, skinChrome, isKnownSkin, skinIsLight };
diff --git a/electron/skin-overlay.test.mjs b/electron/skin-overlay.test.mjs
index 77fb6ada10..59505bb209 100644
--- a/electron/skin-overlay.test.mjs
+++ b/electron/skin-overlay.test.mjs
@@ -5,7 +5,7 @@ import { createRequire } from "node:module";
import { describe, expect, it } from "vitest";
const require = createRequire(import.meta.url);
-const { SKIN_CHROME, DEFAULT_SKIN, skinChrome, isKnownSkin } = require("./skin-overlay.cjs");
+const { SKIN_CHROME, DEFAULT_SKIN, skinChrome, isKnownSkin, skinIsLight } = require("./skin-overlay.cjs");
const here = dirname(fileURLToPath(import.meta.url));
const css = readFileSync(join(here, "../src/styles.css"), "utf8");
@@ -31,6 +31,13 @@ describe("skin overlay chrome", () => {
}
});
+ it("tells light skins from dark ones as the renderer's --code-color-scheme does", () => {
+ for (const skin of Object.keys(SKIN_CHROME)) {
+ const scheme = css.match(new RegExp(`\\[data-skin="${skin}"\\]\\s*\\{[^}]*--code-color-scheme:\\s*(light|dark)`))?.[1];
+ expect(skinIsLight(skin) ? "light" : "dark", skin).toBe(scheme);
+ }
+ });
+
it("uses opaque symbol colours the overlay can accept", () => {
// The Windows overlay rejects alpha, so every symbolColor is plain 6-digit hex.
for (const chrome of Object.values(SKIN_CHROME)) {
diff --git a/electron/speech-helper-release.node-test.mjs b/electron/speech-helper-release.node-test.mjs
new file mode 100644
index 0000000000..6c1f70fd41
--- /dev/null
+++ b/electron/speech-helper-release.node-test.mjs
@@ -0,0 +1,38 @@
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+
+const CONTROL = 0x40000, OPTION = 0x80000, SHIFT = 0x20000, COMMAND = 0x100000;
+
+const swiftc =
+ process.platform === "darwin" &&
+ spawnSync("xcrun", ["--find", "swiftc"], { encoding: "utf8" }).status === 0;
+
+test("the helper finishes when any of the chosen modifiers is let go", { skip: !swiftc && "needs macOS with swiftc" }, () => {
+ const dir = mkdtempSync(join(tmpdir(), "speech-helper-release-"));
+ try {
+ const bin = join(dir, "speech-helper");
+ execFileSync(
+ "xcrun",
+ ["swiftc", "-Onone", fileURLToPath(new URL("./resources/speech-helper.swift", import.meta.url)), "-o", bin],
+ { timeout: 180_000 },
+ );
+ const check = (mods, flags) =>
+ JSON.parse(execFileSync(bin, ["--release-check", mods, String(flags)], { encoding: "utf8", timeout: 10_000 }));
+ assert.deepEqual(check("control,option", CONTROL | OPTION), { released: false });
+ assert.deepEqual(check("control,option", CONTROL | OPTION | SHIFT), { released: false });
+ assert.deepEqual(check("control,option", CONTROL), { released: true });
+ assert.deepEqual(check("control,option", 0), { released: true });
+ assert.deepEqual(check("option,shift", OPTION | SHIFT), { released: false });
+ assert.deepEqual(check("option,shift", SHIFT | COMMAND), { released: true });
+ const bad = spawnSync(bin, ["--release-check", "control,hyper", "0"], { encoding: "utf8", timeout: 10_000 });
+ assert.equal(bad.status, 1);
+ assert.deepEqual(JSON.parse(bad.stdout), { error: "bad-modifiers" });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/electron/speech.mjs b/electron/speech.mjs
index 60bf1fdbfa..110f6a0a13 100644
--- a/electron/speech.mjs
+++ b/electron/speech.mjs
@@ -42,14 +42,49 @@ function ensureBuilt() {
buildSpeechHelper();
}
-function sendEnd(win, info) {
- if (!win.isDestroyed()) win.webContents.send("speech:end", info);
+const RELEASE_MODIFIERS = ["control", "option", "shift", "command"];
+const PAGE_GONE = ["render-process-gone", "did-navigate"];
+
+function speechTarget(target) {
+ if (typeof target?.transcript === "function") return {
+ owner: target,
+ transcript: (line) => target.transcript(line),
+ end: (info) => target.end(info),
+ replaced: () => target.replaced(),
+ whenGone: () => () => {},
+ };
+ const send = (channel, body) => {
+ if (!target.isDestroyed()) target.webContents.send(channel, body);
+ };
+ return {
+ owner: target,
+ transcript: (line) => send("speech:transcript", line),
+ end: (info) => send("speech:end", info),
+ replaced: () => {},
+ whenGone: (listener) => {
+ // Electron: a destroyed BrowserWindow throws when its webContents is read.
+ const contents = target.webContents;
+ target.on("closed", listener);
+ for (const event of PAGE_GONE) contents.on(event, listener);
+ return () => {
+ target.removeListener("closed", listener);
+ for (const event of PAGE_GONE) contents.removeListener(event, listener);
+ };
+ },
+ };
}
-export function startSpeech(win, options = {}) {
+export function speechBusy() {
+ return child !== null;
+}
+
+export function startSpeech(target, options = {}) {
+ const running = child;
stopSpeech();
+ running?.target.replaced();
+ const sink = speechTarget(target);
if (process.platform !== "darwin") {
- sendEnd(win, { code: 2, reason: "unsupported-platform" });
+ sink.end({ code: 2, reason: "unsupported-platform" });
return;
}
const requested = Number(options?.endpointMs);
@@ -57,11 +92,14 @@ export function startSpeech(win, options = {}) {
? Math.min(5_000, Math.max(250, Math.round(requested)))
: 0;
const args = endpointMs ? ["--endpoint-ms", String(endpointMs)] : [];
+ const release = [...new Set(Array.isArray(options?.finishOnRelease) ? options.finishOnRelease : [])]
+ .filter((name) => RELEASE_MODIFIERS.includes(name));
+ if (release.length) args.push("--finish-on-release", release.join(","));
try {
ensureBuilt();
} catch {
- sendEnd(win, { code: 1, reason: "helper-build-failed" });
+ sink.end({ code: 1, reason: "helper-build-failed" });
return;
}
@@ -98,12 +136,16 @@ export function startSpeech(win, options = {}) {
);
} catch {
rmSync(sessionDir, { recursive: true, force: true });
- sendEnd(win, { code: 1, reason: "helper-start-failed" });
+ sink.end({ code: 1, reason: "helper-start-failed" });
return;
}
- const speechSession = { proc, outputPath, errorPath, stopPath, finishPath, sessionDir };
+ const speechSession = {
+ proc, outputPath, errorPath, stopPath, finishPath, sessionDir,
+ owner: sink.owner, target: sink,
+ };
child = speechSession;
+ const forgetWindow = sink.whenGone(() => stopSpeech(sink.owner));
let buf = "";
let offset = 0;
let reportedError = null;
@@ -130,9 +172,7 @@ export function startSpeech(win, options = {}) {
if (typeof parsed.error === "string") reportedError = parsed.error;
if (parsed.partial === false && typeof parsed.text === "string") completed = true;
// A stopped or replaced helper can flush one last chunk: never into the session that replaced it.
- if (child === speechSession && !win.isDestroyed()) {
- win.webContents.send("speech:transcript", transcript(parsed));
- }
+ if (child === speechSession) sink.transcript(transcript(parsed));
} catch {
}
}
@@ -143,6 +183,7 @@ export function startSpeech(win, options = {}) {
const cleanup = () => {
if (cleaned) return;
cleaned = true;
+ forgetWindow();
unwatchFile(outputPath, drain);
rmSync(sessionDir, { recursive: true, force: true });
};
@@ -153,23 +194,25 @@ export function startSpeech(win, options = {}) {
if (child !== speechSession) return;
child = null;
if (reportedError) {
- sendEnd(win, { code: 1, reason: reportedError });
+ sink.end({ code: 1, reason: reportedError });
} else if (completed && code === 0) {
- sendEnd(win, { code: 0, reason: "completed" });
+ sink.end({ code: 0, reason: "completed" });
} else {
- sendEnd(win, { code: 1, reason: "helper-exited" });
+ sink.end({ code: 1, reason: "helper-exited" });
}
});
proc.on("error", () => {
cleanup();
if (child !== speechSession) return;
child = null;
- sendEnd(win, { code: 1, reason: "helper-start-failed" });
+ sink.end({ code: 1, reason: "helper-start-failed" });
});
}
-export function stopSpeech() {
- if (!child) return;
+const ownedBy = (owner) => child !== null && (owner === undefined || child.owner === owner);
+
+export function stopSpeech(owner) {
+ if (!ownedBy(owner)) return;
const speechSession = child;
child = null;
try {
@@ -177,8 +220,8 @@ export function stopSpeech() {
} catch {}
}
-export function finishSpeech() {
- if (!child) return;
+export function finishSpeech(owner) {
+ if (!ownedBy(owner)) return;
try {
writeFileSync(child.finishPath, "finish");
} catch {}
diff --git a/electron/speech.test.mjs b/electron/speech.test.mjs
index 49ad6ab47f..db3498101e 100644
--- a/electron/speech.test.mjs
+++ b/electron/speech.test.mjs
@@ -9,20 +9,27 @@ vi.mock("node:child_process", () => ({
spawn: (_file, args) => {
const proc = new EventEmitter();
const arg = flag => args[args.indexOf(flag) + 1];
- fixture.launches.push({ proc, output: arg("-o"), stop: arg("--stop-file"), finish: arg("--finish-file") });
+ fixture.launches.push({ proc, args, output: arg("-o"), stop: arg("--stop-file"), finish: arg("--finish-file") });
return proc;
},
}));
Object.defineProperty(process, "resourcesPath", { configurable: true, value: "/synthetic-speech-resources" });
-const { startSpeech, stopSpeech, finishSpeech } = await import("./speech.mjs");
+const { startSpeech, stopSpeech, finishSpeech, speechBusy } = await import("./speech.mjs");
+const PAGE_GONE = ["did-navigate", "render-process-gone"];
const launch = () => {
const events = [];
- const win = { isDestroyed: () => false, webContents: { send: (channel, body) => events.push({ channel, body }) } };
+ let destroyed = false;
+ const contents = Object.assign(new EventEmitter(), { send: (channel, body) => events.push({ channel, body }) });
+ const win = Object.assign(new EventEmitter(), { isDestroyed: () => destroyed });
+ // Electron: a destroyed BrowserWindow throws "Object has been destroyed" when its webContents is read.
+ Object.defineProperty(win, "webContents", { get: () => { if (destroyed) throw new TypeError("Object has been destroyed"); return contents; } });
+ const close = () => { destroyed = true; win.emit("closed"); };
startSpeech(win);
- return { ...fixture.launches.at(-1), events };
+ return { ...fixture.launches.at(-1), events, win, contents, close };
};
+const pageListeners = session => PAGE_GONE.map(event => session.contents.listenerCount(event));
const emit = (session, line) => appendFileSync(session.output, `${JSON.stringify(line)}\n`);
afterEach(() => {
@@ -76,4 +83,117 @@ describe.skipIf(process.platform !== "darwin")("native speech file transport", (
session.proc.emit("close", 0);
expect(session.events[0].body.text).toBe("確定結果");
});
+
+ const sinkOf = () => {
+ const heard = { lines: [], ends: [], replaced: 0 };
+ return { heard, sink: { transcript: line => heard.lines.push(line), end: info => heard.ends.push(info), replaced: () => { heard.replaced += 1; } } };
+ };
+ const flag = (session, name) => session.args.includes(name) ? session.args[session.args.indexOf(name) + 1] : undefined;
+
+ it("delivers a sink's session to the sink and tells the helper which keys end it", () => {
+ const { heard, sink } = sinkOf();
+ startSpeech(sink, { finishOnRelease: ["control", "option"] });
+ const session = fixture.launches.at(-1);
+ expect(flag(session, "--finish-on-release")).toBe("control,option");
+ expect(speechBusy()).toBe(true);
+ emit(session, { text: "what's on today", partial: false });
+ session.proc.emit("close", 0);
+ expect(heard.lines).toEqual([{ text: "what's on today", partial: false }]);
+ expect(heard.ends).toEqual([{ code: 0, reason: "completed" }]);
+ expect(speechBusy()).toBe(false);
+ });
+ it("tells a replaced sink, and never ends it", () => {
+ const { heard, sink } = sinkOf();
+ startSpeech(sink);
+ const first = fixture.launches.at(-1);
+ launch();
+ expect(heard.replaced).toBe(1);
+ first.proc.emit("close", 0);
+ expect(heard.ends).toEqual([]);
+ });
+ it("a page's stop or finish never touches a session it did not start", () => {
+ const { sink } = sinkOf();
+ startSpeech(sink);
+ const session = fixture.launches.at(-1);
+ const page = { isDestroyed: () => false, webContents: { send: () => {} } };
+ stopSpeech(page); finishSpeech(page); stopSpeech(null);
+ expect(existsSync(session.stop)).toBe(false);
+ expect(existsSync(session.finish)).toBe(false);
+ finishSpeech(sink); expect(existsSync(session.finish)).toBe(true);
+ stopSpeech(sink); expect(existsSync(session.stop)).toBe(true);
+ expect(speechBusy()).toBe(false);
+ });
+ it("a window's stop and finish reach the session that window started", () => {
+ const session = launch();
+ finishSpeech(session.win);
+ expect(existsSync(session.finish)).toBe(true);
+ stopSpeech(session.win);
+ expect(existsSync(session.stop)).toBe(true);
+ expect(speechBusy()).toBe(false);
+ });
+ it("another window's stop and finish leave a window's session alone", () => {
+ const session = launch();
+ const other = { isDestroyed: () => false, webContents: { send: () => {} } };
+ stopSpeech(other); finishSpeech(other);
+ expect(existsSync(session.stop)).toBe(false);
+ expect(existsSync(session.finish)).toBe(false);
+ expect(speechBusy()).toBe(true);
+ });
+ it("a window that closes stops the session it started, and an ended session lets go of its window", () => {
+ const session = launch();
+ expect(session.win.listenerCount("closed")).toBe(1);
+ expect(pageListeners(session)).toEqual([1, 1]);
+ session.close();
+ expect(existsSync(session.stop)).toBe(true);
+ expect(speechBusy()).toBe(false);
+ expect(() => session.proc.emit("close", 0)).not.toThrow();
+ expect(session.events).toEqual([]);
+ expect(session.win.listenerCount("closed")).toBe(0);
+ expect(pageListeners(session)).toEqual([0, 0]);
+ });
+ it("a window's page that reloads or navigates away stops the session it started; a route change inside the page does not", () => {
+ const session = launch();
+ session.contents.emit("did-navigate-in-page", {}, "http://127.0.0.1:8799/#/settings");
+ expect(existsSync(session.stop)).toBe(false);
+ expect(speechBusy()).toBe(true);
+ session.contents.emit("did-navigate", {}, "http://127.0.0.1:8799/");
+ expect(existsSync(session.stop)).toBe(true);
+ expect(speechBusy()).toBe(false);
+ session.proc.emit("close", 0);
+ expect(session.events).toEqual([]);
+ expect(session.win.listenerCount("closed")).toBe(0);
+ expect(pageListeners(session)).toEqual([0, 0]);
+ });
+ it("a window's page whose renderer goes away stops the session it started", () => {
+ const session = launch();
+ session.contents.emit("render-process-gone", {}, { reason: "crashed" });
+ expect(existsSync(session.stop)).toBe(true);
+ expect(speechBusy()).toBe(false);
+ session.proc.emit("close", 0);
+ expect(session.win.listenerCount("closed")).toBe(0);
+ expect(pageListeners(session)).toEqual([0, 0]);
+ });
+ it("a window's session that ends on its own lets go of the window and its page", () => {
+ const session = launch();
+ emit(session, { text: "done", partial: false });
+ session.proc.emit("close", 0);
+ expect(session.events.at(-1)).toEqual({ channel: "speech:end", body: { code: 0, reason: "completed" } });
+ expect(session.win.listenerCount("closed")).toBe(0);
+ expect(pageListeners(session)).toEqual([0, 0]);
+ });
+ it("a window or page that goes away after its session was replaced leaves the new session alone", () => {
+ const first = launch();
+ const second = launch();
+ first.proc.emit("close", 0);
+ for (const event of PAGE_GONE) first.contents.emit(event, {});
+ first.close();
+ expect(existsSync(second.stop)).toBe(false);
+ expect(speechBusy()).toBe(true);
+ });
+ it("passes only known release modifiers", () => {
+ startSpeech(sinkOf().sink, { finishOnRelease: ["control", "hyper", "control"] });
+ expect(flag(fixture.launches.at(-1), "--finish-on-release")).toBe("control");
+ startSpeech(sinkOf().sink, { finishOnRelease: ["hyper"] });
+ expect(fixture.launches.at(-1).args).not.toContain("--finish-on-release");
+ });
});
diff --git a/electron/talk-keys.mjs b/electron/talk-keys.mjs
new file mode 100644
index 0000000000..348bdb3cc6
--- /dev/null
+++ b/electron/talk-keys.mjs
@@ -0,0 +1,8 @@
+export const TALK_KEYS = Object.freeze({
+ "ctrl-opt-space": Object.freeze({ accelerator: "Control+Alt+Space", release: Object.freeze(["control", "option"]), label: "⌃⌥Space" }),
+ "ctrl-shift-space": Object.freeze({ accelerator: "Control+Shift+Space", release: Object.freeze(["control", "shift"]), label: "⌃⇧Space" }),
+ "opt-shift-space": Object.freeze({ accelerator: "Alt+Shift+Space", release: Object.freeze(["option", "shift"]), label: "⌥⇧Space" }),
+});
+export const DEFAULT_TALK_KEY = "ctrl-opt-space";
+export const isTalkKey = id => typeof id === "string" && Object.hasOwn(TALK_KEYS, id);
+export const talkKey = id => TALK_KEYS[isTalkKey(id) ? id : DEFAULT_TALK_KEY];
diff --git a/electron/talk-main.mjs b/electron/talk-main.mjs
new file mode 100644
index 0000000000..d3050c9340
--- /dev/null
+++ b/electron/talk-main.mjs
@@ -0,0 +1,84 @@
+import skins from "./skin-overlay.cjs";
+import { createTalkPanel } from "./talk-panel.mjs";
+import { createTalkServer } from "./talk-server.mjs";
+import { createTalkSession } from "./talk-session.mjs";
+import { createCallPresence, createTalkShortcut, TALK_SHORTCUT_UNAVAILABLE } from "./talk-shortcut.mjs";
+
+export { isTalkPanel } from "./talk-panel.mjs";
+
+/**
+ * The microphone's IPC for this app's pages (dictation, calls, the talk setting), then the talk shortcut once the app
+ * is ready. `speech`: speech.mjs's start/stop/finish/busy. `packaged`: asks go to `localRequest`, this computer's own
+ * server; in development to `devUrl`, whose Vite /api proxy reaches `pnpm dev:server`.
+ */
+export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech, speech, packaged, devUrl, nativeImage, iconPath, openLink, reveal, log, fetch = globalThis.fetch }) {
+ const callPresence = createCallPresence();
+ let shortcut = null, session = null, panel = null, theme = null;
+
+ ipcMain.handle("speech:start", localOnly("speech:start", (event, options) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (!win) return;
+ if (!appleSpeech) {
+ win.webContents.send("speech:end", { code: 2, reason: "unsupported-platform" });
+ return;
+ }
+ speech.start(win, options);
+ }));
+ ipcMain.handle("speech:stop", localOnly("speech:stop", (event) => {
+ if (appleSpeech) speech.stop(BrowserWindow.fromWebContents(event.sender));
+ }));
+ ipcMain.handle("speech:finish", localOnly("speech:finish", (event) => {
+ if (appleSpeech) speech.finish(BrowserWindow.fromWebContents(event.sender));
+ }));
+ ipcMain.handle("talk-shortcut:state", localOnly("talk-shortcut:state", () => shortcut?.state() ?? TALK_SHORTCUT_UNAVAILABLE));
+ ipcMain.handle("talk-shortcut:set", localOnly("talk-shortcut:set", (_event, change) => shortcut?.set({
+ enabled: typeof change?.enabled === "boolean" ? change.enabled : undefined,
+ key: typeof change?.key === "string" ? change.key : undefined,
+ }) ?? TALK_SHORTCUT_UNAVAILABLE));
+ ipcMain.handle("call:active", localOrHome("call:active", (event, active) => {
+ callPresence.set(event.sender, active === true);
+ }));
+
+ // Electron: a throw inside a globalShortcut or webContents event callback reaches no caller.
+ const logged = (what, run) => () => {
+ try { run(); } catch (error) { log(`talk ${what} failed: ${error?.message ?? error}`); }
+ };
+
+ return {
+ /** `remote()`: this desktop is a remote client of another computer. `away()`: this computer's bots moved to My Cloud,
+ * so its own copy is frozen. `starting()`: this computer's server is on its way up. `dataDir()`: the data folder
+ * this process runs. */
+ start({ globalShortcut, screen, prefs, remote, away, starting, localRequest, dataDir }) {
+ const request = (route, init) => (packaged ? localRequest(route, init) : fetch(new URL(route, devUrl), init));
+ try {
+ panel = createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath, theme, onOpen: logged("open", () => session.open()), onDismiss: logged("dismiss", () => session.dismiss()) });
+ session = createTalkSession({
+ speech,
+ server: createTalkServer({ request, prefs, starting, serverKey: () => (packaged ? dataDir() : devUrl) ?? "local" }),
+ panel,
+ voiceInUse: () => speech.busy() || callPresence.active(),
+ release: () => shortcut.releaseModifiers(),
+ openChat: chat => (chat ? openLink(`openmausbot://thread/${encodeURIComponent(chat.threadId)}?bot=${encodeURIComponent(chat.botId)}`) : reveal()),
+ });
+ shortcut = createTalkShortcut({ globalShortcut, prefs, available: () => appleSpeech && !remote() && !away(), onPress: logged("press", () => session.press()) });
+ } catch (error) {
+ session = null;
+ log(`talk shortcut unavailable: ${error?.message ?? error}`);
+ }
+ },
+ /** Home changed (My Cloud, or this computer again): the key is let go or taken again to match. */
+ homeChanged: logged("home change", () => shortcut?.refresh()),
+ /** A page painted the app's skin (its id, resolved from the Theme setting): the box takes its light or dark. */
+ skin(id) {
+ if (!skins.isKnownSkin(id)) return;
+ theme = skins.skinIsLight(id) ? "light" : "dark";
+ logged("skin", () => panel?.setTheme(theme))();
+ },
+ /** Listening, or an ask on its way that has not been answered yet. */
+ busy: () => session?.busy() ?? false,
+ close() {
+ logged("close", () => session?.close())();
+ logged("close", () => shortcut?.close())();
+ },
+ };
+}
diff --git a/electron/talk-main.node-test.mjs b/electron/talk-main.node-test.mjs
new file mode 100644
index 0000000000..5bd0af37ca
--- /dev/null
+++ b/electron/talk-main.node-test.mjs
@@ -0,0 +1,317 @@
+import { EventEmitter } from "node:events";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createDesktopPrefs } from "./desktop-prefs.mjs";
+import { installTalk, isTalkPanel } from "./talk-main.mjs";
+import { TALK_SHORTCUT_UNAVAILABLE } from "./talk-shortcut.mjs";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const main = readFileSync(join(here, "main.mjs"), "utf8").replace(/\r\n/g, "\n");
+const preload = readFileSync(join(here, "preload.cjs"), "utf8");
+const settle = async () => { for (let i = 0; i < 10; i += 1) await new Promise(resolve => setImmediate(resolve)); };
+const json = body => Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }));
+const names = windows => windows.map(win => win?.name ?? null);
+
+function harness({ packaged = true, appleSpeech = true, remote = false, register, serve = () => undefined } = {}) {
+ const h = { handlers: new Map(), guards: new Map(), started: [], stopped: [], finished: [], requests: [], links: [], reveals: 0, log: [],
+ registered: new Map(), windows: [], busy: false, fail: {}, away: false, starting: false };
+ const owners = new Map();
+ class FakeBrowserWindow {
+ static fromWebContents(contents) { return owners.get(contents) ?? null; }
+ constructor(options = {}) {
+ Object.assign(this, { options, name: options.name, destroyed: false, events: new EventEmitter() });
+ this.webContents = Object.assign(new EventEmitter(), { sent: [], scripts: [], setWindowOpenHandler() {} });
+ this.webContents.executeJavaScript = async script => { this.webContents.scripts.push(script); return 56; };
+ this.webContents.send = (...message) => { this.webContents.sent.push(message); };
+ owners.set(this.webContents, this);
+ h.windows.push(this);
+ }
+ on(...args) { this.events.on(...args); }
+ setAlwaysOnTop() {}
+ setVisibleOnAllWorkspaces() {}
+ setBounds() {}
+ getBounds() { return { x: 0, y: 0, width: 0, height: 0 }; }
+ showInactive() {}
+ loadURL() { return Promise.resolve(); }
+ isDestroyed() { return this.destroyed; }
+ destroy() { this.destroyed = true; }
+ }
+ const failing = (name, run) => (...args) => {
+ if (h.fail[name]) throw new Error(h.fail[name]);
+ return run(...args);
+ };
+ const answer = route => serve(route) ?? new Promise(() => {});
+ const guard = kind => (channel, handler) => { h.guards.set(channel, kind); return handler; };
+ h.talk = installTalk({
+ ipcMain: { handle: (channel, handler) => h.handlers.set(channel, handler) },
+ localOnly: guard("localOnly"), localOrHome: guard("localOrHome"), BrowserWindow: FakeBrowserWindow, appleSpeech,
+ speech: {
+ start: (target, options) => { h.started.push([target, options]); },
+ stop: failing("stop", owner => { h.stopped.push(owner); }),
+ finish: owner => { h.finished.push(owner); },
+ busy: failing("busy", () => h.busy),
+ },
+ packaged, devUrl: "http://127.0.0.1:5199", iconPath: join(here, "resources", "app-icon.png"),
+ nativeImage: { createFromPath: () => ({ isEmpty: () => false, resize: () => ({ toPNG: () => Buffer.from("png") }) }) },
+ openLink: link => { h.links.push(link); }, reveal: failing("reveal", () => { h.reveals += 1; }), log: line => { h.log.push(line); },
+ fetch: url => { h.requests.push(["dev", String(url)]); return answer(`${url.pathname}${url.search}`); },
+ });
+ const globalShortcut = {
+ register: register ?? ((accelerator, press) => { h.registered.set(accelerator, press); return true; }),
+ unregister: accelerator => { h.registered.delete(accelerator); },
+ };
+ const screen = { getCursorScreenPoint: () => ({ x: 0, y: 0 }), getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 25, width: 1440, height: 875 } }) };
+ h.start = () => h.talk.start({ globalShortcut, screen, prefs: createDesktopPrefs({ read: () => null, write: () => {} }), remote: () => remote,
+ away: failing("away", () => h.away), starting: () => h.starting,
+ localRequest: route => { h.requests.push(["local", route]); return answer(route); }, dataDir: () => "/Users/a/.openmausbot" });
+ h.handle = (channel, event, ...args) => h.handlers.get(channel)(event, ...args);
+ h.press = () => h.registered.get("Control+Alt+Space")();
+ h.page = name => new FakeBrowserWindow({ name });
+ h.box = () => h.windows.findLast(win => isTalkPanel(win));
+ h.click = what => h.box().webContents.emit("ipc-message", {}, `talk-panel:${what}`);
+ h.painted = async () => { h.box().webContents.emit("did-finish-load"); await settle(); return h.box().webContents.scripts.filter(script => script.startsWith("render(")).map(script => JSON.parse(script.slice(7, -1))); };
+ return h;
+}
+
+test("every list of the app's windows leaves the talk box out", () => {
+ assert.equal(main.match(/BrowserWindow\.getAllWindows\(\)/g).length, 1);
+ assert.match(main, /function appWindows\(\) \{\s*return BrowserWindow\.getAllWindows\(\)\.filter\(\(win\) => !isTalkPanel\(win\)\);/);
+ assert.match(main, /if \(appWindows\(\)\.length === 0\) openWindowForLink\(\);/);
+ assert.match(main, /allWindows: \(\) => appWindows\(\)/);
+});
+
+test("main hands the talk wiring its speech sinks, this computer's own server and window, and closes it first on quit", () => {
+ assert.match(main, /const talk = installTalk\(\{ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions\.appleSpeech,\s*speech: \{ start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy \},/);
+ assert.match(main, /packaged: app\.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog \}\);/);
+ assert.match(main, /talk\.start\(\{ globalShortcut, screen, prefs: desktopPrefs, remote: \(\) => Boolean\(desktopRemoteAccess\), away: \(\) => homeWindow\.current\(\)\.kind !== "computer", starting: \(\) => !serverReady, localRequest: localServerRequest, dataDir: \(\) => runningDataDir \}\);/);
+ assert.match(main, /app\.on\("before-quit", \(e\) => \{\s*talk\.close\(\);/);
+ assert.doesNotMatch(main, /ipcMain\.handle\("(?:speech|talk-shortcut|call):/);
+});
+
+test("main tells the talk wiring when home changes and which skin the app painted, and counts a talk ask as busy for a quiet update", () => {
+ assert.match(main, /const homeWindow = createHomeWindow\(\{[^]*?rehomed: \(\) => talk\.homeChanged\(\),[^]*?\}\);\ninstallHomeWindowIpc/);
+ assert.match(main, /ipcMain\.handle\("desktop:skin", \(event, skin\) => \{\s*if \(!isKnownSkin\(skin\)\) return false;\s*if \(chromeRail\.owns\(event\)\) return true;\s*try \{\s*talk\.skin\(skin\);/);
+ assert.match(main, /busy: \(\) => \(oneHome\.oneHome\.busy\(\) && "move"\) \|\| \(computerSharing\?\.busy\(\) && "lending"\) \|\| \(talk\.busy\(\) && "talk"\) \|\|/);
+});
+
+test("the talk bridge keys stay off other servers' pages; a call can be reported from My Cloud's page", () => {
+ const list = name => preload.match(new RegExp(`const ${name} = (?:new Set\\()?\\[([^\\]]*)\\]`))[1];
+ assert.doesNotMatch(list("REMOTE_SAFE"), /talkShortcut|callActive/);
+ assert.match(list("HOME_PAGE"), /"callActive"/);
+ assert.doesNotMatch(list("HOME_PAGE"), /talkShortcut/);
+});
+
+test("every microphone channel answers only this computer's page; a call can be reported from My Cloud's page too", () => {
+ const { guards, handlers } = harness();
+ assert.deepEqual(Object.fromEntries(guards), {
+ "speech:start": "localOnly", "speech:stop": "localOnly", "speech:finish": "localOnly",
+ "talk-shortcut:state": "localOnly", "talk-shortcut:set": "localOnly", "call:active": "localOrHome",
+ });
+ assert.deepEqual([...handlers.keys()], [...guards.keys()]);
+});
+
+test("a page's speech stop and finish name that page's own window, so they touch only the session it started", () => {
+ const h = harness();
+ const page = h.page("page"), other = h.page("other");
+ h.handle("speech:start", { sender: page.webContents }, { endpointMs: 900 });
+ h.handle("speech:start", { sender: {} });
+ h.handle("speech:stop", { sender: other.webContents });
+ h.handle("speech:finish", { sender: page.webContents });
+ h.handle("speech:stop", { sender: page.webContents });
+ h.handle("speech:stop", { sender: {} });
+ assert.deepEqual(h.started.map(([win, options]) => [win.name, options]), [["page", { endpointMs: 900 }]]);
+ assert.deepEqual(names(h.stopped), ["other", "page", null]);
+ assert.deepEqual(names(h.finished), ["page"]);
+
+ const elsewhere = harness({ appleSpeech: false });
+ const win = elsewhere.page("page");
+ elsewhere.handle("speech:start", { sender: win.webContents });
+ elsewhere.handle("speech:stop", { sender: win.webContents });
+ elsewhere.handle("speech:finish", { sender: win.webContents });
+ assert.deepEqual(win.webContents.sent, [["speech:end", { code: 2, reason: "unsupported-platform" }]]);
+ assert.deepEqual([elsewhere.started, elsewhere.stopped, elsewhere.finished], [[], [], []]);
+});
+
+test("the shortcut is offered only with Apple speech, on a desktop that is not a remote client of another computer", () => {
+ for (const options of [{ appleSpeech: false }, { remote: true }]) {
+ const h = harness(options);
+ h.start();
+ assert.equal(h.handle("talk-shortcut:state", {}).available, false);
+ assert.deepEqual([...h.registered.keys()], []);
+ }
+ const h = harness();
+ h.start();
+ assert.equal(h.handle("talk-shortcut:state", {}).available, true);
+ assert.deepEqual([...h.registered.keys()], ["Control+Alt+Space"]);
+});
+
+test("before the shortcut is set up its setting says unavailable; afterwards a change passes on only what it understands", () => {
+ const h = harness();
+ assert.equal(h.handle("talk-shortcut:state", {}), TALK_SHORTCUT_UNAVAILABLE);
+ assert.equal(h.handle("talk-shortcut:set", {}, { enabled: false }), TALK_SHORTCUT_UNAVAILABLE);
+ h.start();
+ const shown = state => ({ enabled: state.enabled, key: state.key, taken: state.taken });
+ assert.deepEqual(shown(h.handle("talk-shortcut:set", {}, { enabled: "no", key: 7, extra: 1 })), { enabled: true, key: "ctrl-opt-space", taken: false });
+ assert.deepEqual(shown(h.handle("talk-shortcut:set", {}, { enabled: false })), { enabled: false, key: "ctrl-opt-space", taken: false });
+ assert.deepEqual([...h.registered.keys()], []);
+ h.handle("talk-shortcut:set", {}, { enabled: true, key: "ctrl-shift-space" });
+ assert.deepEqual([...h.registered.keys()], ["Control+Shift+Space"]);
+ h.talk.close();
+ assert.deepEqual([...h.registered.keys()], [], "quitting lets the key go");
+});
+
+test("a press listens until the key's modifiers are let go, and asks this computer's own server; in development, the dev server's proxy", () => {
+ const built = harness();
+ built.start();
+ built.press();
+ assert.equal(typeof built.started[0][0].transcript, "function", "the box's own speech sink, not a window");
+ assert.deepEqual(built.started.map(([, options]) => options), [{ finishOnRelease: ["control", "option"] }]);
+ assert.deepEqual(built.requests, [["local", "/api/bots?messages=0"]]);
+ built.talk.close();
+
+ const dev = harness({ packaged: false });
+ dev.start();
+ dev.press();
+ assert.deepEqual(dev.requests, [["dev", "http://127.0.0.1:5199/api/bots?messages=0"]]);
+ dev.talk.close();
+});
+
+test("a call or composer dictation holding the microphone keeps a press from listening", () => {
+ const h = harness();
+ h.start();
+ const page = new EventEmitter();
+ h.handle("call:active", { sender: page }, true);
+ h.press();
+ assert.equal(h.started.length, 0);
+ h.handle("call:active", { sender: page }, "yes");
+ h.press();
+ assert.equal(h.started.length, 1);
+ h.talk.close();
+
+ const dictating = harness();
+ dictating.busy = true;
+ dictating.start();
+ dictating.press();
+ assert.equal(dictating.started.length, 0);
+ dictating.talk.close();
+});
+
+test("a talk shortcut that cannot be set up is logged, says unavailable, and startup goes on", () => {
+ const h = harness({ register: () => { throw new Error("no hotkeys"); } });
+ assert.doesNotThrow(() => h.start());
+ assert.deepEqual(h.log, ["talk shortcut unavailable: no hotkeys"]);
+ assert.equal(h.handle("talk-shortcut:state", {}), TALK_SHORTCUT_UNAVAILABLE);
+ assert.doesNotThrow(() => h.talk.close());
+});
+
+test("a press, an open or a dismiss that throws is logged, never thrown at Electron", () => {
+ const h = harness();
+ h.start();
+ h.fail.busy = "busy broke";
+ h.press();
+ h.fail.busy = null;
+ h.press();
+ h.fail.reveal = "reveal broke";
+ h.click("open");
+ h.fail.reveal = null;
+ h.press();
+ h.fail.stop = "stop broke";
+ h.click("dismiss");
+ h.fail.stop = null;
+ assert.deepEqual(h.log, ["talk press failed: busy broke", "talk open failed: reveal broke", "talk dismiss failed: stop broke"]);
+ h.talk.close();
+});
+
+test("clicking the box opens its chat by a link with both ids escaped, or else just shows MausBot", async () => {
+ const h = harness({ serve: route => {
+ if (route === "/api/bots?messages=0") return json({ bots: [{ id: "b?1&x", defaultBot: {}, tasks: [] }] });
+ if (route === "/api/bots/b%3F1%26x/tasks") return json({ task: { threadId: "t 1/x" } });
+ return undefined;
+ } });
+ h.start();
+ h.press();
+ h.click("open");
+ assert.equal(h.reveals, 1);
+ assert.deepEqual(h.links, []);
+ h.press();
+ await settle();
+ const [sink] = h.started.at(-1);
+ sink.transcript({ text: "what's on today" });
+ sink.end({ code: 0, reason: "completed" });
+ h.click("open");
+ assert.deepEqual(h.links, ["openmausbot://thread/t%201%2Fx?bot=b%3F1%26x"]);
+ h.talk.close();
+});
+
+test("while home is My Cloud or this computer's copy is frozen the shortcut is unavailable and the key free; home here again takes it back", () => {
+ const h = harness();
+ h.away = true;
+ h.start();
+ assert.equal(h.handle("talk-shortcut:state", {}).available, false);
+ assert.deepEqual([...h.registered.keys()], []);
+ assert.equal(h.handle("talk-shortcut:set", {}, { enabled: false }).available, false, "a change does nothing meanwhile");
+ h.away = false;
+ h.talk.homeChanged();
+ assert.equal(h.handle("talk-shortcut:state", {}).available, true);
+ assert.deepEqual([...h.registered.keys()], ["Control+Alt+Space"]);
+ h.away = true;
+ h.talk.homeChanged();
+ assert.deepEqual([...h.registered.keys()], []);
+ h.fail.away = "home unknown";
+ assert.doesNotThrow(() => h.talk.homeChanged());
+ assert.deepEqual(h.log, ["talk home change failed: home unknown"]);
+ const early = harness();
+ assert.doesNotThrow(() => early.talk.homeChanged(), "before start");
+ h.talk.close();
+});
+
+test("a press while this computer's server is still starting says so", async () => {
+ const h = harness({ serve: route => (route === "/api/bots?messages=0" ? Promise.reject(new Error("not running")) : undefined) });
+ h.starting = true;
+ h.start();
+ h.press();
+ await settle();
+ assert.deepEqual((await h.painted()).at(-1), { state: "error", text: "MausBot is still starting. Try again in a moment." });
+ h.talk.close();
+});
+
+test("the box takes the light or dark of the skin the app painted last, before or after it opens", async () => {
+ const h = harness();
+ h.talk.skin("meadow");
+ h.start();
+ h.press();
+ assert.deepEqual((await h.painted()).at(-1), { state: "listening", text: "", theme: "light" });
+ h.talk.skin("midnight");
+ await settle();
+ assert.deepEqual((await h.painted()).at(-1), { state: "listening", text: "", theme: "dark" });
+ h.talk.skin("no-such-skin");
+ h.talk.skin(undefined);
+ await settle();
+ assert.equal((await h.painted()).at(-1).theme, "dark");
+ h.talk.close();
+});
+
+test("busy while a talk ask is under way, never before the shortcut is set up", () => {
+ const h = harness();
+ assert.equal(h.talk.busy(), false);
+ h.start();
+ assert.equal(h.talk.busy(), false);
+ h.press();
+ assert.equal(h.talk.busy(), true);
+ h.click("dismiss");
+ assert.equal(h.talk.busy(), false);
+ h.talk.close();
+});
+
+test("quitting while listening logs a failure to stop speech and still lets the key go", () => {
+ const h = harness();
+ h.start();
+ h.press();
+ h.fail.stop = "stop broke";
+ assert.doesNotThrow(() => h.talk.close());
+ assert.deepEqual(h.log, ["talk close failed: stop broke"]);
+ assert.deepEqual([...h.registered.keys()], []);
+});
diff --git a/electron/talk-panel-preload.cjs b/electron/talk-panel-preload.cjs
new file mode 100644
index 0000000000..6e50afb78a
--- /dev/null
+++ b/electron/talk-panel-preload.cjs
@@ -0,0 +1,6 @@
+const { contextBridge, ipcRenderer } = require("electron");
+
+contextBridge.exposeInMainWorld("talk", {
+ open: () => ipcRenderer.send("talk-panel:open"),
+ dismiss: () => ipcRenderer.send("talk-panel:dismiss"),
+});
diff --git a/electron/talk-panel.d.mts b/electron/talk-panel.d.mts
new file mode 100644
index 0000000000..457631fb78
--- /dev/null
+++ b/electron/talk-panel.d.mts
@@ -0,0 +1,22 @@
+export declare const TALK_PANEL: Readonly<{ width: 400; margin: 24; minHeight: 56; maxHeight: 240; fadeMs: 180 }>;
+export type TalkViewState = "listening" | "sending" | "thinking" | "reply" | "needs-you" | "still-working" | "error";
+export interface TalkView {
+ state: TalkViewState;
+ text: string;
+}
+export declare const TALK_LABELS: Readonly<Record<TalkViewState, string>>;
+export declare function talkPanelBounds(workArea: { x: number; y: number; width: number; height: number }, height: number): { x: number; y: number; width: number; height: number };
+export declare function replyPreview(text: string, limit?: number): string;
+export declare function talkPanelHtml(iconBase64: string): string;
+export declare function isTalkPanel(win: unknown): boolean;
+export type TalkTheme = "light" | "dark";
+export declare function createTalkPanel(deps: {
+ BrowserWindow: new (options: Record<string, unknown>) => any;
+ screen: { getCursorScreenPoint(): { x: number; y: number }; getDisplayNearestPoint(point: { x: number; y: number }): { workArea: { x: number; y: number; width: number; height: number } } };
+ nativeImage: { createFromPath(path: string): { isEmpty(): boolean; resize(options: { width: number; height: number; quality?: string }): { toPNG(): Buffer } } };
+ iconPath: string;
+ onOpen: () => void;
+ onDismiss: () => void;
+ /** The app's skin as last painted; null follows macOS's appearance. */
+ theme?: TalkTheme | null;
+}): { render(view: TalkView): void; setTheme(theme: TalkTheme | null): void; close(): void; hovered(): boolean };
diff --git a/electron/talk-panel.mjs b/electron/talk-panel.mjs
new file mode 100644
index 0000000000..469aa083c8
--- /dev/null
+++ b/electron/talk-panel.mjs
@@ -0,0 +1,217 @@
+import { fileURLToPath } from "node:url";
+
+export const TALK_PANEL = Object.freeze({ width: 400, margin: 24, minHeight: 56, maxHeight: 240, fadeMs: 180 });
+const MASCOT_PX = 28;
+/** Lines of 13 px text at 1.4 that fit the tallest box with its label and padding. */
+const TEXT_LINES = 10;
+const LIGHT = "color-scheme:light;--panel:#f7f7f7f5;--border:#0000001a;--ink:#0d0d0d;--ink2:#444444;--accent:#0b62c4;--warning:#8a5a00;--danger:#c02b3a;--hover:#0000000d";
+
+export const TALK_LABELS = Object.freeze({
+ listening: "Listening…",
+ sending: "Sending to MausBot…",
+ thinking: "MausBot is thinking…",
+ reply: "MausBot",
+ "needs-you": "MausBot needs you · Open chat",
+ "still-working": "Still working · Open chat",
+ error: "",
+});
+
+const panels = new WeakSet();
+
+export function isTalkPanel(win) {
+ return panels.has(win);
+}
+
+export function talkPanelBounds(workArea, height) {
+ const h = Math.min(TALK_PANEL.maxHeight, Math.max(TALK_PANEL.minHeight, Math.round(height)));
+ return {
+ x: Math.round(workArea.x + (workArea.width - TALK_PANEL.width) / 2),
+ y: Math.round(workArea.y + workArea.height - TALK_PANEL.margin - h),
+ width: TALK_PANEL.width,
+ height: h,
+ };
+}
+
+export function replyPreview(text, limit = 400) {
+ const plain = String(text ?? "")
+ .slice(0, limit * 4)
+ .replace(/```/g, " ")
+ .replace(/^[ \t]*#{1,6}[ \t]+/gm, "")
+ .replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm, "")
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
+ .replace(/(\*\*|__)(?=\S)(.+?)(?<=\S)\1/g, "$2")
+ .replace(/(^|[\s(])([*_])(?=\S)(.+?)(?<=\S)\2(?=$|[\s).,;:!?])/g, "$1$3")
+ .replace(/`/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+ if (plain.length <= limit) return plain;
+ const room = plain.slice(0, limit - 1);
+ const space = plain[limit - 1] === " " ? limit - 1 : room.lastIndexOf(" ");
+ return `${(space > 0 ? plain.slice(0, space) : room).trimEnd()}…`;
+}
+
+export function talkPanelHtml(iconBase64) {
+ const labels = JSON.stringify(TALK_LABELS);
+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>MausBot</title><style>
+:root{color-scheme:dark light}
+body{color-scheme:dark;--panel:#111111f5;--border:#ffffff16;--ink:#fcfcfc;--ink2:#fcfcfcbf;--accent:#1084fe;--warning:#ff9800;--danger:#ff5667;--hover:#ffffff14}
+body.light{${LIGHT}}
+@media (prefers-color-scheme: light){body:not(.dark){${LIGHT}}}
+*{box-sizing:border-box}html,body{margin:0;background:transparent;overflow:hidden;font:13px/1.4 -apple-system,BlinkMacSystemFont,system-ui,sans-serif;color:var(--ink);-webkit-user-select:none;user-select:none}
+body{opacity:0;transition:opacity 160ms ease}body.on{opacity:1}
+#card{position:relative;display:flex;gap:12px;align-items:flex-start;min-height:56px;padding:14px 40px 14px 14px;border:1px solid var(--border);border-radius:16px;background:var(--panel);cursor:pointer}
+#mascot{position:relative;flex:none;width:${MASCOT_PX}px;height:${MASCOT_PX}px}#mascot img{width:${MASCOT_PX}px;height:${MASCOT_PX}px;object-fit:contain;display:block;-webkit-user-drag:none}
+#mascot::after{content:"";position:absolute;inset:-3px;border-radius:50%;border:2px solid var(--accent);opacity:0;pointer-events:none}
+body.listening #mascot::after{animation:pulse 1.4s ease-out infinite}
+#body{flex:1;min-width:0;align-self:center}
+#label{font-weight:600}#label:empty{display:none}
+body.needs-you #label,body.still-working #label{color:var(--warning)}body.error #text{color:var(--danger)}
+#text{color:var(--ink2);overflow-wrap:anywhere;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${TEXT_LINES};overflow:hidden}#text:empty{display:none}#label:not(:empty)+#text{margin-top:2px}
+#close{position:absolute;top:8px;right:8px;width:24px;height:24px;display:grid;place-items:center;padding:0;border:0;border-radius:6px;background:transparent;color:var(--ink2);cursor:pointer}
+#close:hover{background:var(--hover);color:var(--ink)}#close svg{pointer-events:none}
+@keyframes pulse{from{transform:scale(.9);opacity:.8}to{transform:scale(1.35);opacity:0}}
+@media (prefers-reduced-motion: reduce){body{transition:none}body.listening #mascot::after{animation:none;opacity:.7}}
+</style></head><body><div id="card"><div id="mascot"><img src="data:image/png;base64,${iconBase64}" alt=""></div><div id="body"><div id="label"></div><div id="text" role="status"></div></div><button id="close" type="button" aria-label="Dismiss"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button></div><script>
+const LABELS=${labels};
+const card=document.getElementById("card"),label=document.getElementById("label"),text=document.getElementById("text");
+function render(view){
+ document.body.className=["on",view.state,view.theme].filter(Boolean).join(" ");
+ label.textContent=LABELS[view.state]||"";
+ text.textContent=view.text||(view.state==="listening"?"Let go to send":"");
+ return Math.ceil(card.getBoundingClientRect().height);
+}
+function fadeOut(){document.body.classList.remove("on")}
+card.addEventListener("click",()=>window.talk.open());
+document.getElementById("close").addEventListener("click",e=>{e.stopPropagation();window.talk.dismiss()});
+</script></body></html>`;
+}
+
+/** The mascot as a PNG at twice its CSS size, for Retina displays. */
+function mascotPng(nativeImage, iconPath) {
+ const icon = nativeImage.createFromPath(iconPath);
+ if (icon.isEmpty()) throw new Error(`no talk box icon at ${iconPath}`);
+ return icon.resize({ width: 2 * MASCOT_PX, height: 2 * MASCOT_PX, quality: "best" }).toPNG().toString("base64");
+}
+
+export function createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath, onOpen, onDismiss, theme: initialTheme = null }) {
+ let win = null;
+ let loaded = false;
+ let shown = false;
+ let view = null;
+ let latest = 0;
+ let page = null;
+ let area = null;
+ let theme = initialTheme;
+
+ const workArea = () => screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea;
+ const live = target => target && !target.isDestroyed();
+
+ function create() {
+ page ??= `data:text/html;charset=utf-8,${encodeURIComponent(talkPanelHtml(mascotPng(nativeImage, iconPath)))}`;
+ area = workArea();
+ const target = new BrowserWindow({
+ type: "panel",
+ ...talkPanelBounds(area, TALK_PANEL.minHeight),
+ frame: false,
+ transparent: true,
+ backgroundColor: "#00000000",
+ focusable: false,
+ skipTaskbar: true,
+ hasShadow: false,
+ resizable: false,
+ movable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ show: false,
+ // Electron/macOS: lets a click on an inactive window reach the page.
+ acceptFirstMouse: true,
+ hiddenInMissionControl: true,
+ webPreferences: {
+ contextIsolation: true,
+ sandbox: true,
+ nodeIntegration: false,
+ spellcheck: false,
+ preload: fileURLToPath(new URL("./talk-panel-preload.cjs", import.meta.url)),
+ },
+ });
+ panels.add(target);
+ target.excludedFromShownWindowsMenu = true;
+ target.setAlwaysOnTop(true, "screen-saver");
+ // Electron/macOS: skipTransformProcessType keeps the Dock icon.
+ target.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, skipTransformProcessType: true });
+ target.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
+ target.webContents.on("will-navigate", event => event.preventDefault());
+ target.webContents.on("did-finish-load", () => {
+ if (win !== target) return;
+ loaded = true;
+ if (view) repaint();
+ });
+ target.webContents.on("ipc-message", (_event, channel) => {
+ if (channel === "talk-panel:open") onOpen();
+ else if (channel === "talk-panel:dismiss") onDismiss();
+ });
+ target.on("closed", () => {
+ if (win === target) win = null;
+ });
+ target.loadURL(page).catch(() => {});
+ return target;
+ }
+
+ async function paint() {
+ const target = win;
+ const ticket = ++latest;
+ const payload = JSON.stringify({ state: view.state, text: replyPreview(view.text), ...(theme ? { theme } : {}) });
+ let height;
+ try {
+ height = await target.webContents.executeJavaScript(`render(${payload})`);
+ } catch {
+ return;
+ }
+ if (win !== target || ticket !== latest || !live(target)) return;
+ target.setBounds(talkPanelBounds(area, height));
+ if (!shown) {
+ shown = true;
+ target.showInactive();
+ }
+ }
+
+ const repaint = () => void paint().catch(() => {});
+
+ return {
+ render(next) {
+ view = next;
+ if (!win) {
+ win = create();
+ loaded = false;
+ shown = false;
+ }
+ if (loaded) repaint();
+ },
+ /** The app's skin, light or dark; the box follows macOS until a page of the app says which. */
+ setTheme(next) {
+ if (next === theme) return;
+ theme = next;
+ if (win && loaded && view) repaint();
+ },
+ close() {
+ const target = win;
+ if (!target) return;
+ win = null;
+ view = null;
+ if (!live(target)) return;
+ if (loaded) {
+ target.webContents.executeJavaScript("fadeOut()").catch(() => {});
+ setTimeout(() => { if (live(target)) target.destroy(); }, TALK_PANEL.fadeMs);
+ } else {
+ target.destroy();
+ }
+ },
+ hovered() {
+ if (!live(win)) return false;
+ const point = screen.getCursorScreenPoint();
+ const box = win.getBounds();
+ return point.x >= box.x && point.x < box.x + box.width && point.y >= box.y && point.y < box.y + box.height;
+ },
+ };
+}
diff --git a/electron/talk-panel.node-test.mjs b/electron/talk-panel.node-test.mjs
new file mode 100644
index 0000000000..10c8f1172c
--- /dev/null
+++ b/electron/talk-panel.node-test.mjs
@@ -0,0 +1,297 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import { existsSync, readFileSync } from "node:fs";
+import test, { mock } from "node:test";
+import { fileURLToPath } from "node:url";
+import { TALK_LABELS, TALK_PANEL, createTalkPanel, isTalkPanel, replyPreview, talkPanelBounds, talkPanelHtml } from "./talk-panel.mjs";
+
+const flush = () => new Promise(resolve => setImmediate(resolve));
+const pick = (object, keys) => Object.fromEntries(keys.map(key => [key, object[key]]));
+
+const APP_ICON = fileURLToPath(new URL("./resources/app-icon.png", import.meta.url));
+
+function harness({ cursor = { x: 100, y: 100 }, workArea = { x: 0, y: 25, width: 1440, height: 875 }, loadFails = false, boundsFail = false, iconPath = APP_ICON, theme } = {}) {
+ const made = [];
+ const resized = [];
+ const nativeImage = {
+ createFromPath: path => ({
+ isEmpty: () => !existsSync(path),
+ resize: size => { resized.push(size); return { toPNG: () => Buffer.from(`png ${size.width}x${size.height}`) }; },
+ }),
+ };
+ class FakeBrowserWindow {
+ constructor(options) {
+ const { x, y, width, height } = options;
+ Object.assign(this, { options, url: "", bounds: { x, y, width, height }, calls: [], destroyed: false, openHandler: null });
+ this.webContents = Object.assign(new EventEmitter(), {
+ scripts: [],
+ executeJavaScript: async script => {
+ this.webContents.scripts.push(script);
+ return 96;
+ },
+ setWindowOpenHandler: handler => { this.openHandler = handler; },
+ });
+ this.events = new EventEmitter();
+ made.push(this);
+ }
+ on(...args) { this.events.on(...args); }
+ setAlwaysOnTop(...args) { this.calls.push(["setAlwaysOnTop", ...args]); }
+ setVisibleOnAllWorkspaces(...args) { this.calls.push(["setVisibleOnAllWorkspaces", ...args]); }
+ setBounds(bounds) { if (boundsFail) throw new Error("bounds failed"); this.bounds = bounds; this.calls.push(["setBounds", bounds]); }
+ getBounds() { return this.bounds; }
+ show() { this.calls.push(["show"]); }
+ focus() { this.calls.push(["focus"]); }
+ showInactive() { this.calls.push(["showInactive"]); }
+ loadURL(url) { this.url = url; return loadFails ? Promise.reject(new Error("load failed")) : Promise.resolve(); }
+ isDestroyed() { return this.destroyed; }
+ destroy() { this.destroyed = true; }
+ }
+ const state = { cursor, workArea };
+ const screen = { getCursorScreenPoint: () => state.cursor, getDisplayNearestPoint: () => ({ workArea: state.workArea }) };
+ const opened = [];
+ const dismissed = [];
+ const panel = createTalkPanel({ BrowserWindow: FakeBrowserWindow, screen, nativeImage, iconPath, onOpen: () => opened.push(1), onDismiss: () => dismissed.push(1), theme });
+ return { panel, made, opened, dismissed, state, resized };
+}
+
+test("talkPanelBounds sits the box bottom-centre of the work area, clamped", () => {
+ assert.deepEqual(talkPanelBounds({ x: 0, y: 25, width: 1440, height: 875 }, 72), { x: 520, y: 804, width: 400, height: 72 });
+ assert.deepEqual(talkPanelBounds({ x: 1440, y: 0, width: 1920, height: 1050 }, 500), { x: 2200, y: 786, width: 400, height: 240 });
+ assert.equal(talkPanelBounds({ x: 0, y: 0, width: 800, height: 600 }, 10).height, 56);
+});
+
+test("the constants are frozen and carry the spec's values", () => {
+ assert.deepEqual(TALK_PANEL, { width: 400, margin: 24, minHeight: 56, maxHeight: 240, fadeMs: 180 });
+ assert.ok(Object.isFrozen(TALK_PANEL) && Object.isFrozen(TALK_LABELS));
+ assert.equal(TALK_LABELS["needs-you"], "MausBot needs you · Open chat");
+ assert.equal(TALK_LABELS["still-working"], "Still working · Open chat");
+ assert.equal(TALK_LABELS.error, "");
+});
+
+test("the box is a non-activating panel on every Space, shown without focus on the display under the pointer", async () => {
+ const { panel, made } = harness({ cursor: { x: 2000, y: 500 }, workArea: { x: 1440, y: 25, width: 1440, height: 875 } });
+ panel.render({ state: "listening", text: "" });
+ const win = made[0];
+ assert.deepEqual(pick(win.options, ["type", "focusable", "transparent", "frame", "skipTaskbar", "hasShadow", "resizable", "show", "acceptFirstMouse", "hiddenInMissionControl"]),
+ { type: "panel", focusable: false, transparent: true, frame: false, skipTaskbar: true, hasShadow: false, resizable: false, show: false, acceptFirstMouse: true, hiddenInMissionControl: true });
+ assert.deepEqual(win.calls.filter(c => c[0] !== "setBounds"), [["setAlwaysOnTop", true, "screen-saver"], ["setVisibleOnAllWorkspaces", true, { visibleOnFullScreen: true, skipTransformProcessType: true }]]);
+ assert.ok(win.url.startsWith("data:text/html"));
+ win.webContents.emit("did-finish-load");
+ await flush();
+ assert.match(win.webContents.scripts[0], /^render\(\{"state":"listening","text":""\}\)$/);
+ assert.deepEqual(win.bounds, { x: 1960, y: 780, width: 400, height: 96 });
+ assert.deepEqual(win.calls.map(c => c[0]).filter(n => ["show", "focus", "showInactive"].includes(n)), ["showInactive"]);
+});
+
+test("later renders resize without showing again, and use only the latest view", async () => {
+ const { panel, made } = harness();
+ panel.render({ state: "listening", text: "" });
+ panel.render({ state: "thinking", text: "" });
+ made[0].webContents.emit("did-finish-load");
+ await flush();
+ assert.equal(made[0].webContents.scripts.length, 1);
+ assert.match(made[0].webContents.scripts[0], /"state":"thinking"/);
+ panel.render({ state: "reply", text: "**Hi** there" });
+ await flush();
+ assert.match(made[0].webContents.scripts[1], /^render\(\{"state":"reply","text":"Hi there"\}\)$/);
+ assert.deepEqual(made[0].calls.filter(c => c[0] === "showInactive").length, 1);
+});
+
+test("the page shows reply text as plain text, never HTML", () => {
+ assert.equal(replyPreview("## Today\n\n- **Standup** at 10\n- [Lunch](https://x.test) with `Sam`"), "Today Standup at 10 Lunch with Sam");
+ assert.equal(replyPreview("<img src=x onerror=alert(1)>"), "<img src=x onerror=alert(1)>");
+ assert.equal(replyPreview("```js\nconst a_b = 1;\n```\nsnake_case and __bold__ and _it_"), "js const a_b = 1; snake_case and bold and it");
+ const cut = replyPreview("word ".repeat(120));
+ assert.ok(cut.length <= 400 && cut.endsWith("…") && !cut.endsWith(" …") && !cut.includes("wor…"));
+ const html = talkPanelHtml("AAAA");
+ assert.match(html, /default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"/);
+ assert.match(html, /textContent/);
+ assert.match(html, /prefers-color-scheme: light/);
+ assert.doesNotMatch(html, /innerHTML|insertAdjacentHTML|outerHTML|https?:\/\//);
+});
+
+test("the page's bridge is open and dismiss, and they count only from this box", async () => {
+ const preload = readFileSync(new URL("./talk-panel-preload.cjs", import.meta.url), "utf8");
+ assert.deepEqual([...preload.matchAll(/ipcRenderer\.(\w+)\("([^"]+)"/g)].map(m => [m[1], m[2]]), [["send", "talk-panel:open"], ["send", "talk-panel:dismiss"]]);
+ const { panel, made, opened, dismissed } = harness();
+ panel.render({ state: "reply", text: "Hi" });
+ made[0].webContents.emit("ipc-message", {}, "talk-panel:open");
+ made[0].webContents.emit("ipc-message", {}, "talk-panel:other");
+ made[0].webContents.emit("ipc-message", {}, "talk-panel:dismiss");
+ assert.deepEqual([opened.length, dismissed.length], [1, 1]);
+});
+
+test("navigation and new windows are refused", () => {
+ const { panel, made } = harness();
+ panel.render({ state: "reply", text: "Hi" });
+ const event = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } };
+ made[0].webContents.emit("will-navigate", event);
+ assert.equal(event.defaultPrevented, true);
+ assert.deepEqual(made[0].openHandler(), { action: "deny" });
+});
+
+test("close fades, then destroys; the next render makes a new box; hovered follows the pointer", async () => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ const { panel, made, state } = harness({ cursor: { x: 700, y: 850 } });
+ assert.equal(panel.hovered(), false);
+ panel.render({ state: "reply", text: "Hi" });
+ made[0].webContents.emit("did-finish-load");
+ await flush();
+ assert.deepEqual(made[0].bounds, { x: 520, y: 780, width: 400, height: 96 });
+ assert.equal(panel.hovered(), true);
+ state.cursor = { x: 10, y: 10 };
+ assert.equal(panel.hovered(), false);
+ panel.close();
+ assert.equal(made[0].webContents.scripts.at(-1), "fadeOut()");
+ mock.timers.tick(179);
+ assert.equal(made[0].destroyed, false);
+ mock.timers.tick(1);
+ assert.equal(made[0].destroyed, true);
+ assert.equal(panel.hovered(), false);
+ panel.render({ state: "listening", text: "" });
+ assert.equal(made.length, 2);
+ } finally {
+ mock.timers.reset();
+ }
+});
+
+test("close destroys at once when the page never loaded", () => {
+ const { panel, made } = harness();
+ panel.render({ state: "listening", text: "" });
+ panel.close();
+ assert.equal(made[0].destroyed, true);
+});
+
+test("isTalkPanel tells the box from app windows", () => {
+ const { panel, made } = harness();
+ panel.render({ state: "listening", text: "" });
+ assert.equal(isTalkPanel(made[0]), true);
+ assert.equal(isTalkPanel({}), false);
+});
+
+test("a rejected page load is swallowed, not an unhandled rejection", async () => {
+ const unhandled = [];
+ const record = reason => unhandled.push(reason);
+ process.on("unhandledRejection", record);
+ try {
+ const { panel, made } = harness({ loadFails: true });
+ panel.render({ state: "listening", text: "" });
+ panel.close();
+ await flush();
+ await flush();
+ assert.equal(made.length, 1);
+ assert.deepEqual(unhandled, []);
+ } finally {
+ process.off("unhandledRejection", record);
+ }
+});
+
+test("an unreadable icon creates no window", () => {
+ const { panel, made } = harness({ iconPath: "/nonexistent/icon.png" });
+ assert.throws(() => panel.render({ state: "listening", text: "" }));
+ assert.equal(made.length, 0);
+});
+
+test("the box's security invariants are pinned", () => {
+ const { panel, made } = harness();
+ panel.render({ state: "listening", text: "" });
+ const { webPreferences } = made[0].options;
+ assert.deepEqual(pick(webPreferences, ["contextIsolation", "sandbox", "nodeIntegration"]), { contextIsolation: true, sandbox: true, nodeIntegration: false });
+ assert.ok(webPreferences.preload.endsWith("talk-panel-preload.cjs"));
+ assert.equal(made[0].excludedFromShownWindowsMenu, true);
+});
+
+test("a box destroyed outside close() is forgotten, so the next render makes a new one", async () => {
+ const { panel, made } = harness();
+ panel.render({ state: "listening", text: "" });
+ made[0].webContents.emit("did-finish-load");
+ await flush();
+ made[0].destroyed = true;
+ made[0].events.emit("closed");
+ assert.equal(panel.hovered(), false);
+ panel.render({ state: "thinking", text: "" });
+ assert.equal(made.length, 2);
+ assert.equal(made[0].webContents.scripts.length, 1);
+});
+
+test("a reply of wide characters is cut at whole lines, so the card's bottom edge stays inside the tallest box", () => {
+ const html = talkPanelHtml("AAAA");
+ assert.match(html, /#text\{[^}]*display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:10;overflow:hidden\}/);
+ assert.match(html, /font:13px\/1\.4 /);
+ assert.match(html, /padding:14px 40px 14px 14px;border:1px solid/);
+ assert.ok(28 + 2 + 2 + 11 * 18.2 <= TALK_PANEL.maxHeight, "label and ten lines of text fit the box");
+});
+
+test("replyPreview stays within the limit on pathological input", () => {
+ const out = replyPreview("**".repeat(200000) + " tail");
+ assert.ok(out.length <= 400);
+});
+
+test("the box stays on the display it opened on while it is up; the next box opens under the pointer", async () => {
+ const { panel, made, state } = harness();
+ panel.render({ state: "listening", text: "" });
+ state.cursor = { x: 2000, y: 500 };
+ state.workArea = { x: 1440, y: 25, width: 1440, height: 875 };
+ made[0].webContents.emit("did-finish-load");
+ await flush();
+ panel.render({ state: "reply", text: "Hi" });
+ await flush();
+ assert.deepEqual(made[0].bounds, { x: 520, y: 780, width: 400, height: 96 });
+ panel.close();
+ panel.render({ state: "listening", text: "" });
+ assert.deepEqual(made[1].options.x, 1960);
+});
+
+test("the mascot is inlined at 56 px, twice its 28 px size, never the full-size app icon", () => {
+ const { panel, made, resized } = harness();
+ panel.render({ state: "listening", text: "" });
+ assert.deepEqual(resized, [{ width: 56, height: 56, quality: "best" }]);
+ const page = decodeURIComponent(made[0].url);
+ assert.ok(page.includes(`data:image/png;base64,${Buffer.from("png 56x56").toString("base64")}`));
+ assert.ok(!page.includes(readFileSync(APP_ICON).toString("base64").slice(0, 200)));
+ panel.close();
+ panel.render({ state: "listening", text: "" });
+ assert.equal(resized.length, 1, "made once, then reused");
+});
+
+test("the box takes the app's skin, light or dark, over macOS's appearance, and repaints when it changes", async () => {
+ const { panel, made } = harness({ theme: "light" });
+ panel.render({ state: "reply", text: "Hi" });
+ made[0].webContents.emit("did-finish-load");
+ await flush();
+ assert.equal(made[0].webContents.scripts.at(-1), 'render({"state":"reply","text":"Hi","theme":"light"})');
+ panel.setTheme("dark");
+ await flush();
+ assert.equal(made[0].webContents.scripts.at(-1), 'render({"state":"reply","text":"Hi","theme":"dark"})');
+ panel.setTheme("dark");
+ await flush();
+ assert.equal(made[0].webContents.scripts.length, 2, "the same skin again repaints nothing");
+ panel.close();
+ panel.setTheme("light");
+ assert.equal(made[0].webContents.scripts.at(-1), "fadeOut()", "a closed box is not painted");
+
+ const html = talkPanelHtml("AAAA");
+ assert.match(html, /body\{color-scheme:dark;--panel:#111111f5;/);
+ assert.match(html, /body\.light\{color-scheme:light;--panel:#f7f7f7f5;/);
+ assert.match(html, /@media \(prefers-color-scheme: light\)\{body:not\(\.dark\)\{color-scheme:light;--panel:#f7f7f7f5;/);
+ assert.match(html, /document\.body\.className=\["on",view\.state,view\.theme\]/);
+});
+
+test("a box that fails to place itself is not an unhandled rejection", async () => {
+ const unhandled = [];
+ const record = reason => unhandled.push(reason);
+ process.on("unhandledRejection", record);
+ try {
+ const { panel, made } = harness({ boundsFail: true });
+ panel.render({ state: "listening", text: "" });
+ made[0].webContents.emit("did-finish-load");
+ await flush();
+ panel.render({ state: "thinking", text: "" });
+ await flush();
+ await flush();
+ assert.deepEqual(unhandled, []);
+ } finally {
+ process.off("unhandledRejection", record);
+ }
+});
diff --git a/electron/talk-server.d.mts b/electron/talk-server.d.mts
new file mode 100644
index 0000000000..545db76ac8
--- /dev/null
+++ b/electron/talk-server.d.mts
@@ -0,0 +1,41 @@
+import type { DesktopPrefs } from "./desktop-prefs.mjs";
+
+export declare const QUICK_ASKS_TITLE: "Quick asks";
+/** `starting`: this computer's server is not up yet; `moved`: its bots moved to My Cloud, so it takes no asks. */
+export type TalkServerErrorCode = "server-down" | "starting" | "no-mausbot" | "refused" | "moved" | "lost";
+export declare class TalkServerError extends Error {
+ constructor(code: TalkServerErrorCode);
+ readonly code: TalkServerErrorCode;
+}
+/** MausBot's Quick asks chat on this computer's server. */
+export interface TalkChat { botId: string; threadId: string }
+/** `text` is the reply as last shown: the streamed words, then the finished message. */
+export type TalkUpdate =
+ | { kind: "thinking" }
+ | { kind: "reply"; text: string }
+ | { kind: "needs-you" }
+ | { kind: "done"; ok: boolean; text: string };
+export interface TalkBot { id: string; defaultBot?: { person?: string }; chiefOfStaff?: boolean; hidden?: boolean }
+/** This computer's own MausBot (not a Team Cloud member's), else the Chief of Staff. */
+export declare function findMausBot<T extends TalkBot>(bots: readonly T[]): T | null;
+/** Server-sent events whose data is JSON; `signal` cancels the stream. */
+export declare function readFrames(body: ReadableStream<Uint8Array>, onFrame: (frame: object) => void, signal?: AbortSignal): Promise<void>;
+/** Follows the frames of one ask: from its own echoed message, through the turn that answers it. That turn is the
+ * running one when the ask was steered into it, else the first turn not already under way before the echo; frames of
+ * any other turn are ignored, so a box never shows another ask's reply. */
+export declare function createReplyTracker(options: { threadId: string; sendId: string }): (frame: object) => TalkUpdate | null;
+export declare function createTalkServer(options: {
+ /** A request to this computer's own server, never a Cloud or team one. */
+ request: (route: string, init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<Response>;
+ prefs: Pick<DesktopPrefs, "quickAsksChat" | "setQuickAsksChat">;
+ /** Which server the saved Quick asks chat belongs to. */
+ serverKey: () => string;
+ /** This computer's server is on its way up, so a request that can't reach it says "starting". */
+ starting?: () => boolean;
+}): {
+ /** Rejects with TalkServerError "server-down", "starting", "no-mausbot", "refused" or "moved". One call runs at a
+ * time; a call while one runs gets the same promise. */
+ prepare(): Promise<TalkChat>;
+ /** Rejects with TalkServerError "server-down", "starting", "refused", "moved" or "lost", or with `signal.reason`. */
+ ask(input: { chat: TalkChat; text: string; sendId: string; signal: AbortSignal; onUpdate: (update: TalkUpdate) => void }): Promise<"done" | "needs-you" | "failed">;
+};
diff --git a/electron/talk-server.mjs b/electron/talk-server.mjs
new file mode 100644
index 0000000000..1f1e99e88a
--- /dev/null
+++ b/electron/talk-server.mjs
@@ -0,0 +1,183 @@
+export const QUICK_ASKS_TITLE = "Quick asks";
+
+export class TalkServerError extends Error {
+ constructor(code) {
+ super(code);
+ this.name = "TalkServerError";
+ this.code = code;
+ }
+}
+
+export function findMausBot(bots) {
+ return bots.find(bot => bot.defaultBot && !bot.defaultBot.person?.trim())
+ ?? bots.find(bot => bot.chiefOfStaff && !bot.hidden)
+ ?? null;
+}
+
+export async function readFrames(body, onFrame, signal) {
+ const reader = body.getReader();
+ const cancel = () => void reader.cancel(signal.reason).catch(() => {});
+ if (signal?.aborted) cancel();
+ else signal?.addEventListener("abort", cancel, { once: true });
+ const decoder = new TextDecoder();
+ let partial = "", data = [];
+ const dispatch = () => {
+ if (!data.length) return;
+ let frame = null;
+ try { frame = JSON.parse(data.join("\n")); } catch {}
+ data = [];
+ if (frame && typeof frame === "object") onFrame(frame);
+ };
+ try {
+ while (!signal?.aborted) {
+ const { done, value } = await reader.read();
+ if (done) return;
+ const lines = (partial + decoder.decode(value, { stream: true })).split("\n");
+ partial = lines.pop();
+ for (const raw of lines) {
+ if (signal?.aborted) return;
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
+ if (line === "") dispatch();
+ else if (line.startsWith("data:")) data.push(line.slice(line.startsWith("data: ") ? 6 : 5));
+ }
+ }
+ } finally {
+ signal?.removeEventListener("abort", cancel);
+ }
+}
+
+const waitingCard = card => !(card?.answered || card?.dismissed || card?.expired);
+
+export function createReplyTracker({ threadId, sendId }) {
+ const earlierTurns = new Set();
+ let echoed = false, steered = false, turnId = null;
+ let itemId, streamed = "", shown = "";
+ const show = text => { shown = text; return { kind: "reply", text }; };
+ const answersThisAsk = frameTurn => {
+ if (frameTurn === undefined) return true;
+ if (turnId !== null) return frameTurn === turnId;
+ if (!steered && earlierTurns.has(frameTurn)) return false;
+ turnId = frameTurn;
+ return true;
+ };
+ return frame => {
+ const event = frame.kind === "runtime" ? frame.event : undefined;
+ const message = frame.kind === "message" ? frame.message : undefined;
+ if ((event ? event.threadId : message ? frame.threadId : undefined) !== threadId) return null;
+ const frameTurn = (event ?? message).turnId ?? undefined;
+ if (!echoed) {
+ if (message?.role === "user" && message.sendId === sendId) {
+ echoed = true;
+ steered = message.steered === true;
+ return { kind: "thinking" };
+ }
+ if (frameTurn !== undefined) earlierTurns.add(frameTurn);
+ return null;
+ }
+ if (!answersThisAsk(frameTurn)) return null;
+ if (event) {
+ if (event.type === "content.delta" && event.streamKind === "assistant_text") {
+ if (event.itemId !== itemId) { itemId = event.itemId; streamed = ""; }
+ streamed += event.delta;
+ return show(streamed);
+ }
+ if (event.type === "item.completed" && event.itemType === "assistant_text") return show(event.text);
+ if (event.type === "request.opened") return { kind: "needs-you" };
+ if (event.type === "turn.completed") return { kind: "done", ok: event.ok, text: shown };
+ return null;
+ }
+ if (message.role !== "bot") return null;
+ if (message.kind === "text") return show(message.text ?? "");
+ if (message.kind === "options" && waitingCard(message.card)) return { kind: "needs-you" };
+ return null;
+ };
+}
+
+const JSON_HEADERS = { "content-type": "application/json" };
+
+/** A server whose bots moved to My Cloud refuses every change with 409 `{ code: "moved" }`. */
+async function refusal(response) {
+ const body = response.status === 409 ? await response.json().catch(() => null) : null;
+ if (!body) void response.body?.cancel().catch(() => {});
+ return new TalkServerError(body?.code === "moved" ? "moved" : "refused");
+}
+
+export function createTalkServer({ request, prefs, serverKey, starting = () => false }) {
+ let preparing = null;
+ const down = () => new TalkServerError(starting() ? "starting" : "server-down");
+
+ const quickAsksChat = async () => {
+ const listing = await request("/api/bots?messages=0").catch(() => null);
+ const bots = listing?.ok ? (await listing.json().catch(() => null))?.bots : null;
+ if (!Array.isArray(bots)) throw down();
+ const bot = findMausBot(bots);
+ if (!bot) throw new TalkServerError("no-mausbot");
+ const server = serverKey();
+ const saved = prefs.quickAsksChat(server);
+ if (saved?.botId === bot.id && bot.tasks?.some(task => task.threadId === saved.threadId)) return saved;
+ const made = await request(`/api/bots/${encodeURIComponent(bot.id)}/tasks`, {
+ method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ title: QUICK_ASKS_TITLE, select: false }),
+ }).catch(() => { throw down(); });
+ if (!made.ok) throw await refusal(made);
+ const threadId = (await made.json().catch(() => null))?.task?.threadId;
+ if (typeof threadId !== "string") throw new TalkServerError("refused");
+ const chat = { botId: bot.id, threadId };
+ prefs.setQuickAsksChat(server, chat);
+ return chat;
+ };
+
+ const ask = ({ chat, text, sendId, signal, onUpdate }) => new Promise((resolve, reject) => {
+ const reading = new AbortController();
+ const track = createReplyTracker({ threadId: chat.threadId, sendId });
+ let sent = false, settled = false;
+ const settle = (finish, value) => {
+ if (settled) return;
+ settled = true;
+ signal.removeEventListener("abort", aborted);
+ reading.abort();
+ finish(value);
+ };
+ const aborted = () => settle(reject, signal.reason);
+ if (signal.aborted) return aborted();
+ signal.addEventListener("abort", aborted, { once: true });
+
+ const send = () => request(`/api/bots/${encodeURIComponent(chat.botId)}/messages`, {
+ method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ text, threadId: chat.threadId, sendId }),
+ }).then(
+ async response => {
+ if (response.ok) void response.body?.cancel().catch(() => {});
+ else settle(reject, await refusal(response));
+ },
+ () => settle(reject, down()),
+ );
+ const onFrame = frame => {
+ if (settled) return;
+ if (!sent) {
+ if (frame.kind !== "hello") return;
+ sent = true;
+ void send();
+ return;
+ }
+ const update = track(frame);
+ if (!update) return;
+ onUpdate(update);
+ if (update.kind === "done") settle(resolve, !update.ok && !update.text ? "failed" : "done");
+ else if (update.kind === "needs-you") settle(resolve, "needs-you");
+ };
+ const ended = () => settle(reject, sent ? new TalkServerError("lost") : down());
+ request("/api/events?screens=off", { signal: reading.signal })
+ .then(response => {
+ if (response.ok && response.body) return readFrames(response.body, onFrame, reading.signal);
+ void response.body?.cancel().catch(() => {});
+ })
+ .then(ended, ended);
+ });
+
+ return {
+ prepare() {
+ preparing ??= quickAsksChat().finally(() => { preparing = null; });
+ return preparing;
+ },
+ ask,
+ };
+}
diff --git a/electron/talk-server.node-test.mjs b/electron/talk-server.node-test.mjs
new file mode 100644
index 0000000000..1aa199e920
--- /dev/null
+++ b/electron/talk-server.node-test.mjs
@@ -0,0 +1,230 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createReplyTracker, createTalkServer, findMausBot, readFrames } from "./talk-server.mjs";
+
+const flush = () => new Promise(resolve => setImmediate(resolve));
+const turn = turnId => (turnId ? { turnId } : {});
+const userMessage = (threadId, sendId, fields = {}) => ({ kind: "message", threadId, message: { id: `u-${sendId}`, role: "user", kind: "text", text: "asked", sendId, ...fields } });
+const delta = (threadId, itemId, text, turnId) => ({ kind: "runtime", event: { type: "content.delta", streamKind: "assistant_text", threadId, itemId, delta: text, ...turn(turnId) } });
+const itemDone = (threadId, itemId, text, turnId) => ({ kind: "runtime", event: { type: "item.completed", itemType: "assistant_text", threadId, itemId, text, ...turn(turnId) } });
+const botText = (threadId, text, turnId) => ({ kind: "message", threadId, message: { id: `b-${text}`, role: "bot", kind: "text", text, ...turn(turnId) } });
+const card = (threadId, cardFields) => ({ kind: "message", threadId, message: { id: "card", role: "bot", kind: "options", card: { question: "Allow?", options: ["Allow", "Deny"], ...cardFields } } });
+const opened = threadId => ({ kind: "runtime", event: { type: "request.opened", threadId, requestType: "permission", tool: "Bash", summary: "ls" } });
+const completed = (threadId, ok, turnId) => ({ kind: "runtime", event: { type: "turn.completed", threadId, ok, ...turn(turnId) } });
+const HELLO = { kind: "hello", cursor: "s:1", resumed: false };
+const CHAT = { botId: "m", threadId: "t1" };
+
+const MOVED = { error: "This bot lives on My Cloud now.", code: "moved" };
+
+function fakeServer({ bots, saved = null, sendStatus = 202, sendBody = { ok: true }, made = null, starting }) {
+ const encoder = new TextEncoder();
+ const server = { calls: [], saves: [], events: null, listing: { down: false, status: 200 } };
+ const request = async (route, init = {}) => {
+ const method = init.method ?? "GET";
+ server.calls.push([method, route, init.body === undefined ? undefined : JSON.parse(init.body)]);
+ if (method === "GET" && route === "/api/bots?messages=0") {
+ if (server.listing.down) throw new TypeError("fetch failed");
+ return Response.json({ bots }, { status: server.listing.status });
+ }
+ if (method === "POST" && /^\/api\/bots\/[\w-]+\/tasks$/.test(route)) return made ? Response.json(made.body, { status: made.status }) : Response.json({ task: { threadId: "t-new", title: "Quick asks" } }, { status: 201 });
+ if (method === "GET" && route === "/api/events?screens=off") {
+ let stream;
+ const body = new ReadableStream({ start: controller => { stream = controller; }, cancel: () => { server.events.cancelled = true; } });
+ server.events = { cancelled: false, push: frame => stream.enqueue(encoder.encode(`data: ${JSON.stringify(frame)}\n\n`)), end: () => stream.close() };
+ return new Response(body, { headers: { "content-type": "text/event-stream" } });
+ }
+ if (method === "POST" && /^\/api\/bots\/[\w-]+\/messages$/.test(route)) return Response.json(sendBody, { status: sendStatus });
+ return new Response(null, { status: 404 });
+ };
+ server.talk = createTalkServer({ request, serverKey: () => "server-a", starting, prefs: { quickAsksChat: () => saved, setQuickAsksChat: (key, chat) => server.saves.push([key, chat]) } });
+ return server;
+}
+
+const asking = (server, { signal = new AbortController().signal, onUpdate = () => {} } = {}) =>
+ server.talk.ask({ chat: CHAT, text: "hi", sendId: "s1", signal, onUpdate });
+
+test("findMausBot picks this computer's MausBot, else the Chief of Staff", () => {
+ const mine = { id: "m", defaultBot: {} }, member = { id: "p", defaultBot: { person: "[email protected]" } }, chief = { id: "c", chiefOfStaff: true };
+ assert.equal(findMausBot([member, chief, mine]).id, "m");
+ assert.equal(findMausBot([member, chief]).id, "c");
+ assert.equal(findMausBot([{ id: "x" }, { ...chief, hidden: true }]), null);
+});
+
+test("prepare reuses the saved Quick asks chat while MausBot still has it", async () => {
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [{ threadId: "t0" }, { threadId: "t1" }] }], saved: { botId: "m", threadId: "t1" } });
+ assert.deepEqual(await server.talk.prepare(), { botId: "m", threadId: "t1" });
+ assert.deepEqual(server.calls.map(([method]) => method), ["GET"]);
+ assert.deepEqual(server.saves, []);
+});
+
+test("prepare makes a Quick asks chat without selecting it when the saved one is gone, and keeps it", async () => {
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }], saved: { botId: "m", threadId: "t-gone" } });
+ assert.deepEqual(await server.talk.prepare(), { botId: "m", threadId: "t-new" });
+ assert.deepEqual(server.calls.at(-1), ["POST", "/api/bots/m/tasks", { title: "Quick asks", select: false }]);
+ assert.deepEqual(server.saves, [["server-a", { botId: "m", threadId: "t-new" }]]);
+});
+
+test("prepare makes a new chat when the saved one belongs to another bot", async () => {
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [{ threadId: "t1" }] }], saved: { botId: "old", threadId: "t1" } });
+ assert.deepEqual(await server.talk.prepare(), { botId: "m", threadId: "t-new" });
+});
+
+test("two prepares at once make one chat", async () => {
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }] });
+ const first = server.talk.prepare(), second = server.talk.prepare();
+ assert.equal(first, second);
+ assert.deepEqual(await Promise.all([first, second]), [{ botId: "m", threadId: "t-new" }, { botId: "m", threadId: "t-new" }]);
+ assert.equal(server.calls.filter(([method]) => method === "POST").length, 1);
+});
+
+test("prepare says why it cannot ask", async () => {
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }] });
+ server.listing.down = true;
+ await assert.rejects(server.talk.prepare(), { name: "TalkServerError", code: "server-down" });
+ server.listing = { down: false, status: 503 };
+ await assert.rejects(server.talk.prepare(), { code: "server-down" });
+ server.listing.status = 200;
+ assert.deepEqual(await server.talk.prepare(), { botId: "m", threadId: "t-new" });
+ await assert.rejects(fakeServer({ bots: [] }).talk.prepare(), { code: "no-mausbot" });
+ await assert.rejects(fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }], made: { status: 500, body: {} } }).talk.prepare(), { code: "refused" });
+});
+
+test("a server still on its way up says starting, not down", async () => {
+ let starting = true;
+ const server = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }], starting: () => starting });
+ server.listing.down = true;
+ await assert.rejects(server.talk.prepare(), { code: "starting" });
+ starting = false;
+ await assert.rejects(server.talk.prepare(), { code: "server-down" });
+});
+
+test("a computer whose bots moved to My Cloud says so, on making the chat and on sending", async () => {
+ const frozen = fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }], made: { status: 409, body: MOVED } });
+ await assert.rejects(frozen.talk.prepare(), { name: "TalkServerError", code: "moved" });
+ assert.deepEqual(frozen.saves, []);
+ await assert.rejects(fakeServer({ bots: [{ id: "m", defaultBot: {}, tasks: [] }], made: { status: 409, body: { code: "thread_busy" } } }).talk.prepare(), { code: "refused" });
+
+ const sending = fakeServer({ bots: [], sendStatus: 409, sendBody: MOVED });
+ const refusing = asking(sending);
+ await flush();
+ sending.events.push(HELLO);
+ await assert.rejects(refusing, { name: "TalkServerError", code: "moved" });
+ assert.equal(sending.events.cancelled, true);
+});
+
+test("the reply tracker follows only this ask", () => {
+ const track = createReplyTracker({ threadId: "t1", sendId: "s1" });
+ for (const early of [delta("t1", "i0", "old answer"), completed("t1", true), userMessage("t1", "s0"), userMessage("t2", "s1")]) assert.equal(track(early), null);
+ assert.deepEqual(track(userMessage("t1", "s1")), { kind: "thinking" });
+ assert.deepEqual(track(delta("t1", "i1", "Let me ")), { kind: "reply", text: "Let me " });
+ assert.deepEqual(track(delta("t1", "i1", "check")), { kind: "reply", text: "Let me check" });
+ assert.deepEqual(track(delta("t1", "i2", "You have")), { kind: "reply", text: "You have" });
+ assert.deepEqual(track(botText("t1", "You have two meetings.")), { kind: "reply", text: "You have two meetings." });
+ assert.equal(track(delta("t2", "i9", "elsewhere")), null);
+ assert.deepEqual(track(completed("t1", true)), { kind: "done", ok: true, text: "You have two meetings." });
+});
+
+test("an earlier turn's turn.completed after this ask's echo does not end the box", () => {
+ const track = createReplyTracker({ threadId: "t1", sendId: "s2" });
+ assert.equal(track(delta("t1", "i1", "The first answer", "turn-1")), null);
+ assert.deepEqual(track(userMessage("t1", "s2")), { kind: "thinking" });
+ assert.equal(track(delta("t1", "i1", " goes on", "turn-1")), null);
+ assert.equal(track(botText("t1", "The first answer goes on", "turn-1")), null);
+ assert.equal(track(completed("t1", true, "turn-1")), null);
+ assert.deepEqual(track(delta("t1", "i2", "The second", "turn-2")), { kind: "reply", text: "The second" });
+ assert.equal(track(delta("t1", "i1", " and more of the first", "turn-1")), null);
+ assert.deepEqual(track(itemDone("t1", "i2", "The second answer", "turn-2")), { kind: "reply", text: "The second answer" });
+ assert.deepEqual(track(completed("t1", true, "turn-2")), { kind: "done", ok: true, text: "The second answer" });
+});
+
+test("an ask steered into the running turn follows that turn to its end", () => {
+ const track = createReplyTracker({ threadId: "t1", sendId: "s2" });
+ assert.equal(track(delta("t1", "i1", "Looking at the first", "turn-1")), null);
+ assert.deepEqual(track(userMessage("t1", "s2", { steered: true })), { kind: "thinking" });
+ assert.deepEqual(track(delta("t1", "i2", "Both done", "turn-1")), { kind: "reply", text: "Both done" });
+ assert.equal(track(delta("t1", "i3", "unrelated", "turn-0")), null);
+ assert.deepEqual(track(completed("t1", true, "turn-1")), { kind: "done", ok: true, text: "Both done" });
+});
+
+test("a waiting card or an opened request means MausBot needs the person", () => {
+ const track = createReplyTracker({ threadId: "t1", sendId: "s1" });
+ track(userMessage("t1", "s1"));
+ assert.equal(track(card("t1", { answered: "Allow" })), null);
+ assert.equal(track(card("t1", { dismissed: true })), null);
+ assert.equal(track(card("t1", { expired: true })), null);
+ assert.deepEqual(track(card("t1", {})), { kind: "needs-you" });
+ assert.deepEqual(track(opened("t1")), { kind: "needs-you" });
+});
+
+test("ask listens before it sends, posts to the Quick asks chat, and ends with the turn", async () => {
+ const server = fakeServer({ bots: [] });
+ const updates = [];
+ const asking = server.talk.ask({ chat: { botId: "m", threadId: "t1" }, text: "hi", sendId: "s1", signal: new AbortController().signal, onUpdate: u => updates.push(u) });
+ await flush();
+ assert.deepEqual(server.calls.map(c => c[1]), ["/api/events?screens=off"]);
+ server.events.push({ kind: "hello", cursor: "s:1", resumed: false });
+ await flush();
+ assert.deepEqual(server.calls[1], ["POST", "/api/bots/m/messages", { text: "hi", threadId: "t1", sendId: "s1" }]);
+ for (const frame of [userMessage("t1", "s1"), botText("t1", "Hello"), completed("t1", true)]) server.events.push(frame);
+ assert.equal(await asking, "done");
+ assert.deepEqual(updates.map(u => u.kind), ["thinking", "reply", "done"]);
+ assert.equal(server.events.cancelled, true);
+});
+
+test("a refused send, a lost stream, a failed turn and an abort", async () => {
+ const refused = fakeServer({ bots: [], sendStatus: 409 });
+ const refusing = asking(refused);
+ await flush();
+ refused.events.push(HELLO);
+ await assert.rejects(refusing, { name: "TalkServerError", code: "refused" });
+ assert.equal(refused.events.cancelled, true);
+
+ const lost = fakeServer({ bots: [] });
+ const updates = [];
+ const losing = asking(lost, { onUpdate: update => updates.push(update) });
+ await flush();
+ lost.events.push(HELLO);
+ lost.events.push(userMessage("t1", "s1"));
+ await flush();
+ assert.deepEqual(updates, [{ kind: "thinking" }]);
+ lost.events.end();
+ await assert.rejects(losing, { code: "lost" });
+
+ const failed = fakeServer({ bots: [] });
+ const failing = asking(failed);
+ await flush();
+ for (const frame of [HELLO, userMessage("t1", "s1"), completed("t1", false)]) failed.events.push(frame);
+ assert.equal(await failing, "failed");
+
+ const waiting = fakeServer({ bots: [] });
+ const waits = asking(waiting);
+ await flush();
+ for (const frame of [HELLO, userMessage("t1", "s1"), card("t1", {})]) waiting.events.push(frame);
+ assert.equal(await waits, "needs-you");
+ assert.equal(waiting.events.cancelled, true);
+
+ const aborted = fakeServer({ bots: [] });
+ const controller = new AbortController();
+ const aborting = asking(aborted, { signal: controller.signal });
+ await flush();
+ aborted.events.push(HELLO);
+ await flush();
+ controller.abort();
+ await assert.rejects(aborting, { name: "AbortError" });
+ assert.equal(aborted.events.cancelled, true);
+});
+
+test("a failed turn that still said something is done, not failed", async () => {
+ const server = fakeServer({ bots: [] });
+ const ending = asking(server);
+ await flush();
+ for (const frame of [HELLO, userMessage("t1", "s1"), botText("t1", "I hit a limit"), completed("t1", false)]) server.events.push(frame);
+ assert.equal(await ending, "done");
+});
+
+test("readFrames joins frames split across chunks and skips heartbeats and junk", async () => {
+ const chunks = [": heartbeat\n\n", "id: s:1\ndata: {\"kind\":\"he", "llo\"}\n\ndata: not json\n\n", "data: {\"kind\":\"x\"}\n\n"];
+ const frames = [];
+ await readFrames(ReadableStream.from(chunks.map(c => new TextEncoder().encode(c))), f => frames.push(f));
+ assert.deepEqual(frames, [{ kind: "hello" }, { kind: "x" }]);
+});
diff --git a/electron/talk-session.mjs b/electron/talk-session.mjs
new file mode 100644
index 0000000000..87100a2832
--- /dev/null
+++ b/electron/talk-session.mjs
@@ -0,0 +1,198 @@
+import { randomUUID } from "node:crypto";
+import { TalkServerError } from "./talk-server.mjs";
+
+export const TALK_TIMING = Object.freeze({ replyHideMs: 12_000, noticeHideMs: 4_000, stillWorkingMs: 120_000, hoverRecheckMs: 500, maxListenMs: 60_000 });
+
+export const TALK_TEXT = Object.freeze({
+ busy: "Voice is in use in MausBot",
+ serverDown: "Open MausBot to talk",
+ starting: "MausBot is still starting. Try again in a moment.",
+ noMausbot: "Set up MausBot first, then try again.",
+ moved: "MausBot lives on My Cloud now — talk to it there",
+ permission: "Talking needs Microphone + Speech Recognition access — System Settings → Privacy & Security.",
+ dictationOff: "Turn on Dictation in System Settings → Keyboard, then try again.",
+ unavailable: "Talking couldn't start. Try again.",
+ failed: "MausBot couldn't take that · Open chat",
+});
+
+const SPEECH_PROBLEMS = new Map([
+ ["speech-not-authorized", TALK_TEXT.permission],
+ ["mic-failed", TALK_TEXT.unavailable],
+ ["recognizer-unavailable", TALK_TEXT.unavailable],
+ ["dictation-disabled", TALK_TEXT.dictationOff],
+ ["helper-build-failed", TALK_TEXT.unavailable],
+ ["helper-start-failed", TALK_TEXT.unavailable],
+ ["unsupported-platform", TALK_TEXT.unavailable],
+]);
+
+const SERVER_NOTICES = new Map([
+ ["server-down", TALK_TEXT.serverDown],
+ ["starting", TALK_TEXT.starting],
+ ["no-mausbot", TALK_TEXT.noMausbot],
+ ["moved", TALK_TEXT.moved],
+]);
+
+const UNDER_WAY = new Set(["listening", "sending", "thinking"]);
+
+export function createTalkSession({ speech, server, panel, voiceInUse, release, openChat, newSendId = randomUUID }) {
+ let current = null;
+
+ const live = ask => current === ask && !ask.controller.signal.aborted;
+
+ function begin(state) {
+ const ask = { state, words: "", reply: "", chat: null, sink: null, controller: new AbortController(), listenTimer: null, hideTimer: null, answerTimer: null };
+ current = ask;
+ return ask;
+ }
+
+ function show(ask, state, text) {
+ ask.state = state;
+ try {
+ panel.render({ state, text });
+ } catch {}
+ }
+
+ function closeBox(ask) {
+ if (current !== ask) return;
+ current = null;
+ clearTimeout(ask.listenTimer);
+ clearTimeout(ask.hideTimer);
+ clearTimeout(ask.answerTimer);
+ ask.controller.abort();
+ try {
+ panel.close();
+ } catch {}
+ }
+
+ function cancel(ask) {
+ if (ask.state === "listening") speech.stop(ask.sink);
+ closeBox(ask);
+ }
+
+ function hovered() {
+ try {
+ return panel.hovered();
+ } catch {
+ return false;
+ }
+ }
+
+ function hideIn(ask, ms) {
+ clearTimeout(ask.hideTimer);
+ const check = () => {
+ if (current !== ask) return;
+ if (hovered()) ask.hideTimer = setTimeout(check, TALK_TIMING.hoverRecheckMs);
+ else closeBox(ask);
+ };
+ ask.hideTimer = setTimeout(check, ms);
+ }
+
+ function settle(ask, state, text, hideMs) {
+ clearTimeout(ask.answerTimer);
+ show(ask, state, text);
+ hideIn(ask, hideMs);
+ }
+
+ function stillWorking(ask) {
+ ask.controller.abort();
+ settle(ask, "still-working", ask.reply, TALK_TIMING.replyHideMs);
+ }
+
+ function failed(ask, error) {
+ const code = error instanceof TalkServerError ? error.code : null;
+ if (code === "lost") stillWorking(ask);
+ else if (SERVER_NOTICES.has(code)) settle(ask, "error", SERVER_NOTICES.get(code), TALK_TIMING.noticeHideMs);
+ else settle(ask, "error", TALK_TEXT.failed, TALK_TIMING.replyHideMs);
+ }
+
+ function follow(ask, update) {
+ if (!live(ask)) return;
+ if (update.kind === "thinking") show(ask, "thinking", ask.words);
+ else if (update.kind === "reply") {
+ ask.reply = update.text;
+ show(ask, "reply", update.text);
+ } else if (update.kind === "done") ask.reply = update.text;
+ }
+
+ function answered(ask, outcome) {
+ if (!live(ask)) return;
+ if (outcome === "done") settle(ask, "reply", ask.reply, TALK_TIMING.replyHideMs);
+ else if (outcome === "needs-you") settle(ask, "needs-you", ask.reply, TALK_TIMING.replyHideMs);
+ else settle(ask, "error", TALK_TEXT.failed, TALK_TIMING.replyHideMs);
+ }
+
+ function send(ask, prepared) {
+ show(ask, "sending", ask.words);
+ ask.answerTimer = setTimeout(() => { if (live(ask)) stillWorking(ask); }, TALK_TIMING.stillWorkingMs);
+ prepared.then(chat => {
+ if (!live(ask)) return;
+ server.ask({
+ chat,
+ text: ask.words,
+ sendId: newSendId(),
+ signal: ask.controller.signal,
+ onUpdate: update => follow(ask, update),
+ }).then(outcome => answered(ask, outcome), error => { if (live(ask)) failed(ask, error); });
+ }, () => {});
+ }
+
+ function listen() {
+ const ask = begin("listening");
+ const listening = () => current === ask && ask.state === "listening";
+ show(ask, "listening", "");
+ const prepared = server.prepare();
+ ask.sink = {
+ transcript(line) {
+ if (!listening() || typeof line?.text !== "string") return;
+ ask.words = line.text;
+ show(ask, "listening", ask.words);
+ },
+ replaced() {
+ if (listening()) closeBox(ask);
+ },
+ end(info) {
+ if (!listening()) return;
+ const problem = SPEECH_PROBLEMS.get(info?.reason);
+ if (problem) settle(ask, "error", problem, TALK_TIMING.noticeHideMs);
+ else if (!ask.words.trim()) closeBox(ask);
+ else send(ask, prepared);
+ },
+ };
+ prepared.then(chat => { ask.chat = chat; }, error => {
+ if (!live(ask) || !(ask.state === "listening" || ask.state === "sending")) return;
+ if (ask.state === "listening") speech.stop(ask.sink);
+ failed(ask, error);
+ });
+ try {
+ speech.start(ask.sink, { finishOnRelease: release() });
+ } catch {
+ if (!listening()) return;
+ speech.stop(ask.sink);
+ settle(ask, "error", TALK_TEXT.unavailable, TALK_TIMING.noticeHideMs);
+ return;
+ }
+ ask.listenTimer = setTimeout(() => { if (listening()) speech.finish(ask.sink); }, TALK_TIMING.maxListenMs);
+ }
+
+ const dismiss = () => { if (current) cancel(current); };
+
+ return {
+ press() {
+ if (current && UNDER_WAY.has(current.state)) return;
+ dismiss();
+ if (voiceInUse()) settle(begin("error"), "error", TALK_TEXT.busy, TALK_TIMING.noticeHideMs);
+ else listen();
+ },
+ open() {
+ const ask = current;
+ if (!ask) return;
+ const chat = ask.state === "listening" ? null : ask.chat;
+ cancel(ask);
+ openChat(chat);
+ },
+ dismiss,
+ close: dismiss,
+ /** Listening, or an ask on its way that has not been answered yet. */
+ busy: () => Boolean(current && UNDER_WAY.has(current.state)),
+ };
+}
diff --git a/electron/talk-session.node-test.mjs b/electron/talk-session.node-test.mjs
new file mode 100644
index 0000000000..01a7165dad
--- /dev/null
+++ b/electron/talk-session.node-test.mjs
@@ -0,0 +1,483 @@
+import assert from "node:assert/strict";
+import test, { mock } from "node:test";
+import { TalkServerError } from "./talk-server.mjs";
+import { TALK_TEXT, TALK_TIMING, createTalkSession } from "./talk-session.mjs";
+
+const flush = () => new Promise(resolve => setImmediate(resolve));
+const pick = (object, keys) => Object.fromEntries(keys.map(key => [key, object[key]]));
+
+test.beforeEach(() => mock.timers.enable({ apis: ["setTimeout"] }));
+test.afterEach(() => mock.timers.reset());
+
+const CHAT = { botId: "m", threadId: "t1" };
+function harness({ busy = false, prepare = async () => CHAT, ask } = {}) {
+ const h = { views: [], closed: 0, hovered: false, renderFails: false, closeFails: false, hoverFails: false, startFails: false, releaseFails: false, starts: [], stops: [], finishes: [], opened: [], asks: [], prepares: 0, sink: null };
+ h.session = createTalkSession({
+ speech: {
+ start: (sink, options) => { h.sink = sink; h.starts.push(options); if (h.startFails) throw new Error("spawn failed"); },
+ stop: sink => h.stops.push(sink === h.sink),
+ finish: sink => h.finishes.push(sink === h.sink),
+ },
+ server: {
+ prepare: () => { h.prepares += 1; return prepare(); },
+ ask: ask ?? (async input => { h.asks.push(input); input.onUpdate({ kind: "thinking" }); input.onUpdate({ kind: "reply", text: "Hi" }); input.onUpdate({ kind: "done", ok: true, text: "Hi" }); return "done"; }),
+ },
+ panel: {
+ render: view => { h.views.push(view); if (h.renderFails) throw new Error("render failed"); },
+ close: () => { h.closed += 1; if (h.closeFails) throw new Error("close failed"); },
+ hovered: () => { if (h.hoverFails) throw new Error("hovered failed"); return h.hovered; },
+ },
+ voiceInUse: () => busy,
+ release: () => { if (h.releaseFails) throw new Error("no key"); return ["control", "option"]; },
+ openChat: chat => h.opened.push(chat), newSendId: () => "send-1",
+ });
+ return h;
+}
+const say = (h, text) => h.sink.transcript({ text, partial: true });
+const release = (h, info = { code: 0, reason: "completed" }) => h.sink.end(info);
+const holdAsk = updates => {
+ const inputs = [];
+ const ask = async input => {
+ inputs.push(input);
+ for (const update of updates) input.onUpdate(update);
+ return new Promise(() => {});
+ };
+ return { inputs, ask };
+};
+
+test("the box's words and timings are fixed", () => {
+ assert.deepEqual(TALK_TIMING, { replyHideMs: 12_000, noticeHideMs: 4_000, stillWorkingMs: 120_000, hoverRecheckMs: 500, maxListenMs: 60_000 });
+ assert.deepEqual(TALK_TEXT, {
+ busy: "Voice is in use in MausBot",
+ serverDown: "Open MausBot to talk",
+ starting: "MausBot is still starting. Try again in a moment.",
+ noMausbot: "Set up MausBot first, then try again.",
+ moved: "MausBot lives on My Cloud now — talk to it there",
+ permission: "Talking needs Microphone + Speech Recognition access — System Settings → Privacy & Security.",
+ dictationOff: "Turn on Dictation in System Settings → Keyboard, then try again.",
+ unavailable: "Talking couldn't start. Try again.",
+ failed: "MausBot couldn't take that · Open chat",
+ });
+ assert.ok(Object.isFrozen(TALK_TIMING));
+ assert.ok(Object.isFrozen(TALK_TEXT));
+});
+
+test("a press listens with the key's release modifiers and shows the live words", () => {
+ const h = harness(); h.session.press(); say(h, "what's on");
+ assert.deepEqual(h.starts, [{ finishOnRelease: ["control", "option"] }]);
+ assert.deepEqual(h.views, [{ state: "listening", text: "" }, { state: "listening", text: "what's on" }]);
+ assert.equal(h.prepares, 1);
+});
+
+test("letting go sends the words to the Quick asks chat and shows the reply, which hides 12 s later", async () => {
+ const h = harness(); h.session.press(); say(h, "what's on my calendar"); release(h); await flush();
+ assert.deepEqual(pick(h.asks[0], ["chat", "text", "sendId"]), { chat: CHAT, text: "what's on my calendar", sendId: "send-1" });
+ assert.deepEqual([...new Set(h.views.map(v => v.state))], ["listening", "sending", "thinking", "reply"]);
+ assert.deepEqual(h.views.find(v => v.state === "sending"), { state: "sending", text: "what's on my calendar" });
+ assert.deepEqual(h.views.find(v => v.state === "thinking"), { state: "thinking", text: "what's on my calendar" });
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi" });
+ mock.timers.tick(11_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+
+test("a reply under the pointer stays until the pointer leaves", async () => {
+ const h = harness(); h.session.press(); say(h, "hello"); release(h); await flush();
+ h.hovered = true;
+ mock.timers.tick(12_000); assert.equal(h.closed, 0);
+ mock.timers.tick(500); assert.equal(h.closed, 0);
+ h.hovered = false;
+ mock.timers.tick(499); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+
+test("presses while listening, sending or thinking are ignored", async () => {
+ const { inputs, ask } = holdAsk([]);
+ const h = harness({ ask });
+ h.session.press(); h.session.press(); h.session.press();
+ say(h, "book a table"); release(h); await flush();
+ assert.equal(h.views.at(-1).state, "sending");
+ h.session.press();
+ inputs[0].onUpdate({ kind: "thinking" });
+ assert.equal(h.views.at(-1).state, "thinking");
+ h.session.press();
+ assert.equal(h.starts.length, 1);
+ assert.equal(h.prepares, 1);
+ assert.equal(h.closed, 0);
+ assert.equal(inputs.length, 1);
+ assert.equal(inputs[0].signal.aborted, false);
+ assert.equal(h.views.filter(v => v.state === "listening" && v.text === "").length, 1);
+});
+
+test("a press while a reply shows closes it and starts a new ask", async () => {
+ const { inputs, ask } = holdAsk([{ kind: "thinking" }, { kind: "reply", text: "Hi" }]);
+ const h = harness({ ask });
+ h.session.press(); say(h, "first"); release(h); await flush();
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi" });
+ h.session.press();
+ assert.equal(inputs[0].signal.aborted, true);
+ assert.equal(h.closed, 1);
+ assert.equal(h.starts.length, 2);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "" });
+ inputs[0].onUpdate({ kind: "reply", text: "late words from the first ask" });
+ mock.timers.tick(TALK_TIMING.stillWorkingMs);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "" });
+ assert.equal(h.closed, 1);
+
+ const settled = harness(); settled.session.press(); say(settled, "first"); release(settled); await flush();
+ settled.session.press();
+ assert.equal(settled.closed, 1);
+ mock.timers.tick(TALK_TIMING.replyHideMs);
+ assert.equal(settled.closed, 1);
+ assert.deepEqual(settled.views.at(-1), { state: "listening", text: "" });
+});
+
+test("voice in use refuses without listening", () => {
+ const h = harness({ busy: true }); h.session.press();
+ assert.deepEqual(h.starts, []);
+ assert.equal(h.prepares, 0);
+ assert.deepEqual(h.views, [{ state: "error", text: "Voice is in use in MausBot" }]);
+ mock.timers.tick(3_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+
+test("an empty transcript closes silently, even when the recognizer reports an error", async () => {
+ for (const info of [{ code: 0, reason: "completed" }, { code: 1, reason: "recognition-error" }, { code: 1, reason: "helper-exited" }]) {
+ const h = harness(); h.session.press(); release(h, info); await flush();
+ assert.equal(h.closed, 1, info.reason); assert.equal(h.asks.length, 0);
+ assert.ok(h.views.every(v => v.state === "listening"), info.reason);
+ }
+ const blank = harness(); blank.session.press(); say(blank, " "); release(blank, { code: 1, reason: "recognition-error" }); await flush();
+ assert.equal(blank.closed, 1); assert.equal(blank.asks.length, 0);
+ assert.ok(blank.views.every(v => v.state === "listening"));
+});
+
+test("words heard before a recognizer error are still sent", async () => {
+ const h = harness(); h.session.press(); say(h, "remind me");
+ h.sink.transcript({ error: "recognition-error" });
+ release(h, { code: 1, reason: "recognition-error" }); await flush();
+ assert.equal(h.asks.length, 1);
+ assert.equal(h.asks[0].text, "remind me");
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi" });
+});
+
+test("permission and setup problems say what to fix, in the composer's words: only a refused permission asks for access", async () => {
+ const problems = [
+ ["speech-not-authorized", TALK_TEXT.permission],
+ ["mic-failed", TALK_TEXT.unavailable],
+ ["recognizer-unavailable", TALK_TEXT.unavailable],
+ ["dictation-disabled", TALK_TEXT.dictationOff],
+ ["helper-build-failed", TALK_TEXT.unavailable],
+ ["helper-start-failed", TALK_TEXT.unavailable],
+ ["unsupported-platform", TALK_TEXT.unavailable],
+ ];
+ for (const [reason, text] of problems) {
+ const h = harness(); h.session.press(); release(h, { code: 1, reason }); await flush();
+ assert.deepEqual(h.views.at(-1), { state: "error", text }, reason);
+ assert.equal(h.asks.length, 0, reason);
+ mock.timers.tick(3_999); assert.equal(h.closed, 0, reason);
+ mock.timers.tick(1); assert.equal(h.closed, 1, reason);
+ }
+});
+
+test("a server that can't take asks says why and stops listening: down, still starting, no MausBot, or moved to My Cloud", async () => {
+ const notices = [
+ ["server-down", "Open MausBot to talk"],
+ ["starting", TALK_TEXT.starting],
+ ["no-mausbot", TALK_TEXT.noMausbot],
+ ["moved", "MausBot lives on My Cloud now — talk to it there"],
+ ];
+ for (const [code, text] of notices) {
+ const h = harness({ prepare: async () => { throw new TalkServerError(code); } });
+ h.session.press(); await flush();
+ assert.deepEqual(h.stops, [true], code);
+ assert.deepEqual(h.views.at(-1), { state: "error", text }, code);
+ say(h, "too late"); release(h); await flush();
+ assert.equal(h.asks.length, 0, code);
+ assert.deepEqual(h.views.at(-1), { state: "error", text }, code);
+ mock.timers.tick(3_999); assert.equal(h.closed, 0, code);
+ mock.timers.tick(1); assert.equal(h.closed, 1, code);
+ }
+});
+
+test("a server that goes away as the words are sent says Open MausBot to talk", async () => {
+ let fail;
+ const late = harness({ prepare: () => new Promise((_, reject) => { fail = reject; }) });
+ late.session.press(); say(late, "hello"); release(late); await flush();
+ assert.equal(late.views.at(-1).state, "sending");
+ fail(new TalkServerError("server-down")); await flush();
+ assert.deepEqual(late.stops, []);
+ assert.equal(late.asks.length, 0);
+ assert.deepEqual(late.views.at(-1), { state: "error", text: TALK_TEXT.serverDown });
+ mock.timers.tick(TALK_TIMING.noticeHideMs); assert.equal(late.closed, 1);
+
+ const gone = harness({ ask: async () => { throw new TalkServerError("server-down"); } });
+ gone.session.press(); say(gone, "hello"); release(gone); await flush();
+ assert.deepEqual(gone.views.at(-1), { state: "error", text: TALK_TEXT.serverDown });
+ mock.timers.tick(TALK_TIMING.noticeHideMs); assert.equal(gone.closed, 1);
+
+ const moved = harness({ ask: async () => { throw new TalkServerError("moved"); } });
+ moved.session.press(); say(moved, "hello"); release(moved); await flush();
+ assert.deepEqual(moved.views.at(-1), { state: "error", text: TALK_TEXT.moved });
+ mock.timers.tick(TALK_TIMING.noticeHideMs); assert.equal(moved.closed, 1);
+});
+
+test("busy while listening, sending or thinking; not once a reply, a notice or nothing shows", async () => {
+ const { inputs, ask } = holdAsk([]);
+ const h = harness({ ask });
+ assert.equal(h.session.busy(), false);
+ h.session.press();
+ assert.equal(h.session.busy(), true, "listening");
+ say(h, "hello"); release(h); await flush();
+ assert.equal(h.views.at(-1).state, "sending");
+ assert.equal(h.session.busy(), true, "sending");
+ inputs[0].onUpdate({ kind: "thinking" });
+ assert.equal(h.session.busy(), true, "thinking");
+ inputs[0].onUpdate({ kind: "reply", text: "Hi" });
+ assert.equal(h.session.busy(), false, "reply");
+ h.session.dismiss();
+ assert.equal(h.session.busy(), false, "closed");
+
+ const refused = harness({ busy: true });
+ refused.session.press();
+ assert.equal(refused.session.busy(), false, "a notice");
+});
+
+test("a box that fails to close or to say where the pointer is still hides, and the next press works", async () => {
+ const h = harness(); h.session.press(); say(h, "hello"); release(h); await flush();
+ h.hoverFails = true; h.closeFails = true;
+ assert.doesNotThrow(() => mock.timers.tick(TALK_TIMING.replyHideMs));
+ assert.equal(h.closed, 1);
+ h.closeFails = false;
+ h.session.press();
+ assert.equal(h.starts.length, 2);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "" });
+});
+
+test("needs-you shows and hides like a reply", async () => {
+ const h = harness({ ask: async input => { input.onUpdate({ kind: "thinking" }); input.onUpdate({ kind: "reply", text: "Checking" }); input.onUpdate({ kind: "needs-you" }); return "needs-you"; } });
+ h.session.press(); say(h, "clean up my downloads"); release(h); await flush();
+ assert.deepEqual(h.views.at(-1), { state: "needs-you", text: "Checking" });
+ mock.timers.tick(11_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+
+test("no answer in 120 s shows Still working · Open chat", async () => {
+ let signal; const h = harness({ ask: async input => { signal = input.signal; input.onUpdate({ kind: "thinking" }); return new Promise(() => {}); } });
+ h.session.press(); say(h, "book a table"); release(h); await flush();
+ mock.timers.tick(119_999); assert.notEqual(h.views.at(-1).state, "still-working");
+ mock.timers.tick(1);
+ assert.deepEqual(h.views.at(-1), { state: "still-working", text: "" });
+ assert.equal(signal.aborted, true);
+ mock.timers.tick(11_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+
+test("a lost stream shows Still working; a refused send shows the failure", async () => {
+ const lost = harness({ ask: async input => { input.onUpdate({ kind: "thinking" }); input.onUpdate({ kind: "reply", text: "Half an answer" }); throw new TalkServerError("lost"); } });
+ lost.session.press(); say(lost, "summarise my inbox"); release(lost); await flush();
+ assert.deepEqual(lost.views.at(-1), { state: "still-working", text: "Half an answer" });
+ mock.timers.tick(11_999); assert.equal(lost.closed, 0);
+ mock.timers.tick(1); assert.equal(lost.closed, 1);
+
+ const refused = harness({ ask: async () => { throw new TalkServerError("refused"); } });
+ refused.session.press(); say(refused, "summarise my inbox"); release(refused); await flush();
+ assert.deepEqual(refused.views.at(-1), { state: "error", text: TALK_TEXT.failed });
+ mock.timers.tick(11_999); assert.equal(refused.closed, 0);
+ mock.timers.tick(1); assert.equal(refused.closed, 1);
+});
+
+test("a turn that fails shows the failure", async () => {
+ const h = harness({ ask: async input => { input.onUpdate({ kind: "thinking" }); input.onUpdate({ kind: "done", ok: false, text: "" }); return "failed"; } });
+ h.session.press(); say(h, "summarise my inbox"); release(h); await flush();
+ assert.deepEqual(h.views.at(-1), { state: "error", text: TALK_TEXT.failed });
+ mock.timers.tick(11_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+});
+
+test("a box that fails to draw never breaks the reply stream", async () => {
+ const { inputs, ask } = holdAsk([{ kind: "thinking" }]);
+ const h = harness({ ask });
+ h.session.press(); say(h, "hello"); release(h); await flush();
+ h.renderFails = true;
+ assert.doesNotThrow(() => inputs[0].onUpdate({ kind: "reply", text: "Hi" }));
+ h.renderFails = false;
+ inputs[0].onUpdate({ kind: "reply", text: "Hi there" });
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi there" });
+});
+
+test("replaced while listening closes the box and nothing is sent", async () => {
+ const h = harness(); h.session.press(); say(h, "hello");
+ h.sink.replaced();
+ assert.equal(h.closed, 1);
+ say(h, "hello there"); release(h); await flush();
+ assert.equal(h.asks.length, 0);
+ assert.equal(h.closed, 1);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "hello" });
+ h.session.press();
+ assert.equal(h.starts.length, 2);
+});
+
+test("clicking the box opens the chat; before the chat is known it only brings MausBot forward", async () => {
+ const idle = harness(); idle.session.open();
+ assert.deepEqual(idle.opened, []); assert.equal(idle.closed, 0);
+
+ const listening = harness(); listening.session.press(); say(listening, "hello"); await flush();
+ listening.session.open();
+ assert.deepEqual(listening.opened, [null]);
+ assert.deepEqual(listening.stops, [true]);
+ assert.equal(listening.closed, 1);
+
+ const preparing = harness({ prepare: () => new Promise(() => {}) });
+ preparing.session.press(); say(preparing, "hello"); release(preparing); await flush();
+ preparing.session.open();
+ assert.deepEqual(preparing.opened, [null]);
+ assert.deepEqual(preparing.stops, []);
+ assert.equal(preparing.closed, 1);
+
+ const { inputs, ask } = holdAsk([{ kind: "thinking" }]);
+ const thinking = harness({ ask });
+ thinking.session.press(); say(thinking, "hello"); release(thinking); await flush();
+ thinking.session.open();
+ assert.deepEqual(thinking.opened, [CHAT]);
+ assert.equal(inputs[0].signal.aborted, true);
+ assert.equal(thinking.closed, 1);
+
+ const answered = harness(); answered.session.press(); say(answered, "hello"); release(answered); await flush();
+ answered.session.open();
+ assert.deepEqual(answered.opened, [CHAT]);
+ assert.equal(answered.closed, 1);
+ mock.timers.tick(TALK_TIMING.replyHideMs);
+ assert.equal(answered.closed, 1);
+});
+
+test("dismissing while listening cancels capture", async () => {
+ const h = harness(); h.session.press(); say(h, "hello");
+ h.session.dismiss();
+ assert.deepEqual(h.stops, [true]);
+ assert.equal(h.closed, 1);
+ say(h, "hello there"); release(h); await flush();
+ assert.equal(h.asks.length, 0);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "hello" });
+ assert.deepEqual(h.opened, []);
+
+ const { inputs, ask } = holdAsk([{ kind: "thinking" }]);
+ const thinking = harness({ ask });
+ thinking.session.press(); say(thinking, "hello"); release(thinking); await flush();
+ thinking.session.dismiss();
+ assert.equal(inputs[0].signal.aborted, true);
+ assert.equal(thinking.closed, 1);
+ assert.deepEqual(thinking.opened, []);
+});
+
+test("quitting closes the box and cancels the ask under way", async () => {
+ const listening = harness(); listening.session.press();
+ listening.session.close();
+ assert.deepEqual(listening.stops, [true]);
+ assert.equal(listening.closed, 1);
+
+ const { inputs, ask } = holdAsk([{ kind: "thinking" }]);
+ const thinking = harness({ ask });
+ thinking.session.press(); say(thinking, "hello"); release(thinking); await flush();
+ thinking.session.close();
+ assert.equal(inputs[0].signal.aborted, true);
+ assert.equal(thinking.closed, 1);
+ mock.timers.tick(TALK_TIMING.stillWorkingMs);
+ assert.equal(thinking.views.at(-1).state, "thinking");
+});
+
+test("listening stops by itself after 60 s and sends what was heard", async () => {
+ const h = harness(); h.session.press(); say(h, "remind me to call mum");
+ mock.timers.tick(59_999);
+ assert.deepEqual(h.finishes, []);
+ assert.equal(h.views.at(-1).state, "listening");
+ mock.timers.tick(1);
+ assert.deepEqual(h.finishes, [true]);
+ assert.deepEqual(h.stops, []);
+ release(h); await flush();
+ assert.equal(h.asks[0].text, "remind me to call mum");
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi" });
+
+ const sent = harness(); sent.session.press(); say(sent, "hello"); release(sent); await flush();
+ mock.timers.tick(TALK_TIMING.maxListenMs);
+ assert.deepEqual(sent.finishes, []);
+
+ const dismissed = harness(); dismissed.session.press(); dismissed.session.dismiss();
+ mock.timers.tick(TALK_TIMING.maxListenMs);
+ assert.deepEqual(dismissed.finishes, []);
+});
+
+test("an earlier ask's sink cannot touch the next ask", async () => {
+ const h = harness(); h.session.press();
+ const first = h.sink;
+ h.session.dismiss();
+ h.session.press();
+ assert.notEqual(h.sink, first);
+ const before = { views: h.views.length, closed: h.closed, stops: [...h.stops] };
+ first.transcript({ text: "old words", partial: true });
+ first.end({ code: 0, reason: "completed" });
+ first.end({ code: 1, reason: "speech-not-authorized" });
+ first.replaced();
+ await flush();
+ assert.equal(h.views.length, before.views);
+ assert.equal(h.closed, before.closed);
+ assert.deepEqual(h.stops, before.stops);
+ assert.equal(h.asks.length, 0);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "" });
+ say(h, "new words"); release(h); await flush();
+ assert.equal(h.asks.length, 1);
+ assert.equal(h.asks[0].text, "new words");
+});
+
+test("a box that fails to draw when listening starts leaves later presses working", () => {
+ const h = harness();
+ h.renderFails = true;
+ assert.doesNotThrow(() => h.session.press());
+ assert.equal(h.starts.length, 1);
+ h.renderFails = false;
+ release(h);
+ assert.equal(h.closed, 1);
+ h.session.press();
+ assert.equal(h.starts.length, 2);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "" });
+});
+
+test("speech that fails to start says Talking couldn't start, and a later press works", () => {
+ const h = harness();
+ h.startFails = true;
+ assert.doesNotThrow(() => h.session.press());
+ assert.deepEqual(h.views.at(-1), { state: "error", text: TALK_TEXT.unavailable });
+ assert.deepEqual(h.stops, [true]);
+ mock.timers.tick(3_999); assert.equal(h.closed, 0);
+ mock.timers.tick(1); assert.equal(h.closed, 1);
+ mock.timers.tick(TALK_TIMING.maxListenMs);
+ assert.deepEqual(h.finishes, []);
+ h.startFails = false;
+ h.session.press();
+ assert.equal(h.starts.length, 2);
+ assert.deepEqual(h.views.at(-1), { state: "listening", text: "" });
+
+ const keyless = harness();
+ keyless.releaseFails = true;
+ assert.doesNotThrow(() => keyless.session.press());
+ assert.deepEqual(keyless.starts, []);
+ assert.deepEqual(keyless.views.at(-1), { state: "error", text: TALK_TEXT.unavailable });
+ keyless.releaseFails = false;
+ keyless.session.press();
+ assert.equal(keyless.starts.length, 1);
+});
+
+test("a box that fails to draw when speech ends never throws back into speech", async () => {
+ const h = harness(); h.session.press(); say(h, "hello");
+ h.renderFails = true;
+ assert.doesNotThrow(() => release(h));
+ h.renderFails = false;
+ await flush();
+ assert.equal(h.asks.length, 1);
+ assert.deepEqual(h.views.at(-1), { state: "reply", text: "Hi" });
+
+ const denied = harness(); denied.session.press();
+ denied.renderFails = true;
+ assert.doesNotThrow(() => release(denied, { code: 1, reason: "mic-failed" }));
+ mock.timers.tick(TALK_TIMING.noticeHideMs);
+ assert.equal(denied.closed, 1);
+});
diff --git a/electron/talk-shortcut.d.mts b/electron/talk-shortcut.d.mts
new file mode 100644
index 0000000000..dcf45aa6d2
--- /dev/null
+++ b/electron/talk-shortcut.d.mts
@@ -0,0 +1,35 @@
+import type { DesktopPrefs } from "./desktop-prefs.mjs";
+
+export type TalkKeyId = "ctrl-opt-space" | "ctrl-shift-space" | "opt-shift-space";
+export interface TalkShortcutState {
+ /** False hides the setting and lets the key go: not macOS with Apple speech, this desktop is a remote client, or this
+ * computer's bots moved to My Cloud (its own copy is frozen). */
+ available: boolean;
+ enabled: boolean;
+ key: TalkKeyId;
+ keys: { id: TalkKeyId; label: string }[];
+ /** On, but another app holds the key. */
+ taken: boolean;
+}
+export interface TalkShortcutChange { enabled?: boolean; key?: TalkKeyId }
+/** What the setting says before the shortcut is set up, or when setting it up failed. */
+export declare const TALK_SHORTCUT_UNAVAILABLE: Readonly<TalkShortcutState>;
+export interface TalkShortcutBridge {
+ state(): Promise<TalkShortcutState>;
+ set(change: TalkShortcutChange): Promise<TalkShortcutState>;
+}
+export declare function createTalkShortcut(options: {
+ globalShortcut: { register(accelerator: string, handler: () => void): boolean; unregister(accelerator: string): void };
+ prefs: Pick<DesktopPrefs, "talkShortcut" | "setTalkShortcut" | "talkKey" | "setTalkKey">;
+ available(): boolean;
+ onPress(): void;
+}): {
+ state(): TalkShortcutState;
+ set(change: { enabled?: unknown; key?: unknown }): TalkShortcutState;
+ /** Takes or lets go of the key when `available()` changed since the key was last set up. */
+ refresh(): void;
+ releaseModifiers(): string[];
+ close(): void;
+};
+type Sender = { on(event: string, listener: () => void): unknown; removeListener(event: string, listener: () => void): unknown };
+export declare function createCallPresence(): { set(sender: Sender, active: boolean): void; active(): boolean };
diff --git a/electron/talk-shortcut.mjs b/electron/talk-shortcut.mjs
new file mode 100644
index 0000000000..29e87379d2
--- /dev/null
+++ b/electron/talk-shortcut.mjs
@@ -0,0 +1,61 @@
+import { DEFAULT_TALK_KEY, TALK_KEYS } from "./talk-keys.mjs";
+
+const KEY_LIST = Object.entries(TALK_KEYS).map(([id, { label }]) => ({ id, label }));
+
+export const TALK_SHORTCUT_UNAVAILABLE = Object.freeze({ available: false, enabled: false, key: DEFAULT_TALK_KEY, keys: KEY_LIST, taken: false });
+
+export function createTalkShortcut({ globalShortcut, prefs, available, onPress }) {
+ let registered = null, taken = false, offered = false;
+ const release = () => {
+ if (registered) globalShortcut.unregister(registered);
+ registered = null;
+ taken = false;
+ };
+ const apply = () => {
+ release();
+ offered = available();
+ if (!offered || !prefs.talkShortcut()) return;
+ const { accelerator } = TALK_KEYS[prefs.talkKey()];
+ if (globalShortcut.register(accelerator, onPress)) registered = accelerator;
+ else taken = true;
+ };
+ apply();
+ const state = () => ({ available: available(), enabled: prefs.talkShortcut(), key: prefs.talkKey(), keys: KEY_LIST, taken });
+ return {
+ state,
+ set(change) {
+ if (!available()) return state();
+ if (typeof change?.enabled === "boolean") prefs.setTalkShortcut(change.enabled);
+ if (change?.key !== undefined) prefs.setTalkKey(change.key);
+ apply();
+ return state();
+ },
+ refresh() {
+ if (available() !== offered) apply();
+ },
+ releaseModifiers: () => [...TALK_KEYS[prefs.talkKey()].release],
+ close: release,
+ };
+}
+
+const GONE = ["destroyed", "render-process-gone", "did-navigate"];
+
+export function createCallPresence() {
+ const calling = new Map();
+ const forget = sender => {
+ const stop = calling.get(sender);
+ if (!stop) return;
+ calling.delete(sender);
+ stop();
+ };
+ return {
+ set(sender, active) {
+ if (!active) return forget(sender);
+ if (calling.has(sender)) return;
+ const gone = () => forget(sender);
+ for (const event of GONE) sender.on(event, gone);
+ calling.set(sender, () => { for (const event of GONE) sender.removeListener(event, gone); });
+ },
+ active: () => calling.size > 0,
+ };
+}
diff --git a/electron/talk-shortcut.node-test.mjs b/electron/talk-shortcut.node-test.mjs
new file mode 100644
index 0000000000..51e2972255
--- /dev/null
+++ b/electron/talk-shortcut.node-test.mjs
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import test from "node:test";
+import { createDesktopPrefs } from "./desktop-prefs.mjs";
+import { createCallPresence, createTalkShortcut, TALK_SHORTCUT_UNAVAILABLE } from "./talk-shortcut.mjs";
+
+const memoryPrefs = () => {
+ let saved = null;
+ return createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+};
+const fakeShortcuts = (taken = []) => {
+ const registered = new Map();
+ return { registered, register: (accelerator, fn) => !taken.includes(accelerator) && Boolean(registered.set(accelerator, fn)),
+ unregister: accelerator => { registered.delete(accelerator); } };
+};
+const KEYS = [{ id: "ctrl-opt-space", label: "⌃⌥Space" }, { id: "ctrl-shift-space", label: "⌃⇧Space" }, { id: "opt-shift-space", label: "⌥⇧Space" }];
+
+test("registers the saved key when on; a press reaches onPress", () => {
+ const shortcuts = fakeShortcuts(); let presses = 0;
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs: memoryPrefs(), available: () => true, onPress: () => { presses += 1; } });
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Alt+Space"]);
+ shortcuts.registered.get("Control+Alt+Space")();
+ assert.equal(presses, 1);
+ assert.deepEqual(talk.state(), { available: true, enabled: true, key: "ctrl-opt-space", keys: KEYS, taken: false });
+ assert.deepEqual(talk.releaseModifiers(), ["control", "option"]);
+});
+
+test("a key another app holds is reported, and another key can be chosen", () => {
+ const shortcuts = fakeShortcuts(["Control+Alt+Space"]); const prefs = memoryPrefs();
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs, available: () => true, onPress: () => {} });
+ assert.equal(talk.state().taken, true);
+ assert.deepEqual(talk.set({ key: "ctrl-shift-space" }), { available: true, enabled: true, key: "ctrl-shift-space", keys: KEYS, taken: false });
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Shift+Space"]);
+ assert.deepEqual(talk.releaseModifiers(), ["control", "shift"]);
+ assert.equal(prefs.talkKey(), "ctrl-shift-space");
+});
+
+test("off lets the key go, on takes it again, close lets it go", () => {
+ const shortcuts = fakeShortcuts(); const prefs = memoryPrefs();
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs, available: () => true, onPress: () => {} });
+ assert.equal(talk.set({ enabled: false }).enabled, false);
+ assert.deepEqual([...shortcuts.registered.keys()], []);
+ assert.equal(prefs.talkShortcut(), false);
+ assert.equal(talk.state().taken, false);
+ talk.set({ enabled: true });
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Alt+Space"]);
+ talk.close();
+ assert.deepEqual([...shortcuts.registered.keys()], []);
+});
+
+test("an unknown key changes nothing", () => {
+ const shortcuts = fakeShortcuts(); const prefs = memoryPrefs();
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs, available: () => true, onPress: () => {} });
+ talk.set({ key: "cmd-space" });
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Alt+Space"]);
+ assert.equal(prefs.talkKey(), "ctrl-opt-space");
+});
+
+test("where Apple speech is unavailable nothing registers and nothing changes", () => {
+ const shortcuts = fakeShortcuts(); const prefs = memoryPrefs();
+ const talk = createTalkShortcut({ globalShortcut: shortcuts, prefs, available: () => false, onPress: () => {} });
+ assert.deepEqual([...shortcuts.registered.keys()], []);
+ assert.equal(talk.state().available, false);
+ talk.set({ enabled: false, key: "opt-shift-space" });
+ assert.equal(prefs.talkShortcut(), true);
+ assert.equal(prefs.talkKey(), "ctrl-opt-space");
+ assert.deepEqual([...shortcuts.registered.keys()], []);
+});
+
+test("refresh lets the key go once it is no longer available and takes it again when it is, keeping the saved choice", () => {
+ const shortcuts = fakeShortcuts(); const prefs = memoryPrefs(); let available = true; let registrations = 0;
+ const counting = { ...shortcuts, register: (accelerator, fn) => { registrations += 1; return shortcuts.register(accelerator, fn); } };
+ const talk = createTalkShortcut({ globalShortcut: counting, prefs, available: () => available, onPress: () => {} });
+ talk.set({ key: "ctrl-shift-space" });
+ talk.refresh();
+ assert.equal(registrations, 2, "nothing changed, so the key is not taken again");
+ available = false;
+ talk.refresh();
+ assert.deepEqual([...shortcuts.registered.keys()], []);
+ assert.equal(talk.state().available, false);
+ talk.refresh();
+ assert.equal(registrations, 2);
+ available = true;
+ talk.refresh();
+ assert.deepEqual([...shortcuts.registered.keys()], ["Control+Shift+Space"]);
+ assert.deepEqual(talk.state(), { available: true, enabled: true, key: "ctrl-shift-space", keys: KEYS, taken: false });
+
+ const off = memoryPrefs(); off.setTalkShortcut(false); let offAvailable = false;
+ const quiet = fakeShortcuts();
+ const later = createTalkShortcut({ globalShortcut: quiet, prefs: off, available: () => offAvailable, onPress: () => {} });
+ offAvailable = true;
+ later.refresh();
+ assert.deepEqual([...quiet.registered.keys()], [], "turned off stays off");
+});
+
+test("a shortcut not set up says it is unavailable, in the same shape as a real one", () => {
+ assert.deepEqual(TALK_SHORTCUT_UNAVAILABLE, { available: false, enabled: false, key: "ctrl-opt-space", keys: KEYS, taken: false });
+ const real = createTalkShortcut({ globalShortcut: fakeShortcuts(), prefs: memoryPrefs(), available: () => false, onPress: () => {} }).state();
+ assert.deepEqual(Object.keys(TALK_SHORTCUT_UNAVAILABLE).sort(), Object.keys(real).sort());
+ assert.ok(Object.isFrozen(TALK_SHORTCUT_UNAVAILABLE));
+});
+
+test("a reported call blocks until it ends, its page navigates, or its renderer goes away", () => {
+ const presence = createCallPresence(), page = Object.assign(new EventEmitter(), { id: 1 });
+ presence.set(page, true); assert.equal(presence.active(), true);
+ presence.set(page, false); assert.equal(presence.active(), false);
+ for (const event of ["did-navigate", "render-process-gone", "destroyed"]) {
+ presence.set(page, true); page.emit(event); assert.equal(presence.active(), false, event);
+ }
+ for (let i = 0; i < 5; i += 1) presence.set(page, true);
+ for (const event of ["did-navigate", "render-process-gone", "destroyed"]) assert.equal(page.listenerCount(event), 1, event);
+});
diff --git a/electron/update-when-quiet.mjs b/electron/update-when-quiet.mjs
index 8f48386431..9f149e6bc0 100644
--- a/electron/update-when-quiet.mjs
+++ b/electron/update-when-quiet.mjs
@@ -64,8 +64,9 @@ export function launchAfter(record, { version, now = Date.now }) {
* now?(): number,
* log?(line: string): void,
* }} deps `signals`: the screen locked, how long since anyone touched this computer, when someone last typed in the
- * app, whether its window is open, work under way in the app itself (a move, a lending job, a backup), and work under
- * way on the servers this app talks to (a bot's turn, a routine run, a sign-in, a Live call), each a name or null.
+ * app, whether its window is open, work under way in the app itself (a move, a lending job, a talk-shortcut ask, a
+ * backup), and work under way on the servers this app talks to (a bot's turn, a routine run, a sign-in, a Live call),
+ * each a name or null.
*/
export function createQuietInstall({ updater, signals, record, version, now = Date.now, log = () => {} }) {
let outOfSightSince = null, looking = null;
diff --git a/scripts/talk-box-evidence.mjs b/scripts/talk-box-evidence.mjs
new file mode 100644
index 0000000000..666414b377
--- /dev/null
+++ b/scripts/talk-box-evidence.mjs
@@ -0,0 +1,116 @@
+// Renders the talk box (electron/talk-panel.mjs) in headless Chrome for every state, light and dark, into
+// docs/verification/evidence/talk-shortcut/. The viewport is the box's own window: 400 px wide and as tall as the card,
+// 56 to 240 px, at 2x. Each skin is rendered with macOS's appearance emulated the other way round, so the pictures show
+// the box following the app's skin. Reduced motion is on, so the listening ring is still.
+//
+// node scripts/talk-box-evidence.mjs [path to Chrome]
+import { spawn, execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { replyPreview, TALK_PANEL, talkPanelHtml } from "../electron/talk-panel.mjs";
+import { TALK_TEXT } from "../electron/talk-session.mjs";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+const out = join(root, "docs/verification/evidence/talk-shortcut");
+const chrome = process.argv[2] ?? process.env.CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
+const asked = "what's on my calendar today";
+const STATES = [
+ ["listening", { state: "listening", text: "" }],
+ ["listening-words", { state: "listening", text: asked }],
+ ["sending", { state: "sending", text: asked }],
+ ["thinking", { state: "thinking", text: asked }],
+ ["reply", { state: "reply", text: "Standup at 10, then lunch with Sam at 1. Nothing after 4." }],
+ ["reply-long", { state: "reply", text: "Here is a fairly long answer so the card grows. ".repeat(12) }],
+ ["reply-wide", { state: "reply", text: "今日の予定は十時のスタンドアップと一時のランチです。".repeat(20) }],
+ ["needs-you", { state: "needs-you", text: "Approve the file write to ~/Desktop/report.md" }],
+ ["still-working", { state: "still-working", text: "" }],
+ ["error", { state: "error", text: TALK_TEXT.moved }],
+];
+const BACKDROP = { light: { r: 222, g: 222, b: 222, a: 1 }, dark: { r: 40, g: 40, b: 40, a: 1 } };
+
+const scratch = mkdtempSync(join(tmpdir(), "talk-box-evidence-"));
+/** The mascot at the 56 px the app inlines (talk-panel.mjs resizes it with nativeImage; here macOS's sips does). */
+function mascot() {
+ const icon = join(root, "electron/resources/app-icon.png"), small = join(scratch, "mascot.png");
+ try {
+ execFileSync("sips", ["-z", "56", "56", icon, "--out", small], { stdio: "ignore" });
+ return readFileSync(small).toString("base64");
+ } catch {
+ return readFileSync(icon).toString("base64");
+ }
+}
+
+async function devtools(profile) {
+ for (let i = 0; i < 200; i += 1) {
+ try {
+ const [port] = readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n");
+ const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
+ const page = pages.find((target) => target.type === "page");
+ if (page) return page.webSocketDebuggerUrl;
+ } catch {}
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ }
+ throw new Error("Chrome did not open its DevTools port");
+}
+
+function session(url) {
+ const socket = new WebSocket(url);
+ const waiting = new Map(), events = new Map();
+ let next = 0;
+ socket.addEventListener("message", ({ data }) => {
+ const message = JSON.parse(data);
+ if (message.id && waiting.has(message.id)) {
+ const { resolve, reject } = waiting.get(message.id);
+ waiting.delete(message.id);
+ if (message.error) reject(new Error(message.error.message)); else resolve(message.result);
+ } else events.get(message.method)?.();
+ });
+ return {
+ opened: new Promise((resolve, reject) => { socket.addEventListener("open", resolve); socket.addEventListener("error", reject); }),
+ send: (method, params = {}) => new Promise((resolve, reject) => {
+ const id = ++next;
+ waiting.set(id, { resolve, reject });
+ socket.send(JSON.stringify({ id, method, params }));
+ }),
+ once: (method) => new Promise((resolve) => events.set(method, () => { events.delete(method); resolve(); })),
+ close: () => socket.close(),
+ };
+}
+
+const profile = join(scratch, "profile");
+const browser = spawn(chrome, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", "about:blank"], { stdio: "ignore" });
+try {
+ const cdp = session(await devtools(profile));
+ await cdp.opened;
+ await cdp.send("Page.enable");
+ const page = `data:text/html;charset=utf-8,${encodeURIComponent(talkPanelHtml(mascot()))}`;
+ for (const theme of ["light", "dark"]) {
+ await cdp.send("Emulation.setEmulatedMedia", { features: [
+ { name: "prefers-color-scheme", value: theme === "light" ? "dark" : "light" },
+ { name: "prefers-reduced-motion", value: "reduce" },
+ ] });
+ await cdp.send("Emulation.setDefaultBackgroundColorOverride", { color: BACKDROP[theme] });
+ for (const [name, view] of STATES) {
+ await cdp.send("Emulation.setDeviceMetricsOverride", { width: TALK_PANEL.width, height: TALK_PANEL.maxHeight, deviceScaleFactor: 2, mobile: false });
+ const loaded = cdp.once("Page.loadEventFired");
+ await cdp.send("Page.navigate", { url: page });
+ await loaded;
+ const { result } = await cdp.send("Runtime.evaluate", { expression: `render(${JSON.stringify({ ...view, text: replyPreview(view.text), theme })})`, returnByValue: true });
+ const height = Math.min(TALK_PANEL.maxHeight, Math.max(TALK_PANEL.minHeight, result.value));
+ await cdp.send("Emulation.setDeviceMetricsOverride", { width: TALK_PANEL.width, height, deviceScaleFactor: 2, mobile: false });
+ const { data } = await cdp.send("Page.captureScreenshot", { format: "png" });
+ writeFileSync(join(out, `${theme}-${name}.png`), Buffer.from(data, "base64"));
+ console.log(`${theme}-${name}.png card ${result.value} px, box ${height} px`);
+ }
+ }
+ cdp.close();
+} finally {
+ if (browser.exitCode === null) {
+ const exited = new Promise((resolve) => browser.once("exit", resolve));
+ browser.kill();
+ await exited;
+ }
+ rmSync(scratch, { recursive: true, force: true });
+}
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 21adc9eb96..2b8e5e782a 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -163,6 +163,7 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
if (m && method === "POST") {
const body = await readBody(req);
if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "body must be a JSON object" });
+ if (body.select !== undefined && typeof body.select !== "boolean") return json(res, 400, { error: "select must be a boolean" });
const bot = store.bot(m[1]);
if (!bot) return json(res, 404, { error: "no such bot" });
let cwd: string | undefined;
@@ -191,7 +192,7 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
if (body.projectId !== undefined && (typeof body.projectId !== "string" || !store.project(bot.id, body.projectId))) {
return json(res, 400, { error: "projectId must belong to this bot" });
}
- const task = store.createTask(bot.id, typeof body.title === "string" ? body.title : undefined, true, body.projectId, undefined, body.approvalMode, undefined, cwd);
+ const task = store.createTask(bot.id, typeof body.title === "string" ? body.title : undefined, body.select !== false, body.projectId, undefined, body.approvalMode, undefined, cwd);
if (!task) return json(res, 500, { error: "couldn't create that task" });
// Who opened it decides who may answer its cards on a shared workspace.
if (auth.kind === "session") threadStarters.set(task.threadId, actorKey(auth));
diff --git a/server/talk-server.e2e.test.ts b/server/talk-server.e2e.test.ts
new file mode 100644
index 0000000000..4daf04a732
--- /dev/null
+++ b/server/talk-server.e2e.test.ts
@@ -0,0 +1,51 @@
+import { randomBytes, randomUUID } from "node:crypto";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { createTalkServer, QUICK_ASKS_TITLE, type TalkChat, type TalkUpdate } from "../electron/talk-server.mjs";
+import { launchVerificationServer } from "../scripts/control-omb.ts";
+
+const owner = randomBytes(32).toString("base64url");
+const realFetch = globalThis.fetch;
+let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;
+const request = (route: string, init?: RequestInit) => fetch(`${fixture.info.url}${route}`, init);
+
+beforeAll(async () => {
+ globalThis.fetch = (input, init = {}) => realFetch(input, { ...init, headers: { ...Object.fromEntries(new Headers(init.headers)), "x-openmausbot-desktop-owner": owner } });
+ fixture = await launchVerificationServer({ ...process.env, OMB_TEST_DESKTOP_OWNER_TOKEN: owner });
+}, 90_000);
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ await fixture?.close();
+});
+
+it("asks MausBot in its own Quick asks chat, as the desktop app does, and follows the reply to the end", async () => {
+ let saved: TalkChat | null = null;
+ const talk = createTalkServer({ request, serverKey: () => "fixture", prefs: { quickAsksChat: () => saved, setQuickAsksChat: (_s, chat) => { saved = chat; } } });
+ const before = (await (await request("/api/bots?messages=0")).json() as any).bots.find((b: any) => b.defaultBot);
+ const chat = await talk.prepare();
+ expect(chat.botId).toBe(before.id);
+ const updates: TalkUpdate[] = [];
+ expect(await talk.ask({ chat, text: "What can you do?", sendId: randomUUID(), signal: AbortSignal.timeout(60_000), onUpdate: u => updates.push(u) })).toBe("done");
+ expect(updates[0]).toEqual({ kind: "thinking" });
+ expect(updates.at(-1)).toMatchObject({ kind: "done", ok: true, text: expect.stringContaining("hello from fake claude") });
+ const after = (await (await request("/api/bots?messages=0")).json() as any).bots.find((b: any) => b.id === chat.botId);
+ expect(after.threadId).toBe(before.threadId);
+ expect(after.tasks.find((t: any) => t.threadId === chat.threadId).title).toBe(QUICK_ASKS_TITLE);
+ expect(await talk.prepare()).toEqual(chat);
+}, 90_000);
+
+it("a computer whose bots moved to My Cloud refuses asks with moved, both a new chat and a send to the saved one", async () => {
+ let saved: TalkChat | null = null;
+ const prefs = { quickAsksChat: () => saved, setQuickAsksChat: (_s: string, chat: TalkChat) => { saved = chat; } };
+ const chat = await createTalkServer({ request, serverKey: () => "fixture", prefs }).prepare();
+ expect((await request("/api/move/freeze", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status).toBe(200);
+ try {
+ const fresh = createTalkServer({ request, serverKey: () => "fixture", prefs: { quickAsksChat: () => null, setQuickAsksChat: () => {} } });
+ await expect(fresh.prepare()).rejects.toMatchObject({ name: "TalkServerError", code: "moved" });
+ const talk = createTalkServer({ request, serverKey: () => "fixture", prefs });
+ expect(await talk.prepare()).toEqual(chat);
+ await expect(talk.ask({ chat, text: "Still there?", sendId: randomUUID(), signal: AbortSignal.timeout(30_000), onUpdate: () => {} }))
+ .rejects.toMatchObject({ name: "TalkServerError", code: "moved" });
+ } finally {
+ await request("/api/move/freeze", { method: "DELETE" });
+ }
+}, 90_000);
diff --git a/server/task-select.test.ts b/server/task-select.test.ts
new file mode 100644
index 0000000000..03a248b50e
--- /dev/null
+++ b/server/task-select.test.ts
@@ -0,0 +1,44 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { launchVerificationServer, type VerificationServer } from "../scripts/control-omb.ts";
+
+describe("creating a chat without selecting it", () => {
+ let fixture: VerificationServer;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, {
+ method,
+ headers: { "content-type": "application/json", origin: fixture.info.url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json() as any };
+ };
+
+ beforeAll(async () => {
+ fixture = await launchVerificationServer();
+ }, 90_000);
+
+ afterAll(async () => {
+ await fixture?.close();
+ });
+
+ it("creates a chat without switching the bot's open chat when select is false", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Select fixture" })).body.bot;
+ const created = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Quick asks", select: false });
+ expect(created.status).toBe(201);
+ expect(created.body.task.title).toBe("Quick asks");
+ const after = (await api("GET", "/api/bots?messages=0")).body.bots.find((b: any) => b.id === bot.id);
+ expect(after.threadId).toBe(bot.threadId);
+ expect(after.tasks.map((t: any) => t.threadId)).toContain(created.body.task.threadId);
+ });
+
+ it("still selects a new chat by default", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Default select" })).body.bot;
+ const created = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Picked" });
+ expect((await api("GET", "/api/bots?messages=0")).body.bots.find((b: any) => b.id === bot.id).threadId).toBe(created.body.task.threadId);
+ });
+
+ it("refuses a select that is not a boolean", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Bad select" })).body.bot;
+ expect(await api("POST", `/api/bots/${bot.id}/tasks`, { select: "no" })).toEqual({ status: 400, body: { error: "select must be a boolean" } });
+ });
+});
diff --git a/src/components/LiveCallHost.tsx b/src/components/LiveCallHost.tsx
index f0e9134240..4ac32371fe 100644
--- a/src/components/LiveCallHost.tsx
+++ b/src/components/LiveCallHost.tsx
@@ -1,10 +1,12 @@
import { useEffect } from "react";
+import { useReportCallPresence } from "@/lib/call-presence";
import { isMacPlatform } from "@/lib/keyboard-shortcuts";
import { handleLiveCallKey, onLiveStreamConnected, onServerCall } from "@/lib/live-call-media";
import { useStore } from "@/state/store";
export function LiveCallHost() {
const { state } = useStore();
+ useReportCallPresence();
useEffect(() => onServerCall(state.liveCall), [state.liveCall]);
useEffect(() => onLiveStreamConnected(state.connected), [state.connected]);
useEffect(() => {
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 494bac8fb1..043db0ebe7 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -11,6 +11,7 @@ import { AnalyticsRow } from "./AnalyticsRow";
import { UpdatesConsentRow } from "./UpdatesConsent";
import { OpenAtLoginRow } from "./OpenAtLoginRow";
import { DefaultBotSidebarRow } from "./DefaultBotControls";
+import { TalkShortcutRow, talkShortcutKeywords } from "./TalkShortcutRow";
import { DiagnosticsRow } from "./DiagnosticsRow";
import { DecisionModelSettings } from "./DecisionModelSettings";
import { EnginesSettings } from "./EnginesSettings";
@@ -78,7 +79,7 @@ export const SECTIONS: Array<{
icon: typeof User;
keywords: string[];
}> = [
- { id: "general", group: "you", labelKey: "settings.section.general", icon: User, keywords: ["profile", "name", "email", "about me", "about", "suggestions", "suggested", "memory", "analytics", "updates", "product updates", "newsletter", "email updates", "effort", "new bots", "reasoning", "threads", "parallel", "concurrency", "cleanup", "retention", "event log", "event-log", "log size", "automatic recovery", "backup model", "fallback", "routines", "conversation", "schedule", "usage", "limit", "plan", "upgrade", "cloud desktop hours", "storage"] },
+ { id: "general", group: "you", labelKey: "settings.section.general", icon: User, keywords: ["profile", "name", "email", "about me", "about", "suggestions", "suggested", "memory", "analytics", "updates", "product updates", "newsletter", "email updates", "effort", "new bots", "reasoning", "threads", "parallel", "concurrency", "cleanup", "retention", "event log", "event-log", "log size", "automatic recovery", "backup model", "fallback", "routines", "conversation", "schedule", "usage", "limit", "plan", "upgrade", "cloud desktop hours", "storage", ...talkShortcutKeywords()] },
{ id: "appearance", group: "you", labelKey: "settings.section.appearance", icon: Palette, keywords: ["skin", "theme", "appearance", "chat width", "width", "wide", "full width", "bubble", "bubbles", "tools", "tool calls", "threads", "show threads", "hide threads", "sidebar", "density", "compact", "comfortable", "avatars", "display", "run", "this run", "run card", "commands", "notifications", "sound", "sounds", "mute", "silent", "chime", "pinned", "circles", "universal", "groups", "top", "send", "enter", "return", "shift+enter", "ctrl+enter", "cmd+enter", "⌘+enter", "new line", "keyboard", "ime", "japanese", "message color", "my messages", "toolbar", "tools layout", "footer", "routines", "triggers", "team map", "color", "cloud color", "server color", "tint"] },
{ id: "companion", group: "you", labelKey: "settings.section.companion", icon: TabletSmartphone, keywords: ["companion", "device", "phone", "desktop", "client", "host", "pair", "pairing", "mobile", "https", "secure", "tailscale", "wifi", "remote", "advanced", "domain", "dns", "self-hosted", "server", "caddy"] },
{ id: "engines", group: "ai", labelKey: "settings.section.engines", icon: Terminal, keywords: ["models", "model providers", "engines", "claude", "codex", "grok", "providers", "cli", "sign in", "subscription"] },
@@ -325,6 +326,7 @@ export function SettingsModal() {
<>
<AdvancedModeRow />
<DefaultBotSidebarRow />
+ <TalkShortcutRow />
<ProSettingsCard />
<CloudUsageSettings />
diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsx
index bc8cb41418..daeacd683a 100644
--- a/src/components/SettingsSimplePages.tsx
+++ b/src/components/SettingsSimplePages.tsx
@@ -8,6 +8,7 @@ import { AnalyticsRow } from "./AnalyticsRow";
import { UpdatesConsentRow } from "./UpdatesConsent";
import { OpenAtLoginRow } from "./OpenAtLoginRow";
import { DefaultBotSidebarRow } from "./DefaultBotControls";
+import { TalkShortcutRow } from "./TalkShortcutRow";
import { DiagnosticsRow } from "./DiagnosticsRow";
import { EnginesSettings } from "./EnginesSettings";
import { LocalComputerSection } from "./LocalComputerSection";
@@ -77,6 +78,7 @@ export function SimpleGeneralPage({ has, peopleOpen, onLooks }: { has: Has; peop
<SettingsRows>
<OpenAtLoginRow simple />
<DefaultBotSidebarRow simple />
+ <TalkShortcutRow />
<AnalyticsRow simple />
</SettingsRows>
</SettingsGroup>
diff --git a/src/components/TalkShortcutRow.test.ts b/src/components/TalkShortcutRow.test.ts
new file mode 100644
index 0000000000..8927db48e1
--- /dev/null
+++ b/src/components/TalkShortcutRow.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { TalkShortcutState } from "../../electron/talk-shortcut.mjs";
+import { setLocale } from "@/lib/i18n";
+import { TalkShortcutRow, talkShortcutKeywords } from "./TalkShortcutRow";
+
+const KEYS: TalkShortcutState["keys"] = [
+ { id: "ctrl-opt-space", label: "⌃⌥Space" },
+ { id: "ctrl-shift-space", label: "⌃⇧Space" },
+ { id: "opt-shift-space", label: "⌥⇧Space" },
+];
+const base: TalkShortcutState = { available: true, enabled: true, key: "ctrl-opt-space", keys: KEYS, taken: false };
+let current: TalkShortcutState;
+let bridge: { state: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
+let host: HTMLDivElement;
+let root: Root;
+
+const settle = async () => { for (let i = 0; i < 3; i++) await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); };
+const show = async () => { await act(async () => { root.render(createElement(TalkShortcutRow)); }); await settle(); };
+const toggle = () => host.querySelector<HTMLButtonElement>('button[aria-label="Talk to MausBot from any app"]')!;
+const click = async (element: HTMLElement) => { await act(async () => { element.click(); }); await settle(); };
+
+beforeEach(() => {
+ setLocale("en");
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ current = { ...base };
+ bridge = {
+ state: vi.fn(async () => current),
+ set: vi.fn(async (change: Partial<TalkShortcutState>) => (current = { ...current, ...change })),
+ };
+ (window as unknown as { ogb: unknown }).ogb = { talkShortcut: bridge };
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(async () => { root.unmount(); });
+ host.remove();
+ delete (window as unknown as { ogb?: unknown }).ogb;
+ vi.unstubAllGlobals();
+});
+
+describe("TalkShortcutRow", () => {
+ it("is not shown without the bridge or where Apple speech is unavailable", async () => {
+ (window as unknown as { ogb: unknown }).ogb = {};
+ await show();
+ expect(host.textContent).toBe("");
+ await act(async () => { root.unmount(); });
+ root = createRoot(host);
+ (window as unknown as { ogb: unknown }).ogb = { talkShortcut: bridge };
+ current = { ...base, available: false };
+ await show();
+ expect(host.textContent).toBe("");
+ });
+
+ it("shows the switch on with the key in its subtitle, and turns it off", async () => {
+ await show();
+ expect(host.textContent).toContain("Talk to MausBot from any app");
+ expect(host.textContent).toContain("Hold ⌃⌥Space, speak, let go");
+ await click(toggle());
+ expect(bridge.set).toHaveBeenCalledWith({ enabled: false });
+ expect(toggle().getAttribute("aria-checked")).toBe("false");
+ expect(host.querySelector("select")).toBeNull();
+ });
+
+ it("changes the key and says so", async () => {
+ await show();
+ const select = host.querySelector<HTMLSelectElement>("select")!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")!.set!.call(select, "ctrl-shift-space");
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await settle();
+ expect(bridge.set).toHaveBeenCalledWith({ key: "ctrl-shift-space" });
+ expect(host.textContent).toContain("Hold ⌃⇧Space");
+ });
+
+ it("shows nothing when the setting can't be read, and says so when a change fails, keeping the row as it was", async () => {
+ bridge.state.mockRejectedValueOnce(new Error("no main process"));
+ await show();
+ expect(host.textContent).toBe("");
+ await act(async () => { root.unmount(); });
+ root = createRoot(host);
+ await show();
+ bridge.set.mockRejectedValueOnce(new Error("refused"));
+ await click(toggle());
+ expect(host.querySelector('[role="alert"]')?.textContent).toBe("Could not change this. Try again.");
+ expect(toggle().getAttribute("aria-checked")).toBe("true");
+ expect(toggle().disabled).toBe(false);
+ await click(toggle());
+ expect(host.querySelector('[role="alert"]')).toBeNull();
+ expect(toggle().getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("holds the switch and the key while a change is on its way, so two changes never cross", async () => {
+ let finish!: (state: TalkShortcutState) => void;
+ await show();
+ bridge.set.mockImplementationOnce(() => new Promise<TalkShortcutState>((resolve) => { finish = resolve; }));
+ await click(toggle());
+ expect(toggle().disabled).toBe(true);
+ expect(host.querySelector("select")?.disabled).toBe(true);
+ await act(async () => { finish({ ...base, enabled: false }); });
+ await settle();
+ expect(toggle().disabled).toBe(false);
+ });
+
+ it("is found by search only where the row can show: the Mac app's own page", () => {
+ const mac = { platform: "darwin", talkShortcut: bridge } as unknown as Window["ogb"];
+ expect(talkShortcutKeywords(mac)).toContain("hold to talk");
+ expect(talkShortcutKeywords({ platform: "win32", talkShortcut: bridge } as unknown as Window["ogb"])).toEqual([]);
+ expect(talkShortcutKeywords({ platform: "darwin" } as unknown as Window["ogb"])).toEqual([]);
+ expect(talkShortcutKeywords(undefined)).toEqual([]);
+ });
+
+ it("says when another app holds the key", async () => {
+ current = { ...base, taken: true };
+ await show();
+ expect(host.querySelector('[role="alert"]')?.textContent).toBe("⌃⌥Space is used by another app. Pick another shortcut.");
+ });
+});
diff --git a/src/components/TalkShortcutRow.tsx b/src/components/TalkShortcutRow.tsx
new file mode 100644
index 0000000000..a3874eb85e
--- /dev/null
+++ b/src/components/TalkShortcutRow.tsx
@@ -0,0 +1,50 @@
+import { useEffect, useState } from "react";
+import type { TalkKeyId, TalkShortcutState } from "../../electron/talk-shortcut.mjs";
+import { t } from "@/lib/i18n";
+import { Select } from "./Select";
+import { SettingRow, Switch } from "./SettingsPrimitives";
+
+/** Settings search finds the talk shortcut only where its row can show: this Mac app's own page. */
+export function talkShortcutKeywords(ogb: Window["ogb"] = typeof window === "undefined" ? undefined : window.ogb): string[] {
+ return ogb?.platform === "darwin" && ogb.talkShortcut ? ["talk", "voice", "shortcut", "hotkey", "hold to talk", "push to talk", "quick asks"] : [];
+}
+
+export function TalkShortcutRow() {
+ const bridge = window.ogb?.talkShortcut;
+ const [state, setState] = useState<TalkShortcutState | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [failed, setFailed] = useState(false);
+ useEffect(() => {
+ let live = true;
+ void bridge?.state().then((next) => { if (live) setState(next); }).catch(() => {});
+ return () => { live = false; };
+ }, [bridge]);
+ if (!bridge || !state?.available) return null;
+ const label = state.keys.find((key) => key.id === state.key)?.label ?? "";
+ const change = (next: { enabled?: boolean; key?: TalkKeyId }) => {
+ setBusy(true); setFailed(false);
+ void bridge.set(next).then(setState, () => setFailed(true)).finally(() => setBusy(false));
+ };
+ const problem = failed ? t("settings.talk.failed") : state.enabled && state.taken ? t("settings.talk.taken", { key: label }) : null;
+ const message = (
+ <>
+ {state.enabled && (
+ <Select size="sm" className="w-full max-w-[240px]"
+ value={state.key}
+ disabled={busy}
+ aria-label={t("settings.talk.keyAria")}
+ // SAFETY: the options are rendered from state.keys, so the value is always a member.
+ onChange={(event) => change({ key: event.target.value as TalkKeyId })}
+ >
+ {state.keys.map((key) => <option key={key.id} value={key.id}>{key.label}</option>)}
+ </Select>
+ )}
+ {problem && <div role="alert" className={state.enabled ? "mt-2 text-danger" : "text-danger"}>{problem}</div>}
+ </>
+ );
+ return (
+ <SettingRow title={t("settings.talk.title")} subtitle={t("settings.talk.subtitle", { key: label })} message={state.enabled || problem ? message : null}>
+ <Switch checked={state.enabled} disabled={busy} aria-label={t("settings.talk.aria")} onClick={() => change({ enabled: !state.enabled })} />
+ </SettingRow>
+ );
+}
diff --git a/src/lib/call-presence.test.ts b/src/lib/call-presence.test.ts
new file mode 100644
index 0000000000..e4ed024ee9
--- /dev/null
+++ b/src/lib/call-presence.test.ts
@@ -0,0 +1,39 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { endCall, startCall } from "./call";
+import { callInProgress, useReportCallPresence } from "./call-presence";
+
+let root: Root;
+let host: HTMLDivElement;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ host = document.createElement("div");
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(async () => { root.unmount(); });
+ endCall();
+ delete (window as unknown as { ogb?: unknown }).ogb;
+ vi.unstubAllGlobals();
+});
+
+describe("call presence", () => {
+ it("a turn call or a running Live call is a call", () => {
+ expect(callInProgress(null, "idle")).toBe(false);
+ expect(callInProgress("bot-1", "idle")).toBe(true);
+ for (const phase of ["starting", "live", "ending"] as const) expect(callInProgress(null, phase)).toBe(true);
+ for (const phase of ["ended", "failed"] as const) expect(callInProgress(null, phase)).toBe(false);
+ });
+
+ it("tells main when a call starts and ends, and says none on mount", async () => {
+ const callActive = vi.fn(async () => {});
+ (window as unknown as { ogb: unknown }).ogb = { callActive };
+ await act(async () => { root.render(createElement(() => { useReportCallPresence(); return null; })); });
+ await act(async () => { startCall("bot-1"); });
+ await act(async () => { endCall("bot-1"); });
+ expect(callActive.mock.calls).toEqual([[false], [true], [false]]);
+ });
+});
diff --git a/src/lib/call-presence.ts b/src/lib/call-presence.ts
new file mode 100644
index 0000000000..e668775057
--- /dev/null
+++ b/src/lib/call-presence.ts
@@ -0,0 +1,16 @@
+import { useEffect } from "react";
+import { useOnCall } from "./call";
+import { isLiveCallRunning, useLiveMedia, type LiveMediaPhase } from "./live-call-media";
+
+export function callInProgress(onCall: string | null, phase: LiveMediaPhase): boolean {
+ return onCall !== null || isLiveCallRunning(phase);
+}
+
+export function useReportCallPresence(): void {
+ const onCall = useOnCall();
+ const { phase } = useLiveMedia();
+ const active = callInProgress(onCall, phase);
+ useEffect(() => {
+ void window.ogb?.callActive?.(active);
+ }, [active]);
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 1bd6e65c28..1dd298cf01 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1285,6 +1285,12 @@
"settings.analytics.subtitle": "Anonymous product events and a once-a-day count of what's set up: which providers have a key (never the key) and how many bots, rooms, routines and computers. Never conversations, prompts, file contents, names or addresses. Your email is only attached if you shared it during setup, or if you choose upgrade, manage or compare plans on the Cloud Pro popup while signed in to MausBot Cloud (your Cloud account's email).",
"settings.analytics.link": "See everything it sends",
"settings.analytics.aria": "Send usage analytics",
+ "settings.talk.title": "Talk to MausBot from any app",
+ "settings.talk.subtitle": "Hold {key}, speak, let go. MausBot answers in a small box at the bottom of the screen; click it to open the chat.",
+ "settings.talk.aria": "Talk to MausBot from any app",
+ "settings.talk.keyAria": "Talk shortcut",
+ "settings.talk.taken": "{key} is used by another app. Pick another shortcut.",
+ "settings.talk.failed": "Could not change this. Try again.",
"updatesConsent.title": "Get MausBot updates?",
"updatesConsent.body": "We'll email you about new features and tips, about twice a month. You can unsubscribe any time.",
"updatesConsent.yes": "Yes, send me updates",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 83c4ac1a22..ab783ba09c 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -287,6 +287,10 @@ const __APP_VERSION__: string;
speechStop(): Promise<void>;
/** Finish capture and emit the recognizer's final transcript. */
speechFinish?(): Promise<void>;
+ /** This computer's page only: Settings → General's talk shortcut. */
+ talkShortcut?: import("../../electron/talk-shortcut.mjs").TalkShortcutBridge;
+ /** A call holds the microphone, so the talk shortcut waits. */
+ callActive?(active: boolean): Promise<void>;
onSpeechTranscript(
cb: (line: { partial?: boolean; text?: string; error?: string }) => void,
): () => void;