Skip to content

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

fix(session): restore running state when the window reopens (#1915)

FuYukiHea0289edb0b3
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index 31cc924cd..e26f99650 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -215,6 +215,7 @@ export function registerSessionIpc({
: { sessions: [] as RuntimeSession[] };
return {
...result,
+ runningSessionIds: [...activeTurns.keys()],
sessions: [
...result.sessions.map((session) => ({
...enrichSession(session, providers, defaults),
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index eeb901160..c7bb9fa05 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -726,7 +726,7 @@ export const api = {
bootId?: string;
}) => invoke<{ ok: boolean }>(IPC.invoke.pluginSessionActive, input),
listSessions: () =>
- invoke<{ sessions: SessionSummary[] }>(IPC.invoke.sessionList).then((result) => ({
+ invoke<{ sessions: SessionSummary[]; runningSessionIds?: string[] }>(IPC.invoke.sessionList).then((result) => ({
...result,
sessions: result.sessions.map(normalizeSession),
})),
diff --git a/apps/desktop/src/stores/app-store.ts b/apps/desktop/src/stores/app-store.ts
index e29e77143..4a998e7ae 100644
--- a/apps/desktop/src/stores/app-store.ts
+++ b/apps/desktop/src/stores/app-store.ts
@@ -363,12 +363,17 @@ export const useAppStore = create<AppState>((set, get) => {
planningStates[proposal.sessionId] = "awaiting_approval";
}
if (generation !== bootstrapGeneration) return;
- set({
+ set((state) => ({
ready: true,
version,
healthOk: health.ok,
settings,
sessions: hydratedSessions,
+ runningSessions: {
+ ...Object.fromEntries((sessions.runningSessionIds ?? []).map((id) => [id, true])),
+ // Live start/end events received during bootstrap outrank its snapshot.
+ ...state.runningSessions,
+ },
providers: providers.providers,
providerModels: cachedProviderModels,
workspace: currentWorkspace,
@@ -383,7 +388,7 @@ export const useAppStore = create<AppState>((set, get) => {
notifications: notifications.notifications,
unreadNotificationCount: notifications.unreadCount,
sessionOutcomes: latestSessionOutcomes(notifications.notifications),
- });
+ }));
// The artifact's surface depends on which plugin views are launchable, and
// the launcher list is only read after `ready`. Resolve it before the
diff --git a/apps/desktop/test/helpers/session-running-fixture.mjs b/apps/desktop/test/helpers/session-running-fixture.mjs
new file mode 100644
index 000000000..93a46a337
--- /dev/null
+++ b/apps/desktop/test/helpers/session-running-fixture.mjs
@@ -0,0 +1,32 @@
+/** Host responses for a fresh renderer while a Desktop turn remains alive. */
+export function seedRunningSessionApi(api, protocolVersion, runningSessionIds = ["running"]) {
+ const sessions = ["running", "idle"].map((id) => ({
+ id, title: id, source: "desktop", mode: "agent", permissionMode: "inherit",
+ providerId: "provider", modelId: "model", thinkingLevel: "off", messageCount: 1,
+ createdAt: "2026-10-27T00:00:00Z", updatedAt: "2026-10-27T00:00:00Z",
+ }));
+ const snapshot = { sessions, ...(runningSessionIds ? { runningSessionIds } : {}) };
+ Object.assign(api, {
+ getSettings: async () => ({ defaultMode: "agent" }),
+ getVersion: async () => ({ protocolVersion }),
+ health: async () => ({ ok: true }),
+ listSessions: async () => snapshot,
+ listProviders: async () => ({ providers: [] }),
+ getProject: async () => ({ workspace: null }),
+ getOnboarding: async () => ({}),
+ listPlugins: async () => ({ plugins: [] }),
+ listNotifications: async () => ({ notifications: [{
+ id: "old-completion", sessionId: "running", kind: "task.completed",
+ createdAt: "2026-10-26T00:00:00Z", readAt: null,
+ }], unreadCount: 1 }),
+ pendingPlans: async () => ({ plans: [] }),
+ listPluginViews: async () => [],
+ listQueuedPrompts: async () => ({ entries: [] }),
+ pendingInteractive: async () => ({ permissions: [], asks: [] }),
+ markNotificationRead: async () => ({}),
+ getSession: async (id) => ({ session: { ...sessions.find((item) => item.id === id),
+ messages: [{ id: "answer", role: "assistant", content: "Working", createdAt: "2026-10-27T00:00:00Z" }],
+ } }),
+ });
+ return snapshot;
+}
diff --git a/apps/desktop/test/session-list-runtime.test.mjs b/apps/desktop/test/session-list-runtime.test.mjs
new file mode 100644
index 000000000..d40c17988
--- /dev/null
+++ b/apps/desktop/test/session-list-runtime.test.mjs
@@ -0,0 +1,55 @@
+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 { IPC } from "../../../packages/shared/src/protocol.ts";
+import { localNativeProjectPaths } from "../electron/main/services/session-search.ts";
+
+const source = fs.readFileSync(new URL("../electron/main/ipc/session-ipc.ts", import.meta.url), "utf8");
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+});
+const imports = {
+ electron: { shell: {} },
+ "node:fs": fs,
+ "node:path": path,
+ "@pi-desktop/shared": { IPC },
+ "../importers": {},
+ "../services/session-collaboration": {},
+ "../services/session-search": { localNativeProjectPaths },
+ "../bootstrap/remote-hosts.js": { getActiveRemoteHostsBoot: () => null },
+};
+const loaded = { exports: {} };
+new Function("require", "exports", "module", outputText)((id) => {
+ assert.ok(Object.hasOwn(imports, id), `unexpected dependency: ${id}`);
+ return imports[id];
+}, loaded.exports, loaded);
+
+// #1912: durable history alone cannot tell a new renderer which turns are live.
+test("session listing returns the current host-owned running IDs after its reads settle", async () => {
+ const handlers = new Map();
+ const activeTurns = new Map([["completed-during-read", "turn-old"]]);
+ let finishListing;
+ const host = { call: async (method) => {
+ if (method === "projects.list") return { projects: [] };
+ assert.equal(method, "session.list");
+ return new Promise((resolve) => { finishListing = resolve; });
+ } };
+ loaded.exports.registerSessionIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => host,
+ getSidecar: () => null,
+ activeTurns,
+ sessionCapabilityContext: async () => ({ providers: [], defaults: {} }),
+ enrichSession: (session) => session,
+ });
+ const pending = handlers.get(IPC.invoke.sessionList)();
+ activeTurns.delete("completed-during-read");
+ activeTurns.set("still-running", "turn-current");
+ finishListing({ sessions: [{ id: "still-running", updatedAt: "2026-10-27T00:00:00Z" }] });
+ const result = await pending;
+ assert.deepEqual(result.runningSessionIds, ["still-running"]);
+ activeTurns.clear();
+ assert.deepEqual(result.runningSessionIds, ["still-running"], "the result must be a detached snapshot");
+});
diff --git a/apps/desktop/test/session-running-bootstrap.test.mjs b/apps/desktop/test/session-running-bootstrap.test.mjs
new file mode 100644
index 000000000..54b8bc54c
--- /dev/null
+++ b/apps/desktop/test/session-running-bootstrap.test.mjs
@@ -0,0 +1,91 @@
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, test } from "node:test";
+import { fileURLToPath } from "node:url";
+import { build } from "esbuild";
+import { seedRunningSessionApi } from "./helpers/session-running-fixture.mjs";
+
+const root = fileURLToPath(new URL("../../../", import.meta.url));
+const temp = await mkdtemp(join(tmpdir(), "pi-running-bootstrap-"));
+const entry = join(temp, "store.cjs");
+await build({
+ stdin: {
+ contents: `
+ export { useAppStore } from "./src/stores/app-store";
+ export { api } from "./src/lib/api";
+ export { sidebarSessionStatus } from "./src/lib/sidebar-session-status";
+ export { PROTOCOL_VERSION } from "@pi-desktop/shared";
+ `,
+ resolveDir: join(root, "apps/desktop"),
+ loader: "ts",
+ },
+ outfile: entry,
+ bundle: true,
+ platform: "node",
+ format: "cjs",
+ jsx: "automatic",
+ define: { "import.meta.env.DEV": "false" },
+});
+after(() => rm(temp, { recursive: true, force: true }));
+
+const require = createRequire(import.meta.url);
+function harness(runningSessionIds = ["running"]) {
+ delete require.cache[entry];
+ const { useAppStore, api, sidebarSessionStatus, PROTOCOL_VERSION } = require(entry);
+ const snapshot = seedRunningSessionApi(api, PROTOCOL_VERSION, runningSessionIds);
+ return { useAppStore, api, snapshot, sidebarSessionStatus };
+}
+
+// #1912: a new renderer missed agent_start while the host kept the turn alive.
+test("reopening restores running badges and the selected session before another agent event", async () => {
+ const h = harness();
+ await h.useAppStore.getState().bootstrap();
+ const state = h.useAppStore.getState();
+ assert.equal(state.healthOk, true, state.error);
+ assert.equal(state.runningSessions.running, true);
+ assert.notEqual(state.runningSessions.idle, true);
+ assert.equal(h.sidebarSessionStatus({
+ running: state.runningSessions.running, selected: false, outcome: state.sessionOutcomes.running,
+ }), "running");
+ await state.selectSession("running");
+ assert.equal(h.useAppStore.getState().isRunning, true);
+});
+
+test("a completion arriving during bootstrap wins over the earlier running snapshot", async () => {
+ const h = harness();
+ let release;
+ h.api.listSessions = () => new Promise((resolve) => { release = resolve; });
+ const pending = h.useAppStore.getState().bootstrap();
+ const first = release;
+ h.api.listSessions = async () => h.snapshot;
+ h.useAppStore.getState().handleAgentEvent({
+ sessionId: "running", ts: 1, event: { type: "agent_end" },
+ });
+ first(h.snapshot);
+ await pending;
+ assert.equal(h.useAppStore.getState().runningSessions.running, false);
+});
+
+test("a new live run is retained when the bootstrap snapshot did not contain it", async () => {
+ const h = harness([]);
+ let release;
+ h.api.listSessions = () => new Promise((resolve) => { release = resolve; });
+ const pending = h.useAppStore.getState().bootstrap();
+ h.useAppStore.getState().handleAgentEvent({
+ sessionId: "running", ts: 1, event: { type: "agent_start" },
+ });
+ release(h.snapshot);
+ await pending;
+ assert.equal(h.useAppStore.getState().runningSessions.running, true);
+});
+
+test("a session list without a running snapshot remains compatible", async () => {
+ const h = harness(null);
+ h.useAppStore.setState({ runningSessions: {} });
+ await h.useAppStore.getState().bootstrap();
+ assert.equal(h.useAppStore.getState().healthOk, true);
+ assert.deepEqual(h.useAppStore.getState().runningSessions, {});
+});
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 2035a0a20..f92d539ce 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -2507,6 +2507,13 @@ startup failure is logged and does not prevent the desktop from launching.
## Native Pi session routing (ADR 0254)
+The Electron `pi-desktop/session/list` response also includes
+`runningSessionIds`, a snapshot of the Desktop turns still owned by Main after
+the list reads settle. A recreated renderer restores these running flags during
+bootstrap; start/end events already received by that renderer take precedence.
+An older response without this field remains valid. Historical completion
+notifications are not evidence that a currently active turn has finished.
+
`pi-desktop/session/list` returns both Desktop and native summaries. Each summary
may carry `source: "desktop" | "pi-native"`, capability flags, and a stable
`readOnlyReason`; clients normalize omitted source to `desktop` for backward
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 0e0c8e1b7..aa5f00a70 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6780,6 +6780,23 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
- **Specs linked**: `04-ux/07-ui-design-system.md` §8, `04-ux/02-i18n-english-first.md`, decisions-log D146 / D304 / D348
- **Acceptance**: A (app startup), Quality
- **Milestone**: M5
+
+#### E2E-SESSION-reopen-restores-running: Recreated windows retain live turn status
+
+- **Steps**: Start a Desktop turn in a session with an older completion
+ notification. Close and recreate its renderer while Main keeps the turn
+ alive. Inspect the sidebar and select the session before another agent event.
+ Repeat after the turn ends, and with a start/end event arriving during bootstrap.
+- **Expected**: Live tasks show running, and selecting one restores the running
+ composer state. Completed tasks stay idle. A delayed snapshot never overrides
+ a start/end event already received by the new renderer.
+- **Automation**: `node scripts/e2e-running-session-reopen.mjs` recreates real
+ Electron windows with the production bootstrap, Sidebar and selection flow,
+ using fixture backend responses. `session-list-runtime.test.mjs` checks the
+ Main snapshot; `session-running-bootstrap.test.mjs` covers event races and
+ responses from older hosts. The native macOS close gesture remains a manual check.
+- **Specs**: `03-runtime/01-ipc-protocol.md`, ADR 0090.
+
#### E2E-099: Brand logo follows the active theme
- **Status**: Draft
- **Priority**: P3
diff --git a/scripts/e2e-running-session-reopen.mjs b/scripts/e2e-running-session-reopen.mjs
new file mode 100644
index 000000000..a7701450f
--- /dev/null
+++ b/scripts/e2e-running-session-reopen.mjs
@@ -0,0 +1,110 @@
+/** #1912: a recreated Electron renderer restores live sidebar/session state. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { build } from "esbuild";
+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = repositoryRoot();
+const temp = await mkdtemp(join(tmpdir(), "pi-running-reopen-"));
+try {
+ await build({
+ stdin: { resolveDir: root, loader: "tsx", contents: `
+ import { createRoot } from "react-dom/client";
+ import { flushSync } from "react-dom";
+ import i18n from "i18next";
+ import { initReactI18next } from "react-i18next";
+ import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+ import { PROTOCOL_VERSION } from "@pi-desktop/shared";
+ import { Sidebar } from "./apps/desktop/src/components/Sidebar";
+ import { useAppStore } from "./apps/desktop/src/stores/app-store";
+ import { api } from "./apps/desktop/src/lib/api";
+ import { seedRunningSessionApi } from "./apps/desktop/test/helpers/session-running-fixture.mjs";
+ await i18n.use(initReactI18next).init({ lng: "en", fallbackLng: "en",
+ resources: { en: { translation: flattenCatalog(catalogs.en) } },
+ interpolation: { escapeValue: false } });
+ const noop = () => {};
+ const reactRoot = createRoot(document.getElementById("root"));
+ window.runningSessionProbe = async (runningSessionIds) => {
+ seedRunningSessionApi(api, PROTOCOL_VERSION, runningSessionIds);
+ api.updatesGetState = async () => null;
+ api.onUpdateState = () => noop;
+ await useAppStore.getState().bootstrap();
+ if (!useAppStore.getState().healthOk) throw new Error(useAppStore.getState().error);
+ flushSync(() => reactRoot.render(<Sidebar onToggleSidebar={noop} sidebarToggleShortcut=""
+ sidebarWidth={260} onWidthChange={noop} onWidthCommit={noop} onResizeCollapse={noop} />));
+ const row = document.querySelector('[data-sidebar-session-row="running"]');
+ if (!row) throw new Error("the restored session is missing from the sidebar");
+ const badge = row.querySelector(".thread-item-status");
+ const running = badge?.classList.contains("running") === true;
+ const completed = badge?.classList.contains("completed") === true;
+ row.querySelector(".thread-item-main").click();
+ for (let frame = 0; frame < 120 && useAppStore.getState().activeSessionId !== "running"; frame++) {
+ await new Promise(requestAnimationFrame);
+ }
+ const state = useAppStore.getState();
+ return { running, completed, active: state.activeSessionId, isRunning: state.isRunning };
+ };
+ ` },
+ outfile: join(temp, "renderer.js"),
+ bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },
+ loader: { ".png": "dataurl", ".gif": "dataurl", ".svg": "dataurl" },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><div id="root"></div><script type="module" src="renderer.js"></script>');
+ await writeFile(join(temp, "main.cjs"), `
+ const { app, BrowserWindow } = require("electron");
+ const path = require("node:path");
+ app.setPath("userData", path.join(__dirname, "profile"));
+ app.on("window-all-closed", () => {});
+ app.whenReady().then(async () => {
+ try {
+ const results = [];
+ for (const runningIds of [["running"], ["running"], []]) {
+ const window = new BrowserWindow({ show: false, width: 900, height: 700,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false,
+ backgroundThrottling: false, offscreen: process.platform === "win32" } });
+ window.webContents.on("console-message", (event) => console.error(event.message));
+ await window.loadFile(path.join(__dirname, "index.html"));
+ results.push(await window.webContents.executeJavaScript(
+ "window.runningSessionProbe(" + JSON.stringify(runningIds) + ")"));
+ window.destroy();
+ }
+ console.log("RUNNING_REOPEN_PROBE " + JSON.stringify(results));
+ app.exit(0);
+ } catch (error) { console.error(error.stack || error); app.exit(1); }
+ });
+ `);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {
+ env, stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally { clearTimeout(timer); }
+ assert.equal(code, 0, output.slice(-6000));
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("RUNNING_REOPEN_PROBE "));
+ assert.ok(line, output.slice(-6000));
+ const results = JSON.parse(line.slice("RUNNING_REOPEN_PROBE ".length));
+ assert.deepEqual(results, [true, true, false].map((running) => ({
+ running, completed: !running, active: "running", isRunning: running,
+ })));
+ console.log("RUNNING_REOPEN_PROBE " + JSON.stringify({ passed: true, results }));
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}