From 95958f17b31e686af6a35f495aa8619568d7d934 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 11:22:22 -0400 Subject: [PATCH 1/5] fix(transcript): let sent prompts be selected; plan chat forking The app body sets user-select: none and only assistant Markdown opted back in, so a sent user prompt could not be selected with the pointer. The user bubble and the unrenderable-message fallback now allow text selection. An Electron E2E drags across a sent prompt and reads the selection back. Adds docs/plans/chat-fork-plan.md: fork a chat from any message on desktop, Remote, iOS and Android, informed by opencode and pi. Co-Authored-By: Claude Opus 5.5 --- docs/plans/README.md | 1 + docs/plans/chat-fork-plan.md | 263 ++++++++++++++++++++++ renderer/components/message-bubble.tsx | 4 +- tests/e2e/chat-shell-interactions.spec.ts | 23 ++ 4 files changed, 289 insertions(+), 2 deletions(-) create mode 100644 docs/plans/chat-fork-plan.md diff --git a/docs/plans/README.md b/docs/plans/README.md index 4c0d7d7536..ba9133fec9 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -25,6 +25,7 @@ Last refreshed 2026-10-01 against `main` at `d2197dfef` (0.51.0 plus later merge | [Bot-First Aiden On The Go](bot-first-aiden-on-the-go-plan.md) | Active | Phases 0–9 are implemented. Native approval/Stop hardening merged in PR #218, and mid-flight Steer/Queue, question prompts and quiet chat merged in PR #251. Bot chat deep links (`aiden-otg://bot/{id}/chat`) merged in PR #276 and are on main. Every Bot has one persistent chat and one contact row; Favorites are a pinned placement, Bot chat reuses the shared runtime with Messages-inspired identity/bubbles and Aiden's existing composer, and New/Edit Bot exclusively own its durable model. Remote open-or-create, immediate exact-cache chat entry, optimistic favorites, shaped skeleton loading, stable photos, atomic desktop creation, fresh-inventory save retries, conflict-safe Mac/iOS draft rebasing, final-only Bot replies with expandable progress, native-or-companion image handling, and internal TestFlight build 22 are green. Eligible Apple Intelligence hardware, physical iPad, multi-device/Mac, packaged rollback, live Telegram, wider staged TestFlight, Xcode 27, accessibility, and App Store owner gates remain open. | | [Aiden Manual Pairing](aiden-manual-pairing-plan.md) | Implemented | The reviewed 100-bit setup-code path, shared one-use QR window, staged iOS activation, and adversarial coverage ship; hands-on LAN/Tailscale UI and physical-iPad acceptance remain open. | | [Compaction](compaction-plan.md) | Partial | Pi-native checkpoints, lifecycle/crash recovery, and exact audited-upstream compatibility ship; durable memory and provider-native paths remain open. | +| [Fork a chat from any message](chat-fork-plan.md) | Planned | Decisions approved 2026-10-05: per-message Fork from here / Edit in fork (after-reply and before-prompt cut points), optional Fork with summary via Pi branch summarization, `forkedFrom` lineage with a flat sidebar glyph, Pi journal fork, busy chats still refused, Remote `POST /chats/{id}/fork` (revision 21, `chat-fork-v1`), iOS/Android menus and CLI daemon. Extends the existing desktop `/fork` and `/clone`. | | [Designer Mode](designer-mode-plan.md) | Planned | Phase 0 validation has not started in the runtime. | | [Dynamic Model Catalog](dynamic-model-catalog-plan.md) | Implemented | Validated pi.dev overlays, offline `0600` cache hydration, scoped setup refresh, four-hour launch refresh, force refresh, Pi metadata fallback, and Mac/iOS projection ship; Pi is now pinned to 0.87.1 (PR #246). | | [Generative UI Artifacts](generative-ui-artifacts-plan.md) | Active | Phases 0–6 shipped: chat-scoped `render_artifact`, strict sandboxed preview/export hosts, verified vendored Chart.js/Plotly/KaTeX, permission-aware `/visualize`, crash-recoverable authoritative storage/copies, descriptor-relative workspace reads, one-iframe handoff/expansion, visible failure states, and route-stable Responding/Visualizing activity. Three-agent PR review findings are remediated with focused regression coverage. | diff --git a/docs/plans/chat-fork-plan.md b/docs/plans/chat-fork-plan.md new file mode 100644 index 0000000000..930dae2d27 --- /dev/null +++ b/docs/plans/chat-fork-plan.md @@ -0,0 +1,263 @@ +# Fork a chat from any message + +Status: **Planned (decisions approved 2026-10-05)**. Not implemented yet. Written against `main` at `7e339cf1d` (0.53.0). + +## Goal + +A user can fork a workspace chat from any message on desktop, iOS, Android and paired Macs. A fork is a new chat in the same workspace that contains the conversation up to that point. The original chat is left unchanged. The fork remembers which chat and message it came from. Optionally, the fork can also carry a summary of what happened in the original chat after the fork point. + +## Decisions + +| Question | Decision | +|---|---| +| Naming | **Fork** everywhere. This covers UI copy, the `/fork` command, the Remote route and the feature token. | +| Busy chats | Keep today's rule. Forking is refused while the source chat is generating or waiting on an approval. | +| Sidebar | Flat list. Each fork row shows a small fork glyph and a "Forked from …" tooltip. Forks are not nested. | +| Summaries | Optional **Fork with summary**. The summary uses Pi's branch summarization, and the model sees it in the fork's context. | + +## What already exists + +Aiden already ships a narrow version on desktop: +- `/fork` ("Fork from a turn") opens a picker of completed assistant turns. +- `/clone` copies the whole visible chat. +- Code: `renderer/shared/slash-commands.ts`, `renderer/lib/chat-copy-view.ts`, and the composer dialog. + +Both commands call `chats:copyVisibleHistory` (`main/handlers/chats.ts`), which calls `chatStore.copyVisibleHistory({ throughAssistantMessageId })` (`main/services/chat-store-core.ts`). That method: +- gives copied messages fresh IDs and their own copies of attachment and artifact bytes; +- refuses to run while the source chat is busy; +- adds `(fork)` or `(copy)` to the title. + +Gaps in that version: + +| Gap | Effect | +|---|---| +| The command is the only way in. Messages have no fork action. | Hard to discover. | +| It can only cut *after* an assistant turn. | You can't fork to rewrite a prompt and try again. | +| No lineage: `ChatMeta` has no `forkedFrom`. | A fork looks like any other chat except for its title. | +| Only the visible projection is copied, and the fork starts with no Pi journal. | The fork's model loses earlier tool results and compaction checkpoints. | +| No application-service method, Remote route or CLI command. | iOS, Android, paired Macs and `aiden serve` can't fork. | + +## How opencode and pi do it + +### opencode (`dev` at `907b3bc518`) + +- **API:** `POST /session/:id/fork { messageID? }` deep-copies every message that comes strictly before `messageID` into a new session. + - Message and part IDs are regenerated. + - Assistant→user parent links and compaction tail IDs are remapped. + - Tool, file and snapshot parts are copied as-is. +- **UI:** + - Clicking a user message offers Revert, Copy and **Fork**. + - `/fork` lists user messages newest first, with "Full session" at the top. + - After forking, the new session opens with the forked prompt and its attachments in the composer. +- **Lineage:** v1 keeps none; the title just becomes `X (fork #N)`. The v2 client adds `fork: { sessionID, messageID }` and a `session.forked` event. +- **Files:** forking never touches the working tree. + +### pi (`main` at `021eae60a`) + +- **Session file:** an append-only tree of entries with `id`/`parentId`, plus a leaf pointer. +- **`/fork`:** calls `fork(entryId, { position: "before" })`. This copies the path from the root to the parent of the selected user message into a **new session file**, sets `parentSession` in its header, and puts the message text back in the editor. +- **`/clone`:** uses `position: "at"`. +- **`/tree`:** navigates within one file. It can summarize the branch being left into a `branch_summary` entry. + - The summary uses a fixed Goal / Constraints / Progress / Decisions / Next steps format and lists the files read and modified. + - The model receives it as "The user explored a different conversation branch…". +- **Hooks:** `session_before_fork` can cancel a fork. `session_start` fires with `{ reason: "fork" }`. +- **Aiden's pinned `@earendil-works/pi-agent-core@0.87.1` already exports:** + - `SessionRepo.fork(source, { scope: "branch", entryId, position: "before" | "at" })` + - `collectEntriesForBranchSummary`, `prepareBranchEntries` and `generateBranchSummary` +- **Aiden support:** `main/services/pi-session-port.ts` already turns `branch_summary` entries into model context. + +### What we take from them + +1. Two cut points: + - *before a user message*, to edit it and resend; + - *after a reply*, to continue from there. +2. Pre-fill the composer when cutting before a prompt. +3. Each fork is a separate chat, not an in-place tree. Remote, mobile caches and sidebar summaries all assume one linear transcript per chat. +4. Lineage is recorded explicitly. +5. The agent's own context is forked, not just the visible text. +6. pi's branch summary is reused so the fork can know what was tried after the fork point. + +## Design + +### Cut points + +| Action | Shown on | Copies | Composer after navigation | +|---|---|---|---| +| **Fork from here** | Settled assistant reply | Everything through that reply | Empty | +| **Edit in fork** | User message | Everything *before* that message | That prompt's text, attachments and skill, ready to edit | + +- `/fork` keeps working. Its picker gains user-message rows, which use the "before" cut point, alongside the existing assistant turns. +- `/clone` is unchanged. +- A request looks like `{ chatId, messageId, position: "after" | "before", summary? }`. + - `after` requires a settled assistant message. + - `before` requires a user message. On the first message, the result is an empty chat with the prompt pre-filled. This matches pi's `parentId === null` case. + +### Fork with summary + +The summary is offered only when the source chat has messages after the cut point. + +**UI** +- The hover button always makes a plain fork. +- The message context menu and the `/fork` picker also offer **Fork with summary…**. This opens a small sheet with: + - a single optional "Focus the summary on…" instructions field. pi uses the same field for custom instructions. + - **Fork** and **Cancel** buttons. + +**Content** +- The summary covers source entries after the cut point, up to the source's current tip. +- It is built with `collectEntriesForBranchSummary`, `prepareBranchEntries` (token budget, default 16k) and `generateBranchSummary`. +- It runs on the source chat's provider and model, through the existing compaction summarizer routing and usage accounting. +- If the source has no Pi journal, the summarizer runs over the visible messages after the cut. + +**Storage** +- In the fork's Pi journal, the summary is a `branch_summary` entry that is a child of the cut entry. `pi-session-port` already feeds that entry type to the model. +- In the visible transcript, `forkedFrom.summary` holds `{ state: "pending" | "ready" | "failed", text?, files? }`. The lineage row renders it as an expandable "What happened after this point" card. This is the same treatment as the compaction checkpoint card. + +**Async flow** +- The fork is created immediately with `summary.state = "pending"`, and generation runs in the background. +- While the summary is pending, the fork's first send is held. This reuses the queue-while-compacting hold: the composer stays editable, shows "Summarizing the original chat…", and queues the message. +- The summary can be cancelled. On cancel, or when generation fails, `state` becomes `"failed"` with **Retry** and **Continue without summary** actions, and any held message is paused rather than dropped. +- Progress and completion reach desktop and Remote clients through the existing `chats:metadata-updated` broadcast and chat revision bumps. + +### Lineage + +- `ChatMeta` gains an optional field. Existing chats load unchanged. + + ```ts + forkedFrom?: { + chatId: string; + messageId: string; + position: "after" | "before"; + at: number; + summary?: { state: "pending" | "ready" | "failed"; text?: string; files?: { read: string[]; modified: string[] } }; + } + ``` + +- **Title:** `Title (fork 2)`, numbered like opencode. This replaces the static `(fork)` suffix. +- **Transcript header:** a quiet "Forked from **{source title}**" row. It links to the source and scrolls to the message. If the source chat was deleted, the row reads "Forked from a deleted chat" with no link. +- **Sidebar:** the list stays flat. A fork row shows the fork glyph (the existing `fork` slash icon) and a "Forked from …" tooltip. +- **Bot chats:** forking is excluded. A Bot has one canonical chat. + +### Pi journal fork + +The visible copy stays the source of truth for the transcript. + +**New method:** `PiCompactionSessionStore.forkChat(sourceChatId, targetChatId, cut, position, messageIdMap)`. +1. Resolve the cut to a journal entry through the `aiden.chat-message.v1` markers that `syncChatMessagesToPiSession` already writes. +2. Call `SessionRepo.fork(source, { scope: "branch", entryId, position, id: targetChatId })`. +3. Rewrite the copied markers to the fork's new visible message IDs, using the map from the visible copy. +4. Register the new journal in `aiden-journal-index.json`. + +**Fallback:** a legacy chat, a missing journal, an ineligible chat or an unresolvable cut means no journal is forked, and the fork rebuilds lazily from visible messages as it does today. A fork never fails just because the richer copy wasn't possible. + +**Atomicity:** the visible copy and the journal fork run under the existing dual-ID lock and recovery transaction. + +### Workspace and files + +A fork keeps the source `workspaceId`. It doesn't touch files, git branches or worktrees. This matches both opencode and pi. "Fork into a new worktree" is a possible later option. + +### Busy chats + +Unchanged: a fork is refused while the source chat is generating or waiting on an approval. In the UI: +- On desktop, the fork actions are disabled with a tooltip. +- On Remote, the route returns `409`, and mobile clients show the same reason. + +## Surfaces + +### Desktop + +- **Shared service:** move fork and clone into `chat-application-service.ts` as `fork(input)`. IPC, Remote and the CLI daemon then share one implementation. `chats:copyVisibleHistory` becomes a thin caller and gains `position` and `summary`. +- **Message actions:** + - `MessageBubble` and `MessageList` gain `messageId` and an `onFork(messageId, position, { summarize })` callback. + - In `message-actions.tsx`, assistant replies get a **Fork** button that uses the shared squircle action shape. + - User messages get **Edit in fork** next to the hover Copy button. + - Both actions, plus **Fork with summary…**, also appear in a right-click context menu on the bubble. +- **Navigation and pre-fill:** reuse the `copyChat` path in `chat-pane.tsx` to update the cache, select the workspace and navigate. For `before`, seed the fork's per-chat draft (text, attachments, skill) and focus the composer. +- **Lineage UI:** the transcript header row, the summary card and the sidebar glyph. +- **Paired Macs:** `remote-chat-view.tsx` gets the same actions, routed through `HostChatAdapter.fork` → `peer-operation.ts` → the Remote route and gated on the peer's `chat-fork-v1` feature. + +### Aiden Remote + +- **New route:** `POST /chats/{chatId}/fork` (`forkChat`). + - **Body:** `{ messageId, position, summary?: { instructions?: string } }`. + - **Headers:** `Idempotency-Key`, and `If-Match` on the source revision. + - **Response:** `{ chat, prefill? }`. For `before`, `prefill` is `{ text, attachmentIds, skill }`, and the attachments are re-referenced rather than re-uploaded. + - **Errors:** `409` when the source is busy, `404` for an unknown message, `422` for an ineligible message. +- **Summary controls:** `POST /chats/{chatId}/fork-summary/retry` and `/cancel` drive the failed and pending states. +- **Projections:** chat and chat-summary projections gain `forkedFrom`, including `summary`. Older clients ignore the extra optional field. +- **Revision and feature token:** contract revision **21** plus feature `chat-fork-v1`. Claim the revision at merge time. Update all of these in the same change: + - `docs/aiden-remote-api-v1.md` + - `protocol/aiden-remote/v1/openapi.json` + - `fixtures/contract.json` + - the TS constants + - Swift `AidenRemoteContract.swift` + - Kotlin `AidenRemoteProtocol.kt` + - the fixture tests + +### iOS (`ios/AidenOnTheGo`) + +- **Client:** `AidenRemoteClient.forkChat(chatId:messageId:position:summary:)`, plus the retry and cancel calls. The DTO gains `forkedFrom`. +- **Message context menu:** `AidenMessageView` currently offers Copy, Select Text and Ask About This. It gains: + - **Fork from Here** and **Fork with Summary…** on assistant replies; + - **Edit in Fork** on user messages; + - matching accessibility actions. + - All of these are hidden when the host lacks `chat-fork-v1`. +- **After forking:** push the new chat and seed the composer draft from `prefill`. This reuses the per-chat draft path and its pairing-generation fencing. +- **Lineage:** + - a lineage row at the top of the transcript, with the summary card and the pending, failed and retry states; + - a fork glyph in `AidenWorkspaceChatsView` rows. +- **New Swift files** must be registered in pbxproj and in the `scripts/check-ios-shipping-target.test.mjs` allowlist. + +### Android (`android/app/.../AidenOnTheGo`) + +- **Client:** `AidenRemoteClient.forkChat`, plus retry and cancel. `AidenChat` gains `forkedFrom`. +- **Message context menu:** `AidenMessageContextMenu.kt` currently offers Copy Text, Select Text, Ask about this and Share. It gains the same three actions, gated on the feature. +- **After forking:** navigate via `AidenChatViewModel` and seed the composer from `prefill`. +- **Lineage:** + - a lineage row with the summary card in `AidenChatDetailScreen`; + - a glyph in `AidenWorkspaceChatRow`. + +### CLI (`packages/cli`) + +- **`aiden serve`:** `remote-chats.ts` already composes `createChatApplicationService`. The route works there once the daemon journal adapter (`daemon-chats/journals/.jsonl`) implements `forkChat` and summary generation. +- **CLI TUI:** it runs pi's interactive mode. Check whether pi's own `/fork` and `/tree` are reachable. If they are, document them in `packages/cli/README.md` instead of adding duplicates. + +### Onboarding + +No onboarding step: forking is not setup-critical. Advertise it as a bento tile only if you want it in the tour. A tile needs its own 1024 × 1024 asset. + +## Delivery: five PRs + +1. **Desktop fork** + - Scope: `position`, lineage metadata and `(fork N)` titles, the application-service move, message actions, `/fork` picker user rows, pre-fill, lineage row and sidebar glyph. + - Tests: + - store tests for the `before` and `after` boundaries and lineage; + - handler parse tests; + - a picker test; + - Playwright for both actions and the pre-fill. +2. **Pi journal fork** + - Scope: `forkChat` with marker remapping and fallback. + - Tests: + - a replay test showing the fork's model context contains the source's tool results and compaction checkpoint up to the cut, and nothing after it; + - a crash-recovery test. +3. **Fork with summary (desktop)** + - Scope: background generation, `branch_summary` journal entry, `forkedFrom.summary` states, held first send, cancel/retry/continue, summary card, usage accounting. + - Tests: + - summarizer input boundaries: only entries after the cut; + - the held-send lifecycle; + - failure leaves held messages paused; + - the model context contains the summary. +4. **Remote and daemon** + - Scope: routes, projections, revision 21 contract set, CLI daemon, paired-Mac desktop actions. + - Tests: + - router tests for idempotency, `If-Match`, `409`/`404`/`422`, and summary retry/cancel; + - fixture and contract tests; + - a CLI daemon test. +5. **iOS and Android** + - Scope: clients, menus, pre-fill, lineage row, summary card states, glyph. + - Tests: focused decode and view-model tests on both platforms, and the mobile suites run. + +Dependencies: +- 2 and 1 can land in either order. +- 3 needs 1 and 2. +- 4 needs 1. The summary routes need 3. +- 5 needs 4. diff --git a/renderer/components/message-bubble.tsx b/renderer/components/message-bubble.tsx index 1f4ddb2842..a8886bc649 100644 --- a/renderer/components/message-bubble.tsx +++ b/renderer/components/message-bubble.tsx @@ -84,7 +84,7 @@ export function MessageBubble({ ) : null} {content ? ( -
+
) : null} @@ -182,7 +182,7 @@ function UnrenderableMessage({ content }: { content: string }) { This message could not be formatted - + {content} diff --git a/tests/e2e/chat-shell-interactions.spec.ts b/tests/e2e/chat-shell-interactions.spec.ts index 5cb6da1623..1fd3355331 100644 --- a/tests/e2e/chat-shell-interactions.spec.ts +++ b/tests/e2e/chat-shell-interactions.spec.ts @@ -778,6 +778,29 @@ test("holding Command reveals chat shortcuts and typing outside a field lands in await expect(composer).toHaveValue("hi there"); }); +test("sent user prompts can be selected with the pointer", async ({ aiden }) => { + const { page } = aiden; + await finishLmStudioOnboarding(page); + await seedPaletteChats(aiden); + + await page.keyboard.press(`${PRIMARY_MODIFIER}+1`); + const prompt = page.getByText(/^Opened palette-chat-/u); + await expect(prompt).toBeVisible(); + const expected = (await prompt.textContent()) ?? ""; + + const box = await prompt.boundingBox(); + expect(box).toBeTruthy(); + const y = box!.y + box!.height / 2; + await page.mouse.move(box!.x + 1, y); + await page.mouse.down(); + await page.mouse.move(box!.x + box!.width - 1, y, { steps: 8 }); + await page.mouse.up(); + + const selected = await page.evaluate(() => window.getSelection()?.toString() ?? ""); + expect(selected.length).toBeGreaterThan(expected.length / 2); + expect(expected).toContain(selected.trim()); +}); + // Human-readable palette labels may legitimately collide. Keyboard selection // must target the underlying chat/model identity, not the label string. test("command palette selects each chat with identical labels independently", async ({ aiden }) => { From 00f3bcf2518bd63a2404fa1f2fe50556717a9b84 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 11:51:17 -0400 Subject: [PATCH 2/5] feat(chats): fork from any message on desktop Settled replies offer "Fork from here" and sent prompts offer "Edit in fork", which copies everything before the prompt and pre-fills the new chat's composer with its text and attachments. Editing the first prompt opens an unsaved draft instead of persisting an empty chat. Forks record a strictly parsed `forkedFrom` lineage and are titled `Title (fork)`, `(fork 2)`, ... per workspace. The chat header links back to the source (or notes it was deleted) and sidebar rows carry a fork glyph. A corrupt lineage is dropped on read rather than hiding the chat. Co-Authored-By: Claude Opus 5.5 --- docs/plans/README.md | 2 +- main/handlers/chat-session-params.test.ts | 20 +++- main/handlers/chat-session-params.ts | 32 ++++-- main/handlers/chats.ts | 12 +-- main/services/chat-copy-artifacts.ts | 24 ++++- main/services/chat-session-copy.test.ts | 113 +++++++++++++++++++ main/services/chat-store-core.ts | 87 ++++++++++++--- main/services/types.ts | 3 + package.json | 2 +- renderer/components/chat-sidebar.tsx | 34 ++++-- renderer/components/composer.test.tsx | 1 - renderer/components/composer.tsx | 32 ++++-- renderer/components/fork-message-button.tsx | 41 +++++++ renderer/components/message-actions.tsx | 12 ++- renderer/components/message-bubble.test.tsx | 38 +++++++ renderer/components/message-bubble.tsx | 28 +++-- renderer/components/message-list.tsx | 39 +++++++ renderer/lib/chat-copy-view.test.ts | 15 +++ renderer/lib/chat-copy-view.ts | 14 ++- renderer/lib/composer-draft-store.ts | 21 ++++ renderer/lib/ipc.ts | 9 +- renderer/lib/types.ts | 3 + renderer/main/chat-pane.tsx | 114 +++++++++++++++++++- renderer/shared/chat-copy-contract.test.ts | 43 ++++++++ renderer/shared/chat-copy-contract.ts | 72 +++++++++++++ tests/e2e/chat-fork.spec.ts | 95 ++++++++++++++++ 26 files changed, 838 insertions(+), 68 deletions(-) create mode 100644 renderer/components/fork-message-button.tsx create mode 100644 renderer/shared/chat-copy-contract.test.ts create mode 100644 tests/e2e/chat-fork.spec.ts diff --git a/docs/plans/README.md b/docs/plans/README.md index ba9133fec9..dd86456cef 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -25,7 +25,7 @@ Last refreshed 2026-10-01 against `main` at `d2197dfef` (0.51.0 plus later merge | [Bot-First Aiden On The Go](bot-first-aiden-on-the-go-plan.md) | Active | Phases 0–9 are implemented. Native approval/Stop hardening merged in PR #218, and mid-flight Steer/Queue, question prompts and quiet chat merged in PR #251. Bot chat deep links (`aiden-otg://bot/{id}/chat`) merged in PR #276 and are on main. Every Bot has one persistent chat and one contact row; Favorites are a pinned placement, Bot chat reuses the shared runtime with Messages-inspired identity/bubbles and Aiden's existing composer, and New/Edit Bot exclusively own its durable model. Remote open-or-create, immediate exact-cache chat entry, optimistic favorites, shaped skeleton loading, stable photos, atomic desktop creation, fresh-inventory save retries, conflict-safe Mac/iOS draft rebasing, final-only Bot replies with expandable progress, native-or-companion image handling, and internal TestFlight build 22 are green. Eligible Apple Intelligence hardware, physical iPad, multi-device/Mac, packaged rollback, live Telegram, wider staged TestFlight, Xcode 27, accessibility, and App Store owner gates remain open. | | [Aiden Manual Pairing](aiden-manual-pairing-plan.md) | Implemented | The reviewed 100-bit setup-code path, shared one-use QR window, staged iOS activation, and adversarial coverage ship; hands-on LAN/Tailscale UI and physical-iPad acceptance remain open. | | [Compaction](compaction-plan.md) | Partial | Pi-native checkpoints, lifecycle/crash recovery, and exact audited-upstream compatibility ship; durable memory and provider-native paths remain open. | -| [Fork a chat from any message](chat-fork-plan.md) | Planned | Decisions approved 2026-10-05: per-message Fork from here / Edit in fork (after-reply and before-prompt cut points), optional Fork with summary via Pi branch summarization, `forkedFrom` lineage with a flat sidebar glyph, Pi journal fork, busy chats still refused, Remote `POST /chats/{id}/fork` (revision 21, `chat-fork-v1`), iOS/Android menus and CLI daemon. Extends the existing desktop `/fork` and `/clone`. | +| [Fork a chat from any message](chat-fork-plan.md) | In progress | PR 1 (desktop Fork from here / Edit in fork, lineage, `(fork N)` titles) implemented 2026-10-05; Pi journal fork, Fork with summary, Remote and mobile follow. Decisions approved 2026-10-05: per-message Fork from here / Edit in fork (after-reply and before-prompt cut points), optional Fork with summary via Pi branch summarization, `forkedFrom` lineage with a flat sidebar glyph, Pi journal fork, busy chats still refused, Remote `POST /chats/{id}/fork` (revision 21, `chat-fork-v1`), iOS/Android menus and CLI daemon. Extends the existing desktop `/fork` and `/clone`. | | [Designer Mode](designer-mode-plan.md) | Planned | Phase 0 validation has not started in the runtime. | | [Dynamic Model Catalog](dynamic-model-catalog-plan.md) | Implemented | Validated pi.dev overlays, offline `0600` cache hydration, scoped setup refresh, four-hour launch refresh, force refresh, Pi metadata fallback, and Mac/iOS projection ship; Pi is now pinned to 0.87.1 (PR #246). | | [Generative UI Artifacts](generative-ui-artifacts-plan.md) | Active | Phases 0–6 shipped: chat-scoped `render_artifact`, strict sandboxed preview/export hosts, verified vendored Chart.js/Plotly/KaTeX, permission-aware `/visualize`, crash-recoverable authoritative storage/copies, descriptor-relative workspace reads, one-iframe handoff/expansion, visible failure states, and route-stable Responding/Visualizing activity. Three-agent PR review findings are remediated with focused regression coverage. | diff --git a/main/handlers/chat-session-params.test.ts b/main/handlers/chat-session-params.test.ts index 9d518907e5..d9532905ae 100644 --- a/main/handlers/chat-session-params.test.ts +++ b/main/handlers/chat-session-params.test.ts @@ -9,14 +9,18 @@ import { } from "./chat-session-params.js"; test("session command parsers accept only exact bounded chat selectors", () => { - assert.deepEqual(parseChatCopyRequest({ chatId: "chat-1" }), { - chatId: "chat-1", - throughMessageId: undefined, - }); + assert.deepEqual(parseChatCopyRequest({ chatId: "chat-1" }), { chatId: "chat-1" }); + // The legacy selector still means "fork after this reply". assert.deepEqual(parseChatCopyRequest({ chatId: "chat-1", throughMessageId: "message-1" }), { chatId: "chat-1", - throughMessageId: "message-1", + forkAt: { messageId: "message-1", position: "after" }, }); + for (const position of ["after", "before"] as const) { + assert.deepEqual( + parseChatCopyRequest({ chatId: "chat-1", messageId: "message-1", position }), + { chatId: "chat-1", forkAt: { messageId: "message-1", position } }, + ); + } assert.deepEqual(parseChatOnlyRequest({ chatId: "chat-1" }), { chatId: "chat-1" }); for (const invalid of [ null, @@ -25,6 +29,12 @@ test("session command parsers accept only exact bounded chat selectors", () => { { chatId: "chat", path: "/tmp/private" }, { chatId: "x".repeat(CHAT_SESSION_ID_LIMITS.chatCharacters + 1) }, { chatId: "chat", throughMessageId: "" }, + { chatId: "chat", messageId: "message-1" }, + { chatId: "chat", position: "after" }, + { chatId: "chat", messageId: "message-1", position: "at" }, + { chatId: "chat", messageId: "", position: "before" }, + { chatId: "chat", throughMessageId: "message-1", messageId: "message-1", position: "after" }, + { chatId: "chat", throughMessageId: "message-1", position: "before" }, ]) { assert.throws(() => parseChatCopyRequest(invalid)); } diff --git a/main/handlers/chat-session-params.ts b/main/handlers/chat-session-params.ts index c41bc40ebd..cc132cb0bb 100644 --- a/main/handlers/chat-session-params.ts +++ b/main/handlers/chat-session-params.ts @@ -1,7 +1,9 @@ +import type { ChatForkPosition } from "../../renderer/shared/chat-copy-contract.js"; + const MAX_CHAT_ID_CHARS = 160; const MAX_CHAT_ID_BYTES = 640; const MAX_DRAFT_TEXT_CHARS = 65_536; -const COPY_KEYS = new Set(["chatId", "throughMessageId"]); +const COPY_KEYS = new Set(["chatId", "throughMessageId", "messageId", "position"]); const CHAT_ONLY_KEYS = new Set(["chatId"]); const CONTEXT_PRESSURE_KEYS = new Set([ "chatId", @@ -55,17 +57,33 @@ function boundedId(value: unknown, label: string): string { export interface ParsedChatCopyRequest { chatId: string; - throughMessageId?: string; + /** Absent for a whole-chat clone. */ + forkAt?: { messageId: string; position: ChatForkPosition }; } +/** + * `{ chatId }` clones; `{ chatId, messageId, position }` forks. The older + * `{ chatId, throughMessageId }` shape remains a fork after that reply. + */ export function parseChatCopyRequest(value: unknown): ParsedChatCopyRequest { const record = exactRecord(value, COPY_KEYS, "chat copy request"); + const chatId = boundedId(record.chatId, "chat id"); + if (record.throughMessageId !== undefined) { + if (record.messageId !== undefined || record.position !== undefined) { + throw new Error("Invalid chat copy request."); + } + return { + chatId, + forkAt: { messageId: boundedId(record.throughMessageId, "turn id"), position: "after" }, + }; + } + if (record.messageId === undefined && record.position === undefined) return { chatId }; + if (record.position !== "after" && record.position !== "before") { + throw new Error("Invalid fork position."); + } return { - chatId: boundedId(record.chatId, "chat id"), - throughMessageId: - record.throughMessageId === undefined - ? undefined - : boundedId(record.throughMessageId, "turn id"), + chatId, + forkAt: { messageId: boundedId(record.messageId, "message id"), position: record.position }, }; } diff --git a/main/handlers/chats.ts b/main/handlers/chats.ts index 230a7fe684..d2fad67d8d 100644 --- a/main/handlers/chats.ts +++ b/main/handlers/chats.ts @@ -342,10 +342,13 @@ export function registerChatHistoryHandlers(): void { throw new Error(appendReconciliationFailureMessage("blocked")); } }; + if (parsed.forkAt?.position === "before") { + throw new Error("Bot chats can only be forked after a reply."); + } const copied = await botApplicationService.copyChat({ botId: source.botId, sourceChatId: parsed.chatId, - throughAssistantMessageId: parsed.throughMessageId, + throughAssistantMessageId: parsed.forkAt?.messageId, assertCurrent, }); ipcMain.broadcast("chats:metadata-updated", { @@ -385,10 +388,7 @@ export function registerChatHistoryHandlers(): void { if (!(await configStore.getWorkspace(workspaceId))) { throw new Error("The chat workspace is no longer available."); } - const htmlMediaIds = selectedHtmlArtifactMediaIds( - source.messages, - parsed.throughMessageId, - ); + const htmlMediaIds = selectedHtmlArtifactMediaIds(source.messages, parsed.forkAt); const targetChatId = randomUUID(); let preparedHtmlArtifacts: ChatHtmlArtifactV1[] = []; const copied = await (async () => { @@ -397,7 +397,7 @@ export function registerChatHistoryHandlers(): void { sourceChatId: parsed.chatId, targetChatId, expectedWorkspaceId: workspaceId, - throughAssistantMessageId: parsed.throughMessageId, + forkAt: parsed.forkAt, assertCurrent, beforeInstall: async () => { if (htmlMediaIds.length === 0) return; diff --git a/main/services/chat-copy-artifacts.ts b/main/services/chat-copy-artifacts.ts index 2df0fdb2db..a04b1aa874 100644 --- a/main/services/chat-copy-artifacts.ts +++ b/main/services/chat-copy-artifacts.ts @@ -1,18 +1,28 @@ import type { ChatMessage } from "./types.js"; +import type { ChatForkPosition } from "../../renderer/shared/chat-copy-contract.js"; /** Collects the artifact payload copied by a clone or fork in one bounded pass. */ export function selectedHtmlArtifactMediaIds( messages: readonly ChatMessage[], - throughAssistantMessageId?: string, + cut?: string | { messageId: string; position: ChatForkPosition }, ): string[] { + const boundary = typeof cut === "string" ? { messageId: cut, position: "after" as const } : cut; const mediaIds: string[] = []; - let foundBoundary = throughAssistantMessageId === undefined; + let foundBoundary = boundary === undefined; for (const message of messages) { + if ( + boundary?.position === "before" && + message.id === boundary.messageId && + message.role === "user" + ) { + foundBoundary = true; + break; + } for (const artifact of message.htmlArtifacts ?? []) mediaIds.push(artifact.mediaId); if ( - throughAssistantMessageId !== undefined && - message.id === throughAssistantMessageId && + boundary?.position === "after" && + message.id === boundary.messageId && message.role === "assistant" ) { foundBoundary = true; @@ -21,7 +31,11 @@ export function selectedHtmlArtifactMediaIds( } if (!foundBoundary) { - throw new Error("The selected fork point is not a completed assistant turn."); + throw new Error( + boundary?.position === "before" + ? "The selected message is no longer in this chat." + : "The selected fork point is not a completed assistant turn.", + ); } return mediaIds; } diff --git a/main/services/chat-session-copy.test.ts b/main/services/chat-session-copy.test.ts index 2d3278e178..aeaee5bed2 100644 --- a/main/services/chat-session-copy.test.ts +++ b/main/services/chat-session-copy.test.ts @@ -151,6 +151,119 @@ test("clone and fork copy visible linear history with fresh identities", async ( } }); +test("forks record lineage, number titles, and can cut before a prompt", async (t) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-fork-")); + t.after(() => fs.rm(directory, { recursive: true, force: true })); + const store = createChatStore(async () => directory); + const chat = await store.create({ title: "Plan trip", workspaceId: "workspace-fork" }); + const first = await store.appendMessage(chat.id, { role: "user", content: "Where to go?" }); + const firstReply = await store.appendMessage(chat.id, { role: "assistant", content: "Lisbon." }); + const second = await store.appendMessage(chat.id, { + role: "user", + content: "And for food?", + attachments: [{ + id: "attachment-menu", + name: "menu.txt", + mimeType: "text/plain", + kind: "text", + size: 4, + text: "menu", + }], + }); + await store.appendMessage(chat.id, { role: "assistant", content: "Pastéis." }); + const firstUserId = first.messages[first.messages.length - 1]!.id; + const firstReplyId = firstReply.messages[firstReply.messages.length - 1]!.id; + const secondUserId = second.messages[second.messages.length - 1]!.id; + + const after = await store.copyVisibleHistory({ + sourceChatId: chat.id, + forkAt: { messageId: firstReplyId, position: "after" }, + }); + assert.equal(after.title, "Plan trip (fork)"); + assert.deepEqual(after.messages.map(({ content }) => content), ["Where to go?", "Lisbon."]); + assert.deepEqual( + { ...after.forkedFrom, at: undefined }, + { chatId: chat.id, messageId: firstReplyId, position: "after", at: undefined }, + ); + + // Editing the second prompt keeps everything strictly before it. + const before = await store.copyVisibleHistory({ + sourceChatId: chat.id, + forkAt: { messageId: secondUserId, position: "before" }, + }); + assert.equal(before.title, "Plan trip (fork 2)"); + assert.deepEqual(before.messages.map(({ content }) => content), ["Where to go?", "Lisbon."]); + assert.equal(before.forkedFrom?.position, "before"); + + // Forking a fork numbers against the shared base title instead of stacking suffixes. + const nested = await store.copyVisibleHistory({ + sourceChatId: after.id, + forkAt: { messageId: after.messages[1]!.id, position: "after" }, + }); + assert.equal(nested.title, "Plan trip (fork 3)"); + assert.equal(nested.forkedFrom?.chatId, after.id); + + // A plain clone stays a copy with no lineage. + const clone = await store.copyVisibleHistory({ sourceChatId: chat.id }); + assert.equal(clone.forkedFrom, undefined); + + await assert.rejects( + store.copyVisibleHistory({ + sourceChatId: chat.id, + forkAt: { messageId: firstUserId, position: "before" }, + }), + /nothing comes before/iu, + ); + await assert.rejects( + store.copyVisibleHistory({ + sourceChatId: chat.id, + forkAt: { messageId: firstReplyId, position: "before" }, + }), + /your messages/iu, + ); + await assert.rejects( + store.copyVisibleHistory({ + sourceChatId: chat.id, + forkAt: { messageId: secondUserId, position: "after" }, + }), + /completed assistant turn/iu, + ); + + // Lineage survives a restart and stays visible after the source is deleted. + await store.remove(chat.id); + const restarted = createChatStore(async () => directory); + const listed = await restarted.list("workspace-fork"); + assert.equal(listed.find((meta) => meta.id === after.id)?.forkedFrom?.chatId, chat.id); + assert.equal(listed.find((meta) => meta.id === clone.id)?.forkedFrom, undefined); + assert.equal((await restarted.get(before.id))?.forkedFrom?.messageId, secondUserId); +}); + +test("a corrupt fork lineage is dropped without hiding the chat", async (t) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-fork-lineage-")); + t.after(() => fs.rm(directory, { recursive: true, force: true })); + const store = createChatStore(async () => directory); + const chat = await store.create({ title: "Source", workspaceId: "workspace-lineage" }); + await store.appendMessage(chat.id, { role: "user", content: "Hello" }); + const reply = await store.appendMessage(chat.id, { role: "assistant", content: "Hi" }); + const fork = await store.copyVisibleHistory({ + sourceChatId: chat.id, + forkAt: { messageId: reply.messages[reply.messages.length - 1]!.id, position: "after" }, + }); + + const file = path.join(directory, `${fork.id}.json`); + const payload = JSON.parse(await fs.readFile(file, "utf8")) as Record; + payload.forkedFrom = { chatId: "../escape", messageId: "m", position: "sideways", at: -1 }; + await fs.writeFile(file, JSON.stringify(payload)); + await fs.rm(path.join(directory, "index.json"), { force: true }); + + const restarted = createChatStore(async () => directory); + const reopened = await restarted.get(fork.id); + assert.equal(reopened?.title, "Source (fork)"); + assert.equal(reopened?.forkedFrom, undefined); + const listed = await restarted.list("workspace-lineage"); + assert.ok(listed.some((meta) => meta.id === fork.id && meta.forkedFrom === undefined)); +}); + test("bulk copies use collision-resistant identities even when Math.random repeats", async (t) => { const directory = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-copy-ids-")); t.after(() => fs.rm(directory, { recursive: true, force: true })); diff --git a/main/services/chat-store-core.ts b/main/services/chat-store-core.ts index cb09b1865c..51e6905248 100644 --- a/main/services/chat-store-core.ts +++ b/main/services/chat-store-core.ts @@ -20,6 +20,11 @@ import { deriveChatTitleSeed, } from "./chat-title-policy.js"; import type { Chat, ChatMessage, ChatMeta } from "./types.js"; +import { + nextForkTitle, + parseChatForkLineageV1, + type ChatForkPosition, +} from "../../renderer/shared/chat-copy-contract.js"; import { parseGenerationTimeline } from "../../renderer/shared/generation-timeline.js"; import { parseSubagentMessageReferenceV1 } from "../../renderer/shared/subagent-runs.js"; import { migrateLegacyPiProviderId } from "../../renderer/shared/google-provider.js"; @@ -379,7 +384,8 @@ export function createChatStore( (meta.lastAssistantAt === undefined || (typeof meta.lastAssistantAt === "number" && Number.isSafeInteger(meta.lastAssistantAt) && - meta.lastAssistantAt >= 0)) + meta.lastAssistantAt >= 0)) && + (meta.forkedFrom === undefined || parseChatForkLineageV1(meta.forkedFrom) !== undefined) ); } @@ -751,6 +757,19 @@ export function createChatStore( if (policy !== "pure") await quarantinePayload(id, policy); return null; } + if ( + parsed !== null && + typeof parsed === "object" && + !Array.isArray(parsed) && + Object.prototype.hasOwnProperty.call(parsed, "forkedFrom") + ) { + // Lineage is display-only provenance: a damaged value is dropped rather + // than hiding the whole transcript. + const record = parsed as Record; + const lineage = parseChatForkLineageV1(record.forkedFrom); + if (lineage) record.forkedFrom = lineage; + else delete record.forkedFrom; + } const messages = (parsed as { messages?: unknown } | null)?.messages; if ( policy !== "pure" && @@ -912,6 +931,7 @@ export function createChatStore( ...(boundedPreview ? { preview: boundedPreview } : {}), summaryRevision: chatSummaryRevision(chat), ...(lastAssistantAt !== undefined ? { lastAssistantAt, lastAssistantSequence } : {}), + ...(chat.forkedFrom ? { forkedFrom: chat.forkedFrom } : {}), createdAt: chat.createdAt, updatedAt: chat.updatedAt, }; @@ -1192,7 +1212,10 @@ export function createChatStore( /** Main-owned destination for copies that move legacy Bot history into its hidden home. */ targetWorkspaceId?: string; expectedWorkspaceId?: string; + /** Legacy cut used by Bot copies: through a settled assistant reply, without lineage. */ throughAssistantMessageId?: string; + /** Fork cut that records `forkedFrom` lineage on the new chat. */ + forkAt?: { messageId: string; position: ChatForkPosition }; assertCurrent?: () => void; /** Prepare dependent durable records before this chat becomes visible. */ beforeInstall?: (chat: Chat) => void | Promise; @@ -1212,16 +1235,30 @@ export function createChatStore( ); } + const cut = + input.forkAt ?? + (input.throughAssistantMessageId !== undefined + ? { messageId: input.throughAssistantMessageId, position: "after" as const } + : undefined); + // Inclusive index of the last copied message. let throughIndex = source.messages.length - 1; - if (input.throughAssistantMessageId !== undefined) { + if (cut?.position === "after") { throughIndex = source.messages.findIndex( - (message) => - message.id === input.throughAssistantMessageId && - message.role === "assistant", + (message) => message.id === cut.messageId && message.role === "assistant", ); if (throughIndex < 0) { throw new Error("Choose a completed assistant turn to fork from."); } + } else if (cut?.position === "before") { + const userIndex = source.messages.findIndex( + (message) => message.id === cut.messageId && message.role === "user", + ); + if (userIndex < 0) { + throw new Error("Choose one of your messages to edit in a fork."); + } + throughIndex = userIndex - 1; + } + if (cut) { let hasVisibleUser = false; for (let index = 0; index <= throughIndex; index += 1) { if (source.messages[index]?.role === "user") { @@ -1230,7 +1267,11 @@ export function createChatStore( } } if (!hasVisibleUser) { - throw new Error("The selected turn has no user message to copy."); + throw new Error( + cut.position === "before" + ? "Nothing comes before the first message to fork." + : "The selected turn has no user message to copy.", + ); } } @@ -1248,13 +1289,23 @@ export function createChatStore( } }; const metadata = projectVisibleChatMetadata(source); - const suffix = input.throughAssistantMessageId ? " (fork)" : " (copy)"; - const maximumBaseLength = Math.max(1, 120 - suffix.length); - const title = `${Array.from( - metadata.title.slice(0, maximumBaseLength * 2), - ) - .slice(0, maximumBaseLength) - .join("")}${suffix}`; + let title: string; + if (cut) { + const destinationWorkspaceId = + input.targetWorkspaceId ?? metadata.workspaceId ?? DEFAULT_WORKSPACE_ID; + const siblings = (await withIndexLock(() => loadIndex())).filter( + (entry) => (entry.workspaceId ?? DEFAULT_WORKSPACE_ID) === destinationWorkspaceId, + ); + title = nextForkTitle(metadata.title, siblings.map((entry) => entry.title)); + } else { + const suffix = " (copy)"; + const maximumBaseLength = Math.max(1, 120 - suffix.length); + title = `${Array.from( + metadata.title.slice(0, maximumBaseLength * 2), + ) + .slice(0, maximumBaseLength) + .join("")}${suffix}`; + } chargedBytes += 1_024; charge(title); charge(input.targetWorkspaceId ?? metadata.workspaceId); @@ -1321,6 +1372,16 @@ export function createChatStore( botId: source.botId, providerId: metadata.providerId, model: metadata.model, + ...(input.forkAt && !source.botId + ? { + forkedFrom: { + chatId: source.id, + messageId: input.forkAt.messageId, + position: input.forkAt.position, + at: now, + }, + } + : {}), createdAt: now, updatedAt: now, messages: copiedMessages, diff --git a/main/services/types.ts b/main/services/types.ts index 8e8a6e1079..172a4f1255 100644 --- a/main/services/types.ts +++ b/main/services/types.ts @@ -14,6 +14,7 @@ import type { SubagentMessageReferenceV1 } from "../../renderer/shared/subagent- import type { SkillProvenanceV1 } from "../../renderer/shared/slash-commands.js"; import type { ProviderFailureV1 } from "../../renderer/shared/provider-failure.js"; import type { ChatHtmlArtifactV1 } from "../../renderer/shared/chat-artifacts.js"; +import type { ChatForkLineageV1 } from "../../renderer/shared/chat-copy-contract.js"; import type { AssistantMessage } from "@earendil-works/pi-ai"; import type { ProviderArtwork } from "../../renderer/shared/provider-artwork.js"; import type { WebSearchSettingsV2 } from "./web-search-provider-registry-core.js"; @@ -432,6 +433,8 @@ export interface ChatMeta { */ lastAssistantAt?: number; lastAssistantSequence?: number; + /** Main-owned provenance for chats created by Fork; absent for ordinary chats and copies. */ + forkedFrom?: ChatForkLineageV1; createdAt: number; updatedAt: number; } diff --git a/package.json b/package.json index fbf9ec144c..3fb4018952 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "test:model-insights": "tsx --test main/services/openrouter-benchmark.test.ts main/services/models.test.ts main/services/provider-model-info-core.test.ts main/handlers/ipc-contract.test.ts", "test:model-pad": "tsx --test renderer/components/settings/model-pad-settings.test.tsx renderer/lib/google-provider-migration.test.ts renderer/lib/model-pad-layout.test.ts renderer/lib/model-picker-data.test.ts renderer/lib/pi-provider-display.test.ts", "test:command-system": "tsx --test main/services/native-menu-command-contract.test.ts main/services/renderer-readiness-core.test.ts main/services/shortcut-registration-core.test.ts main/services/shortcut-transaction-core.test.ts main/services/superseding-task-core.test.ts renderer/lib/appearance-intent.test.ts renderer/lib/command-palette-contract.test.ts renderer/lib/command-palette-recent.test.ts renderer/lib/command-system-core.test.ts renderer/lib/shortcut-settings-contract.test.ts renderer/lib/use-model-selection.test.ts renderer/shared/keybindings.test.ts renderer/lib/composer-type-focus.test.ts renderer/lib/held-modifier-reveal.test.ts", - "test:slash-commands": "tsx --test main/services/generation-initialization-terminal.test.ts main/handlers/attachments.contract.test.ts main/handlers/chat.parse.test.ts main/handlers/chat-create-params.test.ts main/handlers/chat-session-params.test.ts main/handlers/worktree-create-params.test.ts main/services/chat-workspace-authority.test.ts main/handlers/chats.append.contract.test.ts main/services/attachment-contract.test.ts main/services/attachments.test.ts main/services/chat-append-commit.test.ts main/services/chat-export.test.ts main/services/chat-message-contract.test.ts main/services/chat-session-copy.test.ts main/services/chat-store-core.test.ts main/services/empty-chat-migration.test.ts main/services/chat-first-message-commit.test.ts main/services/chat-run-input-admission.test.ts main/services/chat-turn-admission.test.ts main/services/generation-messages.test.ts main/services/provider-auth-flow-core.test.ts main/services/provider-list-core.test.ts main/services/provider-artwork-core.test.ts main/services/provider-artwork.test.ts main/services/scheduled-chat-creation.test.ts main/services/skill-invocation-flow.integration.test.ts main/services/skill-invocation-turn.test.ts main/services/skill-registry-core.test.ts main/services/skill-registry.test.ts main/services/skill-tools.test.ts main/services/skills-discovery.test.ts renderer/components/assistant/assistant-ui.test.tsx renderer/components/assistant/use-assistant-chat.test.ts renderer/components/composer.test.tsx renderer/lib/chat-message-queue.test.ts renderer/lib/chat-draft.test.ts renderer/components/message-bubble.test.tsx renderer/lib/chat-copy-view.test.ts renderer/lib/codex-provider-cache.test.ts renderer/lib/computer-use-control.test.ts renderer/lib/ipc-stream.test.ts renderer/lib/skill-catalog-workspace.test.ts renderer/lib/slash-command-actions.test.ts renderer/lib/slash-command-core.test.ts renderer/lib/slash-command-performance.test.ts renderer/main/chat-transition.test.tsx renderer/shared/attachment-contract.test.ts renderer/shared/chat-message-contract.test.ts renderer/shared/slash-commands.test.ts renderer/components/settings/skills-settings.test.tsx renderer/lib/composer-type-focus.test.ts renderer/lib/compaction-command-admission.test.ts", + "test:slash-commands": "tsx --test main/services/generation-initialization-terminal.test.ts main/handlers/attachments.contract.test.ts main/handlers/chat.parse.test.ts main/handlers/chat-create-params.test.ts main/handlers/chat-session-params.test.ts main/handlers/worktree-create-params.test.ts main/services/chat-workspace-authority.test.ts main/handlers/chats.append.contract.test.ts main/services/attachment-contract.test.ts main/services/attachments.test.ts main/services/chat-append-commit.test.ts main/services/chat-export.test.ts main/services/chat-message-contract.test.ts main/services/chat-session-copy.test.ts main/services/chat-store-core.test.ts main/services/empty-chat-migration.test.ts main/services/chat-first-message-commit.test.ts main/services/chat-run-input-admission.test.ts main/services/chat-turn-admission.test.ts main/services/generation-messages.test.ts main/services/provider-auth-flow-core.test.ts main/services/provider-list-core.test.ts main/services/provider-artwork-core.test.ts main/services/provider-artwork.test.ts main/services/scheduled-chat-creation.test.ts main/services/skill-invocation-flow.integration.test.ts main/services/skill-invocation-turn.test.ts main/services/skill-registry-core.test.ts main/services/skill-registry.test.ts main/services/skill-tools.test.ts main/services/skills-discovery.test.ts renderer/components/assistant/assistant-ui.test.tsx renderer/components/assistant/use-assistant-chat.test.ts renderer/components/composer.test.tsx renderer/lib/chat-message-queue.test.ts renderer/lib/chat-draft.test.ts renderer/components/message-bubble.test.tsx renderer/lib/chat-copy-view.test.ts renderer/shared/chat-copy-contract.test.ts renderer/lib/codex-provider-cache.test.ts renderer/lib/computer-use-control.test.ts renderer/lib/ipc-stream.test.ts renderer/lib/skill-catalog-workspace.test.ts renderer/lib/slash-command-actions.test.ts renderer/lib/slash-command-core.test.ts renderer/lib/slash-command-performance.test.ts renderer/main/chat-transition.test.tsx renderer/shared/attachment-contract.test.ts renderer/shared/chat-message-contract.test.ts renderer/shared/slash-commands.test.ts renderer/components/settings/skills-settings.test.tsx renderer/lib/composer-type-focus.test.ts renderer/lib/compaction-command-admission.test.ts", "test:rich-links": "tsx --test renderer/lib/rich-link.test.ts renderer/components/message-bubble.test.tsx renderer/lib/streaming-motion-contract.test.ts", "test:display-image": "tsx --test main/services/display-image-artifact-store.test.ts main/services/display-image-extension.test.ts main/services/generation-timeline.test.ts renderer/components/message-bubble.test.tsx renderer/lib/ipc-stream.test.ts", "test:ask-user-question": "tsx --test renderer/shared/ask-user-question.test.ts main/services/ask-user-question-coordinator.test.ts main/services/ask-user-question-extension.test.ts renderer/components/ask-user-question-composer.test.ts renderer/components/ask-user-question-expiry-notice.test.tsx", diff --git a/renderer/components/chat-sidebar.tsx b/renderer/components/chat-sidebar.tsx index a4d39b300d..5e85477e80 100644 --- a/renderer/components/chat-sidebar.tsx +++ b/renderer/components/chat-sidebar.tsx @@ -1,4 +1,5 @@ import { createChatDraft, discardChatDraft } from "../lib/chat-draft"; +import { forkedFromLabel } from "../lib/chat-copy-view"; // Unified workspace/chat sidebar with workspace-grouped, recent, and // needs-attention views, route-driven selection, and workspace/chat actions. @@ -47,6 +48,7 @@ import { Folder, FolderPlus, FolderGit2, + GitFork, GitPullRequest, Loader2, MoreHorizontal, @@ -702,6 +704,10 @@ export function ChatSidebar({ activeChatId, activeRemoteChat = null, titleReveal const readMarkers = useChatReadMarkers(); const appendReconciliationRequired = useAppendReconciliationRequired(); const chats = useAllRegularChats(workspaces.length > 0); + const chatTitlesById = React.useMemo( + () => new Map((chats.data ?? []).map((chat) => [chat.id, chat.title])), + [chats.data], + ); const foundationModels = useFoundationModelsConnection(capabilities.appleFoundationModels); const [search, setSearch] = React.useState(""); const initialPreferences = React.useMemo( @@ -1310,6 +1316,19 @@ export function ChatSidebar({ activeChatId, activeRemoteChat = null, titleReveal const showsState = rowState !== "idle"; // The open chat is being viewed, so its own output never reads as unread. const unread = chat.id !== activeChatId && isChatUnread(chat.lastAssistantAt, readMarkers, chat.id, chat.lastAssistantSequence); + const forkedFrom = chat.forkedFrom + ? forkedFromLabel(chatTitlesById.get(chat.forkedFrom.chatId)) + : undefined; + const titleContent = + titleReveal?.chatId === chat.id ? ( + + ) : ( + chat.title + ); return ( @@ -1321,15 +1340,16 @@ export function ChatSidebar({ activeChatId, activeRemoteChat = null, titleReveal ) : undefined } aria-busy={renamingWithAppleId === chat.id || rowState === "working"} + aria-description={forkedFrom} + data-forked={forkedFrom ? "true" : undefined} title={ - titleReveal?.chatId === chat.id ? ( - + forkedFrom ? ( + + ) : ( - chat.title + titleContent ) } trailing={ diff --git a/renderer/components/composer.test.tsx b/renderer/components/composer.test.tsx index e60f637c2c..58b4d3dd24 100644 --- a/renderer/components/composer.test.tsx +++ b/renderer/components/composer.test.tsx @@ -330,7 +330,6 @@ test("selected session slash commands dispatch through explicit Aiden-owned work assert.match(composer, /readOnly=\{composerInputLocked \|\| firstSendPending\}/u); assert.match(composer, /role="status" aria-live="polite"/u); assert.match(branchPicker, /openManagedWorktree \? "worktree" : null/u); - assert.match(chatPane, /chatsApi\.copyVisibleHistory\([\s\S]{0,100}throughAssistantMessageId/u); assert.match(chatPane, /logoutBuiltinProvider\(qc, providerId\)/u); assert.match(chatPane, /provider\.canLogout === true/u); assert.match(ipc, /"chats:export", \{ chatId \}/u); diff --git a/renderer/components/composer.tsx b/renderer/components/composer.tsx index c69b083b4d..81c6a244f4 100644 --- a/renderer/components/composer.tsx +++ b/renderer/components/composer.tsx @@ -99,6 +99,7 @@ import { saveComposerDraftText, settleComposerSubmission, subscribeGuidanceRestore, + takeComposerAttachmentSeed, } from "../lib/composer-draft-store"; import { COMPOSER_SLASH_PALETTE_ID, @@ -109,7 +110,7 @@ import { import type { SettingsSection } from "../shared/settings-section"; import type { SkillCatalogEntry, SkillInvocationV1, SkillSource } from "../shared/slash-commands"; import { filterForkTurnChoices, forkTurnEligibility } from "../lib/chat-copy-view"; -import { MAX_FORK_QUERY_CODE_UNITS } from "../shared/chat-copy-contract"; +import { MAX_FORK_QUERY_CODE_UNITS, type ChatForkPosition } from "../shared/chat-copy-contract"; import { attachmentInlineBytesRemaining, attachmentSlotsRemaining, @@ -215,7 +216,8 @@ interface ComposerProps { sessionChat?: Chat; authenticatedProviders?: Array<{ id: string; label: string; detail: string }>; onCloneChat?: () => Promise; - onForkChat?: (throughAssistantMessageId: string) => Promise; + /** `after` keeps the reply; `before` cuts ahead of a prompt and pre-fills it for editing. */ + onForkChat?: (messageId: string, position: ChatForkPosition) => Promise; onExportChat?: () => Promise<"saved" | "cancelled">; onCompactChat?: (engine?: CompactionEngine) => Promise< | { @@ -454,6 +456,10 @@ export function Composer({ attachmentsRef.current = next; setAttachments(next); }, []); + React.useEffect(() => { + const seed = takeComposerAttachmentSeed(chatId); + if (seed) updateAttachments(seed); + }, [chatId, updateAttachments]); // Ambient projections (context pressure) follow the draft on a quiet cadence. const onDraftChangeRef = React.useRef(onDraftChange); React.useLayoutEffect(() => { @@ -913,14 +919,14 @@ export function Composer({ ); const forkFromTurn = React.useCallback( - async (messageId: string) => { + async (messageId: string, position: ChatForkPosition = "after") => { if (!onForkChat || sessionCommandBusy) return; sessionCommandBusyRef.current = true; setSessionCommandStatus("Forking chat…"); try { - await onForkChat(messageId); + await onForkChat(messageId, position); setForkDialogOpen(false); - toast.success("Chat forked"); + toast.success(position === "before" ? "Forked — edit your message and send" : "Chat forked"); } catch (error) { toast.error(error instanceof Error ? error.message : "Couldn't fork this chat."); } finally { @@ -2522,7 +2528,7 @@ export function Composer({ if (!open) setForkQuery(""); }} title="Fork from a completed turn" - description="The new chat copies visible messages and attachments through the selected response. Private reasoning, tool state, and subagent runtime records are omitted." + description="Fork keeps visible messages and attachments through the selected response. Edit in fork keeps everything before that turn's prompt and puts the prompt in the composer. Private reasoning, tool state, and subagent runtime records are omitted." confirmHidden busy={sessionCommandBusy} returnFocus={() => inputRef?.current ?? null} @@ -2549,10 +2555,10 @@ export function Composer({
    {visibleForkTurns.length > 0 ? ( visibleForkTurns.map((turn) => ( -
  • +
  • +
  • )) ) : ( diff --git a/renderer/components/fork-message-button.tsx b/renderer/components/fork-message-button.tsx new file mode 100644 index 0000000000..9bb642bb64 --- /dev/null +++ b/renderer/components/fork-message-button.tsx @@ -0,0 +1,41 @@ +// Transcript hover action that forks the chat at one message. Settled replies +// offer "Fork from here"; sent prompts offer "Edit in fork". + +import { GitFork, SquarePen } from "lucide-react"; +import { cn } from "../lib/ui-utils"; + +export interface MessageForkAction { + onFork: () => void; + /** When set, forking is unavailable right now and this explains why. */ + disabledReason?: string | null; +} + +interface ForkMessageButtonProps { + action: MessageForkAction; + kind: "fork" | "edit"; + className?: string; +} + +export function ForkMessageButton({ action, kind, className }: ForkMessageButtonProps) { + const label = kind === "fork" ? "Fork from here" : "Edit in fork"; + const disabledReason = action.disabledReason ?? null; + const Icon = kind === "fork" ? GitFork : SquarePen; + return ( + + ); +} diff --git a/renderer/components/message-actions.tsx b/renderer/components/message-actions.tsx index 8fdbad7a71..6155e5506a 100644 --- a/renderer/components/message-actions.tsx +++ b/renderer/components/message-actions.tsx @@ -4,6 +4,7 @@ import type * as React from "react"; import { CopyButton } from "./copy-button"; +import { ForkMessageButton, type MessageForkAction } from "./fork-message-button"; import { ReadAloudButton, type ReadAloudActionProps } from "./read-aloud-button"; interface MessageActionsProps { @@ -14,9 +15,11 @@ interface MessageActionsProps { hidden?: boolean; /** Always-visible trailing turn facts; they share the row so it never grows. */ footer?: React.ReactNode; + /** Present on settled replies that can start a fork. */ + fork?: MessageForkAction; } -export function MessageActions({ copyText, readAloud, hidden, footer }: MessageActionsProps) { +export function MessageActions({ copyText, readAloud, hidden, footer, fork }: MessageActionsProps) { return (
    + {fork ? ( + + ) : null} {readAloud ? ( { assert.ok(alert, "the failure reason sits inside the alert region"); assert.match(alert[0], /Generation failed/u); }); + +test("settled turns offer fork actions only when the chat can fork", () => { + const render = (props: { onFork?: () => void; forkDisabledReason?: string | null }) => + renderToStaticMarkup( + undefined} + agentActivity={null} + error={null} + {...props} + />, + ); + + const enabled = render({ onFork: () => undefined }); + // Each sent prompt can be edited in a fork; only the settled reply forks after itself. + assert.equal((enabled.match(/aria-label="Edit in fork"/gu) ?? []).length, 2); + assert.equal((enabled.match(/aria-label="Fork from here"/gu) ?? []).length, 1); + const forkAt = enabled.indexOf('aria-label="Fork from here"'); + assert.ok(forkAt > enabled.indexOf("First answer")); + assert.ok(forkAt < enabled.indexOf("Second question")); + assert.doesNotMatch(enabled, /aria-disabled="true"[^>]*data-fork-action/u); + + const busy = render({ onFork: () => undefined, forkDisabledReason: "Finish the current response" }); + assert.equal((busy.match(/aria-disabled="true"/gu) ?? []).length, 3); + assert.equal((busy.match(/title="Finish the current response"/gu) ?? []).length, 3); + + assert.doesNotMatch(render({}), /data-fork-action/u); +}); diff --git a/renderer/components/message-bubble.tsx b/renderer/components/message-bubble.tsx index a8886bc649..766004a867 100644 --- a/renderer/components/message-bubble.tsx +++ b/renderer/components/message-bubble.tsx @@ -8,6 +8,7 @@ import { Markdown } from "./markdown"; import { StreamingMarkdownReveal } from "./streaming-markdown-reveal"; import { CopyButton } from "./copy-button"; import { MessageActions } from "./message-actions"; +import { ForkMessageButton, type MessageForkAction } from "./fork-message-button"; import type { ReadAloudActionProps } from "./read-aloud-button"; import type { Attachment, ChatMessage } from "../lib/types"; import type { SkillProvenanceV1 } from "../shared/slash-commands"; @@ -37,6 +38,8 @@ export interface MessageBubbleProps { richLinks?: boolean; /** Settled turn facts rendered at the trailing edge of the action row. */ footer?: React.ReactNode; + /** Fork from a settled reply, or edit a sent prompt in a fork. */ + fork?: MessageForkAction; } /** Isolate untrusted model-formatting failures to the individual message. */ @@ -64,6 +67,7 @@ export function MessageBubble({ readAloud, richLinks = true, footer, + fork, }: MessageBubbleProps) { if (role === "user") { return ( @@ -88,12 +92,23 @@ export function MessageBubble({
    ) : null} - {content ? ( - + {content || fork ? ( +
    + {fork ? ( + + ) : null} + {content ? ( + + ) : null} +
    ) : null}
@@ -127,6 +142,7 @@ export function MessageBubble({ readAloud={readAloud} hidden={Boolean(streaming && !streamComplete)} footer={footer} + fork={streaming ? undefined : fork} /> ) : null} diff --git a/renderer/components/message-list.tsx b/renderer/components/message-list.tsx index e0807ab25a..c5233c5e1a 100644 --- a/renderer/components/message-list.tsx +++ b/renderer/components/message-list.tsx @@ -7,6 +7,8 @@ import { ActivityFeed } from "./activity-feed"; import { EventPresence } from "./event-presence"; import { SafeMessageBubble } from "./message-bubble"; import type { ReadAloudActionProps } from "./read-aloud-button"; +import type { MessageForkAction } from "./fork-message-button"; +import type { ChatForkPosition } from "../shared/chat-copy-contract"; import { MessageAttachmentPreviewProvider, MessageAttachments } from "./message-attachments"; import { ReasoningBlock } from "./reasoning-block"; import { SubagentChips } from "./subagent-chips"; @@ -64,6 +66,10 @@ interface MessageListProps { /** Message id whose whole response may host the read-aloud action. */ readAloudMessageId?: string; readAloud?: ReadAloudActionProps; + /** Fork the chat at a settled message; absent where forking is unsupported. */ + onFork?: (messageId: string, position: ChatForkPosition) => void; + /** Shown on the fork actions while the chat is busy. */ + forkDisabledReason?: string | null; } interface AssistantResponseProps { @@ -80,6 +86,7 @@ interface AssistantResponseProps { richLinks?: boolean; /** Settled turn facts; joins the tail action row, or stands alone without prose. */ footer?: React.ReactNode; + fork?: MessageForkAction; } function AssistantResponse({ @@ -94,6 +101,7 @@ function AssistantResponse({ readAloud, richLinks = true, footer, + fork, }: AssistantResponseProps) { const rows = assistantPresentationRows(content, timeline, reasoning ?? ""); const reasoningActive = hasActiveThinkingStep(timeline ?? null); @@ -127,6 +135,7 @@ function AssistantResponse({ readAloud={readAloud} richLinks={richLinks} footer={footer} + fork={fork} /> ) : null} {attachments?.length ? ( @@ -188,6 +197,7 @@ function AssistantResponse({ readAloud={isLastText ? readAloud : undefined} richLinks={richLinks} footer={isLastText ? footer : undefined} + fork={isLastText ? fork : undefined} /> ); })} @@ -210,6 +220,10 @@ interface SettledMessageRowProps { richLinks: boolean; subagentsEnabled: boolean; onOpenSubagent: (runId: string, trigger: HTMLButtonElement) => void; + /** Stable across renders so settled rows stay memoized. */ + onFork?: (messageId: string, position: ChatForkPosition) => void; + /** Settled user prompts with an earlier prompt can be edited in a fork. */ + forkDisabledReason?: string | null; } /** @@ -222,7 +236,17 @@ const SettledMessageRow = React.memo(function SettledMessageRow({ richLinks, subagentsEnabled, onOpenSubagent, + onFork, + forkDisabledReason, }: SettledMessageRowProps) { + const fork = React.useMemo(() => { + if (!onFork || (message.role !== "user" && message.role !== "assistant")) return undefined; + const position: ChatForkPosition = message.role === "user" ? "before" : "after"; + return { + onFork: () => onFork(message.id, position), + disabledReason: forkDisabledReason, + }; + }, [forkDisabledReason, message.id, message.role, onFork]); return (
{message.role === "assistant" ? ( @@ -235,6 +259,7 @@ const SettledMessageRow = React.memo(function SettledMessageRow({ readAloud={readAloud} richLinks={richLinks} footer={settledTurnFooter(message)} + fork={fork} subagentChips={ subagentsEnabled && message.subagents ? ( @@ -251,6 +276,7 @@ const SettledMessageRow = React.memo(function SettledMessageRow({ content={message.content} attachments={message.attachments} skill={message.skill} + fork={fork} /> )}
@@ -299,7 +325,18 @@ export function MessageList({ error, readAloudMessageId, readAloud, + onFork, + forkDisabledReason = null, }: MessageListProps) { + const onForkRef = React.useRef(onFork); + React.useLayoutEffect(() => { + onForkRef.current = onFork; + }, [onFork]); + const forkEnabled = Boolean(onFork); + const stableOnFork = React.useCallback( + (messageId: string, position: ChatForkPosition) => onForkRef.current?.(messageId, position), + [], + ); const transcriptRef = React.useRef(null); const chipFocusCaptureRef = React.useRef(null); const persistedAttachmentIds = React.useMemo(() => { @@ -431,6 +468,8 @@ export function MessageList({ richLinks={message.id !== richLinkHandoffDuplicateId} subagentsEnabled={subagentsEnabled} onOpenSubagent={onOpenSubagent} + onFork={forkEnabled ? stableOnFork : undefined} + forkDisabledReason={forkDisabledReason} />, ); transcriptRows.push(...artifactFrames(`message:${message.id}`)); diff --git a/renderer/lib/chat-copy-view.test.ts b/renderer/lib/chat-copy-view.test.ts index 4f81c82f41..5ea54298b3 100644 --- a/renderer/lib/chat-copy-view.test.ts +++ b/renderer/lib/chat-copy-view.test.ts @@ -34,3 +34,18 @@ test("copy eligibility stops at the shared limit and keeps only searchable eligi assert.equal(filterForkTurnChoices(result.turns, "1")[0]?.turnNumber, 1); assert.deepEqual(filterForkTurnChoices(result.turns, "x".repeat(257)), []); }); + +test("each fork choice points Edit in fork at the prompt that opened its turn", () => { + const result = forkTurnEligibility([ + { id: "system", role: "system", content: "hidden", createdAt: 0 }, + { id: "u1", role: "user", content: "first", createdAt: 1 }, + { id: "a1", role: "assistant", content: "one", createdAt: 2 }, + { id: "a1b", role: "assistant", content: "one more", createdAt: 3 }, + { id: "u2", role: "user", content: "second", createdAt: 4 }, + { id: "a2", role: "assistant", content: "two", createdAt: 5 }, + ]); + assert.deepEqual( + result.turns.map(({ id, userMessageId }) => [id, userMessageId]), + [["a1", "u1"], ["a1b", "u1"], ["a2", "u2"]], + ); +}); diff --git a/renderer/lib/chat-copy-view.ts b/renderer/lib/chat-copy-view.ts index 6d7c5f8197..7710322b1b 100644 --- a/renderer/lib/chat-copy-view.ts +++ b/renderer/lib/chat-copy-view.ts @@ -8,7 +8,10 @@ import { import { boundedUnicodePrefix } from "../shared/unicode-prefix.js"; export interface ForkTurnChoice { + /** The settled assistant reply a plain fork keeps. */ id: string; + /** The prompt that opened this turn; Edit in fork cuts just before it. */ + userMessageId: string; label: string; createdAt: number; turnNumber: number; @@ -20,6 +23,7 @@ export function forkTurnEligibility(messages: readonly ChatMessage[]): { } { const turns: ForkTurnChoice[] = []; let latestUserLabel: string | undefined; + let latestUserId: string | undefined; let visibleMessageCount = 0; for (const message of messages) { if (message.role !== "user" && message.role !== "assistant") continue; @@ -34,9 +38,11 @@ export function forkTurnEligibility(messages: readonly ChatMessage[]): { latestUserLabel = preview ? Array.from(preview).slice(0, 96).join("") : "Attachment-only turn"; - } else if (latestUserLabel) { + latestUserId = message.id; + } else if (latestUserLabel && latestUserId) { turns.push({ id: message.id, + userMessageId: latestUserId, label: latestUserLabel, createdAt: message.createdAt, turnNumber: turns.length + 1, @@ -62,3 +68,9 @@ export function filterForkTurnChoices( : turns; return matches.slice(Math.max(0, matches.length - MAX_VISIBLE_FORK_CHOICES)); } + +/** Plain-language provenance for a forked chat; the source may have been deleted. */ +export function forkedFromLabel(sourceTitle: string | undefined): string { + const title = sourceTitle?.trim(); + return title ? `Forked from “${title}”` : "Forked from a deleted chat"; +} diff --git a/renderer/lib/composer-draft-store.ts b/renderer/lib/composer-draft-store.ts index 8b54f746e0..e9170b4eae 100644 --- a/renderer/lib/composer-draft-store.ts +++ b/renderer/lib/composer-draft-store.ts @@ -1,3 +1,5 @@ +import type { Attachment } from "./types"; + /** Device-local text drafts. Attachment bytes stay in the attachment picker. */ interface StoredComposerDraft { version: 1; @@ -55,9 +57,28 @@ export function settleComposerSubmission(chatId: string, accepted: boolean, curr } export function discardComposerDraft(chatId: string): void { + attachmentSeeds.delete(chatId); try { localStorage.removeItem(key(chatId)); } catch { /* Deletion still proceeds. */ } } +// One-shot, in-memory attachment seeds for a composer that is about to open +// (Edit in fork). Never persisted: attachment bytes stay out of storage. +const attachmentSeeds = new Map(); + +export function seedComposerAttachments(chatId: string, attachments: readonly Attachment[]): void { + const usable = attachments.filter((attachment) => + attachment.kind === "image" ? Boolean(attachment.data) : attachment.text !== undefined, + ); + if (usable.length > 0) attachmentSeeds.set(chatId, usable.map((attachment) => ({ ...attachment }))); + else attachmentSeeds.delete(chatId); +} + +export function takeComposerAttachmentSeed(chatId: string): Attachment[] | undefined { + const seed = attachmentSeeds.get(chatId); + attachmentSeeds.delete(chatId); + return seed; +} + type GuidanceRestoreListener = (guidance: readonly string[]) => void; const restoreListeners = new Map>(); const MAX_RESTORED_GUIDANCE = 32; diff --git a/renderer/lib/ipc.ts b/renderer/lib/ipc.ts index ad75de4bfd..753d792ab8 100644 --- a/renderer/lib/ipc.ts +++ b/renderer/lib/ipc.ts @@ -1,4 +1,5 @@ import type { CompactionEngine } from "../shared/compaction"; +import type { ChatForkPosition } from "../shared/chat-copy-contract"; import type { TtsJobSnapshot, TtsSafeError, @@ -1080,10 +1081,14 @@ export const chatsApi = { rename: (id: string, title: string) => invoke("chats:rename", id, title), renameWithFoundationModels: (id: string) => invoke("chats:renameWithFoundationModels", id), - copyVisibleHistory: (chatId: string, throughMessageId?: string) => + /** Clone the whole visible chat, or fork it at `forkAt`. */ + copyVisibleHistory: ( + chatId: string, + forkAt?: { messageId: string; position: ChatForkPosition }, + ) => invokeChatMutation("chats:copyVisibleHistory", { chatId, - ...(throughMessageId ? { throughMessageId } : {}), + ...(forkAt ? { messageId: forkAt.messageId, position: forkAt.position } : {}), }), export: (chatId: string) => invoke<{ status: "saved" | "cancelled" }>("chats:export", { chatId }), moveEmptyToWorkspace: (id: string, workspaceId: string) => diff --git a/renderer/lib/types.ts b/renderer/lib/types.ts index 5958eca5d8..553d65699a 100644 --- a/renderer/lib/types.ts +++ b/renderer/lib/types.ts @@ -15,6 +15,7 @@ import type { GoogleThinkingLevel } from "../shared/google-thinking"; import type { SubagentMessageReferenceV1 } from "../shared/subagent-runs"; import type { SkillProvenanceV1 } from "../shared/slash-commands"; import type { ProviderFailureV1 } from "../shared/provider-failure"; +import type { ChatForkLineageV1 } from "../shared/chat-copy-contract"; import type { ProviderArtwork } from "../shared/provider-artwork"; import type { BoundedNonSecretProviderConfig, @@ -632,6 +633,8 @@ export interface ChatMeta { /** createdAt of the newest assistant output; drives honest unread markers. */ lastAssistantAt?: number; lastAssistantSequence?: number; + /** Set when this chat was created by Fork. */ + forkedFrom?: ChatForkLineageV1; createdAt: number; updatedAt: number; } diff --git a/renderer/main/chat-pane.tsx b/renderer/main/chat-pane.tsx index 414d4b8ccc..8feb0f370b 100644 --- a/renderer/main/chat-pane.tsx +++ b/renderer/main/chat-pane.tsx @@ -9,6 +9,11 @@ import { updateChatDraft, } from "../lib/chat-draft"; import { QueuedMessages } from "../components/queued-messages"; +import { + saveComposerDraftText, + seedComposerAttachments, +} from "../lib/composer-draft-store"; +import type { ChatForkPosition } from "../shared/chat-copy-contract"; import { chatMessageQueue, steerQueuedMessage, @@ -32,7 +37,7 @@ import { useQueryClient } from "@tanstack/react-query"; import { Button, EmptyState, ScrollArea, Text, toast } from "../components/ui"; import { CONNECT_PROVIDER_ACTION, PROVIDER_SETTINGS_LABEL } from "../lib/provider-setup-copy"; import { BotAvatar } from "../components/bot-avatar"; -import { TerminalSquare } from "lucide-react"; +import { GitFork, TerminalSquare } from "lucide-react"; import { MessageList } from "../components/message-list"; import { useReadAloud } from "../lib/tts-client"; import type { ReadAloudActionProps } from "../components/read-aloud-button"; @@ -81,6 +86,7 @@ import { installAppendedChatSnapshot, logoutBuiltinProvider, refreshCodexProviderState, + useAllRegularChats, useChat, useBot, useComputerUseStatus, @@ -89,6 +95,7 @@ import { useProviders, useSettings, } from "../lib/queries"; +import { forkedFromLabel } from "../lib/chat-copy-view"; import { isModelSelectionReadyForNewWork, resolveVisibleModelSelection, @@ -841,7 +848,10 @@ export function ChatPane({ chatId }: { chatId: string }) { ); const copyChat = React.useCallback( - async (throughAssistantMessageId?: string) => { + async ( + forkAt?: { messageId: string; position: ChatForkPosition }, + prefill?: { text: string; attachments: readonly Attachment[] }, + ) => { if (getChatDraft(chatId)) throw new Error("Send the first message before copying this chat."); if (documentAppendReconciliationRequired) { throw new Error("Reload Aiden before copying this chat."); @@ -860,7 +870,11 @@ export function ChatPane({ chatId }: { chatId: string }) { throw new Error("Finish the current response or approval before copying this chat."); } const sourceChatId = chatId; - const copied = await chatsApi.copyVisibleHistory(sourceChatId, throughAssistantMessageId); + const copied = await chatsApi.copyVisibleHistory(sourceChatId, forkAt); + if (prefill) { + saveComposerDraftText(copied.id, prefill.text); + seedComposerAttachments(copied.id, prefill.attachments); + } const copiedWorkspaceId = persistedChatWorkspaceId(copied.workspaceId); qc.setQueryData(queryKeys.chat(copied.id), copied); qc.setQueryData(queryKeys.chatsIn(copiedWorkspaceId), (current) => [ @@ -870,6 +884,7 @@ export function ChatPane({ chatId }: { chatId: string }) { workspaceId: copiedWorkspaceId, providerId: copied.providerId, model: copied.model, + ...(copied.forkedFrom ? { forkedFrom: copied.forkedFrom } : {}), createdAt: copied.createdAt, updatedAt: copied.updatedAt, }, @@ -901,6 +916,75 @@ export function ChatPane({ chatId }: { chatId: string }) { ], ); + const forkLineage = chat.data?.botId ? undefined : chat.data?.forkedFrom; + const allChats = useAllRegularChats(Boolean(forkLineage)); + const forkSource = forkLineage + ? allChats.data?.find((candidate) => candidate.id === forkLineage.chatId) + : undefined; + const forkSourceLabel = forkLineage + ? allChats.isPending + ? "Forked chat" + : forkedFromLabel(forkSource?.title) + : undefined; + + const forkDisabledReason = + isGenerating || isStartingGeneration || approvals.length > 0 + ? "Finish the current response or approval before forking" + : documentAppendReconciliationRequired + ? "Reload Aiden before forking this chat" + : imageArtifactRecoveryPending || imageArtifactRecoveryUnavailable + ? "Recover this chat's visual artifacts before forking" + : null; + + /** + * Fork from a transcript message. `after` keeps the chosen reply; `before` + * keeps everything earlier and pre-fills the chosen prompt for editing. The + * first prompt has nothing before it, so editing it opens a fresh chat in + * the same workspace instead. + */ + const forkFromMessage = React.useCallback( + async (messageId: string, position: ChatForkPosition) => { + if (position === "after") { + await copyChat({ messageId, position }); + return; + } + const index = messages.findIndex((message) => message.id === messageId); + const message = messages[index]; + if (!message || message.role !== "user") { + throw new Error("That message is no longer in this chat."); + } + const prefill = { text: message.content, attachments: message.attachments ?? [] }; + if (messages.slice(0, index).some((earlier) => earlier.role === "user")) { + await copyChat({ messageId, position }, prefill); + return; + } + if (forkDisabledReason) throw new Error(`${forkDisabledReason}.`); + const workspaceId = persistedChatWorkspaceId(chat.data?.workspaceId); + const created = createChatDraft(workspaceId, undefined, prefill.text).chat; + seedComposerAttachments(created.id, prefill.attachments); + selectWorkspace(workspaceId); + try { + await navigate({ to: "/chat/$chatId", params: { chatId: created.id } }); + requestAnimationFrame(() => composerRef.current?.focus({ preventScroll: true })); + } catch { + discardChatDraft(created.id); + toast.info("Aiden could not open the new chat."); + } + }, + [chat.data?.workspaceId, copyChat, forkDisabledReason, messages, navigate, selectWorkspace], + ); + + const forkFromTranscript = React.useCallback( + (messageId: string, position: ChatForkPosition) => { + void forkFromMessage(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."), + ); + }, + [forkFromMessage], + ); + const exportChat = React.useCallback(async () => { if (getChatDraft(chatId)) throw new Error("Send the first message before exporting this chat."); const result = await chatsApi.export(chatId); @@ -2370,6 +2454,26 @@ export function ChatPane({ chatId }: { chatId: string }) { + ) : forkSourceLabel ? ( + + {chat.data?.title ?? "New agent"} + + + ) : ( (chat.data?.title ?? "New agent") ) @@ -2608,7 +2712,7 @@ export function ChatPane({ chatId }: { chatId: string }) { sessionChat={draft ? undefined : (chat.data ?? undefined)} authenticatedProviders={authenticatedProviders} onCloneChat={() => copyChat()} - onForkChat={(throughAssistantMessageId) => copyChat(throughAssistantMessageId)} + onForkChat={(messageId, position) => forkFromMessage(messageId, position)} onExportChat={exportChat} onCompactChat={ draft @@ -2798,6 +2902,8 @@ export function ChatPane({ chatId }: { chatId: string }) { agentActivity={visibleAgentActivity} readAloudMessageId={readAloudCandidateId} readAloud={readAloudProps} + onFork={chat.data?.botId ? undefined : forkFromTranscript} + forkDisabledReason={forkDisabledReason} error={ error ?? (imageArtifactRecoveryUnavailable diff --git a/renderer/shared/chat-copy-contract.test.ts b/renderer/shared/chat-copy-contract.test.ts new file mode 100644 index 0000000000..7a917d0e23 --- /dev/null +++ b/renderer/shared/chat-copy-contract.test.ts @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + MAX_CHAT_TITLE_CHARS, + nextForkTitle, + parseChatForkLineageV1, +} from "./chat-copy-contract.js"; + +test("fork titles count past the highest fork of the same base title", () => { + assert.equal(nextForkTitle("Plan", []), "Plan (fork)"); + assert.equal(nextForkTitle("Plan", ["Plan", "Plan (copy)"]), "Plan (fork)"); + assert.equal(nextForkTitle("Plan", ["Plan (fork)"]), "Plan (fork 2)"); + assert.equal(nextForkTitle("Plan (fork 2)", ["Plan (fork)", "Plan (fork 7)"]), "Plan (fork 8)"); + // Another chat whose title merely ends the same way is not a sibling. + assert.equal(nextForkTitle("Plan", ["Other plan (fork 4)"]), "Plan (fork)"); +}); + +test("fork titles stay within the title limit without splitting a character", () => { + const title = nextForkTitle("😀".repeat(MAX_CHAT_TITLE_CHARS), []); + assert.ok(title.endsWith(" (fork)")); + assert.ok(Array.from(title).length <= MAX_CHAT_TITLE_CHARS); + assert.ok(!title.replace(" (fork)", "").includes("�")); + assert.match(title.replace(" (fork)", ""), /^(?:😀)+$/u); +}); + +test("fork lineage parsing accepts only the exact recorded shape", () => { + const lineage = { chatId: "chat_1", messageId: "msg-2", position: "before", at: 1_700_000_000_000 }; + assert.deepEqual(parseChatForkLineageV1(lineage), lineage); + for (const invalid of [ + null, + [], + "chat_1", + { ...lineage, extra: true }, + { chatId: "chat_1", messageId: "msg-2", position: "before" }, + { ...lineage, chatId: "../chat" }, + { ...lineage, messageId: "x".repeat(161) }, + { ...lineage, position: "at" }, + { ...lineage, at: -1 }, + { ...lineage, at: 1.5 }, + ]) { + assert.equal(parseChatForkLineageV1(invalid), undefined); + } +}); diff --git a/renderer/shared/chat-copy-contract.ts b/renderer/shared/chat-copy-contract.ts index 91806aec90..eb1fe7ff81 100644 --- a/renderer/shared/chat-copy-contract.ts +++ b/renderer/shared/chat-copy-contract.ts @@ -2,3 +2,75 @@ export const MAX_VISIBLE_COPY_MESSAGES = 10_000; export const MAX_VISIBLE_FORK_CHOICES = 100; export const MAX_FORK_PREVIEW_CODE_UNITS = 256; export const MAX_FORK_QUERY_CODE_UNITS = 256; +export const MAX_CHAT_TITLE_CHARS = 120; + +/** + * Where a fork cuts the source transcript. `after` keeps the chosen settled + * assistant reply; `before` keeps everything strictly before the chosen user + * message so its text can be edited and resent in the fork. + */ +export type ChatForkPosition = "after" | "before"; + +/** Main-owned provenance recorded on a chat created by Fork. */ +export interface ChatForkLineageV1 { + chatId: string; + messageId: string; + position: ChatForkPosition; + /** Epoch milliseconds when the fork was created. */ + at: number; +} + +const MAX_LINEAGE_ID_CHARS = 160; +const SAFE_LINEAGE_ID = /^[A-Za-z0-9_-]+$/u; + +function lineageId(value: unknown): string | undefined { + return typeof value === "string" && + value.length > 0 && + value.length <= MAX_LINEAGE_ID_CHARS && + SAFE_LINEAGE_ID.test(value) + ? value + : undefined; +} + +/** Strict, exact-shape parser. Anything else is dropped, never repaired. */ +export function parseChatForkLineageV1(value: unknown): ChatForkLineageV1 | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const record = value as Record; + const keys = Object.keys(record); + if (keys.length !== 4 || !["chatId", "messageId", "position", "at"].every((key) => keys.includes(key))) { + return undefined; + } + const chatId = lineageId(record.chatId); + const messageId = lineageId(record.messageId); + if (!chatId || !messageId) return undefined; + if (record.position !== "after" && record.position !== "before") return undefined; + if (typeof record.at !== "number" || !Number.isSafeInteger(record.at) || record.at < 0) { + return undefined; + } + return { chatId, messageId, position: record.position, at: record.at }; +} + +const FORK_SUFFIX = / \(fork(?: (\d{1,6}))?\)$/u; + +/** The title a fork suffix was appended to, so forks of forks don't stack suffixes. */ +export function forkTitleBase(title: string): string { + const base = title.replace(FORK_SUFFIX, "").trim(); + return base || title.trim() || "Chat"; +} + +/** + * `Title (fork)`, then `Title (fork 2)`, `Title (fork 3)` … numbered past the + * highest existing fork of the same base title. + */ +export function nextForkTitle(sourceTitle: string, existingTitles: Iterable): string { + const base = forkTitleBase(sourceTitle); + let highest = 0; + for (const title of existingTitles) { + const match = FORK_SUFFIX.exec(title); + if (!match || forkTitleBase(title) !== base) continue; + highest = Math.max(highest, match[1] ? Number(match[1]) : 1); + } + const suffix = highest === 0 ? " (fork)" : ` (fork ${highest + 1})`; + const maximumBaseLength = Math.max(1, MAX_CHAT_TITLE_CHARS - suffix.length); + return `${Array.from(base.slice(0, maximumBaseLength * 2)).slice(0, maximumBaseLength).join("")}${suffix}`; +} diff --git a/tests/e2e/chat-fork.spec.ts b/tests/e2e/chat-fork.spec.ts new file mode 100644 index 0000000000..00688ed0c1 --- /dev/null +++ b/tests/e2e/chat-fork.spec.ts @@ -0,0 +1,95 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { expect, finishLmStudioOnboarding, test } from "./fixtures"; + +type StoredMessage = { id: string; role: string; content: string }; +type StoredChat = { + id: string; + title: string; + workspaceId?: string; + botId?: string; + forkedFrom?: { chatId: string; messageId: string; position: string; at: number }; + messages: StoredMessage[]; +}; + +async function regularChats(root: string): Promise { + let metas: StoredChat[] = []; + try { + metas = JSON.parse(await readFile(path.join(root, "chats", "index.json"), "utf8")); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } + return Promise.all( + metas + .filter((chat) => !chat.botId && chat.workspaceId !== "assistant") + .map(async (chat) => + JSON.parse(await readFile(path.join(root, "chats", `${chat.id}.json`), "utf8")) as StoredChat, + ), + ); +} + +const replies = (chat: StoredChat | undefined) => + chat?.messages.filter((message) => message.role === "assistant").length ?? 0; + +test("a chat forks from a reply or edits a prompt in a fork", async ({ aiden }) => { + const { page, userDataDir } = aiden; + await finishLmStudioOnboarding(page); + const composer = page.locator("textarea"); + + await composer.fill("Plan a weekend trip"); + await composer.press("Enter"); + await expect.poll(async () => replies((await regularChats(userDataDir))[0])).toBe(1); + await composer.fill("What should we eat?"); + await composer.press("Enter"); + await expect.poll(async () => replies((await regularChats(userDataDir))[0])).toBe(2); + const [source] = await regularChats(userDataDir); + const [firstPrompt, firstReply, secondPrompt] = source.messages.filter( + (message) => message.role === "user" || message.role === "assistant", + ); + + // Fork after the first reply. + const forkFromReply = page.getByRole("button", { name: "Fork from here" }).first(); + await expect(forkFromReply).not.toHaveAttribute("aria-disabled", "true"); + await page.getByText(firstReply.content.trim().slice(0, 24), { exact: false }).first().hover(); + await forkFromReply.click(); + await expect.poll(async () => (await regularChats(userDataDir)).length).toBe(2); + const afterFork = (await regularChats(userDataDir)).find((chat) => chat.forkedFrom)!; + expect(afterFork.forkedFrom).toMatchObject({ + chatId: source.id, + messageId: firstReply.id, + position: "after", + }); + expect(afterFork.messages.map((message) => message.content)).toEqual([ + firstPrompt.content, + firstReply.content, + ]); + const lineage = page.locator("[data-chat-fork-lineage]"); + await expect(lineage).toContainText(afterFork.title); + const sourceLink = lineage.getByRole("button", { name: `Forked from “${source.title}”` }); + await expect(sourceLink).toBeVisible(); + await expect(page.locator('[data-forked="true"]')).toHaveCount(1); + + // The lineage link returns to the source, where a later prompt can be edited in a fork. + await sourceLink.click(); + await expect(page.getByRole("button", { name: "Edit in fork" })).toHaveCount(2); + await page.getByRole("button", { name: "Edit in fork" }).nth(1).click(); + await expect(composer).toHaveValue(secondPrompt.content); + await expect.poll(async () => (await regularChats(userDataDir)).length).toBe(3); + const editFork = (await regularChats(userDataDir)).find( + (chat) => chat.forkedFrom?.position === "before", + )!; + expect(editFork.forkedFrom?.messageId).toBe(secondPrompt.id); + expect(editFork.messages.map((message) => message.content)).toEqual([ + firstPrompt.content, + firstReply.content, + ]); + await expect(page.locator('[data-forked="true"]')).toHaveCount(2); + + // Editing the very first prompt opens a prefilled draft and persists nothing until sent. + await page.locator("[data-chat-fork-lineage]").getByRole("button").click(); + await expect(page.getByRole("button", { name: "Edit in fork" })).toHaveCount(2); + await page.getByRole("button", { name: "Edit in fork" }).first().click(); + await expect(composer).toHaveValue(firstPrompt.content); + expect(await regularChats(userDataDir)).toHaveLength(3); +}); From 668dd90e05d8bbdb6d7606101b6e8fddb4fda5fa Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 11:51:37 -0400 Subject: [PATCH 3/5] docs(memory): record desktop chat fork Co-Authored-By: Claude Opus 5.5 --- .memory/chat-fork.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .memory/chat-fork.md diff --git a/.memory/chat-fork.md b/.memory/chat-fork.md new file mode 100644 index 0000000000..75d66632e5 --- /dev/null +++ b/.memory/chat-fork.md @@ -0,0 +1,35 @@ +# Chat fork from any message — 2026-10-05 + +Plan: `docs/plans/chat-fork-plan.md` (five PRs). This note tracks what has landed. + +## PR 1 — desktop fork (branch `feat/chat-fork-desktop`) + +- **Cut points.** `chatStore.copyVisibleHistory` takes `forkAt: { messageId, position }`. `after` keeps a settled assistant reply. `before` keeps everything strictly before a user prompt, which is how Edit in fork works. The legacy `throughAssistantMessageId` input remains for Bot copies and records no lineage. +- **Lineage.** `ChatMeta.forkedFrom` is a `ChatForkLineageV1 { chatId, messageId, position, at }`, parsed strictly by `parseChatForkLineageV1` in `renderer/shared/chat-copy-contract.ts`. + - `readChat` drops an invalid lineage instead of letting `isValidMeta` hide the chat. + - Bot chats never get a lineage. +- **Titles.** Forks are named `Title (fork)`, then `(fork N)`, numbered past the highest sibling in the destination workspace. Forks of forks reuse the base title. Clones keep the `(copy)` suffix. +- **IPC.** `chats:copyVisibleHistory` accepts three request shapes: + - `{chatId}` → clone; + - `{chatId, throughMessageId}` → legacy fork after a reply; + - `{chatId, messageId, position}` → fork at the given cut. + + Bot chats reject `before`. +- **UI.** + - Hover actions: settled replies show "Fork from here" (in `MessageActions`); sent prompts show "Edit in fork" (next to Copy). Both use the `ForkMessageButton` component. + - `MessageList` forwards `onFork` through a ref so settled rows stay memoized. The streaming row and Bot chats get no actions. + - While the chat is busy or needs recovery, the buttons are `aria-disabled` and their title gives the reason. + - `/fork` picker rows also get "Edit in fork". +- **Pre-fill.** Edit in fork seeds the new chat's composer: the text goes to the localStorage draft, and the attachments go to a one-shot in-memory seed (`seedComposerAttachments` / `takeComposerAttachmentSeed`; bytes are never persisted). Editing the *first* prompt opens a renderer-only chat draft instead, so no empty chat is persisted. +- **Lineage UI.** The chat header shows a second line with "Forked from “X”", which links to the source, or "Forked from a deleted chat". Sidebar rows get a `GitFork` glyph, a tooltip, and `aria-description`. +- **Deferred.** + - Moving fork into `ChatApplicationService` waits for PR 4 (Remote). + - The right-click context menu and skill pre-fill are not built. + - The Pi journal is not forked yet (PR 2), so the forked model context is rebuilt from visible messages only. +- **Tests.** + - `chat-session-copy.test.ts`: cuts, titles, lineage survival, and corrupt lineage being dropped. + - `chat-copy-contract.test.ts` (registered in `test:slash-commands`). + - The parser test and `chat-copy-view.test.ts`. + - `message-bubble.test.tsx`: which rows show fork actions. + - `tests/e2e/chat-fork.spec.ts`: the real flow against the fake LM Studio. +- **CI note.** Renderer-only PRs skip the Linux packaging jobs, so the required Linux checks never post. #342 (prompt selection) was therefore landed through this branch. From 14550130b8622614a6ca987cff485df12868cb30 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 11:57:19 -0400 Subject: [PATCH 4/5] ci: assign the fork contract test to a desktop unit lane Co-Authored-By: Claude Opus 5.5 --- scripts/ci-test-registry.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index 74980b8b17..ec319d3224 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -545,6 +545,7 @@ "renderer/lib/assistant-motion-contract.test.ts", "renderer/lib/chat-activity.test.ts", "renderer/lib/chat-copy-view.test.ts", + "renderer/shared/chat-copy-contract.test.ts", "renderer/lib/chat-deletion-cache.test.ts", "renderer/lib/chat-draft.test.ts", "renderer/lib/chat-message-queue.test.ts", From a9c0029949d7f15a0294ca16d6eeb5e8b7630743 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Mon, 5 Oct 2026 12:09:42 -0400 Subject: [PATCH 5/5] fix(chats): address fork review findings - Bot chats no longer offer Edit in fork in the /fork picker, and the renderer refuses a before-prompt fork for them, including the first-prompt draft shortcut that never reached IPC. - Fork titles keep numbering when a long base title was truncated to fit its suffix. - Settled replies with only attachments or tool activity now show Fork from here. Co-Authored-By: Claude Opus 5.5 --- renderer/components/composer.tsx | 31 +++++++++++------- renderer/components/message-actions.tsx | 13 +++++--- renderer/components/message-bubble.test.tsx | 36 +++++++++++++++++++++ renderer/components/message-list.tsx | 16 +++++++-- renderer/lib/chat-copy-view.test.ts | 12 +++++++ renderer/lib/chat-copy-view.ts | 14 +++++--- renderer/main/chat-pane.tsx | 3 +- renderer/shared/chat-copy-contract.test.ts | 13 ++++++++ renderer/shared/chat-copy-contract.ts | 7 +++- 9 files changed, 120 insertions(+), 25 deletions(-) diff --git a/renderer/components/composer.tsx b/renderer/components/composer.tsx index 81c6a244f4..dba6e079a8 100644 --- a/renderer/components/composer.tsx +++ b/renderer/components/composer.tsx @@ -647,7 +647,8 @@ export function Composer({ const forkEligibility = React.useMemo(() => { if (!sessionChat) return { turns: [], cloneBlocked: false }; - return forkTurnEligibility(sessionChat.messages); + // A Bot has one canonical chat, so its forks may only keep a reply. + return forkTurnEligibility(sessionChat.messages, { editInFork: !sessionChat.botId }); }, [sessionChat]); const completedForkTurns = forkEligibility.turns; const visibleForkTurns = React.useMemo(() => { @@ -2528,7 +2529,11 @@ export function Composer({ if (!open) setForkQuery(""); }} title="Fork from a completed turn" - description="Fork keeps visible messages and attachments through the selected response. Edit in fork keeps everything before that turn's prompt and puts the prompt in the composer. Private reasoning, tool state, and subagent runtime records are omitted." + description={`Fork keeps visible messages and attachments through the selected response.${ + sessionChat?.botId + ? "" + : " Edit in fork keeps everything before that turn's prompt and puts the prompt in the composer." + } Private reasoning, tool state, and subagent runtime records are omitted.`} confirmHidden busy={sessionCommandBusy} returnFocus={() => inputRef?.current ?? null} @@ -2571,16 +2576,18 @@ export function Composer({ - + {turn.userMessageId ? ( + + ) : null} )) ) : ( diff --git a/renderer/components/message-actions.tsx b/renderer/components/message-actions.tsx index 6155e5506a..f26c0f8757 100644 --- a/renderer/components/message-actions.tsx +++ b/renderer/components/message-actions.tsx @@ -8,6 +8,7 @@ import { ForkMessageButton, type MessageForkAction } from "./fork-message-button import { ReadAloudButton, type ReadAloudActionProps } from "./read-aloud-button"; interface MessageActionsProps { + /** Empty for replies with no prose; the copy action is then omitted. */ copyText: string; /** Present only on the tail of an eligible whole response. */ readAloud?: ReadAloudActionProps; @@ -25,11 +26,13 @@ export function MessageActions({ copyText, readAloud, hidden, footer, fork }: Me className={`group/actions mt-1 flex items-center gap-0.5 ${hidden ? "invisible" : ""}`} aria-hidden={hidden} > - + {copyText ? ( + + ) : null} {fork ? ( { assert.doesNotMatch(render({}), /data-fork-action/u); }); + +test("settled replies without prose still offer Fork from here", () => { + const toolOnly: GenerationTimeline = { + version: 3, + generationId: "generation-tool-only", + status: "completed", + startedAt: 1, + steps: [{ + id: "tool-1", order: 0, kind: "tool", toolCallId: "call-1", toolName: "read_file", + label: "Read file", status: "completed", startedAt: 1, updatedAt: 2, finishedAt: 2, + }], + }; + const markup = renderToStaticMarkup( + undefined} + agentActivity={null} + error={null} + onFork={() => undefined} + />, + ); + assert.equal((markup.match(/aria-label="Fork from here"/gu) ?? []).length, 2); + // With no prose there is nothing to copy; only the two prompts keep Copy. + assert.equal((markup.match(/aria-label="Copy message"/gu) ?? []).length, 2); +}); diff --git a/renderer/components/message-list.tsx b/renderer/components/message-list.tsx index c5233c5e1a..0958016e69 100644 --- a/renderer/components/message-list.tsx +++ b/renderer/components/message-list.tsx @@ -8,6 +8,7 @@ import { EventPresence } from "./event-presence"; import { SafeMessageBubble } from "./message-bubble"; import type { ReadAloudActionProps } from "./read-aloud-button"; import type { MessageForkAction } from "./fork-message-button"; +import { MessageActions } from "./message-actions"; import type { ChatForkPosition } from "../shared/chat-copy-contract"; import { MessageAttachmentPreviewProvider, MessageAttachments } from "./message-attachments"; import { ReasoningBlock } from "./reasoning-block"; @@ -141,7 +142,7 @@ function AssistantResponse({ {attachments?.length ? ( ) : null} - {!content && footer ? footer : null} + {!content ? proselessActions(footer, fork) : null} ); } @@ -204,11 +205,22 @@ function AssistantResponse({ {attachments?.length ? ( ) : null} - {lastTextIndex < 0 && footer ? footer : null} + {lastTextIndex < 0 ? proselessActions(footer, fork) : null} ); } +/** A reply with only attachments or activity still needs its fork action. */ +function proselessActions(footer: React.ReactNode, fork: MessageForkAction | undefined): React.ReactNode { + if (!fork) return footer ?? null; + // The reply's media sits above, so hovering this row reveals the action. + return ( +
+ +
+ ); +} + function settledTurnFooter(message: ChatMessage): React.ReactNode { const items = turnFooterItems(message); return items.length > 0 ? : undefined; diff --git a/renderer/lib/chat-copy-view.test.ts b/renderer/lib/chat-copy-view.test.ts index 5ea54298b3..0c43a359b5 100644 --- a/renderer/lib/chat-copy-view.test.ts +++ b/renderer/lib/chat-copy-view.test.ts @@ -49,3 +49,15 @@ test("each fork choice points Edit in fork at the prompt that opened its turn", [["a1", "u1"], ["a1b", "u1"], ["a2", "u2"]], ); }); + +test("Bot chats offer no Edit in fork, including on their first prompt", () => { + const messages: ChatMessage[] = [ + { id: "u1", role: "user", content: "first", createdAt: 1 }, + { id: "a1", role: "assistant", content: "one", createdAt: 2 }, + { id: "u2", role: "user", content: "second", createdAt: 3 }, + { id: "a2", role: "assistant", content: "two", createdAt: 4 }, + ]; + const result = forkTurnEligibility(messages, { editInFork: false }); + assert.deepEqual(result.turns.map(({ id }) => id), ["a1", "a2"]); + assert.ok(result.turns.every((turn) => turn.userMessageId === undefined)); +}); diff --git a/renderer/lib/chat-copy-view.ts b/renderer/lib/chat-copy-view.ts index 7710322b1b..909aba979e 100644 --- a/renderer/lib/chat-copy-view.ts +++ b/renderer/lib/chat-copy-view.ts @@ -10,14 +10,20 @@ import { boundedUnicodePrefix } from "../shared/unicode-prefix.js"; export interface ForkTurnChoice { /** The settled assistant reply a plain fork keeps. */ id: string; - /** The prompt that opened this turn; Edit in fork cuts just before it. */ - userMessageId: string; + /** + * The prompt that opened this turn; Edit in fork cuts just before it. + * Absent when the chat can't fork before a prompt (Bot chats). + */ + userMessageId?: string; label: string; createdAt: number; turnNumber: number; } -export function forkTurnEligibility(messages: readonly ChatMessage[]): { +export function forkTurnEligibility( + messages: readonly ChatMessage[], + options: { editInFork?: boolean } = {}, +): { turns: ForkTurnChoice[]; cloneBlocked: boolean; } { @@ -42,7 +48,7 @@ export function forkTurnEligibility(messages: readonly ChatMessage[]): { } else if (latestUserLabel && latestUserId) { turns.push({ id: message.id, - userMessageId: latestUserId, + ...(options.editInFork === false ? {} : { userMessageId: latestUserId }), label: latestUserLabel, createdAt: message.createdAt, turnNumber: turns.length + 1, diff --git a/renderer/main/chat-pane.tsx b/renderer/main/chat-pane.tsx index 8feb0f370b..82dc498036 100644 --- a/renderer/main/chat-pane.tsx +++ b/renderer/main/chat-pane.tsx @@ -948,6 +948,7 @@ export function ChatPane({ chatId }: { chatId: string }) { await copyChat({ messageId, position }); return; } + if (chat.data?.botId) throw new Error("Bot chats can only fork after a reply."); const index = messages.findIndex((message) => message.id === messageId); const message = messages[index]; if (!message || message.role !== "user") { @@ -971,7 +972,7 @@ export function ChatPane({ chatId }: { chatId: string }) { toast.info("Aiden could not open the new chat."); } }, - [chat.data?.workspaceId, copyChat, forkDisabledReason, messages, navigate, selectWorkspace], + [chat.data?.botId, chat.data?.workspaceId, copyChat, forkDisabledReason, messages, navigate, selectWorkspace], ); const forkFromTranscript = React.useCallback( diff --git a/renderer/shared/chat-copy-contract.test.ts b/renderer/shared/chat-copy-contract.test.ts index 7a917d0e23..6ead1cca93 100644 --- a/renderer/shared/chat-copy-contract.test.ts +++ b/renderer/shared/chat-copy-contract.test.ts @@ -23,6 +23,19 @@ test("fork titles stay within the title limit without splitting a character", () assert.match(title.replace(" (fork)", ""), /^(?:😀)+$/u); }); +test("long titles keep numbering forks after the base is truncated", () => { + const source = "x".repeat(MAX_CHAT_TITLE_CHARS); + const titles: string[] = []; + for (let index = 0; index < 11; index += 1) titles.push(nextForkTitle(source, titles)); + assert.deepEqual( + titles.map((title) => / \((fork(?: \d+)?)\)$/u.exec(title)?.[1]), + ["fork", ...Array.from({ length: 10 }, (_, index) => `fork ${index + 2}`)], + ); + assert.ok(titles.every((title) => Array.from(title).length <= MAX_CHAT_TITLE_CHARS)); + // Forking one of those forks continues the same sequence. + assert.match(nextForkTitle(titles[0]!, titles), / \(fork 12\)$/u); +}); + test("fork lineage parsing accepts only the exact recorded shape", () => { const lineage = { chatId: "chat_1", messageId: "msg-2", position: "before", at: 1_700_000_000_000 }; assert.deepEqual(parseChatForkLineageV1(lineage), lineage); diff --git a/renderer/shared/chat-copy-contract.ts b/renderer/shared/chat-copy-contract.ts index eb1fe7ff81..4c2a9c4db6 100644 --- a/renderer/shared/chat-copy-contract.ts +++ b/renderer/shared/chat-copy-contract.ts @@ -67,7 +67,12 @@ export function nextForkTitle(sourceTitle: string, existingTitles: Iterable= MAX_CHAT_TITLE_CHARS && base.startsWith(siblingBase); + if (siblingBase !== base && !truncated) continue; highest = Math.max(highest, match[1] ? Number(match[1]) : 1); } const suffix = highest === 0 ? " (fork)" : ` (fork ${highest + 1})`;