Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): /shells inspector that can stop background shells
Akarshan Biswas73c4eb8823cb
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 e24a5fc90..ab2fdd251 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@@ -892,6 +892,11 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// land in a file the agent reads when it is ready -- no second tool// mode, no job registry. `None` means the background file could not// be created; the command still runs, its output just isn't captured.+ // Flag it in the process registry so the `/shells` inspector lists it+ // as a detached shell the user can stop.+ if let Some(pid) = pid {+ proc::mark_backgrounded(ctx.thread_id, pid);+ }match new_temp_path(ctx.scratch_root) {Some(path) => {let display =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 3d699ea4d..74eae25fe 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@@ -4,10 +4,11 @@//! top-level shell. Without this, any command that spawns children (a build, a//! `foo &`, a pipeline) leaks orphans when the run is torn down.-use std::collections::{HashMap, HashSet};+use std::collections::HashMap;use std::path::{Path, PathBuf};use std::process::Stdio;use std::sync::{Mutex, OnceLock};+use std::time::Instant;use tokio::process::{Child, Command};@@ -369,7 +370,7 @@ pub async fn spawn(}if let Some(pid) = child.id() {- register(thread, pid);+ register(thread, pid, command);}Ok(child)}@@ -405,26 +406,52 @@ pub fn kill_tree(pid: u32) {.output();}-/// Running bash pids, bucketed by the session (thread id) that spawned them, so-/// a per-session cancel (`kill_thread`) reaps exactly that session's shells-/// without touching a concurrently-running one. Callers with no session (the-/// monitor poll children, tests) share the [`NO_THREAD`] bucket, which only-/// `kill_all` reaps.-fn running() -> &'static Mutex<HashMap<String, HashSet<u32>>> {- static RUNNING: OnceLock<Mutex<HashMap<String, HashSet<u32>>>> = OnceLock::new();+/// A running bash command: what it is, when it started, and whether it outran+/// its call's timeout and detached into the background. Backs the `/shells`+/// inspector, which lists the detached ones so the user can stop a stuck job.+struct ShellProc {+ command: String,+ started: Instant,+ backgrounded: bool,+}++/// One running background shell, as `snapshot` reports it to the UI. `pid` is+/// the handle [`kill`] takes to stop it.+#[derive(Debug, Clone)]+pub struct ShellInfo {+ pub pid: u32,+ pub command: String,+ pub elapsed_secs: u64,+ pub backgrounded: bool,+}++/// Running bash commands, bucketed by the session (thread id) that spawned them+/// and keyed by pid, so a per-session cancel (`kill_thread`) reaps exactly that+/// session's shells without touching a concurrently-running one. Callers with no+/// session (the monitor poll children, tests) share the [`NO_THREAD`] bucket,+/// which only `kill_all` reaps.+fn running() -> &'static Mutex<HashMap<String, HashMap<u32, ShellProc>>> {+ static RUNNING: OnceLock<Mutex<HashMap<String, HashMap<u32, ShellProc>>>> = OnceLock::new();RUNNING.get_or_init(|| Mutex::new(HashMap::new()))}/// Bucket for pids spawned outside any session.const NO_THREAD: &str = "";-pub fn register(thread: Option<&str>, pid: u32) {+pub fn register(thread: Option<&str>, pid: u32, command: &str) {running().lock().unwrap().entry(thread.unwrap_or(NO_THREAD).to_string()).or_default()- .insert(pid);+ .insert(+ pid,+ ShellProc {+ command: command.to_string(),+ started: Instant::now(),+ backgrounded: false,+ },+ );}pub fn unregister(thread: Option<&str>, pid: u32) {@@ -438,6 +465,51 @@ 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) {+ 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;+ }+ }+}++/// 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> {+ let map = running().lock().unwrap();+ let mut out: Vec<ShellInfo> = map+ .values()+ .flat_map(|set| {+ set.iter().map(|(pid, p)| ShellInfo {+ pid: *pid,+ command: p.command.clone(),+ elapsed_secs: p.started.elapsed().as_secs(),+ backgrounded: p.backgrounded,+ })+ })+ .collect();+ out.sort_by_key(|s| s.pid);+ out+}++/// Stop one running shell by pid: reap its whole tree and drop it from the+/// registry. Returns whether the pid was known. Drives the `/shells` stop action.+pub fn kill(pid: u32) -> bool {+ let found = {+ let mut map = running().lock().unwrap();+ let hit = map.values_mut().any(|set| set.remove(&pid).is_some());+ map.retain(|_, set| !set.is_empty());+ hit+ };+ if found {+ kill_tree(pid);+ }+ found+}+/// Reap every bash tree a session started. The per-session counterpart of/// [`kill_all`]: the Stop button drives this so a running or backgrounded shell/// is terminated with the run rather than left to finish on the host.@@ -446,7 +518,7 @@ pub fn kill_thread(thread: &str) {.lock().unwrap().remove(thread)- .map(|set| set.into_iter().collect())+ .map(|set| set.into_keys().collect()).unwrap_or_default();for pid in pids {kill_tree(pid);@@ -460,7 +532,7 @@ pub fn kill_all() {.lock().unwrap().drain()- .flat_map(|(_, set)| set)+ .flat_map(|(_, set)| set.into_keys()).collect();for pid in pids {kill_tree(pid);@@ -596,7 +668,7 @@ mod tests {.lock().unwrap().get(thread.unwrap_or(NO_THREAD))- .map(|set| set.contains(&pid))+ .map(|set| set.contains_key(&pid)).unwrap_or(false)}@@ -606,20 +678,51 @@ mod tests {// signalling a live process (kill_all is shutdown-only and would reap// other tests' children if called under the parallel harness).let fake = u32::MAX - 1;- register(Some("thread-a"), fake);+ register(Some("thread-a"), fake, "sleep 1");assert!(is_registered(Some("thread-a"), fake));unregister(Some("thread-a"), fake);assert!(!is_registered(Some("thread-a"), fake));}+ /// `mark_backgrounded` flips only the named pid, and `snapshot` reports it+ /// with its command so `/shells` can name the detached job.+ #[test]+ fn snapshot_reports_backgrounded_shells_with_their_command() {+ let (fg, bg) = (u32::MAX - 10, u32::MAX - 11);+ register(Some("snap"), fg, "cargo build");+ register(Some("snap"), bg, "sleep 300");+ mark_backgrounded(Some("snap"), bg);+ let shells = snapshot();+ let got = |pid| shells.iter().find(|s| s.pid == pid).cloned();+ assert_eq!(got(bg).unwrap().command, "sleep 300");+ assert!(got(bg).unwrap().backgrounded, "marked one is backgrounded");+ assert!(!got(fg).unwrap().backgrounded, "the other is not");+ unregister(Some("snap"), fg);+ unregister(Some("snap"), bg);+ }++ /// `kill` drops the named pid from the registry (whichever bucket it is in)+ /// and reports whether it was known; an unknown pid is a no-op. Fake pids+ /// chosen to stay a positive, implausible i32 so the `kill_tree` this reaches+ /// signals a non-existent group (ESRCH), never a real low-numbered one.+ #[test]+ fn kill_removes_a_known_pid_and_reports_unknown() {+ let fake = 2_000_000_001;+ register(Some("kill-sess"), fake, "sleep 300");+ assert!(is_registered(Some("kill-sess"), fake));+ assert!(kill(fake), "a known pid is reported found");+ assert!(!is_registered(Some("kill-sess"), fake), "and dropped");+ assert!(!kill(2_000_000_002), "an unknown pid is a no-op");+ }+/// `kill_thread` reaps only its own session's pids and leaves another/// session's registrations intact, so Stop in one run cannot tear down a/// concurrent run's shell. Fake pids: exercising bucketing, never signalling.#[test]fn kill_thread_is_scoped_to_its_session() {let (a, b) = (u32::MAX - 2, u32::MAX - 3);- register(Some("sess-a"), a);- register(Some("sess-b"), b);+ register(Some("sess-a"), a, "sleep 1");+ register(Some("sess-b"), b, "sleep 1");kill_thread("sess-a");assert!(!is_registered(Some("sess-a"), a), "own session must be reaped");assert!(is_registered(Some("sess-b"), b), "other session must survive");diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 33effb675..c702b46bc 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -440,6 +440,9 @@ enum PickerKind {/// One subagent's detail: its stats, brief, and collapsed call history./// Reached with Enter from `Agents`; Esc steps back to the list.AgentDetail,+ /// `/shells`: the background-shell inspector. Lists commands the `bash` tool+ /// detached (outran their timeout, still running), each stoppable with `x`.+ BackgroundShells,}/// Interactive list overlay (`/resume`, `/login`, `/mcp`, etc.): rows with a@@ -470,6 +473,7 @@ impl Picker {PickerKind::McpServer => " mcp server ",PickerKind::Agents => " subagents ",PickerKind::AgentDetail => " subagent ",+ PickerKind::BackgroundShells => " background shells ",}}@@ -492,6 +496,7 @@ impl Picker {PickerKind::McpServer => " ↑/↓ select Enter run Esc back",PickerKind::Agents => " ↑/↓ select Enter view Esc close",PickerKind::AgentDetail => " Esc back",+ PickerKind::BackgroundShells => " ↑/↓ select x stop Esc close",}}}@@ -1758,6 +1763,11 @@ struct App {/// [`LIVE_OUTPUT_MAX_BYTES`] from the end. This is what turns a running/// command from a spinner into a terminal.live_output: HashMap<String, String>,+ /// Background shells the `bash` tool has detached, refreshed from the process+ /// registry once per frame in the render loop (never in `draw`, so tests are+ /// not coupled to that process-global state). Drives the `/shells` inspector+ /// and the footer chip; the row that stops one reads the pid off it.+ bg_shells: Vec<tauri_plugin_agent_tools::tools::proc::ShellInfo>,/// Base snapshot (working-tree state before the first turn) for the active/// thread. `Some` once snapshotting is armed; `None` = no workspace restore.base_snapshot: Option<String>,@@ -2407,6 +2417,7 @@ impl App {diff_paths: HashMap::new(),bash_commands: HashMap::new(),live_output: HashMap::new(),+ bg_shells: Vec::new(),base_snapshot: None,checkpoints: Vec::new(),snap_queue: std::collections::VecDeque::new(),@@ -8728,6 +8739,15 @@ async fn chat_loop<B: Backend>(if app.take_repaint() {apply_repaint(terminal);}+ // Refresh the detached-shell list from the process registry here, in the+ // live loop, rather than inside `draw`: the registry is process-global, so+ // reading it from the render path would couple every render test to+ // whatever a parallel test has spawned. `draw`, the footer chip and the+ // `/shells` picker all read `app.bg_shells` instead.+ app.bg_shells = tauri_plugin_agent_tools::tools::proc::snapshot()+ .into_iter()+ .filter(|s| s.backgrounded)+ .collect();let draw_result = terminal.draw(|f| draw(f, app)).map_err(|e| e.to_string());if sync_output {let _ = execute!(io::stdout(), EndSynchronizedUpdate);@@ -9998,6 +10018,21 @@ async fn handle_key(}}}+ // `/shells`: `x` stops the selected background shell (kills its whole+ // process tree). The rows are rebuilt from the live registry each+ // frame, so the stopped one drops out on the next draw.+ KeyCode::Char('x') if picker.kind == PickerKind::BackgroundShells => {+ let pid: Option<u32> = picker.items[picker.selected].value.parse().ok();+ match pid {+ Some(pid)+ if tauri_plugin_agent_tools::tools::proc::kill(pid) =>+ {+ app.note(&format!("stopped background shell (pid {pid})"));+ }+ Some(pid) => app.note(&format!("shell {pid} already finished")),+ None => {}+ }+ }// Collection picker: Space toggles the selected plugin, Enter hands// the checked set to the loop (see `plugin_select_request`). Rows// already installed stay displayed but are not toggleable -- checking@@ -10088,8 +10123,11 @@ async fn handle_key(// McpServer Enter is handled by the guarded arm above.PickerKind::McpServer => {}// Agents Enter is handled by the guarded arm above; the- // detail has no Enter action of its own.- PickerKind::Agents | PickerKind::AgentDetail => {}+ // detail has no Enter action of its own. Background shells are+ // acted on with `x` (stop), not Enter.+ PickerKind::Agents+ | PickerKind::AgentDetail+ | PickerKind::BackgroundShells => {}}}// Esc on the detail screen steps back to the server list rather@@ -10723,6 +10761,18 @@ const SLASH_COMMANDS: &[SlashCommand] = &[description: "Inspect running subagents: their stats and current activity",alias_of: None,},+ SlashCommand {+ name: "/shells",+ hint: "",+ description: "Inspect and stop background shell commands the agent left running",+ alias_of: None,+ },+ SlashCommand {+ name: "/jobs",+ hint: "",+ description: "Alias of /shells: inspect and stop background shell commands",+ alias_of: Some("/shells"),+ },SlashCommand {name: "/plugin",hint: "[list|install <spec>|remove <name>|search [query]]",@@ -10959,6 +11009,7 @@ async fn run_command(}"mcp" => open_mcp_picker(app, mcp_servers).await,"agents" => open_agents_picker(app),+ "shells" | "jobs" => open_background_shells_picker(app),"plugin" => plugin_command(app, arg).await,"login" => login_command(app, arg),"logout" => logout_command(app, arg),@@ -13017,6 +13068,48 @@ fn open_agents_picker(app: &mut App) {});}+/// Open the `/shells` inspector: background shells the `bash` tool detached. The+/// rows are rebuilt from the live process registry every frame (see `draw`), so+/// a shell that finishes or is stopped drops out without reopening.+fn open_background_shells_picker(app: &mut App) {+ app.picker = Some(Picker {+ kind: PickerKind::BackgroundShells,+ items: background_shell_picker_items(&app.bg_shells),+ selected: 0,+ armed_delete: None,+ });+}++/// One row per detached background shell (`<elapsed> <command>`), whose `value`+/// is the real pid so `x` can stop it. A single watermark row when nothing is+/// backgrounded. `shells` is `App::bg_shells` (already filtered to backgrounded+/// and refreshed off the render path), so this stays a pure render function.+fn background_shell_picker_items(+ shells: &[tauri_plugin_agent_tools::tools::proc::ShellInfo],+) -> Vec<PickerItem> {+ if shells.is_empty() {+ return vec![PickerItem {+ label: "no background shells running".to_string(),+ value: String::new(),+ hint: None,+ checkbox: None,+ }];+ }+ shells+ .iter()+ .map(|s| PickerItem {+ label: format!(+ "{} {}",+ format_elapsed(s.elapsed_secs),+ single_line(&s.command)+ ),+ value: s.pid.to_string(),+ hint: Some("running".to_string()),+ checkbox: None,+ })+ .collect()+}+/// One row per running subagent (`name · Nt · w-K · <activity>`), or a/// single watermark row when the fan-out is empty. The row `value` is the/// child's `run_id`, which Enter drills into.@@ -15061,6 +15154,16 @@ fn draw(f: &mut Frame, app: &mut App) {p.items = items;}}+ // The /shells inspector is likewise live: rebuild from the refreshed+ // `bg_shells` each frame so a shell that finished or was just stopped drops+ // out. (`bg_shells` is refreshed off the render path; see the loop.)+ if app.picker.as_ref().map(|p| p.kind) == Some(PickerKind::BackgroundShells) {+ let items = background_shell_picker_items(&app.bg_shells);+ if let Some(p) = app.picker.as_mut() {+ p.selected = p.selected.min(items.len().saturating_sub(1));+ p.items = items;+ }+ }if let Some(picker) = &app.picker {app.row_index.clear();let toml_path = app.agent_dir.join("agent.toml");@@ -17818,7 +17921,19 @@ fn footer_spans(app: &App) -> Vec<Span<'static>> {// the other states.Status::Idle => vec![Span::raw(" ")],};- // Standing indicator leads the row in both states.+ // Standing indicators lead the row in both states, newest concern leftmost:+ // pending queue, then background shells still running unattended.+ let bg_shells = app.bg_shells.len();+ if bg_shells > 0 {+ let plural = if bg_shells == 1 { "" } else { "s" };+ spans.insert(+ 0,+ Span::styled(+ format!("⚙ {bg_shells} bg shell{plural} · /shells "),+ Style::new().magenta().bold(),+ ),+ );+ }let queue_count = app.message_queue.len();if queue_count > 0 {spans.insert(@@ -17882,8 +17997,9 @@ mod tests {SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,};use super::{- agent_detail_lines, agent_picker_items, agents_column, collapse_runs, open_agents_picker,- trailing_repeat, workqueue_column, SubagentPanel, WorkItemView,+ agent_detail_lines, agent_picker_items, agents_column, background_shell_picker_items,+ collapse_runs, open_agents_picker, trailing_repeat, workqueue_column, SubagentPanel,+ WorkItemView,};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::r#loop::PermissionRegistry;@@ -18149,6 +18265,38 @@ mod tests {assert!(!text.contains("/agents"), "no hint when it would not fit: {text}");}+ #[test]+ fn shells_commands_are_registered() {+ assert!(SLASH_COMMANDS.iter().any(|command| command.name == "/shells"));+ assert!(SLASH_COMMANDS.iter().any(|command| command.name == "/jobs"));+ }++ /// Each `/shells` row names its command and its elapsed time, and carries the+ /// real pid in `value` so `x` can stop it.+ #[test]+ fn shells_picker_names_each_shell_by_command_and_elapsed() {+ use tauri_plugin_agent_tools::tools::proc::ShellInfo;+ let shells = vec![ShellInfo {+ pid: 4242,+ command: "sleep 9000".into(),+ elapsed_secs: 65,+ backgrounded: true,+ }];+ let items = background_shell_picker_items(&shells);+ assert_eq!(items.len(), 1);+ assert_eq!(items[0].value, "4242", "pid rides in value for the stop action");+ assert!(items[0].label.contains("sleep 9000"), "{}", items[0].label);+ assert!(items[0].label.contains("1m05s"), "elapsed shown: {}", items[0].label);+ }++ #[test]+ fn shells_picker_shows_an_empty_state() {+ let items = background_shell_picker_items(&[]);+ assert_eq!(items.len(), 1);+ assert!(items[0].label.contains("no background shells"));+ assert!(items[0].value.is_empty());+ }+#[test]fn agent_status_tags_the_child_panel_and_ignores_main() {let mut app = test_app();