Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): address PR review on phased subagents + TUI
Akarshan Biswas0778c9936026
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 209e19a13..a259e1ba2 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -48,6 +48,8 @@ See [Sessions](/docs/agent/sessions).| `/compact` | Summarize older turns to free up context || `/context` | Show what is filling the context window, by category - opens a live overlay while the turn keeps running || `/cancel [N]` | Cancel queued messages. Bare: all, or an index |+| `/agents` | Inspect running subagents: each one's stats and current activity |+| `/shells` (alias `/jobs`) | Inspect and stop background shell commands the agent left running |See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-todos), and[Context and compaction](/docs/agent/context).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.rsindex ab2fdd251..a75d6ec91 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@@ -909,8 +909,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {});format!("Command exceeded {timeout_secs}s and is still running in the \- background. Its full output will be written to {display} once it \- finishes; read that file to collect the result."+ background. Its result will be written to {display} once it \+ finishes; read that file to collect it (if the output was large \+ that file keeps a tail and points to the full log).")}None => format!(diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rsindex 74eae25fe..aa6a36cbb 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs@@ -389,14 +389,19 @@ fn set_process_group(cmd: &mut Command) {}/// Kill the process `pid` and every descendant it spawned.+///+/// Every child we register is spawned with `process_group(0)` (see+/// [`set_process_group`]), so its pgid equals its pid and `killpg` reaps the+/// whole tree. There is deliberately no bare-`kill(pid)` fallback: `killpg`+/// fails only when the group is already gone (ESRCH) or we lack permission+/// (EPERM, which a single `kill` would hit too), so the fallback could never+/// help a live tree -- it could only signal a recycled pid, since the registry+/// lock is dropped before this call and the OS may have reused the number.#[cfg(unix)]pub fn kill_tree(pid: u32) {use nix::sys::signal::{killpg, Signal};use nix::unistd::Pid;- let group = Pid::from_raw(pid as i32);- if killpg(group, Signal::SIGKILL).is_err() {- let _ = nix::sys::signal::kill(Pid::from_raw(pid as i32), Signal::SIGKILL);- }+ let _ = killpg(Pid::from_raw(pid as i32), Signal::SIGKILL);}#[cfg(windows)]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rsindex d4abc94e0..688e71280 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs@@ -136,6 +136,25 @@ pub fn reserve_blackboard_result(scratch: &Path, name: &str) -> Option<PathBuf>}}+/// Read `<scratch>/blackboard/<name>.md` for injection into the next phase,+/// fail-closed against the same redirection the write path guards: the shell+/// shares this scratch and can `rm` a finished answer and `ln -s` a host file in+/// its place, which a plain read would follow, feeding host contents into the+/// successor's prompt. The directory is re-validated as a real (non-symlink)+/// dir and the leaf must be a real file, not a symlink. `name` is the model's+/// blackboard stem; it is sanitized to one safe component before resolving.+/// Returns `None` on a missing, redirected, or unreadable entry -- all "no+/// input", indistinguishable to the caller.+pub fn read_blackboard_result(scratch: &Path, name: &str) -> Option<String> {+ let dir = validated_subdir(scratch, BLACKBOARD_DIR)?;+ let path = dir.join(format!("{}.md", sanitize_stem(name)));+ match std::fs::symlink_metadata(&path) {+ Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => {}+ _ => return None,+ }+ std::fs::read_to_string(&path).ok()+}+/// 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.@@ -268,6 +287,45 @@ mod tests {let _ = std::fs::remove_dir_all(&scratch);}+ #[test]+ fn reads_a_real_blackboard_answer() {+ let scratch = tmp("bb-read");+ let p = reserve_blackboard_result(&scratch, "research").unwrap();+ assert!(fill_subagent_result(&p, "the answer"));+ assert_eq!(+ read_blackboard_result(&scratch, "research").as_deref(),+ Some("the answer")+ );+ assert!(read_blackboard_result(&scratch, "missing").is_none());+ let _ = std::fs::remove_dir_all(&scratch);+ }++ #[cfg(unix)]+ #[test]+ fn refuses_to_read_through_a_swapped_link() {+ let scratch = tmp("bb-read-swap");+ let host = tmp("bb-read-host").join("secret");+ std::fs::write(&host, "host-secret").unwrap();+ let path = reserve_blackboard_result(&scratch, "research").unwrap();+ std::fs::remove_file(&path).unwrap();+ std::os::unix::fs::symlink(&host, &path).unwrap();+ assert!(read_blackboard_result(&scratch, "research").is_none());+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(host.parent().unwrap());+ }++ #[cfg(unix)]+ #[test]+ fn refuses_to_read_through_a_redirected_dir() {+ let scratch = tmp("bb-read-dir");+ let host = tmp("bb-read-dir-host");+ std::fs::write(host.join("research.md"), "host-secret").unwrap();+ std::os::unix::fs::symlink(&host, scratch.join(BLACKBOARD_DIR)).unwrap();+ assert!(read_blackboard_result(&scratch, "research").is_none());+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(&host);+ }+#[cfg(unix)]#[test]fn refuses_to_fill_through_a_swapped_link() {diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 858833caa..b3ee31e52 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1153,12 +1153,10 @@ fn read_blackboard(scratch: Option<&Path>, names: &[String]) -> Vec<(String, Strlet Some(s) = scratch else {return Vec::new();};- let dir = blackboard_dir_path(s);names.iter().filter_map(|n| {- std::fs::read_to_string(dir.join(format!("{n}.md")))- .ok()+ tauri_plugin_agent_tools::tools::spill::read_blackboard_result(s, n).map(|c| (n.clone(), c))}).collect()diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex aaeebf4e9..bbd06bb46 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -6589,6 +6589,18 @@ fn collapse_command(cmd: &str) -> String {.to_string()}+/// The name of the first subagent in a phased `dispatch_subagent` call. The+/// schema is a flat `subagents: [{ name, task, phase }]`; the transient row+/// names the first, mirroring the web card (`firstPlannedSubagent`).+fn first_dispatched_subagent_name(args: &serde_json::Value) -> &str {+ args.get("subagents")+ .and_then(|v| v.as_array())+ .and_then(|a| a.first())+ .and_then(|s| s.get("name"))+ .and_then(|v| v.as_str())+ .unwrap_or("")+}+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| {@@ -6614,7 +6626,9 @@ 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")),+ "dispatch_subagent" => {+ format!("Dispatching subagent: {}", first_dispatched_subagent_name(args))+ }"await_subagent" => format!("Awaiting subagent: {}",subagent_name_from_run_id(s("run_id"))@@ -6771,7 +6785,9 @@ fn tool_finished(name: &str, args: &serde_json::Value) -> String {"list" | "ls" => "Listed files".to_string(),"write" => format!("Wrote {}", base(s("path"))),"edit" => format!("Edited {}", base(s("path"))),- "dispatch_subagent" => format!("Dispatched subagent: {}", s("subagent_name")),+ "dispatch_subagent" => {+ format!("Dispatched subagent: {}", first_dispatched_subagent_name(args))+ }"await_subagent" => format!("Subagent {} returned",subagent_name_from_run_id(s("run_id"))@@ -21496,7 +21512,7 @@ mod tests {#[test]fn subagent_tool_rows_have_readable_labels() {- let dispatch = json!({ "subagent_name": "reviewer", "description": "x" });+ let dispatch = json!({ "subagents": [{ "name": "reviewer", "task": "x" }] });assert_eq!(tool_activity("dispatch_subagent", &dispatch),"Dispatching subagent: reviewer"diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex e8e3e2612..24c95f59e 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -441,11 +441,13 @@ export async function fillSubagentResult(}/**- * The model-visible blackboard directory. The session scratch is mounted over- * `/tmp` (see `scratch_display_path`), and the blackboard is its `blackboard`- * subdir (`spill::BLACKBOARD_DIR`), so a finished child's answer is read from- * `/tmp/blackboard/<name>.md`. Reported up front by the plan summary; each- * child's completion notice carries the exact path `writeBlackboard` returns.+ * The model-visible blackboard directory on Linux only, where the session+ * scratch is bound over `/tmp` (see `scratch_display_path`, whose `/tmp`+ * mapping is gated on `target_os = "linux"`), so a finished child's answer is+ * read from `/tmp/blackboard/<name>.md`. On macOS/Windows the scratch is a real+ * host path, so callers must not advertise this constant there. Reported up+ * front by the plan summary; each child's completion notice always carries the+ * exact path `writeBlackboard` returns.*/export const BLACKBOARD_DIR_DISPLAY = '/tmp/blackboard'diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsindex 8b65fc54a..6d596949f 100644--- a/web-app/src/lib/coworkSubagent.ts+++ b/web-app/src/lib/coworkSubagent.ts@@ -362,6 +362,16 @@ function ephemeralSubagentPrompt(name: string): string {* always on the blackboard. Mirrors `subagent.rs::PHASE_INPUT_MAX_BYTES`. */export const PHASE_INPUT_MAX_BYTES = 12 * 1024+/** Cap a finished child's answer to what a next-phase brief can hold before it+ * is retained in memory, so a plan never keeps arbitrarily large outputs across+ * its phases: `injectInputs` would truncate to the same bound at prompt-build+ * anyway, and the full answer is always on the blackboard (the brief header+ * points there). Mirrors the Rust read path, which never holds more than the+ * blackboard file it just read. */+function capRetainedAnswer(output: string): string {+ return truncateToBytes(output, PHASE_INPUT_MAX_BYTES).text+}+/** UTF-8 byte length of a single code point, without allocating. */function utf8Len(codePoint: number): number {if (codePoint <= 0x7f) return 1@@ -855,7 +865,9 @@ export async function runDispatchPlan(? await cb.writeBlackboard(req.name, result.output): nullcb.onComplete(id, req.name, result, savedPath)- return realAnswer ? { name: req.name, output: result.output } : null+ return realAnswer+ ? { name: req.name, output: capRetainedAnswer(result.output) }+ : null}))inputs = results.filter(diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 3dd8accc7..f16eab915 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -809,9 +809,16 @@ function CoworkPage() {}const model = transport.model- const blackboardDir = isPlatformTauri()- ? BLACKBOARD_DIR_DISPLAY- : null+ // `BLACKBOARD_DIR_DISPLAY` (/tmp/blackboard) is only where the+ // scratch surfaces on Linux, where the sandbox binds it over+ // /tmp (`scratch_display_path`). On macOS/Windows the scratch+ // is a real host path we don't know up front, so advertise no+ // dir there and let each completion notice carry the exact+ // path `writeBlackboard` returns.+ const blackboardDir =+ isPlatformTauri() && environment.os === 'linux'+ ? BLACKBOARD_DIR_DISPLAY+ : null// The plan hold keeps the run alive across the whole plan,// including the gap between one phase finishing and the next