Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(desktop): serialize consecutive session message deletes

Seraph-x0fbb0ce129d1
diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.ts
index e732a6641..b6791acc3 100644
--- a/apps/desktop/src/stores/slices/transcript-slice.ts
+++ b/apps/desktop/src/stores/slices/transcript-slice.ts
@@ -53,6 +53,9 @@ export function createTranscriptSlice({
| "rollbackWorkspaceChange"
| "abort"
> {
+ // Keep each delete's read/optimistic update/Host result together. Main's
+ // mutation lock alone cannot prevent a second renderer read of old history.
+ const pendingMessageDeletes = new Map<string, Promise<void>>();
const canEdit = () => {
const state = get();
return sessionAllows(state.sessions.find((session) => session.id === state.activeSessionId)
@@ -360,72 +363,85 @@ export function createTranscriptSlice({
if (!canEdit()) return;
const sessionId = get().activeSessionId;
if (!sessionId || get().isRunning) return;
- const fullMessages = await runtime.loadFullSessionMessages(sessionId);
- // Re-read the store after the reload: writes that landed during the
- // await (an aborted turn's final message_end, a late tool_end) exist
- // only here, so merging the pre-await snapshot would erase them
- // (#1614) — the same post-await read abort() below relies on. A turn
- // that started during the reload also bails: no rewrite under a live
- // stream.
- if (
- !fullMessages ||
- get().activeSessionId !== sessionId ||
- get().isRunning
- ) {
- return;
- }
- const merged = mergeLiveSessionMessages(fullMessages, get().messages);
- set((current) =>
- current.activeSessionId === sessionId
- ? {
- messages: merged,
- sessionHistory: {
- ...current.sessionHistory,
- [sessionId]: { messageStart: 0, hasMoreBefore: false },
- },
- }
- : {},
- );
- const state = get();
- const index = state.messages.findIndex((message) => message.id === messageId);
- if (index < 0) return;
- const target = state.messages[index];
- let end = index + 1;
- if (target.role === "user") {
- while (
- end < state.messages.length &&
- state.messages[end].role !== "user"
+ const previousDelete = pendingMessageDeletes.get(sessionId);
+ let releaseDelete!: () => void;
+ const completion = new Promise<void>((resolve) => { releaseDelete = resolve; });
+ pendingMessageDeletes.set(sessionId, completion);
+ try {
+ await previousDelete;
+ if (get().activeSessionId !== sessionId || get().isRunning || !canEdit()) return;
+ const fullMessages = await runtime.loadFullSessionMessages(sessionId);
+ // Re-read the store after the reload: writes that landed during the
+ // await (an aborted turn's final message_end, a late tool_end) exist
+ // only here, so merging the pre-await snapshot would erase them
+ // (#1614) — the same post-await read abort() below relies on. A turn
+ // that started during the reload also bails: no rewrite under a live
+ // stream.
+ if (
+ !fullMessages ||
+ get().activeSessionId !== sessionId ||
+ get().isRunning
) {
- end += 1;
+ return;
}
- }
- const previous = state.messages;
- const next = [...previous.slice(0, index), ...previous.slice(end)];
- const fullWindow = { messageStart: 0, hasMoreBefore: false };
- runtime.cacheSessionTranscript(sessionId, next, fullWindow);
- set((current) => ({
- messages: next,
- sessionHistory: { ...current.sessionHistory, [sessionId]: fullWindow },
- error: null,
- errorCode: null,
- }));
- try {
- await api.deleteSessionMessage({ sessionId, messageId });
- } catch (error) {
- const current = get();
- const rollback = mergeLiveSessionMessages(
- previous,
+ const merged = mergeLiveSessionMessages(fullMessages, get().messages);
+ set((current) =>
current.activeSessionId === sessionId
- ? current.messages
- : runtime.sessionTranscriptCache.get(sessionId) ?? [],
+ ? {
+ messages: merged,
+ sessionHistory: {
+ ...current.sessionHistory,
+ [sessionId]: { messageStart: 0, hasMoreBefore: false },
+ },
+ }
+ : {},
);
- runtime.cacheSessionTranscript(sessionId, rollback, fullWindow);
+ const state = get();
+ const index = state.messages.findIndex((message) => message.id === messageId);
+ if (index < 0) return;
+ const target = state.messages[index];
+ let end = index + 1;
+ if (target.role === "user") {
+ while (
+ end < state.messages.length &&
+ state.messages[end].role !== "user"
+ ) {
+ end += 1;
+ }
+ }
+ const previous = state.messages;
+ const next = [...previous.slice(0, index), ...previous.slice(end)];
+ const fullWindow = { messageStart: 0, hasMoreBefore: false };
+ runtime.cacheSessionTranscript(sessionId, next, fullWindow);
set((current) => ({
- messages:
- current.activeSessionId === sessionId ? rollback : current.messages,
- error: error instanceof Error ? error.message : String(error),
- errorCode: (error as { code?: string })?.code ?? null,
+ messages: next,
+ sessionHistory: { ...current.sessionHistory, [sessionId]: fullWindow },
+ error: null,
+ errorCode: null,
}));
+ try {
+ await api.deleteSessionMessage({ sessionId, messageId });
+ } catch (error) {
+ const current = get();
+ const rollback = mergeLiveSessionMessages(
+ previous,
+ current.activeSessionId === sessionId
+ ? current.messages
+ : runtime.sessionTranscriptCache.get(sessionId) ?? [],
+ );
+ runtime.cacheSessionTranscript(sessionId, rollback, fullWindow);
+ set((current) => ({
+ messages:
+ current.activeSessionId === sessionId ? rollback : current.messages,
+ error: error instanceof Error ? error.message : String(error),
+ errorCode: (error as { code?: string })?.code ?? null,
+ }));
+ }
+ } finally {
+ releaseDelete();
+ if (pendingMessageDeletes.get(sessionId) === completion) {
+ pendingMessageDeletes.delete(sessionId);
+ }
}
},
diff --git a/apps/desktop/test/bounded-history-mutations.test.mjs b/apps/desktop/test/bounded-history-mutations.test.mjs
index a888a6683..62c47544b 100644
--- a/apps/desktop/test/bounded-history-mutations.test.mjs
+++ b/apps/desktop/test/bounded-history-mutations.test.mjs
@@ -222,3 +222,75 @@ test("a completed smart stop updates its own cache and restores its session draf
assert.equal(h.state().composerPrefill?.sessionId, "s");
assert.equal(h.state().composerPrefill?.text, "second");
});
+
+function deferred() {
+ let resolve;
+ const promise = new Promise((res) => { resolve = res; });
+ return { promise, resolve };
+}
+
+for (const firstFails of [false, true]) {
+ test(`consecutive deletes serialize their reads and release the session queue after ${firstFails ? "failure" : "success"}`, async () => {
+ const firstStarted = deferred();
+ const firstResponse = deferred();
+ let durable = [...previous];
+ let loads = 0;
+ const calls = [];
+ let h;
+ h = harness({ runtime: { loadFullSessionMessages: async () => { loads++; return [...durable]; } }, api: {
+ deleteSessionMessage: async (input) => {
+ calls.push(input);
+ if (input.messageId === "u1") {
+ firstStarted.resolve();
+ await firstResponse.promise;
+ if (firstFails) throw new Error("first delete failed");
+ durable = durable.filter((message) => ["u2", "a2", "u3", "late"].includes(message.id));
+ } else {
+ durable = durable.filter((message) => !["u2", "a2"].includes(message.id));
+ }
+ return { ok: true, deleted: true };
+ },
+ } });
+ const first = h.actions.deleteMessage("u1");
+ await firstStarted.promise;
+ const second = h.actions.deleteMessage("u2");
+ // A callback from the surviving turn arrives while the first request waits.
+ const late = [row("u3", "user"), row("late", "assistant")];
+ durable = [...durable, ...late];
+ h.update({ messages: [...h.state().messages, ...late] });
+ assert.equal(loads, 1, "the second delete cannot reload pre-mutation durable history");
+ firstResponse.resolve();
+ await Promise.all([first, second]);
+ assert.deepEqual(calls, [{ sessionId: "s", messageId: "u1" }, { sessionId: "s", messageId: "u2" }]);
+ assert.deepEqual(h.state().messages.map((message) => message.id), firstFails ? ["u1", "t1", "a1", "u3", "late"] : ["u3", "late"]);
+ assert.deepEqual(h.state().messages, durable);
+ });
+}
+
+test("a queued delete cannot switch to a different active session and releases its queue", async () => {
+ const firstStarted = deferred();
+ const firstResponse = deferred();
+ let durable = [...previous];
+ const calls = [];
+ let h;
+ h = harness({ runtime: { loadFullSessionMessages: async () => [...durable] }, api: {
+ deleteSessionMessage: async (input) => {
+ calls.push(input);
+ if (input.messageId === "u1") { firstStarted.resolve(); await firstResponse.promise; }
+ durable = durable.filter((message) => input.messageId === "u1" ? ["u2", "a2"].includes(message.id) : !["u2", "a2"].includes(message.id));
+ return { ok: true, deleted: true };
+ },
+ } });
+ const first = h.actions.deleteMessage("u1");
+ await firstStarted.promise;
+ const queued = h.actions.deleteMessage("u2");
+ h.update({ activeSessionId: "other", messages: [row("other", "user")] });
+ firstResponse.resolve();
+ await Promise.all([first, queued]);
+ assert.deepEqual(calls, [{ sessionId: "s", messageId: "u1" }]);
+ assert.equal(h.state().messages[0].id, "other");
+ h.update({ activeSessionId: "s", messages: [...durable] });
+ await h.actions.deleteMessage("u2");
+ assert.deepEqual(calls.at(-1), { sessionId: "s", messageId: "u2" });
+ assert.deepEqual(h.state().messages, []);
+});