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(storage): preserve tool images losslessly across host files
Seraph-xba51b924d8e5
diff --git a/apps/desktop/test/helpers/transcript-rewrite-harness.mjs b/apps/desktop/test/helpers/transcript-rewrite-harness.mjsnew file mode 100644index 000000000..b64f01bf3--- /dev/null+++ b/apps/desktop/test/helpers/transcript-rewrite-harness.mjs@@ -0,0 +1,65 @@+import assert from "node:assert/strict";+import * as fs from "node:fs";+import * as path from "node:path";+import ts from "typescript";+import * as shared from "../../../../packages/shared/dist/index.js";+import { PersistenceOutbox } from "../../electron/main/persistence-outbox.ts";++// Electron shell and unused importer/search services are external to these IPC+// operations. The handlers, rewrite fence, outbox and Host port remain real.+function load(relative, imports) {+ const file = new URL(relative, import.meta.url);+ const { outputText } = ts.transpileModule(fs.readFileSync(file, "utf8"), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+ fileName: file.pathname,+ });+ const module = { exports: {} };+ new Function("require", "exports", "module", outputText)((id) => {+ assert.ok(Object.hasOwn(imports, id), `unexpected IPC dependency: ${id}`);+ return imports[id];+ }, module.exports, module);+ return module.exports;+}++const { createSessionCoordination } = load("../../electron/main/runtime/session-coordination.ts", {+ "@pi-desktop/shared": shared,+ "../notification-policy": load("../../electron/main/notification-policy.ts", {}),+});+const { registerSessionIpc } = load("../../electron/main/ipc/session-ipc.ts", {+ electron: { shell: {} },+ "node:fs": fs,+ "node:path": path,+ "@pi-desktop/shared": shared,+ "../importers": {},+ "../services/session-collaboration": {},+ "../bootstrap/remote-hosts.js": {},+ "../services/session-search": {},+});++export function transcriptRewriteHarness(host, dataDir) {+ const handlers = new Map();+ const activeTurns = new Map();+ const coordination = createSessionCoordination({ activeTurns, getMainWindow: () => null, getViewingSessionId: () => null });+ const persistenceOutbox = new PersistenceOutbox(dataDir, () => undefined);+ registerSessionIpc({+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },+ getHost: () => host,+ getSidecar: () => null,+ dataDir,+ activeTurns,+ sessionProjects: new Map(),+ persistenceOutbox,+ logger: { app() {} },+ plugins: { broadcastEvent() {} },+ acquireSessionOperation: coordination.acquireSessionOperation,+ beginTranscriptRewrite: coordination.beginTranscriptRewrite,+ });+ return {+ persistenceOutbox,+ replace: (input) => handlers.get(shared.IPC.invoke.sessionReplaceMessages)(input),+ deleteMessage: (input) => handlers.get(shared.IPC.invoke.sessionDeleteMessage)(input),+ retractPendingPrompt: (input) => handlers.get(shared.IPC.invoke.sessionRetractPendingPrompt)(input),+ activateRevision: (input) => handlers.get(shared.IPC.invoke.sessionActivateRevision)(input),+ saveRevision: (input) => handlers.get(shared.IPC.invoke.sessionSaveRevision)(input),+ };+}diff --git a/crates/host-core/src/data_relocation.rs b/crates/host-core/src/data_relocation.rsindex 425aec6db..927824677 100644--- a/crates/host-core/src/data_relocation.rs+++ b/crates/host-core/src/data_relocation.rs@@ -85,6 +85,31 @@ impl Roots {_ => false,}}++ fn stored_record(&self, value: &mut Value) -> Result<bool> {+ if value.get("binaryStorage").is_none() {+ // Offline relocation must not upgrade a legacy profile's storage+ // without its database version gate. Preserve the old plain form.+ return Ok(self.structured(value));+ }+ let next = crate::transcripts::binary_storage::relocate(value.clone(), |record| {+ self.structured(record)+ })?;+ let changed = next != *value;+ *value = next;+ Ok(changed)+ }++ fn stored_queue(&self, value: &mut Value) -> Result<bool> {+ let Some(entries) = value.as_array_mut() else {+ anyhow::bail!("invalid relocation persistence queue");+ };+ let mut changed = false;+ for entry in entries {+ changed |= self.stored_record(entry)?;+ }+ Ok(changed)+ }}fn regular_file(path: &Path) -> Result<bool> {@@ -135,13 +160,20 @@ fn replace_file(path: &Path, write: impl FnOnce(&mut fs::File) -> Result<bool>)}fn rewrite_json(path: &Path, rewrite: impl FnOnce(&mut Value) -> bool) -> Result<()> {+ rewrite_json_checked(path, |value| Ok(rewrite(value)))+}++fn rewrite_json_checked(+ path: &Path,+ rewrite: impl FnOnce(&mut Value) -> Result<bool>,+) -> Result<()> {if !regular_file(path)? {return Ok(());}let mut value: Value =serde_json::from_slice(&fs::read(path)?).context("parse relocation metadata")?;replace_file(path, |output| {- let changed = rewrite(&mut value);+ let changed = rewrite(&mut value)?;if changed {serde_json::to_writer(output, &value)?;}@@ -171,7 +203,7 @@ fn rewrite_transcript(path: &Path, roots: &Roots) -> Result<()> {}Err(error) => return Err(error).context("parse relocation transcript"),};- if roots.structured(&mut value) {+ if roots.stored_record(&mut value)? {serde_json::to_writer(&mut *output, &value)?;if line.ends_with(b"\n") {output.write_all(b"\n")?;@@ -278,16 +310,20 @@ pub fn relocate(source: &Path, destination: &Path) -> Result<()> {.file_name().is_some_and(|name| name.to_string_lossy().ends_with(".inflight.json")) =>{- rewrite_json(&path, |value| roots.structured(value))?;+ rewrite_json_checked(&path, |value| roots.stored_record(value))?;}_ => {}}}}- rewrite_json(- &roots.destination.join("session-message-outbox.json"),- |value| roots.structured(value),- )?;+ for file in [+ "session-message-outbox.json",+ "session-message-outbox.dead-letter.json",+ ] {+ rewrite_json_checked(&roots.destination.join(file), |value| {+ roots.stored_queue(value)+ })?;+ }let capabilities = roots.destination.join("agent-capabilities");if regular_directory(&capabilities)? {for name in ["mcp", "skills", "subagents", "subagent-builtins"] {@@ -368,7 +404,7 @@ fn relocate_database(roots: &Roots) -> Result<()> {} else {roots.remap(&text).map(|path| {if table == "projects" {- crate::db::normalize_project_path(&path).unwrap_or(path)+ crate::db::canonical_project_path(&path).unwrap_or(path)} else {path}@@ -401,7 +437,7 @@ fn relocate_database(roots: &Roots) -> Result<()> {{roots.remap(&key)- .map(|path| crate::db::normalize_project_path(&path).unwrap_or(path))+ .map(|path| crate::db::canonical_project_path(&path).unwrap_or(path)).unwrap_or_else(|| key.clone())} else {key.clone()diff --git a/crates/host-core/src/data_relocation/tests.rs b/crates/host-core/src/data_relocation/tests.rsindex 8cfde59a5..f3756fe69 100644--- a/crates/host-core/src/data_relocation/tests.rs+++ b/crates/host-core/src/data_relocation/tests.rs@@ -198,7 +198,7 @@ fn relocates_a_real_copied_profile_without_recovery_or_changing_user_content() {.unwrap();assert_eq!(inside,- crate::db::normalize_project_path(&destination.join("project").to_string_lossy()).unwrap()+ crate::db::canonical_project_path(&destination.join("project").to_string_lossy()).unwrap());let outside: String = connection.query_row(@@ -233,7 +233,7 @@ fn relocates_a_real_copied_profile_without_recovery_or_changing_user_content() {.unwrap();assert_eq!(memory_key,- crate::db::normalize_project_path(&destination.join("project").to_string_lossy()).unwrap()+ crate::db::canonical_project_path(&destination.join("project").to_string_lossy()).unwrap());let group: String = connection.query_row(@@ -434,3 +434,108 @@ fn refuses_colliding_project_capability_keys_without_losing_an_override() {assert!(relocate(&source, &destination).is_err());assert_eq!(fs::read(file).unwrap(), before);}++#[test]+fn encoded_tool_images_remain_lossless_in_all_relocated_file_kinds() {+ use crate::transcripts::binary_storage::{decode, encode};+ let temporary = tempfile::tempdir().unwrap();+ let source = temporary.path().join("old");+ let destination = temporary.path().join("new");+ fs::create_dir_all(source.join("sessions")).unwrap();+ let old = source+ .join("scratch/screenshot.png")+ .to_string_lossy()+ .into_owned();+ let new = destination+ .join("scratch/screenshot.png")+ .to_string_lossy()+ .into_owned();+ let image = json!({"type":"image","data":"YWJjLw==","mimeType":"image/png"});+ let result =+ json!({"content":[image.clone()],"details":{"content":[image],"path":old},"note":"last"});+ let text =+ serde_json::to_string_pretty(&result)+ .unwrap()+ .replacen("{", "{\n \"note\":\"first\",", 1);+ let record = json!({"type":"message","id":"m","role":"tool","blocks":[{"type":"tool_call","result":result,"text":text}],"createdAt":"2026-10-24T00:00:00Z"});+ let ui = json!({"id":"m","role":"tool","content":text,"toolResult":result});+ let line_files = [+ ("sessions/s.jsonl", record.clone()),+ (+ "sessions/s.revisions.jsonl",+ json!({"type":"revision","rootUserId":"u","revisionIndex":1,"messages":[record.clone()]}),+ ),+ ];+ for (name, value) in &line_files {+ fs::write(+ source.join(name),+ format!("{}\n", encode(value.clone()).unwrap()),+ )+ .unwrap();+ }+ fs::write(+ source.join("sessions/s.inflight.json"),+ encode(json!({"schema":1,"message":record}))+ .unwrap()+ .to_string(),+ )+ .unwrap();+ let outbox =+ json!([encode(json!({"key":"message:s:m","sessionId":"s","message":ui})).unwrap()]);+ for name in [+ "session-message-outbox.json",+ "session-message-outbox.dead-letter.json",+ ] {+ fs::write(source.join(name), outbox.to_string()).unwrap();+ }+ copy_directory(&source, &destination);+ relocate(&source, &destination).unwrap();+ let expected_text = text.replace(+ &serde_json::to_string(&old).unwrap(),+ &serde_json::to_string(&new).unwrap(),+ );+ for name in [+ "sessions/s.jsonl",+ "sessions/s.revisions.jsonl",+ "sessions/s.inflight.json",+ "session-message-outbox.json",+ "session-message-outbox.dead-letter.json",+ ] {+ let stored = fs::read_to_string(destination.join(name)).unwrap();+ assert_eq!(+ stored.matches("YWJjLw==").count(),+ 1,+ "{name} must retain one physical image"+ );+ let raw: Value = serde_json::from_str(&stored).unwrap();+ let decoded = decode(if raw.is_array() { raw[0].clone() } else { raw }).unwrap();+ let (actual_result, actual_text) = if name.contains("outbox") {+ (+ &decoded["message"]["toolResult"],+ &decoded["message"]["content"],+ )+ } else {+ let message = if name.contains("revisions") {+ &decoded["messages"][0]+ } else if name.contains("inflight") {+ &decoded["message"]+ } else {+ &decoded+ };+ (+ &message["blocks"][0]["result"],+ &message["blocks"][0]["text"],+ )+ };+ assert_eq!(actual_result["details"]["path"], new, "{name}");+ assert_eq!(actual_result["content"][0]["data"], "YWJjLw==");+ assert_eq!(actual_text, &Value::String(expected_text.clone()), "{name}");+ assert_eq!(+ fs::read_to_string(source.join(name))+ .unwrap()+ .matches("YWJjLw==")+ .count(),+ 1+ );+ }+}diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex 0ec286825..e69e1e7c7 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;pub(crate) use std::path::{Path, PathBuf};/// Current SQLite schema version.-pub const SCHEMA_VERSION: i64 = 25;+pub const SCHEMA_VERSION: i64 = 26;/// Absolute approval deadline for a newly submitted Plan or Goal proposal.pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;@@ -24,6 +24,7 @@ mod repositories;mod schema;mod session_collaboration_migration;mod session_title_source_migration;+mod tool_image_storage_migration;mod worktree_migration;pub(crate) use migrations::{archive_legacy_db, create_migration_backup, migrate_and_validate_top_level_mode,diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rsindex 178e1cb55..0b346cb0b 100644--- a/crates/host-core/src/db/repositories.rs+++ b/crates/host-core/src/db/repositories.rs@@ -210,6 +210,9 @@ impl Database {24 => {super::model_discovery_migration::migrate(&conn, path)?;}+ 25 => {+ super::tool_image_storage_migration::migrate(&conn, path)?;+ }legacy @ 1..=6 => {let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");drop(conn);@@ -264,6 +267,10 @@ impl Database {}if migrated_version == 24 {super::model_discovery_migration::migrate(&conn, path)?;+ migrated_version = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;+ }+ if migrated_version == 25 {+ super::tool_image_storage_migration::migrate(&conn, path)?;}let db = Self { conn, data_dir };db.boot_maintenance()?;diff --git a/crates/host-core/src/db/tool_image_storage_migration.rs b/crates/host-core/src/db/tool_image_storage_migration.rsnew file mode 100644index 000000000..fd039b55a--- /dev/null+++ b/crates/host-core/src/db/tool_image_storage_migration.rs@@ -0,0 +1,181 @@+use super::{create_migration_backup, Connection, Context, Path, Result};++/// v25 → v26 marks the storage-private lossless tool-image envelope. No table+/// changes or transcript conversion happen at startup. Earlier applications+/// refuse this version before they can interpret encoded transcript records.+pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 25)?;+ let tx = conn.unchecked_transaction()?;+ tx.pragma_update(None, "user_version", 26i64)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v25 to v26 storage migration; backup {} remains",+ backup.display()+ )+ })?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use crate::db::*;+ use rusqlite::types::Value as SqlValue;++ fn version(conn: &Connection) -> i64 {+ conn.query_row("PRAGMA user_version", [], |row| row.get(0))+ .unwrap()+ }++ fn legacy_database(path: &Path) {+ let db = Database::open(path).unwrap();+ db.conn().execute_batch("INSERT INTO kv(ns,key,value_json,updated_at) VALUES ('fixture','config','{\"exact\":true}',1);+ INSERT INTO providers(id,name,config_json,created_at,updated_at) VALUES ('fixture','Saved provider','{\"baseUrl\":\"https://example.test\"}',1,1);+ INSERT INTO models(provider_id,model_id,display_name,source,updated_at) VALUES ('fixture','saved-model','Saved model','user',1);+ INSERT INTO sessions(id,title,title_source,provider_id,model_id,last_seq,created_at,updated_at) VALUES ('fixture-session','Saved session','manual','fixture','saved-model',1,1,1);+ INSERT INTO turns(id,session_id,status,started_at,ended_at) VALUES ('fixture-turn','fixture-session','completed',1,2);+ INSERT INTO messages(id,session_id,turn_id,seq,role,text,created_at) VALUES ('fixture-message','fixture-session','fixture-turn',0,'user','Saved searchable text',1);+ PRAGMA user_version=25;").unwrap();+ }++ fn rows(conn: &Connection, table: &str) -> Vec<Vec<SqlValue>> {+ // The test controls every table name; values remain SQLite-owned data.+ let mut statement = conn+ .prepare(&format!("SELECT * FROM {table} ORDER BY 1"))+ .unwrap();+ let columns = statement.column_count();+ statement+ .query_map([], |row| {+ (0..columns).map(|column| row.get(column)).collect()+ })+ .unwrap()+ .collect::<rusqlite::Result<_>>()+ .unwrap()+ }++ #[test]+ fn schema_25_upgrades_only_the_version_and_keeps_legacy_files_and_backup() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_database(&path);+ let before = Connection::open(&path).unwrap();+ let tables = [+ "kv",+ "providers",+ "models",+ "sessions",+ "messages",+ "turns",+ "message_revisions",+ "sqlite_master",+ ];+ let snapshots: Vec<_> = tables.iter().map(|table| rows(&before, table)).collect();+ drop(before);+ let files = [+ crate::transcripts::transcript_path(dir.path(), "fixture-session").unwrap(),+ crate::transcripts::revisions_path(dir.path(), "fixture-session").unwrap(),+ crate::transcripts::inflight_path(dir.path(), "fixture-session").unwrap(),+ ];+ for file in &files {+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(file, b"legacy bytes are not rewritten on database open\n").unwrap();+ }+ let db = Database::open(&path).unwrap();+ assert_eq!(version(db.conn()), 26);+ let backup_path = migration_backup_path(&path, 25);+ let backup = Connection::open(&backup_path).unwrap();+ assert_eq!(version(&backup), 25);+ for (table, snapshot) in tables.iter().zip(&snapshots) {+ assert_eq!(&rows(db.conn(), table), snapshot, "live {table}");+ assert_eq!(&rows(&backup, table), snapshot, "backup {table}");+ }+ for file in &files {+ assert_eq!(+ std::fs::read(file).unwrap(),+ b"legacy bytes are not rewritten on database open\n"+ );+ }+ drop(backup);+ drop(db);+ let original_backup = std::fs::read(&backup_path).unwrap();+ let db = Database::open(&path).unwrap();+ assert_eq!(version(db.conn()), 26);+ assert_eq!(+ std::fs::read(backup_path).unwrap(),+ original_backup,+ "reopening must not replace the schema-25 backup"+ );+ }++ #[test]+ fn fresh_database_uses_26_and_future_27_is_refused() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let db = Database::open(&path).unwrap();+ assert_eq!(version(db.conn()), 26);+ db.conn().pragma_update(None, "user_version", 27).unwrap();+ drop(db);+ let error = Database::open(&path)+ .err()+ .expect("future schema must be refused");+ assert!(error.to_string().contains("27 is newer than supported 26"));+ assert_eq!(version(&Connection::open(path).unwrap()), 27);+ }++ #[test]+ fn schema_24_chains_through_25_and_its_original_model_migration_stays_single_step() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_database(&path);+ let conn = Connection::open(&path).unwrap();+ conn.execute_batch(+ "ALTER TABLE models DROP COLUMN discovery_state; PRAGMA user_version=24;",+ )+ .unwrap();+ super::super::model_discovery_migration::migrate(&conn, &path).unwrap();+ assert_eq!(+ version(&conn),+ 25,+ "the model migration still produces schema 25"+ );+ drop(conn);+ // Recreate the old version to exercise Database::open's complete chain.+ let conn = Connection::open(&path).unwrap();+ conn.execute_batch(+ "ALTER TABLE models DROP COLUMN discovery_state; PRAGMA user_version=24;",+ )+ .unwrap();+ drop(conn);+ let db = Database::open(&path).unwrap();+ assert_eq!(version(db.conn()), 26);+ for schema in [24, 25] {+ let backup = Connection::open(migration_backup_path(&path, schema)).unwrap();+ assert_eq!(version(&backup), schema);+ }+ assert_eq!(rows(db.conn(), "messages").len(), 1);+ }+ #[test]+ fn failed_version_stamp_keeps_schema_25_and_its_readable_backup() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ legacy_database(&path);+ let conn = Connection::open(&path).unwrap();+ let original = rows(&conn, "messages");+ conn.pragma_update(None, "query_only", true).unwrap();+ let error = super::migrate(&conn, &path).unwrap_err();+ assert!(error.to_string().contains("readonly"), "{error:#}");+ assert_eq!(version(&conn), 25);+ assert_eq!(rows(&conn, "messages"), original);+ let backup = Connection::open(migration_backup_path(&path, 25)).unwrap();+ assert_eq!(version(&backup), 25);+ assert_eq!(rows(&backup, "messages"), original);+ let integrity: String = backup+ .query_row("PRAGMA integrity_check", [], |row| row.get(0))+ .unwrap();+ assert_eq!(integrity, "ok");+ drop(backup);+ // The failed transaction releases its lock so the same DB can retry.+ conn.pragma_update(None, "query_only", false).unwrap();+ super::migrate(&conn, &path).unwrap();+ assert_eq!(version(&conn), 26);+ }+}diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rsindex 6278a8e98..83aaef330 100644--- a/crates/host-core/src/plugins/providers/tests.rs+++ b/crates/host-core/src/plugins/providers/tests.rs@@ -100,9 +100,9 @@ fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {// v17 added the owner column, v18 the turn-queue priority column,// v19 session omit, v21 the session Todo checklist, and v22 the// session-list index, v23 the session title source, and v24 the worktree- // registry; v25 adds model discovery state. A fresh database is stamped with the newest version, so the+ // registry; v25 adds model discovery state; v26 marks lossless image storage. A fresh database is stamped with the newest version, so the// column set is the current one.- assert_eq!(SCHEMA_VERSION, 25);+ assert_eq!(SCHEMA_VERSION, 26);let version: i64 = db.conn().query_row("PRAGMA user_version", [], |row| row.get(0))diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rsindex 76985f9c9..f871d757a 100644--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@ -31,13 +31,17 @@ use anyhow::{anyhow, Context, Result};use serde::{Deserialize, Serialize};use serde_json::Value;+mod binary_migration;+pub(crate) mod binary_storage;+#[cfg(test)]+mod binary_storage_tests;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;+pub const TRANSCRIPT_SCHEMA: i64 = 2;/// One persisted message: the canonical block array plus promoted fields,/// not the flat UiMessage projection (spec 04 §1 "lossless transcripts").@@ -188,7 +192,9 @@ pub fn find_message_position(struct Identity {id: String,}- let mut reader = BufReader::new(File::open(transcript_path(data_dir, session_id)?)?);+ let path = transcript_path(data_dir, session_id)?;+ binary_migration::validate_header(&path)?;+ let mut reader = BufReader::new(File::open(&path)?);let mut raw = Vec::new();let mut line = String::new();for (position, offset) in layout.message_offsets.iter().enumerate().rev() {@@ -246,8 +252,9 @@ pub fn read_tool_call(.any(|block| block.get("callId").and_then(Value::as_str) == Some(call_id))});if matches_call {- match serde_json::from_str(&line) {+ match binary_storage::read(&line) {Ok(record) => return Ok(Some(record)),+ Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) if invalid_utf8 => {tracing::warn!(%error, "skipping invalid indexed tool-call message");}@@ -456,7 +463,7 @@ fn scan_json_string(bytes: &[u8], start: usize) -> Option<(&[u8], usize)> {/// 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 body = serde_json::to_string(&binary_storage::encode(serde_json::to_value(body)?)?)?;let fields = body.strip_prefix('{').and_then(|rest| rest.strip_suffix('}'))@@ -542,9 +549,10 @@ pub fn read_inflight(data_dir: &Path, session_id: &str) -> Result<Option<InflighErr(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),Err(e) => return Err(e).with_context(|| format!("read {}", path.display())),};- match serde_json::from_str::<InflightRecord>(raw.trim()) {+ match binary_storage::read::<InflightRecord>(raw.trim()) {Ok(record) if record.schema == INFLIGHT_SCHEMA => Ok(Some(record)),Ok(_) => Ok(None),+ Err(error) if binary_storage::is_error(&error) => Err(error),Err(error) => {tracing::warn!(path = %path.display(), %error, "skipping invalid inflight checkpoint");Ok(None)@@ -648,7 +656,8 @@ mod durability {/// will. The record is serialized now, so the commit only touches the file.pub(super) fn owe_checkpoint(path: &Path, record: &InflightRecord) -> Result<()> {let decided = decision_order();- let payload = serde_json::to_string(record)?;+ let payload =+ serde_json::to_string(&binary_storage::encode(serde_json::to_value(record)?)?)?;if PENDING.try_with(|_| ()).is_err() {return write_checkpoint(path, &payload, decided);}@@ -772,14 +781,26 @@ fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()>if let Some(parent) = path.parent() {fs::create_dir_all(parent)?;}+ let converted = binary_migration::prepare(path, header.as_deref())?;+ if converted {+ if let Some((data_dir, session_id)) = path.parent().and_then(|p| p.parent()).zip(+ path.file_name()+ .and_then(|n| n.to_str())+ .and_then(|n| n.strip_suffix(".jsonl")),+ ) {+ layout::invalidate(data_dir, session_id);+ }+ }let fresh = !path.exists();let mut file = OpenOptions::new().create(true).append(true).open(path)?;let mut buf = String::new();if fresh {- if let Some(header) = header {- buf.push_str(&header);- buf.push('\n');- }+ buf.push_str(+ header+ .as_deref()+ .unwrap_or("{\"type\":\"storage\",\"schema\":2}"),+ );+ buf.push('\n');} else if !ends_with_newline(path)? {// A crash mid-append left a torn tail. `read_transcript_window` tolerates it on// read, but appending straight after it would fuse the torn bytes and@@ -875,6 +896,7 @@ pub fn read_transcript_window_with_layout(message_limit: Option<usize>,) -> Result<TranscriptRead> {let path = transcript_path(data_dir, session_id)?;+ binary_migration::validate_header(&path)?;let mut out = TranscriptRead::default();let total = layout.message_count();let start = message_start.min(total);@@ -948,16 +970,18 @@ pub fn read_transcript_window_with_layout(.with_context(|| format!("read indexed transcript line in {}", path.display()))?;let trimmed = line.trim();if is_message {- match serde_json::from_str::<MessageRecord>(trimmed) {+ match binary_storage::read::<MessageRecord>(trimmed) {Ok(record) => out.messages.push(record),+ Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) if invalid_utf8 => {tracing::warn!(path = %path.display(), %error, "skipping invalid indexed message line");}Err(error) => return Err(error).context("decode indexed transcript message"),}} else {- match serde_json::from_str::<CompactionRecord>(trimmed) {+ match binary_storage::read::<CompactionRecord>(trimmed) {Ok(record) => out.compactions.push(record),+ Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) if invalid_utf8 => {tracing::warn!(path = %path.display(), %error, "skipping invalid indexed compaction line");}@@ -987,6 +1011,7 @@ pub fn read_transcript_window(message_limit: Option<usize>,) -> Result<TranscriptRead> {let path = transcript_path(data_dir, session_id)?;+ binary_migration::validate_header(&path)?;let file = match File::open(&path) {Ok(file) => file,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(TranscriptRead::default()),@@ -1015,16 +1040,18 @@ pub fn read_transcript_window(message_index += 1;let selected = index >= message_start && end.is_none_or(|limit| index < limit);if selected {- match serde_json::from_str::<MessageRecord>(line.trim()) {+ match binary_storage::read::<MessageRecord>(line.trim()) {Ok(record) => out.messages.push(record),+ Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) => {tracing::warn!(path = %path.display(), %error, "skipping invalid message line");}}}}- "compaction" => match serde_json::from_str::<CompactionRecord>(line.trim()) {+ "compaction" => match binary_storage::read::<CompactionRecord>(line.trim()) {Ok(record) => out.compactions.push(record),+ Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) => {tracing::warn!(path = %path.display(), %error, "skipping invalid compaction line");}@@ -1145,6 +1172,9 @@ fn swap_into_place(tmp: &Path, path: &Path) -> Result<()> {/// 21 MB, measured against the always-rewrite splice on the same fixture.pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord) -> Result<bool> {let path = transcript_path(data_dir, session_id)?;+ if binary_migration::prepare(&path, Some(&header_line(session_id, &record.created_at)?))? {+ layout::invalidate(data_dir, session_id);+ }let replacement = tagged("message", record)?;// Fast path. A message is decided by the *last* occurrence of its id, so// when that occurrence is already the file's last line, appending the@@ -1419,6 +1449,7 @@ pub fn read_revision(revision_index: i64,) -> Result<Option<RevisionPayload>> {let path = revisions_path(data_dir, session_id)?;+ binary_migration::validate_header(&path)?;let file = match File::open(&path) {Ok(file) => file,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),@@ -1466,16 +1497,14 @@ pub fn read_revision(}let body = line.trim();let decoded = if *kind == "revision_live" {- serde_json::from_str::<LiveRevisionRecord>(body)- .ok()- .map(RevisionPayload::Live)+ binary_storage::read::<LiveRevisionRecord>(body).map(RevisionPayload::Live)} else {- serde_json::from_str::<RevisionRecord>(body)- .ok()- .map(RevisionPayload::Stored)+ binary_storage::read::<RevisionRecord>(body).map(RevisionPayload::Stored)};- if decoded.is_some() {- return Ok(decoded);+ match decoded {+ Ok(record) => return Ok(Some(record)),+ Err(error) if binary_storage::is_error(&error) => return Err(error),+ Err(_) => {}}}Ok(None)diff --git a/crates/host-core/src/transcripts/binary_migration.rs b/crates/host-core/src/transcripts/binary_migration.rsnew file mode 100644index 000000000..e8ffa3835--- /dev/null+++ b/crates/host-core/src/transcripts/binary_migration.rs@@ -0,0 +1,116 @@+//! Upgrade one self-contained legacy file before appending to it. Conversion is+//! streaming and independently atomic per file; readers never mutate history.+use super::*;++fn current_header(value: &Value) -> Result<bool> {+ if !matches!(+ value.get("type").and_then(Value::as_str),+ Some("session" | "storage")+ ) {+ return Ok(false);+ }+ match value.get("schema").and_then(Value::as_i64) {+ Some(1) => Ok(false),+ None if value["type"] == "session" => Ok(false),+ Some(TRANSCRIPT_SCHEMA) => Ok(true),+ _ => Err(anyhow!("unsupported transcript storage schema")),+ }+}++pub(super) fn validate_header(path: &Path) -> Result<()> {+ let file = match File::open(path) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error).context("open transcript storage header"),+ };+ let mut bytes = Vec::new();+ BufReader::new(file).read_until(b'\n', &mut bytes)?;+ if let Ok(value) = serde_json::from_slice::<Value>(&bytes) {+ current_header(&value)?;+ }+ Ok(())+}++pub(super) fn prepare(path: &Path, header: Option<&str>) -> Result<bool> {+ let file = match File::open(path) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),+ Err(error) => return Err(error).context("open legacy transcript for conversion"),+ };+ // Conversion replaces regular files atomically. Preserve device/pipe+ // identity so the append still exposes its original write/flush error.+ if !file.metadata()?.is_file() {+ return Ok(false);+ }+ let mut reader = BufReader::new(file);+ let mut raw = Vec::new();+ reader.read_until(b'\n', &mut raw)?;+ let mut has_session_header = false;+ if let Ok(value) = serde_json::from_slice::<Value>(&raw) {+ if current_header(&value)? {+ return Ok(false);+ }+ has_session_header = value["type"] == "session";+ }+ reader.seek(SeekFrom::Start(0))?;+ let tmp = path.with_extension("binary.tmp");+ let mut writer = BufWriter::new(File::create(&tmp)?);+ if !has_session_header {+ writer.write_all(+ header+ .unwrap_or("{\"type\":\"storage\",\"schema\":2}")+ .as_bytes(),+ )?;+ writer.write_all(b"\n")?;+ }+ loop {+ raw.clear();+ if reader.read_until(b'\n', &mut raw)? == 0 {+ break;+ }+ let mut replacement = None;+ // Preserve historical torn/invalid lines verbatim, including invalid+ // UTF-8. A valid envelope with invalid references must fail explicitly.+ if let Ok(mut value) = serde_json::from_slice::<Value>(&raw) {+ let kind = value.get("type").and_then(Value::as_str).map(str::to_owned);+ match kind.as_deref() {+ Some("session") => {+ current_header(&value)?;+ value["schema"] = Value::from(TRANSCRIPT_SCHEMA);+ replacement = Some(value);+ }+ Some("message" | "compaction" | "revision") => {+ let decoded = binary_storage::decode(value.clone())?;+ let encoded = binary_storage::encode(decoded.clone())?;+ anyhow::ensure!(+ binary_storage::decode(encoded.clone())? == decoded,+ "lossless transcript conversion verification failed"+ );+ if encoded != value {+ replacement = Some(encoded);+ }+ }+ _ => {}+ }+ }+ if let Some(value) = replacement {+ let tag = value["type"].as_str().unwrap_or_default().to_owned();+ let mut fields = value.as_object().expect("decoded record object").clone();+ fields.remove("type");+ // Keep type first: bounded identity scanners rely on this ordering.+ let body = serde_json::to_string(&fields)?;+ let fields = &body[1..body.len() - 1];+ writeln!(writer, "{{\"type\":{},{} }}", Value::String(tag), fields)?;+ } else {+ writer.write_all(&raw)?;+ if !raw.ends_with(b"\n") {+ writer.write_all(b"\n")?;+ }+ }+ }+ writer.flush()?;+ writer.get_ref().sync_data()?;+ drop(writer);+ swap_into_place(&tmp, path)?;+ Ok(true)+}diff --git a/crates/host-core/src/transcripts/binary_storage.rs b/crates/host-core/src/transcripts/binary_storage.rsnew file mode 100644index 000000000..950e3a30a--- /dev/null+++ b/crates/host-core/src/transcripts/binary_storage.rs@@ -0,0 +1,731 @@+//! Reversible storage representation shared with host-runtime/binary-storage.ts.+//! This codec never escapes the file store: business objects stay unchanged.+use anyhow::{anyhow, Result};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::collections::{HashMap, HashSet};++#[derive(Debug, thiserror::Error)]+#[error("invalid binary storage: {0}")]+struct InvalidStorage(String);+fn invalid(reason: impl Into<String>) -> anyhow::Error {+ InvalidStorage(reason.into()).into()+}+pub(super) fn is_error(error: &anyhow::Error) -> bool {+ error.downcast_ref::<InvalidStorage>().is_some()+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(untagged)]+enum Key {+ Field(String),+ Index(usize),+}+type Path = Vec<Key>;+#[derive(Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Ref {+ path: Path,+ image: usize,+}+#[derive(Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Escape {+ at: usize,+ raw: String,+}+#[derive(Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct ImagePart {+ image: usize,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ escapes: Vec<Escape>,+}+#[derive(Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct MirrorPart {+ text: usize,+}+#[derive(Clone, Serialize, Deserialize)]+#[serde(untagged)]+enum Part {+ Literal(String),+ Image(ImagePart),+ Mirror(MirrorPart),+}+#[derive(Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Text {+ path: Path,+ parts: Vec<Part>,+}+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Envelope {+ version: u32,+ data: Vec<String>,+ refs: Vec<Ref>,+ texts: Vec<Text>,+}+struct Token {+ path: Path,+ start: usize,+ end: usize,+ value: String,+}++fn base64(value: &str) -> bool {+ let body = value.trim_end_matches('=');+ !body.is_empty()+ && value.len() - body.len() <= 2+ && body+ .bytes()+ .all(|c| c.is_ascii_alphanumeric() || c == b'+' || c == b'/')+}+fn child<'a>(value: &'a Value, key: &Key) -> Result<&'a Value> {+ match key {+ Key::Field(k) => value.as_object().and_then(|o| o.get(k)),+ Key::Index(i) => value.as_array().and_then(|a| a.get(*i)),+ }+ .ok_or_else(|| invalid("missing or mistyped path"))+}+fn at<'a>(root: &'a Value, path: &[Key]) -> Result<&'a Value> {+ path.iter().try_fold(root, child)+}+fn put(root: &mut Value, path: &[Key], value: Value) -> Result<()> {+ let (last, parents) = path.split_last().ok_or_else(|| invalid("empty path"))?;+ let mut parent = root;+ for key in parents {+ parent = match key {+ Key::Field(k) => parent.as_object_mut().and_then(|o| o.get_mut(k)),+ Key::Index(i) => parent.as_array_mut().and_then(|a| a.get_mut(*i)),+ }+ .ok_or_else(|| invalid("missing path"))?;+ }+ let slot = match last {+ Key::Field(k) => parent.as_object_mut().and_then(|o| o.get_mut(k)),+ Key::Index(i) => parent.as_array_mut().and_then(|a| a.get_mut(*i)),+ }+ .ok_or_else(|| invalid("missing path"))?;+ *slot = value;+ Ok(())+}+fn field(path: &[Key], name: &str) -> Path {+ let mut out = path.to_vec();+ out.push(Key::Field(name.into()));+ out+}+fn walk(value: &Value, path: &mut Path, visit: &mut impl FnMut(&Value, &Path)) {+ match value {+ Value::Object(map) => {+ visit(value, path);+ for (k, v) in map {+ path.push(Key::Field(k.clone()));+ walk(v, path, visit);+ path.pop();+ }+ }+ Value::Array(items) => {+ for (i, v) in items.iter().enumerate() {+ path.push(Key::Index(i));+ walk(v, path, visit);+ path.pop();+ }+ }+ _ => {}+ }+}+fn image_positions(root: &Value) -> Vec<Path> {+ let mut out = Vec::new();+ let mut seen = HashSet::new();+ let mut add = |path: Path| {+ if seen.insert(path.clone()) {+ out.push(path);+ }+ };+ walk(root, &mut Vec::new(), &mut |v, p| {+ if v["type"] == "image" && v.get("data").is_some() {+ add(field(p, "data"));+ }+ if v["type"] == "resource"+ && v.get("resource")+ .is_some_and(|r| r.is_object() && r.get("blob").is_some())+ {+ add(field(&field(p, "resource"), "blob"));+ }+ if let Some(items) = v.get("images").and_then(Value::as_array) {+ for (i, image) in items.iter().enumerate() {+ if image.get("mimeType").is_some_and(Value::is_string)+ && image.get("data").is_some()+ {+ let mut path = field(p, "images");+ path.push(Key::Index(i));+ add(field(&path, "data"));+ }+ }+ }+ });+ out+}+fn json_equal(left: &Value, right: &Value) -> bool {+ match (left, right) {+ (Value::Number(a), Value::Number(b)) => a.as_f64() == b.as_f64(),+ (Value::Array(a), Value::Array(b)) => {+ a.len() == b.len() && a.iter().zip(b).all(|(a, b)| json_equal(a, b))+ }+ (Value::Object(a), Value::Object(b)) => {+ a.len() == b.len()+ && a.iter()+ .all(|(k, v)| b.get(k).is_some_and(|other| json_equal(v, other)))+ }+ _ => left == right,+ }+}+fn sibling_matches(parent: &Value, parsed: &Value) -> bool {+ ["result", "toolResult"]+ .iter()+ .any(|k| parent.get(k).is_some_and(|r| json_equal(r, parsed)))+}++fn mirrors(root: &Value) -> Vec<(Path, String, Value)> {+ let mut out = Vec::new();+ walk(root, &mut Vec::new(), &mut |parent, path| {+ for key in ["content", "text"] {+ if let Some(text) = parent.get(key).and_then(Value::as_str) {+ if let Ok(parsed) = serde_json::from_str::<Value>(text) {+ if sibling_matches(parent, &parsed) {+ out.push((field(path, key), text.to_owned(), parsed));+ }+ }+ }+ }+ });+ out+}++fn mirrors_in(root: &Value) -> HashMap<Path, String> {+ mirrors(root)+ .into_iter()+ .map(|(path, text, _)| (path, text))+ .collect()+}++// The caller parsed the JSON already. Scan its string tokens to retain exact+// offsets/spelling; serde's map ordering must not rewrite the original mirror.+fn tokens(text: &str) -> Result<Vec<Token>> {+ struct Scanner<'a> {+ text: &'a str,+ pos: usize,+ out: Vec<Token>,+ }+ impl Scanner<'_> {+ fn white(&mut self) {+ while self.pos < self.text.len() && self.text.as_bytes()[self.pos].is_ascii_whitespace()+ {+ self.pos += 1;+ }+ }+ fn string(&mut self) -> Result<(usize, usize, String)> {+ let start = self.pos;+ self.pos += 1;+ while self.pos < self.text.len() {+ let c = self.text.as_bytes()[self.pos];+ self.pos += 1;+ if c == b'\\' {+ self.pos += 1;+ } else if c == b'"' {+ return Ok((+ start,+ self.pos,+ serde_json::from_str(&self.text[start..self.pos])?,+ ));+ }+ }+ Err(invalid("unterminated JSON string"))+ }+ fn value(&mut self, path: Path) -> Result<()> {+ self.white();+ let c = *self+ .text+ .as_bytes()+ .get(self.pos)+ .ok_or_else(|| invalid("missing JSON value"))?;+ if c == b'"' {+ let (start, end, value) = self.string()?;+ self.out.push(Token {+ path,+ start,+ end,+ value,+ });+ } else if c == b'{' || c == b'[' {+ let object = c == b'{';+ let end = if object { b'}' } else { b']' };+ self.pos += 1;+ self.white();+ let mut index = 0;+ while self.text.as_bytes().get(self.pos) != Some(&end) {+ self.white();+ let key = if object {+ let (_, _, key) = self.string()?;+ self.white();+ self.pos += 1;+ Key::Field(key)+ } else {+ let k = Key::Index(index);+ index += 1;+ k+ };+ let mut next = path.clone();+ next.push(key);+ self.value(next)?;+ self.white();+ if self.text.as_bytes().get(self.pos) != Some(&b',') {+ break;+ }+ self.pos += 1;+ }+ self.pos += 1;+ } else {+ while self.pos < self.text.len()+ && !matches!(+ self.text.as_bytes()[self.pos],+ b' ' | b'\t' | b'\r' | b'\n' | b',' | b']' | b'}'+ )+ {+ self.pos += 1;+ }+ }+ Ok(())+ }+ }+ let mut scanner = Scanner {+ text,+ pos: 0,+ out: Vec::new(),+ };+ scanner.value(Vec::new())?;+ Ok(scanner.out)+}+fn image_tokens(text: &str, parsed: &Value) -> Result<Vec<Token>> {+ let positions: HashSet<_> = image_positions(parsed).into_iter().collect();+ Ok(tokens(text)?+ .into_iter()+ .filter(|t| positions.contains(&t.path) && base64(&t.value))+ .collect())+}+fn image_part(text: &str, token: &Token, image: usize) -> ImagePart {+ let bytes = &text.as_bytes()[token.start + 1..token.end - 1];+ let mut pos = 0;+ let mut index = 0;+ let mut escapes = Vec::new();+ while pos < bytes.len() {+ if bytes[pos] == b'\\' {+ let size = if bytes[pos + 1] == b'u' { 6 } else { 2 };+ escapes.push(Escape {+ at: index,+ raw: String::from_utf8(bytes[pos..pos + size].to_vec()).expect("ASCII JSON escape"),+ });+ pos += size;+ } else {+ pos += 1;+ }+ index += 1;+ }+ ImagePart { image, escapes }+}+fn index_of(data: &mut Vec<String>, indexes: &mut HashMap<String, usize>, value: &str) -> usize {+ if let Some(i) = indexes.get(value) {+ return *i;+ }+ let index = data.len();+ data.push(value.into());+ indexes.insert(value.into(), index);+ index+}++pub(crate) fn encode(mut value: Value) -> Result<Value> {+ if !value.is_object() {+ return Ok(value);+ }+ if value.get("binaryStorage").is_some() {+ return Err(invalid("reserved binaryStorage field"));+ }+ let mut data = Vec::new();+ let mut indexes = HashMap::new();+ let mut refs = Vec::new();+ let mut texts = Vec::new();+ for path in image_positions(&value) {+ if let Some(s) = at(&value, &path)?.as_str().filter(|s| base64(s)) {+ let image = index_of(&mut data, &mut indexes, s);+ refs.push(Ref { path, image });+ }+ }+ if refs.is_empty() {+ return Ok(value);+ }+ let mirrors: Vec<_> = mirrors(&value)+ .into_iter()+ .filter(|(_, _, parsed)| {+ image_positions(parsed).iter().any(|path| {+ at(parsed, path)+ .ok()+ .and_then(Value::as_str)+ .is_some_and(base64)+ })+ })+ .collect();+ let mut mirror_indexes = HashMap::new();+ for (index, (_, text, _)) in mirrors.iter().enumerate() {+ mirror_indexes.entry(text.as_str()).or_insert(index);+ }+ for (path, text, parsed) in &mirrors {+ let images: HashSet<_> = image_positions(parsed).into_iter().collect();+ let nested: HashMap<_, _> = mirrors_in(parsed);+ let mut parts = Vec::new();+ let mut start = 0;+ for token in tokens(text)? {+ let part = if images.contains(&token.path) && base64(&token.value) {+ let image = index_of(&mut data, &mut indexes, &token.value);+ Part::Image(image_part(text, &token, image))+ } else if let Some(index) = mirror_indexes.get(token.value.as_str()) {+ if nested.get(&token.path) != Some(&token.value)+ || text[token.start..token.end] != serde_json::to_string(&token.value)?+ {+ continue;+ }+ Part::Mirror(MirrorPart { text: *index })+ } else {+ continue;+ };+ parts.push(Part::Literal(text[start..token.start].into()));+ parts.push(part);+ start = token.end;+ }+ parts.push(Part::Literal(text[start..].into()));+ texts.push(Text {+ path: path.clone(),+ parts,+ });+ }+ let occurrences = refs.len()+ + texts+ .iter()+ .map(|t| {+ t.parts+ .iter()+ .filter(|p| !matches!(p, Part::Literal(_)))+ .count()+ })+ .sum::<usize>();+ if occurrences == data.len() {+ return Ok(value);+ }+ for path in refs+ .iter()+ .map(|r| &r.path)+ .chain(texts.iter().map(|t| &t.path))+ {+ put(&mut value, path, Value::Null)?;+ }+ value["binaryStorage"] = serde_json::to_value(Envelope {+ version: 1,+ data,+ refs,+ texts,+ })?;+ Ok(value)+}+fn render(part: &ImagePart, data: &str) -> Result<String> {+ let mut out = String::from("\"");+ let mut start = 0;+ for escape in &part.escapes {+ if escape.at < start || escape.at >= data.len() {+ return Err(invalid("invalid escape offset"));+ }+ let raw = escape.raw.as_bytes();+ let valid = raw == b"\\/"+ || (raw.len() == 6+ && raw.starts_with(b"\\u")+ && raw[2..].iter().all(u8::is_ascii_hexdigit));+ if !valid {+ return Err(invalid("invalid escape spelling"));+ }+ let decoded: String = serde_json::from_str(&format!("\"{}\"", escape.raw))+ .map_err(|_| invalid("invalid escape"))?;+ if decoded.as_bytes() != &data.as_bytes()[escape.at..escape.at + 1] {+ return Err(invalid("escape changes data"));+ }+ out.push_str(&data[start..escape.at]);+ out.push_str(&escape.raw);+ start = escape.at + 1;+ }+ out.push_str(&data[start..]);+ out.push('"');+ Ok(out)+}+fn validate_paths(root: &Value, paths: &[Path]) -> Result<()> {+ let mut sorted = paths.to_vec();+ sorted.sort();+ let mut previous: Option<&Path> = None;+ for path in &sorted {+ if path.is_empty()+ || matches!(path.first(),Some(Key::Field(k)) if k=="binaryStorage")+ || !at(root, path)?.is_null()+ {+ return Err(invalid("invalid placeholder"));+ }+ if previous.is_some_and(|p| path.starts_with(p)) {+ return Err(invalid("duplicate or overlapping placeholders"));+ }+ previous = Some(path);+ }+ Ok(())+}++struct RestoredMirror {+ value: String,+ spans: Vec<(usize, usize, Part)>,+}++fn restore_texts(envelope: &Envelope) -> Result<Vec<RestoredMirror>> {+ fn resolve(+ index: usize,+ envelope: &Envelope,+ restored: &mut [Option<RestoredMirror>],+ visiting: &mut HashSet<usize>,+ ) -> Result<()> {+ let text = envelope+ .texts+ .get(index)+ .ok_or_else(|| invalid("invalid text index"))?;+ if restored[index].is_some() {+ return Ok(());+ }+ if !visiting.insert(index) {+ return Err(invalid("text dependency cycle"));+ }+ let mut out = String::new();+ let mut spans = Vec::new();+ for part in &text.parts {+ let start = out.len();+ match part {+ Part::Literal(s) => out.push_str(s),+ Part::Image(p) => {+ let data = envelope+ .data+ .get(p.image)+ .ok_or_else(|| invalid("invalid image index"))?;+ out.push_str(&render(p, data)?);+ }+ Part::Mirror(p) => {+ resolve(p.text, envelope, restored, visiting)?;+ out.push_str(&serde_json::to_string(+ &restored[p.text].as_ref().expect("resolved mirror").value,+ )?);+ }+ }+ if !matches!(part, Part::Literal(_)) {+ spans.push((start, out.len(), part.clone()));+ }+ }+ if spans.is_empty() {+ return Err(invalid("text has no binary references"));+ }+ visiting.remove(&index);+ restored[index] = Some(RestoredMirror { value: out, spans });+ Ok(())+ }+ let mut restored: Vec<_> = envelope.texts.iter().map(|_| None).collect();+ let mut visiting = HashSet::new();+ for index in 0..envelope.texts.len() {+ resolve(index, envelope, &mut restored, &mut visiting)?;+ }+ Ok(restored+ .into_iter()+ .map(|value| value.expect("all mirrors resolved"))+ .collect())+}++pub(crate) fn decode(mut value: Value) -> Result<Value> {+ let Some(object) = value.as_object_mut() else {+ return Ok(value);+ };+ let Some(raw) = object.remove("binaryStorage") else {+ return Ok(value);+ };+ let envelope: Envelope = serde_json::from_value(raw).map_err(|e| invalid(e.to_string()))?;+ if envelope.version != 1 {+ return Err(invalid("unsupported version"));+ }+ let mut unique = HashSet::new();+ if envelope.data.is_empty()+ || envelope+ .data+ .iter()+ .any(|s| !base64(s) || !unique.insert(s))+ {+ return Err(invalid("invalid data table"));+ }+ let paths: Vec<_> = envelope+ .refs+ .iter()+ .map(|r| r.path.clone())+ .chain(envelope.texts.iter().map(|t| t.path.clone()))+ .collect();+ validate_paths(&value, &paths)?;+ let positions: HashSet<_> = image_positions(&value).into_iter().collect();+ let mut used = HashSet::new();+ for r in &envelope.refs {+ if !positions.contains(&r.path) {+ return Err(invalid("reference is not a binary field"));+ }+ let data = envelope+ .data+ .get(r.image)+ .ok_or_else(|| invalid("invalid image index"))?;+ put(&mut value, &r.path, json!(data))?;+ used.insert(r.image);+ }+ let restored = restore_texts(&envelope)?;+ // Nested siblings can contain other mirrors. Restore all placeholders first.+ for (text, mirror) in envelope.texts.iter().zip(&restored) {+ put(&mut value, &text.path, json!(mirror.value))?;+ }+ for (text, mirror) in envelope.texts.iter().zip(&restored) {+ let (key, parents) = text+ .path+ .split_last()+ .ok_or_else(|| invalid("empty text path"))?;+ let parsed: Value =+ serde_json::from_str(&mirror.value).map_err(|_| invalid("invalid mirror JSON"))?;+ if !matches!(key,Key::Field(k) if k=="content"||k=="text")+ || !sibling_matches(at(&value, parents)?, &parsed)+ {+ return Err(invalid("not an exact result mirror"));+ }+ let tokens = tokens(&mirror.value).map_err(|e| invalid(e.to_string()))?;+ let images: HashSet<_> = image_positions(&parsed).into_iter().collect();+ let nested = mirrors_in(&parsed);+ for (start, end, part) in &mirror.spans {+ let token = tokens+ .iter()+ .find(|t| t.start == *start && t.end == *end)+ .ok_or_else(|| invalid("text reference is not a JSON token"))?;+ match part {+ Part::Image(p) => {+ if !images.contains(&token.path) || token.value != envelope.data[p.image] {+ return Err(invalid("text reference is not a binary token"));+ }+ used.insert(p.image);+ }+ Part::Mirror(p) => {+ if token.value != restored[p.text].value+ || nested.get(&token.path) != Some(&token.value)+ {+ return Err(invalid("text reference is not a proven mirror token"));+ }+ }+ Part::Literal(_) => unreachable!("literal parts have no reference span"),+ }+ }+ }+ if used.len() != envelope.data.len() {+ return Err(invalid("unused data table entry"));+ }+ Ok(value)+}++pub(super) fn read<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {+ let value: Value = serde_json::from_str(text).map_err(|e| {+ if text.contains("\"binaryStorage\"") {+ invalid(e.to_string())+ } else {+ anyhow!(e)+ }+ })?;+ let encoded = value.get("binaryStorage").is_some();+ let decoded = decode(value)?;+ serde_json::from_value(decoded).map_err(|e| {+ if encoded {+ invalid(e.to_string())+ } else {+ anyhow!(e)+ }+ })+}++/// Relocation changes structured paths. Apply that same intentional change to+/// proven image-result JSON mirrors, preserving every other literal byte. Plain+/// narrative content is never rewritten or guessed to be a machine mirror.+pub(crate) fn relocate(value: Value, mut rewrite: impl FnMut(&mut Value) -> bool) -> Result<Value> {+ let original = decode(value)?;+ let mut mirrors = Vec::new();+ walk(&original, &mut Vec::new(), &mut |parent, path| {+ for key in ["content", "text"] {+ if let Some(text) = parent.get(key).and_then(Value::as_str) {+ if let Ok(parsed) = serde_json::from_str::<Value>(text) {+ if !image_tokens(text, &parsed).is_ok_and(|tokens| !tokens.is_empty()) {+ continue;+ }+ if let Some(sibling) = ["result", "toolResult"].into_iter().find(|key| {+ parent+ .get(key)+ .is_some_and(|value| json_equal(value, &parsed))+ }) {+ mirrors.push((+ field(path, key),+ field(path, sibling),+ text.to_owned(),+ parsed,+ ));+ }+ }+ }+ }+ });+ let mut relocated = original.clone();+ rewrite(&mut relocated);+ // An outer mirror embeds its inner mirrors as JSON strings, so it must see+ // their already relocated values rather than a separately transformed copy.+ mirrors.sort_by_key(|(path, _, _, _)| std::cmp::Reverse(path.len()));+ for (path, sibling, text, before) in mirrors {+ let target = at(&relocated, &sibling)?;+ let parsed_tokens = tokens(&text)?;+ let last: HashMap<_, _> = parsed_tokens+ .iter()+ .enumerate()+ .map(|(index, token)| (token.path.clone(), index))+ .collect();+ let mut next = String::new();+ let mut cursor = 0;+ for (index, token) in parsed_tokens.iter().enumerate() {+ // JSON duplicate keys have last-write-wins semantics. Earlier+ // overwritten members and objects are literal bytes, not metadata.+ if last.get(&token.path) != Some(&index) {+ continue;+ }+ let (Ok(previous), Ok(replacement)) =+ (at(&before, &token.path), at(target, &token.path))+ else {+ continue;+ };+ if previous.as_str() == Some(token.value.as_str())+ && replacement.is_string()+ && replacement != previous+ {+ next.push_str(&text[cursor..token.start]);+ next.push_str(&serde_json::to_string(replacement)?);+ cursor = token.end;+ }+ }+ next.push_str(&text[cursor..]);+ let parsed: Value = serde_json::from_str(&next)?;+ anyhow::ensure!(+ json_equal(&parsed, target),+ "relocated result mirror diverged from canonical data"+ );+ put(&mut relocated, &path, Value::String(next))?;+ }+ encode(relocated)+}diff --git a/crates/host-core/src/transcripts/binary_storage_tests.rs b/crates/host-core/src/transcripts/binary_storage_tests.rsnew file mode 100644index 000000000..298af7b73--- /dev/null+++ b/crates/host-core/src/transcripts/binary_storage_tests.rs@@ -0,0 +1,359 @@+use super::*;+use serde_json::json;++fn screenshot() -> MessageRecord {+ let image = json!({"type":"image", "data":"YWJjLw==", "mimeType":"image/png"});+ let result = json!({"content":[image.clone()], "details":{"content":[image]}});+ MessageRecord {+ id: "screenshot-call".into(),+ role: "tool".into(),+ tool_name: Some("Snapshot".into()),+ is_error: false,+ blocks: json!([{"type":"tool_call", "callId":"opaque-id", "result":result,+ "text":serde_json::to_string_pretty(&result).unwrap()}]),+ meta: None,+ created_at: "2026-10-24T19:00:00Z".into(),+ }+}++#[test]+fn screenshot_binary_occurs_once_on_disk_and_round_trips_exactly() {+ let dir = tempfile::tempdir().unwrap();+ let record = screenshot();+ append_message(dir.path(), "s", &record.created_at, &record).unwrap();+ let raw = fs::read_to_string(transcript_path(dir.path(), "s").unwrap()).unwrap();+ assert_eq!(+ raw.matches("YWJjLw==").count(),+ 1,+ "fourfold tool-result persistence"+ );+ let restored = read_transcript(dir.path(), "s").unwrap();+ assert_eq!(+ serde_json::to_value(&restored[0]).unwrap(),+ serde_json::to_value(&record).unwrap()+ );+}++#[test]+fn legacy_plain_messages_stay_readable_without_rewriting_on_read() {+ let dir = tempfile::tempdir().unwrap();+ let path = transcript_path(dir.path(), "s").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ let record = screenshot();+ let mut value = serde_json::to_value(&record).unwrap();+ value["type"] = json!("message");+ let raw = format!("{{\"type\":\"session\",\"schema\":1,\"sessionId\":\"s\",\"createdAt\":\"old\"}}\n{value}\n");+ fs::write(&path, &raw).unwrap();+ assert_eq!(+ read_transcript(dir.path(), "s").unwrap()[0].blocks,+ record.blocks+ );+ assert_eq!(fs::read_to_string(path).unwrap(), raw);+}++#[test]+fn unknown_binary_storage_is_an_error_instead_of_an_empty_history() {+ let dir = tempfile::tempdir().unwrap();+ let path = transcript_path(dir.path(), "s").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ let mut value = serde_json::to_value(screenshot()).unwrap();+ value["type"] = json!("message");+ value["binaryStorage"] = json!({"version":999, "data":[], "refs":[], "texts":[]});+ fs::write(path, format!("{value}\n")).unwrap();+ assert!(read_transcript(dir.path(), "s").is_err());+}++#[test]+fn first_append_converts_legacy_records_without_changing_their_values() {+ let dir = tempfile::tempdir().unwrap();+ let path = transcript_path(dir.path(), "s").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ let record = screenshot();+ let mut value = serde_json::to_value(&record).unwrap();+ value["type"] = json!("message");+ fs::write(&path, format!("{{\"type\":\"session\",\"schema\":1,\"sessionId\":\"s\",\"createdAt\":\"old\"}}\n{value}\n")).unwrap();+ let mut next = record.clone();+ next.id = "next".into();+ append_message(dir.path(), "s", "old", &next).unwrap();+ let stored = fs::read_to_string(&path).unwrap();+ assert_eq!(stored.matches("YWJjLw==").count(), 2);+ assert_eq!(+ read_transcript(dir.path(), "s").unwrap()[0].blocks,+ record.blocks+ );+ assert_eq!(+ serde_json::from_str::<Value>(stored.lines().next().unwrap()).unwrap()["schema"],+ 2+ );+}++#[test]+fn javascript_golden_and_non_ascii_numeric_mirrors_are_lossless() {+ let golden: Value = serde_json::from_str(include_str!(+ "../../../../packages/host-runtime/src/fixtures/binary-storage.json"+ ))+ .unwrap();+ assert_eq!(+ binary_storage::decode(golden["encoded"].clone()).unwrap(),+ golden["original"]+ );+ assert_eq!(+ binary_storage::decode(binary_storage::encode(golden["original"].clone()).unwrap())+ .unwrap(),+ golden["original"]+ );+ let value = json!({"toolResult":{"content":[{"type":"image","data":"YWJjLw==","mimeType":"image/png"}], "value":1},+ "content":"{\"value\":1.0,\"content\":[{\"data\":\"YWJjLw==\",\"type\":\"image\",\"mimeType\":\"image/png\"}]}"});+ let encoded = binary_storage::encode(value.clone()).unwrap();+ assert!(encoded.get("binaryStorage").is_some());+ assert_eq!(binary_storage::decode(encoded).unwrap(), value);+}++#[test]+fn corrupted_reference_does_not_replace_a_legacy_file_or_hide_history() {+ let dir = tempfile::tempdir().unwrap();+ let path = transcript_path(dir.path(), "s").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ let mut encoded = binary_storage::encode(serde_json::to_value(screenshot()).unwrap()).unwrap();+ encoded["type"] = json!("message");+ encoded["binaryStorage"]["refs"][0]["image"] = json!(99);+ let raw = format!("{{\"type\":\"session\",\"schema\":1,\"sessionId\":\"s\",\"createdAt\":\"old\"}}\n{encoded}\n");+ fs::write(&path, &raw).unwrap();+ assert!(append_message(dir.path(), "s", "old", &screenshot()).is_err());+ assert_eq!(fs::read_to_string(&path).unwrap(), raw);+ assert!(read_transcript(dir.path(), "s").is_err());+}++#[test]+fn revisions_checkpoints_compactions_and_indexed_reads_restore_complete_images() {+ let dir = tempfile::tempdir().unwrap();+ let record = screenshot();+ append_message(dir.path(), "s", "old", &record).unwrap();+ let layout = layout::session_layout(dir.path(), "s").unwrap();+ assert_eq!(+ read_transcript_window_with_layout(dir.path(), "s", &layout, 0, Some(1))+ .unwrap()+ .messages[0]+ .blocks,+ record.blocks+ );+ assert_eq!(+ read_tool_call(dir.path(), "s", &layout, "opaque-id")+ .unwrap()+ .unwrap()+ .blocks,+ record.blocks+ );+ let revision = RevisionRecord {+ root_user_id: "root".into(),+ revision_index: 1,+ created_at: record.created_at.clone(),+ messages: vec![record.clone()],+ turns: Default::default(),+ };+ append_revision(dir.path(), "s", &revision).unwrap();+ let branch = read_revision(dir.path(), "s", "root", 1).unwrap().unwrap();+ let RevisionPayload::Stored(branch) = branch else {+ panic!("expected stored revision")+ };+ assert_eq!(branch.messages[0].blocks, record.blocks);+ let checkpoint = InflightRecord {+ schema: INFLIGHT_SCHEMA,+ session_id: "s".into(),+ turn_id: Some("turn".into()),+ saved_at: record.created_at.clone(),+ message: record.clone(),+ };+ write_inflight(dir.path(), "s", &checkpoint).unwrap();+ assert_eq!(+ read_inflight(dir.path(), "s")+ .unwrap()+ .unwrap()+ .message+ .blocks,+ record.blocks+ );+ let compaction = CompactionRecord {+ id: "compact".into(),+ summary: "summary".into(),+ first_kept_message_id: None,+ through_message_id: record.id.clone(),+ tokens_before: 100,+ usage: None,+ retained_tail: Some(json!([record.blocks.clone()])),+ details: None,+ provider_id: None,+ model_id: None,+ created_at: record.created_at.clone(),+ };+ append_compaction(dir.path(), "s", "old", &compaction).unwrap();+ assert_eq!(+ read_compactions(dir.path(), "s").unwrap()[0].retained_tail,+ compaction.retained_tail+ );+ for path in [+ revisions_path(dir.path(), "s").unwrap(),+ inflight_path(dir.path(), "s").unwrap(),+ ] {+ assert_eq!(+ fs::read_to_string(path)+ .unwrap()+ .matches("YWJjLw==")+ .count(),+ 1+ );+ }+}++fn nested_mirror(depth: usize) -> Value {+ let mut result = json!({"content":[{"type":"image","data":"YWJjLw==","mimeType":"image/png"}], "details":{"path":"/old/project/file.png"}});+ for level in 0..depth {+ let text = serde_json::to_string_pretty(&result).unwrap();+ result = json!({"source":format!("层{level}😀"), "nested":{"result":result,"text":text}});+ }+ let content = serde_json::to_string_pretty(&result).unwrap();+ json!({"toolResult":result,"content":content})+}++#[test]+fn nested_result_mirrors_store_each_image_once_and_restore_exactly() {+ for depth in 1..=3 {+ let original = nested_mirror(depth);+ let encoded = binary_storage::encode(original.clone()).unwrap();+ assert_eq!(+ serde_json::to_string(&encoded)+ .unwrap()+ .matches("YWJjLw==")+ .count(),+ 1,+ "depth {depth}"+ );+ assert_eq!(binary_storage::decode(encoded).unwrap(), original);+ }+}++#[test]+fn relocated_nested_mirrors_follow_the_structured_path_without_losing_text() {+ let original = nested_mirror(3);+ let encoded = binary_storage::encode(original).unwrap();+ let relocated = binary_storage::relocate(encoded, |value| {+ value["toolResult"]["nested"]["result"]["nested"]["result"]["nested"]["result"]+ ["details"]["path"] = json!("/new/project/file.png");+ true+ })+ .unwrap();+ assert_eq!(+ serde_json::to_string(&relocated)+ .unwrap()+ .matches("YWJjLw==")+ .count(),+ 1+ );+ let restored = binary_storage::decode(relocated).unwrap();+ assert!(restored["content"]+ .as_str()+ .unwrap()+ .contains("/new/project/file.png"));+ assert!(!restored["content"]+ .as_str()+ .unwrap()+ .contains("/old/project/file.png"));+}++#[test]+fn nested_mirror_dependencies_reject_missing_indexes_and_cycles() {+ for kind in ["missing", "self", "mutual"] {+ let mut encoded = binary_storage::encode(nested_mirror(2)).unwrap();+ let texts = encoded["binaryStorage"]["texts"].as_array_mut().unwrap();+ let (owner, part) = texts+ .iter()+ .enumerate()+ .find_map(|(index, text)| {+ text["parts"]+ .as_array()+ .unwrap()+ .iter()+ .position(|part| part.get("text").is_some())+ .map(|part| (index, part))+ })+ .unwrap();+ let target = texts[owner]["parts"][part]["text"].as_u64().unwrap() as usize;+ texts[owner]["parts"][part]["text"] = json!(match kind {+ "missing" => texts.len(),+ "self" => owner,+ _ => target,+ });+ if kind == "mutual" {+ texts[target]["parts"] = json!(["", {"text":owner}]);+ }+ let error = binary_storage::decode(encoded).unwrap_err();+ assert!(binary_storage::is_error(&error), "{kind}: {error}");+ assert!(+ error+ .to_string()+ .contains(if kind == "missing" { "index" } else { "cycle" }),+ "{error}"+ );+ }+}++#[test]+fn javascript_nested_golden_preserves_escape_spelling_and_dependency_links() {+ let golden: Value = serde_json::from_str(include_str!(+ "../../../../packages/host-runtime/src/fixtures/binary-storage-nested.json"+ ))+ .unwrap();+ assert_eq!(+ binary_storage::decode(golden["encoded"].clone()).unwrap(),+ golden["original"]+ );+ let encoded = binary_storage::encode(golden["original"].clone()).unwrap();+ assert_eq!(+ binary_storage::decode(encoded.clone()).unwrap(),+ golden["original"]+ );+ let data = encoded["binaryStorage"]["data"][0].as_str().unwrap();+ assert_eq!(+ serde_json::to_string(&encoded)+ .unwrap()+ .matches(data)+ .count(),+ 1+ );+}++#[test]+fn headerless_and_empty_legacy_files_receive_a_current_header_once() {+ for empty in [false, true] {+ let dir = tempfile::tempdir().unwrap();+ let path = transcript_path(dir.path(), "s").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ let record = screenshot();+ let mut value = serde_json::to_value(&record).unwrap();+ value["type"] = json!("message");+ fs::write(+ &path,+ if empty {+ String::new()+ } else {+ format!("{value}\n")+ },+ )+ .unwrap();+ let mut next = record.clone();+ next.id = "next".into();+ append_message(dir.path(), "s", "old", &next).unwrap();+ let raw = fs::read_to_string(&path).unwrap();+ let header: Value = serde_json::from_str(raw.lines().next().unwrap()).unwrap();+ assert_eq!(header["type"], "session", "empty={empty}");+ assert_eq!(header["schema"], TRANSCRIPT_SCHEMA);+ assert!(+ !binary_migration::prepare(&path, Some(&header_line("s", "old").unwrap())).unwrap(),+ "already converted files must not be scanned/replaced again"+ );+ assert_eq!(+ read_transcript(dir.path(), "s").unwrap().len(),+ if empty { 1 } else { 2 }+ );+ }+}diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rsindex 6ca93814e..d64b6e53b 100644--- a/crates/host-core/src/turn_queue.rs+++ b/crates/host-core/src/turn_queue.rs@@ -532,7 +532,7 @@ mod tests {assert_eq!(entries[0].content, "existing");assert!(entries[0].user_message_id.is_none());assert!(entries[0].voice_origin.is_none());- assert_eq!(crate::db::SCHEMA_VERSION, 25);+ assert_eq!(crate::db::SCHEMA_VERSION, 26);}#[test]diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 2d2c0e784..d69edbbb8 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,6 +20,7 @@ Each ADR includes:| ID | Title | Status ||---|---|---|+| lossless-tool-image-storage | [Lossless tool-image storage and bounded history mutations](lossless-tool-image-storage.md) | Implemented candidate || browser-background-lifecycle | [Browser page execution outlives side-panel presentation](browser-background-lifecycle.md) | Accepted || asktool-draft-survives-session-switch | [AskTool drafts survive a card remount](asktool-draft-survives-session-switch.md) | Accepted || tool-abort-abandons-host-call | [A user stop ends the turn even when the running tool cannot be cancelled](tool-abort-abandons-host-call.md) | Accepted for implementation |diff --git a/docs/adr/lossless-tool-image-storage.md b/docs/adr/lossless-tool-image-storage.mdnew file mode 100644index 000000000..57b224ff8--- /dev/null+++ b/docs/adr/lossless-tool-image-storage.md@@ -0,0 +1,34 @@+# ADR: Lossless tool-image storage and bounded history mutations++- Status: Implemented candidate+- Date: 2026-10-26+- Issue: #1868++## Context++MCP images are duplicated in structured content/details and exact JSON text+mirrors. A normal long screenshot session can exceed the 64 MiB incoming RPC+frame limit when a Desktop action uploads its retained history. Removing details+bytes changes extension inputs; dropping only text mirrors leaves duplication.++## Decision++Use reversible storage-private per-record image tables and text templates in+Host-owned self-contained files and the Desktop outbox. Decode before business+consumers see the data. Preserve existing public RPC/plugin data shapes and old+file reads. Use a backed-up version-only DB migration to prevent older binaries+from silently interpreting the new records. Convert legacy files only at write,+with verified temporary files and atomic replacement.++Use additive ID commands for remaining normal history operations and retain the+existing full-upload APIs. Keep the 64 MiB limit and explicit failure semantics.+Do not introduce external blob ownership, global deduplication or wire compression.++## Consequences++Images persist once per record without changing visible/plugin/model values.+Failed conversion/drain/restore is visible, preserving original files or pending+writes. New code reads legacy data; old applications cannot open the upgraded+profile. Revisions and forks remain self-contained and may each own a copy.+Unique histories over 64 MiB remain usable via IDs, while arbitrary oversized+requests still fail. Validation must prove exact restoration and actual user paths.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 8bc6deda6..e2d5dfe20 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1,4 +1,32 @@-# 04. Data Storage (Schema v25)+# 04. Data Storage (Schema v26)+++### Lossless tool-image storage (#1868)++Transcript format 2 uses an optional storage-private `binaryStorage` version 1+envelope. Each recognized image/blob string appears once in its record; typed+JSON paths and exact text templates reconstruct the original structured result+and JSON mirror. Templates preserve key order, whitespace and escape spelling. Nested proven+mirrors share text references when their outer JSON string token has canonical+JSON spelling, as produced by `JSON.stringify`; other spellings stay literal.+Arbitrary narrative text is never inferred to be an image or a result mirror.+The public `UiMessage`, plugin card inputs, extension context, model history and+existing RPC request/response objects contain the complete decoded values.++Live transcripts, revisions, checkpoints, compaction tails and the Desktop+outbox share the lossless representation. A first append/update converts an+existing legacy file through a verified sibling temporary file and atomic+replacement. Reading alone never converts files. Conversion failure preserves+the original and propagates an error. Invalid references/unknown codec versions+are errors; restoration must not continue with an empty history.++New code reads both plain legacy records and encoded records. Database schema+26 is a version-only migration with a schema-25 backup: it stops older applications+from misreading a new encoded file. It does not alter user configuration or+rewrite transcripts at startup. Downgrading to an old application requires a+complete compatible backup, not merely swapping the SQLite file. No external+blob directory, new file cleanup lifecycle or lossy image transform is added.+## 0. Ownership decision@@ -237,7 +265,7 @@ commit does not remove historical review evidence.per message; `seq` is implied by line order:```jsonl-{"type":"session","schema":1,"sessionId":"0b0e…","createdAt":"2026-07-26T09:00:00.000Z"}+{"type":"session","schema":2,"sessionId":"0b0e…","createdAt":"2026-07-26T09:00:00.000Z"}{"type":"message","id":"m1","role":"user","createdAt":"…","blocks":[{"type":"text","text":"…"}]}{"type":"message","id":"m2","role":"tool","toolName":"Write","blocks":[{"type":"tool_call","callId":"c1","args":{},"result":{},"status":"success"}]}{"type":"message","id":"m3","role":"assistant","createdAt":"…","blocks":[{"type":"thinking","text":"…"},{"type":"text","text":"…"}],"meta":{"usage":{},"modelId":"…"}}@@ -581,7 +609,7 @@ Refresh (spec 13 §6/§9) upserts `discovered` rows and **never overwrites`source='user'`** rows. Recent-model MRU stays in `kv(cache)` — it is abounded display list, not relational data.-Schema v25 adds nullable `discovery_state`, distinct from metadata deprecation.+Schema v26 adds nullable `discovery_state`, distinct from metadata deprecation.The v24 upgrade backs up first, adds the field transactionally, and marksexisting discovered rows as past publication evidence. User-owned rows remainunknown. No provider configuration, credentials, sessions, or turns are changed.diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex 7e5a92e13..dd78255c5 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -1,5 +1,33 @@# 06. Host RPC Protocol++### Bounded existing-history operations (#1868)++The Desktop uses additive Host methods for existing history: `session.deleteMessage`+takes `sessionId/messageId` and returns `ok/deleted/deletedCount`;+`session.retractPendingPrompt` takes `sessionId/userMessageId` and optional+`turnId`, returning `ok/retracted/removedCount` and a refusal `reason` when needed.+Host verifies canonical message/turn ownership and meaningful reply activity;+a refused retract leaves history intact. Repeating an already completed deletion+or retraction does not delete another prompt. No history array is required.++`session.activateRevision` accepts optional `requireCanonicalPrefix: true` to+require a durable Host prefix; a missing family/anchor fails explicitly. Existing+explicit-prefix activation, `session.replaceMessages`, `session.saveRevision`+and their original request/response forms remain supported. Existing edit and+regenerate continue using `session.truncateFrom`; branch archival and fork+remain Host-owned. Oversized local requests report the method and UTF-8 byte count without payload+content; the caller sees a local-transport explanation and the existing session+Fork recovery path. No identical oversized payload is retried.+The unchanged 64 MiB limit still applies to arbitrary incoming+requests, including a genuinely oversized single tool result.++ID mutations use the same session operation lock, rewrite fence and runtime+disposal boundary. Their outbox drain must confirm all target-session entries+were written; failure preserves the queue and rejects the mutation. Smart-stop+restores a draft only after Host confirmation, and exposes failures.++## 1. GoalDefine the local protocol between:diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0b6ed5423..3e3b9f3a4 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6,6 +6,25 @@---++### E2E-TRANSCRIPT-lossless-tool-images++- Entry: `PI_DESKTOP_HOST_BIN=<candidate-host> pnpm test:e2e:tool-result-persistence`+ after building Host, shared, agent-runtime and host-runtime.+- Environment: Real isolated Host, SQLite and JSONL, production Desktop IPC and+ outbox; only Electron shell and unused importer/search services are stubs.+- Build 35 deterministic valid PNGs / 548 rows. Verify the old redundant full+ request exceeds 64 MiB, each stored image occurs once, and restarting restores+ every canonical image, detail field and original JSON text spelling.+- Build a second history whose unique image bytes alone exceed 64 MiB through+ individually legal appends. Exercise bounded ID operations and retained-image+ restoration, revision/fork, missing anchors and duplicate operation retries.+- Unit/process gates also cover old-format files/outbox, corrupted references,+ failed conversion/drain, late callbacks and real sidecar restore errors.+- The original Windows incident did not identify the failed RPC method; this+ deterministic regression does not claim to recover that missing evidence.++## 1. Goals### E2E model discovery membershipdiff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 3ec3db405..4d0a78edc 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -1,8 +1,36 @@-# 04. 数据存储(架构 v23)+# 04. 数据存储(架构 v26)> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/04-data-storage) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。++### Lossless tool-image storage (#1868)++Transcript format 2 uses an optional storage-private `binaryStorage` version 1+envelope. Each recognized image/blob string appears once in its record; typed+JSON paths and exact text templates reconstruct the original structured result+and JSON mirror. Templates preserve key order, whitespace and escape spelling. Nested proven+mirrors share text references when their outer JSON string token has canonical+JSON spelling, as produced by `JSON.stringify`; other spellings stay literal.+Arbitrary narrative text is never inferred to be an image or a result mirror.+The public `UiMessage`, plugin card inputs, extension context, model history and+existing RPC request/response objects contain the complete decoded values.++Live transcripts, revisions, checkpoints, compaction tails and the Desktop+outbox share the lossless representation. A first append/update converts an+existing legacy file through a verified sibling temporary file and atomic+replacement. Reading alone never converts files. Conversion failure preserves+the original and propagates an error. Invalid references/unknown codec versions+are errors; restoration must not continue with an empty history.++New code reads both plain legacy records and encoded records. Database schema+26 is a version-only migration with a schema-25 backup: it stops older applications+from misreading a new encoded file. It does not alter user configuration or+rewrite transcripts at startup. Downgrading to an old application requires a+complete compatible backup, not merely swapping the SQLite file. No external+blob directory, new file cleanup lifecycle or lossy image transform is added.++## 0. 所有权决定**Rust host-core 独家拥有 SQLite (D002),以及转录文件@@ -98,7 +126,7 @@ commit 不会删除历史审查证据。每条消息; `seq` 由行顺序隐含:```jsonl-{"type":"session","schema":1,"sessionId":"0b0e…","createdAt":"2026-07-26T09:00:00.000Z"}+{"type":"session","schema":2,"sessionId":"0b0e…","createdAt":"2026-07-26T09:00:00.000Z"}{"type":"message","id":"m1","role":"user","createdAt":"…","blocks":[{"type":"text","text":"…"}]}{"type":"message","id":"m2","role":"tool","toolName":"Write","blocks":[{"type":"tool_call","callId":"c1","args":{},"result":{},"status":"success"}]}{"type":"message","id":"m3","role":"assistant","createdAt":"…","blocks":[{"type":"thinking","text":"…"},{"type":"text","text":"…"}],"meta":{"usage":{},"modelId":"…"}}diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex b47139846..2d692bd00 100644--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@ -3,6 +3,34 @@> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/06-host-rpc-protocol) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。++### Bounded existing-history operations (#1868)++The Desktop uses additive Host methods for existing history: `session.deleteMessage`+takes `sessionId/messageId` and returns `ok/deleted/deletedCount`;+`session.retractPendingPrompt` takes `sessionId/userMessageId` and optional+`turnId`, returning `ok/retracted/removedCount` and a refusal `reason` when needed.+Host verifies canonical message/turn ownership and meaningful reply activity;+a refused retract leaves history intact. Repeating an already completed deletion+or retraction does not delete another prompt. No history array is required.++`session.activateRevision` accepts optional `requireCanonicalPrefix: true` to+require a durable Host prefix; a missing family/anchor fails explicitly. Existing+explicit-prefix activation, `session.replaceMessages`, `session.saveRevision`+and their original request/response forms remain supported. Existing edit and+regenerate continue using `session.truncateFrom`; branch archival and fork+remain Host-owned. Oversized local requests report the method and UTF-8 byte count without payload+content; the caller sees a local-transport explanation and the existing session+Fork recovery path. No identical oversized payload is retried.+The unchanged 64 MiB limit still applies to arbitrary incoming+requests, including a genuinely oversized single tool result.++ID mutations use the same session operation lock, rewrite fence and runtime+disposal boundary. Their outbox drain must confirm all target-session entries+were written; failure preserves the queue and rejects the mutation. Smart-stop+restores a draft only after Host confirmation, and exposes failures.++## 1. Goal定义以下之间的本地协议:diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 0d853866b..52434cf98 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -115,6 +115,25 @@- **预期:** 取消编辑保留原绑定;保存清除候选和默认生图绑定。重新打开后摘要行隐藏、复选框未勾选,模型恢复为可选对话模型。- **覆盖:** `scripts/e2e-image-generation-ui.mjs` 使用 API 边界 fixture 验证英文与中文交互;不代表真实服务商测试。++### E2E-TRANSCRIPT-lossless-tool-images++- Entry: `PI_DESKTOP_HOST_BIN=<candidate-host> pnpm test:e2e:tool-result-persistence`+ after building Host, shared, agent-runtime and host-runtime.+- Environment: Real isolated Host, SQLite and JSONL, production Desktop IPC and+ outbox; only Electron shell and unused importer/search services are stubs.+- Build 35 deterministic valid PNGs / 548 rows. Verify the old redundant full+ request exceeds 64 MiB, each stored image occurs once, and restarting restores+ every canonical image, detail field and original JSON text spelling.+- Build a second history whose unique image bytes alone exceed 64 MiB through+ individually legal appends. Exercise bounded ID operations and retained-image+ restoration, revision/fork, missing anchors and duplicate operation retries.+- Unit/process gates also cover old-format files/outbox, corrupted references,+ failed conversion/drain, late callbacks and real sidecar restore errors.+- The original Windows incident did not identify the failed RPC method; this+ deterministic regression does not claim to recover that missing evidence.++## 1. 目标- 记录 MVP 必须验证的每个用户可见和协议可见的行为。diff --git a/package.json b/package.jsonindex b91451644..38cf999be 100644--- a/package.json+++ b/package.json@@ -30,6 +30,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:tool-result-persistence": "node --max-old-space-size=4096 scripts/e2e-tool-result-persistence.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",diff --git a/packages/host-runtime/src/host-process.ts b/packages/host-runtime/src/host-process.tsindex 8729e526b..69be7bfb0 100644--- a/packages/host-runtime/src/host-process.ts+++ b/packages/host-runtime/src/host-process.ts@@ -302,10 +302,15 @@ export class HostProcess {const id = randomUUID();const timeoutMs = timeoutOverrideMs ?? rpcTimeoutMs(method, params);const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";- if (Buffer.byteLength(payload, "utf8") > MAX_HOST_STDIN_LINE_BYTES) {- throw Object.assign(new Error("request line exceeds 64 MiB"), {+ const requestBytes = Buffer.byteLength(payload, "utf8");+ if (requestBytes > MAX_HOST_STDIN_LINE_BYTES) {+ throw Object.assign(new Error(+ "Local request line exceeds 64 MiB. This request was not sent. " ++ "Use Fork from the session menu to preserve the history in a separate conversation.",+ ), {errorCode: ErrorCodes.LIMIT_EXCEEDED,code: 1002,+ data: { scope: "host-request", method, requestBytes, limitBytes: MAX_HOST_STDIN_LINE_BYTES },});}return new Promise<T>((resolve, reject) => {diff --git a/packages/host-runtime/src/host-request-limit.test.ts b/packages/host-runtime/src/host-request-limit.test.tsnew file mode 100644index 000000000..a4971c113--- /dev/null+++ b/packages/host-runtime/src/host-request-limit.test.ts@@ -0,0 +1,51 @@+import { MAX_HOST_STDIN_LINE_BYTES } from "@pi-desktop/shared";+import { describe, expect, it } from "vitest";+import { HostProcess } from "./host-process.js";++describe("local Host request limit", () => {+ it("reports method and UTF-8 size without writing or retrying an oversized request", async () => {+ let writes = 0;+ const host = Object.assign(Object.create(HostProcess.prototype), {+ closed: false,+ available: true,+ disposed: false,+ child: {+ exitCode: null,+ killed: false,+ stdin: {+ writable: true,+ destroyed: false,+ write() {+ writes++;+ },+ },+ },+ }) as HostProcess;+ const once = (host as any).callOnce.bind(host);+ let attempts = 0;+ (host as any).callOnce = (...args: unknown[]) => {+ attempts++;+ return once(...args);+ };+ const params = { content: "x".repeat(MAX_HOST_STDIN_LINE_BYTES) };+ let failure: any;+ try {+ await host.call("session.replaceMessages", params);+ } catch (error) {+ failure = error;+ }+ expect(failure).toMatchObject({+ errorCode: "LIMIT_EXCEEDED",+ code: 1002,+ data: {+ method: "session.replaceMessages",+ limitBytes: MAX_HOST_STDIN_LINE_BYTES,+ scope: "host-request",+ },+ });+ expect(failure.data.requestBytes).toBeGreaterThan(MAX_HOST_STDIN_LINE_BYTES);+ expect(JSON.stringify(failure)).not.toContain(params.content);+ expect(writes).toBe(0);+ expect(attempts).toBe(1);+ });+});diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex d4673ecfc..3be4d42ed 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -318,6 +318,7 @@ export const de = {sessionMissing: "Diese Sitzung existiert nicht mehr",},"chat": {+ promptRetractionFailed: "Der Entwurf konnte nicht sicher wiederhergestellt werden. Der Gesprächsverlauf bleibt erhalten.","tableActions": "Tabellenaktionen","markdownPlainTextFallback": "Große Antworten werden zur besseren Reaktionsfähigkeit als Klartext angezeigt.","largeTextPageControls": "Seiten der großen Ausgabe",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 8f81407d0..038578cc7 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -325,6 +325,7 @@ export const en = {sessionMissing: "That session no longer exists",},chat: {+ promptRetractionFailed: "Could not safely restore the draft. Your conversation has been preserved.",tableActions: "Table actions",markdownPlainTextFallback: "Large response shown as plain text to keep the conversation responsive.",largeTextPageControls: "Large output pages",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 0b2d870b3..70014efaf 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -318,6 +318,7 @@ export const es = {sessionMissing: "Esa sesión ya no existe",},"chat": {+ promptRetractionFailed: "No se pudo restaurar el borrador de forma segura. Se ha conservado la conversación.","tableActions": "Acciones de tabla","markdownPlainTextFallback": "La respuesta extensa se muestra como texto sin formato para mantener la fluidez.","largeTextPageControls": "Páginas de la salida extensa",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex e4c1ed23c..fc79b6e49 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -318,6 +318,7 @@ export const fr = {sessionMissing: "Cette session n'existe plus",},"chat": {+ promptRetractionFailed: "Impossible de restaurer le brouillon en toute sécurité. La conversation a été conservée.","tableActions": "Actions du tableau","markdownPlainTextFallback": "La réponse volumineuse est affichée en texte brut pour préserver la réactivité.","largeTextPageControls": "Pages de la sortie volumineuse",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex df9576c0b..1a5f3cd3d 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -327,6 +327,7 @@ export const ko = {sessionMissing: "해당 세션이 더 이상 존재하지 않습니다",},chat: {+ promptRetractionFailed: "초안을 안전하게 복원하지 못했습니다. 대화 내용은 보존되었습니다.",tableActions: "표 작업",markdownPlainTextFallback: "긴 응답은 화면의 반응성을 유지하기 위해 일반 텍스트로 표시됩니다.",largeTextPageControls: "대용량 출력 페이지",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex ccef8e9a3..46a2c393c 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -317,6 +317,7 @@ export const ptBR = {sessionMissing: "Essa sessão não existe mais"},chat: {+ promptRetractionFailed: "Não foi possível restaurar o rascunho com segurança. A conversa foi preservada.",tableActions: "Ações da tabela",markdownPlainTextFallback: "Respostas extensas são exibidas como texto simples para manter a interface responsiva.",largeTextPageControls: "Páginas da saída extensa",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 88726748a..6fd1c016b 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -327,6 +327,7 @@ export const tr = {sessionMissing: "Bu oturum artık mevcut değil",},chat: {+ promptRetractionFailed: "Taslak güvenli biçimde geri yüklenemedi. Konuşmanız korundu.",tableActions: "Tablo işlemleri",markdownPlainTextFallback: "Büyük yanıtlar arayüzün duyarlı kalması için düz metin olarak gösterilir.",largeTextPageControls: "Büyük çıktı sayfaları",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 551cc80ff..36eaa4f2b 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -320,6 +320,7 @@ export const zhCN = {sessionMissing: "该会话已不存在",},chat: {+ promptRetractionFailed: "无法安全恢复草稿。会话内容已保留。",tableActions: "表格操作",markdownPlainTextFallback: "内容较长,为保持界面响应速度,现以纯文本显示。",largeTextPageControls: "大段输出分页",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 6e962a278..b9cee4465 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -320,6 +320,7 @@ export const zhTW = {sessionMissing: "該對話已不存在",},chat: {+ promptRetractionFailed: "無法安全恢復草稿。對話內容已保留。",tableActions: "表格操作",markdownPlainTextFallback: "內容較長,為維持介面回應速度,現以純文字顯示。",largeTextPageControls: "大型輸出分頁",diff --git a/scripts/e2e-tool-result-persistence.mjs b/scripts/e2e-tool-result-persistence.mjsnew file mode 100644index 000000000..113521fe4--- /dev/null+++ b/scripts/e2e-tool-result-persistence.mjs@@ -0,0 +1,204 @@+#!/usr/bin/env node+import assert from "node:assert/strict";+import { cp, mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { deflateSync } from "node:zlib";+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import { HostProcess } from "../packages/host-runtime/dist/host-process.js";+import { MAX_HOST_STDIN_LINE_BYTES } from "../packages/shared/dist/index.js";+import { toolResultFromUi } from "../packages/agent-runtime/dist/runtime.js";+import { transcriptRewriteHarness } from "../apps/desktop/test/helpers/transcript-rewrite-harness.mjs";++// Valid, deterministic PNGs with incompressible pixels approximate the reported+// 35 screenshots / 25 MB of distinct base64 without private screenshots or APIs.+function screenshot(seed) {+ const side = 420;+ const pixels = Buffer.alloc((side * 3 + 1) * side);+ let state = seed;+ for (let y = 0; y < side; y++) {+ for (let x = 1; x <= side * 3; x++) {+ state ^= state << 13; state ^= state >>> 17; state ^= state << 5;+ pixels[y * (side * 3 + 1) + x] = state & 255;+ }+ }+ function chunk(name, bytes) {+ const body = Buffer.concat([Buffer.from(name), bytes]);+ let crc = 0xffffffff;+ for (const byte of body) {+ crc ^= byte;+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);+ }+ const size = Buffer.alloc(4); size.writeUInt32BE(bytes.length);+ const checksum = Buffer.alloc(4); checksum.writeUInt32BE((crc ^ 0xffffffff) >>> 0);+ return Buffer.concat([size, body, checksum]);+ }+ const header = Buffer.alloc(13);+ header.writeUInt32BE(side); header.writeUInt32BE(side, 4); header[8] = 8; header[9] = 2;+ return Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), chunk("IHDR", header), chunk("IDAT", deflateSync(pixels)), chunk("IEND", Buffer.alloc(0))]).toString("base64");+}++const binaryPath = process.env.PI_DESKTOP_HOST_BIN;+assert.ok(binaryPath, "PI_DESKTOP_HOST_BIN must name the candidate's built Host binary");+const dataDir = await mkdtemp(join(tmpdir(), "pi-tool-image-e2e-"));+const createdAt = "2026-10-24T19:00:00.000Z";+let host;+let movedDataDir;+let largestMutationBytes = 0;+function start(directory = dataDir) {+ const childHost = new HostProcess({ binaryPath, dataDir: directory, onStderr: (text) => process.stderr.write(text) });+ const call = childHost.call.bind(childHost);+ childHost.call = (method, params, ...rest) => {+ if (["session.deleteMessage", "session.retractPendingPrompt", "session.activateRevision"].includes(method)) {+ const bytes = Buffer.byteLength(JSON.stringify({ method, params }));+ largestMutationBytes = Math.max(largestMutationBytes, bytes);+ assert.ok(bytes < 512, "existing-history operations must contain IDs, never image history");+ }+ return call(method, params, ...rest);+ };+ return childHost;+}+function row(index) {+ const image = { type: "image", data: screenshot(index + 1), mimeType: "image/png" };+ const content = [{ type: "text", text: `Screenshot ${index + 1}` }, image];+ const result = { content, details: { content, imageCount: 1, label: "保留 metadata" } };+ return { id: `call-${index}`, role: "tool", toolCallId: `call-${index}`, toolName: "mcp_windows_mcp_Snapshot", toolStatus: "success", content: JSON.stringify(result, null, 2), toolResult: result, createdAt };+}+function nestedRow(path) {+ const image = { type: "image", data: screenshot(9000), mimeType: "image/png" };+ let result = { content: [image], details: { path } };+ for (let level = 0; level < 3; level++) {+ const text = JSON.stringify(result, null, 2);+ result = { content: [image], source: `层${level}😀`, nested: { result, text } };+ }+ return { id: "nested-result", role: "tool", toolCallId: "nested-result", toolName: "Snapshot", toolStatus: "success", content: JSON.stringify(result, null, 2), toolResult: result, createdAt };+}+async function session(title) { return (await host.call("session.create", { title, mode: "agent" })).session.id; }+async function append(sessionId, message, turnId) { await host.call("session.appendMessage", { sessionId, message, ...(turnId ? { turnId } : {}) }); }+async function verifyPages(sessionId, expected, images, forked = false) {+ for (let start = 0; start < expected.length; start += 10) {+ const page = (await host.call("session.get", { id: sessionId, messageBefore: Math.min(expected.length, start + 10), messageLimit: Math.min(10, expected.length-start) })).session;+ if (!forked) assert.deepEqual(page.messages.map((m) => m.id), expected.slice(start, start+10).map((m) => m.id));+ for (const [offset, actual] of page.messages.entries()) {+ const expectedRow = expected[start + offset];+ assert.equal(actual.content, expectedRow.content);+ const original = images.get(expectedRow.id);+ if (!original) continue;+ assert.equal(actual.content, original.content, "mirror spelling must survive restart exactly");+ assert.deepEqual(actual.toolResult, original.toolResult, "plugins must receive the complete original result");+ const restored = toolResultFromUi(actual, 1);+ assert.deepEqual(restored.content, original.toolResult.content);+ assert.deepEqual(restored.details, original.toolResult.details);+ }+ }+}+try {+ host = start(); await host.handshake();+ const smallId = await session("35 screenshots / 548 messages");+ const small = [{ id: "root-user", role: "user", content: "Keep screenshot history", createdAt }];+ const originals = new Map();+ for (let index = 0; index < 35; index++) { const message = row(index); small.push(message); originals.set(message.id, message); }+ while (small.length < 548) small.push({ id: `text-${small.length}`, role: "assistant", content: `Retained ${small.length}`, createdAt });+ const oldBytes = Buffer.byteLength(JSON.stringify({ jsonrpc: "2.0", id: "baseline", method: "session.replaceMessages", params: { sessionId: smallId, messages: small } }) + "\n");+ assert.ok(oldBytes > MAX_HOST_STDIN_LINE_BYTES);+ await assert.rejects(host.call("session.replaceMessages", { sessionId: smallId, messages: small }), { errorCode: "LIMIT_EXCEEDED", code: 1002 });+ for (const message of small) await append(smallId, message);+ const raw = await readFile(join(dataDir, "sessions", `${smallId}.jsonl`), "utf8");+ for (const original of originals.values()) assert.equal(raw.split(original.toolResult.content[1].data).length - 1, 1);+ const { decodeBinaryStorage } = await import("../packages/host-runtime/dist/binary-storage.js");+ const encodedRow = raw.split("\n").filter(Boolean).map(JSON.parse).find((m) => m.id === "call-0");+ const crossLanguage = decodeBinaryStorage(encodedRow);+ assert.deepEqual(crossLanguage.blocks[0].result, originals.get("call-0").toolResult);+ assert.equal(crossLanguage.blocks[0].text, originals.get("call-0").content);+ await host.dispose(); host = start(); await host.handshake();+ await verifyPages(smallId, small, originals);+ const harness = transcriptRewriteHarness(host, dataDir);+ const deletion = await harness.deleteMessage({ sessionId: smallId, messageId: "text-547" });+ assert.equal(deletion.deleted, true); small.pop();+ assert.equal((await harness.deleteMessage({ sessionId: smallId, messageId: "text-547" })).deleted, false);+ await verifyPages(smallId, small, originals);+ console.log(JSON.stringify({ phase: "35-screenshot-history", screenshots: 35, oldRequestBytes: oldBytes, storedBytes: Buffer.byteLength(raw), retainedMessages: small.length }));++ // Unique bytes alone cross 64 MiB. Build through legal individual requests,+ // so success cannot be a fortuitous 99 MB -> 49 MB boundary crossing.+ const largeId = await session("Unique images exceed 64 MiB");+ const root = { id: "large-root", role: "user", content: "Keep large history", createdAt };+ const expected = [root]; let uniqueBytes = 0;+ await append(largeId, root);+ for (let index = 0; uniqueBytes <= MAX_HOST_STDIN_LINE_BYTES; index++) {+ const message = row(index + 1000); uniqueBytes += message.toolResult.content[1].data.length;+ await append(largeId, message); expected.push(message);+ }+ const largeCount = expected.length;+ console.log(JSON.stringify({ phase: "large-history-built", uniqueBytes, images: largeCount - 1 }));+ await host.call("session.saveActiveRevision", { sessionId: largeId });+ const tip = { id: "delete-tip", role: "assistant", content: "Delete only this row", createdAt };+ await append(largeId, tip);+ assert.equal((await harness.deleteMessage({ sessionId: largeId, messageId: tip.id })).deletedCount, 1);+ const { turnId } = await host.call("session.beginTurn", { sessionId: largeId });+ const pending = { id: "pending-user", role: "user", content: "Restore my draft", createdAt };+ await append(largeId, pending, turnId);+ await host.call("session.endTurn", { turnId, status: "aborted", createNotification: false });+ assert.equal((await harness.retractPendingPrompt({ sessionId: largeId, userMessageId: pending.id, turnId })).retracted, true);+ assert.equal((await harness.retractPendingPrompt({ sessionId: largeId, userMessageId: pending.id, turnId })).retracted, false);+ // A late user turn has a small branch but a >64 MiB image prefix. Switch+ // its revisions without uploading that prefix, then remove only that turn.+ const branchUser = { id: "branch-user", role: "user", content: "Regenerate this turn", createdAt };+ const branchAnswer = { id: "branch-answer", role: "assistant", content: "original answer", createdAt };+ await append(largeId, branchUser); await append(largeId, branchAnswer);+ const archived = await host.call("session.truncateFrom", { sessionId: largeId, fromMessageId: branchUser.id });+ assert.ok(archived.revision, "regenerate must archive the removed branch");+ await append(largeId, { ...branchUser, id: "new-branch-user", revisionRootId: branchUser.id, revisionCount: archived.revision.revisionCount, activeRevision: archived.revision.activeRevision });+ await append(largeId, { ...branchAnswer, id: "new-branch-answer", content: "new answer" });+ const saved = await host.call("session.saveActiveRevision", { sessionId: largeId });+ assert.ok(saved.saved, "automatic archival remains Host-owned");+ const revisions = await host.call("session.listRevisions", { sessionId: largeId, rootUserId: branchUser.id });+ const selected = await harness.activateRevision({ sessionId: largeId, rootUserId: branchUser.id, revisionIndex: revisions.revisions[0].revisionIndex, requireCanonicalPrefix: true });+ assert.equal(selected.messages.at(-1).content, branchAnswer.content);+ assert.deepEqual(selected.messages.find((m) => m.id === expected[1].id).toolResult, expected[1].toolResult);+ assert.equal((await harness.deleteMessage({ sessionId: largeId, messageId: branchUser.id })).deletedCount, 2);+ await assert.rejects(harness.activateRevision({ sessionId: largeId, rootUserId: "missing-root", revisionIndex: 0, requireCanonicalPrefix: true }));+ const fork = await host.call("session.fork", { sessionId: largeId, throughMessageId: expected.at(-1).id });+ assert.equal(fork.session.messages.length, largeCount);+ await host.dispose(); host = start(); await host.handshake();+ const expectedImages = new Map(expected.filter((m) => m.role === "tool").map((m) => [m.id, m]));+ for (const id of [largeId, fork.session.id]) {+ await verifyPages(id, expected, expectedImages, id !== largeId);+ const last = (await host.call("session.get", { id, messageLimit: 1 })).session;+ if (id === largeId) assert.equal(last.messages[0].id, expected.at(-1).id);+ else assert.notEqual(last.messages[0].id, expected.at(-1).id, "fork must namespace message identities");+ assert.deepEqual(last.messages[0].toolResult, expected.at(-1).toolResult);+ }+ const after = (await host.call("session.get", { id: largeId, messageLimit: 1 })).session;+ assert.equal(after.messages[0].id, expected.at(-1).id);+ console.log(JSON.stringify({ phase: "over-64-MiB-unique-history", uniqueImageBytes: uniqueBytes, images: largeCount-1, largestMutationBytes, result: "pass" }));+ const nestedId = await session("Nested image result survives profile relocation");+ const originalNested = nestedRow(join(dataDir, "scratch", "nested.png"));+ await append(nestedId, originalNested);+ const nestedPath = join("sessions", `${nestedId}.jsonl`);+ const originalNestedRaw = await readFile(join(dataDir, nestedPath), "utf8");+ assert.equal(originalNestedRaw.split(originalNested.toolResult.content[0].data).length - 1, 1);+ const nestedEncoded = originalNestedRaw.split("\n").filter(Boolean).map(JSON.parse).find((row) => row.id === originalNested.id);+ const nestedDecoded = decodeBinaryStorage(nestedEncoded);+ assert.deepEqual(nestedDecoded.blocks[0].result, originalNested.toolResult, "TS decodes nested Rust output");+ assert.equal(nestedDecoded.blocks[0].text, originalNested.content);+ await host.dispose(); host = undefined;+ movedDataDir = await mkdtemp(join(tmpdir(), "pi-tool-image-moved-"));+ await cp(dataDir, movedDataDir, { recursive: true });+ await promisify(execFile)(binaryPath, ["--relocate-data", dataDir, movedDataDir]);+ assert.equal(await readFile(join(dataDir, nestedPath), "utf8"), originalNestedRaw, "relocation leaves source intact");+ host = start(movedDataDir); await host.handshake();+ const movedNested = (await host.call("session.get", { id: nestedId })).session.messages[0];+ const expectedNested = nestedRow(join(movedDataDir, "scratch", "nested.png"));+ assert.deepEqual(movedNested.toolResult, expectedNested.toolResult);+ assert.equal(movedNested.content, expectedNested.content);+ const movedRaw = await readFile(join(movedDataDir, nestedPath), "utf8");+ assert.equal(movedRaw.split(originalNested.toolResult.content[0].data).length - 1, 1);+ assert.deepEqual((await host.call("session.get", { id: largeId, messageLimit: 1 })).session.messages[0].toolResult, expected.at(-1).toolResult);+ console.log(JSON.stringify({ phase: "nested-cross-language-profile-relocation", levels: 3, storedCopies: 1, result: "pass" }));+} finally {+ if (host) await host.dispose();+ await rm(dataDir, { recursive: true, force: true });+ if (movedDataDir) await rm(movedDataDir, { recursive: true, force: true });+}