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(persistence): recover stale transcript turn references
vastsac201518e69f9
diff --git a/apps/desktop/electron/main/persistence-outbox.ts b/apps/desktop/electron/main/persistence-outbox.tsindex 1c0ab34a4..b5358723d 100644--- a/apps/desktop/electron/main/persistence-outbox.ts+++ b/apps/desktop/electron/main/persistence-outbox.ts@@ -45,10 +45,12 @@ export class PersistenceOutbox {if (this.entries.length >= MAX_ENTRIES) await this.flush(getHost);if (this.entries.length >= MAX_ENTRIES) {this.logger("error", "session persistence outbox is full", {+ key: entry.key,+ sessionId: entry.sessionId,size: this.entries.length,max: MAX_ENTRIES,});- return;+ throw new Error("session persistence outbox is full");}this.entries.push(entry);}diff --git a/apps/desktop/test/persistence-outbox.test.mjs b/apps/desktop/test/persistence-outbox.test.mjsindex 247f45520..cbe738fb2 100644--- a/apps/desktop/test/persistence-outbox.test.mjs+++ b/apps/desktop/test/persistence-outbox.test.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdtemp, readFile } from "node:fs/promises";+import { mkdtemp, readFile, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";@@ -103,6 +103,38 @@ test("duplicate message id does not stall later outbox entries (D444)", async ());});+test("a full outbox rejects an entry instead of reporting it enqueued", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-outbox-full-"));+ const path = join(dir, "session-message-outbox.json");+ const entries = Array.from({ length: 1024 }, (_, index) => ({+ key: `message:s${index}:m${index}`,+ sessionId: `s${index}`,+ message: { id: `m${index}` },+ }));+ await writeFile(path, JSON.stringify(entries), "utf8");+ const logs = [];+ const outbox = new PersistenceOutbox(dir, (level, message, data) => {+ logs.push({ level, message, data });+ });++ await assert.rejects(+ outbox.enqueue(+ { key: "message:last:missing", sessionId: "last", message: { id: "missing" } },+ () => null,+ ),+ /outbox is full/i,+ );+ assert.equal(outbox.size(), 1024);+ assert.equal(JSON.parse(await readFile(path, "utf8")).length, 1024);+ assert.ok(+ logs.some(+ (entry) =>+ entry.message === "session persistence outbox is full" &&+ entry.data?.key === "message:last:missing",+ ),+ );+});+test("non-unique flush errors still pause the outbox", async () => {const dir = await mkdtemp(join(tmpdir(), "pi-outbox-"));const outbox = new PersistenceOutbox(dir, silent);diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex f8e794fb4..d0b9c5d1e 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -1788,6 +1788,9 @@ pub fn append_message(let message = crate::session_collaboration::prepare_append(db, session_id, message, turn_id)?;let session_created = ensure_session_for_append(db, session_id)?;let (mut record, text) = ui_to_record(&message);+ let had_turn_reference = turn_id.is_some();+ let turn_id = valid_turn_reference(db, session_id, turn_id)?;+ let stale_turn_reference = had_turn_reference && turn_id.is_none();// Electron may replay an outbox entry after a host restart. Message ids// are globally unique, so an existing row in this session is already the// durable result. Provider toolCallIds are not globally unique: a collision@@ -1829,14 +1832,18 @@ pub fn append_message(return Ok(());}}- append_record(- db,- session_id,- &session_created,- &record,- text.as_deref(),- turn_id,- )?;+ let transcript_repaired =+ stale_turn_reference && repair_unindexed_transcript_message(db, session_id, &record)?;+ if !transcript_repaired {+ append_record(+ db,+ session_id,+ &session_created,+ &record,+ text.as_deref(),+ turn_id.as_deref(),+ )?;+ }}if message.role == "assistant" && message.status.as_deref() == Some("streaming") {// Even an empty reservation needs a checkpoint so a crash can settle@@ -1851,8 +1858,8 @@ pub fn append_message(&transcripts::InflightRecord {schema: transcripts::INFLIGHT_SCHEMA,session_id: session_id.to_string(),- turn_id: turn_id.map(str::to_string),saved_at: ms_to_ts(now_ms()),+ turn_id: turn_id.clone(),message: record,},)?;@@ -1908,6 +1915,116 @@ fn transcript_contains_id(db: &Database, session_id: &str, message_id: &str) ->.any(|record| record.id == message_id))}+fn valid_turn_reference(+ db: &Database,+ session_id: &str,+ turn_id: Option<&str>,+) -> Result<Option<String>> {+ let Some(turn_id) = turn_id else {+ return Ok(None);+ };+ let owner: Option<String> = db+ .conn()+ .query_row(+ "SELECT session_id FROM turns WHERE id = ?1",+ params![turn_id],+ |row| row.get(0),+ )+ .optional()?;+ if owner.as_deref() == Some(session_id) {+ return Ok(Some(turn_id.to_string()));+ }+ tracing::warn!(+ %session_id,+ %turn_id,+ turn_session_id = owner.as_deref().unwrap_or("(missing)"),+ "omitting invalid turn reference from transcript message"+ );+ Ok(None)+}++/// Reconcile an old outbox replay whose transcript line landed before its+/// SQLite index insert failed. Keep the file as source of truth and restore+/// index sequence from its keep-last, unique-message projection.+fn repair_unindexed_transcript_message(+ db: &Database,+ session_id: &str,+ record: &MessageRecord,+) -> Result<bool> {+ let mut records = dedupe_records(transcripts::read_transcript(db.data_dir(), session_id)?);+ let Some(position) = records.iter().position(|existing| existing.id == record.id) else {+ return Ok(false);+ };+ if !transcripts::update_message(db.data_dir(), session_id, record)? {+ return Ok(false);+ }+ records[position] = record.clone();+ invalidate_transcript_layout(session_id);+ rebuild_session_message_index(db, session_id, &records)?;+ tracing::warn!(+ %session_id,+ message_id = %record.id,+ "reconciled transcript message after an unindexed outbox replay"+ );+ Ok(true)+}++fn rebuild_session_message_index(+ db: &Database,+ session_id: &str,+ records: &[MessageRecord],+) -> Result<()> {+ let existing_turns: std::collections::HashMap<String, String> = {+ let mut stmt = db.conn().prepare_cached(+ "SELECT m.id, m.turn_id, t.session_id+ FROM messages m JOIN turns t ON t.id = m.turn_id+ WHERE m.session_id = ?1 AND m.turn_id IS NOT NULL",+ )?;+ let rows = stmt.query_map(params![session_id], |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ ))+ })?;+ let mut turns = std::collections::HashMap::new();+ for row in rows {+ let (message_id, turn_id, turn_session_id) = row?;+ if turn_session_id == session_id {+ turns.insert(message_id, turn_id);+ }+ }+ turns+ };+ let last_seq = i64::try_from(records.len())+ .map_err(|_| anyhow!("transcript has too many messages to index"))?;+ let conn = db.conn();+ let tx = conn.unchecked_transaction()?;+ tx.prepare_cached("DELETE FROM messages WHERE session_id = ?1")?+ .execute(params![session_id])?;+ for (seq, record) in records.iter().enumerate() {+ let seq =+ i64::try_from(seq).map_err(|_| anyhow!("transcript has too many messages to index"))?;+ let text = record_index_text(record);+ insert_index_row(+ &tx,+ session_id,+ seq,+ existing_turns.get(&record.id).map(String::as_str),+ record,+ text.as_deref(),+ )?;+ }+ let changed = tx+ .prepare_cached("UPDATE sessions SET last_seq = ?1, updated_at = ?2 WHERE id = ?3")?+ .execute(params![last_seq, now_ms(), session_id])?;+ if changed == 0 {+ return Err(anyhow!("session not found while rebuilding message index"));+ }+ tx.commit()?;+ Ok(())+}+fn streaming_assistant_indexed(db: &Database, session_id: &str, message_id: &str) -> Result<bool> {let layout = session_layout(db, session_id)?;let mut end = layout.message_count();@@ -3715,6 +3832,139 @@ mod tests {}}+ #[test]+ fn append_message_without_a_live_same_session_turn_keeps_the_message() {+ let db = test_db();+ let source = create_session(&db, None, None, None, None, None).unwrap();+ let target = create_session(&db, None, None, None, None, None).unwrap();+ let source_turn = begin_turn(&db, &source.id, None, None).unwrap();+ let missing = user_msg("missing-turn-message", "kept", "2026-07-28T00:00:00Z");+ let cross_session = user_msg(+ "cross-session-turn-message",+ "also kept",+ "2026-07-28T00:00:01Z",+ );++ append_message(&db, &target.id, &missing, Some("missing-turn"))+ .expect("a stale optional turn must not block transcript persistence");+ append_message(&db, &target.id, &cross_session, Some(&source_turn))+ .expect("a turn owned by another session must not block transcript persistence");++ let links: Vec<(String, Option<String>)> = db+ .conn()+ .prepare("SELECT id, turn_id FROM messages WHERE session_id = ?1 ORDER BY seq")+ .unwrap()+ .query_map(params![target.id], |row| Ok((row.get(0)?, row.get(1)?)))+ .unwrap()+ .collect::<rusqlite::Result<_>>()+ .unwrap();+ assert_eq!(+ links,+ vec![(missing.id.clone(), None), (cross_session.id.clone(), None),]+ );+ assert_eq!(+ get_session(&db, &target.id)+ .unwrap()+ .unwrap()+ .messages+ .iter()+ .map(|message| message.id.as_str())+ .collect::<Vec<_>>(),+ vec![missing.id.as_str(), cross_session.id.as_str()]+ );+ }++ #[test]+ fn replay_after_a_failed_index_insert_updates_transcript_without_duplicate_or_reordering() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let turn_id = begin_turn(&db, &session.id, None, None).unwrap();+ let before = user_msg("before", "before", "2026-07-28T00:00:00Z");+ let replay = user_msg("replay", "latest replay snapshot", "2026-07-28T00:00:01Z");+ let old_replay = user_msg("replay", "old failed snapshot", "2026-07-28T00:00:01Z");+ let after = user_msg("after", "after", "2026-07-28T00:00:02Z");+ append_message(&db, &session.id, &before, Some(&turn_id)).unwrap();++ // Older hosts wrote the transcript line before the index transaction;+ // repeated retries could leave multiple stale copies while the index stayed absent.+ let (record, _) = ui_to_record(&old_replay);+ let created_at = session_created_at(&db, &session.id).unwrap();+ transcripts::append_message(db.data_dir(), &session.id, &created_at, &record).unwrap();+ transcripts::append_message(db.data_dir(), &session.id, &created_at, &record).unwrap();+ append_message(&db, &session.id, &after, Some(&turn_id)).unwrap();++ append_message(&db, &session.id, &replay, Some("missing-turn"))+ .expect("replaying an old outbox entry must reconcile the existing transcript line");++ let indexed: Vec<(String, i64, Option<String>)> = db+ .conn()+ .prepare("SELECT id, seq, turn_id FROM messages WHERE session_id = ?1 ORDER BY seq")+ .unwrap()+ .query_map(params![session.id], |row| {+ Ok((row.get(0)?, row.get(1)?, row.get(2)?))+ })+ .unwrap()+ .collect::<rusqlite::Result<_>>()+ .unwrap();+ assert_eq!(+ indexed,+ vec![+ (before.id.clone(), 0, Some(turn_id.clone())),+ (replay.id.clone(), 1, None),+ (after.id.clone(), 2, Some(turn_id.clone())),+ ]+ );+ let last_seq: i64 = db+ .conn()+ .query_row(+ "SELECT last_seq FROM sessions WHERE id = ?1",+ params![session.id],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(last_seq, 3);++ let transcript = transcripts::read_transcript(db.data_dir(), &session.id).unwrap();+ assert_eq!(+ transcript+ .iter()+ .filter(|record| record.id == replay.id)+ .count(),+ 2,+ "replay updates existing lines but does not append another copy"+ );+ let restored = get_session(&db, &session.id).unwrap().unwrap();+ assert_eq!(+ restored+ .messages+ .iter()+ .map(|message| message.id.as_str())+ .collect::<Vec<_>>(),+ vec![before.id.as_str(), replay.id.as_str(), after.id.as_str()]+ );+ assert_eq!(restored.messages[1].content, replay.content);+ assert_eq!(+ search_messages(&db, &replay.content, 10)+ .unwrap()+ .iter()+ .map(|hit| hit.message_id.as_str())+ .collect::<Vec<_>>(),+ vec![replay.id.as_str()]+ );++ let next = user_msg("next", "after repair", "2026-07-28T00:00:03Z");+ append_message(&db, &session.id, &next, Some(&turn_id)).unwrap();+ let next_seq: i64 = db+ .conn()+ .query_row(+ "SELECT seq FROM messages WHERE session_id = ?1 AND id = ?2",+ params![session.id, next.id],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(next_seq, 3);+ }+#[test]fn compaction_survives_restart_and_late_truncation_but_not_early_truncation() {let db = test_db();diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex da0e7ef4b..85caae73f 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1182,7 +1182,8 @@ is the source of truth, the index is derived and self-healing.| event | file step | index/DB transaction ||---|---|---|| prompt accepted | append user message line | `last_seq` alloc (RETURNING) + index row + touch `sessions.updated_at`; then insert `turns(running)` |-| assistant/tool message end | append message line; remove the in-flight checkpoint when its id matches | index row + touch session |+| assistant/tool message end | append message line; remove the in-flight checkpoint when its id matches | validate optional `turnId` belongs to this session; if stale/missing, keep the message with a null turn link and emit a warning; otherwise insert the index row and touch session |+| stale-turn outbox replay after an index failure | update all existing transcript lines for the message id to the latest snapshot; do not append another line | rebuild deduplicated message rows and `last_seq` from transcript order in one transaction, preserving only valid same-session turn links; FTS triggers stay synchronized || streaming reply checkpoint (`session.saveInflightMessage`, D299) | atomically replace `<id>.inflight.json`; no-op for an empty message or an id already indexed | — || context checkpoint (`session.appendCompaction`) | append typed checkpoint line after its referenced message boundary | — (checkpoint is not searchable transcript content) || tool succeeded (Write/Edit) | — | upsert `artifacts` + `audit_log` row, same tx as result persistence |@@ -1219,9 +1220,9 @@ prompt, computed from the full durable transcript merged with the live rows.A checkpoint is installed into the live runtime only after its append succeeds;therefore a failed/crashed checkpoint write leaves the previous full context orprevious checkpoint authoritative rather than creating a memory-only state.-A crash between file append and index commit leaves the message readable-(transcript loads from the file) with only its search row missing until the-next rewrite; transcript reads dedupe repeated ids keep-last.+An append failure after the file write leaves the transcript authoritative while+its derived index is repaired by the next rewrite or by replaying an unindexed+outbox message with a stale turn reference; repeated ids are deduped keep-last.The renderer never needs the whole JSONL file to open a session. Its`session.get` request may specify a zero-based exclusive `messageBefore`, a@@ -1523,18 +1524,25 @@ line and search text, retaining sequence, owning turn and every other row.Late partial snapshots and duplicate terminal snapshots cannot overwrite thesettled result. Recovery promotes the latest checkpoint in that same position.The outbox likewise keeps a newer snapshot that replaces an append while its-host call is still pending. If `messages.id` already belongs to another-session, the host remaps to `{sessionId}:{id}` before any JSONL write; a-replay of the original id is a no-op against that remapped row. The outbox-treats `UNIQUE constraint failed: messages.id` as an ack and keeps draining-(D444). A permanently rejected append whose host error carries a-`PERMISSION_DENIED:` prefix is likewise dropped so the FIFO can continue;-`PLUGIN_PERMISSION_DENIED` and other host failures still pause (D597).-Steering into a claimed collaboration delivery turn is extra human input: it-must target that delivery's session, is exempt from the delivery-content/attachment contract, does not inherit the delivery origin, and has-any client-supplied `session_message` stripped. No schema migration is-required.+host call is still pending. An optional `turnId` is retained only when the turn+exists and belongs to the target session; a missing or cross-session turn is+logged and omitted without rejecting or losing the message. If an older failed+append already wrote that message to JSONL, replay updates those lines and+rebuilds the deduplicated index in transcript order rather than appending again.+If `messages.id` already belongs to another session, the host remaps to+`{sessionId}:{id}` before any JSONL write; a replay of the original id is a+no-op against that remapped row. The outbox treats+`UNIQUE constraint failed: messages.id` as an ack and keeps draining (D444).+A permanently rejected append whose host error carries a `PERMISSION_DENIED:`+prefix is likewise dropped so the FIFO can continue; `PLUGIN_PERMISSION_DENIED`+and other host failures still pause (D597). When the 1024-entry cap remains+full after a flush attempt, enqueue logs the rejected key/session and rejects;+it does not report that entry as queued. Generic foreign-key errors are not+treated as acknowledgements. Steering into a claimed collaboration delivery+turn is extra human input: it must target that delivery's session, is exempt+from the delivery content/attachment contract, does not inherit the delivery+origin, and has any client-supplied `session_message` stripped. No schema+migration is required.## 12. Native Pi session authority (ADR 0254)diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c11032959..a27a48e29 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -11154,24 +11154,30 @@ are withdrawn with ADR 0165.#### E2E-178: A missing sessions row is restored so the outbox can drain- **Preconditions**: A session has a live `sessions/<id>.jsonl` and queued- turns in `session-message-outbox.json`, but its row is gone from- `pi.sqlite` `sessions` (WAL/index loss).+ appends in `session-message-outbox.json`, but its row is gone from+ `pi.sqlite` `sessions` (WAL/index loss). The queued head may carry a turn+ id whose row is missing or belongs to another session. For legacy replay,+ the JSONL may already contain repeated copies of that message id.- **Steps**: 1) Confirm the sidebar no longer lists the session and`session.appendMessage` would fail `session not found`. 2) Restart theapp (or otherwise complete a host handshake that flushes the outbox).- 3) Optional: delete the session and confirm its outbox entries are+ 3) Replay an unindexed message with a stale turn id after writing its+ transcript line more than once, with a later indexed message behind it.+ 4) Optional: delete the session and confirm its outbox entries aredropped rather than resurrected.-- **Expected**: Host boot reinserts the sessions row from the JSONL and- rebuilds the search index. The outbox drains without pausing at the- head. The conversation returns to the sidebar with its messages. A- user-deleted session is not recreated from leftover outbox entries.+- **Expected**: Host boot reinserts the sessions row from JSONL and rebuilds+ its index. The stale turn link is omitted without losing the message; the+ outbox drains and later messages keep transcript order. Replayed copies are+ updated in place and do not add another line; `last_seq` and search index+ match the deduplicated transcript. A user-deleted session is not recreated.- **Specs linked**: `03-runtime/04-data-storage.md`,`03-runtime/06-host-rpc-protocol.md`, `03-runtime/07-process-model.md`,ADR 0041, `08-meta/decisions-log.md` (D318)- **Acceptance**: C (conversation & stream), F (persistence)- **Milestone**: M5-- **Status**: Unit-covered (host-core orphaned-session restore tests,- `persistence-outbox.test.mjs`); full desktop journey Draft (run only in a capable environment when this surface changes)+- **Status**: Unit-covered (`sessions.rs` stale-turn/replay tests,+ `persistence-outbox.test.mjs` full-cap rejection and drain tests); full+ desktop journey Draft (run only in a capable environment when this surface changes).#### E2E-179: Parent tools after a Task fan-out stay outside the delegation carddiff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 1afc09689..fd210ac79 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -1021,7 +1021,8 @@ CREATE INDEX idx_notifications_unread| 事件 | 文件步骤 | index/DB 交易 ||---|---|---|| 接受提示 | 附加用户消息行 | `last_seq` 分配(返回)+索引行+触摸 `sessions.updated_at`;然后插入 `turns(running)` |-| assistant/tool 消息结束 | 附加消息行;id 匹配时移除进行中检查点 | 索引行+触摸会话 |+| assistant/tool 消息结束 | 附加消息行;id 匹配时移除进行中检查点 | 校验可选 `turnId` 属于本会话;过期/缺失时记录警告并置空关联,仍写入索引并更新时间 |+| 过期 turn 下的 outbox 重放 | 将同一消息 id 的现有转录行更新为最新快照,不再追加新行 | 在单个事务中按转录顺序重建去重后的消息索引和 `last_seq`,仅保留有效的本会话 turn 关联;FTS 触发器保持同步 || 流式回复检查点(`session.saveInflightMessage`,D299) | 原子替换 `<id>.inflight.json`;空消息或已索引的 id 为空操作 | — || 上下文检查点(`session.appendCompaction`) | 在其引用的消息边界之后附加类型化检查点行 | —(检查点是不可搜索的转录本内容) || 工具成功(Write/Edit) | — | upsert `artifacts` + `audit_log` 行,与结果持久化相同的 tx |@@ -1054,9 +1055,8 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录只有在追加成功后,检查点才会安装到实时运行时中;因此 failed/crashed 检查点写入会留下先前的完整上下文或先前的检查点具有权威性,而不是创建仅内存状态。-文件追加和索引提交之间的崩溃使消息可读-(从文件加载脚本)只有其搜索行丢失,直到-下一步重写;转录读取重复数据删除重复的 id keep-last。+文件追加后索引提交失败时,转录文件仍是权威来源;后续重写,或携带过期 turn 引用的+未索引 outbox 消息重放,会修复其派生索引。重复 id 按 keep-last 规则去重。渲染器打开一个会话时并不需要整个 JSONL 文件。它的 `session.get` 请求可以指定一个从零开始、不含上界的 `messageBefore`,一个正数 `messageLimit`,以及@@ -1315,10 +1315,14 @@ UI投影损失终态助手替换索引中的流式助手。更新仅涉及该转录行和搜索文本,保留顺序、所属回合及其他所有行。迟到的部分快照和重复终态快照不能覆盖已落定结果。恢复时在原位置应用最新检查点。如果主机调用尚未完成时出现更新的追加快照,outbox 同样保留该快照。-若 `messages.id` 已属于另一会话,主机在写 JSONL 之前改写为 `{sessionId}:{id}`;-重放原始 id 对该改写行无操作。outbox 把 `UNIQUE constraint failed: messages.id`-当作确认并继续排空(D444)。带 `PERMISSION_DENIED:` 前缀的永久拒绝同样丢弃该行-以便 FIFO 继续;`PLUGIN_PERMISSION_DENIED` 和其他宿主失败仍暂停(D597)。+可选 `turnId` 仅在对应 turn 存在且属于目标会话时保留;缺失或跨会话时记录警告并省略,+不因此拒绝消息。旧版失败追加若已写入 JSONL,重放会更新同 id 行,并按去重后的转录顺序+重建索引,不再追加副本。若 `messages.id` 已属于另一会话,主机在写 JSONL 前改写为+`{sessionId}:{id}`;重放原始 id 对该改写行无操作。outbox 将+`UNIQUE constraint failed: messages.id` 当作确认并继续排空(D444)。带+`PERMISSION_DENIED:` 前缀的永久拒绝同样丢弃该行以便 FIFO 继续;+`PLUGIN_PERMISSION_DENIED` 和其他宿主失败仍暂停(D597)。1024 条上限在尝试 flush 后仍满时,+enqueue 会记录被拒 key/session 并 reject,不会谎报已入队;通用外键错误不会被当作确认。向已认领的协作投递回合做 steering 是额外的人类输入:必须指向该投递的会话,不受投递内容/附件契约约束,不继承投递来源,并清掉客户端带来的`session_message`。无需存储架构迁移。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 596ca1f21..bc2ccee26 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@@ -6888,15 +6888,15 @@ eleven-tool-round desktop paths are verified by#### E2E-178:缺失的 sessions 行被恢复,outbox 才能排空-- **前提条件**:会话仍有活的 `sessions/<id>.jsonl`,以及 `session-message-outbox.json` 里排队的回合,但 `pi.sqlite` 的 `sessions` 行已不在(WAL/索引丢失)。-- **步骤**:1)确认侧边栏不再列出该会话,且 `session.appendMessage` 会因 `session not found` 失败。2)重启应用(或完成一次会刷新 outbox 的主机握手)。3)可选:删除该会话,确认其 outbox 条目被丢掉而不是被救回。-- **预期**:主机启动从 JSONL 重新插入 sessions 行并重建搜索索引。outbox 不会卡在队头,能够排空。对话回到侧边栏且消息还在。用户删除的会话不会被残留 outbox 条目重建。+- **前提条件**:会话仍有 `sessions/<id>.jsonl` 和 `session-message-outbox.json` 中的待追加消息,但 `pi.sqlite` 中的 `sessions` 行已丢失(WAL/索引丢失)。队首可能带有缺失或属于另一会话的 turn id;旧版重放时 JSONL 也可能已有该消息 id 的重复行。+- **步骤**:1)确认侧边栏不再列出该会话,且 `session.appendMessage` 会因 `session not found` 失败。2)重启应用(或完成一次刷新 outbox 的主机握手)。3)在索引缺失、JSONL 已重复写入同一消息且后面还有已索引消息时,用过期 turn id 重放该条消息。4)可选:删除会话,并确认其 outbox 条目被丢弃而非复活。+- **预期**:主机从 JSONL 重新插入 sessions 行并重建索引。失效 turn 关联会被省略,但消息内容保留;outbox 不会卡在队首,后续消息顺序不变。重放会原位更新现有行,不再追加副本;`last_seq` 和搜索索引与去重后的转录顺序一致。用户删除的会话不会被残留 outbox 重建。- **链接规格**:`03-runtime/04-data-storage.md`、`03-runtime/06-host-rpc-protocol.md`、`03-runtime/07-process-model.md`、ADR 0041、`08-meta/decisions-log.md`(D318)- **验收**:C(对话和直播)、F(持久化)- **里程碑**:M5-- **状态**:单元已覆盖(host-core 孤儿会话恢复测试、`persistence-outbox.test.mjs`);完整桌面旅程仍为草稿(除非用户明确要求,否则不要在本地跑 E2E)+- **状态**:单元已覆盖(`sessions.rs` stale-turn/replay 测试、`persistence-outbox.test.mjs` 满载拒绝与排空测试);完整桌面旅程仍为草稿(除非用户明确要求,否则不要在本地跑 E2E)#### E2E-180:已发送的文件引用保持芯片并可点击打开