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
fix(speech): free whisper before quit — an in-flight transcribe was aborting the app
enes3aaca1f9b7e6
diff --git a/src/core/speech/speech-service.test.ts b/src/core/speech/speech-service.test.tsindex 9300a530c..19c166e59 100644--- a/src/core/speech/speech-service.test.ts+++ b/src/core/speech/speech-service.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { mkdtempSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { describeWhisperLoadError, SpeechService, type WhisperEngineHandle } from './speech-service'+import { describeWhisperLoadError, isGgmlModelHeader, SpeechService, type WhisperEngineHandle } from './speech-service'import { WhisperModelStore } from './whisper-models'describe('SpeechService', () => {@@ -71,6 +71,118 @@ describe('SpeechService', () => {})})+describe('SpeechService.shutdown', () => {+ let dir: string+ let models: WhisperModelStore+ const freed: string[] = []+ const pcm = new Float32Array(16000)++ /** An engine whose transcribe is held open until the returned `release` is called —+ * this is the exact state (native transcribe in flight) that aborts the process if+ * the node env is torn down under it. */+ function blockingFactory(): {+ engineFactory: (p: string) => Promise<WhisperEngineHandle>+ release: () => void+ started: () => number+ } {+ let release = (): void => {}+ let started = 0+ const gate = new Promise<void>((r) => { release = r })+ return {+ started: () => started,+ release: () => release(),+ engineFactory: async (modelPath: string) => ({+ transcribe: async () => { started++; await gate; return 'hello world' },+ free: async () => { freed.push(modelPath) },+ }),+ }+ }++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'svc-'))+ models = new WhisperModelStore({ dir })+ freed.length = 0+ writeFileSync(models.modelPath('tiny'), 'x')+ })++ it('frees the loaded engine', async () => {+ const svc = new SpeechService({+ models,+ isPremium: () => true,+ engineFactory: async (modelPath) => ({+ transcribe: async () => 'hi',+ free: async () => { freed.push(modelPath) },+ }),+ })+ await svc.transcribe(pcm, { model: 'tiny', language: 'auto' })+ await svc.shutdown()+ expect(freed).toEqual([models.modelPath('tiny')])+ })++ it('is a no-op when no engine was ever loaded', async () => {+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory: async () => { throw new Error('nope') } })+ await expect(svc.shutdown()).resolves.toBeUndefined()+ expect(freed).toEqual([])+ })++ it('never frees while a transcribe is in flight — the crash guard', async () => {+ const { engineFactory, release } = blockingFactory()+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory })+ const inFlight = svc.transcribe(pcm, { model: 'tiny', language: 'auto' })+ // Let the engine load and the native transcribe start.+ await new Promise((r) => setTimeout(r, 0))++ let settled = false+ const done = svc.shutdown().then(() => { settled = true })+ await new Promise((r) => setTimeout(r, 5))+ expect(freed).toEqual([]) // still transcribing: freeing here is what kills the app+ expect(settled).toBe(false)++ release()+ await expect(inFlight).resolves.toBe('hello world')+ await done+ expect(freed).toEqual([models.modelPath('tiny')]) // freed only after it settled+ })++ it('gives up after the timeout so a stuck transcribe cannot hold quit open', async () => {+ const { engineFactory, release } = blockingFactory()+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory })+ void svc.transcribe(pcm, { model: 'tiny', language: 'auto' }).catch(() => {})+ await new Promise((r) => setTimeout(r, 0))+ await expect(svc.shutdown(10)).resolves.toBeUndefined()+ expect(freed).toEqual([]) // it bailed rather than freeing under a live transcribe+ release()+ })++ it('swallows a rejecting free() — quit must proceed regardless', async () => {+ const svc = new SpeechService({+ models,+ isPremium: () => true,+ engineFactory: async () => ({+ transcribe: async () => 'hi',+ free: async () => { throw new Error('whisper.free blew up') },+ }),+ })+ await svc.transcribe(pcm, { model: 'tiny', language: 'auto' })+ await expect(svc.shutdown()).resolves.toBeUndefined()+ })++ it('refuses new transcriptions afterwards instead of reloading the model', async () => {+ const loads: string[] = []+ const svc = new SpeechService({+ models,+ isPremium: () => true,+ engineFactory: async (modelPath) => {+ loads.push(modelPath)+ return { transcribe: async () => 'hi', free: async () => { freed.push(modelPath) } }+ },+ })+ await svc.shutdown()+ await expect(svc.transcribe(pcm, { model: 'tiny', language: 'auto' })).rejects.toThrow(/shutting down/)+ expect(loads).toEqual([])+ })+})+describe('describeWhisperLoadError', () => {it('recognizes MODULE_NOT_FOUND code', () => {const err = new Error('Cannot find module') as any@@ -103,3 +215,24 @@ describe('describeWhisperLoadError', () => {expect(describeWhisperLoadError(err)).toBe('boom')})})++// whisper.cpp's loader dereferences a null context when a model file fails to load, taking the+// whole process down with SIGSEGV instead of rejecting — so a bad file must never reach it.+describe('isGgmlModelHeader', () => {+ it('accepts the ggml magic (0x67676d6c, "lmgg" on disk)', () => {+ expect(isGgmlModelHeader(Uint8Array.from([0x6c, 0x6d, 0x67, 0x67, 0x99]))).toBe(true)+ })++ it('rejects an HTML error page saved as a .bin', () => {+ expect(isGgmlModelHeader(Buffer.from('<!DOCTYPE html>'))).toBe(false)+ })++ it('rejects a truncated/empty file', () => {+ expect(isGgmlModelHeader(new Uint8Array(0))).toBe(false)+ expect(isGgmlModelHeader(Uint8Array.from([0x6c, 0x6d, 0x67]))).toBe(false)+ })++ it('rejects the big-endian byte order', () => {+ expect(isGgmlModelHeader(Uint8Array.from([0x67, 0x67, 0x6d, 0x6c]))).toBe(false)+ })+})diff --git a/src/core/speech/speech-service.ts b/src/core/speech/speech-service.tsindex b10f31e2e..498fdcda1 100644--- a/src/core/speech/speech-service.ts+++ b/src/core/speech/speech-service.ts@@ -1,3 +1,4 @@+import { open } from 'node:fs/promises'import { whisperModel } from '../../shared/speech'import type { WhisperModelStore } from './whisper-models'@@ -17,6 +18,15 @@ export function describeWhisperLoadError(err: unknown): string {return msg}+/** ggml weights start with GGML_FILE_MAGIC (0x67676d6c, written little-endian, so "lmgg" on+ * disk). Pure — tested. */+export function isGgmlModelHeader(header: Uint8Array): boolean {+ return (+ header.length >= 4 &&+ header[0] === 0x6c && header[1] === 0x6d && header[2] === 0x67 && header[3] === 0x67+ )+}+/** Local dictation via whisper.cpp (smart-whisper). One loaded model at a* time (they are hundreds of MB of RAM); same-model loads dedupe onto one* in-flight promise; transcriptions run FIFO on a promise chain. The Pro@@ -28,6 +38,7 @@ export class SpeechService {private readonly engineFactory: (modelPath: string) => Promise<WhisperEngineHandle>private loaded: { path: string; engine: Promise<WhisperEngineHandle> } | null = nullprivate queue: Promise<unknown> = Promise.resolve()+ private closed = falseconstructor(opts: {models: WhisperModelStore@@ -40,12 +51,45 @@ export class SpeechService {}transcribe(pcm: Float32Array, opts: { model: string; language: string }): Promise<string> {+ // After shutdown, loading a fresh 500MB model is not just wasteful — it re-opens the+ // quit-time crash window (see shutdown), and a late dictation IPC can arrive while the+ // quit flush is still running.+ if (this.closed) return Promise.reject(new Error('Speech is shutting down.'))const run = this.queue.then(() => this.transcribeNow(pcm, opts))// FIFO: the next caller waits for this one, success or failure.this.queue = run.catch(() => {})return run}+ /** Releases the loaded model and stops accepting work — call this on app quit.+ *+ * The ordering is the whole point. smart-whisper runs a transcription on a libuv+ * worker with a ThreadSafeFunction posting segments back to JS; if the main process's+ * node env is torn down while one is in flight, the TSFN callback is dispatched into a+ * dying env, its `Napi::Error` escapes as a C++ exception and std::terminate()s the WHOLE+ * app (SIGABRT, Napi::ThreadSafeFunction::CallJS in the crash report). Quitting with a+ * merely *loaded* engine is fine — it is the in-flight transcribe that kills us. So the+ * free is queued behind the same FIFO as transcriptions and awaited before quit proceeds.+ *+ * `timeoutMs` caps that wait: a wedged whisper must never hold the quit open forever.+ * Bailing on the timeout means quitting into the crash window again, which is strictly+ * no worse than today and much rarer than the common sub-second case. Never rejects. */+ async shutdown(timeoutMs = 5_000): Promise<void> {+ this.closed = true+ const drained = this.queue.then(async () => {+ const loaded = this.loaded+ this.loaded = null+ if (loaded) await loaded.engine.then((e) => e.free())+ })+ this.queue = drained.catch(() => {})+ let timer: ReturnType<typeof setTimeout> | undefined+ await Promise.race([+ drained.catch(() => {}),+ new Promise<void>((resolve) => { timer = setTimeout(resolve, timeoutMs) }),+ ])+ if (timer) clearTimeout(timer) // a live timer would itself delay the quit it is guarding+ }+private async transcribeNow(pcm: Float32Array, opts: { model: string; language: string }): Promise<string> {const info = whisperModel(opts.model)if (!info) throw new Error(`Unknown whisper model: ${opts.model}`)@@ -84,6 +128,24 @@ async function defaultEngineFactory(modelPath: string): Promise<WhisperEngineHan`Local whisper is unavailable (${describeWhisperLoadError(err)}). Try the Cloud engine.`,)}+ // whisper.cpp's loader logs timings through the context it just failed to build+ // (LoadModelWorker::Execute → whisper_print_timings(nullptr)), so a model file it rejects+ // SIGSEGVs the entire process instead of rejecting a promise. Screen the header before the+ // native side ever sees the path: a truncated download or an error page saved as .bin is the+ // realistic corruption, and this turns it into a message. (A file with a valid magic but a+ // corrupt body still reaches the null deref — that one needs an upstream fix.)+ const header = new Uint8Array(4)+ const fh = await open(modelPath, 'r')+ try {+ await fh.read(header, 0, 4, 0)+ } finally {+ await fh.close()+ }+ if (!isGgmlModelHeader(header)) {+ throw new Error(+ `The whisper model file at ${modelPath} is not a valid ggml model (corrupt or incomplete download). Delete and re-download it in Settings → Speech.`,+ )+ }const whisper = new mod.Whisper(modelPath, { gpu: true })return {async transcribe(pcm, language) {diff --git a/src/main/index.ts b/src/main/index.tsindex 0fc8cc08b..d580cf065 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2177,5 +2177,12 @@ app.on('before-quit', (e) => {// a master mid-write used to leave a truncated project.json on the server. The masters are// therefore kept up through the raced flush and dropped on the second before-quit pass.const flush = Promise.allSettled([remoteWorkspaceIO.flush(), ptyManager.killAll()])- void Promise.race([flush, new Promise((r) => setTimeout(r, 1500))]).finally(() => app.quit())+ void Promise.race([flush, new Promise((r) => setTimeout(r, 1500))])+ // Then let whisper go. A dictation still transcribing when Electron tears down the main+ // process's node env aborts the WHOLE app from inside the native addon (SIGABRT in+ // Napi::ThreadSafeFunction::CallJS) — see SpeechService.shutdown. It needs its own budget+ // because the 1500ms cap above is shorter than a transcription, and it costs nothing at+ // all when dictation is idle, which is nearly always.+ .then(() => speechService.shutdown())+ .finally(() => app.quit())})diff --git a/src/server/index.ts b/src/server/index.tsindex fd950867e..9652a5468 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -456,6 +456,9 @@ export async function startServer(sessionReaper.stop()await contextLink.stop()await ptyManager.killAll()+ // Same native hazard as the desktop app: a whisper transcribe still running when the+ // node env is torn down aborts the process. See SpeechService.shutdown.+ await speechService.shutdown()hookServer.stop()}}@@ -499,6 +502,9 @@ export async function startServer(sessionReaper.stop()await contextLink.stop()await ptyManager.killAll()+ // Same native hazard as the desktop app: a whisper transcribe still running when the node+ // env is torn down aborts the process. See SpeechService.shutdown.+ await speechService.shutdown()// Close the loopback hook-server listener (it would otherwise die with the process anyway).hookServer.stop()await new Promise<void>((resolve, reject) => {