Skip to content

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

fix(modes): claim persisted runs before catalog lookup

Linuxdazhao056ec3e4d29e
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 79787f693..a4078a8e2 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -1,6 +1,7 @@
import { expandMcpInvocation } from "../composer-mcp";
import { IPC, ErrorCodes, compactionRecordId, composeMentionPrompt, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AgentStopSubagentsRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type VoiceOrigin } from "@pi-desktop/shared";
import type { FinishTurn } from "../runtime/plans";
+import type { ModeDefinition } from "@pi-desktop/shared";
import { modeContinuationOrigin, type ModeRunCoordinator, type PreparedModeTurn } from "../runtime/mode-runs";
import { expandSlashInvocation, visionFromModelConfig, type ComposerTemplate } from "@pi-desktop/agent-runtime";
import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";
@@ -343,8 +344,6 @@ export function registerAgentIpc({
);
sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);
- const modeDefinition = await modeRuns.definitionForPrompt(launch.sidecarParams.mode ?? "agent");
-
// Open a durable turn row, then persist the user message under it.
const turn = await host.call<{ turnId?: string }>("session.beginTurn", {
sessionId: req.sessionId,
@@ -363,6 +362,7 @@ export function registerAgentIpc({
// A staged mode claims its run for this durable turn before anything runs;
// the sidecar then executes the run's own definition snapshot.
let preparedMode: PreparedModeTurn | undefined;
+ let modeDefinition: ModeDefinition | undefined;
try {
preparedMode = await modeRuns.prepareTurn({
sessionId: req.sessionId,
@@ -371,6 +371,7 @@ export function registerAgentIpc({
content: req.content,
origin: modeOrigin ?? "user",
});
+ modeDefinition = preparedMode?.definition ?? await modeRuns.definitionForPrompt(launch.sidecarParams.mode ?? "agent");
} catch (error) {
await finishTurn(req.sessionId, modeOrigin ? "aborted" : "error", (error as any)?.errorCode, {
turnId: durableTurnId,
diff --git a/apps/desktop/electron/main/runtime/mode-runs.ts b/apps/desktop/electron/main/runtime/mode-runs.ts
index 79c256663..84f4e6fa4 100644
--- a/apps/desktop/electron/main/runtime/mode-runs.ts
+++ b/apps/desktop/electron/main/runtime/mode-runs.ts
@@ -137,15 +137,20 @@ export function createModeRunCoordinator(deps: {
content: string;
origin: ModeTurnOrigin;
}): Promise<PreparedModeTurn | undefined> {
- const selected = await deps.catalog.definition(input.sessionMode);
- if (!selected || selected.stages.length === 0) {
+ if (isPlainMode(input.sessionMode)) {
if (input.origin !== "user") throw Object.assign(new Error("mode run is not staged"), { errorCode: "MODE_NOT_STAGED" });
return undefined;
}
const hostCaller = host();
const { run } = await hostCaller.call<ModeRunResult>("modes.get", { sessionId: input.sessionId });
+ let selected: ModeDefinition | undefined;
let claim: ModeClaimResult;
if (!run) {
+ selected = await deps.catalog.definition(input.sessionMode);
+ if (!selected || selected.stages.length === 0) {
+ if (input.origin !== "user") throw Object.assign(new Error("mode run is not staged"), { errorCode: "MODE_NOT_STAGED" });
+ return undefined;
+ }
if (input.origin !== "user") throw Object.assign(new Error("no open mode run"), { errorCode: "MODE_RUN_NOT_FOUND" });
claim = await hostCaller.call<ModeClaimResult>("modes.start", {
sessionId: input.sessionId,
@@ -169,10 +174,15 @@ export function createModeRunCoordinator(deps: {
return undefined;
}
turnRuns.set(input.turnId, { sessionId: input.sessionId, runId: claim.run.id });
+ const definition = claim.definition ?? selected;
+ if (!definition) {
+ await this.abandonTurn(input.sessionId, input.turnId);
+ throw Object.assign(new Error("Mode run snapshot is unavailable"), { errorCode: "MODE_NOT_FOUND" });
+ }
return {
// The run executes the snapshot it started with; editing the file
// during a run never changes it.
- definition: claim.definition ?? selected,
+ definition,
modeTurn: {
runId: claim.run.id,
stageId: claim.run.stageId,
diff --git a/apps/desktop/test/custom-mode-dispatch.test.mjs b/apps/desktop/test/custom-mode-dispatch.test.mjs
index c8071ed7f..fd84a26af 100644
--- a/apps/desktop/test/custom-mode-dispatch.test.mjs
+++ b/apps/desktop/test/custom-mode-dispatch.test.mjs
@@ -10,6 +10,7 @@ const { IPC } = await import("@pi-desktop/shared");
async function promptFixture({ unavailable = false, prepared } = {}) {
const handlers = new Map();
const prompts = [];
+ const finished = [];
const definition = {
version: 1, id: "review", label: "Review", description: "", source: "user",
permission: "contract", prompt: "Review without changing files.",
@@ -52,11 +53,11 @@ async function promptFixture({ unavailable = false, prepared } = {}) {
providerId: "fixture", modelId: "fixture",
sidecarParams: { sessionId: "s", mode: "review", provider: { modelConfig: { input: ["text"] } } },
}),
- finishTurn: async () => assert.fail("prompt admission failed"),
+ finishTurn: async (...args) => finished.push(args),
emitAgentEvent() {}, setNotificationViewingSessionId() {},
});
return {
- prompts, hostCalls, definition,
+ prompts, hostCalls, definition, finished,
prompt: () => handlers.get(IPC.invoke.agentPrompt)({ sessionId: "s", content: "Inspect the changes." }),
};
}
@@ -69,11 +70,12 @@ test("a simple custom mode reaches the sidecar with its instructions and policy"
assert.equal(prompts[0].modeTurn, undefined);
});
-test("an unavailable mode is rejected before creating a durable turn", async () => {
- const { prompt, prompts, hostCalls } = await promptFixture({ unavailable: true });
+test("an unavailable mode closes admission without persisting a message or calling the sidecar", async () => {
+ const { prompt, prompts, hostCalls, finished } = await promptFixture({ unavailable: true });
await assert.rejects(prompt, { errorCode: "MODE_NOT_FOUND" });
assert.equal(prompts.length, 0);
- assert.ok(!hostCalls.includes("session.beginTurn"));
+ assert.ok(!hostCalls.includes("session.appendMessage"));
+ assert.deepEqual(finished, [["s", "error", "MODE_NOT_FOUND", { turnId: "turn" }]]);
});
test("a staged run keeps its persisted snapshot over the current catalog", async () => {
@@ -85,6 +87,15 @@ test("a staged run keeps its persisted snapshot over the current catalog", async
assert.deepEqual(prompts[0].modeTurn, modeTurn);
});
+test("a staged run dispatches its persisted snapshot after its catalog entry is removed", async () => {
+ const definition = { id: "review", prompt: "Persisted stage instructions." };
+ const modeTurn = { runId: "run", stageId: "work", permission: "contract" };
+ const { prompt, prompts } = await promptFixture({ unavailable: true, prepared: { definition, modeTurn } });
+ await prompt();
+ assert.deepEqual(prompts[0].modeDefinition, definition);
+ assert.deepEqual(prompts[0].modeTurn, modeTurn);
+});
+
test("an inactive Plan projection preserves a custom or staged Goal mode", () => {
for (const mode of ["review", "goal"]) {
assert.equal(modeAfterPlanningUpdate(mode, "inactive", () => "agent"), mode);
diff --git a/apps/desktop/test/mode-runs-main.test.mjs b/apps/desktop/test/mode-runs-main.test.mjs
index cadcc20fd..e4b4ed8ee 100644
--- a/apps/desktop/test/mode-runs-main.test.mjs
+++ b/apps/desktop/test/mode-runs-main.test.mjs
@@ -118,7 +118,7 @@ test("a user turn in a simple mode claims nothing", async () => {
const { coordinator, calls } = fixture();
const prepared = await coordinator.prepareTurn({ sessionId: "s1", turnId: "t1", sessionMode: "review", content: "x", origin: "user" });
assert.equal(prepared, undefined);
- assert.equal(calls.length, 0);
+ assert.deepEqual(calls.map(call => call.method), ["modes.get"]);
});
test("the first user turn of a staged mode starts a run and carries the snapshot", async () => {
@@ -152,6 +152,20 @@ test("an open run is claimed with its revision, and a host turn without a run fa
);
});
+test("an open run keeps its snapshot when its catalog definition is removed or made simple", async () => {
+ for (const catalogModes of [[], ["review"]]) {
+ const snapshot = { ...staged, id: "review" };
+ const { coordinator, calls } = fixture({
+ open: run({ modeId: "review" }), catalogModes,
+ claim: { claimed: true, run: run({ modeId: "review" }), enteredStage: false, definition: snapshot },
+ });
+ const prepared = await coordinator.prepareTurn({ sessionId: "s1", turnId: "t2", sessionMode: "review", content: "more", origin: "host" });
+ assert.deepEqual(prepared.definition, snapshot);
+ assert.equal(prepared.modeTurn.runId, "run1");
+ assert.deepEqual(calls.map(call => call.method), ["modes.get", "modes.claimTurn"]);
+ }
+});
+
test("a rejected claim runs a user turn plainly but refuses a continuation", async () => {
const rejected = { claimed: false, run: null, enteredStage: false };
const { coordinator } = fixture({ open: run({ activeTurnId: "other" }), claim: rejected });
@@ -165,6 +179,19 @@ test("a rejected claim runs a user turn plainly but refuses a continuation", asy
);
});
+test("an accepted claim without its snapshot is abandoned instead of using an edited catalog", async () => {
+ const { coordinator, calls } = fixture({
+ open: run(), claim: { claimed: true, run: run(), enteredStage: false },
+ });
+ await assert.rejects(
+ coordinator.prepareTurn({ sessionId: "s1", turnId: "t2", sessionMode: "feature", content: "more", origin: "user" }),
+ { errorCode: "MODE_NOT_FOUND" },
+ );
+ assert.equal(coordinator.claimedTurns().size, 0);
+ assert.equal(calls.at(-1).method, "modes.settleTurn");
+ assert.equal(calls.at(-1).params.outcome, "aborted");
+});
+
test("settling a claimed turn reports tokens and starts the Host continuation", async () => {
const { coordinator, calls, continuations } = fixture({ settle: { run: run(), continue: true } });
await coordinator.prepareTurn({ sessionId: "s1", turnId: "t1", sessionMode: "feature", content: "x", origin: "user" });
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 1af49878c..7f5cda722 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -863,10 +863,12 @@ Builtins: Agent uses `agent`; Plan uses `contract`; Goal is a staged run whose
`work` stage uses `agent`. A legacy Goal session without a snapshot, and any
mode id the Host cannot resolve, falls back to `contract` (fail closed).
-Prompt admission resolves the selected mode from the main-process catalog before
-opening a durable turn. Simple custom modes carry that definition to the runtime;
-a staged run overrides it with the run's persisted snapshot. An unavailable mode
-is rejected before admission. Plan-state projection may rename only Agent/Plan
+Prompt admission first claims an existing staged run through the Host and uses
+its persisted snapshot without consulting the current catalog. Editing, removing,
+or making the catalog definition simple does not change an existing run.
+Without a claim, simple custom modes carry the current catalog definition to the
+runtime. An unavailable mode closes the admission turn without persisting a user
+message or invoking the sidecar. Plan-state projection may rename only Agent/Plan
sessions; an inactive projection preserves Goal and custom-mode identity.
New Goal/custom sessions persist the catalog snapshot before returning from
Desktop creation, including sessions created directly in the default mode.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 6af56bfba..6af178934 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20533,13 +20533,18 @@ session data is used.
Select a simple custom mode with a distinctive prompt and contract policy, send a
message, and refresh planning state. The runtime receives the selected definition
and the session retains its mode. Remove the definition before another send: reject
-before creating a turn. For a staged run, edit the catalog after starting; subsequent
-dispatch retains the run snapshot. Controlled coverage:
+without persisting a user message or invoking the sidecar; the admission turn is
+closed. For a staged run, edit the catalog into a simple mode and then remove it;
+subsequent dispatch retains the run snapshot in both cases. Controlled coverage:
`apps/desktop/test/custom-mode-dispatch.test.mjs`. Native Electron/provider
acceptance is separate from these stubbed Host/sidecar boundary checks.
Also create directly in Goal or a staged custom mode without switching modes:
the first send starts a run. `mode-session-create.test.mjs` checks the production
creation registrar persists its snapshot before returning.
+`scripts/e2e-mode-definitions.mjs` also exercises production prompt IPC and the
+coordinator against an isolated real Host, including edit/removal, durable claim
+settlement and unavailable-mode cleanup. The sidecar boundary is synthetic; this
+does not qualify native Electron interaction or live-provider execution.
#### E2E-ISSUE-1926-scratch-prefix
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index 1c03164f4..2d22e2c26 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -660,6 +660,16 @@ MVP 可以通过写入 SQLite 或日志文件来启动。
内置模式:Agent 使用 `agent`;Plan 使用 `contract`;Goal 是分阶段运行,其 `work` 阶段使用 `agent`。没有快照的旧 Goal 会话,以及 Host 无法解析的模式 id,一律回退为 `contract`(失败即关闭)。
+Prompt admission first claims an existing staged run through the Host and uses
+its persisted snapshot without consulting the current catalog. Editing, removing,
+or making the catalog definition simple does not change an existing run.
+Without a claim, simple custom modes carry the current catalog definition to the
+runtime. An unavailable mode closes the admission turn without persisting a user
+message or invoking the sidecar. Plan-state projection may rename only Agent/Plan
+sessions; an inactive projection preserves Goal and custom-mode identity.
+New Goal/custom sessions persist the catalog snapshot before returning from
+Desktop creation, including sessions created directly in the default mode.
+
### 说明
- `contract` 在权限 UI 之前硬性拒绝 Write/Edit 和未声明 `planSafeActions` 的插件工具;直接调用 host 也无法绕过该矩阵。声明了非空列表的插件工具会被放行,但运行器仍会拒绝列表之外的操作(ADR 0211)。
- `agent` 对 Write/Edit/Bash 和已注册插件工具使用权限卡片或所选的自动策略。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 4f7f956b8..9e3111f7d 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -10550,6 +10550,24 @@ Desktop 工作区后,列出、读取和解析 native 文件,再拒绝不存
`native-workspace-files.test.mjs` 另验证 sidecar 更换后拒绝旧响应。
不执行模型或访问用户 native 会话。
+#### E2E-custom-mode-prompt-admission
+
+Select a simple custom mode with a distinctive prompt and contract policy, send a
+message, and refresh planning state. The runtime receives the selected definition
+and the session retains its mode. Remove the definition before another send: reject
+without persisting a user message or invoking the sidecar; the admission turn is
+closed. For a staged run, edit the catalog into a simple mode and then remove it;
+subsequent dispatch retains the run snapshot in both cases. Controlled coverage:
+`apps/desktop/test/custom-mode-dispatch.test.mjs`. Native Electron/provider
+acceptance is separate from these stubbed Host/sidecar boundary checks.
+Also create directly in Goal or a staged custom mode without switching modes:
+the first send starts a run. `mode-session-create.test.mjs` checks the production
+creation registrar persists its snapshot before returning.
+`scripts/e2e-mode-definitions.mjs` also exercises production prompt IPC and the
+coordinator against an isolated real Host, including edit/removal, durable claim
+settlement and unavailable-mode cleanup. The sidecar boundary is synthetic; this
+does not qualify native Electron interaction or live-provider execution.
+
#### E2E-ISSUE-1926-scratch-prefix
创建配置相同但 scratch 不同的真实 runtime,基础提示段相同且尾部各保留自身路径;验证 shell 语法和自定义提示兼容,不调用真实供应商。
diff --git a/scripts/e2e-mode-definitions.mjs b/scripts/e2e-mode-definitions.mjs
index 574de861a..a8030ef47 100644
--- a/scripts/e2e-mode-definitions.mjs
+++ b/scripts/e2e-mode-definitions.mjs
@@ -3,10 +3,17 @@
import assert from "node:assert/strict";
import { mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
+import { register } from "node:module";
import { resolveHostBinary } from "./e2e/host.mjs";
import { withScenario } from "./e2e/fixture.mjs";
import { beginTurn, createSession, endTurn } from "./e2e/session.mjs";
+register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));
+const { createModeRunCoordinator } = await import("../apps/desktop/electron/main/runtime/mode-runs.ts");
+const { createModeCatalogService } = await import("../apps/desktop/electron/main/runtime/mode-catalog.ts");
+const { registerAgentIpc } = await import("../apps/desktop/electron/main/ipc/agent-ipc.ts");
+const { IPC } = await import("@pi-desktop/shared");
+
const root = process.env.PI_SCRATCH_DIR;
assert.ok(root, "PI_SCRATCH_DIR is required for isolated test state");
const temp = join(root, "mode-e2e");
@@ -72,3 +79,74 @@ await withScenario("mode-workflow", async ({ host, workspace }) => {
assert.equal((await host.call("modes.get", { sessionId })).run, null);
console.log("PASS mode snapshot -> artifact checks -> approval -> command gate -> completion -> Agent");
}, resolveHostBinary(), temp);
+
+await withScenario("mode-snapshot-dispatch", async ({ host, workspace, dataDir }) => {
+ const catalog = createModeCatalogService({ dir: join(dataDir, "modes") });
+ await catalog.write("review", "---\nname: review\npermission: contract\nstages:\n work:\n prompt: Keep the original stage.\n exit: [{ ask: user }]\n---\nOriginal instructions.\n");
+ const definition = await catalog.definition("review");
+ const session = await createSession(host, workspace, "Snapshot dispatch");
+ await host.call("session.configure", { id: session.id, mode: "review", modeSnapshot: definition });
+ const handlers = new Map();
+ const prompts = [];
+ const activeTurns = new Map();
+ const coordinator = createModeRunCoordinator({
+ getHost: () => host, catalog, logger: { app() {} }, isQuitting: () => false,
+ startContinuation: async () => assert.fail("non-looping stage must not continue automatically"),
+ });
+ registerAgentIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ modeRuns: coordinator, getHost: () => host, getAgentHostBridge: () => null,
+ getSidecar: () => ({
+ setProjectInstructionRoot() {},
+ async call(method, params) {
+ assert.equal(method, "agent.prompt");
+ prompts.push(params);
+ return { accepted: true, turnId: params.turnId };
+ },
+ }),
+ logger: { app() {} }, persistenceOutbox: {}, dataDir, activeTurns,
+ activeTurnUsages: new Map(), approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
+ recordTurnStart() {}, acquireSessionOperation: async () => () => {},
+ resolveAgentRuntimeLaunch: async () => ({
+ providerId: "fixture", modelId: "fixture", workspaceRoot: workspace,
+ sidecarParams: { sessionId: session.id, mode: "review", provider: { modelConfig: { input: ["text"] } } },
+ }),
+ finishTurn: async (_sessionId, status, _error, { turnId }) => {
+ await endTurn(host, turnId, status);
+ activeTurns.delete(session.id);
+ },
+ emitAgentEvent() {}, setNotificationViewingSessionId() {},
+ });
+ const send = async () => {
+ const result = await handlers.get(IPC.invoke.agentPrompt)({ sessionId: session.id, content: "Review the change." });
+ assert.equal(result.accepted, true);
+ await endTurn(host, result.turnId);
+ await coordinator.settleTurn(session.id, result.turnId, { reason: "completed" });
+ activeTurns.delete(session.id);
+ return prompts.at(-1);
+ };
+ const first = await send();
+ assert.deepEqual(first.modeDefinition, definition);
+ assert.ok(first.modeTurn.runId);
+ await catalog.write("review", "---\nname: review\npermission: agent\n---\nReplacement simple mode.\n");
+ const edited = await send();
+ assert.deepEqual(edited.modeDefinition, definition);
+ assert.equal(edited.modeTurn.runId, first.modeTurn.runId);
+ await catalog.remove("review");
+ const removed = await send();
+ assert.deepEqual(removed.modeDefinition, definition);
+ assert.equal(removed.modeTurn.runId, first.modeTurn.runId);
+ const current = (await host.call("modes.get", { sessionId: session.id })).run;
+ await coordinator.control({ sessionId: session.id, runId: current.id, expectedRevision: current.revision, action: "remove" });
+ await host.call("session.configure", { id: session.id, mode: "review", modeSnapshot: { ...definition, stages: [] } });
+ const before = (await host.call("session.get", { id: session.id })).session.messages;
+ assert.equal(before.length, 3);
+ await assert.rejects(
+ handlers.get(IPC.invoke.agentPrompt)({ sessionId: session.id, content: "Unavailable mode." }),
+ { errorCode: "MODE_NOT_FOUND" },
+ );
+ assert.equal(prompts.length, 3);
+ assert.equal(activeTurns.size, 0);
+ assert.deepEqual((await host.call("session.get", { id: session.id })).session.messages, before);
+ console.log("PASS production prompt IPC -> coordinator -> real Host snapshot after catalog edit/removal; missing mode closes admission");
+}, resolveHostBinary(), temp);