Skip to content

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

Rust

show a live timer while a tool call runs (#3329)

ktb8591c5a1a30
diff --git a/crates/pa-cli/src/interactive_mode/telemetry.rs b/crates/pa-cli/src/interactive_mode/telemetry.rs
index e1bd908222..9e18b87b77 100644
--- a/crates/pa-cli/src/interactive_mode/telemetry.rs
+++ b/crates/pa-cli/src/interactive_mode/telemetry.rs
@@ -1,10 +1,10 @@
//! The interaction-telemetry concern: the pa-tui interactive loop reports
//! through the `InteractionTelemetry` trait. Interactions only count into
-//! the session run's counters, which ride its one `tui exit` event. Two
-//! standalone events remain their own (TS parity, plus one upstream
-//! addition): `agent command used`, and `tui ipython bash rendered` —
-//! the settled-shell-cell metric upstream #3307 tracks per render, kept
-//! intact from main.
+//! the session run's counters, which ride its one `tui exit` event. The
+//! standalone events remain their own (TS parity, plus upstream additions):
+//! `agent command used`, `tui ipython bash rendered` — the
+//! settled-shell-cell metric upstream #3307 tracks per render, kept intact
+//! from main.
use std::collections::BTreeMap;
use std::sync::Mutex;
@@ -12,10 +12,9 @@ use std::sync::Mutex;
use super::{Future, PathBuf, Pin};
/// The interactive client's telemetry: per-session-run adoption counters
-/// flushed with `tui exit`, plus the two standalone events — the TS
-/// `agent command used`, and the upstream #3307 `tui ipython bash
-/// rendered` — each on a one-shot client. Telemetry must never fail the
-/// session: opt-out or a broken install id drops the events.
+/// flushed with `tui exit`, plus the standalone events — the TS
+/// `agent command used`, the upstream #3307 `tui ipython bash rendered` — each on a one-shot client. Telemetry must
+/// never fail the session: opt-out or a broken install id drops the events.
pub(super) struct CliInteractionTelemetry {
pub(super) cwd: PathBuf,
pub(super) agent_dir: PathBuf,
@@ -173,6 +172,11 @@ impl pa_tui::interactive::InteractionTelemetry for CliInteractionTelemetry {
})
}
+ fn live_tool_timer_started(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ self.count("tui_live_tool_timer_count");
+ Box::pin(std::future::ready(()))
+ }
+
fn scroll_used(
&self,
_action: &'static str,
diff --git a/crates/pa-telemetry/src/catalog.rs b/crates/pa-telemetry/src/catalog.rs
index f91abb1069..3acf9be488 100644
--- a/crates/pa-telemetry/src/catalog.rs
+++ b/crates/pa-telemetry/src/catalog.rs
@@ -981,8 +981,9 @@ const SESSION_ARCHIVED: EventRule = EventRule {
/// A settled ipython cell that rendered as bash (v2): its executed
/// `bash()` line share and command count, never command text. One of the
-/// two standalone TUI events (with `agent command used`), tracked per
-/// render by the upstream #3307 addition and kept intact.
+/// standalone TUI events (with `agent command used`),
+/// tracked per render by the upstream #3307
+/// addition and kept intact.
const TUI_IPYTHON_BASH_RENDERED: EventRule = EventRule {
name: "tui ipython bash rendered",
since: 2,
@@ -1010,6 +1011,7 @@ const TUI_EXIT: EventRule = EventRule {
),
("turn_active", required(boolean())),
("tui_scroll_count", optional(count())),
+ ("tui_live_tool_timer_count", optional(count())),
("tui_selection_count", optional(count())),
("tui_click_count", optional(count())),
("tui_menu_open_count", optional(count())),
diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs
index 0f71f9f038..b6b97e0a41 100644
--- a/crates/pa-tui/src/interactive.rs
+++ b/crates/pa-tui/src/interactive.rs
@@ -271,6 +271,8 @@ pub trait InteractionTelemetry: Send + Sync {
cell_lines: usize,
count: usize,
) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
+ /// A tool call started executing with a live timer; counted on `tui exit`.
+ fn live_tool_timer_started(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}
/// Options for one interactive run. `Debug` skips the telemetry handle (the trait object is not
diff --git a/crates/pa-tui/src/session_ui/apply.rs b/crates/pa-tui/src/session_ui/apply.rs
index 2a18cc6b30..336c5dcce4 100644
--- a/crates/pa-tui/src/session_ui/apply.rs
+++ b/crates/pa-tui/src/session_ui/apply.rs
@@ -349,8 +349,13 @@ impl SessionUi {
TurnUpdate::TurnStarted => {
self.turn_active = true;
self.turn_error_shown = false;
- // No card from a previous run settles on this one's failure.
- self.pending_tools.clear();
+ // A new turn also settles leftovers from a lost turn-end frame.
+ crate::snapshot::settle_pending_tool_cards(
+ view,
+ &mut self.pending_tools,
+ &mut self.aborted_tools,
+ "the turn ended before this call returned",
+ );
self.aborted_tools.clear();
self.start_loader(view);
}
@@ -392,8 +397,11 @@ impl SessionUi {
args,
} => {
// The failed frame's sweep owns the call: the run's late tool frames land
- // on nothing.
- if !self.aborted_tools.contains(&tool_call_id) {
+ // on nothing. A start outside a live turn is one of those late
+ // frames — it would allocate a fresh card whose timer then
+ // reticks the settled id on this run's paints, so it lands
+ // on nothing too.
+ if !self.aborted_tools.contains(&tool_call_id) && self.turn_active {
crate::snapshot::apply_tool_execution_start(
view,
&tool_call_id,
@@ -404,6 +412,7 @@ impl SessionUi {
// pending-state reset or arrive without its own streamed frame).
self.pending_tools.insert(tool_call_id.clone());
Self::set_working_activity("Executing", false, view);
+ self.track_live_tool_timer();
}
}
TurnUpdate::ToolExecutionUpdate {
@@ -446,8 +455,12 @@ impl SessionUi {
view.retry = None;
// The turn settled: the held bash cards stream into the transcript.
Self::flush_pending_bash(view);
- // Stragglers never leak into the next run.
- self.pending_tools.clear();
+ crate::snapshot::settle_pending_tool_cards(
+ view,
+ &mut self.pending_tools,
+ &mut self.aborted_tools,
+ "the turn ended before this call returned",
+ );
self.aborted_tools.clear();
// A provider failure already surfaced through the failed assistant message
// or the retry-exhausted banner; the turn result error is only a backstop.
@@ -893,6 +906,16 @@ impl SessionUi {
false
}
+ /// Count live timer starts with the session's other interaction counters.
+ fn track_live_tool_timer(&self) {
+ let Some(telemetry) = self.telemetry.clone() else {
+ return;
+ };
+ tokio::spawn(async move {
+ telemetry.live_tool_timer_started().await;
+ });
+ }
+
/// `tui ipython bash rendered`: the settled ipython card that renders
/// as bash reports its bash share, primitives only.
fn track_ipython_bash_rendered(&self, card: &crate::tool_card::ToolCallCard) {
diff --git a/crates/pa-tui/src/snapshot/tool_fold.rs b/crates/pa-tui/src/snapshot/tool_fold.rs
index 0274b4817b..8bbbc0fda3 100644
--- a/crates/pa-tui/src/snapshot/tool_fold.rs
+++ b/crates/pa-tui/src/snapshot/tool_fold.rs
@@ -49,23 +49,29 @@ pub fn settle_pending_tool_cards<S: std::hash::BuildHasher + Default>(
text: &str,
) {
for tool_call_id in pending.drain() {
- // Every drained id records as aborted — late frames for a call
- // that never created a card land on nothing the same way.
- aborted.insert(tool_call_id.clone());
- // The settle targets the newest card carrying the id; the older
- // settled card keeps the previous sweep's result.
- if let Some(index) = view
+ // Later message updates may repeat an already-completed call's id.
+ // Drain that stale pending entry without changing its final result.
+ let card_index = view
.chat
.iter()
- .rposition(|entry| matches!(entry, ChatEntry::Tool(card) if card.id == tool_call_id))
- {
+ .rposition(|entry| matches!(entry, ChatEntry::Tool(card) if card.id == tool_call_id));
+ if card_index.is_some_and(
+ |index| matches!(&view.chat[index], ChatEntry::Tool(card) if card.ended_at.is_some()),
+ ) {
+ continue;
+ }
+ // Calls without a card also record as aborted, blocking their late frames.
+ aborted.insert(tool_call_id.clone());
+ if let Some(index) = card_index {
view.prepare_entry_mutation(index);
if let Some(ChatEntry::Tool(card)) = view.chat.get_mut(index) {
- card.result = Some(ToolResultView {
+ // Keep any partial output when an abort or turn boundary settles the call.
+ let result = card.result.get_or_insert_with(|| ToolResultView {
content: vec![serde_json::json!({ "type": "text", "text": text })],
details: serde_json::Value::Null,
is_error: true,
});
+ result.is_error = true;
card.result_partial = false;
card.ended_at = Some(std::time::Instant::now());
card.aborted = true;
diff --git a/crates/pa-tui/src/tool_card/bash.rs b/crates/pa-tui/src/tool_card/bash.rs
index 4178a14c07..05fe3a8789 100644
--- a/crates/pa-tui/src/tool_card/bash.rs
+++ b/crates/pa-tui/src/tool_card/bash.rs
@@ -6,7 +6,7 @@
use serde_json::Value;
use super::layout::{panel_content_width, RowOutput};
-use super::{format_bash_duration, ToolCallCard, ToolResultView};
+use super::{ToolCallCard, ToolResultView};
use crate::chat::Detail;
use crate::code_preview::{preview_bash_command, CodePreviewLanguage};
use crate::theme::{Theme, ThemeColor};
@@ -52,7 +52,6 @@ fn visit(card: &ToolCallCard, detail: Detail, theme: &Theme, width: usize, rows:
rows.wrapped_line(&format_bash_call(card, theme), content_width);
if let Some(result) = &card.result {
bash_result_rows(
- card,
result,
detail.tool_output_expanded(),
theme,
@@ -60,6 +59,11 @@ fn visit(card: &ToolCallCard, detail: Detail, theme: &Theme, width: usize, rows:
rows,
);
}
+ // The live `Took`/`Elapsed` duration row: the shared emitter ticks
+ // the running card's elapsed on every repaint (a running call has no
+ // result rows yet, so the row is the card's only timing until the
+ // streamed output arrives).
+ super::duration_row(card, theme, content_width, rows);
}
/// The `$ command` call row (TS `formatBashCall`): dim, with the command
@@ -100,7 +104,6 @@ fn format_bash_call(card: &ToolCallCard, theme: &Theme) -> Line {
/// The result rows (TS `rebuildBashResultRenderComponent`): output rows,
/// the truncation warning, the duration row.
fn bash_result_rows(
- card: &ToolCallCard,
result: &ToolResultView,
expanded: bool,
theme: &Theme,
@@ -164,17 +167,6 @@ fn bash_result_rows(
rows.blank();
rows.wrapped_text(&warning, theme.fg_style(ThemeColor::Warning), content_width);
}
- if let Some(started) = card.started_at {
- let label = if card.result_partial {
- "Elapsed"
- } else {
- "Took"
- };
- let elapsed = card.ended_at.unwrap_or_else(std::time::Instant::now) - started;
- let text = format!("{label} {}", format_bash_duration(elapsed.as_millis()));
- rows.blank();
- rows.wrapped_text(&text, theme.fg_style(ThemeColor::Dim), content_width);
- }
}
/// The truncation notice (`[Full output: ... . Truncated: ...]`, warning
@@ -237,6 +229,13 @@ mod tests {
Theme::builtin("prime", ColorMode::TrueColor)
}
+ /// The instant `ms` milliseconds ago: the live timer's start.
+ fn started_ms_ago(ms: u64) -> std::time::Instant {
+ std::time::Instant::now()
+ .checked_sub(std::time::Duration::from_millis(ms))
+ .expect("the clock is past the start")
+ }
+
fn done_card(command: &str, output: &str) -> ToolCallCard {
ToolCallCard {
id: "toolu_1".into(),
@@ -380,6 +379,28 @@ mod tests {
assert!(flat.iter().any(|r| r.contains("Elapsed ")), "got: {flat:?}");
}
+ #[test]
+ fn running_card_renders_live_elapsed_before_any_result() {
+ // The quiet window between `tool_execution_start` and the first
+ // streamed frame: the card has a start and no result at all, and
+ // the live timer is the only timing it shows. The value follows
+ // the execution start (the 80ms repaints recompute it) — the
+ // headless timer e2e asserts that tracking across frames, so
+ // this test pins only the row's presence.
+ let card = ToolCallCard {
+ id: "t".into(),
+ name: "bash".into(),
+ args: json!({ "command": "sleep 1" }),
+ started: true,
+ started_at: Some(started_ms_ago(300)),
+ ..Default::default()
+ };
+ let rows = render(&card, 3, Detail::Overview, &theme(), 120, true);
+ let flat: Vec<String> = rows.iter().map(text_of).collect();
+ assert!(flat.iter().any(|r| r.contains("Elapsed ")), "got: {flat:?}");
+ assert!(!flat.iter().any(|r| r.contains("Took ")), "got: {flat:?}");
+ }
+
#[test]
fn invalid_and_missing_command_shapes() {
let card = ToolCallCard {
diff --git a/crates/pa-tui/src/tool_card/generic.rs b/crates/pa-tui/src/tool_card/generic.rs
index dc6cc67384..7af55089d2 100644
--- a/crates/pa-tui/src/tool_card/generic.rs
+++ b/crates/pa-tui/src/tool_card/generic.rs
@@ -68,6 +68,14 @@ fn traverse(
);
}
out.images(card.result.as_ref(), show_images, theme);
+ // The live timer (operator feature 2026-10-03): while the call runs,
+ // the panel carries the same `Elapsed x.xs` row the bash panel shows,
+ // ticking on the loader spinner's repaints. The settled card keeps
+ // its exact TS shape — the fallback panel renders no duration row —
+ // so the tick retires with the call.
+ if super::live_started(card).is_some() {
+ super::duration_row(card, theme, content_width, out);
+ }
}
/// Preview the first three source lines, not the first three wrapped rows.
@@ -107,6 +115,13 @@ mod tests {
Theme::builtin("prime", ColorMode::TrueColor)
}
+ /// The instant `ms` milliseconds ago: the live timer's start.
+ fn started_ms_ago(ms: u64) -> std::time::Instant {
+ std::time::Instant::now()
+ .checked_sub(std::time::Duration::from_millis(ms))
+ .expect("the clock is past the start")
+ }
+
fn text_of(line: &Line) -> String {
line.iter().map(|s| s.content.as_str()).collect()
}
@@ -178,6 +193,25 @@ mod tests {
assert!(!flat.iter().any(|r| r.contains("[image/png")));
}
+ #[test]
+ fn running_card_renders_live_elapsed() {
+ // The live timer (operator feature 2026-10-03): a running call
+ // carries the same `Elapsed x.xs` row the bash panel shows,
+ // recomputed on every repaint.
+ let card = ToolCallCard {
+ id: "t".into(),
+ name: "custom".into(),
+ args: json!({ "query": "sweep" }),
+ started: true,
+ started_at: Some(started_ms_ago(300)),
+ ..Default::default()
+ };
+ let rows = render(&card, 3, Detail::Overview, &theme(), 120, true);
+ let flat: Vec<String> = rows.iter().map(text_of).collect();
+ assert!(flat.iter().any(|r| r.contains("Elapsed ")), "got: {flat:?}");
+ assert!(!flat.iter().any(|r| r.contains("Took ")), "got: {flat:?}");
+ }
+
#[test]
fn collapsed_fallback_shows_three_lines_and_hint() {
let card = ToolCallCard {
diff --git a/crates/pa-tui/src/tool_card/ipython.rs b/crates/pa-tui/src/tool_card/ipython.rs
index 6d9054703e..98659c2c7f 100644
--- a/crates/pa-tui/src/tool_card/ipython.rs
+++ b/crates/pa-tui/src/tool_card/ipython.rs
@@ -39,6 +39,13 @@ enum CardStatus {
impl CardStatus {
fn of(card: &ToolCallCard, details: &IpythonDetails) -> CardStatus {
+ // An interrupted cell never renders as a success: a settled
+ // straggler's kept partial can still carry a background shell
+ // whose exit code reads Done, and the aborted stamp is the
+ // truth the exit code never saw.
+ if card.aborted {
+ return CardStatus::Aborted;
+ }
let result = card.result.as_ref();
let is_error = result.is_some_and(|r| r.is_error);
if !card.result_partial {
@@ -214,6 +221,7 @@ fn collapsed_line(
};
let mut parts: Vec<Line> = Vec::new();
+ let mut preview_index: Option<usize> = None;
let mut marker = marker;
marker.push(Span::raw(" "));
marker.push(Span::styled(language_label, muted));
@@ -221,12 +229,14 @@ fn collapsed_line(
if let Some(bash) = dominant {
let preview = preview_bash_command(&bash.first);
if !preview.text.is_empty() {
+ preview_index = Some(parts.len());
parts.push(vec![Span::styled(preview.text, dim)]);
}
if bash.count > 1 {
parts.push(vec![Span::styled(format!("+{} more", bash.count - 1), dim)]);
}
} else if !preview.text.is_empty() {
+ preview_index = Some(parts.len());
parts.push(vec![Span::styled(preview.text, dim)]);
} else if !card.started {
parts.push(vec![Span::styled("waiting for code".to_string(), dim)]);
@@ -234,6 +244,7 @@ fn collapsed_line(
if let Some(counts) = line_counts(card, details, code) {
parts.push(vec![Span::styled(counts, dim)]);
}
+ let mut live_timer = false;
if let Some(duration) = details.duration_ms {
let label = if background.is_some() {
format!("cell {}", format_duration(duration))
@@ -241,6 +252,16 @@ fn collapsed_line(
format_duration(duration)
};
parts.push(vec![Span::styled(label, dim)]);
+ } else if let Some(started) = card
+ .started_at
+ .filter(|_| card.ended_at.is_none() || card.aborted)
+ {
+ let elapsed = card.ended_at.unwrap_or_else(std::time::Instant::now) - started;
+ parts.push(vec![Span::styled(
+ format_duration(elapsed.as_millis() as f64),
+ dim,
+ )]);
+ live_timer = card.ended_at.is_none();
}
if !card.result_partial {
let error_name = details
@@ -258,6 +279,38 @@ fn collapsed_line(
}
}
+ // The live timer is only useful on screen, but the summary clips
+ // from the right and the duration slot clips first: while the cell
+ // runs, the code preview gives the ticking duration room by
+ // shortening (or, if it cannot fit at all, dropping) itself. The
+ // settled card keeps its established layout — `durationMs` lands
+ // in the same slot, clipped exactly as before.
+ if live_timer {
+ let separator_width = str_width(" \u{00b7} ");
+ let used = parts
+ .iter()
+ .map(|p| crate::width::line_width(p))
+ .sum::<usize>()
+ + separator_width * parts.len().saturating_sub(1)
+ + 1;
+ if used > width {
+ let excess = used - width;
+ match preview_index {
+ Some(index) if crate::width::line_width(&parts[index]) > excess => {
+ let part = &mut parts[index];
+ let target = crate::width::line_width(part) - excess;
+ if let Some(span) = part.first_mut() {
+ span.content = crate::width::truncate_to_width(&span.content, target, "");
+ }
+ }
+ Some(index) => {
+ parts.remove(index);
+ }
+ None => {}
+ }
+ }
+ }
+
let mut row: Line = vec![Span::raw(" ")];
for (index, part) in parts.iter().enumerate() {
if index > 0 {
diff --git a/crates/pa-tui/src/tool_card/ipython/tests.rs b/crates/pa-tui/src/tool_card/ipython/tests.rs
index f0def089b6..1f389733e9 100644
--- a/crates/pa-tui/src/tool_card/ipython/tests.rs
+++ b/crates/pa-tui/src/tool_card/ipython/tests.rs
@@ -244,6 +244,63 @@ fn bash_cell_renders_bash_mode_line() {
assert!(flat[2].contains("echo hi"), "got: {flat:?}");
}
+#[test]
+fn running_cell_summary_ticks_live_elapsed() {
+ // The live timer (operator feature 2026-10-03): while the cell runs,
+ // the duration slot ticks the elapsed since the execution start; the
+ // kernel's `durationMs` lands in the same slot when the cell settles.
+ let mut card = cell_card("time.sleep(2)", json!({ "status": "ok" }), false, true);
+ card.started_at = Some(
+ std::time::Instant::now()
+ .checked_sub(std::time::Duration::from_millis(1500))
+ .expect("the clock is past the start"),
+ );
+ let lines = render(&card, 0, Detail::Overview, &theme(), 100, true);
+ let text = text_of(&lines[0]);
+ assert!(text.contains("↑ 1 lines"), "got: {text}");
+ // The duration slot ticks right after the line counts: the summary's
+ // last segment is a live `<seconds>s` value, without pinning the
+ // leading second (a descheduled render must not flake the shape).
+ let duration_part = text.rsplit(" \u{00b7} ").next().unwrap_or_default();
+ assert!(
+ duration_part.ends_with('s') && duration_part.trim_end_matches('s').parse::<f64>().is_ok(),
+ "the live duration ticks in its own slot: {text}"
+ );
+ assert!(!text.contains("Took "), "got: {text}");
+}
+
+#[test]
+fn running_cell_long_preview_keeps_live_duration_visible() {
+ // The summary clips from the right, so a preview that fills the width
+ // would clip the ticking duration first: while the cell runs, the
+ // preview shortens itself to keep the live duration on screen (the
+ // settled card keeps its established layout, clipping the same way
+ // it always has). The preview words stay under the noise-redaction
+ // run length so the descriptor caps at its full 64 units.
+ let code = format!("print('{}')", "lorem ipsum ".repeat(8));
+ let mut card = cell_card(&code, json!({ "status": "ok" }), false, true);
+ card.started_at = Some(
+ std::time::Instant::now()
+ .checked_sub(std::time::Duration::from_millis(1500))
+ .expect("the clock is past the start"),
+ );
+ let lines = render(&card, 0, Detail::Overview, &theme(), 80, true);
+ let text = text_of(&lines[0]);
+ // Pre-fix this line is red: the row overflows to 95 columns and the
+ // right clip eats the duration slot entirely, so the summary's last
+ // segment is a fragment of the line counts, never a duration.
+ let duration_part = text.rsplit(" \u{00b7} ").next().unwrap_or_default();
+ assert!(
+ duration_part.ends_with('s') && duration_part.trim_end_matches('s').parse::<f64>().is_ok(),
+ "the live duration stays on screen as its own segment: {text}"
+ );
+ assert!(crate::width::str_width(&text) <= 80, "got: {text}");
+ assert!(
+ text.matches("lorem").count() < 8,
+ "the preview gave the duration its room: {text}"
+ );
+}
+
#[test]
fn background_shell_duration_label_and_exit() {
let code = "h = bash('sleep 0.1')";
@@ -268,6 +325,26 @@ fn background_shell_duration_label_and_exit() {
assert!(text.contains("\u{2717}"), "got: {text}");
}
+#[test]
+fn aborted_cell_never_renders_done_from_a_stale_exit_code() {
+ // The settle shape: a straggler's kept partial carries a background
+ // shell that already exited 0, but the aborted stamp is the truth —
+ // the turn cut the call off, so the summary renders the aborted
+ // marker, never the success checkmark.
+ let code = "h = bash('sleep 0.1')";
+ let details = json!({
+ "status": "ok",
+ "durationMs": 12,
+ "result": "<BashHandle pid=421 exit_code=0 command='sleep 0.1'>",
+ });
+ let mut card = cell_card(code, details, false, false);
+ card.aborted = true;
+ let lines = render(&card, 0, Detail::Overview, &theme(), 100, true);
+ let text = text_of(&lines[0]);
+ assert!(text.contains("\u{2717}"), "got: {text}");
+ assert!(!text.contains("\u{2713}"), "got: {text}");
+}
+
#[test]
fn partial_cell_shows_waiting_for_output() {
let card = cell_card("print(2)", json!({ "status": "ok" }), false, true);
@@ -403,3 +480,19 @@ fn bash_minority_cell_stays_python() {
);
assert_eq!(bash_dominated_stats(&card), None);
}
+
+#[test]
+fn an_aborted_cell_freezes_its_duration_from_card_timestamps() {
+ let now = std::time::Instant::now();
+ let mut card = cell_card("print('x')", Value::Null, true, false);
+ card.started_at = now.checked_sub(std::time::Duration::from_secs(4));
+ card.ended_at = now.checked_sub(std::time::Duration::from_secs(1));
+ card.aborted = true;
+ let first = render(&card, 0, Detail::Overview, &theme(), 100, true);
+ let later = render(&card, 10, Detail::Overview, &theme(), 100, true);
+ assert_eq!(
+ first, later,
+ "a settled timer never repaints a different duration"
+ );
+ assert!(text_of(&first[0]).contains("3.0s"), "got: {first:?}");
+}
diff --git a/crates/pa-tui/src/tool_card/mod.rs b/crates/pa-tui/src/tool_card/mod.rs
index 597ee07cac..28eb2f70e9 100644
--- a/crates/pa-tui/src/tool_card/mod.rs
+++ b/crates/pa-tui/src/tool_card/mod.rs
@@ -208,6 +208,46 @@ pub(crate) fn format_bash_duration(ms: u128) -> String {
format!("{:.1}s", ms as f64 / 1000.0)
}
+/// The instant a still-running call started (the live-timer gate,
+/// operator feature 2026-10-03): `Some` while the card saw its execution
+/// start and the final result never landed — every settle path stamps
+/// `ended_at` together with the result — `None` once settled or when the
+/// card never saw its start (the TS render-state lifecycle). A running
+/// call exists only inside an active turn, and the turn's loader spinner
+/// keeps the loop repainting at its 80ms phase cadence (#3296's wake), so
+/// a duration rendered from this instant ticks on those repaints without
+/// adding a wake of its own.
+fn live_started(card: &ToolCallCard) -> Option<Instant> {
+ card.started_at.filter(|_| card.ended_at.is_none())
+}
+
+/// The `Elapsed`/`Took` duration row the panel shells render below the
+/// call's content (the bash card's TS `Took 1.2s` row): while the call
+/// runs the label is `Elapsed` and the value is recomputed on every
+/// paint — the loader spinner's 80ms phase repaints tick it — and once
+/// the final result lands the row is the exact static `Took` timing the
+/// settled card always rendered. A card that never saw its execution
+/// start renders no row.
+fn duration_row(
+ card: &ToolCallCard,
+ theme: &Theme,
+ content_width: usize,
+ rows: &mut layout::RowOutput,
+) {
+ let Some(started) = card.started_at else {
+ return;
+ };
+ let label = if card.ended_at.is_some() {
+ "Took"
+ } else {
+ "Elapsed"
+ };
+ let elapsed = card.ended_at.unwrap_or_else(Instant::now) - started;
+ let text = format!("{label} {}", format_bash_duration(elapsed.as_millis()));
+ rows.blank();
+ rows.wrapped_text(&text, theme.fg_style(ThemeColor::Dim), content_width);
+}
+
/// The bash tool's output byte budget, used when the spill carries no
/// `maxBytes`.
pub const DEFAULT_MAX_BYTES: usize = 50 * 1024;
diff --git a/crates/pa-tui/src/view/tests.rs b/crates/pa-tui/src/view/tests.rs
index 59f193835d..7b340b40b4 100644
--- a/crates/pa-tui/src/view/tests.rs
+++ b/crates/pa-tui/src/view/tests.rs
@@ -1625,6 +1625,9 @@ fn a_landing_result_with_receipts_settles_the_card() {
}),
is_error: false,
});
+ // The final result settles the call (the pipeline stamps
+ // `ended_at` with every settle path): the live timer stops.
+ card.ended_at = Some(std::time::Instant::now());
}
view.mark_entry_stale(index);
let text = transcript_text(&mut view, 80);
diff --git a/crates/pa-tui/tests/tool_card_live_timer_headless.rs b/crates/pa-tui/tests/tool_card_live_timer_headless.rs
new file mode 100644
index 0000000000..42e6382a26
--- /dev/null
+++ b/crates/pa-tui/tests/tool_card_live_timer_headless.rs
@@ -0,0 +1,873 @@
+//! Headless e2e for the live tool-call timer (operator feature
+//! 2026-10-03): while a tool call executes with no stream events, its card
+//! shows the elapsed time ticking up, and once the result lands the
+//! ticking stops and the card shows the final static duration — the
+//! exact `Took` row the settled card always rendered. The red first:
+//! a running card showed no duration until the first partial result
+//! arrived, so a quiet tool run (no output) left the card with no
+//! timing at all.
+// - the mock's serve loop is one flat request table (one arm per
+// command); splitting it would add indirection without changing the
+// flow.
+#![allow(clippy::too_many_lines)]
+#![cfg(unix)]
+
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+
+use pa_tui::interactive::{
+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,
+ SessionSelection, UiMode,
+};
+use serde_json::{json, Value};
+
+/// One mock daemon: serves one client connection, answering the attach
+/// with a mid-turn snapshot and then running one quiet tool call — a
+/// `tool_execution_start` frame, a silent window, the final
+/// `tool_execution_end`, and `turn_end`.
+struct MockSupervisor {
+ listener: UnixListener,
+ /// The scripted frame sequence the mock daemon streams after the
+ /// attach (one scenario per test).
+ scenario: Scenario,
+}
+
+/// The attach-then-stream scenarios: which frames the mock writes decides
+/// which settle path the test drives.
+#[derive(Clone, Copy, PartialEq)]
+enum Scenario {
+ /// The quiet bash run: start, silent window, end, `turn_end`.
+ Quiet,
+ /// A streamed call never receives its execution-start frame before turn end.
+ Queued,
+ /// A completed call is repeated by a later streaming assistant update.
+ CompletedRestream,
+ /// The bash straggler: the end frame is dropped, so the turn's settle
+ /// freezes the card; then a late end frame and a late start (the
+ /// retick probe) must both land on nothing.
+ Straggler,
+ /// The `python_repl` straggler: same shape with the ipython shell, so
+ /// the summary's duration slot freezes instead of vanishing.
+ IpythonStraggler,
+ /// The lost turn: turn one's call never ends and its `turn_end`
+ /// never lands; turn two's `turn_start` settles turn one's leftover
+ /// card (partial preserved, stale timer stopped) and runs to its
+ /// own settle.
+ LostTurn,
+}
+
+impl MockSupervisor {
+ fn bind(socket: &std::path::Path, scenario: Scenario) -> Self {
+ MockSupervisor {
+ listener: UnixListener::bind(socket).expect("bind mock socket"),
+ scenario,
+ }
+ }
+
+ /// Serve one client connection until it goes quiet (bounded, so the
+ /// plan teardown join always finishes).
+ fn serve(self) {
+ self.listener
+ .set_nonblocking(true)
+ .expect("nonblocking mock listener");
+ let idle_window = std::time::Duration::from_millis(1500);
+ let idle_until = std::time::Instant::now() + idle_window;
+ let (stream, _) = loop {
+ match self.listener.accept() {
+ Ok(accepted) => break accepted,
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ if std::time::Instant::now() >= idle_until {
+ return;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ Err(_) => return,
+ }
+ };
+ // macOS inherits O_NONBLOCK from the listener on accept; the request loop blocks.
+ stream.set_nonblocking(false).expect("blocking mock stream");
+ let mut writer = stream.try_clone().expect("clone mock socket");
+ let mut reader = BufReader::new(stream);
+
+ let hello = json!({
+ "type": "daemon_hello",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "serverCapabilities": [],
+ "clientId": "mock",
+ });
+ write_json(&mut writer, &hello);
+
+ let mut line = String::new();
+ loop {
+ line.clear();
+ match reader.read_line(&mut line) {
+ Ok(0) | Err(_) => break,
+ Ok(_) => {}
+ }
+ let Ok(envelope) = serde_json::from_str::<Value>(line.trim()) else {
+ continue;
+ };
+ let id = envelope.get("id").and_then(Value::as_str).unwrap_or("");
+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);
+ let command_type = command
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ match command_type.as_str() {
+ "create" => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": "create",
+ "success": true,
+ "data": {
+ "activeSessionId": "s1",
+ "id": "s1",
+ "sessionId": "sess-1",
+ "sessionFile": "/tmp/sess-1.jsonl",
+ },
+ }),
+ );
+ }
+ "attach" => {
+ write_json(&mut writer, &attach_data(id));
+ // The scripted stream happens from a side thread
+ // (the reader loop keeps answering the client's
+ // post-attach requests); the events queue on the
+ // socket behind the attach response, so the client
+ // consumes them in order (the same shape as the
+ // quiet-tick stream mock) — no readiness sleep to
+ // race.
+ let scenario = self.scenario;
+ let mut w = writer.try_clone().expect("clone event socket");
+ std::thread::spawn(move || {
+ match scenario {
+ Scenario::Quiet => {
+ tool_start(
+ &mut w,
+ "call_1",
+ "bash",
+ &json!({ "command": "sleep 1" }),
+ );
+ std::thread::sleep(std::time::Duration::from_millis(TOOL_RUN_MS));
+ tool_end(&mut w, "call_1", "bash", "ok");
+ event(&mut w, &json!({ "type": "turn_end" }));
+ }
+ Scenario::Queued => {
+ event(
+ &mut w,
+ &json!({
+ "type": "message_update",
+ "message": {
+ "role": "assistant",
+ "content": [{
+ "type": "toolCall",
+ "id": "call_queued",
+ "name": "bash",
+ "arguments": { "command": "echo never started" },
+ }],
+ },
+ }),
+ );
+ event(&mut w, &json!({ "type": "turn_end" }));
+ drain_barrier(&mut w);
+ }
+ Scenario::CompletedRestream => {
+ tool_start(
+ &mut w,
+ "call_complete",
+ "bash",
+ &json!({ "command": "echo finished call output" }),
+ );
+ tool_end(&mut w, "call_complete", "bash", "finished call output");
+ event(
+ &mut w,
+ &json!({
+ "type": "message_update",
+ "message": {
+ "role": "assistant",
+ "content": [{
+ "type": "toolCall",
+ "id": "call_complete",
+ "name": "bash",
+ "arguments": { "command": "echo finished call output" },
+ }],
+ },
+ }),
+ );
+ event(&mut w, &json!({ "type": "turn_end" }));
+ drain_barrier(&mut w);
+ }
+ Scenario::Straggler => {
+ tool_start(
+ &mut w,
+ "call_1",
+ "bash",
+ &json!({ "command": "sleep 1" }),
+ );
+ std::thread::sleep(std::time::Duration::from_millis(TOOL_RUN_MS));
+ // The end frame is dropped: the turn
+ // settles with a still-running card.
+ event(&mut w, &json!({ "type": "turn_end" }));
+ // The probes, after the turn: a late end
+ // (the resurrection probe — the aborted
+ // stamp must keep it landing on nothing)
+ // and a late start (the retick probe —
+ // outside a live turn it must land on
+ // nothing too, no fresh ticking card).
+ std::thread::sleep(std::time::Duration::from_millis(250));
+ tool_end(&mut w, "call_1", "bash", "late frame resurrection");
+ tool_start(
+ &mut w,
+ "call_1",
+ "bash",
+ &json!({ "command": "sleep 2" }),
+ );
+ drain_barrier(&mut w);
+ }
+ Scenario::IpythonStraggler => {
+ tool_start(
+ &mut w,
+ "call_1",
+ "ipython",
+ &json!({ "code": "print('x')" }),
+ );
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ // The cell streams a partial before the turn
+ // cuts it off: the settle keeps the streamed
+ // output but must still close the card as an
+ // ERROR — an unfinished cell never renders
+ // the success checkmark.
+ event(
+ &mut w,
+ &json!({
+ "type": "tool_execution_update",
+ "toolCallId": "call_1",
+ "partialResult": {
+ "content": [{
+ "type": "text",
+ "text": "streamed cell output",
+ }],
+ },
+ }),
+ );
+ std::thread::sleep(std::time::Duration::from_millis(TOOL_RUN_MS));
+ event(&mut w, &json!({ "type": "turn_end" }));
+ drain_barrier(&mut w);
+ }
+ Scenario::LostTurn => {
+ // Turn one (the attach's streaming turn):
+ // a start and a streamed partial, but the
+ // end frame AND the turn's own `turn_end`
+ // never land — the turn is lost.
+ tool_start(
+ &mut w,
+ "call_1",
+ "bash",
+ &json!({ "command": "sleep 1" }),
+ );
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ event(
+ &mut w,
+ &json!({
+ "type": "tool_execution_update",
+ "toolCallId": "call_1",
+ "partialResult": {
+ "content": [{
+ "type": "text",
+ "text": "turn one partial output",
+ }],
+ },
+ }),
+ );
+ // Turn two (its own call id) runs to its
+ // own settle; the pending-scoped sweep
+ // must leave turn one's card alone.
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ event(&mut w, &json!({ "type": "turn_start" }));
+ tool_start(
+ &mut w,
+ "call_2",
+ "bash",
+ &json!({ "command": "sleep 2" }),
+ );
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ tool_end(&mut w, "call_2", "bash", "turn two output");
+ event(&mut w, &json!({ "type": "turn_end" }));
+ drain_barrier(&mut w);
+ }
+ }
+ });
+ }
+ _ => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": command_type,
+ "success": true,
+ "data": {},
+ }),
+ );
+ }
+ }
+ }
+ }
+}
+
+fn write_json(writer: &mut UnixStream, value: &Value) {
+ let mut line = serde_json::to_string(value).expect("serialize mock frame");
+ line.push('\n');
+ writer.write_all(line.as_bytes()).expect("write mock frame");
+ writer.flush().expect("flush mock frame");
+}
+
+/// One session event frame on the mock socket.
+fn event(writer: &mut UnixStream, payload: &Value) {
+ write_json(
+ writer,
+ &json!({
+ "type": "session_event",
+ "activeSessionId": "s1",
+ "event": payload,
+ }),
+ );
+}
+
+/// The `tool_execution_start` frame for one call id.
+fn tool_start(writer: &mut UnixStream, call_id: &str, tool: &str, args: &Value) {
+ event(
+ writer,
+ &json!({
+ "type": "tool_execution_start",
+ "toolCallId": call_id,
+ "toolName": tool,
+ "args": args,
+ }),
+ );
+}
+
+/// The `tool_execution_end` frame for one call id.
+fn tool_end(writer: &mut UnixStream, call_id: &str, tool: &str, text: &str) {
+ event(
+ writer,
+ &json!({
+ "type": "tool_execution_end",
+ "toolCallId": call_id,
+ "toolName": tool,
+ "result": {
+ "content": [{ "type": "text", "text": text }],
+ "isError": false,
+ },
+ }),
+ );
+}
+
+/// The drain barrier: a visible user row whose render is the observable
+/// proof the frames written just before it on the same socket were
+/// processed first, so the tests' negative assertions cannot pass
+/// vacuously when the plan finishes early.
+fn drain_barrier(writer: &mut UnixStream) {
+ event(
+ writer,
+ &json!({
+ "type": "message_start",
+ "message": {
+ "role": "user",
+ "content": [{ "type": "text", "text": "late-probe-drained" }],
+ },
+ }),
+ );
+}
+
+/// The attach result: a streaming mid-turn snapshot whose prompt landed
+/// just now, so the working loader (and the turn) is active when the
+/// tool call starts.
+fn attach_data(id: &str) -> Value {
+ let now_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("clock after the epoch")
+ .as_millis();
+ json!({
+ "type": "response",
+ "id": id,
+ "command": "attach",
+ "success": true,
+ "data": {
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "activeSessionId": "s1",
+ "snapshot": {
+ "activeSessionId": "s1",
+ "summary": { "id": "s1", "cwd": "/tmp" },
+ "state": {
+ "activeSessionId": "s1",
+ "cwd": "/tmp",
+ "sessionId": "sess-1",
+ "sessionName": "live timer session",
+ "model": null,
+ "isStreaming": true,
+ "isCompacting": false,
+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
+ },
+ "messages": [
+ {
+ "role": "user",
+ "content": [{ "type": "text", "text": "run the sweep" }],
+ "timestamp": now_ms,
+ },
+ ],
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ },
+ "client": { "id": "mock", "capabilities": [] },
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ },
+ })
+}
+
+fn options(socket: PathBuf) -> InteractiveOptions {
+ InteractiveOptions {
+ models: None,
+ socket_path: socket,
+ cwd: PathBuf::from("/tmp"),
+ 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::New,
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: false,
+ 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,
+ }
+}
+
+/// How long the mock's tool call runs with no stream events.
+const TOOL_RUN_MS: u64 = 1200;
+
+/// The duration one card row paints, in tenths of a second: the `X.Y`
+/// of an `Elapsed X.Ys` (or `Took X.Ys`) row.
+fn row_tenths(frame: &str, label: &str) -> Option<u64> {
+ let line = frame.lines().find(|line| line.contains(label))?;
+ let value = line.split(label).nth(1)?;
+ let value = value.trim_end().trim_end_matches('s').trim();
+ let (whole, frac) = value.split_once('.')?;
+ let tenths = u64::from(frac.chars().next()?.to_digit(10)?);
+ Some(whole.parse::<u64>().ok()? * 10 + tenths)
+}
+
+#[test]
+fn a_running_tool_card_ticks_and_settles_to_the_final_duration() {
+ // The ambient TMUX variable adds a startup notice to the
+ // transcript; scrub it so the run is the same inside tmux and out.
+ 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, Scenario::Quiet);
+ let handle = std::thread::spawn(move || supervisor.serve());
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ // No input during the run: the loader's own phase wake repaints the
+ // running card, and the live timer rides those paints. The plan holds
+ // on observable conditions, not wall-clock guesses: the first live
+ // tick, then the settled card's static row.
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::WaitRender {
+ needle: "Elapsed ".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitRender {
+ needle: "Took ".to_string(),
+ timeout_ms: 5000,
+ },
+ ],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+
+ // The ticking phase: every frame that shows the running card paints
+ // its elapsed, and the painted values advance with the repaints.
+ let ticks: Vec<u64> = outcome
+ .frames
+ .iter()
+ .filter_map(|frame| row_tenths(frame, "Elapsed "))
+ .collect();
+ assert!(
+ ticks.len() >= 3,
+ "the quiet tool run repaints the card with a live duration:\n{}",
+ outcome.frames.join("\n===\n")
+ );
+ assert!(
+ ticks.windows(2).all(|pair| pair[0] <= pair[1]),
+ "the live duration only ticks up: {ticks:?}"
+ );
+ let distinct = ticks.iter().collect::<std::collections::HashSet<_>>();
+ assert!(
+ distinct.len() >= 3,
+ "the live duration advances through the run: {ticks:?}"
+ );
+
+ // The settle: the final result lands and the ticking stops — the
+ // settled card carries the static `Took` row and never an `Elapsed`
+ // row again.
+ let settle = outcome
+ .frames
+ .iter()
+ .position(|frame| row_tenths(frame, "Took ").is_some())
+ .expect("the settled card paints its final duration");
+ let took = row_tenths(&outcome.frames[settle], "Took ").expect("the took row parses");
+ assert!(
+ took >= ticks.iter().copied().max().unwrap_or_default(),
+ "the final duration covers the whole run (tenths of a second): \
+ took {took}, live max {:?}",
+ ticks.iter().copied().max()
+ );
+ let settled_tickers = outcome.frames[settle..]
+ .iter()
+ .filter(|frame| frame.contains("Elapsed "))
+ .count();
+ assert_eq!(
+ settled_tickers,
+ 0,
+ "the settled card never ticks again:\n{}",
+ outcome.frames[settle..].join("\n===\n")
+ );
+}
+
+/// The straggler: a tool call whose end frame never lands still gets its
+/// timer frozen at the turn's settle — the `turn_end` sweep settles the card
+/// the way the failed-frame sweep does (a terminal error result, the
+/// settle instant, the aborted stamp): the frozen `Took` row renders, the
+/// panel header is terminal (no running spinner), no later paint ticks
+/// `Elapsed`, and the late end frame lands on nothing.
+#[test]
+fn a_straggler_tool_card_freezes_at_the_turn_settle() {
+ 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, Scenario::Straggler);
+ let handle = std::thread::spawn(move || supervisor.serve());
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::WaitRender {
+ needle: "Elapsed ".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitRender {
+ needle: "Took ".to_string(),
+ timeout_ms: 5000,
+ },
+ // The drain barrier: the late end frame is followed on the
+ // same socket by the marker render, so waiting for the marker
+ // proves the late frame was processed first — the
+ // no-resurrection assertion cannot pass vacuously.
+ HeadlessStep::WaitRender {
+ needle: "late-probe-drained".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitIdle { timeout_ms: 5000 },
+ ],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let settle = outcome
+ .frames
+ .iter()
+ .position(|frame| frame.contains("Took "))
+ .expect("the straggler's timer froze at the turn settle");
+ // A timed-out WaitRender only notes; assert the barrier rendered,
+ // so the negatives below are read only after the late frame
+ // demonstrably drained.
+ assert!(
+ outcome.frames[settle..]
+ .iter()
+ .any(|frame| frame.contains("late-probe-drained")),
+ "the drain barrier rendered:\n{}",
+ outcome.frames[settle..].join("\n===\n")
+ );
+ let rendered = outcome.frames[settle..].join("\n===\n");
+ assert!(
+ !rendered.contains("Elapsed "),
+ "the frozen straggler never ticks again:
+{rendered}"
+ );
+ assert!(
+ !rendered.contains("running"),
+ "the settled straggler carries a terminal header, not a running spinner:
+{rendered}"
+ );
+ assert!(
+ !rendered.contains("resurrection"),
+ "the late end frame lands on the aborted straggler:
+{rendered}"
+ );
+}
+
+/// The lost turn: turn one's call never ends and its `turn_end` never
+/// lands. Turn two's `turn_start` is the definitive end of turn one: its
+/// leftover pending card settles there — the streamed partial output
+/// preserved, the card terminal, its stale timer and header stopped from
+/// ticking into turn two's paints — while the pending-scoped turn-end
+/// sweep never stamps a card the turn did not track.
+#[test]
+fn a_lost_turns_card_settles_when_the_next_turn_starts() {
+ 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, Scenario::LostTurn);
+ let handle = std::thread::spawn(move || supervisor.serve());
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::WaitRender {
+ needle: "turn one partial output".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitRender {
+ needle: "Took ".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitRender {
+ needle: "late-probe-drained".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitIdle { timeout_ms: 5000 },
+ ],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ // The barrier rendered: the assertions below are read only after turn
+ // two's settle demonstrably drained — both calls are terminal by then,
+ // so no card may tick or spin past it.
+ let barrier = outcome
+ .frames
+ .iter()
+ .position(|frame| frame.contains("late-probe-drained"))
+ .expect("the drain barrier rendered");
+ let settled = outcome.frames[barrier..].join("\n===\n");
+ assert!(
+ settled.contains("turn one partial output"),
+ "the lost turn's streamed output survives the settle:\n{settled}"
+ );
+ assert!(
+ !settled.contains("Elapsed "),
+ "the lost turn's stale timer never ticks past the new turn's settle:\n{settled}"
+ );
+ assert!(
+ !settled.contains("running"),
+ "the lost turn's header is terminal, not a running spinner:\n{settled}"
+ );
+ assert!(
+ settled.contains("turn two output"),
+ "turn two's own call settles normally:\n{settled}"
+ );
+}
+
+/// The `python_repl` straggler: the summary's duration slot ticks while the
+/// cell runs, and at the settle it FREEZES on the run's honest duration
+/// (from the card timestamps) instead of vanishing — the
+/// bash panel keeps its static `Took` row from the same timestamps, and
+/// the ipython summary keeps its duration segment.
+#[test]
+fn a_python_repl_straggler_freezes_its_duration_slot() {
+ 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, Scenario::IpythonStraggler);
+ let handle = std::thread::spawn(move || supervisor.serve());
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::WaitRender {
+ needle: "\u{2191} 1 lines".to_string(),
+ timeout_ms: 5000,
+ },
+ // The settle marker: the terminal error status replaces the
+ // working spinner.
+ HeadlessStep::WaitRender {
+ needle: "\u{2717}".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitRender {
+ needle: "late-probe-drained".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitIdle { timeout_ms: 5000 },
+ ],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let settle = outcome
+ .frames
+ .iter()
+ .position(|frame| frame.contains("\u{2717}"))
+ .expect("the settled cell renders the error marker");
+ assert!(
+ outcome.frames[settle..]
+ .iter()
+ .any(|frame| frame.contains("late-probe-drained")),
+ "the drain barrier rendered:\n{}",
+ outcome.frames[settle..].join("\n===")
+ );
+ // The frozen duration: the summary's last segment on the settled
+ // frame parses as the run's duration from the card timestamps.
+ let settled = &outcome.frames[settle..];
+ let with_duration = settled
+ .iter()
+ .filter_map(|frame| {
+ frame
+ .lines()
+ .find(|line| line.contains("\u{2717} python"))
+ .map(std::string::ToString::to_string)
+ })
+ .collect::<Vec<_>>();
+ assert!(
+ !with_duration.is_empty(),
+ "the settled cell's summary renders:\n{}",
+ settled.join("\n===")
+ );
+ let summary = with_duration[0].clone();
+ let duration_part = summary
+ .rsplit(" \u{00b7} ")
+ .next()
+ .unwrap_or_default()
+ .trim()
+ .to_string();
+ assert!(
+ (duration_part.ends_with('s')
+ && duration_part.trim_end_matches('s').parse::<f64>().is_ok())
+ || (duration_part.ends_with("ms")
+ && duration_part.trim_end_matches("ms").parse::<f64>().is_ok()),
+ "the summary's duration slot freezes on the run's duration, not vanishes:\n{summary}"
+ );
+}
+
+/// A queued streamed call must settle even when execution never started.
+#[test]
+fn a_queued_tool_card_settles_at_the_turn_boundary() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor::bind(&socket, Scenario::Queued);
+ let handle = std::thread::spawn(move || supervisor.serve());
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::WaitRender {
+ needle: "late-probe-drained".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitIdle { timeout_ms: 5000 },
+ ],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let settled = outcome.frames.last().expect("the drained frame rendered");
+ assert!(
+ settled.contains("the turn ended before this call returned"),
+ "the queued call must settle: {settled}"
+ );
+ assert!(
+ !settled.contains("queued"),
+ "the queued state survived: {settled}"
+ );
+}
+
+/// Later assistant updates repeat completed tool IDs; turn end must keep their success.
+#[test]
+fn a_completed_tool_repeated_by_a_streaming_update_stays_successful() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor::bind(&socket, Scenario::CompletedRestream);
+ let handle = std::thread::spawn(move || supervisor.serve());
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps: vec![
+ HeadlessStep::WaitRender {
+ needle: "late-probe-drained".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitIdle { timeout_ms: 5000 },
+ ],
+ width: 100,
+ height: 40,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let settled = outcome.frames.last().expect("the drained frame rendered");
+ assert!(
+ settled.contains("finished call output"),
+ "output lost: {settled}"
+ );
+ assert!(
+ settled.contains("bash \u{00b7} done"),
+ "completed call lost its success: {settled}"
+ );
+}