From a5940dbea756bc0d84ff36e5eee2444bb3f2efe2 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 14:12:52 -0400 Subject: [PATCH 1/4] feat(remote): fork chats on a paired Mac from the desktop Adds the forkChat and fork-summary peer operations, gates them on the host's chat-fork-v1 and chat-fork-summary-v1 features, and wires Fork from here, Edit in fork and Fork with summary into the remote chat pane with the lineage row, the summary card and the send hold. A fork whose answer is lost is retried under the same idempotency key, so the host replays it instead of copying again. Edit in fork seeds only the prompt text; files the host staged for it are released. Co-Authored-By: Claude Opus 5.5 --- .memory/chat-fork.md | 29 ++ main/services/peer-operation.test.ts | 104 +++++++ main/services/peer-operation.ts | 75 ++++- main/services/peer-remote-chat-fork.test.ts | 322 ++++++++++++++++++++ main/services/peer-response.ts | 4 + package.json | 2 +- renderer/components/message-list.tsx | 10 +- renderer/lib/hosts/chat-session-control.ts | 44 +++ renderer/lib/hosts/host-chat-adapter.ts | 44 +++ renderer/lib/hosts/host-query-keys.ts | 2 + renderer/lib/hosts/local-host-adapter.ts | 1 + renderer/lib/hosts/remote-host-adapter.ts | 82 +++++ renderer/main/remote-chat-view.test.tsx | 106 ++++++- renderer/main/remote-chat-view.tsx | 306 ++++++++++++++++++- renderer/shared/peer-operation.ts | 6 +- scripts/ci-test-registry.json | 1 + 16 files changed, 1121 insertions(+), 17 deletions(-) create mode 100644 main/services/peer-remote-chat-fork.test.ts diff --git a/.memory/chat-fork.md b/.memory/chat-fork.md index a95f236bab..7a1a4805a0 100644 --- a/.memory/chat-fork.md +++ b/.memory/chat-fork.md @@ -71,3 +71,32 @@ Plan: `docs/plans/chat-fork-plan.md` (five PRs). This note tracks what has lande - `fork-summary-card.test.tsx`: the card states. - `chat-copy-view.test.ts`: `withForkLineage` and `forkSummaryRows`. - `message-bubble.test.tsx`: the card's placement. + +## Paired Macs — desktop forks a peer's chat (branch `feat/chat-fork-peer`, stacked on `feat/chat-fork-remote`) + +- **Peer operations.** + - `forkChat` is `POST /chats/{id}/fork`, with If-Match, an Idempotency-Key and a strictly validated body. + - `forkSummaryRetry`, `forkSummarySkip` and `forkSummaryCancel` are `POST /chats/{id}/fork-summary/`. They take an empty body and are not keyed. + - All of them are parsed by the protocol's own parsers. +- **Adapter and gating.** + - `RemoteHostAdapter` grants `fork` when the host advertises `chat-fork-v1` and `forkSummary` when it also advertises `chat-fork-summary-v1`. Both also need `chat:write`. + - `LocalHostAdapter` never grants either: the local pane forks through `chatsApi`. + - `forkLineage(chatId)` reads the full chat, because feed rows leave the summary out. +- **Keys.** `ChatSessionControl.fork` keeps the idempotency key for an identical request (same message, position, summary and revision) after an `outcome_unknown`. A retry therefore replays the first fork instead of making a second copy. +- **Pane** (`remote-chat-view.tsx`). + - Fork is offered only for chats the feed lists (`forkable`). That excludes Bot chats, and also chats beyond the 2000-row feed cap. + - Edit in fork is hidden on the first prompt while no older page exists (`MessageList forkBeforeFirstPrompt`). + - Forks are disabled while a run has started or a send is in flight. + - After a fork the pane opens the new chat. A `before` fork seeds the composer draft with only `prefill.text`. The composer can't show uploads staged on the host, so those are released and the user is told to attach them again. + - The lineage row and `ForkSummaryCard` come from `useRemoteForkLineage`. It runs one full-chat read (best-effort, under the 1 MiB GET cap), and reads again only while a pending summary's feed revision moves. + - Summary actions write the returned lineage into that query. + - A pending or failed summary holds the composer with `FORK_SUMMARY_HOLD_MESSAGE`. +- **Tests.** + - `main/services/peer-remote-chat-fork.test.ts` (in `test:remote-chat`) runs end to end over the real IPC, peer-operation and host chat service. It covers: + - a lost answer replaying one fork; + - a stale revision; + - the prefill; + - capability gating; + - the summary actions; + - refusal codes. + - `remote-chat-view.test.tsx` covers the rendered fork actions, lineage, summary hold and `remoteForkErrorMessage`. diff --git a/main/services/peer-operation.test.ts b/main/services/peer-operation.test.ts index fa0214b7e4..6c3ae56c1f 100644 --- a/main/services/peer-operation.test.ts +++ b/main/services/peer-operation.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import protocol from "../../protocol/aiden-remote/v1/openapi.json"; +import contract from "../../protocol/aiden-remote/v1/fixtures/contract.json"; import { peerOperationRequest, peerOperationResult } from "./peer-operation.js"; type Endpoint = { @@ -197,3 +198,106 @@ test("expanded peer reads reject malformed DTOs and attachment bytes stay bounde peerOperationResult({ operation: "attachmentContent" }, invalid), ); }); + +test("fork operations reach the contract's fork routes with the headers each one declares", () => { + const fork = peerOperationRequest({ + operation: "forkChat", + resourceId: "chat_1", + body: contract.chatFork.fork.request, + idempotencyKey: KEY, + revision: "rev_1", + }); + const route = contractRoute(fork.method ?? "GET", fork.path); + assert.equal(route?.operationId, "forkChat"); + assert.equal(fork.method, "POST"); + assert.ok(route?.idempotent && route.conditional, "the contract keys and conditions a fork"); + assert.equal(fork.idempotencyKey, KEY); + assert.equal(fork.revision, "rev_1"); + assert.deepEqual(fork.body, contract.chatFork.fork.request); + + for (const [operation, action] of [ + ["forkSummaryRetry", "retry"], + ["forkSummarySkip", "skip"], + ["forkSummaryCancel", "cancel"], + ] as const) { + const request = peerOperationRequest({ operation, resourceId: "chat_1" }); + assert.equal(request.path, `/chats/chat_1/fork-summary/${action}`); + const summaryRoute = contractRoute(request.method ?? "GET", request.path); + assert.equal(summaryRoute?.operationId, "chatForkSummaryAction", operation); + // The contract declares neither header, and the host reads no body. + assert.equal(summaryRoute?.idempotent, false); + assert.equal(summaryRoute?.conditional, false); + assert.equal(request.idempotencyKey, undefined); + assert.equal(request.revision, undefined); + assert.deepEqual(request.body, {}); + } +}); + +test("a fork without its key, revision or a well-formed cut point never leaves this Mac", () => { + const valid = { + operation: "forkChat", + resourceId: "chat_1", + body: { messageId: "m1", position: "before" }, + idempotencyKey: KEY, + revision: "rev_1", + }; + assert.doesNotThrow(() => peerOperationRequest(valid)); + const { idempotencyKey: _key, ...unkeyed } = valid; + const { revision: _revision, ...unconditional } = valid; + for (const invalid of [ + unkeyed, + unconditional, + { ...valid, idempotencyKey: "short" }, + { ...valid, body: undefined }, + { ...valid, body: { messageId: "m1" } }, + { ...valid, body: { messageId: "m1", position: "middle" } }, + { ...valid, body: { messageId: "../m1", position: "after" } }, + { ...valid, body: { messageId: "m1", position: "after", extra: true } }, + { ...valid, body: { messageId: "m1", position: "after", summary: { focus: "x" } } }, + { ...valid, body: { messageId: "m1", position: "after", summary: { instructions: " " } } }, + { ...valid, body: { messageId: "m1", position: "after", summary: { instructions: "x".repeat(1001) } } }, + { ...valid, resourceId: "../server" }, + { operation: "forkSummaryRetry", resourceId: "chat_1", body: { force: true } }, + ]) + assert.throws(() => peerOperationRequest(invalid), JSON.stringify(invalid)); + // At the bound, and with no focus at all, a summary request is accepted. + for (const summary of [{}, { instructions: "x".repeat(1000) }]) + assert.deepEqual( + peerOperationRequest({ ...valid, body: { messageId: "m1", position: "after", summary } }).body, + { messageId: "m1", position: "after", summary }, + ); +}); + +test("fork answers are parsed into the contract's chat and prefill shapes", async () => { + // Restaged attachments carry IDs the host minted for uploads. + const restaged = `att_${"B".repeat(43)}`; + const editFork = contract.chatFork.editFork.response; + const edited = (await peerOperationResult( + { operation: "forkChat" }, + { + ...editFork, + prefill: { ...editFork.prefill, attachments: editFork.prefill.attachments.map((entry) => ({ ...entry, id: restaged })) }, + }, + )) as { chat: { id: string; forkedFrom?: { position: string } }; prefill?: { text: string; attachments?: { id: string }[] } }; + assert.equal(edited.chat.id, "chat_fixture_fork_02"); + assert.equal(edited.chat.forkedFrom?.position, "before"); + assert.equal(edited.prefill?.text, "Now check the error codes."); + assert.deepEqual(edited.prefill?.attachments?.map((attachment) => attachment.id), [restaged]); + + const summarized = (await peerOperationResult( + { operation: "forkSummaryRetry" }, + contract.chatFork.fork.response.chat, + )) as { forkedFrom?: { summary?: { state: string } } }; + assert.equal(summarized.forkedFrom?.summary?.state, "pending"); + assert.deepEqual( + await peerOperationResult({ operation: "forkSummaryCancel" }, contract.chatFork.summaryCancel), + { cancelled: true }, + ); + + // A fork answer without lineage, or a cancel answer that is not a chat or {cancelled}, is refused. + const { forkedFrom: _lineage, ...plain } = contract.chatFork.fork.response.chat; + await assert.rejects(peerOperationResult({ operation: "forkChat" }, { chat: plain })); + for (const operation of ["forkChat", "forkSummaryRetry", "forkSummarySkip", "forkSummaryCancel"]) + await assert.rejects(peerOperationResult({ operation }, {}), operation); + await assert.rejects(peerOperationResult({ operation: "forkSummaryCancel" }, { cancelled: "yes" })); +}); diff --git a/main/services/peer-operation.ts b/main/services/peer-operation.ts index b31bce6cd2..0d6ff475c4 100644 --- a/main/services/peer-operation.ts +++ b/main/services/peer-operation.ts @@ -11,9 +11,11 @@ import { type PeerRequest, } from "./peer-transport.js"; import { + parseAidenRemoteChatForkResult, parseAidenRemoteChatProjection, parseAidenRemoteChatSummaryPage, } from "./aiden-remote-protocol.js"; +import { MAX_FORK_SUMMARY_INSTRUCTIONS_CHARS } from "../../renderer/shared/chat-copy-contract.js"; const OPERATION_FIELDS = new Set([ "operation", @@ -54,8 +56,49 @@ export const PEER_CHAT_MUTATIONS: ReadonlySet = new Set([ "markRead", "interruptAgent", "updateBotChatAccess", + // A fork never changes its source, but a summary action changes the fork. + "forkSummaryRetry", + "forkSummarySkip", + "forkSummaryCancel", ]); +/** A fork names one message to cut at and, optionally, a summary of what followed. */ +function forkBody(value: unknown): Record { + const body = peerRecord(value); + const keys = Object.keys(body); + if ( + keys.some((key) => key !== "messageId" && key !== "position" && key !== "summary") || + typeof body.messageId !== "string" || + !PUBLIC_ID.test(body.messageId) || + (body.position !== "after" && body.position !== "before") + ) + throw new Error("Invalid peer fork request."); + if (body.summary === undefined) return { messageId: body.messageId, position: body.position }; + const summary = peerRecord(body.summary); + const instructions = summary.instructions; + if ( + Object.keys(summary).some((key) => key !== "instructions") || + (instructions !== undefined && + (typeof instructions !== "string" || + !instructions.trim() || + instructions.length > MAX_FORK_SUMMARY_INSTRUCTIONS_CHARS)) + ) + throw new Error("Invalid peer fork request."); + return { + messageId: body.messageId, + position: body.position, + summary: instructions === undefined ? {} : { instructions }, + }; +} + +/** `{cancelled}` from `POST /chats/{chatId}/fork-summary/cancel`. */ +function forkSummaryCancelled(value: unknown): { cancelled: boolean } { + const record = peerRecord(value); + if (typeof record.cancelled !== "boolean") + throw new Error("Invalid peer fork summary answer."); + return { cancelled: record.cancelled }; +} + function binaryContent(value: unknown): PeerAttachmentContent { const record = peerRecord(value); const data = record.data; @@ -81,8 +124,17 @@ export async function peerOperationResult( await validatePeerResponse(name, value); if (name === "summaries") return parseAidenRemoteChatSummaryPage(value, "Peer chat summaries"); - if (name === "chat" || name === "createChat" || name === "renameChat") + if ( + name === "chat" || + name === "createChat" || + name === "renameChat" || + name === "forkSummaryRetry" || + name === "forkSummarySkip" + ) return parseAidenRemoteChatProjection(value, "Peer chat"); + if (name === "forkChat") + return parseAidenRemoteChatForkResult(value, "Peer chat fork"); + if (name === "forkSummaryCancel") return forkSummaryCancelled(value); return value; } @@ -128,6 +180,7 @@ export function peerOperationRequest( let needsKey = false; let needsRevision = false; let maxBodyBytes: number | undefined; + let body: unknown = input.body; switch (operation) { case "server": path = "/server"; @@ -324,6 +377,24 @@ export function peerOperationRequest( path = `/chats/${id()}/attachments/${pattern(input.itemId, STAGED_ATTACHMENT_ID)}`; method = "DELETE"; break; + case "forkChat": + path = `/chats/${id()}/fork`; + method = "POST"; + needsKey = true; + needsRevision = true; + body = forkBody(input.body); + break; + case "forkSummaryRetry": + case "forkSummarySkip": + case "forkSummaryCancel": + // Not keyed: retry and skip act only on the summary state they find, and + // the host reads no body for any of them. + path = `/chats/${id()}/fork-summary/${operation === "forkSummaryRetry" ? "retry" : operation === "forkSummarySkip" ? "skip" : "cancel"}`; + method = "POST"; + if (input.body !== undefined && Object.keys(peerRecord(input.body)).length > 0) + throw new Error("Invalid peer fork summary request."); + body = {}; + break; default: throw new Error("Unsupported peer operation."); } @@ -337,7 +408,7 @@ export function peerOperationRequest( path, method, ...(method !== "GET" && method !== "DELETE" - ? { body: input.body ?? {} } + ? { body: body ?? {} } : {}), ...(needsKey ? { idempotencyKey: token(input.idempotencyKey, 16) } : {}), ...(needsRevision ? { revision: token(input.revision, 1) } : {}), diff --git a/main/services/peer-remote-chat-fork.test.ts b/main/services/peer-remote-chat-fork.test.ts new file mode 100644 index 0000000000..fe5f185170 --- /dev/null +++ b/main/services/peer-remote-chat-fork.test.ts @@ -0,0 +1,322 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { AidenRemoteChatService } from "./aiden-remote-chats.js"; +import { ChatForkError } from "./chat-fork-error.js"; +import { FakeHost, FEATURES, UNHANDLED, setup } from "./peer-remote-chat-test-host.js"; +import { PeerTransportError, type PeerRequest } from "./peer-transport.js"; +import { ChatIntentLedger } from "../../renderer/lib/hosts/chat-intent-ledger.js"; +import { ChatSessionControl } from "../../renderer/lib/hosts/chat-session-control.js"; +import { HostChatControlError, hostResultValue, isOutcomeUnknown } from "../../renderer/lib/hosts/host-chat-adapter.js"; +import type { Chat, ChatMessage } from "../../renderer/lib/types.js"; + +/** + * Forking a chat on a paired Mac end to end: the pane's session control over + * the renderer adapter, main's real live IPC handlers, operation builder and + * response parsers, and the host's real chat service with its revision check, + * replay ledger and attachment staging. The fork store and the summarizer + * are stand-ins that copy and settle the way the real ones do. + */ + +const FORK_FEATURES = [...FEATURES, "chat-fork-v1", "chat-fork-summary-v1"]; + +function source(): ChatMessage[] { + return [ + { id: "u1", role: "user", content: "Why does the build fail?", createdAt: 1_100 }, + { id: "a1", role: "assistant", content: "A missing token.", createdAt: 1_200 }, + { + id: "u2", + role: "user", + content: "Fix it.", + createdAt: 1_300, + attachments: [{ id: "stored-notes", name: "notes.txt", mimeType: "text/plain", kind: "text", size: 5, text: "notes" }], + }, + { id: "a2", role: "assistant", content: "Fixed.", createdAt: 1_400 }, + ]; +} + +/** + * Serves the fork and fork-summary routes from the host's real chat service. + * `forks` is the host's chat store for the copies it made. + */ +function forkingHost(features = FORK_FEATURES) { + const host = new FakeHost("host_b", source()); + host.features = features; + const forks = new Map(); + const forkRequests: PeerRequest[] = []; + let dropForkAcks = 0; + let failure: ChatForkError | undefined; + const chatById = (id: string) => (id === host.chat.id ? host.chat : forks.get(id)); + const unused = {} as never; + const chats = new AidenRemoteChatService({ + application: { + list: async () => [{ id: host.chat.id, title: host.chat.title }, ...[...forks.values()].map(({ id, title }) => ({ id, title }))], + get: async (id: string) => ({ chat: chatById(id) ?? null }), + } as unknown as ConstructorParameters[0]["application"], + chatStore: unused, + generation: unused, + streams: unused, + models: unused, + bots: unused, + botMutations: unused, + forks: { + service: { + supportsSummaries: true, + async fork(request, caller) { + const refusal = failure; + failure = undefined; + if (refusal) throw refusal; + const chat = chatById(request.chatId); + if (!chat) throw new ChatForkError("not_found", "The chat is no longer available."); + caller.assertSource?.(chat); + caller.admitWorkspace(chat.workspaceId!).release(); + const { messageId, position } = request.forkAt!; + const cut = chat.messages.findIndex((message) => message.id === messageId); + if (cut < 0) throw new ChatForkError("message_not_found", "That message is no longer in this chat."); + const id = `fork-${forks.size + 1}`; + const kept = chat.messages + .slice(0, position === "after" ? cut + 1 : cut) + .map((message) => ({ ...message, id: `${id}-${message.id}` })); + const forked: Chat = { + ...chat, + id, + title: `${chat.title} (fork)`, + messages: kept, + forkedFrom: { + chatId: chat.id, + messageId, + position, + at: 5_000, + ...(request.summary + ? { + summary: { + state: "pending" as const, + afterMessageId: kept[kept.length - 1]!.id, + ...(request.summary.instructions ? { instructions: request.summary.instructions } : {}), + }, + } + : {}), + }, + }; + forks.set(id, forked); + return forked; + }, + }, + admitWorkspace: () => ({ isAborted: () => false, release: () => undefined }), + summaries: { + retry: async (chatId) => settle(chatId, "failed", (lineage) => ({ ...lineage, summary: { ...lineage.summary!, state: "pending" } })), + skip: async (chatId) => settle(chatId, "failed", ({ summary: _summary, ...lineage }) => lineage), + cancel: (chatId) => { + if (forks.get(chatId)?.forkedFrom?.summary?.state !== "pending") return false; + void settle(chatId, "pending", (lineage) => ({ ...lineage, summary: { ...lineage.summary!, state: "failed", error: "Stopped." } })); + return true; + }, + }, + }, + }); + + /** Moves a fork's summary on from `from`, or refuses like the real summarizer. */ + async function settle(chatId: string, from: "pending" | "failed", next: (lineage: NonNullable) => Chat["forkedFrom"]) { + const fork = forks.get(chatId); + if (fork?.forkedFrom?.summary?.state !== from) throw new Error("The fork summary changed."); + const updated = { ...fork, forkedFrom: next(fork.forkedFrom), updatedAt: fork.updatedAt + 1 }; + forks.set(chatId, updated); + return updated; + } + + const json = (value: unknown) => JSON.parse(JSON.stringify(value)) as unknown; + host.routes = async (input, deviceId) => { + const url = new URL(input.path, "https://host.invalid"); + const fork = /^\/chats\/([^/]+)\/fork$/u.exec(url.pathname); + if (fork && input.method === "POST") { + forkRequests.push(input); + const result = await chats.fork(deviceId, fork[1]!, input.revision ?? "", input.idempotencyKey ?? "", input.body); + if (dropForkAcks > 0) { + dropForkAcks -= 1; + throw new PeerTransportError("unavailable"); + } + return json(result); + } + const summary = /^\/chats\/([^/]+)\/fork-summary\/(retry|skip|cancel)$/u.exec(url.pathname); + if (summary && input.method === "POST") { + const [, chatId, action] = summary; + if (action === "retry") return json(await chats.retryForkSummary(chatId!)); + if (action === "skip") return json(await chats.skipForkSummary(chatId!)); + return json(await chats.cancelForkSummary(chatId!)); + } + const read = /^\/chats\/(fork-[^/]+)$/u.exec(url.pathname); + if (read && (input.method ?? "GET") === "GET") return json(await chats.get(read[1]!)); + return UNHANDLED; + }; + return { + host, + forks, + forkRequests, + dropNextForkAck: () => { + dropForkAcks += 1; + }, + /** The host's fork store refuses the next fork the way the real one does. */ + failNextFork: (error: ChatForkError) => { + failure = error; + }, + }; +} + +async function open(features?: string[]) { + const fixture = forkingHost(features); + const harness = await setup(fixture.host); + await harness.open(); + const control = (chatId = "chat-1") => { + const next = new ChatSessionControl(harness.adapter, { hostId: harness.adapter.hostId, chatId }, new ChatIntentLedger()); + next.attach(); + return next; + }; + const revision = harness.transcript().transcript.revision ?? undefined; + return { ...fixture, harness, control, revision }; +} + +function code(expected: string) { + return (error: unknown) => error instanceof HostChatControlError && error.code === expected; +} + +/** A refusal the host answered with `expected` as its error code. */ +function remote(expected: string) { + return (error: unknown) => error instanceof HostChatControlError && error.remoteCode === expected; +} + +test("a fork whose answer is lost is retried under the same key and makes one copy on the host", async () => { + const { host, forks, forkRequests, dropNextForkAck, harness, control, revision } = await open(); + try { + const pane = control(); + dropNextForkAck(); + await assert.rejects(pane.fork({ messageId: "a1", position: "after" }, revision), isOutcomeUnknown); + assert.equal(forks.size, 1, "the host made the fork before its answer was lost"); + + const forked = await pane.fork({ messageId: "a1", position: "after" }, revision); + assert.equal(forks.size, 1, "the retry replayed the first fork instead of copying again"); + assert.equal(forked.id, "fork-1"); + assert.equal(forked.title, "Release notes (fork)"); + assert.deepEqual(forked.forkedFrom, { chatId: "chat-1", messageId: "a1", position: "after", at: 5_000 }); + assert.equal(forked.prefill, undefined, "a fork after a reply hands nothing back to edit"); + assert.equal(forkRequests.length, 2); + assert.equal(forkRequests[1]!.idempotencyKey, forkRequests[0]!.idempotencyKey); + assert.equal(forkRequests[0]!.revision, revision); + + // A fork at another message is new work under a new key. + await pane.fork({ messageId: "a2", position: "after" }, revision); + assert.equal(forks.size, 2); + assert.notEqual(forkRequests[2]!.idempotencyKey, forkRequests[0]!.idempotencyKey); + assert.deepEqual(host.chat.messages.map((message) => message.id), ["u1", "a1", "u2", "a2"], "the source is untouched"); + } finally { + harness.close(); + } +}); + +test("a fork against a chat that changed on the host is refused and copies nothing", async () => { + const { host, forks, harness, control, revision } = await open(); + try { + host.append({ id: "u3", role: "user", content: "One more thing", createdAt: 1_500 }); + await assert.rejects(control().fork({ messageId: "a1", position: "after" }, revision), remote("revision_conflict")); + assert.equal(forks.size, 0); + } finally { + harness.close(); + } +}); + +test("editing a prompt in a fork hands its text back and stages its files on the fork", async () => { + const { forks, harness, control, revision } = await open(); + try { + const forked = await control().fork({ messageId: "u2", position: "before" }, revision); + assert.equal(forked.prefill?.text, "Fix it."); + assert.equal(forked.prefill?.attachmentIds.length, 1, "the prompt's file was staged for the fork"); + assert.deepEqual(forked.forkedFrom, { chatId: "chat-1", messageId: "u2", position: "before", at: 5_000 }); + assert.deepEqual( + forks.get(forked.id)?.messages.map((message) => message.content), + ["Why does the build fail?", "A missing token."], + "the fork stops before the prompt being edited", + ); + } finally { + harness.close(); + } +}); + +test("a host without fork support refuses forks before anything is sent", async () => { + const { forkRequests, harness, control, revision } = await open(FEATURES); + try { + assert.equal(harness.adapter.capabilities().has("fork"), false); + await assert.rejects(control().fork({ messageId: "a1", position: "after" }, revision), code("unsupported")); + assert.equal(forkRequests.length, 0); + } finally { + harness.close(); + } +}); + +test("a host that forks but cannot summarize refuses only the summary actions", async () => { + const { forks, forkRequests, harness, control, revision } = await open([...FEATURES, "chat-fork-v1"]); + try { + const pane = control(); + await assert.rejects(pane.fork({ messageId: "a1", position: "after", summary: {} }, revision), code("unsupported")); + assert.equal(forkRequests.length, 0); + + const forked = await pane.fork({ messageId: "a1", position: "after" }, revision); + assert.equal(forks.size, 1); + await assert.rejects(control(forked.id).forkSummary("skip"), code("unsupported")); + await assert.rejects(control(forked.id).cancelForkSummary(), code("unsupported")); + } finally { + harness.close(); + } +}); + +test("a fork with a summary can be cancelled, retried and skipped from the paired Mac", async () => { + const { forks, harness, control, revision } = await open(); + try { + const forked = await control().fork({ messageId: "a1", position: "after", summary: { instructions: "the token" } }, revision); + assert.deepEqual(forked.forkedFrom.summary, { state: "pending", afterMessageId: "fork-1-a1", instructions: "the token" }); + + const fork = control(forked.id); + assert.equal(await fork.cancelForkSummary(), true); + assert.equal(forks.get(forked.id)?.forkedFrom?.summary?.state, "failed"); + assert.equal(await fork.cancelForkSummary(), false, "nothing is running once it stopped"); + + // The fork's own read carries the summary the feed leaves out. + const read = hostResultValue(await harness.adapter.forkLineage(forked.id)); + assert.equal(read.forkedFrom?.summary?.state, "failed"); + assert.equal(read.forkedFrom?.summary?.error, "Stopped."); + + const retried = await fork.forkSummary("retry"); + assert.equal(retried.forkedFrom?.summary?.state, "pending"); + assert.equal(retried.forkedFrom?.summary?.instructions, "the token", "a retry keeps the focus"); + assert.notEqual(retried.revision, read.revision); + + await assert.rejects(fork.forkSummary("skip"), remote("revision_conflict"), "only a failed summary can be skipped"); + await fork.cancelForkSummary(); + const skipped = await fork.forkSummary("skip"); + assert.equal(skipped.forkedFrom?.summary, undefined, "the fork continues as a plain fork"); + assert.equal(forks.get(forked.id)?.forkedFrom?.summary, undefined); + } finally { + harness.close(); + } +}); + +test("the host's refusals reach the pane with their codes and whether waiting helps", async () => { + const { forks, failNextFork, harness, control, revision } = await open(); + try { + failNextFork(new ChatForkError("busy", "A response is still running.")); + await assert.rejects( + control().fork({ messageId: "a1", position: "after" }, revision), + (error: unknown) => remote("operation_in_progress")(error) && (error as HostChatControlError).retryable === true, + ); + + failNextFork(new ChatForkError("unavailable", "Forking is turned off.")); + await assert.rejects( + control().fork({ messageId: "a1", position: "after" }, revision), + (error: unknown) => remote("operation_in_progress")(error) && (error as HostChatControlError).retryable !== true, + ); + + await assert.rejects(control().fork({ messageId: "gone", position: "after" }, revision), remote("not_found")); + assert.equal(forks.size, 0); + + await assert.rejects(control().forkSummary("retry"), remote("not_found"), "a chat that isn't a summarized fork has no summary"); + } finally { + harness.close(); + } +}); diff --git a/main/services/peer-response.ts b/main/services/peer-response.ts index 832f05ee06..99043395b4 100644 --- a/main/services/peer-response.ts +++ b/main/services/peer-response.ts @@ -48,6 +48,10 @@ const operationIds: Record = { updateBotChatAccess: "updateBotChatAccess", uploadAttachment: "uploadChatAttachment", removeAttachment: "removeChatAttachment", + forkChat: "forkChat", + forkSummaryRetry: "chatForkSummaryAction", + forkSummarySkip: "chatForkSummaryAction", + forkSummaryCancel: "chatForkSummaryAction", }; type PeerProtocol = typeof import("../../protocol/aiden-remote/v1/openapi.json"); interface PeerContract { diff --git a/package.json b/package.json index 6a8cd8437e..291462ee2c 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "test:preflight": "npm run test:mcp && npm run test:artificial-analysis && npm run test:model-pad && tsx --test main/services/appearance-preview-core.test.ts main/services/generation-timeline.test.ts main/services/local-runtime-status.test.ts main/services/mcp-tool-result.test.ts main/services/pi-thinking-disclosure.integration.test.ts renderer/components/activity-feed.test.tsx renderer/components/context-meter.test.tsx renderer/components/chat-sidebar.test.tsx renderer/components/composer.test.tsx renderer/components/settings/providers-settings.test.tsx renderer/main/chat-transition.test.tsx renderer/components/reasoning-block.test.tsx renderer/components/reasoning-visibility-control.test.tsx renderer/components/thinking-control.test.tsx renderer/lib/agent-steps.test.ts renderer/lib/button-appearance-contract.test.ts renderer/lib/dialog-motion-contract.test.ts renderer/lib/inline-metadata-hierarchy.test.ts renderer/lib/scrollbar-gutter-contract.test.ts renderer/lib/scroll-follow.test.ts renderer/lib/text-entry-focus-contract.test.ts renderer/lib/pill-appearance.test.ts renderer/lib/reasoning-disclosure.test.ts renderer/lib/streaming-motion-contract.test.ts renderer/lib/streaming-reveal.test.ts renderer/lib/voice-recorder-core.test.ts renderer/lib/media-recorder-stop.test.ts renderer/lib/dictation-vad.test.ts renderer/lib/dictation-sounds.test.ts renderer/pill-preload-channels.test.ts renderer/shared/anthropic-thinking.test.ts renderer/shared/app-update.test.ts renderer/shared/claim-check.test.ts renderer/shared/codex-thinking.test.ts renderer/shared/context-pressure.test.ts renderer/shared/google-thinking.test.ts renderer/shared/provider-deployment.test.ts renderer/shared/assistant-turn-stats.test.ts renderer/lib/sticky-section.test.ts", "test:chat-row-states": "tsx --test renderer/shared/chat-row-state.test.ts renderer/components/chat-row-status.test.tsx renderer/lib/use-mark-chat-read.test.ts main/services/chat-read-markers.test.ts", "test:sidebar": "tsx --test renderer/components/chat-sidebar.test.tsx renderer/lib/sidebar-workspace-groups.test.ts renderer/lib/sidebar-chat-shortcuts.test.ts renderer/lib/held-modifier-reveal.test.ts renderer/lib/sidebar-organization.test.ts renderer/components/sidebar-organize-menu.test.tsx renderer/components/sidebar-remote.test.tsx renderer/lib/sidebar-remote-groups.test.ts renderer/lib/hosts/peer-host-feed-state.test.ts renderer/lib/hosts/use-peer-host-sidebar.test.tsx", - "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx main/services/peer-remote-new-chat.test.ts", + "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts", "test:peer-hosts": "tsx --test main/services/peer-host-registry.test.ts main/services/peer-transport.test.ts main/services/peer-operation.test.ts main/services/peer-host-feed-cache.test.ts main/services/peer-run-subscriptions.test.ts main/services/peer-host-manager.test.ts main/handlers/peer-host-live.test.ts main/services/peer-bootstrap-transport.test.ts main/services/peer-host-pairing.test.ts main/services/peer-pairing-client.test.ts main/services/peer-discovery.test.ts main/handlers/peer-pairing.test.ts main/services/peer-lan-addresses.test.ts main/services/peer-multi-host-acceptance.test.ts", "pretest:aiden-remote": "npm run build:worktree-file-io", "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/repository-identity.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs && tsx --test renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx", diff --git a/renderer/components/message-list.tsx b/renderer/components/message-list.tsx index dcb76b22fb..7028eb5fe8 100644 --- a/renderer/components/message-list.tsx +++ b/renderer/components/message-list.tsx @@ -76,6 +76,11 @@ interface MessageListProps { onForkWithSummary?: (messageId: string, position: ChatForkPosition) => void; /** This fork's summary card, placed after the last copied message. */ forkSummary?: { afterMessageId: string; node: React.ReactNode }; + /** + * False where nothing comes before the first prompt shown, and editing it + * in a fork is refused (a paired Mac's chat): that prompt offers no fork. + */ + forkBeforeFirstPrompt?: boolean; } interface AssistantResponseProps { @@ -358,6 +363,7 @@ export function MessageList({ forkDisabledReason = null, onForkWithSummary, forkSummary, + forkBeforeFirstPrompt = true, }: MessageListProps) { const onForkRef = React.useRef(onFork); const onForkWithSummaryRef = React.useRef(onForkWithSummary); @@ -499,6 +505,8 @@ export function MessageList({ const transcriptRows: React.ReactNode[] = []; const summaryRows = forkWithSummaryEnabled ? forkSummaryRows(messages) : null; + const unforkablePromptId = + forkEnabled && !forkBeforeFirstPrompt ? messages.find((message) => message.role === "user")?.id : undefined; for (const message of messages) { transcriptRows.push( , diff --git a/renderer/lib/hosts/chat-session-control.ts b/renderer/lib/hosts/chat-session-control.ts index 3ebc89a4a7..a68b5888e5 100644 --- a/renderer/lib/hosts/chat-session-control.ts +++ b/renderer/lib/hosts/chat-session-control.ts @@ -10,10 +10,13 @@ import { type HostChatApprovalResult, type HostChatAttachmentUpload, type HostChatCapability, + type HostChatForkInput, + type HostChatLineage, type HostChatQuestionInput, type HostChatQuestionResult, type HostChatStatus, type HostChatTurnReceipt, + type HostForkedChat, } from "./host-chat-adapter"; /** The chat a session is bound to, fixed for the session's lifetime. */ @@ -84,6 +87,8 @@ const UNSUPPORTED_REASON: Partial> = { browseFolders: "That Mac doesn't allow browsing its folders from here.", createWorkspace: "That Mac doesn't allow new projects from here.", botChats: "That Mac doesn't allow Bot chats from here.", + fork: "That Mac doesn't allow forking from here.", + forkSummary: "That Mac doesn't allow fork summaries from here.", }; /** What a turn carries besides its text. */ @@ -161,6 +166,8 @@ export class ChatSessionControl { private offStatus: (() => void) | null = null; private offLedger: (() => void) | null = null; private attached = false; + /** The key of a fork whose answer was lost, reused when the same fork is asked for again. */ + private pendingFork: { signature: string; key: string } | null = null; constructor(adapter: HostChatAdapter, ref: ChatSessionRef, ledger: ChatIntentLedger = chatIntentLedger) { if (adapter.hostId !== ref.hostId) throw new Error("The adapter belongs to another host."); @@ -449,6 +456,43 @@ export class ChatSessionControl { return this.adapter.remove(this.ref.chatId, revision ? { revision } : {}); } + /** + * Forks this chat on its host. When the host's answer is lost, the key is + * kept: asking for the same fork again returns the one the host already + * made instead of a second copy. + */ + async fork(input: Omit, revision?: string): Promise { + this.guard(input.summary ? "forkSummary" : "fork"); + if (!this.adapter.fork) throw new HostChatControlError({ code: "unsupported", message: UNSUPPORTED_REASON.fork! }); + if (!revision) throw new HostChatControlError({ code: "invalid", message: "Load the chat before forking it." }); + // The host fingerprints the body and the revision together with the key. + const signature = JSON.stringify([input.messageId, input.position, input.summary ?? null, revision]); + const key = this.pendingFork?.signature === signature ? this.pendingFork.key : mintPeerIdempotencyKey(); + this.pendingFork = { signature, key }; + try { + const forked = await this.adapter.fork(this.ref.chatId, { ...input, revision, idempotencyKey: key }); + if (this.pendingFork?.key === key) this.pendingFork = null; + return forked; + } catch (error) { + if (!isOutcomeUnknown(error) && this.pendingFork?.key === key) this.pendingFork = null; + throw error; + } + } + + /** Retries or skips this fork's summary. */ + async forkSummary(action: "retry" | "skip"): Promise { + this.guard("forkSummary"); + if (!this.adapter.forkSummary) throw new HostChatControlError({ code: "unsupported", message: UNSUPPORTED_REASON.forkSummary! }); + return this.adapter.forkSummary(this.ref.chatId, action); + } + + /** Stops this fork's pending summary; false when it had already settled. */ + async cancelForkSummary(): Promise { + this.guard("forkSummary"); + if (!this.adapter.cancelForkSummary) throw new HostChatControlError({ code: "unsupported", message: UNSUPPORTED_REASON.forkSummary! }); + return this.adapter.cancelForkSummary(this.ref.chatId); + } + dismissElsewhere(): void { this.update({ elsewhere: null }); } diff --git a/renderer/lib/hosts/host-chat-adapter.ts b/renderer/lib/hosts/host-chat-adapter.ts index 3bf835656b..b2d8890f5d 100644 --- a/renderer/lib/hosts/host-chat-adapter.ts +++ b/renderer/lib/hosts/host-chat-adapter.ts @@ -1,4 +1,5 @@ import type { AskUserQuestionAnswerStatus, AskUserQuestionResponseV1 } from "../../shared/ask-user-question"; +import type { ChatForkLineageV1, ChatForkPosition } from "../../shared/chat-copy-contract"; import type { ChatRunInputAdmissionResult, ChatRunInputMode } from "../../shared/chat-run-input"; import type { PeerBlockedReason, @@ -36,6 +37,10 @@ export type HostChatCapability = | "attach" /** Read the host's skill catalog and invoke a skill with a turn. */ | "skills" + /** Fork a chat at a settled reply, or just before a prompt to edit it. */ + | "fork" + /** Fork with summary, and retry, skip or cancel a fork's summary. */ + | "forkSummary" // Host-wide: starting new work on the host. | "createChat" | "browseFolders" @@ -157,6 +162,34 @@ export interface HostChatRenameInput { revision?: string; } +export interface HostChatForkInput { + messageId: string; + position: ChatForkPosition; + /** Fork with summary: the host summarizes what the fork leaves out. */ + summary?: { instructions?: string }; + /** The source chat's revision; a paired host refuses a fork of an older one. */ + revision: string; + /** Minted once per fork intent and reused by a retry, so a lost answer never makes a second fork. */ + idempotencyKey: string; +} + +export interface HostForkedChat { + id: string; + title: string; + forkedFrom: ChatForkLineageV1; + /** + * A fork before a prompt hands the prompt back for editing. The attachments + * are staged on the host under these IDs. + */ + prefill?: { text: string; attachmentIds: string[] }; +} + +/** A chat's fork lineage, read with the revision it belongs to. */ +export interface HostChatLineage { + revision: string; + forkedFrom?: ChatForkLineageV1; +} + /** * Why a control call failed. `outcome_unknown` means the request may or may * not have been applied: retry it with the same idempotency key, never a new @@ -223,6 +256,17 @@ export interface HostChatAdapter { uploadAttachment?(chatId: string, upload: HostChatAttachmentUpload): Promise; /** Drops a staged attachment no turn will use. */ removeAttachment?(chatId: string, attachmentId: string): Promise; + /** + * Copies the chat into a new one on the same host. The local pane forks + * through `chatsApi` directly, so only a paired host's adapter has these. + */ + fork?(chatId: string, input: HostChatForkInput): Promise; + /** Retries or skips a fork's failed or pending summary; resolves to the fork's new lineage. */ + forkSummary?(chatId: string, action: "retry" | "skip"): Promise; + /** Stops a pending summary. Resolves false when it had already settled. */ + cancelForkSummary?(chatId: string): Promise; + /** Reads the chat's lineage, including its summary, which list rows leave out. */ + forkLineage?(chatId: string): Promise>; dispose(): void; } diff --git a/renderer/lib/hosts/host-query-keys.ts b/renderer/lib/hosts/host-query-keys.ts index 4cf801499e..eae34439bb 100644 --- a/renderer/lib/hosts/host-query-keys.ts +++ b/renderer/lib/hosts/host-query-keys.ts @@ -17,6 +17,8 @@ export const hostQueryKeys = { /** The open remote chat's paged transcript (newest window plus older pages). */ messagesWindow: (hostId: string, chatId: string) => ["host", hostId, "chat", chatId, "messages"] as const, + /** A forked chat's lineage with its summary, which feed rows leave out. */ + forkLineage: (hostId: string, chatId: string) => ["host", hostId, "chat", chatId, "fork-lineage"] as const, /** The skills one chat on one host may invoke. */ skills: (hostId: string, chatId: string) => ["host", hostId, "chat", chatId, "skills"] as const, /** The models a host offers for new chats. */ diff --git a/renderer/lib/hosts/local-host-adapter.ts b/renderer/lib/hosts/local-host-adapter.ts index a96334d664..674ad1957e 100644 --- a/renderer/lib/hosts/local-host-adapter.ts +++ b/renderer/lib/hosts/local-host-adapter.ts @@ -58,6 +58,7 @@ const LOCAL_CAPABILITIES: ReadonlySet = new Set text(record(attachment).id)); + if (attachmentIds.some((attachmentId) => !attachmentId)) throw new Error("The host's fork prefill was incomplete."); + return { ...forked, prefill: { text: prefill.text, attachmentIds: attachmentIds as string[] } }; +} + /** * `HostChatAdapter` for a paired host, over the peer IPC. It never holds or * sees host credentials; main signs and sends every request. @@ -404,6 +443,49 @@ export class RemoteHostAdapter implements HostChatAdapter { await this.mutate("attach", { operation: "removeAttachment", resourceId: chatId, itemId: attachmentId }); } + async fork(chatId: string, input: HostChatForkInput): Promise { + const summary = input.summary + ? { summary: input.summary.instructions ? { instructions: input.summary.instructions } : {} } + : {}; + // A summary fork needs the summary feature too; a plain fork does not. + const value = await this.guarded(chatId, () => + this.mutate(input.summary ? "forkSummary" : "fork", { + operation: "forkChat", + resourceId: chatId, + body: { messageId: input.messageId, position: input.position, ...summary }, + revision: input.revision, + idempotencyKey: input.idempotencyKey, + }), + ); + // A fork leaves its source untouched, so the open transcript stays current. + return this.shaped(value, mapHostForkedChat); + } + + async forkSummary(chatId: string, action: "retry" | "skip"): Promise { + const value = await this.guarded(chatId, () => + this.mutate("forkSummary", { + operation: action === "retry" ? "forkSummaryRetry" : "forkSummarySkip", + resourceId: chatId, + body: {}, + }), + ); + this.chatChanged(chatId); + return this.shaped(value, mapHostChatLineage); + } + + async cancelForkSummary(chatId: string): Promise { + const value = await this.guarded(chatId, () => + this.mutate("forkSummary", { operation: "forkSummaryCancel", resourceId: chatId, body: {} }), + ); + this.chatChanged(chatId); + return record(value).cancelled === true; + } + + /** The chat's lineage with its summary. It reads the whole chat, so a very long one may not fit the response cap. */ + forkLineage(chatId: string): Promise> { + return this.read("messagesWindow", { operation: "chat", resourceId: chatId }, mapHostChatLineage); + } + /** Runs a read the host must grant first, dropping its answer when the connection moved on. */ private read(capability: HostChatCapability, operation: PeerOperation, map: (value: unknown) => T): Promise> { if (!this.granted.has(capability)) diff --git a/renderer/main/remote-chat-view.test.tsx b/renderer/main/remote-chat-view.test.tsx index 0142ad012f..12ce0c167b 100644 --- a/renderer/main/remote-chat-view.test.tsx +++ b/renderer/main/remote-chat-view.test.tsx @@ -22,7 +22,13 @@ import type { SidebarHost } from "../lib/sidebar-remote-groups"; import type { RemoteChatSnapshot } from "../lib/hosts/remote-chat-session"; import { applyRemoteRunEvents, initialRemoteRunView, type RemoteRunView } from "../lib/hosts/remote-stream-translator"; import type { ChatRunInputAdmissionResult } from "../shared/chat-run-input"; -import { RemoteChatPane, RemoteChatRoute, remoteComposerActions, type RemoteChatPaneProps } from "./remote-chat-view"; +import { + RemoteChatPane, + RemoteChatRoute, + remoteComposerActions, + remoteForkErrorMessage, + type RemoteChatPaneProps, +} from "./remote-chat-view"; const noop = () => undefined; const reconnect = async () => undefined; @@ -545,3 +551,101 @@ test("a remote chat whose Mac is unpaired, turned off or unreadable says so once assert.match(failed, /Paired Macs could not be read/); assert.match(failed, /Keychain locked/); }); + +const FORKING: HostChatCapability[] = [...RUN_CONTROL, "fork", "forkSummary"]; + +function forkActions(view: ReturnType, label: string) { + return view.buttons.filter((node) => node.getAttribute("aria-label") === label); +} + +test("a listed chat on a Mac that forks offers Fork from here on replies and Edit in fork past the first prompt", () => { + const forkable = render({ host: online, snapshot: snapshot(online), chat: session(online, FORKING).chat(), forkable: true }); + assert.equal(forkActions(forkable, "Fork from here").length, 1, "the settled reply forks after itself"); + assert.equal(forkActions(forkable, "Edit in fork").length, 0, "the host can't fork before a chat's first prompt"); + + // With older messages above, the oldest prompt shown isn't the chat's first. + const paged = snapshot(online, { transcript: { chatId: "chat-1", revision: "r1", messages, hasOlder: true } }); + const older = render({ host: online, snapshot: paged, chat: session(online, FORKING).chat(), forkable: true }); + assert.equal(forkActions(older, "Edit in fork").length, 1); + assert.equal(forkActions(older, "Fork from here")[0]?.hasAttribute("aria-disabled"), false); + + // Bot chats are never listed; a host without the feature offers nothing. + const unlisted = render({ host: online, snapshot: snapshot(online), chat: session(online, FORKING).chat() }); + assert.equal(forkActions(unlisted, "Fork from here").length, 0); + const plain = render({ host: online, snapshot: snapshot(online), chat: session(online).chat(), forkable: true }); + assert.equal(forkActions(plain, "Fork from here").length, 0); +}); + +test("forking waits while a run on the host is still going", () => { + const live = run([event(1, "run.started", { runId: "run-1", chatId: "chat-1", origin: "device" })]); + const view = render({ + host: online, + snapshot: snapshot(online, { run: live }), + chat: session(online, FORKING).chat(), + forkable: true, + }); + const fork = forkActions(view, "Fork from here")[0]; + assert.equal(fork?.getAttribute("aria-disabled"), "true"); + assert.equal(fork?.getAttribute("title"), "Finish the current response or approval before forking"); +}); + +test("a fork shows where it came from, and a pending summary holds the composer", () => { + const view = render({ + host: online, + snapshot: snapshot(online), + chat: session(online, FORKING).chat(), + forkable: true, + onOpenChat: noop, + lineage: { + forkedFrom: { + chatId: "chat-0", + messageId: "m9", + position: "after", + at: 1, + summary: { state: "pending", afterMessageId: "m2", instructions: "the parser" }, + }, + sourceTitle: "Release plan", + }, + }); + assert.ok(view.button(/Forked from “Release plan”/), "the source opens from the lineage row"); + assert.match(view.text, /Summarizing the original chat…/); + assert.ok(view.markup.indexOf('data-fork-summary="pending"') > view.markup.indexOf("Here is the summary so far")); + assert.match(view.text, /This fork is waiting for its summary\./); + assert.ok(view.button(/Send message/)?.hasAttribute("disabled")); + + const unlistedSource = render({ + host: online, + snapshot: snapshot(online), + chat: session(online, FORKING).chat(), + lineage: { forkedFrom: { chatId: "chat-0", messageId: "m9", position: "after", at: 1 } }, + }); + assert.match(unlistedSource.text, /Forked from another chat/); + assert.equal(unlistedSource.button(/Forked from/), undefined, "a source the host doesn't list can't be opened"); + assert.doesNotMatch(unlistedSource.text, /waiting for its summary/); +}); + +test("a failed remote fork says what to do next", () => { + assert.match( + remoteForkErrorMessage(new HostChatControlError({ code: "outcome_unknown", message: "lost" }), "Studio"), + /Studio didn't confirm the fork\. Fork again to check; it won't make a second copy\./, + ); + assert.equal( + remoteForkErrorMessage( + new HostChatControlError({ code: "failed", message: "busy", remoteCode: "operation_in_progress", retryable: true }), + "Studio", + ), + "Finish the current response or approval before copying this chat.", + ); + assert.equal( + remoteForkErrorMessage( + new HostChatControlError({ code: "failed", message: "Forking is turned off.", remoteCode: "operation_in_progress" }), + "Studio", + ), + "Forking is turned off.", + "a fork the host won't make at all isn't blamed on a running response", + ); + assert.match( + remoteForkErrorMessage(new HostChatControlError({ code: "failed", message: "x", remoteCode: "revision_conflict" }), "Studio"), + /This chat changed on Studio\./, + ); +}); diff --git a/renderer/main/remote-chat-view.tsx b/renderer/main/remote-chat-view.tsx index 5cf39ebf40..5e8b6b4f3e 100644 --- a/renderer/main/remote-chat-view.tsx +++ b/renderer/main/remote-chat-view.tsx @@ -1,10 +1,11 @@ import * as React from "react"; import { skipToken, useQuery, useQueryClient } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; -import { Info, Loader2, MessageCircleQuestion, MoreHorizontal, ShieldQuestion, TriangleAlert } from "lucide-react"; +import { GitFork, Info, Loader2, MessageCircleQuestion, MoreHorizontal, ShieldQuestion, TriangleAlert } from "lucide-react"; import { AskUserQuestionComposer } from "../components/ask-user-question-composer"; import { ChatApprovalCard, toolLabel, type ChatApprovalDecisionOptions } from "../components/chat-approval-card"; import { Composer, type ComposerSkillCatalog } from "../components/composer"; +import { ForkSummaryCard, ForkSummaryDialog } from "../components/fork-summary-card"; import { MessageList } from "../components/message-list"; import { RemoteHostMarker, RemoteHostStatusRow } from "../components/sidebar-remote"; import { @@ -22,13 +23,20 @@ import { toast, } from "../components/ui"; import { peerHostsApi, type ApprovalPrompt } from "../lib/ipc"; -import type { ChatSessionControl, ChatSessionSnapshot } from "../lib/hosts/chat-session-control"; +import { forkedFromLabel } from "../lib/chat-copy-view"; +import { saveComposerDraftText } from "../lib/composer-draft-store"; +import { releaseAttachments, type ChatSessionControl, type ChatSessionSnapshot } from "../lib/hosts/chat-session-control"; import { composerSurfacesFor } from "../lib/hosts/composer-surfaces"; import { animationFrame } from "../lib/hosts/frame-scheduler"; -import { hostResultValue, isOutcomeUnknown } from "../lib/hosts/host-chat-adapter"; +import { + HostChatControlError, + hostResultValue, + isOutcomeUnknown, + type HostChatLineage, +} from "../lib/hosts/host-chat-adapter"; import { remoteAttachmentUploads } from "../lib/hosts/remote-attachments"; import { hostQueryKeys } from "../lib/hosts/host-query-keys"; -import { RemoteHostAdapter } from "../lib/hosts/remote-host-adapter"; +import { mapHostForkLineage, RemoteHostAdapter } from "../lib/hosts/remote-host-adapter"; import type { RemoteTranscript } from "../lib/hosts/remote-chat-mapper"; import { RemoteChatSession, type RemoteChatSnapshot } from "../lib/hosts/remote-chat-session"; import { remoteRunTranscript } from "../lib/hosts/remote-stream-translator"; @@ -36,6 +44,12 @@ import { useChatSession, type ChatSession } from "../lib/hosts/use-chat-session" import { sidebarHosts, type SidebarHost } from "../lib/sidebar-remote-groups"; import type { Attachment } from "../lib/types"; import type { AskUserQuestionPromptV1, AskUserQuestionResponseV1 } from "../shared/ask-user-question"; +import { + FORK_SUMMARY_HOLD_MESSAGE, + forkSummaryHoldsSend, + type ChatForkLineageV1, + type ChatForkPosition, +} from "../shared/chat-copy-contract"; import type { ChatRunInputMode, ChatRunInputRejectionReason } from "../shared/chat-run-input"; import { hostResourceKey, type PeerHostFeedSnapshot, type PeerHostStatus, type PeerHostView } from "../shared/peer-host"; import type { SkillInvocationV1 } from "../shared/slash-commands"; @@ -157,6 +171,21 @@ function reportControlError(control: ChatSessionControl, error: unknown, fallbac toast.error(error instanceof Error ? error.message : fallback); } +/** Why a fork on a paired Mac failed, worded like a local fork's failure. */ +export function remoteForkErrorMessage(error: unknown, hostLabel: string): string { + if (isOutcomeUnknown(error)) { + return `${hostLabel} didn't confirm the fork. Fork again to check; it won't make a second copy.`; + } + if (error instanceof HostChatControlError) { + // The source is mid-run or waiting on an approval on that Mac. + if (error.remoteCode === "operation_in_progress" && error.retryable) { + return "Finish the current response or approval before copying this chat."; + } + if (error.remoteCode === "revision_conflict") return `This chat changed on ${hostLabel}. Try forking again.`; + } + return error instanceof Error && error.message ? error.message : "Couldn't fork this chat."; +} + function ReadOnlyApprovalCard({ prompt, reason }: { prompt: ApprovalPrompt; reason: string }) { const titleId = `remote-approval-title-${prompt.approvalId}`; return ( @@ -260,6 +289,23 @@ export interface RemoteChatPaneProps { onRemoved(): void; /** The skills this chat's host offers after `$`; absent when it grants none. */ hostSkills?: ComposerSkillCatalog; + /** + * True when the host's chat list includes this chat. Bot chats are never + * listed and can't be forked on a paired Mac, so only listed chats fork. + */ + forkable?: boolean; + /** Where this chat was forked from, when it is a fork. */ + lineage?: RemoteChatLineage; + /** Opens another chat on the same host: a new fork, or a fork's source. */ + onOpenChat?(chatId: string): void; + /** A summary action answered with the fork's new lineage. */ + onLineageChange?(lineage: HostChatLineage): void; +} + +export interface RemoteChatLineage { + forkedFrom: ChatForkLineageV1; + /** The source chat's title, while the host still lists it. */ + sourceTitle?: string; } /** The remote chat's presentation; all state arrives in `snapshot` and `chat`. */ @@ -273,6 +319,10 @@ export function RemoteChatPane({ onManage, onRemoved, hostSkills, + forkable = false, + lineage, + onOpenChat, + onLineageChange, }: RemoteChatPaneProps) { const messages = snapshot?.transcript.messages ?? []; const run = snapshot?.run; @@ -371,6 +421,91 @@ export function RemoteChatPane({ } }; + const [forking, setForking] = React.useState(false); + const [forkSummaryRequest, setForkSummaryRequest] = React.useState<{ + messageId: string; + position: ChatForkPosition; + } | null>(null); + const [forkSummaryBusy, setForkSummaryBusy] = React.useState(false); + const forkOffered = forkable && Boolean(capabilities?.has("fork")); + const forkWithSummaryOffered = forkOffered && Boolean(capabilities?.has("forkSummary")); + const forkDisabledReason = + runId !== null || state?.sending + ? "Finish the current response or approval before forking" + : forking + ? "A fork is already being made" + : refusal("fork"); + + /** + * Forks on the host and opens the fork. `before` hands the prompt back as + * the fork's draft. The composer can't show uploads already staged on the + * host, so only the prompt's text comes back; its staged attachments are + * released and the user is told to attach them again. + */ + const forkAt = async (messageId: string, position: ChatForkPosition, summary?: { instructions?: string }) => { + if (!control) throw new Error(`Connecting to ${host.label}…`); + if (forkDisabledReason) throw new Error(`${forkDisabledReason}.`); + setForking(true); + try { + const forked = await control.fork({ messageId, position, ...(summary ? { summary } : {}) }, revision); + if (forked.prefill) { + saveComposerDraftText(hostResourceKey({ hostId: control.ref.hostId, resourceId: forked.id }), forked.prefill.text); + if (forked.prefill.attachmentIds.length > 0) { + releaseAttachments(control.adapter, forked.id, forked.prefill.attachmentIds); + toast.info("The prompt's attachments weren't copied into the fork. Attach them again before you send."); + } + } + onOpenChat?.(forked.id); + } catch (error) { + throw new Error(remoteForkErrorMessage(error, host.label)); + } finally { + setForking(false); + } + }; + + const forkFromTranscript = (messageId: string, position: ChatForkPosition) => { + void forkAt(messageId, position).then( + () => toast.success(position === "before" ? "Forked — edit your message and send" : "Chat forked"), + (error: unknown) => toast.error(error instanceof Error ? error.message : "Couldn't fork this chat."), + ); + }; + + const forkWithSummary = async (instructions: string | undefined) => { + if (!forkSummaryRequest) return; + const { messageId, position } = forkSummaryRequest; + try { + await forkAt(messageId, position, instructions ? { instructions } : {}); + toast.success( + position === "before" + ? "Forked — Aiden is summarizing the original chat. Edit your message and send" + : "Forked — Aiden is summarizing the original chat", + ); + } catch (error) { + toast.error(error instanceof Error ? error.message : "Couldn't fork this chat."); + throw error; + } + }; + + const forkSummary = lineage?.forkedFrom.summary; + const runForkSummaryAction = async (action: "retry" | "cancel" | "skip") => { + if (!control) return; + setForkSummaryBusy(true); + try { + if (action === "cancel") { + // The host settles the summary as failed once the attempt stops. + if (!(await control.cancelForkSummary())) toast.info("The summary already finished."); + return; + } + onLineageChange?.(await control.forkSummary(action)); + } catch (error) { + toast.error(error instanceof Error ? error.message : "Couldn't update the fork's summary."); + } finally { + setForkSummaryBusy(false); + } + }; + // The host refuses a turn until the fork's summary settles. + const summaryHold = forkSummaryHoldsSend(lineage?.forkedFrom) ? FORK_SUMMARY_HOLD_MESSAGE : null; + const canSend = Boolean(capabilities?.has("send")); const questionAnswerable = Boolean(capabilities?.has("answerQuestion")); const openQuestion = questionAnswerable && questionRefusal === null && runId ? questions[0] : undefined; @@ -393,6 +528,24 @@ export function RemoteChatPane({ {title} + {lineage ? ( + + + ) : null} 0} onSend={send} @@ -628,11 +782,44 @@ export function RemoteChatPane({ onOpenSubagent={noop} agentActivity={row!.agentActivity} error={row!.error ?? snapshot.error} + onFork={forkOffered ? forkFromTranscript : undefined} + forkDisabledReason={forkDisabledReason} + onForkWithSummary={ + forkWithSummaryOffered ? (messageId, position) => setForkSummaryRequest({ messageId, position }) : undefined + } + // The host refuses to edit the chat's first prompt in a fork. + forkBeforeFirstPrompt={snapshot.transcript.hasOlder} + forkSummary={ + forkSummary + ? { + afterMessageId: forkSummary.afterMessageId, + node: ( + void runForkSummaryAction("cancel")} + onRetry={() => void runForkSummaryAction("retry")} + onSkip={() => void runForkSummaryAction("skip")} + /> + ), + } + : undefined + } /> )} + { + if (!open) setForkSummaryRequest(null); + }} + onConfirm={forkWithSummary} + /> + !open && setRenaming(false)} @@ -742,15 +929,83 @@ export function useHostSkills(adapter: RemoteHostAdapter, chatId: string): Compo }; } +/** + * A fork's lineage with its summary. Feed rows carry the lineage without the + * summary, so a listed fork reads its chat once, and again only while a + * pending summary's row moves to a new revision. A chat too large for one + * read keeps the feed's lineage and shows no summary card. + */ +function useRemoteForkLineage( + adapter: RemoteHostAdapter, + chatId: string, + listed: ChatForkLineageV1 | undefined, + rowRevision: string | undefined, +): { forkedFrom?: ChatForkLineageV1; update(lineage: HostChatLineage): void } { + const qc = useQueryClient(); + const key = hostQueryKeys.forkLineage(adapter.hostId, chatId); + const enabled = Boolean(listed) && adapter.capabilities().has("messagesWindow"); + const query = useQuery({ + queryKey: key, + queryFn: async () => hostResultValue(await adapter.forkLineage(chatId)), + enabled, + staleTime: Infinity, + retry: false, + }); + const read = query.data; + const pendingElsewhere = + read?.forkedFrom?.summary?.state === "pending" && rowRevision !== undefined && rowRevision !== read.revision; + React.useEffect(() => { + if (pendingElsewhere) void qc.invalidateQueries({ queryKey: key, exact: true }); + // `key` is rebuilt every render, so its parts are the dependencies. + }, [qc, pendingElsewhere, adapter.hostId, chatId, rowRevision]); + const update = React.useCallback( + (lineage: HostChatLineage) => qc.setQueryData(hostQueryKeys.forkLineage(adapter.hostId, chatId), lineage), + [qc, adapter.hostId, chatId], + ); + const forkedFrom = enabled && read?.forkedFrom ? read.forkedFrom : listed; + return forkedFrom ? { forkedFrom, update } : { update }; +} + /** Binds the pane's session control to this host's adapter and this chat. */ function ControlledRemoteChatPane({ adapter, chatId, + listedLineage, + sourceTitle, + rowRevision, ...props -}: RemoteChatFrameProps & { adapter: RemoteHostAdapter; chatId: string }) { +}: RemoteChatFrameProps & { + adapter: RemoteHostAdapter; + chatId: string; + listedLineage?: ChatForkLineageV1; + sourceTitle?: string; + rowRevision?: string; +}) { const chat = useChatSession(adapter, { hostId: adapter.hostId, chatId }); const hostSkills = useHostSkills(adapter, chatId); - return ; + const fork = useRemoteForkLineage(adapter, chatId, listedLineage, rowRevision); + const lineage: RemoteChatLineage | undefined = fork.forkedFrom + ? { forkedFrom: fork.forkedFrom, ...(sourceTitle !== undefined ? { sourceTitle } : {}) } + : undefined; + return ( + + ); +} + +/** A feed row's lineage, or nothing when the row carries none or a malformed one. */ +function feedRowLineage(row: Record | undefined): ChatForkLineageV1 | undefined { + if (!row?.forkedFrom) return undefined; + try { + return mapHostForkLineage(row.forkedFrom); + } catch { + return undefined; + } } export function RemoteChatView({ hostId, chatId }: { hostId: string; chatId: string }) { @@ -761,7 +1016,15 @@ export function RemoteChatView({ hostId, chatId }: { hostId: string; chatId: str const removed = React.useCallback(() => { void navigate({ to: "/" }); }, [navigate]); - return ; + const openChat = React.useCallback( + (next: string) => { + void navigate({ to: "/host/$hostId/chat/$chatId", params: { hostId, chatId: next } }); + }, + [navigate, hostId], + ); + return ( + + ); } export interface RemoteChatRouteProps { @@ -771,10 +1034,12 @@ export interface RemoteChatRouteProps { onManage(): void; /** Leaves the route after the open chat was deleted. */ onRemoved(): void; + /** Opens another chat on this host: a new fork, or a fork's source. */ + onOpenChat?(chatId: string): void; } /** The remote chat route, fed by the host queries the sidebar keeps current. */ -export function RemoteChatRoute({ hostId, chatId, onManage, onRemoved }: RemoteChatRouteProps) { +export function RemoteChatRoute({ hostId, chatId, onManage, onRemoved, onOpenChat }: RemoteChatRouteProps) { const list = useQuery({ queryKey: hostQueryKeys.list(), queryFn: skipToken }); const statuses = useQuery({ queryKey: hostQueryKeys.statuses(), queryFn: skipToken }); const feed = useQuery({ queryKey: hostQueryKeys.feed(hostId), queryFn: skipToken }); @@ -837,6 +1102,15 @@ export function RemoteChatRoute({ hostId, chatId, onManage, onRemoved }: RemoteC : listed; const summary = feed.data?.summaries.find((row) => row.id === chatId); const title = typeof summary?.title === "string" && summary.title.trim() ? summary.title : "Remote chat"; + const listedLineage = feedRowLineage(summary); + const source = listedLineage ? feed.data?.summaries.find((row) => row.id === listedLineage.chatId) : undefined; + const sourceTitle = + source === undefined + ? undefined + : typeof source.title === "string" && source.title.trim() + ? source.title + : "Remote chat"; + const rowRevision = typeof summary?.revision === "string" ? summary.revision : undefined; const frame: RemoteChatFrameProps = { title, host, @@ -845,10 +1119,20 @@ export function RemoteChatRoute({ hostId, chatId, onManage, onRemoved }: RemoteC onReconnect: reconnect, onManage, onRemoved, + // Bot chats are never listed, and the host refuses to fork them. + forkable: summary !== undefined, + ...(onOpenChat ? { onOpenChat } : {}), }; return binding ? ( - + ) : ( ); diff --git a/renderer/shared/peer-operation.ts b/renderer/shared/peer-operation.ts index cfa4d18046..55ac3ba26c 100644 --- a/renderer/shared/peer-operation.ts +++ b/renderer/shared/peer-operation.ts @@ -44,7 +44,11 @@ export type PeerWriteOperation = | "updateBotFavorites" | "updateBotChatAccess" | "uploadAttachment" - | "removeAttachment"; + | "removeAttachment" + | "forkChat" + | "forkSummaryRetry" + | "forkSummarySkip" + | "forkSummaryCancel"; export interface PeerOperation { operation: PeerReadOperation | PeerWriteOperation; /** The chat, stream, run, Bot or prompt the operation addresses. */ diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index f377ba49a0..af64f84589 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -379,6 +379,7 @@ "main/services/peer-operation.test.ts", "main/services/peer-pairing-client.test.ts", "main/services/peer-remote-chat-control.test.ts", + "main/services/peer-remote-chat-fork.test.ts", "main/services/peer-remote-chat-view.test.ts", "main/services/peer-remote-new-chat.test.ts", "main/services/peer-run-subscriptions.test.ts", From f273a601cd72bcc712c68325b3a69d46dc6dd173 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 14:36:41 -0400 Subject: [PATCH 2/4] fix(peer): send a fork summary's focus under its wire name The Remote contract now calls the summary focus `focus`. The peer bridge sends and validates `summary.focus`, and maps the host's `focus` back to the desktop's `instructions` when it reads fork lineage. Co-Authored-By: Claude Opus 5.5 --- main/services/peer-operation.test.ts | 9 +++++---- main/services/peer-operation.ts | 12 +++++------- main/services/peer-remote-chat-fork.test.ts | 8 ++++---- renderer/lib/hosts/remote-host-adapter.ts | 17 ++++++++++++++--- 4 files changed, 28 insertions(+), 18 deletions(-) diff --git a/main/services/peer-operation.test.ts b/main/services/peer-operation.test.ts index 6c3ae56c1f..a3777c8d10 100644 --- a/main/services/peer-operation.test.ts +++ b/main/services/peer-operation.test.ts @@ -253,15 +253,16 @@ test("a fork without its key, revision or a well-formed cut point never leaves t { ...valid, body: { messageId: "m1", position: "middle" } }, { ...valid, body: { messageId: "../m1", position: "after" } }, { ...valid, body: { messageId: "m1", position: "after", extra: true } }, - { ...valid, body: { messageId: "m1", position: "after", summary: { focus: "x" } } }, - { ...valid, body: { messageId: "m1", position: "after", summary: { instructions: " " } } }, - { ...valid, body: { messageId: "m1", position: "after", summary: { instructions: "x".repeat(1001) } } }, + // The desktop's internal name for the focus is not part of the wire. + { ...valid, body: { messageId: "m1", position: "after", summary: { instructions: "x" } } }, + { ...valid, body: { messageId: "m1", position: "after", summary: { focus: " " } } }, + { ...valid, body: { messageId: "m1", position: "after", summary: { focus: "x".repeat(1001) } } }, { ...valid, resourceId: "../server" }, { operation: "forkSummaryRetry", resourceId: "chat_1", body: { force: true } }, ]) assert.throws(() => peerOperationRequest(invalid), JSON.stringify(invalid)); // At the bound, and with no focus at all, a summary request is accepted. - for (const summary of [{}, { instructions: "x".repeat(1000) }]) + for (const summary of [{}, { focus: "x".repeat(1000) }]) assert.deepEqual( peerOperationRequest({ ...valid, body: { messageId: "m1", position: "after", summary } }).body, { messageId: "m1", position: "after", summary }, diff --git a/main/services/peer-operation.ts b/main/services/peer-operation.ts index 0d6ff475c4..90d770f122 100644 --- a/main/services/peer-operation.ts +++ b/main/services/peer-operation.ts @@ -75,19 +75,17 @@ function forkBody(value: unknown): Record { throw new Error("Invalid peer fork request."); if (body.summary === undefined) return { messageId: body.messageId, position: body.position }; const summary = peerRecord(body.summary); - const instructions = summary.instructions; + const focus = summary.focus; if ( - Object.keys(summary).some((key) => key !== "instructions") || - (instructions !== undefined && - (typeof instructions !== "string" || - !instructions.trim() || - instructions.length > MAX_FORK_SUMMARY_INSTRUCTIONS_CHARS)) + Object.keys(summary).some((key) => key !== "focus") || + (focus !== undefined && + (typeof focus !== "string" || !focus.trim() || focus.length > MAX_FORK_SUMMARY_INSTRUCTIONS_CHARS)) ) throw new Error("Invalid peer fork request."); return { messageId: body.messageId, position: body.position, - summary: instructions === undefined ? {} : { instructions }, + summary: focus === undefined ? {} : { focus }, }; } diff --git a/main/services/peer-remote-chat-fork.test.ts b/main/services/peer-remote-chat-fork.test.ts index fe5f185170..6890f410d7 100644 --- a/main/services/peer-remote-chat-fork.test.ts +++ b/main/services/peer-remote-chat-fork.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { AidenRemoteChatService } from "./aiden-remote-chats.js"; -import { ChatForkError } from "./chat-fork-error.js"; +import { ChatForkError, ForkSummaryStateError } from "./chat-fork-error.js"; import { FakeHost, FEATURES, UNHANDLED, setup } from "./peer-remote-chat-test-host.js"; import { PeerTransportError, type PeerRequest } from "./peer-transport.js"; import { ChatIntentLedger } from "../../renderer/lib/hosts/chat-intent-ledger.js"; @@ -107,7 +107,7 @@ function forkingHost(features = FORK_FEATURES) { skip: async (chatId) => settle(chatId, "failed", ({ summary: _summary, ...lineage }) => lineage), cancel: (chatId) => { if (forks.get(chatId)?.forkedFrom?.summary?.state !== "pending") return false; - void settle(chatId, "pending", (lineage) => ({ ...lineage, summary: { ...lineage.summary!, state: "failed", error: "Stopped." } })); + void settle(chatId, "pending", (lineage) => ({ ...lineage, summary: { ...lineage.summary!, state: "failed", error: "Summary cancelled." } })); return true; }, }, @@ -117,7 +117,7 @@ function forkingHost(features = FORK_FEATURES) { /** Moves a fork's summary on from `from`, or refuses like the real summarizer. */ async function settle(chatId: string, from: "pending" | "failed", next: (lineage: NonNullable) => Chat["forkedFrom"]) { const fork = forks.get(chatId); - if (fork?.forkedFrom?.summary?.state !== from) throw new Error("The fork summary changed."); + if (fork?.forkedFrom?.summary?.state !== from) throw new ForkSummaryStateError("The fork summary changed."); const updated = { ...fork, forkedFrom: next(fork.forkedFrom), updatedAt: fork.updatedAt + 1 }; forks.set(chatId, updated); return updated; @@ -280,7 +280,7 @@ test("a fork with a summary can be cancelled, retried and skipped from the paire // The fork's own read carries the summary the feed leaves out. const read = hostResultValue(await harness.adapter.forkLineage(forked.id)); assert.equal(read.forkedFrom?.summary?.state, "failed"); - assert.equal(read.forkedFrom?.summary?.error, "Stopped."); + assert.equal(read.forkedFrom?.summary?.error, "Summary cancelled."); const retried = await fork.forkSummary("retry"); assert.equal(retried.forkedFrom?.summary?.state, "pending"); diff --git a/renderer/lib/hosts/remote-host-adapter.ts b/renderer/lib/hosts/remote-host-adapter.ts index 790ef6ead1..a7e28010b4 100644 --- a/renderer/lib/hosts/remote-host-adapter.ts +++ b/renderer/lib/hosts/remote-host-adapter.ts @@ -131,11 +131,22 @@ function failure(error: unknown): HostChatError { return { code: "failed", message: error instanceof Error ? error.message : "The host request failed." }; } -/** A host's lineage carries an RFC 3339 time; the chat UI reads epoch milliseconds. */ +/** + * A host's lineage carries an RFC 3339 time and calls the summary's focus + * `focus`; the chat UI reads epoch milliseconds and `instructions`. + */ export function mapHostForkLineage(value: unknown): ChatForkLineageV1 { const lineage = record(value); const at = typeof lineage.at === "string" ? Date.parse(lineage.at) : Number.NaN; - const parsed = Number.isFinite(at) ? parseChatForkLineageV1({ ...lineage, at }) : undefined; + let summary: Record | undefined; + if (lineage.summary !== undefined) { + const { focus, ...rest } = record(lineage.summary); + if ("instructions" in rest) throw new Error("The host's fork lineage was malformed."); + summary = focus === undefined ? rest : { ...rest, instructions: focus }; + } + const parsed = Number.isFinite(at) + ? parseChatForkLineageV1({ ...lineage, at, ...(summary ? { summary } : {}) }) + : undefined; if (!parsed) throw new Error("The host's fork lineage was malformed."); return parsed; } @@ -445,7 +456,7 @@ export class RemoteHostAdapter implements HostChatAdapter { async fork(chatId: string, input: HostChatForkInput): Promise { const summary = input.summary - ? { summary: input.summary.instructions ? { instructions: input.summary.instructions } : {} } + ? { summary: input.summary.instructions ? { focus: input.summary.instructions } : {} } : {}; // A summary fork needs the summary feature too; a plain fork does not. const value = await this.guarded(chatId, () => From 56071b93a790107e564ac6425a05024b4685efb7 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 18:30:14 -0400 Subject: [PATCH 3/4] fix(peer): keep a lost fork's key across panes and follow summaries changed elsewhere A fork whose answer was lost kept its idempotency key only on the pane's session control, so reopening the chat and retrying minted a new key and the host made a second copy. The key now lives in the window's chat intent ledger, scoped to host and chat, like other unresolved chat mutations. The fork lineage read again only while a pending summary's row moved, and compared the feed's metadata token with the chat's content revision. A failed summary retried or skipped on another device stayed failed here and kept the composer held. The lineage now records the feed revision it was read at and reads again whenever that moves while the summary is pending or failed. Co-Authored-By: Claude Opus 5.5 --- .memory/chat-fork.md | 4 +- main/services/peer-remote-chat-fork.test.ts | 15 ++- renderer/lib/hosts/chat-intent-ledger.ts | 35 ++++- renderer/lib/hosts/chat-session-control.ts | 14 +- renderer/main/remote-chat-view.test.tsx | 140 +++++++++++++++++++- renderer/main/remote-chat-view.tsx | 43 ++++-- 6 files changed, 224 insertions(+), 27 deletions(-) diff --git a/.memory/chat-fork.md b/.memory/chat-fork.md index 7a1a4805a0..7e598f1953 100644 --- a/.memory/chat-fork.md +++ b/.memory/chat-fork.md @@ -82,13 +82,13 @@ Plan: `docs/plans/chat-fork-plan.md` (five PRs). This note tracks what has lande - `RemoteHostAdapter` grants `fork` when the host advertises `chat-fork-v1` and `forkSummary` when it also advertises `chat-fork-summary-v1`. Both also need `chat:write`. - `LocalHostAdapter` never grants either: the local pane forks through `chatsApi`. - `forkLineage(chatId)` reads the full chat, because feed rows leave the summary out. -- **Keys.** `ChatSessionControl.fork` keeps the idempotency key for an identical request (same message, position, summary and revision) after an `outcome_unknown`. A retry therefore replays the first fork instead of making a second copy. +- **Keys.** The key of a fork whose answer was lost lives in the window's `chatIntentLedger` (`forkKey`/`beginFork`/`settleFork`, scoped to host + chat), not on the `ChatSessionControl`. Asking for the identical fork (same message, position, summary and revision) from this pane or one reopened on the same chat reuses the original key, so the host replays the first fork instead of making a second copy. The key is cleared on success or a definite refusal and kept only on `outcome_unknown`. A fork entry raises no ledger notification, so it never shows the unresolved banner or holds sending. - **Pane** (`remote-chat-view.tsx`). - Fork is offered only for chats the feed lists (`forkable`). That excludes Bot chats, and also chats beyond the 2000-row feed cap. - Edit in fork is hidden on the first prompt while no older page exists (`MessageList forkBeforeFirstPrompt`). - Forks are disabled while a run has started or a send is in flight. - After a fork the pane opens the new chat. A `before` fork seeds the composer draft with only `prefill.text`. The composer can't show uploads staged on the host, so those are released and the user is told to attach them again. - - The lineage row and `ForkSummaryCard` come from `useRemoteForkLineage`. It runs one full-chat read (best-effort, under the 1 MiB GET cap), and reads again only while a pending summary's feed revision moves. + - The lineage row and `ForkSummaryCard` come from `useRemoteForkLineage`. It runs one full-chat read (best-effort, under the 1 MiB GET cap) and caches `{lineage, feedRevision}`, where `feedRevision` is the feed row revision when the read started. While the summary is pending or failed it reads again whenever the row revision differs from that cached one; it never compares the feed token with the content-hash revision. A retry, skip or ready result from another device therefore replaces a stale failed card and releases the composer hold. - Summary actions write the returned lineage into that query. - A pending or failed summary holds the composer with `FORK_SUMMARY_HOLD_MESSAGE`. - **Tests.** diff --git a/main/services/peer-remote-chat-fork.test.ts b/main/services/peer-remote-chat-fork.test.ts index 6890f410d7..36edc25466 100644 --- a/main/services/peer-remote-chat-fork.test.ts +++ b/main/services/peer-remote-chat-fork.test.ts @@ -165,8 +165,10 @@ async function open(features?: string[]) { const fixture = forkingHost(features); const harness = await setup(fixture.host); await harness.open(); + // One window: every pane opened on a chat shares its intent ledger. + const ledger = new ChatIntentLedger(); const control = (chatId = "chat-1") => { - const next = new ChatSessionControl(harness.adapter, { hostId: harness.adapter.hostId, chatId }, new ChatIntentLedger()); + const next = new ChatSessionControl(harness.adapter, { hostId: harness.adapter.hostId, chatId }, ledger); next.attach(); return next; }; @@ -186,11 +188,14 @@ function remote(expected: string) { test("a fork whose answer is lost is retried under the same key and makes one copy on the host", async () => { const { host, forks, forkRequests, dropNextForkAck, harness, control, revision } = await open(); try { - const pane = control(); + const first = control(); dropNextForkAck(); - await assert.rejects(pane.fork({ messageId: "a1", position: "after" }, revision), isOutcomeUnknown); + await assert.rejects(first.fork({ messageId: "a1", position: "after" }, revision), isOutcomeUnknown); assert.equal(forks.size, 1, "the host made the fork before its answer was lost"); + // The user leaves the chat and comes back: the reopened pane gets a new control. + first.attach()(); + const pane = control(); const forked = await pane.fork({ messageId: "a1", position: "after" }, revision); assert.equal(forks.size, 1, "the retry replayed the first fork instead of copying again"); assert.equal(forked.id, "fork-1"); @@ -205,6 +210,10 @@ test("a fork whose answer is lost is retried under the same key and makes one co await pane.fork({ messageId: "a2", position: "after" }, revision); assert.equal(forks.size, 2); assert.notEqual(forkRequests[2]!.idempotencyKey, forkRequests[0]!.idempotencyKey); + // Once the host answered, the same fork asked for again is a deliberate second copy. + await pane.fork({ messageId: "a1", position: "after" }, revision); + assert.equal(forks.size, 3); + assert.notEqual(forkRequests[3]!.idempotencyKey, forkRequests[0]!.idempotencyKey); assert.deepEqual(host.chat.messages.map((message) => message.id), ["u1", "a1", "u2", "a2"], "the source is untouched"); } finally { harness.close(); diff --git a/renderer/lib/hosts/chat-intent-ledger.ts b/renderer/lib/hosts/chat-intent-ledger.ts index a734730b6b..465cc241d3 100644 --- a/renderer/lib/hosts/chat-intent-ledger.ts +++ b/renderer/lib/hosts/chat-intent-ledger.ts @@ -27,6 +27,17 @@ export interface ChatIntent { replay(adapter: HostChatAdapter, idempotencyKey: string): Promise; } +/** + * A fork whose answer was lost: what it asked for and the key it was sent + * under. Forks don't block the chat the way an unresolved intent does; the + * key is only reused when the same fork is asked for again. + */ +export interface ChatForkIntent { + /** The request the host fingerprints with the key: message, position, summary and revision. */ + signature: string; + idempotencyKey: string; +} + export interface ChatIntentUnresolved { intent: ChatIntent; retrying: boolean; @@ -42,6 +53,7 @@ interface PendingIntent { interface Entry { pending: Map; unresolved: ChatIntentUnresolved | null; + fork: ChatForkIntent | null; } const refKey = ({ hostId, chatId }: ChatIntentRef) => `${hostId}\u0000${chatId}`; @@ -121,6 +133,25 @@ export class ChatIntentLedger { this.changed(ref); } + /** The key of this chat's fork with `signature` whose outcome is still unknown, if any. */ + forkKey(ref: ChatIntentRef, signature: string): string | null { + const fork = this.entries.get(refKey(ref))?.fork; + return fork?.signature === signature ? fork.idempotencyKey : null; + } + + /** Remembers the fork now being sent, replacing any earlier one for this chat. */ + beginFork(ref: ChatIntentRef, fork: ChatForkIntent): void { + this.entry(ref).fork = fork; + } + + /** Forgets the fork sent under `idempotencyKey` once its outcome is known; ignored if it was replaced. */ + settleFork(ref: ChatIntentRef, idempotencyKey: string): void { + const entry = this.entries.get(refKey(ref)); + if (entry?.fork?.idempotencyKey !== idempotencyKey) return; + entry.fork = null; + this.prune(ref, entry); + } + subscribe(ref: ChatIntentRef, listener: () => void): () => void { const key = refKey(ref); const set = this.listeners.get(key) ?? new Set(); @@ -136,14 +167,14 @@ export class ChatIntentLedger { const key = refKey(ref); let entry = this.entries.get(key); if (!entry) { - entry = { pending: new Map(), unresolved: null }; + entry = { pending: new Map(), unresolved: null, fork: null }; this.entries.set(key, entry); } return entry; } private prune(ref: ChatIntentRef, entry: Entry): void { - if (entry.pending.size === 0 && !entry.unresolved) this.entries.delete(refKey(ref)); + if (entry.pending.size === 0 && !entry.unresolved && !entry.fork) this.entries.delete(refKey(ref)); } private changed(ref: ChatIntentRef): void { diff --git a/renderer/lib/hosts/chat-session-control.ts b/renderer/lib/hosts/chat-session-control.ts index a68b5888e5..9e4703ecbd 100644 --- a/renderer/lib/hosts/chat-session-control.ts +++ b/renderer/lib/hosts/chat-session-control.ts @@ -166,8 +166,6 @@ export class ChatSessionControl { private offStatus: (() => void) | null = null; private offLedger: (() => void) | null = null; private attached = false; - /** The key of a fork whose answer was lost, reused when the same fork is asked for again. */ - private pendingFork: { signature: string; key: string } | null = null; constructor(adapter: HostChatAdapter, ref: ChatSessionRef, ledger: ChatIntentLedger = chatIntentLedger) { if (adapter.hostId !== ref.hostId) throw new Error("The adapter belongs to another host."); @@ -458,7 +456,8 @@ export class ChatSessionControl { /** * Forks this chat on its host. When the host's answer is lost, the key is - * kept: asking for the same fork again returns the one the host already + * kept in the window's ledger: asking for the same fork again, from this + * pane or one reopened on the same chat, returns the fork the host already * made instead of a second copy. */ async fork(input: Omit, revision?: string): Promise { @@ -467,14 +466,15 @@ export class ChatSessionControl { if (!revision) throw new HostChatControlError({ code: "invalid", message: "Load the chat before forking it." }); // The host fingerprints the body and the revision together with the key. const signature = JSON.stringify([input.messageId, input.position, input.summary ?? null, revision]); - const key = this.pendingFork?.signature === signature ? this.pendingFork.key : mintPeerIdempotencyKey(); - this.pendingFork = { signature, key }; + const key = this.ledger.forkKey(this.ref, signature) ?? mintPeerIdempotencyKey(); + this.ledger.beginFork(this.ref, { signature, idempotencyKey: key }); try { const forked = await this.adapter.fork(this.ref.chatId, { ...input, revision, idempotencyKey: key }); - if (this.pendingFork?.key === key) this.pendingFork = null; + this.ledger.settleFork(this.ref, key); return forked; } catch (error) { - if (!isOutcomeUnknown(error) && this.pendingFork?.key === key) this.pendingFork = null; + // Only a lost answer keeps the key; a refusal means the host made no fork. + if (!isOutcomeUnknown(error)) this.ledger.settleFork(this.ref, key); throw error; } } diff --git a/renderer/main/remote-chat-view.test.tsx b/renderer/main/remote-chat-view.test.tsx index 12ce0c167b..03624a61c1 100644 --- a/renderer/main/remote-chat-view.test.tsx +++ b/renderer/main/remote-chat-view.test.tsx @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { renderToStaticMarkup } from "react-dom/server"; -import { DOMParser } from "@xmldom/xmldom"; +import { DOMImplementation, DOMParser } from "@xmldom/xmldom"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { CommandSystemProvider } from "../lib/command-system"; import { ChatIntentLedger } from "../lib/hosts/chat-intent-ledger"; @@ -12,6 +12,7 @@ import { type HostChatApprovalResult, type HostChatCapability, type HostChatInput, + type HostChatLineage, type HostChatStatus, } from "../lib/hosts/host-chat-adapter"; import type { ChatSession } from "../lib/hosts/use-chat-session"; @@ -22,11 +23,13 @@ import type { SidebarHost } from "../lib/sidebar-remote-groups"; import type { RemoteChatSnapshot } from "../lib/hosts/remote-chat-session"; import { applyRemoteRunEvents, initialRemoteRunView, type RemoteRunView } from "../lib/hosts/remote-stream-translator"; import type { ChatRunInputAdmissionResult } from "../shared/chat-run-input"; +import type { ChatForkLineageV1, ChatForkSummaryV1 } from "../shared/chat-copy-contract"; import { RemoteChatPane, RemoteChatRoute, remoteComposerActions, remoteForkErrorMessage, + useRemoteForkLineage, type RemoteChatPaneProps, } from "./remote-chat-view"; @@ -649,3 +652,138 @@ test("a failed remote fork says what to do next", () => { /This chat changed on Studio\./, ); }); + +/** A minimal document for react-dom; the lineage harness renders nothing itself. */ +function installDocument() { + const document = new DOMImplementation().createDocument(null, "html", null) as unknown as Document; + const container = document.createElement("div"); + document.documentElement.appendChild(container); + const elementPrototype = Object.getPrototypeOf(container) as Record; + elementPrototype.addEventListener = noop; + elementPrototype.removeEventListener = noop; + Object.defineProperty(elementPrototype, "style", { configurable: true, get: () => ({}) }); + const documentPrototype = Object.getPrototypeOf(document) as Record; + documentPrototype.addEventListener = noop; + documentPrototype.removeEventListener = noop; + const windowValue = { + document, + event: undefined, + HTMLIFrameElement: class HTMLIFrameElement {}, + addEventListener: noop, + removeEventListener: noop, + }; + Object.defineProperty(document, "defaultView", { configurable: true, value: windowValue }); + const keys = ["window", "document", "navigator", "Node", "Element", "HTMLElement"] as const; + const previous = new Map(keys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); + const ElementConstructor = Object.getPrototypeOf(document.documentElement).constructor; + Object.defineProperties(globalThis, { + window: { configurable: true, value: windowValue }, + document: { configurable: true, value: document }, + navigator: { configurable: true, value: { userAgent: "remote-chat-view-test" } }, + Node: { configurable: true, value: ElementConstructor }, + Element: { configurable: true, value: ElementConstructor }, + HTMLElement: { configurable: true, value: ElementConstructor }, + }); + return { + container, + restore() { + for (const key of keys) { + const descriptor = previous.get(key); + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; +} + +/** Lets the read, the query cache's batched notifications and React's renders land. */ +async function settle(): Promise { + for (let step = 0; step < 10; step += 1) { + await new Promise((resolve) => setTimeout(resolve, 0)); + await new Promise((resolve) => setImmediate(resolve)); + } +} + +test("a fork's summary changed on another device reaches the open pane when its feed row moves", async () => { + const listed: ChatForkLineageV1 = { chatId: "chat-0", messageId: "m9", position: "after", at: 1 }; + const failed: ChatForkSummaryV1 = { state: "failed", afterMessageId: "m2", error: "The model was unavailable." }; + // The host's copy of the fork; each read returns its lineage under a content revision. + let summary: ChatForkSummaryV1 | undefined = failed; + let reads = 0; + const host = { + hostId: "host-b", + capabilities: () => new Set(["messagesWindow"]), + async forkLineage(): Promise<{ ok: true; value: HostChatLineage }> { + reads += 1; + return { ok: true, value: { revision: `content-${reads}`, forkedFrom: { ...listed, ...(summary ? { summary } : {}) } } }; + }, + }; + let latest: ReturnType = { update: noop }; + function Harness({ rowRevision }: { rowRevision: string }) { + latest = useRemoteForkLineage(host, "chat-1", listed, rowRevision); + return null; + } + + const dom = installDocument(); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const { createRoot } = await import("react-dom/client"); + const { flushSync } = await import("react-dom"); + const root = createRoot(dom.container); + const show = async (rowRevision: string) => { + root.render( + + + , + ); + await settle(); + return latest.forkedFrom; + }; + const seen: Array = []; + try { + seen.push(await show("rev_1")); + assert.equal(reads, 1); + assert.equal(seen[0]?.summary?.state, "failed"); + await show("rev_1"); + assert.equal(reads, 1, "a render without a feed change reads nothing"); + + // Another device retries the summary: the host's row moves. + summary = { state: "pending", afterMessageId: "m2" }; + seen.push(await show("rev_2")); + assert.equal(seen[1]?.summary?.state, "pending"); + assert.equal(reads, 2); + + // The retry fails again, then another device continues without the summary. + summary = failed; + seen.push(await show("rev_3")); + assert.equal(seen[2]?.summary?.state, "failed"); + summary = undefined; + seen.push(await show("rev_4")); + assert.equal(seen[3]?.summary, undefined, "the skipped summary is gone from the lineage"); + assert.equal(reads, 4); + + // With nothing left to settle, later row changes don't read the chat again. + await show("rev_5"); + assert.equal(reads, 4); + } finally { + flushSync(() => root.unmount()); + client.clear(); + await settle(); + dom.restore(); + } + + const pane = (forkedFrom: ChatForkLineageV1 | undefined) => + render({ + host: online, + snapshot: snapshot(online), + chat: session(online, FORKING).chat(), + ...(forkedFrom ? { lineage: { forkedFrom } } : {}), + }); + const [stale, retried, , skipped] = seen.map(pane); + assert.ok(stale!.button(/^Retry$/), "the failed summary offers Retry"); + assert.match(stale!.text, /This fork is waiting for its summary\./); + assert.match(retried!.text, /Summarizing the original chat…/); + assert.equal(retried!.button(/^Retry$/), undefined, "the stale Retry is gone once the summary is pending again"); + assert.match(retried!.text, /This fork is waiting for its summary\./); + assert.doesNotMatch(skipped!.markup, /data-fork-summary/); + assert.doesNotMatch(skipped!.text, /waiting for its summary/, "the composer is no longer held"); +}); diff --git a/renderer/main/remote-chat-view.tsx b/renderer/main/remote-chat-view.tsx index 5e8b6b4f3e..6c38c85acb 100644 --- a/renderer/main/remote-chat-view.tsx +++ b/renderer/main/remote-chat-view.tsx @@ -929,14 +929,22 @@ export function useHostSkills(adapter: RemoteHostAdapter, chatId: string): Compo }; } +/** A fork's lineage, with the feed revision its row had when the read started. */ +interface ForkLineageRead { + lineage: HostChatLineage; + feedRevision: string | undefined; +} + /** * A fork's lineage with its summary. Feed rows carry the lineage without the - * summary, so a listed fork reads its chat once, and again only while a - * pending summary's row moves to a new revision. A chat too large for one - * read keeps the feed's lineage and shows no summary card. + * summary, so a listed fork reads its chat once. While the summary is pending + * or failed it can still change elsewhere (it settles, or another device + * retries or skips it), and each such change moves the row's revision, so the + * chat is read again whenever the row moved since the last read. A chat too + * large for one read keeps the feed's lineage and shows no summary card. */ -function useRemoteForkLineage( - adapter: RemoteHostAdapter, +export function useRemoteForkLineage( + adapter: Pick, chatId: string, listed: ChatForkLineageV1 | undefined, rowRevision: string | undefined, @@ -944,22 +952,33 @@ function useRemoteForkLineage( const qc = useQueryClient(); const key = hostQueryKeys.forkLineage(adapter.hostId, chatId); const enabled = Boolean(listed) && adapter.capabilities().has("messagesWindow"); + // Read when a request starts, so a row that moves during the read triggers another. + const currentRevision = React.useRef(rowRevision); + currentRevision.current = rowRevision; const query = useQuery({ queryKey: key, - queryFn: async () => hostResultValue(await adapter.forkLineage(chatId)), + queryFn: async (): Promise => { + const feedRevision = currentRevision.current; + return { lineage: hostResultValue(await adapter.forkLineage(chatId)), feedRevision }; + }, enabled, staleTime: Infinity, retry: false, }); - const read = query.data; - const pendingElsewhere = - read?.forkedFrom?.summary?.state === "pending" && rowRevision !== undefined && rowRevision !== read.revision; + const read = query.data?.lineage; + // Only the feed's own revisions are compared; the lineage's revision is a different token. + const movedElsewhere = + forkSummaryHoldsSend(read?.forkedFrom) && rowRevision !== undefined && rowRevision !== query.data?.feedRevision; React.useEffect(() => { - if (pendingElsewhere) void qc.invalidateQueries({ queryKey: key, exact: true }); + if (movedElsewhere) void qc.invalidateQueries({ queryKey: key, exact: true }); // `key` is rebuilt every render, so its parts are the dependencies. - }, [qc, pendingElsewhere, adapter.hostId, chatId, rowRevision]); + }, [qc, movedElsewhere, adapter.hostId, chatId, rowRevision]); const update = React.useCallback( - (lineage: HostChatLineage) => qc.setQueryData(hostQueryKeys.forkLineage(adapter.hostId, chatId), lineage), + (lineage: HostChatLineage) => + qc.setQueryData(hostQueryKeys.forkLineage(adapter.hostId, chatId), { + lineage, + feedRevision: currentRevision.current, + }), [qc, adapter.hostId, chatId], ); const forkedFrom = enabled && read?.forkedFrom ? read.forkedFrom : listed; From dd506060fd5f158b43b3e81e2543e8445a911c78 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 19:29:26 -0400 Subject: [PATCH 4/4] fix(peer): don't let a late summary-action answer overwrite a newer summary A Retry's answer was stamped with the feed revision current when it arrived. If the summary finished and the pane had already read "ready" meanwhile, the late "pending" answer replaced it and kept the composer held with no further read. Summary actions now record the row revision when they start; an answer whose row moved in the meantime triggers a fresh read instead. Co-Authored-By: Claude Opus 5.5 --- .memory/chat-fork.md | 2 +- renderer/main/remote-chat-view.test.tsx | 102 ++++++++++++++++++------ renderer/main/remote-chat-view.tsx | 38 +++++---- 3 files changed, 101 insertions(+), 41 deletions(-) diff --git a/.memory/chat-fork.md b/.memory/chat-fork.md index 7e598f1953..affdda1026 100644 --- a/.memory/chat-fork.md +++ b/.memory/chat-fork.md @@ -89,7 +89,7 @@ Plan: `docs/plans/chat-fork-plan.md` (five PRs). This note tracks what has lande - Forks are disabled while a run has started or a send is in flight. - After a fork the pane opens the new chat. A `before` fork seeds the composer draft with only `prefill.text`. The composer can't show uploads staged on the host, so those are released and the user is told to attach them again. - The lineage row and `ForkSummaryCard` come from `useRemoteForkLineage`. It runs one full-chat read (best-effort, under the 1 MiB GET cap) and caches `{lineage, feedRevision}`, where `feedRevision` is the feed row revision when the read started. While the summary is pending or failed it reads again whenever the row revision differs from that cached one; it never compares the feed token with the content-hash revision. A retry, skip or ready result from another device therefore replaces a stale failed card and releases the composer hold. - - Summary actions write the returned lineage into that query. + - Summary actions call `beginUpdate()` as they start, which records the row revision. If the row hasn't moved when the answer arrives, the answer is written into the query under that revision. If it has moved, the answer may be older than a feed-driven read, so the query is invalidated and re-read instead. - A pending or failed summary holds the composer with `FORK_SUMMARY_HOLD_MESSAGE`. - **Tests.** - `main/services/peer-remote-chat-fork.test.ts` (in `test:remote-chat`) runs end to end over the real IPC, peer-operation and host chat service. It covers: diff --git a/renderer/main/remote-chat-view.test.tsx b/renderer/main/remote-chat-view.test.tsx index 03624a61c1..5069fa67dc 100644 --- a/renderer/main/remote-chat-view.test.tsx +++ b/renderer/main/remote-chat-view.test.tsx @@ -23,7 +23,7 @@ import type { SidebarHost } from "../lib/sidebar-remote-groups"; import type { RemoteChatSnapshot } from "../lib/hosts/remote-chat-session"; import { applyRemoteRunEvents, initialRemoteRunView, type RemoteRunView } from "../lib/hosts/remote-stream-translator"; import type { ChatRunInputAdmissionResult } from "../shared/chat-run-input"; -import type { ChatForkLineageV1, ChatForkSummaryV1 } from "../shared/chat-copy-contract"; +import { forkSummaryHoldsSend, type ChatForkLineageV1, type ChatForkSummaryV1 } from "../shared/chat-copy-contract"; import { RemoteChatPane, RemoteChatRoute, @@ -704,6 +704,38 @@ async function settle(): Promise { } } +/** Mounts the fork-lineage hook for one chat; `show` renders it at a feed row revision. */ +async function mountForkLineage(host: Parameters[0], listed: ChatForkLineageV1) { + let latest: ReturnType = { beginUpdate: () => noop }; + function Harness({ rowRevision }: { rowRevision: string }) { + latest = useRemoteForkLineage(host, "chat-1", listed, rowRevision); + return null; + } + const dom = installDocument(); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const { createRoot } = await import("react-dom/client"); + const { flushSync } = await import("react-dom"); + const root = createRoot(dom.container); + return { + async show(rowRevision: string) { + root.render( + + + , + ); + await settle(); + return latest.forkedFrom; + }, + latest: () => latest, + async dispose() { + flushSync(() => root.unmount()); + client.clear(); + await settle(); + dom.restore(); + }, + }; +} + test("a fork's summary changed on another device reaches the open pane when its feed row moves", async () => { const listed: ChatForkLineageV1 = { chatId: "chat-0", messageId: "m9", position: "after", at: 1 }; const failed: ChatForkSummaryV1 = { state: "failed", afterMessageId: "m2", error: "The model was unavailable." }; @@ -718,26 +750,8 @@ test("a fork's summary changed on another device reaches the open pane when its return { ok: true, value: { revision: `content-${reads}`, forkedFrom: { ...listed, ...(summary ? { summary } : {}) } } }; }, }; - let latest: ReturnType = { update: noop }; - function Harness({ rowRevision }: { rowRevision: string }) { - latest = useRemoteForkLineage(host, "chat-1", listed, rowRevision); - return null; - } - - const dom = installDocument(); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { createRoot } = await import("react-dom/client"); - const { flushSync } = await import("react-dom"); - const root = createRoot(dom.container); - const show = async (rowRevision: string) => { - root.render( - - - , - ); - await settle(); - return latest.forkedFrom; - }; + const mounted = await mountForkLineage(host, listed); + const show = mounted.show; const seen: Array = []; try { seen.push(await show("rev_1")); @@ -765,10 +779,7 @@ test("a fork's summary changed on another device reaches the open pane when its await show("rev_5"); assert.equal(reads, 4); } finally { - flushSync(() => root.unmount()); - client.clear(); - await settle(); - dom.restore(); + await mounted.dispose(); } const pane = (forkedFrom: ChatForkLineageV1 | undefined) => @@ -787,3 +798,44 @@ test("a fork's summary changed on another device reaches the open pane when its assert.doesNotMatch(skipped!.markup, /data-fork-summary/); assert.doesNotMatch(skipped!.text, /waiting for its summary/, "the composer is no longer held"); }); + +test("a summary action's late answer does not replace a newer summary the pane already read", async () => { + const listed: ChatForkLineageV1 = { chatId: "chat-0", messageId: "m9", position: "after", at: 1 }; + let summary: ChatForkSummaryV1 = { state: "failed", afterMessageId: "m2", error: "The model was unavailable." }; + let reads = 0; + const host = { + hostId: "host-b", + capabilities: () => new Set(["messagesWindow"]), + async forkLineage(): Promise<{ ok: true; value: HostChatLineage }> { + reads += 1; + return { ok: true, value: { revision: `content-${reads}`, forkedFrom: { ...listed, summary } } }; + }, + }; + const mounted = await mountForkLineage(host, listed); + try { + assert.equal((await mounted.show("rev_1"))?.summary?.state, "failed"); + + // Retry starts; the host answers "pending", but the answer is delayed. + const applyRetry = mounted.latest().beginUpdate(); + const retryAnswer: HostChatLineage = { + revision: "content-retry", + forkedFrom: { ...listed, summary: { state: "pending", afterMessageId: "m2" } }, + }; + // Meanwhile the summary finishes and the feed brings the pane up to date. + summary = { state: "ready", afterMessageId: "m2", text: "Earlier, the user asked about the release." }; + assert.equal((await mounted.show("rev_3"))?.summary?.state, "ready"); + + applyRetry(retryAnswer); + const shown = await mounted.show("rev_3"); + assert.equal(shown?.summary?.state, "ready", "the late pending answer does not bring the summary back"); + assert.equal(forkSummaryHoldsSend(shown), false, "the composer stays released"); + + // An answer whose row has not moved since the action started applies as-is. + summary = { state: "failed", afterMessageId: "m2", error: "The model was unavailable." }; + const applySkip = mounted.latest().beginUpdate(); + applySkip({ revision: "content-skip", forkedFrom: listed }); + assert.equal((await mounted.show("rev_3"))?.summary, undefined); + } finally { + await mounted.dispose(); + } +}); diff --git a/renderer/main/remote-chat-view.tsx b/renderer/main/remote-chat-view.tsx index 6c38c85acb..b9094dc08b 100644 --- a/renderer/main/remote-chat-view.tsx +++ b/renderer/main/remote-chat-view.tsx @@ -298,8 +298,8 @@ export interface RemoteChatPaneProps { lineage?: RemoteChatLineage; /** Opens another chat on the same host: a new fork, or a fork's source. */ onOpenChat?(chatId: string): void; - /** A summary action answered with the fork's new lineage. */ - onLineageChange?(lineage: HostChatLineage): void; + /** Called as a summary action starts; the returned function takes the action's answer. */ + beginLineageChange?(): (lineage: HostChatLineage) => void; } export interface RemoteChatLineage { @@ -322,7 +322,7 @@ export function RemoteChatPane({ forkable = false, lineage, onOpenChat, - onLineageChange, + beginLineageChange, }: RemoteChatPaneProps) { const messages = snapshot?.transcript.messages ?? []; const run = snapshot?.run; @@ -490,13 +490,15 @@ export function RemoteChatPane({ const runForkSummaryAction = async (action: "retry" | "cancel" | "skip") => { if (!control) return; setForkSummaryBusy(true); + const applyLineage = beginLineageChange?.(); try { if (action === "cancel") { // The host settles the summary as failed once the attempt stops. if (!(await control.cancelForkSummary())) toast.info("The summary already finished."); return; } - onLineageChange?.(await control.forkSummary(action)); + const answered = await control.forkSummary(action); + applyLineage?.(answered); } catch (error) { toast.error(error instanceof Error ? error.message : "Couldn't update the fork's summary."); } finally { @@ -948,7 +950,7 @@ export function useRemoteForkLineage( chatId: string, listed: ChatForkLineageV1 | undefined, rowRevision: string | undefined, -): { forkedFrom?: ChatForkLineageV1; update(lineage: HostChatLineage): void } { +): { forkedFrom?: ChatForkLineageV1; beginUpdate(): (lineage: HostChatLineage) => void } { const qc = useQueryClient(); const key = hostQueryKeys.forkLineage(adapter.hostId, chatId); const enabled = Boolean(listed) && adapter.capabilities().has("messagesWindow"); @@ -973,16 +975,22 @@ export function useRemoteForkLineage( if (movedElsewhere) void qc.invalidateQueries({ queryKey: key, exact: true }); // `key` is rebuilt every render, so its parts are the dependencies. }, [qc, movedElsewhere, adapter.hostId, chatId, rowRevision]); - const update = React.useCallback( - (lineage: HostChatLineage) => - qc.setQueryData(hostQueryKeys.forkLineage(adapter.hostId, chatId), { - lineage, - feedRevision: currentRevision.current, - }), - [qc, adapter.hostId, chatId], - ); + // An action's answer describes the host as of the row the action started from. + const beginUpdate = React.useCallback(() => { + const startRevision = currentRevision.current; + return (lineage: HostChatLineage) => { + const queryKey = hostQueryKeys.forkLineage(adapter.hostId, chatId); + if (currentRevision.current === startRevision) { + qc.setQueryData(queryKey, { lineage, feedRevision: startRevision }); + } else { + // The row moved while the action ran, so the answer may be older than + // what the pane already shows. Read the chat again instead. + void qc.invalidateQueries({ queryKey, exact: true }); + } + }; + }, [qc, adapter.hostId, chatId]); const forkedFrom = enabled && read?.forkedFrom ? read.forkedFrom : listed; - return forkedFrom ? { forkedFrom, update } : { update }; + return forkedFrom ? { forkedFrom, beginUpdate } : { beginUpdate }; } /** Binds the pane's session control to this host's adapter and this chat. */ @@ -1012,7 +1020,7 @@ function ControlledRemoteChatPane({ chat={chat} {...(hostSkills ? { hostSkills } : {})} {...(lineage ? { lineage } : {})} - onLineageChange={fork.update} + beginLineageChange={fork.beginUpdate} /> ); }