Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): shell cwd, gate hardening, subagent worktree safety and TUI subagent steering (#9625)
Akarshan Biswasfeacc628fb73
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex bc9b694c4..ae686c36f 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -45,6 +45,8 @@ jan <COMMAND>| `--fork-session` | Open the resumed session as a new thread, leaving the original resumable || `--worktree` | Work in a dedicated git worktree instead of the project directory. Off by default || `--no-worktree` | Work in the project directory, overriding a persistent `worktree` setting |+| `--subagent-worktrees` | Give each subagent that can write its own git worktree unless it asks for another `workspace`. Off by default: it edits your checkout. See [Where a subagent works](/docs/agent/subagents#where-a-subagent-works) |+| `--no-subagent-worktrees` | Subagents edit your checkout, overriding `[agent].subagent_worktrees` || `--provider <ID>` | Target a specific provider for this run || `--api-key <KEY>` | API key for that provider || `--base-url <URL>` | Base URL for the `--provider` named, e.g. a gateway. Requires `--provider`. See [Using a gateway](/docs/agent/providers#using-a-gateway) |@@ -108,6 +110,8 @@ jan cli agent run --max-turns 5 --max-session-tokens 20000 "triage the build fai| `--fork-session` | Open the resumed session as a new thread, leaving the original resumable || `--worktree` | Work in a dedicated git worktree instead of the project directory. Off by default || `--no-worktree` | Work in the project directory, overriding a persistent `worktree` setting |+| `--subagent-worktrees` | Give each subagent that can write its own git worktree unless it asks for another `workspace`. Off by default: it edits your checkout |+| `--no-subagent-worktrees` | Subagents edit your checkout, overriding `[agent].subagent_worktrees` || `--max-turns <N>` | Hard cap on agentic turns. If the model is still calling tools at N the run fails with `reached the N-turn limit...` and exits `53`; with `--output-format json` the partial answer is still in `result`. Bounds the parent run only - subagent turns are not counted. `0` means unbounded, which is the default || `--max-session-tokens <N>` | Advisory token ceiling for this run, overriding `[budget].max_tokens`. Records a note when passed (it does not compact); it does not terminate the run. `0` means no ceiling || `--max-budget-usd <USD>` | Stop the run once it has spent this much, overriding `[budget].max_usd`. Priced from the provider's published rates, so a model with no published price is **refused** rather than run uncapped - including a subagent whose definition names its own model. Subagents inherit the ceiling. Compaction is billed against it like any other request. Stopping this way exits `0` with `stop_reason: budget_exceeded`; `0` as a limit stops at the first billed request |@@ -607,6 +611,38 @@ jan cli threads messages <THREAD_ID>jan cli threads delete <ID>```+## `jan cli worktrees`++See and prune the checkouts subagents left under `~/.jan/worktrees/<project>/` and their shared+build cache. The agent cannot clean these itself: its sandbox mounts `~/.jan` read-only.++```bash+jan cli worktrees list [--project <DIR>] [--json]+jan cli worktrees prune [--project <DIR>] [--build-cache] [--all --yes]+```++`list` prints each checkout's branch, size and state (in use by a live session, holds uncommitted+work, holds commits not in your repository, or removable), then the build cache and trash sizes.+`prune` removes only what is safe to remove, the same rule a session end uses: a clean checkout+whose commits are all in your repository (its branch is brought back first). Clean means no+changed, untracked or ignored file, except ignored build output (anything under `target/`,+`node_modules/`, `dist/`, `build/`, `.next/`, `__pycache__/`, `.venv/` or `.gradle/` that the+ignore rule naming that folder hides, and `*.o`, `*.pyc`, `*.class` files): an ignored `.env` or+local config keeps the checkout, listed as holding uncommitted work with the files named. Only a+rule in a `.gitignore` committed at the checkout's HEAD, unchanged since, names a folder; one the+subagent wrote (in a `.gitignore` it did not commit or edited, or in the checkout's+`.git/info/exclude`) exempts nothing, except the `*` that `python -m venv` writes into `.venv/`. A rule like `build/` matches at any depth, so ignored files+in a tracked folder such as `tools/build/` are treated as build output too (a `.env` or key there+still keeps the checkout). With+`--json`, an uncommitted checkout's `build_output` is an array of those build output paths and+`build_output_bytes` their size. What it removes is moved to the trash under the same+directory, kept 7 days and emptied at a later start. `--build-cache` also clears the build cache,+refused while any subagent may be building there or a live session holds a checkout of the+project. `--all --yes` deletes every checkout no live session holds at once, uncommitted work and+commits not in your repository included; committed branches are still brought back first, and a+checkout with uncommitted work whose branch cannot be brought back is kept. A checkout a live+session holds is never removed.+## `jan cli models`Print every configured provider's models as JSON, keys redacted.diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdxindex df63651bd..24fee4b65 100644--- a/docs/src/pages/docs/agent/project-config.mdx+++ b/docs/src/pages/docs/agent/project-config.mdx@@ -118,6 +118,8 @@ set `fallback_files = []`.# compaction_reserve_tokens = 16384 # absolute headroom instead, in tokens; wins over compaction_ratio# max_tokens = 4096# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO+# subagent_worktrees = false # true: a subagent that can write gets its own git worktree; false: it edits this checkout+# subagent_build_cache_max_gb = 20 # clear the subagents' shared build cache past this size; 0 never# show_reasoning = false # unfold thinking blocks in the transcript (Ctrl-O still toggles)# send_reasoning = true # resend prior reasoning to the model; false drops it from the request# worktree = true # give each session its own git checkout instead of editing this one@@ -165,6 +167,8 @@ The running agent reads this file at startup. After editing `context_window`, `c| `compaction_reserve_tokens` | unset | Absolute headroom instead of the ratio, in tokens. Wins over `compaction_ratio` when set || `max_tokens` | unset | Cap on tokens generated per response. Omitted from the request when unset || `max_parallel_subagents` | `10` | Subagents that may run at once (min 1); extra dispatches queue FIFO |+| `subagent_worktrees` | `false` | Give a subagent that can write or edit, and names no `workspace`, its own git worktree. Off, it works in your checkout, shared with other writers (nothing serializes them). `workspace: "new"` or a `ref` still get a worktree. Overridden by `--subagent-worktrees` / `--no-subagent-worktrees`. See [Where a subagent works](/docs/agent/subagents#where-a-subagent-works) |+| `subagent_build_cache_max_gb` | `20` | Size in GB past which the subagents' shared build cache (`cargo-target` under `~/.jan/worktrees/<project>/`) is moved to the trash, at session end or the next start, so the next build starts cold. Skipped while any subagent of any session may be building there. `0` never clears it. Falls back to the same key in `~/.jan/config.toml` || `thread_retention_days` | `90` | Saved threads untouched for this many days are deleted at session start, once `prune_threads = true` in `~/.jan/config.toml` turns pruning on (it is off by default); `0` disables. The newest few, the resumed thread, a fork's parent, worktree-owning threads and threads with no timestamp are always kept || `max_threads` | `500` | Most saved threads a project keeps; with pruning on, the oldest past it are deleted at session start, with the same exemptions. `0` disables || `show_reasoning` | `false` | Unfold model reasoning (`<thinking>`) blocks in the transcript instead of folding them to a summary row. <kbd>Ctrl</kbd>+<kbd>O</kbd> still toggles a folded block |diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex dcd64b972..ce943719c 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -40,6 +40,7 @@ Either form loads the skill's full instructions into the conversation (no separa| `/fork` | Branch this session at a past message into a new thread, keeping this one || `/tree` | Saved threads as a fork tree. Enter resumes one || `/worktree` | The dedicated checkout this session works in, what changed there, and its subagents' worktrees |+| `/worktrees` | This project's subagent checkouts under `~/.jan/worktrees/` (branch, size, and whether each is in use, holds uncommitted work, holds commits not in your repository, or is removable) and the shared build cache's size. Enter on **Remove what is safe to remove** applies the session-end rule and moves those checkouts to the trash (kept 7 days); **Clear build cache** deletes it unless a build may be running; Enter on a checkout removes it, asking first and naming what would be lost when it holds work (its uncommitted files, and its commits only when its branch cannot be brought back), then deleting it at once. An ignored file that is not build output, such as a `.env`, counts as uncommitted work. A checkout a running subagent, this session's settling, or another live session holds is never removed || `/quit` | Exit |See [Sessions](/docs/agent/sessions).diff --git a/docs/src/pages/docs/agent/subagents.mdx b/docs/src/pages/docs/agent/subagents.mdxindex c1ab68e45..2ff762802 100644--- a/docs/src/pages/docs/agent/subagents.mdx+++ b/docs/src/pages/docs/agent/subagents.mdx@@ -171,7 +171,14 @@ dispatch result says where each one works, for example`working in worktree ~/.jan/worktrees/jan-582afba2/general-3f2a (branch jan/agent/general-3f2a, from 587e06393); uncommitted changes in your checkout are not in it`or `working read-only in /home/you/src/jan`.-- **Writers get their own checkout.** A subagent whose tools include `write` or `edit` gets a fresh+- **Writers share your checkout, unless worktrees are on.** A subagent whose tools include `write`+ or `edit` works in your checkout, as you do, so writers dispatched together can overwrite each+ other's edits: give parallel writers disjoint files, or ask for `workspace: "new"`. Nothing+ serializes them. Set `subagent_worktrees = true` under `[agent]` in `agent.toml`, or pass+ `--subagent-worktrees` (`--no-subagent-worktrees` overrides the file), to give each its own+ checkout instead, as described next.+- **With subagent worktrees on, writers get their own checkout.** A subagent whose tools include+ `write` or `edit` gets a freshcheckout on a `jan/agent/<name>-<id>` branch, started from `HEAD`, under`~/.jan/worktrees/<project>/`. It is a repository of its own (a `git clone --shared`, not a linkedworktree), so two writers dispatched together never edit the same checkout, none of them sees your@@ -192,12 +199,16 @@ or `working read-only in /home/you/src/jan`.- Not a git repository, or no commits yet: every subagent works in your checkout (readers stillread-only), and the dispatch result says so.+The first writer bullet is the default. The rest of this page, from the checkout's branch to the+session-end sweep, applies to a checkout a subagent has: one made by subagent worktrees, `"new"`+or a `ref`.+A dispatch entry can choose with its optional `workspace` field:| `workspace` | Meaning || --- | --- || omitted | The default above |-| `"new"` | A fresh checkout |+| `"new"` | A fresh checkout, whether or not subagent worktrees are on || `"shared"` | Your checkout (read-only for a reader) || `"<earlier subagent name>"` | That subagent's workspace, for follow-ups or a reviewer of its work. Only one writer may be in a worktree at a time: a writer naming one that another writer is still in is refused, not queued, so dispatch it again once that one has finished || `{"ref": "<git ref>"}` | A fresh checkout at that ref, fetched from `origin` when it is not local (for example `pull/9486/head`). A fetch that has not finished within 60 seconds is stopped and the dispatch fails with that error |@@ -225,9 +236,20 @@ The main agent can read its subagents' checkouts with the file tools (`read`, `l`find`, `grep`), and from its shell only while that shell is sandboxed, where they are mountedread-only (`git -C <checkout> diff` works; an escalated command naming them is refused).-When the session ends, checkouts with no commits beyond their base and no uncommitted changes are-deleted. The rest are kept and named (their branches already fetched into your repository), and so-is any checkout git cannot read; `/worktree` lists them while the session runs.+When the session ends, a checkout with no uncommitted work whose commits (if any) are all on its+branch in your repository is moved to the trash under `~/.jan/worktrees/<project>/.trash`, kept 7+days and emptied at a later start. Uncommitted work includes untracked files and ignored files+that are not build output (`target/`, `node_modules/`, `dist/`, `build/`, `.next/`,+`__pycache__/`, `.venv/`, `.gradle/`, `*.o`, `*.pyc`, `*.class`), whatever ignore rule hides them,+the checkout's own `.git/info/exclude` included: an ignored `.env` keeps its checkout. The rest are+kept and named (their branches already fetched into your repository), and so is any checkout git+cannot read; `/worktree` lists them while the session runs, and `/worktrees` lists every checkout+of the project.++A subagent given the shared build directory holds a shared lock on+`~/.jan/worktrees/<project>/.meta/cargo-target.lock` while it runs, a reader in your own checkout+included, so no session clears the directory under a running build: the size cap and **Clear+build cache** both skip while any such lock is held.<Callout type="info">Because a subagent's context is separate, a long research task that would have crowded your sessiondiff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex a87112e24..1b6f7ef01 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -19,7 +19,7 @@ use app_lib::core::cli::{cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,cli_get_thread, cli_list_messages, cli_list_threads, cli_plugin_install, cli_plugin_list,cli_plugin_remove, cli_plugin_search, cli_web_search_reset, cli_web_search_set,- cli_web_search_status, ResumeRequest, SessionFlags,+ cli_web_search_status, cli_worktrees_list, cli_worktrees_prune, ResumeRequest, SessionFlags,};use std::fmt::Write as _;@@ -121,6 +121,14 @@ struct WorktreeArgs {/// Work in the project directory, overriding a persistent worktree setting#[arg(long, conflicts_with = "worktree")]no_worktree: bool,+ /// Give each subagent that can write its own git worktree, unless it asks+ /// for another workspace (default: it edits the session's checkout)+ #[arg(long)]+ subagent_worktrees: bool,+ /// Subagents edit the session's checkout, overriding a persistent+ /// [agent].subagent_worktrees setting+ #[arg(long, conflicts_with = "subagent_worktrees")]+ no_subagent_worktrees: bool,}impl WorktreeArgs {@@ -132,6 +140,15 @@ impl WorktreeArgs {_ => None,}}++ /// `None` when neither subagent flag was passed, so agent.toml decides.+ fn into_subagent_flag(self) -> Option<bool> {+ match (self.subagent_worktrees, self.no_subagent_worktrees) {+ (true, _) => Some(true),+ (_, true) => Some(false),+ _ => None,+ }+ }}impl SandboxArgs {@@ -429,6 +446,47 @@ enum CliCommands {#[command(subcommand)]cmd: McpCommands,},+ /// See and prune the project's subagent worktrees and their build cache+ #[command(display_order = 14)]+ Worktrees {+ #[command(subcommand)]+ cmd: WorktreesCommands,+ },+}++// -- Worktrees subcommands ---------------------------------------------------++/// The checkouts subagents left under ~/.jan/worktrees/<project>, which the+/// agent itself cannot reach (its sandbox mounts ~/.jan read-only).+#[derive(Subcommand)]+enum WorktreesCommands {+ /// List each checkout's branch, size and state, then the build cache+ List {+ /// Project root whose subagent worktrees to list+ #[arg(long, default_value = ".")]+ project: String,+ /// Print JSON instead of text+ #[arg(long)]+ json: bool,+ },+ /// Remove the checkouts that are safe to remove: clean, with every commit+ /// in your repository (committed branches are brought back first)+ Prune {+ /// Project root whose subagent worktrees to prune+ #[arg(long, default_value = ".")]+ project: String,+ /// Also clear the shared build cache (refused while a live session+ /// holds a checkout of the project, as it may be building there)+ #[arg(long)]+ build_cache: bool,+ /// Remove every checkout no live session holds, deleting uncommitted+ /// work and commits not in your repository; needs --yes+ #[arg(long, requires = "yes")]+ all: bool,+ /// Confirm --all+ #[arg(long, requires = "all")]+ yes: bool,+ },}// ── Agent subcommands ──────────────────────────────────────────────────────@@ -810,6 +868,7 @@ async fn main() {sandbox: cli.sandbox.into_flag(),allow_escalation: cli.sandbox.escalation_flag(),worktree: cli.worktree.into_flag(),+ subagent_worktrees: cli.worktree.into_subagent_flag(),..Default::default()},cli.resume.into_request(),@@ -1084,6 +1143,28 @@ async fn handle_cli(cmd: CliCommands) {std::process::exit(1);}}+ CliCommands::Worktrees { cmd } => handle_worktrees(cmd).await,+ }+}++// -- Worktrees handlers ------------------------------------------------------++async fn handle_worktrees(cmd: WorktreesCommands) {+ // Git per checkout and a walk of every file: off the async runtime.+ let result = tokio::task::spawn_blocking(move || match cmd {+ WorktreesCommands::List { project, json } => Ok(cli_worktrees_list(&project, json)),+ WorktreesCommands::Prune { project, build_cache, all, yes } => {+ cli_worktrees_prune(&project, build_cache, all && yes)+ }+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()));+ match result {+ Ok(text) => println!("{text}"),+ Err(e) => {+ eprintln!("Error: {e}");+ std::process::exit(1);+ }}}@@ -1129,6 +1210,7 @@ async fn run_agent(cmd: AgentCommands) -> Result<(), String> {sandbox: sandbox.into_flag(),allow_escalation: sandbox.escalation_flag(),worktree: worktree.into_flag(),+ subagent_worktrees: worktree.into_subagent_flag(),max_turns: budget.max_turns,max_session_tokens: budget.max_session_tokens,max_budget_usd: budget.max_budget_usd,@@ -1676,6 +1758,37 @@ mod tests {);}+ /// `--subagent-worktrees` and its opposite parse on the bare TUI and on+ /// `agent run`; neither leaves agent.toml in charge, and they exclude each other.+ #[test]+ fn subagent_worktree_flags_parse_on_both_surfaces() {+ let bare = |extra: &[&str]| {+ let mut argv = vec!["jan"];+ argv.extend_from_slice(extra);+ Cli::parse_from(argv).worktree.into_subagent_flag()+ };+ assert_eq!(bare(&[]), None);+ assert_eq!(bare(&["--subagent-worktrees"]), Some(true));+ assert_eq!(bare(&["--no-subagent-worktrees"]), Some(false));+ let run = |extra: &[&str]| {+ let mut argv = vec!["jan", "cli", "agent", "run", "task"];+ argv.extend_from_slice(extra);+ match Cli::parse_from(argv).command {+ Some(Commands::Cli {+ cmd:+ CliCommands::Agent {+ cmd: AgentCommands::Run { worktree, .. },+ },+ }) => worktree.into_subagent_flag(),+ _ => panic!("expected `cli agent run`"),+ }+ };+ assert_eq!(run(&[]), None);+ assert_eq!(run(&["--subagent-worktrees"]), Some(true));+ assert_eq!(run(&["--no-subagent-worktrees"]), Some(false));+ assert!(Cli::try_parse_from(["jan", "--subagent-worktrees", "--no-subagent-worktrees"]).is_err());+ }+/// Parse `jan cli agent run <task> <extra...>` and pull out its input format.fn parsed_input_format(extra: &[&str]) -> InputFormat {let mut argv = vec!["jan", "cli", "agent", "run", "task"];@@ -1978,6 +2091,48 @@ mod tests {));}+ #[test]+ fn worktrees_list_parses_with_its_defaults() {+ let cli = Cli::parse_from(["jan", "cli", "worktrees", "list"]);+ assert!(matches!(+ cli.command,+ Some(Commands::Cli {+ cmd: CliCommands::Worktrees {+ cmd: WorktreesCommands::List { ref project, json: false }+ }+ }) if project == "."+ ));+ let cli = Cli::parse_from(["jan", "cli", "worktrees", "list", "--json"]);+ assert!(matches!(+ cli.command,+ Some(Commands::Cli {+ cmd: CliCommands::Worktrees { cmd: WorktreesCommands::List { json: true, .. } }+ })+ ));+ }++ /// `prune` is safe by default; removing work takes `--all --yes`, both.+ #[test]+ fn worktrees_prune_needs_all_and_yes_together_to_remove_work() {+ let prune = |extra: &[&str]| {+ let mut argv = vec!["jan", "cli", "worktrees", "prune"];+ argv.extend_from_slice(extra);+ Cli::try_parse_from(argv).map(|cli| match cli.command {+ Some(Commands::Cli {+ cmd: CliCommands::Worktrees {+ cmd: WorktreesCommands::Prune { build_cache, all, yes, .. },+ },+ }) => (build_cache, all, yes),+ _ => panic!("not worktrees prune"),+ })+ };+ assert_eq!(prune(&[]).ok(), Some((false, false, false)));+ assert_eq!(prune(&["--build-cache"]).ok(), Some((true, false, false)));+ assert_eq!(prune(&["--all", "--yes"]).ok(), Some((false, true, true)));+ assert!(prune(&["--all"]).is_err(), "--all alone is refused");+ assert!(prune(&["--yes"]).is_err(), "--yes alone is refused");+ }+#[test]fn login_command_parses_and_takes_no_args() {let cli = Cli::parse_from(["jan", "login"]);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex a9a1e0665..c779f0d54 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -91,7 +91,7 @@ fn with_renamed_tool_notices(for notice in hooks.renamed_notices(tool) {crate::tools::handlers::insert_before_exit_marker(&mut content,- &format!("\n[hook config: {notice}]"),+ &format!("\n{} {notice}]", crate::tools::hooks::NOTICE_TAG),);}content@@ -944,9 +944,18 @@ async fn execute_tool_inner(Decision::HardDeny(gate::DenyReason::Policy) => {return Err(format!("tool '{name}' is denied by policy").into());}- Decision::HardDeny(gate::DenyReason::Hidden) => {+ // No held shell cwd here, so `HiddenShellCwd` never comes up.+ Decision::HardDeny(gate::DenyReason::Hidden | gate::DenyReason::HiddenShellCwd) => {return Err(format!("tool '{name}' is denied: the Jan home (~/.jan) is hidden").into());}+ Decision::HardDeny(gate::DenyReason::TooComplex) => {+ return Err(format!(+ "tool '{name}' is denied: the command or path is too large or deeply nested to \+ check; split it or shorten the path, or \+ write a long script to a file and run that"+ )+ .into());+ }// An exec prompt asks the user to vouch for a command that could reach// anything. Under an enforcing sandbox it cannot: writes stay in the// thread workspace and $HOME is unreadable, so the containment the promptdiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 255885cbf..d8d7e59b6 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -5,7 +5,8 @@ use serde::{Deserialize, Serialize};use crate::permissions::ToolPermissions;use crate::tools::cmdscan::{normalize, scan_command, CommandScan};use crate::tools::sandbox::{- escapes_read_roots, escapes_write_roots, hidden_tokens, in_attached_root, in_hidden_root,+ canonicalize_metered, escapes_roots_metered, hidden_tokens, resolve_cost, HiddenRoot, Meter,+ MAX_RESOLVE_COST,};use crate::tools::{BuiltinTool, Capability};@@ -136,6 +137,18 @@ pub enum DenyReason {Policy,/// The call reaches the Jan home (`~/.jan`), hidden from every tool.Hidden,+ /// An escalated shell call would start in the held shell cwd, which is in+ /// the Jan home or above it. Told apart from [`DenyReason::Hidden`]+ /// because the command itself may name nothing hidden: the fix is to+ /// move the shell back, which a message has to say.+ HiddenShellCwd,+ /// The command, or a path argument, is too large or deeply nested to+ /// resolve within the gate's budget (see+ /// [`crate::tools::sandbox::MAX_RESOLVE_COST`]), so it cannot be shown to+ /// stay out of the Jan home. Told apart from [`DenyReason::Hidden`]+ /// because the call may name nothing hidden: the fix is to simplify it,+ /// not to avoid a path.+ TooComplex,}#[derive(Debug, PartialEq, Eq)]@@ -178,10 +191,46 @@ pub fn resolve_decision(ctx: &GateContext,perms: &ToolPermissions,grants: &SessionGrants,+) -> Decision {+ resolve_decision_with_cwd(tool, args, ctx, None, perms, grants)+}++/// [`resolve_decision`] for a session whose shell holds a directory a `cd`+/// moved it to (`ToolContext::shell_cwd`; `None` is the project root). A+/// confined shell command's relative tokens name paths under that directory,+/// so `cat .jan/config.toml` after `cd ~` must be checked there; an escalated+/// command starts in the held directory as well. Every other tool still+/// resolves against the project root.+pub fn resolve_decision_with_cwd(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ ctx: &GateContext,+ shell_cwd: Option<&Path>,+ perms: &ToolPermissions,+ grants: &SessionGrants,) -> Decision {if perms.is_denied(tool.name) {return Decision::HardDeny(DenyReason::Policy);}+ // One budget for every path this decision resolves, with or without a+ // hidden root: the escape checks below walk the path arguments too, and+ // with the sandbox off they are the only walk. Each walk charges the+ // meter what it really does.+ let meter = Meter::new(MAX_RESOLVE_COST);+ // Estimated from the text first, so a path argument too deep on its+ // face (whose missing tail a walk would append for free) is refused+ // without a syscall. A cap, not a charge: charging it as well made each+ // path argument pay twice, so the deepest one that fit was ~1650+ // components rather than the 2048 the budget is sized for.+ let root_depth = ctx.project_root.components().count();+ let path_cost = tool+ .path_args+ .iter()+ .filter_map(|key| args.get(key).and_then(|v| v.as_str()))+ .fold(0usize, |sum, p| sum.saturating_add(resolve_cost(root_depth, p)));+ if path_cost > MAX_RESOLVE_COST {+ return Decision::HardDeny(DenyReason::TooComplex);+ }// Ahead of allow rules and session grants, so neither an allowed tool name// nor a routine "allow writes" approval reaches keys, hooks or the agent's// own permissions.@@ -194,28 +243,100 @@ pub fn resolve_decision(// otherwise `rm -rf` on a child's worktree would be one prompt away.let shell_reads_only = tool.capability == Capability::Exec&& !requests_escalation(tool, args);- let carved = |p: &str| match tool.capability {- Capability::Read => {- in_attached_root(ctx.project_root, ctx.read_roots, p)- }- Capability::Exec if shell_reads_only => {- in_attached_root(ctx.project_root, ctx.read_roots, p)- && !in_attached_root(ctx.project_root, ctx.write_roots, p)+ // An escalated command starts in the held directory too, so its+ // relative tokens resolve there as well.+ let base = shell_cwd+ .filter(|_| tool.capability == Capability::Exec)+ .unwrap_or(ctx.project_root);+ // Carved out against the same base as the hidden check: a shell held+ // in an attached root under the home splits every word of a command+ // (`ls` too) into a token there, and each must be carved out by the+ // root it lands in, or nothing could run until the shell left.+ // Resolved once for the decision, not once per token.+ let hidden_root = HiddenRoot::new(ctx.project_root, base, hidden, &meter).map(|h| {+ match tool.capability {+ Capability::Read => h.carving(ctx.read_roots, &[], &meter),+ Capability::Exec if shell_reads_only => {+ h.carving(ctx.read_roots, ctx.write_roots, &meter)+ }+ _ => h,}- _ => false,- };- let hidden_hit = |p: &str| {- in_hidden_root(ctx.project_root, hidden, p) && !carved(p)- };+ });+ // A path the meter ran out on reads as not hidden here; the decision+ // checks `meter.spent()` before it trusts any of these answers.+ let hidden_hit = |p: &str| hidden_root.as_ref().is_some_and(|h| h.holds(p, &meter));let hits_path = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str()).is_some_and(hidden_hit)});- let hits_command = tool.capability == Capability::Exec- && args.get("command").and_then(|v| v.as_str()).is_some_and(|c| {- hidden_tokens(hidden, c).into_iter().any(|t| hidden_hit(&t))- });+ // A command too complex to scan in bounded time (`None`) cannot be+ // shown to stay out of the home, so it is refused with its own+ // reason (`TooComplex`) telling the model to simplify it. Checked+ // ahead of `HiddenShellCwd`, so that refusal does not reset the held+ // cwd; the next, simpler command gets it.+ //+ // Not covered: a link the model made earlier to `/proc/self/cwd`+ // (`ln -s /proc/self/cwd l`, then an escalated `cat l/../../.jan/x`).+ // Resolving the token follows `/proc/self` as Jan's own process, not+ // the shell's, so the climb is checked from Jan's cwd and passes; the+ // user still approves the escalation, and a confined run is masked.+ let tokens = match args.get("command").and_then(|v| v.as_str()) {+ Some(c) if tool.capability == Capability::Exec => match hidden_tokens(hidden, c) {+ Some(tokens) => tokens,+ None => return Decision::HardDeny(DenyReason::TooComplex),+ },+ _ => Vec::new(),+ };+ // Each distinct token once: the words of a long heredoc mostly+ // repeat, and the answer for a word does not change within the call.+ let tokens: std::collections::HashSet<&str> = tokens.iter().map(String::as_str).collect();+ // Estimated from the text before any is resolved, so a command too+ // large on its face (one deep path whose missing tail the walk+ // would append for free) is refused without a syscall. Not charged:+ // the walks charge the meter what they really do, a link into a+ // deep directory included. Each token is resolved against `base`,+ // the held cwd for a shell.+ let base_depth = base.components().count();+ let token_cost = tokens+ .iter()+ .fold(path_cost, |sum, t| sum.saturating_add(resolve_cost(base_depth, t)));+ if token_cost > MAX_RESOLVE_COST {+ return Decision::HardDeny(DenyReason::TooComplex);+ }+ let hits_command = tokens.iter().any(|t| hidden_hit(t));+ // An escalated command runs on the host from the held directory+ // whatever it names, so that directory is a token too: one in the+ // home (an attached worktree there, or a link swapped in for it)+ // would let a bare `cat config.toml` reach it. One above the home+ // reaches it by a relative path no token scan catches in every+ // spelling, and no escalated command needs to start there. Without+ // a held directory it starts in the project root, which the+ // worktree exception keeps reachable, as before.+ //+ // Not covered: a project root that is itself above the home (the+ // home's parent opened as a project) with no held directory is not+ // denied for where it starts, so relative spellings no token scan+ // catches reach the home from there. Pre-existing and the same as+ // before held directories existed; only a held one is refused here.+ let starts_hidden = |held: &Path| {+ let above = hidden_root+ .as_ref()+ .zip(canonicalize_metered(held, &meter).ok())+ .map_or(true, |(hidden, held)| hidden.path().starts_with(held));+ above || hidden_hit(".")+ };+ let held_hidden = !shell_reads_only+ && tool.capability == Capability::Exec+ && shell_cwd.is_some_and(starts_hidden);+ // Ahead of `HiddenShellCwd`, so that refusal does not reset the held+ // cwd when the answers it rests on were cut short.+ if meter.spent() {+ return Decision::HardDeny(DenyReason::TooComplex);+ }+ if held_hidden {+ return Decision::HardDeny(DenyReason::HiddenShellCwd);+ }if hits_path || hits_command {return Decision::HardDeny(DenyReason::Hidden);}@@ -238,15 +359,9 @@ pub fn resolve_decision(// Read roots widen only this branch; the Write branch below widens// only by `write_roots`, so an attached folder is writable exactly// when the caller marked it so.- let escapes = tool.path_args.iter().any(|key| {- args.get(key)- .and_then(|v| v.as_str())- .map(|p| {- escapes_read_roots(ctx.project_root, ctx.scratch, ctx.read_roots, p)- .unwrap_or(true)- })- .unwrap_or(false)- });+ let Some(escapes) = escapes_any(tool, args, ctx, ctx.read_roots, &meter) else {+ return Decision::HardDeny(DenyReason::TooComplex);+ };if !escapes || grants.covers(PromptKind::ReadEscape) {Decision::Allow} else {@@ -266,15 +381,9 @@ pub fn resolve_decision(// this branch exactly the way read roots widen the Read branch; a// caller that passes none keeps the unchanged `escapes_project`.Capability::Write => {- let escapes = tool.path_args.iter().any(|key| {- args.get(key)- .and_then(|v| v.as_str())- .map(|p| {- escapes_write_roots(ctx.project_root, ctx.scratch, ctx.write_roots, p)- .unwrap_or(true)- })- .unwrap_or(false)- });+ let Some(escapes) = escapes_any(tool, args, ctx, ctx.write_roots, &meter) else {+ return Decision::HardDeny(DenyReason::TooComplex);+ };if escapes {if grants.covers(PromptKind::WriteEscape) {Decision::Allow@@ -296,6 +405,26 @@ pub fn resolve_decision(}}+/// True iff a path argument of the call escapes the project, the scratch+/// and `roots` (one that fails to resolve counts as escaping). `None` when+/// `meter` ran out on the way: the answer is unknown, and the caller refuses+/// the call as too complex rather than let a cut-short check read as an+/// escape it could grant or as inside the project.+fn escapes_any(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ ctx: &GateContext,+ roots: &[PathBuf],+ meter: &Meter,+) -> Option<bool> {+ let escapes = tool.path_args.iter().any(|key| {+ args.get(key).and_then(|v| v.as_str()).is_some_and(|p| {+ escapes_roots_metered(ctx.project_root, ctx.scratch, roots, p, meter).unwrap_or(true)+ })+ });+ (!meter.spent()).then_some(escapes)+}+fn gated(kind: PromptKind, grants: &SessionGrants) -> Decision {if grants.covers(kind) {Decision::Allow@@ -1188,6 +1317,181 @@ mod tests {let _ = std::fs::remove_dir_all(&home);}+ /// The gate's time is bounded for any argument a model can send. A path+ /// within the budget is decided as before; one past it (a path argument+ /// had no cap at all, and a command just under the scan's caps can be one+ /// deep path) is refused as too complex instead of taking minutes.+ #[test]+ fn a_deep_path_is_decided_quickly() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let path = |n: usize| format!("missing/{}", format!("{}/", "a".repeat(63)).repeat(n));+ let (fits, deep) = (path(1500), path(60_000));+ let cat = |p: &str| json!({"command": format!("cat {p}")});+ let perms = ToolPermissions::default();+ let grants = SessionGrants::default();+ let refused = || Decision::HardDeny(DenyReason::TooComplex);+ for (tool, args, want) in [+ ("read", json!({"path": fits}), Decision::Allow),+ ("shell", cat(&fits), Decision::Prompt(PromptKind::Exec)),+ ("read", json!({"path": deep}), refused()),+ ("write", json!({"path": deep, "content": ""}), refused()),+ ("shell", cat(&deep), refused()),+ ] {+ let start = std::time::Instant::now();+ let d = resolve_decision(lookup(tool).unwrap(), &args, &ctx, &perms, &grants);+ let took = start.elapsed();+ assert_eq!(d, want, "{tool}");+ assert!(took < std::time::Duration::from_secs(5), "{tool}: {took:?}");+ }+ // Without a hidden root a path argument is still resolved, so the+ // budget applies there too.+ let open = GateContext { hidden_root: None, ..ctx };+ let args = json!({"path": path(60_000)});+ let d = resolve_decision(lookup("read").unwrap(), &args, &open, &perms, &grants);+ assert_eq!(d, refused());+ let _ = std::fs::remove_dir_all(&home);+ }++ /// A short token through a link into a deep directory is cheap as text+ /// but walks the whole target, so the budget meters the real walk: many+ /// distinct such tokens (which ordinary approved commands can set up)+ /// stalled the gate for minutes before ending in an exec prompt.+ #[cfg(target_os = "linux")]+ #[test]+ fn tokens_through_a_link_into_a_deep_directory_are_decided_quickly() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ let project = home.join("proj");+ let deep = project.join("d").join("a/".repeat(1500));+ std::fs::create_dir_all(&deep).unwrap();+ std::os::unix::fs::symlink(&deep, project.join("l")).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let words: Vec<String> = (0..500).map(|n| format!("l/w{n}")).collect();+ let args = json!({"command": format!("cat {}", words.join(" "))});+ let start = std::time::Instant::now();+ let d = resolve_decision(+ lookup("shell").unwrap(),+ &args,+ &ctx,+ &ToolPermissions::default(),+ &SessionGrants::default(),+ );+ let took = start.elapsed();+ assert_eq!(d, Decision::HardDeny(DenyReason::TooComplex));+ assert!(took < std::time::Duration::from_secs(5), "{took:?}");+ // A few such tokens are ordinary work and still decided as before.+ let few = json!({"command": "cat l/x l/y"});+ let d = resolve_decision(+ lookup("shell").unwrap(),+ &few,+ &ctx,+ &ToolPermissions::default(),+ &SessionGrants::default(),+ );+ assert_eq!(d, Decision::Prompt(PromptKind::Exec));+ let _ = std::fs::remove_dir_all(&home);+ }++ /// With no hidden root (the sandbox off) the escape checks are the only+ /// walk of a path argument, and are metered too: a read or write path+ /// through a chain of links, each leading back into a deep directory,+ /// took the gate 20 s. It is refused as too complex instead, never let+ /// through on a check cut short; a shallow path is decided as before.+ #[cfg(target_os = "linux")]+ #[test]+ fn a_path_through_links_into_a_deep_directory_is_decided_quickly_unsandboxed() {+ let project = std::fs::canonicalize(unique_root()).unwrap();+ let deep = project.join("a/".repeat(1900));+ std::fs::create_dir_all(&deep).unwrap();+ std::os::unix::fs::symlink(&deep, deep.join("l0")).unwrap();+ for n in 1..30 {+ let prev = deep.join(format!("l{}", n - 1));+ std::os::unix::fs::symlink(prev, deep.join(format!("l{n}"))).unwrap();+ }+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: None,+ };+ let perms = ToolPermissions::default();+ let grants = SessionGrants::default();+ let chained = deep.join("l29/x").to_string_lossy().into_owned();+ for (tool, args) in [+ ("read", json!({"path": chained})),+ ("write", json!({"path": chained, "content": ""})),+ ] {+ let start = std::time::Instant::now();+ let d = resolve_decision(lookup(tool).unwrap(), &args, &ctx, &perms, &grants);+ let took = start.elapsed();+ assert_eq!(d, Decision::HardDeny(DenyReason::TooComplex), "{tool}");+ assert!(took < std::time::Duration::from_secs(5), "{tool}: {took:?}");+ }+ let shallow = json!({"path": "a/a/x"});+ let d = resolve_decision(lookup("read").unwrap(), &shallow, &ctx, &perms, &grants);+ assert_eq!(d, Decision::Allow);+ let _ = std::fs::remove_dir_all(&project);+ }++ /// Realistic large calls stay well inside the budget: a long prose or+ /// path-filled heredoc, a long `find`, and a deeply held shell cwd.+ #[test]+ fn realistic_large_commands_fit_the_budget() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ let project = home.join("proj");+ let held = project.join("l/".repeat(15));+ std::fs::create_dir_all(&held).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let words = "the quick brown fox jumps over the lazy dog and keeps going ";+ let prose = format!("cat <<E > notes.md\n{}E\n", words.repeat(300_000 / words.len()));+ let paths = format!("cat <<E > notes.md\n{}E\n", "see src/a/b/c.rs here\n".repeat(2000));+ let find = format!("find .{}", " -path ./src/a/b/c.rs -o".repeat(2000));+ let many = format!("cat <<E > notes.md\n{}E\n", "word ".repeat(100_000));+ let shell = |c: &str, cwd: Option<&Path>| {+ resolve_decision_with_cwd(+ lookup("shell").unwrap(),+ &json!({"command": c}),+ &ctx,+ cwd,+ &ToolPermissions::default(),+ &SessionGrants::default(),+ )+ };+ for c in [&prose, &paths, &find, &many] {+ for cwd in [None, Some(held.as_path())] {+ assert_eq!(shell(c, cwd), Decision::Prompt(PromptKind::Exec), "{}", &c[..40]);+ }+ }+ let _ = std::fs::remove_dir_all(&home);+ }+/// The Cowork opt-in at the gate layer: an attached root also passed as a/// write root takes the ordinary in-project Write prompt, not WriteEscape,/// while a path outside both roots keeps the escape classification.@@ -1259,4 +1563,439 @@ mod tests {let _ = std::fs::remove_dir_all(d);}}++ /// After `cd ~` a relative token names a path under the held directory,+ /// so `cat .jan/config.toml` reaches the Jan home even though the project+ /// root has no `.jan` of its own.+ #[test]+ fn a_held_shell_cwd_resolves_relative_tokens_for_the_hidden_deny() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let cat = json!({"command": "cat .jan/config.toml"});+ let gate = |tool, args: &serde_json::Value, held: Option<&Path>| {+ resolve_decision_with_cwd(tool, args, &ctx, held, &perms, &grants)+ };+ assert_eq!(gate(shell, &cat, None), Decision::Prompt(PromptKind::Exec), "no .jan here");+ assert_eq!(gate(shell, &cat, Some(&home)), Decision::HardDeny(DenyReason::Hidden));+ // An escalated command starts in the held dir too, and the hidden+ // deny runs ahead of the escalate prompt. Held above the home, it is+ // refused for where it starts, whatever it names.+ let start = Decision::HardDeny(DenyReason::HiddenShellCwd);+ let escalated = json!({"command": "cat .jan/config.toml", ESCALATE_ARG: true});+ assert_eq!(gate(shell, &escalated, Some(&home)), start);+ assert_eq!(gate(shell, &escalated, None), Decision::Prompt(PromptKind::Escalate));+ // A substitution's closing `)` is no command boundary: the word after+ // it is still an argument, and is checked.+ let tar = json!({+ "command": "tar czf backup-\"$(date +%F)\".tgz .jan",+ ESCALATE_ARG: true,+ });+ assert_eq!(gate(shell, &tar, Some(&home)), start);+ let plain = json!({"command": "/bin/true", ESCALATE_ARG: true});+ assert_eq!(gate(shell, &plain, Some(&home)), start);+ // Confined, the sandbox masks the home wherever the shell stands.+ let plain = json!({"command": "/bin/true"});+ assert_eq!(gate(shell, &plain, Some(&home)), Decision::Prompt(PromptKind::Exec));+ // Other tools resolve against the project root whatever the shell holds.+ let read = json!({"path": ".jan/config.toml"});+ assert_eq!(gate(lookup("read").unwrap(), &read, Some(&home)), Decision::Allow);+ let _ = std::fs::remove_dir_all(&home);+ }++ /// The worktree exception stays keyed on the project root: a relative+ /// token that climbs out of the worktree from the held directory lands in+ /// the Jan home and is refused, though the same token read from the+ /// project root would climb above the home and pass.+ #[test]+ fn a_held_shell_cwd_resolves_relative_tokens_for_the_worktree_escape() {+ let home = unique_root();+ let jan = home.join(".jan");+ let worktree = jan.join("worktrees/proj/wt");+ let held = worktree.join("src");+ std::fs::create_dir_all(&held).unwrap();+ std::fs::write(jan.join("notes.txt"), b"k").unwrap();+ std::fs::write(home.join("notes.txt"), b"x").unwrap();+ let ctx = GateContext {+ project_root: &worktree,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let cat = json!({"command": "cat ../../../../notes.txt"});+ let gate = |held: Option<&Path>| {+ resolve_decision_with_cwd(shell, &cat, &ctx, held, &perms, &grants)+ };+ assert_eq!(gate(None), Decision::Prompt(PromptKind::Exec));+ assert_eq!(gate(Some(&held)), Decision::HardDeny(DenyReason::Hidden));+ let _ = std::fs::remove_dir_all(&home);+ }++ /// A parent held in a child's worktree (an attached read root under the+ /// Jan home, which the sandbox mounts) can still run confined commands+ /// there and leave it: every word, the command name too, resolves into+ /// the home from there, and is carved out by the same root. The rest of+ /// the home stays refused. An escalated command gets no carve-out, so+ /// from there even its command name hits the home: refused, which fails+ /// closed, and a confined `cd` out is always open.+ #[test]+ fn a_held_shell_cwd_in_an_attached_root_under_the_home_is_not_denied() {+ let home = unique_root();+ let jan = home.join(".jan");+ let child = jan.join("worktrees/proj/general-2");+ std::fs::create_dir_all(&child).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let roots = vec![child.clone()];+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &roots,+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |command: &str, escalate: bool| {+ let args = json!({"command": command, ESCALATE_ARG: escalate});+ resolve_decision_with_cwd(shell, &args, &ctx, Some(&child), &perms, &grants)+ };+ let start = Decision::HardDeny(DenyReason::HiddenShellCwd);+ let leave = format!("cd '{}'", project.display());+ let leave = leave.as_str();+ for command in ["ls", "ls -la .", "git diff", "cat src/x", "cd", "cd /", leave] {+ assert_eq!(gate(command, false), Decision::Prompt(PromptKind::Exec), "{command}");+ assert_eq!(gate(command, true), start, "{command}");+ }+ // Out of the root it is the home again.+ let climb = "cat ../../../config.toml";+ assert_eq!(gate(climb, false), Decision::HardDeny(DenyReason::Hidden));+ // An escalated command may not name the child's tree: it leaves the+ // sandbox that mounts it read-only.+ assert_eq!(gate("rm -rf src", true), start);+ // Nor start there with only absolute words: its start dir is in the+ // home whatever it names.+ assert_eq!(gate("/bin/true", true), start);+ // `/proc/self/cwd` is where the command starts, not Jan's own cwd.+ let leak = format!(+ "/usr/bin/cp /proc/self/cwd/../../../config.toml {}",+ project.join("leak").display()+ );+ assert_eq!(gate(&leak, true), start);+ assert_eq!(gate(&leak, false), Decision::HardDeny(DenyReason::Hidden));+ let _ = std::fs::remove_dir_all(&home);+ }++ /// `/proc/self/cwd` names the shell's own start directory, not Jan's: a+ /// command spelling a path through it is checked as if it were relative,+ /// with or without a held directory.+ #[cfg(unix)]+ #[test]+ fn proc_self_cwd_resolves_against_where_the_shell_starts() {+ let home = std::fs::canonicalize(unique_root()).unwrap();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |root: &Path, command: &str, escalate: bool, held: Option<&Path>| {+ let ctx = GateContext {+ project_root: root,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let args = json!({"command": command, ESCALATE_ARG: escalate});+ resolve_decision_with_cwd(shell, &args, &ctx, held, &perms, &grants)+ };+ let hidden = Decision::HardDeny(DenyReason::Hidden);+ let spellings = [+ "/bin/cat /proc/self/cwd/.jan/config.toml",+ "/bin/cat /proc/thread-self/cwd/.jan/config.toml",+ "/bin/cat //proc/./self/cwd/.jan/config.toml",+ "/bin/tar cf /dev/null /proc/self/cwd/.jan",+ ];+ let start = Decision::HardDeny(DenyReason::HiddenShellCwd);+ for command in spellings {+ // Held in the home's parent after a confined `cd ..`; escalated,+ // that start dir alone is refused.+ assert_eq!(gate(&project, command, false, Some(&home)), hidden, "{command}");+ assert_eq!(gate(&project, command, true, Some(&home)), start, "{command}");+ // No held directory: the shell starts in the project root, here+ // the home itself.+ assert_eq!(gate(&home, command, true, None), hidden, "{command}");+ assert_eq!(gate(&home, command, false, None), hidden, "{command}");+ // From a project with no `.jan` of its own it names nothing hidden.+ assert_eq!(+ gate(&project, command, true, None),+ Decision::Prompt(PromptKind::Escalate),+ "{command}"+ );+ }+ let _ = std::fs::remove_dir_all(&home);+ }++ /// Every spelling of the shell's start directory is checked as that+ /// directory: `$PWD` and `~+` (and `~-`, failing closed), any+ /// `/proc/<pid>/cwd` however the pid and the path up to it are spelled,+ /// `/proc/<pid>/root` re-entering `/proc`, and a directory fd opened on+ /// it. From a held `proj/sub` each climbs into the home; with nothing+ /// held the same spellings one level shorter do from the project root.+ #[test]+ fn every_spelling_of_the_start_dir_is_checked_as_it() {+ let home = std::fs::canonicalize(unique_root()).unwrap();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ let sub = project.join("sub");+ std::fs::create_dir_all(&sub).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |command: &str, escalate: bool, held: Option<&Path>| {+ let args = json!({"command": command, ESCALATE_ARG: escalate});+ resolve_decision_with_cwd(shell, &args, &ctx, held, &perms, &grants)+ };+ let hidden = Decision::HardDeny(DenyReason::Hidden);+ let spellings = [+ "/bin/cat /proc/$$/cwd/UP.jan/config.toml",+ "/bin/cat /proc/$BASHPID/cwd/UP.jan/config.toml",+ "/bin/cat /proc/1/cwd/UP.jan/config.toml",+ "/bin/cat /proc/self/../self/cwd/UP.jan/config.toml",+ "/bin/cat /proc/self/root/proc/self/cwd/UP.jan/config.toml",+ "/bin/cat /proc/self/task/1/cwd/UP.jan/config.toml",+ "/bin/cat /proc/self/task/1/root/proc/self/cwd/UP.jan/config.toml",+ "/bin/cat $PWD/UP.jan/config.toml",+ "/bin/cat ${PWD}/UP.jan/config.toml",+ "/bin/cat ~+/UP.jan/config.toml",+ "/bin/cat ~-/UP.jan/config.toml",+ "/bin/cat ~+0/UP.jan/config.toml",+ "/bin/cat ~-0/UP.jan/config.toml",+ "/bin/cat $OLDPWD/UP.jan/config.toml",+ "exec 3<.; /bin/cat /dev/fd/3/UP.jan/config.toml",+ "exec 3<.; /bin/cat /proc/self/fd/3/UP.jan/config.toml",+ "exec 0<.; /bin/cat /dev/stdin/UP.jan/config.toml",+ ];+ for spelling in spellings {+ let from_sub = spelling.replace("UP", "../../");+ for escalate in [true, false] {+ assert_eq!(gate(&from_sub, escalate, Some(&sub)), hidden, "{from_sub}");+ }+ let from_root = spelling.replace("UP", "../");+ for escalate in [true, false] {+ assert_eq!(gate(&from_root, escalate, None), hidden, "{from_root}");+ }+ // From the held directory one level is not enough to leave the+ // project, so nothing hidden is named.+ assert_eq!(+ gate(&from_root, true, Some(&sub)),+ Decision::Prompt(PromptKind::Escalate),+ "{from_root}"+ );+ }+ // A relative path climbing into `/proc` is the same link.+ let climb = format!("/bin/cat {}proc/self/cwd/../.jan/config.toml", "../".repeat(12));+ assert_eq!(gate(&climb, true, None), hidden);+ let _ = std::fs::remove_dir_all(&home);+ }++ /// The kernel follows a link under `/proc` or `/dev` (`/proc/net`,+ /// `/proc/thread-self`, `/dev/fd`) before it applies a `..` after it, so+ /// lexical normalization lands somewhere else than the shell does: any+ /// `cwd` or `fd/<n>` after such a `..` is checked as the start dir. A+ /// plain read under `/proc` or `/dev` is not touched.+ #[test]+ fn a_dotdot_after_a_proc_or_dev_link_is_checked_as_the_start_dir() {+ let home = std::fs::canonicalize(unique_root()).unwrap();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ let sub = project.join("sub");+ std::fs::create_dir_all(&sub).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |command: &str, escalate: bool| {+ let args = json!({"command": command, ESCALATE_ARG: escalate});+ resolve_decision_with_cwd(shell, &args, &ctx, Some(&sub), &perms, &grants)+ };+ let hidden = Decision::HardDeny(DenyReason::Hidden);+ for command in [+ "/bin/cat /proc/net/../cwd/../../.jan/config.toml",+ "/bin/cat /dev/fd/../cwd/../../.jan/config.toml",+ "/bin/cat /proc/thread-self/../../cwd/../../.jan/config.toml",+ "/bin/cat /proc/self/net/../fd/3/../../.jan/config.toml",+ "/bin/cat /proc/mounts/../cwd/../../.jan/config.toml",+ ] {+ for escalate in [true, false] {+ assert_eq!(gate(command, escalate), hidden, "{command}");+ }+ }+ for command in [+ "cat /proc/cpuinfo",+ "ls /proc/self/fd",+ "cat /proc/*/status",+ "ls /dev/null",+ "cat /proc/self/cwd/README.md",+ ] {+ assert_eq!(gate(command, true), Decision::Prompt(PromptKind::Escalate), "{command}");+ assert_eq!(gate(command, false), Decision::Prompt(PromptKind::Exec), "{command}");+ }+ let _ = std::fs::remove_dir_all(&home);+ }++ /// Every glob after a `..` under `/proc` may be a `cwd`, so a token of+ /// repeated `/*` would make one start-dir candidate per component, each+ /// as long as the rest of the token: quadratic in the command. Past a+ /// small cap the command is refused unchecked rather than resolved, in+ /// bounded time.+ #[test]+ fn a_token_with_too_many_start_dir_candidates_is_refused_quickly() {+ let home = std::fs::canonicalize(unique_root()).unwrap();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |command: &str| {+ let args = json!({"command": command, ESCALATE_ARG: true});+ resolve_decision_with_cwd(shell, &args, &ctx, None, &perms, &grants)+ };+ let refused = Decision::HardDeny(DenyReason::TooComplex);+ let started = std::time::Instant::now();+ for n in [200, 8000] {+ let command = format!("cat /proc/..{}", "/*".repeat(n));+ assert_eq!(gate(&command), refused, "{n} globs");+ }+ assert!(started.elapsed() < std::time::Duration::from_secs(2), "{:?}", started.elapsed());+ // A few globs are still resolved one by one, and name nothing hidden.+ let few = format!("cat /proc/..{}", "/*".repeat(4));+ assert_eq!(gate(&few), Decision::Prompt(PromptKind::Escalate));+ let _ = std::fs::remove_dir_all(&home);+ }++ /// `~-` and `$OLDPWD` are checked as the start dir because the wrapper+ /// makes them that (see `posix_cwd_script`), not the project root the+ /// shell was spawned in: from a held directory outside the home's+ /// subtree, climbing one level from it names nothing hidden, and climbing+ /// from the held dir in the home's subtree does.+ #[test]+ fn oldpwd_is_checked_as_the_held_dir() {+ let home = std::fs::canonicalize(unique_root()).unwrap();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ let sub = project.join("sub");+ std::fs::create_dir_all(&sub).unwrap();+ let outside = std::fs::canonicalize(unique_root()).unwrap();+ let held = outside.join("held");+ std::fs::create_dir_all(&held).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |command: &str, held: &Path| {+ let args = json!({"command": command, ESCALATE_ARG: true});+ resolve_decision_with_cwd(shell, &args, &ctx, Some(held), &perms, &grants)+ };+ for word in ["~-", "$OLDPWD", "${OLDPWD}"] {+ let one_up = format!("/bin/cat {word}/../.jan/config.toml");+ assert_eq!(gate(&one_up, &held), Decision::Prompt(PromptKind::Escalate), "{one_up}");+ let two_up = format!("/bin/cat {word}/../../.jan/config.toml");+ assert_eq!(gate(&two_up, &sub), Decision::HardDeny(DenyReason::Hidden), "{two_up}");+ }+ let _ = std::fs::remove_dir_all(&home);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// A held directory swapped for a symlink into the Jan home is where an+ /// escalated command would really start, so it is refused even when the+ /// command names nothing under it.+ #[cfg(unix)]+ #[test]+ fn an_escalation_from_a_held_cwd_swapped_for_a_link_into_the_home_is_denied() {+ let home = std::fs::canonicalize(unique_root()).unwrap();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ let project = home.join("proj");+ let sub = project.join("sub");+ std::fs::create_dir_all(&sub).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let shell = lookup(crate::tools::SHELL_TOOL).unwrap();+ let gate = |escalate: bool| {+ let args = json!({"command": "/bin/true", ESCALATE_ARG: escalate});+ resolve_decision_with_cwd(shell, &args, &ctx, Some(&sub), &perms, &grants)+ };+ assert_eq!(gate(true), Decision::Prompt(PromptKind::Escalate));+ std::fs::remove_dir(&sub).unwrap();+ // Relative to the link's own directory, so `proj/../.jan`.+ std::os::unix::fs::symlink("../.jan", &sub).unwrap();+ assert_eq!(gate(true), Decision::HardDeny(DenyReason::HiddenShellCwd));+ // Confined, the sandbox masks the home wherever the shell stands.+ assert_eq!(gate(false), Decision::Prompt(PromptKind::Exec));+ let _ = std::fs::remove_dir_all(&home);+ }}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 c2a36caa5..14fc8f574 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@@ -14,6 +14,7 @@ use crate::skills;use crate::tools::jail;use crate::tools::proc;use crate::tools::nofollow;+use crate::tools::sandbox;use crate::tools::sandbox::{escapes_write_roots, hidden_under, in_read_only_root, in_scratch, landing, lexical_normalize,refuse_windows_name, resolve_path, symlink_escapes_any_root, Landing,@@ -1134,9 +1135,21 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {Ok(v) => v,Err(e) => return e,};+ // Start where the last call's `cd` left the shell (see `posix_cwd_script`).+ // The held path is never read on the host: whether it can be entered is+ // decided inside the sandbox, so holding a path discloses nothing the+ // sandbox would not. The host only asks, before holding it, whether it is+ // a place the shell may stand (see `unholdable_shell_cwd`).+ let persist = ctx.shell_cwd.as_ref().filter(|_| proc::shell_cwd_supported());+ let start = persist.and_then(|cwd| cwd.lock().unwrap().clone());+ let script = match persist {+ Some(_) => posix_cwd_script(command, start.as_deref()),+ None => command.to_string(),+ };+ let reports_cwd = persist.is_some();let child = match proc::spawn(&shell,- command,+ &script,root,sandbox_env.as_ref(),ctx.shell_env(),@@ -1148,6 +1161,10 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {Err(e) => return format!("ERROR: failed to run command: {e}"),};let pid = child.id();+ // `spawn` registered the wrapper; `/shells` should show what was asked for.+ if let (Some(pid), Some(_)) = (pid, persist) {+ proc::relabel(ctx.thread_id, pid, command);+ }// The child is handed to a detached task immediately so it keeps running// (and its output keeps being collected) no matter what the race below@@ -1169,11 +1186,15 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// denials get the note too.let sandboxed = ctx.shell_confined();let escalation = ctx.escalation;+ // The task takes `policy` for its denial note; settling the cwd below+ // asks it which paths only the sandbox has.+ let confined_by = sandboxed.then(|| policy.clone());// Fed from the first byte, so a command the user opens in `/shells` after it// backgrounded still shows what it printed before the timeout.let tail = pid.and_then(proc::output_handle);tokio::spawn(async move {- let mut out = collect_and_format(child, spill_scratch, sink, tail).await;+ let (mut out, landed) =+ collect_and_format(child, spill_scratch, sink, tail, reports_cwd).await;// Appended inside the task so a backgrounded job carries the hint too.if sandboxed {let note = sandbox_denial_note(&out, &policy, escalation);@@ -1182,11 +1203,26 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if let Some(pid) = pid {proc::unregister(thread_owned.as_deref(), pid);}- let _ = tx.send(out);+ let _ = tx.send((out, landed));});tokio::select! {- res = &mut rx => res.unwrap_or_else(|_| "ERROR: background command ended without producing output".to_string()),+ res = &mut rx => {+ let (mut out, landed) = res.unwrap_or_else(|_| {+ let lost = "ERROR: background command ended without producing output";+ (lost.to_string(), CwdLanding::Unreported)+ });+ let refused = match &landed {+ CwdLanding::At(dir) => unholdable_shell_cwd(ctx, confined_by.as_ref(), dir),+ _ => None,+ };+ if let Some(note) =+ persist.and_then(|cwd| settle_shell_cwd(cwd, root, landed, refused))+ {+ insert_before_exit_marker(&mut out, ¬e);+ }+ out+ }by_user = hand_off_after(timeout_secs, ctx.detach_signal.clone()) => {// The command outran its timeout, or the user wants the agent back// sooner. Rather than killing it or blocking this call, let it keep@@ -1205,6 +1241,18 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {} else {format!("{BACKGROUNDED_PREFIX}{timeout_secs}s and is still running in the background")};+ // Its `cd` is dropped (see the task below), which the model would+ // otherwise only learn from where its next command runs.+ let lead = match persist {+ Some(_) => {+ let stays = start.clone().unwrap_or_else(|| root.to_path_buf());+ format!(+ "{lead}. Any `cd` in it is not carried over: the shell stays in {}",+ stays.display()+ )+ }+ None => lead,+ };if let Some(pid) = pid {proc::mark_backgrounded(ctx.thread_id, pid);}@@ -1226,7 +1274,10 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {(Some(path), Some(display)) => {let done_display = display.clone();tokio::spawn(async move {- let out = rx.await.unwrap_or_else(|_| {+ // A backgrounded command's `cd` is not carried over: it+ // would move the shell under later calls at a moment+ // the model cannot see.+ let out = rx.await.map(|(out, _)| out).unwrap_or_else(|_| {"ERROR: background command ended without producing output".to_string()});// The file is published before the doorbell rings, so a@@ -1234,7 +1285,10 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// already there -- and if publishing failed the ping// says nothing was captured rather than naming a file// that is absent or stale.- let published = write_background_output(&path, &out);+ // The model reads this file, so it gets what a direct+ // result would have given it; `failed` below reads the+ // marker from `out` itself.+ let published = write_background_output(&path, &model_shell_result(&out));if let Some(sink) = done_sink {sink(crate::tools::ShellEvent::Finished(crate::tools::ShellDone {id,@@ -1262,7 +1316,7 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// No file, but the completion is still worth reporting: the// model otherwise has no way to learn the command ended.tokio::spawn(async move {- let out = rx.await.unwrap_or_default();+ let out = rx.await.map(|(out, _)| out).unwrap_or_default();if let Some(sink) = done_sink {sink(crate::tools::ShellEvent::Finished(crate::tools::ShellDone {id,@@ -1309,6 +1363,295 @@ async fn hand_off_after(}}+/// Starts the line a wrapped command reports its final directory on. The+/// record separator keeps it off any line a command prints by accident; a+/// command that prints one on purpose only picks where its own next call+/// starts, which `cd` already lets it do.+const CWD_MARKER: &[u8] = b"\x1eJAN_CWD ";++/// `command` for a POSIX shell that starts in `start` (the project root when+/// `None`) and reports its final directory as a [`CWD_MARKER`] line on stdout+/// when it exits normally, by `exit`, or on an error (not when a signal kills+/// it). The report goes through fd 9, a copy of stdout the command itself runs+/// without, so a command that redirects its own stdout still reports. Only a+/// pipe is written to: after a fatal error bash runs the trap with the+/// command's own fd 9 (closed, or a lock file it opened), so the report falls+/// back to stdout when that is still the pipe, and is skipped otherwise rather+/// than written into the command's file. A `start` the sandbox cannot enter+/// refuses the command rather than running it somewhere it was not written+/// for; the report then names the project root, which resets the held+/// directory.+///+/// So does a `start` that is no longer its own physical path: a link swapped+/// in for it (or for a directory above it) after the host last checked it.+/// Checked here, after the move, because nothing earlier can close that+/// window: hooks, the spawn and the shell's startup all run between any host+/// check and this `cd`, and an escalated run has no sandbox to mask where a+/// link leads. The held path is always a `pwd -P` report, so on every run+/// that has not been tampered with the test is true; it applies to confined+/// runs too, where it costs one `pwd` and keeps one rule for every run. The+/// refusal reports the directory the wrapper started in (the project root),+/// not the link's target it now stands in, so that target is never held; if+/// the start could not be read, the report is not a path, which resets too.+/// The refusal prints that report itself and drops the trap, rather than+/// leaving a value for the trap to read: the command runs in the same shell+/// and could set any variable the trap reads.+///+/// The report is best-effort, not a boundary. The variable route is closed+/// (the trap sets each variable it reads, and the refusal reads only one set+/// before the command runs), but+/// the command shares the shell, so it can still spoof the report by+/// redefining `pwd`, `printf` or `[` as functions, replacing the trap, or+/// printing a marker line itself; no wrapper in the same shell can guard+/// against that. What a spoofed report can do stays bounded: the host+/// refuses to hold a directory [`unholdable_shell_cwd`] names a reason for;+/// the next call's `cd -P` plus `pwd -P` check refuses to run anywhere that+/// is not its own physical path; and the gate hard-denies an escalated call+/// from a held directory in the Jan home or above it+/// (`DenyReason::HiddenShellCwd`). At worst the model picks where its own+/// next call starts, which a `cd` already lets it do.+///+/// `OLDPWD` is set to the start directory on every run, held or not: the+/// gate checks `~-` and `$OLDPWD` as the start dir (see+/// `sandbox::start_dir_relative`), and after the `cd` the shell's own would+/// name the project root, or without one whatever the shell inherited.+///+/// The command runs through `eval` on one single-quoted word, so the shell+/// parses it a command at a time as it would unwrapped: a `shopt -s extglob`+/// or an alias applies to the lines after it, a trailing `\` and an+/// unterminated heredoc behave as they do in `bash -c`, and nothing the+/// command contains can reach the wrapper's own syntax. The cost is that+/// `$LINENO` and the shell's `line N:` errors count from the line the quoted+/// word ends on, so in a multi-line command they run high by its line count+/// less one; a one-line command still says line 1. Not reported: a command that sets its own+/// `EXIT` trap (it replaces this one).+fn posix_cwd_script(command: &str, start: Option<&Path>) -> String {+ // printf's own octal escape spells the separator, so the script stays ASCII.+ let marker = String::from_utf8_lossy(&CWD_MARKER[1..]);+ let report = format!("printf \"\\036{marker}%s\\n\"");+ let mut script = format!(+ "exec 9>&1; trap '{{ __jan_rc=$?; set +x; }} 2>/dev/null; \+ __jan_cwd=$(pwd -P); {{ if [ -p /dev/fd/9 ]; then \+ {report} \"$__jan_cwd\" >&9; elif [ -p /dev/fd/1 ]; then \+ {report} \"$__jan_cwd\"; fi; }} 2>/dev/null; exit $__jan_rc' EXIT; "+ );+ if let Some(dir) = start {+ let notice = format!(+ "{SHELL_CWD_TAG} {} is not reachable (gone, or a link now stands in its path); the \+ command was NOT run. The shell is back in the project root: re-run it from there]",+ dir.display()+ );+ let dir = shell_quote(&dir.to_string_lossy());+ script.push_str(&format!(+ "__jan_root=$(pwd -P); cd -P -- {dir} 2>/dev/null && [ \"$(pwd -P)\" = {dir} ] || \+ {{ printf '%s\\n' {} >&2; {report} \"${{__jan_root:-unreadable}}\" >&9; \+ trap - EXIT; exit 1; }}; ",+ shell_quote(¬ice)+ ));+ }+ script.push_str("OLDPWD=$PWD; ");+ script.push_str(&format!("{{ eval {}\n}} 9>&-\n", shell_quote(command)));+ script+}++/// Where a wrapped command said it ended, from its last [`CWD_MARKER`] line.+#[derive(Debug, PartialEq, Eq)]+enum CwdLanding {+ /// No report: a signal killed the shell, or it was not wrapped.+ Unreported,+ /// A report that does not read as a directory (an absolute, single-line+ /// path with nothing [`unsafe_in_a_note`] in it): `pwd -P` failed in a+ /// removed directory, or the name cannot be shown safely.+ Unreadable,+ At(PathBuf),+}++/// Splits [`CWD_MARKER`] lines out of a command's stdout as it streams, so+/// neither the result nor the live view shows them, and keeps the last one.+#[derive(Default)]+struct CwdReport {+ held: Vec<u8>,+ landed: Option<Vec<u8>>,+}++impl CwdReport {+ /// A marker longer than this is not one: flushed as ordinary output rather+ /// than held back without bound.+ const MAX_LINE: usize = 8192;++ /// The bytes of `chunk` (after any held back from earlier) that are+ /// ordinary output. A trailing partial marker is held for the next chunk.+ fn feed(&mut self, chunk: &[u8]) -> Vec<u8> {+ self.held.extend_from_slice(chunk);+ let mut out = Vec::new();+ loop {+ let Some(at) = self.held.iter().position(|&b| b == CWD_MARKER[0]) else {+ out.append(&mut self.held);+ return out;+ };+ out.extend(self.held.drain(..at));+ let rest = &self.held[..];+ let n = rest.len().min(CWD_MARKER.len());+ if rest[..n] != CWD_MARKER[..n] {+ // A stray separator: output, like everything up to the next one.+ let next = rest[1..].iter().position(|&b| b == CWD_MARKER[0]).map_or(rest.len(), |i| i + 1);+ out.extend(self.held.drain(..next));+ continue;+ }+ match rest.iter().position(|&b| b == b'\n') {+ Some(nl) if n == CWD_MARKER.len() => {+ self.landed = Some(rest[CWD_MARKER.len()..nl].to_vec());+ self.held.drain(..=nl);+ }+ _ if rest.len() > Self::MAX_LINE => out.append(&mut self.held),+ _ => return out,+ }+ }+ }++ /// What is still held once the stream ends, and the directory last+ /// reported.+ fn finish(mut self) -> (Vec<u8>, CwdLanding) {+ let rest = std::mem::take(&mut self.held);+ let landed = match self.landed {+ None => CwdLanding::Unreported,+ Some(raw) => String::from_utf8(raw)+ .ok()+ .filter(|path| path.starts_with('/') && !path.chars().any(unsafe_in_a_note))+ .map_or(CwdLanding::Unreadable, |path| CwdLanding::At(PathBuf::from(path))),+ };+ (rest, landed)+ }+}++/// Whether `c` must not reach a note or an approval prompt: a control+/// character, or a format character that reorders or hides text (bidi+/// overrides and isolates, zero-width marks), which could make a path read as+/// another one.+fn unsafe_in_a_note(c: char) -> bool {+ c.is_control()+ || matches!(c, '\u{061C}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}'+ | '\u{2060}'..='\u{2069}' | '\u{FEFF}')+}++/// Why the shell may not stand in `dir` for later calls, or `None` when it+/// may. Checked where it landed, before it is held:+///+/// - A directory only the sandbox has (`confined_by` is the policy the call+/// ran under): an escalated call starting there would enter the host's+/// same-named directory, a different one, and a confined call needs no help+/// to make a fresh one. See [`jail::sandbox_private`].+/// - The Jan home outside the project and the attached read roots the confined+/// shell may name: the gate would refuse every later command naming a path+/// relative to it, and the sandbox masks it anyway.+fn unholdable_shell_cwd(+ ctx: &ToolContext<'_>,+ confined_by: Option<&jail::Policy>,+ dir: &Path,+) -> Option<&'static str> {+ if confined_by.is_some_and(|policy| jail::sandbox_private(policy, dir)) {+ return Some(+ "exists only inside the sandbox (its private /tmp or a masked folder), so a later \+ command run outside it would land in a different directory",+ );+ }+ let hidden = ctx.hidden_root?;+ let raw = dir.to_string_lossy();+ let root = ctx.project_root;+ (sandbox::in_hidden_root_from(root, root, hidden, &raw)+ && !sandbox::shell_reads_attached_from(root, root, ctx.read_roots, ctx.write_roots, &raw))+ .then_some("is in the Jan home, which the shell may not work in")+}++/// Why an escalated command may not start in the held shell directory, with+/// the held directory reset to the project root, or `None` when it may (or+/// none is held). Asked before the approval prompt, so the prompt never names+/// a directory the command would not really start in: a component of the+/// held path can have been swapped for a link since the shell landed there+/// (`rmdir sub && ln -s ../.jan sub` from beside it).+///+/// This check covers the swap alone. A held directory in the Jan home or+/// above it was already refused by the gate (`DenyReason::HiddenShellCwd`);+/// a swap made after this check, while the prompt is up for one, is refused+/// by the wrapper once it has moved (see [`posix_cwd_script`]), the one check+/// no later swap can slip past; and a held directory that is gone is left to+/// the wrapper too.+///+/// The held path is compared lexically normalized, since it is a `pwd -P`+/// report and bash keeps a leading `//` there (`cd //tmp`), which is no link.+pub fn escalated_shell_cwd_refusal(ctx: &ToolContext<'_>) -> Option<String> {+ let cwd = ctx.shell_cwd.as_ref().filter(|_| proc::shell_cwd_supported())?;+ // One lock for the read and the reset, so a held directory set in between+ // is never dropped unchecked.+ let mut held = cwd.lock().unwrap();+ let dir = held.as_ref()?;+ if std::fs::canonicalize(dir).ok()? == lexical_normalize(dir) {+ return None;+ }+ let dir = held.take()?;+ Some(format!(+ "the shell cwd {} no longer resolves to itself (a link stands in its path), so the \+ command was not run. The shell is back in the project root {}: re-run it from there",+ dir.display(),+ ctx.project_root.display()+ ))+}++/// Hold the directory a command ended in for the next call, and say so when it+/// moved: the model cannot otherwise tell that a later relative command runs+/// somewhere else. Silent when nothing changed, so a plain command carries no+/// note. The project root is held as `None`. A directory `refused` names a+/// reason for (see [`unholdable_shell_cwd`]) is not held: the shell goes back+/// to the root, and the note says why, since it did not stay where the+/// command left it.+///+/// A report naming no directory ([`CwdLanding::Unreadable`]) resets too: the+/// held path may since name something else, a link put in place of a removed+/// directory, and the directory the shell really ended in cannot be named.+fn settle_shell_cwd(+ cwd: &crate::tools::ShellCwd,+ root: &Path,+ landed: CwdLanding,+ refused: Option<&str>,+) -> Option<String> {+ let landed = match landed {+ CwdLanding::Unreported => return None,+ CwdLanding::Unreadable => {+ let held = cwd.lock().unwrap().take()?;+ return Some(format!(+ "\n{SHELL_CWD_TAG} where the command ended could not be read back, so {} is not \+ kept; the shell is back in the project root {}]",+ held.display(),+ root.display()+ ));+ }+ CwdLanding::At(dir) => dir,+ };+ if let Some(why) = refused {+ *cwd.lock().unwrap() = None;+ return Some(format!(+ "\n{SHELL_CWD_TAG} {} {why}; the shell is back in the project root {}]",+ landed.display(),+ root.display()+ ));+ }+ let canonical_root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());+ let next = (landed != canonical_root).then_some(landed);+ let mut held = cwd.lock().unwrap();+ if *held == next {+ return None;+ }+ *held = next.clone();+ Some(match next {+ Some(dir) => format!(+ "\n{SHELL_CWD_TAG} is now {}: later bash calls start there. Other tools still resolve \+ relative paths against the project root]",+ dir.display()+ ),+ None => format!("\n{SHELL_CWD_TAG} is back to the project root {}]", root.display()),+ })+}+/// Serial number for one backgrounded command, so a completion can be paired/// with the hand-off that created it.fn next_background_id() -> u64 {@@ -1355,8 +1698,10 @@ async fn collect_and_format(scratch: Option<PathBuf>,sink: Option<crate::tools::OutputSink>,tail: Option<proc::OutputTail>,-) -> String {+ reports_cwd: bool,+) -> (String, CwdLanding) {use tokio::io::AsyncReadExt;+ let mut report = reports_cwd.then(CwdReport::default);let mut stdout = child.stdout.take();let mut stderr = child.stderr.take();let mut cap = BashCapture::new(scratch);@@ -1389,7 +1734,14 @@ async fn collect_and_format(tokio::select! {r = stdout.as_mut().unwrap().read(&mut bo), if out_open => match r {Ok(0) | Err(_) => out_open = false,- Ok(n) => { cap.push(&bo[..n]); tee(&bo[..n], &mut carry); }+ Ok(n) => {+ let shown = match report.as_mut() {+ Some(report) => report.feed(&bo[..n]),+ None => bo[..n].to_vec(),+ };+ cap.push(&shown);+ tee(&shown, &mut carry);+ }},r = stderr.as_mut().unwrap().read(&mut be), if err_open => match r {Ok(0) | Err(_) => err_open = false,@@ -1397,16 +1749,23 @@ async fn collect_and_format(},}}+ let landed = report.map_or(CwdLanding::Unreported, |report| {+ let (rest, landed) = report.finish();+ cap.push(&rest);+ tee(&rest, &mut carry);+ landed+ });// Whatever is left was never completed: emit it lossily rather than losing it.if !carry.is_empty() {if let Some(sink) = sink.as_ref() {sink(String::from_utf8_lossy(&carry).into_owned());}}- match child.wait().await {+ let out = match child.wait().await {Ok(status) => cap.finish(status.code()),Err(e) => format!("ERROR: failed to run command: {e}"),- }+ };+ (out, landed)}/// Bounded, tail-preserving accumulator for a command's combined output.@@ -1599,6 +1958,50 @@ pub fn exit_marker(line: &str) -> Option<Option<i32>> {.map(Some)}+/// How every shell-cwd note begins.+const SHELL_CWD_TAG: &str = "[shell cwd";++/// The lines the harness adds to a shell result, which are not the command's+/// own output, matched by how each begins: the sandbox hint, the escalation+/// hint, the shell-cwd notes, a hook-config notice. Taken from the constants+/// that write them, so a reworded note cannot fall out of this list.+fn is_harness_note(line: &str) -> bool {+ let escalation = ESCALATION_HINT.trim_start_matches('\n');+ line == escalation+ || [jail::DENIAL_HINT_TAG, SHELL_CWD_TAG, crate::tools::hooks::NOTICE_TAG]+ .iter()+ .any(|tag| line.starts_with(tag))+}++/// A shell result as the model receives it: `[exit 0]` is left off when the+/// command printed output, since the output already says it worked. Any other+/// marker -- a nonzero exit, a signal -- is kept: a `diff` or `test` that+/// prints and fails, or a command killed partway, has no other failure signal,+/// and compaction reads failures back from the recorded message. A+/// backgrounded hand-off and an `ERROR` result carry no marker and come back+/// unchanged.+pub fn model_shell_result(content: &str) -> String {+ let lines: Vec<&str> = content.lines().collect();+ // The last one is ours: a command can print `[exit 0]` itself.+ let Some(at) = lines.iter().rposition(|line| exit_marker(line).is_some()) else {+ return content.to_string();+ };+ if exit_marker(lines[at]) != Some(Some(0)) {+ return content.to_string();+ }+ let printed = lines.iter().enumerate().any(|(i, line)| {+ i != at+ && !line.trim().is_empty()+ && !is_harness_note(line)+ });+ if !printed {+ return content.to_string();+ }+ let mut kept = lines;+ kept.remove(at);+ kept.join("\n")+}+/// How the result of a command that outran its timeout starts. Private: callers/// ask [`bash_result_backgrounded`], which also rules out real output that/// happens to begin with the same words.@@ -3935,6 +4338,523 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A context whose shell carries its directory, the way an agent session's+ /// does: sandboxed with a scratch, or unsandboxed.+ #[cfg(unix)]+ fn cwd_ctx<'a>(+ root: &'a Path,+ store: &'a Path,+ scratch: &'a Path,+ cwd: &crate::tools::ShellCwd,+ sandbox: bool,+ ) -> ToolContext<'a> {+ ToolContext::new(root, store, &[])+ .with_sandbox(sandbox)+ .with_scratch_root(scratch)+ .with_shell_cwd(cwd.clone())+ }++ #[cfg(unix)]+ async fn run_in(ctx: &ToolContext<'_>, command: &str) -> String {+ let args = json!({ "command": command });+ super::execute_builtin(lookup("shell").unwrap(), &args, ctx).await.0+ }++ /// A `cd` holds for the next call, the result says so each time the+ /// directory moves (and never when it does not), and `cd` back to the root+ /// says that too. The report line itself never reaches the result.+ #[cfg(unix)]+ #[tokio::test]+ async fn shell_cwd_persists_across_calls_and_is_announced() {+ for sandbox in [true, false] {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub/deep")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, sandbox);+ let sub = std::fs::canonicalize(root.join("sub")).unwrap();++ let out = run_in(&ctx, "echo hi").await;+ assert_eq!(out, "hi\n[exit 0]", "nothing moved, nothing added");++ let out = run_in(&ctx, "cd sub").await;+ assert!(out.contains(&format!("shell cwd is now {}", sub.display())), "{out}");+ assert!(out.ends_with("[exit 0]"), "the note sits above the marker: {out}");+ assert!(!out.contains("JAN_CWD"), "{out}");++ let out = run_in(&ctx, "pwd -P").await;+ assert_eq!(out, format!("{}\n[exit 0]", sub.display()), "unchanged, so silent");++ // A failing command still reports where it ended.+ let out = run_in(&ctx, "cd deep && false").await;+ assert!(out.contains("shell cwd is now"), "{out}");+ assert!(out.ends_with("[exit 1]"), "{out}");++ let out = run_in(&ctx, &format!("cd {}", shell_quote(&root.to_string_lossy()))).await;+ assert!(out.contains("back to the project root"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), None);+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }+ }++ /// The wrapper keeps the command's own exit code however it ends, and the+ /// report survives a command that redirects its stdout or traces itself.+ #[cfg(unix)]+ #[tokio::test]+ async fn shell_cwd_wrapper_keeps_exit_codes_and_reports_through_redirects() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ assert!(run_in(&ctx, "exit 3").await.ends_with("[exit 3]"));+ assert!(run_in(&ctx, "set -e; false; echo no").await.ends_with("[exit 1]"));+ let out = run_in(&ctx, "cd sub; exec >/dev/null; echo hidden").await;+ assert!(out.contains("shell cwd is now"), "{out}");+ assert!(!out.contains("hidden"), "{out}");+ let out = run_in(&ctx, "set -x; cd ..").await;+ assert!(out.contains("back to the project root"), "{out}");+ assert!(!out.contains("__jan_rc"), "the trap does not trace itself: {out}");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// Commands the wrapper used to break still run, and a fatal `set -eu`+ /// error still reports its `cd` without writing into the command's own fd 9.+ #[cfg(unix)]+ #[tokio::test]+ async fn shell_cwd_wrapper_survives_awkward_commands() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ // macOS's bash 3.2 drops a trailing backslash under `eval`, so the+ // parity with an unwrapped run only holds where bash is 4 or newer.+ #[cfg(not(target_os = "macos"))]+ {+ let out = run_in(&ctx, "echo a \\").await;+ assert_eq!(out, "a \\\n[exit 0]", "a trailing backslash prints as it does unwrapped");+ }+ let out = run_in(&ctx, "cat <<EOF\nbody").await;+ // bash warns about it, as it does unwrapped, then runs it.+ assert!(out.ends_with("body\n[exit 0]"), "an unterminated heredoc still runs: {out}");+ let out = run_in(&ctx, "set -eu; cd sub; echo $JAN_UNSET_VAR").await;+ assert!(out.contains("shell cwd is now"), "{out}");+ assert!(!out.contains("Bad file descriptor"), "{out}");+ // bash 3.2 (macOS) exits 0 after a fatal `set -u` error under `eval`.+ #[cfg(not(target_os = "macos"))]+ assert!(!out.ends_with("[exit 0]"), "{out}");+ let lock = scratch.join("lock");+ let out = run_in(&ctx, &format!("cd ..; exec 9>{}; set -e; false", shell_quote(&lock.to_string_lossy()))).await;+ assert!(out.contains("back to the project root"), "{out}");+ assert_eq!(std::fs::read_to_string(&lock).unwrap(), "", "nothing written into the command's fd 9");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// Bash parses one command at a time, so a `shopt` or an alias set on one+ /// line takes effect on the next. Parsing the whole command up front, as a+ /// `{ ... }` wrapper does, breaks both.+ #[cfg(unix)]+ #[tokio::test]+ async fn shell_cwd_wrapper_applies_shopt_and_aliases_to_later_lines() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("a")).unwrap();+ std::fs::create_dir_all(root.join("b")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ let out = run_in(&ctx, "shopt -s extglob\nls -d !(a)").await;+ assert_eq!(out, "b\n[exit 0]", "extglob across lines");+ let out = run_in(&ctx, "shopt -s expand_aliases\nalias hi='echo alias-ok'\nhi").await;+ assert_eq!(out, "alias-ok\n[exit 0]", "alias across lines");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// `/shells` and the background panel list the command the model wrote,+ /// not the cwd wrapper it runs inside.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_wrapped_command_is_listed_as_written() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ run_in(&ctx, "cd sub").await;+ let command = format!("sleep 30; echo listed-{}", std::process::id());+ let args = json!({ "command": command, "timeout": 0 });+ let out = super::execute_builtin(lookup("shell").unwrap(), &args, &ctx).await.0;+ assert!(out.contains("still running in the background"), "{out}");+ let listed = proc::snapshot().into_iter().find(|s| s.command == command);+ if let Some(shell) = &listed {+ proc::kill(shell.pid);+ }+ assert!(listed.is_some(), "listed under the command as written");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// A reported path carrying text-reordering characters is refused, so a+ /// note or an approval prompt cannot be made to show another path.+ #[test]+ fn a_cwd_report_with_bidi_characters_is_dropped() {+ for path in ["/a\u{202E}b", "/a\u{2066}b", "/a\u{200B}b", "/a\tb"] {+ let mut report = CwdReport::default();+ report.feed(format!("\x1eJAN_CWD {path}\n").as_bytes());+ assert_eq!(report.finish().1, CwdLanding::Unreadable, "{path:?}");+ }+ let mut report = CwdReport::default();+ report.feed("\x1eJAN_CWD /caf\u{e9}\n".as_bytes());+ let cafe = CwdLanding::At(PathBuf::from("/caf\u{e9}"));+ assert_eq!(report.finish().1, cafe, "plain non-ASCII is fine");+ }++ /// A held directory the shell can no longer enter refuses the command+ /// instead of running it in the root it was not written for, and resets.+ #[cfg(unix)]+ #[tokio::test]+ async fn an_unreachable_shell_cwd_refuses_the_command_and_resets() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ run_in(&ctx, "cd sub").await;+ std::fs::remove_dir_all(root.join("sub")).unwrap();+ let out = run_in(&ctx, "touch ran-here").await;+ assert!(out.contains("NOT run"), "{out}");+ assert!(out.contains("back to the project root"), "{out}");+ assert!(out.ends_with("[exit 1]"), "{out}");+ assert!(!root.join("ran-here").exists(), "the command must not run in the root");+ assert_eq!(*cwd.lock().unwrap(), None);+ assert!(run_in(&ctx, "touch ran-here").await.ends_with("[exit 0]"));+ assert!(root.join("ran-here").exists());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The host check before an escalation can pass and the held directory+ /// still be swapped for a link before the wrapper enters it (hooks, the+ /// spawn and the shell's own startup run in between). The wrapper checks+ /// where it really landed, refuses to run anything there, and resets.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_held_shell_cwd_swapped_after_the_host_check_is_refused_by_the_wrapper() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ std::fs::create_dir_all(root.join("elsewhere")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ run_in(&ctx, "cd sub").await;+ assert!(cwd.lock().unwrap().is_some());+ assert_eq!(escalated_shell_cwd_refusal(&ctx), None, "nothing swapped yet");+ std::fs::remove_dir(root.join("sub")).unwrap();+ std::os::unix::fs::symlink("elsewhere", root.join("sub")).unwrap();+ let out = run_in(&ctx, "touch marker").await;+ assert!(out.contains("NOT run"), "{out}");+ assert!(out.contains("back to the project root"), "{out}");+ assert!(out.ends_with("[exit 1]"), "{out}");+ assert!(!root.join("elsewhere/marker").exists(), "followed the link");+ assert!(!root.join("marker").exists(), "ran in the project root");+ assert_eq!(*cwd.lock().unwrap(), None);+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// `~-` and `$OLDPWD` name where the command starts, as the gate assumes:+ /// the held directory after the wrapper's `cd` (not the project root it+ /// was spawned in), and the project root without one, whatever OLDPWD the+ /// shell inherited. `~+0` and `~-0`, the ends of a stack nothing was+ /// pushed on, name it as well.+ #[cfg(unix)]+ #[tokio::test]+ async fn oldpwd_is_the_start_dir() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let set = vec![("OLDPWD".to_string(), "/usr".to_string())];+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false).with_env_set(&set);+ let canon = std::fs::canonicalize(&root).unwrap();+ let out = run_in(&ctx, "echo ~- $OLDPWD ~+0 ~-0").await;+ assert_eq!(out, format!("{0} {0} {0} {0}\n[exit 0]", canon.display()), "no held dir");+ run_in(&ctx, "cd sub").await;+ let sub = canon.join("sub");+ let out = run_in(&ctx, "echo ~- $OLDPWD ~+0 ~-0").await;+ assert_eq!(out, format!("{0} {0} {0} {0}\n[exit 0]", sub.display()), "held dir");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The cwd report is the wrapper's, not the command's: a variable the+ /// command can set (it runs in the same shell) never picks the directory+ /// held next, on a normal run or a refused one.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_command_cannot_set_the_reported_cwd_through_a_variable() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ let out = run_in(&ctx, "__jan_cwd_at=/tmp").await;+ assert!(!out.contains("shell cwd"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), None);+ run_in(&ctx, "cd sub").await;+ let sub = std::fs::canonicalize(root.join("sub")).unwrap();+ run_in(&ctx, "__jan_cwd_at=/tmp; true").await;+ assert_eq!(*cwd.lock().unwrap(), Some(sub));+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// A held path is compared to where it resolves lexically normalized, not+ /// as spelled: bash's `pwd -P` after `cd //tmp` keeps the double slash,+ /// and a `..` over a plain directory is no link either.+ #[cfg(unix)]+ #[test]+ fn a_held_cwd_spelled_with_extra_slashes_is_no_swap() {+ let root = std::fs::canonicalize(unique_root()).unwrap();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ let spellings = [+ format!("/{}", root.display()),+ format!("{}/.", root.display()),+ format!("{}/sub/..", root.display()),+ ];+ for held in spellings {+ *cwd.lock().unwrap() = Some(PathBuf::from(&held));+ assert_eq!(escalated_shell_cwd_refusal(&ctx), None, "{held}");+ }+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// A command that removes the directory it stands in reports no directory+ /// (`pwd -P` fails), so the held path is not kept: a link put in its place+ /// later would otherwise be entered unchecked. The shell is back in the+ /// root. (With a link already in place, bash's `pwd -P` reports the+ /// link's target, which is checked like any other landing.)+ #[cfg(unix)]+ #[tokio::test]+ async fn a_held_shell_cwd_removed_under_the_shell_is_reset() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ run_in(&ctx, "cd sub").await;+ assert!(cwd.lock().unwrap().is_some());+ let out = run_in(&ctx, "rmdir ../sub").await;+ assert!(out.contains("could not be read back"), "{out}");+ assert!(out.contains("back in the project root"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), None);+ assert!(run_in(&ctx, "true").await.ends_with("[exit 0]"), "runs from the root");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The report is the only thing the host takes from it: a forged one that+ /// is not a single absolute path is dropped, nothing is ever read from a+ /// file the shell names, and a held path is never opened on the host.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_forged_cwd_report_discloses_nothing() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let secret = unique_root().join("secret.txt");+ std::fs::write(&secret, "TOP-SECRET").unwrap();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ for forged in ["relative/path", "/a\\tb"] {+ let out = run_in(&ctx, &format!("printf '\\036JAN_CWD {forged}\\n'; trap - EXIT")).await;+ assert!(!out.contains("shell cwd"), "{forged}: {out}");+ assert_eq!(*cwd.lock().unwrap(), None, "{forged}");+ }+ // A file path is held as a path, never read: the next call fails to+ // enter it inside the shell, and its contents appear nowhere.+ let target = secret.to_string_lossy().into_owned();+ let out = run_in(&ctx, &format!("printf '\\036JAN_CWD %s\\n' {}; trap - EXIT", shell_quote(&target))).await;+ assert!(!out.contains("TOP-SECRET"), "{out}");+ let out = run_in(&ctx, "true").await;+ assert!(out.contains("NOT run"), "{out}");+ assert!(!out.contains("TOP-SECRET"), "{out}");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(secret.parent().unwrap());+ }++ /// A test dir outside the host temp dir, as the real project and scratch+ /// are, so a `/tmp` path inside the sandbox names something else.+ #[cfg(target_os = "linux")]+ fn outside_tmp_root() -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("target")+ .join("handlers-tests")+ .join(format!("{}_{n}", std::process::id()));+ std::fs::create_dir_all(&dir).expect("create test root");+ dir+ }++ /// Inside bubblewrap `/tmp` is a private tmpfs, so a directory made there+ /// is not the host's same-named one, which an escalated run would enter.+ /// It is never held: the shell is back in the root at once, and says so.+ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn a_sandboxed_cd_into_private_tmp_is_not_held() {+ if !jail::backend().enforces() {+ eprintln!("skipping: no sandbox backend on this host");+ return;+ }+ let root = outside_tmp_root();+ let store = crate::workspace::project_store(&root);+ let scratch = outside_tmp_root();+ let host_twin = std::env::temp_dir().join(format!("jan_cwd_twin_{}", std::process::id()));+ std::fs::create_dir_all(&host_twin).unwrap();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, true);+ let make = format!("mkdir -p {0} && cd {0}", shell_quote(&host_twin.to_string_lossy()));+ let out = run_in(&ctx, &make).await;+ assert!(out.contains("exists only inside the sandbox"), "{out}");+ assert!(out.contains("back in the project root"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), None);+ // The scratch is bound at its real path, so it is held.+ let out = run_in(&ctx, &format!("cd {}", shell_quote(&scratch.to_string_lossy()))).await;+ assert!(out.contains("shell cwd is now"), "{out}");+ let _ = std::fs::remove_dir_all(&host_twin);+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// A directory in the Jan home is not held unless an attached read root+ /// covers it (a parent viewing a child's worktree) or it is the project+ /// itself (a worktree under the home): the gate would refuse every command+ /// that names a relative path from there.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_cd_into_the_jan_home_is_not_held() {+ let home = unique_root();+ let jan = home.join(".jan");+ let other = jan.join("worktrees/proj/general-1");+ let child = jan.join("worktrees/proj/general-2");+ let project = home.join("proj");+ for d in [&other, &child, &project] {+ std::fs::create_dir_all(d).unwrap();+ }+ let store = crate::workspace::project_store(&project);+ let scratch = unique_root();+ let roots = vec![std::fs::canonicalize(&child).unwrap()];+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&project, &store, &scratch, &cwd, false)+ .with_hidden_root(Some(&jan))+ .with_read_roots(&roots);+ let cd = |dir: &Path| format!("cd {}", shell_quote(&dir.to_string_lossy()));+ for dir in [&other, &jan, &jan.join("worktrees/proj")] {+ let out = run_in(&ctx, &cd(dir)).await;+ assert!(out.contains("Jan home"), "{out}");+ assert!(out.contains("back in the project root"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), None, "{}", dir.display());+ }+ let out = run_in(&ctx, &cd(&child)).await;+ assert!(out.contains("shell cwd is now"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), Some(roots[0].clone()));+ // From the child's worktree, `dirname "$PWD"` lands in the home.+ let out = run_in(&ctx, "cd \"$(dirname \"$PWD\")\"").await;+ assert!(out.contains("Jan home"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), None);+ // A worktree under the home as the project keeps its own tree.+ let wt = std::fs::canonicalize(&other).unwrap();+ std::fs::create_dir_all(wt.join("src")).unwrap();+ let wt_store = crate::workspace::project_store(&wt);+ let ctx = cwd_ctx(&wt, &wt_store, &scratch, &cwd, false).with_hidden_root(Some(&jan));+ let out = run_in(&ctx, "cd src").await;+ assert!(out.contains("shell cwd is now"), "{out}");+ assert_eq!(*cwd.lock().unwrap(), Some(wt.join("src")));+ let _ = std::fs::remove_dir_all(&home);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The report line is split out wherever a read boundary falls, and a+ /// stray separator is passed through as output.+ #[test]+ fn cwd_report_splits_the_marker_across_chunks() {+ let stream = b"one\n\x1eJAN_CWD /tmp/x\ntwo\x1e\n";+ for cut in 0..stream.len() {+ let mut report = CwdReport::default();+ let mut shown = report.feed(&stream[..cut]);+ shown.extend(report.feed(&stream[cut..]));+ let (rest, landed) = report.finish();+ shown.extend(rest);+ assert_eq!(shown, b"one\ntwo\x1e\n", "cut at {cut}");+ assert_eq!(landed, CwdLanding::At(PathBuf::from("/tmp/x")), "cut at {cut}");+ }+ }++ /// A backgrounded command's `cd` is not carried: it would move the shell+ /// under later calls at a moment the model cannot see.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_backgrounded_cd_is_not_carried() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let store = crate::workspace::project_store(&root);+ let scratch = unique_root();+ let cwd = crate::tools::ShellCwd::default();+ let ctx = cwd_ctx(&root, &store, &scratch, &cwd, false);+ let args = json!({ "command": "cd sub; sleep 0.3", "timeout": 0 });+ let out = super::execute_builtin(lookup("shell").unwrap(), &args, &ctx).await.0;+ assert!(out.contains("still running in the background"), "{out}");+ let stays = format!("the shell stays in {}", root.display());+ assert!(out.contains(&stays), "the hand-off says the cd is dropped: {out}");+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;+ assert_eq!(*cwd.lock().unwrap(), None);+ // A held directory is the one named, not the root.+ run_in(&ctx, "cd sub").await;+ let sub = std::fs::canonicalize(root.join("sub")).unwrap();+ let args = json!({ "command": "cd ..; sleep 0.3", "timeout": 0 });+ let out = super::execute_builtin(lookup("shell").unwrap(), &args, &ctx).await.0;+ assert!(out.contains(&format!("the shell stays in {}", sub.display())), "{out}");+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;+ assert_eq!(*cwd.lock().unwrap(), Some(sub));+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// Without a carried directory (the MCP server) every call starts in the+ /// root and nothing is announced, exactly as before.+ #[cfg(unix)]+ #[tokio::test]+ async fn shell_cwd_is_not_carried_without_a_holder() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let out = execute_builtin(lookup("shell").unwrap(), &json!({"command": "cd sub"}), &root).await;+ assert_eq!(out, "[exit 0]");+ let out = execute_builtin(lookup("shell").unwrap(), &json!({"command": "pwd -P"}), &root).await;+ let canonical_root = std::fs::canonicalize(&root).unwrap();+ assert!(out.starts_with(&canonical_root.display().to_string()), "{out}");+ let _ = std::fs::remove_dir_all(&root);+ }+/// The doorbell: a backgrounded command must announce itself the moment it/// is detached (so the caller knows a result is owed and does not end the/// run under it) and report again when it really finishes, naming the file@@ -4169,8 +5089,9 @@ mod tests {tokio::time::sleep(std::time::Duration::from_millis(100)).await;}let body = body.expect("output file must appear after the command finishes");- assert!(body.contains("done"), "unexpected: {body}");- assert!(body.contains("[exit 0]"), "carries the exit marker: {body}");+ // The model reads this file, so it gets the result a direct call+ // would: output present, so no exit marker.+ assert_eq!(body, "done", "unexpected: {body}");let _ = std::fs::remove_file(&path);let _ = std::fs::remove_dir_all(&root);}@@ -4410,6 +5331,75 @@ mod tests {let _ = std::fs::remove_dir_all(&scratch);}+ /// `[exit 0]` is left off only when the command printed output; harness+ /// notes do not count as output, a failure or a signal is always kept, and+ /// a marker the command printed itself stays as output.+ #[test]+ fn model_shell_result_drops_only_a_clean_exit_after_output() {+ assert_eq!(model_shell_result("hi\n[exit 0]"), "hi");+ assert_eq!(model_shell_result("boom\n[exit 1]"), "boom\n[exit 1]");+ assert_eq!(model_shell_result("[exit 0]"), "[exit 0]");+ assert_eq!(model_shell_result("[exit 3]"), "[exit 3]");+ assert_eq!(model_shell_result("\n[exit 0]"), "\n[exit 0]");+ assert_eq!(model_shell_result("[terminated by signal]"), "[terminated by signal]");+ assert_eq!(+ model_shell_result("partial\n[terminated by signal]"),+ "partial\n[terminated by signal]"+ );+ let notes = "[shell cwd is now /x: later]\n[exit 0]";+ assert_eq!(model_shell_result(notes), notes, "notes alone are not output");+ // Each note as its writer produces it, so a reworded one fails here.+ let policy = jail::Policy::new(Path::new("/w"), true);+ let written = [+ jail::denial_hint(&policy),+ ESCALATION_HINT.to_string(),+ settle_shell_cwd(+ &std::sync::Arc::default(),+ Path::new("/w"),+ CwdLanding::At(PathBuf::from("/x")),+ None,+ )+ .unwrap(),+ settle_shell_cwd(+ &std::sync::Arc::default(),+ Path::new("/w"),+ CwdLanding::At(PathBuf::from("/x")),+ Some("is elsewhere"),+ )+ .unwrap(),+ settle_shell_cwd(+ &std::sync::Arc::new(std::sync::Mutex::new(Some(PathBuf::from("/x")))),+ Path::new("/w"),+ CwdLanding::Unreadable,+ None,+ )+ .unwrap(),+ format!("\n{} renamed", crate::tools::hooks::NOTICE_TAG),+ ];+ for note in written {+ let only = format!("{}\n[exit 0]", note.trim_start_matches('\n'));+ assert_eq!(model_shell_result(&only), only, "{note:?} is not output");+ }+ assert_eq!(+ model_shell_result("ok\n[shell cwd is now /x: later]\n[exit 0]"),+ "ok\n[shell cwd is now /x: later]"+ );+ assert_eq!(+ model_shell_result("x\n[exit 0]\n[output truncated at 10 of 99 bytes]"),+ "x\n[output truncated at 10 of 99 bytes]"+ );+ assert_eq!(+ model_shell_result("x\n[exit 2]\n[output truncated at 10 of 99 bytes]"),+ "x\n[exit 2]\n[output truncated at 10 of 99 bytes]"+ );+ assert_eq!(model_shell_result("echoed [exit 0]\n[exit 0]"), "echoed [exit 0]");+ assert_eq!(model_shell_result("[exit 0]\n[exit 4]"), "[exit 0]\n[exit 4]", "the last is ours");+ assert_eq!(model_shell_result("[exit 4]\n[exit 0]"), "[exit 4]", "the last is ours");+ let handoff = "Command exceeded 5s and is still running in the background.";+ assert_eq!(model_shell_result(handoff), handoff);+ assert_eq!(model_shell_result("ERROR: missing"), "ERROR: missing");+ }+/// The sandbox hint is spliced in above the exit marker, so the marker/// stays the final line.#[test]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rsindex c33c888fd..12051d5d0 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs@@ -67,6 +67,10 @@ pub fn resolve_for(project: Option<&Path>) -> HookSet {/// and a run must not stall on one that never returns.pub const DEFAULT_TIMEOUT_SECS: u64 = 60;+/// How a load notice begins when it rides on a tool result, so a reader can+/// tell it from the tool's own output.+pub const NOTICE_TAG: &str = "[hook config:";+/// Upper bound on a hook's stdout that is parsed. A hook answers with a small/// JSON object; anything past this is a runaway and is truncated rather than/// buffered without limit.diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex 5a67d9d72..b0a547aab 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -338,6 +338,71 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {}}+/// True when `path`, as a shell confined by `policy` names it, is not the+/// host's directory of that name: it sits on a mount only the sandbox has+/// (bubblewrap's private `/tmp`, the tmpfs masks over `$HOME` and the Jan+/// home, its own `/proc` and `/dev`). An unconfined command naming the same+/// path would reach another directory, or none.+///+/// Seatbelt and AppContainer only filter access to the host's filesystem and+/// remap nothing, so there every path is the host's.+pub fn sandbox_private(policy: &Policy, path: &Path) -> bool {+ backend() == Backend::Bubblewrap && bwrap_private(policy, path)+}++/// [`sandbox_private`] for bubblewrap, read off the argv [`bwrap_args`]+/// builds so the mount table is described in one place. Mounts apply in+/// order and a later one over a path hides every earlier one beneath it, so+/// the last mount covering `path` decides: a tmpfs, `/proc` or `/dev` is the+/// sandbox's own, a bind of a folder onto its own path is the host's.+///+/// A mount lands where its target resolves, and the shell reports where it+/// stands with `pwd -P`, so a `$HOME` behind a symlink (`/home -> /var/home`)+/// must be compared resolved or no mask over it would match and `--ro-bind /`+/// would claim the path. Each mount target is tried in both spellings, so a+/// caller naming the literal path still matches, and a target that does not+/// exist falls back to its literal. `path` itself is taken as written: it is+/// physical inside the sandbox, and resolving it through the host's symlinks+/// (a host `/tmp/x -> ~/proj/sub`) would name another directory.+fn bwrap_private(policy: &Policy, path: &Path) -> bool {+ use crate::tools::sandbox::{canonicalize_lenient, lexical_normalize};+ let cfg = ShellConfig {+ program: PathBuf::from("/bin/sh"),+ args: Vec::new(),+ kind: super::proc::ShellKind::Posix,+ };+ let args = bwrap_args(policy, &cfg);+ let spellings = |p: &Path| {+ let literal = lexical_normalize(p);+ let resolved = canonicalize_lenient(&literal).unwrap_or_else(|_| literal.clone());+ [literal, resolved]+ };+ let path = lexical_normalize(path);+ let covers = |dest: &str| spellings(Path::new(dest)).iter().any(|d| path.starts_with(d));+ let mut private = false;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "--tmpfs" | "--proc" | "--dev" if i + 1 < args.len() => {+ private |= covers(&args[i + 1]);+ i += 2;+ }+ "--bind" | "--ro-bind" if i + 2 < args.len() => {+ if covers(&args[i + 2]) {+ // A file bound onto another name (the cargo config) is+ // not the host's file of that name.+ private = args[i + 1] != args[i + 2];+ }+ i += 3;+ }+ // The shell's own argv follows; nothing after it is a mount.+ "--" => break,+ _ => i += 1,+ }+ }+ private+}+// ---------------------------------------------------------------------------// bubblewrap (Linux)// ---------------------------------------------------------------------------@@ -1037,6 +1102,10 @@ pub fn looks_denied(output: &str) -> bool {DENIAL_MARKERS.iter().any(|m| lower.contains(m))}+/// How every [`denial_hint`] begins (after its newline), so a reader can tell+/// the note from the command's own output.+pub const DENIAL_HINT_TAG: &str = "[sandbox:";+/// Sentence appended to a denied command's output, telling the model the limits/// rather than leaving it to infer them from `Permission denied`.pub fn denial_hint(policy: &Policy) -> String {@@ -1106,12 +1175,12 @@ pub fn denial_hint(policy: &Policy) -> String {format!("; writes are limited to {scratch}")};return format!(- "\n[sandbox: the workspace ({}) is read-only{writes}{home}.{net}{attached}]",+ "\n{DENIAL_HINT_TAG} the workspace ({}) is read-only{writes}{home}.{net}{attached}]",policy.workspace.display());}format!(- "\n[sandbox: writes are limited to the workspace ({}){scratch}{home}.{net}{attached}]",+ "\n{DENIAL_HINT_TAG} writes are limited to the workspace ({}){scratch}{home}.{net}{attached}]",policy.workspace.display())}@@ -1132,6 +1201,102 @@ mod tests {Policy::new(Path::new("/data/agent-workspace/threads/t1"), false)}+ /// A directory on a tmpfs the sandbox mounts is not the host's, unless a+ /// later bind puts a host folder back at that path.+ #[test]+ fn bwrap_private_follows_the_mount_order() {+ let home = home_dir().expect("a home");+ let scratch = PathBuf::from("/tmp/jan-scratch");+ let p = Policy::new(&home.join("proj"), false)+ .with_scratch_root(&scratch)+ .with_hide_root(&home.join(".jan"))+ .with_read_roots(vec![home.join(".jan/worktrees/p/child")]);+ for private in ["/tmp/x", "/tmp", "/proc/1", "/dev/shm"] {+ assert!(bwrap_private(&p, Path::new(private)), "{private}");+ }+ for private in [home.join("docs"), home.join(".jan/worktrees/p")] {+ assert!(bwrap_private(&p, &private), "{}", private.display());+ }+ for shared in [+ PathBuf::from("/usr/lib"),+ PathBuf::from("/"),+ scratch.join("sub"),+ home.join("proj/src"),+ home.join(".jan/worktrees/p/child/src"),+ ] {+ assert!(!bwrap_private(&p, &shared), "{}", shared.display());+ }+ // A readable home is the host's own.+ let p = p.with_home_readonly(true);+ assert!(!bwrap_private(&p, &home.join("docs")));+ assert!(bwrap_private(&p, &home.join(".jan/x")), "still hidden");+ }++ /// The shell reports where it landed with `pwd -P`, the physical path,+ /// while the mounts name a home behind a symlink (Fedora Atomic's+ /// `/home -> /var/home`); the kernel puts each mount at the resolved+ /// path, so that is the one the landed path must be compared with. The+ /// home is passed as the data-folder mask here: `$HOME` itself is+ /// process-wide and cannot be swapped under parallel tests. The real home+ /// is mounted read-only (the host's own), and the fixture lives under the+ /// crate's `target/`, not the private `/tmp`, so only the fake home's+ /// mounts decide.+ #[cfg(unix)]+ #[test]+ fn bwrap_private_sees_mounts_through_a_symlinked_home() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ static N: AtomicUsize = AtomicUsize::new(0);+ let n = N.fetch_add(1, Ordering::SeqCst);+ let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("target/jail-tests")+ .join(format!("symhome_{}_{n}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ let real = base.join("var/home/u");+ std::fs::create_dir_all(real.join(".jan/x")).unwrap();+ std::fs::create_dir_all(real.join("proj/src")).unwrap();+ std::fs::create_dir_all(real.join("docs")).unwrap();+ std::fs::create_dir_all(base.join("r")).unwrap();+ std::os::unix::fs::symlink(base.join("var/home"), base.join("home")).unwrap();+ let home = base.join("home/u");+ let p = Policy::new(&home.join("proj"), false)+ .with_home_readonly(true)+ .with_mask_root(&home)+ .with_hide_root(&home.join(".jan"));+ for private in [real.join("docs"), real.join(".jan/x"), home.join("docs")] {+ assert!(bwrap_private(&p, &private), "{}", private.display());+ }+ for shared in [real.join("proj/src"), home.join("proj/src"), base.join("r")] {+ assert!(!bwrap_private(&p, &shared), "{}", shared.display());+ }+ let _ = std::fs::remove_dir_all(&base);+ }++ /// The landed path is physical inside the sandbox already: a `/tmp/x`+ /// the shell reports is on the private `/tmp`, even when the host's+ /// `/tmp/x` is a symlink into the project. Resolving it on the host would+ /// call it the project's folder and let an unconfined command land there.+ #[cfg(unix)]+ #[test]+ fn bwrap_private_does_not_resolve_the_landed_path_on_the_host() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ static N: AtomicUsize = AtomicUsize::new(0);+ let n = N.fetch_add(1, Ordering::SeqCst);+ let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("target/jail-tests")+ .join(format!("tmplink_{}_{n}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ let project = base.join("proj");+ std::fs::create_dir_all(project.join("sub")).unwrap();+ let link = PathBuf::from("/tmp").join(format!("jan_tmplink_{}_{n}", std::process::id()));+ let _ = std::fs::remove_file(&link);+ std::os::unix::fs::symlink(project.join("sub"), &link).unwrap();+ let p = Policy::new(&project, false);+ let private = bwrap_private(&p, &link);+ let _ = std::fs::remove_file(&link);+ let _ = std::fs::remove_dir_all(&base);+ assert!(private, "{}", link.display());+ }+#[cfg(unix)]struct BwrapFixture(PathBuf);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex c9a322bd0..a31a974f8 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -225,6 +225,11 @@ pub struct ToolContext<'a> {/// the agent for a message the user typed mid-call instead of holding it/// until the command ends. `None` leaves the timeout as the only hand-off.pub detach_signal: Option<tokio::sync::watch::Receiver<bool>>,+ /// Where the next `bash` call starts, carried over from the last one so a+ /// `cd` holds for the session instead of being repeated in every command.+ /// `None` starts every call in `project_root`, as a surface with no+ /// conversation (the MCP server) wants. See [`ShellCwd`].+ pub shell_cwd: Option<ShellCwd>,/// The backend `web_search`/`web_fetch` use, as the host's settings chose/// it. `None` keeps the default: keyless Exa, upgraded by an `EXA_API_KEY`/// in the environment.@@ -272,6 +277,7 @@ impl std::fmt::Debug for ToolContext<'_> {.field("hook_sink", &self.hook_sink.is_some()).field("shell_done_sink", &self.shell_done_sink.is_some()).field("detach_signal", &self.detach_signal.is_some())+ .field("shell_cwd", &self.shell_cwd.as_ref().map(|c| c.lock().unwrap().clone()))// The config can hold an API key, so only the backend id is shown..field("web_search",@@ -357,6 +363,11 @@ pub enum ShellEvent {/// call which created it.pub type ShellDoneSink = std::sync::Arc<dyn Fn(ShellEvent) + Send + Sync>;+/// The shell's working directory between calls: `None` is the project root.+/// Shared rather than borrowed so the session, not one run, owns it -- a `cd`+/// made in one turn still holds in the next. Only POSIX shells update it.+pub type ShellCwd = std::sync::Arc<std::sync::Mutex<Option<PathBuf>>>;+/// How long a caller should hold a run open waiting for one backgrounded/// command, in seconds.///@@ -431,6 +442,7 @@ impl<'a> ToolContext<'a> {hook_sink: None,shell_done_sink: None,detach_signal: None,+ shell_cwd: None,web_search: None,workspace_readonly: false,}@@ -477,6 +489,13 @@ impl<'a> ToolContext<'a> {self}+ /// Carry the shell's directory across calls in `cwd`. See+ /// [`Self::shell_cwd`].+ pub fn with_shell_cwd(mut self, cwd: ShellCwd) -> Self {+ self.shell_cwd = Some(cwd);+ self+ }+/// Attach the run's lifecycle hooks, the plan-mode flag they honor, and/// where their non-blocking output goes. See [`Self::hooks`].pub fn with_hooks(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 195cb994e..0c6069f45 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@@ -630,6 +630,23 @@ whereout}+/// Whether `bash` can carry its working directory between calls here: a known+/// POSIX shell on unix, whose `pwd -P` names the path the next call can `cd` to.+/// git-bash on Windows prints `/c/...` instead, and PowerShell and cmd have no+/// `EXIT` trap to report from.+pub fn shell_cwd_supported() -> bool {+ cfg!(unix) && speaks_posix(&shell().program)+}++/// Whether `program` is a shell the cwd wrapper's POSIX syntax runs in.+/// [`kind_of`] calls anything not PowerShell or cmd POSIX, which is right for+/// handing it `-c`; a `JAN_AGENT_SHELL` of fish or nu takes `-c` too but would+/// reject the wrapper, so only names known to speak POSIX sh qualify.+fn speaks_posix(program: &Path) -> bool {+ let name = program.file_name().and_then(|n| n.to_str()).unwrap_or_default();+ matches!(name, "sh" | "bash" | "dash" | "zsh" | "ksh" | "mksh" | "ash" | "busybox")+}+pub async fn spawn(cfg: &ShellConfig,command: &str,@@ -1019,17 +1036,29 @@ pub fn unregister(thread: Option<&str>, pid: u32) {}}-/// Flag a still-running command as backgrounded: it outran its `bash` call's-/// timeout and is now detached, so `/shells` should list it. A no-op if the pid-/// already finished (the detached task unregistered it in the race).-pub fn mark_backgrounded(thread: Option<&str>, pid: u32) {+/// Apply `change` to a registered shell; a no-op if the pid already finished+/// (its task unregistered it in the race).+fn update(thread: Option<&str>, pid: u32, change: impl FnOnce(&mut ShellProc)) {if let Some(set) = running().lock().unwrap().get_mut(thread.unwrap_or(NO_THREAD)) {if let Some(proc) = set.get_mut(&pid) {- proc.backgrounded = true;+ change(proc);}}}+/// List a registered shell under `command` instead of the script it was+/// spawned with, for a caller that wraps what the user wrote (the shell-cwd+/// wrapper) and wants `/shells` to show the original.+pub fn relabel(thread: Option<&str>, pid: u32, command: &str) {+ update(thread, pid, |proc| proc.command = command.to_string());+}++/// Flag a still-running command as backgrounded: it outran its `bash` call's+/// timeout and is now detached, so `/shells` should list it.+pub fn mark_backgrounded(thread: Option<&str>, pid: u32) {+ update(thread, pid, |proc| proc.backgrounded = true);+}+/// Every currently-running bash command across all sessions, pid-sorted for a/// stable list. The `/shells` inspector filters to the backgrounded ones.pub fn snapshot() -> Vec<ShellInfo> {@@ -1679,6 +1708,18 @@ mod tests {unregister(Some("sess-b"), b);}+ /// Only shells known to speak POSIX sh run the cwd wrapper; fish and nu+ /// take `-c` but would reject its syntax.+ #[test]+ fn only_known_posix_shells_carry_the_cwd() {+ for posix in ["/bin/sh", "/usr/bin/bash", "/bin/dash", "/bin/zsh", "/bin/busybox"] {+ assert!(speaks_posix(Path::new(posix)), "{posix}");+ }+ for other in ["/usr/bin/fish", "/usr/bin/nu", "/usr/bin/xonsh", "pwsh"] {+ assert!(!speaks_posix(Path::new(other)), "{other}");+ }+ }+#[cfg(unix)]#[tokio::test]async fn confine_limits_caps_child_resource_limits() {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex 3be1b3c03..fb23f7439 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -10,30 +10,7 @@ pub fn escapes_project(scratch: Option<&Path>,raw: &str,) -> Result<bool, String> {- let root = project_root- .canonicalize()- .map_err(|e| format!("project root {:?}: {e}", project_root))?;- let abs = if Path::new(raw).is_absolute() {- PathBuf::from(raw)- } else {- root.join(raw)- };- let resolved = canonicalize_lenient(&abs)?;- if resolved.starts_with(&root) {- return Ok(false);- }- // The scratch is the agent's own per-session area and is writable under- // every backend at this same real path, so a path landing in it is not a- // host escape even though it sits outside the project. Canonicalized, so- // a symlink the shell planted in the scratch cannot lead back out. A- // scratch that cannot be canonicalized grants nothing: the path stays an- // escape.- if let Some(scratch) = scratch {- if let Ok(scratch) = scratch.canonicalize() {- return Ok(!resolved.starts_with(&scratch));- }- }- Ok(true)+ escapes_roots_metered(project_root, scratch, &[], raw, &Meter::unlimited())}/// True iff `raw` escapes every root a *read* may legitimately reach: the@@ -43,7 +20,7 @@ pub fn escapes_project(/// keeps the exact check it has today and a read root can only ever widen what/// reads reach, never what writes do.///-/// A read root that cannot be canonicalized grants nothing — same rule as the+/// A read root that cannot be canonicalized grants nothing -- same rule as the/// scratch above. A vanished root must not silently open a path up.pub fn escapes_read_roots(project_root: &Path,@@ -51,29 +28,7 @@ pub fn escapes_read_roots(read_roots: &[PathBuf],raw: &str,) -> Result<bool, String> {- if !escapes_project(project_root, scratch, raw)? {- return Ok(false);- }- if read_roots.is_empty() {- return Ok(true);- }- let abs = if Path::new(raw).is_absolute() {- PathBuf::from(raw)- } else {- // Relative paths belong to the workspace, never to an attached folder:- // resolving them against a read root would make `write` and `read`- // disagree about what one path means.- project_root.join(raw)- };- let resolved = canonicalize_lenient(&abs)?;- for root in read_roots {- if let Ok(root) = root.canonicalize() {- if resolved.starts_with(&root) {- return Ok(false);- }- }- }- Ok(true)+ escapes_roots_metered(project_root, scratch, read_roots, raw, &Meter::unlimited())}/// True iff `raw` escapes every root a *write* may legitimately reach: the@@ -89,28 +44,44 @@ pub fn escapes_write_roots(write_roots: &[PathBuf],raw: &str,) -> Result<bool, String> {- if !escapes_project(project_root, scratch, raw)? {- return Ok(false);- }- if write_roots.is_empty() {- return Ok(true);- }+ escapes_roots_metered(project_root, scratch, write_roots, raw, &Meter::unlimited())+}++/// [`escapes_project`] widened by `roots` (the read or the write roots),+/// charging `meter` for resolving `raw`; an error once it runs out, which+/// the gate must tell from an escape with [`Meter::spent`]. Only `raw` is+/// metered: it is what the model sends, while the roots are the user's and+/// cost one `canonicalize` each.+///+/// `raw` is resolved once, relative paths against the project root: they+/// belong to the workspace, never to an attached folder, or `write` and+/// `read` would disagree about what one path means.+pub fn escapes_roots_metered(+ project_root: &Path,+ scratch: Option<&Path>,+ roots: &[PathBuf],+ raw: &str,+ meter: &Meter,+) -> Result<bool, String> {+ let root = project_root+ .canonicalize()+ .map_err(|e| format!("project root {:?}: {e}", project_root))?;let abs = if Path::new(raw).is_absolute() {PathBuf::from(raw)} else {- // Relative paths belong to the workspace, never to an attached folder- // -- the same rule reads follow, so one path means one place to both.- project_root.join(raw)+ root.join(raw)};- let resolved = canonicalize_lenient(&abs)?;- for root in write_roots {- if let Ok(root) = root.canonicalize() {- if resolved.starts_with(&root) {- return Ok(false);- }- }- }- Ok(true)+ let resolved = canonicalize_metered(&abs, meter)?;+ // The scratch is the agent's own per-session area and is writable under+ // every backend at this same real path, so a path landing in it is not a+ // host escape even though it sits outside the project. Canonicalized, so+ // a symlink the shell planted in the scratch (or a root) cannot lead back+ // out. A scratch or root that cannot be canonicalized grants nothing: the+ // path stays an escape.+ let within = |dir: &Path| dir.canonicalize().is_ok_and(|dir| resolved.starts_with(dir));+ Ok(!resolved.starts_with(&root)+ && !scratch.is_some_and(within)+ && !roots.iter().any(|r| within(r)))}/// Resolve a tool-supplied path to its on-disk location: absolute paths as@@ -229,18 +200,128 @@ pub fn in_read_only_root(project_root: &Path, scratch: Option<&Path>, raw: &str)/// `~/.jan/worktrees/`) is the agent's working tree, so paths inside it stay/// reachable. The home itself as the project grants nothing.pub fn in_hidden_root(project_root: &Path, hidden: &Path, raw: &str) -> bool {- let Ok(hidden) = canonicalize_lenient(hidden) else {- return false;- };- let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, raw)) else {- return false;- };- if !resolved.starts_with(&hidden) {- return false;+ in_hidden_root_from(project_root, project_root, hidden, raw)+}++/// [`in_hidden_root`] with a relative `raw` resolved against `base` instead of+/// the project root: a shell that a `cd` moved elsewhere reads `.jan/...`+/// from there. The worktree exception stays keyed on `project_root`, since+/// that, not where the shell stands, is the agent's working tree.+pub fn in_hidden_root_from(project_root: &Path, base: &Path, hidden: &Path, raw: &str) -> bool {+ let meter = Meter::unlimited();+ HiddenRoot::new(project_root, base, hidden, &meter).is_some_and(|h| h.holds(raw, &meter))+}++/// The hidden root, its worktree exception (see [`in_hidden_root`]), the+/// base relative paths resolve against and the attached roots carved out of+/// it, resolved once: a caller checking many paths (every token of a+/// command) would otherwise re-resolve all of them for each, which from a+/// deep base cost every token a syscall per component of it.+pub struct HiddenRoot {+ hidden: PathBuf,+ /// The project root when it is a worktree inside `hidden`.+ worktree: Option<PathBuf>,+ base: Base,+ carve: Carve,+}++impl HiddenRoot {+ /// `None` when `hidden` cannot be resolved: then nothing is in it. No+ /// attached root is carved out until [`HiddenRoot::carving`] says so.+ pub fn new(project_root: &Path, base: &Path, hidden: &Path, meter: &Meter) -> Option<Self> {+ let hidden = canonicalize_metered(hidden, meter).ok()?;+ let worktree = meter+ .canonicalize(project_root)+ .ok()+ .flatten()+ .filter(|root| *root != hidden && root.starts_with(&hidden));+ let base = Base::new(project_root, base, meter);+ Some(Self { hidden, worktree, base, carve: Carve::default() })}- match project_root.canonicalize() {- Ok(root) if root != hidden && root.starts_with(&hidden) => !resolved.starts_with(&root),- _ => true,++ /// This root with what [`shell_reads_attached_from`] lets through carved+ /// out of it: paths in `read_roots` and in none of `write_roots`. A tool+ /// that only reads passes no write roots.+ pub fn carving(self, read_roots: &[PathBuf], write_roots: &[PathBuf], meter: &Meter) -> Self {+ Self { carve: Carve::new(read_roots, write_roots, meter), ..self }+ }++ /// The resolved hidden root.+ pub fn path(&self) -> &Path {+ &self.hidden+ }++ /// [`in_hidden_root_from`] against this root and base, less the carve-out.+ /// False when `meter` runs out, which the caller must check.+ pub fn holds(&self, raw: &str, meter: &Meter) -> bool {+ let Ok(resolved) = self.base.resolve(raw, meter) else {+ return false;+ };+ resolved.starts_with(&self.hidden)+ && !self.worktree.as_ref().is_some_and(|w| resolved.starts_with(w))+ && !self.carve.covers(&self.base, raw, &resolved)+ }+}++/// The directory relative paths resolve against, resolved once.+struct Base {+ /// Canonical when it resolves; else as given, and each path is resolved+ /// from scratch.+ dir: Result<PathBuf, PathBuf>,+ /// The base is the project root: its relative paths belong to the+ /// project, never to an attached root. A literal comparison on purpose:+ /// the held cwd is always a physical path (`pwd -P`) and is cleared once+ /// it equals the canonical root, so a caller passes either the root+ /// itself or something else. A caller that spells the root differently+ /// gets no carve-out for relative paths from it, which fails closed.+ is_project: bool,+}++impl Base {+ fn new(project_root: &Path, base: &Path, meter: &Meter) -> Self {+ let dir = match meter.canonicalize(base) {+ Ok(Some(dir)) => Ok(dir),+ _ => Err(base.to_path_buf()),+ };+ Self { dir, is_project: base == project_root }+ }++ /// `raw` resolved against this base, every link followed.+ fn resolve(&self, raw: &str, meter: &Meter) -> Result<PathBuf, String> {+ match &self.dir {+ Ok(dir) if !Path::new(raw).is_absolute() => resolve_from(dir, raw, meter),+ Ok(dir) | Err(dir) => canonicalize_metered(&resolve_path(dir, raw), meter),+ }+ }+}++/// Attached roots a path in the Jan home may still be named in (see+/// [`shell_reads_attached_from`]), canonicalized once. A root that cannot+/// be canonicalized grants nothing.+#[derive(Default)]+struct Carve {+ read: Vec<PathBuf>,+ write: Vec<PathBuf>,+}++impl Carve {+ fn new(read_roots: &[PathBuf], write_roots: &[PathBuf], meter: &Meter) -> Self {+ // Charged on every decision that carves: two attached roots ~1900+ // deep would spend the budget alone, accepted as the user attaches them.+ let real = |roots: &[PathBuf]| -> Vec<PathBuf> {+ roots.iter().filter_map(|r| meter.canonicalize(r).ok().flatten()).collect()+ };+ Self { read: real(read_roots), write: real(write_roots) }+ }++ /// True iff `raw`, which resolved to `resolved` from `base`, is in a read+ /// root and in no write root.+ fn covers(&self, base: &Base, raw: &str, resolved: &Path) -> bool {+ if self.read.is_empty() || (!Path::new(raw).is_absolute() && base.is_project) {+ return false;+ }+ let within = |roots: &[PathBuf]| roots.iter().any(|r| resolved.starts_with(r));+ within(&self.read) && !within(&self.write)}}@@ -249,31 +330,318 @@ pub fn in_hidden_root(project_root: &Path, hidden: &Path, raw: &str) -> bool {/// to spell a path under it. The gate refuses a command when one of them is/// in the hidden root; best-effort is enough only because the OS sandbox/// masks the directory too (see [`super::jail::Policy::hide_root`]).-pub fn hidden_tokens(hidden: &Path, command: &str) -> Vec<String> {+///+/// Every word is a token, the command name too: telling one from an argument+/// takes a shell parser, and each guess at one let a path through. A word+/// naming no path is harmless; one resolved under a held cwd in the home is+/// let through only by the gate's attached-root carve-out, and the shell is+/// never held anywhere else in the home (see `settle_shell_cwd`).+///+/// A backslash splits nothing, so a Windows path (`C:\Users\me\x`) stays one+/// token; a word with one is also checked unescaped, the way a POSIX shell+/// reads it (`\x` is `x`). A word with quotes in it is also checked with them+/// dropped, as the shell joins it: `"$PWD"/../x` is one path, not two.+///+/// A token spelling the shell's start directory some other way (see+/// [`start_dir_relative`]) is followed by the path it names from there, which+/// the caller resolves against the start dir like any relative token: read+/// as written, the host would resolve it against Jan's own process. The word+/// as written stays a token too: it may also be an ordinary relative path+/// (a `proc/` directory in the project), and an extra token only adds a+/// refusal.+///+/// `None` when the command is too complex to check in bounded time: more+/// than [`MAX_TOKENS`] tokens or [`MAX_TOKEN_BYTES`] of them, or one token+/// with more start-dir candidates than [`start_dir_past_links`] allows. The+/// caller resolves every token, so a scan without a bound would stall the+/// agent in the gate; it refuses the command instead, failing closed, and+/// the model can split or simplify it. What resolving the tokens costs is+/// bounded by the caller, with a [`Meter`].+pub fn hidden_tokens(hidden: &Path, command: &str) -> Option<Vec<String>> {let home = hidden.parent().map(|h| h.to_string_lossy().into_owned());- command- .split(|c: char| c.is_whitespace() || ";|&><()\"'`=".contains(c))+ let words = command.split(|c: char| c.is_whitespace() || ";|&><()\"'`=".contains(c));+ let joined = command+ .split(|c: char| c.is_whitespace() || ";|&><()`=".contains(c))+ .filter(|w| w.contains(['"', '\'']))+ .map(|w| w.replace(['"', '\''], ""));+ let tokens = words+ .map(str::to_string)+ .chain(joined).filter(|t| !t.is_empty())+ .flat_map(|t| {+ let unescaped = t.contains('\\').then(|| unescape(&t));+ std::iter::once(t).chain(unescaped)+ }).map(|t| match &home {- Some(home) => expand_home(t, home),- None => t.to_string(),+ Some(home) => expand_home(&t, home),+ None => t,+ });+ let mut out = Vec::new();+ let mut bytes = 0;+ for t in tokens {+ let start = start_dir_relative(&t);+ let linked = start_dir_past_links(&t)?;+ for t in std::iter::once(t).chain(start).chain(linked) {+ bytes += t.len();+ out.push(t);+ }+ if out.len() > MAX_TOKENS || bytes > MAX_TOKEN_BYTES {+ return None;+ }+ }+ Some(out)+}++/// The most tokens [`hidden_tokens`] hands back for one command: half again+/// a 100k-word heredoc, far more than a model writes by hand. It bounds the+/// scan's memory; the gate's time to resolve them is bounded by+/// [`MAX_RESOLVE_COST`].+const MAX_TOKENS: usize = 150_000;++/// The most bytes of tokens [`hidden_tokens`] hands back for one command. A+/// few times the largest command a model plausibly writes, since quoted and+/// escaped words are counted twice. Like [`MAX_TOKENS`] it bounds the scan's+/// memory and time, not the resolving that follows.+const MAX_TOKEN_BYTES: usize = 4 << 20;++/// The most one gate decision may spend on all the paths it resolves+/// (command tokens and path arguments together), in path components the OS+/// walks, charged to one [`Meter`]: a path 2048 components deep, or a+/// 150k-word command run from a directory 25 levels deep. A path syscall+/// walks the path from the root, so the work is quadratic in a path's depth+/// whichever way it is resolved: one path a model can send, made of real+/// directories and `..`, took minutes, and so did many short tokens through+/// a link into a deep directory. Up to this budget it takes well under a+/// second in a release build.+pub const MAX_RESOLVE_COST: usize = 2048 * 2048;++/// What resolving `raw` against a directory `base_depth` components deep+/// costs, estimated from the text in the units of [`MAX_RESOLVE_COST`]: each+/// component of the full path is a step, and each step walks the path so+/// far. A bare word thus costs the depth of its directory; an absolute path+/// ignores the base.+///+/// Blind to links, so the gate uses it only as a cap, to refuse what is too+/// deep on its face before any syscall; the [`Meter`] is charged by the+/// walks, with what they really do.+pub fn resolve_cost(base_depth: usize, raw: &str) -> usize {+ let own = raw.bytes().filter(|b| *b == b'/' || *b == b'\\').count() + 1;+ let depth = if Path::new(raw).is_absolute() { own } else { own + base_depth };+ own.saturating_mul(depth)+}++/// The most candidates [`start_dir_past_links`] makes from one token. Each+/// is as long as the rest of the token, so without a cap a token of repeated+/// globs (`/proc/..` then `/*` many times, every glob a possible `cwd`)+/// makes candidates quadratic in its length. An ordinary path has none or+/// one or two.+const MAX_LINKED: usize = 16;++/// Words a POSIX shell expands to its current directory when it starts: the+/// start dir. `~-` and `$OLDPWD` name the previous one, which the cwd+/// wrapper sets to the start dir on every run (see+/// `handlers::posix_cwd_script`): after its `cd` the shell's own would name+/// the project root it was spawned in.+///+/// `~+0` and `~-0` are bash's directory-stack ends: the top is the current+/// directory, and the bottom is too while nothing was pushed (the stack is+/// that one entry), so at the start both name the start dir. A `pushd` or+/// `cd` in the same command moves them, as a `cd` moves `$PWD`.+///+/// Only these literal words are mapped. `$(pwd)`, backticks,+/// `${PWD%...}`-style expansions and the other stack entries (`~+N`, `~-N`,+/// `~N` for N > 0, which name directories only a `pushd` in the same+/// command put there) also spell a directory the gate cannot know and are+/// not: the same gap as any other `$VAR` the gate cannot evaluate, which the+/// OS sandbox masking the home covers for a confined run.+const START_DIR_WORDS: [&str; 8] =+ ["$PWD", "${PWD}", "~+", "~-", "~+0", "~-0", "$OLDPWD", "${OLDPWD}"];++/// Where a token's leading components put it, as far as+/// [`start_dir_relative`] cares.+enum Spot {+ /// The shell's start directory (or, failing closed, maybe it).+ Start,+ /// The filesystem root again, through `/proc/<pid>/root`.+ Root,+ Elsewhere,+}++/// True iff the component `part` may be `literal` once the shell expands it:+/// equal, or carrying a glob or an expansion that could turn into it+/// (`/proc/s*/cwd`, `/proc/self/$d`). Fails closed for a word the gate+/// cannot evaluate.+fn may_be(part: &str, literal: &str) -> bool {+ part == literal || part.contains(['*', '?', '[', '$', '{', '`'])+}++/// Where the components so far (`.`/`..` already applied) lead. Every+/// process's `cwd` and `root`, and every fd, are matched whatever names the+/// process (`self`, `$$`, a pid, `thread-self`, a task id): the gate cannot+/// tell which process a pid is, and the shell's own is one of them.+fn spot(parts: &[String]) -> Spot {+ let is = |i: usize, literal: &str| parts.get(i).is_some_and(|p| may_be(p, literal));+ let proc = is(0, "proc");+ // `/proc/<pid>` or `/proc/<pid>/task/<tid>`: what follows is the same.+ let base = if proc && parts.len() >= 5 && is(2, "task") { 4 } else { 2 };+ match parts.len() {+ 2 if is(0, "dev") && ["stdin", "stdout", "stderr"].iter().any(|s| is(1, s)) => Spot::Start,+ 3 if is(0, "dev") && is(1, "fd") => Spot::Start,+ n if proc && n == base + 1 && is(base, "cwd") => Spot::Start,+ n if proc && n == base + 1 && is(base, "root") => Spot::Root,+ n if proc && n == base + 2 && is(base, "fd") => Spot::Start,+ _ => Spot::Elsewhere,+ }+}++/// A shell token spelling a path through the shell's start directory, as the+/// same path relative to that directory; `None` for any other token. The+/// spellings: [`START_DIR_WORDS`] in front, `/proc/<pid>/cwd`, and a+/// directory fd opened on it (`exec 3<.` then `/dev/fd/3`, `/proc/<pid>/fd/3`,+/// `/dev/stdin`), the last two failing closed for an fd that names something+/// else.+///+/// The host would resolve each against Jan's own process, not the shell, so+/// `/proc/self/cwd/../.jan` from a shell held in `~/proj` would pass as a path+/// under Jan's cwd. Leading components are normalized lexically first, so+/// `/proc/self/../self/cwd` and `/proc/self/root/proc/self/cwd` (which+/// re-enters `/proc` from the root) are caught too; what follows the match is+/// kept as written, so a `..` there climbs from the start dir, as it does in+/// the shell. A relative token is walked as if from the root, since it may+/// climb there: at worst an ordinary `proc/x/cwd` directory is also checked+/// as the start dir, which only adds a refusal.+///+/// A token through `/proc/<pid>/root` that never reaches the start dir is+/// the absolute path it names under that root (`/proc/1/root/etc/x` is+/// `/etc/x`), which the host may not be allowed to resolve as written.+pub fn start_dir_relative(token: &str) -> Option<String> {+ use std::path::Component;+ let rel = |rest: &Path| {+ Some(match rest.as_os_str().is_empty() {+ true => ".".to_string(),+ false => rest.to_string_lossy().into_owned(),})- .collect()+ };+ let mut components = Path::new(token).components();+ if let Some(Component::Normal(first)) = components.clone().next() {+ if START_DIR_WORDS.iter().any(|w| first == *w) {+ components.next();+ return rel(components.as_path());+ }+ }+ let mut parts: Vec<String> = Vec::new();+ let mut rerooted = false;+ while let Some(c) = components.next() {+ match c {+ Component::ParentDir => {+ parts.pop();+ }+ Component::Normal(name) => parts.push(name.to_string_lossy().into_owned()),+ Component::CurDir => {}+ // A root (or a Windows prefix) restarts the walk.+ _ => parts.clear(),+ }+ match spot(&parts) {+ Spot::Start => return rel(components.as_path()),+ Spot::Root => {+ parts.clear();+ rerooted = true;+ }+ Spot::Elsewhere => {}+ }+ }+ rerooted.then(|| format!("/{}", parts.join("/")))}-/// True iff `raw` resolves inside one of `roots` (canonicalized attached-/// folders). Relative paths belong to the project, never to a root.-pub fn in_attached_root(project_root: &Path, roots: &[PathBuf], raw: &str) -> bool {- if roots.is_empty() || !Path::new(raw).is_absolute() {- return false;+/// The paths a token under `/proc` or `/dev` may name through the shell's+/// start dir once the kernel follows the links in it, which+/// [`start_dir_relative`] does not see: a `..` after a link (`/proc/net`,+/// `/proc/self`, `/proc/thread-self`, `/proc/mounts`, `/dev/fd`) climbs from+/// the link's target, not from where the token spells it, so+/// `/proc/net/../cwd` is `/proc/self/cwd` while it normalizes lexically to+/// `/proc/cwd`. Which components are links the gate cannot know without the+/// shell's `/proc`, so once a `..` follows a `proc` or `dev` component,+/// every later `cwd`, `fd/<n>` and `std*` component is taken as the start+/// dir and every `root` as the filesystem root, and what follows each is a+/// candidate. Fails closed; a token with no such `..` (`/proc/cpuinfo`,+/// `/proc/self/fd`, `/dev/null`) yields nothing, so ordinary reads are not+/// touched. The candidates are not walked again.+///+/// One candidate per matching component, each the rest of the token, is+/// quadratic in the token's length when many components match (every glob+/// may be a `cwd`). So past [`MAX_LINKED`] candidates this gives up with+/// `None`, which refuses the whole command (see [`hidden_tokens`]): what it+/// would have to check cannot be checked in bounded time.+fn start_dir_past_links(token: &str) -> Option<Vec<String>> {+ use std::path::Component;+ let parts: Vec<Component> = Path::new(token).components().collect();+ let name = |i: usize| match parts.get(i) {+ Some(Component::Normal(n)) => Some(n.to_string_lossy()),+ _ => None,+ };+ let is = |i: usize, literal: &str| name(i).is_some_and(|n| may_be(&n, literal));+ let Some(linked) = (0..parts.len()).find(|&i| is(i, "proc") || is(i, "dev")) else {+ return Some(Vec::new());+ };+ if !parts[linked..].contains(&Component::ParentDir) {+ return Some(Vec::new());}- let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, raw)) else {- return false;+ let rest = |from: usize| {+ let rest: PathBuf = parts.iter().skip(from).collect();+ match rest.as_os_str().is_empty() {+ true => ".".to_string(),+ false => rest.to_string_lossy().into_owned(),+ }};- roots- .iter()- .filter_map(|r| r.canonicalize().ok())- .any(|r| resolved.starts_with(r))+ let std_stream = |i: usize| ["stdin", "stdout", "stderr"].iter().any(|s| is(i, s));+ let mut out = Vec::new();+ for i in linked + 1..parts.len() {+ if is(i, "cwd") || std_stream(i) {+ out.push(rest(i + 1));+ } else if is(i, "fd") && name(i + 1).is_some() {+ out.push(rest(i + 2));+ } else if is(i, "root") {+ out.push(format!("/{}", rest(i + 1)));+ }+ if out.len() > MAX_LINKED {+ return None;+ }+ }+ Some(out)+}++/// `word` with POSIX backslash escapes removed: each `\` keeps the character+/// after it and drops itself.+fn unescape(word: &str) -> String {+ let mut out = String::with_capacity(word.len());+ let mut chars = word.chars();+ while let Some(c) = chars.next() {+ match c {+ '\\' => out.extend(chars.next()),+ _ => out.push(c),+ }+ }+ out+}++/// True iff the confined shell may name `raw` (relative to `base`, where a+/// `cd` left it) even though it is in the Jan home: it sits in an attached+/// read root the sandbox mounts read-only, which a root also marked writable+/// is not. From the project root itself a relative path belongs to the+/// project, never a root. The gate's carve-out ([`HiddenRoot::carving`]) and+/// the shell's choice of where it may stand both ask this, so the shell+/// never holds a directory the gate would then refuse every command in.+pub fn shell_reads_attached_from(+ project_root: &Path,+ base: &Path,+ read_roots: &[PathBuf],+ write_roots: &[PathBuf],+ raw: &str,+) -> bool {+ let meter = Meter::unlimited();+ let carve = Carve::new(read_roots, write_roots, &meter);+ let base = Base::new(project_root, base, &meter);+ base.resolve(raw, &meter).is_ok_and(|resolved| carve.covers(&base, raw, &resolved))}fn expand_home(token: &str, home: &str) -> String {@@ -397,12 +765,37 @@ pub fn landing(/// project. A link's target is spliced in place of its name instead, relative/// targets against the link's own directory, as the kernel does. Too many hops/// (a cycle) is an error, so callers fail closed.-fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {+///+/// Linear in the path's length: below a component that does not exist (and+/// is no link) nothing exists either, so the rest is appended without a+/// syscall until a `..` climbs back out. A syscall per component on the whole+/// prefix made one deep missing path a model sent cost the gate minutes.+pub(crate) fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {+ canonicalize_metered(path, &Meter::unlimited())+}++/// [`canonicalize_lenient`] charging `meter` for the work it does; an error+/// once the meter runs out.+///+/// On Linux a limited meter skips the whole-path `canonicalize` and the+/// probes for the existing prefix, and walks from the root: `realpath` there+/// is glibc making the walk's own lookups, a component at a time, so the+/// result is the same, but a failing call tells nothing of what it spent (a+/// link into a deep directory walks all of it before a missing leaf fails),+/// so it could not be charged. One difference is deliberate: the walk stops+/// at `MAX_HOPS` links, as the kernel's `open` does (ELOOP), where glibc's+/// `realpath` follows more; do not raise it to match, since a path no syscall+/// can open must not be judged by where it would have led. Elsewhere the calls are kept, since they also+/// spell the path as the roots are spelled (case; Windows applies `..`+/// lexically), and a failing one is charged by the input's depth: a link+/// there can cost more than it is charged.+pub(crate) fn canonicalize_metered(path: &Path, meter: &Meter) -> Result<PathBuf, String> {use std::path::Component;- // Linux's MAXSYMLINKS: the most hops `open` itself would follow.- const MAX_HOPS: usize = 40;- if let Ok(p) = path.canonicalize() {- return Ok(p);+ let walk_all = meter.walks_all();+ if !walk_all {+ if let Some(p) = meter.canonicalize(path)? {+ return Ok(p);+ }}let abs = if path.is_absolute() {path.to_path_buf()@@ -411,41 +804,182 @@ fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {.map_err(|e| format!("current dir: {e}"))?.join(path)};+ let parts: Vec<Component> = abs.components().collect();+ let (seeded, resolved) = match walk_all {+ true => (0, PathBuf::new()),+ false => existing_prefix(&parts, meter)?,+ };+ walk(path, resolved, &parts[seeded..], meter)+}++/// [`canonicalize_lenient`] of a relative `raw` under `dir`, a canonical+/// directory: walked from `dir` without resolving it again, so many paths+/// under one deep directory do not each pay for its depth.+fn resolve_from(dir: &Path, raw: &str, meter: &Meter) -> Result<PathBuf, String> {+ let parts: Vec<std::path::Component> = Path::new(raw).components().collect();+ walk(Path::new(raw), dir.to_path_buf(), &parts, meter)+}++/// A budget for the path lookups one gate decision makes, shared by every+/// path it resolves, in components the OS walks: a lookup of a path `k`+/// components deep walks `k`. Charged with what the walk really does, the+/// components of a link's target and the depth it lands at included, not+/// estimated from the text: a short token through a link into a deep+/// directory costs as much as that directory is deep, and thousands of+/// them took the gate minutes.+///+/// Shared through `&self` (a `Cell`), as the gate's checks are closures+/// over one meter. Once a charge fails the meter stays spent, so a caller+/// that saw a path fail to resolve can tell running out from a path that+/// does not resolve, with [`Meter::spent`].+pub struct Meter {+ used: std::cell::Cell<usize>,+ /// `None` for callers outside the gate, which are not metered.+ budget: Option<usize>,+}++impl Meter {+ /// A meter that refuses past `budget` components walked.+ pub fn new(budget: usize) -> Self {+ Self { used: std::cell::Cell::new(0), budget: Some(budget) }+ }++ fn unlimited() -> Self {+ Self { used: std::cell::Cell::new(0), budget: None }+ }++ /// True when walks charged to this meter make every lookup themselves+ /// rather than ask `realpath` (see [`canonicalize_metered`]).+ fn walks_all(&self) -> bool {+ self.budget.is_some() && cfg!(any(target_os = "linux", target_os = "android"))+ }++ /// True once a charge went past the budget.+ pub fn spent(&self) -> bool {+ self.budget.is_some_and(|b| self.used.get() > b)+ }++ /// Add `cost`; an error once the budget is exceeded.+ pub fn charge(&self, cost: usize) -> Result<(), String> {+ self.used.set(self.used.get().saturating_add(cost));+ match self.spent() {+ true => Err("too complex to resolve within the gate's budget".to_string()),+ false => Ok(()),+ }+ }++ /// `path.canonicalize()` charged: `Ok(None)` when it fails, an error+ /// when the meter runs out (and then no call is made). `realpath` looks+ /// up every prefix of the path, and after an absolute link every prefix+ /// of where it leads, so a result `d` deep from an input `n` deep costs+ /// about `1 + .. + n` plus `1 + .. + d`. A failed call is charged as if+ /// it reached the input's depth; one that failed deep inside a dangling+ /// link's target is paid for again by the walk that follows, which+ /// splices that target in and charges each of its components.+ fn canonicalize(&self, path: &Path) -> Result<Option<PathBuf>, String> {+ // Refused before the call: a spent meter must stop the work, not+ // just report it afterwards.+ self.charge(0)?;+ let prefixes = |k: usize| k.saturating_mul(k + 1) / 2;+ let n = prefixes(path.components().count());+ match path.canonicalize() {+ Ok(real) => {+ self.charge(n.saturating_add(prefixes(real.components().count())))?;+ Ok(Some(real))+ }+ Err(_) => self.charge(n).map(|()| None),+ }+ }+}++/// The walk of [`canonicalize_lenient`]: `parts` resolved one at a time onto+/// `resolved`, which exists and is canonical (or is empty, and `parts`+/// starts at a root). `path` names the whole path in an error.+fn walk(+ path: &Path,+ mut resolved: PathBuf,+ parts: &[std::path::Component],+ meter: &Meter,+) -> Result<PathBuf, String> {+ use std::path::Component;+ // Linux's MAXSYMLINKS: the most hops `open` itself would follow.+ const MAX_HOPS: usize = 40;// Components still to resolve, next one last so a link splices onto the end.let mut pending: Vec<std::ffi::OsString> =- abs.components().rev().map(|c| c.as_os_str().to_owned()).collect();- let mut resolved = PathBuf::new();+ parts.iter().rev().map(|c| c.as_os_str().to_owned()).collect();let mut hops = 0;+ // How many trailing components of `resolved` are not on disk; 0 while+ // all of it exists (and is canonical).+ let mut missing = 0usize;+ // Components in `resolved`: what a lookup of it walks, and is charged.+ let mut depth = resolved.components().count();while let Some(raw) = pending.pop() {match Path::new(&raw).components().next() {Some(Component::Prefix(_) | Component::RootDir) => {resolved.push(&raw);- if let Ok(root) = resolved.canonicalize() {+ missing = 0;+ if let Some(root) = meter.canonicalize(&resolved)? {resolved = root;}+ depth = resolved.components().count();}Some(Component::ParentDir) => {- resolved.pop();+ if resolved.pop() {+ depth = depth.saturating_sub(1);+ }+ missing = missing.saturating_sub(1);+ }+ Some(Component::Normal(name)) if missing > 0 => {+ // Appended by hand: `push` onto a verbatim Windows path (the+ // project root is one) re-collects all of it, which would make+ // the walk quadratic again. `resolved` ends in a name here, so+ // it needs the separator.+ let s = resolved.as_mut_os_string();+ s.push(std::path::MAIN_SEPARATOR_STR);+ s.push(name);+ missing += 1;+ depth += 1;}Some(Component::Normal(name)) => {- let candidate = resolved.join(name);- if let Ok(real) = candidate.canonicalize() {- resolved = real;+ resolved.push(name);+ depth += 1;+ meter.charge(depth)?;+ // `lstat` first: a name that is not there costs one syscall,+ // where `canonicalize` would read every ancestor again first.+ let Ok(meta) = std::fs::symlink_metadata(&resolved) else {+ missing = 1;continue;- }- let is_link = std::fs::symlink_metadata(&candidate)- .is_ok_and(|m| m.file_type().is_symlink());- if !is_link {- // Does not exist: nothing below it can be a link either way.- resolved = candidate;+ };+ if !meta.file_type().is_symlink() {+ if !spell_as_on_disk(&mut resolved, meter)? {+ missing = 1;+ }continue;}+ // Through a link the lookup walks wherever it leads, which+ // may be far deeper than the text: charged by the result.+ // Where the meter walks all, the target is spliced in and+ // walked instead: one `realpath` through a chain of links+ // into a deep directory took seconds before it could be+ // charged.+ if !meter.walks_all() {+ if let Some(real) = meter.canonicalize(&resolved)? {+ depth = real.components().count();+ resolved = real;+ continue;+ }+ }hops += 1;if hops > MAX_HOPS {return Err(format!("too many levels of symbolic links in {:?}", path));}- let target = std::fs::read_link(&candidate)- .map_err(|e| format!("read link {:?}: {e}", candidate))?;+ meter.charge(depth)?;+ let target = std::fs::read_link(&resolved)+ .map_err(|e| format!("read link {:?}: {e}", resolved))?;+ // The link's name gives way to its target, whose components+ // are charged as they are walked.+ resolved.pop();+ depth = depth.saturating_sub(1);// An absolute target restarts from its own root when its// RootDir component is popped; a relative one stays here.pending.extend(target.components().rev().map(|c| c.as_os_str().to_owned()));@@ -456,6 +990,82 @@ fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {Ok(resolved)}+/// Respell `path`, a canonical directory joined with a name on disk that is+/// no link, the way `canonicalize` would; false if that fails. On Linux it is+/// already spelled so (`realpath` only follows links), and skipping the call+/// saves a syscall per component of the whole prefix: a command of many+/// `dir/..` steps paid seconds for it.+#[cfg(any(target_os = "linux", target_os = "android"))]+fn spell_as_on_disk(path: &mut PathBuf, meter: &Meter) -> Result<bool, String> {+ let _ = (path, meter);+ Ok(true)+}++/// [`spell_as_on_disk`] where the disk may be case-insensitive (macOS,+/// Windows): `canonicalize` spells the name as stored, which is how the+/// roots it is compared with are spelled.+#[cfg(not(any(target_os = "linux", target_os = "android")))]+fn spell_as_on_disk(path: &mut PathBuf, meter: &Meter) -> Result<bool, String> {+ Ok(match meter.canonicalize(path)? {+ Some(real) => {+ *path = real;+ true+ }+ None => false,+ })+}++/// How many of `parts` (an absolute path's components) the OS resolves, up+/// to the first `..`, and their real path; `(0, empty)` when none does. The+/// walk in [`canonicalize_lenient`] starts from there: walked from the root,+/// each existing component costs a `canonicalize` of its whole prefix, so+/// every word of a command (a new leaf, as most are) paid that once per+/// ancestor of the project root.+///+/// A binary search, as the OS resolves a path one component at a time: once+/// a prefix fails every longer one does. That holds only without a `..`,+/// which Windows applies lexically before it opens anything, hence the cut.+/// Each probe stops at the first missing component, so it costs no more+/// than the existing part however long the path is. The deepest candidate+/// is probed first: for a new leaf, the usual miss, that is its directory,+/// found in one probe.+fn existing_prefix(+ parts: &[std::path::Component],+ meter: &Meter,+) -> Result<(usize, PathBuf), String> {+ use std::path::Component;+ let mut lead = parts.iter().take_while(|c| **c != Component::ParentDir).count();+ // The caller already tried the whole path.+ if lead == parts.len() {+ lead -= 1;+ }+ // Never a bare Windows prefix (`C:`): that names the drive's cwd.+ let root = parts+ .iter()+ .take_while(|c| matches!(c, Component::Prefix(_) | Component::RootDir))+ .count()+ .max(1);+ let real = |n: usize| meter.canonicalize(&parts[..n].iter().collect::<PathBuf>());+ if lead < root {+ return Ok((0, PathBuf::new()));+ }+ if let Some(path) = real(lead)? {+ return Ok((lead, path));+ }+ let (mut found, mut lo, mut hi) = ((0, PathBuf::new()), root, lead - 1);+ while lo <= hi {+ let mid = lo + (hi - lo) / 2;+ match real(mid)? {+ Some(path) => {+ found = (mid, path);+ lo = mid + 1;+ }+ None => hi = mid - 1,+ }+ }+ Ok(found)+}+#[cfg(test)]mod windows_name_tests {use super::windows_name_problem as problem;@@ -934,6 +1544,7 @@ mod tests {fn command_touches_hidden_root(project: &Path, hidden: &Path, cmd: &str) -> bool {hidden_tokens(hidden, cmd)+ .unwrap().iter().any(|t| in_hidden_root(project, hidden, t))}@@ -962,6 +1573,200 @@ mod tests {let _ = std::fs::remove_dir_all(&home);}+ /// Every word is a token, whatever shell syntax surrounds it: quotes,+ /// escapes, redirects, substitutions, expansions, arrays, assignments,+ /// extglobs, tests and heredocs. Telling a command name from an argument+ /// takes a shell parser, and each guess at one hid a path.+ #[test]+ fn hidden_tokens_keep_words_after_quoted_or_closing_separators() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ for command in [+ "grep -E \"a|b\" .jan",+ "cat 'x;' .jan",+ "tar czf /tmp/k.tgz \"$(true)\" .jan",+ "cd \"$(true)\".jan && cat config.toml",+ "GIT_DIR=\".jan\" git log",+ "ls &>/dev/null .jan",+ "echo \\; .jan",+ "tar czf - -T - <<E\n.jan\nE",+ "tar czf - -T - <<-'E'\n\t.jan\n\tE\nls",+ "tar czf backup-\"$(date +%F)\".tgz .jan",+ "cat `true` .jan",+ "ls >|/dev/null .jan",+ "ls 2>&1 .jan",+ "echo \"`true`\" .jan",+ "x`true` .jan",+ "cat \\.jan",+ "cat \"$HOME/.jan\"",+ "'.jan'",+ "x=(.jan)",+ "cat <<<.jan",+ "echo \"\\\\$(true)\" .jan",+ "true || cat .jan",+ "sh -c 'cat .jan/config.toml'",+ "a=(\n .jan/k\n)",+ "cat ${f%;} .jan",+ "ls ${x:-|} .jan",+ "NODE_OPTIONS=--require=.jan/x.js node a.js",+ "X+=~/.jan/k cmd",+ "X+=.jan cmd",+ "ls @(.jan|x)",+ "[[ -n x && .jan -nt y ]]",+ "tar czf - -T - <<\"E\\\\x\"\nEx\n.jan\nE\\\\x",+ "<<E\nx\\\nE\n.jan\nE",+ ] {+ let tokens = hidden_tokens(&jan, command).unwrap();+ assert!(+ tokens.iter().any(|t| in_hidden_root_from(&project, &home, &jan, t)),+ "{command:?}: {tokens:?}"+ );+ }+ // A Windows path stays whole: a backslash separates its components+ // there, which is how it resolves into the home on Windows.+ for (command, token) in [+ ("Get-Content .jan\\config.toml", ".jan\\config.toml"),+ ("type C:\\Users\\me\\.jan\\config.toml", "C:\\Users\\me\\.jan\\config.toml"),+ ] {+ let tokens = hidden_tokens(&jan, command).unwrap();+ assert!(tokens.iter().any(|t| t == token), "{command:?}: {tokens:?}");+ }+ #[cfg(windows)]+ assert!(hidden_tokens(&jan, "Get-Content .jan\\config.toml")+ .unwrap()+ .iter()+ .any(|t| in_hidden_root_from(&project, &home, &jan, t)));+ // Command names are tokens too: from a cwd in the home they resolve+ // there, and only the gate's carve-out lets them through.+ assert_eq!(+ hidden_tokens(Path::new("/h/.jan"), "cd /p && ls src | git diff; F=~/.jan/c cat")+ .unwrap(),+ ["cd", "/p", "ls", "src", "git", "diff", "F", "/h/.jan/c", "cat"]+ );+ let _ = std::fs::remove_dir_all(&home);+ }++ /// A command whose tokens would take the gate too long to resolve is+ /// reported as uncheckable (`None`), which the gate refuses; an ordinary+ /// long command, and a `..` under `/proc` with a few globs, is scanned.+ #[test]+ fn hidden_tokens_give_up_on_a_command_too_complex_to_check() {+ let jan = Path::new("/h/.jan");+ let many = "a ".repeat(MAX_TOKENS + 1);+ assert_eq!(hidden_tokens(jan, &many), None);+ let long = format!("cat {}", "x".repeat(MAX_TOKEN_BYTES + 1));+ assert_eq!(hidden_tokens(jan, &long), None);+ // A deep path is the gate's budget to refuse (`resolve_cost`), not+ // the scan's: the scan hands it back whole.+ let deep = format!("cat {}", "a/".repeat(100_000));+ assert_eq!(hidden_tokens(jan, &deep).map(|t| t.len()), Some(2));+ let shallow = format!("cat {}", "a/".repeat(1000));+ assert!(hidden_tokens(jan, &shallow).is_some());+ let globs = |n: usize| format!("cat /proc/..{}", "/*".repeat(n));+ assert_eq!(hidden_tokens(jan, &globs(MAX_LINKED + 1)), None);+ // The two words, `start_dir_relative`'s one and a candidate per glob.+ let tokens = hidden_tokens(jan, &globs(3)).unwrap();+ assert_eq!(tokens.len(), 2 + 1 + 3, "{tokens:?}");+ let script = "cat <<E > notes.md\nsome ordinary words\nE\n".repeat(2000);+ assert!(hidden_tokens(jan, &script).is_some());+ }++ /// A path that stops existing early costs no syscall per missing+ /// component, so its resolution is linear in its length: a quadratic walk+ /// took minutes on a path of this shape, which a model can send as one+ /// tool argument.+ #[test]+ fn a_deep_missing_path_resolves_in_linear_time() {+ let root = unique_root();+ let comp = format!("{}/", "a".repeat(63));+ let deep = root.join("missing").join(comp.repeat(DEEP));+ let start = std::time::Instant::now();+ let resolved = canonicalize_lenient(&deep).unwrap();+ let took = start.elapsed();+ assert!(took < std::time::Duration::from_secs(5), "{took:?}");+ assert_eq!(resolved, root.canonicalize().unwrap().join("missing").join(comp.repeat(DEEP)));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Components after a missing one that climb back out of it with `..`+ /// reach the disk again, so a link there is still followed.+ #[cfg(unix)]+ #[test]+ fn a_climb_out_of_a_missing_tail_follows_links_again() {+ let root = unique_root();+ let outside = unique_root();+ std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();+ let climb = format!("missing/{}{}link/x", "a/".repeat(1000), "../".repeat(1001));+ assert_eq!(+ canonicalize_lenient(&root.join(&climb)).unwrap(),+ outside.canonicalize().unwrap().join("x")+ );+ assert_eq!(escapes_project(&root, None, &climb), Ok(true));+ // One `..` short stays in the missing tail, where nothing is a link.+ let short = format!("missing/{}{}link/x", "a/".repeat(1000), "../".repeat(1000));+ assert_eq!(+ canonicalize_lenient(&root.join(&short)).unwrap(),+ root.canonicalize().unwrap().join("missing/link/x")+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// The gate's metered walk skips the whole-path `canonicalize` and the+ /// prefix probes, but must land where the unmetered one does: through+ /// links absolute, relative and dangling, a regular file mid-path, `..`+ /// after a link and a missing tail.+ #[cfg(unix)]+ #[test]+ fn the_metered_walk_resolves_as_the_unmetered_one() {+ use std::os::unix::fs::symlink;+ let root = unique_root();+ let outside = unique_root();+ std::fs::create_dir_all(root.join("a/b")).unwrap();+ std::fs::write(root.join("a/f"), b"x").unwrap();+ symlink(&outside, root.join("abs")).unwrap();+ symlink("a/b", root.join("rel")).unwrap();+ symlink("../nowhere/x", root.join("a/dangling")).unwrap();+ symlink("loop", root.join("loop")).unwrap();+ let raws = [+ "", "a", "a/b", "a/f", "a/f/x", "a/f/../b", "abs", "abs/new", "abs/..",+ "rel/../f", "rel/../../a", "a/dangling", "a/dangling/y", "loop", "missing/x/..",+ "missing/../rel/z", "./a//b/./", "../",+ ];+ for raw in raws {+ let path = root.join(raw);+ let meter = Meter::new(MAX_RESOLVE_COST);+ assert_eq!(canonicalize_metered(&path, &meter), canonicalize_lenient(&path), "{raw}");+ assert!(!meter.spent(), "{raw}");+ }+ // A spent meter refuses rather than answering.+ let meter = Meter::new(1);+ assert!(canonicalize_metered(&root.join("a/b"), &meter).is_err());+ assert!(meter.spent());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// Components in the path of the timing test, 63 bytes each: a 4 MB path,+ /// just under the scan's byte cap, which a quadratic walk took minutes on.+ const DEEP: usize = 65_000;++ /// The cost is quadratic in a path's own depth and charges a bare word+ /// the depth of the directory it is resolved in.+ #[test]+ fn resolve_cost_grows_with_depth() {+ assert_eq!(resolve_cost(10, "word"), 11);+ assert_eq!(resolve_cost(10, "src/a/b/c.rs"), 4 * 14);+ // Windows spells an absolute path with a drive, not a leading slash.+ #[cfg(unix)]+ assert_eq!(resolve_cost(10, "/usr/lib/x.so"), 4 * 4);+ assert!(resolve_cost(0, &"a/".repeat(2048)) > MAX_RESOLVE_COST);+ assert!(resolve_cost(10, &"a/".repeat(2000)) <= MAX_RESOLVE_COST);+ }+#[test]fn hidden_under_spells_the_home_the_way_a_walk_does() {let home = unique_root();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 0c6b8ac13..9d991aeba 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -30,6 +30,39 @@ pub fn bash_description(kind: super::proc::ShellKind) -> String {/// Appended to the shell description when the run offers escalation.const ESCALATE_NOTE: &str = " Commands run inside an OS sandbox. If a command that matters to the task fails because of the sandbox (a read-only file system or permission error outside the project, such as a package manager writing its cache, or a blocked download), rerun the same command with `escalate: true` and a one-line `justification`: the user is asked to approve running it outside the sandbox. Never escalate pre-emptively, and never to work around a denial the user gave.";+/// Appended to the shell description when the caller rings a completion+/// doorbell (`ToolContext::shell_done_sink`), so the model learns up front --+/// not only from a hand-off result -- that a backgrounded command needs no polling.+const BACKGROUND_NOTE: &str = " A command that outlives its `timeout` keeps running in the background and you are notified automatically when it finishes, with where its output was written: do not poll, sleep, or re-run it to check; carry on with other work or end your turn.";++/// Appended for an agent run, which leaves off `[exit 0]` after output (see+/// `handlers::model_shell_result`). An MCP client keeps every marker, as the+/// plain description promises.+const EXIT_NOTE: &str = " In this session `[exit 0]` is left off when the command printed output: output with no exit line means it succeeded. A nonzero exit or a signal is always reported.";++/// Appended when the caller carries the shell's directory across calls+/// (`ToolContext::shell_cwd`), so the model stops prefixing every command with+/// `cd <path> &&`.+const CWD_NOTE: &str = " The working directory persists between calls: after `cd dir`, later calls start in `dir` until you `cd` elsewhere, and a note in the result tells you whenever it changes. Do not repeat `cd <path> &&` in every command. Other tools still resolve relative paths against the project root.";++/// Add the agent session's shell notes to the `shell` schema in `schemas`:+/// [`BACKGROUND_NOTE`] and [`EXIT_NOTE`] always, [`CWD_NOTE`] with+/// `persistent_cwd`. An MCP client served the same schemas gets none of these+/// behaviours, so it keeps the plain description.+pub fn offer_session_shell(schemas: &mut [Value], persistent_cwd: bool) {+ for schema in schemas.iter_mut() {+ let function = &mut schema["function"];+ if function["name"] != super::SHELL_TOOL {+ continue;+ }+ if let Some(description) = function["description"].as_str() {+ let cwd = if persistent_cwd { CWD_NOTE } else { "" };+ function["description"] =+ Value::String(format!("{description}{EXIT_NOTE}{BACKGROUND_NOTE}{cwd}"));+ }+ }+}+/// Add the escalation arguments to the `shell` schema in `schemas`, for a run/// whose shell is sandboxed and whose user can be asked to lift it. Applied/// once per run by the caller, so the array stays byte-identical across turns;@@ -316,6 +349,32 @@ mod tests {use super::*;use crate::tools::BUILTIN_TOOLS;+ /// The plain array (what an MCP client is served) promises neither a+ /// completion notice nor a persistent directory; offering them touches only+ /// the shell entry, and the directory note only when asked for.+ #[test]+ fn session_shell_notes_are_offered_only_on_request_and_only_on_the_shell() {+ let plain = builtin_tool_schemas();+ let plain_text = serde_json::to_string(&plain).unwrap();+ assert!(!plain_text.contains("notified automatically"));+ assert!(!plain_text.contains("directory persists"));+ for persistent_cwd in [false, true] {+ let mut offered = plain.clone();+ offer_session_shell(&mut offered, persistent_cwd);+ for (before, after) in plain.iter().zip(&offered) {+ if before["function"]["name"] == crate::tools::SHELL_TOOL {+ let text = after["function"]["description"].as_str().unwrap();+ assert!(text.contains("notified automatically when it finishes"), "{text}");+ assert!(text.contains("do not poll"), "{text}");+ assert!(text.contains("output with no exit line means it succeeded"), "{text}");+ assert_eq!(text.contains("directory persists"), persistent_cwd, "{text}");+ } else {+ assert_eq!(before, after);+ }+ }+ }+ }+/// The plain array never mentions escalation; offering it touches only the/// shell entry, adding both arguments and the when-to-use note.#[test]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rsindex a012c8d20..86cb89b23 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs@@ -224,7 +224,9 @@ mod shell_tool {.unwrap_or_else(|| panic!("notice names the output file: {started}"));let body = wait_for(&path).expect("output file must appear after the command finishes");assert!(body.contains("done"), "unexpected: {body}");- assert!(body.contains("[exit 0]"), "carries the exit marker: {body}");+ // The model reads this file, so it gets the result a direct call+ // would: output present, so no exit marker.+ assert!(!body.contains("[exit"), "a clean exit carries no marker: {body}");let _ = std::fs::remove_file(&path);eprintln!("sandbox_spawn: shell tool ok");diff --git a/src-tauri/src/core/agent/child_workspace.rs b/src-tauri/src/core/agent/child_workspace.rsindex 265a1b119..10965853e 100644--- a/src-tauri/src/core/agent/child_workspace.rs+++ b/src-tauri/src/core/agent/child_workspace.rs@@ -3,9 +3,12 @@//!//! Decided by the harness when the child is dispatched, never by a tool the//! model calls. A child whose tool set can change files (`write`/`edit`) is a-//! *writer* and gets a fresh checkout on `jan/agent/<name>-<id>`, so parallel-//! writers never edit one checkout and none of them mixes its edits with the-//! user's uncommitted work. Every other child is a *reader*: it runs in the+//! *writer*. With subagent worktrees on (`--subagent-worktrees`,+//! `[agent].subagent_worktrees`; off by default) it gets a fresh checkout on+//! `jan/agent/<name>-<id>`, so parallel writers never edit one checkout and+//! none of them mixes its edits with the user's uncommitted work; off, it+//! shares the parent's checkout and concurrent writers are not serialized.+//! Every other child is a *reader*: it runs in the//! checkout it was given with that checkout read-only, enforced by the file//! tools and by a sandbox that is always on for it.//!@@ -293,7 +296,7 @@ pub(crate) fn scope_for(ws: &ChildWorkspace, parent_root: &Path) -> ChildScope {read_only: ws.read_only,..ChildScope::default()};- if ws.worktree.is_some() || ws.read_only {+ if builds_in_cache(ws) {if let Some(target) = project_worktrees_dir(parent_root).map(|d| d.join(CARGO_TARGET)) {if std::fs::create_dir_all(&target).is_ok() {scope.env_set.push((@@ -310,40 +313,110 @@ pub(crate) fn scope_for(ws: &ChildWorkspace, parent_root: &Path) -> ChildScope {scope}+/// Whether a child in `ws` is given the shared build directory: any child+/// outside the plain writable checkout, readers in the parent's own checkout+/// included.+fn builds_in_cache(ws: &ChildWorkspace) -> bool {+ ws.worktree.is_some() || ws.read_only+}+/// What a child's args take from its workspace beyond `project_root`, read/// from git by [`place`] when the child is dispatched.-#[derive(Debug, Clone)]+#[derive(Debug)]pub(crate) struct Placement {/// The child's own Session Start, when it is not in the parent's checkout.session_start: Option<crate::core::agent::context::SessionStart>,scope: ChildScope,+ /// The child's shared lock on the build directory (see+ /// [`hold_build_cache`]), which the child keeps until it is done.+ build_hold: Option<std::fs::File>,}/// Resolve the [`Placement`] of a child in `ws`: its checkout's branch and the/// scope its tools enforce. Runs git, so the dispatch calls it on-/// the blocking pool and [`apply`], on the async child task, runs none.+/// the blocking pool and [`apply`], on the async child task, runs none. The+/// build lock is taken before the scope creates the build directory, so a+/// trim never moves it away between the two.pub(crate) fn place(ws: &ChildWorkspace, parent_root: &Path) -> Placement {+ let build_hold = builds_in_cache(ws).then(|| hold_build_cache(parent_root)).flatten();Placement {session_start: ws.worktree.as_ref().map(|wt| {crate::core::agent::context::SessionStart::with_branch(worktree_branch(wt))}),scope: scope_for(ws, parent_root),+ build_hold,}}/// Point a child's run at its workspace: `project_root` (and so its prompt's/// Working Directory and Runtime Environment blocks), its own Session Start/// when it is not in the parent's checkout, and the scope its tools enforce.+/// Returns the child's build lock, which the caller holds until the child+/// has finished: dropping it lets a trim move the build directory away.pub(crate) fn apply(args: &mut crate::core::agent::r#loop::OrchestrationArgs,ws: &ChildWorkspace,placement: Placement,-) {+) -> Option<std::fs::File> {if let Some(start) = placement.session_start {args.session_start = Some(start);}args.project_root = Some(ws.root.clone());args.child_scope = Some(placement.scope);+ placement.build_hold+}++/// The lock file every build in the project's shared build directory holds+/// shared, and a trim or clear exclusive. Under `.meta`, out of every+/// child's write roots, so no child can replace it.+#[cfg(feature = "cli")]+const BUILD_LOCK: &str = "cargo-target.lock";++/// Take a shared lock on `root`'s project's build lock, for a child that+/// builds in the shared build directory: while any such lock is held, in+/// this process or another, [`trim_build_cache`] and [`clear_build_cache`]+/// leave the directory alone. Waits out a trim's brief exclusive hold (the+/// dispatch runs on the blocking pool). `None` when it cannot be locked: the+/// filesystem then cannot lock for a trim either, so none happens.+///+/// The hold lasts as long as the child's run. A build the child detached+/// itself (`nohup cargo build &`) outlives it, and a trim may then move the+/// directory under that build, which fails or rebuilds. Accepted: nothing+/// is lost but build time, and tracking every process a child leaves behind+/// is not something a lock file can do.+#[cfg(feature = "cli")]+fn hold_build_cache(root: &Path) -> Option<std::fs::File> {+ let file = open_build_lock(&project_worktrees_dir(root)?)?;+ fs4::FileExt::lock_shared(&file).ok()?;+ Some(file)+}++/// The build lock of the worktrees in `dir`, created if need be; never a+/// link, so nothing else is locked through it.+#[cfg(feature = "cli")]+fn open_build_lock(dir: &Path) -> Option<std::fs::File> {+ let meta = dir.join(META_DIR);+ std::fs::create_dir_all(&meta).ok()?;+ crate::core::agent::session_log::open_no_follow(+ std::fs::OpenOptions::new().write(true).create(true).truncate(false),+ &meta.join(BUILD_LOCK),+ )+ .ok()+}++/// The desktop gives no child the shared build directory.+#[cfg(not(feature = "cli"))]+fn hold_build_cache(_root: &Path) -> Option<std::fs::File> {+ None+}++/// The exclusive lock on the build lock of the worktrees in `dir`, taken+/// without waiting: `None` while any child builds there (or the filesystem+/// cannot lock, when no build can be shown to have stopped). Held across+/// the move of the build directory only.+#[cfg(feature = "cli")]+fn lock_build_cache(dir: &Path) -> Option<std::fs::File> {+ lock(open_build_lock(dir)?).ok()}/// The directory the parent's sandboxed tools may read its children's@@ -377,6 +450,18 @@ struct LedgerState {/// The lock on each of `created`'s metadata, held so no other jan/// process's startup sweep takes a worktree this one still owns.holds: HashMap<PathBuf, std::fs::File>,+ /// Worktrees a conversation end took and still holds, each with the+ /// generation of its newest mark (see [`Settling`]).+ #[cfg(feature = "cli")]+ settling: HashMap<PathBuf, u64>,+ /// The generation the last [`Settling`] mark took.+ #[cfg(feature = "cli")]+ marks: u64,+ /// The parent's checkout of the last assignment: whose project's shared+ /// build directory the session end may trim. The desktop makes no+ /// checkouts, so has no build directory to trim.+ #[cfg(feature = "cli")]+ root: Option<PathBuf>,}/// The session's record of its children's workspaces.@@ -403,13 +488,16 @@ impl Drop for WriterLease {impl Ledger {/// Assign `name` its workspace and record it. A writer in a worktree gets/// the lease that keeps a second writer out until it is done: a second- /// writer naming a busy worktree is refused, not queued.+ /// writer naming a busy worktree is refused, not queued. `worktrees` is+ /// whether a writer with no `request` gets a worktree of its own; without+ /// it, it shares the parent's checkout. A request is honored either way.pub(crate) fn assign(self: &Arc<Self>,parent_root: &Path,name: &str,writer: bool,request: Option<&WorkspaceRequest>,+ worktrees: bool,) -> Result<(ChildWorkspace, Option<WriterLease>), String> {let read_only = !writer && READ_ONLY_READERS;let (ws, hold) = match request {@@ -432,10 +520,14 @@ impl Ledger {}Some(WorkspaceRequest::New) => create(parent_root, name, None, read_only)?,Some(WorkspaceRequest::Ref(r)) => create(parent_root, name, Some(r), read_only)?,- None if writer => create(parent_root, name, None, read_only)?,+ None if writer && worktrees => create(parent_root, name, None, read_only)?,None => (ChildWorkspace::shared(parent_root, read_only), None),};let mut state = self.state.lock().unwrap();+ #[cfg(feature = "cli")]+ {+ state.root = Some(parent_root.to_path_buf());+ }// A reuse was looked up under an earlier hold of the lock: a sweep may// have removed that worktree since (dropping it from `created`). Only// a worktree the ledger still records, and that is still on disk, is@@ -526,16 +618,22 @@ impl Ledger {if gone {forget_meta(wt);}+ self.release(&wt.path, gone);+ gone+ }++ /// End a [`Self::claim`] of `path`; when it is `gone`, forget it and+ /// every name that pointed at it, dropping its lock.+ fn release(&self, path: &Path, gone: bool) {let mut state = self.state.lock().unwrap();- state.removing.remove(&wt.path);+ state.removing.remove(path);if gone {- state.holds.remove(&wt.path);- state.created.retain(|c| c.path != wt.path);+ state.holds.remove(path);+ state.created.retain(|c| c.path != path);state.by_name- .retain(|_, ws| ws.worktree.as_ref().is_none_or(|w| w.path != wt.path));+ .retain(|_, ws| ws.worktree.as_ref().is_none_or(|w| w.path != path));}- gone}}@@ -544,20 +642,243 @@ impl Ledger {/// work, since removal deletes it. Returns whether it went.#[cfg(feature = "cli")]fn remove_if_empty(wt: &ChildWorktree) -> bool {- empty_into_trash(wt).is_some()+ matches!(dispose(wt, false), Disposition::Removed { .. })}-/// [`remove_if_empty`], saying how it went: `Some(true)` when it was moved-/// into trash, `Some(false)` when deleted in place, `None` when kept.+/// What [`dispose`] did with a checkout.#[cfg(feature = "cli")]-fn empty_into_trash(wt: &ChildWorktree) -> Option<bool> {+enum Disposition {+ /// It went (see [`Gone`]). `brought` names its branch when it held+ /// commits, which are now only in the user's repository.+ Removed { gone: Gone, brought: Option<String> },+ /// It stays. `not_brought` says why its branch is not in the user's+ /// repository, when bringing it back failed.+ Kept { not_brought: Option<String> },+}++/// The one rule every settle and undo removes a checkout by. It may go when+/// it is clean (nothing uncommitted, no untracked file that is not ignored)+/// and either holds no commit past its base, or (with `bring`) its branch was+/// brought into the user's repository and that branch there reaches every+/// commit the checkout holds on any ref. Anything else stays: uncommitted+/// work, a branch that could not be brought back, commits off the branch,+/// and any checkout git cannot read, since removal deletes what it holds.+#[cfg(feature = "cli")]+fn dispose(wt: &ChildWorktree, bring: bool) -> Disposition {+ let keep = Disposition::Kept { not_brought: None };+ let first = classify(wt);+ // Everything it holds is in the user's repository already: no fetch is+ // needed, so none can fail and keep it.+ if let CheckoutState::Removable { commits } = first {+ return removed(wt, (commits > 0).then(|| wt.branch.clone()));+ }+ if !bring {+ return keep;+ }+ // Whatever the child committed, kept or not, so the user has the branch+ // to merge. One git cannot read fails here, and is kept.+ if let Err(why) = bring_back(wt) {+ return Disposition::Kept { not_brought: Some(why) };+ }+ // Only bringing the branch back can change where it stands.+ let now = match first {+ CheckoutState::Unbrought { .. } => classify(wt),+ other => other,+ };+ match now {+ CheckoutState::Removable { .. } => removed(wt, Some(wt.branch.clone())),+ _ => keep,+ }+}++/// Where a subagent checkout stands, for the user deciding what to prune.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[serde(tag = "state", rename_all = "snake_case")]+pub(crate) enum CheckoutState {+ /// A running subagent of this session works in it, or another live jan+ /// session owns it: never removed from here.+ InUse { by: InUseBy },+ /// Uncommitted work that is only in it: changed, untracked and ignored+ /// files that are not build output (see [`Checkout::uncommitted`]).+ /// `commits` past its base, of which `off_branch` are on no branch (a+ /// stash, a tag, a detached `HEAD`), which bringing its branch back does+ /// not carry. `build_output` names the ignored build output a forced+ /// removal deletes with it, relative to the checkout; it is measured+ /// only where a number is shown (see [`sizes`]), not by every classify.+ /// In `jan cli worktrees list --json` it is therefore an array of those+ /// paths (it used to be a byte count); the bytes are `build_output_bytes`.+ ///+ /// [`Checkout::uncommitted`]: crate::core::agent::git::Checkout::uncommitted+ Uncommitted { files: Vec<String>, commits: u64, off_branch: u64, build_output: Vec<String> },+ /// Clean, with commits its branch in the user's repository lacks.+ Unbrought { commits: u64 },+ /// Clean, and everything it committed (if anything) is in the user's+ /// repository: removing it loses nothing.+ Removable { commits: u64 },+ /// No longer what Jan made, or git cannot read it: never removed.+ Unreadable { why: String },+}++/// Who holds a checkout that is [`CheckoutState::InUse`].+#[cfg(feature = "cli")]+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum InUseBy {+ Child,+ Session,+ /// This session's conversation end is settling it (bringing its branch+ /// back), or holds it until the user is told it was kept.+ Settling,+}++/// How many uncommitted paths a description names before eliding the rest.+#[cfg(feature = "cli")]+const NAMED_FILES: usize = 3;++#[cfg(feature = "cli")]+impl CheckoutState {+ /// The state in words, for a list row.+ pub(crate) fn describe(&self) -> String {+ match self {+ Self::InUse { by: InUseBy::Child } => "in use by a running subagent".to_string(),+ Self::InUse { by: InUseBy::Session } => {+ "in use by another live jan session".to_string()+ }+ Self::InUse { by: InUseBy::Settling } => {+ "in use by this session, which is settling it".to_string()+ }+ Self::Uncommitted { files, commits, .. } => {+ let more = match files.len().saturating_sub(NAMED_FILES) {+ 0 => String::new(),+ n => format!(" and {n} more"),+ };+ let named = files.iter().take(NAMED_FILES).cloned().collect::<Vec<_>>();+ let commits = match commits {+ 0 => String::new(),+ n => format!("; {n} commit(s)"),+ };+ format!("holds uncommitted work: {}{more}{commits}", named.join(", "))+ }+ Self::Unbrought { .. } => format!("holds {}", self.loses().unwrap_or_default()),+ Self::Removable { commits: 0 } => "removable (no work in it)".to_string(),+ Self::Removable { commits } => {+ format!("removable ({commits} commit(s), all in your repository)")+ }+ Self::Unreadable { why } => format!("kept, git cannot read it: {why}"),+ }+ }++ /// What removing it would lose, when the user may still remove it after+ /// confirming; `None` when it loses nothing or may not be removed here.+ /// A removal brings its branch back first (see [`Self::brings_back`]),+ /// so the commits on it are not lost; an `Unbrought` one's are, since+ /// its branch could not be brought back.+ /// The build output it deletes as well is not named here: see+ /// [`CheckoutInfo::loses`], which has it measured.+ pub(crate) fn loses(&self) -> Option<String> {+ match self {+ Self::Uncommitted { files, off_branch, .. } => {+ let stashed = match off_branch {+ 0 => String::new(),+ n => format!(" and {n} commit(s) on no branch"),+ };+ Some(format!("{} uncommitted file(s){stashed}", files.len()))+ }+ Self::Unbrought { commits } => {+ Some(format!("{commits} commit(s) not in your repository"))+ }+ _ => None,+ }+ }++ /// What a removal keeps by bringing the branch into the user's+ /// repository first, for the confirm; `None` when there is nothing to+ /// bring back.+ pub(crate) fn brings_back(&self) -> Option<String> {+ match self {+ Self::Uncommitted { commits, off_branch, .. } if commits > off_branch => Some(format!(+ "its branch ({} commit(s)) is brought back to your repository first",+ commits - off_branch+ )),+ _ => None,+ }+ }+}++/// `" plus ignored build output (<size>)"` when a forced removal deletes+/// `bytes` of it, else nothing: not work, but space the user should know+/// goes with the checkout rather than be surprised by.+#[cfg(feature = "cli")]+fn plus_build_output(bytes: u64) -> String {+ match bytes {+ 0 => String::new(),+ n => format!(" plus ignored build output ({})", human_bytes(n)),+ }+}++/// Where a checkout stands under [`dispose`]'s rule, read without changing+/// anything: what `/worktrees` shows, and what every removal decides by.+#[cfg(feature = "cli")]+fn classify(wt: &ChildWorktree) -> CheckoutState {// A checkout that is no longer what Jan made is never removed: what it// holds cannot be read without trusting it.- let checkout = checkout(wt).ok()?;- if checkout.commits_anywhere(&wt.base) != Some(0) || checkout.is_clean() != Ok(true) {- return None;+ let checkout = match checkout(wt) {+ Ok(checkout) => checkout,+ Err(why) => return CheckoutState::Unreadable { why },+ };+ let commits = checkout.commits_anywhere(&wt.base);+ match checkout.work() {+ Ok(work) if work.is_empty() => {}+ Ok(work) => {+ // A submodule's work is not a path status lists: say so rather+ // than show no file.+ let files = match work.paths {+ files if !files.is_empty() => files,+ _ => vec!["a submodule".to_string()],+ };+ let build_output = work.build_output;+ let on_branch = checkout.commits_on(&wt.base, &format!("refs/heads/{}", wt.branch));+ let (commits, off_branch) = match (commits, on_branch) {+ // The branch is among the refs counted, so the rest are on+ // no branch.+ (Some(all), Some(on)) => (all, all.saturating_sub(on)),+ // Unknown is all off the branch: the confirm must not+ // promise to bring back what may not be there.+ (all, _) => (all.unwrap_or(0), all.unwrap_or(0)),+ };+ return CheckoutState::Uncommitted { files, commits, off_branch, build_output };+ }+ Err(why) => return CheckoutState::Unreadable { why },+ }+ match commits {+ Some(0) => CheckoutState::Removable { commits: 0 },+ Some(n) if in_users_branch(wt, &checkout) => CheckoutState::Removable { commits: n },+ Some(n) => CheckoutState::Unbrought { commits: n },+ None => CheckoutState::Unreadable { why: "git could not count its commits".to_string() },+ }+}++/// Move `wt` into the trash for [`dispose`], never deleting it: the trash+/// keeps it a week in case the check missed work. Kept when it cannot be+/// moved, which leaks it but loses nothing.+#[cfg(feature = "cli")]+fn removed(wt: &ChildWorktree, brought: Option<String>) -> Disposition {+ match move_to_trash(&wt.path) {+ Some(to) => Disposition::Removed { gone: Gone::Trashed(to), brought },+ None => Disposition::Kept { not_brought: None },}- trash(&wt.path)+}++/// Whether the user's branch `wt.branch` reaches every commit the checkout+/// holds, on any ref or `HEAD`: only then is nothing lost with the checkout.+/// The user's tip must be an object the checkout has, which a fetch it+/// fast-forwarded guarantees; a branch the user has since built on reads as+/// `None` here and keeps the checkout, which is the safe side.+#[cfg(feature = "cli")]+fn in_users_branch(wt: &ChildWorktree, checkout: &crate::core::agent::git::Checkout) -> bool {+ crate::core::agent::git::resolve_commit(&wt.repo, &format!("refs/heads/{}", wt.branch))+ .is_some_and(|tip| checkout.commits_anywhere(&tip) == Some(0))}/// Where Jan keeps what it knows of each checkout of a project: beside the@@ -584,10 +905,14 @@ const UNLOCKED_EXT: &str = "unlocked";/// reopens an existing lock file, see [`reserve`]).fn forget_meta(wt: &ChildWorktree) {let (Some(dir), Some(id)) = (wt.path.parent(), wt.path.file_name()) else { return };- let id = id.to_string_lossy();- let _ = std::fs::remove_file(meta_file(dir, &id, "json"));- let _ = std::fs::remove_file(meta_file(dir, &id, UNLOCKED_EXT));- let _ = std::fs::remove_file(meta_file(dir, &id, "lock"));+ forget_meta_at(dir, &id.to_string_lossy());+}++/// [`forget_meta`] by checkout id, for a checkout with no usable record.+fn forget_meta_at(dir: &Path, id: &str) {+ let _ = std::fs::remove_file(meta_file(dir, id, "json"));+ let _ = std::fs::remove_file(meta_file(dir, id, UNLOCKED_EXT));+ let _ = std::fs::remove_file(meta_file(dir, id, "lock"));}/// What Jan recorded about a subagent checkout when it made it, so a later@@ -679,23 +1004,36 @@ fn reserve_with(}}-/// Move a checkout that holds nothing out of the way at once, into the-/// project's trash: deleting in place walks every file a child left-/// (`node_modules`, build output) while the user waits, and the trash keeps-/// it a while in case the emptiness check missed work. Deletes in place when-/// the rename fails (something mounted there, a handle still open on-/// Windows). `Some(true)` when trashed, `Some(false)` when deleted, `None`-/// when it is still there.+/// Get a checkout the user confirmed losing out of the way: renamed into the+/// project's trash first, so the caller can delete it there after dropping+/// its record, else deleted in place (something mounted there, a handle+/// still open on Windows). `None` when it is still there.#[cfg(feature = "cli")]-fn trash(path: &Path) -> Option<bool> {- if let (Some(dir), Some(id)) = (path.parent(), path.file_name()) {- let bin = dir.join(TRASH_DIR);- let to = bin.join(tauri_plugin_agent_tools::workspace::trash_name(&id.to_string_lossy()));- if std::fs::create_dir_all(&bin).is_ok() && std::fs::rename(path, to).is_ok() {- return Some(true);- }+fn trash(path: &Path) -> Option<Gone> {+ if let Some(to) = move_to_trash(path) {+ return Some(Gone::Trashed(to));}- std::fs::remove_dir_all(path).is_ok().then_some(false)+ std::fs::remove_dir_all(path).is_ok().then_some(Gone::Deleted)+}++/// How [`trash`] got a directory out of the way.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, PartialEq, Eq)]+enum Gone {+ /// Renamed to this path in the trash.+ Trashed(PathBuf),+ /// Deleted in place.+ Deleted,+}++/// Rename `path` into the trash beside it, never deleting anything. Where+/// it went, when it moved.+#[cfg(feature = "cli")]+fn move_to_trash(path: &Path) -> Option<PathBuf> {+ let (dir, id) = (path.parent()?, path.file_name()?);+ let bin = dir.join(TRASH_DIR);+ let to = bin.join(tauri_plugin_agent_tools::workspace::trash_name(&id.to_string_lossy()));+ (std::fs::create_dir_all(&bin).is_ok() && std::fs::rename(path, &to).is_ok()).then_some(to)}/// Delete what has been in the trash of `root`'s project for@@ -909,6 +1247,33 @@ fn create(struct Owned {wt: ChildWorktree,hold: Option<std::fs::File>,+ /// Set while a ledger's conversation end owns it, so `/worktrees` names+ /// it as this session's rather than another live one's.+ mark: Option<Settling>,+}++/// A ledger's mark on a worktree its conversation end took: the session+/// still holds it (settling it, or until the user is told it was kept)+/// though it is no longer among the ledger's `created`. Unmarked on drop,+/// unless a newer mark took the same path meanwhile (a later conversation+/// end of a reused checkout): `generation` tells the two apart, so an old+/// mark dropping late never unmarks what the session still holds.+#[cfg(feature = "cli")]+#[derive(Debug)]+struct Settling {+ ledger: Arc<Ledger>,+ path: PathBuf,+ generation: u64,+}++#[cfg(feature = "cli")]+impl Drop for Settling {+ fn drop(&mut self) {+ let mut state = self.ledger.state.lock().unwrap();+ if state.settling.get(&self.path) == Some(&self.generation) {+ state.settling.remove(&self.path);+ }+ }}/// Worktrees taken from a ledger (or found orphaned) to be settled, off the@@ -959,6 +1324,10 @@ impl Batch {settled.trashed += 1;settled.trash = Some(bin);}+ Outcome::Brought(branch, bin) => {+ settled.brought.push(branch);+ settled.brought_to = Some(bin);+ }Outcome::Gone => {}}}@@ -976,6 +1345,13 @@ pub(crate) struct Settled {/// emptiness check can miss work, and the user must know where to look.trashed: usize,trash: Option<PathBuf>,+ /// The branches whose checkouts went once their commits were brought+ /// into the user's repository: where that work is now. Their checkouts+ /// wait in the trash at `brought_to`.+ brought: Vec<String>,+ brought_to: Option<PathBuf>,+ /// Set when the shared build directory was over its cap and cleared.+ cache_notice: Option<String>,/// Kept orphans not yet marked reported, each still locked: a sweep marks/// them only once its notice is taken, so a run that ends before it can/// show it leaves them for the next start to report.@@ -987,7 +1363,33 @@ impl Settled {/// The notices naming what was kept and where the empty ones went, each/// shown on its own: the trash line is not one of the kept worktrees.pub(crate) fn notices(&self) -> Vec<String> {- self.kept_notice().into_iter().chain(self.trash_notice()).collect()+ self.kept_notice()+ .into_iter()+ .chain(self.brought_notice())+ .chain(self.trash_notice())+ .chain(self.cache_notice.clone())+ .collect()+ }++ /// The branches brought back whose checkouts went: the one place the+ /// user learns where that work is, so each is named once.+ /// The checkouts wait in the trash, since one may hold what the check+ /// missed, and the user must know where to look.+ fn brought_notice(&self) -> Option<String> {+ let bin = self.brought_to.as_deref().map(display).unwrap_or_default();+ let days = tauri_plugin_agent_tools::workspace::TRASH_KEPT_FOR.as_secs() / 86_400;+ match self.brought.as_slice() {+ [] => None,+ [one] => Some(format!(+ "brought back branch {one}, moved its worktree to {bin}; deleted after {days} days"+ )),+ many => Some(format!(+ "brought back {} branches, moved their worktrees to {bin}; deleted after {days} \+ days\n{}",+ many.len(),+ many.join("\n")+ )),+ }}fn kept_notice(&self) -> Option<String> {@@ -1013,7 +1415,10 @@ impl Settled {if self.kept_notice().is_some_and(&mut *report) {self.mark_reported();}- if let Some(notice) = self.trash_notice() {+ // The checkout and its record are gone already, so an untold one is+ // not repeated: the branch itself stays in the user's repository.+ let rest = self.brought_notice().into_iter().chain(self.trash_notice());+ for notice in rest.chain(self.cache_notice.take()) {report(notice);}}@@ -1021,9 +1426,9 @@ impl Settled {/// The user has been told about the kept worktrees: no later sweep/// repeats them. Their locks drop once each is marked.fn mark_reported(&mut self) {- for Owned { wt, hold } in self.unmarked.drain(..) {+ for Owned { wt, hold, mark } in self.unmarked.drain(..) {let _ = write_meta(&wt, true);- drop(hold);+ drop((hold, mark));}}}@@ -1038,6 +1443,9 @@ enum Outcome {KeptUnmarked(String, Owned),/// It held nothing and went into the trash at this path.Trashed(PathBuf),+ /// Its commits were brought back on this branch of the user's+ /// repository, and the checkout went into the trash at this path.+ Brought(String, PathBuf),/// It held nothing and is gone, or it stays the ledger's unreported.Gone,}@@ -1053,7 +1461,7 @@ fn settle_one(report_busy: bool,mark_when_told: bool,) -> Outcome {- let Owned { wt, hold } = one;+ let Owned { wt, hold, mark } = one;if let Some(ledger) = ledger {if !ledger.claim(&wt.path) {let mut state = ledger.state.lock().unwrap();@@ -1071,33 +1479,39 @@ fn settle_one(};}}- let emptied = if wt.path.is_dir() { empty_into_trash(&wt) } else { Some(false) };- let outcome = if let Some(trashed) = emptied {- forget_meta(&wt);- match (trashed, wt.path.parent()) {- (true, Some(dir)) => Outcome::Trashed(dir.join(TRASH_DIR)),- _ => Outcome::Gone,- }- } else {- // Whatever the child committed before it was stopped, so the user- // has the branch to merge.- let brought = bring_back(&wt).err();- let line = kept_line(&wt, brought.as_deref());+ let disposed = match wt.path.is_dir() {+ true => dispose(&wt, true),+ false => Disposition::Removed { gone: Gone::Deleted, brought: None },+ };+ let outcome = if let Disposition::Kept { not_brought } = disposed {+ let line = kept_line(&wt, not_brought.as_deref());if mark_when_told {if let Some(ledger) = ledger {ledger.state.lock().unwrap().removing.remove(&wt.path);}- return Outcome::KeptUnmarked(line, Owned { wt, hold });+ return Outcome::KeptUnmarked(line, Owned { wt, hold, mark });}// This process names it at its own end, so the user owns it now: no// later sweep reports it again.let _ = write_meta(&wt, true);Outcome::Kept(line)+ } else {+ forget_meta(&wt);+ match disposed {+ Disposition::Removed { gone: Gone::Trashed(to), brought } => {+ let bin = to.parent().map(Path::to_path_buf).unwrap_or(to);+ match brought {+ Some(branch) => Outcome::Brought(branch, bin),+ None => Outcome::Trashed(bin),+ }+ }+ _ => Outcome::Gone,+ }};if let Some(ledger) = ledger {ledger.state.lock().unwrap().removing.remove(&wt.path);}- drop(hold);+ drop((hold, mark));outcome}@@ -1122,8 +1536,27 @@ impl Ledger {/// The ledger's lock is held only to take the worktrees and to record/// each decision, never across git, so leases and dispatches carry on/// meanwhile.+ ///+ /// Then, once no writer of this session is left building, the project's+ /// shared build directory is deleted if it outgrew its cap (see+ /// [`trim_build_cache`]).pub(crate) fn finish_session(self: &Arc<Self>) -> Settled {- self.take(true).settle()+ self.finish_with(crate::core::agent::project::subagent_build_cache_cap)+ }++ /// [`Self::finish_session`] with the build directory's cap, in bytes,+ /// read by `cap_of` from the project root, so a test can make it small.+ fn finish_with(self: &Arc<Self>, cap_of: impl FnOnce(&Path) -> u64) -> Settled {+ let mut settled = self.take(true).settle();+ let (root, idle) = {+ let state = self.state.lock().unwrap();+ (state.root.clone(), state.busy.is_empty() && state.removing.is_empty())+ };+ // A writer still in its worktree may be mid-build in that directory.+ if let Some(root) = root.filter(|_| idle) {+ settled.cache_notice = trim_build_cache(&root, cap_of(&root));+ }+ settled}fn take(self: &Arc<Self>, busy_too: bool) -> Batch {@@ -1137,11 +1570,20 @@ impl Ledger {continue;}let hold = state.holds.remove(&wt.path);- owned.push(Owned { wt, hold });+ let mark = Some(self.mark(state, &wt.path));+ owned.push(Owned { wt, hold, mark });}Batch { ledger: Some(self.clone()), owned, report_busy: busy_too, mark_when_told: false }}+ /// Mark `path` as held by this ledger's conversation end, in its locked+ /// `state`, until the returned mark drops.+ fn mark(self: &Arc<Self>, state: &mut LedgerState, path: &Path) -> Settling {+ state.marks += 1;+ state.settling.insert(path.to_path_buf(), state.marks);+ Settling { ledger: self.clone(), path: path.to_path_buf(), generation: state.marks }+ }+/// The session's subagent worktrees still on disk, for `/worktree`. Runs/// git per worktree, outside the ledger's lock.pub(crate) fn live(&self) -> Vec<String> {@@ -1180,25 +1622,9 @@ pub(crate) fn sweep_orphans(root: &Path) -> Settled {if !is_checkout_id(id) {continue;}- // Reserved without a lock: nothing can show its owner is gone.- if meta_file(&dir, id, UNLOCKED_EXT).exists() {- continue;- }// Once: a lock that is not free right now has a live owner, and// skipping is always safe.- let Ok(hold) = crate::core::agent::session_log::open_no_follow(- std::fs::OpenOptions::new().write(true),- &entry.path(),- )- .and_then(lock) else {- continue;- };- // The owner may have unlinked this lock (it settled the worktree)- // between the open and the lock, and a new owner of a reused id made- // a fresh one: the lock taken is then on a file no one else sees.- if !still_at(&hold, &entry.path()) {- continue;- }+ let Probe::Free(hold) = probe_lock(&dir, id) else { continue };let path = dir.join(id);let present = std::fs::symlink_metadata(&path);let meta = match std::fs::read(meta_file(&dir, id, "json")) {@@ -1217,7 +1643,9 @@ pub(crate) fn sweep_orphans(root: &Path) -> Settled {let Some(wt) = recorded_worktree(&dir, id, meta.clone()) else { continue };match present {Err(_) => forget_meta(&wt),- Ok(m) if m.is_dir() && !meta.finished => owned.push(Owned { wt, hold: Some(hold) }),+ Ok(m) if m.is_dir() && !meta.finished => {+ owned.push(Owned { wt, hold: Some(hold), mark: None })+ }Ok(_) => {}}}@@ -1251,9 +1679,652 @@ pub(crate) fn spawn_startup_sweep(}empty_trash(&root);sweep_and_report(&root, &mut report);+ let cap = crate::core::agent::project::subagent_build_cache_cap(&root);+ if let Some(notice) = trim_build_cache(&root, cap) {+ report(notice);+ }+ });+}++/// Delete `root`'s project's shared build directory when it is+/// larger than `cap` bytes (0 never), so it cannot grow without bound: the+/// next build starts cold. Never while any child of any process holds the+/// build lock (see [`hold_build_cache`]), readers without a checkout+/// included, nor while any live jan session (this one included) holds a+/// checkout of the project, since its next child may be building there.+/// The notice for the user when it was cleared. Walks the directory only up+/// to the cap, so a huge one costs little, and before taking the build lock,+/// so a dispatch never waits on the walk: the size only decides whether to+/// try, and the lock alone keeps a build from losing its directory mid-run.+/// A rename under the lock, then the moved cache is deleted on a thread of+/// its own: it holds nothing worth the trash's week, and the space is why+/// it was trimmed. Runs I/O: call it off the render loop.+#[cfg(feature = "cli")]+pub(crate) fn trim_build_cache(root: &Path, cap: u64) -> Option<String> {+ if cap == 0 {+ return None;+ }+ let dir = project_worktrees_dir(root)?;+ let target = dir.join(CARGO_TARGET);+ // A link there is not Jan's to move.+ if !std::fs::symlink_metadata(&target).is_ok_and(|m| m.is_dir()) || !larger_than(&target, cap)+ {+ return None;+ }+ let to = {+ let _building = lock_build_cache(&dir)?;+ // Checked again under the lock: a clear may have taken it meanwhile.+ if checkouts_in_use(&dir, &HashSet::new())+ || !std::fs::symlink_metadata(&target).is_ok_and(|m| m.is_dir())+ {+ return None;+ }+ move_to_trash(&target)?+ };+ // Should the thread not finish (the process exits first), the startup+ // sweep empties what is left after the trash's week.+ std::thread::spawn(move || {+ if let Err(e) = std::fs::remove_dir_all(&to) {+ log::warn!("agent: could not delete the trimmed build cache {}: {e}", to.display());+ }});+ Some(format!("subagent build cache over {}, cleared (next build starts cold)", size(cap)))+}++/// `cap` as the user set it: whole GB, else bytes (a test's tiny cap).+#[cfg(feature = "cli")]+fn size(cap: u64) -> String {+ match cap % (1 << 30) {+ 0 => format!("{} GB", cap >> 30),+ _ => format!("{cap} bytes"),+ }+}++/// Whether any checkout among `dir`'s, but those named in `ours` (the+/// caller's own, whose locks it holds), is owned by a live session: its lock+/// is held, or it was reserved without one (nothing can show its owner has+/// gone). Taking a free lock here only to test it is harmless: a sweep that+/// meets it meanwhile skips that checkout until the next start.+#[cfg(feature = "cli")]+fn checkouts_in_use(dir: &Path, ours: &HashSet<String>) -> bool {+ let Ok(entries) = std::fs::read_dir(dir.join(META_DIR)) else { return false };+ entries.filter_map(Result::ok).any(|entry| {+ let name = entry.file_name();+ let Some(id) = name.to_str().and_then(|n| n.strip_suffix(".lock")) else {+ return false;+ };+ // Only checkout locks: the build lock sits beside them.+ is_checkout_id(id) && !ours.contains(id) && matches!(probe_lock(dir, id), Probe::Held)+ })+}++/// Who owns a checkout's lock, as [`probe_lock`] found it.+#[cfg(feature = "cli")]+enum Probe {+ /// No live owner: this lock, now taken, keeps every other sweep off it.+ Free(std::fs::File),+ /// A live owner holds it, it was reserved without a lock (nothing can+ /// show its owner has gone), or it cannot be read: unknown is held.+ Held,+ /// Its owner settled it and unlinked the lock meanwhile.+ Gone,+}++/// Try the lock of checkout `id` in `dir` once, without waiting. A lock+/// taken on a file that is no longer the one at its path is held: its owner+/// unlinked it (it settled the worktree) between the open and the lock, and+/// a new owner of a reused id made a fresh one that no one else sees.+#[cfg(feature = "cli")]+fn probe_lock(dir: &Path, id: &str) -> Probe {+ if meta_file(dir, id, UNLOCKED_EXT).exists() {+ return Probe::Held;+ }+ let path = meta_file(dir, id, "lock");+ match crate::core::agent::session_log::open_no_follow(+ std::fs::OpenOptions::new().write(true),+ &path,+ ) {+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Probe::Gone,+ Err(_) => Probe::Held,+ Ok(file) => match lock(file) {+ Ok(hold) if still_at(&hold, &path) => Probe::Free(hold),+ _ => Probe::Held,+ },+ }+}++/// Whether the files under `dir` add up to more than `cap` bytes. Stops as+/// soon as they do, so a tree far over the cap is not walked whole, and never+/// follows a link (what it names is not in the directory). Unreadable+/// entries count as empty: the cost is a trim that waits for the next end.+#[cfg(feature = "cli")]+fn larger_than(dir: &Path, cap: u64) -> bool {+ dir_size(dir, cap) > cap+}++/// The bytes of the files under `dir`, walked without following a link, and+/// only until they pass `stop_above` (the total so far is returned then).+#[cfg(feature = "cli")]+fn dir_size(dir: &Path, stop_above: u64) -> u64 {+ sizes(dir, &[], stop_above).0+}++/// [`dir_size`], and of that the bytes under `within` (paths relative to+/// `dir`, as [`CheckoutState::Uncommitted`] names build output), counted in+/// the same walk: a checkout listed is walked for its size anyway, so its+/// build output costs nothing more to measure.+#[cfg(feature = "cli")]+fn sizes(dir: &Path, within: &[String], stop_above: u64) -> (u64, u64) {+ let marked: HashSet<PathBuf> =+ within.iter().map(|p| dir.join(p.trim_end_matches('/'))).collect();+ let (mut total, mut inside) = (0u64, 0u64);+ let mut pending = vec![(dir.to_path_buf(), false)];+ while let Some((next, in_marked)) = pending.pop() {+ let Ok(entries) = std::fs::read_dir(&next) else { continue };+ for entry in entries.filter_map(Result::ok) {+ let Ok(meta) = entry.metadata() else { continue };+ let path = entry.path();+ // Hashing every path of a large tree is skipped when nothing is+ // marked, as for every plain size.+ let in_marked = in_marked || (!marked.is_empty() && marked.contains(&path));+ if meta.is_dir() {+ pending.push((path, in_marked));+ } else if meta.is_file() {+ total = total.saturating_add(meta.len());+ if in_marked {+ inside = inside.saturating_add(meta.len());+ }+ if total > stop_above {+ return (total, inside);+ }+ }+ }+ }+ (total, inside)+}++/// `bytes` for a person: whole bytes, else one decimal of the largest unit.+#[cfg(feature = "cli")]+pub(crate) fn human_bytes(bytes: u64) -> String {+ const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];+ if bytes < 1024 {+ return format!("{bytes} B");+ }+ let mut value = bytes as f64 / 1024.0;+ let mut unit = 0;+ while value >= 1024.0 && unit < UNITS.len() - 1 {+ value /= 1024.0;+ unit += 1;+ }+ format!("{value:.1} {}", UNITS[unit])+}++/// The live session asking `/worktrees` what it may prune, so its own+/// checkouts do not read as another session's and its running subagents+/// keep their checkouts and the build cache. `None` for `jan cli worktrees`,+/// which owns nothing.+#[cfg(feature = "cli")]+pub(crate) struct Session<'a> {+ pub(crate) ledger: &'a Ledger,+ /// Whether any subagent of the session is running right now: a reader+ /// builds in the shared build cache too, without a checkout of its own.+ /// Asked at each decision, not once when the job was queued, since a+ /// subagent may have started meanwhile.+ pub(crate) children_running: &'a dyn Fn() -> bool,+}++#[cfg(feature = "cli")]+impl Session<'_> {+ /// The ids of the checkouts this session made and still holds the locks+ /// of, those its conversation end is settling included.+ fn own_ids(&self) -> HashSet<String> {+ let state = self.ledger.state.lock().unwrap();+ let created = state.created.iter().map(|wt| wt.path.as_path());+ created.chain(state.settling.keys().map(PathBuf::as_path)).filter_map(id_of_path).collect()+ }++ /// Who of the session holds `path`, if anyone: a writer, any running+ /// subagent (a reader reusing a checkout holds no lease, so a running+ /// one may be reading any of the session's), or its conversation end.+ fn in_use(&self, path: &Path) -> Option<InUseBy> {+ let state = self.ledger.state.lock().unwrap();+ if state.settling.contains_key(path) {+ Some(InUseBy::Settling)+ } else if state.busy.contains(path) {+ Some(InUseBy::Child)+ } else {+ drop(state);+ (self.children_running)().then_some(InUseBy::Child)+ }+ }+}++#[cfg(feature = "cli")]+fn id_of_path(path: &Path) -> Option<String> {+ path.file_name().map(|id| id.to_string_lossy().into_owned())+}++/// One subagent checkout of the project, as `/worktrees` lists it.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub(crate) struct CheckoutInfo {+ pub(crate) id: String,+ pub(crate) path: PathBuf,+ pub(crate) branch: String,+ pub(crate) bytes: u64,+ /// Of `bytes`, those of the ignored build output its state names.+ pub(crate) build_output_bytes: u64,+ #[serde(flatten)]+ pub(crate) state: CheckoutState,+}++#[cfg(feature = "cli")]+impl CheckoutInfo {+ /// [`CheckoutState::loses`], with the build output a forced removal+ /// deletes as well, for the confirm.+ pub(crate) fn loses(&self) -> Option<String> {+ let loses = self.state.loses()?;+ Some(format!("{loses}{}", plus_build_output(self.build_output_bytes)))+ }++ /// The row `jan cli worktrees list` prints.+ pub(crate) fn line(&self) -> String {+ format!("{} {} {}", self.branch, human_bytes(self.bytes), self.state.describe())+ }+}++/// What the project's subagents left on disk under its worktrees directory.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]+pub(crate) struct WorktreesReport {+ /// `~/.jan/worktrees/<slug>`, `None` without a Jan home.+ pub(crate) dir: Option<PathBuf>,+ pub(crate) checkouts: Vec<CheckoutInfo>,+ /// The shared build cache's size, `None` when there is none.+ pub(crate) build_cache_bytes: Option<u64>,+ /// What already-removed checkouts and caches hold until the trash is+ /// emptied at a later start.+ pub(crate) trash_bytes: u64,+}++#[cfg(feature = "cli")]+impl WorktreesReport {+ /// The checkouts a safe prune would remove now, and their total size.+ pub(crate) fn removable(&self) -> (usize, u64) {+ let ones = self.checkouts.iter().filter(|c| matches!(c.state, CheckoutState::Removable { .. }));+ ones.fold((0, 0), |(n, bytes), c| (n + 1, bytes + c.bytes))+ }++ /// The report as `jan cli worktrees list` prints it.+ pub(crate) fn lines(&self) -> Vec<String> {+ let mut lines: Vec<String> = match &self.dir {+ Some(dir) => vec![format!("subagent worktrees in {}", display(dir))],+ None => return vec!["no Jan home: there are no subagent worktrees".to_string()],+ };+ if self.checkouts.is_empty() {+ lines.push(" no subagent checkouts".to_string());+ }+ lines.extend(self.checkouts.iter().map(|c| format!(" {}", c.line())));+ lines.push(match self.build_cache_bytes {+ Some(bytes) => format!("build cache {}", human_bytes(bytes)),+ None => "build cache none".to_string(),+ });+ if self.trash_bytes > 0 {+ let days = tauri_plugin_agent_tools::workspace::TRASH_KEPT_FOR.as_secs() / 86_400;+ lines.push(format!(+ "trash {} (deleted after {days} days)",+ human_bytes(self.trash_bytes)+ ));+ }+ lines+ }+}++/// How a found checkout is held while it is looked at or pruned.+#[cfg(feature = "cli")]+enum Hold {+ /// The asking session made it and holds its lock.+ Ours,+ /// No live session owns it: this lock keeps every sweep off it meanwhile.+ Locked(std::fs::File),+ /// Another live session owns it.+ Theirs,+}++#[cfg(feature = "cli")]+struct Found {+ id: String,+ wt: ChildWorktree,+ hold: Hold,+}++#[cfg(feature = "cli")]+impl Found {+ /// Where it stands, without changing anything.+ fn state(&self, session: Option<&Session>) -> CheckoutState {+ let ours = match (&self.hold, session) {+ (Hold::Ours, Some(session)) => session.in_use(&self.wt.path),+ _ => None,+ };+ match (&self.hold, ours) {+ (Hold::Theirs, _) => CheckoutState::InUse { by: InUseBy::Session },+ (_, Some(by)) => CheckoutState::InUse { by },+ _ => classify(&self.wt),+ }+ }+}++/// The project's canonical worktrees directory, as records name it.+#[cfg(feature = "cli")]+fn worktrees_dir(root: &Path) -> Option<PathBuf> {+ project_worktrees_dir(root).and_then(|d| dunce::canonicalize(d).ok())+}++/// Every recorded checkout in `dir`, in id order, each held as [`Hold`]+/// says. One without a record that describes it is not Jan's to judge, so is+/// left out, as the startup sweep leaves it.+#[cfg(feature = "cli")]+fn found_checkouts(dir: &Path, session: Option<&Session>) -> Vec<Found> {+ let ours = session.map(Session::own_ids).unwrap_or_default();+ let Ok(entries) = std::fs::read_dir(dir.join(META_DIR)) else { return Vec::new() };+ let mut found = Vec::new();+ for entry in entries.filter_map(Result::ok) {+ let name = entry.file_name();+ let Some(id) = name.to_str().and_then(|n| n.strip_suffix(".lock")) else { continue };+ if !is_checkout_id(id) || !std::fs::symlink_metadata(dir.join(id)).is_ok_and(|m| m.is_dir())+ {+ continue;+ }+ let Some(wt) = std::fs::read(meta_file(dir, id, "json"))+ .ok()+ .and_then(|bytes| serde_json::from_slice::<WorktreeMeta>(&bytes).ok())+ .and_then(|meta| recorded_worktree(dir, id, meta))+ else {+ continue;+ };+ let hold = if ours.contains(id) {+ Hold::Ours+ } else {+ match probe_lock(dir, id) {+ Probe::Free(hold) => Hold::Locked(hold),+ Probe::Held => Hold::Theirs,+ Probe::Gone => continue,+ }+ };+ found.push(Found { id: id.to_string(), wt, hold });+ }+ found.sort_by(|a, b| a.id.cmp(&b.id));+ found+}++/// List `root`'s project's subagent checkouts, its shared build cache and+/// its trash, with their sizes and where each checkout stands. Runs git and+/// walks every checkout: call it off the render loop.+#[cfg(feature = "cli")]+pub(crate) fn list_worktrees(root: &Path, session: Option<&Session>) -> WorktreesReport {+ let Some(dir) = worktrees_dir(root) else {+ return WorktreesReport { dir: project_worktrees_dir(root), ..WorktreesReport::default() };+ };+ let checkouts = found_checkouts(&dir, session)+ .iter()+ .map(|found| {+ let state = found.state(session);+ let built = match &state {+ CheckoutState::Uncommitted { build_output, .. } => build_output.as_slice(),+ _ => &[],+ };+ // One walk for the size shown and the build output the confirm+ // names: no file is read twice.+ let (bytes, build_output_bytes) = sizes(&found.wt.path, built, u64::MAX);+ CheckoutInfo {+ id: found.id.clone(),+ path: found.wt.path.clone(),+ branch: found.wt.branch.clone(),+ bytes,+ build_output_bytes,+ state,+ }+ })+ .collect();+ let target = dir.join(CARGO_TARGET);+ let build_cache_bytes = std::fs::symlink_metadata(&target)+ .is_ok_and(|m| m.is_dir())+ .then(|| dir_size(&target, u64::MAX));+ WorktreesReport {+ trash_bytes: dir_size(&dir.join(TRASH_DIR), u64::MAX),+ dir: Some(dir),+ checkouts,+ build_cache_bytes,+ }+}++/// Which checkouts a prune removes.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum Prune {+ /// Every checkout session end would remove (see [`dispose`]).+ Safe,+ /// Every checkout that is not in use, its uncommitted work and unbrought+ /// commits included: the user confirmed the loss.+ All,+ /// The checkout with this id, by the safe rule, or (`force`) whatever it+ /// holds once the user confirmed the loss.+ One { id: String, force: bool },+}++/// What a prune did, for the notice that tells the user.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct Pruned {+ /// The branches of the checkouts removed.+ pub(crate) removed: Vec<String>,+ /// Of those, the branches whose commits were brought into the user's+ /// repository first: where that work is now.+ pub(crate) brought: Vec<String>,+ /// A line per checkout kept, saying why.+ pub(crate) kept: Vec<String>,+ /// The bytes deleted: a forced removal's, once its delete succeeded.+ pub(crate) freed: u64,+ /// The bytes moved to the trash (a safe removal's, or a forced one whose+ /// delete failed), which a later start empties, and where it is.+ pub(crate) trashed: u64,+ pub(crate) trash: Option<PathBuf>,+ /// Of the bytes removed, those of ignored build output a forced removal+ /// of uncommitted work took with it, named as the confirm named it.+ pub(crate) build_output: u64,+}++#[cfg(feature = "cli")]+impl Pruned {+ /// The notice for the user: what went, the space it freed or where it+ /// waits, what stayed.+ pub(crate) fn notice(&self) -> String {+ let mut text = match self.removed.len() {+ 0 => "no subagent worktree removed".to_string(),+ n => format!("removed {n} subagent worktree(s)"),+ };+ text.push_str(&plus_build_output(self.build_output));+ if self.freed > 0 {+ text.push_str(&format!(", freed {}", human_bytes(self.freed)));+ }+ if let Some(bin) = self.trash.as_ref().filter(|_| self.trashed > 0) {+ let days = tauri_plugin_agent_tools::workspace::TRASH_KEPT_FOR.as_secs() / 86_400;+ text.push_str(&format!(+ "; moved {} to {}, deleted after {days} days",+ human_bytes(self.trashed),+ display(bin)+ ));+ }+ if !self.brought.is_empty() {+ text.push_str(&format!("\nbrought back first: {}", self.brought.join(", ")));+ }+ for line in &self.kept {+ text.push_str(&format!("\nkept {line}"));+ }+ text+ }+}++/// Remove `root`'s project's subagent checkouts that `which` names, never+/// one a running subagent of `session` or another live session holds, nor+/// one git cannot read. What the safe rule removes goes to the trash, as at+/// session end: the check may miss work. What a forced prune removes is+/// deleted at once: the user confirmed the loss and asked for the space.+/// Runs git and deletes: call it off the render loop.+#[cfg(feature = "cli")]+pub(crate) fn prune_worktrees(root: &Path, session: Option<&Session>, which: &Prune) -> Pruned {+ let mut pruned = Pruned::default();+ let Some(dir) = worktrees_dir(root) else { return pruned };+ for found in found_checkouts(&dir, session) {+ let force = match which {+ Prune::Safe => false,+ Prune::All => true,+ Prune::One { id, force } if *id == found.id => *force,+ Prune::One { .. } => continue,+ };+ prune_one(found, session, force, &mut pruned);+ }+ pruned+}++/// [`prune_worktrees`] for one checkout.+#[cfg(feature = "cli")]+fn prune_one(found: Found, session: Option<&Session>, force: bool, pruned: &mut Pruned) {+ let Found { wt, hold, .. } = found;+ let kept = |state: CheckoutState| format!("{} ({})", wt.branch, state.describe());+ let ledger = match (&hold, session) {+ (Hold::Theirs, _) => {+ return pruned.kept.push(kept(CheckoutState::InUse { by: InUseBy::Session }));+ }+ // Claimed, as a session end claims it, so no dispatch is handed it+ // while it goes; a writer in it refuses the claim.+ (Hold::Ours, Some(session)) => {+ let by = session.in_use(&wt.path);+ let claimed = || session.ledger.claim(&wt.path);+ if let Some(by) = by.or_else(|| (!claimed()).then_some(InUseBy::Child)) {+ return pruned.kept.push(kept(CheckoutState::InUse { by }));+ }+ Some(session.ledger)+ }+ _ => None,+ };+ // Sized only once it is known to go, and in the walk that also finds+ // its build output: a kept checkout is not walked at all.+ let (mut bytes, mut build_output) = (0, 0);+ let (gone, brought) = match dispose(&wt, true) {+ Disposition::Removed { gone, brought } => {+ // Moved, not deleted: what is in the trash is what went.+ if let Gone::Trashed(to) = &gone {+ bytes = dir_size(to, u64::MAX);+ }+ (Some(gone), brought)+ }+ Disposition::Kept { not_brought } => match classify(&wt) {+ // The confirm promised an uncommitted checkout's branch is+ // brought back first: when it could not be, its commits would be+ // lost too, which the user did not confirm. When it was, the+ // notice names it, as the confirm did.+ CheckoutState::Uncommitted { commits, off_branch, build_output: built, .. }+ if force && not_brought.is_none() =>+ {+ (bytes, build_output) = sizes(&wt.path, &built, u64::MAX);+ (trash(&wt.path), (commits > off_branch).then(|| wt.branch.clone()))+ }+ CheckoutState::Unbrought { .. } | CheckoutState::Removable { .. } if force => {+ bytes = dir_size(&wt.path, u64::MAX);+ (trash(&wt.path), None)+ }+ // Everything in it is in the user's repository, so only the move+ // into the trash can have failed.+ CheckoutState::Removable { .. } => {+ pruned.kept.push(format!("{} (could not be moved to the trash)", wt.branch));+ (None, None)+ }+ state => {+ let why = not_brought+ .map(|why| format!("; its branch could not be brought back: {why}"))+ .unwrap_or_default();+ pruned.kept.push(format!("{} ({}{why})", wt.branch, state.describe()));+ (None, None)+ }+ },+ };+ if gone.is_some() {+ forget_meta(&wt);+ }+ if let Some(ledger) = ledger {+ ledger.release(&wt.path, gone.is_some());+ }+ // Only now may a sweep take it: the decision and the removal are done.+ if let Hold::Locked(lock) = hold {+ drop(lock);+ }+ let Some(gone) = gone else { return };+ // The user confirmed the loss and asked for the space: delete it now.+ // Once its record is gone the trash entry is nobody's, so a failed+ // delete is left for the startup sweep to empty, and counted there.+ let left = match gone {+ Gone::Trashed(to) if force && std::fs::remove_dir_all(&to).is_err() => Some(to),+ Gone::Trashed(to) if !force => Some(to),+ _ => None,+ };+ match left.as_deref().and_then(Path::parent) {+ Some(bin) => {+ pruned.trashed += bytes;+ pruned.trash = Some(bin.to_path_buf());+ }+ None => pruned.freed += bytes,+ }+ pruned.removed.push(wt.branch.clone());+ pruned.brought.extend(brought);+ pruned.build_output += build_output;+}++/// Delete `root`'s project's shared build cache now, returning the bytes+/// freed. Refused while a build may be running in it: a running subagent of+/// `session`, any child of any process holding the build lock, or any other+/// live session that holds a checkout of the project (the same checks as+/// [`trim_build_cache`]). Call it off the render loop.+#[cfg(feature = "cli")]+pub(crate) fn clear_build_cache(root: &Path, session: Option<&Session>) -> Result<u64, String> {+ let dir = worktrees_dir(root).ok_or("there is no subagent build cache")?;+ let target = dir.join(CARGO_TARGET);+ if !std::fs::symlink_metadata(&target).is_ok_and(|m| m.is_dir()) {+ return Err("there is no subagent build cache".to_string());+ }+ let ours = match session {+ // A reader builds there too, without a lease, so any running+ // subagent counts.+ Some(s) if (s.children_running)() || !s.ledger.state.lock().unwrap().busy.is_empty() => {+ return Err(BUILDING.to_string());+ }+ Some(s) => s.own_ids(),+ None => HashSet::new(),+ };+ let to = {+ let Some(_building) = lock_build_cache(&dir) else {+ return Err(BUILDING.to_string());+ };+ if checkouts_in_use(&dir, &ours) {+ return Err("another live jan session has a subagent checkout of this project \+ and may be building there"+ .to_string());+ }+ move_to_trash(&target).ok_or("could not move the build cache out of the way")?+ };+ // Measured once moved and the lock let go, so no dispatch waits on the+ // walk; nothing builds in the trash, so the size is exact.+ let bytes = dir_size(&to, u64::MAX);+ // Deleted now, not after the trash's week: the user asked for the space.+ let _ = std::fs::remove_dir_all(to);+ Ok(bytes)}+/// Why the build cache was not cleared while a subagent may build in it.+#[cfg(feature = "cli")]+const BUILDING: &str =+ "a subagent is running and may be building there; try again once it has finished";+/// Settle `root`'s orphaned worktrees and report them (see/// [`Settled::report`]).#[cfg(feature = "cli")]@@ -1316,8 +2387,7 @@ fn kept_line(wt: &ChildWorktree, not_brought: Option<&str>) -> String {delete the directory"),Ok(checkout) => {- let mut held = match (checkout.commits_anywhere(&wt.base), checkout.try_changed_paths())- {+ let mut held = match (checkout.commits_anywhere(&wt.base), checkout.uncommitted()) {(Some(commits), Ok(changed)) => {format!("{commits} commit(s), {} uncommitted file(s)", changed.len())}@@ -1378,7 +2448,7 @@ mod tests {let root = std::env::temp_dir().join(format!("jan_child_ws_desk_{}", std::process::id()));std::fs::create_dir_all(&root).unwrap();let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "explore", false, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "explore", false, None, true).unwrap();assert!(lease.is_none());assert!(!ws.read_only, "{ws:?}");assert_eq!(scope_for(&ws, &root), ChildScope::default());@@ -1455,7 +2525,7 @@ mod git_tests {fn a_writer_gets_its_own_worktree_and_a_reader_the_checkout_read_only() {let Some(root) = repo("default") else { return };let ledger = Arc::new(Ledger::default());- let (writer, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (writer, lease) = ledger.assign(&root, "general", true, None, true).unwrap();let wt = writer.worktree.clone().expect("a writer gets a worktree");assert!(lease.is_some());assert!(!writer.read_only);@@ -1470,7 +2540,7 @@ mod git_tests {assert!(note.contains(&wt.branch) && note.contains("worktree"), "{note}");assert_eq!(writer.answer_footer(None).map(|f| f.contains(&wt.branch)), Some(true));- let (reader, lease) = ledger.assign(&root, "explore", false, None).unwrap();+ let (reader, lease) = ledger.assign(&root, "explore", false, None, true).unwrap();assert!(lease.is_none());assert_eq!(reader, ChildWorkspace::shared(&root, true));assert!(reader.note().starts_with("working read-only in "), "{}", reader.note());@@ -1478,29 +2548,63 @@ mod git_tests {let _ = std::fs::remove_dir_all(&root);}+ /// With worktrees off, a writer that asks for nothing works in the+ /// parent's checkout: no clone, no lease, no branch.+ #[test]+ fn a_writer_with_no_request_shares_the_checkout_when_worktrees_are_off() {+ let Some(root) = repo("shared_default") else { return };+ let ledger = Arc::new(Ledger::default());+ let (w, lease) = ledger.assign(&root, "general", true, None, false).unwrap();+ assert_eq!(w, ChildWorkspace::shared(&root, false));+ assert!(lease.is_none());+ assert!(ledger.live().is_empty(), "{:?}", ledger.live());+ assert!(w.note().starts_with("working in your checkout"), "{}", w.note());+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Asking for a worktree is honored with the setting off: only the default+ /// changes, so `"new"` and a ref still get one and the writer is leased.+ #[test]+ fn an_explicit_new_or_ref_still_gets_a_worktree_when_worktrees_are_off() {+ let Some(root) = repo("explicit_off") else { return };+ let ledger = Arc::new(Ledger::default());+ let new = WorkspaceRequest::New;+ let (w, lease) = ledger.assign(&root, "general", true, Some(&new), false).unwrap();+ assert!(w.worktree.is_some() && lease.is_some(), "{w:?}");+ let at = WorkspaceRequest::Ref("HEAD".to_string());+ let (r, _) = ledger.assign(&root, "review", false, Some(&at), false).unwrap();+ assert!(r.worktree.is_some() && r.read_only, "{r:?}");+ let shared = WorkspaceRequest::Shared;+ let (s, _) = ledger.assign(&root, "general-2", true, Some(&shared), false).unwrap();+ assert_eq!(s, ChildWorkspace::shared(&root, false));+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn two_concurrent_writers_never_share_and_reuse_of_a_busy_worktree_is_refused() {let Some(root) = repo("lease") else { return };let ledger = Arc::new(Ledger::default());- let (a, lease_a) = ledger.assign(&root, "general", true, None).unwrap();- let (b, _lease_b) = ledger.assign(&root, "general-2", true, None).unwrap();+ let (a, lease_a) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (b, _lease_b) = ledger.assign(&root, "general-2", true, None, true).unwrap();assert_ne!(a.root, b.root, "two writers, two checkouts");let reuse = WorkspaceRequest::Reuse("general".to_string());- let err = ledger.assign(&root, "general-3", true, Some(&reuse)).unwrap_err();+ let err = ledger.assign(&root, "general-3", true, Some(&reuse), true).unwrap_err();assert!(err.contains("still writing") && err.contains("not started"), "{err}");// A reader may look at it meanwhile, read-only.- let (look, _) = ledger.assign(&root, "review", false, Some(&reuse)).unwrap();+ let (look, _) = ledger.assign(&root, "review", false, Some(&reuse), true).unwrap();assert_eq!(look.root, a.root);assert!(look.read_only);drop(lease_a);- let (again, lease) = ledger.assign(&root, "general-3", true, Some(&reuse)).unwrap();+ let (again, lease) = ledger.assign(&root, "general-3", true, Some(&reuse), true).unwrap();assert_eq!(again.root, a.root, "sequential reuse gets the same checkout");assert!(!again.read_only && lease.is_some());drop(lease);assert!(ledger- .assign(&root, "x", true, Some(&WorkspaceRequest::Reuse("nobody".into())))+ .assign(&root, "x", true, Some(&WorkspaceRequest::Reuse("nobody".into())), true).unwrap_err().contains("no earlier subagent"));let _ = ledger.finish_session();@@ -1526,7 +2630,7 @@ mod git_tests {let ledger = Arc::new(Ledger::default());let req = WorkspaceRequest::Ref("feature".to_string());- let (ws, lease) = ledger.assign(&clone, "review", false, Some(&req)).unwrap();+ let (ws, lease) = ledger.assign(&clone, "review", false, Some(&req), true).unwrap();let wt = ws.worktree.clone().expect("a ref gets a worktree");assert!(ws.read_only && lease.is_none(), "a reader there is still read-only");assert_eq!(wt.base, feature);@@ -1540,25 +2644,26 @@ mod git_tests {}/// A writer working in a `ref` worktree commits on its `jan/agent/...`- /// branch; session end must not delete that branch and lose the commits,- /// nor drop uncommitted edits made there.+ /// branch; session end must not lose those commits (they are brought+ /// back before the checkout goes), nor drop uncommitted edits made there.#[test]fn a_ref_worktree_that_holds_work_is_kept_at_session_end() {let Some(root) = repo("refwork") else { return };assert!(git(&root, &["branch", "feature"]));let ledger = Arc::new(Ledger::default());let req = WorkspaceRequest::Ref("feature".to_string());- let (committed, l1) = ledger.assign(&root, "general", true, Some(&req)).unwrap();- let (dirty, l2) = ledger.assign(&root, "general-2", true, Some(&req)).unwrap();- let (idle, l3) = ledger.assign(&root, "general-3", true, Some(&req)).unwrap();+ let (committed, l1) = ledger.assign(&root, "general", true, Some(&req), true).unwrap();+ let (dirty, l2) = ledger.assign(&root, "general-2", true, Some(&req), true).unwrap();+ let (idle, l3) = ledger.assign(&root, "general-3", true, Some(&req), true).unwrap();drop((l1, l2, l3));commit(&committed.root, "b.txt");let tip = crate::core::agent::git::head_sha(&committed.root).unwrap();std::fs::write(dirty.root.join("a.txt"), "edited\n").unwrap();let kept = ledger.finish_session().kept;- assert_eq!(kept.len(), 2, "{kept:?}");- assert!(committed.root.is_dir() && dirty.root.is_dir());+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(!committed.root.exists(), "its commits are in the user's repo");+ assert!(dirty.root.is_dir());assert!(!idle.root.exists(), "an untouched ref worktree still goes");let branch = &committed.worktree.as_ref().unwrap().branch;assert_eq!(@@ -1577,7 +2682,7 @@ mod git_tests {fn a_worktree_whose_status_cannot_be_read_is_kept() {let Some(root) = repo("badstatus") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();let out = Command::new("git")@@ -1598,27 +2703,30 @@ mod git_tests {let _ = std::fs::remove_dir_all(&root);}+ /// Only a checkout whose work is all in the user's repository goes: one+ /// with no commits, or one whose commits were brought back.#[test]- fn session_end_removes_only_clean_commitless_worktrees() {+ fn session_end_removes_only_clean_worktrees_whose_work_is_in_the_repo() {let Some(root) = repo("cleanup") else { return };let ledger = Arc::new(Ledger::default());- let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (committed, l2) = ledger.assign(&root, "general-2", true, None).unwrap();- let (dirty, l3) = ledger.assign(&root, "general-3", true, None).unwrap();+ let (idle, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (committed, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();+ let (dirty, l3) = ledger.assign(&root, "general-3", true, None, true).unwrap();drop((l1, l2, l3));commit(&committed.root, "b.txt");std::fs::write(dirty.root.join("a.txt"), "edited\n").unwrap();let kept = ledger.finish_session().kept;- assert_eq!(kept.len(), 2, "{kept:?}");- assert!(!idle.root.exists());+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(!idle.root.exists() && !committed.root.exists());let idle_branch = &idle.worktree.as_ref().unwrap().branch;assert_eq!(crate::core::agent::git::resolve_commit(&root, idle_branch), None);- assert!(committed.root.is_dir() && dirty.root.is_dir());- assert!(kept.iter().any(|k| k.contains("1 commit(s)")), "{kept:?}");+ let branch = &committed.worktree.as_ref().unwrap().branch;+ assert!(crate::core::agent::git::resolve_commit(&root, branch).is_some());+ assert!(dirty.root.is_dir());+ assert!(kept[0].contains("1 uncommitted file(s)"), "{kept:?}");// Named once and handed to the user: the ledger holds none of them.assert!(ledger.live().is_empty(), "{:?}", ledger.live());- let _ = std::fs::remove_dir_all(&committed.root);let _ = std::fs::remove_dir_all(&dirty.root);let _ = std::fs::remove_dir_all(&root);}@@ -1632,7 +2740,7 @@ mod git_tests {fn an_untracked_only_worktree_is_kept_when_status_hides_untracked_files() {let Some(root) = repo("untracked") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);std::fs::create_dir_all(ws.root.join("out")).unwrap();std::fs::write(ws.root.join("out/report.md"), "deliverable\n").unwrap();@@ -1647,24 +2755,23 @@ mod git_tests {}/// A writer that committed on its branch and then moved HEAD away (back to- /// the base, detached) still holds that work on the branch: the sweep- /// must not force-delete it.+ /// the base, detached) still holds that work on the branch: it is brought+ /// back before the checkout goes, never lost with it.#[test]- fn a_branch_holding_commits_is_kept_even_when_head_moved_away() {+ fn a_branch_holding_commits_is_brought_back_even_when_head_moved_away() {let Some(root) = repo("head-moved") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let wt = ws.worktree.as_ref().unwrap();commit(&ws.root, "b.txt");assert!(git(&ws.root, &["switch", "-q", "--detach", &wt.base]));+ let tip = crate::core::agent::git::resolve_commit(&ws.root, &wt.branch);let kept = ledger.finish_session().kept;- assert_eq!(kept.len(), 1, "{kept:?}");- assert!(kept[0].contains("1 commit(s)"), "{kept:?}");- assert!(ws.root.is_dir());- assert!(crate::core::agent::git::resolve_commit(&root, &wt.branch).is_some());- let _ = std::fs::remove_dir_all(&ws.root);+ assert!(kept.is_empty(), "{kept:?}");+ assert!(!ws.root.exists());+ assert_eq!(crate::core::agent::git::resolve_commit(&root, &wt.branch), tip);let _ = std::fs::remove_dir_all(&root);}@@ -1677,11 +2784,11 @@ mod git_tests {let Some(root) = repo("undo") else { return };let ledger = Arc::new(Ledger::default());let new = WorkspaceRequest::New;- let (reader, _) = ledger.assign(&root, "explore", false, Some(&new)).unwrap();- let (writer, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (reader, _) = ledger.assign(&root, "explore", false, Some(&new), true).unwrap();+ let (writer, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);- let (late, lease) = ledger.assign(&root, "late", true, None).unwrap();+ let (late, lease) = ledger.assign(&root, "late", true, None, true).unwrap();drop(lease);ledger.undo("late", &late);let late_wt = late.worktree.as_ref().unwrap();@@ -1692,18 +2799,18 @@ mod git_tests {// An undone reuse hands nothing back: the worktree was not its own.let reuse = WorkspaceRequest::Reuse("general".to_string());- let (borrowed, lease) = ledger.assign(&root, "late-2", true, Some(&reuse)).unwrap();+ let (borrowed, lease) = ledger.assign(&root, "late-2", true, Some(&reuse), true).unwrap();drop(lease);ledger.undo("late-2", &borrowed);assert!(writer.root.is_dir(), "an earlier child's worktree survives");for earlier in ["explore", "general"] {let reuse = WorkspaceRequest::Reuse(earlier.to_string());- assert!(ledger.assign(&root, "next", false, Some(&reuse)).is_ok(), "{earlier}");+ assert!(ledger.assign(&root, "next", false, Some(&reuse), true).is_ok(), "{earlier}");}for gone in ["late", "late-2"] {let reuse = WorkspaceRequest::Reuse(gone.to_string());- assert!(ledger.assign(&root, "next", false, Some(&reuse)).is_err(), "{gone}");+ assert!(ledger.assign(&root, "next", false, Some(&reuse), true).is_err(), "{gone}");}let _ = ledger.finish_session();let _ = std::fs::remove_dir_all(&root);@@ -1747,8 +2854,8 @@ mod git_tests {use std::time::{Duration, Instant};let Some(root) = repo("slow") else { return };let ledger = Arc::new(Ledger::default());- let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (busy, l2) = ledger.assign(&root, "general-2", true, None).unwrap();+ let (idle, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (busy, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();drop(l1);commit(&busy.root, "b.txt");if !slow_status(&idle.root) {@@ -1776,18 +2883,18 @@ mod git_tests {fn a_worktree_being_removed_is_not_reused() {let Some(root) = repo("removing") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let path = ws.worktree.as_ref().unwrap().path.clone();assert!(ledger.claim(&path));assert!(!ledger.claim(&path), "one removal at a time");let reuse = WorkspaceRequest::Reuse("general".to_string());for writer in [true, false] {- let err = ledger.assign(&root, "next", writer, Some(&reuse)).unwrap_err();+ let err = ledger.assign(&root, "next", writer, Some(&reuse), true).unwrap_err();assert!(err.contains("being removed"), "{err}");}ledger.state.lock().unwrap().removing.remove(&path);- let (again, lease) = ledger.assign(&root, "next", true, Some(&reuse)).unwrap();+ let (again, lease) = ledger.assign(&root, "next", true, Some(&reuse), true).unwrap();assert_eq!(again.root, ws.root);assert!(!ledger.claim(&path), "a busy worktree is never claimed");drop(lease);@@ -1802,7 +2909,7 @@ mod git_tests {fn a_reuse_of_a_worktree_swept_meanwhile_is_refused() {let Some(root) = repo("swept") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let wt = ws.worktree.clone().unwrap();// The sweep's effect, landing between the lookup and the record.@@ -1811,7 +2918,7 @@ mod git_tests {let reuse = WorkspaceRequest::Reuse("general".to_string());for writer in [true, false] {- let err = ledger.assign(&root, "next", writer, Some(&reuse)).unwrap_err();+ let err = ledger.assign(&root, "next", writer, Some(&reuse), true).unwrap_err();assert!(err.contains("was removed"), "{err}");}assert!(ledger.live().is_empty(), "{:?}", ledger.live());@@ -1831,7 +2938,7 @@ mod git_tests {std::fs::write(root.join("scratch/u.txt"), "u\n").unwrap();let ledger = Arc::new(Ledger::default());- let (here, _l) = ledger.assign(&root.join("tracked"), "a", true, None).unwrap();+ let (here, _l) = ledger.assign(&root.join("tracked"), "a", true, None, true).unwrap();let wt = here.worktree.clone().unwrap();assert_eq!(here.root, wt.path.join("tracked"), "a tracked subdirectory maps across");// Filed under the repository's slug, the one its alternates name, or@@ -1840,13 +2947,13 @@ mod git_tests {assert_eq!(project_worktrees_dir(&root.join("tracked")), project_worktrees_dir(&root));assert!(!here.note().contains("not in this checkout"), "{}", here.note());- let (untracked, _l) = ledger.assign(&root.join("scratch"), "b", true, None).unwrap();+ let (untracked, _l) = ledger.assign(&root.join("scratch"), "b", true, None, true).unwrap();let wt = untracked.worktree.clone().unwrap();assert_eq!(untracked.root, wt.path);assert!(untracked.note().contains("scratch is not in this checkout"), "{}", untracked.note());let old = WorkspaceRequest::Ref("old".to_string());- let (at_ref, _) = ledger.assign(&root.join("tracked"), "c", false, Some(&old)).unwrap();+ let (at_ref, _) = ledger.assign(&root.join("tracked"), "c", false, Some(&old), true).unwrap();let wt = at_ref.worktree.clone().unwrap();assert_eq!(at_ref.root, wt.path);assert!(at_ref.note().contains("tracked is not in this checkout"), "{}", at_ref.note());@@ -1863,10 +2970,10 @@ mod git_tests {return;}let ledger = Arc::new(Ledger::default());- let (w, lease) = ledger.assign(&dir, "general", true, None).unwrap();+ let (w, lease) = ledger.assign(&dir, "general", true, None, true).unwrap();assert!(w.worktree.is_none() && !w.read_only && lease.is_none());assert!(w.note().contains("not a git repository"), "{}", w.note());- let (r, _) = ledger.assign(&dir, "explore", false, Some(&WorkspaceRequest::New)).unwrap();+ let (r, _) = ledger.assign(&dir, "explore", false, Some(&WorkspaceRequest::New), true).unwrap();assert!(r.read_only);let _ = std::fs::remove_dir_all(&dir);}@@ -1878,7 +2985,7 @@ mod git_tests {fn a_writer_childs_args_point_at_its_worktree() {let Some(root) = repo("apply") else { return };let ledger = Arc::new(Ledger::default());- let (ws, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, _lease) = ledger.assign(&root, "general", true, None, true).unwrap();let wt = ws.worktree.clone().unwrap();let mut args = crate::core::agent::subagent::tests::max_par_args(&root);args.session_start = Some(crate::core::agent::context::SessionStart::capture(Some(&root)));@@ -1902,7 +3009,7 @@ mod git_tests {assert!(prompt.contains(&format!("Work directory: `{shown}`")), "{prompt}");assert!(prompt.contains(&format!("Current project directory: `{}`", wt.path.display())));- let (reader, _) = ledger.assign(&root, "explore", false, None).unwrap();+ let (reader, _) = ledger.assign(&root, "explore", false, None, true).unwrap();let mut args = crate::core::agent::subagent::tests::max_par_args(&root);let parent_start = args.session_start.clone();apply(&mut args, &reader, place(&reader, &root));@@ -1922,7 +3029,7 @@ mod git_tests {fn a_checkout_whose_git_dir_was_swapped_for_a_pointer_is_never_followed() {let Some(root) = repo("redirect") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let wt = ws.worktree.clone().unwrap();let marker = root.with_extension("pwned");@@ -1974,7 +3081,7 @@ mod git_tests {let Some(root) = repo("verbatim") else { return };let verbatim = std::fs::canonicalize(&root).unwrap();let ledger = Arc::new(Ledger::default());- let (ws, _lease) = ledger.assign(&verbatim, "general", true, None).unwrap();+ let (ws, _lease) = ledger.assign(&verbatim, "general", true, None, true).unwrap();let wt = ws.worktree.clone().expect("a writer gets a worktree");assert!(!wt.path.to_string_lossy().starts_with(r"\\?\"), "{wt:?}");assert!(wt.path.join(".git").is_dir(), "{wt:?}");@@ -1988,7 +3095,7 @@ mod git_tests {fn a_writer_is_granted_the_build_dir_and_read_access_to_the_borrowed_objects_only() {let Some(root) = repo("scope") else { return };let ledger = Arc::new(Ledger::default());- let (w, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (w, _lease) = ledger.assign(&root, "general", true, None, true).unwrap();let scope = scope_for(&w, &root);assert!(!scope.read_only);// Its commits go to the repository it is, inside its workspace: none@@ -1998,7 +3105,7 @@ mod git_tests {assert_eq!(scope.read_roots, vec![root.join(".git/objects")], "{scope:?}");assert!(scope.env_set.iter().any(|(k, v)| k == "CARGO_TARGET_DIR" && Path::new(v) == target));- let (r, _) = ledger.assign(&root, "explore", false, None).unwrap();+ let (r, _) = ledger.assign(&root, "explore", false, None, true).unwrap();let scope = scope_for(&r, &root);assert!(scope.read_only);assert_eq!(scope.write_roots, vec![target], "a reader never gets the git dir");@@ -2089,7 +3196,7 @@ mod git_tests {let Some(root) = repo("anyop") else { return };assert!(git(&root, &["tag", "v1"]));let ledger = Arc::new(Ledger::default());- let (ws, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, _lease) = ledger.assign(&root, "general", true, None, true).unwrap();let id = "-c user.name=t -c user.email=t@t -c commit.gpgSign=false -c tag.gpgSign=false";let steps = [format!("echo b > b.txt && git add b.txt && git {id} commit -q -m b"),@@ -2121,7 +3228,7 @@ mod git_tests {fn a_sandboxed_writer_cannot_write_the_users_git_dir() {let Some(root) = repo("nouser") else { return };let ledger = Arc::new(Ledger::default());- let (ws, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, _lease) = ledger.assign(&root, "general", true, None, true).unwrap();let dot = root.join(".git");let outside = root.with_extension("outside");let _ = std::fs::remove_dir_all(&outside);@@ -2179,7 +3286,7 @@ mod git_tests {fn a_tampered_checkout_runs_nothing_when_jan_inspects_and_fetches_it() {let Some(root) = repo("tamper") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let wt = ws.worktree.clone().unwrap();let c = wt.path.clone();@@ -2254,9 +3361,9 @@ mod git_tests {fn a_writers_branch_is_brought_back_and_never_overwrites_the_users() {let Some(root) = repo("bring") else { return };let ledger = Arc::new(Ledger::default());- let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (done, l2) = ledger.assign(&root, "general-2", true, None).unwrap();- let (clash, l3) = ledger.assign(&root, "general-3", true, None).unwrap();+ let (idle, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (done, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();+ let (clash, l3) = ledger.assign(&root, "general-3", true, None, true).unwrap();drop((l1, l2, l3));commit(&done.root, "b.txt");commit(&clash.root, "c.txt");@@ -2270,7 +3377,7 @@ mod git_tests {let none = idle.bring_back();let brought = done.bring_back();let refused = clash.bring_back();- let git_head = |ws: &ChildWorkspace| crate::core::agent::git::head_sha(&ws.root);+ let done_head = crate::core::agent::git::head_sha(&done.root);let in_repo = crate::core::agent::git::resolve_commit(&root, &branch(&done));let footer = done.answer_footer(brought.as_deref()).unwrap();let clash_footer = clash.answer_footer(refused.as_deref()).unwrap();@@ -2278,11 +3385,12 @@ mod git_tests {let idle_branch = crate::core::agent::git::resolve_commit(&root, &branch(&idle));let reader = ChildWorkspace::shared(&root, true);let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&clash.root);let _ = std::fs::remove_dir_all(&root);assert_eq!(none, None);assert_eq!(idle_branch, None, "a branch with no commits is not created");assert_eq!(brought, None);- assert_eq!(in_repo, git_head(&done));+ assert_eq!(in_repo, done_head);assert!(footer.contains(&branch(&done)) && !footer.contains("could not"), "{footer}");assert!(refused.is_some(), "a branch the user moved is not overwritten");assert_eq!(clash_now, user_tip);@@ -2304,7 +3412,7 @@ mod git_tests {] {let Some(root) = repo("config") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let wt = ws.worktree.clone().unwrap();commit(&wt.path, "b.txt");@@ -2332,7 +3440,7 @@ mod git_tests {fn a_checkout_with_rewritten_alternates_is_not_fetched_from() {let Some(root) = repo("alternates") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let wt = ws.worktree.clone().unwrap();commit(&wt.path, "b.txt");@@ -2352,6 +3460,751 @@ mod git_tests {assert!(kept[0].contains("alternates"), "{kept:?}");}+ /// A writer's committed, clean checkout is removed once its branch is in+ /// the user's repository, whether its finish brought it back or the+ /// settle did, and the user is told the branch, once.+ #[test]+ fn a_committed_checkout_whose_branch_was_brought_back_is_trashed_and_named() {+ let Some(root) = repo("brought") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ let tip = crate::core::agent::git::head_sha(&ws.root).unwrap();+ assert_eq!(ws.bring_back(), None, "as the writer's finish does");+ let branch = ws.worktree.as_ref().unwrap().branch.clone();++ let settled = ledger.finish_session();+ let in_repo = crate::core::agent::git::resolve_commit(&root, &branch);+ let gone = !ws.root.exists();+ let _ = std::fs::remove_dir_all(&root);+ assert!(settled.kept.is_empty(), "{:?}", settled.kept);+ assert!(gone, "its worktree goes");+ assert_eq!(in_repo.as_deref(), Some(tip.as_str()), "its work is on the branch");+ let bin = display(&dunce::canonicalize(trash_of(&root)).unwrap());+ assert_eq!(+ settled.notices(),+ [format!(+ "brought back branch {branch}, moved its worktree to {bin}; deleted after 7 days"+ )]+ );+ }++ /// Commit `.gitignore` with `rules` in the checkout `ws`, as a child would.+ fn commit_ignore(ws: &ChildWorkspace, rules: &str) {+ std::fs::write(ws.root.join(".gitignore"), rules).unwrap();+ assert!(git(&ws.root, &["add", ".gitignore"]));+ assert!(git(&ws.root, &["commit", "-q", "--no-gpg-sign", "-m", "ignore"]));+ }++ /// An ignored file that is not build output (a `.env`, local config) is+ /// only in the checkout: a brought-back checkout holding one is kept and+ /// listed with the file named, while one holding only ignored build+ /// output goes, into the trash rather than deleted.+ #[test]+ fn a_brought_back_checkout_keeps_ignored_files_but_not_build_output() {+ let Some(root) = repo("ignored") else { return };+ let ledger = Arc::new(Ledger::default());+ let (env, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (built, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();+ drop((l1, l2));+ commit_ignore(&env, ".env\ntarget/\n");+ std::fs::write(env.root.join(".env"), "KEY=1\n").unwrap();+ commit_ignore(&built, "target/\n");+ std::fs::create_dir_all(built.root.join("target/debug")).unwrap();+ std::fs::write(built.root.join("target/debug/app"), "x").unwrap();+ // As each writer's finish does.+ assert_eq!((env.bring_back(), built.bring_back()), (None, None));++ let session = Session { ledger: &ledger, children_running: &|| false };+ let listed = list_worktrees(&root, Some(&session));+ let settled = ledger.finish_with(|_| 0);+ let env_kept = env.root.join(".env").is_file();+ let built_gone = !built.root.exists();+ let trashed = std::fs::read_dir(trash_of(&root)).map_or(0, |e| e.count());+ let _ = std::fs::remove_dir_all(&env.root);+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(+ state_of(&listed, &env),+ &CheckoutState::Uncommitted {+ files: vec![".env".to_string()],+ commits: 1,+ off_branch: 0,+ build_output: vec![]+ }+ );+ assert_eq!(state_of(&listed, &built), &CheckoutState::Removable { commits: 1 });+ let shown = state_of(&listed, &env).describe();+ assert!(shown.starts_with("holds uncommitted work") && shown.contains(".env"), "{shown}");+ assert!(env_kept, "the .env is still there");+ assert_eq!(settled.kept.len(), 1, "{:?}", settled.kept);+ assert!(settled.kept[0].contains("1 uncommitted file(s)"), "{:?}", settled.kept);+ assert!(built_gone && trashed == 1, "build output alone does not keep it");+ }++ /// What is inside an ignored build-output directory is looked at: a+ /// `.env` in an ignored `build/`, or a repository cloned under an ignored+ /// `node_modules/`, keeps the checkout and is listed; the confirm and a+ /// forced prune's notice name the build output deleted with it.+ #[test]+ fn work_inside_ignored_build_output_keeps_the_checkout() {+ let Some(root) = repo("inside-ignored") else { return };+ let ledger = Arc::new(Ledger::default());+ let (env, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (nested, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();+ drop((l1, l2));+ commit_ignore(&env, "build/\n");+ std::fs::create_dir_all(env.root.join("build/out")).unwrap();+ std::fs::write(env.root.join("build/out/app.js"), "x".repeat(100)).unwrap();+ std::fs::write(env.root.join("build/out/.env"), "KEY=1\n").unwrap();+ commit_ignore(&nested, "node_modules/\n");+ std::fs::create_dir_all(nested.root.join("node_modules/x/.git")).unwrap();+ assert_eq!((env.bring_back(), nested.bring_back()), (None, None));++ let session = Session { ledger: &ledger, children_running: &|| false };+ let listed = list_worktrees(&root, Some(&session));+ let forced = Prune::One { id: id_of(&env), force: true };+ let pruned = prune_worktrees(&root, Some(&session), &forced);+ let settled = ledger.finish_with(|_| 0);+ let nested_kept = nested.root.join("node_modules/x/.git").is_dir();+ let _ = std::fs::remove_dir_all(&nested.root);+ let _ = std::fs::remove_dir_all(&root);+ let env_state = state_of(&listed, &env);+ assert_eq!(+ env_state,+ &CheckoutState::Uncommitted {+ files: vec!["build/out/.env".to_string()],+ commits: 1,+ off_branch: 0,+ build_output: vec!["build/".to_string()]+ }+ );+ let env_info = listed.checkouts.iter().find(|c| &c.state == env_state).unwrap();+ assert_eq!(+ env_info.loses().as_deref(),+ Some("1 uncommitted file(s) plus ignored build output (106 B)")+ );+ let nested_state = state_of(&listed, &nested);+ assert!(nested_state.describe().contains("node_modules/x/"), "{nested_state:?}");+ assert!(nested_kept, "a nested repository under node_modules keeps it");+ assert_eq!(settled.kept.len(), 1, "{:?}", settled.kept);+ assert_eq!(pruned.build_output, 106, "{pruned:?}");+ let notice = pruned.notice();+ assert!(+ notice.starts_with(+ "removed 1 subagent worktree(s) plus ignored build output (106 B), freed "+ ),+ "{notice}"+ );+ }++ /// A forced prune of an uncommitted checkout brings its branch back first+ /// and says so, as the confirm promised.+ #[test]+ fn a_forced_prune_of_uncommitted_work_names_the_branch_it_brought_back() {+ let Some(root) = repo("prune-brought") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();+ let session = Session { ledger: &ledger, children_running: &|| false };+ let forced = Prune::One { id: id_of(&ws), force: true };+ let pruned = prune_worktrees(&root, Some(&session), &forced);+ let branch = ws.worktree.as_ref().unwrap().branch.clone();+ let there = crate::core::agent::git::resolve_commit(&root, &branch);+ let _ = ledger.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(pruned.removed, std::slice::from_ref(&branch), "{pruned:?}");+ assert!(there.is_some());+ assert_eq!(pruned.brought, [branch], "{pruned:?}");+ }++ /// A mark taken again on the same path (a later conversation end) is not+ /// undone when the earlier one drops.+ #[test]+ fn an_old_settling_mark_never_removes_a_newer_one() {+ let ledger = Arc::new(Ledger::default());+ let path = Path::new("/w/general-0001");+ let mut state = ledger.state.lock().unwrap();+ let old = ledger.mark(&mut state, path);+ let new = ledger.mark(&mut state, path);+ drop(state);+ let session = Session { ledger: &ledger, children_running: &|| false };+ drop(old);+ assert_eq!(session.in_use(path), Some(InUseBy::Settling), "the newer mark stays");+ drop(new);+ assert_eq!(session.in_use(path), None);+ }++ /// A child can write its checkout's `.git/info/exclude`: what that hides+ /// is still the child's, so the checkout does not read as clean.+ #[test]+ fn a_file_hidden_by_the_checkouts_own_exclude_keeps_it() {+ let Some(root) = repo("info-exclude") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ std::fs::write(ws.root.join(".git/info/exclude"), "notes.md\n").unwrap();+ std::fs::write(ws.root.join("notes.md"), "mine\n").unwrap();+ let kept = ledger.finish_session().kept;+ let there = ws.root.join("notes.md").is_file();+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ assert!(there);+ assert_eq!(kept.len(), 1, "{kept:?}");+ }++ /// A branch already in the user's repository needs no bringing back, so a+ /// failed bring-back never keeps a checkout that holds nothing else, nor+ /// lists it as kept while calling it removable.+ #[test]+ fn a_checkout_whose_branch_is_already_in_the_repository_goes_without_a_fetch() {+ let Some(root) = repo("already") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ assert_eq!(ws.bring_back(), None);+ // Any fetch from the checkout into the user's repository now fails.+ let from = ws.root.join(".git").to_string_lossy().into_owned();+ let nowhere = format!("url.{}.insteadOf", root.join("nowhere").display());+ assert!(git(&root, &["config", &nowhere, &from]));+ let session = Session { ledger: &ledger, children_running: &|| false };+ let pruned = prune_worktrees(&root, Some(&session), &Prune::Safe);+ let gone = !ws.root.exists();+ let _ = ledger.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&root);+ assert!(gone && pruned.kept.is_empty(), "{pruned:?}");+ assert_eq!(pruned.removed.len(), 1, "{pruned:?}");+ }++ /// The settle brings a committed branch back itself; with two, one+ /// headline names both.+ #[test]+ fn the_settle_brings_branches_back_before_removing_their_checkouts() {+ let Some(root) = repo("brought-two") else { return };+ let ledger = Arc::new(Ledger::default());+ let (a, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (b, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();+ drop((l1, l2));+ commit(&a.root, "a2.txt");+ commit(&b.root, "b.txt");+ let branch = |ws: &ChildWorkspace| ws.worktree.as_ref().unwrap().branch.clone();+ let settled = ledger.end_conversation().settle();+ let fetched = [&a, &b].map(|ws| crate::core::agent::git::resolve_commit(&root, &branch(ws)));+ let gone = !a.root.exists() && !b.root.exists();+ let _ = std::fs::remove_dir_all(&root);+ assert!(settled.kept.is_empty(), "{:?}", settled.kept);+ assert!(gone);+ assert!(fetched.iter().all(Option::is_some), "{fetched:?}");+ let notices = settled.notices();+ assert_eq!(notices.len(), 1, "{notices:?}");+ assert!(notices[0].starts_with("brought back 2 branches, moved their worktrees to "));+ assert!(notices[0].contains("; deleted after 7 days\n"), "{notices:?}");+ assert!(notices[0].contains(&branch(&a)) && notices[0].contains(&branch(&b)));+ }++ /// Uncommitted work is only in the checkout: it stays, though its+ /// committed branch is brought back.+ #[test]+ fn a_committed_checkout_with_uncommitted_changes_is_kept() {+ let Some(root) = repo("brought-dirty") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();+ let branch = ws.worktree.as_ref().unwrap().branch.clone();+ let kept = ledger.finish_session().kept;+ let fetched = crate::core::agent::git::resolve_commit(&root, &branch);+ let there = ws.root.join("a.txt").is_file();+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ assert!(there);+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(kept[0].contains("1 commit(s), 1 uncommitted file(s)"), "{kept:?}");+ assert!(fetched.is_some(), "the commits are brought back anyway");+ }++ /// A branch that could not be brought back (the user's branch of that+ /// name moved on) is only in the checkout, which stays.+ #[test]+ fn a_checkout_whose_branch_could_not_be_brought_back_is_kept() {+ let Some(root) = repo("brought-clash") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ let branch = ws.worktree.as_ref().unwrap().branch.clone();+ commit(&root, "u.txt");+ assert!(git(&root, &["branch", &branch]));+ let kept = ledger.finish_session().kept;+ let there = ws.root.is_dir();+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ assert!(there);+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(kept[0].contains("its branch is not in your repository"), "{kept:?}");+ }++ /// A crashed session's committed, clean checkout is settled by the next+ /// start under the same rule: branch brought back, checkout removed.+ #[test]+ fn a_startup_sweep_trashes_an_orphan_once_its_branch_is_brought_back() {+ let Some(root) = repo("crash-brought") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ commit(&ws.root, "b.txt");+ let tip = crate::core::agent::git::head_sha(&ws.root).unwrap();+ let branch = ws.worktree.as_ref().unwrap().branch.clone();+ drop(ledger);+ let mut told = Vec::new();+ sweep_and_report(&root, &mut |text| {+ told.push(text);+ true+ });+ let fetched = crate::core::agent::git::resolve_commit(&root, &branch);+ let gone = !ws.root.exists();+ let record = meta_of(&root).join(format!("{}.json", id_of(&ws))).exists();+ let bin = display(&dunce::canonicalize(trash_of(&root)).unwrap());+ let _ = std::fs::remove_dir_all(&root);+ assert!(gone && !record);+ assert_eq!(fetched.as_deref(), Some(tip.as_str()));+ assert_eq!(+ told,+ [format!(+ "brought back branch {branch}, moved its worktree to {bin}; deleted after 7 days"+ )]+ );+ }++ /// Fill `root`'s project's shared build directory with `bytes` of output.+ fn fill_build_cache(root: &Path, bytes: usize) -> PathBuf {+ let target = project_worktrees_dir(root).unwrap().join(CARGO_TARGET);+ std::fs::create_dir_all(target.join("debug/deps")).unwrap();+ std::fs::write(target.join("debug/deps/lib.rlib"), vec![0u8; bytes]).unwrap();+ target+ }++ /// What of the trash's entries came from the build directory.+ fn trashed_caches(root: &Path) -> usize {+ std::fs::read_dir(trash_of(root)).map_or(0, |entries| {+ entries+ .filter_map(Result::ok)+ .filter(|e| e.file_name().to_string_lossy().starts_with(CARGO_TARGET))+ .count()+ })+ }++ /// A build directory over the cap is deleted when the session ends (not+ /// left in the trash), and the user is told once; one under it stays.+ #[test]+ fn a_build_cache_over_its_cap_is_deleted_at_session_end() {+ let Some(root) = repo("cache-over") else { return };+ let ledger = Arc::new(Ledger::default());+ let (_ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ let target = fill_build_cache(&root, 4096);+ let settled = ledger.finish_with(|_| 1024);+ let gone = !target.exists();+ use std::time::{Duration, Instant};+ // Deleted on a background thread, not left in the trash for a week.+ let deadline = Instant::now() + Duration::from_secs(10);+ while trashed_caches(&root) > 0 && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(20));+ }+ let trashed = trashed_caches(&root);+ let _ = std::fs::remove_dir_all(&root);+ assert!(gone && trashed == 0, "gone {gone}, trashed {trashed}");+ let notices = settled.notices();+ let cleared: Vec<_> = notices.iter().filter(|n| n.contains("build cache")).collect();+ assert_eq!(+ cleared,+ ["subagent build cache over 1024 bytes, cleared (next build starts cold)"],+ "{notices:?}"+ );+ }++ #[test]+ fn a_build_cache_under_its_cap_or_with_no_cap_is_kept() {+ let Some(root) = repo("cache-under") else { return };+ for cap in [1 << 20, 0] {+ let ledger = Arc::new(Ledger::default());+ let (_ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ let target = fill_build_cache(&root, 4096);+ let settled = ledger.finish_with(|_| cap);+ assert!(target.join("debug/deps/lib.rlib").is_file(), "cap {cap}");+ assert!(settled.notices().iter().all(|n| !n.contains("build cache")), "cap {cap}");+ assert_eq!(trim_build_cache(&root, cap), None, "cap {cap}");+ assert!(target.is_dir(), "cap {cap}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A child still building when the session ends (its writer holds its+ /// worktree) keeps the build directory it is writing into.+ #[test]+ fn a_build_cache_is_not_trimmed_while_a_child_is_busy() {+ let Some(root) = repo("cache-busy") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ let target = fill_build_cache(&root, 4096);+ let busy = ledger.finish_with(|_| 1024);+ let kept = target.is_dir();+ drop(lease);+ let after = ledger.finish_with(|_| 1024);+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ assert!(kept, "a busy child's build directory stays");+ assert!(busy.notices().iter().all(|n| !n.contains("build cache")));+ assert!(after.notices().iter().any(|n| n.contains("build cache")), "then it goes");+ }++ /// The startup sweep trims too, but never under a live session of+ /// another process (or this one) that holds a checkout of the project.+ #[test]+ fn the_startup_trim_spares_a_build_cache_a_live_session_may_use() {+ let Some(root) = repo("cache-sweep") else { return };+ let target = fill_build_cache(&root, 4096);+ let ledger = Arc::new(Ledger::default());+ let (_ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ let live = trim_build_cache(&root, 1024);+ let kept = target.is_dir();+ let _ = ledger.finish_with(|_| 0);+ let orphaned = trim_build_cache(&root, 1024);+ let gone = !target.exists();+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(live, None);+ assert!(kept);+ assert!(orphaned.is_some_and(|n| n.contains("cleared")) && gone);+ }++ /// The size walk stops once the cap is passed, and never follows a link.+ #[cfg(unix)]+ #[test]+ fn the_size_walk_is_bounded_and_follows_no_link() {+ let Some(root) = repo("cache-walk") else { return };+ let target = fill_build_cache(&root, 100);+ std::os::unix::fs::symlink(&root, target.join("link")).unwrap();+ std::fs::write(root.join("big"), vec![0u8; 8192]).unwrap();+ let over = |cap| larger_than(&target, cap);+ let (small, big) = (over(99), over(100));+ let _ = std::fs::remove_dir_all(&root);+ assert!(small, "100 bytes is over a 99-byte cap");+ assert!(!big, "and not over 100, the linked repository not counted");+ }++ /// A project with a checkout in each state `/worktrees` shows: in use by+ /// a writer of `ledger`, by another live session (`other`), with+ /// uncommitted work, with commits not in the user's repository, and+ /// removable. Returns the workspaces in that order and the writer's lease.+ fn every_state(+ root: &Path,+ ledger: &Arc<Ledger>,+ other: &Arc<Ledger>,+ ) -> ([ChildWorkspace; 5], Option<WriterLease>) {+ let (busy, lease) = ledger.assign(root, "busy", true, None, true).unwrap();+ let (theirs, l1) = other.assign(root, "theirs", true, None, true).unwrap();+ let (dirty, l2) = ledger.assign(root, "dirty", true, None, true).unwrap();+ let (committed, l3) = ledger.assign(root, "committed", true, None, true).unwrap();+ let (idle, l4) = ledger.assign(root, "idle", true, None, true).unwrap();+ drop((l1, l2, l3, l4));+ std::fs::write(dirty.root.join("a.txt"), "edited\n").unwrap();+ commit(&committed.root, "b.txt");+ ([busy, theirs, dirty, committed, idle], lease)+ }++ fn state_of<'a>(report: &'a WorktreesReport, ws: &ChildWorkspace) -> &'a CheckoutState {+ let branch = &ws.worktree.as_ref().unwrap().branch;+ &report.checkouts.iter().find(|c| &c.branch == branch).expect("listed").state+ }++ /// Each checkout is listed under the state that decides what may be done+ /// with it, with its size; the build cache with its own.+ #[test]+ fn the_list_names_each_checkouts_state_and_size() {+ let Some(root) = repo("list") else { return };+ let (ledger, other) = (Arc::new(Ledger::default()), Arc::new(Ledger::default()));+ let (ws, lease) = every_state(&root, &ledger, &other);+ fill_build_cache(&root, 4096);+ let session = Session { ledger: &ledger, children_running: &|| false };+ let report = list_worktrees(&root, Some(&session));+ let headless = list_worktrees(&root, None);+ drop(lease);+ let _ = ledger.finish_with(|_| 0);+ let _ = other.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(report.checkouts.len(), 5, "{report:?}");+ assert_eq!(state_of(&report, &ws[0]), &CheckoutState::InUse { by: InUseBy::Child });+ assert_eq!(state_of(&report, &ws[1]), &CheckoutState::InUse { by: InUseBy::Session });+ assert_eq!(+ state_of(&report, &ws[2]),+ &CheckoutState::Uncommitted {+ files: vec!["a.txt".to_string()],+ commits: 0,+ off_branch: 0,+ build_output: vec![]+ }+ );+ assert_eq!(state_of(&report, &ws[3]), &CheckoutState::Unbrought { commits: 1 });+ assert_eq!(state_of(&report, &ws[4]), &CheckoutState::Removable { commits: 0 });+ assert!(report.checkouts.iter().all(|c| c.bytes > 0), "{report:?}");+ assert_eq!(report.build_cache_bytes, Some(4096));+ assert_eq!(report.removable().0, 1);+ // Headless owns nothing: this session's checkouts are another's.+ for one in &ws {+ assert_eq!(state_of(&headless, one), &CheckoutState::InUse { by: InUseBy::Session });+ }+ let lines = report.lines().join("\n");+ assert!(lines.contains("build cache 4.0 KB"), "{lines}");+ assert!(lines.contains("holds uncommitted work: a.txt"), "{lines}");+ }++ /// The safe prune removes what session end would (bringing a committed+ /// branch back first), and never a checkout a running subagent or+ /// another live session holds, nor one with uncommitted work.+ #[test]+ fn a_safe_prune_removes_only_what_session_end_would() {+ let Some(root) = repo("prune-safe") else { return };+ let (ledger, other) = (Arc::new(Ledger::default()), Arc::new(Ledger::default()));+ let (ws, lease) = every_state(&root, &ledger, &other);+ let session = Session { ledger: &ledger, children_running: &|| false };+ let pruned = prune_worktrees(&root, Some(&session), &Prune::Safe);+ let there = ws.each_ref().map(|w| w.root.is_dir());+ let branch = |w: &ChildWorkspace| w.worktree.as_ref().unwrap().branch.clone();+ let brought = crate::core::agent::git::resolve_commit(&root, &branch(&ws[3]));+ let live = ledger.live().len();+ let trashed = std::fs::read_dir(trash_of(&root)).map_or(0, |e| e.count());+ drop(lease);+ let _ = ledger.finish_with(|_| 0);+ let _ = other.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&ws[2].root);+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(there, [true, true, true, false, false], "{pruned:?}");+ assert!(brought.is_some(), "its commits were brought back before it went");+ assert_eq!(pruned.removed.len(), 2, "{pruned:?}");+ assert_eq!(pruned.brought, [branch(&ws[3])]);+ assert_eq!(pruned.kept.len(), 3, "{pruned:?}");+ // Moved to the trash, as session end does, not deleted.+ assert!(pruned.freed == 0 && pruned.trashed > 0, "{pruned:?}");+ assert_eq!(trashed, 2);+ assert_eq!(live, 2, "the ledger forgets what went (theirs is another's)");+ assert!(pruned.notice().starts_with("removed 2 subagent worktree(s); moved "));+ }++ /// A checkout a running subagent works in is never removed, whatever is+ /// asked: not by the safe prune, not by a forced one, not by name.+ #[test]+ fn a_checkout_in_use_by_a_live_child_is_never_removed() {+ let Some(root) = repo("prune-busy") else { return };+ let ledger = Arc::new(Ledger::default());+ let (busy, lease) = ledger.assign(&root, "busy", true, None, true).unwrap();+ let (reused, l2) = ledger.assign(&root, "reused", true, None, true).unwrap();+ drop(l2);+ let id = id_of(&busy);+ // A reader holds no lease: while any subagent runs, none of the+ // session's checkouts goes.+ let running = Session { ledger: &ledger, children_running: &|| true };+ let pruned = prune_worktrees(&root, Some(&running), &Prune::All);+ assert!(reused.root.is_dir() && pruned.removed.is_empty(), "{pruned:?}");+ let session = Session { ledger: &ledger, children_running: &|| false };+ for which in [Prune::Safe, Prune::All, Prune::One { id: id.clone(), force: true }] {+ let pruned = prune_worktrees(&root, Some(&session), &which);+ assert!(busy.root.is_dir(), "{which:?}");+ assert!(!pruned.removed.contains(&busy.worktree.as_ref().unwrap().branch));+ }+ assert!(!reused.root.exists(), "the idle one went once nothing ran");+ drop(lease);+ let _ = ledger.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// After the user confirms the loss, one checkout with uncommitted work+ /// goes by name (its committed branch still brought back first), and+ /// `All` takes every one not in use.+ #[test]+ fn a_confirmed_prune_removes_work_but_never_another_sessions_checkout() {+ let Some(root) = repo("prune-force") else { return };+ let (ledger, other) = (Arc::new(Ledger::default()), Arc::new(Ledger::default()));+ let (ws, lease) = every_state(&root, &ledger, &other);+ let session = Session { ledger: &ledger, children_running: &|| false };+ let unforced = Prune::One { id: id_of(&ws[2]), force: false };+ let kept = prune_worktrees(&root, Some(&session), &unforced);+ let dirty_kept = ws[2].root.is_dir();+ let forced = Prune::One { id: id_of(&ws[2]), force: true };+ let one = prune_worktrees(&root, Some(&session), &forced);+ let dirty_gone = !ws[2].root.exists();+ let all = prune_worktrees(&root, Some(&session), &Prune::All);+ let there = ws.each_ref().map(|w| w.root.is_dir());+ drop(lease);+ let _ = ledger.finish_with(|_| 0);+ let _ = other.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&root);+ assert!(dirty_kept && kept.removed.is_empty(), "{kept:?}");+ assert!(dirty_gone && one.removed.len() == 1, "{one:?}");+ assert!(one.freed > 0 && one.trashed == 0, "deleted at once: {one:?}");+ assert_eq!(there, [true, true, false, false, false], "{all:?}");+ assert_eq!(all.removed.len(), 2, "{all:?}");+ }++ /// Clearing the build cache deletes it and says how much it freed, but+ /// not while a subagent of this session or another live session may be+ /// building in it.+ #[test]+ fn the_build_cache_is_cleared_only_when_no_build_may_run() {+ let Some(root) = repo("clear-cache") else { return };+ let target = fill_build_cache(&root, 4096);+ let (ledger, other) = (Arc::new(Ledger::default()), Arc::new(Ledger::default()));+ let (_mine, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ let session = Session { ledger: &ledger, children_running: &|| false };+ let busy = clear_build_cache(&root, Some(&session));+ drop(lease);+ let running = Session { ledger: &ledger, children_running: &|| true };+ let reading = clear_build_cache(&root, Some(&running));+ let (_theirs, l2) = other.assign(&root, "general", true, None, true).unwrap();+ drop(l2);+ let elsewhere = clear_build_cache(&root, Some(&session));+ let kept = target.join("debug/deps/lib.rlib").is_file();+ let _ = other.finish_with(|_| 0);+ // This session's own idle checkout does not hold the cache back.+ let cleared = clear_build_cache(&root, Some(&session));+ let gone = !target.exists();+ let trashed = trashed_caches(&root);+ let again = clear_build_cache(&root, None);+ let _ = ledger.finish_with(|_| 0);+ let _ = std::fs::remove_dir_all(&root);+ assert!(busy.is_err() && reading.is_err(), "{busy:?} {reading:?}");+ assert!(elsewhere.is_err_and(|e| e.contains("another live jan session")));+ assert!(kept);+ assert_eq!(cleared, Ok(4096));+ assert!(gone && trashed == 0, "deleted, not left in the trash");+ assert!(again.is_err_and(|e| e.contains("no subagent build cache")));+ }++ /// Any child given the build directory (a reader in the parent's own+ /// checkout too, which holds no checkout lock) holds the build lock+ /// shared, from another process as from this one: while it does, neither+ /// the trim nor the clear touches the directory; once it lets go, both may.+ #[test]+ fn the_build_cache_is_neither_trimmed_nor_cleared_while_a_child_holds_it() {+ let Some(root) = repo("build-lock") else { return };+ let target = fill_build_cache(&root, 4096);+ let reader = ChildWorkspace::shared(&root, true);+ let placement = place(&reader, &root);+ let mut args = crate::core::agent::subagent::tests::max_par_args(&root);+ let hold = apply(&mut args, &reader, placement);+ assert!(hold.is_some(), "a reader building in the cache holds its lock");+ let trimmed = trim_build_cache(&root, 1024);+ let cleared = clear_build_cache(&root, None);+ let kept = target.join("debug/deps/lib.rlib").is_file();+ drop(hold);+ // Another process's child: its own open of the lock file, held shared.+ let other = open_build_lock(&project_worktrees_dir(&root).unwrap()).unwrap();+ fs4::FileExt::lock_shared(&other).unwrap();+ let elsewhere = clear_build_cache(&root, None);+ drop(other);+ let free = trim_build_cache(&root, 1024);+ let gone = !target.exists();+ let refilled = fill_build_cache(&root, 4096);+ let cleared_free = clear_build_cache(&root, None);+ let gone_again = !refilled.exists();+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(trimmed, None);+ assert!(cleared.is_err() && elsewhere.is_err(), "{cleared:?} {elsewhere:?}");+ assert!(kept);+ assert!(free.is_some() && gone, "{free:?}");+ assert_eq!(cleared_free, Ok(4096));+ assert!(gone_again);+ }++ /// A checkout this session kept at a conversation end is still held by+ /// it until the user is told: `/worktrees` says so, rather than calling+ /// it another session's, and prunes it as nobody's once told.+ #[test]+ fn a_checkout_held_after_a_conversation_end_is_labelled_as_this_sessions() {+ let Some(root) = repo("settling") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();+ drop(lease);+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();+ let settled = ledger.end_conversation().settle();+ let session = Session { ledger: &ledger, children_running: &|| false };+ let held = list_worktrees(&root, Some(&session));+ let pruned = prune_worktrees(&root, Some(&session), &Prune::All);+ let there = ws.root.is_dir();+ settled.report(&mut |_| true);+ let told = list_worktrees(&root, Some(&session));+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(state_of(&held, &ws), &CheckoutState::InUse { by: InUseBy::Settling });+ assert!(state_of(&held, &ws).describe().contains("this session"));+ assert!(there && pruned.removed.is_empty(), "{pruned:?}");+ assert!(matches!(state_of(&told, &ws), CheckoutState::Uncommitted { .. }), "{told:?}");+ }++ /// The confirm names only what is really lost: a removal brings an+ /// uncommitted checkout's branch back first, so only its files (and any+ /// commit on no branch) are lost; an unbrought one loses its commits.+ #[test]+ fn the_loss_named_counts_only_what_a_removal_cannot_bring_back() {+ let files = vec!["a.txt".to_string(), ".env".to_string()];+ let dirty = CheckoutState::Uncommitted {+ files: files.clone(),+ commits: 3,+ off_branch: 0,+ build_output: vec![],+ };+ assert_eq!(dirty.loses().as_deref(), Some("2 uncommitted file(s)"));+ assert_eq!(+ dirty.brings_back().as_deref(),+ Some("its branch (3 commit(s)) is brought back to your repository first")+ );+ let stashed = CheckoutState::Uncommitted {+ files: files.clone(),+ commits: 3,+ off_branch: 1,+ build_output: vec![],+ };+ assert_eq!(+ stashed.loses().as_deref(),+ Some("2 uncommitted file(s) and 1 commit(s) on no branch")+ );+ let only_files =+ CheckoutState::Uncommitted { files, commits: 0, off_branch: 0, build_output: vec![] };+ assert_eq!(only_files.brings_back(), None);+ let ahead = CheckoutState::Unbrought { commits: 2 };+ assert_eq!(ahead.loses().as_deref(), Some("2 commit(s) not in your repository"));+ assert_eq!(ahead.brings_back(), None);+ }++ /// A checkout's size and its build output's are counted in one walk,+ /// a named file as well as a named directory.+ #[test]+ fn build_output_is_measured_in_the_walk_that_sizes_the_checkout() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join("build/out")).unwrap();+ std::fs::write(dir.path().join("build/out/app.js"), "x".repeat(100)).unwrap();+ std::fs::write(dir.path().join("x.o"), "x".repeat(10)).unwrap();+ std::fs::write(dir.path().join("a.txt"), "x").unwrap();+ let built = vec!["build/".to_string(), "x.o".to_string()];+ assert_eq!(sizes(dir.path(), &built, u64::MAX), (111, 110));+ assert_eq!(sizes(dir.path(), &[], u64::MAX), (111, 0));+ assert_eq!(dir_size(dir.path(), u64::MAX), 111);+ }++ #[test]+ fn sizes_read_as_a_person_would_say_them() {+ assert_eq!(human_bytes(0), "0 B");+ assert_eq!(human_bytes(1023), "1023 B");+ assert_eq!(human_bytes(1536), "1.5 KB");+ assert_eq!(human_bytes(20 << 30), "20.0 GB");+ }+/// The `.meta` and `.trash` directories beside `root`'s checkouts.fn meta_of(root: &Path) -> PathBuf {dunce::canonicalize(project_worktrees_dir(root).unwrap()).unwrap().join(META_DIR)@@ -2372,14 +4225,14 @@ mod git_tests {fn a_new_conversation_cannot_reuse_an_earlier_conversations_worktree_by_name() {let Some(root) = repo("names") else { return };let ledger = Arc::new(Ledger::default());- let (kept, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (_idle, l2) = ledger.assign(&root, "explore", true, None).unwrap();+ let (kept, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (_idle, l2) = ledger.assign(&root, "explore", true, None, true).unwrap();drop((l1, l2));- commit(&kept.root, "b.txt");+ std::fs::write(kept.root.join("a.txt"), "edited\n").unwrap();assert_eq!(ledger.end_conversation().settle().kept.len(), 1);for earlier in ["general", "explore"] {let reuse = WorkspaceRequest::Reuse(earlier.to_string());- let err = ledger.assign(&root, "next", true, Some(&reuse)).unwrap_err();+ let err = ledger.assign(&root, "next", true, Some(&reuse), true).unwrap_err();assert!(err.contains("no earlier subagent"), "{earlier}: {err}");}assert!(ledger.live().is_empty(), "{:?}", ledger.live());@@ -2394,9 +4247,9 @@ mod git_tests {fn a_replaced_conversations_kept_worktree_is_marked_only_once_reported() {let Some(root) = repo("conv-unsent") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);- commit(&ws.root, "b.txt");+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();let untold = ledger.end_conversation().settle();assert_eq!(untold.kept.len(), 1);drop(untold);@@ -2419,10 +4272,10 @@ mod git_tests {fn ending_a_conversation_leaves_the_next_conversations_worktrees_alone() {let Some(root) = repo("next") else { return };let ledger = Arc::new(Ledger::default());- let (old, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (old, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let batch = ledger.end_conversation();- let (new, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (new, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);assert!(batch.settle().kept.is_empty());assert!(!old.root.exists(), "the old conversation's empty worktree goes");@@ -2438,14 +4291,14 @@ mod git_tests {fn a_late_undo_keeps_the_next_conversations_name() {let Some(root) = repo("late-undo") else { return };let ledger = Arc::new(Ledger::default());- let (old, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (old, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let batch = ledger.end_conversation();- let (new, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (new, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);ledger.undo("general", &old);let reuse = WorkspaceRequest::Reuse("general".to_string());- let again = ledger.assign(&root, "next", false, Some(&reuse)).map(|(ws, _)| ws.root);+ let again = ledger.assign(&root, "next", false, Some(&reuse), true).map(|(ws, _)| ws.root);drop(batch.settle());let _ = ledger.finish_session();let _ = std::fs::remove_dir_all(&root);@@ -2458,7 +4311,7 @@ mod git_tests {fn a_busy_worktree_survives_a_conversation_end_and_goes_at_the_next() {let Some(root) = repo("busyend") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();assert!(ledger.end_conversation().settle().kept.is_empty());assert!(ws.root.is_dir(), "a writer is still in it");drop(lease);@@ -2474,7 +4327,7 @@ mod git_tests {fn an_empty_worktree_is_moved_to_trash_not_deleted_in_place() {let Some(root) = repo("trash") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);let settled = ledger.finish_session();assert!(settled.kept.is_empty());@@ -2509,7 +4362,7 @@ mod git_tests {fn an_untracked_directory_keeps_a_worktree_under_the_fast_check() {let Some(root) = repo("untracked-dir") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);std::fs::create_dir_all(ws.root.join("node_modules/x")).unwrap();std::fs::write(ws.root.join("node_modules/x/y.js"), "y\n").unwrap();@@ -2532,9 +4385,9 @@ mod git_tests {let ledger = Arc::new(Ledger::default());let mut roots = Vec::new();for name in ["general", "general-2", "general-3"] {- let (ws, lease) = ledger.assign(&root, name, true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, name, true, None, true).unwrap();drop(lease);- commit(&ws.root, "b.txt");+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();if !slow_status(&ws.root) {return;}@@ -2557,8 +4410,8 @@ mod git_tests {fn each_worktree_records_its_metadata_beside_not_inside_its_checkout() {let Some(root) = repo("meta") else { return };let ledger = Arc::new(Ledger::default());- let (kept, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (idle, l2) = ledger.assign(&root, "general-2", true, None).unwrap();+ let (kept, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (idle, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();drop((l1, l2));let wt = kept.worktree.clone().unwrap();let json = meta_of(&root).join(format!("{}.json", id_of(&kept)));@@ -2573,7 +4426,7 @@ mod git_tests {assert_eq!(meta.repo, wt.repo);assert_eq!(meta.objects, wt.objects);assert!(!meta.finished);- commit(&kept.root, "b.txt");+ std::fs::write(kept.root.join("a.txt"), "edited\n").unwrap();assert_eq!(ledger.finish_session().kept.len(), 1);assert!(read(&json).finished, "a reported worktree is marked");for ext in ["json", "lock"] {@@ -2586,17 +4439,19 @@ mod git_tests {/// A session that dies without settling (its locks drop with it) leaves/// worktrees the next start settles: the empty one goes, the branch of- /// the committed one is brought back, and each is reported only once.+ /// the committed one is brought back though it is kept for its+ /// uncommitted edit, and each kept one is reported only once.#[test]fn a_startup_sweep_settles_what_a_crashed_session_left() {let Some(root) = repo("crash") else { return };let ledger = Arc::new(Ledger::default());- let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (committed, l2) = ledger.assign(&root, "general-2", true, None).unwrap();- let (dirty, l3) = ledger.assign(&root, "general-3", true, None).unwrap();+ let (idle, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (committed, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();+ let (dirty, l3) = ledger.assign(&root, "general-3", true, None, true).unwrap();drop((l1, l2, l3));commit(&committed.root, "b.txt");let tip = crate::core::agent::git::head_sha(&committed.root).unwrap();+ std::fs::write(committed.root.join("b.txt"), "edited\n").unwrap();std::fs::write(dirty.root.join("a.txt"), "edited\n").unwrap();drop(ledger);@@ -2624,9 +4479,9 @@ mod git_tests {fn an_orphan_is_marked_reported_only_once_its_notice_is_taken() {let Some(root) = repo("crash-unsent") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);- commit(&ws.root, "b.txt");+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();drop(ledger);let sweep = |accept: bool| {let mut seen = Vec::new();@@ -2654,7 +4509,7 @@ mod git_tests {use std::time::{Duration, Instant};let Some(root) = repo("sweep-exit") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);drop(ledger);if !slow_status(&ws.root) {@@ -2679,7 +4534,7 @@ mod git_tests {fn a_startup_sweep_skips_worktrees_a_live_session_owns() {let Some(root) = repo("live") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);assert!(sweep_orphans(&root).kept.is_empty());assert!(ws.root.is_dir(), "a live session's worktree stays");@@ -2693,7 +4548,7 @@ mod git_tests {fn a_startup_sweep_never_removes_a_checkout_git_cannot_read() {let Some(root) = repo("crash-unread") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);drop(ledger);let alternates = ws.root.join(".git/objects/info/alternates");@@ -2714,8 +4569,8 @@ mod git_tests {let Some(root) = repo("crash-forged") else { return };let Some(other) = repo("crash-other") else { return };let ledger = Arc::new(Ledger::default());- let (a, l1) = ledger.assign(&root, "general", true, None).unwrap();- let (b, l2) = ledger.assign(&root, "general-2", true, None).unwrap();+ let (a, l1) = ledger.assign(&root, "general", true, None, true).unwrap();+ let (b, l2) = ledger.assign(&root, "general-2", true, None, true).unwrap();drop((l1, l2));commit(&b.root, "b.txt");drop(ledger);@@ -2821,7 +4676,7 @@ mod git_tests {fn a_sweep_never_takes_a_checkout_reserved_without_a_lock() {let Some(root) = repo("nolock-sweep") else { return };let ledger = Arc::new(Ledger::default());- let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(&root, "general", true, None, true).unwrap();drop(lease);commit(&ws.root, "b.txt");let dir = meta_of(&root).parent().unwrap().to_path_buf();diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex e11189afd..8190d5265 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -26,8 +26,10 @@ const GUIDELINES: &str =- Call `ask` when the user's answer would materially change scope, behavior, or an irreversible action and it cannot be safely inferred from the request or project context. Ask concise, decision-ready questions; otherwise make the reasonable choice and proceed.\n\- Tool output is complete and verbatim. Trust it. Do not re-run a command to check for hidden or \missing output: when output is cut it always carries an explicit `[output truncated ...]` notice, so \-its absence means you have everything. A command's `[exit N]` line is the authoritative result -- \-`[exit 0]` is success even if there is text on stderr (many tools write normal status there).\n\+its absence means you have everything. A shell result's `[exit N]` line is the authoritative result, \+and a nonzero exit or a signal is always reported; a command that printed output and succeeded comes \+back without `[exit 0]`. Text on stderr is not failure on its own (many tools write normal status \+there).\n\- You may end your turn while background work is still running -- a backgrounded shell command, a \dispatched subagent, a monitor. You are notified automatically when each one finishes, and the \notice reaches you as a `<SYSTEM>` note that resumes the conversation, so nothing is lost by \@@ -243,7 +245,10 @@ that could pull in a lot of file content or tool output (broad codebase search,multi-step research), prefer `dispatch_subagent` over doing it inline: the subagent absorbs that context \in its own window and returns only the distilled answer. For read-only codebase questions set `agent: \"explore\"` \and for web lookups `agent: \"research\"`: both run on a cheaper model; use `agent: \"general\"` when no \-other agent fits. Dispatch independent subagents in parallel when \+other agent fits. A difficult task -- a change spanning several subsystems, a hard bug, a large \+refactor or migration -- is where subagents pay off most: split it into independent parts and hand them \+out (parallel investigations up front, a `debug` agent on a failure, a `review` of the finished change) \+instead of carrying the whole task in one context. Dispatch independent subagents in parallel when \their work doesn't depend on each other; each returns in the background and a note carries its answer when \it finishes. Once you delegate a task it belongs to that subagent -- do not do the same work yourself; \spend the wait on other steps, and only `await_subagent` when nothing else is left to do. Do inline work \@@ -256,16 +261,52 @@ task, and record anything worth keeping from its answer yourself.";/// `child_workspace`), so there it would describe branches that never exist./// A constant per build, so the prefix stays byte-stable.const SUBAGENT_WORKSPACE_GUIDE: &str = if cfg!(feature = "cli") {- "\n\nEach subagent's workspace is set when you dispatch it. One that can write or edit files works in its own \-checkout (a clone) on its own branch, started from HEAD, so parallel writers never share a checkout and \-your uncommitted changes are not in it; its branch is in your repository when it is done, to merge. \+ "\n\nEach subagent's workspace is set when you dispatch it. By default one that can write or edit files works in your checkout, shared with you and with any \+other writer, so parallel writers can overwrite each other: give them disjoint files, or `workspace: \"new\"`. \+When the user turned on subagent worktrees (`--subagent-worktrees`, or `subagent_worktrees` under `[agent]` in \+agent.toml) it instead works in its own checkout (a clone) on its own branch, started from HEAD, so parallel \+writers never share a checkout and your uncommitted changes are not in it; its branch is in your repository \+when it is done, to merge. \Any other subagent works in your checkout read-only. The dispatch result says where each one works. Override with `workspace`: \"new\", \\"shared\", the name of an earlier subagent to continue in its worktree, or `workspace: {\"ref\": \"<git \-ref>\"}` to review or test a branch or pull request in a checkout of its own."+ref>\"}` to review or test a branch or pull request in a checkout of its own. In a later phase, \+`workspace` naming the agent of an earlier-phase subagent of the same plan (e.g. \"general\") means \+that sibling's checkout, so a review phase checks exactly what the implementer wrote."} else {""};+/// How to split, coordinate and verify parallel work. Kept apart from+/// [`SUBAGENT_GUIDE`] (when to delegate at all) because these are the failures+/// seen once several children run at once: siblings editing the same file, a+/// contract one changes that the others never hear of, and children that each+/// verify only their own slice so nobody checks the combined result.+const SUBAGENT_COORDINATION_GUIDE: &str = "\n\n## Parallel work\n\n\+- Split by ownership, not by step: give each parallel subagent a disjoint set of files or \+subsystems, say in its task which files it owns and which ones siblings are editing, and tell it \+to change nothing else. Work that must follow other work goes in a later `phase` (implement, \+then review), not in the same one.\n\+- Write each task as a complete brief: the goal, the relevant paths and facts you already know, \+the project rules that apply, the checks to run, and the shape of the report you want back \+(what changed, commit, what was run and its result). A child that has to rediscover context \+you already have wastes its window.\n\+- You are the hub between siblings: they cannot talk to each other. When one reports a decision \+another depends on (an event shape, a renamed function, a changed signature), relay it with \+`message_subagent` at once instead of fixing the mismatch after both finish. A later-phase \+subagent can be messaged before it starts.\n\+- Read each answer as soon as it arrives and act on it while the others still run: relay, \+merge, or correct a child heading the wrong way.\n\n\+## Verification\n\n\+- Ask every implementing subagent to prove its change: a failing test first where it fits, then \+the project's checks for what it touched, reported with the exact commands, their results, and \+what was not run and why.\n\+- A child's report is evidence, not proof. Check claims that matter (a reported commit, a \+passing suite) before you build on them.\n\+- Each child sees only its slice. After merging parallel work, run the checks on the combined \+result yourself, then hand the combined change to a fresh `review` subagent that wrote none of \+it. Point it at the exact range or commit to review and at the risky parts, and verify each \+finding before acting on it.";+/// The `# Subagents` block: the guide, then the predefined agents the/// `dispatch_subagent` `agent` enum accepts, each with its model and purpose./// Read from the registry when the prompt is composed, so it is fixed for the@@ -275,9 +316,10 @@ fn subagent_guide(project_root: &Path) -> String {let registry = crate::core::agent::subagent::SubagentRegistry::load(project_root);match crate::core::agent::subagent::agent_catalog(®istry) {Some(catalog) => format!(- "{SUBAGENT_GUIDE}{SUBAGENT_WORKSPACE_GUIDE}\n\nPredefined agents (`agent` field):\n{catalog}"+ "{SUBAGENT_GUIDE}{SUBAGENT_WORKSPACE_GUIDE}{SUBAGENT_COORDINATION_GUIDE}\n\n\+ Predefined agents (`agent` field):\n{catalog}"),- None => format!("{SUBAGENT_GUIDE}{SUBAGENT_WORKSPACE_GUIDE}"),+ None => format!("{SUBAGENT_GUIDE}{SUBAGENT_WORKSPACE_GUIDE}{SUBAGENT_COORDINATION_GUIDE}"),}}@@ -345,7 +387,9 @@ fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> Str// name it too.let scratch_line = match scratch {Some(scratch) => format!(- "\nScratch: `{}` is a writable scratch space for temporary work; it persists for this session.",+ "\nScratch: `{}` is a writable scratch space for temporary work; it persists for this session. \+Put temporary files, clones and worktrees there, not in `/tmp`: under the sandbox `/tmp` can be \+private to a single command and gone once it exits.",display_path(scratch)),None => String::new(),@@ -1222,6 +1266,30 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // Parallel work fails at the seams: siblings editing the same file, a+ // contract one changes that the other never hears of, and each child+ // verifying only its own slice. The guide must cover all three, plus an+ // independent review of the combined result.+ #[test]+ fn subagent_guide_covers_splitting_coordination_and_verification() {+ let root = scratch_project("subagent-coordination");+ let with = default_prompt(None, &root, None, true).expect("prompt");+ for needle in [+ "## Parallel work",+ "which files it owns",+ "relay it with `message_subagent`",+ "## Verification",+ "what was not run",+ "combined result yourself",+ "a fresh `review` subagent",+ ] {+ assert!(with.contains(needle), "missing {needle:?}");+ }+ let guide = with.find("## Parallel work").unwrap();+ assert!(guide < with.find("Predefined agents").unwrap_or(usize::MAX));+ let _ = std::fs::remove_dir_all(&root);+ }+// Where a child works is decided at dispatch, and the CLI guide says so,// ahead of the agent catalog.#[cfg(feature = "cli")]@@ -1231,8 +1299,13 @@ mod tests {let with = default_prompt(None, &root, None, true).expect("prompt");assert!(with.contains("own checkout"), "{with}");assert!(with.contains("is in your repository"), "{with}");+ // Off by default: a writer shares the checkout unless worktrees are on.+ assert!(with.contains("works in your checkout, shared with you"), "{with}");+ assert!(with.contains("overwrite each other"), "{with}");+ assert!(with.contains("subagent_worktrees"), "{with}");assert!(with.contains("read-only"), "{with}");assert!(with.contains("workspace: {\"ref\""), "{with}");+ assert!(with.contains("means that sibling's checkout"), "{with}");let guide = with.find("Each subagent's workspace").expect("workspace paragraph");assert!(guide < with.find("Predefined agents").unwrap(), "{with}");let _ = std::fs::remove_dir_all(&root);diff --git a/src-tauri/src/core/agent/continuation.rs b/src-tauri/src/core/agent/continuation.rsindex f31e3068a..1af464a5c 100644--- a/src-tauri/src/core/agent/continuation.rs+++ b/src-tauri/src/core/agent/continuation.rs@@ -877,6 +877,23 @@ mod tests {/// (#13) Recent errors are read back, so failures from before the last/// compaction are still listed after the next one.+ /// A shell call reaches the record as the model saw it: a clean exit+ /// after output has no marker, a failure keeps one, so compaction still+ /// lists a command that printed and failed.+ #[test]+ fn gather_lists_a_shell_failure_that_printed_output() {+ use tauri_plugin_agent_tools::tools::handlers::model_shell_result;+ let recorded = vec![+ call("ok", "shell", "{}"),+ result("ok", &model_shell_result("built\n[exit 0]")),+ call("bad", "shell", "{}"),+ result("bad", &model_shell_result("error: E0308\n[exit 101]")),+ ];+ let gathered = gather(&recorded);+ assert_eq!(gathered.errors.len(), 1, "{:?}", gathered.errors);+ assert!(gathered.errors[0].contains("E0308"), "{:?}", gathered.errors);+ }+#[test]fn recent_errors_survive_a_recompaction() {let first = gather(&[diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rsindex c361538d2..bee2a2f19 100644--- a/src-tauri/src/core/agent/git.rs+++ b/src-tauri/src/core/agent/git.rs@@ -1073,26 +1073,45 @@ impl Checkout {/// `git <args>` in the checkout, its git dir and work tree named/// explicitly.fn run(&self, args: &[&str]) -> Result<String, String> {- let out = self.output(args)?;+ let out = self.output(args, &[])?;outcome(&out, args)}/// [`Self::run`] with stdout as git wrote it: paths are bytes, and a- /// lossy decoding can name a file that does not exist.- fn run_raw(&self, args: &[&str]) -> Result<Vec<u8>, String> {- let out = self.output(args)?;+ /// lossy decoding can name a file that does not exist. `input`, when not+ /// empty, is git's stdin (a `--stdin` list).+ fn run_raw(&self, args: &[&str], input: &[u8]) -> Result<Vec<u8>, String> {+ let out = self.output(args, input)?;outcome(&out, args)?;Ok(out.stdout)}- fn output(&self, args: &[&str]) -> Result<std::process::Output, String> {+ fn output(&self, args: &[&str], input: &[u8]) -> Result<std::process::Output, String> {+ use std::process::Stdio;let opts = self.hardened();let mut full: Vec<&str> = opts.iter().map(String::as_str).collect();full.extend_from_slice(args);let mut cmd = repo_command(&self.path, &full)?;cmd.env("GIT_DIR", self.path.join(".git")).env("GIT_WORK_TREE", &self.path);- cmd.output().map_err(|e| format!("failed to launch git: {e}"))+ if input.is_empty() {+ return cmd.output().map_err(|e| format!("failed to launch git: {e}"));+ }+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());+ let mut child = cmd.spawn().map_err(|e| format!("failed to launch git: {e}"))?;+ let stdin = child.stdin.take();+ let input = input.to_vec();+ // Written while git runs: it answers as it reads, and a long list+ // would fill both pipes and stall the two of us if written first.+ let feed = std::thread::spawn(move || {+ if let Some(mut stdin) = stdin {+ // A git that exits early closes the pipe; its status says why.+ let _ = std::io::Write::write_all(&mut stdin, &input);+ }+ });+ let out = child.wait_with_output().map_err(|e| format!("failed to run git: {e}"));+ let _ = feed.join();+ out}/// The branch checked out there, `None` when detached or unreadable.@@ -1124,21 +1143,38 @@ impl Checkout {self.run(&["rev-list", "--count", "--all", "--not", base, "--"]).ok()?.parse().ok()}- /// [`try_changed_paths`] for this checkout. A nested repository (or a- /// recorded submodule) is never opened: its own config can name a program- /// (`core.fsmonitor`) that its status would run.- pub(crate) fn try_changed_paths(&self) -> Result<Vec<String>, String> {- changed_paths_with(|args| {- let mut full = args.to_vec();- full.push("--ignore-submodules=all");- self.run(&full)- })+ /// What removing the checkout would lose besides its commits: every path+ /// [`work_with`] reports, as one list for both the clean check and the+ /// count the user is shown, so the two never disagree. A nested+ /// repository (or a recorded submodule) is never opened: its own config+ /// can name a program (`core.fsmonitor`) that its status would run.+ pub(crate) fn uncommitted(&self) -> Result<Vec<String>, String> {+ work_with(+ &self.path,+ |args, input| Ok(String::from_utf8_lossy(&self.run_raw(args, input)?).into_owned()),+ |path| std::fs::read(self.path.join(path)).ok(),+ )+ .map(|work| work.paths)+ }++ /// Everything removal would lose or delete, read once: [`Self::uncommitted`],+ /// the ignored build output, and whether a submodule holds work.+ pub(crate) fn work(&self) -> Result<Work, String> {+ let submodule = self.holds_submodule_work()?;+ let work = work_with(+ &self.path,+ |args, input| Ok(String::from_utf8_lossy(&self.run_raw(args, input)?).into_owned()),+ |path| std::fs::read(self.path.join(path)).ok(),+ )?;+ Ok(Work { submodule, ..work })}/// Whether the checkout has no uncommitted change. `Err` when git cannot/// tell, which a caller deciding on removal must never read as clean.+ /// Tests only: a removal reads [`Self::work`] once, for its paths too.+ #[cfg(test)]pub(crate) fn is_clean(&self) -> Result<bool, String> {- Ok(!self.holds_submodule_work()? && clean_with(|args| self.run(args))?)+ Ok(self.work()?.is_empty())}/// Whether a submodule holds anything: status never looks inside one (see@@ -1156,7 +1192,7 @@ impl Checkout {return Ok(true);}// `<mode> <object> <stage>\t<path>`; mode 160000 is a submodule.- let listed = self.run_raw(&["ls-files", "--stage", "-z"])?;+ let listed = self.run_raw(&["ls-files", "--stage", "-z"], &[])?;for entry in listed.split(|&b| b == 0) {let Some(tab) = entry.iter().position(|&b| b == b'\t') else { continue };if !entry.starts_with(b"160000 ") {@@ -1243,23 +1279,452 @@ pub(crate) fn try_changed_paths(worktree: &Path) -> Result<Vec<String>, String>changed_paths_with(|args| run(worktree, None, args))}-/// The status [`Checkout::is_clean`] runs, split out so its arguments are-/// testable. `--untracked-files=normal` shows a new directory as one `?? dir/`-/// line instead of walking every file a child left in it (`node_modules`,-/// build output), and still overrides a user's `status.showUntrackedFiles=no`,-/// under which new files would read as clean and be deleted. The user's-/// global excludes file is emptied too: what it hides is still the child's.+/// What an ignored build directory holds, which decides what inside it is+/// work. Either may go with its checkout: rebuilt or reinstalled by the next+/// build, and never what a person wrote. Kept short on purpose: an ignored+/// file anywhere else (a `.env`, local config, notes) is the child's work,+/// since removal would delete it.+#[cfg(feature = "cli")]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum BuildKind {+ /// Dependencies or a tool's cache ([`DEPENDENCY_DIRS`]). Packages ship+ /// certificates (pip's vendored `cacert.pem`), key fixtures and+ /// `.env.example` files, so a secret-like name there means nothing; only+ /// a nested repository is work, as a clone a person made in it.+ Dependency,+ /// What a build writes for the project ([`OUTPUT_DIRS`]), where a person+ /// may also have dropped a `.env` or a key: those are work too.+ Output,+}++#[cfg(feature = "cli")]+const DEPENDENCY_DIRS: [&str; 5] = ["node_modules", ".venv", "target", "__pycache__", ".gradle"];++#[cfg(feature = "cli")]+const OUTPUT_DIRS: [&str; 3] = ["build", "dist", ".next"];++/// Extensions of ignored files that are build output wherever they are.+#[cfg(feature = "cli")]+const BUILD_OUTPUT_EXTS: [&str; 3] = ["o", "pyc", "class"];++#[cfg(feature = "cli")]+impl BuildKind {+ /// The kind of a directory named `name`, if it is a build directory.+ fn of(name: &str) -> Option<Self> {+ match name {+ n if DEPENDENCY_DIRS.contains(&n) => Some(Self::Dependency),+ n if OUTPUT_DIRS.contains(&n) => Some(Self::Output),+ _ => None,+ }+ }++ /// Whether a file named `name` somewhere inside such a directory is work.+ /// `top` says it sits directly in the build folder itself, where no+ /// package ever puts a file (they all live in a folder of their own), so+ /// a secret there (`node_modules/.env`) is one a person dropped even in a+ /// dependency tree.+ fn holds_work(self, name: &str, top: bool) -> bool {+ name == ".git" || ((self == Self::Output || top) && looks_like_secret(name))+ }+}++/// How [`work_with`] treats an ignored path that is build output.+#[cfg(feature = "cli")]+#[derive(Debug, PartialEq, Eq)]+enum BuildOutput {+ /// A build directory, looked inside (see [`work_inside`]).+ Dir(BuildKind),+ /// A file that is build output as it is.+ File,+}++/// The ignore rule that matched a path, as `check-ignore -v` reports it.+#[cfg(feature = "cli")]+#[derive(Debug)]+struct IgnoreRule {+ /// The file the rule is in.+ source: String,+ pattern: String,+ /// Whether `source` is a `.gitignore` in HEAD, one the child did not+ /// write unseen (see [`named_folder`]).+ committed: bool,+}++/// Whether the ignored `path` (as status names it, `/`-separated, a+/// directory with a trailing `/`) is build output, given the `rule` that+/// matched it (see [`named_folder`]), when known.+///+/// A directory is so by its own name, and a file by one of+/// [`BUILD_OUTPUT_EXTS`], whatever the rule. Otherwise an ancestor named+/// like a build folder counts only when the rule names that folder: with+/// `dist/*` git lists each built entry of `dist/` apart, so `dist/app.js` is+/// build output and `dist/assets/` is walked as `dist/` would be (see+/// [`work_inside`]), while a `*.local` rule says nothing of the tracked+/// source folder `tools/build/` its `my.local` sits in, so that file is+/// work. A file still is when [`BuildKind::holds_work`] says so, so+/// `dist/.env` is work.+#[cfg(feature = "cli")]+fn build_output(path: &str, rule: Option<&IgnoreRule>) -> Option<BuildOutput> {+ let trimmed = path.trim_end_matches('/');+ let (parent, last) = trimmed.rsplit_once('/').unwrap_or(("", trimmed));+ let dir = path.ends_with('/');+ if let (true, Some(kind)) = (dir, BuildKind::of(last)) {+ return Some(BuildOutput::Dir(kind));+ }+ if !dir && last.rsplit_once('.').is_some_and(|(_, ext)| BUILD_OUTPUT_EXTS.contains(&ext)) {+ return Some(BuildOutput::File);+ }+ let rule = rule?;+ let name = named_folder(&rule.source, &rule.pattern, rule.committed)?;+ let kind = BuildKind::of(name)?;+ // How far up the folder the rule names is; 0 is the path's own parent.+ // The nearest ancestor so named is taken: `build/` matches at any depth,+ // and that is the folder it hid.+ let depth = parent.rsplit('/').position(|part| part == name)?;+ if dir {+ return Some(BuildOutput::Dir(kind));+ }+ (!kind.holds_work(last, depth == 0)).then_some(BuildOutput::File)+}++/// The folder an ignore rule names, as `check-ignore -v` reports it: the+/// rule's `pattern` and the `source` file it is in. That is the last folder+/// in the pattern's directory part that is not a bare `*` or `**` (`dist`+/// for `dist/*`, `/dist/**`, `dist/`, `**/dist/*` and `dist/*/`); a+/// pattern's last part is the entry itself unless it ends in `/`. A rule+/// with no leading or inner `/` matches at any depth, so `build/` names a+/// tracked `tools/build/` too: its ignored files are build output then,+/// though a secret there is still work. A pattern with no directory part+/// (`*.local`) names no folder, except one that matches everything (`*`)+/// in a nested `.gitignore`, which names the folder that file sits in:+/// `python -m venv` writes such a file into `.venv/`. A negated pattern+/// never ignored anything.+///+/// Only a rule someone could have reviewed names anything, since the child+/// can write a rule to exempt its own files. So `.git/info/exclude`, the one+/// source besides `.gitignore` files the clean check reads (see+/// [`in_git_dir`]), names nothing, and a `.gitignore` that is not+/// `committed` (in HEAD) names only a venv's own: a `*` directly in a+/// `.venv/`, which `python -m venv` writes there and no one commits. No tool+/// writes such a file into another dependency folder (`target/`), so there+/// it is one the child wrote to exempt its files.+#[cfg(feature = "cli")]+fn named_folder<'a>(source: &'a str, pattern: &'a str, committed: bool) -> Option<&'a str> {+ let wild = |part: &str| matches!(part, "*" | "**");+ if pattern.starts_with('!') || in_git_dir(source) {+ return None;+ }+ let mut parts: Vec<&str> = pattern.trim_matches('/').split('/').collect();+ let last = match pattern.ends_with('/') {+ true => None,+ false => parts.pop(),+ };+ let bare = parts.iter().all(|part| part.is_empty());+ // A nested `.gitignore` of `*` names the folder it sits in.+ let own = || match (last, source.rsplit_once('/')) {+ (Some(last), Some((base, ".gitignore"))) if bare && wild(last) => base.rsplit('/').next(),+ _ => None,+ };+ if !committed {+ return own().filter(|name| *name == ".venv");+ }+ if last.is_some() && bare {+ return own();+ }+ parts.into_iter().rev().find(|part| !part.is_empty() && !wild(part))+}++/// Whether a rule's `source` is in the checkout's git dir rather than its+/// work tree, as `.git/info/exclude` is: git names it by its absolute path+/// (`GIT_DIR` is absolute), while a `.gitignore` is named relative to the+/// top. A relative `.git/...` is caught too, should git ever name it so.+#[cfg(feature = "cli")]+fn in_git_dir(source: &str) -> bool {+ Path::new(source).is_absolute() || source.split('/').next() == Some(".git")+}++/// Whether a file named `name`, found inside ignored build output, looks+/// like a secret or local config a person put there rather than a build+/// wrote: `.env` and its variants (`.env.local`), a key or certificate+/// (`*.pem`, `*.key`), a package registry token file (`.npmrc`, `.pypirc`),+/// or a credentials file (`credentials`, `credentials.json`). Kept small on+/// purpose: every match keeps a checkout. `credentials.*` is not matched+/// whole, since SDKs ship `credentials.js`. A name with an example part+/// (`.env.example`, `.env.sample`, `key.pem.template`) is a+/// placeholder shipped to be copied, not a secret.#[cfg(feature = "cli")]-fn clean_with(git: impl Fn(&[&str]) -> Result<String, String>) -> Result<bool, String> {+fn looks_like_secret(name: &str) -> bool {+ let name = name.to_ascii_lowercase();+ let example = name.split('.').any(|part| ["example", "sample", "template"].contains(&part));+ !example+ && (name.starts_with(".env")+ || name.ends_with(".pem")+ || name.ends_with(".key")+ || [".npmrc", ".pypirc", "credentials", "credentials.json"].contains(&name.as_str()))+}++/// How many entries [`work_inside`] reads before it gives up. A dependency+/// tree or a build directory can hold hundreds of thousands.+#[cfg(feature = "cli")]+const INSIDE_LIMIT: usize = 200_000;++/// The first work inside the ignored build directory `dir` of `kind`+/// (relative to `root`, with its trailing `/`), as a path for the user: a+/// nested repository (any `.git`, named by the directory holding it) or a+/// file [`BuildKind::holds_work`] says is work. Status never looks inside an+/// ignored directory, so this is the only place either is seen. Walks the+/// names as the filesystem gives them, never a lossy spelling that would+/// name a directory that does not exist. Never follows a link.+///+/// Past `limit` entries an output folder is `dir` itself: what the walk did+/// not see is not known to be build output. A dependency tree is let go+/// instead: it is regenerable, and a monorepo's often passes the limit, so+/// keeping it would keep every such checkout forever; a nested repository+/// seen before the limit still keeps it. A directory that cannot be read is+/// `dir` for either kind, since that is not a matter of size. A directory+/// gone meanwhile holds nothing.+#[cfg(feature = "cli")]+fn work_inside(root: &Path, dir: &str, kind: BuildKind, limit: usize) -> Option<String> {+ let shown = |path: &Path| {+ let rel = path.strip_prefix(root).unwrap_or(path).to_string_lossy();+ rel.replace(std::path::MAIN_SEPARATOR, "/")+ };+ let start = root.join(dir.trim_end_matches('/'));+ let last = dir.trim_end_matches('/').rsplit('/').next().unwrap_or_default();+ // Only the build folder itself has a top that no package writes into; a+ // folder listed below one (`node_modules/x/`) is a package's own.+ let top_folder = BuildKind::of(last).is_some();+ let mut pending = vec![start.clone()];+ let mut seen = 0;+ while let Some(next) = pending.pop() {+ let top = top_folder && next == start;+ let entries = match std::fs::read_dir(&next) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,+ Err(_) => return Some(dir.to_string()),+ };+ for entry in entries {+ seen += 1;+ if seen > limit {+ return (kind == BuildKind::Output).then(|| dir.to_string());+ }+ let Ok(entry) = entry else { return Some(dir.to_string()) };+ let name = entry.file_name();+ if name == ".git" {+ return Some(format!("{}/", shown(&next)));+ }+ // The entry's own type, not its target's: a link is not walked.+ match entry.file_type() {+ Ok(file) if file.is_dir() => pending.push(entry.path()),+ Ok(_) if kind.holds_work(&name.to_string_lossy(), top) => {+ return Some(shown(&entry.path()));+ }+ Ok(_) => {}+ Err(_) => return Some(dir.to_string()),+ }+ }+ }+ None+}++/// What a checkout holds that its commits do not (see [`Checkout::work`]).+#[cfg(feature = "cli")]+#[derive(Debug, Default, PartialEq, Eq)]+pub(crate) struct Work {+ /// Every path removal would lose.+ pub(crate) paths: Vec<String>,+ /// The ignored build output removal would delete as well, relative to+ /// the checkout: nothing anyone wrote, but the user confirming a forced+ /// removal is told its size.+ pub(crate) build_output: Vec<String>,+ /// Whether a submodule holds work, which is not a path status lists.+ pub(crate) submodule: bool,+}++#[cfg(feature = "cli")]+impl Work {+ /// Whether removal would lose nothing.+ pub(crate) fn is_empty(&self) -> bool {+ !self.submodule && self.paths.is_empty()+ }+}++/// The status [`Checkout::uncommitted`] runs and how it is read, split out so+/// both are testable. `--untracked-files=normal` shows a new directory as one+/// `?? dir/` line instead of walking every file a child left in it, and still+/// overrides a user's `status.showUntrackedFiles=no`, under which new files+/// would read as clean and be deleted. Ignored paths are listed too+/// (`--ignored=matching`, a wholly ignored directory as one line), and any+/// that is not build output counts: an ignore rule says what not to commit,+/// not what may be deleted. That also covers whatever the user's global+/// excludes file (emptied anyway) or the checkout's own `.git/info/exclude`,+/// which the child can write, hides. An ignored build-output directory is+/// looked inside (see [`work_inside`]), relative to the checkout at `root`.+/// `-z`, so a path is never quoted and a rename's old name is its own field.+///+/// Which rule ignored each ignored path is asked once, with the same+/// excludes, for [`build_output`]. `git` is given its args and its stdin.+#[cfg(feature = "cli")]+fn work_with(+ root: &Path,+ git: impl Fn(&[&str], &[u8]) -> Result<String, String>,+ read: impl Fn(&str) -> Option<Vec<u8>>,+) -> Result<Work, String> {let args = ["-c","core.excludesFile=","status","--porcelain",+ "-z","--untracked-files=normal",+ "--ignored=matching","--ignore-submodules=all",];- Ok(git(&args)?.trim().is_empty())+ let out = git(&args, &[])?;+ let mut entries = Vec::new();+ let mut fields = out.split('\0').filter(|f| !f.is_empty());+ while let Some(field) = fields.next() {+ let (code, path) = (field.get(..2).unwrap_or(field), field.get(3..).unwrap_or_default());+ if code.contains(['R', 'C']) {+ fields.next();+ }+ entries.push((field, code, path));+ }+ // Status gives raw bytes and the caller reads them lossily: a name that+ // was not UTF-8 cannot be judged by its spelling, found on disk or asked+ // about by it, so it is work rather than a guess.+ let judged = |code: &str, path: &str| code == "!!" && !path.contains('\u{FFFD}');+ let asked: Vec<&str> = entries+ .iter()+ .filter(|(_, code, path)| judged(code, path) && build_output(path, None).is_none())+ .map(|(_, _, path)| *path)+ .collect();+ let rules = ignore_rules(&asked, &git, read);+ let mut work = Work::default();+ for (field, code, path) in entries {+ let built = match judged(code, path) {+ true => build_output(path, rules.get(path)),+ false => None,+ };+ if let Some(built) = built {+ work.build_output.push(path.to_string());+ if let BuildOutput::Dir(kind) = built {+ work.paths.extend(work_inside(root, path, kind, INSIDE_LIMIT));+ }+ continue;+ }+ // A line git wrote in a shape not read here is still a change.+ work.paths.push(if path.is_empty() { field.to_string() } else { path.to_string() });+ }+ Ok(work)+}++/// The rule that ignores each of `paths`, by path, from one `check-ignore`.+/// `--no-index`, since status lists a file that is tracked yet ignored only+/// when it is not, and with the same excludes [`work_with`] reads (its own+/// `.git/info/exclude`, never the user's global file). Which `.gitignore`+/// sources are committed is decided by [`committed_sources`]. If git fails,+/// nothing is known, so no ancestor exempts anything (and an unknown source+/// counts as written by the child): the fallback keeps rather than deletes.+#[cfg(feature = "cli")]+fn ignore_rules(+ paths: &[&str],+ git: impl Fn(&[&str], &[u8]) -> Result<String, String>,+ read: impl Fn(&str) -> Option<Vec<u8>>,+) -> std::collections::HashMap<String, IgnoreRule> {+ if paths.is_empty() {+ return Default::default();+ }+ let input: Vec<u8> = paths.iter().flat_map(|p| p.bytes().chain([0])).collect();+ let args = ["-c", "core.excludesFile=", "check-ignore", "-v", "--no-index", "--stdin", "-z"];+ let Ok(out) = git(&args, &input) else { return Default::default() };+ // Four fields a path: source, line number, pattern, path.+ let fields: Vec<&str> = out.split('\0').collect();+ let (rules, _) = fields.as_chunks::<4>();+ let mut sources: Vec<&str> =+ rules.iter().map(|[source, ..]| *source).filter(|s| !in_git_dir(s)).collect();+ sources.sort_unstable();+ sources.dedup();+ let committed = committed_sources(&sources, &git, read);+ rules+ .iter()+ .map(|[source, _, pattern, path]| {+ let rule = IgnoreRule {+ source: source.to_string(),+ pattern: pattern.to_string(),+ committed: committed.contains(source),+ };+ (path.to_string(), rule)+ })+ .collect()+}++/// Which of the `.gitignore` `sources` (relative to the top) hold, in the+/// work tree, exactly what HEAD holds: rules someone could have reviewed.+/// Asked of HEAD, never of the index, which the child controls: it can+/// `git add` a rule of its own, or edit a tracked `.gitignore` and hide that+/// from status with `update-index --skip-worktree` or `--assume-unchanged`.+/// So a source counts only if it is a blob in HEAD (one `ls-tree`) whose id+/// matches the file on disk (one `hash-object` of its bytes on stdin).+/// `--no-filters`, since a clean filter is config the child could set; Jan+/// does the one conversion a checkout makes itself, CRLF to LF, because Git+/// for Windows checks a tracked file out as CRLF under its default+/// `core.autocrlf=true` while the blob is LF (git reads a rule line without+/// its CR, so the two spell the same rules). Any other difference counts as+/// edited, which keeps rather than deletes. Any git error, or a file that+/// cannot be read, means it is not committed.+#[cfg(feature = "cli")]+fn committed_sources<'a>(+ sources: &[&'a str],+ git: impl Fn(&[&str], &[u8]) -> Result<String, String>,+ read: impl Fn(&str) -> Option<Vec<u8>>,+) -> std::collections::HashSet<&'a str> {+ if sources.is_empty() {+ return Default::default();+ }+ // Literal, so a folder named with `*` or `[` matches only itself.+ let mut args = vec!["--literal-pathspecs", "ls-tree", "-r", "-z", "HEAD", "--"];+ args.extend(sources);+ let Ok(listed) = git(&args, &[]) else { return Default::default() };+ // Each entry reads `<mode> <type> <id>\t<path>`; only a blob is a file.+ let in_head: Vec<(&str, &str)> = listed+ .split('\0')+ .filter_map(|entry| entry.split_once('\t'))+ .filter_map(|(meta, path)| match meta.split(' ').collect::<Vec<_>>()[..] {+ [_, "blob", id] => Some((path, id)),+ _ => None,+ })+ .collect();+ // Only a path git was asked about, so a reply cannot add a source.+ let in_head: Vec<(&'a str, &str)> = in_head+ .into_iter()+ .filter_map(|(path, id)| Some((*sources.iter().find(|s| **s == path)?, id)))+ .collect();+ if in_head.is_empty() {+ return Default::default();+ }+ in_head+ .into_iter()+ .filter(|(path, id)| {+ let Some(bytes) = read(path) else { return false };+ let args = ["hash-object", "--no-filters", "--stdin"];+ git(&args, &lf_only(&bytes)).is_ok_and(|disk| disk.trim() == *id)+ })+ .map(|(path, _)| path)+ .collect()+}++/// `bytes` with each CRLF as LF: the one conversion a Windows checkout makes+/// to a tracked text file, undone here without running any git filter.+#[cfg(feature = "cli")]+fn lf_only(bytes: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(bytes.len());+ for (i, b) in bytes.iter().enumerate() {+ if !(*b == b'\r' && bytes.get(i + 1) == Some(&b'\n')) {+ out.push(*b);+ }+ }+ out}#[cfg(feature = "cli")]@@ -1840,7 +2305,7 @@ mod tests {assert_eq!(child.commits_on(&head, "--all"), None, "never an option");assert_eq!(child.commits_anywhere(&head), Some(1));std::fs::write(wt.join("c.txt"), "c\n").unwrap();- assert_eq!(child.try_changed_paths(), Ok(vec!["c.txt".to_string()]));+ assert_eq!(child.uncommitted(), Ok(vec!["c.txt".to_string()]));assert_eq!(resolve_commit(&root, "jan/agent/child-1"), None, "not there yet");child.fetch_branch(&root, "jan/agent/child-1", LIMIT).unwrap();@@ -1931,20 +2396,515 @@ mod tests {#[test]fn the_emptiness_check_lists_untracked_files_normally() {let seen = std::cell::RefCell::new(Vec::new());- let answer = |out: Result<&str, &str>| {- clean_with(|args| {+ // No checkout on disk: an ignored directory there holds nothing.+ let root = std::env::temp_dir().join("jan_no_such_checkout");+ // `rules` is what check-ignore answers, as `source\0line\0pattern\0path\0`;+ // ls-tree lists every source it is asked about as a blob in HEAD,+ // unless `untracked`, and hash-object finds each unchanged on disk.+ let untracked = std::cell::Cell::new(false);+ let ask = |out: Result<&str, &str>, rules: Result<&str, &str>| {+ work_with(&root, |args, input| {seen.borrow_mut().extend(args.iter().map(|a| a.to_string()));- out.map(str::to_string).map_err(str::to_string)- })+ let asked = args.iter().skip_while(|a| **a != "--").skip(1);+ if args.contains(&"ls-tree") {+ assert!(args.contains(&"HEAD"), "{args:?}");+ let listed = asked.map(|a| format!("100644 blob id-{a}\t{a}\0")).collect();+ return Ok(if untracked.get() { String::new() } else { listed });+ }+ if args.contains(&"hash-object") {+ // The stand-in file holds its own name.+ assert!(args.contains(&"--stdin"), "{args:?}");+ return Ok(format!("id-{}\n", String::from_utf8_lossy(input)));+ }+ let answer = match args.contains(&"check-ignore") {+ true => {+ assert!(input.ends_with(b"\0"), "{input:?}");+ rules+ }+ false => out,+ };+ answer.map(str::to_string).map_err(str::to_string)+ }, |path| Some(path.as_bytes().to_vec()))+ .map(|work| work.paths)};- assert_eq!(answer(Ok("")), Ok(true));+ let answer = |out| ask(out, Err("not asked"));+ assert_eq!(answer(Ok("")), Ok(vec![]));assert!(seen.borrow().iter().any(|a| a == "--untracked-files=normal"), "{seen:?}");assert!(seen.borrow().iter().any(|a| a == "core.excludesFile="), "{seen:?}");+ assert!(seen.borrow().iter().any(|a| a == "--ignored=matching"), "{seen:?}");assert!(!seen.borrow().iter().any(|a| a == "--untracked-files=all"), "{seen:?}");- assert_eq!(answer(Ok("?? node_modules/")), Ok(false));+ assert_eq!(answer(Ok("?? node_modules/\0")), Ok(vec!["node_modules/".to_string()]));+ // A rename's second field is its old name, never a path of its own.+ assert_eq!(answer(Ok("R b.txt\0a.txt\0")), Ok(vec!["b.txt".to_string()]));+ // Ignored build output is not work; any other ignored file is.+ let ignored = "!! target/\0!! web/node_modules/\0!! src/x.o\0!! .env\0!! conf/\0";+ assert_eq!(answer(Ok(ignored)), Ok(vec![".env".to_string(), "conf/".to_string()]));+ // A path below a build folder is build output by it only when the+ // rule that ignored it names that folder, and a file is not when it+ // looks like a secret.+ let below = "!! dist/a.txt\0!! web/dist/js/b.js\0!! dist/.env\0!! dist/assets/\0\+ !! tools/build/my.local\0!! dist/x.local\0";+ let rules = ".gitignore\x001\0dist/*\0dist/a.txt\0\+ web/.gitignore\x002\0/dist/**\0web/dist/js/b.js\0\+ .gitignore\x001\0dist/*\0dist/.env\0\+ .gitignore\x001\0dist/*\0dist/assets/\0\+ .gitignore\x003\0*.local\0tools/build/my.local\0\+ .gitignore\x003\0*.local\0dist/x.local\0";+ let listed = vec![+ "dist/.env".to_string(),+ "tools/build/my.local".to_string(),+ "dist/x.local".to_string(),+ ];+ assert_eq!(ask(Ok(below), Ok(rules)), Ok(listed));+ assert!(seen.borrow().iter().any(|a| a == "--no-index"), "{seen:?}");+ assert!(seen.borrow().iter().any(|a| a == "--literal-pathspecs"), "{seen:?}");+ // A `.gitignore` the child wrote and never committed names nothing.+ untracked.set(true);+ let listed = vec!["dist/a.txt".to_string()];+ let rules = ".gitignore\x001\0dist/*\0dist/a.txt\0";+ assert_eq!(ask(Ok("!! dist/a.txt\0"), Ok(rules)), Ok(listed));+ untracked.set(false);+ // When git cannot say which rule it was, no ancestor exempts anything.+ let listed = vec!["dist/a.txt".to_string(), "dist/assets/".to_string()];+ assert_eq!(ask(Ok("!! dist/a.txt\0!! dist/assets/\0"), Err("broken")), Ok(listed));+ // A name git gave as bytes that are not UTF-8 is not judged by its+ // lossy spelling: it is work.+ let lossy = "!! dist/a\u{FFFD}.js\0!! x\u{FFFD}.o\0";+ let listed = vec!["dist/a\u{FFFD}.js".to_string(), "x\u{FFFD}.o".to_string()];+ assert_eq!(answer(Ok(lossy)), Ok(listed));assert!(answer(Err("broken")).is_err());}+ /// A file only an ignore rule hides (a `.env`, local config) is work, as+ /// is one hidden by the checkout's own `.git/info/exclude`, which a child+ /// can write; ignored build output is not, so it never keeps a checkout.+ #[test]+ fn the_clean_check_sees_ignored_files_that_are_not_build_output() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("ignored");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/ignored-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), "ignored/\ntarget/\n.env\n").unwrap();+ run(&wt, None, &["commit", "-qam", "ignore", "--no-gpg-sign"]).unwrap();+ assert_eq!(child.is_clean(), Ok(true));++ std::fs::create_dir_all(wt.join("target/debug")).unwrap();+ std::fs::write(wt.join("target/debug/app"), "x").unwrap();+ assert_eq!(child.is_clean(), Ok(true), "build output is not work");++ std::fs::write(wt.join(".env"), "KEY=1\n").unwrap();+ assert_eq!(child.is_clean(), Ok(false), "an ignored .env is");+ assert_eq!(child.uncommitted(), Ok(vec![".env".to_string()]));+ std::fs::remove_file(wt.join(".env")).unwrap();++ std::fs::write(wt.join(".git/info/exclude"), "secret.txt\n").unwrap();+ std::fs::write(wt.join("secret.txt"), "s\n").unwrap();+ assert_eq!(child.is_clean(), Ok(false), "the checkout's own excludes hide nothing");+ assert_eq!(child.uncommitted(), Ok(vec!["secret.txt".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Status names a wholly ignored directory in one line, so what is inside+ /// an ignored build-output directory is looked at: a secret-like file or+ /// a nested repository there is work. A folder listed apart below one, by+ /// a rule naming it (`dist/*`), is walked the same way.+ #[test]+ fn work_inside_ignored_build_output_is_seen() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("inside");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/inside-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), "build/\nnode_modules/\ndist/*\n").unwrap();+ run(&wt, None, &["commit", "-qam", "ignore", "--no-gpg-sign"]).unwrap();+ std::fs::create_dir_all(wt.join("build/out")).unwrap();+ std::fs::write(wt.join("build/out/app.js"), "x").unwrap();+ assert_eq!(child.is_clean(), Ok(true), "plain build output is not work");++ std::fs::write(wt.join("build/out/.env"), "KEY=1\n").unwrap();+ assert_eq!(child.is_clean(), Ok(false), "a .env inside ignored build/ is");+ assert_eq!(child.uncommitted(), Ok(vec!["build/out/.env".to_string()]));+ std::fs::remove_file(wt.join("build/out/.env")).unwrap();++ std::fs::create_dir_all(wt.join("node_modules/x/.git")).unwrap();+ assert_eq!(child.is_clean(), Ok(false), "a nested repository there is");+ assert_eq!(child.uncommitted(), Ok(vec!["node_modules/x/".to_string()]));+ std::fs::remove_dir_all(wt.join("node_modules")).unwrap();++ // `dist/*` lists each entry of `dist/` apart, and names `dist/`, so+ // `dist/notes/` is walked as output: only a secret in it is work.+ std::fs::create_dir_all(wt.join("dist/notes")).unwrap();+ std::fs::write(wt.join("dist/notes/todo.md"), "x\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![]));+ std::fs::write(wt.join("dist/notes/id.key"), "x\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["dist/notes/id.key".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A dependency tree is regenerable and ships certificates, key fixtures+ /// and example env files: only a nested repository in one is work. An+ /// output folder is still searched for secrets, but an example file is+ /// not one.+ #[test]+ fn dependency_trees_hold_only_nested_repositories_as_work() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("deps");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/deps-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), ".venv/\nnode_modules/\nbuild/\n").unwrap();+ run(&wt, None, &["commit", "-qam", "ignore", "--no-gpg-sign"]).unwrap();+ let certifi = wt.join(".venv/lib/python3.12/site-packages/pip/_vendor/certifi");+ std::fs::create_dir_all(&certifi).unwrap();+ std::fs::write(certifi.join("cacert.pem"), "x").unwrap();+ std::fs::create_dir_all(wt.join("node_modules/x/test")).unwrap();+ std::fs::write(wt.join("node_modules/x/test/fixture.key"), "x").unwrap();+ std::fs::write(wt.join("node_modules/x/.env"), "x").unwrap();+ std::fs::create_dir_all(wt.join("build")).unwrap();+ std::fs::write(wt.join("build/.env.example"), "KEY=\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![]), "none of these is work");++ std::fs::write(wt.join("build/.env"), "KEY=1\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["build/.env".to_string()]));+ std::fs::remove_file(wt.join("build/.env")).unwrap();++ // No package puts a file in the tree's top folder: a secret there+ // is one a person dropped.+ std::fs::write(wt.join("node_modules/.env"), "KEY=1\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["node_modules/.env".to_string()]));+ std::fs::remove_file(wt.join("node_modules/.env")).unwrap();++ std::fs::create_dir_all(wt.join("node_modules/x/.git")).unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["node_modules/x/".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// `python -m venv` writes a `.gitignore` of `*` into the venv, so with+ /// no rule of the project's own git lists each entry of `.venv/` apart.+ /// That rule names `.venv/`, so its folders are walked as a dependency+ /// tree; a secret listed directly in it is still work.+ #[test]+ fn a_venv_ignored_by_its_own_gitignore_is_a_dependency_tree() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("venv");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/venv-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ let certifi = wt.join(".venv/lib/python3.12/site-packages/pip/_vendor/certifi");+ std::fs::create_dir_all(&certifi).unwrap();+ std::fs::write(certifi.join("cacert.pem"), "x").unwrap();+ std::fs::create_dir_all(wt.join(".venv/bin")).unwrap();+ std::fs::write(wt.join(".venv/bin/python"), "x").unwrap();+ std::fs::write(wt.join(".venv/pyvenv.cfg"), "x").unwrap();+ std::fs::write(wt.join(".venv/.gitignore"), "*\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![]), "a venv is not work");+ std::fs::write(wt.join(".venv/.env"), "KEY=1\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![".venv/.env".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The child writes `.git/info/exclude` and no one reviews it, so a rule+ /// there exempts nothing, even one naming a build folder.+ #[test]+ fn a_rule_in_the_checkouts_own_exclude_file_exempts_nothing() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("exclude");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/exclude-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".git/info/exclude"), "sub/build/*\n").unwrap();+ std::fs::create_dir_all(wt.join("sub/build")).unwrap();+ std::fs::write(wt.join("sub/build/todo.md"), "mine\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["sub/build/todo.md".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A nested `.gitignore` the child wrote and never committed names no+ /// folder, except the `*` one `python -m venv` writes into `.venv/` (see+ /// [`a_venv_ignored_by_its_own_gitignore_is_a_dependency_tree`]). A+ /// committed one still does.+ #[test]+ fn an_untracked_nested_gitignore_names_no_folder() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("nested");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/nested-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::create_dir_all(wt.join("web")).unwrap();+ std::fs::write(wt.join("web/.gitignore"), "**/build/\ndist/*\n").unwrap();+ run(&wt, None, &["add", "-A"]).unwrap();+ run(&wt, None, &["commit", "-qm", "web", "--no-gpg-sign"]).unwrap();+ std::fs::create_dir_all(wt.join("web/build/out")).unwrap();+ std::fs::write(wt.join("web/build/out/app.js"), "x").unwrap();+ std::fs::create_dir_all(wt.join("web/dist")).unwrap();+ std::fs::write(wt.join("web/dist/app.js"), "x").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![]), "a committed rule still exempts");++ std::fs::create_dir_all(wt.join("src/build")).unwrap();+ std::fs::write(wt.join("src/build/.gitignore"), "*\n").unwrap();+ std::fs::write(wt.join("src/build/mine.md"), "mine\n").unwrap();+ let both = vec!["src/build/.gitignore".to_string(), "src/build/mine.md".to_string()];+ assert_eq!(child.uncommitted(), Ok(both));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The child controls the index, so a tracked `.gitignore` it edited and+ /// hid from status with `update-index --skip-worktree` is not committed:+ /// what HEAD holds decides, and its new rules exempt nothing.+ #[test]+ fn a_gitignore_edit_hidden_from_the_index_exempts_nothing() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("skipwt");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/skipwt-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), "ignored/\nnotes/*\ndist/*\n").unwrap();+ run(&wt, None, &["update-index", "--skip-worktree", ".gitignore"]).unwrap();+ std::fs::create_dir_all(wt.join("notes")).unwrap();+ std::fs::write(wt.join("notes/x.md"), "mine\n").unwrap();+ // `dist/*` would name a build folder, had a reviewed file said it.+ std::fs::create_dir_all(wt.join("dist")).unwrap();+ std::fs::write(wt.join("dist/plan.md"), "mine\n").unwrap();+ let both = vec!["dist/plan.md".to_string(), "notes/x.md".to_string()];+ assert_eq!(child.uncommitted(), Ok(both));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A tracked source folder that happens to be named like a build folder+ /// exempts nothing: an ignored file in it is hand-written unless the rule+ /// that ignored it names that folder.+ #[test]+ fn ignored_files_in_a_source_folder_named_build_are_work() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("srcbuild");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/srcbuild-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), "*.local\n").unwrap();+ std::fs::create_dir_all(wt.join("tools/build")).unwrap();+ std::fs::write(wt.join("tools/build/run.sh"), "x").unwrap();+ run(&wt, None, &["add", "-A"]).unwrap();+ run(&wt, None, &["commit", "-qm", "tools", "--no-gpg-sign"]).unwrap();+ std::fs::write(wt.join("tools/build/my.local"), "mine\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["tools/build/my.local".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Over the walk's limit a dependency tree is let go, since it is+ /// regenerable, unless a nested repository was already seen; an output+ /// folder over it is kept, since what was not seen may be a secret.+ #[test]+ fn the_walk_limit_lets_a_dependency_tree_go_but_not_an_output_folder() {+ let root = tempfile::tempdir().unwrap();+ for i in 0..5 {+ std::fs::create_dir_all(root.path().join(format!("node_modules/p{i}"))).unwrap();+ std::fs::create_dir_all(root.path().join(format!("dist/p{i}"))).unwrap();+ }+ let deps = BuildKind::Dependency;+ assert_eq!(work_inside(root.path(), "node_modules/", deps, 3), None);+ assert_eq!(+ work_inside(root.path(), "dist/", BuildKind::Output, 3),+ Some("dist/".to_string())+ );+ assert_eq!(work_inside(root.path(), "dist/", BuildKind::Output, 100), None);+ std::fs::create_dir_all(root.path().join("node_modules/.git")).unwrap();+ let found = work_inside(root.path(), "node_modules/", deps, 100);+ assert_eq!(found, Some("node_modules/".to_string()));+ }++ /// A source is committed only as a HEAD blob the file on disk still+ /// matches, and any git error or odd reply means none is.+ #[test]+ fn a_source_is_committed_only_as_head_holds_it() {+ let sources = [".gitignore", "web/.gitignore", "new/.gitignore"];+ let head = "100644 blob a\t.gitignore\x00100644 blob b\tweb/.gitignore\0\+ 040000 tree c\tnew/.gitignore\x00100644 blob d\tother\0";+ let ask = |tree: Result<&str, &str>, disk: Result<&str, &str>| {+ let mut got: Vec<&str> = committed_sources(&sources, |args, input| {+ if args.contains(&"hash-object") {+ // The stand-in file holds its own name; `disk` says which+ // ids git would give the files, in order.+ let name = String::from_utf8_lossy(input).into_owned();+ let at = sources.iter().position(|s| *s == name).unwrap();+ return disk.map(|d| d.lines().nth(at).unwrap_or("").to_string()).map_err(str::to_string);+ }+ tree.map(str::to_string).map_err(str::to_string)+ }, |path| Some(path.as_bytes().to_vec()))+ .into_iter()+ .collect();+ got.sort_unstable();+ got+ };+ assert_eq!(ask(Ok(head), Ok("a\nb\n")), vec![".gitignore", "web/.gitignore"]);+ // An edit hidden from the index still changes what is on disk.+ assert_eq!(ask(Ok(head), Ok("a\nx\n")), vec![".gitignore"]);+ // Each file is judged on its own: a missing id is one that differs.+ assert_eq!(ask(Ok(head), Ok("a\n")), vec![".gitignore"]);+ assert_eq!(ask(Ok(head), Err("broken")), Vec::<&str>::new());+ assert_eq!(ask(Err("broken"), Ok("a\nb\n")), Vec::<&str>::new());+ }++ /// CRLF is the only difference a checkout may make to a tracked rule file.+ #[test]+ fn crlf_is_undone_and_nothing_else() {+ assert_eq!(lf_only(b"dist/*\r\n!dist/.gitkeep\r\n"), b"dist/*\n!dist/.gitkeep\n");+ assert_eq!(lf_only(b"a\rb\r\r\n"), b"a\rb\r\n");+ assert_eq!(lf_only(b"a\n"), b"a\n");+ }++ /// Git for Windows checks a tracked `.gitignore` out as CRLF under its+ /// default `core.autocrlf=true`: it is still the rules HEAD holds, so a+ /// built file under `dist/*` stays build output, while an edit does not.+ #[test]+ fn a_rule_file_a_checkout_converted_to_crlf_is_still_committed() {+ let Some(root) = init_repo() else { return };+ std::fs::write(root.join(".gitignore"), "dist/*\n!dist/.gitkeep\n").unwrap();+ std::fs::create_dir_all(root.join("dist")).unwrap();+ std::fs::write(root.join("dist/.gitkeep"), "").unwrap();+ run(&root, None, &["add", "-A"]).unwrap();+ run(&root, None, &["commit", "-qm", "ignore", "--no-gpg-sign"]).unwrap();+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("crlf");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = with_global_config("[core]\n\tautocrlf = true\n", || {+ clone_shared(&root, &wt, "jan/agent/crlf-1", &head).unwrap()+ });+ let wt = dunce::canonicalize(&wt).unwrap();+ let on_disk = std::fs::read(wt.join(".gitignore")).unwrap();+ assert!(on_disk.windows(2).any(|w| w == b"\r\n"), "the checkout converted it");+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join("dist/app.js"), "x").unwrap();+ // The user's own config reaches every git Jan runs, so status reads+ // the converted files as the clean checkout they are.+ let config = "[core]\n\tautocrlf = true\n";+ let work = || with_global_config(config, || child.uncommitted());+ assert_eq!(work(), Ok(vec![]), "a built file is not work");+ // A rule the child added is an edit, converted line endings or not.+ let mut edited = on_disk.clone();+ edited.extend_from_slice(b"extra\r\n");+ std::fs::write(wt.join(".gitignore"), edited).unwrap();+ assert_eq!(work(), Ok(vec![".gitignore".to_string(), "dist/app.js".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Which folder each rule shape names, so a file below a folder named+ /// like a build folder is exempt only by a rule about that folder.+ #[test]+ fn the_folder_a_rule_names() {+ for pattern in ["dist/*", "/dist/**", "dist/", "**/dist/*", "dist/*/", "web/dist/**"] {+ assert_eq!(named_folder(".gitignore", pattern, true), Some("dist"), "{pattern}");+ assert_eq!(named_folder(".gitignore", pattern, false), None, "{pattern}");+ }+ for pattern in ["*.local", "*", "!dist/*", "/notes.txt", "*/"] {+ assert_eq!(named_folder(".gitignore", pattern, true), None, "{pattern}");+ }+ assert_eq!(named_folder(".venv/.gitignore", "*", true), Some(".venv"));+ assert_eq!(named_folder(".venv/.gitignore", "*", false), Some(".venv"));+ assert_eq!(named_folder("src/build/.gitignore", "*", true), Some("build"));+ assert_eq!(named_folder("src/build/.gitignore", "*", false), None);+ // Only a venv is let write its own: no tool commits a `*` elsewhere.+ assert_eq!(named_folder("src/target/.gitignore", "*", false), None);+ assert_eq!(named_folder("web/node_modules/.gitignore", "*", false), None);+ assert_eq!(named_folder("web/.venv/.gitignore", "*", false), Some(".venv"));+ assert_eq!(named_folder("tools/build/.gitignore", "*.local", true), None);+ let exclude = std::env::temp_dir().join("x/.git/info/exclude");+ for pattern in ["*", "build/", "sub/build/*"] {+ assert_eq!(named_folder(&exclude.to_string_lossy(), pattern, true), None);+ assert_eq!(named_folder(".git/info/exclude", pattern, true), None);+ }+ }++ #[test]+ fn example_files_do_not_look_like_secrets() {+ for name in [".env", ".env.local", "server.pem", "id.key", ".npmrc"] {+ assert!(looks_like_secret(name), "{name}");+ }+ for name in [".env.example", ".env.sample", ".env.template", "key.pem.example"] {+ assert!(!looks_like_secret(name), "{name}");+ }+ }++ /// With `dist/*` and a kept `.gitkeep`, git lists each built file on its+ /// own: one is build output by its `dist/` ancestor, but a secret there+ /// is still work.+ #[test]+ fn files_listed_below_an_output_folder_are_build_output_unless_secret() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("listed");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/listed-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), "dist/*\n!dist/.gitkeep\n").unwrap();+ std::fs::create_dir_all(wt.join("dist")).unwrap();+ std::fs::write(wt.join("dist/.gitkeep"), "").unwrap();+ run(&wt, None, &["add", "-A"]).unwrap();+ run(&wt, None, &["commit", "-qm", "ignore", "--no-gpg-sign"]).unwrap();+ std::fs::write(wt.join("dist/app.js"), "x").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![]), "a built file is not work");+ // The build's own subfolder is listed as one line by the same rule.+ std::fs::create_dir_all(wt.join("dist/assets")).unwrap();+ std::fs::write(wt.join("dist/assets/index.css"), "x").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec![]), "a built subfolder is not work");+ std::fs::write(wt.join("dist/.env"), "KEY=1\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["dist/.env".to_string()]));+ std::fs::remove_file(wt.join("dist/.env")).unwrap();+ std::fs::write(wt.join("dist/assets/.env"), "KEY=1\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["dist/assets/.env".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A directory whose name is not UTF-8 is walked by its real name, so a+ /// secret inside it is still seen.+ #[cfg(unix)]+ #[test]+ fn a_directory_named_in_raw_bytes_is_walked() {+ use std::os::unix::ffi::OsStrExt;+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ let wt = root.with_extension("raw");+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/raw-1", &head).unwrap();+ let wt = dunce::canonicalize(&wt).unwrap();+ let child = Checkout::open(&wt, &objects).unwrap();+ std::fs::write(wt.join(".gitignore"), "build/\n").unwrap();+ run(&wt, None, &["commit", "-qam", "ignore", "--no-gpg-sign"]).unwrap();+ let raw = wt.join("build").join(std::ffi::OsStr::from_bytes(b"bad\xff"));+ std::fs::create_dir_all(&raw).unwrap();+ std::fs::write(raw.join(".env"), "KEY=1\n").unwrap();+ assert_eq!(child.uncommitted(), Ok(vec!["build/bad\u{FFFD}/.env".to_string()]));+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }+/// A new directory full of files is work, even for a user who hides/// untracked files from `git status`.#[test]diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex 11202468f..265b85dd4 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -73,6 +73,11 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # under each project's agent.toml# # thread_retention_days / max_threads.# # Off by default: nothing is deleted+# subagent_build_cache_max_gb = 20 # clear a project's shared subagent+# # cargo-target at session end once it+# # is larger than this (default 20; 0+# # never). A project's agent.toml+# # [agent] key of the same name wins## [tui]# animations = false # hold the TUI still: no shimmer and@@ -195,6 +200,12 @@ struct GlobalConfigToml {/// something they turn on, not something they find out about.#[serde(default, skip_serializing_if = "Option::is_none")]prune_threads: Option<bool>,+ /// The user-wide default for how large, in GB, a project's shared+ /// subagent build directory may grow before a session end clears it.+ /// `None` = the default, 20; `0` never clears. A project's+ /// `[agent].subagent_build_cache_max_gb` wins.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ subagent_build_cache_max_gb: Option<u64>,/// Host env-var names (exact or `*`-glob) the sandboxed `bash` may inherit/// beyond the fixed base allowlist. Empty by default, so the shell env is/// unchanged. Merged with a project's `[tools].env_passthrough`; a secret-@@ -551,6 +562,13 @@ pub(crate) fn worktree_setting() -> Option<bool> {load_raw().ok().and_then(|config| config.worktree)}+/// `subagent_build_cache_max_gb` in `~/.jan/config.toml`; `None` when unset+/// or unreadable, so the project's setting or the default decides.+#[cfg(feature = "cli")]+pub(crate) fn subagent_build_cache_max_gb_setting() -> Option<u64> {+ load_raw().ok().and_then(|config| config.subagent_build_cache_max_gb)+}+/// Whether saved threads are pruned at TUI start (`prune_threads` in/// `~/.jan/config.toml`), defaulting to off. An unreadable config also reads/// as off: the failure direction of a setting that deletes data is to keep it.diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex f491fd4b8..204bb9162 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -136,6 +136,11 @@ pub(crate) struct OrchestrationArgs {/// (`[agent].max_parallel_subagents` in agent.toml, default 10). Snapshot/// taken at run start: a mid-run config edit affects the *next* run only.pub max_parallel_subagents: u32,+ /// Whether a subagent that can write and asked for no `workspace` gets a+ /// worktree of its own (`--subagent-worktrees`, `[agent].subagent_worktrees`).+ /// Off: it works in the parent's checkout. CLI-only in effect, like the+ /// worktrees themselves.+ pub subagent_worktrees: bool,/// Auto-allow every tool call that would otherwise prompt (built-in/// reads/writes/exec and MCP). The CLI default, since the OS jail in the/// tools plugin confines exec regardless; `--safe` turns it off. Desktop@@ -201,6 +206,13 @@ pub(crate) struct OrchestrationArgs {/// `bg_shells`, which reports the command's end as a turn of its own./// Never inherited by a child run, which the user's message is not for.pub shell_detach: Option<tokio::sync::watch::Receiver<bool>>,+ /// The session's shell directory, so a `cd` holds across turns (see+ /// `ToolContext::shell_cwd`). `None` carries nothing: every call starts in+ /// the root, which is right for a caller that cannot keep one across its+ /// turns (the API server starts a fresh run per request). A child run gets+ /// a fresh one of its own: it works in its own workspace, not wherever the+ /// parent last `cd`ed.+ pub shell_cwd: Option<tauri_plugin_agent_tools::tools::ShellCwd>,/// When this run compacts ahead of dispatching: the route's context window,/// the share of it a prompt may fill, and any explicitly configured reserve.///@@ -896,6 +908,8 @@ struct CompositeToolInvoker {parent_link: Option<crate::core::agent::subagent::ParentLink>,/// See [`OrchestrationArgs::shell_detach`].shell_detach: Option<tokio::sync::watch::Receiver<bool>>,+ /// See [`OrchestrationArgs::shell_cwd`].+ shell_cwd: Option<tauri_plugin_agent_tools::tools::ShellCwd>,/// The session's memory snapshot, for a mid-run `# Memory Changes`/// block. `None` where the run's tail carries none (a child run, a/// host-owned prompt, no snapshot).@@ -1243,10 +1257,16 @@ fn format_dispatched_plan(d: &crate::core::agent::subagent::DispatchedPlan) -> SNone => " Each answer rides the note that tells you it finished.",};let head = if d.phase_count > 1 {+ let reuses: String = d+ .later_workspaces+ .iter()+ .map(|(worker, owner)| format!("\n - {worker} will work in {owner}'s workspace"))+ .collect();format!("Dispatched a {}-phase plan of {} subagents. Phase 1 is now running:\n{roster}\nLater \phases start automatically as each phase finishes, each receiving the previous \- phase's results; their run ids are reported as they start.",+ phase's results; their run ids are reported as they start, but each can already be \+ messaged or stopped by name.{reuses}",d.phase_count, d.total_subagents)} else {@@ -1352,6 +1372,10 @@ impl CompositeToolInvoker {).with_shell_done_sink(self.shell_done_sink()).with_thread_id(self.shell_owner.as_deref());+ let ctx = match &self.shell_cwd {+ Some(cwd) => ctx.with_shell_cwd(cwd.clone()),+ None => ctx,+ };match &self.shell_detach {Some(signal) => ctx.with_detach_signal(signal.clone()),None => ctx,@@ -1407,6 +1431,31 @@ impl CompositeToolInvoker {)}+ /// The directory the next `shell` call starts in, when a `cd` has moved it+ /// off the project root; `None` for every other tool.+ fn held_shell_cwd(+ &self,+ tool: &tauri_plugin_agent_tools::tools::BuiltinTool,+ ) -> Option<String> {+ if tool.name != tauri_plugin_agent_tools::tools::SHELL_TOOL+ || !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported()+ {+ return None;+ }+ let held = self.shell_cwd.as_ref()?.lock().unwrap().clone()?;+ Some(held.display().to_string())+ }++ /// The refusal for an escalated `name` call whose held shell directory is+ /// no longer one it may start in; see+ /// [`tauri_plugin_agent_tools::tools::handlers::escalated_shell_cwd_refusal`].+ fn escalated_shell_cwd_refusal(&self, name: &str) -> Option<String> {+ let why = tauri_plugin_agent_tools::tools::handlers::escalated_shell_cwd_refusal(+ &self.tool_context(),+ )?;+ Some(format!("ERROR: tool '{name}' escalation refused: {why}."))+ }+/// A tool context whose output streams to the run's event channel as/// [`StreamEvent::ToolOutputDelta`], tagged with the call's `id`.///@@ -1449,6 +1498,11 @@ impl CompositeToolInvoker {// under it: under `--safe` the command would have been asked about// anyway, so one prompt covers both.Escalation::Allow | Escalation::Prompt => {+ // Before the prompt, so the directory it names is the one the+ // command would really start in, not a link swapped in for it.+ if let Some(refusal) = self.escalated_shell_cwd_refusal(name) {+ return refusal;+ }let request_id = next_permission_id();let (tx, rx) = tokio::sync::oneshot::channel();self.permission_requests@@ -1459,7 +1513,10 @@ impl CompositeToolInvoker {request_id: request_id.clone(),tool_name: name.to_string(),capability: "exec outside the sandbox".to_string(),- path: None,+ // Where it runs, once a `cd` has moved the shell, as an+ // ordinary exec prompt shows: the command alone does not+ // say which tree an `rm -rf build` would hit.+ path: self.held_shell_cwd(tool),command: args.get("command").and_then(|v| v.as_str()).map(String::from),diff: None,prompt_kind: "escalate".to_string(),@@ -1483,6 +1540,14 @@ impl CompositeToolInvoker {if !approved {return escalation_denied_msg(name);}+ // The held directory comes along: the model was told every later call+ // starts there, and the prompt named it. No host re-check here after+ // the prompt: the wrapper checks it after its own `cd`, the last+ // moment a link can be swapped in, and refuses and resets as it does+ // for a gone one (see `posix_cwd_script`). Where it lands is held+ // too, checked no differently from a confined call's: never on the+ // host, but by the next call entering it inside its own sandbox, or+ // refusing and resetting to the root.let ctx = self.streaming_tool_context(id).with_sandbox(false);tauri_plugin_agent_tools::tools::handlers::execute_builtin_with_diff(tool, args, &ctx).await@@ -1840,7 +1905,7 @@ impl CompositeToolInvoker {Err(e) => return format!("ERROR: {e}"),};match crate::core::agent::subagent::message_subagent(&ctx.bg, &target, &message) {- Ok(s) => s,+ Ok(s) => s.into_text(),Err(e) => format!("ERROR: {e}"),}}@@ -2157,6 +2222,8 @@ impl CompositeToolInvoker {pub(crate) const DENIED_BY_USER: &str = "denied by user";pub(crate) const DENIED_BY_POLICY: &str = "denied by project policy";pub(crate) const HIDDEN_PATH_REFUSED: &str = "refused: the Jan home";+pub(crate) const TOO_COMPLEX_REFUSED: &str =+ "refused: the command or path is too large or deeply nested";pub(crate) const PLAN_MODE_UNAVAILABLE: &str = "unavailable in plan_mode_read_only";pub(crate) const HOOK_DENIED: &str = "denied: ";@@ -2252,6 +2319,28 @@ impl CompositeToolInvoker {&offered,)}+ // The command may name nothing hidden, so the generic refusal+ // would leave the model retrying it from the same place. Reset+ // as the other escalation refusals do (see+ // `escalated_shell_cwd_refusal`): the project root is always a+ // safe start, and the model is told to re-run from it.+ DenyReason::HiddenShellCwd => {+ let held = self.shell_cwd.as_ref().and_then(|cwd| cwd.lock().unwrap().take());+ let held = held.map_or_else(|| "(unknown)".into(), |d| d.display().to_string());+ format!(+ "ERROR: tool '{name}' escalation {HIDDEN_PATH_REFUSED} (~/.jan) is hidden, \+ and the shell cwd {held} is in it or above it, where an escalated command \+ would start outside the sandbox that masks it. The command was not run. The \+ shell is back in the project root {}: re-run it from there, or `cd` \+ somewhere outside the Jan home first",+ self.project_root.display()+ )+ }+ DenyReason::TooComplex => format!(+ "ERROR: tool '{name}' was {TOO_COMPLEX_REFUSED} to check that it stays out of \+ the Jan home (~/.jan). It was not run. Split it into smaller calls or \+ shorten the path, or write a long script to a file and run that"+ ),}}}@@ -2345,7 +2434,7 @@ impl ToolInvoker for CompositeToolInvoker {git_status: crate::core::agent::git::workspace_status(&self.project_root),..Default::default()};- let mut workspace = workspace_lines(&self.project_root);+ let mut workspace = workspace_lines(&self.project_root, self.shell_cwd.as_ref());if self.workspace.read_only {workspace.push_str("\nThe working directory is read-only for this run.");}@@ -2436,7 +2525,7 @@ impl ToolInvoker for CompositeToolInvoker {on_complete: &OnComplete<'_>,) -> Result<Vec<ToolOutcome>, String> {use tauri_plugin_agent_tools::tools::{- gate::{resolve_decision, Decision, PromptKind},+ gate::{resolve_decision_with_cwd, Decision, PromptKind},handlers::{execute_builtin_with_diff, preview_diff},is_builtin, lookup, Capability, ToolContext,};@@ -2827,7 +2916,7 @@ impl ToolInvoker for CompositeToolInvoker {continue;}let snapshot = { self.grants.lock().unwrap().clone() };- let decision = resolve_decision(+ let decision = resolve_decision_with_cwd(tool,&args,&tauri_plugin_agent_tools::tools::gate::GateContext {@@ -2840,6 +2929,7 @@ impl ToolInvoker for CompositeToolInvoker {write_roots: &self.workspace.write_roots,hidden_root: self.hidden_root.as_deref(),},+ self.held_shell_cwd(tool).as_deref().map(std::path::Path::new),&self.permissions,&snapshot,);@@ -2944,12 +3034,16 @@ impl ToolInvoker for CompositeToolInvoker {// Settled by `escalate` above; labelled for completeness.PromptKind::Escalate => "escalate",};+ // An exec has no path argument; where it runs stands in,+ // once a `cd` has moved the shell off the project root, so+ // the user does not approve a command for the wrong tree.let path = tool.path_args.first().and_then(|k| args.get(*k)).and_then(|v| v.as_str())- .map(String::from);+ .map(String::from)+ .or_else(|| self.held_shell_cwd(tool));let command = matches!(tool.capability, Capability::Exec).then(|| args.get("command").and_then(|v| v.as_str())).flatten()@@ -3113,6 +3207,7 @@ pub(crate) async fn run_server_side_openai_orchestration(project_memory: true,subagents_enabled: false,max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,+ subagent_worktrees: false,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,@@ -3129,6 +3224,7 @@ pub(crate) async fn run_server_side_openai_orchestration(parent_link: None,// Nobody can type into a proxy run.shell_detach: None,+ shell_cwd: None,// Sized inside the run once the model is picked (see// `proxy_budget`): the body may name none, and the choice is the// loop's.@@ -3839,6 +3935,8 @@ async fn orchestrate_inner(project_memory,subagents_enabled,max_parallel_subagents,+ // Read through `args` by the subagent dispatch, which clones them.+ subagent_worktrees: _,auto_approve,run_mode,session_id,@@ -3850,6 +3948,7 @@ async fn orchestrate_inner(// invoker), so this stays a plain destructure of the rest.parent_link: _,shell_detach: _,+ shell_cwd: _,sandbox,allow_escalation,compaction,@@ -4137,6 +4236,14 @@ async fn orchestrate_inner(host_tools,args.parent_link.is_some(),);+ // Every agent run rings the shell doorbell (`shell_done_sink`), and one+ // with a session-owned directory carries it where the shell can (see+ // `bash`), so its shell description says exactly that. Both inputs are+ // fixed for the run, so the array stays byte-identical across its turns.+ tauri_plugin_agent_tools::tools::schema::offer_session_shell(+ &mut openai_tools,+ args.shell_cwd.is_some() && tauri_plugin_agent_tools::tools::proc::shell_cwd_supported(),+ );// Resolved once per run, so the array is byte-identical across its turns.if settings.as_ref().is_some_and(|s| s.escalation.offered()) {tauri_plugin_agent_tools::tools::schema::offer_escalation(&mut openai_tools);@@ -4367,6 +4474,7 @@ async fn orchestrate_inner(// command's end except a park, which holds the message just the// same; so the signal only applies where the session owns shells.shell_detach: args.shell_detach.clone().filter(|_| session_bg_shells.is_some()),+ shell_cwd: args.shell_cwd.clone(),memory_changes,memory_change_budget: args.memory_change_budget.clone(),workspace: RunWorkspace::resolve(child_scope.as_ref(), root),@@ -4738,7 +4846,7 @@ async fn between_turn_harness(let mut harness = crate::core::agent::continuation::HarnessContext::default();if let Some(root) = args.project_root.as_deref() {harness.git_status = crate::core::agent::git::workspace_status(root);- harness.push("Workspace", workspace_lines(root));+ harness.push("Workspace", workspace_lines(root, args.shell_cwd.as_ref()));}if let Some(bg) = &args.subagent_bg {harness.push("Subagents", bg.roster_lines().join("\n"));@@ -5092,13 +5200,20 @@ impl CompactionScope<'_> {}}-/// The `Workspace` section's opening lines: where the run works, and on which-/// branch.-fn workspace_lines(root: &std::path::Path) -> String {+/// The `Workspace` section's opening lines: where the run works, on which+/// branch, and where a `cd` left the shell. A compaction drops the call whose+/// result announced that `cd`, so this is where the model finds it again.+fn workspace_lines(+ root: &std::path::Path,+ shell_cwd: Option<&tauri_plugin_agent_tools::tools::ShellCwd>,+) -> String {let mut workspace = format!("Working directory: {}", root.display());if let Some(branch) = crate::core::agent::git::current_branch(root) {workspace.push_str(&format!("\nBranch: {branch}"));}+ if let Some(dir) = shell_cwd.and_then(|cwd| cwd.lock().unwrap().clone()) {+ workspace.push_str(&format!("\nShell cwd: {} (later bash calls start there)", dir.display()));+ }workspace}@@ -5908,6 +6023,14 @@ async fn run_turn_cycle(// stay plain text, preserving the standard tool protocol. A host// that answered with content parts chose the message itself, so// its parts go out verbatim.+ // A shell result reaches the model without its exit marker when+ // the command printed something; the event above kept the full+ // text, so the UIs still read the code and failure from it.+ let content = if name == tauri_plugin_agent_tools::tools::SHELL_TOOL {+ tauri_plugin_agent_tools::tools::handlers::model_shell_result(&content)+ } else {+ content+ };let wire_content = if let Some(parts) = parts {serde_json::Value::Array(parts)} else if images.is_empty() {@@ -10225,6 +10348,7 @@ mod tests {),parent_link: None,shell_detach: None,+ shell_cwd: None,memory_changes: None,memory_change_budget: None,shell_owner: None,@@ -12706,6 +12830,296 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A `shell` call with `args`, as the model sends it.+ #[cfg(all(feature = "cli", unix))]+ fn shell_call(id: &str, args: serde_json::Value) -> serde_json::Value {+ json!({+ "id": id,+ "type": "function",+ "function": { "name": "shell", "arguments": args.to_string() }+ })+ }++ /// An invoker holding `held` as the shell's directory whose escalation+ /// prompt is approved, and the task answering it, which reports the+ /// prompt's `path`.+ #[cfg(all(feature = "cli", unix))]+ fn held_cwd_escalation(+ root: &std::path::Path,+ held: std::path::PathBuf,+ ) -> (+ CompositeToolInvoker,+ tauri_plugin_agent_tools::tools::ShellCwd,+ tokio::task::JoinHandle<Option<String>>,+ ) {+ let (tx, mut rx) = mpsc::unbounded_channel();+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let mut invoker = build_prompting_invoker(root.to_path_buf(), tx, registry.clone());+ invoker.escalation = Escalation::Prompt;+ let cwd = tauri_plugin_agent_tools::tools::ShellCwd::default();+ *cwd.lock().unwrap() = Some(held);+ invoker.shell_cwd = Some(cwd.clone());+ let responder = tokio::spawn(async move {+ loop {+ match rx.recv().await {+ Some(StreamEvent::PermissionRequest { request_id, path, .. }) => {+ if let Some(tx) = registry.lock().await.remove(&request_id) {+ let _ = tx.send(PermissionDecision::AllowOnce);+ }+ return path;+ }+ Some(_) => continue,+ None => panic!("no prompt was sent"),+ }+ }+ });+ (invoker, cwd, responder)+ }++ /// An escalated command starts where a `cd` left the shell, as the tool+ /// description promises every later call does, and its prompt names that+ /// directory: after `cd pkg`, an approved `rm -rf build` hits `pkg/build`,+ /// and the user sees that it will.+ #[tokio::test]+ #[cfg(all(feature = "cli", unix))]+ async fn escalation_runs_in_and_names_the_held_shell_cwd() {+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported() {+ return;+ }+ let root = unique_project_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let sub = std::fs::canonicalize(root.join("sub")).unwrap();+ let (invoker, cwd, responder) = held_cwd_escalation(&root, sub.clone());+ let escalated = json!({ "command": "pwd -P", "escalate": true, "justification": "x" });+ let out = invoker.invoke(&[shell_call("esc", escalated)]).await.unwrap();+ assert_eq!(responder.await.unwrap(), Some(sub.display().to_string()));+ assert!(+ out[0].content.starts_with(&sub.display().to_string()),+ "ran in the held directory: {}",+ out[0].content+ );+ assert_eq!(*cwd.lock().unwrap(), Some(sub), "a plain command moves nothing");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// An escalated `cd` holds like any other and is announced. It needs no+ /// host-side check: no held directory gets one, and the next confined+ /// call enters it inside the sandbox or refuses and resets to the root.+ #[tokio::test]+ #[cfg(all(feature = "cli", unix))]+ async fn an_escalated_cd_is_held_and_announced() {+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported() {+ return;+ }+ let root = unique_project_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ std::fs::create_dir_all(root.join("other")).unwrap();+ let sub = std::fs::canonicalize(root.join("sub")).unwrap();+ let other = std::fs::canonicalize(root.join("other")).unwrap();+ let (invoker, cwd, responder) = held_cwd_escalation(&root, sub);+ let command = format!("cd '{}'", other.display());+ let escalated = json!({ "command": command, "escalate": true, "justification": "x" });+ let out = invoker.invoke(&[shell_call("esc", escalated)]).await.unwrap();+ responder.await.unwrap();+ assert!(out[0].content.contains("shell cwd is now"), "{}", out[0].content);+ assert_eq!(*cwd.lock().unwrap(), Some(other));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// An escalated `cd` into a host directory the sandbox cannot see (the+ /// host's `/tmp`, under bubblewrap's private tmpfs) is held, since it runs+ /// on the host and is not checked there, and the next confined call+ /// refuses to run anywhere else and resets the shell to the root.+ #[tokio::test]+ #[cfg(all(feature = "cli", target_os = "linux"))]+ async fn an_escalated_cd_the_sandbox_cannot_see_is_refused_by_the_next_call() {+ use tauri_plugin_agent_tools::tools::jail;+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported()+ || jail::backend() != jail::Backend::Bubblewrap+ {+ return;+ }+ let root = unique_project_root();+ let host = std::path::PathBuf::from(format!("/tmp/jan_loop_host_{}", std::process::id()));+ std::fs::create_dir_all(&host).unwrap();+ let host = std::fs::canonicalize(&host).unwrap();+ let canonical_root = std::fs::canonicalize(&root).unwrap();+ let (mut invoker, cwd, responder) = held_cwd_escalation(&root, canonical_root);+ // bubblewrap binds the scratch, so it must exist for the confined call.+ std::fs::create_dir_all(&invoker.scratch_root).unwrap();+ // The confined call below runs without a prompt; the escalation+ // still asks, which the responder answers.+ invoker.auto_approve = true;+ let command = format!("cd '{}'", host.display());+ let escalated = json!({ "command": command, "escalate": true, "justification": "x" });+ let out = invoker.invoke(&[shell_call("esc", escalated)]).await.unwrap();+ responder.await.unwrap();+ assert!(out[0].content.contains("shell cwd is now"), "{}", out[0].content);+ assert_eq!(*cwd.lock().unwrap(), Some(host.clone()));+ let confined = json!({ "command": "touch marker" });+ let out = invoker.invoke(&[shell_call("next", confined)]).await.unwrap();+ assert!(out[0].content.contains("was NOT run"), "{}", out[0].content);+ assert!(!root.join("marker").exists(), "fell back to the project root");+ assert!(!host.join("marker").exists(), "ran on the host");+ assert_eq!(*cwd.lock().unwrap(), None, "the shell is back in the root");+ let _ = std::fs::remove_dir_all(&host);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A held directory that is gone refuses the escalated command rather than+ /// running it in the project root, and the shell is back in the root.+ #[tokio::test]+ #[cfg(all(feature = "cli", unix))]+ async fn escalation_refuses_a_held_shell_cwd_that_is_gone() {+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported() {+ return;+ }+ let root = unique_project_root();+ let gone = std::fs::canonicalize(&root).unwrap().join("gone");+ let (invoker, cwd, responder) = held_cwd_escalation(&root, gone);+ let escalated = json!({ "command": "touch marker", "escalate": true, "justification": "x" });+ let out = invoker.invoke(&[shell_call("esc", escalated)]).await.unwrap();+ responder.await.unwrap();+ assert!(out[0].content.contains("was NOT run"), "{}", out[0].content);+ assert!(!root.join("marker").exists(), "fell back to the project root");+ assert_eq!(*cwd.lock().unwrap(), None, "the shell is back in the root");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A held directory swapped for a link refuses the escalation before the+ /// user is asked: the prompt would name the held path while the command+ /// followed the link somewhere else. The shell is back in the root.+ #[tokio::test]+ #[cfg(all(feature = "cli", unix))]+ async fn escalation_refuses_a_held_shell_cwd_swapped_for_a_link() {+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported() {+ return;+ }+ let root = unique_project_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ std::fs::create_dir_all(root.join("elsewhere")).unwrap();+ let sub = std::fs::canonicalize(root.join("sub")).unwrap();+ std::fs::remove_dir(&sub).unwrap();+ std::os::unix::fs::symlink("elsewhere", &sub).unwrap();+ let (invoker, cwd, responder) = held_cwd_escalation(&root, sub);+ let escalated = json!({ "command": "touch marker", "escalate": true, "justification": "x" });+ let out = invoker.invoke(&[shell_call("esc", escalated)]).await.unwrap();+ assert!(out[0].content.contains("was not run"), "{}", out[0].content);+ assert!(out[0].content.contains("back in the project root"), "{}", out[0].content);+ assert!(!root.join("elsewhere/marker").exists(), "followed the link");+ assert!(!root.join("marker").exists(), "fell back to the project root");+ assert_eq!(*cwd.lock().unwrap(), None, "the shell is back in the root");+ responder.abort();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A command the gate cannot scan within its bounds gets its own refusal,+ /// telling the model to split it, not the hidden-home one that would send+ /// it looking for a path it never named. Telemetry counts it as a config+ /// refusal like the others.+ #[tokio::test]+ #[cfg(feature = "cli")]+ async fn a_command_too_complex_to_check_is_refused_with_its_own_reason() {+ let root = unique_project_root();+ let jan = root.join("jan-home");+ std::fs::create_dir_all(&jan).unwrap();+ let (tx, _rx) = mpsc::unbounded_channel();+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let mut invoker = build_prompting_invoker(root.clone(), tx, registry);+ invoker.hidden_root = Some(jan);+ let deep = format!("cat {}", "a/".repeat(70_000));+ let out = invoker.invoke(&[shell_call("c", json!({ "command": deep }))]).await.unwrap();+ let text = &out[0].content;+ assert!(text.contains(TOO_COMPLEX_REFUSED), "{}", &text[..text.len().min(300)]);+ assert!(!text.contains(HIDDEN_PATH_REFUSED), "not refused as naming the home");+ assert_eq!(+ crate::core::agent::otel::refusal_of(text),+ Some(crate::core::agent::otel::Refusal::Config)+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// An escalated call from a held directory above the Jan home is refused+ /// for where it would start, though the command names nothing hidden.+ /// The refusal names that directory and how to get out of it, and resets+ /// the shell, rather than the generic hidden-home message that would+ /// leave the model retrying from the same place. No prompt is sent.+ #[tokio::test]+ #[cfg(all(feature = "cli", unix))]+ async fn escalation_from_a_held_shell_cwd_above_the_home_names_it_and_resets() {+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported() {+ return;+ }+ let home = std::fs::canonicalize(unique_project_root()).unwrap();+ let jan = home.join("jan-home");+ let project = home.join("proj");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::create_dir_all(&project).unwrap();+ let (mut invoker, cwd, responder) = held_cwd_escalation(&project, home.clone());+ invoker.hidden_root = Some(jan);+ let escalated = json!({ "command": "/bin/true", "escalate": true, "justification": "x" });+ let out = invoker.invoke(&[shell_call("esc", escalated)]).await.unwrap();+ let text = &out[0].content;+ assert!(text.contains(HIDDEN_PATH_REFUSED), "{text}");+ assert!(text.contains(&format!("shell cwd {} is in it", home.display())), "{text}");+ assert!(text.contains("back in the project root"), "{text}");+ assert_eq!(*cwd.lock().unwrap(), None, "the shell is back in the root");+ assert!(!responder.is_finished(), "no prompt was sent");+ responder.abort();+ let _ = std::fs::remove_dir_all(&home);+ }++ /// A gated confined exec names the held directory in its prompt, so the+ /// user does not approve a command for the wrong tree.+ #[tokio::test]+ #[cfg(all(feature = "cli", unix))]+ async fn a_gated_exec_names_the_held_shell_cwd() {+ if !tauri_plugin_agent_tools::tools::proc::shell_cwd_supported() {+ return;+ }+ let root = unique_project_root();+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let canonical_sub = std::fs::canonicalize(root.join("sub")).unwrap();+ let (tx, mut rx) = mpsc::unbounded_channel();+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let mut invoker = build_prompting_invoker(root.clone(), tx, registry.clone());+ let cwd = tauri_plugin_agent_tools::tools::ShellCwd::default();+ *cwd.lock().unwrap() = Some(canonical_sub.clone());+ invoker.shell_cwd = Some(cwd);+ let responder = tokio::spawn(async move {+ loop {+ match rx.recv().await {+ Some(StreamEvent::PermissionRequest { request_id, path, command, .. }) => {+ if let Some(tx) = registry.lock().await.remove(&request_id) {+ let _ = tx.send(PermissionDecision::Deny);+ }+ return (path, command);+ }+ Some(_) => continue,+ None => panic!("no prompt was sent"),+ }+ }+ });+ invoker.invoke(&[shell_call("plain", json!({ "command": "rm -rf build" }))]).await.unwrap();+ let (path, command) = responder.await.unwrap();+ assert_eq!(command.as_deref(), Some("rm -rf build"));+ assert_eq!(path, Some(canonical_sub.display().to_string()));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// After a compaction the call that announced a `cd` is gone, so the+ /// workspace section names where the shell is.+ #[test]+ fn workspace_lines_name_a_held_shell_cwd() {+ let root = unique_project_root();+ let cwd = tauri_plugin_agent_tools::tools::ShellCwd::default();+ assert!(!workspace_lines(&root, Some(&cwd)).contains("Shell cwd"));+ *cwd.lock().unwrap() = Some(root.join("sub"));+ let lines = workspace_lines(&root, Some(&cwd));+ assert!(lines.contains(&format!("Shell cwd: {}", root.join("sub").display())), "{lines}");+ let _ = std::fs::remove_dir_all(&root);+ }+/// A denied escalation runs nothing, inside the sandbox or out, and tells/// the model not to retry it -- the same answer a headless run without a/// terminal gets, which is why it names the opt-in.@@ -13729,6 +14143,7 @@ mod tests {],blackboard_dir: Some("blackboard".to_string()),names: vec!["explorer-a".to_string(), "explorer-b".to_string()],+ later_workspaces: Vec::new(),});assert!(out.contains("sub-explorer-a-1"), "{out}");assert!(out.contains("sub-explorer-b-2"), "{out}");@@ -13751,8 +14166,12 @@ mod tests {}],blackboard_dir: None,names: vec!["researcher".to_string(), "writer".to_string()],+ later_workspaces: vec![("writer".to_string(), "researcher".to_string())],});assert!(out.contains("sub-researcher-1"), "{out}");+ // The parent named neither worker, so it is told whose workspace the+ // later one will get.+ assert!(out.contains("writer will work in researcher's workspace"), "{out}");// Every worker is named, the later phase's included, in listed order.assert!(out.contains(&crate::core::agent::subagent::worker_names_line(&[@@ -14043,6 +14462,7 @@ mod tests {}],blackboard_dir: None,names: vec!["w".to_string()],+ later_workspaces: Vec::new(),});assert!(out.contains("stop_subagent"), "{out}");assert!(out.contains("by name"), "{out}");@@ -14565,6 +14985,7 @@ mod tests {});let mut args = crate::core::agent::subagent::tests::max_par_args(&root);+ args.subagent_worktrees = true;args.sandbox = Some(false);args.project_memory = false;args.provider_configs = Arc::new(Mutex::new(HashMap::from([(diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rsindex eb6bafd0e..e90edefb1 100644--- a/src-tauri/src/core/agent/otel/mod.rs+++ b/src-tauri/src/core/agent/otel/mod.rs@@ -142,6 +142,8 @@ pub enum EventSignal {code: String,message: String,},+ /// A child was dispatched: started now, or queued for a slot.+ SubagentStart,SubagentEnd {failed: bool,},@@ -173,7 +175,8 @@ impl From<&Usage> for Tokens {pub enum Refusal {/// The user answered a permission prompt with deny.User,- /// Project policy, plan mode or the hidden Jan home.+ /// Project policy, plan mode, the hidden Jan home, or a command too+ /// complex for the gate to check.Config,/// A `PreToolUse` hook said no.Hook,@@ -196,6 +199,7 @@ impl Refusal {pub fn refusal_of(content: &str) -> Option<Refusal> {use crate::core::agent::r#loop::{DENIED_BY_POLICY, DENIED_BY_USER, HIDDEN_PATH_REFUSED, HOOK_DENIED, PLAN_MODE_UNAVAILABLE,+ TOO_COMPLEX_REFUSED,};if !content.starts_with("ERROR:") {return None;@@ -206,6 +210,7 @@ pub fn refusal_of(content: &str) -> Option<Refusal> {} else if head.contains(DENIED_BY_POLICY)|| head.contains(PLAN_MODE_UNAVAILABLE)|| head.contains(HIDDEN_PATH_REFUSED)+ || head.contains(TOO_COMPLEX_REFUSED){Some(Refusal::Config)} else if head.starts_with("ERROR: tool '") && head.contains(&format!("' {HOOK_DENIED}")) {@@ -293,6 +298,13 @@ pub fn classify(cfg: &Config, event: &StreamEvent, child: Option<Child>) -> Opticode: code.clone(),message: truncate(&redact_secrets(message), ERROR_CAP),},+ StreamEvent::SubagentStart { run_id, name, .. }+ | StreamEvent::SubagentQueued { run_id, name, .. } => {+ return Some(Signal::Event {+ child: Some(Child { run_id: run_id.clone(), name: name.clone() }),+ event: EventSignal::SubagentStart,+ });+ }StreamEvent::SubagentEnd { run_id, name, error } => {return Some(Signal::Event {child: Some(Child { run_id: run_id.clone(), name: name.clone() }),@@ -663,6 +675,10 @@ pub struct State {run_session: HashMap<Option<String>, String>,requests: HashMap<Option<String>, PendingRequest>,tools: HashMap<(Option<String>, String), PendingTool>,+ /// Child runs dispatched and not yet ended. A `SubagentEnd` for a run not+ /// here is a child that never started (stopped while pending on its+ /// phase): it reports no result, or it would count as a failed run.+ subagents: HashSet<String>,/// Tools a permission prompt was raised for and not yet resolved, per run.prompted: HashMap<Option<String>, Vec<String>>,/// The prompt currently in flight, per session (`""` = no session id),@@ -721,6 +737,7 @@ impl State {run_session: HashMap::new(),requests: HashMap::new(),tools: HashMap::new(),+ subagents: HashSet::new(),prompted: HashMap::new(),prompt_ids: HashMap::new(),main_session: None,@@ -1183,16 +1200,24 @@ impl State {}self.log(wall, "jan_agent.api_error", true, session.as_deref(), child.as_ref(), fields);}+ EventSignal::SubagentStart => {+ if let Some(run) = run {+ self.subagents.insert(run);+ }+ }EventSignal::SubagentEnd { failed } => {- let session = self.session_of(&None);- self.log(- wall,- "jan_agent.subagent_result",- failed,- session.as_deref(),- child.as_ref(),- vec![("success".into(), AnyValue::Bool(!failed))],- );+ let started = run.as_ref().is_some_and(|r| self.subagents.remove(r));+ if started {+ let session = self.session_of(&None);+ self.log(+ wall,+ "jan_agent.subagent_result",+ failed,+ session.as_deref(),+ child.as_ref(),+ vec![("success".into(), AnyValue::Bool(!failed))],+ );+ }// The child's bookkeeping ends with it.self.requests.remove(&run);self.run_session.remove(&run);diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rsindex 48893eca2..9cb8680d0 100644--- a/src-tauri/src/core/agent/otel/tests.rs+++ b/src-tauri/src/core/agent/otel/tests.rs@@ -275,6 +275,13 @@ fn a_subagents_signals_carry_its_run_and_the_parent_session() {None,&[provenance(None, "sess-1"),+ StreamEvent::SubagentStart {+ run_id: "run-7".into(),+ name: "scout".into(),+ task: None,+ workspace: None,+ internal: false,+ },wrapped(provenance(Some("run-7"), "sess-1")),wrapped(StreamEvent::Step { index: 1, max: 0 }),wrapped(usage(4, 2, 0, 0)),@@ -293,6 +300,37 @@ fn a_subagents_signals_carry_its_run_and_the_parent_session() {assert!(state.logs.iter().any(|l| l.event_name == "jan_agent.subagent_result"));}+/// A later-phase child stopped before it started is closed by a+/// `SubagentEnd` carrying an error, under a run id nothing else ever used.+/// That is not a failed subagent run, so it reports no result; a child that+/// was queued and then ended still does.+#[test]+fn an_end_for_a_run_never_started_reports_no_result() {+ let end = |run: &str, error: Option<&str>| StreamEvent::SubagentEnd {+ run_id: run.into(),+ name: run.into(),+ error: error.map(str::to_string),+ };+ let state = fold(+ cfg_with(false, false),+ None,+ &[+ end("never", Some("stopped by the parent agent before it started")),+ StreamEvent::SubagentQueued { run_id: "waited".into(), name: "waited".into(), task: None, waiting: 1 },+ end("waited", Some("boom")),+ // A second end for the same run is not a second result.+ end("waited", Some("boom")),+ ],+ );+ let results: Vec<_> = state+ .logs+ .iter()+ .filter(|l| l.event_name == "jan_agent.subagent_result")+ .map(|l| attr(l, "agent.run_id").cloned())+ .collect();+ assert_eq!(results, vec![Some(AnyValue::Str("waited".into()))]);+}+#[test]fn an_error_after_a_request_counts_a_failed_request() {let state = fold(@@ -758,6 +796,7 @@ fn every_exported_metric_is_described() {fn refusals_classify_the_messages_the_loop_builds() {use crate::core::agent::r#loop::{DENIED_BY_POLICY, DENIED_BY_USER, HIDDEN_PATH_REFUSED, HOOK_DENIED, PLAN_MODE_UNAVAILABLE,+ TOO_COMPLEX_REFUSED,};// Built the way loop.rs builds them, from the same constants.assert_eq!(refusal_of(&format!("ERROR: tool 'bash' {DENIED_BY_USER}")), Some(Refusal::User));@@ -774,6 +813,10 @@ fn refusals_classify_the_messages_the_loop_builds() {Some(Refusal::Config));assert_eq!(refusal_of(&format!("ERROR: tool 'x' {HOOK_DENIED}nope")), Some(Refusal::Hook));+ assert_eq!(+ refusal_of(&format!("ERROR: tool 'bash' was {TOO_COMPLEX_REFUSED} to check")),+ Some(Refusal::Config)+ );}#[test]diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex e42e6ad55..7ff42cd1b 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -235,6 +235,18 @@ pub(crate) struct AgentSection {/// run only.#[serde(default)]pub max_parallel_subagents: Option<u32>,+ /// Give a subagent that can write or edit, and asked for no `workspace`, a+ /// git worktree of its own. `None` and `false`: it works in the parent's+ /// checkout, so concurrent writers edit the same files. Overridden by+ /// `--subagent-worktrees`.+ #[serde(default)]+ pub subagent_worktrees: Option<bool>,+ /// Largest the build directory shared by this project's subagents+ /// (`~/.jan/worktrees/<slug>/cargo-target`) may grow, in GB, before a+ /// session end moves it to the trash so the next build starts cold.+ /// `None` defers to `~/.jan/config.toml`, then 20; 0 never trims.+ #[serde(default)]+ pub subagent_build_cache_max_gb: Option<u64>,/// Saved threads untouched for this many days are pruned at session start/// (default 90; 0 disables), when `prune_threads = true` in/// `~/.jan/config.toml` turns pruning on. The newest few, the resumed thread, forks'@@ -328,6 +340,10 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]# compaction_reserve_tokens = 16384 # absolute headroom instead, in tokens; wins over compaction_ratio# max_tokens = 4096 # cap on tokens the model generates per response (OpenAI max_tokens); omitted if unset# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO+# subagent_worktrees = false # true: a subagent that can write gets its own git worktree; false+# # (default): it edits your checkout, shared with its siblings+# subagent_build_cache_max_gb = 20 # clear the subagents' shared cargo-target at session end once+# # it is larger than this; 0 never clears it# thread_retention_days = 90 # prune saved threads older than this at startup; 0 disables# max_threads = 500 # keep at most this many saved threads; 0 disables# # (both apply only with prune_threads = true in ~/.jan/config.toml)@@ -614,6 +630,24 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {}}+/// The default cap, in GB, on a project's shared subagent build directory.+#[cfg(feature = "cli")]+pub(crate) const DEFAULT_SUBAGENT_BUILD_CACHE_MAX_GB: u64 = 20;++/// The cap, in bytes, on `project_root`'s shared subagent build directory:+/// `[agent].subagent_build_cache_max_gb` in its agent.toml, else the same key+/// in `~/.jan/config.toml`, else [`DEFAULT_SUBAGENT_BUILD_CACHE_MAX_GB`].+/// `0` never trims. An unreadable agent.toml falls through, like every knob.+#[cfg(feature = "cli")]+pub(crate) fn subagent_build_cache_cap(project_root: &Path) -> u64 {+ let gb = load_agent_config(project_root)+ .ok()+ .and_then(|cfg| cfg.agent.subagent_build_cache_max_gb)+ .or_else(crate::core::agent::global_config::subagent_build_cache_max_gb_setting)+ .unwrap_or(DEFAULT_SUBAGENT_BUILD_CACHE_MAX_GB);+ gb.saturating_mul(1 << 30)+}+/// See [`RunSettings::tool_notices`].fn renamed_tool_notices(tools: &ToolsSection) -> Vec<String> {[@@ -1208,6 +1242,23 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// The project's cap wins, 0 is kept as "never", and an unset key falls+ /// back to 20 GB.+ #[cfg(feature = "cli")]+ #[test]+ fn subagent_build_cache_cap_reads_the_project_key_in_gb() {+ let root = unique_root("build_cache_cap");+ ensure_project(&root).expect("scaffold");+ assert_eq!(subagent_build_cache_cap(&root), 20 << 30, "template leaves it unset");+ let path = agent_toml_path(&root);+ for (value, bytes) in [(3i64, 3u64 << 30), (0, 0)] {+ set_agent_key(&path, "subagent_build_cache_max_gb", Some(toml_edit::value(value)))+ .expect("set");+ assert_eq!(subagent_build_cache_cap(&root), bytes, "{value}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }+#[cfg(feature = "cli")]#[test]fn max_parallel_subagents_parses_and_defaults_to_none() {@@ -1235,6 +1286,19 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// Off unless asked for: the scaffold leaves the key unset, and an explicit+ /// value reads back both ways.+ #[cfg(feature = "cli")]+ #[test]+ fn subagent_worktrees_parses_and_defaults_to_none() {+ let cfg: AgentToml = toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");+ assert_eq!(cfg.agent.subagent_worktrees, None, "template leaves it unset");+ let on: AgentToml = toml::from_str("[agent]\nsubagent_worktrees = true\n").expect("parses");+ assert_eq!(on.agent.subagent_worktrees, Some(true));+ let off: AgentToml = toml::from_str("[agent]\nsubagent_worktrees = false\n").expect("parses");+ assert_eq!(off.agent.subagent_worktrees, Some(false));+ }+#[cfg(feature = "cli")]#[test]fn thread_retention_keys_parse_and_default_to_none() {diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex b51da330a..c70d531c9 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -138,6 +138,9 @@ pub enum SubagentError {PermissionDenied(String),Upstream(String),Cancelled,+ /// A later-phase child was stopped by its parent before it started, so+ /// its phase goes on without it.+ Stopped,}impl std::fmt::Display for SubagentError {@@ -146,6 +149,7 @@ impl std::fmt::Display for SubagentError {SubagentError::PermissionDenied(m) => write!(f, "permission denied: {m}"),SubagentError::Upstream(m) => write!(f, "{m}"),SubagentError::Cancelled => write!(f, "subagent run cancelled"),+ SubagentError::Stopped => write!(f, "stopped by the parent agent before it started"),}}}@@ -1060,6 +1064,28 @@ fn resolve_target<'a>(})}+/// What became of a [`message_subagent`] call that did not error. Both carry+/// the reply the parent agent's tool returns verbatim; the variant is for a+/// caller that shows the message as sent (the TUI's `/agents` detail), which+/// must not do so for a message nobody will read.+#[derive(Debug, Clone)]+pub(crate) enum MessageReply {+ /// On the child's inbox: it reads it at its next turn boundary.+ Queued(String),+ /// Not queued, and not an error to the model: the child already finished,+ /// or was stopped before it started.+ NotDelivered(String),+}++impl MessageReply {+ /// The text the `message_subagent` tool replies with.+ pub(crate) fn into_text(self) -> String {+ match self {+ MessageReply::Queued(s) | MessageReply::NotDelivered(s) => s,+ }+ }+}+/// Deliver one parent message to a live child, addressed by the name the/// dispatch gave it (see [`resolve_target`]) or its `run_id`.///@@ -1071,8 +1097,13 @@ pub(crate) fn message_subagent(bg: &Arc<BackgroundSubagents>,target: &str,message: &str,-) -> Result<String, SubagentError> {+) -> Result<MessageReply, SubagentError> {use std::sync::atomic::Ordering;+ // Pending first: a starting child leaves the pending table only once it+ // is in `inner`, so checked in this order it is always found.+ if let Some(reply) = bg.message_pending(target, message) {+ return reply;+ }let (run_id, name, finished, inbox) = {let guard = bg.inner.lock().unwrap();let entry = resolve_target(&guard, target)?;@@ -1084,17 +1115,17 @@ pub(crate) fn message_subagent()};if finished {- return Ok(format!(+ return Ok(MessageReply::NotDelivered(format!("Subagent '{name}' ({run_id}) has already finished, so there is nobody to read this. \Its answer is already yours; dispatch a follow-up subagent if more work is needed."- ));+ )));}let depth = inbox.push(message.to_string())?;- Ok(format!(+ Ok(MessageReply::Queued(format!("Queued for subagent '{name}' ({run_id}); it reads this at its next turn boundary, after \any tool call already in flight. {depth} message(s) pending for it. Keep working -- \nothing waits on this."- ))+ )))}/// Stop a live child by name (or `run_id`). Unlike [`BackgroundSubagents::abort_child`]@@ -1107,6 +1138,10 @@ pub(crate) fn stop_subagent() -> Result<String, SubagentError> {use crate::core::agent::events::StreamEvent;use std::sync::atomic::Ordering;+ // Pending first, for the reason `message_subagent` gives.+ if let Some(reply) = bg.stop_pending(target) {+ return Ok(reply);+ }let guard = bg.inner.lock().unwrap();let entry = resolve_target(&guard, target)?;if entry.finished.swap(true, Ordering::SeqCst) {@@ -1309,6 +1344,28 @@ pub(crate) struct BackgroundSubagents {/// because a teardown drains `inner`, and a compaction afterwards still/// has to name the children whose answers sit on the blackboard.roster: std::sync::Mutex<Vec<RosterEntry>>,+ /// Later-phase children of a plan that have not started yet, by worker+ /// name. The dispatch result names them, so the parent may address them+ /// before they exist in `inner`; see [`PendingChild`]. When both are+ /// held, this is locked first.+ pending: std::sync::Mutex<std::collections::HashMap<String, PendingChild>>,+}++/// A later-phase child of a plan, known by name before its phase starts.+struct PendingChild {+ /// The model's own `phase` key for it, as the dispatch result shows it.+ phase: u32,+ /// The inbox it will be started with, so a message left now is read+ /// right after its task, before its first turn.+ inbox: Arc<ChildInbox>,+ /// Set by `stop_subagent`: the plan driver skips it, so it never starts.+ stopped: bool,+ /// The registry generation its plan was dispatched under, so a teardown+ /// forgets only the plans it ended: a session-owned registry may already+ /// be taking the next run's plan while that teardown is still draining.+ generation: u64,+ /// Where its waiting panel was announced, to close it if it is stopped.+ events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,}/// How a dispatched child stands, as a parent's continuation state shows it.@@ -1411,7 +1468,125 @@ impl BackgroundSubagents {session_events: std::sync::Mutex::new(None),workspaces: Arc::default(),roster: std::sync::Mutex::new(Vec::new()),+ pending: std::sync::Mutex::new(std::collections::HashMap::new()),+ }+ }++ /// Record the later phases of a plan dispatched under `generation` as+ /// pending children, reporting into `events`. A teardown of that+ /// generation forgets them (see [`Self::abort_all`]): no driver is left+ /// to start them.+ fn add_pending(+ &self,+ phases: &[Phase],+ generation: u64,+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) {+ let mut pending = self.pending.lock().unwrap();+ // Read under the lock `abort_all` sweeps with, after its bump: a plan+ // already torn down records nothing that no sweep would ever forget.+ if self.generation() != generation {+ return;+ }+ for phase in phases {+ for req in &phase.subagents {+ pending.insert(+ req.name.clone(),+ PendingChild {+ phase: phase.number,+ inbox: Arc::default(),+ stopped: false,+ generation,+ events: self.child_events(events),+ },+ );+ }+ }+ }++ /// Forget the pending children of every plan dispatched under generation+ /// `ended` or before: those plans were torn down, so no driver will start+ /// them. Only those: a new run's plan on a session-owned registry may+ /// register its own between the teardown's bump and this sweep, under the+ /// new generation, and they are that live plan's to start.+ fn forget_pending_through(&self, ended: u64) {+ self.pending+ .lock()+ .unwrap()+ .retain(|_, child| child.generation > ended);+ }++ /// Forget the pending children `names`: their plan skipped them or could+ /// not start them, so nobody will read what is left for them.+ fn forget_pending<'a>(&self, names: impl IntoIterator<Item = &'a String>) {+ let mut pending = self.pending.lock().unwrap();+ for name in names {+ pending.remove(name);+ }+ }++ /// Whether the pending child `name` was stopped, so its phase must start+ /// without it: checked before its workspace is assigned, so a stopped+ /// child costs no worktree. [`start_dispatch`] checks again, for a stop+ /// landing while the workspace was assigned.+ fn pending_stopped(&self, name: &str) -> bool {+ self.pending+ .lock()+ .unwrap()+ .get(name)+ .is_some_and(|c| c.stopped)+ }++ /// `message_subagent` on a child still pending in a live plan: queue it+ /// on the inbox the child starts with. `None` when no such child is+ /// pending, so the caller reports its own "no subagent" error.+ fn message_pending(+ &self,+ name: &str,+ message: &str,+ ) -> Option<Result<MessageReply, SubagentError>> {+ let pending = self.pending.lock().unwrap();+ let child = pending.get(name)?;+ if child.stopped {+ return Some(Ok(MessageReply::NotDelivered(format!(+ "Subagent '{name}' was stopped before it started, so nobody will read this. \+ Dispatch a new subagent if the work is still needed."+ ))));+ }+ Some(child.inbox.push(message.to_string()).map(|depth| {+ MessageReply::Queued(format!(+ "Queued for subagent '{name}', which is pending on phase {}: it starts once the \+ phases before it finish and reads this right after its task, before its first \+ turn. {depth} message(s) pending for it. Keep working -- nothing waits on this.",+ child.phase+ ))+ }))+ }++ /// `stop_subagent` on a child still pending in a live plan: mark it so+ /// its phase starts without it, and close the waiting panel its plan+ /// announced. `None` when no such child is pending.+ fn stop_pending(&self, name: &str) -> Option<String> {+ use crate::core::agent::events::StreamEvent;+ let mut pending = self.pending.lock().unwrap();+ let child = pending.get_mut(name)?;+ if std::mem::replace(&mut child.stopped, true) {+ return Some(format!(+ "Subagent '{name}' was already stopped before it started; nothing to stop."+ ));}+ // A run id of its own, never shared: it never ran, and a consumer+ // keys the panel it closes by name for a child that never started.+ let _ = child.events.send(StreamEvent::SubagentEnd {+ run_id: next_subagent_run_id(name),+ name: name.to_string(),+ error: Some("stopped by the parent agent before it started".to_string()),+ });+ Some(format!(+ "Stopped subagent '{name}' before it started (it was pending on phase {}): it will \+ never start and produces no answer. The rest of its phase still runs.",+ child.phase+ ))}/// Add a dispatched child to the roster.@@ -1675,8 +1850,12 @@ impl BackgroundSubagents {// so it is published first: a dispatch registering under the lock below// reads the new value and refuses, and one that read the old value has// already inserted and is found by the drain beneath it.- self.generation+ let ended = self+ .generation.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ // Before `inner` is locked, never nested inside it: `start_dispatch`+ // locks pending first.+ self.forget_pending_through(ended);let mut guard = self.inner.lock().unwrap();for (_, entry) in guard.drain() {entry.abort.abort();@@ -1702,6 +1881,7 @@ impl BackgroundSubagents {error: None,});}+ drop(guard);self.notices.lock().unwrap().clear();// Everything a parked waiter re-reads just changed, and `notify_waiters`// only reaches waiters already registered: without this a driver whose@@ -2253,10 +2433,13 @@ async fn run_subagent(let mut child_args = without_memory(parent_args, memory_access);// Where it works: its own worktree, or the parent's checkout read-only.// The git behind it was read at dispatch, on the blocking pool.- let workspace = placed.map(|(ws, placement)| {- crate::core::agent::child_workspace::apply(&mut child_args, &ws, placement);- ws- });+ let (workspace, build_hold) = match placed {+ Some((ws, placement)) => {+ let hold = crate::core::agent::child_workspace::apply(&mut child_args, &ws, placement);+ (Some(ws), hold)+ }+ None => (None, None),+ };child_args.system_prompt_override = Some(resolved.definition.system_prompt.clone());// The host wrote its prompt for the conversation it drives, not for a// delegate with a task of its own; left in place it would also replace the@@ -2280,6 +2463,9 @@ async fn run_subagent(// A message the user types is for the main agent, so it must not hurry a// child's shell into the background.child_args.shell_detach = None;+ // The child's own, so its shell starts in its workspace root rather than+ // wherever the parent last `cd`ed, and keeps its `cd` across its own calls.+ child_args.shell_cwd = Some(Default::default());// A child cannot dispatch subagents at all (`subagents_enabled = false`// above), so it has no registry to share; clearing this keeps it from// inheriting the parent session's by accident.@@ -2389,6 +2575,9 @@ async fn run_subagent(});let result = run_orchestration_steered(&child_tx, &body, &child_args, Some(&steering_tx)).await;+ // The child's build is over: the shared build directory may be trimmed+ // once no other child holds it.+ drop(build_hold);drop(child_tx);drop(steering_tx);let _ = forwarder.await;@@ -2557,11 +2746,12 @@ async fn assign_dispatch(let root = project_root.clone();let name = name.clone();let request = req.workspace.clone();+ let worktrees = parent_args.subagent_worktrees;tokio::task::spawn_blocking(move || {let (ws, lease) = scope.bg.workspaces- .assign(&root, &name, writer, request.as_ref())+ .assign(&root, &name, writer, request.as_ref(), worktrees).map_err(SubagentError::Upstream)?;// Checked here too, not only under the registry lock: a run// cancelled while git worked drops this dispatch's future, and@@ -2625,6 +2815,11 @@ fn start_dispatch(reserve_blackboard_result(s, &name).map(|path| (path.to_string_lossy().into_owned(), path))});let display_path = result_file.as_ref().map(|(display, _)| display.clone());+ // A later-phase child leaves the pending table in the same critical+ // section that registers it below, so `message_subagent`/`stop_subagent`+ // (which look there first) always find it in one table or the other.+ let mut pending = bg.pending.lock().unwrap();+ let planned = pending.remove(&name);// Admission and registration are one critical section: a teardown either// finds the entry below and aborts that child, or has already published its@@ -2632,13 +2827,23 @@ fn start_dispatch(// `tokio::spawn` is safe -- nothing a starting child does touches `inner`;// a child reports its progress through `notices`.let mut entries = bg.inner.lock().unwrap();- if scope.is_stale() {+ let refusal = if scope.is_stale() {+ Some(SubagentError::Cancelled)+ } else if planned.as_ref().is_some_and(|p| p.stopped) {+ // Stopped while its workspace was being assigned.+ Some(SubagentError::Stopped)+ } else {+ None+ };+ if let Some(refusal) = refusal {drop(entries);- // Torn down between the check above and here: give the worktree back- // and take back this assignment, since the teardown's own sweep may- // already have run. Only this one: a session-owned registry outlives- // the teardown (Esc stops its children mid-session), and its earlier- // children's worktrees and names are still the session's to reuse.+ drop(pending);+ // Torn down (or stopped) between the check above and here: give the+ // worktree back and take back this assignment, since the teardown's+ // own sweep may already have run. Only this one: a session-owned+ // registry outlives the teardown (Esc stops its children+ // mid-session), and its earlier children's worktrees and names are+ // still the session's to reuse.lease.release();// `undo` runs git, so it goes to the blocking pool rather than// stalling this async worker. Nothing waits on it: the dispatch is@@ -2649,8 +2854,11 @@ fn start_dispatch(Ok(handle) => drop(handle.spawn_blocking(undo)),Err(_) => undo(),}- return Err(SubagentError::Cancelled);+ return Err(refusal);}+ // The inbox it collected messages on while pending, so they land right+ // after its task, before its first turn.+ let inbox = planned.map(|p| p.inbox).unwrap_or_default();// Try to grab a permit at dispatch time. On success the child is admitted// immediately; on exhaustion it joins the semaphore waitlist (FIFO) and is@@ -2705,10 +2913,9 @@ fn start_dispatch(if admitted.is_ok() {slot.admitted_at_dispatch();}- // Created before the task, and registered below, so a message can be queued+ // Registered below before the task can start, so a message can be queued// for this child from the moment the dispatch returns -- including while it// is still parked on the semaphore.- let inbox = Arc::new(ChildInbox::default());let task_inbox = inbox.clone();let parent_link = ParentLink {bg: registry.clone(),@@ -2813,6 +3020,7 @@ fn start_dispatch(},);drop(entries);+ drop(pending);Ok(Dispatched {run_id,workspace: workspace_note,@@ -2991,6 +3199,10 @@ pub(crate) struct DispatchedPlan {/// Every worker's name, in the order the call listed them (see/// [`DispatchPlan::names`]).pub(crate) names: Vec<String>,+ /// `(worker, owner)` for each later-phase worker that reuses another's+ /// workspace, in phase order: the parent named neither, so the result+ /// says whose workspace each will get.+ pub(crate) later_workspaces: Vec<(String, String)>,}/// Lead of the dispatch result line naming every worker in the call's order.@@ -3139,6 +3351,18 @@ pub(crate) async fn spawn_dispatch_plan(let phase_count = plan.phases.len();let total_subagents = plan.phases.iter().map(|p| p.subagents.len()).sum();let names = plan.names.clone();+ let later_workspaces = plan+ .phases+ .iter()+ .skip(1)+ .flat_map(|p| p.subagents.iter())+ .filter_map(|s| match &s.workspace {+ Some(crate::core::agent::child_workspace::WorkspaceRequest::Reuse(of)) => {+ Some((s.name.clone(), of.clone()))+ }+ _ => None,+ })+ .collect();let blackboard_dir = scratch.map(|s| blackboard_dir_path(s).to_string_lossy().into_owned());let multi = phase_count > 1;@@ -3159,9 +3383,15 @@ pub(crate) async fn spawn_dispatch_plan(}).collect();let _ = events.send(crate::core::agent::events::StreamEvent::SubagentPlan { pending });+ // Addressable by name from now on, though none has started.+ bg.add_pending(&plan.phases[1..], generation, events);// Hold the park open for the whole plan before the first child can finish.bg.begin_plan();}+ let later_names: Vec<String> = plan.phases[1..]+ .iter()+ .flat_map(|p| p.subagents.iter().map(|s| s.name.clone()))+ .collect();let scope = DispatchScope {bg: bg.clone(),@@ -3178,7 +3408,8 @@ pub(crate) async fn spawn_dispatch_plan(} = spawn_first_phase(bg, multi, first.subagents, |req| {spawn_subagent(&scope, parent_args, req, parent, events, scratch, !multi)})- .await?;+ .await+ .inspect_err(|_| bg.forget_pending(&later_names))?;if multi {let remaining: Vec<Phase> = phases.collect();@@ -3215,6 +3446,7 @@ pub(crate) async fn spawn_dispatch_plan(first_phase: first_children,blackboard_dir,names,+ later_workspaces,})}@@ -3329,6 +3561,12 @@ async fn run_phase_plan(let mut ids = Vec::with_capacity(phase.subagents.len());let mut names = Vec::with_capacity(phase.subagents.len());for mut req in phase.subagents {+ // Stopped while pending: skipped before its workspace is assigned,+ // so it costs nothing. Its waiting panel was closed by the stop.+ if scope.bg.pending_stopped(&req.name) {+ scope.bg.forget_pending([&req.name]);+ continue;+ }req.description = inject_inputs(&req.description, &inputs, &dir);// Push the name only on a successful spawn, so `ids` and `names` stay// aligned: a child that never started has no blackboard file for the@@ -3355,14 +3593,25 @@ async fn run_phase_plan(scope.bg.end_plan();return;}- Err(e) => scope.bg.push_notice(- "plan",- format!("A subagent in the next phase could not start: {e}"),- ),+ // Stopped while its workspace was being assigned.+ Err(SubagentError::Stopped) => {}+ Err(e) => {+ // Nobody will read what was left for it now.+ scope.bg.forget_pending([&name]);+ scope.bg.push_notice(+ "plan",+ format!("A subagent in the next phase could not start: {e}"),+ )+ }}}- prev_ids = ids;- prev_names = names;+ // A phase that started nothing (every child stopped or refused) has+ // no results of its own, so the next phase is handed the last ones+ // there are, and the terminal ping reports them.+ if !ids.is_empty() {+ prev_ids = ids;+ prev_names = names;+ }}// Ring the doorbell once, only after the last phase's last child is done --// and never for a plan whose run was torn down while that last phase ran.@@ -3775,7 +4024,7 @@ pub fn subagent_tool_schemas("properties": {"agent": agent_field,"task": { "type": "string", "description": "The subagent's sole instruction. Include everything it needs, including any facts from your memory; it does not see this conversation or your memory. A subagent in a later phase also receives the previous phase's results automatically, so tell it what to DO with them." },- "phase": { "type": "integer", "minimum": 0, "description": "Optional stage (default 0). Subagents with the same phase run concurrently; a phase starts only after every lower phase has finished. Omit it entirely for a plain fan-out." },+ "phase": { "type": "integer", "minimum": 0, "description": "Optional stage (default 0). Subagents with the same phase run concurrently; a phase starts only after every lower phase has finished. Omit it entirely for a plain fan-out. A later-phase subagent can be messaged or stopped by its name before its phase starts: a message waits for it, and a stopped one never starts." },"allowed_tools": {"type": "array","items": { "type": "string" },@@ -3843,7 +4092,7 @@ pub fn subagent_tool_schemas(if cfg!(feature = "cli") {tools[0]["function"]["parameters"]["properties"]["subagents"]["items"]["properties"]["workspace"] = json!({- "description": "Optional; where the subagent works. OMIT for the default: one that can write or edit gets a fresh worktree (a clone of its own) on its own branch, any other works read-only in your checkout. \"new\": a fresh worktree. \"shared\": your checkout. The name of an earlier subagent: that subagent's workspace (one writer at a time). {\"ref\": \"<git ref>\"}: a fresh worktree at that ref, fetched if needed (e.g. pull/123/head).",+ "description": "Optional; where the subagent works. OMIT for the default: one that can write or edit works in your checkout, shared with you and with any sibling writer (concurrent writers can overwrite each other, so give parallel writers disjoint files or \"new\"); only when the user turned on subagent worktrees (--subagent-worktrees, or subagent_worktrees under [agent] in agent.toml) does it get a fresh worktree (a clone of its own) on its own branch. Any other subagent works read-only in your checkout. The dispatch result says where it works. \"new\": a fresh worktree, whatever that setting. \"shared\": your checkout. The name of an earlier subagent: that subagent's workspace (one writer at a time). In a later phase, an agent (e.g. \"general\") or worker name of an item in an earlier phase of this same call means that item's workspace, whatever it ends up named; if several earlier-phase items use that agent the reference is ambiguous and the dispatch is refused with their worker names, so name one of those instead. {\"ref\": \"<git ref>\"}: a fresh worktree at that ref, fetched if needed (e.g. pull/123/head).","anyOf": [{ "type": "string" },{@@ -3957,13 +4206,69 @@ pub fn parse_dispatch_plan(workspace,});}- let phases = by_phase+ let mut phases: Vec<Phase> = by_phase.into_iter().map(|(number, subagents)| Phase { number, subagents }).collect();+ bind_sibling_workspaces(&mut phases)?;Ok(DispatchPlan { phases, names })}+/// Point each later-phase `workspace: "<agent or name>"` at the earlier-phase+/// sibling of this plan it means.+///+/// The parent cannot know a sibling's name before dispatching -- names are+/// numbered per session, so its `general` may become `general-5` -- and the+/// session's own `general` is then an older, finished worker whose worktree+/// it silently got. So the plan's own items are consulted first: an exact+/// name the plan assigned binds to that item, else an agent type used by+/// exactly one earlier-phase item binds to it, and a reference matching no+/// item is left to name an earlier worker of the session. The exact name+/// wins because it names one worker outright, where the agent type is only+/// a guess at one. An agent type several earlier-phase items use, none of+/// them named exactly that, is refused, since which one is meant cannot be+/// told.+fn bind_sibling_workspaces(phases: &mut [Phase]) -> Result<(), SubagentError> {+ use crate::core::agent::child_workspace::WorkspaceRequest;+ for later in 1..phases.len() {+ let (earlier, rest) = phases.split_at_mut(later);+ let earlier: Vec<&SubagentRequest> =+ earlier.iter().flat_map(|p| p.subagents.iter()).collect();+ for req in &mut rest[0].subagents {+ let Some(WorkspaceRequest::Reuse(target)) = &mut req.workspace else {+ continue;+ };+ // Already the exact name of a sibling: bound as it stands.+ if earlier.iter().any(|s| s.name == *target) {+ continue;+ }+ let by_agent: Vec<&str> = earlier+ .iter()+ .filter(|s| s.agent == *target)+ .map(|s| s.name.as_str())+ .collect();+ let bound = match by_agent.as_slice() {+ [one] => Some(one.to_string()),+ [] => None,+ several => {+ return Err(SubagentError::Upstream(format!(+ "subagent '{}': workspace '{target}' is ambiguous: several earlier-phase \+ subagents of this dispatch use that agent ({}). Name one of those \+ numbered workers exactly, or give it workspace \"new\". Nothing was \+ started.",+ req.name,+ several.join(", ")+ )))+ }+ };+ if let Some(name) = bound {+ *target = name;+ }+ }+ }+ Ok(())+}+/// Name each worker after its agent, in order: the agent's own name the first/// time (`explore`), then numbered (`explore-2`, `explore-3`), skipping any/// name `taken` reports in use. The one numbering rule, shared by dispatch and@@ -4109,6 +4414,31 @@ pub(crate) mod tests {root}+ /// Run git in `root` with a throwaway identity; whether it succeeded.+ #[cfg(feature = "cli")]+ fn git_in(root: &Path, args: &[&str]) -> bool {+ std::process::Command::new("git")+ .arg("-C")+ .arg(root)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .is_ok_and(|o| o.status.success())+ }++ /// Make `root` a git repository with one commit, so a writer child can be+ /// given a worktree. `false` where git is unavailable: the caller skips.+ #[cfg(feature = "cli")]+ fn committed_repo(root: &Path) -> bool {+ std::fs::write(root.join("a.txt"), "a\n").unwrap();+ git_in(root, &["init", "-q"])+ && git_in(root, &["add", "a.txt"])+ && git_in(root, &["commit", "-q", "--no-gpg-sign", "-m", "a"])+ }+fn write_def(dir: &Path, name: &str, extra: &str) {std::fs::create_dir_all(dir).unwrap();let body = format!(@@ -5454,12 +5784,14 @@ pub(crate) mod tests {project_memory: true,subagents_enabled: true,max_parallel_subagents: 1,+ subagent_worktrees: false,auto_approve: false,monitors: None,bg_shells: None,subagent_bg: None,parent_link: None,shell_detach: None,+ shell_cwd: None,run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,sandbox: None,@@ -5687,7 +6019,7 @@ pub(crate) mod tests {let queued_id = dispatch_reviewer(&bg, &args, &events_tx).await;let reply = message_subagent(&bg, &queued_id, "narrow it to the parser").unwrap();- assert!(reply.contains("Queued for subagent"), "{reply}");+ assert!(reply.clone().into_text().contains("Queued for subagent"), "{reply:?}");let inbox = bg.inner@@ -5716,23 +6048,7 @@ pub(crate) mod tests {#[tokio::test]async fn a_dispatch_after_teardown_leaves_no_worktree_behind() {let root = unique_root("stale-wt");- let git = |args: &[&str]| {- std::process::Command::new("git")- .arg("-C")- .arg(&root)- .args(args)- .env("GIT_AUTHOR_NAME", "t")- .env("GIT_AUTHOR_EMAIL", "t@t")- .env("GIT_COMMITTER_NAME", "t")- .env("GIT_COMMITTER_EMAIL", "t@t")- .output()- .is_ok_and(|o| o.status.success())- };- std::fs::write(root.join("a.txt"), "a\n").unwrap();- if !(git(&["init", "-q"])- && git(&["add", "a.txt"])- && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))- {+ if !committed_repo(&root) {return;}write_def(&project_subagents_dir(&root), "writer", "");@@ -5772,22 +6088,8 @@ pub(crate) mod tests {async fn a_dispatch_waiting_on_git_does_not_stall_the_runtime() {use crate::core::agent::child_workspace::WorkspaceRequest;let root = unique_root("no-stall");- let git = |args: &[&str]| {- std::process::Command::new("git")- .arg("-C")- .arg(&root)- .args(args)- .env("GIT_AUTHOR_NAME", "t")- .env("GIT_AUTHOR_EMAIL", "t@t")- .env("GIT_COMMITTER_NAME", "t")- .env("GIT_COMMITTER_EMAIL", "t@t")- .output()- .is_ok_and(|o| o.status.success())- };- std::fs::write(root.join("a.txt"), "a\n").unwrap();- if !(git(&["init", "-q"])- && git(&["add", "a.txt"])- && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"])+ let git = |args: &[&str]| git_in(&root, args);+ if !(committed_repo(&root)&& git(&["config", "protocol.ext.allow", "always"])&& git(&["remote", "add", "origin", "ext::sh -c sleep% 1"])){@@ -5836,28 +6138,13 @@ pub(crate) mod tests {async fn a_stale_dispatch_takes_back_only_its_own_worktree() {use crate::core::agent::child_workspace::WorkspaceRequest;let root = unique_root("stale-own");- let git = |args: &[&str]| {- std::process::Command::new("git")- .arg("-C")- .arg(&root)- .args(args)- .env("GIT_AUTHOR_NAME", "t")- .env("GIT_AUTHOR_EMAIL", "t@t")- .env("GIT_COMMITTER_NAME", "t")- .env("GIT_COMMITTER_EMAIL", "t@t")- .output()- .is_ok_and(|o| o.status.success())- };- std::fs::write(root.join("a.txt"), "a\n").unwrap();- if !(git(&["init", "-q"])- && git(&["add", "a.txt"])- && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))- {+ if !committed_repo(&root) {return;}write_def(&project_subagents_dir(&root), "writer", "");write_def(&project_subagents_dir(&root), "reader", "allowed_tools = [\"read\"]\n");- let args = max_par_args(&root);+ let mut args = max_par_args(&root);+ args.subagent_worktrees = true;let bg = Arc::new(BackgroundSubagents::new(2));let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();bg.install_session_events(events_tx.clone());@@ -5909,7 +6196,7 @@ pub(crate) mod tests {assert_eq!(bg.workspaces.live(), before, "the earlier worktrees stay");for name in ["reader", "writer"] {let reuse = WorkspaceRequest::Reuse(name.to_string());- let again = bg.workspaces.assign(&root, "next", false, Some(&reuse));+ let again = bg.workspaces.assign(&root, "next", false, Some(&reuse), true);assert!(again.is_ok(), "{name}: {:?}", again.err());}let _ = bg.workspaces.finish_session();@@ -5926,27 +6213,12 @@ pub(crate) mod tests {async fn a_stopped_writer_releases_its_worktree_before_the_stop_returns() {use crate::core::agent::child_workspace::WorkspaceRequest;let root = unique_root("lease-stop");- let git = |args: &[&str]| {- std::process::Command::new("git")- .arg("-C")- .arg(&root)- .args(args)- .env("GIT_AUTHOR_NAME", "t")- .env("GIT_AUTHOR_EMAIL", "t@t")- .env("GIT_COMMITTER_NAME", "t")- .env("GIT_COMMITTER_EMAIL", "t@t")- .output()- .is_ok_and(|o| o.status.success())- };- std::fs::write(root.join("a.txt"), "a\n").unwrap();- if !(git(&["init", "-q"])- && git(&["add", "a.txt"])- && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))- {+ if !committed_repo(&root) {return;}write_def(&project_subagents_dir(&root), "writer", "");- let args = max_par_args(&root);+ let mut args = max_par_args(&root);+ args.subagent_worktrees = true;let bg = Arc::new(BackgroundSubagents::new(1));let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();// Queued behind the only permit, so it is still holding its lease.@@ -5964,11 +6236,11 @@ pub(crate) mod tests {.unwrap();assert!(d.workspace.contains("worktree"), "{}", d.workspace);let reuse = WorkspaceRequest::Reuse("writer".to_string());- let busy = bg.workspaces.assign(&root, "next", true, Some(&reuse)).unwrap_err();+ let busy = bg.workspaces.assign(&root, "next", true, Some(&reuse), true).unwrap_err();assert!(busy.contains("still writing"), "{busy}");stop_subagent(&bg, "writer").unwrap();- let next = bg.workspaces.assign(&root, "next", true, Some(&reuse));+ let next = bg.workspaces.assign(&root, "next", true, Some(&reuse), true);assert!(next.is_ok(), "{:?}", next.err());drop(next);drop(held);@@ -6820,6 +7092,466 @@ pub(crate) mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A two-or-more-phase plan whose phase 0 is parked on the semaphore, so a+ /// test can address the later phases before any of them can start. Returns+ /// the permit holding phase 0 back; drop it to let the plan run.+ #[cfg(feature = "cli")]+ async fn parked_plan(+ bg: &Arc<BackgroundSubagents>,+ root: &Path,+ later: Vec<Phase>,+ tx: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) -> tokio::sync::OwnedSemaphorePermit {+ let held = bg.semaphore.clone().try_acquire_owned().unwrap();+ let scratch = root.join("scratch");+ std::fs::create_dir_all(&scratch).unwrap();+ let mut phases = vec![Phase {+ number: 0,+ subagents: vec![worker("alpha")],+ }];+ phases.extend(later);+ let plan = DispatchPlan {+ names: Vec::new(),+ phases,+ };+ let args = max_par_args(root);+ spawn_dispatch_plan(bg, bg.generation(), &args, plan, &parent_run(), tx, Some(&scratch))+ .await+ .unwrap();+ held+ }++ /// Drain a plan the way the real loop does, bounded so a bug fails rather+ /// than hangs, returning every ping it rang.+ #[cfg(feature = "cli")]+ async fn drain_plan(bg: &Arc<BackgroundSubagents>) -> Vec<String> {+ let mut all = Vec::new();+ tokio::time::timeout(std::time::Duration::from_secs(20), async {+ while bg.has_pending_work() {+ bg.wait_for_notice().await;+ all.extend(bg.take_notices().into_iter().map(|n| n.text));+ }+ })+ .await+ .expect("the whole plan drains and releases the run");+ all+ }++ /// A later-phase child exists only in the plan until its phase starts, yet+ /// the dispatch result already named it. A message to it waits on the+ /// inbox the child is then started with, so it is read before its first+ /// turn, and the reply says the child is pending on its phase.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_message_to_a_pending_later_phase_child_reaches_it_when_it_starts() {+ let root = unique_root("pending-msg");+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let later = vec![Phase {+ number: 1,+ subagents: vec![worker("review")],+ }];+ let held = parked_plan(&bg, &root, later, &tx).await;++ let reply = message_subagent(&bg, "review", "check the parser too").unwrap();+ assert!(matches!(reply, MessageReply::Queued(_)), "{reply:?}");+ let reply = reply.into_text();+ assert!(+ reply.contains("review") && reply.contains("pending") && reply.contains("phase 1"),+ "{reply}"+ );++ drop(held);+ drain_plan(&bg).await;+ // The child fails fast (no provider) before its first turn, so the+ // message is still on the inbox its registry entry carries: the one+ // its steering channel drains at that turn.+ let inbox = bg+ .inner+ .lock()+ .unwrap()+ .values()+ .find(|e| e.name == "review")+ .expect("the later-phase child started")+ .inbox+ .clone();+ let waiting = inbox.drain().1;+ assert_eq!(waiting, vec!["check the parser too".to_string()]);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Stopping a pending child cancels it: it never starts, its siblings in+ /// the same phase still run, its waiting panel is closed, and a message to+ /// it afterwards is not queued for anyone.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn stopping_a_pending_child_keeps_it_from_ever_starting() {+ use crate::core::agent::events::StreamEvent;+ let root = unique_root("pending-stop");+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let later = vec![Phase {+ number: 1,+ subagents: vec![worker("review"), worker("gamma")],+ }];+ let held = parked_plan(&bg, &root, later, &tx).await;++ let reply = stop_subagent(&bg, "review").unwrap();+ assert!(reply.contains("review") && reply.contains("never start"), "{reply}");+ let again = stop_subagent(&bg, "review").unwrap();+ assert!(again.contains("already"), "{again}");+ let late = message_subagent(&bg, "review", "hello").unwrap();+ assert!(matches!(late, MessageReply::NotDelivered(_)), "{late:?}");+ assert!(late.clone().into_text().contains("stopped"), "{late:?}");++ drop(held);+ let pings = drain_plan(&bg).await;+ assert_eq!(pings.len(), 1, "the plan still rings once: {pings:?}");+ let mut started = Vec::new();+ let mut closed = false;+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::SubagentStart { name, .. }+ | StreamEvent::SubagentQueued { name, .. } => started.push(name),+ StreamEvent::SubagentEnd { name, error, .. } if name == "review" => {+ closed = error.is_some();+ }+ _ => {}+ }+ }+ assert!(!started.iter().any(|n| n == "review"), "{started:?}");+ assert!(started.iter().any(|n| n == "gamma"), "the sibling runs: {started:?}");+ assert!(closed, "the stopped child's waiting panel is closed");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A phase whose every child was stopped before it started is empty; the+ /// plan carries on to the phase after it rather than stalling or ending.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_phase_emptied_by_stops_lets_the_plan_carry_on() {+ use crate::core::agent::events::StreamEvent;+ let root = unique_root("pending-empty");+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let later = vec![+ Phase {+ number: 1,+ subagents: vec![worker("middle")],+ },+ Phase {+ number: 2,+ subagents: vec![worker("last")],+ },+ ];+ let held = parked_plan(&bg, &root, later, &tx).await;+ stop_subagent(&bg, "middle").unwrap();+ drop(held);+ let pings = drain_plan(&bg).await;+ assert_eq!(pings.len(), 1, "{pings:?}");+ assert!(pings[0].contains("last"), "{}", pings[0]);+ let started: Vec<String> = std::iter::from_fn(|| rx.try_recv().ok())+ .filter_map(|ev| match ev {+ StreamEvent::SubagentStart { name, .. } => Some(name),+ _ => None,+ })+ .collect();+ assert!(started.iter().any(|n| n == "last"), "{started:?}");+ assert!(!started.iter().any(|n| n == "middle"), "{started:?}");+ assert!(bg.pending.lock().unwrap().is_empty(), "nothing is left pending");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A teardown forgets the plan's pending children with it: there is no+ /// phase left to start them, so addressing one is an error again.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_teardown_forgets_pending_children() {+ let root = unique_root("pending-teardown");+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let later = vec![Phase {+ number: 1,+ subagents: vec![worker("review")],+ }];+ let held = parked_plan(&bg, &root, later, &tx).await;+ bg.abort_all();+ assert!(message_subagent(&bg, "review", "x").is_err());+ assert!(stop_subagent(&bg, "review").is_err());+ drop(held);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A teardown forgets only the plans it ended. On a session-owned+ /// registry the next run's plan can register its pending children (under+ /// the new generation) while the teardown is still draining; those are+ /// that live plan's, and addressing them must keep working.+ #[cfg(feature = "cli")]+ #[test]+ fn a_teardown_keeps_the_pending_children_of_a_newer_plan() {+ let bg = BackgroundSubagents::new(1);+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let phase = |name: &str| Phase {+ number: 1,+ subagents: vec![worker(name)],+ };+ let ended = bg.generation();+ bg.add_pending(&[phase("old")], ended, &tx);+ // `abort_all`'s steps with the next run's plan landing between its+ // bump and its sweep.+ bg.generation.fetch_add(1, Ordering::SeqCst);+ bg.add_pending(&[phase("new")], ended + 1, &tx);+ // A plan of the ended run registering only now records nothing.+ bg.add_pending(&[phase("late")], ended, &tx);+ bg.forget_pending_through(ended);+ let pending = bg.pending.lock().unwrap();+ assert!(!pending.contains_key("old"), "the ended plan is forgotten");+ assert!(!pending.contains_key("late"), "a torn-down plan adds nothing");+ assert!(pending.contains_key("new"), "the live plan keeps its children");+ }++ /// A pending child stopped while its workspace was being assigned (after+ /// the driver's `pending_stopped` check, before it is registered) is+ /// refused at registration: it never shows as started, its fresh worktree+ /// and writer lease are given back, the stop's own `SubagentEnd` is its+ /// only one, and a sibling of its phase still starts.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_child_stopped_during_workspace_assignment_never_starts() {+ use crate::core::agent::events::StreamEvent;+ let root = unique_root("stop-assign");+ if !committed_repo(&root) {+ return;+ }+ write_def(&project_subagents_dir(&root), "writer", "");+ let mut args = max_par_args(&root);+ args.subagent_worktrees = true;+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ // Hold the only slot so the sibling stays queued, not running.+ let _held = bg.semaphore.clone().try_acquire_owned().unwrap();+ let late = SubagentRequest {+ agent: "writer".to_string(),+ ..req("late", None)+ };+ let phase = Phase {+ number: 1,+ subagents: vec![late.clone(), worker("gamma")],+ };+ bg.add_pending(std::slice::from_ref(&phase), bg.generation(), &tx);+ let scope = bg.scope();++ // The driver's pre-check passed, then git assigned the worktree...+ assert!(!bg.pending_stopped("late"));+ let prepared = prepare_dispatch(&scope, &args, late, &parent_run()).await.unwrap();+ let late_wt = prepared.workspace.worktree.clone().expect("a writer gets a worktree");+ let lease = prepared.lease.clone();+ assert!(lease.0.lock().unwrap().is_some(), "the writer holds its lease");+ // ...and the stop lands before it is registered.+ let reply = stop_subagent(&bg, "late").unwrap();+ assert!(reply.contains("never start"), "{reply}");+ let refused = start_dispatch(&scope, &args, prepared, &tx, None, false);+ assert!(matches!(refused, Err(SubagentError::Stopped)));+ assert!(lease.0.lock().unwrap().is_none(), "the lease is released");+ // The undo runs on the blocking pool; give it a bounded moment.+ for _ in 0..300 {+ if !late_wt.path.exists() {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ assert!(!late_wt.path.exists(), "the stopped child's worktree is removed");+ assert!(bg.workspaces.live().is_empty(), "{:?}", bg.workspaces.live());++ let sibling = spawn_subagent(&scope, &args, worker("gamma"), &parent_run(), &tx, None, false)+ .await+ .expect("the sibling still starts");+ assert_eq!(bg.live_run_ids(), [sibling.run_id.clone()].into());+ let events: Vec<StreamEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();+ let late_ends = events+ .iter()+ .filter(|ev| matches!(ev, StreamEvent::SubagentEnd { name, .. } if name == "late"))+ .count();+ assert_eq!(late_ends, 1, "exactly one end bracket: {events:?}");+ assert!(+ !events.iter().any(|ev| matches!(+ ev,+ StreamEvent::SubagentStart { name, .. } | StreamEvent::SubagentQueued { name, .. }+ if name == "late"+ )),+ "{events:?}"+ );+ assert!(+ events.iter().any(|ev| matches!(+ ev,+ StreamEvent::SubagentQueued { name, .. } if name == "gamma"+ )),+ "{events:?}"+ );+ bg.abort_all();+ let _ = bg.workspaces.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The later phases' workspaces taken from the plan's own earlier phases,+ /// as `(worker, sibling)` pairs, in phase order.+ #[cfg(feature = "cli")]+ fn later_reuses(plan: &DispatchPlan) -> Vec<(String, String)> {+ use crate::core::agent::child_workspace::WorkspaceRequest;+ plan.phases[1..]+ .iter()+ .flat_map(|p| p.subagents.iter())+ .filter_map(|s| match &s.workspace {+ Some(WorkspaceRequest::Reuse(n)) => Some((s.name.clone(), n.clone())),+ _ => None,+ })+ .collect()+ }++ /// The bug: `general` is taken by an earlier dispatch's worker, so the+ /// plan's phase-0 general is `general-2`, yet phase 1 asking for the+ /// `general` workspace means that sibling, not the stale earlier worker.+ #[cfg(feature = "cli")]+ #[test]+ fn a_later_phase_workspace_naming_an_agent_binds_to_the_earlier_sibling() {+ let plan = parse_dispatch_plan(+ &serde_json::json!({+ "subagents": [+ { "agent": "general", "task": "fix it" },+ { "agent": "review", "task": "review it", "phase": 1, "workspace": "general" }+ ]+ }),+ |name| name == "general",+ )+ .unwrap();+ assert_eq!(later_reuses(&plan), [("review".to_string(), "general-2".to_string())]);+ }++ /// The exact numbered name the plan assigned binds too, and a reference+ /// matching nothing in the plan is left for the session's earlier workers.+ #[cfg(feature = "cli")]+ #[test]+ fn a_later_phase_workspace_binds_by_exact_name_or_falls_through() {+ let plan = parse_dispatch_plan(+ &serde_json::json!({+ "subagents": [+ { "agent": "general", "task": "a" },+ { "agent": "general", "task": "b" },+ { "agent": "review", "task": "c", "phase": 1, "workspace": "general-2" },+ { "agent": "debug", "task": "d", "phase": 1, "workspace": "explore" }+ ]+ }),+ |_| false,+ )+ .unwrap();+ assert_eq!(+ later_reuses(&plan),+ [+ ("review".to_string(), "general-2".to_string()),+ ("debug".to_string(), "explore".to_string()),+ ]+ );+ }++ /// Several earlier-phase items of the agent named, none of them named+ /// exactly that (an earlier dispatch holds `general`): which one is meant+ /// cannot be told, so the whole dispatch is refused before anything runs.+ #[cfg(feature = "cli")]+ #[test]+ fn an_ambiguous_later_phase_workspace_refuses_the_dispatch() {+ let err = parse_dispatch_plan(+ &serde_json::json!({+ "subagents": [+ { "agent": "general", "task": "a" },+ { "agent": "general", "task": "b", "phase": 1 },+ { "agent": "review", "task": "c", "phase": 2, "workspace": "general" }+ ]+ }),+ |name| name == "general",+ )+ .unwrap_err()+ .to_string();+ assert!(+ err.contains("ambiguous") && err.contains("general-2") && err.contains("general-3"),+ "{err}"+ );+ }++ /// A target that is both an earlier sibling's exact worker name and an+ /// agent type several earlier siblings use names that one worker: the+ /// exact name is checked before the agent type, so it binds rather than+ /// being refused as ambiguous.+ #[cfg(feature = "cli")]+ #[test]+ fn an_exact_sibling_name_binds_before_its_agent_type() {+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({+ "subagents": [+ { "agent": "general", "task": "a" },+ { "agent": "general", "task": "b", "phase": 1 },+ { "agent": "review", "task": "c", "phase": 2, "workspace": "general" }+ ]+ }))+ .unwrap();+ assert_eq!(later_reuses(&plan), [("review".to_string(), "general".to_string())]);+ }++ /// The schema is where the model learns that a later phase can name an+ /// earlier phase's agent for its workspace, and address a pending child.+ #[cfg(feature = "cli")]+ #[test]+ fn the_schema_says_how_a_later_phase_names_an_earlier_workspace() {+ let registry = SubagentRegistry::load_one(Path::new("/nonexistent"), SubagentScope::Project);+ let tools = subagent_tool_schemas(®istry, 4);+ let item = &tools[0]["function"]["parameters"]["properties"]["subagents"]["items"]+ ["properties"];+ let workspace = item["workspace"]["description"].as_str().unwrap();+ assert!(+ workspace.contains("earlier phase") && workspace.contains("ambiguous"),+ "{workspace}"+ );+ let phase = item["phase"]["description"].as_str().unwrap();+ assert!(phase.contains("before its phase starts"), "{phase}");+ }++ /// The dispatch result tells the parent whose workspace each later-phase+ /// item will get, since it chose neither name.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn the_dispatch_reports_which_workspace_a_later_phase_reuses() {+ let root = unique_root("reuse-report");+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let held = bg.semaphore.clone().try_acquire_owned().unwrap();+ let plan = parse_dispatch_plan(+ &serde_json::json!({+ "subagents": [+ { "agent": "general", "task": "fix it" },+ { "agent": "general", "task": "check", "phase": 1, "workspace": "general" }+ ]+ }),+ |_| false,+ )+ .unwrap();+ let d = spawn_dispatch_plan(+ &bg,+ bg.generation(),+ &max_par_args(&root),+ plan,+ &parent_run(),+ &tx,+ None,+ )+ .await+ .unwrap();+ assert_eq!(+ d.later_workspaces,+ [("general-2".to_string(), "general".to_string())]+ );+ bg.abort_all();+ drop(held);+ let _ = std::fs::remove_dir_all(&root);+ }+/// F3, end to end through the phase-0 loop: one child starts, the next/// cannot, and the dispatch's `Err` leaves nothing behind -- the started/// child aborted and bracketed, the counters and the plan hold released.@@ -7118,7 +7850,13 @@ pub(crate) mod tests {assert_eq!(shapes[0]["type"], "string");assert_eq!(shapes[1]["type"], "object");assert_eq!(shapes[1]["required"], serde_json::json!(["ref"]));- assert!(ws["description"].as_str().unwrap().contains("\"shared\""));+ let desc = ws["description"].as_str().unwrap();+ assert!(desc.contains("\"shared\""));+ // Worktrees are opt-in, so the default is the shared checkout, and the+ // model is told that writers there can collide.+ assert!(desc.contains("OMIT for the default: one that can write or edit works in your checkout"), "{desc}");+ assert!(desc.contains("--subagent-worktrees") && desc.contains("subagent_worktrees"), "{desc}");+ assert!(desc.contains("overwrite each other"), "{desc}");assert_eq!(item["required"], serde_json::json!(["agent", "task"]));assert_eq!(schemas,@@ -7650,6 +8388,8 @@ pub(crate) mod tests {bg.inner.lock().unwrap().insert("sub-a-1".to_string(), entry);let reply = message_subagent(&bg, "sub-a-1", "look at loop.rs instead").unwrap();+ assert!(matches!(reply, MessageReply::Queued(_)), "{reply:?}");+ let reply = reply.into_text();assert!(reply.contains("sub-a-1"), "the reply names the child: {reply}");let drained = inbox.drain().0;@@ -7782,6 +8522,8 @@ pub(crate) mod tests {g.insert("sub-w-2".into(), b);}let reply = message_subagent(&bg, "w", "late").unwrap();+ assert!(matches!(reply, MessageReply::NotDelivered(_)), "{reply:?}");+ let reply = reply.into_text();assert!(reply.contains("already finished") && reply.contains("sub-w-2"), "{reply}");assert_eq!(ia.drain().0.len() + ib.drain().0.len(), 0);}@@ -7986,7 +8728,8 @@ pub(crate) mod tests {/// A finished child is a different situation from a bad id: the parent's/// next move is a follow-up dispatch, so it gets a plain result saying so- /// rather than an error it might retry.+ /// rather than an error it might retry. The result still says it was not+ /// delivered, so a caller that shows a message as sent can tell.#[tokio::test]async fn a_message_to_a_finished_child_reports_rather_than_errors() {let bg = Arc::new(BackgroundSubagents::default());@@ -7997,6 +8740,8 @@ pub(crate) mod tests {bg.inner.lock().unwrap().insert("sub-a-1".to_string(), entry);let reply = message_subagent(&bg, "sub-a-1", "too late").unwrap();+ assert!(matches!(reply, MessageReply::NotDelivered(_)), "{reply:?}");+ let reply = reply.into_text();assert!(reply.contains("already finished"), "{reply}");assert!(inbox.drain().0.is_empty(), "nothing is queued for a dead child");}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex f44e31c52..0ea5d5cde 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1440,6 +1440,40 @@ pub fn cli_web_search_status() -> serde_json::Value {})}+/// `jan cli worktrees list`: `project`'s subagent checkouts, each with its+/// branch, size and state, then the build cache and trash; JSON with `json`.+/// This process owns no checkout, so one a live session holds reads as in use.+pub fn cli_worktrees_list(project: &str, json: bool) -> String {+ use crate::core::agent::child_workspace as cw;+ let report = cw::list_worktrees(&resolve_project_root(project), None);+ match json {+ true => serde_json::to_string_pretty(&report).unwrap_or_default(),+ false => report.lines().join("\n"),+ }+}++/// `jan cli worktrees prune`: move `project`'s subagent checkouts that are+/// safe to remove (the session-end rule) to the trash, or with `all` delete+/// every one no live session holds, work included; with `build_cache`, then+/// clear the shared build cache. What happened, for the user; `Err` only when the cache was+/// asked for and could not be cleared.+pub fn cli_worktrees_prune(project: &str, build_cache: bool, all: bool) -> Result<String, String> {+ use crate::core::agent::child_workspace as cw;+ let root = resolve_project_root(project);+ let which = if all { cw::Prune::All } else { cw::Prune::Safe };+ let notice = cw::prune_worktrees(&root, None, &which).notice();+ if !build_cache {+ return Ok(notice);+ }+ match cw::clear_build_cache(&root, None) {+ Ok(bytes) => Ok(format!(+ "{notice}\ncleared the subagent build cache, freed {}",+ cw::human_bytes(bytes)+ )),+ Err(why) => Err(format!("{notice}\nbuild cache not cleared: {why}")),+ }+}+/// List plugins installed for a project.pub fn cli_plugin_list(project: &str) -> Vec<crate::core::agent::plugins::InstalledPlugin> {crate::core::agent::plugins::installed(&resolve_project_root(project))@@ -1566,6 +1600,8 @@ fn build_cli_orchestration_args(project_memory: true,subagents_enabled: true,max_parallel_subagents,+ // Filled in by `prepare_agent_session`, which reads the flag and agent.toml.+ subagent_worktrees: false,auto_approve,run_mode: if plan {crate::core::agent::plan::RunMode::Plan@@ -1590,6 +1626,9 @@ fn build_cli_orchestration_args(parent_link: None,// Headless: nobody types mid-run. The TUI installs its own.shell_detach: None,+ // Kept on `args`, which a multi-turn caller reuses, so a `cd` holds+ // into the next turn. The TUI installs its own per conversation.+ shell_cwd: Some(Default::default()),// `--sandbox` only when passed; unset falls through to the project's// `[tools].sandbox` and then the user's global `sandbox`.sandbox,@@ -1815,6 +1854,11 @@ pub struct SessionFlags {/// defers to `[agent].worktree`, then the global `worktree`, then the CLI/// default of off.pub worktree: Option<bool>,+ /// `--subagent-worktrees`: a subagent that can write gets its own worktree+ /// unless it asks for another workspace. `None` (not passed) defers to+ /// `[agent].subagent_worktrees`, then the default of off: it shares the+ /// session's checkout.+ pub subagent_worktrees: Option<bool>,/// `--max-turns`: hard cap on agentic turns, and the only setting that/// ends a run. `None` (not passed) leaves the run unbounded by turns; `0`/// is unbounded as well.@@ -2160,6 +2204,9 @@ fn prepare_agent_session(window_pinned: cfg.agent.context_window.is_some(),});+ args.subagent_worktrees =+ worktree::resolve_subagent_worktrees(flags.subagent_worktrees, cfg.agent.subagent_worktrees);+let session_budget = resolve_session_budget(flags.max_session_tokens,cfg.budget.max_tokens,@@ -3652,10 +3699,13 @@ fn permission_detail(path: Option<String>,justification: Option<String>,) -> String {- let target = command- .map(|c| format!(" ({c})"))- .or_else(|| path.map(|p| format!(" on {p}")))- .unwrap_or_default();+ // A command's path is the directory it runs in (a `cd` moved the shell).+ let target = match (command, path) {+ (Some(c), Some(dir)) => format!(" ({c}) in {dir}"),+ (Some(c), None) => format!(" ({c})"),+ (None, Some(p)) => format!(" on {p}"),+ (None, None) => String::new(),+ };match justification {Some(why) => format!("{target} because: {why}"),None => target,@@ -3708,6 +3758,10 @@ mod tests {" (cargo build) because: fetch crates");assert_eq!(permission_detail(None, None, None), "");+ assert_eq!(+ permission_detail(s("rm -rf build"), s("/repo/pkg"), None),+ " (rm -rf build) in /repo/pkg"+ );}/// A prompt a subagent raised, as the printer receives it: wrapped in@@ -5563,6 +5617,65 @@ mod tests {assert_eq!(note, None);}+ /// `jan cli worktrees list` names what a crashed session left, and+ /// `prune` removes it while `--build-cache` clears the cache; a checkout+ /// a live session holds is listed as in use and survives `--all`.+ #[test]+ fn cli_worktrees_lists_and_prunes_what_no_live_session_holds() {+ use crate::core::agent::child_workspace::Ledger;+ let dir = tempfile::tempdir().unwrap();+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .arg("-C")+ .arg(dir.path())+ .args(["-c", "user.email=t@t", "-c", "user.name=t"])+ .args(args)+ .status()+ .is_ok_and(|s| s.success())+ };+ std::fs::write(dir.path().join("a.txt"), "a\n").unwrap();+ if !(git(&["init", "-q"]) && git(&["add", "a.txt"])+ && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))+ {+ return;+ }+ let root = dunce::canonicalize(dir.path()).unwrap();+ let project = root.to_string_lossy().into_owned();+ let (live, crashed) = (Arc::new(Ledger::default()), Arc::new(Ledger::default()));+ let (held, _) = live.assign(&root, "held", true, None, true).unwrap();+ let (left, _) = crashed.assign(&root, "left", true, None, true).unwrap();+ // Its process died: the lock drops, the checkout stays.+ drop(crashed);+ let target = crate::core::agent::child_workspace::project_worktrees_dir(&root)+ .unwrap()+ .join("cargo-target");+ std::fs::create_dir_all(&target).unwrap();+ std::fs::write(target.join("lib.rlib"), vec![0u8; 2048]).unwrap();++ let listed = cli_worktrees_list(&project, false);+ let json: serde_json::Value =+ serde_json::from_str(&cli_worktrees_list(&project, true)).unwrap();+ let busy_cache = cli_worktrees_prune(&project, true, true);+ let after = (held.root.is_dir(), left.root.exists(), target.is_dir());+ let _ = live.finish_session();+ let cleared = cli_worktrees_prune(&project, true, false);++ assert!(listed.contains("in use by another live jan session"), "{listed}");+ assert!(listed.contains("removable (no work in it)"), "{listed}");+ assert!(listed.contains("build cache 2.0 KB"), "{listed}");+ assert_eq!(json["build_cache_bytes"], 2048);+ let states: Vec<&str> =+ json["checkouts"].as_array().unwrap().iter().filter_map(|c| c["state"].as_str()).collect();+ assert_eq!(states.len(), 2, "{json}");+ assert!(states.contains(&"in_use") && states.contains(&"removable"), "{json}");+ let refused = busy_cache.unwrap_err();+ assert!(refused.starts_with("removed 1 subagent worktree(s)"), "{refused}");+ assert!(refused.contains("build cache not cleared"), "{refused}");+ assert_eq!(after, (true, false, true), "the live one and the cache stay");+ assert!(cleared.is_ok_and(|text| text.contains("freed 2.0 KB")));+ assert!(!target.exists());+ }+/// Asking for a worktree outside a repository is not fatal: the session runs/// in the project directory and is told why.#[test]diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 24738bfa9..a6970bcf2 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -923,6 +923,13 @@ struct Pending {justification: Option<String>,/// Highlighted option in the docked prompt (index into `options()`).selected: usize,+ /// Whether the user moved the highlight with the arrows. Over a subagent's+ /// `/agents` detail the prompt can land mid-sentence, so there Enter only+ /// confirms an option the user picked (see `handle_key_input`).+ picked: bool,+ /// Over a subagent's detail, when the prompt next takes a key; see+ /// `PromptPause::key_lands`.+ pause: PromptPause,/// 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>,@@ -1002,6 +1009,15 @@ impl Pending {vec![Span::styled(lead, dim)],vec![Span::raw(" ")],));+ // A command's path is the directory a `cd` left the shell in: the+ // command runs there, so it is approved with it in view.+ if let (Some(_), Some(dir)) = (&self.command, &self.path) {+ out.extend(gutter_lines(+ wrap_text(dir, Style::new().yellow(), max.saturating_sub(3).max(1)),+ vec![Span::styled("in ", dim)],+ vec![Span::raw(" ")],+ ));+ }// The model's own words, set apart from the command so it is read as// its claim rather than as part of what will run.if let Some(why) = &self.justification {@@ -1044,6 +1060,106 @@ impl Pending {let len = self.options().len() as isize;self.selected = (self.selected as isize + delta).rem_euclid(len) as usize;}++ /// Up/Down on the prompt: over a subagent's detail `detail_arrow`, armed+ /// on Deny; elsewhere it moves and wraps.+ fn arrow(&mut self, delta: isize, over_detail: bool) {+ if over_detail {+ let len = self.options().len();+ self.selected = detail_arrow(self.selected, len, len - 1, delta, self.picked);+ } else {+ self.move_selection(delta);+ }+ self.picked = true;+ }+}++/// How long a prompt over a subagent's detail stays deaf after it appears and+/// after each key it takes. The user was typing for the child when it landed:+/// a recall (Up/Down) and a send (Enter) already on their way must not arm,+/// move and confirm it. The TUI does not ask for the keyboard enhancement+/// that reports repeats as such, so a held key's repeats arrive as ordinary+/// presses, the first after the OS repeat delay (500 ms on GNOME and Windows,+/// 600 ms on KDE, 660 ms for X11's `xset` default). 750 ms outlasts all of+/// those, so holding a key cannot land its first repeat as a second press,+/// and is still short enough that a user who stopped to read barely notices.+const PROMPT_PAUSE: Duration = Duration::from_millis(750);++/// How soon after a press of the same key another counts as its repeat, on a+/// prompt over the detail (`PromptPause::key_lands`). Longer than+/// `PROMPT_PAUSE`, which already covers the defaults, to reach the slower+/// repeat delays users pick (Windows' longest is about 1 s): there a held Up+/// would otherwise arm on Deny and its first repeat move to a grant. Only the+/// first repeat needs it; later ones come every few tens of ms. The cost is+/// that a deliberate second press of the same arrow waits a little longer.+/// A repeat slower still lands each repeat as a fresh press, so the prompt+/// also caps a run of one arrow at one step (`PromptPause::stepped`).+const HELD_KEY_WINDOW: Duration = Duration::from_millis(1200);++/// How long the arrow that last stepped an armed prompt over the detail must+/// be left alone before it steps again (`PromptPause::stepped`). Twice the+/// held-key window: a repeat that slow is past any setting a desktop offers.+const STEP_AGAIN_WINDOW: Duration = HELD_KEY_WINDOW.saturating_mul(2);++/// Over a subagent's detail, when a prompt next takes a key and which key it+/// took last. Both are reset to the default whenever the prompt (re)appears+/// there, so it is deaf until drawn and lands as new.+#[derive(Clone, Copy, Debug, Default)]+struct PromptPause {+ /// When the prompt next takes a key; `None`: not drawn over the detail+ /// yet, so it has not appeared and takes none.+ until: Option<Instant>,+ /// The last key pressed on the prompt and when, to tell a held key's+ /// repeats from a fresh press.+ last_key: Option<(KeyCode, Instant)>,+ /// The arrow that last moved the highlight of the armed prompt, and when+ /// it was last pressed. A key held with a repeat slower than+ /// `HELD_KEY_WINDOW` lands every repeat as a fresh press and would walk+ /// the highlight from the safe row to the widest grant, one step each;+ /// with this, a run of one arrow arms and moves once, and moves again only+ /// after another key or `STEP_AGAIN_WINDOW` without it.+ stepped: Option<(KeyCode, Instant)>,+}++impl PromptPause {+ /// Whether `code`, pressed at `now`, reaches the prompt: only once the+ /// pause has run out since it appeared or took its last key, and only if+ /// it is not the repeat of a held key (the same key again within+ /// `HELD_KEY_WINDOW` of its last press), so holding an arrow only ever+ /// arms, nor the arrow that just moved the armed (`picked`) prompt+ /// (`stepped`). Every key restarts all three, landed or not, so a burst of+ /// presses or a run of repeats keeps the prompt deaf until the user lets go.+ fn key_lands(&mut self, code: KeyCode, now: Instant, picked: bool) -> bool {+ let repeat = self+ .last_key+ .is_some_and(|(last, at)| last == code && now < at + HELD_KEY_WINDOW);+ let stepped = self.stepped.filter(|&(last, _)| last == code);+ let steps_again = stepped.is_some_and(|(_, at)| now < at + STEP_AGAIN_WINDOW);+ let lands = !repeat && !steps_again && self.until.is_some_and(|until| now >= until);+ let arrow = matches!(code, KeyCode::Up | KeyCode::Down);+ self.stepped = (stepped.is_some() || (lands && picked && arrow)).then_some((code, now));+ self.until = Some(now + PROMPT_PAUSE);+ self.last_key = Some((code, now));+ lands+ }++ /// Whether Enter would confirm the highlight at `now` of a prompt armed+ /// with an arrow (`picked`): it has been left alone for the pause.+ fn live(&self, picked: bool, now: Instant) -> bool {+ picked && self.until.is_some_and(|until| now >= until)+ }+}++/// Where Up/Down takes the highlight of a prompt over a subagent's detail,+/// among `len` rows. Up/Down is also the draft's recall key there, so the+/// first arrow only arms the prompt, on `safe` (the row that grants nothing),+/// and later ones stop at the ends rather than wrap: wrapping would carry a+/// second reflex Down from Deny round to Allow once.+fn detail_arrow(selected: usize, len: usize, safe: usize, delta: isize, picked: bool) -> usize {+ if !picked {+ return safe;+ }+ (selected as isize + delta).clamp(0, len as isize - 1) as usize}/// What a highlighted picker row does on Enter.@@ -1100,6 +1216,12 @@ enum PickerKind {ShellDetail,/// `/monitors`: the session's running monitors, each stoppable with `x`.Monitors,+ /// `/worktrees`: this project's subagent checkouts and build cache, with+ /// the prune actions first. Rows come from `App::worktrees`.+ Worktrees,+ /// Removing one checkout that holds work: what would be lost, then keep+ /// or remove. Esc steps back to `Worktrees`.+ WorktreeConfirm,}/// Interactive list overlay (`/resume`, `/login`, `/mcp`, etc.): rows with a@@ -1165,6 +1287,8 @@ impl Picker {PickerKind::BackgroundShells => " background shells ",PickerKind::ShellDetail => " background shell ",PickerKind::Monitors => " monitors ",+ PickerKind::Worktrees => " subagent worktrees ",+ PickerKind::WorktreeConfirm => " remove worktree ",}}@@ -1192,13 +1316,20 @@ impl Picker {PickerKind::PluginSetup => " Type to search Up/Down select Enter set up Esc cancel",PickerKind::PluginConnect => " Up/Down select Enter confirm Esc cancel setup",PickerKind::McpServer => " ↑/↓ select Enter run Esc back",- PickerKind::Agents => " ↑/↓ select Enter view m message x stop Esc close",- PickerKind::AgentDetail => " PgUp/PgDn scroll m message x stop Esc back",+ PickerKind::Agents => " \u{2191}/\u{2193} select Enter view x stop Esc close",+ // The input is live here, so the stop is a chord a typed letter+ // cannot hit. Terse (`^X`, one slot for both ways out) so the+ // location still fits beside it at 80 columns (`dock_line`).+ PickerKind::AgentDetail => {+ " PgUp/PgDn scroll Enter send ^X stop Esc back/^C close"+ }PickerKind::BackgroundShells => {" \u{2191}/\u{2193} select Enter view x stop Esc close"}PickerKind::ShellDetail => " x stop Esc back",PickerKind::Monitors => " \u{2191}/\u{2193} select x stop Esc close",+ PickerKind::Worktrees => " \u{2191}/\u{2193} select Enter run or remove Esc close",+ PickerKind::WorktreeConfirm => " \u{2191}/\u{2193} select Enter choose Esc back",}}}@@ -2501,13 +2632,15 @@ enum RowKind {/// under it, or `• Finished <name> · 3 tools` for a child that ended, with how/// it ended under it. Neither is rewritten as the child runs: the dock and/// `/agents` show where a child stands, and its end is an event of its own.+/// A child a later plan phase holds back reads `Queued <name>` with its+/// phase instead, since the call did not start it.#[derive(Clone)]struct AgentRow {state: ToolState,verb: AgentVerb,/// Each child the row names, with the first line of its task (empty for a/// finished child's row, which has its status instead).- children: Vec<(String, String)>,+ children: Vec<RowChild>,/// Dim text after a finished child's name: its tool count and run time.stats: Option<String>,/// How a finished child ended, then where it worked, under its name.@@ -2515,6 +2648,18 @@ struct AgentRow {workspace: Option<String>,}+/// One child an `AgentRow` names.+#[derive(Clone, Default)]+struct RowChild {+ name: String,+ brief: String,+ /// The plan phase that holds this child back, for a dispatch child past+ /// the call's first phase. Such a child is not started by the call: it+ /// waits for the phase before it, so the row must not say it was+ /// dispatched.+ later_phase: Option<u32>,+}+#[derive(Clone, Copy, PartialEq)]enum AgentVerb {Dispatch,@@ -2522,13 +2667,17 @@ enum AgentVerb {}impl AgentRow {- /// The row's verb: present tense while the dispatch is in flight (or was- /// cut short before it resolved), past tense once it has.- fn verb(&self) -> &'static str {- match (self.verb, self.state) {- (AgentVerb::Dispatch, ToolState::Running | ToolState::Interrupted) => "Dispatching",- (AgentVerb::Dispatch, _) => "Dispatched",- (AgentVerb::Finish, _) => "Finished",+ /// The verb for `child`: present tense while the dispatch is in flight (or+ /// was cut short before it resolved), past tense once it has. A later-phase+ /// child is queued by the call rather than started by it.+ fn verb(&self, child: &RowChild) -> &'static str {+ let in_flight = matches!(self.state, ToolState::Running | ToolState::Interrupted);+ match (self.verb, child.later_phase.is_some(), in_flight) {+ (AgentVerb::Dispatch, false, true) => "Dispatching",+ (AgentVerb::Dispatch, false, false) => "Dispatched",+ (AgentVerb::Dispatch, true, true) => "Queueing",+ (AgentVerb::Dispatch, true, false) => "Queued",+ (AgentVerb::Finish, ..) => "Finished",}}@@ -2539,14 +2688,18 @@ impl AgentRow {let dim = Style::new().fg(theme::muted());// A dispatch that names no child it can parse keeps a bare header, so// the error it is answered with still has a title above it.- let bare = [(String::new(), String::new())];+ let bare = [RowChild::default()];let children = if self.children.is_empty() { &bare[..] } else { &self.children[..] };let mut out = Vec::new();- for (name, brief) in children {- let mut head = vec![Span::styled(self.verb(), Style::new().bold())];+ for child in children {+ let (name, brief) = (&child.name, &child.brief);+ let mut head = vec![Span::styled(self.verb(child), Style::new().bold())];if !name.is_empty() {head.extend([Span::raw(" "), agent_label(name)]);}+ if let Some(p) = child.later_phase {+ head.push(Span::styled(format!(" \u{b7} {}", phase_badge(p)), dim));+ }if let Some(stats) = &self.stats {head.push(Span::styled(format!(" \u{b7} {stats}"), dim));}@@ -2683,12 +2836,23 @@ fn dispatched_workers<'a>(/// the first line of its task. `reported` is the worker names from the/// dispatch result, once it has landed.fn dispatch_row(args: &serde_json::Value, reported: Option<&[String]>) -> AgentRow {- let children = dispatched_workers(args, reported)+ let workers = dispatched_workers(args, reported);+ // Read the way dispatch groups them: a missing `phase` is 0, and only the+ // lowest phase starts with the call; the rest wait their turn.+ let phase = |s: &serde_json::Value| {+ s.get("phase").and_then(|v| v.as_u64()).and_then(|n| u32::try_from(n).ok()).unwrap_or(0)+ };+ let first = workers.iter().map(|(_, s)| phase(s)).min().unwrap_or(0);+ let children = workers.into_iter().map(|(name, s)| {let task = s.get("task").and_then(|v| v.as_str()).unwrap_or("");let brief = task.lines().map(str::trim).find(|l| !l.is_empty());- (name, brief.unwrap_or("").to_string())+ RowChild {+ name,+ brief: brief.unwrap_or("").to_string(),+ later_phase: Some(phase(s)).filter(|p| *p > first),+ }}).collect();AgentRow {@@ -4627,6 +4791,11 @@ struct PendingAsk {custom_input: String,rect: Rect,row_hitboxes: Vec<(u16, usize)>,+ /// Whether the user moved through the options with the arrows; see+ /// `Pending::picked`, which this mirrors for a question.+ picked: bool,+ /// `Pending::pause`, for the question on screen.+ pause: PromptPause,/// When the `ask` loop auto-selects the recommended option if unanswered./// `Some` only when a timeout was configured; drives the live countdown in/// the prompt title. Anchored here at event receipt, a hair before the@@ -4661,6 +4830,8 @@ impl PendingAsk {custom_input: String::new(),rect: Rect::default(),row_hitboxes: Vec::new(),+ picked: false,+ pause: PromptPause::default(),deadline: timeout.map(|d| std::time::Instant::now() + d),}}@@ -4771,14 +4942,35 @@ impl PendingAsk {(self.selected as isize + delta).rem_euclid(self.row_count() as isize) as usize;}+ /// Up/Down on the question; `Pending::arrow`'s rule, armed on "Other",+ /// which only opens the free-text field and so chooses nothing.+ fn arrow(&mut self, delta: isize, over_detail: bool) {+ if over_detail {+ let other = self.question().options.len();+ self.selected = detail_arrow(self.selected, self.row_count(), other, delta, self.picked);+ } else {+ self.move_selection(delta);+ }+ self.picked = true;+ }+fn move_question(&mut self, delta: isize) {let last = self.request.questions.len().saturating_sub(1) as isize;- self.question_index = (self.question_index as isize + delta).clamp(0, last) as usize;- self.selected = 0;+ self.show_question((self.question_index as isize + delta).clamp(0, last) as usize);self.editing_custom = false;self.custom_input.clear();}+ /// A new question is a new prompt: over the detail it opens unarmed and+ /// with the pause restarted, or the second Enter of a double press would+ /// answer it on whatever row it happened to land on.+ fn show_question(&mut self, index: usize) {+ self.question_index = index;+ self.selected = 0;+ self.picked = false;+ self.pause = PromptPause::default();+ }+fn all_answered(&self) -> bool {self.answers.iter()@@ -4839,17 +5031,26 @@ impl PendingAsk {if self.all_answered() {true} else {- self.question_index = self+ let index = self.answers.iter().position(|answer| answer.selected.is_empty() && answer.custom_input.is_none()).unwrap_or(self.question_index);- self.selected = 0;+ self.show_question(index);false}}}+/// A composer's field and its recall, set aside while another owns the input+/// row (`App::parked_composer`).+struct Composer {+ input: String,+ cursor: usize,+ history: Vec<String>,+ recall_pos: Option<usize>,+}+struct App {model: String,/// Fast model for the `smol` role, used by `/goal` evaluation. Defaults to@@ -5046,8 +5247,6 @@ struct App {/// keyboard while open. Holds the setting being edited and any validation/// error; writes go straight to agent.toml on Enter.settings_prompt: Option<SettingsPrompt>,- /// `/agents` message dock: text the user is writing to one running child.- agent_message: Option<AgentMessagePrompt>,/// `/vibe-setting`'s side call mapping the request onto settings, while it/// runs. Awaited by the chat loop; off the render loop like `/context`.vibe_task: Option<JoinHandle<Result<String, String>>>,@@ -5065,6 +5264,12 @@ struct App {/// Set by `/worktree` to ask the loop to gather its report off the render/// loop: it runs git per worktree. Taken once, like `context_request`.worktree_request: bool,+ /// What `/worktrees` asked the loop to do off the render loop (list,+ /// prune, clear the build cache): git and deletes. Taken once; one that+ /// arrives while another runs waits for it.+ worktrees_request: Option<WorktreesJob>,+ /// The last `/worktrees` listing, which its picker rows are built from.+ worktrees: Option<crate::core::agent::child_workspace::WorktreesReport>,/// The provider's execution id for the most recent request that reported/// one, so `/usage` can name something concrete to look up. `None` when no/// request has reported one -- which is the normal case on the default@@ -5089,6 +5294,19 @@ struct App {/// Lines the `/agents` detail is scrolled up from its bottom; 0 follows/// the child as it works. Clamped to the content on every draw.agent_detail_scroll: u16,+ /// The main composer, parked while a subagent's `/agents` detail has the+ /// field: the detail's draft is a message to a child, and must never be+ /// what the next Enter in the main view sends to the main agent. `Some`+ /// exactly while the swap is in effect (see `settle_agent_detail`).+ parked_composer: Option<Composer>,+ /// What was sent to subagents from their detail, for that field's Up/Down+ /// recall. Kept apart from `input_history` so a steer recalled in the main+ /// view cannot go to the main agent.+ steer_history: Vec<String>,+ /// Why the detail's last send went nowhere (a full inbox, a child that+ /// already finished), shown over the draft it kept until the next key.+ /// On the input row rather than in the child's rows, which are its run.+ steer_refusal: Option<String>,/// The background shell the `/shells` inspector is drilled into, or `None`/// at the list. Refreshed off the render path (`refresh_shell_tail`).shell_detail: Option<ShellDetail>,@@ -5252,6 +5470,9 @@ struct App {/// at the next step rather than after the command ends (see/// `OrchestrationArgs::shell_detach`). Kept in step by `sync_shell_detach`.shell_detach: tokio::sync::watch::Sender<bool>,+ /// The conversation's shell directory (`OrchestrationArgs::shell_cwd`),+ /// cleared when the conversation is replaced.+ shell_cwd: tauri_plugin_agent_tools::tools::ShellCwd,/// The session-owned background-subagent registry, on the same terms as/// `shell_set`. Children outlive the run that dispatched them, so their/// panels survive a run end and a completion between runs starts a turn.@@ -5498,6 +5719,19 @@ struct SubagentPanel {/// request -- no completed tool call yet, so a stats line frozen at/// "0 tools" and an activity line stuck on "starting…".active: Option<StartingCall>,+ /// Calls the child has issued whose results have not come back, oldest+ /// first, as `(tool-call id, running label, done label)` from the same+ /// `tool_activity`/`tool_finished` pair the transcript's rows use. One+ /// request can issue several calls that run in parallel and answer in any+ /// order, so each is retired by its own id: the activity line names the+ /// newest call still running until the last sibling answers.+ in_flight: Vec<(String, String, String)>,+ /// The done label of the call that closed the latest batch, so the+ /// activity line flips the verb of what it last named to the past tense+ /// rather than jumping to whichever call happened to be issued last.+ /// Cleared by a new call (or a batch that lost its results), which leaves+ /// the last call made to speak for the child.+ settled: Option<String>,/// True while the dispatch is parked on the parent run's/// `max_parallel_subagents` cap (reported via `SubagentQueued`); flipped/// off when the child's `SubagentStart` arrives. Queued panels render@@ -5538,6 +5772,12 @@ struct SubagentPanel {output_tokens: u64,/// When it ended, so a finished internal agent keeps the duration it took.ended: Option<Instant>,+ /// Messages the user sent it from the `/agents` detail that it has not+ /// taken yet, for the detail's `Pending (n)` cue -- the child's own+ /// version of the main composer's queue count. Settled by each delivery+ /// from the main agent (`AgentMessage`), saturating: the parent agent's+ /// own `message_subagent` calls share the inbox and are delivered too.+ steers_pending: usize,}/// Most rows a child's transcript keeps. The detail view opens on the tail,@@ -5581,6 +5821,8 @@ impl SubagentPanel {total_cached_tokens: 0,cache_reported: false,active: None,+ in_flight: Vec::new(),+ settled: None,queued: false,waiting: 0,pending: false,@@ -5593,6 +5835,23 @@ impl SubagentPanel {model: None,output_tokens: 0,ended: None,+ steers_pending: 0,+ }+ }++ /// The handle `/agents` addresses this child by, for its rows, its detail+ /// and the core's `stop_subagent` / `message_subagent`. A started or+ /// queued child is its `run_id`, so a re-dispatched name can never+ /// redirect a stop or a message to a newer run. A pending later-phase+ /// child has no run id yet, only its worker name -- which the core checks+ /// against the plan's pending table before any running child, and which+ /// `plan_dispatch` reserves for the whole session, so it names this child+ /// and no other. Promotion swaps the handle back (`readdress_pending`).+ fn target(&self) -> &str {+ if self.pending {+ &self.name+ } else {+ &self.run_id}}@@ -5662,6 +5921,8 @@ impl SubagentPanel {.is_some_and(|m| m.status == session_log::RunStatus::Finished);t.settle(!finished);self.active = None;+ self.in_flight.clear();+ self.settled = None;}/// A finished child rebuilt from its journal entry, which keeps only the@@ -5754,7 +6015,9 @@ enum AgentStatus {Running,/// Parked on the `max_parallel_subagents` cap, at this queue position.Queued(u32),- /// A later-phase child waiting on the phase before it.+ /// A later-phase child, announced by its plan but not started: it is+ /// queued behind the phase before it. Reads as queued, with its phase, so+ /// it is never taken for a child that is already running.Waiting(Option<u32>),/// Started, but idle until a command it backgrounded reports back.Parked,@@ -5774,8 +6037,10 @@ impl AgentStatus {match self {AgentStatus::Running => word("Running", Style::new().fg(theme::accent()).bold()),AgentStatus::Queued(n) => word(&format!("Queued ({n})"), dim),- AgentStatus::Waiting(Some(p)) => word(&format!("Waiting (phase {p})"), dim),- AgentStatus::Waiting(None) => word("Waiting", dim),+ AgentStatus::Waiting(Some(p)) => {+ word(&format!("Queued \u{b7} {}", phase_badge(*p)), dim)+ }+ AgentStatus::Waiting(None) => word("Queued", dim),AgentStatus::Parked => word("Waiting on background work", dim),AgentStatus::Completed(preview) => {let mut out = word("Completed", Style::new().fg(theme::success()));@@ -5791,6 +6056,12 @@ impl AgentStatus {}}+/// A plan phase as every surface names it: the model's own `phase` key, so+/// the number matches the dispatch call that set it.+fn phase_badge(phase: u32) -> String {+ format!("phase {phase}")+}+/// A subagent's name as every surface shows it.fn agent_label(name: &str) -> Span<'static> {Span::styled(name.to_string(), Style::new().fg(theme::accent()).bold())@@ -5815,7 +6086,7 @@ fn agent_stats(panel: &SubagentPanel, context_window: u64) -> Vec<Span<'static>>// A running later-phase child keeps its phase, so the dependent stage// stays visible past the wait.if let Some(p) = panel.phase {- parts.push(format!("phase {p}"));+ parts.push(phase_badge(p));}// `context_window` arrives as 0 when the session has disproven it, and the// share is clamped: a child on a model with a larger window than the@@ -5866,10 +6137,12 @@ fn agent_name_spans(panel: &SubagentPanel) -> Vec<Span<'static>> {}/// What a running subagent is doing, verb-first like a transcript row: the call-/// it is building, else the last call it made with a dim ` ×N` for a short run-/// of the same call. A run of `STUCK_REPEAT_THRESHOLD` reads as a loop and is-/// flagged as one, even while the newest copy is still streaming. Empty for a-/// child that has not started.+/// it is building, else the newest call still running in the continuous tense+/// (so a parallel batch reads as running until its last call answers), else+/// the call it last finished in the past tense, with a dim repeat count for a+/// short run of the same call. A run of `STUCK_REPEAT_THRESHOLD` reads as a+/// loop and is flagged as one, even while the newest copy is still streaming.+/// Empty for a child that has not started.fn agent_activity(panel: &mut SubagentPanel) -> Vec<Span<'static>> {if panel.queued || panel.pending {return Vec::new();@@ -5887,18 +6160,23 @@ fn agent_activity(panel: &mut SubagentPanel) -> Vec<Span<'static>> {}return out;}+ let accent = Style::new().fg(theme::accent()).dim();if let Some(call) = panel.active.as_mut() {- return vec![Span::styled(- call.activity_label(),- Style::new().fg(theme::accent()).dim(),- )];- }- match last {- Some(last) if repeats > 1 => vec![- Span::styled(last, dim),+ return vec![Span::styled(call.activity_label(), accent)];+ }+ if let Some((_, running, _)) = panel.in_flight.last() {+ return vec![Span::styled(single_line(running), accent)];+ }+ // The repeat count belongs to the last call made, so it rides only on a+ // settled label that is that call.+ let settled = panel.settled.as_deref().map(single_line);+ let repeated = repeats > 1 && (settled.is_none() || settled == last);+ match settled.or(last) {+ Some(done) if repeated => vec![+ Span::styled(done, dim),Span::styled(format!(" \u{d7}{repeats}"), dim),],- Some(last) => vec![Span::styled(last, dim)],+ Some(done) => vec![Span::styled(done, dim)],None => vec![Span::styled("starting\u{2026}", dim)],}}@@ -5975,6 +6253,15 @@ enum SnapshotJob {},}+/// Which list holds the child the `/agents` detail shows (see+/// `App::detail_at`), by index, so the shared and the mutable lookups agree.+#[derive(Clone, Copy)]+enum DetailAt {+ Live(usize),+ Block(usize),+ Internal(usize),+}+/// `(repo, parent sha, commit message, thread id, changed paths)` resolved/// from a queued [`SnapshotJob`], ready to hand to `git::snapshot`.type SnapshotInputs = (PathBuf, Option<String>, String, String, Vec<PathBuf>);@@ -6064,18 +6351,22 @@ impl App {model_picker: None,login: None,settings_prompt: None,- agent_message: None,vibe_task: None,vibe_confirm: None,readout: None,context_request: false,worktree_request: false,+ worktrees_request: None,+ worktrees: None,last_execution_id: None,reported_usage_request: None,mcp_prompt: None,mcp_detail: None,agent_detail: None,agent_detail_scroll: 0,+ parked_composer: None,+ steer_history: Vec::new(),+ steer_refusal: None,shell_detail: None,mcp_job_request: None,mcp_auth: None,@@ -6129,6 +6420,7 @@ impl App {monitor_set: Arc::new(MonitorSet::new()),shell_set: Arc::new(crate::core::agent::bg_shell::BackgroundShells::default()),shell_detach: tokio::sync::watch::Sender::default(),+ shell_cwd: Default::default(),subagent_set: Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,)),@@ -6293,6 +6585,8 @@ impl App {self.stop_monitors();// Pings for work whose conversation is gone have no turn to join.self.shell_set.take_notices();+ // A new conversation starts in the project root, as its prompt says.+ *self.shell_cwd.lock().unwrap() = None;self.transcript.expanded.clear();self.transcript.reveal = None;self.find = None;@@ -6426,6 +6720,8 @@ impl App {/// streaming tool-call throbbers, which all animate in the dock/tail;/// - an active `/goal`, whose header chip counts seconds;/// - an `ask` with a timeout, whose title counts down;+ /// - a prompt over a subagent's detail in its pause, whose hints name+ /// Enter once it runs out;/// - the `copied N lines` notice until it expires;/// - a closed todo plan until it hides itself;/// - a drag-select, which auto-scrolls while held past an edge.@@ -6451,6 +6747,7 @@ impl App {.as_ref().is_some_and(|g| g.status == crate::core::agent::goal::GoalStatus::Active)|| self.ask_queue.iter().any(|a| a.deadline.is_some())+ || self.prompt_pausing()|| self.copy_notice().is_some()|| (self.todos_closed_at.is_some() && !self.todos_expired())|| self.selection.as_ref().is_some_and(|s| s.dragging)@@ -6614,6 +6911,7 @@ impl App {.transcript.settle(outcome != SubagentOutcome::Finished);panel.active = None;+ panel.in_flight.clear();// Jan's own agent reports in its own one-line note (`memory tidied:`),// so it gets no row here and is kept for `/agents` alone.if panel.internal {@@ -6657,7 +6955,10 @@ impl App {self.transcript.push_row(RowKind::Agent(Box::new(AgentRow {state,verb: AgentVerb::Finish,- children: vec![(name, String::new())],+ children: vec![RowChild {+ name,+ ..RowChild::default()+ }],stats: Some(stats),status: Some(panel.status(Some(&outcome))),workspace: panel.workspace.clone(),@@ -6774,6 +7075,181 @@ impl App {self.monitors.clear();}+ /// A pending child `name` was just promoted to `run_id`: a `/agents`+ /// detail opened on it while it waited holds its name, and now follows the+ /// run id instead (see `SubagentPanel::target`), so it keeps pointing at+ /// this exact run -- and so does what the user types into it.+ fn readdress_pending(&mut self, name: &str, run_id: &str) {+ if self.agent_detail.as_deref() == Some(name) {+ self.agent_detail = Some(run_id.to_string());+ }+ }++ /// The `/agents` detail is open: the composer is aimed at that child.+ fn agent_detail_open(&self) -> bool {+ self.picker.as_ref().is_some_and(|p| p.kind == PickerKind::AgentDetail)+ }++ /// Drill the open `/agents` list into `target`'s detail, handing the field+ /// to it: the main composer is parked and the detail's own, empty, takes+ /// its place, with the steer recall.+ fn enter_agent_detail(&mut self, target: String) {+ let Some(picker) = self.picker.as_mut() else {+ return;+ };+ picker.kind = PickerKind::AgentDetail;+ if self.parked_composer.is_none() {+ let history = std::mem::take(&mut self.steer_history);+ self.parked_composer = Some(Composer {+ input: std::mem::take(&mut self.input),+ cursor: self.cursor,+ history: std::mem::replace(&mut self.input_history, history),+ recall_pos: self.recall_pos,+ });+ self.input_clear();+ }+ self.agent_detail = Some(target);+ self.agent_detail_scroll = 0;+ self.steer_refusal = None;+ }++ /// Give the field back to the main composer once the detail is no longer+ /// on screen, however it went: Esc, Ctrl-C, or another screen replacing+ /// it (a plugin listing that lands meanwhile). Run ahead of every key,+ /// paste and frame, so no path can leave a child's draft where the main+ /// agent's next message goes. A draft left in the detail is kept in the+ /// steer recall.+ fn settle_agent_detail(&mut self) {+ if self.agent_detail_open() {+ return;+ }+ self.agent_detail = None;+ self.agent_detail_scroll = 0;+ self.steer_refusal = None;+ let Some(main) = self.parked_composer.take() else {+ return;+ };+ self.record_draft();+ self.steer_history = std::mem::replace(&mut self.input_history, main.history);+ self.set_input(main.input);+ self.cursor = main.cursor.min(self.input.len());+ self.recall_pos = main.recall_pos;+ }++ /// Leave the open detail, for the `/agents` list (`to_list`) or the main+ /// view, handing the field back to the main composer.+ fn leave_agent_detail(&mut self, to_list: bool) {+ match self.picker.as_mut() {+ Some(picker) if to_list => picker.kind = PickerKind::Agents,+ _ => self.picker = None,+ }+ self.settle_agent_detail();+ }++ /// A permission request or an `ask` waits over the open detail. It owns+ /// the keyboard there, but the user was typing a message when it landed,+ /// so only an option picked with the arrows answers it.+ fn prompt_over_detail(&self) -> bool {+ self.agent_detail_open() && (!self.pending_queue.is_empty() || !self.ask_queue.is_empty())+ }++ /// The prompt on screen (the front ask, else the front permission request,+ /// as `draw_queued_prompt` picks): when it next takes a key over the+ /// detail, and whether it was armed with an arrow.+ fn front_prompt_state(&self) -> Option<(PromptPause, bool)> {+ match self.ask_queue.front() {+ Some(ask) => Some((ask.pause, ask.picked)),+ None => self.pending_queue.front().map(|p| (p.pause, p.picked)),+ }+ }++ /// Whether Enter would confirm the prompt on screen now+ /// (`PromptPause::live`).+ fn front_prompt_live(&self) -> bool {+ self.front_prompt_state()+ .is_some_and(|(pause, picked)| pause.live(picked, Instant::now()))+ }++ /// A prompt over the detail is still in its pause. The footer names Enter+ /// only once it runs out, so frames keep coming until then (`animating`).+ fn prompt_pausing(&self) -> bool {+ self.prompt_over_detail()+ && self+ .front_prompt_state()+ .and_then(|(pause, _)| pause.until)+ .is_some_and(|until| Instant::now() < until)+ }++ /// Lines the view on screen is scrolled up from its bottom: the open+ /// subagent detail's, else the main transcript's. One field per view, so+ /// leaving the detail finds the main transcript where it was; 0 follows.+ fn view_scroll(&mut self) -> &mut u16 {+ if self.agent_detail_open() {+ &mut self.agent_detail_scroll+ } else {+ &mut self.scrollback+ }+ }++ /// Where the child `agent_detail` names is kept. A live child is found by+ /// its `target` (a pending one has only its name); a finished one in its+ /// summary row's block, which keeps it, or among Jan's own agents.+ fn detail_at(&self) -> Option<DetailAt> {+ let id = self.agent_detail.as_deref()?;+ if let Some(i) = self.subagents.iter().position(|p| p.target() == id) {+ return Some(DetailAt::Live(i));+ }+ let blocks = &self.transcript.subagent_blocks;+ if let Some(i) = blocks.iter().position(|b| b.panel.run_id == id) {+ return Some(DetailAt::Block(i));+ }+ let internal = &self.internal_agents;+ internal.iter().position(|a| a.panel.run_id == id).map(DetailAt::Internal)+ }++ /// The child the `/agents` detail shows, with its outcome once it ended.+ fn detail_panel(&self) -> Option<(&SubagentPanel, Option<&SubagentOutcome>)> {+ Some(match self.detail_at()? {+ DetailAt::Live(i) => (&self.subagents[i], None),+ DetailAt::Block(i) => {+ let block = &self.transcript.subagent_blocks[i];+ (&block.panel, Some(&block.outcome))+ }+ DetailAt::Internal(i) => {+ let agent = &self.internal_agents[i];+ (&agent.panel, agent.outcome.as_ref())+ }+ })+ }++ /// `detail_panel`, for drawing: laying a panel out caches into it.+ fn detail_panel_mut(&mut self) -> Option<(&mut SubagentPanel, Option<&SubagentOutcome>)> {+ Some(match self.detail_at()? {+ DetailAt::Live(i) => (&mut self.subagents[i], None),+ DetailAt::Block(i) => {+ let block = &mut self.transcript.subagent_blocks[i];+ (&mut block.panel, Some(&block.outcome))+ }+ DetailAt::Internal(i) => {+ let agent = &mut self.internal_agents[i];+ (&mut agent.panel, agent.outcome.as_ref())+ }+ })+ }++ /// The child the open `/agents` detail shows, if it can still be steered:+ /// `None` once it has ended, and for Jan's own agents, which no inbox+ /// reaches.+ fn steerable_detail_child(&self) -> Option<&SubagentPanel> {+ if !self.agent_detail_open() {+ return None;+ }+ match self.detail_panel()? {+ (panel, None) if !panel.internal => Some(panel),+ _ => None,+ }+ }+/// Abort every background child and undock its panel. Cancelling stops the/// whole session's background work, not just the turn in flight: children/// used to die with the run through `AbortOnDrop`, and a session-owned@@ -6973,8 +7449,6 @@ impl App {Some("answer the question above")} else if self.settings_prompt.is_some() {Some("edit the setting above")- } else if self.agent_message.is_some() {- Some("finish the message to the subagent above")} else if self.vibe_confirm.is_some() {Some("answer the proposal above")} else if self.mcp_prompt.is_some()@@ -7259,7 +7733,9 @@ impl App {/// so the slash popup must not open: a pending permission request (drawn/// first, and its Up/Down/Enter/Esc answer it) or a pending `ask`.fn slash_popup_blocked(&self) -> bool {- !self.pending_queue.is_empty() || !self.ask_queue.is_empty()+ // In a subagent's detail the field is a message to that child, which+ // runs no commands: a `/word` there is text to send.+ !self.pending_queue.is_empty() || !self.ask_queue.is_empty() || self.agent_detail_open()}/// The `[skills].enabled` whitelist the slash popup filters by. Every@@ -7540,7 +8016,9 @@ impl App {fn refresh_path_hints(&mut self) {#[cfg(test)]tally(&PATH_HINT_REFRESHES);- if self.path_hint_dismissed || !self.accepts_input() {+ // A message to a child is sent verbatim, so an `@path` there is never+ // expanded and completing one would only mislead.+ if self.path_hint_dismissed || !self.accepts_input() || self.agent_detail_open() {self.path_hints.clear();return;}@@ -8878,6 +9356,8 @@ impl App {offers_always,justification,selected: 0,+ picked: false,+ pause: PromptPause::default(),subagent: None,});self.publish_agent_status();@@ -8960,6 +9440,8 @@ impl App {if let Some(t) = task {panel.task = t;}+ let run_id = panel.run_id.clone();+ self.readdress_pending(&name, &run_id);} else {// Jan's own agent never touches the conversation, so the// prose it starts beside is not committed early for it.@@ -8999,6 +9481,8 @@ impl App {if let Some(t) = task {panel.task = t;}+ let run_id = panel.run_id.clone();+ self.readdress_pending(&name, &run_id);} else {self.subagents.push(SubagentPanel {queued: true,@@ -9013,8 +9497,19 @@ impl App {error,} => {// A child with no panel (its start never reached this screen)- // still gets its row, from an empty one.- let panel = match self.subagents.iter().position(|p| p.run_id == run_id) {+ // still gets its row, from an empty one. A later-phase child+ // stopped before it started ends under a run id its panel never+ // learned (only a start or queue names it), so an unknown id+ // falls back to the waiting panel of that name -- else its row+ // waits on its phase forever.+ let at = self+ .subagents+ .iter()+ .position(|p| p.run_id == run_id)+ .or_else(|| {+ self.subagents.iter().position(|p| p.pending && p.name == name)+ });+ let panel = match at {Some(at) => self.subagents.remove(at),None => SubagentPanel::new(run_id.clone(), name, String::new()),};@@ -9195,7 +9690,10 @@ impl App {panel.active = None;}// Stored untruncated; the dock clamps it to the draw width.- panel.record_call(&tool, &args, tool_finished(&tool, &args));+ let done = tool_finished(&tool, &args);+ panel.record_call(&tool, &args, done.clone());+ panel.in_flight.push((id.clone(), tool_activity(&tool, &args), done));+ panel.settled = None;panel.transcript.tool_call(id, &tool, &args);panel.transcript.cap_rows(CHILD_ROWS_MAX);}@@ -9218,6 +9716,12 @@ impl App {diff,} => {if let Some(panel) = panel {+ let at = panel.in_flight.iter().position(|(call, ..)| *call == id);+ if let Some((_, _, done)) = at.map(|i| panel.in_flight.remove(i)) {+ if panel.in_flight.is_empty() {+ panel.settled = Some(done);+ }+ }truncate_head(&mut content, CHILD_RESULT_MAX);panel.transcript.tool_result(id, content, is_error, diff);panel.transcript.cap_rows(CHILD_ROWS_MAX);@@ -9265,6 +9769,8 @@ impl App {offers_always,justification,selected: 0,+ picked: false,+ pause: PromptPause::default(),subagent: Some(name.to_string()),});self.publish_agent_status();@@ -9275,6 +9781,10 @@ impl App {if let Some(panel) = panel {// A request is the child working again, so a park is over.panel.parked = false;+ // A request only goes out once every call of the last batch+ // has answered, so a call still listed lost its result and+ // would otherwise read as running for the rest of the run.+ panel.in_flight.clear();panel.requests += 1;panel.transcript.step();panel.transcript.cap_rows(CHILD_ROWS_MAX);@@ -9316,6 +9826,9 @@ impl App {// delivery adds nothing there.StreamEvent::AgentMessage { from, to, text } => {if let Some(panel) = panel {+ if from == MAIN_AGENT {+ panel.steers_pending = panel.steers_pending.saturating_sub(1);+ }panel.transcript.agent_message(name, &from, &to, &text);panel.transcript.cap_rows(CHILD_ROWS_MAX);}@@ -13933,6 +14446,10 @@ pub async fn run(// typed message is not held until a long build ends.let (shell_detach, detach_signal) = tokio::sync::watch::channel(false);args.shell_detach = Some(detach_signal);+ // The shell's directory is the conversation's too: a `cd` holds into the+ // next turn, and a new conversation starts back in the project root.+ let shell_cwd = tauri_plugin_agent_tools::tools::ShellCwd::default();+ args.shell_cwd = Some(shell_cwd.clone());let subagent_set = Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(args.max_parallel_subagents,));@@ -14027,6 +14544,7 @@ pub async fn run(app.send_reasoning = send_reasoning;app.monitor_set = monitor_set;app.shell_set = shell_set;+ app.shell_cwd = shell_cwd;app.shell_detach = shell_detach;app.subagent_set = subagent_set;// Weak, so exit's drain never waits on a startup sweep still fetching.@@ -14084,6 +14602,10 @@ pub async fn run(if let Some(note) = project_instructions_note(&app.project_root) {app.note(¬e);}+ let instructions = crate::core::agent::context::project_context_files(&app.project_root);+ if let Some(warning) = instructions_size_warning(&instructions) {+ app.system(Level::Warn, &warning);+ }// A modified key the terminal is dropping looks like a bug in the composer,// so say so once, and only where a config file proves it is unconfigured// (see `terminal_setup::setup_hint`): the note disappears on its own once@@ -14395,6 +14917,9 @@ async fn chat_loop<B: Backend>(// `/worktree` gathering its report: git per worktree, so on the blocking// pool. One at a time.let mut worktree_task: Option<tokio::task::JoinHandle<WorktreeReport>> = None;+ // `/worktrees` listing or pruning: git and deletes, so on the blocking+ // pool. One at a time.+ let mut worktrees_task: Option<tokio::task::JoinHandle<WorktreesDone>> = None;type ReportedUsageResult = (super::tokamak::usage::Query,Result<super::tokamak::usage::Payload, super::tokamak::usage::UsageError>,@@ -14560,6 +15085,11 @@ async fn chat_loop<B: Backend>(app.worktree_request = false;worktree_task = Some(spawn_worktree_report(app));}+ if worktrees_task.is_none() {+ if let Some(job) = app.worktrees_request.take() {+ worktrees_task = Some(spawn_worktrees_job(app, job));+ }+ }// `/usage <view>` asked for an account read. It is a network call, so// it runs off the render loop exactly like `/context`'s report: one at// a time, with the overlay sitting on its loading state until it lands.@@ -14911,9 +15441,12 @@ async fn chat_loop<B: Backend>(// landing after the overlay was closed must not reopen it.finish_context_report(app, report);}- Some(report) = await_worktree_report(&mut worktree_task) => {+ Some(report) = await_job(&mut worktree_task) => {finish_worktree_report(app, report);}+ Some(done) = await_job(&mut worktrees_task) => {+ finish_worktrees_job(app, done);+ }Some(kept) = app.cleanup_rx.recv() => {app.notice(&kept, None);}@@ -15061,11 +15594,13 @@ fn handle_mouse(app: &mut App, mouse: MouseEvent) {match mouse.kind {MouseEventKind::ScrollUp => {app.clear_selection();- app.scrollback = app.scrollback.saturating_add(1);+ let scroll = app.view_scroll();+ *scroll = scroll.saturating_add(1);}MouseEventKind::ScrollDown => {app.clear_selection();- app.scrollback = app.scrollback.saturating_sub(1);+ let scroll = app.view_scroll();+ *scroll = scroll.saturating_sub(1);}MouseEventKind::Down(MouseButton::Left) => {app.copy_armed = false;@@ -15397,6 +15932,22 @@ async fn handle_ask_key(app.request_repaint();return true;}+ let over_detail = app.agent_detail_open();+ // While the free-text answer is open the cursor keys are its own, so only+ // the scroll keys reach the draft behind it.+ let editing = app.ask_queue.front().is_some_and(|ask| ask.editing_custom);+ // Over the detail Esc in the free-text field closes just the field, back+ // to the options: leaving the detail would hide a question the user was+ // halfway through answering.+ if over_detail && editing && key.code == KeyCode::Esc {+ let ask = app.ask_queue.front_mut().expect("checked non-empty above");+ ask.editing_custom = false;+ ask.custom_input.clear();+ return true;+ }+ if over_detail && detail_key_under_prompt(&key, !editing) {+ return false;+ }if ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')) {crate::core::agent::interaction::cancel_all(registry).await;app.ask_queue.clear();@@ -15419,16 +15970,21 @@ async fn handle_ask_key(KeyCode::Char(ch) if !ctrl => ask.custom_input.push(ch),_ => {}}- } else {+ } else if !over_detail || ask.pause.key_lands(key.code, Instant::now(), ask.picked) {+ // Over the detail the user may be mid-message: a space or Enter+ // typed for it must not choose an option they never picked, nor+ // open the free-text field that the next message would fill.+ let armed = !over_detail || ask.picked;match key.code {- KeyCode::Up => ask.move_selection(-1),- KeyCode::Down => ask.move_selection(1),+ KeyCode::Up => ask.arrow(-1, over_detail),+ KeyCode::Down => ask.arrow(1, over_detail),+ // Over the detail Left/Right went to the draft above.KeyCode::Left => ask.move_question(-1),KeyCode::Right => ask.move_question(1),- KeyCode::Char(' ') if ask.question().multi => {+ KeyCode::Char(' ') if ask.question().multi && armed => {submit = ask.choose();}- KeyCode::Enter => submit = ask.choose(),+ KeyCode::Enter if armed => submit = ask.choose(),_ => {}}}@@ -15447,6 +16003,7 @@ fn route_paste_event(app: &mut App, event: Event) {let Event::Paste(text) = event else {return;};+ app.settle_agent_detail();if let Some(prompt) = app.account_login.as_mut() {// A pasted redirect/code belongs to the OAuth prompt, not chat.prompt.paste(&text);@@ -15464,8 +16021,6 @@ fn route_paste_event(app: &mut App, event: Event) {picker.refresh_search();} else if let Some(prompt) = app.settings_prompt.as_mut() {prompt.paste(&text);- } else if let Some(prompt) = app.agent_message.as_mut() {- prompt.input.push_str(&text);} else if let Some(proposal) = app.vibe_confirm.as_mut() {proposal.paste(&text);} else if let Some(prompt) = app.mcp_prompt.as_mut() {@@ -15476,6 +16031,12 @@ fn route_paste_event(app: &mut App, event: Event) {prompt.paste(&text);} else if !app.ask_queue.is_empty() {handle_ask_paste(app, &text);+ } else if app.picker.is_some()+ && (app.steerable_detail_child().is_none() || app.prompt_over_detail())+ {+ // Under a picker the field reads "selecting...", and a detail that+ // cannot send (or waits on a prompt) takes no typing: a paste there+ // would sit unseen in the composer and later go out as a message.} else {app.input_insert_str(&text);}@@ -15532,9 +16093,16 @@ async fn handle_ask_mouse(if app.blocking_dock().is_some() {return false;}+ let over_detail = app.agent_detail_open();let Some(ask) = app.ask_queue.front_mut() else {return false;};+ // The wheel still scrolls the child's run under the question, so the user+ // can read what it did before answering (`detail_key_under_prompt`).+ let wheel = matches!(mouse.kind, MouseEventKind::ScrollUp | MouseEventKind::ScrollDown);+ if over_detail && wheel {+ return false;+ }if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {return true;}@@ -15553,6 +16121,9 @@ async fn handle_ask_mouse(else {return true;};+ // A click answers at once, even over the detail where keys wait out a+ // pause and need an arrow first (`PromptPause`): those guard against keys+ // already on their way for the draft, and a click on a row is aimed.ask.selected = selected;let submit = ask.choose();if submit {@@ -16149,6 +16720,9 @@ async fn handle_key_input(if key.kind != KeyEventKind::Press {return;}+ // Whatever replaced the detail since the last key, the main composer is+ // what this key edits.+ app.settle_agent_detail();let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);@@ -16241,11 +16815,6 @@ async fn handle_key_input(handle_settings_key(app, key, ctrl);return;}- // So does the `/agents` message dock, drawn over the inspector it came from.- if app.agent_message.is_some() {- handle_agent_message_key(app, key, ctrl);- return;- }// So does `/vibe-setting`'s confirm dock: nothing is written without it.if app.vibe_confirm.is_some() {vibe_setting::handle_key(app, key, ctrl);@@ -16275,8 +16844,14 @@ async fn handle_key_input(// unanswered prompt. Several subagents can have requests queued at once// (see `pending_queue`), so cancelling denies all of them, not just the// one on screen. Quitting itself stays with the two-press exit below.- if !app.pending_queue.is_empty() {- if ctrl_c || ctrl_d {+ // Over a subagent's detail the user may be mid-message when the prompt+ // lands, so the letter keys and an Enter the user never aimed at it must+ // not answer it, and the detail's own keys (`detail_key_under_prompt`)+ // pass it by: Esc/Ctrl-C step out rather than denying and cancelling the+ // main run, and the draft and the child's run stay reachable.+ let over_detail = app.agent_detail_open();+ if !app.pending_queue.is_empty() && !(over_detail && detail_key_under_prompt(&key, true)) {+ if !over_detail && (ctrl_c || ctrl_d) {for pending in app.pending_queue.drain(..) {deny(registry, &pending.request_id).await;}@@ -16288,16 +16863,24 @@ async fn handle_key_input(.pending_queue.front_mut().expect("checked non-empty above");+ // Keys already on their way when the prompt landed over the detail,+ // or pressed in a burst, fall on it without effect.+ if over_detail && !pending.pause.key_lands(key.code, Instant::now(), pending.picked) {+ return;+ }let decision = match key.code {KeyCode::Up => {- pending.move_selection(-1);+ pending.arrow(-1, over_detail);None}KeyCode::Down => {- pending.move_selection(1);+ pending.arrow(1, over_detail);None}- KeyCode::Enter => Some(pending.options()[pending.selected].0),+ KeyCode::Enter if !over_detail || pending.picked => {+ Some(pending.options()[pending.selected].0)+ }+ _ if over_detail => None,KeyCode::Char('y') | KeyCode::Char('Y') => Some(PermissionDecision::AllowOnce),KeyCode::Char('a') | KeyCode::Char('A') if pending.offers_always => {Some(PermissionDecision::AllowAlways)@@ -16338,9 +16921,17 @@ async fn handle_key_input(// Ctrl-C and Ctrl-D both cancel a run, clear a draft, or (on a blank idle// composer, and only on a second press) quit.- // An open picker owns navigation/Enter/Esc. One-shot pickers (thread/model)- // act and close; the `/mcp` picker toggles the selected row in place.- if let Some(picker) = app.picker.as_mut() {+ // A subagent's `/agents` detail is not a list: its keys are the main+ // view's, aimed at the child. What it does not take falls through to the+ // composer's editing keys below, so typing (`m`, `x`, `q` included) types.+ if app.agent_detail_open() {+ if handle_agent_detail_key(app, key, ctrl, newline) {+ return;+ }+ // Any other open picker owns navigation/Enter/Esc. One-shot pickers+ // (thread/model) act and close; the `/mcp` picker toggles the selected row+ // in place.+ } else if let Some(picker) = app.picker.as_mut() {match key.code {KeyCode::Char(ch) if picker.search.is_some() && !ctrl && !alt && !sup => {if let Some(search) = picker.search.as_mut() {@@ -16395,65 +16986,44 @@ async fn handle_key_input(run_mcp_action(app, &action, mcp_servers).await;}// `/agents`: Enter drills into the selected subagent's detail.+ // A pending child opens too: its header says which phase it waits+ // on, and the detail follows it once it starts.KeyCode::Enter if picker.kind == PickerKind::Agents => {- let run_id = picker+ let target = picker.items.get(picker.selected).map(|i| i.value.clone()).unwrap_or_default();// The watermark row (no subagents running) has no id to open.- if run_id.is_empty() {+ if target.is_empty() {return;}- picker.kind = PickerKind::AgentDetail;- replay_finished_agent(app, &run_id);- app.agent_detail = Some(run_id);- app.agent_detail_scroll = 0;- }- // The detail scrolls like the main body: PgUp/PgDn by a page's- // worth, Home to the start of the run, End back to following it.- KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End- if picker.kind == PickerKind::AgentDetail =>- {- let at = app.agent_detail_scroll;- app.agent_detail_scroll = match key.code {- KeyCode::PageUp => at.saturating_add(10),- KeyCode::PageDown => at.saturating_sub(10),- KeyCode::Home => u16::MAX,- _ => 0,- };+ replay_finished_agent(app, &target);+ app.enter_agent_detail(target);+ }+ // `/agents`: `x` stops the selected child through the registry+ // call the parent agent's `stop_subagent` tool makes. Its detail+ // stops it with Ctrl-X (`handle_agent_detail_key`).+ KeyCode::Char('x') if !ctrl && picker.kind == PickerKind::Agents => {+ let target = picker+ .items+ .get(picker.selected)+ .map(|i| i.value.clone())+ .unwrap_or_default();+ stop_agent(app, &target);+ }+ // `/worktrees`: Enter runs the action row, or removes the+ // checkout row (asking first when that loses work).+ KeyCode::Enter if picker.kind == PickerKind::Worktrees => {+ if let Some(item) = picker.items.get(picker.selected) {+ let value = item.value.clone();+ worktrees_action(app, &value);+ }}- // `/agents`: `m` writes to the selected child (or the one drilled- // into), `x` stops it. Both reach the same registry calls the parent- // agent's `message_subagent` / `stop_subagent` tools make.- KeyCode::Char('m') | KeyCode::Char('x')- if !ctrl- && matches!(picker.kind, PickerKind::Agents | PickerKind::AgentDetail) =>- {- let run_id = if picker.kind == PickerKind::AgentDetail {- app.agent_detail.clone().unwrap_or_default()- } else {- picker- .items- .get(picker.selected)- .map(|i| i.value.clone())- .unwrap_or_default()- };- let Some(name) = app- .subagents- .iter()- .find(|p| p.run_id == run_id && !run_id.is_empty())- .map(|p| p.name.clone())- else {- return;- };- if key.code == KeyCode::Char('m') {- app.agent_message = Some(AgentMessagePrompt::new(&run_id, &name));- } else {- match crate::core::agent::subagent::stop_subagent(&app.subagent_set, &run_id) {- Ok(_) => app.note(&format!("stopped subagent {name}")),- Err(e) => app.note(&format!("could not stop subagent {name}\n{e}")),- }+ KeyCode::Enter if picker.kind == PickerKind::WorktreeConfirm => {+ if let Some(item) = picker.items.get(picker.selected) {+ let value = item.value.clone();+ confirm_worktree_removal(app, &value);}}KeyCode::Enter if picker.kind == PickerKind::PluginConnect => {@@ -16840,7 +17410,9 @@ async fn handle_key_input(| PickerKind::AgentDetail| PickerKind::BackgroundShells| PickerKind::ShellDetail- | PickerKind::Monitors => {}+ | PickerKind::Monitors+ | PickerKind::Worktrees+ | PickerKind::WorktreeConfirm => {}PickerKind::PluginConnect => {}}}@@ -16862,11 +17434,12 @@ async fn handle_key_input(open_mcp_picker(app, mcp_servers).await;}}- // Esc on a subagent's detail steps back to the `/agents` list, one- // level up, rather than closing the inspector outright.- KeyCode::Esc | KeyCode::Char('q') if !ctrl && picker.kind == PickerKind::AgentDetail => {- picker.kind = PickerKind::Agents;- app.agent_detail = None;+ // The confirm sits one level inside `/worktrees`: Esc keeps the+ // checkout and steps back to the list.+ KeyCode::Esc | KeyCode::Char('q')+ if !ctrl && picker.kind == PickerKind::WorktreeConfirm =>+ {+ open_worktrees_picker(app);}// Likewise a shell's detail steps back to the `/shells` list.KeyCode::Esc | KeyCode::Char('q') if !ctrl && picker.kind == PickerKind::ShellDetail => {@@ -17165,14 +17738,16 @@ async fn handle_key_input(return;}let step = if key.code == KeyCode::PageUp { 10 } else { 1 };- app.scrollback = app.scrollback.saturating_add(step);+ let scroll = app.view_scroll();+ *scroll = scroll.saturating_add(step);}KeyCode::Down | KeyCode::PageDown => {if key.code == KeyCode::Down && app.recall_next() {return;}let step = if key.code == KeyCode::PageDown { 10 } else { 1 };- app.scrollback = app.scrollback.saturating_sub(step);+ let scroll = app.view_scroll();+ *scroll = scroll.saturating_sub(step);}_ => {}}@@ -17446,7 +18021,7 @@ const SLASH_COMMANDS: &[SlashCommand] = &[SlashCommand {name: "/init",hint: "",- description: "Study the project, then write AGENTS.md, skills, and memory",+ description: "Study the project, then write or update AGENTS.md",alias_of: None,},SlashCommand {@@ -17521,6 +18096,12 @@ const SLASH_COMMANDS: &[SlashCommand] = &[description: "Show the dedicated checkout this session works in, and what changed there",alias_of: None,},+ SlashCommand {+ name: "/worktrees",+ hint: "",+ description: "See and prune this project's subagent worktrees and their build cache",+ alias_of: None,+ },SlashCommand {name: "/tree",hint: "",@@ -17839,6 +18420,7 @@ async fn run_command(},"fork" => open_fork_picker(app),"worktree" => worktree_command(app),+ "worktrees" => worktrees_command(app),"tree" => open_tree_picker(app),"resume" => {if arg.is_empty() {@@ -18075,32 +18657,58 @@ fn parse_usage_mode(arg: &str) -> UsageMode {}-/// The `/init` prompt. Onboarding a project means producing the three things a-/// later session reads back: the root instructions file (ingested as project-/// context), skills for repeatable workflows, and memory for durable facts.-/// Phrased as a task for the model rather than executed here -- only the model-/// can read the project and judge what is worth writing down. `{file}` is the-/// file [`init_plan`] chose.+/// The `/init` prompt. `/init` writes or updates the root instructions file and+/// nothing else: skills and memory are the model's to grow as it works, and an+/// onboarding pass that also invents them fills both with guesswork. Phrased as+/// a task for the model rather than executed here -- only the model can read the+/// project and judge what is worth writing down. `{file}` is the file+/// [`init_plan`] chose.fn init_prompt(file: &str) -> String {+ let budget = INSTRUCTIONS_WARN_CHARS / 1000;format!(- "Onboard yourself to this project so future sessions start informed.\n\n\+ "Onboard yourself to this project so future sessions start informed. Your only output is \+`{file}` in the project root: do not write skills, memory notes, or any other file.\n\n\1. Study the project first. Read the README and any contributor docs, map the directory layout, and \find the real build, test, lint, and type-check commands (from the manifests and CI config, not from \guesswork). Note the conventions the code actually follows.\n\n\-2. Write `{file}` in the project root. It is loaded into your system prompt every session, so it \-must earn its tokens: the commands to build/test/lint, the architecture a newcomer cannot infer from \-the tree, and the conventions worth enforcing. Skip anything obvious from a directory listing, and \-do not pad it. If `{file}` already exists, read it and correct what has drifted instead of rewriting \-it wholesale.\n\n\-3. Write skills with `skill_write` for the project's repeatable procedures -- releasing, running \-migrations, adding a module, debugging a subsystem -- one skill per procedure, only where a real \-multi-step recipe exists. Do not invent skills to fill space.\n\n\-4. Record durable project facts with the `memory` tool (search first, update rather than duplicate): decisions, constraints, and gotchas that are \-true beyond this session and not already stated in the code.\n\n\+2. Write `{file}`. It is loaded into your system prompt every session, so it must earn its tokens: \+the commands to build/test/lint, the architecture a newcomer cannot infer from the tree, and the \+conventions worth enforcing. Skip anything obvious from a directory listing, and do not pad it. Keep \+it well under {budget}K characters. If `{file}` already exists, read it and correct what has drifted \+instead of rewriting it wholesale; if it has grown past that size, tighten it -- drop what is stale \+or obvious and fold long step-by-step recipes into a line each.\n\n\Then report what you wrote and why, briefly.")}+/// Loaded instructions above this many characters draw a startup warning. They+/// sit in the system prompt of every turn, so past a few thousand tokens they+/// crowd the window and dilute the rules that matter; the `/init` prompt asks+/// for a file well under it.+const INSTRUCTIONS_WARN_CHARS: usize = 20_000;++/// The startup warning for instructions that have grown too large: the loaded+/// files together, since that total is what every turn pays for, naming each+/// file so the user knows what to trim. `None` while under the limit.+fn instructions_size_warning(+ files: &[crate::core::agent::context::ContextFile],+) -> Option<String> {+ let total: usize = files.iter().map(|f| f.content.chars().count()).sum();+ if total <= INSTRUCTIONS_WARN_CHARS {+ return None;+ }+ // Exact counts: rounded to K, a total just past the limit reads as equal to it.+ let names: Vec<String> = files+ .iter()+ .map(|f| format!("{} ({} chars)", f.path.display(), f.content.chars().count()))+ .collect();+ Some(format!(+ "project instructions are {total} characters, past the {INSTRUCTIONS_WARN_CHARS} that keeps \+ them cheap to load every turn: trim {} or run /init to tighten it",+ names.join(", ")+ ))+}+/// The startup note about project instructions: an invitation to `/init` when/// there are none, and a plain statement when a loaded file is not the default/// `AGENTS.md` -- a legacy `JAN.md` or an opt-in `CLAUDE.md` -- so which file@@ -18182,14 +18790,12 @@ fn init_command(app: &mut App) {let plan = init_plan(&app.project_root);let file = plan.file;match (plan.seed, plan.existing) {- (_, true) => app.note(&format!(- "◈ init · reviewing {file}, skills, and memory for this project"- )),+ (_, true) => app.note(&format!("\u{25c8} init \u{b7} reviewing {file} for this project")),(Some(seed), false) => app.note(&format!(- "◈ init · writing {file} from this project's {seed}, plus skills and memory"+ "\u{25c8} init \u{b7} writing {file} from this project's {seed}")),(None, false) => app.note(&format!(- "◈ init · studying the project to write {file}, skills, and memory"+ "\u{25c8} init \u{b7} studying the project to write {file}")),}let mut prompt = init_prompt(file);@@ -18845,126 +19451,147 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[},];-/// Docked message field for one running subagent, opened from `/agents`. What-/// it sends goes through `subagent::message_subagent`, the call the parent-/// agent's own `message_subagent` tool makes, so the child cannot tell (and-/// need not care) which of the two steered it.-struct AgentMessagePrompt {- run_id: String,- name: String,- input: String,- error: Option<String>,+/// Stop the child `/agents` addresses as `target` (`SubagentPanel::target`:+/// a pending child by name, before it starts) through the registry call the+/// parent agent's `stop_subagent` tool makes.+fn stop_agent(app: &mut App, target: &str) {+ let Some(name) = app+ .subagents+ .iter()+ .find(|p| !target.is_empty() && p.target() == target)+ .map(|p| p.name.clone())+ else {+ return;+ };+ match crate::core::agent::subagent::stop_subagent(&app.subagent_set, target) {+ Ok(_) => app.note(&format!("stopped subagent {name}")),+ Err(e) => app.note(&format!("could not stop subagent {name}\n{e}")),+ }}-impl AgentMessagePrompt {- fn new(run_id: &str, name: &str) -> Self {- Self {- run_id: run_id.to_string(),- name: name.to_string(),- input: String::new(),- error: None,+/// The keys of a subagent's `/agents` detail that differ from the main+/// view's; true when the key was taken. Everything else falls through to the+/// composer, so typing, cursor motion, recall and scrolling behave as they do+/// on the main screen (`App::view_scroll` points the scroll keys here).+/// A child that can no longer be steered takes no text: only the scroll keys+/// fall through, so nothing typed piles up in a field that cannot send.+fn handle_agent_detail_key(app: &mut App, key: KeyEvent, ctrl: bool, newline: bool) -> bool {+ // A refused send is reported until the user acts on it.+ app.steer_refusal = None;+ match key.code {+ // One level up, to the `/agents` list, as before.+ KeyCode::Esc => app.leave_agent_detail(true),+ // Ctrl-C clears a draft first, the way the main composer does; on an+ // empty field it closes the inspector, and never cancels the main run.+ KeyCode::Char('c') | KeyCode::Char('d') if ctrl => {+ if app.input.trim().is_empty() {+ app.leave_agent_detail(false);+ } else {+ app.record_draft();+ app.input_clear();+ }+ }+ KeyCode::Char('x') if ctrl => {+ if let Some(target) = app.steerable_detail_child().map(|p| p.target().to_string()) {+ stop_agent(app, &target);+ }}+ // The main view's expand-all, on the child's own rows.+ KeyCode::Char('o') if ctrl => {+ if let Some((panel, _)) = app.detail_panel_mut() {+ panel.transcript.toggle_regions();+ }+ }+ KeyCode::Enter if !newline => send_to_detail_child(app),+ // A newline opening an empty field is nothing to send; and falling+ // through, it would step a `/find` on the main transcript behind.+ KeyCode::Enter if app.input.is_empty() => {}+ // The main session's own keys mean nothing aimed at a child: Ctrl-F+ // would fill the field with a `/find` to send it, Ctrl-V would stage an+ // image the message does not carry, and the effort keys retune the+ // main model from a screen about another one.+ KeyCode::Char('f') if ctrl && app.input.is_empty() => {}+ KeyCode::Char('v') if ctrl => {}+ KeyCode::Char('t') if key.modifiers.contains(KeyModifiers::ALT) => {}+ KeyCode::BackTab => {}+ KeyCode::PageUp | KeyCode::PageDown => return false,+ // With no draft to move through, Home jumps to the start of the+ // child's run and End follows it again.+ KeyCode::Home | KeyCode::End if app.input.is_empty() => {+ app.agent_detail_scroll = if key.code == KeyCode::Home { u16::MAX } else { 0 };+ }+ // Up/Down recall what was sent to children (`App::steer_history`)+ // while there is a field to recall into; otherwise they scroll.+ KeyCode::Up | KeyCode::Down if app.steerable_detail_child().is_none() => {+ let scroll = app.view_scroll();+ *scroll = match key.code {+ KeyCode::Up => scroll.saturating_add(1),+ _ => scroll.saturating_sub(1),+ };+ }+ _ => return app.steerable_detail_child().is_none(),}+ true}-/// Keyboard for the `/agents` message dock: chars/backspace edit, Enter queues-/// the message on the child's inbox and closes, Esc closes without sending.-/// Either way the inspector underneath stays open where the user left it.-fn handle_agent_message_key(app: &mut App, key: KeyEvent, ctrl: bool) {- if key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c')) {- app.agent_message = None;+/// Send the composer's text to the child the `/agents` detail shows, through+/// `subagent::message_subagent` -- the call the parent agent's own+/// `message_subagent` tool makes, so the child cannot tell (and need not care)+/// which of the two steered it. Addressed by `SubagentPanel::target`: the+/// user picked this exact child, so its run id, or its reserved name while it+/// is pending (queued for when it starts). A message that was not queued (a+/// full inbox, a child that already finished) keeps the draft and says why on+/// the input row (`App::steer_refusal`), leaving the child's run untouched.+fn send_to_detail_child(app: &mut App) {+ let text = app.input.trim().to_string();+ if text.is_empty() {return;}- let Some(prompt) = app.agent_message.as_mut() else {+ let Some((target, name)) = app+ .steerable_detail_child()+ .map(|p| (p.target().to_string(), p.name.clone()))+ else {return;};- match key.code {- KeyCode::Enter => {- let text = prompt.input.trim().to_string();- if text.is_empty() {- prompt.error = Some("type a message first (Esc to cancel)".to_string());- return;+ use crate::core::agent::subagent::{message_subagent, MessageReply};+ match message_subagent(&app.subagent_set, &target, &text) {+ Ok(MessageReply::Queued(_)) => {+ if let Some(panel) = app.subagents.iter_mut().find(|p| p.target() == target) {+ panel.steers_pending += 1;}- // By run id: the user picked this exact child, and a re-dispatched- // name must not redirect the message to a newer one.- match crate::core::agent::subagent::message_subagent(- &app.subagent_set,- &prompt.run_id,- &text,- ) {- Ok(_) => {- let name = prompt.name.clone();- app.agent_message = None;- // One entry, when the user sends it: the child taking it- // later adds nothing to this transcript.- app.scrollback = 0;- app.transcript.agent_message(MAIN_AGENT, MAIN_AGENT, &name, &text);- }- Err(e) => prompt.error = Some(e.to_string()),- }- }- KeyCode::Backspace => {- prompt.input.pop();+ app.record_submitted(&text);+ app.input_clear();+ // One entry, when the user sends it: the child taking it later+ // adds nothing to the main transcript.+ app.transcript.agent_message(MAIN_AGENT, MAIN_AGENT, &name, &text);+ // Sending is a request to see the answer: follow the tail again.+ app.agent_detail_scroll = 0;}- KeyCode::Char(ch) if !ctrl => prompt.input.push(ch),- _ => {}- }-}--/// The message dock's contents at `width`.-fn agent_message_lines(prompt: &AgentMessagePrompt, width: u16) -> Vec<Line<'static>> {- let dim = Style::new().fg(theme::muted());- let max = width.max(1) as usize;- let mut lines: Vec<Line<'static>> = wrap_text(- "Delivered at the subagent's next step, after any tool call in flight, as a \- message from you.",- dim,- max,- )- .into_iter()- .map(Line::from)- .collect();- if let Some(error) = &prompt.error {- lines.extend(wrap_text(error, Style::new().red(), max).into_iter().map(Line::from));+ Ok(MessageReply::NotDelivered(reply)) => app.steer_refusal = Some(reply),+ Err(e) => app.steer_refusal = Some(e.to_string()),}- lines.extend(field_lines(- vec![Span::styled("message: ", Style::new().bold())],- &prompt.input,- Style::new(),- max,- ));- lines.push(Line::styled("Enter send \u{b7} Esc cancel".to_string(), dim));- lines}-/// Where the message dock sits: grown upward from the input row into `body`,-/// sized to its contents, the way the other docks are placed.-fn agent_message_rect(- prompt: &AgentMessagePrompt,- body: ratatui::layout::Rect,- input: ratatui::layout::Rect,-) -> ratatui::layout::Rect {- let height = (agent_message_lines(prompt, panel_inner_width(input.width)).len() as u16 + 2)- .min(body.height);- ratatui::layout::Rect {- x: input.x,- y: input.y.saturating_sub(height).max(body.y),- width: input.width,- height,- }+/// The keys that leave (or clear) a subagent's detail: Esc and Ctrl-C/Ctrl-D.+/// A prompt waiting over the detail lets them through to the detail, so they+/// never deny it or cancel the main run from a screen about a child; the+/// prompt stays queued and is drawn, with its own keys, where the user lands.+fn detail_leave_key(key: &KeyEvent) -> bool {+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ key.code == KeyCode::Esc || (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')))}-fn draw_agent_message(f: &mut Frame, area: ratatui::layout::Rect, prompt: &AgentMessagePrompt) {- use ratatui::widgets::Clear;- let block = panel_block(theme::border_active())- .title(Span::styled(- format!(" message subagent: {} ", prompt.name),- title_style(theme::border_active()),- ));- f.render_widget(Clear, area);- let inner = block.inner(area);- f.render_widget(block, area);- f.render_widget(Paragraph::new(agent_message_lines(prompt, inner.width)), inner);+/// The keys a prompt over a subagent's detail lets through to the detail:+/// `detail_leave_key`, PgUp/PgDn so the child's run can be read before+/// deciding, and, with `cursor_keys`, Left/Right/Home/End, which edit the+/// draft (Home/End scroll the run on an empty field). Left/Right in+/// particular must not reach the prompt: on an `ask` they would switch the+/// question and arm it, and a typo fixed then Enter would answer it.+fn detail_key_under_prompt(key: &KeyEvent, cursor_keys: bool) -> bool {+ let cursor = matches!(key.code, KeyCode::Left | KeyCode::Right | KeyCode::Home | KeyCode::End);+ detail_leave_key(key)+ || matches!(key.code, KeyCode::PageUp | KeyCode::PageDown)+ || (cursor_keys && cursor)}/// Docked edit prompt for one `/settings` row: value field, inline validation@@ -21640,8 +22267,9 @@ fn monitor_picker_items(monitors: &[MonitorSnapshot]) -> Vec<PickerItem> {/// (green while it runs, dim while it waits and once it has finished), its name, its dim stats and/// its status -- for a running child, what it is doing now. Jan's own agents/// (`internal`) follow, marked as internal. A single watermark row stands in-/// when there are none. The row `value` is the child's `run_id`, which Enter-/// drills into.+/// when there are none. The row `value` is the child's `SubagentPanel::target`+/// (its `run_id`, or its name while pending), which Enter drills into and+/// `m` / `x` address.fn agent_picker_items(subagents: &mut [SubagentPanel],finished: &[SubagentBlock],@@ -21677,7 +22305,7 @@ fn agent_picker_items(spans.push(Span::raw(" "));}spans.extend(tail);- styled_item(p.run_id.clone(), spans)+ styled_item(p.target().to_string(), spans)};let mut items = Vec::new();for p in subagents.iter_mut() {@@ -21788,7 +22416,10 @@ fn agent_detail_header(/// inspector's box: `agent_detail_header`, then the child's transcript laid out/// by the code that lays out the main body, at the box's inner width, with the/// call it is still building below it. Pinned to the bottom unless scrolled-/// back (`App::agent_detail_scroll`).+/// back (`App::agent_detail_scroll`), so it follows the child like the main+/// body follows the main run. Drawn every frame from the live panel, so the+/// child's streaming text lands as it arrives; its working row is the input+/// row's (`detail_input_line`).fn draw_agent_detail(f: &mut Frame, area: Rect, app: &mut App) {let block = panel_block(theme::border_active()).title(" subagent ");let inner = block.inner(area);@@ -21797,25 +22428,12 @@ fn draw_agent_detail(f: &mut Frame, area: Rect, app: &mut App) {return;}let dim = Style::new().fg(theme::muted());- let run_id = app.agent_detail.clone().unwrap_or_default();let spinner_frame = app.spinner_frame;let context_window = app.context_window;- // A finished child is read from its summary row's block, which keeps it.- let found = match app.subagents.iter_mut().find(|p| p.run_id == run_id) {- Some(panel) => Some((panel, None)),- None => app- .transcript- .subagent_blocks- .iter_mut()- .find(|b| b.panel.run_id == run_id)- .map(|b| (&mut b.panel, Some(&b.outcome)))- .or_else(|| {- app.internal_agents- .iter_mut()- .find(|a| a.panel.run_id == run_id)- .map(|a| (&mut a.panel, a.outcome.as_ref()))- }),- };+ // Copied out: the panel below borrows `app` whole, and written back once+ // it is laid out.+ let mut back = app.agent_detail_scroll;+ let found = app.detail_panel_mut();let Some((panel, outcome)) = found else {let gone = "this subagent is no longer available. Press Esc to go back.";f.render_widget(Paragraph::new(Line::styled(gone, dim)), inner);@@ -21841,12 +22459,11 @@ fn draw_agent_detail(f: &mut Frame, area: Rect, app: &mut App) {}layout.pin(body.height);let max_back = layout.content_h.saturating_sub(body.height);- app.agent_detail_scroll = app.agent_detail_scroll.min(max_back);- let scroll = max_back - app.agent_detail_scroll;+ back = back.min(max_back);let (lines, _, offset) = layout.window(&panel.transcript.rows,width,- scroll,+ max_back - back,body.height,None,&|_| None,@@ -21857,6 +22474,7 @@ fn draw_agent_detail(f: &mut Frame, area: Rect, app: &mut App) {.scroll((offset, 0)),body,);+ app.agent_detail_scroll = back;}fn open_login_picker(app: &mut App) {@@ -23235,11 +23853,10 @@ fn spawn_worktree_report(app: &App) -> tokio::task::JoinHandle<WorktreeReport> {})}-/// Await an in-flight `/worktree` report, parking forever when none is-/// running so this can sit in the loop's `select!` unconditionally.-async fn await_worktree_report(- task: &mut Option<tokio::task::JoinHandle<WorktreeReport>>,-) -> Option<WorktreeReport> {+/// Await an in-flight off-loop job (`/worktree`'s report, a `/worktrees`+/// action), parking forever when none is running so this can sit in the+/// loop's `select!` unconditionally.+async fn await_job<T>(task: &mut Option<tokio::task::JoinHandle<T>>) -> Option<T> {let joined = match task.as_mut() {Some(h) => h.await,None => return pending().await,@@ -23288,6 +23905,243 @@ fn finish_worktree_report(app: &mut App, report: WorktreeReport) {/// away and the point of the row is the shape of the change, not the manifest.const WORKTREE_CHANGE_ROWS: usize = 20;+/// What `/worktrees` asks the loop to run on the blocking pool.+#[derive(Debug, Clone, PartialEq, Eq)]+enum WorktreesJob {+ List,+ Prune(crate::core::agent::child_workspace::Prune),+ ClearCache,+}++/// What a [`WorktreesJob`] found or did.+#[derive(Debug)]+enum WorktreesDone {+ Listed(crate::core::agent::child_workspace::WorktreesReport),+ Pruned(crate::core::agent::child_workspace::Pruned),+ Cleared(Result<u64, String>),+}++/// `/worktrees`: list this project's subagent checkouts and build cache.+/// Sizing them walks every file and reading them runs git, so this only asks+/// the loop; [`finish_worktrees_job`] opens the picker when the list lands.+fn worktrees_command(app: &mut App) {+ app.worktrees_request = Some(WorktreesJob::List);+}++/// Run `job` on the blocking pool as this session, so its own checkouts and+/// running subagents are told apart from another live session's. Whether a+/// subagent runs is asked live, at each decision, not when the job was+/// queued: one may start while git runs.+fn spawn_worktrees_job(app: &App, job: WorktreesJob) -> tokio::task::JoinHandle<WorktreesDone> {+ use crate::core::agent::child_workspace as cw;+ let subagents = app.subagent_set.clone();+ let root = app.project_root.clone();+ tokio::task::spawn_blocking(move || {+ let running = || !subagents.live_run_ids().is_empty();+ let session = cw::Session { ledger: &subagents.workspaces, children_running: &running };+ match job {+ WorktreesJob::List => WorktreesDone::Listed(cw::list_worktrees(&root, Some(&session))),+ WorktreesJob::Prune(which) => {+ WorktreesDone::Pruned(cw::prune_worktrees(&root, Some(&session), &which))+ }+ WorktreesJob::ClearCache => {+ WorktreesDone::Cleared(cw::clear_build_cache(&root, Some(&session)))+ }+ }+ })+}++fn finish_worktrees_job(app: &mut App, done: WorktreesDone) {+ use crate::core::agent::child_workspace::human_bytes;+ match done {+ WorktreesDone::Listed(report) => {+ app.worktrees = Some(report);+ // The listing walks every checkout, so the user may be typing or+ // looking at something else when it lands: a picker whose first+ // row prunes must not appear under their Enter.+ if app.picker.is_none()+ && app.model_picker.is_none()+ && app.readout.is_none()+ && app.input.trim().is_empty()+ {+ open_worktrees_picker(app);+ } else {+ app.note("worktree listing ready - /worktrees to view");+ }+ }+ // The listing no longer says what is on disk: nothing may reopen it.+ WorktreesDone::Pruned(pruned) => {+ app.worktrees = None;+ app.note(&pruned.notice());+ }+ WorktreesDone::Cleared(Ok(bytes)) => {+ app.worktrees = None;+ app.note(&format!(+ "cleared the subagent build cache, freed {} (next build starts cold)",+ human_bytes(bytes)+ ));+ }+ WorktreesDone::Cleared(Err(why)) => app.note(&format!("build cache not cleared: {why}")),+ }+}++/// Open (or return to) the `/worktrees` list from the last listing; with+/// none (a prune since made it stale), list again rather than show nothing.+fn open_worktrees_picker(app: &mut App) {+ let Some(report) = app.worktrees.as_ref() else {+ app.picker = None;+ return worktrees_command(app);+ };+ let items = worktrees_picker_items(report);+ app.picker = Some(Picker {+ kind: PickerKind::Worktrees,+ items,+ selected: 0,+ search: None,+ armed_delete: None,+ });+}++/// Picker value of a checkout row: the checkout's id behind this prefix.+const WORKTREE_ROW: &str = "wt:";+/// Picker value of the confirm's remove row, likewise.+const WORKTREE_FORCE_ROW: &str = "force:";++/// The `/worktrees` rows: the two actions, then one row per checkout+/// (`branch size state`, the state coloured by what may be done with it).+fn worktrees_picker_items(+ report: &crate::core::agent::child_workspace::WorktreesReport,+) -> Vec<PickerItem> {+ use crate::core::agent::child_workspace::{human_bytes, CheckoutState};+ if report.dir.is_none() {+ return vec![watermark_item("no Jan home: there are no subagent worktrees")];+ }+ let dim = Style::new().fg(theme::muted());+ let (count, bytes) = report.removable();+ let safe = match count {+ 0 => "nothing to remove".to_string(),+ n => format!("{n} checkout(s), {}", human_bytes(bytes)),+ };+ let mut items = vec![styled_item(+ "safe".to_string(),+ vec![+ Span::raw("Remove what is safe to remove"),+ Span::styled(format!(" {safe}"), dim),+ ],+ )];+ items.push(match report.build_cache_bytes {+ Some(bytes) => styled_item(+ "cache".to_string(),+ vec![+ Span::raw("Clear build cache"),+ Span::styled(format!(" {}", human_bytes(bytes)), dim),+ ],+ ),+ None => watermark_item("no build cache"),+ });+ if report.checkouts.is_empty() {+ items.push(watermark_item("no subagent checkouts"));+ }+ items.extend(report.checkouts.iter().map(|c| {+ let tone = match c.state {+ CheckoutState::Removable { .. } => theme::success(),+ CheckoutState::Uncommitted { .. } | CheckoutState::Unbrought { .. } => theme::warning(),+ CheckoutState::InUse { .. } | CheckoutState::Unreadable { .. } => theme::muted(),+ };+ styled_item(+ format!("{WORKTREE_ROW}{}", c.id),+ vec![+ Span::styled(c.branch.clone(), Style::new().fg(theme::accent())),+ Span::styled(format!(" {}", human_bytes(c.bytes)), dim),+ Span::styled(format!(" {}", c.state.describe()), Style::new().fg(tone)),+ ],+ )+ }));+ items+}++/// Enter on a `/worktrees` row. A checkout that holds work opens the+/// confirm naming what it would lose; one in use, or that git cannot read,+/// is never removed from here, and says why.+fn worktrees_action(app: &mut App, value: &str) {+ use crate::core::agent::child_workspace::{CheckoutState, Prune};+ let job = match value {+ "" => return,+ "safe" => {+ app.note("removing the subagent worktrees that are safe to remove...");+ WorktreesJob::Prune(Prune::Safe)+ }+ "cache" => WorktreesJob::ClearCache,+ row => {+ let Some(id) = row.strip_prefix(WORKTREE_ROW) else { return };+ let Some(found) = app+ .worktrees+ .as_ref()+ .and_then(|r| r.checkouts.iter().find(|c| c.id == id))+ .cloned()+ else {+ return;+ };+ if let Some(loses) = found.loses() {+ return open_worktree_confirm(app, &found, &loses);+ }+ if !matches!(found.state, CheckoutState::Removable { .. }) {+ return app.note(&format!("{} is kept: {}", found.branch, found.state.describe()));+ }+ WorktreesJob::Prune(Prune::One { id: id.to_string(), force: false })+ }+ };+ app.picker = None;+ app.worktrees_request = Some(job);+}++/// The confirm before removing a checkout that holds work: what is lost, and+/// "keep" selected, so a stray Enter loses nothing.+fn open_worktree_confirm(+ app: &mut App,+ found: &crate::core::agent::child_workspace::CheckoutInfo,+ loses: &str,+) {+ let mut items = vec![+ watermark_item(&format!("{} at {}", found.branch, tilde_path(&found.path))),+ watermark_item(&format!("removing it deletes {loses}, for good")),+ ];+ items.extend(found.state.brings_back().map(|kept| watermark_item(&kept)));+ let keep = items.len();+ items.extend([+ styled_item("keep".to_string(), vec![Span::raw("Keep it")]),+ styled_item(+ format!("{WORKTREE_FORCE_ROW}{}", found.id),+ vec![Span::styled(+ format!("Remove it and lose {loses}"),+ Style::new().fg(theme::warning()),+ )],+ ),+ ]);+ app.picker = Some(Picker {+ kind: PickerKind::WorktreeConfirm,+ items,+ selected: keep,+ search: None,+ armed_delete: None,+ });+}++/// Enter on the confirm: remove the checkout whatever it holds, or keep it+/// and go back to the list.+fn confirm_worktree_removal(app: &mut App, value: &str) {+ use crate::core::agent::child_workspace::Prune;+ match value.strip_prefix(WORKTREE_FORCE_ROW) {+ Some(id) => {+ app.picker = None;+ app.worktrees_request =+ Some(WorktreesJob::Prune(Prune::One { id: id.to_string(), force: true }));+ }+ None if value == "keep" => open_worktrees_picker(app),+ None => {}+ }+}+/// Branch the session before its `target`-th user message into a new thread and/// switch to it, leaving the source whole on disk. The cut turn lands in the/// input, as a rewind's does, so the branch opens ready to re-ask it.@@ -23777,6 +24631,10 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value, verb: &str) {app.end_conversation_worktrees();app.stop_monitors();app.shell_set.take_notices();+ // The loaded thread's shell starts in the project root, like a new one;+ // its saved history may still announce an old `cd`, which the first+ // command's result corrects.+ *app.shell_cwd.lock().unwrap() = None;app.transcript.expanded.clear();app.transcript.reveal = None;app.find = None;@@ -24262,7 +25120,29 @@ fn panel_budget(frame_h: u16, input_h: u16) -> usize {spare_rows(frame_h, input_h).min(PANEL_MAX_ROWS)}+/// How far the input row scrolls to keep the cursor row visible once a draft+/// outgrows `area`: the main composer's, or a subagent detail's.+fn input_scroll(app: &App, area: Rect) -> u16 {+ let typing = if app.agent_detail_open() {+ app.steerable_detail_child().is_some() && !app.input.is_empty()+ } else {+ app.accepts_input() && app.picker.is_none()+ };+ if !typing || app.blocking_dock().is_some() {+ return 0;+ }+ let visible = area.height.saturating_sub(1);+ let total = Paragraph::new(composer_lines(app))+ .wrap(Wrap { trim: false })+ .line_count(area.width.saturating_sub(2).max(1))+ .min(u16::MAX as usize) as u16;+ total.saturating_sub(visible)+}+fn draw(f: &mut Frame, app: &mut App) {+ // A screen that replaced the detail since the last key gets the main+ // composer back before it is drawn.+ app.settle_agent_detail();// Cached before anything reads it: the plan dock sizes the layout, so a// stale width would mis-size the frame a resize lands on. The body spans// the full frame width (its border is top-only).@@ -24396,17 +25276,17 @@ fn draw(f: &mut Frame, app: &mut App) {app.spinner(),);}- f.render_widget(input_box(app, chunks[2].width), chunks[2]);+ let input_scroll = input_scroll(app, chunks[2]);+ f.render_widget(input_box(app, chunks[2].width).scroll((input_scroll, 0)), chunks[2]);f.render_widget(dock_line(app, chunks[3].width), chunks[3]);// The `/mcp` sign-in confirm lives here too: the picker path returns// before the overlay chain below, so without this the "open a browser?"- // prompt never shows on the one screen that raises it.+ // prompt never shows on the one screen that raises it. Likewise a+ // queued permission request or `ask`, whose keys work under a picker.if let Some(confirm) = &app.browser_confirm {draw_browser_confirm_overlay(f, confirm, chunks[2], chunks[1]);- }- // Likewise the `/agents` message dock, opened over the inspector.- if let Some(prompt) = &app.agent_message {- draw_agent_message(f, agent_message_rect(prompt, chunks[1], chunks[2]), prompt);+ } else {+ draw_queued_prompt(f, app, chunks[2], chunks[1]);}return;}@@ -24522,18 +25402,7 @@ fn draw(f: &mut Frame, app: &mut App) {app.last_scroll = scroll;app.row_index = row_index;- // Keep the cursor row visible when the input outgrows the box.- let input_scroll =- if app.accepts_input() && app.picker.is_none() && app.blocking_dock().is_none() {- let visible = chunks[2].height.saturating_sub(1);- let total = Paragraph::new(input_content_lines(&app.input, app.cursor))- .wrap(Wrap { trim: false })- .line_count(chunks[2].width.saturating_sub(2).max(1))- .min(u16::MAX as usize) as u16;- total.saturating_sub(visible)- } else {- 0- };+ let input_scroll = input_scroll(app, chunks[2]);if let Some(lines) = panel_lines {f.render_widget(Paragraph::new(lines), panel_area);}@@ -24646,8 +25515,6 @@ fn draw(f: &mut Frame, app: &mut App) {height,};draw_settings_prompt(f, rect, prompt, &toml_path);- } else if let Some(prompt) = &app.agent_message {- draw_agent_message(f, agent_message_rect(prompt, chunks[1], chunks[2]), prompt);} else if let Some(prompt) = &app.mcp_prompt {let height = (mcp_prompt_lines(prompt, panel_inner_width(chunks[2].width)).len() as u16 + 2).min(chunks[1].height);@@ -24671,33 +25538,7 @@ fn draw(f: &mut Frame, app: &mut App) {draw_provider_prompt(f, rect, prompt);} else if let Some(prompt) = &app.web_search_prompt {draw_web_search_prompt(f, web_search_prompt_rect(prompt, chunks[1], chunks[2]), prompt);- } else if !app.ask_queue.is_empty() {- let queue_len = app.ask_queue.len();- let ask = app.ask_queue.front_mut().expect("checked non-empty above");- let height = ask.box_height(chunks[2].width).min(chunks[1].height);- let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);- let rect = ratatui::layout::Rect {- x: chunks[2].x,- y,- width: chunks[2].width,- height,- };- draw_ask(f, rect, ask, queue_len);- } else if let Some(pending) = app.pending() {- let inner_w = panel_inner_width(chunks[2].width);- let detail_rows = pending.detail_lines(inner_w).len() as u16;- let diff_rows = pending.diff_preview(inner_w).len() as u16;- let height =- (pending.options().len() as u16 + detail_rows + diff_rows + 2).min(chunks[1].height);- let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);- let rect = ratatui::layout::Rect {- x: chunks[2].x,- y,- width: chunks[2].width,- height,- };- draw_permission(f, rect, pending, app.pending_queue.len());- } else {+ } else if !draw_queued_prompt(f, app, chunks[2], chunks[1]) {// Dock the slash-command hints above the input box, growing upward// and clamped to the body so they never overrun the transcript.let matches = app.slash_matches();@@ -24747,8 +25588,77 @@ fn draw(f: &mut Frame, app: &mut App) {}}-fn draw_ask(f: &mut Frame, area: Rect, ask: &mut PendingAsk, queue_len: usize) {- use ratatui::widgets::{Clear, List, ListItem, ListState};+/// Dock the front queued `ask`, else the front permission request, above+/// `input`, clamped to `body`; false when neither waits. Shared by the main+/// view and the picker path: the prompt's keys work under a picker too, so it+/// has to be seen there, above all over a subagent's detail, where the user+/// may be typing when it lands.+fn draw_queued_prompt(f: &mut Frame, app: &mut App, input: Rect, body: Rect) -> bool {+ let over_detail = app.agent_detail_open();+ // A prompt's pause over the detail starts when the user can see it there+ // (`PromptPause::key_lands`), not when it was queued: one queued behind+ // another, or seen in the main view before the detail opened, lands as new+ // when it shows over the detail. It lands unarmed too: an arrow the user+ // pressed on it in the main view was not aimed at a prompt over the+ // detail, so the Enter they then type for the child must not confirm it.+ // Clearing `picked` also hides the highlight (`prompt_highlight`), and the+ // next arrow re-arms on the safe row (`detail_arrow`). The main view reads+ // neither the pause nor `picked`, so it is unchanged.+ let now = Instant::now();+ let stamp = |pause: &mut PromptPause, picked: &mut bool| {+ if !over_detail {+ *pause = PromptPause::default();+ } else if pause.until.is_none() {+ pause.until = Some(now + PROMPT_PAUSE);+ *picked = false;+ }+ };+ // Every prompt but the one in front is hidden, so it forgets its pause and+ // its arming: a permission request covered by a newer ask, then uncovered+ // when the ask is answered, comes back with a fresh pause and unarmed.+ // Otherwise its old, long-past deadline would let a reflex second Enter,+ // meant for the ask, confirm whatever the user had armed on it before.+ // It has to be armed again, on the safe row, like any prompt that lands+ // over the detail. The main view reads neither (`prompt_highlight`, and+ // its Enter ignores `picked`), so it is unchanged.+ let shown_requests = usize::from(app.ask_queue.is_empty());+ let hidden_asks = app.ask_queue.iter_mut().skip(1);+ let hidden_requests = app.pending_queue.iter_mut().skip(shown_requests);+ let hidden = hidden_asks+ .map(|ask| (&mut ask.pause, &mut ask.picked))+ .chain(hidden_requests.map(|p| (&mut p.pause, &mut p.picked)));+ for (pause, picked) in hidden {+ *pause = PromptPause::default();+ *picked = false;+ }+ if !app.ask_queue.is_empty() {+ let queue_len = app.ask_queue.len();+ let ask = app.ask_queue.front_mut().expect("checked non-empty above");+ stamp(&mut ask.pause, &mut ask.picked);+ let height = ask.box_height(input.width).min(body.height);+ let y = input.y.saturating_sub(height).max(body.y);+ let rect = Rect { x: input.x, y, width: input.width, height };+ draw_ask(f, rect, ask, queue_len, over_detail);+ return true;+ }+ if let Some(pending) = app.pending_queue.front_mut() {+ stamp(&mut pending.pause, &mut pending.picked);+ }+ let Some(pending) = app.pending() else {+ return false;+ };+ let inner_w = panel_inner_width(input.width);+ let detail_rows = pending.detail_lines(inner_w).len() as u16;+ let diff_rows = pending.diff_preview(inner_w).len() as u16;+ let height = (pending.options().len() as u16 + detail_rows + diff_rows + 2).min(body.height);+ let y = input.y.saturating_sub(height).max(body.y);+ let rect = Rect { x: input.x, y, width: input.width, height };+ draw_permission(f, rect, pending, app.pending_queue.len(), over_detail);+ true+}++fn draw_ask(f: &mut Frame, area: Rect, ask: &mut PendingAsk, queue_len: usize, over_detail: bool) {+ use ratatui::widgets::{Clear, HighlightSpacing, List, ListItem, ListState};let dim = Style::new().fg(theme::muted());// Whole seconds until the auto-select deadline, rounded up (ceil) so a@@ -24786,9 +25696,10 @@ fn draw_ask(f: &mut Frame, area: Rect, ask: &mut PendingAsk, queue_len: usize) {let list = List::new(items.into_iter().map(ListItem::new).collect::<Vec<_>>()).highlight_style(select_style())- .highlight_symbol(SELECT_MARK);+ .highlight_symbol(SELECT_MARK)+ .highlight_spacing(HighlightSpacing::Always);let mut state = ListState::default();- state.select(Some(ask.selected));+ state.select(prompt_highlight(ask.selected, ask.picked, over_detail));f.render_stateful_widget(list, rows[1], &mut state);// Hitboxes come from the same heights the list just laid out, offset by the@@ -24810,20 +25721,35 @@ fn draw_ask(f: &mut Frame, area: Rect, ask: &mut PendingAsk, queue_len: usize) {}let help = if ask.editing_custom {+ // Over the detail the draft row sits just below with its own cursor,+ // so the field says plainly that what is typed here is the answer.+ let label = if over_detail {+ Span::styled("your answer: ", Style::new().fg(theme::accent()).bold())+ } else {+ Span::styled("Other: ", Style::new().fg(theme::accent()))+ };Line::from(vec![- Span::styled("Other: ", Style::new().fg(theme::accent())),+ label,Span::raw(ask.custom_input.clone()),Span::styled("\u{2588}", Style::new().fg(theme::accent())),])} else {- Line::styled(- if ask.question().multi {- "\u{2191}\u{2193} move \u{b7} Space toggle \u{b7} Enter choose \u{b7} \u{2190}\u{2192} question \u{b7} Esc cancel"- } else {- "\u{2191}\u{2193} move \u{b7} Enter choose \u{b7} \u{2190}\u{2192} question \u{b7} Esc cancel"- },- dim,- )+ let toggle = if ask.question().multi { " \u{b7} Space toggle" } else { "" };+ // Over a subagent's detail Esc goes back and leaves the question+ // waiting, Left/Right edit the draft rather than switch questions, and+ // Enter and Space do nothing until an arrow arms it and its pause runs+ // out (`handle_ask_key`).+ let live = ask.pause.live(ask.picked, std::time::Instant::now());+ let help = match (over_detail, live) {+ (false, _) => format!(+ "\u{2191}\u{2193} move{toggle} \u{b7} Enter choose \u{b7} \u{2190}\u{2192} question \u{b7} Esc cancel"+ ),+ (true, false) => "\u{2191}\u{2193} pick \u{b7} Esc back".to_string(),+ (true, true) => {+ format!("\u{2191}\u{2193} move{toggle} \u{b7} Enter choose \u{b7} Esc back")+ }+ };+ Line::styled(help, dim)};f.render_widget(Paragraph::new(help), rows[2]);}@@ -25538,8 +26464,9 @@ fn draw_permission(area: ratatui::layout::Rect,pending: &Pending,queue_len: usize,+ over_detail: bool,) {- use ratatui::widgets::{Clear, List, ListItem, ListState};+ use ratatui::widgets::{Clear, HighlightSpacing, List, ListItem, ListState};let title = if queue_len > 1 {format!(" permission required (1 of {queue_len}) ")@@ -25572,12 +26499,22 @@ fn draw_permission(.collect();let list = List::new(items).highlight_style(select_style())- .highlight_symbol(SELECT_MARK);+ .highlight_symbol(SELECT_MARK)+ .highlight_spacing(HighlightSpacing::Always);let mut state = ListState::default();- state.select(Some(pending.selected));+ state.select(prompt_highlight(pending.selected, pending.picked, over_detail));f.render_stateful_widget(list, rows[2], &mut state);}+/// The row a docked prompt highlights. Over a subagent's detail an unarmed+/// prompt highlights none: Enter does not choose there until an arrow arms it+/// (`Pending::arrow`), and a highlight would say it does. The lists keep the+/// mark's gutter either way (`HighlightSpacing::Always`), so arming does not+/// shift the rows sideways.+fn prompt_highlight(selected: usize, picked: bool, over_detail: bool) -> Option<usize> {+ (picked || !over_detail).then_some(selected)+}+fn count_label(label: &str, count: usize, width: u16) -> String {let width = width as usize;if width == 0 {@@ -26353,12 +27290,12 @@ const MAX_INPUT_ROWS: u16 = 8;/// editing, plus one row of air above the dock. The box is borderless, so the/// two rows this used to add on top of its content were simply blank.fn input_box_height(app: &App, width: u16) -> u16 {- let content = if app.picker.is_none()+ let content = if (app.picker.is_none() || app.steerable_detail_child().is_some())&& app.blocking_dock().is_none()&& !(app.status == Status::Running && app.input.is_empty()){let inner = width.saturating_sub(2).max(1);- let rows = Paragraph::new(input_content_lines(&app.input, app.cursor))+ let rows = Paragraph::new(composer_lines(app)).wrap(Wrap { trim: false }).line_count(inner).max(1) as u16;@@ -26369,6 +27306,30 @@ fn input_box_height(app: &App, width: u16) -> u16 {content + 1}+/// The draft as the input row shows it: `input_content_lines`, then, in a+/// subagent's detail, why its last send went nowhere (`App::steer_refusal`),+/// under the draft it kept, and that a prompt over it holds Enter. One source+/// for the row and the rows it is sized to.+fn composer_lines(app: &App) -> Vec<Line<'static>> {+ let mut lines = input_content_lines(&app.input, app.cursor);+ if let Some(why) = app.steer_refusal.as_ref().filter(|_| app.agent_detail_open()) {+ let (gutter, body) = Level::Error.styles();+ lines.push(Line::from(vec![+ Span::styled(format!("{} ", Level::Error.glyph()), gutter),+ Span::styled(why.clone(), body),+ ]));+ }+ // The draft stays visible under a prompt, but Enter does not send it+ // there (`handle_key`), so the row says so rather than looking ready.+ if app.prompt_over_detail() && !app.input.is_empty() {+ lines.push(Line::styled(+ "answer the prompt above, then Enter sends this",+ Style::new().dim().italic(),+ ));+ }+ lines+}+/// Visible input as styled lines: `USER_GLYPH` on the first line, 2-space hang on/// continuations, and a solid block cursor at the byte offset `cursor` (the/// character under the cursor is drawn in reverse video; at end of line a@@ -26439,13 +27400,24 @@ const WORKING_HINTS: [&str; 2] = [/// not fit `width` drops to the shorter one, then to none, so the row never/// wraps or changes height.fn working_row(app: &App, width: u16) -> Line<'static> {+ working_line(&app.transcript, app.spinner_frame, &WORKING_HINTS, width)+}++/// `working_row` for the run `transcript` belongs to -- the main run's, or a+/// subagent's in its `/agents` detail -- with `hints` offered beside it.+fn working_line<H: AsRef<str>>(+ transcript: &Transcript,+ spinner_frame: usize,+ hints: &[H],+ width: u16,+) -> Line<'static> {let mode = motion::mode();// The spinner carries the fast motion; the action word turns over on a// slower cadence, cycling "working" synonyms -- or "thinking" synonyms in// orange while a reasoning block streams -- so the row reads alive without// shifting under the eye.- let step = app.spinner_frame / WORD_ROTATE_FRAMES;- let (word, style, tint) = if app.transcript.reasoning_open() {+ let step = spinner_frame / WORD_ROTATE_FRAMES;+ let (word, style, tint) = if transcript.reasoning_open() {(THINKING_WORDS[step % THINKING_WORDS.len()],// Same theme-aware accent as markdown bold, so reasoning reads@@ -26467,7 +27439,7 @@ fn working_row(app: &App, width: u16) -> Line<'static> {vec![Line::from(Span::styled(message, style))],style,tint,- motion::frame_time(app.spinner_frame),+ motion::frame_time(spinner_frame),mode,theme::Theme::current(),)@@ -26485,7 +27457,7 @@ fn working_row(app: &App, width: u16) -> Line<'static> {let pad = (longest + 1).saturating_sub(word.chars().count() + 1);spans.push(Span::raw(" ".repeat(pad)));spans.splice(0..0, empty_prompt_prefix());- push_fitting_hint(&mut spans, &WORKING_HINTS, width);+ push_fitting_hint(&mut spans, hints, width);Line::from(spans)}@@ -26503,11 +27475,65 @@ fn empty_prompt_prefix() -> [Span<'static>; 3] {/// Append the longest of `hints` that still fits `width` beside `spans`, or/// none, so an input-row hint is dropped whole rather than clipped mid-word.-fn push_fitting_hint(spans: &mut Vec<Span<'static>>, hints: &[&'static str], width: u16) {+fn push_fitting_hint<H: AsRef<str>>(spans: &mut Vec<Span<'static>>, hints: &[H], width: u16) {let used = spans_width(spans);- if let Some(hint) = hints.iter().find(|h| used + h.len() <= width as usize) {- spans.push(Span::styled(*hint, Style::new().dim().italic()));+ let fits = |h: &&H| used + h.as_ref().chars().count() <= width as usize;+ if let Some(hint) = hints.iter().find(fits) {+ spans.push(Span::styled(hint.as_ref().to_string(), Style::new().dim().italic()));+ }+}++/// The input row of a subagent's `/agents` detail: the main composer's states,+/// for the child. A draft shows as typed; an empty field shows what was sent+/// and not yet taken, else the main view's working row while the child is+/// generating, else the composer's placeholder, addressed to the child. A+/// child that has ended, or one of Jan's own, takes nothing, and says so.+fn detail_input_line(app: &App, width: u16) -> Vec<Line<'static>> {+ let note = |text: String| vec![Line::styled(text, Style::new().dim().italic())];+ let Some((panel, outcome)) = app.detail_panel() else {+ return note("this subagent is no longer available - Esc to go back".to_string());+ };+ let name = &panel.name;+ if outcome.is_some() {+ return note(format!("{name} has finished and takes no messages - Esc to go back"));+ }+ if panel.internal {+ return note(format!("{name} is Jan's own agent and takes no messages"));+ }+ if !app.input.is_empty() {+ return composer_lines(app);+ }+ // The prompt owns the keys until it is answered or left: the field does+ // not invite typing that would go nowhere.+ if app.prompt_over_detail() {+ return note("answer the prompt above, or Esc to go back".to_string());+ }+ if panel.steers_pending > 0 {+ // The main composer's queue cue, for this child's inbox.+ let n = panel.steers_pending;+ return vec![Line::styled(+ format!("\u{23f3} Pending ({n}) - {name} reads it at its next step; type to add more"),+ Style::new().fg(theme::warning()),+ )];+ }+ if panel.status(None) == AgentStatus::Running {+ let hints = [+ format!(" (type to message {name}, Ctrl-X to stop)"),+ format!(" (type to message {name})"),+ ];+ return vec![working_line(&panel.transcript, app.spinner_frame, &hints, width)];+ }+ // Queued, pending on a phase, or parked: not generating, so the field+ // offers itself. A child that has not started reads it first thing.+ let mut spans: Vec<Span<'static>> = empty_prompt_prefix().into();+ spans.push(Span::styled(+ format!("Message {name}\u{2026}"),+ Style::new().dim().italic(),+ ));+ if panel.pending || panel.queued {+ push_fitting_hint(&mut spans, &[" (it reads this when it starts)"], width);}+ vec![Line::from(spans)]}/// Most child rows one group of the background-work block hangs under its@@ -26536,6 +27562,11 @@ struct WorkHead {struct WorkChild {name: String,facts: Vec<Vec<Span<'static>>>,+ /// Whether the last fact is a verb-first label that is cut with `...`,+ /// keeping at least its verb, before it is dropped whole. A subagent's activity is+ /// often a long command, and dropped whole it left a busy child reading+ /// as idle on any row narrower than the command.+ cut_last: bool,}/// A group of the background-work block: monitors, subagents or shells.@@ -26555,10 +27586,13 @@ struct WorkGroup {/// keeps the most meaning per column, so nothing is cut mid-word without a/// mark: the head drops its hint words, then its commands, then every count/// but the first; a child drops its facts from the last in (activity before-/// elapsed before status); only then is the remaining text cut, with `...`.-/// Under `BACKGROUND_CHILD_MIN_NAME` columns of name the group is its head-/// alone, whatever `cap` allows.+/// elapsed before status), except that a `cut_last` fact is first cut to what+/// fits, so long as its verb survives; only then is the remaining text cut,+/// with `...`. Under `BACKGROUND_CHILD_MIN_NAME` columns of name the group is+/// its head alone, whatever `cap` allows.fn work_group_lines(group: &WorkGroup, cap: usize, max: usize) -> Vec<Line<'static>> {+ use unicode_width::UnicodeWidthStr;+let dim = Style::new().fg(theme::muted());let accent = Style::new().fg(theme::accent());let sep = || Span::styled(" \u{b7} ", dim);@@ -26612,10 +27646,47 @@ fn work_group_lines(group: &WorkGroup, cap: usize, max: usize) -> Vec<Line<'stat}spans};- let spans = (0..=facts.len())- .rev()- .map(|kept| row(kept, child.name.clone()))- .find(|spans| spans_width(spans) <= max)+ let full = row(facts.len(), child.name.clone());+ let cut = || {+ // The flag names the child's own last fact: an empty one was+ // filtered out above, and the fact before it is not verb-first.+ child.facts.last().filter(|f| !f.is_empty())?;+ let fact = facts.last()?;+ let mut spans = row(facts.len() - 1, child.name.clone());+ let room = max.checked_sub(spans_width(&spans) + sep().width())?;+ let verb = fact.first()?.content.split_whitespace().next()?;+ if room < verb.width() + 3 {+ return None;+ }+ spans.push(sep());+ // Whole spans while they leave room for the mark, then the one+ // that does not, cut to what is left in that span's style. The+ // mark is part of what `ellipsize` measures, so a span that just+ // fits without it is still cut; its trailing space is trimmed so+ // the mark does not float off the word.+ let mut left = room;+ for span in fact.iter() {+ if span.width() + 3 <= left {+ left -= span.width();+ spans.push(span.clone());+ continue;+ }+ let cut = ellipsize(&format!("{}...", span.content), left);+ let head = cut.strip_suffix("...").unwrap_or(&cut).trim_end();+ spans.push(Span::styled(format!("{head}..."), span.style));+ break;+ }+ Some(spans)+ };+ let spans = Some(full)+ .filter(|spans| spans_width(spans) <= max)+ .or_else(|| child.cut_last.then(cut).flatten())+ .or_else(|| {+ (0..facts.len())+ .rev()+ .map(|kept| row(kept, child.name.clone()))+ .find(|spans| spans_width(spans) <= max)+ }).unwrap_or_else(|| row(0, ellipsize(&child.name, max.saturating_sub(prefix_w))));out.push(Line::from(spans));}@@ -26645,6 +27716,7 @@ fn monitor_group(monitors: &[MonitorSnapshot]) -> Option<WorkGroup> {.map(|m| WorkChild {name: format!("{} {}", m.monitor_id, single_line(&m.name)),facts: vec![vec![Span::styled(pluralize("poll", m.polls as usize), dim)]],+ cut_last: false,}).collect(),})@@ -26653,8 +27725,9 @@ fn monitor_group(monitors: &[MonitorSnapshot]) -> Option<WorkGroup> {/// The session's subagents as a group. A running child shows its elapsed/// time and what it is doing; the head already says it is running, so only/// a child that is not carries a status word: queued for a slot (with its-/// place in line), waiting on an earlier phase, or started and waiting on-/// background work of its own, which keeps its elapsed time.+/// place in line), queued behind an earlier phase (with its phase), or+/// started and waiting on background work of its own, which keeps its+/// elapsed time./// The head names `/agents` because that is where a child is viewed and/// stopped in either state: Esc mid-turn cancels the turn and every child/// with it, and idle it only clears the input.@@ -26667,8 +27740,11 @@ fn subagent_group(panels: &mut [SubagentPanel], now: Instant) -> Option<WorkGroulet count = |want: fn(&AgentStatus) -> bool| statuses.iter().filter(|s| want(s)).count();let counts = vec![("running", count(|s| *s == AgentStatus::Running)),- ("queued", count(|s| matches!(s, AgentStatus::Queued(_)))),- ("waiting", count(|s| matches!(s, AgentStatus::Waiting(_) | AgentStatus::Parked))),+ // A later-phase child has not started either, so it counts as queued+ // with the capped ones; "waiting" is a started child idle on its own+ // background work.+ ("queued", count(|s| matches!(s, AgentStatus::Queued(_) | AgentStatus::Waiting(_)))),+ ("waiting", count(|s| *s == AgentStatus::Parked)),];let children = panels.iter_mut()@@ -26685,6 +27761,7 @@ fn subagent_group(panels: &mut [SubagentPanel], now: Instant) -> Option<WorkGrouWorkChild {name: panel.name.clone(),facts,+ cut_last: running,}}).collect();@@ -26713,6 +27790,7 @@ fn shell_group(shells: &[tauri_plugin_agent_tools::tools::proc::ShellInfo]) -> O.map(|shell| WorkChild {name: single_line(&shell.command),facts: vec![vec![Span::styled(format_elapsed(shell.elapsed_secs), dim)]],+ cut_last: false,}).collect(),})@@ -26753,6 +27831,13 @@ fn background_rows(app: &mut App, width: u16, rows: usize, now: Instant) -> Vec<fn input_box(app: &App, width: u16) -> Paragraph<'static> {let block = Block::default();+ // Ahead of the main run's states: the field is the child's here, and the+ // main run's own state is still in the header.+ if app.agent_detail_open() {+ return Paragraph::new(detail_input_line(app, width))+ .wrap(Wrap { trim: false })+ .block(block);+ }if let Some(kind) = app.compacting.filter(|_| app.input.is_empty()) {// Compaction puts nothing in the transcript while it runs, so the input// row carries the label and the elapsed seconds.@@ -26895,6 +27980,25 @@ fn dock_line(app: &App, width: u16) -> Paragraph<'static> {}fn footer_spans(app: &App) -> Vec<Span<'static>> {+ // Over a subagent's detail the letters and a stray Enter answer nothing,+ // and Esc/Ctrl-C step out of the detail (`handle_key_input`).+ if app.prompt_over_detail() {+ let style = Style::new().fg(theme::warning()).bold();+ // The free-text field takes the keys, and Esc closes only it.+ if app.ask_queue.front().is_some_and(|ask| ask.editing_custom) {+ return hint_spans(style, &[("Enter", "answer"), ("Esc", "options")]);+ }+ // Enter is named only once it would confirm something: armed with an+ // arrow (`Pending::arrow`) and past its pause (`PromptPause::key_lands`).+ return if app.front_prompt_live() {+ hint_spans(+ style,+ &[("\u{2191}/\u{2193}", "move"), ("Enter", "confirm"), ("Esc", "back")],+ )+ } else {+ hint_spans(style, &[("\u{2191}/\u{2193}", "pick"), ("Esc", "back")])+ };+ }if !app.pending_queue.is_empty() {return hint_spans(Style::new().fg(theme::warning()).bold(),@@ -26906,6 +28010,13 @@ fn footer_spans(app: &App) -> Vec<Span<'static>> {],);}+ // A child that takes no messages has nothing to send or stop.+ if app.agent_detail_open() && app.steerable_detail_child().is_none() {+ return vec![Span::styled(+ " PgUp/PgDn scroll Esc back/^C close",+ Style::new().dim(),+ )];+ }if let Some(picker) = &app.picker {return vec![Span::styled(picker.action_hint(), Style::new().dim())];}@@ -26996,6 +28107,7 @@ mod tests {cancel_command, next_event, RunEvent, SessionLimits, SteeringRequest, SubagentOutcome,};use tokio::sync::mpsc;+ use super::{PromptPause, HELD_KEY_WINDOW, PROMPT_PAUSE, STEP_AGAIN_WINDOW};use super::{age_closed_todos, alt_scroll_restore, alt_scroll_save_off, answer_without_reasoning,apply_repaint, apply_resume, apply_stream_event, assistant_is_awaiting_user_answer,@@ -27020,7 +28132,9 @@ mod tests {subagent_name_from_run_id, summarize_result, sync_output_for,thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,transcript_top_padding, unescape_partial_json_string, user_content_parts,- with_real_think_tag_gate, worktree_command, await_worktree_report, spawn_worktree_report,+ with_real_think_tag_gate, worktree_command, await_job, spawn_worktree_report,+ worktrees_command, spawn_worktrees_job, finish_worktrees_job, worktrees_picker_items,+ open_worktrees_picker, worktrees_action, WorktreesDone, WorktreesJob,finish_worktree_report, AgentStatus, App, CompactKind, ContextReport,ContextSegment, CurrentRun, Readout, McpField, McpPrompt, MonitorSet, Pending,PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeRequest, ResumeTarget, Row,@@ -27278,7 +28392,7 @@ mod tests {assert_eq!(text, "Error - 429");assert_eq!(style.fg, Some(ratatui::style::Color::Red));assert_eq!(words(AgentStatus::Queued(2)).0, "Queued (2)");- assert_eq!(words(AgentStatus::Waiting(Some(3))).0, "Waiting (phase 3)");+ assert_eq!(words(AgentStatus::Waiting(Some(3))).0, "Queued \u{b7} phase 3");assert_eq!(words(AgentStatus::Parked).0, "Waiting on background work");}@@ -27754,7 +28868,7 @@ mod tests {let text = subagent_text(&mut app, 80, Instant::now()).join("\n");assert!(- text.contains("collector") && text.contains("Waiting (phase 2)"),+ text.contains("collector") && text.contains("Queued \u{b7} phase 2"),"the waiting hint is shown: {text}");@@ -27776,6 +28890,97 @@ mod tests {);}+ /// A multi-phase dispatch, driven by the events the core sends in order:+ /// the call, its `SubagentPlan`, phase 0's start, the result, then a later+ /// phase's start and the end of one stopped before it started. Only a+ /// started child reads as dispatched or running; a later-phase one reads+ /// as queued for its phase on every surface until its own start flips it,+ /// and one stopped before it started ends instead of waiting forever.+ #[test]+ fn a_later_phase_child_reads_queued_until_it_starts() {+ use crate::core::agent::events::PendingSubagent;+ let mut app = test_app();+ let now = Instant::now();+ app.apply(StreamEvent::ToolCall {+ id: "d1".into(),+ name: "dispatch_subagent".into(),+ args: json!({ "subagents": [+ { "agent": "explore", "task": "Find the parser." },+ { "agent": "collector", "task": "Merge the findings.", "phase": 2 },+ { "agent": "general", "task": "Write it up.", "phase": 2 },+ ] }),+ });+ assert!(transcript_text(&app).contains("\u{2022} Queueing collector \u{b7} phase 2\n"));+ app.apply(StreamEvent::SubagentPlan {+ pending: ["collector", "general"]+ .map(|name| PendingSubagent { name: name.into(), phase: 2 })+ .to_vec(),+ });+ start_subagent(&mut app, "sub-explore-1", "explore");+ app.apply(StreamEvent::ToolResult {+ id: "d1".into(),+ content: crate::core::agent::subagent::worker_names_line(&[+ "explore".to_string(),+ "collector".to_string(),+ "general".to_string(),+ ]),+ is_error: false,+ diff: None,+ });+ let text = transcript_text(&app);+ assert!(text.contains("\u{2022} Dispatched explore\n"), "{text}");+ assert!(+ text.contains(concat!(+ "\u{2022} Queued collector \u{b7} phase 2\n",+ " \u{2514} Merge the findings."+ )),+ "{text}"+ );+ assert!(!text.contains("Dispatched collector"), "{text}");+ assert!(!text.contains("Dispatched general"), "{text}");+ let block = subagent_text(&mut app, 100, now);+ assert_eq!(block[0], " 1 subagent running \u{b7} 2 queued \u{b7} /agents to view or stop");+ // The plan announces its later phases before phase 0 starts, so+ // their panels come first.+ assert!(block[1].ends_with("collector \u{b7} Queued \u{b7} phase 2"), "{block:?}");+ assert!(block[3].contains("explore") && !block[3].contains("Queued"), "{block:?}");+ let items = agent_picker_items(&mut app.subagents, &[], &[], 128_000);+ assert!(items[0].label.ends_with("Queued \u{b7} phase 2"), "{}", items[0].label);+ assert!(items[2].label.contains("Running"), "{}", items[2].label);+ let header = super::agent_detail_header(&mut app.subagents[0], None, 128_000, 80);+ let header: String = header[1].spans.iter().map(|s| s.content.as_ref()).collect();+ assert_eq!(header, "Queued \u{b7} phase 2");++ // A child stopped before it started ends under a run id no panel+ // knows: its end falls back to the waiting panel of its name, so its+ // row closes rather than waiting forever.+ app.apply(StreamEvent::SubagentEnd {+ run_id: "sub-general-stopped-9".into(),+ name: "general".into(),+ error: Some("stopped by the parent agent before it started".into()),+ });+ let names: Vec<&str> = app.subagents.iter().map(|p| p.name.as_str()).collect();+ assert_eq!(names, ["collector", "explore"], "only the stopped row is gone");+ let text = transcript_text(&app);+ assert!(+ text.contains("Finished general")+ && text.contains("Error - stopped by the parent agent before it started"),+ "{text}"+ );++ // Phase 0 ends and the next phase starts: the label flips in place.+ app.apply(StreamEvent::SubagentEnd {+ run_id: "sub-explore-1".into(),+ name: "explore".into(),+ error: None,+ });+ start_subagent(&mut app, "sub-collector-1", "collector");+ let block = subagent_text(&mut app, 100, now);+ assert_eq!(block[0], " 1 subagent running \u{b7} /agents to view or stop");+ assert!(!block[1].contains("Queued"), "{block:?}");+ assert_eq!(app.subagents[0].status(None), AgentStatus::Running);+ }+/// Enter on the `/agents` list drills into a child's detail; Esc steps back/// to the list rather than closing the inspector.#[tokio::test]@@ -27997,11 +29202,12 @@ mod tests {);}- /// `m` on a child's detail opens a message dock; Enter queues the text on- /// the child's inbox through the same `message_subagent` the parent agent- /// uses, so it lands as a plain user turn at the child's next boundary.+ /// The detail's input is the composer, aimed at the child: Enter queues+ /// the typed text on the child's inbox through the same `message_subagent`+ /// the parent agent uses, so it lands as a plain user turn at the child's+ /// next boundary, and the field clears for the next one.#[tokio::test]- async fn agents_detail_m_steers_the_child_like_the_parent_does() {+ async fn agents_detail_input_steers_the_child_like_the_parent_does() {let mut app = test_app();let inbox = crate::core::agent::subagent::tests::register_live_child(&app.subagent_set,@@ -28017,14 +29223,15 @@ mod tests {});open_agents_picker(&mut app);press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;- press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;- assert!(app.agent_message.is_some(), "m opens the message dock");- assert!(app.blocking_dock().is_some(), "the dock owns the keyboard");+ assert!(app.blocking_dock().is_none(), "no dock: the field itself is live");type_key_chars(&mut app, "also say BANANA").await;+ assert_eq!(app.input, "also say BANANA");+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("\u{203a} also say BANANA"), "{screen}");press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;- assert!(app.agent_message.is_none(), "Enter sends and closes the dock");+ assert!(app.input.is_empty(), "Enter sends and clears the field");assert_eq!(app.picker.as_ref().map(|p| p.kind),Some(PickerKind::AgentDetail),@@ -28061,6 +29268,1063 @@ mod tests {assert_eq!(parent.matches("BANANA").count(), 1, "{parent}");}+ /// Keys that type go into the field, not to the inspector: `m`, `x`, `j`,+ /// `k` and `q` were picker keys on this screen. Ctrl-X is the stop.+ #[tokio::test]+ async fn agents_detail_letters_type_and_ctrl_x_stops() {+ use crate::core::agent::subagent::tests::{child_is_finished, register_live_child};+ let mut app = test_app();+ register_live_child(&app.subagent_set, "sub-counter-1", "counter");+ start_subagent(&mut app, "sub-counter-1", "counter");+ open_agents_picker(&mut app);+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ type_key_chars(&mut app, "mxjkq").await;+ assert_eq!(app.input, "mxjkq");+ assert_eq!(+ app.picker.as_ref().map(|p| p.kind),+ Some(PickerKind::AgentDetail),+ "q does not leave the detail"+ );+ assert!(!child_is_finished(&app.subagent_set, "sub-counter-1"), "x typed");+ press(&mut app, KeyCode::Char('x'), KeyModifiers::CONTROL).await;+ assert!(child_is_finished(&app.subagent_set, "sub-counter-1"));+ assert_eq!(app.input, "mxjkq", "the stop leaves the draft alone");+ }++ /// A running child shows the main view's working row under its panel,+ /// with the steer hint aimed at it, instead of a dead `selecting` row:+ /// between a child's events (a request in flight, a folded thought) that+ /// row is the one thing on screen that moves.+ #[test]+ fn agents_detail_shows_the_childs_working_row() {+ let mut app = app_with_child_activity();+ let text = agent_detail_text(&mut app, "sub-counter-1", 100, 30);+ assert!(!text.contains("selecting"), "{text}");+ assert!(text.contains("working\u{2026}"), "{text}");+ assert!(text.contains("type to message counter"), "{text}");+ }++ /// A parked child is not generating, so the field offers itself with the+ /// main composer's placeholder, addressed to the child.+ #[test]+ fn agents_detail_placeholder_names_an_idle_child() {+ let mut app = app_with_child_activity();+ subagent_event(&mut app, "sub-counter-1", "counter", StreamEvent::Parked);+ let text = agent_detail_text(&mut app, "sub-counter-1", 100, 30);+ assert!(text.contains("Message counter\u{2026}"), "{text}");+ }++ /// Streamed text reaches the open detail as it arrives, with the main run+ /// idle: a child's events are applied and drawn on their own, not only+ /// alongside the parent's.+ #[test]+ fn a_child_token_streams_into_the_open_detail_while_main_is_idle() {+ let mut app = app_with_child_activity();+ app.status = Status::Idle;+ let before = agent_detail_text(&mut app, "sub-counter-1", 100, 30);+ assert!(!before.contains("half a sent"), "{before}");+ subagent_event(+ &mut app,+ "sub-counter-1",+ "counter",+ StreamEvent::Token { text: " Now half a sent".into() },+ );+ assert!(app.animating(), "a live child keeps the frame gate drawing");+ let after = render_rows(&mut app, 100, 30).join("\n");+ assert!(after.contains("half a sent"), "{after}");+ }++ /// A finished child takes no steering: the field says so and typing does+ /// nothing, rather than queueing text for the main agent from a screen+ /// about someone else. Esc still goes back.+ #[tokio::test]+ async fn agents_detail_of_a_finished_child_takes_no_input() {+ let mut app = app_with_child_activity();+ app.apply(StreamEvent::SubagentEnd {+ run_id: "sub-counter-1".into(),+ name: "counter".into(),+ error: None,+ });+ let text = agent_detail_text(&mut app, "sub-counter-1", 100, 30);+ assert!(text.contains("counter has finished"), "{text}");+ type_key_chars(&mut app, "hello").await;+ assert!(app.input.is_empty(), "{:?}", app.input);+ // Nor does a paste: the field cannot send it.+ route_paste_event(&mut app, Event::Paste("pasted".into()));+ assert!(app.input.is_empty(), "{:?}", app.input);+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::Agents));+ }++ /// `counter`, live in the registry and on screen, with `/agents` open on+ /// its detail, as the user reaches it; and the inbox it reads.+ async fn counter_detail(+ app: &mut App,+ ) -> std::sync::Arc<crate::core::agent::subagent::ChildInbox> {+ let inbox = crate::core::agent::subagent::tests::register_live_child(+ &app.subagent_set,+ "sub-counter-1",+ "counter",+ );+ start_subagent(app, "sub-counter-1", "counter");+ open_agents_picker(app);+ press(app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ inbox+ }++ /// Deliver a key the way the event loop does: a queued `ask` sees it+ /// first, and only what it declines reaches `handle_key`.+ async fn press_routed(+ app: &mut App,+ asks: &crate::core::agent::interaction::AskRegistry,+ perms: &PermissionRegistry,+ code: KeyCode,+ mods: KeyModifiers,+ ) {+ let key = KeyEvent::new(code, mods);+ if !handle_ask_key(app, key, asks).await {+ handle_key(app, key, perms, &mut None, &no_mcp()).await;+ }+ }++ fn child_permission(app: &mut App, request_id: &str, command: &str) {+ subagent_event(+ app,+ "sub-counter-1",+ "counter",+ StreamEvent::PermissionRequest {+ request_id: request_id.into(),+ tool_name: "bash".into(),+ capability: "execute".into(),+ path: None,+ command: Some(command.into()),+ diff: None,+ prompt_kind: "exec".into(),+ offers_always: true,+ justification: None,+ },+ );+ }++ /// A child's permission request that lands while its detail is open is+ /// drawn over the detail, and what the user was typing answers nothing:+ /// `a` is not "allow always" and the Enter that would have sent the+ /// message does not confirm the highlighted option. Only an option picked+ /// with the arrows and confirmed with Enter answers it.+ #[tokio::test]+ async fn a_prompt_over_the_detail_is_drawn_and_typing_does_not_answer_it() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ app.status = Status::Running;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");++ for ch in "also".chars() {+ press_routed(&mut app, &asks, &perms, KeyCode::Char(ch), KeyModifiers::NONE).await;+ }+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.pending_queue.len(), 1, "nothing answered the prompt");+ assert!(decision.try_recv().is_err(), "no decision was sent");+ assert!(app.input.is_empty(), "nor did the letters type: {:?}", app.input);+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("permission required"), "{screen}");+ assert!(screen.contains("rm -rf build"), "{screen}");+ assert!(footer_text(&app).contains("pick"), "{}", footer_text(&app));++ // The first arrow arms on Deny, the next moves up to Allow always,+ // each a pause apart.+ settle_prompt(&mut app);+ let keys = [KeyCode::Down, KeyCode::Up, KeyCode::Enter];+ press_detail(&mut app, &asks, &perms, &keys, true).await;+ assert!(app.pending_queue.is_empty());+ assert_eq!(decision.try_recv().unwrap(), PermissionDecision::AllowAlways);+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ }++ /// The same for an `ask`: drawn over the detail, deaf to typing, and+ /// answered only by an arrow-picked Enter.+ #[tokio::test]+ async fn an_ask_over_the_detail_is_drawn_and_typing_does_not_answer_it() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (request_id, answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });++ for ch in "also".chars() {+ press_routed(&mut app, &asks, &perms, KeyCode::Char(ch), KeyModifiers::NONE).await;+ }+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ route_paste_event(&mut app, Event::Paste("pasted".into()));+ assert_eq!(app.ask_queue.len(), 1, "nothing answered the ask");+ assert!(app.ask_queue[0].answers[0].selected.is_empty());+ assert!(app.input.is_empty(), "{:?}", app.input);+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("Which scope?"), "{screen}");++ // The first arrow arms on "Other", the next moves up to Large.+ settle_prompt(&mut app);+ let keys = [KeyCode::Down, KeyCode::Up, KeyCode::Enter];+ press_detail(&mut app, &asks, &perms, &keys, true).await;+ assert!(app.ask_queue.is_empty());+ assert_eq!(answer.await.unwrap().unwrap()[0].selected, vec!["Large"]);+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ }++ /// Left/Right edit the draft over the detail: they neither arm the ask+ /// nor switch its question, so fixing a typo and pressing Enter answers+ /// nothing (for the plan review that would have been "Execute plan").+ #[tokio::test]+ async fn left_or_right_then_enter_over_the_detail_answers_no_ask() {+ for arrow in [KeyCode::Left, KeyCode::Right] {+ let mut app = test_app();+ counter_detail(&mut app).await;+ type_key_chars(&mut app, "tpyo").await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, true),+ timeout_secs: None,+ });+ press_routed(&mut app, &asks, &perms, KeyCode::Left, KeyModifiers::NONE).await;+ press_routed(&mut app, &asks, &perms, arrow, KeyModifiers::NONE).await;+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.ask_queue.len(), 1, "{arrow:?} then Enter answered the ask");+ let ask = &app.ask_queue[0];+ assert!(!ask.picked, "{arrow:?} armed the ask");+ assert_eq!(ask.question_index, 0, "{arrow:?} switched the question");+ assert!(ask.answers.iter().all(|a| a.selected.is_empty()));+ let expected = if arrow == KeyCode::Left { 2 } else { 4 };+ assert_eq!(app.cursor, expected, "{arrow:?} moves the draft's cursor");+ assert_eq!(app.input, "tpyo");+ }+ }++ /// Down is the detail's recall key, so over the detail a fresh prompt is+ /// drawn with no highlight, and the first arrow only arms it, on the row+ /// that grants nothing: a reflex Down then Enter denies rather than+ /// allowing once or always, and on an ask it opens the free-text field+ /// rather than choosing an option.+ #[tokio::test]+ async fn down_then_enter_over_the_detail_grants_nothing() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ let marked = |app: &mut App, label: &str| {+ let mark = format!("{}{label}", super::SELECT_MARK);+ render_rows(app, 100, 30).iter().any(|row| row.contains(&mark))+ };+ assert!(!marked(&mut app, "Allow once"), "an unarmed prompt marks nothing");+ assert!(!marked(&mut app, "Deny"), "an unarmed prompt marks nothing");+ assert!(!footer_text(&app).contains("Enter"), "{}", footer_text(&app));++ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[KeyCode::Down], true).await;+ assert!(marked(&mut app, "Deny"), "armed, on Deny");+ assert!(footer_text(&app).contains("Enter"), "{}", footer_text(&app));+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(decision.try_recv().unwrap(), PermissionDecision::Deny);++ // The same rule for an ask.+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ assert!(!marked(&mut app, "\u{25cb} Small"), "an unarmed ask marks nothing");+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[KeyCode::Down], true).await;+ assert!(marked(&mut app, "\u{25cb} Other"), "armed, on Other");+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.ask_queue.len(), 1, "nothing was answered");+ assert!(app.ask_queue[0].answers[0].selected.is_empty());+ }++ /// Lets the pause run out on the prompt on screen, as if the user had+ /// stopped to read it (`PROMPT_PAUSE`), without sleeping.+ /// The last key is forgotten too, so the next press is a fresh one rather+ /// than a held key's repeat (`HELD_KEY_WINDOW`). The arrow that last+ /// stepped the prompt is kept: a pause this short does not free it+ /// (`STEP_AGAIN_WINDOW`).+ fn settle_prompt(app: &mut App) {+ let pause = match app.ask_queue.front_mut() {+ Some(ask) => &mut ask.pause,+ None => match app.pending_queue.front_mut() {+ Some(pending) => &mut pending.pause,+ None => return,+ },+ };+ pause.until = Some(Instant::now());+ pause.last_key = None;+ }++ /// A key over the detail, then the pause runs out when `settle` asks.+ async fn press_detail(+ app: &mut App,+ asks: &crate::core::agent::interaction::AskRegistry,+ perms: &PermissionRegistry,+ keys: &[KeyCode],+ settle: bool,+ ) {+ for &code in keys {+ press_routed(app, asks, perms, code, KeyModifiers::NONE).await;+ if settle {+ settle_prompt(app);+ }+ }+ }++ /// Two reflex arrows then Enter, typed faster than the pause, grant nothing+ /// over the detail: Down Down does not wrap from Deny to Allow once, and Up+ /// Up Enter (recalling the message two back) does not allow always. The+ /// prompt has been up a while first, so the arming arrow itself counts.+ #[tokio::test]+ async fn two_fast_arrows_then_enter_over_the_detail_grant_nothing() {+ for arrow in [KeyCode::Down, KeyCode::Up] {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[arrow, arrow, KeyCode::Enter], false).await;+ assert_eq!(app.pending_queue.len(), 1, "{arrow:?} {arrow:?} Enter answered");+ assert!(decision.try_recv().is_err(), "{arrow:?} {arrow:?} Enter decided");+ assert!(!footer_text(&app).contains("Enter"), "{}", footer_text(&app));++ // The same for an ask: neither option 0 nor the last is chosen.+ app.pending_queue.clear();+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[arrow, arrow, KeyCode::Enter], false).await;+ assert_eq!(app.ask_queue.len(), 1, "{arrow:?} {arrow:?} Enter answered the ask");+ let ask = &app.ask_queue[0];+ assert!(ask.answers[0].selected.is_empty(), "{arrow:?}: {:?}", ask.answers);+ assert!(!ask.editing_custom, "{arrow:?} {arrow:?} Enter opened Other");+ }+ }++ /// With the pause run out before Enter, Enter confirms the highlighted+ /// row. Fast arrows count only once (the second lands inside the pause the+ /// first started), and arrows a pause apart move but clamp at the ends: Down+ /// Down stays on Deny rather than wrapping to Allow once.+ #[tokio::test]+ async fn arrows_then_a_pause_then_enter_over_the_detail_pick_the_highlight() {+ let cases = [+ (KeyCode::Down, false, PermissionDecision::Deny),+ (KeyCode::Up, false, PermissionDecision::Deny),+ (KeyCode::Down, true, PermissionDecision::Deny),+ (KeyCode::Up, true, PermissionDecision::AllowAlways),+ ];+ for (arrow, paused, expected) in cases {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[arrow, arrow], paused).await;+ settle_prompt(&mut app);+ assert!(footer_text(&app).contains("Enter"), "{}", footer_text(&app));+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ let got = decision.try_recv();+ assert_eq!(got.ok(), Some(expected), "{arrow:?} {arrow:?} paused={paused}");+ }++ // An ask has Small, Large, Other: Up Up a pause apart lands on Large;+ // fast, or Down Down, it stays on Other, whose Enter opens the field.+ for (arrow, paused, chosen) in [+ (KeyCode::Up, true, Some("Large")),+ (KeyCode::Up, false, None),+ (KeyCode::Down, true, None),+ ] {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (request_id, answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[arrow, arrow], paused).await;+ settle_prompt(&mut app);+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ match chosen {+ Some(label) => {+ assert!(app.ask_queue.is_empty(), "{arrow:?} paused={paused}");+ assert_eq!(answer.await.unwrap().unwrap()[0].selected, vec![label]);+ }+ None => {+ assert_eq!(app.ask_queue.len(), 1, "{arrow:?} paused={paused}");+ assert!(app.ask_queue[0].editing_custom, "{arrow:?} paused={paused}");+ }+ }+ }+ }++ /// What the user types for the child never becomes the ask's answer: a+ /// reflex Down (recall) and Enter (send) do not open the free-text field,+ /// so the next message and its Enter answer nothing. Opened deliberately,+ /// the field is labelled inside the box, and Esc closes it back to the+ /// options rather than leaving the detail.+ #[tokio::test]+ async fn typing_for_the_child_never_answers_an_ask_over_the_detail() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[KeyCode::Down, KeyCode::Enter], false).await;+ for ch in "next message".chars() {+ press_routed(&mut app, &asks, &perms, KeyCode::Char(ch), KeyModifiers::NONE).await;+ }+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.ask_queue.len(), 1, "the typed message answered the ask");+ let ask = &app.ask_queue[0];+ assert!(!ask.editing_custom, "the reflex Enter opened the field");+ assert_eq!(ask.answers[0].custom_input, None);++ settle_prompt(&mut app);+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(app.ask_queue[0].editing_custom, "a paused Enter on Other opens it");+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("your answer"), "{screen}");+ assert!(footer_text(&app).contains("Esc options"), "{}", footer_text(&app));+ press_routed(&mut app, &asks, &perms, KeyCode::Esc, KeyModifiers::NONE).await;+ assert!(!app.ask_queue[0].editing_custom, "Esc closes the field");+ assert_eq!(app.ask_queue.len(), 1);+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ }++ /// Answering question 1 over the detail does not leave question 2 armed:+ /// it opens unarmed, like a fresh prompt, so Enter Enter answers nothing.+ #[tokio::test]+ async fn the_next_question_over_the_detail_opens_unarmed() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, true),+ timeout_secs: None,+ });+ settle_prompt(&mut app);+ let keys = [KeyCode::Down, KeyCode::Up, KeyCode::Enter];+ press_detail(&mut app, &asks, &perms, &keys, true).await;+ assert_eq!(app.ask_queue[0].answers[0].selected, vec!["Large"]);+ assert_eq!(app.ask_queue[0].question_index, 1);+ press_detail(&mut app, &asks, &perms, &[KeyCode::Enter, KeyCode::Enter], true).await;+ assert_eq!(app.ask_queue.len(), 1, "question 2 was answered unarmed");+ assert!(app.ask_queue[0].answers[1].selected.is_empty());+ assert!(!footer_text(&app).contains("Enter"), "{}", footer_text(&app));+ }++ /// `by` passes for the prompt on screen, without sleeping: its pause and+ /// its last key's press move that far into the past.+ fn elapse(app: &mut App, by: Duration) {+ let back = |at: Instant| at.checked_sub(by).expect("monotonic clock this far back");+ let pause = match app.ask_queue.front_mut() {+ Some(ask) => &mut ask.pause,+ None => &mut app.pending_queue.front_mut().expect("a prompt on screen").pause,+ };+ pause.until = pause.until.map(back);+ pause.last_key = pause.last_key.map(|(code, at)| (code, back(at)));+ pause.stepped = pause.stepped.map(|(code, at)| (code, back(at)));+ }++ /// A held key, as the TUI gets it without keyboard enhancement: a press,+ /// its first repeat after the OS repeat delay `delay`, then repeats every+ /// 33 ms, then the release and a pause.+ async fn hold_key(+ app: &mut App,+ asks: &crate::core::agent::interaction::AskRegistry,+ perms: &PermissionRegistry,+ code: KeyCode,+ delay: Duration,+ ) {+ press_routed(app, asks, perms, code, KeyModifiers::NONE).await;+ elapse(app, delay);+ for _ in 0..10 {+ press_routed(app, asks, perms, code, KeyModifiers::NONE).await;+ elapse(app, Duration::from_millis(33));+ }+ elapse(app, PROMPT_PAUSE);+ }++ /// The OS repeat delays a held key is checked against: GNOME and Windows'+ /// default, X11's `xset` default, a slow one a user might pick, and none+ /// (the repeats start at once).+ const REPEAT_DELAYS: [u64; 4] = [500, 660, 1000, 33];++ /// Holding an arrow over the detail counts as one press: it arms the+ /// prompt on its safe row and its repeats never move it, so after the+ /// release and a pause Enter denies (or, on an ask, opens "Other") rather+ /// than granting the row a repeat would have reached.+ #[tokio::test]+ async fn a_held_arrow_over_the_detail_only_arms() {+ for arrow in [KeyCode::Up, KeyCode::Down] {+ for delay in REPEAT_DELAYS.map(Duration::from_millis) {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ settle_prompt(&mut app);+ hold_key(&mut app, &asks, &perms, arrow, delay).await;+ let pending = &app.pending_queue[0];+ assert!(pending.picked, "{arrow:?} held {delay:?} did not arm");+ assert_eq!(pending.selected, 2, "{arrow:?} held {delay:?} moved off Deny");+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ let got = decision.try_recv().ok();+ assert_eq!(got, Some(PermissionDecision::Deny), "{arrow:?} held {delay:?}");++ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ settle_prompt(&mut app);+ hold_key(&mut app, &asks, &perms, arrow, delay).await;+ assert_eq!(app.ask_queue[0].selected, 2, "{arrow:?} held {delay:?} left Other");+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.ask_queue.len(), 1, "{arrow:?} held {delay:?} answered the ask");+ assert!(app.ask_queue[0].answers[0].selected.is_empty());+ assert!(app.ask_queue[0].editing_custom, "Enter on Other opens the field");+ }+ }+ }++ /// Deliberate presses still move: the same arrow again once a held key's+ /// repeat would have come, or a different key a pause after the last.+ #[tokio::test]+ async fn distinct_presses_a_pause_apart_over_the_detail_still_move() {+ let cases = [+ ([KeyCode::Up, KeyCode::Up], HELD_KEY_WINDOW, PermissionDecision::AllowAlways),+ ([KeyCode::Down, KeyCode::Up], PROMPT_PAUSE, PermissionDecision::AllowAlways),+ ([KeyCode::Up, KeyCode::Up], PROMPT_PAUSE, PermissionDecision::Deny),+ ];+ for (keys, gap, expected) in cases {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ settle_prompt(&mut app);+ for code in keys {+ press_routed(&mut app, &asks, &perms, code, KeyModifiers::NONE).await;+ elapse(&mut app, gap);+ }+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(decision.try_recv().ok(), Some(expected), "{keys:?} {gap:?} apart");+ }+ }++ /// An arrow held with a repeat slower than `HELD_KEY_WINDOW` lands each+ /// repeat as a fresh press. Over the detail it still takes one step past+ /// the arming at most: once an armed arrow has moved, the same arrow moves+ /// again only after a different key or `STEP_AGAIN_WINDOW` of quiet, so+ /// the held Up stops on Allow always rather than walking on to Allow once.+ #[tokio::test]+ async fn a_slow_repeating_arrow_over_the_detail_moves_one_step_at_most() {+ let slow = HELD_KEY_WINDOW + Duration::from_millis(100);+ let quiet = STEP_AGAIN_WINDOW + Duration::from_millis(100);+ // (keys, gap after each, decision): a slow held Up, then deliberate+ // presses that still reach Allow once: after a long quiet, or with a+ // different key between.+ let cases = [+ (vec![KeyCode::Up; 6], slow, PermissionDecision::AllowAlways),+ (vec![KeyCode::Up; 3], quiet, PermissionDecision::AllowOnce),+ (+ vec![KeyCode::Up, KeyCode::Up, KeyCode::Char('x'), KeyCode::Up],+ slow,+ PermissionDecision::AllowOnce,+ ),+ ];+ for (keys, gap, expected) in cases {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ settle_prompt(&mut app);+ for &code in &keys {+ press_routed(&mut app, &asks, &perms, code, KeyModifiers::NONE).await;+ elapse(&mut app, gap);+ }+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(decision.try_recv().ok(), Some(expected), "{keys:?} {gap:?} apart");+ }++ // An ask (Small, Large, Other): the slow held Up stops on Large.+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (request_id, answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ settle_prompt(&mut app);+ for _ in 0..6 {+ press_routed(&mut app, &asks, &perms, KeyCode::Up, KeyModifiers::NONE).await;+ elapse(&mut app, slow);+ }+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(answer.await.unwrap().unwrap()[0].selected, vec!["Large"]);+ }++ /// A permission request covered by a newer ask comes back from behind it+ /// unarmed and with a fresh pause: the reflex second Enter of the one that+ /// answered the ask does not confirm what the user had armed on it before.+ #[tokio::test]+ async fn a_request_uncovered_by_an_answered_ask_returns_unarmed() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ render_rows(&mut app, 100, 30);+ settle_prompt(&mut app);+ press_detail(&mut app, &asks, &perms, &[KeyCode::Down, KeyCode::Up], true).await;+ assert_eq!(app.pending_queue[0].selected, 1, "armed on Allow always");++ let (request_id, answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ render_rows(&mut app, 100, 30);+ settle_prompt(&mut app);+ let keys = [KeyCode::Down, KeyCode::Up, KeyCode::Enter];+ press_detail(&mut app, &asks, &perms, &keys, true).await;+ assert_eq!(answer.await.unwrap().unwrap()[0].selected, vec!["Large"]);+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(decision.try_recv().is_err(), "the reflex Enter confirmed the request");++ // Drawn again, it still has to be armed after its pause, on Deny.+ render_rows(&mut app, 100, 30);+ let pending = &app.pending_queue[0];+ assert!(!pending.picked, "the uncovered request is still armed");+ assert!(pending.pause.until.is_some_and(|until| until > Instant::now()));+ settle_prompt(&mut app);+ assert!(!footer_text(&app).contains("Enter"), "{}", footer_text(&app));+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(decision.try_recv().is_err(), "an unarmed Enter decided");+ }++ /// A prompt armed in the main view and then shown over the detail (the+ /// detail opened, say with the mouse, while it waits) lands there unarmed:+ /// the Enter the user then types for the child does not confirm the row+ /// they had moved to before, and nothing is marked until an arrow arms it.+ #[tokio::test]+ async fn a_prompt_armed_in_the_main_view_lands_unarmed_over_the_detail() {+ let open_detail = |app: &mut App| {+ open_agents_picker(app);+ app.enter_agent_detail("sub-counter-1".to_string());+ assert!(app.agent_detail_open());+ };+ let marks_any = |app: &mut App| {+ let mark = super::SELECT_MARK;+ render_rows(app, 100, 30).iter().any(|row| row.contains(mark))+ };+ let mut app = test_app();+ start_subagent(&mut app, "sub-counter-1", "counter");+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "rm -rf build");+ render_rows(&mut app, 100, 30);+ press_routed(&mut app, &asks, &perms, KeyCode::Down, KeyModifiers::NONE).await;+ assert!(app.pending_queue[0].picked, "Down arms it in the main view");+ assert_eq!(app.pending_queue[0].selected, 1, "on Allow always");++ open_detail(&mut app);+ assert!(!marks_any(&mut app), "the moved prompt is still armed");+ assert!(!app.pending_queue[0].picked, "the moved prompt is still armed");+ settle_prompt(&mut app);+ assert!(!footer_text(&app).contains("Enter"), "{}", footer_text(&app));+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(decision.try_recv().is_err(), "Enter confirmed the main view's arming");+ assert_eq!(app.pending_queue.len(), 1);++ // The same for an ask armed in the main view.+ app.pending_queue.clear();+ app.picker = None;+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ render_rows(&mut app, 100, 30);+ press_routed(&mut app, &asks, &perms, KeyCode::Down, KeyModifiers::NONE).await;+ assert!(app.ask_queue[0].picked, "Down arms the ask in the main view");+ open_detail(&mut app);+ assert!(!marks_any(&mut app), "the moved ask is still armed");+ assert!(!app.ask_queue[0].picked, "the moved ask is still armed");+ settle_prompt(&mut app);+ press_routed(&mut app, &asks, &perms, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.ask_queue.len(), 1, "Enter answered the ask");+ assert!(app.ask_queue[0].answers[0].selected.is_empty());+ assert!(!app.ask_queue[0].editing_custom, "Enter opened Other");+ }++ /// With a prompt over the detail the child's run still scrolls: PgUp/PgDn,+ /// Home/End on an empty field, and the wheel reach the detail, so the+ /// user can read what the child did before deciding.+ #[tokio::test]+ async fn the_detail_scrolls_under_a_prompt() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "ls");+ for (prompt, ask) in [("permission", false), ("ask", true)] {+ if ask {+ let (request_id, _answer) = crate::core::agent::interaction::register(&asks).await;+ app.apply(StreamEvent::AskRequest {+ request_id,+ request: ask_request(false, false),+ timeout_secs: None,+ });+ }+ app.agent_detail_scroll = 0;+ press_routed(&mut app, &asks, &perms, KeyCode::PageUp, KeyModifiers::NONE).await;+ assert_eq!(app.agent_detail_scroll, 10, "PgUp under the {prompt}");+ press_routed(&mut app, &asks, &perms, KeyCode::PageDown, KeyModifiers::NONE).await;+ assert_eq!(app.agent_detail_scroll, 0, "PgDn under the {prompt}");+ press_routed(&mut app, &asks, &perms, KeyCode::Home, KeyModifiers::NONE).await;+ assert_eq!(app.agent_detail_scroll, u16::MAX, "Home under the {prompt}");+ press_routed(&mut app, &asks, &perms, KeyCode::End, KeyModifiers::NONE).await;+ assert_eq!(app.agent_detail_scroll, 0, "End under the {prompt}");+ let wheel = mouse_at(MouseEventKind::ScrollUp, 5, 5);+ if !handle_ask_mouse(&mut app, wheel, &asks).await {+ handle_mouse(&mut app, wheel);+ }+ assert_eq!(app.agent_detail_scroll, 1, "the wheel under the {prompt}");+ }+ assert_eq!(app.pending_queue.len(), 1);+ assert_eq!(app.ask_queue.len(), 1);+ assert!(decision.try_recv().is_err());+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ }++ /// A draft kept under a prompt says why Enter will not send it.+ #[tokio::test]+ async fn a_draft_under_a_prompt_says_enter_will_not_send_it() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ type_key_chars(&mut app, "also").await;+ child_permission(&mut app, "p1", "ls");+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("also"), "{screen}");+ assert!(screen.contains("answer the prompt above"), "{screen}");+ }++ /// Ctrl-C in the detail clears the draft, then closes the inspector. It+ /// never cancels the main run or arms the exit, and with a prompt up it+ /// neither denies it nor cancels anything: the prompt waits in the main+ /// view.+ #[tokio::test]+ async fn ctrl_c_in_the_detail_never_cancels_the_main_run() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ app.status = Status::Running;+ assert!(footer_text(&app).contains("^C close"), "{}", footer_text(&app));+ type_key_chars(&mut app, "draft").await;+ press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;+ assert!(app.input.is_empty());+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;+ assert!(app.picker.is_none(), "the empty field closes the inspector");+ assert_eq!(app.status, Status::Running, "the main run goes on");+ assert!(!app.should_quit && !app.exit_armed);++ open_agents_picker(&mut app);+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ let asks = crate::core::agent::interaction::new_registry();+ let perms = PermissionRegistry::default();+ let (tx, mut decision) = tokio::sync::oneshot::channel();+ perms.lock().await.insert("p1".to_string(), tx);+ child_permission(&mut app, "p1", "ls");+ let ctrl_c = (KeyCode::Char('c'), KeyModifiers::CONTROL);+ press_routed(&mut app, &asks, &perms, ctrl_c.0, ctrl_c.1).await;+ assert!(app.picker.is_none());+ assert_eq!(app.pending_queue.len(), 1, "the prompt still waits");+ assert!(decision.try_recv().is_err(), "nothing was denied");+ assert_eq!(app.status, Status::Running);+ assert!(!app.should_quit && !app.exit_armed);+ }++ /// The `Pending (n)` cue counts what was sent and not yet taken: it rises+ /// with each send and falls as the child takes each message.+ #[tokio::test]+ async fn the_detail_pending_cue_rises_on_send_and_falls_on_delivery() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ let screen = |app: &mut App| render_rows(app, 100, 30).join("\n");+ for text in ["one", "two"] {+ type_key_chars(&mut app, text).await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ }+ assert!(screen(&mut app).contains("Pending (2)"), "{}", screen(&mut app));+ for text in ["one", "two"] {+ subagent_event(+ &mut app,+ "sub-counter-1",+ "counter",+ StreamEvent::AgentMessage {+ from: super::MAIN_AGENT.into(),+ to: "counter".into(),+ text: text.into(),+ },+ );+ if text == "one" {+ assert!(screen(&mut app).contains("Pending (1)"), "{}", screen(&mut app));+ }+ }+ assert!(!screen(&mut app).contains("Pending ("), "{}", screen(&mut app));+ }++ /// A live child's field takes a paste like the main composer does.+ #[tokio::test]+ async fn a_paste_lands_in_a_live_childs_field() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ route_paste_event(&mut app, Event::Paste("look at a.rs".into()));+ assert_eq!(app.input, "look at a.rs");+ }++ /// The `/agents` list has no field: a paste there is dropped, not hidden in+ /// the composer to turn up later as a message to a child.+ #[tokio::test]+ async fn a_paste_on_the_agents_list_goes_nowhere() {+ let mut app = test_app();+ crate::core::agent::subagent::tests::register_live_child(+ &app.subagent_set,+ "sub-counter-1",+ "counter",+ );+ start_subagent(&mut app, "sub-counter-1", "counter");+ open_agents_picker(&mut app);+ route_paste_event(&mut app, Event::Paste("stray".into()));+ assert!(app.input.is_empty(), "{:?}", app.input);+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert!(app.input.is_empty(), "{:?}", app.input);+ }++ /// Up/Down in the detail recall what was sent to children, on an empty+ /// field, and otherwise scroll the child's run. The main composer's recall+ /// is its own: a steer never comes back there to go to the main agent.+ #[tokio::test]+ async fn detail_recall_is_the_detail_own_and_scrolls_otherwise() {+ let mut app = test_app();+ counter_detail(&mut app).await;+ press(&mut app, KeyCode::Up, KeyModifiers::NONE).await;+ assert_eq!(app.agent_detail_scroll, 1, "nothing to recall: Up scrolls");+ press(&mut app, KeyCode::Down, KeyModifiers::NONE).await;+ assert_eq!(app.agent_detail_scroll, 0);++ type_key_chars(&mut app, "first").await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ press(&mut app, KeyCode::Up, KeyModifiers::NONE).await;+ assert_eq!(app.input, "first", "Up recalls the sent message");+ press(&mut app, KeyCode::Down, KeyModifiers::NONE).await;+ assert!(app.input.is_empty());+ type_key_chars(&mut app, "x").await;+ press(&mut app, KeyCode::Up, KeyModifiers::NONE).await;+ assert_eq!(app.input, "x", "with a draft, Up scrolls");+ assert_eq!(app.agent_detail_scroll, 1);++ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert!(app.picker.is_none());+ press(&mut app, KeyCode::Up, KeyModifiers::NONE).await;+ assert!(app.input.is_empty(), "a steer is not main recall: {:?}", app.input);+ assert_eq!(app.scrollback, 1, "with nothing to recall, Up scrolls");+ }++ /// The main composer's draft and scroll position are where they were+ /// after a visit to a child's detail, whatever was typed or scrolled there.+ #[tokio::test]+ async fn the_main_draft_and_scrollback_survive_the_detail() {+ let mut app = test_app();+ app.scrollback = 4;+ app.set_input("main draft".to_string());+ counter_detail(&mut app).await;+ assert!(app.input.is_empty(), "the detail's field is its own");+ press(&mut app, KeyCode::PageUp, KeyModifiers::NONE).await;+ type_key_chars(&mut app, "for the child").await;+ assert_eq!(app.scrollback, 4);+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert!(app.picker.is_none());+ assert_eq!(app.input, "main draft");+ assert_eq!(app.scrollback, 4);+ }++ /// Another screen replacing the detail (a plugin collection listing+ /// arriving) leaves no child draft in the main composer, where the next+ /// Enter would send it to the main agent.+ #[tokio::test]+ async fn a_picker_replacing_the_detail_restores_the_main_composer() {+ let mut app = test_app();+ app.set_input("main draft".to_string());+ counter_detail(&mut app).await;+ type_key_chars(&mut app, "for the child").await;+ finish_plugin_install(+ &mut app,+ Some("file:///tmp/collection".to_string()),+ Ok(crate::core::agent::plugins::GitInstall::Collection(vec![+ crate::core::agent::plugins::CollectionPlugin {+ path: "alpha".to_string(),+ installed: false,+ },+ ])),+ );+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::PluginSelect));+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert!(app.picker.is_none());+ assert_eq!(app.input, "main draft");+ assert!(app.agent_detail.is_none());+ }++ /// The field is a message to the child, which runs no commands: a+ /// `/word` typed there is sent as written.+ #[tokio::test]+ async fn a_typed_command_in_the_detail_is_sent_verbatim() {+ let mut app = test_app();+ let inbox = counter_detail(&mut app).await;+ app.submit_user("keep me".to_string());+ type_key_chars(&mut app, "/clear").await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(inbox.drain().1, vec!["/clear".to_string()]);+ assert!(transcript_text(&app).contains("keep me"), "nothing was cleared");+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::AgentDetail));+ }++ /// The registry marks the child finished before its end reaches the+ /// screen: the core takes the message without queueing it, so it is not+ /// shown as sent. The draft stays and the reason shows on the input row.+ #[tokio::test]+ async fn a_message_to_a_child_that_just_finished_is_not_shown_as_sent() {+ let mut app = test_app();+ let inbox = counter_detail(&mut app).await;+ crate::core::agent::subagent::stop_subagent(&app.subagent_set, "sub-counter-1").unwrap();+ type_key_chars(&mut app, "late").await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.input, "late", "the draft is kept");+ assert_eq!(app.subagents[0].steers_pending, 0);+ assert!(!transcript_text(&app).contains("Message to counter"), "{}", transcript_text(&app));+ assert!(inbox.drain().0.is_empty());+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("already finished"), "{screen}");+ assert!(!screen.contains("Pending ("), "{screen}");+ }++ /// A refused send (a full inbox) leaves the child's run as it was: its+ /// running tool group is not closed, nothing is added to its rows, and+ /// the view is not moved. The error shows on the input row, over the+ /// draft it kept.+ #[tokio::test]+ async fn a_refused_send_leaves_the_childs_run_alone() {+ let mut app = test_app();+ let inbox = counter_detail(&mut app).await;+ subagent_event(+ &mut app,+ "sub-counter-1",+ "counter",+ StreamEvent::ToolCall {+ id: "c1".into(),+ name: "bash".into(),+ args: json!({ "command": "sleep 20" }),+ },+ );+ for i in 0..crate::core::agent::subagent::MAX_CHILD_INBOX {+ inbox.push(format!("m{i}")).unwrap();+ }+ let rows = app.subagents[0].transcript.rows.len();+ app.agent_detail_scroll = 2;+ type_key_chars(&mut app, "more").await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.input, "more");+ let child = &app.subagents[0].transcript;+ assert!(child.tool_group.is_some(), "the running group is still open");+ assert_eq!(child.rows.len(), rows, "nothing added to the child's run");+ assert_eq!(app.agent_detail_scroll, 2, "the view did not move");+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("inbox is full"), "{screen}");+ assert!(screen.contains("more"), "{screen}");+ }++ /// A modified Enter on an empty detail field is the detail's: it does not+ /// step a `/find` running on the main transcript behind it.+ #[tokio::test]+ async fn shift_enter_in_the_detail_does_not_step_a_main_find() {+ let mut app = long_answer_app();+ run_command(&mut app, "find answer line", &no_mcp()).await;+ let at = app.find.as_ref().and_then(|f| f.current);+ assert!(at.is_some());+ counter_detail(&mut app).await;+ press(&mut app, KeyCode::Enter, KeyModifiers::SHIFT).await;+ assert_eq!(app.find.as_ref().and_then(|f| f.current), at);+ press(&mut app, KeyCode::Enter, KeyModifiers::ALT).await;+ assert_eq!(app.find.as_ref().and_then(|f| f.current), at);+ assert!(app.input.is_empty(), "{:?}", app.input);+ }+/// A message is one entry: the main agent's `message_subagent` call reads/// as `Message to <name>` with the text under it, and the child taking it/// later (after the turn ended) appends nothing. A child's@@ -28310,56 +30574,27 @@ fn a() {}});}- /// The dock opens over the `/agents` inspector, whose draw path returns- /// before the ordinary dock chain: it must still be on screen, or the user- /// types into a field they cannot see.+ /// Esc abandons a draft without sending it, back on the `/agents` list,+ /// and keeps it in the steer recall rather than leaving it in the main+ /// composer, or in the main recall where Up would send it to main.#[tokio::test]- async fn agents_message_dock_is_drawn_over_the_inspector() {- let mut app = test_app();- crate::core::agent::subagent::tests::register_live_child(- &app.subagent_set,- "sub-counter-1",- "counter",- );- app.apply(StreamEvent::SubagentStart {- run_id: "sub-counter-1".to_string(),- name: "counter".to_string(),- task: None,- workspace: None,- internal: false,- });- open_agents_picker(&mut app);- press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;- press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;- type_key_chars(&mut app, "hello").await;- let screen = render_rows(&mut app, 100, 30).join("\n");- assert!(screen.contains("message subagent: counter"), "{screen}");- assert!(screen.contains("message: hello"), "{screen}");- }-- /// Esc abandons a message without sending it, back on the detail screen.- #[tokio::test]- async fn agents_message_dock_esc_sends_nothing() {+ async fn agents_detail_esc_sends_nothing() {let mut app = test_app();let inbox = crate::core::agent::subagent::tests::register_live_child(&app.subagent_set,"sub-counter-1","counter",);- app.apply(StreamEvent::SubagentStart {- run_id: "sub-counter-1".to_string(),- name: "counter".to_string(),- task: None,- workspace: None,- internal: false,- });+ start_subagent(&mut app, "sub-counter-1", "counter");open_agents_picker(&mut app);- press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;type_key_chars(&mut app, "never mind").await;press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;- assert!(app.agent_message.is_none());+ assert!(app.input.is_empty());assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::Agents));assert!(inbox.drain().0.is_empty());+ assert!(app.input_history.is_empty(), "{:?}", app.input_history);+ assert_eq!(app.steer_history.last().map(String::as_str), Some("never mind"));}/// `x` on the list stops the selected child through `stop_subagent`.@@ -28386,6 +30621,117 @@ fn a() {}));}+ /// A pending later-phase child (named by `SubagentPlan`, not started) has+ /// no run id yet, so `/agents` addresses it by its worker name: the core+ /// checks the plan's pending table under that name first. With no plan+ /// behind this test the core answers "no subagent named 'collector'",+ /// which is the proof the name -- not an empty id -- was what got sent.+ #[tokio::test]+ async fn agents_stop_and_message_a_pending_child_by_name() {+ use crate::core::agent::events::PendingSubagent;+ let mut app = test_app();+ app.apply(StreamEvent::SubagentPlan {+ pending: vec![PendingSubagent {+ name: "collector".to_string(),+ phase: 2,+ }],+ });+ open_agents_picker(&mut app);+ assert_eq!(app.picker.as_ref().unwrap().items[0].value, "collector");++ press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;+ let text = transcript_text(&app);+ assert!(text.contains("no subagent named 'collector'"), "{text}");++ // A refused message is reported where the user is looking, in the+ // child's view, and the draft stays for another try.+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ type_key_chars(&mut app, "hi").await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.input, "hi");+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(screen.contains("no subagent named 'collector'"), "{screen}");+ }++ /// Enter drills into a pending child too (its header says what it waits+ /// on), and the open detail follows the child once it starts.+ #[tokio::test]+ async fn agents_detail_of_a_pending_child_follows_its_promotion() {+ use crate::core::agent::events::PendingSubagent;+ let mut app = test_app();+ app.apply(StreamEvent::SubagentPlan {+ pending: vec![PendingSubagent {+ name: "collector".to_string(),+ phase: 2,+ }],+ });+ open_agents_picker(&mut app);+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.picker.as_ref().unwrap().kind, PickerKind::AgentDetail);+ assert_eq!(app.agent_detail.as_deref(), Some("collector"));+ let screen = render_rows(&mut app, 100, 30).join("\n");+ assert!(!screen.contains("no longer available"), "{screen}");+ assert!(screen.contains("collector"), "{screen}");++ app.apply(StreamEvent::SubagentStart {+ run_id: "sub-collector-1".to_string(),+ name: "collector".to_string(),+ task: None,+ workspace: None,+ internal: false,+ });+ assert_eq!(app.agent_detail.as_deref(), Some("sub-collector-1"));+ }++ /// Once promoted, the panel is addressed by its run id again: another live+ /// child answering to the same name (which name resolution would prefer,+ /// being newer) is left alone by both `x` and `m`.+ #[tokio::test]+ async fn agents_a_promoted_pending_child_is_addressed_by_run_id() {+ use crate::core::agent::events::PendingSubagent;+ use crate::core::agent::subagent::tests::{child_is_finished, register_live_child};+ let mut app = test_app();+ let mine = register_live_child(&app.subagent_set, "sub-collector-1", "collector");+ let other = register_live_child(&app.subagent_set, "sub-collector-9", "collector");+ app.apply(StreamEvent::SubagentPlan {+ pending: vec![PendingSubagent {+ name: "collector".to_string(),+ phase: 2,+ }],+ });+ open_agents_picker(&mut app);+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ app.apply(StreamEvent::SubagentQueued {+ run_id: "sub-collector-1".to_string(),+ name: "collector".to_string(),+ task: None,+ waiting: 1,+ });+ assert_eq!(+ app.agent_detail.as_deref(),+ Some("sub-collector-1"),+ "a detail opened while pending follows the promotion"+ );+ type_key_chars(&mut app, "hello").await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(mine.drain().1, vec!["hello".to_string()]);+ assert!(other.drain().1.is_empty());+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;++ app.apply(StreamEvent::SubagentStart {+ run_id: "sub-collector-1".to_string(),+ name: "collector".to_string(),+ task: None,+ workspace: None,+ internal: false,+ });+ render_rows(&mut app, 100, 30);+ assert_eq!(app.picker.as_ref().unwrap().items[0].value, "sub-collector-1");+ press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;+ assert!(child_is_finished(&app.subagent_set, "sub-collector-1"));+ assert!(!child_is_finished(&app.subagent_set, "sub-collector-9"));+ }+#[test]fn shells_commands_are_registered() {assert!(SLASH_COMMANDS.iter().any(|command| command.name == "/shells"));@@ -29059,6 +31405,8 @@ fn a() {}offers_always,justification: None,selected: 0,+ picked: false,+ pause: PromptPause::default(),subagent: None,}}@@ -34434,7 +36782,7 @@ fn a() {}/// the next dock added cannot quietly regress only the rendering half.#[test]fn every_blocking_dock_marks_the_input_row_inactive() {- let setups: [DockSetup; 10] = [+ let setups: [DockSetup; 9] = [// The account OAuth dock takes every keystroke and outranks the// API-key one, so it has to block the field as hard as the rest.("account_login", |app| {@@ -34472,9 +36820,6 @@ fn a() {}("mcp_prompt", |app| {app.mcp_prompt = Some(blank_mcp_prompt())}),- ("agent_message", |app| {- app.agent_message = Some(super::AgentMessagePrompt::new("sub-a-1", "a"))- }),("provider_prompt", |app| {app.provider_prompt = Some(super::ProviderPrompt::new())}),@@ -34625,15 +36970,15 @@ fn a() {}}#[test]- fn init_starts_a_turn_covering_all_three_artifacts() {+ fn init_starts_a_turn_writing_only_the_instructions_file() {let mut app = test_app();super::init_command(&mut app);assert!(app.want_start, "/init must start a turn");let sent = app.history.last().expect("user message").to_string();assert!(sent.contains("Write `AGENTS.md`"), "{sent}");assert!(!sent.contains("JAN.md"), "a new project never hears of JAN.md: {sent}");- assert!(sent.contains("skill_write"), "{sent}");- assert!(sent.contains("`memory` tool"), "{sent}");+ assert!(sent.contains("do not write skills, memory notes"), "{sent}");+ assert!(!sent.contains("skill_write"), "/init writes only the instructions file: {sent}");let _ = std::fs::remove_dir_all(&app.agent_dir);}@@ -35176,6 +37521,7 @@ fn a() {}project_memory: true,subagents_enabled: true,max_parallel_subagents: 4,+ subagent_worktrees: false,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,@@ -35186,6 +37532,7 @@ fn a() {}subagent_bg: Some(app.subagent_set.clone()),parent_link: None,shell_detach: None,+ shell_cwd: None,compaction: None,session_start: None,memory_change_budget: None,@@ -41421,6 +43768,18 @@ fn a() {});}+ /// `/resume` starts the loaded thread's shell in the project root, not+ /// wherever the replaced conversation last `cd`ed.+ #[tokio::test]+ async fn a_resumed_thread_starts_its_shell_in_the_project_root() {+ let mut app = test_app();+ *app.shell_cwd.lock().unwrap() = Some(std::path::PathBuf::from("/somewhere"));+ let history = vec![json!({ "role": "user", "content": "first" })];+ let id = super::super::cli_save_thread(&app.agent_dir, None, "m", &history, None).unwrap();+ super::load_thread(&mut app, &json!({ "id": id }), "resumed").await;+ assert_eq!(*app.shell_cwd.lock().unwrap(), None);+ }+/// `/new` keeps the checkout: it belongs to the invocation, not the thread.#[test]fn a_new_session_stays_in_the_same_worktree() {@@ -41439,7 +43798,7 @@ fn a() {}assert!(app.transcript.rows.is_empty(), "nothing is shown before git answers");assert!(std::mem::take(&mut app.worktree_request));let mut task = Some(spawn_worktree_report(app));- let report = await_worktree_report(&mut task).await.unwrap();+ let report = await_job(&mut task).await.unwrap();finish_worktree_report(app, report);}@@ -41463,7 +43822,7 @@ fn a() {}assert!(git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]));let mut app = test_app();let ledger = app.subagent_set.workspaces.clone();- let (ws, lease) = ledger.assign(root.path(), "general", true, None).unwrap();+ let (ws, lease) = ledger.assign(root.path(), "general", true, None, true).unwrap();drop(lease);let branch = ws.worktree.as_ref().unwrap().branch.clone();@@ -41508,8 +43867,8 @@ fn a() {}root: &std::path::Path,) -> (std::path::PathBuf, std::path::PathBuf, String) {let ledger = app.subagent_set.workspaces.clone();- let (idle, l1) = ledger.assign(root, "general", true, None).unwrap();- let (work, l2) = ledger.assign(root, "general-2", true, None).unwrap();+ let (idle, l1) = ledger.assign(root, "general", true, None, true).unwrap();+ let (work, l2) = ledger.assign(root, "general-2", true, None, true).unwrap();drop((l1, l2));let ok = std::process::Command::new("git").arg("-C")@@ -41519,6 +43878,9 @@ fn a() {}.status().is_ok_and(|s| s.success());assert!(ok);+ // Work only the checkout holds, so it is kept: a clean one whose+ // branch is brought back goes.+ std::fs::write(work.root.join("notes.md"), "draft\n").unwrap();let branch = work.worktree.as_ref().unwrap().branch.clone();(idle.root, work.root, branch)}@@ -41548,7 +43910,7 @@ fn a() {}let err = app.subagent_set.workspaces- .assign(root.path(), "next", true, Some(&reuse))+ .assign(root.path(), "next", true, Some(&reuse), true).unwrap_err();assert!(err.contains("no earlier subagent"), "{err}");// Shown as the kept notice, one worktree per row.@@ -41585,7 +43947,7 @@ fn a() {}assert!(idle.is_dir() && kept.is_dir());let reuse = crate::core::agent::child_workspace::WorkspaceRequest::Reuse("general".into());let ledger = app.subagent_set.workspaces.clone();- assert!(ledger.assign(root.path(), "next", true, Some(&reuse)).is_ok());+ assert!(ledger.assign(root.path(), "next", true, Some(&reuse), true).is_ok());let _ = tokio::task::spawn_blocking(move || ledger.finish_session()).await;let _ = std::fs::remove_dir_all(&kept);}@@ -41641,6 +44003,222 @@ fn a() {}let _ = std::fs::remove_dir_all(&kept);}+ /// A `/worktrees` listing with one checkout in each state.+ fn worktrees_fixture() -> crate::core::agent::child_workspace::WorktreesReport {+ use crate::core::agent::child_workspace::{+ CheckoutInfo, CheckoutState, InUseBy, WorktreesReport,+ };+ let checkout = |id: &str, state| CheckoutInfo {+ id: id.to_string(),+ path: std::path::PathBuf::from(format!("/w/{id}")),+ branch: format!("jan/agent/{id}"),+ bytes: 2048,+ build_output_bytes: 0,+ state,+ };+ WorktreesReport {+ dir: Some(std::path::PathBuf::from("/w")),+ checkouts: vec![+ checkout("child-0001", CheckoutState::InUse { by: InUseBy::Child }),+ checkout("other-0002", CheckoutState::InUse { by: InUseBy::Session }),+ checkout(+ "dirty-0003",+ CheckoutState::Uncommitted {+ files: vec!["a.txt".into(), ".env".into()],+ commits: 1,+ off_branch: 0,+ build_output: vec![],+ },+ ),+ checkout("ahead-0004", CheckoutState::Unbrought { commits: 3 }),+ checkout("idle-0005", CheckoutState::Removable { commits: 0 }),+ ],+ build_cache_bytes: Some(3 << 30),+ trash_bytes: 0,+ }+ }++ #[test]+ fn worktrees_command_is_registered() {+ assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/worktrees"));+ }++ /// The actions come first, sized; then a row per checkout naming its+ /// branch, size and state.+ #[test]+ fn worktrees_picker_lists_actions_then_each_checkouts_state() {+ let items = worktrees_picker_items(&worktrees_fixture());+ let labels: Vec<(&str, &str)> =+ items.iter().map(|i| (i.value.as_str(), i.label.as_str())).collect();+ assert_eq!(+ labels,+ [+ ("safe", "Remove what is safe to remove 1 checkout(s), 2.0 KB"),+ ("cache", "Clear build cache 3.0 GB"),+ ("wt:child-0001", "jan/agent/child-0001 2.0 KB in use by a running subagent"),+ ("wt:other-0002", "jan/agent/other-0002 2.0 KB in use by another live jan session"),+ (+ "wt:dirty-0003",+ "jan/agent/dirty-0003 2.0 KB holds uncommitted work: a.txt, .env; 1 commit(s)"+ ),+ ("wt:ahead-0004", "jan/agent/ahead-0004 2.0 KB holds 3 commit(s) not in your repository"),+ ("wt:idle-0005", "jan/agent/idle-0005 2.0 KB removable (no work in it)"),+ ]+ );+ }++ /// Open `/worktrees` on the fixture with `row` selected, and press Enter.+ async fn enter_on_worktrees_row(app: &mut App, row: &str) {+ app.worktrees = Some(worktrees_fixture());+ open_worktrees_picker(app);+ let picker = app.picker.as_mut().unwrap();+ picker.selected = picker.items.iter().position(|i| i.value == row).unwrap();+ press(app, KeyCode::Enter, KeyModifiers::NONE).await;+ }++ #[tokio::test]+ async fn worktrees_actions_run_off_the_render_loop() {+ use crate::core::agent::child_workspace::Prune;+ for (row, job) in [+ ("safe", WorktreesJob::Prune(Prune::Safe)),+ ("cache", WorktreesJob::ClearCache),+ ("wt:idle-0005", WorktreesJob::Prune(Prune::One { id: "idle-0005".into(), force: false })),+ ] {+ let mut app = test_app();+ enter_on_worktrees_row(&mut app, row).await;+ assert_eq!(app.worktrees_request, Some(job), "{row}");+ assert!(app.picker.is_none(), "{row}");+ }+ }++ /// A checkout in use is never removed from here: Enter says why and asks+ /// for nothing.+ #[tokio::test]+ async fn a_checkout_in_use_cannot_be_removed_from_worktrees() {+ for row in ["wt:child-0001", "wt:other-0002"] {+ let mut app = test_app();+ enter_on_worktrees_row(&mut app, row).await;+ assert_eq!(app.worktrees_request, None, "{row}");+ let notes: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(notes.contains("is kept: in use by"), "{notes}");+ }+ }++ /// Removing a checkout that holds work asks first, naming the loss, with+ /// "keep" selected; only the remove row removes it, and Esc steps back.+ #[tokio::test]+ async fn removing_a_checkout_with_work_asks_first_and_names_the_loss() {+ use crate::core::agent::child_workspace::Prune;+ let mut app = test_app();+ enter_on_worktrees_row(&mut app, "wt:dirty-0003").await;+ let picker = app.picker.as_ref().unwrap();+ assert_eq!(picker.kind, PickerKind::WorktreeConfirm);+ let text: Vec<&str> = picker.items.iter().map(|i| i.label.as_str()).collect();+ // Its branch is brought back first: only the files are lost.+ assert!(text[1].ends_with("deletes 2 uncommitted file(s), for good"), "{text:?}");+ assert!(text[2].contains("its branch (1 commit(s)) is brought back"), "{text:?}");+ assert_eq!(picker.items[picker.selected].value, "keep");+ assert_eq!(app.worktrees_request, None);+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::Worktrees));+ assert_eq!(app.worktrees_request, None, "keep removes nothing");++ enter_on_worktrees_row(&mut app, "wt:ahead-0004").await;+ let text: Vec<String> =+ app.picker.as_ref().unwrap().items.iter().map(|i| i.label.clone()).collect();+ assert!(text[1].contains("deletes 3 commit(s) not in your repository"), "{text:?}");+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::Worktrees));++ enter_on_worktrees_row(&mut app, "wt:ahead-0004").await;+ press(&mut app, KeyCode::Down, KeyModifiers::NONE).await;+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;+ let force = Prune::One { id: "ahead-0004".into(), force: true };+ assert_eq!(app.worktrees_request, Some(WorktreesJob::Prune(force)));+ assert!(app.picker.is_none());+ }++ /// `/worktrees` the way the loop runs it, on a real project: the listing+ /// lands as the picker, and the safe prune reports what it freed while+ /// this session's busy checkout stays.+ #[tokio::test]+ async fn worktrees_lists_and_prunes_a_real_project() {+ let Some(root) = conversation_repo() else { return };+ let mut app = test_app();+ app.project_root = root.path().to_path_buf();+ let ledger = app.subagent_set.workspaces.clone();+ let (busy, lease) = ledger.assign(root.path(), "busy", true, None, true).unwrap();+ let (idle, l2) = ledger.assign(root.path(), "idle", true, None, true).unwrap();+ drop(l2);+ let run = |app: &mut App| {+ let job = app.worktrees_request.take().expect("a job was asked for");+ Some(spawn_worktrees_job(app, job))+ };+ worktrees_command(&mut app);+ let mut task = run(&mut app);+ finish_worktrees_job(&mut app, await_job(&mut task).await.unwrap());+ let picker = app.picker.as_ref().expect("the listing opens the picker");+ let labels: String = picker.items.iter().map(|i| format!("{}\n", i.label)).collect();+ assert!(labels.contains("in use by a running subagent"), "{labels}");+ assert!(labels.contains("removable (no work in it)"), "{labels}");++ worktrees_action(&mut app, "safe");+ let mut task = run(&mut app);+ finish_worktrees_job(&mut app, await_job(&mut task).await.unwrap());+ let notes: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(notes.contains("removed 1 subagent worktree(s); moved "), "{notes}");+ assert!(busy.root.is_dir() && !idle.root.exists());+ assert!(app.worktrees.is_none(), "the listing it acted on is dropped");+ drop(lease);+ let _ = tokio::task::spawn_blocking(move || ledger.finish_session()).await;+ }++ /// A listing that lands while the user is typing, or has something else+ /// open, is kept and announced, never opened under their next Enter (its+ /// first row prunes).+ #[tokio::test]+ async fn a_listing_landing_over_a_draft_or_another_view_does_not_open() {+ let mut app = test_app();+ app.input = "half a message".to_string();+ finish_worktrees_job(&mut app, WorktreesDone::Listed(worktrees_fixture()));+ assert!(app.picker.is_none());+ assert!(app.worktrees.is_some(), "kept, so /worktrees shows it at once");+ let notes: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(notes.contains("worktree listing ready"), "{notes}");++ let mut app = test_app();+ app.picker = Some(super::Picker {+ kind: PickerKind::Agents,+ items: vec![],+ selected: 0,+ search: None,+ armed_delete: None,+ });+ finish_worktrees_job(&mut app, WorktreesDone::Listed(worktrees_fixture()));+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::Agents));++ let mut app = test_app();+ finish_worktrees_job(&mut app, WorktreesDone::Listed(worktrees_fixture()));+ assert_eq!(app.picker.as_ref().map(|p| p.kind), Some(PickerKind::Worktrees));+ }++ /// Once a prune or a clear lands, the listing it acted on is stale: it is+ /// dropped, so stepping back to the list lists again rather than showing+ /// checkouts that are gone.+ #[tokio::test]+ async fn a_finished_prune_drops_the_stale_listing() {+ use crate::core::agent::child_workspace::Pruned;+ for done in [WorktreesDone::Pruned(Pruned::default()), WorktreesDone::Cleared(Ok(1))] {+ let mut app = test_app();+ app.worktrees = Some(worktrees_fixture());+ finish_worktrees_job(&mut app, done);+ assert!(app.worktrees.is_none());+ open_worktrees_picker(&mut app);+ assert!(app.picker.is_none());+ assert_eq!(app.worktrees_request, Some(WorktreesJob::List));+ }+ }+#[tokio::test]async fn worktree_command_without_one_points_at_the_flag() {let mut app = test_app();@@ -48786,7 +51364,7 @@ fn a() {}/// Past `BACKGROUND_GROUP_ROWS` the last row counts the rest, without/// repeating the `/agents` the head already names, and a later phase reads- /// as waiting, not running.+ /// as queued, not running.#[test]fn a_wide_fan_out_overflows_to_agents() {let mut app = test_app();@@ -48800,7 +51378,7 @@ fn a() {}});let rows = subagent_text(&mut app, 100, Instant::now());assert_eq!(rows.len(), 1 + super::BACKGROUND_GROUP_ROWS, "{rows:#?}");- assert!(rows[0].contains("4 subagents running \u{b7} 1 waiting"), "{rows:#?}");+ assert!(rows[0].contains("4 subagents running \u{b7} 1 queued"), "{rows:#?}");assert_eq!(rows[3], " +3 more", "{rows:#?}");assert_eq!(rows.join("\n").matches("/agents").count(), 1, "{rows:#?}");}@@ -48819,6 +51397,7 @@ fn a() {}.iter().map(|f| vec![ratatui::text::Span::raw(f.to_string())]).collect(),+ cut_last: false,}],}}@@ -49990,14 +52569,15 @@ fn a() {}app.cursor = app.input.len();app.slash_dismissed = true;assert!(app.slash_matches().is_empty());- // Editing the buffer re-shows the popup; fuzzy matching offers both- // commands whose name contains `res` as a subsequence, resume first.+ // Editing the buffer re-shows the popup; fuzzy matching offers every+ // command whose name contains `res` as a subsequence, resume first.app.input_insert('s');assert_eq!(names(&app),vec!["/resume".to_string(),"/reasoning".to_string(),+ "/worktrees".to_string(),"/threads".to_string(),]);@@ -50229,13 +52809,14 @@ fn a() {}app.input = "/res".into();let all = names(&app);// Built-in wins the `/resume` collision: no `/command:x:resume` row and- // no skill row. `/reasoning` and `/threads` are separate fuzzy hits- // (res is a subsequence of both names), not collisions.+ // no skill row. `/reasoning`, `/worktrees` and `/threads` are separate+ // fuzzy hits (res is a subsequence of each name), not collisions.assert_eq!(all,vec!["/resume".to_string(),"/reasoning".to_string(),+ "/worktrees".to_string(),"/threads".to_string(),],"built-in only"@@ -52176,6 +54757,40 @@ fn a() {}});}+ /// A new conversation starts its shell back in the project root, as its+ /// prompt says, whatever the last one `cd`ed into.+ #[test]+ fn reset_session_returns_the_shell_to_the_project_root() {+ let mut app = test_app();+ *app.shell_cwd.lock().unwrap() = Some(std::path::PathBuf::from("/somewhere"));+ app.reset_session();+ assert_eq!(*app.shell_cwd.lock().unwrap(), None);+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }++ /// Instructions past the budget warn, summed over every loaded file and+ /// naming each; at or under it nothing is said.+ #[test]+ fn instructions_size_warning_fires_only_past_the_budget() {+ let file = |path: &str, chars: usize| crate::core::agent::context::ContextFile {+ path: path.into(),+ content: "x".repeat(chars),+ fallback: true,+ };+ let limit = super::INSTRUCTIONS_WARN_CHARS;+ assert_eq!(super::instructions_size_warning(&[]), None);+ assert_eq!(super::instructions_size_warning(&[file("/r/AGENTS.md", limit)]), None);+ let warning = super::instructions_size_warning(&[+ file("/r/AGENTS.md", limit / 2 + 1),+ file("/r/pkg/AGENTS.md", limit / 2),+ ])+ .expect("the total is past the budget");+ assert!(warning.contains("/r/AGENTS.md"), "{warning}");+ assert!(warning.contains("/r/pkg/AGENTS.md"), "{warning}");+ assert!(warning.contains("/init"), "{warning}");+ assert!(warning.contains(&format!("{} characters", limit + 1)), "{warning}");+ }+/// `/context` lists the files the project context holds, labelling a legacy/// JAN.md and a CLAUDE.md fallback.#[test]diff --git a/src-tauri/src/core/cli/tui/tests/snapshot.rs b/src-tauri/src/core/cli/tui/tests/snapshot.rsindex 99f3d4a97..a57d27f77 100644--- a/src-tauri/src/core/cli/tui/tests/snapshot.rs+++ b/src-tauri/src/core/cli/tui/tests/snapshot.rs@@ -509,6 +509,16 @@ fn monitors_inspector_empty() {assert_buffer("monitors_inspector_empty", &frame(&mut app, DARK, 60, 9));}+/// `/worktrees`: the actions, then each checkout coloured by what may be+/// done with it (removable green, holding work amber, in use dim).+#[test]+fn worktrees_inspector_lists_each_state() {+ let mut app = snapshot_app();+ app.worktrees = Some(worktrees_fixture());+ open_worktrees_picker(&mut app);+ assert_buffer("worktrees_inspector_list", &frame(&mut app, DARK, 100, 15));+}+#[test]fn monitor_group_overflow_counts_the_rest() {let mut app = snapshot_app();@@ -614,6 +624,71 @@ fn subagents_running_after_the_turn() {assert_buffer("subagents_idle_one_finished", &background_rows_buffer(&mut app, 80, now));}+/// A child that issues several calls in one request, as its stream delivers+/// them: every call announced before any runs, then the results out of order.+/// The row names the newest call still running, in continuous tense, and a+/// label too long for the row is cut after its verb rather than dropped; each+/// result retires its own call by id, so the row follows whatever is still+/// running and flips to the past tense only once the last one answers.+#[test]+fn subagent_parallel_calls_stay_visible_until_the_last_result() {+ let now = Instant::now();+ let mut app = idle_fan_out(now);+ app.subagents.truncate(1);+ let child = |event: StreamEvent| StreamEvent::Subagent {+ run_id: "sub-kv-review-1".into(),+ name: "kv-review".into(),+ event: Box::new(event),+ };+ let cmd = "cargo test --locked --no-default-features --features cli --lib tui";+ let calls = [+ ("a", "read", json!({ "path": "src/a.rs" })),+ ("b", "read", json!({ "path": "src/b.rs" })),+ ("c", "bash", json!({ "command": cmd })),+ ];+ for (id, tool, args) in calls {+ app.apply(child(StreamEvent::ToolCall {+ id: id.into(),+ name: tool.into(),+ args,+ }));+ }+ let row = |app: &mut App, w: u16| {+ let text = render_snapshot(&background_rows_buffer(app, w, now));+ text.lines().nth(1).unwrap_or_default().to_string()+ };+ // The newest call's whole command does not fit, so the row keeps its verb+ // and cuts the rest with a visible mark rather than going blank.+ for w in [80, 50, 36] {+ let shown = row(&mut app, w);+ assert!(shown.contains("1m 05s \u{b7} Running"), "@{w}: {shown}");+ assert!(shown.trim_end_matches([' ', '|']).ends_with("..."), "@{w}: {shown}");+ assert!(!shown.contains("in flight"), "@{w}: {shown}");+ }+ assert!(row(&mut app, 120).contains(&format!("1m 05s \u{b7} Running {cmd}")));+ assert_buffer("subagents_idle_parallel", &background_rows_buffer(&mut app, 80, now));+ let result = |id: &str| {+ child(StreamEvent::ToolResult {+ id: id.into(),+ content: "ok".into(),+ is_error: false,+ diff: None,+ })+ };+ app.apply(result("c"));+ let shown = row(&mut app, 80);+ assert!(shown.contains("1m 05s \u{b7} Reading b.rs "), "{shown}");+ app.apply(result("b"));+ let shown = row(&mut app, 80);+ assert!(shown.contains("1m 05s \u{b7} Reading a.rs "), "{shown}");+ // The batch is done: the call the row last named stays, its verb now in+ // the past tense.+ app.apply(result("a"));+ assert!(app.subagents[0].in_flight.is_empty());+ let shown = row(&mut app, 120);+ assert!(shown.contains("1m 05s \u{b7} Read a.rs "), "{shown}");+}+/// Where the block sits: over the rule, subagents over shells, the rule on/// the input.#[test]@@ -866,6 +941,90 @@ fn agents_inspector_detail_for_a_richer_child() {);}+/// The detail's input is the composer, aimed at the child: a parked child+/// offers the placeholder addressed to it, and a draft shows with the main+/// composer's prompt and cursor under the panel.+#[test]+fn agents_inspector_detail_takes_a_message() {+ let mut app = snapshot_app();+ start_turn(&mut app, "fan out");+ start_kv_review(&mut app);+ child(&mut app, StreamEvent::Step { index: 1, max: 0 });+ child(+ &mut app,+ StreamEvent::Token {+ text: "Waiting on the test run.".into(),+ },+ );+ child(&mut app, StreamEvent::Parked);+ open_kv_review_detail(&mut app);+ assert_buffer("agents_inspector_detail_idle_input", &frame(&mut app, DARK, 80, 16));+ app.input = "check the lock order too".into();+ app.cursor = app.input.len();+ assert_buffer("agents_inspector_detail_draft", &frame(&mut app, DARK, 80, 16));+}++/// A permission request from the child lands while its detail is open: it is+/// drawn over the detail, and the footer says only a picked option answers.+#[test]+fn agents_inspector_detail_under_a_permission_prompt() {+ let mut app = snapshot_app();+ start_turn(&mut app, "fan out");+ start_kv_review(&mut app);+ child(&mut app, StreamEvent::Step { index: 1, max: 0 });+ child(+ &mut app,+ StreamEvent::Token {+ text: "Running the tests.".into(),+ },+ );+ open_kv_review_detail(&mut app);+ app.input = "also".into();+ app.cursor = app.input.len();+ child(+ &mut app,+ StreamEvent::PermissionRequest {+ request_id: "p1".into(),+ tool_name: "bash".into(),+ capability: "execute".into(),+ path: None,+ command: Some("cargo test --lib".into()),+ diff: None,+ prompt_kind: "exec".into(),+ offers_always: true,+ justification: None,+ },+ );+ assert_buffer(+ "agents_inspector_detail_permission",+ &frame(&mut app, DARK, 80, 20),+ );+}++/// The same for an `ask`: drawn over the detail, its help line naming the+/// detail's keys.+#[test]+fn agents_inspector_detail_under_an_ask() {+ let mut app = snapshot_app();+ start_turn(&mut app, "fan out");+ start_kv_review(&mut app);+ open_kv_review_detail(&mut app);+ let request = crate::core::agent::interaction::AskRequest::parse(&json!({+ "questions": [{+ "id": "scope",+ "question": "Which scope?",+ "options": [{"label": "Small"}, {"label": "Large"}]+ }]+ }))+ .unwrap();+ app.apply(StreamEvent::AskRequest {+ request_id: "a1".into(),+ request,+ timeout_secs: None,+ });+ assert_buffer("agents_inspector_detail_ask", &frame(&mut app, DARK, 80, 20));+}+// ---- Model picker -----------------------------------------------------------fn picker_app() -> TestApp {diff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail.snapindex b4fb2758e..db9f72596 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail.snap@@ -23,9 +23,9 @@ expression: render_snapshot(buf)|╰──────────────────────────────────────────────────────────────────────────────╯|| ||────────────────────────────────────────────────────────────────────────────────|-|selecting… |+|› working… (type to message kv-review, Ctrl-X to stop) || |-|📂 /snapshot/repo PgUp/PgDn scroll m message x stop Esc back|+|📂 /snapshot/repo PgUp/PgDn scroll Enter send ^X stop Esc back/^C close|0 0..2 fg=Yellow0 3..14 mod=BOLD@@ -86,7 +86,10 @@ expression: render_snapshot(buf)17 6..26 mod=DIM17 79..80 fg=#56B6C218 0..80 fg=#56B6C2-21 0..10 mod=DIM | ITALIC+21 0..2 fg=#56B6C2 mod=BOLD+21 2..3 mod=REVERSED+21 4..12 mod=DIM | ITALIC+21 18..62 mod=DIM | ITALIC23 0..1 fg=#80808023 2..17 fg=#808080-23 31..80 mod=DIM+23 20..80 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_ask.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_ask.snapnew file mode 100644index 000000000..fc44e6c6e--- /dev/null+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_ask.snap@@ -0,0 +1,79 @@+---+source: src/core/cli/tui/tests/snapshot.rs+expression: render_snapshot(buf)+---+| 👋 gpt-5-mini effort medium ctx 0K/128K fallback ◉ [working] |+|╭ subagent ────────────────────────────────────────────────────────────────────╮|+|│ kv-review (sub-kv-review-1) │|+|│ 0 tools · 0 req · 75% cache hit Running │|+|│ │|+|│ Review the key-value store for races. │|+|│ │|+|│ (no activity yet) │|+|│ │|+|│ │|+|╭ question 1/1 ────────────────────────────────────────────────────────────────╮|+|│ Which scope? │|+|│ ○ Small │|+|│ ○ Large │|+|│ ○ Other (type your own) │|+|│ ↑↓ pick · Esc back │|+|╰──────────────────────────────────────────────────────────────────────────────╯|+|answer the prompt above, or Esc to go back |+| |+|📂 /snapshot/repo ↑/↓ pick Esc back|++ 0 0..2 fg=Yellow+ 0 3..14 mod=BOLD+ 0 14..29 fg=#E5C07B+ 0 55..57 fg=#56B6C2+ 0 57..66 fg=#56B6C2 mod=BOLD+ 1 0..80 fg=#56B6C2+ 2 0..1 fg=#56B6C2+ 2 2..11 fg=#56B6C2 mod=BOLD+ 2 11..30 fg=#808080+ 2 79..80 fg=#56B6C2+ 3 0..1 fg=#56B6C2+ 3 2..33 fg=#808080+ 3 35..42 fg=#56B6C2 mod=BOLD+ 3 79..80 fg=#56B6C2+ 4 0..1 fg=#56B6C2+ 4 79..80 fg=#56B6C2+ 5 0..1 fg=#56B6C2+ 5 2..39 mod=DIM | ITALIC+ 5 79..80 fg=#56B6C2+ 6 0..1 fg=#56B6C2+ 6 79..80 fg=#56B6C2+ 7 0..1 fg=#56B6C2+ 7 2..19 fg=#808080+ 7 79..80 fg=#56B6C2+ 8 0..1 fg=#56B6C2+ 8 79..80 fg=#56B6C2+ 9 0..1 fg=#56B6C2+ 9 79..80 fg=#56B6C2+10 0..1 fg=#56B6C2+10 1..15 fg=Black bg=#56B6C2 mod=BOLD+10 15..80 fg=#56B6C2+11 0..1 fg=#56B6C2+11 2..14 mod=BOLD+11 79..80 fg=#56B6C2+12 0..1 fg=#56B6C2+12 4..6 fg=Cyan+12 79..80 fg=#56B6C2+13 0..1 fg=#56B6C2+13 4..6 fg=Cyan+13 79..80 fg=#56B6C2+14 0..1 fg=#56B6C2+14 4..6 fg=Cyan+14 79..80 fg=#56B6C2+15 0..1 fg=#56B6C2+15 2..20 fg=#808080+15 79..80 fg=#56B6C2+16 0..80 fg=#56B6C2+17 0..42 mod=DIM | ITALIC+19 0..1 fg=#808080+19 2..17 fg=#808080+19 61..64 fg=#E5C07B mod=BOLD+19 64..69 mod=DIM+19 72..75 fg=#E5C07B mod=BOLD+19 75..80 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_draft.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_draft.snapnew file mode 100644index 000000000..042318e18--- /dev/null+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_draft.snap@@ -0,0 +1,55 @@+---+source: src/core/cli/tui/tests/snapshot.rs+expression: render_snapshot(buf)+---+| 👋 gpt-5-mini effort medium ctx 0K/128K fallback ◉ [working] |+|╭ subagent ────────────────────────────────────────────────────────────────────╮|+|│ kv-review (sub-kv-review-1) │|+|│ 0 tools · 1 req · 75% cache hit Waiting on background work │|+|│ │|+|│ Review the key-value store for races. │|+|│ │|+|│ │|+|│ │|+|│ • Waiting on the test run. │|+|╰──────────────────────────────────────────────────────────────────────────────╯|+| |+|────────────────────────────────────────────────────────────────────────────────|+|› check the lock order too |+| |+|📂 /snapshot/repo PgUp/PgDn scroll Enter send ^X stop Esc back/^C close|++ 0 0..2 fg=Yellow+ 0 3..14 mod=BOLD+ 0 14..29 fg=#E5C07B+ 0 55..57 fg=#56B6C2+ 0 57..66 fg=#56B6C2 mod=BOLD+ 1 0..80 fg=#56B6C2+ 2 0..1 fg=#56B6C2+ 2 2..11 fg=#56B6C2 mod=BOLD+ 2 11..30 fg=#808080+ 2 79..80 fg=#56B6C2+ 3 0..1 fg=#56B6C2+ 3 2..33 fg=#808080+ 3 35..61 fg=#808080+ 3 79..80 fg=#56B6C2+ 4 0..1 fg=#56B6C2+ 4 79..80 fg=#56B6C2+ 5 0..1 fg=#56B6C2+ 5 2..39 mod=DIM | ITALIC+ 5 79..80 fg=#56B6C2+ 6 0..1 fg=#56B6C2+ 6 79..80 fg=#56B6C2+ 7 0..1 fg=#56B6C2+ 7 79..80 fg=#56B6C2+ 8 0..1 fg=#56B6C2+ 8 79..80 fg=#56B6C2+ 9 0..1 fg=#56B6C2+ 9 2..4 mod=DIM+ 9 79..80 fg=#56B6C2+10 0..80 fg=#56B6C2+13 0..2 fg=#56B6C2 mod=BOLD+13 26..27 mod=REVERSED+15 0..1 fg=#808080+15 2..17 fg=#808080+15 20..80 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_idle_input.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_idle_input.snapnew file mode 100644index 000000000..e47eb9cef--- /dev/null+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_idle_input.snap@@ -0,0 +1,56 @@+---+source: src/core/cli/tui/tests/snapshot.rs+expression: render_snapshot(buf)+---+| 👋 gpt-5-mini effort medium ctx 0K/128K fallback ◉ [working] |+|╭ subagent ────────────────────────────────────────────────────────────────────╮|+|│ kv-review (sub-kv-review-1) │|+|│ 0 tools · 1 req · 75% cache hit Waiting on background work │|+|│ │|+|│ Review the key-value store for races. │|+|│ │|+|│ │|+|│ │|+|│ • Waiting on the test run. │|+|╰──────────────────────────────────────────────────────────────────────────────╯|+| |+|────────────────────────────────────────────────────────────────────────────────|+|› Message kv-review… |+| |+|📂 /snapshot/repo PgUp/PgDn scroll Enter send ^X stop Esc back/^C close|++ 0 0..2 fg=Yellow+ 0 3..14 mod=BOLD+ 0 14..29 fg=#E5C07B+ 0 55..57 fg=#56B6C2+ 0 57..66 fg=#56B6C2 mod=BOLD+ 1 0..80 fg=#56B6C2+ 2 0..1 fg=#56B6C2+ 2 2..11 fg=#56B6C2 mod=BOLD+ 2 11..30 fg=#808080+ 2 79..80 fg=#56B6C2+ 3 0..1 fg=#56B6C2+ 3 2..33 fg=#808080+ 3 35..61 fg=#808080+ 3 79..80 fg=#56B6C2+ 4 0..1 fg=#56B6C2+ 4 79..80 fg=#56B6C2+ 5 0..1 fg=#56B6C2+ 5 2..39 mod=DIM | ITALIC+ 5 79..80 fg=#56B6C2+ 6 0..1 fg=#56B6C2+ 6 79..80 fg=#56B6C2+ 7 0..1 fg=#56B6C2+ 7 79..80 fg=#56B6C2+ 8 0..1 fg=#56B6C2+ 8 79..80 fg=#56B6C2+ 9 0..1 fg=#56B6C2+ 9 2..4 mod=DIM+ 9 79..80 fg=#56B6C2+10 0..80 fg=#56B6C2+13 0..2 fg=#56B6C2 mod=BOLD+13 2..3 mod=REVERSED+13 4..22 mod=DIM | ITALIC+15 0..1 fg=#808080+15 2..17 fg=#808080+15 20..80 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_permission.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_permission.snapnew file mode 100644index 000000000..4db048318--- /dev/null+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_permission.snap@@ -0,0 +1,80 @@+---+source: src/core/cli/tui/tests/snapshot.rs+expression: render_snapshot(buf)+---+| 👋 gpt-5-mini effort medium ctx 0K/128K fallback ◉ [working] |+|╭ subagent ────────────────────────────────────────────────────────────────────╮|+|│ kv-review (sub-kv-review-1) │|+|│ 0 tools · 1 req · 75% cache hit Running │|+|│ │|+|│ Review the key-value store for races. │|+|│ │|+|│ │|+|╭ permission required ─────────────────────────────────────────────────────────╮|+|│ subagent kv-review is asking: │|+|│ bash wants execute │|+|│ $ cargo test --lib │|+|│ Allow once │|+|│ Allow all 'cargo' commands (this thread) │|+|│ Deny │|+|╰──────────────────────────────────────────────────────────────────────────────╯|+|› also |+|answer the prompt above, then Enter sends this |+| |+|📂 /snapshot/repo ↑/↓ pick Esc back|++ 0 0..2 fg=Yellow+ 0 3..14 mod=BOLD+ 0 14..29 fg=#E5C07B+ 0 55..57 fg=#56B6C2+ 0 57..66 fg=#56B6C2 mod=BOLD+ 1 0..80 fg=#56B6C2+ 2 0..1 fg=#56B6C2+ 2 2..11 fg=#56B6C2 mod=BOLD+ 2 11..30 fg=#808080+ 2 79..80 fg=#56B6C2+ 3 0..1 fg=#56B6C2+ 3 2..33 fg=#808080+ 3 35..42 fg=#56B6C2 mod=BOLD+ 3 79..80 fg=#56B6C2+ 4 0..1 fg=#56B6C2+ 4 79..80 fg=#56B6C2+ 5 0..1 fg=#56B6C2+ 5 2..39 mod=DIM | ITALIC+ 5 79..80 fg=#56B6C2+ 6 0..1 fg=#56B6C2+ 6 79..80 fg=#56B6C2+ 7 0..1 fg=#56B6C2+ 7 79..80 fg=#56B6C2+ 8 0..1 fg=#E5C07B+ 8 1..22 fg=Black bg=#E5C07B mod=BOLD+ 8 22..80 fg=#E5C07B+ 9 0..1 fg=#E5C07B+ 9 2..11 fg=DarkGray+ 9 11..20 fg=#56B6C2 mod=BOLD+ 9 20..31 fg=DarkGray+ 9 79..80 fg=#E5C07B+10 0..1 fg=#E5C07B+10 2..6 fg=Cyan mod=BOLD+10 6..13 fg=DarkGray+10 13..20 fg=Yellow mod=BOLD+10 79..80 fg=#E5C07B+11 0..1 fg=#E5C07B+11 2..4 fg=DarkGray+11 79..80 fg=#E5C07B+12 0..1 fg=#E5C07B+12 79..80 fg=#E5C07B+13 0..1 fg=#E5C07B+13 79..80 fg=#E5C07B+14 0..1 fg=#E5C07B+14 79..80 fg=#E5C07B+15 0..80 fg=#E5C07B+16 0..2 fg=#56B6C2 mod=BOLD+16 6..7 mod=REVERSED+17 0..46 mod=DIM | ITALIC+19 0..1 fg=#808080+19 2..17 fg=#808080+19 61..64 fg=#E5C07B mod=BOLD+19 64..69 mod=DIM+19 72..75 fg=#E5C07B mod=BOLD+19 75..80 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_rich.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_rich.snapindex decb74e0c..1db7261e2 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_rich.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_detail_rich.snap@@ -29,9 +29,9 @@ expression: render_snapshot(buf)|╰──────────────────────────────────────────────────────────────────────────────╯|| ||────────────────────────────────────────────────────────────────────────────────|-|selecting… |+|› working… (type to message kv-review, Ctrl-X to stop) || |-|📂 /snapshot/repo PgUp/PgDn scroll m message x stop Esc back|+|📂 /snapshot/repo PgUp/PgDn scroll Enter send ^X stop Esc back/^C close|0 0..2 fg=Yellow0 3..14 mod=BOLD@@ -126,7 +126,10 @@ expression: render_snapshot(buf)23 37..77 bg=#16342023 79..80 fg=#56B6C224 0..80 fg=#56B6C2-27 0..10 mod=DIM | ITALIC+27 0..2 fg=#56B6C2 mod=BOLD+27 2..3 mod=REVERSED+27 4..12 mod=DIM | ITALIC+27 18..62 mod=DIM | ITALIC29 0..1 fg=#80808029 2..17 fg=#808080-29 31..80 mod=DIM+29 20..80 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_list.snap b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_list.snapindex 80db76dc4..f5753d3ae 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_list.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/agents_inspector_list.snap@@ -8,7 +8,7 @@ expression: render_snapshot(buf)|│ • perf-scan 3 tools · 3 req · 16% ctx · 0% cache hit Running · Read mod_2.rs │||│ • lint-fix 1 tool · 1 req · 4% ctx Running · Read mod_0.rs │||│ • docs-writer Queued (1) │|-|│ • collector Waiting (phase 2) │|+|│ • collector Queued · phase 2 │||│ │||│ │||│ │|@@ -17,7 +17,7 @@ expression: render_snapshot(buf)|──────────────────────────────────────────────────────────────────────────────────────────||selecting… || |-|📂 /snapshot/repo ↑/↓ select Enter view m message x stop Esc close|+|📂 /snapshot/repo ↑/↓ select Enter view x stop Esc close|0 0..2 fg=Yellow0 3..14 mod=BOLD@@ -51,7 +51,7 @@ expression: render_snapshot(buf)6 0..1 fg=#56B6C26 4..6 fg=#8080806 6..15 fg=#56B6C2 mod=BOLD- 6 17..34 fg=#808080+ 6 17..33 fg=#8080806 89..90 fg=#56B6C27 0..1 fg=#56B6C27 89..90 fg=#56B6C2@@ -63,4 +63,4 @@ expression: render_snapshot(buf)13 0..10 mod=DIM | ITALIC15 0..1 fg=#80808015 2..17 fg=#808080-15 33..90 mod=DIM+15 45..90 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/background_work_very_narrow.snap b/src-tauri/src/core/cli/tui/tests/snapshots/background_work_very_narrow.snapindex af526f128..5b9c4478e 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/background_work_very_narrow.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/background_work_very_narrow.snap@@ -13,7 +13,7 @@ expression: render_snapshot(buf)| 1 monitor watching || └ mon-3 CI done #9487 || 2 subagents running |-| └ kv-review |+| └ kv-review · Read... || perf-scan || docs-writer || 2 background shells ...|@@ -38,6 +38,7 @@ expression: render_snapshot(buf)9 0..20 fg=#80808010 0..4 fg=DarkGray10 4..13 fg=#56B6C2 mod=BOLD+10 13..23 fg=#80808011 0..4 fg=DarkGray11 4..13 fg=#56B6C2 mod=BOLD12 0..4 fg=DarkGraydiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states.snap b/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states.snapindex 2af080c49..d01ebe908 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states.snap@@ -1,12 +1,11 @@---source: src/core/cli/tui/tests/snapshot.rs-assertion_line: 165expression: render_snapshot(buf)----| 1 subagent running · 1 queued · 2 waiting · /agents to view or stop |+| 1 subagent running · 2 queued · 1 waiting · /agents to view or stop || └ kv-review · 1m 05s · Read mod_3.rs || docs-writer · Queued (1) |-| collector · Waiting (phase 2) |+| collector · Queued · phase 2 || builder · Waiting on background work · 30s |0 0..45 fg=#808080@@ -20,7 +19,7 @@ expression: render_snapshot(buf)2 15..28 fg=#8080803 0..4 fg=DarkGray3 4..13 fg=#56B6C2 mod=BOLD- 3 13..33 fg=#808080+ 3 13..32 fg=#8080804 0..4 fg=DarkGray4 4..11 fg=#56B6C2 mod=BOLD4 11..46 fg=#808080diff --git a/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states_inspector.snap b/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states_inspector.snapindex e2adf38d3..be5fd9357 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states_inspector.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/subagent_states_inspector.snap@@ -1,13 +1,12 @@---source: src/core/cli/tui/tests/snapshot.rs-assertion_line: 165expression: render_snapshot(buf)---| 👋 gpt-5-mini effort medium ctx 0K/128K fallback ● [ready] ||╭ subagents ───────────────────────────────────────────────────────────────────────────────────────╮||│ ▶ • kv-review 4 tools · 4 req · 50% ctx · 75% cache hit Running · Read mod_3.rs │||│ • docs-writer Queued (1) │|-|│ • collector Waiting (phase 2) │|+|│ • collector Queued · phase 2 │||│ • builder 2 tools · 2 req · 6% ctx Waiting on background work │||│ │||╰──────────────────────────────────────────────────────────────────────────────────────────────────╯|@@ -15,7 +14,7 @@ expression: render_snapshot(buf)|────────────────────────────────────────────────────────────────────────────────────────────────────||selecting… || |-|📂 /snapshot/repo ↑/↓ select Enter view m message x stop Esc close|+|📂 /snapshot/repo ↑/↓ select Enter view x stop Esc close|0 0..2 fg=Yellow0 3..14 mod=BOLD@@ -33,7 +32,7 @@ expression: render_snapshot(buf)4 0..1 fg=#56B6C24 4..6 fg=#8080804 6..15 fg=#56B6C2 mod=BOLD- 4 17..34 fg=#808080+ 4 17..33 fg=#8080804 99..100 fg=#56B6C25 0..1 fg=#56B6C25 4..6 fg=#808080@@ -47,4 +46,4 @@ expression: render_snapshot(buf)10 0..10 mod=DIM | ITALIC12 0..1 fg=#80808012 2..17 fg=#808080-12 43..100 mod=DIM+12 55..100 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_narrow.snap b/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_narrow.snapindex a0de9e623..09a2bfe69 100644--- a/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_narrow.snap+++ b/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_narrow.snap@@ -4,14 +4,14 @@ assertion_line: 165expression: render_snapshot(buf)---| 2 subagents running · 1 queued |-| └ kv-review · 1m 05s |+| └ kv-review · 1m 05s · Read mod...|| perf-scan · 12s · starting… || docs-writer · Queued (1) |0 0..31 fg=#8080801 0..4 fg=DarkGray1 4..13 fg=#56B6C2 mod=BOLD- 1 13..22 fg=#808080+ 1 13..36 fg=#8080802 0..4 fg=DarkGray2 4..13 fg=#56B6C2 mod=BOLD2 13..31 fg=#808080diff --git a/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_parallel.snap b/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_parallel.snapnew file mode 100644index 000000000..d311a5952--- /dev/null+++ b/src-tauri/src/core/cli/tui/tests/snapshots/subagents_idle_parallel.snap@@ -0,0 +1,15 @@+---+source: src/core/cli/tui/tests/snapshot.rs+assertion_line: 165+expression: render_snapshot(buf)+---+| 1 subagent running · /agents to view or stop |+| └ kv-review · 1m 05s · Running cargo test --locked --no-default-features --...|++ 0 0..22 fg=#808080+ 0 22..29 fg=#56B6C2+ 0 29..45 fg=#808080+ 1 0..4 fg=DarkGray+ 1 4..13 fg=#56B6C2 mod=BOLD+ 1 13..25 fg=#808080+ 1 25..80 fg=#56B6C2 mod=DIMdiff --git a/src-tauri/src/core/cli/tui/tests/snapshots/worktrees_inspector_list.snap b/src-tauri/src/core/cli/tui/tests/snapshots/worktrees_inspector_list.snapnew file mode 100644index 000000000..2a23538f6--- /dev/null+++ b/src-tauri/src/core/cli/tui/tests/snapshots/worktrees_inspector_list.snap@@ -0,0 +1,59 @@+---+source: src/core/cli/tui/tests/snapshot.rs+expression: render_snapshot(buf)+---+| 👋 gpt-5-mini effort medium ctx 0K/128K fallback ● [ready] |+|╭ subagent worktrees ──────────────────────────────────────────────────────────────────────────────╮|+|│ ▶ Remove what is safe to remove 1 checkout(s), 2.0 KB │|+|│ Clear build cache 3.0 GB │|+|│ jan/agent/child-0001 2.0 KB in use by a running subagent │|+|│ jan/agent/other-0002 2.0 KB in use by another live jan session │|+|│ jan/agent/dirty-0003 2.0 KB holds uncommitted work: a.txt, .env; 1 commit(s) │|+|│ jan/agent/ahead-0004 2.0 KB holds 3 commit(s) not in your repository │|+|│ jan/agent/idle-0005 2.0 KB removable (no work in it) │|+|╰──────────────────────────────────────────────────────────────────────────────────────────────────╯|+| |+|────────────────────────────────────────────────────────────────────────────────────────────────────|+|selecting… |+| |+|📂 /snapshot/repo ↑/↓ select Enter run or remove Esc close|++ 0 0..2 fg=Yellow+ 0 3..14 mod=BOLD+ 0 14..29 fg=#E5C07B+ 0 55..64 fg=#98C379+ 1 0..100 fg=#56B6C2+ 2 0..1 fg=#56B6C2+ 2 2..98 fg=Cyan mod=BOLD+ 2 99..100 fg=#56B6C2+ 3 0..1 fg=#56B6C2+ 3 21..29 fg=#808080+ 3 99..100 fg=#56B6C2+ 4 0..1 fg=#56B6C2+ 4 4..24 fg=#56B6C2+ 4 24..62 fg=#808080+ 4 99..100 fg=#56B6C2+ 5 0..1 fg=#56B6C2+ 5 4..24 fg=#56B6C2+ 5 24..68 fg=#808080+ 5 99..100 fg=#56B6C2+ 6 0..1 fg=#56B6C2+ 6 4..24 fg=#56B6C2+ 6 24..32 fg=#808080+ 6 32..82 fg=#E5C07B+ 6 99..100 fg=#56B6C2+ 7 0..1 fg=#56B6C2+ 7 4..24 fg=#56B6C2+ 7 24..32 fg=#808080+ 7 32..74 fg=#E5C07B+ 7 99..100 fg=#56B6C2+ 8 0..1 fg=#56B6C2+ 8 4..23 fg=#56B6C2+ 8 23..31 fg=#808080+ 8 31..58 fg=#98C379+ 8 99..100 fg=#56B6C2+ 9 0..100 fg=#56B6C2+12 0..10 mod=DIM | ITALIC+14 0..1 fg=#808080+14 2..17 fg=#808080+14 55..100 mod=DIMdiff --git a/src-tauri/src/core/cli/worktree.rs b/src-tauri/src/core/cli/worktree.rsindex 6f632b1e9..7396d0b62 100644--- a/src-tauri/src/core/cli/worktree.rs+++ b/src-tauri/src/core/cli/worktree.rs@@ -51,6 +51,14 @@ pub fn resolve_enabled(flag: Option<bool>, configured: Option<bool>) -> bool {.unwrap_or(DEFAULT_WORKTREE)}+/// Resolve whether a subagent that can write, and asked for no `workspace`, gets+/// a worktree of its own: the per-invocation flag, then the project's+/// `[agent].subagent_worktrees`, then off, where it shares the session's+/// checkout.+pub fn resolve_subagent_worktrees(flag: Option<bool>, configured: Option<bool>) -> bool {+ flag.or(configured).unwrap_or(false)+}+/// `~/.jan/worktrees`, the user-wide home for agent checkouts.pub fn worktrees_root() -> Result<PathBuf, String> {Ok(crate::core::agent::global_config::global_jan_dir()?.join("worktrees"))@@ -198,6 +206,16 @@ mod tests {assert!(resolve_enabled(None, Some(true)));}+ #[test]+ fn subagent_worktrees_follow_flag_then_config_then_off() {+ assert!(!resolve_subagent_worktrees(None, None));+ assert!(resolve_subagent_worktrees(None, Some(true)));+ assert!(!resolve_subagent_worktrees(None, Some(false)));+ assert!(resolve_subagent_worktrees(Some(true), None));+ assert!(resolve_subagent_worktrees(Some(true), Some(false)));+ assert!(!resolve_subagent_worktrees(Some(false), Some(true)));+ }+#[test]fn metadata_round_trips() {let worktree = Worktree {diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rsindex 506c46a2f..2c9751d9d 100644--- a/src-tauri/src/core/mcp/server/mod.rs+++ b/src-tauri/src/core/mcp/server/mod.rs@@ -258,7 +258,18 @@ impl JanToolServer {Decision::HardDeny(DenyReason::Policy) => {return (format!("ERROR: tool '{name}' is denied by policy"), Vec::new())}- Decision::HardDeny(DenyReason::Hidden) => {+ Decision::HardDeny(DenyReason::TooComplex) => {+ return (+ format!(+ "ERROR: tool '{name}' was refused: the command or path is too large or \+ deeply nested to check; split it or shorten the path, or write a \+ long script to a file and run that"+ ),+ Vec::new(),+ )+ }+ // No held shell cwd here, so `HiddenShellCwd` never comes up.+ Decision::HardDeny(DenyReason::Hidden | DenyReason::HiddenShellCwd) => {let offered: Vec<&str> = tauri_plugin_agent_tools::tools::JAN_HOME_TOOLS.into_iter().filter(|t| self.opts.served.is_served(t))