A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
TUI: never paint escape sequences from content; keep the reader's place across transcript replaces (#3698)
Sebastian Müller824da28927b5
diff --git a/Cargo.lock b/Cargo.lockindex 753c2573e9..4c0645974a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1658,6 +1658,7 @@ dependencies = ["unicode-width 0.2.0","url","uuid",+ "vt100",][[package]]diff --git a/crates/pa-cli/tests/exit_backfill_pty_e2e.rs b/crates/pa-cli/tests/exit_backfill_pty_e2e.rsindex 922c869666..0ba8ee336f 100644--- a/crates/pa-cli/tests/exit_backfill_pty_e2e.rs+++ b/crates/pa-cli/tests/exit_backfill_pty_e2e.rs@@ -46,7 +46,7 @@ const CHILD_SOCKET_ENV: &str = "PA_EXIT_BACKFILL_CHILD_SOCKET";/// above a clean detach-and-flush exit.const EXIT_BOUND: Duration = Duration::from_secs(5);/// The windowed attach's cursor sits this many messages into the history.-const HISTORY_BEFORE: usize = 2_000;+const HISTORY_BEFORE: usize = 3_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;@@ -124,7 +124,7 @@ fn the_top_key_loads_the_session_start_as_the_last_input() {/// Older pages the window keeps resident above the tail; one more evicts the/// chunk next to the tail.-const RESIDENT_CHUNKS: usize = 3;+const RESIDENT_CHUNKS: usize = 8;const PAGE_UP: &[u8] = b"\x1b[5~";/// Scrolled far up, the resident rows are cut off from the tail: the exit flush@@ -142,7 +142,7 @@ fn exit_flushes_the_tail_without_a_disjoint_resident_run() {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 {+ for _ in 0..600 {harness.write(PAGE_UP);harness.master.drain_until_quiet(1);if served.load(Ordering::SeqCst) > RESIDENT_CHUNKS {diff --git a/crates/pa-cli/tests/transcript_window_e2e.rs b/crates/pa-cli/tests/transcript_window_e2e.rsindex 817659542c..f444738b83 100644--- a/crates/pa-cli/tests/transcript_window_e2e.rs+++ b/crates/pa-cli/tests/transcript_window_e2e.rs@@ -28,6 +28,9 @@ const TURNS: usize = 900;const COMPACTED_AFTER_TURN: usize = 600;const FIRST_KEPT_TURN: usize = 590;const SUMMARY_TEXT: &str = "fixture compaction summary";+/// Turns the window keeps resident above the tail (eight 256-message chunks of+/// four-message turns), with slack.+const RESIDENT_TURNS: usize = 520;struct Supervisor {child: Child,@@ -379,8 +382,8 @@ async fn the_compaction_summary_renders_once_across_eviction_and_refetch() {// 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));+ steps.extend(paced_keys(crossterm::event::KeyCode::PageUp, 140));+ steps.extend(paced_keys(crossterm::event::KeyCode::PageDown, 110));let frames = run_plan(&session, steps, 40).await;let highest = frames.iter()@@ -390,7 +393,7 @@ async fn the_compaction_summary_renders_once_across_eviction_and_refetch() {.expect("frames rendered");let highest_turn = turn_markers(&frames[highest])[0];assert!(- highest_turn + 300 < COMPACTED_AFTER_TURN,+ highest_turn + RESIDENT_TURNS < COMPACTED_AFTER_TURN,"the climb must pass the compaction by more than the resident window, \reached turn {highest_turn}:\n{}",frames[highest]diff --git a/crates/pa-tui/Cargo.toml b/crates/pa-tui/Cargo.tomlindex 553dd706ec..86b84ec82f 100644--- a/crates/pa-tui/Cargo.toml+++ b/crates/pa-tui/Cargo.toml@@ -33,6 +33,7 @@ path = "src/bin/pa-tui-replay.rs"[dev-dependencies]tempfile = "3"proptest = { workspace = true }+vt100 = "0.15"[lints]workspace = truediff --git a/crates/pa-tui/src/hyperlinks.rs b/crates/pa-tui/src/hyperlinks.rsindex 1f3604ab62..59aad1ec2f 100644--- a/crates/pa-tui/src/hyperlinks.rs+++ b/crates/pa-tui/src/hyperlinks.rs@@ -376,14 +376,28 @@ impl<W: Write> HyperlinkWriter<W> {/// Emit the buffered printable run and advance the tracked column.fn flush_text(&mut self) -> io::Result<()> {+ use unicode_segmentation::UnicodeSegmentation;if self.text.is_empty() {return Ok(());}let chunk = std::mem::take(&mut self.text);- self.inner.write_all(&chunk)?;- if let Ok(text) = std::str::from_utf8(&chunk) {+ let Ok(text) = std::str::from_utf8(&chunk) else {+ return self.inner.write_all(&chunk);+ };+ for grapheme in text.graphemes(true) {+ let width = crate::width::str_width(grapheme) as u16;+ // Terminals disagree on the width of a multi-codepoint two-column cluster (a VS16+ // emoji, a ZWJ sequence, a flag): blank both of its cells first, so a terminal that+ // advances one column keeps no stale cell beside the glyph.+ if let Some((row, col)) = self+ .pos+ .filter(|_| width == 2 && grapheme.chars().nth(1).is_some())+ {+ write!(self.inner, " \x1b[{};{}H", row + 1, col + 1)?;+ }+ self.inner.write_all(grapheme.as_bytes())?;if let Some((_, col)) = self.pos.as_mut() {- *col = col.saturating_add(crate::width::str_width(text) as u16);+ *col = col.saturating_add(width);}}Ok(())@@ -656,6 +670,110 @@ mod tests {String::from_utf8(writer.into_inner()).expect("utf-8")}+ /// The bytes the chat paint writes for consecutive frames of one row each: every frame+ /// passes `to_ratatui_line` and the [`HyperlinkWriter`], as `app::draw` does.+ fn paint_frames(frames: &[&str], width: u16) -> Vec<u8> {+ #[derive(Clone, Default)]+ struct Sink(std::rc::Rc<RefCell<Vec<u8>>>);+ impl Write for Sink {+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {+ self.0.borrow_mut().extend_from_slice(buf);+ Ok(buf.len())+ }+ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+ }+ let sink = Sink::default();+ let area = ratatui::layout::Rect::new(0, 0, width, 1);+ let mut terminal = ratatui::Terminal::with_options(+ ratatui::backend::CrosstermBackend::new(HyperlinkWriter::new(sink.clone())),+ ratatui::TerminalOptions {+ viewport: ratatui::Viewport::Fixed(area),+ },+ )+ .unwrap();+ for text in frames {+ let line = crate::markdown::to_ratatui_line(&vec![crate::Span::raw(*text)]);+ terminal+ .draw(|frame| frame.render_widget(line, area))+ .unwrap();+ }+ let bytes = sink.0.borrow().clone();+ bytes+ }++ /// A minimal terminal that measures graphemes with `columns` (the width choice vt100 cannot+ /// model): it follows cursor moves, skips the other escape sequences, and records the first+ /// row's cells.+ fn screen_row(bytes: &[u8], width: usize, columns: impl Fn(&str) -> usize) -> Vec<String> {+ use unicode_segmentation::UnicodeSegmentation;+ let text = std::str::from_utf8(bytes).unwrap();+ let mut row = vec![" ".to_string(); width];+ let mut col = 0;+ let mut rest = text;+ while !rest.is_empty() {+ if let Some(len) = crate::width::escape_len(rest) {+ let sequence = &rest[..len];+ if let Some(position) = sequence+ .strip_prefix("\x1b[")+ .and_then(|s| s.strip_suffix('H'))+ {+ col = position+ .split(';')+ .nth(1)+ .and_then(|c| c.parse::<usize>().ok())+ .unwrap_or(1)+ - 1;+ }+ rest = &rest[len..];+ continue;+ }+ let grapheme = rest.graphemes(true).next().unwrap();+ let advance = columns(grapheme);+ if advance > 0 && col < width {+ row[col] = grapheme.to_string();+ for cell in row.iter_mut().skip(col + 1).take(advance - 1) {+ cell.clear();+ }+ }+ col += advance;+ rest = &rest[grapheme.len()..];+ }+ row+ }++ /// A terminal that gives the soft hyphen a column (glibc `wcwidth`, pyte) and one that gives+ /// it none (iTerm2) paint the same row: the hyphen never reaches the terminal.+ #[test]+ fn a_soft_hyphen_never_shifts_the_cells_after_it() {+ let bytes = paint_frames(&["a\u{ad}b"], 4);+ let row = screen_row(&bytes, 4, |grapheme| {+ usize::from(grapheme == "\u{ad}") + crate::width::str_width(grapheme)+ });+ assert_eq!(+ row[..2],+ ["a", "b"],+ "the row a one-column soft hyphen terminal paints"+ );+ }++ /// A terminal that measures a VS16 emoji one column wide (vt100, like iTerm2) keeps no stale+ /// character in the second cell the paint assigns it.+ #[test]+ fn a_two_column_cluster_leaves_no_stale_cell_on_a_narrow_measuring_terminal() {+ let bytes = paint_frames(&["abcd", "\u{26a0}\u{fe0f}cd"], 4);+ let mut parser = vt100::Parser::new(1, 4, 0);+ parser.process(&bytes);+ let screen = parser.screen();+ assert_eq!(screen.cell(0, 0).unwrap().contents(), "\u{26a0}\u{fe0f}");+ let second = screen.cell(0, 1).unwrap().contents();+ assert!(+ second.trim().is_empty(),+ "the second cell still shows the previous frame's {second:?}"+ );+ }+#[test]fn writer_injects_open_close_around_link_cells() {// Link covers the `cd` label at columns 4..6 of row 0.diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rsindex 7ac9e1d0ac..2a80daa300 100644--- a/crates/pa-tui/src/interactive/run.rs+++ b/crates/pa-tui/src/interactive/run.rs@@ -833,7 +833,7 @@ async fn run_interactive_surface('run: while running {if !session.dirty {- session.spawn_transcript_page(&view);+ session.spawn_transcript_page(&mut view);}if enhanced_keys_pending {if let Some((kitty, modify_other_keys)) = crate::enhanced_keys::settle_state() {@@ -1808,6 +1808,7 @@ async fn run_interactive_surface(// The reconnect attempt's budget covers the attach alone: the surface is already// up and its dock holds, so the first-frame fold's bounded fetches cannot eat the// 10s attempt budget on a slow daemon.+ let anchor = session.reader_anchor(&view);let attempt = tokio::time::timeout(Duration::from_secs(SESSION_RECONNECT_ATTEMPT_TIMEOUT_S),session.attach_session(@@ -1820,10 +1821,7 @@ async fn run_interactive_surface(Ok(Ok(())) => {// The resynced transcript replaces the chat, then the reconnected status// lands on the rebuilt chat.- session.rebuild_view(- &mut view,- &crate::session_ui::RebuildKind::Resync,- );+ session.resync_view(anchor, &mut view).await;session.note_as("Daemon reconnected",crate::chat::StatusKind::Info,diff --git a/crates/pa-tui/src/markdown.rs b/crates/pa-tui/src/markdown.rsindex bd35a05fd7..34c89fa7bb 100644--- a/crates/pa-tui/src/markdown.rs+++ b/crates/pa-tui/src/markdown.rs@@ -1121,17 +1121,14 @@ fn wrap_quote(spans: &[Span], width: usize, style: &MarkdownStyle, out: &mut Vec}}-/// Convert our Line type to ratatui text for rendering. OSC zone markers and OSC 8-/// hyperlink sequences are stripped: ratatui has no escape-sequence support and would count-/// their bytes as visible cells (the paint path re-emits them).+/// Convert our Line type to ratatui text for rendering. Every painted line passes here, so+/// no escape sequence or control character reaches a cell: ratatui counts their bytes as+/// visible cells while the terminal executes them (OSC 8 links are re-emitted by the paint+/// backend from the frame's link ranges).#[must_use]pub fn to_ratatui_line(line: &Line) -> rt::Line<'static> {- let mut stripped = line.clone();- crate::osc133::strip(&mut stripped);- crate::hyperlinks::strip_osc8(&mut stripped);- // TS `applyLineResets` normalizes every painted line right before the differential- // paint (Thai/Lao AM decomposition, tabs to three spaces).- let spans: Vec<rt::Span<'static>> = stripped+ // TS `applyLineResets` normalizes every painted line right before the differential paint.+ let spans: Vec<rt::Span<'static>> = line.iter().map(|s| rt::Span::styled(crate::width::normalize_terminal_output(&s.content), s.style)).collect();diff --git a/crates/pa-tui/src/markdown/tests.rs b/crates/pa-tui/src/markdown/tests.rsindex 7a9887161b..99992a8ac4 100644--- a/crates/pa-tui/src/markdown/tests.rs+++ b/crates/pa-tui/src/markdown/tests.rs@@ -1892,3 +1892,71 @@ fn an_escaped_bang_before_a_link_is_not_an_image() {let joined: String = spans.iter().map(|s| s.content.as_str()).collect();assert_eq!(joined, "\\alt");}++/// Text carrying escape sequences and control characters (a model or a tool can emit any of+/// them) paints only its visible characters, in exactly as many cells as `str_width` measures.+#[test]+fn painted_cells_hold_no_control_characters_and_match_the_measured_width() {+ let text = "a\x07b\x08c\x1b[31md\x0be\u{9b}f\x1b[2Jg\x1bch\x1b[?1049li\x1b]0;title\x07j\x1bPq\x1b\\k\x7fl\u{85}m\tn";+ let line: Line = vec![Span::raw(text)];+ let area = ratatui::layout::Rect::new(0, 0, 30, 1);+ let mut buffer = ratatui::buffer::Buffer::empty(area);+ ratatui::widgets::Widget::render(to_ratatui_line(&line), area, &mut buffer);+ let cells: Vec<&str> = (0..area.width).map(|x| buffer[(x, 0)].symbol()).collect();+ assert!(+ cells.iter().all(|cell| !cell.chars().any(char::is_control)),+ "{cells:?}"+ );+ assert_eq!(cells.concat().trim_end(), "abcdefgchijklm n");+ assert_eq!(str_width(text), "abcdefgchijklm n".len());+}++/// Screen-clearing and screen-switching sequences inside message text never reach the terminal:+/// the painted bytes hold only the paint's own cursor moves, colors and cursor visibility.+#[test]+fn screen_clearing_sequences_in_message_text_never_reach_the_terminal() {+ #[derive(Clone, Default)]+ struct Sink(std::rc::Rc<std::cell::RefCell<Vec<u8>>>);+ impl std::io::Write for Sink {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0.borrow_mut().extend_from_slice(buf);+ Ok(buf.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }+ let text = "keep\x1b[2Jone\x1b[3Jtwo\x1bcthree\x1b[?1049lfour";+ let sink = Sink::default();+ let area = ratatui::layout::Rect::new(0, 0, 40, 1);+ let mut terminal = ratatui::Terminal::with_options(+ ratatui::backend::CrosstermBackend::new(sink.clone()),+ ratatui::TerminalOptions {+ viewport: ratatui::Viewport::Fixed(area),+ },+ )+ .unwrap();+ terminal+ .draw(|frame| frame.render_widget(to_ratatui_line(&vec![Span::raw(text)]), area))+ .unwrap();+ let bytes = String::from_utf8(sink.0.borrow().clone()).unwrap();+ let mut visible = String::new();+ let mut rest = bytes.as_str();+ while let Some(c) = rest.chars().next() {+ if let Some(len) = crate::width::escape_len(rest) {+ let sequence = &rest[..len];+ assert!(+ sequence.ends_with('H')+ || sequence.ends_with('m')+ || matches!(sequence, "\x1b[?25l" | "\x1b[?25h"),+ "{sequence:?} reached the terminal"+ );+ rest = &rest[len..];+ continue;+ }+ assert!(!c.is_control(), "{c:?} reached the terminal");+ visible.push(c);+ rest = &rest[c.len_utf8()..];+ }+ assert_eq!(visible.trim_end(), "keeponetwocthreefour");+}diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rsindex 589c4dd54e..d285d20558 100644--- a/crates/pa-tui/src/session_ui/lifecycle.rs+++ b/crates/pa-tui/src/session_ui/lifecycle.rs@@ -250,6 +250,7 @@ impl SessionUi {self.client.hard_close();anyhow::bail!("the session's durable id is unknown; cannot reattach");}+ let anchor = self.reader_anchor(view);let attach = tokio::time::timeout(REATTACH_BUDGET,self.attach_session(&durable, DockFold::Held),@@ -273,9 +274,9 @@ impl SessionUi {return Ok(ReattachOutcome::AttachBudgetExceeded);}}- // Flush the attach snapshot BEFORE the banner lands: `rebuild_view` replaces the transcript+ // Flush the attach snapshot BEFORE the banner lands: the rebuild replaces the transcript// from the snapshot, so the banner must come after it to survive the rebuild.- self.rebuild_view(view, &RebuildKind::Resync);+ self.resync_view(anchor, view).await;match kind {RecoveryKind::Update => match complete {Some(false) => view.push_entry(crate::chat::ChatEntry::Status {diff --git a/crates/pa-tui/src/session_ui/window.rs b/crates/pa-tui/src/session_ui/window.rsindex f33fb60f3f..e37d754f6b 100644--- a/crates/pa-tui/src/session_ui/window.rs+++ b/crates/pa-tui/src/session_ui/window.rs@@ -18,9 +18,9 @@ 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;+const RESIDENT_CHUNKS: usize = 8;/// A page loads once the viewport is this many entries from the resident edge.-const PREFETCH_ENTRIES: usize = 128;+const PREFETCH_ENTRIES: usize = 256;#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum PageKind {@@ -35,6 +35,7 @@ pub(crate) enum PageKind {pub(crate) struct TranscriptPageNote {pub epoch: u64,pub kind: PageKind,+ pub request: TranscriptPage,pub page: std::result::Result<LoadedPage, String>,}@@ -51,6 +52,29 @@ struct Chunk {last_id: String,entries: usize,seam: BackfillSeam,+ /// The request that loaded the chunk: replaying it on the same branch reloads the same rows.+ page: TranscriptPage,+}++/// Where a paused reader sits, captured before the transcript is replaced so the rebuilt view+/// can put them back.+pub(crate) enum ReaderAnchor {+ /// Inside the tail: restorable while the rebuilt tail starts at the same row.+ Tail {+ tail_first_id: String,+ entry: usize,+ row: usize,+ },+ /// Inside a resident chunk: its page is reloaded, validated against the old branch.+ Chunk {+ leaf_id: String,+ page: TranscriptPage,+ /// The tail's first row when the chunk joined the tail directly.+ joins_tail: Option<String>,+ start_resident: bool,+ entry: usize,+ row: usize,+ },}#[derive(Default)]@@ -163,7 +187,13 @@ impl TranscriptWindow {/// 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 {+ fn apply(+ &mut self,+ kind: PageKind,+ request: TranscriptPage,+ 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,@@ -182,6 +212,7 @@ impl TranscriptWindow {last_id,entries,seam: page.seam,+ page: request,};match kind {PageKind::Older => {@@ -199,14 +230,22 @@ impl TranscriptWindow {}PageKind::Newer => {let at = self.resident_entries();+ // The page joins the chunk it continues: a restored or head chunk never met+ // the rows after it.+ let superseded = self.chunks.back_mut().map_or(0, |back| {+ let rows = &view.chat[at - back.entries..at];+ let superseded = crate::snapshot::superseded_by_seam(rows, page.seam);+ back.entries -= superseded;+ superseded+ });let count = entries.len();if page.more {entries.push(gap_row());}- view.replace_entries(at..at + 1, entries);+ view.replace_entries(at - superseded..at + 1, entries);self.chunks.push_back(chunk(count));self.gap = page.more;- let mut grown = count as isize - isize::from(!page.more);+ let mut grown = count as isize - isize::from(!page.more) - superseded as isize;if self.chunks.len() > RESIDENT_CHUNKS {let oldest = self.chunks.pop_front().map_or(0, |chunk| chunk.entries);view.drop_leading_entries(oldest);@@ -250,6 +289,73 @@ impl TranscriptWindow {}}+ /// The anchor of a reader paused with row `row` of `entry` at the viewport top.+ fn reader_anchor(&self, entry: usize, row: usize) -> Option<ReaderAnchor> {+ let tail_start = self.tail_start();+ if entry >= tail_start {+ // Without an older-history anchor nothing ties the tail to its rebuilt successor.+ return Some(ReaderAnchor::Tail {+ tail_first_id: self.tail_first_id.clone()?,+ entry: entry - tail_start,+ row,+ });+ }+ let mut start = 0;+ for (index, chunk) in self.chunks.iter().enumerate() {+ if entry < start + chunk.entries {+ let last = index + 1 == self.chunks.len();+ return Some(ReaderAnchor::Chunk {+ leaf_id: self.leaf_id.clone()?,+ page: chunk.page.clone(),+ joins_tail: (last && !self.gap)+ .then(|| self.tail_first_id.clone())+ .flatten(),+ start_resident: index == 0 && self.start_resident,+ entry: entry - start,+ row,+ });+ }+ start += chunk.entries;+ }+ None+ }++ /// Put a reloaded anchor chunk above the freshly reset tail. Returns how many entries+ /// the rows above the tail grew by; `None` when the page came back empty.+ fn restore_chunk(+ &mut self,+ page: TranscriptPage,+ loaded: LoadedPage,+ joins_tail: Option<&str>,+ start_resident: bool,+ view: &mut AgentView,+ ) -> Option<isize> {+ let (Some(first_id), Some(last_id)) = (loaded.first_id, loaded.last_id) else {+ return None;+ };+ let joins = joins_tail.is_some() && joins_tail == self.tail_first_id.as_deref();+ let mut entries = loaded.entries;+ if joins {+ crate::snapshot::join_backfilled_entries(&mut entries, self.tail_seam);+ }+ let count = entries.len();+ if !joins {+ entries.push(gap_row());+ }+ let inserted = entries.len();+ view.prepend_entries(entries);+ self.chunks = VecDeque::from([Chunk {+ first_id,+ last_id,+ entries: count,+ seam: loaded.seam,+ page,+ }]);+ self.gap = !joins;+ self.start_resident = start_resident;+ Some(inserted 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 {@@ -281,47 +387,33 @@ impl SessionUi {/// 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) {+ pub(crate) fn spawn_transcript_page(&mut self, view: &mut AgentView) {let Some((kind, page)) = self.window.next_page(view) else {return;};+ if kind != PageKind::Newer {+ view.older_history_loading = true;+ self.dirty = true;+ }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 loaded = 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+ fetch_page(&client, active_session_id, leaf_id, page.clone()).await}- .await;- let page = page.map_err(|error| error.to_string());- let _ = notes.send(TranscriptPageNote { epoch, kind, page });+ .await+ .map_err(|error| error.to_string());+ let _ = notes.send(TranscriptPageNote {+ epoch,+ kind,+ request: page,+ page: loaded,+ });}));self.window.fetch = Some(task);}@@ -331,6 +423,7 @@ impl SessionUi {return;}self.window.fetch = None;+ view.older_history_loading = false;let page = match note.page {Ok(page) => page,Err(error) => {@@ -348,7 +441,7 @@ impl SessionUi {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);+ let grown = self.window.apply(note.kind, note.request, page, view);self.shift_tail_indices(grown);self.pressed_click = None;self.trim_after_frame = true;@@ -359,6 +452,7 @@ impl SessionUi {pub(crate) fn collapse_transcript_window(&mut self, view: &mut AgentView) {let dropped = self.window.collapse_to_tail(view);if dropped > 0 {+ view.older_history_loading = false;self.shift_tail_indices(-(dropped as isize));self.dirty = true;}@@ -379,15 +473,105 @@ impl SessionUi {}}+ /// Where the paused reader sits, captured before a transcript replace.+ pub(crate) fn reader_anchor(&self, view: &AgentView) -> Option<ReaderAnchor> {+ let (entry, row) = view.reader_position()?;+ self.window.reader_anchor(entry, row)+ }++ /// Reload the anchor's chunk on the (re)attached session while the old rows are still on+ /// screen. `None` when the anchor needs no page or the old branch no longer holds it.+ pub(crate) async fn load_reader_anchor(+ &self,+ anchor: Option<&ReaderAnchor>,+ ) -> Option<LoadedPage> {+ let Some(ReaderAnchor::Chunk { leaf_id, page, .. }) = anchor else {+ return None;+ };+ let fetch = fetch_page(+ &self.client,+ self.active_session_id.clone(),+ leaf_id.clone(),+ page.clone(),+ );+ // Awaited on the interactive loop: the UI request budget bounds it, and a late page+ // follows the tail instead.+ tokio::time::timeout(+ std::time::Duration::from_millis(super::UI_REQUEST_TIMEOUT_MS),+ fetch,+ )+ .await+ .ok()?+ .ok()+ }++ /// Put the reader back on their entry in the rebuilt view; follow the tail when their place+ /// is gone (another branch, a tail that moved past it).+ pub(crate) fn restore_reader(+ &mut self,+ anchor: Option<ReaderAnchor>,+ loaded: Option<LoadedPage>,+ view: &mut AgentView,+ ) {+ match (anchor, loaded) {+ (+ Some(ReaderAnchor::Tail {+ tail_first_id,+ entry,+ row,+ }),+ _,+ ) if self.window.tail_first_id.as_ref() == Some(&tail_first_id) => {+ view.scroll_to_entry(entry, row);+ }+ (+ Some(ReaderAnchor::Chunk {+ page,+ joins_tail,+ start_resident,+ entry,+ row,+ ..+ }),+ Some(loaded),+ ) => match self.window.restore_chunk(+ page,+ loaded,+ joins_tail.as_deref(),+ start_resident,+ view,+ ) {+ Some(grown) => {+ self.shift_tail_indices(grown);+ view.scroll_to_entry(entry, row);+ }+ None => view.follow(),+ },+ _ => view.follow(),+ }+ self.dirty = true;+ }++ /// Rebuild the view from a re-attach snapshot, keeping a paused reader on their entry.+ pub(crate) async fn resync_view(&mut self, anchor: Option<ReaderAnchor>, view: &mut AgentView) {+ let loaded = self.load_reader_anchor(anchor.as_ref()).await;+ self.rebuild_view(view, &super::RebuildKind::Resync);+ self.restore_reader(anchor, loaded, view);+ }+/// 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.+ /// fork, import, and reload rebuilds), keeping a paused reader on their entry while+ /// the branch still holds it. Best effort: a failed fetch keeps the view.pub(crate) async fn rebuild_transcript(&mut self, view: &mut AgentView) {+ let anchor = self.reader_anchor(view);let incomplete_history = self.window.incomplete();self.window.retire();+ view.older_history_loading = false;self.last_status_index = None;self.pressed_click = None;- let data = self- .bounded_request(+ // The anchor page is validated against the old branch, independent of the tail.+ let (data, anchor_page) = tokio::join!(+ self.bounded_request(std::time::Duration::from_millis(super::UI_REQUEST_TIMEOUT_MS),DaemonCommand::GetMessages {id: None,@@ -399,8 +583,9 @@ impl SessionUi {capabilities: Some(crate::session_ui::attach_capabilities()),rest: Map::default(),},- )- .await;+ ),+ self.load_reader_anchor(anchor.as_ref()),+ );let leaf_id = data.as_ref().ok()@@ -429,9 +614,36 @@ impl SessionUi {for entry in page.entries {view.push_entry(entry);}- view.follow();- self.dirty = true;+ self.restore_reader(anchor, anchor_page, view);+ }+}++/// One display-transcript page validated against the attached branch `leaf_id`.+async fn fetch_page(+ client: &crate::daemon_client::DaemonClient,+ active_session_id: String,+ leaf_id: String,+ page: TranscriptPage,+) -> Result<LoadedPage> {+ 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}/// Decode a page response off the UI thread.@@ -540,6 +752,10 @@ mod tests {.send(TranscriptPageNote {epoch: old_epoch,kind: PageKind::Older,+ request: TranscriptPage::End {+ before: Some("e1".to_string()),+ limit: CHUNK_MESSAGES,+ },page: Ok(LoadedPage {entries: crate::snapshot::transcript_to_entries(&[json!({"role": "user", "content": "stale history", "timestamp": 0}),@@ -570,6 +786,57 @@ mod tests {}).await.expect("mock session open, rebuild and stale-note delivery complete within ten seconds");}+ #[test]+ fn an_empty_anchor_page_restores_nothing() {+ let mut window = TranscriptWindow::default();+ window.reset(+ Some("leaf".to_string()),+ Some("tail".to_string()),+ BackfillSeam::Preserve,+ );+ let mut view = AgentView::new(crate::theme::Theme::builtin(+ "prime",+ crate::theme::ColorMode::TrueColor,+ ));+ let empty = LoadedPage {+ entries: Vec::new(),+ seam: BackfillSeam::Preserve,+ first_id: None,+ last_id: None,+ more: false,+ };+ let page = TranscriptPage::End {+ before: Some("tail".to_string()),+ limit: CHUNK_MESSAGES,+ };+ assert!(+ window+ .restore_chunk(page, empty, Some("tail"), false, &mut view)+ .is_none(),+ "the reader follows the tail instead of scrolling to a chunk that never came back"+ );+ assert!(view.chat.is_empty() && window.chunks.is_empty());+ }++ #[test]+ fn only_a_tail_with_an_older_history_anchor_restores_a_reader() {+ let mut window = TranscriptWindow::default();+ window.reset(Some("leaf".to_string()), None, BackfillSeam::Preserve);+ assert!(+ window.reader_anchor(3, 0).is_none(),+ "a whole-session tail cannot tell its rebuilt successor from another branch"+ );+ window.reset(+ Some("leaf".to_string()),+ Some("tail".to_string()),+ BackfillSeam::Preserve,+ );+ assert!(matches!(+ window.reader_anchor(3, 0),+ Some(ReaderAnchor::Tail { entry: 3, .. })+ ));+ }+#[test]fn a_page_reaching_the_tail_joins_its_retry_seam() {let attempt = json!({@@ -597,7 +864,12 @@ mod tests {last_id: Some("e1".to_string()),more: false,};- window.apply(PageKind::Head, page, &mut view);+ let request = TranscriptPage::Start {+ after: None,+ until: Some("tail".to_string()),+ limit: CHUNK_MESSAGES,+ };+ window.apply(PageKind::Head, request, page, &mut view);assert_eq!(view.chat,vec![ChatEntry::User {@@ -606,4 +878,70 @@ mod tests {"the tail's retry outcome supersedes the attempt the head page ends with");}++ #[test]+ fn a_newer_page_supersedes_the_failed_attempt_a_restored_chunk_ends_with() {+ let user = |text: &str| json!({"role": "user", "content": text, "timestamp": 1});+ let attempt = json!({+ "role": "assistant", "content": [], "stopReason": "error",+ "errorMessage": "attempt failed", "timestamp": 2,+ });+ let outcome = json!({+ "role": "custom", "customType": "provider_retry_outcome",+ "content": "Recovered after retries", "display": true,+ "details": { "success": true }, "timestamp": 3,+ });+ let answer = json!({+ "role": "assistant", "content": [{"type": "text", "text": "done"}], "timestamp": 4,+ });+ let page = |messages: &[Value], first: &str, last: &str| {+ let (entries, seam) = crate::snapshot::transcript_with_backfill_seam(messages);+ LoadedPage {+ entries,+ seam,+ first_id: Some(first.to_string()),+ last_id: Some(last.to_string()),+ more: false,+ }+ };+ let mut window = TranscriptWindow::default();+ window.reset(+ Some("leaf".to_string()),+ Some("tail".to_string()),+ BackfillSeam::Preserve,+ );+ let mut view = AgentView::new(crate::theme::Theme::builtin(+ "prime",+ crate::theme::ColorMode::TrueColor,+ ));+ view.push_entry(crate::snapshot::transcript_to_entries(&[user("later")]).remove(0));+ let anchor_page = TranscriptPage::End {+ before: Some("e2".to_string()),+ limit: CHUNK_MESSAGES,+ };+ let loaded = page(&[user("run"), attempt.clone()], "e0", "e1");+ let mut grown = window+ .restore_chunk(anchor_page, loaded, None, true, &mut view)+ .expect("a non-empty anchor page restores");+ let request = TranscriptPage::Start {+ after: Some("e1".to_string()),+ until: Some("tail".to_string()),+ limit: CHUNK_MESSAGES,+ };+ let newer = page(&[outcome.clone(), answer.clone()], "e2", "e3");+ grown += window.apply(PageKind::Newer, request, newer, &mut view);+ let full = crate::snapshot::transcript_to_entries(&[+ user("run"),+ attempt,+ outcome,+ answer,+ user("later"),+ ]);+ assert_eq!(+ view.chat, full,+ "the newer page's retry outcome supersedes the attempt the restored chunk ends with"+ );+ assert_eq!(grown, full.len() as isize - 1, "the rows above the tail");+ assert_eq!(window.tail_start(), full.len() - 1);+ }}diff --git a/crates/pa-tui/src/snapshot.rs b/crates/pa-tui/src/snapshot.rsindex 9124f2fafb..2d1cf4fda9 100644--- a/crates/pa-tui/src/snapshot.rs+++ b/crates/pa-tui/src/snapshot.rs@@ -305,12 +305,22 @@ fn pop_superseded_attempts(chat: &mut Vec<ChatEntry>) {}}-pub(crate) fn join_backfilled_entries(head: &mut Vec<ChatEntry>, seam: BackfillSeam) {- if matches!(seam, BackfillSeam::RetryOutcome) {- pop_superseded_attempts(head);+/// How many rows at the end of `head` the rows after it supersede.+pub(crate) fn superseded_by_seam(head: &[ChatEntry], seam: BackfillSeam) -> usize {+ match seam {+ BackfillSeam::Preserve => 0,+ BackfillSeam::RetryOutcome => head+ .iter()+ .rev()+ .take_while(|entry| is_superseded_attempt_row(entry))+ .count(),}}+pub(crate) fn join_backfilled_entries(head: &mut Vec<ChatEntry>, seam: BackfillSeam) {+ head.truncate(head.len() - superseded_by_seam(head, seam));+}+pub fn reconstruct(attach: &AttachData) -> Reconstructed {let snapshot = &attach.snapshot;let (messages, backfill_seam) = snapshotdiff --git a/crates/pa-tui/src/view.rs b/crates/pa-tui/src/view.rsindex e78bd11444..9c07cfdc42 100644--- a/crates/pa-tui/src/view.rs+++ b/crates/pa-tui/src/view.rs@@ -116,6 +116,8 @@ pub struct AgentView {/// The brand splash never renders while set (operator ruling 2026-09-26, zero layout/// shift): an opening non-empty transcript suppresses it.pub splash_suppressed: bool,+ /// An older history page is on its way: a marker row stands above the first entry.+ pub(crate) older_history_loading: bool,pub(crate) scroll_top: usize,following: bool,/// The transcript-tail offset of the last composed frame: scroll@@ -314,6 +316,7 @@ impl AgentView {show_images: true,show_hardware_cursor: false,splash_suppressed: false,+ older_history_loading: false,scroll_top: 0,following: true,last_max_scroll: 0,@@ -597,6 +600,7 @@ impl AgentView {self.entry_heights.clear();self.md_caches.borrow_mut().clear();self.pending_bash.clear();+ self.older_history_loading = false;}/// Prepare an in-place mutation of one entry: capture its currentdiff --git a/crates/pa-tui/src/view/layout.rs b/crates/pa-tui/src/view/layout.rsindex b308a3f395..081c07d472 100644--- a/crates/pa-tui/src/view/layout.rs+++ b/crates/pa-tui/src/view/layout.rs@@ -188,6 +188,11 @@ pub(crate) struct TranscriptLayout {}impl TranscriptLayout {+ /// The absolute first row of chat entry `index` (the end sentinel past the last entry).+ pub(super) fn entry_start(&self, index: usize) -> usize {+ self.offsets[index.min(self.offsets.len() - 1)]+ }+pub(super) fn cursor_at(&self, row: usize) -> (usize, usize) {if row < self.splash.len() {return (0, row);@@ -267,6 +272,22 @@ impl AgentView {}}+ /// The rows above the first entry: the splash, or, once a transcript suppressed it, the+ /// marker of an older history page on its way (styled like the gap row's status row).+ pub(super) fn top_section_rows(&self, width: usize) -> Vec<Line> {+ if !self.splash_suppressed {+ return render_splash(&self.chrome, &self.theme, width);+ }+ if self.older_history_loading {+ return crate::chat::render_text_rows(+ "Loading older history\u{2026}",+ self.theme.fg_style(crate::theme::ThemeColor::Dim),+ width,+ );+ }+ Vec::new()+ }+/// Measure entries through shared count-only render geometry.pub(crate) fn layout_pass(&mut self, width: usize) -> TranscriptLayout {self.sparse_enabled = false;@@ -276,13 +297,7 @@ impl AgentView {crate::chat::Detail::Details => 1,crate::chat::Detail::All => 2,};- // A suppressed splash contributes no rows: the offsets start at- // the first entry.- let splash = if self.splash_suppressed {- Vec::new()- } else {- render_splash(&self.chrome, &self.theme, width)- };+ let splash = self.top_section_rows(width);let mut offsets = Vec::with_capacity(self.chat.len() + 1);offsets.push(splash.len());let mut first = true;diff --git a/crates/pa-tui/src/view/lazy.rs b/crates/pa-tui/src/view/lazy.rsindex 58b57139a5..89a5545fb9 100644--- a/crates/pa-tui/src/view/lazy.rs+++ b/crates/pa-tui/src/view/lazy.rs@@ -7,7 +7,6 @@ use crate::chat::Detail;/// immediately; only a resumed session's pad-scale row sets cross this.const HUGE_PACKED_ROWS: usize = 8192;-use crate::chrome::render_splash;use crate::Line;#[cfg(test)]@@ -217,6 +216,31 @@ impl AgentView {self.sparse_window = Some(window);}+ /// The chat entry and its row at the top of a paused viewport; `None` while following or+ /// when the top is the splash or the tail section.+ pub(crate) fn reader_position(&self) -> Option<(usize, usize)> {+ if self.following {+ return None;+ }+ let (section, row) = self.sparse_window?.cursor?;+ (1..=self.chat.len())+ .contains(§ion)+ .then(|| (section - 1, row))+ }++ /// Pause the viewport with row `row` of entry `index` at its top.+ pub(crate) fn scroll_to_entry(&mut self, index: usize, row: usize) {+ if self.layout_width == 0 {+ return;+ }+ let sparse = self.sparse_enabled;+ let offset = self.layout_pass(self.layout_width).entry_start(index) + row;+ self.sparse_enabled = sparse;+ self.sparse_window = None;+ self.scroll_top = offset;+ self.following = false;+ }+/// `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 {@@ -277,13 +301,9 @@ impl AgentView {let splash = splash.get_or_insert_with(|| {#[cfg(test)]SPLASH_RENDERS.with(|count| count.set(count.get() + 1));- // The suppressed splash is an empty section: the sparse walker skips- // zero-row sections like an empty tail.- if view.splash_suppressed {- std::sync::Arc::new(Vec::new())- } else {- std::sync::Arc::new(render_splash(&view.chrome, &view.theme, window.width))- }+ // An empty top section: the sparse walker skips zero-row sections like an+ // empty tail.+ std::sync::Arc::new(view.top_section_rows(window.width))});EntryRows::Fresh(splash.clone())} else if section == last {@@ -461,13 +481,9 @@ impl AgentView {let splash = splash.get_or_insert_with(|| {#[cfg(test)]SPLASH_RENDERS.with(|count| count.set(count.get() + 1));- // The suppressed splash is an empty section: the sparse walker skips- // zero-row sections like an empty tail.- if view.splash_suppressed {- std::sync::Arc::new(Vec::new())- } else {- std::sync::Arc::new(render_splash(&view.chrome, &view.theme, width))- }+ // An empty top section: the sparse walker skips zero-row sections like an+ // empty tail.+ std::sync::Arc::new(view.top_section_rows(width))});return EntryRows::Fresh(splash.clone());}diff --git a/crates/pa-tui/src/width.rs b/crates/pa-tui/src/width.rsindex 3d297f26ba..f78c1bd387 100644--- a/crates/pa-tui/src/width.rs+++ b/crates/pa-tui/src/width.rs@@ -356,20 +356,33 @@ pub fn is_punctuation_char(c: char) -> bool {/// Normalize text for terminal output without changing logical content: Thai/Lao AM vowels/// decompose to compatibility forms (same width, no stale cells); tabs expand to three spaces.+/// Escape sequences and the remaining control characters drop: [`str_width`] measures them as+/// zero columns, and painted raw they would move the cursor or erase cells the differential+/// paint believes are drawn.#[must_use]pub fn normalize_terminal_output(s: &str) -> String {- let has_thai_lao_am = s.contains('\u{0e33}') || s.contains('\u{0eb3}');- if !has_thai_lao_am && !s.contains('\t') {+ if !s+ .chars()+ .any(|c| matches!(c, '\u{0e33}' | '\u{0eb3}' | '\u{ad}') || c.is_control())+ {return s.to_string();}let mut out = String::with_capacity(s.len() + 8);- for c in s.chars() {+ let mut rest = s;+ while let Some(c) = rest.chars().next() {+ if let Some(len) = escape_len(rest) {+ rest = &rest[len..];+ continue;+ }match c {'\u{0e33}' => out.push_str("\u{0e4d}\u{0e32}"),'\u{0eb3}' => out.push_str("\u{0ecd}\u{0eb2}"),'\t' => out.push_str(" "),+ // The soft hyphen measures zero columns, but terminals give it zero or one.+ c if c.is_control() || c == '\u{ad}' => {}c => out.push(c),}+ rest = &rest[c.len_utf8()..];}out}diff --git a/crates/pa-tui/tests/transcript_window_headless.rs b/crates/pa-tui/tests/transcript_window_headless.rsindex c74d1f9fc0..aaf33861c3 100644--- a/crates/pa-tui/tests/transcript_window_headless.rs+++ b/crates/pa-tui/tests/transcript_window_headless.rs@@ -20,11 +20,14 @@ use pa_tui::interactive::{};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 RESIDENT_CHUNKS: usize = 8;+/// Enough history above the tail that a climb to the top evicts resident chunks.+const MESSAGES: usize = TAIL + (RESIDENT_CHUNKS + 3) * CHUNK;+/// Paced batches that cover the whole session (about 13 messages per page at `HEIGHT`).+const CLIMB: usize = MESSAGES / 12;const LEAF: &str = "leaf";const GAP_ROW: &str = "Loading newer history";const WHEEL_UP: &str = "\x1b[<64;10;10M";@@ -47,11 +50,23 @@ fn message(index: usize) -> Value {}}+/// How the mock serves pages.+#[derive(Clone, Copy, Default)]+struct Paging {+ /// Never answer newer pages (`from: start` with an `after` cursor).+ hold_newer: bool,+ /// Never answer older pages (`from: end` with a `before` cursor).+ hold_older: bool,+ /// After a `reload`, every page answers this late.+ slow_after_reload_ms: u64,+ /// After a `reload`, the old branch anchor is gone (a navigation or fork).+ branch_changed_after_reload: bool,+}+/// 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,+ paging: Paging,pages: Arc<Mutex<Vec<Value>>>,}@@ -69,6 +84,7 @@ impl MockSupervisor {}),);let mut line = String::new();+ let mut reloaded = false;loop {line.clear();match reader.read_line(&mut line) {@@ -83,12 +99,34 @@ impl MockSupervisor {let kind = command["type"].as_str().unwrap_or_default().to_string();let data = match kind.as_str() {"attach" => attach_data(),+ "reload" => {+ reloaded = true;+ json!({})+ }"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() {+ let paging = self.paging;+ if paging.hold_newer && page["from"] == "start" && page.get("after").is_some() {continue;}+ if paging.hold_older && page["from"] == "end" && page.get("before").is_some() {+ continue;+ }+ if reloaded {+ std::thread::sleep(std::time::Duration::from_millis(+ paging.slow_after_reload_ms,+ ));+ if paging.branch_changed_after_reload+ && command.get("historyLeafId").is_some()+ {+ write_json(+ &mut writer,+ &json!({ "type": "response", "id": id, "command": kind, "success": false, "error": "History branch changed" }),+ );+ continue;+ }+ }page_data(&page)}"get_session_stats" => json!({@@ -196,14 +234,14 @@ fn options(socket: PathBuf) -> InteractiveOptions {}}-fn run(hold_newer: bool, steps: Vec<HeadlessStep>) -> (Vec<String>, Vec<Value>) {+fn run(paging: Paging, 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,+ paging,pages: Arc::clone(&pages),};let handle = std::thread::spawn(move || supervisor.serve());@@ -299,7 +337,7 @@ fn scrolling_up_through_older_pages_keeps_the_viewport_anchored() {.map(|_| HeadlessStep::Mouse(WHEEL_UP.to_string())).collect();batch.push(key(crossterm::event::KeyCode::PageUp));- let (frames, pages) = run(false, paced(&batch, 220));+ let (frames, pages) = run(Paging::default(), paced(&batch, CLIMB));let reached_top = frames.iter().position(|frame| top_marker(frame) == Some(0))@@ -334,13 +372,19 @@ fn scrolling_up_through_older_pages_keeps_the_viewport_anchored() {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);+ let mut up = paced(&[key(crossterm::event::KeyCode::PageUp)], CLIMB);up.extend(- paced(&[key(crossterm::event::KeyCode::PageDown)], 60)+ paced(&[key(crossterm::event::KeyCode::PageDown)], CLIMB).into_iter().skip(1),);- let (frames, _) = run(true, up);+ let (frames, _) = run(+ Paging {+ hold_newer: true,+ ..Paging::default()+ },+ up,+ );let top = frames.iter().position(|frame| top_marker(frame) == Some(0))@@ -375,14 +419,14 @@ fn the_resident_run_stays_bounded_and_refills_on_return() {// 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);+ let mut steps = paced(&[key(crossterm::event::KeyCode::PageUp)], CLIMB);steps.push(HeadlessStep::ScrollTop);steps.extend(- paced(&[key(crossterm::event::KeyCode::PageDown)], 150)+ paced(&[key(crossterm::event::KeyCode::PageDown)], CLIMB).into_iter().skip(1),);- let (frames, pages) = run(false, steps);+ let (frames, pages) = run(Paging::default(), steps);let top = frames.iter().position(|frame| top_marker(frame) == Some(0))@@ -429,3 +473,81 @@ fn the_resident_run_stays_bounded_and_refills_on_return() {"rows evicted on the way up were refetched on the way down: {pages:?}");}++/// Climb into the older chunks, then `/reload`: the transcript is replaced from the daemon+/// while every page answers slowly.+fn reload_from_mid_history(paging: Paging) -> (usize, Vec<String>) {+ let mut steps = paced(&[key(crossterm::event::KeyCode::PageUp)], 40);+ steps.push(HeadlessStep::WaitMs(300));+ steps.push(HeadlessStep::Type("/reload".to_string()));+ steps.push(key(crossterm::event::KeyCode::Enter));+ steps.push(HeadlessStep::WaitRender {+ needle: "Reloaded".to_string(),+ timeout_ms: 10_000,+ });+ let (frames, _) = run(paging, steps);+ let typed = frames+ .iter()+ .position(|frame| frame.contains("/reload"))+ .expect("the reload command was typed");+ let reader = top_marker(&frames[typed]).expect("the reader's rows before the reload");+ assert!(+ reader < MESSAGES - TAIL,+ "the climb reached the older chunks (msg-{reader:05})"+ );+ for frame in &frames[typed..] {+ assert!(+ !marker_rows(frame).is_empty(),+ "the transcript rows stayed rendered through the replace:\n{frame}"+ );+ }+ (reader, frames[typed..].to_vec())+}++#[test]+fn a_transcript_replace_keeps_a_mid_history_reader_on_their_entry() {+ let (reader, frames) = reload_from_mid_history(Paging {+ slow_after_reload_ms: 600,+ ..Paging::default()+ });+ let last = frames.last().expect("frames rendered");+ assert_eq!(+ top_marker(last),+ Some(reader),+ "the reader stays on msg-{reader:05} after the replace:\n{last}"+ );+}++#[test]+fn a_transcript_replace_onto_another_branch_follows_the_tail() {+ let (_, frames) = reload_from_mid_history(Paging {+ branch_changed_after_reload: true,+ ..Paging::default()+ });+ let last = frames.last().expect("frames rendered");+ assert!(+ last.contains(&format!("msg-{:05}", MESSAGES - 1)),+ "the reader's place left the branch, so the view follows the tail:\n{last}"+ );+}++#[test]+fn an_older_page_in_flight_marks_the_top_of_the_resident_rows() {+ let (frames, _) = run(+ Paging {+ hold_older: true,+ ..Paging::default()+ },+ paced(&[key(crossterm::event::KeyCode::PageUp)], 40),+ );+ let last = frames.last().expect("frames rendered");+ let marker = last+ .lines()+ .position(|line| line.contains("Loading older history"))+ .unwrap_or_else(|| panic!("no loading marker at the top of the rows:\n{last}"));+ assert!(+ marker_rows(last).iter().all(|(row, _)| *row > marker)+ && top_marker(last) == Some(MESSAGES - TAIL),+ "the marker stands above the stale first resident row:\n{last}"+ );+}