Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
perf(host-core): keep per-turn revision saves off the full transcript
zszz3914559a2b0b3
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex aca114058..08d5aba39 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -10,6 +10,8 @@ use std::collections::HashMap;use crate::transcripts::{self, CompactionRecord, MessageRecord, RevisionRecord};+#[cfg(test)]+mod active_revision_tests;mod fork_files;mod history_mutations;pub use history_mutations::{@@ -2119,7 +2121,9 @@ pub fn configure_session_with_mode_snapshot(if changed == 0 {return Ok(None);}- Ok(get_session(db, id)?.map(|detail| detail.summary))+ // Only the summary goes back; reading it through `get_session` parsed the+ // whole transcript on every model, mode or permission switch.+ session_summary(db, id)}pub fn delete_session(db: &Database, id: &str) -> Result<bool> {@@ -3662,10 +3666,15 @@ pub fn save_active_branch_revision(db: &Database,session_id: &str,) -> Result<Option<ActiveRevisionSave>> {- let Some(detail) = get_session(db, session_id)? else {+ // This runs after every turn. A session that was never regenerated owns no+ // revision rows, and every path that stamps a root writes its rows first,+ // so the index answers it without touching the transcript.+ if !session_has_revisions(db, session_id)? {+ return Ok(None);+ }+ let Some(mut messages) = revision_root_window(db, session_id)? else {return Ok(None);};- let mut messages = detail.messages;let Some(root_index) = messages.iter().rposition(|message| message.role == "user" && message.revision_count.is_some())@@ -3709,11 +3718,23 @@ pub fn save_active_branch_revision(}let root = &mut messages[root_index];- root.revision_root_id = Some(root_user_id.clone());- root.revision_count = Some(total);- root.active_revision = Some(active);- let (record, _) = ui_to_record(root);- transcripts::update_message(db.data_dir(), session_id, &record)?;+ let stamp = (Some(root_user_id.clone()), Some(total), Some(active));+ let stamped = (+ root.revision_root_id.clone(),+ root.revision_count,+ root.active_revision,+ ) == stamp;+ (+ root.revision_root_id,+ root.revision_count,+ root.active_revision,+ ) = stamp;+ // Once the branch has its stamp, later turns leave it unchanged. The root is+ // rarely the last line, so restating it would scan and copy the whole file.+ if !stamped {+ let (record, _) = ui_to_record(root);+ transcripts::update_message(db.data_dir(), session_id, &record)?;+ }Ok(Some(ActiveRevisionSave {root_user_id,revision_count: total,@@ -3723,6 +3744,57 @@ pub fn save_active_branch_revision(}))}+fn session_has_revisions(db: &Database, session_id: &str) -> Result<bool> {+ Ok(db.conn().query_row(+ "SELECT EXISTS(SELECT 1 FROM message_revisions WHERE session_id = ?1)",+ params![session_id],+ |row| row.get(0),+ )?)+}++/// The newest messages of a session, as the full read lists them, reaching back+/// to the latest user row that carries revision metadata (every message when+/// none does). `None` when the session does not exist.+///+/// The root usually sits a few turns from the end while the transcript can hold+/// hundreds of megabytes, so this reads an id-closed suffix: positions and+/// keep-last contents inside it match the full read, and so does the branch.+fn revision_root_window(db: &Database, session_id: &str) -> Result<Option<Vec<UiMessage>>> {+ if !session_exists(db, session_id)? {+ return Ok(None);+ }+ // The record-level form of `role == "user" && revision_count.is_some()`,+ // which is how `save_active_branch_revision` picks the root.+ let carries_root = |record: &MessageRecord| {+ record.role == "user"+ && record+ .meta+ .as_ref()+ .and_then(|meta| meta.get("revisionCount"))+ .and_then(Value::as_i64)+ .is_some()+ };+ let suffix = transcripts::read_closed_message_suffix(db.data_dir(), session_id, |records| {+ // Keep-last: only an id's newest line decides what it carries.+ let mut seen = std::collections::HashSet::new();+ records+ .iter()+ .rev()+ .filter(|record| seen.insert(record.id.as_str()))+ .any(carries_root)+ })?;+ let records = match suffix {+ Some(records) => records,+ None => transcripts::read_transcript_with_compactions(db.data_dir(), session_id)?.messages,+ };+ Ok(Some(+ dedupe_records(records)+ .into_iter()+ .map(record_to_ui)+ .collect(),+ ))+}+/// Activate a stored revision: replace the live transcript with prefix + branch./// `prefix` is every message before the root user turn, as the renderer sees/// it; the durable transcript wins over it whenever the family is found there.@@ -3935,7 +4007,19 @@ pub fn import_session(if exists > 0 {return Ok(false);}- let (records, texts) = records_and_texts(messages);+ // An import brings no regenerate history, so a pager stamp it carries would+ // name revisions that do not exist. Forks drop the stamp the same way.+ let messages: Vec<UiMessage> = messages+ .iter()+ .cloned()+ .map(|mut message| {+ message.revision_root_id = None;+ message.revision_count = None;+ message.active_revision = None;+ message+ })+ .collect();+ let (records, texts) = records_and_texts(&messages);transcripts::write_transcript(db.data_dir(), &summary.id, &summary.created_at, &records)?;let indexed = (|| -> Result<()> {let tx = conn.unchecked_transaction()?;@@ -7882,6 +7966,8 @@ mod tests {root.revision_count = Some(1);root.active_revision = Some(1);append_message(&db, &session.id, &root, Some(&turn)).unwrap();+ // Regenerate writes a family's revision rows before it stamps the root.+ save_message_revision(&db, &session.id, "u1", &[root.clone()], true).unwrap();// Ten finished turns, each appending a sizeable answer, each archived// exactly the way a real turn ends.@@ -7972,6 +8058,8 @@ mod tests {root.revision_count = Some(1);root.active_revision = Some(1);append_message(&db, &session.id, &root, Some(&turn)).unwrap();+ // Regenerate writes a family's revision rows before it stamps the root.+ save_message_revision(&db, &session.id, "u1", &[root.clone()], true).unwrap();let mut answer = user_msg("a1", "the answer", "2025-05-01T00:01:00Z");answer.role = "assistant".into();append_message(&db, &session.id, &answer, Some(&turn)).unwrap();@@ -8022,6 +8110,8 @@ mod tests {first.revision_count = Some(1);first.active_revision = Some(1);append_message(&db, &session.id, &first, Some(&turn)).unwrap();+ // Regenerate writes a family's revision rows before it stamps the root.+ save_message_revision(&db, &session.id, "u1", &[first.clone()], true).unwrap();let mut first_answer = user_msg("a1", "first answer", "2025-05-01T00:00:01Z");first_answer.role = "assistant".into();append_message(&db, &session.id, &first_answer, Some(&turn)).unwrap();@@ -8033,6 +8123,7 @@ mod tests {second.revision_count = Some(1);second.active_revision = Some(1);append_message(&db, &session.id, &second, Some(&turn)).unwrap();+ save_message_revision(&db, &session.id, "u2", &[second.clone()], true).unwrap();let mut second_answer = user_msg("a2", "second answer", "2025-05-01T00:01:01Z");second_answer.role = "assistant".into();append_message(&db, &session.id, &second_answer, Some(&turn)).unwrap();diff --git a/crates/host-core/src/sessions/active_revision_tests.rs b/crates/host-core/src/sessions/active_revision_tests.rsnew file mode 100644index 000000000..c51cbe361--- /dev/null+++ b/crates/host-core/src/sessions/active_revision_tests.rs@@ -0,0 +1,156 @@+//! The per-turn revision save and the session configure call run on every turn+//! and every model or mode switch, so neither may cost a read of the whole+//! transcript; and reading less must not change what they decide.++use super::*;++fn fixture() -> (tempfile::TempDir, Database, String) {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("test.sqlite")).unwrap();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ (dir, db, session.id)+}++fn message(id: &str, role: &str, text: &str) -> UiMessage {+ serde_json::from_value(json!({+ "id": id, "role": role, "content": text, "createdAt": "2026-11-14T00:00:00Z"+ }))+ .unwrap()+}++/// `count` finished exchanges of ordinary history.+fn history(db: &Database, session: &str, count: usize) {+ for index in 0..count {+ append_message(+ db,+ session,+ &message(&format!("q{index}"), "user", "question"),+ None,+ )+ .unwrap();+ append_message(+ db,+ session,+ &message(&format!("r{index}"), "assistant", "answer"),+ None,+ )+ .unwrap();+ }+}++/// A regenerated user turn as `truncate_from` leaves it: the discarded variant+/// stored as revision 1, then the new prompt stamped as revision 2 of 2.+fn regenerated_root(db: &Database, session: &str, id: &str) -> UiMessage {+ let discarded = [+ message(id, "user", "first try"),+ message("old", "assistant", "dropped"),+ ];+ save_message_revision(db, session, id, &discarded, false).unwrap();+ let mut root = message(&format!("{id}-v2"), "user", "second try");+ root.revision_root_id = Some(id.into());+ root.revision_count = Some(2);+ root.active_revision = Some(2);+ append_message(db, session, &root, None).unwrap();+ root+}++fn stored_root(db: &Database, session: &str, id: &str) -> UiMessage {+ get_session(db, session)+ .unwrap()+ .unwrap()+ .messages+ .into_iter()+ .find(|message| message.id == id)+ .unwrap()+}++#[test]+fn turn_end_and_configure_skip_the_transcript_of_a_session_never_regenerated() {+ let (_dir, db, session) = fixture();+ history(&db, &session, 200);+ transcripts::take_whole_file_reads();++ assert!(save_active_branch_revision(&db, &session)+ .unwrap()+ .is_none());+ let summary = configure_session(&db, &session, "plan", None, None)+ .unwrap()+ .unwrap();+ assert_eq!(summary.mode, "plan");+ assert_eq!(transcripts::take_whole_file_reads(), 0);+}++#[test]+fn later_turns_on_a_regenerated_branch_read_only_the_branch() {+ let (_dir, db, session) = fixture();+ history(&db, &session, 300);+ regenerated_root(&db, &session, "u1");+ append_message(&db, &session, &message("a1", "assistant", "answer"), None).unwrap();+ let first = save_active_branch_revision(&db, &session).unwrap().unwrap();+ assert!(first.archived);+ assert_eq!((first.revision_count, first.active_revision), (2, 2));++ // The next turns on the same branch: the stamp is already right.+ for turn in 0..3 {+ append_message(+ &db,+ &session,+ &message(&format!("p{turn}"), "user", "more"),+ None,+ )+ .unwrap();+ append_message(+ &db,+ &session,+ &message(&format!("x{turn}"), "assistant", "ok"),+ None,+ )+ .unwrap();+ transcripts::take_whole_file_reads();+ let saved = save_active_branch_revision(&db, &session).unwrap().unwrap();+ assert_eq!(transcripts::take_whole_file_reads(), 0, "turn {turn}");+ assert!(!saved.archived);+ assert_eq!(saved.root_user_id, "u1");+ assert_eq!((saved.revision_count, saved.active_revision), (2, 2));+ assert_eq!(saved.root.id, "u1-v2");+ }+ let revisions = list_message_revisions(&db, &session, "u1").unwrap();+ let live = revisions+ .iter()+ .find(|revision| revision.revision_index == 2)+ .unwrap();+ assert_eq!(+ live.message_count, 8,+ "root, its answer and three exchanges"+ );+ let root = stored_root(&db, &session, "u1-v2");+ assert_eq!(+ (root.revision_count, root.active_revision),+ (Some(2), Some(2))+ );+}++#[test]+fn an_imported_pager_stamp_is_dropped_because_no_revisions_come_with_it() {+ let (_dir, db, session) = fixture();+ let mut summary = session_summary(&db, &session).unwrap().unwrap();+ summary.id = "import-pi-stamped".into();+ let mut root = message("u1", "user", "question");+ root.revision_root_id = Some("u0".into());+ root.revision_count = Some(3);+ root.active_revision = Some(3);+ assert!(import_session(&db, &summary, &[root, message("a1", "assistant", "answer")]).unwrap());++ let imported = stored_root(&db, "import-pi-stamped", "u1");+ assert_eq!(+ (+ imported.revision_root_id,+ imported.revision_count,+ imported.active_revision+ ),+ (None, None, None)+ );+ assert!(save_active_branch_revision(&db, "import-pi-stamped")+ .unwrap()+ .is_none());+}diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rsindex e42974be2..eafa038b9 100644--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@ -41,9 +41,13 @@ mod binary_storage_tests;pub mod layout;#[cfg(test)]mod review_state_tests;+mod suffix;+#[cfg(test)]+mod suffix_tests;#[cfg(test)]use layout::refresh_layout;pub use layout::TranscriptLayout;+pub use suffix::read_closed_message_suffix;/// Bumped when the line format changes shape incompatibly.pub const TRANSCRIPT_SCHEMA: i64 = 2;@@ -425,6 +429,15 @@ fn read_layout_line(#[cfg(test)]thread_local! {static LAYOUT_LINE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+ static WHOLE_FILE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}++/// Reads of every message line — the full read, and the rewrite in+/// `update_message` — on this thread since the last call. Tests use it to pin+/// paths that must stay independent of history length.+#[cfg(test)]+pub(crate) fn take_whole_file_reads() -> usize {+ WHOLE_FILE_READS.with(|reads| reads.replace(0))}/// Whether a JSON string for this value is the value itself.@@ -1248,6 +1261,8 @@ pub fn read_transcript_with_compactions(data_dir: &Path,session_id: &str,) -> Result<TranscriptRead> {+ #[cfg(test)]+ WHOLE_FILE_READS.with(|reads| reads.set(reads.get() + 1));read_transcript_window(data_dir, session_id, 0, None)}@@ -1363,6 +1378,8 @@ pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord)return Ok(true);}}+ #[cfg(test)]+ WHOLE_FILE_READS.with(|reads| reads.set(reads.get() + 1));let raw = match fs::read(&path) {Ok(bytes) => match String::from_utf8(bytes) {Ok(raw) => raw,diff --git a/crates/host-core/src/transcripts/suffix.rs b/crates/host-core/src/transcripts/suffix.rsnew file mode 100644index 000000000..7697eb330--- /dev/null+++ b/crates/host-core/src/transcripts/suffix.rs@@ -0,0 +1,121 @@+//! Read the end of a transcript without reading the whole file.+//!+//! A reader that only needs the newest records still has to see them as the+//! full read would: deduplicated keep-last by id, each id at the position of+//! its *first* line. A suffix gives that answer only when no id in it also+//! appears before it, so the suffix is widened until it is closed under ids.+//! Then the full deduplicated list is the prefix's list followed by the+//! suffix's, and anything the caller derives from the suffix matches the full+//! read exactly.++use std::collections::HashMap;+use std::path::Path;++use anyhow::Result;++use super::layout::{self, InvalidLayoutBoundary, TranscriptLayout};+use super::{read_transcript_window_with_layout, MessageRecord};++/// First chunk read from the end. Each further step doubles, so a reader whose+/// answer sits N lines from the end reads O(N) lines in O(log N) steps.+const FIRST_CHUNK: usize = 8;++/// The message records (in file order, not deduplicated) of the shortest+/// id-closed suffix for which `enough` answers true, or of the whole+/// transcript when no suffix does.+///+/// `None` means the layout cannot prove closure — an unreadable identity, or a+/// line the indexed reader rejects where the full reader would skip it — and+/// the caller must use the full read instead.+pub fn read_closed_message_suffix(+ data_dir: &Path,+ session_id: &str,+ mut enough: impl FnMut(&[MessageRecord]) -> bool,+) -> Result<Option<Vec<MessageRecord>>> {+ layout::with_layout_recovery(data_dir, session_id, |layout| {+ read_suffix_with_layout(data_dir, session_id, layout, &mut enough)+ })+}++fn read_suffix_with_layout(+ data_dir: &Path,+ session_id: &str,+ layout: &TranscriptLayout,+ enough: &mut impl FnMut(&[MessageRecord]) -> bool,+) -> Result<Option<Vec<MessageRecord>>> {+ let Some(first_line) = first_line_by_id(layout) else {+ return Ok(None);+ };+ let total = layout.message_count();+ // Chunks are read newest-first; `suffix` is kept in file order.+ let mut suffix: Vec<MessageRecord> = Vec::new();+ let mut start = total;+ let mut chunk = FIRST_CHUNK;+ while start > 0 {+ let wanted = start.saturating_sub(chunk);+ let next = close_under_ids(layout, &first_line, wanted, start);+ let read = match read_transcript_window_with_layout(+ data_dir,+ session_id,+ layout,+ next,+ Some(start - next),+ ) {+ Ok(read) => read,+ // A stale layout is rebuilt by the caller's recovery and retried.+ Err(error) if error.is::<InvalidLayoutBoundary>() => return Err(error),+ Err(error) => {+ tracing::debug!(%error, "transcript suffix read fell back to the full read");+ return Ok(None);+ }+ };+ if read.messages.len() != start - next {+ // The indexed reader skipped a line (torn UTF-8). The full reader+ // decides those differently, so do not guess.+ return Ok(None);+ }+ let mut widened = read.messages;+ widened.append(&mut suffix);+ suffix = widened;+ start = next;+ if enough(&suffix) {+ break;+ }+ chunk = chunk.saturating_mul(2);+ }+ Ok(Some(suffix))+}++/// Physical line of each id's first occurrence; `None` when any message line+/// has no readable identity, because closure cannot be proven for it.+fn first_line_by_id(layout: &TranscriptLayout) -> Option<HashMap<&str, usize>> {+ let mut first = HashMap::with_capacity(layout.message_ids.len());+ for (line, id) in layout.message_ids.iter().enumerate() {+ first.entry(id.as_deref()?).or_insert(line);+ }+ Some(first)+}++/// Lowest start `<= wanted` such that every id on lines `[start, total)` first+/// occurs at or after `start`. Lines `[old_start, total)` are already closed,+/// so only the newly added lines can pull the start earlier.+fn close_under_ids(+ layout: &TranscriptLayout,+ first_line: &HashMap<&str, usize>,+ wanted: usize,+ old_start: usize,+) -> usize {+ let mut start = wanted;+ let mut scanned_from = old_start;+ while scanned_from > start {+ let lowest = layout.message_ids[start..scanned_from]+ .iter()+ .filter_map(|id| id.as_deref().and_then(|id| first_line.get(id)))+ .copied()+ .min()+ .unwrap_or(start);+ scanned_from = start;+ start = start.min(lowest);+ }+ start+}diff --git a/crates/host-core/src/transcripts/suffix_tests.rs b/crates/host-core/src/transcripts/suffix_tests.rsnew file mode 100644index 000000000..576b0a168--- /dev/null+++ b/crates/host-core/src/transcripts/suffix_tests.rs@@ -0,0 +1,71 @@+use super::*;+use serde_json::json;+use tempfile::tempdir;++const CREATED_AT: &str = "2026-11-14T00:00:00Z";++fn message(id: &str, text: &str) -> MessageRecord {+ MessageRecord {+ id: id.into(),+ role: "assistant".into(),+ tool_name: None,+ is_error: false,+ blocks: json!([{ "type": "text", "text": text }]),+ meta: None,+ created_at: CREATED_AT.into(),+ }+}++fn write_lines(dir: &std::path::Path, records: &[MessageRecord]) {+ write_transcript(dir, "s1", CREATED_AT, records).unwrap();+}++#[test]+fn the_suffix_widens_until_no_id_in_it_also_appears_before_it() {+ let dir = tempdir().unwrap();+ let mut records = (0..300)+ .map(|index| message(&format!("m{index}"), "first"))+ .collect::<Vec<_>>();+ // A later line restates m5: the full read keeps it at position 5 with the+ // newer content, so a suffix starting after line 5 would misplace it.+ records.push(message("m5", "restated"));+ write_lines(dir.path(), &records);++ let suffix = read_closed_message_suffix(dir.path(), "s1", |_| true)+ .unwrap()+ .unwrap();+ assert_eq!(suffix.len(), records.len() - 5);+ assert_eq!(suffix.first().unwrap().id, "m5");+ assert_eq!(suffix.last().unwrap().blocks[0]["text"], "restated");++ // Chained restatements are followed to the earliest first line.+ let mut chained = (0..300)+ .map(|index| message(&format!("m{index}"), "first"))+ .collect::<Vec<_>>();+ chained.push(message("m200", "again"));+ chained[250] = message("m3", "restated early");+ write_lines(dir.path(), &chained);+ let suffix = read_closed_message_suffix(dir.path(), "s1", |records| {+ records.iter().any(|record| record.id == "m200")+ })+ .unwrap()+ .unwrap();+ assert_eq!(suffix.first().unwrap().id, "m3");+ assert_eq!(suffix.len(), chained.len() - 3);+}++#[test]+fn a_line_without_a_readable_identity_leaves_the_decision_to_the_full_read() {+ let dir = tempdir().unwrap();+ let records = (0..10)+ .map(|index| message(&format!("m{index}"), "body"))+ .collect::<Vec<_>>();+ write_lines(dir.path(), &records);+ let path = transcript_path(dir.path(), "s1").unwrap();+ let text = std::fs::read_to_string(&path).unwrap();+ std::fs::write(&path, text.replacen("\"id\":\"m3\"", "\"id\":3", 1)).unwrap();++ assert!(read_closed_message_suffix(dir.path(), "s1", |_| true)+ .unwrap()+ .is_none());+}