Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

pa-tui: count persistent shells in the agents view and the activity dock (#3641)

Sebastian Müller69a826f982f9
diff --git a/crates/pa-cli/tests/agents_view_inactive_shells_e2e.rs b/crates/pa-cli/tests/agents_view_inactive_shells_e2e.rs
new file mode 100644
index 0000000000..0a4402934d
--- /dev/null
+++ b/crates/pa-cli/tests/agents_view_inactive_shells_e2e.rs
@@ -0,0 +1,224 @@
+// Casts: narrowing sits at the pid boundary, where the kernel bounds the values.
+#![allow(clippy::large_futures, clippy::cast_possible_wrap)]
+#![cfg(target_os = "linux")]
+
+//! E2E verifier for an inactive session's shells line: the open agents view follows the
+//! daemon's live persistent shells, so a shell that ends (or starts) while the view stays open
+//! moves its session's `$` line within a poll cycle instead of keeping the catalog's open-time
+//! snapshot until a reopen.
+
+use std::fmt::Write as _;
+use std::os::unix::net::UnixStream;
+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 pa_tui::agents_view::{AgentsHeadlessPlan, AgentsStep, AgentsViewOptions, AgentsViewUiMode};
+use serde_json::json;
+
+struct Supervisor {
+ child: Child,
+ socket: PathBuf,
+}
+
+impl Drop for Supervisor {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+#[allow(clippy::zombie_processes)]
+fn spawn_supervisor(dir: &Path) -> Supervisor {
+ let socket = dir.join("daemon.sock");
+ 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", dir.join("agent"))
+ .env_remove("PRIME_AGENT_SESSION_DIR")
+ .env_remove("PRIME_AGENT_CODING_AGENT_SESSION_DIR")
+ .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 saved session: a header plus a named user/assistant exchange.
+fn write_session(sessions_dir: &Path, id: &str, name: &str) {
+ let mut content = String::new();
+ let _ = writeln!(
+ content,
+ r#"{{"type":"session","version":3,"id":"{id}","timestamp":"2024-01-01T00:00:00.000Z","cwd":"/tmp"}}"#
+ );
+ let _ = writeln!(
+ content,
+ r#"{{"type":"session_info","id":"{id}-info","timestamp":"2024-01-01T00:00:00.000Z","name":"{name}"}}"#
+ );
+ let _ = writeln!(
+ content,
+ r#"{{"type":"message","id":"{id}-u","timestamp":"2024-01-01T00:00:00.000Z","message":{{"role":"user","content":"start a server","timestamp":0}}}}"#
+ );
+ let _ = writeln!(
+ content,
+ r#"{{"type":"message","id":"{id}-a","timestamp":"2024-01-01T00:00:01.000Z","message":{{"role":"assistant","content":[{{"type":"text","text":"started"}}],"timestamp":1}}}}"#
+ );
+ std::fs::write(sessions_dir.join(format!("{id}.jsonl")), content).expect("write session");
+}
+
+/// A persistent shell: a `sleep` leading its own process group, registered in the agent dir's
+/// persistent-shell home under its real start identity and assigned to `session_id`.
+struct Shell(Child);
+
+impl Shell {
+ fn start(agent_dir: &Path, session_id: &str) -> Shell {
+ let mut command = Command::new("sleep");
+ command.arg("300");
+ pa_core::platform::process::set_new_session(&mut command);
+ let child = command.spawn().expect("spawn shell");
+ let pid = child.id();
+ let home = agent_dir.join("persistent-shells");
+ std::fs::create_dir_all(&home).expect("persistent-shell home");
+ let id = format!("{pid:032}");
+ let record = json!({
+ "id": id,
+ "pid": pid,
+ "startId": pa_daemon::lease::get_process_start_id(pid).expect("start id"),
+ "command": "sleep 300",
+ "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");
+ Shell(child)
+ }
+
+ /// End the shell's process group (what a user's kill does) and reap it.
+ fn stop(mut self) {
+ killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGTERM).expect("signal the group");
+ self.0.wait().expect("reap the shell");
+ }
+}
+
+impl Drop for Shell {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+}
+
+fn view_options(socket: &Path, session_dir: &Path) -> AgentsViewOptions {
+ AgentsViewOptions {
+ socket_path: socket.to_path_buf(),
+ cwd: PathBuf::from("/tmp"),
+ session_dir: Some(session_dir.to_path_buf()),
+ 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: json!({}),
+ }
+}
+
+/// The sessions' indented `$` lines: the unindented `Persistent shells` rows also start with `$`.
+fn shell_lines(frame: &str) -> Vec<&str> {
+ frame
+ .lines()
+ .filter(|line| line.starts_with(' '))
+ .map(str::trim)
+ .filter(|line| line.starts_with("$ "))
+ .collect()
+}
+
+/// Session A's shell ends while the view is open, then session B (already listed, no shells at
+/// the catalog load) starts two: B's line can only land from a registry read made after A's
+/// shell was reaped, so the frame that shows it must also show A without a line.
+#[tokio::test]
+async fn an_inactive_sessions_shells_line_follows_its_live_persistent_shells() {
+ 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("session dir");
+ write_session(&sessions_dir, "session-a", "server session a");
+ write_session(&sessions_dir, "session-b", "server session b");
+ let shell_a = Shell::start(&agent_dir, "session-a");
+ let supervisor = spawn_supervisor(dir.path());
+
+ let line_rendered = std::sync::Arc::new(tokio::sync::Notify::new());
+ let view = pa_tui::agents_view::run_agents_view(
+ view_options(&supervisor.socket, &sessions_dir),
+ AgentsViewUiMode::Headless(AgentsHeadlessPlan {
+ steps: vec![
+ AgentsStep::WaitRender {
+ needle: "$ 1 shell \u{b7} 1 persistent".to_string(),
+ timeout_ms: 20_000,
+ },
+ AgentsStep::Notify(line_rendered.clone()),
+ // Two poll cycles: the change lands with the first cycle after it.
+ AgentsStep::WaitRender {
+ needle: "$ 2 shells \u{b7} 2 persistent".to_string(),
+ timeout_ms: 2 * 2_000 + 500,
+ },
+ ],
+ width: 120,
+ height: 36,
+ }),
+ None,
+ );
+ let shells_b = async {
+ line_rendered.notified().await;
+ shell_a.stop();
+ [
+ Shell::start(&agent_dir, "session-b"),
+ Shell::start(&agent_dir, "session-b"),
+ ]
+ };
+ let (view, _shells_b) = tokio::join!(view, shells_b);
+ let frames = view.expect("agents view run").outcome.frames;
+
+ let before = frames
+ .iter()
+ .position(|frame| shell_lines(frame) == ["$ 1 shell \u{b7} 1 persistent"])
+ .unwrap_or_else(|| panic!("A's line rendered:\n{}", frames.join("\n---\n")));
+ let after = frames[before..]
+ .iter()
+ .find(|frame| frame.contains("$ 2 shells"))
+ .unwrap_or_else(|| {
+ panic!(
+ "B's shells never reached the open view; last frame:\n{}",
+ frames.last().map_or("", String::as_str)
+ )
+ });
+ assert_eq!(
+ shell_lines(after),
+ ["$ 2 shells \u{b7} 2 persistent"],
+ "A's ended shell left its line:\n{after}"
+ );
+}
diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rs
index 6fa106c291..dcf8998d2b 100644
--- a/crates/pa-tui/src/agents_view.rs
+++ b/crates/pa-tui/src/agents_view.rs
@@ -14,8 +14,8 @@ 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, subtree_contains, AgentsViewRow, RowKind,
- ScopeRoot, SelectionKey, SessionActivity,
+ scope_ancestors, scope_root, scope_to_subtree, subtree_contains, ActivityCounts, AgentsViewRow,
+ RowKind, ScopeRoot, SelectionKey, SessionActivity,
};
use crate::agents_view_state::truncate_text;
use crate::agents_view_state::{
@@ -313,7 +313,7 @@ pub struct AgentsViewLink {
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>,
+ session_activity: ActivityCounts,
/// The persistent shells list the previous run held, for the same first-frame restore of a
/// shell row.
persistent_shells: Value,
@@ -329,7 +329,7 @@ impl AgentsViewLink {
client,
events,
saved: SavedCatalog::default(),
- session_activity: std::collections::HashMap::new(),
+ session_activity: ActivityCounts::default(),
persistent_shells: Value::Null,
activity_fetch: None,
})
@@ -481,8 +481,8 @@ struct AgentsViewMode {
/// 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 activity polls' counts behind the shells and factory-run lines.
+ session_activity: ActivityCounts,
}
/// The press state of one left click, row-scoped: the release must land on the same row.
@@ -584,7 +584,7 @@ impl AgentsViewMode {
shell_view: None,
pending_shell_action: None,
pending_shell_open: None,
- session_activity: std::collections::HashMap::new(),
+ session_activity: ActivityCounts::default(),
}
}
}
diff --git a/crates/pa-tui/src/agents_view/persistent_shells.rs b/crates/pa-tui/src/agents_view/persistent_shells.rs
index c96939f443..9b16b61a18 100644
--- a/crates/pa-tui/src/agents_view/persistent_shells.rs
+++ b/crates/pa-tui/src/agents_view/persistent_shells.rs
@@ -9,7 +9,7 @@ use super::{
};
use crate::agents_view_state::{summary_for_record, UnifiedRecord};
use crate::bash_view::{
- format_duration, parse_bash_activities, BashActivity, BashView, BashViewAction,
+ format_duration, parse_bash_activities, BashActivity, BashView, BashViewAction, ShellCounts,
};
/// The daemon capability that serves the machine-wide shell list, output, and kill.
@@ -257,11 +257,37 @@ impl AgentsViewMode {
view.clear_error();
}
}
+ self.session_activity.persistent_shells = shell_counts_by_session(&data);
self.persistent_shells = data;
self.rebuild_rows();
}
}
+/// The list's shell counts by assigned `sessionId`: every session's persistent shells.
+fn shell_counts_by_session(data: &Value) -> HashMap<String, ShellCounts> {
+ let mut rows: HashMap<String, Vec<Value>> = HashMap::new();
+ for row in data
+ .get("activities")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ if let Some(session_id) = row.get("sessionId").and_then(Value::as_str) {
+ rows.entry(session_id.to_string())
+ .or_default()
+ .push(row.clone());
+ }
+ }
+ rows.into_iter()
+ .map(|(session_id, rows)| {
+ (
+ session_id,
+ crate::bash_view::running_shell_counts(&Value::Array(rows)),
+ )
+ })
+ .collect()
+}
+
/// 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)
diff --git a/crates/pa-tui/src/agents_view/session_activity.rs b/crates/pa-tui/src/agents_view/session_activity.rs
index 38cab4ca67..b07f7edf92 100644
--- a/crates/pa-tui/src/agents_view/session_activity.rs
+++ b/crates/pa-tui/src/agents_view/session_activity.rs
@@ -1,5 +1,6 @@
//! The per-session shells and factory-run counts behind the agents-view activity lines.
use super::{AgentsViewMode, DaemonClient, DaemonCommand, SessionActivity};
+use crate::bash_view::ShellCounts;
use anyhow::Result;
use serde_json::{Map, Value};
use tokio::sync::oneshot;
@@ -8,7 +9,7 @@ use tokio::sync::oneshot;
/// count.
pub(super) struct ActivityRead {
pub(super) active_session_id: String,
- pub(super) shells: Option<usize>,
+ pub(super) shells: Option<ShellCounts>,
pub(super) factory_runs: Option<crate::factory_view::FactoryRunCounts>,
}
@@ -29,7 +30,7 @@ pub(super) fn spawn_session_activity_fetch(
reads.spawn(async move {
let shells = async {
if !shells_supported {
- return Some(0);
+ return Some(ShellCounts::default());
}
let reply = client
.request_ok(DaemonCommand::ListKernelBash {
@@ -39,7 +40,7 @@ pub(super) fn spawn_session_activity_fetch(
})
.await;
count(reply, |data| {
- Some(crate::bash_view::running_shell_count(data))
+ Some(crate::bash_view::running_shell_counts(data))
})
};
let factory_runs = async {
@@ -79,7 +80,7 @@ pub(super) fn spawn_session_activity_fetch(
rx
}
-/// A session without a running kernel hosts nothing: zero, not a failed read.
+/// The daemon's no-kernel refusal reads as zero, not a failed read.
fn count<T: Default>(reply: Result<Value>, count: impl Fn(&Value) -> Option<T>) -> Option<T> {
match reply {
Ok(data) => count(&data),
@@ -89,7 +90,7 @@ fn count<T: Default>(reply: Result<Value>, count: impl Fn(&Value) -> Option<T>)
}
impl AgentsViewMode {
- /// The roster's live sessions a fetch cycle asks: saved rows have no kernel and render no lines.
+ /// The roster's live sessions a fetch cycle asks: saved rows have no kernel.
pub(super) fn live_session_ids(&self) -> Vec<String> {
self.roster
.iter()
@@ -102,11 +103,12 @@ impl AgentsViewMode {
/// 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
+ let live = reads
.into_iter()
.map(|read| {
let last = self
.session_activity
+ .live
.get(&read.active_session_id)
.copied()
.unwrap_or_default();
@@ -117,8 +119,8 @@ impl AgentsViewMode {
(read.active_session_id, counts)
})
.collect();
- if activity != self.session_activity {
- self.session_activity = activity;
+ if live != self.session_activity.live {
+ self.session_activity.live = live;
self.rebuild_rows();
}
}
diff --git a/crates/pa-tui/src/agents_view/tests/activity_lines.rs b/crates/pa-tui/src/agents_view/tests/activity_lines.rs
index d8015c8fcf..fd4325e86f 100644
--- a/crates/pa-tui/src/agents_view/tests/activity_lines.rs
+++ b/crates/pa-tui/src/agents_view/tests/activity_lines.rs
@@ -3,13 +3,17 @@
use super::*;
use crate::agents_view_forest::SessionActivity;
+use crate::bash_view::ShellCounts;
use crate::interactive::SessionPanel;
fn with_activity(mode: &mut AgentsViewMode, active: &str, shells: usize, factory_runs: usize) {
- mode.session_activity.insert(
+ mode.session_activity.live.insert(
active.to_string(),
SessionActivity {
- shells,
+ shells: ShellCounts {
+ running: shells,
+ persistent: 0,
+ },
factory_runs: crate::factory_view::FactoryRunCounts {
running: factory_runs,
paused: 0,
diff --git a/crates/pa-tui/src/agents_view_forest.rs b/crates/pa-tui/src/agents_view_forest.rs
index ebdf9d4ce7..2624f67f78 100644
--- a/crates/pa-tui/src/agents_view_forest.rs
+++ b/crates/pa-tui/src/agents_view_forest.rs
@@ -65,7 +65,8 @@ pub enum RowKind {
Subagent,
/// A read-only spawn-program line.
Code,
- /// The node's own running kernel shells line.
+ /// The node's own shells line: its kernel's running shells, or without a live kernel its live
+ /// persistent shells from the daemon's list.
Shells,
/// The node's own live factory runs line.
FactoryRuns,
@@ -121,14 +122,22 @@ pub struct SelectionKey {
pub active_session_id: Option<String>,
}
-/// One live session's own activity counts, keyed by its `activeSessionId`: the shells and
+/// One session's own activity counts (a live one's 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 shells: crate::bash_view::ShellCounts,
pub factory_runs: crate::factory_view::FactoryRunCounts,
}
+/// The activity poll's counts: each live session's by its `activeSessionId`, and the live
+/// persistent shells by their assigned `sessionId` (every session's persistent count).
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ActivityCounts {
+ pub live: std::collections::HashMap<String, SessionActivity>,
+ pub persistent_shells: std::collections::HashMap<String, crate::bash_view::ShellCounts>,
+}
+
/// 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.rs
index 78afd25938..83b5afd874 100644
--- a/crates/pa-tui/src/agents_view_forest/rows.rs
+++ b/crates/pa-tui/src/agents_view_forest/rows.rs
@@ -4,13 +4,14 @@ use serde_json::Value;
use super::lineage::{depth_consistent_parent, is_subagent_descendant};
use super::{
- session_model, session_title, AgentsViewRow, AgentsViewScope, Rollup, RowKind, SessionActivity,
- SUMMARY_ROW_PREFIX,
+ session_model, session_title, ActivityCounts, AgentsViewRow, AgentsViewScope, Rollup, RowKind,
+ SessionActivity, SUMMARY_ROW_PREFIX,
};
use crate::agents_view_state::{
is_unnamed_empty, now_ms, relative_age, section_rank, summary_for_record, Section,
UnifiedRecord,
};
+use crate::bash_view::ShellCounts;
use crate::factory_view::FactoryRunCounts;
use crate::subagents::{is_subagent_summary, summary_identity_keys, summary_parent_keys};
@@ -43,7 +44,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>,
+ activity: &ActivityCounts,
anchor: Option<&str>,
) -> Vec<AgentsViewRow> {
let now = now_ms();
@@ -100,12 +101,25 @@ 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
+ let live = summary
.get("activeSessionId")
.and_then(Value::as_str)
- .and_then(|active| activity.get(active))
+ .and_then(|active| activity.live.get(active))
.copied()
.unwrap_or_default();
+ // Persistent shells count from the daemon list only; the kernel adds its other shells.
+ let persistent = summary
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .and_then(|session_id| activity.persistent_shells.get(session_id))
+ .map_or(0, |shells| shells.persistent);
+ let activity = SessionActivity {
+ shells: ShellCounts {
+ running: live.shells.running - live.shells.persistent + persistent,
+ persistent,
+ },
+ factory_runs: live.factory_runs,
+ };
base.push(BaseRow {
kind,
section: record.section,
@@ -380,8 +394,8 @@ 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;
-/// paused runs read apart from the running ones (`⚙ 0 factory runs · 1 paused`).
+/// The node's own `$ N shells[ · M persistent]` and `⚙ N factory runs` lines, each only when its
+/// count is nonzero; paused runs read apart from the running ones (`⚙ 0 factory runs · 1 paused`).
/// 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 {
@@ -405,11 +419,20 @@ fn activity_rows(parent: &BaseRow, depth: usize) -> Vec<AgentsViewRow> {
factory_runs,
} = parent.activity;
let mut rows = Vec::new();
- if shells > 0 {
+ if shells.running > 0 {
+ let persistent = if shells.persistent > 0 {
+ format!(" · {} persistent", shells.persistent)
+ } else {
+ String::new()
+ };
rows.push(line(
RowKind::Shells,
super::SHELLS_ROW_PREFIX,
- format!("$ {shells} shell{}", if shells == 1 { "" } else { "s" }),
+ format!(
+ "$ {} shell{}{persistent}",
+ shells.running,
+ if shells.running == 1 { "" } else { "s" }
+ ),
));
}
let FactoryRunCounts { running, paused } = factory_runs;
diff --git a/crates/pa-tui/src/agents_view_forest/tests.rs b/crates/pa-tui/src/agents_view_forest/tests.rs
index b74a99097e..d45d20fab8 100644
--- a/crates/pa-tui/src/agents_view_forest/tests.rs
+++ b/crates/pa-tui/src/agents_view_forest/tests.rs
@@ -1,5 +1,6 @@
use super::*;
use crate::agents_view_state::reconcile_unified_sessions;
+use crate::bash_view::ShellCounts;
use serde_json::json;
use std::collections::{HashMap, HashSet};
@@ -59,7 +60,10 @@ fn rows_with_activity(
&expanded,
&HashSet::default(),
&rollups,
- activity,
+ &ActivityCounts {
+ live: activity.clone(),
+ ..ActivityCounts::default()
+ },
None,
)
}
@@ -613,7 +617,7 @@ fn saved_child_nests_under_its_saved_parent() {
&std::collections::HashSet::default(),
&HashSet::default(),
&rollups,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
assert_eq!(rows.len(), 2);
@@ -627,7 +631,7 @@ fn saved_child_nests_under_its_saved_parent() {
&expanded,
&HashSet::default(),
&rollups,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
assert_eq!(rows[2].title, "saved child");
@@ -810,7 +814,7 @@ fn rollups_sum_costs_over_descendants_only() {
&std::collections::HashSet::default(),
&HashSet::default(),
&empty,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
// Without rollups the per-pass walk fills the same totals.
@@ -877,7 +881,7 @@ fn an_active_query_ranks_hits_globally_ancestors_sink_last() {
&expanded,
&HashSet::default(),
&rollups,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
let titles: Vec<&str> = rows.iter().map(|row| row.title.as_str()).collect();
@@ -954,7 +958,7 @@ fn equal_scores_break_ties_by_recency_not_section() {
&std::collections::HashSet::default(),
&HashSet::default(),
&rollups,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
assert_eq!(
@@ -1038,7 +1042,7 @@ fn the_summary_line_bills_the_deleted_descendant_bucket() {
&HashSet::new(),
&HashSet::new(),
&rollups,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
let summary = rows
@@ -1233,7 +1237,7 @@ fn a_ledger_child_nests_across_the_windows_path_forms() {
&HashSet::default(),
&HashSet::default(),
&rollups,
- &HashMap::new(),
+ &ActivityCounts::default(),
None,
);
// RED on main: the child's `file:\\?\...` parent key never matches the
@@ -1260,7 +1264,10 @@ fn activity(entries: &[(&str, usize, usize, usize)]) -> HashMap<String, SessionA
(
active.to_string(),
SessionActivity {
- shells,
+ shells: ShellCounts {
+ running: shells,
+ persistent: 0,
+ },
factory_runs: crate::factory_view::FactoryRunCounts { running, paused },
},
)
@@ -1344,6 +1351,101 @@ fn activity_lines_without_subagents_and_without_counts() {
);
}
+fn shells_lines(rows: &[AgentsViewRow]) -> Vec<(&str, &str)> {
+ rows.iter()
+ .filter(|row| row.kind == RowKind::Shells)
+ .map(|row| (row.identity.as_str(), row.title.as_str()))
+ .collect()
+}
+
+/// A live node's shells line breaks out its persistent shells; without any it keeps the plain
+/// count. The kernel lists its persistent shells too, so they count once.
+#[test]
+fn a_live_shells_line_counts_its_persistent_shells() {
+ let roster = vec![
+ roster_entry("a", "idle", &parent_summary("a")),
+ roster_entry("b", "idle", &parent_summary("b")),
+ ];
+ let shells = |running, persistent| SessionActivity {
+ shells: ShellCounts {
+ running,
+ persistent,
+ },
+ factory_runs: crate::factory_view::FactoryRunCounts::default(),
+ };
+ let records = reconcile_unified_sessions(&roster, &[], None);
+ let rows = build_rows(
+ &records,
+ None,
+ &HashSet::default(),
+ &HashSet::default(),
+ &compute_rollups(&records),
+ &ActivityCounts {
+ live: HashMap::from([
+ ("a-live".to_string(), shells(2, 1)),
+ ("b-live".to_string(), shells(2, 0)),
+ ]),
+ persistent_shells: HashMap::from([(
+ "a".to_string(),
+ ShellCounts {
+ running: 1,
+ persistent: 1,
+ },
+ )]),
+ },
+ None,
+ );
+ let mut lines = shells_lines(&rows);
+ lines.sort_unstable();
+ assert_eq!(
+ lines,
+ vec![
+ ("shells:file:/x/a.jsonl", "$ 2 shells · 1 persistent"),
+ ("shells:file:/x/b.jsonl", "$ 2 shells"),
+ ]
+ );
+}
+
+/// A node's persistent shells come from the poll's daemon list (by `sessionId`), with or without
+/// a live kernel: an idle live session still shows them.
+#[test]
+fn a_node_without_kernel_shells_shows_its_live_persistent_shells() {
+ let roster = vec![roster_entry("live", "idle", &parent_summary("live"))];
+ let saved = vec![
+ json!({ "id": "gone", "path": "/x/gone.jsonl", "messageCount": 2 }),
+ json!({ "id": "live", "path": "/x/live.jsonl", "messageCount": 2 }),
+ ];
+ let records = reconcile_unified_sessions(&roster, &saved, None);
+ let persistent = |shells| ShellCounts {
+ running: shells,
+ persistent: shells,
+ };
+ let rows = build_rows(
+ &records,
+ None,
+ &HashSet::default(),
+ &HashSet::default(),
+ &compute_rollups(&records),
+ &ActivityCounts {
+ live: HashMap::new(),
+ persistent_shells: HashMap::from([
+ ("gone".to_string(), persistent(2)),
+ ("live".to_string(), persistent(1)),
+ ]),
+ },
+ None,
+ );
+ let mut lines = shells_lines(&rows);
+ lines.sort_unstable();
+ assert_eq!(
+ lines,
+ vec![
+ ("shells:file:/x/gone.jsonl", "$ 2 shells · 2 persistent"),
+ ("shells:file:/x/live.jsonl", "$ 1 shell · 1 persistent"),
+ ]
+ );
+}
+
/// Paused factory runs never read as running: the line counts the running runs and names the
/// paused ones apart, like the dock's paused cluster.
#[test]
diff --git a/crates/pa-tui/src/agents_view_state.rs b/crates/pa-tui/src/agents_view_state.rs
index ff18362e3d..260b1e2dee 100644
--- a/crates/pa-tui/src/agents_view_state.rs
+++ b/crates/pa-tui/src/agents_view_state.rs
@@ -858,7 +858,7 @@ mod tests {
&std::collections::HashSet::default(),
&std::collections::HashSet::default(),
&std::collections::HashMap::default(),
- &std::collections::HashMap::default(),
+ &crate::agents_view_forest::ActivityCounts::default(),
None,
);
assert_eq!(rows[0].section, Section::Running);
@@ -1049,7 +1049,7 @@ mod tests {
&std::collections::HashSet::default(),
&std::collections::HashSet::default(),
&std::collections::HashMap::default(),
- &std::collections::HashMap::default(),
+ &crate::agents_view_forest::ActivityCounts::default(),
None,
);
let layout = build_layout(&rows, 120);
@@ -1096,7 +1096,7 @@ mod tests {
&std::collections::HashSet::default(),
&std::collections::HashSet::default(),
&std::collections::HashMap::default(),
- &std::collections::HashMap::default(),
+ &crate::agents_view_forest::ActivityCounts::default(),
None,
);
let age = rows
diff --git a/crates/pa-tui/src/bash_view.rs b/crates/pa-tui/src/bash_view.rs
index 6b7a9cae7f..f271337ac2 100644
--- a/crates/pa-tui/src/bash_view.rs
+++ b/crates/pa-tui/src/bash_view.rs
@@ -50,6 +50,8 @@ pub struct BashActivity {
pub status: String,
pub exit_code: Option<i64>,
pub duration_ms: Option<u64>,
+ /// A persistent shell outlives its session's kernel (absent on the wire: false).
+ pub persistent: bool,
}
impl BashActivity {
@@ -95,6 +97,7 @@ pub fn parse_bash_activities(data: &Value) -> Vec<BashActivity> {
.map_or_else(|| "unknown".to_string(), crate::menu_panel::scrub_controls),
exit_code: row.get("exitCode").and_then(Value::as_i64),
duration_ms: row.get("durationMs").and_then(Value::as_u64),
+ persistent: row.get("persistent").and_then(Value::as_bool) == Some(true),
})
})
.collect();
@@ -136,13 +139,29 @@ pub(crate) fn registry_rows_moved(old: &Value, new: &Value) -> bool {
signature(old) != signature(new)
}
-/// The running shells in a `list_kernel_bash` reply: finished shells stay in the bash view only.
+/// The running shells and the persistent ones among them: finished shells stay in the bash view
+/// only.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct ShellCounts {
+ pub running: usize,
+ pub persistent: usize,
+}
+
+impl ShellCounts {
+ #[must_use]
+ pub fn of(activities: &[BashActivity]) -> Self {
+ let running = activities.iter().filter(|activity| activity.running());
+ Self {
+ running: running.clone().count(),
+ persistent: running.filter(|activity| activity.persistent).count(),
+ }
+ }
+}
+
+/// The shell counts of a `list_kernel_bash` reply (or a bare row array).
#[must_use]
-pub fn running_shell_count(data: &Value) -> usize {
- parse_bash_activities(data)
- .iter()
- .filter(|activity| activity.running())
- .count()
+pub fn running_shell_counts(data: &Value) -> ShellCounts {
+ ShellCounts::of(&parse_bash_activities(data))
}
/// The pane's interactive mode: the columned list, or a row's detail
diff --git a/crates/pa-tui/src/bash_view/tests.rs b/crates/pa-tui/src/bash_view/tests.rs
index 4125b2900f..8bff9cd037 100644
--- a/crates/pa-tui/src/bash_view/tests.rs
+++ b/crates/pa-tui/src/bash_view/tests.rs
@@ -246,6 +246,7 @@ fn the_pane_runs_to_the_bottom() {
status: "finished".to_string(),
exit_code: Some(0),
duration_ms: Some(u64::from(n) * 1_000),
+ persistent: false,
})
.collect();
for viewport in [10usize, 16, 24] {
@@ -1213,12 +1214,21 @@ fn dropping_the_detail_retires_its_fetch_error() {
assert!(!text.contains("unavailable"), "{text}");
}
+/// Only running shells count, and the persistent ones among them; a finished persistent shell
+/// counts in neither.
#[test]
-fn running_shell_count_skips_finished_shells() {
+fn running_shell_counts_skip_finished_shells() {
let data = json!({"activities": [
- {"id": "a", "command": "x", "status": "running"},
- {"id": "b", "command": "y", "status": "done"},
- {"id": "c", "command": "z", "status": "failed"},
+ {"id": "a", "command": "x", "status": "running", "persistent": true},
+ {"id": "b", "command": "y", "status": "running"},
+ {"id": "c", "command": "z", "status": "done", "persistent": true},
+ {"id": "d", "command": "w", "status": "failed"},
]});
- assert_eq!(running_shell_count(&data), 1);
+ assert_eq!(
+ running_shell_counts(&data),
+ ShellCounts {
+ running: 2,
+ persistent: 1,
+ }
+ );
}
diff --git a/crates/pa-tui/src/chrome.rs b/crates/pa-tui/src/chrome.rs
index 9be4773610..94033fd5ff 100644
--- a/crates/pa-tui/src/chrome.rs
+++ b/crates/pa-tui/src/chrome.rs
@@ -145,6 +145,8 @@ pub struct ActivityDock {
/// current session's kernel registry only): finished runs stay rows
/// inside the bash view.
pub shells: Vec<String>,
+ /// How many of the running shells are persistent.
+ pub shells_persistent: usize,
/// The live factory runs, paused first, each `<name> <state>` (a live
/// state — running, stopping, or paused — or a terminal run whose
/// children are still in flight; the current session's kernel registry
@@ -793,10 +795,18 @@ pub fn render_activity_dock_segments(
}
}
// The label reads "shell(s)": the tool name stays bash() everywhere else.
- ActivityGroup::Bash => line.push(theme.fg_span(
- activity_color(shells),
- format!("▸ {} shell{}", shells, if shells == 1 { "" } else { "s" }),
- )),
+ ActivityGroup::Bash => {
+ line.push(theme.fg_span(
+ activity_color(shells),
+ format!("▸ {} shell{}", shells, if shells == 1 { "" } else { "s" }),
+ ));
+ if dock.shells_persistent > 0 {
+ line.extend(cluster(
+ &format!("{} persistent", dock.shells_persistent),
+ activity_color(shells),
+ ));
+ }
+ }
// The factory indicator counts the running runs, and the paused
// ones in their own amber cluster (the heartbeats' grammar): done
// and failed runs stay as panels inside the factory page.
diff --git a/crates/pa-tui/src/chrome/tests.rs b/crates/pa-tui/src/chrome/tests.rs
index 511524ff00..f9f564acda 100644
--- a/crates/pa-tui/src/chrome/tests.rs
+++ b/crates/pa-tui/src/chrome/tests.rs
@@ -392,6 +392,7 @@ fn the_focused_dock_expands_into_one_row_per_group() {
heartbeats_active: vec!["5m lane canary".to_string()],
heartbeats_paused: 1,
shells: vec!["cargo test · 12.0s".to_string()],
+ shells_persistent: 0,
factory_runs: vec!["nightly paused".to_string()],
factory_counts: crate::factory_view::FactoryRunCounts {
running: 0,
@@ -987,3 +988,30 @@ fn detail_status_label() {
"Expanded mode (Ctrl+O to collapse)"
);
}
+
+/// The collapsed shells segment breaks out its persistent shells like the heartbeats' paused
+/// cluster, and its click region covers the cluster; without any it keeps the plain count.
+#[test]
+fn the_collapsed_shells_segment_counts_persistent_shells() {
+ let render = |shells_persistent| {
+ let dock = ActivityDock {
+ shells: items(2),
+ shells_persistent,
+ ..ActivityDock::default()
+ };
+ let (frame, segments) = render_activity_dock_segments(&dock, &theme(), 120);
+ let text: String = frame[1].iter().map(|span| span.content.as_str()).collect();
+ let bash = segments
+ .iter()
+ .find(|segment| segment.group == ActivityGroup::Bash)
+ .expect("the shells segment")
+ .cols
+ .clone();
+ text.chars()
+ .skip(bash.start)
+ .take(bash.end - bash.start)
+ .collect::<String>()
+ };
+ assert_eq!(render(1), "▸ 2 shells · 1 persistent");
+ assert_eq!(render(0), "▸ 2 shells");
+}
diff --git a/crates/pa-tui/src/session_ui/panels.rs b/crates/pa-tui/src/session_ui/panels.rs
index f87b2e122a..45696e2b43 100644
--- a/crates/pa-tui/src/session_ui/panels.rs
+++ b/crates/pa-tui/src/session_ui/panels.rs
@@ -111,9 +111,8 @@ impl SessionUi {
let goal_label = tray_goal_label(&self.goal_view.goal);
// The dock's shells group lists only runs actively running right now (operator scoping):
// finished runs stay in the bash view.
- let shells = crate::bash_view::dock_shell_items(&crate::bash_view::parse_bash_activities(
- &self.bash_activities,
- ));
+ let shell_rows = crate::bash_view::parse_bash_activities(&self.bash_activities);
+ let shells = crate::bash_view::dock_shell_items(&shell_rows);
// The dock's factory group lists live runs only — the view's one liveness rule
// (`FactoryRunSnapshot::is_live`: a live state, or children still in flight — a `done`
// run whose resident children still run keeps its entry like its panel and its stop
@@ -137,6 +136,7 @@ impl SessionUi {
),
heartbeats_paused: paused_heartbeat_count(&self.heartbeat_catalog),
shells,
+ shells_persistent: crate::bash_view::ShellCounts::of(&shell_rows).persistent,
factory_runs,
factory_counts: crate::factory_view::FactoryRunCounts::of(&runs),
// The group renders exactly while the daemon advertises the
diff --git a/crates/pa-tui/src/subagents.rs b/crates/pa-tui/src/subagents.rs
index be70c98ed6..6941efa734 100644
--- a/crates/pa-tui/src/subagents.rs
+++ b/crates/pa-tui/src/subagents.rs
@@ -455,7 +455,7 @@ mod tests {
&std::collections::HashSet::new(),
&std::collections::HashSet::new(),
&rollups,
- &std::collections::HashMap::new(),
+ &crate::agents_view_forest::ActivityCounts::default(),
None,
);
let row = rows