Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(transcripts): recover stale layout caches (#1599)
Lancdfbf714a59a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b05e6e022..c8fce3e16 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -79,6 +79,45 @@ jobs:- name: Testrun: cargo test -p host-core --locked+ rust-windows:+ name: Rust host-core Windows / transcript cache E2E+ runs-on: windows-latest+ timeout-minutes: 45+ steps:+ - uses: actions/checkout@v7++ - uses: pnpm/action-setup@v6++ - uses: actions/setup-node@v7+ with:+ node-version: 24+ cache: pnpm++ - uses: dtolnay/rust-toolchain@stable++ - uses: Swatinem/rust-cache@v2++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Check formatting+ run: cargo fmt --all -- --check++ - name: Clippy+ run: cargo clippy -p host-core --all-targets --locked++ - name: Test transcript module on Windows+ run: "cargo test -p host-core --locked transcripts::"++ - name: Build host-core+ run: cargo build -p host-core --locked++ - name: Build Host RPC helper dependency+ run: pnpm --filter @pi-desktop/shared build++ - name: Run transcript cache Host RPC E2E+ run: node scripts/e2e-transcript-cache.mjs+trusted-extensions-e2e:name: Trusted extensions Electron E2Eruns-on: ubuntu-latestdiff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rsindex ad98fce43..c45da1878 100644--- a/crates/host-core/src/plugin_sessions.rs+++ b/crates/host-core/src/plugin_sessions.rs@@ -443,7 +443,6 @@ fn write_and_index(source_label: Option<&str>,prepared: &PreparedImport,) -> Result<()> {- sessions::invalidate_transcript_layout(&prepared.session_id);transcripts::write_transcript(db.data_dir(),&prepared.session_id,@@ -677,7 +676,6 @@ pub fn import_batch(db: &Database, plugin_id: &str, params: &Value) -> Result<Valet mut written: Vec<String> = Vec::with_capacity(prepared.len());for item in &prepared {- sessions::invalidate_transcript_layout(&item.session_id);if let Err(error) = transcripts::write_transcript(db.data_dir(),&item.session_id,@@ -1209,7 +1207,6 @@ pub fn delete(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Vaif changed == 0 {return Err(not_found("session not found"));}- sessions::invalidate_transcript_layout(&session_id);transcripts::remove_session_files(db.data_dir(), &session_id);} else {db.conn().execute(diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 8e84bc07b..5ea64fea6 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -7,7 +7,6 @@ use uuid::Uuid;use crate::db::{ms_to_ts, now_ms, ts_to_ms, Database};use crate::notifications::{self, Notification};use std::collections::HashMap;-use std::sync::{Mutex, OnceLock};use crate::transcripts::{self, CompactionRecord, MessageRecord, RevisionRecord};@@ -1194,7 +1193,6 @@ pub fn restore_orphaned_session(db: &Database, session_id: &str) -> Result<bool>&records,&read.compactions,)?;- invalidate_transcript_layout(session_id);}let created_at = records.first()@@ -1471,43 +1469,13 @@ pub fn session_mode(db: &Database, id: &str) -> Result<Option<String>> {.map(|mode| normalize_mode(Some(&mode))))}-/// Process-wide cache of transcript layouts, keyed by session id.-///-/// The layout is derived data: it can always be rebuilt by scanning the file,-/// and `file_len` makes a stale entry detectable. Caching it turns a repeated-/// session open, and each older page, into a bounded seek-and-parse instead of-/// another full-history scan.-static TRANSCRIPT_LAYOUTS: OnceLock<Mutex<HashMap<String, transcripts::TranscriptLayout>>> =- OnceLock::new();--fn layout_cache() -> &'static Mutex<HashMap<String, transcripts::TranscriptLayout>> {- TRANSCRIPT_LAYOUTS.get_or_init(|| Mutex::new(HashMap::new()))-}--/// Return an up-to-date layout for one session, reusing the cached offsets and+/// Return an up-to-date layout for one session, reusing cached offsets and/// scanning only what was appended since.pub(crate) fn session_layout(db: &Database,session_id: &str,) -> Result<transcripts::TranscriptLayout> {- let cached = layout_cache()- .lock()- .ok()- .and_then(|guard| guard.get(session_id).cloned())- .unwrap_or_default();- let layout = transcripts::refresh_layout(db.data_dir(), session_id, cached)?;- if let Ok(mut guard) = layout_cache().lock() {- guard.insert(session_id.to_string(), layout.clone());- }- Ok(layout)-}--/// Drop a session's cached layout. Called after a rewrite or a delete so the-/// next read rebuilds from the file rather than trusting stale offsets.-pub fn invalidate_transcript_layout(session_id: &str) {- if let Ok(mut guard) = layout_cache().lock() {- guard.remove(session_id);- }+ transcripts::layout::session_layout(db.data_dir(), session_id)}pub fn get_session(db: &Database, id: &str) -> Result<Option<SessionDetail>> {@@ -1544,55 +1512,62 @@ pub fn get_session_with_options(return Ok(None);};- let (records, compactions, message_start, has_more_before, message_end, has_more_after) =- if let Some(raw_limit) = options.message_limit.filter(|limit| *limit > 0) {- let limit = raw_limit.min(1_000) as usize;- // Window coordinates are physical transcript lines, so they must be- // clamped against the file layout rather than against `last_seq`.- // The index counter is a deduplicated logical count: a retried- // append leaves two lines with one id, and mixing the two spaces- // silently dropped the newest messages of a long session.- let layout = session_layout(db, id)?;- let total = layout.message_count();- let before = if let Some(message_id) = options.message_around.as_deref() {- let Some(position) =- transcripts::find_message_position(db.data_dir(), id, &layout, message_id)?- else {- return Ok(None);+ let bounded = if let Some(raw_limit) = options.message_limit.filter(|limit| *limit > 0) {+ let limit = raw_limit.min(1_000) as usize;+ Some(transcripts::layout::with_layout_recovery(+ db.data_dir(),+ id,+ |layout| {+ let total = layout.message_count();+ let before = if let Some(message_id) = options.message_around.as_deref() {+ let Some(position) =+ transcripts::find_message_position(db.data_dir(), id, layout, message_id)?+ else {+ return Ok(None);+ };+ (position + limit / 2 + 1).min(total)+ } else {+ match options.message_before {+ Some(value) => (value.max(0) as usize).min(total),+ None => total,+ }};- (position + limit / 2 + 1).min(total)- } else {- match options.message_before {- Some(value) => (value.max(0) as usize).min(total),- None => total,- }- };- let start = before.saturating_sub(limit);- let read = transcripts::read_transcript_window_with_layout(- db.data_dir(),- id,- &layout,- start,- Some(before.saturating_sub(start)),- )?;- (- dedupe_records(read.messages),- read.compactions,- Some(start as i64),- Some(start > 0),- Some(before as i64),- Some(before < total),- )- } else {- let read = transcripts::read_transcript_with_compactions(db.data_dir(), id)?;- (- dedupe_records(read.messages),- read.compactions,- None,- None,- None,- None,- )+ let start = before.saturating_sub(limit);+ let read = transcripts::read_transcript_window_with_layout(+ db.data_dir(),+ id,+ layout,+ start,+ Some(before.saturating_sub(start)),+ )?;+ Ok(Some((+ dedupe_records(read.messages),+ read.compactions,+ Some(start as i64),+ Some(start > 0),+ Some(before as i64),+ Some(before < total),+ )))+ },+ )?)+ } else {+ None+ };+ let (records, compactions, message_start, has_more_before, message_end, has_more_after) =+ match bounded {+ Some(Some(window)) => window,+ Some(None) => return Ok(None),+ None => {+ let read = transcripts::read_transcript_with_compactions(db.data_dir(), id)?;+ (+ dedupe_records(read.messages),+ read.compactions,+ None,+ None,+ None,+ None,+ )+ }};// Content comes from the transcript file; SQLite only indexes it. A// renderer window may additionally request a display cap so a single@@ -1635,14 +1610,13 @@ pub fn get_session_with_options(.and_then(|message| message.parent_tool_call_id.as_deref())});let navigation_parent = match parent_call_id {- Some(call_id) => {- transcripts::read_tool_call(db.data_dir(), id, &session_layout(db, id)?, call_id)?.map(- |record| match options.content_limit {- Some(limit) => record_to_ui_for_display(record, limit),- None => record_to_ui(record),- },- )- }+ Some(call_id) => transcripts::layout::with_layout_recovery(db.data_dir(), id, |layout| {+ transcripts::read_tool_call(db.data_dir(), id, layout, call_id)+ })?+ .map(|record| match options.content_limit {+ Some(limit) => record_to_ui_for_display(record, limit),+ None => record_to_ui(record),+ }),None => None,};Ok(Some(SessionDetail {@@ -1778,8 +1752,6 @@ pub fn fork_session_through(let title = requested_title.map(|value| value.chars().take(100).collect::<String>()).unwrap_or_else(|| format!("{} (branch)", source.summary.title));-- invalidate_transcript_layout(&id);if let Err(error) = transcripts::write_transcript_with_compactions(db.data_dir(),&id,@@ -1813,7 +1785,6 @@ pub fn fork_session_through(Ok(())})();if let Err(error) = indexed {- invalidate_transcript_layout(&id);transcripts::remove_session_files(db.data_dir(), &id);return Err(error);}@@ -1924,7 +1895,6 @@ pub fn delete_session(db: &Database, id: &str) -> Result<bool> {if n > 0 {// Here rather than in the RPC handler so every deletion path (UI,// failed scheduled-run cleanup) also drops the transcript files.- invalidate_transcript_layout(id);transcripts::remove_session_files(db.data_dir(), id);}Ok(n > 0)@@ -2311,7 +2281,6 @@ fn repair_unindexed_transcript_message(return Ok(false);}records[position] = record.clone();- invalidate_transcript_layout(session_id);rebuild_session_message_index(db, session_id, &records)?;tracing::warn!(%session_id,@@ -2420,28 +2389,29 @@ fn indexed_message_record(session_id: &str,message_id: &str,) -> Result<Option<MessageRecord>> {- let layout = session_layout(db, session_id)?;- let mut end = layout.message_count();- while end > 0 {- let start = end.saturating_sub(64);- let window = transcripts::read_transcript_window_with_layout(- db.data_dir(),- session_id,- &layout,- start,- Some(end - start),- )?;- if let Some(record) = window- .messages- .into_iter()- .rev()- .find(|record| record.id == message_id)- {- return Ok(Some(record));+ transcripts::layout::with_layout_recovery(db.data_dir(), session_id, |layout| {+ let mut end = layout.message_count();+ while end > 0 {+ let start = end.saturating_sub(64);+ let window = transcripts::read_transcript_window_with_layout(+ db.data_dir(),+ session_id,+ layout,+ start,+ Some(end - start),+ )?;+ if let Some(record) = window+ .messages+ .into_iter()+ .rev()+ .find(|record| record.id == message_id)+ {+ return Ok(Some(record));+ }+ end = start;}- end = start;- }- Ok(None)+ Ok(None)+ })}/// Task is already a completed tool call while its delegated work is running.@@ -2493,7 +2463,6 @@ fn update_delegation_snapshot(}block["result"] = next["result"].clone();block["text"] = next["text"].clone();- invalidate_transcript_layout(session_id);if !transcripts::update_message(db.data_dir(), session_id, &existing)? {return Err(anyhow!("delegation snapshot is missing from its transcript"@@ -2818,7 +2787,6 @@ fn rewrite_transcript_body(db: &Database, session_id: &str, messages: &[UiMessag.into_iter().filter(|record| compaction_valid_for_records(record, &records)).collect();- invalidate_transcript_layout(session_id);transcripts::write_transcript_with_compactions(db.data_dir(),session_id,@@ -3482,7 +3450,6 @@ pub fn save_active_branch_revision(root.revision_count = Some(total);root.active_revision = Some(active);let (record, _) = ui_to_record(root);- invalidate_transcript_layout(session_id);transcripts::update_message(db.data_dir(), session_id, &record)?;Ok(Some(ActiveRevisionSave {root_user_id,@@ -3607,7 +3574,6 @@ pub fn activate_message_revision(&combined,&[root_user_id.to_string()],)?;- invalidate_transcript_layout(session_id);transcripts::write_transcript_with_compactions(db.data_dir(),session_id,@@ -3681,7 +3647,6 @@ pub fn import_session(return Ok(false);}let (records, texts) = records_and_texts(messages);- invalidate_transcript_layout(&summary.id);transcripts::write_transcript(db.data_dir(), &summary.id, &summary.created_at, &records)?;let indexed = (|| -> Result<()> {let tx = conn.unchecked_transaction()?;@@ -3736,7 +3701,6 @@ pub fn import_session(if let Err(e) = indexed {// Don't leave transcript files behind for a session row that never// materialized.- invalidate_transcript_layout(&summary.id);transcripts::remove_session_files(db.data_dir(), &summary.id);return Err(e);}diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rsindex 29b424458..bc1d42906 100644--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@ -31,6 +31,11 @@ use anyhow::{anyhow, Context, Result};use serde::{Deserialize, Serialize};use serde_json::Value;+pub mod layout;+#[cfg(test)]+use layout::refresh_layout;+pub use layout::TranscriptLayout;+/// Bumped when the line format changes shape incompatibly.pub const TRANSCRIPT_SCHEMA: i64 = 1;@@ -171,217 +176,6 @@ pub struct TranscriptRead {pub compactions: Vec<CompactionRecord>,}-/// Where a transcript's line layout is cached between processes.-///-/// A layout is derived data, and so is this: everything below validates a cache-/// against the file it claims to describe, and any mismatch -- missing, a-/// different file, a shorter file, a count that does not add up -- falls back to-/// the scan that always happened before it existed.-fn layout_cache_path(data_dir: &Path, session_id: &str) -> Result<PathBuf> {- Ok(transcript_path(data_dir, session_id)?.with_extension("jsonl.layout"))-}--/// Transcripts below this are cheaper to scan than to cache, and no fixture grows-/// a cache file.-const LAYOUT_CACHE_MIN_LEN: u64 = 2 * 1024 * 1024;--/// Store again once the cached layout lags the file by this much, so a writer-/// that runs for hours does not leave the next process a large tail to scan.-const LAYOUT_CACHE_MAX_LAG: u64 = 4 * 1024 * 1024;--/// An identity that an append keeps and a rewrite through a temporary file-/// changes. Platforms without one never load a cache, which only means they scan-/// exactly as they did before.-#[cfg(unix)]-fn file_identity(meta: &fs::Metadata) -> u64 {- use std::os::unix::fs::MetadataExt;- meta.ino().wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ ((meta.dev() as u64) << 17)-}--#[cfg(not(unix))]-fn file_identity(_meta: &fs::Metadata) -> u64 {- 0-}--/// The layout a previous process cached beside this transcript, or `None` when it-/// cannot be shown to describe the file as it is now.-fn load_layout_cache(data_dir: &Path, session_id: &str) -> Result<Option<TranscriptLayout>> {- let path = transcript_path(data_dir, session_id)?;- let meta = match fs::metadata(&path) {- Ok(meta) => meta,- Err(_) => return Ok(None),- };- if meta.len() < LAYOUT_CACHE_MIN_LEN {- return Ok(None);- }- let identity = file_identity(&meta);- // Zero means this platform cannot distinguish append from replacement.- // Matching two zeroes would resurrect offsets from a rewritten transcript.- if identity == 0 {- return Ok(None);- }- let raw = match fs::read_to_string(layout_cache_path(data_dir, session_id)?) {- Ok(raw) => raw,- Err(_) => return Ok(None),- };- let mut tokens = raw.split_ascii_whitespace();- let (Some(cached_identity), Some(file_len)) = (tokens.next(), tokens.next()) else {- return Ok(None);- };- if cached_identity.parse::<u64>().ok() != Some(identity) {- return Ok(None);- }- let Some(file_len) = file_len.parse::<u64>().ok() else {- return Ok(None);- };- if file_len < LAYOUT_CACHE_MIN_LEN || file_len > meta.len() {- return Ok(None);- }- let (Some(messages), Some(compactions)) = (tokens.next(), tokens.next()) else {- return Ok(None);- };- let (Some(messages), Some(compactions)) = (- messages.parse::<usize>().ok(),- compactions.parse::<usize>().ok(),- ) else {- return Ok(None);- };- let mut layout = TranscriptLayout {- message_offsets: Vec::with_capacity(messages),- compaction_offsets: Vec::with_capacity(compactions),- file_len,- };- for _ in 0..messages + compactions {- let Some(offset) = tokens.next().and_then(|token| token.parse::<u64>().ok()) else {- return Ok(None);- };- if layout.message_offsets.len() < messages {- layout.message_offsets.push(offset);- } else {- layout.compaction_offsets.push(offset);- }- }- // The offsets have to be the ones a scan would have produced: ascending,- // inside the file the cache describes, and pointing at lines the scan would- // have classified the same way.- if layout- .message_offsets- .windows(2)- .any(|pair| pair[0] >= pair[1])- || layout- .compaction_offsets- .windows(2)- .any(|pair| pair[0] >= pair[1])- || !offsets_look_like_a_scan(&path, &layout)?- {- return Ok(None);- }- Ok(Some(layout))-}--/// Read the first cached offset of each kind out of the transcript and check that-/// it carries the kind of line the cache says it does. Two reads, and they are-/// what keeps offsets that survived a rewrite from being trusted.-fn offsets_look_like_a_scan(path: &Path, layout: &TranscriptLayout) -> Result<bool> {- let head = layout- .message_offsets- .first()- .map(|offset| (*offset, "message"))- .into_iter()- .chain(- layout- .compaction_offsets- .first()- .map(|offset| (*offset, "compaction")),- );- for (offset, kind) in head {- if offset >= layout.file_len {- return Ok(false);- }- let mut file = File::open(path)?;- file.seek(SeekFrom::Start(offset))?;- let mut buf = vec![0u8; 4096];- let read = std::io::Read::read(&mut file, &mut buf)?;- let text = String::from_utf8_lossy(&buf[..read]);- if sniff_line_kind(text.lines().next().unwrap_or("").trim()) != Some(kind) {- return Ok(false);- }- }- Ok(true)-}--/// Cache the layout beside its transcript, through a temporary file that is-/// swapped in, so a reader never sees half of one. Failing to cache costs the-/// next process a scan and nothing else, so this never fails a read.-fn store_layout_cache(data_dir: &Path, session_id: &str, layout: &TranscriptLayout) -> Result<()> {- if layout.file_len < LAYOUT_CACHE_MIN_LEN {- return Ok(());- }- let path = transcript_path(data_dir, session_id)?;- let Ok(meta) = fs::metadata(&path) else {- return Ok(());- };- let identity = file_identity(&meta);- if identity == 0 {- return Ok(());- }- if meta.len() != layout.file_len {- return Ok(());- }- let cache = layout_cache_path(data_dir, session_id)?;- let tmp = cache.with_extension("layout.tmp");- {- let mut writer = BufWriter::new(File::create(&tmp)?);- writeln!(writer, "{} {}", identity, layout.file_len)?;- writeln!(- writer,- "{} {}",- layout.message_offsets.len(),- layout.compaction_offsets.len()- )?;- for offsets in [&layout.message_offsets, &layout.compaction_offsets] {- for (index, offset) in offsets.iter().enumerate() {- if index % 8 == 7 {- writeln!(writer, "{offset}")?;- } else {- write!(writer, "{offset} ")?;- }- }- if !offsets.is_empty() && offsets.len() % 8 != 0 {- writeln!(writer)?;- }- }- writer.flush()?;- }- swap_into_place(&tmp, &cache)-}--/// Physical layout of one transcript file: the byte offset of every message and-/// compaction line, plus the file length it was built from.-///-/// A window read seeks straight to its first selected line instead of parsing-/// every earlier line, so opening a long session costs the window rather than-/// the whole history. `file_len` is the validity token: the transcript is-/// append-only between atomic rewrites, so a longer file is scanned-/// incrementally while a shorter or replaced file invalidates the layout.-#[derive(Debug, Default, Clone)]-pub struct TranscriptLayout {- /// Byte offset of each message line, in file order.- pub message_offsets: Vec<u64>,- /// Byte offset of each compaction line, in file order.- pub compaction_offsets: Vec<u64>,- /// Byte length of the file prefix this layout describes.- pub file_len: u64,-}--impl TranscriptLayout {- /// Physical message-line count. Every window offset in this module is- /// expressed in this coordinate space, not in deduplicated positions.- pub fn message_count(&self) -> usize {- self.message_offsets.len()- }-}-/// Resolve a stable ID without materializing historical message bodies. The/// reverse scan agrees with last-write-wins transcript deduplication.pub fn find_message_position(@@ -397,10 +191,10 @@ pub fn find_message_position(let mut reader = BufReader::new(File::open(transcript_path(data_dir, session_id)?)?);let mut line = String::new();for (position, offset) in layout.message_offsets.iter().enumerate().rev() {- reader.seek(SeekFrom::Start(*offset))?;- line.clear();- reader.read_line(&mut line)?;- if serde_json::from_str::<Identity>(&line).is_ok_and(|identity| identity.id == message_id) {+ read_layout_line(&mut reader, *offset, "message", &mut line)?;+ let identity: Identity =+ serde_json::from_str(&line).context("decode indexed transcript message identity")?;+ if identity.id == message_id {return Ok(Some(position));}}@@ -415,16 +209,6 @@ pub fn read_tool_call(layout: &TranscriptLayout,call_id: &str,) -> Result<Option<MessageRecord>> {- #[derive(Deserialize)]- struct CallIdentity {- #[serde(rename = "callId")]- call_id: Option<String>,- }- #[derive(Deserialize)]- struct ToolIdentity {- role: String,- blocks: Vec<CallIdentity>,- }let mut reader = BufReader::new(File::open(transcript_path(data_dir, session_id)?)?);let mut line = String::new();// A provider tool-call id is an opaque token, so it appears verbatim in the@@ -433,25 +217,50 @@ pub fn read_tool_call(// that JSON would escape keeps the unfiltered path.let verbatim = is_json_verbatim(call_id);for offset in layout.message_offsets.iter().rev() {- reader.seek(SeekFrom::Start(*offset))?;- line.clear();- reader.read_line(&mut line)?;+ read_layout_line(&mut reader, *offset, "message", &mut line)?;if verbatim && !line.contains(call_id) {continue;}- if serde_json::from_str::<ToolIdentity>(&line).is_ok_and(|identity| {- identity.role == "tool"- && identity- .blocks- .iter()- .any(|block| block.call_id.as_deref() == Some(call_id))- }) {+ let identity: Value =+ serde_json::from_str(&line).context("decode indexed transcript tool-call identity")?;+ let matches_call = identity.get("role").and_then(Value::as_str) == Some("tool")+ && identity+ .get("blocks")+ .and_then(Value::as_array)+ .is_some_and(|blocks| {+ blocks+ .iter()+ .any(|block| block.get("callId").and_then(Value::as_str) == Some(call_id))+ });+ if matches_call {return Ok(Some(serde_json::from_str(&line)?));}}Ok(None)}+fn read_layout_line(+ reader: &mut BufReader<File>,+ offset: u64,+ expected_kind: &str,+ line: &mut String,+) -> Result<()> {+ reader.seek(SeekFrom::Start(offset))?;+ line.clear();+ match reader.read_line(line) {+ Ok(0) => return Err(layout::invalid_boundary()),+ Ok(_) => {}+ Err(error) if error.kind() == std::io::ErrorKind::InvalidData => {+ return Err(layout::invalid_boundary())+ }+ Err(error) => return Err(error.into()),+ }+ if !line.ends_with('\n') || sniff_line_kind(line.trim_end()) != Some(expected_kind) {+ return Err(layout::invalid_boundary());+ }+ Ok(())+}+/// Whether a JSON string for this value is the value itself.////// serde_json escapes only the quote, the backslash and the C0 controls, so a@@ -597,110 +406,7 @@ fn scan_json_string(bytes: &[u8], start: usize) -> Option<(&[u8], usize)> {None}-/// Extend `base` with any lines appended after `base.file_len`.-///-/// A transcript only grows between atomic rewrites, so the common case after a-/// new message is a short tail scan. A file that shrank or was replaced by a-/// rewrite of a different length is rescanned from the start, because offsets-/// recorded against the previous contents cannot be trusted.-pub fn refresh_layout(- data_dir: &Path,- session_id: &str,- base: TranscriptLayout,-) -> Result<TranscriptLayout> {- let path = transcript_path(data_dir, session_id)?;- let len = match fs::metadata(&path) {- Ok(meta) => meta.len(),- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {- return Ok(TranscriptLayout::default())- }- Err(e) => return Err(e).with_context(|| format!("stat {}", path.display())),- };- if len == base.file_len {- return Ok(base);- }- // A cold process reads the offsets the previous one cached beside the file- // instead of scanning the transcript again -- 531 ms for a 406 MB transcript,- // taken inside the state lock that serialises the RPC surface. A cache that- // cannot be shown to describe this file is dropped, and the scan below is what- // always happened before this existed.- let base = if base.file_len == 0 {- load_layout_cache(data_dir, session_id)?- .filter(|cached| cached.file_len <= len)- .unwrap_or_default()- } else {- base- };- if len == base.file_len {- return Ok(base);- }- if len < base.file_len {- return scan_layout(&path, TranscriptLayout::default());- }- let base_len = base.file_len;- let layout = scan_layout(&path, base)?;- if base_len == 0 || layout.file_len.saturating_sub(base_len) >= LAYOUT_CACHE_MAX_LAG {- let _ = store_layout_cache(data_dir, session_id, &layout);- }- Ok(layout)-}--/// Scan from `layout.file_len` to the end of the file, appending offsets.-fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLayout> {- let mut file = match File::open(path) {- Ok(file) => file,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {- return Ok(TranscriptLayout::default())- }- Err(e) => return Err(e).with_context(|| format!("read {}", path.display())),- };- let mut offset = layout.file_len;- if offset > 0 {- file.seek(SeekFrom::Start(offset))- .with_context(|| format!("seek {}", path.display()))?;- }- let mut reader = BufReader::new(file);- let mut line = String::new();- loop {- line.clear();- let read = reader.read_line(&mut line)?;- if read == 0 {- break;- }- // A torn trailing line (crash mid-append) has no newline yet. Keeping it- // out of both the offsets and `file_len` lets a later refresh pick it up- // once the writer completes it.- if !line.ends_with('\n') {- break;- }- match sniff_line_kind(line.trim_end()) {- Some("message") => layout.message_offsets.push(offset),- Some("compaction") => layout.compaction_offsets.push(offset),- _ => {}- }- offset += read as u64;- // A skipped multi-megabyte line must not leave its capacity attached to- // every following read.- if line.capacity() > 1024 * 1024 {- line = String::new();- }- }- layout.file_len = offset;- Ok(layout)-}--/// Serialize one JSONL line with its `type` discriminator first.-///-/// Position matters for reads: a line has to be classifiable — and, for a-/// message, its id readable — before a reader walks a multi-megabyte tool-/// result, so the discriminator is written first and the id immediately after-/// it. That makes both a fixed-cost prefix check.-///-/// This is a single serialization pass plus one splice. The shape it replaced-/// built a `serde_json::Value` tree, deep-cloned it (a `Value` cannot be-/// re-wrapped without an owned map) and serialized the clone, then formatted-/// the whole payload a second time — four passes over every byte written to a-/// transcript, and an allocation per JSON node.+/// Serialize one JSONL line with its type discriminator first.fn tagged(tag: &str, body: &impl Serialize) -> Result<String> {let body = serde_json::to_string(body)?;let fields = body@@ -708,7 +414,6 @@ fn tagged(tag: &str, body: &impl Serialize) -> Result<String> {.and_then(|rest| rest.strip_suffix('}')).ok_or_else(|| anyhow!("line body must be an object"))?;let head = format!("{{\"type\":{}", Value::String(tag.into()));- // `{}` has no fields to append after the discriminator.if fields.is_empty() {return Ok(format!("{head}}}"));}@@ -719,9 +424,9 @@ fn tagged(tag: &str, body: &impl Serialize) -> Result<String> {/// could traverse out of the sessions base gets no file at all.fn safe_session_id(session_id: &str) -> bool {!session_id.is_empty()- && session_id- .chars()- .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+ && session_id.chars().all(|character| {+ character.is_ascii_alphanumeric() || character == '-' || character == '_'+ })}pub fn base_dir(data_dir: &Path) -> PathBuf {@@ -1186,28 +891,20 @@ pub fn read_transcript_window_with_layout(let mut reader = BufReader::new(file);let mut line = String::new();for (offset, is_message) in wanted {- reader- .seek(SeekFrom::Start(offset))- .with_context(|| format!("seek {}", path.display()))?;- line.clear();- if reader.read_line(&mut line)? == 0 {- continue;- }+ let kind = if is_message { "message" } else { "compaction" };+ read_layout_line(&mut reader, offset, kind, &mut line)+ .with_context(|| format!("read indexed transcript line in {}", path.display()))?;let trimmed = line.trim();if is_message {- match serde_json::from_str::<MessageRecord>(trimmed) {- Ok(record) => out.messages.push(record),- Err(error) => {- tracing::warn!(path = %path.display(), %error, "skipping invalid message line");- }- }+ out.messages.push(+ serde_json::from_str::<MessageRecord>(trimmed)+ .context("decode indexed transcript message")?,+ );} else {- match serde_json::from_str::<CompactionRecord>(trimmed) {- Ok(record) => out.compactions.push(record),- Err(error) => {- tracing::warn!(path = %path.display(), %error, "skipping invalid compaction line");- }- }+ out.compactions.push(+ serde_json::from_str::<CompactionRecord>(trimmed)+ .context("decode indexed transcript compaction")?,+ );}if line.capacity() > 1024 * 1024 {line = String::new();@@ -1338,7 +1035,9 @@ pub fn write_transcript_with_compactions(writer.flush()?;writer.get_ref().sync_data()?;}- swap_into_place(&tmp, &path)+ swap_into_place(&tmp, &path)?;+ layout::invalidate(data_dir, session_id);+ Ok(())}/// Swap a fully written temp file over its target, atomically.@@ -1396,11 +1095,6 @@ pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord)return Ok(true);}}- // The rewrite below moves line contents, so the cached line offsets are stale- // from here on. The append above only grew the file, which the incremental- // layout refresh handles by itself — and dropping that invalidation is what- // keeps the next read of a long session from scanning all of it again.- crate::sessions::invalidate_transcript_layout(session_id);let raw = match fs::read_to_string(&path) {Ok(raw) => raw,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),@@ -1443,6 +1137,7 @@ pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord)writer.get_ref().sync_data()?;}swap_into_place(&tmp, &path)?;+ layout::invalidate(data_dir, session_id);Ok(true)}@@ -1715,6 +1410,7 @@ pub fn read_revision(/// (idempotent, best-effort). Called only from session deletion — transcript/// files are user data and have no age/orphan sweep.pub fn remove_session_files(data_dir: &Path, session_id: &str) {+ layout::invalidate(data_dir, session_id);let Ok(transcript) = transcript_path(data_dir, session_id) else {return;};@@ -1742,10 +1438,6 @@ pub fn remove_session_files(data_dir: &Path, session_id: &str) {}}-#[cfg(test)]-#[path = "transcripts_layout_tests.rs"]-mod layout_tests;-#[cfg(test)]mod tests {use super::*;@@ -2547,13 +2239,15 @@ mod tests {let mut message_offsets = Vec::new();let mut at = 0usize;for line in raw.split_inclusive(|byte| *byte == b'\n') {- message_offsets.push(at as u64);+ if line.starts_with(br#"{"type":"message""#) {+ message_offsets.push(at as u64);+ }at += line.len();}TranscriptLayout {message_offsets,- compaction_offsets: Vec::new(),file_len: raw.len() as u64,+ ..TranscriptLayout::default()}}@@ -2609,6 +2303,34 @@ mod tests {.is_none());}+ #[test]+ fn indexed_message_lookup_does_not_hide_malformed_json() {+ let dir = tempdir().unwrap();+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x")).unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ let mut file = OpenOptions::new().append(true).open(&path).unwrap();+ file.write_all(b"{\"type\":\"message\",\"id\":\"bad\",\"blocks\":[],\"invalid\":}\n")+ .unwrap();+ let layout = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();++ assert!(find_message_position(dir.path(), "s1", &layout, "absent").is_err());+ }++ #[test]+ fn tool_call_lookup_does_not_hide_malformed_json() {+ let dir = tempdir().unwrap();+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x")).unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ let mut file = OpenOptions::new().append(true).open(&path).unwrap();+ file.write_all(+ b"{\"type\":\"message\",\"id\":\"bad\",\"role\":\"tool\",\"blocks\":[{\"callId\":\"call-bad\"}],\"invalid\":}\n",+ )+ .unwrap();+ let layout = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();++ assert!(read_tool_call(dir.path(), "s1", &layout, "call-bad").is_err());+ }+/// Concurrent appends from several sessions must not cost a line, fuse two/// lines, or leak across files: writes are ordered by the state lock and/// each append flushes its own file. Guards the append shape the durabilitydiff --git a/crates/host-core/src/transcripts/layout.rs b/crates/host-core/src/transcripts/layout.rsnew file mode 100644index 000000000..b58286920--- /dev/null+++ b/crates/host-core/src/transcripts/layout.rs@@ -0,0 +1,616 @@+//! The derived physical index for a session transcript.+//!+//! Layout offsets are disposable. They are reused only while the transcript's+//! file identity still matches, and every cache failure falls back to a scan.++use std::{+ collections::HashMap,+ fs::{self, File},+ io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write},+ path::{Path, PathBuf},+ sync::{Mutex, OnceLock},+};++use anyhow::{Context, Result};+use sha2::{Digest, Sha256};++use super::{sniff_line_kind, swap_into_place, transcript_path};++const LAYOUT_CACHE_MIN_LEN: u64 = 2 * 1024 * 1024;+const LAYOUT_CACHE_MAX_LAG: u64 = 4 * 1024 * 1024;+const LAYOUT_CACHE_MAGIC: &str = "PI-DESKTOP-TRANSCRIPT-LAYOUT";+const LAYOUT_CACHE_VERSION: &str = "2";++/// A stable identity available on filesystems that expose one.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub enum FileIdentity {+ Available {+ platform: &'static str,+ volume_id: u64,+ file_id: [u8; 16],+ },+ #[default]+ Unavailable,+}++impl FileIdentity {+ fn is_available(&self) -> bool {+ matches!(self, Self::Available { .. })+ }++ fn write_tokens(&self, writer: &mut impl Write) -> std::io::Result<()> {+ match self {+ Self::Available {+ platform,+ volume_id,+ file_id,+ } => writeln!(writer, "{platform} {volume_id:x} {}", hex::encode(file_id)),+ Self::Unavailable => Err(std::io::Error::other("file identity is unavailable")),+ }+ }++ fn from_tokens(platform: &str, volume_id: &str, file_id: &str) -> Option<Self> {+ let expected_platform = if cfg!(unix) {+ "unix"+ } else if cfg!(windows) {+ "windows"+ } else {+ return None;+ };+ if platform != expected_platform {+ return None;+ }+ let volume_id = u64::from_str_radix(volume_id, 16).ok()?;+ let bytes = hex::decode(file_id).ok()?;+ let file_id: [u8; 16] = bytes.try_into().ok()?;+ Some(Self::Available {+ platform: expected_platform,+ volume_id,+ file_id,+ })+ }+}++/// Physical layout of one transcript file: the byte offset of every message+/// and compaction line, plus the file prefix those offsets describe.+#[derive(Debug, Default, Clone)]+pub struct TranscriptLayout {+ /// Byte offset of each message line, in file order.+ pub message_offsets: Vec<u64>,+ /// Byte offset of each compaction line, in file order.+ pub compaction_offsets: Vec<u64>,+ /// Byte length of the file prefix this layout describes.+ pub file_len: u64,+ pub(crate) identity: FileIdentity,+}++impl TranscriptLayout {+ /// Physical message-line count. Window offsets use this coordinate space,+ /// not the deduplicated message positions.+ pub fn message_count(&self) -> usize {+ self.message_offsets.len()+ }++ fn empty(identity: FileIdentity) -> Self {+ Self {+ identity,+ ..Self::default()+ }+ }+}++#[derive(Debug, Clone, Hash, PartialEq, Eq)]+struct LayoutKey {+ data_dir: PathBuf,+ session_id: String,+}++static TRANSCRIPT_LAYOUTS: OnceLock<Mutex<HashMap<LayoutKey, TranscriptLayout>>> = OnceLock::new();++fn layout_cache() -> &'static Mutex<HashMap<LayoutKey, TranscriptLayout>> {+ TRANSCRIPT_LAYOUTS.get_or_init(|| Mutex::new(HashMap::new()))+}++fn layout_key(data_dir: &Path, session_id: &str) -> LayoutKey {+ LayoutKey {+ data_dir: data_dir.to_path_buf(),+ session_id: session_id.to_string(),+ }+}++fn layout_cache_path(data_dir: &Path, session_id: &str) -> Result<PathBuf> {+ Ok(transcript_path(data_dir, session_id)?.with_extension("jsonl.layout"))+}++/// Return an up-to-date layout, reusing the process cache or a validated disk+/// cache and scanning only the appended tail.+pub(crate) fn session_layout(data_dir: &Path, session_id: &str) -> Result<TranscriptLayout> {+ let key = layout_key(data_dir, session_id);+ let cached = layout_cache()+ .lock()+ .ok()+ .and_then(|guard| guard.get(&key).cloned())+ .unwrap_or_default();+ let layout = refresh_layout(data_dir, session_id, cached)?;+ if let Ok(mut guard) = layout_cache().lock() {+ guard.insert(key, layout.clone());+ }+ Ok(layout)+}++/// Remove both derived cache layers after a rewrite or session deletion.+/// Cleanup failure is diagnostic only; file identity still prevents the stale+/// disk cache from being trusted on the next read.+pub(crate) fn invalidate(data_dir: &Path, session_id: &str) {+ if let Ok(mut guard) = layout_cache().lock() {+ guard.remove(&layout_key(data_dir, session_id));+ }+ let mut paths = Vec::new();+ if let Ok(cache) = layout_cache_path(data_dir, session_id) {+ paths.push(cache.with_extension("layout.tmp"));+ paths.push(cache);+ }+ for path in paths {+ if let Err(error) = fs::remove_file(&path) {+ if error.kind() != std::io::ErrorKind::NotFound {+ tracing::warn!(%error, "failed to invalidate transcript layout cache");+ }+ }+ }+}++/// A boundary failure means an indexed offset does not point at the expected+/// JSONL line. It is distinct from transcript I/O or decoding failures so the+/// common read path can rebuild once and retry.+#[derive(Debug, thiserror::Error)]+#[error("transcript layout boundary is invalid")]+pub(crate) struct InvalidLayoutBoundary;++pub(crate) fn invalid_boundary() -> anyhow::Error {+ InvalidLayoutBoundary.into()+}++/// Rebuild once after an indexed read detects a stale/corrupt boundary. The+/// retry always bypasses the disk cache and callers recompute their selection+/// from the rebuilt message count.+pub(crate) fn with_layout_recovery<T>(+ data_dir: &Path,+ session_id: &str,+ mut operation: impl FnMut(&TranscriptLayout) -> Result<T>,+) -> Result<T> {+ let first = session_layout(data_dir, session_id)?;+ match operation(&first) {+ Ok(value) => Ok(value),+ Err(error) if error.is::<InvalidLayoutBoundary>() => {+ invalidate(data_dir, session_id);+ let rebuilt = scan_current_file(data_dir, session_id)?;+ cache_rebuilt_layout(data_dir, session_id, &rebuilt);+ match operation(&rebuilt) {+ Err(error) if error.is::<InvalidLayoutBoundary>() => {+ Err(error.context("transcript layout remained invalid after one full rebuild"))+ }+ result => result,+ }+ }+ Err(error) => Err(error),+ }+}++fn cache_rebuilt_layout(data_dir: &Path, session_id: &str, layout: &TranscriptLayout) {+ if let Ok(mut guard) = layout_cache().lock() {+ guard.insert(layout_key(data_dir, session_id), layout.clone());+ }+ if let Err(error) = store_layout_cache(data_dir, session_id, layout) {+ tracing::warn!(%error, "failed to persist rebuilt transcript layout cache");+ }+}++/// Refresh the supplied layout only after validating its file identity.+pub fn refresh_layout(+ data_dir: &Path,+ session_id: &str,+ base: TranscriptLayout,+) -> Result<TranscriptLayout> {+ let path = transcript_path(data_dir, session_id)?;+ let metadata = match fs::metadata(&path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ return Ok(TranscriptLayout::default())+ }+ Err(error) => return Err(error).with_context(|| format!("stat {}", path.display())),+ };+ refresh_with_identity(+ data_dir,+ session_id,+ base,+ metadata.len(),+ file_identity(&path, &metadata),+ )+}++fn refresh_with_identity(+ data_dir: &Path,+ session_id: &str,+ base: TranscriptLayout,+ length: u64,+ identity: FileIdentity,+) -> Result<TranscriptLayout> {+ let path = transcript_path(data_dir, session_id)?;+ let mut base =+ if identity.is_available() && base.identity == identity && base.file_len <= length {+ base+ } else {+ TranscriptLayout::empty(identity.clone())+ };++ if !identity.is_available() {+ // Without a reliable identity, no existing offsets can be trusted.+ base = TranscriptLayout::empty(identity);+ } else if base.file_len == 0 {+ base = load_layout_cache(data_dir, session_id, &identity, length)?+ .unwrap_or_else(|| TranscriptLayout::empty(identity.clone()));+ }++ if length == base.file_len {+ return Ok(base);+ }+ let base_len = base.file_len;+ let layout = scan_layout(&path, base)?;+ if base_len == 0 || layout.file_len.saturating_sub(base_len) >= LAYOUT_CACHE_MAX_LAG {+ if let Err(error) = store_layout_cache(data_dir, session_id, &layout) {+ tracing::warn!(%error, "failed to persist transcript layout cache");+ }+ }+ Ok(layout)+}++fn scan_current_file(data_dir: &Path, session_id: &str) -> Result<TranscriptLayout> {+ let path = transcript_path(data_dir, session_id)?;+ let metadata = match fs::metadata(&path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ return Ok(TranscriptLayout::default())+ }+ Err(error) => return Err(error).with_context(|| format!("stat {}", path.display())),+ };+ let identity = file_identity(&path, &metadata);+ scan_layout(&path, TranscriptLayout::empty(identity))+}++/// Scan from the known complete-line prefix to EOF, extending the offsets.+fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLayout> {+ let mut file = match File::open(path) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ return Ok(TranscriptLayout::default())+ }+ Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),+ };+ let mut offset = layout.file_len;+ if offset > 0 {+ file.seek(SeekFrom::Start(offset))+ .with_context(|| format!("seek {}", path.display()))?;+ }+ let mut reader = BufReader::new(file);+ let mut line = String::new();+ loop {+ line.clear();+ let read = reader.read_line(&mut line)?;+ if read == 0 {+ break;+ }+ // A torn append is excluded until its newline arrives.+ if !line.ends_with('\n') {+ break;+ }+ match sniff_line_kind(line.trim_end()) {+ Some("message") => layout.message_offsets.push(offset),+ Some("compaction") => layout.compaction_offsets.push(offset),+ _ => {}+ }+ offset += read as u64;+ if line.capacity() > 1024 * 1024 {+ line = String::new();+ }+ }+ layout.file_len = offset;+ Ok(layout)+}++fn load_layout_cache(+ data_dir: &Path,+ session_id: &str,+ identity: &FileIdentity,+ current_len: u64,+) -> Result<Option<TranscriptLayout>> {+ if current_len < LAYOUT_CACHE_MIN_LEN {+ return Ok(None);+ }+ let cache_path = layout_cache_path(data_dir, session_id)?;+ let raw = match fs::read_to_string(&cache_path) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => {+ tracing::warn!(%error, "failed to read transcript layout cache");+ return Ok(None);+ }+ };+ let mut tokens = raw.split_ascii_whitespace();+ if tokens.next() != Some(LAYOUT_CACHE_MAGIC) || tokens.next() != Some(LAYOUT_CACHE_VERSION) {+ return Ok(None);+ }+ let (Some(platform), Some(volume), Some(file_id)) =+ (tokens.next(), tokens.next(), tokens.next())+ else {+ return Ok(None);+ };+ let Some(cached_identity) = FileIdentity::from_tokens(platform, volume, file_id) else {+ return Ok(None);+ };+ if &cached_identity != identity {+ return Ok(None);+ }+ let Some(file_len) = tokens.next().and_then(|token| token.parse::<u64>().ok()) else {+ return Ok(None);+ };+ if file_len < LAYOUT_CACHE_MIN_LEN || file_len > current_len {+ return Ok(None);+ }+ let (Some(message_count), Some(compaction_count)) = (tokens.next(), tokens.next()) else {+ return Ok(None);+ };+ let (Some(message_count), Some(compaction_count)) = (+ message_count.parse::<usize>().ok(),+ compaction_count.parse::<usize>().ok(),+ ) else {+ return Ok(None);+ };+ let Some(offset_count) = message_count.checked_add(compaction_count) else {+ return Ok(None);+ };+ let Ok(file_len_usize) = usize::try_from(file_len) else {+ return Ok(None);+ };+ // A classified JSONL record needs at least `{"type":"message"}\n`;+ // reject impossible counts before reserving memory from cache input.+ if offset_count > file_len_usize / 19 || offset_count > tokens.clone().count() {+ return Ok(None);+ }+ let mut layout = TranscriptLayout {+ message_offsets: Vec::with_capacity(message_count),+ compaction_offsets: Vec::with_capacity(compaction_count),+ file_len,+ identity: cached_identity,+ };+ for index in 0..offset_count {+ let Some(offset) = tokens.next().and_then(|token| token.parse::<u64>().ok()) else {+ return Ok(None);+ };+ if index < message_count {+ layout.message_offsets.push(offset);+ } else {+ layout.compaction_offsets.push(offset);+ }+ }+ let transcript = transcript_path(data_dir, session_id)?;+ let (Some(checksum_label), Some(checksum)) = (tokens.next(), tokens.next()) else {+ return Ok(None);+ };+ if checksum_label != "checksum"+ || checksum != layout_cache_digest(&layout)+ || tokens.next().is_some()+ || !offsets_are_valid(&layout)+ || !prefix_ends_on_line_boundary(&transcript, file_len)?+ {+ return Ok(None);+ }+ if !offsets_look_like_scan(&transcript, &layout)? {+ return Ok(None);+ }+ Ok(Some(layout))+}++fn offsets_are_valid(layout: &TranscriptLayout) -> bool {+ if layout+ .message_offsets+ .windows(2)+ .any(|pair| pair[0] >= pair[1])+ || layout+ .compaction_offsets+ .windows(2)+ .any(|pair| pair[0] >= pair[1])+ {+ return false;+ }+ let mut messages = layout.message_offsets.iter().copied().peekable();+ let mut compactions = layout.compaction_offsets.iter().copied().peekable();+ let mut previous = None;+ loop {+ let next_message = messages.peek().copied();+ let next_compaction = compactions.peek().copied();+ let next = match (next_message, next_compaction) {+ (None, None) => break,+ (Some(message), Some(compaction)) if message == compaction => return false,+ (Some(message), Some(compaction)) if message < compaction => {+ messages.next();+ message+ }+ (Some(_), Some(compaction)) => {+ compactions.next();+ compaction+ }+ (Some(message), None) => {+ messages.next();+ message+ }+ (None, Some(compaction)) => {+ compactions.next();+ compaction+ }+ };+ if next >= layout.file_len || previous.is_some_and(|offset| offset >= next) {+ return false;+ }+ previous = Some(next);+ }+ true+}++fn prefix_ends_on_line_boundary(path: &Path, file_len: u64) -> Result<bool> {+ if file_len == 0 {+ return Ok(true);+ }+ let mut file = File::open(path)?;+ file.seek(SeekFrom::Start(file_len - 1))?;+ let mut byte = [0u8; 1];+ Ok(file.read_exact(&mut byte).is_ok() && byte[0] == b'\n')+}++fn offsets_look_like_scan(path: &Path, layout: &TranscriptLayout) -> Result<bool> {+ let head = layout+ .message_offsets+ .first()+ .map(|offset| (*offset, "message"))+ .into_iter()+ .chain(+ layout+ .compaction_offsets+ .first()+ .map(|offset| (*offset, "compaction")),+ );+ for (offset, kind) in head {+ if offset >= layout.file_len {+ return Ok(false);+ }+ let mut file = File::open(path)?;+ file.seek(SeekFrom::Start(offset))?;+ let mut prefix = [0u8; 4096];+ let read = BufReader::new(file).read(&mut prefix)?;+ let text = String::from_utf8_lossy(&prefix[..read]);+ if sniff_line_kind(text.trim_end()) != Some(kind) {+ return Ok(false);+ }+ }+ Ok(true)+}++fn layout_cache_digest(layout: &TranscriptLayout) -> String {+ let mut digest = Sha256::new();+ digest.update(LAYOUT_CACHE_MAGIC.as_bytes());+ digest.update(LAYOUT_CACHE_VERSION.as_bytes());+ match &layout.identity {+ FileIdentity::Available {+ platform,+ volume_id,+ file_id,+ } => {+ digest.update(platform.as_bytes());+ digest.update(volume_id.to_le_bytes());+ digest.update(file_id);+ }+ FileIdentity::Unavailable => digest.update(b"unavailable"),+ }+ digest.update(layout.file_len.to_le_bytes());+ digest.update((layout.message_offsets.len() as u64).to_le_bytes());+ digest.update((layout.compaction_offsets.len() as u64).to_le_bytes());+ for offset in layout+ .message_offsets+ .iter()+ .chain(&layout.compaction_offsets)+ {+ digest.update(offset.to_le_bytes());+ }+ hex::encode(digest.finalize())+}++fn store_layout_cache(data_dir: &Path, session_id: &str, layout: &TranscriptLayout) -> Result<()> {+ if layout.file_len < LAYOUT_CACHE_MIN_LEN || !layout.identity.is_available() {+ return Ok(());+ }+ let path = transcript_path(data_dir, session_id)?;+ let metadata = fs::metadata(&path)?;+ if metadata.len() != layout.file_len || file_identity(&path, &metadata) != layout.identity {+ return Ok(());+ }+ let cache = layout_cache_path(data_dir, session_id)?;+ let tmp = cache.with_extension("layout.tmp");+ {+ let mut writer = BufWriter::new(File::create(&tmp)?);+ writeln!(writer, "{LAYOUT_CACHE_MAGIC} {LAYOUT_CACHE_VERSION}")?;+ layout.identity.write_tokens(&mut writer)?;+ writeln!(writer, "{}", layout.file_len)?;+ writeln!(+ writer,+ "{} {}",+ layout.message_offsets.len(),+ layout.compaction_offsets.len()+ )?;+ for offsets in [&layout.message_offsets, &layout.compaction_offsets] {+ for (index, offset) in offsets.iter().enumerate() {+ if index % 8 == 7 {+ writeln!(writer, "{offset}")?;+ } else {+ write!(writer, "{offset} ")?;+ }+ }+ if !offsets.is_empty() && offsets.len() % 8 != 0 {+ writeln!(writer)?;+ }+ }+ writeln!(writer, "checksum {}", layout_cache_digest(layout))?;+ writer.flush()?;+ writer.get_ref().sync_data()?;+ }+ swap_into_place(&tmp, &cache)+}++#[cfg(unix)]+fn file_identity(_path: &Path, metadata: &fs::Metadata) -> FileIdentity {+ use std::os::unix::fs::MetadataExt;+ let mut file_id = [0u8; 16];+ file_id[..8].copy_from_slice(&metadata.ino().to_be_bytes());+ FileIdentity::Available {+ platform: "unix",+ volume_id: metadata.dev(),+ file_id,+ }+}++#[cfg(windows)]+fn file_identity(path: &Path, _metadata: &fs::Metadata) -> FileIdentity {+ use std::{mem::size_of, os::windows::io::AsRawHandle};+ use windows_sys::Win32::{+ Foundation::HANDLE,+ Storage::FileSystem::{FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO},+ };++ let Ok(file) = File::open(path) else {+ return FileIdentity::Unavailable;+ };+ let mut info = FILE_ID_INFO::default();+ let result = unsafe {+ GetFileInformationByHandleEx(+ file.as_raw_handle() as HANDLE,+ FileIdInfo,+ (&mut info as *mut FILE_ID_INFO).cast(),+ size_of::<FILE_ID_INFO>() as u32,+ )+ };+ if result == 0 {+ return FileIdentity::Unavailable;+ }+ FileIdentity::Available {+ platform: "windows",+ volume_id: info.VolumeSerialNumber,+ file_id: info.FileId.Identifier,+ }+}++#[cfg(not(any(unix, windows)))]+fn file_identity(_path: &Path, _metadata: &fs::Metadata) -> FileIdentity {+ FileIdentity::Unavailable+}++#[cfg(test)]+#[path = "../transcripts_layout_tests.rs"]+mod tests;diff --git a/crates/host-core/src/transcripts_layout_tests.rs b/crates/host-core/src/transcripts_layout_tests.rsindex 4ba596776..173f8ff2f 100644--- a/crates/host-core/src/transcripts_layout_tests.rs+++ b/crates/host-core/src/transcripts_layout_tests.rs@@ -1,4 +1,8 @@use super::*;+use crate::transcripts::{+ append_message, read_transcript_window_with_layout, remove_session_files, transcript_path,+ update_message, write_transcript, MessageRecord,+};use serde_json::json;use tempfile::tempdir;@@ -16,6 +20,29 @@ fn message(id: &str, text: &str) -> MessageRecord {}}+fn task_message(status: &str, result: &str) -> MessageRecord {+ MessageRecord {+ id: "m150".into(),+ role: "tool".into(),+ tool_name: Some("Task".into()),+ is_error: false,+ blocks: json!([{+ "type": "tool_call",+ "callId": "task-150",+ "name": "Task",+ "arguments": {},+ "result": { "details": {+ "delegationId": "delegate-150",+ "status": status,+ "result": result+ }},+ "text": result+ }]),+ meta: None,+ created_at: CREATED_AT.into(),+ }+}+fn cold_read(dir: &Path) -> Vec<MessageRecord> {let layout = refresh_layout(dir, "layout-regression", TranscriptLayout::default()).unwrap();read_transcript_window_with_layout(dir, "layout-regression", &layout, 0, None)@@ -118,6 +145,40 @@ fn cold_layout_keeps_append_only_history() {assert_messages(&cold_read(dir.path()), &messages);}+#[test]+fn a_damaged_disk_cache_is_rebuilt_without_skipping_messages() {+ let dir = tempdir().unwrap();+ let messages: Vec<MessageRecord> = (0..300)+ .map(|index| message(&format!("m{index}"), &format!("内容🙂{index}")))+ .chain(std::iter::once(message("large", &"大🙂".repeat(400_000))))+ .collect();+ seed_cache(dir.path(), &messages);+ let cache = layout_cache_path(dir.path(), "layout-regression").unwrap();+ let mut tokens: Vec<String> = fs::read_to_string(&cache)+ .unwrap()+ .split_ascii_whitespace()+ .map(str::to_owned)+ .collect();+ assert_eq!(tokens[0], LAYOUT_CACHE_MAGIC);+ tokens[8] = u64::MAX.to_string();+ fs::write(&cache, tokens.join("\n")).unwrap();++ let rebuilt =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap();+ assert_eq!(rebuilt.message_count(), messages.len());+ let actual = read_transcript_window_with_layout(+ dir.path(),+ "layout-regression",+ &rebuilt,+ rebuilt.message_count().saturating_sub(100),+ Some(100),+ )+ .unwrap()+ .messages;+ assert_messages(&actual, &messages[messages.len() - 100..]);+ assert!(fs::read_to_string(cache).unwrap().contains("checksum "));+}+#[test]fn cold_layout_after_updating_an_earlier_message_preserves_the_tail() {let dir = tempdir().unwrap();@@ -133,20 +194,199 @@ fn cold_layout_after_updating_an_earlier_message_preserves_the_tail() {}#[test]-fn an_unsupported_identity_never_persists_a_layout() {+fn a_growing_middle_rewrite_does_not_reuse_stale_in_memory_offsets() {+ let dir = tempdir().unwrap();+ let body = "中文🙂".repeat(800);+ let mut messages: Vec<MessageRecord> = (0..300)+ .map(|index| {+ if index == 150 {+ task_message("running", "partial")+ } else {+ message(&format!("m{index}"), &body)+ }+ })+ .collect();+ seed_cache(dir.path(), &messages);++ let path = transcript_path(dir.path(), "layout-regression").unwrap();+ let old_len = fs::metadata(&path).unwrap().len();+ assert!(old_len > LAYOUT_CACHE_MIN_LEN);+ let cached =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap();+ assert_eq!(cached.file_len, old_len);++ for index in 300..343 {+ let appended = message(&format!("m{index}"), &body);+ append_message(dir.path(), "layout-regression", CREATED_AT, &appended).unwrap();+ messages.push(appended);+ }++ // Grow a row in the middle. The resulting file remains longer than the+ // cache's scanned prefix, which used to make refresh_layout scan only the+ // new tail while keeping every offset after this row stale.+ messages[150] = task_message("completed", &format!("{}{}", body, "状态🙂".repeat(80)));+ assert!(update_message(dir.path(), "layout-regression", &messages[150]).unwrap());+ assert!(fs::metadata(&path).unwrap().len() > cached.file_len);++ let refreshed = refresh_layout(dir.path(), "layout-regression", cached).unwrap();+ let total = refreshed.message_count();+ let actual = read_transcript_window_with_layout(+ dir.path(),+ "layout-regression",+ &refreshed,+ total.saturating_sub(100),+ Some(100),+ )+ .unwrap()+ .messages;+ assert_messages(&actual, &messages[messages.len() - 100..]);+}++#[test]+fn layout_recovery_rebuilds_once_and_recomputes_the_window() {+ let dir = tempdir().unwrap();+ let body = "中文🙂".repeat(800);+ let messages: Vec<MessageRecord> = (0..300)+ .map(|index| message(&format!("m{index}"), &body))+ .collect();+ seed_cache(dir.path(), &messages);+ let mut stale =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap();+ let path = transcript_path(dir.path(), "layout-regression").unwrap();+ let bytes = fs::read(&path).unwrap();+ let line_start = stale.message_offsets[250] as usize;+ let line_end = bytes[line_start..]+ .iter()+ .position(|byte| *byte == b'\n')+ .map(|offset| line_start + offset)+ .unwrap();+ let line = &bytes[line_start..line_end];+ let text_prefix = b"\"text\":\"";+ let text_start = line+ .windows(text_prefix.len())+ .position(|window| window == text_prefix)+ .unwrap()+ + text_prefix.len();+ // Point into the second byte of a Chinese character so read_line sees+ // invalid UTF-8 at a cached boundary and activates the common retry.+ stale.message_offsets[250] += (text_start + 1) as u64;+ layout_cache()+ .lock()+ .unwrap()+ .insert(layout_key(dir.path(), "layout-regression"), stale);++ let (total, actual) = with_layout_recovery(dir.path(), "layout-regression", |layout| {+ let total = layout.message_count();+ let start = total.saturating_sub(100);+ let read = read_transcript_window_with_layout(+ dir.path(),+ "layout-regression",+ layout,+ start,+ Some(100),+ )?;+ Ok((total, read.messages))+ })+ .unwrap();+ assert_eq!(total, messages.len());+ assert_messages(&actual, &messages[messages.len() - 100..]);+}++#[test]+fn real_invalid_utf8_is_reported_without_changing_transcript_bytes() {+ let dir = tempdir().unwrap();+ let path = transcript_path(dir.path(), "layout-regression").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ let bytes =+ b"{\"type\":\"session\"}\n{\"type\":\"message\",\"id\":\"broken\",\"content\":\"\xff\"}\n";+ fs::write(&path, bytes).unwrap();++ let error =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap_err();+ assert!(format!("{error:#}").contains("valid UTF-8"));+ assert_eq!(fs::read(path).unwrap(), bytes);+}++#[test]+fn a_reliable_identity_persists_a_layout() {let dir = tempdir().unwrap();let messages = vec![message("m1", &"x".repeat(LAYOUT_CACHE_MIN_LEN as usize))];seed_cache(dir.path(), &messages);let path = transcript_path(dir.path(), "layout-regression").unwrap();- let identity = file_identity(&fs::metadata(path).unwrap());+ let metadata = fs::metadata(&path).unwrap();+ let identity = file_identity(&path, &metadata);assert_eq!(layout_cache_path(dir.path(), "layout-regression").unwrap().exists(),- identity != 0+ identity.is_available());}+#[test]+fn unavailable_file_identity_disables_disk_cache_but_keeps_reads_available() {+ let dir = tempdir().unwrap();+ let first = message("m1", &"可读🙂".repeat(LAYOUT_CACHE_MIN_LEN as usize / 6));+ write_transcript(+ dir.path(),+ "layout-regression",+ CREATED_AT,+ std::slice::from_ref(&first),+ )+ .unwrap();+ let length = fs::metadata(transcript_path(dir.path(), "layout-regression").unwrap())+ .unwrap()+ .len();+ let layout = refresh_with_identity(+ dir.path(),+ "layout-regression",+ TranscriptLayout::default(),+ length,+ FileIdentity::Unavailable,+ )+ .unwrap();+ assert_eq!(layout.message_count(), 1);+ assert!(!layout_cache_path(dir.path(), "layout-regression")+ .unwrap()+ .exists());++ let second = message("m2", "仍可读取🙂");+ append_message(dir.path(), "layout-regression", CREATED_AT, &second).unwrap();+ let next_length = fs::metadata(transcript_path(dir.path(), "layout-regression").unwrap())+ .unwrap()+ .len();+ let refreshed = refresh_with_identity(+ dir.path(),+ "layout-regression",+ layout,+ next_length,+ FileIdentity::Unavailable,+ )+ .unwrap();+ assert_eq!(refreshed.message_count(), 2);+}++#[test]+fn an_unwritable_layout_cache_does_not_block_transcript_reads() {+ let dir = tempdir().unwrap();+ let messages = vec![message(+ "large",+ &"可读🙂".repeat(LAYOUT_CACHE_MIN_LEN as usize / 6),+ )];+ write_transcript(dir.path(), "layout-regression", CREATED_AT, &messages).unwrap();+ let cache = layout_cache_path(dir.path(), "layout-regression").unwrap();+ fs::create_dir_all(cache.with_extension("layout.tmp")).unwrap();++ let layout =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap();+ assert_eq!(layout.message_count(), 1);+ let read =+ read_transcript_window_with_layout(dir.path(), "layout-regression", &layout, 0, None)+ .unwrap();+ assert_messages(&read.messages, &messages);+ assert!(!cache.exists());+}+#[test]fn remove_session_files_cleans_up_layout_cache_and_tmp() {let dir = tempdir().unwrap();diff --git a/docs/adr/0120-bounded-session-history-windows.md b/docs/adr/0120-bounded-session-history-windows.mdindex 5548ceeb5..776895be4 100644--- a/docs/adr/0120-bounded-session-history-windows.md+++ b/docs/adr/0120-bounded-session-history-windows.md@@ -33,6 +33,16 @@ the full payload had already crossed the process boundary.4. The uncapped default remains available to non-renderer callers, so modelreconstruction and persistence semantics do not depend on UI pagination.+The original implementation scanned the transcript sequentially to find a+requested window. It now keeps a disposable per-session layout of physical+message and compaction line offsets, with a versioned disk cache when the+filesystem provides a reliable file identity. Appends extend the layout; an+atomic transcript rewrite invalidates both cache layers. A cache is an+optimization only: old or invalid formats rebuild from the JSONL source, and+the bounded read can perform one full rebuild and retry after detecting an+invalid indexed boundary. This does not change the JSONL format, SQLite schema,+RPC contract or the bounded-window decision above.+## Alternatives considered- **Only virtualize the message list:** rejected because the expensive fulldiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex f2683181d..410912593 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -132,8 +132,9 @@ to an absolute path before it reaches host-core as a child-process variable.├── pi.sqlite.v9.bak # exact readable backup before v9→v15 destructive work├── pi.sqlite.v10.bak # exact readable backup before v10→v15 destructive work├── sessions/ # transcript file store (D119) — host-core only- │ ├── <sessionId>.jsonl # live transcript (header + messages)- │ ├── <sessionId>.revisions.jsonl # regenerate branches, append-only+│ ├── <sessionId>.jsonl # live transcript (header + messages)+│ ├── <sessionId>.jsonl.layout # disposable, versioned byte-offset cache+│ ├── <sessionId>.revisions.jsonl # regenerate branches, append-only│ └── <sessionId>.inflight.json # streaming reply checkpoint (D299), transient├── secrets/ # encrypted secret blobs + .machine-key (unchanged)├── config-sync/ # encrypted sync base/pending bundles — host-core only@@ -1415,16 +1416,36 @@ relationship or index. The renderer's unified reading view is shared by ordinaryhistory and search; it never becomes canonical mutation or model input.A bounded window is served through a per-session **transcript layout**: the byte-offset of every message and compaction line, plus the file length those offsets-were recorded against. Serving a window then seeks to its first selected line-instead of parsing the history in front of it, so the cost of opening a session-is proportional to the window rather than to the conversation. Consequences:--- The layout is derived data, cached in memory and rebuilt by scanning the file.- `file_len` is its validity token: the transcript is append-only between atomic- rewrites, so a longer file is scanned from the previous end and a shorter or- replaced file is rescanned in full. Every rewrite and delete path also drops- the cached entry, because a rewrite can land on an identical length.+offset of every message and compaction line, plus the file identity and complete+prefix length those offsets describe. Serving a window seeks to its first+selected line instead of parsing the history in front of it, so the common+cached read is proportional to the requested page. Consequences:++- The layout is derived data, cached in memory and, when reliable file identity+ is available, in the sibling `<sessionId>.jsonl.layout` file. Unix uses the+ device and inode; Windows uses the volume serial number and file ID. If the+ filesystem cannot provide a reliable identity, the host skips the disk cache+ and scans the transcript normally.+- The disk cache has an explicit format version and validates its identity,+ checksum, counts, globally increasing in-range offsets, and the complete-line+ prefix before reuse. Missing, old, unknown, corrupt, or mismatched caches are+ ignored and rebuilt from the JSONL source. Cache read/write failures are+ diagnostic only and do not make the session unreadable.+- A matching identity and complete prefix permits append-only incremental+ scanning. A transcript rewrite invalidates both in-memory and disk layouts+ only after its atomic replacement succeeds; delete also removes both. Cache+ invalidation stays in transcript rewrite/delete ownership, not the generic+ atomic-swap helper used by unrelated files.+- A point read that finds an invalid indexed line boundary drops both cache+ layers, scans the complete transcript without consulting the disk cache, and+ retries once with message counts, page ranges, and message location recomputed+ from the rebuilt layout. A real JSON, UTF-8, or I/O error from that complete+ scan remains an error; the transcript is never rewritten or repaired by+ replacing bytes or skipping messages.+- New cache files use a nonnumeric version header that older parsers safely+ reject and rebuild. Downgrading to an older app preserves the transcript and+ database, though that app's own cache defect may recur. No database or+ transcript migration is involved.- A torn trailing line (crash mid-append) is excluded from both the offsets and`file_len`, so a later refresh picks it up once the writer completes it.- Line classification reads the `type` discriminator with a single depth-awarediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 49dd42b47..76d9ab096 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1848,7 +1848,11 @@ identify the platform validation still needed.visible transcript frame and renderer responsiveness. 2) Scroll to the topof the transcript. 3) Repeat the open/close cycle after the session has beencached. 4) Inspect the host request/response or test fixture for the session- read window.+ read window. 5) In an isolated Host profile, create a transcript above the+ layout-cache threshold, append more rows, settle a middle Task result with a+ longer value, then restart with a legacy layout file beside the transcript.+ 6) Read the newest page, page to the beginning, locate a nested message and+ its owning Task, then read the complete history.- **Expected**: Opening paints the newest bounded page without transferringthe complete 50 MB value to the renderer. The large value is visibly markedas truncated for display while the transcript and model-facing read remain@@ -1858,13 +1862,17 @@ identify the platform validation still needed.historical row before the latest messages become usable. Edit, delete,revision, and Stop operations rehydrate the full transcript before anyrewrite, so older messages are never lost because only a window was visible.+ The isolated Host journey returns every message once and in order after the+ middle rewrite, legacy-cache rejection and restart; the Task result is+ terminal, nested-message navigation resolves its owning Task, and paging+ reaches the beginning without a UTF-8 error or omitted row.- **Specs linked**: `03-runtime/01-ipc-protocol.md`,`03-runtime/04-data-storage.md`, `03-runtime/06-host-rpc-protocol.md`,ADR 0120- **Acceptance**: C (session open and scroll), F (persistence), Quality- **Milestone**: M5-- **Status**: Source-level regression covered; full large-fixture Electron- journey Draft+- **Status**: Source-level and isolated Host RPC cache regressions covered;+ full large-fixture Electron journey Draft#### E2E-011a: New session while another session is still streamingdiff --git a/package.json b/package.jsonindex 99f061716..7cf2b1123 100644--- a/package.json+++ b/package.json@@ -28,6 +28,7 @@"test:e2e:keep-awake": "node scripts/e2e-keep-awake.mjs","test:e2e:live-voice": "node scripts/e2e-live-voice.mjs","test:e2e:rpc-unicode": "node scripts/e2e-rpc-unicode.mjs",+ "test:e2e:transcript-cache": "node scripts/e2e-transcript-cache.mjs","test:e2e:plan": "node scripts/e2e-plan.mjs","test:e2e:plan-history": "node scripts/e2e-plan-history.mjs","test:e2e:plan-ui": "node scripts/e2e-plan-ui.mjs",diff --git a/scripts/README.md b/scripts/README.mdindex 0ae5da379..649663c0f 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -54,6 +54,7 @@ The scenarios are specified in| `e2e-tool-admission.mjs` | `node scripts/e2e-tool-admission.mjs` | Isolated real-host tool admission: queued Bash burst leaves capacity for another session's Read/Write and recovers all counters || `e2e-smoke.mjs` | `pnpm test:e2e` | Protocol-level E2E against host-core, plus an optional live model || `e2e-plan.mjs` | `pnpm test:e2e:plan` | Plan state, checkpoint artifact, and approval transitions |+| `e2e-transcript-cache.mjs` | `pnpm test:e2e:transcript-cache` | Isolated Host RPC regression for large transcript cache creation, append plus middle Task rewrite, legacy cache recovery, paging, message navigation, tool results, and process restart || `e2e-plan-ui.mjs` | `pnpm test:e2e:plan-ui` | Plan approval through the rendered UI || `e2e-electron-boot.mjs` | `pnpm test:e2e:boot` | Electron boot probe || `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` |diff --git a/scripts/e2e-transcript-cache.mjs b/scripts/e2e-transcript-cache.mjsnew file mode 100644index 000000000..2c039b7f7--- /dev/null+++ b/scripts/e2e-transcript-cache.mjs@@ -0,0 +1,249 @@+#!/usr/bin/env node+/** Transcript layout cache recovery through an isolated real Host process. */+import assert from "node:assert/strict";+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++const temp = await mkdtemp(join(tmpdir(), "pi-transcript-layout-"));+const dataDir = join(temp, "data");+const workspace = join(temp, "workspace");+const host = new Host(resolveHostBinary(), dataDir, {+ env: {+ OPENAI_API_KEY: "",+ ANTHROPIC_API_KEY: "",+ GOOGLE_API_KEY: "",+ OPENROUTER_API_KEY: "",+ PI_DESKTOP_TEST_API_KEY: "",+ PI_DESKTOP_TEST_BASE_URL: "",+ PI_DESKTOP_TEST_MODEL: "",+ },+});++const createdAt = "2026-10-11T00:00:00.000Z";+const firstBatch = 230;+const totalMessages = 320;+const messages = [];++function bytesAndOffsets(raw) {+ const offsets = { message: [], compaction: [] };+ let offset = 0;+ for (const line of raw.toString("utf8").split(/(?<=\n)/)) {+ if (!line) continue;+ const value = JSON.parse(line);+ if (value.type === "message") offsets.message.push(offset);+ if (value.type === "compaction") offsets.compaction.push(offset);+ offset += Buffer.byteLength(line);+ }+ return { fileLength: offset, offsets };+}++function writeLegacyLayout(fileLength, offsets) {+ const path = join(dataDir, "sessions", `${sessionId}.jsonl.layout`);+ const rows = [+ `0 ${fileLength}`,+ `${offsets.message.length} ${offsets.compaction.length}`,+ offsets.message.join(" "),+ offsets.compaction.join(" "),+ ];+ return writeFile(path, `${rows.join("\n")}\n`, "utf8");+}++function textMessage(index) {+ return {+ id: `message-${String(index).padStart(3, "0")}`,+ role: "user",+ content: `合成会话 ${index} 🙂 `.repeat(800),+ createdAt,+ status: "complete",+ };+}++function taskMessage(result, suffix = "") {+ return {+ id: "task-middle",+ role: "tool",+ content: `Task result ${suffix}`,+ createdAt,+ toolName: "Task",+ toolCallId: "task-middle-call",+ toolArgs: { agent: "explorer" },+ toolResult: result,+ toolStatus: "success",+ };+}++async function append(sessionId, message) {+ await host.call("session.appendMessage", { sessionId, message });+ messages.push(message);+}++async function readLatest(sessionId) {+ const { session } = await host.call("session.get", {+ id: sessionId,+ messageLimit: 100,+ contentLimit: 20_000,+ });+ assert.ok(session);+ return session;+}++let sessionId;+try {+ await mkdir(workspace, { recursive: true });+ await host.start();+ const created = await host.call("session.create", {+ title: "Transcript layout cache regression",+ mode: "agent",+ projectPath: workspace,+ });+ sessionId = created.session.id;++ for (let index = 0; index < firstBatch; index += 1) {+ if (index === 150) {+ await append(sessionId, taskMessage({+ details: { delegationId: "delegate-middle", status: "running" },+ }));+ } else if (index === 151) {+ await append(sessionId, {+ id: "nested-child",+ role: "assistant",+ content: "子任务结果 🙂",+ createdAt,+ parentToolCallId: "task-middle-call",+ });+ } else {+ await append(sessionId, textMessage(index));+ }+ }++ const initial = await readLatest(sessionId);+ assert.equal(initial.messages.length, 100);+ const transcriptPath = join(dataDir, "sessions", `${sessionId}.jsonl`);+ const initialBytes = await readFile(transcriptPath);+ assert.ok(initialBytes.byteLength > 2 * 1024 * 1024, "fixture must cross the disk-cache threshold");+ const initialLayout = bytesAndOffsets(initialBytes);+ const layoutPath = join(dataDir, "sessions", `${sessionId}.jsonl.layout`);+ let hasDiskCache = false;+ try {+ const cache = await readFile(layoutPath, "utf8");+ assert.ok(cache.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 2\n"));+ hasDiskCache = true;+ } catch (error) {+ if (error.code !== "ENOENT") throw error;+ }++ for (let index = firstBatch; index < totalMessages; index += 1) {+ await append(sessionId, textMessage(index));+ }+ const appendedSize = (await stat(transcriptPath)).size;+ assert.ok(appendedSize > initialLayout.fileLength, "append should leave the transcript longer than the cached prefix");++ const terminalTask = taskMessage({+ details: {+ delegationId: "delegate-middle",+ status: "completed",+ result: "最终结果 中文🙂 ".repeat(600),+ },+ }, "终态回写 中文🙂 ".repeat(600));+ await host.call("session.appendMessage", { sessionId, message: terminalTask });+ messages[150] = terminalTask;+ const rewrittenSize = (await stat(transcriptPath)).size;+ assert.ok(rewrittenSize > appendedSize, "terminal Task update must grow the rewritten transcript");+ assert.ok(rewrittenSize > initialLayout.fileLength, "rewritten transcript must remain longer than the old cached prefix");++ const latestInProcess = await readLatest(sessionId);+ assert.deepEqual(+ latestInProcess.messages.map((message) => message.id),+ messages.slice(-100).map((message) => message.id),+ );+ const settledTask = await host.call("session.get", {+ id: sessionId,+ messageAround: "task-middle",+ messageLimit: 20,+ });+ assert.equal(+ settledTask.session.messages.find((message) => message.id === "task-middle").toolResult.details.status,+ "completed",+ );++ // A legacy zero-identity cache is deliberately restored to model an older+ // installation leaving its disposable index beside the unchanged JSONL.+ await writeLegacyLayout(initialLayout.fileLength, initialLayout.offsets);+ await host.restart();++ const latestAfterRestart = await readLatest(sessionId);+ assert.deepEqual(+ latestAfterRestart.messages.map((message) => message.id),+ messages.slice(-100).map((message) => message.id),+ );+ const taskAfterRestart = await host.call("session.get", {+ id: sessionId,+ messageAround: "task-middle",+ messageLimit: 20,+ });+ assert.equal(+ taskAfterRestart.session.messages.find((message) => message.id === "task-middle").toolResult.details.status,+ "completed",+ );++ const allIds = [];+ let before;+ while (true) {+ const { session } = await host.call("session.get", {+ id: sessionId,+ messageLimit: 100,+ ...(before === undefined ? {} : { messageBefore: before }),+ });+ const pageIds = session.messages.map((message) => message.id);+ allIds.unshift(...pageIds);+ if (session.messageStart === 0) break;+ assert.equal(session.hasMoreBefore, true);+ before = session.messageStart;+ }+ assert.deepEqual(allIds, messages.map((message) => message.id));++ const around = await host.call("session.get", {+ id: sessionId,+ messageAround: "nested-child",+ messageLimit: 20,+ });+ assert.ok(around.session.messages.some((message) => message.id === "nested-child"));+ assert.equal(around.session.navigationParent?.id, "task-middle");+ assert.equal(around.session.navigationParent?.toolResult?.details?.status, "completed");++ const full = await host.call("session.get", { id: sessionId });+ assert.deepEqual(full.session.messages.map((message) => message.id), messages.map((message) => message.id));+ assert.equal(full.session.messages.find((message) => message.id === "task-middle").toolResult.details.status, "completed");+ for (let index = 0; index < messages.length; index += 1) {+ const expected = messages[index];+ const actual = full.session.messages[index];+ if (expected.id === "task-middle") {+ assert.equal(actual.toolResult.details.result, expected.toolResult.details.result);+ } else {+ assert.equal(actual.content, expected.content, `content changed for ${expected.id}`);+ }+ }++ await host.restart();+ const reused = await readLatest(sessionId);+ assert.deepEqual(+ reused.messages.map((message) => message.id),+ messages.slice(-100).map((message) => message.id),+ );+ let rebuiltCache;+ try {+ rebuiltCache = await readFile(layoutPath, "utf8");+ } catch (error) {+ if (error.code !== "ENOENT") throw error;+ }+ if (hasDiskCache) {+ assert.ok(rebuiltCache?.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 2\n"));+ }++ console.log("PASS transcript cache: append, middle Task rewrite, legacy cache recovery, paging, message navigation, tool result and Host restart");+} finally {+ await host.stop();+ await rm(temp, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });+}