Skip to content

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

fix(modes): project bundle definitions for the sidecar

v_wyxgwangc40c8068732f
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index c22332d37..b2b269f65 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -4,6 +4,7 @@ import { IPC, ErrorCodes, compactionRecordId, composeMentionPrompt, findSkillMen
import { modePermissionFor } from "@pi-desktop/shared";
import type { FinishTurn } from "../runtime/plans";
import { modeContinuationOrigin, type ModeRunCoordinator, type PreparedModeTurn } from "../runtime/mode-runs";
+import { toSidecarModeDefinition } from "../runtime/mode-sidecar-definition";
import { goalPromptMode, goalStartRequested } from "../runtime/goal-start";
import { expandSlashInvocation, visionFromModelConfig, type ComposerTemplate } from "@pi-desktop/agent-runtime";
import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";
@@ -659,11 +660,9 @@ export function registerAgentIpc({
"agent.prompt",
{
...launch.sidecarParams,
- mode: promptMode,
- ...(modeDefinition ? { modeDefinition } : {}),
- ...(preparedMode?.modeTurn
- ? { mode: preparedMode.definition.id, modeDefinition: preparedMode.definition, modeTurn: preparedMode.modeTurn }
- : {}),
+ mode: preparedMode?.modeTurn ? preparedMode.definition.id : promptMode,
+ ...(modeDefinition ? { modeDefinition: toSidecarModeDefinition(modeDefinition) } : {}),
+ ...(preparedMode?.modeTurn ? { modeTurn: preparedMode.modeTurn } : {}),
// The host-created durable turn is the approval identity used by
// Rust. The runtime must not replace it with a provider-local UUID.
turnId: durableTurnId,
diff --git a/apps/desktop/electron/main/runtime/mode-runs.ts b/apps/desktop/electron/main/runtime/mode-runs.ts
index 0b334c2ed..f20a04fdc 100644
--- a/apps/desktop/electron/main/runtime/mode-runs.ts
+++ b/apps/desktop/electron/main/runtime/mode-runs.ts
@@ -23,6 +23,7 @@ import type {
} from "@pi-desktop/shared";
import type { ModeCatalogService } from "./mode-catalog";
import { goalPromptMode } from "./goal-start";
+import { toSidecarModeDefinition, type SidecarModeDefinition } from "./mode-sidecar-definition";
type HostCaller = { call<T = unknown>(method: string, params?: unknown): Promise<T> };
@@ -63,7 +64,7 @@ function totalTokens(usage: MessageUsage | undefined): number {
/** Sidecar `agent.modeTurnNotice` payload (without session and turn ids). */
export type ModeTurnNotice =
| { runId: string; action: "closeout" }
- | { runId: string; action: "release"; mode: string; modeDefinition?: ModeDefinition };
+ | { runId: string; action: "release"; mode: string; modeDefinition?: SidecarModeDefinition };
export type ModeRunCoordinator = ReturnType<typeof createModeRunCoordinator>;
@@ -276,7 +277,7 @@ export function createModeRunCoordinator(deps: {
const returnDefinition = await deps.catalog.definition(returnTo);
// A deleted return mode falls back to Agent, as settleReturn does.
const mode = returnDefinition || isPlainMode(returnTo) ? returnTo : "agent";
- const modeDefinition = mode === returnTo ? returnDefinition : undefined;
+ const modeDefinition = mode === returnTo && returnDefinition ? toSidecarModeDefinition(returnDefinition) : undefined;
await deps.notifyTurn(request.sessionId, turnId, {
runId: request.runId,
action: "release",
diff --git a/apps/desktop/electron/main/runtime/mode-sidecar-definition.ts b/apps/desktop/electron/main/runtime/mode-sidecar-definition.ts
new file mode 100644
index 000000000..ed43b1a87
--- /dev/null
+++ b/apps/desktop/electron/main/runtime/mode-sidecar-definition.ts
@@ -0,0 +1,9 @@
+import type { ModeDefinition } from "@pi-desktop/shared";
+
+export type SidecarModeDefinition = Omit<ModeDefinition, "bundle">;
+
+/** Keep bundle metadata in the catalog and Host snapshot. The sidecar gets
+ * the resolved subagent and skill catalogs separately from the definition. */
+export function toSidecarModeDefinition({ bundle: _bundle, ...definition }: ModeDefinition): SidecarModeDefinition {
+ return definition;
+}
diff --git a/apps/desktop/test/custom-mode-dispatch.test.mjs b/apps/desktop/test/custom-mode-dispatch.test.mjs
index fd84a26af..29f2c9300 100644
--- a/apps/desktop/test/custom-mode-dispatch.test.mjs
+++ b/apps/desktop/test/custom-mode-dispatch.test.mjs
@@ -6,12 +6,25 @@ 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");
+const { parseModeBundle, readModeBundleReferences } = await import("../../../packages/agent-runtime/src/mode-definitions-bundle.ts");
+const { parseModeLaunchParams, parseModePromptTurn } = await import("../../../packages/agent-runtime/src/modes/mode-params.ts");
-async function promptFixture({ unavailable = false, prepared } = {}) {
+function yamlMode(staged = false) {
+ const document = readModeBundleReferences("name: review\npermission: contract\npromptFile: prompt.md\n" +
+ (staged ? "stages:\n work: {}\n" : ""));
+ assert.equal(document.ok, true);
+ const parsed = parseModeBundle({
+ ...document, prompt: { path: "prompt.md", text: "Review the changes." }, subagents: [], source: "user",
+ });
+ assert.equal(parsed.ok, true);
+ return parsed.definition;
+}
+
+async function promptFixture({ unavailable = false, prepared, yamlDefinition } = {}) {
const handlers = new Map();
const prompts = [];
const finished = [];
- const definition = {
+ const definition = yamlDefinition ?? {
version: 1, id: "review", label: "Review", description: "", source: "user",
permission: "contract", prompt: "Review without changing files.",
returnTo: "agent", artifacts: [], stages: [],
@@ -30,6 +43,7 @@ async function promptFixture({ unavailable = false, prepared } = {}) {
setProjectInstructionRoot() {},
async call(method, params) {
assert.equal(method, "agent.prompt");
+ if (yamlDefinition) parseModePromptTurn(params.modeTurn, parseModeLaunchParams(params));
prompts.push(params);
return { accepted: true, turnId: "turn" };
},
@@ -43,10 +57,11 @@ async function promptFixture({ unavailable = false, prepared } = {}) {
return definition;
},
prepareTurn: async () => prepared,
+ abandonTurn: async () => {},
},
getHost: () => host, getSidecar: () => sidecar, getAgentHostBridge: () => null,
logger: { app() {} }, persistenceOutbox: {}, dataDir: "/unused-no-attachments",
- activeTurns: new Map(), activeTurnUsages: new Map(),
+ activeTurns: new Map(), activeTurnUsages: new Map(), completionNoticeTurns: new Set(),
approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
recordTurnStart() {}, acquireSessionOperation: async () => () => {},
resolveAgentRuntimeLaunch: async () => ({
@@ -70,6 +85,27 @@ test("a simple custom mode reaches the sidecar with its instructions and policy"
assert.equal(prompts[0].modeTurn, undefined);
});
+test("sending in a YAML mode keeps its instructions and policy at the sidecar boundary", async () => {
+ const { bundle, ...expected } = yamlMode();
+ const { prompt, prompts, definition } = await promptFixture({ yamlDefinition: { ...expected, bundle } });
+ assert.deepEqual(await prompt(), { accepted: true, turnId: "turn" });
+ assert.deepEqual(prompts[0].modeDefinition, expected);
+ assert.deepEqual(definition.bundle, bundle);
+});
+
+test("sending in a staged YAML mode keeps the saved stage and its turn", async () => {
+ const definition = yamlMode(true);
+ const { bundle, ...expected } = definition;
+ const modeTurn = {
+ runId: "run", stageId: "work", origin: "user", enteredStage: true, input: "Inspect the changes.", artifactPaths: {},
+ };
+ const { prompt, prompts } = await promptFixture({ yamlDefinition: yamlMode(), prepared: { definition, modeTurn } });
+ assert.deepEqual(await prompt(), { accepted: true, turnId: "turn" });
+ assert.deepEqual(prompts[0].modeDefinition, expected);
+ assert.deepEqual(prompts[0].modeTurn, modeTurn);
+ assert.deepEqual(definition.bundle, bundle);
+});
+
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" });
diff --git a/apps/desktop/test/mode-runs-main.test.mjs b/apps/desktop/test/mode-runs-main.test.mjs
index b549d08fe..a5c1903e5 100644
--- a/apps/desktop/test/mode-runs-main.test.mjs
+++ b/apps/desktop/test/mode-runs-main.test.mjs
@@ -14,6 +14,7 @@ const { createModeRunCoordinator, modeContinuationOrigin, modeContinuationReques
const { createModeCatalogService } = await import("../electron/main/runtime/mode-catalog.ts");
const { registerModesIpc } = await import("../electron/main/ipc/modes-ipc.ts");
const { IPC } = await import("@pi-desktop/shared");
+const { parseModeTurnNotice } = await import("../../../packages/agent-runtime/src/modes/mode-params.ts");
const staged = {
version: 1,
@@ -50,7 +51,7 @@ function run(overrides = {}) {
};
}
-function fixture({ open = null, claim, settle = { run: null, continue: false }, pendingReturn = null, catalogModes = null, featureReturnTo = "agent" } = {}) {
+function fixture({ open = null, claim, settle = { run: null, continue: false }, pendingReturn = null, catalogModes = null, featureReturnTo = "agent", reviewDefinition } = {}) {
const calls = [];
const continuations = [];
const aborts = [];
@@ -78,7 +79,7 @@ function fixture({ open = null, claim, settle = { run: null, continue: false },
if (catalogModes && !catalogModes.includes(id)) return undefined;
if (id === "feature") return { ...staged, returnTo: featureReturnTo };
if (id === "goal") return { ...staged, id: "goal", source: "builtin" };
- if (id === "review") return { ...staged, id: "review", stages: [] };
+ if (id === "review") return reviewDefinition ?? { ...staged, id: "review", stages: [] };
return undefined;
},
};
@@ -379,6 +380,23 @@ test("remove releases the turn to agent when the return mode was deleted (#2204)
assert.deepEqual(notices, [{ sessionId: "s1", turnId: "t1", runId: "run1", action: "release", mode: "agent" }]);
});
+test("remove releases the active turn to a YAML return mode without discarding the Host snapshot", async () => {
+ const bundle = { subagents: [], includeGlobalSubagents: false, disabledSkills: [] };
+ const expected = { ...staged, id: "review", permission: "contract", prompt: "Review only.", stages: [] };
+ const reviewDefinition = { ...expected, bundle };
+ const stopped = run({ state: "stopped", revision: 4, finishedAt: "t" });
+ const { coordinator, calls, notices } = fixture({
+ settle: { run: stopped, continue: false }, featureReturnTo: "review", pendingReturn: "review", reviewDefinition,
+ });
+ await coordinator.prepareTurn({ sessionId: "s1", turnId: "t1", sessionMode: "feature", content: "x", origin: "user" });
+ await coordinator.control({ sessionId: "s1", runId: "run1", expectedRevision: 3, action: "remove" });
+ assert.deepEqual(parseModeTurnNotice(notices[0]), {
+ turnId: "t1", runId: "run1", action: "release", mode: "review", modeDefinition: expected,
+ });
+ assert.equal(await coordinator.settleReturn("s1", stopped), true);
+ assert.deepEqual(calls.at(-1).params.modeSnapshot, reviewDefinition);
+});
+
test("a user mode whose name differs from its directory is read, saved and deleted in place (#2202)", async () => {
const dir = await mkdtemp(join(tmpdir(), "pi-modes-"));
try {
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index e9ea888d9..2e9a48932 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1116,6 +1116,10 @@ Execution requires an agent-level mode or stage:
from a private role's primary pin requires explicit approval for that task,
in addition to model availability. Each fallback may select its own thinking
level. Neither the bundle nor a task can change the parent session model.
+ Electron Main keeps the bundle in the catalog and complete Host snapshots.
+ The sidecar receives the mode's execution definition without bundle metadata
+ on prompt dispatch and run release; resolved skill and subagent catalogs
+ travel separately on launch.
When a model key is not pre-resolved, the runtime asks Electron main to resolve it
on-demand via the `provider.resolveSubagentModel` RPC. The started `Task`
result details record the effective `modelId` and resolved `thinkingLevel`