Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(modes): settle a closed run's return mode against the catalog
vastsa39384a7cc4b0
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 64752ab1c..f454547ca 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -837,6 +837,7 @@ const { startHost } = createHostRuntime({userMcp,pluginActiveInProject,sendToRenderer,+ settleModeReturn: (sessionId, run) => modeServices.runs.settleReturn(sessionId, run),emitAgentEvent,togglePluginLauncher,finishTurn,diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.tsindex 452c39e5a..1cf337707 100644--- a/apps/desktop/electron/main/runtime/host.ts+++ b/apps/desktop/electron/main/runtime/host.ts@@ -22,6 +22,8 @@ export type HostRuntimeDependencies = {userMcp: UserMcpRuntime;pluginActiveInProject: (pluginId: string, projectPath: string | null | undefined) => boolean;sendToRenderer: (channel: string, payload: unknown) => void;+ /** Settles the session mode of a run that closed; true when it changed. */+ settleModeReturn: (sessionId: string, run: { id: string; state: string }) => Promise<boolean>;emitAgentEvent: (envelope: AgentEventEnvelope) => void;togglePluginLauncher: () => Promise<void>;finishTurn: FinishTurn;@@ -58,6 +60,7 @@ export function createHostRuntime({userMcp,pluginActiveInProject,sendToRenderer,+ settleModeReturn,emitAgentEvent,togglePluginLauncher,finishTurn,@@ -339,6 +342,17 @@ export function createHostRuntime({sendToRenderer(IPC.event.plansChanged, params);} else if (method === "modes.changed") {sendToRenderer(IPC.event.modesChanged, params);+ const { sessionId, run } = (params ?? {}) as { sessionId?: unknown; run?: { id?: unknown; state?: unknown } | null };+ if (typeof sessionId === "string" && typeof run?.id === "string" && typeof run.state === "string") {+ void settleModeReturn(sessionId, { id: run.id, state: run.state })+ .then((changed) => {+ // The renderer reads the session list again on a closed run.+ if (changed && runtimeState.host === h) sendToRenderer(IPC.event.modesChanged, params);+ })+ .catch((error: unknown) =>+ logger.app("session", "warn", "mode run return mode was not settled", { sessionId, data: String(error) }),+ );+ }} else if (method === "todos.changed") {sendToRenderer(IPC.event.todosChanged, params);} else if (method === "configSync.changed") {diff --git a/apps/desktop/electron/main/runtime/mode-runs.ts b/apps/desktop/electron/main/runtime/mode-runs.tsindex 080e010f7..85b011912 100644--- a/apps/desktop/electron/main/runtime/mode-runs.ts+++ b/apps/desktop/electron/main/runtime/mode-runs.ts@@ -25,6 +25,14 @@ import type { ModeCatalogService } from "./mode-catalog";type HostCaller = { call<T = unknown>(method: string, params?: unknown): Promise<T> };+/** `modes.settleReturn` answer: the return mode still pending, or the one applied. */+type ModeSettleReturnResult = { pending: string | null; applied: string | null };++/** Builtins whose Host semantics need no snapshot. */+function isPlainMode(mode: string): boolean {+ return mode === "agent" || mode === "plan";+}+/** Model-facing content of a Host-started turn. It is never persisted as a* user message; the stage brief in the system prompt carries the details. */export const MODE_CONTINUATION_CONTENT =@@ -217,8 +225,11 @@ export function createModeRunCoordinator(deps: {// The session already returned to its return mode in the Host.await (async () => {const definition = result.run ? await deps.catalog.definition(result.run.modeId) : undefined;- const mode = definition?.returnTo ?? "agent";- const modeDefinition = await deps.catalog.definition(mode);+ const returnTo = definition?.returnTo ?? "agent";+ 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;await deps.notifyTurn(request.sessionId, turnId, {runId: request.runId,action: "release",@@ -243,6 +254,33 @@ export function createModeRunCoordinator(deps: {return result;},+ /**+ * After a run closed, the Host left the session on the run's `returnTo`+ * without a snapshot (#2204). Hand it that mode's current definition, or+ * let it fall back to Agent when the mode no longer exists. Returns+ * whether the session's mode row changed.+ */+ async settleReturn(sessionId: string, run: { id: string; state: string }): Promise<boolean> {+ if (run.state !== "finished" && run.state !== "stopped") return false;+ const hostCaller = host();+ const { pending } = await hostCaller.call<ModeSettleReturnResult>("modes.settleReturn", { sessionId, runId: run.id });+ if (!pending) return false;+ const modeSnapshot = await deps.catalog.definition(pending);+ const { applied } = await hostCaller.call<ModeSettleReturnResult>("modes.settleReturn", {+ sessionId,+ runId: run.id,+ mode: pending,+ ...(modeSnapshot ? { modeSnapshot } : {}),+ });+ if (applied && applied !== pending) {+ deps.logger.app("session", "warn", "mode run return mode no longer exists; session uses agent", {+ sessionId,+ data: pending,+ });+ }+ return Boolean(applied);+ },+/** Test seam and diagnostics. */claimedTurns: (): ReadonlyMap<string, { sessionId: string; runId: string }> => turnRuns,};diff --git a/apps/desktop/test/mode-runs-main.test.mjs b/apps/desktop/test/mode-runs-main.test.mjsindex a4556b611..6365a5fb2 100644--- a/apps/desktop/test/mode-runs-main.test.mjs+++ b/apps/desktop/test/mode-runs-main.test.mjs@@ -48,7 +48,7 @@ function run(overrides = {}) {};}-function fixture({ open = null, claim, settle = { run: null, continue: false } } = {}) {+function fixture({ open = null, claim, settle = { run: null, continue: false }, pendingReturn = null, catalogModes = null, featureReturnTo = "agent" } = {}) {const calls = [];const continuations = [];const aborts = [];@@ -62,12 +62,17 @@ function fixture({ open = null, claim, settle = { run: null, continue: false } }}if (method === "modes.settleTurn") return settle;if (method === "modes.control" || method === "modes.resolve" || method === "modes.update") return settle;+ if (method === "modes.settleReturn") {+ if (params.mode === undefined) return { pending: pendingReturn, applied: null };+ return { pending: null, applied: params.modeSnapshot ? params.mode : "agent" };+ }throw new Error(`unexpected ${method}`);},};const catalog = {async definition(id) {- if (id === "feature") return staged;+ if (catalogModes && !catalogModes.includes(id)) return undefined;+ if (id === "feature") return { ...staged, returnTo: featureReturnTo };if (id === "review") return { ...staged, id: "review", stages: [] };return undefined;},@@ -267,3 +272,39 @@ test("the catalog reads, validates, writes and deletes user modes in its own dirawait rm(dir, { recursive: true, force: true });}});++test("a closed run hands the session its existing return mode with a snapshot (#2204)", async () => {+ const { coordinator, calls } = fixture({ pendingReturn: "review" });+ assert.equal(await coordinator.settleReturn("s1", run({ state: "finished" })), true);+ const settles = calls.filter((call) => call.method === "modes.settleReturn");+ assert.equal(settles.length, 2);+ assert.equal(settles[1].params.mode, "review");+ assert.equal(settles[1].params.modeSnapshot.id, "review");+});++test("a deleted return mode is settled without a snapshot, so the Host falls back to agent (#2204)", async () => {+ const { coordinator, calls } = fixture({ pendingReturn: "review", catalogModes: ["feature"] });+ assert.equal(await coordinator.settleReturn("s1", run({ state: "stopped" })), true);+ const last = calls.filter((call) => call.method === "modes.settleReturn").at(-1);+ assert.deepEqual(last.params, { sessionId: "s1", runId: "run1", mode: "review" });+});++test("an open run or a settled session asks the Host nothing more (#2204)", async () => {+ const open = fixture({ pendingReturn: "review" });+ assert.equal(await open.coordinator.settleReturn("s1", run({ state: "paused" })), false);+ assert.deepEqual(open.calls, []);+ const settled = fixture();+ assert.equal(await settled.coordinator.settleReturn("s1", run({ state: "finished" })), false);+ assert.equal(settled.calls.length, 1);+});++test("remove releases the turn to agent when the return mode was deleted (#2204)", async () => {+ const { coordinator, notices } = fixture({+ settle: { run: run({ state: "stopped", revision: 4, finishedAt: "t" }), continue: false },+ catalogModes: ["feature"],+ featureReturnTo: "review",+ });+ 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(notices, [{ sessionId: "s1", turnId: "t1", runId: "run1", action: "release", mode: "agent" }]);+});diff --git a/crates/host-core/src/mode_runs.rs b/crates/host-core/src/mode_runs.rsindex 1a9e35def..3813485c5 100644--- a/crates/host-core/src/mode_runs.rs+++ b/crates/host-core/src/mode_runs.rs@@ -17,6 +17,7 @@ mod gates;mod model;mod policy;mod repository;+mod return_mode;mod snapshot;pub use budget::validate_goal_budget_setting;@@ -27,6 +28,7 @@ pub use engine::{pub use gates::{complete_stage, gate_result, GateExecution, GateExecutions};pub use model::{CompleteStageParams, GateResultParams, ModeRun, SessionParams, StartParams};pub use policy::{authorization, tool_policy, tool_policy_conn, ToolPolicy};+pub use return_mode::settle_return;/// Mode ids are `^[a-z][a-z0-9-]{0,39}$`, shared with `MODE_ID_RE` in/// `packages/shared/src/mode-definition.ts`.@@ -55,3 +57,6 @@ mod snapshot_tests;#[cfg(test)]mod edit_tests;++#[cfg(test)]+mod return_mode_tests;diff --git a/crates/host-core/src/mode_runs/return_mode.rs b/crates/host-core/src/mode_runs/return_mode.rsnew file mode 100644index 000000000..26bb6380e--- /dev/null+++ b/crates/host-core/src/mode_runs/return_mode.rs@@ -0,0 +1,105 @@+//! Settling the session's mode after a run closed (ADR mode-definitions § 8).+//!+//! A closed run hands the session to its `returnTo` without a snapshot,+//! because only Electron main knows the current catalog. Without a snapshot+//! a custom mode resolves to the `Contract` policy, and a mode deleted during+//! the run leaves the session on an id the catalog no longer has. Main asks+//! which mode is pending and answers with that mode's current definition, or+//! with nothing when it no longer exists; the session then takes the+//! snapshot or falls back to `agent`.++use anyhow::Result;+use rusqlite::params;+use serde::Deserialize;+use serde_json::{json, Value};++use super::repository;+use super::snapshot;+use crate::db::{now_ms, Database};++/// `modes.settleReturn`. Without `mode` it only reports the pending return+/// mode. With `mode` (the reported id) it applies `modeSnapshot`, or the+/// `agent` fallback when the snapshot is absent.+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SettleReturnParams {+ pub session_id: String,+ pub run_id: String,+ #[serde(default)]+ pub mode: Option<String>,+ #[serde(default)]+ pub mode_snapshot: Option<Value>,+}++#[derive(Debug, PartialEq, Eq)]+pub enum SettleReturnResult {+ /// Nothing to settle: the run is open, the session moved on, or its mode+ /// needs no snapshot.+ Settled,+ /// The session waits on this return mode.+ Pending(String),+ /// The session now uses this mode.+ Applied(String),+}++impl SettleReturnResult {+ pub fn wire(&self) -> Value {+ match self {+ Self::Settled => json!({ "pending": null, "applied": null }),+ Self::Pending(mode) => json!({ "pending": mode, "applied": null }),+ Self::Applied(mode) => json!({ "pending": null, "applied": mode }),+ }+ }+}++/// The return mode the session still waits on, if any. The session must sit+/// on the run's `returnTo` with no snapshot, outside any open run.+fn pending(db: &Database, session_id: &str, run_id: &str) -> Result<Option<String>> {+ let conn = db.conn();+ let run = repository::owned(conn, session_id, run_id)?;+ if run.state.is_open() || repository::open_run(conn, session_id)?.is_some() {+ return Ok(None);+ }+ let return_to = snapshot::require(conn, &run.snapshot_hash)?+ .definition+ .return_to;+ if matches!(return_to.as_str(), "agent" | "plan") {+ return Ok(None);+ }+ let Some((mode, hash)) = repository::session_mode_row(conn, session_id)? else {+ return Ok(None);+ };+ Ok((mode == return_to && hash.is_none()).then_some(return_to))+}++pub fn settle_return(db: &Database, params: SettleReturnParams) -> Result<SettleReturnResult> {+ let Some(return_to) = pending(db, ¶ms.session_id, ¶ms.run_id)? else {+ return Ok(SettleReturnResult::Settled);+ };+ let Some(mode) = params.mode else {+ return Ok(SettleReturnResult::Pending(return_to));+ };+ if mode != return_to {+ return Ok(SettleReturnResult::Settled);+ }+ let conn = db.conn();+ let (next, hash) = match params.mode_snapshot.filter(|value| !value.is_null()) {+ Some(value) => {+ let snapshot = snapshot::validate(&value, &return_to)?;+ snapshot::store(conn, &snapshot)?;+ (return_to.clone(), Some(snapshot.hash))+ }+ None => ("agent".to_string(), None),+ };+ let changed = conn+ .prepare_cached(+ "UPDATE sessions SET mode = ?3, mode_snapshot_hash = ?4, updated_at = ?5+ WHERE id = ?1 AND mode = ?2 AND mode_snapshot_hash IS NULL",+ )?+ .execute(params![params.session_id, return_to, next, hash, now_ms()])?;+ Ok(if changed == 0 {+ SettleReturnResult::Settled+ } else {+ SettleReturnResult::Applied(next)+ })+}diff --git a/crates/host-core/src/mode_runs/return_mode_tests.rs b/crates/host-core/src/mode_runs/return_mode_tests.rsnew file mode 100644index 000000000..6715a4cba--- /dev/null+++ b/crates/host-core/src/mode_runs/return_mode_tests.rs@@ -0,0 +1,140 @@+//! A closed run's `returnTo` (#2204): a deleted mode falls back to `agent`,+//! an existing custom mode gets its snapshot and policy back.++use serde_json::{json, Value};++use super::model::*;+use super::return_mode::{SettleReturnParams, SettleReturnResult};+use super::tests::{control_run, definition, fixture, mode_row, session, start_run, Fixture};+use super::*;++fn returning_to(target: &str) -> Value {+ let mut def = definition(+ "feature",+ "contract",+ json!([{ "id": "work", "permission": "agent", "loop": true, "exit": [] }]),+ );+ def["returnTo"] = json!(target);+ def+}++fn review() -> Value {+ definition("review", "agent", json!([]))+}++/// A run of `feature` that the user stopped; the session sits on `review`.+fn closed_run(fx: &Fixture) -> (String, ModeRun) {+ let sid = session(fx, "agent");+ super::tests::configure(&fx.db, &sid, "feature", Some(&returning_to("review"))).unwrap();+ let run = start_run(fx, &sid, "t1").run;+ let stopped = control_run(fx, &run, ControlAction::Stop).unwrap().run;+ assert_eq!(mode_row(&fx.db, &sid), ("review".into(), None));+ (sid, stopped)+}++fn settle(+ fx: &Fixture,+ run: &ModeRun,+ mode: Option<&str>,+ snapshot: Option<Value>,+) -> SettleReturnResult {+ settle_return(+ &fx.db,+ SettleReturnParams {+ session_id: run.session_id.clone(),+ run_id: run.id.clone(),+ mode: mode.map(str::to_owned),+ mode_snapshot: snapshot,+ },+ )+ .unwrap()+}++#[test]+fn a_deleted_return_mode_falls_back_to_agent() {+ let fx = fixture();+ let (sid, run) = closed_run(&fx);+ // Without a snapshot the stranded custom id fails closed (the bug).+ assert_eq!(+ tool_policy(&fx.db, &sid).unwrap(),+ Some(ToolPolicy::Contract)+ );++ assert_eq!(+ settle(&fx, &run, None, None),+ SettleReturnResult::Pending("review".into())+ );+ assert_eq!(+ settle(&fx, &run, Some("review"), None),+ SettleReturnResult::Applied("agent".into())+ );+ assert_eq!(mode_row(&fx.db, &sid), ("agent".into(), None));+ assert_eq!(tool_policy(&fx.db, &sid).unwrap(), Some(ToolPolicy::Agent));+ assert_eq!(settle(&fx, &run, None, None), SettleReturnResult::Settled);+}++#[test]+fn an_existing_return_mode_gets_its_snapshot_and_policy() {+ let fx = fixture();+ let (sid, run) = closed_run(&fx);+ assert_eq!(+ settle(&fx, &run, Some("review"), Some(review())),+ SettleReturnResult::Applied("review".into())+ );+ let (mode, hash) = mode_row(&fx.db, &sid);+ assert_eq!(mode, "review");+ assert!(hash.is_some());+ assert_eq!(tool_policy(&fx.db, &sid).unwrap(), Some(ToolPolicy::Agent));+}++#[test]+fn settling_never_overrides_a_mode_the_user_chose() {+ let fx = fixture();+ let (sid, run) = closed_run(&fx);+ super::tests::configure(&fx.db, &sid, "plan", None).unwrap();+ assert_eq!(settle(&fx, &run, None, None), SettleReturnResult::Settled);+ assert_eq!(+ settle(&fx, &run, Some("review"), None),+ SettleReturnResult::Settled+ );+ assert_eq!(mode_row(&fx.db, &sid), ("plan".into(), None));+}++#[test]+fn an_open_run_or_a_builtin_return_mode_needs_nothing() {+ let fx = fixture();+ let sid = session(&fx, "agent");+ super::tests::configure(&fx.db, &sid, "feature", Some(&returning_to("review"))).unwrap();+ let open = start_run(&fx, &sid, "t1").run;+ assert_eq!(+ settle(&fx, &open, Some("feature"), None),+ SettleReturnResult::Settled+ );+ assert_eq!(mode_row(&fx.db, &sid).0, "feature");++ let other = session(&fx, "agent");+ super::tests::configure(&fx.db, &other, "feature", Some(&returning_to("agent"))).unwrap();+ let run = start_run(&fx, &other, "t1").run;+ let stopped = control_run(&fx, &run, ControlAction::Stop).unwrap().run;+ assert_eq!(+ settle(&fx, &stopped, None, None),+ SettleReturnResult::Settled+ );+}++#[test]+fn a_snapshot_for_another_mode_is_rejected() {+ let fx = fixture();+ let (sid, run) = closed_run(&fx);+ let err = settle_return(+ &fx.db,+ SettleReturnParams {+ session_id: sid.clone(),+ run_id: run.id.clone(),+ mode: Some("review".into()),+ mode_snapshot: Some(definition("other", "agent", json!([]))),+ },+ );+ assert!(err.is_err());+ assert_eq!(mode_row(&fx.db, &sid), ("review".into(), None));+}diff --git a/crates/host-core/src/rpc/modes_rpc.rs b/crates/host-core/src/rpc/modes_rpc.rsindex 26ad4b317..1254fc56e 100644--- a/crates/host-core/src/rpc/modes_rpc.rs+++ b/crates/host-core/src/rpc/modes_rpc.rs@@ -118,6 +118,10 @@ pub(super) async fn handle(let result = mode_runs::update(&st.db, parse(params)?).map_err(error)?;(result.wire(), result.changed.then_some(result.run))}+ "modes.settleReturn" => {+ let result = mode_runs::settle_return(&st.db, parse(params)?).map_err(error)?;+ return Ok(result.wire());+ }"modes.resolve" => {let result = mode_runs::resolve(&st.db, parse(params)?).map_err(error)?;(result.wire(), result.changed.then_some(result.run))diff --git a/docs/adr/mode-definitions.md b/docs/adr/mode-definitions.mdindex 4a4cce6ea..1b8bace3c 100644--- a/docs/adr/mode-definitions.md+++ b/docs/adr/mode-definitions.md@@ -216,6 +216,10 @@ One migration after the current schema:existing values `agent`, `plan` and `goal` map to the builtins. A sessionwhose mode no longer exists falls back to `agent`; an active run keeps itssnapshot.+ When a run closes, the Host returns the session to `returnTo` without a+ snapshot; Electron main then settles it through `modes.settleReturn`,+ attaching the return mode's current definition, or moving the session to+ `agent` when that mode was deleted during the run.- `mode_snapshots (hash, json)`: an immutable definition per run, so editing amode never changes a running run.- `mode_runs`: generalized from #2141 `session_goals`. Each row stores the mode,diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex e8309639f..ac4f7bf36 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -1633,6 +1633,7 @@ ADR `mode-definitions` adds the following Host methods. Parameters use camelCase| `modes.control` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; pause, resume, stop or remove. Stop and remove both end the run; Electron main interrupts the active turn only for stop || `modes.update` | `sessionId, runId, expectedRevision, input?, budget?` | `{ run, continue: false }`; edits an open run's input and `{ maxTurns, maxTokens }` budget (both fields required, `null` is unlimited), effective from the next claim || `modes.resolve` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; approve or reject |+| `modes.settleReturn` | `sessionId, runId, mode?, modeSnapshot?` | `{ pending, applied }`; after a run closed, reports the custom `returnTo` the session waits on (`pending`). Called again with that `mode`, it stores `modeSnapshot` for it, or moves the session to `agent` when the snapshot is absent because the mode no longer exists |`session.configure` accepts an optional validated `modeSnapshot`. Custom modeids require a snapshot. Agent and Plan retain their builtin policies. Hostdiff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex eaa2b7795..27113da9f 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@@ -1200,6 +1200,7 @@ ADR `mode-definitions` adds the following Host methods. Parameters use camelCase| `modes.control` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; pause, resume, stop or remove. Stop and remove both end the run; Electron main interrupts the active turn only for stop || `modes.update` | `sessionId, runId, expectedRevision, input?, budget?` | `{ run, continue: false }`; edits an open run's input and `{ maxTurns, maxTokens }` budget (both fields required, `null` is unlimited), effective from the next claim || `modes.resolve` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; approve or reject |+| `modes.settleReturn` | `sessionId, runId, mode?, modeSnapshot?` | `{ pending, applied }`; after a run closed, reports the custom `returnTo` the session waits on (`pending`). Called again with that `mode`, it stores `modeSnapshot` for it, or moves the session to `agent` when the snapshot is absent because the mode no longer exists |`session.configure` accepts an optional validated `modeSnapshot`. Custom modeids require a snapshot. Agent and Plan retain their builtin policies. Host