A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
persistent bash() shells that survive kernel and daemon restarts (#3640)
Sebastian Müllere8dc899692b3
diff --git a/crates/pa-cli/src/interactive_mode.rs b/crates/pa-cli/src/interactive_mode.rsindex 4d38851ce6..987e8f59d8 100644--- a/crates/pa-cli/src/interactive_mode.rs+++ b/crates/pa-cli/src/interactive_mode.rs@@ -332,6 +332,7 @@ async fn run_agents_view_flow(let outcome = pa_tui::interactive::run_interactive_agents_view_open(session_options,UiMode::Terminal,+ view.panel,).await?;if !outcome.session_id.is_empty() {diff --git a/crates/pa-cli/tests/agents_view_flash_e2e.rs b/crates/pa-cli/tests/agents_view_flash_e2e.rsindex 33e0843889..5b8e0735ec 100644--- a/crates/pa-cli/tests/agents_view_flash_e2e.rs+++ b/crates/pa-cli/tests/agents_view_flash_e2e.rs@@ -528,12 +528,12 @@ async fn the_first_agents_view_render_is_clean_behind_hundreds_of_dead_subagents);let settled = frame_of(&view.frames, "flash parent");assert!(- settled.contains("300 subagents (0 running)"),+ settled.contains("300 subagents · 0 running"),"the settled frame carries the dead family behind the parent's ONE collapsed line:\n{settled}");let expanded = frame_of(&view.frames, "flash worker 007");assert!(- expanded.contains("▾ 300 subagents (0 running)"),+ expanded.contains("▾ 300 subagents · 0 running"),"the expansion opens the parent's one group and flips its marker:\n{expanded}");}diff --git a/crates/pa-cli/tests/agents_view_subagents_e2e.rs b/crates/pa-cli/tests/agents_view_subagents_e2e.rsindex 42e0a2c412..0b5be7d6f2 100644--- a/crates/pa-cli/tests/agents_view_subagents_e2e.rs+++ b/crates/pa-cli/tests/agents_view_subagents_e2e.rs@@ -264,7 +264,7 @@ async fn panel_expand_drill_in_and_back_re_expands_the_tree() {// aggregates the whole not-running descendant tree.let collapsed = first_frame_of(&view.frames, "orchestrator chat");assert!(- collapsed.contains("\u{25b8} 2 subagents (0 running)"),+ collapsed.contains("\u{25b8} 2 subagents · 0 running"),"the collapsed parent shows its ONE tree-aggregated summary row:\n{collapsed}");assert!(@@ -276,7 +276,7 @@ async fn panel_expand_drill_in_and_back_re_expands_the_tree() {// collapsed summary keeps the grandchild hidden until the child expands.let expanded = first_frame_of(&view.frames, "worker alpha");assert!(- expanded.contains("\u{25be} 2 subagents (0 running)"),+ expanded.contains("\u{25be} 2 subagents · 0 running"),"the expanded summary row keeps the tree aggregate and flips its marker:\n{expanded}");assert!(@@ -399,7 +399,7 @@ async fn panel_expand_drill_in_and_back_re_expands_the_tree() {// frame renders from the live roster alone — TS `applySessionList`).let returned = first_frame_of(&back.frames, "orchestrator chat");assert!(- returned.contains("\u{25b8} 2 subagents (0 running)"),+ returned.contains("\u{25b8} 2 subagents · 0 running"),"the opened child rides the parent's ONE aggregate (a top-level flip would leave the grandchild alone behind the summary):\n{returned}");assert!(@@ -408,7 +408,7 @@ async fn panel_expand_drill_in_and_back_re_expands_the_tree() {);let expanded = frame_of(&back.frames, "worker alpha");assert!(- expanded.contains("\u{25be} 2 subagents (0 running)"),+ expanded.contains("\u{25be} 2 subagents · 0 running"),"the expanded parent tree carries the live child:\n{expanded}");assert!(@@ -416,7 +416,7 @@ async fn panel_expand_drill_in_and_back_re_expands_the_tree() {"the grandchild stays hidden until the resumed child expands:\n{expanded}");assert!(- expanded.contains("\u{25b8} 1 subagents (0 running)"),+ expanded.contains("\u{25b8} 1 subagent · 0 running"),"the resumed child's own subtree stays behind its collapsed summary row:\n{expanded}");assert!(diff --git a/crates/pa-cli/tests/session_stop_dock_e2e.rs b/crates/pa-cli/tests/session_stop_dock_e2e.rsnew file mode 100644index 0000000000..442ea2273c--- /dev/null+++ b/crates/pa-cli/tests/session_stop_dock_e2e.rs@@ -0,0 +1,284 @@+// Pedantic-gate dispositions: the flow is intentionally linear and its async test future is+// stack-resident by shape.+#![allow(clippy::large_futures, clippy::too_many_lines)]+#![cfg(unix)]++//! E2E verifier for the dock after a session stop: a chat attached to a live session whose kernel+//! runs a shell drops the shell from its dock when the daemon stops the session, instead of+//! keeping the dead kernel's last list.++use std::io::{BufRead, BufReader, Write};+use std::os::unix::net::UnixStream;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};++use pa_tui::interactive::{+ HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection, SessionSelection, UiMode,+};+use serde_json::{json, Value};++struct Supervisor {+ child: Child,+ socket: PathBuf,+}++impl Drop for Supervisor {+ fn drop(&mut self) {+ let _ = ask(&self.socket, &json!({ "type": "shutdown" }));+ let _ = self.child.kill();+ let _ = self.child.wait();+ let _ = std::fs::remove_file(&self.socket);+ }+}++/// The kernel Python with prime-agent-runtime installed (`PA_E2E_KERNEL_PYTHON`, else the+/// product's kernel-venv layout). A missing kernel fails loudly: the shell needs a real kernel.+fn kernel_python() -> PathBuf {+ let python = std::env::var_os("PA_E2E_KERNEL_PYTHON").map_or_else(+ || {+ PathBuf::from(std::env::var("HOME").expect("HOME"))+ .join(".prime/agent/kernel-venv/bin/python")+ },+ PathBuf::from,+ );+ assert!(+ python.exists(),+ "kernel python {} not found: set PA_E2E_KERNEL_PYTHON",+ python.display()+ );+ python+}++#[allow(clippy::zombie_processes)]+fn spawn_supervisor(dir: &Path) -> Supervisor {+ let socket = dir.join("daemon.sock");+ let agent_dir = dir.join("agent");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ let mut command = Command::new(env!("CARGO_BIN_EXE_prime-agent"));+ command+ .args(["--mode", "daemon", "--daemon-socket"])+ .arg(&socket)+ .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)+ .env("PRIME_AGENT_KERNEL_PYTHON", kernel_python())+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ for var in [+ pa_daemon::worker::WORKER_ROLE_ENV,+ pa_daemon::worker::WORKER_TOKEN_ENV,+ pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV,+ pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV,+ pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV,+ pa_daemon::worker::WORKER_SOCKET_ENV,+ pa_daemon::worker::WORKER_INSTANCE_ID_ENV,+ pa_daemon::worker::WORKER_SCRIPT_ENV,+ ] {+ command.env_remove(var);+ }+ let child = command.spawn().expect("spawn prime-agent --mode daemon");+ let deadline = Instant::now() + Duration::from_secs(15);+ while UnixStream::connect(&socket).is_err() {+ assert!(Instant::now() < deadline, "supervisor socket never came up");+ std::thread::sleep(Duration::from_millis(20));+ }+ Supervisor { child, socket }+}++/// One command over a fresh connection; the answer is the response carrying the command's id.+fn ask(socket: &Path, command: &Value) -> Option<Value> {+ let stream = UnixStream::connect(socket).ok()?;+ let mut writer = stream.try_clone().ok()?;+ let mut reader = BufReader::new(stream);+ reader.read_line(&mut String::new()).ok()?;+ let mut line = serde_json::to_string(&json!({+ "type": "command",+ "id": "stop-e2e",+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "command": command,+ }))+ .ok()?;+ line.push('\n');+ writer.write_all(line.as_bytes()).ok()?;+ reader+ .get_ref()+ .set_read_timeout(Some(Duration::from_secs(60)))+ .ok()?;+ loop {+ let mut response = String::new();+ if reader.read_line(&mut response).ok()? == 0 {+ return None;+ }+ let value: Value = serde_json::from_str(&response).ok()?;+ if value.get("type").and_then(Value::as_str) == Some("response")+ && value.get("id").and_then(Value::as_str) == Some("stop-e2e")+ {+ return Some(value);+ }+ }+}++fn ask_ok(socket: &Path, command: &Value) -> Value {+ let response = ask(socket, command).expect("the daemon answered");+ assert_eq!(response["success"], true, "{command} failed: {response}");+ response+}++/// A live session whose kernel runs `cell` on its second turn (the first turn persists the+/// session); returns its active session id.+fn session_running(socket: &Path, dir: &Path, cell: &str) -> String {+ let script = dir.join("faux.json");+ std::fs::write(+ &script,+ json!({ "engine": "faux", "responses": [+ { "text": "ready" },+ { "content": [{ "type": "toolCall", "name": "python_repl",+ "arguments": { "code": cell } }] },+ { "text": "started" },+ ] })+ .to_string(),+ )+ .expect("write faux script");+ let created = ask_ok(+ socket,+ &json!({ "type": "create", "config": {+ "script": script.to_string_lossy(),+ "cwd": dir.to_string_lossy(),+ "sessionDir": dir.join("agent").join("sessions").to_string_lossy(),+ } }),+ );+ let active = created["data"]["activeSessionId"]+ .as_str()+ .expect("the created session is live")+ .to_string();+ for message in ["warm up", "start the shell"] {+ ask_ok(+ socket,+ &json!({ "type": "prompt", "activeSessionId": active, "message": message }),+ );+ ask_ok(+ socket,+ &json!({ "type": "wait_for_idle", "activeSessionId": active }),+ );+ }+ let listed = ask_ok(+ socket,+ &json!({ "type": "list_kernel_bash", "activeSessionId": active }),+ );+ assert_eq!(+ listed["data"]["activities"][0]["status"], "running",+ "the kernel runs the shell: {listed}"+ );+ active+}++fn chat_options(socket: PathBuf, cwd: PathBuf, active: String) -> InteractiveOptions {+ InteractiveOptions {+ models: None,+ socket_path: socket,+ cwd,+ session_dir: None,+ script_path: None,+ model_selection: ModelSelection::default(),+ model_catalog: Vec::new(),+ model_configured_providers: std::collections::HashSet::default(),+ model_recent_models: Vec::new(),+ default_thinking_level: None,+ no_session: false,+ session: SessionSelection::Attach(active),+ initial_message: None,+ show_images: true,+ fullscreen_mouse: true,+ theme: "prime".to_string(),+ code_block_indent: " ".to_string(),+ tree_filter_mode: String::new(),+ branch_summary_skip_prompt: false,+ version: "0.0.0".to_string(),+ onboarding: None,+ telemetry_disabled: None,+ client_auth: None,+ traces: None,+ provider_auth: None,+ update_commands: None,+ telemetry: None,+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),+ session_rlm_depth: None,+ prompt_stash: std::sync::Arc::default(),+ session_has_children: false,+ restore_dock_focus: false,+ client_settings: None,+ }+}++fn dock_line(frame: &str) -> &str {+ frame+ .lines()+ .find(|line| line.contains("subagents") && line.contains("heartbeats"))+ .unwrap_or_default()+}++#[tokio::test]+async fn stopping_the_attached_session_clears_its_shells_from_the_dock() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let supervisor = spawn_supervisor(dir.path());+ let active = session_running(&supervisor.socket, dir.path(), "h = bash('sleep 300')");++ let (rendered_tx, rendered_rx) = std::sync::mpsc::channel();+ let kill_thread = {+ let socket = supervisor.socket.clone();+ let active = active.clone();+ std::thread::spawn(move || {+ rendered_rx+ .recv_timeout(Duration::from_secs(60))+ .expect("the chat rendered the shell");+ ask_ok(+ &socket,+ &json!({ "type": "kill", "activeSessionId": active }),+ );+ })+ };+ let outcome = pa_tui::interactive::run_interactive(+ chat_options(supervisor.socket.clone(), dir.path().to_path_buf(), active),+ UiMode::Headless(HeadlessPlan {+ steps: vec![+ HeadlessStep::WaitRender {+ needle: "\u{25b8} 1 shell".to_string(),+ timeout_ms: 20_000,+ },+ HeadlessStep::Timestamp(rendered_tx),+ HeadlessStep::WaitRender {+ needle: "stopped this agent session".to_string(),+ timeout_ms: 20_000,+ },+ HeadlessStep::WaitRender {+ needle: "\u{25b8} 0 shells".to_string(),+ timeout_ms: 2_500,+ },+ ],+ width: 160,+ height: 30,+ }),+ )+ .await+ .expect("the chat run");+ kill_thread.join().expect("the stop ran");++ let frames = &outcome.frames;+ let stop_frame = frames+ .iter()+ .position(|frame| frame.contains("stopped this agent session"))+ .unwrap_or_else(|| panic!("the stop reached the chat:\n{}", frames.join("\n")));+ assert!(+ frames[..stop_frame]+ .iter()+ .any(|frame| dock_line(frame).contains("\u{25b8} 1 shell")),+ "the dock counted the live shell before the stop:\n{}",+ frames.join("\n")+ );+ let last = frames.last().expect("frames");+ assert!(+ dock_line(last).contains("\u{25b8} 0 shells"),+ "the dock dropped the stopped session's shell; last dock: {:?}\n{last}",+ dock_line(last)+ );+}diff --git a/crates/pa-core/src/kernel/bootstrap/runtime_code.rs b/crates/pa-core/src/kernel/bootstrap/runtime_code.rsindex b478cdd891..83b0f66e39 100644--- a/crates/pa-core/src/kernel/bootstrap/runtime_code.rs+++ b/crates/pa-core/src/kernel/bootstrap/runtime_code.rs@@ -79,7 +79,7 @@ except Exception as _prime_agent_rlm_error:rlm = _PrimeAgentMissingRlm()- def bash(command, yield_after=None):+ def bash(command, yield_after=None, persistent=False):rlm._raise_missing()"#;diff --git a/crates/pa-core/src/kernel/bootstrap/venv/probe.rs b/crates/pa-core/src/kernel/bootstrap/venv/probe.rsindex 8f4c1802de..3b50e17851 100644--- a/crates/pa-core/src/kernel/bootstrap/venv/probe.rs+++ b/crates/pa-core/src/kernel/bootstrap/venv/probe.rs@@ -28,7 +28,7 @@ fn run_quiet(command: &str, args: &[&str]) -> bool {/// The runtime-ready assertion from the TS product: a current/// prime-agent-runtime with the callable RLM surface, harness CRUD, bash/// handles, and protocol version 3.-const RUNTIME_READY_CHECK: &str = "import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ['create_memory', 'update_memory', 'delete_memory', 'create_skill', 'update_skill', 'delete_skill', 'create_subagent', 'update_subagent', 'delete_subagent', 'create_prompt_note', 'update_prompt_note', 'delete_prompt_note', 'record_refinement']; _mcp_discovery_methods = ['list_plugins', 'search_plugins', 'list_connections', 'search_tools', 'describe_tool']; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert all(callable(getattr(mcp, _m, None)) for _m in _mcp_discovery_methods), \"rlm.mcp is missing MCP discovery methods (list_plugins, search_plugins, list_connections, search_tools, describe_tool); the kernel venv needs a current prime-agent-runtime\"; assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert callable(rlm.rename); assert callable(rlm.rlm.rename); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert callable(rlm._set_completion_notices_wired); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')";+const RUNTIME_READY_CHECK: &str = "import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ['create_memory', 'update_memory', 'delete_memory', 'create_skill', 'update_skill', 'delete_skill', 'create_subagent', 'update_subagent', 'delete_subagent', 'create_prompt_note', 'update_prompt_note', 'delete_prompt_note', 'record_refinement']; _mcp_discovery_methods = ['list_plugins', 'search_plugins', 'list_connections', 'search_tools', 'describe_tool']; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert all(callable(getattr(mcp, _m, None)) for _m in _mcp_discovery_methods), \"rlm.mcp is missing MCP discovery methods (list_plugins, search_plugins, list_connections, search_tools, describe_tool); the kernel venv needs a current prime-agent-runtime\"; assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert callable(rlm.rename); assert callable(rlm.rlm.rename); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert {'persistent', 'yield_after'} <= set(inspect.signature(rlm.bash).parameters); assert callable(rlm.persistent_shells); assert callable(rlm._set_completion_notices_wired); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')";pub(crate) fn has_prime_agent_runtime(python: &str) -> bool {run_quiet(python, &["-c", RUNTIME_READY_CHECK])diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rsindex c6e26f5850..0081f706b0 100644--- a/crates/pa-core/src/kernel/provisioner.rs+++ b/crates/pa-core/src/kernel/provisioner.rs@@ -1424,6 +1424,27 @@ mod tests {}}+ #[tokio::test]+ async fn an_unsaved_session_blanks_the_kernel_session_id() {+ let dir = tempfile::tempdir().unwrap();+ let agent_dir = dir.path().join("agent");+ let cwd = dir.path().join("project");+ std::fs::create_dir_all(&agent_dir).unwrap();+ std::fs::create_dir_all(cwd.join(".prime/agent")).unwrap();+ let engine = shell_test_session(cwd, agent_dir).await.unwrap();+ assert_eq!(+ engine+ .provisioner+ .inner+ .options+ .env+ .get("RLM_SESSION_ID")+ .map(String::as_str),+ Some(""),+ "an inherited RLM_SESSION_ID must not reach an unsaved session's kernel"+ );+ }+#[tokio::test]async fn without_a_websearch_skill_no_serper_key_env() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/pa-core/src/platform/process.rs b/crates/pa-core/src/platform/process.rsindex e632fe5a6a..b013a9cc69 100644--- a/crates/pa-core/src/platform/process.rs+++ b/crates/pa-core/src/platform/process.rs@@ -157,6 +157,59 @@ pub fn kill_pid(pid: i32, signal: Signal) -> bool {unsafe { libc::kill(pid, sig) == 0 }}+/// Whether a process group currently exists, without delivering a signal.+/// Existence alone never establishes ownership of a durable group's old id.+///+/// # Errors+/// Returns the native probe error when group existence cannot be established.+#[cfg(unix)]+pub fn process_group_exists(pgid: i32) -> std::io::Result<bool> {+ if pgid <= 1 {+ return Ok(false);+ }+ if unsafe { libc::kill(-pgid, 0) } == 0 {+ return Ok(true);+ }+ let error = std::io::Error::last_os_error();+ if error.raw_os_error() == Some(libc::ESRCH) {+ Ok(false)+ } else {+ Err(error)+ }+}++/// No process groups: none exists.+///+/// # Errors+///+/// Never: the not-unix arm has no group to probe.+#[cfg(not(unix))]+pub fn process_group_exists(_pgid: i32) -> std::io::Result<bool> {+ Ok(false)+}++/// Signal every member of process group `pgid` (`kill(-pgid, sig)`). Returns+/// true only when the signal was delivered to at least one member.+#[cfg(unix)]+#[must_use]+pub fn signal_process_group(pgid: i32, signal: Signal) -> bool {+ if pgid <= 1 {+ return false;+ }+ let sig = match signal {+ Signal::Term => libc::SIGTERM,+ Signal::Kill => libc::SIGKILL,+ };+ unsafe { libc::kill(-pgid, sig) == 0 }+}++#[cfg(not(unix))]+#[must_use]+pub fn signal_process_group(_pgid: i32, _signal: Signal) -> bool {+ // No process groups: persistent shells are POSIX-only.+ false+}+/// Windows: `OpenProcess(PROCESS_TERMINATE)` + `TerminateProcess` on the/// single pid (every signal terminates; the `Term`/`Kill` distinction/// collapses there). Descendants are NOT killed: teardown paths needingdiff --git a/crates/pa-core/src/prompts/layers/core.md b/crates/pa-core/src/prompts/layers/core.mdindex 6cee7a45eb..3ffd237ce3 100644--- a/crates/pa-core/src/prompts/layers/core.md+++ b/crates/pa-core/src/prompts/layers/core.md@@ -6,7 +6,8 @@ The harness often sends messages to the agent. These are user messages starting## Core tools-- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `python_repl` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls+- `bash(command: str, persistent: bool = False) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `python_repl` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls+ - `persistent=True` (POSIX, saved sessions only): the shell survives kernel, worker, and daemon restarts and its session's delete or archive (a deleted session's shells keep running as orphans); it ends only on its own exit or an explicit kill; use it only when really required (a server or long job that must outlive a restart), never for ordinary commands; after a restart, get the handles back with `from rlm import persistent_shells; persistent_shells()` (a shell that finished while no kernel ran is listed once, finished); completion of a re-attached shell is polled, so its result and notification lag by about a second- `BashHandle`:- `.pid: int`- `.running: bool`diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rsindex b5c2ac0b14..25757a785b 100644--- a/crates/pa-core/src/session_engine/runtime_wiring.rs+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs@@ -236,7 +236,9 @@ pub fn kernel_python_skills(skills: &[Skill]) -> Vec<KernelPythonSkill> {/// (`PRIME_AGENT_CODING_AGENT_DIR`): an embedding host whose ambient env differs must not/// leak its own paths into the kernel (#109). A persistent session's artifact dir is/// likewise propagated (`RLM_SESSION_DIR` + `RLM_HARNESS_STATE_DIR`), so kernel-side-/// harness writes land in the session-local store. `cwd` is the SESSION's working directory.+/// harness writes land in the session-local store. The artifact dir is keyed by the+/// durable session id (the session file's stem), exported as `RLM_SESSION_ID` for the+/// persistent `bash()` shells' assignment. `cwd` is the SESSION's working directory./// `shell_path` is the session-start-resolved kernel shell: an invalid `shellPath` fails/// `create_session`, not the kernel boot.#[allow(clippy::too_many_arguments)] // one wiring funnel, same style as AgentSession::from_session_arc@@ -261,6 +263,14 @@ pub fn kernel_provisioner("PRIME_AGENT_CODING_AGENT_DIR".to_string(),agent_dir.to_string_lossy().to_string(),);+ // Always set: an unsaved session blanks an inherited id (a run started inside another+ // session's kernel), so its persistent shells never join that session.+ let rlm_session_id = session_artifact_dir+ .as_deref()+ .and_then(std::path::Path::file_name)+ .map(|id| id.to_string_lossy().to_string())+ .unwrap_or_default();+ env.insert("RLM_SESSION_ID".to_string(), rlm_session_id);for (key, value) in [("RLM_SESSION_DIR", session_artifact_dir.clone()),(diff --git a/crates/pa-daemon/src/lib.rs b/crates/pa-daemon/src/lib.rsindex 5775d7c8af..f3403019ff 100644--- a/crates/pa-daemon/src/lib.rs+++ b/crates/pa-daemon/src/lib.rs@@ -67,6 +67,7 @@ pub mod paths;pub(crate) mod peer;pub(crate) mod peer_client;pub(crate) mod peer_tickets;+pub(crate) mod persistent_shells;pub mod platform;pub mod prompt_admission;pub mod protocol;diff --git a/crates/pa-daemon/src/persistent_shells.rs b/crates/pa-daemon/src/persistent_shells.rsnew file mode 100644index 0000000000..89d696915d--- /dev/null+++ b/crates/pa-daemon/src/persistent_shells.rs@@ -0,0 +1,521 @@+//! The kernel's persistent `bash()` shells (prime-agent-runtime `rlm/bash.py`,+//! `bash(..., persistent=True)`): every session's shells live in one home,+//! `<agent dir>/persistent-shells/`, as a `<id>.json` record assigned to the+//! session that started it, plus the shell's `<id>.out` and `<id>.rc`. The+//! daemon reads the records to list each saved session's live shells and every+//! shell machine-wide, reads a shell's output, and kills one on request.+//! Nothing in the session lifecycle kills them: a deleted session's shells keep+//! running as orphans, still assigned to it.++use std::collections::HashMap;+use std::io::{Read, Seek, SeekFrom};+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant, UNIX_EPOCH};++use pa_core::platform::process::{process_group_exists, signal_process_group, Signal};+use serde::Deserialize;+use serde_json::{json, Value};++use crate::protocol::{response_failure, response_line, response_success};++const HOME_DIR: &str = "persistent-shells";+/// How long a shell may exit on its own after SIGTERM before its group gets SIGKILL.+const TERM_GRACE: Duration = Duration::from_secs(2);+/// The kernel activity rows cap the command at the same length.+const COMMAND_CAP: usize = 512;+/// The output read serves its lines from at most this many trailing bytes.+const TAIL_BYTES: u64 = 64 * 1024;++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct Shell {+ id: String,+ pid: u32,+ start_id: String,+ command: String,+ started_at: String,+ session_id: String,+}++fn shell_file(agent_dir: &Path, id: &str, kind: &str) -> PathBuf {+ agent_dir.join(HOME_DIR).join(format!("{id}.{kind}"))+}++fn registered_shells(agent_dir: &Path) -> Vec<Shell> {+ let Ok(entries) = std::fs::read_dir(agent_dir.join(HOME_DIR)) else {+ return Vec::new();+ };+ let mut shells: Vec<Shell> = entries+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.extension().is_some_and(|ext| ext == "json"))+ .filter_map(|path| std::fs::read(path).ok())+ .filter_map(|raw| serde_json::from_slice(&raw).ok())+ .collect();+ shells.sort_by(|a, b| a.started_at.cmp(&b.started_at));+ shells+}++fn find_shell(agent_dir: &Path, id: &str) -> Option<Shell> {+ registered_shells(agent_dir)+ .into_iter()+ .find(|shell| shell.id == id)+}++/// Whether the shell's pid still runs under the recorded start identity.+fn runs_as_registered(shell: &Shell) -> bool {+ matches!(crate::lease::is_process_alive(shell.pid), Ok(true))+ && crate::lease::get_process_start_id(shell.pid).as_deref() == Some(shell.start_id.as_str())+}++/// An extant group with no verified leader is not safely attributable to this record.+fn group_unverified(shell: &Shell) -> bool {+ !runs_as_registered(shell) && process_group_exists(shell.pid as i32).unwrap_or(true)+}++/// One shell as a row with the kernel bash activity row field names.+fn activity_row(shell: &Shell, status: &str) -> Value {+ json!({+ "id": shell.id,+ "command": shell.command.chars().take(COMMAND_CAP).collect::<String>(),+ "pid": shell.pid,+ "startedAt": shell.started_at,+ "status": status,+ "persistent": true,+ })+}++/// The live persistent shells by assigned session id: a recycled pid or an+/// unreadable identity never counts as live.+pub(crate) fn live_shell_rows_by_session(agent_dir: &Path) -> HashMap<String, Vec<Value>> {+ let mut rows: HashMap<String, Vec<Value>> = HashMap::new();+ for shell in registered_shells(agent_dir)+ .into_iter()+ .filter(runs_as_registered)+ {+ let row = activity_row(&shell, "running");+ rows.entry(shell.session_id).or_default().push(row);+ }+ rows+}++/// Every registered shell with its assigned `sessionId`: running while its+/// leader runs as registered, unverified when a group remains without that+/// proof, otherwise finished with its recorded exit code (if any). Its+/// `durationMs` runs from `startedAt` to now, or to the exit code's write+/// once finished.+pub(crate) fn shell_rows(agent_dir: &Path) -> Vec<Value> {+ registered_shells(agent_dir)+ .iter()+ .map(|shell| {+ let running = runs_as_registered(shell);+ let status = if running {+ "running"+ } else if group_unverified(shell) {+ "unverified"+ } else {+ "finished"+ };+ let mut row = activity_row(shell, status);+ row["sessionId"] = json!(shell.session_id);+ let rc = shell_file(agent_dir, &shell.id, "rc");+ let ended_ms = if status == "finished" {+ row["exitCode"] = json!(std::fs::read_to_string(&rc)+ .ok()+ .and_then(|rc| rc.trim().parse::<i64>().ok()));+ std::fs::metadata(&rc)+ .and_then(|metadata| metadata.modified())+ .ok()+ .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())+ .and_then(|since| u64::try_from(since.as_millis()).ok())+ } else {+ Some(crate::util::now_ms())+ };+ row["durationMs"] = json!(crate::util::iso_to_unix_ms(&shell.started_at)+ .zip(ended_ms)+ .map(|(started, ended)| ended.saturating_sub(started)));+ row+ })+ .collect()+}++/// The newest `lines` lines of the shell's output (read from its last+/// [`TAIL_BYTES`]); `None` for an unknown shell. The kernel creates the `.out`+/// before it writes the record, so a failed read is an error, never an empty tail.+pub(crate) fn output_tail(+ agent_dir: &Path,+ id: &str,+ lines: usize,+) -> Result<Option<String>, String> {+ let Some(shell) = find_shell(agent_dir, id) else {+ return Ok(None);+ };+ let bytes = read_tail(&shell_file(agent_dir, &shell.id, "out"))+ .map_err(|error| format!("Could not read persistent shell output: {error}"))?;+ let text = String::from_utf8_lossy(&bytes);+ let all: Vec<&str> = text.lines().collect();+ Ok(Some(all[all.len().saturating_sub(lines)..].join("\n")))+}++fn read_tail(path: &Path) -> std::io::Result<Vec<u8>> {+ let mut file = std::fs::File::open(path)?;+ let size = file.metadata()?.len();+ file.seek(SeekFrom::Start(size.saturating_sub(TAIL_BYTES)))?;+ let mut bytes = Vec::new();+ file.take(TAIL_BYTES).read_to_end(&mut bytes)?;+ Ok(bytes)+}++/// Kill a shell only while the recorded leader identity still proves ownership.+/// A durable leaderless group may belong to a reused PGID: refuse and retain it.+pub(crate) fn kill_shell(agent_dir: &Path, id: &str) -> Result<bool, String> {+ let Some(shell) = find_shell(agent_dir, id) else {+ return Ok(false);+ };+ if !runs_as_registered(&shell) {+ return if group_unverified(&shell) {+ Err("Cannot verify persistent shell group ownership; no signal sent".to_string())+ } else {+ Ok(true)+ };+ }+ if !signal_process_group(shell.pid as i32, Signal::Term) {+ return Err("Could not signal persistent shell group".to_string());+ }+ // The grace belongs to the whole group: a leader that exits on TERM must not cut short+ // its members' own TERM handling.+ let deadline = Instant::now() + TERM_GRACE;+ while Instant::now() < deadline {+ if !process_group_exists(shell.pid as i32).unwrap_or(true) {+ return Ok(true);+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ kill_group(&shell)?;+ Ok(true)+}++/// The KILL after a verified TERM. A leader that exited during the grace still names the group+/// verified before the TERM: a PGID is not reused while its group has members. A leader pid+/// that runs again under another start identity was recycled, so its group is refused.+fn kill_group(shell: &Shell) -> Result<(), String> {+ let leader_exited = matches!(crate::lease::is_process_alive(shell.pid), Ok(false));+ if !runs_as_registered(shell) && !leader_exited {+ return if group_unverified(shell) {+ Err(+ "Cannot verify persistent shell group ownership; no further signal sent"+ .to_string(),+ )+ } else {+ Ok(())+ };+ }+ if signal_process_group(shell.pid as i32, Signal::Kill)+ || !process_group_exists(shell.pid as i32).unwrap_or(true)+ {+ Ok(())+ } else {+ Err("Could not signal persistent shell group".to_string())+ }+}++/// One persistent-shell supervisor arm, run off the runtime (file reads and+/// the kill's grace block): `None` answers an unknown shell.+pub(crate) async fn respond(+ command_id: &str,+ type_name: &str,+ run: impl FnOnce() -> Result<Option<Value>, String> + Send + 'static,+) -> Value {+ let response = match tokio::task::spawn_blocking(run).await {+ Ok(Ok(Some(data))) => response_success(Some(command_id), type_name, Some(data)),+ Ok(Ok(None)) => response_failure(+ Some(command_id),+ type_name,+ "Unknown persistent shell",+ None,+ ),+ Ok(Err(error)) => response_failure(Some(command_id), type_name, &error, None),+ Err(error) => response_failure(Some(command_id), type_name, &error.to_string(), None),+ };+ response_line(&response)+}++#[cfg(all(test, unix))]+mod test_support {+ use std::path::Path;+ use std::process::{Child, Command};++ /// A setsid'd `sleep` registered in `agent_dir`'s persistent-shell home,+ /// assigned to `session_id`, under `start_id` (`None`: its real start identity).+ pub(super) fn registered_sleeper(+ agent_dir: &Path,+ session_id: &str,+ start_id: Option<&str>,+ ) -> Child {+ let mut command = Command::new("sleep");+ command.arg("60");+ pa_core::platform::process::set_new_session(&mut command);+ let child = command.spawn().expect("spawn sleeper");+ let start_id = start_id.map_or_else(+ || crate::lease::get_process_start_id(child.id()).expect("start id"),+ str::to_string,+ );+ register(agent_dir, child.id(), &start_id, session_id);+ child+ }++ /// Write one record for shell `pid` under `start_id`, assigned to+ /// `session_id`; returns its id.+ pub(super) fn register(agent_dir: &Path, pid: u32, start_id: &str, session_id: &str) -> String {+ let home = agent_dir.join(super::HOME_DIR);+ std::fs::create_dir_all(&home).expect("persistent-shell home");+ let id = format!("{pid:032}");+ let record = serde_json::json!({+ "id": id,+ "pid": pid,+ "startId": start_id,+ "command": "sleep 60",+ "startedAt": "2026-01-01T00:00:00+00:00",+ "sessionId": session_id,+ });+ std::fs::write(home.join(format!("{id}.json")), record.to_string()).expect("write record");+ id+ }+}++#[cfg(all(test, unix))]+mod tests {+ use std::os::unix::process::{CommandExt, ExitStatusExt};+ use std::process::{Child, Command};++ use nix::sys::signal::{kill, Signal as NixSignal};+ use nix::unistd::Pid;++ use super::test_support::{register, registered_sleeper};+ use super::*;++ /// Send `child` our own SIGTERM and return the signal it died by: an+ /// earlier SIGKILL is already pending and wins.+ fn fatal_signal_after_own_term(mut child: Child) -> Option<i32> {+ let _ = kill(Pid::from_raw(child.id() as i32), NixSignal::SIGTERM);+ child.wait().unwrap().signal()+ }++ /// A registered `sleep` leading its own process group, plus one member in+ /// that group.+ fn registered_group(agent_dir: &std::path::Path) -> (Child, Child, String) {+ let mut leader_command = Command::new("sleep");+ leader_command.arg("60");+ pa_core::platform::process::set_new_process_group(&mut leader_command);+ let leader = leader_command.spawn().unwrap();+ let start_id = crate::lease::get_process_start_id(leader.id()).unwrap();+ let id = register(agent_dir, leader.id(), &start_id, "s1");+ let member = Command::new("sleep")+ .arg("60")+ .process_group(leader.id() as i32)+ .spawn()+ .unwrap();+ (leader, member, id)+ }++ #[test]+ fn recycled_pid_is_neither_reported_nor_killed() {+ let root = tempfile::tempdir().unwrap();+ let stranger = registered_sleeper(root.path(), "s1", Some("proc:not-this-process"));+ let id = format!("{:032}", stranger.id());++ assert!(live_shell_rows_by_session(root.path()).is_empty());+ assert_eq!(shell_rows(root.path())[0]["status"], "unverified");+ assert!(kill_shell(root.path(), &id).is_err());++ assert_eq!(+ fatal_signal_after_own_term(stranger),+ Some(NixSignal::SIGTERM as i32),+ "never signalled"+ );+ }++ #[test]+ fn kill_stops_the_whole_group_and_leaves_the_shell_listed_as_finished() {+ let root = tempfile::tempdir().unwrap();+ let (mut leader, member, id) = registered_group(root.path());+ std::fs::write(shell_file(root.path(), &id, "out"), "line\n").unwrap();++ let _outcome = kill_shell(root.path(), &id);++ assert!(!leader.wait().unwrap().success(), "the leader was killed");+ let member_status = member.wait_with_output().unwrap().status;+ assert_eq!(+ member_status.signal(),+ Some(NixSignal::SIGTERM as i32),+ "the group's TERM reached the member"+ );+ assert_eq!(shell_rows(root.path())[0]["status"], "finished");+ assert_eq!(+ output_tail(root.path(), &id, 1),+ Ok(Some("line".to_string()))+ );+ assert_eq!(kill_shell(root.path(), "unknown"), Ok(false));+ }++ #[test]+ fn kill_escalates_to_a_member_that_outlives_its_leaders_term() {+ use std::io::BufRead;+ let root = tempfile::tempdir().unwrap();+ let (mut leader, member, id) = registered_group(root.path());+ let mut stubborn = Command::new("sh")+ .args(["-c", "trap '' TERM; echo ready; exec sleep 60"])+ .process_group(leader.id() as i32)+ .stdout(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ let mut ready = String::new();+ std::io::BufReader::new(stubborn.stdout.take().unwrap())+ .read_line(&mut ready)+ .unwrap();++ assert_eq!(kill_shell(root.path(), &id), Ok(true));++ leader.wait().unwrap();+ member.wait_with_output().unwrap();+ assert_eq!(+ stubborn.wait().unwrap().signal(),+ Some(NixSignal::SIGKILL as i32),+ "the member that ignored TERM got the group's KILL"+ );+ }++ #[test]+ fn a_leader_exiting_on_term_leaves_its_members_the_full_grace() {+ use std::io::BufRead;+ let root = tempfile::tempdir().unwrap();+ let marker = root.path().join("cleaned-up");+ let (leader, member, id) = registered_group(root.path());+ let mut cleanup = Command::new("sh")+ .args([+ "-c",+ "trap 'sleep 1; touch \"$0\"; exit 0' TERM; echo ready; while :; do sleep 0.05; done",+ ])+ .arg(&marker)+ .process_group(leader.id() as i32)+ .stdout(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ let mut ready = String::new();+ std::io::BufReader::new(cleanup.stdout.take().unwrap())+ .read_line(&mut ready)+ .unwrap();+ // Reaped as the kernel reaps them: only live members keep the group.+ let reapers: Vec<_> = [leader, member, cleanup]+ .into_iter()+ .map(|mut child| std::thread::spawn(move || child.wait().unwrap()))+ .collect();++ assert_eq!(kill_shell(root.path(), &id), Ok(true));++ let statuses: Vec<_> = reapers.into_iter().map(|r| r.join().unwrap()).collect();+ assert!(+ marker.exists() && statuses[2].success(),+ "the member finished its TERM cleanup after the leader exited: {statuses:?}"+ );+ }++ #[test]+ fn exited_leaders_group_is_unverified_and_never_signalled() {+ let root = tempfile::tempdir().unwrap();+ let (mut leader, member, id) = registered_group(root.path());+ leader.kill().unwrap();+ leader.wait().unwrap();+ // The same observable state also describes an unrelated group after+ // durable PID/PGID reuse. No old leader start-id can distinguish them.+ let record = shell_file(root.path(), &id, "json");+ let mut stale: Value = serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();+ stale["startId"] = json!("proc:old-unrelated-leader");+ std::fs::write(&record, stale.to_string()).unwrap();++ assert_eq!(shell_rows(root.path())[0]["status"], "unverified");+ assert!(kill_shell(root.path(), &id).is_err());+ assert!(record.exists());+ assert_eq!(+ fatal_signal_after_own_term(member),+ Some(NixSignal::SIGTERM as i32),+ "no earlier KILL reached the unverified group"+ );+ }++ #[test]+ fn pid_recycled_during_the_grace_is_not_killed() {+ let root = tempfile::tempdir().unwrap();+ let mut stranger = registered_sleeper(root.path(), "s1", Some("proc:not-this-process"));+ let shells = registered_shells(root.path());++ assert!(kill_group(&shells[0]).is_err());+ assert!(signal_process_group(stranger.id() as i32, Signal::Term));++ let status = stranger.wait().unwrap();+ assert_eq!(+ status.signal(),+ Some(NixSignal::SIGTERM as i32),+ "no SIGKILL came first"+ );+ }++ #[test]+ fn shell_rows_list_every_shell_with_its_session_and_the_output_tail_reads_the_newest_lines() {+ let root = tempfile::tempdir().unwrap();+ let mut sleeper = registered_sleeper(root.path(), "s1", None);+ let mut done = Command::new("true").spawn().unwrap();+ done.wait().unwrap();+ let finished = register(root.path(), done.id(), "proc:0", "gone");+ std::fs::write(shell_file(root.path(), &finished, "rc"), "3\n").unwrap();+ std::fs::write(+ shell_file(root.path(), &finished, "out"),+ "one\ntwo\nthree\n",+ )+ .unwrap();++ let rows = shell_rows(root.path());++ let row = |id: &str| rows.iter().find(|row| row["id"] == id).unwrap().clone();+ let running = row(&format!("{:032}", sleeper.id()));+ assert_eq!(+ (+ &running["status"],+ &running["sessionId"],+ running.get("exitCode")+ ),+ (&json!("running"), &json!("s1"), None)+ );+ let done_row = row(&finished);+ assert_eq!(+ (+ &done_row["status"],+ &done_row["sessionId"],+ &done_row["exitCode"]+ ),+ (&json!("finished"), &json!("gone"), &json!(3))+ );+ assert!(running["durationMs"].is_u64() && done_row["durationMs"].is_u64());+ assert_eq!(+ output_tail(root.path(), &finished, 2),+ Ok(Some("two\nthree".to_string()))+ );+ assert_eq!(output_tail(root.path(), "unknown", 2), Ok(None));+ sleeper.kill().unwrap();+ sleeper.wait().unwrap();+ }++ #[test]+ fn an_unreadable_output_file_is_an_error_not_an_empty_tail() {+ let root = tempfile::tempdir().unwrap();+ let mut sleeper = registered_sleeper(root.path(), "s1", None);+ let id = format!("{:032}", sleeper.id());+ std::fs::create_dir(shell_file(root.path(), &id, "out")).unwrap();++ let tail = output_tail(root.path(), &id, 5);++ sleeper.kill().unwrap();+ sleeper.wait().unwrap();+ assert!(tail.is_err(), "{tail:?}");+ }+}diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rsindex a2c5a1c6af..17909b97c3 100644--- a/crates/pa-daemon/src/protocol.rs+++ b/crates/pa-daemon/src/protocol.rs@@ -165,6 +165,9 @@ pub const KNOWN_COMMAND_TYPES: &[&str] = &["set_mcp_static_token","remove_mcp_connection","mark_anthropic_warning_shown",+ "list_persistent_shells",+ "tail_persistent_shell",+ "kill_persistent_shell",];/// Parsed client command envelope.@@ -336,6 +339,7 @@ pub fn default_server_capabilities() -> Vec<DaemonServerCapability> {"side_question_transcript","transient_bash","kernel_bash_activity",+ "persistent_shells","factory_activity","session_input_admission","prompt_admission_cancellation",@@ -926,6 +930,9 @@ pub fn command_active_session_id(command: &DaemonCommand) -> Option<&str> {| DaemonCommand::PrepareUpdateRestart { .. }| DaemonCommand::CommitUpdateRestart { .. }| DaemonCommand::UpdateRestoreStatus { .. }+ | DaemonCommand::ListPersistentShells { .. }+ | DaemonCommand::TailPersistentShell { .. }+ | DaemonCommand::KillPersistentShell { .. }| DaemonCommand::Restart { .. }| DaemonCommand::Shutdown { .. } => None,}@@ -974,6 +981,9 @@ pub fn command_type_name(command: &DaemonCommand) -> &'static str {DaemonCommand::ListKernelBash { .. } => "list_kernel_bash",DaemonCommand::TailKernelBash { .. } => "tail_kernel_bash",DaemonCommand::KillKernelBash { .. } => "kill_kernel_bash",+ DaemonCommand::ListPersistentShells { .. } => "list_persistent_shells",+ DaemonCommand::TailPersistentShell { .. } => "tail_persistent_shell",+ DaemonCommand::KillPersistentShell { .. } => "kill_persistent_shell",DaemonCommand::CancelRlmChild { .. } => "cancel_rlm_child",DaemonCommand::FactoryActivity { .. } => "factory_activity",DaemonCommand::DeleteRlmSubagent { .. } => "delete_rlm_subagent",diff --git a/crates/pa-daemon/src/supervisor/clients.rs b/crates/pa-daemon/src/supervisor/clients.rsindex b908214bd1..eb88e96f81 100644--- a/crates/pa-daemon/src/supervisor/clients.rs+++ b/crates/pa-daemon/src/supervisor/clients.rs@@ -825,6 +825,39 @@ impl Supervisor {false,)}+ DaemonCommand::ListPersistentShells { .. } => {+ // The machine-wide persistent shells, each with its assigned session id.+ let agent_dir = self.options.agent_dir.clone();+ let line = crate::persistent_shells::respond(&command_id, &type_name, move || {+ Ok(Some(+ json!({ "activities": crate::persistent_shells::shell_rows(&agent_dir) }),+ ))+ })+ .await;+ (vec![line], false)+ }+ DaemonCommand::TailPersistentShell {+ shell_id, lines, ..+ } => {+ let agent_dir = self.options.agent_dir.clone();+ let (shell_id, lines) = (shell_id.clone(), *lines as usize);+ let line = crate::persistent_shells::respond(&command_id, &type_name, move || {+ crate::persistent_shells::output_tail(&agent_dir, &shell_id, lines)+ .map(|tail| tail.map(|tail| json!({ "shellId": shell_id, "tail": tail })))+ })+ .await;+ (vec![line], false)+ }+ DaemonCommand::KillPersistentShell { shell_id, .. } => {+ let agent_dir = self.options.agent_dir.clone();+ let shell_id = shell_id.clone();+ let line = crate::persistent_shells::respond(&command_id, &type_name, move || {+ crate::persistent_shells::kill_shell(&agent_dir, &shell_id)+ .map(|known| known.then(|| json!({ "shellId": shell_id })))+ })+ .await;+ (vec![line], false)+ }DaemonCommand::Prompt {active_session_id, ..}diff --git a/crates/pa-daemon/src/supervisor/sessions.rs b/crates/pa-daemon/src/supervisor/sessions.rsindex bf9512d390..d5dc4e8f88 100644--- a/crates/pa-daemon/src/supervisor/sessions.rs+++ b/crates/pa-daemon/src/supervisor/sessions.rs@@ -213,9 +213,12 @@ impl Supervisor {let scan_command_id = command_id.to_string();let scan_active_session_id = active_session_id.clone();let scan_cwd = cwd.clone();+ let agent_dir = self.options.agent_dir.clone();let cursor = cursor.clone();let limit = limit.map(|limit| limit as usize);let scan = tokio::task::spawn_blocking(move || {+ let persistent_shells =+ crate::persistent_shells::live_shell_rows_by_session(&agent_dir);let mut file_total = 0usize;let page = list_sessions_with(&dir, cursor.as_deref(), limit, |index, total, info| {file_total = total;@@ -223,7 +226,7 @@ impl Supervisor {// The row is out of scope, but the scan itself goes on.return true;}- let row = saved_session_row(info);+ let row = saved_session_row(info, &persistent_shells);let mut item = json!({"id": scan_command_id,"type": "session_list_item",@@ -262,9 +265,9 @@ impl Supervisor {}}});- (page, file_total)+ (page, file_total, persistent_shells)});- let (page, file_total) = match scan.await {+ let (page, file_total, persistent_shells) = match scan.await {Ok(scanned) => scanned,Err(error) => {return vec![response_line(&response_failure(@@ -335,7 +338,7 @@ impl Supervisor {.filter(|info| !scope_current || info.cwd == cwd).collect();for info in &merged {- let row = saved_session_row(info);+ let row = saved_session_row(info, &persistent_shells);let mut item = json!({"id": command_id,"type": "session_list_item",@@ -384,7 +387,10 @@ impl Supervisor {// The streamed rows already reached the client; the terminal response is// the authoritative array (the scan never re-orders after streaming).let mut lines = Vec::new();- let sessions: Vec<Value> = infos.iter().map(saved_session_row).collect();+ let sessions: Vec<Value> = infos+ .iter()+ .map(|info| saved_session_row(info, &persistent_shells))+ .collect();let mut data = json!({ "sessions": sessions, "remaining": remaining });if let Some(next_cursor) = next_cursor {data["nextCursor"] = json!(next_cursor);@@ -831,7 +837,10 @@ fn offline_summary(worker_id: &str) -> Value {})}-pub(super) fn saved_session_row(info: &crate::session_store::SessionInfo) -> Value {+pub(super) fn saved_session_row(+ info: &crate::session_store::SessionInfo,+ persistent_shells: &std::collections::HashMap<String, Vec<Value>>,+) -> Value {let mut row = json!({"path": info.path.to_string_lossy(),"id": info.id,@@ -873,6 +882,11 @@ pub(super) fn saved_session_row(info: &crate::session_store::SessionInfo) -> Valif let Some(level) = &info.thinking_level {object.insert("thinkingLevel".to_string(), json!(level));}+ // Persistent `bash()` shells outlive the session's kernel: an inactive row still+ // shows the live ones (kernel activity row shape).+ if let Some(shells) = persistent_shells.get(&info.id) {+ object.insert("persistentShells".to_string(), json!(shells));+ }row}diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rsindex b9111c41a1..f3f5438aa8 100644--- a/crates/pa-daemon/src/supervisor/tests.rs+++ b/crates/pa-daemon/src/supervisor/tests.rs@@ -823,14 +823,14 @@ fn saved_session_rows_publish_deleted_descendant_usage() {output_tokens: 110,cost: 0.5,});- let row = saved_session_row(&info);+ let row = saved_session_row(&info, &std::collections::HashMap::new());assert_eq!(row["deletedDescendantUsage"],json!({ "inputTokens": 1_100, "outputTokens": 110, "cost": 0.5 }));// Absent again: the field never rides as a null.info.deleted_descendant_usage = None;- let row = saved_session_row(&info);+ let row = saved_session_row(&info, &std::collections::HashMap::new());assert!(row.get("deletedDescendantUsage").is_none());}@@ -850,7 +850,7 @@ fn saved_session_rows_carry_the_persisted_thinking_level() {let summary = saved_session_summary(&info);assert_eq!(summary["thinkingLevel"], json!("high"));assert!(summary["model"].is_null(), "saved rows carry no model");- let row = saved_session_row(&info);+ let row = saved_session_row(&info, &std::collections::HashMap::new());assert_eq!(row["thinkingLevel"], json!("high"));assert_eq!(row["model"], json!({ "provider": "p", "modelId": "m" }));// A session file without a persisted level stays bare (a fresh@@ -864,9 +864,11 @@ fn saved_session_rows_carry_the_persisted_thinking_level() {assert!(saved_session_summary(&draft_info).get("thinkingLevel").is_none());- assert!(saved_session_row(&draft_info)- .get("thinkingLevel")- .is_none());+ assert!(+ saved_session_row(&draft_info, &std::collections::HashMap::new())+ .get("thinkingLevel")+ .is_none()+ );let _ = std::fs::remove_dir_all(&dir);}@@ -889,7 +891,7 @@ fn saved_session_rows_publish_the_own_usage_summary() {}));session.rewrite().unwrap();let info = crate::session_store::read_session_info(&path).unwrap();- let row = saved_session_row(&info);+ let row = saved_session_row(&info, &std::collections::HashMap::new());assert_eq!(row["usage"],json!({ "inputTokens": 105, "outputTokens": 10, "cost": 0.25 })@@ -905,7 +907,11 @@ fn saved_session_rows_publish_the_own_usage_summary() {draft.set_path(draft_path.clone());draft.rewrite().unwrap();let draft_info = crate::session_store::read_session_info(&draft_path).unwrap();- assert!(saved_session_row(&draft_info).get("usage").is_none());+ assert!(+ saved_session_row(&draft_info, &std::collections::HashMap::new())+ .get("usage")+ .is_none()+ );assert!(saved_session_summary(&draft_info).get("usage").is_none());let _ = std::fs::remove_dir_all(&dir);}@@ -949,7 +955,7 @@ fn saved_session_rows_match_the_catalog_row_golden() {let info = crate::session_store::read_session_info(&path).unwrap();assert_eq!(- saved_session_row(&info),+ saved_session_row(&info, &std::collections::HashMap::new()),json!({"path": path.to_string_lossy(),"id": "golden-session",diff --git a/crates/pa-daemon/tests/command_breadth.rs b/crates/pa-daemon/tests/command_breadth.rsindex 9befd7a1c5..e3ebaf05f5 100644--- a/crates/pa-daemon/tests/command_breadth.rs+++ b/crates/pa-daemon/tests/command_breadth.rs@@ -520,6 +520,18 @@ const WIRE_FIXTURES: &[(&str, &str)] = &["mark_anthropic_warning_shown",r#"{"type": "mark_anthropic_warning_shown", "activeSessionId": "sess"}"#,),+ (+ "list_persistent_shells",+ r#"{"type": "list_persistent_shells"}"#,+ ),+ (+ "tail_persistent_shell",+ r#"{"type": "tail_persistent_shell", "shellId": "s", "lines": 50}"#,+ ),+ (+ "kill_persistent_shell",+ r#"{"type": "kill_persistent_shell", "shellId": "s"}"#,+ ),];/// The accept list is the TS list, in TS order, then the Rust-native supervisor/worker frames.@@ -548,6 +560,9 @@ fn known_command_types_match_the_ts_list() {| "tail_kernel_bash"| "kill_kernel_bash"| "mark_anthropic_warning_shown"+ | "list_persistent_shells"+ | "tail_persistent_shell"+ | "kill_persistent_shell"),"unexpected non-TS command type: {extra}");diff --git a/crates/pa-daemon/tests/persistent_shells_e2e.rs b/crates/pa-daemon/tests/persistent_shells_e2e.rsnew file mode 100644index 0000000000..1f2a097f88--- /dev/null+++ b/crates/pa-daemon/tests/persistent_shells_e2e.rs@@ -0,0 +1,477 @@+//! Persistent `bash()` shells across the daemon: a shell started with+//! `bash(..., persistent=True)` survives the daemon's shutdown (it is neither+//! journaled for the orphan reaper nor killed by the kernel's exit hook), shows+//! on the INACTIVE session's saved-catalog row, is re-attached by the kernel of+//! the reopened session, and keeps running after the session's delete, its+//! record still assigned to the deleted session. The machine-wide+//! `list_persistent_shells` lists every shell with its assignment, and+//! `kill_persistent_shell` ends an orphan. The live-kernel test skips (with a+//! note) without a kernel install.+#![cfg(target_os = "linux")]+// Narrowing casts sit at OS boundaries (pid) where the kernel bounds the values.+#![allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]+// Style gate only, not correctness: the live test is one long scenario.+#![allow(clippy::too_many_lines)]++use std::io::{BufRead, BufReader, Write};+use std::os::unix::net::UnixStream;+use std::os::unix::process::CommandExt;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};++use nix::sys::signal::{killpg, Signal};+use nix::unistd::Pid;+use serde_json::{json, Value};++fn kernel_python() -> Option<PathBuf> {+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {+ return Some(PathBuf::from(explicit));+ }+ let candidate = PathBuf::from(std::env::var("HOME").unwrap_or_default())+ .join(".prime/agent/kernel-venv/bin/python");+ if candidate.exists() {+ return Some(candidate);+ }+ eprintln!(+ "kernel python {} not found; skipping live persistent-shell e2e",+ candidate.display()+ );+ None+}++struct Daemon {+ child: Child,+}++impl Drop for Daemon {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++/// Persistent shells outlive their session: never leak one.+struct GroupGuard(i32);++impl Drop for GroupGuard {+ fn drop(&mut self) {+ let _ = killpg(Pid::from_raw(self.0), Signal::SIGKILL);+ }+}++/// Whether any non-zombie process is in group `pgid` (an unreaped zombie still+/// answers `kill(-pgid, 0)`).+fn group_alive(pgid: i32) -> bool {+ std::fs::read_dir("/proc")+ .expect("read /proc")+ .flatten()+ .filter_map(|entry| std::fs::read_to_string(entry.path().join("stat")).ok())+ .any(|stat| {+ let fields: Vec<&str> = stat[stat.rfind(')').map_or(0, |at| at + 2)..]+ .split(' ')+ .collect();+ fields.first() != Some(&"Z") && fields.get(2) == Some(&pgid.to_string().as_str())+ })+}++// The returned Daemon's Drop kills and reaps the child.+#[allow(clippy::zombie_processes)]+fn spawn_supervisor(socket: &Path, agent_dir: &Path, kernel_python: Option<&Path>) -> Daemon {+ std::fs::create_dir_all(agent_dir).expect("agent dir");+ let mut command = Command::new(env!("CARGO_BIN_EXE_pa-daemon"));+ command+ .arg("supervisor")+ .arg("--socket")+ .arg(socket)+ .arg("--agent-dir")+ .arg(agent_dir)+ .env("PRIME_AGENT_CODING_AGENT_DIR", agent_dir)+ .env_remove("RLM_SESSION_DIR")+ .env_remove("RLM_HARNESS_STATE_DIR")+ .env(+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,+ "15000",+ )+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ if let Some(python) = kernel_python {+ command.env("PRIME_AGENT_KERNEL_PYTHON", python);+ }+ let child = command.spawn().expect("spawn pa-daemon supervisor");+ let deadline = Instant::now() + Duration::from_secs(15);+ while UnixStream::connect(socket).is_err() {+ assert!(Instant::now() < deadline, "supervisor socket never came up");+ std::thread::sleep(Duration::from_millis(20));+ }+ Daemon { child }+}++struct Client {+ reader: BufReader<UnixStream>,+ writer: UnixStream,+}++impl Client {+ fn connect(socket: &Path) -> Self {+ let stream = UnixStream::connect(socket).expect("connect supervisor");+ let writer = stream.try_clone().expect("clone socket");+ stream+ .set_read_timeout(Some(Duration::from_millis(100)))+ .expect("set timeout");+ let mut client = Client {+ reader: BufReader::new(stream),+ writer,+ };+ let _hello = client.read_line();+ client+ }++ fn request(&mut self, id: &str, command: &Value) -> Value {+ let mut line = json!({+ "type": "command",+ "id": id,+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "command": command,+ })+ .to_string();+ line.push('\n');+ self.writer.write_all(line.as_bytes()).expect("send");+ let deadline = Instant::now() + Duration::from_mins(4);+ loop {+ assert!(Instant::now() < deadline, "no response for id {id}");+ let reply = self.read_line();+ if reply.get("id").and_then(Value::as_str) == Some(id)+ && reply.get("type").and_then(Value::as_str) == Some("response")+ {+ assert_eq!(reply["success"], true, "{id} failed: {reply}");+ return reply;+ }+ }+ }++ fn read_line(&mut self) -> Value {+ let mut line = String::new();+ loop {+ match self.reader.read_line(&mut line) {+ Ok(0) => panic!("supervisor closed the connection"),+ Ok(_) if line.trim().is_empty() => line.clear(),+ Ok(_) => return serde_json::from_str(line.trim()).expect("parse line"),+ Err(_) => {}+ }+ }+ }+}++fn saved_row(client: &mut Client, id: &str, sessions_dir: &Path, session_id: &str) -> Value {+ let listed = client.request(+ id,+ &json!({ "type": "list_saved_sessions", "cwd": "/",+ "sessionDir": sessions_dir.to_string_lossy() }),+ );+ listed["data"]["sessions"]+ .as_array()+ .expect("sessions")+ .iter()+ .find(|row| row["id"] == session_id)+ .cloned()+ .expect("the session has a catalog row")+}++#[test]+fn persistent_python_unit_regressions() {+ let Some(python) = kernel_python() else {+ assert!(+ std::env::var_os("CI").is_none(),+ "CI must bootstrap the kernel interpreter before persistent-shell tests"+ );+ return;+ };+ let runtime = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../prime-agent-runtime");+ let output = Command::new(python)+ .current_dir(&runtime)+ .env("PYTHONPATH", runtime.join("src"))+ .args(["-m", "unittest", "test.test_bash.PersistentBashTest"])+ .output()+ .expect("run persistent-shell Python regressions");+ assert!(+ output.status.success(),+ "persistent-shell Python regressions failed:\n{}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+}++#[test]+fn saved_row_lists_its_live_shells_and_the_machine_wide_list_every_shell() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let sessions_dir = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ let session_id = "11111111-2222-3333-4444-555555555555";+ std::fs::write(+ sessions_dir.join(format!("{session_id}.jsonl")),+ format!(+ "{}\n",+ json!({ "type": "session", "version": 3, "id": session_id,+ "timestamp": "2026-01-01T00:00:00.000Z", "cwd": "/tmp" })+ ),+ )+ .expect("write session");+ let mut sleeper = Command::new("sleep")+ .arg("60")+ .process_group(0)+ .spawn()+ .expect("spawn sleeper");+ let _guard = GroupGuard(sleeper.id() as i32);+ let mut gone = Command::new("true").spawn().expect("spawn true");+ gone.wait().expect("reap true");+ let sleeper_start_id = pa_daemon::lease::get_process_start_id(sleeper.id()).expect("start id");+ let home = agent_dir.join("persistent-shells");+ std::fs::create_dir_all(&home).expect("persistent-shell home");+ for (id, pid, start_id, session) in [+ ("a", sleeper.id(), sleeper_start_id.as_str(), session_id),+ ("b", gone.id(), "proc:0", session_id),+ (+ "c",+ sleeper.id(),+ sleeper_start_id.as_str(),+ "another-session",+ ),+ ] {+ let id = id.repeat(32);+ std::fs::write(+ home.join(format!("{id}.json")),+ json!({ "id": id, "pid": pid, "startId": start_id, "command": "sleep 60",+ "startedAt": "2026-01-01T00:00:00+00:00", "sessionId": session })+ .to_string(),+ )+ .expect("write record");+ }++ let socket = dir.path().join("supervisor.sock");+ let _daemon = spawn_supervisor(&socket, &agent_dir, None);+ let mut client = Client::connect(&socket);+ let row = saved_row(&mut client, "l1", &sessions_dir, session_id);++ assert_eq!(+ row["persistentShells"],+ json!([{ "id": "a".repeat(32), "command": "sleep 60", "pid": sleeper.id(),+ "startedAt": "2026-01-01T00:00:00+00:00", "status": "running",+ "persistent": true }])+ );+ let listed = client.request("s1", &json!({ "type": "list_persistent_shells" }));+ let mut shells: Vec<String> = listed["data"]["activities"]+ .as_array()+ .expect("activities")+ .iter()+ .map(|row| format!("{} {} {}", row["id"], row["status"], row["sessionId"]))+ .collect();+ shells.sort();+ assert_eq!(+ shells,+ [+ format!("\"{}\" \"running\" \"{session_id}\"", "a".repeat(32)),+ format!("\"{}\" \"finished\" \"{session_id}\"", "b".repeat(32)),+ format!("\"{}\" \"running\" \"another-session\"", "c".repeat(32)),+ ],+ "the machine-wide list holds every shell with its assignment"+ );+ sleeper.kill().expect("kill sleeper");+ sleeper.wait().expect("reap sleeper");+}++#[test]+fn persistent_shell_survives_daemon_shutdown_is_reattached_and_outlives_session_delete() {+ let Some(kernel_python) = kernel_python() else {+ return;+ };+ let dir = tempfile::TempDir::new().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let sessions_dir = dir.path().join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ let receipt = dir.path().join("pid.txt");+ let script = write_faux_script(+ &dir.path().join("faux.json"),+ &format!(+ "h = bash('echo hi; sleep 600', persistent=True)\nopen({:?}, 'w').write(str(h.pid))\n",+ receipt.to_string_lossy()+ ),+ );++ let baseline = kernel_pids();+ let socket = dir.path().join("supervisor.sock");+ let mut daemon = spawn_supervisor(&socket, &agent_dir, Some(&kernel_python));+ let mut client = Client::connect(&socket);+ let created = client.request(+ "c1",+ &json!({ "type": "create", "config": {+ "cwd": dir.path().to_string_lossy(),+ "sessionDir": sessions_dir.to_string_lossy(),+ "script": script.to_string_lossy(),+ } }),+ );+ let session_id = created["data"]["sessionId"]+ .as_str()+ .expect("session id")+ .to_string();+ client.request(+ "p1",+ &json!({ "type": "prompt", "activeSessionId": session_id, "message": "start it" }),+ );+ client.request(+ "i1",+ &json!({ "type": "wait_for_idle", "activeSessionId": session_id }),+ );+ let pid: i32 = std::fs::read_to_string(&receipt)+ .expect("the cell wrote the shell pid")+ .parse()+ .expect("pid");+ let _guard = GroupGuard(pid);++ // Daemon stop: the workers dispose their kernels (exit hook + orphan reaper).+ client.request("sd", &json!({ "type": "shutdown" }));+ let deadline = Instant::now() + Duration::from_secs(90);+ while daemon.child.try_wait().expect("poll supervisor").is_none() {+ assert!(Instant::now() < deadline, "the supervisor never exited");+ std::thread::sleep(Duration::from_millis(100));+ }+ let deadline = Instant::now() + Duration::from_secs(90);+ while kernel_pids().iter().any(|pid| !baseline.contains(pid)) {+ assert!(+ Instant::now() < deadline,+ "the session kernel outlived shutdown"+ );+ std::thread::sleep(Duration::from_millis(100));+ }+ assert!(+ group_alive(pid),+ "the persistent shell died with the daemon"+ );++ // A fresh daemon lists the inactive session's shell.+ let socket = dir.path().join("supervisor-2.sock");+ let _daemon = spawn_supervisor(&socket, &agent_dir, Some(&kernel_python));+ let mut client = Client::connect(&socket);+ let row = saved_row(&mut client, "l1", &sessions_dir, &session_id);+ assert_eq!(row["persistentShells"][0]["pid"], pid);++ // Reopening the session boots a new kernel, which re-attaches the shell.+ let reattached = dir.path().join("reattached.json");+ let script = write_faux_script(+ &dir.path().join("faux-reopen.json"),+ &format!(+ "import json\nfrom rlm import persistent_shells\njson.dump([[h.pid, h.running, h.output()] for h in persistent_shells()], open({:?}, 'w'))\n",+ reattached.to_string_lossy()+ ),+ );+ let session_file = sessions_dir.join(format!("{session_id}.jsonl"));+ let reopened = client.request(+ "c2",+ &json!({ "type": "create", "sessionPath": session_file.to_string_lossy(), "config": {+ "cwd": dir.path().to_string_lossy(),+ "sessionDir": sessions_dir.to_string_lossy(),+ "script": script.to_string_lossy(),+ } }),+ );+ let active_id = reopened["data"]["activeSessionId"]+ .as_str()+ .or_else(|| reopened["data"]["id"].as_str())+ .expect("active session id")+ .to_string();+ client.request(+ "p2",+ &json!({ "type": "prompt", "activeSessionId": active_id, "message": "find it" }),+ );+ client.request(+ "i2",+ &json!({ "type": "wait_for_idle", "activeSessionId": active_id }),+ );+ let handles: Value = serde_json::from_str(+ &std::fs::read_to_string(&reattached).expect("the reopened kernel wrote its handles"),+ )+ .expect("parse handles");+ assert_eq!(handles, json!([[pid, true, "hi\n"]]));++ // Close the session, then delete it: the shell runs on as an orphan.+ client.request(+ "k1",+ &json!({ "type": "kill", "activeSessionId": active_id }),+ );+ client.request(+ "d1",+ &json!({ "type": "delete_saved_session", "sessionPath": session_file.to_string_lossy() }),+ );+ assert!(!session_file.exists());+ assert!(+ group_alive(pid),+ "the session delete killed its persistent shell"+ );+ let records: Vec<Value> = std::fs::read_dir(agent_dir.join("persistent-shells"))+ .expect("persistent-shell home")+ .flatten()+ .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json"))+ .map(|entry| {+ serde_json::from_slice(&std::fs::read(entry.path()).expect("read record"))+ .expect("parse record")+ })+ .collect();+ assert_eq!(records.len(), 1);+ assert_eq!(records[0]["pid"], pid);+ assert_eq!(records[0]["sessionId"], session_id.as_str());++ // The machine-wide list still names the deleted session; its kill ends the orphan.+ let listed = client.request("s1", &json!({ "type": "list_persistent_shells" }));+ let shell = &listed["data"]["activities"][0];+ assert_eq!(+ (&shell["pid"], &shell["sessionId"], &shell["status"]),+ (&json!(pid), &json!(session_id), &json!("running"))+ );+ client.request(+ "x1",+ &json!({ "type": "kill_persistent_shell", "shellId": shell["id"] }),+ );+ let deadline = Instant::now() + Duration::from_secs(10);+ while group_alive(pid) {+ assert!(+ Instant::now() < deadline,+ "the kill left the orphan's group alive"+ );+ std::thread::sleep(Duration::from_millis(50));+ }+ let listed = client.request("s2", &json!({ "type": "list_persistent_shells" }));+ assert_eq!(+ listed["data"]["activities"][0]["status"], "finished",+ "the killed orphan stays listed as finished"+ );+}++fn write_faux_script(path: &Path, cell: &str) -> PathBuf {+ std::fs::write(+ path,+ json!({ "engine": "faux", "responses": [+ { "content": [{ "type": "toolCall", "name": "python_repl",+ "arguments": { "code": cell } }] },+ { "text": "done" },+ ] })+ .to_string(),+ )+ .expect("write faux script");+ path.to_path_buf()+}++/// Every live `python -m rlm.repl` kernel pid on the box.+fn kernel_pids() -> Vec<u32> {+ std::fs::read_dir("/proc")+ .expect("read /proc")+ .flatten()+ .filter_map(|entry| {+ let pid = entry.file_name().to_string_lossy().parse::<u32>().ok()?;+ let cmdline = std::fs::read_to_string(entry.path().join("cmdline")).ok()?;+ let args: Vec<&str> = cmdline.split('\0').collect();+ args.windows(2)+ .any(|window| window == ["-m", "rlm.repl"])+ .then_some(pid)+ })+ .collect()+}diff --git a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rsindex e6fce4d8b4..e3782e0724 100644--- a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs+++ b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs@@ -51,6 +51,7 @@ fn supervisor_end_to_end_scripted_session_lifecycle() {"side_question_transcript","transient_bash","kernel_bash_activity",+ "persistent_shells","session_input_admission","prompt_admission_cancellation","owned_prompt_cancellation",diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rsindex 1ce7305ced..86fa8286b5 100644--- a/crates/pa-tui/src/agents_view.rs+++ b/crates/pa-tui/src/agents_view.rs@@ -15,6 +15,7 @@ use tokio::sync::mpsc;use crate::agents_view_forest::{ancestor_session_ids, build_rows, compute_rollups, has_session_children, resolve_selection,scope_ancestors, scope_root, scope_to_subtree, AgentsViewRow, RowKind, ScopeRoot, SelectionKey,+ SessionActivity,};use crate::agents_view_state::truncate_text;use crate::agents_view_state::{@@ -27,7 +28,7 @@ use crate::agents_view_state::{pub use crate::agents_view_forest::AgentsViewScope;pub use crate::agents_view_forest::SelectionKey as AgentsViewSelectionKey;use crate::daemon_client::{DaemonClient, DaemonClientEvent};-use crate::interactive::SessionSelection;+use crate::interactive::{SessionPanel, SessionSelection};use crate::theme::{Theme, ThemeColor};use crate::width::{pad_line, str_width};use crate::Line;@@ -42,6 +43,8 @@ use render::Renderer;mod delete;mod heartbeats;+mod persistent_shells;+mod session_activity;#[cfg(test)]use delete::no_effect_summary;@@ -109,6 +112,8 @@ pub struct OpenedRow {/// The opened session's own directory (the roster summary's `cwd`): the session run rides it/// as its cwd, not the view's launch directory.pub cwd: Option<String>,+ /// The panel the opened session mounts (an activity line's or a persistent shell row's open).+ pub panel: Option<SessionPanel>,}pub enum AgentsViewUiMode {@@ -170,6 +175,8 @@ pub struct AgentsViewOutcome {pub opened_cwd: Option<std::path::PathBuf>,/// A status message the session opener left (the unattachable-child fallback).pub status_message: Option<String>,+ /// The panel the opened session mounts (an activity line's or a persistent shell row's open).+ pub panel: Option<SessionPanel>,/// The view actions this run performed (`program_shown`, `renamed`): the composition root/// emits the `tui agents action` adoption events at the run's end.pub actions: Vec<&'static str>,@@ -279,6 +286,21 @@ enum UiInput {generation: u64,heartbeats: Vec<crate::heartbeats_picker::HeartbeatEntry>,},+ /// A `list_persistent_shells` fetch landed (`None`: it failed, the last list stays).+ PersistentShellsLoaded(Option<Value>),+ /// The open bash view's output tail for shell `id`, stamped with its open's generation.+ PersistentShellTail {+ id: String,+ generation: u64,+ outcome: Result<String, String>,+ },+ /// A persistent-shell kill settled.+ PersistentShellKilled {+ id: String,+ outcome: Result<(), String>,+ },+ /// One shells/factory-runs fetch cycle landed: the activity lines re-count.+ SessionActivityLoaded(Vec<session_activity::ActivityRead>),}/// The flow's roster connection: one daemon connection alive across the flow's view runs, so a@@ -289,6 +311,15 @@ pub struct AgentsViewLink {/// The saved catalog the previous view run loaded: a re-entry paints the Inactive rows it/// already holds on its FIRST frame, and a loaded catalog skips the re-fetch.saved: SavedCatalog,+ /// The activity counts the previous run held: a re-entry renders the line the user opened on+ /// its first frame, so the carried selection restores onto it.+ session_activity: std::collections::HashMap<String, SessionActivity>,+ /// The persistent shells list the previous run held, for the same first-frame restore of a+ /// shell row.+ persistent_shells: Value,+ /// An unfinished cycle follows the roster link across session handoffs; re-entry consumes+ /// its result instead of starting another batch while these requests still wait.+ activity_fetch: Option<tokio::sync::oneshot::Receiver<Vec<session_activity::ActivityRead>>>,}impl AgentsViewLink {@@ -298,6 +329,9 @@ impl AgentsViewLink {client,events,saved: SavedCatalog::default(),+ session_activity: std::collections::HashMap::new(),+ persistent_shells: Value::Null,+ activity_fetch: None,})}@@ -438,6 +472,17 @@ struct AgentsViewMode {/// The daemon's heartbeat catalog (the dock's source, TS/// `heartbeats`): each row counts its own session's jobs.heartbeats: Vec<crate::heartbeats_picker::HeartbeatEntry>,+ /// The latest `list_persistent_shells` data: every persistent shell machine-wide.+ persistent_shells: Value,+ /// The bash view an orphan's open mounts over the list.+ shell_view: Option<crate::bash_view::BashView>,+ /// The open bash view's action the run loop dispatches (output fetch or kill).+ pending_shell_action: Option<crate::bash_view::BashViewAction>,+ /// The shell whose open waits on the daemon's walk of the rest of the saved store: its+ /// session opens once the walk lists it, the orphan view once the walk ends without it.+ pending_shell_open: Option<String>,+ /// Each live session's own shells and factory-run counts, keyed by `activeSessionId`.+ session_activity: std::collections::HashMap<String, SessionActivity>,}/// The press state of one left click, row-scoped: the release must land on the same row.@@ -540,6 +585,11 @@ impl AgentsViewMode {pressed_click: None,actions: Vec::new(),heartbeats: Vec::new(),+ persistent_shells: Value::Null,+ shell_view: None,+ pending_shell_action: None,+ pending_shell_open: None,+ session_activity: std::collections::HashMap::new(),}}}@@ -560,6 +610,7 @@ async fn open_roster_link(mut client,mut events,saved,+ ..} = match link {Some(link) => link,None => AgentsViewLink::connect(&options.socket_path)@@ -706,10 +757,19 @@ pub async fn run_agents_view(async fn run_agents_view_surface(options: AgentsViewOptions,ui: AgentsViewUiMode,- link: Option<AgentsViewLink>,+ mut link: Option<AgentsViewLink>,surface_mounted: std::sync::Arc<std::sync::atomic::AtomicBool>,) -> Result<AgentsViewRun> {crossterm::style::force_color_output(true);+ let session_activity = link+ .as_mut()+ .map(|link| std::mem::take(&mut link.session_activity))+ .unwrap_or_default();+ let persistent_shells = link+ .as_mut()+ .map(|link| std::mem::take(&mut link.persistent_shells))+ .unwrap_or_default();+ let mut activity_fetch = link.as_mut().and_then(|link| link.activity_fetch.take());// This pane may arrive already in TUI state (the chat's teardown preserves it), so a// roster-link failure here must hand the terminal back before the error escapes.let (client, mut events, roster, saved) = match open_roster_link(&options, link).await {@@ -733,6 +793,8 @@ async fn run_agents_view_surface(mode.saved = saved.sessions;mode.saved_catalog_loaded = saved.loaded;mode.saved_more = saved.more;+ mode.session_activity = session_activity;+ mode.persistent_shells = persistent_shells;mode.rebuild_rows();// The notice from the log's bounded tail paints on the FIRST frame, before the interval's// first tick.@@ -780,6 +842,19 @@ async fn run_agents_view_surface(// a superseded fetch's answer never applies).let mut heartbeat_generation: u64 = 1;heartbeats::spawn_heartbeat_catalog_fetch(&client, ui_tx.clone(), heartbeat_generation);+ // The persistent shells' list poll: one fetch in flight, the next armed when it lands.+ if client.supports_server_capability(persistent_shells::CAPABILITY) {+ persistent_shells::spawn_list_fetch(&client, ui_tx.clone());+ }+ let mut shells_fetch_at: Option<tokio::time::Instant> = None;+ // The activity lines' counts: one cycle in flight at a time, the next armed when it lands.+ if activity_fetch.is_none() {+ activity_fetch = Some(session_activity::spawn_session_activity_fetch(+ &client,+ mode.live_session_ids(),+ ));+ }+ let mut activity_fetch_at: Option<tokio::time::Instant> = None;// TS `start()`'s open-time settle (`armSavedSearchFetch` followed by// `resolveMissingSelectionAnchor`): a carried catalog arms no fetch,// so no terminal load ever arrives to settle the entry anchor's wait -@@ -871,22 +946,6 @@ async fn run_agents_view_surface(// The parked suggestion request materializes once the key's edits// landed.mode.materialize_composer_autocomplete();- // A failed saved-catalog fetch re-arms on the next query change: one honest- // retry behind a terminal failure.- if mode.take_saved_fetch_rearm() {- catalog_request = Some(spawn_saved_catalog_fetch(- &client,- ui_tx.clone(),- cwd.clone(),- session_dir.clone(),- None,- Some(SAVED_CATALOG_PAGE_FILES),- ));- // A superseded fetch's stream stops applying: the new fetch owns the- // catalog.- mode.drop_saved_stream();- saved_flush = None;- }// The executed stop-or-delete dispatch (the second ctrl+x): the wire call runs// off the key loop, its outcome lands as a `DeleteResult` status line.if let Some(action) = mode.take_delete_action() {@@ -942,6 +1001,9 @@ async fn run_agents_view_surface(deleted_saved_path,} => {mode.delete_result(&message, tone, deleted_saved_path);+ if shells_fetch_at.is_some() {+ shells_fetch_at = Some(tokio::time::Instant::now());+ }}UiInput::RenameResult { rename, outcome } => {mode.rename_result(rename, outcome);@@ -1011,12 +1073,68 @@ async fn run_agents_view_surface(mode.heartbeats = heartbeats;}}+ UiInput::PersistentShellsLoaded(data) => {+ if let Some(data) = data {+ mode.apply_persistent_shells(data);+ }+ shells_fetch_at = Some(+ tokio::time::Instant::now() + crate::interactive::ACTIVITY_POLL_INTERVAL,+ );+ }+ UiInput::PersistentShellTail {+ id,+ generation,+ outcome,+ } => {+ if let Some(view) = mode+ .shell_view+ .as_mut()+ .filter(|view| view.detail_id().as_deref() == Some(id.as_str()))+ {+ match outcome {+ Ok(tail) => view.set_output(&id, &tail, generation),+ Err(error) => view.set_error(error, true, Some(generation)),+ }+ }+ }+ // A landed kill re-reads the list now unless a read is already in flight.+ UiInput::PersistentShellKilled { id, outcome } => match outcome {+ Ok(()) => {+ if shells_fetch_at.is_some() {+ shells_fetch_at = Some(tokio::time::Instant::now());+ }+ }+ Err(error) => {+ if let Some(view) = mode+ .shell_view+ .as_mut()+ .filter(|view| view.detail_id().as_deref() == Some(id.as_str()))+ {+ view.set_error(error, false, None);+ }+ }+ },+ UiInput::SessionActivityLoaded(reads) => {+ mode.apply_session_activity(reads);+ activity_fetch_at = Some(+ tokio::time::Instant::now() + crate::interactive::ACTIVITY_POLL_INTERVAL,+ );+ }// The headless plan ended: the run stops here (the// interactive harness's `HeadlessDone` contract). A plan// that ends without an exit key still captures its frames// and returns instead of spinning forever.UiInput::Done => mode.running = false,}+ // The bash view's keys and wheel scrolls queue its action: dispatch+ // it after the input has been applied.+ if let Some(action) = mode.pending_shell_action.take() {+ action_dispatches.extend(persistent_shells::spawn_action(+ &client,+ ui_tx.clone(),+ action,+ ));+ }// An exit decision skips sync terminal I/O: a wedged pty must// not prevent the reader-armed force-quit deadline from firing.if !mode.running {@@ -1028,6 +1146,7 @@ async fn run_agents_view_surface(// loop state: select evaluates EVERY branch expression whether or not its// precondition passes, so the arms below must never unwrap an Option.let flush_at = saved_flush;+ let shells_at = shells_fetch_at;let status_at = mode.status_expiry(std::time::Instant::now());tokio::select! {maybe_event = events.recv() => {@@ -1079,6 +1198,22 @@ async fn run_agents_view_surface(continue;}}+ result = async {+ match activity_fetch.as_mut() {+ Some(fetch) => fetch.await,+ None => std::future::pending().await,+ }+ } => {+ activity_fetch = None;+ if let Ok(reads) = result {+ pending.push(UiInput::SessionActivityLoaded(reads));+ } else {+ activity_fetch_at = Some(+ tokio::time::Instant::now() + crate::interactive::ACTIVITY_POLL_INTERVAL,+ );+ }+ continue;+ }// Only a running row needs a periodic frame. The timer// stays tied to the last pulse across unrelated inputs.() = tokio::time::sleep_until(last_pulse + Duration::from_millis(PULSE_INTERVAL_MS)),@@ -1096,6 +1231,27 @@ async fn run_agents_view_surface(}saved_flush = None;}+ () = async {+ match shells_at {+ Some(at) => tokio::time::sleep_until(at).await,+ None => std::future::pending().await,+ }+ } => {+ shells_fetch_at = None;+ persistent_shells::spawn_list_fetch(&client, ui_tx.clone());+ }+ () = async {+ match activity_fetch_at {+ Some(at) => tokio::time::sleep_until(at).await,+ None => std::future::pending().await,+ }+ } => {+ activity_fetch_at = None;+ activity_fetch = Some(session_activity::spawn_session_activity_fetch(+ &client,+ mode.live_session_ids(),+ ));+ }// The incident-notice poll's wake-up: the drain below the select// does the refresh, so the arm only ends the wait.() = tokio::time::sleep_until(incident_poll_at) => {}@@ -1129,6 +1285,22 @@ async fn run_agents_view_surface(+ Duration::from_millis(crate::incident_notices::INCIDENT_NOTICE_POLL_INTERVAL_MS);redraw |= mode.refresh_incident_notices();}+ // A failed saved-catalog fetch re-arms on the next query change or deferred shell open+ // (a key, a paste, or a click): one honest retry behind a terminal failure.+ if mode.take_saved_fetch_rearm() {+ catalog_request = Some(spawn_saved_catalog_fetch(+ &client,+ ui_tx.clone(),+ cwd.clone(),+ session_dir.clone(),+ None,+ Some(SAVED_CATALOG_PAGE_FILES),+ ));+ // A superseded fetch's stream stops applying: the new fetch owns the+ // catalog.+ mode.drop_saved_stream();+ saved_flush = None;+ }// The unfolded rest of the store: a scroll near the list's end fetches the next page, a// search fetches all of it (its rows stream in as they fold).if catalog_request.is_none() {@@ -1216,6 +1388,9 @@ async fn run_agents_view_surface(UiInput::KillResult { key, outcome } => {mode.kill_result(&key, outcome);}+ UiInput::SessionActivityLoaded(reads) => {+ mode.apply_session_activity(reads);+ }_ => {}}}@@ -1239,6 +1414,9 @@ async fn run_agents_view_surface(loaded: mode.saved_catalog_loaded,more: mode.saved_more.clone(),},+ session_activity: std::mem::take(&mut mode.session_activity),+ persistent_shells: std::mem::take(&mut mode.persistent_shells),+ activity_fetch,})} else {client.close();@@ -1266,6 +1444,7 @@ async fn run_agents_view_surface(.and_then(|row| row.cwd.clone()).map(std::path::PathBuf::from),status_message: opened.as_ref().and_then(|row| row.status_message.clone()),+ panel: opened.as_ref().and_then(|row| row.panel.clone()),actions: std::mem::take(&mut mode.actions),incident_notice_state: mode.incident_notice_state,},@@ -1306,6 +1485,10 @@ fn is_daemon_answer(input: &UiInput) -> bool {| UiInput::ReplyResult { .. }| UiInput::KillResult { .. }| UiInput::HeartbeatsLoaded { .. }+ | UiInput::PersistentShellsLoaded(_)+ | UiInput::PersistentShellTail { .. }+ | UiInput::PersistentShellKilled { .. }+ | UiInput::SessionActivityLoaded(_))}diff --git a/crates/pa-tui/src/agents_view/data_input.rs b/crates/pa-tui/src/agents_view/data_input.rsindex 6160711106..97af46e6a7 100644--- a/crates/pa-tui/src/agents_view/data_input.rs+++ b/crates/pa-tui/src/agents_view/data_input.rs@@ -73,6 +73,7 @@ impl AgentsViewMode {&self.expanded_parents,&self.program_shown_parents,&rollups,+ &self.session_activity,self.options.anchor_session_id.as_deref(),);// The entry anchor's row may be nested: arm the same ancestor expansion below so this@@ -99,7 +100,7 @@ impl AgentsViewMode {while added {added = false;for row in &rows {- if row.kind == RowKind::SubagentSummary {+ if !matches!(row.kind, RowKind::Agent | RowKind::Subagent) {continue;}let session_id = row.summary.get("sessionId").and_then(Value::as_str);@@ -117,11 +118,16 @@ impl AgentsViewMode {&self.expanded_parents,&self.program_shown_parents,&rollups,+ &self.session_activity,self.options.anchor_session_id.as_deref(),);}}}+ // The machine-wide persistent shells head the unscoped, unsearched list.+ if !scope_active && self.query.trim().is_empty() {+ rows.splice(0..0, self.persistent_shell_rows(&records));+ }// Keep the selection on the same row across rebuilds, falling back to the carried// identity/key.self.selected = resolve_selection(@@ -145,6 +151,12 @@ impl AgentsViewMode {}}self.rows = rows;+ if let Some(view) = self.shell_view.as_mut() {+ view.apply_activities(super::persistent_shells::activities(+ &self.persistent_shells,+ &self.rows,+ ));+ }// The armed confirm only rides a row the list still carries under the session key it// armed with: a removed, re-created, or re-keyed row retires it.if let Some(pending) = &self.pending_delete {@@ -284,6 +296,7 @@ impl AgentsViewMode {let rows = std::mem::take(&mut self.saved_stream);self.upsert_saved(rows);self.rebuild_rows();+ self.settle_pending_shell_open();true}@@ -316,7 +329,7 @@ impl AgentsViewMode {.saved_more.as_ref().filter(|_| !self.saved_fetch_failed)?;- if !self.query.trim().is_empty() {+ if !self.query.trim().is_empty() || self.pending_shell_open.is_some() {return Some((more.cursor.clone(), None));}if self.anchor_selection_pending {@@ -345,6 +358,7 @@ impl AgentsViewMode {if self.saved_more.is_none() {self.end_anchor_wait();}+ self.settle_pending_shell_open();}/// Drop the unflushed stream batch: the terminal response replaces the catalog wholesale, and@@ -353,10 +367,11 @@ impl AgentsViewMode {self.saved_stream.clear();}- /// The saved-catalog fetch settled on a terminal failure: the entry anchor's wait ends with- /// it (the anchor's row can only arrive through this fetch).+ /// The saved-catalog fetch settled on a terminal failure: the entry anchor's wait and a+ /// pending shell open end with it (their rows can only arrive through this fetch).pub(super) fn settle_anchor_wait_on_saved_failure(&mut self) {self.end_anchor_wait();+ self.pending_shell_open = None;}/// One search edit (TS `queryChanged`). The rebuilt list selects its@@ -445,6 +460,10 @@ impl AgentsViewMode {// A sticky line clears on any keypress (the transient lines ride their own// expiry).self.clear_sticky_status();+ if self.shell_view.is_some() {+ self.handle_shell_view_key(key);+ return;+ }let was_armed = self.exit_armed;// The notice panel: any key closes it (the refusal's ways out stay copy-pasteable while// it is up), except the exit key, which falls through so the double-press exit convention@@ -552,6 +571,7 @@ impl AgentsViewMode {has_children: false,status_message: None,cwd,+ panel: None,});self.running = false;return;@@ -725,6 +745,19 @@ impl AgentsViewMode {if !crate::mouse_tracking::active() {return;}+ if let Some(view) = self.shell_view.as_mut() {+ // Mouse movement is semantic: remapped keyboard arrows must not+ // change it, and clicks must not reach hidden session rows.+ if let Some(delta) = crate::mouse::wheel_scroll_delta(event) {+ for _ in 0..delta.unsigned_abs() {+ match view.scroll_output(delta.signum()) {+ crate::bash_view::BashViewAction::None => {}+ action => self.pending_shell_action = Some(action),+ }+ }+ }+ return;+ }// A buttonless motion report is the hover (operator directive 2026-09-29, `?1003` any-event// tracking): the row under the mouse carries the light hover band while it resolves to a// session row. Motion never disturbs the click grammar: a pending press keeps its rowdiff --git a/crates/pa-tui/src/agents_view/delete.rs b/crates/pa-tui/src/agents_view/delete.rsindex d798c0da16..e3e106d96c 100644--- a/crates/pa-tui/src/agents_view/delete.rs+++ b/crates/pa-tui/src/agents_view/delete.rs@@ -41,13 +41,22 @@ pub(super) enum DeleteAction {},/// A saved, non-live agent: delete the session file/// (`delete_saved_session`).- DeleteSavedSession { session_path: String, name: String },+ DeleteSavedSession {+ session_path: String,+ name: String,+ },+ StopShell {+ shell_id: String,+ name: String,+ },}impl DeleteAction {fn success_message(&self) -> String {match self {- DeleteAction::StopSubagent { name, .. } | DeleteAction::StopAgent { name, .. } => {+ DeleteAction::StopSubagent { name, .. }+ | DeleteAction::StopAgent { name, .. }+ | DeleteAction::StopShell { name, .. } => {format!("Stopped {name}")}DeleteAction::DeleteSubagent { name, .. } => {@@ -61,7 +70,9 @@ impl DeleteAction {fn fail_word(&self) -> &'static str {match self {- DeleteAction::StopSubagent { .. } | DeleteAction::StopAgent { .. } => "Stop",+ DeleteAction::StopSubagent { .. }+ | DeleteAction::StopAgent { .. }+ | DeleteAction::StopShell { .. } => "Stop",DeleteAction::DeleteSubagent { .. } | DeleteAction::DeleteSavedSession { .. } => {"Delete"}@@ -81,7 +92,7 @@ impl DeleteAction {DeleteAction::DeleteSubagent { .. } => {data.get("deleted") != Some(&serde_json::json!(false))}- DeleteAction::StopAgent { .. } => true,+ DeleteAction::StopAgent { .. } | DeleteAction::StopShell { .. } => true,DeleteAction::DeleteSavedSession { .. } => {data.get("ok").map(serde_json::Value::as_bool) != Some(Some(false))}@@ -153,6 +164,11 @@ pub(super) fn spawn_delete_dispatch(rest: serde_json::Map::default(),}}+ DeleteAction::StopShell { shell_id, .. } => DaemonCommand::KillPersistentShell {+ id: None,+ shell_id: shell_id.clone(),+ rest: serde_json::Map::default(),+ },};// The outcome's tone is explicit: success muted, a no-effect stop warning, a// failure error — the status line never re-derives it from the text.@@ -192,7 +208,8 @@ pub(super) fn spawn_delete_dispatch(DeleteAction::DeleteSavedSession { .. }| DeleteAction::StopSubagent { .. }| DeleteAction::DeleteSubagent { .. }- | DeleteAction::StopAgent { .. } => None,+ | DeleteAction::StopAgent { .. }+ | DeleteAction::StopShell { .. } => None,};let _ = ui_tx.send(UiInput::DeleteResult {message: outcome,@@ -225,7 +242,10 @@ impl AgentsViewMode {let row = self.rows.get(self.selected)?;let stop = Self::delete_arm_word(row);match row.kind {- RowKind::SubagentSummary | RowKind::Code => None,+ RowKind::SubagentSummary | RowKind::Code | RowKind::Shells | RowKind::FactoryRuns => {+ None+ }+ RowKind::PersistentShell => Some(()),// An agent with a live session stops (an idle-but-live row still stops, never// deletes its file); a saved-only row deletes.RowKind::Agent if row.summary.get("activeSessionId").is_some() => row@@ -313,7 +333,10 @@ impl AgentsViewMode {/// The row's stop-or-delete word: true while the row rides a live session or the running/// section, false for a saved-only row.pub(super) fn delete_arm_word(row: &AgentsViewRow) -> bool {- if row.summary.get("rlmChildId").is_some() {+ if row.kind == RowKind::PersistentShell {+ // A listed shell is live: it always stops.+ true+ } else if row.summary.get("rlmChildId").is_some() {// A child rides its own activity: the running section is its live work, an idle// child deletes — the retained activeSessionId on an idle child is not live work.row.section == crate::agents_view_state::Section::Running@@ -344,7 +367,10 @@ impl AgentsViewMode {// Subagent rows (and promoted children) target the child through// the parent's live session.if let Some(child_id) = child_id {- if row.kind == RowKind::SubagentSummary {+ if matches!(+ row.kind,+ RowKind::SubagentSummary | RowKind::Shells | RowKind::FactoryRuns+ ) {return None;}// The child arms always run through the PARENT's session: a scoped promoted child has@@ -366,7 +392,15 @@ impl AgentsViewMode {// Agent rows: a live session stops (idle-but-live included); a saved-only row deletes// its file.match row.kind {- RowKind::SubagentSummary | RowKind::Subagent | RowKind::Code => None,+ RowKind::SubagentSummary+ | RowKind::Subagent+ | RowKind::Code+ | RowKind::Shells+ | RowKind::FactoryRuns => None,+ RowKind::PersistentShell => {+ let shell_id = row.summary.get("shellId")?.as_str()?.to_string();+ Some(DeleteAction::StopShell { shell_id, name })+ }RowKind::Agent => {if let Some(active_session_id) = active_session_id {Some(DeleteAction::StopAgent {diff --git a/crates/pa-tui/src/agents_view/open_incident.rs b/crates/pa-tui/src/agents_view/open_incident.rsindex a46276a4e8..971987f15f 100644--- a/crates/pa-tui/src/agents_view/open_incident.rs+++ b/crates/pa-tui/src/agents_view/open_incident.rs@@ -3,7 +3,7 @@//! structured-log poll, the dismissal, and the panel render).use super::{ancestor_session_ids, has_session_children, scope_ancestors, AgentsViewMode, AgentsViewRow,- Line, OpenedRow, PathBuf, RowKind, SessionSelection, Value, ANCHOR_LOADING_HINT,+ Line, OpenedRow, PathBuf, RowKind, SessionPanel, SessionSelection, Value, ANCHOR_LOADING_HINT,};impl AgentsViewMode {@@ -19,8 +19,13 @@ impl AgentsViewMode {RowKind::SubagentSummary => self.toggle_subagent_list(&row),RowKind::Subagent => self.open_subagent_row(&row),RowKind::Agent => self.open_row(&row, Vec::new()),+ RowKind::PersistentShell => self.open_persistent_shell(&row),// A program row is read-only context: the open action never fires on it.RowKind::Code => {}+ RowKind::Shells => {+ self.open_activity_line(&row, SessionPanel::Shells { shell_id: None });+ }+ RowKind::FactoryRuns => self.open_activity_line(&row, SessionPanel::FactoryRuns),}}@@ -30,10 +35,13 @@ impl AgentsViewMode {let row = self.rows.get(self.selected)?;let target = match row.kind {RowKind::Agent => row.identity.as_str(),- RowKind::SubagentSummary | RowKind::Subagent => row.parent_identity.as_deref()?,+ RowKind::SubagentSummary+ | RowKind::Subagent+ | RowKind::Shells+ | RowKind::FactoryRuns => row.parent_identity.as_deref()?,// Unreachable (code rows are not selectable), exhaustive by- // the match rule.- RowKind::Code => return None,+ // the match rule; a shell row has no subagents.+ RowKind::Code | RowKind::PersistentShell => return None,};self.rows.iter().find(|row| {row.kind == RowKind::SubagentSummary && row.parent_identity.as_deref() == Some(target)@@ -110,6 +118,21 @@ impl AgentsViewMode {);}+ /// Open an activity line's node with the line's panel requested: the node's ancestors+ /// re-expand on return, and the selection restores onto the line.+ fn open_activity_line(&mut self, row: &AgentsViewRow, panel: SessionPanel) {+ let node_parent = self+ .rows+ .iter()+ .find(|node| Some(node.identity.as_str()) == row.parent_identity.as_deref())+ .and_then(|node| node.parent_identity.clone());+ let ancestors = ancestor_session_ids(&self.rows, node_parent.as_deref());+ self.open_row(row, ancestors);+ if let Some(opened) = self.opened.as_mut() {+ opened.panel = Some(panel);+ }+ }+/// The top-level ancestor row of a nested row.pub(super) fn find_subagent_root_row(&self, row: &AgentsViewRow) -> Option<&AgentsViewRow> {let mut identity = row.parent_identity.as_deref();@@ -207,6 +230,7 @@ impl AgentsViewMode {.and_then(Value::as_str).filter(|cwd| !cwd.is_empty()).map(str::to_string),+ panel: None,});self.running = false;}@@ -251,6 +275,7 @@ impl AgentsViewMode {.and_then(Value::as_str).filter(|cwd| !cwd.is_empty()).map(str::to_string),+ panel: None,});self.running = false;}diff --git a/crates/pa-tui/src/agents_view/persistent_shells.rs b/crates/pa-tui/src/agents_view/persistent_shells.rsnew file mode 100644index 0000000000..c96939f443--- /dev/null+++ b/crates/pa-tui/src/agents_view/persistent_shells.rs@@ -0,0 +1,285 @@+//! The machine-wide persistent shells: the rows under the list's `Persistent shells` heading. A+//! shell's open lands on its session's Bash panel; an orphan's (its session deleted) mounts the+//! bash view over the orphans (output and kill).+use std::collections::HashMap;++use super::{+ mpsc, scope_ancestors, AgentsViewMode, AgentsViewRow, AgentsViewScope, DaemonClient,+ DaemonCommand, RowKind, Section, SessionPanel, UiInput, Value, ANCHOR_LOADING_HINT,+};+use crate::agents_view_state::{summary_for_record, UnifiedRecord};+use crate::bash_view::{+ format_duration, parse_bash_activities, BashActivity, BashView, BashViewAction,+};++/// The daemon capability that serves the machine-wide shell list, output, and kill.+pub(super) const CAPABILITY: &str = "persistent_shells";++/// The row identity prefix of a shell row.+const ROW_PREFIX: &str = "shell:";++/// One `list_persistent_shells` fetch; a failed read lands as `None` and keeps the last list.+pub(super) fn spawn_list_fetch(client: &DaemonClient, ui_tx: mpsc::UnboundedSender<UiInput>) {+ let client = client.clone();+ tokio::spawn(async move {+ let data = client+ .request_ok(DaemonCommand::ListPersistentShells {+ id: None,+ rest: serde_json::Map::default(),+ })+ .await+ .ok();+ let _ = ui_tx.send(UiInput::PersistentShellsLoaded(data));+ });+}++/// Run one bash-view action against the daemon: an open or load-more fetches the output tail, a+/// kill kills the shell (the returned handle lets the exit drain wait for it).+pub(super) fn spawn_action(+ client: &DaemonClient,+ ui_tx: mpsc::UnboundedSender<UiInput>,+ action: BashViewAction,+) -> Option<tokio::task::JoinHandle<()>> {+ let client = client.clone();+ match action {+ BashViewAction::OpenDetail { id, generation } => Some(spawn_tail(+ client,+ ui_tx,+ id,+ generation,+ crate::bash_view::FIRST_TAIL_LINES,+ )),+ BashViewAction::LoadMore {+ id,+ generation,+ lines,+ } => Some(spawn_tail(client, ui_tx, id, generation, lines)),+ BashViewAction::Kill { id } => Some(tokio::spawn(async move {+ let outcome = client+ .request_ok(DaemonCommand::KillPersistentShell {+ id: None,+ shell_id: id.clone(),+ rest: serde_json::Map::default(),+ })+ .await+ .map(|_| ())+ .map_err(|error| format!("Could not kill bash command: {error:#}"));+ let _ = ui_tx.send(UiInput::PersistentShellKilled { id, outcome });+ })),+ BashViewAction::Close | BashViewAction::None => None,+ }+}++fn spawn_tail(+ client: DaemonClient,+ ui_tx: mpsc::UnboundedSender<UiInput>,+ id: String,+ generation: u64,+ lines: u32,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ let outcome = client+ .request_ok(DaemonCommand::TailPersistentShell {+ id: None,+ shell_id: id.clone(),+ lines,+ rest: serde_json::Map::default(),+ })+ .await+ .map(|data| {+ data.get("tail")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string()+ })+ .map_err(|error| format!("Bash output: {error:#}"));+ let _ = ui_tx.send(UiInput::PersistentShellTail {+ id,+ generation,+ outcome,+ });+ })+}++impl AgentsViewMode {+ /// One row per live shell (a finished one only while its bash-view detail is open), its title+ /// the command, carrying its session's summary while the roster or the catalog lists it.+ pub(super) fn persistent_shell_rows(&self, records: &[UnifiedRecord]) -> Vec<AgentsViewRow> {+ let sessions: HashMap<String, Value> = records+ .iter()+ .map(summary_for_record)+ .filter_map(|summary| {+ let session_id = summary.get("sessionId")?.as_str()?.to_string();+ Some((session_id, summary))+ })+ .collect();+ let open = self.shell_view.as_ref().and_then(BashView::detail_id);+ self.persistent_shells+ .get("activities")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|shell| {+ let id = shell.get("id")?.as_str()?;+ if shell.get("status").and_then(Value::as_str) == Some("finished")+ && open.as_deref() != Some(id)+ {+ return None;+ }+ let session = shell+ .get("sessionId")+ .and_then(Value::as_str)+ .and_then(|session_id| sessions.get(session_id).cloned());+ Some(AgentsViewRow {+ kind: RowKind::PersistentShell,+ section: Section::Inactive,+ identity: format!("{ROW_PREFIX}{id}"),+ parent_identity: None,+ summary: serde_json::json!({+ "shellId": id,+ "session": session,+ }),+ title: shell+ .get("command")+ .and_then(Value::as_str)+ .map(single_line)+ .unwrap_or_default(),+ model: "-".to_string(),+ cost: 0.0,+ age: format_duration(shell.get("durationMs").and_then(Value::as_u64)),+ depth: 0,+ descendant_count: 0,+ running_subagent_count: 0,+ expanded: false,+ has_spawn_code: false,+ })+ })+ .collect()+ }++ /// Enter on a shell row: its session opens on the Bash panel with the shell selected; an orphan+ /// opens the bash view over the orphans with it selected, once the daemon's walk of the whole+ /// store says the session is gone (a shell's session may sit past the loaded pages).+ pub(super) fn open_persistent_shell(&mut self, row: &AgentsViewRow) {+ let Some(id) = row.summary.get("shellId").and_then(Value::as_str) else {+ return;+ };+ if let Some(session) = row+ .summary+ .get("session")+ .filter(|session| !session.is_null())+ {+ let ancestors = scope_ancestors(+ &self.records(),+ &AgentsViewScope {+ session_id: session+ .get("sessionId")+ .and_then(Value::as_str)+ .map(str::to_string),+ active_session_id: None,+ session_name: None,+ },+ );+ self.open_row(+ &AgentsViewRow {+ summary: session.clone(),+ ..row.clone()+ },+ ancestors,+ );+ if let Some(opened) = self.opened.as_mut() {+ opened.panel = Some(SessionPanel::Shells {+ shell_id: Some(id.to_string()),+ });+ }+ return;+ }+ if !self.saved_catalog_loaded || self.saved_more.is_some() {+ // The open is an explicit retry, like a query change, of a walk that failed.+ self.saved_query_rearm = self.saved_fetch_failed;+ self.pending_shell_open = Some(id.to_string());+ self.set_status(ANCHOR_LOADING_HINT);+ return;+ }+ let mut view = BashView::new(+ activities(&self.persistent_shells, &self.rows),+ self.last_height,+ )+ .with_subtitle("Session deleted");+ view.select(id);+ self.shell_view = Some(view);+ }++ /// Retry the pending shell open after the catalog grew or its walk ended, while its row is+ /// still the selected one (moving the selection away abandons it).+ pub(super) fn settle_pending_shell_open(&mut self) {+ let Some(id) = self.pending_shell_open.take() else {+ return;+ };+ if let Some(row) = self+ .rows+ .get(self.selected)+ .filter(|row| row.identity == format!("{ROW_PREFIX}{id}"))+ .cloned()+ {+ self.open_persistent_shell(&row);+ }+ }++ /// One key while the bash view is open: it owns every key; its close returns to the list.+ pub(super) fn handle_shell_view_key(&mut self, key: &str) {+ if key == "ctrl+c" {+ self.exit_guard.note_ctrl_c_handled();+ }+ let Some(view) = self.shell_view.as_mut() else {+ return;+ };+ let open = view.detail_id();+ match view.handle_key(key, &self.keybindings) {+ BashViewAction::Close => self.shell_view = None,+ BashViewAction::None => {}+ action => self.pending_shell_action = Some(action),+ }+ // A finished shell's row lives only while its detail is open.+ if self.shell_view.as_ref().and_then(BashView::detail_id) != open {+ self.rebuild_rows();+ }+ }++ /// A landed list: the rows rebuild and an open bash view follows, only when it changed; a kill+ /// error clears only when a row moved, never on a running row's duration tick.+ pub(super) fn apply_persistent_shells(&mut self, data: Value) {+ if data == self.persistent_shells {+ return;+ }+ if crate::bash_view::registry_rows_moved(&self.persistent_shells, &data) {+ if let Some(view) = self.shell_view.as_mut() {+ view.clear_error();+ }+ }+ self.persistent_shells = data;+ self.rebuild_rows();+ }+}++/// The orphan bash view's shells: exactly the shells whose row has no session.+pub(super) fn activities(shells: &Value, rows: &[AgentsViewRow]) -> Vec<BashActivity> {+ parse_bash_activities(shells)+ .into_iter()+ .filter(|activity| {+ rows.iter().any(|row| {+ row.kind == RowKind::PersistentShell+ && row.summary.get("shellId").and_then(Value::as_str)+ == Some(activity.id.as_str())+ && row.summary["session"].is_null()+ })+ })+ .collect()+}++fn single_line(value: &str) -> String {+ crate::menu_panel::scrub_controls(value)+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+}diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rsindex f23cc57191..022dfec315 100644--- a/crates/pa-tui/src/agents_view/render.rs+++ b/crates/pa-tui/src/agents_view/render.rs@@ -15,6 +15,14 @@ impl AgentsViewMode {) -> (Vec<Line>, Option<(usize, usize)>) {// The frame height feeds the page step (TS reads `ui.terminal.rows` live at key time).self.last_height = height;+ if let Some(view) = self.shell_view.as_mut() {+ view.set_viewport_rows(height);+ self.click_rows.clear();+ self.hover_row = None;+ let mut lines = view.render(&self.theme, width, &self.keybindings);+ lines.resize_with(height, Vec::new);+ return (lines, None);+ }let mut lines: Vec<Line> = Vec::new();// The splash counts agent-kind rows only — nested subagent and summary rows never// inflate the header.@@ -275,6 +283,7 @@ impl AgentsViewMode {enum DisplayItem<'a> {Spacer,Heading(Section),+ ShellsHeading(usize),Row(usize, &'a AgentsViewRow),/// One note line of the selected row's expansion; one item per/// line so the viewport clips at line granularity.@@ -317,6 +326,20 @@ impl AgentsViewMode {// While a query is active the list is a ranked picker: one flat, relevance-ordered run// of hits (per-row icons carry the status), not status section blocks.if self.query.trim().is_empty() {+ let shells: Vec<(usize, &AgentsViewRow)> = self+ .rows+ .iter()+ .enumerate()+ .filter(|(_, row)| row.kind == RowKind::PersistentShell)+ .collect();+ if !shells.is_empty() {+ display.push(DisplayItem::ShellsHeading(shells.len()));+ display.extend(+ shells+ .into_iter()+ .map(|(index, row)| DisplayItem::Row(index, row)),+ );+ }for (section, count) in &counts {if *count == 0 {continue;@@ -423,6 +446,12 @@ impl AgentsViewMode {truncate_text(&format!("{} ({count})", section_title(*section)), width),)]);}+ DisplayItem::ShellsHeading(count) => {+ lines.push(vec![self.theme.fg(+ ThemeColor::Muted,+ truncate_text(&format!("Persistent shells ({count})"), width),+ )]);+ }DisplayItem::Row(index, row) => {// The row's frame position carries the hover (operator directive// 2026-09-29): the light band rides the row the mouse rests on.@@ -489,7 +518,7 @@ impl AgentsViewMode {let theme = &self.theme;// A muted, truncated program line on the tool-panel background; never selection-painted.if row.kind == RowKind::Code {- let text = format!("{} {}", " ".repeat(row.depth), row.title);+ let text = format!("{} {}", depth_indent(row.depth), row.title);let line = pad_line(vec![theme.fg(ThemeColor::Muted, truncate_text(&text, width))],width,@@ -498,8 +527,14 @@ impl AgentsViewMode {}let selected = Some(row.identity.as_str())== self.rows.get(self.selected).map(|r| r.identity.as_str());+ // The activity lines' glyph sits in the summary line's marker slot; no cost cell.+ if matches!(row.kind, RowKind::Shells | RowKind::FactoryRuns) {+ let text = format!("{}{}", depth_indent(row.depth), row.title);+ let line = pad_line(vec![crate::Span::raw(truncate_text(&text, width))], width);+ return finish_session_row(theme, line, selected, hovered, width);+ }if row.kind == RowKind::SubagentSummary {- let indent = " ".repeat(row.depth);+ let indent = depth_indent(row.depth);let marker = if row.expanded { "\u{25be}" } else { "\u{25b8}" };let text = format!("{indent}{marker} {}", row.title);// BOTH summary lines bill the descendant tree in the Cost column (operator directive@@ -533,6 +568,7 @@ impl AgentsViewMode {return finish_session_row(theme, line, selected, hovered, width);}let icon = match row.section {+ _ if row.kind == RowKind::PersistentShell => "$",Section::Running => ["\u{25c7}", "\u{25c8}", "\u{25c6}", "\u{25c8}"][self.pulse % 4],_ => "\u{2022}",};@@ -544,7 +580,12 @@ impl AgentsViewMode {let icon_style = theme.fg_style(icon_color).add_modifier(ratatui::style::Modifier::BOLD);- let indent = " ".repeat(row.depth);+ // The indent clips to the name column after the icon prefix, so a deep row keeps the+ // model and cost/age columns in place.+ let indent = truncate_text(+ &depth_indent(row.depth),+ layout.name_width.saturating_sub(2),+ );let indent_width = str_width(&indent);let mut line: Line = Vec::new();if indent_width > 0 {@@ -645,11 +686,7 @@ impl AgentsViewMode {return Vec::new();};// Keep room for a wide character when nesting exceeds the pane.- let indent_width = row- .depth- .saturating_add(1)- .saturating_mul(2)- .min(width.saturating_sub(2));+ let indent_width = (str_width(&depth_indent(row.depth)) + 2).min(width.saturating_sub(2));let indent = " ".repeat(indent_width);let dim = self.theme.fg_style(ThemeColor::Dim);let wrap_width = width.saturating_sub(str_width(&indent)).max(1);@@ -855,6 +892,12 @@ pub(super) fn finish_session_row(line}+/// Every row's leading indent: one step per nesting level, so a row's child lines sit a full+/// step past its `• ` prefix.+fn depth_indent(depth: usize) -> String {+ " ".repeat(4 * depth)+}+pub(super) fn cell(value: &str, width: usize) -> String {let truncated = truncate_text(value, width);format!(diff --git a/crates/pa-tui/src/agents_view/session_activity.rs b/crates/pa-tui/src/agents_view/session_activity.rsnew file mode 100644index 0000000000..dba56bdb8c--- /dev/null+++ b/crates/pa-tui/src/agents_view/session_activity.rs@@ -0,0 +1,122 @@+//! The per-session shells and factory-run counts behind the agents-view activity lines.+use super::{AgentsViewMode, DaemonClient, DaemonCommand, SessionActivity};+use anyhow::Result;+use serde_json::{Map, Value};+use tokio::sync::oneshot;++/// One session's counts from one cycle: `None` is a failed read, which keeps that session's last+/// count.+pub(super) struct ActivityRead {+ pub(super) active_session_id: String,+ pub(super) shells: Option<usize>,+ pub(super) factory_runs: Option<usize>,+}++/// One fetch cycle over the live sessions, off the key loop: each session's kernel answers its+/// own shells list and factory graph; the cycle lands once every session answered.+pub(super) fn spawn_session_activity_fetch(+ client: &DaemonClient,+ sessions: Vec<String>,+) -> oneshot::Receiver<Vec<ActivityRead>> {+ let shells_supported = client.supports_server_capability("kernel_bash_activity");+ let factory_supported = client.supports_server_capability("factory_activity");+ let client = client.clone();+ let (tx, rx) = oneshot::channel();+ tokio::spawn(async move {+ let mut reads = tokio::task::JoinSet::new();+ for active_session_id in sessions {+ let client = client.clone();+ reads.spawn(async move {+ let shells = async {+ if !shells_supported {+ return Some(0);+ }+ let reply = client+ .request_ok(DaemonCommand::ListKernelBash {+ id: None,+ active_session_id: active_session_id.clone(),+ rest: Map::default(),+ })+ .await;+ count(reply, |data| {+ Some(crate::bash_view::running_shell_count(data))+ })+ };+ let factory_runs = async {+ if !factory_supported {+ return Some(0);+ }+ let reply = client+ .request_ok(DaemonCommand::FactoryActivity {+ id: None,+ active_session_id: active_session_id.clone(),+ action: "graph".to_string(),+ run_id: None,+ spec_id: None,+ timeout_ms: None,+ rest: Map::default(),+ })+ .await;+ count(reply, |data| {+ crate::factory_view::factory_reply_lists_runs(data)+ .then(|| crate::factory_view::live_run_count(data))+ })+ };+ let (shells, factory_runs) = tokio::join!(shells, factory_runs);+ ActivityRead {+ active_session_id,+ shells,+ factory_runs,+ }+ });+ }+ let reads = reads.join_all().await;+ let _ = tx.send(reads);+ });+ rx+}++/// A session without a running kernel hosts nothing: zero, not a failed read.+fn count(reply: Result<Value>, count: impl Fn(&Value) -> Option<usize>) -> Option<usize> {+ match reply {+ Ok(data) => count(&data),+ Err(error) if crate::daemon_client::is_kernel_not_running(&error) => Some(0),+ Err(_) => None,+ }+}++impl AgentsViewMode {+ /// The roster's live sessions a fetch cycle asks: saved rows have no kernel and render no lines.+ pub(super) fn live_session_ids(&self) -> Vec<String> {+ self.roster+ .iter()+ .filter_map(|entry| entry.get("summary")?.get("activeSessionId")?.as_str())+ .filter(|active| !active.is_empty())+ .map(str::to_string)+ .collect()+ }++ /// Fold one cycle into the counts (a failed read keeps that session's last count) and+ /// rebuild only when a count moved.+ pub(super) fn apply_session_activity(&mut self, reads: Vec<ActivityRead>) {+ let activity = reads+ .into_iter()+ .map(|read| {+ let last = self+ .session_activity+ .get(&read.active_session_id)+ .copied()+ .unwrap_or_default();+ let counts = SessionActivity {+ shells: read.shells.unwrap_or(last.shells),+ factory_runs: read.factory_runs.unwrap_or(last.factory_runs),+ };+ (read.active_session_id, counts)+ })+ .collect();+ if activity != self.session_activity {+ self.session_activity = activity;+ self.rebuild_rows();+ }+ }+}diff --git a/crates/pa-tui/src/agents_view/tests.rs b/crates/pa-tui/src/agents_view/tests.rsindex ef203f3eb3..6fdc7a12b1 100644--- a/crates/pa-tui/src/agents_view/tests.rs+++ b/crates/pa-tui/src/agents_view/tests.rs@@ -5,6 +5,7 @@use super::*;+mod activity_lines;mod click_surface;mod cost_aggregates;mod delete_stop;@@ -25,6 +26,7 @@ mod saved_catalog;mod saved_pages;mod search_selection;mod selection_churn;+mod shell_enter;/// One idle row under test plus a holder row that keeps the selection, with the given title/// and one model id. The cost/age stay fixed so the expected rows are exact.diff --git a/crates/pa-tui/src/agents_view/tests/activity_lines.rs b/crates/pa-tui/src/agents_view/tests/activity_lines.rsnew file mode 100644index 0000000000..0cfc91a41b--- /dev/null+++ b/crates/pa-tui/src/agents_view/tests/activity_lines.rs@@ -0,0 +1,95 @@+//! The shells and factory-run lines: Enter on a line opens its node's session with the matching+//! panel requested, the line's identity carried for the return.++use super::*;+use crate::agents_view_forest::SessionActivity;+use crate::interactive::SessionPanel;++fn with_activity(mode: &mut AgentsViewMode, active: &str, shells: usize, factory_runs: usize) {+ mode.session_activity.insert(+ active.to_string(),+ SessionActivity {+ shells,+ factory_runs,+ },+ );+ mode.rebuild_rows();+}++fn select_title(mode: &mut AgentsViewMode, title: &str) {+ mode.selected = mode+ .rows+ .iter()+ .position(|row| row.title == title)+ .unwrap_or_else(|| panic!("no {title:?} row: {:?}", mode.rows));+}++#[test]+fn enter_on_the_shells_line_opens_the_node_with_the_shells_panel() {+ let mut mode = mode_with_parent_and_child();+ with_activity(&mut mode, "p-live", 2, 0);+ let (lines, _) = mode.render_frame(120, 36);+ let shells_line = lines+ .iter()+ .map(flat)+ .find(|line| line.contains("$ 2 shells"))+ .expect("the shells line renders");+ assert!(+ !shells_line.contains("$0.00"),+ "the line has no cost cell: {shells_line:?}"+ );+ select_title(&mut mode, "$ 2 shells");+ mode.handle_key("enter");+ let opened = mode.opened.as_ref().expect("open recorded");+ assert_eq!(+ opened.selection,+ SessionSelection::Attach("p-live".to_string())+ );+ assert_eq!(opened.panel, Some(SessionPanel::Shells { shell_id: None }));+ assert_eq!(opened.selected_row_identity, "shells:file:/x/p.jsonl");+ assert!(opened.expanded_ancestors.is_empty());+}++#[test]+fn enter_on_a_nested_factory_line_opens_the_child_with_the_factory_panel() {+ let mut mode = mode_with_parent_and_child();+ mode.expanded_parents.insert("file:/x/p.jsonl".to_string());+ with_activity(&mut mode, "c-live", 0, 1);+ select_title(&mut mode, "\u{2699} 1 factory run");+ mode.handle_key("enter");+ let opened = mode.opened.as_ref().expect("open recorded");+ assert_eq!(+ opened.selection,+ SessionSelection::Attach("c-live".to_string())+ );+ assert_eq!(opened.panel, Some(SessionPanel::FactoryRuns));+ assert_eq!(opened.expanded_ancestors, vec!["p".to_string()]);+}++/// Each node's child lines sit one indent step past its row: the session's at column 4, an+/// expanded subagent's at column 8.+#[test]+fn child_lines_sit_one_indent_step_past_their_row() {+ let mut mode = mode_with_parent_and_child();+ mode.expanded_parents.insert("file:/x/p.jsonl".to_string());+ with_activity(&mut mode, "p-live", 2, 0);+ with_activity(&mut mode, "c-live", 1, 0);+ let (lines, _) = mode.render_frame(120, 36);+ let column = |needle: &str| {+ lines+ .iter()+ .map(flat)+ .find_map(|line| line.find(needle).map(|at| line[..at].chars().count()))+ .unwrap_or_else(|| panic!("no {needle:?} line"))+ };+ assert_eq!(+ [+ column("\u{2022} p name"),+ column("\u{25be} 1 subagent"),+ column("worker one"),+ column("$ 1 shell"),+ column("$ 2 shells"),+ ],+ [0, 4, 6, 8, 4]+ );+}diff --git a/crates/pa-tui/src/agents_view/tests/click_surface.rs b/crates/pa-tui/src/agents_view/tests/click_surface.rsindex dad1b1662a..176bdd7beb 100644--- a/crates/pa-tui/src/agents_view/tests/click_surface.rs+++ b/crates/pa-tui/src/agents_view/tests/click_surface.rs@@ -258,6 +258,22 @@ fn long_session_names_clip_to_the_name_column() {assert!(text.ends_with("$0.00 1s"));}+/// A nesting deeper than the name column clips its indent there: the row keeps the pane width+/// and its model cell stays under the legend's Model heading.+#[test]+fn deep_rows_clip_their_indent_to_the_name_column() {+ let (mut mode, index) = mode_with_row("deep", "mock-1");+ mode.rows[index].depth = 10;+ mode.selected = index;+ let layout = build_layout(&mode.rows, 120);+ assert!(4 * 10 + 2 > layout.name_width);+ let text = flat(&mode.render_row(&mode.rows[index], &layout, 120, false));+ assert_eq!(str_width(&text), 120);+ let model_at = str_width(&text[..text.find("mock-1").expect("model cell")]);+ let heading_at = str_width(&layout.legend[..layout.legend.find("Model").expect("heading")]);+ assert_eq!(model_at, heading_at);+}+#[test]fn short_session_names_pad_to_the_name_column() {let (mode, index) = mode_with_row("short name", "mock-1");@@ -268,3 +284,241 @@ fn short_session_names_pad_to_the_name_column() {let name_cell = format!("short name{}", " ".repeat(28 - 2 - 10));assert_eq!(text, expected_row(&name_cell, &layout));}++#[test]+fn an_orphans_bash_list_consumes_hidden_row_clicks_and_scrolls_its_output() {+ let _guard = crate::mouse_tracking::STATE_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ crate::mouse_tracking::enable(&mut std::io::stdout()).expect("enable");+ let (mut mode, index) = mode_with_row("hidden session", "mock-1");+ let mut bindings = crate::keybindings::KeybindingsConfig::new();+ bindings.insert("tui.select.up".to_string(), vec!["alt+k".to_string()]);+ bindings.insert("tui.select.down".to_string(), vec!["alt+j".to_string()]);+ mode.keybindings = crate::keybindings::KeybindingsManager::with_user_bindings(bindings);+ mode.render_frame(100, 24);+ let (hidden_row, _) = mode+ .click_rows+ .iter()+ .find(|(_, row_index)| *row_index == index)+ .copied()+ .expect("session row");+ mode.saved_catalog_loaded = true;+ mode.apply_persistent_shells(serde_json::json!({ "activities": [{+ "id": "shell-a", "command": "watch build", "status": "running", "persistent": true+ }]}));+ let row = mode+ .rows+ .iter()+ .find(|row| row.kind == RowKind::PersistentShell)+ .cloned()+ .expect("shell row");+ mode.open_persistent_shell(&row);+ mode.handle_shell_view_key("enter");+ let crate::bash_view::BashViewAction::OpenDetail { generation, .. } =+ mode.pending_shell_action.take().expect("tail action")+ else {+ panic!("open detail")+ };+ let output = (0..50)+ .map(|n| format!("output line {n}"))+ .collect::<Vec<_>>()+ .join("\n");+ mode.shell_view+ .as_mut()+ .unwrap()+ .set_output("shell-a", &output, generation);+ let before = mode.render_frame(100, 24);+ let selected = mode.selected;+ mode.handle_mouse(&mouse_report(hidden_row, true, false));+ mode.handle_mouse(&mouse_report(hidden_row, false, false));+ assert_eq!(mode.selected, selected);+ assert!(mode.running && mode.opened.is_none() && mode.shell_view.is_some());+ let wheel = crate::mouse::parse_sgr_mouse_event("\x1b[<64;3;3M").unwrap();+ mode.handle_mouse(&wheel);+ let after = mode.render_frame(100, 24);+ assert_ne!(before, after, "the wheel scrolls the shell's output");+ assert_eq!(mode.selected, selected);+ crate::mouse_tracking::disable(&mut std::io::stdout()).expect("disable");+}++#[test]+fn unverified_persistent_group_stays_visible_without_an_unsafe_cancel() {+ let (mut mode, _) = mode_with_row("holder", "mock-1");+ mode.saved_catalog_loaded = true;+ mode.apply_persistent_shells(serde_json::json!({ "activities": [{+ "id": "orphan", "command": "sleep 60", "sessionId": "deleted",+ "status": "unverified", "durationMs": 4_000, "persistent": true,+ }]}));+ let row = mode.persistent_shell_rows(&[]).remove(0);+ let layout = build_layout(std::slice::from_ref(&row), 100);+ assert_eq!(+ flat(&mode.render_row(&row, &layout, 100, false))+ .split_whitespace()+ .collect::<Vec<_>>(),+ ["$", "sleep", "60", "-", "-", "4.0s"]+ );+ mode.open_persistent_shell(&row);+ mode.handle_shell_view_key("enter");+ mode.pending_shell_action.take();+ mode.handle_shell_view_key("enter");+ assert!(mode.pending_shell_action.is_none());+}++#[test]+fn shell_rows_render_in_the_session_table_columns() {+ let mut mode = fresh_mode(vec![roster_entry("i", "idle", &parent_summary("i"))]);+ mode.rebuild_rows();+ let command = "python train.py --epochs 40 --config configs/sweep-large.yaml";+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ { "id": "s1", "command": command, "sessionId": "i", "status": "running", "durationMs": 754_000 },+ ]}));+ let (lines, _) = mode.render_frame(100, 30);+ let texts: Vec<String> = lines+ .iter()+ .map(|line| flat(line).trim_end().to_string())+ .collect();+ let find = |prefix: &str| {+ texts+ .iter()+ .find(|text| text.starts_with(prefix))+ .unwrap_or_else(|| panic!("{prefix:?} in:\n{}", texts.join("\n")))+ };+ let (legend, shell, session) = (find("Session"), find("$ python"), find("\u{2022} i name"));+ let layout = build_layout(&mode.rows, 100);+ let model_at = layout.name_width + 2;+ let column = |text: &str, at: usize| text.chars().skip(at).collect::<String>();+ assert_eq!(+ shell.chars().take(model_at).collect::<String>(),+ format!(+ "$ {} ",+ crate::agents_view_state::truncate_text(command, layout.name_width - 2)+ ),+ "the command clips to the Session column:\n{}",+ texts.join("\n")+ );+ assert!(column(legend, model_at).starts_with("Model"));+ assert!(+ column(session, model_at - 2).starts_with(" ")+ && !column(session, model_at).starts_with(' ')+ );+ assert_eq!(+ column(shell, model_at)+ .split_whitespace()+ .collect::<Vec<_>>(),+ ["-", "-", "12m", "34s"],+ "Model, Cost, and Age, then nothing"+ );+ assert_eq!(+ str_width(shell),+ str_width(legend),+ "the elapsed ends under Age"+ );+}++#[test]+fn finished_persistent_shells_never_show_the_persistent_shells_heading() {+ let mut mode = fresh_mode(vec![roster_entry("i", "idle", &parent_summary("i"))]);+ mode.rebuild_rows();+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ { "id": "s1", "command": "cargo build", "sessionId": "i", "status": "finished", "exitCode": 0 },+ { "id": "s2", "command": "sleep 600", "sessionId": "gone", "status": "finished", "exitCode": 143 },+ ]}));+ let (lines, _) = mode.render_frame(100, 30);+ let text = lines.iter().map(flat).collect::<Vec<_>>().join("\n");+ assert!(+ !text.contains("Persistent shells")+ && !text.contains("cargo build")+ && !text.contains("sleep 600"),+ "{text}"+ );+}++#[test]+fn the_persistent_shells_heading_and_the_orphans_bash_list_show_only_live_shells() {+ let mut mode = fresh_mode(vec![roster_entry("i", "idle", &parent_summary("i"))]);+ mode.apply_saved_loaded(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ { "id": "s1", "command": "cargo build", "sessionId": "gone", "status": "finished", "exitCode": 0 },+ { "id": "s2", "command": "cargo watch", "sessionId": "gone", "status": "running" },+ { "id": "s3", "command": "sleep 600", "sessionId": "gone", "status": "finished", "exitCode": 143 },+ ]}));+ let render = |mode: &mut AgentsViewMode| {+ let (lines, _) = mode.render_frame(100, 30);+ lines.iter().map(flat).collect::<Vec<_>>()+ };+ let texts = render(&mut mode);+ let heading = texts+ .iter()+ .position(|text| text.contains("Persistent shells (1)"))+ .unwrap_or_else(|| panic!("the heading in:\n{}", texts.join("\n")));+ assert!(+ texts[heading + 1].contains("$ cargo watch") && texts[heading + 2].trim().is_empty(),+ "exactly the running row under the heading:\n{}",+ texts.join("\n")+ );+ let row = mode+ .rows+ .iter()+ .find(|row| row.kind == RowKind::PersistentShell)+ .cloned()+ .expect("shell row");+ mode.open_persistent_shell(&row);+ let bash_list = render(&mut mode).join("\n");+ assert!(+ bash_list.contains("cargo watch")+ && !bash_list.contains("cargo build")+ && !bash_list.contains("sleep 600"),+ "the Bash list keeps only the live shell:\n{bash_list}"+ );+}++#[test]+fn persistent_shells_head_the_list_above_every_section() {+ let mut mode = fresh_mode(vec![+ roster_entry("r", "running", &parent_summary("r")),+ roster_entry("i", "idle", &parent_summary("i")),+ ]);+ mode.apply_saved_loaded(vec![+ saved_catalog_row("/x/old-a.jsonl", "old-a", "old session a"),+ saved_catalog_row("/x/old-b.jsonl", "old-b", "old session b"),+ ]);+ mode.rebuild_rows();+ mode.selected = mode+ .rows+ .iter()+ .position(|row| row.summary.get("sessionId").and_then(Value::as_str) == Some("i"))+ .expect("idle row");+ mode.sync_selected_row_state();+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ { "id": "s1", "command": "cargo watch", "sessionId": "i", "status": "running" },+ { "id": "s2", "command": "sleep 600", "sessionId": "gone", "status": "running" },+ ]}));++ assert_eq!(+ mode.rows[mode.selected].summary["sessionId"], "i",+ "the late shells keep the selection on its session"+ );+ let (lines, _) = mode.render_frame(100, 40);+ let texts: Vec<String> = lines.iter().map(flat).collect();+ let position = |needle: &str| {+ texts+ .iter()+ .position(|text| text.contains(needle))+ .unwrap_or_else(|| panic!("{needle:?} in:\n{}", texts.join("\n")))+ };+ let shells = position("Persistent shells (2)");+ assert!(+ texts[shells + 1].contains("$ cargo watch") && texts[shells + 2].contains("$ sleep 600"),+ "the shell rows sit under their heading:\n{}",+ texts.join("\n")+ );+ assert_eq!(texts[shells + 3].trim(), "");+ assert_eq!(position("Running (1)"), shells + 4);+ assert!(position("Running (1)") < position("Idle (1)"));+ assert!(position("Idle (1)") < position("Inactive (2)"));+ assert!(+ mode.click_rows.windows(2).all(|pair| pair[0].1 < pair[1].1),+ "the row order is the display order"+ );+}diff --git a/crates/pa-tui/src/agents_view/tests/cost_aggregates.rs b/crates/pa-tui/src/agents_view/tests/cost_aggregates.rsindex 7667beda13..c07c2ffd69 100644--- a/crates/pa-tui/src/agents_view/tests/cost_aggregates.rs+++ b/crates/pa-tui/src/agents_view/tests/cost_aggregates.rs@@ -29,19 +29,25 @@ fn the_summary_line_renders_the_aggregate_in_the_cost_column() {roster_entry("x1", "inactive", &inactive_child),];mode.rebuild_rows();- assert_eq!(mode.rows[1].title, "4 subagents (2 running)");+ assert_eq!(mode.rows[1].title, "4 subagents · 2 running");let (lines, _) = mode.render_frame(120, 36);let flat_lines: Vec<String> = lines.iter().map(flat).collect();let summary = flat_lines.iter()- .find(|line| line.contains("4 subagents (2 running)"))+ .find(|line| line.contains("4 subagents · 2 running")).expect("the ONE line renders");let parent_line = flat_lines.iter().find(|line| line.contains("p name")).expect("parent row renders");- let cost_at = summary.find("$4.75").expect("the aggregate prints");- let parent_cost_at = parent_line.find("$5.00").expect("the parent total prints");+ let cost_at = summary+ .find("$4.75")+ .map(|at| str_width(&summary[..at]))+ .expect("the aggregate prints");+ let parent_cost_at = parent_line+ .find("$5.00")+ .map(|at| str_width(&parent_line[..at]))+ .expect("the parent total prints");assert_eq!(cost_at, parent_cost_at,"the aggregate shares the agent rows' Cost column"@@ -105,12 +111,12 @@ fn a_search_keeps_the_rows_totals() {#[test]fn the_summary_line_renders_zero_when_nothing_bills() {let mut mode = mode_with_parent_and_child();- assert_eq!(mode.rows[1].title, "1 subagents (1 running)");+ assert_eq!(mode.rows[1].title, "1 subagent · 1 running");let (lines, _) = mode.render_frame(120, 36);let summary = lines.iter().map(flat)- .find(|line| line.contains("1 subagents (1 running)"))+ .find(|line| line.contains("1 subagent · 1 running")).expect("the ONE line renders");assert!(summary.contains("$0.00"),@@ -136,21 +142,27 @@ fn the_summary_line_renders_the_aggregate_in_the_all_done_state() {];mode.rebuild_rows();assert_eq!(- mode.rows[1].title, "2 subagents (0 running)",+ mode.rows[1].title, "2 subagents · 0 running","the ONE line keeps its row in the all-done state");let (lines, _) = mode.render_frame(120, 36);let flat_lines: Vec<String> = lines.iter().map(flat).collect();let summary = flat_lines.iter()- .find(|line| line.contains("2 subagents (0 running)"))+ .find(|line| line.contains("2 subagents · 0 running")).expect("the ONE line renders in the all-done state");let parent_line = flat_lines.iter().find(|line| line.contains("p name")).expect("parent row renders");- let cost_at = summary.find("$2.00").expect("the aggregate prints");- let parent_cost_at = parent_line.find("$2.25").expect("the parent total prints");+ let cost_at = summary+ .find("$2.00")+ .map(|at| str_width(&summary[..at]))+ .expect("the aggregate prints");+ let parent_cost_at = parent_line+ .find("$2.25")+ .map(|at| str_width(&parent_line[..at]))+ .expect("the parent total prints");assert_eq!(cost_at, parent_cost_at,"the summary line shares the agent rows' Cost column"@@ -191,7 +203,7 @@ fn aggregate_survives_the_incident_notice_render_path() {);let summary = text.iter()- .find(|line| line.contains("1 subagents (0 running)"))+ .find(|line| line.contains("1 subagent · 0 running")).expect("the ONE line renders behind the notice");assert!(summary.contains("$1.25"),@@ -224,7 +236,7 @@ fn aggregate_survives_the_click_surface_render_path() {let flat_lines: Vec<String> = lines.iter().map(flat).collect();let summary = flat_lines.iter()- .find(|line| line.contains("1 subagents (0 running)"))+ .find(|line| line.contains("1 subagent · 0 running")).expect("the ONE line renders");assert!(summary.contains("$1.25"),@@ -251,7 +263,7 @@ fn aggregate_survives_the_click_surface_render_path() {);let summary = flat_lines.iter()- .find(|line| line.contains("1 subagents (0 running)"))+ .find(|line| line.contains("1 subagent · 0 running")).expect("the ONE line still renders expanded");assert!(summary.contains("$1.25"),diff --git a/crates/pa-tui/src/agents_view/tests/hover_band.rs b/crates/pa-tui/src/agents_view/tests/hover_band.rsindex 1febf6bd90..525f2b71e4 100644--- a/crates/pa-tui/src/agents_view/tests/hover_band.rs+++ b/crates/pa-tui/src/agents_view/tests/hover_band.rs@@ -125,7 +125,7 @@ fn the_hover_and_the_selection_share_the_one_band_color() {crate::mouse_tracking::disable(&mut std::io::stdout()).expect("disable");}-/// The dropdown's own rows hover like every other row: the merged `N subagents (M running)`+/// The dropdown's own rows hover like every other row: the merged `N subagents · M running`/// summary and the children it expands both carry the light band under the mouse.#[test]fn the_merged_dropdown_rows_hover_like_every_row() {@@ -136,7 +136,7 @@ fn the_merged_dropdown_rows_hover_like_every_row() {crate::mouse_tracking::enable(&mut std::io::stdout()).expect("enable");let mut mode = mode_with_parent_and_child();let (lines, _) = mode.render_frame(120, 36);- let summary = row_of(&lines, "1 subagents (1 running)").expect("the merged line renders");+ let summary = row_of(&lines, "1 subagent · 1 running").expect("the merged line renders");let light = mode.theme.hover_row_style().bg;mode.handle_mouse(&hover_motion(summary));assert_eq!(mode.hover_row, Some(summary));diff --git a/crates/pa-tui/src/agents_view/tests/key_bindings.rs b/crates/pa-tui/src/agents_view/tests/key_bindings.rsindex 4cb4af4f0b..89e5ba6024 100644--- a/crates/pa-tui/src/agents_view/tests/key_bindings.rs+++ b/crates/pa-tui/src/agents_view/tests/key_bindings.rs@@ -95,6 +95,7 @@ fn new_key_in_a_scoped_view_creates_under_the_scope_root() {has_children: false,status_message: None,cwd: Some("/work/p".into()),+ panel: None,}));}diff --git a/crates/pa-tui/src/agents_view/tests/running_lines.rs b/crates/pa-tui/src/agents_view/tests/running_lines.rsindex ea20f350db..87ababfce2 100644--- a/crates/pa-tui/src/agents_view/tests/running_lines.rs+++ b/crates/pa-tui/src/agents_view/tests/running_lines.rs@@ -152,7 +152,7 @@ fn mode_with_mixed_children() -> AgentsViewMode {fn enter_expands_the_one_line_to_the_full_roster_running_first() {let mut mode = mode_with_mixed_children();assert_eq!(mode.rows.len(), 2);- assert_eq!(mode.rows[1].title, "4 subagents (2 running)");+ assert_eq!(mode.rows[1].title, "4 subagents · 2 running");assert_eq!(mode.rows[1].identity, "subagents:file:/x/p.jsonl");mode.handle_key("down");mode.handle_key("enter");@@ -198,7 +198,7 @@ fn live_transitions_update_the_one_line_and_keep_the_selection() {.iter().find(|row| row.kind == RowKind::SubagentSummary).expect("the ONE line");- assert_eq!(line.title, "4 subagents (1 running)");+ assert_eq!(line.title, "4 subagents · 1 running");assert!(line.expanded, "the line stays open through the flip");let settled = mode.rows@@ -217,7 +217,7 @@ fn live_transitions_update_the_one_line_and_keep_the_selection() {.iter().find(|row| row.kind == RowKind::SubagentSummary).expect("the ONE line");- assert_eq!(line.title, "4 subagents (2 running)");+ assert_eq!(line.title, "4 subagents · 2 running");assert!(mode.rows.iter()@@ -240,11 +240,11 @@ fn frame_renders_the_one_line() {));mode.rebuild_rows();assert_eq!(mode.rows.len(), 2, "the parent and its ONE line");- assert_eq!(mode.rows[1].title, "3 subagents (2 running)");+ assert_eq!(mode.rows[1].title, "3 subagents · 2 running");let (lines, _) = mode.render_frame(120, 36);let frame = lines.iter().map(flat).collect::<Vec<_>>().join("\n");assert!(- frame.contains("\u{25b8} 3 subagents (2 running)"),+ frame.contains("\u{25b8} 3 subagents · 2 running"),"frame: {frame}");assert!(diff --git a/crates/pa-tui/src/agents_view/tests/shell_enter.rs b/crates/pa-tui/src/agents_view/tests/shell_enter.rsnew file mode 100644index 0000000000..02e75b0685--- /dev/null+++ b/crates/pa-tui/src/agents_view/tests/shell_enter.rs@@ -0,0 +1,338 @@+//! Enter on a persistent shell row: a shell whose session still exists opens that session with its+//! Bash panel on the shell; an orphan (its session deleted) opens the Bash list over the orphans.++use super::*;+use crate::interactive::SessionPanel;++fn shell(id: &str, command: &str, session: &str) -> serde_json::Value {+ serde_json::json!({+ "id": id, "command": command, "sessionId": session, "status": "running",+ "pid": 4242, "startedAt": "2026-01-01T00:00:00+00:00", "durationMs": 12_400,+ })+}++fn enter_on_shell(mode: &mut AgentsViewMode, id: &str) {+ mode.render_frame(100, 30);+ mode.selected = mode+ .rows+ .iter()+ .position(|row| row.identity == format!("shell:{id}"))+ .unwrap_or_else(|| panic!("no shell row {id:?}: {:?}", mode.rows));+ mode.handle_key("enter");+}++fn frame(mode: &mut AgentsViewMode) -> Vec<String> {+ let (lines, _) = mode.render_frame(100, 30);+ lines+ .iter()+ .map(|line| flat(line).trim_end().to_string())+ .collect()+}++#[test]+fn enter_on_a_live_sessions_shell_opens_the_session_on_its_bash_panel() {+ let mut mode = fresh_mode(vec![roster_entry("p", "idle", &parent_summary("p"))]);+ mode.apply_saved_loaded(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("s1", "cargo watch", "p"),+ shell("s2", "sleep 600", "p"),+ ]}));+ enter_on_shell(&mut mode, "s2");+ let opened = mode.opened.as_ref().expect("the session opens");+ assert_eq!(+ opened.selection,+ SessionSelection::Attach("p-live".to_string())+ );+ assert_eq!(+ opened.panel,+ Some(SessionPanel::Shells {+ shell_id: Some("s2".to_string())+ })+ );+ assert_eq!(opened.selected_row_identity, "shell:s2");+}++#[test]+fn enter_on_a_collapsed_subagents_shell_opens_the_subagent() {+ let mut mode = mode_with_parent_and_child();+ mode.apply_saved_loaded(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("s1", "cargo watch", "c"),+ ]}));+ assert!(+ !mode.rows.iter().any(|row| row.kind == RowKind::Subagent),+ "the child row is collapsed"+ );+ enter_on_shell(&mut mode, "s1");+ let opened = mode.opened.as_ref().expect("the subagent opens");+ assert_eq!(+ opened.selection,+ SessionSelection::Attach("c-live".to_string())+ );+ assert_eq!(opened.expanded_ancestors, vec!["p".to_string()]);+ assert_eq!(+ opened.panel,+ Some(SessionPanel::Shells {+ shell_id: Some("s1".to_string())+ })+ );+}++#[test]+fn enter_on_a_saved_sessions_shell_resumes_the_session() {+ let mut mode = fresh_mode(Vec::new());+ mode.apply_saved_loaded(vec![saved_catalog_row(+ "/x/old.jsonl",+ "old",+ "old session",+ )]);+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("s1", "cargo watch", "old"),+ ]}));+ enter_on_shell(&mut mode, "s1");+ let opened = mode.opened.as_ref().expect("the saved session resumes");+ assert_eq!(+ opened.selection,+ SessionSelection::Resume(PathBuf::from("/x/old.jsonl"))+ );+ assert_eq!(+ opened.panel,+ Some(SessionPanel::Shells {+ shell_id: Some("s1".to_string())+ })+ );+}++#[test]+fn enter_on_a_shell_while_the_catalog_loads_opens_nothing() {+ let mut mode = fresh_mode(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("s1", "cargo watch", "unknown"),+ ]}));+ enter_on_shell(&mut mode, "s1");+ assert!(mode.opened.is_none() && mode.shell_view.is_none());+ assert_eq!(mode.status_text(), Some(ANCHOR_LOADING_HINT));+}++/// The first catalog page holds only `newer`; the store has more files after it.+fn mode_with_a_partial_catalog() -> AgentsViewMode {+ let mut mode = fresh_mode(Vec::new());+ mode.apply_saved_loaded(vec![saved_catalog_row("/x/new.jsonl", "new", "newer")]);+ mode.rebuild_rows();+ mode.finish_saved_page(Some(SavedMore {+ cursor: "page-two".to_string(),+ remaining: 300,+ }));+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("s1", "cargo watch", "older"),+ ]}));+ mode+}++#[test]+fn enter_on_a_shell_of_a_session_past_the_loaded_pages_opens_that_session() {+ let mut mode = mode_with_a_partial_catalog();+ enter_on_shell(&mut mode, "s1");+ assert!(+ mode.opened.is_none() && mode.shell_view.is_none(),+ "a partial catalog cannot prove the session deleted"+ );+ assert_eq!(+ mode.next_saved_fetch(),+ Some(("page-two".to_string(), None)),+ "the daemon walks the rest of the store"+ );+ mode.buffer_saved_stream_item(saved_catalog_row("/x/older.jsonl", "older", "older"));+ mode.flush_saved_stream();+ let opened = mode.opened.as_ref().expect("the session opens once listed");+ assert_eq!(+ opened.selection,+ SessionSelection::Resume(PathBuf::from("/x/older.jsonl"))+ );+ assert_eq!(+ opened.panel,+ Some(SessionPanel::Shells {+ shell_id: Some("s1".to_string())+ })+ );+}++#[test]+fn enter_after_a_failed_store_walk_retries_the_walk() {+ let mut mode = mode_with_a_partial_catalog();+ enter_on_shell(&mut mode, "s1");+ // The continuation fails (the loop's `SavedFailed` arm).+ mode.settle_anchor_wait_on_saved_failure();+ mode.saved_fetch_failed = true;+ assert!(mode.next_saved_fetch().is_none());+ enter_on_shell(&mut mode, "s1");+ assert!(+ !mode.take_saved_fetch_rearm(),+ "the retry never refetches the first page over the loaded rows"+ );+ assert_eq!(+ mode.next_saved_fetch(),+ Some(("page-two".to_string(), None)),+ "the second Enter resumes the failed walk"+ );+}++#[test]+fn enter_on_a_shell_of_a_session_missing_from_the_whole_store_opens_the_orphans() {+ let mut mode = mode_with_a_partial_catalog();+ enter_on_shell(&mut mode, "s1");+ mode.upsert_saved(Vec::new());+ mode.rebuild_rows();+ mode.finish_saved_page(None);+ assert!(mode.opened.is_none());+ let text = frame(&mut mode).join("\n");+ assert!(+ text.contains("Session deleted") && text.contains("cargo watch"),+ "{text}"+ );+}++#[test]+fn enter_on_an_orphan_lists_the_orphans_with_it_selected() {+ let mut mode = fresh_mode(vec![roster_entry("p", "idle", &parent_summary("p"))]);+ mode.apply_saved_loaded(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("s1", "cargo watch", "p"),+ shell("o1", "tail -f build.log", "gone"),+ shell("o2", "sleep 600", "gone-too"),+ ]}));+ enter_on_shell(&mut mode, "o2");+ assert!(mode.opened.is_none());+ assert!(+ mode.pending_shell_action.is_none(),+ "the list opens without a detail fetch"+ );+ let lines = frame(&mut mode);+ let text = lines.join("\n");+ assert!(+ lines[1].starts_with(" Bash") && lines[1].ends_with("2 running"),+ "{text}"+ );+ assert_eq!(lines[2], " Session deleted", "{text}");+ for column in ["Command", "Duration", "PID", "Status"] {+ assert!(lines[4].contains(column), "{text}");+ }+ let selected = lines+ .iter()+ .find(|line| line.starts_with('\u{203a}'))+ .unwrap_or_else(|| panic!("a selected row in:\n{text}"));+ assert!(selected.contains("sleep 600"), "{text}");+ assert!(+ text.contains("tail -f build.log") && !text.contains("cargo watch"),+ "only the orphans list:\n{text}"+ );+ assert!(text.contains("open"), "the list hint:\n{text}");++ mode.handle_key("enter");+ let detail = frame(&mut mode).join("\n");+ assert!(detail.contains("pid 4242"), "{detail}");+}++#[test]+fn stopping_an_orphan_keeps_its_finished_detail_until_back() {+ let mut mode = fresh_mode(Vec::new());+ mode.apply_saved_loaded(Vec::new());+ let running = serde_json::json!({ "activities": [+ shell("o1", "tail -f build.log", "gone"),+ shell("o2", "sleep 600", "gone"),+ ]});+ mode.apply_persistent_shells(running);+ enter_on_shell(&mut mode, "o2");+ mode.handle_key("enter");+ assert!(matches!(+ mode.pending_shell_action.take(),+ Some(crate::bash_view::BashViewAction::OpenDetail { .. })+ ));+ assert!(frame(&mut mode).join("\n").contains("Cancel command"));+ mode.handle_key("enter");+ assert_eq!(+ mode.pending_shell_action.take(),+ Some(crate::bash_view::BashViewAction::Kill {+ id: "o2".to_string()+ })+ );+ let mut stopped = shell("o2", "sleep 600", "gone");+ stopped["status"] = "finished".into();+ stopped["exitCode"] = 143.into();+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("o1", "tail -f build.log", "gone"),+ stopped,+ ]}));+ let detail = frame(&mut mode).join("\n");+ assert!(+ detail.contains("sleep 600") && detail.contains("exit 143"),+ "{detail}"+ );+ assert!(!detail.contains("Cancel command"), "{detail}");++ mode.handle_key("left");+ let list = frame(&mut mode).join("\n");+ assert!(+ list.contains("1 running") && !list.contains("sleep 600"),+ "{list}"+ );+ mode.handle_key("escape");+ assert!(mode.shell_view.is_none());+ let rows = frame(&mut mode).join("\n");+ assert!(+ rows.contains("Persistent shells (1)") && !rows.contains("sleep 600"),+ "{rows}"+ );+}++#[test]+fn a_refused_stop_keeps_its_error_across_a_duration_tick() {+ let mut mode = fresh_mode(Vec::new());+ mode.apply_saved_loaded(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("o1", "sleep 600", "gone"),+ ]}));+ enter_on_shell(&mut mode, "o1");+ mode.handle_key("enter");+ mode.pending_shell_action.take();+ mode.shell_view.as_mut().expect("the overlay").set_error(+ "Could not kill bash command: refused".to_string(),+ false,+ None,+ );+ let mut ticked = shell("o1", "sleep 600", "gone");+ ticked["durationMs"] = 14_400.into();+ mode.apply_persistent_shells(serde_json::json!({ "activities": [ticked] }));+ let text = frame(&mut mode).join("\n");+ assert!(text.contains("refused"), "{text}");+}++#[test]+fn the_orphan_overlay_follows_a_terminal_resize() {+ let mut mode = fresh_mode(Vec::new());+ mode.apply_saved_loaded(Vec::new());+ mode.apply_persistent_shells(serde_json::json!({ "activities": [+ shell("o1", "sleep 600", "gone"),+ ]}));+ enter_on_shell(&mut mode, "o1");+ mode.handle_key("enter");+ let Some(crate::bash_view::BashViewAction::OpenDetail { id, generation }) =+ mode.pending_shell_action.take()+ else {+ panic!("the detail opens")+ };+ let tail = (1..=100)+ .map(|n| format!("line {n}"))+ .collect::<Vec<_>>()+ .join("\n");+ mode.shell_view+ .as_mut()+ .expect("the overlay")+ .set_output(&id, &tail, generation);+ let (lines, _) = mode.render_frame(100, 12);+ let text = lines.iter().map(flat).collect::<Vec<_>>().join("\n");+ assert!(+ text.contains("line 100") && text.contains("Cancel command"),+ "the shrunk frame keeps the newest output and the action row:\n{text}"+ );+}diff --git a/crates/pa-tui/src/agents_view_forest.rs b/crates/pa-tui/src/agents_view_forest.rsindex c91dae3732..7cb1b8ae1b 100644--- a/crates/pa-tui/src/agents_view_forest.rs+++ b/crates/pa-tui/src/agents_view_forest.rs@@ -54,7 +54,7 @@ pub struct AgentsViewRow {pub has_spawn_code: bool,}-/// The four list row shapes (TS `AgentsViewRowKind`).+/// The list row shapes (TS `AgentsViewRowKind`, plus the activity lines and persistent shells).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RowKind {/// A top-level agent row.@@ -65,6 +65,12 @@ pub enum RowKind {Subagent,/// A read-only spawn-program line.Code,+ /// The node's own running kernel shells line.+ Shells,+ /// The node's own live factory runs line.+ FactoryRuns,+ /// One machine-wide persistent shell with its assigned session.+ PersistentShell,}/// The summary line's identity prefix (the `subagents:` prefix, so a carried selection@@ -84,7 +90,12 @@ impl AgentsViewRow {pub fn selectable(&self) -> bool {match self.kind {RowKind::Code => false,- RowKind::Agent | RowKind::SubagentSummary | RowKind::Subagent => true,+ RowKind::Agent+ | RowKind::SubagentSummary+ | RowKind::Subagent+ | RowKind::Shells+ | RowKind::FactoryRuns+ | RowKind::PersistentShell => true,}}}@@ -97,6 +108,14 @@ pub struct SelectionKey {pub active_session_id: Option<String>,}+/// One live session's own activity counts, keyed by its `activeSessionId`: the shells and+/// factory-run lines render them.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct SessionActivity {+ pub shells: usize,+ pub factory_runs: usize,+}+/// One recursive rollup over the record hierarchy (TS/// `AgentsViewRecursiveRollup`).#[derive(Debug, Clone, Copy, Default, PartialEq)]diff --git a/crates/pa-tui/src/agents_view_forest/rows.rs b/crates/pa-tui/src/agents_view_forest/rows.rsindex 1ec8917023..194d37d8cc 100644--- a/crates/pa-tui/src/agents_view_forest/rows.rs+++ b/crates/pa-tui/src/agents_view_forest/rows.rs@@ -4,7 +4,7 @@ use serde_json::Value;use super::lineage::{depth_consistent_parent, is_subagent_descendant};use super::{- session_model, session_title, AgentsViewRow, AgentsViewScope, Rollup, RowKind,+ session_model, session_title, AgentsViewRow, AgentsViewScope, Rollup, RowKind, SessionActivity,SUMMARY_ROW_PREFIX,};use crate::agents_view_state::{@@ -27,6 +27,8 @@ struct BaseRow {descendant_cost: f64,descendant_count: usize,running_subagent_count: usize,+ /// The session's own shells and factory runs (never subtree-aggregated).+ activity: SessionActivity,record: usize,search_score: Option<f64>,}@@ -40,6 +42,7 @@ pub(crate) fn build_rows<S: std::hash::BuildHasher + Default>(expanded: &HashSet<String, S>,program_shown: &HashSet<String, S>,rollups: &HashMap<String, Rollup, S>,+ activity: &HashMap<String, SessionActivity, S>,anchor: Option<&str>,) -> Vec<AgentsViewRow> {let now = now_ms();@@ -96,6 +99,12 @@ pub(crate) fn build_rows<S: std::hash::BuildHasher + Default>();let rollup = rollups.get(&record.identity).copied().unwrap_or_default();let model = session_model(&summary);+ let activity = summary+ .get("activeSessionId")+ .and_then(Value::as_str)+ .and_then(|active| activity.get(active))+ .copied()+ .unwrap_or_default();base.push(BaseRow {kind,section: record.section,@@ -113,6 +122,7 @@ pub(crate) fn build_rows<S: std::hash::BuildHasher + Default>(descendant_cost: rollup.descendants,descendant_count: rollup.descendant_count,running_subagent_count: 0,+ activity,summary,record: position,});@@ -244,8 +254,8 @@ struct RowForest<'a, S: std::hash::BuildHasher + Default> {}impl<S: std::hash::BuildHasher + Default> RowForest<'_, S> {- /// Emit one row, then its ONE summary line, then its expanded children: the line expands to- /// the FULL roster in one group, the running children first.+ /// Emit one row, then its subagents block, then its shells and factory-run lines (after the+ /// block, so an expanded summary line stays directly above its children).fn emit(&self,index: usize,@@ -255,9 +265,21 @@ impl<S: std::hash::BuildHasher + Default> RowForest<'_, S> {) {let row = &self.base[index];rows.push(agents_row(row, depth, parent_identity));- let Some(children) = self.children_by_parent.get(&index) else {- return;- };+ if let Some(children) = self.children_by_parent.get(&index) {+ self.emit_subagents(row, children, depth, rows);+ }+ rows.extend(activity_rows(row, depth + 1));+ }++ /// The ONE summary line, then its expanded children: the line expands to the FULL roster in+ /// one group, the running children first.+ fn emit_subagents(+ &self,+ row: &BaseRow,+ children: &[usize],+ depth: usize,+ rows: &mut Vec<AgentsViewRow>,+ ) {if children.is_empty() {return;}@@ -270,7 +292,7 @@ impl<S: std::hash::BuildHasher + Default> RowForest<'_, S> {if !is_expanded {return;}- let mut sorted = children.clone();+ let mut sorted = children.to_vec();sorted.sort_by(|a, b| compare_base(&self.base[*a], &self.base[*b], self.anchor));// One group, one order (the operator's contract): the running rows first — the// partition is explicit rather than left to the comparator's section ordering.@@ -328,7 +350,7 @@ fn agents_row(row: &BaseRow, depth: usize, parent_identity: Option<&str>) -> Age}/// The subagents line under one agent (the operator's 2026-09-28 one-dropdown directive):-/// `"{total} subagents ({running} running)"` — `total` = the FULL descendant roster, `running` =+/// `"{total} subagents · {running} running"` — `total` = the FULL descendant roster, `running` =/// the running subset — expanding to the whole roster in one group, the running rows first (a/// sanctioned divergence: TS titles one `"{n} subagents running"` line). The line reuses its/// parent's summary so the open action and selection keys resolve the parent; the `cost` cell is@@ -342,7 +364,10 @@ fn merged_summary_row(parent: &BaseRow, depth: usize, expanded: bool) -> AgentsVidentity: format!("{SUMMARY_ROW_PREFIX}{}", parent.identity),parent_identity: Some(parent.identity.clone()),summary: parent.summary.clone(),- title: format!("{total} subagents ({running} running)"),+ title: format!(+ "{total} subagent{} \u{b7} {running} running",+ if total == 1 { "" } else { "s" }+ ),model: String::new(),cost: parent.descendant_cost,age: String::new(),@@ -354,6 +379,50 @@ fn merged_summary_row(parent: &BaseRow, depth: usize, expanded: bool) -> AgentsV}}+/// The node's own `$ N shells` and `⚙ N factory runs` lines, each only when its count is nonzero.+/// Like the summary line they reuse the parent's summary, so the open action resolves the parent.+fn activity_rows(parent: &BaseRow, depth: usize) -> Vec<AgentsViewRow> {+ let line = |kind: RowKind, prefix: &str, title: String| AgentsViewRow {+ kind,+ section: parent.section,+ identity: format!("{prefix}:{}", parent.identity),+ parent_identity: Some(parent.identity.clone()),+ summary: parent.summary.clone(),+ title,+ model: String::new(),+ cost: 0.0,+ age: String::new(),+ depth,+ descendant_count: 0,+ running_subagent_count: 0,+ expanded: false,+ has_spawn_code: false,+ };+ let SessionActivity {+ shells,+ factory_runs,+ } = parent.activity;+ let mut rows = Vec::new();+ if shells > 0 {+ rows.push(line(+ RowKind::Shells,+ "shells",+ format!("$ {shells} shell{}", if shells == 1 { "" } else { "s" }),+ ));+ }+ if factory_runs > 0 {+ rows.push(line(+ RowKind::FactoryRuns,+ "factory",+ format!(+ "\u{2699} {factory_runs} factory run{}",+ if factory_runs == 1 { "" } else { "s" }+ ),+ ));+ }+ rows+}+/// The summary's `spawnCode` is a string with a non-blank trim — the ONE predicate and the/// value the program rows render, never a second read.fn spawn_code(summary: &Value) -> Option<&str> {diff --git a/crates/pa-tui/src/agents_view_forest/tests.rs b/crates/pa-tui/src/agents_view_forest/tests.rsindex 3e64feb87e..7c326ce1d7 100644--- a/crates/pa-tui/src/agents_view_forest/tests.rs+++ b/crates/pa-tui/src/agents_view_forest/tests.rs@@ -40,6 +40,15 @@ fn rows_for(roster: &[serde_json::Value],scope: Option<&AgentsViewScope>,expanded: &[&str],+) -> Vec<AgentsViewRow> {+ rows_with_activity(roster, scope, expanded, &HashMap::new())+}++fn rows_with_activity(+ roster: &[serde_json::Value],+ scope: Option<&AgentsViewScope>,+ expanded: &[&str],+ activity: &HashMap<String, SessionActivity>,) -> Vec<AgentsViewRow> {let records = reconcile_unified_sessions(roster, &[], None);let rollups = compute_rollups(&records);@@ -50,6 +59,7 @@ fn rows_for(&expanded,&HashSet::default(),&rollups,+ activity,None,)}@@ -82,7 +92,7 @@ fn an_opened_child_nests_under_its_parent() {);assert!(rows.iter().any(|row| {- row.kind == RowKind::SubagentSummary && row.title == "1 subagents (0 running)"+ row.kind == RowKind::SubagentSummary && row.title == "1 subagent · 0 running"}),"the parent's ONE line labels the aggregate: {rows:?}");@@ -152,7 +162,7 @@ fn session_model_reads_every_wire_shape() {);}-/// The ONE line under a parent (the operator's 2026-09-28 merge): `1 subagents (1 running)`,+/// The ONE line under a parent (the operator's 2026-09-28 merge): `1 subagent · 1 running`,/// with the `subagents:` identity, expanding to the child at depth 1.#[test]fn parent_with_child_renders_the_summary_row_and_nested_child() {@@ -166,13 +176,13 @@ fn parent_with_child_renders_the_summary_row_and_nested_child() {assert_eq!(rows[1].kind, RowKind::SubagentSummary);assert_eq!(rows[1].identity, "subagents:file:/x/p.jsonl");assert_eq!(rows[1].parent_identity.as_deref(), Some("file:/x/p.jsonl"));- assert_eq!(rows[1].title, "1 subagents (1 running)");+ assert_eq!(rows[1].title, "1 subagent · 1 running");assert!(!rows[1].expanded);assert_eq!(rows[0].descendant_count, 1);assert_eq!(rows[0].running_subagent_count, 1);let rows = rows_for(&roster, None, &["file:/x/p.jsonl"]);assert_eq!(rows.len(), 3);- assert_eq!(rows[1].title, "1 subagents (1 running)");+ assert_eq!(rows[1].title, "1 subagent · 1 running");assert!(rows[1].expanded);assert_eq!(rows[2].kind, RowKind::Subagent);assert_eq!(rows[2].depth, 1);@@ -194,7 +204,7 @@ fn deeper_descendants_roll_up_and_nest_recursively() {assert_eq!(rows[0].running_subagent_count, 1);assert_eq!(rows.len(), 2);assert_eq!(rows[1].kind, RowKind::SubagentSummary);- assert_eq!(rows[1].title, "2 subagents (1 running)");+ assert_eq!(rows[1].title, "2 subagents · 1 running");let rows = rows_for(&roster, None, &["file:/x/p.jsonl"]);assert_eq!(rows.iter()@@ -207,7 +217,7 @@ fn deeper_descendants_roll_up_and_nest_recursively() {(RowKind::SubagentSummary, 2),]);- assert_eq!(rows[3].title, "1 subagents (1 running)");+ assert_eq!(rows[3].title, "1 subagent · 1 running");assert_eq!(rows[3].parent_identity, Some(rows[2].identity.clone()));// Expanding the child's line reveals the grandchild at depth 2 (the expansion keys off// the rendered row's parent-qualified `agent:` alias).@@ -225,7 +235,7 @@ fn deeper_descendants_roll_up_and_nest_recursively() {}/// The summary row's title is count-only (the operator's 2026-09-26 follow-up): `"{total}-/// subagents ({running} running)"`, no model mix.+/// subagents · {running} running"`, no model mix.#[test]fn summary_rows_stay_count_only() {let mut glm_one = child_summary("c1", "p", "worker one");@@ -247,7 +257,7 @@ fn summary_rows_stay_count_only() {.iter().find(|row| row.kind == RowKind::SubagentSummary).expect("summary row");- assert_eq!(summary.title, "4 subagents (0 running)");+ assert_eq!(summary.title, "4 subagents · 0 running");assert!(summary.model.is_empty(), "no model rides the summary row");let rows = rows_for(&roster, None, &["file:/x/p.jsonl"]);let child = rows@@ -259,7 +269,7 @@ fn summary_rows_stay_count_only() {.iter().find(|row| row.kind == RowKind::SubagentSummary && row.depth == 2).expect("nested summary row");- assert_eq!(nested.title, "1 subagents (0 running)");+ assert_eq!(nested.title, "1 subagent · 0 running");// A FOUR-level chain folds at every depth: the great-grandchild still reaches the root's// count (the tally walk's dynamic bound).let mut gc = child_summary("gc", "c", "grandkid");@@ -279,7 +289,7 @@ fn summary_rows_stay_count_only() {.iter().find(|row| row.kind == RowKind::SubagentSummary).expect("summary row");- assert_eq!(summary.title, "3 subagents (0 running)");+ assert_eq!(summary.title, "3 subagents · 0 running");assert_eq!(rows[0].descendant_count, 3);}@@ -293,13 +303,13 @@ fn idle_descendants_aggregate_into_the_summary_row() {roster_entry("gc", "idle", &grandchild),];let rows = rows_for(&roster, None, &[]);- assert_eq!(rows[1].title, "2 subagents (0 running)");+ assert_eq!(rows[1].title, "2 subagents · 0 running");let rows = rows_for(&roster, None, &["file:/x/p.jsonl"]);let child_summary_row = rows.iter().find(|row| row.kind == RowKind::SubagentSummary && row.depth == 2).expect("child summary row");- assert_eq!(child_summary_row.title, "1 subagents (0 running)");+ assert_eq!(child_summary_row.title, "1 subagent · 0 running");}#[test]@@ -313,11 +323,11 @@ fn running_descendants_aggregate_into_the_summary_row() {];let rows = rows_for(&roster, None, &[]);assert_eq!(rows.len(), 2, "ONE line, never a second per-status line");- assert_eq!(rows[1].title, "2 subagents (2 running)");+ assert_eq!(rows[1].title, "2 subagents · 2 running");}/// The operator's 2026-09-28 one-dropdown contract: the ONE line expands to the FULL roster —-/// `46 subagents (6 running)` expands to all forty-six rows, the runners FIRST.+/// `46 subagents · 6 running` expands to all forty-six rows, the runners FIRST.#[test]fn the_merged_line_expands_to_the_full_roster_running_first() {let mut roster = vec![roster_entry("p", "idle", &parent_summary("p"))];@@ -338,7 +348,7 @@ fn the_merged_line_expands_to_the_full_roster_running_first() {let rows = rows_for(&roster, None, &[]);assert_eq!(rows.len(), 2);assert_eq!(rows[1].kind, RowKind::SubagentSummary);- assert_eq!(rows[1].title, "46 subagents (6 running)");+ assert_eq!(rows[1].title, "46 subagents · 6 running");assert!(!rows[1].expanded);let rows = rows_for(&roster, None, &["file:/x/p.jsonl"]);assert_eq!(rows.len(), 48);@@ -414,7 +424,7 @@ fn selection_pins_the_one_summary_line_identity() {};let index = resolve_selection(&collapsed, 0, Some("subagents:file:/x/p.jsonl"), Some(&key));assert_eq!(collapsed[index].kind, RowKind::SubagentSummary);- assert_eq!(collapsed[index].title, "2 subagents (1 running)");+ assert_eq!(collapsed[index].title, "2 subagents · 1 running");let index = resolve_selection(&collapsed,0,@@ -562,12 +572,13 @@ fn saved_child_nests_under_its_saved_parent() {&std::collections::HashSet::default(),&HashSet::default(),&rollups,+ &HashMap::new(),None,);assert_eq!(rows.len(), 2);assert_eq!(rows[0].kind, RowKind::Agent);assert_eq!(rows[0].title, "root agent");- assert_eq!(rows[1].title, "1 subagents (0 running)");+ assert_eq!(rows[1].title, "1 subagent · 0 running");let expanded: HashSet<String> = [rows[0].identity.clone()].into_iter().collect();let rows = build_rows(&records,@@ -575,6 +586,7 @@ fn saved_child_nests_under_its_saved_parent() {&expanded,&HashSet::default(),&rollups,+ &HashMap::new(),None,);assert_eq!(rows[2].title, "saved child");@@ -757,6 +769,7 @@ fn rollups_sum_costs_over_descendants_only() {&std::collections::HashSet::default(),&HashSet::default(),&empty,+ &HashMap::new(),None,);// Without rollups the per-pass walk fills the same totals.@@ -823,6 +836,7 @@ fn an_active_query_ranks_hits_globally_ancestors_sink_last() {&expanded,&HashSet::default(),&rollups,+ &HashMap::new(),None,);let titles: Vec<&str> = rows.iter().map(|row| row.title.as_str()).collect();@@ -899,6 +913,7 @@ fn equal_scores_break_ties_by_recency_not_section() {&std::collections::HashSet::default(),&HashSet::default(),&rollups,+ &HashMap::new(),None,);assert_eq!(@@ -939,7 +954,7 @@ fn the_summary_line_bills_every_descendant_status() {.iter().find(|row| row.identity == "subagents:file:/x/p.jsonl").expect("the ONE line");- assert_eq!(summary.title, "4 subagents (2 running)");+ assert_eq!(summary.title, "4 subagents · 2 running");assert!((summary.cost - 4.75).abs() < f64::EPSILON,"runner subtree 1.50 + idle 2.50 + inactive 0.75 — every status bills"@@ -982,6 +997,7 @@ fn the_summary_line_bills_the_deleted_descendant_bucket() {&HashSet::new(),&HashSet::new(),&rollups,+ &HashMap::new(),None,);let summary = rows@@ -1011,7 +1027,7 @@ fn the_summary_line_cost_is_zero_when_nothing_bills() {.iter().find(|row| row.identity == "subagents:file:/x/p.jsonl").expect("the ONE line");- assert_eq!(summary.title, "2 subagents (2 running)");+ assert_eq!(summary.title, "2 subagents · 2 running");assert!((summary.cost - 0.0).abs() < f64::EPSILON);let lone = rows_for(&[roster_entry("p", "idle", &parent_summary("p"))],@@ -1048,7 +1064,7 @@ fn a_nested_line_bills_its_own_subtree() {.iter().find(|row| row.identity == format!("{SUMMARY_ROW_PREFIX}{child_identity}")).expect("the child's own line");- assert_eq!(nested.title, "1 subagents (1 running)");+ assert_eq!(nested.title, "1 subagent · 1 running");assert!((nested.cost - 0.25).abs() < f64::EPSILON,"only the grandchild's spend"@@ -1057,7 +1073,7 @@ fn a_nested_line_bills_its_own_subtree() {.iter().find(|row| row.identity == "subagents:file:/x/p.jsonl").expect("the root's line");- assert_eq!(root.title, "3 subagents (2 running)");+ assert_eq!(root.title, "3 subagents · 2 running");assert!((root.cost - 4.0).abs() < f64::EPSILON,"runner subtree 1.50 + idle 2.50"@@ -1065,7 +1081,7 @@ fn a_nested_line_bills_its_own_subtree() {}/// The operator's acceptance line: a fleet-scale roster — 331 inactive children plus 2 running —-/// renders ONE summary row reading `333 subagents (2 running)`, expanding to ALL 333,+/// renders ONE summary row reading `333 subagents · 2 running`, expanding to ALL 333,/// runners first.#[test]fn one_dropdown_renders_the_full_fleet_roster() {@@ -1090,7 +1106,7 @@ fn one_dropdown_renders_the_full_fleet_roster() {let rows = rows_for(&roster, None, &[]);assert_eq!(rows.len(), 2);assert_eq!(rows[1].kind, RowKind::SubagentSummary);- assert_eq!(rows[1].title, "333 subagents (2 running)");+ assert_eq!(rows[1].title, "333 subagents · 2 running");assert_eq!(rows[1].identity, "subagents:file:/x/p.jsonl");assert!(!rows[1].expanded);let rows = rows_for(&roster, None, &["file:/x/p.jsonl"]);@@ -1176,6 +1192,7 @@ fn a_ledger_child_nests_across_the_windows_path_forms() {&HashSet::default(),&HashSet::default(),&rollups,+ &HashMap::new(),None,);// RED on main: the child's `file:\\?\...` parent key never matches the@@ -1193,3 +1210,90 @@ fn a_ledger_child_nests_across_the_windows_path_forms() {"the parent's summary line counts the child: {rows:?}");}++fn activity(entries: &[(&str, usize, usize)]) -> HashMap<String, SessionActivity> {+ entries+ .iter()+ .map(|(active, shells, factory_runs)| {+ (+ (*active).to_string(),+ SessionActivity {+ shells: *shells,+ factory_runs: *factory_runs,+ },+ )+ })+ .collect()+}++/// A node's shells and factory-run lines follow its subagents block: a nested child's own lines+/// sit after its own subtree and before the next sibling; the parent's lines come after its whole+/// subtree. A zero count renders no line.+#[test]+fn activity_lines_follow_each_nodes_subagents_block() {+ let mut grandchild = child_summary("gc", "c1", "grandchild");+ grandchild["rlmChildId"] = json!("child-gc");+ let roster = vec![+ roster_entry("p", "idle", &parent_summary("p")),+ roster_entry("c1", "running", &child_summary("c1", "p", "first child")),+ roster_entry("c2", "idle", &child_summary("c2", "p", "second child")),+ roster_entry("gc", "idle", &grandchild),+ ];+ let counts = activity(&[("p-live", 2, 1), ("c1-live", 1, 0), ("c2-live", 0, 0)]);+ let rows = rows_with_activity(&roster, None, &["file:/x/p.jsonl"], &counts);+ let first_child = rows+ .iter()+ .find(|row| row.title == "first child")+ .expect("the first child row")+ .identity+ .clone();+ let rows = rows_with_activity(+ &roster,+ None,+ &["file:/x/p.jsonl", first_child.as_str()],+ &counts,+ );+ assert_eq!(+ rows.iter()+ .map(|row| (row.kind, row.depth, row.title.as_str()))+ .collect::<Vec<_>>(),+ vec![+ (RowKind::Agent, 0, "p name"),+ (RowKind::SubagentSummary, 1, "3 subagents · 1 running"),+ (RowKind::Subagent, 1, "first child"),+ (RowKind::SubagentSummary, 2, "1 subagent · 0 running"),+ (RowKind::Subagent, 2, "grandchild"),+ (RowKind::Shells, 2, "$ 1 shell"),+ (RowKind::Subagent, 1, "second child"),+ (RowKind::Shells, 1, "$ 2 shells"),+ (RowKind::FactoryRuns, 1, "\u{2699} 1 factory run"),+ ]+ );+ let shells = &rows[7];+ assert_eq!(shells.identity, "shells:file:/x/p.jsonl");+ assert_eq!(shells.parent_identity.as_deref(), Some("file:/x/p.jsonl"));+ assert_eq!(rows[8].identity, "factory:file:/x/p.jsonl");+ assert!(shells.selectable());+}++/// A node without subagents shows its lines directly under its row; a node with no counts shows+/// none.+#[test]+fn activity_lines_without_subagents_and_without_counts() {+ let roster = vec![+ roster_entry("a", "idle", &parent_summary("a")),+ roster_entry("b", "idle", &parent_summary("b")),+ ];+ let rows = rows_with_activity(&roster, None, &[], &activity(&[("a-live", 0, 3)]));+ let titles: Vec<&str> = rows.iter().map(|row| row.title.as_str()).collect();+ let a = titles+ .iter()+ .position(|title| *title == "a name")+ .expect("a row");+ assert_eq!(titles[a + 1], "\u{2699} 3 factory runs");+ assert_eq!(+ rows.len(),+ 3,+ "b has no lines and a has no shells line: {titles:?}"+ );+}diff --git a/crates/pa-tui/src/agents_view_state.rs b/crates/pa-tui/src/agents_view_state.rsindex 96e8b6df17..ff18362e3d 100644--- a/crates/pa-tui/src/agents_view_state.rs+++ b/crates/pa-tui/src/agents_view_state.rs@@ -632,9 +632,16 @@ pub fn build_layout(rows: &[crate::agents_view_forest::AgentsViewRow], width: us.iter().filter(|row| row.kind != crate::agents_view_forest::RowKind::Code).collect();+ let cost = |row: &crate::agents_view_forest::AgentsViewRow| {+ if row.kind == crate::agents_view_forest::RowKind::PersistentShell {+ "-".to_string()+ } else {+ format!("${:.2}", row.cost)+ }+ };let cost_width = rows.iter()- .map(|row| str_width(&format!("${:.2}", row.cost)))+ .map(|row| str_width(&cost(row))).max().unwrap_or(0).max(4);@@ -668,12 +675,7 @@ pub fn build_layout(rows: &[crate::agents_view_forest::AgentsViewRow], width: usheadings.push(detail_line("Cost", "Age"));let details = rows.iter()- .map(|row| {- (- row.identity.clone(),- detail_line(&format!("${:.2}", row.cost), &row.age),- )- })+ .map(|row| (row.identity.clone(), detail_line(&cost(row), &row.age))).collect();RowLayout {legend: table_cell(&headings.join(" "), width),@@ -856,6 +858,7 @@ mod tests {&std::collections::HashSet::default(),&std::collections::HashSet::default(),&std::collections::HashMap::default(),+ &std::collections::HashMap::default(),None,);assert_eq!(rows[0].section, Section::Running);@@ -1046,6 +1049,7 @@ mod tests {&std::collections::HashSet::default(),&std::collections::HashSet::default(),&std::collections::HashMap::default(),+ &std::collections::HashMap::default(),None,);let layout = build_layout(&rows, 120);@@ -1092,6 +1096,7 @@ mod tests {&std::collections::HashSet::default(),&std::collections::HashSet::default(),&std::collections::HashMap::default(),+ &std::collections::HashMap::default(),None,);let age = rowsdiff --git a/crates/pa-tui/src/bash_view.rs b/crates/pa-tui/src/bash_view.rsindex 265a27f815..6b7a9cae7f 100644--- a/crates/pa-tui/src/bash_view.rs+++ b/crates/pa-tui/src/bash_view.rs@@ -15,12 +15,16 @@ use crate::{Line, Span};mod render;-use render::format_duration;+pub(crate) use render::format_duration;use render::{action_row, clean_line, error_line, hint_line, marker_line, metadata_row, pane_header_lines,Columns,};+// A tail response may outlive its entire pane, so tokens belong to the process,+// not one BashView instance. Relaxed ordering only allocates distinct tokens.+static NEXT_DETAIL_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);+const PREFERRED_VISIBLE: usize = 8;/// Rows the list reserves outside its items: rule, title, blank, column@@ -120,6 +124,27 @@ fn dock_shell_item(activity: &BashActivity) -> String {)}+/// Whether a registry update moved a row (its id, status or exit code): the running rows'+/// duration ticks alone never count.+pub(crate) fn registry_rows_moved(old: &Value, new: &Value) -> bool {+ let signature = |data: &Value| -> Vec<(String, String, Option<i64>)> {+ parse_bash_activities(data)+ .into_iter()+ .map(|row| (row.id, row.status, row.exit_code))+ .collect()+ };+ signature(old) != signature(new)+}++/// The running shells in a `list_kernel_bash` reply: finished shells stay in the bash view only.+#[must_use]+pub fn running_shell_count(data: &Value) -> usize {+ parse_bash_activities(data)+ .iter()+ .filter(|activity| activity.running())+ .count()+}+/// The pane's interactive mode: the columned list, or a row's detail/// drill-in.#[derive(Debug, Clone, PartialEq, Eq)]@@ -156,8 +181,8 @@ pub enum BashViewAction {pub struct BashView {/// The latest registry snapshot (kept current by the host's refresh).activities: Vec<BashActivity>,- /// Each open increments it; the host stamps tail requests with the open's- /// generation, so a late response never overwrites the newer open's output.+ /// A process-unique token for this open; tail requests retain it even when+ /// the host replaces the entire view before their responses arrive.detail_generation: u64,selected_id: Option<String>,mode: Mode,@@ -187,6 +212,7 @@ pub struct BashView {/// keeps the registry-refresh lifecycle, [`BashView::clear_error`]).fetch_error: bool,viewport_rows: usize,+ subtitle: Option<String>,}impl BashView {@@ -207,11 +233,30 @@ impl BashView {error: None,fetch_error: false,viewport_rows,+ subtitle: None,};view.selected_id = view.activities.first().map(|row| row.id.clone());view}+ /// The rows the view lays out in: a host whose frame resizes sets it before each render.+ pub fn set_viewport_rows(&mut self, rows: usize) {+ self.viewport_rows = rows;+ }++ /// The list's muted line under its title.+ #[must_use]+ pub fn with_subtitle(mut self, subtitle: &str) -> Self {+ self.subtitle = Some(subtitle.to_string());+ self+ }++ /// Select row `id` in the list; an empty registry keeps the selection for the rows that land+ /// later.+ pub fn select(&mut self, id: &str) {+ self.selected_id = Some(id.to_string());+ }+/// Reset the open detail's fetched-output state (new open, back, or/// row vanished): the next open starts fresh, bottom-anchored.fn reset_detail_output(&mut self) {@@ -224,20 +269,25 @@ impl BashView {}/// A landed registry refresh: replace the rows, keep the selection on- /// the surviving id, and drop a detail pane whose row vanished.+ /// the surviving id (an empty registry keeps it), and drop a detail pane whose row vanished.pub fn apply_activities(&mut self, activities: Vec<BashActivity>) {self.activities = activities;let selected = self.selected_id.clone();let exists = selected.as_deref().is_some_and(|id| self.activities.iter().any(|row| row.id == id));- if !exists {- self.selected_id = self.activities.first().map(|row| row.id.clone());+ if let Some(first) = self.activities.first().filter(|_| !exists) {+ self.selected_id = Some(first.id.clone());}if let Mode::Detail { id } = self.mode.clone() {if !self.activities.iter().any(|row| row.id == id) {self.mode = Mode::List;self.reset_detail_output();+ // The dropped detail's fetch error goes with it; a kill error keeps its lifecycle.+ if self.fetch_error {+ self.error = None;+ self.fetch_error = false;+ }}}self.output_tail = self@@ -312,11 +362,13 @@ impl BashView {self.fetch_error = fetch;}- /// A landed registry update supersedes a shown error; the host calls- /// this only when the registry itself changed.+ /// A changed registry supersedes a kill error. A fetch error keeps its+ /// retry state until output lands; metadata alone cannot satisfy a fetch.pub fn clear_error(&mut self) {- self.error = None;- self.fetch_error = false;+ if !self.fetch_error || matches!(self.mode, Mode::List) {+ self.error = None;+ self.fetch_error = false;+ }}/// The selected row's index (first when unset).@@ -391,7 +443,7 @@ impl BashView {/// Scroll the detail's output region: up lifts the window off the newest lines,/// down lowers it back; at the loaded top, load more or stop.- fn scroll_output(&mut self, delta: isize) -> BashViewAction {+ pub(crate) fn scroll_output(&mut self, delta: isize) -> BashViewAction {let Mode::Detail { id } = self.mode.clone() else {return BashViewAction::None;};@@ -457,7 +509,8 @@ impl BashView {};if self.find_activity(&id).is_some() {self.mode = Mode::Detail { id: id.clone() };- self.detail_generation = self.detail_generation.wrapping_add(1);+ self.detail_generation =+ NEXT_DETAIL_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);self.reset_detail_output();return BashViewAction::OpenDetail {id,@@ -482,7 +535,9 @@ impl BashView {}fn visible_items(&self) -> usize {- let reserved = LIST_FRAME_ROWS + if self.error.is_some() { 2 } else { 0 };+ let reserved = LIST_FRAME_ROWS+ + usize::from(self.subtitle.is_some())+ + if self.error.is_some() { 2 } else { 0 };// The shared layout floors at one row so a picker never reads empty; this view// never renders past its viewport, so a frame too short for any row renders none.if self.viewport_rows <= reserved {@@ -513,7 +568,7 @@ impl BashView {.filter(|activity| activity.running()).count();let counts = vec![(ThemeColor::Success, format!("{running} running"))];- let mut lines = pane_header_lines(theme, width, "Bash", &counts, None);+ let mut lines = pane_header_lines(theme, width, "Bash", &counts, self.subtitle.as_deref());if self.activities.is_empty() {lines.push(vec![Span::raw(" "),diff --git a/crates/pa-tui/src/bash_view/render.rs b/crates/pa-tui/src/bash_view/render.rsindex 760759c4d0..a2bf36c2f9 100644--- a/crates/pa-tui/src/bash_view/render.rs+++ b/crates/pa-tui/src/bash_view/render.rs@@ -220,7 +220,7 @@ pub(super) fn clean_line(value: &str) -> String {/// The duration cell: whole milliseconds read as a compact human word/// (`780ms`, `3.4s`, `2m 05s`), `—` when the wire carries none.-pub(super) fn format_duration(duration_ms: Option<u64>) -> String {+pub(crate) fn format_duration(duration_ms: Option<u64>) -> String {let Some(ms) = duration_ms else {return "\u{2014}".to_string();};diff --git a/crates/pa-tui/src/bash_view/tests.rs b/crates/pa-tui/src/bash_view/tests.rsindex 9dc6166e8b..4125b2900f 100644--- a/crates/pa-tui/src/bash_view/tests.rs+++ b/crates/pa-tui/src/bash_view/tests.rs@@ -15,6 +15,12 @@ fn theme() -> Theme {Theme::builtin("prime", ColorMode::TrueColor)}+/// Enter on row `id`'s list row: its detail opens.+fn open(view: &mut BashView, id: &str) -> BashViewAction {+ view.select(id);+ view.handle_key("enter", &kb())+}+fn activities() -> Vec<BashActivity> {parse_bash_activities(&json!({"activities": [{"id":"a","command":"cargo build --release","pid":42,"startedAt":"2026-09-22T01:00:00Z","status":"running","durationMs":3412},@@ -1127,3 +1133,92 @@ fn the_dock_shell_items_list_running_shells_only() {]);}++#[test]+fn replacing_the_entire_view_rejects_previous_output_and_errors() {+ let mut previous = BashView::new(activities(), 40);+ open(&mut previous, "a");+ let old_generation = previous.detail_generation;+ for id in ["a", "b"] {+ let mut replacement = BashView::new(activities(), 40);+ open(&mut replacement, id);+ replacement.set_output(id, "current output", replacement.detail_generation);+ replacement.set_output(id, "stale output", old_generation);+ replacement.set_error("stale error".to_string(), true, Some(old_generation));+ let text = frame_text(&replacement.render(&theme(), 70, &kb())).join("\n");+ assert!(text.contains("current output"), "{text}");+ assert!(+ !text.contains("stale output") && !text.contains("stale error"),+ "{text}"+ );+ }+}++#[test]+fn registry_changes_preserve_failed_tail_fetches_and_their_retry() {+ let mut view = BashView::new(activities(), 40);+ let action = open(&mut view, "a");+ let BashViewAction::OpenDetail { generation, .. } = action else {+ panic!("open detail")+ };+ view.set_error(+ "Bash output: unavailable".to_string(),+ true,+ Some(generation),+ );+ let mut refreshed = activities();+ refreshed[0].command = "changed metadata".to_string();+ view.apply_activities(refreshed);+ view.clear_error();+ let text = frame_text(&view.render(&theme(), 70, &kb())).join("\n");+ assert!(text.contains("Bash output: unavailable"), "{text}");+ assert_eq!(+ view.handle_key("up", &kb()),+ BashViewAction::OpenDetail {+ id: "a".to_string(),+ generation,+ }+ );+ view.set_output("a", "recovered output", generation);+ let text = frame_text(&view.render(&theme(), 70, &kb())).join("\n");+ assert!(+ text.contains("recovered output") && !text.contains("unavailable"),+ "{text}"+ );+ view.set_error("Bash output: row gone".to_string(), true, Some(generation));+ view.apply_activities(Vec::new());+ view.clear_error();+ assert!(+ view.error.is_none(),+ "a vanished row retires its fetch error"+ );+}++/// The hosts clear a kill error before they apply the refresh. A refresh that drops the open+/// detail's row still retires that detail's fetch error, without a second changed refresh.+#[test]+fn dropping_the_detail_retires_its_fetch_error() {+ let mut view = BashView::new(activities(), 40);+ let BashViewAction::OpenDetail { generation, .. } = open(&mut view, "a") else {+ panic!("open detail")+ };+ view.set_error(+ "Bash output: unavailable".to_string(),+ true,+ Some(generation),+ );+ view.clear_error();+ view.apply_activities(activities().split_off(1));+ let text = frame_text(&view.render(&theme(), 70, &kb())).join("\n");+ assert!(!text.contains("unavailable"), "{text}");+}++#[test]+fn running_shell_count_skips_finished_shells() {+ let data = json!({"activities": [+ {"id": "a", "command": "x", "status": "running"},+ {"id": "b", "command": "y", "status": "done"},+ {"id": "c", "command": "z", "status": "failed"},+ ]});+ assert_eq!(running_shell_count(&data), 1);+}diff --git a/crates/pa-tui/src/chrome.rs b/crates/pa-tui/src/chrome.rsindex 125786c215..b1af29f8c9 100644--- a/crates/pa-tui/src/chrome.rs+++ b/crates/pa-tui/src/chrome.rs@@ -765,7 +765,13 @@ pub fn render_activity_dock_segments(let start = line.iter().map(|s| str_width(&s.content)).sum();match group {ActivityGroup::Subagents => {- line.push(theme.fg_span(activity_color(running), format!("◆ {running} subagents")));+ line.push(theme.fg_span(+ activity_color(running),+ format!(+ "◆ {running} subagent{}",+ if running == 1 { "" } else { "s" }+ ),+ ));}ActivityGroup::Heartbeats => {line.push(theme.fg_span(diff --git a/crates/pa-tui/src/chrome/tests.rs b/crates/pa-tui/src/chrome/tests.rsindex c86e0e1592..e2d98fc769 100644--- a/crates/pa-tui/src/chrome/tests.rs+++ b/crates/pa-tui/src/chrome/tests.rs@@ -315,7 +315,7 @@ fn prompt_bar_subagent_segment_is_the_running_count_only() {.collect::<String>();assert_eq!(text,- " ◆ 1 subagents · ◷ 0 heartbeats · ▸ 0 shells · ⚙ 0 factory"+ " ◆ 1 subagent · ◷ 0 heartbeats · ▸ 0 shells · ⚙ 0 factory");}diff --git a/crates/pa-tui/src/factory_view.rs b/crates/pa-tui/src/factory_view.rsindex 14d638f3b6..439f524ca4 100644--- a/crates/pa-tui/src/factory_view.rs+++ b/crates/pa-tui/src/factory_view.rs@@ -203,6 +203,15 @@ pub fn factory_reply_lists_runs(data: &Value) -> bool {data.get("runs").is_some_and(Value::is_array)}+/// The live runs in a graph reply ([`FactoryRunSnapshot::is_live`]).+#[must_use]+pub fn live_run_count(data: &Value) -> usize {+ parse_factory_runs(data)+ .iter()+ .filter(|run| run.is_live())+ .count()+}+/// The malformed-lane error line (one message for the mount and the/// fold): a reply without the runs list is a malformed lane, never/// zero runs.diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rsindex 3276e4deb6..cf6a7eb703 100644--- a/crates/pa-tui/src/interactive.rs+++ b/crates/pa-tui/src/interactive.rs@@ -78,6 +78,17 @@ pub enum SessionSelection {Resume(PathBuf),}+/// The session panel an agents-view activity line mounts when its session opens; the panel's close+/// returns to the agents view.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum SessionPanel {+ /// The Bash panel, on `shell_id`'s row when a persistent shell row opened it.+ Shells {+ shell_id: Option<String>,+ },+ FactoryRuns,+}+/// Cap on the exit-path telemetry flush (the `tui exit` event's bound):/// the analytics sink alone allows up to 1.5s, so an exit-path event is/// dropped rather than awaited past the exit-within-1s contract. The@@ -85,6 +96,10 @@ pub enum SessionSelection {/// bound.pub const TELEMETRY_EXIT_TIMEOUT_MS: u64 = 500;+/// The kernel activity poll cadence: the session's shells/factory refresh and the agents view's+/// activity-line counts and persistent shells list.+pub(crate) const ACTIVITY_POLL_INTERVAL: Duration = Duration::from_secs(2);+/// Explicit model selection carried into every `create` config: the CLI/// `--provider`/`--model`/`--api-key`/`--thinking` flags, authoritative end-to-end — the/// daemon worker resolves its session model and thinking level from this selection.diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rsindex 092973c59c..7ac9e1d0ac 100644--- a/crates/pa-tui/src/interactive/run.rs+++ b/crates/pa-tui/src/interactive/run.rs@@ -5,9 +5,9 @@ use super::{apply_startup_chrome, arm_shutdown_recovery, check_tmux_keyboard_setup, mpsc,run_onboarding_phase, spawn_session_reader, AgentView, DaemonClient, Duration, ExitGuard,HeadlessSettle, Instant, InteractiveOptions, InteractiveOutcome, PaneDrive, ReconnectConnect,- ReconnectLoop, RecoveryKind, Renderer, Result, SessionReconnect, SessionSelection, SessionUi,- TerminalHandoff, UiInput, UiMode, VecDeque, SESSION_RECONNECT_ATTEMPT_TIMEOUT_S,- TELEMETRY_EXIT_TIMEOUT_MS,+ ReconnectLoop, RecoveryKind, Renderer, Result, SessionPanel, SessionReconnect,+ SessionSelection, SessionUi, TerminalHandoff, UiInput, UiMode, VecDeque,+ ACTIVITY_POLL_INTERVAL, SESSION_RECONNECT_ATTEMPT_TIMEOUT_S, TELEMETRY_EXIT_TIMEOUT_MS,};use crate::suspend::SuspendTerminal;use anyhow::Context;@@ -51,12 +51,13 @@ fn next_spinner_deadline(started: Instant, now: Instant) -> Instant {/// The open route for one interactive run (TS `runAgentsViewLoop`'s/// open versus the CLI's own open): the agents-view open waits through a/// daemon update restart (TS #2391) instead of failing the open hard.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) enum SessionOpenRoute {/// The CLI's open (`prime-agent`, `--resume`, `--attach`): a single attempt.Cli,- /// The agents view's open: waits through the update-restart window and retries.- AgentsView,+ /// The agents view's open: waits through the update-restart window and retries; `panel`+ /// mounts on open and its close returns to the agents view.+ AgentsView { panel: Option<SessionPanel> },}/// Run one interactive session (the CLI open route).@@ -82,8 +83,9 @@ pub async fn run_interactive(pub async fn run_interactive_agents_view_open(options: InteractiveOptions,ui: UiMode,+ panel: Option<SessionPanel>,) -> Result<InteractiveOutcome> {- run_interactive_route(options, ui, SessionOpenRoute::AgentsView).await+ run_interactive_route(options, ui, SessionOpenRoute::AgentsView { panel }).await}async fn run_interactive_route(@@ -310,7 +312,7 @@ async fn run_interactive_surface(let factory_tx = factory_tx.clone();let commands_tx = commands_tx.clone();let page_tx = page_tx.clone();- let waits_through_update_restart = route == SessionOpenRoute::AgentsView;+ let waits_through_update_restart = matches!(route, SessionOpenRoute::AgentsView { .. });tokio::spawn(async move {crate::update_restart_wait::wait_through_update_restart(waits_through_update_restart,@@ -708,6 +710,9 @@ async fn run_interactive_surface(// previous chat view of this session left via the agents view or a// switch) returns to the editor when its chat reopens.session.restore_prompt_stash_on_open(&mut view);+ if let SessionOpenRoute::AgentsView { panel: Some(panel) } = route {+ session.open_agents_view_panel(panel, &mut view);+ }// Declared above the onboarding phase: the pane's drive marks it.let mut headless_done = false;// The settle bound's deadline (see [`HEADLESS_SETTLE_TIMEOUT_MS`]).@@ -1886,7 +1891,7 @@ async fn run_interactive_surface(std::future::pending::<()>().await;}tokio::time::sleep_until(- tokio::time::Instant::from_std(last_bash_refresh + Duration::from_secs(2)),+ tokio::time::Instant::from_std(last_bash_refresh + ACTIVITY_POLL_INTERVAL),).await;} => {@@ -1905,7 +1910,7 @@ async fn run_interactive_surface(std::future::pending::<()>().await;}tokio::time::sleep_until(- tokio::time::Instant::from_std(last_factory_refresh + Duration::from_secs(2)),+ tokio::time::Instant::from_std(last_factory_refresh + ACTIVITY_POLL_INTERVAL),).await;} => {diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rsindex d473f9a57c..cf35c08f2b 100644--- a/crates/pa-tui/src/session_ui.rs+++ b/crates/pa-tui/src/session_ui.rs@@ -329,6 +329,9 @@ pub(crate) struct SessionUi {/// Whether this run may hand the terminal back to the agents view:/// false only for `--no-session` runs.pub(crate) return_to_agents_view: bool,+ /// The open panel was mounted by an agents-view activity line: its close hands the pane back+ /// to the agents view instead of the dock.+ panel_returns_to_agents_view: bool,client_auth: Option<crate::client_auth::ClientAuthCommandsHandle>,keybindings: crate::keybindings::KeybindingsManager,prompt_stash: std::sync::Arc<std::sync::Mutex<crate::prompt_stash::PromptStashStore>>,diff --git a/crates/pa-tui/src/session_ui/apply.rs b/crates/pa-tui/src/session_ui/apply.rsindex 982714d37a..2a18cc6b30 100644--- a/crates/pa-tui/src/session_ui/apply.rs+++ b/crates/pa-tui/src/session_ui/apply.rs@@ -236,6 +236,14 @@ impl SessionUi {if active_session_id == self.active_session_id {self.turn_active = false;view.working = None;+ self.bash_list_epoch += 1;+ self.factory_list_epoch += 1;+ self.bash_activities = serde_json::json!({"activities": []});+ self.factory_graph = serde_json::json!({"runs": []});+ if let Some(factory_view) = view.factory_view.as_mut() {+ factory_view.apply_runs(Vec::new());+ }+ self.update_subagent_summary(view);match reason.as_str() {"shutdown" => self.error_row("The Prime Agent daemon shut down while this window was attached. The session transcript remains saved; restart Prime Agent and reopen it from Agents View.",diff --git a/crates/pa-tui/src/session_ui/bash.rs b/crates/pa-tui/src/session_ui/bash.rsindex 4d518d721e..732f9830c1 100644--- a/crates/pa-tui/src/session_ui/bash.rs+++ b/crates/pa-tui/src/session_ui/bash.rs@@ -247,13 +247,8 @@ impl SessionUi {}// A landed REGISTRY update supersedes a shown error — but only when the registry's// rows actually moved; the running rows' duration ticks never clear anything.- let row_signature = |data: &Value| -> Vec<(String, String, Option<i64>)> {- crate::bash_view::parse_bash_activities(data)- .into_iter()- .map(|row| (row.id, row.status, row.exit_code))- .collect()- };- let rows_settled = row_signature(&self.bash_activities) != row_signature(&data);+ let rows_settled =+ crate::bash_view::registry_rows_moved(&self.bash_activities, &data);self.bash_activities = data;if rows_settled {if let Some(bash_view) = view.bash_view.as_mut() {@@ -378,7 +373,9 @@ impl SessionUi {view.bash_view = None;// The exit restores the dock's own group (the operator's 2026-09-26 panel-exit// ruling): ESC/left lands back on the Shells item, not the prompt bar.- self.focus_activity_dock(view);+ if !self.close_panel_to_agents_view() {+ self.focus_activity_dock(view);+ }}Some(BashViewAction::OpenDetail { id, generation }) => {// The open asks for the first window only; the detail's upward scrolldiff --git a/crates/pa-tui/src/session_ui/factory.rs b/crates/pa-tui/src/session_ui/factory.rsindex 172e41b546..92f391eae0 100644--- a/crates/pa-tui/src/session_ui/factory.rs+++ b/crates/pa-tui/src/session_ui/factory.rs@@ -13,7 +13,7 @@ use pa_types::daemon::DaemonCommand;use super::AgentView;use crate::factory_view::{- factory_reply_lists_runs, parse_factory_runs, FactoryView, FactoryViewAction,+ factory_reply_lists_runs, live_run_count, parse_factory_runs, FactoryView, FactoryViewAction,FACTORY_WATCH_TICK_MS,};use crate::session_ui::{picker_viewport_rows, UI_REQUEST_TIMEOUT_MS};@@ -106,6 +106,7 @@ impl super::SessionUi {self.factory_selected_run = None;self.factory_view_session = None;view.factory_view = None;+ self.close_panel_to_agents_view();self.dirty = true;}Some(FactoryViewAction::Stop { run_id }) => {@@ -212,12 +213,7 @@ impl super::SessionUi {if !factory_reply_lists_runs(&reply) {return None;}- Some(- parse_factory_runs(&reply)- .iter()- .filter(|run| run.is_live())- .count(),- )+ Some(live_run_count(&reply))}/// The refresh cadence (the run's collect cycle): a bounded watch ondiff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rsindex 1033e764b6..589c4dd54e 100644--- a/crates/pa-tui/src/session_ui/lifecycle.rs+++ b/crates/pa-tui/src/session_ui/lifecycle.rs@@ -157,6 +157,7 @@ impl SessionUi {session_file: None,pending_selection: None,return_to_agents_view: !options.no_session,+ panel_returns_to_agents_view: false,client_auth: options.client_auth.clone(),keybindings: options.keybindings.clone(),prompt_stash: options.prompt_stash.clone(),@@ -577,6 +578,9 @@ impl SessionUi {self.factory_view_session = None;self.factory_graph = serde_json::json!({"runs": []});}+ // An agents-view panel the rebind tore down takes its return-to-agents-view flag+ // with it; a kept factory page keeps it.+ self.panel_returns_to_agents_view &= view.factory_view.is_some();// The goal panel dies with the old session too: it is a// snapshot of the previous session's goal state, and until// the new session's own `goal_update` lands it would keep@@ -785,6 +789,172 @@ mod backfill_tests {use serde_json::json;use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+ /// One session attached over a mock daemon that answers `attach` and `get_messages`.+ async fn mock_session(+ socket: &std::path::Path,+ backfill_tx: mpsc::UnboundedSender<TranscriptPageNote>,+ ) -> (SessionUi, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::UnixListener::bind(socket).unwrap();+ let server = tokio::spawn(async move {+ let (stream, _) = listener.accept().await.unwrap();+ let (read, mut write) = stream.into_split();+ write.write_all(b"{\"type\":\"daemon_hello\",\"protocol\":{\"name\":\"prime-agent.daemon\",\"version\":7},\"serverCapabilities\":[],\"clientId\":\"mock\"}\n").await.unwrap();+ let mut lines = BufReader::new(read).lines();+ while let Some(line) = lines.next_line().await.unwrap() {+ let request: Value = serde_json::from_str(&line).unwrap();+ let kind = request["command"]["type"].as_str().unwrap();+ let data = match kind {+ "attach" => json!({+ "activeSessionId": "s1", "snapshot": {+ "activeSessionId": "s1", "summary": {"id": "s1", "cwd": "/tmp"},+ "state": {"sessionId": "s1", "cwd": "/tmp", "isStreaming": false},+ "messages": [], "historyBefore": 1, "lastEventSequence": 0,+ }, "replay": {"status": "complete", "toSequence": 0},+ "lastEventSequence": 0,+ }),+ "get_messages" => {+ json!({"messages": [{"role": "user", "content": "rebuilt transcript", "timestamp": 1}]})+ }+ _ => json!({}),+ };+ let mut reply = serde_json::to_vec(&json!({+ "type": "response", "id": request["id"], "command": kind,+ "success": true, "data": data,+ }))+ .unwrap();+ reply.push(b'\n');+ write.write_all(&reply).await.unwrap();+ }+ });+ let mut options =+ crate::interactive::tests::options(crate::interactive::ModelSelection::default());+ options.socket_path = socket.to_path_buf();+ options.session = SessionSelection::Attach("s1".to_string());+ let (client, _events) = DaemonClient::connect(socket).await.unwrap();+ let session = SessionUi::open(+ client,+ &options,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ mpsc::unbounded_channel().0,+ ActivityUpdates {+ heartbeats: mpsc::unbounded_channel().0,+ bash: mpsc::unbounded_channel().0,+ factory: mpsc::unbounded_channel().0,+ commands: mpsc::unbounded_channel().0,+ },+ backfill_tx,+ )+ .await+ .unwrap();+ (session, server)+ }++ /// A rebind that tears down an agents-view panel drops its return: a later dock-opened shells+ /// panel closes back to the dock, never to the agents view.+ #[tokio::test]+ async fn a_rebind_drops_the_agents_view_panel_return() {+ tokio::time::timeout(Duration::from_secs(10), async {+ let dir = tempfile::tempdir().unwrap();+ let socket = dir.path().join("panel.sock");+ let (mut session, server) = mock_session(&socket, mpsc::unbounded_channel().0).await;+ let mut view = AgentView::new(crate::theme::Theme::builtin(+ "prime",+ crate::theme::ColorMode::TrueColor,+ ));+ session.open_agents_view_panel(+ crate::interactive::SessionPanel::Shells { shell_id: None },+ &mut view,+ );+ session.rebuild_view(&mut view, &RebuildKind::Rebind);+ assert!(view.bash_view.is_none(), "the rebind tore the panel down");+ session.open_bash_view(&mut view);+ let esc = crossterm::event::KeyEvent::new(+ crossterm::event::KeyCode::Esc,+ crossterm::event::KeyModifiers::NONE,+ );+ session.handle_bash_view_key(esc, &mut view).unwrap();+ assert!(view.bash_view.is_none(), "Esc closed the dock's panel");+ assert!(+ !session.open_agents_view && !session.exit_requested,+ "the dock's panel closes to the dock"+ );+ drop(session);+ server.abort();+ })+ .await+ .expect("mock session open, rebind and panel close complete within ten seconds");+ }++ /// An agents-view shell open selects its shell in the Bash panel, also when the shell lands in+ /// a later poll than the panel's first (empty) snapshot.+ #[tokio::test]+ async fn an_agents_view_shell_open_selects_its_shell() {+ tokio::time::timeout(Duration::from_secs(10), async {+ let dir = tempfile::tempdir().unwrap();+ let socket = dir.path().join("shell.sock");+ let (mut session, server) = mock_session(&socket, mpsc::unbounded_channel().0).await;+ let shells = json!({"activities": [+ {"id": "a", "command": "cargo build", "status": "running"},+ {"id": "s2", "command": "sleep 600", "status": "running"},+ ]});+ for preloaded in [true, false] {+ let theme =+ || crate::theme::Theme::builtin("prime", crate::theme::ColorMode::TrueColor);+ let mut view = AgentView::new(theme());+ session.bash_activities = if preloaded {+ shells.clone()+ } else {+ json!({"activities": []})+ };+ session.open_agents_view_panel(+ crate::interactive::SessionPanel::Shells {+ shell_id: Some("s2".to_string()),+ },+ &mut view,+ );+ if !preloaded {+ session.apply_bash_activity(+ crate::session_ui::bash::BashActivityUpdate::List {+ session: session.active_session_id.clone(),+ epoch: session.bash_list_epoch,+ data: shells.clone(),+ },+ &mut view,+ );+ }+ let lines = view.bash_view.as_ref().expect("the Bash panel").render(+ &theme(),+ 80,+ view.editor.keybindings(),+ );+ let selected = lines+ .iter()+ .map(|line| {+ line.iter()+ .map(|span| span.content.as_str())+ .collect::<String>()+ })+ .find(|text| text.starts_with('\u{203a}'))+ .expect("a selected row");+ assert!(+ selected.contains("sleep 600"),+ "preloaded {preloaded}: {selected}"+ );+ }+ drop(session);+ server.abort();+ })+ .await+ .expect("mock session open and both panel opens complete within ten seconds");+ }+#[tokio::test]async fn an_attach_summary_model_fallback_warns_at_the_session_open() {tokio::time::timeout(Duration::from_secs(10), async {diff --git a/crates/pa-tui/src/session_ui/panels.rs b/crates/pa-tui/src/session_ui/panels.rsindex 8160bc425d..1216f59eb2 100644--- a/crates/pa-tui/src/session_ui/panels.rs+++ b/crates/pa-tui/src/session_ui/panels.rs@@ -236,6 +236,36 @@ impl SessionUi {self.dirty = true;}+ /// Mount the panel an agents-view activity line requested; its close returns to the agents+ /// view.+ pub(crate) fn open_agents_view_panel(+ &mut self,+ panel: crate::interactive::SessionPanel,+ view: &mut AgentView,+ ) {+ match panel {+ crate::interactive::SessionPanel::Shells { shell_id } => {+ self.open_bash_view(view);+ if let (Some(id), Some(bash_view)) = (shell_id, view.bash_view.as_mut()) {+ bash_view.select(&id);+ }+ }+ crate::interactive::SessionPanel::FactoryRuns => self.open_factory_page(view),+ }+ self.panel_returns_to_agents_view = view.bash_view.is_some() || view.factory_view.is_some();+ }++ /// The close of a panel the agents view requested hands the pane back to it; returns whether+ /// it did.+ pub(super) fn close_panel_to_agents_view(&mut self) -> bool {+ if !std::mem::take(&mut self.panel_returns_to_agents_view) {+ return false;+ }+ self.open_agents_view = true;+ self.exit_requested = true;+ true+ }+/// The dock's Enter hand-off (the operator's direct-navigation redesign):/// the focused group opens its own view directly, no intermediate list.pub(super) fn open_dock_group_view(&mut self, view: &mut AgentView) {diff --git a/crates/pa-tui/src/subagents.rs b/crates/pa-tui/src/subagents.rsindex 3b11974e4c..be70c98ed6 100644--- a/crates/pa-tui/src/subagents.rs+++ b/crates/pa-tui/src/subagents.rs@@ -455,6 +455,7 @@ mod tests {&std::collections::HashSet::new(),&std::collections::HashSet::new(),&rollups,+ &std::collections::HashMap::new(),None,);let row = rowsdiff --git a/crates/pa-tui/tests/agents_view_hover_headless.rs b/crates/pa-tui/tests/agents_view_hover_headless.rsindex 02bded76b0..0c7fcddb4f 100644--- a/crates/pa-tui/tests/agents_view_hover_headless.rs+++ b/crates/pa-tui/tests/agents_view_hover_headless.rs@@ -1,7 +1,8 @@//! Headless e2e for the agents view's hover + click affordances (operator//! directive 2026-09-29): EVERY row opens on a plain click (inactive//! saved rows resume, the merged summary row expands its dropdown,-//! expanded child rows open the subagent); hover motions ride along.+//! expanded child rows open the subagent); hover motions ride along. The same mock also pins the+//! shells poll's one-cycle-in-flight contract.#![cfg(unix)]// Casts: structurally bounded terminal-layout arithmetic; guarded conversions add panic paths.#![allow(@@ -22,6 +23,8 @@use std::io::{BufRead, BufReader, Write};use std::os::unix::net::{UnixListener, UnixStream};use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::Arc;use std::time::Duration;use pa_tui::agents_view::{@@ -82,14 +85,38 @@ fn saved_row(path: &str, id: &str, name: &str) -> Value {})}+/// The shells-poll probe: the first `list_kernel_bash` answers only after a hold longer than the+/// poll interval; a request arriving while another is still unanswered means the poll stacked.+#[derive(Default)]+struct ShellsProbe {+ requests: AtomicUsize,+ unanswered: AtomicUsize,+ overlapped: AtomicBool,+}++fn shells_reply(running: usize) -> Value {+ let activities: Vec<Value> = (0..running)+ .map(|index| json!({"id": format!("shell-{index}"), "command": "sleep", "status": "running"}))+ .collect();+ json!({ "activities": activities })+}+struct MockSupervisor {listener: UnixListener,+ roster: Vec<Value>,+ /// `Some` advertises the kernel-bash capability and serves the probe's shells replies.+ shells: Option<Arc<ShellsProbe>>,}impl MockSupervisor {fn bind(socket: &std::path::Path) -> Self {MockSupervisor {listener: UnixListener::bind(socket).expect("bind mock socket"),+ roster: vec![+ roster_row("p", "idle", &parent_summary("p")),+ roster_row("c", "running", &child_summary("c", "p", "worker one")),+ ],+ shells: None,}}@@ -101,10 +128,15 @@ impl MockSupervisor {let write_stream = stream.try_clone().expect("clone socket");let mut writer = write_stream;let mut reader = BufReader::new(stream);+ let capabilities: &[&str] = if self.shells.is_some() {+ &["kernel_bash_activity"]+ } else {+ &[]+ };let hello = json!({"type": "daemon_hello","protocol": { "name": "prime-agent.daemon", "version": 7 },- "serverCapabilities": [],+ "serverCapabilities": capabilities,});write_line(&mut writer, &hello);loop {@@ -130,12 +162,7 @@ impl MockSupervisor {&mut writer,id,"roster_subscribe",- &json!({- "roster": [- roster_row("p", "idle", &parent_summary("p")),- roster_row("c", "running", &child_summary("c", "p", "worker one")),- ]- }),+ &json!({ "roster": self.roster }),);}"list_saved_sessions" => {@@ -149,6 +176,26 @@ impl MockSupervisor {"roster_unsubscribe" => {respond(&mut writer, id, "roster_unsubscribe", &Value::Null);}+ "list_kernel_bash" if self.shells.is_some() => {+ let probe = Arc::clone(self.shells.as_ref().expect("the probe"));+ if probe.unanswered.fetch_add(1, Ordering::SeqCst) > 0 {+ probe.overlapped.store(true, Ordering::SeqCst);+ }+ // The unanswered count drops before the reply is written: the client may send+ // its next request the moment the reply lands.+ if probe.requests.fetch_add(1, Ordering::SeqCst) == 0 {+ let mut writer = writer.try_clone().expect("clone socket");+ let id = id.to_string();+ std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(2700));+ probe.unanswered.fetch_sub(1, Ordering::SeqCst);+ respond(&mut writer, &id, "list_kernel_bash", &shells_reply(1));+ });+ } else {+ probe.unanswered.fetch_sub(1, Ordering::SeqCst);+ respond(&mut writer, id, "list_kernel_bash", &shells_reply(2));+ }+ }other => {respond_failure(&mut writer, id, other, "not handled by the mock");}@@ -158,6 +205,9 @@ impl MockSupervisor {}fn write_line(writer: &mut UnixStream, value: &Value) {+ // The probe's held reply writes from its own thread: one line at a time, never interleaved.+ static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ let _guard = WRITE_LOCK.lock().expect("write lock");let mut line = serde_json::to_string(value).expect("serialize line");line.push('\n');writer.write_all(line.as_bytes()).expect("write");@@ -244,10 +294,17 @@ fn view_options(socket: &std::path::Path) -> AgentsViewOptions {/// Run one headless plan and return the outcome. Holds the run lock: the click dispatch gates on/// the process-global tracking state.async fn run_plan(steps: Vec<AgentsStep>) -> pa_tui::agents_view::AgentsViewOutcome {+ run_plan_with(steps, |mock| mock).await+}++async fn run_plan_with(+ steps: Vec<AgentsStep>,+ configure: impl FnOnce(MockSupervisor) -> MockSupervisor,+) -> pa_tui::agents_view::AgentsViewOutcome {let _guard = RUN_LOCK.lock().await;let dir = tempfile::TempDir::new().expect("temp dir");let socket = dir.path().join("agents-view.sock");- let mock = MockSupervisor::bind(&socket);+ let mock = configure(MockSupervisor::bind(&socket));let server = std::thread::spawn(move || mock.serve());let plan = AgentsHeadlessPlan {steps,@@ -324,16 +381,16 @@ async fn a_click_on_an_inactive_row_opens_it() {);}-/// A plain click on the merged `N subagents (M running)` row EXPANDS the dropdown — the toggle, not+/// A plain click on the merged `N subagents · M running` row EXPANDS the dropdown — the toggle, not/// an open: the frame renders the child rows and the run keeps running with no selection.#[tokio::test]async fn a_click_on_the_merged_summary_expands_the_dropdown() {- let frames = settled_frames("subagents (").await;- let row = locate_row(&frames, "subagents (").expect("the merged line renders");+ let frames = settled_frames("1 subagent \u{b7}").await;+ let row = locate_row(&frames, "1 subagent \u{b7}").expect("the merged line renders");let outcome = run_plan(vec![AgentsStep::WaitSettle { timeout_ms: 2500 },AgentsStep::WaitRender {- needle: "subagents (".to_string(),+ needle: "1 subagent \u{b7}".to_string(),timeout_ms: 8000,},AgentsStep::Click { row, col: 4 },@@ -358,12 +415,12 @@ async fn a_click_on_the_merged_summary_expands_the_dropdown() {/// row.#[tokio::test]async fn a_click_on_the_expanded_child_opens_the_subagent() {- let frames = settled_frames("subagents (").await;- let summary = locate_row(&frames, "subagents (").expect("the merged line renders");+ let frames = settled_frames("1 subagent \u{b7}").await;+ let summary = locate_row(&frames, "1 subagent \u{b7}").expect("the merged line renders");let outcome = run_plan(vec![AgentsStep::WaitSettle { timeout_ms: 2500 },AgentsStep::WaitRender {- needle: "subagents (".to_string(),+ needle: "1 subagent \u{b7}".to_string(),timeout_ms: 8000,},AgentsStep::Click {@@ -380,7 +437,7 @@ async fn a_click_on_the_expanded_child_opens_the_subagent() {let outcome = run_plan(vec![AgentsStep::WaitSettle { timeout_ms: 2500 },AgentsStep::WaitRender {- needle: "subagents (".to_string(),+ needle: "1 subagent \u{b7}".to_string(),timeout_ms: 8000,},AgentsStep::Click {@@ -405,12 +462,12 @@ async fn a_click_on_the_expanded_child_opens_the_subagent() {/// merged line, the child rows, and the headings, then a plain click — the subagent still opens.#[tokio::test]async fn hover_motions_never_disturb_the_agents_view_click() {- let frames = settled_frames("subagents (").await;- let summary = locate_row(&frames, "subagents (").expect("the merged line renders");+ let frames = settled_frames("1 subagent \u{b7}").await;+ let summary = locate_row(&frames, "1 subagent \u{b7}").expect("the merged line renders");let outcome = run_plan(vec![AgentsStep::WaitSettle { timeout_ms: 2500 },AgentsStep::WaitRender {- needle: "subagents (".to_string(),+ needle: "1 subagent \u{b7}".to_string(),timeout_ms: 8000,},AgentsStep::Click {@@ -427,7 +484,7 @@ async fn hover_motions_never_disturb_the_agents_view_click() {let outcome = run_plan(vec![AgentsStep::WaitSettle { timeout_ms: 2500 },AgentsStep::WaitRender {- needle: "subagents (".to_string(),+ needle: "1 subagent \u{b7}".to_string(),timeout_ms: 8000,},// Hover motions across the parent row, the merged line, the heading, and the expanded child@@ -454,3 +511,178 @@ async fn hover_motions_never_disturb_the_agents_view_click() {"the click opened the subagent after the hover motions");}++/// The shells poll never stacks: with the first `list_kernel_bash` held past the poll interval, the+/// next request waits for it to land, and the line reaches the second answer's count.+#[tokio::test]+async fn a_slow_shells_read_never_stacks_the_poll() {+ let probe = Arc::new(ShellsProbe::default());+ let outcome = run_plan_with(+ vec![AgentsStep::WaitRender {+ needle: "$ 2 shells".to_string(),+ timeout_ms: 10_000,+ }],+ |mut mock| {+ mock.roster = vec![roster_row("p", "idle", &parent_summary("p"))];+ mock.shells = Some(Arc::clone(&probe));+ mock+ },+ )+ .await;+ assert!(+ outcome+ .frames+ .iter()+ .any(|frame| frame.contains("$ 2 shells")),+ "the poll re-armed after the held read landed"+ );+ assert!(+ !probe.overlapped.load(Ordering::SeqCst),+ "a list_kernel_bash arrived while another was unanswered"+ );+}++/// A cycle held across a session handoff belongs to the returning view, not the old UI channel.+#[tokio::test]+async fn a_held_shells_read_survives_the_agents_view_handoff() {+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt};++ let _guard = RUN_LOCK.lock().await;+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("handoff.sock");+ let listener = tokio::net::UnixListener::bind(&socket).expect("bind mock socket");+ let server = tokio::spawn(async move {+ let (stream, _) = listener.accept().await.expect("accept view connection");+ let (read, mut write) = stream.into_split();+ let hello = json!({+ "type": "daemon_hello",+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "serverCapabilities": ["kernel_bash_activity"],+ });+ write+ .write_all(format!("{hello}\n").as_bytes())+ .await+ .unwrap();+ let mut lines = tokio::io::BufReader::new(read).lines();+ let mut shells_requests = 0;+ let mut heartbeat_requests = 0;+ let mut held_shell = None;+ let mut held_catalog = None;+ while let Some(line) = lines.next_line().await.unwrap() {+ if line.is_empty() {+ break;+ }+ let envelope: Value = serde_json::from_str(&line).unwrap();+ let id = envelope["id"].as_str().unwrap().to_string();+ let command = envelope["command"]["type"].as_str().unwrap();+ let mut replies = Vec::new();+ match command {+ "roster_subscribe" => replies.push((+ id,+ json!({+ "roster": [roster_row("p", "idle", &parent_summary("p"))],+ }),+ )),+ "list_saved_sessions" => held_catalog = Some(id),+ "list_kernel_bash" => {+ shells_requests += 1;+ if shells_requests == 1 {+ held_shell = Some(id);+ } else {+ replies.push((id, shells_reply(2)));+ }+ }+ "heartbeats_list" => {+ heartbeat_requests += 1;+ replies.push((id, json!({"heartbeats": []})));+ if heartbeat_requests == 2 {+ replies.push((+ held_shell.take().expect("the first view issued its poll"),+ shells_reply(1),+ ));+ }+ }+ "roster_unsubscribe" => replies.push((id, Value::Null)),+ other => panic!("unexpected command: {other}"),+ }+ // The first view can open only after the server observed its unanswered shells read.+ if let (true, Some(id)) = (shells_requests > 0, held_catalog.as_ref()) {+ replies.push((+ id.clone(),+ json!({"sessions": [saved_row(+ "/tmp/sessions/old.jsonl", "old", "archived run",+ )]}),+ ));+ held_catalog = None;+ }+ for (id, data) in replies {+ let response_command = if data.get("activities").is_some() {+ "list_kernel_bash"+ } else if data.get("sessions").is_some() {+ "list_saved_sessions"+ } else {+ command+ };+ let reply = json!({+ "type": "response", "id": id, "command": response_command,+ "success": true, "data": data,+ });+ write+ .write_all(format!("{reply}\n").as_bytes())+ .await+ .unwrap();+ }+ }+ shells_requests+ });+ let first = run_agents_view(+ view_options(&socket),+ AgentsViewUiMode::Headless(AgentsHeadlessPlan {+ steps: vec![+ AgentsStep::WaitRender {+ needle: "archived run".to_string(),+ timeout_ms: 2500,+ },+ AgentsStep::Key("home".to_string()),+ AgentsStep::Key("enter".to_string()),+ ],+ width: 120,+ height: 36,+ }),+ None,+ )+ .await+ .expect("the first view opens its session");+ assert_eq!(+ first.outcome.selection,+ Some(SessionSelection::Attach("p-live".to_string()))+ );+ let second = run_agents_view(+ view_options(&socket),+ AgentsViewUiMode::Headless(AgentsHeadlessPlan {+ steps: vec![AgentsStep::WaitRender {+ needle: "$ 1 shell".to_string(),+ timeout_ms: 2500,+ }],+ width: 120,+ height: 36,+ }),+ Some(+ first+ .link+ .expect("the handoff retains the roster connection"),+ ),+ )+ .await+ .expect("the returning view consumes the held cycle");+ assert!(second+ .outcome+ .frames+ .iter()+ .any(|frame| frame.contains("$ 1 shell")));+ assert_eq!(+ server.await.unwrap(),+ 1,+ "re-entry must not issue a second shells request"+ );+}diff --git a/crates/pa-tui/tests/agents_view_persistent_shells_headless.rs b/crates/pa-tui/tests/agents_view_persistent_shells_headless.rsnew file mode 100644index 0000000000..057e9e8dfd--- /dev/null+++ b/crates/pa-tui/tests/agents_view_persistent_shells_headless.rs@@ -0,0 +1,365 @@+//! Headless e2e for the agents view's machine-wide persistent shells against a mock daemon: the+//! kill commands a stop sends from the orphans' Bash list and from Ctrl+X on a `Persistent shells`+//! row, and a late kill failure staying on its own shell.+#![cfg(unix)]++use std::io::{BufRead, BufReader, Write};+use std::os::unix::net::{UnixListener, UnixStream};+use std::path::PathBuf;+use std::time::Duration;++use pa_tui::agents_view::{+ run_agents_view, AgentsHeadlessPlan, AgentsStep, AgentsViewOptions, AgentsViewOutcome,+ AgentsViewUiMode,+};+use serde_json::{json, Value};++// Headless mouse tracking is process-global; all plans in this binary serialize.+static RUN_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++fn shell(id: &str, command: &str, session_id: &str, status: &str) -> Value {+ json!({ "id": id, "command": command, "pid": 4242, "startedAt": "2026-01-01T00:00:00+00:00",+ "durationMs": 12_400, "status": status, "persistent": true, "sessionId": session_id })+}++/// Serves the roster (one live session, `release prep`), an empty saved catalog, and three shells:+/// `build-watch` assigned to the live session, the orphans `long-job` and `orphan-watch` to deleted+/// ones. A kill finishes the shell in later lists (`long-job`'s kill fails late, delivered with+/// `orphan-watch`'s next output read); returns the killed shell ids.+fn serve(listener: &UnixListener) -> Vec<String> {+ let (stream, _) = listener.accept().expect("accept view connection");+ stream+ .set_read_timeout(Some(Duration::from_millis(100)))+ .expect("read timeout");+ let mut writer = stream.try_clone().expect("clone socket");+ let mut reader = BufReader::new(stream);+ write_line(+ &mut writer,+ &json!({+ "type": "daemon_hello",+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "serverCapabilities": ["persistent_shells"],+ }),+ );+ let mut killed = Vec::new();+ let mut pending_kill_failure: Option<String> = None;+ loop {+ let Some(line) = read_line(&mut reader) else {+ return killed;+ };+ let Ok(envelope) = serde_json::from_str::<Value>(&line) else {+ continue;+ };+ let id = envelope["id"].as_str().unwrap_or_default();+ let command = &envelope["command"];+ let command_type = command["type"].as_str().unwrap_or_default();+ let data = match command_type {+ "roster_subscribe" => json!({ "roster": [{+ "agentId": "p",+ "status": "idle",+ "summary": {+ "sessionId": "p",+ "lifecycle": "live",+ "activeSessionId": "p-live",+ "sessionFile": "/tmp/p.jsonl",+ "runtimeKind": "top-level",+ "sessionName": "release prep",+ "messageCount": 2,+ "rlmDepth": 0,+ },+ }] }),+ "list_saved_sessions" => json!({ "sessions": [] }),+ "list_persistent_shells" => {+ let status = |id: &str| {+ if killed.iter().any(|killed| killed == id) {+ "finished"+ } else {+ "running"+ }+ };+ json!({ "activities": [+ shell("b", "build-watch", "p", status("b")),+ shell("l", "long-job", "gone", status("l")),+ shell("o", "orphan-watch", "gone-too", status("o")),+ ] })+ }+ "tail_persistent_shell" => {+ // Deliver the old shell's error only once another shell's+ // pane has opened and requested its output.+ if command["shellId"] == "o" {+ if let Some(kill_id) = pending_kill_failure.take() {+ respond_failure(+ &mut writer,+ &kill_id,+ "kill_persistent_shell",+ "old shell kill failed",+ );+ }+ }+ json!({ "shellId": command["shellId"], "tail": "watching..." })+ }+ "kill_persistent_shell" => {+ if command["shellId"] == "l" {+ pending_kill_failure = Some(id.to_string());+ continue;+ }+ killed.push(command["shellId"].as_str().unwrap_or_default().to_string());+ json!({ "shellId": command["shellId"] })+ }+ "roster_unsubscribe" => Value::Null,+ other => {+ respond_failure(&mut writer, id, other, "not handled by the mock");+ continue;+ }+ };+ respond(&mut writer, id, command_type, &data);+ }+}++fn write_line(writer: &mut UnixStream, value: &Value) {+ let mut line = serde_json::to_string(value).expect("serialize line");+ line.push('\n');+ writer.write_all(line.as_bytes()).expect("write");+ writer.flush().expect("flush");+}++fn respond(writer: &mut UnixStream, id: &str, command: &str, data: &Value) {+ write_line(+ writer,+ &json!({+ "id": id,+ "type": "response",+ "command": command,+ "success": true,+ "data": data,+ }),+ );+}++fn respond_failure(writer: &mut UnixStream, id: &str, command: &str, error: &str) {+ write_line(+ writer,+ &json!({+ "id": id,+ "type": "response",+ "command": command,+ "success": false,+ "error": error,+ }),+ );+}++/// One line with a bounded quiet window; `None` ends the serve loop on EOF or the quiet cap.+fn read_line(reader: &mut BufReader<UnixStream>) -> Option<String> {+ const QUIET_WINDOW_MS: u32 = 90;+ let mut quiet_windows: u32 = 0;+ let mut line = String::new();+ loop {+ match reader.read_line(&mut line) {+ Ok(0) => return None,+ Ok(_) if line.trim().is_empty() => {+ line.clear();+ }+ Ok(_) => return Some(line),+ Err(error)+ if matches!(+ error.kind(),+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut+ ) =>+ {+ quiet_windows += 1;+ if quiet_windows >= QUIET_WINDOW_MS {+ return None;+ }+ std::thread::sleep(Duration::from_millis(50));+ line.clear();+ }+ Err(_) => return None,+ }+ }+}++fn view_options(socket: &std::path::Path) -> AgentsViewOptions {+ AgentsViewOptions {+ socket_path: socket.to_path_buf(),+ cwd: PathBuf::from("/tmp"),+ session_dir: Some(PathBuf::from("/tmp/sessions")),+ theme: "prime".to_string(),+ version: "0.0.0".to_string(),+ anchor_session_id: None,+ scope: None,+ query: None,+ expanded_ancestors: Vec::new(),+ selected_row_identity: None,+ selected_key: None,+ status_message: None,+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),+ show_hardware_cursor: false,+ incident_notice_state: None,+ create_config: serde_json::json!({}),+ }+}++/// Run one headless plan against the mock; returns the outcome and the killed shell ids.+async fn run_plan(steps: Vec<AgentsStep>) -> (AgentsViewOutcome, Vec<String>) {+ let _guard = RUN_LOCK.lock().await;+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("agents-view.sock");+ let listener = UnixListener::bind(&socket).expect("bind mock socket");+ let server = std::thread::spawn(move || serve(&listener));+ let plan = AgentsHeadlessPlan {+ steps,+ width: 100,+ height: 30,+ };+ let outcome = Box::pin(run_agents_view(+ view_options(&socket),+ AgentsViewUiMode::Headless(plan),+ None,+ ))+ .await+ .expect("the agents view run")+ .outcome;+ (outcome, server.join().expect("mock"))+}++fn wait_render(needle: &str) -> AgentsStep {+ AgentsStep::WaitRender {+ needle: needle.to_string(),+ timeout_ms: 8000,+ }+}++#[tokio::test]+async fn enter_on_an_orphan_lists_the_orphans_and_stops_one() {+ let (outcome, killed) = run_plan(vec![+ AgentsStep::WaitSettle { timeout_ms: 2500 },+ wait_render("$ orphan-watch"),+ AgentsStep::Key("home".to_string()),+ AgentsStep::Key("down".to_string()),+ AgentsStep::Key("down".to_string()),+ AgentsStep::Key("enter".to_string()),+ wait_render("Session deleted"),+ AgentsStep::Key("enter".to_string()),+ wait_render("watching..."),+ AgentsStep::Key("enter".to_string()),+ wait_render("\u{25cb} finished"),+ AgentsStep::Key("left".to_string()),+ wait_render("1 running"),+ AgentsStep::Key("escape".to_string()),+ wait_render("Persistent shells (2)"),+ ])+ .await;++ assert_eq!(killed, ["o"], "the stop named the Entered orphan");+ let last = outcome.frames.last().expect("a frame");+ assert!(+ !last.contains("$ orphan-watch") && last.contains("$ long-job"),+ "the stopped orphan left the list:\n{last}"+ );+}++#[tokio::test]+async fn a_late_kill_failure_does_not_move_to_another_shell_pane() {+ let (outcome, _) = run_plan(vec![+ AgentsStep::WaitSettle { timeout_ms: 2500 },+ wait_render("$ orphan-watch"),+ AgentsStep::Key("home".to_string()),+ AgentsStep::Key("down".to_string()),+ AgentsStep::Key("enter".to_string()),+ wait_render("Session deleted"),+ AgentsStep::Key("enter".to_string()),+ wait_render("watching..."),+ AgentsStep::Key("enter".to_string()),+ AgentsStep::Key("left".to_string()),+ AgentsStep::Key("down".to_string()),+ AgentsStep::Key("enter".to_string()),+ wait_render("watching..."),+ ])+ .await;+ let frames = &outcome.frames;+ assert!(frames+ .last()+ .expect("shell o frame")+ .contains("orphan-watch"));+ assert!(+ !frames+ .iter()+ .any(|frame| frame.contains("old shell kill failed")),+ "shell l's failure must not appear on shell o"+ );+}++#[tokio::test]+async fn ctrl_x_on_a_shell_row_stops_it_and_its_finished_row_leaves_the_list() {+ let (outcome, killed) = run_plan(vec![+ AgentsStep::WaitSettle { timeout_ms: 2500 },+ wait_render("$ orphan-watch"),+ AgentsStep::Key("home".to_string()),+ wait_render("open Ctrl+X stop"),+ AgentsStep::Key("ctrl+x".to_string()),+ wait_render("Press Ctrl+X again to stop"),+ AgentsStep::Key("ctrl+x".to_string()),+ wait_render("Persistent shells (2)"),+ ])+ .await;++ assert_eq!(killed, ["b"], "the stop named the selected shell");+ let last = outcome.frames.last().expect("a frame");+ assert!(+ last.contains("Stopped build-watch") && !last.contains("$ build-watch"),+ "the stopped shell left the list:\n{last}"+ );+}++/// A session opened from its shell row returns onto that row: the handoff carries the shells list,+/// so the returning view's first frame already lists the shell the selection restores onto.+#[tokio::test]+async fn a_return_from_a_shells_session_restores_the_shell_row() {+ let _guard = RUN_LOCK.lock().await;+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("agents-view.sock");+ let listener = UnixListener::bind(&socket).expect("bind mock socket");+ let _server = std::thread::spawn(move || serve(&listener));+ let plan = |steps| {+ AgentsViewUiMode::Headless(AgentsHeadlessPlan {+ steps,+ width: 100,+ height: 30,+ })+ };+ let first = Box::pin(run_agents_view(+ view_options(&socket),+ plan(vec![+ AgentsStep::WaitSettle { timeout_ms: 2500 },+ wait_render("$ orphan-watch"),+ AgentsStep::Key("home".to_string()),+ AgentsStep::Key("enter".to_string()),+ ]),+ None,+ ))+ .await+ .expect("the first view opens the shell's session");+ assert_eq!(+ first.outcome.selected_row_identity.as_deref(),+ Some("shell:b")+ );+ let mut options = view_options(&socket);+ options.selected_row_identity = first.outcome.selected_row_identity.clone();+ options.selected_key = first.outcome.selected_key.clone();+ let second = Box::pin(run_agents_view(+ options,+ plan(vec![AgentsStep::Key("enter".to_string())]),+ first.link,+ ))+ .await+ .expect("the returning view")+ .outcome;+ let first_frame = second.frames.first().expect("a first frame");+ assert!(first_frame.contains("$ build-watch"), "{first_frame}");+ assert_eq!(+ second.selected_row_identity.as_deref(),+ Some("shell:b"),+ "Enter reopened the shell row the return restored"+ );+}diff --git a/crates/pa-tui/tests/daemon_rejection_headless.rs b/crates/pa-tui/tests/daemon_rejection_headless.rsindex 0848083e00..c5bfc4cf11 100644--- a/crates/pa-tui/tests/daemon_rejection_headless.rs+++ b/crates/pa-tui/tests/daemon_rejection_headless.rs@@ -569,8 +569,12 @@ fn run_plan(let options = options_with_session(socket, selection);let outcome = runtime.block_on(async {if agents_view_open {- pa_tui::interactive::run_interactive_agents_view_open(options, UiMode::Headless(plan))- .await+ pa_tui::interactive::run_interactive_agents_view_open(+ options,+ UiMode::Headless(plan),+ None,+ )+ .await} else {run_interactive(options, UiMode::Headless(plan)).await}diff --git a/crates/pa-tui/tests/dock_arrows_headless.rs b/crates/pa-tui/tests/dock_arrows_headless.rsindex c6705738f5..281ca85c65 100644--- a/crates/pa-tui/tests/dock_arrows_headless.rs+++ b/crates/pa-tui/tests/dock_arrows_headless.rs@@ -733,7 +733,7 @@ fn goal_event_push(seconds: u64) -> Value {fn a_roster_push_alone_remounts_the_dock_count_and_the_title_cost() {let steps = vec![HeadlessStep::WaitRender {- needle: "\u{25c6} 1 subagents".to_string(),+ needle: "\u{25c6} 1 subagent".to_string(),timeout_ms: 5_000,},HeadlessStep::WaitRender {@@ -748,7 +748,7 @@ fn a_roster_push_alone_remounts_the_dock_count_and_the_title_cost() {let outcome = run_plan_with_roster(steps, None, None, Vec::new(), pushes);let last = outcome.frames.last().cloned().unwrap_or_default();assert!(- last.contains("\u{25c6} 1 subagents") && last.contains("$0.42"),+ last.contains("\u{25c6} 1 subagent") && last.contains("$0.42"),"the roster push repainted the dock's running count and the title's family cost:\n{}",outcome.frames.join("\n"));@@ -805,7 +805,7 @@ fn d_the_attach_mounts_the_snapshot_counts_in_its_first_frame_and_a_switch_follo},HeadlessStep::Submit("/new".to_string()),HeadlessStep::WaitRender {- needle: "\u{25c6} 1 subagents".to_string(),+ needle: "\u{25c6} 1 subagent".to_string(),timeout_ms: 5_000,},];@@ -821,7 +821,7 @@ fn d_the_attach_mounts_the_snapshot_counts_in_its_first_frame_and_a_switch_follolet first_count = outcome.frames.iter()- .position(|frame| frame.contains("\u{25c6} 1 subagents"));+ .position(|frame| frame.contains("\u{25c6} 1 subagent"));let first_note = outcome.frames.iter()diff --git a/crates/pa-tui/tests/dock_panel_exit_focus_headless.rs b/crates/pa-tui/tests/dock_panel_exit_focus_headless.rsindex 9e81c73666..33be57d6b5 100644--- a/crates/pa-tui/tests/dock_panel_exit_focus_headless.rs+++ b/crates/pa-tui/tests/dock_panel_exit_focus_headless.rs@@ -1,7 +1,8 @@//! Headless e2e for the dock panels' exit focus (operator ruling//! 2026-09-26): ESC/left from a dock panel returns to chat with the//! panel's dock item still selected — the dock holds focus, not the-//! prompt bar; the next Enter re-opens the SAME panel.+//! prompt bar; the next Enter re-opens the SAME panel. A panel the agents view requested on open+//! closes back to the agents view instead.#![cfg(unix)]// Casts: structurally bounded terminal-layout arithmetic; guarded conversions add panic paths.#![allow(@@ -25,19 +26,22 @@ use std::path::PathBuf;use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};use pa_tui::interactive::{- run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, InteractiveOutcome,- ModelSelection, SessionSelection, UiMode,+ run_interactive, run_interactive_agents_view_open, HeadlessPlan, HeadlessStep,+ InteractiveOptions, InteractiveOutcome, ModelSelection, SessionPanel, SessionSelection, UiMode,};use serde_json::{json, Value};struct MockSupervisor {listener: UnixListener,+ /// The factory graph reply; `Some` also advertises the factory lane.+ factory_graph: Option<Value>,}impl MockSupervisor {- fn bind(socket: &std::path::Path) -> Self {+ fn bind(socket: &std::path::Path, factory_graph: Option<Value>) -> Self {MockSupervisor {listener: UnixListener::bind(socket).expect("bind mock socket"),+ factory_graph,}}@@ -51,10 +55,14 @@ impl MockSupervisor {// The hello advertises the kernel-bash activity capability: the registry poll is// capability-gated (the dock and the shells view stay empty without it).+ let mut capabilities = vec!["kernel_bash_activity"];+ if self.factory_graph.is_some() {+ capabilities.push("factory_activity");+ }let hello = json!({"type": "daemon_hello","protocol": { "name": "prime-agent.daemon", "version": 7 },- "serverCapabilities": ["kernel_bash_activity"],+ "serverCapabilities": capabilities,"clientId": "mock",});write_json(&mut writer, &hello);@@ -142,6 +150,18 @@ impl MockSupervisor {}),);}+ "factory_activity" => {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "factory_activity",+ "success": true,+ "data": self.factory_graph.clone().unwrap_or(Value::Null),+ }),+ );+ }"get_session_stats" => {write_json(&mut writer,@@ -273,10 +293,18 @@ fn options(socket: PathBuf) -> InteractiveOptions {}fn run_plan(steps: Vec<HeadlessStep>) -> InteractiveOutcome {+ run_plan_with(steps, None, None)+}++fn run_plan_with(+ steps: Vec<HeadlessStep>,+ open_panel: Option<SessionPanel>,+ factory_graph: Option<Value>,+) -> InteractiveOutcome {std::env::remove_var("TMUX");let dir = tempfile::TempDir::new().expect("temp dir");let socket = dir.path().join("tui.sock");- let supervisor = MockSupervisor::bind(&socket);+ let supervisor = MockSupervisor::bind(&socket, factory_graph);let handle = std::thread::spawn(move || supervisor.serve());let runtime = tokio::runtime::Builder::new_multi_thread()@@ -289,7 +317,19 @@ fn run_plan(steps: Vec<HeadlessStep>) -> InteractiveOutcome {height: 30,};let outcome = runtime- .block_on(run_interactive(options(socket), UiMode::Headless(plan)))+ .block_on(async {+ match open_panel {+ Some(panel) => {+ run_interactive_agents_view_open(+ options(socket),+ UiMode::Headless(plan),+ Some(panel),+ )+ .await+ }+ None => run_interactive(options(socket), UiMode::Headless(plan)).await,+ }+ }).expect("interactive run");handle.join().expect("mock supervisor finished");outcome@@ -506,3 +546,57 @@ fn goal_panel_left_returns_to_the_dock_item() {"the exit stays in the chat view");}++/// The agents view's shells line opens the chat with the shells panel mounted; Esc hands the pane+/// straight back to the agents view.+#[test]+fn agents_view_shells_panel_esc_returns_to_the_agents_view() {+ let outcome = run_plan_with(+ vec![wait_render("render the frames"), key(KeyCode::Esc)],+ Some(SessionPanel::Shells { shell_id: None }),+ None,+ );+ assert!(+ outcome+ .frames+ .iter()+ .any(|frame| frame.contains("render the frames")),+ "the shells panel mounted on open"+ );+ assert!(+ outcome.return_to_agents_view,+ "the panel's close returns to the agents view"+ );+}++/// The factory line mounts the factory page on its run list even with exactly one live run.+#[test]+fn agents_view_factory_panel_opens_on_the_run_list_and_returns() {+ let graph = json!({+ "runs": [{+ "runId": "run-1",+ "specId": "solo-spec",+ "state": "running",+ "elapsedMs": 100,+ "machine": { "states": [], "transitions": [] },+ "nodes": [],+ "usage": { "running": 0 },+ }]+ });+ let outcome = run_plan_with(+ vec![wait_render("solo-spec"), key(KeyCode::Esc)],+ Some(SessionPanel::FactoryRuns),+ Some(graph),+ );+ assert!(+ outcome+ .frames+ .iter()+ .any(|frame| frame.contains("solo-spec") && frame.contains("actions \u{b7}")),+ "the factory page mounted on its run list"+ );+ assert!(+ outcome.return_to_agents_view,+ "the page's close returns to the agents view"+ );+}diff --git a/crates/pa-tui/tests/factory_command_headless.rs b/crates/pa-tui/tests/factory_command_headless.rsindex 0b189f7651..97c9ee0915 100644--- a/crates/pa-tui/tests/factory_command_headless.rs+++ b/crates/pa-tui/tests/factory_command_headless.rs@@ -99,6 +99,9 @@ impl MockSupervisor {});write_json(&mut writer, &hello);+ // A page stop also stops the mock's session: the daemon's `session_closed` follows the+ // stop's reply, and the closed session's graph lane answers a refusal from then on.+ let mut session_closed = false;let mut line = String::new();loop {line.clear();@@ -169,8 +172,35 @@ impl MockSupervisor {// kernel-not-running wire shape) or the configured// runs reply; every other action answers empty data// (the guard reads the graph list only).+ if command.get("action").and_then(Value::as_str) == Some("stop") {+ write_json(+ &mut writer,+ &json!({+ "type": "response",+ "id": id,+ "command": "factory_activity",+ "success": true,+ "data": { "state": "stopping" },+ }),+ );+ write_json(+ &mut writer,+ &json!({+ "type": "session_closed",+ "activeSessionId": "s1",+ "reason": "killed",+ }),+ );+ session_closed = true;+ continue;+ }if command.get("action").and_then(Value::as_str) == Some("graph") {- if let Some(error) = factory_graph_error.as_ref() {+ let error = if session_closed {+ Some("Unknown active session: s1".to_string())+ } else {+ factory_graph_error.clone()+ };+ if let Some(error) = error.as_ref() {write_json(&mut writer,&json!({@@ -883,3 +913,36 @@ fn factory_page_picker_keys_paint_the_moved_selection_on_the_key() {"the arrow's own repaint painted the moved selection before the page closed:\n{all}");}++/// A session the daemon stops while its factory page is open leaves no stale run cards: the+/// close clears the dock's run cache and the mounted page with it.+#[test]+fn a_closed_session_clears_the_open_factory_page() {+ let graph = json!({ "runs": [factory_page_run("run-1", "only-run")] });+ let steps = vec![+ HeadlessStep::Key(alt_a()),+ HeadlessStep::Key(down()),+ HeadlessStep::Key(down()),+ HeadlessStep::Key(down()),+ HeadlessStep::Key(enter()),+ HeadlessStep::WaitRender {+ needle: "factory: only-run".to_string(),+ timeout_ms: 5_000,+ },+ // Enter opens the run's action rows, the second Enter stops it; the mock's daemon then+ // closes the session.+ HeadlessStep::Key(enter()),+ HeadlessStep::Key(enter()),+ HeadlessStep::WaitRender {+ needle: "No live factory runs.".to_string(),+ timeout_ms: 5_000,+ },+ HeadlessStep::WaitMs(200),+ ];+ let frames = run_plan_config(vec!["factory_activity".to_string()], Some(graph), steps);+ let last = flat_text(&frames[frames.len() - 1..]);+ assert!(+ last.contains("No live factory runs.") && !last.contains("only-run"),+ "the closed session's page drops its run cards:\n{last}"+ );+}diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rsindex 3a464a7088..fb6bcaa378 100644--- a/crates/pa-types/src/daemon/command.rs+++ b/crates/pa-types/src/daemon/command.rs@@ -557,6 +557,29 @@ pub enum DaemonCommand {#[serde(flatten)]rest: JsonMap,},+ /// Every persistent `bash()` shell machine-wide with its assigned session id.+ /// Rust-native extension, advertised by the `persistent_shells` capability.+ ListPersistentShells {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ id: Option<String>,+ #[serde(flatten)]+ rest: JsonMap,+ },+ TailPersistentShell {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ id: Option<String>,+ shell_id: String,+ lines: u32,+ #[serde(flatten)]+ rest: JsonMap,+ },+ KillPersistentShell {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ id: Option<String>,+ shell_id: String,+ #[serde(flatten)]+ rest: JsonMap,+ },/// The `/factory` view's bridge lane over the session kernel's factory/// executor (`graph`/`status`/`watch`/`run`/`stop`/`resume`)./// Rust-native extension, advertised by the `factory_activity` capability.diff --git a/crates/pa-types/src/daemon/plane.rs b/crates/pa-types/src/daemon/plane.rsindex b79dd5275b..7d70510fb4 100644--- a/crates/pa-types/src/daemon/plane.rs+++ b/crates/pa-types/src/daemon/plane.rs@@ -123,6 +123,8 @@ const READ_ONLY_DAEMON_COMMANDS: &[&str] = &["wait_for_idle","list_kernel_bash","tail_kernel_bash",+ "list_persistent_shells",+ "tail_persistent_shell","get_session_header","get_state","get_connection_state",diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 90e85f85fe..4a40f277e4 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -8,7 +8,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from .bash import BashHandle, BashResult, BashSnapshot, bash, _set_completion_notices_wired+from .bash import BashHandle, BashResult, BashSnapshot, bash, persistent_shells, _set_completion_notices_wiredfrom .factory import (FACTORY_HELP,graph_factory,@@ -723,6 +723,7 @@ __all__ = ["harness","host_request","list_subagents",+ "persistent_shells","progress_note","rename","rlm",diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.pyindex 2c6297d0a0..c0c4ddb790 100644--- a/prime-agent-runtime/src/rlm/bash.py+++ b/prime-agent-runtime/src/rlm/bash.py@@ -94,14 +94,14 @@ _MAX_DEGRADE_HINTS = 3_degrade_hints_written = 0-def _note_degrade(handle: "BashHandle") -> None:+def _note_degrade(handle: "BashHandle", bound: float) -> None:"""Write the degrade hint to the awaiting cell's stderr, within budget."""global _degrade_hints_writtenif _degrade_hints_written >= _MAX_DEGRADE_HINTS:return_degrade_hints_written += 1sys.stderr.write(- f"bash: still running after {handle._yield_after:g}s (pid {handle._pid}); "+ f"bash: still running after {bound:g}s (pid {handle._pid}); ""returned a snapshot: r.running is True, r.output is the output so ""far, r.handle is the live handle. End the turn — a [bash-done] ""notification arrives when it finishes.\n"@@ -148,6 +148,22 @@ _live_lock = threading.Lock()_hook_installed = False_hook_lock = threading.Lock()+# bash(persistent=True): every session's persistent shells live in one home+# under the agent dir (the cross-language contract pa-daemon reads): per shell+# a <id>.json record assigned to its session (RLM_SESSION_ID, the durable+# session id the host exports), plus <id>.out and <id>.rc.+_PERSISTENT_DIR = "persistent-shells"+_PERSISTENT_POLL = 1.0+# Gate on stdin, then run the command in its own shell so exit/exec/set -e+# cannot skip the atomic status write.+_PERSISTENT_WRAPPER = (+ "read -r _prime_agent_gate || exit 127\n"+ "exec 0</dev/null\n"+ '"$1" -c "$2"\n'+ "__prime_status=$?\n"+ "printf '%s\\n' \"$__prime_status\" > \"$3.tmp\" && mv -f \"$3.tmp\" \"$3\"\n"+)+def _current_cell_completion_context() -> tuple[asyncio.Event, asyncio.Task[Any] | None] | None:"""Get the creating REPL cell's lifecycle without coupling standalone use to repl."""@@ -365,8 +381,8 @@ class BashHandle:def __init__(self, command: str, yield_after: float | None = None) -> None:self.command = command- # The bound every await of this handle uses (None = unbounded); the- # caller's effective value, resolved once in bash().+ # The requested bound (None = the session default); every await+ # resolves it through _effective_yield_after.self._yield_after = yield_afterself._activity_id = secrets.token_hex(16)completion_context = _current_cell_completion_context()@@ -1054,13 +1070,14 @@ class BashHandle:except RuntimeError:current_task = Nonecreating_cell_waited = _creating_cell_waits_for(self._creating_cell_task, current_task)+ bound = _effective_yield_after(self._yield_after)owned = not self._releasedwait = self._wait_owned() if owned else self._wait()self._released = Truecompleted = Falsedegraded = Falsetry:- result = yield from _bounded_wait(wait, self._yield_after).__await__()+ result = yield from _bounded_wait(wait, bound).__await__()if result is None:degraded = Trueelse:@@ -1080,7 +1097,7 @@ class BashHandle:if completed:self._note_result_consumed(current_task)if degraded:- _note_degrade(self)+ _note_degrade(self, cast("float", bound))return self._degrade_snapshot()return cast("BashResult", result)@@ -1107,7 +1124,193 @@ class BashHandle:return f"<BashHandle pid={self._pid} {state} command={self.command!r}>"-def bash(command: str, yield_after: float | None = None) -> BashHandle:+class _OutputFile:+ """Bounded view of a persistent shell's output file: first _HEAD_CAP plus last _TAIL_CAP bytes.++ keep() holds the final text in memory, so the file can be removed.+ """++ def __init__(self, path: str) -> None:+ self._path = path+ self._kept: str | None = None++ def keep(self) -> None:+ self._kept = self.text()++ def text(self) -> str:+ if self._kept is not None:+ return self._kept+ try:+ f = open(self._path, "rb")+ except FileNotFoundError:+ return ""+ with f:+ size = os.fstat(f.fileno()).st_size+ if size <= _HEAD_CAP + _TAIL_CAP:+ return f.read(size).decode("utf-8", errors="replace")+ head = f.read(_HEAD_CAP)+ f.seek(size - _TAIL_CAP)+ tail = f.read(_TAIL_CAP)+ marker = f"\n... [{size - _HEAD_CAP - _TAIL_CAP} bytes dropped] ...\n"+ return head.decode("utf-8", errors="replace") + marker + tail.decode("utf-8", errors="replace")+++class PersistentBashHandle(BashHandle):+ """bash(..., persistent=True); see bash() for its lifecycle.++ Its record (assigned to the session), output, and exit status are files in+ the agent dir's persistent-shells home instead of an orphan journal entry.+ Awaits never own it: cancelling an await leaves it running. Finished+ output is kept in memory. Files remain recoverable on read errors or when+ a leaderless group cannot be verified because no watcher saw its leader+ exit; such a group is never signalled using only its old numeric+ process-group id.+ """++ def __init__(+ self,+ command: str,+ shell_id: str,+ pid: int,+ start_id: str,+ started_at: str,+ home: str,+ proc: subprocess.Popen[bytes] | None,+ running: bool = True,+ yield_after: float | None = None,+ ) -> None:+ self.command = command+ self._yield_after = yield_after+ self._activity_id = shell_id+ completion_context = _current_cell_completion_context()+ self._creating_cell_finished = completion_context[0] if completion_context else None+ self._creating_cell_task = completion_context[1] if completion_context else None+ self._awaited_by_creating_cell = False+ self._home = home+ self._buffer = _OutputFile(_persistent_file(home, shell_id, "out")) # type: ignore[assignment]+ self._rc_path = _persistent_file(home, shell_id, "rc")+ self._done = threading.Event()+ self._result: BashResult | None = None+ self._completion_error: OSError | ValueError | None = None+ self._callbacks: list[Callable[[], None]] = []+ self._reap_callback: Callable[[], None] | None = None+ self._result_consumed = False+ self._consumed_notice: Callable[[], None] | None = None+ self._callback_lock = threading.Lock()+ self._reaped = False+ self._kill_lock = threading.Lock()+ self._started_at = started_at+ self._started = time.monotonic() - max(+ 0.0, (datetime.now(timezone.utc) - datetime.fromisoformat(started_at)).total_seconds()+ )+ self._pid = pid+ self._start_id = start_id+ self._proc = proc # type: ignore[assignment]+ self._released = True+ with _live_lock:+ _activity_handles[shell_id] = self+ threading.Thread(target=self._watch, args=(running,), daemon=True).start()+ self._schedule_background_completion_notice()++ def kill(self, sig: int = signal.SIGTERM, grace: float = 5.0) -> None:+ # Even a fresh Popen may have been reaped by the watcher before it+ # commits _reaped. Every persistent signal must check its identity.+ with self._kill_lock:+ if self._reaped or _shell_identity(self._pid, self._start_id) is not True:+ return+ super().kill(sig, grace)++ def _force_kill(self) -> None:+ with self._kill_lock:+ if not self._reaped:+ _reap_persistent_group(self._pid, self._start_id)++ def _watch(self, running: bool) -> None:+ # running=False: the shell finished while no kernel ran; its pid may+ # since name another process, so it is never polled or signalled.+ exit_code = -1+ if self._proc is not None:+ exit_code = self._proc.wait()+ elif running:+ # Not our child, so nothing to wait() on: poll the rc file and the+ # pid identity (completion lags by up to _PERSISTENT_POLL seconds).+ while not os.path.exists(self._rc_path) and _shell_identity(self._pid, self._start_id) is not False:+ time.sleep(_PERSISTENT_POLL)+ try:+ with open(self._rc_path) as f:+ exit_code = int(f.read())+ except FileNotFoundError:+ pass # killed before the wrapper recorded a status+ except (OSError, ValueError) as error:+ self._completion_error = error+ # A dead leader's group can still contain the shell's children. A live+ # recycled pid instead names a stranger's group and must not be signalled.+ with self._kill_lock:+ reaped = _reap_persistent_group(+ self._pid, self._start_id, leader_exit_witnessed=self._proc is not None or running+ )+ self._reaped = True+ try:+ cast("_OutputFile", self._buffer).keep()+ except OSError as error:+ self._completion_error = error+ if self._completion_error is None and reaped:+ _remove_shell_files(self._home, self._activity_id)+ # Failed I/O must settle waiters too, without losing the recoverable files.+ self._finalize(exit_code, "" if self._completion_error is not None else None)+ with self._callback_lock:+ callback, self._reap_callback = self._reap_callback, None+ if callback is not None:+ callback()+ with _live_lock:+ _activity_order.append(self._activity_id)+ while len(_activity_order) > _ACTIVITY_HISTORY_CAP:+ _activity_handles.pop(_activity_order.popleft(), None)++ async def _wait(self) -> BashResult:+ result = await super()._wait()+ if self._completion_error is not None:+ raise self._completion_error+ return result++ def poll(self) -> BashResult | None:+ result = super().poll()+ if result is not None and self._completion_error is not None:+ raise self._completion_error+ return result++ def _schedule_background_completion_notice(self) -> None:+ # No bash-activity residency hold: the shell survives kernel release.+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return+ loop.create_task(self._notify_completion()).add_done_callback(_consume_notice_task)++ async def _notify_completion(self) -> None:+ from . import repl++ try:+ result = await self._wait()+ if self._creating_cell_finished is not None:+ await self._creating_cell_finished.wait()+ if self._awaited_by_creating_cell or self._result_consumed or not repl.is_active():+ return+ command = _capped(self.command)+ reply = await repl.host_request(+ {"type": "bash.completed", "pid": self._pid, "command": command, "exitCode": result.exit_code}+ )+ if isinstance(reply, dict) and reply.get("status") == "ok":+ self._arm_consumed_notice(command)+ except (OSError, RuntimeError):+ return++ def __repr__(self) -> str:+ state = f"exit_code={self._result.exit_code}" if self._result else "running"+ return f"<BashHandle persistent pid={self._pid} {state} command={self.command!r}>"+++def bash(command: str, yield_after: float | None = None, persistent: bool = False) -> BashHandle:"""Start a shell command immediately; await the handle for the result.`await bash(cmd)` is a one-shot: cancelling the await (e.g. an interrupt)@@ -1129,13 +1332,29 @@ def bash(command: str, yield_after: float | None = None) -> BashHandle:Output written after the completion fence (e.g. by an EXIT trap or abackground job) is not in BashResult.output but stays visible viahandle.output()/tail().++ persistent=True (POSIX, saved sessions only; use only when really+ required, e.g. a server or long job that must outlive a restart): the+ shell survives kernel, worker, and daemon restarts and its session's+ delete or archive (a deleted session's shells keep running as orphans);+ only its own exit or an explicit kill() ends it. Its output and exit+ status live in files under the agent dir, and awaits never own it: an+ await bounded by yield_after degrades as for any handle and the shell runs+ on. After a restart, get the handles back with `from rlm import+ persistent_shells; persistent_shells()`; a shell that finished while no+ kernel ran is listed once, finished. Completion of a re-attached shell is+ polled, so its result and completion notice lag by up to a second; its+ exit_code is -1 when it was killed before recording a status."""if not isinstance(command, str) or not command:raise TypeError("command must be a non-empty str")if yield_after is not None and yield_after <= 0:raise ValueError("yield_after must be a positive number of seconds")- _install_shutdown_hook()- handle = BashHandle(command, _effective_yield_after(yield_after))+ if persistent:+ handle: BashHandle = _spawn_persistent(command, yield_after)+ else:+ _install_shutdown_hook()+ handle = BashHandle(command, yield_after)from . import replrepl.emit(@@ -1259,6 +1478,185 @@ def _helper_env() -> dict[str, str]:return {**os.environ, "NoDefaultCurrentDirectoryInExePath": "1"}+def _persistent_home() -> str:+ return os.path.join(os.environ["PRIME_AGENT_CODING_AGENT_DIR"], _PERSISTENT_DIR)+++def _persistent_file(home: str, shell_id: str, kind: str) -> str:+ return os.path.join(home, f"{shell_id}.{kind}")+++def _remove_shell_files(home: str, shell_id: str) -> None:+ # The record goes last: until then, the next boot still finds and removes the rest.+ for kind in ("rc", "out", "json"):+ try:+ os.remove(_persistent_file(home, shell_id, kind))+ except OSError:+ pass+++def _session_records(home: str, session_id: str) -> list[dict[str, Any]]:+ """The records assigned to session_id, oldest first."""+ try:+ names = os.listdir(home)+ except FileNotFoundError:+ return []+ records = []+ for name in names:+ if not name.endswith(".json"):+ continue+ try:+ with open(os.path.join(home, name)) as f:+ record = json.load(f)+ except FileNotFoundError:+ continue # its kernel removed the finished shell meanwhile+ if record["sessionId"] == session_id:+ records.append(record)+ return sorted(records, key=lambda record: record["startedAt"])+++def _pid_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ pass+ # kill(0) also accepts zombies. Match the host's liveness policy so a+ # reattached shell can finish without waiting for another process to reap it.+ try:+ if sys.platform.startswith("linux"):+ with open(f"/proc/{pid}/stat") as stat_file:+ stat = stat_file.read()+ return stat[stat.rindex(")") + 2:].split()[0] != "Z"+ if sys.platform == "darwin":+ state = subprocess.run(+ ["/bin/ps", "-p", str(pid), "-o", "stat="],+ capture_output=True, text=True, timeout=5,+ env={**os.environ, "LC_ALL": "C", "LANG": "C"},+ )+ return state.returncode != 0 or not state.stdout.lstrip().startswith("Z")+ except (OSError, ValueError, IndexError, subprocess.SubprocessError):+ pass # unknown state stays alive; never claim a recycled group+ return True+++def _shell_identity(pid: int, start_id: str) -> bool | None:+ """True while pid still names the recorded shell, False once it is provably+ gone (dead, or recycled under a new start identity), None when unprovable."""+ if not _pid_alive(pid):+ return False+ current = _process_start_id(pid)+ return None if current is None else current == start_id+++def _spawn_persistent(command: str, yield_after: float | None) -> PersistentBashHandle:+ if not _IS_POSIX:+ raise RuntimeError("bash(persistent=True) is only supported on POSIX")+ session_id = os.environ.get("RLM_SESSION_ID")+ if not session_id:+ raise RuntimeError(+ "bash(persistent=True) needs a saved session (RLM_SESSION_ID is unset): "+ "the shell is assigned to the session that started it"+ )+ home = _persistent_home()+ shell_id = secrets.token_hex(16)+ os.makedirs(home, exist_ok=True)+ shell = _shell()+ script = f'{{\n{_with_prefix(command)}\n}}\n__prime_status=$?\nwait\nexit "$__prime_status"\n'+ with open(_persistent_file(home, shell_id, "out"), "wb") as out:+ proc = subprocess.Popen(+ [shell, "-c", _PERSISTENT_WRAPPER, "prime-agent-persistent", shell, script,+ _persistent_file(home, shell_id, "rc")],+ cwd=os.getcwd(),+ env=_child_env(),+ stdin=subprocess.PIPE,+ stdout=out,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ )+ gate = cast("Any", proc.stdin)+ try:+ # The wrapper runs nothing until the shell is registered: a failure+ # (or a kernel death) before the gate byte closes the pipe instead.+ start_id = _process_start_id(proc.pid)+ if start_id is None:+ raise RuntimeError("bash(persistent=True): the shell's start identity is unreadable")+ started_at = datetime.now(timezone.utc).isoformat()+ record = {+ "id": shell_id, "pid": proc.pid, "startId": start_id, "command": command,+ "startedAt": started_at, "sessionId": session_id,+ }+ path = _persistent_file(home, shell_id, "json")+ with open(f"{path}.tmp", "w") as f:+ json.dump(record, f)+ os.replace(f"{path}.tmp", path)+ gate.write(b"\n")+ finally:+ gate.close()+ return PersistentBashHandle(+ command, shell_id, proc.pid, start_id, started_at, home, proc, yield_after=yield_after+ )+++def persistent_shells() -> list[BashHandle]:+ """This kernel's persistent bash() handles, including the ones re-attached at boot.++ After a kernel restart (or a worker/daemon restart), call this to get the+ session's persistent shells back. A shell that finished while no kernel ran+ is listed once, finished, in the first kernel after it ended.+ """+ with _live_lock:+ return [h for h in _activity_handles.values() if isinstance(h, PersistentBashHandle)]+++def _rehydrate_persistent_shells() -> None:+ """Kernel boot: re-attach this session's live shells, surface the ones that+ finished while no kernel ran, and remove its dead ones. Records with an+ unprovable identity and other sessions' records stay untouched."""+ session_id = os.environ.get("RLM_SESSION_ID")+ if not session_id or not _IS_POSIX:+ return+ home = _persistent_home()+ for record in _session_records(home, session_id):+ identity = _shell_identity(record["pid"], record["startId"])+ if identity is None:+ continue+ if identity or os.path.exists(_persistent_file(home, record["id"], "rc")):+ PersistentBashHandle(+ record["command"], record["id"], record["pid"], record["startId"], record["startedAt"],+ home, None, identity,+ )+ elif _reap_persistent_group(record["pid"], record["startId"]):+ _remove_shell_files(home, record["id"])+++def _reap_persistent_group(pid: int, start_id: str, leader_exit_witnessed: bool = False) -> bool:+ """Reap stragglers without ever signalling a live recycled or unverified pid."""+ # Existence is distinct from liveness: a recycled zombie can still own an+ # unrelated group. It must pass the same start-identity check as a live pid.+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ if leader_exit_witnessed:+ return _signal_group(pid, signal.SIGKILL)+ # A durable record can outlive its original group. An extant group+ # without the recorded leader may be a reused PGID: retain it, do not kill.+ try:+ os.killpg(pid, 0)+ except ProcessLookupError:+ return True+ except OSError:+ return False+ return False+ except PermissionError:+ pass+ current = _process_start_id(pid)+ if current == start_id:+ return _signal_group(pid, signal.SIGKILL)+ return current is not None++def _taskkill_tree(pid: int) -> bool:# Windows has no process groups to signal; taskkill /T kills the whole tree.try:@@ -1424,6 +1822,7 @@ def activity_request(action: str, activity_id: str | None = None, lines: int = 5"durationMs": int((handle._result.duration if handle._result else time.monotonic() - handle._started) * 1000),"status": "finished" if handle._reaped else "running","exitCode": handle._result.exit_code if handle._result else None,+ "persistent": isinstance(handle, PersistentBashHandle),}for key, handle in handles]diff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.pyindex fd76e26d80..eeb7d91228 100644--- a/prime-agent-runtime/src/rlm/repl.py+++ b/prime-agent-runtime/src/rlm/repl.py@@ -33,7 +33,7 @@ from collections.abc import Awaitable, Callablefrom typing import Anyfrom . import factory as factory_module-from .bash import _kill_live_handles+from .bash import _kill_live_handles, _rehydrate_persistent_shellsPROTOCOL_VERSION = 3@@ -1746,6 +1746,8 @@ def main() -> None:_send({"event": "ready", "protocol": PROTOCOL_VERSION, "python": platform.python_version()})_serve_task = _loop.create_task(_serve(queue, user_module.__dict__))+ # On the loop, so re-attached shells can deliver their completion notices.+ _loop.call_soon(_rehydrate_persistent_shells)# A KeyboardInterrupt escaping a cell or background task stops# run_until_complete; the interrupt is already recorded, so resume serving.while not _serve_task.done():diff --git a/prime-agent-runtime/test/test_bash.py b/prime-agent-runtime/test/test_bash.pyindex e6149e1aad..070d64e24f 100644--- a/prime-agent-runtime/test/test_bash.py+++ b/prime-agent-runtime/test/test_bash.py@@ -5,6 +5,7 @@ import ioimport jsonimport osimport resource+import shleximport signalimport socketimport subprocess@@ -14,6 +15,7 @@ import threadingimport timeimport unittestfrom concurrent.futures import ThreadPoolExecutor+from contextlib import nullcontextfrom types import FunctionType, SimpleNamespacefrom unittest import mock@@ -1489,5 +1491,359 @@ async def _poll_journal(path: str, count: int, timeout: float = 2.0) -> list[dicreturn records[email protected](os.name == "posix", "persistent shells are POSIX-only")+class PersistentBashTest(unittest.IsolatedAsyncioTestCase):+ def setUp(self):+ agent_dir = tempfile.mkdtemp()+ self.journal = os.path.join(agent_dir, "journal.jsonl")+ self.home = os.path.join(agent_dir, "persistent-shells")+ self.pgids: list[int] = []+ env = mock.patch.dict(+ os.environ,+ {+ "PRIME_AGENT_CODING_AGENT_DIR": agent_dir,+ "RLM_SESSION_ID": "own-session",+ },+ )+ env.start()+ self.addCleanup(env.stop)++ def tearDown(self):+ # Persistent shells survive by design: never leak one out of a test.+ for pgid in self.pgids:+ try:+ os.killpg(pgid, signal.SIGKILL)+ except ProcessLookupError:+ pass++ def records(self):+ records = []+ for name in self.files():+ if name.endswith(".json"):+ with open(os.path.join(self.home, name)) as f:+ records.append(json.load(f))+ return records++ def files(self):+ try:+ return sorted(os.listdir(self.home))+ except FileNotFoundError:+ return []++ def handle_for(self, pid):+ return next((h for h in bash_module.persistent_shells() if h.pid == pid), None)++ async def wait_for(self, predicate, timeout=10.0):+ deadline = time.monotonic() + timeout+ while not predicate():+ self.assertLess(time.monotonic(), deadline)+ await asyncio.sleep(0.05)++ async def test_persistent_shell_survives_its_kernel_and_is_reattached(self):+ journal = self.journal+ child = (+ "from rlm import bash\n"+ "import asyncio, sys\n"+ "async def main():\n"+ " await bash('true')\n"+ " done = bash('echo first; sleep 1.5; echo second; exit 3', persistent=True)\n"+ " held = bash('sleep 60', persistent=True)\n"+ " print(done.pid, held.pid)\n"+ "asyncio.run(main())\n"+ )+ out = subprocess.run(+ [sys.executable, "-c", child],+ env={+ **os.environ,+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),+ },+ capture_output=True,+ text=True,+ check=True,+ ).stdout+ done_pid, held_pid = (int(pid) for pid in out.split())+ self.pgids += [done_pid, held_pid]+ # The kernel exited (atexit ran): only the one-shot bash() was journaled.+ with open(journal) as f:+ journaled = {json.loads(line)["pid"] for line in f}+ self.assertEqual(len(journaled), 1)+ self.assertNotIn(done_pid, journaled)+ self.assertNotIn(held_pid, journaled)+ os.killpg(held_pid, 0)+ self.assertEqual({r["sessionId"] for r in self.records()}, {"own-session"})++ bash_module._rehydrate_persistent_shells()+ done, held = self.handle_for(done_pid), self.handle_for(held_pid)+ self.assertTrue(done.running and held.running)+ rows = {row["pid"]: row for row in bash_module.activity_request("list")["activities"]}+ self.assertTrue(rows[held_pid]["persistent"])+ self.assertEqual(rows[held_pid]["status"], "running")+ self.assertEqual(done.output(), "first\n")++ result = await done+ self.assertEqual(result.exit_code, 3)+ self.assertEqual(result.output, "first\nsecond\n")+ self.assertFalse(done.running)+ self.assertEqual(done.output(), "first\nsecond\n")+ self.assertEqual([r["pid"] for r in self.records()], [held_pid])+ self.assertEqual(len(self.files()), 2)++ # Re-attached before the notices were wired, its await still degrades:+ # the bound resolves at await time.+ bash_module._set_completion_notices_wired(True)+ self.addCleanup(bash_module._set_completion_notices_wired, False)+ with mock.patch.object(bash_module, "_DEFAULT_YIELD_AFTER_SECONDS", 0.2):+ self.assertIsInstance(await held, bash_module.BashSnapshot)++ held.kill()+ await held+ await _poll_group_dead(held_pid)+ self.assertEqual(self.files(), [])++ async def test_fresh_persistent_shell_reports_through_files(self):+ go = os.path.join(os.path.dirname(self.home), "go")+ handle = bash(f"while [ ! -e {shlex.quote(go)} ]; do sleep 0.01; done; echo hi; exit 4", persistent=True)+ self.pgids.append(handle.pid)+ rows = {row["pid"]: row for row in bash_module.activity_request("list")["activities"]}+ self.assertTrue(rows[handle.pid]["persistent"])+ self.assertEqual([(r["pid"], r["sessionId"]) for r in self.records()], [(handle.pid, "own-session")])+ open(go, "w").close()+ result = await handle+ self.assertEqual((result.exit_code, result.output), (4, "hi\n"))+ await self.wait_for(lambda: self.files() == [])+ self.assertEqual(handle.output(), "hi\n")+ plain = bash("true")+ rows = {row["pid"]: row for row in bash_module.activity_request("list")["activities"]}+ self.assertFalse(rows[plain.pid]["persistent"])+ await plain++ async def test_a_watched_leader_exit_kills_the_members_it_leaves_behind(self):+ handle = bash("( sleep 30 & ); exit 0", persistent=True)+ self.pgids.append(handle.pid)+ self.assertEqual((await handle).exit_code, 0)+ self.assertEqual(self.files(), [])+ await _poll_group_dead(handle.pid)++ async def test_persistent_requires_a_saved_session(self):+ with mock.patch.dict(os.environ):+ del os.environ["RLM_SESSION_ID"]+ with self.assertRaises(RuntimeError):+ bash("true", persistent=True)++ def write_record(self, record, rc=None):+ os.makedirs(self.home, exist_ok=True)+ with open(os.path.join(self.home, f"{record['id']}.out"), "w") as f:+ f.write("old output\n")+ if rc is not None:+ with open(os.path.join(self.home, f"{record['id']}.rc"), "w") as f:+ f.write(f"{rc}\n")+ with open(os.path.join(self.home, f"{record['id']}.json"), "w") as f:+ json.dump(record, f)++ def record(self, shell_id, pid, start_id, session_id="own-session"):+ return {"id": shell_id, "pid": pid, "startId": start_id, "command": "sleep 60",+ "startedAt": "2026-01-01T00:00:00+00:00", "sessionId": session_id}++ def sleeper(self):+ proc = subprocess.Popen(["sleep", "60"], start_new_session=True)+ self.addCleanup(proc.wait)+ self.pgids.append(proc.pid)+ return proc++ async def test_another_sessions_shells_are_left_alone(self):+ live = self.sleeper()+ gone = subprocess.Popen(["true"])+ gone.wait()+ self.write_record(self.record("1" * 32, live.pid, bash_module._process_start_id(live.pid), "other"))+ self.write_record(self.record("2" * 32, gone.pid, "proc:1", "other"), rc=0)+ self.write_record(self.record("3" * 32, gone.pid, "proc:1", "other"))+ before = self.files()++ bash_module._rehydrate_persistent_shells()++ claimed = {h._activity_id for h in bash_module.persistent_shells()}+ self.assertFalse(claimed & {"1" * 32, "2" * 32, "3" * 32})+ self.assertEqual(self.files(), before)+ self.assertIsNone(live.poll())++ async def test_recycled_pid_is_never_claimed_or_signalled(self):+ stranger = self.sleeper()+ self.write_record(self.record("a" * 32, stranger.pid, "proc:not-this-process"))+ self.write_record(self.record("b" * 32, stranger.pid, "proc:not-this-process"), rc=7)++ bash_module._rehydrate_persistent_shells()+ # The shell that finished while no kernel ran surfaces once, finished.+ surfaced = [h for h in bash_module.persistent_shells() if h._activity_id == "b" * 32]+ self.assertEqual(len(surfaced), 1)+ result = await surfaced[0]+ self.assertEqual((result.exit_code, result.output), (7, "old output\n"))+ self.assertNotIn("a" * 32, [h._activity_id for h in bash_module.persistent_shells()])+ self.assertIsNone(stranger.poll())+ await self.wait_for(lambda: self.files() == [])++ async def test_reattached_shell_whose_pid_is_recycled_finishes_without_a_signal(self):+ stranger = self.sleeper()+ self.write_record(self.record("d" * 32, stranger.pid, bash_module._process_start_id(stranger.pid)))+ bash_module._rehydrate_persistent_shells()+ handle = self.handle_for(stranger.pid)+ self.assertTrue(handle.running)+ # The shell died without a status and its pid now names another process.+ handle._start_id = "proc:not-this-process"+ self.assertEqual((await asyncio.wait_for(handle, 10)).exit_code, -1)+ self.assertIsNone(stranger.poll())+ await self.wait_for(lambda: self.files() == [])++ async def test_completed_file_errors_settle_waiters_and_leave_records_recoverable(self):+ for kind in ("output", "status"):+ with self.subTest(kind=kind):+ shell_id = ("e" if kind == "output" else "f") * 32+ gone = subprocess.Popen(["true"])+ gone.wait()+ self.write_record(self.record(shell_id, gone.pid, "proc:gone"), rc=7)+ rc_path = os.path.join(self.home, f"{shell_id}.rc")+ if kind == "status":+ with open(rc_path, "w") as status:+ status.write("invalid status")+ fault = (+ mock.patch.object(bash_module._OutputFile, "keep", side_effect=PermissionError("output denied"))+ if kind == "output" else nullcontext()+ )+ with fault, mock.patch("threading.excepthook") as thread_error:+ bash_module._rehydrate_persistent_shells()+ handle = self.handle_for(gone.pid)+ with self.assertRaises((PermissionError, ValueError)):+ await asyncio.wait_for(handle, 5)+ with self.assertRaises((PermissionError, ValueError)):+ handle.poll()+ self.assertFalse(handle.running)+ thread_error.assert_not_called()+ self.assertTrue(os.path.exists(os.path.join(self.home, f"{shell_id}.json")))+ with open(rc_path, "w") as status:+ status.write("7\n")+ bash_module._rehydrate_persistent_shells()+ recovered = self.handle_for(gone.pid)+ result = await asyncio.wait_for(recovered, 5)+ self.assertEqual((result.exit_code, result.output), (7, "old output\n"))+ await self.wait_for(lambda: self.files() == [])++ async def test_restart_retains_unverified_leaderless_groups_without_signalling(self):+ for recorded_status in (None, 7):+ with self.subTest(recorded_status=recorded_status):+ leader = subprocess.Popen(["sleep", "60"], process_group=0)+ self.pgids.append(leader.pid)+ member = subprocess.Popen(["sleep", "60"], process_group=leader.pid)+ self.addCleanup(member.wait)+ self.addCleanup(leader.wait)+ shell_id = ("8" if recorded_status is None else "9") * 32+ self.write_record(+ self.record(shell_id, leader.pid, bash_module._process_start_id(leader.pid)),+ rc=recorded_status,+ )+ leader.kill()+ leader.wait()+ with mock.patch.object(bash_module, "_signal_group", wraps=bash_module._signal_group) as signal_group:+ bash_module._rehydrate_persistent_shells()+ if recorded_status is not None:+ handle = self.handle_for(leader.pid)+ self.assertEqual((await asyncio.wait_for(handle, 5)).exit_code, recorded_status)+ signal_group.assert_not_called()+ self.assertIsNone(member.poll())+ self.assertTrue(os.path.exists(os.path.join(self.home, f"{shell_id}.json")))+ member.kill()+ member.wait()+ bash_module._remove_shell_files(self.home, shell_id)++ def test_restart_keeps_dead_group_record_if_cleanup_cannot_deliver(self):+ shell_id = "7" * 32+ self.write_record(self.record(shell_id, 424242, "proc:gone"))+ before = self.files()+ with mock.patch.object(bash_module, "_shell_identity", return_value=False):+ with mock.patch.object(bash_module.os, "kill", side_effect=ProcessLookupError):+ with mock.patch.object(bash_module.os, "killpg", side_effect=PermissionError):+ bash_module._rehydrate_persistent_shells()+ self.assertEqual(self.files(), before)++ async def test_unreaped_dead_leader_does_not_leave_a_running_handle(self):+ if not (sys.platform.startswith("linux") or sys.platform == "darwin"):+ self.skipTest("native zombie checks cover Linux and macOS")+ leader = subprocess.Popen(+ ["/bin/sh", "-c", "read gate; exit 0"],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, start_new_session=True,+ )+ self.addCleanup(leader.wait)+ self.addCleanup(leader.kill)+ self.write_record(self.record("6" * 32, leader.pid, bash_module._process_start_id(leader.pid)))+ bash_module._rehydrate_persistent_shells()+ handle = self.handle_for(leader.pid)+ self.assertTrue(handle.running)+ leader.stdin.close()+ self.assertEqual(leader.stdout.read(), b"") # observable exit, no waitpid+ leader.stdout.close()+ self.assertEqual((await asyncio.wait_for(handle, 5)).exit_code, -1)+ self.assertFalse(handle.running)+ leader.wait()++ def test_persistent_escalation_rechecks_the_identity(self):+ # A real registered process stands in for the reused PID: no signal may+ # reach it once its recorded identity changed or became unreadable.+ stranger = self.sleeper()+ handle = object.__new__(bash_module.PersistentBashHandle)+ handle._pid = stranger.pid+ handle._start_id = "proc:recycled"+ handle._reaped = False+ handle._kill_lock = threading.Lock()+ for identity in (False, None):+ with self.subTest(identity=identity):+ current = None if identity is None else "proc:stranger"+ with mock.patch.object(bash_module, "_process_start_id", return_value=current):+ with mock.patch.object(bash_module, "_signal_group") as signal_group:+ handle._force_kill()+ signal_group.assert_not_called()+ self.assertIsNone(stranger.poll())++ async def test_cancelled_persistent_await_leaves_the_shell_running(self):+ handle = bash("sleep 60", persistent=True)+ self.pgids.append(handle.pid)+ waiter = asyncio.ensure_future(handle)+ started = asyncio.Event()++ async def observe_wait():+ started.set()+ return await waiter++ observed = asyncio.create_task(observe_wait())+ await started.wait()+ observed.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await observed+ self.assertTrue(handle.running)+ os.kill(handle.pid, 0)+ self.assertEqual([record["pid"] for record in self.records()], [handle.pid])+ handle.kill()+ await asyncio.wait_for(handle, 5)++ def test_fresh_persistent_kill_refuses_a_recycled_pid(self):+ stranger = self.sleeper()+ handle = object.__new__(bash_module.PersistentBashHandle)+ handle._pid = stranger.pid+ handle._start_id = "proc:recycled"+ handle._proc = stranger # fresh-handle path, but ownership has expired+ handle._reaped = False+ handle._kill_lock = threading.Lock()+ with mock.patch.object(bash_module, "_signal_group") as signal_group:+ handle.kill(signal.SIGKILL)+ signal_group.assert_not_called()+ self.assertIsNone(stranger.poll())++ async def test_dead_entry_is_swept(self):+ gone = subprocess.Popen(["true"])+ gone.wait()+ self.write_record(self.record("c" * 32, gone.pid, "proc:1"))+ bash_module._rehydrate_persistent_shells()+ self.assertIsNone(self.handle_for(gone.pid))+ self.assertEqual(self.files(), [])++if __name__ == "__main__":unittest.main()diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.pyindex a1bbe8e5a6..81d6bd0288 100644--- a/prime-agent-runtime/test/test_repl.py+++ b/prime-agent-runtime/test/test_repl.py@@ -1204,6 +1204,42 @@ class ReplTest(unittest.TestCase):)reply_ok(self.repl, request)+ def test_degraded_await_of_a_persistent_shell_keeps_it_running_to_its_notice(self):+ # yield_after and persistent= compose: the persistent handle's await+ # degrades like any handle's, and the shell (never owned by an await)+ # runs on to its [bash-done] notice.+ temp = tempfile.TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ repl = ReplProcess(+ env={"PRIME_AGENT_CODING_AGENT_DIR": temp.name, "RLM_SESSION_ID": "own-session"}+ )+ self.addCleanup(repl.close)+ repl.ready()+ code = "\n".join(+ [+ "import rlm",+ "rlm._set_completion_notices_wired(True)",+ "from rlm import bash",+ "handle = bash('sleep 0.6; printf persisted', persistent=True, yield_after=0.3)",+ "snapshot = await handle",+ "(snapshot.running, snapshot.handle is handle, handle.pid)",+ ]+ )+ events = repl.execute("persistent-degrade", code)+ running, same, pid = one(events, "result")["text"].strip("()").split(", ")+ self.assertEqual((running, same), ("True", "True"))+ request = wait_for_host_request(repl, events)+ self.assertEqual(+ request["data"],+ {+ "type": "bash.completed",+ "pid": int(pid),+ "command": "sleep 0.6; printf persisted",+ "exitCode": 0,+ },+ )+ reply_ok(repl, request)+def test_result_read_after_notice_requests_one_withdrawal(self):reads = (("poll", "handle.poll().output"),diff --git a/scripts/review_dock_events_parity.py b/scripts/review_dock_events_parity.pyindex 3e18dd9ad4..8a90e22ab8 100644--- a/scripts/review_dock_events_parity.py+++ b/scripts/review_dock_events_parity.py@@ -108,9 +108,9 @@ class DockSupervisor(Supervisor):def running_visible(text, kind, count, expanded=False):- # Rust's collapsed dock reads "N subagents"; its focused (expanded) dock's+ # Rust's collapsed dock reads "N subagent(s)"; its focused (expanded) dock's# subagents row reads the "N running · …" breakdown, like TS's box.- label = 'running' if kind == 'ts' or expanded else 'subagents'+ label = 'running' if kind == 'ts' or expanded else 'subagents?'return re.search(r'(?<!\d)' + str(count) + r'\s+' + label + r'\b', text) is not Nonediff --git a/scripts/test_review_dock_events_parity.py b/scripts/test_review_dock_events_parity.pyindex 1ba89ac300..af6dd2935f 100644--- a/scripts/test_review_dock_events_parity.py+++ b/scripts/test_review_dock_events_parity.py@@ -37,6 +37,7 @@ class CaptureTests(unittest.TestCase):self.assertTrue(running_visible('1 running', 'ts', 1))self.assertFalse(running_visible('1 running', 'ts', 2))self.assertTrue(running_visible('2 subagents', 'rust', 2))+ self.assertTrue(running_visible('◆ 1 subagent ·', 'rust', 1))expanded = '◆ subagents 2 running · 0 idle · 0 inactive'self.assertTrue(running_visible(expanded, 'rust', 2, expanded=True))self.assertFalse(running_visible(expanded, 'rust', 2))