Skip to content

Commit 94e4b01

Browse files
committed
🤖 fix: use atomic writes for partial.json to prevent corruption
Non-atomic fs.writeFile can leave truncated/malformed JSON if the app crashes mid-write. This causes 'Unexpected end of JSON input' errors when reading partial.json on the next stream start, leading to amnesia (messages being lost). Use write-file-atomic which writes to a temp file then renames, ensuring readers always see either the old complete file or the new complete file, never a partial write. Fixes #803
1 parent 284dbc7 commit 94e4b01

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/node/services/partialService.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as fs from "fs/promises";
22
import * as path from "path";
3+
import writeFileAtomic from "write-file-atomic";
34
import type { Result } from "@/common/types/result";
45
import { Ok, Err } from "@/common/types/result";
56
import type { MuxMessage } from "@/common/types/message";
@@ -80,7 +81,9 @@ export class PartialService {
8081
},
8182
};
8283

83-
await fs.writeFile(partialPath, JSON.stringify(partialMessage, null, 2));
84+
// Atomic write: writes to temp file then renames, preventing corruption
85+
// if app crashes mid-write (prevents "Unexpected end of JSON input" on read)
86+
await writeFileAtomic(partialPath, JSON.stringify(partialMessage, null, 2));
8487
return Ok(undefined);
8588
} catch (error) {
8689
const message = error instanceof Error ? error.message : String(error);

0 commit comments

Comments
 (0)