Skip to content

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

fix(session): one rewrite boundary for replacement and revision activation (#1674)

Liu Zixiangbde97bc494de
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 0d345e055..8f834cac2 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -627,6 +627,7 @@ const {
addActiveTurnUsage,
activeToolCallKey,
planSubmissionTurnKey,
+ recordTurnStart,
lockAbortReason,
isTurnDispatchable,
isSessionBusy,
@@ -718,6 +719,7 @@ const eventPersistence = createEventPersistence({
logger,
finishTurn,
isStaleTerminalEvent,
+ transcriptRewrite: sessionCoordination,
finishApprovedExecution,
emitAgentEvent: (envelope) => emitAgentEvent(envelope),
});
@@ -875,6 +877,9 @@ function registerIpc() {
sessionCapabilityContext,
enrichSession,
acquireSessionOperation,
+ beginTranscriptRewrite: eventPersistence.beginTranscriptRewrite,
+ forgetTranscriptRewriteHistory: sessionCoordination.forgetTranscriptRewriteHistory,
+ recordTurnStart,
stripWinLongPrefix,
normalizeSettings,
validateSettingsWrite,
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 43b43d136..18ffd87ae 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -25,6 +25,7 @@ export type AgentIpcDependencies = {
persistenceOutbox: PersistenceOutbox;
dataDir: string;
activeTurns: Map<string, string>;
+ recordTurnStart: (sessionId: string, turnId: string) => void;
/** Whether the named turn can still start or steer host work. */
isTurnDispatchable: (sessionId: string, turnId: string | null | undefined) => boolean;
activeTurnUsages: Map<string, MessageUsage>;
@@ -86,6 +87,7 @@ export function registerAgentIpc({
persistenceOutbox,
dataDir,
activeTurns,
+ recordTurnStart,
isTurnDispatchable,
activeTurnUsages,
approvedExecutionIdsBySession,
@@ -336,6 +338,7 @@ export function registerAgentIpc({
throw new Error("session.beginTurn returned no turn");
}
activeTurns.set(req.sessionId, durableTurnId);
+ recordTurnStart(req.sessionId, durableTurnId);
activeTurnUsages.delete(req.sessionId);
// Slash expansion (D123, ADR 0024): templates expand before persistence
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index eff042db9..352d61399 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -106,6 +106,9 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
sessionCapabilityContext,
enrichSession,
acquireSessionOperation,
+ beginTranscriptRewrite,
+ forgetTranscriptRewriteHistory,
+ recordTurnStart,
stripWinLongPrefix,
normalizeSettings,
validateSettingsWrite,
@@ -265,6 +268,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
sessionCapabilityContext,
enrichSession,
acquireSessionOperation,
+ beginTranscriptRewrite,
+ forgetTranscriptRewriteHistory,
stripWinLongPrefix,
});
registerSettingsIpc({
@@ -402,6 +407,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
persistenceOutbox,
dataDir,
activeTurns,
+ recordTurnStart,
isTurnDispatchable,
activeTurnUsages,
approvedExecutionIdsBySession,
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index 31efaead3..f62be5b1e 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -99,6 +99,11 @@ export type SessionIpcDependencies = {
sessionCapabilityContext: () => Promise<{ providers: any; defaults: any }>;
enrichSession: (session: any, providers: any, defaults: any) => any;
acquireSessionOperation: (sessionId: string) => Promise<() => void>;
+ beginTranscriptRewrite: (sessionId: string) => {
+ commit: () => void;
+ rollback: () => void;
+ };
+ forgetTranscriptRewriteHistory: (sessionId: string) => void;
stripWinLongPrefix: (path: string) => string;
};
@@ -115,6 +120,8 @@ export function registerSessionIpc({
sessionCapabilityContext,
enrichSession,
acquireSessionOperation,
+ beginTranscriptRewrite,
+ forgetTranscriptRewriteHistory,
stripWinLongPrefix,
}: SessionIpcDependencies): void {
let host: HostProcess | null = null;
@@ -127,6 +134,56 @@ 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
+ * (#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
+ * transcript rather than replaying into the new one. The persistence fence
+ * also holds callbacks delivered after that drain: successful rewrites
+ * invalidate pre-rewrite turns, while failed rewrites replay their events.
+ * The sidecar runtime is dropped after the drain so the next prompt reseeds
+ * from the rewritten transcript instead of replaying the discarded branch
+ * in memory.
+ */
+ const runTranscriptRewrite = async <T>(
+ sessionId: string,
+ purpose: string,
+ currentHost: HostProcess,
+ run: () => Promise<T>,
+ ): Promise<T> => {
+ rejectNativeMutation(sessionId, purpose);
+ const releaseSessionOperation = await acquireSessionOperation(sessionId);
+ let rewriteFence: ReturnType<typeof beginTranscriptRewrite> | undefined;
+ try {
+ if (activeTurns.has(sessionId)) {
+ throw Object.assign(
+ new Error("Cannot rewrite the transcript of a running session"),
+ { errorCode: ErrorCodes.AGENT_BUSY },
+ );
+ }
+ rewriteFence = beginTranscriptRewrite(sessionId);
+ await persistenceOutbox.prepareSessionReplacement(sessionId, () => currentHost);
+ if (sidecar) {
+ sidecar.clearProjectInstructionRoot(sessionId);
+ sidecar.clearVendorAuthBindings(sessionId);
+ await sidecar
+ .call("agent.disposeSession", { sessionId })
+ .catch(() => undefined);
+ }
+ const result = await run();
+ rewriteFence.commit();
+ return result;
+ } catch (error) {
+ rewriteFence?.rollback();
+ throw error;
+ } finally {
+ releaseSessionOperation();
+ }
+ };
+
handle(IPC.invoke.sessionSearch, async (input) => {
if (!host) throw new Error("host unavailable");
return searchSessionsAcrossSources(host, sidecar, input);
@@ -336,6 +393,7 @@ export function registerSessionIpc({
if (!host) throw new Error("host unavailable");
const res = await host.call("session.delete", { id });
await persistenceOutbox.dropSession(id);
+ forgetTranscriptRewriteHistory(id);
// Drop the session's pi-agent so a later session with the same id (or a
// stale runtime) can't answer with this session's context.
if (sidecar) {
@@ -440,21 +498,17 @@ export function registerSessionIpc({
if (!host) throw new Error("host unavailable");
const sessionId = String(input?.sessionId || "");
if (!sessionId) throw new Error("sessionId required");
- rejectNativeMutation(sessionId, "transcript replacement");
- await persistenceOutbox.prepareSessionReplacement(sessionId, () => host);
- // Drop the live pi-agent so the next prompt reseeds from the truncated
- // transcript instead of replaying the discarded branch in memory.
- if (sidecar) {
- sidecar.clearProjectInstructionRoot(sessionId);
- sidecar.clearVendorAuthBindings(sessionId);
- await sidecar
- .call("agent.disposeSession", { sessionId })
- .catch(() => undefined);
- }
- return host.call("session.replaceMessages", {
+ const currentHost = host;
+ return runTranscriptRewrite(
sessionId,
- messages: input.messages ?? [],
- });
+ "transcript replacement",
+ currentHost,
+ () =>
+ currentHost.call("session.replaceMessages", {
+ sessionId,
+ messages: input.messages ?? [],
+ }),
+ );
},
);
handle(
@@ -496,20 +550,20 @@ export function registerSessionIpc({
}) => {
if (!host) throw new Error("host unavailable");
const sessionId = String(input?.sessionId || "");
- rejectNativeMutation(sessionId, "revision activation");
- if (sidecar) {
- sidecar.clearProjectInstructionRoot(sessionId);
- sidecar.clearVendorAuthBindings(sessionId);
- await sidecar
- .call("agent.disposeSession", { sessionId })
- .catch(() => undefined);
- }
- return host.call("session.activateRevision", {
+ if (!sessionId) throw new Error("sessionId required");
+ const currentHost = host;
+ return runTranscriptRewrite(
sessionId,
- rootUserId: String(input?.rootUserId || ""),
- revisionIndex: Number(input?.revisionIndex || 0),
- prefix: input?.prefix ?? [],
- });
+ "revision activation",
+ currentHost,
+ () =>
+ currentHost.call("session.activateRevision", {
+ sessionId,
+ rootUserId: String(input?.rootUserId || ""),
+ revisionIndex: Number(input?.revisionIndex || 0),
+ prefix: input?.prefix ?? [],
+ }),
+ );
},
);
handle(IPC.invoke.sessionGetScratchPath, async (input: { sessionId: string }) => {
diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.ts
index c7afa6469..e8cf88d27 100644
--- a/apps/desktop/electron/main/runtime/event-persistence.ts
+++ b/apps/desktop/electron/main/runtime/event-persistence.ts
@@ -5,6 +5,7 @@ import type { RuntimeState } from "./context";
import type { InflightCheckpointer } from "@pi-desktop/host-runtime";
import type { Logger } from "../logger";
import type { PersistenceOutbox } from "../persistence-outbox";
+import type { SessionCoordination } from "./session-coordination";
export type EventPersistenceDependencies = {
runtimeState: RuntimeState;
@@ -28,6 +29,11 @@ export type EventPersistenceDependencies = {
* returning early does not stop this function from running.
*/
isStaleTerminalEvent: (envelope: AgentEventEnvelope) => boolean;
+ /** Per-session turn history and rewrite fence shared with transcript IPC. */
+ transcriptRewrite: Pick<
+ SessionCoordination,
+ "beginTranscriptRewrite" | "deferTranscriptEvent" | "isStaleTranscriptEvent"
+ >;
finishApprovedExecution: (...args: any[]) => Promise<void>;
emitAgentEvent: (envelope: AgentEventEnvelope) => void;
};
@@ -49,11 +55,16 @@ export function createEventPersistence({
logger,
finishTurn,
isStaleTerminalEvent,
+ transcriptRewrite,
finishApprovedExecution,
emitAgentEvent,
}: EventPersistenceDependencies): {
subagentTagged: (message: UiMessage, envelope: AgentEventEnvelope) => UiMessage;
persistAgentEvent: (envelope: AgentEventEnvelope) => UiMessage | undefined;
+ beginTranscriptRewrite: (sessionId: string) => {
+ commit: () => void;
+ rollback: () => void;
+ };
flush: () => Promise<void>;
} {
const inflightSnapshots = new Map<string, UiMessage>();
@@ -70,14 +81,43 @@ export function createEventPersistence({
await Promise.allSettled([...pendingWrites]);
}
}
+
+ function beginTranscriptRewrite(sessionId: string) {
+ const lease = transcriptRewrite.beginTranscriptRewrite(sessionId);
+ let settled = false;
+ return {
+ commit(): void {
+ if (settled) return;
+ settled = true;
+ lease.commit();
+ },
+ rollback(): void {
+ if (settled) return;
+ settled = true;
+ for (const envelope of lease.rollback()) {
+ try {
+ persistAgentEvent(envelope);
+ } catch (error) {
+ logger.app("persistence", "warn", "transcript rewrite event replay failed", {
+ sessionId,
+ data: String(error),
+ });
+ }
+ }
+ },
+ };
+ }
function subagentTagged(message: UiMessage, envelope: AgentEventEnvelope): UiMessage {
return tagMessageToolLineage(message, envelope);
}
function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined {
+ if (transcriptRewrite.deferTranscriptEvent(envelope)) return;
+ const activeTurnId = activeTurns.get(envelope.sessionId);
+ if (transcriptRewrite.isStaleTranscriptEvent(envelope, activeTurnId)) return;
const event = envelope.event;
- const turnId = activeTurns.get(envelope.sessionId);
+ const turnId = activeTurnId;
const usage = usageForEvent(envelope);
if (usage) {
if (ownsUsageTurn(envelope, turnId)) addActiveTurnUsage(envelope.sessionId, usage);
@@ -382,5 +422,5 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined
return message;
}
}
- return { subagentTagged, persistAgentEvent, flush };
+ return { subagentTagged, persistAgentEvent, beginTranscriptRewrite, flush };
}
diff --git a/apps/desktop/electron/main/runtime/plans.ts b/apps/desktop/electron/main/runtime/plans.ts
index 5f53b32af..c49fea7f8 100644
--- a/apps/desktop/electron/main/runtime/plans.ts
+++ b/apps/desktop/electron/main/runtime/plans.ts
@@ -453,6 +453,7 @@ async function dispatchApprovedPlan(rawExecution: unknown): Promise<void> {
turnId = String(turn.turnId || "").trim();
if (!turnId) throw new Error("execution turn was not created");
activeTurns.set(execution.sessionId, turnId);
+ coordination.recordTurnStart(execution.sessionId, turnId);
activeTurnUsages.delete(execution.sessionId);
approvedExecutionIdsBySession.set(execution.sessionId, execution.id);
approvedExecutionTurns.set(execution.id, {
diff --git a/apps/desktop/electron/main/runtime/session-coordination.ts b/apps/desktop/electron/main/runtime/session-coordination.ts
index babef544d..a0fa85bbe 100644
--- a/apps/desktop/electron/main/runtime/session-coordination.ts
+++ b/apps/desktop/electron/main/runtime/session-coordination.ts
@@ -22,6 +22,11 @@ export type TurnEndedPayload = {
reason: TurnEndReason;
};
+export type TranscriptRewriteLease = {
+ commit: () => void;
+ rollback: () => AgentEventEnvelope[];
+};
+
export type SessionCoordinationDependencies = {
activeTurns: Map<string, string>;
getMainWindow: () => BrowserWindow | null;
@@ -57,6 +62,96 @@ export function createSessionCoordination({
* the frozen record already owns the turn.
*/
const pendingAbortReasons = new Map<string, TurnEndReason>();
+ /** Turn identities remain until a transcript rewrite fences their late events. */
+ const startedTurnsBySession = new Map<string, Set<string>>();
+ const invalidatedTranscriptTurns = new Map<string, Set<string>>();
+ const rewrittenSessions = new Set<string>();
+ const transcriptRewriteFences = new Map<
+ string,
+ { turnIds: Set<string>; events: AgentEventEnvelope[]; forgotten: boolean }
+ >();
+
+ function recordTurnStart(sessionId: string, turnId: string): void {
+ const id = sessionId.trim();
+ const turn = turnId.trim();
+ if (!id || !turn) return;
+ const turns = startedTurnsBySession.get(id) ?? new Set<string>();
+ turns.add(turn);
+ startedTurnsBySession.set(id, turns);
+ }
+
+ function beginTranscriptRewrite(sessionId: string): TranscriptRewriteLease {
+ const id = sessionId.trim();
+ if (!id) throw new Error("sessionId is required for transcript rewrite");
+ if (transcriptRewriteFences.has(id)) {
+ throw new Error("a transcript rewrite is already active for this session");
+ }
+ const state = {
+ turnIds: new Set(startedTurnsBySession.get(id) ?? []),
+ events: [] as AgentEventEnvelope[],
+ forgotten: false,
+ };
+ transcriptRewriteFences.set(id, state);
+
+ const finish = (committed: boolean): AgentEventEnvelope[] => {
+ if (transcriptRewriteFences.get(id) !== state) return [];
+ transcriptRewriteFences.delete(id);
+ if (state.forgotten) {
+ clearTranscriptRewriteHistory(id);
+ return [];
+ }
+ if (!committed) return state.events;
+
+ const invalidated = invalidatedTranscriptTurns.get(id) ?? new Set<string>();
+ for (const turnId of state.turnIds) invalidated.add(turnId);
+ invalidatedTranscriptTurns.set(id, invalidated);
+ rewrittenSessions.add(id);
+ startedTurnsBySession.delete(id);
+ state.events.length = 0;
+ return [];
+ };
+
+ return {
+ commit: () => {
+ finish(true);
+ },
+ rollback: () => finish(false),
+ };
+ }
+
+ function deferTranscriptEvent(envelope: AgentEventEnvelope): boolean {
+ const state = transcriptRewriteFences.get(envelope.sessionId.trim());
+ if (!state) return false;
+ state.events.push(envelope);
+ return true;
+ }
+
+ function isStaleTranscriptEvent(
+ envelope: AgentEventEnvelope,
+ currentTurnId: string | undefined,
+ ): boolean {
+ const sessionId = envelope.sessionId.trim();
+ const turnId = envelope.turnId?.trim() || currentTurnId?.trim();
+ if (turnId && invalidatedTranscriptTurns.get(sessionId)?.has(turnId)) return true;
+ return rewrittenSessions.has(sessionId) && !turnId;
+ }
+
+ function forgetTranscriptRewriteHistory(sessionId: string): void {
+ const id = sessionId.trim();
+ if (!id) return;
+ const fence = transcriptRewriteFences.get(id);
+ if (fence) {
+ fence.forgotten = true;
+ return;
+ }
+ clearTranscriptRewriteHistory(id);
+ }
+
+ function clearTranscriptRewriteHistory(sessionId: string): void {
+ startedTurnsBySession.delete(sessionId);
+ invalidatedTranscriptTurns.delete(sessionId);
+ rewrittenSessions.delete(sessionId);
+ }
async function acquireSessionOperation(sessionId: string): Promise<() => void> {
const id = sessionId.trim();
@@ -253,6 +348,11 @@ export function createSessionCoordination({
turnFinalizations,
pendingAbortReasons,
acquireSessionOperation,
+ recordTurnStart,
+ beginTranscriptRewrite,
+ deferTranscriptEvent,
+ isStaleTranscriptEvent,
+ forgetTranscriptRewriteHistory,
addActiveTurnUsage,
activeToolCallKey,
planSubmissionTurnKey,
diff --git a/apps/desktop/test/composer-mcp.test.mjs b/apps/desktop/test/composer-mcp.test.mjs
index 2acc45a37..3b457a7bf 100644
--- a/apps/desktop/test/composer-mcp.test.mjs
+++ b/apps/desktop/test/composer-mcp.test.mjs
@@ -75,6 +75,7 @@ function promptFixture(commandService, projectPath = "/repo", remoteWorkspace) {
logger: { app() {} }, vendorOAuth: {}, agentExtensions: {}, cancelSessionTools() {},
persistenceOutbox: {}, dataDir: "/unused-for-no-attachments",
activeTurns: new Map(), activeTurnUsages: new Map(), approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
+ recordTurnStart() {},
resolveAgentRuntimeLaunch: async () => ({
projectPath, providerId: "provider", modelId: "model",
sidecarParams: { sessionId: "target", provider: { modelConfig: { input: ["text"] } } },
diff --git a/apps/desktop/test/delete-message-preserves-transcript.test.mjs b/apps/desktop/test/delete-message-preserves-transcript.test.mjs
index 3a05e7a62..2cb4deda2 100644
--- a/apps/desktop/test/delete-message-preserves-transcript.test.mjs
+++ b/apps/desktop/test/delete-message-preserves-transcript.test.mjs
@@ -31,13 +31,33 @@ test("deleteMessage merges the store read after the transcript reload, not a pre
);
});
-test("sessionReplaceMessages IPC drops stale pending outbox appends for the session", async () => {
+test("sessionReplaceMessages and sessionActivateRevision share one rewrite boundary with drain and guards", async () => {
const sessionIpcSource = await readMainSource("ipc/session-ipc.ts");
+ // The shared gate: refuse while a turn runs, serialize overlapping
+ // operations, then drain the outbox before the callers' rewrite runs (#1612, #1613).
assert.match(
sessionIpcSource,
- /IPC\.invoke\.sessionReplaceMessages[\s\S]*?await\s+persistenceOutbox\.prepareSessionReplacement\(sessionId,\s*\(\)\s*=>\s*host\);[\s\S]*?return\s+host\.call\("session\.replaceMessages"/,
- "sessionReplaceMessages must drain in-flight appends before dropping the queue and replacing the transcript",
+ /const\s+runTranscriptRewrite\s*=\s*async[\s\S]*?acquireSessionOperation\(sessionId\)[\s\S]*?activeTurns\.has\(sessionId\)[\s\S]*?AGENT_BUSY[\s\S]*?await\s+persistenceOutbox\.prepareSessionReplacement\(sessionId,[\s\S]*?finally\s*\{[\s\S]*?releaseSessionOperation\(\);/,
+ "the rewrite gate must serialize per session, refuse running turns, and drain the outbox",
+ );
+ assert.match(
+ sessionIpcSource,
+ /beginTranscriptRewrite\(sessionId\)[\s\S]*?await\s+persistenceOutbox\.prepareSessionReplacement[\s\S]*?const\s+result\s*=\s*await\s+run\(\);[\s\S]*?rewriteFence\.commit\(\);[\s\S]*?catch\s*\(error\)\s*\{\s*rewriteFence\?\.rollback\(\);/,
+ "the rewrite gate must fence late appends before draining and settle the fence according to the host rewrite result",
+ );
+
+ // Both rewrite entrances route through the gate — activation had no drain
+ // before #1612, and overlapping replaces could interleave (#1613).
+ assert.match(
+ sessionIpcSource,
+ /IPC\.invoke\.sessionReplaceMessages[\s\S]*?runTranscriptRewrite\(\s*sessionId,\s*"transcript replacement"[\s\S]*?session\.replaceMessages/,
+ "sessionReplaceMessages must go through the shared rewrite gate",
+ );
+ assert.match(
+ sessionIpcSource,
+ /IPC\.invoke\.sessionActivateRevision[\s\S]*?runTranscriptRewrite\(\s*sessionId,\s*"revision activation"[\s\S]*?session\.activateRevision/,
+ "sessionActivateRevision must go through the shared rewrite gate (it rewrites the same transcript rows)",
);
});
diff --git a/apps/desktop/test/helpers/live-work-production.mjs b/apps/desktop/test/helpers/live-work-production.mjs
index d0fa3f49d..5b8c65190 100644
--- a/apps/desktop/test/helpers/live-work-production.mjs
+++ b/apps/desktop/test/helpers/live-work-production.mjs
@@ -71,6 +71,7 @@ export async function createProductionWorkHarness(t, server, options = {}) {
persistenceOutbox: { async flush() {} },
dataDir: "/tmp/pi-live-work-production-fixture-data",
activeTurns: new Map(), isTurnDispatchable: () => true, activeTurnUsages: new Map(),
+ recordTurnStart() {},
approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
async resolveAgentRuntimeLaunch(_id, session) {
return {
diff --git a/apps/desktop/test/session-message-input.test.mjs b/apps/desktop/test/session-message-input.test.mjs
index 2fab6e07f..7b88a2ff4 100644
--- a/apps/desktop/test/session-message-input.test.mjs
+++ b/apps/desktop/test/session-message-input.test.mjs
@@ -64,6 +64,7 @@ test("prompt IPC persists original session text, skips slash expansion and binds
const calls = [];
const events = [];
const sidecarCalls = [];
+ const recordedTurns = [];
const host = {
async call(method, params) {
calls.push({ method, params });
@@ -87,6 +88,7 @@ test("prompt IPC persists original session text, skips slash expansion and binds
logger: { app() {} }, vendorOAuth: {}, agentExtensions: {}, cancelSessionTools() {},
persistenceOutbox: {}, dataDir: "/unused-for-no-attachments",
activeTurns: new Map(), activeTurnUsages: new Map(), approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
+ recordTurnStart: (sessionId, turnId) => recordedTurns.push([sessionId, turnId]),
resolveAgentRuntimeLaunch: async () => ({
providerId: "provider", modelId: "model",
sidecarParams: { sessionId: "target", provider: { modelConfig: { input: ["text"] } } },
@@ -107,6 +109,7 @@ test("prompt IPC persists original session text, skips slash expansion and binds
assert.equal(row.command, undefined);
assert.equal(sidecarCalls[0].params.content, message.content);
assert.deepEqual(sidecarCalls[0].params.sessionMessage, origin);
+ assert.deepEqual(recordedTurns, [["target", "turn-1"]]);
assert.equal(events.length, 2);
assert.equal(released, true);
});
@@ -151,6 +154,7 @@ test("abort waits for prompt admission before dispatching to the sidecar", async
logger: { app() {} }, vendorOAuth: {}, agentExtensions: { cancelPrompts() {} }, cancelSessionTools() {},
persistenceOutbox: {}, dataDir: "/unused-for-no-attachments",
activeTurns, activeTurnUsages: new Map(), approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
+ recordTurnStart() {},
resolveAgentRuntimeLaunch: async () => ({
providerId: "provider", modelId: "model",
sidecarParams: { sessionId: "target", provider: { modelConfig: { input: ["text"] } } },
diff --git a/apps/desktop/test/session-turn-ended.test.mjs b/apps/desktop/test/session-turn-ended.test.mjs
index 0ac6c13f3..47e09343d 100644
--- a/apps/desktop/test/session-turn-ended.test.mjs
+++ b/apps/desktop/test/session-turn-ended.test.mjs
@@ -55,6 +55,7 @@ function fixture() {
return Promise.resolve();
},
isStaleTerminalEvent: coordination.isStaleTerminalEvent,
+ transcriptRewrite: coordination,
finishApprovedExecution: async () => undefined,
emitAgentEvent: (envelope) => emitted.push(envelope),
});
@@ -135,6 +136,56 @@ test("non-terminal rows of a late turn are still archived as history", async ()
assert.deepEqual(f.finished, [], "while the live turn is untouched");
});
+test("a transcript rewrite drops late appends from the rewritten turn but keeps a later turn", async () => {
+ const f = fixture();
+ f.coordination.recordTurnStart(SESSION, LIVE_TURN);
+ f.coordination.recordTurnStart(SESSION, OLD_TURN);
+ f.activeTurns.delete(SESSION);
+
+ const rewrite = f.persistence.beginTranscriptRewrite(SESSION);
+ const oldToolEnd = f.envelope(
+ { type: "tool_end", toolCallId: "old-call", result: "old result", isError: false },
+ OLD_TURN,
+ );
+ f.persistence.persistAgentEvent(oldToolEnd);
+ assert.equal(f.enqueued.length, 0, "events arriving during the rewrite stay behind its fence");
+
+ rewrite.commit();
+ f.persistence.persistAgentEvent(oldToolEnd);
+ await Promise.resolve();
+ assert.equal(f.enqueued.length, 0, "neither buffered nor later old-turn events can append");
+
+ const newTurn = "turn-c";
+ f.coordination.recordTurnStart(SESSION, newTurn);
+ f.activeTurns.set(SESSION, newTurn);
+ const newToolEnd = f.envelope(
+ { type: "tool_end", toolCallId: "new-call", result: "new result", isError: false },
+ newTurn,
+ );
+ f.persistence.persistAgentEvent(newToolEnd);
+ await Promise.resolve();
+ assert.deepEqual(f.enqueued.map((entry) => entry.turnId), [newTurn]);
+});
+
+test("a failed transcript rewrite replays events that arrived while fenced", async () => {
+ const f = fixture();
+ f.coordination.recordTurnStart(SESSION, OLD_TURN);
+ f.activeTurns.delete(SESSION);
+
+ const rewrite = f.persistence.beginTranscriptRewrite(SESSION);
+ f.persistence.persistAgentEvent(
+ f.envelope(
+ { type: "tool_end", toolCallId: "old-call", result: "old result", isError: false },
+ OLD_TURN,
+ ),
+ );
+ assert.equal(f.enqueued.length, 0);
+
+ rewrite.rollback();
+ await Promise.resolve();
+ assert.deepEqual(f.enqueued.map((entry) => entry.turnId), [OLD_TURN]);
+});
+
test("isStaleTerminalEvent only classifies terminal events", () => {
const f = fixture();
const stale = {
diff --git a/apps/desktop/test/shutdown-regenerate-persistence.test.mjs b/apps/desktop/test/shutdown-regenerate-persistence.test.mjs
index 17932555b..e5556b64a 100644
--- a/apps/desktop/test/shutdown-regenerate-persistence.test.mjs
+++ b/apps/desktop/test/shutdown-regenerate-persistence.test.mjs
@@ -29,6 +29,11 @@ const { app } = await import("electron");
const { createEventPersistence } = await import("../electron/main/runtime/event-persistence.ts");
const { PersistenceOutbox } = await import("../electron/main/persistence-outbox.ts");
const { registerShutdownHandlers } = await import("../electron/main/bootstrap/shutdown.ts");
+const transcriptRewrite = {
+ beginTranscriptRewrite: () => ({ commit() {}, rollback: () => [] }),
+ deferTranscriptEvent: () => false,
+ isStaleTranscriptEvent: () => false,
+};
for (const outcome of ["complete", "error", "unresponsive"]) {
test(`quit settles a regenerated branch when the host is ${outcome}`, async (t) => {
@@ -72,6 +77,7 @@ test(`quit settles a regenerated branch when the host is ${outcome}`, async (t)
pendingExecutionFinishes: new Map(), planSubmissionTurnIds: new Set(),
planSubmissionTurnKey: (s, turn) => `${s}:${turn}`,
inflightCheckpointer: checkpoint, persistenceOutbox: outbox,
+ transcriptRewrite,
addActiveTurnUsage() {}, logger,
finishTurn: async () => { activeTurns.clear(); },
isStaleTerminalEvent: () => false,
diff --git a/apps/desktop/test/subagent-settlement-persistence.test.mjs b/apps/desktop/test/subagent-settlement-persistence.test.mjs
index 245f1da43..401a27348 100644
--- a/apps/desktop/test/subagent-settlement-persistence.test.mjs
+++ b/apps/desktop/test/subagent-settlement-persistence.test.mjs
@@ -8,6 +8,11 @@ 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 { PersistenceOutbox } = await import("../electron/main/persistence-outbox.ts");
+const transcriptRewrite = {
+ beginTranscriptRewrite: () => ({ commit() {}, rollback: () => [] }),
+ deferTranscriptEvent: () => false,
+ isStaleTranscriptEvent: () => false,
+};
test("a settled Task snapshot survives outbox recovery with its original turn and metadata", async () => {
const dir = await mkdtemp(join(tmpdir(), "pi-subagent-settlement-"));
@@ -31,6 +36,7 @@ test("a settled Task snapshot survives outbox recovery with its original turn an
pendingExecutionFinishes: new Map(),
planSubmissionTurnIds: new Set(),
persistenceOutbox,
+ transcriptRewrite,
logger: { app: silent },
});
const message = {
@@ -86,6 +92,7 @@ for (const delegate of [false, true]) {
pendingExecutionFinishes: new Map(),
planSubmissionTurnIds: new Set(),
persistenceOutbox,
+ transcriptRewrite,
logger: { app: silent },
});
const lineage = {
@@ -157,7 +164,8 @@ test("independent usage aggregates survive an unavailable Host and outbox restar
activeToolCalls: new Map(), activeToolCallKey: (s, t) => `${s}:${t}`,
approvedExecutionIdsBySession: new Map(), approvedExecutionTurns: new Map(),
pendingExecutionFinishes: new Map(), planSubmissionTurnIds: new Set(),
- persistenceOutbox: outbox, logger: { app: () => undefined }, addActiveTurnUsage: () => undefined,
+ persistenceOutbox: outbox, transcriptRewrite,
+ logger: { app: () => undefined }, addActiveTurnUsage: () => undefined,
});
for (const id of ["image-a", "image-b", "image-a"]) {
const operation = { operationId: id, inputTokens: 10, outputTokens: 2, totalTokens: 12 };
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index 4ef568079..db39b7499 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -183,6 +183,12 @@ renderer-facing status):
missing sessions row is restored from the live transcript (or created as a
stub) before those appends apply; deleting a session drops its outbox
entries (D318).
+- Before replacing or activating a session transcript, Electron main fences
+ persistence callbacks for that session and drains appends already queued for
+ the old transcript. If the rewrite succeeds, events from turns that existed
+ before the fence are discarded, including callbacks delivered while the
+ rewrite was running. If the rewrite fails, callbacks buffered by the fence
+ are replayed against the unchanged transcript.
- Host-core's stdin/stdout control path uses one dedicated OS thread per
direction rather than Tokio's dynamic blocking pool. Transient pipe resource
errors are retried; control-thread creation failures are surfaced as a boot
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index a6bfb9f2e..17997e036 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -403,6 +403,23 @@
session IPC contract tests, and real-model desktop acceptance. A local model
fixture or mocked component result is not real-model acceptance evidence.
+### E2E-CHAT-transcript-rewrite-late-events
+
+- **Preconditions:** Isolated session with at least one completed turn and a
+ persistence callback from that turn held until transcript replacement or
+ revision activation begins.
+- **Steps:** Start either transcript replacement or revision activation. Deliver
+ the held old-turn event after the persistence outbox has drained but before
+ the Host rewrite completes. Complete the rewrite, then start a new turn and
+ persist one event. Repeat with the Host rewrite returning an error.
+- **Expected:** A successful rewrite does not append the old-turn event to the
+ rewritten transcript, while the new turn persists normally. A failed rewrite
+ replays the buffered event into the unchanged transcript. Both rewrite
+ entrances use the same fence and outbox drain.
+- **Coverage:** `session-turn-ended.test.mjs` exercises the event persistence
+ fence and rollback with deterministic event delivery; session IPC contract
+ tests assert the fence/drain/rewrite ordering. No live provider is required.
+
### E2E-WORKTREE-isolated-session-lifecycle
- **Preconditions:** Isolated desktop profile and data directory, git 2.29+, a