diff --git a/.changeset/save-failures.md b/.changeset/save-failures.md new file mode 100644 index 00000000..45abcb99 --- /dev/null +++ b/.changeset/save-failures.md @@ -0,0 +1,5 @@ +--- +'lyra': patch +--- + +When Lyra can't write a session's changes to disk (the disk is full, the folder isn't writable, or another app holds the file), it now says so in Activity with the reason and a Retry button, keeps the changes in memory and keeps trying until they're saved, instead of logging it and losing them when you switch away. And if your settings file can't be read, or holds a "Keep audio" value Lyra can't use, Lyra no longer falls back to 30 days and deletes older recordings at startup: it keeps every recording until you choose again, and tells you. diff --git a/apps/lyra/src/main/audioRetention.ts b/apps/lyra/src/main/audioRetention.ts index 9d95d258..c5a27f39 100644 --- a/apps/lyra/src/main/audioRetention.ts +++ b/apps/lyra/src/main/audioRetention.ts @@ -1,12 +1,13 @@ import { readdir, stat, unlink } from 'node:fs/promises' -import { join } from 'node:path' +import { basename, join } from 'node:path' import type { AudioTrack, RetentionPreview } from '../shared/types' import { audioExpired, retentionCutoff } from '../shared/retention' +import { clear, end } from './activity' import { log } from './log' import { notesDir } from './pages' import { deleteSessionAudio, recordingPageId, trackPath } from './recorder' import { peekManifest, sessionIds } from './sessionStore' -import { getSettings, onSettingsChanged } from './settings' +import { audioRetentionUnread, getSettings, onSettingsChanged, type RetentionUnread } from './settings' /** * Deletes recorded audio older than the "Keep recordings" setting. Transcripts, raw passes and @@ -66,6 +67,11 @@ export async function previewAudioSweep(days: number | null, now = Date.now()): /** Deletes expired audio; returns how many sessions (or legacy files) lost theirs. */ export async function sweepAudio(now = Date.now()): Promise { + // A choice that couldn't be read never deletes anything: it may not be the person's. + if (audioRetentionUnread()) { + log('retention', 'skipped the sweep: the keep audio setting was unreadable') + return 0 + } const days = getSettings().audioRetentionDays // Forever keeps everything; 0 is handled as soon as a session is transcribed. const cutoff = retentionCutoff(days, now) @@ -93,6 +99,23 @@ export async function sweepAudio(now = Date.now()): Promise { let timer: ReturnType | null = null +const UNREAD_ACTIVITY_ID = 'settings:retention' + +/** Says, until "Keep audio" is chosen again, that recordings are being kept and why. */ +function reportUnread(unread: RetentionUnread): void { + const aside = unread.aside ? ` A copy of the old file is in ${basename(unread.aside)}.` : '' + end( + { + id: UNREAD_ACTIVITY_ID, + kind: 'settings', + origin: 'settings', + title: unread.why === 'file' ? 'Couldn’t read your settings' : 'Couldn’t read how long to keep audio', + detail: `No recordings are deleted until you choose again in Settings → Keep audio.${aside}` + }, + 'failed' + ) +} + /** Sweeps now, once a day after, and whenever the setting or the notes folder changes. */ export function startAudioRetention(): void { const run = (): void => { @@ -100,9 +123,12 @@ export function startAudioRetention(): void { log('retention', 'sweep failed', String(error)) }) } + const unread = audioRetentionUnread() + if (unread) reportUnread(unread) run() timer ??= setInterval(run, SWEEP_EVERY_MS) onSettingsChanged((next, prev) => { + if (unread && !audioRetentionUnread()) clear(UNREAD_ACTIVITY_ID) if (next.audioRetentionDays !== prev.audioRetentionDays || next.notesDir !== prev.notesDir) run() }) } diff --git a/apps/lyra/src/main/docSave.test.ts b/apps/lyra/src/main/docSave.test.ts new file mode 100644 index 00000000..724b7ad5 --- /dev/null +++ b/apps/lyra/src/main/docSave.test.ts @@ -0,0 +1,153 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + flushSave, + hasUnsaved, + markUnsaved, + newSaveState, + retryDelay, + writeFailureReason, + type SaveIo +} from './docSave' + +const diskFull = (): Error => Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }) + +/** A document whose next `failNext` writes fail; `disk` is what landed last. */ +function harness() { + let doc = 'v0' + const calls: { failed: number[]; recovered: number; writes: string[] } = { failed: [], recovered: 0, writes: [] } + const io: SaveIo & { failNext: number; disk: string | null } = { + failNext: 0, + disk: null, + snapshot: () => doc, + write: (text: string): Promise => { + calls.writes.push(text) + if (io.failNext > 0) { + io.failNext-- + return Promise.reject(diskFull()) + } + io.disk = text + return Promise.resolve() + }, + failed: (_error: unknown, failures: number) => { + calls.failed.push(failures) + }, + recovered: () => { + calls.recovered++ + } + } + const state = newSaveState() + const edit = (next: string): void => { + doc = next + markUnsaved(state, Date.now()) + } + return { io, state, calls, edit } +} + +beforeEach(() => { + vi.useFakeTimers() +}) +afterEach(() => { + vi.useRealTimers() +}) + +describe('flushSave', () => { + it('saves a change and leaves nothing unsaved', async () => { + const { io, state, edit } = harness() + edit('v1') + await flushSave(state, io) + expect(io.disk).toBe('v1') + expect(hasUnsaved(state)).toBe(false) + }) + + it('keeps a change unsaved when its write fails, and says so', async () => { + const { io, state, calls, edit } = harness() + io.failNext = Infinity + edit('v1') + await flushSave(state, io) + expect(io.disk).toBeNull() + expect(hasUnsaved(state)).toBe(true) + expect(calls.failed).toEqual([1]) + }) + + it('writes the change on the next flush once the disk takes it', async () => { + const { io, state, calls, edit } = harness() + io.failNext = Infinity + edit('v1') + await flushSave(state, io) + io.failNext = 0 + // What a quit or an unload does: before the fix this was a no-op and v1 was lost. + await flushSave(state, io) + expect(io.disk).toBe('v1') + expect(hasUnsaved(state)).toBe(false) + expect(calls.recovered).toBe(1) + }) + + it('tries again on its own, backing off, until a write lands', async () => { + const { io, state, calls, edit } = harness() + io.failNext = Infinity + edit('v1') + await flushSave(state, io) + await vi.advanceTimersByTimeAsync(retryDelay(1)) + expect(calls.failed).toEqual([1, 2]) + await vi.advanceTimersByTimeAsync(retryDelay(2)) + expect(calls.failed).toEqual([1, 2, 3]) + io.failNext = 0 + await vi.advanceTimersByTimeAsync(retryDelay(3)) + expect(io.disk).toBe('v1') + expect(hasUnsaved(state)).toBe(false) + expect(calls.recovered).toBe(1) + // Nothing left to retry. + const writes = calls.writes.length + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(calls.writes.length).toBe(writes) + }) + + it('a retry writes the latest document, with changes made while it was failing', async () => { + const { io, state, edit } = harness() + io.failNext = Infinity + edit('v1') + await flushSave(state, io) + edit('v2') + io.failNext = 0 + await vi.advanceTimersByTimeAsync(retryDelay(1)) + expect(io.disk).toBe('v2') + expect(hasUnsaved(state)).toBe(false) + }) + + it('a later write that holds every change covers an earlier failure', async () => { + const { io, state, calls, edit } = harness() + io.failNext = 1 + edit('v1') + const first = flushSave(state, io) + edit('v2') + // The first write fails, the second (queued behind it, with v2) lands. + const second = flushSave(state, io) + await Promise.all([first, second]) + expect(io.disk).toBe('v2') + expect(hasUnsaved(state)).toBe(false) + expect(calls.recovered).toBe(1) + }) + + it('does nothing when there is nothing to save', async () => { + const { io, state, calls } = harness() + await flushSave(state, io) + expect(calls.writes).toEqual([]) + }) +}) + +describe('retryDelay', () => { + it('backs off, then repeats the longest wait', () => { + expect([1, 2, 3, 4, 5, 50].map(retryDelay)).toEqual([1000, 5000, 15_000, 60_000, 60_000, 60_000]) + }) +}) + +describe('writeFailureReason', () => { + it('says why in plain words', () => { + expect(writeFailureReason(diskFull())).toBe('the disk is full') + expect(writeFailureReason(Object.assign(new Error('x'), { code: 'EACCES' }))).toBe( + 'Lyra isn’t allowed to write to the notes folder' + ) + expect(writeFailureReason(new Error('odd'))).toBe('the disk refused the write') + expect(writeFailureReason('not an error')).toBe('the disk refused the write') + }) +}) diff --git a/apps/lyra/src/main/docSave.ts b/apps/lyra/src/main/docSave.ts new file mode 100644 index 00000000..8b8e9a74 --- /dev/null +++ b/apps/lyra/src/main/docSave.ts @@ -0,0 +1,111 @@ +/** + * Saving one session's document (`doc.json`). Pure (no Electron), so the rules can be + * unit-tested: a change stays unsaved until a write that holds it lands, a failed write is tried + * again with backoff (a local write is free, so it keeps trying), and the store hears when saving + * starts failing and when it works again, to tell the person (docs/STATES.md). + */ + +/** Waits between tries after a failed write; the last one repeats until a write lands. */ +export const SAVE_RETRY_MS: readonly number[] = [1000, 5000, 15_000, 60_000] + +export type SaveState = { + /** When the oldest change not yet saved was made; null when everything is saved. */ + unsavedSince: number | null + /** Counts changes, so a write can tell whether it holds the latest one. */ + changes: number + /** The save being written; saves run one after another, so the newest lands last. */ + saving: Promise + /** Writes that failed in a row; 0 once one lands. */ + failures: number + retryTimer: ReturnType | null +} + +export type SaveIo = { + /** The document as it is now, as the file's text. */ + snapshot: () => string + write: (text: string) => Promise + /** A write failed; `failures` counts them since the last one that landed. */ + failed: (error: unknown, failures: number) => void + /** A write landed after one or more failed. */ + recovered: () => void +} + +export function newSaveState(): SaveState { + return { unsavedSince: null, changes: 0, saving: Promise.resolve(), failures: 0, retryTimer: null } +} + +/** A change was made and needs saving. */ +export function markUnsaved(state: SaveState, now: number): void { + state.unsavedSince ??= now + state.changes++ +} + +/** Whether the document has changes that aren't on disk, written or failed. */ +export const hasUnsaved = (state: SaveState): boolean => state.unsavedSince !== null || state.failures > 0 + +export function retryDelay(failures: number): number { + const index = Math.min(Math.max(failures, 1), SAVE_RETRY_MS.length) - 1 + return SAVE_RETRY_MS[index] ?? 1000 +} + +/** + * Writes the document as it is now, if it has changes not saved yet, and resolves once every + * save so far has been tried. Never rejects: a failed write leaves the document unsaved, tells + * `io.failed` and tries again later; `hasUnsaved` says whether it's on disk. + */ +export function flushSave(state: SaveState, io: SaveIo): Promise { + if (state.retryTimer) clearTimeout(state.retryTimer) + state.retryTimer = null + const since = state.unsavedSince + if (since === null) return state.saving + state.unsavedSince = null + const upTo = state.changes + const text = io.snapshot() + state.saving = state.saving.then(() => + io.write(text).then( + () => { + // This write holds every change so far: an earlier failure is covered by it. + if (state.changes === upTo) { + state.unsavedSince = null + if (state.retryTimer) clearTimeout(state.retryTimer) + state.retryTimer = null + } + if (state.failures === 0) return + state.failures = 0 + io.recovered() + }, + (error: unknown) => { + // Still unsaved: the next write takes this change along with any made since. + state.unsavedSince = Math.min(since, state.unsavedSince ?? since) + state.failures++ + io.failed(error, state.failures) + if (state.retryTimer) clearTimeout(state.retryTimer) + state.retryTimer = setTimeout(() => void flushSave(state, io), retryDelay(state.failures)) + } + ) + ) + return state.saving +} + +/** Why a write failed, in plain words for the person, from the file system's error code. */ +export function writeFailureReason(error: unknown): string { + const code = error instanceof Error && 'code' in error ? error.code : null + switch (code) { + case 'ENOSPC': + case 'EDQUOT': + return 'the disk is full' + case 'EACCES': + case 'EPERM': + return 'Lyra isn’t allowed to write to the notes folder' + case 'EBUSY': + return 'another app has the file open' + case 'EROFS': + return 'the drive is read-only' + case 'ENOENT': + case 'ENODEV': + case 'ENXIO': + return 'the notes folder can’t be found (was a drive removed?)' + default: + return 'the disk refused the write' + } +} diff --git a/apps/lyra/src/main/sessionStore.ts b/apps/lyra/src/main/sessionStore.ts index 5f710d96..2477c486 100644 --- a/apps/lyra/src/main/sessionStore.ts +++ b/apps/lyra/src/main/sessionStore.ts @@ -3,7 +3,17 @@ import { createHash } from 'node:crypto' import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import { copyFile, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises' import { extname, join } from 'node:path' +import { clear, end, onActivityAction } from './activity' import { asideStamp, writeFileAtomic, writeFileAtomicSync } from './atomicFile' +import { + flushSave as saveFlush, + hasUnsaved, + markUnsaved, + newSaveState, + writeFailureReason, + type SaveIo, + type SaveState +} from './docSave' import { legacySessionDoc, readLegacyLog } from './legacyYjs' import { manifestForDisk, @@ -98,10 +108,8 @@ type Entry = { subscribers: Set exportTimer: ReturnType | null saveTimer: ReturnType | null - /** When the oldest change not yet saved was made; null when everything is saved. */ - unsavedSince: number | null - /** The save being written; saves run one after another, so the newest lands last. */ - saving: Promise + /** What isn't on disk yet, the write in flight, and failed writes being tried again. */ + save: SaveState unloadTimer: ReturnType | null exporting: Promise } @@ -588,8 +596,7 @@ function makeEntry(init: Pick { await flushExport(entry) // Someone acquired it, or it was replaced, while the export ran: leave it to them. if (inUse(entry) || (!isCurrent(entry) && !entry.closed)) return + // Its document couldn't be written: this copy is the only one with the latest changes, so it + // stays loaded (and keeps being retried) until a write lands; `saveRecovered` unloads it then. + if (hasUnsaved(entry.save)) return // `flushExport` saved it, and nothing has changed it since (nobody holds it). if (isCurrent(entry)) open.delete(keyOf(entry.root, entry.id)) } @@ -776,31 +786,71 @@ function setTitleAuto(entry: Entry, titleAuto: boolean): void { function scheduleSave(entry: Entry): void { const now = Date.now() - entry.unsavedSince ??= now + markUnsaved(entry.save, now) if (entry.saveTimer) clearTimeout(entry.saveTimer) - const delay = Math.min(SAVE_DELAY_MS, Math.max(0, entry.unsavedSince + SAVE_MAX_WAIT_MS - now)) + const since = entry.save.unsavedSince ?? now + const delay = Math.min(SAVE_DELAY_MS, Math.max(0, since + SAVE_MAX_WAIT_MS - now)) entry.saveTimer = setTimeout(() => void flushSave(entry), delay) } +/** Sessions whose document couldn't be written, by id, until a write of it lands. */ +const unsaved = new Map() +const saveActivityId = (id: string): string => `save:${id}` + +function saveIo(entry: Entry): SaveIo { + return { + snapshot: () => docFile(entry.doc, entry.docRaw), + write: (text) => writeFileAtomic(docPathIn(entry.root, entry.id), text), + failed: (error, failures) => { + log('sessions', 'could not save a session', { id: entry.id, failures, error: String(error) }) + unsaved.set(entry.id, entry) + // Persistent until a write lands: the changes exist only in memory (docs/STATES.md). + end( + { + id: saveActivityId(entry.id), + kind: 'save', + origin: 'session', + pageId: entry.id, + title: 'Couldn’t save your latest changes', + detail: `${capitalize(writeFailureReason(error))}. Lyra keeps them and tries again; keep it open until this clears.`, + actions: ['retry', 'open'] + }, + 'failed' + ) + }, + recovered: () => { + log('sessions', 'saved a session after failed writes', { id: entry.id }) + if (unsaved.get(entry.id) === entry) unsaved.delete(entry.id) + clear(saveActivityId(entry.id)) + // `unload` kept it loaded while it was unsaved; let it go now if nobody holds it. + if (!inUse(entry) && (isCurrent(entry) || entry.closed)) { + if (entry.unloadTimer) clearTimeout(entry.unloadTimer) + entry.unloadTimer = setTimeout(() => void unload(entry), UNLOAD_AFTER_MS) + } + } + } +} + +const capitalize = (text: string): string => text.charAt(0).toUpperCase() + text.slice(1) + /** * Writes the document as it is now, if it has changes not saved yet, and resolves once every - * save so far is on disk. Atomic and durable, as the manifest is; never throws. + * save so far has been tried. Atomic and durable, as the manifest is; never throws. A failed + * write keeps the changes unsaved, shows in Activity and is tried again (`docSave.ts`). */ function flushSave(entry: Entry): Promise { if (entry.saveTimer) clearTimeout(entry.saveTimer) entry.saveTimer = null - if (entry.unsavedSince === null) return entry.saving - entry.unsavedSince = null - const text = docFile(entry.doc, entry.docRaw) - const path = docPathIn(entry.root, entry.id) - entry.saving = entry.saving.then(() => - writeFileAtomic(path, text).catch((error: unknown) => { - log('sessions', 'could not save a session', { id: entry.id, error: String(error) }) - }) - ) - return entry.saving + return saveFlush(entry.save, saveIo(entry)) } +/** Activity's Retry on a session that couldn't be saved. */ +onActivityAction('save', async (item, action) => { + if (action !== 'retry' || !item.pageId) return + const entry = unsaved.get(item.pageId) + if (entry) await flushSave(entry) +}) + function scheduleExport(entry: Entry, delay: number): void { if (entry.exportTimer) clearTimeout(entry.exportTimer) entry.exportTimer = setTimeout(() => { @@ -1409,8 +1459,10 @@ export function closeSessionFor(id: string, contentsId: number): void { /** Writes pending saves and exports; called on quit. Safe to call twice. */ export async function flushAllSessions(): Promise { - for (const entry of [...open.values()]) { + // Sessions closed by a folder change while unsaved are no longer in `open`, but still owed. + for (const entry of new Set([...open.values(), ...unsaved.values()])) { await flushExport(entry).catch(() => undefined) + if (hasUnsaved(entry.save)) log('sessions', 'a session is still unsaved', { id: entry.id }) } } diff --git a/apps/lyra/src/main/settings.ts b/apps/lyra/src/main/settings.ts index 43c2a899..d5d9d913 100644 --- a/apps/lyra/src/main/settings.ts +++ b/apps/lyra/src/main/settings.ts @@ -4,11 +4,11 @@ import { homedir } from 'node:os' import { dirname, join } from 'node:path' import { defaultLanguage } from '../shared/languages' import { DEFAULT_SEND_PARTS } from '../shared/sendParts' -import { PANEL_WIDTHS, parseSettings, type Settings } from '../shared/settings' +import { PANEL_WIDTHS, parseSettings, readSettings, type Settings } from '../shared/settings' import { writeFileAtomic } from './atomicFile' import { config } from './config' import { log } from './log' -import { readSettingsFile, settingsForDisk } from './settingsFile' +import { readSettingsFile, retentionUnread, settingsForDisk } from './settingsFile' export function defaultSettings(): Settings { return { @@ -51,6 +51,19 @@ let current: Settings | null = null let stored: Record = {} const listeners = new Set() +export type RetentionUnread = { why: 'file' | 'field'; aside: string | null } +/** + * Set when the "Keep audio" choice couldn't be read at startup, until one is saved: recordings + * are kept meanwhile (see `retentionUnread`). + */ +let unreadRetention: RetentionUnread | null = null + +/** Why the "Keep audio" choice couldn't be read, or null once it could (or was chosen again). */ +export function audioRetentionUnread(): RetentionUnread | null { + getSettings() + return unreadRetention +} + function settingsPath(): string { return join(app.getPath('userData'), 'settings.json') } @@ -72,7 +85,16 @@ export function getSettings(): Settings { }) break } - current = parseSettings(stored, defaultSettings()) + const { settings, rejected } = readSettings(stored, defaultSettings()) + if (rejected.length) log('settings', 'settings file had values this build can’t use; using defaults', { rejected }) + current = settings + const why = retentionUnread(read, rejected) + if (why) { + // Never the default 30 days, which the sweep would act on at once: keep every recording. + unreadRetention = { why, aside: read.kind === 'corrupt' ? read.aside : null } + current = { ...current, audioRetentionDays: null } + log('settings', 'keep audio setting unread; keeping recordings until it is chosen again', { why }) + } return current } @@ -94,6 +116,7 @@ export async function updateSettings(patch: Partial): Promise mkdtempSync(join(tmpdir(), 'lyra-settings-')) @@ -42,3 +43,64 @@ describe('settingsForDisk', () => { expect(settingsForDisk(stored, { hotkey: 'new' })).toEqual({ hotkey: 'new', fromTheFuture: { on: true } }) }) }) + +describe('retentionUnread', () => { + // What main's defaults hold: 30 days, which the sweep would act on at startup. + const defaults: Settings = { + notesDir: '/tmp/notes', + fileFormat: 'txt', + micDeviceId: null, + hotkey: 'Alt+Space', + launchAtLogin: false, + micPrompt: { enabled: false, ignoredApps: [] }, + meetingPrompt: true, + audioRetentionDays: 30, + captureSystemAudio: true, + transcriptionLanguage: 'auto', + vocabulary: [], + notesEngine: 'off', + cloudProvider: 'anthropic', + cloudModel: null, + cloudBaseUrl: null, + meetingNoticeSeen: false, + semanticSearch: false, + largerSpeakerModel: false, + sendToParts: [], + sidebar: true, + sidebarWidth: 260 + } + + const read = (text: string) => { + const path = join(dir(), 'settings.json') + writeFileSync(path, text) + const file = readSettingsFile(path) + const { settings, rejected } = readSettings(file.kind === 'ok' ? file.raw : {}, defaults) + return { settings, why: retentionUnread(file, rejected) } + } + + it('does not trust the default when the file is corrupt', () => { + const { settings, why } = read('{"audioRetentionDays": null, ') + expect(settings.audioRetentionDays).toBe(30) + expect(why).toBe('file') + }) + + it('does not trust the default when only the retention value is unusable', () => { + for (const value of ['"forever"', '-1', '99999']) { + const { settings, why } = read(`{"audioRetentionDays": ${value}, "hotkey": "Alt+K"}`) + expect(settings.audioRetentionDays).toBe(30) + expect(settings.hotkey).toBe('Alt+K') + expect(why).toBe('field') + } + }) + + it('trusts a value that was read, and a default for a field never written', () => { + expect(read('{"audioRetentionDays": null}')).toMatchObject({ settings: { audioRetentionDays: null }, why: null }) + expect(read('{"audioRetentionDays": 7}').why).toBeNull() + expect(read('{"hotkey": "Alt+K"}').why).toBeNull() + expect(retentionUnread({ kind: 'missing' }, [])).toBeNull() + }) + + it('does not blame retention for another field that fell back', () => { + expect(read('{"audioRetentionDays": 7, "fileFormat": "docx"}').why).toBeNull() + }) +}) diff --git a/apps/lyra/src/main/settingsFile.ts b/apps/lyra/src/main/settingsFile.ts index 36797615..f9496627 100644 --- a/apps/lyra/src/main/settingsFile.ts +++ b/apps/lyra/src/main/settingsFile.ts @@ -51,6 +51,17 @@ export function readSettingsFile(path: string): SettingsFileRead { return { kind: 'ok', raw: parsed } } +/** + * Why the "Keep audio" choice can't be trusted, or null when it can. A file that couldn't be + * read (`file`), or a value the schema refused (`field`: a hand edit, or a value a newer Lyra + * allows), falls back to a default the person may never have chosen; the retention sweep must + * not delete recordings on that, so they're kept until a value is chosen again. + */ +export function retentionUnread(read: SettingsFileRead, rejected: readonly string[]): 'file' | 'field' | null { + if (read.kind === 'corrupt') return 'file' + return rejected.includes('audioRetentionDays') ? 'field' : null +} + /** The settings over what the file held, so keys a newer Lyra wrote survive this one saving. */ export function settingsForDisk(stored: Record, settings: object): Record { return { ...stored, ...settings } diff --git a/apps/lyra/src/shared/activity.ts b/apps/lyra/src/shared/activity.ts index 09766dd9..5d653786 100644 --- a/apps/lyra/src/shared/activity.ts +++ b/apps/lyra/src/shared/activity.ts @@ -5,7 +5,17 @@ */ import { z } from 'zod' -export const ActivityKind = z.enum(['model', 'notes', 'speakers', 'transcribe', 'backfill', 'update']) +/** `save`: a session's changes couldn't be written; `settings`: the settings file couldn't be read. */ +export const ActivityKind = z.enum([ + 'model', + 'notes', + 'speakers', + 'transcribe', + 'backfill', + 'update', + 'save', + 'settings' +]) export type ActivityKind = z.infer /** diff --git a/apps/lyra/src/shared/settings.ts b/apps/lyra/src/shared/settings.ts index e130b629..d2ed2301 100644 --- a/apps/lyra/src/shared/settings.ts +++ b/apps/lyra/src/shared/settings.ts @@ -117,13 +117,22 @@ const isRecord = (value: unknown): value is Record => * falls back to `base`'s value, so a hand-edited or older file never stops Lyra from starting. */ export function parseSettings(input: unknown, base: Settings): Settings { + return readSettings(input, base).settings +} + +/** + * `parseSettings`, plus the fields that fell back to `base` because the file's value was + * malformed (not merely missing): a caller deciding something destructive from one of them + * (the "Keep recordings" sweep) must not trust the fallback. + */ +export function readSettings(input: unknown, base: Settings): { settings: Settings; rejected: string[] } { const merged = { ...base, ...(isRecord(input) ? migrate(input) : {}) } const first = SettingsSchema.safeParse(merged) - if (first.success) return first.data - const bad = new Set(first.error.issues.map((issue) => issue.path[0])) + if (first.success) return { settings: first.data, rejected: [] } + const bad = new Set(first.error.issues.flatMap((issue) => (typeof issue.path[0] === 'string' ? [issue.path[0]] : []))) const fallback: Record = base const repaired = Object.fromEntries( Object.entries(merged).map(([key, value]) => [key, bad.has(key) ? fallback[key] : value]) ) - return SettingsSchema.parse(repaired) + return { settings: SettingsSchema.parse(repaired), rejected: [...bad] } } diff --git a/docs/STATES.md b/docs/STATES.md index f67f2125..32384f42 100644 --- a/docs/STATES.md +++ b/docs/STATES.md @@ -78,6 +78,12 @@ indicator, only a failure. Spinners stop under reduced motion; the words carry t - Blocked before it starts: say what still works, link to the exact system setting, clear it once fixed. - A crashed pane: "Your notes are safe" first, then Reload this pane. +- A session that couldn't be saved: an Activity row (`save:`) with the reason and + Retry, until a write lands. The changes stay in memory and are retried with backoff + (`src/main/docSave.ts`); the session isn't unloaded while it holds unsaved changes. +- Settings that couldn't be read: nothing destructive acts on a fallback value. An unreadable + "Keep audio" keeps every recording until it's chosen again, and says so in Activity + (`settings:retention`). Retry on its own only when it's free and transient (download drops, three times with backoff), never a paid cloud call more than once. Keep the work: a failed summary keeps the old one.