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): acknowledge revision roots without replaying old messages (#1922)
Seraph Zero47f38b766909
diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.tsindex c03a61096..467d5638d 100644--- a/apps/desktop/electron/main/runtime/event-persistence.ts+++ b/apps/desktop/electron/main/runtime/event-persistence.ts@@ -283,14 +283,16 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined// RPC lock. The read-modify-write this replaced raced the append above// and wrote a stale transcript back over the final message.const saved = await runtimeState.host.call<{- saved?: { root?: any } | null+ saved?: { root?: UiMessage } | null}>("session.saveActiveRevision", { sessionId: envelope.sessionId });const root = saved.saved?.root;if (!root) return;+ // This acknowledges a pager stamp on an existing user row. A terminal+ // message event would append an older root outside the loaded window.emitAgentEvent({sessionId: envelope.sessionId,ts: Date.now(),- event: { type: "message_end", message: root },+ event: { type: "user_message_persisted", optimisticMessageId: root.id, message: root },} satisfies AgentEventEnvelope);} catch (error) {logger.app("persistence", "warn", "save active regenerate branch failed", {diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.tsindex 16761c221..cfec5b146 100644--- a/apps/desktop/src/stores/slices/events-slice.ts+++ b/apps/desktop/src/stores/slices/events-slice.ts@@ -259,12 +259,13 @@ export function createEventsSlice({const sessionId = envelope.sessionId;const reconcile = (messages: UiMessage[]) =>reconcilePersistedUserMessage(messages, event.optimisticMessageId, event.message);+ const state = get();+ const current = runtime.sessionTranscriptCache.get(sessionId) ??+ state.retainedTranscripts[sessionId] ??+ (state.activeSessionId === sessionId ? state.messages : undefined);+ if (!current) return;runtime.liveSessionTranscripts.add(sessionId);- runtime.cacheSessionTranscript(sessionId, reconcile(- runtime.sessionTranscriptCache.get(sessionId) ??- get().retainedTranscripts[sessionId] ??- (get().activeSessionId === sessionId ? get().messages : []),- ));+ runtime.cacheSessionTranscript(sessionId, reconcile(current));set((state) => ({...(state.activeSessionId === sessionId ? { messages: reconcile(state.messages) } : {}),retainedTranscripts: state.retainedTranscripts[sessionId]diff --git a/apps/desktop/test/regenerate-root-projection.test.mjs b/apps/desktop/test/regenerate-root-projection.test.mjsnew file mode 100644index 000000000..3d91af8b7--- /dev/null+++ b/apps/desktop/test/regenerate-root-projection.test.mjs@@ -0,0 +1,168 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { createEventPersistence } = await import("../electron/main/runtime/event-persistence.ts");+const { createSessionCoordination } = await import("../electron/main/runtime/session-coordination.ts");+const { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");+const { createEventsSlice } = await import("../src/stores/slices/events-slice.ts");+const { createSessionSlice } = await import("../src/stores/slices/session-slice.ts");+const { api } = await import("../src/lib/api.ts");++const sessionId = "regenerated-session";+const turnId = "latest-turn";+const root = {+ id: "rewritten-user", role: "user", content: "An older regenerated prompt",+ createdAt: "2026-10-20T06:14:11.000Z", status: "complete",+ revisionRootId: "original-user", revisionCount: 2, activeRevision: 2,+};+const tail = [+ { id: "latest-user", role: "user", content: "Continue", createdAt: "2026-10-25T15:00:00.000Z", status: "complete" },+ { id: "latest-answer", role: "assistant", content: "Latest reply", createdAt: "2026-10-25T15:04:05.000Z", status: "complete" },+];++// Drive the actual main persistence and renderer event/cache wiring. The host+// RPC is the external boundary; all transcript projection code remains real.+function fixture({ active, includeRoot, evictCache = false, hostCall }) {+ const messages = includeRoot ? [{ ...root, revisionCount: 1, activeRevision: 1 }, ...tail] : tail;+ const otherMessages = [{ ...tail[0], id: "other-user" }];+ let state = {+ activeSessionId: active ? sessionId : "other-session",+ messages: active ? messages : otherMessages,+ retainedSessionIds: [sessionId], retainedTranscripts: { [sessionId]: messages },+ runningSessions: {}, sessionHistory: {},+ };+ let runtime;+ const access = {+ get: () => state,+ set: (patch) => {+ const previous = state;+ state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) };+ runtime?.syncTranscriptProjection(state, previous);+ },+ };+ runtime = createSessionRuntime(access);+ runtime.cacheSessionTranscript(sessionId, messages);+ if (evictCache) runtime.sessionTranscriptCache.delete(sessionId);+ Object.assign(state, createEventsSlice({ ...access, runtime }));++ const activeTurns = new Map([[sessionId, turnId]]);+ const coordination = createSessionCoordination({+ activeTurns, getMainWindow: () => null, getViewingSessionId: () => null,+ });+ coordination.recordTurnStart(sessionId, turnId);+ const emitted = [];+ const calls = [];+ const warnings = [];+ const persistence = createEventPersistence({+ runtimeState: { host: { async call(method, params) {+ calls.push({ method, params });+ assert.equal(method, "session.saveActiveRevision");+ return hostCall ? hostCall() : { saved: { root, archived: false } };+ } } },+ steeringReplies: new Set(), completionNoticeTurns: new Set(), activeTurns,+ activeToolCalls: new Map(), activeToolCallKey: coordination.activeToolCallKey,+ approvedExecutionIdsBySession: new Map(), approvedExecutionTurns: new Map(),+ pendingExecutionFinishes: new Map(), planSubmissionTurnIds: new Set(),+ planSubmissionTurnKey: coordination.planSubmissionTurnKey,+ inflightCheckpointer: { observe() {}, flush: async () => {}, settleIf() {} },+ persistenceOutbox: { size: () => 0, flush: async () => {} },+ transcriptRewrite: coordination, addActiveTurnUsage() {},+ logger: { app: (...args) => warnings.push(args) },+ finishTurn: async () => { activeTurns.delete(sessionId); },+ isStaleTerminalEvent: coordination.isStaleTerminalEvent,+ finishApprovedExecution: async () => {},+ emitAgentEvent: (envelope) => {+ emitted.push(envelope);+ state.handleAgentEvent(envelope);+ },+ });+ return { ...access, runtime, emitted, calls, warnings, persistence, messages, otherMessages };+}++async function completeTurn(f) {+ f.persistence.persistAgentEvent({ sessionId, turnId, ts: 1,+ event: { type: "agent_end", messageIds: [tail.at(-1).id] } });+ await f.persistence.flush();+}++for (const active of [true, false]) {+ for (const includeRoot of [false, true]) {+ test(`branch archive ${includeRoot ? "updates the loaded pager" : "keeps an unloaded root out of the tail"} in ${active ? "the active session" : "a background session"}`, async () => {+ const f = fixture({ active, includeRoot });+ await completeTurn(f);+ assert.deepEqual(f.warnings, []);+ assert.equal(f.calls.length, 1);+ for (const rows of [+ f.runtime.sessionTranscriptCache.get(sessionId),+ f.get().retainedTranscripts[sessionId],+ ...(active ? [f.get().messages] : []),+ ]) {+ assert.deepEqual(rows.map((row) => row.id), f.messages.map((row) => row.id));+ assert.equal(rows.at(-1).id, "latest-answer");+ if (includeRoot) assert.deepEqual(rows[0], root);+ }+ if (!active) assert.equal(f.get().messages, f.otherMessages);+ });+ }++ test(`an evicted cache keeps the retained ${active ? "active" : "background"} window without resurrecting its absent root`, async () => {+ const f = fixture({ active, includeRoot: false, evictCache: true });+ await completeTurn(f);+ assert.deepEqual(f.warnings, []);+ assert.deepEqual(f.runtime.sessionTranscriptCache.get(sessionId), tail);+ assert.deepEqual(f.get().retainedTranscripts[sessionId], tail);+ });+}++test("an archive acknowledgement does not resurrect a root deleted while the RPC was pending", async () => {+ const started = Promise.withResolvers();+ const response = Promise.withResolvers();+ const f = fixture({ active: true, includeRoot: true, hostCall: () => {+ started.resolve();+ return response.promise;+ } });+ const completion = completeTurn(f);+ await started.promise;+ f.set({ messages: tail });+ response.resolve({ saved: { root } });+ await completion;+ assert.deepEqual(f.warnings, []);+ assert.deepEqual(f.get().messages, tail);+ assert.deepEqual(f.runtime.sessionTranscriptCache.get(sessionId), tail);+ assert.deepEqual(f.get().retainedTranscripts[sessionId], tail);+});++test("an ordinary user message_end still appends a newly delivered prompt", () => {+ const f = fixture({ active: true, includeRoot: false });+ const message = { ...root, id: "new-user", createdAt: "2026-10-25T15:05:00.000Z" };+ f.get().handleAgentEvent({ sessionId, ts: 2, event: { type: "message_end", message } });+ assert.deepEqual(f.get().messages, [...tail, message]);+});++test("an archive acknowledgement leaves an unloaded background session available to prefetch", async () => {+ const f = fixture({ active: false, includeRoot: false, evictCache: true });+ f.set({ retainedTranscripts: {} });+ const originalGetSession = api.getSession;+ const reads = [];+ api.getSession = async (id) => {+ reads.push(id);+ return { session: { id, messages: tail, messageCount: tail.length } };+ };+ try {+ await completeTurn(f);+ assert.deepEqual(f.warnings, []);+ assert.equal(f.runtime.sessionTranscriptCache.has(sessionId), false);+ assert.equal(f.runtime.liveSessionTranscripts.has(sessionId), false);+ assert.deepEqual(f.get().retainedTranscripts, {});+ assert.equal(f.get().messages, f.otherMessages);++ const sessions = createSessionSlice({ get: f.get, set: f.set, runtime: f.runtime });+ await sessions.prefetchSession(sessionId);+ assert.deepEqual(reads, [sessionId]);+ assert.deepEqual(f.runtime.sessionTranscriptCache.get(sessionId), tail);+ } finally {+ api.getSession = originalGetSession;+ }+});diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 4809010b8..f7a62047b 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,3 +1,5 @@# Unreleased changes-No unreleased changes. See the in-app changelog for version 0.21.0.+- Fixed an older regenerated prompt appearing after the latest reply when its+ branch archive completed outside the loaded history window (#1870). Pager+ acknowledgements now update existing rows without appending historical roots.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 8bc6deda6..e9708ed26 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1193,6 +1193,14 @@ CREATE INDEX idx_message_revisions_roottool line appended by the persistence outbox in the meantime survives. Awhole-transcript rewrite from a snapshot taken outside the host lock woulddelete it (ADR 0060).+- Electron acknowledges the stamped root with `user_message_persisted`, using+ the root's current message `id` as `optimisticMessageId`. This updates the+ pager only where that exact user row is already loaded: the active transcript,+ retained pane, and session cache. A root outside the current history window+ must not be appended after the latest reply. Archive completion is not a new+ user-message lifecycle event and does not change the loaded history boundary.+ If no projection exists, the acknowledgement leaves the cache absent and+ does not mark the session live, so later prefetch still loads durable history.- A branch keeps growing after its archive: later prompts append to it and anerror-ended turn never reaches `agent_end`. So every operation that discardsthe live branch first writes it back over the revision it belongs to (D307):diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 7d57524ec..ef4975ded 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8290,6 +8290,23 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`replace_messages_preserves_owning_turn_ids` covers the remaining rewritecallers. UI paging remains manual.+- **Bounded-history regression (#1870)**: Regenerate an older prompt, then+ continue until the root is outside the newest 100-message page. Complete+ another turn while viewing that page, then repeat after switching to another+ session. The archive must not append the older user root after the latest+ answer in the active transcript, retained pane, or session cache. If the root+ is loaded, its pager updates in place using its current message identity,+ which can differ from the stable family key. A root removed during the+ archive RPC stays absent. Previous variants remain available after restart.+ With neither a cached nor retained background transcript, the acknowledgement+ must leave the cache absent and allow the next prefetch to read the Host.+ Automated event-to-projection coverage:+ `apps/desktop/test/regenerate-root-projection.test.mjs`.+ `node scripts/e2e-regenerate-root.mjs` exercises the real Host process,+ production main persistence and renderer projections with an isolated+ 3,484-message transcript, three follow-up turns, restart, and a revision+ round trip. Set `PI_DESKTOP_HOST_BIN` to a host built from the candidate.+#### E2E-246: Retrying a large session truncates without a whole-transcript RPCdiff --git a/scripts/e2e-regenerate-root.mjs b/scripts/e2e-regenerate-root.mjsnew file mode 100644index 000000000..277e3cf29--- /dev/null+++ b/scripts/e2e-regenerate-root.mjs@@ -0,0 +1,200 @@+#!/usr/bin/env node+/** Real Host + main persistence/outbox + renderer projections, with synthetic+ * messages in an isolated profile. No provider or full Electron UI is used. */+import assert from "node:assert/strict";+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));+const { createEventPersistence } = await import("../apps/desktop/electron/main/runtime/event-persistence.ts");+const { createSessionCoordination } = await import("../apps/desktop/electron/main/runtime/session-coordination.ts");+const { PersistenceOutbox } = await import("../apps/desktop/electron/main/persistence-outbox.ts");+const { createSessionRuntime } = await import("../apps/desktop/src/stores/runtime/session-runtime.ts");+const { createEventsSlice } = await import("../apps/desktop/src/stores/slices/events-slice.ts");+const { createSessionSlice } = await import("../apps/desktop/src/stores/slices/session-slice.ts");+const { api } = await import("../apps/desktop/src/lib/api.ts");++const temp = await mkdtemp(join(tmpdir(), "pi-regenerate-root-"));+const dataDir = join(temp, "data");+const workspace = join(temp, "workspace");+const host = new Host(resolveHostBinary(), dataDir);+const totalMessages = 3484;+const rootPosition = 655;+const pageSize = 100;+const warnings = [];+const message = (id, role, content, index) => ({+ id, role, content, status: "complete",+ createdAt: new Date(Date.UTC(2026, 9, 20) + index * 1_000).toISOString(),+});++function renderer(sessionId, page, active) {+ const otherMessages = [message("other-user", "user", "Another session", 0)];+ let state = {+ activeSessionId: active ? sessionId : "another-session",+ messages: active ? page : otherMessages,+ retainedSessionIds: [sessionId], retainedTranscripts: { [sessionId]: page },+ runningSessions: {}, sessionHistory: {},+ };+ let runtime;+ const access = {+ get: () => state,+ set: (patch) => {+ const previous = state;+ state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) };+ runtime?.syncTranscriptProjection(state, previous);+ },+ };+ runtime = createSessionRuntime(access);+ runtime.cacheSessionTranscript(sessionId, page);+ Object.assign(state, createEventsSlice({ ...access, runtime }));+ return { ...access, runtime, otherMessages };+}++async function finishBranch(sessionId, page, active, unloaded = false) {+ const ui = renderer(sessionId, page, active);+ if (unloaded) {+ assert.equal(active, false);+ ui.runtime.sessionTranscriptCache.delete(sessionId);+ ui.set({ retainedTranscripts: {} });+ }+ const { turnId } = await host.call("session.beginTurn", { sessionId });+ const activeTurns = new Map([[sessionId, turnId]]);+ const coordination = createSessionCoordination({+ activeTurns, getMainWindow: () => null, getViewingSessionId: () => null,+ });+ coordination.recordTurnStart(sessionId, turnId);+ const emitted = [];+ const persistence = createEventPersistence({+ runtimeState: { host }, activeTurns,+ steeringReplies: new Set(), completionNoticeTurns: new Set(),+ activeToolCalls: new Map(), activeToolCallKey: coordination.activeToolCallKey,+ approvedExecutionIdsBySession: new Map(), approvedExecutionTurns: new Map(),+ pendingExecutionFinishes: new Map(), planSubmissionTurnIds: new Set(),+ planSubmissionTurnKey: coordination.planSubmissionTurnKey,+ inflightCheckpointer: { observe() {}, flush: async () => {}, settleIf() {} },+ persistenceOutbox: new PersistenceOutbox(dataDir, (...args) => warnings.push(args)),+ transcriptRewrite: coordination, addActiveTurnUsage() {},+ logger: { app: (...args) => warnings.push(args) },+ finishTurn: async (_id, status) => {+ await host.call("session.endTurn", { turnId, status });+ activeTurns.delete(sessionId);+ },+ isStaleTerminalEvent: coordination.isStaleTerminalEvent,+ finishApprovedExecution: async () => {},+ emitAgentEvent: (envelope) => {+ emitted.push(envelope);+ ui.get().handleAgentEvent(envelope);+ },+ });+ persistence.persistAgentEvent({ sessionId, turnId, ts: Date.now(),+ event: { type: "agent_end", messageIds: [page.at(-1).id] } });+ await persistence.flush();+ assert.deepEqual(warnings, []);+ assert.equal(emitted.length, 1, "the real host returned the historical root");+ if (unloaded) {+ assert.equal(ui.runtime.sessionTranscriptCache.has(sessionId), false);+ assert.equal(ui.runtime.liveSessionTranscripts.has(sessionId), false);+ assert.deepEqual(ui.get().retainedTranscripts, {});+ assert.equal(ui.get().messages, ui.otherMessages);+ const originalGetSession = api.getSession;+ let reads = 0;+ api.getSession = async (id, options) => {+ reads++;+ return host.call("session.get", { id, ...options });+ };+ try {+ const sessions = createSessionSlice({ get: ui.get, set: ui.set, runtime: ui.runtime });+ await sessions.prefetchSession(sessionId);+ assert.equal(reads, 1);+ assert.deepEqual(ui.runtime.sessionTranscriptCache.get(sessionId).map((row) => row.id), page.map((row) => row.id));+ } finally {+ api.getSession = originalGetSession;+ }+ return { ui, root: emitted[0].event.message };+ }+ for (const rows of [ui.runtime.sessionTranscriptCache.get(sessionId), ui.get().retainedTranscripts[sessionId]]) {+ assert.deepEqual(rows.map((row) => row.id), page.map((row) => row.id));+ assert.equal(rows.at(-1).id, page.at(-1).id);+ }+ if (active) assert.deepEqual(ui.get().messages.map((row) => row.id), page.map((row) => row.id));+ else assert.equal(ui.get().messages, ui.otherMessages);+ return { ui, root: emitted[0].event.message };+}++try {+ await mkdir(workspace);+ await host.start();+ const { session } = await host.call("session.create", {+ title: "Regenerate root projection regression", mode: "agent", projectPath: workspace,+ });+ const sessionId = session.id;+ const original = Array.from({ length: totalMessages }, (_, index) =>+ message(`old-${index}`, index === rootPosition || index % 2 === 0 ? "user" : "assistant", `History ${index}`, index));+ await host.call("session.replaceMessages", { sessionId, messages: original });+ const truncated = await host.call("session.truncateFrom", {+ sessionId, fromMessageId: original[rootPosition].id,+ });+ assert.equal(truncated.discardedCount, totalMessages - rootPosition);+ const family = truncated.revision.rootUserId;+ const live = original.slice(0, rootPosition);+ live.push({ ...original[rootPosition], id: "rewritten-root",+ revisionRootId: family, revisionCount: truncated.revision.revisionCount,+ activeRevision: truncated.revision.activeRevision });+ for (let index = rootPosition + 1; index < totalMessages; index++) {+ live.push(message(`live-${index}`, index % 2 === 0 ? "user" : "assistant", `Continued history ${index}`, index));+ }+ await host.call("session.replaceMessages", { sessionId, messages: live });++ const latest = async () => (await host.call("session.get", { id: sessionId, messageLimit: pageSize })).session;+ const firstPage = await latest();+ assert.equal(firstPage.messageStart, totalMessages - pageSize);+ assert.equal(firstPage.messages.length, pageSize);+ assert.equal(firstPage.messages.some((row) => row.id === "rewritten-root"), false);+ for (const active of [true, false]) {+ const { root } = await finishBranch(sessionId, firstPage.messages, active);+ assert.equal(root.id, "rewritten-root");+ assert.equal(root.revisionRootId, family);+ }+ await finishBranch(sessionId, firstPage.messages, false, true);++ // The exact arithmetic in #1870 is the normal live suffix length, not a+ // lookup that needs the old family key to remain in the messages table.+ const { revisions } = await host.call("session.listRevisions", { sessionId, rootUserId: family });+ assert.equal(revisions.length, 2);+ assert.equal(revisions[1].messageCount, totalMessages - rootPosition);+ assert.equal(totalMessages - revisions[1].messageCount, rootPosition);+ const full = (await host.call("session.get", { id: sessionId })).session.messages;+ assert.equal(full.some((row) => row.id === family), false);+ for (const active of [true, false]) {+ const loaded = await finishBranch(sessionId, full, active);+ assert.deepEqual(loaded.ui.runtime.sessionTranscriptCache.get(sessionId)[rootPosition], loaded.root);+ assert.deepEqual(loaded.ui.get().retainedTranscripts[sessionId][rootPosition], loaded.root);+ }++ for (let index = 0; index < 3; index++) {+ await host.call("session.appendMessage", { sessionId, message: message(`follow-user-${index}`, "user", "Continue", totalMessages + index * 2) });+ await host.call("session.appendMessage", { sessionId, message: message(`follow-answer-${index}`, "assistant", "Latest reply", totalMessages + index * 2 + 1) });+ await finishBranch(sessionId, (await latest()).messages, index % 2 === 0);+ }+ const expectedIds = [...live.map((row) => row.id), ...Array.from({ length: 3 }, (_, index) => [`follow-user-${index}`, `follow-answer-${index}`]).flat()];+ await host.restart();+ for (const revisionIndex of [1, 2]) {+ const { messages } = await host.call("session.activateRevision", {+ sessionId, rootUserId: family, revisionIndex, prefix: [],+ });+ assert.deepEqual(messages.map((row) => row.id), revisionIndex === 1 ? original.map((row) => row.id) : expectedIds);+ }+ const raw = await readFile(join(dataDir, "sessions", `${sessionId}.jsonl`), "utf8");+ const records = raw.trim().split("\n").map((line) => JSON.parse(line)).filter((row) => row.type === "message");+ assert.deepEqual(records.map((row) => row.id), expectedIds);+ console.log(JSON.stringify({ scenario: "E2E-118 / #1870", totalMessages,+ rootPosition, branchMessageCount: revisions[1].messageCount, pageSize,+ projectionCases: 5, unloadedSessionPrefetch: "passed", followUpTurns: 3, restartAndRevisionRoundTrip: "passed",+ finalMessages: records.length, warnings: warnings.length }));+} finally {+ await host.stop();+ await rm(temp, { recursive: true, force: true });+}