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): core speech service — pro gate, model lifecycle, FIFO (desktop-dictation Task 4)
enes14892ff63cca
diff --git a/src/core/speech/speech-service.test.ts b/src/core/speech/speech-service.test.tsnew file mode 100644index 000000000..b6df3b76c--- /dev/null+++ b/src/core/speech/speech-service.test.ts@@ -0,0 +1,72 @@+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 { SpeechService, type WhisperEngineHandle } from './speech-service'+import { WhisperModelStore } from './whisper-models'++describe('SpeechService', () => {+ let dir: string+ let models: WhisperModelStore+ const loads: string[] = []+ const freed: string[] = []++ function factory(result = 'hello world'): (p: string) => Promise<WhisperEngineHandle> {+ return async (modelPath: string) => {+ loads.push(modelPath)+ return {+ transcribe: vi.fn(async () => result),+ free: vi.fn(async () => { freed.push(modelPath) }),+ }+ }+ }+ const pcm = new Float32Array(16000)++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'svc-'))+ models = new WhisperModelStore({ dir })+ loads.length = 0+ freed.length = 0+ writeFileSync(models.modelPath('tiny'), 'x') // "downloaded"+ writeFileSync(models.modelPath('base'), 'x')+ })++ it('transcribes with a free model without premium', async () => {+ const svc = new SpeechService({ models, isPremium: () => false, engineFactory: factory() })+ await expect(svc.transcribe(pcm, { model: 'tiny', language: 'auto' })).resolves.toBe('hello world')+ })++ it('rejects a Pro model without premium — core-side gate', async () => {+ const svc = new SpeechService({ models, isPremium: () => false, engineFactory: factory() })+ await expect(svc.transcribe(pcm, { model: 'base', language: 'auto' }))+ .rejects.toThrow(/requires nodeterm Pro/)+ expect(loads).toHaveLength(0) // never even loads the model+ })++ it('allows Pro models with premium', async () => {+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory: factory() })+ await expect(svc.transcribe(pcm, { model: 'base', language: 'auto' })).resolves.toBe('hello world')+ })++ it('errors when the model is not downloaded', async () => {+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory: factory() })+ await expect(svc.transcribe(pcm, { model: 'small', language: 'auto' }))+ .rejects.toThrow(/Download the/)+ })++ it('reuses one loaded engine and frees it on model switch', async () => {+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory: factory() })+ await svc.transcribe(pcm, { model: 'tiny', language: 'auto' })+ await svc.transcribe(pcm, { model: 'tiny', language: 'auto' })+ expect(loads).toHaveLength(1)+ await svc.transcribe(pcm, { model: 'base', language: 'auto' })+ expect(loads).toHaveLength(2)+ expect(freed).toEqual([models.modelPath('tiny')])+ })++ it('maps an empty transcript to "No speech detected."', async () => {+ const svc = new SpeechService({ models, isPremium: () => true, engineFactory: factory(' ') })+ await expect(svc.transcribe(pcm, { model: 'tiny', language: 'auto' }))+ .rejects.toThrow('No speech detected.')+ })+})diff --git a/src/core/speech/speech-service.ts b/src/core/speech/speech-service.tsnew file mode 100644index 000000000..0d67d0021--- /dev/null+++ b/src/core/speech/speech-service.ts@@ -0,0 +1,86 @@+import { whisperModel } from '../../shared/speech'+import type { WhisperModelStore } from './whisper-models'++export interface WhisperEngineHandle {+ transcribe(pcm: Float32Array, language: string): Promise<string>+ free(): Promise<void>+}++/** 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+ * rule (non-tiny needs premium) is validated HERE, not only in the UI, so a+ * bypassed renderer lock still can't use a paid model. */+export class SpeechService {+ private readonly models: WhisperModelStore+ private readonly isPremium: () => boolean+ private readonly engineFactory: (modelPath: string) => Promise<WhisperEngineHandle>+ private loaded: { path: string; engine: Promise<WhisperEngineHandle> } | null = null+ private queue: Promise<unknown> = Promise.resolve()++ constructor(opts: {+ models: WhisperModelStore+ isPremium: () => boolean+ engineFactory?: (modelPath: string) => Promise<WhisperEngineHandle>+ }) {+ this.models = opts.models+ this.isPremium = opts.isPremium+ this.engineFactory = opts.engineFactory ?? defaultEngineFactory+ }++ transcribe(pcm: Float32Array, opts: { model: string; language: string }): Promise<string> {+ 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+ }++ 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}`)+ if (info.pro && !this.isPremium()) {+ throw new Error(`The ${info.id} model requires nodeterm Pro — the tiny model is free.`)+ }+ if (!(await this.models.has(info.id))) {+ throw new Error(`Download the ${info.id} model in Settings → Speech first.`)+ }+ const path = this.models.modelPath(info.id)+ if (this.loaded && this.loaded.path !== path) {+ const old = this.loaded+ this.loaded = null+ await old.engine.then((e) => e.free()).catch(() => {})+ }+ if (!this.loaded) {+ const engine = this.engineFactory(path)+ this.loaded = { path, engine }+ engine.catch(() => { if (this.loaded?.engine === engine) this.loaded = null })+ }+ const engine = await this.loaded.engine+ const text = (await engine.transcribe(pcm, opts.language)).trim()+ if (!text) throw new Error('No speech detected.')+ return text+ }+}++async function defaultEngineFactory(modelPath: string): Promise<WhisperEngineHandle> {+ let mod: any+ try {+ // @ts-expect-error -- optional native dep, installed in Task 7+ mod = await import('smart-whisper')+ } catch {+ throw new Error(+ 'Local whisper is unavailable on this install (native module failed to load). Try the Cloud engine.',+ )+ }+ const whisper = new mod.Whisper(modelPath, { gpu: true })+ return {+ async transcribe(pcm, language) {+ const task = await whisper.transcribe(pcm, { language: language === 'auto' ? 'auto' : language })+ const result = await task.result+ return (Array.isArray(result) ? result.map((r: any) => r.text).join(' ') : String(result ?? '')).trim()+ },+ async free() {+ await whisper.free()+ },+ }+}