Skip to content

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

Rust

feat(pa-tui): agents-view rows carry their session's heartbeat count (#3132)

Sebastian Müllerfa3327260ae8
diff --git a/crates/pa-tui/README.md b/crates/pa-tui/README.md
index 888db31581..b327fd0ab5 100644
--- a/crates/pa-tui/README.md
+++ b/crates/pa-tui/README.md
@@ -19,7 +19,8 @@ and the list window follows the selection (TS `renderSessionRows`: the
slice centers on the selected row and clips the overflow behind
leading/trailing ellipses, so arrowing below the fold keeps the
selection on-screen instead of the view snapping back to the top of the
-list), ctrl+o's spawn-program surface (`app.agents.program`: the selected row's target — the row itself for a top-level agent, its parent otherwise — expands its list and shows the program rows, one code block per spawn cell above the children it launched, capped at 10 lines with the remainder marker, on the tool-panel background, skipped by the selection and the click surface, a second press hides it, and collapsing the list clears it), ctrl+r's rename mode (`app.agents.rename`: the prompt becomes the "Rename agent session" header over the name buffer — the search grammar, Enter submits the trimmed name through the daemon `rename`/`rename_saved_session`, Esc cancels back to the untouched query — a saved rename patches the catalog row in place), and the `tui agents action` adoption events (`program_shown`, `renamed`) that ride the view outcome out of the run.
+list; rows carry their session's `◷ N` heartbeat count from the
+`heartbeats_list` catalog, refreshed on `heartbeats_changed`), ctrl+o's spawn-program surface (`app.agents.program`: the selected row's target — the row itself for a top-level agent, its parent otherwise — expands its list and shows the program rows, one code block per spawn cell above the children it launched, capped at 10 lines with the remainder marker, on the tool-panel background, skipped by the selection and the click surface, a second press hides it, and collapsing the list clears it), ctrl+r's rename mode (`app.agents.rename`: the prompt becomes the "Rename agent session" header over the name buffer — the search grammar, Enter submits the trimmed name through the daemon `rename`/`rename_saved_session`, Esc cancels back to the untouched query — a saved rename patches the catalog row in place), and the `tui agents action` adoption events (`program_shown`, `renamed`) that ride the view outcome out of the run.
## Non-goals
No session logic, no providers, no loop policy. The interactive UI renders daemon events and sends user intents (prompts, abort, switch) as daemon commands; the session loop itself lives in the pa-daemon worker. It never computes agent behavior and never spawns the supervisor (launch semantics live in pa-cli).
diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rs
index 49aadc5b3f..a0ee28c61c 100644
--- a/crates/pa-tui/src/agents_view.rs
+++ b/crates/pa-tui/src/agents_view.rs
@@ -45,6 +45,7 @@ use render::cell;
use render::Renderer;
mod delete;
+mod heartbeats;
#[cfg(test)]
use delete::no_effect_summary;
@@ -328,6 +329,12 @@ enum UiInput {
key: String,
outcome: Result<(), String>,
},
+ /// A heartbeat-catalog fetch landed (TS `refreshHeartbeats`'s apply):
+ /// rows re-render their `◷` counts.
+ HeartbeatsLoaded {
+ generation: u64,
+ heartbeats: Vec<crate::heartbeats_picker::HeartbeatEntry>,
+ },
}
/// The flow's roster connection (TS `AgentsViewPersistentState.rosterClient`):
@@ -548,6 +555,9 @@ struct AgentsViewMode {
/// end — the view owns no telemetry handle): `program_shown`,
/// `renamed`.
actions: Vec<&'static str>,
+ /// 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 press state of one left click on the agents view (TS
@@ -656,6 +666,7 @@ impl AgentsViewMode {
hover_row: None,
pressed_click: None,
actions: Vec::new(),
+ heartbeats: Vec::new(),
}
}
}
@@ -927,6 +938,13 @@ async fn run_agents_view_surface(
let mut catalog_request = (!mode.saved_catalog_loaded).then(|| {
spawn_saved_catalog_fetch(&client, ui_tx.clone(), cwd.clone(), session_dir.clone())
});
+ // The heartbeat catalog feeds the rows' `◷ N` badges: the same
+ // selector-less `heartbeats_list` the activity dock reads, fetched
+ // open-time like TS `refreshHeartbeats` and re-read on every
+ // `heartbeats_changed` (the loop local below is the generation gate:
+ // a superseded fetch's answer never applies).
+ let mut heartbeat_generation: u64 = 1;
+ heartbeats::spawn_heartbeat_catalog_fetch(&client, ui_tx.clone(), heartbeat_generation);
// 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 -
@@ -1201,6 +1219,16 @@ async fn run_agents_view_surface(
StatusTone::Error,
);
}
+ // Only the newest fetch applies (TS
+ // `heartbeatCatalogGeneration`): responses can reorder.
+ UiInput::HeartbeatsLoaded {
+ generation,
+ heartbeats,
+ } => {
+ if generation == heartbeat_generation {
+ mode.heartbeats = heartbeats;
+ }
+ }
// 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
@@ -1247,6 +1275,17 @@ async fn run_agents_view_surface(
}
}
}
+ // TS `heartbeats_changed` → `refreshHeartbeats`:
+ // the daemon-global broadcast re-reads the
+ // catalog; the landed answer redraws, not this.
+ Some(DaemonClientEvent::HeartbeatsChanged) => {
+ heartbeat_generation += 1;
+ heartbeats::spawn_heartbeat_catalog_fetch(
+ &client,
+ ui_tx.clone(),
+ heartbeat_generation,
+ );
+ }
Some(_) => {}
None => {
mode.set_status_tone("the daemon connection closed",
@@ -1480,9 +1519,10 @@ fn advance_running_pulse(
}
/// The daemon-driven answers that jump an armed render barrier: the
-/// saved catalog's landing (or its terminal failure) and the
-/// stop-or-delete dispatch results are the events the plan's needles
-/// wait on — they must never queue behind the hold they satisfy.
+/// saved catalog's landing (or its terminal failure), the heartbeat
+/// catalog's landing, and the stop-or-delete dispatch results are the
+/// events the plan's needles wait on — they must never queue behind the
+/// hold they satisfy.
fn is_daemon_answer(input: &UiInput) -> bool {
matches!(
input,
@@ -1494,6 +1534,7 @@ fn is_daemon_answer(input: &UiInput) -> bool {
| UiInput::ReplyProgress(_)
| UiInput::ReplyResult { .. }
| UiInput::KillResult { .. }
+ | UiInput::HeartbeatsLoaded { .. }
)
}
diff --git a/crates/pa-tui/src/agents_view/heartbeats.rs b/crates/pa-tui/src/agents_view/heartbeats.rs
new file mode 100644
index 0000000000..b1b5102b93
--- /dev/null
+++ b/crates/pa-tui/src/agents_view/heartbeats.rs
@@ -0,0 +1,28 @@
+//! The heartbeat-catalog fetch for the agents-view rows' `◷ N` badges.
+use super::{mpsc, DaemonClient, DaemonCommand, UiInput};
+
+/// The heartbeat-catalog fetch (TS `refreshHeartbeats` over
+/// `listDaemonHeartbeats`): the selector-less `heartbeats_list` the
+/// activity dock reads. A landed catalog re-enters the loop tagged with
+/// its generation; a failed fetch keeps the last catalog (the dock's
+/// stale-while-revalidate) and the next `heartbeats_changed` retries.
+pub(super) fn spawn_heartbeat_catalog_fetch(
+ client: &DaemonClient,
+ ui_tx: mpsc::UnboundedSender<UiInput>,
+ generation: u64,
+) {
+ let client = client.clone();
+ tokio::spawn(async move {
+ let request = DaemonCommand::HeartbeatsList {
+ id: None,
+ active_session_id: None,
+ rest: serde_json::Map::default(),
+ };
+ if let Ok(data) = client.request_ok(request).await {
+ let _ = ui_tx.send(UiInput::HeartbeatsLoaded {
+ generation,
+ heartbeats: crate::heartbeats_picker::parse_heartbeats(&data),
+ });
+ }
+ });
+}
diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rs
index c54bdaedd7..dbdce85204 100644
--- a/crates/pa-tui/src/agents_view/render.rs
+++ b/crates/pa-tui/src/agents_view/render.rs
@@ -5,7 +5,7 @@
use super::{
build_layout, mpsc, pad_line, section_title, str_width, truncate_text, AgentsStep,
AgentsViewMode, AgentsViewRow, AgentsViewUiMode, Composer, Duration, Line, Result, RowKind,
- RowLayout, Section, Theme, ThemeColor, UiInput,
+ RowLayout, Section, Theme, ThemeColor, UiInput, Value,
};
impl AgentsViewMode {
@@ -570,20 +570,61 @@ impl AgentsViewMode {
" ".to_string(),
ratatui::style::Style::default(),
));
+ // Operator directive (2026-09-29, a sanctioned TS divergence): the
+ // row carries its own session's heartbeat count in the dock's `◷`
+ // vocabulary — TS renders `♥ N·<countdown>` (error/dim) and rolls
+ // descendants' jobs into ancestors; here the count is per-session
+ // (the dock's operator scoping), green while any job is active,
+ // amber when all are paused.
+ let session_id = row
+ .summary
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ let active_session_id = row.summary.get("activeSessionId").and_then(Value::as_str);
+ let jobs: Vec<&crate::heartbeats_picker::HeartbeatJob> = self
+ .heartbeats
+ .iter()
+ .map(|entry| &entry.job)
+ .filter(|job| job.in_session(active_session_id, session_id))
+ .collect();
+ // The badge rides only a name column with room for the row's
+ // fixed prefix plus it: a too-narrow column would push the model
+ // and cost/age cells right, so the row renders exactly as a
+ // badge-less one instead.
+ let badge = (!jobs.is_empty())
+ .then(|| format!("\u{25f7} {}", jobs.len()))
+ .filter(|badge| layout.name_width > 2 + indent_width + str_width(badge));
+ let badge_width = badge.as_deref().map_or(0, |badge| str_width(badge) + 1);
+ if let Some(badge) = badge {
+ let color = if jobs.iter().any(|job| job.is_active()) {
+ ThemeColor::Success
+ } else {
+ ThemeColor::Warning
+ };
+ line.push(crate::Span::styled(badge, theme.fg_style(color)));
+ line.push(crate::Span::styled(
+ " ".to_string(),
+ ratatui::style::Style::default(),
+ ));
+ }
// TS `formatTableCell(title, nameWidth)`: the name cell (indent +
- // icon + title) clips to the column width, so a long session name
- // can never push the model and cost/age columns off-screen. The
- // icon and its space take the first two cells.
+ // icon + badge + title) clips to the column width, so a long
+ // session name can never push the model and cost/age columns
+ // off-screen. The icon, its space, and the badge take the
+ // leading cells.
let title = truncate_text(
&row.title,
- layout.name_width.saturating_sub(2 + indent_width),
+ layout
+ .name_width
+ .saturating_sub(2 + indent_width + badge_width),
);
// Session titles render uniformly (no bold for named sessions);
// explicit product decision — differs from TS `styleRowTitle`, which
// bolds explicit session names.
let pad = layout
.name_width
- .saturating_sub(str_width(&title) + 2 + indent_width);
+ .saturating_sub(str_width(&title) + 2 + indent_width + badge_width);
line.push(crate::Span::styled(title, theme.fg_style(ThemeColor::Text)));
line.push(crate::Span::raw(" ".repeat(pad)));
line.push(crate::Span::styled(
diff --git a/crates/pa-tui/src/agents_view/tests.rs b/crates/pa-tui/src/agents_view/tests.rs
index 9b19d4c4e6..bb0ccd88fb 100644
--- a/crates/pa-tui/src/agents_view/tests.rs
+++ b/crates/pa-tui/src/agents_view/tests.rs
@@ -14,6 +14,7 @@ mod delete_stop;
mod drill_down;
mod edge_jumps;
mod entry_anchor;
+mod heartbeat_badge;
mod hints_render;
mod hover_band;
mod key_bindings;
diff --git a/crates/pa-tui/src/agents_view/tests/heartbeat_badge.rs b/crates/pa-tui/src/agents_view/tests/heartbeat_badge.rs
new file mode 100644
index 0000000000..dea4b0386e
--- /dev/null
+++ b/crates/pa-tui/src/agents_view/tests/heartbeat_badge.rs
@@ -0,0 +1,134 @@
+//! The heartbeat badge: the row's `◷ N` count between the status icon and
+//! the title, in the dock's active/paused colors.
+
+use super::*;
+
+/// One catalog row wrapping a parsed job (the daemon's session-name and
+/// first-message enrichment stay out of the badge's way).
+fn entry(job_json: &serde_json::Value) -> crate::heartbeats_picker::HeartbeatEntry {
+ crate::heartbeats_picker::HeartbeatEntry {
+ job: crate::heartbeats_picker::parse_heartbeat_job(job_json).expect("job parses"),
+ session_name: None,
+ first_message: None,
+ }
+}
+
+fn job(id: &str, status: &str, session_id: &str, active_session_id: &str) -> serde_json::Value {
+ serde_json::json!({
+ "id": id,
+ "status": status,
+ "source": "heartbeat",
+ "activeSessionId": active_session_id,
+ "sessionId": session_id,
+ "schedule": { "expression": "every 30m" },
+ })
+}
+
+/// The row's own session's jobs count before its title: the passivated
+/// stale-active-id match lands via the durable session id, another
+/// session's job stays out, and the count is active plus paused — green
+/// while any job is active (the dock's `running_color`), amber when all
+/// are paused (the dock's `◐ N paused`).
+#[test]
+fn a_rows_heartbeat_count_renders_before_its_title() {
+ for (jobs_json, badge, color) in [
+ (
+ vec![
+ job("hb-1", "active", "s", "s-live"),
+ job("hb-2", "paused", "s", "stale-live"),
+ job("hb-3", "active", "other", "other-live"),
+ ],
+ "\u{25f7} 2",
+ ThemeColor::Success,
+ ),
+ (
+ vec![job("hb-1", "paused", "s", "s-live")],
+ "\u{25f7} 1",
+ ThemeColor::Warning,
+ ),
+ ] {
+ let (mut mode, index) = mode_with_row("worker", "mock-1");
+ mode.rows[index].summary = serde_json::json!({
+ "sessionName": "worker",
+ "sessionId": "s",
+ "activeSessionId": "s-live",
+ });
+ mode.heartbeats = jobs_json.iter().map(entry).collect();
+ let layout = build_layout(&mode.rows, 120);
+ let line = mode.render_row(&mode.rows[index], &layout, 120, false);
+ let expected: crate::Line = vec![
+ crate::Span::styled(
+ "\u{2022}".to_string(),
+ mode.theme
+ .fg_style(ThemeColor::Warning)
+ .add_modifier(ratatui::style::Modifier::BOLD),
+ ),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ crate::Span::styled(badge.to_string(), mode.theme.fg_style(color)),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ crate::Span::styled("worker".to_string(), mode.theme.fg_style(ThemeColor::Text)),
+ crate::Span::styled(
+ " ".repeat(layout.name_width.saturating_sub(2 + 4 + 6)),
+ ratatui::style::Style::default(),
+ ),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ mode.theme
+ .fg(ThemeColor::Muted, cell("mock-1", layout.model_width)),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ mode.theme.fg(
+ ThemeColor::Dim,
+ layout.details.get("worker").cloned().unwrap_or_default(),
+ ),
+ ];
+ assert_eq!(line, expected);
+ }
+ // An id-less row never counts an id-less job: the empty id is no
+ // session identity (the same truth the dock's scoping holds).
+ let (mut mode, index) = mode_with_row("worker", "mock-1");
+ mode.heartbeats = vec![entry(&job("hb-none", "active", "", ""))];
+ let layout = build_layout(&mode.rows, 120);
+ let line = mode.render_row(&mode.rows[index], &layout, 120, false);
+ assert!(
+ !flat(&line).contains('\u{25f7}'),
+ "the id-less row renders no badge for the id-less job: {line:?}"
+ );
+ // A name column too narrow for the row's fixed prefix plus the badge
+ // renders exactly as a badge-less row: the model and cost/age cells
+ // never move right (width 19 squeezes `name_width` to 5, one cell
+ // short of the badge's 6-cell prefix).
+ let (mut mode, index) = mode_with_row("worker", "mock-1");
+ mode.rows[index].summary = serde_json::json!({
+ "sessionName": "worker",
+ "sessionId": "s",
+ "activeSessionId": "s-live",
+ });
+ mode.heartbeats = [
+ job("hb-1", "active", "s", "s-live"),
+ job("hb-2", "paused", "s", "stale-live"),
+ ]
+ .iter()
+ .map(entry)
+ .collect();
+ let layout = build_layout(&mode.rows, 19);
+ let line = mode.render_row(&mode.rows[index], &layout, 19, false);
+ let expected: crate::Line = vec![
+ crate::Span::styled(
+ "\u{2022}".to_string(),
+ mode.theme
+ .fg_style(ThemeColor::Warning)
+ .add_modifier(ratatui::style::Modifier::BOLD),
+ ),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ crate::Span::styled("wor".to_string(), mode.theme.fg_style(ThemeColor::Text)),
+ crate::Span::styled(String::new(), ratatui::style::Style::default()),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ mode.theme
+ .fg(ThemeColor::Muted, cell("mock-1", layout.model_width)),
+ crate::Span::styled(" ".to_string(), ratatui::style::Style::default()),
+ mode.theme.fg(
+ ThemeColor::Dim,
+ layout.details.get("worker").cloned().unwrap_or_default(),
+ ),
+ ];
+ assert_eq!(line, expected);
+}
diff --git a/crates/pa-tui/src/heartbeats_picker/data.rs b/crates/pa-tui/src/heartbeats_picker/data.rs
index deb8c03b22..28eb48f9eb 100644
--- a/crates/pa-tui/src/heartbeats_picker/data.rs
+++ b/crates/pa-tui/src/heartbeats_picker/data.rs
@@ -29,10 +29,20 @@ pub struct HeartbeatJob {
impl HeartbeatJob {
/// The job's status word, `active` or `paused`.
- pub(super) fn is_active(&self) -> bool {
+ pub(crate) fn is_active(&self) -> bool {
self.status == "active"
}
+ /// Whether this job belongs to the session: its durable session
+ /// matches, or its live session does (TS `scopeHeartbeatsToSession`'s
+ /// own-session arms). An empty id is no session identity: neither
+ /// arm matches on one.
+ pub(crate) fn in_session(&self, active_session_id: Option<&str>, session_id: &str) -> bool {
+ (!session_id.is_empty() && self.session_id == session_id)
+ || active_session_id
+ .is_some_and(|active| !active.is_empty() && self.active_session_id == active)
+ }
+
/// Whether an agent created this job (TS source label test).
fn is_user_created(&self) -> bool {
self.source.as_deref() == Some("heartbeat")
@@ -121,15 +131,13 @@ pub fn scope_heartbeats(
session_id: Option<&str>,
child_active_session_ids: &[String],
) -> Vec<HeartbeatEntry> {
- let Some(session_id) = session_id.filter(|id| !id.is_empty()) else {
+ let Some(session_id) = session_id else {
return Vec::new();
};
entries
.into_iter()
.filter(|entry| {
- entry.job.session_id == session_id
- || (active_session_id.is_some()
- && entry.job.active_session_id == active_session_id.unwrap_or_default())
+ entry.job.in_session(active_session_id, session_id)
|| child_active_session_ids.contains(&entry.job.active_session_id)
})
.collect()
diff --git a/crates/pa-tui/tests/agents_view_heartbeat_badge_headless.rs b/crates/pa-tui/tests/agents_view_heartbeat_badge_headless.rs
new file mode 100644
index 0000000000..f7aa5dda8c
--- /dev/null
+++ b/crates/pa-tui/tests/agents_view_heartbeat_badge_headless.rs
@@ -0,0 +1,290 @@
+//! The heartbeat badge, headless against a mock supervisor: the open
+//! fetch lands an empty catalog, the daemon's `heartbeats_changed`
+//! broadcast re-reads the catalog, and the landed answer (promoted past
+//! the armed render barrier, the generation gate applied) repaints the
+//! row with its `◷ N` badge — the badge can only come from the
+//! event-driven refetch, so the plan proves the whole wiring.
+#![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::{AgentsHeadlessPlan, AgentsStep, AgentsViewOptions, AgentsViewUiMode};
+use serde_json::{json, Value};
+
+struct MockSupervisor {
+ listener: UnixListener,
+}
+
+impl MockSupervisor {
+ fn bind(socket: &std::path::Path) -> Self {
+ MockSupervisor {
+ listener: UnixListener::bind(socket).expect("bind mock socket"),
+ }
+ }
+
+ /// Serve one agents-view connection: hello, then the command loop.
+ /// The first `heartbeats_list` answer is empty and pushes the
+ /// daemon-global `heartbeats_changed` broadcast, so the badge can
+ /// only render through the event-driven refetch.
+ fn serve(self) {
+ let (stream, _) = self.listener.accept().expect("accept view connection");
+ stream
+ .set_read_timeout(Some(Duration::from_millis(100)))
+ .expect("read timeout");
+ let write_stream = stream.try_clone().expect("clone socket");
+ let mut writer = write_stream;
+ let mut reader = BufReader::new(stream);
+ let mut heartbeats_served = 0usize;
+ write_line(
+ &mut writer,
+ &json!({
+ "type": "daemon_hello",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "serverCapabilities": [],
+ }),
+ );
+ loop {
+ let Some(line) = read_line(&mut reader) else {
+ return;
+ };
+ let Ok(envelope) = serde_json::from_str::<Value>(&line) else {
+ continue;
+ };
+ let id = envelope
+ .get("id")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);
+ let command_type = command
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ match command_type {
+ "roster_subscribe" => {
+ let roster = vec![json!({
+ "agentId": "s1",
+ "status": "idle",
+ "summary": {
+ "sessionId": "s1",
+ "lifecycle": "live",
+ "activeSessionId": "s1-live",
+ "sessionFile": "/tmp/s1.jsonl",
+ "runtimeKind": "top-level",
+ "sessionName": "live one",
+ "messageCount": 2,
+ "rlmDepth": 0,
+ },
+ })];
+ if !respond(
+ &mut writer,
+ id,
+ "roster_subscribe",
+ &json!({ "roster": roster }),
+ ) {
+ return;
+ }
+ }
+ "list_saved_sessions" => {
+ if !respond(
+ &mut writer,
+ id,
+ "list_saved_sessions",
+ &json!({ "sessions": [] }),
+ ) {
+ return;
+ }
+ }
+ "heartbeats_list" => {
+ heartbeats_served += 1;
+ if !respond(
+ &mut writer,
+ id,
+ "heartbeats_list",
+ &heartbeat_answer(heartbeats_served),
+ ) {
+ return;
+ }
+ if heartbeats_served == 1 {
+ let changed = json!({ "type": "heartbeats_changed" });
+ if !write_line(&mut writer, &changed) {
+ return;
+ }
+ }
+ }
+ "roster_unsubscribe" => {
+ // The view's teardown fires the unsubscribe
+ // fire-and-forget; the answer ends the mock's one
+ // connection so the test's join never rides out the
+ // quiet cap.
+ let _ = respond(&mut writer, id, "roster_unsubscribe", &Value::Null);
+ return;
+ }
+ other => {
+ if !respond_failure(&mut writer, id, other, "not handled by the mock") {
+ return;
+ }
+ }
+ }
+ }
+ }
+}
+
+/// One best-effort line write: `false` reports the view connection died,
+/// so the serve loop ends instead of panicking inside the test thread.
+fn write_line(writer: &mut UnixStream, value: &Value) -> bool {
+ let Ok(mut line) = serde_json::to_string(value) else {
+ return false;
+ };
+ line.push('\n');
+ writer.write_all(line.as_bytes()).is_ok() && writer.flush().is_ok()
+}
+
+/// The first `heartbeats_list` answer is an empty catalog; the next
+/// carries the roster session's own heartbeat.
+fn heartbeat_answer(heartbeats_served: usize) -> Value {
+ if heartbeats_served == 1 {
+ json!({ "heartbeats": [] })
+ } else {
+ json!({ "heartbeats": [json!({
+ "job": {
+ "id": "hb-1",
+ "status": "active",
+ "source": "heartbeat",
+ "activeSessionId": "s1-live",
+ "sessionId": "s1",
+ "schedule": { "expression": "every 30m" },
+ },
+ })]})
+ }
+}
+
+fn respond(writer: &mut UnixStream, id: &str, command: &str, data: &Value) -> bool {
+ 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) -> bool {
+ write_line(
+ writer,
+ &json!({
+ "id": id,
+ "type": "response",
+ "command": command,
+ "success": false,
+ "error": error,
+ }),
+ )
+}
+
+/// One line with a bounded quiet window: the view connection sits quiet
+/// between its inputs, so timeouts keep the loop alive for a bounded
+/// span; `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,
+ }
+ }
+}
+
+/// One view options set.
+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!({}),
+ }
+}
+
+/// The badge renders through the whole wiring: the open fetch lands an
+/// empty catalog, the daemon's `heartbeats_changed` broadcast re-reads
+/// the catalog (the only path the row's job arrives on), the landed
+/// answer jumps the armed render barrier (without the daemon-answer
+/// promotion it queues behind the hold it satisfies, the deadline pops
+/// it, and `Done` ends the run before the badge ever paints), and the
+/// row renders the dock's `◷ N` vocabulary between its status icon and
+/// its title.
+#[tokio::test]
+async fn the_row_renders_its_heartbeat_count_after_a_heartbeats_changed() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("agents-view.sock");
+ let mock = MockSupervisor::bind(&socket);
+ let server = std::thread::spawn(move || mock.serve());
+
+ let plan = AgentsHeadlessPlan {
+ steps: vec![AgentsStep::WaitRender {
+ needle: "\u{25f7} 1".to_string(),
+ timeout_ms: 10_000,
+ }],
+ width: 120,
+ height: 36,
+ };
+ let outcome = pa_tui::agents_view::run_agents_view(
+ view_options(&socket),
+ AgentsViewUiMode::Headless(plan),
+ None,
+ )
+ .await
+ .expect("the agents view run")
+ .outcome;
+
+ assert!(
+ outcome
+ .frames
+ .last()
+ .is_some_and(|frame| frame.contains("\u{2022} \u{25f7} 1 live one")),
+ "the run ended on the badge-rendered row:\n{:?}",
+ outcome.frames.last()
+ );
+
+ // Yield to the runtime so the teardown's fire-and-forget
+ // roster_unsubscribe runs: the mock answers it and ends, so the
+ // join never rides out its quiet cap.
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ let _ = server.join();
+}