Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(session-collaboration): let the orchestrating plugin own worker concurrency
Tioit-Wang6dad8f87c9bb
diff --git a/crates/host-core/src/session_collaboration/mod.rs b/crates/host-core/src/session_collaboration/mod.rsindex 25c71e708..a72fd3cad 100644--- a/crates/host-core/src/session_collaboration/mod.rs+++ b/crates/host-core/src/session_collaboration/mod.rs@@ -116,8 +116,10 @@ fn spawn(db: &Database, input: &Value) -> Result<Value> {}return Ok(json!({"message":existing,"sessionId":existing.target_session_id}));}- // Worker limits are read inside the transaction so the counts cannot go- // stale between the check and the session/link inserts below.+ // Any further worker creation is refused below, so recursion cannot grow.+ // How many workers may run at once is the orchestrating plugin's call: the+ // host records who created a session and lets the plugin enforce its own+ // configured ceiling instead of a fixed one baked in here. ADR 0237.let tx = db.conn().unchecked_transaction()?;let is_worker: bool = db.conn().query_row("SELECT EXISTS(SELECT 1 FROM session_collaboration_links WHERE session_id=?1)",@@ -127,14 +129,6 @@ fn spawn(db: &Database, input: &Value) -> Result<Value> {if is_worker {return Err(anyhow!("PERMISSION_DENIED: workers may message existing sessions but cannot create further workers"));}- let (parent_active,plugin_active): (i64,i64) = db.conn().query_row(- "SELECT COALESCE(SUM(l.created_by_session_id=?1),0),COUNT(*) FROM session_collaboration_links l- WHERE l.plugin_id=?2 AND (EXISTS(SELECT 1 FROM turns t WHERE t.session_id=l.session_id AND t.status='running')- OR EXISTS(SELECT 1 FROM session_collaboration_messages m WHERE m.target_session_id=l.session_id AND m.status IN ('queued','running')))",- params![source,plugin],|row|Ok((row.get(0)?,row.get(1)?)))?;- if parent_active >= 4 || plugin_active >= 16 {- return Err(anyhow!("LIMIT_EXCEEDED: active worker limit reached"));- }let parent = sessions::get_session_with_options(db,source,diff --git a/crates/host-core/src/session_collaboration/settlement.rs b/crates/host-core/src/session_collaboration/settlement.rsindex a5981a20d..61a5bd60f 100644--- a/crates/host-core/src/session_collaboration/settlement.rs+++ b/crates/host-core/src/session_collaboration/settlement.rs@@ -197,10 +197,27 @@ pub(super) fn cancel(db: &Database, input: &Value) -> Result<Value> {/// The startup fence keeps received data but never replays an unclaimed or/// interrupted operation. Existing turn_queue rows are restored held by Agent Host.+///+/// Nothing will ever settle a run this fence closes, so a sender that opted into+/// the completion callback gets the receipt it is waiting for instead of waiting+/// forever. The callback key keeps repeated starts idempotent.pub fn recover(db: &Database) -> Result<()> {db.conn().execute("UPDATE session_collaboration_messages SET status='interrupted',error='Execution interrupted by application restart',updated_at=?1 WHERE status='running'OR (status='queued' AND NOT EXISTS(SELECT 1 FROM turn_queue q WHERE q.session_message_id=session_collaboration_messages.id))",params![now_ms()])?;+ let interrupted = {+ let mut statement = db.conn().prepare_cached(+ "SELECT id FROM session_collaboration_messages+ WHERE status='interrupted' AND notify_on_completion=1 AND kind<>'completion'",+ )?;+ let rows = statement.query_map([], |row| row.get::<_, String>(0))?;+ rows.collect::<rusqlite::Result<Vec<_>>>()?+ };+ for id in interrupted {+ if let Some(message) = repository::get(db, &id)? {+ callback(db, &message)?;+ }+ }Ok(())}diff --git a/crates/host-core/src/session_collaboration/tests.rs b/crates/host-core/src/session_collaboration/tests.rsindex 1223216d8..85d2b2ea8 100644--- a/crates/host-core/src/session_collaboration/tests.rs+++ b/crates/host-core/src/session_collaboration/tests.rs@@ -449,3 +449,87 @@ fn a_claim_that_loses_the_race_returns_conflict_and_rolls_back() {assert_eq!(turn_count(&db, &child), 0);assert_eq!(get(&db, &message.id).unwrap().unwrap().status, "queued");}++#[test]+fn a_parent_may_run_more_workers_than_the_old_fixed_cap_but_workers_cannot_recurse() {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let parent = session(&db, "Parent");+ let mut children = Vec::new();+ for index in 0..10 {+ let created = spawn(+ &db,+ &json!({+ "sourceSessionId":parent,"pluginId":"pi.session-orchestrator",+ "content":format!("Worker {index}"),"idempotencyKey":format!("worker-{index}"),+ "notifyOnCompletion":true+ }),+ )+ .unwrap();+ children.push(created["sessionId"].as_str().unwrap().to_string());+ }+ // The host records who created each worker and leaves the ceiling to the+ // orchestrating plugin instead of refusing the fifth one.+ assert_eq!(children.len(), 10);+ for child in &children {+ assert_eq!(+ sessions::session_mode(&db, child).unwrap().as_deref(),+ Some("agent")+ );+ }+ let denied = spawn(+ &db,+ &json!({+ "sourceSessionId":children[0],"pluginId":"pi.session-orchestrator",+ "content":"Grandchild","idempotencyKey":"grandchild","notifyOnCompletion":true+ }),+ )+ .unwrap_err();+ assert!(denied.to_string().starts_with("PERMISSION_DENIED"));+}++#[test]+fn a_restart_reports_an_interrupted_delivery_to_its_sender_once() {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let parent = session(&db, "Parent");+ let child = session(&db, "Child");+ let message = send(&db, &parent, &child, "one");+ let turn = begin_turn(&db, &child, &message.id, None, None).unwrap();+ recover(&db).unwrap();+ let interrupted = get(&db, &message.id).unwrap().unwrap();+ assert_eq!(interrupted.status, "interrupted");+ assert_eq!(interrupted.turn_id.as_deref(), Some(turn.as_str()));+ assert!(interrupted+ .error+ .as_deref()+ .unwrap()+ .contains("interrupted"));+ // The sender opted into the callback, so the fence emits the receipt it has+ // been waiting for instead of leaving the parent to poll forever.+ let receipt = |db: &Database| -> i64 {+ db.conn()+ .query_row(+ "SELECT COUNT(*) FROM session_collaboration_messages+ WHERE kind='completion' AND reply_to_message_id=?1",+ params![message.id],+ |row| row.get(0),+ )+ .unwrap()+ };+ assert_eq!(receipt(&db), 1);+ let content: String = db+ .conn()+ .query_row(+ "SELECT content FROM session_collaboration_messages+ WHERE kind='completion' AND reply_to_message_id=?1",+ params![message.id],+ |row| row.get(0),+ )+ .unwrap();+ assert!(content.contains("\"status\":\"interrupted\""), "{content}");+ assert!(content.contains("\"result\":null"), "{content}");+ recover(&db).unwrap();+ assert_eq!(receipt(&db), 1);+ assert_eq!(turn_count(&db, &child), 1);+}diff --git a/docs/adr/0237-session-orchestrator-as-a-plugin.md b/docs/adr/0237-session-orchestrator-as-a-plugin.mdindex b37c0bbf7..9171345d6 100644--- a/docs/adr/0237-session-orchestrator-as-a-plugin.md+++ b/docs/adr/0237-session-orchestrator-as-a-plugin.md@@ -38,8 +38,11 @@ Ship `pi.session-orchestrator` as an ordinary marketplace plugin. It registers t- A parent may control only Worker Session IDs recorded under its own sessionid. A `send` or `supervise` follow-up addresses those same Session IDs, so achild retains its own context without creating a replacement session. Worker- sessions cannot use the tool to create or control more workers. Active work- is capped at four workers per parent and sixteen across the plugin.+ sessions cannot use the tool to create or control more workers, and the host+ records which session created which worker. How many workers may run at once+ is the orchestrating plugin's own configured ceiling — `pi.session-orchestrator`+ defaults to 8 in its `maxConcurrentSessions` setting — because a fixed host+ constant forced every orchestration design into the same fan-out width.- Until a lifecycle subscription exists, `wait` performs one-second lightweightstatus polling with a 25-second default and 45-second maximum timeout. Eachdesktop read is bounded at five seconds, report transcript reads are deferred@@ -73,10 +76,19 @@ behavior remains intact, and plugin data can restore the relationship listafter a plugin or app restart.The first version does not receive lifecycle events and therefore has bounded-polling latency. The plugin also has a four-worker limit and does not provide-unscoped arbitrary-session control or worker-to-worker messaging. A dangerous-host operation is never used for orchestration; any future extension must-preserve the existing desktop-control permission and native-consent boundary.+polling latency. Concurrency is the plugin's own configurable ceiling, so the+host neither dictates a fan-out width nor silently truncates one; the plugin+does not provide unscoped arbitrary-session control or worker-to-worker+messaging. A dangerous host operation is never used for orchestration; any+future extension must preserve the existing desktop-control permission and+native-consent boundary.++The startup fence reports too. A delivery interrupted by an application restart+cannot ever settle, so `recover` emits the single completion receipt its sender+was waiting for instead of leaving an opted-in caller to poll a status that will+never change. The receipt carries `status: "interrupted"` and the fence's error+text; the existing `reply_to_message_id` unique index keeps repeated starts from+duplicating it.## Verificationdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 69ac7542f..6f3e4941e 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -1011,10 +1011,13 @@ invocation. The broker injects `pluginId`, source `sessionId`, source `turnId`,and an invocation identity; plugin arguments cannot supply or override thosevalues. A user-facing plugin panel may use `cancel` with its own pluginidentity, but cannot use that path to send or spawn work. The host enforces-the source permission ceiling, Agent-mode target, inbox and worker limits,-idempotency, and bounded autonomous hops. A requested completion callback is-a host-owned `completion` message linked to the source delivery and is created-at most once after the actual target turn settles.+the source permission ceiling, Agent-mode target, inbox bound, idempotency, and+bounded autonomous hops, and refuses a worker that tries to create a further+worker. How many workers run at once is the calling plugin's own policy: the+host records creator provenance and does not impose a fixed concurrency ceiling.+A requested completion callback is a host-owned `completion` message linked to+the source delivery and is created at most once after the actual target turn+settles, including a delivery fenced as `interrupted` by an application restart.The callback is session data, not a new user authorization, and completionmessages do not trigger another callback.diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex e85be700b..1d96667e7 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -836,8 +836,10 @@ Session ID,并复用该会话的项目、模型、上下文和权限配置;``spawn` 和 `send` 仅在插件当前 Agent 工具调用期间有效。broker 注入 `pluginId`、来源`sessionId`、来源 `turnId` 和调用身份;插件参数不能提供或覆盖这些字段。面向用户的插件面板可使用自有插件身份调用 `cancel`,但不能用该路径发送或创建工作。宿主执行来源权限-上限、Agent 模式目标、收件箱和 worker 限制、幂等性以及有界自主跳数。请求的完成回调是-宿主拥有的 `completion` 消息,链接到源投递,并且只在实际目标回合结算后最多创建一次。+上限、Agent 模式目标、收件箱上限、幂等性以及有界自主跳数,并拒绝子会话再创建子会话。+同时运行多少个 worker 由调用方插件自行决定:宿主只记录创建来源,不施加固定的并发上限。+请求的完成回调是宿主拥有的 `completion` 消息,链接到源投递,并且只在实际目标回合结算后+最多创建一次;被应用重启栅栏标记为 `interrupted` 的投递也一样会生成该回执。回调是会话数据,不是新的用户授权;完成消息不会触发另一个回调。渲染器可以读取单独的侧边栏协作投影,但插件面板不能绕过此网关调用变更操作。