Skip to content

The agent that grows with you

fix(desktop): a corrupt prepared-submission journal no longer blocks every send

Teknium3edb6e3e9e86
diff --git a/apps/desktop/electron/prepared-submissions.test.ts b/apps/desktop/electron/prepared-submissions.test.ts
index 1ab0a73d55a..36409631126 100644
--- a/apps/desktop/electron/prepared-submissions.test.ts
+++ b/apps/desktop/electron/prepared-submissions.test.ts
@@ -23,3 +23,22 @@ test('acknowledged journal mutations survive reopening with exact payload and or
fs.rmSync(dir, { recursive: true, force: true })
}
})
+
+test('a corrupt journal is quarantined with its bytes kept, and the origin can send again', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'prepared-journal-'))
+
+ try {
+ const origin = 'http://localhost:5174'
+ preparedJournal(dir, origin).update('kept', { id: 'id-a' })
+ const [file] = fs.readdirSync(dir).map(name => path.join(dir, name))
+ fs.writeFileSync(file, '{"kept":{"id":"id-')
+
+ expect(preparedJournal(dir, origin).read()).toEqual({})
+ preparedJournal(dir, origin).update('next', { id: 'id-b' })
+ expect(preparedJournal(dir, origin).read()).toEqual({ next: { id: 'id-b' } })
+ const aside = fs.readdirSync(dir).filter(name => name.includes('.corrupt-'))
+ expect(aside.map(name => fs.readFileSync(path.join(dir, name), 'utf8'))).toEqual(['{"kept":{"id":"id-'])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/prepared-submissions.ts b/apps/desktop/electron/prepared-submissions.ts
index aeb5af19473..cf4ab92d8f7 100644
--- a/apps/desktop/electron/prepared-submissions.ts
+++ b/apps/desktop/electron/prepared-submissions.ts
@@ -12,12 +12,29 @@ export function preparedJournal(userData: string, origin: string) {
const file = path.join(userData, `prepared-submissions-${createHash('sha256').update(origin).digest('hex')}.json`)
const read = (): Record<string, unknown> => {
+ let raw: string
+
try {
- return JSON.parse(fs.readFileSync(file, 'utf8'))
+ raw = fs.readFileSync(file, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {return {}}
throw error
}
+
+ try {
+ const parsed: unknown = JSON.parse(raw)
+
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {return parsed as Record<string, unknown>}
+ } catch { /* quarantined below */ }
+
+ // A torn/garbled journal (crash mid-write on a filesystem without atomic rename, disk
+ // corruption) is unrecoverable as JSON. Throwing here blocked every later send of the origin,
+ // since each send must journal first. Move it aside with its bytes intact for diagnosis; its
+ // uncertain entries are lost to automatic retry, which only ever was an explicit user action.
+ fs.renameSync(file, `${file}.corrupt-${Date.now()}`)
+ console.warn(`[prepared-submissions] quarantined unreadable journal ${path.basename(file)}`)
+
+ return {}
}
return {