Skip to content

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

fix(modes): preserve approval transitions and create snapshots atomically

Linuxdazhaof25a7e4be02f
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index a4078a8e2..8b71ec165 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -1,7 +1,6 @@
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";
@@ -362,7 +361,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;
+ let modeDefinition: PreparedModeTurn["definition"] | undefined;
try {
preparedMode = await modeRuns.prepareTurn({
sessionId: req.sessionId,
@@ -544,7 +543,7 @@ export function registerAgentIpc({
turnId: durableTurnId,
});
} catch (error) {
- if (preparedMode) await modeRuns.abandonTurn(req.sessionId, durableTurnId).catch(() => undefined);
+ if (preparedMode?.modeTurn) await modeRuns.abandonTurn(req.sessionId, durableTurnId).catch(() => undefined);
await finishTurn(
req.sessionId,
"error",
@@ -587,7 +586,7 @@ export function registerAgentIpc({
{
...launch.sidecarParams,
...(modeDefinition ? { modeDefinition } : {}),
- ...(preparedMode
+ ...(preparedMode?.modeTurn
? { mode: preparedMode.definition.id, modeDefinition: preparedMode.definition, modeTurn: preparedMode.modeTurn }
: {}),
// The host-created durable turn is the approval identity used by
@@ -629,7 +628,7 @@ export function registerAgentIpc({
);
} catch (e) {
completionNoticeTurns.delete(durableTurnId);
- if (preparedMode) await modeRuns.abandonTurn(req.sessionId, durableTurnId).catch(() => undefined);
+ if (preparedMode?.modeTurn) await modeRuns.abandonTurn(req.sessionId, durableTurnId).catch(() => undefined);
await finishTurn(req.sessionId, "error", (e as any)?.errorCode, {
turnId: durableTurnId,
});
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index 25c68af39..4b8b3197c 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -10,6 +10,7 @@ import {
draftMatchesExisting,
providerCreateInputFromDraft,
isModelConfigImportSource,
+ isModeId,
type ModelConfigImportDraft,
type Mode,
type SessionThinkingLevel,
@@ -238,20 +239,20 @@ export function registerSessionIpc({
});
handle(IPC.invoke.sessionCreate, async (input = {}) => {
if (!host) throw new Error("host unavailable");
- const mode = Reflect.get(input, "mode") ?? "agent";
+ if (!input || typeof input !== "object" || Array.isArray(input) ||
+ (input.mode !== undefined && (typeof input.mode !== "string" || !isModeId(input.mode)))) {
+ throw Object.assign(new Error("Invalid session creation mode"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
+ }
+ const currentHost = host;
+ const mode = input.mode ?? "agent";
const modeSnapshot = await modeCatalog.snapshotFor(mode);
- const capabilityPromise = sessionCapabilityContext();
- let res = await host.call<{ session?: (RuntimeSession & { id?: string }) | null }>(
+ const { providers, defaults } = await sessionCapabilityContext();
+ const res = await currentHost.call<{ session?: (RuntimeSession & { id?: string }) | null }>(
"session.create",
- input,
+ { ...input, mode, modeSnapshot },
);
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) };
});
handle(
diff --git a/apps/desktop/electron/main/runtime/mode-runs.ts b/apps/desktop/electron/main/runtime/mode-runs.ts
index 84f4e6fa4..360c9a6de 100644
--- a/apps/desktop/electron/main/runtime/mode-runs.ts
+++ b/apps/desktop/electron/main/runtime/mode-runs.ts
@@ -49,7 +49,7 @@ export function modeContinuationOrigin(request: object): Exclude<ModeTurnOrigin,
return continuationOrigins.get(request);
}
-export type PreparedModeTurn = { modeTurn: ModeTurnContext; definition: ModeDefinition };
+export type PreparedModeTurn = { modeTurn?: ModeTurnContext; definition: ModeDefinition };
export type ModeTurnEnd = { reason: "completed" | "aborted" | "error"; usage?: MessageUsage; errorCode?: string };
@@ -125,9 +125,8 @@ export function createModeRunCoordinator(deps: {
},
/**
- * Claim the session's run for a durable turn. Returns nothing for simple
- * modes, or when a user turn cannot claim (it then runs as a plain turn of
- * the selected mode). A continuation that cannot claim throws, so the
+ * Claim the session's run for a durable turn, or return a simple mode's
+ * definition without a claim. A continuation that cannot claim throws, so the
* caller closes the empty turn instead of running it.
*/
async prepareTurn(input: {
@@ -146,10 +145,10 @@ export function createModeRunCoordinator(deps: {
let selected: ModeDefinition | undefined;
let claim: ModeClaimResult;
if (!run) {
- selected = await deps.catalog.definition(input.sessionMode);
+ selected = await this.definitionForPrompt(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;
+ return selected ? { definition: selected } : 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", {
diff --git a/apps/desktop/src/stores/helpers/planning-projection.ts b/apps/desktop/src/stores/helpers/planning-projection.ts
index a9dfbf8ef..f3e82a85b 100644
--- a/apps/desktop/src/stores/helpers/planning-projection.ts
+++ b/apps/desktop/src/stores/helpers/planning-projection.ts
@@ -1,4 +1,4 @@
-import type { Mode, PlanningState } from "@pi-desktop/shared";
+import type { Mode, PlanningState, PlanProposal } from "@pi-desktop/shared";
/**
* Which sessions the plan proposal pipeline (ADR 0053) speaks for
@@ -27,15 +27,16 @@ export function visiblePlanningState(
}
/**
- * 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.
+ * An approved legacy Goal proposal returns to Agent. Snapshot-defined modes
+ * can also report inactive, so require that approval evidence before renaming.
*/
export function modeAfterPlanningUpdate(
mode: Mode | undefined,
- _hostState: PlanningState,
+ hostState: PlanningState,
projectedMode: () => Mode,
+ checkpoint?: Pick<PlanProposal, "kind" | "status">,
): Mode {
if (mode === undefined || planningOwnsMode(mode)) return projectedMode();
+ if (mode === "goal" && hostState === "inactive" && checkpoint?.kind === "goal" && checkpoint.status === "approved") return "agent";
return mode;
}
diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.ts
index f02cab2d9..a419761af 100644
--- a/apps/desktop/src/stores/slices/events-slice.ts
+++ b/apps/desktop/src/stores/slices/events-slice.ts
@@ -177,6 +177,7 @@ export function createEventsSlice({
)?.mode;
const nextMode = modeAfterPlanningUpdate(currentMode, event.state, () =>
sessionModeForPlanningState(event.state, event.kind ?? checkpoint?.kind),
+ event.proposal ?? (previousCheckpoint?.status === "pending" ? checkpoint : undefined),
);
const executionActive = isActivePlanExecution(checkpoint);
const planExecutionWasActive = isActivePlanExecution(previousCheckpoint);
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index 5bbc2ba77..b11852d0e 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -263,6 +263,7 @@ export function createSessionSlice({
...session,
mode: modeAfterPlanningUpdate(durableMode, hostState, () =>
sessionModeForPlanningState(hostState, nextKind),
+ wasPending ? checkpoint : undefined,
),
}
: session,
diff --git a/apps/desktop/test/mode-definitions-renderer.test.mjs b/apps/desktop/test/mode-definitions-renderer.test.mjs
index cd4920959..502aaffd9 100644
--- a/apps/desktop/test/mode-definitions-renderer.test.mjs
+++ b/apps/desktop/test/mode-definitions-renderer.test.mjs
@@ -247,6 +247,9 @@ 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");
+ assert.equal(planning.modeAfterPlanningUpdate("goal", "inactive", agent, {
+ kind: "goal", status: "approved",
+ }), "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);
diff --git a/apps/desktop/test/mode-planning-approval.test.mjs b/apps/desktop/test/mode-planning-approval.test.mjs
new file mode 100644
index 000000000..9f90beb86
--- /dev/null
+++ b/apps/desktop/test/mode-planning-approval.test.mjs
@@ -0,0 +1,61 @@
+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 { createSessionSlice } = await import("../src/stores/slices/session-slice.ts");
+const { createEventsSlice } = await import("../src/stores/slices/events-slice.ts");
+const { api } = await import("../src/lib/api.ts");
+
+function harness(mode, proposal) {
+ let state = {
+ sessions: [{ id: "s", mode }], planningStates: {}, pendingPlans: {},
+ planCheckpoints: proposal ? { s: proposal } : {}, runningSessions: {},
+ retainedTranscripts: {}, activeSessionId: null, refreshSessions: async () => {},
+ refreshQueuedPrompts: async () => {},
+ };
+ let generation = 0;
+ const deps = {
+ get: () => state,
+ set: update => { state = { ...state, ...(typeof update === "function" ? update(state) : update) }; },
+ runtime: {
+ nextPlanSyncGeneration: () => ++generation, planSyncGeneration: () => generation,
+ liveSessionTranscripts: new Set(), sessionTranscriptCache: new Map(),
+ },
+ withoutRecordKey: (record, key) => Object.fromEntries(Object.entries(record).filter(([id]) => id !== key)),
+ sessionModeForPlanningState: value => value === "inactive" ? "agent" : "plan",
+ openPlanArtifact() {}, notifyInteractivePrompt() {},
+ };
+ return { get: () => state, sessions: createSessionSlice(deps), events: createEventsSlice(deps) };
+}
+
+test("legacy Goal approval changes the visible mode in live events and restoration", async t => {
+ const pending = { id: "p", sessionId: "s", kind: "goal", status: "pending", version: 1 };
+ const approved = { ...pending, status: "approved", action: "approve", executionState: "queued" };
+ const live = harness("goal", pending);
+ live.events.handlePlansChanged({ sessionId: "s", state: "inactive", proposal: approved });
+ assert.equal(live.get().sessions[0].mode, "agent");
+ t.mock.method(api, "pendingPlans", async () => ({ state: "inactive", plans: [] }));
+ const restored = harness("goal", pending);
+ await restored.sessions.restorePendingPlan("s");
+ assert.equal(restored.get().sessions[0].mode, "agent");
+});
+
+test("old approved Goal history cannot rename a newly selected staged Goal", async t => {
+ t.mock.method(api, "pendingPlans", async () => ({ state: "inactive", plans: [] }));
+ const h = harness("goal", { id: "old", kind: "goal", status: "approved" });
+ h.events.handlePlansChanged({ sessionId: "s", state: "inactive" });
+ assert.equal(h.get().sessions[0].mode, "goal");
+ await h.sessions.restorePendingPlan("s");
+ assert.equal(h.get().sessions[0].mode, "goal");
+});
+
+test("inactive planning without an approved legacy Goal preserves staged and custom modes", async t => {
+ t.mock.method(api, "pendingPlans", async () => ({ state: "inactive", plans: [] }));
+ for (const mode of ["goal", "review"]) {
+ const h = harness(mode);
+ h.events.handlePlansChanged({ sessionId: "s", state: "inactive" });
+ assert.equal(h.get().sessions[0].mode, mode);
+ await h.sessions.restorePendingPlan("s");
+ assert.equal(h.get().sessions[0].mode, mode);
+ }
+});
diff --git a/apps/desktop/test/mode-runs-main.test.mjs b/apps/desktop/test/mode-runs-main.test.mjs
index e4b4ed8ee..9da8c053e 100644
--- a/apps/desktop/test/mode-runs-main.test.mjs
+++ b/apps/desktop/test/mode-runs-main.test.mjs
@@ -117,7 +117,8 @@ test("Agent and Plan dispatch use builtin runtime instructions without a snapsho
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(prepared.definition.id, "review");
+ assert.equal(prepared.modeTurn, undefined);
assert.deepEqual(calls.map(call => call.method), ["modes.get"]);
});
diff --git a/apps/desktop/test/mode-session-create.test.mjs b/apps/desktop/test/mode-session-create.test.mjs
index 633ab0f6f..979e3d2b4 100644
--- a/apps/desktop/test/mode-session-create.test.mjs
+++ b/apps/desktop/test/mode-session-create.test.mjs
@@ -2,14 +2,14 @@ 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";
+import { IPC, ErrorCodes, isModeId } from "@pi-desktop/shared";
// 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": {},
+ "@pi-desktop/shared": { IPC, ErrorCodes, isModeId }, "../importers": {},
"../services/session-collaboration": {}, "../bootstrap/remote-hosts.js": {},
"../services/session-search": {},
};
@@ -38,8 +38,32 @@ test("creating a Goal or custom session persists its selected snapshot before re
});
await handlers.get(IPC.invoke.sessionCreate)({ mode });
assert.deepEqual(calls, [
- ["session.create", { mode }],
- ["session.configure", { id: "s", mode, modeSnapshot: snapshot }],
+ ["session.create", { mode, modeSnapshot: snapshot }],
]);
}
});
+
+test("failed capability reads prevent creation and cannot leave an undisclosed session", async () => {
+ const handlers = new Map();
+ module.exports.registerSessionIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => ({ call: async () => assert.fail("failed enrichment still created a session") }),
+ getSidecar: () => null,
+ modeCatalog: { snapshotFor: async () => undefined },
+ sessionCapabilityContext: async () => { throw new Error("providers unavailable"); },
+ });
+ await assert.rejects(() => handlers.get(IPC.invoke.sessionCreate)(), /providers unavailable/);
+});
+
+test("invalid create input fails before catalog lookup or Host mutation", async () => {
+ const handlers = new Map();
+ module.exports.registerSessionIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => ({ call: async () => assert.fail("invalid input reached Host") }),
+ getSidecar: () => null,
+ modeCatalog: { snapshotFor: async () => assert.fail("invalid mode reached catalog") },
+ });
+ for (const input of [null, [], "goal", { mode: 7 }, { mode: null }, { mode: "Bad Id" }]) {
+ await assert.rejects(() => handlers.get(IPC.invoke.sessionCreate)(input), { errorCode: ErrorCodes.INVALID_ARGUMENT });
+ }
+});
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 9e6f736a7..814f68399 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -14,6 +14,9 @@ mod todos;
mod window_corner_rpc;
mod worktree_rpc;
+#[cfg(test)]
+mod session_mode_create_tests;
+
#[cfg(test)]
mod plugin_reviews_rpc_tests;
#[cfg(test)]
@@ -2767,7 +2770,7 @@ async fn handle_request(
} else {
None
};
- let session = sessions::create_session_with_options(
+ let session = sessions::create_session_with_mode_snapshot(
&st.db,
sessions::SessionCreateOptions {
title: params
@@ -2794,8 +2797,9 @@ async fn handle_request(
permission_mode,
fast_mode,
},
+ params.get("modeSnapshot"),
)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ .map_err(modes_rpc::error)?;
let Some(project) = isolated_project else {
let session = remote_tools::decorate_session(
&st.db,
diff --git a/crates/host-core/src/rpc/session_mode_create_tests.rs b/crates/host-core/src/rpc/session_mode_create_tests.rs
new file mode 100644
index 000000000..c0bdc1b7b
--- /dev/null
+++ b/crates/host-core/src/rpc/session_mode_create_tests.rs
@@ -0,0 +1,99 @@
+use super::*;
+
+fn definition(mode: &str) -> Value {
+ json!({ "version": 1, "id": mode, "permission": "contract", "stages": [] })
+}
+
+#[tokio::test]
+async fn session_create_persists_mode_snapshot_and_policy() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut app = AppState::open(dir.path()).unwrap();
+ app.handshook = true;
+ let state = Arc::new(Mutex::new(app));
+ let (tx, _rx) = mpsc::unbounded_channel();
+ for mode in ["goal", "review"] {
+ let result = handle_request(
+ state.clone(),
+ "session.create",
+ json!({
+ "mode": mode, "modeSnapshot": definition(mode)
+ }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let app = state.lock().await;
+ let id = result["session"]["id"].as_str().unwrap();
+ let hash: Option<String> = app
+ .db
+ .conn()
+ .query_row(
+ "SELECT mode_snapshot_hash FROM sessions WHERE id = ?1",
+ [id],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert!(hash.is_some(), "{mode} must have its snapshot at creation");
+ assert_eq!(
+ crate::mode_runs::tool_policy(&app.db, id).unwrap(),
+ Some(crate::mode_runs::ToolPolicy::Contract)
+ );
+ }
+}
+
+#[tokio::test]
+async fn session_create_rejects_invalid_snapshot_without_leaving_a_session() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut app = AppState::open(dir.path()).unwrap();
+ app.handshook = true;
+ let state = Arc::new(Mutex::new(app));
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let error = handle_request(
+ state.clone(),
+ "session.create",
+ json!({
+ "mode": "review", "modeSnapshot": definition("other")
+ }),
+ tx,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "MODE_SNAPSHOT_INVALID");
+ assert!(sessions::list_sessions(&state.lock().await.db)
+ .unwrap()
+ .is_empty());
+}
+
+#[tokio::test]
+async fn session_create_rolls_back_snapshot_when_session_insert_fails() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut app = AppState::open(dir.path()).unwrap();
+ app.handshook = true;
+ app.db
+ .conn()
+ .execute_batch(
+ "CREATE TRIGGER reject_session BEFORE INSERT ON sessions
+ BEGIN SELECT RAISE(ABORT, 'synthetic insert failure'); END;",
+ )
+ .unwrap();
+ let state = Arc::new(Mutex::new(app));
+ let (tx, _rx) = mpsc::unbounded_channel();
+ assert!(handle_request(
+ state.clone(),
+ "session.create",
+ json!({
+ "mode": "review", "modeSnapshot": definition("review")
+ }),
+ tx
+ )
+ .await
+ .is_err());
+ let app = state.lock().await;
+ assert!(sessions::list_sessions(&app.db).unwrap().is_empty());
+ let count: i64 = app
+ .db
+ .conn()
+ .query_row("SELECT count(*) FROM mode_snapshots", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(count, 0);
+}
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 174391ab5..09e4b70a4 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -1482,6 +1482,16 @@ pub fn create_session_with_thinking(
pub fn create_session_with_options(
db: &Database,
options: SessionCreateOptions,
+) -> Result<SessionSummary> {
+ create_session_with_mode_snapshot(db, options, None)
+}
+
+/// Store a selected definition and its new session in one transaction.
+/// Legacy callers without a snapshot retain their existing creation semantics.
+pub fn create_session_with_mode_snapshot(
+ db: &Database,
+ options: SessionCreateOptions,
+ mode_snapshot: Option<&Value>,
) -> Result<SessionSummary> {
let SessionCreateOptions {
title,
@@ -1502,10 +1512,21 @@ pub fn create_session_with_options(
TITLE_SOURCE_MANUAL
};
let mode = normalize_mode(mode.as_deref());
+ let prepared = mode_snapshot
+ .filter(|value| !value.is_null())
+ .map(|value| crate::mode_runs::prepare_session_mode(db, &id, &mode, Some(value)))
+ .transpose()?;
let thinking_level = thinking_level.unwrap_or_else(default_thinking_level);
validate_thinking_level(&thinking_level)?;
let permission_mode = permission_mode.unwrap_or_else(default_permission_mode);
validate_permission_mode(&permission_mode)?;
+ let transaction = prepared
+ .as_ref()
+ .map(|_| db.conn().unchecked_transaction())
+ .transpose()?;
+ if let Some(prepared) = &prepared {
+ crate::mode_runs::store_session_snapshot(db, prepared)?;
+ }
let project_id = match project_path
.as_deref()
.filter(|path| !path.trim().is_empty())
@@ -1521,8 +1542,8 @@ pub fn create_session_with_options(
.prepare_cached(
"INSERT INTO sessions (
id, title, project_id, provider_id, model_id, mode, thinking_level,
- permission_mode, title_source, fast_mode, created_at, updated_at
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?11)",
+ permission_mode, title_source, fast_mode, created_at, updated_at, mode_snapshot_hash
+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?11, ?12)",
)?
.execute(params![
id,
@@ -1535,8 +1556,12 @@ pub fn create_session_with_options(
permission_mode,
title_source,
fast_mode,
- now
+ now,
+ prepared.as_ref().and_then(|value| value.snapshot_hash())
])?;
+ if let Some(transaction) = transaction {
+ transaction.commit()?;
+ }
Ok(SessionSummary {
id,
title,
diff --git a/docs/adr/mode-definitions.md b/docs/adr/mode-definitions.md
index 9bacc1514..85ed072dc 100644
--- a/docs/adr/mode-definitions.md
+++ b/docs/adr/mode-definitions.md
@@ -215,6 +215,12 @@ Only the Host records a gate as passed and moves the run to another stage.
### 8. Persistence
+Desktop attaches the catalog definition to the additive `session.create`
+`modeSnapshot` input. The Host validates and stores it in the same transaction
+as the session, rather than configuring an already-visible session in a second
+RPC. This avoids an incomplete session if configuration or the process fails;
+legacy callers may still omit the snapshot and retain fail-closed policy.
+
One migration after the current schema:
- `sessions.mode` keeps its column. Its values become mode ids, and the
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 7f5cda722..c55ac270a 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -869,9 +869,14 @@ 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.
+sessions; an inactive projection preserves Goal and custom-mode identity unless
+a legacy Goal proposal was approved. Live approval and restoration of a pending
+legacy proposal then show Agent; unrelated historical approvals do not rename
+a newly selected staged Goal.
+New Goal/custom sessions pass the catalog snapshot in the single Host creation
+call. Host validation, snapshot storage and session insertion share a transaction;
+a rejected snapshot or failed insert leaves neither an incomplete session nor
+an orphan snapshot. Legacy callers without a snapshot keep their existing behavior.
### Notes
- `contract` hard-denies Write/Edit and plugin tools without `planSafeActions` before permission UI; a direct host
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index ac4f7bf36..18f0acb29 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -330,6 +330,9 @@ to later refresh and inference; the vendor picker does not collect them.
`inheritPermissionFromSessionId`; when present, the host copies the existing
session's persisted permission mode atomically, while omission preserves the
existing `inherit` default. Missing/null thinking level defaults to `off`.
+ Optional `modeSnapshot` is validated for the selected mode and committed with
+ the session atomically. A rejected snapshot or failed insert leaves no partial
+ session or orphan snapshot; omitting it retains legacy creation semantics.
Optional boolean `fastMode` (ADR 0334) stores the session `/fast` switch;
missing/null means `false` and a non-boolean returns `INVALID_PARAMS`.
Optional `isolated: true` (ADR 0329) also requires `projectPath` and gives
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7122cfc18..c6f5975c1 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20631,7 +20631,12 @@ subsequent dispatch retains the run snapshot in both cases. Controlled coverage:
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.
+creation registrar validates input and sends its snapshot in one creation RPC.
+Host RPC tests cover snapshot/policy persistence, invalid snapshots and rollback
+after an injected session-insert failure. Approve a legacy Goal proposal: live
+events and pending-proposal restoration show Agent. Inactive polling with no
+approval preserves staged Goal/custom modes, including after older Goal history.
+Coverage: `mode-planning-approval.test.mjs`, `session_mode_create_tests.rs`.
`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
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 2d22e2c26..c1e9e8b16 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
@@ -666,9 +666,14 @@ 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.
+sessions; an inactive projection preserves Goal and custom-mode identity unless
+a legacy Goal proposal was approved. Live approval and restoration of a pending
+legacy proposal then show Agent; unrelated historical approvals do not rename
+a newly selected staged Goal.
+New Goal/custom sessions pass the catalog snapshot in the single Host creation
+call. Host validation, snapshot storage and session insertion share a transaction;
+a rejected snapshot or failed insert leaves neither an incomplete session nor
+an orphan snapshot. Legacy callers without a snapshot keep their existing behavior.
### 说明
- `contract` 在权限 UI 之前硬性拒绝 Write/Edit 和未声明 `planSafeActions` 的插件工具;直接调用 host 也无法绕过该矩阵。声明了非空列表的插件工具会被放行,但运行器仍会拒绝列表之外的操作(ADR 0211)。
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 27113da9f..005cd2b11 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -257,6 +257,9 @@ type ToolBudgetHealth = {
至 `off`。可选布尔值 `fastMode`(ADR 0334)保存会话的 `/fast` 开关;缺省/null 表示
`false`,非布尔值返回 `INVALID_PARAMS`。可选的 `isolated: true`(ADR 0329)同时要求 `projectPath`,并在返回前为新会话
创建专属 git worktree;无法创建时会话会被删除,调用以 `WORKTREE_*` 错误(§7)失败。
+ Optional `modeSnapshot` is validated for the selected mode and committed with
+ the session atomically. A rejected snapshot or failed insert leaves no partial
+ session or orphan snapshot; omitting it retains legacy creation semantics.
- `session.fork` — accepts `sessionId`, an optional caller-provided display
`title`, and optional `throughMessageId`; creates
one independent session from the source's current active canonical
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 e0aec4c23..bfb56ff3b 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
@@ -10597,7 +10597,12 @@ subsequent dispatch retains the run snapshot in both cases. Controlled coverage:
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.
+creation registrar validates input and sends its snapshot in one creation RPC.
+Host RPC tests cover snapshot/policy persistence, invalid snapshots and rollback
+after an injected session-insert failure. Approve a legacy Goal proposal: live
+events and pending-proposal restoration show Agent. Inactive polling with no
+approval preserves staged Goal/custom modes, including after older Goal history.
+Coverage: `mode-planning-approval.test.mjs`, `session_mode_create_tests.rs`.
`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
diff --git a/scripts/e2e-mode-definitions.mjs b/scripts/e2e-mode-definitions.mjs
index a8030ef47..0b5f1866a 100644
--- a/scripts/e2e-mode-definitions.mjs
+++ b/scripts/e2e-mode-definitions.mjs
@@ -84,8 +84,9 @@ 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 { session } = await host.call("session.create", {
+ title: "Snapshot dispatch", projectPath: workspace, mode: "review", modeSnapshot: definition,
+ });
const handlers = new Map();
const prompts = [];
const activeTurns = new Map();