Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(speech): preload + real ws-bridge speech API (desktop-dictation Task 9)
enesbc1c32a25eb4
diff --git a/src/preload/index.ts b/src/preload/index.tsindex cd738bd18..4cf10b4ee 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -129,6 +129,27 @@ const api: NodeTerminalApi = {load: () => ipcRenderer.invoke(IPC.settingsLoad),save: (settings) => ipcRenderer.invoke(IPC.settingsSave, settings)},+ speech: {+ // IPC carries the raw Float32 samples as an ArrayBuffer (structured clone; decodePcmPayload's+ // ArrayBuffer branch reads it directly, no re-encoding). A Float32Array view doesn't always+ // span its whole underlying buffer (e.g. a slice of a pooled/recycled buffer upstream), so a+ // non-spanning view is copied first — sending pcm.buffer as-is would leak neighboring bytes+ // (or the wrong region) into the transcription.+ transcribe: (pcm: Float32Array, language?: string) => {+ const spansBuffer = pcm.byteOffset === 0 && pcm.byteLength === pcm.buffer.byteLength+ const buffer = spansBuffer ? pcm.buffer : pcm.slice().buffer+ return ipcRenderer.invoke(IPC.speechTranscribe, { pcm: buffer, language })+ },+ models: () => ipcRenderer.invoke(IPC.speechModels),+ downloadModel: (id: string) => ipcRenderer.invoke(IPC.speechModelDownload, { id }),+ deleteModel: (id: string) => ipcRenderer.invoke(IPC.speechModelDelete, { id }),+ onProgress: (cb) => {+ const handler = (_e: unknown, p: { id: string; pct: number }) => cb(p)+ ipcRenderer.on(IPC.speechProgress, handler)+ return () => ipcRenderer.removeListener(IPC.speechProgress, handler)+ },+ micConsent: () => ipcRenderer.invoke(IPC.speechMicConsent)+ },ssh: {list: () => ipcRenderer.invoke(IPC.sshList),save: (server) => ipcRenderer.invoke(IPC.sshSave, server),diff --git a/src/renderer/bridge/speech-encode.test.ts b/src/renderer/bridge/speech-encode.test.tsnew file mode 100644index 000000000..c8e4d64f4--- /dev/null+++ b/src/renderer/bridge/speech-encode.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from 'vitest'+import { encodePcmForWire } from './speech-encode'++describe('encodePcmForWire', () => {+ it('emits base64 int16 little-endian', () => {+ const b64 = encodePcmForWire(new Float32Array([0, 1, -1]))+ const raw = Buffer.from(b64, 'base64')+ const i16 = new Int16Array(raw.buffer, raw.byteOffset, 3)+ expect(Array.from(i16)).toEqual([0, 32767, -32768])+ })+})diff --git a/src/renderer/bridge/speech-encode.ts b/src/renderer/bridge/speech-encode.tsnew file mode 100644index 000000000..4d87b7eab--- /dev/null+++ b/src/renderer/bridge/speech-encode.ts@@ -0,0 +1,33 @@+// Pure PCM wire-encoder for the browser (Server Edition) speech bridge.+//+// The bridge cannot import `src/core` (it's the Electron-free service core, and the browser+// build must not pull it in either — see `src/core/no-electron.test.ts`'s sibling rule for the+// bridge). So this duplicates the ws-wire half of `src/core/speech/pcm.ts`'s float32<->int16+// convention (documented there: "Electron IPC carries raw Float32 ArrayBuffers, the ws bridge+// carries base64 int16 — half the bytes over JSON") rather than importing it. Keep the two in+// sync if the encoding ever changes; `decodePcmPayload` on the receiving end is the source of+// truth for the wire format.++/** Encode Float32 PCM samples ([-1, 1]) as base64 of little-endian Int16 samples — the format+ * `decodePcmPayload` (src/core/speech/pcm.ts) expects for the string branch of its payload.+ *+ * Uses `btoa`, not Node's `Buffer` — this file runs in the browser (Server Edition), which has+ * no `Buffer` global. */+export function encodePcmForWire(pcm: Float32Array): string {+ const out = new Int16Array(pcm.length)+ for (let i = 0; i < pcm.length; i++) {+ const v = Math.max(-1, Math.min(1, pcm[i]))+ out[i] = Math.round(v < 0 ? v * 32768 : v * 32767)+ }+ // Typed arrays use the platform's native byte order, which is little-endian on every commodity+ // CPU (and thus every desktop/browser build target) — no DataView byte-swap needed.+ const bytes = new Uint8Array(out.buffer, out.byteOffset, out.byteLength)+ // btoa() takes a binary string. String.fromCharCode.apply has an argument-count ceiling (~64k)+ // on some engines, so build it in chunks rather than spreading the whole array at once.+ const CHUNK = 0x8000+ let binary = ''+ for (let i = 0; i < bytes.length; i += CHUNK) {+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK))+ }+ return btoa(binary)+}diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 77a82c27b..995a76a9a 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -1,8 +1,9 @@// Graceful non-terminal stub surface for the browser (Server Edition) build.//-// The real namespaces (`pty`, `workspace`, `settings`, the fs/git/files/context group from-// `buildFilesApi`, and `dialog` from the in-app `dialog-picker`) are provided by the ws-bridge;-// everything else here degrades benignly so the renderer boots without a full Electron preload.+// The real namespaces (`pty`, `workspace`, `settings`, `speech`, the fs/git/files/context group+// from `buildFilesApi`, and `dialog` from the in-app `dialog-picker`) are provided by the+// ws-bridge; everything else here degrades benignly so the renderer boots without a full+// Electron preload.// The exact per-member behavior is the boot-path contract encoded in the Task 7 brief (derived// from a full renderer-boot audit): every `on*` subscription MUST return a callable no-op// unsubscribe (the renderer uses the return value as a React effect cleanup — a missing member or@@ -117,6 +118,7 @@ export function buildStubApi(): Omit<// it, and a '' stub would propose `/worktrees/…` at the filesystem root.| 'userDataDir'| 'presence'+ | 'speech'> {const api = {ssh: {@@ -327,6 +329,7 @@ export function buildStubApi(): Omit<| 'onSubagentActivity'| 'userDataDir'| 'presence'+ | 'speech'>return apidiff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex c70298c97..63c4b9a63 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -28,6 +28,8 @@ import {type PtyCreateOptions,type SettingsApi,type Settings,+ type SpeechApi,+ type SpeechModelInfo,type TmuxStatus,type Workspace,type WorkspaceApi@@ -35,6 +37,7 @@ import {import type { PeerIdentity } from '../../shared/presence'import { buildStubApi } from './stubs'import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'+import { encodePcmForWire } from './speech-encode'import { type FrameTransport, WebSocketFrameTransport } from './frame-transport'type Listener = (...args: unknown[]) => void@@ -436,6 +439,31 @@ export function buildPresenceApi(client: RpcClient): Pick<NodeTerminalApi, 'presreturn { presence }}+/**+ * Build the `speech` namespace over an RpcClient — a REAL implementation (the server registers+ * `registerSpeechIpc` too; see `src/core/speech/register-ipc.ts`), not a stub. The one wire+ * difference from Electron IPC: `decodePcmPayload` (src/core/speech/pcm.ts) accepts EITHER a raw+ * Float32 ArrayBuffer (what the preload sends over structured-clone IPC) OR a base64 string of+ * little-endian Int16 samples (half the bytes over JSON) — this is the string branch, encoded by+ * the pure `encodePcmForWire` helper. `micConsent` resolves `true` locally: the browser's own+ * `getUserMedia` prompt IS the consent gate, so there is nothing for the server to answer (the+ * server-side handler for this channel is stubbed the same way — see src/server/index.ts).+ */+export function buildSpeechApi(client: RpcClient): Pick<NodeTerminalApi, 'speech'> {+ const speech: SpeechApi = {+ transcribe: (pcm, language) =>+ client.request(IPC.speechTranscribe, { pcm: encodePcmForWire(pcm), language }) as Promise<{+ text: string+ }>,+ models: () => client.request(IPC.speechModels) as Promise<SpeechModelInfo[]>,+ downloadModel: (id) => client.request(IPC.speechModelDownload, { id }) as Promise<void>,+ deleteModel: (id) => client.request(IPC.speechModelDelete, { id }) as Promise<void>,+ onProgress: (cb) => client.subscribe(IPC.speechProgress, cb as Listener),+ micConsent: () => Promise.resolve(true)+ }+ return { speech }+}+/*** Build the `claude` namespace over an RpcClient. `cliCaps` is a REAL handler on the server* (`registerClaudeCliIpc` runs in the server shell too), so the browser resolves the very same@@ -566,6 +594,7 @@ export async function installWsBridge(): Promise<boolean> {...buildAgentApi(client),...buildCanvasApi(client),...buildPresenceApi(client),+ ...buildSpeechApi(client),// Only `cliCaps` is real here — the rest of the namespace stays stubbed (see buildClaudeApi).claude: buildClaudeApi(client, stubApi.claude),// Web replacement for the Electron native dialog: an in-app server-directory browser overdiff --git a/src/shared/types.ts b/src/shared/types.tsindex f5326a163..8492baf0e 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -5,6 +5,7 @@ import type { NormalizedAgentEvent } from './agents/normalize'import type { AgentId, AgentPermissionMode, PromptInjectionMode } from './agents/config'import type { GroupWorktree } from './worktree'import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from './presence'+import type { WhisperModelInfo } from './speech'export interface PtyCreateOptions {shell?: string@@ -558,6 +559,30 @@ export interface SettingsApi {save(settings: Settings): Promise<void>}+/** A downloadable whisper model plus its on-disk status, as returned by `speech.models()`. */+export interface SpeechModelInfo extends WhisperModelInfo {+ downloaded: boolean+ /** Actual on-disk size in MB, present only when `downloaded`. */+ sizeMB?: number+}++export interface SpeechApi {+ /** Transcribe a chunk of mono PCM audio (16kHz Float32 samples) to text.+ * `language` is a BCP-47-ish hint or 'auto'; defaults to the user's speech settings. */+ transcribe(pcm: Float32Array, language?: string): Promise<{ text: string }>+ /** List the known whisper models with their download/pro status. */+ models(): Promise<SpeechModelInfo[]>+ /** Download a whisper model to disk (progress via `onProgress`). */+ downloadModel(id: string): Promise<void>+ /** Delete a downloaded whisper model. */+ deleteModel(id: string): Promise<void>+ /** Subscribe to model-download progress (`pct` 0-100). Returns unsubscribe. */+ onProgress(cb: (p: { id: string; pct: number }) => void): () => void+ /** Ask for microphone permission. Electron: OS-level (macOS TCC prompt); browser: always+ * resolves true — the browser's own getUserMedia prompt is not ours to gate. */+ micConsent(): Promise<boolean>+}+export interface SshApi {list(): Promise<import('./ssh').SshServer[]>save(server: import('./ssh').SshServer): Promise<import('./ssh').SshServer[]>@@ -1321,6 +1346,7 @@ export interface NodeTerminalApi {workspace: WorkspaceApidialog: DialogApisettings: SettingsApi+ speech: SpeechApissh: SshApisshProject: SshProjectApisshFs: SshFsApi