diff --git a/.memory/design-mode.md b/.memory/design-mode.md index 8aa6d91cc..7db39a11f 100644 --- a/.memory/design-mode.md +++ b/.memory/design-mode.md @@ -364,4 +364,18 @@ Deviations from the P1 plan: - Artifact frames load through `frame.chatId ?? the viewing chat`; main serves preview, export and source only when that chat exists and shares the workspace. - Cleanup (`design-canvas/cleanup.ts`): chat delete prunes the chat's comments (no write when there are none) and its view, before and after the commit, using the workspace captured before the delete; it never deletes the canvas file. Workspace remove deletes the canvas, its corrupt copies and the views file. - Attach (`design-canvas/carry.ts`, A8/A22): only with `fileAction: "copy"` and not a legacy shared scratch folder, right after the attach commits and before the hidden workspace is released, `appendCanvasPages` appends the hidden canvas's pages named " · ", file and image frames follow the copied paths (`ScratchCopyTransaction.copied` `{ from, to }` pairs), frames whose files did not come are dropped, and the chat is shown the first new page. Over a limit or on an error nothing merges and the attach result has `canvasCarried: false`; the dialog toasts "The canvas was too large to bring along." -- Phase 1b still owns `chatPages` writes and `canvas_page use`. +- Phase 1b (below) added `chatPages` writes and `canvas_page use`. + +## v2 Phase 1b: chat pages (2026-11-24) + +Branch `t3/design-mode-v2-p1b`, stacked on PR #894. Plan `docs/superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md`. +- Rules live in `renderer/shared/design-canvas/chat-pages.ts` (pure): `claimPage` (cap 2 000, evicts dead chats, else `ChatPagesFullError`), `addChatPage`, `uniquePageName` (60 chars, " 2"…), `followChatTitle`, `withLazyClaim`, `forgetChatOnCanvas`, `forgetChatMove`, `mergeSavedChatPages`, `deletedClaims`, `withoutGoneClaims`, `chatsOnCanvas`. The planned `chatPageId` was removed as unused: chat-aware page resolution lives in `designTurnPages` (main) and `useDesignView` (renderer). `DesignPage.namedFor` marks a page made for a chat; no schema bump. +- D1: only main claims, only for the acting chat: entry, the lazy claim (a design turn's first write), `canvas_page use`, attach carry. Every claim read/write is inside `store.update` on the latest doc; liveness (`designLiveChats` in `liveness.ts`: one chat-index `list(workspaceId)` per check; the chat exists and is in that workspace) is read before. +- D2 entry rules: keep a live claim; else the page holding most of the chat's written pages (not another live chat's); else the resolved page as it is when it isn't another live chat's `namedFor` (a gone chat's mark is stripped in the same write), no other live chat claims it, and it is empty or no other chat's kept view is on it (`DesignCanvasViews.pageIdsOf`); else a new page after it, named after the chat, `namedFor`. Entry always `show`s, then runs the title follow. The consent card's `enter` awaits entry (`awaitEntry`); lazy claims wait for a pending entry (`PendingEntries`). +- D3 saves: the store merges claims from the stored doc; a renderer save never adds a claim. An in-memory per-workspace delete record (`DeletedPage`: chat → where the delete moved it, plus `namedFor`; 200 pages, oldest out) lets an undo bring a page back with every recorded chat that is still where the delete moved it, whatever the saved copy says. A chat whose page a save removes goes to the page the save names for it when both docs have that page, else the first page (so undo/redo of a turn that added and used a page round-trips). The save answer carries `chatPages`/`namedFor` when the merge changed them; the renderer carries them into every kept step (no undo step). `changesBetween` applies page changes item by item. +- D4: `deletePage` moves the page's chats to the first page left. `canvas_page delete` refuses once (person's/locked frames and/or other live chats' claims, pluralised) unless `force: true`. +- D6: `chatStore.onTitleChanged` → `designTitleFollow.follow` (per-chat queue, reads the title at run time). `DesignCanvasStore.namedChats(workspaceId)` (refreshed on every read and write) lets a follow skip chats with no named page without reading the canvas. `renamePage` clears `namedFor`; duplicate and carry never copy it. +- D7: main resolves shown-this-turn → message page → kept view → claim → first; the renderer view → claim → newest earlier → first, and reports a fallback page to main. +- Lifecycle: `forgetChat(chatId, workspaceId, scope)`: `comments` before a delete commits, `all` (claim, `namedFor`, artifact frames) after; `move` for `moveEmptyToWorkspace` (also deletes an empty page made for the chat). Startup recovery uses `recoverDeletedChatCanvas` (cleanup.ts); when the chat's metadata is already gone (crash after the remove) it runs `all` on every canvas (`DesignCanvasStore.workspaceIds`), because the pending-deletion marker lives in the subagent run stores' strict V1 format and can't carry a workspace id. Attaching from a shared legacy No workspace canvas runs `move` on it. Attach carry claims the first carried page; at a full `chatPages` it asks liveness and evicts gone chats, else skips only the claim. +- Picker (`design-toolbar.tsx`): trailing tertiary label "This chat", "This chat · N more", "1 chat", "N chats"; accessible name "Page 1, This chat". Counts only, from the doc. Only entry, `canvas_page use` and `canvas_page delete` drop leftover claims and `namedFor` marks of chats that are not live; other `canvas_page` actions and other writes don't. +- E2E: `tests/e2e/design-canvas.spec.ts` "two chats on one workspace…" (screenshot `1440-canvas-two-chats-{light,dark}.png` in the test's output folder). diff --git a/PRODUCT.md b/PRODUCT.md index d9c937a42..e24249082 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -66,7 +66,7 @@ First-run setup and Settings → Providers share an account, API key and local-m - Settings → Storage shows how much disk Aiden uses on this computer, split into chats, logs, artifacts, browser data, voice models, Bot computers, saved work from removed worktrees, other app data and worktrees, with the largest worktrees and chats listed. Cleanup offers unused worktrees, one chat at a time, the browser cache (sign-ins kept) and logs behind a review that names what will be removed and how much it frees; voice models and Bot computers link to their own settings. Worktrees with uncommitted or unpushed work, a chat or terminal using them or a scheduled task in them are never removed, and cleanup re-checks that right before deleting. See [docs/storage.md](docs/storage.md). - A provider's usage limit makes a reply wait, never switch to another model; limits that last days and billing problems fail at once with the reset time. Spending limits are the owner's: each chat, each Bot's month and each routine run can stop at a dollar amount counted from API-key requests only, and only the person can allow more (on the Mac or a paired phone). See [docs/usage-limits-and-spending.md](docs/usage-limits-and-spending.md). - In chats with Web Search on, the agent can read a public web page. Opt-in extract mode, set up with the person's own Cloudflare account, returns only the named values it asks for, each with supporting page text; a value that is not on the page comes back as a guess, never as read. -- Design mode (desktop, on by default; `AIDEN_DESIGN_MODE=0` turns it off) puts a workspace chat beside an infinite design canvas. Design mode keeps one canvas per workspace, shared by its chats; each chat remembers its own page and view, so a pan, a zoom or a page switch in one chat never moves another. Canvases from earlier versions are cleared on first start; files under `design/` are untouched. Deleting a chat removes its comments from the canvas, removing a workspace deletes its canvas, and a No workspace chat attached to a workspace with its files copied brings its canvas pages along, named after the chat (attaching without copying the files leaves the canvas behind). Pages stay workspace HTML files served only to the canvas in a sandbox with no network; Aiden changes the canvas only in attended desktop turns, through its canvas tools or by an HTML page it writes, edits or makes with a command under the workspace's `design/` folder landing as a frame (and, when the person opens design mode, the pages the chat's earlier replies wrote landing on the chat's empty page), and a comment or an in-place word edit the person makes goes to Aiden only with their next message, while plain word edits are written into the page's file and can be undone. The first time design mode is on in a workspace with no `design/tokens.css`, Aiden reads a few of its style files on the device and offers in chat to write a tokens file and a specimen page from the colours and fonts it found; it writes them only after the person agrees, and asks once per workspace. +- Design mode (desktop, on by default; `AIDEN_DESIGN_MODE=0` turns it off) puts a workspace chat beside an infinite design canvas. Design mode keeps one canvas per workspace, shared by its chats; each chat remembers its own page and view, so a pan, a zoom or a page switch in one chat never moves another. Opening design mode gives the chat a page of its own: the page on screen when no other chat is using it, otherwise a new page named after the chat, which follows the chat's title until someone renames the page. Aiden can switch the chat to another page. Deleting a page moves its chats to the first page, and Aiden won't delete a page another chat uses unless the person asks; the page picker shows how many chats use each page, never which. Deleting a chat removes its comments, its page claim, and the images and visuals it sent from the chat (artifact frames); workspace images, its page, notes and page frames stay. Canvases from earlier versions are cleared on first start; files under `design/` are untouched. Removing a workspace deletes its canvas, and a No workspace chat attached to a workspace with its files copied brings its canvas pages along, named after the chat, and uses the first of them as its page (attaching without copying the files leaves the canvas behind). Pages stay workspace HTML files served only to the canvas in a sandbox with no network; Aiden changes the canvas only in attended desktop turns, through its canvas tools or by an HTML page it writes, edits or makes with a command under the workspace's `design/` folder landing as a frame (and, when the person opens design mode, the pages the chat's earlier replies wrote landing on the chat's page), and a comment or an in-place word edit the person makes goes to Aiden only with their next message, while plain word edits are written into the page's file and can be undone. The first time design mode is on in a workspace with no `design/tokens.css`, Aiden reads a few of its style files on the device and offers in chat to write a tokens file and a specimen page from the colours and fonts it found; it writes them only after the person agrees, and asks once per workspace. - Bot computers (Apple silicon): an opt-in macOS VM per Bot, which the Bot sees and uses with its own `computer` tool (screenshots and clicks, each step with a stated intent the rules read) and `computer_shell` tool, on routine runs too. The Bot panel's Computer tab shows it live with the Bot's avatar where it last pointed; the person's first click or key, or Take over, stops the Bot's current action until Give back, and Float over chat keeps the screen in view. Element control (Aiden's pinned cua-driver in the base computer, allowed once for Accessibility and Screen Recording and inherited by every Bot computer made from it) lets the Bot read an app's buttons and fields and click them by number, and the rules then also read the element acted on; skipping it keeps screen-only Bots. A Bot can ask the person to sign in on its own computer: Open hands the person the computer with Safari at the site, the Bot's computer tools wait, and the password never reaches the model. The onboarding tour introduces Bot computers only where they exist. See [docs/bot-computers.md](docs/bot-computers.md). - On iPhone, an `svg` code block in a reply has View, which draws it with no scripts and no network. A workspace `.html` file opens on a themed Preview, with no network and a Source switch, and tapping a "File written" line in a workspace chat opens that file. diff --git a/docs/plans/README.md b/docs/plans/README.md index 29414b26f..879ff4f73 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -63,7 +63,7 @@ Research addition 2026-10-03 against `main` at `3f86d41af` (0.52.0): [all-PR inv - [Design mode Tweaks panel](design-mode-tweaks-panel-plan.md) — Built 2026-11-18 on `claude/project-thread-m755wc`, in review (owner answered 1a 2a 3a+b). DialKit-style Tweaks: folders, typed number values, a 2D pad, words and buttons as page controls; saved versions with in-memory pictures and Show all; Shuffle, Send to Aiden, Copy and Make default with Undo; and the same controls floating over a page you are inside. -- [Design mode v2: the live app canvas](../superpowers/specs/2026-11-23-design-mode-live-app-design.md) — Approved 2026-11-23. The workspace's real dev-server routes as live, interactive frames (localhost-only network), one canvas per workspace with a page per chat, Aiden-controlled dev server, Inspect tool (X) with measure and drift checks, element chips into the composer, change toasts, error frames with Fix with Aiden, live directions with Adopt, a Styles frame, the app's design system kept in Google's open `DESIGN.md` format (read, linted and drafted by Aiden), React mock apps for non-web React projects such as Electron apps, and later `*.canvas.tsx` component cards. Pre-build checks done and the PR split revised (1a, 1b, 2a–2c, 3a–3d, DM, 4, 5, 7, 6) on 2026-11-23; Phase 1a (workspace canvas document) built 2026-11-23 on `t3/design-mode-live-app-plan`, in review as [PR #894](https://github.com/sambitcreate/aiden-agent/pull/894), plan [p1a](../superpowers/plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md). +- [Design mode v2: the live app canvas](../superpowers/specs/2026-11-23-design-mode-live-app-design.md) — Approved 2026-11-23. The workspace's real dev-server routes as live, interactive frames (localhost-only network), one canvas per workspace with a page per chat, Aiden-controlled dev server, Inspect tool (X) with measure and drift checks, element chips into the composer, change toasts, error frames with Fix with Aiden, live directions with Adopt, a Styles frame, the app's design system kept in Google's open `DESIGN.md` format (read, linted and drafted by Aiden), React mock apps for non-web React projects such as Electron apps, and later `*.canvas.tsx` component cards. Pre-build checks done and the PR split revised (1a, 1b, 2a–2c, 3a–3d, DM, 4, 5, 7, 6) on 2026-11-23; Phase 1a (workspace canvas document) built 2026-11-23 on `t3/design-mode-live-app-plan`, in review as [PR #894](https://github.com/sambitcreate/aiden-agent/pull/894), plan [p1a](../superpowers/plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md). Phase 1b (chat pages) built 2026-11-24 on `t3/design-mode-v2-p1b`, in review as [PR #908](https://github.com/sambitcreate/aiden-agent/pull/908), stacked on PR #894, plan [p1b](../superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md). - [Design Studio + Create Images rebuild](design-studio-create-images-rebuild-plan.md) — Active (Create Images only; Design Studio superseded 2026-10-31). Track F (Studio Foundation) merged in [#375](https://github.com/sambitcreate/aiden-agent/pull/375) and [#376](https://github.com/sambitcreate/aiden-agent/pull/376). Create Images CI-1 merged in [#382](https://github.com/sambitcreate/aiden-agent/pull/382) (headless core) and [#383](https://github.com/sambitcreate/aiden-agent/pull/383) (UI and Playwright); CI-1.10 live OpenRouter acceptance passed (owner, 2026-10-08). Design Studio DS-1a (headless core: projects, design runs, partial publish + Resume, preview resolver, IPC) merged in [#385](https://github.com/sambitcreate/aiden-agent/pull/385) (2026-10-08, shipped in 0.55.0); DS-1b was never started. The Design Studio half was superseded 2026-10-31 by [Design mode](../superpowers/specs/2026-10-31-design-mode-design.md); Studio code removed in P0, and `AIDEN_EXPERIMENTAL_DESIGN_STUDIO` no longer does anything. Create Images continues under this plan behind `AIDEN_EXPERIMENTAL_CREATE_IMAGES` (default off). Haiku-built tasks were independently audited on Opus 5.5 and fixed before merge. Create Images viewer, editor History tab, All Images library and always-on auto-save to Pictures merged in [#689](https://github.com/sambitcreate/aiden-agent/pull/689) (2026-11-02, stacked on [#686](https://github.com/sambitcreate/aiden-agent/pull/686)) and shipped in 0.64.0. - [On-device speech engine foundation (STT sub-project 1)](stt-engine-foundation-spec.md) — Merged in [PR #436](https://github.com/sambitcreate/aiden-agent/pull/436), with hardening in #439; shipped in 0.56.0. Plan: [implementation plan](../superpowers/plans/2026-10-09-stt-engine-foundation.md); the smoke run, packaging check and native client tests are recorded in its Progress section and `.memory/stt-engine-foundation.md`. The onboarding voice step is deferred to sub-project 4. First of four Handy-informed speech-to-text sub-projects (engine foundation, live and accuracy, dictation UX, consistency and onboarding). It stays on sherpa-onnx (pinned 1.13.8) and covers: diff --git a/docs/superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md b/docs/superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md new file mode 100644 index 000000000..d12f0bcf2 --- /dev/null +++ b/docs/superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md @@ -0,0 +1,661 @@ +# Design mode v2 — Phase 1b: workspace canvas chat pages — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give each chat its own page on the shared workspace canvas. +- Main writes `chatPages[chatId]` when a chat enters design mode, on its first canvas write without one, and when Aiden picks another page. +- A page made for a chat follows the chat's title. +- Deleting a page moves its chats to the page the delete leaves first. +- Deleting a chat takes its claim and its artifact frames off the canvas. + +**Architecture:** `chatPages` belongs to main. +- **One module.** Every write to it is a pure helper in a new shared module, `renderer/shared/design-canvas/chat-pages.ts`, called inside `store.update` on the latest document. So two chats' writes never race. +- **Saves.** A person's save from the renderer never adds or moves a claim. The store merges claims from the stored document. It takes the renderer's entry only for a page that save brings back, and only within what the store recorded when the page was deleted. It returns the merged claims, so the saving canvas shows what was stored. +- **View and claim.** The chat's view (`DesignCanvasViews`, 1a) stays the page the canvas shows. The claim is the chat's home page, used when the view's page is gone or the chat has no view. A claim always shows its page, so view and claim agree when the claim is made. After that the person can look anywhere. + +**Tech Stack:** TypeScript (ESM), Electron 43 main, React 19 renderer, `tsx --test` for unit tests, Playwright E2E through `npm run test:e2e:space`. + +**Spec:** `docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md` §6.1 ("A chat's page", "Sharing in practice"), §8 (row 1b), §12. Stacked on PR #894 (Phase 1a, plan `docs/superpowers/plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md`). + +## Scope + +In scope: +- the page claim on design-mode entry, with a page made for the chat named after it and renamed with it until someone renames it by hand; +- a lazy claim on a chat's first canvas write in a design turn while it has no claim; +- `canvas_page {action: "use", page}`; +- page delete reassigns its chats, and `canvas_page delete` refuses a page another chat uses unless `force: true`; +- the `chatPages` fallback in page resolution (the A12 handoff note), in the same order on main and the renderer; +- undo that keeps a deleted page's place when another writer changed the page list (a 1a bug, fixed here because claims depend on it); +- lifecycle: + - chat delete, live and in startup recovery, prunes its `chatPages` entry and its artifact frames; + - moving an empty chat drops its entry and an empty page made for it; + - an attached No workspace chat claims its first carried page; +- the page picker shows how many chats use each page (§6.1 "Sharing in practice"); +- the two-chats E2E. + +Out of scope: +- any live-app, app-server or DESIGN.md work (2a onward); +- a person-facing "use this page for this chat" action. Only entry, the lazy claim and Aiden's `canvas_page use` claim. The picker only shows claims; +- naming other chats in tool answers or the picker. Both give counts only, never another chat's title or id. Page names may still carry a chat's title by design, since a page made for a chat is named after it (D6); +- Remote and phones. `chatPages` stays out of the Remote projection, and phone turns never get canvas tools (`designTurnEligible` requires `localRenderer`, `canvas-tools.ts:167`). The iOS and Android clients don't change; +- analytics events. 1b adds none. + +## What 1a already does (checked against the code at `19d79bbb7`) + +| Item | 1a state | 1b action | +|---|---|---| +| `chatPages` in the schema | Parsed; entries kept only for safe chat ids naming existing pages (`schema.ts:377`). Nothing writes it. | Add the writers, `DesignPage.namedFor` and an explicit 2 000-entry cap. | +| `deletePage` | Drops `chatPages` entries for the deleted page (`pages.ts:84`). | Reassign them to the first page left. | +| `changesBetween` (undo carry) | Takes `to.pages` whole when the outline changed (`canvas-history-core.ts:119-125`). An undo that restores a deleted page loses it when another writer also changed the page list. Claims are kept from the step, not carried. | Apply page changes item by item, and carry claim changes (Task 1). | +| `viewPageId` | View page, else first page (`view.ts:28`). Frames and comment inputs also call it, so it isn't chat-aware. | Leave it. Chat-aware resolution lives in `designTurnPages` (main) and `useDesignView` (renderer); the planned `chatPageId` helper was built and then removed as unused (final review). | +| `designTurnPages` resolver | Shown this turn → message page → kept view page → first page (`views.ts:283`). | Insert `doc.chatPages[chatId]` before the first page. | +| Renderer shown page (`use-design-view.ts:61` `shownPageId`) | View page → newest earlier page → first page. | View page → claim → newest earlier page → first page, and report when the fallback differs from the view. | +| `DesignCanvasViews` | `showPage` mints a `focusId`. Views persist per workspace. `forget` runs on chat delete. | Add `pageIdsOf(workspaceId, exceptChatId)` for entry rule 3. Claims show their page through `showPage`. | +| Entry (`written-pages.ts:362` `entryPlacement`, A21) | `entry: { pageName, hasView }`. Returns early when the chat wrote no pages, so nothing is claimed. | The claim rules in D2. Drop `hasView`. Claim even with no written pages. | +| Entry vs consent | `setDesignMode` starts entry with `void` (`chat-application-service.ts:407`). The consent card's `enter` (`design-canvas-main.ts:41`) awaits only `setDesignMode`, so the tool answers "entered" before entry has claimed. | The consent path awaits entry (Task 6). | +| `canvas_page` tool | add, rename, duplicate, delete (`force` covers the person's or locked frames), move, show (`canvas-tools.ts:1655`). | Add `use`. One refusal for delete. Mark the chat's page in `pagesAnswer`. | +| `forgetChat` (`cleanup.ts`) | Drops the chat's comments and view. The live delete runs it before and after the commit (`chat-application-service.ts:840,857`). Startup recovery runs it once, before `chatStore.remove` (`main/index.ts:2604`). | A required `scope`. The claim, `namedFor` and artifact frames go after the remove commits, in both paths. | +| Title changes | `rename`, `replaceTitleIfUnchanged`, `replaceAutoTitle` and the first-message seed in `appendMessage` (`chat-store-core.ts:1933,1972,2449,2317`). No listener. | `onTitleChanged`, fired after the write resolves, outside the chat lock (Task 4). | +| Workspace remove | Deletes the canvas, its corrupt copies and the views file (`workspace-application-service.ts:543`). | None. | +| Managed-worktree delete, create rollback, startup recovery | Go through the worktree service's `removeWorkspace`, wired to `removeDesignCanvasWorkspace` (`workspace-worktree-application-service-main.ts:143`, `main/index.ts:2749`). Covered by `workspace-worktree-application-service.test.ts` (from line 18, rollback cases near 174 and 814). | Confirm only (Task 9). | +| Attach carry (`carry.ts`) | Appends pages and calls `showPage(firstPage)`. Doesn't copy `chatPages`. | Claim the first carried page in the same update. | + +## Global Constraints + +- **Schema.** No version bump. `version: 3` gains one optional page field, `namedFor?: string`, a safe chat id (`isDesignChatId`). Pre-1.0, no migration: a 1a document has `chatPages: {}` and no `namedFor`, and both read fine. +- **Cap.** `chatPages` holds at most 2 000 entries. `claimPage` enforces it explicitly: it evicts entries of chats that no longer exist first, and otherwise throws `ChatPagesFullError` (`"This canvas has too many chats with pages of their own."`). `mergeSavedChatPages` never adds entries (D3), so it has no cap check and never refuses a person's save. Parse has no cap today (`schema.ts:377-382`); 1b makes it drop entries past 2 000 and count them in `dropped`, as it does for frames, so a hand-edited file is never set aside whole. Every caller of `claimPage` that is part of a larger write (the lazy claim, attach carry) catches `ChatPagesFullError` and skips only the claim. +- **Where claims are written.** Every claim read and write happens inside `store.update`'s mutate on the latest document. Main's checks that need I/O (which chats still exist, other chats' kept views) run before the update. A claim that appears after the check counts as a live chat's. +- **Saves.** A person's save (`DesignCanvasStore.save`) never adds or moves a claim on its own say, except to restore entries that the store recorded when the page was deleted, and to send a chat whose page the save removes back to the page the save names for it when both documents have that page (D3). The save's answer carries the merged claims back. +- **Undo.** Claim changes are never undo steps: + - entry, the lazy claim inside a tool edit, title-follow and cleanup updates are carried into every kept step; + - the save merge keeps a `canvas_page use` claim when the person undoes that turn (D3). +- **Naming other chats.** Tool answers and picker labels name other chats only by count, never by title or id. A page made for a chat carries the chat's title as its name; that is intended. +- **AGENTS.md:** + - no source-grep tests; + - new test files are registered in `scripts/ci-test-registry.json` and in `test:design-mode` in `package.json`, then `npm run test:ci-policy` is run; + - docs change in this PR; + - window-opening E2E runs through `npm run test:e2e:space`; + - the picker change needs before and after screenshots in the PR body. +- **Tests.** A test that can't fail before its task's change is marked **(guard)** and kept only where it pins a rule a later change could break. + +## Data rules + +**D1. Who may claim.** Only main, and only for the acting chat: +- design-mode entry, for the chat entering (Task 6); +- the lazy claim, for the chat whose design turn writes the canvas (Task 8); +- `canvas_page use`, for the chat whose turn calls it. It sets `chatPages[deps.chatId]` only (Task 7); +- attach carry, for the attaching chat (Task 9). + +No chat ever sets another chat's entry. Other chats' entries change only by: +- page delete, which reassigns them (D4); +- chat delete or move, which drops the leaving chat's own entry (Task 9). + +The renderer never writes a claim beyond what the store's merge allows (D3). Bot chats can't have design mode, so they never claim. Several chats may share a page. + +**D2. Claim on entry.** When design mode turns on, `placeWrittenPagesOnCanvas` with `entry` decides the chat's page in one update. Before the update, main reads: +- which claimed chats still exist (`chatStore.getMeta`); +- the other chats' kept view pages (`DesignCanvasViews.pageIdsOf(workspaceId, chatId)`). + +Claims of chats that no longer exist count as absent. The rules, in order: +1. The chat already has a live claim (its entry names an existing page). Keep it. Missing written pages go there; pages already on the canvas are not placed again. No new page. +2. Some of the chat's written pages are already on the canvas. Claim the page holding the most of them (on a tie: the resolved page, then the earliest page). Pages another live chat claims are not counted; when only such pages hold them, go on to rules 3 and 4. This is A21's rule, now written as a claim. +3. The resolved page (kept view page, else first page) is taken as it is, with no rename and no `namedFor`, when: + - its `namedFor`, if any, names this chat; + - and no other live chat claims it; + - and either it holds no frames, or no other chat's kept view is on it. + + An empty page another chat claims is not shared: the second chat on a fresh canvas gets a page of its own (rule 4, spec §6.1). + + This covers the first chat on a fresh canvas, canvases seeded by tests, and a 1a canvas only this chat has looked at. +4. Otherwise, add a page right after the resolved page, named after the chat (D5), with `namedFor: chatId`, and claim it. At the 200-page limit, claim the resolved page (shared) instead. + +After the update, main always calls `pages.show(workspaceId, pageId)`, so the view and the open canvas move to the claimed page. Then it runs the title follow for the chat once (D6), in case the title changed while entry ran. `entry.hasView` is gone. Rule 3's view check covers the race it guarded: a mounting canvas reports a view on another chat's page before entry runs. + +**D3. Claims survive undo.** A person's save (the renderer sends a whole document; undo and redo are saves with `undone`) merges in the store with `mergeSavedChatPages(current, saved, deleted)`: +- Start from `current.chatPages`, the stored claims. +- `deleted` is the store's in-memory record, per workspace, of pages removed by any write (save or update) that had claims or a `namedFor`: `pageId → { namedFor?: string; claims: Map }`. It holds at most 200 such pages per workspace, and the oldest go first. Main and the renderer restart together, so a record lost on restart matches an undo history lost on restart. + - The record changes only after the write succeeded (`beforeWrite` can throw, `store.ts:130`, `store.ts:157`). + - A new delete of the same page id replaces its entry; it never merges into the old one. + - A restore removes the restored chats (and the restored `namedFor`) from the entry, and drops the entry once it is empty. So a redo after an undo, and the same page id deleted twice, each act on the newest delete only. +- For a page the save brings back (in `saved`, not in `current`), restore every chat C that `deleted` records on P while `current[C]` is exactly the page that delete moved C to, whatever the save's own entry for C says. *(Amended 2026-11-24, final review: the renderer carries stored claims into its kept steps, so a redo's document no longer names P for C; requiring the saved entry lost the claim on redo. The record alone makes this safe: it holds only what the store saw.)* A chat that is missing from `current` is never brought back: a live chat of this workspace always has its entry (only dead chats are evicted), so a missing entry means C was deleted or moved away. The merge therefore never adds an entry, so it never hits the cap and never refuses a person's save. +- Every resulting entry whose page is not in `saved` (the save deleted that page) goes to the page the save names for that chat when both `saved` and `current` have that page, else to `saved.pages[0]`, and is recorded in `deleted`. *(Amended 2026-11-24: undoing a turn that added Q and used it puts the chat back on its own earlier page, not the first page, which may be another chat's; the redo then brings Q's claim back through the record.)* +- `namedFor`: a saved page keeps it only when `current`'s page with that id has the same value, or when the page is brought back and its `deleted` entry holds that `namedFor` for a chat that is still live in this workspace. A save can always drop it, as a hand rename does. +- "Live" everywhere in 1b (`isLive`) means the chat's metadata exists **and** its `workspaceId` is this canvas's workspace. A chat that moved away is not live here. + +The answer to a save the merge changed (`{ ok: true, revision, chatPages, namedFor }`, Task 2) gives the stored claims and each page's `namedFor`. The renderer applies them to `server` and `local`, and carries them into kept steps as a non-undo change. + +So: +- undoing an unrelated edit, or an Aiden turn that called `canvas_page use`, never loses or moves a claim, and the picker keeps showing the stored claim; +- undoing a page delete brings the page back with its claims, unless a chat has claimed elsewhere since; +- a renderer can't move a claim onto a page id the store never saw claimed. + +**D4. Page delete.** `deletePage` reassigns every entry naming the deleted page to the first page left, whoever deletes: +- the person in the picker (shared `deletePage` in the renderer, then the store's merge); +- Aiden through `canvas_page delete`; +- entry's retraction, which instead removes the chat's claim on the page it added. + +`canvas_page delete` without `force` checks two things on the latest document: +- the person's or locked frames on the page; +- other live chats' claims on it. + +If either applies, it refuses once, naming what applies. For example: `"That page holds 2 frames the person added or locked and is the page of 1 other chat. Delete it only if the person asked, and then pass force: true."` Counts are pluralised: "1 frame" / "N frames", "1 other chat" / "N other chats". Deleting the acting chat's own page needs no `force` for its claim. The person's picker delete is not refused (it already has an Undo toast). + +A chat whose page another chat deleted reads, in order: its view page, which is gone; its claim, now the first page; the first page. It doesn't get a new page on its next entry, because its claim is live (D2 rule 1). + +Undoing chat A's turn that added page Q, after chat B started using Q, removes Q (the save brings nothing back) and reassigns B to the first page. + +**D5. Names.** A page made for a chat is named `uniquePageName(doc, title)`: +- whitespace is collapsed and the name is cut to 60 characters; +- an empty title gives `"Chat"`; +- when another page already has that name (case-insensitive), the name gets `" 2"`, `" 3"` and so on, with the base cut so the suffix fits. + +So `canvas_page`'s by-name lookup stays unambiguous for pages Aiden names. Pages the person names may still repeat; that is unchanged. + +**D6. Rename with the chat.** +- **What follows.** A page with `namedFor: chatId` takes the chat's current title (through D5, ignoring its own name). +- **When.** After any title change, which covers four writers: + - `rename` (sidebar, title bar, phone); + - `replaceTitleIfUnchanged`; + - `replaceAutoTitle`, which usually lands after entry, so the page goes from "New chat" to the real title; + - the first-message seed in `appendMessage`. +- **How.** `follow(chatId)` ignores the event's title. + - It runs in a per-chat serial queue. + - When its turn comes, it reads `chatStore.getMeta(chatId).title` and writes through `DesignChatCanvases`, so the workspace-exists `beforeWrite` applies. + - It writes only when a page follows the chat and its name would change. + - Listeners fire after the title write resolves, outside the chat lock. + - Entry's late check calls the same `follow`, so two quick renames and an entry running together end on the newest title. +- **What stops it.** + - `renamePage` (the picker's Rename and Aiden's `canvas_page rename`) clears `namedFor`. + - Chat delete clears it; moving the chat clears it or deletes the page (Task 9). + - `duplicatePage` and `appendCanvasPages` never copy it. +- **Brought back.** A page an undo brings back keeps `namedFor` only for a chat that is live in this workspace: `DesignChatCanvases.save` asks `chatIsLive` for the chats the saved pages are named for before it waits on the store's chain, and passes the answer to the merge. +- **Not the claim.** It follows `namedFor`, not the claim, so a chat that used another page still renames the page made for it. + +**D7. View page versus claimed page.** +- Resolution order: + - main, through `designTurnPages`: a page Aiden showed this turn, the message's page, the chat's kept view page, `chatPages[chatId]`, then the first page; + - the renderer, through `useDesignView`: the view page, the claim, the newest earlier page, then the first page; + - on both sides each step counts only while its page exists, and the claim comes right after the view. +- When the renderer shows a fallback page different from `state.pageId`, it schedules a view report, so main's kept view matches what is on screen. +- The view is what the person looks at. Pans and page switches change it, never the claim. +- The claim changes only through D1 and D4. Claims call `showPage`, which mints a `focusId` (A18). A delete's reassignment shows nothing to other chats: their canvases fall through the order above. + +**D8. Two chats' turns at once.** Every claim read and write happens inside one `store.update` mutate on the workspace's chain: +- `canvas_page use` checks that the page exists on the latest document; +- delete's checks and its reassignment, entry's rules and the lazy claim all run on the latest document. + +So: +- chat A's `use P` racing chat B's `delete P` either fails with "There is no page named…" or lands and is then reassigned; +- two chats entering a fresh canvas at once end with the first on Page 1 (rule 3) and the second on a new named page (rule 4: Page 1 now holds the first chat's claim and view); +- a turn whose page was deleted mid-turn resolves to the claim on its next call; +- the consent path awaits entry, so Aiden's first placement after "entered" lands on the claimed page (Task 6). + +**D9. Chats with no claim.** A chat can have no claim: +- it was in design mode when the app upgraded; +- it moved from another workspace; +- it attached without carried pages. + +Its next entry claims by D2. Rule 3 checks other chats' views, so it doesn't take a page another chat is working on. If it writes the canvas in a design turn first, the lazy claim (Task 8) claims the page the write landed on, inside that write. Reads and canvas mounts never claim. Attach carry claims the first carried page in its own update, without `namedFor` (carried pages are named " · <page>"); a `ChatPagesFullError` there skips only the claim. The hidden canvas's own `chatPages` and `namedFor` never come over. + +**D10. Legacy documents.** v1 and v2 files are gone (1a's layout wipe). A 1a v3 document has `chatPages: {}`. Its chats resolve as in 1a until they enter design mode again, write the canvas in a design turn, or call `canvas_page use`. Until then, `canvas_page delete` doesn't protect their page. No sweep runs at startup. + +## Review Focus + +1. **Undo never loses a claim or a page.** Undoing a page delete brings back the page and its claims even after another writer changed the page list, and the saving canvas shows the stored claims (D3, decisions 1–3). Tests: Tasks 1 and 2. +2. **Two chats enter one workspace and each gets its own page, with no page jumps when switching between them after entry** (D2, D7). Tests: Tasks 3, 6 and 11. +3. **A page another live chat uses is never deleted by Aiden without `force`, and a deleted page's chats land on the first page** (D4). Test: Task 7. +4. **Chat delete, live or recovered at startup, leaves the page and other chats' frames, and a failed delete leaves the chat's claim and artifacts** (Task 9). +5. **The title follow ends on the newest title, writes nothing when no page follows the chat, and never renames a page the person renamed** (D6). Test: Task 4. + +## Review amendments (2026-11-23) + +Two adversarial reviews (data and races; lifecycle, UI and tests) were settled in `p1b-plan-decisions.md`. Each decision maps to where the plan handles it. Where a decision needed a change against the code, the change is stated. + +| # | Decision | Where | +|---|---|---| +| 1 | `changesBetween` applies page changes item by item | Task 1, Review Focus 1 | +| 2 | The save's answer returns the merged claims; the renderer applies them and carries them | D3, Task 2 | +| 3 | Restore a saved claim only when the stored entry is missing or names where the delete moved it | D3, Task 2. *Changed:* the store also keeps an in-memory record of which chats were on each deleted page and where each went. Against the code, the store can't tell a page an undo brings back from a page the renderer just created (both are simply absent from `current`). With only the decision's rule, a renderer could move a chat sitting on the first page onto a new page id, which the decision's own test forbids. The record also replaces `current.pages[0]` with the exact page each chat was moved to, which stays right after the pages are reordered. | +| 4 | Startup recovery prunes fully; claims of missing chats are ignored | Task 9 (recovery), D2, D4, Risk 9. *Changed slightly:* the read before the remove stays at `main/index.ts:2603`. The pre-remove call becomes `scope: "comments"` and a new post-remove call uses `"all"`, matching the live delete instead of moving all pruning before the remove. | +| 5 | The title follow reads the title itself, runs in a per-chat queue, goes through `DesignChatCanvases`, and comes before entry | D6, Task 4, Risk 5 | +| 6a | Rule 3 checks other chats' views; `pageIdsOf` | D2, Task 5 | +| 6b | Lazy claim on the first canvas write | D9, Task 8 | +| 7 | The consent path awaits entry | D8, Task 6 | +| 8 | Fallback order view → claim → earlier → first; report on fallback | D7, Task 3 | +| 9 | One refusal for `force` | D4, Task 7 | +| 10 | Counts only; page names may carry titles | Scope, Global Constraints | +| Minor | `use` on own page writes nothing | Task 7 | +| Minor | Entry always shows | D2, Task 6 | +| Minor | Cap enforced explicitly | Global Constraints, Task 1 | +| Minor | Rule 3 never takes another chat's `namedFor` page | D2 | +| Minor | Pluralised messages, picker labels, accessible name | D4, Task 10 | +| Minor | Prompt line | Task 7 | +| Minor | Undoing A's turn that added Q, after B used it | D4 | +| Minor | Brought-back page with a deleted chat's `namedFor` | D6 | +| Minor | Risk 11 deleted | Scope (phones get no canvas tools) | +| Minor | Guards labelled | Global Constraints and the tasks | +| Minor | Moving an empty chat deletes its empty named page | Task 9 | +| Minor | E2E fixes | Task 11 | +| Minor | PRODUCT.md wording | Task 11 | +| Minor | Worktree confirm only | Task 9 | +| Open questions 1–5 | Settled | Rule 3 (1), Task 10 (2), D9 (3), Task 9 (4), D4 (5) | +| Re-check 1 | Rule 3 never shares an empty page another chat claims | D2 rule 3, Task 6 fixture | +| Re-check 2 | Restore only when `current[C]` is exactly where the delete moved C; `isLive` includes the workspace; the merge never adds entries or refuses | D3, Global Constraints (Cap), Task 2 tests | +| Re-check 3 | The delete record holds `namedFor` too (`DeletedPage`) | D3, Task 1 interfaces, Task 2 | +| Re-check 4 | Dead chats' entries go in entry, `delete` and `use`; Risk 9 corrected | Risk 9 | +| Re-check 5 | Parse drops past the cap instead of refusing; attach carry skips a refused claim | Global Constraints (Cap), D9 | +| Re-check 6 | Lazy claim checks on `next` and waits for a pending entry | Task 8 | +| Re-check 7 | Record changes after a successful write; replace on re-delete; restore removes | D3, Task 2 | +| Re-check 8 | PRODUCT.md wording on images | Task 11 | + +--- + +### Task 1: Shared chat-page rules and page-aware undo + +**Files:** +- Create: `renderer/shared/design-canvas/chat-pages.ts` +- Modify: + - `renderer/shared/design-canvas/schema.ts` (`DesignPage.namedFor`, `DESIGN_CANVAS_LIMITS.chatPages = 2000`) + - `renderer/shared/design-canvas/pages.ts` (`deletePage` reassigns, `renamePage` clears `namedFor`) + - `renderer/shared/design-canvas/view.ts` (`chatPageId`, later removed as unused) + - `renderer/design/canvas-history-core.ts` (`changesBetween`) +- Test: create `renderer/shared/design-canvas/chat-pages.test.ts`; extend `schema.test.ts`, `pages.test.ts`, `view.test.ts`, `renderer/design/canvas-history-core.test.ts` + +**Interfaces** (all pure; each returns `doc` itself when nothing changes): +- `DesignPage = { id: string; name: string; namedFor?: string }`. +- `chatPageId(doc: Pick<DesignCanvas, "pages" | "chatPages">, view: { pageId?: string } | null | undefined, chatId: string): string`: the view page while it exists, else the claim while its page exists, else the first page. *(Removed in the final review: nothing used it; Task 3 put the order into `designTurnPages` and `useDesignView`.)* +- `chatsOnPage(doc, pageId, isLive?: (chatId: string) => boolean): string[]`. +- `uniquePageName(doc, base, exceptPageId?)` (D5). +- `claimPage(doc, chatId, pageId, isLive?)`: throws a `ChatPagesFullError` when the cap is reached and no dead chat's entry can be evicted. The caller checks that the page exists. +- `addChatPage(doc, chatId, title, id, after?, isLive?)`: `addPage` with `uniquePageName`, `namedFor` and the claim. Returns `doc` at the page limit. +- `followChatTitle(doc, chatId, title)` (D6). +- `forgetChatOnCanvas(doc, chatId)`: + - drops the claim and the chat's `namedFor` marks; + - drops its artifact frames (`kind === "artifact" && chatId === chatId`) and any chat's comments on them (`commentsWithoutFrames`); + - lets go of connectors (`syncConnectors`) and refits groups (`refitGroups`); + - leaves the chat's comments to the existing comment pass. +- `forgetChatMove(doc, chatId)`: `forgetChatOnCanvas`, plus deleting the page made for the chat when it has no frames and no comments, no other chat claims it, and it isn't the only page. Otherwise `namedFor` is just cleared. +- `type DeletedPage = { namedFor?: string; claims: Map<string, string> }` (chat id → the page the delete moved it to). +- `mergeSavedChatPages(current, saved, deleted, isLive?)` → `{ doc, changed: boolean, deletedNow: Map<pageId, DeletedPage>, restored: Map<pageId, DeletedPage> }` (D3). `restored` is what the store removes from the record once the write succeeded. +- `deletedClaims(before, after)` → `Map<pageId, DeletedPage>` for every page `after` removed that had claims or a `namedFor`. The store uses it for updates as well as saves. +- `deletePage(doc, id)` reassigns entries naming `id` to the first page left. +- `renamePage` drops `namedFor` when the name changes. +- `changesBetween(from, to)` (decision 1): + - pages and their `namedFor` change item by item: remove the pages `to` removed, insert added pages after their predecessor in `to` (at the start when they have none), apply renames and `namedFor` changes, take the order from `to` only among pages both share, and keep pages that exist only in the step; + - claims: apply `to.chatPages`' differences from `from.chatPages` (added, changed, removed) to the step, then reassign entries whose page is gone in the step to the step's first page; + - comments still follow their frames and pages as today. + +- [x] **Step 1: Write failing tests** + - `canvas-history-core.test.ts`: + - `a page another writer adds or renames does not stop an undo from bringing back a deleted page, its frames and its comments`. History: the person deletes P (with a frame and a comment). Take in a store update that adds R and renames Q. Undo. P is back, in its old place among the shared pages, with its frame and comment; R and Q's new name are kept; + - `a claim another writer made reaches every kept step, so undoing a page delete brings back the current claim`. History: delete P (claimed by B), then take in an update where B claims Q. Undo, and the doc has P and `chatPages.B === "Q"`; + - `a page that exists only in an older step stays in that step after a carry`. + - `chat-pages.test.ts`: + - `chatPageId prefers the view's page, then the claim, then the first page, skipping pages that are gone` (removed with `chatPageId`); + - `uniquePageName adds the lowest free number and cuts the base so the name stays within 60 characters`; + - `uniquePageName ignores the page being renamed`; + - `addChatPage adds a named page after the given page, marks it and claims it; at the page limit it changes nothing`; + - `claimPage at the cap evicts a dead chat's entry, and refuses when every entry is a live chat's`; + - `parse keeps the first 2 000 chatPages entries and counts the rest in dropped, without setting the canvas aside` (schema.test.ts); + - `followChatTitle renames only pages named for that chat, and changes nothing when none is`; + - `forgetChatOnCanvas drops the claim, the named-for marks and the artifact frames with the comments on them, and keeps other chats' frames, the page and the chat's notes`; + - `forgetChatOnCanvas lets go of an arrow joined to a removed artifact frame and refits its group`; + - `forgetChatMove deletes the empty page made for the chat, and keeps a page with frames, a comment or another chat's claim, clearing namedFor`; + - `mergeSavedChatPages keeps the stored claims when the save carries stale ones`; + - `mergeSavedChatPages restores a claim for a brought-back page only when the delete record has it and the chat is still where the delete moved it`; + - `mergeSavedChatPages does not let a save move a chat on the first page onto a new page id`; + - `mergeSavedChatPages reassigns claims on a page the save removed and records them`; + - `mergeSavedChatPages never adds namedFor to a stored page without it, and restores it on a brought-back page the record holds`. + - `schema.test.ts`: `keeps namedFor only when it is a safe chat id`; `refuses more than 2000 chatPages entries`. + - `pages.test.ts`: + - replace `deletePage drops chatPages entries for the deleted page` with `deletePage moves the deleted page's chats to the first page left`, including deleting the first page; + - `renaming a page stops it following its chat`; + - `duplicating a page copies neither namedFor nor claims` **(guard)**. +- [x] **Step 2:** Run `npx tsx --test renderer/shared/design-canvas/chat-pages.test.ts renderer/shared/design-canvas/schema.test.ts renderer/shared/design-canvas/pages.test.ts renderer/shared/design-canvas/view.test.ts renderer/design/canvas-history-core.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement. `appendCanvasPages` builds `{id, name}` pages, so it drops `namedFor`; note that in its comment. Register `chat-pages.test.ts` in `scripts/ci-test-registry.json` and `test:design-mode`. +- [x] **Step 4:** Rerun, plus `npx tsx --test renderer/design/use-design-canvas.test.tsx` (history consumer). Expected: PASS. Run `npm run test:ci-policy`. +- [x] **Step 5:** Commit `fix(design): undo keeps deleted pages; chat page rules`. + +### Task 2: The store merges claims and the saving canvas sees them + +**Files:** +- Modify: + - `main/services/design-canvas/store.ts` (`save`, `update`, `DesignCanvasSaveResult`, the per-workspace delete record) + - `main/handlers/design-canvas.ts` (passes the answer through), `renderer/lib/ipc.ts` (the result type) + - `renderer/design/use-design-canvas.ts` (the `result.ok` branch near line 257) +- Test: `main/services/design-canvas/store.test.ts`, `renderer/design/use-design-canvas.test.tsx` + +**Interfaces:** +- `DesignCanvasSaveResult` `ok` arm: `{ ok: true; revision: number; chatPages?: Record<string, string>; namedFor?: Record<string, string> }`. The two optional fields are present only when the merge changed the saved document; `namedFor` maps page id to chat id. +- `save` runs `mergeSavedChatPages(current, parsed.doc, this.deleted(workspaceId))` on the workspace chain, after the revision check and before `withRemovedPagePaths`. After the write succeeds, it replaces the record's entries with `deletedNow` and removes `restored` from it. +- `update` replaces the record's entries with `deletedClaims(current, next)` after its write succeeds. The record is cleared on `delete(workspaceId)`. +- Extra store tests: + - `a chat deleted or moved after its page was deleted is not brought back by undoing the delete`; + - `undoing the delete of a page made for a chat that now uses another page brings back its namedFor`; + - `a write whose beforeWrite throws leaves the delete record unchanged`; + - `deleting the same page id twice and undoing restores the claims of the newest delete only`. +- Renderer, on `ok` with those fields: + - `server = applyStoredClaims({ ...doc, revision })`; + - `local` gets the same claims (`applyStoredClaims(local)`); + - `history = takeIn(history, { before: local, from: doc, to: server })` with no `aidenTurn`, so the claims reach every kept step and make no step. + +- [x] **Step 1: Write failing tests** + - `store.test.ts`: + - `a person's save cannot add or move a claim`: store `{A: P1}`; save `{A: P2, B: P1}`, both pages present; stored stays `{A: P1}`, and the answer carries `chatPages: {A: P1}`; + - `a stale claim in a save after the chat's own turn does not move it back` (review A's M1): A's turn claims Q (update); A's canvas, still holding `{A: P}`, saves an unrelated edit at the new revision; the stored claim stays Q; + - `an undo that brings a deleted page back brings its claims back`: P1, P2 and `{B: P2}`; save without P2 (B moves to P1); save with P2 and `{B: P2}`; B is on P2; + - `a renderer cannot move another chat's claim to a new page id`: `{B: P1}` with P1 first; save a new page P9 and `{B: P9}`; B stays on P1; + - `a page Aiden deletes is recorded, so the person's undo of a later edit cannot resurrect claims for it unless it brings the page back`; + - `a save that deletes a page moves its chats to the first page, even when the renderer's copy forgot them`; + - `a save cannot mark a page as following a chat`. + - `use-design-canvas.test.tsx`: `undoing a turn that used a page keeps the picker on the stored claim`. The fake save answers with `chatPages`; after the save the hook's `doc.chatPages` equals the stored ones, and one more undo does not bring the stale claim back. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/store.test.ts renderer/design/use-design-canvas.test.tsx`. Expected: FAIL. +- [x] **Step 3:** Implement. Update the `save` doc comment to say claims are main's, and how the record works. +- [x] **Step 4:** Rerun, plus `npx tsx --test main/handlers/design-canvas.test.ts`. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): saves keep main's chat pages and report them back`. + +### Task 3: Page resolution falls back to the claim, on both sides + +**Files:** +- Modify: `main/services/design-canvas/views.ts` (`designTurnPages`), `renderer/design/use-design-view.ts` (`shownPageId`, report scheduling) +- Test: `main/services/design-canvas/views.test.ts`, `renderer/design/use-design-view.test.tsx`, `renderer/design/design-canvas.test.tsx` + +**Interfaces:** +- `DesignTurnPages.resolver(workspaceId)` returns `(doc: Pick<DesignCanvas, "pages" | "chatPages">) => DesignChatView`, with `doc.chatPages[chatId]` between the kept view page and the first page. `view()` takes the same `Pick`. +- `shownPageId(doc, state, chatId)`: the view page, the claim, the newest existing earlier page, then the first page. +- When the shown page differs from `state.pageId` (a fallback), the hook schedules a report of the shown page, through the 250 ms debounce. + +- [x] **Step 1: Write failing tests.** Check that each fails before the change. + - `views.test.ts`: + - `with no view, a turn works on the chat's claimed page`; + - `when the view's page is gone, a turn works on the claim before the first page`; + - `the view still wins over the claim` **(guard)**. + - `use-design-view.test.tsx`: + - `when the view's page is gone, the canvas shows the claim before an earlier page`: state with `earlier: [P1]`, the claim on P3, the view's P2 deleted; the shown page is P3; + - `a canvas with no kept view opens on the claim`; + - `a fallback page is reported to main`: the fake `reportDesignCanvasView` receives P3 after the debounce. + - `design-canvas.test.tsx`: `when another chat deletes the page on screen, the canvas shows this chat's claim`. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/views.test.ts renderer/design/use-design-view.test.tsx renderer/design/design-canvas.test.tsx`. Expected: FAIL (except the guard). +- [x] **Step 3:** Implement. Update both doc comments. Remove A12's "1b note" wherever 1a left it in code comments. +- [x] **Step 4:** Rerun, plus `npx tsx --test main/services/design-canvas/canvas-tools.test.ts main/services/design-canvas/written-pages.test.ts`. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): a chat falls back to its own page`. + +### Task 4: Title listeners and the title follow + +**Files:** +- Modify: `main/services/chat-store-core.ts`, `main/services/design-canvas/main.ts` +- Create: `main/services/design-canvas/title-follow.ts`, `main/services/design-canvas/title-follow.test.ts` +- Test: `main/services/chat-store-core.test.ts`, the new test (register it) + +**Interfaces:** +- `chatStore.onTitleChanged(listener: (chatId: string) => void): () => void`. + - Fired once after `rename`, `replaceTitleIfUnchanged`, `replaceAutoTitle`, or an `appendMessage` that seeded the title, resolves with a changed title. That is after the method's `shared(...)` returns, outside the chat lock. + - A listener that throws is caught and logged, as `onIndexChanged` does (`chat-store-core.ts:539`). +- `createDesignTitleFollow({ canvases: Pick<DesignChatCanvases, "update" | "workspaceIdOf">, titleOf(chatId): Promise<string | undefined>, broadcast })` returns `{ follow(chatId): Promise<void> }`. + - Calls for one chat run one after another (a per-chat promise chain). A call queued behind a running one for the same chat merges into the next run. + - Each run reads the title when it starts and updates through `DesignChatCanvases.update(chatId, …)`, writing nothing (sentinel) when `followChatTitle` returns `doc`. + - It broadcasts `{ workspaceId, chatId, revision }` and logs failures. A chat or workspace that is gone is a no-op. +- `main.ts` subscribes `chatStore.onTitleChanged((chatId) => void designTitleFollow.follow(chatId))` and exports `designTitleFollow` for entry (Task 6). + +- [x] **Step 1: Write failing tests** + - `chat-store-core.test.ts`: + - `a rename, a replaced title, an auto-title and the first-message seed each tell title listeners once, after the write`; + - `a rename that changes nothing tells no one`; + - `a listener that throws does not fail the rename`. + - `title-follow.test.ts` (real `DesignCanvasStore` on a temp root, `DesignChatCanvases` with fakes): + - `a chat's rename renames the page made for it and tells open canvases`; + - `a page the person renamed no longer follows`; + - `a rename of a chat with no page made for it writes nothing` (revision unchanged); + - `a title another page already has gets a number`; + - `two quick renames and an entry running at once end on the newest title`: three `follow` calls race a `titleOf` that changes between them; the final page name is the last title, and no run writes after a newer one; + - `a follow after the workspace was removed writes no file`. +- [x] **Step 2:** Run `npx tsx --test main/services/chat-store-core.test.ts main/services/design-canvas/title-follow.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement. Register the new test. `packages/cli` bundles `chat-store-core.ts`, so run `npm run cli:build`. +- [x] **Step 4:** Rerun. Expected: PASS. Run `npm run test:ci-policy`. +- [x] **Step 5:** Commit `feat(design): a page made for a chat follows its title`. + +### Task 5: Other chats' kept views + +**Files:** +- Modify: `main/services/design-canvas/views.ts` +- Test: `main/services/design-canvas/views.test.ts` + +**Interfaces:** `DesignCanvasViews.pageIdsOf(workspaceId, exceptChatId): Promise<Set<string>>`, the kept view pages of every other chat on that workspace. It loads the views file the way `get` does. + +- [x] **Step 1: Write failing tests:** `pageIdsOf lists other chats' kept pages, not the asking chat's, and reads them from the file after a restart`. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/views.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement. +- [x] **Step 4:** Rerun. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): main can list the pages other chats look at`. + +### Task 6: Entry claims the chat's page + +**Files:** +- Modify: + - `main/services/design-canvas/written-pages.ts` (`entryPlacement`, `placeWrittenPagesOnCanvas`, `retractPlacedFrames`) + - `main/services/chat-application-service.ts` (`setDesignMode` option `awaitEntry`) + - `main/services/chat-application-service-main.ts` (`designPagesOnEntry` wiring) + - `main/handlers/design-canvas-main.ts:41` (the consent `enter` passes `awaitEntry: true`) +- Test: `main/services/design-canvas/written-pages.test.ts`, `main/services/chat-application-service.test.ts` + +**Interfaces:** +- `entry?: { pageName: string; otherViews(workspaceId): Promise<Set<string>>; isLive(chatIds: string[]): Promise<Set<string>> }`; `hasView` is removed. + - Before the update, entry reads the doc's claimed chat ids through `isLive`, and other chats' views through `otherViews`. + - The mutate applies D2. A claimed chat id not checked counts as live. +- With `entry`, there is no early return when no written page exists. The update claims, and the no-change short cut (`UNCHANGED`) applies only when no frame is placed and the claim didn't change. +- The result always has `pageId`, the chat's page, and `focusId` from the `show` that always follows. +- `shouldSave` false (design mode turned off meanwhile) writes neither frames nor claim, and shows nothing. +- `retractPlacedFrames`, given the page entry added, removes the chat's claim on it as well as the page. +- `designPagesOnEntry` keeps `pageName: chat.title`. After the claim, it calls `designTitleFollow.follow(chat.id)` (Task 4). +- `setDesignMode(chatId, enabled, options & { awaitEntry?: boolean })`: with `awaitEntry`, it awaits `designPagesOnEntry` (logging, not throwing, on failure) before returning. The consent `enter` passes it, so the `design_mode` tool answers "entered" only after the claim. + +- [x] **Step 1: Write failing tests** (edit the A21 tests that assumed 1a's rule, seeding claims where needed): + - `the first chat on a fresh canvas claims Page 1 without renaming it, adds no page, and shows it`, with no written pages; + - `chat B entering a workspace whose first page is chat A's gets a page named after B, claimed and shown`: `chatPages: {A: page-1}`, A alive, page-1 holding no frames (so the test pins that an empty claimed page is not shared), B with no written pages; + - `a page with frames that another chat's kept view is on is not taken; B gets its own page`: no claims, A's view on page-1; + - `a page with frames that only this chat has looked at is claimed as it is` (the 1a-upgrade case); + - `a claim of a chat that no longer exists does not stop the page being claimed`; + - `a page named for another chat is never taken by rule 3`; + - `a chat entering again keeps its claim, adds no page and still shows it`; + - `the chat's earlier pages already on the canvas make the page holding most of them its claim`; + - `two chats entering a fresh canvas at once end on Page 1 and a new page`; + - `B's new page is numbered when a page already has B's title`; + - `at the page limit, a chat whose page is taken shares it`; + - `leaving design mode while entry's file is being written takes back the added page and the claim on it`; + - `with design mode turned off before the write, no claim is made and nothing is shown`; + - `chat-application-service.test.ts`: `entering design mode from Aiden's card waits for the chat's page, so a placement right after lands on it`. A fake entry resolves late; `setDesignMode(..., { awaitEntry: true })` resolves only after it, and a placement through `designTurnPages` then lands on the claimed page. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/written-pages.test.ts main/services/chat-application-service.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement with Task 1's helpers. Rewrite the `entryPlacement` doc comment to list D2's rules. +- [x] **Step 4:** Rerun, plus `npx tsx --test main/services/design-canvas/design-mode-tool.test.ts`. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): a chat claims its page when design mode opens`. + +### Task 7: `canvas_page use`, one delete refusal, and page marks for Aiden + +**Files:** +- Modify: `main/services/design-canvas/canvas-tools.ts`, covering: + - `canvas_page` (line 1655); + - `pagesAnswer` (line 934); + - the design-mode prompt line near 209; + - the load-on-demand summary near 800. +- `DesignCanvasToolDeps` gains `isLive?(chatIds: string[]): Promise<Set<string>>` (production: `chatStore.getMeta`), wired in `llm-client.ts`. +- Test: `main/services/design-canvas/canvas-tools.test.ts`; `skill.test.ts` only if `skill.ts` text changes (it defers to the tools today). + +**Interfaces:** +- **`use`.** The `action` enum gains `"use"`, which needs `page`. + - First it reads. If the chat's claim already names the resolved page, it only shows the page and writes nothing. + - Otherwise it runs an `edit` whose mutate resolves the page with `pageOf` on the latest document. If the claim already names that page there, it throws a no-change sentinel; else it calls `claimPage`. Either way it returns `show`. + - Answer: `{ status: "done", action: "use", page: { id, name }, pages }`. +- **`delete`.** + - Before the edit, it reads which claimed chats are live (`deps.isLive`). + - Inside the mutate, without `force`, it counts the person's/locked frames and the other live chats' claims, and refuses once with D4's pluralised message naming whichever apply. + - With `force`, or when neither applies, it deletes (`deletePage` reassigns). +- **`pagesAnswer`** entries gain `yours: boolean` and `otherChats: number` (live chats only). +- **Description:** `"…move (step -1 or 1), show, or use (make it this chat's own page and show it) a design canvas page… delete needs force: true for a page holding the person's or locked frames or used by another chat, only when they asked."` +- **Prompt line** replaces line 209's first clause: `"Work on the page the person is looking at, which starts as this chat's own page, unless they name another; canvas_page use makes a page this chat's page."` + +- [x] **Step 1: Write failing tests** + - `canvas_page use makes the page this chat's and shows it, leaving other chats' claims alone`; + - `canvas_page use on a missing page is refused and writes nothing` (revision unchanged); + - `canvas_page use on the chat's own page writes nothing and still shows it` (revision unchanged, `focus` called); + - `canvas_page delete refuses a page another live chat uses, and with force deletes it and moves that chat to the first page`; + - `canvas_page delete names both reasons once when the page holds the person's frames and another chat's claim`; + - `canvas_page delete ignores the claim of a chat that no longer exists`; + - `canvas_page delete of this chat's own page needs no force`; + - `the pages list marks this chat's page and counts other chats, naming none of them`: no other chat's id or title appears in the answer; + - `after canvas_page use, a placement with no page in the same turn lands on the used page` **(guard: A1's `shown` step already does this; kept to pin `use` going through it)**. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/canvas-tools.test.ts`. Expected: FAIL (except the guard). +- [x] **Step 3:** Implement. +- [x] **Step 4:** Rerun, plus `npx tsx --test main/services/llm-client*.test.ts`, in case tool schemas or prompt text are asserted by replay. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): canvas_page use and pages other chats rely on`. + +### Task 8: Lazy claim on a chat's first canvas write + +**Files:** +- Modify: + - `main/services/design-canvas/canvas-tools.ts` (`edit`, line 884) + - `main/services/design-canvas/written-pages.ts` (`placeWrittenPagesOnCanvas` without `entry`) + - `main/services/design-canvas/artifact-frames.ts` (`placeArtifactsOnCanvas` line 107, `placeImagesOnCanvas` line 189) +- Test: `canvas-tools.test.ts`, `written-pages.test.ts`, `artifact-frames.test.ts` + +**Behaviour:** Inside the mutate of each design-turn write, after the write's own change, the write checks `next.chatPages[chatId]` and takes the page the write landed on: the page it shows (`canvas_page add` or `duplicate`), else the page of the frames it added or changed, else the turn's page. A delete lands on no page. When the chat has no claim and that page exists in `next`, it calls `claimPage(next, chatId, pageId)`. Answers that list pages (`pagesAnswer`) are built after the claim. At a full `chatPages` the write skips the claim, then asks which claimed chats are live and claims in a follow-up write when a gone chat's entry makes room (`claimWithRoom`). +- Checking on `next` keeps a `canvas_page use` claim made by this same write, and never claims a page this write deleted. +- While an entry for the chat is pending, the lazy claim waits for it: main keeps a per-chat promise for a running entry (`pendingEntries`, set by `designPagesOnEntry` and cleared when it settles, whichever path turned design mode on, including the toolbar's `chat-renderer-mutations.ts:145`), and the design-turn write awaits it before its update. +- It runs only when the write changes something else; a refused or no-change write claims nothing. +- Never on reads (`canvas_read`, `canvas_inspect`), never on mount, never in the person's `designCanvas:placeArtifact` (`main/handlers/design-canvas.ts:415`, not a design turn). +- A cap refusal from `claimPage` skips the claim and lets the write land. + +- [x] **Step 1: Write failing tests** + - `a chat with no claim claims the page its first tool edit lands on, in the same write` (one revision bump); + - `canvas_read claims nothing`; + - `a written page auto-placed in a turn claims for a chat with none`; `an artifact placed in a turn claims for a chat with none`; + - `a chat that has a claim keeps it when it writes on another page`; + - `canvas_page use and a frame placed in the same write keep the use claim`; + - `a write that deletes the turn's page claims nothing`; + - `a write during a pending entry waits for it and keeps the entry's claim`. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/canvas-tools.test.ts main/services/design-canvas/written-pages.test.ts main/services/design-canvas/artifact-frames.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement with one helper in `chat-pages.ts`, `withLazyClaim(doc, chatId, pageId)`. +- [x] **Step 4:** Rerun. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): a chat claims the page its first write lands on`. + +### Task 9: Lifecycle + +**Files:** +- Modify: + - `main/services/design-canvas/cleanup.ts`: `forgetChat(chatId, workspaceId, scope: "comments" | "all" | "move")`, with `scope` required so `tsc` finds every caller. + - `"comments"` is 1a's pass. + - `"all"` adds `forgetChatOnCanvas` in the same update. + - `"move"` adds `forgetChatMove`. + - Each skips the write when nothing changes. + - `main/services/chat-application-service.ts`: + - the live delete's pre-commit pass (line 840) uses `"comments"`, and the post-commit pass (line 857) uses `"all"`; + - `moveEmptyToWorkspace` uses `"move"`. + - `main/index.ts:2603-2605` (`reconcilePendingChatDeletions`): + - keep `getMeta` before the remove and capture the workspace id; + - the pre-remove call uses `"comments"`; + - after `chatStore.remove`, call `forgetChat(chatId, workspaceId, "all")`, logging failures. + - `main/services/design-canvas/carry.ts`: the same update claims `merged.pageIds[0]` for `input.chatId` (D9). +- Test: `main/services/chat-application-service.test.ts`, `main/services/design-canvas/carry.test.ts`, and a recovery test where the reconcile callback is reachable. If `reconcilePendingChatDeletions`' callback lives only in `main/index.ts`, extract it into a small function in `cleanup.ts` (`recoverDeletedChatCanvas(deps, chatId)`) and test that function. + +- [x] **Step 1: Write failing tests** + - `deleting a chat drops its claim, its named-for mark and its artifact frames, and keeps the page, its notes and other chats' frames and claims`; + - `a delete that fails after the first cleanup keeps the chat's claim and artifact frames` **(guard: nothing prunes them before 1b; pins that the pre-commit pass stays comments-only)**; + - `a canvas save that lands while the chat is being deleted does not bring back its claim or artifact frames` (extends the A25 case); + - `a chat delete recovered at startup prunes the claim and artifact frames after the remove`; + - `moving an empty chat drops its claim and deletes the empty page made for it; a page with frames stays, no longer following`; + - `carry.test.ts`: `an attached chat claims the first page it brought along`; `when nothing comes along, no claim is made` **(guard)**. + - Worktree: confirm `workspace-worktree-application-service.test.ts` still asserts that create rollback and managed delete call `removeWorkspace` (from line 18, rollback cases near 174 and 814). No new test. +- [x] **Step 2:** Run `npx tsx --test main/services/chat-application-service.test.ts main/services/design-canvas/carry.test.ts` and the recovery test. Expected: FAIL (except guards). +- [x] **Step 3:** Implement. Update the `cleanup.ts` header comment: a deleted chat's artifact frames and claim go after the delete commits, while its other frames stay as the workspace's work. +- [x] **Step 4:** Rerun. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): chat delete takes its page claim and artifacts off the canvas`. + +### Task 10: The page picker shows how many chats use each page + +**Files:** +- Modify: `renderer/design/design-toolbar.tsx` (`DesignPageMenu`, line 280), and the prop passing `chatId` from `renderer/design/design-canvas.tsx` +- Test: `renderer/design/design-canvas.test.tsx`, or a toolbar test beside it + +**Behaviour.** First read `docs/chatgpt-desktop-ui-inspiration.md`, `docs/chatgpt-ui-element-specimen.html` and `docs/design-guide.md`. Then each page row shows a trailing label in tertiary `text-small`, the pattern in `docs/design-guide.md:286`: +- `"This chat"` on this chat's claim; +- `"This chat · N more"` when others share it; +- `"1 chat"` or `"N chats"` on a page only others use; +- nothing on a page no chat uses. + +Each row's accessible name is the page name, a comma, then the label (`"Page 1, This chat"`). The trigger's `aria-label` stays `Page: <name>`. Counts only; no titles. Semantic tokens only, with no new colours, borders or badges. + +- [x] **Step 1: Write failing tests:** `the page picker marks this chat's page and counts other chats on theirs`. Use Testing Library: open the menu and assert each row's accessible name, covering all four labels. +- [x] **Step 2:** Run `npx tsx --test renderer/design/design-canvas.test.tsx`. Expected: FAIL. +- [x] **Step 3:** Implement. +- [x] **Step 4:** Rerun. Expected: PASS. Take before and after screenshots of the open picker with two chats, light and dark, for the PR body. +- [x] **Step 5:** Commit `feat(design): the page picker shows each page's chats`. + +### Task 11: Two-chats E2E, docs and memory + +**Files:** +- Modify: `tests/e2e/design-canvas.spec.ts` (new test; extend `savedCanvases`' type with `chatPages` and `namedFor`) +- Docs: `PRODUCT.md` (design-mode paragraph, line 69), `README.md` (only if its design-mode line mentions pages), `docs/plans/README.md` (the v2 row), `.memory/design-mode.md`, and this plan's checkboxes. + +- [x] **Step 1: Write the E2E** `two chats on one workspace each get their own page, keep it across switches, and a page another chat uses is not deleted without force`: + 1. Chat A sends "Design the Northwind landing page" and runs `/design`. Assert the saved doc's `chatPages[A] === pages[0].id`. + 2. A's turn places a note through `canvas_place_frame` (fake model tool scenario). + 3. Start chat B in the same workspace. It sends "Sketch the pricing table" and runs `/design`. + - Wait until B's title has settled (poll the title bar until the auto-title has replaced the seed, or turn auto-title off for this test through the fixture). + - Then assert the picker trigger reads `Page: <B's title>`, and A's note is not on screen. + - Assert the saved doc has a second page with `namedFor === B` and `chatPages[B]` naming it. + - Don't assert "no jump" during entry: entry moves B's canvas to its page by design. + 4. B's turn places a note. Switch to A: A's page is on screen with only A's note. Switch back to B: B's page. + 5. Open the picker in B. B's page row is named "<B's page>, This chat", and Page 1 "Page 1, 1 chat". + 6. B's turn calls `canvas_page {action: "delete", page: "Page 1"}`. The scenario's result contains "1 other chat", and Page 1 still exists. + 7. Rename B from the sidebar. The picker trigger and the saved page name follow. + 8. Delete chat B. The saved doc has no `chatPages[B]`, B's page is still there with B's note, and that page has no `namedFor`. + 9. Capture `1440-canvas-two-chats` for the PR body. +- [x] **Step 2:** Run `npm run test:e2e:space -- tests/e2e/design-canvas.spec.ts`. Fix until it passes. If an existing test fails because entry now claims, update the expectation only where the claim causes it, and say so in the commit. +- [x] **Step 3: Docs** + - `PRODUCT.md`, after "each chat remembers its own page and view": + > "Opening design mode gives the chat a page of its own: the page on screen when no other chat is using it, otherwise a new page named after the chat, which follows the chat's title until someone renames the page. Aiden can switch the chat to another page. Deleting a page moves its chats to the first page, and Aiden won't delete a page another chat uses unless the person asks. Deleting a chat removes its comments, its page claim, and the images and visuals it sent from the chat (artifact frames); workspace images, its page, notes and page frames stay." + + Replace "landing on the chat's empty page" with "landing on the chat's page". + - `docs/plans/README.md` v2 row: "Phase 1b (chat pages) built <date>, in review as PR #<n>, plan [p1b](../superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md)." + - `.memory/design-mode.md`: add a "v2 Phase 1b: chat pages" section with D1–D10 and the delete record in short form, and replace "Phase 1b still owns `chatPages` writes and `canvas_page use`". + - Search the docs for stale claims: `rg -n "chatPages|own page|page per chat|empty page" README.md PRODUCT.md docs .memory`. +- [x] **Step 4: Verify the whole phase** (below). +- [x] **Step 5:** Commit `feat(design): two chats keep their own pages; docs`. + +## Verification + +Run, in order, each expected to pass: +- `npm run test:design-mode` +- `npx tsx --test main/services/chat-application-service.test.ts main/services/chat-store-core.test.ts`, which are outside `test:design-mode` +- `npm run type-check` and `npx tsc --noEmit -p main/tsconfig.json` +- `npm run type-check:e2e` +- `npm run cli:build` (Task 4 touches `chat-store-core.ts`, which the CLI bundles) +- `npm run lint` +- `npm run test:ci-policy` +- `npm run test:e2e:space -- tests/e2e/design-canvas.spec.ts tests/e2e/design-mode.spec.ts` + +Then `npm run test` once before the PR. CI must be green on the exact head. + +## Risks and edge cases + +For reviewers to attack: + +1. **The delete record is memory only.** A main crash with the renderer alive is impossible: the window goes with it. But a renderer reload keeps main's record while the history is lost, which is harmless. A record evicted after 200 claimed-page deletes in one workspace means an undo of an old delete brings the page back without its claims; those chats stay where they were moved. +2. **Page-aware undo (decision 1).** Inserting a brought-back page "after its predecessor in `to`" needs a predecessor that still exists. When it is gone too, the page goes after the nearest earlier page that exists, else first. Attack the case where two steps restore pages whose predecessors are each other. +3. **Merge answer and history.** The renderer applies the stored claims as a carried change. If the save that got them was a replay after a conflict, `local` may already hold newer edits; `applyStoredClaims` touches only `chatPages` and `namedFor`, so it can't overwrite them. +4. **Title-follow cost.** Every title change reads its workspace canvas once. Auto-titles happen once per chat, so the cost is small, but a canvas near 16 MiB pays a parse per rename. +5. **Title-follow ordering and a failed write.** The per-chat queue and reading the title at run time make the newest title win. If `writeChatAndMeta` fails after the payload file was renamed into place (`chat-store-core.ts:1324`; meta update or transaction clear throws), the method throws and no listener fires. The page keeps its old name until the next title change, whose follow reads the newest title. +6. **Retraction and claims.** Leaving design mode while entry writes takes back the added page and its claim. A claim on an existing page (rule 3) stays after a retraction; the next entry keeps it. +7. **Lazy claim breadth.** Placing an artifact in a turn claims the resolved page for a chat with no claim. That page may be another chat's page that this chat's person was looking at. That is intended: the person was working there. +8. **Delete refusal counts claims only.** A chat that uses a page without a claim (D10) is not protected until its first write or entry. +9. **Crash windows in chat delete.** *(Corrected 2026-11-24, final review.)* + - Live delete: the claim, `namedFor` and artifacts are pruned after `chatStore.remove`. A crash between the remove and that prune leaves them. The pending marker is still set then, but `getMeta` already returns null, so no record names the chat's workspace. The marker belongs to the subagent run stores, whose V1 file format is strict (exactly three keys) and must stay readable by rollback builds, so it cannot carry a workspace id. Recovery (`recoverDeletedChatCanvas`) therefore checks every canvas file (`DesignCanvasStore.workspaceIds`) for a chat with no metadata and runs `all` on each, writing only those that hold something of the chat's. This runs only for pending deletions at startup. + - Independently, entry, `canvas_page delete` and `canvas_page use` read which chats with claims or `namedFor` marks are live before their update, and drop the claims and marks of chats that are not live in the same mutate. Other `canvas_page` actions and other writes don't. +10. **Shared page and `namedFor`.** Chat B uses chat A's named page, and A is renamed. The page follows A's title, which may surprise B. That is the spec's rule. +11. **Existing E2E expectations.** Rule 3 keeps Page 1's name, so existing assertions on `["Page 1", "Page 2"]` hold. Entry now writes `chatPages` into saved docs that tests read: check `savedCanvases` callers for deep-equal assertions. +12. **Awaiting entry in the consent path.** The card's answer waits for entry's file reads and one canvas write. Entry already limits itself to `EARLIER_PAGES_LIMIT` pages, so the wait is short. A failure is logged, and the tool still answers "entered". + +## Open questions + +None of the earlier five remain (see Review amendments). New: + +1. **Picker counts and deleted chats** (Risk 9). Should the renderer hide claims of chats it doesn't know, using the chat list it may have? *Settled:* no. Counts stay document-only; the leftover needs a crash in a narrow window and goes at the workspace's next entry or `canvas_page` write. diff --git a/docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md b/docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md index fd6cbbd27..537cdb196 100644 --- a/docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md +++ b/docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md @@ -600,3 +600,11 @@ An adversarial review checked this spec against the code and Electron 43's typin - **S13. Export (3a).** Export renders app frames in a hidden window on the default session, under the same dispatchers, so cookies and storage match the canvas. (The offline proxy pattern would block loopback.) Remove "for tweaks" from §6.3.10: tweaks are for `file` frames only (§6.3.3), so anti-goal 5's "tweaks keep working" applies to `file` frames. - **S14. Bind to loopback (2b).** Next.js and create-react-app bind `0.0.0.0` by default. When Aiden starts a server, it passes the framework's host flag or env (`--hostname 127.0.0.1`, `HOST=127.0.0.1`, Vite `--host 127.0.0.1`), so design mode never exposes the app to the local network. - **S15. Two allowlist openings closed (2c, 3a).** `aiden-design:` is removed from app frames' allowlist and added to the cancelled test rows; the bridge arrives through `executeJavaScript`, not that scheme. A repo-supplied `apps[].url` in `.aiden/canvas.json` needs the S2 consent before it is registered as an app origin. + +### Phase 1b amendments (2026-11-24) + +Phase 1b (chat pages, plan `docs/superpowers/plans/2026-11-23-design-mode-v2-p1b-chat-pages.md`) built §6.1 "A chat's page" with three changes. They win over §6.1 and §6.5 where those disagree. + +- **S16. Entry takes the free page on screen (1b).** Entry doesn't always add a page named after the chat. It keeps a live claim; else it takes the page holding most of the chat's earlier pages; else it takes the page on screen as it is (no rename, no `namedFor`) when no other live chat claims it, it isn't another live chat's named page, and it is empty or no other chat's kept view is on it. Only otherwise does it add a page named after the chat. So the first chat on a fresh canvas keeps Page 1. +- **S17. A moved chat's empty named page goes (1b).** Moving an empty chat drops its claim, its `namedFor` marks and its artifact frames, and deletes the page made for it when that page holds no frames or comments, no other chat uses it, and it isn't the only page. §6.1's "just drops its entry" is replaced. The same applies when a chat attaches from a shared legacy No workspace canvas that stays behind. +- **S18. The view comes before the claim when placing (1b).** A placement with no page lands on the page Aiden showed this turn, then the message's page, then the chat's kept view page, then its claim, then the first page; the renderer shows the view page, then the claim. So Aiden works on the page the person is looking at, not always on the claimed page as §6.5 "Where Aiden's work lands" says. §6.5 is to be revisited in 3b, when app frames and the rewritten prompt land. diff --git a/main/handlers/design-canvas-main.ts b/main/handlers/design-canvas-main.ts index ba4813739..c6ef69c5a 100644 --- a/main/handlers/design-canvas-main.ts +++ b/main/handlers/design-canvas-main.ts @@ -39,7 +39,8 @@ export function registerDesignCanvasIpc(): void { answer, rendererDocumentOwner(event, () => new Error("Active renderer required.")), async (chatId) => { - await chatApplicationService.setDesignMode(chatId, true, { rejectFeatureOwned: true }); + // Waits for the chat's page, so Aiden's first placement after "entered" lands there. + await chatApplicationService.setDesignMode(chatId, true, { rejectFeatureOwned: true, awaitEntry: true }); ipcMain.broadcast("chats:design-mode-changed", { chatId, designMode: true }); }, ); diff --git a/main/index.ts b/main/index.ts index 5b10143e3..cecf9ff91 100644 --- a/main/index.ts +++ b/main/index.ts @@ -170,8 +170,8 @@ import { EmptyChatMigrationSnapshotError } from "./services/empty-chat-migration import { migrateLegacyEmptyWorkspaceChats } from "./services/empty-chat-migration-main.js"; import { ensureUserDataDir } from "./services/data-store.js"; import { piCompactionSessionStore } from "./services/pi-compaction-session-store.js"; -import { designCanvasChatCleanup, designCanvasViews, removeDesignCanvasWorkspace } from "./services/design-canvas/main.js"; -import { persistedChatWorkspaceId } from "../renderer/shared/chat-workspace.js"; +import { designCanvasChatCleanup, designCanvasViews, designWorkspaceCanvasStore, removeDesignCanvasWorkspace } from "./services/design-canvas/main.js"; +import { recoverDeletedChatCanvas } from "./services/design-canvas/cleanup.js"; import { reconcileExternalProviderCredentialChanges, reconcilePendingProviderCredentialRotation, @@ -2599,10 +2599,18 @@ if (!ownsSingleInstanceLock) { } await piRuntimeEffectStore.deleteChat(chatId); await piCompactionSessionStore.deleteChat(chatId); - // The chat's comments and view leave its workspace's canvas, which stays. - const meta = await chatStore.getMeta(chatId); - if (meta) await designCanvasChatCleanup.forgetChat(chatId, persistedChatWorkspaceId(meta.workspaceId)); - await chatStore.remove(chatId); + // The chat's comments and view leave its workspace's canvas before the + // remove, and its claim and artifact frames after it; the canvas stays. + await recoverDeletedChatCanvas( + { + getMeta: (id) => chatStore.getMeta(id), + remove: (id) => chatStore.remove(id), + cleanup: designCanvasChatCleanup, + workspaceIds: () => designWorkspaceCanvasStore.workspaceIds(), + onError: (error) => logger.warn("design", "Could not remove a deleted chat's page claim and artifacts from its design canvas.", error), + }, + chatId, + ); // The same Inbox cleanup the live delete runs: no snooze or pin is left // behind for a chat whose delete a crash cut short. await forgetChatInboxState({ readMarkers: chatReadMarkers, triage: chatTriage }, chatId, (area, message, error) => diff --git a/main/services/chat-application-service-main.ts b/main/services/chat-application-service-main.ts index d86740e2f..a81d31156 100644 --- a/main/services/chat-application-service-main.ts +++ b/main/services/chat-application-service-main.ts @@ -24,11 +24,13 @@ import { designCanvasStore, designCanvasViews, designGrants, + designLiveChats, designModeConsent, + designPendingEntries, + designTitleFollow, recentWrittenPages, } from "./design-canvas/main.js"; -import { designTurnPages } from "./design-canvas/views.js"; -import { EARLIER_PAGES_LIMIT, pagesWrittenInChat, placeWrittenPagesOnCanvas } from "./design-canvas/written-pages.js"; +import { createDesignEntry } from "./design-canvas/entry.js"; import { DESIGN_CANVAS_UPDATED_CHANNEL } from "../handlers/design-canvas.js"; import { cancelVisualSnapshots } from "./visual-snapshot-service.js"; import { beginFollowThroughMove, deleteChatFollowThrough, restoreChatFollowThrough } from "./follow-through/follow-through-main.js"; @@ -55,30 +57,19 @@ export const chatApplicationService = createChatApplicationService({ designCanvasCarry, designGrants, designModeConsent, - designPagesOnEntry: async (chat, workspaceRoot) => { - const entered = await placeWrittenPagesOnCanvas({ - chatId: chat.id, - workspaceRoot, - // A reply still running has not saved its activity yet; its pages come from this run's record. - paths: recentWrittenPages.merged(chat.id, pagesWrittenInChat(chat.messages)), - limit: EARLIER_PAGES_LIMIT, - shouldSave: async () => (await chatStore.getMeta(chat.id))?.designMode === true, - store: designCanvasStore, - pages: designTurnPages({ views: designCanvasViews, chatId: chat.id }), - broadcast: (update) => ipcMain.broadcast(DESIGN_CANVAS_UPDATED_CHANNEL, update), - newId: randomUUID, - // The chat's earlier pages land on its own page of the shared canvas. - entry: { - pageName: chat.title, - hasView: async (workspaceId) => (await designCanvasViews.get(chat.id, workspaceId)) !== undefined, - }, - }); - // The canvas shows that page and fits them once it loads, so the person sees them whole. - const { frameIds, pageId, focusId } = entered; - if (pageId && (frameIds.length > 0 || focusId !== undefined)) { - ipcMain.broadcast("designCanvas:focus", { chatId: chat.id, pageId, frameIds, ...(focusId !== undefined ? { focusId } : {}) }); - } - }, + // Tracked whichever way design mode turned on, so the chat's canvas writes wait for its claim. + designPagesOnEntry: createDesignEntry({ + store: designCanvasStore, + views: designCanvasViews, + recent: recentWrittenPages, + pending: designPendingEntries, + titleFollow: designTitleFollow, + isLive: designLiveChats, + designModeOn: async (chatId) => (await chatStore.getMeta(chatId))?.designMode === true, + broadcast: (update) => ipcMain.broadcast(DESIGN_CANVAS_UPDATED_CHANNEL, update), + focus: (request) => ipcMain.broadcast("designCanvas:focus", request), + newId: randomUUID, + }), visualSnapshots: { cancelChat: cancelVisualSnapshots }, followThrough: { beginMove: beginFollowThroughMove, deleteChat: deleteChatFollowThrough, restoreChat: restoreChatFollowThrough }, memoryStore, diff --git a/main/services/chat-application-service.test.ts b/main/services/chat-application-service.test.ts index 3b57702f4..0276ad61b 100644 --- a/main/services/chat-application-service.test.ts +++ b/main/services/chat-application-service.test.ts @@ -1,13 +1,13 @@ import assert from "node:assert/strict"; import test from "node:test"; import { ASSISTANT_WORKSPACE_ID } from "../../renderer/shared/assistant.js"; -import { emptyDesignCanvas } from "../../renderer/shared/design-canvas/schema.js"; +import { emptyDesignCanvas, type DesignCanvas, type DesignFrame } from "../../renderer/shared/design-canvas/schema.js"; import { DesignGrantRegistry } from "./design-canvas/grants.js"; import { DesignModeConsent } from "./design-canvas/design-mode-tool.js"; import type { ChatGenerationOwner } from "./chat-generation-owner.js"; import { DesignCanvasStore } from "./design-canvas/store.js"; import { DesignCanvasViews } from "./design-canvas/views.js"; -import { createDesignChatCleanup } from "./design-canvas/cleanup.js"; +import { createDesignChatCleanup, recoverDeletedChatCanvas } from "./design-canvas/cleanup.js"; import { captureAnalyticsEvents } from "./analytics/test-support.js"; import type { Chat, Workspace } from "./types.js"; import fs from "node:fs/promises"; @@ -842,6 +842,53 @@ test("turning design mode on hands the chat and its folder to the canvas once, a assert.equal(logged.length, 1); }); +test("entering design mode from Aiden's card answers only once entry has claimed the chat's page, and a failed entry is logged", async () => { + const folderWorkspace: Workspace = { + id: "workspace-1", + name: "Workspace", + folderPath: "/work/site", + permission: "ask", + createdAt: 1, + updatedAt: 1, + }; + let releaseEntry!: () => void; + const entryHeld = new Promise<void>((resolve) => (releaseEntry = resolve)); + const logged: string[] = []; + const finished: string[] = []; + let failEntry = false; + const { service } = fixture({ + configStore: { getWorkspace: async (id: string) => (id === folderWorkspace.id ? folderWorkspace : undefined) }, + chatStore: { + setDesignMode: async (id: string, enabled: boolean, assertCurrent?: (current: Chat) => void | Promise<void>) => { + await assertCurrent?.(chat(id, "workspace-1")); + return { ...chat(id, "workspace-1"), ...(enabled ? { designMode: true as const } : {}) }; + }, + } as unknown as ChatApplicationDependencies["chatStore"], + designPagesOnEntry: async (entered) => { + if (failEntry) throw new Error("disk failed"); + if (entered.id === "chat-1") await entryHeld; + finished.push(entered.id); + }, + logError: (_area, message) => logged.push(message), + }); + + let answered = false; + const switched = service.setDesignMode("chat-1", true, { awaitEntry: true }).then((result) => { + answered = true; + return result; + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(answered, false, "the answer waits for entry"); + releaseEntry(); + assert.equal((await switched)?.designMode, true); + assert.deepEqual(finished, ["chat-1"], "entry had finished when the switch answered"); + + // A failed entry is logged; the switch still answers. + failEntry = true; + assert.equal((await service.setDesignMode("chat-3", true, { awaitEntry: true }))?.designMode, true); + assert.equal(logged.length, 1); +}); + test("a canvas save or grant that lands while the chat is being deleted does not bring back its comments or outlive it", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-delete-race-")); try { @@ -887,6 +934,144 @@ test("deleting a chat whose workspace has no canvas writes no canvas file", asyn } }); +function canvasFrame(id: string, pageId: string, extra: Partial<DesignFrame> & Pick<DesignFrame, "kind">): DesignFrame { + return { id, title: id, x: 0, y: 0, w: 200, h: 120, pageId, createdBy: "aiden", ...extra }; +} + +/** + * chat-1's own page "page-2" (made for it), chat-2 on "page-1", each chat's + * artifact frame and chat-1's note: what main writes, so it goes in through + * `update` (a save never adds claims or `namedFor`). + */ +async function seedChatOnCanvas(store: DesignCanvasStore): Promise<void> { + await store.update("workspace-1", (current): DesignCanvas => ({ + ...current, + pages: [{ id: "page-1", name: "Page 1" }, { id: "page-2", name: "Chat", namedFor: "chat-1" }], + chatPages: { "chat-1": "page-2", "chat-2": "page-1" }, + frames: [ + canvasFrame("art-1", "page-2", { kind: "artifact", mediaId: "m-1", chatId: "chat-1" }), + canvasFrame("art-2", "page-1", { kind: "artifact", mediaId: "m-2", chatId: "chat-2" }), + canvasFrame("note-1", "page-2", { kind: "note", text: "warmer", chatId: "chat-1" }), + ], + })); +} + +/** What a chat delete must leave: the page, chat-1's note, chat-2's frame and claim. */ +function assertChatOneForgotten(after: DesignCanvas): void { + assert.deepEqual(after.chatPages, { "chat-2": "page-1" }); + assert.deepEqual(after.pages, [{ id: "page-1", name: "Page 1" }, { id: "page-2", name: "Chat" }], "the page stays, no longer following the chat"); + assert.deepEqual(after.frames.map((entry) => entry.id), ["art-2", "note-1"]); +} + +test("deleting a chat drops its claim, its named-for mark and its artifact frames, and keeps the page, its notes and other chats' frames and claims", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-delete-claim-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const store = new DesignCanvasStore({ root: () => root }); + await seedChatOnCanvas(store); + await fixture({ designCanvasCleanup: createDesignChatCleanup({ store, views: new DesignCanvasViews() }) }).service.remove("chat-1"); + assertChatOneForgotten(await store.get("workspace-1")); +}); + +test("a delete that fails after the first cleanup keeps the chat's claim and artifact frames", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-delete-failed-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const store = new DesignCanvasStore({ root: () => root }); + await seedChatOnCanvas(store); + const failing = fixture({ + designCanvasCleanup: createDesignChatCleanup({ store, views: new DesignCanvasViews() }), + chatStore: { + listRegular: async () => [], + list: async () => [], + get: async (id: string) => chat(id), + create: async () => chat(), + rename: async () => chat(), + setChatModelSelection: async () => chat(), + setDesignMode: async () => chat(), + moveEmptyChatToWorkspace: async () => chat(), + remove: async () => { throw new Error("disk failed"); }, + } as ChatApplicationDependencies["chatStore"], + }); + await assert.rejects(failing.service.remove("chat-1"), /disk failed/u); + const after = await store.get("workspace-1"); + assert.equal(after.chatPages["chat-1"], "page-2"); + assert.equal(after.pages[1]?.namedFor, "chat-1"); + assert.ok(after.frames.some((entry) => entry.id === "art-1")); +}); + +test("a chat delete recovered at startup prunes the claim and artifact frames after the remove", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-delete-recovered-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const store = new DesignCanvasStore({ root: () => root }); + await seedChatOnCanvas(store); + const cleanup = createDesignChatCleanup({ store, views: new DesignCanvasViews() }); + let present = true; + let atRemove: DesignCanvas | undefined; + await recoverDeletedChatCanvas( + { + getMeta: async () => (present ? { workspaceId: "workspace-1" } : null), + remove: async () => { + atRemove = await store.get("workspace-1"); + present = false; + }, + cleanup, + workspaceIds: () => store.workspaceIds(), + onError: (error) => assert.fail(String(error)), + }, + "chat-1", + ); + assert.equal(atRemove?.chatPages["chat-1"], "page-2", "only comments go before the remove commits"); + assertChatOneForgotten(await store.get("workspace-1")); + +}); + +test("a chat delete cut short after the remove committed is pruned at startup from every canvas that holds it", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-delete-recovered-late-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const store = new DesignCanvasStore({ root: () => root }); + await seedChatOnCanvas(store); + const untouched = await store.update("workspace-2", (current): DesignCanvas => ({ ...current, chatPages: { "chat-2": "page-1" } })); + let removed = false; + // The remove committed before the crash, so the chat's metadata and workspace are gone. + await recoverDeletedChatCanvas( + { + getMeta: async () => null, + remove: async () => { removed = true; }, + cleanup: createDesignChatCleanup({ store, views: new DesignCanvasViews() }), + workspaceIds: () => store.workspaceIds(), + onError: (error) => assert.fail(String(error)), + }, + "chat-1", + ); + assert.equal(removed, true); + assertChatOneForgotten(await store.get("workspace-1")); + assert.equal((await store.get("workspace-2")).revision, untouched.revision, "a canvas without the chat is not written"); +}); + +test("moving an empty chat drops its claim and deletes the empty page made for it; a page with frames stays, no longer following", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-move-claim-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const store = new DesignCanvasStore({ root: () => root }); + await store.update("workspace-1", (current): DesignCanvas => ({ + ...current, + pages: [ + { id: "page-1", name: "Page 1" }, + { id: "empty", name: "Chat", namedFor: "chat-2" }, + { id: "worked", name: "Chat 2", namedFor: "chat-2" }, + ], + chatPages: { "chat-2": "empty", "chat-3": "page-1" }, + frames: [canvasFrame("kept", "worked", { kind: "note", text: "keep" })], + })); + const { service } = fixture({ + designCanvasCleanup: createDesignChatCleanup({ store, views: new DesignCanvasViews() }), + configStore: { getWorkspace: async (id: string) => ({ id, name: id, permission: "ask", createdAt: 1, updatedAt: 1 }) }, + } as Partial<ChatApplicationDependencies>); + await service.moveEmptyToWorkspace("chat-2", "workspace-2"); + const after = await store.get("workspace-1"); + assert.deepEqual(after.chatPages, { "chat-3": "page-1" }); + assert.deepEqual(after.pages, [{ id: "page-1", name: "Page 1" }, { id: "worked", name: "Chat 2" }]); + assert.deepEqual(after.frames.map((entry) => entry.id), ["kept"]); +}); + test("a delete rolled forward at startup clears the chat's Inbox state, even when one store fails", async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-app-inbox-")); t.after(() => fs.rm(root, { recursive: true, force: true })); diff --git a/main/services/chat-application-service.ts b/main/services/chat-application-service.ts index cfcea61ef..4a8154921 100644 --- a/main/services/chat-application-service.ts +++ b/main/services/chat-application-service.ts @@ -135,8 +135,9 @@ export interface ChatApplicationDependencies { /** Forgets the person's "Not now" on Aiden's design mode card once they open design mode themselves. */ designModeConsent?: { forgetDecline(chatId: string): void }; /** - * Runs once design mode turns on: puts the HTML pages this chat's earlier - * replies wrote on an empty canvas. Never awaited by the switch. + * Runs once design mode turns on: the chat claims its page of the + * workspace canvas, and the HTML pages its earlier replies wrote go there. + * Awaited by the switch only with `awaitEntry`. */ designPagesOnEntry?(chat: Chat, workspaceRoot: string): Promise<unknown>; /** Queued visual snapshots; a deleted chat's are dropped, not captured. */ @@ -388,7 +389,14 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) * folder. Turning it off is always allowed. A running reply is not * affected, because design mode only changes the layout. */ - async setDesignMode(chatId: string, enabled: boolean, options: ChatApplicationMutationOptions = {}) { + async setDesignMode( + chatId: string, + enabled: boolean, + options: ChatApplicationMutationOptions & { + /** Answer only once entry has claimed the chat's page (Aiden's card), logging a failure. */ + awaitEntry?: boolean; + } = {}, + ) { let turnedOn = false; let workspaceRoot: string | undefined; const updated = await deps.chatStore.setDesignMode(chatId, enabled, async (chat) => { @@ -405,9 +413,10 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) if (!enabled) deps.designGrants?.revokeChat(chatId); else deps.designModeConsent?.forgetDecline(chatId); if (turnedOn && workspaceRoot && deps.designPagesOnEntry) { - void deps.designPagesOnEntry(updated, workspaceRoot).catch((error) => { - deps.logError("design", "Could not put earlier pages on the design canvas.", error); + const entry = deps.designPagesOnEntry(updated, workspaceRoot).catch((error) => { + deps.logError("design", "Could not give the chat its page on the design canvas.", error); }); + if (options.awaitEntry) await entry; } return chatForRenderer(updated); }, @@ -444,9 +453,10 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) ); // A grant names the old workspace root; the canvas asks again for the new one. deps.designGrants?.revokeChat(chatId); - // The chat's view and comments on the old workspace's canvas are no one's now. + // The chat's view, comments, claim and artifacts on the old workspace's canvas + // are no one's now, and an empty page made for it goes. await deps.designCanvasCleanup - ?.forgetChat(chatId, persistedChatWorkspaceId(current.workspaceId)) + ?.forgetChat(chatId, persistedChatWorkspaceId(current.workspaceId), "move") .catch((error: unknown) => { deps.logError("design", "Could not clear the chat's view of its old workspace's canvas.", error); }); @@ -699,6 +709,12 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) }); if (outcome === "too-large" || outcome === "failed") canvasCarried = false; } + if (sharedLegacyScratch) { + // The shared canvas stays for the other chats: this chat leaves it as a moved chat does. + await deps.designCanvasCleanup?.forgetChat(chatId, oldWorkspaceId, "move").catch((error: unknown) => { + deps.logError("design", "Could not take the attached chat off its old shared canvas.", error); + }); + } // Release workspace operation admissions BEFORE releasing the old hidden // workspace, otherwise `workspaceOperationRegistry.cancelAndSettle(oldWorkspaceId)` @@ -837,7 +853,7 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) // The workspace the chat was in, read before the delete: its canvas keeps no trace of the chat. const canvasWorkspaceId = persistedChatWorkspaceId(current.workspaceId); try { - await deps.designCanvasCleanup?.forgetChat(chatId, canvasWorkspaceId); + await deps.designCanvasCleanup?.forgetChat(chatId, canvasWorkspaceId, "comments"); } catch (error) { deps.logError("design", "Could not remove the chat's comments from its design canvas.", error); throw new Error("Aiden could not remove this chat's comments from its design canvas."); @@ -854,8 +870,9 @@ export function createChatApplicationService(deps: ChatApplicationDependencies) // A canvas save or grant that passed its chat check before the remove // committed may have landed since the first cleanup; repeat it. deps.designGrants?.revokeChat(chatId); - await deps.designCanvasCleanup?.forgetChat(chatId, canvasWorkspaceId).catch((error: unknown) => { - deps.logError("design", "Could not remove the deleted chat's comments from its design canvas.", error); + // Its claim and artifact frames go only now, so a delete that failed keeps them. + await deps.designCanvasCleanup?.forgetChat(chatId, canvasWorkspaceId, "all").catch((error: unknown) => { + deps.logError("design", "Could not remove the deleted chat's comments, page claim and artifacts from its design canvas.", error); }); void forgetChatInboxState(deps.inboxState, chatId, deps.logError); await deps.scheduledTasks?.releaseOriginChat(chatId).catch((error: unknown) => { diff --git a/main/services/chat-attach-workspace.test.ts b/main/services/chat-attach-workspace.test.ts index 2b51e7510..e31738d23 100644 --- a/main/services/chat-attach-workspace.test.ts +++ b/main/services/chat-attach-workspace.test.ts @@ -24,6 +24,10 @@ import { filterRemoteVisibleWorkspaces } from "./visible-chat-projection.js"; import { WorkspaceMutationGate } from "./workspace-mutation-gate.js"; import { WorkspaceOperationRegistry } from "./workspace-operation-registry.js"; import type { Workspace } from "./types.js"; +import { createDesignChatCleanup } from "./design-canvas/cleanup.js"; +import { DesignCanvasStore } from "./design-canvas/store.js"; +import { DesignCanvasViews } from "./design-canvas/views.js"; +import type { DesignCanvas } from "../../renderer/shared/design-canvas/schema.js"; async function withTempDir(fn: (dir: string) => Promise<void>): Promise<void> { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-attach-ws-")); @@ -487,6 +491,7 @@ test("legacy shared No-workspace folder refuses copying sibling chats' files and const chatStore = createChatStore(async () => storeDir); const carried: unknown[] = []; + const canvases = new DesignCanvasStore({ root: () => path.join(dir, "canvases") }); const workspaces: Record<string, Workspace> = { "nows-legacy": { id: "nows-legacy", @@ -545,6 +550,7 @@ test("legacy shared No-workspace folder refuses copying sibling chats' files and return "carried"; }, }, + designCanvasCleanup: createDesignChatCleanup({ store: canvases, views: new DesignCanvasViews() }), assertManagedWorktreeAdmission: async () => undefined, logError: () => undefined, }); @@ -553,6 +559,13 @@ test("legacy shared No-workspace folder refuses copying sibling chats' files and const chatB = "66666666-6666-4666-8666-666666666666"; await chatStore.create({ id: chatA, workspaceId: "nows-legacy" }); await chatStore.create({ id: chatB, workspaceId: "nows-legacy" }); + // The shared canvas: chat A's own empty page and its artifact, chat B on Page 1. + await canvases.update("nows-legacy", (current): DesignCanvas => ({ + ...current, + pages: [...current.pages, { id: "page-a", name: "A", namedFor: chatA }], + chatPages: { [chatA]: "page-a", [chatB]: "page-1" }, + frames: [{ id: "art-a", kind: "artifact", mediaId: "m", chatId: chatA, title: "art", x: 0, y: 0, w: 100, h: 100, pageId: "page-1", createdBy: "aiden" }], + })); // Must not list sibling chats' files for carry-over or trash. const inspected = await service.inspectAttachFiles(chatA); @@ -574,8 +587,12 @@ test("legacy shared No-workspace folder refuses copying sibling chats' files and await fs.readFile(path.join(legacyScratchDir, "other-chat.txt"), "utf8"), "belongs to sibling", ); - // A legacy folder shared with other chats keeps its canvas for them. + // A legacy folder shared with other chats keeps its canvas for them, without chat A on it. assert.deepEqual(carried, []); + const shared = await canvases.get("nows-legacy"); + assert.deepEqual(shared.chatPages, { [chatB]: "page-1" }); + assert.deepEqual(shared.pages.map((page) => page.id), ["page-1"], "chat A's empty page goes"); + assert.deepEqual(shared.frames, []); }); }); diff --git a/main/services/chat-store-core.test.ts b/main/services/chat-store-core.test.ts index af74e3ab6..fdc37d095 100644 --- a/main/services/chat-store-core.test.ts +++ b/main/services/chat-store-core.test.ts @@ -65,6 +65,95 @@ test("index observers see each committed summary change and stop after unsubscri assert.equal(observed.length, beforeQuiet); }); +test("a rename, a replaced title, an auto-title and the first-message seed each tell title listeners once, after the write", async (t) => { + const store = await testStore(t); + const chat = await store.create({ workspaceId: "workspace" }); + const seen: Promise<string | undefined>[] = []; + store.onTitleChanged((chatId) => { + assert.equal(chatId, chat.id); + seen.push(store.getMeta(chatId).then((meta) => meta?.title)); + }); + + const seeded = await store.appendMessage(chat.id, { role: "user", content: "Sketch the pricing table" }, { autoTitle: true }); + assert.equal(seen.length, 1); + assert.equal(await seen[0], "Sketch the pricing table"); + + await store.replaceAutoTitle(chat.id, seeded.title, "Pricing table"); + assert.equal(seen.length, 2); + assert.equal(await seen[1], "Pricing table"); + + await store.replaceTitleIfUnchanged(chat.id, "Pricing table", "Pricing table sketch"); + assert.equal(seen.length, 3); + assert.equal(await seen[2], "Pricing table sketch"); + + await store.rename(chat.id, "Plans page"); + assert.equal(seen.length, 4); + assert.equal(await seen[3], "Plans page"); + + // A later message seeds nothing, so nobody is told. + await store.appendMessage(chat.id, { role: "user", content: "And a footer" }, { autoTitle: true }); + assert.equal(seen.length, 4); +}); + +test("title listeners hear only committed titles, and can write the chat from inside the listener", async (t) => { + const store = await testStore(t); + const chat = await store.create({ workspaceId: "workspace" }); + let told = 0; + const nested: Promise<unknown>[] = []; + store.onTitleChanged((chatId) => { + told += 1; + // A write that takes the chat's lock: it completes because the listener runs after the lock is released. + if (told === 1) nested.push(store.rename(chatId, "Renamed from the listener")); + }); + + // The renderer document goes away while the seeded title is being written: the write fails. + let checks = 0; + await assert.rejects( + store.appendMessage(chat.id, { role: "user", content: "Sketch the pricing table" }, { autoTitle: true, isCurrent: () => ++checks === 1 }), + ); + assert.equal(told, 0, "a failed write tells no one"); + + await store.appendMessage(chat.id, { role: "user", content: "Sketch the pricing table" }, { autoTitle: true }); + assert.equal(told, 1); + await Promise.all(nested); + assert.equal((await store.getMeta(chat.id))?.title, "Renamed from the listener"); + assert.equal(told, 2, "the listener's own rename is heard too"); +}); + +test("a rename that changes nothing tells no one", async (t) => { + const store = await testStore(t); + const chat = await store.create({}); + await store.rename(chat.id, "Same"); + let told = 0; + const unsubscribe = store.onTitleChanged(() => { + told += 1; + }); + await store.rename(chat.id, "Same"); + await store.rename(chat.id, " "); + assert.equal(await store.replaceTitleIfUnchanged(chat.id, "Other", "New"), null); + assert.equal(await store.replaceAutoTitle(chat.id, "Other", "New"), null); + assert.equal(told, 0); + + unsubscribe(); + await store.rename(chat.id, "Changed"); + assert.equal(told, 0); +}); + +test("a title listener that throws does not fail the rename", async (t) => { + const store = await testStore(t); + const chat = await store.create({}); + let later = 0; + store.onTitleChanged(() => { + throw new Error("listener failed"); + }); + store.onTitleChanged(() => { + later += 1; + }); + const renamed = await store.rename(chat.id, "Still renamed"); + assert.equal(renamed.title, "Still renamed"); + assert.equal(later, 1); +}); + test("serializes assistant persistence with a background title update", async (t) => { const store = await testStore(t); const chat = await store.create({}); diff --git a/main/services/chat-store-core.ts b/main/services/chat-store-core.ts index 3053adf2b..f3dbb6902 100644 --- a/main/services/chat-store-core.ts +++ b/main/services/chat-store-core.ts @@ -181,6 +181,7 @@ export function createChatStore( durability: ChatStoreDurability = {}, ) { const indexListeners = new Set<() => void>(); + const titleListeners = new Set<(chatId: string) => void>(); const syncDirectory = durability.syncDirectory ?? syncPath; const syncFile = durability.syncFile ?? syncPath; const readFile = @@ -545,6 +546,28 @@ export function createChatStore( } } + /** Called after a title write resolved, outside the chat lock. */ + function notifyTitleChanged(chatId: string): void { + for (const listener of [...titleListeners]) { + try { + listener(chatId); + } catch { + // Observers are best-effort signals; the title is already written. + } + } + } + + /** Runs a title write and tells title listeners when the title it returns differs from `before`'s. */ + async function withTitleNotice<T extends Chat | null>( + id: string, + write: (before: { title?: string }) => Promise<T>, + ): Promise<T> { + const before: { title?: string } = {}; + const chat = await write(before); + if (chat && before.title !== undefined && chat.title !== before.title) notifyTitleChanged(id); + return chat; + } + async function writeIndex(index: readonly ChatMeta[]): Promise<void> { await writeIndexDurably(index, "index-write"); } @@ -1420,6 +1443,16 @@ export function createChatStore( return () => indexListeners.delete(listener); }, + /** + * Observe title changes: told once after `rename`, `replaceTitleIfUnchanged`, + * `replaceAutoTitle` or a first-message seed in `appendMessage` wrote a new + * title, outside the chat lock. A listener that throws is ignored. + */ + onTitleChanged(listener: (chatId: string) => void): () => void { + titleListeners.add(listener); + return () => titleListeners.delete(listener); + }, + /** List chats, newest first. Legacy chats without a workspace fall under the default one. */ async list(workspaceId?: string): Promise<ChatMeta[]> { return shared([], true, () => withIndexLock(async () => { @@ -1935,15 +1968,16 @@ export function createChatStore( title: string, assertCurrent: (chat: Chat) => void | Promise<void> = () => undefined, ): Promise<Chat> { - return withImageData(await shared([id], true, async () => { + return withImageData(await withTitleNotice(id, (before) => shared([id], true, async () => { const chat = await readChat(id, "owner"); if (!chat) throw new Error(`Chat ${id} not found`); await assertCurrent(chat); + before.title = chat.title; chat.title = title.trim() || chat.title; chat.updatedAt = Date.now(); await writeChatAndMeta(chat); return chat; - })); + }))); }, /** @@ -1974,16 +2008,17 @@ export function createChatStore( expectedTitle: string, title: string, ): Promise<Chat | null> { - return withImageData(await shared([id], true, async () => { + return withImageData(await withTitleNotice(id, (before) => shared([id], true, async () => { const chat = await readChat(id, "owner"); if (!chat || chat.title !== expectedTitle) return null; const nextTitle = title.trim(); if (!nextTitle || nextTitle === chat.title) return null; + before.title = chat.title; chat.title = nextTitle; chat.updatedAt = Date.now(); await writeChatAndMeta(chat); return chat; - })); + }))); }, /** Move only an untouched new chat so its workspace can be chosen from the composer. */ @@ -2336,9 +2371,10 @@ export function createChatStore( hookBlockedReason?: string; }, ): Promise<Chat> { - return withImageData(await shared([id], true, async () => { + return withImageData(await withTitleNotice(id, (before) => shared([id], true, async () => { const chat = await readChat(id, "owner"); if (!chat) throw new Error(`Chat ${id} not found`); + before.title = chat.title; if (meta?.rejectFeatureOwned && chat.owner !== undefined) { throw new Error("This conversation belongs to another Aiden feature and cannot be written from chat."); } @@ -2442,7 +2478,7 @@ export function createChatStore( } }); return chat; - })); + }))); }, /** Replace only the untouched first-message seed, preserving any manual rename. */ @@ -2451,17 +2487,18 @@ export function createChatStore( expectedSeed: string, title: string, ): Promise<Chat | null> { - return withImageData(await shared([id], true, async () => { + return withImageData(await withTitleNotice(id, (before) => shared([id], true, async () => { const chat = await readChat(id, "owner"); if (!chat || !canReplaceGeneratedChatTitle(chat.title, expectedSeed)) return null; const nextTitle = title.trim(); if (!nextTitle || nextTitle === chat.title) return null; + before.title = chat.title; chat.title = nextTitle; chat.updatedAt = Date.now(); await writeChatAndMeta(chat); return chat; - })); + }))); }, }; } diff --git a/main/services/design-canvas/artifact-frames.test.ts b/main/services/design-canvas/artifact-frames.test.ts index 66cef4df3..97f9b5559 100644 --- a/main/services/design-canvas/artifact-frames.test.ts +++ b/main/services/design-canvas/artifact-frames.test.ts @@ -225,3 +225,32 @@ test("saved images land on the page the turn works on, which the result names", assert.deepEqual(placed, { frameIds: ["frame-1"], pageId: "p2" }); assert.equal((await shared.read()).frames[0]!.pageId, "p2"); }); + +test("an artifact placed in a turn claims for a chat with none", async (t) => { + const base = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-artifact-claim-")); + t.after(() => fs.rm(base, { recursive: true, force: true })); + const shared = sharedCanvas(base); + await shared.store.update("chat-1", (doc) => ({ ...doc, pages: [...doc.pages, { id: "p2", name: "Pricing" }], chatPages: { "chat-1": "page-1" } })); + await shared.views.report("chat-2", "ws-1", onPage("p2"), 0); + assert.equal(await placeArtifactsOnCanvas({ ...shared.deps("chat-2"), artifacts: [{ mediaId: "m1", title: "Chart" }], newId: ids() }), true); + const doc = await shared.read(); + assert.equal(doc.revision, 2, "the claim rides on the placement's write"); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1", "chat-2": "p2" }); + // An artifact already there writes nothing, so it claims nothing either. + await shared.store.update("chat-1", (current) => ({ ...current, chatPages: { "chat-1": "page-1" } })); + assert.equal(await placeArtifactsOnCanvas({ ...shared.deps("chat-2"), artifacts: [{ mediaId: "m1", title: "Chart" }], newId: ids() }), false); + assert.deepEqual((await shared.read()).chatPages, { "chat-1": "page-1" }); +}); + +test("a saved image placed in a turn claims for a chat with none, and keeps a claim it has", async (t) => { + const base = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-image-claim-")); + t.after(() => fs.rm(base, { recursive: true, force: true })); + const shared = sharedCanvas(base); + await shared.store.update("chat-1", (doc) => ({ ...doc, pages: [...doc.pages, { id: "p2", name: "Pricing" }] })); + await shared.views.report("chat-1", "ws-1", onPage("p2"), 0); + await placeImagesOnCanvas({ ...shared.deps("chat-1"), images: [{ path: "design/a.png", width: 10, height: 10 }], newId: ids() }); + assert.deepEqual((await shared.read()).chatPages, { "chat-1": "p2" }); + await shared.views.report("chat-1", "ws-1", onPage("page-1"), 0); + await placeImagesOnCanvas({ ...shared.deps("chat-1"), images: [{ path: "design/b.png", width: 10, height: 10 }], newId: () => "frame-b" }); + assert.deepEqual((await shared.read()).chatPages, { "chat-1": "p2" }); +}); diff --git a/main/services/design-canvas/artifact-frames.ts b/main/services/design-canvas/artifact-frames.ts index 0356e9512..58c2c28da 100644 --- a/main/services/design-canvas/artifact-frames.ts +++ b/main/services/design-canvas/artifact-frames.ts @@ -3,6 +3,8 @@ // llm-client runs it once the turn's artifacts are committed. import { canvasView } from "../../../renderer/shared/design-canvas/canvas-summary.js"; +import { landedPageId, withLazyClaim } from "../../../renderer/shared/design-canvas/chat-pages.js"; +import { claimWithRoom } from "./lazy-claim.js"; import { placeFrame } from "../../../renderer/shared/design-canvas/placement.js"; import { DESIGN_CANVAS_LIMITS, type DesignCanvas } from "../../../renderer/shared/design-canvas/schema.js"; import type { DesignChatView } from "../../../renderer/shared/design-canvas/view.js"; @@ -87,13 +89,19 @@ type CanvasPlacement = { pages: Pick<DesignTurnPages, "resolver">; broadcast(update: DesignCanvasUpdated): void; newId(): string; + /** Settles once a design-mode entry running for this chat has claimed its page. */ + pendingEntry?(): Promise<void>; + /** Which claimed chats are live, asked only when the lazy claim finds `chatPages` full. */ + isLive?(chatIds: string[], workspaceId: string): Promise<Set<string>>; }; /** * The chat's workspace, resolved once so the save and the broadcast name the - * same one, and the turn's view resolver for it. + * same one, and the turn's view resolver for it. Waits for a pending entry + * first, so a placement's lazy claim never comes before entry's claim. */ async function placementTurn(input: CanvasPlacement): Promise<{ workspaceId: string; viewOf: (doc: DesignCanvas) => DesignChatView }> { + await input.pendingEntry?.(); const workspaceId = await input.store.workspaceIdOf(input.chatId); if (workspaceId === null) throw new Error("This chat is no longer available."); return { workspaceId, viewOf: await input.pages.resolver(workspaceId) }; @@ -102,22 +110,26 @@ async function placementTurn(input: CanvasPlacement): Promise<{ workspaceId: str /** * Places the artifacts in the chat's workspace canvas and tells open * canvases. Saves nothing (and announces nothing) when every artifact is - * already there. + * already there. A chat with no page of its own claims the turn's page. */ export async function placeArtifactsOnCanvas(input: CanvasPlacement & { artifacts: readonly CanvasArtifact[] }): Promise<boolean> { if (input.artifacts.length === 0) return false; try { const { workspaceId, viewOf } = await placementTurn(input); + let landed: string | undefined; const { doc: saved } = await input.store.update( input.chatId, (doc) => { - const placed = placeArtifactFrames(doc, input.artifacts, input.newId, { chatId: input.chatId, view: viewOf(doc) }); + const view = viewOf(doc); + const placed = placeArtifactFrames(doc, input.artifacts, input.newId, { chatId: input.chatId, view }); if (!placed.changed) throw UNCHANGED; - return placed.doc; + landed = landedPageId(doc, placed.doc, view.pageId); + return withLazyClaim(placed.doc, input.chatId, landed); }, { workspaceId }, ); input.broadcast({ workspaceId, chatId: input.chatId, revision: saved.revision }); + await claimWithRoom({ ...input, workspaceId, pageId: landed, saved }); return true; } catch (error) { if (error === UNCHANGED) return false; @@ -181,7 +193,8 @@ export function placeImageFrames( } /** - * Places saved images in the chat's workspace canvas and tells open canvases. + * Places saved images in the chat's workspace canvas and tells open canvases, + * claiming the turn's page for a chat with none. * Returns the frames showing them and the page they are on, or null when * `shouldSave` refused under the canvas lock (design mode went off, or the * workspace changed). @@ -196,6 +209,7 @@ export async function placeImagesOnCanvas( let frameIds: string[] = []; let pageId = ""; let refused = false; + let landed: string | undefined; const { workspaceId, viewOf } = await placementTurn(input); try { const { doc: saved } = await input.store.update( @@ -207,7 +221,8 @@ export async function placeImagesOnCanvas( const placed = placeImageFrames(doc, input.images, input.newId, view); frameIds = placed.frameIds; if (!placed.changed) throw UNCHANGED; - return placed.doc; + landed = landedPageId(doc, placed.doc, view.pageId); + return withLazyClaim(placed.doc, input.chatId, landed); }, { workspaceId, @@ -224,6 +239,7 @@ export async function placeImagesOnCanvas( }, ); input.broadcast({ workspaceId, chatId: input.chatId, revision: saved.revision }); + await claimWithRoom({ ...input, workspaceId, pageId: landed, saved }); return { frameIds, pageId }; } catch (error) { if (error !== UNCHANGED) throw error; diff --git a/main/services/design-canvas/canvas-tools.test.ts b/main/services/design-canvas/canvas-tools.test.ts index 6f112c9c5..2dac39d12 100644 --- a/main/services/design-canvas/canvas-tools.test.ts +++ b/main/services/design-canvas/canvas-tools.test.ts @@ -16,9 +16,11 @@ import { } from "../../../renderer/shared/design-canvas/canvas-summary.js"; import { addPage, deletePage, movePage } from "../../../renderer/shared/design-canvas/pages.js"; import { addComment, markCommentsSent, reopenComment } from "../../../renderer/shared/design-canvas/comments.js"; -import type { DesignCanvas } from "../../../renderer/shared/design-canvas/schema.js"; +import { DESIGN_CANVAS_LIMITS, type DesignCanvas } from "../../../renderer/shared/design-canvas/schema.js"; import { DesignCanvasStore, DesignChatCanvases, type DesignCanvasUpdated } from "./store.js"; import { DesignCanvasViews, designTurnPages } from "./views.js"; +import { PendingEntries } from "./written-pages.js"; +import { claimPage } from "../../../renderer/shared/design-canvas/chat-pages.js"; type ToolDeps = Parameters<typeof createDesignCanvasTools>[0]; type FocusRequest = Parameters<NonNullable<ToolDeps["focus"]>>[0]; @@ -523,6 +525,8 @@ test("canvas_focus asks the canvas to show frames that exist, and refuses ones t test("Aiden reads and places on a page it names, and focusing a frame on another page brings that page on screen", async (t) => { const { store, views, focused, focusRequests, personShows, call, newTurn } = await setup(t); await store.update("chat-1", (doc) => addPage(addPage(doc, "p2", "Pricing"), "p3", "Empty")); + // The person is on Page 1. (With no view, the chat would read its own page, which this placement claims.) + await personShows("page-1"); const placed = await call("canvas_place_frame", { kind: "note", title: "Tiers", page: "pricing" }); assert.equal(placed.status, "placed"); @@ -1541,6 +1545,277 @@ test("deleting a page that holds the person's frames needs force", async (t) => assert.equal((await store.get("chat-1")).frames.length, 0); }); +/** Every chat counts as live except "chat-gone". */ +const liveExceptGone = { isLive: async (chatIds: string[]) => new Set(chatIds.filter((chatId) => chatId !== "chat-gone")) }; + +test("canvas_page use makes the page this chat's and shows it, leaving other chats' claims alone", async (t) => { + const { store, views, broadcasts, focusRequests, call } = await setup(t, liveExceptGone); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-2": "page-1", "chat-gone": "page-1" } })); + const used = await call("canvas_page", { action: "use", page: "Pricing" }); + assert.equal(used.status, "done"); + assert.equal(used.action, "use"); + assert.deepEqual(used.page, { id: "p2", name: "Pricing" }); + const doc = await store.get("chat-1"); + // The gone chat's claim goes in the same write. + assert.deepEqual(doc.chatPages, { "chat-2": "page-1", "chat-1": "p2" }); + assert.equal(broadcasts.length, 1); + assert.equal((await views.get("chat-1", "ws-1"))?.pageId, "p2"); + assert.equal(focusRequests[focusRequests.length - 1]?.pageId, "p2"); +}); + +test("canvas_page use on a missing page is refused and writes nothing", async (t) => { + const { store, call } = await setup(t); + const before = (await store.get("chat-1")).revision; + const used = await call("canvas_page", { action: "use", page: "Nope" }); + assert.equal(used.status, "error"); + assert.equal((await store.get("chat-1")).revision, before); +}); + +test("canvas_page use on the chat's own page writes nothing and still shows it", async (t) => { + const { store, views, broadcasts, focusRequests, call } = await setup(t); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-1": "p2" } })); + const before = (await store.get("chat-1")).revision; + const used = await call("canvas_page", { action: "use", page: "Pricing" }); + assert.equal(used.status, "done"); + assert.equal((await store.get("chat-1")).revision, before); + assert.equal(broadcasts.length, 0); + assert.deepEqual(focusRequests, [{ pageId: "p2", frameIds: [], focusId: 1 }]); + assert.equal((await views.get("chat-1", "ws-1"))?.pageId, "p2"); +}); + +test("canvas_page delete refuses a page another live chat uses, and with force deletes it and moves that chat to the first page", async (t) => { + const { store, call } = await setup(t, liveExceptGone); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-2": "p2" } })); + const before = (await store.get("chat-1")).revision; + const refused = await call("canvas_page", { action: "delete", page: "Pricing" }); + assert.equal(refused.status, "error"); + assert.equal( + refused.message, + "That page is the page of 1 other chat. Delete it only if the person asked, and then pass force: true.", + ); + assert.equal((await store.get("chat-1")).revision, before); + assert.equal((await call("canvas_page", { action: "delete", page: "Pricing", force: true })).status, "deleted"); + const doc = await store.get("chat-1"); + assert.deepEqual(doc.pages.map((page) => page.id), ["page-1"]); + // A delete lands on no page, so it claims none for chat-1. + assert.deepEqual(doc.chatPages, { "chat-2": "page-1" }); +}); + +test("canvas_page delete names both reasons once when the page holds the person's frames and another chat's claim", async (t) => { + const { store, call } = await setup(t, liveExceptGone); + const person = (id: string) => ({ id, kind: "note" as const, title: id, text: "", x: 0, y: 0, w: 240, h: 160, pageId: "p2", createdBy: "person" as const }); + await store.update("chat-1", (doc) => ({ + ...addPage(doc, "p2", "Pricing"), + frames: [person("a"), person("b")], + chatPages: { "chat-2": "p2", "chat-3": "p2", "chat-gone": "p2" }, + })); + const refused = await call("canvas_page", { action: "delete", page: "Pricing" }); + assert.equal( + refused.message, + "That page holds 2 frames the person added or locked and is the page of 2 other chats. Delete it only if the person asked, and then pass force: true.", + ); +}); + +test("canvas_page delete ignores the claim of a chat that no longer exists", async (t) => { + const { store, call } = await setup(t, liveExceptGone); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-gone": "p2", "chat-2": "page-1" } })); + assert.equal((await call("canvas_page", { action: "delete", page: "Pricing" })).status, "deleted"); + assert.deepEqual((await store.get("chat-1")).chatPages, { "chat-2": "page-1" }); +}); + +test("canvas_page delete and use drop the page marks of chats that no longer exist", async (t) => { + const { store, call } = await setup(t, liveExceptGone); + await store.update("chat-1", (doc) => ({ + ...doc, + pages: [ + { id: "page-1", name: "Page 1", namedFor: "chat-gone" }, + { id: "p2", name: "Pricing" }, + { id: "p3", name: "Ideas", namedFor: "chat-2" }, + ], + })); + assert.equal((await call("canvas_page", { action: "delete", page: "Pricing" })).status, "deleted"); + assert.deepEqual((await store.get("chat-1")).pages, [{ id: "page-1", name: "Page 1" }, { id: "p3", name: "Ideas", namedFor: "chat-2" }]); + + await store.update("chat-1", (doc) => ({ ...doc, pages: doc.pages.map((page) => (page.id === "page-1" ? { ...page, namedFor: "chat-gone" } : page)) })); + await call("canvas_page", { action: "use", page: "Ideas" }); + const used = await store.get("chat-1"); + assert.equal(used.chatPages["chat-1"], "p3"); + assert.equal(used.pages[0]!.namedFor, undefined); + assert.equal(used.pages[1]!.namedFor, "chat-2", "a live chat's mark stays"); +}); + +test("canvas_page delete of this chat's own page needs no force", async (t) => { + const { store, call } = await setup(t); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-1": "p2" } })); + assert.equal((await call("canvas_page", { action: "delete", page: "Pricing" })).status, "deleted"); + assert.deepEqual((await store.get("chat-1")).chatPages, { "chat-1": "page-1" }); +}); + +test("the pages list marks this chat's page and counts other chats, naming none of them", async (t) => { + const { store, call } = await setup(t, liveExceptGone); + await store.update("chat-1", (doc) => ({ + ...addPage(doc, "p2", "Pricing"), + chatPages: { "chat-1": "p2", "chat-2": "page-1", "chat-3": "page-1", "chat-gone": "page-1" }, + })); + const shown = await call("canvas_page", { action: "show", page: "Page 1" }); + assert.deepEqual( + shown.pages.map((page: { id: string; yours: boolean; otherChats: number }) => [page.id, page.yours, page.otherChats]), + [["page-1", false, 2], ["p2", true, 0]], + ); + // A rename reads no liveness, so it counts every claim; it still marks this chat's page. + const renamed = await call("canvas_page", { action: "rename", page: "Pricing", name: "Plans" }); + assert.deepEqual( + renamed.pages.map((page: { id: string; yours: boolean }) => [page.id, page.yours]), + [["page-1", false], ["p2", true]], + ); + for (const answer of [shown, renamed]) assert.doesNotMatch(JSON.stringify(answer), /chat-2|chat-3|chat-gone/u); +}); + +test("after canvas_page use, a placement with no page in the same turn lands on the used page", async (t) => { + const { store, call } = await setup(t); + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + await call("canvas_page", { action: "use", page: "Pricing" }); + const placed = await call("canvas_place_frame", { kind: "note", title: "Idea" }); + assert.equal((await store.get("chat-1")).frames.find((frame) => frame.id === placed.frame.id)?.pageId, "p2"); +}); + +test("a chat with no claim claims the page its first tool edit lands on, in the same write", async (t) => { + const { store, personShows, call } = await setup(t); + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + await personShows("p2"); + const before = (await store.get("chat-1")).revision; + await call("canvas_place_frame", { kind: "note", title: "Idea" }); + const doc = await store.get("chat-1"); + assert.equal(doc.revision, before + 1, "one write"); + assert.deepEqual(doc.chatPages, { "chat-1": "p2" }); +}); + +test("canvas_read claims nothing", async (t) => { + const { store, call } = await setup(t); + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + const before = await store.get("chat-1"); + await call("canvas_read"); + await call("canvas_page", { action: "show", page: "Pricing" }); + assert.deepEqual(await store.get("chat-1"), before); +}); + +test("a chat that has a claim keeps it when it writes on another page", async (t) => { + const { store, personShows, call } = await setup(t); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-1": "page-1" } })); + await personShows("p2"); + const placed = await call("canvas_place_frame", { kind: "note", title: "Idea" }); + const doc = await store.get("chat-1"); + assert.equal(doc.frames.find((frame) => frame.id === placed.frame.id)?.pageId, "p2"); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1" }); +}); + +test("canvas_page use and the lazy claim in the same write keep the use claim", async (t) => { + const { store, call } = await setup(t); + // The turn works on Page 1; use names Pricing. + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + await call("canvas_page", { action: "use", page: "Pricing" }); + assert.deepEqual((await store.get("chat-1")).chatPages, { "chat-1": "p2" }); +}); + +test("a frame placed on a named page claims that page, not the one on screen", async (t) => { + const { store, call } = await setup(t); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-2": "page-1" } })); + const placed = await call("canvas_place_frame", { kind: "note", title: "Idea", page: "Pricing" }); + const doc = await store.get("chat-1"); + assert.equal(doc.frames.find((frame) => frame.id === placed.frame.id)?.pageId, "p2"); + assert.deepEqual(doc.chatPages, { "chat-2": "page-1", "chat-1": "p2" }, "chat-2's page is never shared by the lazy claim"); +}); + +test("canvas_page add claims the new page, and the answer marks it this chat's", async (t) => { + const { store, call } = await setup(t); + await store.update("chat-1", (doc) => ({ ...doc, chatPages: { "chat-2": "page-1" } })); + const added = await call("canvas_page", { action: "add", name: "Mine" }); + assert.deepEqual((await store.get("chat-1")).chatPages, { "chat-2": "page-1", "chat-1": added.page.id }); + assert.deepEqual( + added.pages.map((page: { name: string; yours: boolean; otherChats: number }) => [page.name, page.yours, page.otherChats]), + [["Page 1", false, 1], ["Mine", true, 0]], + ); +}); + +test("at a full chatPages of gone chats, the lazy claim makes room and claims", async (t) => { + const { store, call } = await setup(t, { isLive: async (chatIds: string[]) => new Set(chatIds.filter((chatId) => !chatId.startsWith("gone-"))) }); + await store.update("chat-1", (doc) => ({ + ...doc, + chatPages: Object.fromEntries(Array.from({ length: DESIGN_CANVAS_LIMITS.chatPages }, (_, index) => [`gone-${index}`, "page-1"])), + })); + await call("canvas_place_frame", { kind: "note", title: "Idea" }); + const doc = await store.get("chat-1"); + assert.equal(doc.chatPages["chat-1"], "page-1"); + assert.ok(Object.keys(doc.chatPages).length <= DESIGN_CANVAS_LIMITS.chatPages); +}); + +test("canvas_page rename asks about no chat's liveness", async (t) => { + let asked = 0; + const { store, call } = await setup(t, { + isLive: async (chatIds: string[]) => { + asked += 1; + return new Set(chatIds); + }, + }); + await store.update("chat-1", (doc) => ({ ...addPage(doc, "p2", "Pricing"), chatPages: { "chat-2": "p2" } })); + assert.equal((await call("canvas_page", { action: "rename", page: "Pricing", name: "Plans" })).status, "done"); + assert.equal(asked, 0); +}); + +test("canvas_page use writes nothing when the chat's claim on that page lands between its read and its edit", async (t) => { + const { canvases, store, focusRequests, newTurn } = await setup(t); + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + let landed = false; + // Another write makes Pricing this chat's right after use has read the canvas. + const racing: ToolDeps["store"] = { + workspaceIdOf: (chatId) => canvases.workspaceIdOf(chatId), + update: (chatId, mutate, options) => canvases.update(chatId, mutate, options), + get: async (chatId, options) => { + const read = await canvases.get(chatId, options); + if (!landed) { + landed = true; + await canvases.update(chatId, (doc) => claimPage(doc, "chat-1", "p2")); + } + return read; + }, + }; + const call = newTurn("chat-1", { store: racing }); + const revision = (await store.get("chat-1")).revision; + const used = await call("canvas_page", { action: "use", page: "Pricing" }); + assert.equal(used.status, "done"); + assert.equal((await store.get("chat-1")).revision, revision + 1, "only the racing write landed"); + assert.deepEqual((await store.get("chat-1")).chatPages, { "chat-1": "p2" }); + assert.equal(focusRequests[focusRequests.length - 1]?.pageId, "p2"); +}); + +test("a write that deletes the turn's page claims nothing", async (t) => { + const { store, personShows, call } = await setup(t); + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + await personShows("p2"); + assert.equal((await call("canvas_page", { action: "delete", page: "Pricing" })).status, "deleted"); + assert.deepEqual((await store.get("chat-1")).chatPages, {}); +}); + +test("a write during a pending entry waits for it and keeps the entry's claim", async (t) => { + const pending = new PendingEntries(); + const { store, call } = await setup(t, { pendingEntry: () => pending.wait("chat-1") }); + await store.update("chat-1", (doc) => addPage(doc, "p2", "Pricing")); + let release!: () => void; + const held = new Promise<void>((resolve) => (release = resolve)); + // Entry, like the real one, keeps a claim the chat already has. + const entry = pending.track( + "chat-1", + held.then(() => store.update("chat-1", (doc) => (doc.chatPages["chat-1"] ? doc : claimPage(doc, "chat-1", "p2")))), + ); + const before = (await store.get("chat-1")).revision; + const placing = call("canvas_place_frame", { kind: "note", title: "Idea" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal((await store.get("chat-1")).revision, before, "the write waits for entry"); + release(); + await Promise.all([entry, placing]); + assert.deepEqual((await store.get("chat-1")).chatPages, { "chat-1": "p2" }); +}); + test("canvas_focus with a page brings that page on screen", async (t) => { const { store, views, focused, call } = await setup(t); const added = await call("canvas_page", { action: "add", name: "Flows" }); diff --git a/main/services/design-canvas/canvas-tools.ts b/main/services/design-canvas/canvas-tools.ts index 19620b6c6..4b6c54bc6 100644 --- a/main/services/design-canvas/canvas-tools.ts +++ b/main/services/design-canvas/canvas-tools.ts @@ -84,7 +84,18 @@ import { isDesignTweakValue, type DesignTweakValues, } from "../../../renderer/shared/design-canvas/tweaks.js"; +import { + ChatPagesFullError, + chatsOnPage, + claimPage, + landedPageId, + withLazyClaim, + chatsOnCanvas, + withoutGoneClaims, + type IsChatLive, +} from "../../../renderer/shared/design-canvas/chat-pages.js"; import { designPageTweakNames } from "./inspect.js"; +import { claimWithRoom } from "./lazy-claim.js"; import { resolveDesignFile } from "./resolve-core.js"; import type { DesignCanvasUpdated, DesignChatCanvases } from "./store.js"; import { viewPageId, type DesignChatView } from "../../../renderer/shared/design-canvas/view.js"; @@ -206,7 +217,7 @@ export const DESIGN_MODE_PROMPT_SECTION = [ "- You can move, resize, retitle, restyle, regroup, hide, lock or reorder any unlocked frame, the person's too, with canvas_update_frame. A locked frame stays as it is unless the person asks you to unlock it. Remove a frame the person added only when they ask, with force: true.", "- Use canvas_arrange to lay frames out in a tidy row, column or grid, put them in a group (it fits itself around them) or take them out, in one call. Put each direction in its own group.", "- For a flow or diagram, draw it in one canvas_build call: boxes (shapes with their labels in text, text, notes) with refs of your own, and connectors between them by ref or frameId; a connector follows its frames when they move. A build counts as one of the turn's canvas calls.", - "- The canvas can have several pages. Work on the page the person is looking at unless they name another; canvas_page adds, renames, duplicates, reorders, shows or deletes pages, and canvas_update_frame with page moves a frame to another.", + "- The canvas can have several pages. Work on the page the person is looking at, which starts as this chat's own page, unless they name another; canvas_page use makes a page this chat's page. canvas_page adds, renames, duplicates, reorders, shows or deletes pages, and canvas_update_frame with page moves a frame to another.", "- After placing or moving frames, call canvas_focus with their ids so the person sees them (canvas_arrange does this by itself). canvas_read with snapshot: true shows you the canvas as the person sees it.", "- canvas_inspect draws one page offline at its design width, with its frame's look, and reports script errors, files that did not load, sideways overflow and tweaks that do nothing, with a picture when you can see images. Each page you write is checked the same way without a picture, and the report follows in the conversation before your next step: fix what it lists once, call canvas_inspect for a picture after a big change, and say what you fixed.", "- The person's canvas comments come with their message or in canvas_read. After acting on one they sent you, canvas_comment can reply on it in a sentence (what you changed, or a question when it is unclear) and resolve it once it is done. An open comment in canvas_read is still their draft, or one they reopened after your reply, so it is left for them to send.", @@ -223,12 +234,20 @@ export type DesignCanvasToolDeps = { broadcast(update: DesignCanvasUpdated): void; /** * The page this turn works on (`designTurnPages`): a page Aiden showed this - * turn, the page the message came from, the chat's kept page, then the - * first page. Built from `viewState` alone when absent. + * turn, the page the message came from, the chat's kept page, the chat's + * own page, then the first page. Built from `viewState` alone when absent. */ pages?: DesignTurnPages; /** False once the chat left design mode or was deleted. Checked on every call. */ stillAvailable?(): Promise<boolean>; + /** + * Which of `chatIds` still exist in the workspace, so a deleted or moved + * chat's claim neither protects a page nor counts in canvas_page answers. + * Left out, every chat counts as live. + */ + isLive?(chatIds: string[], workspaceId: string): Promise<Set<string>>; + /** Settles once a design-mode entry running for this chat has claimed its page; writes wait for it. */ + pendingEntry?(): Promise<void>; newId?(): string; /** * Asks the window showing the chat's canvas to show `pageId` and fit these @@ -278,6 +297,27 @@ const result = (value: unknown): ToolResult => ({ class CanvasToolError extends Error {} +/** `canvas_page use` found the page already this chat's on the latest canvas. */ +const OWN_PAGE_ALREADY = Symbol("own page already"); + +const counted = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`; + +/** + * Why Aiden may not delete a page without force: the person's or locked + * frames on it, and other live chats using it as their own page. Undefined + * when neither applies. + */ +function deleteRefusal(doc: DesignCanvas, pageId: string, isLive: IsChatLive, chatId?: string): string | undefined { + const kept = doc.frames.filter((frame) => frame.pageId === pageId && (frame.createdBy === "person" || frame.locked)).length; + const others = chatsOnPage(doc, pageId, isLive).filter((other) => other !== chatId).length; + const reasons = [ + ...(kept > 0 ? [`holds ${counted(kept, "frame", "frames")} the person added or locked`] : []), + ...(others > 0 ? [`is the page of ${counted(others, "other chat", "other chats")}`] : []), + ]; + if (reasons.length === 0) return undefined; + return `That page ${reasons.join(" and ")}. Delete it only if the person asked, and then pass force: true.`; +} + function text(value: unknown, field: string, max: number): string { if (typeof value !== "string" || !value.trim()) throw new CanvasToolError(`${field} must be a non-empty string.`); return value.trim().slice(0, max); @@ -797,7 +837,7 @@ function withCoEditReport<T>(value: T, report: ReturnType<typeof keepPersonsMove * request carries fewer tool definitions. */ const CANVAS_CATALOG_LINES: Readonly<Record<string, string>> = { - canvas_page: "Add, rename, duplicate, reorder, show or delete design canvas pages, when the canvas needs another page.", + canvas_page: "Add, rename, duplicate, reorder, show, use or delete design canvas pages, when the canvas needs another page or this chat another page of its own.", canvas_duplicate: "Copy a design canvas frame or group beside it, or lay out a page's light/dark, width or tweak variants in one labelled group.", }; @@ -880,38 +920,64 @@ export function createDesignCanvasTools(deps: DesignCanvasToolDeps): AgentTool[] * person moved since Aiden last saw it keeps the person's box, and the * answer says so with its box now. `show` brings a page on screen after * the change has landed. + * + * A chat with no page of its own claims the page the change landed on, in + * the same write, once a pending entry is done: the page it shows, else + * the page of the frames it touched, else the turn's page. `landed: null` + * says it landed on no page (a delete). `answer` builds the value from the + * saved document, so it sees that claim. */ const edit = async <T>( - change: (doc: DesignCanvas, view: DesignChatView) => { doc: DesignCanvas; value: T; show?: { pageId: string; frameIds: string[] } }, + change: ( + doc: DesignCanvas, + view: DesignChatView, + ) => { + doc: DesignCanvas; + value: T; + show?: { pageId: string; frameIds: string[] }; + landed?: null; + answer?: (saved: DesignCanvas) => T; + }, ): Promise<T> => { let value: T | undefined; + let answer: ((saved: DesignCanvas) => T) | undefined; + let landed: string | undefined; let show: { pageId: string; frameIds: string[] } | undefined; let report: ReturnType<typeof keepPersonsMoves> | undefined; let touched = new Set<string>(); + await deps.pendingEntry?.(); const { workspaceId, viewOf } = await turnFor(); const { doc: saved } = await deps.store.update( deps.chatId, (doc) => { - const next = change(doc, viewOf(doc)); + const view = viewOf(doc); + const next = change(doc, view); report = keepPersonsMoves(doc, next.doc, seen); const earlier = new Map(doc.frames.map((frame) => [frame.id, JSON.stringify(frame)])); touched = new Set( report.doc.frames.filter((frame) => earlier.get(frame.id) !== JSON.stringify(frame)).map((frame) => frame.id), ); value = next.value; + answer = next.answer; show = next.show; - return report.doc; + landed = undefined; + if (next.doc === doc || next.landed === null) return report.doc; + const exists = (pageId: string | undefined): pageId is string => + pageId !== undefined && report!.doc.pages.some((page) => page.id === pageId); + landed = exists(next.show?.pageId) ? next.show.pageId : landedPageId(doc, report.doc, view.pageId); + return withLazyClaim(report.doc, deps.chatId, landed); }, { workspaceId }, ); deps.broadcast({ workspaceId, chatId: deps.chatId, revision: saved.revision }); + await claimWithRoom({ chatId: deps.chatId, workspaceId, pageId: landed, saved, store: deps.store, isLive: deps.isLive, broadcast: deps.broadcast }); remember(saved.frames.filter((frame) => touched.has(frame.id))); for (const entry of report?.changed ?? []) { const now = saved.frames.find((frame) => frame.id === entry.id); if (now) seen.set(entry.id, boxKey(now)); } if (show) await showOnCanvas(workspaceId, show.pageId, show.frameIds); - return withCoEditReport(value as T, report, saved); + return withCoEditReport(answer ? answer(saved) : (value as T), report, saved); }; const frameIn = (doc: DesignCanvas, id: unknown, onScreen: string): DesignFrame => { @@ -931,14 +997,31 @@ export function createDesignCanvasTools(deps: DesignCanvasToolDeps): AgentTool[] return frame; }; - const pagesAnswer = (doc: DesignCanvas, onScreen: string) => + /** + * Each page, with whether it is this chat's own page and how many other + * live chats use it. Other chats are only counted, never named. + */ + const pagesAnswer = (doc: DesignCanvas, onScreen: string, isLive?: IsChatLive) => doc.pages.map((entry) => ({ id: entry.id, name: entry.name, frames: doc.frames.filter((frame) => frame.pageId === entry.id).length, onScreen: entry.id === onScreen, + yours: Object.prototype.hasOwnProperty.call(doc.chatPages, deps.chatId) && doc.chatPages[deps.chatId] === entry.id, + otherChats: chatsOnPage(doc, entry.id, isLive).filter((chatId) => chatId !== deps.chatId).length, })); + /** + * Which chats claiming or named on pages in `doc` are live, as a check that + * needs no waiting. A claim made after this read counts as a live chat's. + */ + const livenessOf = async (doc: DesignCanvas, workspaceId: string): Promise<IsChatLive> => { + const checked = new Set(chatsOnCanvas(doc).filter((chatId) => chatId !== deps.chatId)); + if (!deps.isLive || checked.size === 0) return () => true; + const live = await deps.isLive([...checked], workspaceId); + return (chatId) => !checked.has(chatId) || live.has(chatId); + }; + /** The canvas as this chat may see it: the comments its own messages sent, none of another chat's. */ const ownComments = (doc: DesignCanvas): DesignCanvas => ({ ...doc, @@ -1655,9 +1738,9 @@ export function createDesignCanvasTools(deps: DesignCanvasToolDeps): AgentTool[] name: "canvas_page", label: "Change design canvas pages", description: - "Add, rename, duplicate (with everything on it), delete (with its frames; never the last; force: true for one holding the person's or locked frames, only when they asked), move (step -1 or 1) or show a design canvas page, named by name or id.", + "Add, rename, duplicate (with everything on it), delete (with its frames; never the last), move (step -1 or 1), show, or use (make it this chat's own page and show it) a design canvas page, named by name or id. delete needs force: true for a page holding the person's or locked frames or used by another chat, only when they asked.", parameters: Type.Object({ - action: enumOf(["add", "rename", "duplicate", "delete", "move", "show"] as const), + action: enumOf(["add", "rename", "duplicate", "delete", "move", "show", "use"] as const), page: Type.Optional(Type.String({ maxLength: 128 })), name: Type.Optional(Type.String({ maxLength: DESIGN_CANVAS_LIMITS.pageNameChars })), show: Type.Optional(Type.Boolean()), @@ -1674,89 +1757,132 @@ export function createDesignCanvasTools(deps: DesignCanvasToolDeps): AgentTool[] throw new CanvasToolError(`The ${String(action)} action needs page.`); } }; - // Showing a page changes only this chat's view, never the shared canvas. - if (action === "show") { + // Only show, use and delete read the canvas first, to tell which + // claimed chats are live; the other actions count every claim. + let isLive: IsChatLive = () => true; + let workspaceId = ""; + if (action === "show" || action === "use" || action === "delete") { pageNeeded(); - const { doc, view, workspaceId } = await read(); - const pageId = pageOf(doc, p.page, view.pageId); - await showOnCanvas(workspaceId, pageId, []); - return { - status: "done", - action, - page: { id: pageId, name: doc.pages.find((entry) => entry.id === pageId)?.name }, - pages: pagesAnswer(doc, pageId), - }; + const { doc: current, view: currentView, workspaceId: readWorkspace } = await read(); + workspaceId = readWorkspace; + isLive = await livenessOf(current, workspaceId); + // Showing a page changes only this chat's view, never the shared canvas, + // and so does using the page that is already this chat's. + const pageId = action === "delete" ? "" : pageOf(current, p.page, currentView.pageId); + const own = Object.prototype.hasOwnProperty.call(current.chatPages, deps.chatId) && current.chatPages[deps.chatId] === pageId; + if (action === "show" || (action === "use" && own)) { + await showOnCanvas(workspaceId, pageId, []); + return { + status: "done", + action, + page: { id: pageId, name: current.pages.find((entry) => entry.id === pageId)?.name }, + pages: pagesAnswer(current, pageId, isLive), + }; + } } - return edit((doc, view) => { - let next = doc; - let pageId: string; - // The page that comes on screen after the change, when it changes. - let shown: string | undefined; - switch (action) { - case "add": { - if (!canAddPage(doc)) throw new CanvasToolError(`The canvas has its most pages (${DESIGN_CANVAS_LIMITS.pages}).`); - pageId = newId(); - next = addPage(doc, pageId, name, view.pageId); - if (optionalBoolean(p.show, "show") !== false) shown = pageId; - break; - } - case "rename": { - pageNeeded(); - pageId = pageOf(doc, p.page, view.pageId); - if (!name) throw new CanvasToolError("rename needs a non-empty name."); - next = renamePage(doc, pageId, name); - break; - } - case "duplicate": { - pageNeeded(); - const source = pageOf(doc, p.page, view.pageId); - if (!canAddPage(doc)) throw new CanvasToolError(`The canvas has its most pages (${DESIGN_CANVAS_LIMITS.pages}).`); - pageId = newId(); - next = duplicatePage(doc, source, pageId, newId); - if (next === doc) throw new CanvasToolError(`A copy would pass the canvas's ${DESIGN_CANVAS_LIMITS.frames} frames.`); - if (name) next = renamePage(next, pageId, name); - shown = pageId; - break; - } - case "delete": { - pageNeeded(); - pageId = pageOf(doc, p.page, view.pageId); - if (doc.pages.length <= 1) throw new CanvasToolError("The canvas keeps at least one page, so its only page cannot be deleted."); - const kept = doc.frames.filter((frame) => frame.pageId === pageId && (frame.createdBy === "person" || frame.locked)); - if (kept.length > 0 && p.force !== true) { - throw new CanvasToolError( - `That page holds ${kept.length} ${kept.length === 1 ? "frame" : "frames"} the person added or locked. Delete it only if they asked, and then pass force: true.`, - ); + // Set when `use` finds the page already this chat's on the latest canvas. + let ownAlready: { pageId: string; doc: DesignCanvas } | undefined; + try { + return await edit((doc, view) => { + let next = doc; + let pageId: string; + // The page that comes on screen after the change, when it changes. + let shown: string | undefined; + switch (action) { + case "add": { + if (!canAddPage(doc)) throw new CanvasToolError(`The canvas has its most pages (${DESIGN_CANVAS_LIMITS.pages}).`); + pageId = newId(); + next = addPage(doc, pageId, name, view.pageId); + if (optionalBoolean(p.show, "show") !== false) shown = pageId; + break; } - next = deletePage(doc, pageId); - // Deleting the page on screen brings the one before it on screen. - if (pageId === view.pageId) { - const at = doc.pages.findIndex((entry) => entry.id === pageId); - shown = next.pages[Math.max(0, at - 1)]!.id; + case "rename": { + pageNeeded(); + pageId = pageOf(doc, p.page, view.pageId); + if (!name) throw new CanvasToolError("rename needs a non-empty name."); + next = renamePage(doc, pageId, name); + break; } - break; - } - case "move": { - pageNeeded(); - pageId = pageOf(doc, p.page, view.pageId); - if (p.step !== -1 && p.step !== 1) throw new CanvasToolError("move needs step -1 (earlier) or 1 (later)."); - next = movePage(doc, pageId, p.step); - break; + case "duplicate": { + pageNeeded(); + const source = pageOf(doc, p.page, view.pageId); + if (!canAddPage(doc)) throw new CanvasToolError(`The canvas has its most pages (${DESIGN_CANVAS_LIMITS.pages}).`); + pageId = newId(); + next = duplicatePage(doc, source, pageId, newId); + if (next === doc) throw new CanvasToolError(`A copy would pass the canvas's ${DESIGN_CANVAS_LIMITS.frames} frames.`); + if (name) next = renamePage(next, pageId, name); + shown = pageId; + break; + } + case "delete": { + pageNeeded(); + pageId = pageOf(doc, p.page, view.pageId); + if (doc.pages.length <= 1) throw new CanvasToolError("The canvas keeps at least one page, so its only page cannot be deleted."); + if (p.force !== true) { + const refusal = deleteRefusal(doc, pageId, isLive, deps.chatId); + if (refusal) throw new CanvasToolError(refusal); + } + next = deletePage(withoutGoneClaims(doc, isLive), pageId); + // Deleting the page on screen brings the one before it on screen. + if (pageId === view.pageId) { + const at = doc.pages.findIndex((entry) => entry.id === pageId); + shown = next.pages[Math.max(0, at - 1)]!.id; + } + break; + } + case "move": { + pageNeeded(); + pageId = pageOf(doc, p.page, view.pageId); + if (p.step !== -1 && p.step !== 1) throw new CanvasToolError("move needs step -1 (earlier) or 1 (later)."); + next = movePage(doc, pageId, p.step); + break; + } + case "use": { + pageId = pageOf(doc, p.page, view.pageId); + if (Object.prototype.hasOwnProperty.call(doc.chatPages, deps.chatId) && doc.chatPages[deps.chatId] === pageId) { + ownAlready = { pageId, doc }; + throw OWN_PAGE_ALREADY; + } + try { + next = claimPage(withoutGoneClaims(doc, isLive), deps.chatId, pageId, isLive); + } catch (error) { + if (error instanceof ChatPagesFullError) throw new CanvasToolError(error.message); + throw error; + } + shown = pageId; + break; + } + default: + throw new CanvasToolError('action must be "add", "rename", "duplicate", "delete", "move", "show" or "use".'); } - default: - throw new CanvasToolError('action must be "add", "rename", "duplicate", "delete", "move" or "show".'); - } - return { - doc: next, - ...(shown ? { show: { pageId: shown, frameIds: [] } } : {}), - value: { + const onScreen = shown ?? viewPageId(next, view); + const value = (saved: DesignCanvas) => ({ status: action === "delete" ? "deleted" : "done", action, - ...(action !== "delete" ? { page: { id: pageId, name: next.pages.find((entry) => entry.id === pageId)?.name } } : { page: { id: pageId } }), - pages: pagesAnswer(next, shown ?? viewPageId(next, view)), - }, + ...(action !== "delete" ? { page: { id: pageId, name: saved.pages.find((entry) => entry.id === pageId)?.name } } : { page: { id: pageId } }), + pages: pagesAnswer(saved, onScreen, isLive), + }); + return { + doc: next, + ...(shown ? { show: { pageId: shown, frameIds: [] } } : {}), + // A delete lands on no page, so it claims none. + ...(action === "delete" ? { landed: null } : {}), + value: value(next), + answer: value, + }; + }); + } catch (error) { + if (error !== OWN_PAGE_ALREADY || !ownAlready) throw error; + // Another call made the page this chat's meanwhile: nothing to write, only to show. + const { pageId, doc } = ownAlready; + await showOnCanvas(workspaceId, pageId, []); + return { + status: "done", + action, + page: { id: pageId, name: doc.pages.find((entry) => entry.id === pageId)?.name }, + pages: pagesAnswer(doc, pageId, isLive), }; - }); + } }), }, "never", diff --git a/main/services/design-canvas/carry.test.ts b/main/services/design-canvas/carry.test.ts index 29471f2f6..d15065dd2 100644 --- a/main/services/design-canvas/carry.test.ts +++ b/main/services/design-canvas/carry.test.ts @@ -105,3 +105,86 @@ test("a hidden workspace with nothing on its canvas writes no canvas for the pro assert.equal(outcome, "nothing"); assert.deepEqual((await fs.readdir(root)).filter((name) => name.endsWith(".json")), []); }); + +test("an attached chat claims the first page it brought along, and the hidden canvas's own claims and marks stay behind", async (t) => { + const { store, carry } = await setup(t); + await store.update("hidden", (current): DesignCanvas => ({ + ...hiddenCanvas(), + pages: [{ id: "page-1", name: "Page 1", namedFor: "chat-1" }], + chatPages: { "chat-1": "page-1", "chat-7": "page-1" }, + revision: current.revision, + })); + await store.update("project", (current): DesignCanvas => ({ ...current, chatPages: { "chat-2": "page-1" } })); + await carry.carry({ + chatId: "chat-1", + label: "Brand refresh", + fromWorkspaceId: "hidden", + toWorkspaceId: "project", + copied: [{ from: "design/hero.html", to: "design/hero.html" }], + }); + const merged = await store.get("project"); + const carriedPage = merged.pages[1]!; + assert.deepEqual(merged.chatPages, { "chat-2": "page-1", "chat-1": carriedPage.id }); + assert.equal(carriedPage.namedFor, undefined, "carried pages are named after the chat, not made for it"); +}); + +test("at a full set of chat pages, the pages still come over without a claim", async (t) => { + const { store, views, carry } = await setup(t); + await store.save("hidden", hiddenCanvas(), 0); + const full = Object.fromEntries( + Array.from({ length: DESIGN_CANVAS_LIMITS.chatPages }, (_, index) => [`chat-other-${index}`, "page-1"]), + ); + await store.update("project", (current): DesignCanvas => ({ ...current, chatPages: full })); + const outcome = await carry.carry({ + chatId: "chat-1", + label: "Chat", + fromWorkspaceId: "hidden", + toWorkspaceId: "project", + copied: [{ from: "design/hero.html", to: "design/hero.html" }], + }); + assert.equal(outcome, "carried"); + const merged = await store.get("project"); + assert.equal(merged.pages.length, 2); + assert.equal(merged.chatPages["chat-1"], undefined); + assert.equal((await views.get("chat-1", "project"))?.pageId, merged.pages[1]!.id, "the chat is still shown its page"); +}); + +test("at a full set of chat pages, a gone chat's entry makes room for the attached chat's claim", async (t) => { + const { root, store } = await setup(t); + await store.save("hidden", hiddenCanvas(), 0); + const full = Object.fromEntries( + Array.from({ length: DESIGN_CANVAS_LIMITS.chatPages }, (_, index) => [`chat-other-${index}`, "page-1"]), + ); + await store.update("project", (current): DesignCanvas => ({ ...current, chatPages: full })); + const asked: string[][] = []; + const carry = createDesignCanvasCarry({ + store: new DesignCanvasStore({ root: () => root }), + views: new DesignCanvasViews(), + newId: () => "carried-page", + isLive: async (chatIds) => { + asked.push(chatIds); + return new Set(chatIds.filter((chatId) => chatId !== "chat-other-7")); + }, + }); + await carry.carry({ + chatId: "chat-1", + label: "Chat", + fromWorkspaceId: "hidden", + toWorkspaceId: "project", + copied: [{ from: "design/hero.html", to: "design/hero.html" }], + }); + const merged = await store.get("project"); + assert.equal(merged.chatPages["chat-1"], "carried-page"); + assert.equal(merged.chatPages["chat-other-7"], undefined); + assert.equal(Object.keys(merged.chatPages).length, DESIGN_CANVAS_LIMITS.chatPages); + assert.equal(asked.length, 1); +}); + +test("when nothing comes along, no claim is made", async (t) => { + const { store, carry } = await setup(t); + await store.save("hidden", { ...emptyDesignCanvas(), frames: [frame("left-behind", { kind: "image", path: "tmp/scratch.png" })] }, 0); + await store.save("project", { ...emptyDesignCanvas(), frames: [frame("theirs", { kind: "note", text: "" })] }, 0); + const outcome = await carry.carry({ chatId: "chat-1", label: "Chat", fromWorkspaceId: "hidden", toWorkspaceId: "project", copied: [] }); + assert.equal(outcome, "nothing"); + assert.deepEqual((await store.get("project")).chatPages, {}); +}); diff --git a/main/services/design-canvas/carry.ts b/main/services/design-canvas/carry.ts index ef9bd5995..4aaa6c23f 100644 --- a/main/services/design-canvas/carry.ts +++ b/main/services/design-canvas/carry.ts @@ -2,9 +2,13 @@ // along when its files come too. Its pages are appended to the project's // canvas, named after the chat, and file and image frames follow the paths // their files were copied to (`appendCanvasPages`). The hidden canvas is only -// read: it goes with the hidden workspace. +// read: it goes with the hidden workspace, and its own claims and `namedFor` +// marks never come over. The attaching chat claims the first page it brought +// (in the same write); at a full `chatPages` only that claim is skipped. +import { ChatPagesFullError, claimPage, type IsChatLive } from "../../../renderer/shared/design-canvas/chat-pages.js"; import { appendCanvasPages } from "../../../renderer/shared/design-canvas/pages.js"; +import { DESIGN_CANVAS_LIMITS } from "../../../renderer/shared/design-canvas/schema.js"; import type { DesignCanvasStore, DesignCanvasUpdated } from "./store.js"; import type { DesignCanvasViews } from "./views.js"; @@ -30,6 +34,11 @@ export function createDesignCanvasCarry(deps: { views: Pick<DesignCanvasViews, "showPage">; broadcast?(update: DesignCanvasUpdated): void; newId(): string; + /** + * Which claimed chats are live in the target workspace. Asked only when its + * `chatPages` is full, so a gone chat's entry makes room for the claim. + */ + isLive?(chatIds: string[], workspaceId: string): Promise<Set<string>>; }): DesignCanvasCarry { return { async carry(input) { @@ -38,6 +47,17 @@ export function createDesignCanvasCarry(deps: { const pathMap = new Map(input.copied.map((pair) => [pair.from, pair.to])); let outcome: DesignCanvasCarryOutcome = "nothing"; let firstPage: string | undefined; + let isLive: IsChatLive | undefined; + if (deps.isLive) { + const target = await deps.store.get(input.toWorkspaceId); + const claimed = Object.keys(target.chatPages).filter((chatId) => chatId !== input.chatId); + if (claimed.length >= DESIGN_CANVAS_LIMITS.chatPages) { + const checked = new Set(claimed); + const live = await deps.isLive(claimed, input.toWorkspaceId); + // A claim made after this check is a live chat's. + isLive = (chatId) => !checked.has(chatId) || live.has(chatId); + } + } try { const doc = await deps.store.update(input.toWorkspaceId, (target) => { const merged = appendCanvasPages(target, source, { label: input.label, pathMap, newId: deps.newId }); @@ -47,8 +67,13 @@ export function createDesignCanvasCarry(deps: { } if (merged.pageIds.length === 0) throw STOP; outcome = "carried"; - firstPage = merged.pageIds[0]; - return merged.doc; + firstPage = merged.pageIds[0]!; + try { + return claimPage(merged.doc, input.chatId, firstPage, isLive); + } catch (error) { + if (error instanceof ChatPagesFullError) return merged.doc; + throw error; + } }); deps.broadcast?.({ workspaceId: input.toWorkspaceId, chatId: input.chatId, revision: doc.revision }); } catch (error) { diff --git a/main/services/design-canvas/cleanup.ts b/main/services/design-canvas/cleanup.ts index 87c5b82f4..8c5d6b454 100644 --- a/main/services/design-canvas/cleanup.ts +++ b/main/services/design-canvas/cleanup.ts @@ -1,38 +1,62 @@ // Design canvas cleanup when a chat or a workspace goes. // -// A deleted chat's comments and its view leave its workspace's canvas. The -// canvas itself is the workspace's and stays, and so do the chat's frames: -// they are the workspace's work now. A removed workspace takes its canvas -// file, the copies set aside as corrupt, and every chat's view of it. +// A deleted chat's comments and its view leave its workspace's canvas before +// the delete commits. Its artifact frames (the images and visuals it sent), +// its page claim and its pages' `namedFor` marks go after the delete commits, +// so a delete that fails keeps them. The canvas is the workspace's and stays, +// and so do the chat's pages, notes and other frames: they are the +// workspace's work now. A chat moving to another workspace leaves the same +// way, and an empty page made for it goes too. A removed workspace takes its +// canvas file, the copies set aside as corrupt, and every chat's view of it. +import { persistedChatWorkspaceId } from "../../../renderer/shared/chat-workspace.js"; +import { forgetChatMove, forgetChatOnCanvas } from "../../../renderer/shared/design-canvas/chat-pages.js"; +import type { DesignCanvas } from "../../../renderer/shared/design-canvas/schema.js"; import type { DesignCanvasStore, DesignCanvasUpdated } from "./store.js"; import type { DesignCanvasViews } from "./views.js"; +/** + * What a chat cleanup takes off the canvas: + * - `comments`: the chat's comments, before a delete commits; + * - `all`: also its claim, `namedFor` marks and artifact frames, after it commits; + * - `move`: `all`, plus an empty page made for the chat, for a chat moving away. + */ +export type DesignChatCleanupScope = "comments" | "all" | "move"; + export interface DesignChatCleanup { /** - * Drops `chatId`'s comments from `workspaceId`'s canvas and its view of it. - * The workspace is the one the chat was in before the delete, read before it. - * Safe to run twice: chat delete runs it before and after the delete commits, - * so a save that landed in between does not bring the comments back. + * Takes `chatId` off `workspaceId`'s canvas by `scope`, and drops its view + * of it. The workspace is the one the chat was in before the delete, read + * before it. Safe to run twice: chat delete runs `comments` before the + * delete commits and `all` after, so a save that landed in between does not + * bring anything back. Writes nothing when nothing changes. */ - forgetChat(chatId: string, workspaceId: string): Promise<void>; + forgetChat(chatId: string, workspaceId: string, scope: DesignChatCleanupScope): Promise<void>; } const NOTHING_TO_DROP = Symbol("nothing to drop"); +function withoutChatComments(doc: DesignCanvas, chatId: string): DesignCanvas { + if (!doc.comments.some((comment) => comment.chatId === chatId)) return doc; + return { ...doc, comments: doc.comments.filter((comment) => comment.chatId !== chatId) }; +} + export function createDesignChatCleanup(deps: { store: Pick<DesignCanvasStore, "update">; views: Pick<DesignCanvasViews, "forget">; - /** Tells open canvases the comments went; the deleted chat is named as the one acting. */ + /** Tells open canvases what went; the deleted chat is named as the one acting. */ broadcast?(update: DesignCanvasUpdated): void; }): DesignChatCleanup { return { - async forgetChat(chatId, workspaceId) { + async forgetChat(chatId, workspaceId, scope) { try { const doc = await deps.store.update(workspaceId, (current) => { - // A canvas without the chat's comments (or no canvas at all) is not written. - if (!current.comments.some((comment) => comment.chatId === chatId)) throw NOTHING_TO_DROP; - return { ...current, comments: current.comments.filter((comment) => comment.chatId !== chatId) }; + let next = withoutChatComments(current, chatId); + if (scope === "all") next = forgetChatOnCanvas(next, chatId); + if (scope === "move") next = forgetChatMove(next, chatId); + // A canvas without anything of the chat's (or no canvas at all) is not written. + if (next === current) throw NOTHING_TO_DROP; + return next; }); deps.broadcast?.({ workspaceId, chatId, revision: doc.revision }); } catch (error) { @@ -43,6 +67,42 @@ export function createDesignChatCleanup(deps: { }; } +/** + * A chat delete rolled forward at startup: the same two canvas passes as the + * live delete around `remove`. The chat's workspace is read before the + * remove. When its metadata is already gone (the crash came after the remove + * committed), no record names its workspace: the pending-deletion marker + * belongs to the subagent run stores, whose strict format older builds must + * still read, so it cannot carry one. Every canvas is checked instead, and + * `all` runs on each, writing only those that hold something of the chat's. + * A failed pass before the remove throws, so the delete stays pending; one + * after it is reported to `onError`. + */ +export async function recoverDeletedChatCanvas( + deps: { + getMeta(chatId: string): Promise<{ workspaceId?: string } | null>; + remove(chatId: string): Promise<void>; + cleanup: Pick<DesignChatCleanup, "forgetChat">; + /** The workspaces with a canvas file (`DesignCanvasStore.workspaceIds`). */ + workspaceIds(): Promise<string[]>; + onError(error: unknown): void; + }, + chatId: string, +): Promise<void> { + const meta = await deps.getMeta(chatId); + const workspaceId = meta ? persistedChatWorkspaceId(meta.workspaceId) : undefined; + if (workspaceId !== undefined) await deps.cleanup.forgetChat(chatId, workspaceId, "comments"); + await deps.remove(chatId); + try { + const workspaceIds = workspaceId !== undefined ? [workspaceId] : await deps.workspaceIds(); + for (const id of workspaceIds) { + await deps.cleanup.forgetChat(chatId, id, "all").catch(deps.onError); + } + } catch (error) { + deps.onError(error); + } +} + export interface DesignWorkspaceCleanup { /** Deletes the workspace's canvas, its corrupt copies and its views file. Run once its record is gone. */ removeWorkspace(workspaceId: string): Promise<void>; diff --git a/main/services/design-canvas/entry.ts b/main/services/design-canvas/entry.ts new file mode 100644 index 000000000..e55ccca06 --- /dev/null +++ b/main/services/design-canvas/entry.ts @@ -0,0 +1,64 @@ +// What runs when a chat turns design mode on, by the Design toggle or +// Aiden's card: the chat claims its page of the workspace canvas, its +// earlier pages land there, the canvas is asked to show it, and a page made +// for the chat takes its newest title. The run is tracked in +// `PendingEntries`, so the chat's turn writes wait for its claim. + +import type { DesignTitleFollow } from "./title-follow.js"; +import type { DesignCanvasUpdated, DesignChatCanvases } from "./store.js"; +import { designTurnPages, type DesignCanvasViews } from "./views.js"; +import { + EARLIER_PAGES_LIMIT, + pagesWrittenInChat, + placeWrittenPagesOnCanvas, + type PendingEntries, + type RecentWrittenPages, +} from "./written-pages.js"; + +/** The chat as entry reads it: its id, title and saved messages. */ +type EnteringChat = { id: string; title: string; messages: Parameters<typeof pagesWrittenInChat>[0] }; + +export function createDesignEntry(deps: { + store: Pick<DesignChatCanvases, "get" | "update" | "workspaceIdOf">; + views: Pick<DesignCanvasViews, "get" | "viewports" | "showPage" | "pageIdsOf">; + recent: Pick<RecentWrittenPages, "merged">; + pending: Pick<PendingEntries, "track">; + titleFollow: Pick<DesignTitleFollow, "follow">; + isLive(chatIds: string[], workspaceId: string): Promise<Set<string>>; + /** Checked on the canvas's chain before the write: false once design mode is off or the chat is gone. */ + designModeOn(chatId: string): Promise<boolean>; + broadcast(update: DesignCanvasUpdated): void; + /** Asks the canvas to show the chat's page and fit these frames. */ + focus(request: { chatId: string; pageId: string; frameIds: string[]; focusId?: number }): void; + newId(): string; +}): (chat: EnteringChat, workspaceRoot: string) => Promise<void> { + return (chat, workspaceRoot) => + deps.pending.track( + chat.id, + (async () => { + const { frameIds, pageId, focusId } = await placeWrittenPagesOnCanvas({ + chatId: chat.id, + workspaceRoot, + // A reply still running has not saved its activity yet; its pages come from this run's record. + paths: deps.recent.merged(chat.id, pagesWrittenInChat(chat.messages)), + limit: EARLIER_PAGES_LIMIT, + shouldSave: () => deps.designModeOn(chat.id), + store: deps.store, + pages: designTurnPages({ views: deps.views, chatId: chat.id }), + broadcast: deps.broadcast, + newId: deps.newId, + entry: { + pageName: chat.title, + otherViews: (workspaceId) => deps.views.pageIdsOf(workspaceId, chat.id), + isLive: deps.isLive, + }, + }); + // The canvas shows that page and fits the pages once it loads, so the person sees them whole. + if (pageId && (frameIds.length > 0 || focusId !== undefined)) { + deps.focus({ chatId: chat.id, pageId, frameIds, ...(focusId !== undefined ? { focusId } : {}) }); + } + // The title may have changed while entry ran; a page made for the chat follows it. + await deps.titleFollow.follow(chat.id); + })(), + ); +} diff --git a/main/services/design-canvas/lazy-claim.ts b/main/services/design-canvas/lazy-claim.ts new file mode 100644 index 000000000..724ab09c7 --- /dev/null +++ b/main/services/design-canvas/lazy-claim.ts @@ -0,0 +1,44 @@ +// A design turn's write claims the page it landed on in that same write +// (`withLazyClaim`). At a full `chatPages` the write cannot tell which +// claimed chats are gone without waiting, so it skips the claim, and this +// runs after it: it asks which of them are live and, when that makes room, +// claims in a write of its own. Below the cap it reads and writes nothing. + +import { lazyClaimNeedsRoom, withLazyClaim } from "../../../renderer/shared/design-canvas/chat-pages.js"; +import type { DesignCanvas } from "../../../renderer/shared/design-canvas/schema.js"; +import type { DesignCanvasUpdated, DesignChatCanvases } from "./store.js"; + +const NO_ROOM = Symbol("no room"); + +export async function claimWithRoom(input: { + chatId: string; + workspaceId: string; + /** The page the write landed on; undefined when it landed on none. */ + pageId: string | undefined; + /** The document the write saved. */ + saved: DesignCanvas; + store: Pick<DesignChatCanvases, "update">; + isLive?(chatIds: string[], workspaceId: string): Promise<Set<string>>; + broadcast(update: DesignCanvasUpdated): void; +}): Promise<void> { + const pageId = input.pageId; + if (!input.isLive || pageId === undefined || !lazyClaimNeedsRoom(input.saved, input.chatId)) return; + const checked = new Set(Object.keys(input.saved.chatPages)); + const live = await input.isLive([...checked], input.workspaceId); + // A claim made after this check is a live chat's. + const isLive = (chatId: string) => !checked.has(chatId) || live.has(chatId); + try { + const { doc } = await input.store.update( + input.chatId, + (current) => { + const next = withLazyClaim(current, input.chatId, pageId, isLive); + if (next === current) throw NO_ROOM; + return next; + }, + { workspaceId: input.workspaceId }, + ); + input.broadcast({ workspaceId: input.workspaceId, chatId: input.chatId, revision: doc.revision }); + } catch { + // The write it follows has landed; the chat's next write tries again. + } +} diff --git a/main/services/design-canvas/liveness.test.ts b/main/services/design-canvas/liveness.test.ts new file mode 100644 index 000000000..05a522330 --- /dev/null +++ b/main/services/design-canvas/liveness.test.ts @@ -0,0 +1,24 @@ +// Which chats count as live on a workspace's canvas. + +import assert from "node:assert/strict"; +import test from "node:test"; +import { createDesignLiveChats } from "./liveness.js"; + +test("which chats are live takes one index read for any number of chats; a gone chat or one in another workspace is not live", async () => { + let reads = 0; + const liveChats = createDesignLiveChats({ + list: async (workspaceId?: string) => { + reads += 1; + const all = [ + { id: "chat-1", workspaceId: "ws-1" }, + { id: "chat-2", workspaceId: "ws-2" }, + { id: "chat-3", workspaceId: "ws-1" }, + ]; + return all.filter((meta) => workspaceId === undefined || meta.workspaceId === workspaceId); + }, + }); + assert.deepEqual([...(await liveChats(["chat-1", "chat-2", "chat-3", "chat-gone"], "ws-1"))].sort(), ["chat-1", "chat-3"]); + assert.equal(reads, 1); + assert.deepEqual([...(await liveChats([], "ws-1"))], []); + assert.equal(reads, 1, "nothing to check reads nothing"); +}); diff --git a/main/services/design-canvas/liveness.ts b/main/services/design-canvas/liveness.ts new file mode 100644 index 000000000..32549fe63 --- /dev/null +++ b/main/services/design-canvas/liveness.ts @@ -0,0 +1,18 @@ +// Which chats count as live on a workspace's canvas: the chat exists and is +// in that workspace. A chat that moved away is not live there. Claims and +// `namedFor` marks of chats that are not live are dropped by the writes that +// check (entry, `canvas_page use` and `delete`). + +/** Which of `chatIds` are live in `workspaceId`, from one read of the chat index. */ +export type DesignLiveChats = (chatIds: readonly string[], workspaceId: string) => Promise<Set<string>>; + +export function createDesignLiveChats(chats: { + /** The chats of a workspace, from the chat index (`ChatStore.list`). */ + list(workspaceId?: string): Promise<ReadonlyArray<{ id: string }>>; +}): DesignLiveChats { + return async (chatIds, workspaceId) => { + if (chatIds.length === 0) return new Set(); + const here = new Set((await chats.list(workspaceId)).map((meta) => meta.id)); + return new Set(chatIds.filter((chatId) => here.has(chatId))); + }; +} diff --git a/main/services/design-canvas/main.ts b/main/services/design-canvas/main.ts index 61c2b648a..edb92d667 100644 --- a/main/services/design-canvas/main.ts +++ b/main/services/design-canvas/main.ts @@ -13,16 +13,27 @@ import { createDesignChatCleanup, createDesignWorkspaceCleanup } from "./cleanup import { DesignModeConsent } from "./design-mode-tool.js"; import { DesignSystemOffers } from "./design-system-offers.js"; import { DesignGrantRegistry } from "./grants.js"; +import { createDesignLiveChats } from "./liveness.js"; import { DESIGN_CANVAS_UPDATED_CHANNEL, DesignCanvasStore, DesignChatCanvases, type DesignCanvasUpdated } from "./store.js"; +import { createDesignTitleFollow } from "./title-follow.js"; import { DesignCanvasViews } from "./views.js"; import { DESIGN_FILES_CHANGED_CHANNEL, DesignFileWatcher } from "./watch.js"; -import { RecentWrittenPages } from "./written-pages.js"; +import { PendingEntries, RecentWrittenPages } from "./written-pages.js"; /** One canvas file per workspace, under `userData/design-canvases/`. */ export const designWorkspaceCanvasStore = new DesignCanvasStore({ root: () => path.join(app.getPath("userData"), "design-canvases"), }); +/** Whether the chat still exists and is in that workspace: a chat that moved away is not live there. */ +async function designChatIsLive(chatId: string, workspaceId: string): Promise<boolean> { + const meta = await chatStore.getMeta(chatId); + return meta !== null && persistedChatWorkspaceId(meta.workspaceId) === workspaceId; +} + +/** Which of `chatIds` are live in the workspace, for claims on its canvas: one chat index read per check. */ +export const designLiveChats = createDesignLiveChats(chatStore); + /** The workspace canvases seen through chats: what handlers, tools and placements use. */ export const designCanvasStore = new DesignChatCanvases({ store: designWorkspaceCanvasStore, @@ -31,6 +42,7 @@ export const designCanvasStore = new DesignChatCanvases({ return meta ? persistedChatWorkspaceId(meta.workspaceId) : null; }, workspaceExists: async (workspaceId) => (await configStore.getWorkspace(workspaceId)) !== undefined, + chatIsLive: designChatIsLive, }); /** @@ -46,6 +58,15 @@ export function broadcastDesignCanvasUpdate(update: DesignCanvasUpdated): void { } } +/** A page made for a chat follows the chat's title; entry runs it once more after claiming. */ +export const designTitleFollow = createDesignTitleFollow({ + canvases: designCanvasStore, + titleOf: async (chatId) => (await chatStore.getMeta(chatId))?.title, + broadcast: broadcastDesignCanvasUpdate, + onError: (error) => logger.warn("design", "Could not rename the chat's canvas page.", error), +}); +chatStore.onTitleChanged((chatId) => void designTitleFollow.follow(chatId)); + /** * Each chat's canvas view (page, viewports, the latest Aiden page change), as * its canvas reports it and Aiden's tools change it. Persisted per workspace @@ -69,6 +90,7 @@ export const designCanvasCarry = createDesignCanvasCarry({ views: designCanvasViews, broadcast: broadcastDesignCanvasUpdate, newId: randomUUID, + isLive: designLiveChats, }); /** A removed workspace's canvas, its corrupt copies and its chats' views of it. */ @@ -107,6 +129,9 @@ export const designModeConsent = new DesignModeConsent(); /** Pending `canvas_read` snapshot requests. Memory only. */ export const designCanvasSnapshots = new DesignCanvasSnapshots(); +/** Each chat's running design-mode entry, which its turn's canvas writes wait for. Memory only. */ +export const designPendingEntries = new PendingEntries(); + /** HTML pages each chat's replies wrote in this run, for opening design mode mid-reply. Memory only. */ export const recentWrittenPages = new RecentWrittenPages(); diff --git a/main/services/design-canvas/store.test.ts b/main/services/design-canvas/store.test.ts index af21e2162..e0c6fc278 100644 --- a/main/services/design-canvas/store.test.ts +++ b/main/services/design-canvas/store.test.ts @@ -7,6 +7,9 @@ import { emptyDesignCanvas, type DesignCanvas, } from "../../../renderer/shared/design-canvas/schema.js"; +import { addChatPage, applyStoredClaims, claimPage } from "../../../renderer/shared/design-canvas/chat-pages.js"; +import { changesBetween, keepUnchanged, redo, takeIn, undo, type CanvasHistory } from "../../../renderer/design/canvas-history-core.js"; +import { addPage, deletePage } from "../../../renderer/shared/design-canvas/pages.js"; import { writeJsonAtomic } from "../durable-fs.js"; import { DESIGN_CANVAS_LAYOUT_MARKER, DesignCanvasStore, DesignChatCanvases } from "./store.js"; @@ -407,3 +410,325 @@ test("a v2 document at a workspace path is set aside as corrupt", async (t) => { assert.equal(names.includes("ws-1.json"), false); assert.equal(names.filter((name) => name.startsWith("ws-1.json.corrupt-")).length, 1); }); + +// Chats' own pages are main's: a person's save is merged with the stored claims. + +const pageIdsOf = (doc: DesignCanvas) => doc.pages.map((page) => page.id); + +/** A store whose canvas has pages page-1, then each of `ids`, and the given claims, written as main would. */ +async function claimedStore(t: TestContext, ids: string[], chatPages: Record<string, string>) { + const root = await tempRoot(t); + const real = new DesignCanvasStore({ root: () => root }); + const doc = await real.update("ws-1", (current) => { + let next = current; + for (const id of ids) next = addPage(next, id, id); + return { ...next, chatPages }; + }); + return { store: real, doc, root }; +} + +async function saveOk(store: DesignCanvasStore, doc: DesignCanvas, options: Parameters<DesignCanvasStore["save"]>[3] = {}) { + const current = await store.get("ws-1"); + const result = await store.save("ws-1", doc, current.revision, options); + assert.equal(result.ok, true, JSON.stringify(result)); + return result as Extract<typeof result, { ok: true }>; +} + +test("a person's save cannot add or move a claim", async (t) => { + const { store, doc } = await claimedStore(t, ["P2"], { A: "page-1" }); + const result = await saveOk(store, { ...doc, chatPages: { A: "P2", B: "page-1" } }); + assert.deepEqual((await store.get("ws-1")).chatPages, { A: "page-1" }); + assert.deepEqual(result.chatPages, { A: "page-1" }); + // A save that changes no claim answers with the revision alone. + const plain = await saveOk(store, withNote(await store.get("ws-1"), "n")); + assert.deepEqual(Object.keys(plain).sort(), ["ok", "revision"]); +}); + +test("a stale claim in a save after the chat's own turn does not move it back", async (t) => { + const { store, doc: held } = await claimedStore(t, ["P", "Q"], { A: "P" }); + // A's turn makes Q its page. + const turned = await store.update("ws-1", (current) => ({ ...current, chatPages: { A: "Q" } })); + // A's canvas, still holding {A: P}, saves an unrelated edit at the new revision. + const result = await store.save("ws-1", withNote({ ...held, revision: turned.revision }, "n"), turned.revision); + assert.equal(result.ok, true); + const stored = await store.get("ws-1"); + assert.equal(stored.chatPages.A, "Q"); + assert.deepEqual(stored.frames.map((frame) => frame.id), ["n"]); +}); + +test("an undo that brings a deleted page back brings its claims back", async (t) => { + const { store, doc: before } = await claimedStore(t, ["P2"], { B: "P2" }); + await saveOk(store, deletePage(before, "P2")); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "page-1" }); + await saveOk(store, before, { undone: [] }); + const stored = await store.get("ws-1"); + assert.deepEqual(pageIdsOf(stored), ["page-1", "P2"]); + assert.deepEqual(stored.chatPages, { B: "P2" }); +}); + +/** + * One chat's canvas the way `useDesignCanvas` keeps it: Aiden's turns are + * taken in as undo steps, undo and redo are saves, and stored claims in a + * save's answer are applied and carried into every kept step. + */ +function canvasWindow(store: DesignCanvasStore, start: DesignCanvas) { + let server = start; + let local = start; + let history: CanvasHistory = { past: [], future: [] }; + const save = async (step: { doc: DesignCanvas; history: CanvasHistory } | null) => { + assert.ok(step); + const doc = changesBetween(local, step.doc)(local); + history = step.history; + const result = await store.save("ws-1", doc, server.revision); + assert.equal(result.ok, true, JSON.stringify(result)); + const ok = result as Extract<typeof result, { ok: true }>; + server = { ...doc, revision: ok.revision }; + local = server; + if (ok.chatPages) { + server = applyStoredClaims(server, ok.chatPages, ok.namedFor); + local = server; + history = takeIn(history, { before: doc, from: doc, to: server }); + } + }; + return { + takeInTurn(to: DesignCanvas, aidenTurn: string) { + const kept = keepUnchanged(server, to); + history = takeIn(history, { before: local, from: server, to: kept, aidenTurn }); + server = kept; + local = kept; + }, + undo: () => save(undo(history, local)), + redo: () => save(redo(history, local)), + shown: () => local, + }; +} + +test("undoing a turn that added and used a page puts the chat back on its own page, and redoing it brings the claim back", async (t) => { + const { store, doc: start } = await claimedStore(t, ["p2"], { A: "page-1", B: "p2" }); + const canvas = canvasWindow(store, start); + // B's turn: canvas_page add Q, then use Q. + canvas.takeInTurn(await store.update("ws-1", (current) => claimPage(addPage(current, "q", "Q", "p2"), "B", "q")), "turn-1"); + + await canvas.undo(); + let stored = await store.get("ws-1"); + assert.deepEqual(pageIdsOf(stored), ["page-1", "p2"]); + assert.deepEqual(stored.chatPages, { A: "page-1", B: "p2" }, "B is back on its own page, not A's"); + assert.deepEqual(canvas.shown().chatPages, stored.chatPages); + + await canvas.redo(); + stored = await store.get("ws-1"); + assert.deepEqual(pageIdsOf(stored), ["page-1", "p2", "q"]); + assert.deepEqual(stored.chatPages, { A: "page-1", B: "q" }); + assert.deepEqual(canvas.shown().chatPages, stored.chatPages); +}); + +test("an undo that brings a deleted page back restores its chats from the record, even when the save's copy carried them elsewhere", async (t) => { + const { store, doc: before } = await claimedStore(t, ["P2"], { B: "P2" }); + await saveOk(store, deletePage(before, "P2")); + // The renderer carried the stored move into its steps, so the undone document says page-1. + await saveOk(store, { ...before, chatPages: { B: "page-1" } }); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "P2" }); +}); + +test("a renderer cannot move another chat's claim to a new page id", async (t) => { + const { store, doc } = await claimedStore(t, [], { B: "page-1" }); + await saveOk(store, { ...addPage(doc, "P9", "New"), chatPages: { B: "P9" } }); + const stored = await store.get("ws-1"); + assert.deepEqual(pageIdsOf(stored), ["page-1", "P9"]); + assert.deepEqual(stored.chatPages, { B: "page-1" }); +}); + +test("a page Aiden deletes is recorded, so the person's undo of a later edit cannot resurrect claims for it unless it brings the page back", async (t) => { + const { store, doc: before } = await claimedStore(t, ["P2"], { B: "P2" }); + await store.update("ws-1", (current) => deletePage(current, "P2")); + // An undo that does not bring P2 back leaves B where the delete moved it. + await saveOk(store, withNote(await store.get("ws-1"), "n")); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "page-1" }); + // One that does brings B back with it. + await saveOk(store, before); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "P2" }); +}); + +test("a save that deletes a page moves its chats to the first page, even when the renderer's copy forgot them", async (t) => { + const { store, doc } = await claimedStore(t, ["P2"], { B: "P2" }); + const result = await saveOk(store, { ...deletePage(doc, "P2"), chatPages: {} }); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "page-1" }); + assert.deepEqual(result.chatPages, { B: "page-1" }); +}); + +test("a save cannot mark a page as following a chat", async (t) => { + const { store, doc } = await claimedStore(t, ["P2"], {}); + const marked = { ...doc, pages: doc.pages.map((page) => (page.id === "P2" ? { ...page, namedFor: "A" } : page)) }; + const result = await saveOk(store, marked); + assert.equal((await store.get("ws-1")).pages.find((page) => page.id === "P2")?.namedFor, undefined); + assert.deepEqual(result.namedFor, {}); +}); + +test("a chat deleted or moved after its page was deleted is not brought back by undoing the delete", async (t) => { + const { store, doc: before } = await claimedStore(t, ["P2"], { B: "P2", C: "P2", D: "P2" }); + await saveOk(store, deletePage(before, "P2")); + // B is deleted and C moves away: main drops both entries. D stays. + await store.update("ws-1", (current) => ({ ...current, chatPages: { D: "page-1" } })); + await saveOk(store, before); + assert.deepEqual((await store.get("ws-1")).chatPages, { D: "P2" }); +}); + +test("undoing the delete of a page made for a chat that now uses another page brings back its namedFor", async (t) => { + const root = await tempRoot(t); + const store = new DesignCanvasStore({ root: () => root }); + const before = await store.update("ws-1", (current) => addChatPage(current, "A", "Landing", "pa")); + await saveOk(store, deletePage(before, "pa")); + // A uses another page since. + await store.update("ws-1", (current) => ({ ...addPage(current, "P3", "Other"), chatPages: { A: "P3" } })); + // The person's undo: the old document, with the claim carried into it. + const result = await saveOk(store, { ...addPage(before, "P3", "Other"), chatPages: { A: "P3" } }); + const stored = await store.get("ws-1"); + assert.deepEqual(stored.pages.find((page) => page.id === "pa"), { id: "pa", name: "Landing", namedFor: "A" }); + assert.deepEqual(stored.chatPages, { A: "P3" }); + assert.equal("namedFor" in result, false, "nothing was merged, so the answer is plain"); +}); + +test("a write whose beforeWrite throws leaves the delete record unchanged", async (t) => { + const { store, doc: before } = await claimedStore(t, ["P2"], { B: "P2" }); + await store.update("ws-1", (current) => deletePage(current, "P2")); + const current = await store.get("ws-1"); + await assert.rejects( + store.save("ws-1", before, current.revision, { + beforeWrite: () => { + throw new Error("workspace gone"); + }, + }), + /workspace gone/u, + ); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "page-1" }); + // The failed restore did not use up the record. + await saveOk(store, before); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "P2" }); +}); + +test("deleting the same page id twice and undoing restores the claims of the newest delete only", async (t) => { + const { store, doc: original } = await claimedStore(t, ["P2", "P3"], { B: "P2", D: "P2" }); + await saveOk(store, deletePage(original, "P2")); + // D uses P3, so the undo brings back only B; D's part of that delete stays recorded. + await store.update("ws-1", (current) => ({ ...current, chatPages: { ...current.chatPages, D: "P3" } })); + await saveOk(store, { ...original, chatPages: { B: "P2", D: "P2" } }); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "P2", D: "P3" }); + // D goes back to Page 1, where the first delete moved it, and C joins P2. + const shared = await store.update("ws-1", (current) => ({ ...current, chatPages: { B: "P2", C: "P2", D: "page-1" } })); + // The redo deletes P2 again: B and C are on it, D is not. + await saveOk(store, deletePage(shared, "P2")); + await store.update("ws-1", (current) => ({ ...current, chatPages: { ...current.chatPages, B: "P3" } })); + // An undo that claims all three on P2 restores C only: B moved since, and D was not on P2 at this delete. + await saveOk(store, { ...original, chatPages: { B: "P2", C: "P2", D: "P2" } }); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "P3", C: "P2", D: "page-1" }); +}); + +test("a page deleted again with no one on it replaces the older delete's record, so its undo brings no one back", async (t) => { + const { store, doc: original } = await claimedStore(t, ["P2", "P3"], { D: "P2" }); + // The first delete records D on P2. + await saveOk(store, deletePage(original, "P2")); + // D uses P3, and P2 comes back without D. + await store.update("ws-1", (current) => ({ ...current, chatPages: { D: "P3" } })); + await saveOk(store, { ...original, chatPages: { D: "P3" } }); + // P3 goes, so D is back on Page 1, where the first delete moved it. + const before = await store.update("ws-1", (current) => deletePage(current, "P3")); + assert.deepEqual(before.chatPages, { D: "page-1" }); + // The second delete of P2 has no one on it; undoing it with D on P2 brings no one back. + await saveOk(store, deletePage(before, "P2")); + await saveOk(store, { ...before, chatPages: { D: "P2" } }); + assert.deepEqual((await store.get("ws-1")).chatPages, { D: "page-1" }); +}); + +test("a workspace delete that fails keeps the delete record", async (t) => { + const { store, doc: before, root } = await claimedStore(t, ["P2"], { B: "P2" }); + const afterDelete = await store.update("ws-1", (current) => deletePage(current, "P2")); + // The canvas path is a folder with something in it, so removing it fails. + await fs.rm(path.join(root, "ws-1.json")); + await fs.mkdir(path.join(root, "ws-1.json")); + await fs.writeFile(path.join(root, "ws-1.json", "x"), ""); + await assert.rejects(store.delete("ws-1")); + await fs.rm(path.join(root, "ws-1.json"), { recursive: true }); + await writeJsonAtomic(path.join(root, "ws-1.json"), afterDelete); + // The undo of the page delete still brings B back. + await saveOk(store, before); + assert.deepEqual((await store.get("ws-1")).chatPages, { B: "P2" }); +}); + +test("undoing the delete of a page made for a chat that has since moved does not bring back its namedFor", async (t) => { + const root = await tempRoot(t); + const store = new DesignCanvasStore({ root: () => root }); + const asked: [string, string][] = []; + const chats = new DesignChatCanvases({ + store, + workspaceIdOf: async () => "ws-1", + chatIsLive: async (chatId, workspaceId) => { + asked.push([chatId, workspaceId]); + return chatId !== "A"; + }, + }); + const before = await store.update("ws-1", (current) => addChatPage(addChatPage(current, "A", "Landing", "pa"), "C", "Other", "pc")); + const afterDelete = deletePage(deletePage(before, "pa"), "pc"); + await chats.save("chat-x", afterDelete, before.revision); + // A moved away and C stayed; the person undoes both deletes. + await store.update("ws-1", (current) => ({ ...current, chatPages: { C: "page-1" } })); + const current = await store.get("ws-1"); + const { result } = await chats.save("chat-x", { ...before, chatPages: { C: "page-1" } }, current.revision); + assert.equal(result.ok, true); + const stored = await store.get("ws-1"); + assert.deepEqual(stored.pages.find((page) => page.id === "pa"), { id: "pa", name: "Landing" }); + assert.equal(stored.pages.find((page) => page.id === "pc")?.namedFor, "C"); + assert.ok(asked.some(([chatId, workspaceId]) => chatId === "A" && workspaceId === "ws-1")); +}); + +test("a save that brings back no page made for a chat asks about no chat's liveness", async (t) => { + const root = await tempRoot(t); + const store = new DesignCanvasStore({ root: () => root }); + let asked = 0; + const chats = new DesignChatCanvases({ + store, + workspaceIdOf: async () => "ws-1", + chatIsLive: async () => { + asked += 1; + return true; + }, + }); + const named = await store.update("ws-1", (current) => addChatPage(addChatPage(current, "A", "Landing", "pa"), "B", "Pricing", "pb")); + // An unrelated edit of a canvas whose pages follow two chats. + const { result } = await chats.save("chat-x", withNote(named, "n"), named.revision); + assert.equal(result.ok, true); + assert.equal(asked, 0); +}); + +test("a chat that moves away while an undo waits its turn does not get its page's namedFor back", async (t) => { + const root = await tempRoot(t); + const store = new DesignCanvasStore({ root: () => root }); + const live = new Set(["A"]); + const chats = new DesignChatCanvases({ + store, + workspaceIdOf: async () => "ws-1", + chatIsLive: async (chatId) => live.has(chatId), + }); + const before = await store.update("ws-1", (current) => addChatPage(current, "A", "Landing", "pa")); + const deleted = await chats.save("chat-x", deletePage(before, "pa"), before.revision); + assert.equal(deleted.result.ok, true); + const revision = (await store.get("ws-1")).revision; + // Another write holds the workspace's chain while the undo is sent. + let release!: () => void; + const held = new Promise<void>((resolve) => (release = resolve)); + const holding = store + .update("ws-1", (current) => current, { + beforeWrite: async () => { + await held; + throw new Error("held only"); + }, + }) + .catch(() => undefined); + const undo = chats.save("chat-x", { ...before, chatPages: { A: "page-1" } }, revision); + await new Promise((resolve) => setTimeout(resolve, 20)); + // A moves to another workspace before the undo's turn comes. + live.delete("A"); + release(); + await holding; + assert.equal((await undo).result.ok, true); + assert.deepEqual((await store.get("ws-1")).pages.find((page) => page.id === "pa"), { id: "pa", name: "Landing" }); +}); diff --git a/main/services/design-canvas/store.ts b/main/services/design-canvas/store.ts index f8f8d8df7..0fcc01589 100644 --- a/main/services/design-canvas/store.ts +++ b/main/services/design-canvas/store.ts @@ -13,6 +13,11 @@ import * as fs from "node:fs/promises"; import path from "node:path"; +import { + deletedClaims, + mergeSavedChatPages, + type DeletedPage, +} from "../../../renderer/shared/design-canvas/chat-pages.js"; import { emptyDesignCanvas, isDesignChatId, @@ -49,10 +54,12 @@ export const DESIGN_CANVAS_LAYOUT_MARKER = ".layout-v3"; /** * A save's answer. `moved` means the canvas being saved belongs to a workspace * the chat has left: nothing was written, the edits are not to be retried, and - * `workspaceId` names the workspace the chat is in now. + * `workspaceId` names the workspace the chat is in now. `chatPages` and + * `namedFor` (page id to chat id) come back only when the store's merge + * changed what was sent: they are what was stored. */ export type DesignCanvasSaveResult = - | { ok: true; revision: number } + | { ok: true; revision: number; chatPages?: Record<string, string>; namedFor?: Record<string, string> } | { ok: false; reason: "conflict"; doc: DesignCanvas } | { ok: false; reason: "moved"; workspaceId: string } | { ok: false; reason: "invalid"; issues: string[] }; @@ -60,6 +67,17 @@ export type DesignCanvasSaveResult = /** A canvas holds at most 4 000 frames and 2 000 comments; anything past 16 MiB is not ours. */ const MAX_DOCUMENT_BYTES = 16 * 1024 * 1024; +/** Deleted pages with claims or a `namedFor` remembered per workspace; the oldest go first. */ +const DELETED_PAGES_LIMIT = 200; + +/** The chat is gone, or its workspace has no record: it has no canvas to read or write. */ +export class DesignCanvasUnavailableError extends Error { + constructor(message: string) { + super(message); + this.name = "DesignCanvasUnavailableError"; + } +} + /** Same alphabet and bound as the chat store's file names. */ export function assertDesignCanvasChatId(chatId: unknown): asserts chatId is string { if (!isDesignChatId(chatId)) throw new Error("Invalid chat id."); @@ -75,6 +93,19 @@ export class DesignCanvasStore { private readonly writeJson: typeof writeJsonAtomic; private readonly maxDocumentBytes: number; private readonly chains = new Map<string, Promise<unknown>>(); + /** + * Per workspace, the deleted pages that had claims or a `namedFor`, and + * where each chat on one went, so an undo that brings a page back brings + * back its claims (`mergeSavedChatPages`). Memory only: main and the + * renderer's undo history restart together. + */ + private readonly deletedPages = new Map<string, Map<string, DeletedPage>>(); + /** + * Per workspace, the chats a page is made for (`namedFor`), as of the last + * read or write of its canvas, so a title change of any other chat needs + * no read. Memory only; unknown until the workspace's first read. + */ + private readonly namedFor = new Map<string, ReadonlySet<string>>(); /** The one-time clear of pre-v3 files; shared by every workspace's first call. */ private layout: Promise<void> | null = null; @@ -100,12 +131,30 @@ export class DesignCanvasStore { * are not remembered as removed, so Aiden writing one again shows it again. * `beforeWrite` runs on the workspace's chain just before the file is * written, as for `update`; throwing there writes nothing. + * + * Chats' own pages are main's: the save's `chatPages` and `namedFor` are + * merged with the stored ones (`mergeSavedChatPages`). A save never adds or + * moves a claim, except to give back a claim on a page it brings back that + * this store recorded when the page was deleted, while the chat is still + * where that delete moved it, and to send a chat whose page the save removes + * to the page the save names for it when both documents have that page. + * The record changes only once the write lands. */ async save( workspaceId: string, doc: DesignCanvas, baseRevision: number, - options: { undone?: readonly string[]; beforeWrite?: () => Promise<void> | void } = {}, + options: { + undone?: readonly string[]; + beforeWrite?: () => Promise<void> | void; + /** + * Which of these chats are live in this workspace. Asked on the chain, + * only for the chats a page this save brings back was made for, as the + * delete record has it; a brought-back page keeps `namedFor` only for a + * live chat. Left out, every chat counts as live. + */ + chatsLive?: (chatIds: string[]) => Promise<ReadonlySet<string>>; + } = {}, ): Promise<DesignCanvasSaveResult> { assertDesignCanvasWorkspaceId(workspaceId); if (!Number.isSafeInteger(baseRevision) || baseRevision < 0) { @@ -123,14 +172,23 @@ export class DesignCanvasStore { const current = await this.read(workspaceId); if (current.revision !== baseRevision) return { ok: false, reason: "conflict", doc: current }; const revision = baseRevision + 1; + const deleted = this.deletedOf(workspaceId); + const isLive = await this.livenessFor(current, parsed.doc, deleted, options.chatsLive); + const merged = mergeSavedChatPages(current, parsed.doc, deleted, isLive); // A save comes from the person's canvas: a page they took off is remembered, // unless it was their undo that took it off. - const doc = withRemovedPagePaths(current, { ...parsed.doc, revision }, true, new Set(options.undone ?? [])); + const doc = withRemovedPagePaths(current, { ...merged.doc, revision }, true, new Set(options.undone ?? [])); // The pages remembered as taken off count too: what is written must read back. if (this.tooLarge(doc)) return tooLarge(); await options.beforeWrite?.(); await this.write(workspaceId, doc); - return { ok: true, revision }; + this.forgetRestored(workspaceId, merged.restored); + this.remember(workspaceId, removedPageIds(current, doc), merged.deletedNow); + if (!merged.changed) return { ok: true, revision }; + const namedFor = Object.fromEntries( + doc.pages.flatMap((page) => (page.namedFor !== undefined ? [[page.id, page.namedFor]] : [])), + ); + return { ok: true, revision, chatPages: { ...doc.chatPages }, namedFor }; }); } @@ -157,14 +215,40 @@ export class DesignCanvasStore { if (this.tooLarge(doc)) throw new Error("The canvas is too large to save."); await options.beforeWrite?.(); await this.write(workspaceId, doc); + this.remember(workspaceId, removedPageIds(current, doc), deletedClaims(current, doc)); return doc; }); } + /** + * The workspaces that have a canvas file. Only startup recovery asks, for a + * chat delete whose workspace is no longer known. + */ + async workspaceIds(): Promise<string[]> { + const names = await fs.readdir(this.root()).catch((error: unknown) => { + if (isMissing(error)) return [] as string[]; + throw error; + }); + return names + .filter((name) => name.endsWith(".json")) + .map((name) => name.slice(0, -".json".length)) + .filter((workspaceId) => isWorkspaceArtifactWorkspaceId(workspaceId)) + .sort(); + } + + /** + * The chats some page of the workspace's canvas is made for, as of this + * store's last read or write of it; undefined until the first. + */ + namedChats(workspaceId: string): ReadonlySet<string> | undefined { + return this.namedFor.get(workspaceId); + } + /** Removes the workspace's canvas file and any copies set aside as corrupt. Missing is fine. */ async delete(workspaceId: string): Promise<void> { assertDesignCanvasWorkspaceId(workspaceId); return this.serialize(workspaceId, async () => { + this.namedFor.delete(workspaceId); await fs.rm(this.file(workspaceId), { force: true }); const prefix = `${workspaceId}.json.corrupt-`; const names = await fs.readdir(this.root()).catch((error: unknown) => { @@ -174,14 +258,84 @@ export class DesignCanvasStore { for (const name of names) { if (name.startsWith(prefix)) await fs.rm(path.join(this.root(), name), { force: true }); } + // Only once the files are gone: a delete that fails leaves the canvas, so undo still needs the record. + this.deletedPages.delete(workspaceId); }); } + /** + * Liveness for the chats whose page `saved` brings back with the + * `namedFor` the delete record holds: usually none, so nothing is asked. + */ + private async livenessFor( + current: DesignCanvas, + saved: DesignCanvas, + deleted: ReadonlyMap<string, DeletedPage>, + chatsLive: ((chatIds: string[]) => Promise<ReadonlySet<string>>) | undefined, + ): Promise<((chatId: string) => boolean) | undefined> { + if (!chatsLive) return undefined; + const stored = new Set(current.pages.map((page) => page.id)); + const asked = new Set<string>(); + for (const page of saved.pages) { + if (stored.has(page.id) || page.namedFor === undefined) continue; + if (deleted.get(page.id)?.namedFor === page.namedFor) asked.add(page.namedFor); + } + if (asked.size === 0) return undefined; + const live = await chatsLive([...asked]); + return (chatId) => !asked.has(chatId) || live.has(chatId); + } + + private deletedOf(workspaceId: string): ReadonlyMap<string, DeletedPage> { + return this.deletedPages.get(workspaceId) ?? new Map(); + } + + /** + * Records pages a write deleted. Every page it removed forgets what an older + * delete of that id recorded, even when this delete had nothing to record. + */ + private remember(workspaceId: string, removed: readonly string[], deleted: ReadonlyMap<string, DeletedPage>): void { + let record = this.deletedPages.get(workspaceId); + if (record) for (const pageId of removed) record.delete(pageId); + if (deleted.size === 0) { + if (record?.size === 0) this.deletedPages.delete(workspaceId); + return; + } + if (!record) this.deletedPages.set(workspaceId, (record = new Map())); + for (const [pageId, entry] of deleted) { + record.delete(pageId); + record.set(pageId, entry); + } + for (const pageId of record.keys()) { + if (record.size <= DELETED_PAGES_LIMIT) break; + record.delete(pageId); + } + } + + /** Takes what a save gave back out of the record, so a later undo acts on the newest delete only. */ + private forgetRestored(workspaceId: string, restored: ReadonlyMap<string, DeletedPage>): void { + const record = this.deletedPages.get(workspaceId); + if (!record) return; + for (const [pageId, given] of restored) { + const entry = record.get(pageId); + if (!entry) continue; + for (const chatId of given.claims.keys()) entry.claims.delete(chatId); + if (given.namedFor !== undefined && entry.namedFor === given.namedFor) delete entry.namedFor; + if (entry.claims.size === 0 && entry.namedFor === undefined) record.delete(pageId); + } + if (record.size === 0) this.deletedPages.delete(workspaceId); + } + private file(workspaceId: string): string { return path.join(this.root(), `${workspaceId}.json`); } private async read(workspaceId: string): Promise<DesignCanvas> { + const doc = await this.readFile(workspaceId); + this.noteNamed(workspaceId, doc); + return doc; + } + + private async readFile(workspaceId: string): Promise<DesignCanvas> { let text: string; try { const file = this.file(workspaceId); @@ -221,8 +375,13 @@ export class DesignCanvasStore { return Buffer.byteLength(JSON.stringify(doc), "utf8") > this.maxDocumentBytes; } - private write(workspaceId: string, doc: DesignCanvas): Promise<void> { - return this.writeJson(this.file(workspaceId), doc, { mode: 0o600, mkdirMode: 0o700 }); + private async write(workspaceId: string, doc: DesignCanvas): Promise<void> { + await this.writeJson(this.file(workspaceId), doc, { mode: 0o600, mkdirMode: 0o700 }); + this.noteNamed(workspaceId, doc); + } + + private noteNamed(workspaceId: string, doc: DesignCanvas): void { + this.namedFor.set(workspaceId, new Set(doc.pages.flatMap((page) => (page.namedFor !== undefined ? [page.namedFor] : [])))); } /** @@ -274,6 +433,12 @@ export class DesignCanvasStore { } } +/** The ids of the pages `before` has and `after` does not. */ +function removedPageIds(before: DesignCanvas, after: DesignCanvas): string[] { + const kept = new Set(after.pages.map((page) => page.id)); + return before.pages.filter((page) => !kept.has(page.id)).map((page) => page.id); +} + function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -293,13 +458,16 @@ export type DesignChatCanvasSave = { result: DesignCanvasSaveResult; workspaceId * it checked) and returns it, so whatever the caller does next (broadcast, * focus) names the same workspace even if the chat moves meanwhile. */ +type ChatCanvasesStore = Pick<DesignCanvasStore, "get" | "save" | "update"> & Partial<Pick<DesignCanvasStore, "namedChats">>; + export class DesignChatCanvases { - private readonly store: Pick<DesignCanvasStore, "get" | "save" | "update">; + private readonly store: ChatCanvasesStore; private readonly resolveWorkspace: (chatId: string) => Promise<string | null>; private readonly workspaceExists: ((workspaceId: string) => Promise<boolean>) | undefined; + private readonly chatIsLive: ((chatId: string, workspaceId: string) => Promise<boolean>) | undefined; constructor(options: { - store: Pick<DesignCanvasStore, "get" | "save" | "update">; + store: ChatCanvasesStore; workspaceIdOf(chatId: string): Promise<string | null>; /** * Whether the workspace still has its record. A removed workspace's canvas @@ -309,10 +477,18 @@ export class DesignChatCanvases { * and one queued after finds the record gone and writes nothing. */ workspaceExists?(workspaceId: string): Promise<boolean>; + /** + * Whether the chat still exists and is in that workspace. A save asks it, + * on the workspace's chain, only for the chats a page it brings back was + * made for, so that page follows only a live chat. Left out, every chat + * counts as live. + */ + chatIsLive?(chatId: string, workspaceId: string): Promise<boolean>; }) { this.store = options.store; this.resolveWorkspace = options.workspaceIdOf; this.workspaceExists = options.workspaceExists; + this.chatIsLive = options.chatIsLive; } /** The chat's workspace id, or null when the chat is gone. */ @@ -321,6 +497,11 @@ export class DesignChatCanvases { return this.resolveWorkspace(chatId); } + /** The chats a page of the workspace's canvas is made for, when the store knows (`DesignCanvasStore.namedChats`). */ + namedChats(workspaceId: string): ReadonlySet<string> | undefined { + return this.store.namedChats?.(workspaceId); + } + async get(chatId: string, options: { workspaceId?: string } = {}): Promise<DesignChatCanvasRead> { const workspaceId = await this.workspaceFor(chatId, options.workspaceId); return { doc: await this.store.get(workspaceId), workspaceId }; @@ -333,9 +514,18 @@ export class DesignChatCanvases { options: { undone?: readonly string[]; workspaceId?: string } = {}, ): Promise<DesignChatCanvasSave> { const workspaceId = await this.workspaceFor(chatId, options.workspaceId); + const ask = this.chatIsLive; const result = await this.store.save(workspaceId, doc, baseRevision, { ...(options.undone ? { undone: options.undone } : {}), beforeWrite: () => this.assertWorkspaceExists(workspaceId), + ...(ask + ? { + chatsLive: async (chatIds: string[]) => { + const live = await Promise.all(chatIds.map((id) => ask(id, workspaceId))); + return new Set(chatIds.filter((_, index) => live[index])); + }, + } + : {}), }); return { result, workspaceId }; } @@ -364,7 +554,7 @@ export class DesignChatCanvases { workspaceId = given; } else { const resolved = await this.resolveWorkspace(chatId); - if (resolved === null) throw new Error("This chat is no longer available."); + if (resolved === null) throw new DesignCanvasUnavailableError("This chat is no longer available."); workspaceId = resolved; } // Asked again on the chain before a write; this early answer only spares the wait. @@ -374,7 +564,7 @@ export class DesignChatCanvases { private async assertWorkspaceExists(workspaceId: string): Promise<void> { if (this.workspaceExists && !(await this.workspaceExists(workspaceId))) { - throw new Error("This workspace is no longer available."); + throw new DesignCanvasUnavailableError("This workspace is no longer available."); } } } diff --git a/main/services/design-canvas/title-follow.test.ts b/main/services/design-canvas/title-follow.test.ts new file mode 100644 index 000000000..9323a9106 --- /dev/null +++ b/main/services/design-canvas/title-follow.test.ts @@ -0,0 +1,171 @@ +import assert from "node:assert/strict"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import test, { type TestContext } from "node:test"; +import { addChatPage } from "../../../renderer/shared/design-canvas/chat-pages.js"; +import { renamePage } from "../../../renderer/shared/design-canvas/pages.js"; +import type { DesignCanvas } from "../../../renderer/shared/design-canvas/schema.js"; +import { DesignCanvasStore, DesignChatCanvases, type DesignCanvasUpdated } from "./store.js"; +import { createDesignTitleFollow } from "./title-follow.js"; + +async function setup(t: TestContext, options: { seed?: (doc: DesignCanvas) => DesignCanvas } = {}) { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-design-title-follow-")); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + const root = path.join(dir, "design-canvases"); + const store = new DesignCanvasStore({ root: () => root }); + const workspaces = new Set(["ws-1"]); + const canvases = new DesignChatCanvases({ + store, + workspaceIdOf: async () => "ws-1", + workspaceExists: async (workspaceId) => workspaces.has(workspaceId), + }); + if (options.seed) { + await store.update("ws-1", (doc) => options.seed!(doc)); + } + const titles = new Map<string, string>(); + const broadcasts: DesignCanvasUpdated[] = []; + const errors: unknown[] = []; + const follow = createDesignTitleFollow({ + canvases, + titleOf: async (chatId) => titles.get(chatId), + broadcast: (update) => broadcasts.push(update), + onError: (error) => errors.push(error), + }); + return { root, store, workspaces, titles, broadcasts, errors, follow }; +} + +const withChatPage = (doc: DesignCanvas) => addChatPage(doc, "chat-b", "New chat", "page-b", "page-1"); + +test("a chat's rename renames the page made for it and tells open canvases", async (t) => { + const { store, titles, broadcasts, follow } = await setup(t, { seed: withChatPage }); + titles.set("chat-b", "Pricing table"); + await follow.follow("chat-b"); + const doc = await store.get("ws-1"); + assert.deepEqual( + doc.pages.map((page) => page.name), + ["Page 1", "Pricing table"], + ); + assert.equal(doc.pages[1]!.namedFor, "chat-b"); + assert.deepEqual(broadcasts, [{ workspaceId: "ws-1", chatId: "chat-b", revision: doc.revision }]); +}); + +test("a page the person renamed no longer follows", async (t) => { + const { store, titles, broadcasts, follow } = await setup(t, { + seed: (doc) => renamePage(withChatPage(doc), "page-b", "Mine"), + }); + const before = (await store.get("ws-1")).revision; + titles.set("chat-b", "Pricing table"); + await follow.follow("chat-b"); + const doc = await store.get("ws-1"); + assert.equal(doc.pages[1]!.name, "Mine"); + assert.equal(doc.revision, before); + assert.deepEqual(broadcasts, []); +}); + +test("a rename of a chat with no page made for it writes nothing", async (t) => { + const { store, titles, broadcasts, follow } = await setup(t, { seed: withChatPage }); + const before = (await store.get("ws-1")).revision; + titles.set("chat-a", "Northwind landing"); + await follow.follow("chat-a"); + assert.equal((await store.get("ws-1")).revision, before); + assert.deepEqual(broadcasts, []); +}); + +test("a title another page already has gets a number", async (t) => { + const { store, titles, follow } = await setup(t, { seed: withChatPage }); + titles.set("chat-b", "page 1"); + await follow.follow("chat-b"); + assert.deepEqual( + (await store.get("ws-1")).pages.map((page) => page.name), + ["Page 1", "page 1 2"], + ); +}); + +test("two quick renames and an entry running at once end on the newest title", async (t) => { + const { store, titles } = await setup(t, { seed: withChatPage }); + const written: string[] = []; + const original = store.update.bind(store); + store.update = (async (workspaceId, mutate, options) => { + const doc = await original(workspaceId, mutate, options); + written.push(doc.pages[1]!.name); + return doc; + }) as typeof store.update; + + let release!: () => void; + const held = new Promise<void>((resolve) => (release = resolve)); + let reads = 0; + const follower = createDesignTitleFollow({ + canvases: new DesignChatCanvases({ store, workspaceIdOf: async () => "ws-1" }), + titleOf: async (chatId) => { + const title = titles.get(chatId); + // The first run reads its title, then is slow to get going. + if (++reads === 1) await held; + return title; + }, + broadcast: () => undefined, + }); + + titles.set("chat-b", "First title"); + const first = follower.follow("chat-b"); + titles.set("chat-b", "Second title"); + const second = follower.follow("chat-b"); + titles.set("chat-b", "Newest title"); + const third = follower.follow("chat-b"); + release(); + await Promise.all([first, second, third]); + + assert.equal((await store.get("ws-1")).pages[1]!.name, "Newest title"); + // The two calls queued behind the first ran as one, reading the newest title. + assert.deepEqual(written, ["First title", "Newest title"]); + assert.equal(reads, 2); +}); + +test("a follow after the workspace record was removed writes nothing and logs nothing", async (t) => { + const { store, workspaces, titles, broadcasts, errors, follow } = await setup(t, { seed: withChatPage }); + // The record goes first; the canvas file is still there until cleanup runs. + workspaces.delete("ws-1"); + const before = await store.get("ws-1"); + titles.set("chat-b", "Pricing table"); + await follow.follow("chat-b"); + assert.deepEqual(await store.get("ws-1"), before); + assert.deepEqual(broadcasts, []); + assert.deepEqual(errors, [], "a chat whose workspace has no record has no canvas to follow"); +}); + +test("a follow of a chat that is gone writes nothing", async (t) => { + const { store, broadcasts, errors, follow } = await setup(t, { seed: withChatPage }); + const before = (await store.get("ws-1")).revision; + await follow.follow("chat-b"); + assert.equal((await store.get("ws-1")).revision, before); + assert.deepEqual(broadcasts, []); + assert.deepEqual(errors, []); +}); + +test("once the canvas is known, a title change of a chat with no page made for it reads no canvas, and a page made for it later still follows", async (t) => { + const { root, titles } = await setup(t, { seed: withChatPage }); + // A fresh start: nothing is known about the canvas until one read. + const store = new DesignCanvasStore({ root: () => root }); + let reads = 0; + const counted = { + get: (...args: Parameters<DesignCanvasStore["get"]>) => ((reads += 1), store.get(...args)), + save: (...args: Parameters<DesignCanvasStore["save"]>) => store.save(...args), + update: (...args: Parameters<DesignCanvasStore["update"]>) => ((reads += 1), store.update(...args)), + namedChats: (workspaceId: string) => store.namedChats(workspaceId), + }; + const follow = createDesignTitleFollow({ + canvases: new DesignChatCanvases({ store: counted, workspaceIdOf: async () => "ws-1" }), + titleOf: async (chatId) => titles.get(chatId), + broadcast: () => undefined, + }); + titles.set("chat-a", "Northwind landing"); + await follow.follow("chat-a"); + assert.equal(reads, 1, "one read learns which chats have pages made for them"); + await follow.follow("chat-a"); + assert.equal(reads, 1, "a chat with no page made for it reads nothing"); + + // Any write that makes a page for the chat (entry here) is seen, so the next rename follows. + await store.update("ws-1", (doc) => addChatPage(doc, "chat-a", "New chat", "page-a", "page-1")); + await follow.follow("chat-a"); + assert.equal((await store.get("ws-1")).pages.find((page) => page.id === "page-a")?.name, "Northwind landing"); +}); diff --git a/main/services/design-canvas/title-follow.ts b/main/services/design-canvas/title-follow.ts new file mode 100644 index 000000000..1483a8d3a --- /dev/null +++ b/main/services/design-canvas/title-follow.ts @@ -0,0 +1,77 @@ +// A page made for a chat (`namedFor`) takes the chat's title whenever it +// changes. Each run reads the title itself when it starts, and a chat's runs +// go one after another, so the newest title always wins however the renames +// and design-mode entry interleave. Once the store has read or written the +// workspace's canvas, it knows which chats have a page made for them, and a +// title change of any other chat reads no canvas. + +import { followChatTitle } from "../../../renderer/shared/design-canvas/chat-pages.js"; +import { DesignCanvasUnavailableError, type DesignCanvasUpdated, type DesignChatCanvases } from "./store.js"; + +export interface DesignTitleFollow { + /** Renames the pages made for the chat to its current title. Never throws. */ + follow(chatId: string): Promise<void>; +} + +const NOTHING_TO_RENAME = Symbol("nothing to rename"); + +export function createDesignTitleFollow(deps: { + canvases: Pick<DesignChatCanvases, "update" | "workspaceIdOf" | "namedChats">; + /** The chat's title now, or undefined when the chat is gone. */ + titleOf(chatId: string): Promise<string | undefined>; + broadcast(update: DesignCanvasUpdated): void; + onError?(error: unknown): void; +}): DesignTitleFollow { + const runs = new Map<string, { running: Promise<void>; next?: Promise<void> }>(); + + async function run(chatId: string): Promise<void> { + try { + const title = await deps.titleOf(chatId); + if (title === undefined) return; + const resolved = await deps.canvases.workspaceIdOf(chatId); + if (resolved === null) return; + if (deps.canvases.namedChats(resolved)?.has(chatId) === false) return; + // Through the chat's canvases, so a removed workspace is not written back. + const { doc, workspaceId } = await deps.canvases.update( + chatId, + (current) => { + const next = followChatTitle(current, chatId, title); + if (next === current) throw NOTHING_TO_RENAME; + return next; + }, + { workspaceId: resolved }, + ); + deps.broadcast({ workspaceId, chatId, revision: doc.revision }); + } catch (error) { + // A chat with no canvas (gone, or in a workspace with no record, such as an Assistant thread) has nothing to follow. + if (error !== NOTHING_TO_RENAME && !(error instanceof DesignCanvasUnavailableError)) deps.onError?.(error); + } + } + + function settle(chatId: string, done: Promise<void>): void { + const entry = runs.get(chatId); + if (entry?.running === done && !entry.next) runs.delete(chatId); + } + + return { + follow(chatId) { + const entry = runs.get(chatId); + if (!entry) { + const running: Promise<void> = run(chatId).finally(() => settle(chatId, running)); + runs.set(chatId, { running }); + return running; + } + // Calls behind a running one share the next run, which reads the newest title. + if (entry.next) return entry.next; + const next: Promise<void> = entry.running + .then(() => { + entry.running = next; + entry.next = undefined; + return run(chatId); + }) + .finally(() => settle(chatId, next)); + entry.next = next; + return next; + }, + }; +} diff --git a/main/services/design-canvas/views.test.ts b/main/services/design-canvas/views.test.ts index d899e7d51..731f043c7 100644 --- a/main/services/design-canvas/views.test.ts +++ b/main/services/design-canvas/views.test.ts @@ -108,6 +108,21 @@ test("when the window goes, every view is unmounted and every page kept", async assert.equal((await views.get("chat-b", "ws-2"))?.pageId, "p3"); }); +test("pageIdsOf lists other chats' kept pages, not the asking chat's, and reads them from the file after a restart", async (t) => { + const root = await tempRoot(t); + const before = new DesignCanvasViews({ root: () => root }); + await before.report("chat-a", "ws-1", view("page-1"), 0); + await before.report("chat-b", "ws-1", view("page-2"), 0); + await before.showPage("chat-c", "ws-1", "page-3"); + await before.report("chat-d", "ws-2", view("page-4"), 0); + assert.deepEqual([...(await before.pageIdsOf("ws-1", "chat-a"))].sort(), ["page-2", "page-3"]); + await before.flush(); + + const after = new DesignCanvasViews({ root: () => root }); + assert.deepEqual([...(await after.pageIdsOf("ws-1", "chat-b"))].sort(), ["page-1", "page-3"]); + assert.deepEqual([...(await after.pageIdsOf("ws-3", "chat-a"))], []); +}); + test("views survive a restart: a new instance on the same root reads the page, viewports and focusId", async (t) => { const root = await tempRoot(t); const before = new DesignCanvasViews({ root: () => root }); @@ -249,6 +264,30 @@ test("a turn's page: what Aiden showed this turn, then the message's page, then assert.equal((await turn.view(docWith("p9"), "ws-1")).pageId, "p9"); }); +test("with no view, a turn works on the chat's claimed page", async () => { + const views = new DesignCanvasViews(); + const doc = { ...docWith("p1", "p2", "p3"), chatPages: { "chat-a": "p3", "chat-b": "p2" } }; + assert.equal((await designTurnPages({ views, chatId: "chat-a" }).view(doc, "ws-1")).pageId, "p3"); + assert.equal((await designTurnPages({ chatId: "chat-b" }).view(doc, "ws-1")).pageId, "p2"); + assert.equal((await designTurnPages({ views, chatId: "chat-c" }).view(doc, "ws-1")).pageId, "p1", "no claim: the first page"); +}); + +test("when the view's page is gone, a turn works on the claim before the first page", async () => { + const views = new DesignCanvasViews(); + await views.report("chat-a", "ws-1", view("deleted"), 0); + const doc = { ...docWith("p1", "p2"), chatPages: { "chat-a": "p2" } }; + assert.equal((await designTurnPages({ views, chatId: "chat-a" }).view(doc, "ws-1")).pageId, "p2"); + // A claim on a page that is gone too falls through to the first page. + assert.equal((await designTurnPages({ views, chatId: "chat-a" }).view({ ...doc, chatPages: { "chat-a": "gone" } }, "ws-1")).pageId, "p1"); +}); + +test("the view still wins over the claim", async () => { + const views = new DesignCanvasViews(); + await views.report("chat-a", "ws-1", view("p1"), 0); + const doc = { ...docWith("p1", "p2"), chatPages: { "chat-a": "p2" } }; + assert.equal((await designTurnPages({ views, chatId: "chat-a" }).view(doc, "ws-1")).pageId, "p1"); +}); + test("a turn without the registry still follows its own shown page", async () => { const doc = docWith("p1", "p2"); const turn = designTurnPages({ chatId: "chat-a" }); diff --git a/main/services/design-canvas/views.ts b/main/services/design-canvas/views.ts index b7fc2c2c3..8eb085975 100644 --- a/main/services/design-canvas/views.ts +++ b/main/services/design-canvas/views.ts @@ -164,6 +164,15 @@ export class DesignCanvasViews { }; } + /** The pages every other chat on the workspace was last on, whether or not its canvas is open. */ + async pageIdsOf(workspaceId: string, exceptChatId: string): Promise<Set<string>> { + const pageIds = new Set<string>(); + for (const [chatId, entry] of (await this.workspace(workspaceId)).entries) { + if (chatId !== exceptChatId) pageIds.add(entry.pageId); + } + return pageIds; + } + /** How many chats have this workspace's canvas open. */ mounted(workspaceId: string): number { let count = 0; @@ -275,8 +284,10 @@ export class DesignCanvasViews { * The page a chat's Aiden turn works on, resolved the same way everywhere in * the turn (tools, auto-placed pages and images, the prompt line), in order: * a page Aiden showed earlier in this turn, the page the person's message was - * sent from, the chat's kept page, then the first page. Each counts only while - * the page exists. Background and entry placements use it without a message. + * sent from, the chat's kept page, the chat's own page (`chatPages`), then + * the first page. Each counts only while the page exists. The renderer's + * canvas falls back in the same order (`useDesignView`). Background and entry + * placements use it without a message. */ export type DesignTurnPages = { /** @@ -284,9 +295,9 @@ export type DesignTurnPages = { * turn's view for any version of the document without waiting, so a store * update's mutate can use it on the latest document. */ - resolver(workspaceId: string): Promise<(doc: Pick<DesignCanvas, "pages">) => DesignChatView>; + resolver(workspaceId: string): Promise<(doc: Pick<DesignCanvas, "pages" | "chatPages">) => DesignChatView>; /** The chat's view for this turn, on a page that exists in `doc`. */ - view(doc: Pick<DesignCanvas, "pages">, workspaceId: string): Promise<DesignChatView>; + view(doc: Pick<DesignCanvas, "pages" | "chatPages">, workspaceId: string): Promise<DesignChatView>; /** Aiden shows `pageId`: later calls in the turn work on it. The change's `focusId`, when main keeps views. */ show(workspaceId: string, pageId: string): Promise<number | undefined>; }; @@ -303,7 +314,10 @@ export function designTurnPages(options: { return (doc) => { const exists = (pageId: string | undefined): pageId is string => pageId !== undefined && doc.pages.some((page) => page.id === pageId); - const pageId = [shown, options.message?.pageId, kept?.pageId].find(exists) ?? doc.pages[0]!.id; + const claim = Object.prototype.hasOwnProperty.call(doc.chatPages, options.chatId) + ? doc.chatPages[options.chatId] + : undefined; + const pageId = [shown, options.message?.pageId, kept?.pageId, claim].find(exists) ?? doc.pages[0]!.id; const size = options.message?.viewSize ?? kept?.size; return { pageId, diff --git a/main/services/design-canvas/written-pages.test.ts b/main/services/design-canvas/written-pages.test.ts index 90ba7782c..ef55f11f2 100644 --- a/main/services/design-canvas/written-pages.test.ts +++ b/main/services/design-canvas/written-pages.test.ts @@ -3,7 +3,7 @@ import * as fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; -import { emptyDesignCanvas, type DesignCanvas, type DesignFrame } from "../../../renderer/shared/design-canvas/schema.js"; +import { DESIGN_CANVAS_LIMITS, emptyDesignCanvas, type DesignCanvas, type DesignFrame } from "../../../renderer/shared/design-canvas/schema.js"; import { createDesignPageScanner, DESIGN_WIDTH_HINT_BYTES, @@ -21,6 +21,10 @@ import type { DesignViewState } from "../../../renderer/shared/design-canvas/can import type { DesignChatView } from "../../../renderer/shared/design-canvas/view.js"; import { DesignCanvasStore, DesignChatCanvases } from "./store.js"; import { DesignCanvasViews, designTurnPages } from "./views.js"; +import { placeArtifactsOnCanvas } from "./artifact-frames.js"; +import { createDesignEntry } from "./entry.js"; +import { createDesignTitleFollow } from "./title-follow.js"; +import { PendingEntries } from "./written-pages.js"; const ids = () => { let next = 0; @@ -329,9 +333,10 @@ test("deleted newest pages do not starve older surviving pages under limit, and } // Pages 12..15 were noted most recently and then deleted before entry. // Pages 00..11 still exist on disk and should all 12 land in chronological order. - const { workspaceStore: store, via } = canvasesAt(canvasesDir); + const canvases = canvasesAt(canvasesDir); + const { workspaceStore: store, via } = canvases; const broadcasts: string[] = []; - const entry = { pageName: "Landing", hasView: async () => false }; + const entry = entryFor(canvases, "chat-1", "Landing"); // A deleted chat places nothing and writes no canvas. let canSave = false; @@ -397,6 +402,7 @@ test("leaving design mode while the page's save waits keeps the frame off the st paths: ["design/home.html"], // The person leaves design mode once the save is already under way. store: { + get: (chatId, options) => store.get(chatId, options), workspaceIdOf: (chatId) => store.workspaceIdOf(chatId), update: (chatId, mutate, options) => store.update( @@ -433,6 +439,7 @@ test("leaving design mode while the page's file is being written takes the frame workspaceRoot, paths: ["design/home.html"], store: { + get: (id, options) => store.get(id, options), workspaceIdOf: (id) => store.workspaceIdOf(id), update: async (id, mutate, options) => { calls += 1; @@ -560,6 +567,22 @@ test("a written page dedupes only against the chat's view page", () => { assert.equal(again.changed, false, "on p2 the page is already there"); }); +test("a written page auto-placed in a turn claims for a chat with none", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, ["home.html"]); + await canvases.store.update("chat-1", (doc) => ({ ...doc, pages: [...doc.pages, { id: "p2", name: "Pricing" }] })); + await canvases.views.report("chat-1", "ws-1", onPage("p2"), 0); + await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-1"), + workspaceRoot, + paths: ["design/home.html"], + broadcast: () => undefined, + newId: ids(), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.equal(doc.revision, 2, "the claim rides on the placement's write"); + assert.deepEqual(doc.chatPages, { "chat-1": "p2" }); +}); + test("a turn's message page beats the chat's kept page for a page written mid-turn", async (t) => { const { workspaceRoot, canvases } = await workspaceWith(t, ["home.html"]); await canvases.store.update("chat-1", (doc) => ({ ...doc, pages: [...doc.pages, { id: "p2", name: "Pricing" }] })); @@ -575,53 +598,204 @@ test("a turn's message page beats the chat's kept page for a page written mid-tu assert.equal((await canvases.workspaceStore.get("ws-1")).frames[0]?.pageId, "page-1"); }); -test("re-entering design mode after a restart, with the pages already on page 1, makes no page and no frame", async (t) => { - const { workspaceRoot, canvases } = await workspaceWith(t, ["home.html", "about.html"]); - await canvases.store.update("chat-1", (doc) => ({ - ...doc, - frames: [fileFrame("home", "design/home.html", "page-1"), fileFrame("about", "design/about.html", "page-1")], - })); - const before = await canvases.workspaceStore.get("ws-1"); - const broadcasts: unknown[] = []; +/** Design-mode entry for `chatId`: other chats' views from `views`, and every chat live unless `gone` names it. */ +function entryFor( + canvases: ReturnType<typeof canvasesAt>, + chatId: string, + pageName: string, + gone: readonly string[] = [], +) { + return { + pageName, + otherViews: (workspaceId: string) => canvases.views.pageIdsOf(workspaceId, chatId), + isLive: async (chatIds: string[]) => new Set(chatIds.filter((id) => !gone.includes(id))), + }; +} + +test("the first chat on a fresh canvas claims Page 1 without renaming it, adds no page, and shows it", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); const placed = await placeWrittenPagesOnCanvas({ ...canvases.via("chat-1"), workspaceRoot, - paths: ["design/home.html", "design/about.html"], - broadcast: (update) => broadcasts.push(update), + paths: [], + broadcast: () => undefined, newId: ids(), - entry: { pageName: "Landing", hasView: async () => false }, + entry: entryFor(canvases, "chat-1", "Northwind landing"), }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages, [{ id: "page-1", name: "Page 1" }]); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1" }); assert.deepEqual(placed.frameIds, []); - assert.deepEqual(await canvases.workspaceStore.get("ws-1"), before, "the canvas is untouched"); - assert.deepEqual(broadcasts, []); - assert.equal((await canvases.views.get("chat-1", "ws-1"))?.pageId, "page-1", "the chat's page is where its pages are"); + assert.equal(placed.pageId, "page-1"); + assert.equal(placed.focusId, 1, "the claimed page is shown"); + assert.equal((await canvases.views.get("chat-1", "ws-1"))?.pageId, "page-1"); +}); + +test("chat B entering a workspace whose first page is chat A's gets a page named after B, claimed and shown", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + // Page 1 is A's, and empty: an empty page another chat claims is not shared. + await canvases.store.update("chat-1", (doc) => ({ ...doc, chatPages: { "chat-1": "page-1" } })); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-2", "Pricing table"), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages.map((page) => page.name), ["Page 1", "Pricing table"]); + const page = doc.pages[1]!; + assert.equal(page.namedFor, "chat-2"); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1", "chat-2": page.id }); + assert.equal(placed.pageId, page.id); + assert.equal(placed.focusId, 1); + assert.equal((await canvases.views.get("chat-2", "ws-1"))?.pageId, page.id); }); -test("chat B entering a workspace whose first page is chat A's gets a page of its own holding B's pages", async (t) => { +test("chat B's earlier pages go on the page made for it when the first page is chat A's", async (t) => { const { workspaceRoot, canvases } = await workspaceWith(t, ["b-home.html", "b-about.html"]); - await canvases.store.update("chat-1", (doc) => ({ ...doc, frames: [fileFrame("a-home", "design/a-home.html", "page-1")] })); + await canvases.store.update("chat-1", (doc) => ({ + ...doc, + chatPages: { "chat-1": "page-1" }, + frames: [fileFrame("a-home", "design/a-home.html", "page-1")], + })); const placed = await placeWrittenPagesOnCanvas({ ...canvases.via("chat-2"), workspaceRoot, paths: ["design/b-home.html", "design/b-about.html"], broadcast: () => undefined, newId: ids(), - entry: { pageName: "Brand refresh", hasView: async () => false }, + entry: entryFor(canvases, "chat-2", "Brand refresh"), }); const doc = await canvases.workspaceStore.get("ws-1"); const page = doc.pages.find((entry) => entry.name === "Brand refresh"); assert.ok(page, "a page named after chat B"); assert.equal(placed.pageId, page.id); - assert.equal(placed.focusId, 1, "showing it is an Aiden page change"); assert.deepEqual( doc.frames.filter((frame) => frame.pageId === page.id).map((frame) => frame.path), ["design/b-home.html", "design/b-about.html"], ); assert.equal(doc.frames.find((frame) => frame.id === "a-home")?.pageId, "page-1", "chat A's page is left alone"); - assert.equal((await canvases.views.get("chat-2", "ws-1"))?.pageId, page.id, "B's view is its new page"); }); -test("entry puts the missing pages beside the ones already on the canvas, on the page holding most of them", async (t) => { +test("a page with frames that another chat's kept view is on is not taken; B gets its own page", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ ...doc, frames: [fileFrame("a-home", "design/a-home.html", "page-1")] })); + await canvases.views.report("chat-1", "ws-1", onPage("page-1"), 0); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-2", "Brand refresh"), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages.map((page) => page.name), ["Page 1", "Brand refresh"]); + assert.deepEqual(doc.chatPages, { "chat-2": doc.pages[1]!.id }); + assert.equal(placed.pageId, doc.pages[1]!.id); +}); + +test("a page with frames that only this chat has looked at is claimed as it is", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, ["mine.html"]); + await canvases.store.update("chat-1", (doc) => ({ ...doc, frames: [fileFrame("other", "design/other.html", "page-1")] })); + await canvases.views.report("chat-1", "ws-1", onPage("page-1"), 0); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-1"), + workspaceRoot, + paths: ["design/mine.html"], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-1", "Landing"), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages, [{ id: "page-1", name: "Page 1" }]); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1" }); + assert.equal(placed.pageId, "page-1"); + assert.equal(doc.frames.find((frame) => frame.path === "design/mine.html")?.pageId, "page-1"); +}); + +test("a claim of a chat that no longer exists does not stop the page being claimed", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ ...doc, chatPages: { "chat-gone": "page-1" } })); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-2", "Pricing table", ["chat-gone"]), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.equal(doc.pages.length, 1); + assert.equal(placed.pageId, "page-1"); + // The gone chat's entry is dropped in the same write. + assert.deepEqual(doc.chatPages, { "chat-2": "page-1" }); +}); + +test("a page named for another chat is never taken by rule 3", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ ...doc, pages: [{ id: "page-1", name: "Landing", namedFor: "chat-1" }] })); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-2", "Pricing table"), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages.map((page) => [page.name, page.namedFor]), [["Landing", "chat-1"], ["Pricing table", "chat-2"]]); + assert.equal(placed.pageId, doc.pages[1]!.id); +}); + +test("a page named for a chat that no longer exists is taken by rule 3, and the mark goes in the same write", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ ...doc, pages: [{ id: "page-1", name: "Landing", namedFor: "chat-gone" }] })); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-2", "Pricing table", ["chat-gone"]), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages, [{ id: "page-1", name: "Landing" }]); + assert.equal(placed.pageId, "page-1"); + assert.deepEqual(doc.chatPages, { "chat-2": "page-1" }); +}); + +test("a chat entering again keeps its claim, adds no page and still shows it", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, ["home.html", "about.html"]); + await canvases.store.update("chat-1", (doc) => ({ + ...doc, + pages: [...doc.pages, { id: "p2", name: "Flows" }], + chatPages: { "chat-1": "p2" }, + frames: [fileFrame("home", "design/home.html", "page-1"), fileFrame("about", "design/about.html", "page-1")], + })); + // The chat last looked at page 1; its claim is still p2. + await canvases.views.report("chat-1", "ws-1", onPage("page-1"), 0); + const before = await canvases.workspaceStore.get("ws-1"); + const broadcasts: unknown[] = []; + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-1"), + workspaceRoot, + paths: ["design/home.html", "design/about.html"], + broadcast: (update) => broadcasts.push(update), + newId: ids(), + entry: entryFor(canvases, "chat-1", "Landing"), + }); + assert.deepEqual(placed.frameIds, []); + assert.deepEqual(await canvases.workspaceStore.get("ws-1"), before, "the canvas is untouched"); + assert.deepEqual(broadcasts, []); + assert.equal(placed.pageId, "p2"); + assert.equal(placed.focusId, 1); + assert.equal((await canvases.views.get("chat-1", "ws-1"))?.pageId, "p2"); +}); + +test("the chat's earlier pages already on the canvas make the page holding most of them its claim", async (t) => { const { workspaceRoot, canvases } = await workspaceWith(t, ["a.html", "b.html", "c.html"]); await canvases.store.update("chat-1", (doc) => ({ ...doc, @@ -634,71 +808,116 @@ test("entry puts the missing pages beside the ones already on the canvas, on the paths: ["design/a.html", "design/b.html", "design/c.html"], broadcast: () => undefined, newId: ids(), - entry: { pageName: "Landing", hasView: async () => false }, + entry: entryFor(canvases, "chat-1", "Landing"), }); const doc = await canvases.workspaceStore.get("ws-1"); assert.equal(doc.pages.length, 2, "no new page"); + assert.deepEqual(doc.chatPages, { "chat-1": "p2" }); assert.equal(placed.pageId, "p2"); assert.deepEqual(placed.frameIds.map((id) => doc.frames.find((frame) => frame.id === id)?.path), ["design/c.html"]); assert.equal(doc.frames.find((frame) => frame.path === "design/c.html")?.pageId, "p2"); assert.equal((await canvases.views.get("chat-1", "ws-1"))?.pageId, "p2"); }); -test("a chat with a view of its own enters onto its page, even when that page has frames", async (t) => { - const { workspaceRoot, canvases } = await workspaceWith(t, ["mine.html"]); - await canvases.store.update("chat-1", (doc) => ({ ...doc, frames: [fileFrame("other", "design/other.html", "page-1")] })); - await canvases.views.report("chat-1", "ws-1", onPage("page-1"), 0); +test("a page another live chat claims does not count toward the chat's earlier pages", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, ["index.html"]); + // A's page holds design/index.html; B wrote the same file in its own replies. + await canvases.store.update("chat-1", (doc) => ({ + ...doc, + chatPages: { "chat-1": "page-1" }, + frames: [fileFrame("a-index", "design/index.html", "page-1")], + })); const placed = await placeWrittenPagesOnCanvas({ - ...canvases.via("chat-1"), + ...canvases.via("chat-2"), workspaceRoot, - paths: ["design/mine.html"], + paths: ["design/index.html"], broadcast: () => undefined, newId: ids(), - entry: { pageName: "Landing", hasView: async () => true }, + entry: entryFor(canvases, "chat-2", "Pricing"), }); const doc = await canvases.workspaceStore.get("ws-1"); - assert.equal(doc.pages.length, 1); - assert.equal(placed.pageId, "page-1"); - assert.equal(placed.focusId, undefined, "the page on screen does not change"); + assert.notEqual(placed.pageId, "page-1"); + assert.deepEqual(doc.pages.map((page) => page.name), ["Page 1", "Pricing"]); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1", "chat-2": placed.pageId }); }); -test("whether the chat had a view is read before its files, so a canvas opening meanwhile cannot send its pages onto another chat's page", async (t) => { - const { workspaceRoot, canvases } = await workspaceWith(t, ["b-home.html"]); - await canvases.store.update("chat-1", (doc) => ({ ...doc, frames: [fileFrame("a-home", "design/a-home.html", "page-1")] })); - // The canvas this entry opens reports a view of page 1 while the files are being read. - let reported = false; - const via = canvases.via("chat-2"); +test("two chats entering a fresh canvas at once end on Page 1 and a new page", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + const enter = (chatId: string, title: string) => + placeWrittenPagesOnCanvas({ + ...canvases.via(chatId), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: () => `page-${chatId}`, + entry: entryFor(canvases, chatId, title), + }); + const [a, b] = await Promise.all([enter("chat-1", "Landing"), enter("chat-2", "Pricing")]); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.equal(doc.pages.length, 2); + assert.notEqual(a.pageId, b.pageId); + assert.deepEqual(new Set(Object.values(doc.chatPages)), new Set(doc.pages.map((page) => page.id))); + assert.deepEqual(doc.chatPages, { "chat-1": a.pageId, "chat-2": b.pageId }); + assert.equal(doc.pages[0]!.name, "Page 1"); + const made = doc.pages[1]!; + assert.equal(doc.chatPages[made.namedFor!], made.id, "the new page is named for the chat that claimed it"); +}); + +test("B's new page is numbered when a page already has B's title", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ + ...doc, + pages: [...doc.pages, { id: "p2", name: "Pricing" }], + chatPages: { "chat-1": "page-1" }, + })); + await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + workspaceRoot, + paths: [], + broadcast: () => undefined, + newId: () => "page-b", + entry: entryFor(canvases, "chat-2", "pricing"), + }); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.pages.map((page) => page.name), ["Page 1", "pricing 2", "Pricing"]); + assert.equal(doc.chatPages["chat-2"], "page-b"); +}); + +test("at the page limit, a chat whose page is taken shares it", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ + ...doc, + pages: Array.from({ length: DESIGN_CANVAS_LIMITS.pages }, (_, index) => ({ id: `page-${index + 1}`, name: `Page ${index + 1}` })), + chatPages: { "chat-1": "page-1" }, + })); const placed = await placeWrittenPagesOnCanvas({ - ...via, - pages: { - ...via.pages, - resolver: async (workspaceId: string) => { - reported = true; - return via.pages.resolver(workspaceId); - }, - }, + ...canvases.via("chat-2"), workspaceRoot, - paths: ["design/b-home.html"], + paths: [], broadcast: () => undefined, - newId: ids(), - entry: { pageName: "Brand refresh", hasView: async () => reported }, + newId: () => "page-b", + entry: entryFor(canvases, "chat-2", "Pricing"), }); const doc = await canvases.workspaceStore.get("ws-1"); - const page = doc.pages.find((entry) => entry.name === "Brand refresh"); - assert.ok(page, "chat B still gets a page of its own"); - assert.equal(placed.pageId, page.id); - assert.deepEqual(doc.frames.filter((frame) => frame.pageId === "page-1").map((frame) => frame.id), ["a-home"]); + assert.equal(doc.pages.length, DESIGN_CANVAS_LIMITS.pages); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1", "chat-2": "page-1" }); + assert.equal(placed.pageId, "page-1"); }); -test("leaving design mode while entry's file is being written takes back the page it added as well as its frames", async (t) => { +test("leaving design mode while entry's file is being written takes back the added page and the claim on it", async (t) => { const { workspaceRoot, canvases } = await workspaceWith(t, ["b-home.html"]); - await canvases.store.update("chat-1", (doc) => ({ ...doc, frames: [fileFrame("a-home", "design/a-home.html", "page-1")] })); + await canvases.store.update("chat-1", (doc) => ({ + ...doc, + chatPages: { "chat-1": "page-1" }, + frames: [fileFrame("a-home", "design/a-home.html", "page-1")], + })); let designMode = true; let calls = 0; const via = canvases.via("chat-2"); - await placeWrittenPagesOnCanvas({ + const placed = await placeWrittenPagesOnCanvas({ ...via, store: { + get: (id, options) => canvases.store.get(id, options), workspaceIdOf: (id) => canvases.store.workspaceIdOf(id), update: async (id, mutate, options) => { calls += 1; @@ -712,9 +931,113 @@ test("leaving design mode while entry's file is being written takes back the pag paths: ["design/b-home.html"], broadcast: () => undefined, newId: ids(), - entry: { pageName: "Brand refresh", hasView: async () => false }, + entry: entryFor(canvases, "chat-2", "Brand refresh"), }); const doc = await canvases.workspaceStore.get("ws-1"); assert.deepEqual(doc.pages.map((page) => page.name), ["Page 1"], "no empty page is left on the shared canvas"); assert.deepEqual(doc.frames.map((frame) => frame.id), ["a-home"]); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1" }); + assert.equal(placed.focusId, undefined, "nothing is shown"); +}); + +test("with design mode turned off before the write, no claim is made and nothing is shown", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, ["b-home.html"]); + await canvases.store.update("chat-1", (doc) => ({ ...doc, chatPages: { "chat-1": "page-1" } })); + const before = await canvases.workspaceStore.get("ws-1"); + const placed = await placeWrittenPagesOnCanvas({ + ...canvases.via("chat-2"), + shouldSave: () => false, + workspaceRoot, + paths: ["design/b-home.html"], + broadcast: () => undefined, + newId: ids(), + entry: entryFor(canvases, "chat-2", "Brand refresh"), + }); + assert.deepEqual(await canvases.workspaceStore.get("ws-1"), before); + assert.deepEqual(placed.frameIds, []); + assert.equal(placed.focusId, undefined); + assert.equal(await canvases.views.get("chat-2", "ws-1"), undefined); +}); + +test("an entry still running when its chat moves to another workspace writes nothing back to the canvas it left", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, ["b-home.html"]); + await canvases.store.update("chat-1", (doc) => ({ ...doc, chatPages: { "chat-1": "page-1" } })); + const before = await canvases.workspaceStore.get("ws-1"); + // chat-2 starts in ws-1; the move points it at ws-2 while entry waits. + const workspaces = new Map([["chat-1", "ws-1"], ["chat-2", "ws-1"]]); + const store = new DesignChatCanvases({ + store: canvases.workspaceStore, + workspaceIdOf: async (chatId) => workspaces.get(chatId) ?? null, + }); + let release: () => void = () => undefined; + const held = new Promise<void>((resolve) => { + release = resolve; + }); + let reached: () => void = () => undefined; + const waiting = new Promise<void>((resolve) => { + reached = resolve; + }); + const entry = placeWrittenPagesOnCanvas({ + chatId: "chat-2", + store, + pages: canvases.pages("chat-2"), + shouldSave: () => true, + workspaceRoot, + paths: ["design/b-home.html"], + broadcast: () => undefined, + newId: ids(), + entry: { + ...entryFor(canvases, "chat-2", "Brand refresh"), + isLive: async (chatIds: string[]) => { + reached(); + await held; + return new Set(chatIds); + }, + }, + }); + await waiting; + // The move commits, then the old canvas's cleanup finds nothing of chat-2's. + workspaces.set("chat-2", "ws-2"); + release(); + const placed = await entry; + assert.deepEqual(await canvases.workspaceStore.get("ws-1"), before, "no claim, named page or frames come back to ws-1"); + assert.deepEqual(placed.frameIds, []); + assert.equal(placed.focusId, undefined); +}); + +test("a turn's write while design mode's entry runs waits for it, lands on the chat's new page, and the page takes the newest title", async (t) => { + const { workspaceRoot, canvases } = await workspaceWith(t, []); + await canvases.store.update("chat-1", (doc) => ({ ...doc, chatPages: { "chat-1": "page-1" } })); + const pending = new PendingEntries(); + // The auto-title lands while entry runs. + const titles = new Map([["chat-2", "Pricing table"]]); + const focused: { chatId: string; pageId: string; focusId?: number }[] = []; + const enter = createDesignEntry({ + store: canvases.store, + views: canvases.views, + recent: new RecentWrittenPages(), + pending, + titleFollow: createDesignTitleFollow({ canvases: canvases.store, titleOf: async (chatId) => titles.get(chatId), broadcast: () => undefined }), + isLive: async (chatIds) => new Set(chatIds), + designModeOn: async () => true, + broadcast: () => undefined, + focus: (request) => focused.push(request), + newId: () => "page-chat-2", + }); + const entered = enter({ id: "chat-2", title: "New chat", messages: [] }, workspaceRoot); + // The turn places a visual right away. + const placed = placeArtifactsOnCanvas({ + ...canvases.via("chat-2"), + broadcast: () => undefined, + newId: () => "frame-visual", + artifacts: [{ mediaId: "m1", title: "Chart" }], + pendingEntry: () => pending.wait("chat-2"), + }); + await Promise.all([entered, placed]); + const doc = await canvases.workspaceStore.get("ws-1"); + assert.deepEqual(doc.chatPages, { "chat-1": "page-1", "chat-2": "page-chat-2" }); + assert.deepEqual(doc.pages.find((page) => page.id === "page-chat-2"), { id: "page-chat-2", name: "Pricing table", namedFor: "chat-2" }); + assert.equal(doc.frames.find((frame) => frame.id === "frame-visual")?.pageId, "page-chat-2"); + assert.deepEqual(focused.map(({ chatId, pageId }) => [chatId, pageId]), [["chat-2", "page-chat-2"]]); + assert.equal(typeof focused[0]?.focusId, "number"); }); diff --git a/main/services/design-canvas/written-pages.ts b/main/services/design-canvas/written-pages.ts index 3cdba87b9..4b4be617b 100644 --- a/main/services/design-canvas/written-pages.ts +++ b/main/services/design-canvas/written-pages.ts @@ -15,7 +15,18 @@ import * as path from "node:path"; import { canvasView } from "../../../renderer/shared/design-canvas/canvas-summary.js"; import { placeFrame } from "../../../renderer/shared/design-canvas/placement.js"; import { parseProducedFile } from "../../../renderer/shared/produced-file.js"; -import { addPage, canAddPage, deletePage } from "../../../renderer/shared/design-canvas/pages.js"; +import { deletePage } from "../../../renderer/shared/design-canvas/pages.js"; +import { + addChatPage, + chatsOnPage, + ChatPagesFullError, + claimPage, + landedPageId, + withLazyClaim, + chatsOnCanvas, + withoutGoneClaims, + type IsChatLive, +} from "../../../renderer/shared/design-canvas/chat-pages.js"; import { DESIGN_CANVAS_LIMITS, DESIGN_DEFAULT_FILE_WIDTH, @@ -26,6 +37,7 @@ import { type DesignWidth, } from "../../../renderer/shared/design-canvas/schema.js"; import { DESIGN_FRESH_VIEWPORT, type DesignChatView } from "../../../renderer/shared/design-canvas/view.js"; +import { claimWithRoom } from "./lazy-claim.js"; import { resolveDesignFile } from "./resolve-core.js"; import type { DesignCanvasUpdated, DesignChatCanvases } from "./store.js"; import type { DesignTurnPages } from "./views.js"; @@ -348,92 +360,184 @@ export class RecentWrittenPages { } } +/** + * The design-mode entry running for each chat, so a design turn's first + * canvas write waits for entry's claim instead of claiming a page first. + * Memory only. + */ +export class PendingEntries { + private readonly byChat = new Map<string, Promise<unknown>>(); + + /** Remembers `entry` until it settles, and returns it. */ + track<T>(chatId: string, entry: Promise<T>): Promise<T> { + this.byChat.set(chatId, entry); + const clear = () => { + if (this.byChat.get(chatId) === entry) this.byChat.delete(chatId); + }; + entry.then(clear, clear); + return entry; + } + + /** Settles once the chat's running entry has, whether or not it failed. */ + async wait(chatId: string): Promise<void> { + await this.byChat.get(chatId)?.catch(() => undefined); + } +} + const UNCHANGED = Symbol("unchanged"); +/** What design mode's entry decides the chat's page by, read before the canvas update. */ +type EntryRules = { + chatId: string; + /** Names a page made for the chat. */ + pageName: string; + /** The pages other chats' kept views are on. */ + otherViews: ReadonlySet<string>; + isLive: IsChatLive; +}; + +/** The claim, or undefined when the canvas has no room for another chat's page. */ +function tryClaim(claim: () => DesignCanvas): DesignCanvas | undefined { + try { + return claim(); + } catch (error) { + if (error instanceof ChatPagesFullError) return undefined; + throw error; + } +} + /** - * Where design mode's entry puts the chat's earlier pages (A21), and which - * page becomes the chat's. Pages already on the canvas, on any page, are not - * placed again: the chat's page becomes the page holding most of them, and - * only the missing ones go there. Otherwise they go on the chat's page, - * unless the chat has never had a view and that page already holds frames - * (another chat's): then a page named after the chat is added for them, but - * only when at least one page would actually be placed. + * Which page design mode's entry makes the chat's own, and which of its + * earlier pages go there. In order: + * 1. the chat's claim, when it has one, stays; + * 2. else the page holding most of its earlier pages already on the canvas, + * leaving out pages another live chat claims (on a tie the resolved page, + * then the earliest page); + * 3. else the resolved page as it is, when it is not named for another chat, + * no other live chat claims it, and it holds no frames or no other chat's + * kept view is on it; + * 4. else a new page named after the chat, right after the resolved page. At + * the page limit the resolved page is shared instead. + * Pages already on the canvas, on any page, are not placed again; the missing + * ones go on the chat's page. Claims and `namedFor` marks of chats that are + * gone are dropped first, so a gone chat's mark does not keep rule 3 off a page. */ function entryPlacement( doc: DesignCanvas, paths: readonly string[], view: DesignChatView, - entry: { pageName: string; hasView: boolean }, + rules: EntryRules, newId: () => string, -): { doc: DesignCanvas; view: DesignChatView; claim: boolean; missing: string[] } { - const takenOff = new Set(doc.removedPagePaths ?? []); +): { doc: DesignCanvas; view: DesignChatView; missing: string[]; added?: string } { + const base = withoutGoneClaims(doc, rules.isLive); + const takenOff = new Set(base.removedPagePaths ?? []); const holding = new Map<string, number>(); const missing: string[] = []; for (const relativePath of paths) { - const shown = doc.frames.filter((frame) => frame.kind === "file" && frame.path === relativePath); + const shown = base.frames.filter((frame) => frame.kind === "file" && frame.path === relativePath); if (shown.length === 0) { if (!takenOff.has(relativePath)) missing.push(relativePath); continue; } - for (const pageId of new Set(shown.map((frame) => frame.pageId))) holding.set(pageId, (holding.get(pageId) ?? 0) + 1); + for (const pageId of new Set(shown.map((frame) => frame.pageId))) { + // Another live chat's page is not counted: the chat does not take it over. + if (claimedByOther(base, pageId, rules)) continue; + holding.set(pageId, (holding.get(pageId) ?? 0) + 1); + } } const lookAt = (pageId: string): DesignChatView => ({ ...view, pageId, viewport: { ...(pageId === view.pageId ? view.viewport : DESIGN_FRESH_VIEWPORT) }, }); - if (holding.size > 0) { - // The most of them; on a tie the chat's own page, then the earliest page. + const own = base.chatPages[rules.chatId]; + let pageId: string; + if (Object.prototype.hasOwnProperty.call(base.chatPages, rules.chatId) && base.pages.some((page) => page.id === own)) { + pageId = own!; + } else if (holding.size > 0) { const most = Math.max(...holding.values()); - const pageId = - holding.get(view.pageId) === most ? view.pageId : doc.pages.find((page) => holding.get(page.id) === most)!.id; - return { doc, view: lookAt(pageId), claim: !entry.hasView || pageId !== view.pageId, missing }; - } - if (!entry.hasView && missing.length > 0 && framesOnPage(doc, view.pageId).length > 0 && canAddPage(doc)) { - const pageId = newId(); - const name = entry.pageName.trim().slice(0, DESIGN_CANVAS_LIMITS.pageNameChars) || "Chat"; - return { doc: addPage(doc, pageId, name), view: lookAt(pageId), claim: true, missing }; + pageId = holding.get(view.pageId) === most ? view.pageId : base.pages.find((page) => holding.get(page.id) === most)!.id; + } else if (takeAsItIs(base, view.pageId, rules)) { + pageId = view.pageId; + } else { + const id = newId(); + const added = tryClaim(() => addChatPage(base, rules.chatId, rules.pageName, id, view.pageId, rules.isLive)); + if (added && added !== base) return { doc: added, view: lookAt(id), missing, added: id }; + pageId = view.pageId; } - return { doc, view, claim: !entry.hasView, missing }; + const claimed = tryClaim(() => claimPage(base, rules.chatId, pageId, rules.isLive)) ?? base; + return { doc: claimed, view: lookAt(pageId), missing }; +} + +/** Whether another live chat claims the page. */ +function claimedByOther(doc: DesignCanvas, pageId: string, rules: EntryRules): boolean { + return chatsOnPage(doc, pageId, rules.isLive).some((chatId) => chatId !== rules.chatId); +} + +/** Rule 3: the resolved page is not another chat's, by name, claim or what it is looking at. */ +function takeAsItIs(doc: DesignCanvas, pageId: string, rules: EntryRules): boolean { + const page = doc.pages.find((entry) => entry.id === pageId)!; + if (page.namedFor !== undefined && page.namedFor !== rules.chatId) return false; + if (claimedByOther(doc, pageId, rules)) return false; + return framesOnPage(doc, pageId).length === 0 || !rules.otherViews.has(pageId); } /** * Places the pages that still exist and the canvas can show in the chat's * workspace canvas, on the page its turn works on, and tells open canvases. * Saves and announces nothing when every page is already there. Returns the - * new frames' ids, the page they are on and, when entry made a page the - * chat's, main's `focusId` for that page change. + * new frames' ids and the page they are on. Entry also returns the chat's + * page and main's `focusId` for showing it. */ export async function placeWrittenPagesOnCanvas(input: { chatId: string; workspaceRoot: string; paths: readonly string[]; - store: Pick<DesignChatCanvases, "update" | "workspaceIdOf">; + store: Pick<DesignChatCanvases, "get" | "update" | "workspaceIdOf">; /** The turn's page resolver (`designTurnPages`); entry without a message or turn. */ pages: Pick<DesignTurnPages, "resolver" | "show">; broadcast(update: DesignCanvasUpdated): void; newId(): string; /** - * Design mode opening: the chat's earlier pages, placed by `entryPlacement`. - * `pageName` names a page added for them; `hasView` says whether the chat - * has ever had a view of this workspace's canvas. + * Design mode opening: the chat claims its page (`entryPlacement`) and its + * earlier pages go there, even when there are none. `pageName` names a page + * made for the chat; `otherViews` lists the pages other chats' kept views + * are on; `isLive` says which of the claimed chats are live in the workspace. */ - entry?: { pageName: string; hasView(workspaceId: string): Promise<boolean> }; + entry?: { + pageName: string; + otherViews(workspaceId: string): Promise<Set<string>>; + isLive(chatIds: string[], workspaceId: string): Promise<Set<string>>; + }; /** At most this many newest existing pages are placed, in chronological order. */ limit?: number; /** Checked on the canvas's own chain just before the save, so a deleted chat or exited mode is not saved. */ shouldSave?: () => Promise<boolean> | boolean; /** Told the pages left off because the person took them off the canvas. */ onRemoved?: (paths: readonly string[]) => void; + /** + * Settles once a design-mode entry running for this chat has claimed its + * page. A turn's placement waits for it, then claims the turn's page for + * a chat with none, in the same write. Not used with `entry`. + */ + pendingEntry?(): Promise<void>; + /** Which claimed chats are live, asked only when a turn's lazy claim finds `chatPages` full. */ + isLive?(chatIds: string[], workspaceId: string): Promise<Set<string>>; }): Promise<{ frameIds: string[]; pageId?: string; focusId?: number }> { if (input.limit !== undefined && input.limit <= 0) return { frameIds: [] }; // A chat deleted meanwhile has no canvas to put them on. const workspaceId = await input.store.workspaceIdOf(input.chatId); if (workspaceId === null) return { frameIds: [] }; - // Whether the chat had a view is read before the files are, so the canvas - // this entry is opening cannot report one first and send these pages onto - // another chat's page. - const entryHasView = input.entry ? await input.entry.hasView(workspaceId) : undefined; + let rules: EntryRules | undefined; + if (input.entry) { + const otherViews = await input.entry.otherViews(workspaceId); + const { doc: current } = await input.store.get(input.chatId, { workspaceId }); + const checked = new Set(chatsOnCanvas(current).filter((chatId) => chatId !== input.chatId)); + const live = await input.entry.isLive([...checked], workspaceId); + // A claim made after this check is a live chat's. + const isLive: IsChatLive = (chatId) => !checked.has(chatId) || live.has(chatId); + rules = { chatId: input.chatId, pageName: input.entry.pageName, otherViews, isLive }; + } const newestFirst: string[] = []; const widths = new Map<string, DesignWidth>(); const seen = new Set<string>(); @@ -453,24 +557,31 @@ export async function placeWrittenPagesOnCanvas(input: { } } const showable = newestFirst.reverse(); - if (showable.length === 0) return { frameIds: [] }; + // Entry claims a page even when the chat wrote none. + if (showable.length === 0 && !rules) return { frameIds: [] }; + if (!rules) await input.pendingEntry?.(); const viewOf = await input.pages.resolver(workspaceId); - const entry = input.entry ? { pageName: input.entry.pageName, hasView: entryHasView! } : undefined; - const shouldSave = input.shouldSave; + // Asked on the canvas's chain before the write, and again after it: the + // chat must still be in design mode, if the caller asks that, and still in + // this workspace. A chat that moved while this ran writes nothing back to the + // canvas it left, whose cleanup may already have run. + const callerAllows = input.shouldSave; + const shouldSave = async (): Promise<boolean> => + (await input.store.workspaceIdOf(input.chatId)) === workspaceId && (!callerAllows || (await callerAllows())); let placedIds: string[] = []; let removed: string[] = []; let pageId: string | undefined; - // The page entry makes the chat's, shown once the canvas is settled. - let claimed: string | undefined; - let addedPage = false; // The page entry added in the save that landed, so taking the frames back also takes it. let addedPageId: string | undefined; + let refused = false; + let landed: string | undefined; // Reported whether or not anything was saved, once the canvas has been read. const reportRemoved = () => { if (removed.length > 0) input.onRemoved?.(removed); }; - const claim = async (): Promise<number | undefined> => - claimed === undefined ? undefined : await input.pages.show(workspaceId, claimed); + // Entry always shows the chat's page, so the view and the open canvas move to it. + const show = async (): Promise<number | undefined> => + rules && pageId !== undefined ? await input.pages.show(workspaceId, pageId) : undefined; try { const { doc: saved } = await input.store.update( input.chatId, @@ -478,56 +589,64 @@ export async function placeWrittenPagesOnCanvas(input: { let view = viewOf(doc); let base = doc; let paths: readonly string[] = showable; - if (entry) { - const placement = entryPlacement(doc, showable, view, entry, input.newId); + addedPageId = undefined; + if (rules) { + const placement = entryPlacement(doc, showable, view, rules, input.newId); base = placement.doc; view = placement.view; paths = placement.missing; - // A page added for them exists only if the save lands, so it is claimed only then. - if (placement.claim) claimed = view.pageId; - addedPage = placement.doc !== doc; - addedPageId = addedPage ? view.pageId : undefined; + addedPageId = placement.added; } pageId = view.pageId; const placed = placeWrittenPageFrames(base, paths, input.newId, widths, view); removed = placed.removed; - if (!placed.changed) throw UNCHANGED; + if (placed.doc === doc) throw UNCHANGED; placedIds = placed.placedIds; - return placed.doc; + // A turn's placement claims the page it landed on for a chat with none; entry has claimed already. + if (rules) return placed.doc; + landed = landedPageId(doc, placed.doc, view.pageId); + return withLazyClaim(placed.doc, input.chatId, landed); }, { workspaceId, - // Leaving design mode (or deleting the chat) while this waited keeps the frames off the stored canvas. - ...(shouldSave - ? { - beforeWrite: async () => { - if (!(await shouldSave())) { - removed = []; - claimed = undefined; - throw UNCHANGED; - } - }, - } - : {}), + // Leaving design mode, deleting the chat or moving it while this waited keeps the frames off the stored canvas. + beforeWrite: async () => { + if (!(await shouldSave())) { + removed = []; + refused = true; + throw UNCHANGED; + } + }, }, ); // The mode can still turn off while the file is being written. Then the // frames are taken back off, unless the person changed the canvas since // or design mode is on again by the time that runs. - if (shouldSave && !(await shouldSave())) { - await retractPlacedFrames(input, workspaceId, saved.revision, placedIds, shouldSave, addedPageId); + if (!(await shouldSave())) { + if (placedIds.length > 0 || addedPageId !== undefined) { + await retractPlacedFrames(input, workspaceId, saved.revision, placedIds, shouldSave, addedPageId); + } return { frameIds: [] }; } input.broadcast({ workspaceId, chatId: input.chatId, revision: saved.revision }); + await claimWithRoom({ + chatId: input.chatId, + workspaceId, + pageId: landed, + saved, + store: input.store, + isLive: input.isLive, + broadcast: input.broadcast, + }); reportRemoved(); - const focusId = await claim(); + const focusId = await show(); return { frameIds: placedIds, ...(pageId ? { pageId } : {}), ...(focusId !== undefined ? { focusId } : {}) }; } catch (error) { if (error === UNCHANGED) { reportRemoved(); - if (addedPage) claimed = undefined; - const focusId = await claim(); - return { frameIds: [], ...(claimed && pageId ? { pageId } : {}), ...(focusId !== undefined ? { focusId } : {}) }; + if (!rules || refused || !(await shouldSave())) return { frameIds: [] }; + const focusId = await show(); + return { frameIds: [], ...(pageId ? { pageId } : {}), ...(focusId !== undefined ? { focusId } : {}) }; } throw error; } @@ -551,9 +670,12 @@ async function retractPlacedFrames( const frames = doc.frames.filter((frame) => !placed.has(frame.id)); const dropPage = addedPageId !== undefined && doc.pages.length > 1 && !frames.some((frame) => frame.pageId === addedPageId); - return dropPage - ? deletePage({ ...doc, frames }, addedPageId) - : { ...doc, frames }; + if (!dropPage) return { ...doc, frames }; + // The claim on the added page goes with it, rather than moving to the first page. + const chatPages = Object.fromEntries( + Object.entries(doc.chatPages).filter(([chatId, pageId]) => chatId !== input.chatId || pageId !== addedPageId), + ); + return deletePage({ ...doc, frames, chatPages }, addedPageId); }, { workspaceId, diff --git a/main/services/llm-client.ts b/main/services/llm-client.ts index 4f35e064c..10c80b57f 100644 --- a/main/services/llm-client.ts +++ b/main/services/llm-client.ts @@ -585,7 +585,9 @@ import { designCanvasStore, designCanvasViews, designGrants, + designLiveChats, designModeConsent, + designPendingEntries, designSystemOffers, recentWrittenPages, } from "./design-canvas/main.js"; @@ -1998,13 +2000,16 @@ async function prepareGeneration( * The canvas page this turn works on, one resolver for the whole turn: the * canvas tools, pages and images placed by themselves, and the canvas status * line all read the page the same way (a page Aiden showed this turn, the - * page the message came from, the chat's kept page, the first page). + * page the message came from, the chat's kept page, the chat's own page, + * the first page). */ const designPages = designTurnPages({ views: designCanvasViews, chatId: params.chatId, ...(params.designView ? { message: params.designView } : {}), }); + /** The turn's canvas writes wait for a design-mode entry still claiming this chat's page. */ + const designPendingEntry = () => designPendingEntries.wait(params.chatId); /** Asks the window showing the chat's canvas to show a page and fit these frames. */ const focusDesignCanvas = (request: { pageId: string; frameIds: readonly string[]; focusId?: number }) => { const liveOwner = getOwner(); @@ -2739,6 +2744,8 @@ async function prepareGeneration( pages: designPages, broadcast: announceCanvasChange, newId: randomUUID, + pendingEntry: designPendingEntry, + isLive: designLiveChats, }); if (placed === null) return null; if (placed.frameIds.length > 0) focusDesignCanvas(placed); @@ -2994,6 +3001,8 @@ async function prepareGeneration( store: designCanvasStore, broadcast: announceCanvasChange, pages: designPages, + isLive: designLiveChats, + pendingEntry: designPendingEntry, focus: focusDesignCanvas, snapshot: async (toolSignal) => supportsImages @@ -3029,6 +3038,8 @@ async function prepareGeneration( pages: designPages, broadcast: announceCanvasChange, newId: randomUUID, + pendingEntry: designPendingEntry, + isLive: designLiveChats, }); }; } @@ -3134,6 +3145,8 @@ async function prepareGeneration( pages: designPages, broadcast: announceCanvasChange, newId: randomUUID, + pendingEntry: designPendingEntry, + isLive: designLiveChats, onRemoved: () => { leftOff = true; }, diff --git a/package.json b/package.json index 96a59b42a..8e32f4897 100644 --- a/package.json +++ b/package.json @@ -270,7 +270,7 @@ "test:bot-allowed": "tsx --test main/services/bot-runtime/bot-approval-tallies.test.ts main/services/bot-runtime/bot-allow-target.test.ts main/services/bot-runtime/bot-approvals.test.ts main/services/bot-runtime/bot-allow-list.test.ts main/handlers/bot-allowed.test.ts", "pretest:bot-plans": "npm run build:lease-flock && npm run build:subagent-file-mutator", "test:bot-plans": "tsx --test renderer/shared/bot-plans.test.ts main/services/bot-plans/validate.test.ts main/services/bot-plans/plans.test.ts main/services/bot-plans/authority.test.ts main/services/bot-runtime/bot-plan-tools.test.ts main/handlers/bot-plans.test.ts main/services/bot-plans/lifecycle.test.ts renderer/components/bots/plan-card.test.tsx", - "test:design-mode": "tsx --test renderer/lib/design-mode.test.tsx main/windows/design-window-core.test.ts renderer/design/design-layout.test.tsx renderer/components/chat-sidebar-scope.test.tsx renderer/components/chat-top-bar-design.test.tsx renderer/shared/design-canvas/schema.test.ts renderer/shared/design-canvas/view.test.ts main/services/design-canvas/store.test.ts main/services/design-canvas/views.test.ts main/services/design-canvas/carry.test.ts renderer/design/canvas-focus-requests.test.ts main/handlers/design-canvas.test.ts main/services/design-canvas/resolve-core.test.ts main/services/design-canvas/grants.test.ts main/services/design-canvas/protocol.test.ts main/services/design-canvas/zoom-gate.test.ts renderer/design/canvas-adapter-core.test.ts renderer/design/canvas-history-core.test.ts renderer/design/canvas-keymap-core.test.ts renderer/design/use-design-canvas.test.tsx renderer/design/use-design-view.test.tsx renderer/design/design-canvas-region.test.tsx renderer/design/live-set-core.test.ts renderer/design/frame-snapshots.test.ts main/services/design-canvas/watch.test.ts renderer/design/nodes/file-node.test.tsx renderer/design/design-canvas.test.tsx renderer/shared/design-canvas/canvas-summary.test.ts renderer/shared/design-canvas/pages.test.ts renderer/shared/design-canvas/comments.test.ts renderer/shared/design-canvas/connectors.test.ts renderer/shared/design-canvas/drawing.test.ts renderer/shared/design-canvas/rich-text.test.ts renderer/design/rich-text-dom.test.ts renderer/shared/design-canvas/frame-export.test.ts renderer/design/layers-core.test.ts renderer/shared/design-canvas/tweaks.test.ts renderer/shared/design-canvas/text-edit.test.ts renderer/design/comment-geometry.test.ts main/services/design-canvas/bridge-source.test.ts main/services/design-canvas/canvas-tools.test.ts main/services/design-canvas/inspect.test.ts main/services/design-canvas/frame-navigation.test.ts main/services/design-canvas/text-write.test.ts main/services/close-guard-prompt.test.ts main/services/design-canvas/artifact-frames.test.ts main/services/design-canvas/written-pages.test.ts main/services/design-canvas/skill.test.ts main/services/design-canvas/design-system.test.ts main/services/design-canvas/design-system-offers.test.ts main/services/design-canvas/design-mode-tool.test.ts main/services/design-canvas/canvas-snapshots.test.ts renderer/design/design-mode-consent.test.tsx renderer/design/tweak-versions.test.ts renderer/design/design-tweaks-panel.test.tsx renderer/design/design-side-panel-layers.test.tsx" + "test:design-mode": "tsx --test renderer/lib/design-mode.test.tsx main/windows/design-window-core.test.ts renderer/design/design-layout.test.tsx renderer/components/chat-sidebar-scope.test.tsx renderer/components/chat-top-bar-design.test.tsx renderer/shared/design-canvas/schema.test.ts renderer/shared/design-canvas/view.test.ts main/services/design-canvas/store.test.ts main/services/design-canvas/views.test.ts main/services/design-canvas/title-follow.test.ts main/services/design-canvas/liveness.test.ts main/services/design-canvas/carry.test.ts renderer/design/canvas-focus-requests.test.ts main/handlers/design-canvas.test.ts main/services/design-canvas/resolve-core.test.ts main/services/design-canvas/grants.test.ts main/services/design-canvas/protocol.test.ts main/services/design-canvas/zoom-gate.test.ts renderer/design/canvas-adapter-core.test.ts renderer/design/canvas-history-core.test.ts renderer/design/canvas-keymap-core.test.ts renderer/design/use-design-canvas.test.tsx renderer/design/use-design-view.test.tsx renderer/design/design-canvas-region.test.tsx renderer/design/live-set-core.test.ts renderer/design/frame-snapshots.test.ts main/services/design-canvas/watch.test.ts renderer/design/nodes/file-node.test.tsx renderer/design/design-canvas.test.tsx renderer/shared/design-canvas/canvas-summary.test.ts renderer/shared/design-canvas/pages.test.ts renderer/shared/design-canvas/chat-pages.test.ts renderer/shared/design-canvas/comments.test.ts renderer/shared/design-canvas/connectors.test.ts renderer/shared/design-canvas/drawing.test.ts renderer/shared/design-canvas/rich-text.test.ts renderer/design/rich-text-dom.test.ts renderer/shared/design-canvas/frame-export.test.ts renderer/design/layers-core.test.ts renderer/shared/design-canvas/tweaks.test.ts renderer/shared/design-canvas/text-edit.test.ts renderer/design/comment-geometry.test.ts main/services/design-canvas/bridge-source.test.ts main/services/design-canvas/canvas-tools.test.ts main/services/design-canvas/inspect.test.ts main/services/design-canvas/frame-navigation.test.ts main/services/design-canvas/text-write.test.ts main/services/close-guard-prompt.test.ts main/services/design-canvas/artifact-frames.test.ts main/services/design-canvas/written-pages.test.ts main/services/design-canvas/skill.test.ts main/services/design-canvas/design-system.test.ts main/services/design-canvas/design-system-offers.test.ts main/services/design-canvas/design-mode-tool.test.ts main/services/design-canvas/canvas-snapshots.test.ts renderer/design/design-mode-consent.test.tsx renderer/design/tweak-versions.test.ts renderer/design/design-tweaks-panel.test.tsx renderer/design/design-side-panel-layers.test.tsx" }, "dependencies": { "@agentclientprotocol/sdk": "1.7.0", diff --git a/renderer/design/canvas-history-core.test.ts b/renderer/design/canvas-history-core.test.ts index c2245bbaa..9fcf559cc 100644 --- a/renderer/design/canvas-history-core.test.ts +++ b/renderer/design/canvas-history-core.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { emptyDesignCanvas, type DesignCanvas } from "../shared/design-canvas/schema"; +import { DESIGN_CANVAS_LIMITS, emptyDesignCanvas, type DesignCanvas } from "../shared/design-canvas/schema"; import { addPage, deletePage, movePage, renamePage } from "../shared/design-canvas/pages"; import { changesBetween, keepUnchanged, record, redo, takeIn, undo, type CanvasHistory } from "./canvas-history-core"; @@ -70,14 +70,61 @@ test("undoing a frame move keeps a page rename another chat made meanwhile", () assert.deepEqual(kept, { ...renamedElsewhere, frames: two.frames }); }); -test("undoing a page edit takes the pages back whole, and drops chat pages that point at a page gone", () => { +test("undoing a page edit puts the pages back, and a chat on a page the undo removes moves to the first page", () => { const two: DesignCanvas = { ...addPage(state("a"), "p2"), chatPages: { "chat-1": "p2" } }; const reordered = movePage(two, "p2", -1); assert.deepEqual(changesBetween(reordered, two)(reordered).pages.map((page) => page.id), ["page-1", "p2"]); - // Undoing the add of p2 takes it away again, and the chat that used it no longer names it. - const withoutP2 = changesBetween(two, state("a"))(two); + // Undoing the add of p2 takes it away again; the claim that the step did not make is the doc's to keep. + const withoutP2 = changesBetween(two, { ...state("a"), chatPages: { "chat-1": "p2" } })({ ...two, chatPages: { "chat-1": "p2", "chat-2": "p2" } }); assert.deepEqual(withoutP2.pages.map((page) => page.id), ["page-1"]); - assert.deepEqual(withoutP2.chatPages, {}); + assert.deepEqual(withoutP2.chatPages, { "chat-1": "page-1", "chat-2": "page-1" }); +}); + +const pageIds = (doc: DesignCanvas | undefined) => doc?.pages.map((page) => page.id); + +test("a page another writer adds or renames does not stop an undo from bringing back a deleted page, its frames and its comments", () => { + const three = addPage(addPage(state("kept"), "P", "Pricing"), "Q", "Plans"); + const before: DesignCanvas = { + ...three, + frames: [...three.frames, { ...three.frames[0]!, id: "on-p", pageId: "P" }], + comments: [ + { id: "c", pageId: "P", frameId: "on-p", x: 0, y: 0, note: "c", state: "open", anchorState: "anchored", createdAt: "2026-11-23T10:00:00.000Z" }, + ], + }; + const deleted = deletePage(before, "P"); + let history = record(fresh, before); + // A store update from another writer adds R and renames Q while the delete is on screen. + const elsewhere = keepUnchanged(deleted, renamePage(addPage(deleted, "R", "Roadmap"), "Q", "Tiers")); + history = takeIn(history, { before: deleted, from: deleted, to: elsewhere }); + const back = undo(history, elsewhere)!; + assert.deepEqual(pageIds(back.doc), ["page-1", "P", "Q", "R"], "P is back in its old place among the shared pages"); + assert.equal(back.doc.pages.find((page) => page.id === "Q")?.name, "Tiers"); + assert.deepEqual(back.doc.frames.map((frame) => frame.id).sort(), ["kept", "on-p"]); + assert.deepEqual(back.doc.comments.map((entry) => entry.id), ["c"]); +}); + +test("a claim another writer made reaches every kept step, so undoing a page delete brings back the current claim", () => { + const before: DesignCanvas = { ...addPage(addPage(state("a"), "P"), "Q"), chatPages: { B: "P" } }; + const deleted = deletePage(before, "P"); + let history = record(fresh, before); + const claimed: DesignCanvas = { ...deleted, chatPages: { B: "Q" } }; + history = takeIn(history, { before: deleted, from: deleted, to: claimed }); + const back = undo(history, claimed)!; + assert.deepEqual(pageIds(back.doc), ["page-1", "P", "Q"]); + assert.equal(back.doc.chatPages.B, "Q"); +}); + +test("a page that exists only in an older step stays in that step after a carry", () => { + const from = state("a"); + const to = addPage(from, "R", "Roadmap"); + const step = addPage(from, "X", "Mine"); + const carried = changesBetween(from, to)(step); + assert.deepEqual(pageIds(carried), ["page-1", "R", "X"]); + // A brought-back page whose predecessor is gone goes after the nearest earlier page that exists. + const wide = addPage(addPage(addPage(state("a"), "P1"), "P2"), "P3"); + const narrowed = deletePage(deletePage(wide, "P1"), "P2"); + const restored = changesBetween(narrowed, wide)(deletePage(narrowed, "page-1")); + assert.deepEqual(pageIds(restored), ["P1", "P2", "P3"]); }); test("undoing a comment edit keeps comments someone else changed, and a comment goes with its frame", () => { @@ -141,3 +188,41 @@ test("a fetched canvas keeps the objects of frames that did not change, so undo const carried = changesBetween(local, merged)(withFrames(note("a", 50), note("b"))); assert.deepEqual(carried.frames.map((frame) => [frame.id, frame.x]), [["a", 50], ["b", 300]]); }); + +test("a carry that only drops namedFor keeps the rename a redo step holds", () => { + const base: DesignCanvas = { ...emptyDesignCanvas(), pages: [{ id: "page-1", name: "Page 1" }, { id: "P", name: "Chat A", namedFor: "chat-a" }] }; + const renamed = renamePage(base, "P", "Bar"); + const back = undo(record(fresh, base), renamed)!; + // The undo's save answers that the store keeps no namedFor on P. + const stored: DesignCanvas = { ...base, pages: [base.pages[0]!, { id: "P", name: "Chat A" }] }; + const history = takeIn(back.history, { before: back.doc, from: back.doc, to: stored }); + const forward = redo(history, stored)!; + assert.deepEqual(forward.doc.pages[1], { id: "P", name: "Bar" }); +}); + +test("a carry never takes a step past the page limit: pages only the step has go first", () => { + let full: DesignCanvas = emptyDesignCanvas(); + for (let index = 2; index <= DESIGN_CANVAS_LIMITS.pages; index += 1) full = addPage(full, `p${index}`, `P${index}`); + const deleted = deletePage(full, "p100"); + let history = record(fresh, full); + // Another chat's reply adds R and makes it that chat's page. + const other: DesignCanvas = { ...addPage(deleted, "R", "Roadmap"), chatPages: { "chat-b": "R" } }; + history = takeIn(history, { before: deleted, from: deleted, to: keepUnchanged(deleted, other) }); + const back = undo(history, other)!; + assert.equal(back.doc.pages.length, DESIGN_CANVAS_LIMITS.pages); + assert.ok(back.doc.pages.some((page) => page.id === "R"), "the other chat's page survives the undo"); + assert.equal(back.doc.chatPages["chat-b"], "R"); +}); + +test("a frame only an older step has, on a page another writer deleted, does not come back on another page", () => { + const two = addPage(emptyDesignCanvas(), "Q", "Q"); + const withG: DesignCanvas = { ...two, frames: [{ ...note("G"), pageId: "Q" }] }; + const withoutG: DesignCanvas = { ...two, frames: [] }; + let history = record(fresh, withG); + const other = deletePage(withoutG, "Q"); + history = takeIn(history, { before: withoutG, from: withoutG, to: keepUnchanged(withoutG, other) }); + const back = undo(history, other)!; + assert.deepEqual(back.doc.pages.map((page) => page.id), ["page-1"]); + assert.deepEqual(back.doc.frames, []); +}); + diff --git a/renderer/design/canvas-history-core.ts b/renderer/design/canvas-history-core.ts index b94a0c9c6..d6e0b2608 100644 --- a/renderer/design/canvas-history-core.ts +++ b/renderer/design/canvas-history-core.ts @@ -1,7 +1,7 @@ // Undo and redo for the design canvas: whole documents, newest last. Pure, so // the hook can keep the history in React state and tests need no DOM. -import type { DesignCanvas } from "../shared/design-canvas/schema"; +import { DESIGN_CANVAS_LIMITS, type DesignCanvas, type DesignPage } from "../shared/design-canvas/schema"; export interface CanvasHistory { past: DesignCanvas[]; @@ -105,10 +105,11 @@ export function keepUnchanged(from: DesignCanvas, to: DesignCanvas): DesignCanva * different canvas: it adds, removes and replaces only the frames and * comments that differ between the two, so ones someone else changed in the * meantime are kept. Comments whose frame or page is gone go with it. - * Pages (names and order) are taken whole when the edit changed them, and a - * chat's page that is gone is forgotten. Which page anyone looks at is not - * in the document, so an undo never moves anyone's view. Run on `from` - * itself it gives exactly `to`. + * Pages change item by item too (`pageChanges`), and so do chats' own pages: + * the claims the edit added, moved or removed are applied, and a claim whose + * page is gone moves to the first page. Which page anyone looks at is not in + * the document, so an undo never moves anyone's view. Run on `from` itself it + * gives exactly `to`. */ export function changesBetween( from: DesignCanvas, @@ -116,16 +117,16 @@ export function changesBetween( ): (doc: DesignCanvas) => DesignCanvas { const frameEdit = itemChanges(from.frames, to.frames); const commentEdit = itemChanges(from.comments, to.comments); - const outline = (doc: DesignCanvas) => JSON.stringify(doc.pages.map((page) => [page.id, page.name])); - const pagesChanged = outline(from) !== outline(to); + const pageEdit = pageChanges(from.pages, to.pages); + const claimEdit = claimChanges(from.chatPages, to.chatPages); return (doc) => { if (doc === from) return to; - const frames = frameEdit(doc.frames); - const pages = pagesChanged ? to.pages : doc.pages; + const pages = pageEdit(doc.pages); const pageIds = new Set(pages.map((page) => page.id)); - const chatPages = Object.values(doc.chatPages).every((pageId) => pageIds.has(pageId)) - ? doc.chatPages - : Object.fromEntries(Object.entries(doc.chatPages).filter(([, pageId]) => pageIds.has(pageId))); + // A frame left on a page that is gone goes with it, as comments do. + const edited = frameEdit(doc.frames); + const frames = edited.every((frame) => pageIds.has(frame.pageId)) ? edited : edited.filter((frame) => pageIds.has(frame.pageId)); + const chatPages = claimEdit(doc.chatPages, pageIds, pages[0]!.id); const framePages = new Map(frames.map((frame) => [frame.id, frame.pageId])); const comments = commentEdit(doc.comments).flatMap((comment) => { if (comment.frameId === undefined) return pageIds.has(comment.pageId) ? [comment] : []; @@ -137,6 +138,90 @@ export function changesBetween( }; } +/** + * The page edit that turns `from` into `to`, run on another page list: the + * pages `to` removed go, renames and `namedFor` changes apply, a page `to` + * added goes after the nearest page before it in `to` that is there (first + * when none is), and pages only the other list has stay. A page's name and + * `namedFor` each change only when the edit changed that field. When the + * edit reordered pages, the pages both lists share take `to`'s order among + * the places they hold. Past the page limit, pages `to` lacks are dropped. + */ +function pageChanges(from: readonly DesignPage[], to: readonly DesignPage[]): (pages: readonly DesignPage[]) => DesignPage[] { + const before = new Map(from.map((page) => [page.id, page])); + const after = new Map(to.map((page) => [page.id, page])); + const sharedOrder = (list: readonly DesignPage[]) => + list.filter((page) => before.has(page.id) && after.has(page.id)).map((page) => page.id); + const reordered = sharedOrder(from).join("\n") !== sharedOrder(to).join("\n"); + return (pages) => { + let next = pages.flatMap((page): DesignPage[] => { + const was = before.get(page.id); + if (!was) return [page]; + const now = after.get(page.id); + if (!now) return []; + // Each field the edit changed, and only those, so a step's own rename stays. + let changed = page; + if (was.name !== now.name) changed = { ...changed, name: now.name }; + if (was.namedFor !== now.namedFor) { + const { namedFor: _namedFor, ...rest } = changed; + changed = now.namedFor === undefined ? rest : { ...rest, namedFor: now.namedFor }; + } + return [changed]; + }); + if (reordered) { + const order = new Map(to.map((page, index) => [page.id, index])); + const ordered = next.filter((page) => before.has(page.id) && order.has(page.id)); + ordered.sort((a, b) => order.get(a.id)! - order.get(b.id)!); + let at = 0; + next = next.map((page) => (before.has(page.id) && order.has(page.id) ? ordered[at++]! : page)); + } + for (const [index, page] of to.entries()) { + if (before.has(page.id) || next.some((entry) => entry.id === page.id)) continue; + let place = 0; + for (let earlier = index - 1; earlier >= 0; earlier -= 1) { + const found = next.findIndex((entry) => entry.id === to[earlier]!.id); + if (found >= 0) { + place = found + 1; + break; + } + } + next = [...next.slice(0, place), page, ...next.slice(place)]; + } + // Past the page limit, pages only the step has go first, newest first, so + // parsing never drops a page someone else added. + const inTo = new Set(to.map((page) => page.id)); + for (let at = next.length - 1; at >= 0 && next.length > DESIGN_CANVAS_LIMITS.pages; at -= 1) { + if (!inTo.has(next[at]!.id)) next = [...next.slice(0, at), ...next.slice(at + 1)]; + } + return next.length > 0 ? next : [...to]; + }; +} + +/** + * The claims the edit added, moved or removed, applied to another set; a + * claim left on a page that is gone moves to `first`. + */ +function claimChanges( + from: Record<string, string>, + to: Record<string, string>, +): (chatPages: Record<string, string>, pageIds: ReadonlySet<string>, first: string) => Record<string, string> { + const own = (map: Record<string, string>, key: string) => + Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined; + const changed = [...new Set([...Object.keys(from), ...Object.keys(to)])].filter((chatId) => own(from, chatId) !== own(to, chatId)); + return (chatPages, pageIds, first) => { + const stale = Object.values(chatPages).some((pageId) => !pageIds.has(pageId)); + if (changed.length === 0 && !stale) return chatPages; + const next: Record<string, string> = { ...chatPages }; + for (const chatId of changed) { + const pageId = own(to, chatId); + if (pageId === undefined) delete next[chatId]; + else next[chatId] = pageId; + } + for (const [chatId, pageId] of Object.entries(next)) if (!pageIds.has(pageId)) next[chatId] = first; + return next; + }; +} + /** Adds, removes and replaces only the items (by id) that differ between `from` and `to`. */ function itemChanges<T extends { id: string }>(from: readonly T[], to: readonly T[]): (items: readonly T[]) => T[] { const before = new Map(from.map((item) => [item.id, item])); diff --git a/renderer/design/design-canvas.test.tsx b/renderer/design/design-canvas.test.tsx index 7e459cf08..8d3212862 100644 --- a/renderer/design/design-canvas.test.tsx +++ b/renderer/design/design-canvas.test.tsx @@ -633,6 +633,61 @@ test("when another chat deletes the page on screen, the canvas goes back to the assert.ok(screen.getByRole("button", { name: "Page: Home" })); }); +test("when another chat deletes the page on screen, the canvas shows this chat's claim", async () => { + const base = twoPageCanvas(); + let doc: DesignCanvas = { + ...base, + pages: [...base.pages, { id: "p3", name: "Ideas" }], + frames: [...base.frames, sticky("n3", "On ideas", "p3")], + chatPages: { "chat-1": "p3" }, + }; + setup(doc, { "designCanvas:get": () => doc }); + await mount(); + assert.ok(screen.getByRole("button", { name: "Page: Ideas" }), "with no kept view, the canvas opens on the claim"); + await choosePageItem("Pricing", "menuitemradio"); + assert.ok(await screen.findByRole("group", { name: "On pricing" })); + + doc = { ...doc, revision: doc.revision + 1, pages: doc.pages.filter((page) => page.id !== "p2"), frames: doc.frames.filter((frame) => frame.pageId !== "p2") }; + act(() => emitBotTestNotification("designCanvas:updated", { workspaceId: "workspace-1", chatId: "chat-2", revision: doc.revision })); + assert.ok(await screen.findByRole("group", { name: "On ideas" }, SAVE_WAIT)); + assert.ok(screen.getByRole("button", { name: "Page: Ideas" })); +}); + +test("the page picker marks this chat's page and counts other chats on theirs", async () => { + const doc: DesignCanvas = { + ...canvasWith(), + pages: [ + { id: "page-1", name: "Home" }, + { id: "p2", name: "Pricing" }, + { id: "p3", name: "Ideas" }, + { id: "p4", name: "Shared" }, + { id: "p5", name: "Empty" }, + ], + chatPages: { "chat-1": "p4", "chat-2": "page-1", "chat-3": "p2", "chat-4": "p2", "chat-5": "p4", "chat-6": "p4" }, + }; + setup(doc); + await mount(); + const trigger = screen.getByRole("button", { name: /^Page: / }); + assert.equal(trigger.getAttribute("aria-label"), "Page: Shared", "the trigger names only the page"); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: "mouse" }); + await screen.findByRole("menuitemradio", { name: /^Home/u }); + assert.deepEqual( + screen.getAllByRole("menuitemradio").map((row) => row.getAttribute("aria-label") ?? row.textContent), + ["Home, 1 chat", "Pricing, 2 chats", "Ideas", "Shared, This chat · 2 more", "Empty"], + ); + for (const name of ["Home, 1 chat", "Pricing, 2 chats", "Ideas", "Shared, This chat · 2 more"]) { + assert.ok(screen.getByRole("menuitemradio", { name }), name); + } + assert.equal(screen.queryByText(/chat-\d/u), null, "no other chat is named"); +}); + +test("the page picker reads This chat on a page only this chat uses", async () => { + setup({ ...twoPageCanvas(), chatPages: { "chat-1": "p2" } }); + await mount(); + await choosePageItem("Pricing, This chat", "menuitemradio"); + assert.ok(await screen.findByRole("button", { name: "Page: Pricing" }), "choosing the marked row still shows the page"); +}); + test("a new page starts empty and is shown; deleting it can be undone from the toast", async () => { const { saved } = setup(canvasWith(sticky("n1", "On home"))); render(<Toaster />); diff --git a/renderer/design/design-canvas.tsx b/renderer/design/design-canvas.tsx index aa0532d9f..345f070e6 100644 --- a/renderer/design/design-canvas.tsx +++ b/renderer/design/design-canvas.tsx @@ -1335,6 +1335,7 @@ function LoadedDesignCanvas({ toolbar={ <DesignToolbar doc={doc} + chatId={chatId} pageId={pageId} tool={tool} onToolChange={changeTool} diff --git a/renderer/design/design-toolbar.tsx b/renderer/design/design-toolbar.tsx index 7e2268495..944c2c8a0 100644 --- a/renderer/design/design-toolbar.tsx +++ b/renderer/design/design-toolbar.tsx @@ -34,6 +34,7 @@ import { DropdownMenuTrigger, Input, } from "../components/ui"; +import { chatsOnPage } from "../shared/design-canvas/chat-pages"; import { canAddPage } from "../shared/design-canvas/pages"; import { prettyAccelerator } from "../shared/keybindings"; import { DESIGN_DRAW_SHORTCUTS } from "./canvas-keymap-core"; @@ -77,6 +78,7 @@ const DRAW_MENU: readonly DesignDrawTool[] = ["pencil", "pen"]; export function DesignToolbar({ doc, + chatId, pageId, tool, onToolChange, @@ -90,6 +92,8 @@ export function DesignToolbar({ onDraw, }: { doc: DesignCanvas; + /** The chat whose canvas this is; the page picker marks its own page. */ + chatId: string; /** The page on screen, from the chat's view. */ pageId: string; tool: CanvasTool; @@ -113,7 +117,7 @@ export function DesignToolbar({ aria-label="Canvas tools" className="glass-surface nodrag flex max-w-full flex-wrap items-center gap-0.5 rounded-button p-1 shadow-control" > - <DesignPageMenu doc={doc} pageId={pageId} onPage={onPage} /> + <DesignPageMenu doc={doc} chatId={chatId} pageId={pageId} onPage={onPage} /> <div aria-hidden className="mx-1 h-4 w-px shrink-0 bg-separator" /> {TOOLS.map(({ tool: item, label, Icon }) => { const shortcut = CANVAS_TOOL_SHORTCUTS[item]; @@ -276,8 +280,31 @@ function DrawToolMenu({ ); } -/** The page picker: every page, and what can be done to the one on screen. */ -function DesignPageMenu({ doc, pageId, onPage }: { doc: DesignCanvas; pageId: string; onPage(action: DesignPageAction): void }) { +/** + * Which chats use a page as their own, by count only (never a title or id): + * "This chat", "This chat · N more", "1 chat", "N chats", or nothing. + */ +function pageChatsLabel(doc: DesignCanvas, pageId: string, chatId: string): string | undefined { + const chats = chatsOnPage(doc, pageId); + const mine = chats.includes(chatId); + const others = chats.length - (mine ? 1 : 0); + if (mine) return others > 0 ? `This chat · ${others} more` : "This chat"; + if (others === 0) return undefined; + return others === 1 ? "1 chat" : `${others} chats`; +} + +/** The page picker: every page with the chats that use it, and what can be done to the one on screen. */ +function DesignPageMenu({ + doc, + chatId, + pageId, + onPage, +}: { + doc: DesignCanvas; + chatId: string; + pageId: string; + onPage(action: DesignPageAction): void; +}) { const page = doc.pages.find((entry) => entry.id === pageId) ?? doc.pages[0]!; const at = doc.pages.indexOf(page); const [renaming, setRenaming] = React.useState(false); @@ -312,11 +339,24 @@ function DesignPageMenu({ doc, pageId, onPage }: { doc: DesignCanvas; pageId: st > <DropdownMenuLabel>Pages</DropdownMenuLabel> <DropdownMenuRadioGroup value={page.id} onValueChange={(id) => onPage({ type: "show", id })}> - {doc.pages.map((entry) => ( - <DropdownMenuRadioItem key={entry.id} value={entry.id}> - <span className="min-w-0 truncate">{entry.name}</span> - </DropdownMenuRadioItem> - ))} + {doc.pages.map((entry) => { + const chats = pageChatsLabel(doc, entry.id, chatId); + return ( + <DropdownMenuRadioItem + key={entry.id} + value={entry.id} + textValue={entry.name} + aria-label={chats === undefined ? undefined : `${entry.name}, ${chats}`} + > + <span className="min-w-0 flex-1 truncate">{entry.name}</span> + {chats === undefined ? null : ( + <span aria-hidden className="ml-4 shrink-0 text-small text-tertiary"> + {chats} + </span> + )} + </DropdownMenuRadioItem> + ); + })} </DropdownMenuRadioGroup> <DropdownMenuSeparator /> <DropdownMenuItem disabled={!canAddPage(doc)} onSelect={() => onPage({ type: "add" })}> diff --git a/renderer/design/use-design-canvas.test.tsx b/renderer/design/use-design-canvas.test.tsx index 0f587621f..5f39b189c 100644 --- a/renderer/design/use-design-canvas.test.tsx +++ b/renderer/design/use-design-canvas.test.tsx @@ -3,12 +3,13 @@ import { emitBotTestNotification, installBotTestIpc, type BotTestIpcCall } from import assert from "node:assert/strict"; import { afterEach, beforeEach, mock, test } from "node:test"; import { act, cleanup, render } from "@testing-library/react"; +import { deletePage, renamePage } from "../shared/design-canvas/pages"; import { emptyDesignCanvas, type DesignCanvas, type DesignFrame } from "../shared/design-canvas/schema"; import { DESIGN_CANVAS_CLOSED_RETRY_MS, useDesignCanvas } from "./use-design-canvas"; type Controller = ReturnType<typeof useDesignCanvas>; type SaveReply = - | { ok: true; revision: number } + | { ok: true; revision: number; chatPages?: Record<string, string>; namedFor?: Record<string, string> } | { ok: false; reason: "conflict"; doc: DesignCanvas } | { ok: false; reason: "moved"; workspaceId: string } | { ok: false; reason: "invalid"; issues: string[] }; @@ -29,7 +30,7 @@ const ids = (doc: DesignCanvas | undefined) => doc?.frames.map((frame) => frame. let calls: BotTestIpcCall[]; let stored: DesignCanvas; -let saveReplies: Array<(doc: DesignCanvas, base: number) => SaveReply>; +let saveReplies: Array<(doc: DesignCanvas, base: number) => SaveReply | Promise<SaveReply>>; let controller: Controller; let movedTo: string[]; @@ -402,6 +403,93 @@ test("all of one Aiden reply's canvas changes undo as one step, after which the assert.deepEqual(ids(stored), ["a", "b", "c"]); }); +test("undoing a turn that used a page keeps the picker on the stored claim", async () => { + stored = { ...canvas(4, note("a")), pages: [{ id: "page-1", name: "Page 1" }, { id: "p2", name: "Pricing" }] }; + await mount(); + await act(async () => controller.change(moveTo("a", 10))); + await tick(800); + // Aiden's reply makes Pricing this chat's page and adds a note there. + await aidenSaves({ ...stored, revision: 6, chatPages: { "chat-1": "p2" }, frames: [note("a", 10), { ...note("b"), pageId: "p2" }] }, "reply-1"); + assert.deepEqual(controller.doc?.chatPages, { "chat-1": "p2" }); + + // Undoing the reply sends the old claims; the store keeps its own and says so. + saveReplies.push((doc, base) => { + stored = { ...doc, revision: base + 1, chatPages: { "chat-1": "p2" } }; + return { ok: true, revision: stored.revision, chatPages: { "chat-1": "p2" }, namedFor: {} }; + }); + await act(async () => controller.undo()); + await tick(800); + assert.deepEqual(ids(controller.doc), ["a"]); + assert.deepEqual(controller.doc?.chatPages, { "chat-1": "p2" }, "the canvas shows the stored claim"); + + // The claim is in every kept step, so the next undo does not bring the stale one back. + await act(async () => controller.undo()); + assert.equal(xOf(controller.doc, "a"), 0); + assert.deepEqual(controller.doc?.chatPages, { "chat-1": "p2" }); + await tick(800); + assert.deepEqual(stored.chatPages, { "chat-1": "p2" }); +}); + +/** A save reply that answers only once `release` is called, as a save still on its way. */ +function heldReply(answer: (doc: DesignCanvas, base: number) => SaveReply) { + let release!: () => void; + const gate = new Promise<void>((resolve) => (release = resolve)); + saveReplies.push(async (doc, base) => { + await gate; + return answer(doc, base); + }); + return () => act(async () => release()); +} + +test("a save's stored claims do not undo a second undo made while that save was on its way", async () => { + stored = { + ...canvas(4, note("a")), + pages: [{ id: "page-1", name: "Page 1" }, { id: "p", name: "P" }, { id: "pa", name: "Pa" }], + chatPages: { "chat-1": "pa", "chat-b": "p" }, + }; + await mount(); + // The person deletes P, chat-b's page; chat-b moves to Page 1. + await act(async () => controller.change((doc) => deletePage(doc, "p"))); + await tick(800); + // This chat's reply makes Page 1 its page. + await aidenSaves({ ...stored, revision: 6, chatPages: { "chat-1": "page-1", "chat-b": "page-1" } }, "reply-1"); + + // Undoing the reply sends chat-1 back to Pa; the store keeps its claim on Page 1. + const release = heldReply((doc, base) => { + stored = { ...doc, revision: base + 1, chatPages: { "chat-1": "page-1", "chat-b": "page-1" } }; + return { ok: true, revision: stored.revision, chatPages: { "chat-1": "page-1", "chat-b": "page-1" }, namedFor: {} }; + }); + await act(async () => controller.undo()); + await tick(800); + // Before that save answers, the person undoes the delete: P is back with chat-b on it. + await act(async () => controller.undo()); + assert.equal(controller.doc?.chatPages["chat-b"], "p"); + await release(); + await settle(); + assert.deepEqual(controller.doc?.chatPages, { "chat-1": "page-1", "chat-b": "p" }, "only what the store changed is applied"); + assert.ok(controller.doc?.pages.some((page) => page.id === "p")); +}); + +test("a page renamed while a save was on its way keeps the person's name and does not follow its chat again", async () => { + stored = { + ...canvas(4, note("a")), + pages: [{ id: "page-1", name: "Page 1" }, { id: "P", name: "Chat A", namedFor: "chat-a" }], + chatPages: { "chat-a": "page-1" }, + }; + await mount(); + const release = heldReply((doc, base) => { + stored = { ...doc, revision: base + 1, chatPages: { "chat-a": "P" } }; + return { ok: true, revision: stored.revision, chatPages: { "chat-a": "P" }, namedFor: { P: "chat-a" } }; + }); + await act(async () => controller.change(moveTo("a", 50))); + await tick(800); + await act(async () => controller.change((doc) => renamePage(doc, "P", "Bar"))); + await release(); + await settle(); + assert.deepEqual(controller.doc?.pages[1], { id: "P", name: "Bar" }); + assert.equal(controller.doc?.chatPages["chat-a"], "P"); +}); + test("a reply's change the canvas fetched before hearing whose it was still undoes with the rest of that reply", async () => { await mount(); await act(async () => controller.change(moveTo("a", 10))); diff --git a/renderer/design/use-design-canvas.ts b/renderer/design/use-design-canvas.ts index f72956ce4..b41e6e25b 100644 --- a/renderer/design/use-design-canvas.ts +++ b/renderer/design/use-design-canvas.ts @@ -34,6 +34,7 @@ import * as React from "react"; import { designCanvasApi } from "../lib/ipc"; import { registerLifecycleFlush, setRendererLifecycleGuard } from "../lib/lifecycle-guard"; +import { applyStoredClaims } from "../shared/design-canvas/chat-pages"; import { shownPagePaths, type DesignCanvas } from "../shared/design-canvas/schema"; import { carryUnrecorded, @@ -257,7 +258,19 @@ function createCanvasSync( if (result.ok) { for (const page of undone) undonePages.delete(page); server = { ...doc, revision: result.revision }; - if (local === doc) local = server; + if (result.chatPages) { + // The store kept its own chats' pages over what was sent: show those, and + // carry them into every kept step, so no undo brings the sent ones back. + // Newer edits take only what the store changed, so a later undo or rename stays. + const before = local ?? doc; + server = applyStoredClaims(server, result.chatPages, result.namedFor); + local = changesBetween(doc, server)(before); + const change = { before, from: doc, to: server }; + if (unsettled) noteChange({ takenIn: change }); + history = takeIn(history, change); + } else if (local === doc) { + local = server; + } failed = false; } else if (result.reason === "conflict") { takeInStored(result.doc, local ?? doc); diff --git a/renderer/design/use-design-view.test.tsx b/renderer/design/use-design-view.test.tsx index 483251096..60f0e82d6 100644 --- a/renderer/design/use-design-view.test.tsx +++ b/renderer/design/use-design-view.test.tsx @@ -162,3 +162,56 @@ test("when the page on screen goes (an added page undone), the chat goes back to await tick(DESIGN_VIEW_REPORT_DELAY_MS); assert.equal((lastReport()?.[1] as { view: { pageId: string } }).view.pageId, "p2"); }); + +test("when the view's page is gone, the canvas shows the claim before an earlier page", async () => { + kept = { pageId: "page-1", viewport: { x: 0, y: 0, zoom: 1 }, focusId: 0, viewports: {} }; + const claimed: DesignCanvas = { ...doc, chatPages: { "chat-1": "p3" } }; + const shown = render(<Probe canvas={claimed} />); + await settle(); + await act(async () => view.showPage("p2")); + assert.equal(view.pageId, "p2"); + // Another chat deletes p2; page-1 was shown earlier, but the chat's own page comes first. + shown.rerender(<Probe canvas={{ ...claimed, pages: claimed.pages.filter((page) => page.id !== "p2") }} />); + assert.equal(view.pageId, "p3"); +}); + +test("a canvas with no kept view opens on the claim", async () => { + kept = null; + render(<Probe canvas={{ ...doc, chatPages: { "chat-1": "p3", "chat-2": "p2" } }} />); + await settle(); + assert.equal(view.pageId, "p3"); +}); + +test("a fallback page is reported to main", async () => { + kept = { pageId: "p2", viewport: { x: 0, y: 0, zoom: 1 }, focusId: 0, viewports: {} }; + const claimed: DesignCanvas = { ...doc, chatPages: { "chat-1": "p3" } }; + const shown = render(<Probe canvas={claimed} />); + await settle(); + await tick(DESIGN_VIEW_REPORT_DELAY_MS); + const opened = reports().length; + shown.rerender(<Probe canvas={{ ...claimed, pages: claimed.pages.filter((page) => page.id !== "p2") }} />); + await settle(); + await tick(DESIGN_VIEW_REPORT_DELAY_MS); + assert.deepEqual(reports().slice(opened), [ + ["chat-1", { workspaceId: "ws-1", view: { pageId: "p3", viewport: { x: 0, y: 0, zoom: 1 } }, focusId: 0 }], + ]); +}); + +test("when the view's page comes back after a fallback was reported, main hears the page on screen again", async () => { + kept = { pageId: "p2", viewport: { x: 0, y: 0, zoom: 1 }, focusId: 0, viewports: {} }; + const claimed: DesignCanvas = { ...doc, chatPages: { "chat-1": "p3" } }; + const shown = render(<Probe canvas={claimed} />); + await settle(); + await tick(DESIGN_VIEW_REPORT_DELAY_MS); + shown.rerender(<Probe canvas={{ ...claimed, pages: claimed.pages.filter((page) => page.id !== "p2") }} />); + await settle(); + await tick(DESIGN_VIEW_REPORT_DELAY_MS); + assert.equal((lastReport()?.[1] as { view: { pageId: string } }).view.pageId, "p3"); + // An undo elsewhere brings p2 back. + shown.rerender(<Probe canvas={claimed} />); + await settle(); + await tick(DESIGN_VIEW_REPORT_DELAY_MS); + assert.equal(view.pageId, "p2"); + assert.equal((lastReport()?.[1] as { view: { pageId: string } }).view.pageId, "p2"); +}); + diff --git a/renderer/design/use-design-view.ts b/renderer/design/use-design-view.ts index f7c74f824..ce339265f 100644 --- a/renderer/design/use-design-view.ts +++ b/renderer/design/use-design-view.ts @@ -13,7 +13,7 @@ import * as React from "react"; import { designCanvasApi } from "../lib/ipc"; import type { DesignCanvas, DesignViewport } from "../shared/design-canvas/schema"; -import { DESIGN_FRESH_VIEWPORT, viewPageId } from "../shared/design-canvas/view"; +import { DESIGN_FRESH_VIEWPORT } from "../shared/design-canvas/view"; export const DESIGN_VIEW_REPORT_DELAY_MS = 250; @@ -22,7 +22,7 @@ type Size = { w: number; h: number }; export interface DesignViewHandle { /** False until main's kept view has been read; the canvas waits for it. */ loaded: boolean; - /** The page on screen: the view's page while it exists, else the first page. */ + /** The page on screen: the view's page while it exists, else the chat's own page, else an earlier or the first page. */ pageId: string; /** Where the person looks at that page. */ viewport: DesignViewport; @@ -43,7 +43,12 @@ export interface DesignViewHandle { type State = { loaded: boolean; pageId: string | undefined; - /** Pages shown before this one, newest first, so undoing a page's creation goes back to where the person was. */ + /** + * Pages shown before this one, newest first. When the page on screen goes + * and the chat has no page of its own that exists, the canvas goes back to + * the newest of these, so undoing a page's creation returns to where the + * person was. + */ earlier: readonly string[]; viewports: Readonly<Record<string, DesignViewport>>; }; @@ -58,11 +63,17 @@ function showing(state: State, pageId: string): State { return { ...state, pageId, earlier: earlier.filter((id) => id !== pageId).slice(0, MAX_EARLIER) }; } -/** The page on screen: the view's own while it exists, else the newest earlier page that does, else the first. */ -function shownPageId(doc: DesignCanvas, state: State): string { - if (state.pageId !== undefined && doc.pages.some((page) => page.id === state.pageId)) return state.pageId; - const back = state.earlier.find((id) => doc.pages.some((page) => page.id === id)); - return viewPageId(doc, back === undefined ? state : { pageId: back }); +/** + * The page on screen: the view's own while it exists, else the chat's own + * page (`chatPages`), else the newest earlier page that exists, else the + * first. Main resolves a turn's page in the same order (`designTurnPages`). + */ +function shownPageId(doc: DesignCanvas, state: State, chatId: string): string { + const exists = (id: string | undefined): id is string => id !== undefined && doc.pages.some((page) => page.id === id); + if (exists(state.pageId)) return state.pageId; + const claim = Object.prototype.hasOwnProperty.call(doc.chatPages, chatId) ? doc.chatPages[chatId] : undefined; + if (exists(claim)) return claim; + return state.earlier.find(exists) ?? doc.pages[0]!.id; } export function useDesignView(workspaceId: string, chatId: string, doc: DesignCanvas | undefined): DesignViewHandle { @@ -81,7 +92,7 @@ export function useDesignView(workspaceId: string, chatId: string, doc: DesignCa const current = stateRef.current; const shown = docRef.current; if (!current.loaded || !shown) return; - const pageId = shownPageId(shown, current); + const pageId = shownPageId(shown, current, chatId); const view = { pageId, viewport: current.viewports[pageId] ?? DESIGN_FRESH_VIEWPORT, @@ -134,11 +145,7 @@ export function useDesignView(workspaceId: string, chatId: string, doc: DesignCa }; }, [chatId, workspaceId, send]); - // Once loaded, main hears the canvas is open, and what it shows. const hasDoc = doc !== undefined; - React.useEffect(() => { - if (state.loaded && hasDoc) schedule(); - }, [state.loaded, hasDoc, schedule]); const showPage = React.useCallback( (pageId: string) => { @@ -152,14 +159,14 @@ export function useDesignView(workspaceId: string, chatId: string, doc: DesignCa const shown = docRef.current; if (!shown) return; setState((current) => { - const pageId = shownPageId(shown, current); + const pageId = shownPageId(shown, current, chatId); const before = current.viewports[pageId]; if (before && before.x === viewport.x && before.y === viewport.y && before.zoom === viewport.zoom) return current; return { ...current, viewports: { ...current.viewports, [pageId]: { x: viewport.x, y: viewport.y, zoom: viewport.zoom } } }; }); schedule(); }, - [schedule], + [schedule, chatId], ); const setSize = React.useCallback( (next: Size) => { @@ -183,7 +190,13 @@ export function useDesignView(workspaceId: string, chatId: string, doc: DesignCa [schedule], ); - const pageId = doc ? shownPageId(doc, state) : (state.pageId ?? ""); + const pageId = doc ? shownPageId(doc, state, chatId) : (state.pageId ?? ""); + // Once loaded, main hears the canvas is open and what it shows, and again + // whenever the page on screen changes (a fallback, or the view's page coming + // back), so its kept view matches the screen. + React.useEffect(() => { + if (state.loaded && hasDoc) schedule(); + }, [state.loaded, hasDoc, pageId, schedule]); return { loaded: state.loaded, pageId, diff --git a/renderer/lib/ipc.ts b/renderer/lib/ipc.ts index 75cdb9786..268521bb2 100644 --- a/renderer/lib/ipc.ts +++ b/renderer/lib/ipc.ts @@ -2726,9 +2726,13 @@ export const ttsApi = { onNotification<TtsServiceEvent>("tts:event", handler), }; -/** Result of `designCanvas:save`; mirrors main's `DesignCanvasSaveResult`. */ +/** + * Result of `designCanvas:save`; mirrors main's `DesignCanvasSaveResult`. + * `chatPages` and `namedFor` (page id to chat id) come only when the store + * merged in its own chat pages: they are what was stored. + */ export type DesignCanvasSaveResult = - | { ok: true; revision: number } + | { ok: true; revision: number; chatPages?: Record<string, string>; namedFor?: Record<string, string> } | { ok: false; reason: "conflict"; doc: DesignCanvas } | { ok: false; reason: "moved"; workspaceId: string } | { ok: false; reason: "invalid"; issues: string[] }; diff --git a/renderer/shared/design-canvas/chat-pages.test.ts b/renderer/shared/design-canvas/chat-pages.test.ts new file mode 100644 index 000000000..d4cab75f5 --- /dev/null +++ b/renderer/shared/design-canvas/chat-pages.test.ts @@ -0,0 +1,324 @@ +// Each chat's own page on the shared workspace canvas: the rules main uses to +// claim, name, follow, forget and merge `chatPages`. + +import assert from "node:assert/strict"; +import test from "node:test"; +import { + addChatPage, + applyStoredClaims, + ChatPagesFullError, + chatsOnPage, + claimPage, + deletedClaims, + followChatTitle, + forgetChatMove, + forgetChatOnCanvas, + mergeSavedChatPages, + landedPageId, + uniquePageName, + withLazyClaim, + type DeletedPage, +} from "./chat-pages.js"; +import { addPage, deletePage } from "./pages.js"; +import { DESIGN_CANVAS_LIMITS, emptyDesignCanvas, type DesignCanvas, type DesignComment, type DesignFrame } from "./schema.js"; + +function note(id: string, pageId: string, extra: Partial<DesignFrame> = {}): DesignFrame { + return { id, kind: "note", title: id, x: 0, y: 0, w: 200, h: 120, text: id, pageId, createdBy: "person", ...extra }; +} + +function artifact(id: string, pageId: string, chatId: string, extra: Partial<DesignFrame> = {}): DesignFrame { + return { id, kind: "artifact", title: id, x: 300, y: 0, w: 200, h: 120, mediaId: `m-${id}`, pageId, chatId, createdBy: "aiden", ...extra }; +} + +function comment(id: string, pageId: string, extra: Partial<DesignComment> = {}): DesignComment { + return { id, pageId, x: 0, y: 0, note: id, state: "open", anchorState: "anchored", createdAt: "2026-11-23T10:00:00.000Z", ...extra }; +} + +/** Pages with the given ids, the first one "page-1". */ +function canvas(pageIds: string[] = [], extra: Partial<DesignCanvas> = {}): DesignCanvas { + let doc = emptyDesignCanvas(); + for (const id of pageIds) doc = addPage(doc, id, id.toUpperCase()); + return { ...doc, ...extra }; +} + +const names = (doc: DesignCanvas) => doc.pages.map((page) => page.name); +const pageOf = (doc: DesignCanvas, id: string) => doc.pages.find((page) => page.id === id); + +test("uniquePageName adds the lowest free number and cuts the base so the name stays within 60 characters", () => { + let doc = canvas(); + assert.equal(uniquePageName(doc, " Northwind landing "), "Northwind landing"); + assert.equal(uniquePageName(doc, " "), "Chat", "an empty title gives Chat"); + assert.equal(uniquePageName(doc, "page 1"), "page 1 2", "a name in any case is taken"); + doc = addPage(addPage(doc, "p2", "Pricing"), "p3", "pricing 2"); + assert.equal(uniquePageName(doc, "Pricing"), "Pricing 3"); + + const long = "x".repeat(80); + const cut = uniquePageName(doc, long); + assert.equal(cut, "x".repeat(DESIGN_CANVAS_LIMITS.pageNameChars)); + doc = addPage(doc, "p4", cut); + const numbered = uniquePageName(doc, long); + assert.equal(numbered.length, DESIGN_CANVAS_LIMITS.pageNameChars); + assert.ok(numbered.endsWith(" 2"), numbered); +}); + +test("uniquePageName ignores the page being renamed", () => { + const doc = addPage(canvas(), "p2", "Pricing"); + assert.equal(uniquePageName(doc, "Pricing", "p2"), "Pricing"); + assert.equal(uniquePageName(doc, "Pricing"), "Pricing 2"); +}); + +test("addChatPage adds a named page after the given page, marks it and claims it; at the page limit it changes nothing", () => { + const base = canvas(["p2"], { chatPages: { other: "p2" } }); + const doc = addChatPage(base, "chat-b", "Sketch the pricing table", "pb", "page-1"); + assert.deepEqual(names(doc), ["Page 1", "Sketch the pricing table", "P2"]); + assert.deepEqual(pageOf(doc, "pb"), { id: "pb", name: "Sketch the pricing table", namedFor: "chat-b" }); + assert.deepEqual(doc.chatPages, { other: "p2", "chat-b": "pb" }); + + let full = emptyDesignCanvas(); + for (let index = 2; index <= DESIGN_CANVAS_LIMITS.pages; index += 1) full = addPage(full, `p${index}`); + assert.equal(addChatPage(full, "chat-b", "Title", "one-more"), full); +}); + +test("claimPage at the cap evicts a dead chat's entry, and refuses when every entry is a live chat's", () => { + const chatPages: Record<string, string> = {}; + for (let index = 0; index < DESIGN_CANVAS_LIMITS.chatPages; index += 1) chatPages[`chat-${index}`] = "page-1"; + const full = canvas(["p2"], { chatPages }); + + // Moving a chat that already has a claim needs no room. + assert.equal(claimPage(full, "chat-3", "p2").chatPages["chat-3"], "p2"); + assert.equal(claimPage(full, "chat-3", "page-1"), full, "the same claim changes nothing"); + + const dead = new Set(["chat-7"]); + const evicted = claimPage(full, "new-chat", "p2", (chatId) => !dead.has(chatId)); + assert.equal(evicted.chatPages["new-chat"], "p2"); + assert.equal("chat-7" in evicted.chatPages, false); + assert.equal(Object.keys(evicted.chatPages).length, DESIGN_CANVAS_LIMITS.chatPages); + + assert.throws(() => claimPage(full, "new-chat", "p2", () => true), ChatPagesFullError); + assert.throws(() => claimPage(full, "new-chat", "p2"), ChatPagesFullError); +}); + +test("chatsOnPage lists the chats whose page it is, skipping chats that are not live", () => { + const doc = canvas(["p2"], { chatPages: { a: "p2", b: "page-1", c: "p2" } }); + assert.deepEqual(chatsOnPage(doc, "p2").sort(), ["a", "c"]); + assert.deepEqual(chatsOnPage(doc, "p2", (chatId) => chatId !== "c"), ["a"]); + assert.deepEqual(chatsOnPage(doc, "missing"), []); +}); + +test("followChatTitle renames only pages named for that chat, and changes nothing when none is", () => { + const base = addChatPage(addChatPage(canvas(), "chat-a", "New chat", "pa"), "chat-b", "Other", "pb"); + const doc = followChatTitle(base, "chat-a", "Northwind landing"); + assert.equal(pageOf(doc, "pa")?.name, "Northwind landing"); + assert.equal(pageOf(doc, "pa")?.namedFor, "chat-a"); + assert.equal(pageOf(doc, "pb")?.name, "Other"); + assert.equal(followChatTitle(doc, "chat-a", "Northwind landing"), doc, "the same title changes nothing"); + assert.equal(followChatTitle(doc, "chat-z", "Anything"), doc, "a chat with no page made for it changes nothing"); + // Its own name is not counted as taken, but another page's is. + assert.equal(pageOf(followChatTitle(doc, "chat-a", "Other"), "pa")?.name, "Other 2"); +}); + +test("forgetChatOnCanvas drops the claim, the named-for marks and the artifact frames with the comments on them, and keeps other chats' frames, the page and the chat's notes", () => { + const base = addChatPage(canvas(), "chat-a", "Landing", "pa"); + const doc: DesignCanvas = { + ...base, + chatPages: { ...base.chatPages, "chat-b": "pa" }, + frames: [ + artifact("a-art", "pa", "chat-a"), + artifact("b-art", "pa", "chat-b"), + note("a-note", "pa", { chatId: "chat-a", createdBy: "aiden" }), + ], + comments: [ + comment("on-a-art", "pa", { frameId: "a-art", chatId: "chat-b" }), + comment("on-b-art", "pa", { frameId: "b-art" }), + comment("a-own", "pa", { chatId: "chat-a" }), + ], + }; + const forgotten = forgetChatOnCanvas(doc, "chat-a"); + assert.deepEqual(forgotten.chatPages, { "chat-b": "pa" }); + assert.deepEqual(pageOf(forgotten, "pa"), { id: "pa", name: "Landing" }); + assert.deepEqual(forgotten.frames.map((frame) => frame.id), ["b-art", "a-note"]); + assert.deepEqual(forgotten.comments.map((entry) => entry.id), ["on-b-art", "a-own"], "the chat's own comments are left to the comment pass"); + assert.equal(forgetChatOnCanvas(forgotten, "chat-a"), forgotten, "nothing left to forget changes nothing"); +}); + +test("forgetChatOnCanvas lets go of an arrow joined to a removed artifact frame and refits its group", () => { + const group: DesignFrame = { id: "g", kind: "group", title: "Group", x: 0, y: 0, w: 1000, h: 400, pageId: "page-1", createdBy: "aiden" }; + const doc: DesignCanvas = { + ...canvas(), + frames: [ + group, + note("kept", "page-1", { groupId: "g", x: 20, y: 40, w: 200, h: 120 }), + artifact("art", "page-1", "chat-a", { groupId: "g", x: 600, y: 40, w: 300, h: 200 }), + note("other", "page-1", { x: 0, y: 600 }), + { + id: "arrow", + kind: "connector", + title: "Arrow", + x: 0, + y: 0, + w: 1, + h: 1, + ends: [{ x: 0, y: 0, frameId: "other" }, { x: 0, y: 0, frameId: "art" }], + pageId: "page-1", + createdBy: "person", + }, + ], + }; + const forgotten = forgetChatOnCanvas(doc, "chat-a"); + const arrow = forgotten.frames.find((frame) => frame.id === "arrow")!; + assert.equal(arrow.ends?.[0].frameId, "other"); + assert.equal(arrow.ends?.[1].frameId, undefined, "the end on the removed frame is let go"); + const refit = forgotten.frames.find((frame) => frame.id === "g")!; + assert.ok(refit.w < group.w, `the group shrank to its member left (w ${refit.w})`); +}); + +test("forgetChatMove deletes the empty page made for the chat, and keeps a page with frames, a comment or another chat's claim, clearing namedFor", () => { + const empty = addChatPage(canvas(), "chat-a", "Landing", "pa"); + const gone = forgetChatMove(empty, "chat-a"); + assert.deepEqual(gone.pages.map((page) => page.id), ["page-1"]); + assert.deepEqual(gone.chatPages, {}); + + const cases: [string, Partial<DesignCanvas>][] = [ + ["a frame", { frames: [note("n", "pa")] }], + ["a comment", { comments: [comment("c", "pa")] }], + ["another chat's claim", { chatPages: { "chat-a": "pa", "chat-b": "pa" } }], + ]; + for (const [label, extra] of cases) { + const doc: DesignCanvas = { ...empty, ...extra }; + const moved = forgetChatMove(doc, "chat-a"); + assert.deepEqual(pageOf(moved, "pa"), { id: "pa", name: "Landing" }, label); + assert.equal("chat-a" in moved.chatPages, false, label); + } + + // The only page is never deleted. + const only: DesignCanvas = { ...emptyDesignCanvas(), pages: [{ id: "pa", name: "Landing", namedFor: "chat-a" }], chatPages: { "chat-a": "pa" } }; + assert.deepEqual(forgetChatMove(only, "chat-a").pages, [{ id: "pa", name: "Landing" }]); + + // An empty page made for the chat goes even when it is the first page; other chats keep theirs. + const first: DesignCanvas = { + ...emptyDesignCanvas(), + pages: [{ id: "pa", name: "Landing", namedFor: "chat-a" }, { id: "page-1", name: "Page 1" }], + chatPages: { "chat-a": "pa", "chat-b": "page-1" }, + }; + const left = forgetChatMove(first, "chat-a"); + assert.deepEqual(left.pages, [{ id: "page-1", name: "Page 1" }]); + assert.deepEqual(left.chatPages, { "chat-b": "page-1" }); +}); + +test("deletedClaims records each removed page's chats and where they went, and its namedFor", () => { + const before = addChatPage(canvas(["p2"], { chatPages: { b: "p2" } }), "a", "Landing", "pa"); + const after = deletePage(deletePage(before, "p2"), "pa"); + const record = deletedClaims(before, after); + assert.deepEqual([...record.keys()].sort(), ["p2", "pa"]); + assert.deepEqual([...record.get("p2")!.claims], [["b", "page-1"]]); + assert.equal(record.get("p2")!.namedFor, undefined); + assert.deepEqual([...record.get("pa")!.claims], [["a", "page-1"]]); + assert.equal(record.get("pa")!.namedFor, "a"); + // A removed page no chat used and no chat named is not recorded. + assert.equal(deletedClaims(canvas(["p2"]), canvas()).size, 0); +}); + +test("mergeSavedChatPages keeps the stored claims when the save carries stale ones", () => { + const current = canvas(["p2"], { revision: 4, chatPages: { a: "p2" } }); + const saved = canvas(["p2"], { revision: 4, chatPages: { a: "page-1", b: "page-1" }, frames: [note("n", "page-1")] }); + const merged = mergeSavedChatPages(current, saved, new Map()); + assert.equal(merged.changed, true); + assert.deepEqual(merged.doc.chatPages, { a: "p2" }); + assert.deepEqual(merged.doc.frames, saved.frames, "everything else is the save's"); + assert.equal(merged.deletedNow.size, 0); + + const same = mergeSavedChatPages(current, { ...saved, chatPages: { a: "p2" } }, new Map()); + assert.equal(same.changed, false); +}); + +test("mergeSavedChatPages restores a claim for a brought-back page only when the delete record has it and the chat is still where the delete moved it", () => { + const before = canvas(["p2"], { chatPages: { a: "p2", b: "p2", c: "p2" } }); + const afterDelete = deletePage(before, "p2"); + const deleted = deletedClaims(before, afterDelete); + // Since the delete: a stayed where it was moved, b used another page, c was deleted. + const current: DesignCanvas = { ...addPage(afterDelete, "p3"), chatPages: { a: "page-1", b: "p3" } }; + // The person's undo sends the old document back. + const saved: DesignCanvas = { ...addPage(before, "p3"), chatPages: before.chatPages }; + const merged = mergeSavedChatPages(current, saved, deleted, (chatId) => chatId !== "c"); + assert.deepEqual(merged.doc.chatPages, { a: "p2", b: "p3" }); + assert.deepEqual([...merged.restored.get("p2")!.claims], [["a", "page-1"]]); +}); + +test("mergeSavedChatPages does not let a save move a chat on the first page onto a new page id", () => { + const current = canvas([], { chatPages: { b: "page-1" } }); + const saved = canvas(["p9"], { chatPages: { b: "p9" } }); + const merged = mergeSavedChatPages(current, saved, new Map()); + assert.deepEqual(merged.doc.chatPages, { b: "page-1" }); + assert.deepEqual(merged.doc.pages.map((page) => page.id), ["page-1", "p9"], "the new page itself is kept"); + // Nor does a record for another page let it in. + const record = new Map<string, DeletedPage>([["p8", { claims: new Map([["b", "page-1"]]) }]]); + assert.deepEqual(mergeSavedChatPages(current, saved, record).doc.chatPages, { b: "page-1" }); +}); + +test("mergeSavedChatPages reassigns claims on a page the save removed and records them", () => { + const current = addChatPage(canvas(["p2"], { chatPages: { b: "p2" } }), "a", "Landing", "pa"); + // The renderer's copy forgot both claims, and deletes p2 and pa. + const saved: DesignCanvas = { ...canvas(), chatPages: {} }; + const merged = mergeSavedChatPages(current, saved, new Map()); + assert.deepEqual(merged.doc.chatPages, { a: "page-1", b: "page-1" }); + assert.deepEqual([...merged.deletedNow.get("p2")!.claims], [["b", "page-1"]]); + assert.deepEqual([...merged.deletedNow.get("pa")!.claims], [["a", "page-1"]]); + assert.equal(merged.deletedNow.get("pa")!.namedFor, "a"); +}); + +test("mergeSavedChatPages never adds namedFor to a stored page without it, and restores it on a brought-back page the record holds", () => { + const current = canvas(["p2"]); + const marked: DesignCanvas = { ...current, pages: current.pages.map((page) => (page.id === "p2" ? { ...page, namedFor: "a" } : page)) }; + assert.equal(pageOf(mergeSavedChatPages(current, marked, new Map()).doc, "p2")?.namedFor, undefined); + // A save may drop it, as a rename does. + assert.equal(pageOf(mergeSavedChatPages(marked, current, new Map()).doc, "p2")?.namedFor, undefined); + assert.equal(pageOf(mergeSavedChatPages(marked, marked, new Map()).doc, "p2")?.namedFor, "a"); + + // Chat a now uses another page; the person undoes the delete of the page made for it. + const before = addChatPage(canvas(), "a", "Landing", "pa"); + const afterDelete = deletePage(before, "pa"); + const deleted = deletedClaims(before, afterDelete); + const now: DesignCanvas = { ...addPage(afterDelete, "p3"), chatPages: { a: "p3" } }; + const undone: DesignCanvas = { ...addPage(before, "p3"), chatPages: before.chatPages }; + const merged = mergeSavedChatPages(now, undone, deleted, () => true); + assert.equal(pageOf(merged.doc, "pa")?.namedFor, "a"); + assert.equal(merged.doc.chatPages.a, "p3", "the chat stays on the page it used since"); + assert.equal(merged.restored.get("pa")?.namedFor, "a"); + // Not for a chat that is no longer live here. + assert.equal(pageOf(mergeSavedChatPages(now, undone, deleted, () => false).doc, "pa")?.namedFor, undefined); + // Nor for a brought-back page the record does not hold. + assert.equal(pageOf(mergeSavedChatPages(now, undone, new Map(), () => true).doc, "pa")?.namedFor, undefined); +}); + +test("applyStoredClaims takes the stored claims and marks, keeps newer edits, and moves a claim on a page since deleted to the first page", () => { + const local: DesignCanvas = { + ...canvas(["p2", "p3"], { chatPages: { a: "page-1", stale: "p2" } }), + frames: [note("newer", "p3")], + }; + local.pages = local.pages.map((page) => (page.id === "p3" ? { ...page, namedFor: "x" } : page)); + const applied = applyStoredClaims(local, { a: "p2", b: "gone" }, { p2: "a" }); + assert.deepEqual(applied.chatPages, { a: "p2", b: "page-1" }); + assert.equal(pageOf(applied, "p2")?.namedFor, "a"); + assert.equal(pageOf(applied, "p3")?.namedFor, undefined); + assert.deepEqual(applied.frames, local.frames); +}); + +test("the lazy claim at a full chatPages evicts a gone chat's entry and claims, and skips only the claim when every entry is live", () => { + const full = (prefix: string): DesignCanvas => ({ + ...emptyDesignCanvas(), + chatPages: Object.fromEntries(Array.from({ length: DESIGN_CANVAS_LIMITS.chatPages }, (_, index) => [`${prefix}-${index}`, "page-1"])), + }); + const claimed = withLazyClaim(full("gone"), "chat-1", "page-1", (chatId) => !chatId.startsWith("gone-")); + assert.equal(claimed.chatPages["chat-1"], "page-1"); + assert.ok(Object.keys(claimed.chatPages).length <= DESIGN_CANVAS_LIMITS.chatPages); + const live = full("live"); + assert.equal(withLazyClaim(live, "chat-1", "page-1", () => true), live); +}); + +test("a write lands on the page of the first frame it adds or changes, else on the fallback", () => { + const before: DesignCanvas = { ...addPage(emptyDesignCanvas(), "p2", "Pricing"), frames: [note("a", "page-1")] }; + assert.equal(landedPageId(before, { ...before, frames: [...before.frames, note("b", "p2")] }, "page-1"), "p2"); + assert.equal(landedPageId(before, { ...before, frames: [{ ...note("a", "page-1"), x: 50 }] }, "p2"), "page-1"); + assert.equal(landedPageId(before, { ...before, frames: [note("a", "page-1")] }, "p2"), "p2", "an equal copy is no change"); + assert.equal(landedPageId(before, { ...before, frames: [] }, "p2"), "p2"); +}); diff --git a/renderer/shared/design-canvas/chat-pages.ts b/renderer/shared/design-canvas/chat-pages.ts new file mode 100644 index 000000000..2d0c6b6a8 --- /dev/null +++ b/renderer/shared/design-canvas/chat-pages.ts @@ -0,0 +1,337 @@ +// Each chat's own page on the shared workspace canvas (`chatPages`), and the +// pages made for a chat (`namedFor`). +// +// Only main claims, and only for the acting chat: on design-mode entry, on a +// design turn's first canvas write, through `canvas_page use` and on attach. +// Every write runs inside the store's update on the latest document, so two +// chats' writes never race. A person's save never adds or moves a claim on +// its own say: the store merges it with `mergeSavedChatPages`. +// Pure, like `pages.ts`; every function returns `doc` itself when it changes +// nothing. + +import { commentsWithoutFrames } from "./comments.js"; +import { syncConnectors } from "./connectors.js"; +import { addPage, canAddPage, deletePage } from "./pages.js"; +import { refitGroups } from "./placement.js"; +import { DESIGN_CANVAS_LIMITS, isDesignChatId, type DesignCanvas, type DesignPage } from "./schema.js"; + +/** Whether a chat still exists in this canvas's workspace. Left out, every chat counts as live. */ +export type IsChatLive = (chatId: string) => boolean; + +export class ChatPagesFullError extends Error { + constructor() { + super("This canvas has too many chats with pages of their own."); + this.name = "ChatPagesFullError"; + } +} + +/** + * What the store remembers of a deleted page that had claims or a + * `namedFor`: each chat that was on it and the page the delete moved it to. + */ +export type DeletedPage = { namedFor?: string; claims: Map<string, string> }; + +const FALLBACK_NAME = "Chat"; + +function claimOf(doc: Pick<DesignCanvas, "chatPages">, chatId: string): string | undefined { + return Object.prototype.hasOwnProperty.call(doc.chatPages, chatId) ? doc.chatPages[chatId] : undefined; +} + +/** The chats whose own page `pageId` is, skipping those `isLive` says are gone. */ +export function chatsOnPage(doc: Pick<DesignCanvas, "chatPages">, pageId: string, isLive?: IsChatLive): string[] { + return Object.entries(doc.chatPages) + .filter(([chatId, claimed]) => claimed === pageId && isLive?.(chatId) !== false) + .map(([chatId]) => chatId); +} + +/** + * A page name for `base` that no other page has (case-insensitive): + * whitespace collapsed, cut to the page-name limit, "Chat" when empty, and + * " 2", " 3"… on a clash, with the base cut so the number fits. + */ +export function uniquePageName(doc: Pick<DesignCanvas, "pages">, base: string, exceptPageId?: string): string { + const limit = DESIGN_CANVAS_LIMITS.pageNameChars; + const clean = base.replace(/\s+/gu, " ").trim().slice(0, limit).trim() || FALLBACK_NAME; + const taken = new Set( + doc.pages.filter((page) => page.id !== exceptPageId).map((page) => page.name.toLocaleLowerCase()), + ); + if (!taken.has(clean.toLocaleLowerCase())) return clean; + for (let number = 2; ; number += 1) { + const suffix = ` ${number}`; + const name = `${clean.slice(0, limit - suffix.length).trimEnd()}${suffix}`; + if (!taken.has(name.toLocaleLowerCase())) return name; + } +} + +/** + * Makes `pageId` the chat's own page. The caller checks the page exists. At + * the cap a new chat first evicts the entries of chats that are gone, and + * throws `ChatPagesFullError` when none is. + */ +export function claimPage(doc: DesignCanvas, chatId: string, pageId: string, isLive?: IsChatLive): DesignCanvas { + if (!isDesignChatId(chatId) || claimOf(doc, chatId) === pageId) return doc; + let chatPages = doc.chatPages; + if (claimOf(doc, chatId) === undefined && Object.keys(chatPages).length >= DESIGN_CANVAS_LIMITS.chatPages) { + const live = Object.entries(chatPages).filter(([other]) => isLive?.(other) !== false); + if (live.length >= DESIGN_CANVAS_LIMITS.chatPages) throw new ChatPagesFullError(); + chatPages = Object.fromEntries(live); + } + return { ...doc, chatPages: { ...chatPages, [chatId]: pageId } }; +} + +/** + * A design turn's write claims the page it landed on for a chat with no + * claim yet, in the same write. `doc` is the document after the write's own + * change, so a claim that change made stays, and a page it deleted is not + * claimed. At a full `chatPages`, entries of chats `isLive` says are gone + * make room; when none is, only the claim is skipped. + */ +export function withLazyClaim(doc: DesignCanvas, chatId: string, pageId: string, isLive?: IsChatLive): DesignCanvas { + if (claimOf(doc, chatId) !== undefined || !doc.pages.some((page) => page.id === pageId)) return doc; + try { + return claimPage(doc, chatId, pageId, isLive); + } catch (error) { + if (error instanceof ChatPagesFullError) return doc; + throw error; + } +} + +/** + * The page a write landed on: the page of the first frame in `after` that + * it added or changed, while that page exists, else `fallback`. + */ +export function landedPageId(before: DesignCanvas, after: DesignCanvas, fallback: string): string { + const earlier = new Map(before.frames.map((frame) => [frame.id, frame])); + const pages = new Set(after.pages.map((page) => page.id)); + for (const frame of after.frames) { + const old = earlier.get(frame.id); + if (old === frame || !pages.has(frame.pageId)) continue; + if (old === undefined || JSON.stringify(old) !== JSON.stringify(frame)) return frame.pageId; + } + return fallback; +} + +/** Whether a design turn's write should look for room to claim: no claim yet, and `chatPages` is full. */ +export function lazyClaimNeedsRoom(doc: DesignCanvas, chatId: string): boolean { + return claimOf(doc, chatId) === undefined && Object.keys(doc.chatPages).length >= DESIGN_CANVAS_LIMITS.chatPages; +} + +/** Every chat the canvas names as a page's owner: claims and `namedFor` marks. */ +export function chatsOnCanvas(doc: Pick<DesignCanvas, "chatPages" | "pages">): string[] { + const ids = new Set(Object.keys(doc.chatPages)); + for (const page of doc.pages) if (page.namedFor !== undefined) ids.add(page.namedFor); + return [...ids]; +} + +/** + * Drops the claims and `namedFor` marks of chats `isLive` says are gone, so a + * chat deleted between its delete and the cleanup that follows it does not + * keep its page, or keep other chats off it, forever. + */ +export function withoutGoneClaims(doc: DesignCanvas, isLive: IsChatLive): DesignCanvas { + const kept = Object.entries(doc.chatPages).filter(([chatId]) => isLive(chatId)); + let next = kept.length === Object.keys(doc.chatPages).length ? doc : { ...doc, chatPages: Object.fromEntries(kept) }; + if (next.pages.some((page) => page.namedFor !== undefined && !isLive(page.namedFor))) { + next = { ...next, pages: next.pages.map((page) => (page.namedFor !== undefined && !isLive(page.namedFor) ? withoutNamedFor(page) : page)) }; + } + return next; +} + +/** + * Adds a page made for the chat right after `after`, named after its title + * (`uniquePageName`), marked `namedFor` and claimed. At the page limit, or + * when `id` is taken, returns `doc`. + */ +export function addChatPage( + doc: DesignCanvas, + chatId: string, + title: string, + id: string, + after?: string, + isLive?: IsChatLive, +): DesignCanvas { + if (!canAddPage(doc) || doc.pages.some((page) => page.id === id)) return doc; + const added = addPage(doc, id, uniquePageName(doc, title), after); + const marked = { ...added, pages: added.pages.map((page) => (page.id === id ? { ...page, namedFor: chatId } : page)) }; + return claimPage(marked, chatId, id, isLive); +} + +/** Renames the pages made for the chat to its title. Their own names are not counted as taken. */ +export function followChatTitle(doc: DesignCanvas, chatId: string, title: string): DesignCanvas { + let next = doc; + for (const page of doc.pages) { + if (page.namedFor !== chatId) continue; + const name = uniquePageName(next, title, page.id); + if (name === page.name) continue; + next = { ...next, pages: next.pages.map((entry) => (entry.id === page.id ? { ...entry, name } : entry)) }; + } + return next; +} + +/** + * A deleted chat leaves the canvas: its claim and `namedFor` marks go, and so + * do its artifact frames with every comment on them, letting go of arrows and + * refitting groups. Its pages, notes and other frames stay as the workspace's + * work, and its own comments are left to the comment pass. + */ +export function forgetChatOnCanvas(doc: DesignCanvas, chatId: string): DesignCanvas { + const hasClaim = claimOf(doc, chatId) !== undefined; + const marked = doc.pages.some((page) => page.namedFor === chatId); + const removed = doc.frames.filter((frame) => frame.kind === "artifact" && frame.chatId === chatId); + if (!hasClaim && !marked && removed.length === 0) return doc; + let next: DesignCanvas = doc; + if (hasClaim) { + next = { ...next, chatPages: Object.fromEntries(Object.entries(next.chatPages).filter(([other]) => other !== chatId)) }; + } + if (marked) next = { ...next, pages: next.pages.map((page) => (page.namedFor === chatId ? withoutNamedFor(page) : page)) }; + if (removed.length > 0) { + const ids = new Set(removed.map((frame) => frame.id)); + const frames = next.frames.filter((frame) => !ids.has(frame.id)); + const comments = commentsWithoutFrames(next.comments, ids); + next = refitGroups( + syncConnectors({ ...next, frames, comments }), + removed.map((frame) => frame.groupId), + ); + } + return next; +} + +/** + * A chat moving to another workspace leaves this canvas: `forgetChatOnCanvas`, + * and a page made for it is deleted when it holds no frames or comments, no + * other chat uses it and it is not the only page. Otherwise it only stops + * following the chat. + */ +export function forgetChatMove(doc: DesignCanvas, chatId: string): DesignCanvas { + const made = doc.pages.filter((page) => page.namedFor === chatId).map((page) => page.id); + let next = forgetChatOnCanvas(doc, chatId); + for (const pageId of made) { + const empty = + !next.frames.some((frame) => frame.pageId === pageId) && + !next.comments.some((comment) => comment.pageId === pageId) && + chatsOnPage(next, pageId).length === 0; + if (empty && next.pages.length > 1) next = deletePage(next, pageId); + } + return next; +} + +/** + * The pages `after` removed that had claims or a `namedFor` in `before`, with + * each chat that was on one and the page it is on in `after`. + */ +export function deletedClaims(before: DesignCanvas, after: DesignCanvas): Map<string, DeletedPage> { + const kept = new Set(after.pages.map((page) => page.id)); + const record = new Map<string, DeletedPage>(); + for (const page of before.pages) { + if (kept.has(page.id)) continue; + const claims = new Map<string, string>(); + for (const chatId of chatsOnPage(before, page.id)) { + const movedTo = claimOf(after, chatId); + if (movedTo !== undefined) claims.set(chatId, movedTo); + } + if (claims.size === 0 && page.namedFor === undefined) continue; + record.set(page.id, { ...(page.namedFor !== undefined ? { namedFor: page.namedFor } : {}), claims }); + } + return record; +} + +/** + * A person's save (`saved`, the whole document from the renderer) merged with + * the stored claims (`current`) and the store's record of deleted pages: + * - claims start from `current`; + * - a page the save brings back gets back every chat `deleted` records on it + * that is still exactly where that delete moved it, whatever the save's + * copy says, so a save never adds an entry and never moves a chat the + * store did not record there; + * - a claim on a page the save removed moves to the page the save names for + * that chat when both documents have it, else to the save's first page, + * and is recorded in `deletedNow`; + * - a saved page keeps `namedFor` only when `current`'s page has the same, or + * when it is brought back with that `namedFor` in its record for a chat + * still live here. A save may always drop it. + * `restored` is what the store takes out of its record once the write lands. + */ +export function mergeSavedChatPages( + current: DesignCanvas, + saved: DesignCanvas, + deleted: ReadonlyMap<string, DeletedPage>, + isLive?: IsChatLive, +): { doc: DesignCanvas; changed: boolean; deletedNow: Map<string, DeletedPage>; restored: Map<string, DeletedPage> } { + const currentPages = new Map(current.pages.map((page) => [page.id, page])); + const savedIds = new Set(saved.pages.map((page) => page.id)); + const chatPages: Record<string, string> = { ...current.chatPages }; + const restored = new Map<string, DeletedPage>(); + const restoredOf = (pageId: string): DeletedPage => { + let entry = restored.get(pageId); + if (!entry) restored.set(pageId, (entry = { claims: new Map() })); + return entry; + }; + + const pages = saved.pages.map((page): DesignPage => { + const stored = currentPages.get(page.id); + if (stored) { + return page.namedFor !== undefined && page.namedFor === stored.namedFor ? page : withoutNamedFor(page); + } + const record = deleted.get(page.id); + if (record) { + for (const [chatId, movedTo] of record.claims) { + if (claimOf(current, chatId) !== movedTo || isLive?.(chatId) === false) continue; + chatPages[chatId] = page.id; + restoredOf(page.id).claims.set(chatId, movedTo); + } + } + const named = page.namedFor; + if (named !== undefined && record?.namedFor === named && isLive?.(named) !== false) { + restoredOf(page.id).namedFor = named; + return page; + } + return withoutNamedFor(page); + }); + + // A chat whose page the save removed goes back to the page the save names + // for it when both documents have that page (an undo of the turn that made + // the page its own), else to the first page. + const first = pages[0]!.id; + for (const [chatId, pageId] of Object.entries(chatPages)) { + if (savedIds.has(pageId)) continue; + const named = claimOf(saved, chatId); + chatPages[chatId] = named !== undefined && savedIds.has(named) && currentPages.has(named) ? named : first; + } + + const sameClaims = + Object.keys(chatPages).length === Object.keys(saved.chatPages).length && + Object.entries(chatPages).every(([chatId, pageId]) => claimOf(saved, chatId) === pageId); + const samePages = pages.every((page, index) => page === saved.pages[index]); + const doc = sameClaims && samePages ? saved : { ...saved, pages, chatPages }; + return { doc, changed: doc !== saved, deletedNow: deletedClaims(current, doc), restored }; +} + +/** + * `doc` with the claims and `namedFor` marks a save's answer says were + * stored (`namedFor` maps page id to chat id). Nothing else changes, so newer + * edits in `doc` stay. A claim on a page `doc` no longer has goes to its + * first page, as a delete would move it. + */ +export function applyStoredClaims( + doc: DesignCanvas, + chatPages: Readonly<Record<string, string>>, + namedFor: Readonly<Record<string, string>> = {}, +): DesignCanvas { + const ids = new Set(doc.pages.map((page) => page.id)); + const first = doc.pages[0]!.id; + const claims = Object.fromEntries( + Object.entries(chatPages).map(([chatId, pageId]) => [chatId, ids.has(pageId) ? pageId : first]), + ); + const pages = doc.pages.map((page) => { + const named = Object.prototype.hasOwnProperty.call(namedFor, page.id) ? namedFor[page.id] : undefined; + if (named === page.namedFor) return page; + return named === undefined ? withoutNamedFor(page) : { ...page, namedFor: named }; + }); + return { ...doc, pages, chatPages: claims }; +} + +function withoutNamedFor(page: DesignPage): DesignPage { + if (page.namedFor === undefined) return page; + const { namedFor: _namedFor, ...rest } = page; + return rest; +} diff --git a/renderer/shared/design-canvas/pages.test.ts b/renderer/shared/design-canvas/pages.test.ts index 5bf46990c..9974f96ea 100644 --- a/renderer/shared/design-canvas/pages.test.ts +++ b/renderer/shared/design-canvas/pages.test.ts @@ -102,9 +102,29 @@ test("deleting a page removes its frames and comments", () => { assert.equal(deletePage(single, "page-1"), single, "the last page stays"); }); -test("deletePage drops chatPages entries for the deleted page", () => { +test("deletePage moves the deleted page's chats to the first page left", () => { const doc: DesignCanvas = { ...addPage(twoPages(), "p3"), chatPages: { "chat-1": "p3", "chat-2": "p2", "chat-3": "p3" } }; - assert.deepEqual(deletePage(doc, "p3").chatPages, { "chat-2": "p2" }); + assert.deepEqual(deletePage(doc, "p3").chatPages, { "chat-1": "page-1", "chat-2": "p2", "chat-3": "page-1" }); + // Deleting the first page moves its chats to the page that is first after it. + const first: DesignCanvas = { ...doc, chatPages: { "chat-1": "page-1", "chat-2": "p3" } }; + assert.deepEqual(deletePage(first, "page-1").chatPages, { "chat-1": "p2", "chat-2": "p3" }); +}); + +test("renaming a page stops it following its chat", () => { + const doc: DesignCanvas = { ...emptyDesignCanvas(), pages: [{ id: "page-1", name: "Landing", namedFor: "chat-1" }] }; + assert.equal(renamePage(doc, "page-1", "Landing"), doc, "the same name changes nothing"); + assert.deepEqual(renamePage(doc, "page-1", "Mine").pages, [{ id: "page-1", name: "Mine" }]); +}); + +test("duplicating a page copies neither namedFor nor claims", () => { + const doc: DesignCanvas = { + ...emptyDesignCanvas(), + pages: [{ id: "page-1", name: "Landing", namedFor: "chat-1" }], + chatPages: { "chat-1": "page-1" }, + }; + const copied = duplicatePage(doc, "page-1", "copy", () => "x"); + assert.deepEqual(copied.pages[1], { id: "copy", name: "Landing copy" }); + assert.deepEqual(copied.chatPages, { "chat-1": "page-1" }); }); test("pages move one place at a time and stop at the ends", () => { diff --git a/renderer/shared/design-canvas/pages.ts b/renderer/shared/design-canvas/pages.ts index d6beeb868..3a22691d9 100644 --- a/renderer/shared/design-canvas/pages.ts +++ b/renderer/shared/design-canvas/pages.ts @@ -39,12 +39,15 @@ export function addPage(doc: DesignCanvas, id: string, name?: string, after?: st return { ...doc, pages: [...doc.pages.slice(0, at), page, ...doc.pages.slice(at)] }; } -/** Renames a page. An empty name is refused. */ +/** + * Renames a page. An empty name is refused. A page made for a chat stops + * following that chat's title once it is renamed. + */ export function renamePage(doc: DesignCanvas, id: string, name: string): DesignCanvas { const clean = cleanName(name); const page = doc.pages.find((entry) => entry.id === id); if (!clean || !page || page.name === clean) return doc; - return { ...doc, pages: doc.pages.map((entry) => (entry.id === id ? { ...entry, name: clean } : entry)) }; + return { ...doc, pages: doc.pages.map((entry) => (entry.id === id ? { id: entry.id, name: clean } : entry)) }; } /** @@ -78,15 +81,19 @@ export function duplicatePage(doc: DesignCanvas, id: string, pageId: string, new } /** - * Deletes a page with its frames and comments, and forgets it as any chat's - * page. The last page cannot be deleted. A chat looking at it sees the first - * page instead (`viewPageId`). + * Deletes a page with its frames and comments. Chats whose page it was move + * to the first page left. The last page cannot be deleted. A chat looking at + * it sees its own page, else the first page, instead (`designTurnPages` in + * main, `useDesignView` in the renderer). */ export function deletePage(doc: DesignCanvas, id: string): DesignCanvas { const at = doc.pages.findIndex((page) => page.id === id); if (at < 0 || doc.pages.length <= 1) return doc; const pages = doc.pages.filter((page) => page.id !== id); - const chatPages = Object.fromEntries(Object.entries(doc.chatPages).filter(([, pageId]) => pageId !== id)); + const first = pages[0]!.id; + const chatPages = Object.fromEntries( + Object.entries(doc.chatPages).map(([chatId, pageId]) => [chatId, pageId === id ? first : pageId]), + ); return { ...doc, pages, @@ -143,7 +150,8 @@ export function moveFramesToPage(doc: DesignCanvas, ids: readonly string[], page * chat's earlier tool calls still name them, and are only given new ones * where the target already uses them, with groups, arrows and comments * following. A page or image frame's path goes through `pathMap` (old path to - * new); one whose file was not copied is dropped. `chatPages` is not copied. + * new); one whose file was not copied is dropped. `chatPages` is not copied, + * and the new pages are built as `{ id, name }`, so no `namedFor` comes over. * All or nothing: null when the result would pass the page, frame or comment * limit. `pageIds` are the new pages, in order (none when nothing came over). */ diff --git a/renderer/shared/design-canvas/schema.test.ts b/renderer/shared/design-canvas/schema.test.ts index 67f167d26..16c577c8d 100644 --- a/renderer/shared/design-canvas/schema.test.ts +++ b/renderer/shared/design-canvas/schema.test.ts @@ -137,7 +137,8 @@ test("caps pages at 200, frames at 4000 and comments at 2000", () => { assert.equal(many.doc.frames.filter((entry) => entry.pageId === "p10").length, 0, "the eleventh page has no room left"); assert.equal(many.doc.frames.filter((entry) => entry.pageId === "p9").length, 400); assert.equal(many.doc.comments.length, 2000); - assert.equal(many.dropped, 400 + 5); + // Five pages, 400 frames and five comments past the limits. + assert.equal(many.dropped, 5 + 400 + 5); }); test("a groupId naming a missing group is removed but the frame stays", () => { @@ -227,6 +228,34 @@ test("parses a v3 document and keeps chatPages entries that name existing pages assert.deepEqual(parsed(JSON.parse(JSON.stringify(doc))).doc, doc); }); +test("keeps namedFor only when it is a safe chat id", () => { + const { doc } = parsed( + canvas({ + pages: [ + { id: "a", name: "A", namedFor: "chat-1" }, + { id: "b", name: "B", namedFor: "../x" }, + { id: "c", name: "C", namedFor: 4 }, + ], + }), + ); + assert.deepEqual(doc.pages, [ + { id: "a", name: "A", namedFor: "chat-1" }, + { id: "b", name: "B" }, + { id: "c", name: "C" }, + ]); + assert.deepEqual(parsed(JSON.parse(JSON.stringify(doc))).doc.pages, doc.pages); +}); + +test("parse keeps the first 2 000 chatPages entries and counts the rest in dropped, without setting the canvas aside", () => { + const chatPages: Record<string, string> = {}; + for (let index = 0; index < DESIGN_CANVAS_LIMITS.chatPages + 3; index += 1) chatPages[`chat-${index}`] = "page-1"; + const { doc, dropped } = parsed(canvas({ chatPages })); + assert.equal(Object.keys(doc.chatPages).length, DESIGN_CANVAS_LIMITS.chatPages); + assert.equal(doc.chatPages["chat-0"], "page-1"); + assert.equal(doc.chatPages[`chat-${DESIGN_CANVAS_LIMITS.chatPages}`], undefined); + assert.equal(dropped, 3); +}); + test("keeps chatId on artifact frames and comments only when it is a safe chat id", () => { const comment = (id: string, chatId: unknown) => ({ id, diff --git a/renderer/shared/design-canvas/schema.ts b/renderer/shared/design-canvas/schema.ts index b7856b785..90696e936 100644 --- a/renderer/shared/design-canvas/schema.ts +++ b/renderer/shared/design-canvas/schema.ts @@ -193,15 +193,22 @@ export type DesignComment = { export type DesignViewport = { x: number; y: number; zoom: number }; -/** A page of the canvas. Where each chat looks at it is that chat's view (`view.ts`). */ -export type DesignPage = { id: string; name: string }; +/** + * A page of the canvas. Where each chat looks at it is that chat's view + * (`view.ts`). `namedFor` is the chat a page was made for: it takes that + * chat's title until someone renames it (`chat-pages.ts`). + */ +export type DesignPage = { id: string; name: string; namedFor?: string }; export type DesignCanvas = { version: 3; revision: number; /** At least one, in the order the page picker lists them. */ pages: DesignPage[]; - /** The page each chat works on, by chat id; every value is one of `pages`. */ + /** + * Each chat's own page, by chat id; every value is one of `pages`. Only + * main writes it (`chat-pages.ts`); a person's save is merged in the store. + */ chatPages: Record<string, string>; frames: DesignFrame[]; comments: DesignComment[]; @@ -220,6 +227,7 @@ export const DESIGN_CANVAS_LIMITS = { comments: 2000, pages: 200, pageNameChars: 60, + chatPages: 2000, minSize: 40, maxSize: 8000, maxCoord: 1_000_000, @@ -366,8 +374,8 @@ export function parseDesignCanvas(value: unknown): DesignCanvasParseResult { if (!Array.isArray(value.comments)) issues.push("The canvas comments are not a list."); if (issues.length > 0) return { ok: false, issues }; - let dropped = 0; - const pages = parsePages(value.pages); + const { pages, dropped: droppedPages } = parsePages(value.pages); + let dropped = droppedPages; const pageIds = new Set(pages.map((page) => page.id)); const firstPageId = pages[0]!.id; const pageOf = (raw: unknown) => { @@ -376,8 +384,16 @@ export function parseDesignCanvas(value: unknown): DesignCanvasParseResult { }; const chatPages: Record<string, string> = {}; if (isRecord(value.chatPages)) { + let kept = 0; for (const [chatId, pageId] of Object.entries(value.chatPages)) { - if (isDesignChatId(chatId) && typeof pageId === "string" && pageIds.has(pageId)) chatPages[chatId] = pageId; + if (!isDesignChatId(chatId) || typeof pageId !== "string" || !pageIds.has(pageId)) continue; + // Past the cap an entry is dropped and counted, as frames are, so the canvas is never set aside. + if (kept >= DESIGN_CANVAS_LIMITS.chatPages) { + dropped += 1; + continue; + } + chatPages[chatId] = pageId; + kept += 1; } } @@ -472,22 +488,28 @@ export function withRemovedPagePaths<T extends DesignCanvas>( return (removedPagePaths.length > 0 ? { ...rest, removedPagePaths } : rest) as T; } -/** The pages of a document; never empty, and ids are unique. */ -function parsePages(value: unknown): DesignPage[] { +/** The pages of a document; never empty, and ids are unique. `dropped` counts pages past the limit. */ +function parsePages(value: unknown): { pages: DesignPage[]; dropped: number } { const pages: DesignPage[] = []; const ids = new Set<string>(); + let dropped = 0; if (Array.isArray(value)) { for (const raw of value) { - if (pages.length >= DESIGN_CANVAS_LIMITS.pages) break; if (!isRecord(raw)) continue; const id = identifier(raw.id); if (!id || ids.has(id)) continue; ids.add(id); - pages.push({ id, name: pageName(raw.name, pages.length) }); + if (pages.length >= DESIGN_CANVAS_LIMITS.pages) { + dropped += 1; + continue; + } + const page: DesignPage = { id, name: pageName(raw.name, pages.length) }; + if (isDesignChatId(raw.namedFor)) page.namedFor = raw.namedFor; + pages.push(page); } } if (pages.length === 0) pages.push({ id: DESIGN_FIRST_PAGE_ID, name: "Page 1" }); - return pages; + return { pages, dropped }; } function pageName(value: unknown, index: number): string { diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index dafb812ad..f77b0d46b 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -353,6 +353,8 @@ "main/windows/design-window-core.test.ts", "main/services/design-canvas/store.test.ts", "main/services/design-canvas/views.test.ts", + "main/services/design-canvas/title-follow.test.ts", + "main/services/design-canvas/liveness.test.ts", "main/services/design-canvas/carry.test.ts", "main/handlers/design-canvas.test.ts", "main/services/design-canvas/resolve-core.test.ts", @@ -1245,6 +1247,7 @@ "renderer/shared/design-canvas/view.test.ts", "renderer/shared/design-canvas/canvas-summary.test.ts", "renderer/shared/design-canvas/pages.test.ts", + "renderer/shared/design-canvas/chat-pages.test.ts", "renderer/shared/design-canvas/comments.test.ts", "renderer/shared/design-canvas/connectors.test.ts", "renderer/shared/design-canvas/drawing.test.ts", diff --git a/tests/e2e/design-canvas.spec.ts b/tests/e2e/design-canvas.spec.ts index dd89a14e4..0742dff47 100644 --- a/tests/e2e/design-canvas.spec.ts +++ b/tests/e2e/design-canvas.spec.ts @@ -7,6 +7,7 @@ import { capture, chooseWorkspace, designCanvas, + previewAppearance, sendFirstMessage, setDisplayWidth, setWindowWidth, @@ -183,7 +184,8 @@ async function savedCanvases(userDataDir: string): Promise< Array<{ version: number; frames: Array<{ kind: string; text?: string; title: string; pageId: string }>; - pages: Array<{ id: string; name: string }>; + pages: Array<{ id: string; name: string; namedFor?: string }>; + chatPages: Record<string, string>; }> > { const root = path.join(userDataDir, "design-canvases"); @@ -1591,3 +1593,138 @@ test("pages Aiden writes land on the canvas by themselves and follow its edits, await waitForToastsToClear(page); await capture(page, "1440-canvas-live-pages"); }); + +const sidebarChat = (page: Page, title: string) => + page.locator("[data-sidebar]").getByRole("button", { name: new RegExp(`^${title}`, "u") }).first(); + +/** Opens a sidebar chat row's menu from the keyboard, where the row is. */ +async function openChatRowMenu(page: Page, title: string): Promise<void> { + await sidebarChat(page, title).focus(); + await page.keyboard.press("Shift+F10"); +} + +/** Light and dark screenshots in the test's output folder, so a sandboxed run brings them back; also `capture`'s folder when set. */ +async function captureToResults(page: Page, name: string): Promise<void> { + await capture(page, name); + for (const scheme of ["light", "dark"] as const) { + await previewAppearance(page, scheme); + await expect(page.locator("html")).toHaveAttribute("data-appearance-scheme", scheme); + await page.screenshot({ path: test.info().outputPath(`${name}-${scheme}.png`), animations: "disabled" }); + } + await previewAppearance(page, null); +} + +test("two chats on one workspace each get their own page, keep it across switches, and a page another chat uses is not deleted without force", async ({ + aiden, +}) => { + const { app, page, lmStudio, userDataDir } = aiden; + const A_TITLE = "Design the Northwind landing page"; + const B_TITLE = "Sketch the pricing table"; + const B_RENAMED = "Pricing table for launch"; + const composer = page.locator("textarea").first(); + const pickerTrigger = () => designCanvas(page).getByRole("button", { name: /^Page: /u }); + const canvasDoc = async () => (await savedCanvases(userDataDir))[0]; + + // 1. Chat A opens design mode on a fresh canvas and claims Page 1 as it is. + await openDesignChat(app, page); + await expect.poll(async () => Object.keys((await canvasDoc())?.chatPages ?? {}).length).toBe(1); + const first = (await canvasDoc())!; + const [chatA, aPage] = Object.entries(first.chatPages)[0]!; + expect(aPage).toBe(first.pages[0]!.id); + expect(first.pages.map((entry) => entry.name)).toEqual(["Page 1"]); + + // 2. A's turn places a note on its page. + const aPrompt = "Two chats test: note the Northwind hero."; + const aNote = lmStudio.enqueueToolScenario!({ + prompt: aPrompt, + calls: [{ name: "canvas_place_frame", arguments: { kind: "note", title: "Northwind hero", text: "A bigger headline" } }], + finalText: "Placed a note for the hero.", + }); + await composer.fill(aPrompt); + await composer.press("Enter"); + await expect.poll(() => aNote.completed).toBe(true); + expect(aNote.error).toBeUndefined(); + await expect(frame(page, "Northwind hero")).toBeVisible(); + + // 3. Chat B in the same workspace gets a page of its own, named after it (its title is set by hand, so it has settled). + await page.getByRole("button", { name: "New Agent", exact: true }).click(); + await chooseWorkspace(page, new RegExp(`^${WORKSPACE_NAME}`, "u")); + await sendFirstMessage(page, B_TITLE); + await typeSlashCommand(page, "/design"); + await expect(pickerTrigger()).toHaveAccessibleName(`Page: ${B_TITLE}`); + await expect(frame(page, "Northwind hero")).toHaveCount(0); + await expect.poll(async () => Object.keys((await canvasDoc())?.chatPages ?? {}).length).toBe(2); + const second = (await canvasDoc())!; + const chatB = Object.keys(second.chatPages).find((id) => id !== chatA)!; + const bPage = second.pages.find((entry) => entry.namedFor === chatB); + expect(bPage?.name).toBe(B_TITLE); + expect(second.chatPages[chatB]).toBe(bPage!.id); + expect(second.chatPages[chatA]).toBe(aPage); + + // 4. B's turn places a note on B's page; each chat keeps its page across switches. + const bPrompt = "Two chats test: note the pricing tiers."; + const bNote = lmStudio.enqueueToolScenario!({ + prompt: bPrompt, + calls: [{ name: "canvas_place_frame", arguments: { kind: "note", title: "Pricing tiers", text: "Three tiers" } }], + finalText: "Placed a note for the tiers.", + }); + await composer.fill(bPrompt); + await composer.press("Enter"); + await expect.poll(() => bNote.completed).toBe(true); + expect(bNote.error).toBeUndefined(); + await expect(frame(page, "Pricing tiers")).toBeVisible(); + expect((await canvasDoc())!.frames.find((entry) => entry.title === "Pricing tiers")?.pageId).toBe(bPage!.id); + + await sidebarChat(page, A_TITLE).click(); + await expect(pickerTrigger()).toHaveAccessibleName("Page: Page 1"); + await expect(frame(page, "Northwind hero")).toBeVisible(); + await expect(frame(page, "Pricing tiers")).toHaveCount(0); + await sidebarChat(page, B_TITLE).click(); + await expect(pickerTrigger()).toHaveAccessibleName(`Page: ${B_TITLE}`); + await expect(frame(page, "Pricing tiers")).toBeVisible(); + await expect(frame(page, "Northwind hero")).toHaveCount(0); + + // 5. B's picker marks its own page and counts A on Page 1, naming no chat. + await pickerTrigger().click(); + await expect(page.getByRole("menuitemradio", { name: `${B_TITLE}, This chat`, exact: true })).toBeVisible(); + await expect(page.getByRole("menuitemradio", { name: "Page 1, 1 chat", exact: true })).toBeVisible(); + await waitForToastsToClear(page); + await captureToResults(page, "1440-canvas-two-chats"); + await page.keyboard.press("Escape"); + await expect(page.getByRole("menuitemradio")).toHaveCount(0); + + // 6. Aiden in B won't delete A's page without force. + const deletePrompt = "Two chats test: delete Page 1."; + const refused = lmStudio.enqueueToolScenario!({ + prompt: deletePrompt, + calls: [{ name: "canvas_page", arguments: { action: "delete", page: "Page 1" } }], + finalText: "Page 1 is another chat's page, so I left it.", + }); + await composer.fill(deletePrompt); + await composer.press("Enter"); + await expect.poll(() => refused.completed).toBe(true); + expect(JSON.stringify(refused.results)).toContain("1 other chat"); + expect((await canvasDoc())!.pages.some((entry) => entry.id === aPage)).toBe(true); + + // 7. Renaming B from the sidebar renames the page made for it. + await openChatRowMenu(page, B_TITLE); + await page.getByRole("menu").getByRole("menuitem", { name: "Rename", exact: true }).click(); + const rename = page.getByRole("dialog", { name: "Rename chat" }); + await rename.getByRole("textbox").fill(B_RENAMED); + await rename.getByRole("button", { name: "Save" }).click(); + await expect(rename).toBeHidden(); + await expect(pickerTrigger()).toHaveAccessibleName(`Page: ${B_RENAMED}`); + await expect.poll(async () => (await canvasDoc())!.pages.find((entry) => entry.id === bPage!.id)?.name).toBe(B_RENAMED); + + // 8. Deleting B takes its claim and mark off the canvas; its page and note stay. + await openChatRowMenu(page, B_RENAMED); + await page.getByRole("menu").getByRole("menuitem", { name: "Delete", exact: true }).click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Delete", exact: true }).click(); + await expect(sidebarChat(page, B_RENAMED)).toHaveCount(0); + await expect.poll(async () => Object.keys((await canvasDoc())!.chatPages)).toEqual([chatA]); + const after = (await canvasDoc())!; + const kept = after.pages.find((entry) => entry.id === bPage!.id); + expect(kept?.name).toBe(B_RENAMED); + expect(kept?.namedFor).toBeUndefined(); + expect(after.frames.find((entry) => entry.title === "Pricing tiers")?.pageId).toBe(bPage!.id); +});