From 9ace692729bd32786502a3523ec68dcd21c0475c Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Fri, 27 Nov 2026 12:28:41 -0600 Subject: [PATCH] Resume work a quit or crash cut short, and checkpoint long steps. - Save raw/live.json every few seconds while recording, with open-ended untranscribed marks; the next start transcribes the marked audio again. - Track owed steps (transcribe, speakers, notes) in the manifest's pending list; resume.ts picks them up at startup, reading only sessions that owe something. - Keep the whole recording's diarization and each notes model answer as checkpoints, so a retry skips what was already done. - Add `--crash` to smoke:meeting to replay a crash and the resume. --- .changeset/resume-interrupted-work.md | 5 + AGENTS.md | 2 +- apps/lyra/src/main/checkpoints.ts | 60 ++++ apps/lyra/src/main/index.ts | 13 + apps/lyra/src/main/lifecycle.ts | 14 + apps/lyra/src/main/livePass.test.ts | 40 ++- apps/lyra/src/main/livePass.ts | 52 ++- apps/lyra/src/main/meeting/notes.ts | 81 ++++- apps/lyra/src/main/meeting/notesLocal.ts | 22 +- .../src/main/meeting/notesPipeline.test.ts | 56 +++- apps/lyra/src/main/meeting/notesPipeline.ts | 37 ++- apps/lyra/src/main/meeting/notesProtocol.ts | 13 +- apps/lyra/src/main/meeting/notesWorker.ts | 13 +- apps/lyra/src/main/meeting/notesWriter.ts | 7 +- apps/lyra/src/main/meeting/ollama.ts | 3 +- apps/lyra/src/main/meeting/protocol.ts | 29 +- apps/lyra/src/main/meeting/relabel.ts | 89 +++++- apps/lyra/src/main/meeting/replay.ts | 11 +- apps/lyra/src/main/pendingWork.ts | 57 ++++ apps/lyra/src/main/recorder.ts | 184 ++++++++--- apps/lyra/src/main/resume.ts | 300 ++++++++++++++++++ apps/lyra/src/main/resumePlan.test.ts | 55 ++++ apps/lyra/src/main/resumePlan.ts | 45 +++ apps/lyra/src/main/sessionManifest.test.ts | 16 +- apps/lyra/src/main/sessionManifest.ts | 15 +- apps/lyra/src/main/sessionStore.ts | 11 +- apps/lyra/src/main/takeWriter.ts | 2 +- apps/lyra/src/main/tasks/args.ts | 13 +- apps/lyra/src/main/tasks/meeting.ts | 20 +- apps/lyra/src/main/tasks/smoke.ts | 87 +++++ apps/lyra/src/main/transcriber.ts | 30 +- apps/lyra/src/shared/activity.ts | 2 +- docs/CONFIG.md | 2 + docs/SESSION-MODEL.md | 29 ++ 34 files changed, 1286 insertions(+), 129 deletions(-) create mode 100644 .changeset/resume-interrupted-work.md create mode 100644 apps/lyra/src/main/checkpoints.ts create mode 100644 apps/lyra/src/main/lifecycle.ts create mode 100644 apps/lyra/src/main/pendingWork.ts create mode 100644 apps/lyra/src/main/resume.ts create mode 100644 apps/lyra/src/main/resumePlan.test.ts create mode 100644 apps/lyra/src/main/resumePlan.ts diff --git a/.changeset/resume-interrupted-work.md b/.changeset/resume-interrupted-work.md new file mode 100644 index 00000000..c4289ede --- /dev/null +++ b/.changeset/resume-interrupted-work.md @@ -0,0 +1,5 @@ +--- +'lyra': minor +--- + +Work a quit or crash cuts short now picks up where it stopped the next time Lyra starts. A recording's words are saved every few seconds, and any audio that wasn't transcribed yet is transcribed from the saved recording. Speakers are then settled and the summary written, as they would have been. Long steps keep what they had already done: a diarized recording isn't diarized again, and a long meeting's summary only asks the model for the parts it hadn't answered yet. Downloads already resumed from where they stopped. diff --git a/AGENTS.md b/AGENTS.md index cde823cb..88eba604 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ Roadmap: [docs/PLAN.md](docs/PLAN.md). Human contributor guide: [CONTRIBUTING.md | UI smoke test | `pnpm smoke:ui` (builds, launches Electron headless, exercises the IPC bridge) | | Native addon smoke | `pnpm smoke` (only needed when touching `src/main/whisper.ts` or native deps) | | QA with real audio | `node scripts/make-demo-audio.cjs` (in `apps/lyra`; Windows SAPI or macOS `say`) makes `test-audio/meeting.wav` (two synthetic voices); see the `qa-test` skill | -| Meeting pipeline smoke | `pnpm smoke:meeting [system.wav]`: replays the audio as a live recording (chunked Whisper per track, speakers labeled every half minute, relabel after stop); `--offline` runs diarize-then-transcribe instead; `--notes local` adds notes; `--no-relabel` keeps the labels given while recording; `--enroll owner.wav` saves a voice first; `LYRA_MODELS_DIR` reuses downloads | +| Meeting pipeline smoke | `pnpm smoke:meeting [system.wav]`: replays the audio as a live recording (chunked Whisper per track, speakers labeled every half minute, relabel after stop); `--offline` runs diarize-then-transcribe instead; `--notes local` adds notes; `--no-relabel` keeps the labels given while recording; `--enroll owner.wav` saves a voice first; `--crash` dies half way through, then resumes as the next start would; `LYRA_MODELS_DIR` reuses downloads | | Speaker evals | `pnpm eval:sessions` (in `apps/lyra`): real voices (LibriSpeech, CC BY 4.0; needs ffmpeg) laid out as 2–6 person room, hybrid and call sessions with exact ground truth (Opus remote audio, speaker bleed, music or a video playing, a fan, backchannels, crosstalk); `--seeds 3` for three draws each, `--enroll` to save the owner's voice first; `pnpm eval:calls`: TTS call/room scenarios (speaker bleed, clipping, quick turns, crosstalk); `pnpm eval:ami` scores real AMI meetings (`--meetings`, `--minutes`, `--mic`). WER, cpWER, DER; data and results go to `eval-data/`. `--pipeline live` (default: what the app runs), `stream` (the lines as labeled while recording, before relabel), `offline`, or `capture` (mic-only items played as a fake microphone through the window's real capture path, in real time). Experiments: `--asr parakeet`, `--no-context` (Whisper without its prompt). `--quick` runs a fixed subset (about 2 min for calls, 4 for sessions) for direction while working; `--jobs 2` runs items in parallel. `--check` fails the run if it is worse than the stored baseline (`scripts/eval/baselines/`), `--update-baseline` stores it; `pnpm eval:local` scores your own recordings, added with `node scripts/eval/local.cjs add ` and kept out of the repo. Task runs are headless: no window opens | | Tune speaker clustering | In `apps/lyra`, with `LYRA_MODELS_DIR`: `node scripts/eval/cluster-lab.cjs` sweeps voice models, window sizes and clustering bars on the sessions in seconds, without Whisper; `node scripts/eval/voice-scores.cjs` shows how a saved voice scores against its owner and everyone else (the basis for `meeting/thresholds.ts`) | | Word lists | `pnpm word-lists` (in `apps/lyra`) regenerates `src/main/data/hallucinations.json` and `src/shared/data/whisperLanguages.json` from pinned upstream sources; never edit them by hand | diff --git a/apps/lyra/src/main/checkpoints.ts b/apps/lyra/src/main/checkpoints.ts new file mode 100644 index 00000000..e859bebf --- /dev/null +++ b/apps/lyra/src/main/checkpoints.ts @@ -0,0 +1,60 @@ +import { mkdir, readFile, rm } from 'node:fs/promises' +import { join } from 'node:path' +import type { z } from 'zod' +import { writeFileAtomic } from './atomicFile' +import { log } from './log' +import { sessionCheckpointDir } from './sessionStore' + +/** + * What a long step has worked out so far, in `.sessions//checkpoint/.json`, so a quit, + * crash or failure part way through doesn't throw it away: the diarization of a whole recording + * (`meeting/relabel.ts`), the model's answers for a long meeting's summary (`meeting/notes.ts`). + * Derived data, deleted once the step is done; losing it only costs the time to redo the work. + * Each checkpoint says what it was worked out from (a key), and one for other input is ignored. + */ + +export type CheckpointName = 'diarize' | 'notes' + +const pathOf = (id: string, name: CheckpointName): string => join(sessionCheckpointDir(id), `${name}.json`) + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +/** The checkpoint, or null when there is none or it doesn't read as `schema`. */ +export async function readCheckpoint( + id: string, + name: CheckpointName, + schema: z.ZodType +): Promise { + let text: string + try { + text = await readFile(pathOf(id, name), 'utf8') + } catch { + return null + } + try { + const parsed = schema.safeParse(JSON.parse(text)) + if (parsed.success) return parsed.data + } catch { + // Not JSON: written by something else, or torn by a disk that ignores fsync. + } + log('checkpoint', 'ignored an unreadable checkpoint', { id, name }) + return null +} + +/** Replaces the checkpoint atomically; a failure is logged, never thrown (it only costs a redo). */ +export async function writeCheckpoint(id: string, name: CheckpointName, value: unknown): Promise { + try { + await mkdir(sessionCheckpointDir(id), { recursive: true }) + await writeFileAtomic(pathOf(id, name), JSON.stringify(value)) + } catch (error) { + log('checkpoint', 'could not save a checkpoint', { id, name, error: errorMessage(error) }) + } +} + +export async function clearCheckpoint(id: string, name: CheckpointName): Promise { + await rm(pathOf(id, name), { force: true }).catch((error: unknown) => { + log('checkpoint', 'could not delete a checkpoint', { id, name, error: errorMessage(error) }) + }) +} diff --git a/apps/lyra/src/main/index.ts b/apps/lyra/src/main/index.ts index 84ce9af1..b64e0d5c 100644 --- a/apps/lyra/src/main/index.ts +++ b/apps/lyra/src/main/index.ts @@ -78,6 +78,8 @@ import { prefetchNotesModel, releaseNotesModel, reportNotesModel, stopNotesWorke import { stopSpeakerWorker } from './meeting/speakers' import { startLiveLabels } from './meeting/liveLabels' import { relabelSession } from './meeting/relabel' +import { markQuitting } from './lifecycle' +import { resumeUnfinishedWork } from './resume' import { finishRecordingForQuit, identifiesSpeakers, @@ -598,6 +600,7 @@ void app.whenReady().then(() => { enabled: !isTestRun, beforeInstall: () => { quitting = true + markQuitting() } }) saveForPower = registerPowerHandling(saveWork) @@ -650,6 +653,15 @@ void app.whenReady().then(() => { }) startAudioRetention() createWindow() + // What a quit or crash cut short: transcription, speakers, summaries. Task runs have their own work. + const notes = services?.notes + if (!isTestRun && notes) { + void resumeUnfinishedWork({ + speakers: identifiesSpeakers(), + relabel: relabelSession, + writeNotes: (pageId) => notes.writeOwed(pageId) + }) + } }) broadcastStatus({ state: 'idle' }) @@ -707,6 +719,7 @@ async function shutdownWork(): Promise { let flushed = false app.on('before-quit', (event) => { quitting = true + markQuitting() // Finish a recording in progress, write pending exports and compact session logs before the // process goes away, but never let a stuck disk or worker keep the app from quitting. if (flushed) return diff --git a/apps/lyra/src/main/lifecycle.ts b/apps/lyra/src/main/lifecycle.ts new file mode 100644 index 00000000..b9a1ca7b --- /dev/null +++ b/apps/lyra/src/main/lifecycle.ts @@ -0,0 +1,14 @@ +/** + * Whether the app is on its way out. Work cut off by quitting (a worker killed, a call aborted) + * fails like any other; this tells it apart, so a step interrupted by the quit stays owed and is + * resumed at the next start instead of being marked done. + */ +let quitting = false + +export function markQuitting(): void { + quitting = true +} + +export function isQuitting(): boolean { + return quitting +} diff --git a/apps/lyra/src/main/livePass.test.ts b/apps/lyra/src/main/livePass.test.ts index 32a47dbc..898043c9 100644 --- a/apps/lyra/src/main/livePass.test.ts +++ b/apps/lyra/src/main/livePass.test.ts @@ -2,7 +2,16 @@ import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { heardSpans, mergeLivePass, parseLiveFile, readLiveFile, writeLiveFile, type LiveSegment } from './livePass' +import { + closeOpenMarks, + heardSpans, + marksToResume, + mergeLivePass, + parseLiveFile, + readLiveFile, + writeLiveFile, + type LiveSegment +} from './livePass' function segment(id: string, start: number, track: 'mic' | 'system' = 'mic'): LiveSegment { return { id, start, end: start + 1, track, cluster: null, confidence: null, words: [{ text: ' hi', start, end: start + 1 }] } @@ -82,3 +91,32 @@ describe('live.json on disk', () => { expect(JSON.parse(await readFile(join(dir, 'live.json'), 'utf8'))).toMatchObject({ id: 'live', kind: 'live' }) }) }) + +describe('untranscribed marks', () => { + const file = { + segments: [], + untranscribed: [ + { take: 0, track: 'mic' as const, start: 40, end: 40, open: true }, + { take: 0, track: 'system' as const, start: 38.5, end: 38.5, open: true }, + { take: 100, track: 'mic' as const, start: 120, end: 130 } + ] + } + + it('closes the open marks of a take a crash cut short where the next take starts', () => { + expect(closeOpenMarks(file, 60)?.untranscribed).toEqual([ + { take: 0, track: 'mic', start: 40, end: 60 }, + { take: 0, track: 'system', start: 38.5, end: 60 }, + { take: 100, track: 'mic', start: 120, end: 130 } + ]) + expect(closeOpenMarks({ segments: [], untranscribed: [{ take: 0, track: 'mic', start: 1, end: 2 }] }, 60)).toBeNull() + }) + + it('runs open marks to the end of their audio, and drops what has none left', () => { + const seconds = { mic: 125, system: 38.5 } + expect(marksToResume(file.untranscribed, (track) => seconds[track])).toEqual([ + { take: 0, track: 'mic', start: 40, end: 125 }, + // The audio stops before the closed mark's end: only what's on disk is transcribed. + { take: 100, track: 'mic', start: 120, end: 125 } + ]) + }) +}) diff --git a/apps/lyra/src/main/livePass.ts b/apps/lyra/src/main/livePass.ts index 2b9dd571..d25282f4 100644 --- a/apps/lyra/src/main/livePass.ts +++ b/apps/lyra/src/main/livePass.ts @@ -3,6 +3,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { z } from 'zod' import type { AudioTrack } from '../shared/types' +import type { TranscribedChunk } from './transcriber' /** * `raw/live.json`: every word transcribed while recording, across all of a session's takes. Each @@ -25,15 +26,18 @@ export const LiveSegment = z.looseObject({ export type LiveSegment = z.infer /** - * Audio of a take that was recorded but not transcribed, because the app quit before Whisper - * caught up. Seconds on the session timeline; `take` is where that take starts, so the take's - * own final save can replace its marker. + * Audio of a take that was recorded but not transcribed, because the app quit or crashed before + * Whisper caught up; the next start transcribes it (`resume.ts`). Seconds on the session + * timeline; `take` is where that take starts, so the take's own later saves replace its marker. + * `open`: saved while recording, before the end was known, so it runs to the end of the take's + * audio, whatever `end` says. */ export const Untranscribed = z.object({ take: z.number(), track: z.enum(['mic', 'system']), start: z.number(), - end: z.number() + end: z.number(), + open: z.boolean().optional() }) export type Untranscribed = z.infer @@ -127,6 +131,46 @@ export async function writeLiveFile(dir: string, pass: Record): await rename(temp, path) } +/** A transcribed chunk as kept in `raw/live.json`, labeled with the track it was heard on. */ +export function liveSegmentOf(chunk: TranscribedChunk): LiveSegment { + return { + id: `live-${chunk.track}-${String(Math.round(chunk.start * 1000))}`, + start: chunk.words[0]?.start ?? chunk.start, + end: chunk.words.at(-1)?.end ?? chunk.end, + track: chunk.track, + cluster: null, + confidence: null, + words: chunk.words + } +} + +/** + * The file with its open markers closed at `end`: a new take starts there, so an earlier take a + * crash cut short ends there too. Null when nothing was open. + */ +export function closeOpenMarks(file: LiveFile, end: number): LiveFile | null { + const marks = file.untranscribed ?? [] + if (!marks.some((mark) => mark.open)) return null + const closed = marks.map(({ open, ...mark }) => + open ? { ...mark, end: Math.max(mark.start, end) } : mark + ) + return { ...file, untranscribed: closed } +} + +/** + * The spans to transcribe again, with open markers run to the end of their track's audio + * (`seconds`); empty ones (all of it was transcribed after all) left out. + */ +export function marksToResume( + marks: readonly Untranscribed[], + seconds: (track: AudioTrack) => number +): Untranscribed[] { + return marks.flatMap(({ open, ...mark }) => { + const end = open ? seconds(mark.track) : Math.min(mark.end, seconds(mark.track)) + return end > mark.start ? [{ ...mark, end: +end.toFixed(3) }] : [] + }) +} + /** Where each track was heard in the takes so far. */ export function heardSpans(file: LiveFile | null): { track: AudioTrack; start: number; end: number }[] { return liveSegments(file).flatMap((segment) => diff --git a/apps/lyra/src/main/meeting/notes.ts b/apps/lyra/src/main/meeting/notes.ts index 98d170bb..3f00daec 100644 --- a/apps/lyra/src/main/meeting/notes.ts +++ b/apps/lyra/src/main/meeting/notes.ts @@ -7,7 +7,9 @@ import type { NotesBackfillResult, NotesState } from '../../shared/types' +import { clearCheckpoint, readCheckpoint, writeCheckpoint } from '../checkpoints' import { log } from '../log' +import { settle } from '../pendingWork' import { changeSession, editSession, listSessions } from '../sessionStore' import { notesLinesOf } from './notesChunks' import { renderNotes, type NotesLine } from './notesFormat' @@ -22,7 +24,7 @@ import { type NotesRun, type NotesTrigger } from './notesJobs' -import { NOTES_PIPELINE } from './notesPipeline' +import { NOTES_PIPELINE, type NotesAnswers } from './notesPipeline' import type { NotesWriter } from './notesWriter' import { onMeetingLabeled } from './events' import { worthSummarizing } from './notesWorth' @@ -60,10 +62,53 @@ export type MeetingNotesService = { backfill(kind: NotesBackfillKind): Promise /** Stops a bulk run on the session it is on; returns whether one was going. */ stopBackfill(): boolean + /** + * Writes the summary a labeled recording owes its session (unless the user edited it, or + * too little was said), then marks it no longer owed. After each labeled meeting, and at + * startup for one a quit or crash cut off (`resume.ts`). + */ + writeOwed(pageId: string): Promise /** Generates notes after each labeled meeting, and answers the renderer's requests. */ register(): void } +/** The answers a writer got for a session's notes so far, by call (`NotesAnswers`). */ +const NotesCheckpoint = z.object({ writer: z.string(), answers: z.record(z.string(), z.unknown()) }) + +type CheckpointedAnswers = NotesAnswers & { saved: () => Promise } + +/** + * The answers an earlier, unfinished try by this writer got, and a `save` that keeps each new one + * on disk as it comes: a long meeting is many calls, and a retry then only asks what's missing. + * `saved` resolves once what was saved so far is on disk. Once `signal` aborts (the run was + * replaced or stopped) nothing more is saved, so a late answer can't bring back a checkpoint the + * run that replaced it has cleared. + */ +async function checkpointedAnswers( + pageId: string, + writer: string, + signal: AbortSignal +): Promise { + const kept = await readCheckpoint(pageId, 'notes', NotesCheckpoint) + const known = kept?.writer === writer ? kept.answers : {} + const calls = Object.keys(known).length + if (calls) log('notes', 'answers kept from an earlier try', { pageId, calls }) + const answers: Record = { ...known } + let saving = Promise.resolve() + return { + known, + save: (key, answer) => { + if (signal.aborted) return + answers[key] = answer + // Checked again when the write's turn comes: the run may have been replaced since. + saving = saving.then(() => + signal.aborted ? undefined : writeCheckpoint(pageId, 'notes', { writer, answers }) + ) + }, + saved: () => saving + } +} + /** The session as notes need it, plus the fingerprint of the summary Lyra last wrote. */ function readForNotes(pageId: string): Promise<{ lines: NotesLine[]; summary: string; fingerprint: unknown }> { return changeSession(pageId, (doc) => ({ @@ -141,8 +186,10 @@ export function createMeetingNotes(deps: { if (!before.lines.length) throw new Error('This note has no transcript to summarize') broadcast(pageId, 'summarizing', 0) const started = Date.now() + const answers = await checkpointedAnswers(pageId, writer.name, job.signal) const notes = await writer.notes(before.lines, { signal: job.signal, + answers, onProgress: (done, total) => { broadcast(pageId, 'summarizing', total ? done / total : 0, total > 1 ? `step ${String(done)} of ${String(total)}` : undefined) }, @@ -152,6 +199,8 @@ export function createMeetingNotes(deps: { }) // A writer that finished despite an abort still mustn't write; the catch reports why. job.signal.throwIfAborted() + await answers.saved() + await clearCheckpoint(pageId, 'notes') const summary = renderNotes(notes) const run: NotesRun = { pipeline: NOTES_PIPELINE, writer: writer.name, at: new Date().toISOString() } // Only the summary changes, so edits made elsewhere while the model worked are untouched. @@ -273,10 +322,27 @@ export function createMeetingNotes(deps: { return true } + async function writeOwed(pageId: string): Promise { + try { + const writer = await deps.writer().catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error) + log('notes', 'not generated', { pageId, error: message }) + return null + }) + if (writer) await generateNotes(pageId, 'auto') + } catch { + // A failed run was already reported through meeting:status and the log. + } finally { + // Not while quitting: then the run was cut short and is still owed (`settle`). + await settle(pageId, 'notes') + } + } + return { generateNotes: async (pageId, trigger) => { await generateNotes(pageId, trigger) }, + writeOwed, summaryEdited: edited, backfillStatus, backfill, @@ -296,18 +362,7 @@ export function createMeetingNotes(deps: { if (action === 'cancel') stopBackfill() }) onMeetingLabeled((pageId) => { - void deps.writer().then( - (writer) => { - if (!writer) return - generateNotes(pageId, 'auto').catch(() => { - // Already reported through meeting:status and the log. - }) - }, - (error: unknown) => { - const message = error instanceof Error ? error.message : String(error) - log('notes', 'not generated', { pageId, error: message }) - } - ) + void writeOwed(pageId) }) ipcMain.handle('notes:generate', (_event, pageId: unknown) => generateNotes(z.string().parse(pageId), 'manual')) ipcMain.handle('notes:summaryEdited', (_event, pageId: unknown) => edited(z.string().parse(pageId))) diff --git a/apps/lyra/src/main/meeting/notesLocal.ts b/apps/lyra/src/main/meeting/notesLocal.ts index 393c2617..431f7a8b 100644 --- a/apps/lyra/src/main/meeting/notesLocal.ts +++ b/apps/lyra/src/main/meeting/notesLocal.ts @@ -52,6 +52,7 @@ type Pending = { resolve: (value: unknown) => void reject: (error: Error) => void onProgress?: ((done: number, total: number) => void) | undefined + onAnswer?: ((key: string, answer: unknown) => void) | undefined } const pending = new Map() @@ -71,6 +72,9 @@ function getWorker(): UtilityProcess { case 'progress': entry.onProgress?.(message.done, message.total) return + case 'answer': + entry.onAnswer?.(message.key, message.answer) + return case 'result': pending.delete(message.id) entry.resolve(message.result) @@ -91,14 +95,13 @@ function getWorker(): UtilityProcess { return child } -type Work = { kind: 'notes'; modelPath: string; lines: NotesLine[] } | { kind: 'title'; modelPath: string; text: string } +type Work = + | { kind: 'notes'; modelPath: string; lines: NotesLine[]; known: Readonly> } + | { kind: 'title'; modelPath: string; text: string } +type Hooks = Pick /** Sends one request to the worker; aborting `signal` stops it there too. */ -function ask( - work: Work, - signal?: AbortSignal, - onProgress?: (done: number, total: number) => void -): Promise { +function ask(work: Work, signal?: AbortSignal, hooks: Hooks = {}): Promise { signal?.throwIfAborted() const id = nextId++ const child = getWorker() @@ -111,7 +114,7 @@ function ask( } signal?.addEventListener('abort', onAbort, { once: true }) pending.set(id, { - onProgress, + ...hooks, resolve: (value) => { signal?.removeEventListener('abort', onAbort) resolve(value) @@ -135,10 +138,11 @@ export function createLocalNotesWriter(): NotesWriter { return { name: 'local', onDevice: true, - async notes(lines, { onDownload, signal, onProgress } = {}) { + async notes(lines, { onDownload, signal, onProgress, answers } = {}) { const modelPath = await fetchModel(onDownload) + const work: Work = { kind: 'notes', modelPath, lines, known: answers?.known ?? {} } // The worker's pipeline already tidied the notes; this checks what crossed the boundary. - return WrittenNotes.parse(await ask({ kind: 'notes', modelPath, lines }, signal, onProgress)) + return WrittenNotes.parse(await ask(work, signal, { onProgress, onAnswer: answers?.save })) }, async title(text, signal) { const modelPath = await ensureModelFile(MODEL) diff --git a/apps/lyra/src/main/meeting/notesPipeline.test.ts b/apps/lyra/src/main/meeting/notesPipeline.test.ts index 4b48bc2e..1a57f737 100644 --- a/apps/lyra/src/main/meeting/notesPipeline.test.ts +++ b/apps/lyra/src/main/meeting/notesPipeline.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { estimateTokens } from './notesChunks' import { ActionItemsFound, NotesDraft, OverviewNotes, SectionNotes, type NotesLine } from './notesFormat' -import { quotedFrom, sameItem, uniqueItems, writeNotes, type NotesCall } from './notesPipeline' +import { callKey, quotedFrom, sameItem, uniqueItems, writeNotes, type NotesCall } from './notesPipeline' const TOPICS = [ ['budget', 'spending', 'quarter', 'finance', 'invoice', 'forecast'], @@ -203,3 +203,57 @@ describe('sameItem', () => { expect(uniqueItems(['a b c d e', 'A B C D E', 'f'], String)).toEqual(['a b c d e', 'f']) }) }) + +describe('answers kept from an earlier try', () => { + it('asks a retry only what the try it replaces had no answer to', async () => { + const whole = recorder() + const expected = await writeNotes({ lines: meeting(10), budget: 8000, count: estimateTokens, ask: whole.ask }) + // The first try gets five answers, then the app quits. + const kept: Record = {} + const first = recorder() + let answered = 0 + const failing = async (call: NotesCall): Promise => { + if (answered === 5) throw new Error('quit') + answered++ + return first.ask(call) + } + const save = (key: string, answer: unknown): void => { + kept[key] = answer + } + await expect( + writeNotes({ lines: meeting(10), budget: 8000, count: estimateTokens, ask: failing, answers: { known: {}, save } }) + ).rejects.toThrow('quit') + expect(Object.keys(kept)).toHaveLength(5) + + const retry = recorder() + const notes = await writeNotes({ + lines: meeting(10), + budget: 8000, + count: estimateTokens, + ask: retry.ask, + answers: { known: kept, save } + }) + expect(retry.calls).toHaveLength(whole.calls.length - 5) + expect(retry.calls.map(callKey)).toEqual(whole.calls.slice(5).map(callKey)) + expect(notes).toEqual(expected) + }) + + it('asks again where a kept answer no longer fits its call', async () => { + const lines: NotesLine[] = [{ speaker: 'Sam', text: 'We ship Friday.', start: 0, end: 2 }] + const first = recorder() + await writeNotes({ lines, budget: 1000, count: estimateTokens, ask: first.ask }) + const [draft] = first.calls + if (!draft) throw new Error('expected a call') + const saved: string[] = [] + const retry = recorder() + await writeNotes({ + lines, + budget: 1000, + count: estimateTokens, + ask: retry.ask, + answers: { known: { [callKey(draft)]: { summary: 42 } }, save: (key) => saved.push(key) } + }) + expect(retry.calls.map((call) => call.schema)).toEqual([NotesDraft, ActionItemsFound]) + expect(saved).toEqual(retry.calls.map(callKey)) + }) +}) diff --git a/apps/lyra/src/main/meeting/notesPipeline.ts b/apps/lyra/src/main/meeting/notesPipeline.ts index 99604f13..85e5ebd7 100644 --- a/apps/lyra/src/main/meeting/notesPipeline.ts +++ b/apps/lyra/src/main/meeting/notesPipeline.ts @@ -11,6 +11,7 @@ * summary is written from the sections' summaries, which are short enough to fit even a 4k * context; past that they are summarized in groups first. Pure: the model is the `ask` callback. */ +import { createHash } from 'node:crypto' import type { z } from 'zod' import { fitText, @@ -50,6 +51,37 @@ export type NotesCall = { system: string; schema: z.ZodObject; name: string; pro /** Answers one call; the pipeline checks the answer against `call.schema` itself. */ export type NotesAsk = (call: NotesCall) => Promise +/** + * The answers an earlier try at the same notes already got (it was cut off by a quit, a crash or + * a failed call part way through a long meeting), by `callKey`, and where to keep each new one. + * A long meeting's notes are many calls; a retry then only asks what it doesn't have. + */ +export type NotesAnswers = { + known: Readonly> + save: (key: string, answer: unknown) => void +} + +/** The same prompt under the same instructions asks the same thing, whichever run sends it. */ +export function callKey(call: NotesCall): string { + return createHash('sha256').update(`${call.name}\0${call.system}\0${call.prompt}`).digest('hex') +} + +/** + * `ask`, answered from `answers` where an earlier try asked the same and its answer still fits + * the call's shape. Only answers that fit are kept: a bad one is asked again next time. + */ +export function rememberedAsk(ask: NotesAsk, answers: NotesAnswers | undefined): NotesAsk { + if (!answers) return ask + return async (call) => { + const key = callKey(call) + const known = answers.known[key] + if (known !== undefined && call.schema.safeParse(known).success) return known + const answer = await ask(call) + if (call.schema.safeParse(answer).success) answers.save(key, answer) + return answer + } +} + /** * The pipeline's version, recorded with each session's notes (`NotesRun`). Bump it when a change * would make old notes worth rewriting (better items, a new part of the notes): Settings then @@ -81,6 +113,8 @@ export type WriteNotesOptions = { signal?: AbortSignal | undefined /** Calls done of those planned, after each one (a long meeting takes many). */ onProgress?: ((done: number, total: number) => void) | undefined + /** What an earlier, unfinished try already asked; see `NotesAnswers`. */ + answers?: NotesAnswers | undefined } function durationOf(lines: NotesLine[]): number { @@ -208,7 +242,8 @@ async function overviewOf(sections: NoteSection[], options: WriteNotesOptions): } /** Notes for a meeting: one call when it's short and fits, else by sections (see above). */ -export async function writeNotes(options: WriteNotesOptions): Promise { +export async function writeNotes(input: WriteNotesOptions): Promise { + const options = { ...input, ask: rememberedAsk(input.ask, input.answers) } const { lines, budget, count, ask, signal, onProgress } = options if (!lines.length) throw new Error('This note has no transcript to summarize') const text = lines.map(lineText).join('\n') diff --git a/apps/lyra/src/main/meeting/notesProtocol.ts b/apps/lyra/src/main/meeting/notesProtocol.ts index 843a16d6..a52037b8 100644 --- a/apps/lyra/src/main/meeting/notesProtocol.ts +++ b/apps/lyra/src/main/meeting/notesProtocol.ts @@ -4,7 +4,14 @@ import { NotesLine } from './notesFormat' export const NotesWorkerRequest = z.discriminatedUnion('kind', [ /** Meeting notes for a whole transcript; the worker cuts it into sections to fit the model. */ - z.object({ kind: z.literal('notes'), id: z.number(), modelPath: z.string(), lines: z.array(NotesLine) }), + z.object({ + kind: z.literal('notes'), + id: z.number(), + modelPath: z.string(), + lines: z.array(NotesLine), + /** Answers an earlier, unfinished try already got, by call (`NotesAnswers`). */ + known: z.record(z.string(), z.unknown()) + }), z.object({ kind: z.literal('title'), id: z.number(), modelPath: z.string(), text: z.string() }), /** Stops request `id`, running or queued. */ z.object({ kind: z.literal('cancel'), id: z.number() }), @@ -17,6 +24,8 @@ export const NotesWorkerResponse = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('result'), id: z.number(), result: z.unknown() }), z.object({ kind: z.literal('error'), id: z.number(), error: z.string() }), /** Model calls done of those planned for request `id`; more messages follow. */ - z.object({ kind: z.literal('progress'), id: z.number(), done: z.number(), total: z.number() }) + z.object({ kind: z.literal('progress'), id: z.number(), done: z.number(), total: z.number() }), + /** A model call of request `id` answered: main keeps it, so a retry needn't ask again. */ + z.object({ kind: z.literal('answer'), id: z.number(), key: z.string(), answer: z.unknown() }) ]) export type NotesWorkerResponse = z.infer diff --git a/apps/lyra/src/main/meeting/notesWorker.ts b/apps/lyra/src/main/meeting/notesWorker.ts index edc55d6c..d7a9c95a 100644 --- a/apps/lyra/src/main/meeting/notesWorker.ts +++ b/apps/lyra/src/main/meeting/notesWorker.ts @@ -113,7 +113,12 @@ async function promptOnce( type Work = Exclude -async function answer(request: Work, signal: AbortSignal, onProgress: (done: number, total: number) => void): Promise { +async function answer( + request: Work, + signal: AbortSignal, + onProgress: (done: number, total: number) => void, + onAnswer: (key: string, answer: unknown) => void +): Promise { signal.throwIfAborted() const { llama: runtime, model } = await getModel(request.modelPath) // Chunks are measured with the model's own tokenizer: a character count is ~4x off for @@ -142,6 +147,7 @@ async function answer(request: Work, signal: AbortSignal, onProgress: (done: num count, signal, onProgress, + answers: { known: request.known, save: onAnswer }, ask: async (call) => prompt(model, { grammar: await grammarFor(call.schema), @@ -202,7 +208,10 @@ process.parentPort.on('message', (event: Electron.MessageEvent) => { const onProgress = (done: number, total: number): void => { reply({ kind: 'progress', id: request.id, done, total }) } - enqueue(() => answer(request, controller.signal, onProgress)) + const onAnswer = (key: string, value: unknown): void => { + reply({ kind: 'answer', id: request.id, key, answer: value }) + } + enqueue(() => answer(request, controller.signal, onProgress, onAnswer)) .then( (result) => { reply({ kind: 'result', id: request.id, result }) diff --git a/apps/lyra/src/main/meeting/notesWriter.ts b/apps/lyra/src/main/meeting/notesWriter.ts index 30822a2e..f1eb47a5 100644 --- a/apps/lyra/src/main/meeting/notesWriter.ts +++ b/apps/lyra/src/main/meeting/notesWriter.ts @@ -17,7 +17,7 @@ import { type NotesLine, type WrittenNotes } from './notesFormat' -import { writeNotes } from './notesPipeline' +import { writeNotes, type NotesAnswers } from './notesPipeline' export type NotesOptions = { onDownload?: DownloadProgress | undefined @@ -25,6 +25,8 @@ export type NotesOptions = { signal?: AbortSignal | undefined /** Model calls done of those planned; a long meeting takes one per section. */ onProgress?: ((done: number, total: number) => void) | undefined + /** Answers an earlier, unfinished try at these notes got, and where to keep new ones. */ + answers?: NotesAnswers | undefined } /** @@ -109,7 +111,7 @@ export function createModelNotesWriter(model: LanguageModel, name: string, optio return { name, onDevice: options.onDevice ?? false, - async notes(lines, { signal, onProgress } = {}) { + async notes(lines, { signal, onProgress, answers } = {}) { try { return await writeNotes({ lines, @@ -117,6 +119,7 @@ export function createModelNotesWriter(model: LanguageModel, name: string, optio count, signal, onProgress, + answers, ask: async (call) => { const { output } = await generateText({ model, diff --git a/apps/lyra/src/main/meeting/ollama.ts b/apps/lyra/src/main/meeting/ollama.ts index 3c1ff919..46bbc8d0 100644 --- a/apps/lyra/src/main/meeting/ollama.ts +++ b/apps/lyra/src/main/meeting/ollama.ts @@ -246,7 +246,7 @@ export function createOllamaNotesWriter(options: OllamaWriterOptions): NotesWrit return { name, onDevice: options.onDevice, - async notes(lines, { signal, onProgress } = {}) { + async notes(lines, { signal, onProgress, answers } = {}) { try { const numCtx = await contextFor(fetchFn, root, model, apiKey) const numPredict = Math.min(2048, Math.floor(numCtx / 4)) @@ -256,6 +256,7 @@ export function createOllamaNotesWriter(options: OllamaWriterOptions): NotesWrit count: estimateTokens, signal, onProgress, + answers, // The pipeline checks the answer against the call's schema; this checks it's JSON. ask: (call) => chat( diff --git a/apps/lyra/src/main/meeting/protocol.ts b/apps/lyra/src/main/meeting/protocol.ts index 8ef50598..ece24937 100644 --- a/apps/lyra/src/main/meeting/protocol.ts +++ b/apps/lyra/src/main/meeting/protocol.ts @@ -1,4 +1,5 @@ /** Messages between the main process and the speaker worker (a utilityProcess). */ +import { z } from 'zod' export type SpeakerModels = { segmentation: string @@ -35,21 +36,25 @@ export type EmbedRequest = { export type WorkerRequest = (DiarizeRequest | RollRequest | EmbedRequest) & { id: number } -export type DiarizedSegment = { - start: number - end: number - speaker: number +export const DiarizedSegment = z.object({ + start: z.number(), + end: z.number(), + speaker: z.number(), /** Share of the segment's energy on the mic track (1 = all mic, 0 = all system audio). */ - micShare: number -} + micShare: z.number() +}) +export type DiarizedSegment = z.infer -export type ClusterEmbedding = { speaker: number; embedding: number[] } +export const ClusterEmbedding = z.object({ speaker: z.number(), embedding: z.array(z.number()) }) +export type ClusterEmbedding = z.infer -export type DiarizeResult = { - seconds: number - segments: DiarizedSegment[] - clusters: ClusterEmbedding[] -} +/** A schema as well as a type: relabeling keeps one on disk as a checkpoint (`relabel.ts`). */ +export const DiarizeResult = z.object({ + seconds: z.number(), + segments: z.array(DiarizedSegment), + clusters: z.array(ClusterEmbedding) +}) +export type DiarizeResult = z.infer /** A rolling round's result, with what it cost: numbers for the log. */ export type RollResult = DiarizeResult & { diff --git a/apps/lyra/src/main/meeting/relabel.ts b/apps/lyra/src/main/meeting/relabel.ts index 11a4ad1c..c3addf8f 100644 --- a/apps/lyra/src/main/meeting/relabel.ts +++ b/apps/lyra/src/main/meeting/relabel.ts @@ -1,7 +1,8 @@ import { BrowserWindow } from 'electron' import { z } from 'zod' +import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' -import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { mkdir, readFile, stat, writeFile } from 'node:fs/promises' import { join } from 'node:path' import type { MeetingStatus, TranscriptWord } from '../../shared/types' import { @@ -14,14 +15,16 @@ import { type SessionDoc, type SpeakerEntry } from '../../shared/sessionDoc' +import { clearCheckpoint, readCheckpoint, writeCheckpoint } from '../checkpoints' import { log } from '../log' +import { settle } from '../pendingWork' import { deleteSessionAudio, recordingPageId, trackPath } from '../recorder' import { editSession, readSession, sessionRawDir, updateManifest } from '../sessionStore' import { getSettings } from '../settings' import { notifyLabeled } from './events' import { changedLabels, noteSettled } from './labelChanges' import { learnSamples, mergeSamePerson, mergeTinySpeakers, nameSpeakers, nextPassId } from './pipeline' -import type { DiarizedSegment } from './protocol' +import { DiarizeResult, type DiarizeRequest, type DiarizedSegment } from './protocol' import { audioSeconds, diarize, ensureSpeakerModels } from './speakers' import { startEstimate } from './estimate' import { MIC_SIDE } from './clustering' @@ -288,19 +291,74 @@ function broadcast(status: MeetingStatus): void { const running = new Map>() +/** + * Marks settling the speakers as done, and `next` as owed. Not while the session is being recorded + * again: that take owes its own relabel, which this run's ending mustn't cross off. + */ +async function speakersSettled(pageId: string, next: 'notes' | null = null): Promise { + if (recordingPageId() === pageId) return + await settle(pageId, 'speakers', next ? [next] : []) +} + +const DiarizeCheckpoint = z.object({ key: z.string(), result: DiarizeResult }) + +/** What a diarization was worked out from: the audio as long as it is, the words, the settings. */ +async function diarizeKey(request: Omit): Promise { + const size = async (path: string | null): Promise => + path ? (await stat(path)).size : null + const input = { + mic: await size(request.micPath), + system: await size(request.systemPath), + models: request.models, + threshold: request.threshold, + words: request.words + } + return createHash('sha256').update(JSON.stringify(input)).digest('hex') +} + +/** + * Diarizes the recording, or takes what an earlier try at the same audio and words worked out: + * the longest step of relabeling (minutes for an hour's meeting), so a quit, crash or failure + * after it doesn't cost it again. The checkpoint goes once the pass is written. + */ +async function diarizeOnce( + pageId: string, + request: Omit +): Promise { + const key = await diarizeKey(request) + const kept = await readCheckpoint(pageId, 'diarize', DiarizeCheckpoint) + if (kept?.key === key) { + const segments = kept.result.segments.length + log('relabel', 'diarization kept from an earlier try', { pageId, segments }) + return kept.result + } + const result = await diarize(request) + await writeCheckpoint(pageId, 'diarize', { key, result }) + return result +} + /** Whether any session's speakers are being settled right now. */ export function isRelabeling(): boolean { return running.size > 0 } +/** + * How a run ended: `labeled` wrote a pass with speakers (and asked for the summary), `unlabeled` + * wrote one with none, `skipped` wrote nothing (no audio or words, the session changed meanwhile, + * or it failed), so the session's lines are as they were. + */ +export type RelabelOutcome = 'labeled' | 'unlabeled' | 'skipped' + /** Settles a session's speakers after a recording; one run per session at a time. */ -export function relabelSession(pageId: string): Promise { +export function relabelSession(pageId: string): Promise { const previous = running.get(pageId) ?? Promise.resolve() let finished = false + let outcome: RelabelOutcome = 'skipped' const next = previous .then(() => relabel(pageId)) - .then(() => { + .then((result) => { finished = true + outcome = result }) .catch((error: unknown) => { log('relabel', 'failed', { pageId, error: error instanceof Error ? error.message : String(error) }) @@ -308,6 +366,8 @@ export function relabelSession(pageId: string): Promise { }) .finally(async () => { if (running.get(pageId) === next) running.delete(pageId) + // Done or failed, it's no longer owed (a success already said what comes next). + await speakersSettled(pageId) if (getSettings().audioRetentionDays !== 0 || recordingPageId() === pageId) return // "Keep recordings until transcribed": this was the last step that needed the audio. A // failed run (a model download, a worker crash) keeps it: it's the only copy, and the next @@ -316,7 +376,7 @@ export function relabelSession(pageId: string): Promise { else log('relabel', 'kept audio after a failed relabel', { pageId }) }) running.set(pageId, next) - return next + return next.then(() => outcome) } /** Resolves once any relabeling of `pageId` has finished (fixtures wait on this). */ @@ -324,13 +384,13 @@ export function relabeled(pageId: string): Promise { return running.get(pageId) ?? Promise.resolve() } -async function relabel(pageId: string): Promise { +async function relabel(pageId: string): Promise { const micPath = trackPath(pageId, 'mic') - if (!existsSync(micPath)) return + if (!existsSync(micPath)) return 'skipped' const systemFile = trackPath(pageId, 'system') const systemPath = existsSync(systemFile) ? systemFile : null const words = await liveWords(pageId) - if (!words.length) return + if (!words.length) return 'skipped' const before = await readSession(pageId) const started = Date.now() @@ -339,7 +399,7 @@ async function relabel(pageId: string): Promise { broadcast({ pageId, task: 'speakers', state: 'diarizing', progress: 0, estimate: timing.estimate }) const result = await mergeSamePerson( mergeTinySpeakers( - await diarize({ + await diarizeOnce(pageId, { micPath, systemPath, models, @@ -380,7 +440,7 @@ async function relabel(pageId: string): Promise { if (stale((await readSession(pageId)).transcript)) { log('relabel', 'session changed while diarizing; left as is', { pageId }) broadcast({ pageId, task: 'speakers', state: 'done', progress: 1 }) - return + return 'skipped' } // Moved lines say who the user chose, not which diarized speaker continues whom. @@ -413,7 +473,7 @@ async function relabel(pageId: string): Promise { if (!written) { log('relabel', 'session changed while diarizing; left as is', { pageId }) broadcast({ pageId, task: 'speakers', state: 'done', progress: 1 }) - return + return 'skipped' } // Only now that the pass is in the session may it teach saved voices. await learnSamples(learn) @@ -452,6 +512,9 @@ async function relabel(pageId: string): Promise { ...manifest, passes: [...manifest.passes, { id: passId, kind: 'diarized', createdAt: pass.createdAt, model: pass.model }] })) + await clearCheckpoint(pageId, 'diarize') + // The summary is owed before it is asked for, so a crash while it's written still resumes it. + await speakersSettled(pageId, fields.size >= 1 ? 'notes' : null) timing.finish() broadcast({ pageId, task: 'speakers', state: 'done', progress: 1 }) // How much of what was labeled while recording this pass changed (`labelChanges.ts`). @@ -465,5 +528,7 @@ async function relabel(pageId: string): Promise { liveLabeledSeconds: +stability.labeled.toFixed(1), changedSeconds: +stability.changed.toFixed(1) }) - if (fields.size >= 1) notifyLabeled(pageId) + if (fields.size < 1) return 'unlabeled' + notifyLabeled(pageId) + return 'labeled' } diff --git a/apps/lyra/src/main/meeting/replay.ts b/apps/lyra/src/main/meeting/replay.ts index 897e6b15..82a34dcf 100644 --- a/apps/lyra/src/main/meeting/replay.ts +++ b/apps/lyra/src/main/meeting/replay.ts @@ -25,16 +25,25 @@ function pcm16(samples: Float32Array): Int16Array { return out } +/** + * `crashAt` (seconds): the app dies there instead of stopping, leaving what a crash leaves + * (`recorderFixture.crash`): the audio and words saved so far, nothing finished. + */ export async function replayRecording( pageId: string, micPath: string, systemPath: string | null, - transcribe?: TranscribeExperiment + transcribe?: TranscribeExperiment, + crashAt?: number ): Promise { const mic = await readWav(micPath) const system = systemPath ? await readWav(systemPath) : null await recorderFixture.start(pageId, system !== null, transcribe) for (let at = 0; at < mic.length; at += BATCH) { + if (crashAt !== undefined && at >= crashAt * SAMPLE_RATE) { + await recorderFixture.crash() + return + } recorderFixture.append('mic', pcm16(mic.subarray(at, at + BATCH))) if (system) recorderFixture.append('system', pcm16(system.subarray(at, at + BATCH))) // Let transcription and speaker labeling keep up between batches, as they do while recording: diff --git a/apps/lyra/src/main/pendingWork.ts b/apps/lyra/src/main/pendingWork.ts new file mode 100644 index 00000000..9949af50 --- /dev/null +++ b/apps/lyra/src/main/pendingWork.ts @@ -0,0 +1,57 @@ +import { isQuitting } from './lifecycle' +import { log } from './log' +import type { PendingWork } from './sessionManifest' +import { updateManifest } from './sessionStore' + +/** + * The steps a recording still owes its session (`Manifest.pending`): marked when they become due, + * cleared when they end, so what a quit or crash cut short is resumed at the next start + * (`resume.ts`). A failure clears its step too: it was reported, and retrying it at every launch + * would only report it again. Only the quit itself leaves a step owed. + */ + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +/** Marks `work` as owed by session `id`. */ +export async function owe(id: string, work: readonly PendingWork[]): Promise { + if (!work.length) return + await updateManifest(id, (manifest) => ({ + ...manifest, + pending: [...new Set([...manifest.pending, ...work])] + })).catch((error: unknown) => { + log('resume', 'could not mark work as owed', { id, work, error: errorMessage(error) }) + }) +} + +/** + * Marks `done` as no longer owed even while quitting: for a step whose own last save says for sure + * that it is done (a recording stopped for the quit with all of its audio transcribed). + */ +export async function clearOwed(id: string, done: PendingWork): Promise { + await updateManifest(id, (manifest) => ({ + ...manifest, + pending: manifest.pending.filter((work) => work !== done) + })).catch((error: unknown) => { + log('resume', 'could not mark work as done', { id, done, error: errorMessage(error) }) + }) +} + +/** + * Marks `done` as no longer owed, and `next` as owed, in one write: a crash between the two never + * loses the next step. Does nothing while quitting, when `done` was cut short rather than done. + */ +export async function settle( + id: string, + done: PendingWork, + next: readonly PendingWork[] = [] +): Promise { + if (isQuitting()) return + await updateManifest(id, (manifest) => ({ + ...manifest, + pending: [...new Set([...manifest.pending.filter((work) => work !== done), ...next])] + })).catch((error: unknown) => { + log('resume', 'could not mark work as done', { id, done, error: errorMessage(error) }) + }) +} diff --git a/apps/lyra/src/main/recorder.ts b/apps/lyra/src/main/recorder.ts index 704a7fdb..6ffc1aae 100644 --- a/apps/lyra/src/main/recorder.ts +++ b/apps/lyra/src/main/recorder.ts @@ -5,13 +5,22 @@ import { join } from 'node:path' import { finished } from 'node:stream/promises' import type { AudioTrack, MeetingRecording, TranscriptProgress } from '../shared/types' import { getSettings } from './settings' -import { mergeLivePass, readLiveFile, writeLiveFile, type LiveSegment } from './livePass' +import { + closeOpenMarks, + liveSegmentOf, + mergeLivePass, + readLiveFile, + writeLiveFile, + type LiveSegment, + type Untranscribed +} from './livePass' import { log } from './log' import { notifyLabeled } from './meeting/events' +import { clearOwed, owe } from './pendingWork' import { resolveInNotes } from './pages' import { sessionAudioDir, sessionRawDir, sessionsRoot, updateManifest, type TrackInfo } from './sessionStore' import { TakeWriter } from './takeWriter' -import { ChunkedTranscriber, type TranscribedChunk, type Transcribe, type UnfinishedSpan } from './transcriber' +import { ChunkedTranscriber, type Transcribe } from './transcriber' import { createSpeechClassifier, ensureSpeechVad } from './speechVad' import { BYTES_PER_SECOND, @@ -45,6 +54,12 @@ const HEADER_PATCH_MS = 5000 * isn't transcribed by then is marked in `live.json` rather than silently lost. */ const QUIT_TRANSCRIBE_MS = 5000 +/** + * How often the words so far are saved to `raw/live.json` while recording, with a mark of the + * audio not transcribed yet, so a crash loses only this much transcription (redone from the + * audio at the next start) rather than the whole take's. + */ +const LIVE_CHECKPOINT_MS = 5000 type TrackFile = { track: AudioTrack @@ -72,6 +87,12 @@ type Recording = { headerPatch: Promise /** Whether `live.json` holds an untranscribed marker for this take, to clear when it's done. */ marked: boolean + /** The next save of the words so far, if one is due. */ + checkpointTimer: ReturnType | null + /** Saves of `live.json` in order, so a checkpoint never lands over the take's final save. */ + saving: Promise + /** A fixture's crash: words that come back after it go nowhere, as they would with the app gone. */ + dead: boolean } let active: Recording | null = null @@ -193,6 +214,9 @@ async function start(pageId: string, withSystem: boolean): Promise { if (existing.state === 'corrupt') { log('recorder', 'live.json was unreadable; moved it aside', { pageId, aside: existing.aside }) } + // An earlier take a crash cut short ends where this one starts. + const closed = existing.state === 'ok' ? closeOpenMarks(existing.file, offset) : null + if (closed) await writeLiveFile(sessionRawDir(pageId), closed) // Normally loaded by the window's warm-up already; replays and evals start here. if (transcribeAudio) { await ensureSpeechVad() @@ -213,13 +237,18 @@ async function start(pageId: string, withSystem: boolean): Promise { recording.headerPatch = recording.headerPatch.then(() => patchHeaders(recording)) }, HEADER_PATCH_MS), marked: false, + checkpointTimer: null, + saving: Promise.resolve(), + dead: false, transcriber: new ChunkedTranscriber( [...tracks.keys()], aligned / 2, transcribeAudio ? experiment.transcribe : () => Promise.resolve([]), (chunk) => { - live.push(segmentOf(chunk)) + if (recording.dead) return + live.push(liveSegmentOf(chunk)) writer.write(chunk) + scheduleCheckpoint(recording) // Only while it's still being recorded: once stopped, the whole recording is settled. if (active === recording) for (const listener of chunkListeners) listener(liveTake(recording)) }, @@ -242,6 +271,13 @@ async function start(pageId: string, withSystem: boolean): Promise { return [{ name: track, file: `${track}.wav`, sampleRate: SAMPLE_RATE, seconds: bytes / BYTES_PER_SECOND }] }) await updateManifest(pageId, (manifest) => ({ ...manifest, tracks: listed, audio: 'kept' })) + // Owed from the start: a take a crash cuts short still has its speakers settled next launch, + // and its audio transcribed, even if Whisper hadn't handed out a word yet. + await owe(pageId, [ + ...(transcribeAudio ? (['transcribe'] as const) : []), + ...(identifySpeakers ? (['speakers'] as const) : []) + ]) + if (transcribeAudio) await saveCheckpoint(recording) log('recorder', 'started', { pageId, tracks: [...tracks.keys()], offset }) return offset } catch (error) { @@ -294,19 +330,6 @@ function toFloat(bytes: Buffer): Float32Array { return out } -/** A transcribed chunk as kept in `raw/live.json`, labeled with the track it was heard on. */ -function segmentOf(chunk: TranscribedChunk): LiveSegment { - return { - id: `live-${chunk.track}-${String(Math.round(chunk.start * 1000))}`, - start: chunk.words[0]?.start ?? chunk.start, - end: chunk.words.at(-1)?.end ?? chunk.end, - track: chunk.track, - cluster: null, - confidence: null, - words: chunk.words - } -} - function reportProgress(recording: Recording, progress: { queued: number; queuedSeconds: number }): void { if (progress.queued === recording.queued) return recording.queued = progress.queued @@ -340,31 +363,70 @@ async function finalize(file: TrackFile): Promise { } /** - * Merges this take's words so far into `raw/live.json`, with a marker for the audio of the take - * not transcribed yet. Saving again replaces both, so the take can be saved before Whisper is - * done and again after. True when the take has words. + * Merges this take's words so far into `raw/live.json`, with markers for the audio of the take + * not transcribed yet. Saving again replaces both, so the take can be saved while recording, + * before Whisper is done, and after. Saves run one at a time. True when the take has words. */ -async function saveLivePass(recording: Recording, unfinished: readonly UnfinishedSpan[]): Promise { - if (!recording.live.length && !unfinished.length && !recording.marked) return false - const dir = sessionRawDir(recording.pageId) - try { - const existing = await readLiveFile(dir) - if (existing.state === 'corrupt') { - log('recorder', 'live.json was unreadable; moved it aside', { pageId: recording.pageId, aside: existing.aside }) +function saveLivePass( + recording: Recording, + untranscribed: readonly Omit[] +): Promise { + const save = recording.saving.then(async () => { + if (!recording.live.length && !untranscribed.length && !recording.marked) return false + const dir = sessionRawDir(recording.pageId) + try { + const existing = await readLiveFile(dir) + if (existing.state === 'corrupt') { + log('recorder', 'live.json was unreadable; moved it aside', { pageId: recording.pageId, aside: existing.aside }) + } + const pass = mergeLivePass(existing.state === 'ok' ? existing.file : null, { + model: MODEL_LABEL, + createdAt: new Date().toISOString(), + take: recording.offset, + segments: recording.live, + untranscribed: untranscribed.map((span) => ({ take: recording.offset, ...span })) + }) + await writeLiveFile(dir, pass) + recording.marked = untranscribed.length > 0 + } catch (error) { + log('recorder', 'could not save the live words', { pageId: recording.pageId, error: errorMessage(error) }) } - const pass = mergeLivePass(existing.state === 'ok' ? existing.file : null, { - model: MODEL_LABEL, - createdAt: new Date().toISOString(), - take: recording.offset, - segments: recording.live, - untranscribed: unfinished.map((span) => ({ take: recording.offset, ...span })) - }) - await writeLiveFile(dir, pass) - recording.marked = unfinished.length > 0 - } catch (error) { - log('recorder', 'could not save the live words', { pageId: recording.pageId, error: errorMessage(error) }) - } - return recording.live.length > 0 + return recording.live.length > 0 + }) + recording.saving = save.then(() => undefined) + return save +} + +/** Lists the live pass in the manifest, once the session has one. */ +async function listLivePass(pageId: string, createdAt: string): Promise { + await updateManifest(pageId, (manifest) => ({ + ...manifest, + passes: manifest.passes.some((pass) => pass.id === 'live') + ? manifest.passes + : [...manifest.passes, { id: 'live', kind: 'live', createdAt, model: MODEL_LABEL }] + })) +} + +/** + * Saves the words so far, marking everything after them as not transcribed, open-ended: if the + * app dies before the next save, the next start transcribes the take from there to the end of + * its audio (`resume.ts`). + */ +async function saveCheckpoint(recording: Recording): Promise { + const marks = recording.transcriber + .handedOut() + .map(({ track, at }) => ({ track, start: at, end: at, open: true })) + const hasLive = await saveLivePass(recording, marks) + if (hasLive) await listLivePass(recording.pageId, new Date().toISOString()) +} + +/** A checkpoint a few seconds after a chunk lands, so a burst of chunks is one save. */ +function scheduleCheckpoint(recording: Recording): void { + if (recording.checkpointTimer || active !== recording) return + recording.checkpointTimer = setTimeout(() => { + recording.checkpointTimer = null + if (active === recording) void saveCheckpoint(recording) + }, LIVE_CHECKPOINT_MS) } /** Waits for the take's transcription, up to `limitMs` when given; 'timeout' if it ran out. */ @@ -396,6 +458,8 @@ async function stop(limitMs?: number): Promise { if (!recording) return null active = null clearInterval(recording.headerTimer) + if (recording.checkpointTimer) clearTimeout(recording.checkpointTimer) + recording.checkpointTimer = null await recording.headerPatch const { pageId } = recording const mic = recording.tracks.get('mic') @@ -426,7 +490,7 @@ async function stop(limitMs?: number): Promise { const outcome = await transcriptionDone(transcribing, pageId, limitMs) const unfinished = outcome === 'timeout' ? recording.transcriber.unfinished() : [] if (unfinished.length) { - // Not resumed on the next launch yet: the marker in live.json says what is missing. + // The markers in live.json say what is missing; the next start transcribes it (`resume.ts`). log('recorder', 'stopped before the transcription caught up', { pageId, untranscribed: unfinished.map((span) => ({ ...span, seconds: +(span.end - span.start).toFixed(1) })) @@ -434,14 +498,9 @@ async function stop(limitMs?: number): Promise { } const conversation = await recording.writer.end() hasLive = (await saveLivePass(recording, unfinished)) || hasLive - if (hasLive) { - await updateManifest(pageId, (manifest) => ({ - ...manifest, - passes: manifest.passes.some((pass) => pass.id === 'live') - ? manifest.passes - : [...manifest.passes, { id: 'live', kind: 'live', createdAt: endedAt, model: MODEL_LABEL }] - })) - } + if (hasLive) await listLivePass(pageId, endedAt) + // All of it transcribed: nothing for the next start to pick up, even if this stop is the quit's. + if (!unfinished.length) await clearOwed(pageId, 'transcribe') const result: MeetingRecording = { pageId, @@ -459,7 +518,10 @@ async function stop(limitMs?: number): Promise { // audio and announces the labeled session; without, the live words are final. if (!identifySpeakers) { if (getSettings().audioRetentionDays === 0) await deleteSessionAudio(pageId) - if (conversation) notifyLabeled(pageId) + if (conversation) { + await owe(pageId, ['notes']) + notifyLabeled(pageId) + } } for (const listener of listeners) listener(result) for (const win of BrowserWindow.getAllWindows()) win.webContents.send('recorder:finished', result) @@ -557,7 +619,29 @@ export const recorderFixture = { caughtUp: async (): Promise => { await active?.transcriber.settled() }, - stop + stop, + /** + * The app dying mid-recording, as far as one process can play it: the audio reaches the disk + * with its header as last patched, the words saved so far stay as they are, and nothing is + * finished, saved or announced. Resolves once the dead take's Whisper calls are done, so they + * don't run alongside whatever comes next. + */ + crash: async (): Promise => { + const recording = active + if (!recording) return + active = null + recording.dead = true + clearInterval(recording.headerTimer) + if (recording.checkpointTimer) clearTimeout(recording.checkpointTimer) + await recording.headerPatch + await recording.saving + for (const file of recording.tracks.values()) { + file.stream.end() + await finished(file.stream).catch(() => undefined) + } + await recording.transcriber.settled() + log('recorder', 'crashed (fixture)', { pageId: recording.pageId }) + } } export function registerRecorderIpc(options: { identifySpeakers: boolean; transcribe: boolean }): void { diff --git a/apps/lyra/src/main/resume.ts b/apps/lyra/src/main/resume.ts new file mode 100644 index 00000000..8c6f6aef --- /dev/null +++ b/apps/lyra/src/main/resume.ts @@ -0,0 +1,300 @@ +import { existsSync } from 'node:fs' +import { readFile, stat } from 'node:fs/promises' +import { join } from 'node:path' +import { appendLiveSegment } from '../shared/sessionDoc' +import type { AudioTrack } from '../shared/types' +import { end as endActivity, report as reportActivity } from './activity' +import { + LIVE_FILE, + liveSegmentOf, + liveSegments, + marksToResume, + mergeLivePass, + parseLiveFile, + writeLiveFile, + type LiveFile, + type LiveSegment +} from './livePass' +import { log } from './log' +import type { RelabelOutcome } from './meeting/relabel' +import { readWav } from './meeting/wav' +import { notesDir } from './pages' +import { settle } from './pendingWork' +import { recordingPageId, trackPath } from './recorder' +import { newWords, resumeSpans, spanTracks, type ResumeSpan } from './resumePlan' +import { changeSession, peekManifest, sessionIds, sessionRawDir } from './sessionStore' +import { createSpeechClassifier, ensureSpeechVad } from './speechVad' +import { promptFor } from './takeWriter' +import { ChunkedTranscriber, type TranscribedChunk } from './transcriber' +import { BYTES_PER_SECOND, dataBytesOf, SAMPLE_RATE } from './wavFile' +import { MODEL_LABEL, transcribePcm } from './whisper' + +/** + * Picks up, once at startup, what a quit or crash cut short, one session at a time. Only + * sessions whose manifest owes something are read (`Manifest.pending`): + * + * 1. `transcribe`: audio recorded but not transcribed (the `untranscribed` marks in + * `raw/live.json`: the recorder saves its words every few seconds with a mark of what comes + * after them, and at a quit that couldn't wait for Whisper) is transcribed from the audio. + * 2. `speakers`: settled over the whole recording, which also rebuilds the lines from every word, + * the recovered ones included; that run then owes the summary and asks for it, as after any + * recording. Recovered words get a relabel even if the speakers had been settled already. + * 3. `notes`: a summary still owed is written. + * + * Model downloads resume on their own: each of these steps fetches the model it needs, and a + * download picks up from its `.part` file (`models.ts`). The long steps keep checkpoints of their + * own (`checkpoints.ts`), so what they had done before is not done again. + */ + +export type ResumeDeps = { + /** Whether speakers are settled after a recording (off in test runs, without the models). */ + speakers: boolean + relabel: (pageId: string) => Promise + writeNotes: (pageId: string) => Promise +} + +const LINE_JOIN_GAP = 8 +const MAX_LINE_SECONDS = 30 +/** Audio is read and fed to the transcriber this much at a time, so a long backlog isn't all in memory. */ +const READ_SECONDS = 30 + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +type LiveRead = { state: 'missing' } | { state: 'ok'; file: LiveFile } | { state: 'unreadable' } + +/** + * `raw/live.json` as it is. Never moved aside here, unlike when recording: a file a sync client + * is still writing, or one from a newer Lyra, is left for later and the step stays owed. + */ +async function readLive(pageId: string): Promise { + const path = join(sessionRawDir(pageId), LIVE_FILE) + if (!existsSync(path)) return { state: 'missing' } + const file = parseLiveFile(await readFile(path, 'utf8')) + return file ? { state: 'ok', file } : { state: 'unreadable' } +} + +/** The file now, for a write that merges into it; refuses to write over one it can't read. */ +async function liveForWrite(pageId: string): Promise { + const live = await readLive(pageId) + if (live.state === 'unreadable') throw new Error('live.json became unreadable while resuming') + return live.state === 'ok' ? live.file : null +} + +async function trackSeconds(pageId: string, track: AudioTrack): Promise { + const path = trackPath(pageId, track) + if (!existsSync(path)) return 0 + return dataBytesOf((await stat(path)).size) / BYTES_PER_SECOND +} + +/** + * Whisper's prompt for a span: the session's title and the words heard just before it, as the + * recording would have given it, not text from after the gap. + */ +async function promptBefore(pageId: string, file: LiveFile, from: number): Promise { + const title = await changeSession(pageId, (doc) => doc.title) + const before = liveSegments(file) + .filter((segment) => segment.end <= from) + .sort((a, b) => a.start - b.start) + .map((segment) => segment.words.map((word) => word.text).join('')) + return promptFor(title, before.join(' ')) +} + +/** Transcribes one take's untranscribed audio the way it would have been while recording. */ +async function transcribeSpan( + pageId: string, + span: ResumeSpan, + context: string, + onSeconds: (seconds: number) => void +): Promise { + const tracks = spanTracks(span).filter((track) => existsSync(trackPath(pageId, track))) + const chunks: TranscribedChunk[] = [] + const transcriber = new ChunkedTranscriber( + tracks, + Math.round(span.from * SAMPLE_RATE), + transcribePcm, + (chunk) => { + const kept = newWords(chunk, span.marks) + if (kept) chunks.push(kept) + }, + undefined, + { context, classifier: createSpeechClassifier } + ) + for (let at = span.from; at < span.to; at += READ_SECONDS) { + const until = Math.min(span.to, at + READ_SECONDS) + // Both tracks are cut to the same length, so they stay aligned as the transcriber pairs them. + const length = Math.round((until - at) * SAMPLE_RATE) + for (const track of tracks) { + const read = await readWav(trackPath(pageId, track), at, until) + const samples = new Float32Array(length) + samples.set(read.subarray(0, length)) + transcriber.audio(track, samples) + } + await transcriber.settled() + onSeconds(until - span.from) + } + await transcriber.finish() + return chunks +} + +/** + * Lines for the recovered words, where the session doesn't already show them: only when no + * relabel rebuilt the lines from every word. A line of the same track over the same time (as the + * take wrote it, `live--…`, or as live labeling rewrote it, `roll--…`) already does. + */ +function appendRecovered(pageId: string, segments: readonly LiveSegment[]): Promise { + return changeSession(pageId, (doc) => { + const shown = (segment: LiveSegment): boolean => + doc.transcript.some( + (line) => + (line.id.startsWith(`live-${segment.track}-`) || line.id.startsWith(`roll-${segment.track}-`)) && + line.start < segment.end && + segment.start < line.end + ) + const ordered = [...segments].sort((a, b) => a.start - b.start) + for (const segment of ordered) { + if (shown(segment)) continue + const text = segment.words.map((word) => word.text).join('') + // At the end, as a take writes; the next relabel puts every line in time order. + appendLiveSegment( + doc, + { + id: segment.id, + rawId: null, + start: segment.start, + end: segment.end, + cluster: null, + confidence: null, + text + }, + { joinGap: LINE_JOIN_GAP, maxLine: MAX_LINE_SECONDS } + ) + } + }) +} + +/** + * Drops the marks of `takes`, all transcribed now or with nothing left to transcribe (their audio + * was deleted, or it was all heard after all). A take recorded since keeps its own. + */ +async function dropMarks(pageId: string, takes: ReadonlySet): Promise { + const current = await liveForWrite(pageId) + if (!current) return + const marks = current.untranscribed ?? [] + const kept = marks.filter((mark) => !takes.has(mark.take)) + if (kept.length === marks.length) return + const { untranscribed: _, ...rest } = current + await writeLiveFile(sessionRawDir(pageId), kept.length ? { ...rest, untranscribed: kept } : rest) +} + +/** + * Transcribes the audio `file` marks as untranscribed, and saves the words with the marks gone. + * Returns the recovered segments. + */ +async function resumeTranscription(pageId: string, file: LiveFile): Promise { + const lengths = { mic: await trackSeconds(pageId, 'mic'), system: await trackSeconds(pageId, 'system') } + const spans = resumeSpans(marksToResume(file.untranscribed ?? [], (track) => lengths[track])) + const total = spans.reduce((sum, span) => sum + span.to - span.from, 0) + const activity = { + id: `transcribe:${pageId}`, + kind: 'transcribe' as const, + origin: 'session' as const, + pageId + } + const started = Date.now() + const takes = new Set((file.untranscribed ?? []).map((mark) => mark.take)) + let done = 0 + const recovered: LiveSegment[] = [] + try { + if (spans.length) await ensureSpeechVad() + for (const span of spans) { + const context = await promptBefore(pageId, file, span.from) + const chunks = await transcribeSpan(pageId, span, context, (seconds) => { + reportActivity({ + ...activity, + title: 'Transcribing an interrupted recording', + detail: `${String(Math.round(done + seconds))} of ${String(Math.round(total))} s`, + progress: total ? (done + seconds) / total : null + }) + }) + done += span.to - span.from + const segments = chunks.map(liveSegmentOf) + recovered.push(...segments) + const pass = mergeLivePass(await liveForWrite(pageId), { + model: MODEL_LABEL, + createdAt: new Date().toISOString(), + take: span.take, + segments, + untranscribed: [] + }) + // Saved a take at a time, so a second interruption keeps what this one recovered. + await writeLiveFile(sessionRawDir(pageId), pass) + } + await dropMarks(pageId, takes) + log('resume', 'transcribed interrupted audio', { + pageId, + seconds: +total.toFixed(1), + words: recovered.reduce((sum, segment) => sum + segment.words.length, 0), + ms: Date.now() - started + }) + if (spans.length) endActivity({ ...activity, title: 'Transcribed an interrupted recording' }, 'done') + return recovered + } catch (error) { + endActivity( + { ...activity, title: "Couldn't transcribe an interrupted recording", detail: errorMessage(error) }, + 'failed' + ) + throw error + } +} + +/** Transcribes what a take left untranscribed, if anything; the recovered segments. */ +async function resumeOwedTranscription(pageId: string): Promise { + const live = await readLive(pageId) + if (live.state === 'unreadable') { + log('resume', 'live.json is unreadable; transcription left owed', { pageId }) + return [] + } + try { + const marked = live.state === 'ok' && live.file.untranscribed?.length + const recovered = marked ? await resumeTranscription(pageId, live.file) : [] + await settle(pageId, 'transcribe') + return recovered + } catch (error) { + // Reported in Activity; owed no more, so one bad recording can't hold up its speakers and + // summary at every start. Its marks stay in live.json for `pnpm replay:session`. + log('resume', 'could not transcribe interrupted audio', { pageId, error: errorMessage(error) }) + await settle(pageId, 'transcribe') + return [] + } +} + +async function resumeSession(pageId: string, deps: ResumeDeps): Promise { + const pending = peekManifest(pageId)?.pending ?? [] + if (!pending.length) return false + log('resume', 'resuming', { pageId, pending }) + const recovered = pending.includes('transcribe') ? await resumeOwedTranscription(pageId) : [] + const relabel = deps.speakers && (pending.includes('speakers') || recovered.length > 0) + // A labeled run owes the summary and asks for it itself. + const outcome: RelabelOutcome = relabel ? await deps.relabel(pageId) : 'skipped' + if (!deps.speakers && pending.includes('speakers')) await settle(pageId, 'speakers') + if (outcome === 'skipped' && recovered.length) await appendRecovered(pageId, recovered) + if (outcome !== 'labeled' && pending.includes('notes')) await deps.writeNotes(pageId) + return true +} + +/** Resumes every session's unfinished work, one session at a time; see the top of this file. */ +export async function resumeUnfinishedWork(deps: ResumeDeps): Promise { + let resumed = 0 + for (const pageId of await sessionIds()) { + // A session whose note is gone has nowhere to put the work; one being recorded is the recorder's. + if (!existsSync(join(notesDir(), pageId)) || recordingPageId() === pageId) continue + try { + if (await resumeSession(pageId, deps)) resumed++ + } catch (error) { + log('resume', 'could not resume a session', { pageId, error: errorMessage(error) }) + } + } + if (resumed) log('resume', 'resumed unfinished work', { sessions: resumed }) +} diff --git a/apps/lyra/src/main/resumePlan.test.ts b/apps/lyra/src/main/resumePlan.test.ts new file mode 100644 index 00000000..8dd742b7 --- /dev/null +++ b/apps/lyra/src/main/resumePlan.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { newWords, resumeSpans, spanTracks } from './resumePlan' + +describe('resumeSpans', () => { + it('transcribes each take once, over every track from its earliest mark to its latest end', () => { + const spans = resumeSpans([ + { take: 100, track: 'mic', start: 120, end: 125 }, + { take: 0, track: 'mic', start: 40, end: 60 }, + { take: 0, track: 'system', start: 38.5, end: 60 } + ]) + expect(spans.map(({ take, from, to }) => ({ take, from, to }))).toEqual([ + { take: 0, from: 38.5, to: 60 }, + { take: 100, from: 120, to: 125 } + ]) + expect(spans.map(spanTracks)).toEqual([['mic', 'system'], ['mic']]) + }) +}) + +describe('newWords', () => { + const marks = [ + { take: 0, track: 'mic' as const, start: 40, end: 60 }, + { take: 0, track: 'system' as const, start: 38.5, end: 60 } + ] + + it('keeps only the words its track had not transcribed yet', () => { + const chunk = { + track: 'mic' as const, + start: 38.5, + end: 45, + words: [ + { text: ' kept', start: 38.6, end: 39 }, + { text: ' before', start: 39.9, end: 40.2 }, + { text: ' new', start: 40, end: 40.4 }, + { text: ' words', start: 41, end: 41.5 } + ] + } + expect(newWords(chunk, marks)?.words.map((word) => word.text)).toEqual([' new', ' words']) + }) + + it('drops a chunk with nothing new, and words of a track with no mark', () => { + const early = { + track: 'mic' as const, + start: 38.5, + end: 39.5, + words: [{ text: ' old', start: 38.6, end: 39 }] + } + expect(newWords(early, marks)).toBeNull() + expect( + newWords( + { ...early, track: 'system', start: 70, words: [{ text: ' late', start: 70, end: 71 }] }, + marks + ) + ).toBeNull() + }) +}) diff --git a/apps/lyra/src/main/resumePlan.ts b/apps/lyra/src/main/resumePlan.ts new file mode 100644 index 00000000..667d493e --- /dev/null +++ b/apps/lyra/src/main/resumePlan.ts @@ -0,0 +1,45 @@ +import type { AudioTrack } from '../shared/types' +import type { Untranscribed } from './livePass' +import type { TranscribedChunk } from './transcriber' + +/** + * What resuming an interrupted transcription runs, kept pure for tests: the stretches of audio + * to transcribe again, and which of the words that come back are new. + */ + +/** One take's untranscribed audio: every track from the earliest mark to the latest end. */ +export type ResumeSpan = { take: number; from: number; to: number; marks: Untranscribed[] } + +/** + * The marks of each take as one span. The tracks of a take are transcribed together, as when it + * was recorded (on a call the mic's echo is gated against the system track), so a track whose + * mark starts later is heard again from the earlier one; `newWords` drops what it already had. + */ +export function resumeSpans(marks: readonly Untranscribed[]): ResumeSpan[] { + const byTake = new Map() + for (const mark of marks) byTake.set(mark.take, [...(byTake.get(mark.take) ?? []), mark]) + return [...byTake.entries()] + .sort(([a], [b]) => a - b) + .map(([take, group]) => ({ + take, + from: Math.min(...group.map((mark) => mark.start)), + to: Math.max(...group.map((mark) => mark.end)), + marks: group + })) +} + +/** The tracks a span transcribes. */ +export function spanTracks(span: ResumeSpan): AudioTrack[] { + return [...new Set(span.marks.map((mark) => mark.track))] +} + +/** + * The chunk with only the words its track's mark left untranscribed: a word starting before the + * mark was already kept, by the take itself. Null when none are left. + */ +export function newWords(chunk: TranscribedChunk, marks: readonly Untranscribed[]): TranscribedChunk | null { + const words = chunk.words.filter((word) => + marks.some((mark) => mark.track === chunk.track && word.start >= mark.start && word.start < mark.end) + ) + return words.length ? { ...chunk, words } : null +} diff --git a/apps/lyra/src/main/sessionManifest.test.ts b/apps/lyra/src/main/sessionManifest.test.ts index c839ca66..ac87c39b 100644 --- a/apps/lyra/src/main/sessionManifest.test.ts +++ b/apps/lyra/src/main/sessionManifest.test.ts @@ -19,7 +19,8 @@ const good = { tags: ['team'], speakers: 2, exportHash: 'abc', - dirty: false + dirty: false, + pending: ['speakers', 'notes'] } describe('parseManifest', () => { @@ -64,6 +65,19 @@ describe('parseManifest', () => { expect(read.idMismatch).toBe(true) }) + it('keeps the pending steps it knows, once each', () => { + const read = parseManifest({ ...good, pending: ['notes', 'mystery', 'notes', 7] }, ID, NOW) + if (read.kind !== 'ok') throw new Error('expected ok') + expect(read.manifest.pending).toEqual(['notes']) + }) + + it('reads a manifest from before pending work as owing nothing', () => { + const { pending: _, ...older } = good + const read = parseManifest(older, ID, NOW) + if (read.kind !== 'ok') throw new Error('expected ok') + expect(read.manifest.pending).toEqual([]) + }) + it('refuses what is not a manifest', () => { expect(parseManifest(null, ID, NOW).kind).toBe('invalid') expect(parseManifest([], ID, NOW).kind).toBe('invalid') diff --git a/apps/lyra/src/main/sessionManifest.ts b/apps/lyra/src/main/sessionManifest.ts index f896465f..d97b3671 100644 --- a/apps/lyra/src/main/sessionManifest.ts +++ b/apps/lyra/src/main/sessionManifest.ts @@ -29,6 +29,15 @@ const Pass = z.object({ model: z.string() }) +/** + * A step a recording still owes its session, from when it is due until it is done: its audio + * transcribed (the `untranscribed` marks in `raw/live.json` say which), speakers settled from the + * whole recording, then its summary. Kept in the manifest so a quit or crash in between is picked + * up at the next start (`resume.ts`), which then reads only the sessions that owe something. + */ +export const PendingWork = z.enum(['transcribe', 'speakers', 'notes']) +export type PendingWork = z.infer + export const ManifestSchema = z.object({ version: z.literal(MANIFEST_VERSION), id: z.string(), @@ -49,7 +58,8 @@ export const ManifestSchema = z.object({ /** sha256 of the export as last written, to spot edits made outside Lyra. */ exportHash: z.string().nullable(), /** The document changed since the last export (e.g. Lyra quit mid-debounce). */ - dirty: z.boolean() + dirty: z.boolean(), + pending: z.array(PendingWork) }) export type Manifest = z.infer export type TrackInfo = Manifest['tracks'][number] @@ -115,7 +125,8 @@ export function parseManifest(input: unknown, id: string, now: string): ParsedMa tags: items(z.string(), input.tags), speakers: field(z.number(), input.speakers, 0), exportHash: field(z.string().nullable(), input.exportHash, null), - dirty: input.dirty === true + dirty: input.dirty === true, + pending: [...new Set(items(PendingWork, input.pending))] } return { kind: 'ok', diff --git a/apps/lyra/src/main/sessionStore.ts b/apps/lyra/src/main/sessionStore.ts index 21978d28..5f710d96 100644 --- a/apps/lyra/src/main/sessionStore.ts +++ b/apps/lyra/src/main/sessionStore.ts @@ -135,6 +135,8 @@ const docPathIn = (root: string, id: string): string => join(sessionDirIn(root, const legacyLogPathIn = (root: string, id: string): string => join(sessionDirIn(root, id), 'doc.yjs') export const sessionAudioDir = (id: string): string => join(sessionDir(id), 'audio') export const sessionRawDir = (id: string): string => join(sessionDir(id), 'raw') +/** Work a long step has done so far (`checkpoints.ts`); not a pass, so not in `raw/`. */ +export const sessionCheckpointDir = (id: string): string => join(sessionDir(id), 'checkpoint') /** One model pass over a session's audio, kept as it was produced (docs/SESSION-MODEL.md). */ export type RawPass = { @@ -514,7 +516,8 @@ async function migrateNote(id: string, root: string): Promise { // The file is already what the document says; leave it byte-for-byte as it is. exportHash: sha256(raw), // A migrated meeting's export gains the metadata file; plain notes stay untouched. - dirty: meeting !== null + dirty: meeting !== null, + pending: [] } createDocFile(root, id, doc) writeManifest({ root, manifest, manifestRaw: undefined }) @@ -570,7 +573,8 @@ async function rebuildManifest(id: string, root: string, snapshot: SessionDoc): ...docSummaryFields(snapshot), titleAuto: !snapshot.title.trim(), exportHash: null, - dirty: true + dirty: true, + pending: [] } } @@ -1140,7 +1144,8 @@ export async function createSession(options: CreateSessionOptions = {}): Promise tags: [], speakers: 0, exportHash: sha256(text), - dirty: false + dirty: false, + pending: [] } const entry = makeEntry({ id, root, doc, docRaw: undefined, manifest, manifestRaw: undefined }) writeManifest(entry) diff --git a/apps/lyra/src/main/takeWriter.ts b/apps/lyra/src/main/takeWriter.ts index 80c038a2..4f190a31 100644 --- a/apps/lyra/src/main/takeWriter.ts +++ b/apps/lyra/src/main/takeWriter.ts @@ -25,7 +25,7 @@ const CONTEXT_CHARS = 300 const STYLE_SEED = 'Okay, so here are my thoughts, written out in full sentences.' /** The session's title and the end of its transcript, as Whisper's first prompt. */ -function promptFor(title: string, transcript: string): string { +export function promptFor(title: string, transcript: string): string { const tail = transcript.replace(/\s+/g, ' ').trim().slice(-CONTEXT_CHARS) const start = tail.length === CONTEXT_CHARS ? tail.indexOf(' ') + 1 : 0 const heading = title && title !== 'Untitled' ? `${title}. ` : '' diff --git a/apps/lyra/src/main/tasks/args.ts b/apps/lyra/src/main/tasks/args.ts index 318a5790..68dbdf99 100644 --- a/apps/lyra/src/main/tasks/args.ts +++ b/apps/lyra/src/main/tasks/args.ts @@ -14,6 +14,8 @@ import { ConfigError } from '../config' * [--larger-speaker-model] label with the opt-in speaker-activity model * [--capture] play mic.wav as a fake microphone through the * window's real capture path, in real time + * [--crash] the app dies half way through the recording; + * then resumed as the next start resumes it * * In development the scripts launch `electron . `. Each task runs in a throwaway profile * and exits with its result. @@ -55,7 +57,8 @@ const Meeting = z '--asr': z.enum(['whisper', 'parakeet']).optional(), '--no-context': z.literal(true).optional(), '--larger-speaker-model': z.literal(true).optional(), - '--capture': z.literal(true).optional() + '--capture': z.literal(true).optional(), + '--crash': z.literal(true).optional() }) .strict() .transform((args) => ({ @@ -82,9 +85,15 @@ const Meeting = z * microphone playing the WAV, instead of feeding main directly. Mic only: loopback can't be * faked. */ - capture: args['--capture'] === true + capture: args['--capture'] === true, + /** Stop half way through as a crash would (nothing finished or saved), then resume. */ + crash: args['--crash'] === true })) .refine((task) => !task.capture || task.system === null, '--capture replays the mic track only') + .refine( + (task) => !task.crash || (!task.capture && task.pipeline === 'live'), + '--crash replays a live recording' + ) export type Task = z.output | z.output | z.output diff --git a/apps/lyra/src/main/tasks/meeting.ts b/apps/lyra/src/main/tasks/meeting.ts index 0fa2973e..dda1302e 100644 --- a/apps/lyra/src/main/tasks/meeting.ts +++ b/apps/lyra/src/main/tasks/meeting.ts @@ -12,8 +12,9 @@ import { readWav } from '../meeting/wav' import type { Services } from '../services' import { replayRecording } from '../meeting/replay' import { labelStability } from '../meeting/labelChanges' -import { liveWords, relabeled } from '../meeting/relabel' -import { onRecordingFinished, recordingPageId, trackPath } from '../recorder' +import { liveWords, relabeled, relabelSession } from '../meeting/relabel' +import { onRecordingFinished, recordingPageId, repairInterruptedAudio, trackPath } from '../recorder' +import { resumeUnfinishedWork } from '../resume' import { toggleSession } from '../session' import { log } from '../log' import { transcribeWithParakeet } from '../parakeet' @@ -83,7 +84,20 @@ export async function runMeetingFixture(task: MeetingTask, services: Services): await processMeeting({ pageId: page.id, micPath, systemPath, seconds: 0 }) } else { const transcribe = task.asr === 'parakeet' ? transcribeWithParakeet : transcribePcm - await replayRecording(page.id, wavPath, systemFixture, { transcribe, carryContext: task.context }) + const crashAt = task.crash ? (await readWav(wavPath)).length / 16000 / 2 : undefined + const experiment = { transcribe, carryContext: task.context } + await replayRecording(page.id, wavPath, systemFixture, experiment, crashAt) + if (crashAt !== undefined) { + // What the next start does: mend the audio, then pick up the take where it stopped. + process.stdout.write(`meeting-fixture: crashed at ${crashAt.toFixed(1)} s; resuming +`) + await repairInterruptedAudio() + await resumeUnfinishedWork({ + speakers: task.relabel, + relabel: relabelSession, + writeNotes: (pageId) => services.notes.writeOwed(pageId) + }) + } await relabeled(page.id) } await flushAllSessions() diff --git a/apps/lyra/src/main/tasks/smoke.ts b/apps/lyra/src/main/tasks/smoke.ts index 26052c57..4a66d8fc 100644 --- a/apps/lyra/src/main/tasks/smoke.ts +++ b/apps/lyra/src/main/tasks/smoke.ts @@ -19,6 +19,8 @@ import { editSession, readManifestOf, openSessionFor, + peekManifest, + sessionCheckpointDir, readSession, readSessionFromDisk, restoreSession, @@ -61,6 +63,8 @@ import { import { getSettings, overrideSettings, updateSettings } from '../settings' import { assignSpeaker, sessionAudio } from '../meeting/pipeline' import { relabelSession } from '../meeting/relabel' +import { resumeUnfinishedWork } from '../resume' +import { readCheckpoint, writeCheckpoint } from '../checkpoints' import { MANIFEST_VERSION } from '../sessionManifest' import { wavHeader } from '../wavFile' import { defaultTitle, partOfDay } from '../sessionTitle' @@ -823,6 +827,13 @@ async function checkChunkedTranscriber(): Promise { if (cuts.some((cut) => cut.seconds > 28.5)) fail(`a chunk ran past Whisper's window: ${JSON.stringify(cuts)}`) if (tracks.filter((track) => track === 'mic').length < 3) fail(`a long stretch was not cut: ${out.join(' ')}`) if (transcriber.progress().queued !== 0) fail('chunks still queued after finishing') + + // A later take's marks start where that take does, never at the session's start. + const later = new ChunkedTranscriber(['mic'], 300 * 16000, () => Promise.resolve([]), () => undefined) + const marks = later.handedOut() + if (marks.length !== 1 || marks[0]?.at !== 300) fail(`a new take's mark: ${JSON.stringify(marks)}`) + later.audio('mic', new Float32Array(16000)) + if (later.unfinished().some((span) => span.start < 300)) fail(`unfinished before the take: ${JSON.stringify(later.unfinished())}`) } async function checkTranscriptModel(): Promise { @@ -1168,6 +1179,81 @@ async function checkRelabelKeepsAudio(): Promise { } } +/** + * What a quit or crash cut short is picked up at the next start: a summary still owed is + * written, owed speakers with no way to settle them are let go, untranscribed marks whose audio + * is gone are dropped (the words kept), and a summary's checkpoint goes once the summary is in. + * Only sessions that owe something are read, and an unreadable live.json is left where it is. + */ +async function checkResume(): Promise { + const fail = (message: string): never => { + throw new Error(`resume: ${message}`) + } + const owesNotes = await createPage() + const owesSpeakers = await createPage() + const marked = await createPage() + const owesNothing = await createPage() + const unreadable = await createPage() + const pages = [owesNotes, owesSpeakers, marked, owesNothing, unreadable] + try { + await updateManifest(owesNotes.id, (manifest) => ({ ...manifest, pending: ['notes'] })) + await updateManifest(owesSpeakers.id, (manifest) => ({ ...manifest, pending: ['speakers'] })) + const segment = { id: 'live-mic-0', start: 0, end: 1, track: 'mic', cluster: null, confidence: null, words: [] } + const open = { take: 0, track: 'mic', start: 1, end: 1, open: true } + const markedFile = JSON.stringify({ segments: [segment], untranscribed: [open] }) + const liveOf = (id: string): string => join(sessionRawDir(id), 'live.json') + for (const page of [marked, owesNothing, unreadable]) await mkdir(sessionRawDir(page.id), { recursive: true }) + await writeFile(liveOf(marked.id), markedFile) + await writeFile(liveOf(owesNothing.id), markedFile) + await writeFile(liveOf(unreadable.id), '{"segments": [') + await updateManifest(marked.id, (manifest) => ({ ...manifest, pending: ['transcribe'] })) + await updateManifest(unreadable.id, (manifest) => ({ ...manifest, pending: ['transcribe'] })) + + const notes: string[] = [] + const relabeled: string[] = [] + await resumeUnfinishedWork({ + speakers: false, + relabel: (pageId) => { + relabeled.push(pageId) + return Promise.resolve('skipped' as const) + }, + writeNotes: (pageId) => { + notes.push(pageId) + return Promise.resolve() + } + }) + if (!notes.includes(owesNotes.id) || notes.includes(owesSpeakers.id)) fail(`notes asked for ${JSON.stringify(notes)}`) + if (relabeled.length) fail('relabeled without speaker models') + if (peekManifest(owesSpeakers.id)?.pending.length) fail('owed speakers were kept without a way to settle them') + const live: unknown = JSON.parse(await readFile(liveOf(marked.id), 'utf8')) + const kept = z.looseObject({ segments: z.array(z.unknown()) }).safeParse(live) + if (!kept.success || kept.data.segments.length !== 1 || 'untranscribed' in kept.data) { + fail(`marks with no audio left: ${JSON.stringify(live)}`) + } + if (peekManifest(marked.id)?.pending.length) fail('transcription still owed with nothing left to do') + if ((await readFile(liveOf(owesNothing.id), 'utf8')) !== markedFile) fail('read a session that owed nothing') + if (!existsSync(liveOf(unreadable.id))) fail('moved an unreadable live.json aside') + if (!peekManifest(unreadable.id)?.pending.includes('transcribe')) fail('gave up on an unreadable live.json') + + // A summary written for good takes its checkpoint with it, and is no longer owed. + await editSession(owesNotes.id, (doc) => { + replaceTranscript(doc, [{ id: 'r0', rawId: 'r0', start: 0, end: 2, cluster: 'c0', confidence: null, text: 'We ship Friday.' }]) + }) + const writer = createFakeNotesWriter({ + notes: { decisions: [], actionItems: [], openQuestions: [], summary: 'Shipping.' }, + title: null + }) + await writeCheckpoint(owesNotes.id, 'notes', { writer: writer.name, answers: { a: 1 } }) + if (!(await readCheckpoint(owesNotes.id, 'notes', z.unknown()))) fail('the checkpoint was not saved') + await createMeetingNotes({ writer: () => Promise.resolve(writer) }).generateNotes(owesNotes.id) + if (existsSync(join(sessionCheckpointDir(owesNotes.id), 'notes.json'))) fail('a written summary kept its checkpoint') + await createMeetingNotes({ writer: () => Promise.resolve(null) }).writeOwed(owesNotes.id) + if (peekManifest(owesNotes.id)?.pending.includes('notes')) fail('a summary was still owed after its run') + } finally { + for (const page of pages) await deletePage(page.id) + } +} + /** A WAV whose header was never finalised (a crash) still plays: its audio runs to the end. */ async function checkUnfinishedWav(): Promise { const page = await createPage() @@ -1403,6 +1489,7 @@ export async function runUiSmoke(win: BrowserWindow): Promise { await checkVoices() await checkSettingsFile() await checkRelabelKeepsAudio() + await checkResume() await checkUnfinishedWav() // Last of the index checks: the rebuilt index holds only what changed since (see the report). await checkSearchIndexRecovery() diff --git a/apps/lyra/src/main/transcriber.ts b/apps/lyra/src/main/transcriber.ts index 96ddec1c..748f382b 100644 --- a/apps/lyra/src/main/transcriber.ts +++ b/apps/lyra/src/main/transcriber.ts @@ -126,7 +126,7 @@ export class ChunkedTranscriber { constructor( tracks: readonly AudioTrack[], /** Where this take starts on the session timeline, in samples. */ - start: number, + private readonly start: number, private readonly transcribe: Transcribe, private readonly onChunk: (chunk: TranscribedChunk) => void, private readonly onProgress: (progress: TranscriberProgress) => void = () => undefined, @@ -189,13 +189,35 @@ export class ChunkedTranscriber { */ unfinished(): UnfinishedSpan[] { return [...this.lanes.values()].flatMap((lane) => { - const waiting = this.pending.find((entry) => entry.track === lane.track) - const from = Math.min(waiting?.start ?? Infinity, lane.chunker.pendingFrom() / SAMPLE_RATE) - const end = (lane.at + lane.bufferedLength) / SAMPLE_RATE + const from = this.handedOutTo(lane) + const end = this.receivedTo(lane) return from < end ? [{ track: lane.track, start: +from.toFixed(3), end: +end.toFixed(3) }] : [] }) } + /** + * Per track, where the audio not handed out as words yet starts (where it ends if all of it + * was). Saved while recording, so a crash leaves a mark of what to transcribe again: from there + * to wherever the audio on disk ends. + */ + handedOut(): { track: AudioTrack; at: number }[] { + return [...this.lanes.values()].map((lane) => ({ + track: lane.track, + at: +Math.min(this.handedOutTo(lane), this.receivedTo(lane)).toFixed(3) + })) + } + + private handedOutTo(lane: Lane): number { + const waiting = this.pending.find((entry) => entry.track === lane.track) + const from = Math.min(waiting?.start ?? Infinity, lane.chunker.pendingFrom() / SAMPLE_RATE) + // Before its first frame a chunker says 0, not where the take starts: never before the take. + return Math.max(this.start / SAMPLE_RATE, from) + } + + private receivedTo(lane: Lane): number { + return (lane.at + lane.bufferedLength) / SAMPLE_RATE + } + stats(): Record { const levels = Object.fromEntries( [...this.lanes.values()].flatMap((lane) => { diff --git a/apps/lyra/src/shared/activity.ts b/apps/lyra/src/shared/activity.ts index 6c3602a9..09766dd9 100644 --- a/apps/lyra/src/shared/activity.ts +++ b/apps/lyra/src/shared/activity.ts @@ -5,7 +5,7 @@ */ import { z } from 'zod' -export const ActivityKind = z.enum(['model', 'notes', 'speakers', 'backfill', 'update']) +export const ActivityKind = z.enum(['model', 'notes', 'speakers', 'transcribe', 'backfill', 'update']) export type ActivityKind = z.infer /** diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 149303a6..55ae72c9 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -45,4 +45,6 @@ lyra meeting [system.wav] the real speaker pipeline (pnpm smok [--larger-speaker-model] label with the opt-in speaker-activity model [--capture] play mic.wav as a fake microphone through the window's real capture path, in real time + [--crash] the app dies half way through the recording; + then resumed as the next start resumes it ``` diff --git a/docs/SESSION-MODEL.md b/docs/SESSION-MODEL.md index 908a9e59..2172cb5a 100644 --- a/docs/SESSION-MODEL.md +++ b/docs/SESSION-MODEL.md @@ -59,6 +59,7 @@ agents open, grep and sync. audio/mic.wav audio/system.wav ← raw capture raw/live.json ← words transcribed during recording, per track raw/pass-1.json ← diarization + per-turn re-transcription + checkpoint/diarize.json ← a long step's work so far, until it finishes (derived) doc.json ← the editable document doc.yjs.migrated ← the document as Lyra 0.6 and earlier kept it (Yjs), once migrated ``` @@ -115,9 +116,37 @@ type SessionManifest = { tracks: { name: 'mic' | 'system'; file: string; sampleRate: 16000; seconds: number }[] passes: { id: string; kind: 'live' | 'diarized'; createdAt: string; model: string }[] audio: 'kept' | 'deleted' // retention outcome, so the UI can say why playback is missing + pending: ('transcribe' | 'speakers' | 'notes')[] // steps a recording still owes, until they end } ``` +### Resuming interrupted work + +A quit or crash part way through a session's work is picked up at the next start +(`src/main/resume.ts`), one session at a time: + +- **Only what's owed is read.** Startup looks at each manifest's `pending` and reads nothing else + of a session that owes nothing. An unreadable `live.json` is left where it is and its step stays + owed. +- **Transcription.** `pending` gets `transcribe` when a take starts, and the take's stop clears it + once all of its audio is transcribed. While recording, `raw/live.json` is saved every few + seconds with an `untranscribed` mark per track, open-ended, from where the words handed out so + far end (from the take's start before the first words). A quit that can't wait for Whisper + leaves closed marks. At the next start the marked audio is transcribed again from + `audio/*.wav`, with the words heard just before it as Whisper's prompt, and only the words after + each mark are kept. Recovered words are always relabeled, even if the speakers were already + settled. Without a relabel they're added as lines where no line of their track covers them yet. +- **Speakers and summary.** `pending` gets `speakers` when a take starts. Relabeling swaps it for + `notes` when it finds speakers, and writing the summary clears that. A step that fails is + cleared too, since retrying it at every launch would only report it again. A step cut off by the + quit itself stays owed. +- **Checkpoints.** The long steps keep what they have done in `checkpoint/`: the whole + recording's diarization, keyed by the audio's length, the words and the settings, and each + answer the notes model gave, keyed by prompt and writer. A retry reuses what matches, and each + file is deleted once its step is done. They're kept apart from `raw/`, where every file is a + pass. +- **Downloads** resume from their `.part` file once a step needs the model again. + Small, rewritten atomically (temp file + rename, as `settings.ts` does). The list view reads manifests plus each document's title and tags, never the audio.