Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

41.0 KB
Raw Blame
import { AUDIO_SPEAKER } from '../src/shared/audioUpload'
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Capture, encodeFrame, hookCapture, setMicMuted, setRecordingPaused, recordingFinished, type CaptureProc } from '../src/main/capture'
import { liveSilentMs, hookTranscription, transcribeRecorded, settleTranscription, transcriptPartials, speechLocaleFor, spokenChanged, stopTranscriptionServer, transcribing, releaseIdleSpeech } from '../src/main/asr'
import type { Spoken } from '../src/shared/spoken'
import type { TranscriptPartial } from '../src/shared/types'
import { openStore, type Meeting, type Store } from '../src/main/store'
import type { Line } from '../src/main/asr/transcribe'
import { aec3 } from '../src/main/asr/aec3'
import type { Chunk } from '../src/main/asr/chunker'

// these tests are about the session around the pipeline; the echo canceller is tested on its own (aec.test.ts), and its
// work on minutes of test audio would only make them slow on CI
vi.mock('../src/main/asr/aec3', () => ({ loadAec3: async () => {}, aec3: vi.fn(() => null) }))

const RATE = 16000
const tone = (sec: number) => Float32Array.from({ length: Math.round(sec * RATE) }, (_, i) => 0.3 * Math.sin(i / 10))
const tick = () => new Promise((r) => setTimeout(r, 15))

/** a stand-in recorder process: frames go in through `out`, 'stop' on stdin ends it */
function fakeProc() {
  const ev = new EventEmitter(), out = new PassThrough(), stdin = new PassThrough()
  /** what the recorder still sends after it is asked to stop (the real one flushes its last buffers), before it exits */
  const f = { lastWords: undefined as (() => void) | undefined }
  stdin.on('data', (d: Buffer) => {
    if (!d.toString().includes('stop')) return
    if (!f.lastWords) { setImmediate(() => ev.emit('exit', 0, null)); return }
    setTimeout(() => { f.lastWords!(); setTimeout(() => ev.emit('exit', 0, null), 30) }, 30)
  })
  const proc: CaptureProc = { stdout: out, stdin, on: (e, fn) => { ev.on(e, fn); return proc }, kill: () => { ev.emit('exit', null, 'SIGKILL'); return true } }
  return Object.assign(f, {
    proc, exit: (code: number | null, sig: NodeJS.Signals | null = null) => ev.emit('exit', code, sig),
    /** one phrase: 1 s of tone then 1 s of quiet, from meeting time `ms` */
    say: (track: 'me' | 'them', ms: number) => {
      const all = Float32Array.from([...tone(1), ...new Float32Array(RATE)])
      for (let i = 0; i < all.length; i += 1600) out.write(encodeFrame({ t: 'pcm', track, ms: ms + i / 16, samples: all.subarray(i, i + 1600) }))
    },
  })
}

let store: Store
beforeEach(() => { store = openStore(':memory:') })
const meeting = (source?: string): Meeting => store.createMeeting({ source, title: 't', startedAt: 1, endedAt: null, eventId: null, app: null, attendees: [], state: 'recording' })
const says = (c: Chunk): Line[] => [{ track: c.track, startMs: c.startMs, endMs: c.startMs + 1000, text: `${c.track} said it at ${c.startMs}` }]

const disposers: Array<() => void> = []
afterEach(async () => { disposers.splice(0).forEach((d) => d()); await settleTranscription(2000); stopTranscriptionServer() })

/** both hooks over one shared start/stop fan-out, registered in the order asked for */
function rig(order: 'capture-first' | 'transcription-first', t: { transcriber?: (c: Chunk, heard?: (language: string, chars: number) => void, opts?: { partial?: boolean }) => Promise<Line[]> | Line[]; sendPartial?: (p: TranscriptPartial) => void; modelPath?: () => string | undefined; refresh?: (id: string) => void; holdMs?: number; queued?: (id: string) => void } = {}) {
  const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []
  const onStart = (fn: (m: Meeting) => void) => { starts.push(fn); return () => {} }
  const onStop = (fn: (m: Meeting) => void) => { stops.push(fn); return () => {} }
  const procs: ReturnType<typeof fakeProc>[] = []
  const sent: string[] = [], warns: string[] = []
  const hookT = () => disposers.push(hookTranscription({
    store, modelPath: t.modelPath ?? (() => '/model.bin'), send: (s) => sent.push(`${s.track}:${s.text}`), warn: (c) => warns.push(c),
    sendPartial: t.sendPartial, refresh: t.refresh, holdMs: t.holdMs, queued: t.queued, transcriber: 'transcriber' in t ? t.transcriber : async (c) => says(c), onStart, onStop, pidFile: undefined,
  }))
  const hookC = () => hookCapture({
    dirOf: (id) => `/m/${id}`, onStart, onStop, stopMeeting: (id) => stops.forEach((f) => f({ id } as Meeting)),
    start: (_d, o) => { const f = fakeProc(); procs.push(f); return new Capture(f.proc, { startMs: o?.startMs }) }, join: async () => {},
  })
  if (order === 'capture-first') { hookC(); hookT() } else { hookT(); hookC() }
  return {
    procs, sent, warns,
    begin: (m: Meeting) => starts.forEach((f) => f(m)),
    stop: async (m: Meeting) => { stops.forEach((f) => f(m)); procs.at(-1)!.exit(0); await recordingFinished(m.id); await settleTranscription(5000) },
    /** the way the app stops: the recorder is asked to, flushes its last audio and exits on its own */
    stopGently: async (m: Meeting) => { stops.forEach((f) => f(m)); await recordingFinished(m.id); await settleTranscription(5000) },
  }
}

describe('live transcription of a meeting', () => {
  it('keeps the visible mic words until a delayed final replaces them while muted', async () => {
    const shown: string[] = []
    let finish!: (lines: Line[]) => void
    const r = rig('transcription-first', { holdMs: 0, sendPartial: part => {
      if (part.track === 'me') shown.push(part.text || r.sent.at(-1) || '')
    }, transcriber: (c, _hear, opts) => opts?.partial
      ? [{ track: c.track, startMs: 150, endMs: 800, text: 'Testing testing' }]
      : new Promise(resolve => { finish = resolve }) })
    const m = meeting()
    r.begin(m)
    const out = r.procs[0].proc.stdout as PassThrough
    try {
      r.procs[0].say('me', 0)
      await tick()
      expect(shown).toEqual(['Testing testing'])
      setMicMuted(m.id, true); out.write(encodeFrame({ t: 'mic-muted', id: 1, muted: true, ms: 2000 }))
      expect(transcriptPartials().find(p => p.track === 'me')?.text).toBe('Testing testing')
      finish([{ track: 'me', startMs: 80, endMs: 1000, text: 'Testing, testing.' }])
      await expect.poll(() => shown).toEqual(['Testing testing', 'Testing testing', 'me:Testing, testing.'])
      expect(r.sent).toEqual(['me:Testing, testing.'])
    } finally { await r.stop(m) }
  })

  it('finishes the mic audio still buffered by echo cancellation while muted', async () => {
    const shown: string[] = []
    vi.mocked(aec3).mockReturnValue({ analyze() {}, process(input, output) { output.set(input) }, free() {} })
    const clock = vi.spyOn(performance, 'now')
    clock.mockReturnValue(0)
    const r = rig('transcription-first', { holdMs: 0, sendPartial: p => {
      if (p.track === 'me') shown.push(p.text || r.sent.at(-1) || '')
    }, transcriber: (c, _hear, opts) => [{ track: c.track, startMs: opts?.partial ? 150 : 80, endMs: c.startMs + c.samples.length / 16,
      text: opts?.partial ? 'Testing testing' : 'Testing, testing.' }] })
    const m = meeting()
    r.begin(m)
    const out = r.procs[0].proc.stdout as PassThrough
    try {
      out.write(encodeFrame({ t: 'pcm', track: 'them', ms: 0, samples: new Float32Array(800 * 16) }))
      out.write(encodeFrame({ t: 'pcm', track: 'me', ms: 0, samples: tone(0.9) }))
      await tick()
      expect(shown).toEqual(['Testing testing'])
      setMicMuted(m.id, true); out.write(encodeFrame({ t: 'mic-muted', id: 1, muted: true, ms: 900 }))
      out.write(encodeFrame({ t: 'pcm', track: 'me', ms: 900, samples: tone(1) }))
      clock.mockReturnValue(3000)
      out.write(encodeFrame({ t: 'level', me: 0, them: 0 }))
      await expect.poll(() => shown).toEqual(['Testing testing', 'Testing testing', 'me:Testing, testing.'])
      expect(store.segments(m.id)).toMatchObject([{ startMs: 80, endMs: 900 }])
    } finally { clock.mockRestore(); vi.mocked(aec3).mockReturnValue(null); await r.stop(m) }
  })

  it('reads both sides of a brief mute separately on the original recording clock', async () => {
    const clips: Array<[number, number]> = []
    const r = rig('transcription-first', { transcriber: c => {
      clips.push([c.startMs, c.samples.length / 16])
      return says(c)
    } })
    const m = meeting()
    r.begin(m)
    const out = r.procs[0].proc.stdout as PassThrough
    out.write(encodeFrame({ t: 'pcm', track: 'me', ms: 0, samples: tone(0.4) }))
    setMicMuted(m.id, true); out.write(encodeFrame({ t: 'mic-muted', id: 1, muted: true, ms: 400 }))
    setMicMuted(m.id, false); out.write(encodeFrame({ t: 'mic-muted', id: 2, muted: false, ms: 450 }))
    out.write(encodeFrame({ t: 'pcm', track: 'me', ms: 450, samples: tone(0.4) }))
    out.write(encodeFrame({ t: 'pcm', track: 'me', ms: 850, samples: new Float32Array(RATE * 1.2) }))
    await r.stop(m)
    expect(clips.map(([start]) => start)).toEqual([0, 450])
    expect(clips[0][1]).toBe(400)
    expect(clips[1][1]).toBeGreaterThanOrEqual(400)
  })

  it('finishes eligible pre-mute words but fences a delayed Whisper partial after unmute', async () => {
    const parts: TranscriptPartial[] = []
    let finishRead!: (lines: Line[]) => void
    const r = rig('transcription-first', { sendPartial: p => parts.push(p), transcriber: (chunk, _hear, opts) =>
      opts?.partial ? new Promise(resolve => { finishRead = resolve }) : says(chunk) })
    const m = meeting()
    r.begin(m)
    const out = r.procs[0].proc.stdout as PassThrough
    try {
      out.write(encodeFrame({ t: 'pcm', track: 'me', ms: 0, samples: tone(0.9) }))
      expect(finishRead).toBeTypeOf('function')
      setMicMuted(m.id, true); out.write(encodeFrame({ t: 'mic-muted', id: 1, muted: true, ms: 900 }))
      setMicMuted(m.id, false); out.write(encodeFrame({ t: 'mic-muted', id: 2, muted: false, ms: 950 }))
      finishRead([{ track: 'me', startMs: 0, endMs: 800, text: 'Old partial' }])
      await tick()
      expect(parts.every(p => !p.text.includes('Old partial'))).toBe(true)
    } finally { await r.stop(m) }
    expect(r.sent).toEqual(['me:me said it at 0'])
  })

  it('only clears pending audio after transcription saves, and retains older unfinished sessions', async () => {
    const r = rig('transcription-first'), m = meeting()
    r.begin(m)
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
    r.procs[0].say('them', 500)
    await r.stop(m)
    expect(store.segments(m.id).length).toBeGreaterThan(0)
    expect(store.meeting(m.id)?.transcriptionPending).not.toBe(true)
    store.updateMeeting(m.id, { transcriptionPending: true })
    r.begin(m); r.procs[1].say('them', 500)
    await r.stop(m)
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
  })
  it('keeps audio pending when a transcript write fails', async () => {
    const r = rig('transcription-first'), m = meeting()
    r.begin(m)
    const save = vi.spyOn(store, 'addSegments').mockImplementation(() => { throw new Error('disk full') })
    r.procs[0].say('them', 500)
    await r.stop(m)
    save.mockRestore()
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
  })
  it('a resumed recording spells new words from the current invite without rewriting retained transcript', async () => {
    const r = rig('transcription-first', { transcriber: (c) => [{ track: c.track, startMs: c.startMs, endMs: c.startMs + 1000, text: 'Zentric ships Tuesday.' }] })
    const m = meeting()
    store.updateMeeting(m.id, { attendees: [{ name: 'Ann Lee', email: '[email protected]' }] })
    store.addSegments([{ meetingId: m.id, track: 'them', startMs: 0, endMs: 1000, text: 'Earlier Zentric discussion.', speaker: null }])
    const prior = store.segments(m.id)
    r.begin(m)
    r.procs[0].say('them', 5000)
    await tick()
    await r.stop(m)
    const all = store.segments(m.id)
    expect(all.slice(0, prior.length)).toEqual(prior)
    expect(all.at(-1)?.text).toBe('Zentrik ships Tuesday.')
    expect(r.sent).toEqual(['them:Zentrik ships Tuesday.'])
  })

  // index.ts hooks transcription before capture: its "meeting stopped" runs first, before the recorder is told to stop
  it('the last words the recorder sends after Stop are kept (the app\'s hook order)', async () => {
    const r = rig('transcription-first')
    const m = meeting()
    r.begin(m)
    r.procs[0].say('me', 500)
    r.procs[0].lastWords = () => r.procs[0].say('them', 4000)
    await tick()
    await r.stopGently(m)
    expect(store.segments(m.id).map((x) => x.text)).toEqual(['me said it at 500', 'them said it at 4000'])
  })

  it('when the transcript is done, the language most of it was in is saved on the meeting', async () => {
    const r = rig('transcription-first', { transcriber: (c, heard) => { heard?.(c.track === 'them' ? 'spanish' : 'english', c.track === 'them' ? 50 : 10); return says(c) } })
    const m = meeting()
    r.begin(m)
    r.procs[0].say('me', 500)
    r.procs[0].say('them', 5000)
    await tick()
    await r.stop(m)
    expect(store.meeting(m.id)!.language).toBe('spanish')
  })

  for (const order of ['capture-first', 'transcription-first'] as const) {
    it(`start, audio, stop saves and sends the lines (${order})`, async () => {
      const r = rig(order)
      const m = meeting()
      r.begin(m)
      r.procs[0].say('me', 500)
      r.procs[0].say('them', 5000)
      await tick()
      await r.stop(m)
      const segs = store.segments(m.id)
      expect(segs.map((s) => [s.track, s.speaker, s.text])).toEqual([['me', 'me', 'me said it at 500'], ['them', null, 'them said it at 5000']])
      expect(r.sent.sort()).toEqual(['me:me said it at 500', 'them:them said it at 5000'])
      expect(transcribing()).toBe(false)
    })
  }

  for (const resumed of [false, true]) it(`after the meeting, echoes are swept out without changing prior transcript (${resumed ? 'resumed' : 'new'})`, async () => {
    const refreshed: string[] = []
    // whisper hears the same words on both tracks; the them chunk takes long, so the me line is saved before it arrives
    const slow = async (c: Chunk): Promise<Line[]> => {
      if (c.track === 'them') await new Promise((r) => setTimeout(r, 120))
      return [{ track: c.track, startMs: c.startMs, endMs: c.startMs + 1000, text: 'we should move the launch to friday' }]
    }
    const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []
    const procs: ReturnType<typeof fakeProc>[] = []
    hookCapture({ dirOf: (id) => `/m/${id}`, onStart: (fn) => { starts.push(fn); return () => {} }, onStop: (fn) => { stops.push(fn); return () => {} }, stopMeeting: () => {}, start: () => { const f = fakeProc(); procs.push(f); return new Capture(f.proc) }, join: async () => {} })
    disposers.push(hookTranscription({ store, modelPath: () => '/model.bin', send: () => {}, warn: () => {}, refresh: (id) => refreshed.push(id), transcriber: slow, holdMs: 20, extraWaitMs: 20, onStart: (fn) => { starts.push(fn); return () => {} }, onStop: (fn) => { stops.push(fn); return () => {} }, pidFile: undefined }))
    const m = meeting()
    // A retained line at the session boundary must not be reclassified by new audio.
    if (resumed) store.addSegments([{ meetingId: m.id, track: 'me', startMs: 1400, endMs: 2400, text: 'we should move the launch to friday', speaker: 'me' }])
    const prior = store.segments(m.id), priorIds = new Set(prior.map((s) => s.id))
    starts.forEach((f) => f(m))
    expect(procs).toHaveLength(1)
    procs[0].say('me', 1200)
    // the me line is out (the hold is over, the release timer ran) before their chunk has even been heard
    await expect.poll(() => store.segments(m.id).filter((s) => !priorIds.has(s.id)).map((s) => s.track), { timeout: 2000 }).toEqual(['me'])
    procs[0].say('them', 1000)
    // and the rest of the meeting: their voice on the mic a little late, so the audio says echo is present
    for (let k = 1; k < 14; k++) { procs[0].say('them', k * 2000 + 1000); procs[0].say('me', k * 2000 + 1200) }
    await new Promise((r) => setTimeout(r, 400))
    stops.forEach((f) => f(m))
    await recordingFinished(m.id)
    await settleTranscription(15_000)
    // the copy is hidden, not gone
    expect(store.segments(m.id).filter((s) => !priorIds.has(s.id) && s.startMs < 2000).map((s) => s.track)).toEqual(['them'])
    expect(store.segments(m.id, { hidden: true }).filter((s) => !priorIds.has(s.id) && s.startMs < 2000).map((s) => [s.track, s.hidden])).toEqual([['them', false], ['me', true]])
    expect(store.segments(m.id).filter((s) => priorIds.has(s.id))).toEqual(prior)
    expect(new Set(refreshed)).toEqual(new Set([m.id]))
  })

  it('a restarted recorder keeps feeding the same meeting', async () => {
    const r = rig('transcription-first')
    const m = meeting()
    r.begin(m)
    r.procs[0].say('them', 500)
    await tick()
    r.procs[0].exit(null, 'SIGKILL')
    expect(r.procs).toHaveLength(2)
    r.procs[1].say('them', 10_000)
    await tick()
    await r.stop(m)
    expect(store.segments(m.id).map((s) => s.startMs)).toEqual([500, 10_000])
  })

  it('tells once per meeting when chunks fail, and again in the next meeting', async () => {
    const r = rig('capture-first', { transcriber: async () => { throw new Error('boom') } })
    const a = meeting()
    r.begin(a)
    r.procs[0].say('them', 500); r.procs[0].say('them', 4000)
    await tick()
    await r.stop(a)
    expect(r.warns).toEqual(['transcribe-failed'])
    expect(store.meeting(a.id)?.transcriptionPending).toBe(true)
    const b = meeting()
    r.begin(b)
    r.procs[1].say('them', 500)
    await tick()
    await r.stop(b)
    expect(r.warns).toEqual(['transcribe-failed', 'transcribe-failed'])
  })

  it('without a speech model the meeting still records, and says so once', async () => {
    const r = rig('transcription-first', { transcriber: undefined, modelPath: () => undefined })
    // no injected transcriber: the real path is taken, and it finds no model
    const m = meeting()
    r.begin(m)
    r.procs[0].say('me', 500)
    await new Promise((res) => setTimeout(res, 700))
    expect(r.warns).toEqual(['no-speech-model'])
    await r.stop(m)
    expect(store.segments(m.id)).toEqual([])
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
  })
})

describe('whisper-server between meetings', () => {
  const wait = (ms: number) => new Promise((r) => setTimeout(r, ms))
  function fakeServers() {
    const made: Array<{ urls: number; stops: number }> = []
    const make = () => {
      const rec = { urls: 0, stops: 0 }
      made.push(rec)
      return { url: async () => { rec.urls++; return 'http://127.0.0.1:1' }, resetBudget: () => {}, gpuAgain: () => false, timeoutMs: () => 30_000, timed: () => {}, tooSlow: false, cpuRtf: null, wedged: async () => 'http://127.0.0.1:1', alive: async () => true, kill: () => {}, stop: async () => { rec.stops++ } } as unknown as import('../src/main/asr/server').WhisperServer
    }
    return { made, make }
  }
  function hooks(server: () => import('../src/main/asr/server').WhisperServer, idleMs: number) {
    const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []
    disposers.push(hookTranscription({
      store, modelPath: () => '/model.bin', send: () => {}, warn: () => {}, server, serverIdleMs: idleMs,
      onStart: (fn) => { starts.push(fn) }, onStop: (fn) => { stops.push(fn) },
    }))
    return { begin: (m: Meeting) => starts.forEach((f) => f(m)), end: async (m: Meeting) => { stops.forEach((f) => f(m)); await settleTranscription(2000) } }
  }

  it('starts (warms up) when a meeting starts, stops a while after the last one, and starts again for the next', async () => {
    const s = fakeServers()
    const h = hooks(s.make, 60)
    const a = meeting()
    h.begin(a)
    expect(s.made).toHaveLength(1)
    expect(s.made[0].urls).toBe(1)
    await h.end(a)
    await wait(20)
    expect(s.made[0].stops).toBe(0)
    await wait(80)
    expect(s.made[0].stops).toBe(1)
    const b = meeting()
    h.begin(b)
    expect(s.made).toHaveLength(2)
    expect(s.made[1].urls).toBe(1)
    await h.end(b)
  })
  it('a small Mac lets an idle whisper-server go at once, before the notes model loads next to it (a 24 GB Mac froze)', async () => {
    const s = fakeServers()
    const h = hooks(s.make, 60_000)
    const a = meeting()
    h.begin(a); await h.end(a)
    expect(s.made[0].stops).toBe(0)
    await releaseIdleSpeech()
    expect(s.made[0].stops).toBe(1)
    // the next meeting starts a new one
    const b = meeting()
    h.begin(b)
    expect(s.made).toHaveLength(2)
    await h.end(b)
  })
  it('never while a meeting is still being transcribed', async () => {
    const s = fakeServers()
    const h = hooks(s.make, 60_000)
    const a = meeting()
    h.begin(a)
    await releaseIdleSpeech()
    expect(s.made[0].stops).toBe(0)
    await h.end(a)
  })
  it('a meeting starting before the wait is up keeps the same server running', async () => {
    const s = fakeServers()
    const h = hooks(s.make, 60)
    const a = meeting()
    h.begin(a); await h.end(a)
    await wait(20)
    const b = meeting()
    h.begin(b)
    await wait(80)
    expect(s.made).toHaveLength(1)
    expect(s.made[0].stops).toBe(0)
    await h.end(b)
  })
})

// #156: on a processor too slow for the model, live transcription gave up mid-meeting, and the audio it missed was never read
describe('when whisper cannot keep up', () => {
  /** a whisper-server stand-in that answers every request with one line */
  async function inference() {
    const { createServer } = await import('node:http')
    const srv = createServer((q, r) => { q.resume(); q.on('end', () => r.end(JSON.stringify({ detected_language: 'english', detected_language_probability: 0.99, segments: [{ start: 0, end: 0.5, text: ' Fine words here today' }] }))) })
    await new Promise<void>((res) => srv.listen(0, '127.0.0.1', () => res()))
    disposers.push(() => srv.close())
    return `http://127.0.0.1:${(srv.address() as { port: number }).port}`
  }
  /** stand-in servers on the processor that judge themselves too slow once they have read `slowAfter` chunks */
  function servers(url: string, slowAfter = 1) {
    const made: Array<{ model: string; timed: number; gpuAgain: string[] }> = []
    const make = (model: string) => {
      const rec = { model, timed: 0, gpuAgain: [] as string[] }
      made.push(rec)
      return { url: async () => url, resetBudget: () => {}, gpuAgain: (why: string) => { rec.gpuAgain.push(why); return false }, timeoutMs: () => 30_000,
        timed: () => { rec.timed++ }, get tooSlow() { return rec.timed >= slowAfter }, cpuRtf: 1.8, cpuOnly: true, slow: () => {},
        wedged: async () => url, alive: async () => true, kill: () => {}, stop: async () => {} } as unknown as import('../src/main/asr/server').WhisperServer
    }
    return { made, make }
  }
  function hooks(make: (model: string) => import('../src/main/asr/server').WhisperServer, smaller: string[] = [], capture = true, afterMeeting = false) {
    const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []
    const warns: string[] = [], queued: string[] = []
    disposers.push(hookTranscription({
      store, modelPath: () => '/turbo.bin', smallerModels: () => smaller, send: () => {}, warn: (c) => warns.push(c), server: make, serverIdleMs: 60_000, holdMs: 0,
      queued: (id) => queued.push(id), onStart: (fn) => { starts.push(fn) }, onStop: (fn) => { stops.push(fn) }, afterMeeting: () => afterMeeting,
    }))
    const procs: ReturnType<typeof fakeProc>[] = []
    if (capture) hookCapture({
      dirOf: (id) => `/m/${id}`, onStart: (fn) => { starts.push(fn); return () => {} }, onStop: (fn) => { stops.push(fn); return () => {} }, stopMeeting: () => {},
      start: (_d, o) => { const f = fakeProc(); procs.push(f); return new Capture(f.proc, { startMs: o?.startMs }) }, join: async () => {},
    })
    return { warns, queued, procs, begin: (m: Meeting) => starts.forEach((f) => f(m)),
      end: async (m: Meeting) => { stops.forEach((f) => f(m)); procs.at(-1)?.exit(0); await recordingFinished(m.id); await settleTranscription(5000) } }
  }
  const quietly = () => { const w = vi.spyOn(console, 'warn').mockImplementation(() => {}); return () => w.mockRestore() }

  it('too slow on the processor with no smaller model: live transcription pauses, says so, and the saved recording finishes it', async () => {
    const restore = quietly()
    const s = servers(await inference())
    const h = hooks(s.make)
    const m = meeting()
    h.begin(m)
    h.procs[0].say('them', 500)
    await vi.waitFor(() => expect(h.warns).toEqual(['live-paused']))
    h.procs[0].say('them', 4000)
    await tick()
    await h.end(m)
    expect(store.segments(m.id).map((x) => x.startMs)).toEqual([500])
    expect(store.meeting(m.id)?.transcriptionState).toBe('queued')
    expect(h.queued).toEqual([m.id])
    restore()
  })

  it('the speed check found no model that keeps up live: the meeting records, says so, nothing is read live, and the saved recording gives the transcript', async () => {
    const restore = quietly()
    const s = servers(await inference(), Infinity)
    const h = hooks(s.make, [], true, true)
    const m = meeting()
    h.begin(m)
    h.procs[0].say('them', 500)
    h.procs[0].say('me', 3000)
    await vi.waitFor(() => expect(h.warns).toEqual(['live-paused']))
    await h.end(m)
    expect(store.segments(m.id)).toEqual([])
    expect(s.made.every((x) => x.timed === 0)).toBe(true)
    expect(store.meeting(m.id)?.transcriptionState).toBe('queued')
    expect(h.queued).toEqual([m.id])
    restore()
  })

  it('too slow on the processor with a smaller model on disk: that one takes over and live transcription goes on', async () => {
    const restore = quietly()
    const s = servers(await inference())
    const h = hooks(s.make, ['/small.bin'])
    const m = meeting()
    h.begin(m)
    h.procs[0].say('them', 500)
    await vi.waitFor(() => expect(s.made.map((x) => x.model)).toEqual(['/turbo.bin', '/small.bin']))
    h.procs[0].say('them', 4000)
    await vi.waitFor(() => expect(s.made[1].timed).toBe(1))
    // the smaller one is too slow as well: nothing smaller is left, so it pauses
    expect(h.warns).toEqual(['live-paused'])
    await h.end(m)
    expect(store.segments(m.id).map((x) => x.startMs)).toEqual([500, 4000])
    restore()
  })

  it('a chunk that got no lines: the lines after it on that track go, and the saved recording reads the track again from there', async () => {
    const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
    const restore = quietly()
    const refreshed: string[] = []
    const r = rig('transcription-first', { refresh: (id) => refreshed.push(id), holdMs: 0, transcriber: async (c) => { if (c.track === 'them' && c.startMs === 4000) throw new Error('boom'); return says(c) } })
    const m = meeting()
    r.begin(m)
    r.procs[0].say('them', 500); r.procs[0].say('me', 500)
    await tick()
    r.procs[0].say('them', 4000)
    await tick()
    r.procs[0].say('them', 8000); r.procs[0].say('me', 8000)
    await tick()
    await r.stop(m)
    expect(store.segments(m.id, { hidden: true }).map((x) => `${x.track}@${x.startMs}`).sort()).toEqual(['me@500', 'me@8000', 'them@500'])
    expect(store.meeting(m.id)?.transcriptionState).toBe('queued')
    expect(refreshed).toContain(m.id)
    errors.mockRestore(); restore()
  })

  it('the graphics card gets another chance at each meeting and before a saved recording, never while another meeting uses the server', async () => {
    const s = servers('http://127.0.0.1:1', Infinity)
    const h = hooks(s.make, [], false)
    const a = meeting()
    h.begin(a)
    const b = meeting()
    h.begin(b)
    expect(s.made[0].gpuAgain).toEqual(['a new meeting'])
    await h.end(a); await h.end(b)
    const c = meeting()
    store.updateMeeting(c.id, { state: 'stopped', transcriptionPending: true })
    async function* none(): AsyncGenerator<Float32Array> { yield new Float32Array(0) }
    await transcribeRecorded(c.id, { them: none() })
    expect(s.made[0].gpuAgain).toEqual(['a new meeting', 'a saved recording'])
  })
})

describe('the spoken language picked', () => {
  /** Apple's speech on a Mac with English and Spanish models, the last meeting in Spanish */
  async function speechRig(spoken: () => Spoken) {
    const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []
    const procs: Array<ReturnType<typeof fakeProc> & { locale?: string | null }> = []
    const parts: TranscriptPartial[] = []
    disposers.push(hookTranscription({
      store, modelPath: () => '/model.bin', send: () => {}, warn: () => {}, transcriber: async (c) => says(c), sendPartial: (x) => parts.push(x),
      onStart: (fn) => { starts.push(fn) }, onStop: (fn) => { stops.push(fn) }, spoken,
      speech: { host: { platform: 'darwin', arch: 'arm64', osRelease: '25.4.0' }, binary: '/none', ui: () => 'en-GB', last: () => 'spanish',
        locales: async () => ({ available: true, supported: ['en-GB', 'en-US', 'es-ES'], installed: ['en-GB', 'en-US', 'es-ES'] }), install: async () => true },
    }))
    hookCapture({
      dirOf: (id) => `/m/${id}`, onStart: (fn) => { starts.push(fn); return () => {} }, onStop: (fn) => { stops.push(fn); return () => {} }, stopMeeting: () => {}, join: async () => {},
      speech: (id) => speechLocaleFor(id),
      start: (_d, o) => { const f = Object.assign(fakeProc(), { locale: o?.speech ?? null }); procs.push(f); return new Capture(f.proc) },
    })
    await tick()
    const m = meeting()
    starts.forEach((f) => f(m))
    const speak = (text: string) => (procs[0].proc.stdout as PassThrough).write(encodeFrame({ t: 'speech', track: 'them', final: false, startMs: 0, endMs: 900, text }))
    return { m, procs, parts, speak, stop: async () => { stops.forEach((f) => f(m)); procs[0].exit(0); await recordingFinished(m.id); await settleTranscription(2000) } }
  }

  it('keeps the live mic partial and ignores delayed Apple words across a short mute', async () => {
    const r = await speechRig(() => 'en')
    const out = r.procs[0].proc.stdout as PassThrough
    const say = (track: 'me' | 'them', startMs: number, text: string) =>
      out.write(encodeFrame({ t: 'speech', track, final: false, startMs, endMs: startMs + 200, text }))
    try {
      say('me', 100, 'Before'); say('them', 200, 'Remote')
      setMicMuted(r.m.id, true); out.write(encodeFrame({ t: 'mic-muted', id: 1, muted: true, ms: 350 }))
      out.write(encodeFrame({ t: 'speech-ready', tracks: ['them'] }))
      say('me', 100, 'Late mic reading'); say('them', 350, 'Remote continues')
      expect(r.parts.filter(p => p.track === 'me').map(p => p.text)).toEqual(['Before', 'Before'])
      setMicMuted(r.m.id, false); out.write(encodeFrame({ t: 'mic-muted', id: 2, muted: false, ms: 400 }))
      out.write(encodeFrame({ t: 'speech-ready', tracks: ['me', 'them'] }))
      say('me', 100, 'Old interval'); say('me', 450, 'After')
      expect(r.parts.filter(p => p.track === 'me').at(-1)?.text).toBe('Before After')
      expect(r.parts.filter(p => p.track === 'them').at(-1)?.text).toBe('Remote continues')
    } finally { await r.stop() }
  })

  it("English only: Apple's speech listens in English, in the interface's region, whatever the last meeting was in", async () => {
    const r = await speechRig(() => 'en')
    expect(r.procs[0].locale).toBe('en-GB')
    await r.stop()
  })
  it("Multi-language: today's choice, the last meeting's language", async () => {
    const r = await speechRig(() => 'multi')
    expect(r.procs[0].locale).toBe('es-ES')
    await r.stop()
  })
  it("switched to English only while recording in Spanish: Apple's Spanish words are set aside, whisper's come back", async () => {
    let spoken: Spoken = 'multi'
    const r = await speechRig(() => spoken)
    r.speak('hola')
    await expect.poll(() => r.parts.some((x) => x.text.includes('hola'))).toBe(true)
    spoken = 'en'
    spokenChanged()
    r.speak('adios')
    await new Promise((res) => setTimeout(res, 80))
    expect(r.parts.some((x) => x.text.includes('adios'))).toBe(false)
    await r.stop()
  })
})

it('refreshes saved live echoes with their IDs before recording ends', async () => {
  const refreshed: string[] = []
  const r = rig('transcription-first', { holdMs: 20, refresh: id => refreshed.push(id), transcriber: async c => [{ track: c.track, startMs: c.startMs, endMs: c.startMs + 1000, text: 'we should move the launch to friday' }] })
  const m = meeting(); r.begin(m)
  for (let i = 0; i < 14; i++) {
    r.procs[0].say('them', i * 2000 + 1000)
    await tick()
    r.procs[0].say('me', i * 2000 + 1200)
  }
  await expect.poll(() => refreshed.length, { timeout: 3000 }).toBeGreaterThan(0)
  expect(store.segments(m.id, { hidden: true }).some(s => s.hidden && Number.isInteger(s.id))).toBe(true)
  expect(store.segments(m.id).every(s => !s.hidden)).toBe(true)
  await r.stop(m)
})

describe('a meeting recorded before the speech model was in (#30)', () => {
  async function* track(...phrases: number[]): AsyncGenerator<Float32Array> {
    // a phrase (1 s of tone, 1 s of quiet) at each given second
    let at = 0
    for (const sec of phrases) {
      yield new Float32Array(Math.round((sec - at) * RATE))
      yield Float32Array.from([...tone(1), ...new Float32Array(RATE)])
      at = sec + 2
    }
  }
  it('once the model is in, is transcribed from its saved recording and no longer waits', async () => {
    rig('transcription-first')
    // as a meeting recorded with no speech model ends up: stopped, waiting, not one line
    const m = meeting()
    store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })
    expect(store.untranscribedMeetings().map((x) => x.id)).toEqual([m.id])
    expect(await transcribeRecorded(m.id, { them: track(1, 4), me: track(7) })).toBe(true)
    const lines = store.segments(m.id).map((x) => `${x.track}@${Math.round(x.startMs / 1000)}`)
    expect(lines).toEqual(expect.arrayContaining(['them@1', 'them@4', 'me@7']))
    expect(store.meeting(m.id)?.transcriptionPending).not.toBe(true)
    expect(store.untranscribedMeetings()).toEqual([])
  })
  it('continues saved audio at the persisted timestamp without duplicating its first line', async () => {
    rig('transcription-first')
    const m=meeting('audio-file')
    store.addSegments([{meetingId:m.id,track:'them',startMs:1000,endMs:2000,text:'Kept first line',speaker:AUDIO_SPEAKER}])
    expect(await transcribeRecorded(m.id,{them:track(1,4)},undefined,{fromMs:{them:2000}})).toBe(true)
    const lines=store.segments(m.id)
    expect(lines[0].text).toBe('Kept first line');expect(lines).toHaveLength(2)
    expect(lines[1].startMs).toBeGreaterThanOrEqual(4000)
  })
  it('stages replacement words through the actual pipeline without publishing or removing old words', async () => {
    const r=rig('transcription-first'),m=meeting('audio-file')
    store.addSegments([{meetingId:m.id,track:'them',startMs:0,endMs:100,text:'Original transcript',speaker:AUDIO_SPEAKER}])
    expect(await transcribeRecorded(m.id,{them:track(1,4)},undefined,{save:lines=>store.addTranscriptionDraft(m.id,lines)})).toBe(true)
    expect(store.segments(m.id).map(line=>line.text)).toEqual(['Original transcript'])
    expect(r.sent).toEqual([]);expect(store.transcriptionDraft(m.id)).toHaveLength(2)
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
    store.commitTranscriptionDraft(m.id)
    expect(store.segments(m.id)).toHaveLength(2);expect(store.segments(m.id).some(line=>line.text==='Original transcript')).toBe(false)
  })
  it.each([undefined, 'audio-file'])('reports saved transcription progress for source %s without requiring an upload job', async source => {
    rig('transcription-first')
    const m = meeting(source), progress = vi.fn()
    store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })
    expect(await transcribeRecorded(m.id, { them: track(1, 4) }, undefined, { progress })).toBe(true)
    expect(store.segments(m.id).length).toBeGreaterThan(0)
    expect(store.segments(m.id).map(line => line.speaker)).toEqual(source ? [AUDIO_SPEAKER, AUDIO_SPEAKER] : [null, null])
    expect(progress).toHaveBeenCalled()
    expect(store.meeting(m.id)?.transcriptionPending).not.toBe(true)
  })
  it('retains an interrupted uploaded transcript for restart recovery, but never calls it complete', async () => {
    const abort = new AbortController(), progress = vi.fn()
    rig('transcription-first', { transcriber: c => { abort.abort(); return says(c) } })
    const m = meeting('audio-file')
    store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })
    expect(await transcribeRecorded(m.id, { them: track(1, 4) }, undefined, { signal: abort.signal, progress })).toBe(false)
    expect(progress).not.toHaveBeenCalled()
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
    store.addSegments([{ meetingId: m.id, track: 'them', startMs: 0, endMs: 1000, text: 'A partial line', speaker: AUDIO_SPEAKER }])
    expect(store.untranscribedMeetings().map(m => m.id)).toContain(m.id)
  })
  it('does not report successful deferred transcription when the model fails', async () => {
    rig('transcription-first', { transcriber: () => { throw new Error('speech model failed') } })
    const m = meeting()
    store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })
    expect(await transcribeRecorded(m.id, { them: track(1) })).toBe(false)
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
  })
  it('whisper failing partway through a live meeting queues the rest of its saved recording for later (#127)', async () => {
    let calls = 0
    const queued: string[] = []
    const r = rig('transcription-first', { transcriber: async (c) => { if (calls++) throw new Error('whisper-server exited (SIGKILL)'); return says(c) }, queued: (id) => queued.push(id) })
    const m = meeting()
    r.begin(m); r.procs[0].say('them', 500); r.procs[0].say('them', 4000)
    await tick()
    await r.stop(m)
    store.updateMeeting(m.id, { state: 'stopped' })
    expect(store.segments(m.id)).toHaveLength(1)
    expect(store.meeting(m.id)).toMatchObject({ transcriptionPending: true, transcriptionState: 'queued' })
    // the saved recording carries on from where its lines end (savedTranscription's fromMs), so no line comes twice
    expect(store.untranscribedMeetings().map((x) => x.id)).toEqual([m.id])
    expect(queued).toEqual([m.id])
  })
  it('without the model yet, nothing happens and the meeting keeps waiting', async () => {
    rig('transcription-first', { modelPath: () => undefined })
    const m = meeting()
    store.updateMeeting(m.id, { state: 'stopped', transcriptionPending: true })
    expect(await transcribeRecorded(m.id, { them: track(1) })).toBe(false)
    expect(store.meeting(m.id)?.transcriptionPending).toBe(true)
  })
})


describe('live silence for call detection', () => {
  it('requires fresh input on both tracks and resets for either voice, pause, gaps and live words', async () => {
    let now = 10_000, ms = 0
    const time = vi.spyOn(Date, 'now').mockImplementation(() => now)
    const r = rig('transcription-first', { transcriber: () => [] }), m = meeting()
    r.begin(m)
    const output = r.procs[0].proc.stdout as PassThrough
    const frame = (voice?: 'me' | 'them', tracks: readonly ('me' | 'them')[] = ['me', 'them']) => {
      now += 100; ms += 100
      for (const track of tracks) output.write(encodeFrame({ t: 'pcm', track, ms, samples: voice === track ? tone(0.1) : new Float32Array(1600) }))
    }
    const quiet = (n: number) => { for (let i = 0; i < n; i++) frame() }
    try {
      expect(liveSilentMs(m.id)).toBe(0)
      quiet(601)
      expect(liveSilentMs(m.id)).toBe(60_000)
      frame('me'); expect(liveSilentMs(m.id)).toBe(0)
      quiet(620); expect(liveSilentMs(m.id)).toBeGreaterThanOrEqual(60_000)
      frame('them'); expect(liveSilentMs(m.id)).toBe(0)
      quiet(620)
      expect(setRecordingPaused(m.id, true)).toBe(true)
      quiet(620); expect(liveSilentMs(m.id)).toBe(0)
      expect(setRecordingPaused(m.id, false)).toBe(true)
      frame(); expect(liveSilentMs(m.id)).toBeLessThan(1000)
      quiet(610); expect(liveSilentMs(m.id)).toBeGreaterThanOrEqual(60_000)
      now += 3001; expect(liveSilentMs(m.id)).toBe(0)
      frame(); expect(liveSilentMs(m.id)).toBe(0)
      quiet(610)
      output.write(encodeFrame({ t: 'speech', track: 'me', final: false, text: 'Still talking', startMs: ms, endMs: ms + 100 }))
      expect(liveSilentMs(m.id)).toBe(0)
      quiet(610)
      // One missing track is unknown input, not a quiet conversation.
      for (let i = 0; i < 31; i++) { now += 100; ms += 100; output.write(encodeFrame({ t: 'pcm', track: 'me', ms, samples: new Float32Array(1600) })) }
      expect(liveSilentMs(m.id)).toBe(0)
      frame(); expect(liveSilentMs(m.id)).toBe(0)
      setMicMuted(m.id, true)
      output.write(encodeFrame({ t: 'mic-muted', id: 1, muted: true, ms }))
      expect(liveSilentMs(m.id)).toBe(0)
      for (let i = 0; i < 610; i++) frame(undefined, ['them'])
      expect(liveSilentMs(m.id)).toBeGreaterThanOrEqual(60_000)
      frame('them', ['them']); expect(liveSilentMs(m.id)).toBe(0)
    } finally { time.mockRestore(); await r.stop(m) }
    expect(liveSilentMs(m.id)).toBe(0)
  })
  it('cannot claim silence without a speech pipeline, before capture, or for an unknown meeting', async () => {
    const r = rig('transcription-first', { modelPath: () => undefined }), m = meeting()
    expect(liveSilentMs(m.id)).toBe(0)
    r.begin(m)
    r.procs[0].say('me', 0)
    expect(liveSilentMs(m.id, Date.now() + 60_000)).toBe(0)
    await r.stop(m)
  })
})