Skip to content

Commit 323a663

Browse files
authored
fix(persistent): serialize concurrent saveState calls to prevent data loss (#24)
1 parent 8900995 commit 323a663

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ dist/
55
data/
66
.agent-inbox/
77
.worktrees/
8+
.DS_Store

packages/core/src/persist.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,8 @@ function mergeScopedObjectRecord<T extends object>(
276276
return merged;
277277
}
278278

279+
let writeQueue: Promise<void> = Promise.resolve();
280+
279281
async function readExistingPersistedState(): Promise<Partial<PersistedState>> {
280282
try {
281283
const raw = await readFile(config.stateFile, 'utf-8');
@@ -350,6 +352,26 @@ export async function saveState(
350352
threadContinuationSnapshots: Map<string, ThreadContinuationSnapshot>,
351353
savedCwdList: string[],
352354
options: StateScopeOptions = {},
355+
): Promise<void> {
356+
const task = writeQueue.then(() => doSaveState(
357+
sessions, models, effort, cwd, backend,
358+
threadSessionBindings, threadContinuationSnapshots,
359+
savedCwdList, options,
360+
));
361+
writeQueue = task.catch(() => {});
362+
return task;
363+
}
364+
365+
async function doSaveState(
366+
sessions: Map<string, string>,
367+
models: Map<string, string>,
368+
effort: Map<string, string>,
369+
cwd: Map<string, string>,
370+
backend: Map<string, string>,
371+
threadSessionBindings: Map<string, ThreadSessionBinding>,
372+
threadContinuationSnapshots: Map<string, ThreadContinuationSnapshot>,
373+
savedCwdList: string[],
374+
options: StateScopeOptions = {},
353375
): Promise<void> {
354376
try {
355377
const existing = options.platform ? await readExistingPersistedState() : {};

0 commit comments

Comments
 (0)