Skip to content

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.

feat(speech): renderer PCM capture via AudioWorklet (desktop-dictation Task 8)

enes9b2bc0638296
diff --git a/src/renderer/lib/pcm-capture.ts b/src/renderer/lib/pcm-capture.ts
new file mode 100644
index 000000000..d92f21e2f
--- /dev/null
+++ b/src/renderer/lib/pcm-capture.ts
@@ -0,0 +1,195 @@
+/**
+ * Renderer-side microphone capture: mono 16 kHz PCM via an AudioWorklet,
+ * with a ScriptProcessorNode fallback for engines that reject
+ * `audioWorklet.addModule` (older/atypical Chromium builds, or a CSP that
+ * somehow blocks it).
+ *
+ * Kept free of React and of any top-level browser-API references so
+ * `concatChunks` stays importable (and testable) under plain Node — only
+ * `PcmCapture`'s methods touch `navigator`/`AudioContext`/etc.
+ *
+ * Deliberately does NOT import `./pcm-worklet` — that file calls the
+ * worklet-global `registerProcessor(...)` at module scope, which only
+ * exists inside an AudioWorkletGlobalScope. Importing it here would run
+ * that call in the renderer's normal window scope (ReferenceError) and,
+ * worse, under this module's own Node-based unit test. The worklet is
+ * instead loaded indirectly by URL (see `startWorklet`), and its processor
+ * name is duplicated as a plain string constant below.
+ */
+
+/** Must match `PCM_WORKLET_NAME` in `./pcm-worklet.ts` (not imported — see file header). */
+const WORKLET_PROCESSOR_NAME = 'pcm-capture'
+
+const CAPTURE_SAMPLE_RATE = 16000
+/** Buffer size for the `ScriptProcessorNode` fallback; 4096 frames @ 16 kHz ≈ 256 ms per chunk. */
+const SCRIPT_PROCESSOR_BUFFER_SIZE = 4096
+
+export const MIC_PERMISSION_DENIED_MESSAGE =
+ 'Microphone access was denied — allow it in System Settings (or your browser site settings) and try again.'
+
+/** Concatenates PCM chunks, in order, into one buffer. Pure — no side effects. */
+export function concatChunks(chunks: Float32Array[]): Float32Array {
+ let total = 0
+ for (const chunk of chunks) total += chunk.length
+ const out = new Float32Array(total)
+ let offset = 0
+ for (const chunk of chunks) {
+ out.set(chunk, offset)
+ offset += chunk.length
+ }
+ return out
+}
+
+/** RMS of a chunk, clamped to [0, 1] (samples are already in [-1, 1], so RMS can't exceed 1). */
+function rms(chunk: Float32Array): number {
+ if (chunk.length === 0) return 0
+ let sumSquares = 0
+ for (let i = 0; i < chunk.length; i++) sumSquares += chunk[i] * chunk[i]
+ return Math.min(1, Math.sqrt(sumSquares / chunk.length))
+}
+
+/**
+ * Captures the default microphone as mono 16 kHz PCM until `stop()`.
+ * One-shot: create a fresh instance per recording (`start()` after a
+ * `stop()`/`cancel()` on the same instance is not supported).
+ */
+export class PcmCapture {
+ private chunks: Float32Array[] = []
+ private lastChunk: Float32Array = new Float32Array(0)
+ private running = false
+
+ private stream: MediaStream | null = null
+ private audioContext: AudioContext | null = null
+ private sourceNode: MediaStreamAudioSourceNode | null = null
+ private workletNode: AudioWorkletNode | null = null
+ private scriptNode: ScriptProcessorNode | null = null
+ /** Silent sink the ScriptProcessorNode fallback routes through — see `startScriptProcessor`. */
+ private scriptSink: GainNode | null = null
+
+ /** Requests the microphone and starts collecting chunks. Idempotent while already running. */
+ async start(): Promise<void> {
+ if (this.running) return
+
+ const stream = await this.acquireStream()
+ const audioContext = new AudioContext({ sampleRate: CAPTURE_SAMPLE_RATE })
+ const sourceNode = audioContext.createMediaStreamSource(stream)
+
+ this.stream = stream
+ this.audioContext = audioContext
+ this.sourceNode = sourceNode
+
+ const onChunk = (chunk: Float32Array): void => {
+ this.lastChunk = chunk
+ this.chunks.push(chunk)
+ }
+
+ try {
+ await this.startWorklet(audioContext, sourceNode, onChunk)
+ } catch {
+ // `addModule` (or worklet construction) failed — fall back to the
+ // deprecated-but-universal ScriptProcessorNode. Same chunk flow.
+ this.startScriptProcessor(audioContext, sourceNode, onChunk)
+ }
+
+ this.running = true
+ }
+
+ /** Stops capture, tears everything down, and returns the concatenated take. */
+ stop(): Float32Array {
+ const result = concatChunks(this.chunks)
+ this.teardown()
+ return result
+ }
+
+ /** Stops capture and tears everything down, discarding whatever was captured. */
+ cancel(): void {
+ this.teardown()
+ }
+
+ /** 0..1 RMS level of the most recently captured chunk, for a live level meter. */
+ level = (): number => rms(this.lastChunk)
+
+ private async acquireStream(): Promise<MediaStream> {
+ try {
+ return await navigator.mediaDevices.getUserMedia({
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }
+ })
+ } catch (err) {
+ if (err instanceof Error && err.name === 'NotAllowedError') {
+ throw new Error(MIC_PERMISSION_DENIED_MESSAGE)
+ }
+ throw err
+ }
+ }
+
+ private async startWorklet(
+ audioContext: AudioContext,
+ sourceNode: MediaStreamAudioSourceNode,
+ onChunk: (chunk: Float32Array) => void
+ ): Promise<void> {
+ // Vite/electron-vite statically recognizes this `new URL(relative,
+ // import.meta.url)` pattern and emits pcm-worklet.ts as its own
+ // same-origin asset, satisfying CSP `worker-src 'self' blob:'`.
+ const workletUrl = new URL('./pcm-worklet.ts', import.meta.url)
+ await audioContext.audioWorklet.addModule(workletUrl)
+
+ const node = new AudioWorkletNode(audioContext, WORKLET_PROCESSOR_NAME, {
+ numberOfInputs: 1,
+ numberOfOutputs: 0,
+ channelCount: 1
+ })
+ node.port.onmessage = (event: MessageEvent<Float32Array>): void => onChunk(event.data)
+ sourceNode.connect(node)
+ this.workletNode = node
+ }
+
+ private startScriptProcessor(
+ audioContext: AudioContext,
+ sourceNode: MediaStreamAudioSourceNode,
+ onChunk: (chunk: Float32Array) => void
+ ): void {
+ const node = audioContext.createScriptProcessor(SCRIPT_PROCESSOR_BUFFER_SIZE, 1, 1)
+ node.onaudioprocess = (event: AudioProcessingEvent): void => {
+ // Copy: `getChannelData` returns a live view that the audio engine
+ // may reuse for the next block.
+ onChunk(event.inputBuffer.getChannelData(0).slice())
+ event.outputBuffer.getChannelData(0).fill(0)
+ }
+ // A ScriptProcessorNode only fires `onaudioprocess` while it's on a path
+ // to the destination. We write silence to its output above, but route
+ // through a zero-gain sink anyway so nothing is ever audible even if a
+ // browser deviates from spec here.
+ const sink = audioContext.createGain()
+ sink.gain.value = 0
+ sourceNode.connect(node)
+ node.connect(sink)
+ sink.connect(audioContext.destination)
+ this.scriptNode = node
+ this.scriptSink = sink
+ }
+
+ private teardown(): void {
+ this.workletNode?.disconnect()
+ this.workletNode = null
+
+ this.scriptNode?.disconnect()
+ this.scriptNode = null
+ this.scriptSink?.disconnect()
+ this.scriptSink = null
+
+ this.sourceNode?.disconnect()
+ this.sourceNode = null
+
+ for (const track of this.stream?.getTracks() ?? []) track.stop()
+ this.stream = null
+
+ if (this.audioContext && this.audioContext.state !== 'closed') {
+ void this.audioContext.close()
+ }
+ this.audioContext = null
+
+ this.running = false
+ this.chunks = []
+ this.lastChunk = new Float32Array(0)
+ }
+}
diff --git a/src/renderer/lib/pcm-chunks.test.ts b/src/renderer/lib/pcm-chunks.test.ts
new file mode 100644
index 000000000..bc4a1dff5
--- /dev/null
+++ b/src/renderer/lib/pcm-chunks.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest'
+import { concatChunks } from './pcm-capture'
+
+describe('concatChunks', () => {
+ it('concatenates in order', () => {
+ const out = concatChunks([new Float32Array([1, 2]), new Float32Array([3])])
+ expect(Array.from(out)).toEqual([1, 2, 3])
+ })
+ it('handles empty input', () => {
+ expect(concatChunks([]).length).toBe(0)
+ })
+})
diff --git a/src/renderer/lib/pcm-worklet.ts b/src/renderer/lib/pcm-worklet.ts
new file mode 100644
index 000000000..21682de26
--- /dev/null
+++ b/src/renderer/lib/pcm-worklet.ts
@@ -0,0 +1,63 @@
+/**
+ * AudioWorkletProcessor that ships raw mono PCM frames to the main thread.
+ *
+ * Runs in the AudioWorkletGlobalScope, not the DOM/window scope: no imports
+ * from the rest of the renderer, no React, nothing that assumes `window`.
+ * The base lib (`lib.dom.d.ts`) does not declare this scope's globals
+ * (`AudioWorkletProcessor`, `registerProcessor`), so they're declared
+ * ambiently below, file-local, rather than widening a shared lib config
+ * for one file.
+ *
+ * Bundling: loaded by `PcmCapture` via
+ * `new URL('./pcm-worklet.ts', import.meta.url)` passed to
+ * `audioContext.audioWorklet.addModule(url)`. electron-vite (Vite) resolves
+ * that `new URL(..., import.meta.url)` pattern at build time and emits this
+ * file as its own same-origin asset — no bundler-specific worker syntax
+ * needed here, unlike the `?worker` Monaco pattern (that instantiates a
+ * `Worker` object; `addModule` wants a URL string/URL to fetch instead). The
+ * asset is served same-origin, which satisfies CSP `worker-src 'self'
+ * blob:'`.
+ */
+
+declare function registerProcessor(
+ name: string,
+ processorCtor: new (options?: unknown) => AudioWorkletProcessorLike
+): void
+
+interface AudioWorkletProcessorLike {
+ process(
+ inputs: Float32Array[][],
+ outputs: Float32Array[][],
+ parameters: Record<string, Float32Array>
+ ): boolean
+}
+
+declare class AudioWorkletProcessor implements AudioWorkletProcessorLike {
+ readonly port: MessagePort
+ constructor()
+ process(
+ inputs: Float32Array[][],
+ outputs: Float32Array[][],
+ parameters: Record<string, Float32Array>
+ ): boolean
+}
+
+/** Name used on both sides of `audioWorklet.addModule` / `new AudioWorkletNode(ctx, name)`. */
+export const PCM_WORKLET_NAME = 'pcm-capture'
+
+class PcmCaptureProcessor extends AudioWorkletProcessor {
+ process(inputs: Float32Array[][]): boolean {
+ const channel0 = inputs[0]?.[0]
+ // No input yet (device warming up) or the graph was torn down mid-block —
+ // keep the processor alive rather than posting nothing.
+ if (channel0 && channel0.length > 0) {
+ // The Float32Array Web Audio hands us is a scratch buffer the engine
+ // reuses next block — copy it (structured clone across postMessage
+ // does this too, but .slice() makes the ownership explicit here).
+ this.port.postMessage(channel0.slice())
+ }
+ return true
+ }
+}
+
+registerProcessor(PCM_WORKLET_NAME, PcmCaptureProcessor)