Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(sessions): fork completed replies while later turns run

yuxino609d7575ea3f
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index c63162b7c..b00420d88 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -210,7 +210,7 @@ export function registerSessionIpc({
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
- if (activeTurns.has(sessionId)) {
+ if (activeTurns.has(sessionId) && !String(input.throughMessageId ?? "").trim()) {
throw Object.assign(new Error("Cannot fork a running session"), {
errorCode: ErrorCodes.AGENT_BUSY,
});
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index bb7c986b0..24f4f1dd7 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -1,5 +1,4 @@
import i18n from "i18next";
-import { prepareTranscriptAction } from "../runtime/transcript-action";
import type {
Mode,
PlanProposal,
@@ -547,10 +546,11 @@ export function createSessionSlice({
forkAssistantMessage: async (messageId) => {
const intent = runtime.beginNavigationIntent();
- const state = await prepareTranscriptAction({ get, set }, runtime, messageId);
- if (!state || !runtime.navigationIntentIsCurrent(intent)) return;
+ // Fork needs only the anchor id: the host reads the canonical prefix.
+ // Hydrating the source here would overwrite its concurrently streaming tail.
+ const state = get();
const sessionId = state.activeSessionId;
- if (!sessionId || state.runningSessions[sessionId]) return;
+ if (!sessionId || state.selectingSessionId) return;
const message = state.messages.find((candidate) => candidate.id === messageId);
const source = state.sessions.find((session) => session.id === sessionId);
if (!message || message.role !== "assistant" || !source) return;
diff --git a/apps/desktop/test/native-pi-sessions.test.mjs b/apps/desktop/test/native-pi-sessions.test.mjs
index 25a92c0df..c7a185bf7 100644
--- a/apps/desktop/test/native-pi-sessions.test.mjs
+++ b/apps/desktop/test/native-pi-sessions.test.mjs
@@ -210,7 +210,7 @@ function loadSessionIpc(imports) {
return module.exports;
}
-function forkHarness({ host, sidecar }) {
+function forkHarness({ host, sidecar, activeTurns = new Map() }) {
const handlers = new Map();
const hostCalls = [];
const sidecarCalls = [];
@@ -228,7 +228,7 @@ function forkHarness({ host, sidecar }) {
getHost: () => host(hostCalls),
getSidecar: () => sidecar(sidecarCalls),
dataDir: "/tmp/pi-desktop-test",
- activeTurns: new Map(),
+ activeTurns,
sessionProjects: new Map(),
persistenceOutbox: {},
logger: { app() {} },
@@ -428,3 +428,25 @@ test("the native busy message is localized in every locale", async () => {
assert.match(source, /nativeSessionBusy:/, locale);
}
});
+
+
+test("busy Desktop fork delegates only anchored snapshots to the authoritative host", async () => {
+ const { handle, hostCalls } = forkHarness({
+ activeTurns: new Map([["parent", {}]]),
+ sidecar: () => null,
+ host: (calls) => ({ call: async (method, input) => {
+ calls.push({ method, input });
+ if (input.throughMessageId === "current") {
+ throw Object.assign(new Error("session is running"), { data: { errorCode: "CONFLICT" } });
+ }
+ return { session: { id: "child" } };
+ } }),
+ });
+ for (const throughMessageId of [undefined, "", " "]) {
+ await assert.rejects(handle({ sessionId: "parent", throughMessageId }), { errorCode: "AGENT_BUSY" });
+ }
+ assert.equal(hostCalls.length, 0);
+ assert.equal((await handle({ sessionId: "parent", throughMessageId: "old" })).session.id, "child");
+ assert.equal(hostCalls[0].input.throughMessageId, "old");
+ await assert.rejects(handle({ sessionId: "parent", throughMessageId: "current" }), { errorCode: "AGENT_BUSY" });
+});
diff --git a/apps/desktop/test/session-fork-running.test.mjs b/apps/desktop/test/session-fork-running.test.mjs
new file mode 100644
index 000000000..62b6c85f5
--- /dev/null
+++ b/apps/desktop/test/session-fork-running.test.mjs
@@ -0,0 +1,91 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createSessionSlice } = await import("../src/stores/slices/session-slice.ts");
+const { createSessionCoordination } = await import("../src/stores/runtime/session-coordination.ts");
+const { api } = await import("../src/lib/api.ts");
+
+function harness(t) {
+ const old = { id: "old", role: "assistant", content: "first reply", status: "complete" };
+ const live = { id: "live", role: "assistant", content: "second reply", status: "streaming" };
+ let state = {
+ activeSessionId: "parent", isRunning: true, runningSessions: { parent: true },
+ messages: [old, live], sessions: [{ id: "parent", title: "Source", mode: "agent" }],
+ sessionHistory: { parent: { hasMoreBefore: true, contentLimited: true } },
+ sessionMeta: {}, sessionCompactions: {}, planningStates: {},
+ retainedSessionIds: ["parent"], retainedTranscripts: { parent: [old, live] },
+ workPanelContexts: {}, workPanelTabs: [], workPanelOpen: false,
+ navStack: [{ page: "chat", sessionId: "parent" }], navIndex: 0,
+ restorePendingPlan: async () => {},
+ };
+ let intent = 0;
+ const cache = new Map([["parent", state.messages]]);
+ const runtime = {
+ beginNavigationIntent: () => ++intent,
+ navigationIntentIsCurrent: (value) => value === intent,
+ cacheSessionTranscript: (id, messages) => cache.set(id, messages),
+ loadFullSessionMessages: () => assert.fail("fork must not hydrate over a live transcript"),
+ };
+ const access = {
+ get: () => state,
+ set: (update) => { state = { ...state, ...(typeof update === "function" ? update(state) : update) }; },
+ runtime,
+ decorateSessions: (sessions) => sessions,
+ withoutRecordKey: (record, key) => Object.fromEntries(Object.entries(record).filter(([id]) => id !== key)),
+ };
+ const coordination = createSessionCoordination(access);
+ const slice = createSessionSlice({ ...access, ...coordination });
+ let resolve, reject;
+ const pending = new Promise((yes, no) => { resolve = yes; reject = no; });
+ t.mock.method(api, "forkSession", (id, _title, anchor) => {
+ assert.equal(id, "parent"); assert.equal(anchor, "old");
+ return pending;
+ });
+ return {
+ slice, runtime, cache, get: access.get, set: access.set,
+ complete: () => resolve({ session: { id: "child", title: "Branch", mode: "agent", messages: [{ ...old, id: "child-old" }] } }),
+ reject,
+ };
+}
+
+test("reply fork activates an independent child without hydrating or stopping its streaming parent", async (t) => {
+ const h = harness(t);
+ const parent = h.get().messages;
+ const action = h.slice.forkAssistantMessage("old");
+ h.complete();
+ await action;
+ assert.equal(h.get().activeSessionId, "child");
+ assert.equal(h.get().isRunning, false);
+ assert.equal(h.get().runningSessions.parent, true);
+ assert.equal(h.cache.get("parent"), parent);
+ assert.equal(h.get().retainedTranscripts.parent[1].status, "streaming");
+ assert.deepEqual(h.get().messages.map(m => m.id), ["child-old"]);
+ assert.deepEqual(h.get().sessions.map(s => s.id), ["child", "parent"]);
+});
+
+test("a fork that finishes after navigation lists the child without stealing the view", async (t) => {
+ const h = harness(t);
+ const action = h.slice.forkAssistantMessage("old");
+ h.runtime.beginNavigationIntent();
+ h.set({ activeSessionId: "other", messages: [], isRunning: false });
+ h.complete();
+ await action;
+ assert.equal(h.get().activeSessionId, "other");
+ assert.deepEqual(h.get().messages, []);
+ assert.equal(h.get().runningSessions.parent, true);
+ assert.deepEqual(h.get().sessions.map(s => s.id), ["child", "parent"]);
+});
+
+test("a rejected fork reports the error and keeps the original turn and transcript", async (t) => {
+ const h = harness(t);
+ const parent = h.get().messages;
+ const action = h.slice.forkAssistantMessage("old");
+ h.reject(Object.assign(new Error("Cannot fork this active turn"), { code: "AGENT_BUSY" }));
+ await action;
+ assert.equal(h.get().errorCode, "AGENT_BUSY");
+ assert.equal(h.get().activeSessionId, "parent");
+ assert.equal(h.get().messages, parent);
+ assert.equal(h.get().isRunning, true);
+});
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index f8e794fb4..faa5765bb 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -1495,8 +1495,8 @@ pub enum ForkSessionResult {
/// Whether the session currently owns a running turn.
///
/// A running turn owns its project's instructions, tools, and working
-/// directory, so an operation that crosses that boundary (fork, move, or the
-/// bulk delete of a project) is refused for as long as the turn lasts.
+/// directory, so moving or deleting that project is refused while it runs.
+/// A fork may copy a completed prefix without touching that live ownership.
pub fn session_has_running_turn(db: &Database, id: &str) -> Result<bool> {
let running: bool = db.conn().query_row(
"SELECT EXISTS(
@@ -1521,21 +1521,61 @@ pub fn fork_session_through(
let Some(source) = get_session(db, source_id)? else {
return Ok(ForkSessionResult::NotFound);
};
- if session_has_running_turn(db, source_id)? {
+ let running = session_has_running_turn(db, source_id)?;
+ let anchor = through_message_id
+ .map(str::trim)
+ .filter(|id| !id.is_empty());
+ if running && anchor.is_none() {
return Ok(ForkSessionResult::Busy);
}
let mut source_records =
dedupe_records(transcripts::read_transcript(db.data_dir(), source_id)?);
- if let Some(message_id) = through_message_id
- .map(str::trim)
- .filter(|value| !value.is_empty())
- {
+ if let Some(message_id) = anchor {
let Some(position) = source_records
.iter()
.position(|record| record.id == message_id)
else {
return Ok(ForkSessionResult::NotFound);
};
+ if running {
+ let record = &source_records[position];
+ // An assistant message can be complete while its tool loop is still
+ // running. Reject any prefix containing rows owned by a live turn,
+ // not merely a streaming anchor. The RPC holds the host state lock
+ // across this check and publication, including transcript appends.
+ let settled_prefix: bool = db.conn().query_row(
+ "SELECT EXISTS (
+ SELECT 1 FROM messages anchor
+ WHERE anchor.session_id = ?1 AND anchor.id = ?2
+ AND NOT EXISTS (
+ SELECT 1 FROM messages m JOIN turns t ON t.id = m.turn_id
+ WHERE m.session_id = ?1 AND t.status = 'running'
+ AND m.seq <= anchor.seq
+ )
+ )",
+ params![source_id, message_id],
+ |row| row.get(0),
+ )?;
+ if record.role != "assistant"
+ || record.is_error
+ || !matches!(
+ record
+ .meta
+ .as_ref()
+ .and_then(|meta| meta.get("status"))
+ .and_then(Value::as_str),
+ None | Some("complete")
+ )
+ || record
+ .meta
+ .as_ref()
+ .and_then(|meta| meta.get("error"))
+ .is_some_and(|error| !error.is_null())
+ || !settled_prefix
+ {
+ return Ok(ForkSessionResult::Busy);
+ }
+ }
source_records.truncate(position + 1);
}
let source_compactions = transcripts::read_compactions(db.data_dir(), source_id)?;
@@ -5316,6 +5356,107 @@ mod tests {
);
}
+ #[test]
+ fn completed_reply_fork_during_later_turn_preserves_the_running_source() {
+ let db = test_db();
+ let source = create_session(&db, Some("Source".into()), None, None, None, None).unwrap();
+ let first = begin_turn(&db, &source.id, None, None).unwrap();
+ let mut reply = user_msg("reply", "finished reply", "2025-05-01T00:00:01Z");
+ reply.role = "assistant".into();
+ append_message(
+ &db,
+ &source.id,
+ &user_msg("first", "first prompt", "2025-05-01T00:00:00Z"),
+ Some(&first),
+ )
+ .unwrap();
+ append_message(&db, &source.id, &reply, Some(&first)).unwrap();
+ end_turn(&db, &first, "completed", None, None, false).unwrap();
+ let running = begin_turn(&db, &source.id, None, None).unwrap();
+ // Admission can precede persistence of the next user row.
+ let ForkSessionResult::Created(early) =
+ fork_session_through(&db, &source.id, None, Some("reply")).unwrap()
+ else {
+ panic!("completed history should fork during a later turn");
+ };
+ assert_eq!(early.messages.len(), 2);
+ append_message(
+ &db,
+ &source.id,
+ &user_msg("second", "second prompt", "2025-05-01T00:00:02Z"),
+ Some(&running),
+ )
+ .unwrap();
+ let mut current = reply.clone();
+ current.id = "current".into();
+ current.content = "intermediate completed response in a running tool loop".into();
+ append_message(&db, &source.id, &current, Some(&running)).unwrap();
+ let before = get_session(&db, &source.id).unwrap().unwrap();
+ let ForkSessionResult::Created(child) =
+ fork_session_through(&db, &source.id, None, Some("reply")).unwrap()
+ else {
+ panic!("completed history should fork while the source streams");
+ };
+ assert_eq!(child.messages.len(), 2);
+ assert_eq!(child.messages[1].content, "finished reply");
+ assert_ne!(child.messages[1].id, "reply");
+ assert!(session_has_running_turn(&db, &source.id).unwrap());
+ assert!(!session_has_running_turn(&db, &child.summary.id).unwrap());
+ assert_eq!(
+ get_session(&db, &source.id)
+ .unwrap()
+ .unwrap()
+ .messages
+ .len(),
+ before.messages.len()
+ );
+ for anchor in [
+ None,
+ Some(""),
+ Some("first"),
+ Some("second"),
+ Some("current"),
+ ] {
+ assert!(matches!(
+ fork_session_through(&db, &source.id, None, anchor).unwrap(),
+ ForkSessionResult::Busy
+ ));
+ }
+ assert!(matches!(
+ fork_session_through(&db, &source.id, None, Some("missing")).unwrap(),
+ ForkSessionResult::NotFound
+ ));
+ // The original turn can still finish after the child was published.
+ current.id = "final".into();
+ current.content = "source finished independently".into();
+ append_message(&db, &source.id, &current, Some(&running)).unwrap();
+ end_turn(&db, &running, "completed", None, None, false).unwrap();
+ assert_eq!(
+ get_session(&db, &source.id)
+ .unwrap()
+ .unwrap()
+ .messages
+ .len(),
+ 5
+ );
+ assert_eq!(
+ get_session(&db, &child.summary.id)
+ .unwrap()
+ .unwrap()
+ .messages
+ .len(),
+ 2
+ );
+ // A child has no copied turn ids, but its completed history remains forkable.
+ let child_turn = begin_turn(&db, &child.summary.id, None, None).unwrap();
+ assert!(matches!(
+ fork_session_through(&db, &child.summary.id, None, Some(&child.messages[1].id))
+ .unwrap(),
+ ForkSessionResult::Created(_)
+ ));
+ end_turn(&db, &child_turn, "aborted", None, None, false).unwrap();
+ }
+
#[test]
fn message_scoped_fork_stops_at_selected_assistant_response() {
let db = test_db();
diff --git a/docs/adr/0023-independent-conversation-session-fork.md b/docs/adr/0023-independent-conversation-session-fork.md
index 37ccc942a..11a33774b 100644
--- a/docs/adr/0023-independent-conversation-session-fork.md
+++ b/docs/adr/0023-independent-conversation-session-fork.md
@@ -43,9 +43,16 @@ pass startup handshake and fail only when the new command is invoked.
child's existing linear revision store, and activates the edited tail. The
source transcript, revisions, runtime, and provider-cache state remain
untouched.
-- Fork is available only while the source is idle. Electron exposes
- `AGENT_BUSY`; the host retains a persisted running-turn `CONFLICT` guard that
- Electron normalizes at the IPC boundary.
+- Whole-session fork remains idle-only. A Desktop message-scoped fork may
+ copy a completed assistant prefix while a later turn runs (issue #837).
+ Under the same host RPC lock as append/publication, the host checks that no
+ indexed message at or before the anchor belongs to a running turn. It rejects
+ non-assistant, streaming/error, and live-turn anchors with `CONFLICT`, mapped
+ to `AGENT_BUSY` by Electron. Native Pi ownership rules remain unchanged.
+ The renderer sends only the anchor id, without hydrating or replacing the
+ source transcript. This preserves live updates and avoids stopping the parent.
+ Disabling the button would leave the requested concurrent workflow unavailable;
+ removing all busy guards would allow copying a partially executed tool loop.
- A handled file or index failure removes the child transcript and copied
inputs and leaves no visible child. Process crashes continue to follow the transcript store's
existing orphan-file recovery policy.
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 07350b524..341afb1eb 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1063,8 +1063,12 @@ configuration.
`session/fork` is a protocol-v5 channel that creates an independent
session from the source session's current active transcript. When optional
`throughMessageId` is present, the copied snapshot ends at that message; an
-unknown id returns `NOT_FOUND`. Electron rejects
-the request with `AGENT_BUSY` while that source session has an active turn.
+unknown id returns `NOT_FOUND`. While a Desktop source has an active turn,
+`throughMessageId` may select an already-completed assistant prefix containing
+no messages owned by a running turn. The host validates this under its RPC lock;
+whole-session and active-turn forks still return `AGENT_BUSY`. Native Pi forks
+retain their existing idle/ownership guard. The source continues running when
+the child is activated; the renderer never reloads history over its live tail.
Electron owns localization and supplies the user-facing branch title; the host
fallback title is reserved for non-UI callers.
The host assigns a new session id, message ids, and tool-call ids; it copies
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 34e823c99..e5117aab7 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -291,10 +291,12 @@ to later refresh and inference; the vendor picker does not collect them.
The child inherits project/provider/model/mode/thinking and
permission configuration, receives new message/tool-call ids, and starts
without turns, revisions, notifications, artifacts, grants, or scratch data.
- Missing sources return `NOT_FOUND`; Electron rejects active sources with
- `AGENT_BUSY` before forwarding and normalizes the host's persisted
- running-turn `CONFLICT` fallback to `AGENT_BUSY`; an unknown source or
- `throughMessageId` returns `NOT_FOUND`
+ Missing sources or anchors return `NOT_FOUND`. While a Desktop source runs,
+ only a completed assistant prefix containing no indexed messages owned by a
+ running turn is allowed. This check and publication share the host RPC lock.
+ Whole-session, non-assistant, streaming/error, or live-turn anchors return
+ `CONFLICT`, normalized by Electron to `AGENT_BUSY`. The source turn continues
+ without sharing runtime state with the child.
- `session.get` — accepts an optional renderer read window:
`messageBefore` is the exclusive zero-based end offset, `messageLimit` is
the positive page size, and `contentLimit` is the positive character budget
diff --git a/docs/spec/03-runtime/10-session-state-machine.md b/docs/spec/03-runtime/10-session-state-machine.md
index 5bcf5b1f5..c7ac66fb7 100644
--- a/docs/spec/03-runtime/10-session-state-machine.md
+++ b/docs/spec/03-runtime/10-session-state-machine.md
@@ -121,11 +121,12 @@ turn that has ended.
calls are no-ops. Renderer terminal lifecycle events update the transcript
and turn result card; the sidebar terminal mark is derived only from the
corresponding unread notification, never from `agent_end` alone.
-10. Fork is allowed only while the source is idle. The child begins idle with
- no turn or waiting-permission state. Electron returns `AGENT_BUSY` for its
- active runtime guard and normalizes the host's persisted running-turn
- `CONFLICT` fallback to the same IPC error. Neither path produces a partial
- child.
+10. Whole-session fork is idle-only. A Desktop message-scoped fork may copy
+ a completed assistant prefix during a later turn, provided no indexed row in
+ the prefix belongs to a running turn. The source continues; the child begins
+ idle with no turn or waiting-permission state. Other busy forks return host
+ `CONFLICT` / IPC `AGENT_BUSY`; native Pi keeps its ownership/idle guard.
+ No refused fork produces a partial child.
11. Supplying `throughMessageId` changes only the snapshot boundary. Assistant
Fork/Edit still creates a new idle session id with no shared turn,
permission wait, runtime, or provider-cache state (D134).
@@ -217,8 +218,8 @@ transcript-file line first, index transaction second.
transcript-event or workspace-root crossover
5. each unseen completed/failed turn produces exactly one notification record
while a visible-current result or aborted turn produces none
-6. an idle fork starts as an independent idle session; a busy source cannot
- produce a child
+6. a fork starts as an independent idle session; a busy Desktop source can
+ fork only a completed assistant prefix outside its running turn
7. a message-scoped fork excludes later rows and begins with no source runtime
or provider-cache state
8. a running session can queue removable FIFO prompts per session; Send now
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 90b298a14..2d59926f4 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8,6 +8,22 @@
## 1. Goals
+### E2E-CHAT-fork-completed-reply-while-running
+
+- **Preconditions:** Isolated real desktop profile, configured model, two turns
+ in one Desktop conversation; the first assistant reply has completed.
+- **Steps:** Send the second prompt. While it is still running, click **Branch
+ from this reply** on the first reply. Continue chatting in the child, then
+ return to the parent.
+- **Expected:** The child contains only history through the first reply, can
+ continue independently, and starts with no running turn. The parent keeps
+ running and retains its second prompt and reply. No live tail is overwritten.
+ A whole-session fork and a fork within the active tool loop remain rejected.
+ A navigation during the fork response records the child without stealing focus.
+- **Coverage:** Host fork regression, renderer session-fork-running tests,
+ session IPC contract tests, and real-model desktop acceptance. A local model
+ fixture or mocked component result is not real-model acceptance evidence.
+
### E2E-IMAGES-desktop-conversation
- **Preconditions:** Isolated desktop profile and workspace, built image feature,
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index c55a65deb..157911ca2 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -857,8 +857,11 @@ ID、或会话无法解析出默认目标时,得到 `supportsReasoning: false`
`session/fork` 是一个协议 v5 通道,可创建独立的
来自源会话当前活动记录的会话。当可选时
`throughMessageId` 存在,复制的快照以该消息结束;一个
-未知 ID 返回 `NOT_FOUND`。 Electron 拒绝
-当该源会话处于活动状态时,使用 `AGENT_BUSY` 发出请求。
+Unknown ids return `NOT_FOUND`. A running Desktop source may fork a completed
+assistant prefix that contains no messages owned by a running turn. The host
+checks this under its RPC lock. Whole-session and active-turn forks remain
+`AGENT_BUSY`; native Pi keeps its idle/ownership guard. The source continues
+running without renderer history hydration replacing its live tail.
Electron拥有本地化并提供面向用户的分支名称;主机
后备标题是为非 UI 调用者保留的。
主机分配新的会话 ID、消息 ID 和工具调用 ID;它复制
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.md
index a088f1a6b..7687aa4db 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
@@ -226,17 +226,19 @@ type ToolBudgetHealth = {
- `session.list`
- `session.create` — 接受可选的 `thinkingLevel`; missing/null 默认值
至 `off`
-- `session.fork` — 接受 `sessionId`,呼叫者提供的可选显示
- `title`,以及可选的 `throughMessageId`;创造
- 来自源当前活动规范的一个独立会话
- 转录本,在提供时在选定的消息处被截断。
- 孩子继承 project/provider/model/mode/thinking 并且
- 权限配置,接收新的 message/tool-call id,并启动
- 无需轮流、修订、通知、工件、资助或临时数据。
- 缺少源返回 `NOT_FOUND`; Electron 拒绝活动源
- `AGENT_BUSY` 在转发之前并标准化主机的持久化
- 运行转向 `CONFLICT` 回退到 `AGENT_BUSY`;来源不明或
- `throughMessageId` 返回 `NOT_FOUND`
+- `session.fork` — accepts `sessionId`, an optional caller-provided display
+ `title`, and optional `throughMessageId`; creates
+ one independent session from the source's current active canonical
+ transcript, truncated inclusively at the selected message when supplied.
+ The child inherits project/provider/model/mode/thinking and
+ permission configuration, receives new message/tool-call ids, and starts
+ without turns, revisions, notifications, artifacts, grants, or scratch data.
+ Missing sources or anchors return `NOT_FOUND`. While a Desktop source runs,
+ only a completed assistant prefix containing no indexed messages owned by a
+ running turn is allowed. This check and publication share the host RPC lock.
+ Whole-session, non-assistant, streaming/error, or live-turn anchors return
+ `CONFLICT`, normalized by Electron to `AGENT_BUSY`. The source turn continues
+ without sharing runtime state with the child.
- `session.get`
- `session.delete`
- `session.getScratchPath` — 会话的 scratch 目录(D114),按需创建
diff --git a/docs/zh-CN/spec/03-runtime/10-session-state-machine.md b/docs/zh-CN/spec/03-runtime/10-session-state-machine.md
index 52839bf9d..aed1a8a09 100644
--- a/docs/zh-CN/spec/03-runtime/10-session-state-machine.md
+++ b/docs/zh-CN/spec/03-runtime/10-session-state-machine.md
@@ -113,11 +113,11 @@ accept_prompt
插入 `task.failed`,并且结果已在焦点当前中可见
聊天或任何 `aborted` 回合不会插入任何通知 (D117)。重复终端
调用是无操作的。
-9. 仅当源空闲时才允许分叉。孩子开始无所事事
- 没有回合或等待许可状态。 Electron 返回 `AGENT_BUSY` 的
-主动运行时保护并规范主机的持续运行轮流
- `CONFLICT` 回退到相同的 IPC 错误。两条路径均不产生部分
- 孩子。
+9. Whole-session fork is idle-only. A running Desktop source may fork a
+ completed assistant prefix with no indexed rows owned by a running turn.
+ The parent continues and the child starts idle. Other busy forks return
+ host `CONFLICT` / IPC `AGENT_BUSY`; native Pi keeps its existing idle and
+ ownership guards. Refusal never produces a partial child.
10. 提供 `throughMessageId` 仅更改快照边界。助理
Fork/Edit 仍然创建一个新的空闲会话 ID,没有共享轮次,
权限等待、运行时或提供商缓存状态 (D134)。
@@ -194,8 +194,8 @@ accept_prompt
转录事件或工作空间根交叉
5. 每个未见过的 completed/failed 回合恰好产生一条通知记录
而可见当前结果或中止的回合不会产生任何结果
-6. 空闲分叉作为独立的空闲会话启动;繁忙的信号源无法
- 生一个孩子
+6. A fork starts as an independent idle session; a busy Desktop source may
+ fork only a completed assistant prefix outside its running turn
7. 消息范围的分叉排除后面的行并且从没有源运行时开始
或提供商缓存状态
8. Plan、Goal 和 Agent 使用 1 个 pi Agent; Composer-左模式芯片、UI
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.md
index 67407c32f..13d57c541 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
@@ -8674,3 +8674,19 @@ the latest destination. These assertions measure work counts, not device FPS.
**证据:** 记录构建和测试退出码、基线 SHA、依赖版本、产物标识及独立评审,报告位于
`docs/project/hosted-search-contract-verification.md`。不得记录真实会话或凭据。未执行明确标为 NOT RUN,不得标为 PASS。
+
+### E2E-CHAT-fork-completed-reply-while-running
+
+- **Preconditions:** Isolated real desktop profile, configured model, two turns
+ in one Desktop conversation; the first assistant reply has completed.
+- **Steps:** Send the second prompt. While it is still running, click **Branch
+ from this reply** on the first reply. Continue chatting in the child, then
+ return to the parent.
+- **Expected:** The child contains only history through the first reply, can
+ continue independently, and starts with no running turn. The parent keeps
+ running and retains its second prompt and reply. No live tail is overwritten.
+ A whole-session fork and a fork within the active tool loop remain rejected.
+ A navigation during the fork response records the child without stealing focus.
+- **Coverage:** Host fork regression, renderer session-fork-running tests,
+ session IPC contract tests, and real-model desktop acceptance. A local model
+ fixture or mocked component result is not real-model acceptance evidence.