Skip to content

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

Rust

TUI: scroll through the whole session with a windowed transcript (#3674)

Sebastian Müllere061c7ad9955
diff --git a/crates/pa-cli/tests/exit_backfill_pty_e2e.rs b/crates/pa-cli/tests/exit_backfill_pty_e2e.rs
index e0b6de2bc2..922c869666 100644
--- a/crates/pa-cli/tests/exit_backfill_pty_e2e.rs
+++ b/crates/pa-cli/tests/exit_backfill_pty_e2e.rs
@@ -45,8 +45,8 @@ 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 windowed attach's cursor sits this many messages into the history.
+const HISTORY_BEFORE: usize = 2_000;
/// The tail the snapshot carries: rows 0 and 8 are user rows (contiguous
/// needles; assistant rows carry SGR spans).
const TAIL_MESSAGES: usize = 9;
@@ -95,13 +95,108 @@ fn resume_does_not_wait_for_a_pending_backfill_page() {
leave_with_pending_backfill(b"/resume s2\r");
}
+/// The top key (shift+alt+up) as an escape sequence.
+const TOP_KEY: &[u8] = b"\x1b[1;4A";
+
+/// The top key as the last input: the terminal paints the key inline, so nothing but
+/// the loop's own wake starts the head page, and the session start must render.
+#[test]
+fn the_top_key_loads_the_session_start_as_the_last_input() {
+ let _lock = match HARNESS_LOCK.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ let held = Arc::new(AtomicUsize::new(0));
+ let served = Arc::new(AtomicUsize::new(0));
+ let mut harness = ExitBackfillHarness::start(Arc::clone(&held), Some(Arc::clone(&served)));
+ 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();
+ let mark = harness.output().len();
+ harness.write(TOP_KEY);
+ harness.master.wait_from(
+ mark,
+ b"SESSION-START-ROW",
+ "the session start after the top key",
+ );
+}
+
+/// Older pages the window keeps resident above the tail; one more evicts the
+/// chunk next to the tail.
+const RESIDENT_CHUNKS: usize = 3;
+const PAGE_UP: &[u8] = b"\x1b[5~";
+
+/// Scrolled far up, the resident rows are cut off from the tail: the exit flush
+/// writes the contiguous tail alone, without the far rows or the gap row, and
+/// requests no page on the way out.
+#[test]
+fn exit_flushes_the_tail_without_a_disjoint_resident_run() {
+ let _lock = match HARNESS_LOCK.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ let held = Arc::new(AtomicUsize::new(0));
+ let served = Arc::new(AtomicUsize::new(0));
+ let mut harness = ExitBackfillHarness::start(Arc::clone(&held), Some(Arc::clone(&served)));
+ harness.wait_from_start(KITTY_QUERY, "the kitty capability query");
+ harness.write(KITTY_ANSWER);
+ harness.wait_from_start(LAST_ROW, "the attach tail rendered");
+ for _ in 0..200 {
+ harness.write(PAGE_UP);
+ harness.master.drain_until_quiet(1);
+ if served.load(Ordering::SeqCst) > RESIDENT_CHUNKS {
+ break;
+ }
+ }
+ harness.settle();
+ let served_at_exit = served.load(Ordering::SeqCst);
+ assert!(
+ served_at_exit > RESIDENT_CHUNKS,
+ "the climb must load more older pages than stay resident (served {served_at_exit})"
+ );
+ let held_at_exit = held.load(Ordering::SeqCst);
+ let mark = harness.output().len();
+ harness.write(b"/exit\r");
+ assert_eq!(
+ harness.wait_child_exit(EXIT_BOUND),
+ Some(0),
+ "the exit completes"
+ );
+ harness.settle();
+ let output = harness.output();
+ let leave_at = mark
+ + find_subsequence(&output[mark..], ALT_SCREEN_LEAVE)
+ .expect("the exit left the alternate screen");
+ let flushed = &output[leave_at..];
+ assert!(
+ find_subsequence(flushed, FIRST_ROW).is_some()
+ && find_subsequence(flushed, LAST_ROW).is_some(),
+ "the flush carries the tail"
+ );
+ assert!(
+ find_subsequence(flushed, b"old row").is_none(),
+ "the flush drops the resident rows cut off from the tail:\n{}",
+ String::from_utf8_lossy(flushed)
+ );
+ assert!(
+ find_subsequence(flushed, b"Loading newer history").is_none(),
+ "the flush drops the gap row"
+ );
+ assert_eq!(
+ (served.load(Ordering::SeqCst), held.load(Ordering::SeqCst)),
+ (served_at_exit, held_at_exit),
+ "the exit requests no page"
+ );
+}
+
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));
+ let mut harness = ExitBackfillHarness::start(Arc::clone(&held), None);
harness.wait_from_start(KITTY_QUERY, "the kitty capability query");
harness.write(KITTY_ANSWER);
@@ -159,8 +254,8 @@ fn leave_with_pending_backfill(gesture: &[u8]) {
}
/// 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.
+/// windowed (it carries a page cursor), and the older-history page request
+/// is held forever; everything else answers promptly.
struct ExitBackfillHarness {
child: Child,
_server: std::thread::JoinHandle<()>,
@@ -168,10 +263,10 @@ struct ExitBackfillHarness {
}
impl ExitBackfillHarness {
- fn start(held: Arc<AtomicUsize>) -> ExitBackfillHarness {
+ fn start(held: Arc<AtomicUsize>, history: Option<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 supervisor = MockSupervisor::bind(&socket, held, history);
let server = std::thread::spawn(move || supervisor.serve());
let pty = openpty(
@@ -397,31 +492,38 @@ fn child_options(socket: PathBuf) -> InteractiveOptions {
}
/// 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.
+/// a windowed snapshot. Without `history`, every page request is held forever;
+/// with it, older pages are served and only newer pages are held. Every other
+/// request answers promptly.
struct MockSupervisor {
listener: std::os::unix::net::UnixListener,
held: Arc<AtomicUsize>,
+ history: Option<Arc<AtomicUsize>>,
}
impl MockSupervisor {
- fn bind(socket: &Path, held: Arc<AtomicUsize>) -> Self {
+ fn bind(socket: &Path, held: Arc<AtomicUsize>, history: Option<Arc<AtomicUsize>>) -> Self {
MockSupervisor {
listener: std::os::unix::net::UnixListener::bind(socket).expect("bind mock socket"),
held,
+ history,
}
}
fn serve(self) {
for stream in self.listener.incoming() {
match stream {
- Ok(stream) => Self::serve_connection(stream, &self.held),
+ Ok(stream) => Self::serve_connection(stream, &self.held, self.history.as_ref()),
Err(_) => return,
}
}
}
- fn serve_connection(stream: std::os::unix::net::UnixStream, held: &Arc<AtomicUsize>) {
+ fn serve_connection(
+ stream: std::os::unix::net::UnixStream,
+ held: &Arc<AtomicUsize>,
+ history: Option<&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);
@@ -455,10 +557,21 @@ impl MockSupervisor {
"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() => {
+ // With history served: an older page or the head page of `old row`s.
+ "get_messages"
+ if history.is_some()
+ && (command["page"]["from"] == "end"
+ || command["page"].get("after").is_none()) =>
+ {
+ history
+ .expect("history mode")
+ .fetch_add(1, Ordering::SeqCst);
+ write_json(&mut writer, &history_page(id, &command["page"]));
+ }
+ // A page request: counted and held — the run loop starts it
+ // from the windowed attach's cursor, and the exit must not
+ // wait for it.
+ "get_messages" if command.get("page").is_some() => {
held.fetch_add(1, Ordering::SeqCst);
}
_ => {
@@ -485,8 +598,43 @@ fn write_json(writer: &mut std::os::unix::net::UnixStream, value: &Value) {
writer.flush().expect("flush mock frame");
}
+/// One page over `HISTORY_BEFORE` messages `old row 0..`, ids `e<index>`: an
+/// older page, or the head page.
+fn history_page(id: &str, page: &Value) -> Value {
+ let cursor = |key: &str| {
+ page[key]
+ .as_str()
+ .and_then(|cursor| cursor[1..].parse::<usize>().ok())
+ };
+ let limit = page["limit"].as_u64().expect("page limit") as usize;
+ let (start, end) = if page["from"] == "end" {
+ let end = cursor("before").expect("older page cursor");
+ (end.saturating_sub(limit), end)
+ } else {
+ (0, limit.min(cursor("until").expect("head page bound")))
+ };
+ let messages: Vec<Value> = (start..end)
+ .map(|index| match index {
+ // A row the terminal's cell diff must write whole: it shares no cell with an
+ // `old row` line.
+ 0 => json!({ "role": "user", "content": "SESSION-START-ROW" }),
+ _ => json!({ "role": "user", "content": format!("old row {index}") }),
+ })
+ .collect();
+ json!({
+ "type": "response", "id": id, "command": "get_messages", "success": true,
+ "data": {
+ "messages": messages,
+ "firstEntryId": format!("e{start}"),
+ "lastEntryId": format!("e{}", end - 1),
+ "more": if page["from"] == "end" { start > 0 } else { end < HISTORY_BEFORE },
+ "historyLeafId": "attach-leaf",
+ },
+ })
+}
+
/// The attach snapshot: a small windowed tail over an unfinished older
-/// history (`historyBefore` > 0).
+/// history (its page cursor).
fn attach_data(id: &str) -> Value {
let messages: Vec<Value> = (0..TAIL_MESSAGES)
.map(|index| {
@@ -524,7 +672,7 @@ fn attach_data(id: &str) -> Value {
"sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
},
"messages": messages,
- "historyBefore": HISTORY_BEFORE,
+ "historyBeforeEntryId": format!("e{HISTORY_BEFORE}"),
"lastEventSequence": 0,
},
"replay": null,
diff --git a/crates/pa-cli/tests/transcript_window_e2e.rs b/crates/pa-cli/tests/transcript_window_e2e.rs
new file mode 100644
index 0000000000..817659542c
--- /dev/null
+++ b/crates/pa-cli/tests/transcript_window_e2e.rs
@@ -0,0 +1,429 @@
+// Casts: bounded fixture arithmetic.
+#![allow(
+ clippy::too_many_lines,
+ clippy::large_futures,
+ clippy::cast_possible_truncation
+)]
+
+//! Long-session transcript scrolling through a real daemon: a session file with
+//! thousands of rows and a compaction, attached headlessly and scrolled to the top.
+#![cfg(unix)]
+
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::time::{Duration, Instant};
+
+use pa_tui::interactive::{
+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,
+ SessionSelection, UiMode,
+};
+use pa_types::daemon::DaemonCommand;
+use serde_json::{json, Value};
+
+/// Turns in the fixture; each turn writes a user prompt, a tool-calling assistant
+/// message, its tool result, and a closing assistant message.
+const TURNS: usize = 900;
+/// The compaction lands after this turn and keeps the last ten turns before it.
+const COMPACTED_AFTER_TURN: usize = 600;
+const FIRST_KEPT_TURN: usize = 590;
+const SUMMARY_TEXT: &str = "fixture compaction summary";
+
+struct Supervisor {
+ child: Child,
+ socket: PathBuf,
+}
+
+impl Drop for Supervisor {
+ fn drop(&mut self) {
+ use std::io::{BufRead, BufReader, Write};
+ if let Ok(stream) = std::os::unix::net::UnixStream::connect(&self.socket) {
+ if let Ok(mut writer) = stream.try_clone() {
+ let mut reader = BufReader::new(stream);
+ let mut hello = String::new();
+ let _ = reader.read_line(&mut hello);
+ let command = json!({
+ "type": "command", "id": "test-shutdown",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "command": { "type": "shutdown" },
+ });
+ let _ = writeln!(writer, "{command}");
+ let _ = reader
+ .get_ref()
+ .set_read_timeout(Some(Duration::from_secs(5)));
+ let mut response = String::new();
+ let _ = reader.read_line(&mut response);
+ }
+ }
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+#[allow(clippy::zombie_processes)]
+fn spawn_supervisor(dir: &Path) -> Supervisor {
+ let socket = dir.join("daemon.sock");
+ let mut command = Command::new(env!("CARGO_BIN_EXE_prime-agent"));
+ command
+ .args(["--mode", "daemon", "--daemon-socket"])
+ .arg(&socket)
+ .env("PRIME_AGENT_CODING_AGENT_DIR", dir.join("agent"))
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ for var in [
+ pa_daemon::worker::WORKER_ROLE_ENV,
+ pa_daemon::worker::WORKER_TOKEN_ENV,
+ pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV,
+ pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV,
+ pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV,
+ pa_daemon::worker::WORKER_SOCKET_ENV,
+ pa_daemon::worker::WORKER_INSTANCE_ID_ENV,
+ pa_daemon::worker::WORKER_SCRIPT_ENV,
+ ] {
+ command.env_remove(var);
+ }
+ command.env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ );
+ let child = command.spawn().expect("spawn prime-agent --mode daemon");
+ let deadline = Instant::now() + Duration::from_secs(15);
+ while Instant::now() < deadline {
+ if socket.exists() {
+ return Supervisor { child, socket };
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ panic!("supervisor socket never appeared");
+}
+
+fn marker(turn: usize) -> String {
+ format!("turn-{turn:05}")
+}
+
+/// The fixture session file: `TURNS` tool-calling turns with one compaction.
+fn write_long_session(path: &Path, id: &str) {
+ let mut out = String::new();
+ let mut line = |value: Value| {
+ out.push_str(&value.to_string());
+ out.push('\n');
+ };
+ line(json!({
+ "type": "session", "version": 3, "id": id,
+ "timestamp": "2026-01-01T00:00:00.000Z", "cwd": "/tmp",
+ }));
+ let mut parent: Option<String> = None;
+ let mut counter = 0u32;
+ let mut entry = |parent: &mut Option<String>, body: Value| -> Value {
+ counter += 1;
+ let id = format!("{counter:08x}");
+ let mut value = json!({
+ "id": id, "parentId": parent.clone(),
+ "timestamp": "2026-01-01T00:00:00.000Z",
+ });
+ for (key, field) in body.as_object().expect("entry body") {
+ value[key] = field.clone();
+ }
+ *parent = Some(id);
+ value
+ };
+ let mut first_kept = String::new();
+ for turn in 0..TURNS {
+ let mark = marker(turn);
+ let ts = 1_000 + turn as u64 * 10;
+ let user = entry(
+ &mut parent,
+ json!({"type": "message", "message": {
+ "role": "user", "content": format!("{mark} question"), "timestamp": ts,
+ }}),
+ );
+ if turn == FIRST_KEPT_TURN {
+ first_kept = user["id"].as_str().expect("id").to_string();
+ }
+ line(user);
+ let call_id = format!("call-{turn}");
+ line(entry(
+ &mut parent,
+ json!({"type": "message", "message": {
+ "role": "assistant",
+ "content": [
+ {"type": "text", "text": format!("{mark} looking")},
+ {"type": "toolCall", "id": call_id, "name": "bash",
+ "arguments": {"command": format!("echo {mark}")}},
+ ],
+ "stopReason": "toolUse", "timestamp": ts + 1,
+ }}),
+ ));
+ line(entry(
+ &mut parent,
+ json!({"type": "message", "message": {
+ "role": "toolResult", "toolCallId": call_id, "toolName": "bash",
+ "content": [{"type": "text", "text": format!("{mark} output")}],
+ "isError": false, "timestamp": ts + 2,
+ }}),
+ ));
+ line(entry(
+ &mut parent,
+ json!({"type": "message", "message": {
+ "role": "assistant",
+ "content": [{"type": "text", "text": format!("{mark} answer")}],
+ "stopReason": "stop", "timestamp": ts + 3,
+ }}),
+ ));
+ if turn == COMPACTED_AFTER_TURN {
+ line(entry(
+ &mut parent,
+ json!({
+ "type": "compaction", "summary": SUMMARY_TEXT,
+ "firstKeptEntryId": first_kept, "tokensBefore": 123_456,
+ }),
+ ));
+ }
+ }
+ std::fs::write(path, out).expect("write long session");
+}
+
+async fn create_session_from_file(socket: &Path, dir: &Path, session_path: &Path) -> String {
+ let script_path = dir.join("script.json");
+ std::fs::write(&script_path, json!({ "responses": ["ok"] }).to_string()).expect("write script");
+ let (client, _events) = pa_tui::daemon_client::DaemonClient::connect(socket)
+ .await
+ .expect("connect supervisor");
+ let data = client
+ .request_ok(DaemonCommand::Create {
+ id: None,
+ session_path: Some(session_path.display().to_string()),
+ continue_recent: None,
+ no_session: None,
+ name: None,
+ config: Some(json!({
+ "cwd": dir.display().to_string(),
+ "sessionDir": session_path.parent().expect("session dir").display().to_string(),
+ "script": script_path.display().to_string(),
+ })),
+ telemetry_disabled: None,
+ runtime_metadata: None,
+ lifecycle: None,
+ env: None,
+ launch_env: None,
+ rest: serde_json::Map::default(),
+ })
+ .await
+ .expect("create session from file");
+ client.close();
+ data.get("activeSessionId")
+ .or_else(|| data.get("id"))
+ .and_then(Value::as_str)
+ .expect("session id")
+ .to_string()
+}
+
+fn chat_options(socket: &Path, dir: &Path, active: String) -> InteractiveOptions {
+ InteractiveOptions {
+ models: None,
+ socket_path: socket.to_path_buf(),
+ cwd: dir.to_path_buf(),
+ session_dir: None,
+ script_path: None,
+ model_selection: ModelSelection::default(),
+ model_catalog: Vec::new(),
+ model_configured_providers: std::collections::HashSet::default(),
+ model_recent_models: Vec::new(),
+ default_thinking_level: None,
+ no_session: false,
+ session: SessionSelection::Attach(active),
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: true,
+ theme: "prime".to_string(),
+ code_block_indent: " ".to_string(),
+ tree_filter_mode: String::new(),
+ branch_summary_skip_prompt: false,
+ version: "0.0.0".to_string(),
+ onboarding: None,
+ telemetry_disabled: None,
+ client_auth: None,
+ traces: None,
+ provider_auth: None,
+ update_commands: None,
+ telemetry: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ session_rlm_depth: None,
+ prompt_stash: std::sync::Arc::default(),
+ session_has_children: false,
+ restore_dock_focus: false,
+ client_settings: None,
+ }
+}
+
+struct LongSession {
+ _dir: tempfile::TempDir,
+ supervisor: Supervisor,
+ dir: PathBuf,
+ active: String,
+}
+
+async fn open_long_session() -> LongSession {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let session_dir = dir.path().join("agent").join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let supervisor = spawn_supervisor(dir.path());
+ let durable = "01a0tw-000000000001";
+ let path = session_dir.join(format!("{durable}.jsonl"));
+ write_long_session(&path, durable);
+ let active = create_session_from_file(&supervisor.socket, dir.path(), &path).await;
+ LongSession {
+ dir: dir.path().to_path_buf(),
+ _dir: dir,
+ supervisor,
+ active,
+ }
+}
+
+async fn run_plan(session: &LongSession, steps: Vec<HeadlessStep>, height: u16) -> Vec<String> {
+ let plan = HeadlessPlan {
+ steps,
+ width: 100,
+ height,
+ };
+ run_interactive(
+ chat_options(
+ &session.supervisor.socket,
+ &session.dir,
+ session.active.clone(),
+ ),
+ UiMode::Headless(plan),
+ )
+ .await
+ .expect("interactive run")
+ .frames
+}
+
+fn key(code: crossterm::event::KeyCode) -> HeadlessStep {
+ HeadlessStep::Key(crossterm::event::KeyEvent::new(
+ code,
+ crossterm::event::KeyModifiers::NONE,
+ ))
+}
+
+/// The turn markers of a frame, top to bottom, one per run of rows.
+fn turn_markers(frame: &str) -> Vec<usize> {
+ let mut seen: Vec<usize> = Vec::new();
+ for token in frame.split(|c: char| !c.is_ascii_alphanumeric() && c != '-') {
+ if let Some(turn) = token.strip_prefix("turn-").and_then(|t| t.parse().ok()) {
+ if seen.last() != Some(&turn) {
+ seen.push(turn);
+ }
+ }
+ }
+ seen
+}
+
+/// `batches` repetitions of `key`, pausing between batches so arrived pages apply
+/// between keystrokes as they do for a user.
+fn paced_keys(code: crossterm::event::KeyCode, batches: usize) -> Vec<HeadlessStep> {
+ let mut steps = Vec::new();
+ for _ in 0..batches {
+ steps.extend((0..5).map(|_| key(code)));
+ steps.push(HeadlessStep::WaitMs(60));
+ }
+ steps
+}
+
+fn attached() -> Vec<HeadlessStep> {
+ vec![HeadlessStep::WaitRender {
+ needle: marker(TURNS - 1),
+ timeout_ms: 10_000,
+ }]
+}
+
+const SUMMARY_ROW: &str = "Context compacted";
+
+#[tokio::test]
+async fn the_top_of_a_long_session_is_its_first_message_across_a_compaction() {
+ let session = open_long_session().await;
+ // The top key jumps to the session start.
+ let mut steps = attached();
+ steps.push(HeadlessStep::ScrollTop);
+ steps.push(HeadlessStep::WaitRender {
+ needle: marker(0),
+ timeout_ms: 10_000,
+ });
+ let frames = run_plan(&session, steps, 40).await;
+ let last = frames.last().expect("frames rendered");
+ assert_eq!(
+ turn_markers(last).first(),
+ Some(&0),
+ "the top key must reach the session's first message:\n{last}"
+ );
+ // Paging walks there too, through the compaction.
+ let mut steps = attached();
+ steps.extend(paced_keys(crossterm::event::KeyCode::PageUp, 200));
+ let frames = run_plan(&session, steps, 40).await;
+ let last = frames.last().expect("frames rendered");
+ assert_eq!(
+ turn_markers(last).first(),
+ Some(&0),
+ "paging up must reach the session's first message:\n{last}"
+ );
+ assert!(
+ frames.iter().any(|frame| frame.contains(SUMMARY_ROW)),
+ "the climb passed the compaction summary"
+ );
+}
+
+#[tokio::test]
+async fn the_compaction_summary_renders_once_across_eviction_and_refetch() {
+ let session = open_long_session().await;
+ // Climb far enough above the compaction that its chunk is evicted, then descend
+ // past it again so it is refetched.
+ let mut steps = attached();
+ steps.extend(paced_keys(crossterm::event::KeyCode::PageUp, 90));
+ steps.extend(paced_keys(crossterm::event::KeyCode::PageDown, 75));
+ let frames = run_plan(&session, steps, 40).await;
+ let highest = frames
+ .iter()
+ .enumerate()
+ .min_by_key(|(_, frame)| turn_markers(frame).first().copied().unwrap_or(usize::MAX))
+ .map(|(index, _)| index)
+ .expect("frames rendered");
+ let highest_turn = turn_markers(&frames[highest])[0];
+ assert!(
+ highest_turn + 300 < COMPACTED_AFTER_TURN,
+ "the climb must pass the compaction by more than the resident window, \
+ reached turn {highest_turn}:\n{}",
+ frames[highest]
+ );
+ for (index, frame) in frames.iter().enumerate() {
+ assert!(
+ frame.matches(SUMMARY_ROW).count() <= 1,
+ "frame {index} renders the compaction summary twice:\n{frame}"
+ );
+ let mut rows = HashSet::new();
+ for line in frame.lines().filter(|line| line.contains("turn-")) {
+ assert!(
+ rows.insert(line.trim()),
+ "frame {index} renders the row {line:?} twice:\n{frame}"
+ );
+ }
+ }
+ // At the boundary the summary sits once between the last compacted turn and the
+ // first later one, on the way up and again on the way back down.
+ let boundary = |frame: &str| {
+ let before = frame.find(&format!("{} answer", marker(COMPACTED_AFTER_TURN)));
+ let summary = frame.find(SUMMARY_ROW);
+ let after = frame.find(&format!("{} question", marker(COMPACTED_AFTER_TURN + 1)));
+ matches!((before, summary, after), (Some(b), Some(s), Some(a)) if b < s && s < a)
+ && frame.matches(SUMMARY_ROW).count() == 1
+ };
+ assert!(
+ frames[..highest].iter().any(|frame| boundary(frame)),
+ "the climb shows the summary once at its boundary"
+ );
+ assert!(
+ frames[highest..].iter().any(|frame| boundary(frame)),
+ "the descent shows the refetched summary once at its boundary: {}",
+ frames.last().map_or("", String::as_str)
+ );
+}
diff --git a/crates/pa-daemon/src/session_store.rs b/crates/pa-daemon/src/session_store.rs
index 6b3c091033..67c62316a9 100644
--- a/crates/pa-daemon/src/session_store.rs
+++ b/crates/pa-daemon/src/session_store.rs
@@ -103,10 +103,16 @@ pub struct SessionEntry {
pub fields: Value,
}
+/// One display-transcript page ([`SessionFile::transcript_page`]).
#[derive(Debug, Clone)]
-pub struct WindowedTranscript {
+pub struct TranscriptPageRows {
pub messages: Vec<Value>,
- pub omitted: usize,
+ pub first_entry_id: Option<String>,
+ pub last_entry_id: Option<String>,
+ /// Rows exist past the page's far side: older ones for an end page, newer
+ /// ones before `until` for a start page.
+ pub more: bool,
+ /// The newest user prompt's time anywhere on the branch.
pub last_user_prompt_ms: Option<u64>,
}
diff --git a/crates/pa-daemon/src/session_store/view.rs b/crates/pa-daemon/src/session_store/view.rs
index f3eec93dbf..2fcb7f33a9 100644
--- a/crates/pa-daemon/src/session_store/view.rs
+++ b/crates/pa-daemon/src/session_store/view.rs
@@ -1,7 +1,8 @@
//! 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, WindowedTranscript};
+use super::{json, MessageWindowScalars, SessionEntry, SessionFile, TranscriptPageRows, Value};
+use pa_types::daemon::TranscriptPage;
/// Entry types that represent user intent (vs daemon bookkeeping).
const CONTENT_ENTRY_TYPES: &[&str] = &[
@@ -279,20 +280,7 @@ 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());
- 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;
- }
+ self.walk_message_values(|message| {
messages.push(message.into_owned());
true
});
@@ -304,7 +292,7 @@ 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);
@@ -314,41 +302,22 @@ impl SessionFile {
scalars
}
- /// The windowed message sequence behind [`Self::messages`] (`custom_message`
+ /// The model-context 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.
+ /// prepends its summary message).
fn walk_message_values<'a>(
&'a self,
- mut visit: impl FnMut(usize, std::borrow::Cow<'a, Value>) -> bool,
+ mut visit: impl FnMut(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),
- "custom_message" => {
- let mut message = entry.fields.clone();
- if let Some(object) = message.as_object_mut() {
- object.insert("role".to_string(), Value::String("custom".to_string()));
- object.insert(
- "timestamp".to_string(),
- Value::String(entry.timestamp.clone()),
- );
- }
- Some(std::borrow::Cow::Owned(message))
- }
- _ => None,
- }
- };
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) {
- if !visit(index, message) {
+ if !visit(message) {
return;
}
- index += 1;
}
}
return;
@@ -376,133 +345,107 @@ impl SessionFile {
}
}
let summary =
- std::borrow::Cow::Owned(compaction_summary_message(compaction, retained_count));
- if !visit(index, summary) {
+ std::borrow::Cow::Owned(compaction_summary_message(compaction, Some(retained_count)));
+ if !visit(summary) {
return;
}
- index += 1;
let mut keeping = false;
for entry in &branch[..compaction_position] {
// The durable cut can name bookkeeping, not just a message row.
if !keeping && entry.id == first_kept_entry_id {
keeping = true;
}
- if !entry_bears_message(entry) {
- continue;
- }
if keeping {
if let Some(message) = entry_message(entry) {
- if !visit(index, message) {
+ if !visit(message) {
return;
}
- index += 1;
}
}
}
for entry in &branch[compaction_position + 1..] {
if let Some(message) = entry_message(entry) {
- if !visit(index, message) {
+ if !visit(message) {
return;
}
- index += 1;
}
}
}
+ /// The display transcript: the whole branch in order, each row with its entry id.
+ /// A compaction is its summary row at its own position, so every entry shows once.
+ fn display_rows(&self) -> Vec<(&str, std::borrow::Cow<'_, Value>)> {
+ self.branch()
+ .into_iter()
+ .filter_map(|entry| {
+ let message = if entry.type_ == "compaction" {
+ std::borrow::Cow::Owned(compaction_summary_message(entry, None))
+ } else {
+ entry_message(entry)?
+ };
+ Some((entry.id.as_str(), message))
+ })
+ .collect()
+ }
+
+ /// One page of the display transcript; `None` when an anchor row is not on the branch.
#[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,
+ pub fn transcript_page(&self, page: &TranscriptPage) -> Option<TranscriptPageRows> {
+ let mut rows = self.display_rows();
+ let position = |rows: &[(&str, std::borrow::Cow<'_, Value>)], id: &str| {
+ rows.iter().position(|(row_id, _)| *row_id == id)
+ };
+ let (start, end, more) = match page {
+ TranscriptPage::End { before, limit } => {
+ let end = match before {
+ Some(id) => position(&rows, id)?,
+ None => rows.len(),
};
- if let Some(timestamp) = prompt_timestamp_ms {
- last_user_prompt_ms = Some(timestamp);
- }
+ let start = settle_cut(&rows, end.saturating_sub(*limit));
+ // A windowed store's unloaded prefix is older history too.
+ (start, end, start > 0 || self.window.is_some())
}
- 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));
- }
+ TranscriptPage::Start {
+ after,
+ until,
+ limit,
+ } => {
+ let until = match until {
+ Some(id) => position(&rows, id)?,
+ None => rows.len(),
+ };
+ let start = match after {
+ Some(id) => position(&rows, id)? + 1,
+ None => 0,
}
- _ => {}
- }
- }
- 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;
+ .min(until);
+ let end = match start.saturating_add(*limit) {
+ end if end >= until => until,
+ end if end == start => start,
+ end => Some(settle_cut(&rows, end))
+ .filter(|cut| *cut > start)
+ .unwrap_or(until),
+ };
+ (start, end, end < until)
}
- }
- let messages = visited.split_off(cut);
- WindowedTranscript {
- messages: messages
+ };
+ let last_user_prompt_ms = rows
+ .iter()
+ .rev()
+ .find(|(_, message)| message.get("role").and_then(Value::as_str) == Some("user"))
+ .and_then(|(_, message)| prompt_timestamp_ms(message));
+ rows.truncate(end);
+ let page_rows = rows.split_off(start);
+ Some(TranscriptPageRows {
+ first_entry_id: page_rows.first().map(|(id, _)| (*id).to_string()),
+ last_entry_id: page_rows.last().map(|(id, _)| (*id).to_string()),
+ messages: page_rows
.into_iter()
- .map(std::borrow::Cow::into_owned)
+ .map(|(_, message)| message.into_owned())
.collect(),
- omitted: cut,
+ more,
last_user_prompt_ms,
- }
+ })
}
/// The durable entry id the compaction cut keeps: the engine's
@@ -591,6 +534,88 @@ pub(super) fn message_role(message: &Value) -> Option<&str> {
message.get("role").and_then(Value::as_str)
}
+/// A row's wire message (`custom_message` rows rejoin as `role: "custom"`).
+fn entry_message(entry: &SessionEntry) -> Option<std::borrow::Cow<'_, Value>> {
+ match entry.type_.as_str() {
+ "message" => entry.fields.get("message").map(std::borrow::Cow::Borrowed),
+ "custom_message" => {
+ let mut message = entry.fields.clone();
+ if let Some(object) = message.as_object_mut() {
+ object.insert("role".to_string(), Value::String("custom".to_string()));
+ object.insert(
+ "timestamp".to_string(),
+ Value::String(entry.timestamp.clone()),
+ );
+ }
+ Some(std::borrow::Cow::Owned(message))
+ }
+ _ => None,
+ }
+}
+
+/// A user prompt's wall-clock time, mirroring the TUI's numeric/ISO timestamp contract.
+fn prompt_timestamp_ms(message: &Value) -> Option<u64> {
+ 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,
+ }
+}
+
+/// Move a page boundary earlier until the page below it starts at neither a tool
+/// result nor a custom row, and no tool call is split from its result.
+fn settle_cut(rows: &[(&str, std::borrow::Cow<'_, Value>)], mut cut: usize) -> usize {
+ let role = |index: usize| rows[index].1.get("role").and_then(Value::as_str);
+ while cut > 0 && cut < rows.len() && matches!(role(cut), 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 rows.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;
+ }
+ }
+ cut
+}
+
/// Whether one entry contributes a message to the fold: `message` rows need
/// their persisted message; `custom_message` rows rejoin as their wire form.
/// The borrowing twin of the `entry_message` Some-ness.
@@ -602,8 +627,9 @@ fn entry_bears_message(entry: &SessionEntry) -> bool {
}
}
-/// The `compactionSummary` message a compaction fold starts with.
-fn compaction_summary_message(entry: &SessionEntry, retained_count: usize) -> Value {
+/// The `compactionSummary` message of a compaction entry; the context walk's
+/// copy carries its retained count.
+fn compaction_summary_message(entry: &SessionEntry, retained_count: Option<usize>) -> Value {
let timestamp = crate::util::iso_to_unix_ms(&entry.timestamp).unwrap_or(0);
// The TS `compactionSummary` key order: role, summary, tokensBefore,
// retainedMessageCount, customInstructions?, harnessDigest?, timestamp —
@@ -612,8 +638,10 @@ fn compaction_summary_message(entry: &SessionEntry, retained_count: usize) -> Va
"role": "compactionSummary",
"summary": entry.fields.get("summary").cloned().unwrap_or_default(),
"tokensBefore": entry.fields.get("tokensBefore").cloned().unwrap_or(json!(0)),
- "retainedMessageCount": retained_count as u64,
});
+ if let Some(retained_count) = retained_count {
+ message["retainedMessageCount"] = json!(retained_count as u64);
+ }
if let Some(custom_instructions) = entry.fields.get("customInstructions") {
message["customInstructions"] = custom_instructions.clone();
}
diff --git a/crates/pa-daemon/src/snapshot_stream.rs b/crates/pa-daemon/src/snapshot_stream.rs
index 908a3fedd9..318489e645 100644
--- a/crates/pa-daemon/src/snapshot_stream.rs
+++ b/crates/pa-daemon/src/snapshot_stream.rs
@@ -153,7 +153,7 @@ pub(crate) fn stream_attach(
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`).
+ // session's total (the page cursor is `historyBeforeEntryId`).
let message_count = match &messages {
Value::Array(messages) => messages.len() as u64,
// A missing or malformed transcript fails the transfer below.
diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs
index e02ec07832..aace373496 100644
--- a/crates/pa-daemon/src/worker/commands.rs
+++ b/crates/pa-daemon/src/worker/commands.rs
@@ -14,23 +14,27 @@ impl Worker {
pub(crate) async fn dispatch(&self, command_type: &str, payload: &Value) -> DaemonResponse {
// Only operations that inspect or change historical branches need hydration.
// Cancellation is deliberately excluded: it must reach the live turn immediately.
- if matches!(
- command_type,
- "get_session_tree"
- | "get_context_tree"
- | "get_user_messages_for_forking"
- | "set_session_entry_label"
- | "navigate_tree"
- | "fork"
- | "export_html"
- | "export_jsonl"
- ) && self
- .core
- .lock()
- .unwrap()
- .store
- .as_ref()
- .is_some_and(|store| store.window.is_some())
+ let history_page = command_type == "get_messages"
+ && transcript_page(payload).is_some_and(|page| page.reads_history());
+ if (history_page
+ || matches!(
+ command_type,
+ "get_session_tree"
+ | "get_context_tree"
+ | "get_user_messages_for_forking"
+ | "set_session_entry_label"
+ | "navigate_tree"
+ | "fork"
+ | "export_html"
+ | "export_jsonl"
+ ))
+ && self
+ .core
+ .lock()
+ .unwrap()
+ .store
+ .as_ref()
+ .is_some_and(|store| store.window.is_some())
{
let path = self
.core
@@ -463,10 +467,7 @@ impl Worker {
if let Err(response) = self.require_created("get_messages") {
return response;
}
- let before = payload
- .get("before")
- .and_then(Value::as_u64)
- .and_then(|before| usize::try_from(before).ok());
+ let page = transcript_page(payload);
let capabilities = payload
.get("capabilities")
.and_then(Value::as_array)
@@ -479,32 +480,48 @@ impl Worker {
})
.unwrap_or_default();
let core = self.core.lock().unwrap();
- // Validate ancestry atomically with the positional read. Appends keep the
+ let Some(page) = page else {
+ let mut messages = core
+ .store
+ .as_ref()
+ .map(SessionFile::messages)
+ .unwrap_or_default();
+ if crate::snapshot_stream::wants_image_elision(&capabilities) {
+ crate::snapshot_stream::elide_snapshot_image_payloads(&mut messages);
+ }
+ return response_success(None, "get_messages", Some(json!({ "messages": messages })));
+ };
+ let Some(store) = core.store.as_ref() else {
+ return response_failure(None, "get_messages", "History branch changed", None);
+ };
+ // Validate ancestry atomically with the page 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 {
+ let history_leaf = match payload.get("historyLeafId").map(Value::as_str) {
+ Some(Some(leaf)) if store.branch().iter().any(|entry| entry.id == leaf) => {
+ leaf.to_string()
+ }
+ Some(_) => {
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(),
+ None => store.leaf_id.clone().unwrap_or_default(),
+ };
+ let Some(mut rows) = store.transcript_page(&page) else {
+ return response_failure(None, "get_messages", "History branch changed", None);
};
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();
+ crate::snapshot_stream::elide_snapshot_image_payloads(&mut rows.messages);
}
- response_success(None, "get_messages", Some(data))
+ response_success(
+ None,
+ "get_messages",
+ Some(json!({
+ "messages": rows.messages,
+ "firstEntryId": rows.first_entry_id,
+ "lastEntryId": rows.last_entry_id,
+ "more": rows.more,
+ "historyLeafId": history_leaf,
+ })),
+ )
}
fn handle_get_queue(&self) -> DaemonResponse {
@@ -860,6 +877,11 @@ fn cleared_agent_message_bounce_text(receiver: &str, message: &str) -> String {
format!("{prefix}{body}")
}
+/// The display-transcript page a `get_messages` payload asks for, if any.
+fn transcript_page(payload: &Value) -> Option<pa_types::daemon::TranscriptPage> {
+ serde_json::from_value(payload.get("page")?.clone()).ok()
+}
+
#[cfg(test)]
mod bounce_text_tests {
use super::cleared_agent_message_bounce_text;
diff --git a/crates/pa-daemon/src/worker/connection.rs b/crates/pa-daemon/src/worker/connection.rs
index 37ab0b7bbe..995f7c9d9f 100644
--- a/crates/pa-daemon/src/worker/connection.rs
+++ b/crates/pa-daemon/src/worker/connection.rs
@@ -838,17 +838,22 @@ impl Worker {
.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),
+ let (mut messages, history_before_entry_id, last_user_prompt_ms) = match core.store.as_ref()
+ {
+ Some(store) if windowed => store
+ .transcript_page(&pa_types::daemon::TranscriptPage::End {
+ before: None,
+ limit: ATTACH_TAIL_MESSAGE_BUDGET,
+ })
+ .map_or((Vec::new(), None, None), |page| {
+ (
+ page.messages,
+ page.first_entry_id.filter(|_| page.more),
+ page.last_user_prompt_ms,
+ )
+ }),
+ Some(store) => (store.messages(), None, None),
+ None => (Vec::new(), None, None),
};
// The image-payload elision: `elide_snapshot_images` clients read the
// transcript without base64 payloads; the client's set is
@@ -880,8 +885,8 @@ impl Worker {
"children": [],
});
snapshot["messages"] = Value::Array(messages);
- if omitted > 0 {
- snapshot["historyBefore"] = json!(omitted);
+ if let Some(entry_id) = history_before_entry_id {
+ snapshot["historyBeforeEntryId"] = json!(entry_id);
if let Some(last_user_prompt_ms) = last_user_prompt_ms {
snapshot["lastUserPromptMs"] = json!(last_user_prompt_ms);
}
diff --git a/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs b/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs
index 7c5f0033b0..9b6d73182d 100644
--- a/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs
+++ b/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs
@@ -132,6 +132,19 @@ async fn full_messages(worker: &Worker) -> Vec<Value> {
.clone()
}
+/// One display-transcript page, optionally anchored to the attached branch leaf.
+async fn page(worker: &Worker, page: Value, leaf: Option<&str>) -> DaemonResponse {
+ let mut payload = json!({ "page": page, "capabilities": TUI_CAPABILITIES });
+ if let Some(leaf) = leaf {
+ payload["historyLeafId"] = json!(leaf);
+ }
+ worker.dispatch("get_messages", &payload).await
+}
+
+fn row_id(message_index: usize) -> String {
+ format!("m{:07}", message_index + 1)
+}
+
const TUI_CAPABILITIES: &[&str] = &[
"attach_snapshot",
"event_sequence",
@@ -194,9 +207,10 @@ async fn a_windowed_attach_serves_a_tool_result_safe_tail() {
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");
+ let omitted = 198;
assert_eq!(
- omitted, 198,
+ snapshot["historyBeforeEntryId"],
+ json!(row_id(omitted)),
"the cut snaps back off the tool result and custom rows"
);
assert_eq!(tail.len(), 802, "the tail keeps the whole tool call run");
@@ -210,43 +224,37 @@ async fn a_windowed_attach_serves_a_tool_result_safe_tail() {
);
assert_eq!(
&tail[..],
- &full[(omitted as usize)..],
- "the tail is a suffix of the one walk"
+ &full[omitted..],
+ "the tail is a suffix of the walk"
);
assert_eq!(
snapshot["lastUserPromptMs"], 1000,
"the newest user timestamp rides the windowed snapshot"
);
- let head = worker
- .dispatch("get_messages", &json!({ "before": omitted }))
- .await;
+ let head = page(
+ &worker,
+ json!({ "from": "end", "before": row_id(omitted), "limit": 1000 }),
+ None,
+ )
+ .await;
assert!(head.success, "the head fetch failed: {head:?}");
+ let head = head.data.expect("head data");
+ assert_eq!(head["more"], false, "the page reaches the session start");
+ assert_eq!(head["firstEntryId"], json!(row_id(0)));
+ assert_eq!(head["lastEntryId"], json!(row_id(omitted - 1)));
+ let head_messages = head["messages"].as_array().expect("head messages");
assert_eq!(
- head.data.expect("head data")["messages"],
- serde_json::json!(full[..omitted as usize]),
- "the before range serves the walk's omitted prefix"
+ head_messages.len(),
+ omitted,
+ "the page serves the 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"
+ head_messages[197]["content"][1]["data"], "",
+ "the image payload leaves the page"
);
assert_eq!(
- elided_messages[197]["content"][1]["elidedBytes"], 8,
- "the elided marker rides the backfill head"
+ head_messages[197]["content"][1]["elidedBytes"], 8,
+ "the elided marker rides the page"
);
let plain = attach(&worker, &["attach_snapshot", "event_sequence"]).await;
@@ -257,14 +265,14 @@ async fn a_windowed_attach_serves_a_tool_result_safe_tail() {
"a non-windowed attach keeps the full snapshot"
);
assert!(
- plain["snapshot"].get("historyBefore").is_none()
+ plain["snapshot"].get("historyBeforeEntryId").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() {
+async fn pages_continue_into_pre_compaction_history_with_one_summary() {
let dir = session_dir();
let path = dir.join("windowed-compacted.jsonl");
let retained = 400usize;
@@ -277,6 +285,7 @@ async fn a_windowed_attach_never_cuts_inside_the_compaction_retained_segment() {
for _ in 0..10 {
fixture.row(|prev, id| message_row(prev, id, &assistant_message("compacted away")));
}
+ fixture.row(|prev, id| message_row(prev, id, &assistant_message("retained")));
let first_kept = fixture.prev.clone().expect("retained start");
for _ in 1..retained {
fixture.row(|prev, id| message_row(prev, id, &assistant_message("retained")));
@@ -293,23 +302,88 @@ async fn a_windowed_attach_never_cuts_inside_the_compaction_retained_segment() {
std::fs::write(&path, fixture.content).unwrap();
let worker = worker_over(&dir, &path).await;
- let full = full_messages(&worker).await;
+ let data = attach(&worker, TUI_CAPABILITIES).await;
+ let snapshot = &data["snapshot"];
+ let tail = snapshot["messages"]
+ .as_array()
+ .expect("tail messages")
+ .clone();
+ let tail_first = snapshot["historyBeforeEntryId"]
+ .as_str()
+ .expect("older history exists above the tail")
+ .to_string();
+ let older = page(
+ &worker,
+ json!({ "from": "end", "before": tail_first, "limit": 1000 }),
+ None,
+ )
+ .await;
+ assert!(older.success, "the older page failed: {older:?}");
+ let older = older.data.expect("older data");
+ assert_eq!(older["more"], false);
+ let mut display = older["messages"]
+ .as_array()
+ .expect("older messages")
+ .clone();
+ display.extend(tail);
+ let texts: Vec<&str> = display
+ .iter()
+ .map(|message| {
+ message["content"][0]["text"]
+ .as_str()
+ .or_else(|| message["summary"].as_str())
+ .unwrap_or_default()
+ })
+ .collect();
+ let expected: Vec<&str> = std::iter::repeat_n("compacted away", 10)
+ .chain(std::iter::repeat_n("retained", retained))
+ .chain(["the story"])
+ .chain(std::iter::repeat_n("after compaction", post))
+ .collect();
assert_eq!(
- full[0]["role"], "compactionSummary",
- "the walk serves the summary first"
+ texts, expected,
+ "the display walk is the whole branch in order with the summary once at the compaction"
);
- 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}"
+ // A zero limit is an empty page at either end, never a panic under the core lock.
+ for empty in [
+ json!({ "from": "end", "limit": 0 }),
+ json!({ "from": "start", "until": tail_first, "limit": 0 }),
+ ] {
+ let response = page(&worker, empty, None).await;
+ assert!(response.success, "a zero-limit page failed: {response:?}");
+ assert_eq!(
+ response.data.expect("empty page data")["messages"],
+ json!([])
+ );
+ }
+
+ // The head page and a newer page stop at their bounds.
+ let head = page(
+ &worker,
+ json!({ "from": "start", "until": tail_first, "limit": 5 }),
+ None,
+ )
+ .await;
+ let head = head.data.expect("head data");
+ assert_eq!(head["messages"], json!(display[..5]));
+ assert_eq!(head["more"], true);
+ let rest = page(
+ &worker,
+ json!({ "from": "start", "after": head["lastEntryId"], "until": tail_first, "limit": 1000 }),
+ None,
+ )
+ .await;
+ let rest = rest.data.expect("rest data");
+ assert_eq!(
+ rest["more"], false,
+ "the newer page closes the gap to the tail"
+ );
+ assert_eq!(
+ rest["messages"],
+ json!(older["messages"].as_array().unwrap()[5..]),
+ "the newer page ends right before the tail"
);
- assert_eq!(tail.len(), 601 - omitted as usize);
- assert_eq!(&tail[..], &full[(omitted as usize)..]);
}
#[tokio::test]
@@ -341,7 +415,7 @@ async fn a_windowed_attach_preserves_iso_and_fractional_prompt_times() {
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["historyBeforeEntryId"], json!(row_id(88)));
assert_eq!(
snapshot["lastUserPromptMs"], 2000,
"latest timestamp {timestamp} at index {user_index}"
@@ -352,7 +426,7 @@ async fn a_windowed_attach_preserves_iso_and_fractional_prompt_times() {
/// 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.
+/// session total.
#[tokio::test]
async fn a_chunked_windowed_attach_streams_the_count_it_carries() {
let dir = session_dir();
@@ -380,11 +454,10 @@ async fn a_chunked_windowed_attach_streams_the_count_it_carries() {
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!(snapshot["historyBeforeEntryId"], json!(row_id(88)));
assert_eq!(summary_count, 600);
assert_eq!(snapshot["messages"].as_array().expect("tail").len(), 512);
@@ -417,9 +490,9 @@ async fn a_chunked_windowed_attach_streams_the_count_it_carries() {
"the advertised count is the messages the stream carries"
);
assert_eq!(
- omitted + carried,
+ 88 + carried,
summary_count,
- "the tail plus the history-before prefix is the session total"
+ "the tail plus the rows above its cursor is the session total"
);
}
@@ -479,7 +552,8 @@ async fn a_windowed_attach_keeps_interleaved_tool_pairs_together() {
let data = attach(&worker, TUI_CAPABILITIES).await;
let snapshot = &data["snapshot"];
assert_eq!(
- snapshot["historyBefore"], 20,
+ snapshot["historyBeforeEntryId"],
+ json!(row_id(20)),
"both matched pairs belong in the tail; unrelated older history stays omitted"
);
assert_eq!(
@@ -487,9 +561,12 @@ async fn a_windowed_attach_keeps_interleaved_tool_pairs_together() {
json!(full[20..]),
"moving the boundary preserves the complete ordered suffix"
);
- let head = worker
- .dispatch("get_messages", &json!({"before": 20}))
- .await;
+ let head = page(
+ &worker,
+ json!({ "from": "end", "before": row_id(20), "limit": 1000 }),
+ None,
+ )
+ .await;
assert!(head.success);
assert_eq!(
head.data.unwrap()["messages"],
@@ -529,7 +606,8 @@ async fn anchored_backfill_rejects_other_client_branch_navigation() {
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 tail_first = snapshot["historyBeforeEntryId"].clone();
+ assert_eq!(tail_first, json!(row_id(88)));
let navigated = worker
.dispatch(
"navigate_tree",
@@ -539,19 +617,12 @@ async fn anchored_backfill_rejects_other_client_branch_navigation() {
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;
+ let backfill = page(
+ &worker,
+ json!({ "from": "end", "before": tail_first, "limit": 256 }),
+ Some(leaf),
+ )
+ .await;
assert!(
!backfill.success,
"a prefix from {target} must not join the old attach tail: {backfill:?}"
@@ -591,12 +662,12 @@ async fn anchored_backfill_accepts_descendant_appends_and_restored_branch() {
assert!(navigated.success, "navigation failed: {navigated:?}");
}
}
- let backfill = worker
- .dispatch(
- "get_messages",
- &json!({"before": snapshot["historyBefore"], "historyLeafId": leaf}),
- )
- .await;
+ let backfill = page(
+ &worker,
+ json!({ "from": "end", "before": snapshot["historyBeforeEntryId"], "limit": 256 }),
+ Some(leaf),
+ )
+ .await;
assert!(backfill.success, "coherent prefix rejected: {backfill:?}");
let returned = backfill.data.expect("backfill data");
assert_eq!(returned["messages"], json!(original[..88]));
diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rs
index ede6f6a694..092973c59c 100644
--- a/crates/pa-tui/src/interactive/run.rs
+++ b/crates/pa-tui/src/interactive/run.rs
@@ -208,8 +208,7 @@ 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>();
+ let (page_tx, mut page_rx) = mpsc::unbounded_channel::<crate::session_ui::TranscriptPageNote>();
// 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.
@@ -310,7 +309,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 page_tx = page_tx.clone();
let waits_through_update_restart = route == SessionOpenRoute::AgentsView;
tokio::spawn(async move {
crate::update_restart_wait::wait_through_update_restart(
@@ -338,7 +337,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 page_tx = page_tx.clone();
async move {
let (client, events) = match first {
Some(first) => first,
@@ -366,7 +365,7 @@ async fn run_interactive_surface(
factory: factory_tx,
commands: commands_tx,
},
- backfill_tx,
+ page_tx,
)
.await?;
Ok((events, session))
@@ -829,7 +828,7 @@ async fn run_interactive_surface(
'run: while running {
if !session.dirty {
- session.spawn_pending_backfill();
+ session.spawn_transcript_page(&view);
}
if enhanced_keys_pending {
if let Some((kitty, modify_other_keys)) = crate::enhanced_keys::settle_state() {
@@ -1146,6 +1145,7 @@ async fn run_interactive_surface(
UiInput::ScrollTop => {
session.stop_selection_auto_scroll();
view.scroll_to_top();
+ session.window.request_head();
}
UiInput::Resize => {
session.stop_selection_auto_scroll();
@@ -1250,7 +1250,7 @@ async fn run_interactive_surface(
// paint; a keystroke's toast or hint) must not park behind a select that has no other wake.
// The headless barriers' deadlines and the hint/toast expiry arm HERE, not after the frame
// gate.
- if session.dirty && render_deadline.is_none() {
+ if (session.dirty || session.wants_transcript_page(&view)) && render_deadline.is_none() {
render_deadline = Some(Instant::now());
}
for deadline in [
@@ -1328,15 +1328,9 @@ async fn run_interactive_surface(
while let Ok(event) = events.try_recv() {
session.apply_client_event(event, &mut view);
}
- // A succeeded compaction rebuilt the durable transcript: replace the view's
- // chat with it, and refresh the tray usage the same way a settled turn does.
- if session.transcript_stale {
- session.rebuild_transcript(&mut view).await;
- session.refresh_stats().await;
- session.rebuild_tray(&mut view);
- }
- // A settled turn refreshes the tray's context usage.
- if was_active && !session.turn_active {
+ // A settled turn or compaction refreshes the tray's context usage.
+ let compaction_settled = std::mem::take(&mut session.compaction_settled);
+ if compaction_settled || (was_active && !session.turn_active) {
session.refresh_stats().await;
session.rebuild_tray(&mut view);
}
@@ -1533,9 +1527,9 @@ 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_page = page_rx.recv() => {
+ if let Some(note) = maybe_page {
+ session.apply_transcript_page(note, &mut view);
}
}
maybe_compaction_abort = compaction_abort_rx.recv() => {
@@ -2031,13 +2025,15 @@ async fn run_interactive_surface(
// 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);
+ // Leaving the run flushes only the history already loaded and contiguous with
+ // the tail: an unfinished page is abandoned (dropping the task aborts its
+ // request), a page that already arrived applies, and a resident run cut off
+ // from the tail drops before the flush.
+ session.window.retire_fetch();
+ while let Ok(note) = page_rx.try_recv() {
+ session.apply_transcript_page(note, &mut view);
}
+ session.collapse_transcript_window(&mut view);
}
if renderer.is_terminal() && !handing_off {
exit_guard.arm_for_exit();
diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rs
index 3cf220399e..acca9a774f 100644
--- a/crates/pa-tui/src/session_ui.rs
+++ b/crates/pa-tui/src/session_ui.rs
@@ -20,6 +20,8 @@ mod sessions_fork;
mod settings;
mod share;
mod stream;
+mod window;
+pub(crate) use window::TranscriptPageNote;
pub(crate) use apply::CompactionAbortNote;
use auth::{McpAuthIntent, PendingModelSignIn, SetModelOutcome};
@@ -144,11 +146,6 @@ pub(crate) fn last_assistant_text_of(chat: &[ChatEntry]) -> Option<String> {
})
}
-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,
@@ -352,18 +349,10 @@ pub(crate) struct SessionUi {
/// Armed prompt round trips (one per spawned request): the headless
/// 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>,
+ /// A compaction settled: the tray's context usage refreshes.
+ pub(crate) compaction_settled: bool,
+ pub(crate) window: window::TranscriptWindow,
+ page_notes: mpsc::UnboundedSender<window::TranscriptPageNote>,
/// 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 f896508c50..982714d37a 100644
--- a/crates/pa-tui/src/session_ui/apply.rs
+++ b/crates/pa-tui/src/session_ui/apply.rs
@@ -1,10 +1,9 @@
//! 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, 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,
+ assistant_message_parts, event_to_update, pop_superseded_attempt_row, AgentView, ChatEntry,
+ CompactionReason, CompactionState, DaemonClientEvent, DaemonCommand, Map, MessageBlock, Result,
+ RetryState, SessionUi, StatusKind, ToolResultView, TurnUpdate, Value,
};
/// One backgrounded compaction-abort outcome: a failed abort surfaces as
@@ -107,169 +106,6 @@ impl SessionUi {
self.note(text, view);
}
- /// 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 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;
- let Some(messages) = data
- .as_ref()
- .ok()
- .and_then(|data| 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);
- view.clear_chat();
- for entry in entries {
- view.push_entry(entry);
- }
- view.follow();
- 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) {
@@ -689,8 +525,8 @@ impl SessionUi {
} => {
view.compaction = None;
if let Some(result) = result {
- // A succeeded compaction rebuilt the durable transcript: show the outcome
- // row immediately, then re-fetch so the compacted-away rows drop.
+ // The display transcript keeps every row: the summary appends at the
+ // compaction's own position.
view.push_entry(ChatEntry::CompactionSummary {
summary: result
.get("summary")
@@ -703,7 +539,7 @@ impl SessionUi {
.unwrap_or_default(),
custom_instructions,
});
- self.transcript_stale = true;
+ self.compaction_settled = true;
} else if reason == "manual" {
// Aborts and error messages surface only for user-issued compactions.
if aborted {
diff --git a/crates/pa-tui/src/session_ui/keys.rs b/crates/pa-tui/src/session_ui/keys.rs
index afec33e006..b5cbf307bf 100644
--- a/crates/pa-tui/src/session_ui/keys.rs
+++ b/crates/pa-tui/src/session_ui/keys.rs
@@ -422,11 +422,13 @@ impl SessionUi {
}
if to_top {
view.scroll_to_top();
+ self.window.request_head();
self.track_scroll("top", view.is_following());
self.dirty = true;
return Ok(());
}
if follow {
+ self.collapse_transcript_window(view);
view.scroll_to_bottom();
self.track_scroll("follow", view.is_following());
self.dirty = true;
diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rs
index c96b78b27b..8059c0751e 100644
--- a/crates/pa-tui/src/session_ui/lifecycle.rs
+++ b/crates/pa-tui/src/session_ui/lifecycle.rs
@@ -7,7 +7,7 @@ use super::{
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,
+ SessionSelection, SessionUi, ShareNote, TranscriptPageNote, UpdateNote, Value,
EXIT_DETACH_TIMEOUT_MS, EXIT_STATS_TIMEOUT_MS, UI_REQUEST_TIMEOUT_MS,
};
@@ -27,7 +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>,
+ page_notes: mpsc::UnboundedSender<TranscriptPageNote>,
) -> Result<SessionUi> {
let active_session_id = match &options.session {
SessionSelection::New => create_session(&client, options, None).await?,
@@ -168,14 +168,9 @@ impl SessionUi {
prompt_orders: orders_tx,
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,
+ compaction_settled: false,
+ window: super::window::TranscriptWindow::default(),
+ page_notes,
telemetry: options.telemetry.clone(),
scroll_adoption_emitted: false,
exit_reason: "daemon_closed",
@@ -517,15 +512,13 @@ 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);
+ self.window.reset(
+ attach.snapshot["state"]["leafId"]
+ .as_str()
+ .map(str::to_owned),
+ reconstructed.history_before_entry_id,
+ reconstructed.backfill_seam,
+ );
Ok(())
}
@@ -776,103 +769,3 @@ 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/session_ui/window.rs b/crates/pa-tui/src/session_ui/window.rs
new file mode 100644
index 0000000000..f33fb60f3f
--- /dev/null
+++ b/crates/pa-tui/src/session_ui/window.rs
@@ -0,0 +1,609 @@
+//! The transcript window: the resident run of display-transcript chunks above the
+//! live tail. A chunk loads before the viewport reaches the resident edge, and the
+//! chunk farthest from the viewport is evicted, so the view holds a bounded slice of
+//! a session of any length. The tail (the attach rows plus live appends) is never
+//! evicted.
+
+use std::collections::VecDeque;
+
+use anyhow::Result;
+use pa_types::daemon::{DaemonCommand, TranscriptPage};
+use serde_json::{Map, Value};
+
+use super::SessionUi;
+use crate::chat::{ChatEntry, StatusKind};
+use crate::snapshot::BackfillSeam;
+use crate::view::AgentView;
+
+/// Messages per page request.
+pub(crate) const CHUNK_MESSAGES: usize = 256;
+/// Fetched chunks resident above the tail.
+const RESIDENT_CHUNKS: usize = 3;
+/// A page loads once the viewport is this many entries from the resident edge.
+const PREFETCH_ENTRIES: usize = 128;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum PageKind {
+ /// Above the resident run.
+ Older,
+ /// Between the resident run and the tail (closing the gap).
+ Newer,
+ /// The session's first page, replacing the resident run.
+ Head,
+}
+
+pub(crate) struct TranscriptPageNote {
+ pub epoch: u64,
+ pub kind: PageKind,
+ pub page: std::result::Result<LoadedPage, String>,
+}
+
+pub(crate) struct LoadedPage {
+ entries: Vec<ChatEntry>,
+ seam: BackfillSeam,
+ first_id: Option<String>,
+ last_id: Option<String>,
+ more: bool,
+}
+
+struct Chunk {
+ first_id: String,
+ last_id: String,
+ entries: usize,
+ seam: BackfillSeam,
+}
+
+#[derive(Default)]
+pub(crate) struct TranscriptWindow {
+ /// The attached branch: every page request is validated against it.
+ leaf_id: Option<String>,
+ /// The tail's oldest row; `None` when nothing older than the tail exists.
+ tail_first_id: Option<String>,
+ tail_seam: BackfillSeam,
+ chunks: VecDeque<Chunk>,
+ /// The oldest resident row is the session's first.
+ start_resident: bool,
+ /// Rows between the resident chunks and the tail are evicted; one status row
+ /// marks the boundary.
+ gap: bool,
+ head_requested: bool,
+ /// A page failed: no more pages until the next reset.
+ failed: bool,
+ epoch: u64,
+ /// Dropping the handle aborts the in-flight page; the epoch fences a note
+ /// that was already queued.
+ fetch: Option<tokio_util::task::AbortOnDropHandle<()>>,
+}
+
+impl TranscriptWindow {
+ /// Start over on a freshly replaced transcript: the view holds only the tail.
+ pub(crate) fn reset(
+ &mut self,
+ leaf_id: Option<String>,
+ tail_first_id: Option<String>,
+ tail_seam: BackfillSeam,
+ ) {
+ let epoch = self.epoch.wrapping_add(1);
+ *self = Self {
+ start_resident: tail_first_id.is_none(),
+ leaf_id,
+ tail_first_id,
+ tail_seam,
+ epoch,
+ ..Self::default()
+ };
+ }
+
+ /// Fence the in-flight page without touching the resident rows.
+ pub(crate) fn retire(&mut self) {
+ self.epoch = self.epoch.wrapping_add(1);
+ self.fetch = None;
+ }
+
+ /// Abandon the in-flight page; a note that already arrived still applies.
+ pub(crate) fn retire_fetch(&mut self) {
+ self.fetch = None;
+ }
+
+ /// Whether history the view does not hold exists (or is being loaded).
+ pub(crate) fn incomplete(&self) -> bool {
+ !self.start_resident || self.gap || self.fetch.is_some()
+ }
+
+ /// The top key: the session's first page replaces the resident run.
+ pub(crate) fn request_head(&mut self) {
+ self.head_requested = !self.start_resident;
+ }
+
+ fn resident_entries(&self) -> usize {
+ self.chunks.iter().map(|chunk| chunk.entries).sum()
+ }
+
+ fn tail_start(&self) -> usize {
+ self.resident_entries() + usize::from(self.gap)
+ }
+
+ /// The page the viewport needs next, if any.
+ fn next_page(&self, view: &AgentView) -> Option<(PageKind, TranscriptPage)> {
+ if self.fetch.is_some() || self.failed {
+ return None;
+ }
+ let tail_first_id = self.tail_first_id.clone()?;
+ if self.head_requested {
+ let page = TranscriptPage::Start {
+ after: None,
+ until: Some(tail_first_id),
+ limit: CHUNK_MESSAGES,
+ };
+ return Some((PageKind::Head, page));
+ }
+ let (first, last) = view.visible_entries()?;
+ if !self.start_resident && first < PREFETCH_ENTRIES {
+ let before = self
+ .chunks
+ .front()
+ .map_or(tail_first_id, |chunk| chunk.first_id.clone());
+ let page = TranscriptPage::End {
+ before: Some(before),
+ limit: CHUNK_MESSAGES,
+ };
+ return Some((PageKind::Older, page));
+ }
+ let back = self.chunks.back()?;
+ if self.gap && last + PREFETCH_ENTRIES >= self.resident_entries() {
+ let page = TranscriptPage::Start {
+ after: Some(back.last_id.clone()),
+ until: Some(tail_first_id),
+ limit: CHUNK_MESSAGES,
+ };
+ return Some((PageKind::Newer, page));
+ }
+ None
+ }
+
+ /// Fold a loaded page into the view. Returns how many entries the rows above
+ /// the tail grew by (negative when they shrank).
+ fn apply(&mut self, kind: PageKind, page: LoadedPage, view: &mut AgentView) -> isize {
+ let (Some(first_id), Some(last_id)) = (page.first_id, page.last_id) else {
+ match kind {
+ PageKind::Older | PageKind::Head => self.start_resident = true,
+ PageKind::Newer => self.gap = false,
+ }
+ self.head_requested = false;
+ return 0;
+ };
+ let mut entries = page.entries;
+ // A page that reaches the tail joins it, as an older page joins what lies below.
+ if kind != PageKind::Older && !page.more {
+ crate::snapshot::join_backfilled_entries(&mut entries, self.tail_seam);
+ }
+ let chunk = |entries: usize| Chunk {
+ first_id,
+ last_id,
+ entries,
+ seam: page.seam,
+ };
+ match kind {
+ PageKind::Older => {
+ let top_seam = self.chunks.front().map_or(self.tail_seam, |top| top.seam);
+ crate::snapshot::join_backfilled_entries(&mut entries, top_seam);
+ let count = entries.len();
+ view.prepend_entries(entries);
+ self.chunks.push_front(chunk(count));
+ self.start_resident = !page.more;
+ let mut grown = count as isize;
+ if self.chunks.len() > RESIDENT_CHUNKS {
+ grown += self.evict_newest(view);
+ }
+ grown
+ }
+ PageKind::Newer => {
+ let at = self.resident_entries();
+ let count = entries.len();
+ if page.more {
+ entries.push(gap_row());
+ }
+ view.replace_entries(at..at + 1, entries);
+ self.chunks.push_back(chunk(count));
+ self.gap = page.more;
+ let mut grown = count as isize - isize::from(!page.more);
+ if self.chunks.len() > RESIDENT_CHUNKS {
+ let oldest = self.chunks.pop_front().map_or(0, |chunk| chunk.entries);
+ view.drop_leading_entries(oldest);
+ self.start_resident = false;
+ grown -= oldest as isize;
+ }
+ grown
+ }
+ PageKind::Head => {
+ let replaced = self.tail_start();
+ let count = entries.len();
+ if page.more {
+ entries.push(gap_row());
+ }
+ let inserted = entries.len();
+ view.drop_leading_entries(replaced);
+ view.prepend_entries(entries);
+ view.scroll_to_top();
+ self.chunks = VecDeque::from([chunk(count)]);
+ self.gap = page.more;
+ self.start_resident = true;
+ self.head_requested = false;
+ inserted as isize - replaced as isize
+ }
+ }
+ }
+
+ /// Evict the chunk next to the tail, leaving the gap row in its place.
+ fn evict_newest(&mut self, view: &mut AgentView) -> isize {
+ let Some(newest) = self.chunks.pop_back() else {
+ return 0;
+ };
+ let at = self.resident_entries();
+ if self.gap {
+ view.replace_entries(at..at + newest.entries, Vec::new());
+ -(newest.entries as isize)
+ } else {
+ view.replace_entries(at..at + newest.entries, vec![gap_row()]);
+ self.gap = true;
+ 1 - newest.entries as isize
+ }
+ }
+
+ /// Drop a disjoint resident run, leaving the contiguous tail. Returns how many
+ /// entries the rows above the tail shrank by.
+ fn collapse_to_tail(&mut self, view: &mut AgentView) -> usize {
+ if !self.gap {
+ return 0;
+ }
+ let dropped = self.tail_start();
+ view.drop_leading_entries(dropped);
+ self.chunks.clear();
+ self.gap = false;
+ self.start_resident = false;
+ self.retire();
+ dropped
+ }
+}
+
+fn gap_row() -> ChatEntry {
+ ChatEntry::Status {
+ text: "Loading newer history\u{2026}".to_string(),
+ kind: StatusKind::Info,
+ }
+}
+
+impl SessionUi {
+ /// Whether the viewport needs a page that is not yet in flight.
+ pub(crate) fn wants_transcript_page(&self, view: &AgentView) -> bool {
+ self.window.next_page(view).is_some()
+ }
+
+ /// Start the page the viewport needs, if any. Runs at the loop top after a paint,
+ /// so the visible range is the painted one.
+ pub(crate) fn spawn_transcript_page(&mut self, view: &AgentView) {
+ let Some((kind, page)) = self.window.next_page(view) else {
+ return;
+ };
+ let client = self.client.clone();
+ let active_session_id = self.active_session_id.clone();
+ let epoch = self.window.epoch;
+ let leaf_id = self.window.leaf_id.clone();
+ let notes = self.page_notes.clone();
+ let task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
+ let page: Result<LoadedPage> = async {
+ let leaf_id =
+ leaf_id.ok_or_else(|| anyhow::anyhow!("missing history branch anchor"))?;
+ let command = DaemonCommand::GetMessages {
+ id: None,
+ active_session_id,
+ page: Some(page),
+ 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 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 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"));
+ }
+ parse_page(data).await
+ }
+ .await;
+ let page = page.map_err(|error| error.to_string());
+ let _ = notes.send(TranscriptPageNote { epoch, kind, page });
+ }));
+ self.window.fetch = Some(task);
+ }
+
+ pub(crate) fn apply_transcript_page(&mut self, note: TranscriptPageNote, view: &mut AgentView) {
+ if note.epoch != self.window.epoch {
+ return;
+ }
+ self.window.fetch = None;
+ let page = match note.page {
+ Ok(page) => page,
+ Err(error) => {
+ self.window.failed = true;
+ view.push_entry(ChatEntry::Status {
+ text: format!(
+ "History could not be loaded: {error}. Reopen the session to retry."
+ ),
+ kind: StatusKind::Warning,
+ });
+ self.dirty = true;
+ return;
+ }
+ };
+ if self.last_assistant_text.is_none() {
+ self.last_assistant_text = super::last_assistant_text_of(&page.entries);
+ }
+ let grown = self.window.apply(note.kind, page, view);
+ self.shift_tail_indices(grown);
+ self.pressed_click = None;
+ self.trim_after_frame = true;
+ self.dirty = true;
+ }
+
+ /// The follow key and the exit flush: a resident run cut off from the tail drops.
+ pub(crate) fn collapse_transcript_window(&mut self, view: &mut AgentView) {
+ let dropped = self.window.collapse_to_tail(view);
+ if dropped > 0 {
+ self.shift_tail_indices(-(dropped as isize));
+ self.dirty = true;
+ }
+ }
+
+ /// The session's chat indices all point into the tail: rows changing above it
+ /// move them.
+ fn shift_tail_indices(&mut self, delta: isize) {
+ for index in [
+ &mut self.last_status_index,
+ &mut self.streaming_index,
+ &mut self.goal_view.last_status_index,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ *index = index.saturating_add_signed(delta);
+ }
+ }
+
+ /// Re-read the transcript tail and replace the view with it (the navigation,
+ /// fork, import, and reload rebuilds). Best effort: a failed fetch keeps the view.
+ pub(crate) async fn rebuild_transcript(&mut self, view: &mut AgentView) {
+ let incomplete_history = self.window.incomplete();
+ self.window.retire();
+ self.last_status_index = None;
+ self.pressed_click = None;
+ let data = self
+ .bounded_request(
+ std::time::Duration::from_millis(super::UI_REQUEST_TIMEOUT_MS),
+ DaemonCommand::GetMessages {
+ id: None,
+ active_session_id: self.active_session_id.clone(),
+ page: Some(TranscriptPage::End {
+ before: None,
+ limit: CHUNK_MESSAGES,
+ }),
+ capabilities: Some(crate::session_ui::attach_capabilities()),
+ rest: Map::default(),
+ },
+ )
+ .await;
+ let leaf_id = data
+ .as_ref()
+ .ok()
+ .and_then(|data| data.get("historyLeafId"))
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ let page = match data {
+ Ok(data) => parse_page(data).await.ok(),
+ Err(_) => None,
+ };
+ let Some(page) = page else {
+ // The resident rows may no longer match the branch: page no further.
+ self.window.failed = true;
+ 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;
+ };
+ self.window
+ .reset(leaf_id, page.first_id.filter(|_| page.more), page.seam);
+ view.clear_chat();
+ for entry in page.entries {
+ view.push_entry(entry);
+ }
+ view.follow();
+ self.dirty = true;
+ }
+}
+
+/// Decode a page response off the UI thread.
+async fn parse_page(mut data: Value) -> Result<LoadedPage> {
+ let Some(Value::Array(messages)) = data.get_mut("messages").map(Value::take) else {
+ return Err(anyhow::anyhow!("missing messages in history response"));
+ };
+ let id = |key: &str| data.get(key).and_then(Value::as_str).map(str::to_owned);
+ let (first_id, last_id) = (id("firstEntryId"), id("lastEntryId"));
+ let more = data.get("more").and_then(Value::as_bool).unwrap_or(false);
+ let (entries, seam) = tokio::task::spawn_blocking(move || {
+ crate::snapshot::transcript_with_backfill_seam(&messages)
+ })
+ .await?;
+ Ok(LoadedPage {
+ entries,
+ seam,
+ first_id,
+ last_id,
+ more,
+ })
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use crate::daemon_client::DaemonClient;
+ use crate::interactive::SessionSelection;
+ use crate::session_ui::ActivityUpdates;
+ use serde_json::json;
+ use std::time::Duration;
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+ use tokio::sync::mpsc;
+
+ #[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, "leafId": "leaf"},
+ "messages": [], "historyBeforeEntryId": "e1", "lastEventSequence": 0,
+ }, "replay": {"status": "complete", "toSequence": 0},
+ "lastEventSequence": 0,
+ }),
+ "get_messages" => {
+ json!({
+ "messages": [{"role": "user", "content": "rebuilt transcript", "timestamp": 1}],
+ "firstEntryId": "e2", "lastEntryId": "e2", "more": false,
+ "historyLeafId": "leaf",
+ })
+ }
+ _ => 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 (page_tx, mut page_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,
+ },
+ page_tx.clone(),
+ )
+ .await
+ .unwrap();
+ let old_epoch = session.window.epoch;
+ assert!(page_tx
+ .send(TranscriptPageNote {
+ epoch: old_epoch,
+ kind: PageKind::Older,
+ page: Ok(LoadedPage {
+ entries: crate::snapshot::transcript_to_entries(&[
+ json!({"role": "user", "content": "stale history", "timestamp": 0}),
+ ]),
+ seam: BackfillSeam::Preserve,
+ first_id: Some("e0".to_string()),
+ last_id: Some("e0".to_string()),
+ more: false,
+ }),
+ })
+ .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.window.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_page(page_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");
+ }
+
+ #[test]
+ fn a_page_reaching_the_tail_joins_its_retry_seam() {
+ let attempt = json!({
+ "role": "assistant", "content": [], "stopReason": "error",
+ "errorMessage": "attempt failed", "timestamp": 2,
+ });
+ let (entries, seam) = crate::snapshot::transcript_with_backfill_seam(&[
+ json!({"role": "user", "content": "run", "timestamp": 1}),
+ attempt,
+ ]);
+ let mut window = TranscriptWindow::default();
+ window.reset(
+ Some("leaf".to_string()),
+ Some("tail".to_string()),
+ BackfillSeam::RetryOutcome,
+ );
+ let mut view = AgentView::new(crate::theme::Theme::builtin(
+ "prime",
+ crate::theme::ColorMode::TrueColor,
+ ));
+ let page = LoadedPage {
+ entries,
+ seam,
+ first_id: Some("e0".to_string()),
+ last_id: Some("e1".to_string()),
+ more: false,
+ };
+ window.apply(PageKind::Head, page, &mut view);
+ assert_eq!(
+ view.chat,
+ vec![ChatEntry::User {
+ text: "run".to_string()
+ }],
+ "the tail's retry outcome supersedes the attempt the head page ends with"
+ );
+ }
+}
diff --git a/crates/pa-tui/src/snapshot.rs b/crates/pa-tui/src/snapshot.rs
index 7b67c83724..bc1dc16b0b 100644
--- a/crates/pa-tui/src/snapshot.rs
+++ b/crates/pa-tui/src/snapshot.rs
@@ -79,7 +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,
+ /// The tail's oldest row when older history exists (the page cursor).
+ pub history_before_entry_id: Option<String>,
pub(crate) backfill_seam: BackfillSeam,
}
@@ -186,39 +187,6 @@ struct OrphanResult {
view: crate::chat::ToolResultView,
}
-/// The wire context is summary-first for the model, but the transcript
-/// presents the compaction summary at its chronological boundary — after
-/// the retained messages (`retainedMessageCount`). A missing count falls
-/// back to the timestamp split (pre-count summaries).
-fn order_messages_for_transcript(messages: &[Value]) -> Vec<&Value> {
- let Some(summary_index) = messages.iter().position(|message| {
- message.get("role").and_then(Value::as_str) == Some("compactionSummary")
- }) else {
- return messages.iter().collect();
- };
- let summary = &messages[summary_index];
- let mut rest: Vec<&Value> = messages
- .iter()
- .enumerate()
- .filter(|(index, _)| *index != summary_index)
- .map(|(_, message)| message)
- .collect();
- let boundary = if let Some(retained) =
- summary.get("retainedMessageCount").and_then(Value::as_u64)
- {
- (retained as usize).min(rest.len())
- } else {
- let summary_timestamp = summary.get("timestamp").and_then(Value::as_f64);
- let retained = rest
- .iter()
- .filter(|message| message.get("timestamp").and_then(Value::as_f64) < summary_timestamp)
- .count();
- retained.min(rest.len())
- };
- rest.insert(boundary, summary);
- rest
-}
-
/// Replay a whole transcript, folding `toolResult` messages onto their
/// pending cards; one id-to-index map keeps the fold linear.
#[must_use]
@@ -233,12 +201,11 @@ pub(crate) enum BackfillSeam {
RetryOutcome,
}
-fn transcript_with_backfill_seam(messages: &[Value]) -> (Vec<ChatEntry>, BackfillSeam) {
- let ordered = order_messages_for_transcript(messages);
+pub(crate) fn transcript_with_backfill_seam(messages: &[Value]) -> (Vec<ChatEntry>, BackfillSeam) {
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 {
+ for message in messages {
if let Some(result) = tool_result_message_view(message) {
let tool_call_id = result.tool_call_id.clone();
if let Some(result) = settle_last_pending(
@@ -415,10 +382,10 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
.and_then(|state| state.get("serviceTier"))
.and_then(Value::as_str)
.map(str::to_string);
- let history_before = snapshot
- .get("historyBefore")
- .and_then(Value::as_u64)
- .map_or(0, |history| history as usize);
+ let history_before_entry_id = snapshot
+ .get("historyBeforeEntryId")
+ .and_then(Value::as_str)
+ .map(str::to_owned);
let last_user_prompt_ms = snapshot
.get("messages")
.and_then(Value::as_array)
@@ -430,9 +397,9 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
})
})
.or_else(|| {
- (history_before > 0)
- .then(|| snapshot.get("lastUserPromptMs").and_then(Value::as_u64))
- .flatten()
+ history_before_entry_id
+ .as_ref()
+ .and_then(|_| snapshot.get("lastUserPromptMs").and_then(Value::as_u64))
});
Reconstructed {
chat: messages,
@@ -449,7 +416,7 @@ pub fn reconstruct(attach: &AttachData) -> Reconstructed {
queued,
service_tier,
last_user_prompt_ms,
- history_before,
+ history_before_entry_id,
backfill_seam,
}
}
diff --git a/crates/pa-tui/src/snapshot/tests.rs b/crates/pa-tui/src/snapshot/tests.rs
index b0bc7831f8..90e024431c 100644
--- a/crates/pa-tui/src/snapshot/tests.rs
+++ b/crates/pa-tui/src/snapshot/tests.rs
@@ -103,39 +103,6 @@ fn empty_user_message_renders_no_entry() {
assert!(message_value_to_entries(&message).is_empty());
}
-#[test]
-fn transcript_presents_the_summary_after_the_retained_tail() {
- let messages = vec![
- json!({
- "role": "compactionSummary", "summary": "the story",
- "retainedMessageCount": 2, "tokensBefore": 12, "timestamp": 30u64
- }),
- json!({"role": "user", "content": "second turn", "timestamp": 20u64}),
- json!({"role": "assistant", "content": "kept intact", "timestamp": 25u64}),
- json!({
- "role": "custom", "customType": "session_slash_command",
- "content": "/compact focus on the goal", "display": true, "timestamp": 40u64,
- "details": { "command": {
- "name": "compact",
- "args": "focus on the goal",
- "text": "/compact focus on the goal"
- } }
- }),
- ];
- let entries = transcript_to_entries(&messages);
- let order: Vec<String> = entries
- .iter()
- .filter_map(|entry| match entry {
- ChatEntry::User { .. } => Some("user".to_string()),
- ChatEntry::Assistant { .. } => Some("assistant".to_string()),
- ChatEntry::CompactionSummary { .. } => Some("summary".to_string()),
- ChatEntry::SlashCommand { .. } => Some("slash".to_string()),
- _ => None,
- })
- .collect();
- assert_eq!(order, ["user", "assistant", "summary", "slash"]);
-}
-
#[test]
fn unnamed_streamed_tool_call_renders_code_once_named() {
let mut view = test_view();
@@ -2174,7 +2141,7 @@ fn a_windowed_snapshot_reconstructs_the_full_history_scalars() {
{ "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"]["historyBeforeEntryId"] = json!("e1");
windowed["snapshot"]["lastUserPromptMs"] = json!(100u64);
let full_prompt_ms = reconstruct(&attach_data_from_response(full).unwrap()).last_user_prompt_ms;
@@ -2227,7 +2194,7 @@ fn backfilled_entries_match_the_full_decode_across_the_seam() {
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")],
+ &[user("kept one"), user("kept two"), summary, answer("after")],
3,
);
}
@@ -2311,7 +2278,7 @@ fn windowed_prompt_time_prefers_the_readable_tail_over_an_older_scalar() {
json!("1970-01-01T01:00:02.000+01:00"),
] {
let mut data = slim_attach();
- data["snapshot"]["historyBefore"] = json!(1);
+ data["snapshot"]["historyBeforeEntryId"] = json!("e1");
data["snapshot"]["lastUserPromptMs"] = json!(1000);
data["snapshot"]["messages"] = json!([
{ "role": "user", "content": "latest", "timestamp": timestamp }
@@ -2320,7 +2287,7 @@ fn windowed_prompt_time_prefers_the_readable_tail_over_an_older_scalar() {
full["snapshot"]
.as_object_mut()
.unwrap()
- .remove("historyBefore");
+ .remove("historyBeforeEntryId");
full["snapshot"]
.as_object_mut()
.unwrap()
diff --git a/crates/pa-tui/src/view.rs b/crates/pa-tui/src/view.rs
index 62bcc2acde..e78bd11444 100644
--- a/crates/pa-tui/src/view.rs
+++ b/crates/pa-tui/src/view.rs
@@ -486,31 +486,102 @@ impl AgentView {
};
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));
+ self.splice_chat(0..0, entries);
+ self.note_prepended_entries(count, seam_before, cursor_spacing_before);
+ }
+
+ /// Replace `range`, which lies below the viewport, with `entries`: a paused
+ /// viewport keeps its rows.
+ pub fn replace_entries(&mut self, range: std::ops::Range<usize>, entries: Vec<ChatEntry>) {
+ self.pending_handoff = None;
+ let width = self.layout_width;
+ // The entry after the range re-measures too: its spacing follows its neighbor.
+ let follower = usize::from(range.end < self.chat.len());
+ let rows = |view: &Self, from: usize, to: usize| -> usize {
+ (from..to)
+ .map(|index| view.count_entry_rows(index, width))
+ .sum()
+ };
+ let before = if width > 0 {
+ rows(self, range.start, range.end + follower)
+ } else {
+ 0
+ };
+ let start = range.start;
+ let inserted = entries.len();
+ self.splice_chat(range, entries);
+ if width > 0 {
+ let after = rows(self, start, start + inserted + follower);
+ self.sparse_tail_delta(after as isize - before as isize, start);
+ }
+ }
+
+ /// Drop the first `count` entries, which lie above the viewport: the window
+ /// re-anchors to the tail, which they do not touch.
+ pub fn drop_leading_entries(&mut self, count: usize) {
+ if count == 0 {
+ return;
+ }
+ self.pending_handoff = None;
+ self.reanchor_paused_window_for_prepend();
+ self.splice_chat(0..count, Vec::new());
+ self.note_dropped_entries(count);
+ }
+
+ /// Splice the chat and every per-entry cache keyed by its index.
+ fn splice_chat(&mut self, range: std::ops::Range<usize>, entries: Vec<ChatEntry>) {
+ let inserted = entries.len();
+ let removed = range.len();
+ let shift = |index: usize| -> Option<usize> {
+ if index < range.start {
+ Some(index)
+ } else if index < range.end {
+ None
+ } else {
+ Some(index - removed + inserted)
+ }
+ };
+ if let Some((index, rows)) = self.sparse_mutation {
+ self.sparse_mutation = shift(index).map(|index| (index, rows));
+ }
{
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))
+ .filter_map(|(index, cache)| Some((shift(index)?, cache)))
.collect();
*caches = shifted;
}
self.sparse_entries = self
.sparse_entries
.iter()
- .map(|index| index + count)
+ .filter_map(|i| shift(*i))
.collect();
self.toggled_cards = self
.toggled_cards
.iter()
- .map(|index| index + count)
+ .filter_map(|i| shift(*i))
.collect();
- self.note_prepended_entries(count, seam_before, cursor_spacing_before);
+ self.entry_layout.splice(
+ range.clone(),
+ std::iter::repeat_n([None, None, None], inserted),
+ );
+ self.entry_heights.splice(
+ range.clone(),
+ std::iter::repeat_n([None, None, None], inserted),
+ );
+ self.chat.splice(range, entries);
+ }
+
+ /// The first and last chat entries the last frame showed.
+ pub(crate) fn visible_entries(&self) -> Option<(usize, usize)> {
+ let entries = self
+ .click
+ .window_sections
+ .iter()
+ .map(|section| section.entry);
+ Some((entries.clone().min()?, entries.max()?))
}
/// Drop the whole transcript and its cached layout (a fresh snapshot
diff --git a/crates/pa-tui/src/view/lazy.rs b/crates/pa-tui/src/view/lazy.rs
index 95f7c0feeb..58b57139a5 100644
--- a/crates/pa-tui/src/view/lazy.rs
+++ b/crates/pa-tui/src/view/lazy.rs
@@ -186,9 +186,6 @@ impl AgentView {
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;
@@ -220,6 +217,15 @@ impl AgentView {
self.sparse_window = Some(window);
}
+ /// `count` leading entries above the window dropped: the cursor's entry moved up.
+ pub(super) fn note_dropped_entries(&mut self, count: usize) {
+ if let Some(window) = &mut self.sparse_window {
+ window.cursor = window.cursor.and_then(|(section, row)| {
+ Some((section.checked_sub(count).filter(|s| *s > 0)?, row))
+ });
+ }
+ }
+
/// 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
index fbf28de15a..ddcc614269 100644
--- a/crates/pa-tui/src/view/prepend_tests.rs
+++ b/crates/pa-tui/src/view/prepend_tests.rs
@@ -220,3 +220,66 @@ fn prepended_history_keeps_a_paused_tool_after_hidden_entries() {
"removing a leading spacer must preserve the visible tool's content row"
);
}
+
+#[test]
+fn spliced_rows_off_screen_keep_a_paused_window_through_a_geometry_resolve() {
+ let mut sparse = view();
+ sparse.splash_suppressed = true;
+ for index in 0..300 {
+ sparse.push_entry(body("row", index));
+ }
+ sparse.render_frame(37, 24);
+ sparse.scroll_by(-120);
+ let paused = sparse.render_frame(37, 24);
+ let (first, last) = sparse.visible_entries().expect("visible entries");
+ assert!(
+ first > 40 && last + 20 < 300,
+ "the window sits mid-transcript"
+ );
+
+ // Below the window: the evicted rows leave a status row in their place.
+ let gap = ChatEntry::Status {
+ text: "gap".to_string(),
+ kind: crate::chat::StatusKind::Info,
+ };
+ sparse.replace_entries(last + 5..last + 15, vec![gap]);
+ // Above the window: the oldest rows drop.
+ sparse.drop_leading_entries(30);
+ assert_eq!(
+ sparse.render_frame(37, 24),
+ paused,
+ "the walked window keeps its rows"
+ );
+ sparse.resolve_sparse_geometry();
+ sparse.sparse_enabled = false;
+ assert_eq!(
+ sparse.render_frame(37, 24),
+ paused,
+ "the exact geometry places the window on the same rows"
+ );
+
+ // A top-anchored window: rows dropped above it move its absolute offset.
+ let mut top = view();
+ top.splash_suppressed = true;
+ for index in 0..300 {
+ top.push_entry(body("row", index));
+ }
+ top.render_frame(37, 24);
+ top.scroll_to_top();
+ top.render_frame(37, 24);
+ top.scroll_by(120);
+ let paused = top.render_frame(37, 24);
+ top.drop_leading_entries(30);
+ assert_eq!(
+ top.render_frame(37, 24),
+ paused,
+ "the walked window keeps its rows"
+ );
+ top.resolve_sparse_geometry();
+ top.sparse_enabled = false;
+ assert_eq!(
+ top.render_frame(37, 24),
+ paused,
+ "the exact geometry places the top-anchored window on the same rows"
+ );
+}
diff --git a/crates/pa-tui/tests/transcript_window_headless.rs b/crates/pa-tui/tests/transcript_window_headless.rs
new file mode 100644
index 0000000000..c74d1f9fc0
--- /dev/null
+++ b/crates/pa-tui/tests/transcript_window_headless.rs
@@ -0,0 +1,431 @@
+//! The transcript window against a paging mock: anchored scrolling through older
+//! pages, and a bounded resident run.
+#![cfg(unix)]
+// Casts: bounded fixture arithmetic.
+#![allow(
+ clippy::too_many_lines,
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap
+)]
+
+use std::collections::HashSet;
+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 MESSAGES: usize = 2_000;
+const TAIL: usize = 300;
+/// The window's page size and resident chunk count (the bound under test).
+const CHUNK: usize = 256;
+const RESIDENT_CHUNKS: usize = 3;
+const LEAF: &str = "leaf";
+const GAP_ROW: &str = "Loading newer history";
+const WHEEL_UP: &str = "\x1b[<64;10;10M";
+const HEIGHT: u16 = 50;
+
+fn entry_id(index: usize) -> String {
+ format!("e{index:05}")
+}
+
+fn index_of(id: &str) -> usize {
+ id[1..].parse().expect("entry id")
+}
+
+fn message(index: usize) -> Value {
+ let text = format!("msg-{index:05} row");
+ if index.is_multiple_of(2) {
+ json!({ "role": "user", "content": text, "timestamp": index })
+ } else {
+ json!({ "role": "assistant", "content": [{ "type": "text", "text": text }], "timestamp": index })
+ }
+}
+
+/// The paging daemon: `MESSAGES` rows, a `TAIL`-row attach, and pages served by id.
+struct MockSupervisor {
+ listener: UnixListener,
+ /// Never answer newer pages (`from: start` with an `after` cursor).
+ hold_newer: bool,
+ pages: Arc<Mutex<Vec<Value>>>,
+}
+
+impl MockSupervisor {
+ fn serve(self) {
+ let (stream, _) = self.listener.accept().expect("accept");
+ let mut writer = stream.try_clone().expect("clone mock socket");
+ let mut reader = 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["id"].as_str().unwrap_or_default().to_string();
+ let command = envelope["command"].clone();
+ let kind = command["type"].as_str().unwrap_or_default().to_string();
+ let data = match kind.as_str() {
+ "attach" => attach_data(),
+ "get_messages" => {
+ let page = command["page"].clone();
+ self.pages.lock().unwrap().push(page.clone());
+ if self.hold_newer && page["from"] == "start" && page.get("after").is_some() {
+ continue;
+ }
+ page_data(&page)
+ }
+ "get_session_stats" => json!({
+ "contextUsage": { "tokens": 1200, "contextWindow": 200_000 }, "cost": 0.01,
+ }),
+ _ => json!({}),
+ };
+ write_json(
+ &mut writer,
+ &json!({ "type": "response", "id": id, "command": kind, "success": true, "data": data }),
+ );
+ }
+ }
+}
+
+fn attach_data() -> Value {
+ json!({
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "activeSessionId": "s1",
+ "snapshot": {
+ "activeSessionId": "s1",
+ "summary": { "id": "s1", "cwd": "/tmp" },
+ "state": {
+ "activeSessionId": "s1", "cwd": "/tmp", "sessionId": "sess-1",
+ "sessionName": "window probe", "model": "faux-1", "isStreaming": false,
+ "isCompacting": false, "leafId": LEAF,
+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
+ },
+ "messages": (MESSAGES - TAIL..MESSAGES).map(message).collect::<Vec<_>>(),
+ "historyBeforeEntryId": entry_id(MESSAGES - TAIL),
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ },
+ "replay": { "status": "complete", "toSequence": 0 },
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ "client": { "id": "mock", "capabilities": [] },
+ })
+}
+
+fn page_data(page: &Value) -> Value {
+ let limit = page["limit"].as_u64().expect("page limit") as usize;
+ let cursor = |key: &str| page.get(key).and_then(Value::as_str).map(index_of);
+ let (start, end, more) = if page["from"] == "end" {
+ let end = cursor("before").unwrap_or(MESSAGES);
+ let start = end.saturating_sub(limit);
+ (start, end, start > 0)
+ } else {
+ let start = cursor("after").map_or(0, |after| after + 1);
+ let until = cursor("until").unwrap_or(MESSAGES);
+ let end = (start + limit).min(until);
+ (start, end, end < until)
+ };
+ json!({
+ "messages": (start..end).map(message).collect::<Vec<_>>(),
+ "firstEntryId": (start < end).then(|| entry_id(start)),
+ "lastEntryId": (start < end).then(|| entry_id(end - 1)),
+ "more": more,
+ "historyLeafId": LEAF,
+ })
+}
+
+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 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(hold_newer: bool, 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 pages = Arc::new(Mutex::new(Vec::new()));
+ let supervisor = MockSupervisor {
+ listener: UnixListener::bind(&socket).expect("bind mock socket"),
+ hold_newer,
+ pages: Arc::clone(&pages),
+ };
+ 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: HEIGHT,
+ };
+ let outcome = runtime
+ .block_on(run_interactive(options(socket), UiMode::Headless(plan)))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let pages = pages.lock().unwrap().clone();
+ (outcome.frames, pages)
+}
+
+fn key(code: crossterm::event::KeyCode) -> HeadlessStep {
+ HeadlessStep::Key(crossterm::event::KeyEvent::new(
+ code,
+ crossterm::event::KeyModifiers::NONE,
+ ))
+}
+
+/// `(row, message index)` for every marker line of a frame, top to bottom.
+fn marker_rows(frame: &str) -> Vec<(usize, usize)> {
+ frame
+ .lines()
+ .enumerate()
+ .filter_map(|(row, line)| {
+ let at = line.find("msg-")?;
+ Some((row, line[at + 4..at + 9].parse().ok()?))
+ })
+ .collect()
+}
+
+const ROWS_PER_MESSAGE: isize = 3;
+
+/// The transcript row at the frame's top, from its marker lines above any gap row
+/// (which must agree). The first message has no leading spacer, so it is skipped.
+fn transcript_row(frame: &str) -> isize {
+ let gap = frame
+ .lines()
+ .position(|line| line.contains(GAP_ROW))
+ .unwrap_or(usize::MAX);
+ let rows: Vec<isize> = marker_rows(frame)
+ .into_iter()
+ .filter(|(row, index)| *row < gap && *index > 0)
+ .map(|(row, index)| index as isize * ROWS_PER_MESSAGE - row as isize)
+ .collect();
+ assert!(
+ rows.windows(2).all(|pair| pair[0] == pair[1]),
+ "every message renders as {ROWS_PER_MESSAGE} rows:\n{frame}"
+ );
+ rows[0]
+}
+
+/// The content's move between consecutive frames, in rows (positive: it moved down).
+/// A chunk landing above or evicted below must never move it, so every move is one
+/// scroll step.
+fn moves(frames: &[String]) -> Vec<(usize, isize)> {
+ frames
+ .windows(2)
+ .enumerate()
+ .map(|(index, pair)| (index, transcript_row(&pair[0]) - transcript_row(&pair[1])))
+ .collect()
+}
+
+fn top_marker(frame: &str) -> Option<usize> {
+ marker_rows(frame).first().map(|(_, index)| *index)
+}
+
+/// Paced steps: the plan pauses after each batch so arrived pages apply between
+/// batches, as they do between a user's keystrokes.
+fn paced(batch: &[HeadlessStep], batches: usize) -> Vec<HeadlessStep> {
+ let mut steps = vec![HeadlessStep::WaitRender {
+ needle: format!("msg-{:05}", MESSAGES - 1),
+ timeout_ms: 5_000,
+ }];
+ for _ in 0..batches {
+ steps.extend(batch.iter().cloned());
+ steps.push(HeadlessStep::WaitMs(30));
+ }
+ steps
+}
+
+#[test]
+fn scrolling_up_through_older_pages_keeps_the_viewport_anchored() {
+ let mut batch: Vec<HeadlessStep> = (0..5)
+ .map(|_| HeadlessStep::Mouse(WHEEL_UP.to_string()))
+ .collect();
+ batch.push(key(crossterm::event::KeyCode::PageUp));
+ let (frames, pages) = run(false, paced(&batch, 220));
+ let reached_top = frames
+ .iter()
+ .position(|frame| top_marker(frame) == Some(0))
+ .unwrap_or_else(|| {
+ panic!(
+ "scrolling never reached the first message: {}",
+ frames.last().map_or("", String::as_str)
+ )
+ });
+ assert!(
+ pages.iter().filter(|page| page["from"] == "end").count() >= (MESSAGES - TAIL) / CHUNK,
+ "the climb loaded the history in older pages: {pages:?}"
+ );
+ let mut page_rows = None;
+ for (index, moved) in moves(&frames[1..reached_top]) {
+ if moved != 3 {
+ let page = *page_rows.get_or_insert(moved);
+ assert_eq!(
+ moved,
+ page,
+ "frame {}: the content moved by neither a wheel step nor a page:\n{}\n---\n{}",
+ index + 1,
+ frames[index + 1],
+ frames[index + 2]
+ );
+ }
+ }
+ assert!(page_rows.is_some(), "the plan paged as well as wheeled");
+}
+
+#[test]
+fn the_resident_run_stays_bounded_and_refills_on_return() {
+ // Climb to the session top, then descend with newer pages held: the rows still
+ // resident below the top end at the gap row after at most the resident chunks.
+ let mut up = paced(&[key(crossterm::event::KeyCode::PageUp)], 150);
+ up.extend(
+ paced(&[key(crossterm::event::KeyCode::PageDown)], 60)
+ .into_iter()
+ .skip(1),
+ );
+ let (frames, _) = run(true, up);
+ let top = frames
+ .iter()
+ .position(|frame| top_marker(frame) == Some(0))
+ .unwrap_or_else(|| {
+ panic!(
+ "paging up never reached the first message: {}",
+ frames.last().map_or("", String::as_str)
+ )
+ });
+ let gap = frames[top..]
+ .iter()
+ .find(|frame| frame.contains(GAP_ROW))
+ .unwrap_or_else(|| {
+ panic!(
+ "descending from the top never reached the evicted rows: {}",
+ frames.last().map_or("", String::as_str)
+ )
+ });
+ let gap_row = gap.lines().position(|line| line.contains(GAP_ROW)).unwrap();
+ let resident_end = marker_rows(gap)
+ .into_iter()
+ .filter(|(row, _)| *row < gap_row)
+ .map(|(_, index)| index)
+ .max()
+ .expect("resident rows above the gap row");
+ assert!(
+ resident_end < CHUNK * RESIDENT_CHUNKS,
+ "the resident run below the top holds at most {RESIDENT_CHUNKS} chunks, \
+ but reached msg-{resident_end:05}:\n{gap}"
+ );
+
+ // Unheld, the descent refetches the evicted rows: every message renders on the way
+ // back down, in order, without a skip.
+ // The climb ends with the top key, so the descent starts from a top-anchored window.
+ let mut steps = paced(&[key(crossterm::event::KeyCode::PageUp)], 150);
+ steps.push(HeadlessStep::ScrollTop);
+ steps.extend(
+ paced(&[key(crossterm::event::KeyCode::PageDown)], 150)
+ .into_iter()
+ .skip(1),
+ );
+ let (frames, pages) = run(false, steps);
+ let top = frames
+ .iter()
+ .position(|frame| top_marker(frame) == Some(0))
+ .expect("the climb reached the first message");
+ let bottom = frames
+ .iter()
+ .rposition(|frame| !frame.contains(&format!("msg-{:05}", MESSAGES - 1)))
+ .expect("the descent passed above the tail");
+ let descent = moves(&frames[top..bottom]);
+ let page = descent
+ .first()
+ .map(|(_, moved)| *moved)
+ .expect("the descent paged");
+ for (index, moved) in descent {
+ assert_eq!(
+ moved,
+ page,
+ "frame {}: a page down moved the content by {moved}, not one page ({page}):\n{}\n---\n{}",
+ top + index,
+ frames[top + index],
+ frames[top + index + 1]
+ );
+ }
+ let last = frames.last().expect("frames rendered");
+ assert!(
+ !last.contains(GAP_ROW) && last.contains(&format!("msg-{:05}", MESSAGES - 1)),
+ "the descent ends at the tail with the gap closed:\n{last}"
+ );
+ let mut seen = HashSet::new();
+ for frame in &frames[top..] {
+ seen.extend(marker_rows(frame).into_iter().map(|(_, index)| index));
+ }
+ let missing: Vec<usize> = (0..MESSAGES)
+ .filter(|index| !seen.contains(index))
+ .collect();
+ assert!(
+ missing.is_empty(),
+ "the descent skipped messages: {missing:?}"
+ );
+ assert!(
+ pages
+ .iter()
+ .any(|page| page["from"] == "start" && page.get("after").is_some()),
+ "rows evicted on the way up were refetched on the way down: {pages:?}"
+ );
+}
diff --git a/crates/pa-tui/tests/windowed_backfill_headless.rs b/crates/pa-tui/tests/windowed_backfill_headless.rs
index 3ff4931d17..8cd5121c5c 100644
--- a/crates/pa-tui/tests/windowed_backfill_headless.rs
+++ b/crates/pa-tui/tests/windowed_backfill_headless.rs
@@ -27,8 +27,6 @@ struct MockSupervisor {
/// 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>>>,
}
@@ -41,10 +39,6 @@ impl MockSupervisor {
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,
}
@@ -84,17 +78,6 @@ impl MockSupervisor {
"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 {
@@ -102,7 +85,7 @@ impl MockSupervisor {
write_json(&mut writer, &history_failure(id));
continue;
}
- if command.get("before").is_some() {
+ if command["page"].get("before").is_some() {
if self.hold_backfill {
held_backfill = Some(id.to_string());
// The frame is proof the server received this request;
@@ -118,20 +101,14 @@ impl MockSupervisor {
);
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);
+ write_json(&mut writer, &get_messages_response(id, &self));
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
+ // A cursor-less page 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() {
@@ -204,7 +181,7 @@ fn all_messages() -> Vec<Value> {
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))
+ (messages[4..].to_vec(), json!(entry_id(HISTORY_MESSAGES)))
} else {
(messages, Value::Null)
};
@@ -228,7 +205,7 @@ fn attach_response(id: &str, windowed: bool) -> Value {
"lastEventCursor": null,
});
if windowed {
- snapshot["historyBefore"] = history_before;
+ snapshot["historyBeforeEntryId"] = history_before;
snapshot["lastUserPromptMs"] = json!(114u64);
}
json!({
@@ -259,7 +236,12 @@ fn get_messages_response(id: &str, supervisor: &MockSupervisor) -> Value {
"id": id,
"command": "get_messages",
"success": true,
- "data": { "messages": messages },
+ "data": {
+ "messages": messages,
+ "firstEntryId": entry_id(0),
+ "lastEntryId": entry_id(HISTORY_MESSAGES - 1),
+ "more": false,
+ },
});
if let Some(history_leaf_id) = supervisor.history_leaf_id {
response["data"]["historyLeafId"] = json!(history_leaf_id);
@@ -273,10 +255,20 @@ fn whole_head_response(id: &str) -> Value {
"id": id,
"command": "get_messages",
"success": true,
- "data": { "messages": all_messages() },
+ "data": {
+ "messages": all_messages(),
+ "firstEntryId": entry_id(0),
+ "lastEntryId": entry_id(15),
+ "more": false,
+ "historyLeafId": HISTORY_LEAF_ID,
+ },
})
}
+fn entry_id(index: usize) -> String {
+ format!("e{index:02}")
+}
+
fn options(socket: PathBuf) -> InteractiveOptions {
InteractiveOptions {
models: None,
@@ -324,21 +316,12 @@ fn run_attached_with_failures(
failures: usize,
steps: Vec<HeadlessStep>,
) -> (Vec<String>, Vec<Value>) {
- run_attached_with_validation(
- windowed,
- failures,
- /*changed_prefix*/ false,
- None,
- Some(HISTORY_LEAF_ID),
- steps,
- )
+ run_attached_with_validation(windowed, failures, 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>) {
@@ -349,10 +332,6 @@ fn run_attached_with_validation(
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()
@@ -486,8 +465,8 @@ fn a_windowed_open_backfills_history_above_the_tail() {
);
assert_eq!(requests.len(), 1, "exactly one backfill request");
assert_eq!(
- requests[0]["before"],
- json!(HISTORY_MESSAGES as u64),
+ requests[0]["page"]["before"],
+ json!(entry_id(HISTORY_MESSAGES)),
"the backfill requests the omitted history range"
);
assert_eq!(
@@ -506,11 +485,9 @@ fn an_unverified_history_leaf_echo_keeps_the_attached_tail_and_reports_incomplet
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(),
+ needle: "History could not be loaded".to_string(),
timeout_ms: 5000,
}],
);
@@ -522,7 +499,7 @@ fn an_unverified_history_leaf_echo_keeps_the_attached_tail_and_reports_incomplet
assert!(
frames
.iter()
- .any(|frame| frame.contains("Older history could not be loaded")),
+ .any(|frame| frame.contains("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));
@@ -581,13 +558,13 @@ fn a_rejected_backfill_retries_then_reports_incomplete_history() {
true,
/*failures*/ 2,
vec![HeadlessStep::WaitRender {
- needle: "Older history could not be loaded".to_string(),
+ needle: "History could not be loaded".to_string(),
timeout_ms: 5000,
}],
);
assert!(frames
.iter()
- .any(|frame| frame.contains("Older history could not be loaded")));
+ .any(|frame| frame.contains("History could not be loaded")));
assert_eq!(requests.len(), 2);
assert_eq!(requests[0], requests[1]);
}
@@ -609,8 +586,8 @@ fn an_exit_with_backfill_in_flight_releases_the_daemon_connection() {
"the held history request stayed in flight across the run: {requests:?}"
);
assert_eq!(
- requests[0]["before"],
- json!(HISTORY_MESSAGES as u64),
+ requests[0]["page"]["before"],
+ json!(entry_id(HISTORY_MESSAGES)),
"the windowed attach armed exactly the history backfill: {requests:?}"
);
assert!(!frames.is_empty(), "frames were captured");
@@ -654,12 +631,12 @@ fn a_reload_rebuild_during_an_in_flight_backfill_keeps_rows_unique_and_ordered()
"one held backfill page plus the reload's whole-head rebuild: {requests:?}"
);
assert_eq!(
- requests[0]["before"],
- json!(HISTORY_MESSAGES as u64),
+ requests[0]["page"]["before"],
+ json!(entry_id(HISTORY_MESSAGES)),
"the backfill page carries the history cursor: {requests:?}"
);
assert!(
- requests[1].get("before").is_none(),
+ requests[1]["page"].get("before").is_none(),
"the rebuild fetches the whole head without a cursor: {requests:?}"
);
for (index, frame) in frames.iter().enumerate() {
@@ -677,48 +654,6 @@ fn a_reload_rebuild_during_an_in_flight_backfill_keeps_rows_unique_and_ordered()
);
}
-#[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(
@@ -743,9 +678,12 @@ fn a_failed_rebuild_reports_cancelled_incomplete_history() {
2,
"held prefix and failed whole-history rebuild only"
);
- assert_eq!(requests[0]["before"], json!(HISTORY_MESSAGES as u64));
+ assert_eq!(
+ requests[0]["page"]["before"],
+ json!(entry_id(HISTORY_MESSAGES))
+ );
assert!(
- requests[1].get("before").is_none(),
+ requests[1]["page"].get("before").is_none(),
"the cancelled positional cursor is never rearmed"
);
assert!(
diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs
index 627bd7314e..3a464a7088 100644
--- a/crates/pa-types/src/daemon/command.rs
+++ b/crates/pa-types/src/daemon/command.rs
@@ -8,6 +8,36 @@ use super::{
DaemonResumeCursor, Deserialize, JsonMap, Serialize, Value,
};
+/// One page of the display transcript (the branch in order, each compaction as its
+/// summary row), bounded by entry-id cursors.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "from", rename_all = "camelCase")]
+pub enum TranscriptPage {
+ /// The newest `limit` rows before the `before` row; the tail without it.
+ End {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ before: Option<String>,
+ limit: usize,
+ },
+ /// The oldest `limit` rows after the `after` row (the head without it),
+ /// stopping before the `until` row.
+ Start {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ after: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ until: Option<String>,
+ limit: usize,
+ },
+}
+
+impl TranscriptPage {
+ /// Whether the page can reach rows older than a windowed store's loaded suffix.
+ #[must_use]
+ pub fn reads_history(&self) -> bool {
+ !matches!(self, Self::End { before: None, .. })
+ }
+}
+
/// `type: "command"` envelope wrapping a [`DaemonCommand`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -606,7 +636,7 @@ pub enum DaemonCommand {
id: Option<String>,
active_session_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
- before: Option<u64>,
+ page: Option<TranscriptPage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
capabilities: Option<Vec<DaemonClientCapability>>,
#[serde(flatten)]
diff --git a/crates/pa-types/src/daemon/mod.rs b/crates/pa-types/src/daemon/mod.rs
index 9349ee7b09..117c23f920 100644
--- a/crates/pa-types/src/daemon/mod.rs
+++ b/crates/pa-types/src/daemon/mod.rs
@@ -106,6 +106,7 @@ mod worker;
pub use command::{
CycleDirection, DaemonCommand, DaemonCommandEnvelope, DaemonCommandFrameType,
DaemonCommandWire, DaemonSessionLifecycle, ForkPosition, PromptInput, StreamingBehavior,
+ TranscriptPage,
};
pub use outbound::{
DaemonClosingReason, DaemonErrorInfo, DaemonEventEnvelope, DaemonOutbound,