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): bound existing history mutations by message IDs
Seraph-x1dc4c0639c18
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.tsindex 31cc924cd..b92bc4c2f 100644--- a/apps/desktop/electron/main/ipc/session-ipc.ts+++ b/apps/desktop/electron/main/ipc/session-ipc.ts@@ -135,9 +135,9 @@ export function registerSessionIpc({};/**- * The one gate for the two transcript-rewrite entrances — replacement and- * revision activation rewrite the same host-side transcript rows, so both- * go through this boundary instead of each entrance remembering its own+ * The shared gate for transcript-rewrite entrances — replacement, bounded+ * mutations and revision activation all rewrite the host-side transcript.+ * Each entrance uses this boundary rather than remembering its own* (#1612, #1613): refuse while a turn is running (consistent with fork and* move), serialize overlapping operations per session, and drain the* persistence outbox so writes queued before the rewrite land in the old@@ -153,6 +153,7 @@ export function registerSessionIpc({purpose: string,currentHost: HostProcess,run: () => Promise<T>,+ options: { strictDrain?: boolean; didRewrite?: (result: T) => boolean } = {},): Promise<T> => {rejectNativeMutation(sessionId, purpose);const releaseSessionOperation = await acquireSessionOperation(sessionId);@@ -165,7 +166,11 @@ export function registerSessionIpc({);}rewriteFence = beginTranscriptRewrite(sessionId);- await persistenceOutbox.prepareSessionReplacement(sessionId, () => currentHost);+ if (options.strictDrain) {+ await persistenceOutbox.prepareSessionMutation(sessionId, () => currentHost);+ } else {+ await persistenceOutbox.prepareSessionReplacement(sessionId, () => currentHost);+ }if (sidecar) {sidecar.clearProjectInstructionRoot(sessionId);sidecar.clearVendorAuthBindings(sessionId);@@ -174,7 +179,8 @@ export function registerSessionIpc({.catch(() => undefined);}const result = await run();- rewriteFence.commit();+ if (options.didRewrite?.(result) === false) rewriteFence.rollback();+ else rewriteFence.commit();return result;} catch (error) {rewriteFence?.rollback();@@ -514,6 +520,45 @@ export function registerSessionIpc({);},);+ handle(+ IPC.invoke.sessionDeleteMessage,+ async (input: { sessionId: string; messageId: string }) => {+ if (!host) throw new Error("host unavailable");+ const sessionId = String(input?.sessionId || "");+ if (!sessionId) throw new Error("sessionId required");+ const currentHost = host;+ return runTranscriptRewrite(+ sessionId,+ "message deletion",+ currentHost,+ () => currentHost.call<{ deleted: boolean }>("session.deleteMessage", {+ sessionId,+ messageId: String(input?.messageId || ""),+ }),+ { strictDrain: true, didRewrite: (result) => result.deleted },+ );+ },+ );+ handle(+ IPC.invoke.sessionRetractPendingPrompt,+ async (input: { sessionId: string; userMessageId: string; turnId?: string }) => {+ if (!host) throw new Error("host unavailable");+ const sessionId = String(input?.sessionId || "");+ if (!sessionId) throw new Error("sessionId required");+ const currentHost = host;+ return runTranscriptRewrite(+ sessionId,+ "pending prompt retraction",+ currentHost,+ () => currentHost.call<{ retracted: boolean }>("session.retractPendingPrompt", {+ sessionId,+ userMessageId: String(input?.userMessageId || ""),+ ...(input?.turnId === undefined ? {} : { turnId: input.turnId }),+ }),+ { strictDrain: true, didRewrite: (result) => result.retracted },+ );+ },+ );handle(IPC.invoke.sessionSaveRevision,async (input: {@@ -550,6 +595,7 @@ export function registerSessionIpc({rootUserId: string;revisionIndex: number;prefix?: unknown[];+ requireCanonicalPrefix?: boolean;}) => {if (!host) throw new Error("host unavailable");const sessionId = String(input?.sessionId || "");@@ -564,8 +610,11 @@ export function registerSessionIpc({sessionId,rootUserId: String(input?.rootUserId || ""),revisionIndex: Number(input?.revisionIndex || 0),- prefix: input?.prefix ?? [],+ ...(input?.requireCanonicalPrefix === true+ ? { requireCanonicalPrefix: true }+ : { prefix: input?.prefix ?? [] }),}),+ { strictDrain: input?.requireCanonicalPrefix === true },);},);diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 5465a95ab..6e75b1880 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1108,6 +1108,16 @@ export const api = {),replaceSessionMessages: (sessionId: string, messages: UiMessage[]) =>invoke(IPC.invoke.sessionReplaceMessages, { sessionId, messages }),+ deleteSessionMessage: (input: { sessionId: string; messageId: string }) =>+ invoke<{ ok: true; deleted: boolean; deletedCount: number }>(IPC.invoke.sessionDeleteMessage, input),+ retractPendingSessionPrompt: (input: {+ sessionId: string;+ userMessageId: string;+ turnId?: string;+ }) =>+ invoke<{ ok: true; retracted: boolean; removedCount: number; reason?: string }>(+ IPC.invoke.sessionRetractPendingPrompt, input,+ ),saveSessionRevision: (input: {sessionId: string;rootUserId: string;@@ -1124,7 +1134,8 @@ export const api = {sessionId: string;rootUserId: string;revisionIndex: number;- prefix: UiMessage[];+ prefix?: UiMessage[];+ requireCanonicalPrefix?: boolean;}) =>invoke<{ messages: UiMessage[] }>(IPC.invoke.sessionActivateRevision, input),steer: (req: AgentSteerRequest) =>diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.tsindex 9b6b28318..e732a6641 100644--- a/apps/desktop/src/stores/slices/transcript-slice.ts+++ b/apps/desktop/src/stores/slices/transcript-slice.ts@@ -310,7 +310,7 @@ export function createTranscriptSlice({const fullMessages = await runtime.loadFullSessionMessages(sessionId);if (!fullMessages || get().activeSessionId !== sessionId) return;set((current) =>- current.activeSessionId === sessionId+ current.activeSessionId === sessionId && !current.isRunning? {messages: fullMessages,sessionHistory: {@@ -326,21 +326,20 @@ export function createTranscriptSlice({if (rootIndex < 0) return;const root = state.messages[rootIndex];const revisionFamilyId = root.revisionRootId || root.id;- const prefix = state.messages.slice(0, rootIndex);try {const result = await api.activateSessionRevision({sessionId,rootUserId: revisionFamilyId,revisionIndex,- prefix,+ requireCanonicalPrefix: true,});set((current) => ({messages:- current.activeSessionId === sessionId- ? result.messages ?? prefix+ current.activeSessionId === sessionId && !current.isRunning+ ? result.messages: current.messages,sessionHistory:- current.activeSessionId === sessionId+ current.activeSessionId === sessionId && !current.isRunning? {...current.sessionHistory,[sessionId]: { messageStart: 0, hasMoreBefore: false },@@ -411,12 +410,19 @@ export function createTranscriptSlice({errorCode: null,}));try {- await api.replaceSessionMessages(sessionId, next);+ await api.deleteSessionMessage({ sessionId, messageId });} catch (error) {- runtime.cacheSessionTranscript(sessionId, previous, fullWindow);+ 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 ? previous : current.messages,+ current.activeSessionId === sessionId ? rollback : current.messages,error: error instanceof Error ? error.message : String(error),errorCode: (error as { code?: string })?.code ?? null,}));@@ -485,6 +491,9 @@ export function createTranscriptSlice({return;}const submittedDraft = runtime.submittedComposerDrafts.get(sessionId);+ const pendingUserMessageId = stateBeforeAbort.messages+ .slice(submittedDraft?.messageCountBeforeSend ?? 0)+ .findLast((message) => message.role === "user")?.id;const preserveSteering = stateBeforeAbort.messages.slice(submittedDraft?.messageCountBeforeSend ?? 0).findLast((message) => message.role === "user")?.steering;@@ -525,41 +534,77 @@ export function createTranscriptSlice({const smartStop = preserveSteering? { kind: "settle" as const }: resolveComposerSmartStop(state.messages, submittedDraft);+ let retainSubmittedDraft = false;if (smartStop.kind === "restore") {const fullMessages = await runtime.loadFullSessionMessages(sessionId);if (!fullMessages || get().activeSessionId !== sessionId) {submittedDraft?.resolveAbort?.(false);- runtime.submittedComposerDrafts.delete(sessionId);return;}const merged = mergeLiveSessionMessages(fullMessages, get().messages);const fullStop = resolveComposerSmartStop(merged, submittedDraft);if (fullStop.kind === "restore") {- runtime.submittedComposerDrafts.delete(sessionId);- submittedDraft?.resolveAbort?.(true);- const fullWindow = { messageStart: 0, hasMoreBefore: false };- runtime.cacheSessionTranscript(sessionId, fullStop.kept, fullWindow);- set((current) => ({- messages: fullStop.kept,- sessionHistory: { ...current.sessionHistory, [sessionId]: fullWindow },- composerPrefill: { ...fullStop.draft, sessionId },- isRunning: false,- runningSessions: { ...current.runningSessions, [sessionId]: false },- }));- if (fullStop.kept.length < merged.length) {- try {- await api.replaceSessionMessages(sessionId, fullStop.kept);- } catch {- // Best effort — the local transcript already reflects the undo.+ const pendingUser = merged[fullStop.kept.length];+ try {+ if (!pendingUserMessageId || pendingUser?.id !== pendingUserMessageId) {+ throw new Error(i18n.t("chat.promptRetractionFailed"));+ }+ const result = await api.retractPendingSessionPrompt({+ sessionId,+ userMessageId: pendingUserMessageId,+ });+ if (!result.retracted) {+ throw new Error(i18n.t("chat.promptRetractionFailed"));+ }+ submittedDraft?.resolveAbort?.(true);+ if (runtime.submittedComposerDrafts.get(sessionId) === submittedDraft) {+ runtime.submittedComposerDrafts.delete(sessionId);+ }+ // A subsequent prompt can start after the host releases its mutation+ // lock. Never replace that prompt or its composer with this draft.+ const current = get();+ const latestMessages = current.activeSessionId === sessionId+ ? current.messages+ : runtime.sessionTranscriptCache.get(sessionId) ?? merged;+ const latestUser = latestMessages.findLast((message) => message.role === "user");+ if (latestUser?.id === pendingUserMessageId) {+ const fullWindow = { messageStart: 0, hasMoreBefore: false };+ runtime.cacheSessionTranscript(sessionId, fullStop.kept, fullWindow);+ set((current) => ({+ messages: current.activeSessionId === sessionId ? fullStop.kept : current.messages,+ sessionHistory: { ...current.sessionHistory, [sessionId]: fullWindow },+ composerPrefill: { ...fullStop.draft, sessionId },+ isRunning: current.activeSessionId === sessionId ? false : current.isRunning,+ runningSessions: { ...current.runningSessions, [sessionId]: false },+ }));+ }+ void flushPendingSessionConfiguration(sessionId);+ return;+ } catch (error) {+ retainSubmittedDraft = true;+ // agent_end may have removed the old submission while abort waited.+ // Preserve it for recovery without replacing a newer submission.+ if (submittedDraft && !runtime.submittedComposerDrafts.has(sessionId)) {+ runtime.submittedComposerDrafts.set(sessionId, submittedDraft);+ }+ set({+ error: error instanceof Error ? error.message : String(error),+ errorCode: (error as { code?: string })?.code ?? null,+ });+ const current = get();+ if (+ current.activeSessionId !== sessionId ||+ current.messages.findLast((message) => message.role === "user")?.id !== pendingUserMessageId+ ) {+ submittedDraft?.resolveAbort?.(false);+ return;}}- void flushPendingSessionConfiguration(sessionId);- return;}set((current) =>current.activeSessionId === sessionId? {- messages: merged,+ messages: mergeLiveSessionMessages(merged, current.messages),sessionHistory: {...current.sessionHistory,[sessionId]: { messageStart: 0, hasMoreBefore: false },@@ -569,7 +614,9 @@ export function createTranscriptSlice({);}submittedDraft?.resolveAbort?.(false);- runtime.submittedComposerDrafts.delete(sessionId);+ if (!retainSubmittedDraft && runtime.submittedComposerDrafts.get(sessionId) === submittedDraft) {+ runtime.submittedComposerDrafts.delete(sessionId);+ }const stoppedRows = (rows: UiMessage[]) =>rows.map((message) => {if (message.role === "assistant" && message.status === "streaming") {diff --git a/apps/desktop/test/bounded-history-mutations.test.mjs b/apps/desktop/test/bounded-history-mutations.test.mjsnew file mode 100644index 000000000..f24cc0dc0--- /dev/null+++ b/apps/desktop/test/bounded-history-mutations.test.mjs@@ -0,0 +1,214 @@+import assert from "node:assert/strict";+import * as fs from "node:fs";+import * as path from "node:path";+import test from "node:test";+import ts from "typescript";+import { register } from "node:module";+import { ErrorCodes } from "../../../packages/shared/src/errors.ts";+import { IPC, IPC_WHITELIST } from "../../../packages/shared/src/protocol.ts";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const transcript = await import("../src/lib/session-transcript.ts");+const safety = await import("../src/lib/remote-session-safety.ts");+const permissions = await import("../src/lib/pending-permissions.ts");+const smartStop = await import("../src/lib/composer-smart-stop.ts");+function load(relative, imports, globals = {}) {+ const source = fs.readFileSync(new URL(relative, import.meta.url), "utf8");+ const { outputText } = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } });+ const module = { exports: {} };+ new Function("require", "exports", "module", ...Object.keys(globals), outputText)((id) => {+ assert.ok(Object.hasOwn(imports, id), `unexpected dependency: ${id}`);+ return imports[id];+ }, module.exports, module, ...Object.values(globals));+ return module.exports;+}+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 };+ const calls = [];+ const api = {+ deleteSessionMessage: async (input) => { calls.push(["delete", input]); return { ok: true, deleted: true, deletedCount: 3 }; },+ activateSessionRevision: async (input) => { calls.push(["activate", input]); return { messages: previous }; },+ retractPendingSessionPrompt: async (input) => { calls.push(["retract", input]); return { ok: true, retracted: true, removedCount: 1 }; },+ abort: async () => {}, ...overrides.api,+ };+ const runtime = { loadFullSessionMessages: async () => previous, cacheSessionTranscript() {}, sessionTranscriptCache: new Map(), submittedComposerDrafts: new Map(), ...overrides.runtime };+ const { createTranscriptSlice } = load("../src/stores/slices/transcript-slice.ts", {+ i18next: { default: { t: (key) => key } }, "../../lib/api": { api },+ "../../lib/remote-session-safety": safety, "@pi-desktop/shared": {},+ "../../lib/composer-smart-stop": smartStop, "../../lib/pending-permissions": permissions,+ "../../lib/session-transcript": transcript, "../../lib/workspace-review": {},+ "../../lib/context-usage": { settleStoppedAssistantMetrics: (message) => message }, "../runtime/transcript-action": {},+ });+ const actions = createTranscriptSlice({ get: () => state, set: (update) => { state = { ...state, ...(typeof update === "function" ? update(state) : update) }; }, runtime, flushPendingSessionConfiguration: async () => {} });+ return { actions, calls, runtime, state: () => state, update: (next) => { state = { ...state, ...next }; } };+}+test("delete uses only the durable id and removes the entire user turn", async () => {+ const h = harness(); await h.actions.deleteMessage("u1");+ assert.deepEqual(h.calls, [["delete", { sessionId: "s", messageId: "u1" }]]);+ assert.deepEqual(h.state().messages.map((m) => m.id), ["u2", "a2"]);+});+test("failed delete rolls back and exposes the durable error", async () => {+ const h = harness({ api: { deleteSessionMessage: async () => { throw new Error("delete failed"); } } });+ await h.actions.deleteMessage("u1"); assert.deepEqual(h.state().messages, previous); assert.equal(h.state().error, "delete failed");+});+test("activation requests canonical prefix with no historical messages", async () => {+ const h = harness(); await h.actions.activateMessageRevision("u2", 1);+ assert.deepEqual(h.calls, [["activate", { sessionId: "s", rootUserId: "u2", revisionIndex: 1, requireCanonicalPrefix: true }]]);+});+for (const outcome of ["success", "exception", "reply_started"]) {+ test(`smart stop preserves durable state and drafts on ${outcome}`, async () => {+ const messages = previous.slice(0, 4);+ const submitted = { messageCountBeforeSend: 3, draft: { text: "second", fileReferences: [] } };+ const h = harness({ state: { messages, isRunning: true }, runtime: { loadFullSessionMessages: async () => messages, submittedComposerDrafts: new Map([["s", submitted]]) }, api: outcome === "success" ? {} : { retractPendingSessionPrompt: async () => { if (outcome === "exception") throw new Error("retract failed"); return { retracted: false, reason: outcome }; } } });+ await h.actions.abort();+ if (outcome === "success") {+ assert.deepEqual(h.calls, [["retract", { sessionId: "s", userMessageId: "u2" }]]);+ assert.equal(h.state().composerPrefill.text, "second"); assert.equal(await submitted.abortResolution, true);+ assert.deepEqual(h.state().messages.map((m) => m.id), ["u1", "t1", "a1"]);+ } else {+ assert.equal(h.state().messages.at(-1).id, "u2"); assert.equal(h.state().composerPrefill, undefined);+ assert.equal(h.runtime.submittedComposerDrafts.get("s"), submitted); assert.equal(await submitted.abortResolution, false); assert.ok(h.state().error);+ }+ });+}+const { registerSessionIpc } = load("../electron/main/ipc/session-ipc.ts", {+ electron: { shell: {} }, "node:fs": fs, "node:path": path, "@pi-desktop/shared": { ErrorCodes, IPC }, "../importers": {}, "../services/session-collaboration": {}, "../bootstrap/remote-hosts.js": {}, "../services/session-search": {},+});+function ipcHarness(pending = false, result = { ok: true }) {+ const handlers = new Map(); const events = [];+ const host = { call: async (method, input) => { events.push([method, input]); return typeof result === "function" ? result(method) : result; } };+ registerSessionIpc({ registrar: { handle: (channel, handler) => handlers.set(channel, handler) }, getHost: () => host,+ getSidecar: () => ({ clearProjectInstructionRoot() {}, clearVendorAuthBindings() {}, call: async () => { events.push(["dispose"]); } }), activeTurns: new Map(),+ persistenceOutbox: { prepareSessionMutation: async (id) => { events.push(["strict-drain", id]); if (pending) throw new Error("pending write"); }, prepareSessionReplacement: async () => { events.push(["replacement-drain"]); } },+ acquireSessionOperation: async () => { events.push(["lock"]); return () => events.push(["release"]); },+ beginTranscriptRewrite: () => { events.push(["fence"]); return { commit: () => events.push(["commit"]), rollback: () => events.push(["rollback"]) }; }, sessionProjects: new Map(), logger: {}, plugins: {},+ });+ return { events, invoke: (channel, input) => { assert.equal(typeof handlers.get(IPC.invoke[channel]), "function"); return handlers.get(IPC.invoke[channel])(input); } };+}+for (const [channel, method, input] of [+ ["sessionDeleteMessage", "session.deleteMessage", { sessionId: "s", messageId: "u1" }],+ ["sessionRetractPendingPrompt", "session.retractPendingPrompt", { sessionId: "s", userMessageId: "u2", turnId: "turn" }],+ ["sessionActivateRevision", "session.activateRevision", { sessionId: "s", rootUserId: "u1", revisionIndex: 2, requireCanonicalPrefix: true }],+]) {+ test(`${channel} strictly drains before host mutation under rewrite fence`, async () => {+ const h = ipcHarness(); assert.ok(IPC_WHITELIST.has(IPC.invoke[channel])); await h.invoke(channel, input);+ assert.deepEqual(h.events, [["lock"], ["fence"], ["strict-drain", "s"], ["dispose"], [method, input], ["commit"], ["release"]]);+ });+ test(`${channel} refuses mutation on strict drain failure`, async () => {+ const h = ipcHarness(true); await assert.rejects(h.invoke(channel, input), /pending write/);+ assert.deepEqual(h.events, [["lock"], ["fence"], ["strict-drain", "s"], ["rollback"], ["release"]]);+ });+}+test("legacy replace and explicit prefix activation retain old wire shapes", async () => {+ const h = ipcHarness(); await h.invoke("sessionReplaceMessages", { sessionId: "s", messages: previous });+ await h.invoke("sessionActivateRevision", { sessionId: "s", rootUserId: "u2", revisionIndex: 1, prefix: previous });+ assert.deepEqual(h.events.find(([kind]) => kind === "session.replaceMessages"), ["session.replaceMessages", { sessionId: "s", messages: previous }]);+ assert.deepEqual(h.events.find(([kind]) => kind === "session.activateRevision"), ["session.activateRevision", { sessionId: "s", rootUserId: "u2", revisionIndex: 1, prefix: previous }]);+});++test("failed optimistic delete preserves unrelated callbacks received while awaiting the host", async () => {+ let h;+ const late = row("a3", "assistant");+ h = harness({ api: { deleteSessionMessage: async () => { h.update({ messages: [...h.state().messages, late] }); throw new Error("delete failed"); } } });+ await h.actions.deleteMessage("u1");+ assert.deepEqual(h.state().messages.map((message) => message.id), [...previous.map((message) => message.id), "a3"]);+});++test("activation does not overwrite a prompt admitted while its response is pending", async () => {+ let h;+ h = harness({ api: { activateSessionRevision: async () => {+ h.update({ isRunning: true, messages: [...h.state().messages, row("u3", "user")] });+ return { messages: previous };+ } } });+ await h.actions.activateMessageRevision("u2", 1);+ assert.equal(h.state().messages.at(-1).id, "u3");+});++test("smart stop refuses a different pending user projected during its reload", async () => {+ const messages = previous.slice(0, 4);+ const submitted = { messageCountBeforeSend: 3, draft: { text: "second", fileReferences: [] } };+ let h;+ h = harness({ state: { messages, isRunning: true }, runtime: {+ loadFullSessionMessages: async () => { const next = [...messages, row("u3", "user")]; h.update({ messages: next }); return next; },+ submittedComposerDrafts: new Map([["s", submitted]]),+ } });+ await h.actions.abort();+ assert.deepEqual(h.calls, []);+ assert.equal(h.state().messages.at(-1).id, "u3");+ assert.equal(h.state().isRunning, true, "the old abort cannot stop the newer user turn");+ assert.equal(h.state().composerPrefill, undefined);+ assert.equal(await submitted.abortResolution, false);+});++test("refused conditional retraction rolls back its fence so late old-turn callbacks survive", async () => {+ const h = ipcHarness(false, { ok: true, retracted: false, reason: "reply_started" });+ const result = await h.invoke("sessionRetractPendingPrompt", { sessionId: "s", userMessageId: "u2" });+ assert.equal(result.retracted, false);+ assert.deepEqual(h.events.slice(-2), [["rollback"], ["release"]]);+});++test("the real store/API/preload/IPC path uploads bounded ids with more than 64 MiB retained history", async () => {+ const huge = [...previous];+ huge[1] = { ...huge[1], content: "A".repeat(65 * 1024 * 1024) };+ const wire = [];+ const ipc = ipcHarness(false, (method) => method === "session.activateRevision"+ ? { messages: huge }+ : { ok: true, deleted: true, deletedCount: 2, retracted: true, removedCount: 1 });+ let bridge;+ const shared = { ErrorCodes, IPC, IPC_WHITELIST };+ load("../electron/preload/index.ts", {+ electron: { contextBridge: { exposeInMainWorld: (_name, value) => { bridge = value; } }, webUtils: {}, ipcRenderer: { invoke: async (channel, input) => {+ wire.push(JSON.stringify({ channel, input }));+ const key = Object.keys(IPC.invoke).find((key) => IPC.invoke[key] === channel);+ assert.ok(["sessionDeleteMessage", "sessionRetractPendingPrompt", "sessionActivateRevision"].includes(key));+ return { ok: true, data: await ipc.invoke(key, input) };+ } } }, "@pi-desktop/shared": shared, "@pi-desktop/shared/protocol": shared,+ });+ const { api } = load("../src/lib/api.ts", {+ "@pi-desktop/shared": shared, "./plan-history": {}, "./remote-session-safety": safety,+ "./remote-ipc-safety": { guardRemoteInvocation() {} },+ }, { window: { piDesktop: bridge } });+ const h = harness({ state: { messages: huge }, runtime: { loadFullSessionMessages: async () => huge }, api });+ await h.actions.deleteMessage("u2");+ assert.equal(wire.length, 1);+ assert.ok(Buffer.byteLength(wire[0]) < 256);+ assert.equal(h.state().messages[1].content, huge[1].content);+ assert.deepEqual(h.state().messages.map((message) => message.id), ["u1", "t1", "a1"]);+ h.update({ messages: huge });+ await h.actions.activateMessageRevision("u2", 1);+ assert.equal(h.state().messages[1].content, huge[1].content);+ const submitted = { messageCountBeforeSend: 3, draft: { text: "second", fileReferences: [] } };+ const stopMessages = huge.slice(0, 4);+ // Agent abort is outside the transcript mutation channel under test.+ api.abort = async () => {};+ const stop = harness({ state: { messages: stopMessages, isRunning: true }, api, runtime: {+ loadFullSessionMessages: async () => stopMessages,+ submittedComposerDrafts: new Map([["s", submitted]]),+ } });+ await stop.actions.abort();+ assert.equal(await submitted.abortResolution, true);+ assert.equal(stop.state().messages[1].content, huge[1].content);+ assert.equal(wire.length, 3);+ assert.ok(wire.every((frame) => Buffer.byteLength(frame) < 256));+});++test("a completed smart stop updates its own cache and restores its session draft after a session switch", async () => {+ const messages = previous.slice(0, 4);+ const submitted = { messageCountBeforeSend: 3, draft: { text: "second", fileReferences: [] } };+ const cached = new Map([["s", messages]]);+ let h;+ h = harness({ state: { messages, isRunning: true }, runtime: {+ loadFullSessionMessages: async () => messages,+ submittedComposerDrafts: new Map([["s", submitted]]), sessionTranscriptCache: cached,+ cacheSessionTranscript: (id, rows) => cached.set(id, rows),+ }, api: { retractPendingSessionPrompt: async () => {+ h.update({ activeSessionId: "other", messages: [row("other-user", "user")] });+ return { retracted: true, removedCount: 1 };+ } } });+ await h.actions.abort();+ assert.deepEqual(cached.get("s").map((message) => message.id), ["u1", "t1", "a1"]);+ assert.equal(h.state().messages.at(-1).id, "other-user");+ assert.equal(h.state().composerPrefill?.sessionId, "s");+ assert.equal(h.state().composerPrefill?.text, "second");+});diff --git a/apps/desktop/test/sidecar-history-restore.test.mjs b/apps/desktop/test/sidecar-history-restore.test.mjsnew file mode 100644index 000000000..0e316791c--- /dev/null+++ b/apps/desktop/test/sidecar-history-restore.test.mjs@@ -0,0 +1,64 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import { once } from "node:events";+import { createInterface } from "node:readline";+import test from "node:test";++// Exercise the actual sidecar RPC boundary. Only the external Host service and+// provider endpoint are fixtures; runtime admission and restore wiring are real.+test("history restore failures cannot accept a clean prompt for stable or legacy callers", { timeout: 60_000 }, async (t) => {+ let providerRequests = 0;+ const server = createServer((_req, res) => { providerRequests++; res.writeHead(500); res.end(); });+ server.listen(0, "127.0.0.1"); await once(server, "listening");+ t.after(() => new Promise((resolve) => server.close(resolve)));+ const child = spawn(process.execPath, [new URL("../../../packages/agent-runtime/dist/sidecar.js", import.meta.url).pathname], { stdio: ["pipe", "pipe", "pipe"] });+ t.after(() => { child.kill(); });+ let stderr = ""; child.stderr.on("data", (chunk) => { stderr += chunk; });+ const lines = createInterface({ input: child.stdout }); t.after(() => lines.close());+ const responses = new Map(); const events = [];+ const send = (value) => child.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...value }) + "\n");+ let restoreFailure = "host";+ lines.on("line", (line) => {+ const value = JSON.parse(line);+ if (value.method === "host.proxy") {+ assert.equal(value.params.method, "session.get");+ if (restoreFailure === "host") send({ id: value.id, error: { code: -32000, message: "corrupted persisted history", data: { errorCode: "HISTORY_CORRUPT" } } });+ else if (restoreFailure === "empty") send({ id: value.id, result: { session: { messages: [] } } });+ else if (restoreFailure === "missing") send({ id: value.id, result: { session: null } });+ else send({ id: value.id, result: { session: { messages: [{ id: "bad-history", role: "user", content: "retained", attachments: "invalid" }] } } });+ } else if (value.id) {+ const resolve = responses.get(value.id); responses.delete(value.id); resolve?.(value);+ } else if (value.method === "agent.event") events.push(value.params);+ });+ let id = 0;+ const call = (params) => new Promise((resolve, reject) => {+ const requestId = String(++id);+ const timer = setTimeout(() => reject(new Error(`Sidecar RPC timeout: ${stderr}`)), 15_000);+ responses.set(requestId, (value) => { clearTimeout(timer); resolve(value); });+ send({ id: requestId, method: "agent.prompt", params });+ });+ for (const stable of [false, true]) {+ for (const failure of ["host", "hydrate", "missing"]) {+ restoreFailure = failure;+ const response = await call({+ sessionId: `${stable ? "stable" : "legacy"}-${failure}`, content: "must not start clean",+ ...(stable ? { userMessageId: "current-user" } : {}),+ commandShell: { id: "bash", label: "Bash", executable: "/bin/bash", dialect: "posix", available: true, isDefault: true, args: [] },+ provider: { id: "fixture", modelId: "fixture", authKind: "none", apiStyle: "openai-chat", baseUrl: `http://127.0.0.1:${server.address().port}/v1`, modelConfig: { input: ["text", "image"] } },+ });+ assert.ok(response.error, `${stable ? "stable" : "legacy"} ${failure} must reject admission`);+ assert.equal(response.result, undefined);+ if (failure === "host") assert.equal(response.error.message, "corrupted persisted history");+ }+ }+ assert.equal(providerRequests, 0, "a restore failure must never start a provider turn");+ assert.deepEqual(events, [], "no successful or empty-history turn is emitted");+ restoreFailure = "empty";+ const emptySession = await call({+ sessionId: "new-empty-session", content: "valid first prompt", userMessageId: "first-user",+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ provider: { id: "fixture", modelId: "fixture", authKind: "none", apiStyle: "openai-chat", baseUrl: `http://127.0.0.1:${server.address().port}/v1` },+ });+ assert.equal(emptySession.result?.accepted, true, "a real new session with empty history remains valid");+});diff --git a/apps/desktop/test/transcript-style.test.mjs b/apps/desktop/test/transcript-style.test.mjsindex 3ddc58c30..80bb2c930 100644--- a/apps/desktop/test/transcript-style.test.mjs+++ b/apps/desktop/test/transcript-style.test.mjs@@ -450,7 +450,7 @@ test("stopping a turn undoes an unanswered prompt or settles the partial reply",assert.match(storeSource, /resolveComposerSmartStop\(merged, submittedDraft\)/);assert.match(storeSource,- /replaceSessionMessages\(sessionId,\s*fullStop\.kept\)/,+ /retractPendingSessionPrompt\(\{[\s\S]*?sessionId,[\s\S]*?userMessageId: pendingUserMessageId/,);// Settling a partial reply is renderer-only: the runtime's aborted final row// (or its checkpoint) is the durable copy, and a rewrite from this snapshot@@ -462,7 +462,7 @@ test("stopping a turn undoes an unanswered prompt or settles the partial reply",test("delete remains on user turns and is removed from assistant toolbar", async () => {const storeSource = await readStoreSource();assert.match(storeSource, /deleteMessage:\s*async \(messageId\)/);- assert.match(storeSource, /replaceSessionMessages\(sessionId,\s*next\)/);+ assert.match(storeSource, /deleteSessionMessage\(\{ sessionId, messageId \}\)/);assert.match(transcriptSource, /deleteMessage\(message\.id\)/);assert.match(transcriptSource, /chat\.deleteMessage/);assert.match(diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex 1cf9165a1..4533641b2 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -264,34 +264,33 @@ async function runtimeFor(return reusable;}- let history: UiMessage[] = [];- let compaction: ContextCompactionRecord | undefined;- try {- const detail = await hostProxy.call<{- session?: {- messages?: UiMessage[];- compaction?: ContextCompactionRecord;- } | null;- }>("session.get", { id: sessionId });- let restoredMessages = detail?.session?.messages ?? [];- // The current prompt is sent separately below. Exclude its persisted row- // before attachment hydration so it cannot consume the history byte budget.- if (currentPrompt !== undefined && params.userMessageId) {- restoredMessages = restoredMessages.filter((message) =>- message.role !== "user" || message.id !== params.userMessageId,- );- }- const supportsVision = visionFromModelConfig(params.provider.modelConfig);- history = await hydrateAttachmentHistory(restoredMessages, {- scratchDir: params.scratchDir,- projectPath: params.remoteWorkspace ? undefined : params.projectPath,- attachmentsDir: params.attachmentsDir,- supportsVision,+ const detail = await hostProxy.call<{+ session?: {+ messages?: UiMessage[];+ compaction?: ContextCompactionRecord;+ } | null;+ }>("session.get", { id: sessionId });+ if (!detail?.session) {+ throw Object.assign(new Error("session not found while restoring history"), {+ errorCode: "SESSION_NOT_FOUND",});- compaction = detail?.session?.compaction;- } catch {- // History restore is best-effort; a prompt can still start cleanly.}+ let restoredMessages = detail.session.messages ?? [];+ // The current prompt is sent separately below. Exclude its persisted row+ // before attachment hydration so it cannot consume the history byte budget.+ if (currentPrompt !== undefined && params.userMessageId) {+ restoredMessages = restoredMessages.filter((message) =>+ message.role !== "user" || message.id !== params.userMessageId,+ );+ }+ const supportsVision = visionFromModelConfig(params.provider.modelConfig);+ let history = await hydrateAttachmentHistory(restoredMessages, {+ scratchDir: params.scratchDir,+ projectPath: params.remoteWorkspace ? undefined : params.projectPath,+ attachmentsDir: params.attachmentsDir,+ supportsVision,+ });+ const compaction = detail.session.compaction;// Older callers without a stable message id retain the previous content match.if (currentPrompt !== undefined && !params.userMessageId) {const last = history.at(-1);diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 94c172776..bb0090dc4 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -166,6 +166,8 @@ export const IPC = {sessionImportRun: "pi-desktop/session/importRun",modelConfigImportScan: "pi-desktop/modelConfig/importScan",modelConfigImportRun: "pi-desktop/modelConfig/importRun",+ sessionDeleteMessage: "pi-desktop/session/deleteMessage",+ sessionRetractPendingPrompt: "pi-desktop/session/retractPendingPrompt",sessionReplaceMessages: "pi-desktop/session/replaceMessages",sessionSaveRevision: "pi-desktop/session/saveRevision",sessionListRevisions: "pi-desktop/session/listRevisions",