Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(desktop): publish message deletions after Host acknowledgment
Seraph-x7ce7a1fe47ee
diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.tsindex af0eb3541..1a320c729 100644--- a/apps/desktop/src/stores/slices/transcript-slice.ts+++ b/apps/desktop/src/stores/slices/transcript-slice.ts@@ -396,55 +396,40 @@ export function createTranscriptSlice({}: {},);- 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)];+ if (!get().messages.some((message) => message.id === messageId)) return;const fullWindow = { messageStart: 0, hasMoreBefore: false };- runtime.cacheSessionTranscript(sessionId, next, fullWindow);- set((current) => ({- messages: next,- sessionHistory: { ...current.sessionHistory, [sessionId]: fullWindow },- error: null,- errorCode: null,- }));+ runtime.cacheSessionTranscript(sessionId, get().messages, fullWindow);+ set({ error: null, errorCode: null });try {const result = await api.deleteSessionMessage({ sessionId, messageId });- if (result.deleted) return;+ if (!result.deleted) return;+ // Keep the projection intact until Host confirms the mutation. Late+ // terminal events can replace provisional IDs while this RPC waits;+ // restoring an earlier snapshot would resurrect those replaced rows.+ const current = get();+ const live = current.activeSessionId === sessionId+ ? current.messages+ : runtime.sessionTranscriptCache.get(sessionId) ?? current.retainedTranscripts[sessionId] ?? [];+ const index = live.findIndex((message) => message.id === messageId);+ if (index < 0) return;+ let end = index + 1;+ if (live[index].role === "user") {+ while (end < live.length && live[end].role !== "user") end += 1;+ }+ const next = [...live.slice(0, index), ...live.slice(end)];+ runtime.cacheSessionTranscript(sessionId, next, fullWindow);+ set((state) => ({+ messages: state.activeSessionId === sessionId ? next : state.messages,+ retainedTranscripts: state.retainedTranscripts[sessionId]+ ? { ...state.retainedTranscripts, [sessionId]: next }+ : state.retainedTranscripts,+ }));} catch (error) {set({error: error instanceof Error ? error.message : String(error),errorCode: (error as { code?: string })?.code ?? null,});}- // A missing durable target is a Host no-op, so undo the optimistic- // removal just as on failure. Keep callbacks received during the RPC,- // including completed updates, rather than restoring their old values.- const current = get();- const live = current.activeSessionId === sessionId- ? current.messages- : runtime.sessionTranscriptCache.get(sessionId) ?? [];- const liveById = new Map(live.map((message) => [message.id, message]));- const rollback = mergeLiveSessionMessages(- previous.map((message) => liveById.get(message.id) ?? message),- live,- );- runtime.cacheSessionTranscript(sessionId, rollback, fullWindow);- set((current) => ({- messages:- current.activeSessionId === sessionId ? rollback : current.messages,- }));} finally {releaseDelete();if (pendingMessageDeletes.get(sessionId) === completion) {diff --git a/apps/desktop/test/bounded-history-mutations.test.mjs b/apps/desktop/test/bounded-history-mutations.test.mjsindex be2869023..54af13852 100644--- a/apps/desktop/test/bounded-history-mutations.test.mjs+++ b/apps/desktop/test/bounded-history-mutations.test.mjs@@ -24,7 +24,7 @@ function load(relative, imports, globals = {}) {const row = (id, role) => ({ id, role, content: id, status: "complete" });const previous = [row("u1", "user"), row("t1", "tool"), row("a1", "assistant"), row("u2", "user"), row("a2", "assistant")];function harness(overrides = {}) {- let state = { activeSessionId: "s", isRunning: false, messages: [...previous], sessions: [{ id: "s", source: "desktop" }], sessionHistory: {}, pendingPermissions: {}, runningSessions: {}, ...overrides.state };+ let state = { activeSessionId: "s", isRunning: false, messages: [...previous], sessions: [{ id: "s", source: "desktop" }], sessionHistory: {}, retainedTranscripts: {}, pendingPermissions: {}, runningSessions: {}, ...overrides.state };const calls = [];const api = {deleteSessionMessage: async (input) => { calls.push(["delete", input]); return { ok: true, deleted: true, deletedCount: 3 }; },@@ -295,7 +295,7 @@ test("a queued delete cannot switch to a different active session and releases iassert.deepEqual(h.state().messages, []);});-test("a missing durable delete target restores the optimistic user-turn projection and cache", async () => {+test("a missing durable delete target preserves its user-turn projection and cache", async () => {const durable = previous.filter((message) => message.id !== "u1");const cached = new Map();const h = harness({ runtime: {@@ -311,7 +311,7 @@ test("a missing durable delete target restores the optimistic user-turn projectifor (const outcome of ["no-op", "failure"]) {for (const switchSession of [false, true]) {- test(`${outcome} delete restores its own projection while preserving a new turn, late terminal update, and ${switchSession ? "session switch" : "active session"}`, async () => {+ test(`${outcome} delete preserves its own projection with a new turn, late terminal update, and ${switchSession ? "session switch" : "active session"}`, async () => {const started = deferred();const response = deferred();const cached = new Map();@@ -330,14 +330,16 @@ for (const outcome of ["no-op", "failure"]) {const deleting = h.actions.deleteMessage("u1");await started.promise;const completed = { ...row("a2", "assistant"), content: "late completed reply" };- const live = [row("u2", "user"), completed, row("u3", "user"), { ...row("a3", "assistant"), status: "streaming" }];+ const live = [...h.state().messages.map((message) => message.id === "a2" ? completed : message),+ row("u3", "user"), { ...row("a3", "assistant"), status: "streaming" }];const other = [row("other", "user")];cached.set("s", live);h.update({ activeSessionId: switchSession ? "other" : "s", messages: switchSession ? other : live,isRunning: true, runningSessions: { s: true, ...(switchSession ? { other: true } : {}) } });response.resolve();await deleting;- const restored = [...previous.slice(0, 3), ...live];+ const restored = [...previous.slice(0, 3), row("u2", "user"), completed,+ row("u3", "user"), { ...row("a3", "assistant"), status: "streaming" }];assert.deepEqual(cached.get("s"), restored);assert.deepEqual(h.state().messages, switchSession ? other : restored);assert.equal(h.state().isRunning, true);@@ -346,3 +348,77 @@ for (const outcome of ["no-op", "failure"]) {});}}++for (const outcome of ["no-op", "failure"]) {+ for (const switchSession of [false, true]) {+ test(`${outcome} delete preserves a native terminal re-key across ${switchSession ? "session switch" : "active session"}`, async () => {+ const started = deferred();+ const response = deferred();+ const provisional = { ...row("provisional", "assistant"), content: "partial", status: "streaming" };+ const initial = [...previous, provisional];+ const cached = new Map();+ const h = harness({ state: { messages: initial }, runtime: {+ loadFullSessionMessages: async () => initial,+ sessionTranscriptCache: cached,+ cacheSessionTranscript: (id, messages) => cached.set(id, messages),+ }, api: { deleteSessionMessage: async () => {+ started.resolve();+ await response.promise;+ if (outcome === "failure") throw new Error("delete failed");+ return { ok: true, deleted: false, deletedCount: 0 };+ } } });+ const deleting = h.actions.deleteMessage("provisional");+ await started.promise;+ const completed = { ...row("durable-sdk", "assistant"), content: "canonical completion" };+ const event = { type: "message_end", replacesMessageId: "provisional", message: completed };+ const live = [...transcript.projectMessageEnd(h.state().messages, event), row("u3", "user")];+ cached.set("s", live);+ const other = [row("other", "user")];+ h.update({ activeSessionId: switchSession ? "other" : "s", messages: switchSession ? other : live });+ response.resolve();+ await deleting;+ const expected = [...previous, completed, row("u3", "user")];+ assert.deepEqual(cached.get("s"), expected);+ assert.deepEqual(h.state().messages, switchSession ? other : expected);+ assert.equal(h.state().error, outcome === "failure" ? "delete failed" : null);+ });+ }+}++for (const { switchSession, evictCache } of [+ { switchSession: false, evictCache: false },+ { switchSession: true, evictCache: false },+ { switchSession: true, evictCache: true },+]) {+ test(`acknowledged user-turn delete preserves a newer native completion after ${switchSession ? "session switch" : "active session"}${evictCache ? " with evicted cache" : ""}`, async () => {+ const started = deferred();+ const response = deferred();+ const initial = [...previous, { ...row("provisional", "assistant"), status: "streaming" }];+ const cached = new Map();+ const h = harness({ state: { messages: initial, retainedTranscripts: { s: initial, other: [row("other", "user")] } }, runtime: {+ loadFullSessionMessages: async () => initial,+ sessionTranscriptCache: cached,+ cacheSessionTranscript: (id, messages) => cached.set(id, messages),+ }, api: { deleteSessionMessage: async () => {+ started.resolve(); await response.promise;+ return { ok: true, deleted: true, deletedCount: 3 };+ } } });+ const deleting = h.actions.deleteMessage("u2");+ await started.promise;+ assert.deepEqual(h.state().messages, initial, "visible history changes only after Host acknowledgment");+ const completed = row("durable-sdk", "assistant");+ const live = [...transcript.projectMessageEnd(h.state().messages, {+ type: "message_end", replacesMessageId: "provisional", message: completed,+ }), row("u3", "user"), row("a3", "assistant")];+ const other = [row("other", "user")];+ cached.set("s", live);+ h.update({ activeSessionId: switchSession ? "other" : "s", messages: switchSession ? other : live, retainedTranscripts: { s: live, other } });+ if (evictCache) cached.delete("s");+ response.resolve(); await deleting;+ const expected = [...previous.slice(0, 3), row("u3", "user"), row("a3", "assistant")];+ assert.deepEqual(cached.get("s"), expected);+ assert.deepEqual(h.state().retainedTranscripts.s, expected, "retained panes must publish the same acknowledged deletion");+ assert.deepEqual(h.state().retainedTranscripts.other, other);+ assert.deepEqual(h.state().messages, switchSession ? other : expected);+ });+}