Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/resume-interrupted-work.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file.wav> [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 <file.wav> [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 <session>` 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 |
Expand Down
60 changes: 60 additions & 0 deletions apps/lyra/src/main/checkpoints.ts
Original file line number Diff line number Diff line change
@@ -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/<id>/checkpoint/<name>.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<T>(
id: string,
name: CheckpointName,
schema: z.ZodType<T>
): Promise<T | null> {
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<void> {
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<void> {
await rm(pathOf(id, name), { force: true }).catch((error: unknown) => {
log('checkpoint', 'could not delete a checkpoint', { id, name, error: errorMessage(error) })
})
}
13 changes: 13 additions & 0 deletions apps/lyra/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -607,6 +609,7 @@ void app.whenReady().then(() => {
enabled: !isTestRun,
beforeInstall: () => {
quitting = true
markQuitting()
}
})
saveForPower = registerPowerHandling(saveWork)
Expand Down Expand Up @@ -659,6 +662,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' })

Expand Down Expand Up @@ -716,6 +728,7 @@ async function shutdownWork(): Promise<void> {
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
Expand Down
14 changes: 14 additions & 0 deletions apps/lyra/src/main/lifecycle.ts
Original file line number Diff line number Diff line change
@@ -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
}
40 changes: 39 additions & 1 deletion apps/lyra/src/main/livePass.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }] }
Expand Down Expand Up @@ -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 }
])
})
})
52 changes: 48 additions & 4 deletions apps/lyra/src/main/livePass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -25,15 +26,18 @@ export const LiveSegment = z.looseObject({
export type LiveSegment = z.infer<typeof LiveSegment>

/**
* 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<typeof Untranscribed>

Expand Down Expand Up @@ -127,6 +131,46 @@ export async function writeLiveFile(dir: string, pass: Record<string, unknown>):
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) =>
Expand Down
Loading
Loading