Skip to content
Merged
29 changes: 29 additions & 0 deletions .memory/chat-fork.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,35 @@ Plan: `docs/plans/chat-fork-plan.md` (five PRs). This note tracks what has lande
- **Status codes.** Summary actions answer 409 `revision_conflict` only for `ForkSummaryStateError` (the summary moved on); any other error falls through to the router's internal-error path. A fork whose result (chat plus staged prefill) would exceed the durable-operation size limit is refused with 413 before install. Replays of any rejection come back as 409 `internal_error`, because the idempotency ledger stores only contract codes.
- **Peer.** `peer-operation.ts` `forkBody` accepts only `focus`; `remote-host-adapter.ts` maps the wire `focus` back to the desktop's `instructions`.

## Paired Macs — desktop forks a peer's chat (branch `feat/chat-fork-peer`)

- **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/<action>`. 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.** 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 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 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:
- 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`.

## Mobile PR — Android half (branch `feat/chat-fork-android`)

- **Client.** `AidenRemoteClient.forkChat` posts `/chats/{id}/fork` with `If-Match` and an `Idempotency-Key`, expects `201 {chat, prefill?}`, and rejects a result that has no lineage or is the source chat. A blank focus sends `summary: {}`. `retryForkSummary`, `skipForkSummary` and `cancelForkSummary` post to `/fork-summary/{retry|skip|cancel}`. 409 `operation_in_progress` and `revision_conflict` get their own copy in `AidenChatForkErrors`.
Expand Down
105 changes: 105 additions & 0 deletions main/services/peer-operation.test.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -197,3 +198,107 @@ 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 } },
// 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 [{}, { focus: "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" }));
});
73 changes: 71 additions & 2 deletions main/services/peer-operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -54,8 +56,47 @@ export const PEER_CHAT_MUTATIONS: ReadonlySet<string> = 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<string, unknown> {
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 focus = summary.focus;
if (
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: focus === undefined ? {} : { focus },
};
}

/** `{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;
Expand All @@ -81,8 +122,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;
}

Expand Down Expand Up @@ -128,6 +178,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";
Expand Down Expand Up @@ -324,6 +375,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.");
}
Expand All @@ -337,7 +406,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) } : {}),
Expand Down
Loading
Loading