Skip to content

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

Rust

TUI attach ships the transcript tail; older history backfills after first paint (#3431)

Sebastian Müller9d6ca9a4e3cf
diff --git a/Cargo.lock b/Cargo.lock
index a8a8f9f814..fee0ba26b3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1636,6 +1636,7 @@ dependencies = [
"serde_json",
"tempfile",
"tokio",
+ "tokio-util",
"unicode-properties",
"unicode-segmentation",
"unicode-width 0.2.0",
diff --git a/crates/pa-cli/tests/exit_backfill_pty_e2e.rs b/crates/pa-cli/tests/exit_backfill_pty_e2e.rs
new file mode 100644
index 0000000000..e0b6de2bc2
--- /dev/null
+++ b/crates/pa-cli/tests/exit_backfill_pty_e2e.rs
@@ -0,0 +1,533 @@
+// large_futures: stack-resident futures on hot paths by design.
+// too_many_lines: style gate, not correctness. Casts: 64-bit targets;
+// narrowing sits at bounded OS/protocol boundaries.
+#![allow(
+ clippy::large_futures,
+ clippy::too_many_lines,
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap,
+ clippy::cast_sign_loss,
+ clippy::cast_precision_loss
+)]
+
+//! Real-pty e2e for the exit/backfill contract: leaving the run must
+//! flush the history already loaded and never wait for an unfinished
+//! older-history page — the run's own 30s request timeout must not hold
+//! the exit open behind a held `get_messages`.
+
+#![cfg(unix)]
+
+use std::io::{BufRead, Read, Write};
+use std::os::fd::{AsRawFd, OwnedFd};
+use std::os::unix::process::CommandExt;
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use nix::fcntl::{fcntl, FcntlArg::F_SETFL, OFlag};
+use nix::pty::{openpty, Winsize};
+use serde_json::{json, Value};
+
+use pa_tui::interactive::{
+ run_interactive, InteractiveOptions, ModelSelection, SessionSelection, UiMode,
+};
+
+/// Answering like a kitty terminal keeps the probe's bounded wait from adding its full budget.
+const KITTY_QUERY: &[u8] = b"\x1b[?u";
+const KITTY_ANSWER: &[u8] = b"\x1b[?7u\x1b[?62;c";
+/// The alt-screen leave the exit flush begins with.
+const ALT_SCREEN_LEAVE: &[u8] = b"\x1b[?1049l";
+/// The watchdog's user-visible line; the exit must go through its own path.
+const STALL_MSG: &[u8] = b"shutdown stalled; forced exit.";
+const CHILD_SOCKET_ENV: &str = "PA_EXIT_BACKFILL_CHILD_SOCKET";
+/// The exit bound: far below the held page's 30s client timeout, generous
+/// above a clean detach-and-flush exit.
+const EXIT_BOUND: Duration = Duration::from_secs(5);
+/// The windowed attach claims this many older messages exist before the tail.
+const HISTORY_BEFORE: u64 = 40;
+/// The tail the snapshot carries: rows 0 and 8 are user rows (contiguous
+/// needles; assistant rows carry SGR spans).
+const TAIL_MESSAGES: usize = 9;
+const FIRST_ROW: &[u8] = b"tail row 0";
+const LAST_ROW: &[u8] = b"tail row 8";
+
+/// The child half: runs the real interactive loop against the parent's
+/// mock supervisor; a plain `cargo test` run passes trivially.
+#[test]
+fn exit_backfill_child_mode() {
+ let Ok(socket) = std::env::var(CHILD_SOCKET_ENV) else {
+ return;
+ };
+ let options = child_options(PathBuf::from(socket));
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ runtime.block_on(async move {
+ let outcome = run_interactive(options, UiMode::Terminal)
+ .await
+ .expect("the chat surface ran");
+ // The composition root's exit tail (pa-cli `interactive_mode`),
+ // replicated because the child drives the surface directly.
+ if let Some(SessionSelection::Attach(id)) = outcome.selection_request {
+ println!("backfill handoff selected {id}");
+ }
+ if let Some(hint) = outcome.resume_hint {
+ println!("\x1b[2m{hint}\x1b[22m");
+ }
+ pa_tui::exit_guard::note_exit_progress();
+ std::thread::sleep(Duration::from_millis(300));
+ });
+}
+
+/// The pty harnesses serialize: concurrent byte-level waits flake on the shared test CPUs.
+static HARNESS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+#[test]
+fn exit_does_not_wait_for_a_pending_backfill_page() {
+ leave_with_pending_backfill(b"/exit\r");
+}
+
+#[test]
+fn resume_does_not_wait_for_a_pending_backfill_page() {
+ leave_with_pending_backfill(b"/resume s2\r");
+}
+
+fn leave_with_pending_backfill(gesture: &[u8]) {
+ let _lock = match HARNESS_LOCK.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ let held = Arc::new(AtomicUsize::new(0));
+ let mut harness = ExitBackfillHarness::start(Arc::clone(&held));
+
+ harness.wait_from_start(KITTY_QUERY, "the kitty capability query");
+ harness.write(KITTY_ANSWER);
+ harness.wait_from_start(LAST_ROW, "the attach tail rendered");
+ harness.settle();
+
+ // The windowed attach really armed an older-history page request, and it
+ // is still held: the request is pending exactly where the bug waits.
+ let held_at_exit = held.load(Ordering::SeqCst);
+ assert!(
+ held_at_exit >= 1,
+ "the windowed attach must have started an older-history page request before the exit"
+ );
+
+ // Both gestures leave through the session-request route: no Ctrl+C
+ // pair, so no force-quit watchdog can mask a hang.
+ let keys_sent = Instant::now();
+ harness.write(gesture);
+
+ let exit_code = harness.wait_child_exit(EXIT_BOUND);
+ let exit_wall = keys_sent.elapsed();
+ assert_eq!(
+ exit_code,
+ Some(0),
+ "the exit must beat the held page's 30s request timeout (wall {exit_wall:?}, \
+ {held_at_exit} page request(s) held)"
+ );
+
+ harness.settle();
+ let output = harness.output();
+ if gesture == b"/resume s2\r" {
+ assert!(
+ find_subsequence(&output, b"backfill handoff selected s2").is_some(),
+ "the run must return the requested session to the composition root"
+ );
+ }
+ assert!(
+ find_subsequence(&output, STALL_MSG).is_none(),
+ "the exit went through its own path, never the watchdog's"
+ );
+ // The flush carried the loaded tail rows: their LAST copies follow the
+ // alt-screen leave (the startup viewport painted the first copies).
+ let leave_at =
+ find_subsequence(&output, ALT_SCREEN_LEAVE).expect("the exit left the alternate screen");
+ let first_row_at =
+ find_subsequence_last(&output, FIRST_ROW).expect("the flush wrote the tail's first row");
+ let last_row_at =
+ find_subsequence_last(&output, LAST_ROW).expect("the flush wrote the tail's last row");
+ assert!(
+ leave_at < first_row_at && first_row_at < last_row_at,
+ "the flushed tail rows follow the alt-screen leave (output {}B, leave_at {leave_at}, \
+ first_row_at {first_row_at}, last_row_at {last_row_at})",
+ output.len()
+ );
+}
+
+/// One attached session behind a mock supervisor socket: the attach is
+/// windowed (`historyBefore` > 0), and the older-history page request is
+/// held forever; everything else answers promptly.
+struct ExitBackfillHarness {
+ child: Child,
+ _server: std::thread::JoinHandle<()>,
+ master: PtyReader,
+}
+
+impl ExitBackfillHarness {
+ fn start(held: Arc<AtomicUsize>) -> ExitBackfillHarness {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor::bind(&socket, held);
+ let server = std::thread::spawn(move || supervisor.serve());
+
+ let pty = openpty(
+ Some(&Winsize {
+ ws_row: 40,
+ ws_col: 120,
+ ws_xpixel: 0,
+ ws_ypixel: 0,
+ }),
+ None,
+ )
+ .expect("open pty");
+
+ let child = spawn_child(&socket, &pty.slave);
+ // The child needs the socket for its lifetime.
+ std::mem::forget(dir);
+ ExitBackfillHarness {
+ child,
+ _server: server,
+ master: PtyReader::new(pty.master),
+ }
+ }
+
+ fn write(&mut self, payload: &[u8]) {
+ self.master.write(payload);
+ }
+
+ fn wait_from_start(&mut self, needle: &[u8], what: &str) {
+ self.master.wait_from(0, needle, what);
+ }
+
+ /// Drain until the pty goes quiet (the transcript never paints outside
+ /// the viewport, so this is fast).
+ fn settle(&mut self) {
+ self.master.drain_until_quiet(20);
+ }
+
+ fn output(&self) -> Vec<u8> {
+ self.master.output.clone()
+ }
+
+ /// Poll for the child's exit while draining the master, bounded by
+ /// `timeout`; `None` when the child is still alive at the bound.
+ fn wait_child_exit(&mut self, timeout: Duration) -> Option<i32> {
+ let deadline = Instant::now() + timeout;
+ loop {
+ if let Some(status) = self.child.try_wait().ok().flatten() {
+ return status.code();
+ }
+ let mut buffer = [0u8; 8192];
+ match self.master.file.read(&mut buffer) {
+ Ok(0) | Err(_) => {}
+ Ok(n) => self.master.output.extend_from_slice(&buffer[..n]),
+ }
+ if Instant::now() > deadline {
+ return None;
+ }
+ std::thread::sleep(Duration::from_millis(25));
+ }
+ }
+}
+
+impl Drop for ExitBackfillHarness {
+ fn drop(&mut self) {
+ // A panicking wait must never leak the pty child (it owns its
+ // session's controlling terminal).
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// Non-blocking reader over the pty master, collecting the child's bytes.
+struct PtyReader {
+ file: std::fs::File,
+ output: Vec<u8>,
+}
+
+impl PtyReader {
+ fn new(master: OwnedFd) -> PtyReader {
+ let fd = master.as_raw_fd();
+ fcntl(fd, F_SETFL(OFlag::O_NONBLOCK)).expect("pty master non-blocking");
+ PtyReader {
+ file: master.into(),
+ output: Vec::new(),
+ }
+ }
+
+ fn write(&mut self, payload: &[u8]) {
+ self.file.write_all(payload).expect("write to the pty");
+ }
+
+ fn drain_until_quiet(&mut self, quiet_polls: usize) {
+ let mut quiet = 0;
+ while quiet < quiet_polls {
+ let mut buffer = [0u8; 8192];
+ match self.file.read(&mut buffer) {
+ Ok(0) | Err(_) => quiet += 1,
+ Ok(n) => {
+ self.output.extend_from_slice(&buffer[..n]);
+ quiet = 0;
+ }
+ }
+ std::thread::sleep(Duration::from_millis(25));
+ }
+ }
+
+ fn wait_from(&mut self, mark: usize, needle: &[u8], what: &str) {
+ let deadline = Instant::now() + Duration::from_secs(30);
+ loop {
+ if find_subsequence(&self.output[mark..], needle).is_some() {
+ return;
+ }
+ let mut buffer = [0u8; 8192];
+ match self.file.read(&mut buffer) {
+ Ok(0) | Err(_) => {}
+ Ok(n) => self.output.extend_from_slice(&buffer[..n]),
+ }
+ if Instant::now() > deadline {
+ let text = String::from_utf8_lossy(&self.output[mark..]);
+ panic!(
+ "timeout waiting for {what} (needle {needle:?}); pty tail since mark:\n{text}"
+ );
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+}
+
+fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() {
+ return None;
+ }
+ haystack
+ .windows(needle.len())
+ .position(|window| window == needle)
+}
+
+fn find_subsequence_last(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() {
+ return None;
+ }
+ haystack
+ .windows(needle.len())
+ .rev()
+ .position(|window| window == needle)
+ .map(|at| haystack.len() - at - needle.len())
+}
+
+/// A child of this very binary, with the pty slave as its terminal AND
+/// controlling terminal (`setsid` + `TIOCSCTTY`): crossterm's raw-mode and
+/// event reads go through `/dev/tty`.
+fn spawn_child(socket: &Path, slave: &OwnedFd) -> Child {
+ fn claim_controlling_tty(fd: i32) -> std::io::Result<()> {
+ nix::unistd::setsid()?;
+ let rc = unsafe { libc::ioctl(fd, libc::TIOCSCTTY as libc::c_ulong, 0) };
+ if rc < 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(())
+ }
+ let slave_fd = slave.as_raw_fd();
+ let mut command = Command::new(std::env::current_exe().expect("test binary"));
+ command
+ .arg("--exact")
+ .arg("exit_backfill_child_mode")
+ // The parent observes the child's handoff result through the PTY.
+ .arg("--nocapture")
+ .env(CHILD_SOCKET_ENV, socket)
+ .env_remove("TMUX")
+ .stdin(slave_as_stdio(slave))
+ .stdout(slave_as_stdio(slave))
+ .stderr(slave_as_stdio(slave));
+ // SAFETY: the pre_exec hook is the supported std seam for
+ // session/terminal setup; it runs post-fork pre-exec in the child only and cannot allocate.
+ unsafe {
+ command.pre_exec(move || claim_controlling_tty(slave_fd));
+ }
+ command.spawn().expect("spawn pty child")
+}
+
+fn slave_as_stdio(slave: &OwnedFd) -> Stdio {
+ slave.try_clone().expect("clone pty slave").into()
+}
+
+fn child_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,
+ // A direct open into an existing session: the attach drives the
+ // windowed snapshot.
+ session: SessionSelection::Attach("s1".to_string()),
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: true,
+ theme: "prime".to_string(),
+ code_block_indent: " ".to_string(),
+ tree_filter_mode: String::new(),
+ branch_summary_skip_prompt: false,
+ version: "0.0.0".to_string(),
+ onboarding: None,
+ telemetry_disabled: None,
+ client_auth: None,
+ traces: None,
+ provider_auth: None,
+ update_commands: None,
+ telemetry: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ session_rlm_depth: None,
+ prompt_stash: std::sync::Arc::default(),
+ session_has_children: false,
+ restore_dock_focus: false,
+ client_settings: None,
+ }
+}
+
+/// One attached session behind a mock supervisor socket: the attach carries
+/// a windowed snapshot, and the older-history page request (`get_messages`
+/// with `before`) is held forever; every other request answers promptly.
+struct MockSupervisor {
+ listener: std::os::unix::net::UnixListener,
+ held: Arc<AtomicUsize>,
+}
+
+impl MockSupervisor {
+ fn bind(socket: &Path, held: Arc<AtomicUsize>) -> Self {
+ MockSupervisor {
+ listener: std::os::unix::net::UnixListener::bind(socket).expect("bind mock socket"),
+ held,
+ }
+ }
+
+ fn serve(self) {
+ for stream in self.listener.incoming() {
+ match stream {
+ Ok(stream) => Self::serve_connection(stream, &self.held),
+ Err(_) => return,
+ }
+ }
+ }
+
+ fn serve_connection(stream: std::os::unix::net::UnixStream, held: &Arc<AtomicUsize>) {
+ let write_stream = stream.try_clone().expect("clone mock socket");
+ let mut writer = write_stream;
+ let mut reader = std::io::BufReader::new(stream);
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "daemon_hello",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "serverCapabilities": [],
+ "clientId": "mock",
+ }),
+ );
+ 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() {
+ "attach" => {
+ write_json(&mut writer, &attach_data(id));
+ }
+ // The older-history page: counted and held — the run loop
+ // starts it from the windowed attach's `historyBefore`, and
+ // the exit must not wait for it.
+ "get_messages" if command.get("before").is_some() => {
+ held.fetch_add(1, Ordering::SeqCst);
+ }
+ _ => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": command_type,
+ "success": true,
+ "data": {},
+ }),
+ );
+ }
+ }
+ }
+ }
+}
+
+fn write_json(writer: &mut std::os::unix::net::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");
+}
+
+/// The attach snapshot: a small windowed tail over an unfinished older
+/// history (`historyBefore` > 0).
+fn attach_data(id: &str) -> Value {
+ let messages: Vec<Value> = (0..TAIL_MESSAGES)
+ .map(|index| {
+ json!({
+ "role": if index % 2 == 0 { "user" } else { "assistant" },
+ "content": [{
+ "type": "text",
+ "text": format!(
+ "tail row {index} the held-backfill exit harness wraps this text at the terminal width"
+ ),
+ }],
+ })
+ })
+ .collect();
+ 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",
+ "leafId": "attach-leaf",
+ "sessionName": "exit backfill e2e",
+ "model": null,
+ "isStreaming": false,
+ "isCompacting": false,
+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
+ },
+ "messages": messages,
+ "historyBefore": HISTORY_BEFORE,
+ "lastEventSequence": 0,
+ },
+ "replay": null,
+ },
+ })
+}
diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rs
index a4f32c3329..a2c5a1c6af 100644
--- a/crates/pa-daemon/src/protocol.rs
+++ b/crates/pa-daemon/src/protocol.rs
@@ -319,6 +319,7 @@ pub fn supported_client_capabilities() -> &'static [&'static str] {
"chunked_snapshot",
"client_owned_sessions",
"elide_snapshot_images",
+ "windowed_snapshot",
]
}
diff --git a/crates/pa-daemon/src/session_store.rs b/crates/pa-daemon/src/session_store.rs
index d0197d818a..8f5c14d56b 100644
--- a/crates/pa-daemon/src/session_store.rs
+++ b/crates/pa-daemon/src/session_store.rs
@@ -103,6 +103,13 @@ pub struct SessionEntry {
pub fields: Value,
}
+#[derive(Debug, Clone)]
+pub struct WindowedTranscript {
+ pub messages: Vec<Value>,
+ pub omitted: usize,
+ pub last_user_prompt_ms: Option<u64>,
+}
+
/// The windowed sequence's summary scalars (newest timestamp, message count),
/// from [`SessionFile::scan_message_scalars`] without materializing the fold.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
diff --git a/crates/pa-daemon/src/session_store/view.rs b/crates/pa-daemon/src/session_store/view.rs
index 70dd58bc64..33c827bc33 100644
--- a/crates/pa-daemon/src/session_store/view.rs
+++ b/crates/pa-daemon/src/session_store/view.rs
@@ -1,7 +1,7 @@
//! The loaded-session view: the branch walks, the window/settings reads, the
//! compacted message fold and its scalars, and the wire-shape message helpers.
-use super::{json, MessageWindowScalars, SessionEntry, SessionFile, Value};
+use super::{json, MessageWindowScalars, SessionEntry, SessionFile, Value, WindowedTranscript};
/// Entry types that represent user intent (vs daemon bookkeeping).
const CONTENT_ENTRY_TYPES: &[&str] = &[
@@ -279,7 +279,23 @@ impl SessionFile {
#[must_use]
pub fn messages(&self) -> Vec<Value> {
let mut messages = Vec::new();
- self.walk_message_values(|message| messages.push(message.into_owned()));
+ self.walk_message_values(|_, message| {
+ messages.push(message.into_owned());
+ true
+ });
+ messages
+ }
+
+ #[must_use]
+ pub fn messages_before(&self, before: usize) -> Vec<Value> {
+ let mut messages = Vec::new();
+ self.walk_message_values(|index, message| {
+ if index >= before {
+ return false;
+ }
+ messages.push(message.into_owned());
+ true
+ });
messages
}
@@ -288,11 +304,12 @@ impl SessionFile {
#[must_use]
pub fn scan_message_scalars(&self) -> MessageWindowScalars {
let mut scalars = MessageWindowScalars::default();
- self.walk_message_values(|message| {
+ self.walk_message_values(|_, message| {
scalars.message_count += 1;
if let Some(timestamp) = crate::types::message_timestamp_ms(&message) {
scalars.last_timestamp_ms = Some(timestamp);
}
+ true
});
scalars
}
@@ -300,7 +317,10 @@ impl SessionFile {
/// The windowed message sequence behind [`Self::messages`] (`custom_message`
/// rows rejoin as their wire form, `role: "custom"`; a compaction window
/// prepends its summary message). Every consumer derives from this one walk.
- fn walk_message_values<'a>(&'a self, mut visit: impl FnMut(std::borrow::Cow<'a, Value>)) {
+ fn walk_message_values<'a>(
+ &'a self,
+ mut visit: impl FnMut(usize, std::borrow::Cow<'a, Value>) -> bool,
+ ) {
let entry_message = |entry: &'a SessionEntry| -> Option<std::borrow::Cow<'a, Value>> {
match entry.type_.as_str() {
"message" => entry.fields.get("message").map(std::borrow::Cow::Borrowed),
@@ -319,12 +339,16 @@ impl SessionFile {
}
};
let branch = self.branch();
+ let mut index = 0usize;
let Some(compaction_position) =
branch.iter().rposition(|entry| entry.type_ == "compaction")
else {
for entry in &branch {
if let Some(message) = entry_message(entry) {
- visit(message);
+ if !visit(index, message) {
+ return;
+ }
+ index += 1;
}
}
return;
@@ -350,10 +374,12 @@ impl SessionFile {
retained_count += 1;
}
}
- visit(std::borrow::Cow::Owned(compaction_summary_message(
- compaction,
- retained_count,
- )));
+ let summary =
+ std::borrow::Cow::Owned(compaction_summary_message(compaction, retained_count));
+ if !visit(index, summary) {
+ return;
+ }
+ index += 1;
let mut keeping = false;
for entry in &branch[..compaction_position] {
if !entry_bears_message(entry) {
@@ -364,17 +390,119 @@ impl SessionFile {
}
if keeping {
if let Some(message) = entry_message(entry) {
- visit(message);
+ if !visit(index, message) {
+ return;
+ }
+ index += 1;
}
}
}
for entry in &branch[compaction_position + 1..] {
if let Some(message) = entry_message(entry) {
- visit(message);
+ if !visit(index, message) {
+ return;
+ }
+ index += 1;
}
}
}
+ #[must_use]
+ pub fn windowed_messages(&self, tail_budget: usize) -> WindowedTranscript {
+ let mut visited: Vec<std::borrow::Cow<'_, Value>> = Vec::new();
+ let mut last_user_prompt_ms = None;
+ self.walk_message_values(|_, message| {
+ if message.get("role").and_then(Value::as_str) == Some("user") {
+ // The prompt scalar mirrors the TUI's numeric/ISO timestamp
+ // contract without changing the roster's activity-time fold.
+ let prompt_timestamp_ms = match message.get("timestamp") {
+ Some(Value::Number(number)) => number.as_u64().or_else(|| {
+ number
+ .as_f64()
+ .filter(|value| value.is_finite())
+ .map(|value| value.max(0.0) as u64)
+ }),
+ Some(Value::String(iso)) => pa_types::incident::timestamp_to_ms(iso)
+ .filter(|ms| *ms > 0)
+ .map(|ms| ms as u64),
+ _ => None,
+ };
+ if let Some(timestamp) = prompt_timestamp_ms {
+ last_user_prompt_ms = Some(timestamp);
+ }
+ }
+ visited.push(message);
+ true
+ });
+ let mut cut = visited.len().saturating_sub(tail_budget);
+ while cut > 0
+ && matches!(
+ visited[cut].get("role").and_then(Value::as_str),
+ Some("toolResult" | "custom")
+ )
+ {
+ cut -= 1;
+ }
+ // User bash and other message rows can land between a call and its
+ // result. Match the same last-pending call as transcript replay, then
+ // move only across pairs intersecting the cut. Reverse result order
+ // also catches an earlier pair exposed by moving the boundary back.
+ let mut pending: std::collections::HashMap<&str, Vec<usize>> =
+ std::collections::HashMap::new();
+ let mut pairs = Vec::new();
+ for (index, message) in visited.iter().enumerate() {
+ match message.get("role").and_then(Value::as_str) {
+ Some("assistant") => {
+ if let Some(content) = message.get("content").and_then(Value::as_array) {
+ for block in content {
+ if let Some(id) = block.get("id").and_then(Value::as_str).filter(|_| {
+ block.get("type").and_then(Value::as_str) == Some("toolCall")
+ }) {
+ pending.entry(id).or_default().push(index);
+ }
+ }
+ }
+ }
+ Some("toolResult") => {
+ if let Some(call) = message
+ .get("toolCallId")
+ .and_then(Value::as_str)
+ .and_then(|id| pending.get_mut(id))
+ .and_then(Vec::pop)
+ {
+ pairs.push((call, index));
+ }
+ }
+ _ => {}
+ }
+ }
+ for (call, result) in pairs.into_iter().rev() {
+ if call < cut && result >= cut {
+ cut = call;
+ }
+ }
+ if let Some(retained) = visited
+ .first()
+ .filter(|first| first.get("role").and_then(Value::as_str) == Some("compactionSummary"))
+ .and_then(|first| first.get("retainedMessageCount"))
+ .and_then(Value::as_u64)
+ .and_then(|retained| usize::try_from(retained).ok())
+ {
+ if cut > 0 && cut <= retained {
+ cut = 0;
+ }
+ }
+ let messages = visited.split_off(cut);
+ WindowedTranscript {
+ messages: messages
+ .into_iter()
+ .map(std::borrow::Cow::into_owned)
+ .collect(),
+ omitted: cut,
+ last_user_prompt_ms,
+ }
+ }
+
/// The durable entry id the compaction cut keeps: the engine's
/// `firstKeptEntryId` references in-memory ids that never exist in the file —
/// the re-cut pins the boundary the file read recognizes.
diff --git a/crates/pa-daemon/src/snapshot_stream.rs b/crates/pa-daemon/src/snapshot_stream.rs
index 2a2e083ecf..908a3fedd9 100644
--- a/crates/pa-daemon/src/snapshot_stream.rs
+++ b/crates/pa-daemon/src/snapshot_stream.rs
@@ -54,6 +54,10 @@ pub(crate) fn wants_chunked(capabilities: &[String]) -> bool {
capabilities.iter().any(|cap| cap == "chunked_snapshot")
}
+pub(crate) fn wants_windowed(capabilities: &[String]) -> bool {
+ capabilities.iter().any(|cap| cap == "windowed_snapshot")
+}
+
/// True when the client asked for image payloads to leave the snapshot (`elide_snapshot_images`).
pub(crate) fn wants_image_elision(capabilities: &[String]) -> bool {
capabilities
@@ -143,20 +147,23 @@ pub(crate) fn stream_attach(
.get_mut("snapshot")
.and_then(Value::as_object_mut)
.ok_or_else(|| anyhow!("Session worker did not provide a snapshot"))?;
- let message_count = snapshot
- .get("summary")
- .and_then(|summary| summary.get("messageCount"))
- .and_then(Value::as_u64)
- .ok_or_else(|| anyhow!("Session snapshot is missing its message count"))?;
+ // The transcript leaves the response; the snapshot header keeps an
+ // empty `messages` array so the streamed shape matches the full one.
+ let messages = snapshot.remove("messages").unwrap_or(Value::Null);
+ snapshot.insert("messages".to_string(), Value::Array(Vec::new()));
+ // The stream's count is the transcript it carries: a windowed attach
+ // streams the tail alone, while `summary.messageCount` stays the
+ // session's total (the backfill cursor is `historyBefore`).
+ let message_count = match &messages {
+ Value::Array(messages) => messages.len() as u64,
+ // A missing or malformed transcript fails the transfer below.
+ _ => 0,
+ };
let stream = SnapshotStream {
id: snapshot_stream_id(active_session_id, &generation, last_event_sequence),
message_count,
target_chunk_bytes: SNAPSHOT_TARGET_CHUNK_BYTES as u64,
};
- // The transcript leaves the response; the snapshot header keeps an
- // empty `messages` array so the streamed shape matches the full one.
- let messages = snapshot.remove("messages").unwrap_or(Value::Null);
- snapshot.insert("messages".to_string(), Value::Array(Vec::new()));
// Legacy (non-slim) attach results duplicate the transcript at the top
// level; the streamed form drops the copy instead of shipping it empty.
match object.get_mut("messages") {
@@ -486,15 +493,6 @@ mod tests {
"Session worker did not provide a snapshot"
);
let mut data = attach_result(&[]);
- data["snapshot"]["summary"]
- .as_object_mut()
- .unwrap()
- .remove("messageCount");
- assert!(stream_attach(data, "s1", SnapshotPurpose::Attach)
- .unwrap_err()
- .to_string()
- .contains("message count"));
- let mut data = attach_result(&[]);
data.as_object_mut().unwrap().remove("lastEventCursor");
data["snapshot"]
.as_object_mut()
diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs
index 8a59e62972..b34f47d08f 100644
--- a/crates/pa-daemon/src/worker/commands.rs
+++ b/crates/pa-daemon/src/worker/commands.rs
@@ -94,7 +94,7 @@ impl Worker {
self.handle_wait_for_headless_completion(payload).await
}
"get_state" => self.handle_get_state(),
- "get_messages" => self.handle_get_messages(),
+ "get_messages" => self.handle_get_messages(payload),
"get_session_header" => self.handle_get_session_header(),
"get_session_stats" => self.handle_get_session_stats(),
"get_model_catalog" => self.handle_get_model_catalog(),
@@ -457,17 +457,52 @@ impl Worker {
response_success(None, "get_session_stats", Some(stats))
}
- fn handle_get_messages(&self) -> DaemonResponse {
+ fn handle_get_messages(&self, payload: &Value) -> DaemonResponse {
if let Err(response) = self.require_created("get_messages") {
return response;
}
- let core = self.core.lock().unwrap();
- let messages: Vec<Value> = core
- .store
- .as_ref()
- .map(crate::session_store::SessionFile::messages)
+ let before = payload
+ .get("before")
+ .and_then(Value::as_u64)
+ .and_then(|before| usize::try_from(before).ok());
+ let capabilities = payload
+ .get("capabilities")
+ .and_then(Value::as_array)
+ .map(|capabilities| {
+ capabilities
+ .iter()
+ .filter_map(Value::as_str)
+ .map(str::to_string)
+ .collect::<Vec<_>>()
+ })
.unwrap_or_default();
- response_success(None, "get_messages", Some(json!({ "messages": messages })))
+ let core = self.core.lock().unwrap();
+ // Validate ancestry atomically with the positional read. Appends keep the
+ // attached leaf on this branch; navigation to another branch does not.
+ let history_leaf = payload.get("historyLeafId").filter(|_| before.is_some());
+ if let Some(anchor) = history_leaf {
+ let valid = anchor.as_str().is_some_and(|leaf| {
+ core.store
+ .as_ref()
+ .is_some_and(|store| store.branch().iter().any(|entry| entry.id == leaf))
+ });
+ if !valid {
+ return response_failure(None, "get_messages", "History branch changed", None);
+ }
+ }
+ let mut messages: Vec<Value> = match (core.store.as_ref(), before) {
+ (Some(store), Some(before)) => store.messages_before(before),
+ (Some(store), None) => store.messages(),
+ (None, _) => Vec::new(),
+ };
+ if crate::snapshot_stream::wants_image_elision(&capabilities) {
+ crate::snapshot_stream::elide_snapshot_image_payloads(&mut messages);
+ }
+ let mut data = json!({ "messages": messages });
+ if let Some(anchor) = history_leaf {
+ data["historyLeafId"] = anchor.clone();
+ }
+ response_success(None, "get_messages", Some(data))
}
fn handle_get_queue(&self) -> DaemonResponse {
diff --git a/crates/pa-daemon/src/worker/connection.rs b/crates/pa-daemon/src/worker/connection.rs
index 2ef3d3515d..37ab0b7bbe 100644
--- a/crates/pa-daemon/src/worker/connection.rs
+++ b/crates/pa-daemon/src/worker/connection.rs
@@ -765,6 +765,8 @@ impl Worker {
}
}
+const ATTACH_TAIL_MESSAGE_BUDGET: usize = 512;
+
impl Worker {
pub(crate) fn handle_attach(&self, payload: &Value) -> DaemonResponse {
if let Err(response) = self.require_created("attach") {
@@ -832,18 +834,26 @@ impl Worker {
core.attached_client_ids.push(client_id.clone());
}
let summary = self.summary_locked(&core, summary_inputs);
- let mut messages: Vec<Value> = core
- .store
- .as_ref()
- .map(crate::session_store::SessionFile::messages)
- .unwrap_or_default();
+ let client_capabilities = echoed_client_capabilities
+ .clone()
+ .unwrap_or_else(|| capabilities.clone());
+ let windowed = crate::snapshot_stream::wants_windowed(&client_capabilities);
+ let (mut messages, omitted, last_user_prompt_ms) = match core.store.as_ref() {
+ Some(store) if windowed => {
+ let windowed = store.windowed_messages(ATTACH_TAIL_MESSAGE_BUDGET);
+ (
+ windowed.messages,
+ windowed.omitted,
+ windowed.last_user_prompt_ms,
+ )
+ }
+ Some(store) => (store.messages(), 0, None),
+ None => (Vec::new(), 0, None),
+ };
// The image-payload elision: `elide_snapshot_images` clients read the
// transcript without base64 payloads; the client's set is
// `capabilities` unless the routed attach carried
// `clientCapabilities`.
- let client_capabilities = echoed_client_capabilities
- .clone()
- .unwrap_or_else(|| capabilities.clone());
if crate::snapshot_stream::wants_image_elision(&client_capabilities) {
crate::snapshot_stream::elide_snapshot_image_payloads(&mut messages);
}
@@ -870,6 +880,12 @@ impl Worker {
"children": [],
});
snapshot["messages"] = Value::Array(messages);
+ if omitted > 0 {
+ snapshot["historyBefore"] = json!(omitted);
+ if let Some(last_user_prompt_ms) = last_user_prompt_ms {
+ snapshot["lastUserPromptMs"] = json!(last_user_prompt_ms);
+ }
+ }
// Slim clients read summary/messages from the snapshot; duplicating
// them at the top level would serialize the history twice per attach.
let slim = capabilities.iter().any(|cap| cap == "slim_attach");
diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rs
index f7fe594c46..0f32946651 100644
--- a/crates/pa-daemon/src/worker/tests.rs
+++ b/crates/pa-daemon/src/worker/tests.rs
@@ -50,6 +50,7 @@ mod kill_broadcast_tests;
mod queue_tests;
mod summary_tests;
mod warning_marker_tests;
+mod windowed_attach_tests;
#[tokio::test]
async fn background_refinement_event_is_fenced_to_its_review_session() {
let dir = std::env::temp_dir().join(format!("pa-refine-event-{}", uuid::Uuid::new_v4()));
diff --git a/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs b/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs
new file mode 100644
index 0000000000..7c5f0033b0
--- /dev/null
+++ b/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs
@@ -0,0 +1,608 @@
+use super::*;
+
+fn session_dir() -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("pa-windowed-attach-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+fn header_line(id: &str) -> String {
+ format!(
+ "{{\"type\":\"session\",\"version\":3,\"id\":\"{id}\",\"timestamp\":\"2026-01-01T00:00:00.000Z\",\"cwd\":\"/tmp\"}}\n"
+ )
+}
+
+fn parent_json(prev: Option<&str>) -> String {
+ serde_json::to_string(&prev).unwrap()
+}
+
+fn message_row(prev: Option<&str>, id: &str, message: &Value) -> String {
+ format!(
+ "{{\"type\":\"message\",\"message\":{},\"id\":\"{id}\",\"parentId\":{},\"timestamp\":\"2026-01-01T00:00:00.000Z\"}}\n",
+ serde_json::to_string(&message).unwrap(),
+ parent_json(prev),
+ )
+}
+
+fn custom_row(prev: Option<&str>, id: &str) -> String {
+ format!(
+ "{{\"type\":\"custom_message\",\"customType\":\"session_slash_command\",\"content\":\"head slash echo\",\"display\":true,\"id\":\"{id}\",\"parentId\":{},\"timestamp\":\"2026-01-01T00:00:00.000Z\"}}\n",
+ parent_json(prev),
+ )
+}
+
+fn assistant_message(text: &str) -> Value {
+ json!({
+ "role": "assistant",
+ "content": [{ "type": "text", "text": text }],
+ "timestamp": 10u64,
+ })
+}
+
+fn image_tool_result_message() -> Value {
+ json!({
+ "role": "toolResult",
+ "toolCallId": "img-call",
+ "toolName": "ipython",
+ "content": [
+ { "type": "text", "text": "Loaded 1 image(s) into context" },
+ { "type": "image", "data": "QUJDRA==", "mimeType": "image/png" }
+ ],
+ "isError": false,
+ "timestamp": 12u64,
+ })
+}
+
+fn tool_result_message() -> Value {
+ json!({
+ "role": "toolResult",
+ "toolCallId": "call",
+ "toolName": "bash",
+ "content": [{ "type": "text", "text": "output" }],
+ "isError": false,
+ "timestamp": 11u64,
+ })
+}
+
+struct Fixture {
+ content: String,
+ prev: Option<String>,
+ id: usize,
+}
+
+impl Fixture {
+ fn row(&mut self, build: impl FnOnce(Option<&str>, &str) -> String) {
+ let prev = self.prev.clone();
+ self.id += 1;
+ let row_id = format!("m{:07}", self.id);
+ self.content.push_str(&build(prev.as_deref(), &row_id));
+ self.prev = Some(row_id);
+ }
+}
+
+async fn worker_over(dir: &std::path::Path, path: &std::path::Path) -> std::sync::Arc<Worker> {
+ let config = WorkerConfig {
+ socket_path: dir.join("worker.sock"),
+ supervisor_socket_path: PathBuf::new(),
+ token: "token".to_string(),
+ worker_instance_id: String::new(),
+ active_session_id: "windowed-session".to_string(),
+ agent_dir: dir.join("agent"),
+ recovery_journal_path: dir.join("recovery.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({ "responses": ["ack"] })),
+ };
+ let worker = std::sync::Arc::new(Worker::new(config, None));
+ let created = worker
+ .dispatch(
+ "create",
+ &json!({
+ "cwd": dir.to_string_lossy(),
+ "sessionDir": dir.join("sessions").to_string_lossy(),
+ "sessionPath": path.to_string_lossy(),
+ "name": "windowed",
+ }),
+ )
+ .await;
+ assert!(created.success, "create failed: {created:?}");
+ worker
+}
+
+async fn attach(worker: &Worker, capabilities: &[&str]) -> Value {
+ let response = worker
+ .dispatch(
+ "attach",
+ &json!({
+ "activeSessionId": "windowed-session",
+ "clientId": "windowed-client",
+ "capabilities": capabilities,
+ }),
+ )
+ .await;
+ assert!(response.success, "attach failed: {response:?}");
+ response.data.expect("attach data")
+}
+
+async fn full_messages(worker: &Worker) -> Vec<Value> {
+ let response = worker.dispatch("get_messages", &json!({})).await;
+ assert!(response.success, "get_messages failed: {response:?}");
+ response.data.expect("get_messages data")["messages"]
+ .as_array()
+ .expect("messages array")
+ .clone()
+}
+
+const TUI_CAPABILITIES: &[&str] = &[
+ "attach_snapshot",
+ "event_sequence",
+ "slim_attach",
+ "elide_snapshot_images",
+ "windowed_snapshot",
+];
+
+#[tokio::test]
+async fn a_windowed_attach_serves_a_tool_result_safe_tail() {
+ let dir = session_dir();
+ let path = dir.join("windowed-tail.jsonl");
+ let mut fixture = Fixture {
+ content: header_line("windowed-tail"),
+ prev: None,
+ id: 0,
+ };
+ fixture.row(|prev, id| {
+ message_row(
+ prev,
+ id,
+ &json!({
+ "role": "user",
+ "content": "the head prompt",
+ "timestamp": 1000u64,
+ }),
+ )
+ });
+ fixture.row(custom_row);
+ fixture.row(custom_row);
+ for _ in 0..194 {
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("kept context")));
+ }
+ fixture.row(|prev, id| message_row(prev, id, &image_tool_result_message()));
+ fixture.row(|prev, id| {
+ message_row(
+ prev,
+ id,
+ &json!({
+ "role": "assistant",
+ "content": [{ "type": "toolCall", "id": "call-1", "name": "bash", "arguments": { "command": "ls" } }],
+ "timestamp": 4u64,
+ }),
+ )
+ });
+ fixture.row(custom_row);
+ for _ in 0..800 {
+ fixture.row(|prev, id| message_row(prev, id, &tool_result_message()));
+ }
+ std::fs::write(&path, fixture.content).unwrap();
+
+ let worker = worker_over(&dir, &path).await;
+ let full = full_messages(&worker).await;
+ assert_eq!(
+ full.len(),
+ 1000,
+ "the walk visits every message-bearing row"
+ );
+
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ let tail = snapshot["messages"].as_array().expect("tail messages");
+ let omitted = snapshot["historyBefore"].as_u64().expect("historyBefore");
+ assert_eq!(
+ omitted, 198,
+ "the cut snaps back off the tool result and custom rows"
+ );
+ assert_eq!(tail.len(), 802, "the tail keeps the whole tool call run");
+ assert_eq!(
+ tail[0]["role"], "assistant",
+ "the first tail message is never a tool result or custom row"
+ );
+ assert_eq!(
+ tail[1]["role"], "custom",
+ "the custom row rides the tail with its tool call"
+ );
+ assert_eq!(
+ &tail[..],
+ &full[(omitted as usize)..],
+ "the tail is a suffix of the one walk"
+ );
+ assert_eq!(
+ snapshot["lastUserPromptMs"], 1000,
+ "the newest user timestamp rides the windowed snapshot"
+ );
+ let head = worker
+ .dispatch("get_messages", &json!({ "before": omitted }))
+ .await;
+ assert!(head.success, "the head fetch failed: {head:?}");
+ assert_eq!(
+ head.data.expect("head data")["messages"],
+ serde_json::json!(full[..omitted as usize]),
+ "the before range serves the walk's omitted prefix"
+ );
+ let elided = worker
+ .dispatch(
+ "get_messages",
+ &json!({
+ "before": omitted,
+ "capabilities": TUI_CAPABILITIES,
+ }),
+ )
+ .await;
+ assert!(elided.success, "the elided head fetch failed: {elided:?}");
+ let elided_messages = elided.data.expect("elided head data")["messages"]
+ .as_array()
+ .expect("elided messages")
+ .clone();
+ assert_eq!(
+ elided_messages[197]["content"][1]["data"], "",
+ "the image payload leaves the backfill head"
+ );
+ assert_eq!(
+ elided_messages[197]["content"][1]["elidedBytes"], 8,
+ "the elided marker rides the backfill head"
+ );
+
+ let plain = attach(&worker, &["attach_snapshot", "event_sequence"]).await;
+ let plain_messages = plain["snapshot"]["messages"].as_array().expect("messages");
+ assert_eq!(
+ plain_messages.len(),
+ 1000,
+ "a non-windowed attach keeps the full snapshot"
+ );
+ assert!(
+ plain["snapshot"].get("historyBefore").is_none()
+ && plain["snapshot"].get("lastUserPromptMs").is_none(),
+ "the unwindowed snapshot keeps today's shape"
+ );
+}
+
+#[tokio::test]
+async fn a_windowed_attach_never_cuts_inside_the_compaction_retained_segment() {
+ let dir = session_dir();
+ let path = dir.join("windowed-compacted.jsonl");
+ let retained = 400usize;
+ let post = 200usize;
+ let mut fixture = Fixture {
+ content: header_line("windowed-compacted"),
+ prev: None,
+ id: 0,
+ };
+ for _ in 0..10 {
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("compacted away")));
+ }
+ let first_kept = fixture.prev.clone().expect("retained start");
+ for _ in 1..retained {
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("retained")));
+ }
+ fixture.row(|prev, id| {
+ format!(
+ "{{\"type\":\"compaction\",\"summary\":\"the story\",\"firstKeptEntryId\":\"{first_kept}\",\"tokensBefore\":4000,\"id\":\"{id}\",\"parentId\":{},\"timestamp\":\"2026-01-01T00:00:00.000Z\"}}\n",
+ parent_json(prev),
+ )
+ });
+ for _ in 0..post {
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("after compaction")));
+ }
+ std::fs::write(&path, fixture.content).unwrap();
+
+ let worker = worker_over(&dir, &path).await;
+ let full = full_messages(&worker).await;
+ assert_eq!(
+ full[0]["role"], "compactionSummary",
+ "the walk serves the summary first"
+ );
+ assert_eq!(full.len(), 601, "summary plus retained plus post");
+
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ let tail = snapshot["messages"].as_array().expect("tail messages");
+ let omitted = snapshot["historyBefore"].as_u64().unwrap_or(0);
+ assert!(
+ omitted == 0 || omitted >= 401,
+ "the cut is complete history or past the retained segment, got {omitted}"
+ );
+ assert_eq!(tail.len(), 601 - omitted as usize);
+ assert_eq!(&tail[..], &full[(omitted as usize)..]);
+}
+
+#[tokio::test]
+async fn a_windowed_attach_preserves_iso_and_fractional_prompt_times() {
+ for timestamp in [
+ json!(2000.75),
+ json!("1970-01-01T00:00:02.000Z"),
+ json!("1970-01-01T01:00:02.000+01:00"),
+ ] {
+ for user_index in [1usize, 599] {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("timestamp-tail.jsonl");
+ let mut fixture = Fixture {
+ content: header_line("timestamp-tail"),
+ prev: None,
+ id: 0,
+ };
+ for index in 0..600 {
+ let message = if index == user_index {
+ json!({ "role": "user", "content": "latest", "timestamp": timestamp })
+ } else if index == 0 {
+ json!({ "role": "user", "content": "older", "timestamp": 1000 })
+ } else {
+ assistant_message("continuation")
+ };
+ fixture.row(|prev, id| message_row(prev, id, &message));
+ }
+ std::fs::write(&path, fixture.content).unwrap();
+ let worker = worker_over(dir.path(), &path).await;
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ assert_eq!(snapshot["historyBefore"], 88);
+ assert_eq!(
+ snapshot["lastUserPromptMs"], 2000,
+ "latest timestamp {timestamp} at index {user_index}"
+ );
+ }
+ }
+}
+
+/// The chunked stream's advertised count is the transcript it carries:
+/// a windowed attach streams the tail alone, and the summary keeps the
+/// session total the backfill cursor (`historyBefore`) completes.
+#[tokio::test]
+async fn a_chunked_windowed_attach_streams_the_count_it_carries() {
+ let dir = session_dir();
+ let path = dir.join("windowed-chunked.jsonl");
+ let mut fixture = Fixture {
+ content: header_line("windowed-chunked"),
+ prev: None,
+ id: 0,
+ };
+ for index in 0..600 {
+ let message = if index == 0 {
+ json!({ "role": "user", "content": "the head prompt", "timestamp": 1000u64 })
+ } else {
+ assistant_message("kept context")
+ };
+ fixture.row(|prev, id| message_row(prev, id, &message));
+ }
+ std::fs::write(&path, fixture.content).unwrap();
+
+ let worker = worker_over(&dir, &path).await;
+ let full = full_messages(&worker).await;
+ assert_eq!(full.len(), 600, "the walk visits every message row");
+
+ let mut capabilities = TUI_CAPABILITIES.to_vec();
+ capabilities.push("chunked_snapshot");
+ let data = attach(&worker, &capabilities).await;
+ let snapshot = &data["snapshot"];
+ let omitted = snapshot["historyBefore"].as_u64().expect("historyBefore");
+ let summary_count = snapshot["summary"]["messageCount"]
+ .as_u64()
+ .expect("summary count");
+ assert_eq!(omitted, 88);
+ assert_eq!(summary_count, 600);
+ assert_eq!(snapshot["messages"].as_array().expect("tail").len(), 512);
+
+ // The supervisor's streaming step (routing.rs `streamed_attach_lines`).
+ let (streamed, events) = crate::snapshot_stream::stream_attach(
+ data,
+ "windowed-session",
+ pa_types::daemon::SnapshotPurpose::Attach,
+ )
+ .expect("stream");
+ let crate::snapshot_stream::SnapshotStreamEvents::Streamed(lines) = events else {
+ panic!("the windowed tail must stream");
+ };
+ let begin = lines
+ .iter()
+ .find(|line| line["type"] == json!("session_snapshot_begin"))
+ .expect("begin record");
+ let carried: u64 = lines
+ .iter()
+ .filter(|line| line["type"] == json!("session_snapshot_chunk"))
+ .map(|chunk| chunk["messages"].as_array().map_or(0, Vec::len) as u64)
+ .sum();
+ assert_eq!(
+ begin["messageCount"], streamed["snapshotStream"]["messageCount"],
+ "the begin record and the stream descriptor carry one count"
+ );
+ assert_eq!(
+ begin["messageCount"].as_u64().expect("begin count"),
+ carried,
+ "the advertised count is the messages the stream carries"
+ );
+ assert_eq!(
+ omitted + carried,
+ summary_count,
+ "the tail plus the history-before prefix is the session total"
+ );
+}
+
+#[tokio::test]
+async fn a_windowed_attach_keeps_interleaved_tool_pairs_together() {
+ for scenario in [0, 1, 2] {
+ let crossing = scenario != 0;
+ let earlier_id = if scenario == 2 { "boundary" } else { "earlier" };
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("interleaved-tools.jsonl");
+ let mut fixture = Fixture {
+ content: header_line("interleaved-tools"),
+ prev: None,
+ id: 0,
+ };
+ for _ in 0..20 {
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("older history")));
+ }
+ let call = |id: &str| {
+ json!({
+ "role": "assistant", "timestamp": 10,
+ "content": [{"type": "toolCall", "id": id, "name": "bash", "arguments": {"command": "echo paired"}}],
+ })
+ };
+ let result = |id: &str| {
+ json!({
+ "role": "toolResult", "toolCallId": id, "toolName": "bash", "timestamp": 12,
+ "content": [{"type": "text", "text": "paired result"}], "isError": false,
+ })
+ };
+ if crossing {
+ fixture.row(|prev, id| message_row(prev, id, &call(earlier_id)));
+ }
+ fixture.row(|prev, id| message_row(prev, id, &call("boundary")));
+ if crossing {
+ fixture.row(|prev, id| message_row(prev, id, &result(earlier_id)));
+ }
+ // A user !command can finish while an agent tool is still running.
+ // Place this real message role exactly at the nominal 512-row cut.
+ fixture.row(|prev, id| {
+ message_row(
+ prev,
+ id,
+ &json!({
+ "role": "bashExecution", "command": "echo user", "output": "user",
+ "exitCode": 0, "cancelled": false, "truncated": false, "timestamp": 11,
+ }),
+ )
+ });
+ fixture.row(|prev, id| message_row(prev, id, &result("boundary")));
+ for _ in 0..510 {
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("newer history")));
+ }
+ std::fs::write(&path, fixture.content).unwrap();
+ let worker = worker_over(dir.path(), &path).await;
+ let full = full_messages(&worker).await;
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ assert_eq!(
+ snapshot["historyBefore"], 20,
+ "both matched pairs belong in the tail; unrelated older history stays omitted"
+ );
+ assert_eq!(
+ snapshot["messages"],
+ json!(full[20..]),
+ "moving the boundary preserves the complete ordered suffix"
+ );
+ let head = worker
+ .dispatch("get_messages", &json!({"before": 20}))
+ .await;
+ assert!(head.success);
+ assert_eq!(
+ head.data.unwrap()["messages"],
+ json!(full[..20]),
+ "the omitted prefix remains available without duplication"
+ );
+ }
+}
+
+async fn branched_worker() -> (tempfile::TempDir, std::sync::Arc<Worker>) {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("branched-tail.jsonl");
+ let mut fixture = Fixture {
+ content: header_line("branched-tail"),
+ prev: None,
+ id: 0,
+ };
+ fixture.content.push_str(&message_row(
+ /*prev*/ None,
+ "sibling",
+ &assistant_message("other branch"),
+ ));
+ for index in 0..600 {
+ fixture.row(|prev, id| {
+ message_row(prev, id, &assistant_message(&format!("original {index}")))
+ });
+ }
+ std::fs::write(&path, fixture.content).unwrap();
+ let worker = worker_over(dir.path(), &path).await;
+ (dir, worker)
+}
+
+#[tokio::test]
+async fn anchored_backfill_rejects_other_client_branch_navigation() {
+ for target in ["sibling", "m0000300"] {
+ let (_dir, worker) = branched_worker().await;
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ let leaf = snapshot["state"]["leafId"].as_str().expect("attached leaf");
+ assert_eq!(snapshot["historyBefore"], 88);
+ let navigated = worker
+ .dispatch(
+ "navigate_tree",
+ &json!({"clientId": "other-client", "targetId": target}),
+ )
+ .await;
+ assert!(navigated.success, "navigation failed: {navigated:?}");
+ let current = full_messages(&worker).await;
+ assert_eq!(current.len(), if target == "sibling" { 1 } else { 300 });
+ let state = worker.dispatch("get_connection_state", &json!({})).await;
+ assert!(state.success, "state failed: {state:?}");
+ assert_eq!(
+ state.data.unwrap()["compactionCount"],
+ snapshot["state"]["compactionCount"],
+ "the existing compaction fence cannot detect this branch change"
+ );
+ let backfill = worker
+ .dispatch(
+ "get_messages",
+ &json!({"before": snapshot["historyBefore"], "historyLeafId": leaf}),
+ )
+ .await;
+ assert!(
+ !backfill.success,
+ "a prefix from {target} must not join the old attach tail: {backfill:?}"
+ );
+ assert_eq!(
+ full_messages(&worker).await,
+ current,
+ "legacy full reads remain available"
+ );
+ }
+}
+
+#[tokio::test]
+async fn anchored_backfill_accepts_descendant_appends_and_restored_branch() {
+ let (_dir, worker) = branched_worker().await;
+ let original = full_messages(&worker).await;
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ let leaf = snapshot["state"]["leafId"].as_str().expect("attached leaf");
+ let appended = worker
+ .dispatch(
+ "prompt_and_wait",
+ &json!({"activeSessionId": "windowed-session", "message": "append on this branch"}),
+ )
+ .await;
+ assert!(appended.success, "append failed: {appended:?}");
+ assert!(full_messages(&worker).await.len() > original.len());
+ for restore in [false, true] {
+ if restore {
+ for target in ["sibling", leaf] {
+ let navigated = worker
+ .dispatch(
+ "navigate_tree",
+ &json!({"clientId": "other-client", "targetId": target}),
+ )
+ .await;
+ assert!(navigated.success, "navigation failed: {navigated:?}");
+ }
+ }
+ let backfill = worker
+ .dispatch(
+ "get_messages",
+ &json!({"before": snapshot["historyBefore"], "historyLeafId": leaf}),
+ )
+ .await;
+ assert!(backfill.success, "coherent prefix rejected: {backfill:?}");
+ let returned = backfill.data.expect("backfill data");
+ assert_eq!(returned["messages"], json!(original[..88]));
+ assert_eq!(
+ returned["historyLeafId"], leaf,
+ "the worker acknowledges that it honored the anchor"
+ );
+ }
+}
diff --git a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs
index 68cc134aa6..e6fce4d8b4 100644
--- a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs
+++ b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs
@@ -43,6 +43,7 @@ fn supervisor_end_to_end_scripted_session_lifecycle() {
"chunked_snapshot",
"client_owned_sessions",
"elide_snapshot_images",
+ "windowed_snapshot",
"delete_rlm_subagent",
"heartbeat_catalog",
"heartbeat_management",
diff --git a/crates/pa-tui/Cargo.toml b/crates/pa-tui/Cargo.toml
index 0edc16c2c6..553dd706ec 100644
--- a/crates/pa-tui/Cargo.toml
+++ b/crates/pa-tui/Cargo.toml
@@ -23,6 +23,7 @@ anyhow = "1"
base64 = "0.22"
clap = { version = "4", features = ["derive"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util", "net", "process"] }
+tokio-util = { version = "0.7", default-features = false, features = ["rt"] }
uuid = { version = "1", features = ["v4"] }
[[bin]]
diff --git a/crates/pa-tui/src/direct_transport.rs b/crates/pa-tui/src/direct_transport.rs
index 8b118e3207..4b4644b0d7 100644
--- a/crates/pa-tui/src/direct_transport.rs
+++ b/crates/pa-tui/src/direct_transport.rs
@@ -420,6 +420,7 @@ pub(crate) fn direct_attach_capabilities() -> Vec<DaemonClientCapability> {
"event_sequence".to_string(),
"slim_attach".to_string(),
"elide_snapshot_images".to_string(),
+ "windowed_snapshot".to_string(),
]
}
diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs
index 6cfa6c161e..3276e4deb6 100644
--- a/crates/pa-tui/src/interactive.rs
+++ b/crates/pa-tui/src/interactive.rs
@@ -58,7 +58,7 @@ use ratatui::Terminal;
use tokio::sync::mpsc;
#[cfg(test)]
-mod tests;
+pub(crate) mod tests;
/// Which session the interactive run opens.
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rs
index 52b168f76b..13264e256d 100644
--- a/crates/pa-tui/src/interactive/run.rs
+++ b/crates/pa-tui/src/interactive/run.rs
@@ -208,6 +208,8 @@ async fn run_interactive_surface(
// autocomplete provider.
let (commands_tx, mut commands_rx) =
mpsc::unbounded_channel::<crate::session_ui::CommandCatalogUpdate>();
+ let (backfill_tx, mut backfill_rx) =
+ mpsc::unbounded_channel::<crate::session_ui::TranscriptBackfillNote>();
// The double-Ctrl+C force-quit guard: the terminal reader observes the pair while this loop is
// wedged in a daemon request; a std-thread watchdog enforces the exit deadline without the
// runtime.
@@ -308,6 +310,7 @@ async fn run_interactive_surface(
let bash_tx = bash_tx.clone();
let factory_tx = factory_tx.clone();
let commands_tx = commands_tx.clone();
+ let backfill_tx = backfill_tx.clone();
let waits_through_update_restart = route == SessionOpenRoute::AgentsView;
tokio::spawn(async move {
crate::update_restart_wait::wait_through_update_restart(
@@ -335,6 +338,7 @@ async fn run_interactive_surface(
let bash_tx = bash_tx.clone();
let factory_tx = factory_tx.clone();
let commands_tx = commands_tx.clone();
+ let backfill_tx = backfill_tx.clone();
async move {
let (client, events) = match first {
Some(first) => first,
@@ -362,6 +366,7 @@ async fn run_interactive_surface(
factory: factory_tx,
commands: commands_tx,
},
+ backfill_tx,
)
.await?;
Ok((events, session))
@@ -823,6 +828,9 @@ async fn run_interactive_surface(
let mut session_reconnect: Option<SessionReconnect> = None;
'run: while running {
+ if !session.dirty {
+ session.spawn_pending_backfill();
+ }
if enhanced_keys_pending {
if let Some((kitty, modify_other_keys)) = crate::enhanced_keys::settle_state() {
if let Some(telemetry) = &session.telemetry {
@@ -1525,6 +1533,11 @@ async fn run_interactive_surface(
session.apply_background_note(&note, &mut view);
}
}
+ maybe_backfill = backfill_rx.recv() => {
+ if let Some(note) = maybe_backfill {
+ session.apply_transcript_backfill(note, &mut view);
+ }
+ }
maybe_compaction_abort = compaction_abort_rx.recv() => {
if let Some(outcome) = maybe_compaction_abort {
session.apply_compaction_abort_outcome(outcome, &mut view);
@@ -2018,6 +2031,15 @@ async fn run_interactive_surface(
// switch into a mid-teardown process kill ("shutdown stalled; forced exit.", the live report),
// so the deadline covers only the leaves that end this process.
let handing_off = session.open_agents_view || session.pending_selection.is_some();
+ if renderer.is_terminal() && !session.open_agents_view {
+ // Leaving the run flushes only the history already loaded: an unfinished
+ // older-history page is abandoned (dropping the task aborts its request),
+ // while a page that already arrived applies before the view goes away.
+ session.transcript_backfill = None;
+ while let Ok(note) = backfill_rx.try_recv() {
+ session.apply_transcript_backfill(note, &mut view);
+ }
+ }
if renderer.is_terminal() && !handing_off {
exit_guard.arm_for_exit();
}
diff --git a/crates/pa-tui/src/interactive/tests.rs b/crates/pa-tui/src/interactive/tests.rs
index d8a77e81d6..b3760d9941 100644
--- a/crates/pa-tui/src/interactive/tests.rs
+++ b/crates/pa-tui/src/interactive/tests.rs
@@ -89,7 +89,7 @@ fn flush_rows_write_crlf_and_keep_zone_markers() {
assert!(empty.is_empty());
}
-fn options(selection: ModelSelection) -> InteractiveOptions {
+pub(crate) fn options(selection: ModelSelection) -> InteractiveOptions {
InteractiveOptions {
models: None,
socket_path: PathBuf::from("/tmp/unused.sock"),
diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rs
index 55de7d07f4..67ea9ecea1 100644
--- a/crates/pa-tui/src/session_ui.rs
+++ b/crates/pa-tui/src/session_ui.rs
@@ -122,6 +122,33 @@ pub(crate) struct CommandCatalogUpdate {
pub skill_commands: Vec<crate::autocomplete::SlashCommandEntry>,
}
+pub(crate) fn attach_capabilities() -> Vec<pa_types::daemon::DaemonClientCapability> {
+ vec![
+ "attach_snapshot".to_string(),
+ "event_sequence".to_string(),
+ "slim_attach".to_string(),
+ "elide_snapshot_images".to_string(),
+ "windowed_snapshot".to_string(),
+ ]
+}
+
+pub(crate) fn last_assistant_text_of(chat: &[ChatEntry]) -> Option<String> {
+ chat.iter().rev().find_map(|entry| match entry {
+ ChatEntry::Assistant(message) => {
+ message.blocks.iter().rev().find_map(|block| match block {
+ MessageBlock::Text(text) => Some(text.clone()),
+ MessageBlock::Thinking(_) => None,
+ })
+ }
+ _ => None,
+ })
+}
+
+pub(crate) struct TranscriptBackfillNote {
+ pub epoch: u64,
+ pub entries: std::result::Result<Vec<ChatEntry>, String>,
+}
+
pub(crate) struct SessionUi {
pub(crate) client: DaemonClient,
pub(crate) active_session_id: String,
@@ -326,6 +353,17 @@ pub(crate) struct SessionUi {
/// idle and exit gates treat an in-flight submit as busy.
prompt_in_flight: usize,
pub(crate) transcript_stale: bool,
+ transcript_epoch: u64,
+ backfill_compaction_count: Option<u64>,
+ backfill_leaf_id: Option<String>,
+ /// Dropping or replacing the handle aborts an obsolete backfill task. An
+ /// already-running decode finishes on the blocking pool and its result is
+ /// discarded: the aborted task never sends it, and an already-queued note
+ /// is dropped by the epoch check.
+ pub(crate) transcript_backfill: Option<tokio_util::task::AbortOnDropHandle<()>>,
+ pending_backfill: Option<usize>,
+ backfill_seam: crate::snapshot::BackfillSeam,
+ backfill_notes: mpsc::UnboundedSender<TranscriptBackfillNote>,
/// Adoption telemetry (counted into `tui exit`); `None` drops events.
pub(crate) telemetry: Option<std::sync::Arc<dyn crate::interactive::InteractionTelemetry>>,
scroll_adoption_emitted: bool,
diff --git a/crates/pa-tui/src/session_ui/apply.rs b/crates/pa-tui/src/session_ui/apply.rs
index 8f8955106d..f896508c50 100644
--- a/crates/pa-tui/src/session_ui/apply.rs
+++ b/crates/pa-tui/src/session_ui/apply.rs
@@ -1,10 +1,10 @@
//! The streamed-event pump: client events, turn updates, assistant/tool
//! rows, compaction aborts, and the telemetry seams.
use super::{
- assistant_message_parts, event_to_update, pop_superseded_attempt_row, AgentView, ChatEntry,
- CompactionReason, CompactionState, DaemonClientEvent, DaemonCommand, Duration, Map,
- MessageBlock, Result, RetryState, SessionUi, StatusKind, ToolResultView, TurnUpdate, Value,
- UI_REQUEST_TIMEOUT_MS,
+ assistant_message_parts, event_to_update, last_assistant_text_of, pop_superseded_attempt_row,
+ AgentView, ChatEntry, CompactionReason, CompactionState, DaemonClientEvent, DaemonCommand,
+ Duration, Map, MessageBlock, Result, RetryState, SessionUi, StatusKind, ToolResultView,
+ TranscriptBackfillNote, TurnUpdate, Value, UI_REQUEST_TIMEOUT_MS,
};
/// One backgrounded compaction-abort outcome: a failed abort surfaces as
@@ -110,23 +110,39 @@ impl SessionUi {
/// A compaction succeeded and the durable transcript was rebuilt: re-fetch it. Best effort — a
/// failed fetch keeps the pushed outcome row instead of an empty transcript.
pub(crate) async fn rebuild_transcript(&mut self, view: &mut AgentView) {
+ let incomplete_history =
+ self.pending_backfill.is_some() || self.transcript_backfill.is_some();
self.transcript_stale = false;
+ self.transcript_epoch = self.transcript_epoch.wrapping_add(1);
+ self.transcript_backfill = None;
+ self.pending_backfill = None;
self.last_status_index = None;
self.pressed_click = None;
- let Ok(data) = self
+ let data = self
.bounded_request(
Duration::from_millis(UI_REQUEST_TIMEOUT_MS),
DaemonCommand::GetMessages {
id: None,
active_session_id: self.active_session_id.clone(),
+ before: None,
+ capabilities: None,
rest: Map::default(),
},
)
- .await
+ .await;
+ let Some(messages) = data
+ .as_ref()
+ .ok()
+ .and_then(|data| data.get("messages"))
+ .and_then(Value::as_array)
else {
- return;
- };
- let Some(messages) = data.get("messages").and_then(Value::as_array) else {
+ if incomplete_history {
+ view.push_entry(ChatEntry::Status {
+ text: "Transcript refresh failed; displayed history may be incomplete or stale. Reopen the session to retry.".to_string(),
+ kind: StatusKind::Warning,
+ });
+ self.dirty = true;
+ }
return;
};
let entries = crate::snapshot::transcript_to_entries(messages);
@@ -138,6 +154,122 @@ impl SessionUi {
self.dirty = true;
}
+ pub(crate) fn spawn_pending_backfill(&mut self) {
+ if let Some(before) = self.pending_backfill.take() {
+ self.spawn_transcript_backfill(before);
+ }
+ }
+
+ pub(crate) fn spawn_transcript_backfill(&mut self, before: usize) {
+ let client = self.client.clone();
+ let active_session_id = self.active_session_id.clone();
+ let epoch = self.transcript_epoch;
+ let compaction_count = self.backfill_compaction_count;
+ let leaf_id = self.backfill_leaf_id.clone();
+ let session_id = self.session_id.clone();
+ let notes = self.backfill_notes.clone();
+ let task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
+ let entries: Result<Vec<ChatEntry>> = async {
+ let leaf_id =
+ leaf_id.ok_or_else(|| anyhow::anyhow!("missing history branch anchor"))?;
+ let command = DaemonCommand::GetMessages {
+ id: None,
+ active_session_id: active_session_id.clone(),
+ before: Some(before as u64),
+ capabilities: Some(crate::session_ui::attach_capabilities()),
+ rest: Map::from_iter([(
+ "historyLeafId".to_owned(),
+ Value::String(leaf_id.clone()),
+ )]),
+ };
+ // A read-only request can safely retry once on a live link. Keep
+ // the same cursor; a second failure must not masquerade as an empty page.
+ let mut data = match client.request_ok(command.clone()).await {
+ Ok(data) => data,
+ Err(error) if crate::daemon_client::is_daemon_timeout(&error) => {
+ return Err(error)
+ }
+ Err(_) => client.request_ok(command).await?,
+ };
+ // Require the echo so workers that ignore the optional anchor fail closed.
+ if data.get("historyLeafId").and_then(Value::as_str) != Some(leaf_id.as_str()) {
+ return Err(anyhow::anyhow!("unverified history branch anchor"));
+ }
+ // Validate after the prefix read: a compaction that changed its
+ // indices has already advanced the persisted count, even if its
+ // end event has not reached the UI yet. Ordinary appends do not.
+ let state = client
+ .request_ok(DaemonCommand::GetConnectionState {
+ id: None,
+ active_session_id: active_session_id.clone(),
+ rest: Map::default(),
+ })
+ .await?;
+ if compaction_count.is_none()
+ || state.get("compactionCount").and_then(Value::as_u64) != compaction_count
+ || state.get("sessionId").and_then(Value::as_str) != Some(session_id.as_str())
+ || state.get("activeSessionId").and_then(Value::as_str)
+ != Some(active_session_id.as_str())
+ {
+ return Err(anyhow::anyhow!("history changed during backfill"));
+ }
+ let Some(Value::Array(messages)) = data.get_mut("messages").map(Value::take) else {
+ return Err(anyhow::anyhow!("missing messages in history response"));
+ };
+ Ok(tokio::task::spawn_blocking(move || {
+ crate::snapshot::transcript_to_entries(&messages)
+ })
+ .await?)
+ }
+ .await;
+ let entries = entries.map_err(|error| error.to_string());
+ let _ = notes.send(TranscriptBackfillNote { epoch, entries });
+ }));
+ self.transcript_backfill = Some(task);
+ }
+
+ pub(crate) fn apply_transcript_backfill(
+ &mut self,
+ note: TranscriptBackfillNote,
+ view: &mut AgentView,
+ ) {
+ if note.epoch != self.transcript_epoch {
+ return;
+ }
+ self.transcript_backfill = None;
+ let mut entries = match note.entries {
+ Ok(entries) => entries,
+ Err(error) => {
+ view.push_entry(ChatEntry::Status {
+ text: format!(
+ "Older history could not be loaded: {error}. Reopen the session to retry."
+ ),
+ kind: StatusKind::Warning,
+ });
+ self.dirty = true;
+ return;
+ }
+ };
+ crate::snapshot::join_backfilled_entries(&mut entries, self.backfill_seam);
+ let count = entries.len();
+ if let Some(index) = self.last_status_index {
+ self.last_status_index = Some(index + count);
+ }
+ if let Some(index) = self.streaming_index {
+ self.streaming_index = Some(index + count);
+ }
+ if let Some(index) = self.goal_view.last_status_index {
+ self.goal_view.last_status_index = Some(index + count);
+ }
+ self.pressed_click = None;
+ if self.last_assistant_text.is_none() {
+ self.last_assistant_text = last_assistant_text_of(&entries);
+ }
+ view.prepend_entries(entries);
+ self.trim_after_frame = true;
+ self.dirty = true;
+ }
+
/// Report the first scroll action of the run (`tui_scroll_count`),
/// fire-and-forget so the keypress never waits on the telemetry flush.
pub(super) fn track_scroll(&mut self, action: &'static str, resumed_following: bool) {
diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rs
index e6911a4661..6f0a14adf7 100644
--- a/crates/pa-tui/src/session_ui/lifecycle.rs
+++ b/crates/pa-tui/src/session_ui/lifecycle.rs
@@ -2,13 +2,13 @@
//! §10 reattach, the attach fold, and the transcript rebuild it feeds),
//! the stats refresh, and the detach/exit request helpers.
use super::{
- attach_data_from_response, create_session, mpsc, reconstruct, resume_hint_from_stats,
- ActivityUpdates, AgentView, BTreeMap, ChatEntry, CompactionAbortNote, Context, DaemonClient,
- DaemonCommand, DockFold, Duration, GoalView, HashSet, InteractiveOptions, LoaderTokenTracker,
- Map, MessageBlock, ModelCatalogUpdate, PromptOrder, PromptSubmitNote, ReattachOutcome,
- RebuildKind, RecoveryKind, ReloadNote, Result, ResyncBash, SessionSelection, SessionUi,
- ShareNote, UpdateNote, Value, EXIT_DETACH_TIMEOUT_MS, EXIT_STATS_TIMEOUT_MS,
- UI_REQUEST_TIMEOUT_MS,
+ attach_capabilities, attach_data_from_response, create_session, last_assistant_text_of, mpsc,
+ reconstruct, resume_hint_from_stats, ActivityUpdates, AgentView, BTreeMap, ChatEntry,
+ CompactionAbortNote, Context, DaemonClient, DaemonCommand, DockFold, Duration, GoalView,
+ HashSet, InteractiveOptions, LoaderTokenTracker, Map, ModelCatalogUpdate, PromptOrder,
+ PromptSubmitNote, ReattachOutcome, RebuildKind, RecoveryKind, ReloadNote, Result, ResyncBash,
+ SessionSelection, SessionUi, ShareNote, TranscriptBackfillNote, UpdateNote, Value,
+ EXIT_DETACH_TIMEOUT_MS, EXIT_STATS_TIMEOUT_MS, UI_REQUEST_TIMEOUT_MS,
};
impl SessionUi {
@@ -27,6 +27,7 @@ impl SessionUi {
catalog_updates: mpsc::UnboundedSender<ModelCatalogUpdate>,
auth_panel_notes: mpsc::UnboundedSender<crate::auth_panel::AuthPanelRequest>,
activity_updates: ActivityUpdates,
+ backfill_notes: mpsc::UnboundedSender<TranscriptBackfillNote>,
) -> Result<SessionUi> {
let active_session_id = match &options.session {
SessionSelection::New => create_session(&client, options, None).await?,
@@ -168,6 +169,13 @@ impl SessionUi {
input_submission_generation: 0,
prompt_in_flight: 0,
transcript_stale: false,
+ transcript_epoch: 0,
+ backfill_compaction_count: None,
+ backfill_leaf_id: None,
+ transcript_backfill: None,
+ pending_backfill: None,
+ backfill_seam: crate::snapshot::BackfillSeam::Preserve,
+ backfill_notes,
telemetry: options.telemetry.clone(),
scroll_adoption_emitted: false,
exit_reason: "daemon_closed",
@@ -341,12 +349,7 @@ impl SessionUi {
client_id: None,
// `elide_snapshot_images`: the transcript arrives without the base64 image payloads, so
// an image-heavy session's attach stops transferring megabytes.
- capabilities: Some(vec![
- "attach_snapshot".to_string(),
- "event_sequence".to_string(),
- "slim_attach".to_string(),
- "elide_snapshot_images".to_string(),
- ]),
+ capabilities: Some(attach_capabilities()),
resume_cursor: None,
telemetry_disabled: self.telemetry_disabled.filter(|disabled| *disabled),
recovery_config: None,
@@ -482,19 +485,7 @@ impl SessionUi {
// or compaction settles): the rebuild below re-syncs it into the
// chrome exactly like the other reconstructed session fields.
self.context = reconstructed.context_usage;
- self.last_assistant_text = reconstructed
- .chat
- .iter()
- .rev()
- .find_map(|entry| match entry {
- ChatEntry::Assistant(message) => {
- message.blocks.iter().rev().find_map(|block| match block {
- MessageBlock::Text(text) => Some(text.clone()),
- MessageBlock::Thinking(_) => None,
- })
- }
- _ => None,
- });
+ self.last_assistant_text = last_assistant_text_of(&reconstructed.chat);
self.pending_queue = Some(reconstructed.queued);
self.pending_snapshot = Some(reconstructed.chat);
self.loader_anchor_ms = reconstructed.last_user_prompt_ms;
@@ -526,6 +517,15 @@ impl SessionUi {
// The rebuild's first frame materializes the visible window; arm the
// post-frame trim so its wrap/render churn returns too.
self.trim_after_frame = true;
+ self.transcript_epoch = self.transcript_epoch.wrapping_add(1);
+ self.transcript_backfill = None;
+ self.backfill_seam = reconstructed.backfill_seam;
+ self.backfill_compaction_count = attach.snapshot["state"]["compactionCount"].as_u64();
+ self.backfill_leaf_id = attach.snapshot["state"]["leafId"]
+ .as_str()
+ .map(str::to_owned);
+ self.pending_backfill =
+ Some(reconstructed.history_before).filter(|history_before| *history_before > 0);
Ok(())
}
@@ -777,3 +777,103 @@ impl SessionUi {
resume_hint_from_stats(&stats.ok()?.ok()?)
}
}
+
+#[cfg(all(test, unix))]
+mod backfill_tests {
+ use super::*;
+ use serde_json::json;
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+ #[tokio::test]
+ async fn a_rebuild_rejects_an_already_queued_backfill_note() {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ let dir = tempfile::tempdir().unwrap();
+ let socket = dir.path().join("backfill.sock");
+ let listener = tokio::net::UnixListener::bind(&socket).unwrap();
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ let (read, mut write) = stream.into_split();
+ write.write_all(b"{\"type\":\"daemon_hello\",\"protocol\":{\"name\":\"prime-agent.daemon\",\"version\":7},\"serverCapabilities\":[],\"clientId\":\"mock\"}\n").await.unwrap();
+ let mut lines = BufReader::new(read).lines();
+ while let Some(line) = lines.next_line().await.unwrap() {
+ let request: Value = serde_json::from_str(&line).unwrap();
+ let kind = request["command"]["type"].as_str().unwrap();
+ let data = match kind {
+ "attach" => json!({
+ "activeSessionId": "s1", "snapshot": {
+ "activeSessionId": "s1", "summary": {"id": "s1", "cwd": "/tmp"},
+ "state": {"sessionId": "s1", "cwd": "/tmp", "isStreaming": false},
+ "messages": [], "historyBefore": 1, "lastEventSequence": 0,
+ }, "replay": {"status": "complete", "toSequence": 0},
+ "lastEventSequence": 0,
+ }),
+ "get_messages" => {
+ json!({"messages": [{"role": "user", "content": "rebuilt transcript", "timestamp": 1}]})
+ }
+ _ => json!({}),
+ };
+ let mut reply = serde_json::to_vec(&json!({
+ "type": "response", "id": request["id"], "command": kind,
+ "success": true, "data": data,
+ }))
+ .unwrap();
+ reply.push(b'\n');
+ write.write_all(&reply).await.unwrap();
+ }
+ });
+ let mut options =
+ crate::interactive::tests::options(crate::interactive::ModelSelection::default());
+ options.socket_path = socket.clone();
+ options.session = SessionSelection::Attach("s1".to_string());
+ let (client, _events) = DaemonClient::connect(&socket).await.unwrap();
+ let (backfill_tx, mut backfill_rx) = mpsc::unbounded_channel();
+ let mut session = SessionUi::open(
+ client,
+ &options,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ mpsc::unbounded_channel().0,
+ ActivityUpdates {
+ heartbeats: mpsc::unbounded_channel().0,
+ bash: mpsc::unbounded_channel().0,
+ factory: mpsc::unbounded_channel().0,
+ commands: mpsc::unbounded_channel().0,
+ },
+ backfill_tx.clone(),
+ )
+ .await
+ .unwrap();
+ let old_epoch = session.transcript_epoch;
+ assert!(backfill_tx
+ .send(TranscriptBackfillNote {
+ epoch: old_epoch,
+ entries: Ok(crate::snapshot::transcript_to_entries(&[
+ json!({"role": "user", "content": "stale history", "timestamp": 0}),
+ ])),
+ })
+ .is_ok());
+ let mut view = AgentView::new(crate::theme::Theme::builtin(
+ "prime",
+ crate::theme::ColorMode::TrueColor,
+ ));
+ session.rebuild_transcript(&mut view).await;
+ assert_ne!(session.transcript_epoch, old_epoch);
+ assert_eq!(view.chat.len(), 1, "rebuild applied the current transcript");
+ let expected = view.chat.clone();
+ // Deliver the note that was demonstrably queued before the real rebuild.
+ session.apply_transcript_backfill(backfill_rx.try_recv().unwrap(), &mut view);
+ assert_eq!(
+ view.chat, expected,
+ "an obsolete queued page cannot prepend rows after rebuild"
+ );
+ drop(session);
+ server.abort();
+ }).await.expect("mock session open, rebuild and stale-note delivery complete within ten seconds");
+ }
+}
diff --git a/crates/pa-tui/src/snapshot.rs b/crates/pa-tui/src/snapshot.rs
index 9af7fcaeb2..7b67c83724 100644
--- a/crates/pa-tui/src/snapshot.rs
+++ b/crates/pa-tui/src/snapshot.rs
@@ -79,6 +79,8 @@ pub struct Reconstructed {
/// The session's effective service tier (`state.serviceTier`), the
/// `/fast` toggle's baseline.
pub service_tier: Option<String>,
+ pub history_before: usize,
+ pub(crate) backfill_seam: BackfillSeam,
}
impl Reconstructed {
@@ -219,8 +221,21 @@ fn order_messages_for_transcript(messages: &[Value]) -> Vec<&Value> {
/// Replay a whole transcript, folding `toolResult` messages onto their
/// pending cards; one id-to-index map keeps the fold linear.
+#[must_use]
pub fn transcript_to_entries(messages: &[Value]) -> Vec<ChatEntry> {
+ transcript_with_backfill_seam(messages).0
+}
+
+#[derive(Debug, Clone, Copy, Default)]
+pub(crate) enum BackfillSeam {
+ #[default]
+ Preserve,
+ RetryOutcome,
+}
+
+fn transcript_with_backfill_seam(messages: &[Value]) -> (Vec<ChatEntry>, BackfillSeam) {
let ordered = order_messages_for_transcript(messages);
+ let mut seam = BackfillSeam::Preserve;
let mut chat: Vec<ChatEntry> = Vec::new();
let mut card_index: HashMap<String, Vec<usize>> = HashMap::new();
for message in ordered {
@@ -246,8 +261,10 @@ pub fn transcript_to_entries(messages: &[Value]) -> Vec<ChatEntry> {
&& message.get("customType").and_then(Value::as_str)
== Some(crate::custom_message::PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE)
{
- while chat.last().is_some_and(is_superseded_attempt_row) {
- chat.pop();
+ pop_superseded_attempts(&mut chat);
+ if chat.is_empty() {
+ // This outcome also supersedes attempts in the omitted prefix.
+ seam = BackfillSeam::RetryOutcome;
}
}
let first_new = chat.len();
@@ -261,7 +278,7 @@ pub fn transcript_to_entries(messages: &[Value]) -> Vec<ChatEntry> {
}
}
}
- chat
+ (chat, seam)
}
/// Settle one result onto the LAST pending card among `indices` (the
@@ -314,12 +331,24 @@ fn orphan_card(result: ToolResultReplay) -> ChatEntry {
}))
}
+fn pop_superseded_attempts(chat: &mut Vec<ChatEntry>) {
+ while chat.last().is_some_and(is_superseded_attempt_row) {
+ chat.pop();
+ }
+}
+
+pub(crate) fn join_backfilled_entries(head: &mut Vec<ChatEntry>, seam: BackfillSeam) {
+ if matches!(seam, BackfillSeam::RetryOutcome) {
+ pop_superseded_attempts(head);
+ }
+}
+
pub fn reconstruct(attach: &AttachData) -> Reconstructed {
let snapshot = &attach.snapshot;
- let messages = snapshot
+ let (messages, backfill_seam) = snapshot
.get("messages")
.and_then(Value::as_array)
- .map(|messages| transcript_to_entries(messages))
+ .map(|messages| transcript_with_backfill_seam(messages))
.unwrap_or_default();
let state = snapshot.get("state");
let (model_id, model_provider) = state
@@ -386,20 +415,25 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
.and_then(|state| state.get("serviceTier"))
.and_then(Value::as_str)
.map(str::to_string);
- let last_user_prompt_ms =
- snapshot
- .get("messages")
- .and_then(Value::as_array)
- .and_then(|messages| {
- messages
- .iter()
- .rev()
- .find(|message| {
- message.get("role").and_then(Value::as_str) == Some("user")
- && message_timestamp_ms(message).is_some()
- })
- .and_then(message_timestamp_ms)
- });
+ let history_before = snapshot
+ .get("historyBefore")
+ .and_then(Value::as_u64)
+ .map_or(0, |history| history as usize);
+ let last_user_prompt_ms = snapshot
+ .get("messages")
+ .and_then(Value::as_array)
+ .and_then(|messages| {
+ messages.iter().rev().find_map(|message| {
+ (message.get("role").and_then(Value::as_str) == Some("user"))
+ .then(|| message_timestamp_ms(message))
+ .flatten()
+ })
+ })
+ .or_else(|| {
+ (history_before > 0)
+ .then(|| snapshot.get("lastUserPromptMs").and_then(Value::as_u64))
+ .flatten()
+ });
Reconstructed {
chat: messages,
model_id,
@@ -415,6 +449,8 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
queued,
service_tier,
last_user_prompt_ms,
+ history_before,
+ backfill_seam,
}
}
@@ -429,10 +465,9 @@ fn message_timestamp_ms(message: &Value) -> Option<u64> {
.filter(|value| value.is_finite())
.map(|value| value.max(0.0) as u64)
}),
- Some(Value::String(iso)) => {
- let ms = crate::agents_view_state::timestamp_ms(Some(iso));
- (ms > 0).then_some(ms as u64)
- }
+ Some(Value::String(iso)) => pa_types::incident::timestamp_to_ms(iso)
+ .filter(|ms| *ms > 0)
+ .map(|ms| ms as u64),
_ => None,
}
}
diff --git a/crates/pa-tui/src/snapshot/tests.rs b/crates/pa-tui/src/snapshot/tests.rs
index de7e83a1a5..b0bc7831f8 100644
--- a/crates/pa-tui/src/snapshot/tests.rs
+++ b/crates/pa-tui/src/snapshot/tests.rs
@@ -2160,3 +2160,178 @@ fn elided_image_tool_results_render_their_marker_metadata() {
}
mod thinking_pins;
+
+#[test]
+fn a_windowed_snapshot_reconstructs_the_full_history_scalars() {
+ let mut full = slim_attach();
+ full["snapshot"]["messages"] = json!([
+ { "role": "user", "content": "head prompt", "timestamp": 100u64 },
+ { "role": "assistant", "content": [{ "type": "text", "text": "old answer" }], "timestamp": 110u64 },
+ { "role": "assistant", "content": [{ "type": "text", "text": "settled answer" }], "timestamp": 120u64 },
+ ]);
+ let mut windowed = full.clone();
+ windowed["snapshot"]["messages"] = json!([
+ { "role": "assistant", "content": [{ "type": "text", "text": "old answer" }], "timestamp": 110u64 },
+ { "role": "assistant", "content": [{ "type": "text", "text": "settled answer" }], "timestamp": 120u64 },
+ ]);
+ windowed["snapshot"]["historyBefore"] = json!(1u64);
+ windowed["snapshot"]["lastUserPromptMs"] = json!(100u64);
+
+ let full_prompt_ms = reconstruct(&attach_data_from_response(full).unwrap()).last_user_prompt_ms;
+ let windowed_prompt_ms =
+ reconstruct(&attach_data_from_response(windowed).unwrap()).last_user_prompt_ms;
+ assert_eq!(full_prompt_ms, Some(100));
+ assert_eq!(windowed_prompt_ms, full_prompt_ms);
+}
+
+fn comparable(entries: &[ChatEntry]) -> Vec<ChatEntry> {
+ entries
+ .iter()
+ .cloned()
+ .map(|mut entry| {
+ if let ChatEntry::Tool(card) = &mut entry {
+ card.started_at = None;
+ card.ended_at = None;
+ }
+ entry
+ })
+ .collect()
+}
+
+fn joined_matches_full(full: &[Value], cut: usize) {
+ let expected = comparable(&transcript_to_entries(full));
+ let (tail_entries, seam) = transcript_with_backfill_seam(&full[cut..]);
+ let mut joined = transcript_to_entries(&full[..cut]);
+ join_backfilled_entries(&mut joined, seam);
+ joined.extend(tail_entries);
+ assert_eq!(comparable(&joined), expected, "cut {cut}: {joined:?}");
+}
+
+#[test]
+fn backfilled_entries_match_the_full_decode_across_the_seam() {
+ let user = |text: &str| json!({ "role": "user", "content": text, "timestamp": 1u64 });
+ let answer = |text: &str| json!({ "role": "assistant", "content": [{ "type": "text", "text": text }], "timestamp": 2u64 });
+ let tool_call = json!({
+ "role": "assistant",
+ "content": [{ "type": "toolCall", "id": "call-1", "name": "bash", "arguments": { "command": "ls" } }],
+ "timestamp": 4u64,
+ });
+ let tool_result = json!({
+ "role": "toolResult", "toolCallId": "call-1", "toolName": "bash",
+ "content": [{ "type": "text", "text": "output" }], "isError": false, "timestamp": 5u64,
+ });
+ let summary = json!({
+ "role": "compactionSummary", "summary": "the story",
+ "retainedMessageCount": 2, "tokensBefore": 12, "timestamp": 3u64,
+ });
+ joined_matches_full(&[user("one"), answer("a"), user("two"), answer("b")], 2);
+ joined_matches_full(&[user("one"), tool_call, tool_result, answer("done")], 1);
+ joined_matches_full(
+ &[summary, user("kept one"), user("kept two"), answer("after")],
+ 3,
+ );
+}
+
+#[test]
+fn backfilled_entries_collapse_a_seam_split_retry_episode() {
+ let attempt = |n: u64| {
+ json!({
+ "role": "assistant", "content": [], "stopReason": "error",
+ "errorMessage": format!("attempt {n} failed"), "timestamp": n,
+ })
+ };
+ let outcome = || {
+ json!({
+ "role": "custom", "customType": "provider_retry_outcome",
+ "content": "Recovered after retries", "display": true,
+ "details": { "success": true }, "timestamp": 9u64,
+ })
+ };
+ let user = |text: &str| json!({ "role": "user", "content": text, "timestamp": 1u64 });
+ let answer = |text: &str| json!({ "role": "assistant", "content": [{ "type": "text", "text": text }], "timestamp": 20u64 });
+ joined_matches_full(
+ &[
+ user("run"),
+ attempt(2),
+ attempt(3),
+ outcome(),
+ answer("done"),
+ ],
+ 3,
+ );
+ joined_matches_full(
+ &[
+ user("run"),
+ attempt(2),
+ attempt(3),
+ attempt(4),
+ outcome(),
+ answer("done"),
+ ],
+ 2,
+ );
+ joined_matches_full(
+ &[
+ user("run"),
+ attempt(2),
+ attempt(3),
+ user("next turn"),
+ answer("later"),
+ ],
+ 3,
+ );
+}
+
+#[test]
+fn backfill_preserves_errors_before_an_unrelated_status() {
+ let attempt = |n: u64| {
+ json!({
+ "role": "assistant", "content": [], "stopReason": "error",
+ "errorMessage": format!("attempt {n} failed"), "timestamp": n,
+ })
+ };
+ let outcome = json!({
+ "role": "custom", "customType": "compaction_outcome", "display": true,
+ "content": "Compaction cancelled", "details": { "cancelled": true },
+ "timestamp": 9u64,
+ });
+ joined_matches_full(&[attempt(1), outcome.clone()], 1);
+ joined_matches_full(&[attempt(1), attempt(2), outcome.clone()], 1);
+ // An empty assistant is a legal worker cut but renders no row, exposing
+ // the unrelated custom status as the first entry of the tail.
+ let empty = json!({ "role": "assistant", "content": [], "stopReason": "stop" });
+ joined_matches_full(&[attempt(1), empty, outcome], 1);
+}
+
+#[test]
+fn windowed_prompt_time_prefers_the_readable_tail_over_an_older_scalar() {
+ for timestamp in [
+ json!(2000.75),
+ json!("1970-01-01T00:00:02.000Z"),
+ json!("1970-01-01T01:00:02.000+01:00"),
+ ] {
+ let mut data = slim_attach();
+ data["snapshot"]["historyBefore"] = json!(1);
+ data["snapshot"]["lastUserPromptMs"] = json!(1000);
+ data["snapshot"]["messages"] = json!([
+ { "role": "user", "content": "latest", "timestamp": timestamp }
+ ]);
+ let mut full = data.clone();
+ full["snapshot"]
+ .as_object_mut()
+ .unwrap()
+ .remove("historyBefore");
+ full["snapshot"]
+ .as_object_mut()
+ .unwrap()
+ .remove("lastUserPromptMs");
+ assert_eq!(
+ reconstruct(&attach_data_from_response(full).unwrap()).last_user_prompt_ms,
+ Some(2000)
+ );
+ assert_eq!(
+ reconstruct(&attach_data_from_response(data).unwrap()).last_user_prompt_ms,
+ Some(2000)
+ );
+ }
+}
diff --git a/crates/pa-tui/src/view.rs b/crates/pa-tui/src/view.rs
index ee3303a15c..05ca63a590 100644
--- a/crates/pa-tui/src/view.rs
+++ b/crates/pa-tui/src/view.rs
@@ -473,6 +473,46 @@ impl AgentView {
self.push_entry(entry);
}
+ pub fn prepend_entries(&mut self, entries: Vec<ChatEntry>) {
+ let count = entries.len();
+ if count == 0 {
+ return;
+ }
+ self.pending_handoff = None;
+ let seam_before = if self.layout_width > 0 && !self.chat.is_empty() {
+ self.count_entry_rows(0, self.layout_width)
+ } else {
+ 0
+ };
+ self.reanchor_paused_window_for_prepend();
+ let cursor_spacing_before = self.prepend_cursor_spacing(0);
+ self.chat.splice(0..0, entries);
+ self.entry_layout
+ .splice(0..0, std::iter::repeat_n([None, None, None], count));
+ self.entry_heights
+ .splice(0..0, std::iter::repeat_n([None, None, None], count));
+ {
+ let mut caches = self.md_caches.borrow_mut();
+ let shifted: std::collections::HashMap<usize, crate::markdown::MarkdownBlockCache> =
+ caches
+ .drain()
+ .map(|(index, cache)| (index + count, cache))
+ .collect();
+ *caches = shifted;
+ }
+ self.sparse_entries = self
+ .sparse_entries
+ .iter()
+ .map(|index| index + count)
+ .collect();
+ self.toggled_cards = self
+ .toggled_cards
+ .iter()
+ .map(|index| index + count)
+ .collect();
+ self.note_prepended_entries(count, seam_before, cursor_spacing_before);
+ }
+
/// Drop the whole transcript and its cached layout (a fresh snapshot
/// rebuild re-renders every row).
pub fn clear_chat(&mut self) {
@@ -699,6 +739,8 @@ fn item_to_entry(item: TranscriptItem) -> ChatEntry {
}
}
+#[cfg(test)]
+mod prepend_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
diff --git a/crates/pa-tui/src/view/lazy.rs b/crates/pa-tui/src/view/lazy.rs
index 81453672ee..95f7c0feeb 100644
--- a/crates/pa-tui/src/view/lazy.rs
+++ b/crates/pa-tui/src/view/lazy.rs
@@ -121,6 +121,105 @@ impl AgentView {
self.sparse_window = Some(window);
}
+ pub(super) fn reanchor_paused_window_for_prepend(&mut self) {
+ let Some(mut window) = self.sparse_window.take() else {
+ if !self.following && self.layout_width > 0 && !self.chat.is_empty() {
+ let sparse = self.sparse_enabled;
+ let old_rows = self.layout_pass(self.layout_width).total;
+ self.sparse_enabled = sparse;
+ if self.has_selection() {
+ self.rebase_top_selection_to_tail(old_rows);
+ }
+ let distance = old_rows
+ .saturating_sub(self.scroll_top)
+ .saturating_sub(self.window_rows);
+ self.sparse_window = Some(SparseWindow {
+ anchor: Anchor::Tail(distance),
+ detail: self.detail,
+ width: self.layout_width,
+ visible_rows: 0,
+ cursor: None,
+ pending: 0,
+ });
+ }
+ return;
+ };
+ let Anchor::Top(offset) = window.anchor else {
+ self.sparse_window = Some(window);
+ return;
+ };
+ let sparse = self.sparse_enabled;
+ let old_rows = self.layout_pass(self.layout_width).total;
+ self.sparse_enabled = sparse;
+ if self.has_selection() {
+ self.rebase_top_selection_to_tail(old_rows);
+ }
+ window.anchor = Anchor::Tail(
+ old_rows
+ .saturating_sub(offset)
+ .saturating_sub(self.window_rows),
+ );
+ self.sparse_window = Some(window);
+ }
+
+ /// A spacing-driven cursor can look past hidden assistant entries to the
+ /// prepended head, even when it is not on the first entry. Only its leading
+ /// blank can change; preserve the content row without measuring the history.
+ pub(super) fn prepend_cursor_spacing(&self, prepended: usize) -> Option<bool> {
+ let (section, _) = self.sparse_window?.cursor?;
+ let index = section.checked_sub(1)? + prepended;
+ matches!(
+ self.chat.get(index)?,
+ crate::chat::ChatEntry::Tool(_)
+ | crate::chat::ChatEntry::AgentMessage(_)
+ | crate::chat::ChatEntry::ShellCompletion(_)
+ )
+ .then(|| self.conversation_leading(index, self.entry_detail(index).tool_output_expanded()))
+ }
+
+ pub(super) fn note_prepended_entries(
+ &mut self,
+ count: usize,
+ seam_before: usize,
+ cursor_spacing_before: Option<bool>,
+ ) {
+ if self.layout_width == 0 {
+ return;
+ }
+ if let Some((index, rows)) = self.sparse_mutation {
+ self.sparse_mutation = Some((index + count, rows));
+ }
+ let cursor_spacing_after = self.prepend_cursor_spacing(count);
+ let Some(mut window) = self.sparse_window.take() else {
+ return;
+ };
+ let seam_after = if self.chat.len() > count {
+ self.count_entry_rows(count, self.layout_width)
+ } else {
+ 0
+ };
+ window.cursor = match window.cursor.take() {
+ Some((0, _)) if self.chat.len() > count => {
+ Some((count + 1, seam_after.saturating_sub(seam_before)))
+ }
+ Some((0, row)) => Some((0, row)),
+ Some((1, row)) if self.chat.len() > count => {
+ Some((count + 1, (row + seam_after).saturating_sub(seam_before)))
+ }
+ Some((section, row)) => {
+ let row = match cursor_spacing_before.zip(cursor_spacing_after) {
+ Some((before, after)) => {
+ (row + usize::from(after)).saturating_sub(usize::from(before))
+ }
+ None => row,
+ };
+ Some((section + count, row))
+ }
+ None => None,
+ };
+ self.sparse_window = Some(window);
+ }
+
/// The delta of a just-appended entry, countable because the push
/// landed.
pub(super) fn sparse_note_append(&mut self) {
diff --git a/crates/pa-tui/src/view/prepend_tests.rs b/crates/pa-tui/src/view/prepend_tests.rs
new file mode 100644
index 0000000000..fbf28de15a
--- /dev/null
+++ b/crates/pa-tui/src/view/prepend_tests.rs
@@ -0,0 +1,222 @@
+use super::*;
+use crate::chat::{AssistantMessage, MessageBlock};
+use crate::theme::{ColorMode, Theme};
+
+fn view() -> AgentView {
+ AgentView::new(Theme::builtin("prime", ColorMode::TrueColor))
+}
+
+fn assistant_entry(text: &str) -> ChatEntry {
+ ChatEntry::Assistant(Box::new(AssistantMessage {
+ blocks: vec![MessageBlock::Text(text.to_string())],
+ has_tool_calls: false,
+ streaming: false,
+ error: None,
+ aborted: false,
+ }))
+}
+
+fn body(prefix: &str, index: usize) -> ChatEntry {
+ assistant_entry(&format!(
+ "{prefix} body {index} {}",
+ "words ".repeat(index % 9)
+ ))
+}
+
+fn frame_text(frame: &[crate::Line]) -> String {
+ frame
+ .iter()
+ .map(|line| {
+ line.iter()
+ .map(|span| span.content.as_str())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+#[test]
+fn prepended_history_keeps_a_paused_tail_window() {
+ let mut sparse = view();
+ sparse.splash_suppressed = true;
+ let mut full = view();
+ full.sparse_enabled = false;
+ full.splash_suppressed = true;
+ let head: Vec<ChatEntry> = (0..120).map(|index| body("head", index)).collect();
+ for entry in head.iter().cloned() {
+ full.push_entry(entry);
+ }
+ for index in 0..300 {
+ let entry = body("tail", index);
+ sparse.push_entry(entry.clone());
+ full.push_entry(entry);
+ }
+ let card = super::expansion::tests::finished_tool_card("card-b", "beta");
+ sparse.push_entry(card.clone());
+ full.push_entry(card);
+ sparse.toggle_card_expansion(300);
+ full.toggle_card_expansion(300 + head.len());
+
+ sparse.render_frame(37, 24);
+ full.render_frame(37, 24);
+ sparse.scroll_by(-120);
+ full.resolve_sparse_geometry();
+ full.sparse_enabled = false;
+ full.scroll_by(-120);
+ full.resolve_sparse_geometry();
+ full.sparse_enabled = false;
+ assert_eq!(
+ sparse.render_frame(37, 24),
+ full.render_frame(37, 24),
+ "the paused window matches the full rebuild before the prepend"
+ );
+
+ let mut dense = view();
+ dense.splash_suppressed = true;
+ for index in 0..300 {
+ dense.push_entry(body("tail", index));
+ }
+ dense.push_entry(super::expansion::tests::finished_tool_card(
+ "card-b", "beta",
+ ));
+ dense.toggle_card_expansion(300);
+ dense.render_frame(37, 24);
+ dense.scroll_by(-120);
+ dense.resolve_sparse_geometry();
+ dense.sparse_enabled = false;
+ dense.prepend_entries((0..120).map(|index| body("head", index)).collect());
+ assert_eq!(
+ dense.render_frame(37, 24),
+ full.render_frame(37, 24),
+ "a resolved dense window keeps its content across the prepend"
+ );
+
+ sparse.prepend_entries(head);
+ assert_eq!(
+ sparse.render_frame(37, 24),
+ full.render_frame(37, 24),
+ "the paused window and the toggled card keep their content across the prepend"
+ );
+
+ sparse.scroll_to_top();
+ full.scroll_to_top();
+ full.sparse_window = None;
+ full.resolve_sparse_geometry();
+ full.sparse_enabled = false;
+ assert_eq!(
+ sparse.render_frame(37, 24),
+ full.render_frame(37, 24),
+ "the true top renders after the prepend"
+ );
+ assert!(
+ frame_text(&sparse.render_frame(37, 24)).contains("head body 0"),
+ "the prepended head's first row is reachable"
+ );
+
+ let mut empty = view();
+ empty.render_frame(37, 24);
+ empty.prepend_entries(vec![body("head", 0)]);
+ assert_eq!(
+ empty.chat_len(),
+ 1,
+ "a prepend into an empty chat lands without a seam panic"
+ );
+}
+
+#[test]
+fn prepended_history_keeps_a_top_anchored_window() {
+ let mut sparse = view();
+ sparse.splash_suppressed = true;
+ let head: Vec<ChatEntry> = (0..80).map(|index| body("head", index)).collect();
+ sparse.push_entry(ChatEntry::User {
+ text: "the tail opens\nwith a user row".to_string(),
+ });
+ for index in 0..200 {
+ sparse.push_entry(body("tail", index));
+ }
+ sparse.render_frame(37, 24);
+ sparse.scroll_to_top();
+ let home = sparse.render_frame(37, 24);
+ assert!(
+ frame_text(&home).contains("the tail opens"),
+ "the home window renders the tail's first row: {home:?}"
+ );
+
+ sparse.prepend_entries(head);
+ assert_eq!(
+ sparse.render_frame(37, 24),
+ home,
+ "the home window keeps its content across the prepend"
+ );
+
+ sparse.scroll_to_top();
+ let true_top = frame_text(&sparse.render_frame(37, 24));
+ assert!(
+ true_top.contains("head body 0"),
+ "the true top renders the head's first row: {true_top}"
+ );
+ assert!(
+ !true_top.contains("the tail opens"),
+ "the top row is the head's first row: {true_top}"
+ );
+
+ let mut tool_first = view();
+ tool_first.splash_suppressed = true;
+ let mut tool_head: Vec<ChatEntry> = (0..80).map(|index| body("head", index)).collect();
+ tool_head.push(super::expansion::tests::finished_tool_card(
+ "card-a", "alpha",
+ ));
+ tool_first.push_entry(super::expansion::tests::finished_tool_card(
+ "card-b", "beta",
+ ));
+ for index in 0..200 {
+ tool_first.push_entry(body("tail", index));
+ }
+ tool_first.render_frame(37, 24);
+ tool_first.scroll_to_top();
+ tool_first.scroll_by(2);
+ let tool_home = tool_first.render_frame(37, 24);
+ assert!(
+ frame_text(&tool_home).contains("echo hi"),
+ "the tool-first tail renders from its top: {tool_home:?}"
+ );
+ tool_first.prepend_entries(tool_head);
+ assert_eq!(
+ tool_first.render_frame(37, 24),
+ tool_home,
+ "a shrinking seam entry keeps the paused window's content"
+ );
+}
+
+#[test]
+fn prepended_history_keeps_a_paused_tool_after_hidden_entries() {
+ let mut paused = view();
+ paused.splash_suppressed = true;
+ // Empty assistant entries occupy no rows, but make the visible tool a
+ // later entry rather than the first entry handled by seam bookkeeping.
+ for _ in 0..3 {
+ paused.push_entry(assistant_entry(""));
+ }
+ paused.push_entry(super::expansion::tests::finished_tool_card(
+ "visible-tool",
+ "visible result",
+ ));
+ for index in 0..200 {
+ paused.push_entry(body("tail", index));
+ }
+ paused.render_frame(37, 24);
+ paused.scroll_to_top();
+ paused.scroll_by(2);
+ let before = paused.render_frame(37, 24);
+ assert!(frame_text(&before).contains("echo hi"));
+
+ paused.prepend_entries(vec![super::expansion::tests::finished_tool_card(
+ "older-tool",
+ "older result",
+ )]);
+ assert_eq!(
+ paused.render_frame(37, 24),
+ before,
+ "removing a leading spacer must preserve the visible tool's content row"
+ );
+}
diff --git a/crates/pa-tui/tests/windowed_backfill_headless.rs b/crates/pa-tui/tests/windowed_backfill_headless.rs
new file mode 100644
index 0000000000..3ff4931d17
--- /dev/null
+++ b/crates/pa-tui/tests/windowed_backfill_headless.rs
@@ -0,0 +1,759 @@
+#![cfg(unix)]
+
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+
+use pa_tui::interactive::{
+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,
+ SessionSelection, UiMode,
+};
+use serde_json::{json, Value};
+
+const HISTORY_MESSAGES: usize = 4;
+const HISTORY_LEAF_ID: &str = "attached-branch-leaf";
+
+enum RebuildResponse {
+ FullHistory,
+ Reject,
+}
+
+struct MockSupervisor {
+ listener: UnixListener,
+ windowed: bool,
+ failures: usize,
+ /// Hold the history backfill page instead of answering it: the plan then
+ /// leaves the request in flight across an exit or a transcript rebuild.
+ hold_backfill: bool,
+ rebuild_response: RebuildResponse,
+ validation_state: Option<Value>,
+ changed_prefix: bool,
+ history_leaf_id: Option<&'static str>,
+ requests: Arc<Mutex<Vec<Value>>>,
+}
+
+impl MockSupervisor {
+ fn bind(socket: &std::path::Path, windowed: bool, requests: Arc<Mutex<Vec<Value>>>) -> Self {
+ MockSupervisor {
+ listener: UnixListener::bind(socket).expect("bind mock socket"),
+ windowed,
+ failures: 0,
+ hold_backfill: false,
+ rebuild_response: RebuildResponse::FullHistory,
+ validation_state: Some(
+ json!({"compactionCount": 0, "sessionId": "sess-1", "activeSessionId": "s1"}),
+ ),
+ changed_prefix: false,
+ history_leaf_id: Some(HISTORY_LEAF_ID),
+ requests,
+ }
+ }
+
+ fn serve(mut self) {
+ let (stream, _) = self.listener.accept().expect("accept");
+ let mut writer = stream.try_clone().expect("clone mock socket");
+ let mut reader = BufReader::new(stream);
+ let mut held_backfill: Option<String> = None;
+
+ 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();
+ match command_type {
+ "attach" => {
+ write_json(&mut writer, &attach_response(id, self.windowed));
+ }
+ "get_connection_state" => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response", "id": id, "command": "get_connection_state",
+ "success": self.validation_state.is_some(),
+ "data": self.validation_state,
+ "error": if self.validation_state.is_none() { json!("validation rejected") } else { Value::Null },
+ }),
+ );
+ }
+ "get_messages" => {
+ self.requests.lock().unwrap().push(command.clone());
+ if self.failures > 0 {
+ self.failures -= 1;
+ write_json(&mut writer, &history_failure(id));
+ continue;
+ }
+ if command.get("before").is_some() {
+ if self.hold_backfill {
+ held_backfill = Some(id.to_string());
+ // The frame is proof the server received this request;
+ // the headless plan cannot leave or reload before it.
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "session_event", "activeSessionId": "s1",
+ "event": {"type": "message_end", "message": {
+ "role": "assistant", "content": [{"type": "text", "text": "backfill request received"}],
+ }},
+ }),
+ );
+ continue;
+ }
+ let mut response = get_messages_response(id, &self);
+ if self.changed_prefix {
+ // Simulate a compaction that happened before the prefix read,
+ // while its completion event has not yet been delivered.
+ response["data"]["messages"] = json!(all_messages()[4..8]);
+ }
+ write_json(&mut writer, &response);
+ continue;
+ }
+ if matches!(self.rebuild_response, RebuildResponse::Reject) {
+ write_json(&mut writer, &history_failure(id));
+ continue;
+ }
+ // A cursor-less fetch is a transcript rebuild. Release the
+ // obsolete response before it; the separate unit regression
+ // injects an already-queued note to verify the epoch fence.
+ if let Some(held) = held_backfill.take() {
+ write_json(&mut writer, &get_messages_response(&held, &self));
+ }
+ write_json(&mut writer, &whole_head_response(id));
+ }
+ "get_session_stats" => {
+ write_json(
+ &mut writer,
+ &success_response(
+ id,
+ "get_session_stats",
+ &json!({
+ "contextUsage": { "tokens": 1200, "contextWindow": 200_000 },
+ "cost": 0.01,
+ }),
+ ),
+ );
+ }
+ _ => {
+ write_json(&mut writer, &success_response(id, command_type, &json!({})));
+ }
+ }
+ }
+ }
+}
+
+fn history_failure(id: &str) -> Value {
+ json!({
+ "type": "response", "id": id, "command": "get_messages",
+ "success": false, "error": "temporary history rejection",
+ })
+}
+
+fn success_response(id: &str, command: &str, data: &Value) -> Value {
+ json!({
+ "type": "response", "id": id, "command": command,
+ "success": true, "data": 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");
+}
+
+fn message(index: usize) -> Value {
+ let marker = format!("msg-{index:02}");
+ let body =
+ format!("{marker} line one\n{marker} line two\n{marker} line three\n{marker} line four");
+ let timestamp = 100 + index;
+ if index.is_multiple_of(2) {
+ json!({ "role": "user", "content": body, "timestamp": timestamp })
+ } else {
+ json!({
+ "role": "assistant",
+ "content": [{ "type": "text", "text": body }],
+ "timestamp": timestamp,
+ })
+ }
+}
+
+fn all_messages() -> Vec<Value> {
+ (0..16).map(message).collect()
+}
+
+fn attach_response(id: &str, windowed: bool) -> Value {
+ let messages = all_messages();
+ let (snapshot_messages, history_before) = if windowed {
+ (messages[4..].to_vec(), json!(4u64))
+ } else {
+ (messages, Value::Null)
+ };
+ let mut snapshot = json!({
+ "activeSessionId": "s1",
+ "summary": { "id": "s1", "cwd": "/tmp" },
+ "state": {
+ "activeSessionId": "s1",
+ "cwd": "/tmp",
+ "sessionId": "sess-1",
+ "sessionName": "backfill probe",
+ "model": "faux-1",
+ "isStreaming": false,
+ "isCompacting": false,
+ "compactionCount": 0,
+ "leafId": HISTORY_LEAF_ID,
+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
+ },
+ "messages": snapshot_messages,
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ });
+ if windowed {
+ snapshot["historyBefore"] = history_before;
+ snapshot["lastUserPromptMs"] = json!(114u64);
+ }
+ json!({
+ "type": "response",
+ "id": id,
+ "command": "attach",
+ "success": true,
+ "data": {
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "activeSessionId": "s1",
+ "snapshot": snapshot,
+ "replay": { "status": "complete", "toSequence": 0 },
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ "client": { "id": "mock", "capabilities": [] },
+ },
+ })
+}
+
+fn get_messages_response(id: &str, supervisor: &MockSupervisor) -> Value {
+ let messages = if supervisor.windowed {
+ all_messages()[..4].to_vec()
+ } else {
+ Vec::new()
+ };
+ let mut response = json!({
+ "type": "response",
+ "id": id,
+ "command": "get_messages",
+ "success": true,
+ "data": { "messages": messages },
+ });
+ if let Some(history_leaf_id) = supervisor.history_leaf_id {
+ response["data"]["historyLeafId"] = json!(history_leaf_id);
+ }
+ response
+}
+
+fn whole_head_response(id: &str) -> Value {
+ json!({
+ "type": "response",
+ "id": id,
+ "command": "get_messages",
+ "success": true,
+ "data": { "messages": all_messages() },
+ })
+}
+
+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::Attach("s1".to_string()),
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: true,
+ theme: "prime".to_string(),
+ code_block_indent: " ".to_string(),
+ tree_filter_mode: String::new(),
+ branch_summary_skip_prompt: false,
+ version: "0.0.0".to_string(),
+ onboarding: None,
+ telemetry_disabled: None,
+ client_auth: None,
+ traces: None,
+ provider_auth: None,
+ update_commands: None,
+ telemetry: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ session_rlm_depth: None,
+ prompt_stash: std::sync::Arc::default(),
+ session_has_children: false,
+ restore_dock_focus: false,
+ client_settings: None,
+ }
+}
+
+fn run_attached(windowed: bool, steps: Vec<HeadlessStep>) -> (Vec<String>, Vec<Value>) {
+ run_attached_with_failures(windowed, /*failures*/ 0, steps)
+}
+
+fn run_attached_with_failures(
+ windowed: bool,
+ failures: usize,
+ steps: Vec<HeadlessStep>,
+) -> (Vec<String>, Vec<Value>) {
+ run_attached_with_validation(
+ windowed,
+ failures,
+ /*changed_prefix*/ false,
+ None,
+ Some(HISTORY_LEAF_ID),
+ steps,
+ )
+}
+
+fn run_attached_with_validation(
+ windowed: bool,
+ failures: usize,
+ changed_prefix: bool,
+ validation_state: Option<Value>,
+ history_leaf_id: Option<&'static str>,
+ steps: Vec<HeadlessStep>,
+) -> (Vec<String>, Vec<Value>) {
+ std::env::remove_var("TMUX");
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let mut supervisor = MockSupervisor::bind(&socket, windowed, Arc::clone(&requests));
+ supervisor.failures = failures;
+ supervisor.history_leaf_id = history_leaf_id;
+ if changed_prefix {
+ supervisor.validation_state = validation_state;
+ supervisor.changed_prefix = true;
+ }
+ 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,
+ width: 100,
+ height: 100,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let requests = requests.lock().unwrap().clone();
+ (outcome.frames, requests)
+}
+
+fn run_attached_holding_backfill(
+ windowed: bool,
+ rebuild_response: RebuildResponse,
+ height: u16,
+ steps: Vec<HeadlessStep>,
+) -> (Vec<String>, Vec<Value>) {
+ std::env::remove_var("TMUX");
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let mut supervisor = MockSupervisor::bind(&socket, windowed, Arc::clone(&requests));
+ supervisor.hold_backfill = true;
+ supervisor.rebuild_response = rebuild_response;
+ let (served_tx, served_rx) = std::sync::mpsc::channel::<()>();
+ let handle = std::thread::spawn(move || {
+ supervisor.serve();
+ let _ = served_tx.send(());
+ });
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps,
+ width: 100,
+ height,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ assert!(
+ outcome
+ .frames
+ .iter()
+ .any(|frame| frame.contains("backfill request received")),
+ "the plan observed the held request receipt"
+ );
+ assert!(
+ !outcome
+ .frames
+ .iter()
+ .any(|frame| frame.contains("timed out waiting")),
+ "readiness barriers completed without timeouts"
+ );
+ served_rx
+ .recv_timeout(std::time::Duration::from_secs(10))
+ .expect("the run returned, but the mock supervisor socket never closed: the obsolete transcript backfill task still holds the daemon connection");
+ handle.join().expect("mock supervisor finished");
+ let requests = requests.lock().unwrap().clone();
+ (outcome.frames, requests)
+}
+
+fn first_marker_line(frame: &str) -> Option<String> {
+ frame
+ .lines()
+ .find(|line| line.contains("msg-"))
+ .map(|line| {
+ line.split_whitespace()
+ .find(|word| word.starts_with("msg-"))
+ .expect("marker token")
+ .to_string()
+ })
+}
+
+/// The history rows a frame renders, top to bottom: one entry per row, since a
+/// row's body repeats its marker across wrapped lines.
+fn collapsed_markers(frame: &str) -> Vec<String> {
+ frame
+ .split_whitespace()
+ .filter(|token| token.starts_with("msg-"))
+ .fold(Vec::new(), |mut rows: Vec<String>, token| {
+ if rows.last().is_none_or(|last| last != token) {
+ rows.push(token.to_string());
+ }
+ rows
+ })
+}
+
+#[test]
+fn a_windowed_open_backfills_history_above_the_tail() {
+ let (frames, requests) = run_attached(
+ true,
+ vec![
+ HeadlessStep::WaitRender {
+ needle: "msg-00".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::ScrollTop,
+ HeadlessStep::WaitRender {
+ needle: "msg-00".to_string(),
+ timeout_ms: 5000,
+ },
+ ],
+ );
+ assert!(!frames.is_empty(), "frames were captured");
+ assert!(
+ frames[0].contains("msg-15"),
+ "the first frame renders the tail's bottom: {}",
+ frames[0]
+ );
+ assert!(
+ !frames[0].contains("msg-00"),
+ "the windowed first frame holds no head rows: {}",
+ frames[0]
+ );
+ let final_frame = frames.last().expect("the settled frame renders");
+ assert_eq!(
+ first_marker_line(final_frame).as_deref(),
+ Some("msg-00"),
+ "the true top renders the first message: {final_frame}"
+ );
+ assert_eq!(requests.len(), 1, "exactly one backfill request");
+ assert_eq!(
+ requests[0]["before"],
+ json!(HISTORY_MESSAGES as u64),
+ "the backfill requests the omitted history range"
+ );
+ assert_eq!(
+ requests[0]["historyLeafId"],
+ json!(HISTORY_LEAF_ID),
+ "the prefix request stays anchored to the attached branch"
+ );
+}
+
+#[test]
+fn an_unverified_history_leaf_echo_keeps_the_attached_tail_and_reports_incomplete_history() {
+ // An older worker omits the echo; a wrong echo belongs to another branch.
+ // Both otherwise return a successful prefix and matching session/compaction
+ // state, so only the branch-anchor validation can reject these responses.
+ for history_leaf_id in [None, Some("another-branch-leaf")] {
+ let (frames, requests) = run_attached_with_validation(
+ /*windowed*/ true,
+ /*failures*/ 0,
+ /*changed_prefix*/ false,
+ None,
+ history_leaf_id,
+ vec![HeadlessStep::WaitRender {
+ needle: "Older history could not be loaded".to_string(),
+ timeout_ms: 5000,
+ }],
+ );
+ assert_eq!(
+ requests.len(),
+ 1,
+ "unverified branch history is not retried"
+ );
+ assert!(
+ frames
+ .iter()
+ .any(|frame| frame.contains("Older history could not be loaded")),
+ "an absent or wrong history anchor must fail visibly: {history_leaf_id:?}"
+ );
+ assert_eq!(requests[0]["historyLeafId"], json!(HISTORY_LEAF_ID));
+ assert!(
+ !frames
+ .iter()
+ .any(|frame| frame.contains("timed out waiting")),
+ "the warning is an observed result, not a headless timeout"
+ );
+ assert!(
+ frames.iter().all(|frame| (0..HISTORY_MESSAGES)
+ .all(|index| !frame.contains(&format!("msg-{index:02}")))),
+ "no frame may expose the unverified prefix"
+ );
+ assert_eq!(
+ collapsed_markers(frames.last().expect("the warning frame renders")),
+ (HISTORY_MESSAGES..16)
+ .map(|index| format!("msg-{index:02}"))
+ .collect::<Vec<_>>(),
+ "the complete attached tail remains ordered and visible"
+ );
+ }
+}
+
+#[test]
+fn a_full_snapshot_attach_never_backfills() {
+ let (frames, requests) = run_attached(
+ false,
+ vec![
+ HeadlessStep::ScrollTop,
+ HeadlessStep::WaitRender {
+ needle: "msg-00".to_string(),
+ timeout_ms: 5000,
+ },
+ ],
+ );
+ assert!(!frames.is_empty(), "frames were captured");
+ assert!(
+ frames[0].contains("msg-15"),
+ "the full snapshot's first frame renders the tail: {}",
+ frames[0]
+ );
+ assert!(
+ frames.iter().any(|frame| frame.contains("msg-00")),
+ "the full history is reachable by scrolling"
+ );
+ assert!(
+ requests.is_empty(),
+ "a complete snapshot never backfills: {requests:?}"
+ );
+}
+
+#[test]
+fn a_rejected_backfill_retries_then_reports_incomplete_history() {
+ let (frames, requests) = run_attached_with_failures(
+ true,
+ /*failures*/ 2,
+ vec![HeadlessStep::WaitRender {
+ needle: "Older history could not be loaded".to_string(),
+ timeout_ms: 5000,
+ }],
+ );
+ assert!(frames
+ .iter()
+ .any(|frame| frame.contains("Older history could not be loaded")));
+ assert_eq!(requests.len(), 2);
+ assert_eq!(requests[0], requests[1]);
+}
+
+#[test]
+fn an_exit_with_backfill_in_flight_releases_the_daemon_connection() {
+ let (frames, requests) = run_attached_holding_backfill(
+ /*windowed*/ true,
+ RebuildResponse::FullHistory,
+ 30,
+ vec![HeadlessStep::WaitRender {
+ needle: "backfill request received".to_string(),
+ timeout_ms: 5000,
+ }],
+ );
+ assert_eq!(
+ requests.len(),
+ 1,
+ "the held history request stayed in flight across the run: {requests:?}"
+ );
+ assert_eq!(
+ requests[0]["before"],
+ json!(HISTORY_MESSAGES as u64),
+ "the windowed attach armed exactly the history backfill: {requests:?}"
+ );
+ assert!(!frames.is_empty(), "frames were captured");
+ assert!(
+ frames[0].contains("msg-15"),
+ "the windowed first frame renders the tail's bottom: {}",
+ frames[0]
+ );
+}
+
+#[test]
+fn a_reload_rebuild_during_an_in_flight_backfill_keeps_rows_unique_and_ordered() {
+ let (frames, requests) = run_attached_holding_backfill(
+ /*windowed*/ true,
+ RebuildResponse::FullHistory,
+ 50,
+ vec![
+ HeadlessStep::WaitRender {
+ needle: "backfill request received".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::Submit("/reload".to_string()),
+ HeadlessStep::WaitRender {
+ needle: "Reloaded keybindings, skills, prompts, themes".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::WaitGone {
+ needle: "backfill request received".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::ScrollTop,
+ HeadlessStep::WaitRender {
+ needle: "msg-00".to_string(),
+ timeout_ms: 5000,
+ },
+ ],
+ );
+ assert_eq!(
+ requests.len(),
+ 2,
+ "one held backfill page plus the reload's whole-head rebuild: {requests:?}"
+ );
+ assert_eq!(
+ requests[0]["before"],
+ json!(HISTORY_MESSAGES as u64),
+ "the backfill page carries the history cursor: {requests:?}"
+ );
+ assert!(
+ requests[1].get("before").is_none(),
+ "the rebuild fetches the whole head without a cursor: {requests:?}"
+ );
+ for (index, frame) in frames.iter().enumerate() {
+ let markers = collapsed_markers(frame);
+ assert!(
+ markers.windows(2).all(|pair| pair[0] < pair[1]),
+ "frame {index} renders a history row twice or out of order: {frame}"
+ );
+ }
+ let final_frame = frames.last().expect("the settled frame renders");
+ assert_eq!(
+ first_marker_line(final_frame).as_deref(),
+ Some("msg-00"),
+ "the rebuild's true top renders the first message: {final_frame}"
+ );
+}
+
+#[test]
+fn a_changed_or_unverifiable_prefix_is_rejected_before_the_compaction_event() {
+ for state in [
+ Some(json!({"compactionCount": 1, "sessionId": "sess-1", "activeSessionId": "s1"})),
+ Some(json!({"sessionId": "sess-1", "activeSessionId": "s1"})),
+ Some(json!({"compactionCount": 0, "sessionId": "replacement", "activeSessionId": "s1"})),
+ Some(
+ json!({"compactionCount": 0, "sessionId": "sess-1", "activeSessionId": "replacement"}),
+ ),
+ None,
+ ] {
+ let (frames, requests) = run_attached_with_validation(
+ /*windowed*/ true,
+ /*failures*/ 0,
+ /*changed_prefix*/ true,
+ state,
+ Some(HISTORY_LEAF_ID),
+ vec![HeadlessStep::WaitRender {
+ needle: "Older history could not be loaded".to_string(),
+ timeout_ms: 5000,
+ }],
+ );
+ for frame in &frames {
+ let markers = collapsed_markers(frame);
+ assert!(
+ markers.windows(2).all(|pair| pair[0] < pair[1]),
+ "the changed prefix must never duplicate existing tail rows: {frame}"
+ );
+ }
+ assert_eq!(requests.len(), 1, "one prefix read before validation");
+ assert!(
+ frames
+ .iter()
+ .any(|frame| frame.contains("Older history could not be loaded")),
+ "mismatched or unverified history is reported rather than silently prepended"
+ );
+ assert!(!frames
+ .iter()
+ .any(|frame| frame.contains("timed out waiting")));
+ }
+}
+
+#[test]
+fn a_failed_rebuild_reports_cancelled_incomplete_history() {
+ let (frames, requests) = run_attached_holding_backfill(
+ /*windowed*/ true,
+ RebuildResponse::Reject,
+ 100,
+ vec![
+ HeadlessStep::WaitRender {
+ needle: "backfill request received".to_string(),
+ timeout_ms: 5000,
+ },
+ HeadlessStep::Submit("/reload".to_string()),
+ HeadlessStep::WaitRender {
+ needle: "Transcript refresh failed; displayed history may be incomplete or stale"
+ .to_string(),
+ timeout_ms: 5000,
+ },
+ ],
+ );
+ assert_eq!(
+ requests.len(),
+ 2,
+ "held prefix and failed whole-history rebuild only"
+ );
+ assert_eq!(requests[0]["before"], json!(HISTORY_MESSAGES as u64));
+ assert!(
+ requests[1].get("before").is_none(),
+ "the cancelled positional cursor is never rearmed"
+ );
+ assert!(
+ frames.iter().any(|frame| frame
+ .contains("Transcript refresh failed; displayed history may be incomplete or stale")),
+ "a failed rebuild must disclose that older history is unavailable"
+ );
+ let last = frames.last().unwrap();
+ assert!(last.contains("msg-15"), "loaded tail stays visible");
+ assert!(!last.contains("msg-00"), "the held prefix was never loaded");
+}
diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs
index 2c8583a884..43101b8c06 100644
--- a/crates/pa-types/src/daemon/command.rs
+++ b/crates/pa-types/src/daemon/command.rs
@@ -599,6 +599,10 @@ pub enum DaemonCommand {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
active_session_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ before: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ capabilities: Option<Vec<DaemonClientCapability>>,
#[serde(flatten)]
rest: JsonMap,
},