Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): replace the work queue with phased dispatch_subagent + a blackboard
Akarshan Biswas03c7ced65566
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsindex 0aba8f1ef..179e45531 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -20,11 +20,7 @@ const COMMANDS: &[&str] = &["sandbox_status","subagent_result_reserve","subagent_result_fill",- "work_post",- "work_claim",- "work_complete",- "work_list",- "agent_read",+ "blackboard_write","attachment_import","execute_tool","execute_tool_streaming",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.tsindex 79e0e38e5..ab43eee26 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts@@ -296,72 +296,25 @@ export async function subagentResultFill(})}-/** One item on the shared work queue (mirrors the Rust `WorkItemView`). */-export type WorkItemView = {- workId: string- title: string- /** `open` | `claimed` | `done` | `failed` | `blocked`. */- state: string- claimedBy?: string- reason?: string-}--/** The result of a work-queue command: the model-facing message plus the fresh- * queue snapshot the store applies directly. */-export type WorkCommandResult = {- message: string- items: WorkItemView[]- /** The id a `workClaim` handed the caller, if any. */- claimed?: string-}--/** Post a task to `threadId`'s shared work queue. `args` is `{task, deps?, title?}`;- * `agentId` is the poster of record (`"main"` or a subagent run id). */-export async function workPost(- threadId: string,- agentId: string,- args: Record<string, unknown>-): Promise<WorkCommandResult> {- return await invoke('plugin:agent-tools|work_post', { threadId, agentId, args })-}--/** Claim the next ready item for `agentId`. */-export async function workClaim(- threadId: string,- agentId: string-): Promise<WorkCommandResult> {- return await invoke('plugin:agent-tools|work_claim', { threadId, agentId })-}--/** Complete an item `agentId` claimed. `args` is `{work_id, result}`. */-export async function workComplete(+/**+ * Write a finished subagent's answer to `<scratch>/blackboard/<name>.md` -- the+ * predictable, name-keyed coordination file a phased dispatch's next phase and+ * sibling agents read. Reserve + fill in one call (written only after the child+ * finishes). A re-dispatch of the same name truncates the earlier file in place.+ * Returns the model-visible path.+ */+export async function blackboardWrite(threadId: string,- agentId: string,- args: Record<string, unknown>-): Promise<WorkCommandResult> {- return await invoke('plugin:agent-tools|work_complete', {+ name: string,+ content: string+): Promise<string> {+ return await invoke('plugin:agent-tools|blackboard_write', {threadId,- agentId,- args,+ name,+ content,})}-/** The whole work queue as a snapshot, with a summary in `message`. */-export async function workList(threadId: string): Promise<WorkCommandResult> {- return await invoke('plugin:agent-tools|work_list', { threadId })-}--/** Read a peer's status + transcript, or the roster (no `run_id`). `args` is- * `{run_id?, tail?}`; the returned string is model-facing. `agentId` is the- * caller's own collaboration id, so the core can refuse a self-read. */-export async function agentRead(- threadId: string,- agentId: string,- args: Record<string, unknown>-): Promise<string> {- return await invoke('plugin:agent-tools|agent_read', { threadId, agentId, args })-}-/** An attachment copied into a session workspace. */export type ImportedAttachment = {/** The copy inside the workspace, readable by the agent's file tools. */diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.tomlindex eaf64f8d4..277c04754 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -22,11 +22,7 @@ permissions = ["allow-sandbox-status","allow-subagent-result-reserve","allow-subagent-result-fill",- "allow-work-post",- "allow-work-claim",- "allow-work-complete",- "allow-work-list",- "allow-agent-read",+ "allow-blackboard-write","allow-attachment-import","allow-execute-tool","allow-execute-tool-streaming",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.jsonindex 76f203544..09612084a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json@@ -294,18 +294,6 @@"PermissionKind": {"type": "string","oneOf": [- {- "description": "Enables the agent_read command without any pre-configured scope.",- "type": "string",- "const": "allow-agent-read",- "markdownDescription": "Enables the agent_read command without any pre-configured scope."- },- {- "description": "Denies the agent_read command without any pre-configured scope.",- "type": "string",- "const": "deny-agent-read",- "markdownDescription": "Denies the agent_read command without any pre-configured scope."- },{"description": "Enables the attachment_import command without any pre-configured scope.","type": "string",@@ -318,6 +306,18 @@"const": "deny-attachment-import","markdownDescription": "Denies the attachment_import command without any pre-configured scope."},+ {+ "description": "Enables the blackboard_write command without any pre-configured scope.",+ "type": "string",+ "const": "allow-blackboard-write",+ "markdownDescription": "Enables the blackboard_write command without any pre-configured scope."+ },+ {+ "description": "Denies the blackboard_write command without any pre-configured scope.",+ "type": "string",+ "const": "deny-blackboard-write",+ "markdownDescription": "Denies the blackboard_write command without any pre-configured scope."+ },{"description": "Enables the cancel_thread_bash command without any pre-configured scope.","type": "string",@@ -678,54 +678,6 @@"const": "deny-tool-schemas","markdownDescription": "Denies the tool_schemas command without any pre-configured scope."},- {- "description": "Enables the work_claim command without any pre-configured scope.",- "type": "string",- "const": "allow-work-claim",- "markdownDescription": "Enables the work_claim command without any pre-configured scope."- },- {- "description": "Denies the work_claim command without any pre-configured scope.",- "type": "string",- "const": "deny-work-claim",- "markdownDescription": "Denies the work_claim command without any pre-configured scope."- },- {- "description": "Enables the work_complete command without any pre-configured scope.",- "type": "string",- "const": "allow-work-complete",- "markdownDescription": "Enables the work_complete command without any pre-configured scope."- },- {- "description": "Denies the work_complete command without any pre-configured scope.",- "type": "string",- "const": "deny-work-complete",- "markdownDescription": "Denies the work_complete command without any pre-configured scope."- },- {- "description": "Enables the work_list command without any pre-configured scope.",- "type": "string",- "const": "allow-work-list",- "markdownDescription": "Enables the work_list command without any pre-configured scope."- },- {- "description": "Denies the work_list command without any pre-configured scope.",- "type": "string",- "const": "deny-work-list",- "markdownDescription": "Denies the work_list command without any pre-configured scope."- },- {- "description": "Enables the work_post command without any pre-configured scope.",- "type": "string",- "const": "allow-work-post",- "markdownDescription": "Enables the work_post command without any pre-configured scope."- },- {- "description": "Denies the work_post command without any pre-configured scope.",- "type": "string",- "const": "deny-work-post",- "markdownDescription": "Denies the work_post command without any pre-configured scope."- },{"description": "Enables the workspace_path command without any pre-configured scope.","type": "string",@@ -739,10 +691,10 @@"markdownDescription": "Denies the workspace_path command without any pre-configured scope."},{- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-work-post`\n- `allow-work-claim`\n- `allow-work-complete`\n- `allow-work-list`\n- `allow-agent-read`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`",+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-blackboard-write`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`","type": "string","const": "default",- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-work-post`\n- `allow-work-claim`\n- `allow-work-complete`\n- `allow-work-list`\n- `allow-agent-read`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`"+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-blackboard-write`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`"}]}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 34612bc49..00d549aa5 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -447,106 +447,35 @@ pub async fn subagent_result_fill(Ok(())}-/// The result of a work-queue command: the model-facing message the Cowork loop-/// feeds back to the model, plus the post-mutation queue snapshot the store-/// applies directly (so the rail updates without a separate poll).-#[derive(serde::Serialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkCommandResult {- pub message: String,- pub items: Vec<crate::tools::workqueue::WorkItemView>,- #[serde(skip_serializing_if = "Option::is_none")]- pub claimed: Option<String>,-}--/// Run one work-queue tool against a session's scratch and return its message +-/// the fresh snapshot. Host-side, mirroring the CLI loop's dispatch: names cross-/// the JS boundary and are re-validated inside the core (`is_work_id`), and no-/// host path is ever accepted.-async fn run_work(- thread_id: String,- name: &'static str,- args: serde_json::Value,- agent_id: String,-) -> Result<WorkCommandResult, AgentToolsError> {- let scratch = workspace::ensure_scratch_dir(&thread_id).await?;- tokio::task::spawn_blocking(move || {- let now = crate::tools::epoch_secs();- let res = crate::tools::workqueue::run_work_tool(&scratch, name, &args, &agent_id, now);- WorkCommandResult {- message: res.message,- items: crate::tools::workqueue::list_work_dir(&scratch),- claimed: res.claimed,- }- })- .await- .map_err(|e| AgentToolsError::from(format!("work tool failed: {e}")))-}--/// Post a task to the session's shared work queue. `args` is `{task, deps?,-/// title?}`; `agent_id` is the poster of record (`"main"` or a subagent run id).-#[tauri::command]-pub async fn work_post(- thread_id: String,- agent_id: String,- args: serde_json::Value,-) -> Result<WorkCommandResult, AgentToolsError> {- run_work(thread_id, "post_work", args, agent_id).await-}--/// Claim the next ready item for `agent_id`.-#[tauri::command]-pub async fn work_claim(- thread_id: String,- agent_id: String,-) -> Result<WorkCommandResult, AgentToolsError> {- run_work(- thread_id,- "claim_work",- serde_json::Value::Object(Default::default()),- agent_id,- )- .await-}--/// Complete an item `agent_id` claimed. `args` is `{work_id, result}`.+/// Write a finished subagent's answer to `<scratch>/blackboard/<name>.md`, the+/// predictable name-keyed coordination file a phased dispatch's next phase (and+/// sibling agents) read. Reserve + fill in one call: the Cowork scheduler writes+/// only after the child has finished, so there is nothing to claim ahead of time.+/// The name is re-validated and re-resolved under the session scratch; a stale+/// file from an earlier plan is truncated in place. Returns the model-visible+/// path (`spill::reserve_blackboard_result`).#[tauri::command]-pub async fn work_complete(+pub async fn blackboard_write(thread_id: String,- agent_id: String,- args: serde_json::Value,-) -> Result<WorkCommandResult, AgentToolsError> {- run_work(thread_id, "complete_work", args, agent_id).await-}--/// The whole work queue as a snapshot, with a model-facing summary in `message`.-#[tauri::command]-pub async fn work_list(thread_id: String) -> Result<WorkCommandResult, AgentToolsError> {- run_work(- thread_id,- "list_work",- serde_json::Value::Object(Default::default()),- String::new(),- )- .await-}--/// Read a peer's status + transcript, or the roster. `args` is `{run_id?, tail?}`.-/// Returns the model-facing text; a JS-supplied `run_id` is re-validated inside-/// the core (`is_agent_id`). `agent_id` is the caller's own id, so the core can-/// refuse an agent reading its own log (a no-op loop).-#[tauri::command]-pub async fn agent_read(- thread_id: String,- agent_id: String,- args: serde_json::Value,+ name: String,+ content: String,) -> Result<String, AgentToolsError> {let scratch = workspace::ensure_scratch_dir(&thread_id).await?;tokio::task::spawn_blocking(move || {- crate::tools::observ::run_read_agent(&scratch, &args, &agent_id)+ let path = crate::tools::spill::reserve_blackboard_result(&scratch, &name)+ .ok_or_else(|| {+ AgentToolsError::from("could not claim a blackboard file".to_string())+ })?;+ if crate::tools::spill::fill_subagent_result(&path, &content) {+ Ok(crate::tools::sandbox::scratch_display_path(Some(&scratch), &path))+ } else {+ Err(AgentToolsError::from(+ "could not write the blackboard file".to_string(),+ ))+ }}).await- .map_err(|e| AgentToolsError::from(format!("agent read failed: {e}")))+ .map_err(|e| AgentToolsError::from(format!("blackboard write failed: {e}")))?}/// An attachment imported into a session workspace: host paths, which are alsodiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 44ee4163a..7765e0650 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -63,11 +63,7 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::sandbox_status,commands::subagent_result_reserve,commands::subagent_result_fill,- commands::work_post,- commands::work_claim,- commands::work_complete,- commands::work_list,- commands::agent_read,+ commands::blackboard_write,commands::attachment_import,commands::execute_tool,commands::execute_tool_streaming,diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 4f58ab4d8..456ae01c1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -16,10 +16,6 @@ pub mod jail;/// The `monitor` tool's core: file watching + condition-script evaluation./// Loop-dispatched (like the subagent tools), so it is not in `BUILTIN_TOOLS`.pub mod monitor;-/// Per-agent live transcript + status header, written into the collaboration-/// scratch so peers and the main agent can read what an agent is doing while it-/// still runs. Loop-dispatched read side (`read_agent`); not in `BUILTIN_TOOLS`.-pub mod observ;pub mod proc;/// Path containment for the filesystem tools. Distinct from [`jail`], which is/// kernel-level confinement for spawned commands.@@ -27,13 +23,8 @@ pub mod sandbox;pub mod schema;pub mod spill;pub mod web;-/// The shared work queue's core: file-mediated task posting/claiming/completing-/// among the main agent and its depth-1 workers. Loop-dispatched like the-/// subagent and monitor tools, so it is not in `BUILTIN_TOOLS`.-pub mod workqueue;-/// Epoch seconds, saturating to 0 before the epoch. The one clock the-/// collaboration cores (`workqueue`, `observ`) stamp files and leases with.+/// Epoch seconds, saturating to 0 before the epoch, used to stamp spill files.pub fn epoch_secs() -> u64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/observ.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/observ.rsdeleted file mode 100644index a7e8aa0c7..000000000--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/observ.rs+++ /dev/null@@ -1,584 +0,0 @@-//! Shared per-agent observability: a live transcript and a compact status-//! header every agent (the main run and each subagent) writes into the run's-//! collaboration scratch, so any peer, the main agent, or the user can read-//! what another agent is doing while it is still running.-//!-//! This is the machine-and-peer-readable record, distinct from the human-//! display journal (`core::cli::journal`): the journal is the top-level run's-//! transcript replayed on `/resume`; these files are per-child, read mid-flight,-//! and swept with the scratch. They meet only at the one-line `SubagentEnd`-//! summary the journal still owns.-//!-//! Every path reuses the same fail-closed discipline as `spill.rs`:-//! [`validated_subdir`] per directory, [`open_excl`] for a first write,-//! `symlink_metadata` real-file re-checks before a read, and atomic temp+rename-//! for the status header so a reader never sees a torn write.--use std::io::Write;-use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};--use crate::tools::spill::{- open_excl, open_truncating, sanitize_stem, validated_subdir, SUBAGENT_DIR,-};--/// Bytes a single `transcript.jsonl` may reach before it rotates to-/// `transcript.1.jsonl` (one prior generation kept). Bounds scratch growth for-/// a long-running worker at ~2x this.-pub const TRANSCRIPT_MAX_BYTES: u64 = 256 * 1024;--/// Transcript lines returned by default when a reader does not ask for a count.-pub const DEFAULT_TAIL_LINES: usize = 40;-/// Ceiling on the tail a reader may request, so one `read_agent` cannot pull an-/// unbounded slice into the model's context.-pub const MAX_TAIL_LINES: usize = 200;--/// The agent lifecycle states a `status.json` header reports.-pub const STATE_QUEUED: &str = "queued";-pub const STATE_RUNNING: &str = "running";-pub const STATE_PARKED: &str = "parked";-pub const STATE_BLOCKED: &str = "blocked";-pub const STATE_DONE: &str = "done";-pub const STATE_FAILED: &str = "failed";--/// The compact header a reader learns an agent's state from without touching the-/// transcript. Doubles as the on-disk `status.json`, the roster entry, and the-/// payload of a `StreamEvent::AgentStatus`.-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct AgentStatusView {- pub run_id: String,- pub name: String,- /// One of the `STATE_*` constants.- pub state: String,- /// Model turns taken so far.- pub step: u64,- /// Tool calls issued so far.- pub tool_calls: u64,- /// One-line summary of the most recent activity.- pub last: String,- /// The work item this agent currently holds, if any.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub work_id: Option<String>,- /// Epoch seconds of the last write; the heartbeat a claim lease reads.- pub updated_at: u64,- /// Transcript lines written since the last rotation.- pub lines: u64,- /// Number of rotations so far (older lines dropped from the tail).- pub dropped: u64,-}--impl AgentStatusView {- /// A fresh `queued` header for a just-created agent.- pub fn new(run_id: &str, name: &str, now: u64) -> Self {- Self {- run_id: run_id.to_string(),- name: name.to_string(),- state: STATE_QUEUED.to_string(),- step: 0,- tool_calls: 0,- last: String::new(),- work_id: None,- updated_at: now,- lines: 0,- dropped: 0,- }- }-}--/// A caller-supplied id names a single component under `subagents/`: `main`, or-/// a `sub-<name>-<seq>` run id. Charset and length mirror `is_result_file_name`-/// in `spill.rs`; a leading dot is refused so it can never be a dotfile.-pub fn is_agent_id(id: &str) -> bool {- if id == "main" {- return true;- }- !id.is_empty()- && id.len() <= 96- && !id.starts_with('.')- && id- .chars()- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))-}--/// `<scratch>/subagents/<run_id>/`, created if missing. Used by the writers.-pub fn agent_run_dir(scratch: &Path, run_id: &str) -> Option<PathBuf> {- let base = validated_subdir(scratch, SUBAGENT_DIR)?;- validated_subdir(&base, &sanitize_stem(run_id))-}--/// `<scratch>/subagents/<run_id>/` only if it already exists as a real dir.-/// Readers never create.-fn agent_dir_existing(scratch: &Path, run_id: &str) -> Option<PathBuf> {- let dir = scratch.join(SUBAGENT_DIR).join(sanitize_stem(run_id));- match std::fs::symlink_metadata(&dir) {- Ok(m) if m.is_dir() && !m.file_type().is_symlink() => Some(dir),- _ => None,- }-}--fn subagents_dir_existing(scratch: &Path) -> Option<PathBuf> {- let dir = scratch.join(SUBAGENT_DIR);- match std::fs::symlink_metadata(&dir) {- Ok(m) if m.is_dir() && !m.file_type().is_symlink() => Some(dir),- _ => None,- }-}--/// Read a path only if it is a real file (not a symlink the shell may have-/// planted), the exact guard `fill_subagent_result` uses before a write.-fn read_real_to_string(path: &Path) -> Option<String> {- match std::fs::symlink_metadata(path) {- Ok(m) if m.is_file() && !m.file_type().is_symlink() => std::fs::read_to_string(path).ok(),- _ => None,- }-}--/// Append-only transcript writer. Created once at agent start via [`open_excl`]-/// (so a planted file/symlink is refused); the `File` handle is retained for the-/// agent's whole life, so appends hit the inode and survive a later path swap.-pub struct TranscriptWriter {- file: std::fs::File,- path: PathBuf,- prev_path: PathBuf,- bytes: u64,- dropped: u64,- lines: u64,-}--impl TranscriptWriter {- /// Open `subagents/<run_id>/transcript.jsonl` for the run's lifetime.- ///- /// On `AlreadyExists` (a `/resume` reusing surviving scratch minted the same- /// process-reset run id), truncate-to-own iff the existing node is an- /// ordinary file we own by convention; a symlink or non-file fails closed.- pub fn create(scratch: &Path, run_id: &str) -> Option<Self> {- let dir = agent_run_dir(scratch, run_id)?;- let path = dir.join("transcript.jsonl");- let prev_path = dir.join("transcript.1.jsonl");- let file = match open_excl(&path) {- Ok(f) => f,- Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {- match std::fs::symlink_metadata(&path) {- Ok(m) if m.is_file() && !m.file_type().is_symlink() => {- open_truncating(&path).ok()?- }- _ => return None,- }- }- Err(_) => return None,- };- Some(Self {- file,- path,- prev_path,- bytes: 0,- dropped: 0,- lines: 0,- })- }-- /// Append one whole `\n`-terminated JSON line. `kind` mirrors a- /// `StreamEvent` kind (`step`/`tool_call`/`tool_result`/`work`); `err`- /// distinguishes a failed tool result. A single `write_all`, so a concurrent- /// tail sees either the whole line or nothing after the last terminator.- pub fn append(&mut self, kind: &str, detail: &str, err: Option<bool>) {- let entry = TranscriptLine {- t: crate::tools::epoch_secs(),- k: kind,- d: detail,- err,- };- let Ok(mut line) = serde_json::to_string(&entry) else {- return;- };- line.push('\n');- let len = line.len() as u64;- if self.bytes.saturating_add(len) > TRANSCRIPT_MAX_BYTES {- self.rotate();- }- if self.file.write_all(line.as_bytes()).is_ok() {- self.bytes = self.bytes.saturating_add(len);- self.lines = self.lines.saturating_add(1);- }- }-- /// Rename the live log to `transcript.1.jsonl` and reopen fresh. Best-effort:- /// if either step fails the old handle keeps taking appends.- fn rotate(&mut self) {- if std::fs::rename(&self.path, &self.prev_path).is_err() {- return;- }- if let Ok(f) = open_excl(&self.path) {- self.file = f;- self.bytes = 0;- self.lines = 0;- self.dropped = self.dropped.saturating_add(1);- }- }-- pub fn dropped(&self) -> u64 {- self.dropped- }-- pub fn lines(&self) -> u64 {- self.lines- }-}--#[derive(serde::Serialize)]-struct TranscriptLine<'a> {- t: u64,- k: &'a str,- d: &'a str,- #[serde(skip_serializing_if = "Option::is_none")]- err: Option<bool>,-}--/// Rewrite `subagents/<run_id>/status.json` atomically: [`open_excl`] a unique-/// temp then `rename` over the header, so a reader always sees a whole file.-pub fn write_status(scratch: &Path, status: &AgentStatusView) -> bool {- let Some(dir) = agent_run_dir(scratch, &status.run_id) else {- return false;- };- let final_path = dir.join("status.json");- static NONCE: AtomicU64 = AtomicU64::new(1);- let nonce = NONCE.fetch_add(1, Ordering::Relaxed);- let tmp = dir.join(format!("status.json.tmp-{}-{nonce}", std::process::id()));- let mut file = match open_excl(&tmp) {- Ok(f) => f,- Err(_) => return false,- };- if serde_json::to_writer(&mut file, status).is_err() {- drop(file);- let _ = std::fs::remove_file(&tmp);- return false;- }- drop(file);- if std::fs::rename(&tmp, &final_path).is_err() {- let _ = std::fs::remove_file(&tmp);- return false;- }- true-}--/// The cheap read: an agent's status header, or `None` if it has none.-pub fn read_status(scratch: &Path, run_id: &str) -> Option<AgentStatusView> {- let dir = agent_dir_existing(scratch, run_id)?;- let raw = read_real_to_string(&dir.join("status.json"))?;- serde_json::from_str(&raw).ok()-}--/// The last `max_lines` complete transcript lines. A trailing fragment with no-/// newline terminator (a torn concurrent append) is dropped, so a reader never-/// parses half a line; the next append completes it.-pub fn tail_transcript(scratch: &Path, run_id: &str, max_lines: usize) -> Option<String> {- let dir = agent_dir_existing(scratch, run_id)?;- let content = read_real_to_string(&dir.join("transcript.jsonl"))?;- let mut parts: Vec<&str> = content.split('\n').collect();- // A complete log ends with '\n' (last element ""); an incomplete one ends- // with a fragment. Either way the last element is not a whole line.- parts.pop();- let lines: Vec<&str> = parts.into_iter().filter(|l| !l.is_empty()).collect();- let start = lines.len().saturating_sub(max_lines.min(MAX_TAIL_LINES));- Some(lines[start..].join("\n"))-}--/// One status header per agent that has one, ordered by run id. The roster a-/// `read_agent{}` with no id returns.-pub fn roster(scratch: &Path) -> Vec<AgentStatusView> {- let Some(base) = subagents_dir_existing(scratch) else {- return Vec::new();- };- let mut out = Vec::new();- if let Ok(rd) = std::fs::read_dir(&base) {- for entry in rd.flatten() {- let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);- if !is_dir {- continue;- }- if let Some(name) = entry.file_name().to_str() {- if let Some(status) = read_status(scratch, name) {- out.push(status);- }- }- }- }- out.sort_by(|a, b| a.run_id.cmp(&b.run_id));- out-}--/// The loop-dispatched shared-observability tool name (not a built-in).-pub const READ_AGENT_TOOL: &str = "read_agent";--/// OpenAI tool schema for `read_agent`.-pub fn read_agent_tool_schema() -> serde_json::Value {- serde_json::json!({- "type": "function",- "function": {- "name": READ_AGENT_TOOL,- "description": "See what another agent is doing. With no run_id, returns a roster of every agent (the main agent and each worker) with its current state. With a run_id, returns that agent's status plus the tail of its live activity log -- use it to check on a worker mid-flight.",- "parameters": {- "type": "object",- "properties": {- "run_id": { "type": "string", "description": "The agent to inspect (from the roster). Omit for the full roster." },- "tail": { "type": "integer", "description": "How many recent log lines to include (default 40, max 200)." }- }- }- }- })-}--/// Run a `read_agent` call and format its model-facing result. Shared by the-/// CLI loop and the desktop/Cowork command layer. `self_id` is the caller's own-/// collaboration id (`"main"` or a `sub-...` run id): an agent reading its own-/// log is a no-op loop -- the last line it gets back is the `read_agent` call it-/// just made -- so any surface passes its caller here and the read is refused.-pub fn run_read_agent(scratch: &Path, args: &serde_json::Value, self_id: &str) -> String {- let run_id = args- .get("run_id")- .and_then(|v| v.as_str())- .map(str::trim)- .filter(|s| !s.is_empty());- match run_id {- Some(id) if id == self_id => {- "ERROR: that run_id is you. read_agent inspects *other* agents; reading your own log \- tells you nothing. If your task is done, report your result (call complete_work, or \- give your final answer) instead of polling."- .to_string()- }- None => {- let r = roster(scratch);- if r.is_empty() {- return "No agents are registered yet.".to_string();- }- let mut out = String::from("Agents:");- for s in r {- out.push_str(&format!(- "\n- {} ({}) [{}] step {}, {} tool calls{}{}",- s.name,- s.run_id,- s.state,- s.step,- s.tool_calls,- s.work_id- .as_ref()- .map(|w| format!(", on {w}"))- .unwrap_or_default(),- if s.last.is_empty() {- String::new()- } else {- format!(" -- {}", s.last)- }- ));- }- out- }- Some(id) => {- if !is_agent_id(id) {- return format!("ERROR: invalid run_id {id}");- }- let Some(status) = read_status(scratch, id) else {- return format!(- "No agent {id} found. Call read_agent with no run_id to see the roster."- );- };- let tail = args- .get("tail")- .and_then(|v| v.as_u64())- .map(|n| (n as usize).min(MAX_TAIL_LINES))- .unwrap_or(DEFAULT_TAIL_LINES);- let mut out = format!(- "{} ({}) [{}] step {}, {} tool calls{}.",- status.name,- status.run_id,- status.state,- status.step,- status.tool_calls,- status- .work_id- .as_ref()- .map(|w| format!(", on {w}"))- .unwrap_or_default()- );- if !status.last.is_empty() {- out.push_str(&format!("\nLast: {}", status.last));- }- if let Some(lines) = tail_transcript(scratch, id, tail) {- if !lines.is_empty() {- out.push_str(&format!("\n\nRecent activity:\n{lines}"));- }- }- out- }- }-}--#[cfg(test)]-mod tests {- use super::*;- use std::sync::atomic::AtomicUsize;-- fn tmp(tag: &str) -> PathBuf {- static N: AtomicUsize = AtomicUsize::new(0);- let n = N.fetch_add(1, Ordering::SeqCst);- let dir = std::env::temp_dir().join(format!("jan-observ-{tag}-{}-{n}", std::process::id()));- std::fs::create_dir_all(&dir).unwrap();- dir- }-- #[test]- fn accepts_main_and_run_ids_rejects_hostile() {- assert!(is_agent_id("main"));- assert!(is_agent_id("sub-reviewer-3"));- assert!(!is_agent_id(""));- assert!(!is_agent_id(".hidden"));- assert!(!is_agent_id("../escape"));- assert!(!is_agent_id("a/b"));- }-- #[test]- fn status_round_trips_atomically() {- let scratch = tmp("status");- let mut s = AgentStatusView::new("sub-a-1", "a", 100);- s.state = STATE_RUNNING.to_string();- s.step = 4;- s.tool_calls = 12;- s.last = "edit src/auth.rs".to_string();- s.work_id = Some("w-7".to_string());- assert!(write_status(&scratch, &s));- let back = read_status(&scratch, "sub-a-1").unwrap();- assert_eq!(back, s);- // No temp files linger.- let dir = scratch.join("subagents/sub-a-1");- let leftover: Vec<_> = std::fs::read_dir(&dir)- .unwrap()- .flatten()- .filter(|e| e.file_name().to_string_lossy().contains(".tmp-"))- .collect();- assert!(leftover.is_empty(), "temp file left behind");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn transcript_appends_and_tails_dropping_a_torn_line() {- let scratch = tmp("tail");- {- let mut w = TranscriptWriter::create(&scratch, "sub-a-1").unwrap();- w.append("step", "1", None);- w.append("tool_call", "edit {\"path\":\"a.rs\"}", None);- w.append("tool_result", "ok", Some(false));- }- // Simulate a torn trailing append (no newline terminator).- let path = scratch.join("subagents/sub-a-1/transcript.jsonl");- let mut f = std::fs::OpenOptions::new()- .append(true)- .open(&path)- .unwrap();- f.write_all(b"{\"t\":1,\"k\":\"step\",\"d\":\"tor").unwrap();- drop(f);- let tail = tail_transcript(&scratch, "sub-a-1", 10).unwrap();- let lines: Vec<&str> = tail.lines().collect();- assert_eq!(lines.len(), 3, "torn fragment dropped: {tail}");- assert!(lines[0].contains("\"k\":\"step\""));- assert!(lines[2].contains("tool_result"));- let _ = std::fs::remove_dir_all(&scratch);- }-- #[cfg(unix)]- #[test]- fn refuses_to_read_through_a_swapped_link() {- let scratch = tmp("swap");- let host = tmp("swap-host").join("secret");- std::fs::write(&host, "original").unwrap();- // Create the agent dir, then plant a link where status.json would be.- let dir = agent_run_dir(&scratch, "sub-a-1").unwrap();- std::os::unix::fs::symlink(&host, dir.join("status.json")).unwrap();- assert!(read_status(&scratch, "sub-a-1").is_none());- let _ = std::fs::remove_dir_all(&scratch);- let _ = std::fs::remove_dir_all(host.parent().unwrap());- }-- #[test]- fn create_reclaims_a_stale_transcript_on_resume() {- let scratch = tmp("resume");- {- let mut w = TranscriptWriter::create(&scratch, "sub-a-1").unwrap();- w.append("step", "old", None);- }- // A new process minting the same run id reopens truncate-to-own.- {- let mut w = TranscriptWriter::create(&scratch, "sub-a-1").unwrap();- w.append("step", "new", None);- }- let tail = tail_transcript(&scratch, "sub-a-1", 10).unwrap();- assert!(tail.contains("\"d\":\"new\""), "{tail}");- assert!(- !tail.contains("\"d\":\"old\""),- "stale lines survived: {tail}"- );- let _ = std::fs::remove_dir_all(&scratch);- }-- #[cfg(unix)]- #[test]- fn create_refuses_a_planted_transcript_symlink() {- let scratch = tmp("plant");- let host = tmp("plant-host").join("target");- std::fs::write(&host, "x").unwrap();- let dir = agent_run_dir(&scratch, "sub-a-1").unwrap();- std::os::unix::fs::symlink(&host, dir.join("transcript.jsonl")).unwrap();- assert!(TranscriptWriter::create(&scratch, "sub-a-1").is_none());- assert_eq!(std::fs::read_to_string(&host).unwrap(), "x");- let _ = std::fs::remove_dir_all(&scratch);- let _ = std::fs::remove_dir_all(host.parent().unwrap());- }-- #[test]- fn rotation_bumps_dropped_and_keeps_one_prior_generation() {- let scratch = tmp("rotate");- let mut w = TranscriptWriter::create(&scratch, "sub-a-1").unwrap();- let big = "x".repeat(2000);- // Enough lines to force at least one rotation.- for _ in 0..200 {- w.append("tool_result", &big, Some(false));- }- assert!(w.dropped() >= 1, "expected a rotation");- let dir = scratch.join("subagents/sub-a-1");- assert!(dir.join("transcript.jsonl").exists());- assert!(dir.join("transcript.1.jsonl").exists());- drop(w);- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn refuses_reading_your_own_log() {- let scratch = tmp("selfread");- assert!(write_status(&scratch, &AgentStatusView::new("sub-a-1", "a", 100)));- // A peer can read it.- let peer = run_read_agent(&scratch, &serde_json::json!({ "run_id": "sub-a-1" }), "main");- assert!(peer.contains("sub-a-1"), "{peer}");- // Reading yourself is refused, whoever you are.- let own = run_read_agent(&scratch, &serde_json::json!({ "run_id": "sub-a-1" }), "sub-a-1");- assert!(own.starts_with("ERROR") && own.contains("you"), "{own}");- let main = run_read_agent(&scratch, &serde_json::json!({ "run_id": "main" }), "main");- assert!(main.starts_with("ERROR"), "main cannot read itself either: {main}");- // The roster (no run_id) is not a self-read and still works.- let roster = run_read_agent(&scratch, &serde_json::json!({}), "sub-a-1");- assert!(roster.contains("Agents"), "{roster}");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn roster_lists_every_agent_header() {- let scratch = tmp("roster");- for (id, name) in [("main", "main"), ("sub-a-1", "a"), ("sub-b-1", "b")] {- let s = AgentStatusView::new(id, name, 100);- assert!(write_status(&scratch, &s));- }- let r = roster(&scratch);- let ids: Vec<&str> = r.iter().map(|s| s.run_id.as_str()).collect();- assert_eq!(ids, vec!["main", "sub-a-1", "sub-b-1"]);- let _ = std::fs::remove_dir_all(&scratch);- }-}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rsindex 7a49671be..d4abc94e0 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs@@ -110,6 +110,32 @@ pub fn reserve_subagent_result(scratch: &Path, id: &str) -> Option<PathBuf> {None}+/// Scratch subdirectory holding the shared blackboard: one `<name>.md` per+/// subagent, the coordination surface a phased dispatch reads from and writes to.+pub const BLACKBOARD_DIR: &str = "blackboard";++/// Reserve `<scratch>/blackboard/<name>.md` as an empty file, returning the host+/// path. Unlike [`reserve_subagent_result`], the name is predictable and stable:+/// it is how the next phase and sibling agents find this subagent's answer, so a+/// stale file left by an earlier plan is truncated in place rather than suffixed.+/// A pre-planted symlink at the leaf is still refused.+pub fn reserve_blackboard_result(scratch: &Path, name: &str) -> Option<PathBuf> {+ let dir = validated_subdir(scratch, BLACKBOARD_DIR)?;+ let path = dir.join(format!("{}.md", sanitize_stem(name)));+ match open_excl(&path) {+ Ok(_) => Some(path),+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {+ match std::fs::symlink_metadata(&path) {+ Ok(m) if m.is_file() && !m.file_type().is_symlink() => {+ open_truncating(&path).ok().map(|_| path)+ }+ _ => None,+ }+ }+ Err(_) => None,+ }+}+/// Fill a path [`reserve_subagent_result`] handed out. The shell could have/// swapped our empty file for a link in the meantime, so the same fail-closed/// re-check applies: write only to a real file, never through a redirect.@@ -125,9 +151,7 @@ pub fn fill_subagent_result(path: &Path, text: &str) -> bool {}/// `create(false)`: the file must be the one we reserved, so a path that has-/// since been removed is a failure rather than something to recreate. Shared-/// with `observ`'s resume-collision reclaim, which truncates an owned stale-/// transcript rather than suffixing a new run id.+/// since been removed is a failure rather than something to recreate.pub(crate) fn open_truncating(path: &Path) -> std::io::Result<std::fs::File> {std::fs::OpenOptions::new().write(true)@@ -228,6 +252,22 @@ mod tests {let _ = std::fs::remove_dir_all(&scratch);}+ /// The blackboard path is name-keyed and predictable, and a re-dispatch of+ /// the same name truncates the earlier file rather than suffixing it -- so+ /// the next phase always reads it at the one path it was told.+ #[test]+ fn blackboard_is_name_keyed_and_reused_in_place() {+ let scratch = tmp("bb");+ let a = reserve_blackboard_result(&scratch, "research").unwrap();+ assert_eq!(a, scratch.join("blackboard/research.md"));+ assert!(fill_subagent_result(&a, "first"));+ // A later reservation of the same name yields the SAME path, truncated.+ let b = reserve_blackboard_result(&scratch, "research").unwrap();+ assert_eq!(a, b);+ assert_eq!(std::fs::read_to_string(&b).unwrap(), "");+ let _ = std::fs::remove_dir_all(&scratch);+ }+#[cfg(unix)]#[test]fn refuses_to_fill_through_a_swapped_link() {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/workqueue.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/workqueue.rsdeleted file mode 100644index 56aef3cdf..000000000--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/workqueue.rs+++ /dev/null@@ -1,962 +0,0 @@-//! The shared work queue: a file-mediated corkboard under the run's-//! collaboration scratch that lets the main agent and its depth-1 workers-//! load-balance a set of tasks.-//!-//! `post_work` pins a card; a worker `claim_work`s the top ready card (a single-//! [`open_excl`] create is the mutex, so no two workers claim one item),-//! does it, then `complete_work`s the result. Producer/consumer handoff is-//! `deps`: an item is claimable only once every dep completed `ok=true`; a dep-//! that failed makes its item unsatisfiable, which `claim_work` fails-//! transitively rather than leaving to dangle.-//!-//! Every path reuses `spill.rs`: [`validated_subdir`] per directory,-//! [`open_excl`] for every new file, `symlink_metadata` real-file re-checks-//! before a read, and [`compose_subagent_result`] to bound the dep inputs-//! delivered inline to a claiming worker.--use std::io::Write;-use std::path::{Path, PathBuf};--use crate::tools::sandbox::scratch_display_path;-use crate::tools::spill::{compose_subagent_result, open_excl, validated_subdir};--/// Scratch subdirectory holding the whole queue.-pub const WORKQUEUE_DIR: &str = "workqueue";-/// Cap on open (not-yet-done) items, so a runaway poster cannot flood scratch-/// or the display snapshot.-pub const WORKQUEUE_MAX_OPEN: usize = 256;-/// A claim older than this (with no completion) is reclaimable even if the-/// claimer's liveness cannot be read, so a hard-killed worker never wedges an-/// item forever.-pub const CLAIM_LEASE_SECS: u64 = 300;-/// Cap on the id-minting retry loop under concurrent posters.-const POST_ATTEMPTS: u64 = 1024;--/// Display/wire view of one work item. Mirrors `MonitorSnapshot`'s role: the-/// payload of `StreamEvent::WorkQueue`, the `list_work` return, and the Cowork-/// rail row all read this one shape.-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct WorkItemView {- pub work_id: String,- pub title: String,- /// `open` (ready, unclaimed) | `claimed` | `done` | `failed` | `blocked`.- pub state: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub claimed_by: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub reason: Option<String>,-}--/// The outcome of a `claim_work` call.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum ClaimOutcome {- /// An item was claimed by the caller; `deps_results` carries each dep's- /// completed result, inline-bounded via [`compose_subagent_result`].- Claimed {- work_id: String,- task: String,- deps_results: Vec<(String, String)>,- },- /// Nothing is ready and nothing is waiting: the worker should stop.- Empty,- /// Every ready-looking item is waiting on an in-progress dep; the worker- /// should stop and let the main agent re-dispatch when a dep completes.- Blocked(Vec<String>),- /// The queue could not be opened.- Error(String),-}--#[derive(serde::Serialize, serde::Deserialize)]-struct OpenSpec {- work_id: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- title: Option<String>,- task: String,- #[serde(default)]- deps: Vec<String>,- posted_by: String,- posted_at: u64,-}--#[derive(serde::Serialize, serde::Deserialize)]-struct ClaimMarker {- work_id: String,- claimed_by: String,- claimed_at: u64,-}--#[derive(serde::Serialize, serde::Deserialize)]-struct DoneMarker {- work_id: String,- by: String,- ok: bool,- #[serde(default, skip_serializing_if = "Option::is_none")]- reason: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- result_file: Option<String>,- done_at: u64,-}--/// `w-<n>` shape, so a weak model can name it in `deps`.-pub fn is_work_id(id: &str) -> bool {- id.len() <= 24 && work_id_num(id).is_some()-}--fn work_id_num(id: &str) -> Option<u64> {- id.strip_prefix("w-").and_then(|n| n.parse::<u64>().ok())-}--fn ensure_dirs(scratch: &Path) -> Option<(PathBuf, PathBuf, PathBuf)> {- let base = validated_subdir(scratch, WORKQUEUE_DIR)?;- let open = validated_subdir(&base, "open")?;- let claimed = validated_subdir(&base, "claimed")?;- let done = validated_subdir(&base, "done")?;- Some((open, claimed, done))-}--fn write_new_json<T: serde::Serialize>(path: &Path, value: &T) -> std::io::Result<()> {- let mut file = open_excl(path)?;- let bytes = serde_json::to_vec(value)- .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;- file.write_all(&bytes)-}--fn read_real_json<T: serde::de::DeserializeOwned>(path: &Path) -> Option<T> {- match std::fs::symlink_metadata(path) {- Ok(m) if m.is_file() && !m.file_type().is_symlink() => {- let raw = std::fs::read_to_string(path).ok()?;- serde_json::from_str(&raw).ok()- }- _ => None,- }-}--fn is_real_file(path: &Path) -> bool {- matches!(- std::fs::symlink_metadata(path),- Ok(m) if m.is_file() && !m.file_type().is_symlink()- )-}--fn open_spec(open_dir: &Path, id: &str) -> Option<OpenSpec> {- read_real_json(&open_dir.join(format!("{id}.json")))-}--fn done_marker(done_dir: &Path, id: &str) -> Option<DoneMarker> {- read_real_json(&done_dir.join(format!("{id}.done.json")))-}--fn claim_marker(claimed_dir: &Path, id: &str) -> Option<ClaimMarker> {- read_real_json(&claimed_dir.join(format!("{id}.json")))-}--/// All open-item ids, ascending by numeric suffix.-fn open_ids(open_dir: &Path) -> Vec<(u64, String)> {- let mut ids = Vec::new();- if let Ok(rd) = std::fs::read_dir(open_dir) {- for entry in rd.flatten() {- if let Some(name) = entry.file_name().to_str() {- if let Some(stem) = name.strip_suffix(".json") {- if let Some(n) = work_id_num(stem) {- ids.push((n, stem.to_string()));- }- }- }- }- }- ids.sort_by_key(|(n, _)| *n);- ids-}--/// Highest numeric id across all three dirs, so the next post is contiguous.-fn max_existing(open: &Path, claimed: &Path, done: &Path) -> u64 {- let mut max = 0u64;- for dir in [open, claimed, done] {- if let Ok(rd) = std::fs::read_dir(dir) {- for entry in rd.flatten() {- if let Some(name) = entry.file_name().to_str() {- let stem = name.split('.').next().unwrap_or(name);- if let Some(n) = work_id_num(stem) {- max = max.max(n);- }- }- }- }- }- max-}--enum DepState {- Satisfied,- Failed,- InProgress,-}--fn dep_state(done_dir: &Path, dep: &str) -> DepState {- match done_marker(done_dir, dep) {- Some(m) if m.ok => DepState::Satisfied,- Some(_) => DepState::Failed,- None => DepState::InProgress,- }-}--/// Post a new item. `deps` must each name an already-posted work id (which is-/// what makes cycles impossible: a dep can only point at a lower id that already-/// exists). Returns the minted `w-<n>` id.-pub fn post_work_file(- scratch: &Path,- task: &str,- deps: &[String],- title: Option<&str>,- posted_by: &str,- now: u64,-) -> Result<String, String> {- let task = task.trim();- if task.is_empty() {- return Err("post_work requires a non-empty 'task'".to_string());- }- let (open_dir, claimed_dir, done_dir) =- ensure_dirs(scratch).ok_or("could not open the work queue")?;-- let open_count = open_ids(&open_dir)- .into_iter()- .filter(|(_, id)| done_marker(&done_dir, id).is_none())- .count();- if open_count >= WORKQUEUE_MAX_OPEN {- return Err(format!(- "the work queue is full ({WORKQUEUE_MAX_OPEN} open items); complete or wait for some first"- ));- }-- for dep in deps {- if !is_work_id(dep) || !is_real_file(&open_dir.join(format!("{dep}.json"))) {- return Err(format!(- "unknown dep {dep}; deps must reference an already-posted work id"- ));- }- }-- let title = title- .map(str::trim)- .filter(|t| !t.is_empty())- .map(str::to_string);- let mut n = max_existing(&open_dir, &claimed_dir, &done_dir) + 1;- for _ in 0..POST_ATTEMPTS {- let id = format!("w-{n}");- let spec = OpenSpec {- work_id: id.clone(),- title: title.clone(),- task: task.to_string(),- deps: deps.to_vec(),- posted_by: posted_by.to_string(),- posted_at: now,- };- match write_new_json(&open_dir.join(format!("{id}.json")), &spec) {- Ok(()) => return Ok(id),- Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {- n += 1;- continue;- }- Err(_) => return Err("could not write the work item".to_string()),- }- }- Err("could not allocate a work id".to_string())-}--/// Claim the top ready item for `claimer`. `claimer_alive` reports whether a-/// prior claimer is still running (its status header is present and not-/// terminal), so a stale claim can be reclaimed.-pub fn claim_work_file(- scratch: &Path,- claimer: &str,- now: u64,- claimer_alive: &dyn Fn(&str) -> bool,-) -> ClaimOutcome {- let (open_dir, claimed_dir, done_dir) = match ensure_dirs(scratch) {- Some(d) => d,- None => return ClaimOutcome::Error("could not open the work queue".to_string()),- };- let mut blocked: Vec<String> = Vec::new();- for (_, id) in open_ids(&open_dir) {- if done_marker(&done_dir, &id).is_some() {- continue;- }- let Some(spec) = open_spec(&open_dir, &id) else {- continue;- };-- let mut failed_dep: Option<String> = None;- let mut in_progress: Vec<String> = Vec::new();- for dep in &spec.deps {- match dep_state(&done_dir, dep) {- DepState::Satisfied => {}- DepState::Failed => {- failed_dep = Some(dep.clone());- break;- }- DepState::InProgress => in_progress.push(dep.clone()),- }- }- if let Some(dep) = failed_dep {- // Unsatisfiable: fail it so its own dependents fail transitively- // rather than blocking forever. A lost race on the marker is fine.- let _ = write_done(- &done_dir,- &id,- claimer,- false,- Some(&format!("dep {dep} failed")),- None,- now,- );- continue;- }-- let claim_path = claimed_dir.join(format!("{id}.json"));- if let Some(marker) = claim_marker(&claimed_dir, &id) {- let expired = now.saturating_sub(marker.claimed_at) >= CLAIM_LEASE_SECS;- let dead = !claimer_alive(&marker.claimed_by);- if expired || dead {- let _ = std::fs::remove_file(&claim_path);- } else {- continue;- }- }-- if !in_progress.is_empty() {- blocked.extend(in_progress);- continue;- }-- let marker = ClaimMarker {- work_id: id.clone(),- claimed_by: claimer.to_string(),- claimed_at: now,- };- match write_new_json(&claim_path, &marker) {- Ok(()) => {- let deps_results = build_deps_results(scratch, &done_dir, &spec.deps);- return ClaimOutcome::Claimed {- work_id: id,- task: spec.task,- deps_results,- };- }- Err(_) => continue, // lost the race; try the next item- }- }- if blocked.is_empty() {- ClaimOutcome::Empty- } else {- blocked.sort();- blocked.dedup();- ClaimOutcome::Blocked(blocked)- }-}--fn build_deps_results(scratch: &Path, done_dir: &Path, deps: &[String]) -> Vec<(String, String)> {- deps.iter()- .filter_map(|dep| {- let path = done_dir.join(format!("{dep}.result.md"));- let body = read_real_string(&path)?;- let display = scratch_display_path(Some(scratch), &path);- Some((dep.clone(), compose_subagent_result(&body, Some(&display))))- })- .collect()-}--fn read_real_string(path: &Path) -> Option<String> {- match std::fs::symlink_metadata(path) {- Ok(m) if m.is_file() && !m.file_type().is_symlink() => std::fs::read_to_string(path).ok(),- _ => None,- }-}--/// Complete an item `completer` holds a claim on, writing its result body and a-/// success marker. Refused unless the caller owns the claim and the item is not-/// already done.-pub fn complete_work_file(- scratch: &Path,- work_id: &str,- completer: &str,- result: &str,- now: u64,-) -> Result<(), String> {- if !is_work_id(work_id) {- return Err(format!("invalid work id {work_id}"));- }- let (_open_dir, claimed_dir, done_dir) =- ensure_dirs(scratch).ok_or("could not open the work queue")?;- let Some(marker) = claim_marker(&claimed_dir, work_id) else {- return Err(format!("{work_id} is not claimed by you; claim it first"));- };- if marker.claimed_by != completer {- return Err(format!(- "{work_id} is claimed by {}, not you",- marker.claimed_by- ));- }- if done_marker(&done_dir, work_id).is_some() {- return Err(format!("{work_id} is already completed"));- }- let result_name = format!("{work_id}.result.md");- let result_path = done_dir.join(&result_name);- match open_excl(&result_path) {- Ok(mut f) => {- if f.write_all(result.as_bytes()).is_err() {- return Err("could not write the result body".to_string());- }- }- Err(_) => return Err("could not write the result body".to_string()),- }- write_done(- &done_dir,- work_id,- completer,- true,- None,- Some(&result_name),- now,- )- .map_err(|_| "could not write the completion marker".to_string())-}--#[allow(clippy::too_many_arguments)]-fn write_done(- done_dir: &Path,- work_id: &str,- by: &str,- ok: bool,- reason: Option<&str>,- result_file: Option<&str>,- now: u64,-) -> std::io::Result<()> {- let marker = DoneMarker {- work_id: work_id.to_string(),- by: by.to_string(),- ok,- reason: reason.map(str::to_string),- result_file: result_file.map(str::to_string),- done_at: now,- };- write_new_json(&done_dir.join(format!("{work_id}.done.json")), &marker)-}--/// Terminal-path sweep: fail every item `run_id` still holds an uncompleted-/// claim on, so a worker that ended without `complete_work` does not wedge its-/// dependents. Returns the number failed.-pub fn fail_owned_claims(scratch: &Path, run_id: &str, now: u64) -> usize {- let Some((_open, claimed_dir, done_dir)) = ensure_dirs(scratch) else {- return 0;- };- let mut failed = 0;- if let Ok(rd) = std::fs::read_dir(&claimed_dir) {- for entry in rd.flatten() {- let Some(name) = entry.file_name().to_str().map(str::to_string) else {- continue;- };- let Some(id) = name.strip_suffix(".json") else {- continue;- };- let Some(marker) = claim_marker(&claimed_dir, id) else {- continue;- };- if marker.claimed_by != run_id || done_marker(&done_dir, id).is_some() {- continue;- }- if write_done(- &done_dir,- id,- run_id,- false,- Some("worker ended without completing"),- None,- now,- )- .is_ok()- {- failed += 1;- }- }- }- failed-}--/// Every item's current view, ascending by id. Cheap: three small-dir reads, no-/// transcript I/O.-pub fn list_work_dir(scratch: &Path) -> Vec<WorkItemView> {- let Some((open_dir, claimed_dir, done_dir)) = ensure_dirs(scratch) else {- return Vec::new();- };- let mut out = Vec::new();- for (_, id) in open_ids(&open_dir) {- let Some(spec) = open_spec(&open_dir, &id) else {- continue;- };- let title = spec- .title- .clone()- .unwrap_or_else(|| truncate_title(&spec.task));- let (state, claimed_by, reason) = classify(&claimed_dir, &done_dir, &id, &spec.deps);- out.push(WorkItemView {- work_id: id,- title,- state,- claimed_by,- reason,- });- }- out-}--fn classify(- claimed_dir: &Path,- done_dir: &Path,- id: &str,- deps: &[String],-) -> (String, Option<String>, Option<String>) {- if let Some(m) = done_marker(done_dir, id) {- if m.ok {- return ("done".to_string(), None, None);- }- return ("failed".to_string(), None, m.reason);- }- // Deps drive readiness even for a claimed item's display reason.- let mut failed_dep = None;- let mut waiting = Vec::new();- for dep in deps {- match dep_state(done_dir, dep) {- DepState::Satisfied => {}- DepState::Failed => {- failed_dep = Some(dep.clone());- break;- }- DepState::InProgress => waiting.push(dep.clone()),- }- }- if let Some(dep) = failed_dep {- return (- "failed".to_string(),- None,- Some(format!("dep {dep} failed")),- );- }- if let Some(marker) = claim_marker(claimed_dir, id) {- return ("claimed".to_string(), Some(marker.claimed_by), None);- }- if !waiting.is_empty() {- return (- "blocked".to_string(),- None,- Some(format!("waiting on {}", waiting.join(", "))),- );- }- ("open".to_string(), None, None)-}--fn truncate_title(task: &str) -> String {- let flat: String = task.split_whitespace().collect::<Vec<_>>().join(" ");- if flat.chars().count() <= 60 {- return flat;- }- let head: String = flat.chars().take(57).collect();- format!("{head}...")-}--/// The four loop-dispatched work-queue tool names (not built-ins).-pub const POST_WORK_TOOL: &str = "post_work";-pub const CLAIM_WORK_TOOL: &str = "claim_work";-pub const COMPLETE_WORK_TOOL: &str = "complete_work";-pub const LIST_WORK_TOOL: &str = "list_work";--/// Whether `name` is one of the four work-queue tools.-pub fn is_work_tool(name: &str) -> bool {- matches!(- name,- POST_WORK_TOOL | CLAIM_WORK_TOOL | COMPLETE_WORK_TOOL | LIST_WORK_TOOL- )-}--/// Whether `name` mutates the queue (`post`/`claim`/`complete`), so Plan mode-/// must deny it. `list_work` is read-only and stays allowed.-pub fn is_work_mutation(name: &str) -> bool {- matches!(name, POST_WORK_TOOL | CLAIM_WORK_TOOL | COMPLETE_WORK_TOOL)-}--/// OpenAI tool schemas for the four work-queue tools. Deliberately tiny arg-/// surfaces (weak local models choke on rich schemas, the monitor lesson).-pub fn work_tool_schemas() -> Vec<serde_json::Value> {- vec![- serde_json::json!({- "type": "function",- "function": {- "name": POST_WORK_TOOL,- "description": "Post a task to the shared work queue for a worker to pick up. Fan out independent work by posting several, then dispatching generic workers that each claim and complete one. deps names work ids whose results this task needs (each must already be posted); the task is claimable only once they finish, and their results are handed to whoever claims it. Returns the new work id.",- "parameters": {- "type": "object",- "properties": {- "task": { "type": "string", "description": "What the worker should do, self-contained." },- "deps": { "type": "array", "items": {"type": "string"}, "description": "Work ids (e.g. [\"w-1\"]) this task depends on; each must already be posted. Optional." },- "title": { "type": "string", "description": "Optional short label shown on the queue (defaults to the task)." }- },- "required": ["task"]- }- }- }),- serde_json::json!({- "type": "function",- "function": {- "name": CLAIM_WORK_TOOL,- "description": "Claim the next ready task from the shared work queue and receive its instructions and any dependency results. Call this as a worker: claim, do the work, then complete_work. If it reports nothing is ready, stop -- you will be pinged when new work appears; do not loop on it.",- "parameters": { "type": "object", "properties": {} }- }- }),- serde_json::json!({- "type": "function",- "function": {- "name": COMPLETE_WORK_TOOL,- "description": "Report the result of a work item you claimed. Its result is saved and delivered to anything that depends on it. You must have claimed the item first.",- "parameters": {- "type": "object",- "properties": {- "work_id": { "type": "string", "description": "The id you claimed (from claim_work)." },- "result": { "type": "string", "description": "The finished result for this item." }- },- "required": ["work_id", "result"]- }- }- }),- serde_json::json!({- "type": "function",- "function": {- "name": LIST_WORK_TOOL,- "description": "List every item on the shared work queue with its state (open, claimed, done, failed, blocked), so you can see what is ready to dispatch and what is still in flight.",- "parameters": { "type": "object", "properties": {} }- }- }),- ]-}--/// What a work-tool call did, so the caller can ring the doorbell, refresh the-/// queue snapshot, and update its own status header.-pub struct WorkToolResult {- /// The model-facing tool-result string.- pub message: String,- /// A `post_work` succeeded, so a parked main should be woken.- pub posted: bool,- /// The work id a `claim_work` just handed the caller, for its status header.- pub claimed: Option<String>,-}--fn parse_string_array(v: Option<&serde_json::Value>) -> Vec<String> {- v.and_then(|v| v.as_array())- .map(|a| {- a.iter()- .filter_map(|x| x.as_str().map(str::to_string))- .collect()- })- .unwrap_or_default()-}--/// Run one work-queue tool call and format its model-facing result. `agent_id`-/// is the caller's run id (`"main"` or a `sub-...` id): the poster, claimer, and-/// completer of record. `now` is epoch seconds. Shared by the CLI loop and the-/// desktop/Cowork command layer so both surfaces format identically.-pub fn run_work_tool(- scratch: &Path,- name: &str,- args: &serde_json::Value,- agent_id: &str,- now: u64,-) -> WorkToolResult {- let bare = |message: String| WorkToolResult {- message,- posted: false,- claimed: None,- };- match name {- POST_WORK_TOOL => {- let task = args.get("task").and_then(|v| v.as_str()).unwrap_or("");- let deps = parse_string_array(args.get("deps"));- let title = args.get("title").and_then(|v| v.as_str());- match post_work_file(scratch, task, &deps, title, agent_id, now) {- Ok(id) => WorkToolResult {- message: format!(- "Posted {id} to the work queue. Dispatch a worker to claim it (or an idle \- worker will pick it up)."- ),- posted: true,- claimed: None,- },- Err(e) => bare(format!("ERROR: {e}")),- }- }- CLAIM_WORK_TOOL => {- let alive = |id: &str| {- crate::tools::observ::read_status(scratch, id)- .map(|s| {- s.state != crate::tools::observ::STATE_DONE- && s.state != crate::tools::observ::STATE_FAILED- })- .unwrap_or(false)- };- match claim_work_file(scratch, agent_id, now, &alive) {- ClaimOutcome::Claimed {- work_id,- task,- deps_results,- } => {- let mut message = format!("You claimed {work_id}.\n\nTask:\n{task}");- for (dep, body) in deps_results {- message.push_str(&format!("\n\n--- result of {dep} ---\n{body}"));- }- message.push_str(- "\n\nDo the work, then call complete_work with this work_id and your result.",- );- WorkToolResult {- message,- posted: false,- claimed: Some(work_id),- }- }- ClaimOutcome::Empty => bare(- "No work is ready right now. Stop and wait -- you will be pinged when new work \- is ready. Do not call claim_work again in a loop."- .to_string(),- ),- ClaimOutcome::Blocked(deps) => bare(format!(- "The remaining work is waiting on unfinished dependencies ({}). Stop; the main \- agent re-dispatches when they complete.",- deps.join(", ")- )),- ClaimOutcome::Error(e) => bare(format!("ERROR: {e}")),- }- }- COMPLETE_WORK_TOOL => {- let work_id = args.get("work_id").and_then(|v| v.as_str()).unwrap_or("");- let result = args.get("result").and_then(|v| v.as_str()).unwrap_or("");- match complete_work_file(scratch, work_id, agent_id, result, now) {- Ok(()) => bare(format!(- "Completed {work_id}. Its result is now available to any dependent work."- )),- Err(e) => bare(format!("ERROR: {e}")),- }- }- LIST_WORK_TOOL => bare(format_work_list(&list_work_dir(scratch))),- _ => bare("ERROR: unknown work tool".to_string()),- }-}--fn format_work_list(items: &[WorkItemView]) -> String {- if items.is_empty() {- return "The work queue is empty.".to_string();- }- let mut out = String::from("Work queue:");- for it in items {- out.push_str(&format!("\n- {} [{}] {}", it.work_id, it.state, it.title));- if let Some(who) = &it.claimed_by {- out.push_str(&format!(" (claimed by {who})"));- }- if let Some(reason) = &it.reason {- out.push_str(&format!(" ({reason})"));- }- }- out-}--#[cfg(test)]-mod tests {- use super::*;- use std::sync::atomic::{AtomicUsize, Ordering};-- fn tmp(tag: &str) -> PathBuf {- static N: AtomicUsize = AtomicUsize::new(0);- let n = N.fetch_add(1, Ordering::SeqCst);- let dir = std::env::temp_dir().join(format!("jan-workq-{tag}-{}-{n}", std::process::id()));- std::fs::create_dir_all(&dir).unwrap();- dir- }-- fn alive_always(_: &str) -> bool {- true- }-- fn state_of(scratch: &Path, id: &str) -> String {- list_work_dir(scratch)- .into_iter()- .find(|v| v.work_id == id)- .map(|v| v.state)- .unwrap_or_default()- }-- #[test]- fn ids_are_contiguous_and_validated() {- assert!(is_work_id("w-1"));- assert!(is_work_id("w-42"));- assert!(!is_work_id("w-"));- assert!(!is_work_id("x-1"));- assert!(!is_work_id("w-1a"));- let scratch = tmp("ids");- let a = post_work_file(&scratch, "first", &[], None, "main", 1).unwrap();- let b = post_work_file(&scratch, "second", &[], None, "main", 1).unwrap();- assert_eq!(a, "w-1");- assert_eq!(b, "w-2");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn a_claimed_item_cannot_be_double_claimed() {- let scratch = tmp("double");- post_work_file(&scratch, "solo", &[], None, "main", 1).unwrap();- let first = claim_work_file(&scratch, "sub-a-1", 1, &alive_always);- assert!(matches!(first, ClaimOutcome::Claimed { .. }));- let second = claim_work_file(&scratch, "sub-b-1", 1, &alive_always);- assert_eq!(second, ClaimOutcome::Empty, "a live claim is not re-handed");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn producer_consumer_handoff_via_deps() {- let scratch = tmp("deps");- let producer = post_work_file(&scratch, "gather data", &[], None, "main", 1).unwrap();- let consumer = post_work_file(- &scratch,- "summarize the data",- &[producer.clone()],- None,- "main",- 1,- )- .unwrap();- // The consumer is blocked until the producer completes.- let blocked = claim_work_file(&scratch, "sub-b-1", 1, &alive_always);- // sub-a can take the producer; then the outcome is either the producer- // itself (claimed) or, if producer already claimed, blocked. Here fresh:- match blocked {- ClaimOutcome::Claimed { work_id, .. } => assert_eq!(work_id, producer),- other => panic!("expected the producer to be claimable, got {other:?}"),- }- // Consumer still blocked on the in-progress producer.- let still = claim_work_file(&scratch, "sub-c-1", 1, &alive_always);- assert_eq!(still, ClaimOutcome::Blocked(vec![producer.clone()]));- // Producer completes; now the consumer is claimable with the dep result.- complete_work_file(&scratch, &producer, "sub-b-1", "the gathered data", 2).unwrap();- let claimed = claim_work_file(&scratch, "sub-c-1", 2, &alive_always);- match claimed {- ClaimOutcome::Claimed {- work_id,- deps_results,- ..- } => {- assert_eq!(work_id, consumer);- assert_eq!(deps_results.len(), 1);- assert_eq!(deps_results[0].0, producer);- assert!(deps_results[0].1.contains("the gathered data"));- }- other => panic!("expected the consumer, got {other:?}"),- }- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn unknown_dep_is_rejected_synchronously() {- let scratch = tmp("baddep");- let err = post_work_file(&scratch, "x", &["w-9".to_string()], None, "main", 1).unwrap_err();- assert!(err.contains("unknown dep w-9"), "{err}");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn a_failed_dep_fails_its_dependent_transitively() {- let scratch = tmp("transfail");- let a = post_work_file(&scratch, "risky", &[], None, "main", 1).unwrap();- let b = post_work_file(&scratch, "needs a", &[a.clone()], None, "main", 1).unwrap();- let _c = post_work_file(&scratch, "needs b", &[b.clone()], None, "main", 1).unwrap();- // a is claimed then its worker dies without completing.- let claimed = claim_work_file(&scratch, "sub-a-1", 1, &alive_always);- assert!(matches!(claimed, ClaimOutcome::Claimed { .. }));- assert_eq!(fail_owned_claims(&scratch, "sub-a-1", 2), 1);- assert_eq!(state_of(&scratch, &a), "failed");- // Claiming now fails b (its dep a failed), and c fails after b.- let outcome = claim_work_file(&scratch, "sub-b-1", 3, &alive_always);- assert_eq!(- outcome,- ClaimOutcome::Empty,- "nothing claimable, all failed"- );- assert_eq!(state_of(&scratch, &b), "failed");- assert_eq!(state_of(&scratch, &_c), "failed");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn a_stale_claim_is_reclaimed() {- let scratch = tmp("lease");- let a = post_work_file(&scratch, "solo", &[], None, "main", 1).unwrap();- let first = claim_work_file(&scratch, "sub-a-1", 1, &alive_always);- assert!(matches!(first, ClaimOutcome::Claimed { .. }));- // Same instant, claimer reported dead: reclaimable.- let dead = |_: &str| false;- let second = claim_work_file(&scratch, "sub-b-1", 1, &dead);- match second {- ClaimOutcome::Claimed { work_id, .. } => assert_eq!(work_id, a),- other => panic!("expected reclaim, got {other:?}"),- }- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn an_expired_lease_is_reclaimed_even_if_alive() {- let scratch = tmp("expire");- post_work_file(&scratch, "solo", &[], None, "main", 100).unwrap();- let first = claim_work_file(&scratch, "sub-a-1", 100, &alive_always);- assert!(matches!(first, ClaimOutcome::Claimed { .. }));- let later = 100 + CLAIM_LEASE_SECS + 1;- let second = claim_work_file(&scratch, "sub-b-1", later, &alive_always);- assert!(matches!(second, ClaimOutcome::Claimed { .. }), "{second:?}");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[cfg(unix)]- #[test]- fn refuses_a_redirected_workqueue_dir() {- let scratch = tmp("redirect");- let target = tmp("redirect-target");- std::os::unix::fs::symlink(&target, scratch.join(WORKQUEUE_DIR)).unwrap();- assert!(post_work_file(&scratch, "x", &[], None, "main", 1).is_err());- let _ = std::fs::remove_dir_all(&scratch);- let _ = std::fs::remove_dir_all(&target);- }-- #[test]- fn complete_is_refused_for_a_non_owner() {- let scratch = tmp("owner");- let a = post_work_file(&scratch, "solo", &[], None, "main", 1).unwrap();- claim_work_file(&scratch, "sub-a-1", 1, &alive_always);- let err = complete_work_file(&scratch, &a, "sub-b-1", "sneaky", 2).unwrap_err();- assert!(err.contains("claimed by sub-a-1"), "{err}");- let _ = std::fs::remove_dir_all(&scratch);- }-- #[test]- fn list_reports_states() {- let scratch = tmp("list");- let a = post_work_file(&scratch, "one", &[], Some("first"), "main", 1).unwrap();- let b = post_work_file(&scratch, "two", &[a.clone()], None, "main", 1).unwrap();- // a open (ready), b blocked (dep a in progress).- assert_eq!(state_of(&scratch, &a), "open");- assert_eq!(state_of(&scratch, &b), "blocked");- claim_work_file(&scratch, "sub-a-1", 1, &alive_always);- assert_eq!(state_of(&scratch, &a), "claimed");- complete_work_file(&scratch, &a, "sub-a-1", "result", 2).unwrap();- assert_eq!(state_of(&scratch, &a), "done");- assert_eq!(state_of(&scratch, &b), "open", "b ready once a is done");- let view = list_work_dir(&scratch)- .into_iter()- .find(|v| v.work_id == a)- .unwrap();- assert_eq!(view.title, "first");- let _ = std::fs::remove_dir_all(&scratch);- }-}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 64e98c659..f32c42e88 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -145,27 +145,6 @@ it finishes. Once you delegate a task it belongs to that subagent -- do not do tspend the wait on other steps, and only `await_subagent` when nothing else is left to do. Do inline work \yourself for small, targeted tasks where delegating would cost more than it saves.";-/// The worker half of the work-queue guide, shown to every collaborating agent-/// (main and workers). It leads with the direct-task rule: a subagent handed a-/// concrete task must do that task rather than drain the queue or wait on a-/// peer that isn't there -- the loop a lone subagent otherwise fell into.-const WORK_QUEUE_WORKER_GUIDE: &str = "# Shared work queue\n\nYou share a work queue and a live status \-board with the other agents on this run. If your instructions give you a task, do that task yourself -- \-do not wait on the queue for it. Use `claim_work` only when you were dispatched as a generic worker with \-no task of your own: claim the next ready item, do it, then `complete_work` with the result. If \-`claim_work` reports nothing is ready, stop -- do not loop on it and do not wait for a peer; you are \-re-dispatched when new work appears.";--/// The dispatcher half, added only for a run that may dispatch subagents (main),-/// so it learns the post -> dispatch-workers -> chain-with-deps pattern and the-/// offload-only rule.-const WORK_QUEUE_DISPATCH_GUIDE: &str = "To fan work out across workers: `post_work` one item per \-independent piece, then dispatch a generic subagent for each; each claims one item, completes it, and \-stops. Chain steps with `deps` -- a task posted with `deps: [\"w-1\"]` is claimable only once w-1 \-completes, and w-1's result is delivered to whoever claims it. Never post work whose result you need \-within this same turn (a peer, or you on a later turn, completes it -- never you right now); do that \-work inline instead.";-/// System-prompt addendum for a `/goal` run with no staged plan: an unattended/// loop that keeps firing turns until a condition is met needs the phased list/// up front, both to work through and for the user to read on return. Paired@@ -280,7 +259,6 @@ pub(crate) fn build_system_prompt(project_root: &Path,scratch: Option<&Path>,subagents_enabled: bool,- work_queue_enabled: bool,) -> Option<String> {let mut blocks: Vec<String> = Vec::new();match base {@@ -296,14 +274,6 @@ pub(crate) fn build_system_prompt(if subagents_enabled {blocks.push(SUBAGENT_GUIDE.to_string());}- // Independent of `subagents_enabled`: a worker (dispatch disabled) still- // needs the claim -> complete loop; only the dispatch half is gated on it.- if work_queue_enabled {- blocks.push(WORK_QUEUE_WORKER_GUIDE.to_string());- if subagents_enabled {- blocks.push(WORK_QUEUE_DISPATCH_GUIDE.to_string());- }- }blocks.push(DEFAULT_SKILL_GUIDE.trim().to_string());blocks.push(WEB_TOOLS_GUIDE.to_string());if let Some(context) = load_context_files(project_root) {@@ -442,7 +412,7 @@ mod tests {fn build_system_prompt_orders_base_guide_then_skills() {let root = scratch_project("merge");write_skill(&root, "s.md", "Do the thing.");- let out = build_system_prompt(Some("You are Jan."), &root, None, false, false).expect("prompt");+ let out = build_system_prompt(Some("You are Jan."), &root, None, false).expect("prompt");assert!(out.starts_with("You are Jan."));assert!(out.contains("Do the thing."));// Guide sits between the base prompt and the project skills.@@ -455,7 +425,7 @@ mod tests {#[test]fn build_system_prompt_advertises_native_web_tools() {let root = scratch_project("web");- let out = build_system_prompt(None, &root, None, false, false).expect("prompt");+ let out = build_system_prompt(None, &root, None, false).expect("prompt");assert!(out.contains("# Web Access"));assert!(out.contains("web_search"));assert!(out.contains("web_fetch"));@@ -473,13 +443,13 @@ mod tests {fn build_system_prompt_always_includes_guide() {let root = scratch_project("guide");// No base and no project skills: the built-in guide is still injected.- let out = build_system_prompt(None, &root, None, false, false).expect("guide always present");+ let out = build_system_prompt(None, &root, None, false).expect("guide always present");assert!(out.contains("Skills and Project Memory"));assert!(out.contains("skill_write"));assert!(out.contains("memory_write"));// Base is preserved and precedes the guide.- let with_base = build_system_prompt(Some("base"), &root, None, false, false).expect("prompt");+ let with_base = build_system_prompt(Some("base"), &root, None, false).expect("prompt");assert!(with_base.starts_with("base"));assert!(with_base.contains("Skills and Project Memory"));let _ = std::fs::remove_dir_all(&root);@@ -488,7 +458,7 @@ mod tests {#[test]fn default_identity_and_guidelines_present_without_base() {let root = scratch_project("identity");- let out = build_system_prompt(None, &root, None, false, false).expect("prompt");+ let out = build_system_prompt(None, &root, None, false).expect("prompt");assert!(out.starts_with("You're currently running on Jan agent harness"));assert!(out.contains("# Guidelines"));assert!(out.contains("Be concise"));@@ -516,7 +486,7 @@ mod tests {// Nearest (nested) file wins by appearing last.assert!(block.find("ROOT_RULES").unwrap() < block.find("NESTED_RULES").unwrap());- let prompt = build_system_prompt(None, &nested, None, false, false).expect("prompt");+ let prompt = build_system_prompt(None, &nested, None, false).expect("prompt");// Context files precede the skills catalog position and follow the guide.assert!(prompt.contains("NESTED_RULES"));let _ = std::fs::remove_dir_all(&root);@@ -533,9 +503,9 @@ mod tests {#[test]fn build_system_prompt_advertises_subagents_only_when_enabled() {let root = scratch_project("subagents");- let without = build_system_prompt(None, &root, None, false, false).expect("prompt");+ let without = build_system_prompt(None, &root, None, false).expect("prompt");assert!(!without.contains("dispatch_subagent"));- let with = build_system_prompt(None, &root, None, true, false).expect("prompt");+ let with = build_system_prompt(None, &root, None, true).expect("prompt");assert!(with.contains("dispatch_subagent"));let _ = std::fs::remove_dir_all(&root);}@@ -546,31 +516,13 @@ mod tests {#[test]fn subagent_guide_hands_off_ownership_of_a_delegated_task() {let root = scratch_project("subagent-handoff");- let with = build_system_prompt(None, &root, None, true, false).expect("prompt");+ let with = build_system_prompt(None, &root, None, true).expect("prompt");assert!(with.contains("belongs to that subagent"));assert!(with.contains("do not do the same work yourself"));assert!(!with.contains("keep working rather than waiting"));let _ = std::fs::remove_dir_all(&root);}- #[test]- fn work_queue_worker_guide_leads_with_the_direct_task_rule() {- let root = scratch_project("workqueue-guide");- let off = build_system_prompt(None, &root, None, false, false).expect("prompt");- assert!(!off.contains("Shared work queue"));- // A worker (dispatch disabled): worker guide present, dispatch half not.- let worker = build_system_prompt(None, &root, None, false, true).expect("prompt");- assert!(worker.contains("Shared work queue"));- assert!(worker.contains("do that task yourself"));- assert!(worker.contains("do not wait for a peer"));- assert!(!worker.contains("dispatch a generic subagent"));- // Main (dispatch enabled) also learns the fan-out half.- let main = build_system_prompt(None, &root, None, true, true).expect("prompt");- assert!(main.contains("do not wait for a peer"));- assert!(main.contains("post_work"));- let _ = std::fs::remove_dir_all(&root);- }-// ── Runtime environment block ────────────────────────────────────────#[test]@@ -598,7 +550,7 @@ mod tests {fn runtime_environment_block_injected_into_system_prompt() {let root = scratch_project("inject");std::fs::create_dir_all(&root).unwrap();- let out = build_system_prompt(None, &root, None, false, false).expect("prompt");+ let out = build_system_prompt(None, &root, None, false).expect("prompt");assert!(out.contains("# Runtime Environment"));assert!(out.contains("Work directory:"));// The block sits right after the Working Directory section.diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 7a85dc451..5b460ecb2 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -103,6 +103,13 @@ pub enum StreamEvent {#[serde(default, skip_serializing_if = "Option::is_none")]error: Option<String>,},+ /// The later phases of a phased dispatch, named up front so a consumer can+ /// show their subagents as WAITING on an earlier phase before they start.+ /// Each pending subagent is promoted by its own `SubagentStart` (or+ /// `SubagentQueued`), matched by `name`, which is unique across a plan.+ /// Display-only and never journaled; emitted only by the top-level run+ /// (children cannot dispatch), so it is never wrapped in `Subagent`.+ SubagentPlan { pending: Vec<PendingSubagent> },/// A backgrounded subagent's own internal event, tagged with its run so a/// consumer can attribute it to the right child even when several run/// concurrently. `event` is a non-terminal child event (Token/Step/ToolCall/@@ -132,29 +139,6 @@ pub enum StreamEvent {/// Nothing is being generated until a ping resumes the run, which the next/// `Step` marks. Lets a consumer say "watching" rather than "working".Parked,- /// A per-agent status-header change: the main run as `run_id == "main"`, or- /// a child by its `run_id`. Emitted on a state/step change and mirrored into- /// the agent's `status.json`, so a consumer can show live peer status --- /// including the `blocked`/`parked` transitions the [`Subagent`] bracket does- /// not carry -- and which `work_id` the agent currently holds. Display-only- /// and never journaled, like [`Monitors`]/[`Parked`].- AgentStatus {- run_id: String,- name: String,- state: String,- step: u64,- tool_calls: u64,- last: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- work_id: Option<String>,- },- /// The run's shared work queue as a whole, replacing the previous snapshot.- /// Emitted publish-on-change after any work-tool mutation (mirroring- /// [`Monitors`]), so a consumer keeps a live view without bookkeeping of its- /// own. Display-only and never journaled.- WorkQueue {- items: Vec<tauri_plugin_agent_tools::tools::workqueue::WorkItemView>,- },/// The loop's compaction reduced the conversation while retrying a/// context overflow. The client should replace its session history with/// `messages` for subsequent turns.@@ -220,25 +204,14 @@ pub enum StreamEvent {},}-/// Read an agent's `status.json` and emit it as [`StreamEvent::AgentStatus`] on-/// `events`, so the docked per-agent view and roster stay live. A no-op if the-/// agent has no status header yet.-pub(crate) fn maybe_emit_agent_status(- events: &tokio::sync::mpsc::UnboundedSender<StreamEvent>,- scratch: &std::path::Path,- run_id: &str,-) {- if let Some(s) = tauri_plugin_agent_tools::tools::observ::read_status(scratch, run_id) {- let _ = events.send(StreamEvent::AgentStatus {- run_id: s.run_id,- name: s.name,- state: s.state,- step: s.step,- tool_calls: s.tool_calls,- last: s.last,- work_id: s.work_id,- });- }+/// A subagent in a not-yet-started phase of a phased dispatch: its name (unique+/// across the plan, and its blackboard file) and 1-based phase number. Carried by+/// [`StreamEvent::SubagentPlan`] so a consumer can show it waiting on the phase+/// before it.+#[derive(Clone, Debug, serde::Serialize)]+pub struct PendingSubagent {+ pub name: String,+ pub phase: u32,}/// If `path` targets a file in the agent's skill or memory workspace, return the@@ -546,67 +519,6 @@ mod tests {);}- #[test]- fn agent_status_serializes_to_wire_shape() {- let v = serde_json::to_value(StreamEvent::AgentStatus {- run_id: "sub-a-1".into(),- name: "a".into(),- state: "running".into(),- step: 4,- tool_calls: 12,- last: "edit src/auth.rs".into(),- work_id: Some("w-7".into()),- })- .unwrap();- assert_eq!(- v,- json!({- "type": "agent_status",- "run_id": "sub-a-1",- "name": "a",- "state": "running",- "step": 4,- "tool_calls": 12,- "last": "edit src/auth.rs",- "work_id": "w-7"- })- );- // work_id is omitted when the agent holds no item.- let none = serde_json::to_value(StreamEvent::AgentStatus {- run_id: "main".into(),- name: "main".into(),- state: "parked".into(),- step: 1,- tool_calls: 0,- last: String::new(),- work_id: None,- })- .unwrap();- assert!(none.get("work_id").is_none());- }-- #[test]- fn work_queue_serializes_with_camel_case_items() {- use tauri_plugin_agent_tools::tools::workqueue::WorkItemView;- let v = serde_json::to_value(StreamEvent::WorkQueue {- items: vec![WorkItemView {- work_id: "w-1".into(),- title: "lint".into(),- state: "open".into(),- claimed_by: None,- reason: None,- }],- })- .unwrap();- assert_eq!(- v,- json!({- "type": "work_queue",- "items": [{ "workId": "w-1", "title": "lint", "state": "open" }]- })- );- }-#[test]fn usage_parses_present_fields_and_none_when_absent() {let parsed = Usage::from_completion(&json!({diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 85268222b..f86fa9271 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -114,19 +114,6 @@ pub(crate) struct OrchestrationArgs {/// child) scopes monitors to the run, which then parks on them. Never/// inherited by a child run, which gets its own per-run set.pub monitors: Option<std::sync::Arc<tauri_plugin_agent_tools::tools::monitor::MonitorSet>>,- /// Whether this run may use the shared work queue (`post_work`/`claim_work`/- /// `complete_work`/`list_work`) and per-agent observability. Unlike- /// `subagents_enabled` this stays *true* on a child, so a dispatched worker- /// can claim and complete queue items while still being unable to nest.- pub work_queue_enabled: bool,- /// The run-scoped work-available doorbell, shared across the whole run tree- /// via the cloned child args: any agent's `post_work` rings it, waking a- /// parked main to re-dispatch. Created once at the top level.- pub work_signal: std::sync::Arc<crate::core::agent::subagent::WorkSignal>,- /// This run's own collaboration identity: the `run_id` it posts/claims work- /// and writes its status under. `None` for the top-level run, which is- /// `"main"`. Set by `spawn_subagent` on each child's cloned args.- pub collab_run_id: Option<String>,}#[async_trait]@@ -199,36 +186,6 @@ pub(crate) trait ToolInvoker: Send + Sync {fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {Vec::new()}-- /// Record that a new model turn (`index`, 1-based) began, so a collaborating- /// agent's `status.json` shows an accurate live step even on a turn that- /// calls no tools. Default no-op for invokers with no observability.- fn record_step(&self, _index: u32) {}-- /// Whether this run is a dispatched worker (a `sub-...` collaboration id)- /// rather than the top-level agent. Only a child may be hard-stopped by the- /// poll dampener: ending the main run would abort the very children it is- /// waiting on. Default false, so a non-collaborating run is never a child.- fn collab_is_child(&self) -> bool {- false- }-}--/// Work-queue/observability tools that read shared state without doing any work-/// or producing a result. A run whose turns consist only of these is polling,-/// not progressing -- the stuck-worker failure the dampener in [`run_turn_cycle`]-/// catches. `complete_work`/`post_work`/`dispatch_subagent` and every file/exec-/// tool are productive and reset the streak.-fn is_poll_only_tool(name: &str) -> bool {- matches!(name, "claim_work" | "list_work" | "read_agent")-}--/// The `function.name` of a tool call, or `""` when absent.-fn tool_call_fn_name(tc: &serde_json::Value) -> &str {- tc.get("function")- .and_then(|f| f.get("name"))- .and_then(|v| v.as_str())- .unwrap_or("")}/// Emit [`StreamEvent::Monitors`] when the set differs from what was last@@ -248,57 +205,6 @@ fn publish_monitors(}}-/// Flatten and clamp a transcript detail so one line cannot bloat the log.-fn truncate_detail(s: &str) -> String {- const MAX: usize = 200;- let flat: String = s.split_whitespace().collect::<Vec<_>>().join(" ");- if flat.chars().count() <= MAX {- return flat;- }- let head: String = flat.chars().take(MAX).collect();- format!("{head}...")-}--/// A compact roster + queue snapshot folded into each completion/doorbell wake,-/// so a resuming main sees current peer/queue state without a dedicated poll.-/// Empty when there is nothing worth reporting (no queue and no workers).-fn work_queue_digest(scratch: &std::path::Path) -> String {- use tauri_plugin_agent_tools::tools::{observ, workqueue};- let items = workqueue::list_work_dir(scratch);- let roster = observ::roster(scratch);- let workers: Vec<&observ::AgentStatusView> =- roster.iter().filter(|s| s.run_id != "main").collect();- if items.is_empty() && workers.is_empty() {- return String::new();- }- let count = |state: &str| items.iter().filter(|i| i.state == state).count();- let mut out = format!(- "Work queue: {} ready, {} in progress, {} done, {} failed.",- count("open"),- count("claimed"),- count("done"),- count("failed")- );- if !workers.is_empty() {- let list: Vec<String> = workers- .iter()- .map(|s| {- format!(- "{} [{}]{}",- s.name,- s.state,- s.work_id- .as_ref()- .map(|w| format!(" {w}"))- .unwrap_or_default()- )- })- .collect();- out.push_str(&format!(" Workers: {}.", list.join(", ")));- }- out-}-struct HttpModelInvoker {client: Client,upstream_url: String,@@ -453,23 +359,6 @@ struct CompositeToolInvoker {monitors_outlive_run: bool,auto_approve: bool,run_mode: crate::core::agent::plan::RunMode,- /// Whether this run participates in the shared work queue + per-agent- /// observability. Stays true on a child worker (unlike `subagents`).- work_queue_enabled: bool,- /// The run-scoped doorbell rung on `post_work`, shared with the run's- /// `BackgroundSubagents` so a post wakes a parked main.- work_signal: std::sync::Arc<crate::core::agent::subagent::WorkSignal>,- /// This agent's collaboration id (`"main"` or a `sub-...` run id): the- /// poster/claimer/completer of record, and the run_id its status is written- /// under.- collab_run_id: String,- /// Live status header this agent rewrites as it works, mirrored to- /// `status.json` so peers/main/the user can read it mid-flight.- collab_status: std::sync::Mutex<tauri_plugin_agent_tools::tools::observ::AgentStatusView>,- /// Append-only activity log, created once for the run's life. `None` when- /// collaboration is off or there is no scratch.- transcript:- std::sync::Mutex<Option<tauri_plugin_agent_tools::tools::observ::TranscriptWriter>>,}/// Default for the sandboxed shell's network namespace, used when@@ -689,6 +578,34 @@ fn output_sink(})}+/// The model-facing summary of a phased `dispatch_subagent` call.+fn format_dispatched_plan(d: &crate::core::agent::subagent::DispatchedPlan) -> String {+ let names = d.first_phase_names.join(", ");+ let where_answers = match &d.blackboard_dir {+ Some(dir) => format!(+ " Each answer is written to {dir}/<name>.md; read those files when you need them."+ ),+ None => " Each answer rides the note that tells you it finished.".to_string(),+ };+ let head = if d.phase_count > 1 {+ format!(+ "Dispatched a {}-phase plan of {} subagents. Phase 1 is now running: {}. Later phases \+ start automatically as each phase finishes, each receiving the previous phase's \+ results.",+ d.phase_count, d.total_subagents, names+ )+ } else {+ format!(+ "Dispatched {} subagent(s) running concurrently in the background: {}.",+ d.total_subagents, names+ )+ };+ format!(+ "{head}{where_answers} These tasks are the subagents' now -- do not do them yourself; \+ you'll be pinged as each finishes."+ )+}+impl CompositeToolInvoker {/// Whether the monitors owe the model something the run must stay alive/// for: any queued ping, plus a still-running watcher when the set dies@@ -782,122 +699,6 @@ impl CompositeToolInvoker {self.sandbox.then_some(self.scratch_root.as_path())}- /// The collaboration scratch this run shares with its peers: the session- /// scratch dir, independent of the bash sandbox (unlike `subagent_scratch`).- /// `None` when collaboration is off.- fn collab_scratch(&self) -> Option<&std::path::Path> {- self.work_queue_enabled- .then_some(self.scratch_root.as_path())- }-- /// Rewrite `status.json` from the live header and emit `AgentStatus`.- fn flush_collab_status(&self) {- let Some(scratch) = self.collab_scratch() else {- return;- };- {- let status = self.collab_status.lock().unwrap();- tauri_plugin_agent_tools::tools::observ::write_status(scratch, &status);- }- crate::core::agent::events::maybe_emit_agent_status(- &self.events,- scratch,- &self.collab_run_id,- );- }-- /// Append one activity line to this agent's transcript (best-effort).- fn log_activity(&self, kind: &str, detail: &str, err: Option<bool>) {- if let Some(w) = self.transcript.lock().unwrap().as_mut() {- w.append(kind, detail, err);- }- }-- /// Emit the whole work-queue snapshot (publish-on-mutation, mirroring- /// `publish_monitors`; the consumer replaces its view each time).- fn publish_workqueue(&self) {- if let Some(scratch) = self.collab_scratch() {- let items = tauri_plugin_agent_tools::tools::workqueue::list_work_dir(scratch);- let _ = self.events.send(StreamEvent::WorkQueue { items });- }- }-- /// Execute one work-queue / observability tool call and return its result.- /// Rings the doorbell on a post, records a claim in the status header, and- /// republishes the queue snapshot.- fn handle_work_tool(&self, name: &str, args: &serde_json::Value) -> String {- use tauri_plugin_agent_tools::tools::{epoch_secs, observ, workqueue};- let Some(scratch) = self.collab_scratch() else {- return "ERROR: the work queue is not available in this run".to_string();- };- if name == observ::READ_AGENT_TOOL {- // The self-read guard lives in the shared core so every surface- // (this loop and the Cowork command) enforces it identically.- return observ::run_read_agent(scratch, args, &self.collab_run_id);- }- let res = workqueue::run_work_tool(scratch, name, args, &self.collab_run_id, epoch_secs());- if res.posted {- self.work_signal.post();- }- if let Some(work_id) = &res.claimed {- self.collab_status.lock().unwrap().work_id = Some(work_id.clone());- self.flush_collab_status();- }- self.publish_workqueue();- res.message- }-- /// Record a batch of tool calls in this agent's status header + transcript,- /// so peers see live activity. A no-op when collaboration is off.- fn note_batch(&self, calls: &[serde_json::Value], out: &[ToolOutcome]) {- if self.collab_scratch().is_none() {- return;- }- let name_of = |tc: &serde_json::Value| -> String {- tc.get("function")- .and_then(|f| f.get("name"))- .and_then(|v| v.as_str())- .unwrap_or("tool")- .to_string()- };- let names: std::collections::HashMap<String, String> = calls- .iter()- .filter_map(|tc| {- let id = tc.get("id").and_then(|v| v.as_str())?.to_string();- Some((id, name_of(tc)))- })- .collect();- let mut last: Option<String> = None;- for tc in calls {- let name = name_of(tc);- let args = tc- .get("function")- .and_then(|f| f.get("arguments"))- .and_then(|v| v.as_str())- .unwrap_or("");- self.log_activity("tool_call", &truncate_detail(&format!("{name} {args}")), None);- last = Some(name);- }- for o in out {- let name = names.get(&o.id).map(String::as_str).unwrap_or("tool");- let err = o.content.starts_with("ERROR");- self.log_activity(- "tool_result",- &truncate_detail(&format!("{name}: {}", o.content)),- Some(err),- );- }- {- let mut s = self.collab_status.lock().unwrap();- s.tool_calls = s.tool_calls.saturating_add(calls.len() as u64);- if let Some(last) = last {- s.last = last;- }- s.updated_at = tauri_plugin_agent_tools::tools::epoch_secs();- }- self.flush_collab_status();- }-/// Execute one subagent tool call, returning the model-facing result string/// (an `ERROR:`-prefixed message on failure, matching the tool-result/// convention). The registry is loaded fresh from disk each call so a@@ -905,7 +706,8 @@ impl CompositeToolInvoker {async fn handle_subagent_tool(&self, name: &str, args: &serde_json::Value) -> String {use crate::core::agent::subagent::{await_subagent, format_subagent_list, parse_await_args, parse_create_args,- parse_dispatch_args, spawn_subagent, subagent_dir_for, SubagentRegistry, SubagentScope,+ parse_dispatch_plan, spawn_dispatch_plan, subagent_dir_for, SubagentRegistry,+ SubagentScope,};use tauri_plugin_agent_tools::tools::spill::compose_subagent_result;let Some(ctx) = &self.subagents else {@@ -917,14 +719,14 @@ impl CompositeToolInvoker {format_subagent_list(®istry)}"dispatch_subagent" => {- let req = match parse_dispatch_args(args) {- Ok(r) => r,+ let plan = match parse_dispatch_plan(args) {+ Ok(p) => p,Err(e) => return format!("ERROR: {e}"),};- match spawn_subagent(+ match spawn_dispatch_plan(&ctx.bg,&ctx.parent_args,- req,+ plan,&crate::core::agent::subagent::ParentRun {model: ctx.model_id.clone(),budget_remaining: ctx.max_session_tokens,@@ -935,21 +737,7 @@ impl CompositeToolInvoker {// `/tmp`, so there is nowhere sanctioned to spill.self.subagent_scratch(),) {- Ok(d) => match d.display_path {- Some(path) => format!(- "Subagent started in the background. run_id={}. This task is now the \- subagent's -- do not do it yourself. Its answer will be written to \- {path}; you will be told when it lands, so work on other steps \- meanwhile and read that file when you need the answer.",- d.run_id- ),- None => format!(- "Subagent started in the background. run_id={}. This task is now the \- subagent's -- do not do it yourself. Work on other steps; you will be \- told when it finishes, and that note carries its answer.",- d.run_id- ),- },+ Ok(d) => format_dispatched_plan(&d),Err(e) => format!("ERROR: {e}"),}}@@ -1312,50 +1100,9 @@ impl ToolInvoker for CompositeToolInvoker {text: u.text,}),);- // The work-available doorbell: any agent's post_work rang it. Draining- // clears the flag `has_pending_work` reads, so the run can terminate once- // nothing is left. Whenever anything reached the model this drain, append- // a fresh roster + queue digest so a resuming main has current state.- if self.work_signal.take() {- out.push(BackgroundNotice {- headline: Some("work items ready".to_string()),- text: "New work items are ready on the shared queue. Dispatch a worker (or claim \- one) as appropriate."- .to_string(),- });- }- if self.work_queue_enabled && !out.is_empty() {- if let Some(scratch) = self.collab_scratch() {- let digest = work_queue_digest(scratch);- if !digest.is_empty() {- out.push(BackgroundNotice {- headline: None,- text: digest,- });- }- }- }out}- fn record_step(&self, index: u32) {- if self.collab_scratch().is_none() {- return;- }- {- let mut s = self.collab_status.lock().unwrap();- s.step = index as u64;- s.state = tauri_plugin_agent_tools::tools::observ::STATE_RUNNING.to_string();- s.updated_at = tauri_plugin_agent_tools::tools::epoch_secs();- }- self.log_activity("step", &index.to_string(), None);- self.flush_collab_status();- }-- fn collab_is_child(&self) -> bool {- self.collab_run_id != "main"- }-fn background_pending(&self) -> bool {self.subagents.as_ref()@@ -1493,36 +1240,6 @@ impl ToolInvoker for CompositeToolInvoker {out.push(ToolOutcome::plain(id, content));continue;}- // Work-queue + observability tools are loop-dispatched like the- // subagent and monitor tools, ahead of the fs/exec gate: they touch- // only the run's own collaboration scratch, never the filesystem.- if tauri_plugin_agent_tools::tools::workqueue::is_work_tool(name)- || name == tauri_plugin_agent_tools::tools::observ::READ_AGENT_TOOL- {- let id = tc- .get("id")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();- // Plan mode: the queue-mutating tools change shared state and are- // not advertised there; hard-denied here as defense in depth.- // `read_agent`/`list_work` are read-only and fall through.- if self.run_mode == crate::core::agent::plan::RunMode::Plan- && tauri_plugin_agent_tools::tools::workqueue::is_work_mutation(name)- {- out.push(ToolOutcome::plain(id, plan_mode_read_only_msg(name)));- continue;- }- let args: serde_json::Value = tc- .get("function")- .and_then(|f| f.get("arguments"))- .and_then(|v| v.as_str())- .and_then(|s| serde_json::from_str(s).ok())- .unwrap_or(serde_json::Value::Object(Default::default()));- let content = self.handle_work_tool(name, &args);- out.push(ToolOutcome::plain(id, content));- continue;- }if !is_builtin(name) {let id = tc.get("id")@@ -1743,7 +1460,6 @@ impl ToolInvoker for CompositeToolInvoker {.filter_map(|(i, tc)| tc.get("id").and_then(|v| v.as_str()).map(|id| (id, i))).collect();out.sort_by_key(|o| *order.get(o.id.as_str()).unwrap_or(&usize::MAX));- self.note_batch(tool_calls, &out);Ok(out)}}@@ -1789,11 +1505,6 @@ pub(crate) async fn run_server_side_openai_orchestration(session_id: None,sandbox: None,monitors: None,- // The proxy has no session scratch and never dispatches subagents, so the- // collaboration layer is inert here; a fresh signal keeps the field total.- work_queue_enabled: false,- work_signal: std::sync::Arc::new(crate::core::agent::subagent::WorkSignal::new()),- collab_run_id: None,};let body = match json_body.get("max_turns") {Some(_) => std::borrow::Cow::Borrowed(json_body),@@ -1917,7 +1628,6 @@ fn advertise_local_tools(max_parallel_subagents: u32,ask_enabled: bool,todo_enabled: bool,- work_queue_enabled: bool,) {let planning = run_mode == crate::core::agent::plan::RunMode::Plan;if project_root.is_some() {@@ -1990,29 +1700,6 @@ fn advertise_local_tools(openai_tools.push(tauri_plugin_agent_tools::tools::monitor::monitor_tool_schema());}}- // Work-queue tools, gated on collaboration being enabled. Available to- // main AND to workers (unlike subagent dispatch, which caps recursion).- // The mutating three are hidden in Plan mode. `list_work` and `read_agent`- // are not advertised: the queue and each peer's status are visible to the- // user (the panel and `/agents`), and a worker's claim->do->complete loop- // does not need to poll them -- dropping them also shrinks the schema and- // removes two thirds of the poll-only set. Both stay recognized and- // executable (handlers untouched) so a named call still works.- if work_queue_enabled {- for schema in tauri_plugin_agent_tools::tools::workqueue::work_tool_schemas() {- let name = schema["function"]["name"].as_str().unwrap_or_default();- if name == "list_work" || permissions.is_denied(name) {- continue;- }- if planning && tauri_plugin_agent_tools::tools::workqueue::is_work_mutation(name) {- continue;- }- if allowed_names.is_some_and(|allowed| !allowed.contains(name)) {- continue;- }- openai_tools.push(schema);- }- }}// The `ask` tool needs no project (it's an interactive question, not// filesystem access), so it's advertised independent of the project_root@@ -2074,7 +1761,6 @@ fn build_run_system_prompt(session_id: Option<&str>,subagents_enabled: bool,sandbox: bool,- work_queue_enabled: bool,) -> Option<String> {let base = override_prompt.or(assistant_instructions);match project_root {@@ -2088,7 +1774,6 @@ fn build_run_system_prompt(root,scratch.as_deref(),subagents_enabled,- work_queue_enabled,)}None => base.map(str::to_string),@@ -2109,7 +1794,6 @@ pub(crate) fn context_system_prompt_preview(session_id: Option<&str>,subagents_enabled: bool,sandbox_flag: Option<bool>,- work_queue_enabled: bool,) -> Option<String> {let settings = resolve_run_settings(project_root, sandbox_flag);build_run_system_prompt(@@ -2119,7 +1803,6 @@ pub(crate) fn context_system_prompt_preview(session_id,subagents_enabled,settings.sandbox,- work_queue_enabled,)}@@ -2142,7 +1825,6 @@ pub(crate) async fn context_advertised_tools(max_parallel_subagents: u32,ask_enabled: bool,todo_enabled: bool,- work_queue_enabled: bool,) -> Vec<serde_json::Value> {let (mut tools, mut tool_to_server) =crate::core::agent::upstream::collect_mcp_openai_tools(mcp_servers, mcp_settings)@@ -2163,7 +1845,6 @@ pub(crate) async fn context_advertised_tools(max_parallel_subagents,ask_enabled,todo_enabled,- work_queue_enabled,);tools}@@ -2260,9 +1941,6 @@ async fn orchestrate_inner(session_id,monitors: session_monitors,sandbox,- work_queue_enabled,- work_signal,- collab_run_id,} = args;// Per-turn override: the TUI toggles plan mode live via the request body@@ -2326,7 +2004,6 @@ async fn orchestrate_inner(session_id.as_deref(),*subagents_enabled,settings.as_ref().is_some_and(|s| s.sandbox),- *work_queue_enabled,);// Normal parent runs recall project memory for the current query before it// is indexed. Child runs keep their isolated history and skip memory.@@ -2463,7 +2140,6 @@ async fn orchestrate_inner(*max_parallel_subagents,ask_requests.is_some(),todo_registry.is_some(),- *work_queue_enabled,);let (upstream_url, session_api_keys) = resolve_upstream_for_model(@@ -2505,13 +2181,8 @@ async fn orchestrate_inner(// Background subagents are scoped to this run: `_bg_guard` aborts any// still-running child when `orchestrate_inner` returns or is cancelled.// The cap (`max_parallel_subagents`) is snapshotted here, at run start.- // Share the run tree's one doorbell, so a child's `post_work` (its own- // registry, built from the cloned args) wakes this run's park.let bg = std::sync::Arc::new(- crate::core::agent::subagent::BackgroundSubagents::with_signal(- *max_parallel_subagents,- work_signal.clone(),- ),+ crate::core::agent::subagent::BackgroundSubagents::new(*max_parallel_subagents),);let _bg_guard = crate::core::agent::subagent::AbortOnDrop(bg.clone());let subagents = args.subagents_enabled.then(|| SubagentContext {@@ -2533,38 +2204,9 @@ async fn orchestrate_inner(// is unconfined: nothing binds it, so creating it would only leave an// empty directory behind.let scratch_root = scratch_root_for(session_id.as_deref(), root);- // Also ensured when collaboration is on but the shell is unconfined: the- // work queue and observability write here regardless of the sandbox- // (they never become a `resolve_path` rewrite root, so bash still sees- // the real `/tmp`), and their `validated_subdir` needs this to exist.- if settings.sandbox || *work_queue_enabled {+ if settings.sandbox {tauri_plugin_agent_tools::workspace::ensure_scratch_dir_path(&scratch_root).await?;}- // Collaboration identity + initial observability. `run_subagent`- // pre-writes a child's status (with its friendly name) before this runs,- // so reading it back preserves the name; main creates its own as "main".- let collab_run_id = collab_run_id.clone().unwrap_or_else(|| "main".to_string());- let (collab_status, transcript) = if *work_queue_enabled {- use tauri_plugin_agent_tools::tools::observ;- let now = tauri_plugin_agent_tools::tools::epoch_secs();- let mut status = observ::read_status(&scratch_root, &collab_run_id)- .unwrap_or_else(|| observ::AgentStatusView::new(&collab_run_id, &collab_run_id, now));- status.state = observ::STATE_RUNNING.to_string();- status.updated_at = now;- observ::write_status(&scratch_root, &status);- crate::core::agent::events::maybe_emit_agent_status(events, &scratch_root, &collab_run_id);- let transcript = observ::TranscriptWriter::create(&scratch_root, &collab_run_id);- (status, transcript)- } else {- (- tauri_plugin_agent_tools::tools::observ::AgentStatusView::new(- &collab_run_id,- &collab_run_id,- 0,- ),- None,- )- };let tools = CompositeToolInvoker {mcp: mcp_tools,store_root: tauri_plugin_agent_tools::workspace::project_store(root),@@ -2589,11 +2231,6 @@ async fn orchestrate_inner(monitors_outlive_run: session_monitors.is_some(),auto_approve: *auto_approve,run_mode,- work_queue_enabled: *work_queue_enabled,- work_signal: work_signal.clone(),- collab_run_id,- collab_status: std::sync::Mutex::new(collab_status),- transcript: std::sync::Mutex::new(transcript),};let result = run_turn_cycle(events,@@ -2900,13 +2537,6 @@ async fn run_turn_cycle(let mut mid_run_nudge_count: u32 = 0;// One-shot: asked the model to close out its todos before handing back.let mut closeout_nudged = false;- // Poll dampener: consecutive turns whose tool calls were *all* work-queue/- // observability polls (see `is_poll_only_tool`). A worker that only claims,- // lists and reads without doing or completing anything is stuck; nudge it- // once, then hard-stop a child that will not stop itself.- const POLL_STREAK_NUDGE: u32 = 3;- const POLL_STREAK_STOP: u32 = 6;- let mut poll_streak: u32 = 0;// The monitor set last published as `StreamEvent::Monitors`.let mut shown_monitors = Vec::new();@@ -2916,10 +2546,6 @@ async fn run_turn_cycle(index: (turn as u32) + 1,max: max_turns as u32,});- // Mirror the step into this agent's collaboration status header, so a- // peer reading its status sees an accurate live step even on a turn that- // calls no tools.- tools.record_step((turn as u32) + 1);// A turn this run just produced can carry poison of its own: a// length-truncated tool call, or an argument string that decodes to a@@ -3159,16 +2785,6 @@ async fn run_turn_cycle(return Ok(completion);}- // A turn that calls nothing but poll tools is one more turn of a spin;- // any productive call resets the count. Decided here, acted on (nudge/- // stop) after the results are appended so history stays clean.- let poll_only = tool_calls.iter().all(|tc| is_poll_only_tool(tool_call_fn_name(tc)));- if poll_only {- poll_streak += 1;- } else {- poll_streak = 0;- }-// Crossing the session budget is advisory: it is recorded and the run// carries on, tool calls included. Note what this costs -- `max_turns// == 0` is the normal case (see above), so with the budget no longer@@ -3430,41 +3046,6 @@ async fn run_turn_cycle(}}- // Poll dampener: acted on after the results are in the history, so a- // nudge or a synthetic stop leaves a well-formed conversation (no- // dangling tool_calls). Nudge once at the lower threshold; hard-stop a- // child at the higher one -- the main run is only nudged, since ending- // it would abort the children it may be waiting on.- if poll_only && poll_streak == POLL_STREAK_NUDGE {- crate::core::agent::reminder::attach(- &mut conversation_messages,- "You have spent several turns calling only work-queue/observability tools \- (claim_work/list_work/read_agent) without doing any work or producing a result. \- Stop polling -- you are pinged automatically when new work is ready. If your task \- is already done, call complete_work with your result (or, if you are not a worker, \- give your final answer) instead of calling these tools again.",- );- let _ = events.send(StreamEvent::MessagesUpdated {- messages: conversation_messages.clone(),- });- } else if poll_only && poll_streak >= POLL_STREAK_STOP && tools.collab_is_child() {- let stop = "Stopped after several consecutive turns of polling the work queue \- (claim_work/list_work/read_agent) with no progress and no result. There \- was no ready work to claim.";- conversation_messages.push(serde_json::json!({- "role": "assistant",- "content": stop,- }));- let _ = events.send(StreamEvent::MessagesUpdated {- messages: conversation_messages.clone(),- });- return Ok(serde_json::json!({- "choices": [{- "message": { "role": "assistant", "content": stop },- "finish_reason": "stop"- }]- }));- }turn += 1;}@@ -3627,7 +3208,6 @@ mod tests {Some("test-session"),false,true,- false,).expect("prompt");@@ -4684,148 +4264,6 @@ mod tests {);}- /// A worker invoker: every claim reports the queue empty, and `child`- /// decides whether the poll dampener is allowed to hard-stop this run.- struct PollTool {- child: bool,- }- #[async_trait]- impl ToolInvoker for PollTool {- async fn invoke(- &self,- tool_calls: &[serde_json::Value],- ) -> Result<Vec<ToolOutcome>, String> {- Ok(tool_calls- .iter()- .map(|tc| {- let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();- ToolOutcome::plain(id, "No work is ready right now. Stop and wait.".to_string())- })- .collect())- }- fn collab_is_child(&self) -> bool {- self.child- }- }-- fn claim_work_completion() -> serde_json::Value {- json!({- "choices": [{- "message": {- "content": serde_json::Value::Null,- "tool_calls": [{- "id": "call_1",- "type": "function",- "function": { "name": "claim_work", "arguments": "{}" }- }]- },- "finish_reason": "tool_calls"- }]- })- }-- fn carries_poll_nudge(request: &serde_json::Value) -> bool {- request["messages"]- .as_array()- .into_iter()- .flatten()- .any(|m| {- m.get("content")- .and_then(|c| c.as_str())- .is_some_and(|s| s.contains("Stop polling"))- })- }-- /// A child that only ever polls the work queue is hard-stopped by the- /// dampener well before it can exhaust its budget on the spin, and the run- /// ends with the explanatory stop answer rather than an error.- #[tokio::test]- async fn a_worker_spinning_on_poll_tools_is_stopped() {- let (tx, _rx) = mpsc::unbounded_channel();- let model = MockModel::new((0..30).map(|_| claim_work_completion()).collect());- let tool = PollTool { child: true };- let mut budget = SessionBudget::new(None);- let result = run_turn_cycle(- &tx,- &json!({}),- "m",- &[],- vec![json!({ "role": "user", "content": "review the file" })],- 0, // unlimited: only the dampener can end this run- &mut budget,- &model,- &tool,- crate::core::agent::plan::RunMode::Normal,- None,- None,- None,- )- .await- .unwrap();- let content = result["choices"][0]["message"]["content"].as_str().unwrap();- assert!(content.contains("Stopped"), "run ended with the stop answer: {content}");- // Streak reaches POLL_STREAK_STOP (6) on the 6th turn.- assert_eq!(model.requests.lock().unwrap().len(), 6);- }-- /// The nudge lands one turn after the lower threshold and before the stop:- /// absent on the 3rd request, present on the 4th.- #[tokio::test]- async fn a_polling_run_is_nudged_before_it_is_stopped() {- let (tx, _rx) = mpsc::unbounded_channel();- let model = MockModel::new((0..30).map(|_| claim_work_completion()).collect());- let tool = PollTool { child: true };- let mut budget = SessionBudget::new(None);- run_turn_cycle(- &tx,- &json!({}),- "m",- &[],- vec![json!({ "role": "user", "content": "go" })],- 0,- &mut budget,- &model,- &tool,- crate::core::agent::plan::RunMode::Normal,- None,- None,- None,- )- .await- .unwrap();- let requests = model.requests.lock().unwrap();- assert!(!carries_poll_nudge(&requests[2]), "not nudged before the 3rd poll turn");- assert!(carries_poll_nudge(&requests[3]), "nudged on the request after the 3rd");- }-- /// The main run is nudged like a worker but never hard-stopped: ending it- /// would abort the children it may be waiting on, so it runs to the turn cap.- #[tokio::test]- async fn the_main_run_is_nudged_but_not_stopped() {- let (tx, _rx) = mpsc::unbounded_channel();- let model = MockModel::new((0..8).map(|_| claim_work_completion()).collect());- let tool = PollTool { child: false };- let mut budget = SessionBudget::new(None);- let result = run_turn_cycle(- &tx,- &json!({}),- "m",- &[],- vec![json!({ "role": "user", "content": "go" })],- 8, // capped so the test terminates without a stop- &mut budget,- &model,- &tool,- crate::core::agent::plan::RunMode::Normal,- None,- None,- None,- )- .await;- assert!(result.is_err(), "main hit the turn cap, not the child stop: {result:?}");- assert_eq!(model.requests.lock().unwrap().len(), 8, "every turn ran");- }-/// A tool invoker whose one queued ping carries a headline, standing in for/// a monitor match. The headline must surface as `StreamEvent::Notice` at/// delivery; the text must reach the model as a `<SYSTEM>` reminder.@@ -5778,13 +5216,6 @@ mod tests {monitors_outlive_run: false,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,- work_queue_enabled: false,- work_signal: std::sync::Arc::new(crate::core::agent::subagent::WorkSignal::new()),- collab_run_id: "main".to_string(),- collab_status: std::sync::Mutex::new(- tauri_plugin_agent_tools::tools::observ::AgentStatusView::new("main", "main", 0),- ),- transcript: std::sync::Mutex::new(None),}}@@ -5912,7 +5343,6 @@ mod tests {Some("s1"),false,true,- false,).expect("prompt");assert!(confined.contains("Scratch:"), "{confined}");@@ -5923,7 +5353,6 @@ mod tests {Some("s1"),false,false,- false,).expect("prompt");assert!(!bare.contains("Scratch:"), "{bare}");diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex f759c9f82..d876ba227 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -121,12 +121,6 @@ pub(crate) struct AgentSection {/// out of the context budget.#[serde(default)]pub send_reasoning: Option<bool>,- /// Whether the run may use the shared work queue and per-agent- /// observability (`post_work`/`claim_work`/`complete_work`/`list_work`/- /// `read_agent`), letting the main agent fan work out to a pool of workers- /// that coordinate through files. Default true when unset.- #[serde(default)]- pub work_queue_enabled: Option<bool>,}// `default`/`allow`/`deny`/`allow_write` are consumed by `permissions_from`,@@ -183,7 +177,6 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]# show_reasoning = false # expand reasoning in the transcript (Ctrl-O still toggles)# send_reasoning = true # resend prior reasoning to the model; false drops it from the request# # (a provider that rejects the field is detected and stripped automatically)-# work_queue_enabled = true # shared work queue + per-agent observability so workers coordinate through files# Project-local provider override. Wins over ~/.jan/config.toml and any# provider inherited from Jan Desktop's settings.json. Most projects don'tdiff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 735a1e9a1..858833caa 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};use tauri_plugin_agent_tools::permissions::ToolPermissions;use tauri_plugin_agent_tools::tools::sandbox::scratch_display_path;use tauri_plugin_agent_tools::tools::spill::{- compose_subagent_result, fill_subagent_result, reserve_subagent_result,+ compose_subagent_result, fill_subagent_result, reserve_blackboard_result,};use tauri_plugin_agent_tools::workspace;@@ -58,7 +58,6 @@ struct SubagentFile {#[derive(Debug, Clone, PartialEq, Eq)]pub enum SubagentError {- UnknownSubagent(String),PermissionDenied(String),Upstream(String),Cancelled,@@ -67,15 +66,6 @@ pub enum SubagentError {impl std::fmt::Display for SubagentError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {- SubagentError::UnknownSubagent(n) => {- write!(- f,- "unknown subagent '{n}': no matching definition in the user or \- project scope. For a one-off subagent, retry with a `system_prompt` \- describing its role (required for any subagent_name that isn't already \- saved); to check saved names first, call list_subagents."- )- }SubagentError::PermissionDenied(m) => write!(f, "permission denied: {m}"),SubagentError::Upstream(m) => write!(f, "{m}"),SubagentError::Cancelled => write!(f, "subagent run cancelled"),@@ -504,17 +494,33 @@ pub fn intersect_allowed_tools(}}-/// A model- or orchestration-issued request to run a subagent. When-/// `subagent_name` resolves in the registry, that definition is used (and-/// `allowed_tools` further narrows it). Otherwise, if `system_prompt` is-/// provided, an ephemeral one-off subagent is run inline with that prompt (no-/// registry entry, no disk write) so create + dispatch collapse to one call.+/// One subagent within a phased dispatch. When `name` matches a saved definition+/// that definition's role and tools are used (and `allowed_tools` further narrows+/// it); otherwise the subagent runs as a focused general-purpose agent defined by+/// its `description` (the task) alone. `name` is also the blackboard filename its+/// answer is written to (`blackboard/<name>.md`).#[derive(Debug, Clone)]pub struct SubagentRequest {- pub subagent_name: String,+ pub name: String,pub description: String,pub allowed_tools: Option<Vec<String>>,- pub system_prompt: Option<String>,+}++/// A group of subagents that run concurrently. The next phase starts only once+/// every subagent here has finished, and each next-phase subagent is handed this+/// phase's results (the `blackboard/<name>.md` files). `number` is the model's+/// own `phase` key for this group (what the "phase N" badge shows), which the+/// parser only uses to order and group -- gaps and any base are fine.+#[derive(Debug, Clone)]+pub struct Phase {+ pub number: u32,+ pub subagents: Vec<SubagentRequest>,+}++/// A parsed `dispatch_subagent` call: one or more ordered phases.+#[derive(Debug, Clone)]+pub struct DispatchPlan {+ pub phases: Vec<Phase>,}/// The resolved plan for a dispatch: the winning definition plus the effective@@ -532,7 +538,7 @@ fn resolve_dispatch(req: &SubagentRequest,parent: &ToolPermissions,) -> Result<ResolvedDispatch, SubagentError> {- match registry.get(&req.subagent_name).cloned() {+ match registry.get(&req.name).cloned() {Some(definition) => {// Registered definition: the call-site allowlist further narrows it.let allowed_tools = intersect_allowed_tools(@@ -546,23 +552,17 @@ fn resolve_dispatch(})}None => {- // Unregistered: run an ephemeral one-off if an inline system_prompt- // was supplied; otherwise it's a genuine unknown-name error.- let system_prompt = req- .system_prompt- .clone()- .filter(|s| !s.trim().is_empty())- .ok_or_else(|| SubagentError::UnknownSubagent(req.subagent_name.clone()))?;+ // No saved definition: a focused general-purpose subagent defined by+ // its task. The call-site allowlist IS its toolset; only the parent's+ // deny-list narrows it further.let definition = SubagentDefinition {- name: req.subagent_name.clone(),+ name: req.name.clone(),description: req.description.clone(),- system_prompt,+ system_prompt: ephemeral_subagent_prompt(&req.name),allowed_tools: req.allowed_tools.clone(),model: None,scope: SubagentScope::Project,};- // The inline allowed_tools IS the definition's toolset; only the- // parent's deny-list narrows it further.let allowed_tools =intersect_allowed_tools(definition.allowed_tools.as_deref(), None, parent)?;Ok(ResolvedDispatch {@@ -573,6 +573,18 @@ fn resolve_dispatch(}}+/// The system prompt for a subagent dispatched without a saved definition: a+/// focused generalist whose closing report becomes the next phase's input.+fn ephemeral_subagent_prompt(name: &str) -> String {+ format!(+ "You are \"{name}\", a focused subagent handling one task as part of a larger plan. \+ Do exactly the task you are given, using your tools as needed, and do not wait for \+ clarification -- you cannot receive any. When you finish, end with a concise, \+ self-contained report of what you found or did: it is handed verbatim to the agents in \+ the next phase, so include the facts, paths, and decisions they will need."+ )+}+/// Child stream events are folded into the parent's own stream, except the/// child's terminal `Done`/`Error`: the parent must not see the child terminate/// its stream. Dispatch turns the child's result into a synthetic tool result@@ -612,52 +624,6 @@ fn next_subagent_run_id(name: &str) -> String {format!("sub-{name}-{}", SUBAGENT_RUN_SEQ.fetch_add(1, Ordering::Relaxed))}-/// A data-free, run-scoped doorbell rung by `post_work` from any agent (main or-/// a child) to wake a parked main so it can re-dispatch a worker. It shares its-/// `wake` with the run's [`BackgroundSubagents`], so ringing it wakes the same-/// park the completion pings do -- no new `await_background` select arm is added-/// (closing the review's starvation finding). `pending` is a single boolean,-/// *drained* (not queued) at the top of the next turn, so it cannot accumulate.-pub(crate) struct WorkSignal {- pending: std::sync::atomic::AtomicBool,- wake: Arc<tokio::sync::Notify>,-}--impl WorkSignal {- pub(crate) fn new() -> Self {- Self {- pending: std::sync::atomic::AtomicBool::new(false),- wake: Arc::new(tokio::sync::Notify::new()),- }- }-- /// Ring the bell: mark work available and wake a parked waiter.- pub(crate) fn post(&self) {- self.pending.store(true, Ordering::SeqCst);- self.wake.notify_waiters();- }-- /// Whether the bell is ringing (work posted since the last drain).- fn is_pending(&self) -> bool {- self.pending.load(Ordering::SeqCst)- }-- /// Take-and-clear the bell, returning whether it was ringing.- pub(crate) fn take(&self) -> bool {- self.pending.swap(false, Ordering::SeqCst)- }-- fn shared_wake(&self) -> Arc<tokio::sync::Notify> {- self.wake.clone()- }-}--impl Default for WorkSignal {- fn default() -> Self {- Self::new()- }-}-/// One in-flight background subagent: the channel that will carry its final/// result, the handle to abort it on parent cancellation/teardown, and the/// identity + event sink needed to close out its `SubagentStart` bracket if it@@ -716,18 +682,16 @@ pub(crate) struct BackgroundSubagents {/// conversation as a `<SYSTEM>` reminder at the top of the next turn.notices: std::sync::Mutex<Vec<Notice>>,/// Raised whenever a notice lands, so a parent that has run out of work can- /// park until a child finishes instead of ending the run under it. Shared- /// with [`WorkSignal`] (`work.shared_wake()`), so a `post_work` doorbell- /// wakes this same park -- no separate select arm.+ /// park until a child finishes instead of ending the run under it.wake: Arc<tokio::sync::Notify>,/// Children dispatched and not yet finished. Incremented at dispatch and/// decremented only *after* the notice is queued, so `has_pending_work`/// never reads false in the window between the two.running: std::sync::atomic::AtomicUsize,- /// The run-scoped work-available doorbell. Rung by any agent's `post_work`;- /// its `pending` flag counts toward `has_pending_work`/`wait_for_notice` so a- /// parked main stays alive and wakes when ready work appears.- work: Arc<WorkSignal>,+ /// Multi-phase plans still driving. A plan holds this above zero for its+ /// whole life, so the parent stays parked across the gap where one phase has+ /// finished (`running == 0`) but the driver has not yet spawned the next.+ plans_pending: std::sync::atomic::AtomicUsize,}/// Default cap on concurrently *running* subagents per parent run when@@ -745,24 +709,32 @@ impl BackgroundSubagents {/// Clamped to at least 1: a cap of 0 would make every dispatch queue/// forever with nothing ever releasing a permit.pub(crate) fn new(cap: u32) -> Self {- Self::with_signal(cap, Arc::new(WorkSignal::new()))- }-- /// Create a registry sharing a caller-supplied [`WorkSignal`], so `post_work`- /// from a child (which builds its own registry from the cloned run args)- /// rings the same doorbell the top-level run's park awaits.- pub(crate) fn with_signal(cap: u32, work: Arc<WorkSignal>) -> Self {Self {inner: std::sync::Mutex::new(std::collections::HashMap::new()),semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(cap.max(1) as usize)),queued: std::sync::atomic::AtomicUsize::new(0),notices: std::sync::Mutex::new(Vec::new()),- wake: work.shared_wake(),+ wake: Arc::new(tokio::sync::Notify::new()),running: std::sync::atomic::AtomicUsize::new(0),- work,+ plans_pending: std::sync::atomic::AtomicUsize::new(0),}}+ /// Mark a multi-phase plan as driving, keeping the parent parked until the+ /// driver calls [`end_plan`]. Balanced 1:1 with `end_plan`.+ fn begin_plan(&self) {+ self.plans_pending+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ }++ /// A plan's driver has spawned its last phase (or given up): stop holding the+ /// park open and wake anyone waiting so they re-evaluate.+ fn end_plan(&self) {+ self.plans_pending+ .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ self.wake.notify_waiters();+ }+/// Take every queued completion ping, oldest first.pub(crate) fn take_notices(&self) -> Vec<String> {std::mem::take(&mut *self.notices.lock().unwrap())@@ -776,7 +748,7 @@ impl BackgroundSubagents {pub(crate) fn has_pending_work(&self) -> bool {!self.notices.lock().unwrap().is_empty()|| self.running.load(std::sync::atomic::Ordering::SeqCst) > 0- || self.work.is_pending()+ || self.plans_pending.load(std::sync::atomic::Ordering::SeqCst) > 0}/// Park until a ping is available, or until nothing is left to wait for.@@ -789,13 +761,13 @@ impl BackgroundSubagents {let waiter = self.wake.notified();tokio::pin!(waiter);waiter.as_mut().enable();- // Re-check after enabling the waiter so a post/completion landing in- // the window is not missed (`notify_waiters` only reaches an- // already-registered waiter). The doorbell is a return condition- // like a notice; `running == 0` is the "nothing left" exit.+ // Re-check after enabling the waiter so a completion landing in the+ // window is not missed (`notify_waiters` only reaches an+ // already-registered waiter). `running == 0` is the "nothing left"+ // exit.if !self.notices.lock().unwrap().is_empty()- || self.work.is_pending()- || self.running.load(std::sync::atomic::Ordering::SeqCst) == 0+ || (self.running.load(std::sync::atomic::Ordering::SeqCst) == 0+ && self.plans_pending.load(std::sync::atomic::Ordering::SeqCst) == 0){return;}@@ -803,6 +775,32 @@ impl BackgroundSubagents {}}+ /// Park until every `run_id` in `ids` has finished (or is gone from the+ /// registry -- collected or aborted). The phase-plan driver's barrier between+ /// one phase and the next. Mirrors [`wait_for_notice`]'s wake discipline:+ /// the waiter is registered (`enable`) before the flags are re-read, so a+ /// child finishing in the window is not missed.+ async fn await_phase(&self, ids: &[String]) {+ use std::sync::atomic::Ordering;+ loop {+ let waiter = self.wake.notified();+ tokio::pin!(waiter);+ waiter.as_mut().enable();+ let all_done = {+ let guard = self.inner.lock().unwrap();+ ids.iter().all(|id| {+ guard+ .get(id)+ .is_none_or(|e| e.finished.load(Ordering::SeqCst))+ })+ };+ if all_done {+ return;+ }+ waiter.await;+ }+ }+fn push_notice(&self, run_id: &str, text: String) {self.notices.lock().unwrap().push(Notice {run_id: run_id.to_string(),@@ -909,27 +907,12 @@ fn child_body(serde_json::Value::Object(body)}-/// The child's system prompt: the definition's role, plus a one-line identity-/// when collaboration is on. Without its own name a subagent cannot tell it is-/// a lone agent, so the worker guide's queue loop reads as an invitation to wait-/// on a peer that isn't there. The behavioural rule (do your direct task, don't-/// wait on the queue) lives in the shared worker guide, not here.-fn child_system_prompt(role: &str, name: &str, work_queue_enabled: bool) -> String {- let mut prompt = role.to_string();- if work_queue_enabled {- prompt.push_str(&format!(- "\n\n# You\n\nYou are the subagent `{name}`, one of the agents on this run."- ));- }- prompt-}-/// Run one resolved subagent to completion, wrapping its events for `run_id` and/// returning its final assistant text. Isolated: fresh history (`description`),/// the definition's system prompt, narrowed tools, dispatch disabled.async fn run_subagent(parent_args: crate::core::agent::r#loop::OrchestrationArgs,- mut resolved: ResolvedDispatch,+ resolved: ResolvedDispatch,description: String,parent: ParentRun,events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,@@ -940,11 +923,7 @@ async fn run_subagent(let name = resolved.definition.name.clone();let mut child_args = parent_args;- child_args.system_prompt_override = Some(child_system_prompt(- &resolved.definition.system_prompt,- &name,- child_args.work_queue_enabled,- ));+ child_args.system_prompt_override = Some(resolved.definition.system_prompt.clone());child_args.subagents_enabled = false;// A subagent's own interactive question (if any) belongs to its parent's// conversation, not a client waiting on this child's ask_requests -- and@@ -956,32 +935,8 @@ async fn run_subagent(// A child's monitors are its own and die with it; nothing would pick up a// match left in the session set once the child has returned.child_args.monitors = None;- // A worker keeps the shared work queue (it is not nesting): it posts/claims/- // completes under its own run id and writes its status there. `work_signal`- // is the same Arc as the parent's, so its posts wake the parent's park.- child_args.collab_run_id = Some(run_id.clone());- // When collaboration is on, force the five work tools into a narrowed child- // toolset (as skills are), so a definition's `tools:` list does not strip- // them. A `None` allowlist already inherits them via default advertisement.- if child_args.work_queue_enabled {- if let Some(list) = resolved.allowed_tools.as_ref() {- resolved.allowed_tools = Some(with_workqueue_tools(list, &child_args.permissions));- }- }let body = child_body(&resolved, &description, &parent);- let collab_scratch = collab_scratch_for(&child_args);- // Pre-write the child's status header (with its friendly name) before it- // starts, so the roster shows it immediately and its own invoker reads the- // name back rather than falling back to the run id.- if let Some(scratch) = &collab_scratch {- use tauri_plugin_agent_tools::tools::observ;- let now = tauri_plugin_agent_tools::tools::epoch_secs();- let mut s = observ::AgentStatusView::new(&run_id, &name, now);- s.state = observ::STATE_RUNNING.to_string();- observ::write_status(scratch, &s);- crate::core::agent::events::maybe_emit_agent_status(&events, scratch, &run_id);- }let _ = events.send(StreamEvent::SubagentStart {run_id: run_id.clone(),@@ -996,12 +951,6 @@ async fn run_subagent(let forwarder = tokio::spawn(async move {while let Some(ev) = child_rx.recv().await {match &ev {- // A child's own status/queue events name a specific run_id or- // describe the shared queue, so they ride up unwrapped rather- // than nested in this child's Subagent envelope.- StreamEvent::AgentStatus { .. } | StreamEvent::WorkQueue { .. } => {- let _ = parent_events.send(ev);- }_ if forward_to_parent(&ev) => {let _ = parent_events.send(StreamEvent::Subagent {run_id: fwd_run_id.clone(),@@ -1022,13 +971,6 @@ async fn run_subagent(Ok(completion) => Ok(final_assistant_text(&completion)),Err(message) => Err(SubagentError::Upstream(message)),};- // Stamp the child's terminal status and free any work it claimed but never- // completed, so its dependents fail fast instead of blocking on a lease. The- // invoker wrote the running/activity status; this only flips the state.- if let Some(scratch) = &collab_scratch {- finalize_agent_status(scratch, &run_id, &name, outcome.is_ok());- crate::core::agent::events::maybe_emit_agent_status(&events, scratch, &run_id);- }let _ = events.send(StreamEvent::SubagentEnd {run_id,name,@@ -1037,61 +979,6 @@ async fn run_subagent(outcome}-/// The collaboration scratch a run shares with its peers: the session scratch-/// dir, independent of the bash sandbox. `None` when collaboration is off or the-/// run has no session (the proxy path), which also has no peers.-fn collab_scratch_for(- args: &crate::core::agent::r#loop::OrchestrationArgs,-) -> Option<std::path::PathBuf> {- if !args.work_queue_enabled {- return None;- }- args.session_id- .as_deref()- .map(tauri_plugin_agent_tools::workspace::scratch_dir)-}--/// Flip a finished child's `status.json` to `done`/`failed` (preserving the-/// step/tool-call counts its own invoker wrote) and fail every work item it-/// still holds an uncompleted claim on.-fn finalize_agent_status(scratch: &std::path::Path, run_id: &str, name: &str, ok: bool) {- use tauri_plugin_agent_tools::tools::observ;- let now = tauri_plugin_agent_tools::tools::epoch_secs();- let mut status = observ::read_status(scratch, run_id)- .unwrap_or_else(|| observ::AgentStatusView::new(run_id, name, now));- status.state = if ok {- observ::STATE_DONE- } else {- observ::STATE_FAILED- }- .to_string();- status.work_id = None;- status.updated_at = now;- observ::write_status(scratch, &status);- tauri_plugin_agent_tools::tools::workqueue::fail_owned_claims(scratch, run_id, now);-}--/// Tools force-added to every collaborating agent's toolset (the shared work-/// queue and observability), mirroring [`with_skill_tools`]. A worker keeps-/// these even when its definition narrows `tools:`.-const WORKQUEUE_TOOLS: &[&str] = &[- "post_work",- "claim_work",- "complete_work",- "list_work",- "read_agent",-];--fn with_workqueue_tools(tools: &[String], parent: &ToolPermissions) -> Vec<String> {- let mut out = tools.to_vec();- for tool in WORKQUEUE_TOOLS {- if !out.iter().any(|t| t == tool) && !parent.is_denied(tool) {- out.push((*tool).to_string());- }- }- out-}-/// Resolve and start a subagent on a background task, returning its `run_id`/// immediately (non-blocking). The caller collects the result later with/// [`await_subagent`]. Registered in `bg` so the parent run can abort it on@@ -1135,7 +1022,7 @@ pub(crate) fn spawn_subagent(let run_id = next_subagent_run_id(&name);let (tx, rx) = tokio::sync::oneshot::channel();let result_file = scratch.and_then(|s| {- reserve_subagent_result(s, &run_id).map(|path| (scratch_display_path(Some(s), &path), path))+ reserve_blackboard_result(s, &name).map(|path| (scratch_display_path(Some(s), &path), path))});let display_path = result_file.as_ref().map(|(display, _)| display.clone());@@ -1221,12 +1108,232 @@ pub(crate) fn spawn_subagent(finished,},);- Ok(Dispatched {- run_id,- display_path,+ Ok(Dispatched { run_id })+}++/// What a phased dispatch reports back to the model.+pub(crate) struct DispatchedPlan {+ pub(crate) phase_count: usize,+ pub(crate) total_subagents: usize,+ /// The subagents started right now (phase 1).+ pub(crate) first_phase_names: Vec<String>,+ /// The blackboard directory in the model's spelling, or `None` when the run+ /// is unconfined (no scratch: answers ride the completion pings inline).+ pub(crate) blackboard_dir: Option<String>,+}++/// `<scratch>/blackboard`.+fn blackboard_dir_path(scratch: &Path) -> PathBuf {+ scratch.join(tauri_plugin_agent_tools::tools::spill::BLACKBOARD_DIR)+}++/// Max bytes of each previous-phase answer folded into a next-phase brief, so a+/// verbose predecessor cannot blow the successor's context. The full answer is+/// always on the blackboard for the subagent to read in whole if it needs it.+const PHASE_INPUT_MAX_BYTES: usize = 12 * 1024;++/// The largest char boundary at or below `max`, so a byte truncation never splits+/// a UTF-8 sequence.+fn char_boundary(s: &str, max: usize) -> usize {+ if max >= s.len() {+ return s.len();+ }+ let mut i = max;+ while i > 0 && !s.is_char_boundary(i) {+ i -= 1;+ }+ i+}++/// Read the previous phase's answers (`blackboard/<name>.md`) for injection into+/// the next phase. Missing files are skipped -- a subagent that produced nothing+/// contributes nothing. `names` are already validated to the blackboard-stem+/// charset, so each maps to its file directly.+fn read_blackboard(scratch: Option<&Path>, names: &[String]) -> Vec<(String, String)> {+ let Some(s) = scratch else {+ return Vec::new();+ };+ let dir = blackboard_dir_path(s);+ names+ .iter()+ .filter_map(|n| {+ std::fs::read_to_string(dir.join(format!("{n}.md")))+ .ok()+ .map(|c| (n.clone(), c))+ })+ .collect()+}++/// Prefix a next-phase brief with the previous phase's results.+fn inject_inputs(task: &str, inputs: &[(String, String)]) -> String {+ if inputs.is_empty() {+ return task.to_string();+ }+ let mut s = String::from(+ "## Results from the previous phase\n\nThe agents before you produced the following; \+ their full outputs are also on the blackboard at blackboard/<name>.md.\n\n",+ );+ for (name, content) in inputs {+ s.push_str(&format!("### {name}\n"));+ let trimmed = content.trim();+ let cut = char_boundary(trimmed, PHASE_INPUT_MAX_BYTES);+ s.push_str(&trimmed[..cut]);+ if cut < trimmed.len() {+ s.push_str(&format!(+ "\n\n[...truncated; read blackboard/{name}.md for the full output]"+ ));+ }+ s.push_str("\n\n");+ }+ s.push_str("---\n\n");+ s.push_str(task);+ s+}++/// Start a phased dispatch: spawn phase 1 now and, when there is more than one+/// phase, spawn a background driver that advances through the remaining phases as+/// each completes, handing every phase its predecessor's blackboard results.+/// Returns as soon as phase 1 is dispatched. The whole plan is validated up front+/// so a bad subagent fails the dispatch atomically, before any child starts.+pub(crate) fn spawn_dispatch_plan(+ bg: &Arc<BackgroundSubagents>,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ plan: DispatchPlan,+ parent: &ParentRun,+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ scratch: Option<&Path>,+) -> Result<DispatchedPlan, SubagentError> {+ if !parent_args.subagents_enabled {+ return Err(SubagentError::PermissionDenied(+ "subagents cannot dispatch nested subagents".to_string(),+ ));+ }+ if plan.phases.is_empty() {+ return Err(SubagentError::Upstream(+ "a dispatch needs at least one phase".to_string(),+ ));+ }+ let project_root = parent_args.project_root.as_ref().ok_or_else(|| {+ SubagentError::Upstream("subagents require an active project".to_string())+ })?;+ let registry = SubagentRegistry::load(project_root);+ for phase in &plan.phases {+ for req in &phase.subagents {+ resolve_dispatch(®istry, req, &parent_args.permissions)?;+ }+ }++ let phase_count = plan.phases.len();+ let total_subagents = plan.phases.iter().map(|p| p.subagents.len()).sum();+ let blackboard_dir = scratch.map(|s| scratch_display_path(Some(s), &blackboard_dir_path(s)));++ let multi = phase_count > 1;+ if multi {+ // Announce the later phases up front so the UI can show their subagents+ // waiting on the phase before them; each is promoted by its own+ // SubagentStart/SubagentQueued (matched by name).+ let pending: Vec<crate::core::agent::events::PendingSubagent> = plan.phases[1..]+ .iter()+ .flat_map(|ph| {+ let phase = ph.number;+ ph.subagents+ .iter()+ .map(move |s| crate::core::agent::events::PendingSubagent {+ name: s.name.clone(),+ phase,+ })+ })+ .collect();+ let _ = events.send(crate::core::agent::events::StreamEvent::SubagentPlan { pending });+ // Hold the park open for the whole plan before the first child can finish.+ bg.begin_plan();+ }++ let mut phases = plan.phases.into_iter();+ let first = phases.next().expect("non-empty checked above");+ let mut first_names = Vec::with_capacity(first.subagents.len());+ let mut first_ids = Vec::with_capacity(first.subagents.len());+ for req in first.subagents {+ first_names.push(req.name.clone());+ match spawn_subagent(bg, parent_args, req, parent, events, scratch) {+ Ok(d) => first_ids.push(d.run_id),+ Err(e) => {+ if multi {+ bg.end_plan();+ }+ return Err(e);+ }+ }+ }++ if multi {+ let remaining: Vec<Phase> = phases.collect();+ let driver_bg = bg.clone();+ let driver_args = parent_args.clone();+ let driver_parent = parent.clone();+ let driver_events = events.clone();+ let driver_scratch = scratch.map(|s| s.to_path_buf());+ let driver_names = first_names.clone();+ tokio::spawn(async move {+ run_phase_plan(+ driver_bg,+ driver_args,+ driver_parent,+ driver_events,+ driver_scratch,+ first_ids,+ driver_names,+ remaining,+ )+ .await;+ });+ }++ Ok(DispatchedPlan {+ phase_count,+ total_subagents,+ first_phase_names: first_names,+ blackboard_dir,})}+/// The background driver for a multi-phase plan: wait out each phase, gather its+/// blackboard results, and spawn the next phase with those results injected.+#[allow(clippy::too_many_arguments)]+async fn run_phase_plan(+ bg: Arc<BackgroundSubagents>,+ parent_args: crate::core::agent::r#loop::OrchestrationArgs,+ parent: ParentRun,+ events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ scratch: Option<PathBuf>,+ mut prev_ids: Vec<String>,+ mut prev_names: Vec<String>,+ phases: Vec<Phase>,+) {+ for phase in phases {+ bg.await_phase(&prev_ids).await;+ let inputs = read_blackboard(scratch.as_deref(), &prev_names);+ let mut ids = Vec::with_capacity(phase.subagents.len());+ let mut names = Vec::with_capacity(phase.subagents.len());+ for mut req in phase.subagents {+ req.description = inject_inputs(&req.description, &inputs);+ names.push(req.name.clone());+ match spawn_subagent(&bg, &parent_args, req, &parent, &events, scratch.as_deref()) {+ Ok(d) => ids.push(d.run_id),+ Err(e) => bg.push_notice(+ "plan",+ format!("A subagent in the next phase could not start: {e}"),+ ),+ }+ }+ prev_ids = ids;+ prev_names = names;+ }+ // The last phase's children keep the run parked via the normal running count;+ // release the plan hold now that they exist.+ bg.end_plan();+}+/// What goes in the spill file. A failed child writes its failure there rather/// than leaving the reserved file empty: the parent was told to read that path,/// and an empty file reads as "the child had nothing to say".@@ -1259,11 +1366,10 @@ fn completion_notice(}}-/// What a dispatch reports back: the id to await on, and the file the answer-/// will be in when the child is done.+/// What a single `spawn_subagent` reports back: the id to await on. The answer's+/// file is the child's blackboard entry, reported by the plan as a whole.pub(crate) struct Dispatched {pub(crate) run_id: String,- pub(crate) display_path: Option<String>,}/// Block until the background subagent `run_id` finishes and return its final@@ -1338,13 +1444,13 @@ pub fn subagent_tool_schemas(names.dedup();names};- let one_off = " For a one-off subagent, pass system_prompt inline (with a descriptive subagent_name); use create_subagent only to save a reusable definition.";- let bg = format!(" Runs in the BACKGROUND and returns immediately with a run_id; keep working and dispatch more -- a note tells you the moment each one finishes and carries its answer (or the file its answer was written to). Up to {max_parallel} run concurrently (max_parallel_subagents in agent.toml); dispatches beyond that are queued FIFO and start as running ones finish.");+ let bg = format!(" Subagents run in the BACKGROUND, concurrently (up to {max_parallel} at once, from max_parallel_subagents in agent.toml; more are queued FIFO). You keep working and get a note the moment each finishes. Each subagent's final answer is written to blackboard/<name>.md in a shared scratch directory the whole plan can read from and write to.");+ let phases_desc = " List all the subagents in one call. To PIPELINE them, give a subagent a `phase`: subagents sharing a phase run together, lower phases run first, and each later phase is handed the previous phase's results automatically. Omit `phase` for a plain fan-out (one stage, everyone at once); use it to stage work (e.g. phase 0 researches in parallel, phase 1 synthesizes).";let dispatch_desc = if available.is_empty() {- format!("Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools.{bg}{one_off} No saved subagents yet.")+ format!("Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} No saved subagents yet; each runs as a focused general-purpose agent defined by its task.")} else {format!(- "Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools.{bg}{one_off} Saved subagents: {}.",+ "Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} A subagent whose name matches a saved one uses that role and tools; otherwise it runs as a focused general-purpose agent. Saved subagents: {}.",available.join(", "))};@@ -1357,16 +1463,26 @@ pub fn subagent_tool_schemas("parameters": {"type": "object","properties": {- "subagent_name": { "type": "string", "description": "Name of a saved subagent to run. For a one-off (no saved definition), pick a short descriptive name here AND pass system_prompt in the same call -- an unrecognized name with no system_prompt fails." },- "description": { "type": "string", "description": "The task for the subagent, as its sole user message. Include everything it needs; it does not see this conversation." },- "system_prompt": { "type": "string", "description": "Required alongside subagent_name whenever that name isn't already saved -- defines the one-off subagent's role. Omit only when subagent_name matches a saved subagent." },- "allowed_tools": {+ "subagents": {"type": "array",- "items": { "type": "string" },- "description": "Optional tool allowlist. OMIT this to give the subagent the parent's full toolset (the usual choice -- a subagent that runs tests needs bash, one that edits needs write, etc.). Provide a list ONLY to restrict it: for a saved subagent it further narrows that subagent's own tools (never widens); for a one-off the list IS its toolset. An empty list is treated as omitted, not as 'no tools'."+ "description": "The subagents to run. With no phases they all run concurrently; otherwise they run grouped and ordered by their `phase`.",+ "items": {+ "type": "object",+ "properties": {+ "name": { "type": "string", "description": "Short identity for this subagent, unique across the whole call: letters, digits, '-' and '_' only. It is also the blackboard file its answer is written to (blackboard/<name>.md). If it matches a saved subagent, that role and tools are used; otherwise it runs as a focused general-purpose agent." },+ "task": { "type": "string", "description": "The subagent's sole instruction. Include everything it needs; it does not see this conversation. A subagent in a later phase also receives the previous phase's results automatically, so tell it what to DO with them." },+ "phase": { "type": "integer", "minimum": 0, "description": "Optional stage (default 0). Subagents with the same phase run concurrently; a phase starts only after every lower phase has finished. Omit it entirely for a plain fan-out." },+ "allowed_tools": {+ "type": "array",+ "items": { "type": "string" },+ "description": "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs bash, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted."+ }+ },+ "required": ["name", "task"]+ }}},- "required": ["subagent_name", "description"]+ "required": ["subagents"]}}}),@@ -1439,18 +1555,80 @@ fn optional_tool_list(args: &serde_json::Value) -> Option<Vec<String>> {.filter(|list| !list.is_empty())}-/// Parse a `dispatch_subagent` tool-call argument object.-pub fn parse_dispatch_args(args: &serde_json::Value) -> Result<SubagentRequest, SubagentError> {- Ok(SubagentRequest {- subagent_name: required_str(args, "subagent_name")?,- description: required_str(args, "description")?,- allowed_tools: optional_tool_list(args),- system_prompt: args- .get("system_prompt")- .and_then(|v| v.as_str())- .map(str::to_string)- .filter(|s| !s.trim().is_empty()),- })+/// Longest subagent name accepted in a plan. Kept under the blackboard stem's+/// own 80-char cap so a validated name maps to `blackboard/<name>.md` verbatim+/// (no truncation), which is what lets the next phase read it back by name.+const MAX_SUBAGENT_NAME_LEN: usize = 64;++/// Parse a `dispatch_subagent` tool-call argument object into an ordered plan.+///+/// The wire shape is a flat `subagents` array; each subagent's optional `phase`+/// (a non-negative integer, default 0) groups it into a stage. Subagents that+/// share a `phase` run together; lower phases run first. This one shape covers+/// both a plain fan-out (omit `phase` everywhere -> a single stage) and a+/// pipeline (raise `phase` for later work). Names are validated (charset ++/// length) and required unique across the whole plan, since each is a blackboard+/// filename and a panel identity.+pub fn parse_dispatch_plan(args: &serde_json::Value) -> Result<DispatchPlan, SubagentError> {+ let subs_val = args+ .get("subagents")+ .and_then(|v| v.as_array())+ .ok_or_else(|| {+ SubagentError::Upstream(+ "missing required argument 'subagents' (an array of subagents, each with a name \+ and task, plus an optional integer 'phase')"+ .to_string(),+ )+ })?;+ if subs_val.is_empty() {+ return Err(SubagentError::Upstream(+ "'subagents' must contain at least one subagent".to_string(),+ ));+ }+ let mut seen = std::collections::HashSet::new();+ // BTreeMap so phases come out in ascending `phase` order regardless of the+ // order the model listed them, and sparse numbers (0, 5) just collapse to+ // adjacent stages.+ let mut by_phase: std::collections::BTreeMap<u32, Vec<SubagentRequest>> =+ std::collections::BTreeMap::new();+ for sub in subs_val {+ let name = required_str(sub, "name")?;+ validate_name(&name)?;+ if name.len() > MAX_SUBAGENT_NAME_LEN {+ return Err(SubagentError::PermissionDenied(format!(+ "subagent name '{name}' is too long (max {MAX_SUBAGENT_NAME_LEN} characters)"+ )));+ }+ if !seen.insert(name.clone()) {+ return Err(SubagentError::Upstream(format!(+ "duplicate subagent name '{name}': names must be unique across the whole plan \+ (each is a blackboard filename)"+ )));+ }+ let description = required_str(sub, "task")?;+ let phase = match sub.get("phase") {+ None | Some(serde_json::Value::Null) => 0,+ Some(v) => v+ .as_u64()+ .and_then(|n| u32::try_from(n).ok())+ .ok_or_else(|| {+ SubagentError::Upstream(format!(+ "subagent '{name}' has an invalid 'phase': use a non-negative integer \+ (0 = the first stage)"+ ))+ })?,+ };+ by_phase.entry(phase).or_default().push(SubagentRequest {+ name,+ description,+ allowed_tools: optional_tool_list(sub),+ });+ }+ let phases = by_phase+ .into_iter()+ .map(|(number, subagents)| Phase { number, subagents })+ .collect();+ Ok(DispatchPlan { phases })}/// Parse an `await_subagent` tool-call argument object, returning the run_id.@@ -1894,10 +2072,9 @@ mod tests {fn req(name: &str, allowed: Option<Vec<String>>) -> SubagentRequest {SubagentRequest {- subagent_name: name.to_string(),+ name: name.to_string(),description: "do the thing".to_string(),allowed_tools: allowed,- system_prompt: None,}}@@ -1936,42 +2113,20 @@ mod tests {assert_eq!(off["send_reasoning"], serde_json::json!(false));}- /// A collaborating subagent has to know its own name, or the shared worker- /// guide reads as an invitation to wait on a peer that isn't there. Off the- /// queue there are no peers, so no identity line is added.- #[test]- fn child_system_prompt_names_the_subagent_only_when_collaborating() {- let solo = child_system_prompt("You review code.", "kv-review", false);- assert_eq!(solo, "You review code.");- let collab = child_system_prompt("You review code.", "kv-review", true);- assert!(collab.starts_with("You review code."));- assert!(- collab.contains("subagent `kv-review`"),- "identity names the child: {collab}"- );- }-+ /// An unknown name is no longer an error: it runs as a focused generalist+ /// whose default prompt names it, with the request's tools as its toolset.#[test]- fn resolve_unknown_name_without_inline_prompt_errors() {- let reg = registry_with("reviewer", None);- let p = ToolPermissions::allow_all();- let err = resolve_dispatch(®, &req("nope", None), &p).unwrap_err();- assert!(matches!(err, SubagentError::UnknownSubagent(n) if n == "nope"));- }-- #[test]- fn resolve_unknown_name_with_inline_prompt_runs_ephemeral() {+ fn resolve_unknown_name_runs_ephemeral_generalist() {let reg = SubagentRegistry::default();let p = ToolPermissions::allow_all();let request = SubagentRequest {- subagent_name: "one-off".to_string(),+ name: "one-off".to_string(),description: "task".to_string(),allowed_tools: Some(vec!["read".to_string()]),- system_prompt: Some("You are a one-off.".to_string()),};let resolved = resolve_dispatch(®, &request, &p).unwrap();- assert_eq!(resolved.definition.system_prompt, "You are a one-off.");assert_eq!(resolved.definition.name, "one-off");+ assert!(resolved.definition.system_prompt.contains("one-off"));assert_eq!(resolved.allowed_tools,Some(vec![@@ -1983,14 +2138,72 @@ mod tests {}#[test]- fn parse_dispatch_reads_inline_system_prompt() {- let r = parse_dispatch_args(&serde_json::json!({- "subagent_name": "one-off",- "description": "task",- "system_prompt": "You are a one-off."+ fn parse_dispatch_plan_groups_flat_subagents_by_phase() {+ // Listed out of order and with a gap (0, 2); the parser groups and+ // orders them, and the phase number carried is the model's own key.+ let plan = parse_dispatch_plan(&serde_json::json!({+ "subagents": [+ { "name": "synthesize", "task": "write it up", "phase": 2 },+ { "name": "research-api", "task": "study the api" },+ { "name": "research-perf", "task": "study perf", "phase": 0, "allowed_tools": ["read", "grep"] }+ ]+ }))+ .unwrap();+ assert_eq!(plan.phases.len(), 2);+ assert_eq!(plan.phases[0].number, 0);+ assert_eq!(plan.phases[0].subagents.len(), 2);+ assert_eq!(plan.phases[0].subagents[0].name, "research-api");+ assert_eq!(+ plan.phases[0].subagents[1].allowed_tools,+ Some(vec!["read".to_string(), "grep".to_string()])+ );+ assert_eq!(plan.phases[1].number, 2);+ assert_eq!(plan.phases[1].subagents[0].name, "synthesize");+ }++ #[test]+ fn parse_dispatch_plan_fans_out_with_no_phase() {+ let plan = parse_dispatch_plan(&serde_json::json!({+ "subagents": [+ { "name": "a", "task": "x" },+ { "name": "b", "task": "y" }+ ]})).unwrap();- assert_eq!(r.system_prompt.as_deref(), Some("You are a one-off."));+ assert_eq!(plan.phases.len(), 1, "no phase key -> a single stage");+ assert_eq!(plan.phases[0].subagents.len(), 2);+ }++ #[test]+ fn parse_dispatch_plan_rejects_duplicate_names() {+ let err = parse_dispatch_plan(&serde_json::json!({+ "subagents": [+ { "name": "a", "task": "x" },+ { "name": "a", "task": "y", "phase": 1 }+ ]+ }))+ .unwrap_err();+ assert!(matches!(err, SubagentError::Upstream(m) if m.contains("duplicate")));+ }++ #[test]+ fn parse_dispatch_plan_rejects_empty_missing_and_bad_phase() {+ assert!(parse_dispatch_plan(&serde_json::json!({})).is_err());+ assert!(parse_dispatch_plan(&serde_json::json!({ "subagents": [] })).is_err());+ // missing task+ assert!(parse_dispatch_plan(+ &serde_json::json!({ "subagents": [ { "name": "a" } ] })+ )+ .is_err());+ // negative / non-integer phase+ assert!(parse_dispatch_plan(+ &serde_json::json!({ "subagents": [ { "name": "a", "task": "x", "phase": -1 } ] })+ )+ .is_err());+ assert!(parse_dispatch_plan(+ &serde_json::json!({ "subagents": [ { "name": "a", "task": "x", "phase": "later" } ] })+ )+ .is_err());}#[test]@@ -2263,50 +2476,6 @@ mod tests {assert!(bg.inner.lock().unwrap().is_empty(), "teardown drained the map");}- // ── work-available doorbell ────────────────────────────────────────────-- /// The doorbell counts toward `has_pending_work` and is cleared by `take`, so- /// a run with ready-but-unclaimed work stays alive one more turn (the nudge)- /// and then terminates once drained.- #[test]- fn a_post_keeps_the_run_alive_until_drained() {- let signal = Arc::new(WorkSignal::new());- let bg = BackgroundSubagents::with_signal(4, signal.clone());- assert!(!bg.has_pending_work(), "idle registry owes nothing");- signal.post();- assert!(bg.has_pending_work(), "a post keeps the run alive");- assert!(bg.take_notices().is_empty(), "the doorbell is not a notice queue");- assert!(signal.take(), "drain reports it was ringing");- assert!(!bg.has_pending_work(), "drained: nothing left to wait for");- assert!(!signal.take(), "a second drain is empty");- }-- /// A parked wait wakes when a *different* task rings the shared doorbell --- /// the child->main wake path, with no completion ping involved. The registry- /// reports a running child so the wait would otherwise block indefinitely.- #[tokio::test]- async fn a_shared_post_wakes_a_parked_wait() {- let signal = Arc::new(WorkSignal::new());- let bg = Arc::new(BackgroundSubagents::with_signal(4, signal.clone()));- // Pretend a child is running, so `wait_for_notice` does not return early.- bg.running.fetch_add(1, Ordering::SeqCst);-- let waiter = {- let bg = bg.clone();- tokio::spawn(async move { bg.wait_for_notice().await })- };- // Let the waiter register on the shared Notify before ringing.- tokio::task::yield_now().await;- tokio::task::yield_now().await;- assert!(!waiter.is_finished(), "the wait parks while a child runs");-- signal.post(); // a peer's post_work, via the shared signal- tokio::time::timeout(std::time::Duration::from_secs(2), waiter)- .await- .expect("the post must wake the parked wait")- .expect("waiter task");- }-// ── max-parallel admission (semaphore queue) ───────────────────────────/// Minimal run args for queue tests: empty providers (so dispatched@@ -2341,9 +2510,6 @@ mod tests {run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,sandbox: None,- work_queue_enabled: false,- work_signal: Arc::new(WorkSignal::new()),- collab_run_id: None,}}@@ -2466,6 +2632,95 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[test]+ fn inject_inputs_prefixes_and_truncates() {+ assert_eq!(inject_inputs("do it", &[]), "do it");+ let inputs = vec![("alpha".to_string(), "found X".to_string())];+ let out = inject_inputs("synthesize", &inputs);+ assert!(out.contains("Results from the previous phase"));+ assert!(out.contains("### alpha"));+ assert!(out.contains("found X"));+ assert!(out.trim_end().ends_with("synthesize"));++ let big = "x".repeat(PHASE_INPUT_MAX_BYTES + 500);+ let out = inject_inputs("t", &[("beta".to_string(), big)]);+ assert!(out.contains("truncated; read blackboard/beta.md"));+ }++ /// The heart of the phased dispatch: a later phase must not start until the+ /// earlier one has fully finished, and it must receive the earlier phase's+ /// blackboard results in its brief. Children fail fast (no provider), which is+ /// fine -- the scheduling contract and the injection are what this pins.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_later_phase_starts_after_the_earlier_one_with_its_results() {+ use crate::core::agent::events::StreamEvent;++ let root = unique_root("phaseplan");+ let scratch = root.join("scratch");+ std::fs::create_dir_all(&scratch).unwrap();+ let args = max_par_args(&root);+ let bg = Arc::new(BackgroundSubagents::new(4));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();++ let plan = DispatchPlan {+ phases: vec![+ Phase {+ number: 0,+ subagents: vec![req("alpha", None), req("beta", None)],+ },+ Phase {+ number: 1,+ subagents: vec![req("collector", None)],+ },+ ],+ };+ let d = spawn_dispatch_plan(&bg, &args, plan, &parent_run(), &tx, Some(&scratch)).unwrap();+ assert_eq!(d.phase_count, 2);+ assert_eq!(d.total_subagents, 3);+ assert!(bg.has_pending_work(), "a multi-phase plan holds the run open");++ // Drain like the real loop, bounded so a scheduling bug fails not hangs.+ tokio::time::timeout(std::time::Duration::from_secs(20), async {+ while bg.has_pending_work() {+ bg.wait_for_notice().await;+ let _ = bg.take_notices();+ }+ })+ .await+ .expect("the whole plan drains and releases the run");++ let mut order = Vec::new();+ let mut collector_task = None;+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::SubagentStart { name, task, .. } => {+ if name == "collector" {+ collector_task = task;+ }+ order.push(format!("start:{name}"));+ }+ StreamEvent::SubagentEnd { name, .. } => order.push(format!("end:{name}")),+ _ => {}+ }+ }+ let pos = |s: &str| order.iter().position(|e| e == s);+ let collector = pos("start:collector").expect("collector started");+ assert!(+ pos("end:alpha").unwrap() < collector && pos("end:beta").unwrap() < collector,+ "phase 2 waits for all of phase 1: {order:?}"+ );++ let task = collector_task.expect("collector carried a brief");+ assert!(+ task.contains("Results from the previous phase")+ && task.contains("alpha")+ && task.contains("beta"),+ "the collector's brief carries phase 1's blackboard: {task}"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+#[cfg(feature = "cli")]#[tokio::test]async fn await_on_queued_run_blocks_until_a_slot_frees() {@@ -2585,19 +2840,6 @@ mod tests {assert!(listed.contains("reviewer [project]: d"));}- #[test]- fn parse_dispatch_requires_name_and_description() {- let ok = parse_dispatch_args(&serde_json::json!({- "subagent_name": "reviewer",- "description": "review this",- "allowed_tools": ["read"]- }))- .unwrap();- assert_eq!(ok.subagent_name, "reviewer");- assert_eq!(ok.allowed_tools, Some(vec!["read".to_string()]));- assert!(parse_dispatch_args(&serde_json::json!({ "description": "x" })).is_err());- }-#[test]fn parse_create_defaults_scope_to_project() {let (def, scope, overwrite) = parse_create_args(&serde_json::json!({diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 880663055..a272062d6 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -692,7 +692,6 @@ fn build_cli_orchestration_args(plan: bool,max_parallel_subagents: u32,sandbox: Option<bool>,- work_queue_enabled: bool,) -> OrchestrationArgs {OrchestrationArgs {client: crate::core::agent::upstream::agent_http_client(),@@ -725,12 +724,6 @@ fn build_cli_orchestration_args(// `--sandbox` only when passed; unset falls through to the project's// `[tools].sandbox` and then the user's global `sandbox`.sandbox,- work_queue_enabled,- // One doorbell for the whole run tree; children inherit this exact Arc- // via their cloned args, so a child's post_work wakes this run's park.- work_signal: std::sync::Arc::new(crate::core::agent::subagent::WorkSignal::new()),- // The top-level run is "main"; children get their id from spawn_subagent.- collab_run_id: None,}}@@ -969,9 +962,6 @@ fn prepare_agent_session(.agent.max_parallel_subagents.unwrap_or(crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS);- // Collaboration (shared work queue + per-agent observability) is on by- // default; a project opts out with `[agent].work_queue_enabled = false`.- let work_queue_enabled = cfg.agent.work_queue_enabled.unwrap_or(true);let args = build_cli_orchestration_args(project_root,permissions,@@ -983,7 +973,6 @@ fn prepare_agent_session(flags.plan,max_parallel_subagents,flags.sandbox,- work_queue_enabled,);// Resolution order: configured `[agent].context_window` override, then the@@ -1395,6 +1384,14 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {StreamEvent::SubagentQueued { name, waiting, .. } => {eprintln!("\x1b[2m[subagent:{name}] queued ({waiting} waiting)\x1b[0m")}+ StreamEvent::SubagentPlan { pending } => {+ if let Some(max_phase) = pending.iter().map(|p| p.phase).max() {+ eprintln!(+ "\x1b[2m[plan] {} subagent(s) queued across later phases (through phase {max_phase})\x1b[0m",+ pending.len()+ )+ }+ }StreamEvent::SubagentEnd { name, error, .. } => match error {Some(e) => eprintln!("\x1b[2m[subagent:{name}] failed: {e}\x1b[0m"),None => eprintln!("\x1b[2m[subagent:{name}] finished\x1b[0m"),@@ -1408,26 +1405,6 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {StreamEvent::Parked => {eprintln!("\x1b[2m[parked] waiting on background work\x1b[0m")}- // A child's live status is real progress in a headless run; main's own- // status duplicates the [turn]/[tool] lines above, so it is not echoed.- StreamEvent::AgentStatus {- run_id,- name,- state,- work_id,- ..- } => {- if run_id != "main" {- let held = work_id.map(|w| format!(" [{w}]")).unwrap_or_default();- eprintln!("\x1b[2m[agent:{name}] {state}{held}\x1b[0m");- }- }- // One compact line per queue change: how many items are ready to- // dispatch out of the total, so a headless run shows the pool draining.- StreamEvent::WorkQueue { items } => {- let ready = items.iter().filter(|i| i.state == "open").count();- eprintln!("\x1b[2m[work] {ready}/{} ready\x1b[0m", items.len());- }StreamEvent::Subagent { name, event, .. } => {if let StreamEvent::ToolCall { name: tool, args, .. } = *event {eprintln!(diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex c702b46bc..f40fd5a57 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -55,7 +55,6 @@ use crate::core::agent::r#loop::{use serde_json::Value;use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use tauri_plugin_agent_tools::tools::monitor::{MonitorSet, MonitorSnapshot};-use tauri_plugin_agent_tools::tools::workqueue::WorkItemView;use tauri_plugin_agent_tools::workspace;/// Mouse tracking, hand-rolled instead of crossterm's `EnableMouseCapture`,@@ -2045,10 +2044,6 @@ struct App {/// Docked beside the fan-out; never a transcript row, since a monitor/// describes now.monitors: Vec<MonitorSnapshot>,- /// The run's shared work queue, replaced wholesale by each- /// `StreamEvent::WorkQueue`. Docked beside the fan-out and monitors in the- /// status panel (Phase 5); never a transcript row, since it describes now.- workqueue: Vec<WorkItemView>,/// The session-owned monitor registry, shared with every run through/// `OrchestrationArgs::monitors`. A watcher outlives the turn that started/// it, so the model can answer and the user can keep talking while it@@ -2305,10 +2300,13 @@ struct SubagentPanel {queued: bool,/// 1-based position in the queue at the time the child was queued.waiting: u32,- /// The work item this child currently holds, from its `AgentStatus`. Shown- /// as a `w-N` tag beside its stats so a fan-out over the shared queue reads- /// as who-is-on-what, not just who is running.- work_id: Option<String>,+ /// True for a later-phase subagent named by `SubagentPlan` that has not+ /// started yet: it is waiting on the phase before it. Flipped off when its+ /// own `SubagentStart`/`SubagentQueued` arrives (matched by name).+ pending: bool,+ /// 1-based phase this subagent belongs to, for phases past the first. `None`+ /// for a plain (single-phase) fan-out, whose agents carry no phase badge.+ phase: Option<u32>,}/// How a closed child's summary row reads. `Failed` carries the reason the@@ -2512,7 +2510,6 @@ impl App {exit_armed: false,subagents: Vec::new(),monitors: Vec::new(),- workqueue: Vec::new(),monitor_set: Arc::new(MonitorSet::new()),parked: false,subagent_blocks: Vec::new(),@@ -3041,13 +3038,14 @@ impl App {/// accounted for rather than vanishing with the panel.fn close_live_background(&mut self) {for panel in std::mem::take(&mut self.subagents) {+ // A later-phase subagent that never started has no run to summarize;+ // drop it rather than report a phantom "interrupted (0 calls)".+ if panel.pending {+ continue;+ }self.push_subagent_summary(&panel.name, panel.calls, SubagentOutcome::Interrupted);}self.awaiting.clear();- // The work queue is run display state: a finished queue of done/failed- // items should not linger on an idle session (a later run republishes a- // live one). The files persist in scratch for `list_work`/`read_agent`.- self.workqueue.clear();// Session monitors outlive the run, so the dock keeps whatever is// still watching; a run that ended is no longer parked on anything.self.monitors = self.monitor_set.snapshot();@@ -4685,7 +4683,6 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {args.session_id.as_deref(),args.subagents_enabled,args.sandbox,- args.work_queue_enabled,).unwrap_or_default();context_bytes =@@ -4708,7 +4705,6 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {args.max_parallel_subagents,args.ask_requests.is_some(),args.todo_registry.is_some(),- args.work_queue_enabled,).await.iter()@@ -5061,12 +5057,46 @@ impl App {self.ask_queue.retain(|ask| ask.request_id != request_id);self.publish_agent_status();}+ StreamEvent::SubagentPlan { pending } => {+ // The later phases of a plan, named before they start. Open a+ // waiting panel per subagent so a dependent phase is visible up+ // front; its own SubagentStart/SubagentQueued promotes it later.+ self.finalize_tool_group();+ self.flush_assistant();+ for p in pending {+ self.subagents.push(SubagentPanel {+ run_id: String::new(),+ name: p.name,+ task: String::new(),+ calls: Vec::new(),+ requests: 0,+ prompt_tokens: 0,+ active: None,+ queued: false,+ waiting: 0,+ pending: true,+ phase: Some(p.phase),+ });+ }+ }StreamEvent::SubagentStart { run_id, name, task } => {- // A queued dispatch already opened a panel for this run; promote- // it to running instead of pushing a duplicate. Otherwise open a- // fresh live panel (several may be active).+ // A queued/pending dispatch already opened a panel; promote it to+ // running instead of pushing a duplicate. A queued one matches by+ // run_id; a pending later-phase one matches by name (no run_id+ // yet). Otherwise open a fresh live panel (several may be active).if let Some(panel) = self.subagents.iter_mut().find(|p| p.run_id == run_id) {panel.queued = false;+ } else if let Some(panel) = self+ .subagents+ .iter_mut()+ .find(|p| p.pending && p.name == name)+ {+ panel.run_id = run_id;+ panel.pending = false;+ panel.queued = false;+ if let Some(t) = task {+ panel.task = t;+ }} else {self.finalize_tool_group();self.flush_assistant();@@ -5080,7 +5110,8 @@ impl App {active: None,queued: false,waiting: 0,- work_id: None,+ pending: false,+ phase: None,});}}@@ -5091,22 +5122,38 @@ impl App {waiting,} => {// The cap is exhausted; this dispatch will start when a running- // child finishes. Open its panel now, marked queued, so the- // fan-out shows the queue instead of hiding dispatches.+ // child finishes. Promote a pending later-phase panel (matched by+ // name) or open a fresh queued one, so the fan-out shows the queue+ // instead of hiding dispatches.self.finalize_tool_group();self.flush_assistant();- self.subagents.push(SubagentPanel {- run_id,- name,- task: task.unwrap_or_default(),- calls: Vec::new(),- requests: 0,- prompt_tokens: 0,- active: None,- queued: true,- waiting,- work_id: None,- });+ if let Some(panel) = self+ .subagents+ .iter_mut()+ .find(|p| p.pending && p.name == name)+ {+ panel.run_id = run_id;+ panel.pending = false;+ panel.queued = true;+ panel.waiting = waiting;+ if let Some(t) = task {+ panel.task = t;+ }+ } else {+ self.subagents.push(SubagentPanel {+ run_id,+ name,+ task: task.unwrap_or_default(),+ calls: Vec::new(),+ requests: 0,+ prompt_tokens: 0,+ active: None,+ queued: true,+ waiting,+ pending: false,+ phase: None,+ });+ }}StreamEvent::SubagentEnd {run_id,@@ -5137,19 +5184,6 @@ impl App {}StreamEvent::Monitors { monitors } => self.monitors = monitors,StreamEvent::Parked => self.parked = true,- // The shared work queue as a whole, docked in the status panel's- // coordination lane. Display-only, never journaled.- StreamEvent::WorkQueue { items } => self.workqueue = items,- // A per-agent status delta. A child's `work_id` tags its live panel;- // the main run's own status is already conveyed by the header badge,- // so it is not re-shown here (its status.json still feeds read_agent).- StreamEvent::AgentStatus { run_id, work_id, .. } => {- if run_id != "main" {- if let Some(panel) = self.subagents.iter_mut().find(|p| p.run_id == run_id) {- panel.work_id = work_id;- }- }- }StreamEvent::Subagent {run_id,name,@@ -13125,17 +13159,11 @@ fn agent_picker_items(subagents: &[SubagentPanel]) -> Vec<PickerItem> {subagents.iter().map(|p| {- let work = p- .work_id- .as_ref()- .map(|w| format!(" · {w}"))- .unwrap_or_default();PickerItem {label: format!(- "{} · {}t{} · {}",+ "{} · {}t · {}",p.name,p.calls.len(),- work,panel_activity_summary(p)),value: p.run_id.clone(),@@ -13152,6 +13180,12 @@ fn agent_picker_items(subagents: &[SubagentPanel]) -> Vec<PickerItem> {/// `&mut`; the tool name is enough here). A spin of identical calls collapses to/// `label ×N` so a stuck worker reads as stuck.fn panel_activity_summary(panel: &SubagentPanel) -> String {+ if panel.pending {+ return match panel.phase {+ Some(p) => format!("phase {p} (waiting)"),+ None => "waiting".to_string(),+ };+ }let repeats = trailing_repeat(&panel.calls);if repeats >= STUCK_REPEAT_THRESHOLD {return format!("{} ×{repeats}", panel.calls.last().cloned().unwrap_or_default());@@ -13203,9 +13237,6 @@ fn agent_detail_lines(Span::styled(format!(" ({})", panel.run_id), dim),])];let mut stats = format!("{} tools · {} req", panel.calls.len(), panel.requests);- if let Some(w) = &panel.work_id {- stats.push_str(&format!(" · {w}"));- }if panel.queued {stats.push_str(&format!(" · queued ({})", panel.waiting));}@@ -16815,13 +16846,12 @@ const PANEL_GUTTER: u16 = 3;const AGENT_MAX_ROWS: usize = 3;/// A trailing run of identical calls this long reads as a spin, not progress, so-/// the collapsed `×N` marker turns red to flag it. Aligned with the loop's own-/// poll dampener, which nudges around the same point.+/// the collapsed `×N` marker turns red to flag it.const STUCK_REPEAT_THRESHOLD: usize = 4;/// Length of the trailing run of the last entry in `calls`: 0 when empty, 1 when/// the last call differs from the one before it. Lets the panel collapse a spin-/// (`read_agent …` repeated dozens of times) into one `×N` line instead of+/// (`bash …` repeated dozens of times) into one `×N` line instead of/// showing the newest copy alone, with only the tool counter to betray the loop.fn trailing_repeat(calls: &[String]) -> usize {match calls.last() {@@ -16875,11 +16905,26 @@ fn agents_column(.map_or(0, |n| n.min(AGENT_MAX_ROWS - 1));for panel in panels.iter_mut().take(shown) {+ let idle = panel.queued || panel.pending;let mut spans = vec![Span::styled(- format!("{} ", if panel.queued { "·" } else { frame }),+ format!("{} ", if idle { "·" } else { frame }),Style::new().magenta(),)];- if panel.queued {+ if panel.pending {+ // A later-phase subagent waiting on the phase before it: no run yet,+ // so show which phase it belongs to instead of live stats.+ spans.push(Span::styled(+ truncate(&panel.name, max.saturating_sub(18)),+ Style::new().magenta().dim(),+ ));+ spans.push(Span::styled(+ match panel.phase {+ Some(p) => format!(" phase {p} · waiting"),+ None => " waiting".to_string(),+ },+ Style::new().yellow(),+ ));+ } else if panel.queued {// Parked on the `max_parallel_subagents` cap; the child has not// started, so there are no live stats -- its queue position instead.spans.push(Span::styled(@@ -16898,6 +16943,11 @@ fn agents_column(// Compact stats: side by side with the plan there is no room for// "33 tools · 24 req", and the units are obvious in context.let mut stats = format!(" {}t · {}r", panel.calls.len(), panel.requests);+ // A running subagent from a later phase keeps its phase badge, so the+ // dependent-stage hint persists past the wait.+ if let Some(p) = panel.phase {+ stats.push_str(&format!(" · phase {p}"));+ }// Only once the child has reported usage; "0%" before its first// response would read as a stalled agent rather than a starting one.// `context_window` arrives as 0 when the session has disproven it,@@ -16907,9 +16957,6 @@ fn agents_column(let pct = (panel.prompt_tokens as f64 / context_window as f64 * 100.0).min(100.0);stats.push_str(&format!(" · {pct:.1}%"));}- if let Some(work_id) = &panel.work_id {- stats.push_str(&format!(" · {work_id}"));- }spans.push(Span::styled(stats, dim));}out.push(Line::from(spans));@@ -16948,7 +16995,8 @@ fn agents_column((text, Style::new().dim())}).or_else(|| {- (!panel.queued).then(|| ("starting…".to_string(), Style::new().dim()))+ (!panel.queued && !panel.pending)+ .then(|| ("starting…".to_string(), Style::new().dim()))}),}};@@ -17415,14 +17463,12 @@ fn status_panel(app: &mut App, width: u16, rows: usize) -> Vec<Line<'static>> {// known (configured, catalog, or fallback), so it is always a denominator.let context_window = app.context_window;let has_todos = !app.todos.is_empty() && !app.todos_expired();- let has_activity =- !app.subagents.is_empty() || !app.monitors.is_empty() || !app.workqueue.is_empty();+ let has_activity = !app.subagents.is_empty() || !app.monitors.is_empty();match (has_todos, has_activity) {(false, false) => Vec::new(),(true, false) => todo_column(&app.todos, width, rows),(false, true) => activity_column(&mut app.subagents,- &app.workqueue,&app.monitors,context_window,width,@@ -17434,7 +17480,6 @@ fn status_panel(app: &mut App, width: u16, rows: usize) -> Vec<Line<'static>> {// the activity, which is the thing actually moving.let activity = activity_column(&mut app.subagents,- &app.workqueue,&app.monitors,context_window,width,@@ -17451,7 +17496,6 @@ fn status_panel(app: &mut App, width: u16, rows: usize) -> Vec<Line<'static>> {let left = todo_column(&app.todos, left_w, rows);let right = activity_column(&mut app.subagents,- &app.workqueue,&app.monitors,context_window,right_w,@@ -17468,21 +17512,14 @@ fn status_panel(app: &mut App, width: u16, rows: usize) -> Vec<Line<'static>> {/// capped at half the budget; the agents take whatever they leave.fn activity_column(panels: &mut [SubagentPanel],- workqueue: &[WorkItemView],monitors: &[MonitorSnapshot],context_window: u64,width: u16,rows: usize,frame: &str,) -> Vec<Line<'static>> {- // Agents keep priority: the compact sections (the work queue and the- // monitors) share at most half the budget when agents are present, and take- // only what they need otherwise. Queue sits above monitors.- let want_queue = if workqueue.is_empty() {- 0- } else {- 1 + workqueue.len()- };+ // Agents keep priority: the monitors share at most half the budget when+ // agents are present, and take only what they need otherwise.let want_mon = if monitors.is_empty() {0} else {@@ -17491,85 +17528,15 @@ fn activity_column(let compact_budget = if panels.is_empty() {rows} else {- (want_queue + want_mon).min(rows / 2)+ want_mon.min(rows / 2)};- let queue = workqueue_column(workqueue, width, want_queue.min(compact_budget));- let monitors = monitors_column(monitors, width, compact_budget.saturating_sub(queue.len()));- let used = queue.len() + monitors.len();+ let monitors = monitors_column(monitors, width, compact_budget);+ let used = monitors.len();let mut out = agents_column(panels, context_window, width, rows.saturating_sub(used), frame);- out.extend(queue);out.extend(monitors);out}-/// The shared work queue as a column: one line per item with a state glyph, its-/// `w-N` id, title, and the `-> owner` flow tag that is the work-sharing-/// indicator. A failed/blocked item shows its reason so a stuck graph is visible-/// rather than silent.-fn workqueue_column(items: &[WorkItemView], width: u16, rows: usize) -> Vec<Line<'static>> {- if items.is_empty() || rows == 0 {- return Vec::new();- }- let dim = Style::new().dark_gray();- let max = width.max(8) as usize;- let ready = items.iter().filter(|i| i.state == "open").count();- let mut out = vec![Line::from(vec![- Span::styled("~ ", Style::new().magenta()),- Span::styled(- format!("work queue ({ready} ready)"),- Style::new().magenta().bold(),- ),- ])];- let body = rows - 1;- let (shown, hidden) = if items.len() <= body {- (items.len(), 0)- } else {- (body.saturating_sub(1), items.len() - body.saturating_sub(1))- };- for item in items.iter().take(shown) {- let (glyph, gstyle) = work_glyph(&item.state);- let id = format!("{} ", item.work_id);- let owner = item- .claimed_by- .as_deref()- .map(|w| format!(" -> {w}"))- .unwrap_or_default();- let reason = item- .reason- .as_deref()- .map(|r| format!(" ({r})"))- .unwrap_or_default();- let text = format!("{}{owner}{reason}", item.title);- let reserve = 2 + id.len();- out.push(Line::from(vec![- Span::styled(format!("{glyph} "), gstyle),- Span::styled(id, dim),- Span::styled(truncate(&text, max.saturating_sub(reserve)), gstyle),- ]));- }- if hidden > 0 {- out.push(Line::from(vec![Span::styled(- format!(" +{hidden} more"),- dim,- )]));- }- out.truncate(rows);- out-}--/// The leading glyph + colour for a work item's state. ASCII markers so the-/// column stays single-width and alignment-preserving.-fn work_glyph(state: &str) -> (&'static str, Style) {- match state {- "open" => ("o", Style::new().magenta()),- "claimed" => ("@", Style::new().yellow()),- "done" => ("*", Style::new().green()),- "failed" => ("!", Style::new().red()),- "blocked" => ("x", Style::new().dark_gray()),- _ => ("-", Style::new().dark_gray()),- }-}-/// The session's active monitors, as a column: one line per monitor (id, name,/// polls so far), plus its script when the budget stretches to a second row/// each.@@ -17998,8 +17965,7 @@ mod tests {};use super::{agent_detail_lines, agent_picker_items, agents_column, background_shell_picker_items,- collapse_runs, open_agents_picker, trailing_repeat, workqueue_column, SubagentPanel,- WorkItemView,+ collapse_runs, open_agents_picker, trailing_repeat, SubagentPanel,};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::r#loop::PermissionRegistry;@@ -18094,46 +18060,6 @@ mod tests {TestApp { app, _dir: dir }}- fn work_item(work_id: &str, state: &str, claimed_by: Option<&str>, reason: Option<&str>) -> WorkItemView {- WorkItemView {- work_id: work_id.to_string(),- title: format!("task {work_id}"),- state: state.to_string(),- claimed_by: claimed_by.map(str::to_string),- reason: reason.map(str::to_string),- }- }-- #[test]- fn workqueue_column_shows_state_owner_flow_and_reason() {- let items = vec![- work_item("w-1", "done", None, None),- work_item("w-2", "claimed", Some("reviewer-3"), None),- work_item("w-3", "failed", None, Some("dep w-2 failed")),- work_item("w-4", "open", None, None),- ];- let lines: Vec<String> = workqueue_column(&items, 60, 8)- .iter()- .map(line_text)- .collect();- assert!(lines[0].contains("work queue (1 ready)"), "{lines:?}");- let claimed = lines.iter().find(|l| l.contains("w-2")).unwrap();- assert!(claimed.contains("-> reviewer-3"), "owner flow: {claimed}");- let failed = lines.iter().find(|l| l.contains("w-3")).unwrap();- assert!(failed.contains("dep w-2 failed"), "reason: {failed}");- }-- #[test]- fn workqueue_column_elides_its_tail_under_budget() {- let items: Vec<WorkItemView> = (1..=20)- .map(|n| work_item(&format!("w-{n}"), "open", None, None))- .collect();- let lines = workqueue_column(&items, 60, 4);- assert_eq!(lines.len(), 4, "never exceeds its row budget");- let last = line_text(lines.last().unwrap());- assert!(last.contains("more"), "tail elided: {last}");- }-fn panel_with_calls(name: &str, calls: Vec<&str>) -> SubagentPanel {SubagentPanel {run_id: format!("sub-{name}-1"),@@ -18145,7 +18071,8 @@ mod tests {active: None,queued: false,waiting: 0,- work_id: None,+ pending: false,+ phase: None,}}@@ -18162,13 +18089,13 @@ mod tests {/// with one innocuous call on screen.#[test]fn agents_column_collapses_a_repeated_call() {- let call = "read_agent {\"run_id\":\"sub-kv-review-1\",\"tail\":1}";+ let call = "bash {\"command\":\"ls -la\"}";let mut panels = vec![panel_with_calls("kv-review", vec![call; 5])];let lines = agents_column(&mut panels, 200_000, 80, 8, "-");let text = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");assert!(text.contains("×5"), "collapsed spin shows its count: {text}");// The single call is not duplicated across five rows.- assert_eq!(text.matches("read_agent").count(), 1, "one collapsed row: {text}");+ assert_eq!(text.matches("bash").count(), 1, "one collapsed row: {text}");}#[test]@@ -18190,7 +18117,7 @@ mod tests {#[test]fn agents_picker_row_names_the_child_and_flags_a_spin() {- let panels = vec![panel_with_calls("kv-review", vec!["read_agent {}"; 4])];+ let panels = vec![panel_with_calls("kv-review", vec!["bash {}"; 4])];let items = agent_picker_items(&panels);assert_eq!(items.len(), 1);assert_eq!(items[0].value, "sub-kv-review-1");@@ -18200,7 +18127,7 @@ mod tests {#[test]fn agent_detail_shows_stats_and_collapses_a_spin() {- let panels = vec![panel_with_calls("kv-review", vec!["claim_work {}"; 5])];+ let panels = vec![panel_with_calls("kv-review", vec!["bash {}"; 5])];let lines = agent_detail_lines(&panels, Some("sub-kv-review-1"), 80, 20);let text = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");assert!(text.contains("kv-review") && text.contains("sub-kv-review-1"), "{text}");@@ -18217,6 +18144,48 @@ mod tests {assert!(text.contains("finished"), "{text}");}+ /// A later phase's subagents appear waiting (with their phase) before they+ /// start, and each is promoted in place by its own SubagentStart -- no+ /// duplicate panel, and the phase badge survives the promotion.+ #[tokio::test]+ async fn a_pending_phase_subagent_waits_then_is_promoted_by_name() {+ use crate::core::agent::events::PendingSubagent;+ let mut app = test_app();+ app.apply(StreamEvent::SubagentPlan {+ pending: vec![PendingSubagent {+ name: "collector".to_string(),+ phase: 2,+ }],+ });+ assert_eq!(app.subagents.len(), 1);+ assert!(app.subagents[0].pending && app.subagents[0].phase == Some(2));++ let text = agents_column(&mut app.subagents, 200_000, 80, 8, "-")+ .iter()+ .map(line_text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(+ text.contains("collector") && text.contains("phase 2") && text.contains("waiting"),+ "the waiting hint is shown: {text}"+ );++ app.apply(StreamEvent::SubagentStart {+ run_id: "sub-collector-1".to_string(),+ name: "collector".to_string(),+ task: Some("synthesize".to_string()),+ });+ assert_eq!(app.subagents.len(), 1, "promoted in place, not duplicated");+ assert!(!app.subagents[0].pending);+ assert_eq!(app.subagents[0].run_id, "sub-collector-1");+ assert_eq!(app.subagents[0].task, "synthesize");+ assert_eq!(+ app.subagents[0].phase,+ Some(2),+ "keeps its phase badge once running"+ );+ }+/// Enter on the `/agents` list drills into a child's detail; Esc steps back/// to the list rather than closing the inspector.#[tokio::test]@@ -18297,40 +18266,6 @@ mod tests {assert!(items[0].value.is_empty());}- #[test]- fn agent_status_tags_the_child_panel_and_ignores_main() {- let mut app = test_app();- app.apply(StreamEvent::SubagentStart {- run_id: "sub-a-1".to_string(),- name: "a".to_string(),- task: Some("do it".to_string()),- });- app.apply(StreamEvent::AgentStatus {- run_id: "sub-a-1".to_string(),- name: "a".to_string(),- state: "running".to_string(),- step: 2,- tool_calls: 3,- last: "edit".to_string(),- work_id: Some("w-7".to_string()),- });- let panel = app.subagents.iter().find(|p| p.run_id == "sub-a-1").unwrap();- assert_eq!(panel.work_id.as_deref(), Some("w-7"));- // A main status delta never creates or mutates a panel.- let before = app.subagents.len();- app.apply(StreamEvent::AgentStatus {- run_id: "main".to_string(),- name: "main".to_string(),- state: "running".to_string(),- step: 1,- tool_calls: 0,- last: String::new(),- work_id: Some("w-9".to_string()),- });- assert_eq!(app.subagents.len(), before, "main adds no panel");- assert!(app.subagents.iter().all(|p| p.work_id.as_deref() != Some("w-9")));- }-fn steering_request(messages: Vec<serde_json::Value>,) -> (@@ -23394,9 +23329,6 @@ mod tests {session_id: None,sandbox: None,monitors: Some(app.monitor_set.clone()),- work_queue_enabled: false,- work_signal: std::sync::Arc::new(crate::core::agent::subagent::WorkSignal::new()),- collab_run_id: None,});app.args = Some(args.clone());diff --git a/web-app/src/containers/CoworkTasksChip.tsx b/web-app/src/containers/CoworkTasksChip.tsxindex cbc6e1bcc..dbca59ecd 100644--- a/web-app/src/containers/CoworkTasksChip.tsx+++ b/web-app/src/containers/CoworkTasksChip.tsx@@ -7,7 +7,6 @@ import {} from '@/components/ui/tooltip'import { cn } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'-import type { WorkItemView } from '@/lib/agentTools'import type { MonitorView, SubagentRun } from '@/types/coworkSession'/**@@ -23,7 +22,6 @@ import type { MonitorView, SubagentRun } from '@/types/coworkSession'export function CoworkTasksChip({subagents,monitors = [],- workqueue = [],open,onToggle,}: {@@ -31,21 +29,16 @@ export function CoworkTasksChip({/** The run's file monitors: background work like the children, so they* count here too and open the same rail. */monitors?: MonitorView[]- /** The session's shared work queue: also background work, opening the same rail. */- workqueue?: WorkItemView[]open: booleanonToggle: () => void}) {const { t } = useTranslation()- const total = subagents.length + monitors.length + workqueue.length+ const total = subagents.length + monitors.lengthif (total === 0) return nullconst activeSubagents = subagents.filter((s) => s.status !== 'done').lengthconst activeMonitors = monitors.filter((m) => m.status === 'running').length- const activeWork = workqueue.filter(- (w) => w.state !== 'done' && w.state !== 'failed'- ).length- const active = activeSubagents + activeMonitors + activeWork+ const active = activeSubagents + activeMonitorsconst onlyKind = (kept: number) => active > 0 && active === keptconst label =active === 0diff --git a/web-app/src/containers/CoworkTasksPanel.tsx b/web-app/src/containers/CoworkTasksPanel.tsxindex 696276a84..98e259b1c 100644--- a/web-app/src/containers/CoworkTasksPanel.tsx+++ b/web-app/src/containers/CoworkTasksPanel.tsx@@ -1,9 +1,15 @@/* eslint-disable @typescript-eslint/no-explicit-any */import { useEffect, useMemo, useState } from 'react'-import { ChevronLeft, ChevronDown, Eye, Loader2, Sparkles } from 'lucide-react'+import {+ ChevronLeft,+ ChevronDown,+ Clock,+ Eye,+ Loader2,+ Sparkles,+} from 'lucide-react'import { useTranslation } from '@/i18n/react-i18next-compat'import { cn, formatDuration, formatTokenCount } from '@/lib/utils'-import type { WorkItemView } from '@/lib/agentTools'import type {CoworkTurn,MonitorView,@@ -18,15 +24,17 @@ import {} from '@/components/ai-elements/conversation'import { CoworkSidePanel } from '@/containers/CoworkSidePanel'-/** One row in the running/queued/finished lists. */+/** One row in the running/queued/waiting/finished lists. */function TaskRow({ run, onSelect }: { run: SubagentRun; onSelect: () => void }) {const { t } = useTranslation()const running = run.status === 'running'- // Only rendered for finished rows below — skip the scan while running (it- // would just be recomputed and discarded on every tick/stream re-render).- const toolUses = running- ? 0- : run.turns.filter((tn) => tn.role === 'tool').length+ const waiting = run.status === 'waiting'+ // Only rendered for finished rows below — skip the scan while running/waiting+ // (it would just be recomputed and discarded on every tick/stream re-render).+ const toolUses =+ running || waiting+ ? 0+ : run.turns.filter((tn) => tn.role === 'tool').lengthreturn (<buttontype="button"@@ -36,15 +44,34 @@ function TaskRow({ run, onSelect }: { run: SubagentRun; onSelect: () => void })<div className="flex items-center gap-2">{running ? (<Loader2 size={14} className="shrink-0 animate-spin text-accent" />+ ) : waiting ? (+ <Clock size={14} className="shrink-0 text-main-view-fg/50" />) : (<Sparkles size={14} className="shrink-0 text-main-view-fg/50" />)}<span className="truncate text-sm font-medium">{run.name}</span>+ {run.phase != null && (running || waiting) && (+ <span className="ml-auto shrink-0 rounded bg-main-view-fg/5 px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-main-view-fg/50">+ {t('common:subagentPhase', { phase: run.phase })}+ </span>+ )}</div>- <span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">- {formatDuration(run.startedAt, run.endedAt)}- </span>- {!running && run.status === 'done' && (+ {waiting ? (+ <span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">+ {run.phase != null && (+ <>+ {t('common:subagentPhase', { phase: run.phase })}+ {' · '}+ </>+ )}+ {t('common:subagentWaiting')}+ </span>+ ) : (+ <span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">+ {formatDuration(run.startedAt, run.endedAt)}+ </span>+ )}+ {!running && !waiting && run.status === 'done' && (<span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">{run.usage?.total_tokens? `${formatTokenCount(run.usage.total_tokens)} · `@@ -105,46 +132,6 @@ function MonitorRow({ monitor }: { monitor: MonitorView }) {)}-/** Dot colour per work-item state, mirroring the TUI's glyph colours. */-const WORK_STATE_DOT: Record<string, string> = {- open: 'bg-accent',- claimed: 'bg-yellow-500',- done: 'bg-green-500',- failed: 'bg-destructive',- blocked: 'bg-main-view-fg/30',-}--/** One work-queue item: its state dot, id, title, and the `-> owner` flow tag- * that shows who is on it; a failed/blocked item shows its reason. */-function WorkRow({ item }: { item: WorkItemView }) {- return (- <div- data-testid="cowork-work-row"- className="flex w-full flex-col gap-1 rounded-lg border bg-main-view-fg/2 px-3 py-2.5 text-left"- >- <div className="flex items-center gap-2">- <span- className={cn(- 'size-2 shrink-0 rounded-full',- WORK_STATE_DOT[item.state] ?? 'bg-main-view-fg/30'- )}- />- <span className="truncate text-sm font-medium">{item.title}</span>- <span className="ml-auto shrink-0 font-mono text-xs text-main-view-fg/50">- {item.workId}- </span>- </div>- {(item.claimedBy || item.reason) && (- <span className="truncate pl-4 font-mono text-xs text-main-view-fg/50">- {item.claimedBy ? `-> ${item.claimedBy}` : ''}- {item.claimedBy && item.reason ? ' · ' : ''}- {item.reason ?? ''}- </span>- )}- </div>- )-}-/** The run's trace plus its final answer, unless that answer already streamed* as the last assistant turn — appending it again would show it twice. */function visibleSubagentTurns(run: SubagentRun): CoworkTurn[] {@@ -248,15 +235,12 @@ function Section({export function CoworkTasksPanel({subagents,monitors = [],- workqueue = [],onClose,}: {subagents: SubagentRun[]/** The run's file monitors. Transient: they die with the run, so unlike* finished children they never come back from the session. */monitors?: MonitorView[]- /** The session's shared work queue, from each work-tool command snapshot. */- workqueue?: WorkItemView[]onClose: () => void}) {const { t } = useTranslation()@@ -280,6 +264,7 @@ export function CoworkTasksPanel({: nullconst runningRuns = subagents.filter((s) => s.status === 'running')const queuedRuns = subagents.filter((s) => s.status === 'queued')+ const waitingRuns = subagents.filter((s) => s.status === 'waiting')const finishedRuns = subagents.filter((s) => s.status === 'done')return (@@ -303,24 +288,12 @@ export function CoworkTasksPanel({<TaskDetail run={selected} />) : (<div className="flex h-full flex-col gap-4 overflow-y-auto p-3">- {subagents.length === 0 &&- monitors.length === 0 &&- workqueue.length === 0 ? (+ {subagents.length === 0 && monitors.length === 0 ? (<p className="px-1 py-6 text-center text-sm text-main-view-fg/50">{t('common:noBackgroundTasks')}</p>) : (<>- {workqueue.length > 0 && (- <Section- label={t('common:workQueue')}- count={workqueue.filter((w) => w.state === 'open').length}- >- {workqueue.map((item) => (- <WorkRow key={item.workId} item={item} />- ))}- </Section>- )}{monitors.length > 0 && (<Section label={t('common:monitors')} count={monitors.length}>{monitors.map((monitor) => (@@ -350,6 +323,17 @@ export function CoworkTasksPanel({))}</Section>)}+ {waitingRuns.length > 0 && (+ <Section label={t('common:waiting')} count={waitingRuns.length}>+ {waitingRuns.map((run) => (+ <TaskRow+ key={run.runId}+ run={run}+ onSelect={() => setSelectedRunId(run.runId)}+ />+ ))}+ </Section>+ )}{finishedRuns.length > 0 && (<Sectionlabel={t('common:finished')}diff --git a/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx b/web-app/src/containers/__tests__/CoworkTasksChip.test.tsxindex cbb943cdd..7bc5260b1 100644--- a/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx+++ b/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx@@ -54,6 +54,22 @@ describe('CoworkTasksChip', () => {).toBeInTheDocument()})+ /// A later-phase subagent is registered up front as `waiting`; it is pending+ /// work, so it counts against the active total like a running child.+ it('counts a waiting later-phase child as active', () => {+ render(+ <CoworkTasksChip+ subagents={[run('a', 'running'), run('b', 'waiting')]}+ open={false}+ onToggle={vi.fn()}+ />+ )+ expect(screen.getByText('2/2')).toBeInTheDocument()+ expect(+ screen.getByLabelText('common:subagentsRunning 2')+ ).toBeInTheDocument()+ })+/// A watcher is background work like a child: it counts, and it is enough/// on its own to show the chip.it('counts running monitors as background work', () => {diff --git a/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx b/web-app/src/containers/message/__tests__/ToolCallCard.test.tsxindex 7369c0214..5208cd4c0 100644--- a/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx+++ b/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx@@ -83,7 +83,9 @@ describe('ToolCallCard', () => {const part = {type: 'tool-task',toolCallId: 'tc1',- input: { subagent_name: 'researcher', description: 'Research MCP' },+ input: {+ subagents: [{ name: 'researcher', task: 'Research MCP' }],+ },}const { rerender } = render(<ToolCallCarddiff --git a/web-app/src/hooks/__tests__/useCoworkRun.test.ts b/web-app/src/hooks/__tests__/useCoworkRun.test.tsindex 0aa8a3308..3da2fe524 100644--- a/web-app/src/hooks/__tests__/useCoworkRun.test.ts+++ b/web-app/src/hooks/__tests__/useCoworkRun.test.ts@@ -170,6 +170,49 @@ describe('useCoworkRun - subagent lanes', () => {})})+describe('useCoworkRun - phased subagents', () => {+ beforeEach(() => useCoworkRun.setState({ subagents: {} }))++ it('registers later-phase subagents as waiting with their phase', () => {+ useCoworkRun.getState().planSubagents('p1', [+ { runId: 'c1-collector', name: 'collector', phase: 2 },+ ])+ expect(useCoworkRun.getState().subagents.p1).toEqual([+ expect.objectContaining({+ runId: 'c1-collector',+ name: 'collector',+ status: 'waiting',+ phase: 2,+ }),+ ])+ })++ it('does not duplicate a subagent already registered', () => {+ const s = useCoworkRun.getState()+ s.planSubagents('p1', [{ runId: 'c1-a', name: 'a', phase: 2 }])+ s.planSubagents('p1', [{ runId: 'c1-a', name: 'a', phase: 2 }])+ expect(useCoworkRun.getState().subagents.p1).toHaveLength(1)+ })++ it('promotes a waiting subagent to running in place, keeping its phase', () => {+ const s = useCoworkRun.getState()+ s.planSubagents('p1', [{ runId: 'c1-a', name: 'a', phase: 2 }])+ s.startSubagent('p1', 'c1-a', 'a')+ const runs = useCoworkRun.getState().subagents.p1+ expect(runs).toHaveLength(1)+ expect(runs[0]).toMatchObject({ runId: 'c1-a', status: 'running', phase: 2 })+ })++ it('promotes a waiting subagent to queued in place, keeping its phase', () => {+ const s = useCoworkRun.getState()+ s.planSubagents('p1', [{ runId: 'c1-a', name: 'a', phase: 2 }])+ s.queueSubagent('p1', 'c1-a', 'a', 1)+ const runs = useCoworkRun.getState().subagents.p1+ expect(runs).toHaveLength(1)+ expect(runs[0]).toMatchObject({ status: 'queued', waiting: 1, phase: 2 })+ })+})+describe('useCoworkRun - monitors and parking', () => {beforeEach(() => {useCoworkRun.setState({ monitors: {}, parked: {}, runId: {}, liveTurns: {}, subagents: {} })diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.tsindex 37f7a6a70..a655d6165 100644--- a/web-app/src/hooks/useCoworkRun.ts+++ b/web-app/src/hooks/useCoworkRun.ts@@ -8,7 +8,7 @@ import type {TodoList,AskRequestPayload,} from '@/types/coworkSession'-import type { MonitorUpdate, WorkItemView } from '@/lib/agentTools'+import type { MonitorUpdate } from '@/lib/agentTools'import { userTurn } from '@/lib/coworkTurns'import type { ModelLoadProgress } from '@/hooks/useAppState'import type { RunOutcome } from '@/lib/coworkRunner'@@ -207,9 +207,6 @@ type CoworkRunState = {// run: a watcher keeps going after the model has answered, and a later// match starts a turn of its own. Dropped with the session (`clearMonitors`).monitors: Record<string, MonitorView[]>- // The session's shared work queue, replaced wholesale from each work-tool- // command's post-mutation snapshot. Display-only; the files live in scratch.- workqueue: Record<string, WorkItemView[]>// True while the run is parked on a subagent still running with the model// idle. A running monitor never parks a run.parked: Record<string, boolean>@@ -265,6 +262,14 @@ type CoworkRunState = {/** Empty a session's subagent lanes at the start of a run, so the panel shows* this run's children rather than every child the session ever had. */resetSubagents: (sid: string) => void+ /** Register later-phase subagents up front as `waiting`, so the panel shows+ * them queued behind the phase in flight. Each is promoted in place (matched+ * by runId) by its own `queueSubagent`/`startSubagent` when its phase begins.+ * Mirrors the Rust `StreamEvent::SubagentPlan`. */+ planSubagents: (+ sid: string,+ pending: { runId: string; name: string; phase: number }[]+ ) => voidstartSubagent: (sid: string, runId: string, name: string) => void// `subagent_queued`: mark a child as waiting for a concurrency slot.queueSubagent: (@@ -287,8 +292,6 @@ type CoworkRunState = {reconcileMonitors: (sid: string, activeIds: string[]) => void/** Session teardown: the watchers are stopped in Rust alongside. */clearMonitors: (sid: string) => void- /** Replace a session's work-queue snapshot from a work-tool command return. */- setWorkqueue: (sid: string, items: WorkItemView[]) => voidsetParked: (sid: string, parked: boolean) => voidsetUsage: (sid: string, usage: Usage | null) => voidrequestPreview: (sessionId: string, path: string) => void@@ -330,7 +333,6 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({set((s) => ({ liveTurns: { ...s.liveTurns, [sid]: turns } })),subagents: {},monitors: {},- workqueue: {},parked: {},runId: {},pendingAsks: {},@@ -380,14 +382,34 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({resetSubagents: (sid) =>set((s) => ({ subagents: { ...s.subagents, [sid]: [] } })),+ planSubagents: (sid, pending) =>+ set((s) => {+ const runs = s.subagents[sid] ?? []+ const known = new Set(runs.map((r) => r.runId))+ const added = pending+ .filter((p) => !known.has(p.runId))+ .map((p) => ({+ runId: p.runId,+ name: p.name,+ status: 'waiting' as const,+ phase: p.phase,+ startedAt: Date.now(),+ turns: [],+ }))+ return added.length+ ? { subagents: { ...s.subagents, [sid]: [...runs, ...added] } }+ : {}+ }),+startSubagent: (sid, runId, name) =>set((s) => {const runs = s.subagents[sid] ?? []- // Promote a queued child the moment its slot frees; otherwise create it.+ // Promote a waiting/queued child in place the moment it starts (preserving+ // its phase); otherwise create it.const idx = runs.findIndex((r) => r.runId === runId)if (idx !== -1) {const existing = runs[idx]- if (existing.status === 'queued') {+ if (existing.status === 'waiting' || existing.status === 'queued') {return {subagents: {...s.subagents,@@ -426,7 +448,30 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({queueSubagent: (sid, runId, name, waiting) =>set((s) => {const runs = s.subagents[sid] ?? []- if (runs.some((r) => r.runId === runId)) return {}+ // Promote a waiting later-phase child to queued in place (keeping its+ // phase) once its phase dispatches and it lands on the concurrency gate.+ const idx = runs.findIndex((r) => r.runId === runId)+ if (idx !== -1) {+ const existing = runs[idx]+ if (existing.status === 'waiting') {+ return {+ subagents: {+ ...s.subagents,+ [sid]: [+ ...runs.slice(0, idx),+ {+ ...existing,+ status: 'queued' as const,+ waiting,+ startedAt: Date.now(),+ },+ ...runs.slice(idx + 1),+ ],+ },+ }+ }+ return {}+ }return {subagents: {...s.subagents,@@ -547,8 +592,6 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({}),clearMonitors: (sid) => set((s) => ({ monitors: omitKey(s.monitors, sid) })),- setWorkqueue: (sid, items) =>- set((s) => ({ workqueue: { ...s.workqueue, [sid]: items } })),setParked: (sid, parked) =>set((s) => ({@@ -644,7 +687,6 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({liveTurns: omitKey(s.liveTurns, sid),outcomes: omitKey(s.outcomes, sid),subagents: omitKey(s.subagents, sid),- workqueue: omitKey(s.workqueue, sid),parked: omitKey(s.parked, sid),runId: omitKey(s.runId, sid),pendingAsks: omitKey(s.pendingAsks, sid),diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex ed2b81a71..e1c3264d7 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -9,11 +9,6 @@ const memoryCatalog = vi.fn()const memoryRead = vi.fn()const subagentResultReserve = vi.fn()const subagentResultFill = vi.fn()-const workPost = vi.fn()-const workClaim = vi.fn()-const workComplete = vi.fn()-const workList = vi.fn()-const agentRead = vi.fn()const getJanDataFolder = vi.fn()vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({@@ -26,11 +21,6 @@ vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({memoryRead: (...args: unknown[]) => memoryRead(...args),subagentResultReserve: (...args: unknown[]) => subagentResultReserve(...args),subagentResultFill: (...args: unknown[]) => subagentResultFill(...args),- workPost: (...args: unknown[]) => workPost(...args),- workClaim: (...args: unknown[]) => workClaim(...args),- workComplete: (...args: unknown[]) => workComplete(...args),- workList: (...args: unknown[]) => workList(...args),- agentRead: (...args: unknown[]) => agentRead(...args),attachmentImport: vi.fn(),}))@@ -57,51 +47,9 @@ describe('agentTools', () => {memoryRead.mockReset().mockResolvedValue('')subagentResultReserve.mockReset()subagentResultFill.mockReset()- workPost.mockReset()- workClaim.mockReset()- workComplete.mockReset()- workList.mockReset()- agentRead.mockReset()getJanDataFolder.mockReset().mockResolvedValue('/data')})- describe('work queue', () => {- it('posts work as the given agent and returns the snapshot', async () => {- const snapshot = {- message: 'Posted w-1',- items: [{ workId: 'w-1', title: 'do it', state: 'open' }],- }- workPost.mockResolvedValue(snapshot)- const { postWork } = await import('../agentTools')- const result = await postWork('sess-1', 'main', { task: 'do it' })- expect(workPost).toHaveBeenCalledWith('sess-1', 'main', { task: 'do it' })- expect(result).toEqual(snapshot)- })-- it('returns null when a work command throws so the caller can fall back', async () => {- workClaim.mockRejectedValue(new Error('boom'))- const { claimWork } = await import('../agentTools')- expect(await claimWork('sess-1', 'sub-a-1')).toBeNull()- })-- it('carries the claimed id through', async () => {- workClaim.mockResolvedValue({ message: 'ok', items: [], claimed: 'w-3' })- const { claimWork } = await import('../agentTools')- const result = await claimWork('sess-1', 'sub-a-1')- expect(result?.claimed).toBe('w-3')- })-- it('reads a peer through agent_read and surfaces errors as an ERROR string', async () => {- agentRead.mockResolvedValue('reviewer (sub-a-1) [running] step 2')- const { readAgent } = await import('../agentTools')- expect(await readAgent('sess-1', 'main', { run_id: 'sub-a-1' })).toContain('running')- // The caller's own id is forwarded so the core can refuse a self-read.- expect(agentRead).toHaveBeenCalledWith('sess-1', 'main', { run_id: 'sub-a-1' })- agentRead.mockRejectedValue(new Error('nope'))- expect(await readAgent('sess-1', 'main', {})).toBe('ERROR: nope')- })- })-// The chat surface offers the sandboxed shell alone; everything else is// Cowork's. A chat set that grew a write tool would hand the main interface// an agent toolset it no longer advertises a workspace for.diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.tsindex 1e19cb967..197b8fa7d 100644--- a/web-app/src/lib/__tests__/coworkSubagent.test.ts+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts@@ -12,18 +12,24 @@ vi.mock('ai', async (orig) => ({}))import {- dispatchedSubagentResult,+ formatDispatchedPlan,+ injectInputs,intersectAllowedTools,- parseSubagentRequest,+ parseDispatchPlan,parentToolNames,resolveSubagent,runSubagent,+ runDispatchPlan,subagentCompletionNotice,subagentTools,SubagentInbox,MAX_PARALLEL_SUBAGENTS,SUBAGENT_INLINE_MAX,+ PHASE_INPUT_MAX_BYTES,__testing,+ type DispatchPlan,+ type SubagentRequest,+ type SubagentResult,} from '../coworkSubagent'import type { StreamEvent } from '@/hooks/useCoworkRun'import { MAX_SUBAGENT_STEPS } from '../coworkBudget'@@ -41,15 +47,41 @@ const definition = (over = {}) => ({})describe('the task result and its completion ping', () => {- it('names the file the answer will land in, and does not wait', () => {- const out = dispatchedSubagentResult('researcher', 'c1', '/tmp/subagents/r.md')- expect(out).toContain('/tmp/subagents/r.md')- expect(out).toContain('Keep working')+ const single: DispatchPlan = {+ phases: [{ number: 0, subagents: [{ name: 'researcher', description: 'go' }] }],+ }+ const multi: DispatchPlan = {+ phases: [+ {+ number: 0,+ subagents: [+ { name: 'alpha', description: 'a' },+ { name: 'beta', description: 'b' },+ ],+ },+ { number: 1, subagents: [{ name: 'collector', description: 'c' }] },+ ],+ }++ it('summarizes a single-phase fan-out and names the blackboard dir', () => {+ const out = formatDispatchedPlan(single, '/tmp/blackboard')+ expect(out).toContain('running concurrently')+ expect(out).toContain('researcher')+ expect(out).toContain('/tmp/blackboard/<name>.md')+ expect(out).toContain('do not do them yourself')+ })++ it('names the phase count and phase-1 subagents for a multi-phase plan', () => {+ const out = formatDispatchedPlan(multi, '/tmp/blackboard')+ expect(out).toContain('2-phase plan of 3 subagents')+ expect(out).toContain('Phase 1 is now running: alpha, beta')+ expect(out).toContain('Later phases start automatically')})- it('promises the answer itself when there is no file to point at', () => {- const out = dispatchedSubagentResult('researcher', 'c1', null)- expect(out).toContain('You will be given its answer')+ it('falls back to inline delivery when there is no scratch', () => {+ const out = formatDispatchedPlan(single, null)+ expect(out).toContain('rides the note')+ expect(out).not.toContain('blackboard')})/// The row shows the headline and the model gets the instructions after it:@@ -146,38 +178,110 @@ describe('SubagentInbox', () => {})})-describe('parseSubagentRequest', () => {- it('requires a name and a description', () => {- expect(parseSubagentRequest({})).toContain('subagent_name')- // The child cannot see the parent's conversation, so an empty brief is a- // guaranteed-useless run rather than a recoverable one.- expect(parseSubagentRequest({ subagent_name: 'x' })).toContain(- 'description'- )- })-- it('keeps an inline prompt and allowlist', () => {- const req = parseSubagentRequest({- subagent_name: 'oneoff',- description: 'do it',- system_prompt: 'You are terse.',- allowed_tools: ['read', 42, 'grep'],+describe('parseDispatchPlan', () => {+ it('groups a flat subagents list into ordered phases by their `phase` key', () => {+ // Listed out of order and with a gap (0, 2); grouped and ordered, and the+ // phase number carried is the model's own key.+ const plan = parseDispatchPlan({+ subagents: [+ { name: 'c', task: 'do c', phase: 2, allowed_tools: ['read', 42] },+ { name: 'a', task: 'do a' },+ { name: 'b', task: 'do b', phase: 0 },+ ],})- expect(req).toEqual({- subagent_name: 'oneoff',- description: 'do it',- system_prompt: 'You are terse.',- allowed_tools: ['read', 'grep'],+ expect(plan).toEqual({+ phases: [+ {+ number: 0,+ subagents: [+ { name: 'a', description: 'do a' },+ { name: 'b', description: 'do b' },+ ],+ },+ {+ number: 2,+ subagents: [{ name: 'c', description: 'do c', allowed_tools: ['read'] }],+ },+ ],})})- it('drops a blank inline prompt rather than running an empty role', () => {- const req = parseSubagentRequest({- subagent_name: 'x',- description: 'd',- system_prompt: ' ',- })- expect(req).not.toHaveProperty('system_prompt')+ it('fans out into a single phase when no `phase` is given', () => {+ const plan = parseDispatchPlan({+ subagents: [+ { name: 'a', task: 'x' },+ { name: 'b', task: 'y' },+ ],+ }) as DispatchPlan+ expect(plan.phases).toHaveLength(1)+ expect(plan.phases[0].number).toBe(0)+ expect(plan.phases[0].subagents).toHaveLength(2)+ })++ it('requires a non-empty subagents array', () => {+ expect(parseDispatchPlan({})).toContain('subagents')+ expect(parseDispatchPlan({ subagents: [] })).toContain('at least one')+ })++ it('requires a non-empty name and task per subagent', () => {+ expect(parseDispatchPlan({ subagents: [{ task: 'x' }] })).toContain('name')+ expect(parseDispatchPlan({ subagents: [{ name: 'a' }] })).toContain('task')+ })++ it('rejects an invalid name charset and an over-long name', () => {+ expect(+ parseDispatchPlan({ subagents: [{ name: 'a b', task: 't' }] })+ ).toContain('invalid subagent name')+ expect(+ parseDispatchPlan({ subagents: [{ name: 'a'.repeat(65), task: 't' }] })+ ).toContain('too long')+ })++ it('rejects a non-negative-integer phase', () => {+ expect(+ parseDispatchPlan({ subagents: [{ name: 'a', task: 't', phase: -1 }] })+ ).toContain("invalid 'phase'")+ expect(+ parseDispatchPlan({ subagents: [{ name: 'a', task: 't', phase: 'later' }] })+ ).toContain("invalid 'phase'")+ })++ it('rejects a duplicate name across the whole plan', () => {+ expect(+ parseDispatchPlan({+ subagents: [+ { name: 'dup', task: 't1' },+ { name: 'dup', task: 't2', phase: 1 },+ ],+ })+ ).toContain('duplicate subagent name')+ })++ it('treats an empty allowlist as omitted', () => {+ const plan = parseDispatchPlan({+ subagents: [{ name: 'a', task: 't', allowed_tools: [] }],+ }) as DispatchPlan+ expect(plan.phases[0].subagents[0]).not.toHaveProperty('allowed_tools')+ })+})++describe('injectInputs', () => {+ it('returns the task unchanged when there are no inputs', () => {+ expect(injectInputs('do it', [])).toBe('do it')+ })++ it('prefixes the previous phase results and keeps the task last', () => {+ const out = injectInputs('synthesize', [{ name: 'alpha', output: 'found X' }])+ expect(out).toContain('Results from the previous phase')+ expect(out).toContain('### alpha')+ expect(out).toContain('found X')+ expect(out.trimEnd().endsWith('synthesize')).toBe(true)+ })++ it('truncates a verbose input at the byte cap with a pointer to the blackboard', () => {+ const big = 'x'.repeat(PHASE_INPUT_MAX_BYTES + 500)+ const out = injectInputs('t', [{ name: 'beta', output: big }])+ expect(out).toContain('truncated; read blackboard/beta.md')})})@@ -235,7 +339,7 @@ describe('resolveSubagent', () => {it('uses a saved definition', () => {const out = resolveSubagent(- { subagent_name: 'researcher', description: 'go' },+ { name: 'researcher', description: 'go' },[definition({ allowed_tools: ['read'], model: 'm-1' })],parent)@@ -247,43 +351,38 @@ describe('resolveSubagent', () => {})})- it('runs a one-off from an inline prompt', () => {+ it('resolves an unknown name to an ephemeral generalist (no error)', () => {const out = resolveSubagent(- {- subagent_name: 'oneoff',- description: 'go',- system_prompt: 'You are terse.',- allowed_tools: ['read'],- },+ { name: 'designer', description: 'go', allowed_tools: ['read'] },[],parent)- expect(out).toEqual({- name: 'oneoff',- systemPrompt: 'You are terse.',+ expect(out).toMatchObject({+ name: 'designer',allowedTools: ['read', 'skill_list', 'skill_read'],model: null,})+ // The ephemeral system prompt names the subagent and its hand-off role.+ expect((out as { systemPrompt: string }).systemPrompt).toBe(+ __testing.ephemeralSubagentPrompt('designer')+ )+ expect((out as { systemPrompt: string }).systemPrompt).toContain('designer')})- it('errors on an unknown name with no inline prompt', () => {+ it('surfaces a call-site tool outside the saved definition as an error', () => {const out = resolveSubagent(- { subagent_name: 'ghost', description: 'go' },- [],+ { name: 'researcher', description: 'go', allowed_tools: ['write'] },+ [definition({ allowed_tools: ['read'] })],parent)expect(out).toEqual({- error: expect.stringContaining("unknown subagent 'ghost'"),+ error: expect.stringContaining("outside the subagent definition's"),})})it('lets a call site narrow a saved definition', () => {const out = resolveSubagent(- {- subagent_name: 'researcher',- description: 'go',- allowed_tools: ['read'],- },+ { name: 'researcher', description: 'go', allowed_tools: ['read'] },[definition({ allowed_tools: ['read', 'grep'] })],parent)@@ -614,3 +713,165 @@ describe('runSubagent', () => {expect(queued[0].events.onStart).toHaveBeenCalled()})})++describe('runDispatchPlan', () => {+ const okResult = (output: string): SubagentResult => ({+ output,+ usage: null,+ sessionTokens: 0,+ })+ const req = (name: string): SubagentRequest => ({+ name,+ description: `do ${name}`,+ })+ const deferred = () => {+ let resolve!: () => void+ const promise = new Promise<void>((r) => {+ resolve = r+ })+ return { promise, resolve }+ }+ const flush = async () => {+ for (let i = 0; i < 15; i += 1) await Promise.resolve()+ }++ // Mirrors the Rust `a_later_phase_starts_after_the_earlier_one_with_its_results`.+ it('starts a later phase only after the earlier one finished, with its results injected', async () => {+ const plan: DispatchPlan = {+ phases: [+ { number: 0, subagents: [req('alpha'), req('beta')] },+ { number: 1, subagents: [req('collector')] },+ ],+ }+ const order: string[] = []+ const briefs: Record<string, string> = {}+ const gateA = deferred()+ const gateB = deferred()++ const done = runDispatchPlan(plan, 'c1', {+ runOne: async (r, description) => {+ order.push(`start:${r.name}`)+ briefs[r.name] = description+ if (r.name === 'alpha') await gateA.promise+ if (r.name === 'beta') await gateB.promise+ order.push(`end:${r.name}`)+ return okResult(`${r.name} findings`)+ },+ writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,+ onDispatch: () => {},+ onComplete: () => {},+ })++ await flush()+ // Phase 1 is dispatched; phase 2 must not have started yet.+ expect(order).toContain('start:alpha')+ expect(order).toContain('start:beta')+ expect(order).not.toContain('start:collector')++ gateA.resolve()+ gateB.resolve()+ await done++ const collector = order.indexOf('start:collector')+ expect(collector).toBeGreaterThan(-1)+ expect(order.indexOf('end:alpha')).toBeLessThan(collector)+ expect(order.indexOf('end:beta')).toBeLessThan(collector)++ // The collector's brief carries phase 1's blackboard results.+ expect(briefs.collector).toContain('Results from the previous phase')+ expect(briefs.collector).toContain('alpha findings')+ expect(briefs.collector).toContain('beta findings')+ })++ it('keys each subagent `${callId}-${name}` and writes real answers to the blackboard', async () => {+ const dispatched: string[] = []+ const writes: string[] = []+ await runDispatchPlan(+ { phases: [{ number: 0, subagents: [req('alpha')] }] },+ 'call-9',+ {+ runOne: async () => okResult('the answer'),+ writeBlackboard: async (name, content) => {+ writes.push(`${name}:${content}`)+ return `/tmp/blackboard/${name}.md`+ },+ onDispatch: (id) => dispatched.push(id),+ onComplete: () => {},+ }+ )+ expect(dispatched).toEqual(['call-9-alpha'])+ expect(writes).toEqual(['alpha:the answer'])+ })++ it('proceeds past a failed child and does not write its blackboard', async () => {+ const writes: string[] = []+ const completed: { name: string; savedPath: string | null }[] = []+ await runDispatchPlan(+ {+ phases: [+ { number: 0, subagents: [req('flaky')] },+ { number: 1, subagents: [req('next')] },+ ],+ },+ 'c1',+ {+ runOne: async (r) =>+ r.name === 'flaky'+ ? { output: 'boom', usage: null, isError: true, sessionTokens: 0 }+ : okResult('ok'),+ writeBlackboard: async (name) => {+ writes.push(name)+ return `/tmp/blackboard/${name}.md`+ },+ onDispatch: () => {},+ onComplete: (_id, name, _res, savedPath) =>+ completed.push({ name, savedPath }),+ }+ )+ expect(completed).toEqual([+ { name: 'flaky', savedPath: null },+ { name: 'next', savedPath: '/tmp/blackboard/next.md' },+ ])+ expect(writes).toEqual(['next'])+ })++ // The plan hold keeps inbox.pending() true across the phase boundary, even if+ // the run loop drains every ping the instant a child finishes.+ it('keeps the run alive across the whole plan via the plan hold', async () => {+ const inbox = new SubagentInbox()+ const plan: DispatchPlan = {+ phases: [+ { number: 0, subagents: [req('alpha'), req('beta')] },+ { number: 1, subagents: [req('collector')] },+ ],+ }+ let planDone = false+ const observations: boolean[] = []+ inbox.begin() // the plan hold, taken at dispatch++ const drainer = (async () => {+ for (;;) {+ await inbox.wait()+ inbox.take()+ observations.push(inbox.pending())+ if (planDone) break+ }+ })()++ await runDispatchPlan(plan, 'c1', {+ runOne: async (r) => okResult(`${r.name} out`),+ writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,+ onDispatch: () => inbox.begin(),+ onComplete: (_id, name) => inbox.finish({ headline: name, text: name }),+ })+ planDone = true+ inbox.abandon() // release the plan hold, as the finally in onTask does+ await drainer++ // Every drain while the plan ran saw work outstanding; only the final drain+ // (after the hold released) reads idle.+ expect(observations.length).toBeGreaterThan(0)+ expect(observations.slice(0, -1).every((p) => p === true)).toBe(true)+ expect(observations.at(-1)).toBe(false)+ })+})diff --git a/web-app/src/lib/__tests__/coworkTools.test.ts b/web-app/src/lib/__tests__/coworkTools.test.tsindex 3d4e16a0e..b22d3eb27 100644--- a/web-app/src/lib/__tests__/coworkTools.test.ts+++ b/web-app/src/lib/__tests__/coworkTools.test.ts@@ -151,11 +151,28 @@ describe('allowedToolNames', () => {expect(out).toEqual(['read'])})- /// The dispatch that fails is the first one of every fan-out: a model reaches- /// for a descriptive name long before it has saved a definition, and a schema- /// that mentions `system_prompt` only in passing gets it omitted.- describe('the task schema states the one-off rule', () => {- it('says which combination fails, on the field filled in first', async () => {+ /// The flat schema: `{ subagents: [ {name, task, phase?, allowed_tools?} ] }`,+ /// with no system_prompt and no unknown-name failure (an unknown name is an+ /// ephemeral generalist). One optional per-subagent `phase` pipelines them.+ describe('the task schema is a flat subagents array with an optional phase', () => {+ type TaskSchema = {+ description: string+ inputSchema: {+ jsonSchema: {+ required?: string[]+ properties: {+ subagents: {+ items: {+ required?: string[]+ properties: Record<string, unknown>+ }+ }+ }+ }+ }+ }++ it('requires a subagents array with name+task, an optional phase, and no system_prompt', async () => {const { buildCoworkTools } = await import('../coworkTools')const tools = await buildCoworkTools({planMode: false,@@ -163,13 +180,21 @@ describe('allowedToolNames', () => {allowSubagents: true,webSearch: false,})- const task = tools['task'] as unknown as {- description: string- inputSchema: { jsonSchema: { properties: Record<string, { description?: string }> } }- }- const props = task.inputSchema.jsonSchema.properties- expect(props.subagent_name.description).toContain('system_prompt')- expect(props.system_prompt.description).toContain('Required')+ const task = tools['task'] as unknown as TaskSchema+ const schema = task.inputSchema.jsonSchema+ expect(schema.required).toContain('subagents')+ const sub = schema.properties.subagents.items+ expect(sub.required).toEqual(['name', 'task'])+ expect(Object.keys(sub.properties)).toEqual([+ 'name',+ 'task',+ 'phase',+ 'allowed_tools',+ ])+ // The one-off vocabulary is gone entirely.+ const serialized = JSON.stringify(schema)+ expect(serialized).not.toContain('system_prompt')+ expect(serialized).not.toContain('subagent_name')expect(task.description).toContain('No saved subagents yet')})diff --git a/web-app/src/lib/__tests__/coworkWorkqueue.test.ts b/web-app/src/lib/__tests__/coworkWorkqueue.test.tsdeleted file mode 100644index 39f46fc40..000000000--- a/web-app/src/lib/__tests__/coworkWorkqueue.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'--const postWork = vi.fn()-const claimWork = vi.fn()-const completeWork = vi.fn()-const listWork = vi.fn()-const readAgent = vi.fn()--vi.mock('@/lib/agentTools', () => ({- postWork: (...args: unknown[]) => postWork(...args),- claimWork: (...args: unknown[]) => claimWork(...args),- completeWork: (...args: unknown[]) => completeWork(...args),- listWork: (...args: unknown[]) => listWork(...args),- readAgent: (...args: unknown[]) => readAgent(...args),-}))--import {- COMPLETE_WORK_TOOL,- CLAIM_WORK_TOOL,- LIST_WORK_TOOL,- POST_WORK_TOOL,- READ_AGENT_TOOL,- runWorkOp,- workqueueTools,-} from '@/lib/coworkWorkqueue'-import type { WorkItemView } from '@/lib/agentTools'--const snapshot = (items: WorkItemView[]) => ({ message: 'ok', items })--describe('coworkWorkqueue', () => {- beforeEach(() => {- postWork.mockReset()- claimWork.mockReset()- completeWork.mockReset()- listWork.mockReset()- readAgent.mockReset()- })-- it('advertises only the queue mutators, and none in plan mode', () => {- const normal = workqueueTools(false)- expect(Object.keys(normal).sort()).toEqual(- [POST_WORK_TOOL, CLAIM_WORK_TOOL, COMPLETE_WORK_TOOL].sort()- )- // list_work and read_agent are not advertised as tools in either mode; their- // runWorkOp arms stay so a named call is still handled.- expect(normal[LIST_WORK_TOOL]).toBeUndefined()- expect(normal[READ_AGENT_TOOL]).toBeUndefined()- // Plan mode withholds even the mutators.- expect(Object.keys(workqueueTools(true))).toEqual([])- })-- it('posts as the given agent and applies the returned snapshot', async () => {- const items: WorkItemView[] = [- { workId: 'w-1', title: 'do it', state: 'open' },- ]- postWork.mockResolvedValue(snapshot(items))- const applied: WorkItemView[][] = []- const out = await runWorkOp(- POST_WORK_TOOL,- { task: 'do it' },- { sessionId: 's', agentId: 'main', onWorkQueue: (i) => applied.push(i) }- )- expect(postWork).toHaveBeenCalledWith('s', 'main', { task: 'do it' })- expect(out.output).toBe('ok')- expect(out.isError).toBe(false)- expect(applied).toEqual([items])- })-- it('claims and completes under the caller agent id', async () => {- claimWork.mockResolvedValue(snapshot([]))- await runWorkOp(CLAIM_WORK_TOOL, {}, { sessionId: 's', agentId: 'sub-a-1' })- expect(claimWork).toHaveBeenCalledWith('s', 'sub-a-1')- completeWork.mockResolvedValue(snapshot([]))- await runWorkOp(- COMPLETE_WORK_TOOL,- { work_id: 'w-1', result: 'done' },- { sessionId: 's', agentId: 'sub-a-1' }- )- expect(completeWork).toHaveBeenCalledWith('s', 'sub-a-1', {- work_id: 'w-1',- result: 'done',- })- })-- it('routes read_agent to the roster/status read', async () => {- readAgent.mockResolvedValue('reviewer (sub-a-1) [running]')- const out = await runWorkOp(- READ_AGENT_TOOL,- { run_id: 'sub-a-1' },- { sessionId: 's', agentId: 'main' }- )- expect(readAgent).toHaveBeenCalledWith('s', 'main', { run_id: 'sub-a-1' })- expect(out.output).toContain('running')- })-- it('reports a failed command as an error result without a snapshot update', async () => {- listWork.mockResolvedValue(null)- const applied: WorkItemView[][] = []- const out = await runWorkOp(LIST_WORK_TOOL, {}, {- sessionId: 's',- agentId: 'main',- onWorkQueue: (i) => applied.push(i),- })- expect(out.isError).toBe(true)- expect(applied).toEqual([])- })-})diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 0a9c38a71..e8e3e2612 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -8,11 +8,7 @@ import {memoryRead,subagentResultReserve,subagentResultFill,- workPost,- workClaim,- workComplete,- workList,- agentRead,+ blackboardWrite,attachmentImport,startMonitor,stopMonitor,@@ -25,8 +21,6 @@ import {type SandboxStatus,type ToolImage,type ToolSchema,- type WorkCommandResult,- type WorkItemView,type WorkspaceScope,} from '@janhq/tauri-plugin-agent-tools-api'import { getServiceHub } from '@/hooks/useServiceHub'@@ -446,77 +440,34 @@ export async function fillSubagentResult(}}-export type { WorkCommandResult, WorkItemView }--/** A work-tool result plus the fresh queue snapshot. `null` when the command- * failed, so the caller can fall back to an error message inline. */-type WorkResult = WorkCommandResult | null--/** Post a task to the session's shared work queue. */-export async function postWork(- sessionId: string,- agentId: string,- args: Record<string, unknown>-): Promise<WorkResult> {- try {- return await workPost(sessionId, agentId, args)- } catch (e) {- console.warn('[agentTools] Failed to post work:', messageOf(e))- return null- }-}--/** Claim the next ready item for `agentId`. */-export async function claimWork(- sessionId: string,- agentId: string-): Promise<WorkResult> {- try {- return await workClaim(sessionId, agentId)- } catch (e) {- console.warn('[agentTools] Failed to claim work:', messageOf(e))- return null- }-}+/**+ * The model-visible blackboard directory. The session scratch is mounted over+ * `/tmp` (see `scratch_display_path`), and the blackboard is its `blackboard`+ * subdir (`spill::BLACKBOARD_DIR`), so a finished child's answer is read from+ * `/tmp/blackboard/<name>.md`. Reported up front by the plan summary; each+ * child's completion notice carries the exact path `writeBlackboard` returns.+ */+export const BLACKBOARD_DIR_DISPLAY = '/tmp/blackboard'-/** Complete an item `agentId` claimed. */-export async function completeWork(+/**+ * Write a finished subagent's answer to `blackboard/<name>.md` in the session+ * scratch -- the name-keyed coordination file a phased dispatch's next phase+ * reads. Returns the model-visible path, or `null` when no scratch is reachable+ * (the web build), so the caller can fall back to delivering the answer inline.+ */+export async function writeBlackboard(sessionId: string,- agentId: string,- args: Record<string, unknown>-): Promise<WorkResult> {- try {- return await workComplete(sessionId, agentId, args)- } catch (e) {- console.warn('[agentTools] Failed to complete work:', messageOf(e))- return null- }-}--/** The whole work queue as a snapshot. */-export async function listWork(sessionId: string): Promise<WorkResult> {+ name: string,+ content: string+): Promise<string | null> {try {- return await workList(sessionId)+ return await blackboardWrite(sessionId, name, content)} catch (e) {- console.warn('[agentTools] Failed to list work:', messageOf(e))+ console.warn('[agentTools] Failed to write the blackboard:', messageOf(e))return null}}-/** Read a peer's status + transcript, or the roster (no `run_id`). `agentId` is- * the caller's own id, passed so the core can refuse a self-read. */-export async function readAgent(- sessionId: string,- agentId: string,- args: Record<string, unknown>-): Promise<string> {- try {- return await agentRead(sessionId, agentId, args)- } catch (e) {- return `ERROR: ${messageOf(e)}`- }-}-/*** Copy a user attachment into the session workspace, with its extracted text* beside it. `null` when it could not be copied, so the caller can tell thediff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex 29c9efa5c..15ea9e1c5 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -16,8 +16,6 @@ import {monitorSpecFromArgs,type MonitorLane,} from '@/lib/coworkMonitor'-import { WORK_TOOL_NAMES, runWorkOp } from '@/lib/coworkWorkqueue'-import type { WorkItemView } from '@/lib/agentTools'import type { PendingToolCall, ToolOutcome } from '@/lib/coworkRunner'import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'import {@@ -45,12 +43,6 @@ export type DispatchContext = {/** The session's monitor lane; `null` for a subagent's dispatch, which* refuses the tool (a child has no turn of its own for a match to start). */monitors: MonitorLane | null- /** This agent's collaboration id (`"main"` or a `sub-...` worker id): the- * poster/claimer/completer of record for the shared work queue. */- workAgentId: string- /** Applies the post-mutation work-queue snapshot to the session store, so the- * rail stays live. Omitted where there is no display to feed. */- onWorkQueue?: (items: WorkItemView[]) => void}/**@@ -194,13 +186,6 @@ export async function dispatchCoworkTool(if (toolName === MONITOR_TOOL_NAME) {return await runMonitorOp(call.input, ctx)}- if (WORK_TOOL_NAMES.has(toolName)) {- return await runWorkOp(toolName, call.input, {- sessionId: ctx.sessionId,- agentId: ctx.workAgentId,- onWorkQueue: ctx.onWorkQueue,- })- }if (WEB_TOOL_NAMES.has(toolName)) {if (!ctx.webSearch) {diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsindex b079d75d0..8b65fc54a 100644--- a/web-app/src/lib/coworkSubagent.ts+++ b/web-app/src/lib/coworkSubagent.ts@@ -63,18 +63,33 @@ export const MAX_PARALLEL_SUBAGENTS = 3*/export const SUBAGENT_INLINE_MAX = 8 * 1024-/** The `task` result for a child that has just been started. */-export function dispatchedSubagentResult(- name: string,- callId: string,- savedPath: string | null+/**+ * The `task` result for a phased dispatch, reported the moment phase 1 is+ * launched. Port of the Rust `format_dispatched_plan`: single-phase vs+ * multi-phase wording, the blackboard note (or the inline-note fallback when+ * there is no scratch), and the "these are the subagents' now" hand-off.+ */+export function formatDispatchedPlan(+ plan: DispatchPlan,+ blackboardDir: string | null): string {- const where = savedPath- ? `Its answer will be written to ${savedPath}; read that file once you are told it has landed.`- : 'You will be given its answer as soon as it finishes.'+ const firstPhaseNames = plan.phases[0].subagents.map((s) => s.name)+ const names = firstPhaseNames.join(', ')+ const phaseCount = plan.phases.length+ const totalSubagents = plan.phases.reduce(+ (n, p) => n + p.subagents.length,+ 0+ )+ const whereAnswers = blackboardDir+ ? ` Each answer is written to ${blackboardDir}/<name>.md; read those files when you need them.`+ : ' Each answer rides the note that tells you it finished.'+ const head =+ phaseCount > 1+ ? `Dispatched a ${phaseCount}-phase plan of ${totalSubagents} subagents. Phase 1 is now running: ${names}. Later phases start automatically as each phase finishes, each receiving the previous phase's results.`+ : `Dispatched ${totalSubagents} subagent(s) running concurrently in the background: ${names}.`return (- `Subagent '${name}' started in the background (${callId}). ${where} ` +- 'Keep working rather than waiting for it.'+ `${head}${whereAnswers} These tasks are the subagents' now -- do not do them yourself; ` ++ "you'll be pinged as each finishes.")}@@ -213,13 +228,28 @@ const WITHHELD_FROM_SUBAGENTS = new Set([MONITOR_TOOL_NAME,])+/**+ * One subagent within a phased dispatch. `name` is a saved definition's name or,+ * when nothing matches, the identity of an ephemeral generalist; it is also the+ * blackboard file the answer is written to (`blackboard/<name>.md`).+ * `description` is the subagent's sole task (the schema calls it `task`). Ported+ * from `subagent.rs::SubagentRequest`.+ */export type SubagentRequest = {- subagent_name: string+ name: stringdescription: string- system_prompt?: stringallowed_tools?: string[]}+/** A group of subagents that run concurrently; the next phase starts only once+ * every one here has finished. `number` is the model's own `phase` key for the+ * group (what the "phase N" badge shows). Ported from `subagent.rs::Phase`. */+export type Phase = { number: number; subagents: SubagentRequest[] }++/** A parsed `task` call: one or more ordered phases. Ported from+ * `subagent.rs::DispatchPlan`. */+export type DispatchPlan = { phases: Phase[] }+export type ResolvedSubagent = {name: stringsystemPrompt: string@@ -228,28 +258,164 @@ export type ResolvedSubagent = {model: string | null}-/** Reject a malformed `task` call rather than running an errand with no brief. */-export function parseSubagentRequest(input: unknown): SubagentRequest | string {- const raw = (input ?? {}) as Partial<SubagentRequest>- if (typeof raw.subagent_name !== 'string' || !raw.subagent_name.trim()) {- return '`task` requires a non-empty `subagent_name`'+/** Longest subagent name accepted. Mirrors `subagent.rs::MAX_SUBAGENT_NAME_LEN`;+ * kept short so the validated name maps to `blackboard/<name>.md` verbatim. */+const MAX_SUBAGENT_NAME_LEN = 64+/** `[A-Za-z0-9_-]`: a name is a single path component, mirroring+ * `subagent.rs::validate_name`. */+const SUBAGENT_NAME_RE = /^[A-Za-z0-9_-]+$/++/**+ * Parse a `dispatch_subagent` tool-call argument object into an ordered plan, or+ * a helpful error string.+ *+ * The wire shape is a flat `subagents` array; each subagent's optional `phase`+ * (a non-negative integer, default 0) groups it into a stage. Subagents sharing+ * a `phase` run together; lower phases run first. One shape covers both a plain+ * fan-out (omit `phase`) and a pipeline (raise `phase`). Names are validated+ * (charset + length) and required unique across the whole plan, since each is a+ * blackboard filename and a panel identity. Ported from+ * `subagent.rs::parse_dispatch_plan`.+ */+export function parseDispatchPlan(input: unknown): DispatchPlan | string {+ const raw = (input ?? {}) as { subagents?: unknown }+ if (!Array.isArray(raw.subagents)) {+ return '`dispatch_subagent` requires a `subagents` array (each with a name and task, plus an optional integer `phase`)'}- if (typeof raw.description !== 'string' || !raw.description.trim()) {- return '`task` requires a `description`: the subagent cannot see this conversation, so state everything it needs'+ if (raw.subagents.length === 0) {+ return '`subagents` must contain at least one subagent'}- const req: SubagentRequest = {- subagent_name: raw.subagent_name,- description: raw.description,+ const seen = new Set<string>()+ const byPhase = new Map<number, SubagentRequest[]>()+ for (const subVal of raw.subagents) {+ const sub = (subVal ?? {}) as {+ name?: unknown+ task?: unknown+ phase?: unknown+ allowed_tools?: unknown+ }+ if (typeof sub.name !== 'string' || !sub.name.trim()) {+ return 'each subagent requires a non-empty `name`'+ }+ const name = sub.name+ if (!SUBAGENT_NAME_RE.test(name)) {+ return `invalid subagent name '${name}': use only letters, digits, '-' and '_'`+ }+ if (name.length > MAX_SUBAGENT_NAME_LEN) {+ return `subagent name '${name}' is too long (max ${MAX_SUBAGENT_NAME_LEN} characters)`+ }+ if (seen.has(name)) {+ return `duplicate subagent name '${name}': names must be unique across the whole plan (each is a blackboard filename)`+ }+ seen.add(name)+ if (typeof sub.task !== 'string' || !sub.task.trim()) {+ return `subagent '${name}' requires a \`task\`: it cannot see this conversation, so state everything it needs`+ }+ let phase = 0+ if (sub.phase !== undefined && sub.phase !== null) {+ if (+ typeof sub.phase !== 'number' ||+ !Number.isInteger(sub.phase) ||+ sub.phase < 0+ ) {+ return `subagent '${name}' has an invalid 'phase': use a non-negative integer (0 = the first stage)`+ }+ phase = sub.phase+ }+ const req: SubagentRequest = { name, description: sub.task }+ if (Array.isArray(sub.allowed_tools)) {+ const list = sub.allowed_tools.filter(+ (t): t is string => typeof t === 'string'+ )+ // `[]` means "inherit", not "no tools" (see intersectAllowedTools), so a+ // blank list is dropped rather than handed on as a restriction.+ if (list.length > 0) req.allowed_tools = list+ }+ const group = byPhase.get(phase)+ if (group) group.push(req)+ else byPhase.set(phase, [req])}- if (typeof raw.system_prompt === 'string' && raw.system_prompt.trim()) {- req.system_prompt = raw.system_prompt+ // Ascending phase order, so sparse numbers (0, 5) collapse to adjacent stages.+ const phases: Phase[] = [...byPhase.keys()]+ .sort((a, b) => a - b)+ .map((number) => ({ number, subagents: byPhase.get(number)! }))+ return { phases }+}++/**+ * System prompt for a subagent dispatched without a saved definition: a focused+ * generalist whose closing report becomes the next phase's input. Ported+ * verbatim from `subagent.rs::ephemeral_subagent_prompt`.+ */+function ephemeralSubagentPrompt(name: string): string {+ return (+ `You are "${name}", a focused subagent handling one task as part of a larger plan. ` ++ 'Do exactly the task you are given, using your tools as needed, and do not wait for ' ++ 'clarification -- you cannot receive any. When you finish, end with a concise, ' ++ 'self-contained report of what you found or did: it is handed verbatim to the agents in ' ++ 'the next phase, so include the facts, paths, and decisions they will need.'+ )+}++/** Max bytes of each previous-phase answer folded into a next-phase brief, so a+ * verbose predecessor cannot blow the successor's context. The full answer is+ * always on the blackboard. Mirrors `subagent.rs::PHASE_INPUT_MAX_BYTES`. */+export const PHASE_INPUT_MAX_BYTES = 12 * 1024++/** UTF-8 byte length of a single code point, without allocating. */+function utf8Len(codePoint: number): number {+ if (codePoint <= 0x7f) return 1+ if (codePoint <= 0x7ff) return 2+ if (codePoint <= 0xffff) return 3+ return 4+}++/** Truncate to at most `maxBytes` UTF-8 bytes at a code-point boundary, so a+ * byte cut never splits a character. Mirrors `subagent.rs::char_boundary`. */+function truncateToBytes(+ s: string,+ maxBytes: number+): { text: string; truncated: boolean } {+ let bytes = 0+ let cut = 0+ for (const ch of s) {+ const n = utf8Len(ch.codePointAt(0) ?? 0)+ if (bytes + n > maxBytes) return { text: s.slice(0, cut), truncated: true }+ bytes += n+ cut += ch.length}- if (Array.isArray(raw.allowed_tools)) {- req.allowed_tools = raw.allowed_tools.filter(- (t): t is string => typeof t === 'string'+ return { text: s, truncated: false }+}++/**+ * Prefix a next-phase brief with the previous phase's results. Ported verbatim+ * (header wording + byte cap + truncation note) from+ * `subagent.rs::inject_inputs`. Empty inputs leave the task unchanged.+ */+export function injectInputs(+ task: string,+ inputs: { name: string; output: string }[]+): string {+ if (inputs.length === 0) return task+ let s =+ '## Results from the previous phase\n\n' ++ 'The agents before you produced the following; their full outputs are also on ' ++ 'the blackboard at blackboard/<name>.md.\n\n'+ for (const { name, output } of inputs) {+ s += `### ${name}\n`+ const { text, truncated } = truncateToBytes(+ output.trim(),+ PHASE_INPUT_MAX_BYTES)+ s += text+ if (truncated) {+ s += `\n\n[...truncated; read blackboard/${name}.md for the full output]`+ }+ s += '\n\n'}- return req+ s += '---\n\n'+ s += task+ return s}/**@@ -300,20 +466,21 @@ export function intersectAllowedTools(/*** Resolve a request against the saved definitions.*- * An unknown name is only an error when no inline `system_prompt` was supplied:- * a one-off subagent is first-class, which is what keeps `task` useful before- * anything is saved. Ported from `subagent.rs::resolve_dispatch`.+ * A name matching a saved definition uses that role and tools; any other name+ * runs as a focused general-purpose agent whose system prompt is the ephemeral+ * generalist text (no error for an unknown name). Only a tool-allowlist conflict+ * errors. Ported from `subagent.rs::resolve_dispatch`.*/export function resolveSubagent(req: SubagentRequest,definitions: SubagentDefinition[],parentTools: string[]): ResolvedSubagent | { error: string } {- const saved = definitions.find((d) => d.name === req.subagent_name)+ const saved = definitions.find((d) => d.name === req.name)const narrowed = intersectAllowedTools(saved ? saved.allowed_tools : (req.allowed_tools ?? null),- // An inline allowlist *is* the one-off's definition, so it is not also- // applied as a call-site narrowing (that would compare it to itself).+ // An inline allowlist *is* the ephemeral agent's definition, so it is not+ // also applied as a call-site narrowing (that would compare it to itself).saved ? (req.allowed_tools ?? null) : null,parentTools)@@ -326,16 +493,9 @@ export function resolveSubagent(model: saved.model,}}- if (!req.system_prompt) {- return {- error:- `unknown subagent '${req.subagent_name}': no saved definition. For a ` +- 'one-off, retry with a `system_prompt` describing its role.',- }- }return {- name: req.subagent_name,- systemPrompt: req.system_prompt,+ name: req.name,+ systemPrompt: ephemeralSubagentPrompt(req.name),allowedTools: narrowed.tools,model: null,}@@ -626,4 +786,86 @@ export async function runSubagent(}}-export const __testing = { Semaphore, SUBAGENT_SKILL_TOOLS }+/** The lifecycle hooks the phase scheduler drives, so `runDispatchPlan` stays+ * store- and inbox-free (and unit-testable with fakes). */+export type DispatchPlanCallbacks = {+ /** Run one subagent to completion. The caller wires store events + the gate+ * (via `runSubagent`). Its resolved definition is looked up by the caller. */+ runOne: (+ req: SubagentRequest,+ description: string,+ id: string+ ) => Promise<SubagentResult>+ /** Persist a finished child's answer to `blackboard/<name>.md`; returns the+ * model-visible path, or `null` when no scratch is reachable. */+ writeBlackboard: (name: string, content: string) => Promise<string | null>+ /** A child is being dispatched now (for the inbox begin + waiting-promotion). */+ onDispatch: (id: string, name: string) => void+ /** A child finished: its result and the blackboard path (null on failure or+ * when nothing was saved). */+ onComplete: (+ id: string,+ name: string,+ result: SubagentResult,+ savedPath: string | null+ ) => void+}++/**+ * The phase scheduler: run each phase's subagents concurrently, wait for the+ * whole phase, write every real answer to the blackboard AND keep it in memory,+ * then hand the next phase those results (via `injectInputs`). Port of the Rust+ * `spawn_dispatch_plan`/`run_phase_plan` driver.+ *+ * Resilient by construction: a failed child yields an error output and the plan+ * proceeds; this never throws (so the caller can release its plan-hold in a+ * `finally`). Each subagent is keyed `${callId}-${name}` for the store.+ */+export async function runDispatchPlan(+ plan: DispatchPlan,+ callId: string,+ cb: DispatchPlanCallbacks+): Promise<void> {+ let inputs: { name: string; output: string }[] = []+ for (const phase of plan.phases) {+ const results = await Promise.all(+ phase.subagents.map(async (req) => {+ const id = `${callId}-${req.name}`+ const description = injectInputs(req.description, inputs)+ cb.onDispatch(id, req.name)+ let result: SubagentResult+ try {+ result = await cb.runOne(req, description, id)+ } catch (e) {+ // `runSubagent` does not throw, so this is the driver itself failing;+ // the plan must still proceed rather than losing the later phases.+ result = {+ output: e instanceof Error ? e.message : String(e),+ usage: null,+ isError: true,+ sessionTokens: 0,+ }+ }+ // Only a real answer is written to the blackboard and fed forward: an+ // error message in the file the next phase reads would be+ // indistinguishable from an answer. (Rust writes the error there too;+ // Cowork keeps the coordination file answer-only.)+ const realAnswer = !result.isError && result.output.trim().length > 0+ const savedPath = realAnswer+ ? await cb.writeBlackboard(req.name, result.output)+ : null+ cb.onComplete(id, req.name, result, savedPath)+ return realAnswer ? { name: req.name, output: result.output } : null+ })+ )+ inputs = results.filter(+ (r): r is { name: string; output: string } => r !== null+ )+ }+}++export const __testing = {+ Semaphore,+ SUBAGENT_SKILL_TOOLS,+ ephemeralSubagentPrompt,+}diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex 43e47cfb0..fdad20a7f 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -9,11 +9,6 @@import { jsonSchema, type Tool } from 'ai'import { getAgentToolSchemas } from '@/lib/agentTools'import { MONITOR_TOOL_NAME, monitorTool } from '@/lib/coworkMonitor'-import {- WORK_MUTATION_NAMES,- WORK_TOOL_NAMES,- workqueueTools,-} from '@/lib/coworkWorkqueue'import {WEB_FETCH_DESCRIPTION,WEB_FETCH_INPUT_SCHEMA,@@ -31,10 +26,6 @@ export const PLAN_DENIED_TOOLS = new Set(['task',// Starting one schedules shell scripts, which is exec-class work.MONITOR_TOOL_NAME,- // The queue-mutating work tools (post/claim/complete). list_work and- // read_agent are no longer advertised on either surface, so there is nothing- // to gate for them here.- ...WORK_MUTATION_NAMES,])/** Named `todo` to match the Rust tool: the plan-mode addendum instructs the@@ -49,7 +40,6 @@ export const CLIENT_TOOL_NAMES = new Set([ASK_TOOL_NAME,TASK_TOOL_NAME,MONITOR_TOOL_NAME,- ...WORK_TOOL_NAMES,])const todoTool: Tool = {@@ -129,50 +119,65 @@ const askTool: Tool = {} as Tool/**- * Wording ported from `subagent_tool_schemas` in Rust, and it has to stay that- * literal about the one-off rule.- *- * A name with no saved definition and no `system_prompt` is rejected, and- * models reach for a descriptive name (`researcher`, `designer`) long before- * they have saved one -- so a schema that mentions `system_prompt` only as- * something for "a one-off subagent" reads as optional, gets omitted, and the- * first dispatch of every fan-out fails. Saying which combination fails, on the- * field the model fills in first, is what stops that.+ * The dispatch schema, ported from `subagent_tool_schemas` in Rust: a flat+ * `{ subagents: [ {name, task, phase?, allowed_tools?} ] }`. An optional per-+ * subagent `phase` groups them into ordered stages (omit it for a plain fan-+ * out). A name matching a saved subagent uses that role and tools; any other+ * name runs as a focused general-purpose agent, so there is no `system_prompt`+ * and no unknown-name failure. Wording tracks the Rust description.*/function taskTool(subagentNames: string[]): Tool {+ const phasesDesc =+ ' List all the subagents in one call. To PIPELINE them, give a subagent a `phase`: subagents sharing a phase run together, lower phases run first, and each later phase is handed the previous phase\'s results automatically. Omit `phase` for a plain fan-out (one stage, everyone at once); use it to stage work (e.g. phase 0 researches in parallel, phase 1 synthesizes).'+ const bg =+ " Subagents run in the BACKGROUND, concurrently (more than the running cap are queued). You keep working and get a note the moment each finishes. Each subagent's final answer is written to blackboard/<name>.md in a shared scratch directory the whole plan can read from and write to."const saved = subagentNames.length- ? ` Saved subagents: ${subagentNames.join(', ')}.`- : ' No saved subagents yet, so every call needs a `system_prompt`.'+ ? ` A subagent whose name matches a saved one uses that role and tools; otherwise it runs as a focused general-purpose agent. Saved subagents: ${subagentNames.join(', ')}.`+ : ' No saved subagents yet; each runs as a focused general-purpose agent defined by its task.'return {description:- 'Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools. It does not see this conversation, so state everything it needs in `description`. Runs in the BACKGROUND and returns immediately with the file its answer will be written to; call it several times in one step to fan work out, keep working, and a note tells you the moment each one finishes. For a one-off subagent, pass `system_prompt` inline with a descriptive `subagent_name`.' ++ 'Dispatch one or more subagents -- nested, isolated agents -- to do work for you.' ++ phasesDesc ++ bg +saved,inputSchema: jsonSchema({type: 'object',properties: {- subagent_name: {- type: 'string',- description:- 'Name of a saved subagent to run. For a one-off (no saved definition), pick a short descriptive name here AND pass system_prompt in the same call -- an unrecognized name with no system_prompt fails.',- },- description: {- type: 'string',- description:- 'The task for the subagent, as its sole user message. Include everything it needs; it does not see this conversation.',- },- system_prompt: {- type: 'string',- description:- "Required alongside subagent_name whenever that name isn't already saved -- defines the one-off subagent's role. Omit only when subagent_name matches a saved subagent.",- },- allowed_tools: {+ subagents: {type: 'array',- items: { type: 'string' },description:- "Tool allowlist. For a saved subagent this further narrows its own allowed_tools (never widens); for a one-off it is the subagent's toolset.",+ 'The subagents to run. With no phases they all run concurrently; otherwise they run grouped and ordered by their `phase`.',+ items: {+ type: 'object',+ properties: {+ name: {+ type: 'string',+ description:+ "Short identity for this subagent, unique across the whole call: letters, digits, '-' and '_' only. It is also the blackboard file its answer is written to (blackboard/<name>.md). If it matches a saved subagent, that role and tools are used; otherwise it runs as a focused general-purpose agent.",+ },+ task: {+ type: 'string',+ description:+ "The subagent's sole instruction. Include everything it needs; it does not see this conversation. A subagent in a later phase also receives the previous phase's results automatically, so tell it what to DO with them.",+ },+ phase: {+ type: 'integer',+ minimum: 0,+ description:+ 'Optional stage (default 0). Subagents with the same phase run concurrently; a phase starts only after every lower phase has finished. Omit it entirely for a plain fan-out.',+ },+ allowed_tools: {+ type: 'array',+ items: { type: 'string' },+ description:+ "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs bash, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted.",+ },+ },+ required: ['name', 'task'],+ },},},- required: ['subagent_name', 'description'],+ required: ['subagents'],additionalProperties: false,}),} as Tool@@ -259,8 +264,5 @@ export async function buildCoworkTools(if (!opts.planMode) {tools[MONITOR_TOOL_NAME] = monitorTool()}- // The shared work queue + observability. Available to main and to workers- // (unlike `task`, which caps recursion); mutations are dropped in plan mode.- Object.assign(tools, workqueueTools(opts.planMode))return tools}diff --git a/web-app/src/lib/coworkWorkqueue.ts b/web-app/src/lib/coworkWorkqueue.tsdeleted file mode 100644index 71eed2284..000000000--- a/web-app/src/lib/coworkWorkqueue.ts+++ /dev/null@@ -1,153 +0,0 @@-/**- * The shared work queue + observability tools on the Cowork surface.- *- * The queue and per-agent status live in Rust (`tools/workqueue.rs`,- * `tools/observ.rs`), reached through the plugin's guest-js commands. What lives- * here is the client half: the transcribed schemas (like `task`/`monitor`, so- * both surfaces advertise the same contract), and a dispatcher that routes a- * call to the matching command and applies the post-mutation snapshot to the- * session store so the rail stays live.- */-import { jsonSchema, type Tool } from 'ai'-import {- claimWork,- completeWork,- listWork,- postWork,- readAgent,- type WorkCommandResult,- type WorkItemView,-} from '@/lib/agentTools'-import type { ToolOutcome } from '@/lib/coworkRunner'--export const POST_WORK_TOOL = 'post_work'-export const CLAIM_WORK_TOOL = 'claim_work'-export const COMPLETE_WORK_TOOL = 'complete_work'-export const LIST_WORK_TOOL = 'list_work'-export const READ_AGENT_TOOL = 'read_agent'--/** Every work-queue / observability tool Cowork dispatches itself. */-export const WORK_TOOL_NAMES = new Set([- POST_WORK_TOOL,- CLAIM_WORK_TOOL,- COMPLETE_WORK_TOOL,- LIST_WORK_TOOL,- READ_AGENT_TOOL,-])--/** The queue-mutating tools, withheld in plan mode. (list_work and read_agent- * are no longer advertised at all -- see `workqueueTools`.) */-export const WORK_MUTATION_NAMES = new Set([- POST_WORK_TOOL,- CLAIM_WORK_TOOL,- COMPLETE_WORK_TOOL,-])--/** Wording ported from `work_tool_schemas` in Rust; the two surfaces advertise- * the same contract. Only the three queue mutators are offered -- list_work and- * read_agent are un-advertised, matching the Rust loop -- and plan mode drops- * even those, so it returns an empty set there. */-export function workqueueTools(planMode: boolean): Record<string, Tool> {- const tools: Record<string, Tool> = {}- if (!planMode) {- tools[POST_WORK_TOOL] = {- description:- 'Post a task to the shared work queue for a worker to pick up. Fan out independent work by posting several, then dispatching generic workers that each claim and complete one. deps names work ids whose results this task needs (each must already be posted); the task is claimable only once they finish, and their results are handed to whoever claims it. Returns the new work id.',- inputSchema: jsonSchema({- type: 'object',- properties: {- task: {- type: 'string',- description: 'What the worker should do, self-contained.',- },- deps: {- type: 'array',- items: { type: 'string' },- description:- 'Work ids (e.g. ["w-1"]) this task depends on; each must already be posted. Optional.',- },- title: {- type: 'string',- description:- 'Optional short label shown on the queue (defaults to the task).',- },- },- required: ['task'],- }),- } as Tool- tools[CLAIM_WORK_TOOL] = {- description:- 'Claim the next ready task from the shared work queue and receive its instructions and any dependency results. Call this as a worker: claim, do the work, then complete_work. If it reports nothing is ready, stop -- you will be pinged when new work appears; do not loop on it.',- inputSchema: jsonSchema({ type: 'object', properties: {} }),- } as Tool- tools[COMPLETE_WORK_TOOL] = {- description:- 'Report the result of a work item you claimed. Its result is saved and delivered to anything that depends on it. You must have claimed the item first.',- inputSchema: jsonSchema({- type: 'object',- properties: {- work_id: {- type: 'string',- description: 'The id you claimed (from claim_work).',- },- result: {- type: 'string',- description: 'The finished result for this item.',- },- },- required: ['work_id', 'result'],- }),- } as Tool- }- // list_work and read_agent are not advertised (matching the Rust loop): the- // queue and each peer's status are visible to the user via the rail and the- // background-tasks view, and a worker's claim->do->complete loop does not need- // to poll them. Their constants and `runWorkOp` arms stay, so a named call is- // still handled and the change is reversible.- return tools-}--/** What `runWorkOp` needs: the session, the caller's collaboration id (the- * poster/claimer/completer of record), and a sink for the fresh snapshot. */-export type WorkDispatch = {- sessionId: string- agentId: string- onWorkQueue?: (items: WorkItemView[]) => void-}--/** Route one work-queue / observability tool call to its guest-js command and- * apply the post-mutation snapshot. Always resolves to a model-facing result. */-export async function runWorkOp(- toolName: string,- input: unknown,- ctx: WorkDispatch-): Promise<ToolOutcome> {- const args =- input && typeof input === 'object' ? (input as Record<string, unknown>) : {}- if (toolName === READ_AGENT_TOOL) {- const output = await readAgent(ctx.sessionId, ctx.agentId, args)- return { output, isError: output.startsWith('ERROR') }- }- let res: WorkCommandResult | null- switch (toolName) {- case POST_WORK_TOOL:- res = await postWork(ctx.sessionId, ctx.agentId, args)- break- case CLAIM_WORK_TOOL:- res = await claimWork(ctx.sessionId, ctx.agentId)- break- case COMPLETE_WORK_TOOL:- res = await completeWork(ctx.sessionId, ctx.agentId, args)- break- case LIST_WORK_TOOL:- res = await listWork(ctx.sessionId)- break- default:- return { output: `ERROR: unknown work tool '${toolName}'`, isError: true }- }- if (!res) {- return { output: 'ERROR: the work queue is unavailable', isError: true }- }- ctx.onWorkQueue?.(res.items)- return { output: res.message, isError: res.message.startsWith('ERROR') }-}diff --git a/web-app/src/lib/partialJson.ts b/web-app/src/lib/partialJson.tsindex 66bbbb173..358cbd44b 100644--- a/web-app/src/lib/partialJson.ts+++ b/web-app/src/lib/partialJson.ts@@ -125,8 +125,6 @@ const HEADER_FIELDS = ['url','pattern','name',- 'subagent_name',- 'description',] as constexport type PartialEdit = { old_string: string; new_string?: string }diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.tsindex 3df24a4f7..0827df9df 100644--- a/web-app/src/lib/toolPresentation.ts+++ b/web-app/src/lib/toolPresentation.ts@@ -71,6 +71,15 @@ const asEdits = (return edits.length > 0 ? edits : undefined}+/** The first subagent of a `dispatch_subagent` call, tolerating the streaming+ * partial shape (a flat `subagents[]`); undefined until enough args arrive. */+const firstPlannedSubagent = (+ subagents: unknown+): { name?: unknown; task?: unknown } | undefined => {+ if (!Array.isArray(subagents) || subagents.length === 0) return undefined+ return subagents[0] as { name?: unknown; task?: unknown }+}+/*** Build the bar for a native tool call from its arguments. Arguments stream in,* so a missing or partial value is normal and renders as an empty/partial bar@@ -97,10 +106,14 @@ export function describeNativeToolCall(return { variant: 'address', url: asString(args.url) }}if (origin.kind === 'subagent') {+ // The `dispatch_subagent` schema is a flat `subagents[]`; the card names the+ // first one (the widget is transient and hides once the fan-out is launched,+ // so a per-plan summary is not worth the extra chrome).+ const first = firstPlannedSubagent(args.subagents)return {variant: 'subagent',- name: asString(args.subagent_name),- task: asString(args.description),+ name: asString(first?.name),+ task: asString(first?.task),}}if (origin.kind === 'rag' && toolName === RAG_RETRIEVE_TOOL) {diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex f257a563d..8714a640c 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -668,8 +668,6 @@"backgroundRunning_one": "{{count}} background task running","backgroundRunning_other": "{{count}} background tasks running","monitors": "Monitors",- "workQueue": "Work queue",- "workReady": "{{count}} ready","monitorPolling": "Polling","monitorMatched": "Matched","monitorTimedOut": "Timed out",@@ -681,7 +679,10 @@"noBackgroundTasks": "No background tasks yet.","running": "Running","queued": "Queued",+ "waiting": "Waiting","finished": "Finished",+ "subagentPhase": "phase {{phase}}",+ "subagentWaiting": "waiting","viewTranscript": "View transcript","taskWorking": "Working…","taskNoOutput": "The subagent produced no visible output.",diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex b7d780182..3dd8accc7 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -99,13 +99,13 @@ import {import {getSandboxStatus,sandboxEnforces,- fillSubagentResult,+ writeBlackboard,+ BLACKBOARD_DIR_DISPLAY,importAttachment,- reserveSubagentResult,cancelAgentThreadBash,activeAgentMonitorIds,- type WorkItemView,} from '@/lib/agentTools'+import { isPlatformTauri } from '@/lib/platform'import { monitorLaneFor, type MonitorLane } from '@/lib/coworkMonitor'import { CoworkParkedNotice } from '@/containers/CoworkParkedNotice'import type { MonitorView } from '@/types/coworkSession'@@ -128,13 +128,15 @@ import {type SubagentDefinition,} from '@/lib/coworkSubagentRegistry'import {- dispatchedSubagentResult,- parseSubagentRequest,+ formatDispatchedPlan,+ parseDispatchPlan,resolveSubagent,parentToolNames,runSubagent,+ runDispatchPlan,subagentCompletionNotice,SubagentInbox,+ type ResolvedSubagent,} from '@/lib/coworkSubagent'import { useSkills } from '@/hooks/useSkills'import {@@ -174,7 +176,6 @@ const MANUAL_COMPACT_CONFIG: ContextManagerConfig = {// Stable empty set, so a session with no monitors does not re-render on every// store write the way a fresh `[]` from the selector would.const NO_MONITORS: MonitorView[] = []-const NO_WORKQUEUE: WorkItemView[] = []const NO_TURNS: CoworkTurn[] = []/** The session's monitor lane, mirrored into the run store for the rail. */@@ -401,9 +402,6 @@ function CoworkPage() {const monitors = useCoworkRun((s) => (session?.id ? s.monitors[session.id] : undefined) ?? NO_MONITORS)- const workqueue = useCoworkRun(- (s) => (session?.id ? s.workqueue[session.id] : undefined) ?? NO_WORKQUEUE- )const parked = useCoworkRun((s) =>session?.id ? (s.parked[session.id] ?? false) : false)@@ -609,8 +607,8 @@ function CoworkPage() {model: { provider: selectedProvider, id: selectedModel.id },planMode: current?.planMode ?? false,subagentNames: subagentDefs.map((d) => d.name),- // Always on at depth 0, even with nothing saved: a one-off subagent with- // an inline `system_prompt` is first-class, as it is in Rust.+ // Always on at depth 0, even with nothing saved: an unknown name runs as+ // a focused general-purpose subagent, as it does in Rust.allowSubagents: true,webSearch,workspacePath,@@ -706,9 +704,6 @@ function CoworkPage() {failedReadPaths,webSearch,monitors: monitorLane,- workAgentId: 'main',- onWorkQueue: (items) =>- useCoworkRun.getState().setWorkqueue(sid, items),onTodo: async (input) => {const result = applyTodoOp(useCoworkSessions@@ -766,17 +761,9 @@ function CoworkPage() {})}),onTask: async (callId, input) => {- const req = parseSubagentRequest(input)- if (typeof req === 'string') {- return { output: `ERROR: ${req}`, isError: true }- }- const resolved = resolveSubagent(- req,- subagentDefs,- parentToolNames(transport.advertisedTools)- )- if ('error' in resolved) {- return { output: `ERROR: ${resolved.error}`, isError: true }+ const plan = parseDispatchPlan(input)+ if (typeof plan === 'string') {+ return { output: `ERROR: ${plan}`, isError: true }}if (!transport.model) {return {@@ -785,125 +772,150 @@ function CoworkPage() {isError: true,}}- // Claimed before the child starts: the tool call returns now,- // so the path it reports has to exist now.- const saved = await reserveSubagentResult(- sid,- `${resolved.name}-${callId}`+ // Resolve every subagent up front so a tool-allowlist conflict+ // fails the whole dispatch atomically, before any child starts+ // (as in Rust). Names are unique across the plan.+ const parentTools = parentToolNames(transport.advertisedTools)+ const resolvedByName = new Map<string, ResolvedSubagent>()+ for (const phase of plan.phases) {+ for (const req of phase.subagents) {+ const resolved = resolveSubagent(+ req,+ subagentDefs,+ parentTools+ )+ if ('error' in resolved) {+ return {+ output: `ERROR: ${resolved.error}`,+ isError: true,+ }+ }+ resolvedByName.set(req.name, resolved)+ }+ }++ // Register the later phases up front as waiting, so the panel+ // shows them queued behind the phase in flight; each is+ // promoted by its own start (mirrors the Rust SubagentPlan).+ const pending = plan.phases.slice(1).flatMap((phase) =>+ phase.subagents.map((s) => ({+ runId: `${callId}-${s.name}`,+ name: s.name,+ phase: phase.number,+ })))+ if (pending.length > 0) {+ useCoworkRun.getState().planSubagents(sid, pending)+ }++ const model = transport.model+ const blackboardDir = isPlatformTauri()+ ? BLACKBOARD_DIR_DISPLAY+ : null++ // The plan hold keeps the run alive across the whole plan,+ // including the gap between one phase finishing and the next+ // dispatching (mirrors the Rust `plans_pending` guard).+ // Released once, in the finally below.inbox.begin()- const child = runSubagent({- resolved,- description: req.description,- // The parent's instance: a second one would mean a second- // llama-server load for the same model.- model: transport.model,- parentTools: transport.advertisedTools,- system: {- workspacePath,- readOnlyFolder: current?.folder ?? null,- bashAvailable: sandboxEnforces(),- environment,- },- signal: controller.signal,- sessionTokens: 0,- // A child never gets `todo`/`ask`/`task`, so these refuse- // rather than execute: a model can still emit a call to a- // tool that was never advertised.- dispatch: (call) =>- dispatchCoworkTool(call, {- sessionId: sid,- readOnlyFolder: current?.folder ?? null,- planMode: current?.planMode ?? false,- webSearch,- // A child has no inbox for a watcher to ping.- monitors: null,- // A worker posts/claims/completes under its own id so- // the queue attributes items to it.- workAgentId: `sub-${resolved.name}-${callId}`,- onWorkQueue: (items) =>- useCoworkRun.getState().setWorkqueue(sid, items),- onTodo: async () => ({- output:- 'The todo list belongs to the agent that dispatched you.',- isError: true,- }),- onAsk: async () => ({- output:- 'You cannot ask the user questions. Decide, and say what you assumed.',- isError: true,- }),- onTask: async () => ({- output: 'A subagent cannot dispatch subagents.',+ void runDispatchPlan(plan, callId, {+ runOne: (req, description, id) => {+ const resolved = resolvedByName.get(req.name)+ if (!resolved) {+ // Unreachable: every name was resolved above. Guard for+ // types (and never leave the plan hold unbalanced).+ return Promise.resolve({+ output: `ERROR: subagent '${req.name}' was not resolved`,+ usage: null,isError: true,- }),- }),- events: {- onQueued: (waiting) =>- useCoworkRun- .getState()- .queueSubagent(sid, callId, resolved.name, waiting),- onStart: () =>- useCoworkRun- .getState()- .startSubagent(sid, callId, resolved.name),- onInner: (event) =>- useCoworkRun- .getState()- .routeIntoSubagent(sid, callId, event),- onEnd: (usage) =>- useCoworkRun.getState().endSubagent(sid, callId, usage),+ sessionTokens: 0,+ })+ }+ return runSubagent({+ resolved,+ description,+ // The parent's instance: a second one would mean a+ // second llama-server load for the same model.+ model,+ parentTools: transport.advertisedTools,+ system: {+ workspacePath,+ readOnlyFolder: current?.folder ?? null,+ bashAvailable: sandboxEnforces(),+ environment,+ },+ signal: controller.signal,+ sessionTokens: 0,+ // A child never gets `todo`/`ask`/`task`, so these refuse+ // rather than execute: a model can still emit a call to a+ // tool that was never advertised.+ dispatch: (call) =>+ dispatchCoworkTool(call, {+ sessionId: sid,+ readOnlyFolder: current?.folder ?? null,+ planMode: current?.planMode ?? false,+ webSearch,+ // A child has no inbox for a watcher to ping.+ monitors: null,+ onTodo: async () => ({+ output:+ 'The todo list belongs to the agent that dispatched you.',+ isError: true,+ }),+ onAsk: async () => ({+ output:+ 'You cannot ask the user questions. Decide, and say what you assumed.',+ isError: true,+ }),+ onTask: async () => ({+ output: 'A subagent cannot dispatch subagents.',+ isError: true,+ }),+ }),+ events: {+ onQueued: (waiting) =>+ useCoworkRun+ .getState()+ .queueSubagent(sid, id, req.name, waiting),+ onStart: () =>+ useCoworkRun+ .getState()+ .startSubagent(sid, id, req.name),+ onInner: (event) =>+ useCoworkRun+ .getState()+ .routeIntoSubagent(sid, id, event),+ onEnd: (usage) =>+ useCoworkRun.getState().endSubagent(sid, id, usage),+ },+ })},- })- // Detached: the errand outlives its tool call, and the parent- // hears about it through the inbox instead.- void child- .then(async (done) => {+ writeBlackboard: (name, content) =>+ writeBlackboard(sid, name, content),+ // begin at dispatch, finish at completion: with the plan hold+ // above, inbox.pending() never reads false mid-plan.+ onDispatch: () => inbox.begin(),+ onComplete: (id, name, result, savedPath) => {useCoworkRun.getState()- .attachSubagentOutput(sid, callId, done.output)- // Only a real answer is filed: an error message in the file- // the parent was told to read would be indistinguishable- // from the answer it expected.- const filed =- saved && !done.isError && done.output.trim()- ? await fillSubagentResult(- sid,- saved.file,- done.output- )- : false- inbox.finish(- subagentCompletionNotice({- name: resolved.name,- callId,- savedPath: filed && saved ? saved.path : null,- output: done.output,- isError: done.isError,- })- )- })- .catch((e) =>- // `runSubagent` does not throw, so this is the loop itself- // failing. The count still has to come down or the run- // would wait on it forever.+ .attachSubagentOutput(sid, id, result.output)inbox.finish(subagentCompletionNotice({- name: resolved.name,- callId,- savedPath: null,- output: e instanceof Error ? e.message : String(e),- isError: true,+ name,+ callId: id,+ savedPath,+ output: result.output,+ isError: result.isError,}))- )- return {- output: dispatchedSubagentResult(- resolved.name,- callId,- saved?.path ?? null- ),- }+ },+ })+ // runDispatchPlan never throws; this only guarantees the plan+ // hold is released even if a callback above does.+ .catch(() => {})+ .finally(() => inbox.abandon())++ return { output: formatDispatchedPlan(plan, blackboardDir) }},})),@@ -1665,7 +1677,6 @@ function CoworkPage() {<CoworkTasksChipsubagents={subagents}monitors={monitors}- workqueue={workqueue}open={rail?.kind === 'tasks'}onToggle={() =>setRail((r) =>@@ -1740,7 +1751,6 @@ function CoworkPage() {<CoworkTasksPanelsubagents={subagents}monitors={monitors}- workqueue={workqueue}onClose={() => setRail(null)}/>)}diff --git a/web-app/src/types/coworkSession.ts b/web-app/src/types/coworkSession.tsindex b1856862e..147efc5bd 100644--- a/web-app/src/types/coworkSession.ts+++ b/web-app/src/types/coworkSession.ts@@ -80,11 +80,17 @@ export type Usage = {export type SubagentRun = {runId: stringname: string- status: 'queued' | 'running' | 'done'+ /** `waiting`: a later-phase subagent registered up front, not yet dispatched+ * (it starts only once its phase begins). `queued`: dispatched, waiting for a+ * concurrency slot. */+ status: 'waiting' | 'queued' | 'running' | 'done'startedAt: numberendedAt?: number/** 1-based FIFO queue position while `queued`; cleared on start. */waiting?: number+ /** 1-based phase this subagent belongs to (from a phased dispatch); drives the+ * "phase N · waiting" hint and the running-row phase badge. */+ phase?: number/** The subagent's own trace. The final answer is in `finalOutput`, not here. */turns: CoworkTurn[]finalOutput?: string