Skip to content

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

fix(session-ipc): refuse to delete a session with a running turn

liuzixiangf75d2c27e540
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index 4b8b3197c..dbff216ed 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -426,21 +426,36 @@ 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) {
- sidecar.clearProjectInstructionRoot(id);
- sidecar.clearVendorAuthBindings(id);
- await sidecar
- .call("agent.disposeSession", { sessionId: id })
- .catch(() => undefined);
+ // Same contract as session.moveProject: hold the session operation while
+ // deleting so a queued prompt cannot begin a turn between the check and
+ // the host call. The running check happens only after acquiring — a
+ // prompt holding the operation registers its turn and releases it, and
+ // the delete must still refuse that turn (issue #2291).
+ const releaseSessionOperation = await acquireSessionOperation(id);
+ try {
+ if (activeTurns.has(id)) {
+ throw Object.assign(new Error("Cannot delete a running session"), {
+ errorCode: ErrorCodes.AGENT_BUSY,
+ });
+ }
+ 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) {
+ sidecar.clearProjectInstructionRoot(id);
+ sidecar.clearVendorAuthBindings(id);
+ await sidecar
+ .call("agent.disposeSession", { sessionId: id })
+ .catch(() => undefined);
+ }
+ sessionProjects.delete(id);
+ logger.app("session", "info", "session deleted", { sessionId: id });
+ return res;
+ } finally {
+ releaseSessionOperation();
}
- sessionProjects.delete(id);
- logger.app("session", "info", "session deleted", { sessionId: id });
- return res;
});
handle(IPC.invoke.sessionRename, async (id: string, title: string) => {
if (id.startsWith("native-pi:")) {
diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsx
index 95a9d6320..d0c481a6e 100644
--- a/apps/desktop/src/components/Sidebar.tsx
+++ b/apps/desktop/src/components/Sidebar.tsx
@@ -1341,6 +1341,13 @@ export function Sidebar({
const deleteSession = async (session: SessionSummary) => {
closeMenus();
+ // Same pre-check as the project-move entry: deleting a running session
+ // cascades its live rows away, so the row menu stops here with a
+ // translated notice and the main-side guard remains the race backstop.
+ if (runningSessions[session.id]) {
+ showToast(t("nav.deleteRunningSessionBlocked"), { variant: "warning" });
+ return;
+ }
const wasActive = activeSessionId === session.id;
const sameScope = session.projectPath
? projectEntries.find(
@@ -1394,6 +1401,10 @@ export function Sidebar({
(s) => ids.includes(s.id) && s.source !== "pi-native",
);
for (const session of toDelete) {
+ if (runningSessions[session.id]) {
+ showToast(t("nav.deleteRunningSessionBlocked"), { variant: "warning" });
+ continue;
+ }
try {
await deleteSessionAction(session.id);
} catch (error) {
diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.ts
index 119515042..6cb23b786 100644
--- a/apps/desktop/src/stores/slices/project-slice.ts
+++ b/apps/desktop/src/stores/slices/project-slice.ts
@@ -589,7 +589,18 @@ export function createProjectSlice({
deleteSession: async (id) => {
if (!id) return;
- await api.deleteSession(id);
+ try {
+ await api.deleteSession(id);
+ } catch (error) {
+ // The main-side running guard is the backstop for races the sidebar's
+ // pre-check cannot see (issue #2291); surface it translated instead
+ // of the raw IPC error.
+ if (error instanceof Error && error.message.includes("Cannot delete a running session")) {
+ get().showToast(i18n.t("nav.deleteRunningSessionBlocked"), { variant: "warning" });
+ return;
+ }
+ throw error;
+ }
void api.pluginViewClose("pi.browser", "browser", { sessionId: id })
.catch((error) => get().showToast(String(error), { variant: "error" }));
clearLocalSessionState({ get, set, runtime, withoutRecordKey }, id);
diff --git a/apps/desktop/test/session-delete-running-guard.test.mjs b/apps/desktop/test/session-delete-running-guard.test.mjs
new file mode 100644
index 000000000..74c66b3f0
--- /dev/null
+++ b/apps/desktop/test/session-delete-running-guard.test.mjs
@@ -0,0 +1,171 @@
+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 { ErrorCodes } from "../../../packages/shared/src/errors.ts";
+import { IPC } from "../../../packages/shared/src/protocol.ts";
+
+function load(relative, imports) {
+ const file = new URL(relative, import.meta.url);
+ const { outputText } = ts.transpileModule(fs.readFileSync(file, "utf8"), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ fileName: path.resolve(file.pathname),
+ });
+ const module = { exports: {} };
+ new Function("require", "exports", "module", outputText)((id) => {
+ assert.ok(Object.hasOwn(imports, id), `unexpected dependency: ${id}`);
+ return imports[id];
+ }, module.exports, module);
+ return module.exports;
+}
+
+/** The production promise-tail session operation, same semantics. */
+function createSessionOperations() {
+ const tails = new Map();
+ return async function acquireSessionOperation(sessionId) {
+ const id = sessionId.trim();
+ const previous = tails.get(id) ?? Promise.resolve();
+ let resolveCurrent;
+ const current = new Promise((resolve) => { resolveCurrent = resolve; });
+ const tail = previous.then(() => current);
+ tails.set(id, tail);
+ await previous;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ resolveCurrent();
+ if (tails.get(id) === tail) tails.delete(id);
+ };
+ };
+}
+
+function buildHarness({ hostCall, sidecarCall }) {
+ const handlers = new Map();
+ const acquireSessionOperation = createSessionOperations();
+ const activeTurns = new Map();
+ const dropped = [];
+ const host = { call: (method, input) => hostCall(method, input) };
+ const sidecar = sidecarCall
+ ? { call: (method, input) => sidecarCall(method, input), clearProjectInstructionRoot() {}, clearVendorAuthBindings() {} }
+ : null;
+ 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": { getActiveRemoteHostsBoot: () => null },
+ "../services/session-search": {
+ searchSessionsAcrossSources: async () => ({ hits: [], nextOffset: null }),
+ },
+ });
+ registerSessionIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => host,
+ getSidecar: () => sidecar,
+ dataDir: "data-dir",
+ activeTurns,
+ sessionProjects: new Map(),
+ persistenceOutbox: { dropSession: async (id) => dropped.push(id) },
+ logger: { app() {} },
+ plugins: { broadcastEvent() {} },
+ sessionCapabilityContext: async () => ({ providers: [], defaults: {} }),
+ enrichSession: (session) => session,
+ acquireSessionOperation,
+ beginTranscriptRewrite: async () => async () => undefined,
+ forgetTranscriptRewriteHistory() {},
+ stripWinLongPrefix: (value) => value,
+ modeCatalog: {},
+ });
+ return { handlers, activeTurns, dropped, acquireSessionOperation };
+}
+
+const sessionDelete = (h, id) => h.handlers.get(IPC.invoke.sessionDelete)(id);
+
+test("a session with a registered turn refuses deletion before the host is called", async () => {
+ let deleteCalls = 0;
+ const h = buildHarness({
+ hostCall: async (method) => {
+ if (method === "session.delete") {
+ deleteCalls += 1;
+ return { deleted: true };
+ }
+ return {};
+ },
+ });
+ h.activeTurns.set("s1", "turn-1");
+ await assert.rejects(
+ sessionDelete(h, "s1"),
+ (error) => error.errorCode === ErrorCodes.AGENT_BUSY &&
+ /running session/.test(error.message),
+ );
+ assert.equal(deleteCalls, 0, "the host cascade never ran against a live turn");
+ assert.deepEqual(h.dropped, []);
+});
+
+test("a turn registered while a prompt held the operation is still refused", async () => {
+ // vastsa's repro: the prompt setup acquires the operation, registers its
+ // durable turn, and releases; a delete issued afterwards must still see
+ // the turn because the check now runs after acquiring.
+ let deleteCalls = 0;
+ const h = buildHarness({
+ hostCall: async (method) => {
+ if (method === "session.delete") {
+ deleteCalls += 1;
+ return { deleted: true };
+ }
+ return {};
+ },
+ });
+ // Simulate the prompt's setup window: hold the operation, register the
+ // turn, release.
+ const releasePromptOperation = await h.acquireSessionOperation("s1");
+ h.activeTurns.set("s1", "durable-turn");
+ releasePromptOperation();
+ await assert.rejects(
+ sessionDelete(h, "s1"),
+ (error) => error.errorCode === ErrorCodes.AGENT_BUSY,
+ );
+ assert.equal(deleteCalls, 0);
+});
+
+test("a delete holds the operation for its duration, so no turn can begin behind it", async () => {
+ let releaseHost;
+ let deleteCalls = 0;
+ const h = buildHarness({
+ hostCall: async (method) => {
+ if (method === "session.delete") {
+ deleteCalls += 1;
+ await new Promise((resolve) => { releaseHost = resolve; });
+ return { deleted: true };
+ }
+ return {};
+ },
+ });
+ const deleting = sessionDelete(h, "s1");
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(deleteCalls, 1, "the host call started while the operation is held");
+ assert.equal(typeof releaseHost, "function");
+ releaseHost();
+ const result = await deleting;
+ assert.deepEqual(result, { deleted: true });
+ assert.deepEqual(h.dropped, ["s1"], "the outbox drop follows the host cascade");
+});
+
+test("an idle session deletes cleanly and releases the operation", async () => {
+ const h = buildHarness({
+ hostCall: async (method) => (method === "session.delete" ? { deleted: true } : {}),
+ sidecarCall: async (method) => {
+ assert.equal(method, "agent.disposeSession");
+ return {};
+ },
+ });
+ const result = await sessionDelete(h, "s1");
+ assert.deepEqual(result, { deleted: true });
+ // The operation released: a second delete for another idle session works.
+ const second = await sessionDelete(h, "s2");
+ assert.deepEqual(second, { deleted: true });
+});
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 42a3ed5c9..6fa6ec862 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -271,6 +271,7 @@ export const de = {
"sortCreated": "Erstellungsdatum",
"sessionMoved": "Verschoben nach {{name}}",
"moveRunningSessionBlocked": "Beende zuerst die laufende Sitzung.",
+ "deleteRunningSessionBlocked": "Beenden Sie die laufende Sitzung, bevor Sie sie löschen.",
"moveSessionUnavailable": "Diese Sitzung kann nicht in dieses Projekt verschoben werden.",
"dropFolderToAddProject": "Ordner ablegen, um ihn als Projekt hinzuzufügen.",
"dismissFolderDrop": "Schließen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 1ae9d6cf3..9185afc25 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -278,6 +278,7 @@ export const en = {
sortCreated: "Created date",
sessionMoved: "Moved to {{name}}",
moveRunningSessionBlocked: "Stop the running session before moving it.",
+deleteRunningSessionBlocked: "Stop the running session before deleting it.",
moveSessionUnavailable: "This session cannot move to that project.",
dropFolderToAddProject: "Drop a folder to add it as a project.",
dismissFolderDrop: "Dismiss",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 29c7206b7..0e4c803a2 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -271,6 +271,7 @@ export const es = {
"sortCreated": "Fecha de creación",
"sessionMoved": "Movido a {{name}}",
"moveRunningSessionBlocked": "Detén la sesión en ejecución antes de moverla.",
+ "deleteRunningSessionBlocked": "Detén la sesión en ejecución antes de eliminarla.",
"moveSessionUnavailable": "Esta sesión no puede moverse a ese proyecto.",
"dropFolderToAddProject": "Suelta una carpeta para añadirla como proyecto.",
"dismissFolderDrop": "Cerrar",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 0bf83620e..62c17ecdf 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -271,6 +271,7 @@ export const fr = {
"sortCreated": "Date de création",
"sessionMoved": "Déplacé vers {{name}}",
"moveRunningSessionBlocked": "Arrêtez la session en cours avant de la déplacer.",
+ "deleteRunningSessionBlocked": "Arrêtez la session en cours avant de la supprimer.",
"moveSessionUnavailable": "Cette session ne peut pas être déplacée vers ce projet.",
"dropFolderToAddProject": "Déposez un dossier pour l'ajouter comme projet.",
"dismissFolderDrop": "Fermer",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 805ed2941..16c7e062a 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -280,6 +280,7 @@ export const ko = {
sortCreated: "생성일",
sessionMoved: "{{name}}(으)로 이동함",
moveRunningSessionBlocked: "이동하기 전에 실행 중인 세션을 중지하세요.",
+ deleteRunningSessionBlocked: "실행 중인 세션을 먼저 중지한 후 삭제하세요.",
moveSessionUnavailable: "이 세션은 해당 프로젝트로 이동할 수 없습니다.",
dropFolderToAddProject: "폴더를 놓으면 프로젝트로 추가됩니다.",
dismissFolderDrop: "닫기",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 46654830e..c3e88f509 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -270,6 +270,7 @@ export const ptBR = {
sortCreated: "Data de criação",
sessionMoved: "Movido para {{name}}",
moveRunningSessionBlocked: "Interrompa a sessão em execução antes de movê-la.",
+ deleteRunningSessionBlocked: "Encerre a sessão em execução antes de excluí-la.",
moveSessionUnavailable: "Esta sessão não pode ser movida para esse projeto.",
dropFolderToAddProject: "Solte uma pasta para adicioná-la como projeto.",
dismissFolderDrop: "Dispensar",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 9ed72c627..2f1fcf071 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -280,6 +280,7 @@ export const tr = {
sortCreated: "Oluşturma tarihi",
sessionMoved: "{{name}} konumuna taşındı",
moveRunningSessionBlocked: "Taşımadan önce çalışan oturumu durdurun.",
+ deleteRunningSessionBlocked: "Silmeden önce çalışan oturumu durdurun.",
moveSessionUnavailable: "Bu oturum o projeye taşınamaz.",
dropFolderToAddProject: "Proje olarak eklemek için bir klasör bırakın.",
dismissFolderDrop: "Kapat",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index aec05f14f..0e898aeea 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -273,6 +273,7 @@ export const zhCN = {
sortCreated: "创建时间",
sessionMoved: "已移动到 {{name}}",
moveRunningSessionBlocked: "请先停止运行中的会话,再移动它。",
+deleteRunningSessionBlocked: "请先停止运行中的会话,再删除它。",
moveSessionUnavailable: "该会话无法移动到目标项目。",
dropFolderToAddProject: "拖入文件夹即可添加为项目。",
dismissFolderDrop: "关闭",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index f778eb137..27dfa85c0 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -273,6 +273,7 @@ export const zhTW = {
sortCreated: "建立時間",
sessionMoved: "已移動到 {{name}}",
moveRunningSessionBlocked: "請先停止執行中的工作階段,再移動它。",
+deleteRunningSessionBlocked: "請先停止執行中的會話,再刪除它。",
moveSessionUnavailable: "此工作階段無法移動到目標專案。",
dropFolderToAddProject: "拖入資料夾即可新增為專案。",
dismissFolderDrop: "關閉",