Skip to content

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

fix(modes): preserve definitions through session creation and dispatch

Linuxdazhao953c2b5e6d3a
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 354ac85c5..550d49b10 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -52,7 +52,7 @@ export type AgentIpcDependencies = {
composerCommandService: Pick<ComposerCommandService, "buildComposerCommands">;
loadComposerTemplatesCached: (root: string | null) => Promise<ComposerTemplate[]>;
/** Staged mode runs: claim before the sidecar starts a turn (ADR mode-definitions). */
- modeRuns: Pick<ModeRunCoordinator, "canContinue" | "prepareTurn" | "abandonTurn">;
+ modeRuns: Pick<ModeRunCoordinator, "definitionForPrompt" | "canContinue" | "prepareTurn" | "abandonTurn">;
};
function rejectNativeAgentOperation(sessionId: string): void {
@@ -343,6 +343,8 @@ export function registerAgentIpc({
);
sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);
+ const modeDefinition = await modeRuns.definitionForPrompt(launch.sidecarParams.mode);
+
// Open a durable turn row, then persist the user message under it.
const turn = await host.call<{ turnId?: string }>("session.beginTurn", {
sessionId: req.sessionId,
@@ -583,6 +585,7 @@ export function registerAgentIpc({
"agent.prompt",
{
...launch.sidecarParams,
+ ...(modeDefinition ? { modeDefinition } : {}),
...(preparedMode
? { mode: preparedMode.definition.id, modeDefinition: preparedMode.definition, modeTurn: preparedMode.modeTurn }
: {}),
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index 20b9c3c20..25c68af39 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -238,13 +238,19 @@ export function registerSessionIpc({
});
handle(IPC.invoke.sessionCreate, async (input = {}) => {
if (!host) throw new Error("host unavailable");
+ const mode = Reflect.get(input, "mode") ?? "agent";
+ const modeSnapshot = await modeCatalog.snapshotFor(mode);
const capabilityPromise = sessionCapabilityContext();
- const res = await host.call<{ session?: (RuntimeSession & { id?: string }) | null }>(
+ let res = await host.call<{ session?: (RuntimeSession & { id?: string }) | null }>(
"session.create",
input,
);
logger.app("session", "info", "session created", { sessionId: res.session?.id });
if (!res.session) return res;
+ if (modeSnapshot) {
+ res = await host.call("session.configure", { id: res.session.id, mode, modeSnapshot });
+ if (!res.session) throw new Error("Created session was not configured");
+ }
const { providers, defaults } = await capabilityPromise;
return { ...res, session: enrichSession(res.session, providers, defaults) };
});
diff --git a/apps/desktop/src/stores/helpers/planning-projection.ts b/apps/desktop/src/stores/helpers/planning-projection.ts
index bc4f8b015..a9dfbf8ef 100644
--- a/apps/desktop/src/stores/helpers/planning-projection.ts
+++ b/apps/desktop/src/stores/helpers/planning-projection.ts
@@ -27,15 +27,15 @@ export function visiblePlanningState(
}
/**
- * The session mode after a plan update. `inactive` from the Host means the
- * session is in Agent again, whatever the renderer last knew; otherwise a
- * mode the pipeline does not own is left as it is.
+ * The proposal pipeline can change only Agent and Plan modes. An inactive
+ * projection also belongs to custom modes and staged Goal, so it does not
+ * establish that either session switched back to Agent.
*/
export function modeAfterPlanningUpdate(
mode: Mode | undefined,
- hostState: PlanningState,
+ _hostState: PlanningState,
projectedMode: () => Mode,
): Mode {
- if (mode === undefined || planningOwnsMode(mode) || hostState === "inactive") return projectedMode();
+ if (mode === undefined || planningOwnsMode(mode)) return projectedMode();
return mode;
}
diff --git a/apps/desktop/test/composer-agent-mention.test.mjs b/apps/desktop/test/composer-agent-mention.test.mjs
index 257de6312..794b1258e 100644
--- a/apps/desktop/test/composer-agent-mention.test.mjs
+++ b/apps/desktop/test/composer-agent-mention.test.mjs
@@ -24,7 +24,12 @@ function promptFixture({ mode = "agent", projectPath = null, skills = [], templa
assert.fail(`unexpected RPC ${method}`);
} };
registerAgentIpc({
- modeRuns: builtinModeRuns,
+ modeRuns: mode === "goal" ? {
+ ...builtinModeRuns,
+ // This fixture isolates mention expansion; staged admission has its own suite.
+ definitionForPrompt: async () => undefined,
+ prepareTurn: async () => undefined,
+ } : builtinModeRuns,
registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
getHost: () => host,
getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {
diff --git a/apps/desktop/test/custom-mode-dispatch.test.mjs b/apps/desktop/test/custom-mode-dispatch.test.mjs
new file mode 100644
index 000000000..c8071ed7f
--- /dev/null
+++ b/apps/desktop/test/custom-mode-dispatch.test.mjs
@@ -0,0 +1,93 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const { registerAgentIpc } = await import("../electron/main/ipc/agent-ipc.ts");
+const { modeAfterPlanningUpdate } = await import("../src/stores/helpers/planning-projection.ts");
+const { IPC } = await import("@pi-desktop/shared");
+
+async function promptFixture({ unavailable = false, prepared } = {}) {
+ const handlers = new Map();
+ const prompts = [];
+ const definition = {
+ version: 1, id: "review", label: "Review", description: "", source: "user",
+ permission: "contract", prompt: "Review without changing files.",
+ returnTo: "agent", artifacts: [], stages: [],
+ budget: { maxTurns: 20, maxTokens: null },
+ };
+ const hostCalls = [];
+ const host = { async call(method) {
+ hostCalls.push(method);
+ if (method === "settings.get") return {};
+ if (method === "session.get") return { session: { id: "s", mode: "review", messages: [] } };
+ if (method === "session.beginTurn") return { turnId: "turn" };
+ if (method === "session.appendMessage") return {};
+ assert.fail(`unexpected Host method ${method}`);
+ } };
+ const sidecar = {
+ setProjectInstructionRoot() {},
+ async call(method, params) {
+ assert.equal(method, "agent.prompt");
+ prompts.push(params);
+ return { accepted: true, turnId: "turn" };
+ },
+ };
+ registerAgentIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ modeRuns: {
+ definitionForPrompt: async id => {
+ assert.equal(id, "review");
+ if (unavailable) throw Object.assign(new Error("Mode is not available"), { errorCode: "MODE_NOT_FOUND" });
+ return definition;
+ },
+ prepareTurn: async () => prepared,
+ },
+ getHost: () => host, getSidecar: () => sidecar, getAgentHostBridge: () => null,
+ logger: { app() {} }, persistenceOutbox: {}, dataDir: "/unused-no-attachments",
+ activeTurns: new Map(), activeTurnUsages: new Map(),
+ approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
+ recordTurnStart() {}, acquireSessionOperation: async () => () => {},
+ resolveAgentRuntimeLaunch: async () => ({
+ providerId: "fixture", modelId: "fixture",
+ sidecarParams: { sessionId: "s", mode: "review", provider: { modelConfig: { input: ["text"] } } },
+ }),
+ finishTurn: async () => assert.fail("prompt admission failed"),
+ emitAgentEvent() {}, setNotificationViewingSessionId() {},
+ });
+ return {
+ prompts, hostCalls, definition,
+ prompt: () => handlers.get(IPC.invoke.agentPrompt)({ sessionId: "s", content: "Inspect the changes." }),
+ };
+}
+
+test("a simple custom mode reaches the sidecar with its instructions and policy", async () => {
+ const { prompt, prompts, definition } = await promptFixture();
+ await prompt();
+ assert.equal(prompts.length, 1);
+ assert.deepEqual(prompts[0].modeDefinition, definition);
+ 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 });
+ await assert.rejects(prompt, { errorCode: "MODE_NOT_FOUND" });
+ assert.equal(prompts.length, 0);
+ assert.ok(!hostCalls.includes("session.beginTurn"));
+});
+
+test("a staged run keeps its persisted snapshot over the current catalog", async () => {
+ const definition = { id: "review", prompt: "Persisted stage instructions." };
+ const modeTurn = { runId: "run", stageId: "work", permission: "contract" };
+ const { prompt, prompts } = await promptFixture({ 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);
+ }
+ assert.equal(modeAfterPlanningUpdate("plan", "inactive", () => "agent"), "agent");
+});
diff --git a/apps/desktop/test/mode-definitions-renderer.test.mjs b/apps/desktop/test/mode-definitions-renderer.test.mjs
index 2e8408223..cd4920959 100644
--- a/apps/desktop/test/mode-definitions-renderer.test.mjs
+++ b/apps/desktop/test/mode-definitions-renderer.test.mjs
@@ -247,8 +247,10 @@ test("Goal and user modes are never shown as Plan-style planning and keep their
}
// A legacy Goal proposal still awaiting approval stays resolvable.
assert.equal(planning.visiblePlanningState("goal", "awaiting_approval", true), "awaiting_approval");
- // `inactive` means the Host moved the session back to Agent.
- assert.equal(planning.modeAfterPlanningUpdate("goal", "inactive", agent), "agent");
+ // Inactive Plan state does not establish a mode change for other modes.
+ for (const mode of ["goal", "review"]) {
+ assert.equal(planning.modeAfterPlanningUpdate(mode, "inactive", agent), mode);
+ }
});
test("Settings → Modes starts documents with valid ids and an exact name", () => {
diff --git a/apps/desktop/test/mode-session-create.test.mjs b/apps/desktop/test/mode-session-create.test.mjs
new file mode 100644
index 000000000..633ab0f6f
--- /dev/null
+++ b/apps/desktop/test/mode-session-create.test.mjs
@@ -0,0 +1,45 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import ts from "typescript";
+import { IPC } from "../../../packages/shared/src/protocol.ts";
+
+// Execute the production registrar with only external services replaced.
+const source = readFileSync(new URL("../electron/main/ipc/session-ipc.ts", import.meta.url), "utf8");
+const module = { exports: {} };
+const imports = {
+ electron: { shell: {} }, "node:fs": {}, "node:path": {},
+ "@pi-desktop/shared": { IPC }, "../importers": {},
+ "../services/session-collaboration": {}, "../bootstrap/remote-hosts.js": {},
+ "../services/session-search": {},
+};
+new Function("require", "exports", "module", ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+}).outputText)((id) => {
+ assert.ok(Object.hasOwn(imports, id), `unexpected dependency: ${id}`);
+ return imports[id];
+}, module.exports, module);
+
+test("creating a Goal or custom session persists its selected snapshot before returning", async () => {
+ for (const mode of ["goal", "review"]) {
+ const handlers = new Map();
+ const calls = [];
+ const snapshot = { id: mode, stages: [{ id: "work" }] };
+ const host = { async call(method, input) {
+ calls.push([method, input]);
+ return { session: { id: "s", mode } };
+ } };
+ module.exports.registerSessionIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => host, getSidecar: () => null, logger: { app() {} },
+ sessionCapabilityContext: async () => ({ providers: [], defaults: {} }),
+ enrichSession: session => session,
+ modeCatalog: { snapshotFor: async id => { assert.equal(id, mode); return snapshot; } },
+ });
+ await handlers.get(IPC.invoke.sessionCreate)({ mode });
+ assert.deepEqual(calls, [
+ ["session.create", { mode }],
+ ["session.configure", { id: "s", mode, modeSnapshot: snapshot }],
+ ]);
+ }
+});
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 1cf4acea1..1af49878c 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -863,6 +863,14 @@ 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
+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.
+
### Notes
- `contract` hard-denies Write/Edit and plugin tools without `planSafeActions` before permission UI; a direct host
call cannot bypass the matrix. Plugin tools that declare a non-empty list are admitted; the runner still rejects any action outside that list (ADR 0211).
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f7347948c..6af56bfba 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20528,6 +20528,19 @@ or scratch RPC reaches Desktop storage. `native-workspace-files.test.mjs`
additionally rejects replaced sidecars. No provider execution or native user
session data is used.
+#### 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
+before creating a turn. For a staged run, edit the catalog after starting; subsequent
+dispatch retains the run snapshot. 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.
+
#### E2E-ISSUE-1926-scratch-prefix
Build two actual runtimes with identical configuration and different scratch directories. Their leading runtime system sections match; each trailing context retains its own path. Check PowerShell/POSIX guidance and custom system prompt behavior. Coverage: runtime.test.ts. No paid provider requests or cache-hit claims.