Skip to content

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

fix(sessions): keep selectSession from reverting edits made during its detail read

liuzixiang951a1ad780b4
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index 2811ca30c..84afa813e 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -531,6 +531,7 @@ export function createSessionSlice({
);
}
+ const cacheBeforeDetailRead = runtime.sessionTranscriptCache.get(id);
detail ??= await detailPromise;
if (!runtime.navigationIntentIsCurrent(intent)) return;
if (detail.session && sessionReadLooksEmpty(detail.session)) {
@@ -567,6 +568,17 @@ export function createSessionSlice({
}
: { messageStart: 0, hasMoreBefore: false };
const currentState = get();
+ // An idle-session edit (message delete, revision switch) that landed
+ // while the bounded read above was in flight replaces the transcript
+ // cache entry; committing the stale window now would revert that edit
+ // on screen. #2233 taught loadSessionDetail itself to refuse caching
+ // such a read — the caller-level cache write and commit need the same
+ // guard.
+ const transcriptMovedWhileReading =
+ cacheBeforeDetailRead !== undefined &&
+ runtime.sessionTranscriptCache.get(id) !== cacheBeforeDetailRead &&
+ !runtime.liveSessionTranscripts.has(id) &&
+ currentState.runningSessions[id] !== true;
const liveMessages =
(runningAtSelection ||
currentState.runningSessions[id] === true ||
@@ -581,6 +593,11 @@ export function createSessionSlice({
? mergeLiveSessionMessages(detail.session.messages ?? [], liveMessages)
: detail.session.messages ?? []
: liveMessages ?? [];
+ const committedMessages = transcriptMovedWhileReading
+ ? runtime.sessionTranscriptCache.get(id)
+ ?? currentState.retainedTranscripts[id]
+ ?? selectedMessages
+ : selectedMessages;
if (detail.session) {
if (isRemoteSession(detail.session)) {
const { messages: _messages, ...summary } = detail.session;
@@ -588,9 +605,15 @@ export function createSessionSlice({
safeSessionSummary(summary), ...state.sessions.filter((session) => session.id !== id),
], state.sessionMeta) }));
}
- runtime.cacheSessionTranscript(id, selectedMessages, historyWindow);
+ if (!transcriptMovedWhileReading) {
+ runtime.cacheSessionTranscript(id, selectedMessages, historyWindow);
+ }
}
- commitSelection(selectedMessages, false, historyWindow);
+ commitSelection(
+ committedMessages,
+ false,
+ transcriptMovedWhileReading ? undefined : historyWindow,
+ );
if (
currentState.runningSessions[id] !== true &&
durableCoversLiveSessionMessages(detail.session?.messages ?? [], liveMessages)
@@ -611,7 +634,7 @@ export function createSessionSlice({
) {
const pin = pinnedSessionModelBinding({
session: selected,
- messages: selectedMessages,
+ messages: committedMessages,
settings: get().settings,
providers: get().providers,
recentModels: get().recentModels,
diff --git a/apps/desktop/test/session-select-stale-read.test.mjs b/apps/desktop/test/session-select-stale-read.test.mjs
new file mode 100644
index 000000000..6643aae60
--- /dev/null
+++ b/apps/desktop/test/session-select-stale-read.test.mjs
@@ -0,0 +1,98 @@
+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 { createSessionSlice } = await import("../src/stores/slices/session-slice.ts");
+const { createSessionCoordination } = await import("../src/stores/runtime/session-coordination.ts");
+const { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");
+const { api } = await import("../src/lib/api.ts");
+const { withoutRecordKey } = await import("../src/stores/helpers/store-helpers.ts");
+
+function buildStore() {
+ let state = {
+ activeSessionId: "session",
+ sessions: [{ id: "session", mode: "agent" }],
+ runningSessions: {},
+ pendingPlans: {},
+ sessionMeta: {},
+ planningStates: {},
+ retainedTranscripts: {},
+ retainedSessionIds: [],
+ sessionHistory: {},
+ navStack: [],
+ navIndex: -1,
+ settings: {},
+ providers: [],
+ recentModels: [],
+ messages: [],
+ acknowledgeSessionOutcome: () => Promise.resolve(),
+ restorePendingPlan: () => {},
+ restorePendingInteractive: () => {},
+ showToast: () => {},
+ };
+ const access = {
+ get: () => state,
+ set: patch => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },
+ };
+ const runtime = createSessionRuntime(access);
+ const coordination = createSessionCoordination({ ...access, runtime, withoutRecordKey });
+ const slice = createSessionSlice({ ...access, runtime, ...coordination });
+ return { stateRef: () => state, runtime, slice };
+}
+
+test("a warm re-select does not commit a detail window a concurrent idle edit superseded", async t => {
+ const stored = { id: "answer", role: "assistant", content: "before edit" };
+ const edited = [{ ...stored, content: "after edit" }];
+ const { stateRef, runtime, slice } = buildStore();
+ runtime.cacheSessionTranscript("session", [stored], { messageStart: 0, hasMoreBefore: false });
+ let finish;
+ t.mock.method(api, "getSession", () => new Promise(resolve => { finish = resolve; }));
+ const selecting = slice.selectSession("session");
+ await new Promise(resolve => setImmediate(resolve));
+ // The idle edit writers (deleteMessage / activateMessageRevision) replace
+ // the cache entry and the visible transcript while the read is in flight.
+ runtime.cacheSessionTranscript("session", edited, { messageStart: 0, hasMoreBefore: false });
+ stateRef().messages = edited;
+ finish({ session: { id: "session", messages: [stored], messageStart: 0, hasMoreBefore: false } });
+ await selecting;
+ assert.equal(runtime.sessionTranscriptCache.get("session"), edited, "the newer edit cache survives");
+ assert.equal(stateRef().messages, edited, "the visible transcript keeps the edit");
+ assert.deepEqual(stateRef().sessionHistory.session, { messageStart: 0, hasMoreBefore: false },
+ "the window stays the edit writer's, not the stale read's");
+ assert.equal(stateRef().selectingSessionId, undefined, "the selection still completes");
+});
+
+test("an uneventful warm re-select still hydrates the read window", async t => {
+ const saved = { id: "answer", role: "assistant", content: "saved answer" };
+ const { stateRef, runtime, slice } = buildStore();
+ t.mock.method(api, "getSession", async () => ({
+ session: { id: "session", messages: [saved], messageStart: 5, hasMoreBefore: true },
+ }));
+ await slice.selectSession("session");
+ assert.deepEqual(stateRef().messages, [saved]);
+ assert.deepEqual(runtime.sessionTranscriptCache.get("session"), [saved]);
+ assert.deepEqual(stateRef().sessionHistory.session,
+ { messageStart: 5, hasMoreBefore: true, contentLimited: true });
+ assert.equal(stateRef().selectingSessionId, undefined);
+});
+
+test("a running session still merges its live tail over the detail window", async t => {
+ const saved = { id: "prompt", role: "user", content: "question" };
+ const streamed = { id: "live", role: "assistant", content: "partial", status: "streaming" };
+ const { stateRef, runtime, slice } = buildStore();
+ stateRef().runningSessions.session = true;
+ runtime.cacheSessionTranscript("session", [saved, streamed], { messageStart: 0, hasMoreBefore: false });
+ let finish;
+ t.mock.method(api, "getSession", () => new Promise(resolve => { finish = resolve; }));
+ const selecting = slice.selectSession("session");
+ await new Promise(resolve => setImmediate(resolve));
+ const tailed = [saved, streamed, { id: "tail", role: "assistant", content: "more" }];
+ // Streaming events land in the store projection first; the cache boundary
+ // mirrors them (syncTranscriptProjection).
+ stateRef().messages = tailed;
+ runtime.cacheSessionTranscript("session", tailed, { messageStart: 0, hasMoreBefore: false });
+ finish({ session: { id: "session", messages: [saved] } });
+ await selecting;
+ assert.equal(runtime.sessionTranscriptCache.get("session").length, 3, "the live tail survives for running sessions");
+ assert.equal(stateRef().messages.length, 3);
+});
diff --git a/apps/desktop/test/session-switch-performance.test.mjs b/apps/desktop/test/session-switch-performance.test.mjs
index 0e309bde3..8c9bcb678 100644
--- a/apps/desktop/test/session-switch-performance.test.mjs
+++ b/apps/desktop/test/session-switch-performance.test.mjs
@@ -73,9 +73,13 @@ test("only the latest navigation may commit a loaded transcript", () => {
)?.[0] ?? "";
assert.match(selection, /set\(\{ selectingSessionId: id, page: "chat" \}\)/);
assert.match(selection, /navigationIntentIsCurrent\(intent\)/);
+ // The final commit carries the loaded detail window — unless a concurrent
+ // idle edit superseded the read while it was in flight, in which case the
+ // commit keeps the edit writer's cache content and cached window instead.
+ assert.match(selection, /commitSelection\(\s*committedMessages,/);
assert.match(
selection,
- /commitSelection\(selectedMessages, false, historyWindow\)/,
+ /transcriptMovedWhileReading \? undefined : historyWindow/,
);
assert.ok(
selection.indexOf("const detailPromise = runtime.loadSessionDetail(id)") <