Skip to content

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

Rust

catalog: page the saved-session list and backfill info sidecars (#3656)

Sebastian Müllerba119a48187b
diff --git a/.changes/paginated-session-catalog.md b/.changes/paginated-session-catalog.md
new file mode 100644
index 0000000000..5c37e4dc76
--- /dev/null
+++ b/.changes/paginated-session-catalog.md
@@ -0,0 +1 @@
+- Agents view and `/resume`: the newest 200 sessions load first, scrolling loads more, and a search loads the rest. A footer shows how many older sessions are not loaded yet.
diff --git a/crates/pa-daemon/src/session_scan.rs b/crates/pa-daemon/src/session_scan.rs
index 20704299a7..6f43d80435 100644
--- a/crates/pa-daemon/src/session_scan.rs
+++ b/crates/pa-daemon/src/session_scan.rs
@@ -3,13 +3,16 @@
//! file, while an unparseable or blank first line leaves the fold to decide
//! (TS never invalidates on a parse failure).
+use std::cmp::Reverse;
+use std::collections::HashMap;
use std::fs;
-use std::path::Path;
-use std::time::SystemTime;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant, UNIX_EPOCH};
use crate::session_store::{
- parse_session_header_line, read_first_line_bounded_from, read_session_info_from, SessionInfo,
- SESSION_LIST_HEADER_READ_MAX_BYTES,
+ parse_session_header_line, persist_info_sidecar, read_first_line_bounded_from,
+ read_session_info_from, SessionInfo, SESSION_LIST_HEADER_READ_MAX_BYTES,
};
/// The bounded header read's verdict for one roster file.
@@ -54,13 +57,107 @@ fn bounded_header_gate(file: &mut fs::File) -> HeaderGate {
/// One file's roster row: `None` when the file produces none. One open serves
/// the gate and the fold, pinning both to the same inode (a rename racing two
-/// handles could judge one file and fold another).
+/// handles could judge one file and fold another). A fold the sidecar did not
+/// cover backfills it, so the next cold process loads this row cheaply.
fn roster_session_info(path: &Path) -> Option<SessionInfo> {
let mut file = fs::File::open(path).ok()?;
match bounded_header_gate(&mut file) {
HeaderGate::NotAHeader => None,
- HeaderGate::Header | HeaderGate::Unjudged => read_session_info_from(&mut file, path),
+ HeaderGate::Header | HeaderGate::Unjudged => {
+ let (info, sidecar_behind) = read_session_info_from(&mut file, path)?;
+ if sidecar_behind {
+ persist_info_sidecar(path);
+ }
+ Some(info)
+ }
+ }
+}
+
+/// One walk over the store: the folded rows, the files after the walk, and
+/// the cursor that resumes after the last walked file (`None` at the end).
+pub struct SessionPage {
+ pub infos: Vec<SessionInfo>,
+ pub remaining: usize,
+ pub next_cursor: Option<String>,
+}
+
+/// The walk order's key: newest mtime first, the file name breaking ties, so
+/// the initial snapshot order is total.
+type WalkKey = (Reverse<u128>, String);
+
+struct WalkSnapshot {
+ session_dir: PathBuf,
+ files: Arc<Vec<PathBuf>>,
+ last_used: Instant,
+}
+
+fn walk_snapshots() -> &'static Mutex<HashMap<String, WalkSnapshot>> {
+ static SNAPSHOTS: OnceLock<Mutex<HashMap<String, WalkSnapshot>>> = OnceLock::new();
+ SNAPSHOTS.get_or_init(Default::default)
+}
+
+fn snapshot_files(session_dir: &Path, cursor: Option<&str>) -> (String, Arc<Vec<PathBuf>>, usize) {
+ if let Some((id, offset)) = cursor
+ .and_then(|cursor| cursor.strip_prefix("snapshot:"))
+ .and_then(|cursor| cursor.split_once(':'))
+ .and_then(|(id, offset)| offset.parse::<usize>().ok().map(|offset| (id, offset)))
+ {
+ let mut snapshots = walk_snapshots()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ snapshots.retain(|_, snapshot| snapshot.last_used.elapsed() < Duration::from_secs(300));
+ if let Some(snapshot) = snapshots.get_mut(id) {
+ if snapshot.session_dir == session_dir && offset <= snapshot.files.len() {
+ snapshot.last_used = Instant::now();
+ return (id.to_string(), Arc::clone(&snapshot.files), offset);
+ }
+ }
}
+ let mut files: Vec<(WalkKey, PathBuf)> = fs::read_dir(session_dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .map(|entry| entry.path())
+ .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))
+ .filter_map(|path| {
+ let modified = fs::metadata(&path).and_then(|m| m.modified()).ok()?;
+ let modified_ns = modified
+ .duration_since(UNIX_EPOCH)
+ .map_or(0, |since| since.as_nanos());
+ let name = path.file_name()?.to_string_lossy().into_owned();
+ Some(((Reverse(modified_ns), name), path))
+ })
+ .collect();
+ files.sort_unstable();
+ (
+ uuid::Uuid::new_v4().to_string(),
+ Arc::new(files.into_iter().map(|(_, path)| path).collect()),
+ 0,
+ )
+}
+
+fn retain_snapshot(id: String, session_dir: &Path, files: Arc<Vec<PathBuf>>) {
+ let mut snapshots = walk_snapshots()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ snapshots.retain(|_, snapshot| snapshot.last_used.elapsed() < Duration::from_secs(300));
+ if !snapshots.contains_key(&id) && snapshots.len() >= 32 {
+ if let Some(oldest) = snapshots
+ .iter()
+ .min_by_key(|(_, snapshot)| snapshot.last_used)
+ .map(|(id, _)| id.clone())
+ {
+ snapshots.remove(&oldest);
+ }
+ }
+ snapshots.insert(
+ id,
+ WalkSnapshot {
+ session_dir: session_dir.to_path_buf(),
+ files,
+ last_used: Instant::now(),
+ },
+ );
}
/// List every valid session file in a directory, most recently modified first.
@@ -68,43 +165,49 @@ fn roster_session_info(path: &Path) -> Option<SessionInfo> {
/// cross-core cacheline/futex costs on a loaded box (425ms vs 137ms over 1412 files).
#[must_use]
pub fn list_sessions(session_dir: &Path) -> Vec<SessionInfo> {
- list_sessions_with(session_dir, |_, _, _| true)
+ list_sessions_with(session_dir, None, None, |_, _, _| true).infos
}
-/// [`list_sessions`] with the saved-catalog stream's per-file callback:
-/// `on_row` receives rows as each fold completes, so rows reach the client
-/// DURING the scan; the metadata pass runs first, so the first row is the
-/// newest session. `false` stops the scan.
+/// [`list_sessions`] as a page with the saved-catalog stream's per-file
+/// callback. The first request snapshots the names in mtime order; continuations retain that
+/// file order even when sessions change. Expired cursors restart the walk; the TUI deduplicates
+/// repeated paths. At most 32 snapshots are kept, expiring after five idle minutes.
+/// The fold walks only the files after `cursor`, at most `limit` of
+/// them. `on_row` receives rows as each fold completes, so rows reach the
+/// client DURING the scan, newest first. `false` stops the scan.
pub fn list_sessions_with(
session_dir: &Path,
+ cursor: Option<&str>,
+ limit: Option<usize>,
mut on_row: impl FnMut(usize, usize, &SessionInfo) -> bool,
-) -> Vec<SessionInfo> {
- let Ok(read) = fs::read_dir(session_dir) else {
- return Vec::new();
- };
- let mut files: Vec<(std::path::PathBuf, SystemTime)> = read
- .flatten()
- .map(|entry| entry.path())
- .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))
- .filter_map(|path| {
- let modified = fs::metadata(&path).and_then(|m| m.modified()).ok()?;
- Some((path, modified))
- })
- .collect();
- files.sort_by_key(|(_, modified)| std::cmp::Reverse(*modified));
- let total = files.len();
+) -> SessionPage {
+ let (snapshot_id, snapshot, start) = snapshot_files(session_dir, cursor);
+ let files = &snapshot[start..];
+ let walk = limit.map_or(files.len(), |limit| limit.max(1).min(files.len()));
let mut infos = Vec::new();
- for (index, (path, _)) in files.into_iter().enumerate() {
- if let Some(info) = roster_session_info(&path) {
+ let mut walked = 0;
+ for (index, path) in files[..walk].iter().enumerate() {
+ walked = index + 1;
+ if let Some(info) = roster_session_info(path) {
// `false` stops the scan: the consumer is gone, so the remaining
// folds serve nobody — the scan returns the rows it has.
- if !on_row(index, total, &info) {
+ if !on_row(index, walk, &info) {
break;
}
infos.push(info);
}
}
- infos
+ let remaining = files.len() - walked;
+ let next_cursor = (remaining > 0).then(|| {
+ let cursor = format!("snapshot:{snapshot_id}:{}", start + walked);
+ retain_snapshot(snapshot_id, session_dir, Arc::clone(&snapshot));
+ cursor
+ });
+ SessionPage {
+ infos,
+ remaining,
+ next_cursor,
+ }
}
#[cfg(test)]
@@ -112,7 +215,7 @@ mod tests {
use super::*;
use crate::session_store::{read_session_info, session_file_name, SessionFile};
use serde_json::json;
- use std::path::PathBuf;
+ use std::time::SystemTime;
fn temp_dir() -> PathBuf {
let dir = std::env::temp_dir().join(format!("pa-daemon-scan-{}", uuid::Uuid::new_v4()));
@@ -284,10 +387,11 @@ mod tests {
.unwrap();
}
let mut seen: Vec<(usize, usize, Option<String>)> = Vec::new();
- let rows = list_sessions_with(&dir, |index, total, info| {
+ let rows = list_sessions_with(&dir, None, None, |index, total, info| {
seen.push((index, total, info.name.clone()));
true
- });
+ })
+ .infos;
assert_eq!(rows.len(), 3);
assert_eq!(seen.len(), 3, "every row emitted as its fold completes");
assert_eq!(
@@ -320,11 +424,84 @@ mod tests {
write_session(&dir, "/repo/b", Some("second"), 1);
write_session(&dir, "/repo/c", Some("third"), 1);
let mut emitted = 0usize;
- let rows = list_sessions_with(&dir, |_, _, _| {
+ let rows = list_sessions_with(&dir, None, None, |_, _, _| {
emitted += 1;
emitted < 2
- });
+ })
+ .infos;
assert_eq!(emitted, 2, "the scan stops at the consumer's false");
assert_eq!(rows.len(), 1, "only the emitted row returns: {rows:?}");
}
+
+ #[test]
+ fn a_page_cursor_resumes_after_its_file_even_once_that_file_is_deleted() {
+ let dir = temp_dir();
+ let base = SystemTime::now() - std::time::Duration::from_hours(1);
+ let paths: Vec<PathBuf> = (0..5)
+ .map(|index| {
+ let path = write_session(&dir, "/repo/x", Some(&format!("row {index}")), 1);
+ let file = fs::File::options().write(true).open(&path).unwrap();
+ let modified = base + std::time::Duration::from_secs(60 * index);
+ file.set_times(std::fs::FileTimes::new().set_modified(modified))
+ .unwrap();
+ path
+ })
+ .collect();
+ let names = |page: &SessionPage| {
+ page.infos
+ .iter()
+ .map(|info| info.name.clone().unwrap_or_default())
+ .collect::<Vec<_>>()
+ };
+ let first = list_sessions_with(&dir, None, Some(2), |_, _, _| true);
+ assert_eq!(names(&first), ["row 4", "row 3"]);
+ assert_eq!(first.remaining, 3);
+ fs::remove_file(&paths[3]).unwrap();
+ let second =
+ list_sessions_with(&dir, first.next_cursor.as_deref(), Some(2), |_, _, _| true);
+ assert_eq!(names(&second), ["row 2", "row 1"], "no file skipped");
+ assert_eq!(second.remaining, 1);
+ }
+ #[test]
+ fn a_session_modified_between_pages_is_not_skipped() {
+ let dir = temp_dir();
+ let base = SystemTime::now() - Duration::from_secs(3600);
+ let paths: Vec<_> = (0..3)
+ .map(|index| {
+ let path = write_session(&dir, "/repo/x", Some(&format!("row {index}")), 1);
+ fs::File::options()
+ .write(true)
+ .open(&path)
+ .unwrap()
+ .set_modified(base + Duration::from_secs(index))
+ .unwrap();
+ path
+ })
+ .collect();
+ let first = list_sessions_with(&dir, None, Some(1), |_, _, _| true);
+ assert_eq!(first.infos[0].name.as_deref(), Some("row 2"));
+ fs::File::options()
+ .write(true)
+ .open(&paths[0])
+ .unwrap()
+ .set_modified(SystemTime::now())
+ .unwrap();
+ let second =
+ list_sessions_with(&dir, first.next_cursor.as_deref(), Some(2), |_, _, _| true);
+ assert_eq!(
+ second
+ .infos
+ .iter()
+ .map(|info| info.name.as_deref())
+ .collect::<Vec<_>>(),
+ vec![Some("row 1"), Some("row 0")]
+ );
+ assert!(second.next_cursor.is_none());
+ let replay =
+ list_sessions_with(&dir, first.next_cursor.as_deref(), Some(2), |_, _, _| true);
+ assert_eq!(
+ replay.infos, second.infos,
+ "retrying a cursor reads the same file slice"
+ );
+ }
}
diff --git a/crates/pa-daemon/src/session_store/info.rs b/crates/pa-daemon/src/session_store/info.rs
index eb9b4288a4..016b037390 100644
--- a/crates/pa-daemon/src/session_store/info.rs
+++ b/crates/pa-daemon/src/session_store/info.rs
@@ -375,12 +375,18 @@ pub(super) struct SessionInfoEntry<'a> {
#[must_use]
pub fn read_session_info(path: &Path) -> Option<SessionInfo> {
let mut file = fs::File::open(path).ok()?;
- read_session_info_from(&mut file, path)
+ read_session_info_from(&mut file, path).map(|(info, _)| info)
}
/// [`read_session_info`] over an already-open handle: the roster gate shares
/// one open with the fold (the gate reads the first line, the fold rewinds).
-pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option<SessionInfo> {
+/// The flag is true when no in-process state served and the persisted sidecar
+/// did not cover the whole file (absent, unloadable, or behind): the fold read
+/// bytes a sidecar would have spared.
+pub(crate) fn read_session_info_from(
+ file: &mut fs::File,
+ path: &Path,
+) -> Option<(SessionInfo, bool)> {
let generation = SessionInfoGeneration::from_metadata(&file.metadata().ok()?);
// The unchanged case answers from the cache; the grown case resumes.
@@ -390,7 +396,7 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
Some(cached) if cached.generation == generation => {
let info = cached.info.clone();
cache.touch(path);
- return info;
+ return info.map(|info| (info, false));
}
Some(cached)
if cached.same_file_identity(&generation)
@@ -399,7 +405,7 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
if cached.prefix_intact(file) {
Some(cached.clone_for_resume())
} else {
- Some(SessionScanState::fresh(generation))
+ None
}
}
// No in-process state serves (absent or invalidated): the
@@ -408,8 +414,8 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
_ => None,
}
};
- let mut state = match state {
- Some(state) => state,
+ let (mut state, sidecar_behind) = match state {
+ Some(state) => (state, false),
None => {
// A previous lease holder's certified fold state, loaded from
// the sidecar. It passes the same validation ladder a cached
@@ -419,15 +425,15 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
// intact prefix folds its appended entries, and anything
// else is the cold scan the sidecar-less path always ran.
match info_sidecar::load(path) {
- Some(cached) if cached.generation == generation => cached,
+ Some(cached) if cached.generation == generation => (cached, false),
Some(cached)
if cached.same_file_identity(&generation)
&& generation.len > cached.generation.len
&& cached.prefix_intact(file) =>
{
- cached
+ (cached, true)
}
- _ => SessionScanState::fresh(generation),
+ _ => (SessionScanState::fresh(generation), true),
}
}
};
@@ -468,7 +474,7 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
cache.store_state(path, state);
}
}
- Some(info)
+ Some((info, sidecar_behind))
}
impl SessionScanState {
diff --git a/crates/pa-daemon/src/session_store/info_sidecar.rs b/crates/pa-daemon/src/session_store/info_sidecar.rs
index 9ed9fc278c..2700151845 100644
--- a/crates/pa-daemon/src/session_store/info_sidecar.rs
+++ b/crates/pa-daemon/src/session_store/info_sidecar.rs
@@ -4,8 +4,10 @@
//! instead of rescanning the whole file. pa-daemon owns the sidecar:
//! the scan state is this crate's type, and it certifies differently from
//! pa-core's window snapshot (an exact generation there, a grown-file
-//! resume with a prefix check here). Only the lease holder writes (the
-//! worker at release); every reader loads.
+//! resume with a prefix check here). Two writers: the lease holder at
+//! release, and the catalog scan for a file it had to fold. Both persist
+//! only certified states and every load re-validates the generation or
+//! prefix, so a lost race leaves an older valid prefix, never a wrong row.
use std::io::{self, Write};
use std::path::{Path, PathBuf};
@@ -46,8 +48,8 @@ pub(super) fn load(path: &Path) -> Option<SessionScanState> {
(sidecar.version == INFO_SIDECAR_VERSION).then_some(sidecar.state)
}
-/// The lease-release write: persist the cached scan state for `path` (the
-/// path form the lease holder opened and read the file by - the scan
+/// The sidecar write (lease release, catalog backfill): persist the cached
+/// scan state for `path` (the path form the writer read the file by - the scan
/// cache's key, and the form the load derives the sidecar path from) so
/// the next process that opens the file folds only what was appended
/// since. A fresh temp file, then the rename - a torn write never
diff --git a/crates/pa-daemon/src/session_store_info_tests.rs b/crates/pa-daemon/src/session_store_info_tests.rs
index f938cc054a..66968e0c84 100644
--- a/crates/pa-daemon/src/session_store_info_tests.rs
+++ b/crates/pa-daemon/src/session_store_info_tests.rs
@@ -438,7 +438,12 @@ fn a_failed_prefix_check_rescans_from_byte_zero() {
let file = fs::File::open(&path).unwrap();
let _ = file.set_modified(past);
drop(file);
- let second = read_session_info(&path).unwrap();
+ let mut file = fs::File::open(&path).unwrap();
+ let (second, sidecar_behind) = read_session_info_from(&mut file, &path).unwrap();
+ assert!(
+ sidecar_behind,
+ "a rejected prefix must mark the fresh scan for sidecar backfill"
+ );
assert_eq!(
second.name.as_deref(),
Some("after!"),
diff --git a/crates/pa-daemon/src/supervisor/sessions.rs b/crates/pa-daemon/src/supervisor/sessions.rs
index c7905c262f..5f6ff00dc7 100644
--- a/crates/pa-daemon/src/supervisor/sessions.rs
+++ b/crates/pa-daemon/src/supervisor/sessions.rs
@@ -8,6 +8,7 @@ use super::{
ResidentWorker, Result, RouteAdmission, Supervisor, Value, ROUTE_TIMEOUT_MS,
SUMMARY_TIMEOUT_MS,
};
+use crate::session_scan::list_sessions_with;
/// One spawn-name reservation held across a fresh-launch create (TS #2396): the only
/// cross-create serializer for a same-name admission.
@@ -126,7 +127,8 @@ impl Supervisor {
}
/// `list_saved_sessions`: stream `session_list_item`/`session_list_progress` events,
- /// then a final response with the full saved-session rows.
+ /// then a final response with the walked rows, the files left after them
+ /// (`remaining`), and the `nextCursor` that resumes the walk.
pub(super) async fn handle_saved_session_list(
self: &Arc<Self>,
command: &DaemonCommand,
@@ -138,6 +140,8 @@ impl Supervisor {
session_dir,
active_session_id,
scope,
+ limit,
+ cursor,
..
} = command
else {
@@ -209,9 +213,11 @@ impl Supervisor {
let scan_command_id = command_id.to_string();
let scan_active_session_id = active_session_id.clone();
let scan_cwd = cwd.clone();
+ let cursor = cursor.clone();
+ let limit = limit.map(|limit| limit as usize);
let scan = tokio::task::spawn_blocking(move || {
let mut file_total = 0usize;
- let infos = crate::session_scan::list_sessions_with(&dir, |index, total, info| {
+ let page = list_sessions_with(&dir, cursor.as_deref(), limit, |index, total, info| {
file_total = total;
if scope_current && info.cwd != scan_cwd {
// The row is out of scope, but the scan itself goes on.
@@ -256,9 +262,9 @@ impl Supervisor {
}
}
});
- (infos, file_total)
+ (page, file_total)
});
- let (mut infos, file_total) = match scan.await {
+ let (page, file_total) = match scan.await {
Ok(scanned) => scanned,
Err(error) => {
return vec![response_line(&response_failure(
@@ -272,6 +278,11 @@ impl Supervisor {
// The scan's parse trees folded and freed inside the blocking task; return their
// arena high-water to the OS at the phase boundary (live cache untouched).
pa_types::memory_release::trim_freed_heap();
+ let crate::session_scan::SessionPage {
+ mut infos,
+ remaining,
+ next_cursor,
+ } = page;
// The current-cwd scope keeps only the session's own rows in the terminal
// array: the response is the authoritative catalog.
if scope_current {
@@ -374,10 +385,14 @@ impl Supervisor {
// the authoritative array (the scan never re-orders after streaming).
let mut lines = Vec::new();
let sessions: Vec<Value> = infos.iter().map(saved_session_row).collect();
+ let mut data = json!({ "sessions": sessions, "remaining": remaining });
+ if let Some(next_cursor) = next_cursor {
+ data["nextCursor"] = json!(next_cursor);
+ }
lines.push(response_line(&response_success(
Some(command_id),
"list_saved_sessions",
- Some(json!({ "sessions": sessions })),
+ Some(data),
)));
// Telemetry: how many served rows carry a usage summary (a count only,
// never session payload).
diff --git a/crates/pa-daemon/tests/saved_catalog_stream_e2e.rs b/crates/pa-daemon/tests/saved_catalog_stream_e2e.rs
index 1ffe1e455f..ad95e6bfe1 100644
--- a/crates/pa-daemon/tests/saved_catalog_stream_e2e.rs
+++ b/crates/pa-daemon/tests/saved_catalog_stream_e2e.rs
@@ -145,7 +145,7 @@ fn write_fixture(
);
let _ = writeln!(
content,
- "{{\"type\":\"message\",\"id\":\"{id}-mu\",\"timestamp\":\"2024-01-01T00:00:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"run the drill\",\"timestamp\":0}}}}"
+ "{{\"type\":\"message\",\"id\":\"{id}-mu\",\"timestamp\":\"2024-01-01T00:00:00.000Z\",\"message\":{{\"role\":\"user\",\"content\":\"run the drill\",\"timestamp\":1}}}}"
);
for index in 0..grown_lines {
let _ = writeln!(
@@ -294,3 +294,101 @@ fn the_saved_catalog_streams_per_file_during_the_scan() {
"the first streamed row landed at {first_item:?} but the response at {response_at:?}: the catalog streamed after the whole scan, not per file"
);
}
+
+/// Read the stream up to the terminal response and return its `data`.
+fn list_saved(client: &mut Client, id: &str, command: &serde_json::Value) -> serde_json::Value {
+ client.send_command(id, command);
+ loop {
+ let line = client.read_line();
+ if line.get("type").and_then(serde_json::Value::as_str) == Some("response") {
+ assert_eq!(line["success"], true, "list failed: {line}");
+ return line["data"].clone();
+ }
+ }
+}
+
+fn sidecar_count(dir: &Path) -> usize {
+ std::fs::read_dir(dir)
+ .expect("read sessions dir")
+ .flatten()
+ .filter(|entry| {
+ entry
+ .file_name()
+ .to_string_lossy()
+ .ends_with(".info-cache.json")
+ })
+ .count()
+}
+
+/// A paged catalog folds only the newest `limit` files (each fold backfills its sidecar), and the
+/// cursor walks the rest of the store down to the oldest session.
+#[test]
+fn a_paged_catalog_folds_the_newest_page_and_the_cursor_reaches_the_oldest() {
+ const FILES: usize = 400;
+ const PAGE: usize = 200;
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");
+ std::fs::write(
+ agent_dir.join("settings.json"),
+ r#"{"sessionArchiveMaxSessions":"off"}"#,
+ )
+ .expect("write settings");
+ let base = SystemTime::now() - Duration::from_hours(24);
+ for index in 0..FILES {
+ write_fixture(
+ &sessions_dir,
+ &format!("paged-{index:03}"),
+ &format!("row {index:03}"),
+ 1,
+ base + Duration::from_secs(index as u64),
+ );
+ }
+ let socket = dir.path().join("daemon.sock");
+ let _daemon = spawn_daemon(&socket, &agent_dir);
+ let mut client = Client::connect(&socket);
+
+ let page = list_saved(
+ &mut client,
+ "p1",
+ &serde_json::json!({ "type": "list_saved_sessions", "cwd": "/tmp", "limit": PAGE }),
+ );
+ let rows = page["sessions"].as_array().expect("sessions");
+ assert_eq!(
+ rows.len(),
+ PAGE,
+ "the first page carries the newest files only"
+ );
+ assert_eq!(rows[0]["name"], "row 399");
+ assert_eq!(page["remaining"], FILES - PAGE);
+ assert_eq!(
+ sidecar_count(&sessions_dir),
+ PAGE,
+ "only the page's files were folded (and backfilled)"
+ );
+
+ let rest = list_saved(
+ &mut client,
+ "p2",
+ &serde_json::json!({
+ "type": "list_saved_sessions",
+ "cwd": "/tmp",
+ "cursor": page["nextCursor"],
+ }),
+ );
+ let rows = rest["sessions"].as_array().expect("sessions");
+ assert_eq!(
+ rows.len(),
+ FILES - PAGE,
+ "the cursor walks the rest of the store"
+ );
+ assert_eq!(rows[0]["name"], "row 199");
+ assert_eq!(rows[rows.len() - 1]["name"], "row 000");
+ assert_eq!(rest["remaining"], 0);
+ assert!(
+ rest.get("nextCursor").is_none(),
+ "a finished walk has no cursor: {rest}"
+ );
+ assert_eq!(sidecar_count(&sessions_dir), FILES);
+}
diff --git a/crates/pa-tui/src/agents_view.rs b/crates/pa-tui/src/agents_view.rs
index f4d893392f..1ce7305ced 100644
--- a/crates/pa-tui/src/agents_view.rs
+++ b/crates/pa-tui/src/agents_view.rs
@@ -182,6 +182,26 @@ const PULSE_INTERVAL_MS: u64 = 250;
/// The saved-catalog stream's batch window: rows reconcile on this cadence (progressive render).
const SAVED_CATALOG_RECONCILE_INTERVAL_MS: u64 = 75;
+/// The session files one saved-catalog page folds: the first fetch and every scroll fetch ask for
+/// this many (several screens' worth); a search asks for the whole rest of the store.
+const SAVED_CATALOG_PAGE_FILES: u64 = 200;
+
+/// The part of the store the catalog has not folded yet: its file count and the daemon's cursor
+/// that resumes the walk.
+#[derive(Clone)]
+struct SavedMore {
+ remaining: u64,
+ cursor: String,
+}
+
+/// The saved catalog a view run holds; the handoff link carries it to the flow's next run.
+#[derive(Default)]
+struct SavedCatalog {
+ sessions: Vec<Value>,
+ loaded: bool,
+ more: Option<SavedMore>,
+}
+
/// The transient status hint while the entry anchor still waits on its row.
const ANCHOR_LOADING_HINT: &str = "Still loading sessions — press ↓ or ↑ to pick a session now.";
@@ -209,9 +229,12 @@ enum UiInput {
Resize,
Settled,
Done,
- /// The saved-catalog fetch landed: the Inactive section rebuilds from these rows.
+ /// The saved-catalog fetch landed: the Inactive section rebuilds from these rows. A
+ /// `continued` fetch (one that resumed a cursor) adds its rows to the catalog.
SavedLoaded {
sessions: Vec<Value>,
+ more: Option<SavedMore>,
+ continued: bool,
},
/// The saved-catalog fetch failed; the status line reports it.
SavedFailed {
@@ -265,8 +288,7 @@ pub struct AgentsViewLink {
events: mpsc::UnboundedReceiver<DaemonClientEvent>,
/// The saved catalog the previous view run loaded: a re-entry paints the Inactive rows it
/// already holds on its FIRST frame, and a loaded catalog skips the re-fetch.
- saved_sessions: Vec<Value>,
- saved_catalog_loaded: bool,
+ saved: SavedCatalog,
}
impl AgentsViewLink {
@@ -275,8 +297,7 @@ impl AgentsViewLink {
Ok(Self {
client,
events,
- saved_sessions: Vec::new(),
- saved_catalog_loaded: false,
+ saved: SavedCatalog::default(),
})
}
@@ -398,6 +419,10 @@ struct AgentsViewMode {
/// The catalog settled on a successful load: no fetch while it holds, and the exit link
/// carries it so the next run skips its own fetch.
saved_catalog_loaded: bool,
+ /// The store files the catalog has not folded yet; a scroll near the end or a search
+ /// fetches them.
+ saved_more: Option<SavedMore>,
+ saved_page_requested: bool,
/// The screen rows of the rendered session rows, in frame order — exactly the rows the last
/// frame painted (a plain left click opens the row under it). Rebuilt on every render.
click_rows: Vec<(usize, usize)>,
@@ -507,6 +532,8 @@ impl AgentsViewMode {
saved_query_rearm: false,
saved_stream: Vec::new(),
saved_catalog_loaded: false,
+ saved_more: None,
+ saved_page_requested: false,
incident_notice_state,
click_rows: Vec::new(),
hover_row: None,
@@ -527,29 +554,18 @@ async fn open_roster_link(
DaemonClient,
mpsc::UnboundedReceiver<DaemonClientEvent>,
Vec<Value>,
- Vec<Value>,
- bool,
+ SavedCatalog,
)> {
- let (mut client, mut events, saved_sessions, saved_catalog_loaded) =
- if let Some(AgentsViewLink {
- client,
- events,
- saved_sessions,
- saved_catalog_loaded,
- }) = link
- {
- (client, events, saved_sessions, saved_catalog_loaded)
- } else {
- let link = AgentsViewLink::connect(&options.socket_path)
- .await
- .with_context(|| "the agents view could not attach to the daemon")?;
- (
- link.client,
- link.events,
- link.saved_sessions,
- link.saved_catalog_loaded,
- )
- };
+ let AgentsViewLink {
+ mut client,
+ mut events,
+ saved,
+ } = match link {
+ Some(link) => link,
+ None => AgentsViewLink::connect(&options.socket_path)
+ .await
+ .with_context(|| "the agents view could not attach to the daemon")?,
+ };
let roster_subscribe = || DaemonCommand::RosterSubscribe {
id: None,
rest: serde_json::Map::default(),
@@ -579,17 +595,20 @@ async fn open_roster_link(
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
- Ok((client, events, roster, saved_sessions, saved_catalog_loaded))
+ Ok((client, events, roster, saved))
}
/// The saved-catalog fetch: the result (or failure) re-enters the loop as a `UiInput`, while
/// the scan's events ride the fetch's request id — the id the loop compares. A terminal
-/// failure re-arms on the next query change.
+/// failure re-arms on the next query change. `cursor` resumes a previous page's walk; `limit`
+/// caps the files it folds (`None` walks the rest of the store).
fn spawn_saved_catalog_fetch(
client: &DaemonClient,
ui_tx: mpsc::UnboundedSender<UiInput>,
cwd: PathBuf,
session_dir: Option<PathBuf>,
+ cursor: Option<String>,
+ limit: Option<u64>,
) -> String {
static CATALOG_FETCH_SEQUENCE: AtomicU64 = AtomicU64::new(0);
let client = client.clone();
@@ -609,6 +628,8 @@ fn spawn_saved_catalog_fetch(
session_dir: session_dir.map(|dir| dir.to_string_lossy().to_string()),
active_session_id: None,
scope: Value::Null,
+ limit,
+ cursor: cursor.clone(),
rest: serde_json::Map::default(),
},
&request_id,
@@ -616,15 +637,27 @@ fn spawn_saved_catalog_fetch(
)
.await;
let input = match saved {
- Ok(response) if response.success => UiInput::SavedLoaded {
- sessions: response
- .data
- .as_ref()
- .and_then(|data| data.get("sessions"))
- .and_then(Value::as_array)
- .cloned()
- .unwrap_or_default(),
- },
+ Ok(response) if response.success => {
+ let data = response.data.unwrap_or_default();
+ UiInput::SavedLoaded {
+ sessions: data
+ .get("sessions")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default(),
+ more: data
+ .get("nextCursor")
+ .and_then(Value::as_str)
+ .map(|next| SavedMore {
+ remaining: data
+ .get("remaining")
+ .and_then(Value::as_u64)
+ .unwrap_or_default(),
+ cursor: next.to_string(),
+ }),
+ continued: cursor.is_some(),
+ }
+ }
Ok(response) => UiInput::SavedFailed {
error: response.error.unwrap_or_else(|| "unknown error".into()),
},
@@ -679,16 +712,15 @@ async fn run_agents_view_surface(
crossterm::style::force_color_output(true);
// This pane may arrive already in TUI state (the chat's teardown preserves it), so a
// roster-link failure here must hand the terminal back before the error escapes.
- let (client, mut events, roster, saved_sessions, saved_catalog_loaded) =
- match open_roster_link(&options, link).await {
- Ok(open) => open,
- Err(error) => {
- if matches!(ui, AgentsViewUiMode::Terminal) {
- crate::exit_restore::restore_terminal();
- }
- return Err(error);
+ let (client, mut events, roster, saved) = match open_roster_link(&options, link).await {
+ Ok(open) => open,
+ Err(error) => {
+ if matches!(ui, AgentsViewUiMode::Terminal) {
+ crate::exit_restore::restore_terminal();
}
- };
+ return Err(error);
+ }
+ };
// The double-Ctrl+C force-quit guard: same contract as the session loop.
let exit_guard = crate::exit_guard::ExitGuard::new();
@@ -698,8 +730,9 @@ async fn run_agents_view_surface(
mode.roster = roster;
// The flow's carried catalog paints on the FIRST frame (a loaded catalog means no fetch
// below).
- mode.saved = saved_sessions;
- mode.saved_catalog_loaded = saved_catalog_loaded;
+ mode.saved = saved.sessions;
+ mode.saved_catalog_loaded = saved.loaded;
+ mode.saved_more = saved.more;
mode.rebuild_rows();
// The notice from the log's bounded tail paints on the FIRST frame, before the interval's
// first tick.
@@ -731,7 +764,14 @@ async fn run_agents_view_surface(
// A loaded catalog never re-fetches; a first run - or one whose previous fetch failed - arms
// the fetch below.
let mut catalog_request = (!mode.saved_catalog_loaded).then(|| {
- spawn_saved_catalog_fetch(&client, ui_tx.clone(), cwd.clone(), session_dir.clone())
+ spawn_saved_catalog_fetch(
+ &client,
+ ui_tx.clone(),
+ cwd.clone(),
+ session_dir.clone(),
+ None,
+ Some(SAVED_CATALOG_PAGE_FILES),
+ )
});
// The heartbeat catalog feeds the rows' `◷ N` badges: the same
// selector-less `heartbeats_list` the activity dock reads, fetched
@@ -747,7 +787,7 @@ async fn run_agents_view_surface(
// rebuild above or the catalog already settled without it; an armed
// fetch keeps the wait (its load settles it).
if catalog_request.is_none() {
- mode.end_anchor_wait();
+ mode.settle_carried_anchor();
}
let mut pending: Vec<UiInput> = Vec::new();
let mut last_pulse = tokio::time::Instant::now();
@@ -839,6 +879,8 @@ async fn run_agents_view_surface(
ui_tx.clone(),
cwd.clone(),
session_dir.clone(),
+ None,
+ Some(SAVED_CATALOG_PAGE_FILES),
));
// A superseded fetch's stream stops applying: the new fetch owns the
// catalog.
@@ -920,13 +962,21 @@ async fn run_agents_view_surface(
mode.kill_result(&key, outcome);
}
// The saved-catalog scan landed: the Inactive section builds now.
- UiInput::SavedLoaded { sessions } => {
+ UiInput::SavedLoaded {
+ sessions,
+ more,
+ continued,
+ } => {
// The final response is the authoritative array: a late frame must not upsert
// its un-enriched row over the catalog the response just settled.
mode.drop_saved_stream();
saved_flush = None;
catalog_request = None;
- mode.apply_saved_loaded(sessions);
+ if continued {
+ mode.upsert_saved(sessions);
+ } else {
+ mode.apply_saved_loaded(sessions);
+ }
// The catalog's success retires the failure status (never keep reporting an
// unavailable catalog after it loaded).
if mode
@@ -936,9 +986,7 @@ async fn run_agents_view_surface(
mode.status = None;
}
mode.rebuild_rows();
- // The anchor's row can only arrive through THIS fetch, so a terminal load
- // without it ends the wait.
- mode.end_anchor_wait();
+ mode.finish_saved_page(more);
}
UiInput::SavedFailed { error } => {
// The catalog settled on a terminal failure: the anchor's wait ends with it,
@@ -1081,6 +1129,21 @@ async fn run_agents_view_surface(
+ Duration::from_millis(crate::incident_notices::INCIDENT_NOTICE_POLL_INTERVAL_MS);
redraw |= mode.refresh_incident_notices();
}
+ // The unfolded rest of the store: a scroll near the list's end fetches the next page, a
+ // search fetches all of it (its rows stream in as they fold).
+ if catalog_request.is_none() {
+ if let Some((cursor, limit)) = mode.next_saved_fetch() {
+ mode.saved_page_requested = false;
+ catalog_request = Some(spawn_saved_catalog_fetch(
+ &client,
+ ui_tx.clone(),
+ cwd.clone(),
+ session_dir.clone(),
+ Some(cursor),
+ limit,
+ ));
+ }
+ }
if redraw {
renderer.draw(&mut mode);
}
@@ -1171,8 +1234,11 @@ async fn run_agents_view_surface(
Some(AgentsViewLink {
client,
events,
- saved_sessions: mode.saved.clone(),
- saved_catalog_loaded: mode.saved_catalog_loaded,
+ saved: SavedCatalog {
+ sessions: mode.saved.clone(),
+ loaded: mode.saved_catalog_loaded,
+ more: mode.saved_more.clone(),
+ },
})
} else {
client.close();
diff --git a/crates/pa-tui/src/agents_view/data_input.rs b/crates/pa-tui/src/agents_view/data_input.rs
index e1310aa4a8..6160711106 100644
--- a/crates/pa-tui/src/agents_view/data_input.rs
+++ b/crates/pa-tui/src/agents_view/data_input.rs
@@ -5,8 +5,8 @@ use super::{
build_rows, compute_rollups, filter_empty_sessions, filter_unified_sessions,
parse_search_query, reconcile_unified_sessions, resolve_selection, scope_ancestors, scope_root,
scope_to_subtree, AgentsViewMode, AgentsViewRow, AgentsViewScope, Composer, OpenedRow, PathBuf,
- PressedMouseClick, RowKind, ScopeRoot, SelectionEdge, SelectionKey, SessionSelection, Value,
- ANCHOR_LOADING_HINT,
+ PressedMouseClick, RowKind, SavedMore, ScopeRoot, SelectionEdge, SelectionKey,
+ SessionSelection, Value, ANCHOR_LOADING_HINT, SAVED_CATALOG_PAGE_FILES,
};
impl AgentsViewMode {
@@ -276,14 +276,25 @@ impl AgentsViewMode {
self.saved_stream.push(session);
}
- /// Flush the streamed batch into the catalog: upsert by path first, then durable id, so a
- /// superseded fetch's late frames never duplicate a row. Returns whether the catalog changed.
+ /// Flush the streamed batch into the catalog. Returns whether the catalog changed.
pub(super) fn flush_saved_stream(&mut self) -> bool {
if self.saved_stream.is_empty() {
return false;
}
- for row in std::mem::take(&mut self.saved_stream) {
+ let rows = std::mem::take(&mut self.saved_stream);
+ self.upsert_saved(rows);
+ self.rebuild_rows();
+ true
+ }
+
+ /// Upsert rows into the catalog by path first, then durable id, so a superseded fetch's late
+ /// frames or a page that repeats a row never duplicate it. Paths deleted this run stay out.
+ pub(super) fn upsert_saved(&mut self, rows: Vec<Value>) {
+ for row in rows {
let path = row.get("path").and_then(Value::as_str);
+ if path.is_some_and(|path| self.deleted_saved_paths.contains(path)) {
+ continue;
+ }
let durable_id = row.get("id").and_then(Value::as_str);
let existing = self.saved.iter().position(|saved| {
path.is_some_and(|path| saved.get("path").and_then(Value::as_str) == Some(path))
@@ -295,8 +306,45 @@ impl AgentsViewMode {
None => self.saved.push(row),
}
}
- self.rebuild_rows();
- true
+ }
+
+ /// The next fetch of the unfolded store, as its cursor and file limit: a search wants the
+ /// whole rest, a selection within a page step of the list's end wants the next page. A
+ /// failed fetch waits for the query-change retry.
+ pub(super) fn next_saved_fetch(&self) -> Option<(String, Option<u64>)> {
+ let more = self
+ .saved_more
+ .as_ref()
+ .filter(|_| !self.saved_fetch_failed)?;
+ if !self.query.trim().is_empty() {
+ return Some((more.cursor.clone(), None));
+ }
+ if self.anchor_selection_pending {
+ return Some((more.cursor.clone(), Some(SAVED_CATALOG_PAGE_FILES)));
+ }
+ if !self.saved_page_requested {
+ return None;
+ }
+ let last = self
+ .rows
+ .iter()
+ .rposition(AgentsViewRow::selectable)
+ .unwrap_or(0);
+ (self.selected + self.page_step() >= last)
+ .then(|| (more.cursor.clone(), Some(SAVED_CATALOG_PAGE_FILES)))
+ }
+
+ pub(super) fn settle_carried_anchor(&mut self) {
+ if self.saved_more.is_none() {
+ self.end_anchor_wait();
+ }
+ }
+
+ pub(super) fn finish_saved_page(&mut self, more: Option<SavedMore>) {
+ self.saved_more = more;
+ if self.saved_more.is_none() {
+ self.end_anchor_wait();
+ }
}
/// Drop the unflushed stream batch: the terminal response replaces the catalog wholesale, and
@@ -365,13 +413,15 @@ impl AgentsViewMode {
self.saved_catalog_loaded = true;
}
- /// Whether the loop must re-arm the saved-catalog fetch (one retry per terminal failure).
+ /// Whether the loop must re-fetch the first saved-catalog page (one retry per terminal
+ /// failure). A failed continuation's retry resumes its cursor through `next_saved_fetch`
+ /// instead, so the pages already loaded stay.
pub(super) fn take_saved_fetch_rearm(&mut self) -> bool {
let rearm = std::mem::take(&mut self.saved_query_rearm);
if rearm {
self.saved_fetch_failed = false;
}
- rearm
+ rearm && self.saved_more.is_none()
}
/// The loading hint belongs to the wait alone: ending the wait by either arm drops it, so the
@@ -536,6 +586,7 @@ impl AgentsViewMode {
return;
}
if self.keybindings.matches(key, "tui.select.down") {
+ self.saved_page_requested = true;
self.move_selection(1);
return;
}
@@ -544,6 +595,7 @@ impl AgentsViewMode {
return;
}
if self.keybindings.matches(key, "tui.select.pageDown") {
+ self.saved_page_requested = true;
self.move_selection(self.page_step() as isize);
return;
}
@@ -555,6 +607,7 @@ impl AgentsViewMode {
return;
}
if self.keybindings.matches(key, "tui.select.bottom") {
+ self.saved_page_requested = true;
self.move_selection_to(SelectionEdge::Last);
return;
}
diff --git a/crates/pa-tui/src/agents_view/render.rs b/crates/pa-tui/src/agents_view/render.rs
index ffed3b31bd..f23cc57191 100644
--- a/crates/pa-tui/src/agents_view/render.rs
+++ b/crates/pa-tui/src/agents_view/render.rs
@@ -95,9 +95,27 @@ impl AgentsViewMode {
.flatten()
.map(str::to_string);
let notice_height = notice_panel.as_ref().map_or(0, Vec::len);
- let list_rows = height.saturating_sub(lines.len() + 1 + notice_height);
+ // The catalog never truncates silently: while store files are still unfolded, the list
+ // ends with their count.
+ let unloaded = self.saved_more.as_ref().map(|more| {
+ let text = if self.query.trim().is_empty() {
+ format!(
+ "{} older sessions not loaded \u{b7} scroll to load",
+ more.remaining
+ )
+ } else {
+ format!("Searching {} older sessions\u{2026}", more.remaining)
+ };
+ pad_line(
+ vec![self.theme.fg(ThemeColor::Dim, truncate_text(&text, width))],
+ width,
+ )
+ });
+ let list_rows = height
+ .saturating_sub(lines.len() + 1 + notice_height + usize::from(unloaded.is_some()));
let list_frame_row = lines.len();
lines.extend(self.render_list(width, list_rows, list_frame_row));
+ lines.extend(unloaded);
if let Some(panel) = notice_panel {
lines.extend(panel);
}
diff --git a/crates/pa-tui/src/agents_view/tests.rs b/crates/pa-tui/src/agents_view/tests.rs
index 0271680761..ef203f3eb3 100644
--- a/crates/pa-tui/src/agents_view/tests.rs
+++ b/crates/pa-tui/src/agents_view/tests.rs
@@ -22,6 +22,7 @@ mod render_pulse;
mod reply;
mod running_lines;
mod saved_catalog;
+mod saved_pages;
mod search_selection;
mod selection_churn;
diff --git a/crates/pa-tui/src/agents_view/tests/delete_stop.rs b/crates/pa-tui/src/agents_view/tests/delete_stop.rs
index ad272fc91a..222d752720 100644
--- a/crates/pa-tui/src/agents_view/tests/delete_stop.rs
+++ b/crates/pa-tui/src/agents_view/tests/delete_stop.rs
@@ -303,6 +303,31 @@ fn a_deleted_path_survives_a_late_catalog_apply() {
);
}
+#[test]
+fn a_deleted_path_survives_a_late_page_upsert() {
+ let mut mode = mode_with_anchor(None, Vec::new());
+ mode.saved = vec![saved_catalog_row(
+ "/x/gone.jsonl",
+ "gone-1",
+ "a deleted session",
+ )];
+ mode.rebuild_rows();
+ mode.delete_result(
+ "Deleted session a deleted session",
+ StatusTone::Muted,
+ Some("/x/gone.jsonl".to_string()),
+ );
+ mode.upsert_saved(vec![saved_catalog_row(
+ "/x/gone.jsonl",
+ "gone-1",
+ "a deleted session",
+ )]);
+ assert!(
+ mode.saved.is_empty(),
+ "the deleted path stays gone behind a continued page"
+ );
+}
+
#[test]
fn a_roster_replacement_retires_the_armed_confirm() {
let mut mode = mode_with_parent_and_child();
diff --git a/crates/pa-tui/src/agents_view/tests/saved_pages.rs b/crates/pa-tui/src/agents_view/tests/saved_pages.rs
new file mode 100644
index 0000000000..fc2b2792dd
--- /dev/null
+++ b/crates/pa-tui/src/agents_view/tests/saved_pages.rs
@@ -0,0 +1,101 @@
+use super::*;
+
+fn more() -> Option<SavedMore> {
+ Some(SavedMore {
+ cursor: "page-two".to_string(),
+ remaining: 1,
+ })
+}
+
+#[test]
+fn an_empty_saved_page_waits_for_navigation_or_search() {
+ let mut mode = mode_with_anchor(None, Vec::new());
+ mode.apply_saved_loaded(Vec::new());
+ mode.rebuild_rows();
+ mode.finish_saved_page(more());
+ assert!(
+ mode.next_saved_fetch().is_none(),
+ "an empty frame must not drain the store automatically"
+ );
+ mode.handle_key("down");
+ assert_eq!(
+ mode.next_saved_fetch(),
+ Some(("page-two".to_string(), Some(SAVED_CATALOG_PAGE_FILES)))
+ );
+ mode.saved_page_requested = false;
+ mode.query = "older".to_string();
+ assert_eq!(
+ mode.next_saved_fetch(),
+ Some(("page-two".to_string(), None))
+ );
+}
+
+#[test]
+fn a_saved_anchor_beyond_the_first_page_remains_pending_until_it_arrives() {
+ let mut mode = mode_with_anchor(Some("older"), Vec::new());
+ mode.apply_saved_loaded(vec![saved_catalog_row("/x/new.jsonl", "new", "newer")]);
+ mode.rebuild_rows();
+ mode.finish_saved_page(more());
+ assert!(mode.anchor_selection_pending);
+ mode.handle_key("enter");
+ assert!(
+ mode.opened.is_none(),
+ "Enter cannot confirm the wrong row while the anchor is pending"
+ );
+ assert_eq!(
+ mode.next_saved_fetch(),
+ Some(("page-two".to_string(), Some(SAVED_CATALOG_PAGE_FILES)))
+ );
+ mode.upsert_saved(vec![saved_catalog_row("/x/older.jsonl", "older", "older")]);
+ mode.rebuild_rows();
+ mode.finish_saved_page(None);
+ mode.handle_key("enter");
+ assert_eq!(
+ mode.opened.map(|row| row.selection),
+ Some(SessionSelection::Resume(PathBuf::from("/x/older.jsonl")))
+ );
+}
+
+#[test]
+fn a_carried_partial_catalog_keeps_waiting_for_a_missing_anchor() {
+ let mut mode = mode_with_anchor(Some("older"), Vec::new());
+ mode.apply_saved_loaded(vec![saved_catalog_row("/x/new.jsonl", "new", "newer")]);
+ mode.rebuild_rows();
+ mode.finish_saved_page(more());
+ assert!(mode.saved_catalog_loaded);
+ mode.settle_carried_anchor();
+ assert!(
+ mode.anchor_selection_pending,
+ "a carried page is not the complete catalog"
+ );
+ assert!(mode.next_saved_fetch().is_some());
+ mode.handle_key("enter");
+ assert!(mode.opened.is_none());
+ mode.finish_saved_page(None);
+ mode.settle_carried_anchor();
+ assert!(
+ !mode.anchor_selection_pending,
+ "an exhausted catalog settles a missing anchor"
+ );
+}
+
+#[test]
+fn a_failed_continuation_retries_from_its_cursor() {
+ let mut mode = mode_with_anchor(None, Vec::new());
+ mode.apply_saved_loaded(vec![saved_catalog_row("/x/new.jsonl", "new", "newer")]);
+ mode.rebuild_rows();
+ mode.finish_saved_page(more());
+ // The continuation page fails (the loop's `SavedFailed` arm).
+ mode.saved_fetch_failed = true;
+ assert!(mode.next_saved_fetch().is_none());
+ mode.handle_key("o");
+ assert!(
+ !mode.take_saved_fetch_rearm(),
+ "the retry never refetches the first page over the loaded rows"
+ );
+ assert_eq!(
+ mode.next_saved_fetch(),
+ Some(("page-two".to_string(), None)),
+ "the search resumes the failed page's cursor"
+ );
+}
diff --git a/crates/pa-tui/tests/agents_view_paged_catalog.rs b/crates/pa-tui/tests/agents_view_paged_catalog.rs
new file mode 100644
index 0000000000..edad3585c7
--- /dev/null
+++ b/crates/pa-tui/tests/agents_view_paged_catalog.rs
@@ -0,0 +1,238 @@
+//! The paged saved catalog: the first fetch asks for one page, the list says how many older
+//! sessions are not loaded yet, scrolling to the end loads the next page, and a search walks the
+//! rest of the store so the oldest session is still found.
+#![cfg(unix)]
+
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use pa_tui::agents_view::{AgentsHeadlessPlan, AgentsStep, AgentsViewOptions, AgentsViewUiMode};
+use serde_json::{json, Value};
+
+const FILES: usize = 600;
+
+/// Serve one view connection: `list_saved_sessions` answers the newest-first slice its
+/// `cursor`/`limit` select (the mock's cursor is the slice start).
+fn serve(listener: &UnixListener, saved_requests: &Mutex<Vec<Value>>) {
+ let (stream, _) = listener.accept().expect("accept view connection");
+ stream
+ .set_read_timeout(Some(Duration::from_millis(100)))
+ .expect("read timeout");
+ let mut writer = stream.try_clone().expect("clone socket");
+ let mut reader = BufReader::new(stream);
+ write_line(
+ &mut writer,
+ &json!({
+ "type": "daemon_hello",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "serverCapabilities": [],
+ }),
+ );
+ while let Some(line) = read_line(&mut reader) {
+ let Ok(envelope) = serde_json::from_str::<Value>(&line) else {
+ continue;
+ };
+ let id = envelope["id"].as_str().unwrap_or_default().to_string();
+ let command = envelope["command"].clone();
+ match command["type"].as_str().unwrap_or_default() {
+ "roster_subscribe" => respond(
+ &mut writer,
+ &id,
+ "roster_subscribe",
+ &json!({ "roster": [] }),
+ ),
+ "list_saved_sessions" => {
+ saved_requests.lock().unwrap().push(command.clone());
+ let start: usize = command["cursor"].as_str().map_or(0, |c| c.parse().unwrap());
+ let end = command["limit"].as_u64().map_or(FILES, |limit| {
+ (start + usize::try_from(limit).unwrap()).min(FILES)
+ });
+ let rows: Vec<Value> = (start..end)
+ .map(|index| saved_row(FILES - 1 - index))
+ .collect();
+ for row in &rows {
+ write_line(
+ &mut writer,
+ &json!({
+ "id": id,
+ "type": "session_list_item",
+ "command": "list_saved_sessions",
+ "session": row,
+ }),
+ );
+ }
+ let mut data = json!({ "sessions": rows, "remaining": FILES - end });
+ if end < FILES {
+ data["nextCursor"] = json!(end.to_string());
+ }
+ respond(&mut writer, &id, "list_saved_sessions", &data);
+ }
+ other => respond(&mut writer, &id, other, &Value::Null),
+ }
+ }
+}
+
+/// Row `index` 0 is the oldest session; its name is the search target.
+fn saved_row(index: usize) -> Value {
+ let name = if index == 0 {
+ "oldest drill".to_string()
+ } else {
+ format!("row {index:03}")
+ };
+ json!({
+ "path": format!("/tmp/sessions/s{index:03}.jsonl"),
+ "id": format!("s{index:03}"),
+ "cwd": "/tmp",
+ "rlmDepth": 0,
+ "created": "2024-01-01T00:00:00.000Z",
+ "modified": format!("2024-01-01T00:{:02}:{:02}.000Z", index / 60, index % 60),
+ "messageCount": 3,
+ "name": name,
+ })
+}
+
+fn write_line(writer: &mut UnixStream, value: &Value) {
+ let mut line = serde_json::to_string(value).expect("serialize line");
+ line.push('\n');
+ writer.write_all(line.as_bytes()).expect("write");
+ writer.flush().expect("flush");
+}
+
+fn respond(writer: &mut UnixStream, id: &str, command: &str, data: &Value) {
+ write_line(
+ writer,
+ &json!({
+ "id": id,
+ "type": "response",
+ "command": command,
+ "success": true,
+ "data": data,
+ }),
+ );
+}
+
+/// One line with a bounded quiet window (the view connection sits quiet between its inputs); `None`
+/// ends the serve loop on EOF or the quiet cap.
+fn read_line(reader: &mut BufReader<UnixStream>) -> Option<String> {
+ const QUIET_WINDOW_MS: u32 = 90;
+ let mut quiet_windows: u32 = 0;
+ let mut line = String::new();
+ loop {
+ match reader.read_line(&mut line) {
+ Ok(0) => return None,
+ Ok(_) if line.trim().is_empty() => {
+ line.clear();
+ }
+ Ok(_) => return Some(line),
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
+ ) =>
+ {
+ quiet_windows += 1;
+ if quiet_windows >= QUIET_WINDOW_MS {
+ return None;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ line.clear();
+ }
+ Err(_) => return None,
+ }
+ }
+}
+
+fn view_options(socket: &std::path::Path) -> AgentsViewOptions {
+ AgentsViewOptions {
+ socket_path: socket.to_path_buf(),
+ cwd: PathBuf::from("/tmp"),
+ session_dir: Some(PathBuf::from("/tmp/sessions")),
+ theme: "prime".to_string(),
+ version: "0.0.0".to_string(),
+ anchor_session_id: None,
+ scope: None,
+ query: None,
+ expanded_ancestors: Vec::new(),
+ selected_row_identity: None,
+ selected_key: None,
+ status_message: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ show_hardware_cursor: false,
+ incident_notice_state: None,
+ create_config: serde_json::json!({}),
+ }
+}
+
+#[tokio::test]
+async fn the_catalog_pages_on_scroll_and_a_search_walks_the_rest() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("agents-view.sock");
+ let listener = UnixListener::bind(&socket).expect("bind mock socket");
+ let saved_requests = Arc::new(Mutex::new(Vec::new()));
+ let server = {
+ let saved_requests = Arc::clone(&saved_requests);
+ std::thread::spawn(move || serve(&listener, &saved_requests))
+ };
+
+ let plan = AgentsHeadlessPlan {
+ steps: vec![
+ AgentsStep::WaitRender {
+ needle: "400 older sessions not loaded".to_string(),
+ timeout_ms: 3000,
+ },
+ AgentsStep::Key("end".to_string()),
+ AgentsStep::WaitRender {
+ needle: "200 older sessions not loaded".to_string(),
+ timeout_ms: 3000,
+ },
+ AgentsStep::Type("oldest".to_string()),
+ AgentsStep::WaitRender {
+ needle: "oldest drill".to_string(),
+ timeout_ms: 3000,
+ },
+ ],
+ width: 120,
+ height: 36,
+ };
+ let outcome = pa_tui::agents_view::run_agents_view(
+ view_options(&socket),
+ AgentsViewUiMode::Headless(plan),
+ None,
+ )
+ .await
+ .expect("the agents view run")
+ .outcome;
+
+ let frames = outcome.frames.join("\n");
+ assert!(frames.contains("400 older sessions not loaded"), "{frames}");
+ assert!(
+ frames.contains("Searching 200 older sessions"),
+ "the search names the rows it is still loading: {frames}"
+ );
+ assert!(
+ outcome.frames.last().is_some_and(
+ |frame| frame.contains("oldest drill") && !frame.contains("older sessions")
+ ),
+ "the search found the oldest session and the whole store loaded: {:?}",
+ outcome.frames.last()
+ );
+ let requests: Vec<(Value, Value)> = saved_requests
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|request| (request["cursor"].clone(), request["limit"].clone()))
+ .collect();
+ assert_eq!(
+ requests,
+ vec![
+ (Value::Null, json!(200)),
+ (json!("200"), json!(200)),
+ (json!("400"), Value::Null),
+ ],
+ "first page, scroll page, then the search's remainder"
+ );
+ let _ = server.join();
+}
diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs
index 43101b8c06..627bd7314e 100644
--- a/crates/pa-types/src/daemon/command.rs
+++ b/crates/pa-types/src/daemon/command.rs
@@ -117,6 +117,12 @@ pub enum DaemonCommand {
session_dir: Option<String>,
#[serde(default)]
scope: Value,
+ /// The most session files this request folds; `None` walks to the end of the store.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ limit: Option<u64>,
+ /// A previous response's `nextCursor`: the walk resumes after that file.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ cursor: Option<String>,
#[serde(flatten)]
rest: JsonMap,
},
diff --git a/scripts/review_saved_catalog_parity.py b/scripts/review_saved_catalog_parity.py
new file mode 100644
index 0000000000..8b48d602b8
--- /dev/null
+++ b/scripts/review_saved_catalog_parity.py
@@ -0,0 +1,305 @@
+#!/usr/bin/env python3
+"""Actual TS/Rust saved-catalog baseline and Rust paging evidence.
+
+No UI/frame parity is claimed. Historical TS ignores optional limit/cursor;
+Rust intentionally adds a bounded walk. Both actual daemons read the same
+synthetic saved-session corpus without create, prompt, provider or kernel.
+"""
+import argparse
+from datetime import datetime, timezone
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+
+from review_agent_bounce_parity import Client
+from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256
+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish
+
+COUNT = 205
+PAGE = 200
+BASE_MS = 1704067200000
+CWD = '/tmp/catalog-paging-fixture'
+TARGET = 'SAVED_CATALOG_OLD_NAME_SEARCH_TARGET'
+TRANSCRIPT_TARGET = 'SAVED_CATALOG_OLD_ASSISTANT_WIRE_TARGET'
+FIELDS = ('path', 'id', 'cwd', 'name', 'messageCount', 'firstMessage', 'allMessagesText')
+
+
+def iso(milliseconds):
+ return datetime.fromtimestamp(milliseconds / 1000, timezone.utc).isoformat(
+ timespec='milliseconds').replace('+00:00', 'Z')
+
+
+def seed(root):
+ directory = root / 'agent/sessions'
+ directory.mkdir(parents=True, exist_ok=True)
+ expected = []
+ for index in range(COUNT):
+ ident = f'catalog-{index:03}'
+ stamp = BASE_MS + index * 10000
+ user = f'Catalog user {index:03}'
+ assistant = TRANSCRIPT_TARGET if index == 0 else f'Catalog assistant {index:03}'
+ name = TARGET if index == 0 else f'Catalog row {index:03}'
+ entries = [
+ {'type': 'session', 'version': 3, 'id': ident, 'timestamp': iso(stamp),
+ 'cwd': CWD, 'rlmDepth': 0},
+ {'type': 'session_info', 'id': ident + '-info', 'parentId': None,
+ 'timestamp': iso(stamp), 'name': name},
+ {'type': 'session_state', 'id': ident + '-state', 'parentId': ident + '-info',
+ 'timestamp': iso(stamp), 'state': {'status': 'archived'}},
+ {'type': 'message', 'id': ident + '-user', 'parentId': ident + '-state',
+ 'timestamp': iso(stamp), 'message': {'role': 'user', 'content': user,
+ 'timestamp': stamp}},
+ {'type': 'message', 'id': ident + '-assistant', 'parentId': ident + '-user',
+ 'timestamp': iso(stamp + 1000), 'message': {'role': 'assistant',
+ 'content': [{'type': 'text', 'text': assistant}],
+ 'provider': 'parity-local', 'model': 'parity-1', 'timestamp': stamp + 1000}},
+ ]
+ path = directory / (ident + '.jsonl')
+ path.write_text(''.join(json.dumps(row) + '\n' for row in entries))
+ ns = stamp * 1000000
+ os.utime(path, ns=(ns, ns))
+ assert path.stat().st_mtime_ns == ns, 'fixture filesystem lost deterministic mtime'
+ expected.append(dict(zip(FIELDS, (path.name, ident, CWD, name,
+ 2, user, user + ' ' + assistant))))
+ return list(reversed(expected))
+
+
+def normalize(rows, root):
+ assert isinstance(rows, list), 'catalog sessions is not an array'
+ normalized = []
+ for row in rows:
+ assert isinstance(row, dict) and isinstance(row.get('path'), str), row
+ path = Path(row['path'])
+ assert path.parent == root / 'agent/sessions', 'row escaped owned fixture directory'
+ value = {field: row[field] for field in FIELDS}
+ value['path'] = path.name # Only the isolated per-binary root differs.
+ normalized.append(value)
+ ids = [row['id'] for row in normalized]
+ assert len(set(ids)) == len(ids), 'duplicate catalog rows'
+ return normalized
+
+
+def same_rows(actual, expected):
+ assert sorted(actual, key=lambda row: row['id']) == sorted(
+ expected, key=lambda row: row['id']), 'catalog stable fields differ (including allMessagesText)'
+
+
+def ts_ignores_paging(call):
+ assert set(call['final_data']) == {'sessions'}, 'TS paging shape changed; inspect before updating expectation'
+
+
+class RawReader:
+ def __init__(self, reader, received):
+ self.reader, self.received = reader, received
+
+ def readline(self):
+ line = self.reader.readline()
+ self.received.append(line.hex())
+ return line
+
+ def close(self):
+ self.reader.close()
+
+
+class RawSocket:
+ def __init__(self, sock, sent):
+ self.sock, self.sent = sock, sent
+
+ def sendall(self, data):
+ self.sent.append(data.hex())
+ self.sock.sendall(data)
+
+ def close(self):
+ self.sock.close()
+
+
+class CatalogClient(Client):
+ def __init__(self, path, process):
+ super().__init__(path, process)
+ # Preserve exact bytes after the separately recorded actual daemon hello.
+ self.received, self.sent = [], []
+ self.reader = RawReader(self.reader, self.received)
+ self.sock = RawSocket(self.sock, self.sent)
+
+
+def query(client, observed, label, **paging):
+ call = observed['queries'][label] = {'paging': paging}
+ start, raw_start, sent_start = len(client.wire), len(client.received), len(client.sent)
+ try:
+ data = client.call('list_saved_sessions', cwd=CWD, scope='all', **paging)
+ call['final_data'] = data
+ return call
+ finally:
+ call['frames'] = client.wire[start:]
+ call['raw_received_hex'] = client.received[raw_start:]
+ call['raw_sent_hex'] = client.sent[sent_start:]
+
+
+def validate_query(call, root, expected, *, ordered=False, remaining=None, cursor=False):
+ data = call['final_data']
+ assert isinstance(data, dict), 'catalog final data is not an object'
+ rows = normalize(data.get('sessions'), root)
+ same_rows(rows, expected)
+ if ordered:
+ assert rows == expected, 'Rust catalog is not deterministic newest-first'
+ finals = [frame for frame in call['frames'] if frame.get('type') == 'response']
+ assert len(finals) == 1, 'missing/duplicate terminal response'
+ final = finals[0]
+ assert final.get('success') is True and final.get('command') == 'list_saved_sessions', final
+ assert final.get('data') == data and call['frames'][-1] == final, 'final is not the stream terminator'
+ assert call['raw_received_hex'] and call['raw_sent_hex'], 'missing raw traffic'
+ assert [json.loads(bytes.fromhex(line)) for line in call['raw_received_hex']] == call['frames'], 'raw/decoded receipt mismatch'
+ request, = [json.loads(bytes.fromhex(line)) for line in call['raw_sent_hex']]
+ assert request['id'] == final['id'], 'request/response ID mismatch'
+ assert request['command'] == {'type': 'list_saved_sessions', 'cwd': CWD,
+ 'scope': 'all', **call['paging']}, request
+ items = []
+ progress = []
+ for frame in call['frames'][:-1]:
+ assert frame.get('id') == final['id'] and frame.get('command') == 'list_saved_sessions', frame
+ if frame.get('type') == 'session_list_item':
+ items.append(frame['session'])
+ else:
+ assert frame.get('type') == 'session_list_progress', frame
+ assert 0 <= frame['loaded'] <= frame['total'], frame
+ progress.append(frame)
+ # Rust may drop progress/item frames under backpressure. Final rows are
+ # authoritative; streamed rows must be unique, correct members of that final.
+ streamed = normalize(items, root)
+ assert streamed and progress, 'no catalog stream observed'
+ by_id = {row['id']: row for row in rows}
+ assert all(by_id.get(row['id']) == row for row in streamed), 'stream/final disagreement'
+ if ordered:
+ streamed_ids = {row['id'] for row in streamed}
+ assert streamed == [row for row in rows if row['id'] in streamed_ids], 'Rust stream order differs from final'
+ if remaining is not None:
+ assert data.get('remaining') == remaining, 'incorrect remaining count'
+ if cursor:
+ assert isinstance(data.get('nextCursor'), str) and data['nextCursor'], 'missing continuation'
+ else:
+ assert data.get('nextCursor') is None, 'completed catalog still has a cursor'
+ return rows
+
+
+def observe(binary, kind, root, observed, ts_cursor=None):
+ env = env_for(root, kind)
+ env[TAG] = str(root)
+ (root / 'agent/settings.json').write_text(json.dumps({
+ 'prewarmPythonKernel': False, 'sessionArchiveMaxSessions': 'off',
+ 'sessionArchiveMaxAgeDays': 'off',
+ 'onboardingCompleted': True, 'telemetry': {'noticeShown': True}}))
+ expected = seed(root)
+ observed['fixture'] = {'count': COUNT, 'page_size': PAGE, 'mtime_base_ms': BASE_MS,
+ 'mtime_step_ms': 10000, 'session_archive_max_sessions': 'off',
+ 'session_archive_max_age_days': 'off',
+ 'expected_newest_first_ids': [row['id'] for row in expected],
+ 'old_search_target_id': expected[-1]['id'], 'name_search_target': TARGET,
+ 'assistant_wire_target': TRANSCRIPT_TARGET}
+ observed['queries'] = {}
+ path = root / 'd.sock'
+ scope = OwnedProcesses(binary, root, path)
+ daemon = client = None
+ with open(root / 'daemon.log', 'wb') as log:
+ try:
+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]
+ daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log,
+ stderr=subprocess.STDOUT, start_new_session=True)
+ scope.register(daemon, command)
+ client = CatalogClient(path, daemon)
+ observed['hello'] = client.hello
+ baseline = query(client, observed, 'unbounded')
+ observed['baseline_rows'] = validate_query(baseline, root, expected,
+ ordered=kind == 'rust', remaining=0 if kind == 'rust' else None)
+ if kind == 'ts':
+ ts_ignores_paging(baseline)
+ first = query(client, observed, 'limit_200', limit=PAGE)
+ if kind == 'rust':
+ validate_query(first, root, expected[:PAGE], ordered=True,
+ remaining=COUNT - PAGE, cursor=True)
+ cursor = first['final_data']['nextCursor']
+ observed['continuation_cursor'] = cursor
+ else:
+ # Historical TS has no paging semantics. Unexpected acceptance is
+ # RED, not silently reclassified as intentional parity.
+ validate_query(first, root, expected)
+ ts_ignores_paging(first)
+ cursor = ts_cursor
+ assert isinstance(cursor, str) and cursor, 'actual Rust cursor unavailable'
+ observed['optional_paging_behavior'] = 'limit and cursor ignored; complete catalog returned'
+ rest = query(client, observed, 'continuation', cursor=cursor)
+ validate_query(rest, root, expected[PAGE:] if kind == 'rust' else expected,
+ ordered=kind == 'rust', remaining=0 if kind == 'rust' else None)
+ if kind == 'rust':
+ joined = normalize(first['final_data']['sessions'] + rest['final_data']['sessions'], root)
+ assert joined == expected, 'pages did not cover full catalog exactly once'
+ assert TARGET not in json.dumps(first['final_data']['sessions'])
+ assert rest['final_data']['sessions'][-1]['name'] == TARGET
+ assert TRANSCRIPT_TARGET in rest['final_data']['sessions'][-1]['allMessagesText']
+ else:
+ ts_ignores_paging(rest)
+ boundary = expected[PAGE - 1]
+ boundary_path = root / 'agent/sessions' / boundary['path']
+ boundary_path.unlink()
+ observed['deleted_cursor_file'] = boundary['path']
+ after = query(client, observed, 'continuation_after_cursor_delete', cursor=cursor)
+ validate_query(after, root, expected[PAGE:] if kind == 'rust' else [
+ row for row in expected if row['id'] != boundary['id']],
+ ordered=kind == 'rust', remaining=0 if kind == 'rust' else None)
+ if kind == 'ts':
+ ts_ignores_paging(after)
+ for rows in (observed['baseline_rows'], after['final_data']['sessions']):
+ target, = [row for row in rows if row['id'] == expected[-1]['id']]
+ assert target['name'] == TARGET
+ assert TRANSCRIPT_TARGET in target['allMessagesText']
+ scope.discover()
+ assert set(scope.targets) == set(scope.direct), 'catalog unexpectedly spawned a worker/kernel'
+ observed['behavior_verified'] = True
+ finally:
+ observed['wire'] = list(client.wire) if client else []
+ observed['raw_received_hex'] = list(client.received) if client else []
+ observed['raw_sent_hex'] = list(client.sent) if client else []
+ finish(scope, client, daemon, observed)
+ log.flush()
+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-10000:]
+ assert observed['cleanup_verified'], observed
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--receipt', required=True, type=Path)
+ args = parser.parse_args()
+ receipt = {'verified': False, 'scope': __doc__, 'runs': {},
+ 'normalization': 'owned path basename only; baseline order compared as an ID-keyed set',
+ 'intentional_difference': 'Rust limit/cursor pages newest-mtime-first; historical TS ignores both optional fields',
+ 'not_verified': ['TUI frames or keyboard/search interactions', 'paint latency',
+ 'large-transcript timing', 'provider/kernel execution', 'concurrent catalog mutations']}
+ try:
+ assert sys.platform == 'linux', 'hosted Linux only'
+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive digest mismatch'
+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256
+ with tempfile.TemporaryDirectory(prefix='pa-catalog-', dir='/tmp') as folder:
+ for kind in ('rust', 'ts'):
+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()
+ observed = receipt['runs'][kind] = {'binary_sha256': digest(binary)}
+ try:
+ observe(binary, kind, Path(folder) / kind, observed,
+ receipt['runs'].get('rust', {}).get('continuation_cursor'))
+ except Exception as error:
+ observed['error'] = str(error)
+ assert all(run.get('behavior_verified') and run.get('cleanup_verified')
+ and 'error' not in run for run in receipt['runs'].values()), 'actual catalog comparison failed'
+ same_rows(receipt['runs']['ts']['baseline_rows'], receipt['runs']['rust']['baseline_rows'])
+ receipt['verified'] = True
+ except Exception as error:
+ receipt['error'] = str(error)
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(receipt, ensure_ascii=False, indent=2))
+ print(json.dumps({'verified': receipt['verified'], 'error': receipt.get('error')}))
+ return 0 if receipt['verified'] else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/test_review_saved_catalog_parity.py b/scripts/test_review_saved_catalog_parity.py
new file mode 100644
index 0000000000..6ac688c640
--- /dev/null
+++ b/scripts/test_review_saved_catalog_parity.py
@@ -0,0 +1,159 @@
+import copy
+import json
+from pathlib import Path
+import tempfile
+import unittest
+
+from review_saved_catalog_parity import (COUNT, PAGE, TARGET, TRANSCRIPT_TARGET,
+ normalize, same_rows, seed, ts_ignores_paging, validate_query)
+
+
+class SavedCatalogGuards(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.root = Path(self.directory.name)
+ self.expected = seed(self.root)
+
+ def call(self, rows=None, remaining=0, cursor=None):
+ rows = copy.deepcopy(self.expected if rows is None else rows)
+ for row in rows:
+ row['path'] = str(self.root / 'agent/sessions' / row['path'])
+ data = {'sessions': rows, 'remaining': remaining}
+ if cursor is not None:
+ data['nextCursor'] = cursor
+ frames = [{'type': 'session_list_item', 'id': '1',
+ 'command': 'list_saved_sessions', 'session': row} for row in rows]
+ frames.append({'type': 'session_list_progress', 'id': '1',
+ 'command': 'list_saved_sessions', 'loaded': len(rows), 'total': len(rows)})
+ frames.append({'type': 'response', 'id': '1', 'success': True,
+ 'command': 'list_saved_sessions', 'data': data})
+ request = {'type': 'command', 'id': '1',
+ 'command': {'type': 'list_saved_sessions', 'cwd': '/tmp/catalog-paging-fixture',
+ 'scope': 'all'}}
+ return {'paging': {}, 'frames': frames, 'final_data': data,
+ 'raw_received_hex': [(json.dumps(frame) + '\n').encode().hex() for frame in frames],
+ 'raw_sent_hex': [(json.dumps(request) + '\n').encode().hex()]}
+
+ def refresh_raw(self, call):
+ call['raw_received_hex'] = [(json.dumps(frame) + '\n').encode().hex()
+ for frame in call['frames']]
+
+ def check(self, call, rows=None, **kwargs):
+ return validate_query(call, self.root, self.expected if rows is None else rows,
+ ordered=True, remaining=0, **kwargs)
+
+ def test_fixture_is_valid_ordered_and_old_target_is_beyond_first_page(self):
+ files = sorted((self.root / 'agent/sessions').glob('*.jsonl'))
+ self.assertGreater(len(files), PAGE)
+ self.assertEqual(len(files), COUNT)
+ mtimes = [path.stat().st_mtime_ns for path in files]
+ self.assertEqual(len(set(mtimes)), COUNT)
+ self.assertEqual(mtimes, sorted(mtimes))
+ for path in files:
+ entries = [json.loads(line) for line in path.read_text().splitlines()]
+ self.assertEqual(entries[0]['type'], 'session')
+ self.assertEqual(entries[0]['id'], path.stem)
+ self.assertEqual(entries[-1]['message']['role'], 'assistant')
+ self.assertNotIn(TARGET, json.dumps(self.expected[:PAGE]))
+ self.assertEqual(self.expected[-1]['name'], TARGET)
+ self.assertIn(TRANSCRIPT_TARGET, self.expected[-1]['allMessagesText'])
+ self.assertNotIn(TRANSCRIPT_TARGET, self.expected[-1]['firstMessage'])
+ self.assertEqual(self.check(self.call()), self.expected)
+
+ def test_rejects_missing_duplicate_wrong_or_transcript_truncated_rows(self):
+ for mutate in (
+ lambda rows: rows.pop(),
+ lambda rows: rows.append(copy.deepcopy(rows[0])),
+ lambda rows: rows[0].update(name='wrong'),
+ lambda rows: rows[-1].update(allMessagesText=rows[-1]['firstMessage']),
+ ):
+ call = self.call()
+ mutate(call['final_data']['sessions'])
+ self.refresh_raw(call)
+ with self.assertRaises(AssertionError):
+ self.check(call)
+ escaped = self.call()
+ escaped['final_data']['sessions'][0]['path'] = '/ambient/session.jsonl'
+ with self.assertRaises(AssertionError):
+ self.check(escaped)
+
+ def test_pages_cover_full_catalog_once_and_wrong_boundary_is_rejected(self):
+ first = self.call(self.expected[:PAGE], COUNT - PAGE, 'boundary')
+ validate_query(first, self.root, self.expected[:PAGE], ordered=True,
+ remaining=COUNT - PAGE, cursor=True)
+ rest = self.call(self.expected[PAGE:])
+ self.check(rest, self.expected[PAGE:])
+ joined = normalize(first['final_data']['sessions'] + rest['final_data']['sessions'], self.root)
+ self.assertEqual(joined, self.expected)
+ for key, value in (('remaining', 0), ('nextCursor', '')):
+ broken = copy.deepcopy(first)
+ broken['final_data'][key] = value
+ self.refresh_raw(broken)
+ with self.assertRaises(AssertionError):
+ validate_query(broken, self.root, self.expected[:PAGE], ordered=True,
+ remaining=COUNT - PAGE, cursor=True)
+ with self.assertRaises(AssertionError):
+ self.check(self.call(self.expected[PAGE - 1:]), self.expected[PAGE:])
+ with self.assertRaises(AssertionError):
+ self.check(self.call(self.expected[PAGE:], cursor='not-finished'), self.expected[PAGE:])
+
+ def test_deleted_cursor_boundary_still_requires_the_complete_older_tail(self):
+ boundary = self.root / 'agent/sessions' / self.expected[PAGE - 1]['path']
+ boundary.unlink()
+ self.assertFalse(boundary.exists())
+ tail = self.expected[PAGE:]
+ self.assertEqual(self.check(self.call(tail), tail), tail)
+ self.assertEqual(tail[-1]['name'], TARGET)
+ with self.assertRaises(AssertionError):
+ self.check(self.call(tail[1:]), tail)
+
+ def test_raw_terminal_and_stream_disagreement_fail_closed(self):
+ for mode in ('missing_raw', 'bad_raw', 'wrong_request', 'wrong_stream',
+ 'duplicate_stream', 'wrong_order', 'no_stream', 'after_final'):
+ call = self.call()
+ if mode == 'missing_raw':
+ call['raw_received_hex'] = []
+ elif mode == 'bad_raw':
+ call['raw_received_hex'][0] = b'{}\n'.hex()
+ elif mode == 'wrong_request':
+ call['raw_sent_hex'] = [b'{"id":"elsewhere","command":{}}\n'.hex()]
+ elif mode == 'wrong_stream':
+ call['frames'][0] = copy.deepcopy(call['frames'][0])
+ call['frames'][0]['session']['allMessagesText'] = 'lost transcript'
+ elif mode == 'duplicate_stream':
+ call['frames'].insert(0, copy.deepcopy(call['frames'][0]))
+ elif mode == 'wrong_order':
+ call['frames'][0], call['frames'][1] = call['frames'][1], call['frames'][0]
+ elif mode == 'no_stream':
+ call['frames'] = call['frames'][-2:]
+ else:
+ call['frames'].append(copy.deepcopy(call['frames'][0]))
+ if mode not in ('missing_raw', 'bad_raw', 'wrong_request'):
+ self.refresh_raw(call)
+ with self.subTest(mode=mode), self.assertRaises(AssertionError):
+ self.check(call)
+ # Dropped streamed items are legal under real Rust backpressure.
+ call = self.call()
+ del call['frames'][1:PAGE]
+ self.refresh_raw(call)
+ self.check(call)
+
+ def test_ts_baseline_order_is_not_misrepresented_as_paging_parity(self):
+ call = self.call(list(reversed(self.expected)))
+ del call['final_data']['remaining']
+ self.refresh_raw(call)
+ rows = validate_query(call, self.root, self.expected)
+ same_rows(rows, self.expected)
+ ts_ignores_paging(call)
+ for extra in ({'remaining': 0}, {'nextCursor': 'new-ts-cursor'}):
+ broken = copy.deepcopy(call)
+ broken['final_data'].update(extra)
+ with self.assertRaises(AssertionError):
+ ts_ignores_paging(broken)
+ with self.assertRaises(AssertionError):
+ validate_query(self.call(self.expected[:PAGE]), self.root, self.expected)
+
+
+if __name__ == '__main__':
+ unittest.main()