Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces): open picked-up agent chats from the end of their file, never read them whole (CUA-3548) (#6577)
Francesco Bonaccid152839d0099
diff --git a/apps/cua-spaces-web/src/__tests__/pick-up.test.tsx b/apps/cua-spaces-web/src/__tests__/pick-up.test.tsxindex d3f3c66c9b..65751b26c7 100644--- a/apps/cua-spaces-web/src/__tests__/pick-up.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/pick-up.test.tsx@@ -133,7 +133,7 @@ describe.skipIf(!wasmBuilt)("a continued chat in Home", () => {await waitFor(() => expect(q("[data-imported-chat]")).not.toBeNull());// The earlier messages are read from the agent's own store when the task opens (the timeline is// virtualized, so jsdom draws none of its rows; the resume context below carries them).- await waitFor(() => expect(calls.find((c) => c.op === "agents.threadHistory")?.args).toEqual({ agent: "claude-code", id: KETTLE.id }));+ await waitFor(() => expect(calls.find((c) => c.op === "agents.threadHistory")?.args).toEqual({ agent: "claude-code", id: KETTLE.id, limit: 30 }));expect(q("[data-earlier-heading]")?.textContent).toContain("Earlier on this Mac");expect(q("[data-continue-on]")?.textContent).toContain("This Mac");expect(q("[data-imported-note]")?.textContent).toContain("Nothing runs until you send");@@ -150,3 +150,24 @@ describe.skipIf(!wasmBuilt)("a continued chat in Home", () => {await waitFor(() => expect(askTask(task.id)?.runId).toBeTruthy());});});++describe.skipIf(!wasmBuilt)("a long chat in Home", () => {+ it("opens on its newest messages and reads more only when asked", { timeout: 30000 }, async () => {+ const task = addImportedTask(KETTLE);+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ await mountApp(`/home/${task.id}`, {+ failsCreates: false,+ listsGhost: false,+ demo: { onboarded: true },+ intercept: (op, args) => {+ calls.push({ op, args: args as Record<string, unknown> });+ return undefined;+ },+ answer: (op, out) => (op === "agents.threadHistory" ? { ...(out as object), earlierOmitted: 1 } : out),+ });+ await waitFor(() => expect(q("[data-earlier-more]")).not.toBeNull());+ expect(calls.filter((c) => c.op === "agents.threadHistory").map((c) => c.args.limit)).toEqual([30]);+ fireEvent.click(q("[data-earlier-more]")!);+ await waitFor(() => expect(calls.filter((c) => c.op === "agents.threadHistory").map((c) => c.args.limit)).toEqual([30, 130]));+ });+});diff --git a/apps/cua-spaces-web/src/components/ask-first/imported-task.tsx b/apps/cua-spaces-web/src/components/ask-first/imported-task.tsxindex c22a16ea2a..8199b8ad8e 100644--- a/apps/cua-spaces-web/src/components/ask-first/imported-task.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/imported-task.tsx@@ -39,6 +39,11 @@ export function earlierItems(history: PastThread | null): TranscriptItem[] {* own session on this Mac, in the chat's folder, and the run's turns follow* the earlier ones. The chat stays private: nothing goes to a Space thread.*/+/** The newest messages a chat opens with: a long chat is never read or drawn whole. */+export const FIRST_VIEW_MESSAGES = 30;+/** Each "Show earlier messages" adds this many. */+export const MORE_MESSAGES = 100;+export function ImportedTaskView({ task }: { task: AskTask & { imported: NonNullable<AskTask["imported"]> } }) {const { data } = useBridge();const { startRun, sendMessage } = useAgents();@@ -46,16 +51,21 @@ export function ImportedTaskView({ task }: { task: AskTask & { imported: NonNullconst name = agentName(task.agent);const [history, setHistory] = useState<PastThread | null>(null);const [historyError, setHistoryError] = useState<string | null>(null);+ // Only the newest messages are read at first (the host reads the end of the chat's file, never all+ // of it); Show earlier messages asks for more. The page never waits on more than it shows.+ const [limit, setLimit] = useState(FIRST_VIEW_MESSAGES);+ const [loadingMore, setLoadingMore] = useState(false);useEffect(() => {let live = true;data- ?.call("agents.threadHistory", { agent: task.agent as ThreadAgent, id: chat.sessionId })+ ?.call("agents.threadHistory", { agent: task.agent as ThreadAgent, id: chat.sessionId, limit }).then((h) => live && setHistory(h))- .catch((e: unknown) => live && setHistoryError(e instanceof Error ? e.message : String(e)));+ .catch((e: unknown) => live && setHistoryError(e instanceof Error ? e.message : String(e)))+ .finally(() => live && setLoadingMore(false));return () => {live = false;};- }, [data, task.agent, chat.sessionId]);+ }, [data, task.agent, chat.sessionId, limit]);const ref = task.runId && task.spaceId ? { spaceId: task.spaceId, runId: task.runId } : null;const live = useAgentTimeline(ref);@@ -116,7 +126,21 @@ export function ImportedTaskView({ task }: { task: AskTask & { imported: NonNull<div className="flex min-h-0 flex-1 flex-col"><p className="mx-auto w-full max-w-[720px] shrink-0 px-8 pt-6 text-[12px] font-medium text-muted-foreground" data-earlier-heading="">Earlier on {thisComputerText()}- {history?.earlierOmitted ? ` (${history.earlierOmitted} older messages aren't shown)` : ""}+ {history?.earlierOmitted ? " (older messages aren't shown)" : ""}+ {history?.earlierOmitted ? (+ <button+ type="button"+ disabled={loadingMore}+ onClick={() => {+ setLoadingMore(true);+ setLimit((n) => n + MORE_MESSAGES);+ }}+ className="ml-2 underline underline-offset-2 hover:text-foreground disabled:opacity-60"+ data-earlier-more=""+ >+ {loadingMore ? "Loading…" : "Show earlier messages"}+ </button>+ ) : null}</p>{loading ? (<div className="flex flex-1 items-center justify-center text-muted-foreground">diff --git a/libs/cua/crates/cua-agent-threads/examples/measure.rs b/libs/cua/crates/cua-agent-threads/examples/measure.rsnew file mode 100644index 0000000000..bfaa708709--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/examples/measure.rs@@ -0,0 +1,91 @@+//! Times `recent` and `history` on a synthetic, realistic history:+//! `cargo run --release -p cua-agent-threads --example measure -- <dir>`+//! writes (once) 300 Claude Code chats (6 of them 150 MB of tool output) and+//! 60 Codex rollouts under `<dir>`, then times the lister and the reader.+use cua_agent_threads::*;+use std::io::Write;+use std::path::Path;+use std::time::Instant;++fn claude_chat(path: &Path, id: &str, turns: usize, blob: usize) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ let mut f = std::io::BufWriter::new(std::fs::File::create(path).unwrap());+ let pad = "x".repeat(blob);+ for n in 0..turns {+ let ts = format!("2026-11-04T10:{:02}:{:02}.000Z", (n / 60) % 60, n % 60);+ writeln!(f, r#"{{"type":"user","uuid":"u{n}","cwd":"/Users/sam/code/kettle","timestamp":"{ts}","message":{{"role":"user","content":"question {n} about the kettle"}}}}"#).unwrap();+ writeln!(f, r#"{{"type":"user","uuid":"t{n}","timestamp":"{ts}","message":{{"role":"user","content":[{{"type":"tool_result","content":"{pad}"}}]}}}}"#).unwrap();+ writeln!(f, r#"{{"type":"assistant","uuid":"a{n}","timestamp":"{ts}","message":{{"role":"assistant","content":[{{"type":"text","text":"answer {n} for {id}"}}]}}}}"#).unwrap();+ }+}++fn make(dir: &Path) {+ for i in 0..300 {+ let id = format!("00000000-0000-4000-8000-{i:012}");+ let big = i % 50 == 0;+ // 6 chats of about 150 MB; the rest 20 KB to 2 MB.+ let (turns, blob) = if big {+ (1500, 100_000)+ } else {+ (20 + (i % 7) * 10, 1_000 + (i % 13) * 1_000)+ };+ claude_chat(+ &dir.join(format!(+ ".claude/projects/-Users-sam-p{}/{id}.jsonl",+ i % 20+ )),+ &id,+ turns,+ blob,+ );+ }+}++fn main() {+ let dir = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture dir"));+ if !dir.join(".claude").exists() {+ make(&dir);+ }+ let roots = Roots::under_home(&dir);+ for limit in [4usize, 50] {+ let t = Instant::now();+ let r = recent(+ &roots,+ &ListOptions {+ agents: Agent::ALL.to_vec(),+ limit,+ },+ );+ println!(+ "recent limit={limit}: {} chats in {:?}",+ r.len(),+ t.elapsed()+ );+ }+ let mut files: Vec<_> = walk(&dir.join(".claude/projects"));+ files.sort_by_key(|f| std::cmp::Reverse(std::fs::metadata(f).unwrap().len()));+ for f in files.iter().take(2).chain(files.iter().rev().take(1)) {+ let id = f.file_stem().unwrap().to_str().unwrap();+ let t = Instant::now();+ let h = history(&roots, Agent::ClaudeCode, id, None).unwrap();+ println!(+ "history {} MB chat: {} messages ({} older) in {:?}",+ std::fs::metadata(f).unwrap().len() / 1_000_000,+ h.messages.len(),+ h.earlier_omitted,+ t.elapsed()+ );+ }+}++fn walk(d: &Path) -> Vec<std::path::PathBuf> {+ let mut out = vec![];+ for e in std::fs::read_dir(d).unwrap().flatten() {+ if e.path().is_dir() {+ out.extend(walk(&e.path()));+ } else {+ out.push(e.path());+ }+ }+ out+}diff --git a/libs/cua/crates/cua-agent-threads/src/claude.rs b/libs/cua/crates/cua-agent-threads/src/claude.rsindex 3ca5fed911..c5ff4b36f8 100644--- a/libs/cua/crates/cua-agent-threads/src/claude.rs+++ b/libs/cua/crates/cua-agent-threads/src/claude.rs@@ -164,7 +164,14 @@ fn message(v: &Value) -> Option<Message> {})}-pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vec<Message>)>> {+/// A chat's newest messages: the file is read from its end, within+/// [`lines::HISTORY_BUDGET`], until `cap` messages are in hand, so a chat of+/// any size opens at once. `more` is whether older ones were left unread.+pub(crate) fn history(+ root: &Path,+ id: &str,+ cap: usize,+) -> Result<Option<(ThreadSummary, Vec<Message>, bool)>> {let Some(path) = find(root, id) else {return Ok(None);};@@ -173,19 +180,21 @@ pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vereturn Ok(None);};let mut out = vec![];- lines::each(&path, |v| {+ let whole = lines::rev_each(&path, lines::HISTORY_BUDGET, |v| {if let Some(mut m) = message(&v) {if m.key.is_empty() {- m.key = format!("line-{}", out.len());+ m.key = format!("rev-{}", out.len());}out.push(m);}+ out.len() < cap}).map_err(|source| crate::Error::Io {path: path.display().to_string(),source,})?;- Ok(Some((thread, out)))+ out.reverse();+ Ok(Some((thread, out, !whole)))}fn find(root: &Path, id: &str) -> Option<PathBuf> {diff --git a/libs/cua/crates/cua-agent-threads/src/codex.rs b/libs/cua/crates/cua-agent-threads/src/codex.rsindex 92ed5f65dd..13c7deaa04 100644--- a/libs/cua/crates/cua-agent-threads/src/codex.rs+++ b/libs/cua/crates/cua-agent-threads/src/codex.rs@@ -199,7 +199,13 @@ fn build(v: &Value, p: &Value, role: Role, text: String) -> Option<Message> {})}-pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vec<Message>)>> {+/// A chat's newest messages, read from the end of the file within+/// [`lines::HISTORY_BUDGET`]; see [`crate::claude::history`].+pub(crate) fn history(+ root: &Path,+ id: &str,+ cap: usize,+) -> Result<Option<(ThreadSummary, Vec<Message>, bool)>> {let Some(path) = find(root, id) else {return Ok(None);};@@ -211,12 +217,13 @@ pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vereturn Ok(None);}let (mut items, mut events) = (vec![], vec![]);- lines::each(&path, |v| {+ let whole = lines::rev_each(&path, lines::HISTORY_BUDGET, |v| {if let Some(m) = message(&v) {items.push(m);} else if let Some(m) = event_message(&v) {events.push(m);}+ items.len() < cap && events.len() < cap}).map_err(|source| crate::Error::Io {path: path.display().to_string(),@@ -224,12 +231,13 @@ pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Ve})?;// Newer rollouts write each message both ways: the response items win.let mut out = if items.is_empty() { events } else { items };+ out.reverse();for (i, m) in out.iter_mut().enumerate() {if m.key.is_empty() {m.key = format!("item-{i}");}}- Ok(Some((thread, out)))+ Ok(Some((thread, out, !whole)))}/// The rollout whose name ends in `-<id>.jsonl`.diff --git a/libs/cua/crates/cua-agent-threads/src/hermes.rs b/libs/cua/crates/cua-agent-threads/src/hermes.rsindex 2b9aa2226f..08eb519592 100644--- a/libs/cua/crates/cua-agent-threads/src/hermes.rs+++ b/libs/cua/crates/cua-agent-threads/src/hermes.rs@@ -166,7 +166,11 @@ pub(crate) fn recent(root: &Path, limit: usize) -> Vec<ThreadSummary> {.collect()}-pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vec<Message>)>> {+pub(crate) fn history(+ root: &Path,+ id: &str,+ cap: usize,+) -> Result<Option<(ThreadSummary, Vec<Message>, bool)>> {let Some(c) = open(root) else { return Ok(None) };let Some(row) = rows(&c, " AND id = ?2", 1, Some(id)).into_iter().next() else {return Ok(None);@@ -181,12 +185,12 @@ pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Ve};let sql = format!("SELECT id, role, content, timestamp FROM messages \- WHERE session_id = ?1 AND role IN ('user', 'assistant'){active} ORDER BY id"+ WHERE session_id = ?1 AND role IN ('user', 'assistant'){active} ORDER BY id DESC LIMIT ?2");let sqlite = |e: rusqlite::Error| Error::Sqlite(e.to_string());let mut s = c.prepare(&sql).map_err(sqlite)?;let messages = s- .query_map(params![id], |r| {+ .query_map(params![id, cap as i64 + 1], |r| {Ok((r.get::<_, i64>(0)?,r.get::<_, String>(1)?,@@ -214,6 +218,10 @@ pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vecut: false,})})- .collect();- Ok(Some((thread, messages)))+ .collect::<Vec<_>>();+ let more = messages.len() > cap;+ let mut messages = messages;+ messages.truncate(cap);+ messages.reverse();+ Ok(Some((thread, messages, more)))}diff --git a/libs/cua/crates/cua-agent-threads/src/lib.rs b/libs/cua/crates/cua-agent-threads/src/lib.rsindex 0a36b3d37f..acacd554b5 100644--- a/libs/cua/crates/cua-agent-threads/src/lib.rs+++ b/libs/cua/crates/cua-agent-threads/src/lib.rs@@ -10,8 +10,10 @@//! Nothing here writes, caches or sends anything. Each agent's store stays//! the source of truth, and every format is read defensively: a record,//! column or line this crate does not know is skipped, a file it cannot read-//! is left out, and large files are read from their head and tail only when-//! listing.+//! is left out. Large files are read from their head and tail only when+//! listing, and a chat's messages are read from the end of its file, within a+//! byte and time budget, so a chat of any size opens at once (older messages+//! are left unread: `earlier_omitted` is then at least 1).use std::path::{Path, PathBuf};@@ -261,15 +263,19 @@ pub fn history(};let root = roots.root(agent).ok_or_else(not_found)?;let max = max_messages.unwrap_or(HISTORY_DEFAULT).clamp(1, 5000);- let (thread, messages) = match agent {- Agent::ClaudeCode => claude::history(root, id)?,- Agent::Codex => codex::history(root, id)?,- Agent::Hermes => hermes::history(root, id)?,+ // Agent replies in a row are merged into one afterwards, so more than+ // `max` are read; only the newest part of a chat is ever read.+ let cap = max.saturating_mul(4).saturating_add(64);+ let (thread, messages, unread) = match agent {+ Agent::ClaudeCode => claude::history(root, id, cap)?,+ Agent::Codex => codex::history(root, id, cap)?,+ Agent::Hermes => hermes::history(root, id, cap)?,}.ok_or_else(not_found)?;let mut messages = text::merge_agent_runs(messages);- let earlier_omitted = messages.len().saturating_sub(max);- messages.drain(..earlier_omitted);+ // A lower bound when older messages were left unread: at least one more.+ let earlier_omitted = messages.len().saturating_sub(max).max(usize::from(unread));+ messages.drain(..messages.len().saturating_sub(max));for m in &mut messages {let (t, cut) = text::cut_bytes(&m.text, MESSAGE_MAX_BYTES);m.cut |= cut;@@ -344,4 +350,36 @@ mod tests {vec!["codex".to_string(), "resume".into(), "x".into()]);}++ /// A chat of hundreds of megabytes opens by reading the end of its file+ /// (CUA-3548: the whole file was read and every message kept).+ #[test]+ fn a_huge_chat_is_read_from_its_end_only() {+ use std::io::Write;+ let home = tempfile::tempdir().unwrap();+ let id = "0b1e5c2a-1111-4222-8333-944445555666";+ let path = home+ .path()+ .join(format!(".claude/projects/-Users-sam-kettle/{id}.jsonl"));+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ let mut f = std::io::BufWriter::new(std::fs::File::create(&path).unwrap());+ let pad = "x".repeat(200_000);+ for n in 0..400 {+ writeln!(f, r#"{{"type":"user","uuid":"u{n}","cwd":"/k","timestamp":"2026-11-04T10:00:00Z","message":{{"role":"user","content":"q{n}"}}}}"#).unwrap();+ writeln!(f, r#"{{"type":"user","uuid":"t{n}","message":{{"role":"user","content":[{{"type":"tool_result","content":"{pad}"}}]}}}}"#).unwrap();+ writeln!(f, r#"{{"type":"assistant","uuid":"a{n}","message":{{"role":"assistant","content":[{{"type":"text","text":"a{n}"}}]}}}}"#).unwrap();+ }+ drop(f);+ assert!(std::fs::metadata(&path).unwrap().len() > 70 * 1024 * 1024);+ let roots = Roots::under_home(home.path());+ lines::REV_BYTES_READ.with(|c| c.set(0));+ let h = history(&roots, Agent::ClaudeCode, id, Some(30)).unwrap();+ assert_eq!(h.messages.len(), 30);+ assert_eq!(h.messages.last().unwrap().text, "a399");+ assert!(h.earlier_omitted > 0);+ // The listing's head and tail edges are on top of this; the reader itself stays in its budget.+ assert!(+ lines::REV_BYTES_READ.with(|c| c.get()) <= lines::HISTORY_BUDGET.bytes + 512 * 1024+ );+ }}diff --git a/libs/cua/crates/cua-agent-threads/src/lines.rs b/libs/cua/crates/cua-agent-threads/src/lines.rsindex be5b1c71ed..5ada207039 100644--- a/libs/cua/crates/cua-agent-threads/src/lines.rs+++ b/libs/cua/crates/cua-agent-threads/src/lines.rs@@ -96,6 +96,96 @@ pub(crate) fn each(path: &Path, mut f: impl FnMut(Value)) -> std::io::Result<()>}}+/// What a history read may spend on one chat's file: it looks at the newest+/// part of the file only, however big the file is (a chat can run to+/// hundreds of megabytes of tool output).+#[derive(Clone, Copy, Debug)]+pub(crate) struct Budget {+ /// Bytes read from the end of the file.+ pub bytes: u64,+ /// Wall-clock time.+ pub time: std::time::Duration,+}++/// The default: 16 MiB (thousands of messages) within 2 seconds.+pub(crate) const HISTORY_BUDGET: Budget = Budget {+ bytes: 16 * 1024 * 1024,+ time: std::time::Duration::from_secs(2),+};++/// Bytes read per step from the end of a file.+const REV_CHUNK: usize = 256 * 1024;++#[cfg(test)]+thread_local! {+ /// Bytes [`rev_each`] read on this thread (tests assert a bound).+ pub(crate) static REV_BYTES_READ: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };+}++/// Calls `f` with the JSON object lines of `path`, newest (last) first,+/// until `f` returns `false`, the file start is reached, or `budget` is+/// spent. Lines over [`LINE_MAX`] and lines that are not JSON objects are+/// skipped; a line cut by the budget is dropped. Returns whether the start+/// of the file was reached (nothing older is left unread).+pub(crate) fn rev_each(+ path: &Path,+ budget: Budget,+ mut f: impl FnMut(Value) -> bool,+) -> std::io::Result<bool> {+ let mut file = File::open(path)?;+ let mut pos = file.metadata()?.len();+ let started = std::time::Instant::now();+ let mut spent = 0u64;+ // The bytes of the line that starts before the bytes read so far.+ let mut carry: Vec<u8> = vec![];+ // Inside a line too long to keep, looking for its start.+ let mut skipping = false;+ while pos > 0 {+ if spent >= budget.bytes || started.elapsed() >= budget.time {+ return Ok(false);+ }+ let n = (pos as usize).min(REV_CHUNK);+ pos -= n as u64;+ let mut chunk = vec![0u8; n];+ file.seek(SeekFrom::Start(pos))?;+ file.read_exact(&mut chunk)?;+ spent += n as u64;+ #[cfg(test)]+ REV_BYTES_READ.with(|c| c.set(c.get() + n as u64));+ if skipping {+ match chunk.iter().rposition(|b| *b == b'\n') {+ Some(i) => {+ chunk.truncate(i);+ skipping = false;+ }+ None => continue,+ }+ }+ chunk.extend_from_slice(&carry);+ carry.clear();+ let mut parts = chunk.split(|b| *b == b'\n');+ // Before the file start, the first piece may begin in an earlier chunk.+ let first = if pos > 0 { parts.next() } else { None };+ let complete: Vec<&[u8]> = parts.collect();+ for line in complete.into_iter().rev() {+ if line.len() <= LINE_MAX+ && let Some(v) = object(line)+ && !f(v)+ {+ return Ok(false);+ }+ }+ if let Some(first) = first {+ if first.len() > LINE_MAX {+ skipping = true;+ } else {+ carry = first.to_vec();+ }+ }+ }+ Ok(true)+}+/// `v[a][b]...` as a string.pub(crate) fn str_at<'a>(v: &'a Value, path: &[&str]) -> Option<&'a str> {let mut cur = v;@@ -147,4 +237,86 @@ mod tests {assert_eq!(seen.len(), 2);assert_eq!(seen[1]["n"], 3);}++ fn numbered(path: &Path, n: usize, pad: usize) {+ let mut f = std::io::BufWriter::new(File::create(path).unwrap());+ let pad = "x".repeat(pad);+ for i in 0..n {+ writeln!(f, "{{\"n\":{i},\"pad\":\"{pad}\"}}").unwrap();+ }+ }++ #[test]+ fn rev_each_goes_newest_first_across_chunk_edges() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("c.jsonl");+ // Lines of 100 KB straddle the 256 KB chunks.+ numbered(&p, 40, 100_000);+ let mut seen = vec![];+ let whole = rev_each(&p, HISTORY_BUDGET, |v| {+ seen.push(v["n"].as_u64().unwrap());+ true+ })+ .unwrap();+ assert!(whole);+ assert_eq!(seen, (0..40).rev().collect::<Vec<_>>());+ }++ #[test]+ fn rev_each_stops_when_asked_and_reads_only_the_end() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("d.jsonl");+ numbered(&p, 400, 100_000); // about 40 MB+ REV_BYTES_READ.with(|c| c.set(0));+ let mut seen = vec![];+ let whole = rev_each(&p, HISTORY_BUDGET, |v| {+ seen.push(v["n"].as_u64().unwrap());+ seen.len() < 3+ })+ .unwrap();+ assert!(!whole);+ assert_eq!(seen, vec![399, 398, 397]);+ // Three lines of 100 KB: a few chunks of 256 KB, not the 40 MB file.+ assert!(REV_BYTES_READ.with(|c| c.get()) <= 2 * 1024 * 1024);+ }++ #[test]+ fn rev_each_spends_no_more_than_its_budget() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("e.jsonl");+ numbered(&p, 400, 100_000);+ REV_BYTES_READ.with(|c| c.set(0));+ let budget = Budget {+ bytes: 1024 * 1024,+ time: std::time::Duration::from_secs(30),+ };+ let mut n = 0;+ let whole = rev_each(&p, budget, |_| {+ n += 1;+ true+ })+ .unwrap();+ assert!(!whole);+ assert!((5..20).contains(&n), "{n}");+ assert!(REV_BYTES_READ.with(|c| c.get()) <= budget.bytes + REV_CHUNK as u64);+ }++ #[test]+ fn rev_each_skips_a_line_too_long() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("f.jsonl");+ let mut f = File::create(&p).unwrap();+ writeln!(f, "{{\"n\":1}}").unwrap();+ writeln!(f, "{{\"big\":\"{}\"}}", "y".repeat(LINE_MAX + 10)).unwrap();+ write!(f, "{{\"n\":3}}").unwrap();+ drop(f);+ let mut seen = vec![];+ let whole = rev_each(&p, HISTORY_BUDGET, |v| {+ seen.push(v["n"].as_u64().unwrap());+ true+ })+ .unwrap();+ assert!(whole);+ assert_eq!(seen, vec![3, 1]);+ }}diff --git a/libs/cua/crates/cua-agent-threads/tests/threads.rs b/libs/cua/crates/cua-agent-threads/tests/threads.rsindex 9f06b416b1..f64fcab6a0 100644--- a/libs/cua/crates/cua-agent-threads/tests/threads.rs+++ b/libs/cua/crates/cua-agent-threads/tests/threads.rs@@ -362,3 +362,59 @@ fn long_messages_are_cut() {assert!(t.messages[0].cut);assert!(t.messages[0].text.len() <= cua_agent_threads::MESSAGE_MAX_BYTES);}++/// A realistic history (hundreds of chats, a few of them huge) lists its newest+/// chats from their ends only (CUA-3548).+#[test]+fn listing_hundreds_of_chats_with_huge_files_stays_fast() {+ use std::io::Write;+ let home = tempfile::tempdir().unwrap();+ for i in 0..300 {+ let id = format!("00000000-0000-4000-8000-{i:012}");+ let path = home.path().join(format!(+ ".claude/projects/-Users-sam-p{}/{id}.jsonl",+ i % 20+ ));+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ let mut f = std::fs::File::create(&path).unwrap();+ let rec = |n: usize, text: &str| {+ format!(+ "{{\"type\":\"user\",\"uuid\":\"u{n}\",\"cwd\":\"/k\",\"timestamp\":\"2026-11-04T10:00:{:02}Z\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n",+ n % 60+ )+ };+ f.write_all(rec(0, &format!("chat {i}")).as_bytes())+ .unwrap();+ if i % 50 == 0 {+ // 300 MB of the middle that must never be read.+ f.set_len(300 * 1024 * 1024).unwrap();+ f.seek_end_and_write(rec(1, "last words").as_bytes());+ }+ }+ let t = std::time::Instant::now();+ let roots = Roots::under_home(home.path());+ let got = recent(+ &roots,+ &ListOptions {+ agents: Agent::ALL.to_vec(),+ limit: 50,+ },+ );+ assert_eq!(got.len(), 50);+ assert!(+ t.elapsed() < std::time::Duration::from_secs(5),+ "{:?}",+ t.elapsed()+ );+}++trait SeekEnd {+ fn seek_end_and_write(&mut self, bytes: &[u8]);+}+impl SeekEnd for std::fs::File {+ fn seek_end_and_write(&mut self, bytes: &[u8]) {+ use std::io::{Seek, SeekFrom, Write};+ self.seek(SeekFrom::End(0)).unwrap();+ self.write_all(bytes).unwrap();+ }+}