Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): subagents - background dispatch, registry, TUI (#185)
Akarshan Biswasbc4166ffce2b
diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rsindex df06433e2..1a3bf4e30 100644--- a/src-tauri/src/core/agent/commands.rs+++ b/src-tauri/src/core/agent/commands.rs@@ -60,6 +60,8 @@ fn build_orchestration_args<R: Runtime>(permissions: ToolPermissions::allow_all(),project_root: None,permission_requests: Arc::new(Mutex::new(HashMap::new())),+ system_prompt_override: None,+ subagents_enabled: true,}}diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 97598ce39..f2a92732d 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -28,6 +28,23 @@ pub enum StreamEvent {#[serde(default, skip_serializing_if = "Option::is_none")]diff: Option<String>,},+ /// A backgrounded subagent run began. `run_id` identifies the run so a+ /// consumer can attribute concurrent children; brackets the child's wrapped+ /// events with `SubagentEnd`.+ SubagentStart { run_id: String, name: String },+ /// A backgrounded subagent run finished (success or error). Pairs with the+ /// `SubagentStart` of the same `run_id`.+ SubagentEnd { run_id: String, name: String },+ /// A backgrounded subagent's own internal event, tagged with its run so a+ /// consumer can attribute it to the right child even when several run+ /// concurrently. `event` is a non-terminal child event (Token/Step/ToolCall/+ /// ToolResult/PermissionRequest); the child's terminal Done/Error is never+ /// wrapped (its result is delivered via `await_subagent`).+ Subagent {+ run_id: String,+ name: String,+ event: Box<StreamEvent>,+ },/// Terminal success: the model returned a final (tool-free) completion.Done {stop_reason: String,@@ -281,6 +298,47 @@ mod tests {);}+ #[test]+ fn subagent_bracket_events_serialize_to_wire_shape() {+ let start = serde_json::to_value(StreamEvent::SubagentStart {+ run_id: "sub-1".into(),+ name: "rust-reviewer".into(),+ })+ .unwrap();+ assert_eq!(+ start,+ json!({ "type": "subagent_start", "run_id": "sub-1", "name": "rust-reviewer" })+ );+ let end = serde_json::to_value(StreamEvent::SubagentEnd {+ run_id: "sub-1".into(),+ name: "rust-reviewer".into(),+ })+ .unwrap();+ assert_eq!(+ end,+ json!({ "type": "subagent_end", "run_id": "sub-1", "name": "rust-reviewer" })+ );+ }++ #[test]+ fn wrapped_subagent_event_nests_inner_event() {+ let v = serde_json::to_value(StreamEvent::Subagent {+ run_id: "sub-1".into(),+ name: "reviewer".into(),+ event: Box::new(StreamEvent::Token { text: "hi".into() }),+ })+ .unwrap();+ assert_eq!(+ v,+ json!({+ "type": "subagent",+ "run_id": "sub-1",+ "name": "reviewer",+ "event": { "type": "token", "text": "hi" }+ })+ );+ }+#[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 127197c72..ec92564be 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -45,6 +45,7 @@ fn next_permission_id() -> String {/// All state the orchestration loop threads from multiple subsystems. Grouped/// into a struct so the streaming and non-streaming entry points share one/// argument surface instead of a ten-parameter signature.+#[derive(Clone)]pub(crate) struct OrchestrationArgs {pub client: Client,pub provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,@@ -56,6 +57,14 @@ pub(crate) struct OrchestrationArgs {pub permissions: crate::core::agent::permissions::ToolPermissions,pub project_root: Option<std::path::PathBuf>,pub permission_requests: PermissionRegistry,+ /// When set, used verbatim as the system prompt, bypassing project-context+ /// assembly and memory recall/indexing. Set for subagent child runs so a+ /// dispatched subagent gets exactly its definition prompt with no parent+ /// context bleed. `None` for normal runs.+ pub system_prompt_override: Option<String>,+ /// Whether this run may dispatch subagents. `false` for child runs, which+ /// caps recursion depth at one (a subagent cannot spawn grandchildren).+ pub subagents_enabled: bool,}#[async_trait]@@ -141,6 +150,17 @@ impl ToolInvoker for McpToolInvoker {}}+/// Context the invoker needs to dispatch subagents. `None` when subagents are+/// disabled for this run (a child run, or the proxy path), in which case a+/// subagent tool call returns an error instead of spawning a nested run.+struct SubagentContext {+ parent_args: OrchestrationArgs,+ model_id: String,+ max_session_tokens: Option<u64>,+ /// Background children of this run, aborted when the run ends.+ bg: std::sync::Arc<crate::core::agent::subagent::BackgroundSubagents>,+}+/// Dispatches built-in tool calls to native handlers (gated by `resolve_decision`)/// and everything else to the existing `McpToolInvoker`, preserving input order.struct CompositeToolInvoker {@@ -150,6 +170,7 @@ struct CompositeToolInvoker {events: mpsc::UnboundedSender<StreamEvent>,permission_requests: PermissionRegistry,grants: std::sync::Mutex<crate::core::agent::tools::gate::SessionGrants>,+ subagents: Option<SubagentContext>,}impl CompositeToolInvoker {@@ -176,6 +197,118 @@ impl CompositeToolInvoker {self.permission_requests.lock().await.remove(&request_id);decision}++ /// Prompt the user to approve a `user`-scope subagent write (it persists+ /// outside the current project). Project-scope writes are not prompted.+ async fn prompt_subagent_create(&self, name: &str) -> PermissionDecision {+ let request_id = next_permission_id();+ let (tx, rx) = tokio::sync::oneshot::channel();+ self.permission_requests+ .lock()+ .await+ .insert(request_id.clone(), tx);+ let _ = self.events.send(StreamEvent::PermissionRequest {+ request_id: request_id.clone(),+ tool_name: "create_subagent".to_string(),+ capability: "write".to_string(),+ path: Some(name.to_string()),+ command: None,+ diff: None,+ prompt_kind: "subagent_create".to_string(),+ offers_always: false,+ });+ let decision = rx.await.unwrap_or(PermissionDecision::Deny);+ self.permission_requests.lock().await.remove(&request_id);+ decision+ }++ /// 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+ /// just-created subagent is immediately dispatchable within the same run.+ async fn handle_subagent_tool(&self, name: &str, args: &serde_json::Value) -> String {+ use crate::core::agent::subagent::{+ await_subagent, format_subagent_list, parse_await_args, parse_create_args,+ parse_dispatch_args, spawn_subagent, subagent_dir_for, SubagentRegistry, SubagentScope,+ };+ let Some(ctx) = &self.subagents else {+ return "ERROR: subagents are not available in this run".to_string();+ };+ match name {+ "list_subagents" => {+ let registry = SubagentRegistry::load(&self.project_root);+ format_subagent_list(®istry)+ }+ "dispatch_subagent" => {+ let req = match parse_dispatch_args(args) {+ Ok(r) => r,+ Err(e) => return format!("ERROR: {e}"),+ };+ match spawn_subagent(+ &ctx.bg,+ &ctx.parent_args,+ req,+ &ctx.model_id,+ ctx.max_session_tokens,+ &self.events,+ ) {+ 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."+ ),+ Err(e) => format!("ERROR: {e}"),+ }+ }+ "await_subagent" => {+ let run_id = match parse_await_args(args) {+ Ok(r) => r,+ Err(e) => return format!("ERROR: {e}"),+ };+ match await_subagent(&ctx.bg, &run_id).await {+ Ok(text) if text.trim().is_empty() => {+ "The subagent finished but produced no text output.".to_string()+ }+ Ok(text) => text,+ Err(e) => format!("ERROR: {e}"),+ }+ }+ "create_subagent" => {+ let (def, scope, overwrite) = match parse_create_args(args) {+ Ok(v) => v,+ Err(e) => return format!("ERROR: {e}"),+ };+ if scope == SubagentScope::User {+ match self.prompt_subagent_create(&def.name).await {+ PermissionDecision::AllowOnce | PermissionDecision::AllowAlways => {}+ PermissionDecision::Deny => {+ return "ERROR: user-scope subagent creation denied by user".to_string()+ }+ }+ }+ let dir = match subagent_dir_for(&self.project_root, scope) {+ Ok(d) => d,+ Err(e) => return format!("ERROR: {e}"),+ };+ let scope_label = match scope {+ SubagentScope::User => "user",+ SubagentScope::Project => "project",+ };+ let mut registry = SubagentRegistry::load(&self.project_root);+ match registry.create_in(&dir, def.clone(), scope, overwrite) {+ Ok(shadows) => {+ let mut msg = format!("Created {scope_label}-scope subagent '{}'.", def.name);+ if shadows {+ msg.push_str(+ " Note: it shadows a user-scope subagent of the same name.",+ );+ }+ msg+ }+ Err(e) => format!("ERROR: {e}"),+ }+ }+ _ => "ERROR: unknown subagent tool".to_string(),+ }+ }}#[async_trait]@@ -197,6 +330,20 @@ impl ToolInvoker for CompositeToolInvoker {.and_then(|f| f.get("name")).and_then(|v| v.as_str()).unwrap_or("");+ // Subagent tools are handled ahead of the fs/exec gate and the MCP+ // fallback: they orchestrate nested runs, not filesystem access.+ if crate::core::agent::subagent::is_subagent_tool(name) {+ let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();+ 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_subagent_tool(name, &args).await;+ out.push(ToolOutcome::plain(id, content));+ continue;+ }if !is_builtin(name) {let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();// Deny-listed MCP tools are never advertised, but guard anyway.@@ -360,6 +507,8 @@ pub(crate) async fn run_server_side_openai_orchestration(permissions: crate::core::agent::permissions::ToolPermissions::allow_all(),project_root: None,permission_requests: Arc::new(Mutex::new(HashMap::new())),+ system_prompt_override: None,+ subagents_enabled: false,};run_orchestration_streamed(&tx, json_body, &args).await}@@ -476,6 +625,8 @@ async fn orchestrate_inner(permissions,project_root,permission_requests,+ system_prompt_override,+ subagents_enabled: _,} = args;let messages_value = json_body@@ -495,7 +646,9 @@ async fn orchestrate_inner((None, None)};- let system_prompt = if let Some(root) = project_root {+ let system_prompt = if let Some(override_prompt) = system_prompt_override.clone() {+ Some(override_prompt)+ } else if let Some(root) = project_root {let mut sp = crate::core::agent::context::build_system_prompt(assistant_instructions.as_deref(),root,@@ -582,6 +735,26 @@ async fn orchestrate_inner(}openai_tools.push(schema);}+ // Subagent tools are advertised only when this run may dispatch them+ // (never for a child run, capping recursion depth at one). The dispatch+ // tool's description lists the resolvable subagent names.+ if args.subagents_enabled {+ if let Some(root) = project_root {+ let registry = crate::core::agent::subagent::SubagentRegistry::load(root);+ for schema in crate::core::agent::subagent::subagent_tool_schemas(®istry) {+ let name = schema["function"]["name"].as_str().unwrap_or_default();+ if permissions.is_denied(name) {+ continue;+ }+ if let Some(allow) = &allowed_names {+ if !allow.contains(name) {+ continue;+ }+ }+ openai_tools.push(schema);+ }+ }+ }}let (upstream_url, session_api_keys) = resolve_upstream_for_model(@@ -615,9 +788,24 @@ async fn orchestrate_inner(let mut budget = SessionBudget::new(max_session_tokens);if let Some(root) = project_root {- if let Some(query) = latest_user_text(&conversation_messages) {- crate::core::agent::memory::index_message(root, "user", &query);+ // Subagent (override) runs are ephemeral: their turns are never indexed+ // into project memory, so a child cannot pollute the parent's recall.+ let index_memory = system_prompt_override.is_none();+ if index_memory {+ if let Some(query) = latest_user_text(&conversation_messages) {+ crate::core::agent::memory::index_message(root, "user", &query);+ }}+ // Background subagents are scoped to this run: `_bg_guard` aborts any+ // still-running child when `orchestrate_inner` returns or is cancelled.+ let bg = std::sync::Arc::new(crate::core::agent::subagent::BackgroundSubagents::default());+ let _bg_guard = crate::core::agent::subagent::AbortOnDrop(bg.clone());+ let subagents = args.subagents_enabled.then(|| SubagentContext {+ parent_args: args.clone(),+ model_id: model_id.clone(),+ max_session_tokens,+ bg: bg.clone(),+ });let tools = CompositeToolInvoker {mcp: mcp_tools,project_root: root.clone(),@@ -625,6 +813,7 @@ async fn orchestrate_inner(events: events.clone(),permission_requests: permission_requests.clone(),grants: std::sync::Mutex::new(crate::core::agent::tools::gate::SessionGrants::default()),+ subagents,};let result = run_turn_cycle(events,@@ -638,11 +827,13 @@ async fn orchestrate_inner(&tools,).await;- if let Ok(completion) = &result {- if let Some(answer) = extract_choice_message(completion)- .and_then(|m| m.get("content").and_then(|c| c.as_str()).map(str::to_string))- {- crate::core::agent::memory::index_message(root, "assistant", &answer);+ if index_memory {+ if let Ok(completion) = &result {+ if let Some(answer) = extract_choice_message(completion)+ .and_then(|m| m.get("content").and_then(|c| c.as_str()).map(str::to_string))+ {+ crate::core::agent::memory::index_message(root, "assistant", &answer);+ }}}result@@ -1030,6 +1221,7 @@ mod tests {events,permission_requests: registry,grants: std::sync::Mutex::new(SessionGrants::default()),+ subagents: None,}}diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex b0bf73c64..b7f7fa98b 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -11,5 +11,6 @@ pub mod memory;pub mod permissions;pub mod project;pub mod session;+pub mod subagent;pub mod tools;pub mod upstream;diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsnew file mode 100644index 000000000..472401e67--- /dev/null+++ b/src-tauri/src/core/agent/subagent.rs@@ -0,0 +1,1321 @@+//! Subagent definitions and their two-scope registry. A subagent is a named,+//! reusable system prompt + default tool allowlist that the main agent can+//! dispatch a nested, isolated run against (see `dispatch_subagent`). Definitions+//! live as `<scope>/.jan/agent/subagents/<name>.toml`, merged from the user scope+//! (`~/.jan/agent/subagents/`) and the project scope (`<project>/.jan/agent/+//! subagents/`); the project scope shadows the user scope by name.++use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use crate::core::agent::permissions::ToolPermissions;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum SubagentScope {+ User,+ Project,+}++/// A dispatchable subagent definition, resolved from a `<name>.toml` file plus+/// the scope of the directory it was loaded from.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SubagentDefinition {+ pub name: String,+ pub description: String,+ pub system_prompt: String,+ pub allowed_tools: Option<Vec<String>>,+ pub model: Option<String>,+ pub scope: SubagentScope,+}++/// On-disk shape of a subagent `.toml`; `scope` is derived from the directory,+/// not stored in the file.+#[derive(Debug, Clone, Deserialize, Serialize)]+struct SubagentFile {+ name: String,+ description: String,+ system_prompt: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ allowed_tools: Option<Vec<String>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ model: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum SubagentError {+ UnknownSubagent(String),+ PermissionDenied(String),+ Upstream(String),+ Cancelled,+}++impl std::fmt::Display for SubagentError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ SubagentError::UnknownSubagent(n) => {+ write!(f, "unknown subagent '{n}': no matching definition in the user or project scope")+ }+ SubagentError::PermissionDenied(m) => write!(f, "permission denied: {m}"),+ SubagentError::Upstream(m) => write!(f, "{m}"),+ SubagentError::Cancelled => write!(f, "subagent run cancelled"),+ }+ }+}++/// `~/.jan/agent/subagents/`. `None` when the home directory can't be resolved.+pub fn user_subagents_dir() -> Option<PathBuf> {+ dirs::home_dir().map(|h| h.join(".jan").join("agent").join("subagents"))+}++/// `<project_root>/.jan/agent/subagents/`.+pub fn project_subagents_dir(project_root: &Path) -> PathBuf {+ project_root+ .join(".jan")+ .join("agent")+ .join("subagents")+}++/// A subagent name is used to build a filename, so it must be a single path+/// component of `[A-Za-z0-9_-]`. Rejects empty, separators, and dots.+fn validate_name(name: &str) -> Result<(), SubagentError> {+ if name.is_empty()+ || !name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+ {+ return Err(SubagentError::PermissionDenied(format!(+ "invalid subagent name '{name}': use only letters, digits, '-' and '_'"+ )));+ }+ Ok(())+}++/// Merged view of subagent definitions across the user and project scopes.+/// Load order is user first, then project, so `get` (which resolves the winning+/// definition) returns the project entry when both scopes define a name; `list`+/// still reports both so shadowing is visible.+#[derive(Debug, Default)]+pub struct SubagentRegistry {+ defs: Vec<SubagentDefinition>,+}++impl SubagentRegistry {+ /// Load and merge the user scope then the project scope. Malformed files are+ /// skipped with a warning rather than failing the whole run.+ pub fn load(project_root: &Path) -> Self {+ let mut defs = Vec::new();+ if let Some(dir) = user_subagents_dir() {+ load_dir(&dir, SubagentScope::User, &mut defs);+ }+ load_dir(+ &project_subagents_dir(project_root),+ SubagentScope::Project,+ &mut defs,+ );+ Self { defs }+ }++ /// The winning definition for `name`: the project-scoped entry shadows a+ /// user-scoped one of the same name.+ pub fn get(&self, name: &str) -> Option<&SubagentDefinition> {+ self.defs.iter().rev().find(|d| d.name == name)+ }++ /// Every loaded definition, in load order (user scope first). Shadowed+ /// user-scope entries remain visible alongside their project-scope shadows.+ pub fn list(&self) -> Vec<&SubagentDefinition> {+ self.defs.iter().collect()+ }++ /// Write `def` to the directory for `scope`, refusing to clobber an existing+ /// definition of the same name in that same scope unless `overwrite`. Returns+ /// `true` when a project-scope write shadows a user-scope definition (so the+ /// caller can surface a note). A same-name definition in the *other* scope is+ /// not a collision (it is shadowing, by design).+ pub fn create(+ &mut self,+ def: SubagentDefinition,+ scope: SubagentScope,+ overwrite: bool,+ ) -> Result<bool, SubagentError> {+ validate_name(&def.name)?;+ let dir = match scope {+ SubagentScope::User => user_subagents_dir().ok_or_else(|| {+ SubagentError::Upstream("cannot resolve home directory for user scope".to_string())+ })?,+ SubagentScope::Project => {+ return Err(SubagentError::Upstream(+ "project scope requires create_in; use create_in".to_string(),+ ))+ }+ };+ self.create_in(&dir, def, scope, overwrite)+ }++ /// Scope-directory-explicit variant of [`create`]. The project scope depends+ /// on the run's project root, which the registry does not retain, so callers+ /// pass the directory directly.+ pub fn create_in(+ &mut self,+ dir: &Path,+ def: SubagentDefinition,+ scope: SubagentScope,+ overwrite: bool,+ ) -> Result<bool, SubagentError> {+ validate_name(&def.name)?;+ let collides = self+ .defs+ .iter()+ .any(|d| d.name == def.name && d.scope == scope);+ if collides && !overwrite {+ return Err(SubagentError::PermissionDenied(format!(+ "a {scope:?}-scope subagent named '{}' already exists; pass overwrite to replace it",+ def.name+ )));+ }+ std::fs::create_dir_all(dir)+ .map_err(|e| SubagentError::Upstream(format!("failed to create {}: {e}", dir.display())))?;+ let file = SubagentFile {+ name: def.name.clone(),+ description: def.description.clone(),+ system_prompt: def.system_prompt.clone(),+ allowed_tools: def.allowed_tools.clone(),+ model: def.model.clone(),+ };+ let body = toml::to_string_pretty(&file)+ .map_err(|e| SubagentError::Upstream(format!("failed to serialize subagent: {e}")))?;+ let path = dir.join(format!("{}.toml", def.name));+ std::fs::write(&path, body)+ .map_err(|e| SubagentError::Upstream(format!("failed to write {}: {e}", path.display())))?;++ let shadows_user = scope == SubagentScope::Project+ && self+ .defs+ .iter()+ .any(|d| d.name == def.name && d.scope == SubagentScope::User);+ // Keep the in-memory view consistent: replace any same-scope entry.+ self.defs+ .retain(|d| !(d.name == def.name && d.scope == scope));+ self.defs.push(SubagentDefinition { scope, ..def });+ Ok(shadows_user)+ }+}++fn load_dir(dir: &Path, scope: SubagentScope, out: &mut Vec<SubagentDefinition>) {+ let entries = match std::fs::read_dir(dir) {+ Ok(e) => e,+ Err(_) => return,+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().and_then(|e| e.to_str()) != Some("toml") {+ continue;+ }+ let raw = match std::fs::read_to_string(&path) {+ Ok(r) => r,+ Err(e) => {+ log::warn!("subagent: failed to read {}: {e}", path.display());+ continue;+ }+ };+ match toml::from_str::<SubagentFile>(&raw) {+ Ok(file) => out.push(SubagentDefinition {+ name: file.name,+ description: file.description,+ system_prompt: file.system_prompt,+ allowed_tools: file.allowed_tools,+ model: file.model,+ scope,+ }),+ Err(e) => log::warn!("subagent: failed to parse {}: {e}", path.display()),+ }+ }+}++/// Effective tool allowlist for a subagent dispatch: the intersection of the+/// definition's `allowed_tools`, the call-site override, and the parent's+/// permissions. Narrowing only, never widening; deny (from the parent) always+/// wins. Returns the list to set as the child's `allowed_tools` (an empty list+/// means "no tools"), or `None` to inherit the definition's full toolset with no+/// per-run allowlist (the parent's deny-list still applies at gate time).+///+/// Fails closed: a tool named in `request` that the definition does not permit,+/// or that the parent denies, is rejected rather than silently dropped. A+/// definition-listed tool the parent denies is dropped (the definition author+/// need not know the parent's policy).+pub fn intersect_allowed_tools(+ definition: Option<&[String]>,+ request: Option<&[String]>,+ parent: &ToolPermissions,+) -> Result<Option<Vec<String>>, SubagentError> {+ if let Some(requested) = request {+ let mut effective = Vec::with_capacity(requested.len());+ for tool in requested {+ if let Some(def) = definition {+ if !def.iter().any(|t| t == tool) {+ return Err(SubagentError::PermissionDenied(format!(+ "tool '{tool}' is outside the subagent definition's allowed_tools"+ )));+ }+ }+ if parent.is_denied(tool) {+ return Err(SubagentError::PermissionDenied(format!(+ "tool '{tool}' is denied by the parent's policy"+ )));+ }+ effective.push(tool.clone());+ }+ return Ok(Some(effective));+ }+ match definition {+ Some(def) => Ok(Some(+ def.iter()+ .filter(|t| !parent.is_denied(t))+ .cloned()+ .collect(),+ )),+ None => Ok(None),+ }+}++/// A model- or orchestration-issued request to run a subagent. When+/// `subagent_name` resolves in the registry, that definition is used (and+/// `allowed_tools` further narrows it). Otherwise, if `system_prompt` is+/// provided, an ephemeral one-off subagent is run inline with that prompt (no+/// registry entry, no disk write) so create + dispatch collapse to one call.+#[derive(Debug, Clone)]+pub struct SubagentRequest {+ pub subagent_name: String,+ pub description: String,+ pub allowed_tools: Option<Vec<String>>,+ pub system_prompt: Option<String>,+}++/// The resolved plan for a dispatch: the winning definition plus the effective+/// per-run tool allowlist after the three-way intersection.+#[derive(Debug)]+struct ResolvedDispatch {+ definition: SubagentDefinition,+ allowed_tools: Option<Vec<String>>,+}++/// Resolve a dispatch request against the registry and parent permissions,+/// without running anything. Errors on an unknown name or a permission conflict.+fn resolve_dispatch(+ registry: &SubagentRegistry,+ req: &SubagentRequest,+ parent: &ToolPermissions,+) -> Result<ResolvedDispatch, SubagentError> {+ match registry.get(&req.subagent_name).cloned() {+ Some(definition) => {+ // Registered definition: the call-site allowlist further narrows it.+ let allowed_tools = intersect_allowed_tools(+ definition.allowed_tools.as_deref(),+ req.allowed_tools.as_deref(),+ parent,+ )?;+ Ok(ResolvedDispatch {+ definition,+ allowed_tools,+ })+ }+ None => {+ // Unregistered: run an ephemeral one-off if an inline system_prompt+ // was supplied; otherwise it's a genuine unknown-name error.+ let system_prompt = req+ .system_prompt+ .clone()+ .filter(|s| !s.trim().is_empty())+ .ok_or_else(|| SubagentError::UnknownSubagent(req.subagent_name.clone()))?;+ let definition = SubagentDefinition {+ name: req.subagent_name.clone(),+ description: req.description.clone(),+ system_prompt,+ allowed_tools: req.allowed_tools.clone(),+ model: None,+ scope: SubagentScope::Project,+ };+ // The inline allowed_tools IS the definition's toolset; only the+ // parent's deny-list narrows it further.+ let allowed_tools =+ intersect_allowed_tools(definition.allowed_tools.as_deref(), None, parent)?;+ Ok(ResolvedDispatch {+ definition,+ allowed_tools,+ })+ }+ }+}++/// Child stream events are folded into the parent's own stream, except the+/// child's terminal `Done`/`Error`: the parent must not see the child terminate+/// its stream. Dispatch turns the child's result into a synthetic tool result+/// instead, bracketed by `SubagentStart`/`SubagentEnd`.+fn forward_to_parent(ev: &crate::core::agent::events::StreamEvent) -> bool {+ use crate::core::agent::events::StreamEvent;+ !matches!(ev, StreamEvent::Done { .. } | StreamEvent::Error { .. })+}++/// Final assistant text of a completion, or empty when the model returned none.+fn final_assistant_text(completion: &serde_json::Value) -> String {+ completion+ .get("choices")+ .and_then(|c| c.as_array())+ .and_then(|c| c.first())+ .and_then(|c| c.get("message"))+ .and_then(|m| m.get("content"))+ .and_then(|c| c.as_str())+ .unwrap_or("")+ .to_string()+}++use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;++static SUBAGENT_RUN_SEQ: AtomicU64 = AtomicU64::new(1);++fn next_subagent_run_id(name: &str) -> String {+ format!("sub-{name}-{}", SUBAGENT_RUN_SEQ.fetch_add(1, Ordering::Relaxed))+}++/// One in-flight background subagent: the channel that will carry its final+/// result, and the handle to abort it on parent cancellation/teardown.+struct BackgroundEntry {+ result: Option<tokio::sync::oneshot::Receiver<Result<String, SubagentError>>>,+ abort: tokio::task::AbortHandle,+}++/// Registry of a single parent run's background subagents, keyed by `run_id`.+/// Dropped when the parent run ends (see `AbortOnDrop`), aborting any child that+/// was never collected so a finished/cancelled parent leaves no orphan runs.+#[derive(Default)]+pub(crate) struct BackgroundSubagents {+ inner: std::sync::Mutex<std::collections::HashMap<String, BackgroundEntry>>,+}++impl BackgroundSubagents {+ /// Abort and forget every registered child. Called on parent teardown.+ pub(crate) fn abort_all(&self) {+ let mut guard = self.inner.lock().unwrap();+ for (_, entry) in guard.drain() {+ entry.abort.abort();+ }+ }+}++/// RAII guard tying background children to the parent run's lifetime: dropping it+/// (on normal return or when the parent future is cancelled) aborts every child.+pub(crate) struct AbortOnDrop(pub Arc<BackgroundSubagents>);++impl Drop for AbortOnDrop {+ fn drop(&mut self) {+ self.0.abort_all();+ }+}++/// Build the child request body shared by every subagent run.+fn child_body(+ resolved: &ResolvedDispatch,+ description: &str,+ parent_model: &str,+ budget_remaining: Option<u64>,+) -> serde_json::Value {+ let model = resolved+ .definition+ .model+ .clone()+ .unwrap_or_else(|| parent_model.to_string());+ let mut body = serde_json::Map::new();+ body.insert("model".to_string(), serde_json::json!(model));+ body.insert(+ "messages".to_string(),+ serde_json::json!([{ "role": "user", "content": description }]),+ );+ // Unbounded turns: guarded by the inherited budget and parent teardown.+ body.insert("max_turns".to_string(), serde_json::json!(0));+ body.insert("stream".to_string(), serde_json::json!(true));+ if let Some(tools) = &resolved.allowed_tools {+ body.insert("allowed_tools".to_string(), serde_json::json!(tools));+ }+ if let Some(remaining) = budget_remaining {+ body.insert("max_session_tokens".to_string(), serde_json::json!(remaining));+ }+ serde_json::Value::Object(body)+}++/// Run one resolved subagent to completion, wrapping its events for `run_id` and+/// returning its final assistant text. Isolated: fresh history (`description`),+/// the definition's system prompt, narrowed tools, dispatch disabled.+async fn run_subagent(+ parent_args: crate::core::agent::r#loop::OrchestrationArgs,+ resolved: ResolvedDispatch,+ description: String,+ parent_model: String,+ budget_remaining: Option<u64>,+ events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ run_id: String,+) -> Result<String, SubagentError> {+ use crate::core::agent::events::StreamEvent;+ use crate::core::agent::r#loop::run_orchestration_streamed;++ let name = resolved.definition.name.clone();+ let mut child_args = parent_args;+ child_args.system_prompt_override = Some(resolved.definition.system_prompt.clone());+ child_args.subagents_enabled = false;++ let body = child_body(&resolved, &description, &parent_model, budget_remaining);++ let _ = events.send(StreamEvent::SubagentStart {+ run_id: run_id.clone(),+ name: name.clone(),+ });++ let (child_tx, mut child_rx) = tokio::sync::mpsc::unbounded_channel::<StreamEvent>();+ let parent_events = events.clone();+ let fwd_run_id = run_id.clone();+ 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),+ });+ }+ }+ });++ let result = run_orchestration_streamed(&child_tx, &body, &child_args).await;+ drop(child_tx);+ let _ = forwarder.await;++ let _ = events.send(StreamEvent::SubagentEnd { run_id, name });++ match result {+ Ok(completion) => Ok(final_assistant_text(&completion)),+ Err(message) => Err(SubagentError::Upstream(message)),+ }+}++/// 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+/// teardown. Resolution (name lookup, permission intersection) happens+/// synchronously, so a bad request errors here rather than in the background.+pub(crate) fn spawn_subagent(+ bg: &Arc<BackgroundSubagents>,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ req: SubagentRequest,+ parent_model: &str,+ budget_remaining: Option<u64>,+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+) -> Result<String, SubagentError> {+ if !parent_args.subagents_enabled {+ return Err(SubagentError::PermissionDenied(+ "subagents cannot dispatch nested subagents".to_string(),+ ));+ }+ let project_root = parent_args+ .project_root+ .as_ref()+ .ok_or_else(|| SubagentError::Upstream("subagents require an active project".to_string()))?;+ let registry = SubagentRegistry::load(project_root);+ let resolved = resolve_dispatch(®istry, &req, &parent_args.permissions)?;++ let run_id = next_subagent_run_id(&resolved.definition.name);+ let (tx, rx) = tokio::sync::oneshot::channel();++ let parent_args = parent_args.clone();+ let events = events.clone();+ let model = parent_model.to_string();+ let description = req.description.clone();+ let run_id_task = run_id.clone();+ let handle = tokio::spawn(async move {+ let result = run_subagent(+ parent_args,+ resolved,+ description,+ model,+ budget_remaining,+ events,+ run_id_task,+ )+ .await;+ let _ = tx.send(result);+ });++ bg.inner.lock().unwrap().insert(+ run_id.clone(),+ BackgroundEntry {+ result: Some(rx),+ abort: handle.abort_handle(),+ },+ );+ Ok(run_id)+}++/// Block until the background subagent `run_id` finishes and return its final+/// text (or error). Removes the run from the registry; a second await, or an+/// unknown id, errors. A run aborted by parent teardown resolves to `Cancelled`.+pub(crate) async fn await_subagent(+ bg: &Arc<BackgroundSubagents>,+ run_id: &str,+) -> Result<String, SubagentError> {+ let rx = {+ let mut guard = bg.inner.lock().unwrap();+ match guard.get_mut(run_id).and_then(|e| e.result.take()) {+ Some(rx) => {+ guard.remove(run_id);+ rx+ }+ None => {+ return Err(SubagentError::Upstream(format!(+ "unknown or already-collected subagent run '{run_id}'"+ )))+ }+ }+ };+ rx.await.unwrap_or(Err(SubagentError::Cancelled))+}++/// The model-callable subagent tools, handled by the loop's tool invoker ahead+/// of the built-in fs/exec gate and the MCP fallback.+pub fn is_subagent_tool(name: &str) -> bool {+ matches!(+ name,+ "dispatch_subagent" | "await_subagent" | "create_subagent" | "list_subagents"+ )+}++/// One-line "name [scope]: description" per definition; shadowed user-scope+/// entries are listed alongside their project-scope shadows.+pub fn format_subagent_list(registry: &SubagentRegistry) -> String {+ let defs = registry.list();+ if defs.is_empty() {+ return "No subagents are configured in the user or project scope.".to_string();+ }+ let mut lines = Vec::with_capacity(defs.len());+ for d in defs {+ let scope = match d.scope {+ SubagentScope::User => "user",+ SubagentScope::Project => "project",+ };+ lines.push(format!("{} [{}]: {}", d.name, scope, d.description));+ }+ lines.join("\n")+}++/// OpenAI tool schemas for the subagent tools. The dispatch tool's description+/// lists the currently-resolvable subagent names so the model can pick one+/// without a separate discovery call.+pub fn subagent_tool_schemas(registry: &SubagentRegistry) -> Vec<serde_json::Value> {+ use serde_json::json;+ let available: Vec<&str> = {+ let mut names: Vec<&str> = registry.list().iter().map(|d| d.name.as_str()).collect();+ names.sort_unstable();+ names.dedup();+ names+ };+ let one_off = " For a one-off subagent, pass system_prompt inline (with a descriptive subagent_name); use create_subagent only to save a reusable definition.";+ let bg = " Runs in the BACKGROUND and returns a run_id immediately; keep working, dispatch more, then call await_subagent(run_id) to collect each result. Several can run concurrently.";+ 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 {+ format!(+ "Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools.{bg}{one_off} Saved subagents: {}.",+ available.join(", ")+ )+ };+ vec![+ json!({+ "type": "function",+ "function": {+ "name": "dispatch_subagent",+ "description": dispatch_desc,+ "parameters": {+ "type": "object",+ "properties": {+ "subagent_name": { "type": "string", "description": "Name of a saved subagent to run, or a short descriptive name for a one-off (paired with system_prompt)." },+ "description": { "type": "string", "description": "The task for the subagent, as its sole user message. Include everything it needs; it does not see this conversation." },+ "system_prompt": { "type": "string", "description": "Inline system prompt for a one-off subagent when subagent_name is not a saved one. Omit to run a saved subagent." },+ "allowed_tools": {+ "type": "array",+ "items": { "type": "string" },+ "description": "Tool allowlist. For a saved subagent this further narrows its own allowed_tools (never widens); for a one-off it is the subagent's toolset."+ }+ },+ "required": ["subagent_name", "description"]+ }+ }+ }),+ json!({+ "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.",+ "parameters": {+ "type": "object",+ "properties": {+ "run_id": { "type": "string", "description": "The run_id returned by dispatch_subagent." }+ },+ "required": ["run_id"]+ }+ }+ }),+ json!({+ "type": "function",+ "function": {+ "name": "create_subagent",+ "description": "Author a new reusable subagent definition. Writes to the project scope by default (shareable with collaborators); use scope 'user' for a personal one reusable across projects (this requires user approval).",+ "parameters": {+ "type": "object",+ "properties": {+ "name": { "type": "string", "description": "Subagent name: letters, digits, '-' and '_' only." },+ "description": { "type": "string", "description": "One line describing what the subagent is for." },+ "system_prompt": { "type": "string", "description": "The subagent's full system prompt." },+ "allowed_tools": {+ "type": "array",+ "items": { "type": "string" },+ "description": "Optional default tool allowlist for the subagent."+ },+ "scope": { "type": "string", "enum": ["user", "project"], "description": "Where to store it (default 'project')." },+ "overwrite": { "type": "boolean", "description": "Replace an existing same-name definition in that scope (default false)." }+ },+ "required": ["name", "description", "system_prompt"]+ }+ }+ }),+ json!({+ "type": "function",+ "function": {+ "name": "list_subagents",+ "description": "List the subagents available to dispatch, with their scope (user or project) and description. No arguments.",+ "parameters": { "type": "object", "properties": {}, "required": [] }+ }+ }),+ ]+}++fn required_str(args: &serde_json::Value, key: &str) -> Result<String, SubagentError> {+ args.get(key)+ .and_then(|v| v.as_str())+ .map(str::to_string)+ .filter(|s| !s.trim().is_empty())+ .ok_or_else(|| SubagentError::Upstream(format!("missing required argument '{key}'")))+}++fn optional_tool_list(args: &serde_json::Value) -> Option<Vec<String>> {+ args.get("allowed_tools")+ .and_then(|v| v.as_array())+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ })+}++/// Parse a `dispatch_subagent` tool-call argument object.+pub fn parse_dispatch_args(args: &serde_json::Value) -> Result<SubagentRequest, SubagentError> {+ Ok(SubagentRequest {+ subagent_name: required_str(args, "subagent_name")?,+ description: required_str(args, "description")?,+ allowed_tools: optional_tool_list(args),+ system_prompt: args+ .get("system_prompt")+ .and_then(|v| v.as_str())+ .map(str::to_string)+ .filter(|s| !s.trim().is_empty()),+ })+}++/// Parse an `await_subagent` tool-call argument object, returning the run_id.+pub fn parse_await_args(args: &serde_json::Value) -> Result<String, SubagentError> {+ required_str(args, "run_id")+}++/// Parse a `create_subagent` tool-call argument object into a definition plus+/// its target scope and the overwrite flag.+pub fn parse_create_args(+ args: &serde_json::Value,+) -> Result<(SubagentDefinition, SubagentScope, bool), SubagentError> {+ let name = required_str(args, "name")?;+ let description = required_str(args, "description")?;+ let system_prompt = required_str(args, "system_prompt")?;+ let scope = match args.get("scope").and_then(|v| v.as_str()) {+ Some("user") => SubagentScope::User,+ Some("project") | None => SubagentScope::Project,+ Some(other) => {+ return Err(SubagentError::Upstream(format!(+ "invalid scope '{other}': use 'user' or 'project'"+ )))+ }+ };+ let overwrite = args+ .get("overwrite")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ Ok((+ SubagentDefinition {+ name,+ description,+ system_prompt,+ allowed_tools: optional_tool_list(args),+ model: args+ .get("model")+ .and_then(|v| v.as_str())+ .map(String::from),+ scope,+ },+ scope,+ overwrite,+ ))+}++/// The directory a scope writes to for this project. User scope needs a+/// resolvable home directory.+pub fn subagent_dir_for(+ project_root: &Path,+ scope: SubagentScope,+) -> Result<PathBuf, SubagentError> {+ match scope {+ SubagentScope::Project => Ok(project_subagents_dir(project_root)),+ SubagentScope::User => user_subagents_dir().ok_or_else(|| {+ SubagentError::Upstream("cannot resolve home directory for user scope".to_string())+ }),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};+ use std::sync::atomic::{AtomicU32, Ordering};++ static COUNTER: AtomicU32 = AtomicU32::new(0);++ fn unique_root(tag: &str) -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ let root = std::env::temp_dir().join(format!(+ "jan_subagent_test_{tag}_{}_{n}",+ std::process::id()+ ));+ std::fs::create_dir_all(&root).expect("create test root");+ root+ }++ fn write_def(dir: &Path, name: &str, extra: &str) {+ std::fs::create_dir_all(dir).unwrap();+ let body = format!(+ "name = \"{name}\"\ndescription = \"desc for {name}\"\nsystem_prompt = \"You are {name}.\"\n{extra}"+ );+ std::fs::write(dir.join(format!("{name}.toml")), body).unwrap();+ }++ #[test]+ fn empty_directories_yield_empty_registry() {+ let root = unique_root("empty");+ let reg = SubagentRegistry::load(&root);+ assert!(reg.list().is_empty());+ assert!(reg.get("nope").is_none());+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn parses_definition_fields() {+ let root = unique_root("parse");+ let dir = project_subagents_dir(&root);+ write_def(+ &dir,+ "rust-reviewer",+ "allowed_tools = [\"read\", \"grep\"]\nmodel = \"m-1\"\n",+ );+ let reg = SubagentRegistry::load(&root);+ let def = reg.get("rust-reviewer").expect("loaded");+ assert_eq!(def.description, "desc for rust-reviewer");+ assert_eq!(def.system_prompt, "You are rust-reviewer.");+ assert_eq!(def.allowed_tools.as_deref(), Some(&["read".to_string(), "grep".to_string()][..]));+ assert_eq!(def.model.as_deref(), Some("m-1"));+ assert_eq!(def.scope, SubagentScope::Project);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn malformed_file_is_skipped_not_fatal() {+ let root = unique_root("malformed");+ let dir = project_subagents_dir(&root);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("bad.toml"), "this is = not valid = toml").unwrap();+ write_def(&dir, "good", "");+ let reg = SubagentRegistry::load(&root);+ assert!(reg.get("good").is_some());+ assert_eq!(reg.list().len(), 1);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn create_writes_project_scope_and_reloads() {+ let root = unique_root("create");+ let mut reg = SubagentRegistry::load(&root);+ let dir = project_subagents_dir(&root);+ let def = SubagentDefinition {+ name: "helper".to_string(),+ description: "d".to_string(),+ system_prompt: "sp".to_string(),+ allowed_tools: Some(vec!["read".to_string()]),+ model: None,+ scope: SubagentScope::Project,+ };+ let shadows = reg+ .create_in(&dir, def, SubagentScope::Project, false)+ .expect("create");+ assert!(!shadows);+ assert!(dir.join("helper.toml").exists());+ // A fresh load sees it too.+ let reg2 = SubagentRegistry::load(&root);+ let loaded = reg2.get("helper").expect("reloaded");+ assert_eq!(loaded.allowed_tools.as_deref(), Some(&["read".to_string()][..]));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn create_refuses_same_scope_collision_without_overwrite() {+ let root = unique_root("collision");+ let dir = project_subagents_dir(&root);+ write_def(&dir, "dup", "");+ let mut reg = SubagentRegistry::load(&root);+ let def = SubagentDefinition {+ name: "dup".to_string(),+ description: "d".to_string(),+ system_prompt: "sp".to_string(),+ allowed_tools: None,+ model: None,+ scope: SubagentScope::Project,+ };+ let err = reg+ .create_in(&dir, def.clone(), SubagentScope::Project, false)+ .expect_err("must refuse");+ assert!(matches!(err, SubagentError::PermissionDenied(_)));+ // overwrite succeeds.+ reg.create_in(&dir, def, SubagentScope::Project, true)+ .expect("overwrite ok");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn project_scope_shadows_user_but_both_visible() {+ let root = unique_root("shadow");+ // Fake the user dir under the project root to avoid touching the real HOME.+ let user_dir = root.join("user_scope");+ let proj_dir = project_subagents_dir(&root);+ write_def(&user_dir, "reviewer", "model = \"user-model\"\n");+ write_def(&proj_dir, "reviewer", "model = \"proj-model\"\n");++ let mut defs = Vec::new();+ load_dir(&user_dir, SubagentScope::User, &mut defs);+ load_dir(&proj_dir, SubagentScope::Project, &mut defs);+ let reg = SubagentRegistry { defs };++ // get() resolves the project entry (shadowing).+ assert_eq!(reg.get("reviewer").unwrap().model.as_deref(), Some("proj-model"));+ assert_eq!(reg.get("reviewer").unwrap().scope, SubagentScope::Project);+ // list() still shows both, with correct scope tags.+ let all = reg.list();+ assert_eq!(all.len(), 2);+ assert!(all.iter().any(|d| d.scope == SubagentScope::User));+ assert!(all.iter().any(|d| d.scope == SubagentScope::Project));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn create_reports_shadowing_of_user_scope() {+ let root = unique_root("shadow_create");+ let user_dir = root.join("user_scope");+ let proj_dir = project_subagents_dir(&root);+ write_def(&user_dir, "reviewer", "");+ let mut defs = Vec::new();+ load_dir(&user_dir, SubagentScope::User, &mut defs);+ let mut reg = SubagentRegistry { defs };+ let def = SubagentDefinition {+ name: "reviewer".to_string(),+ description: "d".to_string(),+ system_prompt: "sp".to_string(),+ allowed_tools: None,+ model: None,+ scope: SubagentScope::Project,+ };+ let shadows = reg+ .create_in(&proj_dir, def, SubagentScope::Project, false)+ .expect("create");+ assert!(shadows, "project create over a user def must report shadowing");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn create_rejects_invalid_name() {+ let root = unique_root("badname");+ let dir = project_subagents_dir(&root);+ let mut reg = SubagentRegistry::default();+ let def = SubagentDefinition {+ name: "../escape".to_string(),+ description: "d".to_string(),+ system_prompt: "sp".to_string(),+ allowed_tools: None,+ model: None,+ scope: SubagentScope::Project,+ };+ assert!(reg.create_in(&dir, def, SubagentScope::Project, false).is_err());+ let _ = std::fs::remove_dir_all(&root);+ }++ // ── intersect_allowed_tools ─────────────────────────────────────────────++ fn perms_denying(deny: &[&str]) -> ToolPermissions {+ let deny: Vec<String> = deny.iter().map(|s| s.to_string()).collect();+ ToolPermissions::new(PermissionDefault::ReadOnly, &[], &deny, &[])+ }++ #[test]+ fn intersect_none_none_inherits() {+ let p = ToolPermissions::allow_all();+ assert_eq!(intersect_allowed_tools(None, None, &p).unwrap(), None);+ }++ #[test]+ fn intersect_definition_only_drops_parent_denied() {+ let def = vec!["read".to_string(), "write".to_string()];+ let p = perms_denying(&["write"]);+ let out = intersect_allowed_tools(Some(&def), None, &p).unwrap();+ assert_eq!(out, Some(vec!["read".to_string()]));+ }++ #[test]+ fn intersect_request_narrows_within_definition() {+ let def = vec!["read".to_string(), "grep".to_string(), "write".to_string()];+ let req = vec!["read".to_string()];+ let p = ToolPermissions::allow_all();+ let out = intersect_allowed_tools(Some(&def), Some(&req), &p).unwrap();+ assert_eq!(out, Some(vec!["read".to_string()]));+ }++ #[test]+ fn intersect_request_outside_definition_is_rejected() {+ let def = vec!["read".to_string()];+ let req = vec!["bash".to_string()];+ let p = ToolPermissions::allow_all();+ let err = intersect_allowed_tools(Some(&def), Some(&req), &p).unwrap_err();+ assert!(matches!(err, SubagentError::PermissionDenied(_)));+ }++ #[test]+ fn intersect_request_denied_by_parent_is_rejected() {+ let req = vec!["bash".to_string()];+ let p = perms_denying(&["bash"]);+ let err = intersect_allowed_tools(None, Some(&req), &p).unwrap_err();+ assert!(matches!(err, SubagentError::PermissionDenied(_)));+ }++ // ── resolve_dispatch ────────────────────────────────────────────────────++ fn registry_with(name: &str, allowed: Option<Vec<String>>) -> SubagentRegistry {+ SubagentRegistry {+ defs: vec![SubagentDefinition {+ name: name.to_string(),+ description: "d".to_string(),+ system_prompt: "sp".to_string(),+ allowed_tools: allowed,+ model: None,+ scope: SubagentScope::Project,+ }],+ }+ }++ fn req(name: &str, allowed: Option<Vec<String>>) -> SubagentRequest {+ SubagentRequest {+ subagent_name: name.to_string(),+ description: "do the thing".to_string(),+ allowed_tools: allowed,+ system_prompt: None,+ }+ }++ #[test]+ fn resolve_unknown_name_without_inline_prompt_errors() {+ let reg = registry_with("reviewer", None);+ let p = ToolPermissions::allow_all();+ let err = resolve_dispatch(®, &req("nope", None), &p).unwrap_err();+ assert!(matches!(err, SubagentError::UnknownSubagent(n) if n == "nope"));+ }++ #[test]+ fn resolve_unknown_name_with_inline_prompt_runs_ephemeral() {+ let reg = SubagentRegistry::default();+ let p = ToolPermissions::allow_all();+ let request = SubagentRequest {+ subagent_name: "one-off".to_string(),+ description: "task".to_string(),+ allowed_tools: Some(vec!["read".to_string()]),+ system_prompt: Some("You are a one-off.".to_string()),+ };+ let resolved = resolve_dispatch(®, &request, &p).unwrap();+ assert_eq!(resolved.definition.system_prompt, "You are a one-off.");+ assert_eq!(resolved.definition.name, "one-off");+ assert_eq!(resolved.allowed_tools, Some(vec!["read".to_string()]));+ }++ #[test]+ fn parse_dispatch_reads_inline_system_prompt() {+ let r = parse_dispatch_args(&serde_json::json!({+ "subagent_name": "one-off",+ "description": "task",+ "system_prompt": "You are a one-off."+ }))+ .unwrap();+ assert_eq!(r.system_prompt.as_deref(), Some("You are a one-off."));+ }++ #[test]+ fn resolve_narrows_tools_within_definition() {+ let reg = registry_with(+ "reviewer",+ Some(vec!["read".to_string(), "grep".to_string()]),+ );+ let p = ToolPermissions::allow_all();+ let resolved =+ resolve_dispatch(®, &req("reviewer", Some(vec!["read".to_string()])), &p).unwrap();+ assert_eq!(resolved.allowed_tools, Some(vec!["read".to_string()]));+ assert_eq!(resolved.definition.system_prompt, "sp");+ }++ #[test]+ fn resolve_rejects_tool_outside_definition() {+ let reg = registry_with("reviewer", Some(vec!["read".to_string()]));+ let p = ToolPermissions::allow_all();+ let err =+ resolve_dispatch(®, &req("reviewer", Some(vec!["bash".to_string()])), &p).unwrap_err();+ assert!(matches!(err, SubagentError::PermissionDenied(_)));+ }++ // ── event forwarding + final text ───────────────────────────────────────++ #[test]+ fn forward_drops_child_terminal_events() {+ use crate::core::agent::events::StreamEvent;+ assert!(forward_to_parent(&StreamEvent::Token { text: "x".into() }));+ assert!(forward_to_parent(&StreamEvent::Step { index: 1, max: 0 }));+ assert!(forward_to_parent(&StreamEvent::ToolCall {+ id: "c".into(),+ name: "read".into(),+ args: serde_json::Value::Null,+ }));+ assert!(!forward_to_parent(&StreamEvent::Done {+ stop_reason: "stop".into(),+ usage: None,+ }));+ assert!(!forward_to_parent(&StreamEvent::Error {+ code: "e".into(),+ message: "m".into(),+ }));+ }++ /// Cancellation contract: `dispatch_subagent` is awaited inline inside the+ /// parent's run future, which the command layer drops via `tokio::select!` on+ /// cancel. This test encodes that guarantee: an in-flight child future nested+ /// under such a select is dropped (cancelled) when the parent is cancelled,+ /// with no separate child-run registration required.+ #[tokio::test]+ async fn cancelling_parent_drops_in_flight_child() {+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;++ let child_dropped = Arc::new(AtomicBool::new(false));++ struct DropFlag(Arc<AtomicBool>);+ impl Drop for DropFlag {+ fn drop(&mut self) {+ self.0.store(true, Ordering::SeqCst);+ }+ }++ let flag = child_dropped.clone();+ // The "parent run" awaits a never-completing "child" (dispatch) that owns+ // a drop guard, exactly as dispatch_subagent is awaited inline in the loop.+ let parent = async move {+ let _child_guard = DropFlag(flag);+ std::future::pending::<()>().await;+ };+ let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>();+ cancel_tx.send(()).unwrap();++ tokio::select! {+ // Biased so the parent is polled first and actually starts (building+ // the child guard), modelling an in-flight child at cancel time.+ biased;+ _ = parent => unreachable!("parent should be cancelled first"),+ _ = cancel_rx => {}+ }++ assert!(+ child_dropped.load(Ordering::SeqCst),+ "cancelling the parent must drop the in-flight child"+ );+ }++ #[test]+ fn final_text_extracts_or_defaults_empty() {+ let with = serde_json::json!({+ "choices": [{ "message": { "content": "the answer" } }]+ });+ assert_eq!(final_assistant_text(&with), "the answer");+ assert_eq!(final_assistant_text(&serde_json::json!({})), "");+ }++ // ── tool schemas + arg parsing ──────────────────────────────────────────++ #[test]+ fn subagent_tool_names_are_recognized() {+ assert!(is_subagent_tool("dispatch_subagent"));+ assert!(is_subagent_tool("await_subagent"));+ assert!(is_subagent_tool("create_subagent"));+ assert!(is_subagent_tool("list_subagents"));+ assert!(!is_subagent_tool("read"));+ assert!(!is_subagent_tool("web_search"));+ }++ // ── background registry (spawn/await/abort) ─────────────────────────────++ #[tokio::test]+ async fn await_unknown_run_errors() {+ let bg = Arc::new(BackgroundSubagents::default());+ assert!(await_subagent(&bg, "nope").await.is_err());+ }++ #[tokio::test]+ async fn await_delivers_result_and_second_await_errors() {+ let bg = Arc::new(BackgroundSubagents::default());+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = tokio::spawn(async { std::future::pending::<()>().await });+ bg.inner.lock().unwrap().insert(+ "r1".to_string(),+ BackgroundEntry {+ result: Some(rx),+ abort: handle.abort_handle(),+ },+ );+ tx.send(Ok("done".to_string())).unwrap();+ assert_eq!(await_subagent(&bg, "r1").await.unwrap(), "done");+ assert!(await_subagent(&bg, "r1").await.is_err(), "run is consumed");+ handle.abort();+ }++ #[tokio::test]+ async fn abort_on_drop_cancels_and_clears_children() {+ let bg = Arc::new(BackgroundSubagents::default());+ let (_tx, rx) = tokio::sync::oneshot::channel::<Result<String, SubagentError>>();+ let handle = tokio::spawn(async { std::future::pending::<()>().await });+ bg.inner.lock().unwrap().insert(+ "r1".to_string(),+ BackgroundEntry {+ result: Some(rx),+ abort: handle.abort_handle(),+ },+ );+ let guard = AbortOnDrop(bg.clone());+ drop(guard);+ assert!(bg.inner.lock().unwrap().is_empty(), "abort_all drains the map");+ assert!(handle.await.unwrap_err().is_cancelled(), "child was aborted");+ }++ #[test]+ fn schemas_list_available_names_in_dispatch_description() {+ let reg = registry_with("reviewer", None);+ let schemas = subagent_tool_schemas(®);+ assert_eq!(schemas.len(), 4);+ let names: Vec<&str> = schemas+ .iter()+ .map(|s| s["function"]["name"].as_str().unwrap())+ .collect();+ assert_eq!(+ names,+ vec![+ "dispatch_subagent",+ "await_subagent",+ "create_subagent",+ "list_subagents"+ ]+ );+ let dispatch = &schemas[0]["function"]["description"].as_str().unwrap();+ assert!(dispatch.contains("reviewer"), "got: {dispatch}");+ assert!(dispatch.contains("await_subagent"), "dispatch should mention await");+ }++ #[test]+ fn parse_await_requires_run_id() {+ assert_eq!(+ parse_await_args(&serde_json::json!({ "run_id": "sub-x-1" })).unwrap(),+ "sub-x-1"+ );+ assert!(parse_await_args(&serde_json::json!({})).is_err());+ }++ #[test]+ fn format_list_reports_scope_and_empty() {+ let empty = SubagentRegistry::default();+ assert!(format_subagent_list(&empty).contains("No subagents"));+ let reg = registry_with("reviewer", None);+ let listed = format_subagent_list(®);+ assert!(listed.contains("reviewer [project]: d"));+ }++ #[test]+ fn parse_dispatch_requires_name_and_description() {+ let ok = parse_dispatch_args(&serde_json::json!({+ "subagent_name": "reviewer",+ "description": "review this",+ "allowed_tools": ["read"]+ }))+ .unwrap();+ assert_eq!(ok.subagent_name, "reviewer");+ assert_eq!(ok.allowed_tools, Some(vec!["read".to_string()]));+ assert!(parse_dispatch_args(&serde_json::json!({ "description": "x" })).is_err());+ }++ #[test]+ fn parse_create_defaults_scope_to_project() {+ let (def, scope, overwrite) = parse_create_args(&serde_json::json!({+ "name": "helper",+ "description": "d",+ "system_prompt": "sp"+ }))+ .unwrap();+ assert_eq!(scope, SubagentScope::Project);+ assert!(!overwrite);+ assert_eq!(def.name, "helper");+ assert!(def.allowed_tools.is_none());+ }++ #[test]+ fn parse_create_reads_user_scope_and_overwrite() {+ let (_, scope, overwrite) = parse_create_args(&serde_json::json!({+ "name": "helper",+ "description": "d",+ "system_prompt": "sp",+ "scope": "user",+ "overwrite": true+ }))+ .unwrap();+ assert_eq!(scope, SubagentScope::User);+ assert!(overwrite);+ }++ #[test]+ fn parse_create_rejects_bad_scope_and_missing_fields() {+ assert!(parse_create_args(&serde_json::json!({+ "name": "x", "description": "d", "system_prompt": "sp", "scope": "global"+ }))+ .is_err());+ assert!(parse_create_args(&serde_json::json!({ "name": "x" })).is_err());+ }+}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 57ac1b9b1..56dafa566 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -759,6 +759,8 @@ fn build_cli_orchestration_args(permissions,project_root: Some(project_root),permission_requests,+ system_prompt_override: None,+ subagents_enabled: true,}}@@ -1139,6 +1141,20 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {};eprintln!("\x1b[2m[{tag}] {content}\x1b[0m");}+ StreamEvent::SubagentStart { name, .. } => {+ eprintln!("\x1b[2m[subagent:{name}] started (background)\x1b[0m")+ }+ StreamEvent::SubagentEnd { name, .. } => {+ eprintln!("\x1b[2m[subagent:{name}] finished\x1b[0m")+ }+ StreamEvent::Subagent { name, event, .. } => {+ if let StreamEvent::ToolCall { name: tool, args, .. } = *event {+ eprintln!(+ "\x1b[2m[subagent:{name}] {}\x1b[0m",+ crate::core::agent::events::describe_tool_call(&tool, &args)+ );+ }+ }StreamEvent::Done { stop_reason, usage } => {let tokens = usage.and_then(|u| u.total_tokens).unwrap_or(0);eprintln!("\n\x1b[2m[done] stop_reason={stop_reason} tokens={tokens}\x1b[0m");diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 9ce372b97..c2b976731 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -59,6 +59,9 @@ struct Pending {offers_always: bool,/// Highlighted option in the docked prompt (index into `options()`).selected: usize,+ /// Name of the subagent that requested this, when the call originated inside+ /// a nested subagent run; `None` for the parent agent's own calls.+ subagent: Option<String>,}impl Pending {@@ -289,8 +292,43 @@ struct App {view_width: u16,last_kind: Kind,should_quit: bool,+ /// Live panels for background subagents currently streaming, one per run.+ /// Several may be active at once; each renders its own rolling window.+ subagents: Vec<SubagentPanel>,+ /// Committed finished-subagent summary rows, expandable to their full+ /// tool-call list via Ctrl-O (parallel to `groups`/`reasoning_blocks`).+ subagent_blocks: Vec<SubagentBlock>,+ /// In-flight `await_subagent` calls, `(tool_call_id, subagent_name)`. Each+ /// renders a live throbber row until its tool result arrives.+ awaiting: Vec<(String, String)>,+ /// Monotonic frame counter advanced each render tick; drives the throbber.+ spinner_frame: usize,}+/// Braille throbber frames for in-progress rows (e.g. awaiting a subagent).+const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];++/// Live rolling view of an in-flight subagent's tool calls. The panel shows only+/// the most recent [`SUBAGENT_WINDOW`] calls, but the full list is retained so+/// the finished summary row can expand back to every call (Ctrl-O).+struct SubagentPanel {+ run_id: String,+ name: String,+ calls: Vec<String>,+}++/// A committed finished-subagent summary row, folded to one line but retaining+/// its full tool-call list so the row can expand back to it (like a tool group).+struct SubagentBlock {+ /// Transcript index of the summary row this block owns.+ idx: usize,+ /// Full detail lines (one per tool call), revealed when expanded.+ detail: Vec<Line<'static>>,+}++/// Rolling window size for a subagent's live tool-call list.+const SUBAGENT_WINDOW: usize = 5;+impl App {fn new(model: String,@@ -332,6 +370,10 @@ impl App {view_width: 0,last_kind: Kind::None,should_quit: false,+ subagents: Vec::new(),+ subagent_blocks: Vec::new(),+ awaiting: Vec::new(),+ spinner_frame: 0,}}@@ -377,6 +419,7 @@ impl App {self.grouped_ids.clear();self.groups.clear();self.reasoning_blocks.clear();+ self.subagent_blocks.clear();self.expanded.clear();self.reveal = None;self.assistant_buf.clear();@@ -514,6 +557,7 @@ impl App {.iter().map(|g| g.idx).chain(self.reasoning_blocks.iter().map(|r| r.idx))+ .chain(self.subagent_blocks.iter().map(|b| b.idx)).collect();if all.is_empty() {return;@@ -780,6 +824,15 @@ impl App {self.turn = (index, max);}StreamEvent::ToolCall { id, name, args } => {+ // Awaiting a subagent is a long block: show a live throbber row+ // (advanced each render tick) instead of a static grouped row,+ // cleared when its result arrives.+ if name == "await_subagent" {+ let run_id = args.get("run_id").and_then(|v| v.as_str()).unwrap_or("");+ let sub = subagent_name_from_run_id(run_id).to_string();+ self.awaiting.push((id, sub));+ return;+ }let max = self.render_width().saturating_sub(6) as usize;let label = truncate(&tool_activity(&name, &args), max);let done = truncate(&tool_finished(&name, &args), max);@@ -805,6 +858,8 @@ impl App {is_error,diff,} => {+ // Clear the throbber for an awaited subagent once its result lands.+ self.awaiting.retain(|(await_id, _)| await_id != &id);// Grouped calls are already represented by the group row; retain// their result on the group so an expand can show it later.if self.grouped_ids.contains(&id) {@@ -860,12 +915,107 @@ impl App {diff,offers_always,selected: 0,+ subagent: None,});}+ StreamEvent::SubagentStart { run_id, name } => {+ // Open a live rolling panel for this run; several may be active.+ self.finalize_tool_group();+ self.flush_assistant();+ self.subagents.push(SubagentPanel {+ run_id,+ name,+ calls: Vec::new(),+ });+ }+ StreamEvent::SubagentEnd { run_id, name } => {+ // Take the run's full call list, commit a folded summary row, and+ // retain the detail so Ctrl-O can expand it (like a tool group).+ let calls = self+ .subagents+ .iter()+ .find(|p| p.run_id == run_id)+ .map(|p| p.calls.clone())+ .unwrap_or_default();+ self.subagents.retain(|p| p.run_id != run_id);+ let total = calls.len();+ self.gap(Kind::Tool);+ let noun = if total == 1 { "call" } else { "calls" };+ self.push(tool_row(+ "↲",+ Style::new().magenta().dim(),+ &format!("subagent {name} finished ({total} tool {noun})"),+ Style::new().magenta().dim(),+ ));+ if total > 0 {+ let idx = self.transcript.len() - 1;+ let detail = calls+ .into_iter()+ .map(|label| {+ Line::from(vec![+ Span::styled("│ ", Style::new().dark_gray()),+ Span::styled("▸ ", Style::new().magenta()),+ Span::styled(label, Style::new().dim()),+ ])+ })+ .collect();+ self.subagent_blocks.push(SubagentBlock { idx, detail });+ }+ }+ StreamEvent::Subagent {+ run_id,+ name,+ event,+ } => self.apply_subagent_event(&run_id, &name, *event),StreamEvent::Done { .. } | StreamEvent::Error { .. } => {}}}+ /// Route one backgrounded subagent's internal event to its run's live panel.+ /// Only tool calls populate the rolling window; the child's own prose/steps/+ /// results are internal. A permission request docks the shared prompt,+ /// attributed to the asking subagent.+ fn apply_subagent_event(&mut self, run_id: &str, name: &str, event: StreamEvent) {+ match event {+ StreamEvent::ToolCall {+ name: tool, args, ..+ } => {+ let max = self.render_width().saturating_sub(6) as usize;+ let label = truncate(&subagent_activity(&tool, &args), max);+ if let Some(panel) = self.subagents.iter_mut().find(|p| p.run_id == run_id) {+ // Full history retained for expansion; the panel renders only+ // the last SUBAGENT_WINDOW.+ panel.calls.push(label);+ }+ }+ StreamEvent::PermissionRequest {+ request_id,+ tool_name,+ capability,+ path,+ command,+ diff,+ offers_always,+ ..+ } => {+ self.pending = Some(Pending {+ request_id,+ tool_name,+ capability,+ path,+ command,+ diff,+ offers_always,+ selected: 0,+ subagent: Some(name.to_string()),+ });+ }+ // Token/Step/ToolResult and any nested bracket are internal to the+ // child run and not surfaced in the parent transcript.+ _ => {}+ }+ }+/// Flush the current turn and return its text as the final assistant answer.fn take_answer(&mut self) -> String {let answer = self.assistant_buf.trim().to_string();@@ -1029,6 +1179,16 @@ fn boxed_panel(rows: Vec<(String, Style)>, max: usize, gutter: &'static str) ->/// Present-tense activity label for the running tool row ("Executing grep",/// "Searching"). Completed rows use `tool_finished` / `group_summary`.+/// The subagent name embedded in a `sub-<name>-<seq>` run id (falls back to the+/// raw id when it doesn't match that shape).+fn subagent_name_from_run_id(run_id: &str) -> &str {+ let s = run_id.strip_prefix("sub-").unwrap_or(run_id);+ match s.rfind('-') {+ Some(i) if i + 1 < s.len() && s[i + 1..].bytes().all(|b| b.is_ascii_digit()) => &s[..i],+ _ => s,+ }+}+fn tool_activity(name: &str, args: &serde_json::Value) -> String {let s = |k: &str| args.get(k).and_then(|v| v.as_str()).unwrap_or("");let base = |p: &str| {@@ -1055,11 +1215,40 @@ fn tool_activity(name: &str, args: &serde_json::Value) -> String {"list" | "ls" => "Listing files".to_string(),"write" => format!("Writing {}", base(s("path"))),"edit" => format!("Editing {}", base(s("path"))),+ "dispatch_subagent" => format!("Dispatching subagent: {}", s("subagent_name")),+ "await_subagent" => format!("Awaiting subagent: {}", subagent_name_from_run_id(s("run_id"))),+ "create_subagent" => format!("Creating subagent: {}", s("name")),+ "list_subagents" => "Listing subagents".to_string(),// Skill/memory tools already produce active labels ("Updating memory: X")._ => describe_tool_call(name, args),}}+/// Detailed one-line label for a subagent's own tool call, shown in the live+/// panel. Unlike `tool_activity` (deliberately terse for the parent transcript),+/// this keeps the concrete command/path/pattern so consecutive calls are+/// distinguishable ("git log -5" vs "git diff", not two "Executing git" rows).+fn subagent_activity(name: &str, args: &serde_json::Value) -> String {+ let s = |k: &str| args.get(k).and_then(|v| v.as_str()).unwrap_or("");+ match name {+ "bash" | "shell" | "exec" => {+ let cmd = s("command");+ if cmd.trim().is_empty() {+ "command".to_string()+ } else {+ format!("$ {}", cmd.split_whitespace().collect::<Vec<_>>().join(" "))+ }+ }+ "grep" | "search" => format!("grep {}", s("pattern")),+ "find" | "glob" => format!("find {}", s("pattern")),+ "read" => format!("read {}", s("path")),+ "list" | "ls" => format!("ls {}", s("path")),+ "write" => format!("write {}", s("path")),+ "edit" => format!("edit {}", s("path")),+ _ => tool_activity(name, args),+ }+}+/// Past-tense counterpart to `tool_activity` for a finalized single call/// ("Reading main.rs" -> "Read main.rs"); falls back to `describe_tool_call`.fn tool_finished(name: &str, args: &serde_json::Value) -> String {@@ -1086,6 +1275,10 @@ fn tool_finished(name: &str, args: &serde_json::Value) -> String {"find" | "glob" => "Found files".to_string(),"read" => format!("Read {}", base(s("path"))),"list" | "ls" => "Listed files".to_string(),+ "dispatch_subagent" => format!("Dispatched subagent: {}", s("subagent_name")),+ "await_subagent" => format!("Subagent {} returned", subagent_name_from_run_id(s("run_id"))),+ "create_subagent" => format!("Created subagent: {}", s("name")),+ "list_subagents" => "Listed subagents".to_string(),_ => describe_tool_call(name, args),}}@@ -1615,6 +1808,10 @@ async fn chat_loop<B: Backend>(tokio::select! {_ = ticker.tick() => {+ // Advance the throbber (~20fps) so awaiting rows animate.+ if !app.awaiting.is_empty() {+ app.spinner_frame = app.spinner_frame.wrapping_add(1);+ }while event::poll(Duration::ZERO).unwrap_or(false) {if let Ok(Event::Key(key)) = event::read() {handle_key(app, key, registry, &mut current, mcp_servers).await;@@ -2354,6 +2551,7 @@ fn rebuild_transcript(app: &mut App) {app.grouped_ids.clear();app.groups.clear();app.reasoning_blocks.clear();+ app.subagent_blocks.clear();app.expanded.clear();app.reveal = None;app.assistant_buf.clear();@@ -2409,6 +2607,7 @@ fn resume_thread(app: &mut App, id_arg: &str) {app.grouped_ids.clear();app.groups.clear();app.reasoning_blocks.clear();+ app.subagent_blocks.clear();app.expanded.clear();app.reveal = None;app.assistant_buf.clear();@@ -2530,9 +2729,45 @@ fn draw(f: &mut Frame, app: &mut App) {lines.extend(group_detail_lines(group, width));} else if let Some(block) = app.reasoning_blocks.iter().find(|r| r.idx == i) {lines.extend(block.detail.iter().cloned());+ } else if let Some(block) = app.subagent_blocks.iter().find(|b| b.idx == i) {+ lines.extend(block.detail.iter().cloned());}}}+ for (_, name) in &app.awaiting {+ let frame = SPINNER[app.spinner_frame % SPINNER.len()];+ lines.push(Line::from(vec![+ Span::styled(format!("{frame} "), Style::new().cyan()),+ Span::styled(+ format!("Awaiting subagent: {name}"),+ Style::new().cyan().dim(),+ ),+ ]));+ }+ for panel in &app.subagents {+ let last_blank = lines+ .last()+ .map(|l| l.spans.iter().all(|s| s.content.trim().is_empty()))+ .unwrap_or(true);+ if !last_blank {+ lines.push(Line::raw(""));+ }+ // Down-then-left arrow header, then the rolling window (last N calls).+ lines.push(Line::from(vec![+ Span::styled("↲ ", Style::new().magenta()),+ Span::styled(+ format!("subagent: {}", panel.name),+ Style::new().magenta().dim(),+ ),+ ]));+ let start = panel.calls.len().saturating_sub(SUBAGENT_WINDOW);+ for label in &panel.calls[start..] {+ lines.push(Line::from(vec![+ Span::styled(" ", Style::new().dark_gray()),+ Span::styled(label.clone(), Style::new().dim()),+ ]));+ }+ }if !app.assistant_buf.is_empty() {let tail = format_assistant_lines(&app.assistant_buf, width);if !tail.is_empty() {@@ -2612,7 +2847,9 @@ fn draw(f: &mut Frame, app: &mut App) {// Dock the permission prompt directly above the input box, growing upward// and clamped to the body area so it never overruns the transcript.if let Some(pending) = &app.pending {- let detail_rows = 1 + u16::from(pending.path.is_some() || pending.command.is_some());+ let detail_rows = 1+ + u16::from(pending.path.is_some() || pending.command.is_some())+ + u16::from(pending.subagent.is_some());let diff_rows = pending.diff_preview(chunks[2].width.saturating_sub(2)).len() as u16;let height =(pending.options().len() as u16 + detail_rows + diff_rows + 2).min(chunks[1].height);@@ -2686,11 +2923,19 @@ fn draw_permission(f: &mut Frame, area: ratatui::layout::Rect, pending: &Pendinguse ratatui::widgets::{Clear, List, ListItem, ListState};let dim = Style::new().dark_gray();- let mut detail = vec![Line::from(vec![+ let mut detail = Vec::new();+ if let Some(name) = &pending.subagent {+ detail.push(Line::from(vec![+ Span::styled("subagent ", dim),+ Span::styled(name.clone(), Style::new().magenta().bold()),+ Span::styled(" is asking:", dim),+ ]));+ }+ detail.push(Line::from(vec![Span::styled(pending.tool_name.clone(), Style::new().cyan().bold()),Span::styled(" wants ", dim),Span::styled(pending.capability.clone(), Style::new().yellow().bold()),- ])];+ ]));if let Some(command) = &pending.command {detail.push(Line::from(vec![Span::styled("$ ", dim),@@ -2892,8 +3137,9 @@ mod tests {use super::{diff_lines, group_activity, group_detail_lines, group_summary, input_content_lines,is_table_separator, message_text,- parse_command, render_table, run_command, split_reasoning, summarize_result,- tool_activity, tool_finished, transcript_top_padding, App, Pending, DIFF_MAX_ROWS,+ parse_command, render_table, run_command, split_reasoning, subagent_activity,+ subagent_name_from_run_id, summarize_result, tool_activity, tool_finished,+ transcript_top_padding, App, Pending, DIFF_MAX_ROWS,};use ratatui::{style::Modifier, text::Line};use crate::core::agent::events::StreamEvent;@@ -2921,6 +3167,7 @@ mod tests {diff: None,offers_always,selected: 0,+ subagent: None,}}@@ -3301,6 +3548,286 @@ mod tests {line.spans.iter().map(|s| s.content.as_ref()).collect()}+ #[test]+ fn subagent_tool_rows_have_readable_labels() {+ let dispatch = json!({ "subagent_name": "reviewer", "description": "x" });+ assert_eq!(tool_activity("dispatch_subagent", &dispatch), "Dispatching subagent: reviewer");+ assert_eq!(tool_finished("dispatch_subagent", &dispatch), "Dispatched subagent: reviewer");+ let await_args = json!({ "run_id": "sub-sycl-cuda-gap-explorer-1" });+ assert_eq!(+ tool_activity("await_subagent", &await_args),+ "Awaiting subagent: sycl-cuda-gap-explorer"+ );+ assert_eq!(tool_activity("list_subagents", &json!({})), "Listing subagents");+ assert_eq!(tool_activity("create_subagent", &json!({"name": "r"})), "Creating subagent: r");+ }++ #[test]+ fn subagent_name_from_run_id_strips_prefix_and_seq() {+ assert_eq!(subagent_name_from_run_id("sub-reviewer-3"), "reviewer");+ assert_eq!(subagent_name_from_run_id("sub-a-b-c-12"), "a-b-c");+ // Non-conforming ids pass through.+ assert_eq!(subagent_name_from_run_id("weird"), "weird");+ }++ #[test]+ fn subagent_panel_labels_keep_command_detail() {+ // The panel must distinguish consecutive bash calls, not collapse to+ // "Executing git".+ assert_eq!(+ subagent_activity("bash", &json!({ "command": "git log --oneline -5" })),+ "$ git log --oneline -5"+ );+ assert_eq!(+ subagent_activity("bash", &json!({ "command": "git diff" })),+ "$ git diff"+ );+ assert_eq!(+ subagent_activity("read", &json!({ "path": "src/main.rs" })),+ "read src/main.rs"+ );+ assert_eq!(+ subagent_activity("grep", &json!({ "pattern": "TODO" })),+ "grep TODO"+ );+ }++ #[test]+ fn await_subagent_shows_throbber_until_result() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "a1".into(),+ name: "await_subagent".into(),+ args: json!({ "run_id": "sub-reviewer-1" }),+ });+ // Tracked as an awaiting throbber (not folded into a tool group row).+ assert_eq!(app.awaiting.len(), 1);+ assert_eq!(app.awaiting[0], ("a1".to_string(), "reviewer".to_string()));+ assert!(app.tool_group.is_none(), "await must not open a tool group");+ // The result clears the throbber.+ app.apply(StreamEvent::ToolResult {+ id: "a1".into(),+ content: "the subagent's answer".into(),+ is_error: false,+ diff: None,+ });+ assert!(app.awaiting.is_empty());+ }++ fn wrap(run_id: &str, name: &str, event: StreamEvent) -> StreamEvent {+ StreamEvent::Subagent {+ run_id: run_id.into(),+ name: name.into(),+ event: Box::new(event),+ }+ }++ #[test]+ fn subagent_calls_fill_rolling_panel_capped_at_window() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ // Seven calls; only the last SUBAGENT_WINDOW remain visible.+ for i in 0..7 {+ app.apply(wrap(+ "r1",+ "reviewer",+ StreamEvent::ToolCall {+ id: format!("c{i}"),+ name: "bash".into(),+ args: json!({ "command": format!("cmd{i}") }),+ },+ ));+ // Results are internal to the subagent and must not surface.+ app.apply(wrap(+ "r1",+ "reviewer",+ StreamEvent::ToolResult {+ id: format!("c{i}"),+ content: "ok".into(),+ is_error: false,+ diff: None,+ },+ ));+ }+ let panel = app.subagents.iter().find(|p| p.run_id == "r1").expect("active");+ // Full history retained (for later expansion); the window is a render concern.+ assert_eq!(panel.calls.len(), 7);+ assert!(panel.calls.first().unwrap().contains("cmd0"));+ assert!(panel.calls.last().unwrap().contains("cmd6"));+ // The live panel renders only the last SUBAGENT_WINDOW calls.+ use ratatui::{backend::TestBackend, Terminal};+ let render = |app: &mut App| {+ let mut terminal = Terminal::new(TestBackend::new(80, 30)).unwrap();+ terminal.draw(|f| super::draw(f, app)).unwrap();+ let buf = terminal.backend().buffer().clone();+ (0..buf.area.height)+ .map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect::<String>())+ .collect::<Vec<_>>()+ .join("\n")+ };+ let out = render(&mut app);+ assert!(out.contains("cmd6") && out.contains("cmd2"), "window tail shown");+ assert!(!out.contains("cmd0") && !out.contains("cmd1"), "oldest scrolled out: {out}");+ }++ #[test]+ fn concurrent_subagents_track_independent_panels() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "alpha".into(),+ });+ app.apply(StreamEvent::SubagentStart {+ run_id: "r2".into(),+ name: "beta".into(),+ });+ app.apply(wrap(+ "r2",+ "beta",+ StreamEvent::ToolCall {+ id: "c0".into(),+ name: "bash".into(),+ args: json!({ "command": "beta-cmd" }),+ },+ ));+ assert_eq!(app.subagents.len(), 2);+ let alpha = app.subagents.iter().find(|p| p.run_id == "r1").unwrap();+ let beta = app.subagents.iter().find(|p| p.run_id == "r2").unwrap();+ assert_eq!(alpha.calls.len(), 0, "beta's call must not land on alpha");+ assert_eq!(beta.calls.len(), 1);+ assert!(beta.calls.last().unwrap().contains("beta-cmd"));+ }++ #[test]+ fn finished_subagent_summary_expands_full_call_list_via_ctrl_o() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ // More calls than the live window, so expansion reveals ones it hid.+ for i in 0..7 {+ app.apply(wrap(+ "r1",+ "reviewer",+ StreamEvent::ToolCall {+ id: format!("c{i}"),+ name: "bash".into(),+ args: json!({ "command": format!("cmd{i}") }),+ },+ ));+ }+ app.apply(StreamEvent::SubagentEnd {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ // A collapsed summary row + a retained expandable block.+ assert_eq!(app.subagent_blocks.len(), 1);+ let idx = app.subagent_blocks[0].idx;++ use ratatui::{backend::TestBackend, Terminal};+ let render = |app: &mut App| {+ let mut terminal = Terminal::new(TestBackend::new(80, 40)).unwrap();+ terminal.draw(|f| super::draw(f, app)).unwrap();+ let buf = terminal.backend().buffer().clone();+ (0..buf.area.height)+ .map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect::<String>())+ .collect::<Vec<_>>()+ .join("\n")+ };+ // Collapsed: full list (e.g. the oldest call) is hidden.+ assert!(!render(&mut app).contains("cmd0"));+ // Ctrl-O expand-all reveals every call, including ones outside the window.+ app.toggle_regions();+ assert!(app.expanded.contains(&idx));+ let expanded = render(&mut app);+ assert!(expanded.contains("cmd0"), "expanded must reveal earliest call: {expanded}");+ assert!(expanded.contains("cmd6"));+ // Toggling again collapses it.+ app.toggle_regions();+ assert!(!app.expanded.contains(&idx));+ }++ #[test]+ fn subagent_end_commits_summary_and_clears_only_that_panel() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ app.apply(wrap(+ "r1",+ "reviewer",+ StreamEvent::ToolCall {+ id: "c0".into(),+ name: "bash".into(),+ args: json!({ "command": "ls" }),+ },+ ));+ app.apply(StreamEvent::SubagentEnd {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ assert!(app.subagents.iter().all(|p| p.run_id != "r1"));+ assert!(app+ .transcript+ .iter()+ .any(|l| line_text(l).contains("subagent reviewer finished (1 tool call)")));+ }++ #[test]+ fn parent_tokens_still_render_while_subagent_active() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ // A wrapped child token is internal and dropped.+ app.apply(wrap(+ "r1",+ "reviewer",+ StreamEvent::Token {+ text: "child prose".into(),+ },+ ));+ assert!(app.assistant_buf.is_empty());+ // The parent's own token still streams even with a child active.+ app.apply(StreamEvent::Token {+ text: "parent prose".into(),+ });+ assert_eq!(app.assistant_buf, "parent prose");+ }++ #[test]+ fn permission_inside_subagent_attributes_the_asking_subagent() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "reviewer".into(),+ });+ app.apply(wrap(+ "r1",+ "reviewer",+ StreamEvent::PermissionRequest {+ request_id: "p1".into(),+ tool_name: "bash".into(),+ capability: "exec".into(),+ path: None,+ command: Some("cargo test".into()),+ diff: None,+ prompt_kind: "exec".into(),+ offers_always: true,+ },+ ));+ assert_eq!(+ app.pending.as_ref().and_then(|p| p.subagent.as_deref()),+ Some("reviewer")+ );+ }+#[test]fn input_lines_single_line_has_arrow_and_cursor() {let lines = input_content_lines("hello", 5);