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): whisper model store with fenced downloads (desktop-dictation Task 3)
enesb4237b990cf6
diff --git a/src/core/speech/whisper-models.test.ts b/src/core/speech/whisper-models.test.tsnew file mode 100644index 000000000..f60768104--- /dev/null+++ b/src/core/speech/whisper-models.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { WhisperModelStore } from './whisper-models'++function fakeFetch(body: Uint8Array, opts: { delayMs?: number; chunks?: number } = {}) {+ const { delayMs = 0, chunks = 2 } = opts+ return (async (_url: any, init?: any) => {+ const size = Math.ceil(body.length / chunks)+ let sent = 0+ const stream = new ReadableStream<Uint8Array>({+ async pull(controller) {+ if (init?.signal?.aborted) { controller.error(new Error('aborted')); return }+ if (delayMs) await new Promise((r) => setTimeout(r, delayMs))+ if (sent >= body.length) { controller.close(); return }+ controller.enqueue(body.subarray(sent, sent + size))+ sent += size+ },+ })+ return {+ ok: true, status: 200,+ headers: new Headers({ 'content-length': String(body.length) }),+ body: stream,+ } as unknown as Response+ }) as typeof fetch+}++describe('WhisperModelStore', () => {+ let dir: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'wms-')) })+ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })++ it('downloads a model, reports progress, and lists it', async () => {+ const seen: number[] = []+ const store = new WhisperModelStore({+ dir, fetchFn: fakeFetch(new Uint8Array(64).fill(7)),+ onProgress: (_id, pct) => seen.push(pct),+ })+ await store.download('tiny')+ expect(await store.has('tiny')).toBe(true)+ expect(readFileSync(store.modelPath('tiny')).length).toBe(64)+ expect(seen.at(-1)).toBe(100)+ const listed = (await store.list()).find((m) => m.id === 'tiny')+ expect(listed?.downloaded).toBe(true)+ })++ it('rejects unknown model ids', async () => {+ const store = new WhisperModelStore({ dir, fetchFn: fakeFetch(new Uint8Array(1)) })+ await expect(store.download('nope')).rejects.toThrow(/unknown/i)+ })++ it('dedupes a concurrent download of the same id onto one promise', async () => {+ const store = new WhisperModelStore({ dir, fetchFn: fakeFetch(new Uint8Array(64), { delayMs: 20 }) })+ const a = store.download('tiny')+ const b = store.download('tiny')+ expect(a).toBe(b)+ await a+ })++ it('delete mid-download cancels — no file, no resurrection', async () => {+ const store = new WhisperModelStore({ dir, fetchFn: fakeFetch(new Uint8Array(1024), { delayMs: 30, chunks: 8 }) })+ const dl = store.download('tiny')+ await new Promise((r) => setTimeout(r, 40)) // let the first chunk land+ await store.delete('tiny')+ await expect(dl).rejects.toThrow()+ await new Promise((r) => setTimeout(r, 120)) // late chunks must not revive anything+ expect(await store.has('tiny')).toBe(false)+ expect(existsSync(store.modelPath('tiny') + '.part')).toBe(false)+ })+})diff --git a/src/core/speech/whisper-models.ts b/src/core/speech/whisper-models.tsnew file mode 100644index 000000000..dd1d653ad--- /dev/null+++ b/src/core/speech/whisper-models.ts@@ -0,0 +1,100 @@+import { createWriteStream } from 'node:fs'+import { mkdir, rename, rm, stat } from 'node:fs/promises'+import { join } from 'node:path'+import { Writable } from 'node:stream'+import { WHISPER_DOWNLOAD_BASE, WHISPER_MODELS, whisperModel } from '../../shared/speech'++/** Downloads and manages the local ggml whisper models. The fences here are+ * lessons already paid for on iOS: a download streams to `<file>.part` and+ * renames only on completion; delete() aborts an in-flight download and a+ * late chunk can never resurrect a deleted model; concurrent download() of+ * the same id joins the same promise instead of racing two writers. */+export class WhisperModelStore {+ private readonly dir: string+ private readonly fetchFn: typeof fetch+ private readonly onProgress?: (id: string, pct: number) => void+ private readonly inFlight = new Map<string, { promise: Promise<void>; abort: AbortController }>()++ constructor(opts: { dir: string; fetchFn?: typeof fetch; onProgress?: (id: string, pct: number) => void }) {+ this.dir = opts.dir+ this.fetchFn = opts.fetchFn ?? fetch+ this.onProgress = opts.onProgress+ }++ modelPath(id: string): string {+ const info = whisperModel(id)+ return join(this.dir, info ? info.file : `${id}.bin`)+ }++ async has(id: string): Promise<boolean> {+ try { await stat(this.modelPath(id)); return true } catch { return false }+ }++ async list(): Promise<Array<{ id: string; downloaded: boolean; sizeMB?: number }>> {+ const out: Array<{ id: string; downloaded: boolean; sizeMB?: number }> = []+ for (const m of WHISPER_MODELS) {+ try {+ const s = await stat(this.modelPath(m.id))+ out.push({ id: m.id, downloaded: true, sizeMB: Math.round(s.size / 1_000_000) })+ } catch {+ out.push({ id: m.id, downloaded: false })+ }+ }+ return out+ }++ download(id: string): Promise<void> {+ const existing = this.inFlight.get(id)+ if (existing) return existing.promise+ const info = whisperModel(id)+ if (!info) return Promise.reject(new Error(`unknown whisper model: ${id}`))+ const abort = new AbortController()+ const promise = this.run(id, info.file, abort).finally(() => {+ // Only clear our own slot — a delete already removed it.+ if (this.inFlight.get(id)?.abort === abort) this.inFlight.delete(id)+ })+ this.inFlight.set(id, { promise, abort })+ return promise+ }++ private async run(id: string, file: string, abort: AbortController): Promise<void> {+ await mkdir(this.dir, { recursive: true })+ const partPath = this.modelPath(id) + '.part'+ const res = await this.fetchFn(WHISPER_DOWNLOAD_BASE + file, { signal: abort.signal })+ if (!res.ok || !res.body) throw new Error(`model download failed (${res.status})`)+ const total = Number(res.headers.get('content-length')) || 0+ let received = 0+ const sink = createWriteStream(partPath)+ try {+ const reader = res.body.getReader()+ const writer = Writable.toWeb(sink).getWriter()+ for (;;) {+ const { done, value } = await reader.read()+ if (abort.signal.aborted) throw new Error('download cancelled')+ if (done) break+ await writer.write(value)+ received += value.byteLength+ if (total) this.onProgress?.(id, Math.min(99, Math.round((received / total) * 100)))+ }+ await writer.close()+ if (abort.signal.aborted) throw new Error('download cancelled')+ await rename(partPath, this.modelPath(id))+ this.onProgress?.(id, 100)+ } catch (err) {+ sink.destroy()+ await rm(partPath, { force: true })+ throw err+ }+ }++ async delete(id: string): Promise<void> {+ const inFlight = this.inFlight.get(id)+ if (inFlight) {+ this.inFlight.delete(id)+ inFlight.abort.abort()+ await inFlight.promise.catch(() => {}) // wait out the writer's cleanup+ }+ await rm(this.modelPath(id), { force: true })+ await rm(this.modelPath(id) + '.part', { force: true })+ }+}