Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): subagents report to a file and ping the parent when they finish

Akarshan Biswas27ea07e9edc1
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
index d1acf5749..c6e37055a 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
@@ -17,6 +17,8 @@ const COMMANDS: &[&str] = &[
"memory_delete",
"tool_schemas",
"sandbox_status",
+ "subagent_result_reserve",
+ "subagent_result_fill",
"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.ts
index 45328a64d..58a7c806a 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
@@ -223,6 +223,43 @@ export async function memoryDelete(
})
}
+/** A file claimed in a session scratch for a subagent's answer. */
+export type ReservedResult = {
+ /** The reserved name, to pass back to `subagentResultFill`. */
+ file: string
+ /** The model-visible path the parent agent can `read`. */
+ path: string
+}
+
+/**
+ * Claim a file in `threadId`'s session scratch for a subagent's answer
+ * (`<scratch>/subagents/<id>.md`). Claimed at dispatch, not at completion: the
+ * `task` tool reports where the answer will be while the child is still
+ * working. An existing name is suffixed, never overwritten.
+ */
+export async function subagentResultReserve(
+ threadId: string,
+ id: string
+): Promise<ReservedResult> {
+ return await invoke('plugin:agent-tools|subagent_result_reserve', {
+ threadId,
+ id,
+ })
+}
+
+/** Write a finished subagent's answer into the file reserved for it. */
+export async function subagentResultFill(
+ threadId: string,
+ file: string,
+ content: string
+): Promise<void> {
+ return await invoke('plugin:agent-tools|subagent_result_fill', {
+ threadId,
+ file,
+ content,
+ })
+}
+
/**
* Function schemas for every built-in tool. Callers pick which subset to
* advertise; the schemas are never re-typed in TypeScript.
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
index c834123cd..d886252b8 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
@@ -19,6 +19,8 @@ permissions = [
"allow-memory-delete",
"allow-tool-schemas",
"allow-sandbox-status",
+ "allow-subagent-result-reserve",
+ "allow-subagent-result-fill",
"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.json
index 3712b1ffb..6b2aaa0b8 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
@@ -474,6 +474,30 @@
"const": "deny-skill-write",
"markdownDescription": "Denies the skill_write command without any pre-configured scope."
},
+ {
+ "description": "Enables the subagent_result_fill command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-subagent-result-fill",
+ "markdownDescription": "Enables the subagent_result_fill command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the subagent_result_fill command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-subagent-result-fill",
+ "markdownDescription": "Denies the subagent_result_fill command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the subagent_result_reserve command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-subagent-result-reserve",
+ "markdownDescription": "Enables the subagent_result_reserve command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the subagent_result_reserve command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-subagent-result-reserve",
+ "markdownDescription": "Denies the subagent_result_reserve command without any pre-configured scope."
+ },
{
"description": "Enables the thread_workspace_delete command without any pre-configured scope.",
"type": "string",
@@ -535,10 +559,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-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-execute-tool`\n- `allow-execute-tool-streaming`",
+ "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-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-execute-tool`\n- `allow-execute-tool-streaming`",
"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-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-execute-tool`\n- `allow-execute-tool-streaming`"
+ "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-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-execute-tool`\n- `allow-execute-tool-streaming`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 55325ab37..a2fc0d6a8 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -360,6 +360,72 @@ impl WorkspaceScope {
}
}
+/// A claimed subagent result file: `path` is the model-visible spelling to hand
+/// back to the model, `file` the name to pass to [`subagent_result_fill`] once
+/// the child has an answer.
+#[derive(serde::Serialize)]
+pub struct ReservedResult {
+ pub file: String,
+ pub path: String,
+}
+
+/// Claim a file in the parent session's scratch for a subagent's answer.
+///
+/// Host-side, not a model tool: the Cowork loop runs in the frontend, where the
+/// scratch is only reachable through this plugin. Claimed at dispatch rather
+/// than written at completion because the `task` tool returns the path
+/// immediately -- the parent is told where the answer will be while the child is
+/// still working. The path is the one spelling both the filesystem tools and the
+/// sandboxed shell resolve, so the parent can `read` it back. An existing name
+/// is suffixed, never overwritten.
+#[tauri::command]
+pub async fn subagent_result_reserve(
+ thread_id: String,
+ id: String,
+) -> Result<ReservedResult, AgentToolsError> {
+ let scratch = workspace::ensure_scratch_dir(&thread_id).await?;
+ let reserved = tokio::task::spawn_blocking(move || {
+ crate::tools::spill::reserve_subagent_result(&scratch, &id).map(|p| ReservedResult {
+ file: p
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .into_owned(),
+ path: crate::tools::sandbox::scratch_display_path(Some(&scratch), &p),
+ })
+ })
+ .await
+ .map_err(|e| AgentToolsError::from(format!("subagent result reserve failed: {e}")))?;
+ reserved.ok_or_else(|| {
+ AgentToolsError::from("could not claim a file in the session scratch".to_string())
+ })
+}
+
+/// Write a finished subagent's answer into the file that was reserved for it.
+///
+/// Takes the reserved *name*, not a path: it has crossed to the frontend and
+/// back, so it is re-validated and re-resolved under the session's own scratch
+/// rather than trusted (see `spill::fill_named_subagent_result`).
+#[tauri::command]
+pub async fn subagent_result_fill(
+ thread_id: String,
+ file: String,
+ content: String,
+) -> Result<(), AgentToolsError> {
+ let scratch = workspace::ensure_scratch_dir(&thread_id).await?;
+ let filled = tokio::task::spawn_blocking(move || {
+ crate::tools::spill::fill_named_subagent_result(&scratch, &file, &content)
+ })
+ .await
+ .map_err(|e| AgentToolsError::from(format!("subagent result write failed: {e}")))?;
+ if !filled {
+ return Err(AgentToolsError::from(
+ "could not write the reserved result file".to_string(),
+ ));
+ }
+ Ok(())
+}
+
/// Execute one built-in tool.
///
/// The gate decides, not the caller. `write` and `edit` resolve to `Prompt` and
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
index 6cb74c8f7..98d2bdeb9 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
@@ -51,6 +51,8 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
commands::memory_delete,
commands::tool_schemas,
commands::sandbox_status,
+ commands::subagent_result_reserve,
+ commands::subagent_result_fill,
commands::execute_tool,
commands::execute_tool_streaming
])
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index 31fe39ce7..eaa420239 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -1124,28 +1124,7 @@ fn spill_dir(scratch: Option<&Path>) -> Option<PathBuf> {
let base = scratch
.map(Path::to_path_buf)
.unwrap_or_else(std::env::temp_dir);
- let dir = base.join("jan-bash");
- match std::fs::symlink_metadata(&dir) {
- Ok(meta) if !meta.is_dir() => return None,
- Ok(_) => {}
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
- // create_dir (not create_dir_all) refuses to follow a planted
- // symlink in the path it creates.
- let r = std::fs::create_dir(&dir);
- if let Err(e) = r {
- if e.kind() != std::io::ErrorKind::AlreadyExists {
- return None;
- }
- }
- }
- Err(_) => return None,
- }
- // Re-verify the node is a real directory, not a symlink a concurrent
- // process swapped in between the create and this check.
- match std::fs::symlink_metadata(&dir) {
- Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() => Some(dir),
- _ => None,
- }
+ crate::tools::spill::validated_subdir(&base, "jan-bash")
}
fn new_temp_path(scratch: Option<&Path>) -> Option<PathBuf> {
@@ -1153,16 +1132,11 @@ fn new_temp_path(scratch: Option<&Path>) -> Option<PathBuf> {
Some(spill_dir(scratch)?.join(format!("jan-bash-{}-{}.txt", std::process::id(), n)))
}
-/// Open a spill file atomically with `O_EXCL` so we never truncate or write
-/// through an existing symlink the shell planted: `create_new` fails if the
-/// path already exists (as a file or a symlink). Combined with the validated
-/// non-symlink parent from [`spill_dir`], the model-controlled spill bytes
-/// cannot be redirected onto a host file.
+/// Open a spill file atomically; see [`crate::tools::spill::open_excl`].
+/// Combined with the validated non-symlink parent from [`spill_dir`], the
+/// model-controlled spill bytes cannot be redirected onto a host file.
fn open_spill_file(path: &Path) -> std::io::Result<std::fs::File> {
- std::fs::OpenOptions::new()
- .write(true)
- .create_new(true)
- .open(path)
+ crate::tools::spill::open_excl(path)
}
/// Write `content` to a uniquely named temp file, returning its path on
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.rs
index d64e418aa..9c34aec94 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,7 @@ pub mod proc;
/// kernel-level confinement for spawned commands.
pub mod sandbox;
pub mod schema;
+pub mod spill;
pub mod web;
/// A single OpenAI `image_url` content part: the `data:<mime>;base64,<bytes>`
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.rs
new file mode 100644
index 000000000..75b0d5503
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
@@ -0,0 +1,322 @@
+//! Scratch spill files: host-side writes into the session scratch.
+//!
+//! Two producers share this: truncated `bash` output (`handlers.rs`) and
+//! subagent final answers (the CLI loop's `await_subagent` and the desktop's
+//! `subagent_result_reserve`/`subagent_result_fill` commands). The scratch is
+//! writable by the sandboxed shell, so every path here is symlink-defended: a
+//! redirected subdirectory or a pre-planted file must never route our bytes
+//! onto a host path.
+
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+/// Scratch subdirectory holding subagent result files.
+pub const SUBAGENT_DIR: &str = "subagents";
+
+/// Bytes of a subagent's final answer kept inline in the `task`/`await`
+/// tool result; anything past this lives only in the spill file. Roughly 2K
+/// tokens: enough for any real summary, small enough that a child dumping a
+/// whole file does not flood the parent's context.
+pub const SUBAGENT_INLINE_MAX_BYTES: usize = 8 * 1024;
+
+/// Validate-or-create `base/name` as a real, non-symlink directory.
+///
+/// The shell can write `base`, so it could have redirected `name` at a host
+/// directory. Refuse (returning `None`) rather than write through a redirect.
+/// `create_dir` (not `create_dir_all`) refuses to follow a planted symlink in
+/// the path it creates, and the node is re-verified afterwards in case a
+/// concurrent process swapped it between the create and the check.
+pub fn validated_subdir(base: &Path, name: &str) -> Option<PathBuf> {
+ let dir = base.join(name);
+ match std::fs::symlink_metadata(&dir) {
+ Ok(meta) if !meta.is_dir() => return None,
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ if let Err(e) = std::fs::create_dir(&dir) {
+ if e.kind() != std::io::ErrorKind::AlreadyExists {
+ return None;
+ }
+ }
+ }
+ Err(_) => return None,
+ }
+ match std::fs::symlink_metadata(&dir) {
+ Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() => Some(dir),
+ _ => None,
+ }
+}
+
+/// Open a spill file atomically with `O_EXCL` so we never truncate or write
+/// through an existing symlink the shell planted: `create_new` fails if the
+/// path already exists (as a file or a symlink).
+pub fn open_excl(path: &Path) -> std::io::Result<std::fs::File> {
+ std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(path)
+}
+
+/// A filesystem-safe stem from a caller-supplied id: everything outside
+/// `[A-Za-z0-9._-]` collapses to `-`, leading dots are stripped so the name
+/// can never be a dotfile or a `..` component, and an unusable id falls back
+/// to a generic stem rather than failing the write.
+fn sanitize_stem(id: &str) -> String {
+ let mut stem: String = id
+ .chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
+ c
+ } else {
+ '-'
+ }
+ })
+ .collect();
+ while stem.starts_with('.') {
+ stem.remove(0);
+ }
+ stem.truncate(80);
+ if stem.is_empty() {
+ "result".to_string()
+ } else {
+ stem
+ }
+}
+
+/// Claim `<scratch>/subagents/<id>.md` as an empty file, returning the host path.
+///
+/// Reserving is split from writing because a backgrounded subagent has to name
+/// the file at dispatch -- the parent is told where the answer will land long
+/// before there is an answer -- and the empty file is what stops a later
+/// reservation taking the same name. `create_new` semantics mean an existing
+/// name gets a `-2`, `-3`, ... suffix rather than being overwritten: two
+/// children of one run may share a name, and neither result is the other's to
+/// replace.
+pub fn reserve_subagent_result(scratch: &Path, id: &str) -> Option<PathBuf> {
+ let dir = validated_subdir(scratch, SUBAGENT_DIR)?;
+ let stem = sanitize_stem(id);
+ for n in 1..100 {
+ let name = if n == 1 {
+ format!("{stem}.md")
+ } else {
+ format!("{stem}-{n}.md")
+ };
+ let path = dir.join(name);
+ match open_excl(&path) {
+ Ok(_) => return Some(path),
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(_) => return None,
+ }
+ }
+ None
+}
+
+/// Fill a path [`reserve_subagent_result`] handed out. The shell could have
+/// swapped our empty file for a link in the meantime, so the same fail-closed
+/// re-check applies: write only to a real file, never through a redirect.
+pub fn fill_subagent_result(path: &Path, text: &str) -> bool {
+ match std::fs::symlink_metadata(path) {
+ Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => {}
+ _ => return false,
+ }
+ match open_truncating(path) {
+ Ok(mut file) => file.write_all(text.as_bytes()).is_ok(),
+ Err(_) => false,
+ }
+}
+
+/// `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> {
+ std::fs::OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .create(false)
+ .open(path)
+}
+
+/// Fill a reservation named by file name alone -- the shape a caller outside
+/// this process (the Cowork loop, over the plugin boundary) can hand back.
+///
+/// The name is validated to one safe component and re-resolved under the
+/// scratch's own `subagents/`, so nothing the caller says can aim the write
+/// somewhere else. The directory is re-validated too: [`fill_subagent_result`]
+/// only vouches for the leaf, and a `subagents/` swapped for a link would
+/// otherwise resolve the leaf on the far side of it.
+pub fn fill_named_subagent_result(scratch: &Path, file: &str, text: &str) -> bool {
+ if !is_result_file_name(file) {
+ return false;
+ }
+ match validated_subdir(scratch, SUBAGENT_DIR) {
+ Some(dir) => fill_subagent_result(&dir.join(file), text),
+ None => false,
+ }
+}
+
+/// A name [`reserve_subagent_result`] could have produced: one component, the
+/// `sanitize_stem` charset, and a `.md` tail (which is also what rules out
+/// `.` and `..`).
+fn is_result_file_name(name: &str) -> bool {
+ name.len() <= 128
+ && name.ends_with(".md")
+ && !name.starts_with('.')
+ && name
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
+}
+
+/// The model-facing `task`/`await_subagent` result for a child's final answer.
+///
+/// With no spill file the text passes through unchanged (the unconfined CLI has
+/// no scratch by design). With one, a short answer is returned whole plus a
+/// note naming the file; a long answer keeps its head -- a report leads with
+/// its summary, unlike command output whose errors trail -- and the note says
+/// how to read the rest.
+pub fn compose_subagent_result(text: &str, display_path: Option<&str>) -> String {
+ let Some(path) = display_path else {
+ return text.to_string();
+ };
+ if text.len() <= SUBAGENT_INLINE_MAX_BYTES {
+ return format!("{text}\n\n[full result saved to {path}]");
+ }
+ let mut cut = SUBAGENT_INLINE_MAX_BYTES;
+ while cut > 0 && !text.is_char_boundary(cut) {
+ cut -= 1;
+ }
+ format!(
+ "{}\n\n[result truncated at {cut} of {} bytes; full result saved to {path}. Use the \
+ read tool (with offset/limit) on that path to see the rest]",
+ &text[..cut],
+ text.len(),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tmp(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "jan-spill-test-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ /// The dispatch-time path is the one the answer lands in, and a second
+ /// reservation cannot take it even while it is still empty.
+ #[test]
+ fn a_reserved_path_is_held_until_it_is_filled() {
+ let scratch = tmp("reserve");
+ let a = reserve_subagent_result(&scratch, "sub-a-1").unwrap();
+ let b = reserve_subagent_result(&scratch, "sub-a-1").unwrap();
+ assert_eq!(a, scratch.join("subagents/sub-a-1.md"));
+ assert_eq!(b, scratch.join("subagents/sub-a-1-2.md"));
+ assert_eq!(std::fs::read_to_string(&a).unwrap(), "");
+ assert!(fill_subagent_result(&a, "the answer"));
+ assert_eq!(std::fs::read_to_string(&a).unwrap(), "the answer");
+ // Never recreated: a reservation that vanished is a failure, not an
+ // invitation to write somewhere new.
+ std::fs::remove_file(&b).unwrap();
+ assert!(!fill_subagent_result(&b, "x"));
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn refuses_to_fill_through_a_swapped_link() {
+ let scratch = tmp("swap");
+ let host = tmp("swap-host").join("secret");
+ std::fs::write(&host, "original").unwrap();
+ let path = reserve_subagent_result(&scratch, "sub-a-1").unwrap();
+ std::fs::remove_file(&path).unwrap();
+ std::os::unix::fs::symlink(&host, &path).unwrap();
+ assert!(!fill_subagent_result(&path, "overwritten"));
+ assert_eq!(std::fs::read_to_string(&host).unwrap(), "original");
+ let _ = std::fs::remove_dir_all(&scratch);
+ let _ = std::fs::remove_dir_all(host.parent().unwrap());
+ }
+
+ #[test]
+ fn sanitizes_hostile_ids() {
+ assert_eq!(sanitize_stem("../../etc/passwd"), "-..-etc-passwd");
+ assert_eq!(sanitize_stem("..."), "result");
+ assert_eq!(sanitize_stem(""), "result");
+ let scratch = tmp("hostile");
+ let p = reserve_subagent_result(&scratch, "a/b\\c").unwrap();
+ assert!(p.starts_with(scratch.join(SUBAGENT_DIR)));
+ assert_eq!(p.file_name().unwrap().to_str().unwrap(), "a-b-c.md");
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+
+ /// The file name crosses the plugin boundary and comes back, so it is
+ /// re-validated rather than trusted: only a name a reservation could have
+ /// produced, resolved under the scratch's own directory.
+ #[test]
+ fn a_returned_file_name_cannot_aim_the_write_elsewhere() {
+ let scratch = tmp("named");
+ let reserved = reserve_subagent_result(&scratch, "sub-a-1").unwrap();
+ assert!(fill_named_subagent_result(&scratch, "sub-a-1.md", "answer"));
+ assert_eq!(std::fs::read_to_string(&reserved).unwrap(), "answer");
+
+ for hostile in [
+ "../../etc/passwd",
+ "../sub-a-1.md",
+ "sub-a-1.md/../../x.md",
+ ".hidden.md",
+ "sub-a-1.txt",
+ "",
+ ] {
+ assert!(
+ !fill_named_subagent_result(&scratch, hostile, "x"),
+ "accepted {hostile:?}"
+ );
+ }
+ // A well-formed name that was never reserved is still refused: fill
+ // never creates.
+ assert!(!fill_named_subagent_result(
+ &scratch,
+ "never-reserved.md",
+ "x"
+ ));
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn refuses_a_redirected_subagents_dir() {
+ let scratch = tmp("redirect");
+ let target = tmp("redirect-target");
+ std::os::unix::fs::symlink(&target, scratch.join(SUBAGENT_DIR)).unwrap();
+ assert!(reserve_subagent_result(&scratch, "id").is_none());
+ let _ = std::fs::remove_dir_all(&scratch);
+ let _ = std::fs::remove_dir_all(&target);
+ }
+
+ #[test]
+ fn short_results_stay_whole_with_a_pointer() {
+ let out = compose_subagent_result("the answer", Some("/tmp/subagents/r.md"));
+ assert_eq!(
+ out,
+ "the answer\n\n[full result saved to /tmp/subagents/r.md]"
+ );
+ assert_eq!(compose_subagent_result("plain", None), "plain");
+ }
+
+ #[test]
+ fn long_results_keep_their_head_and_name_the_file() {
+ let text = "x".repeat(SUBAGENT_INLINE_MAX_BYTES + 100);
+ let out = compose_subagent_result(&text, Some("/tmp/subagents/r.md"));
+ assert!(out.starts_with(&"x".repeat(SUBAGENT_INLINE_MAX_BYTES)));
+ assert!(out.contains("truncated at 8192 of 8292 bytes"));
+ assert!(out.contains("full result saved to /tmp/subagents/r.md"));
+ // The head is cut at a char boundary even for multi-byte text.
+ let uni = "é".repeat(SUBAGENT_INLINE_MAX_BYTES);
+ let composed = compose_subagent_result(&uni, Some("p"));
+ assert!(composed.contains("truncated at 8192 of 16384 bytes"));
+ }
+}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index bfc29896a..8846024b7 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -145,6 +145,25 @@ impl ToolOutcome {
#[async_trait]
pub(crate) trait ToolInvoker: Send + Sync {
async fn invoke(&self, tool_calls: &[serde_json::Value]) -> Result<Vec<ToolOutcome>, String>;
+
+ /// Pings raised by work the model started and is no longer blocked on (a
+ /// backgrounded subagent finishing), oldest first. Folded into the
+ /// conversation as `<SYSTEM>` reminders at the top of the next turn.
+ fn background_notices(&self) -> Vec<String> {
+ Vec::new()
+ }
+
+ /// Whether such work is still owed to the model. A cycle that would
+ /// otherwise end waits on this rather than dropping the answer of a child
+ /// that was still running.
+ fn background_pending(&self) -> bool {
+ false
+ }
+
+ /// Park until [`Self::background_notices`] has something, or nothing is
+ /// left to wait for. Only called while `background_pending` holds, so the
+ /// default's immediate return cannot spin.
+ async fn await_background(&self) {}
}
struct HttpModelInvoker {
@@ -510,6 +529,13 @@ impl CompositeToolInvoker {
decision
}
+ /// Where a child's answer is spilled, or `None` when this run is
+ /// unconfined: no scratch is in force, so there is nowhere sanctioned to
+ /// write and the answer is delivered inline instead.
+ fn subagent_scratch(&self) -> Option<&std::path::Path> {
+ self.sandbox.then_some(self.scratch_root.as_path())
+ }
+
/// 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
@@ -519,6 +545,7 @@ impl CompositeToolInvoker {
await_subagent, format_subagent_list, parse_await_args, parse_create_args,
parse_dispatch_args, spawn_subagent, subagent_dir_for, SubagentRegistry, SubagentScope,
};
+ use tauri_plugin_agent_tools::tools::spill::compose_subagent_result;
let Some(ctx) = &self.subagents else {
return "ERROR: subagents are not available in this run".to_string();
};
@@ -542,10 +569,25 @@ impl CompositeToolInvoker {
send_reasoning: ctx.send_reasoning,
},
&self.events,
+ // Unconfined means no scratch: the tools see the real
+ // `/tmp`, so there is nowhere sanctioned to spill.
+ self.subagent_scratch(),
) {
- Ok(run_id) => format!(
- "Subagent started in the background. run_id={run_id}. Continue working, then call await_subagent with this run_id to collect its result."
- ),
+ Ok(d) => match d.display_path {
+ Some(path) => format!(
+ "Subagent started in the background. run_id={}. Its answer will be \
+ written to {path}; you will be told when it lands, so keep working \
+ rather than waiting. Read that file when you need the answer, or \
+ call await_subagent with this run_id to block until it is ready.",
+ d.run_id
+ ),
+ None => format!(
+ "Subagent started in the background. run_id={}. You will be told when \
+ it finishes; keep working, then call await_subagent with this run_id \
+ to collect its result.",
+ d.run_id
+ ),
+ },
Err(e) => format!("ERROR: {e}"),
}
}
@@ -555,10 +597,12 @@ impl CompositeToolInvoker {
Err(e) => return format!("ERROR: {e}"),
};
match await_subagent(&ctx.bg, &run_id).await {
- Ok(text) if text.trim().is_empty() => {
+ Ok(c) if c.text.trim().is_empty() => {
"The subagent finished but produced no text output.".to_string()
}
- Ok(text) => text,
+ // The answer was spilled by the child's own task as it
+ // finished, so this only names the file, never rewrites it.
+ Ok(c) => compose_subagent_result(&c.text, c.display_path.as_deref()),
Err(e) => format!("ERROR: {e}"),
}
}
@@ -816,6 +860,25 @@ fn plan_mode_read_only_msg(name: &str) -> String {
#[async_trait]
impl ToolInvoker for CompositeToolInvoker {
+ fn background_notices(&self) -> Vec<String> {
+ self.subagents
+ .as_ref()
+ .map(|ctx| ctx.bg.take_notices())
+ .unwrap_or_default()
+ }
+
+ fn background_pending(&self) -> bool {
+ self.subagents
+ .as_ref()
+ .is_some_and(|ctx| ctx.bg.has_pending_work())
+ }
+
+ async fn await_background(&self) {
+ if let Some(ctx) = &self.subagents {
+ ctx.bg.wait_for_notice().await;
+ }
+ }
+
async fn invoke(&self, tool_calls: &[serde_json::Value]) -> Result<Vec<ToolOutcome>, String> {
use tauri_plugin_agent_tools::tools::{
gate::{resolve_decision, Decision, PromptKind},
@@ -2184,6 +2247,20 @@ async fn run_turn_cycle(
log::warn!("agent: dropped {poisoned} malformed tool call(s) from the live context");
}
+ // Background work that finished since the last request reaches the model
+ // here, as a `<SYSTEM>` reminder rather than an invented tool result:
+ // nothing was called this turn. Several pings fold into one user
+ // message, since `attach` appends to a trailing user turn.
+ let notices = tools.background_notices();
+ if !notices.is_empty() {
+ for notice in &notices {
+ crate::core::agent::reminder::attach(&mut conversation_messages, notice);
+ }
+ let _ = events.send(StreamEvent::MessagesUpdated {
+ messages: conversation_messages.clone(),
+ });
+ }
+
// On a context-overflow error, compact the conversation and retry.
// Compaction runs progressively (a smaller kept tail each attempt) and
// the loop gives up if a pass fails to shrink the message list.
@@ -2319,6 +2396,28 @@ async fn run_turn_cycle(
continue;
}
}
+ // The model has nothing left to do, but a subagent it dispatched is
+ // still running -- and its answer has nowhere to go once this cycle
+ // returns. So park here instead of ending: the ping drained at the
+ // top of the next turn is what resumes the conversation. The turn
+ // the model just took has to be recorded first, exactly as the
+ // closeout nudge above records it, or the reminder would attach to
+ // a conversation missing the answer it follows.
+ if tools.background_pending() {
+ tools.await_background().await;
+ // Re-checked rather than assumed: the wait also returns when
+ // there is nothing left to wait for (a cancelled run drops its
+ // queued pings), and resuming on that would spend a turn asking
+ // the model to react to nothing.
+ if tools.background_pending() {
+ conversation_messages.push(serde_json::json!({
+ "role": "assistant",
+ "content": final_text,
+ }));
+ turn += 1;
+ continue;
+ }
+ }
// Every turn is finished and the run passed its token ceiling, so
// the conversation is both complete and oversized. Compact it here,
// while nothing is waiting on the result: the ceiling no longer
@@ -3689,6 +3788,145 @@ mod tests {
);
}
+ /// A tool invoker with background work outstanding, standing in for a run
+ /// that dispatched subagents. Each `await_background` releases one queued
+ /// ping, so a test controls exactly how many times the cycle is resumed.
+ struct BackgroundTool {
+ pending: StdMutex<VecDeque<Vec<String>>>,
+ ready: StdMutex<Vec<String>>,
+ }
+ impl BackgroundTool {
+ fn new(rounds: Vec<Vec<String>>) -> Self {
+ Self {
+ pending: StdMutex::new(rounds.into_iter().collect()),
+ ready: StdMutex::new(Vec::new()),
+ }
+ }
+ }
+ #[async_trait]
+ impl ToolInvoker for BackgroundTool {
+ async fn invoke(
+ &self,
+ _tool_calls: &[serde_json::Value],
+ ) -> Result<Vec<ToolOutcome>, String> {
+ Ok(Vec::new())
+ }
+ fn background_notices(&self) -> Vec<String> {
+ std::mem::take(&mut *self.ready.lock().unwrap())
+ }
+ fn background_pending(&self) -> bool {
+ !self.ready.lock().unwrap().is_empty() || !self.pending.lock().unwrap().is_empty()
+ }
+ async fn await_background(&self) {
+ if let Some(round) = self.pending.lock().unwrap().pop_front() {
+ *self.ready.lock().unwrap() = round;
+ }
+ }
+ }
+
+ fn final_answer(text: &str) -> serde_json::Value {
+ json!({ "choices": [{ "message": { "content": text }, "finish_reason": "stop" }] })
+ }
+
+ /// The model stopping is not the end of the run while a child it dispatched
+ /// is still going: its answer would have nowhere to land. The cycle parks,
+ /// then resumes on the ping -- as a `<SYSTEM>`-marked user turn, since no
+ /// tool was called and there is no tool result to attach it to.
+ #[tokio::test]
+ async fn a_finished_subagent_resumes_a_cycle_that_would_have_ended() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let model = MockModel::new(vec![
+ final_answer("dispatched, waiting"),
+ final_answer("here is what it found"),
+ ]);
+ let tool = BackgroundTool::new(vec![vec!["Subagent 'researcher' finished".to_string()]]);
+ let mut budget = SessionBudget::new(None);
+
+ let result = run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ vec![json!({ "role": "user", "content": "look into it" })],
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result["choices"][0]["message"]["content"], "here is what it found",
+ "the run continued past the first answer"
+ );
+ let requests = model.requests.lock().unwrap();
+ assert_eq!(requests.len(), 2, "the ping cost exactly one more turn");
+ let sent = requests[1]["messages"].as_array().unwrap();
+ let last = sent.last().unwrap();
+ assert_eq!(last["role"], "user");
+ assert!(
+ crate::core::agent::reminder::is_reminder_only(&last["content"]),
+ "the ping is marked, so rewind and recall skip it: {last}"
+ );
+ assert!(last["content"]
+ .as_str()
+ .unwrap()
+ .contains("Subagent 'researcher' finished"));
+ // The turn the model just took has to be in the history the ping
+ // follows, or it reads as a reply to the previous user message.
+ assert_eq!(sent[sent.len() - 2]["content"], "dispatched, waiting");
+ }
+
+ /// Two children landing together produce one user turn, not two: `attach`
+ /// folds into a trailing user message, and consecutive user messages are
+ /// rejected outright by some providers.
+ #[tokio::test]
+ async fn pings_arriving_together_are_fused_into_one_turn() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let model = MockModel::new(vec![final_answer("waiting"), final_answer("done")]);
+ let tool = BackgroundTool::new(vec![vec![
+ "Subagent 'alpha' finished".to_string(),
+ "Subagent 'beta' finished".to_string(),
+ ]]);
+ let mut budget = SessionBudget::new(None);
+
+ run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ vec![json!({ "role": "user", "content": "go" })],
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let requests = model.requests.lock().unwrap();
+ let sent = requests[1]["messages"].as_array().unwrap();
+ let pings: Vec<&serde_json::Value> = sent
+ .iter()
+ .filter(|m| {
+ m["role"] == "user" && crate::core::agent::reminder::is_reminder_only(&m["content"])
+ })
+ .collect();
+ assert_eq!(pings.len(), 1, "one turn carries both: {sent:?}");
+ let text = pings[0]["content"].as_str().unwrap();
+ assert!(
+ text.contains("'alpha'") && text.contains("'beta'"),
+ "{text}"
+ );
+ }
+
struct FixedTool {
content: String,
}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index e4eba4f30..95768b0ef 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -10,6 +10,8 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use tauri_plugin_agent_tools::permissions::ToolPermissions;
+use tauri_plugin_agent_tools::tools::sandbox::scratch_display_path;
+use tauri_plugin_agent_tools::tools::spill::{fill_subagent_result, reserve_subagent_result};
use tauri_plugin_agent_tools::workspace;
/// Directory name holding `<name>.toml` definitions, under both a project's
@@ -604,6 +606,32 @@ struct BackgroundEntry {
run_id: String,
name: String,
events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
+ /// Model-visible path this child's answer is written to, reserved at
+ /// dispatch so the parent is told where to look before there is an answer.
+ /// `None` with no scratch in force (the unconfined CLI, by design).
+ display_path: Option<String>,
+ /// Set by the child's own task the moment it finishes, so teardown can tell
+ /// a run that ended on its own from one it is aborting. Without it every
+ /// uncollected-but-finished child got a second `SubagentEnd` at teardown --
+ /// which used to be rare and, now that collection is optional, would be the
+ /// common case.
+ finished: Arc<std::sync::atomic::AtomicBool>,
+}
+
+/// A finished child the parent has not been told about yet: the `<SYSTEM>` ping
+/// text, plus the run it belongs to so an explicit `await_subagent` can drop it
+/// rather than reporting the same completion twice.
+struct Notice {
+ run_id: String,
+ text: String,
+}
+
+/// What an `await_subagent` collects: the child's final text plus the file its
+/// full answer was already written to (the same path `dispatch_subagent`
+/// reported), so collecting never writes a second copy.
+pub(crate) struct Collected {
+ pub(crate) text: String,
+ pub(crate) display_path: Option<String>,
}
/// Registry of a single parent run's background subagents, keyed by `run_id`.
@@ -622,6 +650,16 @@ pub(crate) struct BackgroundSubagents {
/// Used to report each queued child's 1-based position; decremented by the
/// task itself the moment it acquires its permit.
queued: std::sync::atomic::AtomicUsize,
+ /// Completions the parent has not been pinged about yet. Drained into the
+ /// 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,
+ /// 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,
}
/// Default cap on concurrently *running* subagents per parent run when
@@ -643,8 +681,59 @@ impl BackgroundSubagents {
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(),
+ running: std::sync::atomic::AtomicUsize::new(0),
}
}
+
+ /// Take every queued completion ping, oldest first.
+ pub(crate) fn take_notices(&self) -> Vec<String> {
+ std::mem::take(&mut *self.notices.lock().unwrap())
+ .into_iter()
+ .map(|n| n.text)
+ .collect()
+ }
+
+ /// Whether anything could still ping the parent: a child still running, or
+ /// one that finished and whose ping has not been delivered.
+ pub(crate) fn has_pending_work(&self) -> bool {
+ !self.notices.lock().unwrap().is_empty()
+ || self.running.load(std::sync::atomic::Ordering::SeqCst) > 0
+ }
+
+ /// Park until a ping is available, or until nothing is left to wait for.
+ ///
+ /// The waiter is registered *before* the state is re-read (`enable`), so a
+ /// child finishing in between wakes this call rather than being missed --
+ /// `notify_waiters` only reaches waiters already registered.
+ pub(crate) async fn wait_for_notice(&self) {
+ loop {
+ let waiter = self.wake.notified();
+ tokio::pin!(waiter);
+ waiter.as_mut().enable();
+ if !self.notices.lock().unwrap().is_empty()
+ || self.running.load(std::sync::atomic::Ordering::SeqCst) == 0
+ {
+ return;
+ }
+ waiter.await;
+ }
+ }
+
+ fn push_notice(&self, run_id: &str, text: String) {
+ self.notices.lock().unwrap().push(Notice {
+ run_id: run_id.to_string(),
+ text,
+ });
+ self.wake.notify_waiters();
+ }
+
+ /// Drop a queued ping for a run the parent collected explicitly: it already
+ /// has the answer, and telling it again would spend context on nothing.
+ fn drop_notice(&self, run_id: &str) {
+ self.notices.lock().unwrap().retain(|n| n.run_id != run_id);
+ }
/// Abort and forget every registered child. Called on parent teardown when
/// the run is cancelled. Emits a closing `SubagentEnd` for each aborted
/// child (its own task is cancelled inside its await and never reaches its
@@ -654,11 +743,17 @@ impl BackgroundSubagents {
let mut guard = self.inner.lock().unwrap();
for (_, entry) in guard.drain() {
entry.abort.abort();
+ // A child that ran to completion already emitted its own end event;
+ // this is only closing the bracket for one cut off mid-run.
+ if entry.finished.load(std::sync::atomic::Ordering::SeqCst) {
+ continue;
+ }
let _ = entry.events.send(StreamEvent::SubagentEnd {
run_id: entry.run_id,
name: entry.name,
});
}
+ self.notices.lock().unwrap().clear();
}
/// Wait for every still-registered child to finish on its own, rather than
@@ -804,13 +899,19 @@ async fn run_subagent(
/// until a running child finishes. A queued dispatch still returns its `run_id`
/// right away, and `await_subagent` on a queued run blocks until it gets a slot
/// and runs to completion -- never errors, never starts out of turn.
+///
+/// `scratch` is where the child's answer is spilled. The file is reserved here,
+/// before the child has produced a word, so the dispatch can report the path the
+/// parent will read it from; the child's own task fills it in and queues the
+/// `<SYSTEM>` ping that tells the parent it is there.
pub(crate) fn spawn_subagent(
bg: &Arc<BackgroundSubagents>,
parent_args: &crate::core::agent::r#loop::OrchestrationArgs,
req: SubagentRequest,
parent: &ParentRun,
events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
-) -> Result<String, SubagentError> {
+ scratch: Option<&Path>,
+) -> Result<Dispatched, SubagentError> {
use crate::core::agent::events::StreamEvent;
use std::sync::atomic::Ordering;
@@ -829,6 +930,10 @@ pub(crate) fn spawn_subagent(
let name = resolved.definition.name.clone();
let run_id = next_subagent_run_id(&name);
let (tx, rx) = tokio::sync::oneshot::channel();
+ let result_file = scratch.and_then(|s| {
+ reserve_subagent_result(s, &run_id).map(|path| (scratch_display_path(Some(s), &path), path))
+ });
+ let display_path = result_file.as_ref().map(|(display, _)| display.clone());
// Try to grab a permit at dispatch time. On success the child is admitted
// immediately; on exhaustion it joins the semaphore waitlist (FIFO) and is
@@ -857,7 +962,12 @@ pub(crate) fn spawn_subagent(
let inherited = parent.clone();
let description = req.description.clone();
let run_id_task = run_id.clone();
- let queued_counter = bg.clone();
+ let name_task = name.clone();
+ let registry = bg.clone();
+ let finished = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let finished_task = finished.clone();
+ let notice_path = display_path.clone();
+ registry.running.fetch_add(1, Ordering::SeqCst);
let handle = tokio::spawn(async move {
let permit = match admitted {
Ok(p) => p,
@@ -866,7 +976,7 @@ pub(crate) fn spawn_subagent(
.acquire_owned()
.await
.expect("subagent semaphore is never closed");
- queued_counter.queued.fetch_sub(1, Ordering::SeqCst);
+ registry.queued.fetch_sub(1, Ordering::SeqCst);
p
}
};
@@ -877,9 +987,21 @@ pub(crate) fn spawn_subagent(
description,
inherited,
task_events,
- run_id_task,
+ run_id_task.clone(),
)
.await;
+ if let Some((_, path)) = &result_file {
+ fill_subagent_result(path, &spilled_text(&result));
+ }
+ finished_task.store(true, Ordering::SeqCst);
+ // Queue the ping before releasing the run count, so a parent asking
+ // "is anything still owed to me?" can never see neither.
+ registry.push_notice(
+ &run_id_task,
+ completion_notice(&name_task, &run_id_task, notice_path.as_deref(), &result),
+ );
+ registry.running.fetch_sub(1, Ordering::SeqCst);
+ registry.wake.notify_waiters();
let _ = tx.send(result);
});
@@ -891,9 +1013,51 @@ pub(crate) fn spawn_subagent(
run_id: run_id.clone(),
name,
events: entry_events,
+ display_path: display_path.clone(),
+ finished,
},
);
- Ok(run_id)
+ Ok(Dispatched {
+ run_id,
+ display_path,
+ })
+}
+
+/// What goes in the spill file. A failed child writes its failure there rather
+/// than leaving the reserved file empty: the parent was told to read that path,
+/// and an empty file reads as "the child had nothing to say".
+fn spilled_text(result: &Result<String, SubagentError>) -> String {
+ match result {
+ Ok(text) => text.clone(),
+ Err(e) => format!("ERROR: {e}"),
+ }
+}
+
+/// The `<SYSTEM>` ping delivered to the parent when a child finishes.
+fn completion_notice(
+ name: &str,
+ run_id: &str,
+ display_path: Option<&str>,
+ result: &Result<String, SubagentError>,
+) -> String {
+ match (result, display_path) {
+ (Err(e), _) => format!("Subagent '{name}' ({run_id}) failed: {e}"),
+ (Ok(_), Some(path)) => format!(
+ "Subagent '{name}' ({run_id}) finished. Its full answer is in {path} -- read that file \
+ when you need it. Do not call await_subagent for this run."
+ ),
+ (Ok(_), None) => format!(
+ "Subagent '{name}' ({run_id}) finished. Call await_subagent with that run_id to read \
+ its answer."
+ ),
+ }
+}
+
+/// What a dispatch reports back: the id to await on, and the file the answer
+/// will be in when the child is done.
+pub(crate) struct Dispatched {
+ pub(crate) run_id: String,
+ pub(crate) display_path: Option<String>,
}
/// Block until the background subagent `run_id` finishes and return its final
@@ -902,17 +1066,18 @@ pub(crate) fn spawn_subagent(
pub(crate) async fn await_subagent(
bg: &Arc<BackgroundSubagents>,
run_id: &str,
-) -> Result<String, SubagentError> {
- let rx = {
+) -> Result<Collected, SubagentError> {
+ let taken = {
let mut guard = bg.inner.lock().unwrap();
- match guard.get_mut(run_id).and_then(|e| e.result.take()) {
- Some(rx) => rx,
- None => {
- return Err(SubagentError::Upstream(format!(
- "unknown or already-collected subagent run '{run_id}'"
- )))
- }
- }
+ guard.get_mut(run_id).and_then(|e| {
+ let rx = e.result.take()?;
+ Some((rx, e.display_path.clone()))
+ })
+ };
+ let Some((rx, display_path)) = taken else {
+ return Err(SubagentError::Upstream(format!(
+ "unknown or already-collected subagent run '{run_id}'"
+ )));
};
// Keep the entry (and its abort handle) in the registry while awaiting, so a
// parent cancellation mid-await can still reach this child via `abort_all`.
@@ -920,7 +1085,9 @@ pub(crate) async fn await_subagent(
// now-spent entry once the await resolves (a no-op if teardown drained it).
let outcome = rx.await.unwrap_or(Err(SubagentError::Cancelled));
bg.inner.lock().unwrap().remove(run_id);
- outcome
+ // Collected explicitly, so the queued ping for this run is redundant.
+ bg.drop_notice(run_id);
+ outcome.map(|text| Collected { text, display_path })
}
/// The model-callable subagent tools, handled by the loop's tool invoker ahead
@@ -966,7 +1133,7 @@ pub fn subagent_tool_schemas(
names
};
let one_off = " For a one-off subagent, pass system_prompt inline (with a descriptive subagent_name); use create_subagent only to save a reusable definition.";
- let bg = format!(" Runs in the BACKGROUND and returns a run_id immediately; keep working, dispatch more, then call await_subagent(run_id) to collect each result. Up to {max_parallel} run concurrently (max_parallel_subagents in agent.toml); dispatches beyond that are queued FIFO and start as running ones finish.");
+ let bg = format!(" Runs in the BACKGROUND and returns immediately with a run_id and the file its answer will be written to; keep working, dispatch more, and a note tells you the moment each one finishes. Awaiting is optional: call await_subagent(run_id) only to block until a specific child is done. Up to {max_parallel} run concurrently (max_parallel_subagents in agent.toml); dispatches beyond that are queued FIFO and start as running ones finish.");
let dispatch_desc = if available.is_empty() {
format!("Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools.{bg}{one_off} No saved subagents yet.")
} else {
@@ -1001,7 +1168,7 @@ pub fn subagent_tool_schemas(
"type": "function",
"function": {
"name": "await_subagent",
- "description": "Block until a backgrounded subagent (started by dispatch_subagent) finishes, and return its final answer. Pass the run_id that dispatch_subagent returned. Each run_id can be awaited once.",
+ "description": "Block until a backgrounded subagent (started by dispatch_subagent) finishes, and return its final answer. Only worth calling when you have nothing else to do: you are notified as each child finishes, and its answer is on disk either way. Pass the run_id that dispatch_subagent returned. Each run_id can be awaited once.",
"parameters": {
"type": "object",
"properties": {
@@ -1164,6 +1331,27 @@ mod tests {
std::fs::write(dir.join(format!("{name}.toml")), body).unwrap();
}
+ /// The ping is what the parent gets when it never awaits, so it has to name
+ /// the file -- and say plainly that awaiting is not the way to read it.
+ #[test]
+ fn the_completion_ping_names_the_reserved_file() {
+ let ok = Ok("the findings".to_string());
+ let note = completion_notice("researcher", "sub-researcher-1", Some("/tmp/x.md"), &ok);
+ assert!(note.contains("/tmp/x.md"), "{note}");
+ assert!(note.contains("Do not call await_subagent"), "{note}");
+
+ // Unconfined: no file, so collecting is the only way to read it.
+ let note = completion_notice("researcher", "sub-researcher-1", None, &ok);
+ assert!(note.contains("await_subagent"), "{note}");
+
+ let failed = Err(SubagentError::Upstream("upstream refused".to_string()));
+ let note = completion_notice("researcher", "sub-researcher-1", Some("/tmp/x.md"), &failed);
+ assert!(note.contains("failed: "), "{note}");
+ // A failure is written to the reserved file too: the parent was told to
+ // read that path, and an empty file reads as an empty answer.
+ assert!(spilled_text(&failed).starts_with("ERROR: "));
+ }
+
#[test]
fn empty_directories_yield_empty_registry() {
let root = unique_root("empty");
@@ -1669,6 +1857,24 @@ mod tests {
// ── background registry (spawn/await/abort) ─────────────────────────────
+ /// A registry entry for the run these tests all call "r1", standing in for
+ /// one `spawn_subagent` would have built.
+ fn test_entry(
+ rx: tokio::sync::oneshot::Receiver<Result<String, SubagentError>>,
+ abort: tokio::task::AbortHandle,
+ events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
+ ) -> BackgroundEntry {
+ BackgroundEntry {
+ result: Some(rx),
+ abort,
+ run_id: "r1".to_string(),
+ name: "reviewer".to_string(),
+ events,
+ display_path: None,
+ finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ }
+ }
+
#[tokio::test]
async fn await_unknown_run_errors() {
let bg = Arc::new(BackgroundSubagents::default());
@@ -1683,16 +1889,10 @@ mod tests {
let (ev_tx, _ev_rx) = tokio::sync::mpsc::unbounded_channel();
bg.inner.lock().unwrap().insert(
"r1".to_string(),
- BackgroundEntry {
- result: Some(rx),
- abort: handle.abort_handle(),
- run_id: "r1".to_string(),
- name: "reviewer".to_string(),
- events: ev_tx,
- },
+ test_entry(rx, handle.abort_handle(), ev_tx),
);
tx.send(Ok("done".to_string())).unwrap();
- assert_eq!(await_subagent(&bg, "r1").await.unwrap(), "done");
+ assert_eq!(await_subagent(&bg, "r1").await.unwrap().text, "done");
assert!(await_subagent(&bg, "r1").await.is_err(), "run is consumed");
handle.abort();
}
@@ -1705,13 +1905,7 @@ mod tests {
let (ev_tx, mut ev_rx) = tokio::sync::mpsc::unbounded_channel();
bg.inner.lock().unwrap().insert(
"r1".to_string(),
- BackgroundEntry {
- result: Some(rx),
- abort: handle.abort_handle(),
- run_id: "r1".to_string(),
- name: "reviewer".to_string(),
- events: ev_tx,
- },
+ test_entry(rx, handle.abort_handle(), ev_tx),
);
let guard = AbortOnDrop(bg.clone());
drop(guard);
@@ -1738,13 +1932,7 @@ mod tests {
let (ev_tx, _ev_rx) = tokio::sync::mpsc::unbounded_channel();
bg.inner.lock().unwrap().insert(
"r1".to_string(),
- BackgroundEntry {
- result: Some(rx),
- abort: handle.abort_handle(),
- run_id: "r1".to_string(),
- name: "reviewer".to_string(),
- events: ev_tx,
- },
+ test_entry(rx, handle.abort_handle(), ev_tx),
);
let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>();
@@ -1775,13 +1963,7 @@ mod tests {
let (ev_tx, _ev_rx) = tokio::sync::mpsc::unbounded_channel();
bg.inner.lock().unwrap().insert(
"r1".to_string(),
- BackgroundEntry {
- result: Some(rx),
- abort: handle.abort_handle(),
- run_id: "r1".to_string(),
- name: "reviewer".to_string(),
- events: ev_tx,
- },
+ test_entry(rx, handle.abort_handle(), ev_tx),
);
bg.join_all().await;
assert!(bg.inner.lock().unwrap().is_empty(), "join_all drains the map");
@@ -1804,13 +1986,7 @@ mod tests {
let (ev_tx, _ev_rx) = tokio::sync::mpsc::unbounded_channel();
bg.inner.lock().unwrap().insert(
"r1".to_string(),
- BackgroundEntry {
- result: Some(rx),
- abort: handle.abort_handle(),
- run_id: "r1".to_string(),
- name: "reviewer".to_string(),
- events: ev_tx,
- },
+ test_entry(rx, handle.abort_handle(), ev_tx),
);
let bg_await = bg.clone();
@@ -1870,6 +2046,19 @@ mod tests {
}
}
+ /// One queue-test dispatch, with no scratch: these assert admission order,
+ /// not spilling, and a child that fails fast has nothing to write anyway.
+ #[cfg(feature = "cli")]
+ fn dispatch_reviewer(
+ bg: &Arc<BackgroundSubagents>,
+ args: &crate::core::agent::r#loop::OrchestrationArgs,
+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
+ ) -> String {
+ spawn_subagent(bg, args, req("reviewer", None), &parent_run(), events, None)
+ .unwrap()
+ .run_id
+ }
+
#[test]
fn subagent_cap_is_clamped_to_at_least_one() {
let bg = BackgroundSubagents::new(0);
@@ -1935,9 +2124,9 @@ mod tests {
let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();
let mut starts = Vec::new();
- let r1 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
- let r2 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
- let r3 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r1 = dispatch_reviewer(&bg, &args, &events_tx);
+ let r2 = dispatch_reviewer(&bg, &args, &events_tx);
+ let r3 = dispatch_reviewer(&bg, &args, &events_tx);
assert_ne!(r1, r2);
assert_ne!(r2, r3);
@@ -1990,8 +2179,8 @@ mod tests {
// Occupy the only slot BEFORE dispatching, so every dispatch queues and
// the await below is deterministic: nothing can start while held.
let _running = bg.semaphore.clone().try_acquire_owned().unwrap();
- let r1 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
- let r2 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let r1 = dispatch_reviewer(&bg, &args, &events_tx);
+ let r2 = dispatch_reviewer(&bg, &args, &events_tx);
// r2 is queued (not started), and awaiting it must NOT start it: the
// slot is still held, so the await parks. Assert via the events: no
@@ -2032,9 +2221,9 @@ mod tests {
// Hold the slot before dispatching so r1, r2, r3 all queue (parked on
// the semaphore) -- the interesting teardown case.
let _running = bg.semaphore.clone().try_acquire_owned().unwrap();
- let _r1 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
- let r2 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
- let r3 = spawn_subagent(&bg, &args, req("reviewer", None), &parent_run(), &events_tx).unwrap();
+ let _r1 = dispatch_reviewer(&bg, &args, &events_tx);
+ let r2 = dispatch_reviewer(&bg, &args, &events_tx);
+ let r3 = dispatch_reviewer(&bg, &args, &events_tx);
AbortOnDrop(bg.clone()); // teardown with queued children parked
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
index ea9fe9f31..66393cc50 100644
--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
@@ -56,6 +56,33 @@ describe('useCoworkSessions', () => {
expect(s.messages.map((m) => m.id)).toEqual(['m1', 'm2', 'm3'])
})
+ /// A subagent ping is a user message with no transcript row, so counting it
+ /// as the question would cut the two histories at different points and
+ /// resume the run from a note about a subagent.
+ it('rewinds past a subagent ping to the real question', () => {
+ const id = useCoworkSessions.getState().createSession()
+ const turns: CoworkTurn[] = [
+ { role: 'user', content: 'second' },
+ { role: 'assistant', content: 'answer' },
+ ]
+ const msgs = [
+ { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'second' }] },
+ { id: 'm2', role: 'assistant', parts: [] },
+ {
+ id: 'ping-2',
+ role: 'user',
+ parts: [{ type: 'text', text: '<SYSTEM>\nalpha done\n</SYSTEM>' }],
+ },
+ { id: 'm3', role: 'assistant', parts: [] },
+ ] as never
+ useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
+ useCoworkSessions.getState().rewindToLastUser(id)
+
+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.turns.map((t) => t.content)).toEqual(['second'])
+ expect(s.messages.map((m) => m.id)).toEqual(['m1'])
+ })
+
// Rewinding a session that has never had a turn would otherwise empty it.
it('leaves a session with no user turn alone', () => {
const id = useCoworkSessions.getState().createSession()
diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.ts
index 33a2c351b..2af358956 100644
--- a/web-app/src/hooks/useCoworkSessions.ts
+++ b/web-app/src/hooks/useCoworkSessions.ts
@@ -4,6 +4,7 @@ import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
import { backendStorage } from '@/lib/backendStorage'
import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
+import { isPingOnly } from '@/lib/coworkPing'
import type {
CoworkTurn,
SubagentRun,
@@ -211,9 +212,15 @@ export const useCoworkSessions = create<CoworkSessionsState>()(
set((s) => ({
sessions: s.sessions.map((x) => {
if (x.id !== id) return x
- const lastIndexOfUser = (roles: { role: string }[]) => {
+ // A `<SYSTEM>` ping is a user *message* but never a user *turn*:
+ // the transcript has no row for it, so counting it here would cut
+ // the two histories at different points and resume the run from a
+ // note about a subagent instead of from the question.
+ const lastIndexOfUser = (
+ roles: { role: string; parts?: unknown }[]
+ ) => {
for (let i = roles.length - 1; i >= 0; i--) {
- if (roles[i].role === 'user') return i
+ if (roles[i].role === 'user' && !isPingOnly(roles[i])) return i
}
return -1
}
diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.ts
index 512c620d8..7b998934b 100644
--- a/web-app/src/lib/__tests__/agentTools.test.ts
+++ b/web-app/src/lib/__tests__/agentTools.test.ts
@@ -7,6 +7,8 @@ const threadWorkspaceSweep = vi.fn()
const sandboxStatus = vi.fn()
const memoryCatalog = vi.fn()
const memoryRead = vi.fn()
+const subagentResultReserve = vi.fn()
+const subagentResultFill = vi.fn()
const getJanDataFolder = vi.fn()
vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({
@@ -17,6 +19,8 @@ vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({
sandboxStatus: () => sandboxStatus(),
memoryCatalog: (...args: unknown[]) => memoryCatalog(...args),
memoryRead: (...args: unknown[]) => memoryRead(...args),
+ subagentResultReserve: (...args: unknown[]) => subagentResultReserve(...args),
+ subagentResultFill: (...args: unknown[]) => subagentResultFill(...args),
}))
vi.mock('@/hooks/useServiceHub', () => ({
@@ -40,6 +44,8 @@ describe('agentTools', () => {
.mockResolvedValue({ backend: 'bubblewrap', enforces: true })
memoryCatalog.mockReset().mockResolvedValue([])
memoryRead.mockReset().mockResolvedValue('')
+ subagentResultReserve.mockReset()
+ subagentResultFill.mockReset()
getJanDataFolder.mockReset().mockResolvedValue('/data')
})
@@ -400,4 +406,44 @@ describe('agentTools', () => {
const { sweepThreadWorkspaces } = await import('../agentTools')
await expect(sweepThreadWorkspaces(['a'])).resolves.toBe(0)
})
+
+ it('claims a result file and reports the model-visible path', async () => {
+ subagentResultReserve.mockResolvedValue({
+ file: 'researcher-c1.md',
+ path: '/tmp/subagents/researcher-c1.md',
+ })
+ const { reserveSubagentResult } = await import('../agentTools')
+ await expect(
+ reserveSubagentResult('sess-1', 'researcher-c1')
+ ).resolves.toEqual({
+ file: 'researcher-c1.md',
+ path: '/tmp/subagents/researcher-c1.md',
+ })
+ expect(subagentResultReserve).toHaveBeenCalledWith('sess-1', 'researcher-c1')
+ })
+
+ it('fills the claimed file by name', async () => {
+ subagentResultFill.mockResolvedValue(undefined)
+ const { fillSubagentResult } = await import('../agentTools')
+ await expect(
+ fillSubagentResult('sess-1', 'researcher-c1.md', 'findings')
+ ).resolves.toBe(true)
+ expect(subagentResultFill).toHaveBeenCalledWith(
+ 'sess-1',
+ 'researcher-c1.md',
+ 'findings'
+ )
+ })
+
+ /// A value, not a throw: the caller falls back to delivering the answer
+ /// inline, which is what a web build with no scratch has to do anyway.
+ it('reports failure rather than throwing when there is no scratch', async () => {
+ subagentResultReserve.mockRejectedValue(new Error('no scratch'))
+ subagentResultFill.mockRejectedValue(new Error('no scratch'))
+ const { reserveSubagentResult, fillSubagentResult } = await import(
+ '../agentTools'
+ )
+ await expect(reserveSubagentResult('s', 'id')).resolves.toBeNull()
+ await expect(fillSubagentResult('s', 'id.md', 'x')).resolves.toBe(false)
+ })
})
diff --git a/web-app/src/lib/__tests__/agentWorkspace.test.ts b/web-app/src/lib/__tests__/agentWorkspace.test.ts
index a83f6e612..033541713 100644
--- a/web-app/src/lib/__tests__/agentWorkspace.test.ts
+++ b/web-app/src/lib/__tests__/agentWorkspace.test.ts
@@ -14,6 +14,8 @@ const api = {
// imports from this module must exist on the mock even though these tests
// never call them.
memoryCatalog: vi.fn(),
+ subagentResultReserve: vi.fn(),
+ subagentResultFill: vi.fn(),
toolSchemas: vi.fn(),
executeTool: vi.fn(),
sandboxStatus: vi.fn(),
diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.ts
index b149334d6..4ee4f4dce 100644
--- a/web-app/src/lib/__tests__/coworkRunner.test.ts
+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts
@@ -117,6 +117,90 @@ describe('runTurn', () => {
expect(d.sendStep).toHaveBeenCalledTimes(1)
})
+ /// A dispatched subagent outlives its tool call, so the answer arrives after
+ /// the model has already stopped. Ending there would drop it.
+ it('parks instead of finishing while a subagent is still running', async () => {
+ const d = deps([textStep('dispatched'), textStep('and here it is')])
+ const queue: string[] = []
+ let running = 1
+ let waits = 0
+ const out = await runTurn({
+ messages: [user('go')],
+ signal: new AbortController().signal,
+ deps: {
+ ...d,
+ inbox: {
+ take: () => queue.splice(0, queue.length),
+ pending: () => queue.length > 0 || running > 0,
+ // Standing in for the child finishing while the parent is parked.
+ wait: async () => {
+ waits += 1
+ queue.push("Subagent 'researcher' finished")
+ running -= 1
+ },
+ },
+ },
+ })
+ expect(out.stoppedBy).toBe('done')
+ expect(waits).toBe(1)
+ expect(d.sendStep).toHaveBeenCalledTimes(2)
+ // The second request carries the ping as a marked user turn, after the
+ // answer the model had already given.
+ const sent = d.sendStep.mock.calls[1][0] as UIMessage[]
+ const last = sent[sent.length - 1]
+ expect(last.role).toBe('user')
+ expect((last.parts[0] as { text: string }).text).toBe(
+ "<SYSTEM>\nSubagent 'researcher' finished\n</SYSTEM>"
+ )
+ expect(sent[sent.length - 2].role).toBe('assistant')
+ })
+
+ /// Two children finishing together take one turn: consecutive user messages
+ /// are rejected outright by some providers.
+ it('fuses pings that arrive together into one marked turn', async () => {
+ const d = deps([textStep('a'), textStep('b')])
+ let running = 2
+ const queue: string[] = []
+ await runTurn({
+ messages: [user('go')],
+ signal: new AbortController().signal,
+ deps: {
+ ...d,
+ inbox: {
+ take: () => queue.splice(0, queue.length),
+ pending: () => queue.length > 0 || running > 0,
+ wait: async () => {
+ queue.push('alpha done', 'beta done')
+ running = 0
+ },
+ },
+ },
+ })
+ const sent = d.sendStep.mock.calls[1][0] as UIMessage[]
+ const pings = sent.filter(
+ (m) =>
+ m.role === 'user' &&
+ (m.parts[0] as { text?: string }).text?.startsWith('<SYSTEM>')
+ )
+ expect(pings).toHaveLength(1)
+ expect((pings[0].parts[0] as { text: string }).text).toBe(
+ '<SYSTEM>\nalpha done\nbeta done\n</SYSTEM>'
+ )
+ })
+
+ /// No inbox at all is the subagent path: a child cannot dispatch children, so
+ /// nothing should change for it.
+ it('finishes normally with no inbox', async () => {
+ const d = deps([textStep('done')])
+ const out = await runTurn({
+ messages: [user('hi')],
+ deps: d,
+ signal: new AbortController().signal,
+ })
+ expect(out.stoppedBy).toBe('done')
+ expect(d.sendStep).toHaveBeenCalledTimes(1)
+ })
+
it('keeps stepping while the model asks for tools', async () => {
const d = deps([toolStep('read'), toolStep('read', 'c2'), textStep('done')])
const out = await runTurn({
diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.ts
index bb97b3eeb..de050911c 100644
--- a/web-app/src/lib/__tests__/coworkSubagent.test.ts
+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts
@@ -12,13 +12,17 @@ vi.mock('ai', async (orig) => ({
}))
import {
+ dispatchedSubagentResult,
intersectAllowedTools,
parseSubagentRequest,
parentToolNames,
resolveSubagent,
runSubagent,
+ subagentCompletionNotice,
subagentTools,
+ SubagentInbox,
MAX_PARALLEL_SUBAGENTS,
+ SUBAGENT_INLINE_MAX,
__testing,
} from '../coworkSubagent'
import type { StreamEvent } from '@/hooks/useCoworkRun'
@@ -36,6 +40,99 @@ const definition = (over = {}) => ({
...over,
})
+describe('the task result and its completion ping', () => {
+ it('names the file the answer will land in, and does not wait', () => {
+ const out = dispatchedSubagentResult('researcher', 'c1', '/tmp/subagents/r.md')
+ expect(out).toContain('/tmp/subagents/r.md')
+ expect(out).toContain('Keep working')
+ })
+
+ it('promises the answer itself when there is no file to point at', () => {
+ const out = dispatchedSubagentResult('researcher', 'c1', null)
+ expect(out).toContain('You will be given its answer')
+ })
+
+ it('points the ping at the file rather than repeating the answer', () => {
+ const out = subagentCompletionNotice({
+ name: 'researcher',
+ callId: 'c1',
+ savedPath: '/tmp/subagents/r.md',
+ output: 'the findings',
+ })
+ expect(out).toContain('/tmp/subagents/r.md')
+ expect(out).not.toContain('the findings')
+ })
+
+ // Nothing else would carry it: with no file, the ping is the only delivery.
+ it('carries the answer inline when nothing was saved, capped', () => {
+ const output = 'y'.repeat(SUBAGENT_INLINE_MAX + 10)
+ const out = subagentCompletionNotice({
+ name: 'researcher',
+ callId: 'c1',
+ savedPath: null,
+ output,
+ })
+ expect(out).toContain('y'.repeat(SUBAGENT_INLINE_MAX))
+ expect(out.length).toBeLessThan(output.length + 200)
+ })
+
+ it('reports a failure as one, with no file named', () => {
+ const out = subagentCompletionNotice({
+ name: 'researcher',
+ callId: 'c1',
+ savedPath: null,
+ output: 'the model refused',
+ isError: true,
+ })
+ expect(out).toContain('failed: the model refused')
+ })
+})
+
+describe('SubagentInbox', () => {
+ it('reports work outstanding from dispatch until the ping is taken', async () => {
+ const inbox = new SubagentInbox()
+ expect(inbox.pending()).toBe(false)
+ inbox.begin()
+ expect(inbox.pending()).toBe(true)
+ inbox.finish('done')
+ // Still pending: the ping has been queued but not delivered, so a run that
+ // stopped here would drop it.
+ expect(inbox.pending()).toBe(true)
+ expect(inbox.take()).toEqual(['done'])
+ expect(inbox.take()).toEqual([])
+ expect(inbox.pending()).toBe(false)
+ })
+
+ it('wakes a waiter when a child finishes', async () => {
+ const inbox = new SubagentInbox()
+ inbox.begin()
+ let woke = false
+ const waiting = inbox.wait().then(() => {
+ woke = true
+ })
+ await Promise.resolve()
+ expect(woke).toBe(false)
+ inbox.finish('done')
+ await waiting
+ expect(woke).toBe(true)
+ })
+
+ it('never parks when there is nothing to wait for', async () => {
+ await expect(new SubagentInbox().wait()).resolves.toBeUndefined()
+ })
+
+ /// A cancelled run aborts its children, and nothing would ever file their
+ /// pings — so the wait has to end with the run, not with the child.
+ it('releases the waiter on cancellation', async () => {
+ const inbox = new SubagentInbox()
+ inbox.begin()
+ const controller = new AbortController()
+ const waiting = inbox.wait(controller.signal)
+ controller.abort()
+ await expect(waiting).resolves.toBeUndefined()
+ })
+})
+
describe('parseSubagentRequest', () => {
it('requires a name and a description', () => {
expect(parseSubagentRequest({})).toContain('subagent_name')
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index c81ec8127..f713e53ba 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -6,6 +6,8 @@ import {
threadWorkspaceSweep,
memoryCatalog,
memoryRead,
+ subagentResultReserve,
+ subagentResultFill,
type MemoryCatalogEntry,
type SandboxStatus,
type ToolSchema,
@@ -276,6 +278,46 @@ export async function executeAgentTool(
}
}
+/** A file claimed for a subagent's answer: the name to fill it by, and the
+ * model-visible path (`/tmp/subagents/<id>.md`, where the scratch is mounted
+ * over `/tmp`) the parent agent can `read`. */
+export type SubagentResultFile = { file: string; path: string }
+
+/**
+ * Claim a file in the session scratch for a subagent's answer.
+ *
+ * Claimed before the child starts, because `task` reports where the answer will
+ * be while it is still working. `null` when no scratch is reachable (the web
+ * build), in which case the caller falls back to delivering the answer inline.
+ */
+export async function reserveSubagentResult(
+ sessionId: string,
+ id: string
+): Promise<SubagentResultFile | null> {
+ try {
+ return await subagentResultReserve(sessionId, id)
+ } catch (e) {
+ console.warn('[agentTools] Failed to claim a result file:', messageOf(e))
+ return null
+ }
+}
+
+/** Write a finished subagent's answer into the file claimed for it. `false`
+ * when it could not be written, so the caller can deliver it inline instead. */
+export async function fillSubagentResult(
+ sessionId: string,
+ file: string,
+ content: string
+): Promise<boolean> {
+ try {
+ await subagentResultFill(sessionId, file, content)
+ return true
+ } catch (e) {
+ console.warn('[agentTools] Failed to save subagent result:', messageOf(e))
+ return false
+ }
+}
+
/**
* Delete a thread's sandbox. Best-effort: a failure here leaves a directory
* behind for the next startup sweep to collect, which is not worth surfacing
diff --git a/web-app/src/lib/coworkPing.ts b/web-app/src/lib/coworkPing.ts
new file mode 100644
index 000000000..b6ed5c441
--- /dev/null
+++ b/web-app/src/lib/coworkPing.ts
@@ -0,0 +1,51 @@
+import type { UIMessage } from 'ai'
+
+/**
+ * Out-of-band notes folded into a Cowork conversation: today, a backgrounded
+ * subagent reporting that it finished.
+ *
+ * Two problems this owns, the same two the Rust `reminder` module owns.
+ *
+ * It is marked with `<SYSTEM>` so the model can tell it from user-authored text,
+ * and so anything that enumerates user *turns* -- rewind, and the transcript it
+ * has to stay in step with -- can skip a message that only exists to carry one.
+ *
+ * And it is folded into the trailing message rather than pushed as its own
+ * whenever that message is the user's own, unanswered: consecutive user
+ * messages are rejected outright by some providers, and two children finishing
+ * together is the normal case.
+ *
+ * Kept free of every other import so the session store can use the predicate
+ * without pulling the runner (and the plugin API behind it) into its graph.
+ */
+
+export const PING_OPEN = '<SYSTEM>'
+export const PING_CLOSE = '</SYSTEM>'
+
+/** True when a message carries pings and nothing the user typed. */
+export function isPingOnly(message: { role: string; parts?: unknown }): boolean {
+ if (message.role !== 'user') return false
+ const parts = (message.parts ?? []) as Array<{ type?: string; text?: string }>
+ const texts = parts.filter((p) => p.type === 'text')
+ return (
+ texts.length > 0 &&
+ texts.every((p) => (p.text ?? '').trim().startsWith(PING_OPEN))
+ )
+}
+
+/** Fold pings into `messages` as one marked user turn. */
+export function attachPings(messages: UIMessage[], pings: string[]): void {
+ if (pings.length === 0) return
+ const text = `${PING_OPEN}\n${pings.join('\n')}\n${PING_CLOSE}`
+ const last = messages[messages.length - 1]
+ if (last?.role === 'user') {
+ const parts = last.parts as Array<{ type: string; text: string }>
+ parts.push({ type: 'text', text })
+ return
+ }
+ messages.push({
+ id: `ping-${messages.length}`,
+ role: 'user',
+ parts: [{ type: 'text', text }],
+ } as UIMessage)
+}
diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.ts
index e5d99fb51..eefb2abac 100644
--- a/web-app/src/lib/coworkRunner.ts
+++ b/web-app/src/lib/coworkRunner.ts
@@ -8,6 +8,7 @@ import {
recordSpend,
type BudgetStop,
} from '@/lib/coworkBudget'
+import { attachPings } from '@/lib/coworkPing'
/**
* The Cowork agent loop.
@@ -317,6 +318,16 @@ export type RunDeps = {
}) => void
/** Monotonic ids for the assistant messages this run appends. */
nextMessageId: () => string
+ /**
+ * Pings from work the model started and is no longer blocked on: a
+ * backgrounded subagent finishing. Omitted by a child run, which cannot
+ * dispatch subagents of its own.
+ */
+ inbox?: {
+ take: () => string[]
+ pending: () => boolean
+ wait: () => Promise<void>
+ }
}
export type RunOutcome = {
@@ -376,6 +387,11 @@ export async function runTurn(opts: {
}
}
+ // Anything that finished since the last request reaches the model here, as
+ // a marked user turn rather than an invented tool result: nothing was
+ // called this step.
+ attachPings(messages, deps.inbox?.take() ?? [])
+
// A snapshot, not the live array: the loop pushes to `messages` after the
// stream is handed over, and the transport rewrites what it is given
// (trimming, compaction) without expecting it to move underneath.
@@ -484,8 +500,10 @@ export async function runTurn(opts: {
}
}
- // Tools run one at a time: they share a workspace, and the progress
- // attribution in the UI assumes a single call in flight.
+ // One at a time: tools share a workspace, and the progress attribution in
+ // the UI assumes a single call in flight. A `task` fan-out is not an
+ // exception any more and needs none -- each `task` call returns as soon as
+ // its child has started, so the children overlap whatever this loop does.
const outcomes = new Map<string, ToolOutcome>()
for (const call of result.toolCalls) {
if (signal.aborted) {
@@ -514,6 +532,23 @@ export async function runTurn(opts: {
}
// No tool calls means the model answered rather than asked for more work.
if (result.toolCalls.length === 0) {
+ // Unless a subagent it dispatched is still going: ending here would drop
+ // that answer on the floor. Park, then let the ping drained at the top of
+ // the next step resume the conversation. Re-checked after the wait, which
+ // also returns on cancellation.
+ if (deps.inbox?.pending()) {
+ await deps.inbox.wait()
+ if (signal.aborted) {
+ return {
+ messages,
+ steps: step,
+ usage,
+ sessionTokens: spend.spent,
+ stoppedBy: 'aborted',
+ }
+ }
+ if (deps.inbox.pending()) continue
+ }
return {
messages,
steps: step,
diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.ts
index 55e400315..94e9b5656 100644
--- a/web-app/src/lib/coworkSubagent.ts
+++ b/web-app/src/lib/coworkSubagent.ts
@@ -39,14 +39,117 @@ import type { StreamEvent } from '@/hooks/useCoworkRun'
* parent then re-prefills on its next step. Fixing it means a dedicated
* subagent slot, which is part of the still-open slot-reservation decision.
*
- * The Rust pair `dispatch_subagent`/`await_subagent` collapses to one blocking
- * `task` call here. The SDK already emits several tool calls per step and the
- * runner dispatches them in order, so a run id to await later buys nothing.
+ * `task` is non-blocking, as `dispatch_subagent` is in Rust: it returns the file
+ * its child's answer will be written to, and the child runs on. Blocking held
+ * the tool call open for the whole errand -- so the transcript sat on a running
+ * frame, and a fan-out could not be reported one child at a time. The parent
+ * hears about each completion through a `<SYSTEM>` ping instead (see
+ * `SubagentInbox`), which is also what lets it keep working meanwhile.
*/
/** Concurrent children, mirroring `DEFAULT_MAX_PARALLEL_SUBAGENTS`. */
export const MAX_PARALLEL_SUBAGENTS = 3
+/**
+ * Characters of a child's answer carried in a ping that has no file to point
+ * at. Anything past this is lost, which is why a file is much preferred.
+ * Mirrors the Rust `SUBAGENT_INLINE_MAX_BYTES`.
+ */
+export const SUBAGENT_INLINE_MAX = 8 * 1024
+
+/** The `task` result for a child that has just been started. */
+export function dispatchedSubagentResult(
+ name: string,
+ callId: string,
+ savedPath: string | null
+): string {
+ const where = savedPath
+ ? `Its answer will be written to ${savedPath}; read that file once you are told it has landed.`
+ : 'You will be given its answer as soon as it finishes.'
+ return (
+ `Subagent '${name}' started in the background (${callId}). ${where} ` +
+ 'Keep working rather than waiting for it.'
+ )
+}
+
+/**
+ * The `<SYSTEM>` ping the parent gets when a child finishes. Port of the Rust
+ * `completion_notice`, with one difference: with no file to point at, the answer
+ * itself rides along, since nothing else would carry it.
+ */
+export function subagentCompletionNotice(opts: {
+ name: string
+ callId: string
+ savedPath: string | null
+ output: string
+ isError?: boolean
+}): string {
+ const who = `Subagent '${opts.name}' (${opts.callId})`
+ if (opts.isError) return `${who} failed: ${opts.output}`
+ if (opts.savedPath) {
+ return `${who} finished. Its full answer is in ${opts.savedPath} -- read that file when you need it.`
+ }
+ return `${who} finished. Its answer:\n\n${opts.output.slice(0, SUBAGENT_INLINE_MAX)}`
+}
+
+/**
+ * Completions the parent has not been told about yet, and the count of children
+ * that could still produce one.
+ *
+ * The runner asks this whether to keep the run alive: a model that stops while a
+ * child is still going would otherwise end the run, and the answer would have
+ * nowhere to land. `finish` queues the ping before dropping the running count,
+ * so `pending` can never read false in the window between the two.
+ */
+export class SubagentInbox {
+ private queue: string[] = []
+ private running = 0
+ private waiters: Array<() => void> = []
+
+ begin(): void {
+ this.running += 1
+ }
+
+ finish(notice: string): void {
+ this.queue.push(notice)
+ this.running -= 1
+ this.wake()
+ }
+
+ /** Take every queued ping, oldest first. */
+ take(): string[] {
+ const out = this.queue
+ this.queue = []
+ return out
+ }
+
+ pending(): boolean {
+ return this.queue.length > 0 || this.running > 0
+ }
+
+ /** Resolve when a ping is available, when nothing is left to wait for, or
+ * when the run is cancelled -- never hang past the run that owns it. */
+ wait(signal?: AbortSignal): Promise<void> {
+ if (!this.pending() || this.queue.length > 0 || signal?.aborted) {
+ return Promise.resolve()
+ }
+ return new Promise<void>((resolve) => {
+ const done = () => {
+ signal?.removeEventListener('abort', done)
+ resolve()
+ }
+ this.waiters.push(done)
+ signal?.addEventListener('abort', done, { once: true })
+ })
+ }
+
+ private wake(): void {
+ const waiters = this.waiters
+ this.waiters = []
+ for (const resolve of waiters) resolve()
+ }
+}
+
/**
* Always granted to a child, whatever the allowlist says.
*
@@ -343,9 +446,10 @@ function childStep(opts: {
/**
* Run one subagent to completion and return its final answer.
*
- * Blocking by design: the parent's `task` call resolves with the result, so the
- * model needs no run-id bookkeeping. Never throws — a failed child comes back as
- * an error string the parent can read and work around.
+ * The caller does not await this inline: `task` has already returned, and this
+ * promise is what eventually files a ping with the `SubagentInbox`. Never
+ * throws -- a failed child comes back as an error string the parent can read
+ * and work around.
*/
export async function runSubagent(
opts: RunSubagentOptions
diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.ts
index fd32ab85a..ac1d13f69 100644
--- a/web-app/src/lib/coworkTools.ts
+++ b/web-app/src/lib/coworkTools.ts
@@ -120,7 +120,7 @@ function taskTool(subagentNames: string[]): Tool {
: ''
return {
description:
- 'Run a subagent: a nested, isolated agent with its own system prompt and narrowed tools. It does not see this conversation, so state everything it needs in `description`. Returns its final answer.' +
+ 'Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools. It does not see this conversation, so state everything it needs in `description`. Runs in the BACKGROUND and returns immediately with the file its answer will be written to; call it several times in one step to fan work out, keep working, and a note tells you the moment each one finishes.' +
known,
inputSchema: jsonSchema({
type: 'object',
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 012c0b2ea..547362599 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -73,7 +73,12 @@ import { CoworkChatTransport } from '@/lib/coworkTransport'
import { dispatchCoworkTool } from '@/lib/coworkDispatch'
import { applyTodoOp, renderTodoResult } from '@/lib/coworkTodo'
import { parseAskRequest, renderAskResult } from '@/lib/coworkAsk'
-import { getSandboxStatus, sandboxEnforces } from '@/lib/agentTools'
+import {
+ getSandboxStatus,
+ sandboxEnforces,
+ fillSubagentResult,
+ reserveSubagentResult,
+} from '@/lib/agentTools'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'
import {
@@ -91,10 +96,13 @@ import {
type SubagentDefinition,
} from '@/lib/coworkSubagentRegistry'
import {
+ dispatchedSubagentResult,
parseSubagentRequest,
resolveSubagent,
parentToolNames,
runSubagent,
+ subagentCompletionNotice,
+ SubagentInbox,
} from '@/lib/coworkSubagent'
export const Route = createFileRoute(route.cowork as any)({
@@ -358,6 +366,9 @@ function CoworkPage() {
const controller = new AbortController()
abortRef.current = controller
+ // Owned by this request: children cannot outlive the run whose signal
+ // aborts them, so a fresh inbox per run can never hold a stale ping.
+ const inbox = new SubagentInbox()
const sink: StreamSink = {
onText: (delta) => {
@@ -469,7 +480,14 @@ function CoworkPage() {
isError: true,
}
}
- const child = await runSubagent({
+ // Claimed before the child starts: the tool call returns now,
+ // so the path it reports has to exist now.
+ const saved = await reserveSubagentResult(
+ sid,
+ `${resolved.name}-${callId}`
+ )
+ inbox.begin()
+ const child = runSubagent({
resolved,
description: req.description,
// The parent's instance: a second one would mean a second
@@ -524,10 +542,51 @@ function CoworkPage() {
useCoworkRun.getState().endSubagent(sid, callId, usage),
},
})
- useCoworkRun
- .getState()
- .attachSubagentOutput(sid, callId, child.output)
- return { output: child.output, isError: child.isError }
+ // Detached: the errand outlives its tool call, and the parent
+ // hears about it through the inbox instead.
+ void child
+ .then(async (done) => {
+ useCoworkRun
+ .getState()
+ .attachSubagentOutput(sid, callId, done.output)
+ // Only a real answer is filed: an error message in the file
+ // the parent was told to read would be indistinguishable
+ // from the answer it expected.
+ const filed =
+ saved && !done.isError && done.output.trim()
+ ? await fillSubagentResult(sid, saved.file, done.output)
+ : false
+ inbox.finish(
+ subagentCompletionNotice({
+ name: resolved.name,
+ callId,
+ savedPath: filed && saved ? saved.path : null,
+ output: done.output,
+ isError: done.isError,
+ })
+ )
+ })
+ .catch((e) =>
+ // `runSubagent` does not throw, so this is the loop itself
+ // failing. The count still has to come down or the run
+ // would wait on it forever.
+ inbox.finish(
+ subagentCompletionNotice({
+ name: resolved.name,
+ callId,
+ savedPath: null,
+ output: e instanceof Error ? e.message : String(e),
+ isError: true,
+ })
+ )
+ )
+ return {
+ output: dispatchedSubagentResult(
+ resolved.name,
+ callId,
+ saved?.path ?? null
+ ),
+ }
},
}),
sink,
@@ -551,6 +610,11 @@ function CoworkPage() {
let n = baseMessages.length
return () => `${sid}-asst-${n++}`
})(),
+ inbox: {
+ take: () => inbox.take(),
+ pending: () => inbox.pending(),
+ wait: () => inbox.wait(controller.signal),
+ },
},
})
} catch (e) {