Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(transcripts): preserve bounded reads across invalid UTF-8
vastsa80dc767b03dd
diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rsindex 629dd3a6f..60676e79d 100644--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@ -189,13 +189,17 @@ pub fn find_message_position(id: String,}let mut reader = BufReader::new(File::open(transcript_path(data_dir, session_id)?)?);+ let mut raw = Vec::new();let mut line = String::new();for (position, offset) in layout.message_offsets.iter().enumerate().rev() {- read_layout_line(&mut reader, *offset, "message", &mut line)?;- let identity: Identity =- serde_json::from_str(&line).context("decode indexed transcript message identity")?;- if identity.id == message_id {- return Ok(Some(position));+ let invalid_utf8 = read_layout_line(&mut reader, *offset, "message", &mut raw, &mut line)?;+ match serde_json::from_str::<Identity>(&line) {+ Ok(identity) if identity.id == message_id => return Ok(Some(position)),+ Ok(_) => {}+ Err(error) if invalid_utf8 => {+ tracing::warn!(%error, "skipping invalid indexed transcript identity");+ }+ Err(error) => return Err(error).context("decode indexed transcript message identity"),}}Ok(None)@@ -210,6 +214,7 @@ pub fn read_tool_call(call_id: &str,) -> Result<Option<MessageRecord>> {let mut reader = BufReader::new(File::open(transcript_path(data_dir, session_id)?)?);+ let mut raw = Vec::new();let mut line = String::new();// A provider tool-call id is an opaque token, so it appears verbatim in the// line that stores it. A byte scan rejects a line before serde walks its@@ -217,12 +222,20 @@ pub fn read_tool_call(// that JSON would escape keeps the unfiltered path.let verbatim = is_json_verbatim(call_id);for offset in layout.message_offsets.iter().rev() {- read_layout_line(&mut reader, *offset, "message", &mut line)?;+ let invalid_utf8 = read_layout_line(&mut reader, *offset, "message", &mut raw, &mut line)?;if verbatim && !line.contains(call_id) {continue;}- let identity: Value =- serde_json::from_str(&line).context("decode indexed transcript tool-call identity")?;+ let identity: Value = match serde_json::from_str(&line) {+ Ok(value) => value,+ Err(error) if invalid_utf8 => {+ tracing::warn!(%error, "skipping invalid indexed transcript tool-call identity");+ continue;+ }+ Err(error) => {+ return Err(error).context("decode indexed transcript tool-call identity");+ }+ };let matches_call = identity.get("role").and_then(Value::as_str) == Some("tool")&& identity.get("blocks")@@ -233,7 +246,15 @@ pub fn read_tool_call(.any(|block| block.get("callId").and_then(Value::as_str) == Some(call_id))});if matches_call {- return Ok(Some(serde_json::from_str(&line)?));+ match serde_json::from_str(&line) {+ Ok(record) => return Ok(Some(record)),+ Err(error) if invalid_utf8 => {+ tracing::warn!(%error, "skipping invalid indexed tool-call message");+ }+ Err(error) => {+ return Err(error).context("decode indexed transcript tool-call message")+ }+ }}}Ok(None)@@ -248,40 +269,43 @@ pub(crate) fn read_line_tolerant(reader: &mut BufReader<File>,raw_buf: &mut Vec<u8>,line_buf: &mut String,-) -> std::io::Result<usize> {+) -> std::io::Result<(usize, bool)> {raw_buf.clear();let n = reader.read_until(b'\n', raw_buf)?;if n == 0 {line_buf.clear();- return Ok(0);+ return Ok((0, false));}line_buf.clear();- match std::str::from_utf8(raw_buf) {- Ok(valid) => line_buf.push_str(valid),- Err(_) => line_buf.push_str(&String::from_utf8_lossy(raw_buf)),+ match String::from_utf8(std::mem::take(raw_buf)) {+ Ok(decoded) => {+ *raw_buf = std::mem::replace(line_buf, decoded).into_bytes();+ Ok((n, false))+ }+ Err(error) => {+ let bytes = error.into_bytes();+ line_buf.push_str(&String::from_utf8_lossy(&bytes));+ *raw_buf = bytes;+ Ok((n, true))+ }}- Ok(n)}fn read_layout_line(reader: &mut BufReader<File>,offset: u64,expected_kind: &str,+ raw: &mut Vec<u8>,line: &mut String,-) -> Result<()> {+) -> Result<bool> {reader.seek(SeekFrom::Start(offset))?;- line.clear();- match reader.read_line(line) {- Ok(0) => return Err(layout::invalid_boundary()),- Ok(_) => {}- Err(error) if error.kind() == std::io::ErrorKind::InvalidData => {- return Err(layout::invalid_boundary())- }- Err(error) => return Err(error.into()),+ let (read, invalid_utf8) = read_line_tolerant(reader, raw, line)?;+ if read == 0 {+ return Err(layout::invalid_boundary());}if !line.ends_with('\n') || sniff_line_kind(line.trim_end()) != Some(expected_kind) {return Err(layout::invalid_boundary());}- Ok(())+ Ok(invalid_utf8)}/// Whether a JSON string for this value is the value itself.@@ -320,7 +344,7 @@ pub fn transcript_contains_id(data_dir: &Path, session_id: &str, message_id: &stlet mut line = String::new();loop {line.clear();- if read_line_tolerant(&mut reader, &mut raw, &mut line)? == 0 {+ if read_line_tolerant(&mut reader, &mut raw, &mut line)?.0 == 0 {return Ok(false);}let trimmed = line.trim();@@ -913,22 +937,34 @@ pub fn read_transcript_window_with_layout(Err(e) => return Err(e).with_context(|| format!("read {}", path.display())),};let mut reader = BufReader::new(file);+ let mut raw = Vec::new();let mut line = String::new();for (offset, is_message) in wanted {let kind = if is_message { "message" } else { "compaction" };- read_layout_line(&mut reader, offset, kind, &mut line)+ let invalid_utf8 = read_layout_line(&mut reader, offset, kind, &mut raw, &mut line).with_context(|| format!("read indexed transcript line in {}", path.display()))?;let trimmed = line.trim();if is_message {- out.messages.push(- serde_json::from_str::<MessageRecord>(trimmed)- .context("decode indexed transcript message")?,- );+ match serde_json::from_str::<MessageRecord>(trimmed) {+ Ok(record) => out.messages.push(record),+ 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 {- out.compactions.push(- serde_json::from_str::<CompactionRecord>(trimmed)- .context("decode indexed transcript compaction")?,- );+ match serde_json::from_str::<CompactionRecord>(trimmed) {+ Ok(record) => out.compactions.push(record),+ Err(error) if invalid_utf8 => {+ tracing::warn!(path = %path.display(), %error, "skipping invalid indexed compaction line");+ }+ Err(error) => {+ return Err(error).context("decode indexed transcript compaction");+ }+ }+ }+ if raw.capacity() > 1024 * 1024 {+ raw = Vec::new();}if line.capacity() > 1024 * 1024 {line = String::new();@@ -961,7 +997,7 @@ pub fn read_transcript_window(let mut out = TranscriptRead::default();loop {line.clear();- if read_line_tolerant(&mut reader, &mut raw, &mut line)? == 0 {+ if read_line_tolerant(&mut reader, &mut raw, &mut line)?.0 == 0 {break;}// Classify by a bounded prefix scan: a full parse here walks every byte@@ -1388,7 +1424,7 @@ pub fn read_revision(line = String::new();}line.clear();- let read = read_line_tolerant(&mut reader, &mut raw, &mut line)?;+ let (read, _) = read_line_tolerant(&mut reader, &mut raw, &mut line)?;if read == 0 {break;}@@ -1412,7 +1448,7 @@ pub fn read_revision(}line.clear();reader.seek(SeekFrom::Start(*offset))?;- if read_line_tolerant(&mut reader, &mut raw, &mut line)? == 0 {+ if read_line_tolerant(&mut reader, &mut raw, &mut line)?.0 == 0 {continue;}let body = line.trim();diff --git a/crates/host-core/src/transcripts/layout.rs b/crates/host-core/src/transcripts/layout.rsindex 2f05a4e5d..acc415090 100644--- a/crates/host-core/src/transcripts/layout.rs+++ b/crates/host-core/src/transcripts/layout.rs@@ -303,12 +303,9 @@ fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLaif !raw.ends_with(b"\n") {break;}- let line = std::str::from_utf8(&raw).map_err(|_| {- std::io::Error::new(- std::io::ErrorKind::InvalidData,- "stream did not contain valid UTF-8",- )- })?;+ // Preserve the readable prefix and suffix when a completed append+ // contains bytes from a character that was torn during a crash.+ let line = String::from_utf8_lossy(&raw);match sniff_line_kind(line.trim_end()) {Some("message") => layout.message_offsets.push(offset),Some("compaction") => layout.compaction_offsets.push(offset),diff --git a/crates/host-core/src/transcripts_layout_tests.rs b/crates/host-core/src/transcripts_layout_tests.rsindex 2007841b8..82fa875b7 100644--- a/crates/host-core/src/transcripts_layout_tests.rs+++ b/crates/host-core/src/transcripts_layout_tests.rs@@ -293,7 +293,7 @@ fn layout_recovery_rebuilds_once_and_recomputes_the_window() {}#[test]-fn real_invalid_utf8_is_reported_without_changing_transcript_bytes() {+fn invalid_utf8_message_lines_are_skipped_without_changing_transcript_bytes() {let dir = tempdir().unwrap();let path = transcript_path(dir.path(), "layout-regression").unwrap();fs::create_dir_all(path.parent().unwrap()).unwrap();@@ -301,12 +301,54 @@ fn real_invalid_utf8_is_reported_without_changing_transcript_bytes() {b"{\"type\":\"session\"}\n{\"type\":\"message\",\"id\":\"broken\",\"content\":\"\xff\"}\n";fs::write(&path, bytes).unwrap();- let error =- refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap_err();- assert!(format!("{error:#}").contains("valid UTF-8"));+ let layout =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap();+ assert_eq!(layout.message_count(), 1);+ let read =+ read_transcript_window_with_layout(dir.path(), "layout-regression", &layout, 0, None)+ .unwrap();+ assert!(read.messages.is_empty());assert_eq!(fs::read(path).unwrap(), bytes);}+#[test]+fn bounded_layout_read_tolerates_invalid_utf8_in_a_complete_message_line() {+ let dir = tempdir().unwrap();+ let path = transcript_path(dir.path(), "layout-regression").unwrap();+ let messages = [+ message("m1", "before"),+ message("m2", "hello world"),+ message("m3", "after"),+ ];+ write_transcript(dir.path(), "layout-regression", CREATED_AT, &messages).unwrap();++ let mut original = fs::read(&path).unwrap();+ let text = b"hello world";+ let text_start = original+ .windows(text.len())+ .position(|window| window == text)+ .unwrap();+ original.splice(text_start + 5..text_start + 5, [0xE6, 0x92]);+ fs::write(&path, &original).unwrap();++ let layout =+ refresh_layout(dir.path(), "layout-regression", TranscriptLayout::default()).unwrap();+ assert_eq!(layout.message_count(), 3);+ let read =+ read_transcript_window_with_layout(dir.path(), "layout-regression", &layout, 0, None)+ .unwrap();++ assert_eq!(+ read.messages+ .iter()+ .map(|row| row.id.as_str())+ .collect::<Vec<_>>(),+ ["m1", "m2", "m3"]+ );+ assert_eq!(read.messages[1].blocks[0]["text"], "hello\u{FFFD} world");+ assert_eq!(fs::read(path).unwrap(), original);+}+#[test]fn torn_invalid_utf8_tail_is_excluded_from_layout_without_error() {let dir = tempdir().unwrap();diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 410912593..e3ce8fb17 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1439,9 +1439,11 @@ cached read is proportional to the requested page. Consequences:- A point read that finds an invalid indexed line boundary drops both cachelayers, scans the complete transcript without consulting the disk cache, andretries once with message counts, page ranges, and message location recomputed- from the rebuilt layout. A real JSON, UTF-8, or I/O error from that complete- scan remains an error; the transcript is never rewritten or repaired by- replacing bytes or skipping messages.+ from the rebuilt layout. Reads tolerate invalid UTF-8 within a complete line:+ parseable records use U+FFFD for the damaged bytes, while records that remain+ invalid JSON or do not match the record schema are skipped with a diagnostic.+ Physical message-line positions stay consistent across bounded reads. The+ transcript bytes are never rewritten; actual file I/O errors remain errors.- New cache files use a nonnumeric version header that older parsers safelyreject and rebuild. Downgrading to an older app preserves the transcript anddatabase, though that app's own cache defect may recur. No database ordiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 7459ee380..774bebc71 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1974,6 +1974,27 @@ identify the platform validation still needed.- **Status**: Source-level and isolated Host RPC cache regressions covered;full large-fixture Electron journey Draft+#### E2E-TRANSCRIPT-invalid-utf8-window-remains-readable++- **Preconditions**: An isolated Host profile contains a session transcript+ with valid messages before and after a complete line containing invalid+ UTF-8 bytes. The damaged bytes are inside message text in one fixture and+ make a separate message line unparseable in another. No real user data.+- **Steps**: Open the session through the renderer's bounded `session.get`+ path with `messageLimit`, page across the damaged line, then read the full+ history through the Host API. Compare the transcript file before and after.+- **Expected**: The session stays readable. Valid surrounding messages appear+ in order; parseable damaged text contains U+FFFD, while an unparseable row is+ skipped. The source transcript remains byte-identical and paging positions+ stay consistent.+- **Specs**: `03-runtime/04-data-storage.md` and ADR 0127.+- **Acceptance**: C (conversation and stream), F (persistence), Quality.+- **Milestone**: Maintenance.+- **Automation**: `pnpm test:e2e:transcript-cache` exercises bounded `session.get`+ against an isolated Host and verifies replacement text plus unchanged source+ bytes. `crates/host-core/src/transcripts_layout_tests.rs` covers the invalid+ row and layout reader directly. Full renderer journey remains Draft.+#### E2E-011a: New session while another session is still streaming- **Preconditions**: Provider configured; session A is streaming a long@@ -10039,6 +10060,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.| Quality (stored model binding array) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry || Quality (unique tool-call ids) | E2E-RUNTIME-unique-tool-call-ids-per-request || C — Conversation & stream (loop context ownership) | E2E-RUNTIME-loop-context-ownership |+| C / F / Quality — Transcript invalid UTF-8 recovery | E2E-TRANSCRIPT-invalid-utf8-window-remains-readable || Quality (loop context ownership) | E2E-RUNTIME-loop-context-ownership || G — Plugin host lifecycle (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code || Quality (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex dd22fcd22..e0d641bdb 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -1120,6 +1120,9 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录条目,因为一次重写可能落在完全相同的长度上。- 撕裂的尾行(追加过程中崩溃)会同时被排除在偏移量和 `file_len` 之外,因此在写入方补全它之后,后续刷新会重新收录它。+- 完整行中包含非法 UTF-8 时,有界与完整读取仍会尽力恢复:可解析记录中的坏字节会以+ U+FFFD 替代;仍不符合 JSON 或记录结构的行会记录诊断并跳过。分页仍使用一致的物理+ 消息行位置。读取不会改写转录文件字节;实际文件 I/O 错误仍会返回错误。- 行分类通过一次感知深度的扫描读取 `type` 判别字段,绝不把整行解析成值。只有**顶层**的 `type` 键决定行的种类:工具结果与检查点详情是开放式 JSON,可能嵌套一个自身带 `type` 的对象,而该 `type` 恰好是某个行种类的名字。每条新行都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 44a7404d2..120c40abd 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@@ -1346,6 +1346,21 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **状态**:草案。2026-09-20 的嵌套披露变更仅把本场景作为静态源码/设计审查的预期行为;该范围不新增或运行单元、组件、集成、浏览器、Electron 或 E2E 测试。+#### E2E-TRANSCRIPT-invalid-utf8-window-remains-readable++- **先决条件**:隔离的 Host 配置中有一个会话转录,损坏行前后都有有效消息。完整行内含非法+ UTF-8 字节:一份夹具把字节放在消息文本中,另一份使消息行无法解析。不使用真实用户数据。+- **步骤**:通过渲染器的有界 `session.get` 路径以 `messageLimit` 打开会话,分页经过损坏行,+ 再通过 Host API 读取完整历史。比较读取前后的转录文件。+- **预期**:会话仍可读取。前后有效消息按顺序出现;可解析的损坏文本以 U+FFFD 替代非法字节,+ 无法解析的行会跳过。源转录逐字节不变,分页位置保持一致。+- **链接规格**:`03-runtime/04-data-storage.md`、ADR 0127。+- **验收**:C(对话和流)、F(持久性)、质量。+- **里程碑**:维护。+- **自动化**:`pnpm test:e2e:transcript-cache` 通过隔离 Host 的有界 `session.get` 验证替代文本+ 和源文件不变;`crates/host-core/src/transcripts_layout_tests.rs` 直接覆盖坏行与布局读取。完整+ Renderer 用户旅程仍为草案。+#### E2E-041:对话小地图导航长记录- **先决条件**:会话包含足够的用户和助理轮流@@ -5809,6 +5824,7 @@ eleven-tool-round desktop paths are verified by| 品质(工具调用 id 唯一) | E2E-RUNTIME-unique-tool-call-ids-per-request || C — 对话与流式(循环上下文归属) | E2E-RUNTIME-loop-context-ownership || 品质(循环上下文归属) | E2E-RUNTIME-loop-context-ownership |+| C / F / 质量 — 转录非法 UTF-8 恢复 | E2E-TRANSCRIPT-invalid-utf8-window-remains-readable || G — 插件宿主生命周期(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code || 品质(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code || F — 持久化(存储的模型绑定数组) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry |diff --git a/scripts/README.md b/scripts/README.mdindex 098f2f283..1bcdb7159 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -55,7 +55,7 @@ The scenarios are specified in| `e2e-tool-admission.mjs` | `node scripts/e2e-tool-admission.mjs` | Isolated real-host tool admission: queued Bash burst leaves capacity for another session's Read/Write and recovers all counters || `e2e-smoke.mjs` | `pnpm test:e2e` | Protocol-level E2E against host-core, plus an optional live model || `e2e-plan.mjs` | `pnpm test:e2e:plan` | Plan state, checkpoint artifact, and approval transitions |-| `e2e-transcript-cache.mjs` | `pnpm test:e2e:transcript-cache` | Isolated Host RPC regression for large transcript cache creation, append plus middle Task rewrite, legacy cache recovery, paging, message navigation, tool results, and process restart |+| `e2e-transcript-cache.mjs` | `pnpm test:e2e:transcript-cache` | Isolated Host RPC regression for large transcript cache creation, append plus middle Task rewrite, legacy cache recovery, paging, message navigation, invalid UTF-8 recovery, and process restart || `e2e-plan-ui.mjs` | `pnpm test:e2e:plan-ui` | Plan approval through the rendered UI || `e2e-electron-boot.mjs` | `pnpm test:e2e:boot` | Electron boot probe || `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` |diff --git a/scripts/e2e-transcript-cache.mjs b/scripts/e2e-transcript-cache.mjsindex 2c039b7f7..95d2e445c 100644--- a/scripts/e2e-transcript-cache.mjs+++ b/scripts/e2e-transcript-cache.mjs@@ -242,7 +242,45 @@ try {assert.ok(rebuiltCache?.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 2\n"));}- console.log("PASS transcript cache: append, middle Task rewrite, legacy cache recovery, paging, message navigation, tool result and Host restart");+ const damagedSession = await host.call("session.create", {+ title: "Invalid UTF-8 bounded transcript recovery",+ mode: "agent",+ projectPath: workspace,+ });+ const damagedRows = [+ { id: "utf8-before", role: "user", content: "before", createdAt, status: "complete" },+ { id: "utf8-middle", role: "user", content: "hello world", createdAt, status: "complete" },+ { id: "utf8-after", role: "user", content: "after", createdAt, status: "complete" },+ ];+ for (const message of damagedRows) {+ await host.call("session.appendMessage", { sessionId: damagedSession.session.id, message });+ }+ const damagedPath = join(dataDir, "sessions", `${damagedSession.session.id}.jsonl`);+ const intactWindow = await host.call("session.get", {+ id: damagedSession.session.id,+ messageLimit: 10,+ });+ assert.equal(intactWindow.session.messages.length, 3);+ const damagedBytes = await readFile(damagedPath);+ const textOffset = damagedBytes.indexOf(Buffer.from("hello world"));+ assert.notEqual(textOffset, -1);+ damagedBytes[textOffset + 6] = 0xE6;+ damagedBytes[textOffset + 7] = 0x92;+ await writeFile(damagedPath, damagedBytes);++ await host.restart();+ const recoveredWindow = await host.call("session.get", {+ id: damagedSession.session.id,+ messageLimit: 10,+ });+ assert.deepEqual(+ recoveredWindow.session.messages.map((message) => message.id),+ damagedRows.map((message) => message.id),+ );+ assert.equal(recoveredWindow.session.messages[1].content, "hello \uFFFDrld");+ assert.deepEqual(await readFile(damagedPath), damagedBytes);++ console.log("PASS transcript cache: paging, legacy cache recovery, navigation, Task rewrite, restart, and invalid UTF-8 bounded reads");} finally {await host.stop();await rm(temp, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });