Skip to content

armgit / jan

Public Imported from GitHub
0

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

feat(agent-tools): Stop kills the session's running/backgrounded bash

Akarshan Biswas04e503d40296
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
index 7a9615731..b799ffa9f 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
@@ -27,6 +27,7 @@ const COMMANDS: &[&str] = &[
"stop_monitor",
"list_monitors",
"stop_session_monitors",
+ "cancel_thread_bash",
"preview_register_root",
"preview_unregister_root",
];
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
index 2f0dd9dfe..daa45d57e 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
@@ -496,3 +496,12 @@ export async function listMonitors(threadId: string): Promise<string> {
export async function stopSessionMonitors(threadId: string): Promise<void> {
await invoke('plugin:agent-tools|stop_session_monitors', { threadId })
}
+
+/**
+ * Kill every `bash` tree this session started, running or backgrounded. Driven
+ * by the Stop button: aborting the JS run only discards a tool result, so a
+ * long or backgrounded shell would otherwise keep executing on the host.
+ */
+export async function cancelThreadBash(threadId: string): Promise<void> {
+ await invoke('plugin:agent-tools|cancel_thread_bash', { threadId })
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
index 3d8aeced9..203a7b8ea 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
@@ -29,6 +29,7 @@ permissions = [
"allow-stop-monitor",
"allow-list-monitors",
"allow-stop-session-monitors",
+ "allow-cancel-thread-bash",
"allow-preview-register-root",
"allow-preview-unregister-root",
]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
index 20093f9fb..93be2cdc3 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
@@ -306,6 +306,18 @@
"const": "deny-attachment-import",
"markdownDescription": "Denies the attachment_import command without any pre-configured scope."
},
+ {
+ "description": "Enables the cancel_thread_bash command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-cancel-thread-bash",
+ "markdownDescription": "Enables the cancel_thread_bash command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the cancel_thread_bash command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-cancel-thread-bash",
+ "markdownDescription": "Denies the cancel_thread_bash command without any pre-configured scope."
+ },
{
"description": "Enables the execute_tool command without any pre-configured scope.",
"type": "string",
@@ -655,12 +667,10 @@
"markdownDescription": "Denies the workspace_path command without any pre-configured scope."
},
{
-
- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`",
+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`"
-
+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 7d58aa9a1..4d74ca88b 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -620,6 +620,17 @@ pub async fn stop_session_monitors(thread_id: String) -> Result<(), AgentToolsEr
Ok(())
}
+/// Kill every `bash` tree this session started, running or backgrounded. Driven
+/// by the Stop button: aborting the JS run only discards a tool result, so
+/// without this a long or backgrounded shell keeps executing on the host until
+/// app shutdown. Scoped to `thread_id`, so a concurrent session's shells are
+/// untouched.
+#[tauri::command]
+pub async fn cancel_thread_bash(thread_id: String) -> Result<(), AgentToolsError> {
+ crate::tools::proc::kill_thread(&thread_id);
+ Ok(())
+}
+
/// Pick the workspace root a tool call resolves relative paths against, plus the
/// side roots it may read and write.
///
@@ -876,7 +887,8 @@ async fn execute_tool_inner(
.with_mask_root(Path::new(&data_folder))
.with_scratch_root(&scratch)
.with_read_roots(&read_roots)
- .with_write_roots(&write_roots);
+ .with_write_roots(&write_roots)
+ .with_thread_id(Some(&thread_id));
if let Some(sp) = skill_project.as_deref() {
ctx = ctx.with_skill_project_root(sp);
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
index 9aab5fdd2..8503f863e 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
@@ -62,6 +62,7 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
commands::stop_monitor,
commands::list_monitors,
commands::stop_session_monitors,
+ commands::cancel_thread_bash,
commands::preview_register_root,
commands::preview_unregister_root
])
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index d4a456d6b..a8bbb2dfc 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
@@ -835,7 +835,15 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
Ok(v) => v,
Err(e) => return e,
};
- let child = match proc::spawn(&shell, command, root, sandbox_tmp.as_deref(), ctx.shell_env()).await
+ let child = match proc::spawn(
+ &shell,
+ command,
+ root,
+ sandbox_tmp.as_deref(),
+ ctx.shell_env(),
+ ctx.thread_id,
+ )
+ .await
{
Ok(c) => c,
Err(e) => return format!("ERROR: failed to run command: {e}"),
@@ -849,6 +857,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
// reap its whole process tree if it is still running.
let (tx, mut rx) = oneshot::channel();
let spill_scratch = ctx.scratch_root.map(Path::to_path_buf);
+ // Owned for the detached task, which unregisters from the same session
+ // bucket the child was registered under.
+ let thread_owned = ctx.thread_id.map(str::to_string);
// Cloned into the detached task, which is what keeps a backgrounded command
// reporting after this call has already returned its `job_id`.
let sink = ctx.on_output.clone();
@@ -876,7 +887,7 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
);
}
if let Some(pid) = pid {
- proc::unregister(pid);
+ proc::unregister(thread_owned.as_deref(), pid);
}
let _ = tx.send(out);
});
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.rs
index b957dc692..eee6732ce 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
@@ -1203,13 +1203,14 @@ mod enforcement_tests {
ws,
tmp.as_deref(),
super::super::proc::ShellEnv::default(),
+ None,
)
.await
.expect("spawn");
let pid = child.id();
let out = child.wait_with_output().await.expect("wait");
if let Some(pid) = pid {
- super::super::proc::unregister(pid);
+ super::super::proc::unregister(None, pid);
}
let mut text = String::from_utf8_lossy(&out.stdout).to_string();
text.push_str(&String::from_utf8_lossy(&out.stderr));
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index 6f554eaf5..44340bffa 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
@@ -129,6 +129,12 @@ pub struct ToolContext<'a> {
/// frontend's tool-call id) rather than inside `bash`, so the sink can carry
/// it from the first chunk.
pub call_id: Option<&'a str>,
+ /// The session (thread) this call belongs to, so a `bash` child is
+ /// registered under it and a per-session Stop (`proc::kill_thread`) reaps
+ /// exactly this session's shells. `None` on run-owned callers with no
+ /// session identity (the CLI, monitor poll children), which share the
+ /// process-wide bucket only `kill_all` reaps.
+ pub thread_id: Option<&'a str>,
/// Host env-var names (exact or `*`-glob) the shell may inherit on top of the
/// fixed base allowlist. Empty on every surface that has not configured any,
/// so the shell env is unchanged by default. Resolved once per run from
@@ -159,6 +165,7 @@ impl std::fmt::Debug for ToolContext<'_> {
.field("read_roots", &self.read_roots)
.field("write_roots", &self.write_roots)
.field("call_id", &self.call_id)
+ .field("thread_id", &self.thread_id)
.field("env_passthrough", &self.env_passthrough)
.field("env_set", &self.env_set)
.finish()
@@ -186,11 +193,18 @@ impl<'a> ToolContext<'a> {
read_roots: &[],
write_roots: &[],
call_id: None,
+ thread_id: None,
env_passthrough: &[],
env_set: &[],
}
}
+ /// The session (thread) this call belongs to. See [`Self::thread_id`].
+ pub fn with_thread_id(mut self, thread_id: Option<&'a str>) -> Self {
+ self.thread_id = thread_id;
+ self
+ }
+
/// Host env-var names the shell may inherit beyond the base allowlist. See
/// [`Self::env_passthrough`].
pub fn with_env_passthrough(mut self, names: &'a [String]) -> Self {
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
index 439a61811..b2f347b12 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -478,12 +478,15 @@ fn match_update(monitor_id: &str, name: &str, content: &str) -> MonitorUpdate {
async fn eval_script(ctx: &MonitorCtx, script: &str) -> Option<String> {
let tool_ctx = ctx.as_tool_context();
let (shell, sandbox_tmp, _policy) = crate::tools::handlers::confined_shell(&tool_ctx).ok()?;
+ // A poll child is short-lived and re-spawned each interval; it is not tied
+ // to a session's Stop, so it registers in the process-wide bucket.
let mut child = crate::tools::proc::spawn(
&shell,
script,
&ctx.project_root,
sandbox_tmp.as_deref(),
tool_ctx.shell_env(),
+ None,
)
.await
.ok()?;
@@ -523,7 +526,7 @@ async fn eval_script(ctx: &MonitorCtx, script: &str) -> Option<String> {
})
.await;
if let Some(pid) = pid {
- crate::tools::proc::unregister(pid);
+ crate::tools::proc::unregister(None, pid);
}
match result {
Ok((Ok(exit), head)) if exit.success() => {
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.rs
index d1efb6681..3d699ea4d 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,7 +4,7 @@
//! 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::HashSet;
+use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Mutex, OnceLock};
@@ -310,6 +310,7 @@ pub async fn spawn(
cwd: &Path,
scratch: Option<&Path>,
env: ShellEnv<'_>,
+ thread: Option<&str>,
) -> std::io::Result<Child> {
let mut cmd = Command::new(&cfg.program);
cmd.args(&cfg.args);
@@ -368,7 +369,7 @@ pub async fn spawn(
}
if let Some(pid) = child.id() {
- register(pid);
+ register(thread, pid);
}
Ok(child)
}
@@ -404,23 +405,63 @@ pub fn kill_tree(pid: u32) {
.output();
}
-fn running() -> &'static Mutex<HashSet<u32>> {
- static RUNNING: OnceLock<Mutex<HashSet<u32>>> = OnceLock::new();
- RUNNING.get_or_init(|| Mutex::new(HashSet::new()))
+/// 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();
+ RUNNING.get_or_init(|| Mutex::new(HashMap::new()))
}
-pub fn register(pid: u32) {
- running().lock().unwrap().insert(pid);
+/// Bucket for pids spawned outside any session.
+const NO_THREAD: &str = "";
+
+pub fn register(thread: Option<&str>, pid: u32) {
+ running()
+ .lock()
+ .unwrap()
+ .entry(thread.unwrap_or(NO_THREAD).to_string())
+ .or_default()
+ .insert(pid);
}
-pub fn unregister(pid: u32) {
- running().lock().unwrap().remove(&pid);
+pub fn unregister(thread: Option<&str>, pid: u32) {
+ let key = thread.unwrap_or(NO_THREAD);
+ let mut map = running().lock().unwrap();
+ if let Some(set) = map.get_mut(key) {
+ set.remove(&pid);
+ if set.is_empty() {
+ map.remove(key);
+ }
+ }
+}
+
+/// 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.
+pub fn kill_thread(thread: &str) {
+ let pids: Vec<u32> = running()
+ .lock()
+ .unwrap()
+ .remove(thread)
+ .map(|set| set.into_iter().collect())
+ .unwrap_or_default();
+ for pid in pids {
+ kill_tree(pid);
+ }
}
-/// Reap every still-running bash command. Called on app shutdown so no shell
-/// tree outlives the process that spawned it.
+/// Reap every still-running bash command across all sessions. Called on app
+/// shutdown so no shell tree outlives the process that spawned it.
pub fn kill_all() {
- let pids: Vec<u32> = running().lock().unwrap().drain().collect();
+ let pids: Vec<u32> = running()
+ .lock()
+ .unwrap()
+ .drain()
+ .flat_map(|(_, set)| set)
+ .collect();
for pid in pids {
kill_tree(pid);
}
@@ -469,10 +510,10 @@ mod tests {
#[tokio::test]
async fn runs_a_command_and_captures_stdout() {
- let child = spawn(shell(), "echo hello", &tmp(), None, ShellEnv::default()).await.unwrap();
+ let child = spawn(shell(), "echo hello", &tmp(), None, ShellEnv::default(), None).await.unwrap();
let pid = child.id().unwrap();
let out = child.wait_with_output().await.unwrap();
- unregister(pid);
+ unregister(None, pid);
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
}
@@ -489,12 +530,13 @@ mod tests {
&tmp(),
Some(&scratch),
ShellEnv::default(),
+ None,
)
.await
.unwrap();
let pid = child.id().unwrap();
let out = child.wait_with_output().await.unwrap();
- unregister(pid);
+ unregister(None, pid);
let s = scratch.to_string_lossy();
assert_eq!(
String::from_utf8_lossy(&out.stdout).trim(),
@@ -507,12 +549,12 @@ mod tests {
/// through, rather than being handed an empty temp dir.
#[tokio::test]
async fn temp_env_is_left_alone_without_a_scratch() {
- let child = spawn(shell(), "echo ${TMPDIR:-unset}", &tmp(), None, ShellEnv::default())
+ let child = spawn(shell(), "echo ${TMPDIR:-unset}", &tmp(), None, ShellEnv::default(), None)
.await
.unwrap();
let pid = child.id().unwrap();
let out = child.wait_with_output().await.unwrap();
- unregister(pid);
+ unregister(None, pid);
let expected = std::env::var("TMPDIR").unwrap_or_else(|_| "unset".to_string());
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), expected);
}
@@ -521,7 +563,7 @@ mod tests {
async fn kill_tree_reaps_backgrounded_grandchild() {
// The shell backgrounds a long sleeper, prints its pid, then waits on
// it. Killing the group must take down that grandchild too.
- let mut child = spawn(shell(), "sleep 300 & echo $! ; wait", &tmp(), None, ShellEnv::default())
+ let mut child = spawn(shell(), "sleep 300 & echo $! ; wait", &tmp(), None, ShellEnv::default(), None)
.await
.unwrap();
let leader = child.id().unwrap();
@@ -537,7 +579,7 @@ mod tests {
kill_tree(leader);
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), child.wait()).await;
- unregister(leader);
+ unregister(None, leader);
// Give the kernel a moment to tear the group down.
for _ in 0..50 {
@@ -549,16 +591,39 @@ mod tests {
assert!(!alive(grandchild), "grandchild must be reaped by group kill");
}
+ fn is_registered(thread: Option<&str>, pid: u32) -> bool {
+ running()
+ .lock()
+ .unwrap()
+ .get(thread.unwrap_or(NO_THREAD))
+ .map(|set| set.contains(&pid))
+ .unwrap_or(false)
+ }
+
#[test]
fn register_and_unregister_track_pids() {
// A pid outside any real range: exercising the registry only, never
// 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(fake);
- assert!(running().lock().unwrap().contains(&fake));
- unregister(fake);
- assert!(!running().lock().unwrap().contains(&fake));
+ register(Some("thread-a"), fake);
+ assert!(is_registered(Some("thread-a"), fake));
+ unregister(Some("thread-a"), fake);
+ assert!(!is_registered(Some("thread-a"), fake));
+ }
+
+ /// `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);
+ 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");
+ unregister(Some("sess-b"), b);
}
#[cfg(unix)]
@@ -566,17 +631,17 @@ mod tests {
async fn confine_limits_caps_the_child_process_count() {
// The rlimit mounting must actually reach the spawned child: with NPROC
// clamped we still run up to the cap, but a fork-bomb past it fails.
- let child = spawn(shell(), "exit 0", &tmp(), None, ShellEnv::default()).await.unwrap();
+ let child = spawn(shell(), "exit 0", &tmp(), None, ShellEnv::default(), None).await.unwrap();
let pid = child.id().unwrap();
child.wait_with_output().await.unwrap();
- unregister(pid);
+ unregister(None, pid);
// Spawn a shell that reports its own soft NOFILE limit; confine_limits
// sets it to 1024, which should be visible inside the sandbox.
- let child = spawn(shell(), "ulimit -n", &tmp(), None, ShellEnv::default()).await.unwrap();
+ let child = spawn(shell(), "ulimit -n", &tmp(), None, ShellEnv::default(), None).await.unwrap();
let pid = child.id().unwrap();
let out = child.wait_with_output().await.unwrap();
- unregister(pid);
+ unregister(None, pid);
let val = String::from_utf8_lossy(&out.stdout).trim().to_string();
assert_eq!(val, "1024", "NOFILE soft limit should be capped, got: {val}");
}
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 43df7ce3c..acf67b0ad 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -65,6 +65,7 @@ import {
SESSION_STORAGE_PREFIX,
} from '@/constants/chat'
import { defaultModel } from '@/lib/models'
+import { cancelAgentThreadBash } from '@/lib/agentTools'
import { useAssistant } from '@/hooks/useAssistant'
import { AssistantSwitcher } from '@/containers/AssistantSwitcher'
import DropdownToolsAvailable from '@/containers/DropdownToolsAvailable'
@@ -794,6 +795,10 @@ const ChatInput = memo(function ChatInput({
abortControllers[threadId]?.abort()
}
cancelToolCall?.()
+ // Aborting the stream/loop only discards a pending tool result; a running
+ // or backgrounded bash keeps executing until its session's shells are
+ // killed. Chat's tool thread_id is the chat thread id.
+ void cancelAgentThreadBash(threadId)
},
[abortControllers, cancelToolCall, onStop]
)
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index 6386503c7..2343f21cb 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -13,6 +13,7 @@ import {
stopMonitor,
listMonitors,
stopSessionMonitors,
+ cancelThreadBash,
type MemoryCatalogEntry,
type MonitorUpdate,
type SandboxStatus,
@@ -370,6 +371,19 @@ export async function stopAgentSessionMonitors(sessionId: string): Promise<void>
}
}
+/**
+ * Kill every `bash` tree this session started when the user presses Stop.
+ * Best-effort: aborting the JS run already unwinds the turn, so a failure here
+ * only means a shell keeps running, not user-visible damage.
+ */
+export async function cancelAgentThreadBash(sessionId: string): Promise<void> {
+ try {
+ await cancelThreadBash(sessionId)
+ } catch (e) {
+ console.warn('[agentTools] Failed to cancel session bash:', messageOf(e))
+ }
+}
+
/** A file claimed for a subagent's answer: the name to fill it by, and the
* model-visible path (`/tmp/subagents/<id>.md`, where the scratch is mounted
* over `/tmp`) the parent agent can `read`. */
diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.ts
index 98b8e74b9..418ec52db 100644
--- a/web-app/src/lib/coworkRunner.ts
+++ b/web-app/src/lib/coworkRunner.ts
@@ -93,9 +93,9 @@ function createHandle(sid: string, runId: string): RunHandle {
* Stop a session's run: the model stream, the tool dispatch loop, every nested
* subagent, and any question the user was being asked.
*
- * An in-flight `bash` cannot be cancelled — `execute_tool` is a plain `invoke`
- * with no cancellation token — so its result is discarded and the process runs
- * to completion.
+ * `abortRun` unwinds only the JS side; a running or backgrounded `bash` child
+ * is killed separately by the Stop handler via `cancelAgentThreadBash`, which
+ * reaps the session's shells in Rust (`proc::kill_thread`).
*/
export function abortRun(sid: string, reason = 'cancelled'): void {
const handle = handles.get(sid)
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index a7f2eef85..11f2f5969 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -98,6 +98,7 @@ import {
fillSubagentResult,
importAttachment,
reserveSubagentResult,
+ cancelAgentThreadBash,
} from '@/lib/agentTools'
import { monitorLaneFor, type MonitorLane } from '@/lib/coworkMonitor'
import { CoworkParkedNotice } from '@/containers/CoworkParkedNotice'
@@ -1286,7 +1287,12 @@ function CoworkPage() {
const handleStop = useCallback(() => {
abortRef.current?.abort('cancelled')
- if (session?.id) abortRun(session.id)
+ // Aborting the JS run only discards the pending tool result; a running or
+ // backgrounded bash keeps executing until this kills the session's shells.
+ if (session?.id) {
+ abortRun(session.id)
+ void cancelAgentThreadBash(session.id)
+ }
for (const resolve of askResolvers.current.values()) resolve(null)
askResolvers.current.clear()
}, [session?.id])