Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): collaborative subagents + TUI chain-of-thought timeline
Akarshan Biswas3a860ab6dfea
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsindex 022e23b94..0aba8f1ef 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -20,6 +20,11 @@ const COMMANDS: &[&str] = &["sandbox_status","subagent_result_reserve","subagent_result_fill",+ "work_post",+ "work_claim",+ "work_complete",+ "work_list",+ "agent_read","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 702387fbd..d3e200dd9 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,6 +296,70 @@ 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(+ threadId: string,+ agentId: string,+ args: Record<string, unknown>+): Promise<WorkCommandResult> {+ return await invoke('plugin:agent-tools|work_complete', {+ threadId,+ agentId,+ args,+ })+}++/** 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. */+export async function agentRead(+ threadId: string,+ args: Record<string, unknown>+): Promise<string> {+ return await invoke('plugin:agent-tools|agent_read', { threadId, 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 c51171cc8..eaf64f8d4 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -22,6 +22,11 @@ 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-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 ca8fd4f87..76f203544 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,6 +294,18 @@"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",@@ -666,6 +678,54 @@"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",@@ -679,10 +739,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-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-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`","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-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-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`"}]}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 006db7680..17f1792d5 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -447,6 +447,104 @@ 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}`.+#[tauri::command]+pub async fn work_complete(+ 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`).+#[tauri::command]+pub async fn agent_read(+ thread_id: String,+ args: serde_json::Value,+) -> 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))+ .await+ .map_err(|e| AgentToolsError::from(format!("agent read failed: {e}")))+}+/// An attachment imported into a session workspace: host paths, which are also/// the model-visible spelling since the workspace is the tools' root.#[derive(serde::Serialize)]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 7b9864bb6..44ee4163a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -63,6 +63,11 @@ 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::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 496626903..1af918264 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,6 +16,10 @@ 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.@@ -23,6 +27,19 @@ 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.+pub fn epoch_secs() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+}/// A single OpenAI `image_url` content part: the `data:<mime>;base64,<bytes>`/// URL plus a display name. This is what the `read` tool returns for an imagediff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/observ.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/observ.rsnew file mode 100644index 000000000..72d97af3c--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/observ.rs@@ -0,0 +1,557 @@+//! 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.+pub fn run_read_agent(scratch: &Path, args: &serde_json::Value) -> 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 {+ 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 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 6384afb7c..7a49671be 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@@ -125,8 +125,10 @@ 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.-fn open_truncating(path: &Path) -> std::io::Result<std::fs::File> {+/// 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.+pub(crate) fn open_truncating(path: &Path) -> std::io::Result<std::fs::File> {std::fs::OpenOptions::new().write(true).truncate(true)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.rsnew file mode 100644index 000000000..56aef3cdf--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/workqueue.rs@@ -0,0 +1,962 @@+//! 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 774b8d3d8..5132e1d3d 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -143,6 +143,25 @@ in its own window and returns only the distilled answer. Dispatch independent sutheir work doesn't depend on each other, then `await_subagent` each. 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), so a worker knows the claim -> do -> complete -> stop loop+/// even though it cannot dispatch.+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. As a worker: call `claim_work` to take the next ready task, do \+it, then `complete_work` with the result. If `claim_work` reports nothing is ready, stop -- do not loop \+on it; you are re-dispatched when new work appears. `list_work` shows the whole queue, and `read_agent` \+shows what any agent is doing (call it with no argument for the roster of every agent).";++/// 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@@ -257,6 +276,7 @@ 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 {@@ -272,6 +292,14 @@ 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) {@@ -410,7 +438,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).expect("prompt");+ let out = build_system_prompt(Some("You are Jan."), &root, None, false, 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.@@ -423,7 +451,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).expect("prompt");+ let out = build_system_prompt(None, &root, None, false, false).expect("prompt");assert!(out.contains("# Web Access"));assert!(out.contains("web_search"));assert!(out.contains("web_fetch"));@@ -441,13 +469,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).expect("guide always present");+ let out = build_system_prompt(None, &root, None, false, 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).expect("prompt");+ let with_base = build_system_prompt(Some("base"), &root, None, false, false).expect("prompt");assert!(with_base.starts_with("base"));assert!(with_base.contains("Skills and Project Memory"));let _ = std::fs::remove_dir_all(&root);@@ -456,7 +484,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).expect("prompt");+ let out = build_system_prompt(None, &root, None, false, false).expect("prompt");assert!(out.starts_with("You're currently running on Jan agent harness"));assert!(out.contains("# Guidelines"));assert!(out.contains("Be concise"));@@ -484,7 +512,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).expect("prompt");+ let prompt = build_system_prompt(None, &nested, None, false, 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);@@ -501,9 +529,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).expect("prompt");+ let without = build_system_prompt(None, &root, None, false, false).expect("prompt");assert!(!without.contains("dispatch_subagent"));- let with = build_system_prompt(None, &root, None, true).expect("prompt");+ let with = build_system_prompt(None, &root, None, true, false).expect("prompt");assert!(with.contains("dispatch_subagent"));let _ = std::fs::remove_dir_all(&root);}@@ -535,7 +563,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).expect("prompt");+ let out = build_system_prompt(None, &root, None, false, 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 02f7d42ce..74aba28e7 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -133,6 +133,29 @@ 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.@@ -198,6 +221,27 @@ 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,+ });+ }+}+/// If `path` targets a file in the agent's skill or memory workspace, return the/// kind (`"skill"`/`"memory"`) and the item name (file stem). None otherwise.fn classify_agent_path(path: &str) -> Option<(&'static str, String)> {@@ -503,6 +547,67 @@ 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 d94571c92..8c1e96f55 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -114,6 +114,19 @@ 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]@@ -186,6 +199,11 @@ 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) {}}/// Emit [`StreamEvent::Monitors`] when the set differs from what was last@@ -205,6 +223,57 @@ 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,@@ -359,6 +428,23 @@ 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@@ -671,6 +757,120 @@ 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 {+ return observ::run_read_agent(scratch, args);+ }+ 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@@ -1085,9 +1285,46 @@ 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 background_pending(&self) -> bool {self.subagents.as_ref()@@ -1225,6 +1462,36 @@ 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")@@ -1445,6 +1712,7 @@ 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)}}@@ -1490,6 +1758,11 @@ 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),@@ -1613,6 +1886,7 @@ 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() {@@ -1678,6 +1952,32 @@ fn advertise_local_tools(openai_tools.push(tauri_plugin_agent_tools::tools::monitor::monitor_tool_schema());}}+ // Work-queue + observability tools. Available to main AND to workers+ // (unlike subagent dispatch, which caps recursion), gated on+ // collaboration being enabled. The mutating three are hidden in Plan;+ // `read_agent`/`list_work` are read-only and stay.+ 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 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);+ }+ let read_agent = tauri_plugin_agent_tools::tools::observ::read_agent_tool_schema();+ let ra_name = read_agent["function"]["name"].as_str().unwrap_or_default();+ if !permissions.is_denied(ra_name)+ && allowed_names.is_none_or(|allowed| allowed.contains(ra_name))+ {+ openai_tools.push(read_agent);+ }+ }}// The `ask` tool needs no project (it's an interactive question, not// filesystem access), so it's advertised independent of the project_root@@ -1739,6 +2039,7 @@ 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 {@@ -1752,6 +2053,7 @@ fn build_run_system_prompt(root,scratch.as_deref(),subagents_enabled,+ work_queue_enabled,)}None => base.map(str::to_string),@@ -1772,6 +2074,7 @@ 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(@@ -1781,6 +2084,7 @@ pub(crate) fn context_system_prompt_preview(session_id,subagents_enabled,settings.sandbox,+ work_queue_enabled,)}@@ -1803,6 +2107,7 @@ 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)@@ -1823,6 +2128,7 @@ pub(crate) async fn context_advertised_tools(max_parallel_subagents,ask_enabled,todo_enabled,+ work_queue_enabled,);tools}@@ -1919,6 +2225,9 @@ 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@@ -1982,6 +2291,7 @@ 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.@@ -2118,6 +2428,7 @@ 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(@@ -2159,9 +2470,14 @@ 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.- let bg = std::sync::Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(- *max_parallel_subagents,- ));+ // 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(),+ ),+ );let _bg_guard = crate::core::agent::subagent::AbortOnDrop(bg.clone());let subagents = args.subagents_enabled.then(|| SubagentContext {parent_args: args.clone(),@@ -2182,9 +2498,38 @@ 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);- if settings.sandbox {+ // 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 {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),@@ -2209,6 +2554,11 @@ 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,@@ -2524,6 +2874,10 @@ 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@@ -3185,6 +3539,7 @@ mod tests {Some("test-session"),false,true,+ false,).expect("prompt");@@ -5193,6 +5548,13 @@ 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),}}@@ -5320,6 +5682,7 @@ mod tests {Some("s1"),false,true,+ false,).expect("prompt");assert!(confined.contains("Scratch:"), "{confined}");@@ -5330,6 +5693,7 @@ 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 d876ba227..f759c9f82 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -121,6 +121,12 @@ 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`,@@ -177,6 +183,7 @@ 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 8c0b9399a..243daf96a 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -599,6 +599,52 @@ 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@@ -657,12 +703,18 @@ 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.- wake: tokio::sync::Notify,+ /// 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.+ 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>,}/// Default cap on concurrently *running* subagents per parent run when@@ -680,13 +732,21 @@ 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: tokio::sync::Notify::new(),+ wake: work.shared_wake(),running: std::sync::atomic::AtomicUsize::new(0),+ work,}}@@ -703,6 +763,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()}/// Park until a ping is available, or until nothing is left to wait for.@@ -715,7 +776,12 @@ 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.if !self.notices.lock().unwrap().is_empty()+ || self.work.is_pending()|| self.running.load(std::sync::atomic::Ordering::SeqCst) == 0{return;@@ -835,7 +901,7 @@ fn child_body(/// the definition's system prompt, narrowed tools, dispatch disabled.async fn run_subagent(parent_args: crate::core::agent::r#loop::OrchestrationArgs,- resolved: ResolvedDispatch,+ mut resolved: ResolvedDispatch,description: String,parent: ParentRun,events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,@@ -858,8 +924,32 @@ 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(),@@ -873,12 +963,21 @@ async fn run_subagent(let fwd_name = name.clone();let forwarder = tokio::spawn(async move {while let Some(ev) = child_rx.recv().await {- if forward_to_parent(&ev) {- let _ = parent_events.send(StreamEvent::Subagent {- run_id: fwd_run_id.clone(),- name: fwd_name.clone(),- event: Box::new(ev),- });+ 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(),+ name: fwd_name.clone(),+ event: Box::new(ev),+ });+ }+ _ => {}}}});@@ -891,6 +990,13 @@ 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,@@ -899,6 +1005,61 @@ 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@@ -2021,6 +2182,50 @@ 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@@ -2055,6 +2260,9 @@ 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,}}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 9eb7178a7..880663055 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -692,6 +692,7 @@ 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(),@@ -724,6 +725,12 @@ 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,}}@@ -962,6 +969,9 @@ 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,@@ -973,6 +983,7 @@ fn prepare_agent_session(flags.plan,max_parallel_subagents,flags.sandbox,+ work_queue_enabled,);// Resolution order: configured `[agent].context_window` override, then the@@ -1397,6 +1408,26 @@ 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 ce1c869cd..c1e10a3c4 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -55,6 +55,7 @@ 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`,@@ -2032,6 +2033,10 @@ 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@@ -2288,6 +2293,10 @@ 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>,}/// How a closed child's summary row reads. `Failed` carries the reason the@@ -2493,6 +2502,7 @@ 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(),@@ -2947,65 +2957,10 @@ impl App {runs}- /// The live run's *settled* steps, folded behind one header so the condensed- /// view shows only the step in flight. Settled steps are the reasoning-summary- /// and tool-group rows after the last answer that are not the running box.- ///- /// The fold is stable for the whole run: it depends only on the run being live- /// (`Status::Running`) and on how many settled steps exist -- never on a- /// transient frontier or a per-event marker -- so the header cannot toggle- /// open as one step hands off to the next, in the gap before a step's content- /// arrives, or when a background (monitor/subagent/notice) event lands. The- /// frontier below the header is the only moving part. Gating on status also- /// means the fold ends the instant the run does: `draw` never gets an animated- /// header over an idle transcript, and the committed `trace_runs` fold (static,- /// past-tense) takes over the same rows, so nothing moves on wrap-up.- ///- /// Returns `None` until two settled steps exist: a lone step is already one- /// line, so a header would save no space and only read as "1 step".- fn active_fold(&self) -> Option<TraceRun> {- if self.status != Status::Running {- return None;- }- let running = self- .tool_group- .as_ref()- .filter(|g| g.is_running())- .map(|g| g.idx);- let last_answer = self.last_answer_idx();- let mut settled: Vec<(usize, bool)> = Vec::new();- for g in &self.groups {- settled.push((g.idx, true));- }- for r in &self.reasoning_blocks {- settled.push((r.idx, false));- }- // A finished-but-not-yet-closed command is a settled prior step too.- if let Some(g) = &self.tool_group {- if !g.is_running() {- settled.push((g.idx, true));- }- }- settled.retain(|(i, _)| last_answer.is_none_or(|a| *i > a) && Some(*i) != running);- if settled.len() < 2 {- return None;- }- settled.sort_by_key(|(i, _)| *i);- let tool_ran =- running.is_some() || !self.starting.is_empty() || settled.iter().any(|(_, t)| *t);- Some(TraceRun {- start: settled[0].0,- end: settled.last().unwrap().0,- tool_ran,- steps: settled.len(),- })- }-/// Expand/fold the trace that starts at `start` (toggles its opt-out of the/// default fold). A no-op if `start` is not a trace or active-fold start.fn toggle_trace(&mut self, start: usize) {- let is_start = self.trace_runs().iter().any(|r| r.start == start)- || self.active_fold().is_some_and(|r| r.start == start);+ let is_start = self.trace_runs().iter().any(|r| r.start == start);if !is_start {return;}@@ -3076,6 +3031,10 @@ impl App {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();@@ -3368,13 +3327,9 @@ impl App {.chain(self.reasoning_blocks.iter().map(|r| r.idx)).chain(self.subagent_blocks.iter().map(|b| b.idx)).collect();- // Ctrl-O also unfolds every collapsed trace (finished runs and the- // active fold), so one keystroke opens both the folds and the per-row- // detail.- let mut trace_starts: Vec<usize> = self.trace_runs().iter().map(|r| r.start).collect();- if let Some(run) = self.active_fold() {- trace_starts.push(run.start);- }+ // Ctrl-O also unfolds every collapsed (finished) trace, so one keystroke+ // opens both the folds and the per-row detail.+ let trace_starts: Vec<usize> = self.trace_runs().iter().map(|r| r.start).collect();if all.is_empty() && trace_starts.is_empty() {return;}@@ -3394,18 +3349,17 @@ impl App {}/// Whether transcript row `idx` is currently drawn as a folded trace header- /// (a finished trace start or the active fold's start, not expanded), so a- /// click there unfolds the trace rather than toggling that row's own detail.+ /// (a finished trace start, not expanded), so a click there unfolds the trace+ /// rather than toggling that row's own detail. The active run never folds, so+ /// only finished traces qualify.fn is_folded_trace_start(&self, idx: usize) -> bool {if self.expanded_traces.contains(&idx) {return false;}let last_answer = self.last_answer_idx();- let finished = self- .trace_runs()+ self.trace_runs().iter()- .any(|r| r.start == idx && last_answer.is_some_and(|a| r.end < a));- finished || self.active_fold().is_some_and(|r| r.start == idx)+ .any(|r| r.start == idx && last_answer.is_some_and(|a| r.end < a))}/// Toggle a single collapsed region by its transcript row index (a click on@@ -4735,6 +4689,7 @@ 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 =@@ -4757,6 +4712,7 @@ 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()@@ -5140,6 +5096,7 @@ impl App {active: None,queued: false,waiting: 0,+ work_id: None,});}}@@ -5164,6 +5121,7 @@ impl App {active: None,queued: true,waiting,+ work_id: None,});}StreamEvent::SubagentEnd {@@ -5195,6 +5153,19 @@ 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,@@ -7218,24 +7189,16 @@ fn group_summary(nouns: &[(&str, bool)]) -> String {group_clauses(nouns, "Read", "ran")}-/// The one-line header a folded trace collapses to, with a step count so the-/// fold advertises how much it hides. A finished run gets a static `▸` and past-/// tense (`▸ Worked · N steps` / `▸ Thought · N steps`); the active run -- still-/// streaming, its current step shown live below -- gets the spinner and present-/// tense (`⠋ Working · N steps` / `⠋ Thinking · N steps`), so the condensed live-/// view reads as one moving header over the current step rather than a growing-/// pile of settled rows.-fn trace_header_line(run: &TraceRun, active: bool, frame: &str) -> Line<'static> {- let (marker, verb) = if active {- let verb = if run.tool_ran { "Working" } else { "Thinking" };- (format!("{frame} "), verb)- } else {- let verb = if run.tool_ran { "Worked" } else { "Thought" };- ("▸ ".to_string(), verb)- };+/// The one-line header a finished trace collapses to, with a step count so the+/// fold advertises how much it hides: a static `▸` and past tense+/// (`▸ Worked · N steps` / `▸ Thought · N steps`). Only finished traces fold;+/// the active run renders as the live growing rail (each step as it happens), so+/// there is no present-tense header form.+fn trace_header_line(run: &TraceRun) -> Line<'static> {+ let verb = if run.tool_ran { "Worked" } else { "Thought" };let unit = if run.steps == 1 { "step" } else { "steps" };Line::from(vec![- Span::styled(marker, Style::new().cyan()),+ Span::styled("▸ ".to_string(), Style::new().cyan()),Span::styled(format!("{verb} · {} {unit}", run.steps),Style::new().cyan().dim(),@@ -7243,6 +7206,17 @@ fn trace_header_line(run: &TraceRun, active: bool, frame: &str) -> Line<'static>])}+/// The terminal cap of an expanded trace's rail: a `└` corner that closes the+/// run of `│`-gutter step rows into a `Done` marker, so the timeline reads as a+/// completed thread. Only rendered under an expanded finished trace; the live+/// rail's terminal is its current step, and a folded trace shows only the header.+fn trace_done_line() -> Line<'static> {+ Line::from(vec![+ Span::styled("└ ", Style::new().dark_gray()),+ Span::styled("Done", Style::new().dark_gray()),+ ])+}+/// Live rows for the still-open tool group: a braille throbber in place of the/// static `▸` tag, the running call's label, and elapsed time, so the user can/// see it's actively working and how long it's taken. Rebuilt fresh every draw@@ -14913,26 +14887,32 @@ fn draw(f: &mut Frame, app: &mut App) {let mut content_h: u16 = 0;let mut reveal_at: Option<u16> = None;let frame = app.spinner();- // Traces fold their run of reasoning/tool rows to one header unless the user- // expanded it. A finished run (an answer follows) folds whole to a static- // `Thought/Worked` header. The active run's settled steps fold to a live- // `Thinking/Working` header, leaving only the current step (the running box /- // live tail) below -- the condensed live view. The `bool` is that live flag.+ // A finished trace (an answer follows) folds its run of reasoning/tool rows+ // to one static `Thought/Worked` header unless the user expanded it. The+ // active run is never folded: its steps render as the live growing rail, so+ // the reader watches each step land as it happens.let last_answer = app.last_answer_idx();- let mut collapsed_headers: HashMap<usize, (TraceRun, bool)> = HashMap::new();+ let mut collapsed_headers: HashMap<usize, TraceRun> = HashMap::new();for run in app.trace_runs() {if last_answer.is_some_and(|a| run.end < a) && !app.expanded_traces.contains(&run.start) {- collapsed_headers.insert(run.start, (run, false));- }- }- if let Some(run) = app.active_fold() {- if !app.expanded_traces.contains(&run.start) {- collapsed_headers.insert(run.start, (run, true));+ collapsed_headers.insert(run.start, run);}}let hidden_trace_rows: std::collections::HashSet<usize> = collapsed_headers.values()- .flat_map(|(r, _)| (r.start + 1)..=r.end)+ .flat_map(|r| (r.start + 1)..=r.end)+ .collect();+ // A finished trace the user expanded caps its rail with a `└ Done` terminal+ // after its last row, keyed by that row's index. The live rail's terminal is+ // its current step, and a folded trace shows only its header, so neither gets+ // one.+ let expanded_trace_ends: std::collections::HashSet<usize> = app+ .trace_runs()+ .iter()+ .filter(|r| {+ last_answer.is_some_and(|a| r.end < a) && app.expanded_traces.contains(&r.start)+ })+ .map(|r| r.end).collect();for (i, row) in app.transcript.iter().enumerate() {// A collapsed trace shows a single header at its start and hides the@@ -14940,8 +14920,8 @@ fn draw(f: &mut Frame, app: &mut App) {if hidden_trace_rows.contains(&i) {continue;}- if let Some((run, active)) = collapsed_headers.get(&i) {- let line = trace_header_line(run, *active, frame);+ if let Some(run) = collapsed_headers.get(&i) {+ let line = trace_header_line(run);let seg = Segment::eager(Some(i), vec![line], width);if app.reveal == Some(i) {reveal_at = Some(content_h);@@ -15015,6 +14995,14 @@ fn draw(f: &mut Frame, app: &mut App) {segs.push(seg);}}+ // Cap an expanded finished trace's rail with the `└ Done` terminal, after+ // its last row (and that row's own detail). Keyed to the same `idx`, so a+ // click on it collapses the run like any other row of the trace.+ if expanded_trace_ends.contains(&i) {+ let seg = Segment::eager(Some(i), vec![trace_done_line()], width);+ content_h = content_h.saturating_add(seg.height);+ segs.push(seg);+ }}// Streaming prose and the awaiting throbbers have no transcript index; they@@ -16570,6 +16558,9 @@ 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));@@ -17043,12 +17034,14 @@ 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();+ let has_activity =+ !app.subagents.is_empty() || !app.monitors.is_empty() || !app.workqueue.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,@@ -17060,6 +17053,7 @@ 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,@@ -17076,6 +17070,7 @@ 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,@@ -17092,23 +17087,108 @@ 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>> {- let monitor_rows = if panels.is_empty() {+ // 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()+ };+ let want_mon = if monitors.is_empty() {+ 0+ } else {+ 1 + monitors.len()+ };+ let compact_budget = if panels.is_empty() {rows} else {- (1 + monitors.len()).min(rows / 2)+ (want_queue + want_mon).min(rows / 2)};- let monitors = monitors_column(monitors, width, monitor_rows);- let mut out = agents_column(panels, context_window, width, rows - monitors.len(), frame);+ 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 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.@@ -17535,6 +17615,7 @@ mod tests {MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON, PROVIDERS_SETTINGS_ROW, SLASH_COMMANDS, SPINNER,SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,};+ use super::{workqueue_column, WorkItemView};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::r#loop::PermissionRegistry;use crate::core::cli::updater::{AvailableUpdate, UpdateOutcome};@@ -17628,6 +17709,80 @@ 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}");+ }++ #[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>,) -> (@@ -22828,6 +22983,9 @@ 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());@@ -26669,6 +26827,60 @@ mod tests {assert!(refolded.contains("Worked \u{b7} 2 steps"), "refolded: {refolded}");}+ /// An expanded finished trace caps its rail with a `└ Done` terminal; the+ /// folded header does not, and neither does a live (unfinished) run.+ #[test]+ fn an_expanded_finished_trace_ends_with_done() {+ let mut app = test_app();+ app.apply(StreamEvent::Token { text: "<think>weigh it</think>".into() });+ app.apply(StreamEvent::ToolCall {+ id: "c1".into(),+ name: "grep".into(),+ args: json!({ "pattern": "x" }),+ });+ app.apply(StreamEvent::ToolResult {+ id: "c1".into(),+ content: "match".into(),+ is_error: false,+ diff: None,+ });+ app.apply(StreamEvent::Token { text: "the answer".into() });+ app.flush_assistant();+ let start = app.trace_runs()[0].start;++ // Folded: header only, no terminal.+ let folded = render_rows(&mut app, 70, 20).join("\n");+ assert!(!folded.contains("Done"), "folded trace has no terminal: {folded}");++ // Expanded: the rail ends in `└ Done`.+ app.toggle_trace(start);+ let open = render_rows(&mut app, 70, 20).join("\n");+ assert!(open.contains("\u{2514} Done"), "expanded rail ends with Done: {open}");+ }++ /// A live (unfinished) run's rail has no `Done` terminal: its current step is+ /// the terminal, and Done would wrongly read as finished.+ #[test]+ fn a_live_rail_has_no_done_terminal() {+ let mut app = test_app();+ app.status = super::Status::Running;+ app.apply(StreamEvent::Token { text: "<think>first</think>".into() });+ app.apply(StreamEvent::ToolCall {+ id: "t1".into(),+ name: "grep".into(),+ args: json!({ "pattern": "x" }),+ });+ app.apply(StreamEvent::ToolResult {+ id: "t1".into(),+ content: "match".into(),+ is_error: false,+ diff: None,+ });+ app.apply(StreamEvent::Token { text: "<think>second</think>".into() });+ let live = render_rows(&mut app, 70, 20).join("\n");+ assert!(!live.contains("Done"), "no Done terminal while live: {live}");+ }+/// Ctrl-O (`toggle_regions`) unfolds every collapsed trace along with the/// per-row detail, and folds them back on the next press.#[test]@@ -26696,11 +26908,12 @@ mod tests {assert!(render_rows(&mut app, 70, 20).join("\n").contains("Worked \u{b7}"), "Ctrl-O refolds");}- /// The condensed live view: while an active run streams, its settled steps- /// fold into a live `Working…` header and only the current step (the running- /// command box here) shows below -- no growing pile of settled rows.+ /// The live growing rail: while an active run streams, each settled step+ /// renders as its own row (reasoning summaries and finished tool rows), with+ /// the current step (the running command box here) as the frontier below --+ /// the reader watches the trail accrue rather than a single folded header.#[test]- fn the_active_trace_folds_to_a_live_header() {+ fn the_active_trace_shows_the_growing_rail() {let mut app = test_app();app.status = super::Status::Running;// reasoning, tool, reasoning, then a running tool -- three settled@@ -26729,17 +26942,15 @@ mod tests {assert!(runs[0].steps == 3 && runs[0].tool_ran, "{:?}", runs[0]);let live = render_rows(&mut app, 70, 20).join("\n");- // Live header (present tense, spinner-led), settled steps folded away.- assert!(live.contains("Working \u{b7} 3 steps"), "live header: {live}");- assert!(!live.contains("Thought"), "settled steps folded: {live}");- // The current step -- the running command -- shows below the header.+ // No live fold header: the settled steps render on the rail instead.+ assert!(!live.contains("Working \u{b7}"), "no live fold header: {live}");+ assert!(live.contains("Thought"), "settled reasoning steps show: {live}");+ // The current step -- the running command -- shows as the frontier.assert!(live.contains("$ cargo test"), "current step shows: {live}");}- /// A lone settled step is not worth a fold header: it is already one line, so- /// a header saves no space, reads as "1 step", and would then un-fold on- /// wrap-up (the committed trace fold needs 2+ too). It stays visible beside- /// the current step instead. Only a second settled step earns the fold.+ /// A live run shows both its settled step and the current reasoning step at+ /// once: the growing rail never hides a settled row while a step is in flight.#[test]fn a_lone_finished_tool_is_not_folded() {let mut app = test_app();@@ -26766,11 +26977,11 @@ mod tests {assert!(live.contains("analyzing the diff"), "the current reasoning shows: {live}");}- /// The reported case: while the next tool call is still typing its arguments- /// (the live typing box), the prior settled steps must fold behind the live- /// header rather than all rendering above the box.+ /// While the next tool call is still typing its arguments (the live typing+ /// box), the prior settled steps render on the rail above it -- the growing+ /// live trail, with the typing box as the current step.#[test]- fn prior_steps_fold_while_the_next_tool_call_is_typing() {+ fn prior_steps_show_while_the_next_tool_call_is_typing() {let mut app = test_app();app.status = super::Status::Running;app.apply(StreamEvent::Token { text: "<think>investigating</think>".into() });@@ -26796,16 +27007,16 @@ mod tests {});let live = render_rows(&mut app, 70, 20).join("\n");- assert!(live.contains("Working \u{b7} 2 steps"), "prior steps fold: {live}");- assert!(!live.contains("grep needle"), "the prior command row is gone: {live}");+ assert!(!live.contains("Working \u{b7}"), "no live fold header: {live}");+ assert!(live.contains("grep needle"), "the prior command row shows on the rail: {live}");assert!(live.contains("cargo build"), "the typing box is the current step: {live}");}- /// The screenshot case: after an answer, a fresh run of settled steps must- /// stay folded across the gap between one step finishing and the next- /// starting -- while the run is live, not only while a token is mid-flight.+ /// After an answer, a fresh run of settled steps renders on the growing rail+ /// -- each step visible -- across the gap between one step finishing and the+ /// next starting, and a `Step` event does not change that.#[test]- fn a_settled_run_stays_folded_in_the_gap_between_steps() {+ fn a_settled_run_shows_its_steps_in_the_gap() {let mut app = test_app();app.status = super::Status::Running;app.apply(StreamEvent::Token { text: "I'll review this PR.".into() });@@ -26827,29 +27038,26 @@ mod tests {});}// No token in flight now: a bare gap, but the run is still live, so the- // settled steps stay folded behind the header rather than un-folding for- // the frame before the next step's content arrives.+ // settled steps render on the rail rather than folding behind a header.let live = render_rows(&mut app, 90, 24).join("\n");- assert!(live.contains("Working \u{b7} 4 steps"), "the run folds in the gap: {live}");- assert!(!live.contains("grep alpha"), "no lingering command rows: {live}");- assert!(!live.contains("grep bravo"), "no lingering command rows: {live}");+ assert!(!live.contains("Working \u{b7}"), "no live fold header in the gap: {live}");+ assert!(live.contains("grep alpha"), "settled step shows on the rail: {live}");+ assert!(live.contains("grep bravo"), "settled step shows on the rail: {live}");- // The fold does not depend on a Step event to hold; a Step (the next- // turn) keeps it folded just the same, never toggling it open.+ // A Step event (the next turn) does not change that: the rail stays.app.apply(StreamEvent::Step { index: 3, max: 8 });- let folded = render_rows(&mut app, 90, 24).join("\n");- assert!(folded.contains("Working \u{b7} 4 steps"), "still folded after a Step: {folded}");- assert!(!folded.contains("grep alpha"), "prior command rows stay hidden: {folded}");- assert!(!folded.contains("grep bravo"), "prior command rows stay hidden: {folded}");+ let after = render_rows(&mut app, 90, 24).join("\n");+ assert!(!after.contains("Working \u{b7}"), "still no fold header after a Step: {after}");+ assert!(after.contains("grep alpha"), "steps stay visible after a Step: {after}");+ assert!(after.contains("grep bravo"), "steps stay visible after a Step: {after}");}- /// Gating the live fold on `Status::Running` ties it to the run's lifetime: a- /// `Step` landing as the last event before the stream stops cannot leave an- /// animated `Working · N steps` header spinning over an idle transcript. This- /// is the phantom-header regression the removed `step_boundary` flag caused- /// (it was never reset on the terminal paths, which skip `apply`).+ /// The active run shows its steps on the rail (no header of either tense);+ /// once the run finishes with an answer, the finished trace folds to the+ /// static `Worked · N steps` header. There is no live header that could be+ /// left spinning over an idle transcript.#[test]- fn the_live_fold_ends_with_the_run() {+ fn the_growing_rail_folds_when_the_run_finishes() {let mut app = test_app();app.status = super::Status::Running;for (id, cmd) in [("t1", "grep alpha"), ("t2", "grep bravo")] {@@ -26868,15 +27076,22 @@ mod tests {diff: None,});}- // A Step arrives, then the run stops with no further content.- app.apply(StreamEvent::Step { index: 2, max: 8 });+ // Live: the steps show on the rail, no fold header of either tense.+ let live = render_rows(&mut app, 90, 24).join("\n");assert!(- render_rows(&mut app, 90, 24).join("\n").contains("Working \u{b7} 4 steps"),- "folded while the run is live"+ !live.contains("Working \u{b7}") && !live.contains("Worked \u{b7}"),+ "no header while live: {live}");+ assert!(live.contains("grep alpha"), "steps show on the rail: {live}");++ // The run answers and ends: the finished trace folds to a static header.+ app.apply(StreamEvent::Token { text: "reviewed it".into() });+ app.flush_assistant();app.status = super::Status::Idle;let idle = render_rows(&mut app, 90, 24).join("\n");- assert!(!idle.contains("Working"), "no phantom animated header at idle: {idle}");+ assert!(idle.contains("Worked \u{b7}"), "finished trace folds: {idle}");+ assert!(!idle.contains("Working"), "no phantom live header at idle: {idle}");+ assert!(idle.contains("reviewed it"), "the answer shows: {idle}");}#[test]diff --git a/web-app/src/containers/CoworkTasksChip.tsx b/web-app/src/containers/CoworkTasksChip.tsxindex 4b98f39d6..cbc6e1bcc 100644--- a/web-app/src/containers/CoworkTasksChip.tsx+++ b/web-app/src/containers/CoworkTasksChip.tsx@@ -7,6 +7,7 @@ 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'/**@@ -22,6 +23,7 @@ import type { MonitorView, SubagentRun } from '@/types/coworkSession'export function CoworkTasksChip({subagents,monitors = [],+ workqueue = [],open,onToggle,}: {@@ -29,22 +31,28 @@ 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+ const total = subagents.length + monitors.length + workqueue.lengthif (total === 0) return nullconst activeSubagents = subagents.filter((s) => s.status !== 'done').lengthconst activeMonitors = monitors.filter((m) => m.status === 'running').length- const active = activeSubagents + activeMonitors+ const activeWork = workqueue.filter(+ (w) => w.state !== 'done' && w.state !== 'failed'+ ).length+ const active = activeSubagents + activeMonitors + activeWork+ const onlyKind = (kept: number) => active > 0 && active === keptconst label =active === 0? t('common:backgroundTasks')- : activeMonitors === 0+ : onlyKind(activeSubagents)? t('common:subagentsRunning', { count: active })- : activeSubagents === 0+ : onlyKind(activeMonitors)? t('common:monitorsRunning', { count: active }): t('common:backgroundRunning', { count: active })diff --git a/web-app/src/containers/CoworkTasksPanel.tsx b/web-app/src/containers/CoworkTasksPanel.tsxindex 04b89f881..696276a84 100644--- a/web-app/src/containers/CoworkTasksPanel.tsx+++ b/web-app/src/containers/CoworkTasksPanel.tsx@@ -3,6 +3,7 @@ import { useEffect, useMemo, useState } from 'react'import { ChevronLeft, ChevronDown, 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,@@ -104,6 +105,46 @@ 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[] {@@ -207,12 +248,15 @@ 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()@@ -259,12 +303,24 @@ 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 ? (+ {subagents.length === 0 &&+ monitors.length === 0 &&+ workqueue.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) => (diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.tsindex e5b4b6317..37f7a6a70 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 } from '@/lib/agentTools'+import type { MonitorUpdate, WorkItemView } from '@/lib/agentTools'import { userTurn } from '@/lib/coworkTurns'import type { ModelLoadProgress } from '@/hooks/useAppState'import type { RunOutcome } from '@/lib/coworkRunner'@@ -207,6 +207,9 @@ 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>@@ -284,6 +287,8 @@ 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@@ -325,6 +330,7 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({set((s) => ({ liveTurns: { ...s.liveTurns, [sid]: turns } })),subagents: {},monitors: {},+ workqueue: {},parked: {},runId: {},pendingAsks: {},@@ -541,6 +547,8 @@ 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) => ({@@ -636,6 +644,7 @@ 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 e1c3264d7..b6095b9e9 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -9,6 +9,11 @@ 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', () => ({@@ -21,6 +26,11 @@ 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(),}))@@ -47,9 +57,49 @@ 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', { run_id: 'sub-a-1' })).toContain('running')+ agentRead.mockRejectedValue(new Error('nope'))+ expect(await readAgent('sess-1', {})).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__/coworkWorkqueue.test.ts b/web-app/src/lib/__tests__/coworkWorkqueue.test.tsnew file mode 100644index 000000000..fbea9212d--- /dev/null+++ b/web-app/src/lib/__tests__/coworkWorkqueue.test.ts@@ -0,0 +1,113 @@+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('withholds the mutating tools in plan mode, keeps the read-only pair', () => {+ const normal = workqueueTools(false)+ expect(Object.keys(normal).sort()).toEqual(+ [+ POST_WORK_TOOL,+ CLAIM_WORK_TOOL,+ COMPLETE_WORK_TOOL,+ LIST_WORK_TOOL,+ READ_AGENT_TOOL,+ ].sort()+ )+ const plan = workqueueTools(true)+ expect(plan[POST_WORK_TOOL]).toBeUndefined()+ expect(plan[CLAIM_WORK_TOOL]).toBeUndefined()+ expect(plan[COMPLETE_WORK_TOOL]).toBeUndefined()+ expect(plan[LIST_WORK_TOOL]).toBeDefined()+ expect(plan[READ_AGENT_TOOL]).toBeDefined()+ })++ 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', { 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 94b5f2ff9..122b7898f 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -8,6 +8,11 @@ import {memoryRead,subagentResultReserve,subagentResultFill,+ workPost,+ workClaim,+ workComplete,+ workList,+ agentRead,attachmentImport,startMonitor,stopMonitor,@@ -20,6 +25,8 @@ 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'@@ -439,6 +446,75 @@ 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+ }+}++/** Complete an item `agentId` claimed. */+export async function completeWork(+ 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> {+ try {+ return await workList(sessionId)+ } catch (e) {+ console.warn('[agentTools] Failed to list work:', messageOf(e))+ return null+ }+}++/** Read a peer's status + transcript, or the roster (no `run_id`). */+export async function readAgent(+ sessionId: string,+ args: Record<string, unknown>+): Promise<string> {+ try {+ return await agentRead(sessionId, 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 15ea9e1c5..29c9efa5c 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -16,6 +16,8 @@ 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 {@@ -43,6 +45,12 @@ 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}/**@@ -186,6 +194,13 @@ 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/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex 00a6fadc7..c1ae76348 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -9,6 +9,11 @@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,@@ -26,6 +31,9 @@ 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); read_agent and+ // list_work are read-only and stay available in plan mode.+ ...WORK_MUTATION_NAMES,])/** Named `todo` to match the Rust tool: the plan-mode addendum instructs the@@ -40,6 +48,7 @@ export const CLIENT_TOOL_NAMES = new Set([ASK_TOOL_NAME,TASK_TOOL_NAME,MONITOR_TOOL_NAME,+ ...WORK_TOOL_NAMES,])const todoTool: Tool = {@@ -249,5 +258,8 @@ 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.tsnew file mode 100644index 000000000..f41418e5c--- /dev/null+++ b/web-app/src/lib/coworkWorkqueue.ts@@ -0,0 +1,170 @@+/**+ * 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`/`read_agent`+ * are read-only and stay available. */+export const WORK_MUTATION_NAMES = new Set([+ POST_WORK_TOOL,+ CLAIM_WORK_TOOL,+ COMPLETE_WORK_TOOL,+])++/** Wording ported from `work_tool_schemas` / `read_agent_tool_schema` in Rust;+ * the two surfaces must advertise the same contract. In plan mode only the+ * read-only pair is offered. */+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+ }+ tools[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.',+ inputSchema: jsonSchema({ type: 'object', properties: {} }),+ } as Tool+ tools[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.",+ inputSchema: jsonSchema({+ 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).',+ },+ },+ }),+ } as Tool+ 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, 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/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 80b461b4c..f257a563d 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -668,6 +668,8 @@"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",diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex b288ae5de..b7d780182 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -104,6 +104,7 @@ import {reserveSubagentResult,cancelAgentThreadBash,activeAgentMonitorIds,+ type WorkItemView,} from '@/lib/agentTools'import { monitorLaneFor, type MonitorLane } from '@/lib/coworkMonitor'import { CoworkParkedNotice } from '@/containers/CoworkParkedNotice'@@ -173,6 +174,7 @@ 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. */@@ -399,6 +401,9 @@ 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)@@ -701,6 +706,9 @@ function CoworkPage() {failedReadPaths,webSearch,monitors: monitorLane,+ workAgentId: 'main',+ onWorkQueue: (items) =>+ useCoworkRun.getState().setWorkqueue(sid, items),onTodo: async (input) => {const result = applyTodoOp(useCoworkSessions@@ -810,6 +818,11 @@ function CoworkPage() {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.',@@ -1652,6 +1665,7 @@ function CoworkPage() {<CoworkTasksChipsubagents={subagents}monitors={monitors}+ workqueue={workqueue}open={rail?.kind === 'tasks'}onToggle={() =>setRail((r) =>@@ -1726,6 +1740,7 @@ function CoworkPage() {<CoworkTasksPanelsubagents={subagents}monitors={monitors}+ workqueue={workqueue}onClose={() => setRail(null)}/>)}