From 64417d666fca5a0727a53cb4f8dd01d99cf200ad Mon Sep 17 00:00:00 2001 From: lutfi-zain <147457356+lutfi-zain@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:25:28 +0700 Subject: [PATCH 1/2] feat(chat): support in-place session cloning when forking from active leaf (#365) - Update ForkTarget to a discriminated union (ForkLeafTarget vs ForkBranchTarget) - Active branch leaf executes parameterless RPC fork(), cloning the session in-place with full history intact (matching CLI /fork) - Historical messages preserve branch(entryId) time-travel rewind and prompt prefill for edit-and-resend - Unlock forking for single-turn sessions ([user, assistant]) - Add concurrency guard in rpc-manager to prevent forking during active token streaming - Add differentiated tooltips: 'Fork session' on leaf vs 'Branch from here' on historical turns - Add comprehensive test coverage in chat-fork.test.mjs and rpc-manager.test.mjs --- components/ChatWindow.tsx | 15 ++++++---- components/MessageView.tsx | 58 ++++++++++++++++++++++++------------- hooks/useAgentSession.ts | 14 ++++++--- lib/chat-fork.test.mjs | 31 +++++++++++++------- lib/chat-fork.ts | 52 +++++++++++++++++++++++++++++---- lib/i18n/locales/en.json | 2 ++ lib/i18n/locales/ja.json | 2 ++ lib/i18n/locales/zh-CN.json | 2 ++ lib/rpc-manager.test.mjs | 27 +++++++++++++++++ lib/rpc-manager.ts | 31 +++++++++++++------- 10 files changed, 178 insertions(+), 56 deletions(-) diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 9838cd986..aa879ebf4 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -293,7 +293,9 @@ interface CommittedTranscriptProps { isNew: boolean; forkingEntryId: string | null; editingEntryId: string | null; - handleFork: (entryId: string, editPrompt: boolean) => void; + handleFork: (entryId?: string, editPrompt?: boolean) => void; + activeLeafId?: string | null; + headLeafId?: string | null; handleEdit: (entryId: string, content: string) => Promise; modelNames: Record; messageCwd: string | undefined; @@ -324,13 +326,13 @@ interface CommittedTranscriptProps { */ const CommittedTranscript = memo(function CommittedTranscript({ messages, entryIds, conversationMeta, messageRefs, isStreaming, sessionBusy, isCompacting, externalRunActive, isNew, forkingEntryId, editingEntryId, - handleFork, handleEdit, modelNames, messageCwd, onOpenFile, sessionId, + handleFork, handleEdit, modelNames, messageCwd, onOpenFile, sessionId, activeLeafId, headLeafId, toolCallsDefaultCollapsed, hideToolActivity, neverFoldActivity, showToolCallsUnfolded, expandThinkingByDefault, hideThinkingBlock, visibleCount, nearBottom, sentinelRef, handleLoadMoreClick, }: CommittedTranscriptProps) { const { t } = useI18n(); const { toolResultsMap, lastAnchorIdx, visibleRefIndexByMessage } = conversationMeta; // omp's `branch` command accepts a user entry only; see lib/chat-fork.ts. - const forkTargets = useMemo(() => resolveForkTargets(messages, entryIds), [messages, entryIds]); + const forkTargets = useMemo(() => resolveForkTargets(messages, entryIds, { activeLeafId, headLeafId }), [messages, entryIds, activeLeafId, headLeafId]); const attachVisibleRef = (idx: number, refIndex: number) => (el: HTMLDivElement | null) => { messageRefs.current[refIndex] = el; @@ -373,8 +375,9 @@ const CommittedTranscript = memo(function CommittedTranscript({ entryId={entryIds[idx]} forkEntryId={forkTarget?.entryId} forkEditsPrompt={forkTarget?.editPrompt} + forkIsLeaf={forkTarget?.type === "fork"} onFork={canOfferFork ? handleFork : undefined} - forking={forkingEntryId === forkTarget?.entryId} + forking={forkingEntryId !== null && (forkTarget?.type === "fork" ? forkingEntryId === "__LEAF__" : forkingEntryId === forkTarget?.entryId)} forkDisabled={historyMutationPending} onEdit={canOfferEdit ? handleEdit : undefined} editing={editingEntryId === entryIds[idx]} @@ -555,7 +558,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu }, [onAgentEnd]); const { - loading, error, messages, entryIds, showPreCompactionHistory, streamState, + loading, error, data, activeLeafId, messages, entryIds, showPreCompactionHistory, streamState, agentRunning, bashRunning, pendingBash, deferredBash, modelNames, modelList, modelsLoading, modelError, modelThinkingLevels, modelThinkingLevelMaps, thinkingLevel, fastModeEnabled, fastModeActive, slowModeSupported, slowModeEnabled, slowModeScope, usageLimit, externalRunActive, toolPreset, @@ -1409,6 +1412,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu isNew={isNew} forkingEntryId={forkingEntryId} editingEntryId={editingEntryId} + activeLeafId={activeLeafId} + headLeafId={data?.leafId} handleFork={handleFork} handleEdit={handleEdit} modelNames={modelNames} diff --git a/components/MessageView.tsx b/components/MessageView.tsx index a8e2f1a1c..b14e98802 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -166,7 +166,8 @@ interface Props { forkEntryId?: string; /** Forking puts the branched prompt back into the composer (edit-and-resend). */ forkEditsPrompt?: boolean; - onFork?: (entryId: string, editPrompt: boolean) => void; + forkIsLeaf?: boolean; + onFork?: (entryId?: string, editPrompt?: boolean) => void; forking?: boolean; forkDisabled?: boolean; onEdit?: (entryId: string, content: string) => Promise; @@ -213,12 +214,12 @@ function haveSameRelevantToolResults( return true; } -export const MessageView = memo(function MessageView({ message, isStreaming, toolResults, modelNames, cwd, onOpenFile, entryId, forkEntryId, forkEditsPrompt, onFork, forking, forkDisabled, onEdit, editing, editDisabled, showTimestamp, prevTimestamp, sessionId, toolCallsDefaultCollapsed = true, expandThinkingByDefault = false, hideThinking = false, sourceBlockIndices, liveTokensPerSecond }: Props) { +export const MessageView = memo(function MessageView({ message, isStreaming, toolResults, modelNames, cwd, onOpenFile, entryId, forkEntryId, forkEditsPrompt, forkIsLeaf, onFork, forking, forkDisabled, onEdit, editing, editDisabled, showTimestamp, prevTimestamp, sessionId, toolCallsDefaultCollapsed = true, expandThinkingByDefault = false, hideThinking = false, sourceBlockIndices, liveTokensPerSecond }: Props) { if (message.role === "user") { - return ; + return ; } if (message.role === "assistant") { - return ; + return ; } if (message.role === "toolResult") { // Rendered inline under its toolCall — skip standalone rendering if paired @@ -251,6 +252,7 @@ export const MessageView = memo(function MessageView({ message, isStreaming, too && prev.entryId === next.entryId && prev.forkEntryId === next.forkEntryId && prev.forkEditsPrompt === next.forkEditsPrompt + && prev.forkIsLeaf === next.forkIsLeaf && prev.onFork === next.onFork && prev.forking === next.forking && prev.forkDisabled === next.forkDisabled @@ -288,10 +290,11 @@ function imageBlockSrc(img: ImageContent): string { * resolved by `resolveForkTargets` — for an assistant reply, the next user * prompt, so the reply stays in the fork's history. */ -function ForkSessionButton({ entryId, editPrompt, onFork, forking, forkDisabled }: { - entryId: string; - editPrompt: boolean; - onFork: (entryId: string, editPrompt: boolean) => void; +function ForkSessionButton({ entryId, editPrompt = false, isLeaf = false, onFork, forking, forkDisabled }: { + entryId?: string; + editPrompt?: boolean; + isLeaf?: boolean; + onFork: (entryId?: string, editPrompt?: boolean) => void; forking?: boolean; forkDisabled?: boolean; }) { @@ -301,20 +304,31 @@ function ForkSessionButton({ entryId, editPrompt, onFork, forking, forkDisabled if (confirmingId !== null && confirmingId !== entryId) setConfirmingId(null); const confirming = confirmingId === entryId; const blocked = forkDisabled || forking; + const tooltipContent = forking + ? t("messageView.creatingSession") + : isLeaf + ? t("messageView.forkSession") + : t("messageView.branchFromHere"); return ( <> { setConfirmingId(open ? entryId : null); }} + onOpenChange={(open) => { setConfirmingId(open ? (isLeaf ? "__LEAF__" : (entryId ?? null)) : null); }} title={t("messageView.forkConfirmTitle")} - description={t(editPrompt ? "messageView.forkConfirmEditBody" : "messageView.forkConfirmBody")} + description={t(!isLeaf && editPrompt ? "messageView.forkConfirmEditBody" : "messageView.forkConfirmBody")} confirmLabel={t("messageView.newSession")} cancelLabel={t("chatInput.cancel")} - onConfirm={() => { setConfirmingId(null); if (!blocked) onFork(entryId, editPrompt); }} + onConfirm={() => { + setConfirmingId(null); + if (!blocked) { + if (isLeaf) onFork(undefined, false); + else if (entryId) onFork(entryId, editPrompt); + } + }} /> - + } - {canFork && } + {canFork && } )} {time && {time}} @@ -624,6 +640,7 @@ function AssistantMessageView({ entryId, forkEntryId, forkEditsPrompt = false, + forkIsLeaf = false, onFork, forking, forkDisabled, @@ -646,7 +663,8 @@ function AssistantMessageView({ /** User entry omp's `branch` command accepts for this reply (see lib/chat-fork.ts). */ forkEntryId?: string; forkEditsPrompt?: boolean; - onFork?: (entryId: string, editPrompt: boolean) => void; + forkIsLeaf?: boolean; + onFork?: (entryId?: string, editPrompt?: boolean) => void; forking?: boolean; forkDisabled?: boolean; toolCallsDefaultCollapsed: boolean; @@ -668,7 +686,7 @@ function AssistantMessageView({ const time = showTimestamp ? formatTime(message.timestamp, locale) : null; const bodyRef = useRef(null); const texts = (message.content ?? []).filter((block): block is TextContent => block.type === "text").map((block) => block.text); - const canFork = !!forkEntryId && !!onFork; + const canFork = (!!forkEntryId || !!forkIsLeaf) && !!onFork; const blockItems = (message.content ?? []) .map((block, index) => ({ block, originalIndex: sourceBlockIndices?.[index] ?? index })) .filter(({ block }) => !(hideThinking && block.type === "thinking") && !isEmptyThinkingBlock(block, { isStreaming })); @@ -895,7 +913,7 @@ function AssistantMessageView({ )} - {canFork && } + {canFork && } {time && {time}} diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index ab01a9695..f1a6fa413 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -45,6 +45,7 @@ import { subscribeSessionsChanged } from "@/lib/session-change-bus"; import { EVENT_STREAM_CLOSED, EVENT_STREAM_OPEN, addToOutbox, dropFromOutbox, newOutboxId, openEventStream, subscribeOutbox, type EventStream, type LocalOutboxEntry } from "@/lib/event-stream"; import { createSessionCatchUp, type SessionCatchUp, type SessionLiveFields } from "./useAgentSession-sync"; import type { SessionLiveSnapshot } from "@/lib/session-sync"; +import type { ForkTarget } from "@/lib/chat-fork"; import { mergeSubagentRoster, parseSubagentActivityEvent, @@ -3559,20 +3560,25 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // editPrompt: omp's `branch` drops the chosen user prompt from the fork and // returns its text — put it in the fork's composer (edit-and-resend). - const handleFork = useCallback(async (entryId: string, editPrompt: boolean) => { + // Leaf fork: parameterless `fork` clones session in-place up to the active leaf. + const handleFork = useCallback(async (target?: ForkTarget | string, editPrompt?: boolean) => { if (bashRunningRef.current || agentRunningRef.current || forkInFlightRef.current || editInFlightRef.current) return; const sid = sessionIdRef.current; if (!sid) return; + + const entryId = typeof target === "object" ? target?.entryId : (typeof target === "string" ? target : undefined); + const shouldEdit = typeof target === "object" ? target?.editPrompt : (editPrompt ?? false); + forkInFlightRef.current = true; - setForkingEntryId(entryId); + setForkingEntryId(entryId ?? "__LEAF__"); try { const result = await sendAgentCommand<{ cancelled?: boolean; newSessionId?: string; text?: string }>(sid, { type: "fork", - entryId, + ...(entryId ? { entryId } : {}), }); const { cancelled, newSessionId, text } = result ?? {}; if (!cancelled && newSessionId) { - if (editPrompt && text) setDraft(newSessionId, { value: text, images: [], files: [] }); + if (shouldEdit && text) setDraft(newSessionId, { value: text, images: [], files: [] }); // The forked child keeps its spawn flags: carry the advisor choice to // the new id, or the toggle flips off on switch and the next prompt // respawns the fork without --advisor. diff --git a/lib/chat-fork.test.mjs b/lib/chat-fork.test.mjs index 35dc6144a..d36da051f 100644 --- a/lib/chat-fork.test.mjs +++ b/lib/chat-fork.test.mjs @@ -3,32 +3,32 @@ import test from "node:test"; const { resolveForkTargets } = await import("./chat-fork.ts"); -const edit = (entryId) => ({ entryId, editPrompt: true }); -const keep = (entryId) => ({ entryId, editPrompt: false }); +const branch = (entryId, editPrompt) => ({ type: "branch", entryId, editPrompt }); +const leafFork = () => ({ type: "fork", editPrompt: false }); const rows = (...roles) => roles.map((role) => (role === "summary" ? { role: "user", branchSummary: true } : { role })); -test("user prompts edit-and-resend; replies fork at the next prompt so they are kept", () => { +test("user prompts edit-and-resend; replies fork at the next prompt so they are kept; active leaf clones in-place", () => { assert.deepEqual( resolveForkTargets(rows("user", "assistant", "toolResult", "assistant", "user", "assistant"), ["u1", "a1", "t1", "a2", "u2", "a3"]), - [undefined, keep("u2"), undefined, keep("u2"), edit("u2"), edit("u2")], + [undefined, branch("u2", false), undefined, branch("u2", false), branch("u2", true), leafFork()], ); }); -test("a fork that would edit the first prompt into an empty session is not offered", () => { - assert.deepEqual(resolveForkTargets(rows("user", "assistant"), ["u1", "a1"]), [undefined, undefined]); +test("single-turn session allows forking assistant response as leaf clone, but first user prompt has no rewind target", () => { + assert.deepEqual(resolveForkTargets(rows("user", "assistant"), ["u1", "a1"]), [undefined, leafFork()]); // After compaction the first prompt has a summary before it, so it can be edited. // A compaction row renders as "custom", not a user message // (lib/session-reader.ts), so it can never become a branch point itself. assert.deepEqual( resolveForkTargets(rows("custom", "user", "assistant"), ["c0", "u1", "a1"]), - [undefined, edit("u1"), edit("u1")], + [undefined, branch("u1", true), leafFork()], ); }); test("branch summaries render as user rows but are never branch points", () => { assert.deepEqual( resolveForkTargets(rows("user", "assistant", "user", "assistant", "summary", "user", "assistant"), ["u0", "a0", "u1", "a1", "s1", "u2", "a2"]), - [undefined, keep("u1"), edit("u1"), keep("u2"), undefined, edit("u2"), edit("u2")], + [undefined, branch("u1", false), branch("u1", true), branch("u2", false), undefined, branch("u2", true), leafFork()], ); }); @@ -39,9 +39,20 @@ test("messages with no usable user entry have no fork target", () => { ); }); -test("a reply with no following prompt to fork at is offered nothing", () => { +test("leaf assistant forks in-place even when terminal user prompt has no entry ID", () => { assert.deepEqual( resolveForkTargets(rows("user", "assistant", "user", "assistant", "user", "assistant"), ["u0", "a0", "u1", "a1", undefined, "a2"]), - [undefined, keep("u1"), edit("u1"), edit("u1"), undefined, undefined], + [undefined, branch("u1", false), branch("u1", true), branch("u1", true), undefined, leafFork()], + ); +}); + +test("when activeLeafId is desynchronized from HEAD, terminal message falls back to branch instead of leaf fork", () => { + assert.deepEqual( + resolveForkTargets( + rows("user", "assistant", "user", "assistant"), + ["u1", "a1", "u2", "a2"], + { activeLeafId: "branch-a-leaf", headLeafId: "head-leaf" }, + ), + [undefined, branch("u2", false), branch("u2", true), branch("u2", true)], ); }); diff --git a/lib/chat-fork.ts b/lib/chat-fork.ts index 8c2ba0675..b9751743e 100644 --- a/lib/chat-fork.ts +++ b/lib/chat-fork.ts @@ -20,27 +20,67 @@ * resolve to that have no fork target, nor do rows with no usable user entry. */ -export interface ForkTarget { +export interface ForkBranchTarget { + type: "branch"; entryId: string; /** Put the branched prompt's text back into the composer. */ editPrompt: boolean; } +export interface ForkLeafTarget { + type: "fork"; + entryId?: undefined; + /** Leaf fork clones session in-place with full history; composer remains untouched. */ + editPrompt: false; +} + +export type ForkTarget = ForkBranchTarget | ForkLeafTarget; + +export interface ResolveForkTargetsOptions { + /** Active branch leaf id in the UI, if navigated away from HEAD. */ + activeLeafId?: string | null; + /** Authoritative leaf id of the running session process. */ + headLeafId?: string | null; +} + export function resolveForkTargets( messages: readonly { role: string; branchSummary?: boolean }[], entryIds: readonly (string | undefined)[], + options?: ResolveForkTargetsOptions, ): (ForkTarget | undefined)[] { // Branch summaries render as user rows but are not entries omp can branch at. const roles = messages.map((message) => (message.branchSummary ? "branchSummary" : message.role)); const targets: (ForkTarget | undefined)[] = roles.map(() => undefined); + + // If there are no user entries in the session, there is no usable conversation to fork or branch. + const hasUserEntry = roles.some((role, index) => role === "user" && !!entryIds[index]); + if (!hasUserEntry) return targets; + // 1. Identify the active branch leaf (the last assistant or user message with a valid entryId) + let leafIndex = -1; + for (let index = roles.length - 1; index >= 0; index--) { + if ((roles[index] === "assistant" || roles[index] === "user") && entryIds[index]) { + leafIndex = index; + break; + } + } + + // 2. When synchronized with HEAD, the active leaf triggers an in-place session clone (CLI /fork parity) + const isHeadSynchronized = options?.activeLeafId == null || options.activeLeafId === options.headLeafId; + if (leafIndex !== -1 && isHeadSynchronized) { + targets[leafIndex] = { type: "fork", editPrompt: false }; + } + + // 3. Historical assistant replies fork at the NEXT user prompt, keeping the reply in history let nextUserEntryId: string | undefined; for (let index = roles.length - 1; index >= 0; index--) { - if (roles[index] === "user") nextUserEntryId = entryIds[index]; - else if (roles[index] === "assistant" && nextUserEntryId) { - targets[index] = { entryId: nextUserEntryId, editPrompt: false }; + if (roles[index] === "user") { + nextUserEntryId = entryIds[index]; + } else if (roles[index] === "assistant" && nextUserEntryId && !targets[index]) { + targets[index] = { type: "branch", entryId: nextUserEntryId, editPrompt: false }; } } - // The row-0 prompt has nothing before it (a compaction summary would be row 0). + + // 4. Historical user prompts rewind to their own entry, returning the prompt for edit-and-resend let ownUserEntryId: string | undefined; let ownIsFirstPrompt = false; for (let index = 0; index < roles.length; index++) { @@ -50,7 +90,7 @@ export function resolveForkTargets( } if (targets[index] || !ownUserEntryId || ownIsFirstPrompt) continue; if (roles[index] === "user" || roles[index] === "assistant") { - targets[index] = { entryId: ownUserEntryId, editPrompt: true }; + targets[index] = { type: "branch", entryId: ownUserEntryId, editPrompt: true }; } } return targets; diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 0d894e18e..71cc7c9cc 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -957,6 +957,8 @@ "messageView.modifiedFiles": "Modified files", "messageView.newSession": "Fork", "messageView.newSessionTitle": "Fork a new session from this point", + "messageView.forkSession": "Fork session (clone full conversation)", + "messageView.branchFromHere": "Branch from here (rewind to prompt)", "messageView.noMessage": "(no message)", "messageView.noOutput": "(no output)", "messageView.noSummary": "(no summary)", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index f4da5be21..1e4da7771 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -916,6 +916,8 @@ "messageView.modifiedFiles": "変更されたファイル", "messageView.newSession": "新しいセッション", "messageView.newSessionTitle": "この時点から新しいセッションをフォークします", + "messageView.forkSession": "セッションをフォーク (会話全体を複製)", + "messageView.branchFromHere": "ここから分岐 (プロンプトを再編集)", "messageView.noMessage": "(メッセージなし)", "messageView.noOutput": "(出力なし)", "messageView.noSummary": "(要約なし)", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 98d0c3479..ecac34dc7 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -916,6 +916,8 @@ "messageView.modifiedFiles": "已修改的文件", "messageView.newSession": "新会话", "messageView.newSessionTitle": "从此处分叉出新会话", + "messageView.forkSession": "分叉会话(完整克隆当前对话)", + "messageView.branchFromHere": "从此处分支(回退并重新编辑提示词)", "messageView.noMessage": "(无消息)", "messageView.noOutput": "(无输出)", "messageView.noSummary": "(无摘要)", diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index fffd581cf..62a130a58 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -2729,6 +2729,33 @@ test("independent Fork still sends native branch and returns a new session ID an assert.equal(wrapper.sessionId, "new-fork-session"); assert.equal(events.some((event) => event.type === "session_history_changed"), false); }); +test("parameterless Fork sends native fork without entryId to clone active session in-place", async (t) => { + const commands = []; + let sessionId = "original-fork-session"; + const { wrapper } = snapshotSession(t, async (command) => { + commands.push(command); + if (command.type === "fork") { + sessionId = "cloned-fork-session"; + return { cancelled: false }; + } + if (command.type === "get_state") return { sessionId, sessionFile: join(isolatedAgentDir, `${sessionId}.jsonl`), isStreaming: false, isCompacting: false }; + return {}; + }, SnapshotWrapper, sessionId); + await wrapper.send({ type: "get_state" }); + commands.length = 0; + assert.deepEqual(await wrapper.send({ type: "fork" }), { + cancelled: false, newSessionId: "cloned-fork-session", + }); + assert.deepEqual(commands.map((command) => command.type), ["fork", "get_state"]); + assert.equal(wrapper.sessionId, "cloned-fork-session"); +}); + +test("Fork rejects while a response is streaming", async (t) => { + const { wrapper } = snapshotSession(t, async () => ({ isStreaming: true }), SnapshotWrapper); + wrapper.streaming = true; + await assert.rejects(wrapper.send({ type: "fork" }), /Cannot fork while a response is streaming/); + await assert.rejects(wrapper.send({ type: "fork", entryId: "u1" }), /Cannot fork while a response is streaming/); +}); test("server agent tools are answered by the server, not the browser (#275)", async (t) => { // Enable the off-by-default gate via the isolated settings file, and // drop the cached settings so this test's gate value is actually read. diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index e6b90dcf1..984c24c31 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2543,20 +2543,29 @@ export class AgentSessionWrapper { return this.editMessage(command.entryId); case "fork": { - // omp's `branch` is pi-web's fork: it creates a branched session file - // and switches this live process onto it (entryId must be a user - // message entry, matching the web UI's fork buttons). if (this.bashRunning) { throw new Error("Cannot fork while a shell command is running"); } - const result = await this.proc.sendCommand<{ text: string; cancelled: boolean }>({ - type: "branch", - entryId: command.entryId as string, - }); - if (result.cancelled) return { cancelled: true }; - const newSessionId = await this.refreshIdentityAfterSessionChange(); - // `text` is the branched prompt omp hands back for edit-and-resend. - return { cancelled: false, newSessionId, text: result.text }; + if (this.isRunning() || this.streaming) { + throw new Error("Cannot fork while a response is streaming"); + } + const entryId = typeof command.entryId === "string" && command.entryId.trim() ? command.entryId.trim() : undefined; + if (entryId) { + const result = await this.proc.sendCommand<{ text: string; cancelled: boolean }>({ + type: "branch", + entryId, + }); + if (result.cancelled) return { cancelled: true }; + const newSessionId = await this.refreshIdentityAfterSessionChange(); + return { cancelled: false, newSessionId, text: result.text }; + } else { + const result = await this.proc.sendCommand<{ cancelled: boolean }>({ + type: "fork", + }); + if (result.cancelled) return { cancelled: true }; + const newSessionId = await this.refreshIdentityAfterSessionChange(); + return { cancelled: false, newSessionId }; + } } case "new_session": From ac7213f56048f2b25c2073668180c377b9527ce5 Mon Sep 17 00:00:00 2001 From: lutfi-zain <147457356+lutfi-zain@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:39:54 +0700 Subject: [PATCH 2/2] fix(chat): bind leaf fork confirmation to synthetic leaf key --- components/MessageView.test.mjs | 21 +++++++++++++++++++++ components/MessageView.tsx | 5 +++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 607ad49b1..4d10e3b35 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -1030,6 +1030,27 @@ test("user messages fork at their own entry and edit the prompt", async (t) => { view.unmount(); }); +test("assistant messages at active leaf fork in place with undefined entryId after confirmation", async (t) => { + const originalMatchMedia = window.matchMedia; + window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }); + t.after(() => { + if (originalMatchMedia) window.matchMedia = originalMatchMedia; + else delete window.matchMedia; + }); + const forked = []; + const view = render(React.createElement(MessageView, { + message: { role: "assistant", model: "test", provider: "test", content: [{ type: "text", text: "Leaf response." }] }, + entryId: "assistant-leaf", + forkIsLeaf: true, + onFork: (entryId, editPrompt) => forked.push([entryId, editPrompt]), + })); + await act(async () => { fireEvent.click(view.getByRole("button", { name: FORK_LABEL })); }); + assert.deepEqual(forked, []); + await act(async () => { fireEvent.click(view.getByRole("button", { name: "Fork" })); }); + assert.deepEqual(forked, [[undefined, false]]); + view.unmount(); +}); + test("user-message Edit only runs after confirmation, and not once blocked", async (t) => { const originalMatchMedia = window.matchMedia; window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }); diff --git a/components/MessageView.tsx b/components/MessageView.tsx index b14e98802..63c665423 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -300,9 +300,10 @@ function ForkSessionButton({ entryId, editPrompt = false, isLeaf = false, onFork }) { const { t } = useI18n(); // Rows are keyed by index, so bind the dialog to the entry it was opened for. + const targetKey = isLeaf ? "__LEAF__" : (entryId ?? null); const [confirmingId, setConfirmingId] = useState(null); - if (confirmingId !== null && confirmingId !== entryId) setConfirmingId(null); - const confirming = confirmingId === entryId; + if (confirmingId !== null && confirmingId !== targetKey) setConfirmingId(null); + const confirming = targetKey !== null && confirmingId === targetKey; const blocked = forkDisabled || forking; const tooltipContent = forking ? t("messageView.creatingSession")