diff --git a/.memory/design-mode.md b/.memory/design-mode.md index 004f63ad4b..8aa6d91cc8 100644 --- a/.memory/design-mode.md +++ b/.memory/design-mode.md @@ -1,5 +1,7 @@ # Design mode +v2 (2026-11-23): owner approved the live app canvas spec `docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md` (live dev-server routes as frames, localhost-only, one canvas per workspace with a page per chat, Aiden-controlled dev server, Inspect tool X, DESIGN.md as the design-system source, React mock apps for non-web React projects). Pre-build checks are in spec §11 (`@google/design.md` 0.4.0: Apache-2.0, `/linter` `lint(content)` offline; v1 `design-system*.ts` used only by `main.ts`, deleted in 3b; no default-session `webRequest` listener exists; E2E fixture symlinks root `node_modules`). The PR split was revised in §8: 1a must move every `activePageId` reader at once (tools, placement, focus with `pageId`, renderer view store), and 1b only writes `chatPages` and handles lifecycle. Phase 1a plan: `docs/superpowers/plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md`, built 2026-11-23 on `t3/design-mode-live-app-plan`, PR #894 opened 2026-11-23 after code review fixes (main `d5b1b14e9`, renderer `f78a6b0ef`); see "v2 Phase 1a" below. Key 1a decisions: `DesignChatCanvases` adapter (chat → workspace) so callers keep chat ids; a `.layout-v3` marker in `design-canvases/` triggers the one-time wipe; `designCanvas:updated` carries `workspaceId`; each No workspace chat has its own hidden workspace and so its own canvas (only legacy chats with no `workspaceId` share `default`). An adversarial plan review on 2026-11-23 added amendments A1–A12 to the 1a plan (origin `chatId` on updates, comment tray filtered by chat in 1a, per-window ordered views, Aiden's page change applied in main at once, attach merges the hidden canvas). An adversarial spec review the same day added §12 S1–S15: subframe `will-redirect` fix, a per-workspace start consent with a script-text hash plus a read-only refusal, a fail-closed null-frame rule, `file://` cookie handling, a narrowed network guarantee, a `design` job owner, an install stamp, a permission dispatcher shared with Gemini Live, no `allow-modals`, untrusted bridge output, Vite-client HMR, loopback binding, and 2b–5 behind `AIDEN_EXPERIMENTAL_DESIGN_LIVE` until Phase 7. + Status: active. P0 (retire Studio), P1 (layout shell) and P2 (canvas and frames, Tasks 1–7) are done. The Mac Studio work was pushed as `claude/design-mode-deep-dive` on 2026-11-05, then merged with `origin/main` on `claude/project-thread-29fzrr` (the PR branch). P3 (Aiden on the canvas) is done (2026-11-05, P3a–P3d, on the PR #778 branch), plan `docs/superpowers/plans/2026-11-05-design-mode-p3-aiden-on-canvas.md`. P3a (canvas tools) is done: `main/services/design-canvas/canvas-tools.ts` (four tools, 20 calls per turn at the time, 60 now, `designCanvasToolsAllowed` gate, `DESIGN_MODE_PROMPT_SECTION`), wired in `llm-client.ts` as the `aiden.design-canvas` runtime extension (static prompt section; since 2026-11-18 the `canvasPromptLine` counts go to the transcript as a `design-canvas-status` section note via `withCanvasStatusNote`, only when they changed, instead of a volatile system prompt line). P3b (artifact frames) is done: `artifact-frames.ts` places committed `render_artifact` visuals after `generativeUiArtifactStore.commit` (never on a failed turn), same-title Aiden frames swap `mediaId` and keep their box; `ArtifactNode` keys its loaded src by mediaId. P3c (skill) is done: `design-canvas/skill.ts` (`aiden-design`, `DESIGN_CANVAS_SKILLS`), registered in `skill-registry-main.ts` only when the flag is on, dropped by `withoutSkills` unless `designCanvasOffered` in llm-client, and from Remote and Telegram catalogs. P3d is done: `design-mode-tool.ts` (`DesignModeConsent`, `design_mode`, on-demand), `canvas-snapshots.ts`, card `renderer/design/design-mode-consent.tsx`, focus store `renderer/design/canvas-focus-requests.ts`; canvas tools held back and added by `withEnteredCanvasTools` after Enter; new tests must also go in `scripts/ci-test-registry.json` or `npm test` fails its registry check. P4 plan (owner chose everything in their reference screenshots): `docs/superpowers/plans/2026-11-05-design-mode-p4-full-canvas.md`; P4a built 2026-11-05, P4e, P4b, P4c, P4d, P4f, P4g and P4h built 2026-11-06, P5 (launch) built 2026-11-06. Placement moved to `renderer/shared/design-canvas/placement.ts`; summaries in `canvas-summary.ts`. P4–P5 plans are written before each phase. - Spec: `docs/superpowers/specs/2026-10-31-design-mode-design.md`. Plans: `docs/superpowers/plans/2026-10-31-design-mode-p0-retire-studio.md`, `docs/superpowers/plans/2026-10-31-design-mode-p1-layout.md`. @@ -353,3 +355,13 @@ Deviations from the P1 plan: - Live's idle corner pill left in #855, but design mode still kept `--aiden-dock-gutter` (96 px) on the chat column's right only, so the narrow design chat showed an empty lane right of the composer. The design column now uses `--design-mode-gutter` (16 px) on both sides, and the design-mode-only wide inline visual rule above is gone: the generic rule fills the slim column. - Outside design mode, `.aiden-dock-inset` keeps 6rem per side at usual widths (reading width unchanged) but gives way down to `--chat-column-gutter-min` (1rem) when the pane is narrow; Full narrows like Default; `[data-chat-card-inset]` keeps the fixed 6rem because Quick View's docking math assumes it. - Live's transient corner pill (connecting, stopping, disconnected, approval) now rises just above the composer when it would cover it (`liveCornerClearance` in `use-live-ribbon-placement.ts`). + +## v2 Phase 1a: one canvas per workspace (2026-11-23) + +- Document: canvas v3 has no `activePageId` and no page viewport; frames and comments may carry `chatId` (the chat that made them). One file per workspace, `userData/design-canvases/.json`. A folder without `.layout-v3` is wiped once (no migration code). `DesignChatCanvases` maps chat → workspace and refuses a removed workspace ("This workspace is no longer available."). +- Views live only in main (`DesignCanvasViews`, `views.ts`), persisted per workspace in `userData/design-canvas-views/.json` as `{ [chatId]: { pageId, viewports, focusId } }`, written at most once a second. No `localStorage` copy (A17). The renderer (`renderer/design/use-design-view.ts`) reads `designCanvas:view:get` on mount, reports `{ workspaceId, view, focusId }` 250 ms after the last change, flushes then sends `{ mounted: false }` on unmount. `kept()`/`view:get` also return per-page `viewports` (a deviation from the plan) so each page opens where the chat left it. Pans, zooms and page switches never save the document or make an undo step. +- Focus: `designCanvas:focus { chatId, pageId, frameIds, focusId? }`; the renderer applies the page even when the fit is skipped (A19) and a focus without a page uses its frames' page (A7). Saves pass `{ workspaceId, undone? }`; a `moved` answer carries the newer `workspaceId`, the renderer drops its edits and the region remounts (A23). Updates are filtered by `workspaceId`; only this chat's `aidenTurn`/`step` updates become undo steps (A2). +- 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`. diff --git a/PRODUCT.md b/PRODUCT.md index da55b26668..d9c937a42e 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. Pages stay workspace HTML files served only to that chat's 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 an empty canvas), 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. 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. - 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 55dc54b6f1..f691dfeda4 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -63,6 +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 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-p1a-workspace-canvas.md b/docs/superpowers/plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md new file mode 100644 index 0000000000..e0de9b7ba6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md @@ -0,0 +1,427 @@ +# Design mode v2 — Phase 1a: workspace canvas document — 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:** Make the design canvas one document per workspace, with each chat's current page and viewport living outside that document. Leave design mode working exactly as today for one chat. + +**Architecture:** The store keeps one file per workspace id. A thin adapter resolves a chat to its workspace, so most callers keep passing a chat id. The view (page, viewport, canvas size) moves out of the document: +- main owns it and persists it per workspace in `userData/design-canvas-views/` (A17); +- the renderer reports it to main over `designCanvas:view`; +- main holds it in memory in `DesignCanvasViews`, and tools read it from there. + +Every `doc.activePageId` reader becomes an explicit `pageId` taken from the chat's view. Page changes Aiden asks for become `designCanvas:focus {chatId, pageId, frameIds}` IPC instead of document writes. + +**Tech Stack:** TypeScript (ESM), Electron 43 main, React 19 renderer with xyflow, `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, §8 (row 1a), §11.6. + +## Global Constraints + +- Pre-1.0: no migration. Old per-chat canvas files are deleted on first start (§6.1, §11.6). +- File: `userData/design-canvases/.json`. The workspace id must pass `isWorkspaceArtifactWorkspaceId` (`renderer/shared/workspace-artifacts.ts:265`). Each No workspace chat has its own hidden workspace record (`noWorkspace: true`), so it gets its own canvas. Only legacy chats with no `workspaceId` resolve through `persistedChatWorkspaceId` to `"default"` and share that canvas. The renderer normalizes with `persistedChatWorkspaceId` too (amendment A11). +- `version: 3`. `activePageId` and `pages[].viewport` are removed. `chatPages: Record` is added: parsed and kept valid, but written by nothing until 1b. +- Optional `chatId` on artifact frames and on comments, stamped when they are created. +- Limits: + - `pages` 200; + - `frames` 4000, `framesPerPage` 400 (unchanged); + - `comments` 2000; + - 16 MiB document cap unchanged. +- Panning, zooming and switching pages never call `change()`, never save and are never undo steps. +- *(Superseded by A17.)* Views are owned by main and persisted to `userData/design-canvas-views/.json`; the renderer keeps no view copy and no `localStorage`. +- `designCanvas:updated` payload: `{workspaceId, chatId, revision, aidenTurn?, step?}`, where `chatId` is the chat whose action caused the change (A2). `designCanvas:focus` payload: `{chatId, pageId?, frameIds}`. +- Handlers keep `chatId` as their argument and authority check: an attended chat, with the design-mode rule each handler has today. +- Design mode stays desktop-only and out of the Remote projection. +- AGENTS.md: + - no source-grep tests; + - new test files are registered in `scripts/ci-test-registry.json` and a `package.json` test script, then `npm run test:ci-policy` is run; + - docs change in this PR; + - window-opening E2E runs through `npm run test:e2e:space`. + +## Review Focus + +1. **Two chats, one workspace, one window.** A save from chat A's canvas must reach chat B's canvas on the same workspace through `{workspaceId}`, and B must refetch. Switching between them never jumps either chat's page. Test: Task 3 (handler broadcast) and Task 7 (sync filters on `workspaceId`). +2. **The view names a deleted page** (another chat deleted it). The canvas shows the first page and does not crash. Tools default to the first page. Test: Task 1 (`viewPageId`) and Task 7 (the canvas shows the first page). +3. **The views file is missing or corrupt** (A17). The canvas opens on the first page at the default viewport. Test: Task 7. +4. **A stale v2 file at a workspace path** (a downgrade and re-upgrade, or a hand copy). Parse refuses it, and the store sets it aside as corrupt instead of crashing. Test: Task 3. +5. **Chat deleted while another chat on the workspace has the canvas open.** The shared file survives, and the deleted chat's artifact frames show their missing state rather than an error. Test: Task 8. + +## Review amendments (2026-11-23) + +An adversarial review of this plan against the code found the problems below, each verified. They are part of the plan: where an amendment and a task disagree, the amendment wins. Each names the task that owns it and the test that pins it. + +- **A1. Aiden's page change counts at once, with or without a window** (Task 5, with a renderer part in Task 7). + - When a tool shows or focuses a page (`canvas_page show`, `add` with show, `canvas_focus`, `canvas_arrange`), main sets that chat's view page immediately: `DesignCanvasViews.showPage(chatId, pageId)` creates a view if none exists. Later tool calls in the same turn read it. + - *(Revised in round 2: no `seq`.)* Each Aiden page change gets a per-chat `focusId` (an increasing integer kept by main). Main sends it in `designCanvas:focus {chatId, pageId, frameIds, focusId}`. Every view report echoes the last `focusId` that renderer applied. Main ignores a report whose echoed `focusId` is older than the chat's current one. A report from a fresh mount echoes nothing (`0`) and is likewise ignored while a newer Aiden change is pending. + - On mount, the canvas asks main for the chat's kept view (`designCanvas:view:get`, answered from `DesignCanvasViews`: page, viewport, `focusId`). It prefers that over `localStorage`, which is only the fallback when main has no view (first launch after a restart). + - The renderer applies a focus request's `pageId` even when it skips the fit because the person interacted within `FOCUS_QUIET_MS`. + - Test: `canvas_page add` with show, then `canvas_place_frame` with no page, puts the frame on the new page, both with a `focus` dep and without one. +- **A2. Another chat's change is never this chat's undo step** (Tasks 3 and 7). `designCanvas:updated` carries the origin `chatId`. The renderer records `aidenTurn` and `step` only when `update.chatId === chatId`; otherwise it records `null` (a change carried into every step). Test (`use-design-canvas.test.tsx`): after an update with chat A's `aidenTurn`, undo in chat B leaves A's frames in place and B's redo stack survives. +- **A3. Comment tray filtered by chat in 1a, not 1b** (Tasks 2 and 7). + - `queuedComments(doc, chatId)` and `markCommentsSent(doc, ids, sentAt, chatId)` consider only comments with `comment.chatId === chatId`. Comments without a `chatId` are none in v3, because the wipe removes v1/v2 documents. + - The tray, its badge and send all use the filtered list. + - Test: two chats each queue comments, and each tray and send shows only its own. +- **A4. Main keeps a chat's last page after its canvas unmounts** (Tasks 4 and 5). + - `set(..., null)` marks the canvas unmounted but keeps the last `pageId` and viewport; `mounted()` counts only mounted canvases. + - The per-message `DesignViewState` (`canvas-summary.ts:20`) gains an optional `pageId`, and `parseDesignViewState` accepts that key (it refuses unknown keys today). + - *(Revised in round 2.)* The page tools use, in order: a page Aiden showed earlier in this turn (A1), then the message's `pageId`, then the registry's kept page, then the first page. `canvasPromptLine` uses the same order minus the first step. + - Test: unmount, then a background placement for that chat lands on its last page. +- **A5. Views keyed by chat, ordered by `focusId`, and cleaned up** (Task 4). *(Revised in round 2: Aiden has a single main window (`main/index.ts` `mainWindow`), and quick chat and the pill never mount design UI, so per-window keying is dropped.)* + - `DesignCanvasViews` stores one view per `chatId`, with a `mounted` flag and the `focusId` (A1). + - When the main window is destroyed, every view is marked unmounted; pages are kept. + - A `null` report skips `requireChat` (it only validates the id), so an unmount after delete still marks the view unmounted. + - `forget(chatId)` runs on chat delete, beside the other per-chat cleanups in `chat-application-service-main.ts`. + - Tests: a report echoing an older `focusId` is ignored; switching chats A→B→A in one window restores A's kept page. +- **A6. Artifact swap stays within its chat; the Code tab reads through the owner** (Tasks 6 and 8). + - `artifact-frames.ts`'s same-title swap only matches frames whose `chatId` equals the acting chat. + - `designCanvas:source` reads an artifact through `frame.chatId ?? chat.id`, with the same workspace check as preview and export. + - Tests: chat B's same-title visual places a new frame instead of swapping chat A's; the Code tab of A's artifact opened from B shows its source. +- **A7. Focus without a page finds the frames' page** (Task 7). When a focus request has no `pageId`, the renderer takes it from the first focused frame's `pageId` in the document. Main's own senders (`designPagesOnEntry` in `chat-application-service-main.ts:62`, `placeImages` in `llm-client.ts`) also include `pageId`. Test: focus with frames on another page switches to it and fits them. +- **A8. Attaching a No workspace chat keeps its canvas when its files come along** (Task 8). *(Revised in round 2.)* + - When: only when `attachToWorkspace` copies the files (`fileAction === "copy"`) and the hidden folder is not a legacy shared scratch (`sharedLegacyScratch` false, `chat-application-service.ts` ~582). Otherwise the hidden canvas is not merged; it is deleted with the hidden workspace (A13), and PRODUCT.md says that attaching without copying files leaves the canvas behind. + - How: `appendCanvasPages(target, source, { label, pathMap, newId })` in `pages.ts`. + - Each source page with frames becomes a new target page named `" · "`. + - Frame and comment ids are kept, and re-id'd only on a collision, with `groupId`, `frameId` and connector links remapped. That keeps the chat's earlier tool calls valid. + - `file` and `image` frame paths are rewritten through `pathMap`, built from the attach's `copiedPaths`; frames whose file wasn't copied are dropped. + - `chatPages` is not copied. + - Within the limits it's all or nothing. Over a limit, nothing is merged. + - After a merge, main calls `designCanvasViews.showPage(chatId, firstMergedPageId)`. + - Tests: two pages with a group and a comment merge with links intact and ids kept; a path renamed into `aiden-scratch/` is rewritten; over the limit, the target is unchanged. +- **A9. One workspace id per operation** (Task 3). + - The handler resolves the workspace once, from the chat it checked: `persistedChatWorkspaceId(chat.workspaceId)`. + - Store calls take that id. `DesignChatCanvases` methods return `{ doc | result, workspaceId }`, and the broadcast uses the returned id rather than resolving again. + - `saveDesignCanvas` sends the renderer's expected `workspaceId`. *(Revised in round 2.)* When it differs from the chat's current workspace, main answers `{ok: false, reason: "moved"}`. The renderer treats that as final: it drops the session's unsent edits, clears its guard state (so quit doesn't ask about them) and remounts. The canvas is keyed `${workspaceId}:${chatId}` in `design-canvas-region.tsx`. + - Test: a save that names W1 for a chat now in W2 returns `moved`, and W2's file is unchanged; the renderer session drops its edits and reports no unsaved work. +- **A10. Entry placement checks the chat's page, not the whole canvas** (Task 6). `written-pages.ts`'s `onlyIfEmpty` tests `framesOnPage(doc, targetPage).length > 0`, where the target page is the chat's page in A4's order. *(Added in round 2.)* When the chat has no view at all and that page has frames, the entry adds a new page named after the chat title, places onto it, and calls `designCanvasViews.showPage` for it. This is a claim without `chatPages`; 1b turns it into a real `chatPages` claim. Test: chat B, with no view, enters a workspace whose first page holds chat A's frames; a new page named after B is created, holds B's written pages, and is B's view page. Reword PRODUCT.md's "landing on an empty canvas" to "landing on the chat's empty page". +- **A11. The renderer normalizes the workspace id** (Task 7). The update filter and every view report use `persistedChatWorkspaceId(chat.workspaceId)`, so legacy chats match `"default"`. +- **A12. One shared layout promise; the 1b handoff** (Task 3). + - `ensureLayout` is a single promise per store instance, so concurrent first calls on different workspace chains run the wipe once. + - 1b note: `viewPageId` will gain the `chatPages[chatId]` fallback between the view and the first page (§6.1). + +Round 2 (a fresh adversarial review of the amended plan and spec) revised A1, A4, A5, A8, A9 and A10 above and added: + +- **A13. Lifecycle items moved from 1b into 1a** (Task 8). Without them 1a regresses cleanup. + - Workspace `remove` (`workspace-application-service.ts` ~177) deletes `.json` and its corrupt copies. That also covers a No workspace chat's hidden workspace released on delete. + - Chat delete removes the deleted chat's comments (`comment.chatId === chatId`) from its workspace canvas, through the store's `update`. + - Tests: removing a workspace deletes its canvas file; deleting chat A drops A's comments and leaves B's. +- **A14. Comments for Aiden are per chat too** (Task 5). + - `canvas_read` lists only comments whose `chatId` is the acting chat. + - `canvas_comment` refuses a comment whose `chatId` differs, with `"That comment belongs to another chat."`. + - Test: chat B's `canvas_read` omits A's sent comment, and B's `canvas_comment` on it is refused. +- **A15. `addComment` requires `chatId`** (Task 2). The input's `chatId` is required, not optional, so `tsc` flags every caller and no queued comment is hidden from every tray. +- **A16. Small fixes.** + - Task 3's `DesignCanvasUpdated` includes `chatId` (per A2). + - `broadcastDesignCanvasUpdate` takes the workspace id the store call returned, instead of resolving it again (A9). + - Task 7's file list includes `renderer/design/design-toolbar.tsx` (it uses `activeDesignPage`). + - Review Focus 1 reads "one window switching between two chats on one workspace". + +Round 3 (a review of the round-2 changes against the built code) found that most remaining races came from keeping a chat's view in two places: main's memory and the renderer's `localStorage`. A17 removes that split, and A18–A26 fix the rest. Where they conflict with A1, A4, A5, A8, A9, A10 or A13, these win. + +- **A17. Main owns the view and persists it; no `localStorage`** (Tasks 4 and 7; replaces the `localStorage` view store and A1's mount-time preference). + - `DesignCanvasViews` keeps, per chat, `{ workspaceId, pageId, viewports: Record, focusId, mounted }`. + - It persists per workspace to `userData/design-canvas-views/.json` (`{ [chatId]: { pageId, viewports, focusId } }`, without `mounted`), written at most once a second through `writeJsonAtomic`, read lazily on first use, and capped at the 200-page limit per chat. A missing or unreadable file reads as empty. + - Workspace remove deletes it with the canvas file (A13). Chat delete drops the chat's entry. + - The renderer keeps no copy. `canvas-view-store.ts` is not created. On mount, `designCanvas:view:get(chatId)` returns `{ pageId, viewport, focusId }`, where `viewport` is the stored one for that page or `DESIGN_FRESH_VIEWPORT`. + - Reports (`designCanvas:view`) are debounced at 250 ms. On unmount the pending report is sent first, then `{ mounted: false }`. + - The plan's Global Constraints line on the `localStorage` key, Task 7's `readDesignView`/`writeDesignView`, and Review Focus 3 are replaced by this. Review Focus 3 becomes "a corrupt views file opens the first page at the fresh viewport". + - Tests: views survive a store restart (a new instance on the same root); a corrupt file reads as empty; switching chats within 250 ms keeps the last page. +- **A18. A view's page change resets the viewport and mints a `focusId`** (Task 4). `showPage(chatId, pageId)` sets `pageId`, takes that page's viewport from `viewports` (or the fresh one), and increments `focusId`. A1, A8 and A10 all go through it. Test: `canvas_page show P2`, then a same-turn placement measures "in view" against P2's viewport, not P1's. +- **A19. Echo the highest `focusId` received; apply the page even when the fit is dropped** (Task 7). The renderer echoes the highest `focusId` it has seen from `view:get` or any focus event, whether or not it fitted. A focus request's `pageId` is applied even when the request is too old for `takeCanvasFocus` or the fit is skipped for a recent gesture. Test: a focus that expires before the canvas loads still switches the page, and the next report is accepted. +- **A20. One page resolver per turn** (Tasks 5 and 6). `chatPageFor({ turnShown, message, doc, chatId })` in `main/services/design-canvas/views.ts` applies A4's order. The registry part comes from `DesignCanvasViews`, so the resolver doesn't need it as a parameter. llm-client builds it once per turn, and passes it to the canvas tools, `placeWrittenPagesOnCanvas`, `placeImagesOnCanvas`, the artifact-frame placement and `canvasPromptLine`. Background and entry paths call it without `turnShown` and `message`. Test: a turn whose message says P1 while the registry says P2 places both a tool frame and an auto-placed written page on P1. +- **A21. Entry never duplicates pages** (Task 6; replaces A10's "new page" rule). + - Entry dedupes the chat's written pages against every page, as today. + - If some of them already have frames, the chat's page becomes the page holding the most of them (`showPage`), and only the missing ones are placed there. + - A new page named after the chat is created only when the chat has no view, its resolved page already holds frames, and at least one written page would actually be placed. + - Tests: re-entering after a restart with the pages already on page 1 creates no page and no frame; chat B entering a workspace whose page 1 is chat A's gets a "B" page holding B's pages. +- **A22. Attach merge: exact path pairs, a defined order, a stated outcome** (Task 8; refines A8). + - `copyScratchFilesToWorkspaceWithRollback` (`chat-attach-workspace.ts`) returns `copied: Array<{ from: string; to: string }>` (workspace-relative), and `pathMap` is built from those pairs. + - The merge runs right after `attachChatToWorkspace` commits and before `afterChatRemoved(oldWorkspaceId)`, reading the hidden canvas through `designWorkspaceCanvasStore` on its own chain. + - If the merge would exceed a limit, nothing is merged and the attach result carries `canvasCarried: false`, which the renderer shows as a short notice ("The canvas was too large to bring along."). The hidden canvas goes with the hidden workspace. + - Test: a target with a clashing top-level name maps `a.html` to `aiden-scratch/a.html` through the pairs. +- **A23. `moved` carries the new workspace id** (Tasks 3 and 7; refines A9). The answer is `{ ok: false, reason: "moved", workspaceId }`. `design-canvas-region.tsx` keys the canvas on the latest workspace id it knows, from that answer or from chat metadata, whichever is newer. A `moved` answer reaching a disposed session does nothing. Test: a `moved` answer remounts on the new id before the metadata broadcast arrives, and the next edit saves. +- **A24. View reports name their workspace** (Task 4). Every `designCanvas:view` report carries the renderer's `workspaceId`. Main drops a report whose workspace differs from the chat's current one. Test: a report naming W1 for a chat now in W2 leaves W2's view unchanged. +- **A25. Cleanup survives the delete and stays deleted** (Task 8; refines A13). + - Chat delete captures the workspace id from the chat record before deleting, and prunes comments and the view entry through `designWorkspaceCanvasStore.update(workspaceId, …)` and the views file, both in the pre-commit pass and in the post-commit repeat. + - `DesignChatCanvases` refuses when the chat's workspace record no longer exists (`"This workspace is no longer available."`), so no handler or flush can write `.json` back. + - Tests: a save in flight during chat delete does not bring back the deleted chat's comments; after workspace remove, a canvas save is refused and no file is written. +- **A26. Mounted state survives reloads and crashes** (Task 4). Every view is marked unmounted on the main window's main-frame `did-navigate` and on `render-process-gone`, as well as on window destroy. + +--- + +### Task 1: v3 schema and the view type + +**Files:** +- Modify: `renderer/shared/design-canvas/schema.ts` +- Create: `renderer/shared/design-canvas/view.ts` +- Test: `renderer/shared/design-canvas/schema.test.ts`, create `renderer/shared/design-canvas/view.test.ts` + +**Interfaces:** +- Produces: + - `DesignCanvas = { version: 3; revision; pages: DesignPage[]; chatPages: Record; frames; comments; removedPagePaths? }`. + - `DesignPage = { id: string; name: string }`. + - `DesignArtifactFrame.chatId?: string`, `DesignComment.chatId?: string`. + - `DESIGN_CANVAS_LIMITS.pages = 200`, `.frames = 4000`, `.comments = 2000`. + - `framesOnPage(doc, pageId: string)` (the argument is required). + - `frameShowingDesignPage(doc, path, pageId?: string)` prefers `pageId`'s frame, otherwise the first in document order. + - Removed: `activeDesignPage`, `withActiveViewport`. + - `view.ts`: + - `DesignChatView = { pageId: string; viewport: DesignViewport; size?: { w: number; h: number } }`; + - `parseDesignChatView(value: unknown): DesignChatView | null`; + - `viewPageId(doc: Pick, view?: { pageId?: string } | null): string`, which returns the view's page when it exists, otherwise `doc.pages[0].id`; + - `DESIGN_FRESH_VIEWPORT = { x: 0, y: 0, zoom: 1 }`. + +- [x] **Step 1: Write failing tests** + - `schema.test.ts`: + - `parses a v3 document and keeps chatPages entries that name existing pages and safe chat ids`: an entry pointing at a missing page and one with chat id `"../x"` are dropped. + - `refuses version 1 and 2 documents`: `ok: false`. + - `drops activePageId and page viewports from input`: the parsed pages have exactly the keys `id` and `name`. + - `keeps chatId on artifact frames and comments only when it is a safe chat id`. + - `caps pages at 200, frames at 4000 and comments at 2000`. + - Update existing cases that build v2 docs to build v3 docs through `emptyDesignCanvas()`. + - `view.test.ts`: + - `viewPageId falls back to the first page when the view's page is gone, or there is no view`. + - `parseDesignChatView clamps zoom to 0.1–4 and refuses a missing pageId or a non-finite viewport`. +- [x] **Step 2:** Run `npx tsx --test renderer/shared/design-canvas/schema.test.ts renderer/shared/design-canvas/view.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement. + - Safe chat id: reuse the regex from `store.ts` (`/^[A-Za-z0-9._:-]{1,160}$/u`), exported from `schema.ts` as `isDesignChatId`, so the store and the schema share it. + - `parseViewport` moves to `view.ts`. +- [x] **Step 4:** Rerun. Expected: PASS. `npx tsc -p renderer --noEmit` now lists every caller to fix in Tasks 2–8. Don't fix them here. +- [x] **Step 5:** Commit `feat(design): canvas document v3 with chat pages and no view state`. + +### Task 2: Shared helpers take an explicit page + +**Files:** +- Modify: + - `renderer/shared/design-canvas/pages.ts` + - `placement.ts`, `comments.ts`, `layers.ts`, `canvas-summary.ts`, `connectors.ts` (if it reads the active page) + - `renderer/design/canvas-adapter-core.ts`, `renderer/design/canvas-history-core.ts` +- Test: the matching `*.test.ts` beside each file. + +**Interfaces:** +- Consumes: Task 1. +- Produces: + - `addPage(doc, id, name?, after?: string)`: inserts after `after` (default: the end) and does not change any view. + - `showPage`: deleted. Showing a page is a view change. + - `duplicatePage(doc, id, pageId, newFrameId)`: unchanged signature, without the view copy. + - `deletePage(doc, id)`: also drops `chatPages` entries that pointed at it (1b adds reassignment). + - `placeFrame(doc, frame & { pageId: string }, view, newId)`: `pageId` is required. + - `addComment(doc, input & { pageId: string; chatId?: string })`: a frame's page still wins over `pageId`. + - `layerRows(doc, pageId)` (or the existing name, given a `pageId`). + - `canvasView(doc, view: DesignChatView | undefined, size?)`: the viewport is `view?.viewport ?? DESIGN_FRESH_VIEWPORT`. A view whose `pageId` differs from the page asked about uses the fresh viewport. + - `describeCanvas(doc, { pageId, view, ... })`: `onScreen` is `page.id === viewPageId(doc, view)`. + - `canvasPromptLine(doc, view: DesignChatView | undefined, selection?)`. + - `adaptCanvas(doc, pageId, ...)` in `canvas-adapter-core.ts`. + - `changesBetween` in `canvas-history-core.ts`: stops tracking `activePageId` and viewports. It still takes page names and order whole when they changed. + +- [x] **Step 1: Write failing tests** + - `pages.test.ts`: + - `addPage inserts after the given page and leaves chatPages alone`; + - `deletePage drops chatPages entries for the deleted page`. + - `canvas-summary.test.ts`: + - `canvasView uses the chat view's viewport only for the view's own page`; + - `canvasPromptLine marks the chat's view page as on screen`. + - `canvas-history-core.test.ts`: `undo after another chat switched pages does not change any page` (a doc with two pages: undoing a frame move must leave `pages` deep-equal). + - `placement.test.ts` / `comments.test.ts`: `placeFrame puts the frame on the given page`; `addComment stamps chatId`. +- [x] **Step 2:** Run each test file. Expected: FAIL. +- [x] **Step 3:** Implement. Delete the tests that only covered `showPage` or active-page tracking, and replace them with the cases above. +- [x] **Step 4:** Run `npx tsx --test renderer/shared/design-canvas/*.test.ts renderer/design/canvas-*-core.test.ts`. Expected: PASS. +- [x] **Step 5:** Commit `refactor(design): canvas helpers take the page explicitly`. + +### Task 3: Workspace-keyed store, chat adapter, workspace broadcast + +**Files:** +- Modify: + - `main/services/design-canvas/store.ts` + - `main/services/design-canvas/main.ts` + - `main/handlers/design-canvas.ts`, `main/handlers/design-canvas-main.ts` +- Test: `main/services/design-canvas/store.test.ts`, `main/handlers/design-canvas.test.ts` + +**Interfaces:** +- Consumes: Task 1. +- Produces: + - `DesignCanvasStore`: same methods, keyed by workspace id. `assertDesignCanvasWorkspaceId(id)` replaces `assertDesignCanvasChatId` for the store (`assertDesignCanvasChatId` stays for handlers). It gains a private `ensureLayout()`, run once per instance before the first read or delete: + - if `/.layout-v3` is missing, remove every entry in `root`; + - then write `.layout-v3`. + - `DesignChatCanvases` (new, in `store.ts`): + - constructed with `new DesignChatCanvases({ store, workspaceIdOf(chatId): Promise })`; + - exposes `get(chatId)`, `save(chatId, doc, base, options)`, `update(chatId, mutate, options)` and `workspaceIdOf(chatId)`; + - each method throws `"This chat is no longer available."` when `workspaceIdOf` returns null. + - Production: `designCanvasStore` (exported from `main.ts`) becomes the `DesignChatCanvases` instance, with `workspaceIdOf = async (id) => { const meta = await chatStore.getMeta(id); return meta ? persistedChatWorkspaceId(meta.workspaceId) : null; }`. The raw workspace store is exported as `designWorkspaceCanvasStore`. + - `DesignCanvasUpdated = { workspaceId: string; chatId: string; revision: number; aidenTurn?: string; step?: string }`. + - Callers keep calling `broadcast({chatId, revision, aidenTurn?, step?})`. A new `broadcastDesignCanvasUpdate(update)` in `main.ts` resolves the workspace through `designCanvasStore.workspaceIdOf` and sends the workspace payload. Its failures are logged and never thrown. + +- [x] **Step 1: Write failing tests** + - `store.test.ts`: + - `two chats of one workspace read and write the same document`, through `DesignChatCanvases` with a fake `workspaceIdOf`; + - `chats of different workspaces get different documents`; + - `first access removes v2 per-chat files and writes the layout marker, once`: seed `chat-1.json` with a v2 doc and `chat-1.json.corrupt-1`, call `get`, assert both are gone and `.layout-v3` exists; seed another file afterwards, call again, and assert it survives; + - `a v2 document at a workspace path is set aside as corrupt`; + - `refuses workspace ids that fail isWorkspaceArtifactWorkspaceId`. + - `design-canvas.test.ts` (handler): `a save broadcasts the chat's workspace id`. With a registered fake whose broadcast records payloads, saving through chat A yields `{workspaceId: "ws-1", revision: 1}`. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/store.test.ts main/handlers/design-canvas.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement. Rename the store's internal `chatId` parameters to `workspaceId`. Update the file header comment. +- [x] **Step 4:** Rerun. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): one canvas file per workspace`. + +### Task 4: Main view registry and `designCanvas:view` + +**Files:** +- Create: `main/services/design-canvas/views.ts` +- Modify: `main/handlers/design-canvas.ts`, `main/services/design-canvas/main.ts`, `renderer/preload-channels.ts`, `renderer/lib/ipc.ts` +- Test: create `main/services/design-canvas/views.test.ts`, extend `main/handlers/design-canvas.test.ts` + +**Interfaces:** +- Consumes: Task 1 `DesignChatView`, `parseDesignChatView`. Task 3 `DesignChatCanvases.workspaceIdOf`. +- Produces: + - `class DesignCanvasViews`: + - `set(chatId: string, workspaceId: string, view: DesignChatView | null): void` (null means the canvas unmounted); + - `get(chatId): DesignChatView | undefined`; + - `mounted(workspaceId): number`, the count of chats with a non-null view, for Phase 2's presence rule; + - `forget(chatId): void`. + - Exported singleton `designCanvasViews` from `main.ts`. + - IPC `designCanvas:view (chatId, view | null)`: + - `requireChat`; + - a view that fails `parseDesignChatView` throws `"Invalid canvas view."`; + - `null` clears it. + - Renderer `designCanvasApi.reportDesignCanvasView(chatId, view | null): Promise`. + +- [x] **Step 1: Write failing tests** + - `views.test.ts`: `mounted counts only chats with a view on that workspace`; `set null marks the view unmounted but keeps its page; forget drops the chat`. + - Handler: `designCanvas:view stores a parsed view and refuses a malformed one`; `designCanvas:view refuses a Bot chat`. +- [x] **Step 2:** Run them. Expected: FAIL. +- [x] **Step 3:** Implement. When the main window is destroyed, mark every view unmounted (A5). +- [x] **Step 4:** Rerun. Expected: PASS. Register `views.test.ts` in `scripts/ci-test-registry.json` and the `package.json` script that holds the other `design-canvas/*.test.ts` files, then run `npm run test:ci-policy`. +- [x] **Step 5:** Commit `feat(design): main keeps each chat's canvas view`. + +### Task 5: Canvas tools and prompt read the chat's view; focus carries the page + +**Files:** +- Modify: + - `main/services/design-canvas/canvas-tools.ts` + - `main/services/llm-client.ts` (the canvas wiring near lines 2714, 2972, 3009, 3082, 3114 and 3179) + - `renderer/design/canvas-focus-requests.ts` +- Test: `main/services/design-canvas/canvas-tools.test.ts`, `renderer/design/canvas-focus-requests` cases in an existing renderer design test, or a new `canvas-focus-requests.test.ts` + +**Interfaces:** +- Consumes: Tasks 1, 2 and 4. +- Produces: + - `DesignCanvasToolDeps.view?(): DesignChatView | undefined`. + - `DesignCanvasToolDeps.focus?(request: { pageId?: string; frameIds: string[] }): void`. + - `CanvasFocusRequest = { ids: string[]; pageId?: string; at: number }`. `canvasFocusFrom` keeps `pageId` when it is a string. +- Behaviour: + - `pageOf(doc, value, view)` defaults to `viewPageId(doc, view)`. + - `onScreen` compares with the view page. + - `canvas_page show` (and `add` with `show !== false`) calls `focus({pageId, frameIds: []})` instead of writing the document. + - `canvas_focus` and `canvas_arrange` include the frames' page. + - Placement into a page that isn't on screen does not move the person's view unless the tool's `focus` / `show` asks for it, exactly as today. + - `withEnteredCanvasTools` and the `viewState` selection keep working. `viewState.viewSize` still wins over `view().size` for this turn. + - Artifact frames placed through tools stamp `chatId: deps.chatId`. + +- [x] **Step 1: Write failing tests.** In `canvas-tools.test.ts`, convert the 22 `activePageId` assertions to the view and focus calls they now make, and add: + - `canvas_read lists the chat's view page as on screen`; + - `canvas_page show sends focus with the page and leaves the document unchanged`, asserting that the store's revision did not move; + - `with no view the tools use the first page`; + - `two chats with different views read different on-screen pages from one document`. + - Focus parse: `canvasFocusFrom keeps a string pageId and drops anything else`. +- [x] **Step 2:** Run `npx tsx --test main/services/design-canvas/canvas-tools.test.ts`. Expected: FAIL. +- [x] **Step 3:** Implement. In `llm-client.ts`: + - pass `view: () => designCanvasViews.get(params.chatId)`; + - make `focus` send `{chatId, pageId, frameIds}`; + - call `canvasPromptLine(doc, designCanvasViews.get(chatId), selection)`. +- [x] **Step 4:** Rerun the tool tests and `npx tsx --test main/services/llm-client*.test.ts` for the touched wiring. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): canvas tools follow the chat's own view`. + +### Task 6: Placement services use the chat's page + +**Files:** +- Modify: + - `main/services/design-canvas/artifact-frames.ts` + - `main/services/design-canvas/written-pages.ts` + - `main/handlers/design-canvas.ts` (`designCanvas:placeArtifact`) + - `main/services/chat-application-service-main.ts:62` +- Test: `artifact-frames.test.ts`, `written-pages.test.ts`, `main/handlers/design-canvas.test.ts` + +**Interfaces:** +- Consumes: Tasks 2, 4 and 5. +- Each service gains `view?(): DesignChatView | undefined` (production: `designCanvasViews.get(chatId)`) and places on `viewPageId(doc, view)`. +- Dedupe compares against that page. +- Artifact frames are stamped with `chatId`. +- `placeArtifact`'s "already on another page" no longer calls `showPage`. It returns `{status: "already", frameId, page}`, and the handler sends `designCanvas:focus {chatId, pageId, frameIds: [frameId]}` to the asking window. + +- [x] **Step 1: Write failing tests** + - `artifact frame lands on the chat's view page and carries chatId`; + - `written page dedupes only against the chat's view page`; + - `placeArtifact on another page focuses that page without changing the document`. +- [x] **Step 2:** Run them. Expected: FAIL. +- [x] **Step 3:** Implement. +- [x] **Step 4:** Rerun. Expected: PASS. +- [x] **Step 5:** Commit `feat(design): placements land on the acting chat's page`. + +### Task 7: Renderer view store, canvas and sync + +**Files:** +- Create: `renderer/design/canvas-view-store.ts` +- Modify: + - `renderer/design/use-design-canvas.ts` + - `renderer/design/design-canvas.tsx` + - `renderer/design/design-comments.tsx` + - `renderer/design/design-side-panel.tsx` + - the component that mounts the canvas with `chatId`, which now also passes `workspaceId` (`renderer/design/design-canvas-region.tsx`) +- Test: create `renderer/design/canvas-view-store.test.ts`, extend `renderer/design/use-design-canvas.test.tsx`, `renderer/design/design-canvas.test.tsx` + +**Interfaces:** +- Consumes: Tasks 1, 4 and 5. +- Produces: + - `readDesignView(workspaceId, chatId): { pageId?: string; viewports: Record }`; + - `writeDesignView(workspaceId, chatId, value)`. + - Both are wrapped in try/catch. A non-object or junk value reads as `{viewports: {}}`. Viewports are capped at the 200 page limit, dropping the oldest. + - `useDesignView({ workspaceId, chatId, doc })` returns `{ pageId: string; viewport: DesignViewport; showPage(id): void; setViewport(v): void; setSize(s): void }`: + - `pageId` is `viewPageId(doc, stored)`; + - it reports `{pageId, viewport, size}` through `reportDesignCanvasView` (250 ms debounce) and reports `null` on unmount. + - `useDesignCanvas(workspaceId, chatId)`: + - the sync ignores `designCanvas:updated` whose `workspaceId` differs; + - `viewsMoved`/`withViews` are deleted; + - panning never reaches `change()`. +- In `design-canvas.tsx`, every `doc.activePageId` and `activeDesignPage(doc).viewport` becomes `view.pageId` / `view.viewport`. The page picker calls `view.showPage`. A focus request with `pageId` calls `view.showPage(pageId)` before fitting. + +- [x] **Step 1: Write failing tests** + - `canvas-view-store.test.ts`: + - `round-trips a view per workspace and chat`; + - `reads junk and a throwing localStorage as an empty view`. + - `use-design-canvas.test.tsx`: + - `an update for another workspace is ignored and one for this workspace refetches`; + - `panning does not save`, asserting no `saveDesignCanvas` call after advancing past `DESIGN_CANVAS_SAVE_DELAY_MS`. + - `design-canvas.test.tsx`: + - `shows the first page when the stored page no longer exists`; + - `switching pages does not create an undo step`. +- [x] **Step 2:** Run `npx tsx --test renderer/design/canvas-view-store.test.ts renderer/design/use-design-canvas.test.tsx renderer/design/design-canvas.test.tsx`. Expected: FAIL. +- [x] **Step 3:** Implement. Register the new test file (CI registry and `package.json`). +- [x] **Step 4:** Rerun, then `npx tsc --noEmit -p renderer` and `-p main`. Expected: PASS, with no type errors left from Task 1. +- [x] **Step 5:** Commit `feat(design): each chat keeps its own page and view`. + +### Task 8: Artifact ownership, chat delete, E2E and docs + +**Files:** +- Modify: + - `renderer/design/nodes/artifact-node.tsx:52`: load with `frame.chatId ?? canvas.chatId`. + - `main/handlers/design-canvas.ts`: preview and export of an artifact frame use `frame.chatId ?? chat.id`, refused unless that chat exists and shares the asking chat's workspace. + - `main/services/chat-application-service.ts:795,812` and `main/index.ts:2598`: chat delete no longer deletes a canvas file. 1b adds pruning. + - `tests/e2e/design-canvas.spec.ts`: seed `design-canvases/.json` and `.layout-v3`. + - `tests/e2e/design-mode.spec.ts`: switch to the v3 key wherever it touches files. + - `PRODUCT.md` design-mode paragraph and `README.md` line 55, if it implies a per-chat canvas. + - `docs/plans/README.md` row, `.memory/design-mode.md`. +- Test: `main/handlers/design-canvas.test.ts`, `main/services/chat-application-service*.test.ts` + +- [x] **Step 1: Write failing tests** + - `artifact preview through another chat of the same workspace works, and of another workspace is refused`; + - `deleting a chat leaves the workspace canvas file in place` (chat application service, with a fake store recording calls: `delete` is never called). +- [x] **Step 2:** Run them. Expected: FAIL. +- [x] **Step 3:** Implement. +- [ ] **Step 4: Verify the whole phase** + - Run `npm run test`. Expected: PASS. + - Run `npm run test:e2e:space -- tests/e2e/design-canvas.spec.ts tests/e2e/design-mode.spec.ts`. Expected: PASS. + - Run `npm run lint`, if the repo has it. Expected: clean. + - Take screenshots of the canvas with two pages, for the PR body. +- [x] **Step 5: Docs** + - `PRODUCT.md`: "Design mode keeps one canvas per workspace, shared by its chats; each chat remembers its own page and view. Canvases from earlier versions are cleared on first start; files under `design/` are untouched." + - The same sentence in the release notes when the version is cut. + - Commit `feat(design): shared workspace canvas with per-chat artifacts; docs`. 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 new file mode 100644 index 0000000000..fd6cbbd270 --- /dev/null +++ b/docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md @@ -0,0 +1,602 @@ +# Design mode v2: the live app canvas + +Status: approved by the owner, 2026-11-23. Pre-build checks recorded in §11, and the PR split revised in §8. Phase 1a is in progress; its plan is [`2026-11-23-design-mode-v2-p1a-workspace-canvas.md`](../plans/2026-11-23-design-mode-v2-p1a-workspace-canvas.md). Builds on [Design mode v1](2026-10-31-design-mode-design.md) (P0–P5 shipped, on by default). Project memory: `.memory/design-mode.md`. + +## 1. Intent + +The owner wants design mode to put a project's **real, running web app** on an infinite canvas. Every route becomes a live, interactive frame. The person can inspect any element's real values, measure, spot values that break the design system, compare live directions side by side and see component variants. All of it updates within a second of a file save. + +Tools of this kind usually have no agent of their own: the person copies an element reference and pastes it into a separate coding agent. Aiden's edge is that the agent sits in the same window. Pointing goes straight into the composer, errors get a **Fix with Aiden** button, and Aiden itself starts the app, writes routes and arranges the board. + +Why now: v1 draws HTML mockups under `design/`. People building real React apps can't use them for their actual product, and the mockups have to be translated into code afterwards. v2 makes the canvas the app. + +## 2. Owner decisions (2026-11-23) + +1. Frames show the **live interactive app**: dev-server routes, not HTML mockups. +2. **One canvas per workspace.** Each design chat gets its own page on it, and Aiden can change which page a chat uses. +3. App-frame network is **localhost only** for now. +4. **Aiden can start and control everything** in design mode (dev server start, stop, restart, install and config) without per-call approval. (Refined in §12 S2: one consent per workspace and app root before the first start, renewed when the script text changes; never per call.) +5. A workspace with no web app: Aiden **asks before scaffolding** a small React app into the repo (§6.8). +6. **Comment stays on C, exactly as today.** Inspect is a separate tool with its own key, X (§6.4.1). +7. The dev server **starts by itself when the person turns design mode on** (toggle, ⇧⌘L, `/design`, or Enter on Aiden's card). It never starts just because Aiden relaunched (§6.2.3). +8. **Monorepos:** Aiden asks which apps to start and work in (§6.2.1). +9. **Live frames are for web apps only.** For a React project that isn't a web app (Electron, for example), Aiden makes React mocks in a mock app to iterate on (§6.8). +10. **Design mode uses the [DESIGN.md](https://github.com/google-labs-code/design.md) standard** for the app's design system (§6.9). + +Standing preferences that apply: pre-1.0 means no migrations (delete old shapes), autonomous phase-by-phase execution, and Opus implementers with reviews in the main session. + +## 3. Goals, non-goals, anti-goals + +**Goals** +- G1. Run or attach to the workspace's dev server from design mode. Aiden and the person can both start, stop, restart and read logs. +- G2. Show any route of the app as a live, interactive frame at a real viewport that reflows on resize. +- G3. Point, comment, inspect, measure and edit text inside live app frames, with React component and `file:line` source mapping. +- G4. One shared canvas per workspace. A chat's page is its working area, and every chat can see the whole board. +- G5. Feedback loops: a "saved · N frames updated" toast, changed-frame dots, and error frames with Fix with Aiden. +- G6. Explore live directions (route variants) and **Adopt** one. Run a drift check against the app's own tokens, and show a Styles frame. +- G7. Component cards from `*.canvas.tsx` files (Phase 6, its own spec before build). +- G8. A workspace with no web app can still design: Aiden scaffolds a small React app (see §6.8). + +**Non-goals (v2)** +- Remote, iOS and Android, and Telegram: design mode stays desktop-only and out of the Remote projection. +- Internet access for app frames (decision 3). Apps that fetch remote APIs, fonts or images show those requests failing. This is a known limit, surfaced in the frame (§6.3.5). +- A native GPU canvas, a plugin runtime, or project tabs. +- Non-React frameworks beyond showing their pages. Vue, Svelte and Astro routes can render as frames, but source mapping and component cards are React-only. +- Collaboration beyond what a shared workspace canvas gives (no multi-user presence). + +**Anti-goals** (a failure even if it technically works) +- An app frame whose renderer-side HTTP or WebSocket requests reach the internet, or that navigates the canvas away, touches Aiden's own renderer, or gets device permissions. Transports outside `webRequest` (WebRTC TURN over TCP) and the dev server's own server-side network are outside this guarantee; see §12 S5. +- A dev server that keeps running after the person has left design mode everywhere in that workspace, or after quit. +- Two chats or windows fighting over the shared canvas: page jumps, lost edits or save-conflict storms. +- Aiden running arbitrary shell commands without approval under the "design mode" banner. Only the fixed dev-server actions skip approval (§6.2.4). +- Losing anything v1 does well: comments, drawing and flows, notes, present and export, tweaks and text edit all keep working on the new canvas. + +## 4. Constraints + +- Electron 43, default session, main window `sandbox: true`, `contextIsolation`, no `webviewTag`. The main-window CSP `frame-src` today is `'self' aiden-genui: aiden-design:` (`main-window.html:8`). +- No `defaultSession.webRequest` handlers exist yet. Electron allows one listener per event per session, so the new filter must own each event through one dispatcher. +- Aiden does not bundle Node. Agent commands use the user's PATH with no login-shell lookup today. `devices/device-toolchain.ts` already resolves `npm`/`node` through `$SHELL -ilc` and rejects the Electron binary. +- `backgroundJobs` (`main/services/follow-through/background-jobs.ts`) already supervises long-running processes: process groups, logs, port polling via lsof or `/proc`, crash reaping, and teardown on quit, chat delete and workspace removal. `hostPlatformCapabilities().backgroundJobs` is true on darwin and linux. +- AGENTS.md: + - New analytics events go in the registry, with a docs row and a test. + - The onboarding gallery tile and art must be updated for a materially changed core capability. + - Docs change in the same PR. + - No source-grep tests. + - New test files are registered in `scripts/ci-test-registry.json` and the `package.json` scripts. + - Window-opening E2E runs in a Cua Space, and darwin-specific paths on the host. + +## 5. Approaches considered + +### 5.1 Hosting a live app frame + +| | A. iframe on the canvas, injected from main (**chosen**) | B. Loopback reverse proxy in main | C. `WebContentsView` per frame on its own partition | +|---|---|---|---| +| How | `