From c1ea0d300baaa9ea0e8948f2dafe47631a12672a Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 05:31:45 -0500 Subject: [PATCH 01/40] docs(plan): design mode v2 Phase 2b (dev server) plan, reviewed --- ...026-11-24-design-mode-v2-p2b-dev-server.md | 1317 +++++++++++++++++ 1 file changed, 1317 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-24-design-mode-v2-p2b-dev-server.md diff --git a/docs/superpowers/plans/2026-11-24-design-mode-v2-p2b-dev-server.md b/docs/superpowers/plans/2026-11-24-design-mode-v2-p2b-dev-server.md new file mode 100644 index 000000000..9fb297dab --- /dev/null +++ b/docs/superpowers/plans/2026-11-24-design-mode-v2-p2b-dev-server.md @@ -0,0 +1,1317 @@ +# Design mode v2 — Phase 2b: the dev server process — 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:** Design mode can run the workspace's web app, safely and only when the person has agreed to it. +- `DesignAppServers` starts, installs, stops and restarts one dev server per workspace and app root, on top of `backgroundJobs`, with a `design` job owner that no chat owns (S7). +- Before the first start, and whenever the launch surface changes, the person sees one consent card naming the commands and the script text. Main keeps a hash of what they approved (S2). +- The server binds to loopback only (S14). Its origin is `http://127.0.0.1:`, and it counts as ready only on a socket its own processes hold. An exposure check that fails closed watches it for as long as it runs. +- A server stops 60 s after no window shows that workspace's canvas, when the workspace changes or goes away, and when Aiden quits (S6). +- Aiden gets a `design_app` tool, recorded as a reviewed approval exception. 2c and 3a get a fixed status, consent and origin contract, so they don't change 2b's types. + +**Architecture:** +- **Shared contract.** `renderer/shared/design-app.ts` holds the status, problem and consent types, the fixed problem messages, the display escaping and the IPC payload shapes. 2c's chip and 3a's frames read only these. +- **Pure core.** `main/services/design-canvas/app-server/app-launch-core.ts` takes a detected app, the scripts and a port, and returns the argv and environment. It also holds: + - the readiness choice and the exposure check; + - the install decision; + - the fingerprint's canonical form. + + It does no I/O. +- **Disk and network edges.** + - `app-fingerprint.ts` hashes the launch surface with bounded, no-follow reads. + - `app-records.ts` keeps consents, install stamps and sticky ports in one userData file, and fails closed. + - `app-ports.ts` picks a free loopback port. + - DM's `canvas-config.ts` (extended here with `script` and `saveCanvasConfigApp`) reads and writes `.aiden/canvas.json`. +- **Process layer.** `backgroundJobs` gains: + - a `design` owner; + - argv spawning without a shell; + - a rotating log; + - its own running cap; + - `designSockets(jobIds)`, which lists every listening socket of each job's process group and descendants, from one `ps` and one `lsof` call for all jobs, and fails closed. +- **Service.** `app-server-main.ts` holds `DesignAppServers`, one per process. It owns the per-app state machine and serialises actions per key. It holds a workspace admission per attempt, drives consent through `DesignAppConsent` (`app-consent.ts`), and watches visible-canvas presence from `DesignCanvasViews`. +- **Surfaces.** + - the `design_app` tool (`app-tool.ts`); + - the `designApp:*` IPC handlers; + - a hook on the person's design-mode toggle; + - one renderer card (`renderer/design/design-app-consent.tsx`). + + There's no status chip: that's 2c. + +**Tech Stack:** TypeScript (ESM), Electron 43 main, React renderer, `tsx --test` for unit and integration tests, Playwright for one E2E (Cua Space and host). + +**Spec:** `docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md`: +- §3 anti-goals 2 and 4, §4, §5.2; +- §6.2.1 (the Choose apps rule), §6.2.2 (the launch environment), §6.2.3, §6.2.4, §6.8 (the Node-missing and install-failed states); +- §6.10 (`design_app_started`), §6.11, §7 (main services), §8 (row 2b), §10; +- §12 S2, S5, S6, S7, S8, S14, S15 (the consent half: 2c reuses S2's card for a repo URL) and S19–S22. + +**Stacking.** DM lands first (cross-phase decision 1). 2b's branch stacks on DM's branch, which stacks on PR #911 (Phase 2a), which is stacked on PR #908 (Phase 1b) and PR #894 (Phase 1a). 2b builds on these DM modules, which must exist on its base: +- `main/services/design-canvas/canvas-config.ts`: `CANVAS_CONFIG_PATH`, `CANVAS_CONFIG_MAX_BYTES`, `CanvasConfigApp` (already carrying `script?: string`, checked with 2a's `isSafeScriptName`), `CanvasConfig`, `parseCanvasConfig`, `parseCanvasConfigObject`, `readCanvasConfigText`, `readCanvasConfig`, `inspectCanvasConfig`, `configuredRoots(config, detected)`, `describedRoots(config, detected)` and `isSafeWorkspaceRelativePath` (a root of exactly `"."` allowed, any other `.` segment refused). DM's `version` rule: a missing `version` or `1` is known; anything else is unknown, and `parseCanvasConfig` returns `null`, which callers can tell apart from an empty config; +- `designLiveEnabled(env)` and `DESIGN_LIVE_FEATURE_FLAG` in `main/services/studio/feature-flags.ts`; +- `const designLive = designLiveEnabled()` in `llm-client.ts`'s canvas-tools block; +- `docs/design-mode.md` with DM's "DESIGN.md (experimental)" section; +- the S33–S44 amendments block in the spec. + +2b's amendments are S25–S32 (cross-phase decision 4). + +## Scope + +In scope: +- reusing DM's flag helper and DM's `studioCapabilities().designLive` for 2c's renderer; +- `backgroundJobs` changes (S7): + - the `design` owner and argv spawning; + - the rotating log with byte-offset reads; + - the design cap; + - `designSockets`; + - the owner guards in `scanPorts` and `forgetOldFinished`; +- address-aware listening sockets with a reader that fails closed (S14); +- the launch plan: argv, environment, port and host per framework (S14, S19); +- port choice with a sticky port per app root, and readiness from sockets the job owns; +- the launch fingerprint, the consent records, the consent card, its IPC, the read-only refusal and the desktop-only refusal (S2); +- the install decision with a completion stamp (S8, refined by D6); +- `DesignAppServers`: + - start, stop, restart, logs and choose; + - crashes and the exposure watch; + - the workspace gate; + - the 60 s visible-presence rule (S6); + - workspace removal and access loss; + - quit and crash recovery; +- the `design_app` tool with its gates, its per-turn budget and its reviewed approval exception; +- the person's toggle (button, ⇧⌘L, `/design`, Enter on Aiden's `design_mode` card) starting the target app; +- `saveCanvasConfigApp`, which saves the monorepo choice (`script`, which DM's parser already reads) through the consent card; +- the `designApp:*` IPC that 2c builds on: status get and broadcast, person start, stop, restart and choose, logs, and consent. Every call goes through `rendererDocumentOwner`; +- the `design_app_started` event (§6.10); +- a "Live apps (experimental)" section appended to `docs/design-mode.md`, plus `docs/analytics.md`, the S25–S32 amendments, memory and the plan index. + +Out of scope: +- **2c:** the status chip, its menu, the logs drawer, Connect running server, attaching a server by URL, and the browser-panel listing. 2b already defines `source: "attached"`, the `attach` consent request and the attach problems, so 2c adds no type; +- **3a:** app frames, the bridge, the network and permission dispatchers, and the iframe CSP. 2b gives 3a `appForOrigin`, `isAppOrigin` and `onOriginsChanged`; +- **other `.aiden/canvas.json` fields:** `routes`, `params`, `mock` and `url` (3b, 3d, 2c). DM owns the parser (including `script` and the `version` rule), `describedRoots` and `designMd`; 2b adds only the writer, which keeps every other field; +- **prompt and skill text.** 3b rewrites them. 2b's only model-facing text is the `design_app` tool's description and results; +- mock apps and scaffolding (3d); +- **Windows.** `hostPlatformCapabilities().backgroundJobs` is false there, so 2b reports `unavailable` and offers no tool; +- **Remote, iOS, Android and the CLI:** + - Remote turns can't start a server (D5); + - design jobs never reach Remote's `chat:jobs`; + - the shared `BackgroundJobView` and `BackgroundJobEndReason` types don't change, so the mobile clients don't either; +- automatic restart after a crash (D10). + +**Feature flag.** Everything that can start a process or show the card is behind DM's `designLiveEnabled()`, which is true when `designModeEnabled(env)` holds and `AIDEN_EXPERIMENTAL_DESIGN_LIVE` is `1`, `true`, `yes` or `on`, trimmed and case-insensitive. Off means: +- the `design_app` tool isn't offered; +- turning design mode on starts nothing; +- every `designApp:*` handler refuses with "Live apps are not available."; +- `DesignAppServers` is never asked to do anything, so no design job, record file, port probe or fingerprint read happens. + +Unflagged and inert while the flag is off: +- `backgroundJobs`' design owner, argv mode, rotating log and `designSockets` (no caller without the flag); +- the address-aware socket reader; +- `DesignCanvasViews.onPresence` and the `visible` field in the view report (a listener with no subscriber); +- the reviewed-exception row in `workspace-tool-approval.ts` (it names a tool that isn't offered); +- `saveCanvasConfigApp` (no caller); +- the `design_app_started` registry row and its docs row. + +## What exists today (checked against the code at `19b464fb9`) + +| Item | Today | 2b action | +|---|---|---| +| `BackgroundJobs.start` (`main/services/follow-through/background-jobs.ts:323`) | `spawn(command, { shell: true, detached: true })` in its own process group, marker env `AIDEN_BACKGROUND_JOB=`, stdin ignored. Per-chat cap 10, global cap 20. | Gains `startDesign` with owner `{ kind: "design", workspaceId, appRoot }` and `argv: { file, args }` (no shell). Design jobs have their own cap and don't count toward the chat caps (Task 2). | +| `list`, `get`, `read`, `settle`, `stop`, `stopChat`, `hasSettleStoppable`, `stopSettled`, `runningCount` | Keyed by `view.chatId`. | Answer only for chat-owned jobs. Design jobs get `getDesign`, `readDesignLog`, `stopDesign`, `listDesign`. | +| `scanPorts` (`:838`, `onChange(view.chatId)` at `:871`) and `forgetOldFinished` (`:931`, `onChange` at `:967-969`) | Call `onChange` with the job's chat id. | Never call `onChange` for a design job; `onDesignChange` instead (Task 2). | +| `listAll()` | Every job; only keep-awake reads it. `backgroundJobKeepAwakeInput` (`keep-awake/keep-awake-inputs.ts:106`) already skips jobs with ports. | Unchanged. A design install keeps the Mac awake while it runs; a listening server doesn't (Q6). | +| `stopWorkspace(workspaceId)`, `shutdown()`, `reapPreviousLaunch()` | Filter by `view.workspaceId`, stop everything, and reap from `running.json`. | Unchanged. They already cover design jobs, because design views keep `workspaceId` and `writeRecord` lists every running job. | +| `capture` (`:880`) | Past 50 MB of output the job is stopped with `output-limit`. | A design job's log rotates instead (D13). A dev server that logs every HMR update must not die after hours. | +| `onEnded`, `onChange(chatId)` (`follow-through-main.ts:191`, the `backgroundJobs` constructor) | `onEnded` posts a notice that wakes the chat; `onChange` broadcasts `chats:follow-through-changed` and feeds `chatSettlement`. | Never called for design jobs. A new `onDesignChange(view)` goes to `DesignAppServers` through a listener set. | +| `listening-ports.ts` | `parseLsofListening` and `parseProcNetTcp` keep ports only. Failures return nothing. | Address-aware siblings, plus `designSockets`, whose reader reports failure instead of nothing (Task 3). | +| `browserLocalServers(output)` (`main/services/browser/core.ts:299`) | Finds loopback URLs in terminal text; maps `0.0.0.0` to `localhost`. | Reused to read the printed port only. Loopback is decided by socket addresses, never by text. | +| `agentShellCommandEnvironment()` (`main/services/agent-command-environment.ts`) | Drops only secret-named `AIDEN_*` variables; keeps tooling tokens and provider keys. | The base of the launch environment, then scrubbed further (D7). | +| pi-ai `findEnvKeys(provider, env)` (`node_modules/@earendil-works/pi-ai/dist/env-api-keys.js:121`, pi-ai 1.5.2) | Exported from `@earendil-works/pi-ai/compat` (which re-exports `env-api-keys`), not from the main entry; returns the provider key variables present in `env`. The name table itself isn't exported. `compat` also exports `getProviders`. | `providerKeyNames(env)` imports both from `@earendil-works/pi-ai/compat`, calls `findEnvKeys` for every provider, and deletes what it finds. | +| `nodeCommandEnvironment`, `resolveAppToolchain`, `toolchainProblemMessage`, `clearAppToolchainCache`, `detectWebApp`, `designTarget`, `installCommand`, `runScriptCommand`, `FRAMEWORKS` (2a) | No caller yet. | First caller. `FRAMEWORKS[].devCommands` tells whether a script runs the framework's own CLI. | +| `DesignCanvasViews.mounted(workspaceId)` (`views.ts:177`) | A count, with no events. `report`, `unmount` and `unmountAll` set `mounted`. The renderer (`renderer/design/use-design-view.ts:102`) reports views; the stacked layout's visible pane is in `renderer/design/design-layout.tsx:48-67`. | The report gains `visible`, and the views gain `visible(workspaceId)` and `onPresence` (Task 7). | +| `chats:setDesignMode` (`main/handlers/chat-renderer-mutations.ts:140`) | Knows `wasOn` and the source; reports `design_mode_entered`. Its event parameter is unused. | On a false → true change with the flag on, it calls `designModeEntered` with `rendererDocumentOwner(event, …)` as the card's owner. | +| `designCanvas:consentAnswer` (`main/handlers/design-canvas-main.ts:35`) | Enter on Aiden's card turns design mode on. | Same hook, with that window as owner. | +| `rendererDocumentOwner(event, invalid)` (`main/services/renderer-document-owner.ts:85`) | Throws unless the sender is the current main frame; the owner can `send` and `onInvalidated`. | Every `designApp:*` handler and the toggle hook use it. | +| `DesignModeConsent` (`design-mode-tool.ts:35`), `renderer/design/design-mode-consent.tsx` | One pending card per chat, owner checks, 2-minute timeout, answers only from the card's window. | The pattern `DesignAppConsent` and its card follow. | +| `createMcpStdioApprovalStore` (`mcp-stdio-approvals.ts`) | Serialised writes, fail closed on an unreadable file, `approveShown`. | The pattern for the records file. | +| `workspaceMutationGate` (`main/services/workspace-mutation-gate.ts`) | `admit(id)` gives a signal that `begin(id)` aborts. Workspace `update` and `remove` call `begin` (`workspace-application-service.ts:381`, `:515`), then `closeForWorkspace` stops the workspace's jobs. Managed worktrees go through `beginWorkspaceMutation` (`workspace-worktree-application-service-main.ts:148`). | Each attempt holds an admission (D11). Because `begin` already aborts admissions, and every workspace change already stops the jobs, 2b adds no separate `pauseWorkspace`. | +| `processRecoveryReady` (`main/index.ts:2588`) | The result of reaping the last launch's jobs; `:2739` refuses work until it's true. | `start` waits for it (D3). | +| `designCanvasWorkspaceCleanup` (`design-canvas/main.ts:97`), `removeDesignCanvasWorkspace` (`:107`) | Called on workspace remove (`main/index.ts:2759`) and on managed-worktree delete (`workspace-worktree-application-service-main.ts:145`). | Also calls `designAppServers.forgetWorkspace`. | +| Remote turns (`main/services/aiden-remote-chats.ts:1420`) | Run with `usageSource: "chat"`, so they pass `followThroughAvailable`. Their owner has `kind: "remote"`. | `start`, `restart` and `choose` refuse them (D5). | +| `write_file`'s confined write (`coding-tools.ts`: `pinWorkspaceRoot` `:369`, `verifyWorkspaceRoot` `:394`, `resolveWritableInRoot` `:563`, `commitPinnedWrite` `:866`, `readReplacedFile` `:909`) | Module-private. Creates parent folders without following links and commits through the pinned writer. `assertAgentMayWriteConfigPath` protects only `.aiden/hooks.json` and `.aiden/hooks/` under `.aiden`. | A new exported `writeConfinedWorkspaceText(root, relPath, text, { expectedSha256?, signal })` reuses that path for `saveCanvasConfigApp` (Task 5). `writeWorkspaceFile` (the Files panel) can't create, and `writeWorkspaceBinaryFile` refuses hidden folders, so neither fits. | +| `AIDEN_ANALYTICS_DEBUG` (`analytics-main.ts:51`) | Read only when `!app.isPackaged`. | The pattern for the E2E grace knob (Q8). | +| `scripts/ci-test-registry.json` lanes | `core-git`, `runtime-subagents`, `renderer-other`, `macos`. | Main tests in `core-git`, renderer tests in `renderer-other`, `app-server-process.test.ts` in `macos`. | +| `scripts/ci-e2e-spec-map.json` | `design-canvas.spec.ts` maps to `main/services/design-canvas/` and `main/handlers/design-canvas`. | A row for `design-app-server.spec.ts`. | + +## Decisions + +These settle the rules the spec leaves open. Task 14 records the ones that change the spec as S25–S32. + +**D1. Owner.** A design job's owner is `{ kind: "design", workspaceId, appRoot }`. It has no chat. +- It never wakes a chat. +- It never appears in `background_job`, Remote's `chat:jobs`, the goal check's `jobsRunning` or chat settlement. +- It isn't stopped by a chat delete. +- It never triggers `chats:follow-through-changed`, including from `scanPorts` and `forgetOldFinished`. + +Its lifetime is visible presence, the workspace and quit (S7). + +**D2. One server per app root.** The key is `workspaceId + "\0" + appRoot`, where `appRoot` is 2a's POSIX relative root. Every action on a key runs through one per-key queue. +- A start while running answers `running`. +- A start while consent, install or start is pending joins that attempt, so the consent broker never shows a second card for a key. +- Two chats in one workspace share the server. +- Two workspace records on the same folder are two keys. Next.js refuses a second dev server in one folder, which then shows as a crash (Risk 12). + +**D3. What starts a server.** Only these: +- the person turning design mode on in a chat of the workspace (false → true), from a desktop window's main frame, with the flag on; +- `design_app start`, `restart` or `choose`; +- `designApp:start`, `restart` or `choose` from a window (2c's chip and 3a's "Start app" overlay). + +Every start first waits for `processRecoveryReady`. If recovery failed, the start ends with `recovery-failed`. Launching Aiden, restoring design-mode chats, opening a canvas, switching chats, moving a chat to another workspace (it isn't a false → true change), Remote, the CLI and background work never start a server, install, probe a port or read a fingerprint. + +**D4. What the toggle starts.** From `designTarget(detectWebApp(root))` and `readCanvasConfig(root)`: +- **configured roots:** DM's `configuredRoots(config, detected)` (cross-phase decision 2): the scripted entries detection sees as web candidates, `[]` for a `null` or unsupported config. 2b doesn't restate or re-implement its rule. When it returns any, they decide, whatever the target. (DM's `describedRoots` adds a detection fallback for DESIGN.md lookup; 2b never uses it to decide what starts); +- otherwise `single`: that app; +- otherwise `choose`: nothing starts, and the snapshot target is `choose`; +- `react-nonweb` and `none`: nothing. + +Each app gets its own card when consent is needed, shown one after another. A config with an unknown `version` (`parseCanvasConfig` returns `null`) describes no roots. + +**D5. Consent (S2).** +- **Fingerprint.** SHA-256 of a canonical JSON object (`launchFingerprintInput`), built from detection and toolchain resolution run now. It holds: + - `v: 2`, `appRoot`, `installRoot`, `lockfileLevelsUp`, the manager name and Yarn flavour, and the script name; + - script texts (absent recorded as `null`): + - the app root's `