From 080fe814bb82fa3810f62fc9949c96c4cfc231db Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:12:47 -0800 Subject: [PATCH 001/140] chore(porch): 1963 init spir --- .../status.yaml | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/status.yaml diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml new file mode 100644 index 000000000..24159eed7 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -0,0 +1,20 @@ +id: '1963' +title: vscode-alternative-layout-seco +protocol: spir +phase: specify +plan_phases: [] +current_plan_phase: null +gates: + spec-approval: + status: pending + plan-approval: + status: pending + pr: + status: pending + verify-approval: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-24T01:12:47.024Z' +updated_at: '2026-11-24T01:12:47.025Z' From 914ae876b33f91797257578918bb748a8903dbf6 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:21:46 -0800 Subject: [PATCH 002/140] [Spec 1963] Initial specification draft --- .../1963-vscode-alternative-layout-seco.md | 561 ++++++++++++++++++ codev/state/spir-1963_thread.md | 26 + 2 files changed, 587 insertions(+) create mode 100644 codev/specs/1963-vscode-alternative-layout-seco.md create mode 100644 codev/state/spir-1963_thread.md diff --git a/codev/specs/1963-vscode-alternative-layout-seco.md b/codev/specs/1963-vscode-alternative-layout-seco.md new file mode 100644 index 000000000..c587a6c30 --- /dev/null +++ b/codev/specs/1963-vscode-alternative-layout-seco.md @@ -0,0 +1,561 @@ +# Specification: VS Code alternative layout ("Codev Cockpit") + + + +## Problem Statement + +The Codev extension (`apps/vscode`) spreads the surfaces an architect watches across three places +and two layouts: + +- **This workspace's controls and agents** sit in the Codev activity-bar container as two separate + views, Workspace (`codev.workspace`) and Agents (`codev.agents`), stacked with Backlog, Pull + Requests, Recently Closed, Team and Status. +- **The machine-wide fleet** sits in a third view, Tower (`codev.tower`), in its own + secondary-sidebar container (`codev-tower`), on the other side of the window, hidden until revealed. +- **Work and Decisions**, the dashboard's two summary surfaces, are not in the extension at all. + Work is the one-screen list of builders, what needs attention, backlog and recently closed. + Decisions is where the owner rules on the architect's pending decisions (Spec 1819). To rule on a + decision from VS Code today the owner has to leave the editor for the browser dashboard. + +The owner wants a second, alternative layout for the same extension. It opens from a new button +under the Codev button. It shows one combined left-hand panel (Workspace, Tower and Agents together) +and an editor-area split, with the `main` architect's terminal on the left and Work and Decisions on +the right. The existing Codev container and its views stay as they are. This is an **addition**, not +a replacement. + +Affected: the owner (and any Codev user who runs an architect from VS Code or the Codev IDE), in +both distribution channels. Those are the marketplace vsix and the same extension built into the +Codev IDE, including the IDE served by Tower at `/ide/`. + +Pain points today: + +1. Ruling on a decision means switching to the browser dashboard and back. +2. Seeing "what needs me in this workspace" (Agents) and "what needs me anywhere" (Tower) at once + means having both side bars open. +3. There is no one-click way to get the architect-centred working layout. The user has to arrange + editor groups and open each surface by hand. + +## Current State + +**Activity bar / containers** (`apps/vscode/package.json` → `contributes.viewsContainers`): + +| Container | Location | Views | +|---|---|---| +| `codev` "Codev" (`icons/codev.svg`) | activity bar | `codev.workspace` (when `codev.hasWorkspace`), `codev.agents` (when `!codev.isBuilderWorktree`), `codev.backlog`, `codev.pullRequests`, `codev.recentlyClosed`, `codev.team`, `codev.status` | +| `codev-tower` "Codev Tower" | secondary side bar | `codev.tower` | +| `codevPanel` "Codev" | bottom panel | `codev.contextualPanel` (webview) | + +**The three views to combine:** + +- **Workspace** (`views/workspace.ts`, `WorkspaceProvider`): an expandable *Architects* root (one + child per architect, `main` first; click opens that architect's terminal; a sibling has a *Remove + Architect* context entry; the root has an inline *Add Architect*), *Open Web Interface*, *Spawn + Builder*, *New Shell*, a single *Start Dev* / *Stop Dev* row, and one row per `worktree.devUrls` + entry. In a builder-worktree window (#1809) the architect, spawn and shell rows are omitted. +- **Agents** (`views/builders.ts`, `BuildersProvider` over `OverviewCache`): builders grouped on a + switchable axis (stage / area / architect, `codev.buildersGroupBy`). Each builder row expands to + its changed files (`BuilderDiffCache`), flat or as a folder tree. Rows carry a state glyph, inline + *Approve Gate* on blocked builders, and a context menu: open terminal, approve, view + spec/plan/review, view diff, open worktree window/folder, run setup, run/stop dev. Behaviour is + wired to the `codev.agents` **TreeView instance** in `extension.ts`: + - the click handler `codev.openBuilderRow` reveals and expands the row (`codev.buildersClickExpands`); + - the accordion collapses peers on expand (`codev.buildersAutoCollapse`); + - active-file sync reveals the open diff file's row (#1066); + - agent-terminal cycling selects the row (#1563); + - selection fires the `builder-active` activity hook; + - the title shows a live count ("Agents (3)"); + - the view's badge is the Codev activity-bar badge (blocked + idle + held + waiting architects, + suppressed in a worktree window). + + The title bar holds refresh, group-by cycle, accordion toggle and file-tree toggle. +- **Tower** (`views/tower.ts`, `TowerProvider` over `TowerFleetCache`): every workspace Tower knows. + Active workspaces are ordered by urgency, each expandable to its attention rows (pending gates, + waits, architects at a prompt, held mail, queued feedback), and dormant ones sit in a collapsed + group. Rows have inline *Open* / *Deactivate* actions. The title bar has refresh, and the view's + badge carries the machine-wide needs-attention count. + +Menus target the source views by id (`view == codev.agents && viewItem =~ …`), so a row rendered in +any other view today would lose its inline and context actions. + +**Editor-area placement** (`terminal-manager.ts`): with `codev.terminalPosition: "editor"` (the +default) the architect terminal opens in editor group 1. Builder and shell terminals open in group 2 +if it exists, else group 1. With `"panel"` they open in the bottom panel. `open-architect.ts` holds +the #1497 invariant: a terminal is opened, and cached, only under its occupant's own name, and a +non-live `main` gets the warning *"Codev: No 'main' architect found — is the workspace activated?"*. +Another architect is never substituted. + +**Dashboard Work and Decisions** (`apps/web`): + +- `WorkView.tsx` composes `BuilderCard` (builders table with an *Open* button that selects the + builder's dashboard tab), `NeedsAttentionList`, `BacklogList`, `RecentlyClosedList`, `TipBanner`, + `OpenFilesShellsSection` (dashboard shell and annotation-viewer tabs) and a collapsible `FileTree` + file browser. It has a *+ Shell* button (creates a dashboard shell tab) and *Refresh*. Data comes + from `useOverview` (polls `/api/overview` every 2.5 s, plus SSE) and the dashboard's + `DashboardState`. +- `DecisionsView.tsx` + `hooks/useDecisions.ts` (Spec 1819, #1938): polls `GET …/api/decisions` + every 2 s while the tab is active and the page is visible. It renders open items with + options/comment/Submit, Q&A threads, the current ruling, held drafts and the Ruled section, and + posts rulings to `POST …/api/decisions/rule`. Item images that are workspace paths are fetched + with the key from `GET …/api/decisions/image` and shown as object URLs. http(s) links and images + open in a new tab via `window.open`. +- Both import their transport (`lib/api.ts`) directly. It uses relative URLs, the injected Tower + key and `window`/`localStorage`. So as written they can only run inside the dashboard page. + `DecisionsView` already uses `renderMarkdown` from `@cluesmith/codev-artifact-canvas`, which the + extension also depends on. + +**Extension webview precedent:** `esbuild.js` already bundles two React webviews: the +markdown-preview canvas (#859) and the contextual panel (#1049). Each uses a nonce CSP, a typed +host↔webview message contract with `is*Message` guards on inbound messages (`contextual-panel/ +messages.ts`), and `retainContextWhenHidden`. `@cluesmith/codev-artifact-canvas` is the precedent +for a host-agnostic React package that both apps bundle, with the host supplying I/O through adapter +interfaces and themes through `--codev-canvas-*` tokens. + +**Tower client:** the extension host reaches Tower only through `ConnectionManager`'s shared +`TowerClient` (`@cluesmith/codev-sdk`), which carries the key and the workspace-scoped route prefix. +The SDK has no decisions methods today. Its generic `request()` drops the response body on a non-2xx +status, so it would lose the decisions routes' structured refusal (`{ ok: false, code, message }`). + +## Desired State + +### 1. A second activity-bar button + +A new activity-bar container, working name **"Codev Cockpit"**, registered directly after the +`codev` container so it sits under the Codev button. Its icon is a new SVG that wraps the same path +as `icons/codev.svg` in `transform="rotate(90 400 400)"` (clockwise). The shape is not redrawn. The +existing `codev`, `codev-tower` and `codevPanel` containers and every view in them are unchanged. + +### 2. One combined left-hand panel + +The container holds **one tree view** with three top-level **sections**: *Workspace*, *Tower* and +*Agents* (that order; see Open Questions). Each section is a collapsible header row, expanded by +default, whose children are exactly the rows the corresponding source view renders today: + +- **Same data, same rows.** Sections read the existing providers' row-building logic over the + existing caches (`OverviewCache`, `TowerFleetCache`, `BuilderDiffCache`, the Workspace provider's + Tower reads). There is no second fetch path, no second SSE subscription and no copied grouping or + ordering logic. +- **Same actions.** Every click, inline action and context-menu entry a row has in its source view + works on the same row in the combined panel with the same effect. Tree behaviours bound to the + source view follow the view the row is in: click-expands, accordion, active-file reveal (when the + combined panel is the visible one), agent-cycle selection and the `builder-active` hook. +- **Section-level actions.** Each source view's title-bar actions (Agents: refresh, group-by cycle, + accordion toggle, file-tree toggle; Tower: refresh) are available in the combined panel, attached + to the section they act on. The combined view's own title bar carries *Arrange Cockpit* (below) + and *Refresh*. +- **Section headers** show the same live summary the source view's title does (*Agents (N)*). +- **Badge.** The combined view badges the new activity-bar button with the same workspace "needs me" + count as the Codev button (`composeActivityBadge`), under the same suppression rules. The Tower + container keeps its machine-wide badge. +- **Empty and degraded states:** + - an Agents section with no builders shows a single *No active builders* row, not an empty header; + - Tower's *Connecting to Tower…* and *No workspaces registered* rows appear as they do today; + - in a **builder-worktree window** the Agents section is absent (as `codev.agents` is today), + Workspace shows its worktree-scoped rows, and Tower shows the fleet; + - in a **window with no Codev workspace** the Tower section is shown, and in place of Workspace + and Agents a single row says no Codev workspace is open, with the open-folder action. + +### 3. Work and Decisions in the extension, in a split with the `main` architect + +- **Ported views.** The dashboard's Work and Decisions views render in VS Code editor-area webview + panels, from the **same React components** the dashboard uses. The components move to a shared + location that both `apps/web` and `apps/vscode` import. Neither app keeps its own copy. +- **Transport through the host.** The webviews never contact Tower. The extension host serves their + data and performs their actions over webview messaging, using `ConnectionManager`'s client: + - Work's data is pushed from the host's `OverviewCache`, the same source the sidebar uses. A + visible Work panel counts toward the periodic overview refresh, as the sidebar views do. + - Decisions' read, ruling and image requests go through the host to the existing Tower routes. + Refusals keep their structured `code`/`message`, so the card shows the same text the dashboard + shows. + - The Tower key never enters a webview. +- **Decisions is fully functional:** + - it polls while its panel is visible and stops while hidden; + - drafts, held drafts and in-flight submits behave as in the dashboard (Spec 1819), and survive + the panel being hidden or moved between groups; + - a ruling round-trips: Submit → Tower writes the file → the card shows the written ruling, and + Tower's ruling notice to the hub architect (#1828) is sent as it is from the dashboard; + - workspace-path item images load through the host; http(s) images load as in the dashboard; + - an http(s) link opens in the user's browser; + - clicking an image shows it full size inside the panel, because a webview cannot open browser + tabs. +- **No decisions file.** A workspace without one (no `afx decisions init`) shows an empty state: + Tower's "There is no decisions file at …" message plus a hint to run `afx decisions init`. It is + not an error banner. The panel keeps polling, so creating the file makes items appear. +- **Dashboard-only affordances, mapped or dropped** (no dead controls): + + | Dashboard affordance | In VS Code | + |---|---| + | Builders table *Open* (select builder tab) | Opens the builder's terminal via `TerminalManager`, as clicking its Agents row does | + | *+ Shell* (dashboard shell tab) | Runs the existing *New Shell* action (a Tower shell opened by `TerminalManager`) | + | *Refresh* | Re-reads the overview from Tower, bypassing Tower's overview cache as the dashboard's does, and updates every consumer of `OverviewCache` | + | Needs Attention / Backlog / Recently Closed http(s) links (issues, PRs) | Open in the user's browser (as the dashboard and the Pull Requests view do) | + | Backlog / Recently Closed *spec* / *plan* / *review* links (dashboard annotation tab) | Open that file in a VS Code editor. The path is checked by the host to be inside the workspace | + | *Open Files & Shells* section (dashboard tabs) | **Dropped.** VS Code's own terminal list and editor tabs are the equivalent | + | Collapsible *Files* panel (`FileTree`) | **Dropped.** VS Code's Explorer is the equivalent | + | *Tip of the day* banner | **Dropped.** Its tips are CLI/dashboard tips, some of which do not apply in VS Code | + | Decisions link / full-size image (`window.open`) | Browser for http(s) links. Full-size image shown in the panel | + + In the dashboard every one of these keeps its current behaviour. The dashboard's Work and + Decisions look and behave exactly as before. +- **Themed by VS Code.** Both panels take their colours, fonts and focus styles from VS Code theme + variables, so they read correctly in light, dark and high-contrast themes and follow a theme + change live. +- **Single instance.** One Work panel and one Decisions panel per window. Opening either again + reveals the existing panel and never creates a second one or reloads the first. Each can also be + opened on its own from the Command Palette (*Codev: Open Work*, *Codev: Open Decisions*). + +**The split (*Arrange Cockpit*):** + +- **Result:** the editor area becomes a left column and a right column, with the right column split + into a top and a bottom group. Left holds the workspace's `main` architect terminal, top-right + Work, bottom-right Decisions. Each of the three is the active tab in its group. +- **Architect resolution** uses the existing path (`openResolvedArchitect` → `TerminalManager`). The + left side is always `main`, with no picker. A non-live `main` gets the existing warning and nothing + is substituted. The right side is arranged and renders regardless. An architect terminal already + open is reused, the same session moved to the left group, never closed and reopened. For this + action the architect goes to the left editor group even when `codev.terminalPosition` is `panel`. + Every other open path keeps honouring the setting. +- **The user's open editors are never closed, discarded or reloaded**, including dirty and untitled + ones. They stay open with their unsaved content and may end up in a different group. +- **Triggers:** + - the first time the Cockpit container becomes visible in a window, that window is arranged; + - after that, showing the container again leaves the editor area alone; + - *Arrange Cockpit* (Command Palette and the combined view's title bar) arranges on demand at any + time, and is idempotent: running it on an already-arranged window changes nothing visible. +- **Where it is offered:** + - in a **builder-worktree window** the split is not offered: no auto-arrange, the title-bar action + is hidden, and the command explains why. This follows #1809: surfaces that act on the parent + workspace stay in the parent's window. Work and Decisions likewise are not offered there; + - in a **window with no Codev workspace** there is nothing to arrange: no auto-arrange, and the + command says no Codev workspace is open. +- **Placement interaction (accepted, not changed here):** with the split in place, builder terminals + and issue previews that target "group 2" land in the Work group, per today's placement rules. + Changing those rules is #1671's scope. + +## Success Criteria + +- [ ] A new activity-bar button with the rotated Codev icon (same path, `rotate(90 400 400)`) appears + directly under the Codev button on a fresh profile, in VS Code and in the Codev IDE (including + `/ide/`). +- [ ] The existing `codev`, `codev-tower` and `codevPanel` containers, their views, view ids, menus + and badges are byte-for-byte unchanged in `package.json` (additions only), and behave as before. +- [ ] Clicking the new button opens one tree view with Workspace, Tower and Agents sections showing + the same rows as the three source views for the same data. +- [ ] Every row click, inline action and context-menu entry of the three source views is present + and works on the same row in the combined panel. This is checked against a list generated from + `package.json` menus, so none is missed. +- [ ] Builder-row click-expands, the accordion, active-file reveal and agent-cycle selection act on + the combined panel's rows when it is the visible view. +- [ ] Source-view title-bar actions are reachable from the combined panel on their sections. +- [ ] No new Tower polling or SSE subscription is added for the combined panel. The Tower request + count while it is open equals the count with the source views open. +- [ ] *Arrange Cockpit* produces `main` architect | (Work over Decisions), each active in its group, + with live data in both panels. +- [ ] With `main` not live, *Arrange Cockpit* shows the existing warning, opens no other architect, + and still arranges and renders Work and Decisions. +- [ ] With a dirty file, an untitled buffer and a modified file open across two or more groups, + arranging closes none of them and loses no unsaved content. +- [ ] Re-running *Arrange Cockpit* on an arranged window creates no duplicate panel or terminal and + reloads neither panel. A Decisions draft typed before the re-run is still there after it. +- [ ] Decisions: a pending item can be ruled from VS Code. The file on disk carries the ruling, the + card shows it, and the hub architect receives the ruling notice, the same as from the dashboard. +- [ ] Decisions: a refused ruling (e.g. `item-changed`) shows the server's message on the card and + keeps the draft. +- [ ] Decisions: a workspace-path image and an http(s) image both render. A missing image shows the + "Image not loaded" note. Clicking an image shows it full size in the panel. +- [ ] Decisions: a workspace without a decisions file shows the empty state, not an error. Creating + the file makes its items appear without reopening the panel. +- [ ] Work: builders, Needs Attention, Backlog and Recently Closed render from the overview. *Open* + opens the builder's terminal, *+ Shell* opens a Tower shell, *Refresh* refreshes, artifact + links open the file, and http(s) links open the browser. No dropped affordance is rendered. +- [ ] Neither webview makes a network request to Tower, and the Tower key is absent from webview + state and messages. +- [ ] The dashboard's Work and Decisions views look and behave as before. Existing `apps/web` tests + (`DecisionsView*.test.tsx`, `useDecisions.test.ts`, `BuilderCard.test.tsx`, + `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`, `App.decisions-tab.test.tsx`, …) pass + unchanged in intent. +- [ ] No React component used by Work or Decisions exists in two copies in the repo. +- [ ] In a builder-worktree window: the button and combined panel work (no Agents section), and the + split, Work and Decisions are not offered. In a no-workspace window: the button and panel work, + with Tower plus the no-workspace row. +- [ ] Both panels render correctly in a light, a dark and a high-contrast theme and follow a live + theme change. +- [ ] `contributes-*` tests cover the new container, view, commands, menus and their `when` clauses. + The existing `contributes-*` tests pass unmodified apart from additions. +- [ ] **Verified by rendering:** the PR carries screenshots taken from a running extension (the + Codev IDE at `/ide/` driven by Playwright, or an equivalent isolated instance). They show the + button; the combined panel with N=0, N=1 and N>1 builders; the split with a pending decision; + and light and dark themes. +- [ ] Lint, type-check and the full `apps/vscode`, `apps/web` and shared-package test suites pass. + +## Constraints + +Prescribed by the architect in the issue ("Prescribed design choices"; settled, not relitigated +here): + +- **Reuse the React components; don't rewrite them.** The extension already bundles React into + webviews (`esbuild.js`, the markdown-preview and contextual-panel webviews) and already depends on + `@cluesmith/codev-artifact-canvas`, which `DecisionsView` uses. If the components have to move to + be shared between `apps/web` and `apps/vscode`, move them to a shared location and have both + import from it. A forked copy inside `apps/vscode` is not acceptable. +- **Webviews don't talk to Tower directly.** Data and actions go through the extension host's + existing Tower connection (`connection-manager.ts`) over webview messaging. That keeps auth, the + workspace-scoped route prefix and web-workbench (`/ide/`) mode working, and respects the + codev-core / codev-sdk import boundary. +- **Dashboard-only affordances need an extension equivalent or get dropped, explicitly.** For each + one the spec says what it maps to in VS Code or that it is left out. No dead buttons. (The mapping + table above.) +- **Theme with VS Code variables**, so the ported views read correctly in light, dark and + high-contrast themes. +- **Both channels.** The same extension ships as the marketplace vsix and inside the Codev IDE. This + must work in both, including a builder-worktree window and a window with no Codev workspace. + +From the issue body: + +- Additive only: the existing Codev container and its views stay exactly as they are; nothing is + removed or moved. +- The icon is a new SVG rotating the same path (`transform="rotate(90 400 400)"`), not a redrawn + shape. +- "A single panel" is one view with three sections, not three stacked views sharing a container. +- One source of truth: the combined panel reuses `views/workspace.ts`, `views/builders.ts`, + `views/tower.ts`, `overview-data.ts` and `tower-cache.ts`, with no second copy of fetch or grouping + logic. +- The architect goes through `open-architect.ts` / `TerminalManager`, and the #1497 invariant + holds. + +From the system: + +- Server/client isolation (#1189): the shared component package and any new SDK methods import only + `codev-types` (and, for the components, the environment-agnostic SDK helpers and + `codev-artifact-canvas`). They never import `codev-core`. The SDK stays environment-agnostic with + zero runtime deps, and boundary tests enforce this in CI. +- No Tower or decisions-route changes: the Spec 1819 / #1938 routes are consumed as they are. +- VS Code engine floor `^1.128.0`. No API newer than that. +- Webview hardening as in the existing webviews: nonce-gated scripts, a CSP that admits only what + the panels load, and every inbound webview message validated by a type guard before it is acted + on. A path from a webview is treated as untrusted and confined to the workspace. +- The extension stays under the existing `regCli` / `reg` command-registration guard (#791). +- UI changes are verified in a browser via Playwright before being called done + (`codev/resources/testing-guide.md`). Verification must not replace or disturb the owner's live + Codev IDE extension or running workspaces. + +## Assumptions + +- `vscode.setEditorLayout` (or an equivalent built-in layout command) can shape the editor area into + left | (top / bottom) while moving editors from groups it removes, not closing them. This is to be + confirmed in the plan by a spike against a running instance. If it does not hold, the arrangement + must only add or reuse groups and never remove one. +- An existing terminal-editor tab can be moved between editor groups, and from the bottom panel into + the editor area, without ending its session. Same spike. +- Webview `postMessage` can carry image bytes, or an equivalent encoding, efficiently enough for + images up to Tower's 10 MB image cap. +- `OverviewData.architects` gives the Work view what the dashboard's `DashboardState` gave it + (architect count for builder attribution), so Work needs no `/api/state` read. +- The Codev IDE at `/ide/` can be driven by Playwright with a build of this branch loaded in an + isolated extensions dir or server instance, so verification never touches the owner's live IDE. +- A fixture workspace, with builder entries but no real agents, can produce the N=0 / N=1 / N>1 + builder states and a pending decision without spawning builders. + +## Solution Approaches + +### A. The combined panel + +**A1 — Composite tree over the existing providers (recommended).** One `TreeDataProvider` whose +roots are the three section headers. Each section's children, `getTreeItem`, `getParent` and element +identity delegate to a Workspace / Tower / Builders provider instance over the shared caches. The +rows are the same objects with the same `contextValue`s and `command`s. Menu `when` clauses that name +a source view also name the combined view. The TreeView-bound behaviours (reveal on click, +accordion, active-file reveal, agent cycle, selection hook, badge, count) are generalised from "the +Agents view" to "the view the row is in". + +- Pros: zero copied row logic; every action works because it is the same row; native tree + affordances (keyboard nav, context menus, theming) for free. +- Cons: `extension.ts` wiring that today closes over `buildersView` must be generalised. Element ids + must stay unique across sections. Tower's non-`TreeItem` node type means the composite element is + a union. +- Risk: medium. The generalisation touches well-tested behaviour, and existing tests guard the + source views. + +**A2 — A webview that renders all three sections.** One React webview drawing the rows as HTML. + +- Pros: full layout freedom. +- Cons: re-implements every row, glyph, ordering and menu in HTML: a second copy of row behaviour, + which the issue forbids. Native context menus, keyboard navigation and tree theming are lost. +- Risk: high. Rejected. + +**A3 — Three views in one container.** Register Workspace, Tower and Agents views again under the +new container. + +- Pros: least code. +- Cons: the issue explicitly reads "a single panel" as one view with three sections. Rejected. + +### B. Sharing Work and Decisions + +**B1 — A new shared React package with host adapters (recommended).** Move `WorkView`, +`DecisionsView`, `useDecisions` and the components they pull in (`BuilderCard`, +`NeedsAttentionList`, `BacklogList`, `RecentlyClosedList`, `issueIds`) into a new workspace package. +It is bundled by each host, not npm-published, the way `codev-artifact-canvas` is. The components +take their data and actions from a small host adapter (overview source; decisions read, rule and +image; open builder, new shell, refresh, open file, open external) instead of importing `lib/api.ts`. +A control renders only when the host provides its action. Each host maps the package's theme +tokens: the dashboard to its palette, the extension to `--vscode-*`. `apps/web` keeps thin wrappers +that supply the fetch-based adapter, so the dashboard is unchanged. Dashboard-only pieces +(`FileTree`, `OpenFilesShellsSection`, `TipBanner`) are passed in by the dashboard host as optional +slots rather than moved. + +- Pros: one copy; mirrors an established repo pattern; a clean host/IO boundary that satisfies the + "webviews don't talk to Tower" constraint by construction. +- Cons: a new package with its own build/test wiring. The existing `apps/web` tests move with the + components or retarget the wrappers. +- Risk: medium. + +**B2 — `apps/vscode` imports from `@cluesmith/codev-web`.** `apps/web` already exports `./*` source +files. + +- Pros: no move. +- Cons: an app depending on an app. The components still hard-import `lib/api.ts` (relative URLs, + `window.__CODEV_TOWER_KEY__`, `localStorage`), so they need the adapter refactor anyway, and the + vsix bundle would trace into dashboard-only modules. +- Risk: medium, worse layering. Not recommended. + +**B3 — Fold into `codev-artifact-canvas`.** That package's charter is rendering and reviewing +markdown artifacts. Work and Decisions are workspace-state surfaces. Not recommended. + +### C. What triggers the split + +- **C1 — First show per window, plus command (recommended).** Auto-arranges the first time the + container becomes visible in a window, including on a restore with the container visible. After + that only *Arrange Cockpit* does it. Predictable: re-showing the sidebar (Cmd+B, switching back + from Explorer) never rearranges tabs the user has since changed. +- **C2 — Every show (idempotent).** Closest to "clicking the button gives you the layout". But VS + Code cannot tell a click from a sidebar toggle, so tabs the user rearranged, or a panel they closed + on purpose, keep coming back. +- **C3 — Command only.** Least surprising, but the button alone would not give the owner the layout + they asked for. + +### D. The right-hand arrangement + +- **D1 — Two stacked editor groups, Work over Decisions (recommended; the issue's assumption).** + Both are visible at once and resizable with VS Code's own sashes. +- **D2 — Two tabs in one group.** Simpler layout, but only one is visible at a time. +- **D3 — One webview holding both.** No group juggling, but no native resize or separation, and it + couples two independent surfaces. + +## Open Questions + +**Critical (blocks progress):** none. The issue's five working assumptions are adopted below, for +confirmation at this gate. + +**Important (shapes design), recommendation given; confirm at the gate:** + +1. **Trigger semantics.** The issue assumes "showing the new container arranges the split". This + spec narrows that to *the first show per window*, plus the command (C1 over C2). Confirm. +2. **`codev.terminalPosition: "panel"`.** This spec has *Arrange Cockpit* put the architect in the + left editor group regardless of the setting (moving an already-open panel terminal into the + editor), because the user explicitly asked for the layout. The alternative is to honour the + setting and leave the left column without the architect. Confirm. +3. **Builder-worktree window.** This spec does not offer the split, Work or Decisions there, + following #1809's "parent-acting surfaces stay in the parent's window". The combined panel still + works (Workspace worktree rows + Tower). The alternative is to show the parent's Work and + Decisions there too. Confirm. +4. **Shared package location/name.** Recommendation: a new `packages/` workspace package bundled by + both hosts (B1). The plan names it. + +**Nice-to-know:** + +5. **Container name.** "Codev Cockpit" (working title) unless the owner prefers another. +6. **Rotation direction.** Clockwise (`rotate(90 …)`), as assumed. +7. **Section order.** Workspace, Tower, Agents (the owner's spoken order). Workspace, Agents, Tower + is the alternative. +8. **Badge source.** The workspace "needs me" count (same as the Codev button) rather than Tower's + machine-wide count. +9. **Reload persistence.** Whether Work and Decisions panels are restored after a window reload + (webview serializer) or re-created by the next arrange. Recommendation: restore them. Decisions + drafts are lost on reload either way, as they are on a dashboard page reload. + +## Test Scenarios + +**Unit / contribution (vitest, existing harness):** + +1. `contributes-*`: new container after `codev`, the rotated icon file, the combined view with no + `when` (always present), the new commands with palette `when`s (hidden in worktree windows where + specified), and menu entries. Each existing source-view menu entry has a combined-view + counterpart (generated check). +2. Rotated SVG: same `d` path as `codev.svg`, wrapped in `rotate(90 400 400)`. +3. Composite provider: + - section roots and order; + - children equal the source providers' children for the same cache state (N=0, N=1, N>1 + builders; each group-by axis); + - `getParent` chains for reveal; + - id uniqueness across sections; + - worktree-window and no-workspace variants. +4. Generalised tree behaviours: accordion, click-expands and reveal act on the view a row belongs + to, both for the Agents view (regression) and the combined view. +5. Host message contract: every inbound message guard rejects malformed input; file-open paths + outside the workspace and `..` escapes are refused. +6. Host decisions bridge: document, refusal (structured code/message preserved), transport error, + image bytes / not-loaded; not-found maps to the empty state. +7. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no + substitute); single-instance panels; idempotent re-run. +8. Shared components: the existing `apps/web` tests pass against the moved components through the + dashboard adapter. New tests run the same components with a fake host adapter, asserting that + dropped affordances are absent and mapped actions call the adapter. + +**Rendered (Playwright against a running extension, isolated from the owner's live IDE):** + +9. Button: rotated icon directly below Codev; the existing Codev container unchanged. +10. Combined panel with N=0, N=1 and N>1 builders. A builder row's context menu shows the same + entries as in Agents. Approve, open terminal and view diff work from it. A Tower row opens or + deactivates a workspace. +11. Arrange on a window with pre-existing editors (one dirty) → the layout appears and the dirty + editor survives with its content. Arrange again → nothing changes, and a typed Decisions draft + persists. +12. `main` not live → warning; Work and Decisions still render. +13. Decisions: rule a pending item → file updated, card shows the ruling, architect notified. A + stale fingerprint gives a refusal with the draft kept. Workspace and http(s) images render; + full-size view opens and closes. +14. No decisions file → empty state. Run `afx decisions init` → items appear. +15. Work: Open / + Shell / Refresh / artifact link / external link each do what the mapping table + says. +16. Light, dark and high-contrast themes, and a live theme switch. +17. Builder-worktree window and no-workspace window variants. +18. Dashboard regression: the browser dashboard's Work and Decisions tabs render and rule as before. + +**Non-functional:** + +19. Tower request rate with the combined panel open is unchanged from the source views alone. The + Decisions poll stops while its panel is hidden. +20. Neither webview opens a network connection to Tower (CSP has no `connect-src` to Tower; the key + is not present in webview state). + +## Risks and Mitigation + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| The layout command closes or discards a user editor | Low | High | Spike the layout primitive first (Assumptions). The invariant is tested with dirty, untitled and modified editors. If the primitive removes groups unsafely, only add or reuse groups | +| Generalising `buildersView`-bound wiring regresses the existing Agents view | Medium | High | Keep the existing Agents view tests as the regression net, add per-view tests for each behaviour, and render both views in verification | +| A menu entry is missed in the combined view (dead or absent action) | Medium | Medium | A generated test cross-checks every source-view `view/item/context` and `view/title` entry against a combined-view counterpart | +| Moving components changes the dashboard's look or behaviour | Medium | Medium | Thin dashboard wrappers with the current fetch adapter, the existing `apps/web` tests unchanged in intent, and a dashboard render check in verification | +| A Decisions draft is lost by the layout or by hiding the panel | Low | High | `retainContextWhenHidden`; arrangement reuses panels and never recreates them; tested. Loss on explicit panel close or reload is parity with the dashboard and stated | +| The new button does not sit under Codev for an existing profile (VS Code persists activity-bar order) | Medium | Low | Register directly after `codev`. Verify on a fresh profile and an existing one, and note in the PR if VS Code places it elsewhere for existing profiles (the user can drag it) | +| Verification disturbs the owner's live Codev IDE or Tower workspaces | Medium | High | Run the branch build in an isolated extensions dir or server instance and a fixture workspace; no real builder spawns. Ask before anything that would touch the live IDE | +| Image bytes over `postMessage` are slow or memory-heavy | Low | Low | Tower's 10 MB cap bounds them. Fetch on demand per visible item, as the dashboard does | +| SDK boundary violation (new client methods pull Node APIs) | Low | Medium | New methods use the injected `fetchFn` only; the SDK boundary tests run in CI | + +## References + +- Issue #1963 (this spec's source) +- Spec 1819 — Decisions tab; #1828 ruling notice; #1938 decision images +- #1809 — builder-worktree windows attach read-only to the parent +- #1497 — architect resolution invariant (`apps/vscode/src/open-architect.ts`) +- #1566 — Codev Tower view; #1211 single-SSE lesson +- #913, #1066, #1563, #1743 — Agents accordion, active-file reveal, agent cycling, click-expands +- #1049 — contextual panel (webview precedent); #859 — markdown-preview canvas webview +- #1189 — server/client isolation +- Related, not absorbed: #1614 (secondary-sidebar container), #1671 (editor-group placement model), + #1548 (architect-context render target) +- `packages/artifact-canvas/README.md` — host-adapter package precedent +- `codev/resources/testing-guide.md` — Playwright verification; `codev/resources/arch.md` — VS Code + Extension, IDE prefix forward (#1668) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md new file mode 100644 index 000000000..d3a32cb31 --- /dev/null +++ b/codev/state/spir-1963_thread.md @@ -0,0 +1,26 @@ +# spir-1963 thread — VS Code alternative layout ("Codev Cockpit") + +## 2026-11-23 — Specify + +No spec existed; wrote `codev/specs/1963-vscode-alternative-layout-seco.md` from the issue. +The issue has no "Baked Decisions" section, but its "Prescribed design choices" are copied into +Constraints as settled. + +Findings that shaped the spec: +- Much Agents-view behaviour is bound to the `codev.agents` TreeView *instance* in `extension.ts` + (click-expands reveal, accordion, active-file reveal, agent-cycle select, badge, title count), and + every menu `when` names the source view id. A combined view needs that wiring generalised to "the + view the row is in" — the main risk on the panel side. +- Work/Decisions components hard-import `apps/web/src/lib/api.ts` (relative URLs, injected key, + localStorage). Sharing them needs a host-adapter seam; recommended a new shared package on the + `codev-artifact-canvas` pattern. +- The SDK `TowerClient` has no decisions methods, and its `request()` drops non-2xx bodies — the + decisions refusal `{ok:false, code, message}` needs preserving. +- `window.open` doesn't work in VS Code webviews (no allow-popups) → Decisions' links/full-size + images need host equivalents. +- Verification must not replace the owner's live IDE extension — isolated instance + fixture + workspace. + +Open points resolved with recommendations, for confirmation at spec-approval: trigger = first show +per window + command; `terminalPosition: panel` overridden for the arrange action; no split/Work/ +Decisions in a builder-worktree window (#1809). From ca5162daa6857481780bae4c45188329cd1f4bfd Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:21:49 -0800 Subject: [PATCH 003/140] chore(porch): 1963 specify build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 24159eed7..dd94df7af 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -14,7 +14,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T01:12:47.025Z' +updated_at: '2026-11-24T01:21:49.325Z' From aca1e16b15810ad649e9a30d05f8025c6cec7daf Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:27:59 -0800 Subject: [PATCH 004/140] [Spec 1963] Specification with multi-agent review --- .../1963-vscode-alternative-layout-seco.md | 179 +++++++++++++----- 1 file changed, 132 insertions(+), 47 deletions(-) diff --git a/codev/specs/1963-vscode-alternative-layout-seco.md b/codev/specs/1963-vscode-alternative-layout-seco.md index c587a6c30..20c982f4d 100644 --- a/codev/specs/1963-vscode-alternative-layout-seco.md +++ b/codev/specs/1963-vscode-alternative-layout-seco.md @@ -137,10 +137,25 @@ default, whose children are exactly the rows the corresponding source view rende existing caches (`OverviewCache`, `TowerFleetCache`, `BuilderDiffCache`, the Workspace provider's Tower reads). There is no second fetch path, no second SSE subscription and no copied grouping or ordering logic. + - **Provider instances:** the combined panel has its **own provider instances** over the + **shared caches**. Its rows are built by the same code as the source views' rows, so they have + the same labels, `contextValue`s and `command`s, but they are distinct objects. Per-view state + (accordion versioning, the group-parent map used by `reveal`, expansion) therefore stays per + view, and a row always belongs to exactly one view. + - **Freshness:** the combined panel takes part in the existing refresh paths, rather than adding + new ones. While it is visible it counts toward the periodic overview refresh + (`codev.overviewRefreshSeconds`) exactly as the Codev-container views do. So with the Codev + container hidden and only the Cockpit visible, Workspace and Agents stay current. The Tower + section rides `TowerFleetCache`'s existing poll and SSE. - **Same actions.** Every click, inline action and context-menu entry a row has in its source view works on the same row in the combined panel with the same effect. Tree behaviours bound to the source view follow the view the row is in: click-expands, accordion, active-file reveal (when the combined panel is the visible one), agent-cycle selection and the `builder-active` hook. +- **Menu contributions are added, not edited.** The existing `view/item/context` and `view/title` + entries for `codev.workspace`, `codev.agents` and `codev.tower` stay byte-for-byte as they are. The + combined view gets its own entries, scoped to it, with the same commands, `viewItem` patterns, + extra `when` terms and groups. A generated parity test fails if any source-view row entry has no + combined-view counterpart, so the two sets cannot drift. - **Section-level actions.** Each source view's title-bar actions (Agents: refresh, group-by cycle, accordion toggle, file-tree toggle; Tower: refresh) are available in the combined panel, attached to the section they act on. The combined view's own title bar carries *Arrange Cockpit* (below) @@ -156,6 +171,10 @@ default, whose children are exactly the rows the corresponding source view rende Workspace shows its worktree-scoped rows, and Tower shows the fleet; - in a **window with no Codev workspace** the Tower section is shown, and in place of Workspace and Agents a single row says no Codev workspace is open, with the open-folder action. +- **Footprint.** The combined view has no `when`, so the new button appears in every window where + the extension activates (`onStartupFinished`), including non-Codev windows. That follows from the + no-workspace requirement, and matches today's Codev and Codev Tower containers, which also appear + there (Agents with its welcome content, Tower with the fleet). ### 3. Work and Decisions in the extension, in a split with the `main` architect @@ -180,6 +199,15 @@ default, whose children are exactly the rows the corresponding source view rende - an http(s) link opens in the user's browser; - clicking an image shows it full size inside the panel, because a webview cannot open browser tabs. +- **Connection and failure states.** Both panels keep last-known-good content, as the sidebar's + caches do: + - before the first data arrives, each shows a loading state; + - while Tower is unreachable or reconnecting, each keeps showing what it last had, with a notice + that it is not connected. Decisions keeps its existing error state (the last document read stays + on screen under the banner), and an in-flight submit that fails shows the error on its card and + keeps the draft; + - a response that arrives after its panel was closed is dropped silently: no toast, no error, no + re-created panel. - **No decisions file.** A workspace without one (no `afx decisions init`) shows an empty state: Tower's "There is no decisions file at …" message plus a hint to run `afx decisions init`. It is not an error banner. The panel keeps polling, so creating the file makes items appear. @@ -191,7 +219,7 @@ default, whose children are exactly the rows the corresponding source view rende | *+ Shell* (dashboard shell tab) | Runs the existing *New Shell* action (a Tower shell opened by `TerminalManager`) | | *Refresh* | Re-reads the overview from Tower, bypassing Tower's overview cache as the dashboard's does, and updates every consumer of `OverviewCache` | | Needs Attention / Backlog / Recently Closed http(s) links (issues, PRs) | Open in the user's browser (as the dashboard and the Pull Requests view do) | - | Backlog / Recently Closed *spec* / *plan* / *review* links (dashboard annotation tab) | Open that file in a VS Code editor. The path is checked by the host to be inside the workspace | + | Backlog / Recently Closed *spec* / *plan* / *review* links (dashboard annotation tab) | Open that file in a VS Code editor. The host refuses the path unless its canonical (symlink-resolved) location is inside the workspace | | *Open Files & Shells* section (dashboard tabs) | **Dropped.** VS Code's own terminal list and editor tabs are the equivalent | | Collapsible *Files* panel (`FileTree`) | **Dropped.** VS Code's Explorer is the equivalent | | *Tip of the day* banner | **Dropped.** Its tips are CLI/dashboard tips, some of which do not apply in VS Code | @@ -220,16 +248,27 @@ default, whose children are exactly the rows the corresponding source view rende - **The user's open editors are never closed, discarded or reloaded**, including dirty and untitled ones. They stay open with their unsaved content and may end up in a different group. - **Triggers:** - - the first time the Cockpit container becomes visible in a window, that window is arranged; - - after that, showing the container again leaves the editor area alone; + - the first time the Cockpit container is visible in a window session, that window is arranged. + This includes a window restored with the container already visible, where no visibility-change + event fires, so the check runs when the view is created as well as on change; + - a window session ends at reload. After a reload the next first show arranges again. Because + arranging is idempotent, an intact layout (panels restored in their groups) changes nothing + visible. The architect terminal, which VS Code does not restore across a reload, is reopened on + the left; + - after the first show, showing the container again leaves the editor area alone; - *Arrange Cockpit* (Command Palette and the combined view's title bar) arranges on demand at any - time, and is idempotent: running it on an already-arranged window changes nothing visible. + time, and is idempotent: running it on an already-arranged window changes nothing visible; + - a setting, `codev.cockpit.autoArrange` (default on), turns the first-show auto-arrange off. With + it off, only the command arranges. - **Where it is offered:** - - in a **builder-worktree window** the split is not offered: no auto-arrange, the title-bar action - is hidden, and the command explains why. This follows #1809: surfaces that act on the parent - workspace stay in the parent's window. Work and Decisions likewise are not offered there; - - in a **window with no Codev workspace** there is nothing to arrange: no auto-arrange, and the - command says no Codev workspace is open. + - in a **builder-worktree window** the split is not offered. There is no auto-arrange and the + title-bar action is hidden. This follows #1809: surfaces that act on the parent workspace stay + in the parent's window. Work and Decisions likewise are not offered there; + - in a **window with no Codev workspace** there is nothing to arrange, and there is no + auto-arrange; + - in both kinds of window, *Arrange Cockpit*, *Open Work* and *Open Decisions* stay invocable + from the Command Palette. Invoking one shows a message saying why it does nothing there, + instead of being silently absent. - **Placement interaction (accepted, not changed here):** with the split in place, builder terminals and issue previews that target "group 2" land in the Work group, per today's placement rules. Changing those rules is #1671's scope. @@ -239,8 +278,9 @@ default, whose children are exactly the rows the corresponding source view rende - [ ] A new activity-bar button with the rotated Codev icon (same path, `rotate(90 400 400)`) appears directly under the Codev button on a fresh profile, in VS Code and in the Codev IDE (including `/ide/`). -- [ ] The existing `codev`, `codev-tower` and `codevPanel` containers, their views, view ids, menus - and badges are byte-for-byte unchanged in `package.json` (additions only), and behave as before. +- [ ] The existing `codev`, `codev-tower` and `codevPanel` containers, their views, view ids, menu + entries and badges are byte-for-byte unchanged in `package.json` (additions only), and behave + as before. - [ ] Clicking the new button opens one tree view with Workspace, Tower and Agents sections showing the same rows as the three source views for the same data. - [ ] Every row click, inline action and context-menu entry of the three source views is present @@ -249,8 +289,12 @@ default, whose children are exactly the rows the corresponding source view rende - [ ] Builder-row click-expands, the accordion, active-file reveal and agent-cycle selection act on the combined panel's rows when it is the visible view. - [ ] Source-view title-bar actions are reachable from the combined panel on their sections. -- [ ] No new Tower polling or SSE subscription is added for the combined panel. The Tower request - count while it is open equals the count with the source views open. +- [ ] No second poll loop or SSE subscription is added for the combined panel. It takes part in the + existing ones, so the Tower request count while it is open equals the count with the source + views open. +- [ ] With the Codev container hidden and only the Cockpit visible, the overview still refreshes on + the `codev.overviewRefreshSeconds` cadence. With neither visible (nor the Work panel), the + periodic refresh stops, as today. - [ ] *Arrange Cockpit* produces `main` architect | (Work over Decisions), each active in its group, with live data in both panels. - [ ] With `main` not live, *Arrange Cockpit* shows the existing warning, opens no other architect, @@ -272,6 +316,14 @@ default, whose children are exactly the rows the corresponding source view rende links open the file, and http(s) links open the browser. No dropped affordance is rendered. - [ ] Neither webview makes a network request to Tower, and the Tower key is absent from webview state and messages. +- [ ] The host opens externally only `http:`/`https:` URLs from a webview, and opens a file from a + webview only when its canonical path is inside the workspace. A symlink escape, `..`, an + absolute path outside the workspace or another URL scheme is refused. +- [ ] With Tower unreachable and then back, both panels keep their last content with a + not-connected notice and recover on reconnect, with no error toast. This is simulated in the + isolated verification instance, never by stopping the owner's Tower. +- [ ] With `codev.cockpit.autoArrange` off, showing the container never arranges, and the command + still does. - [ ] The dashboard's Work and Decisions views look and behave as before. Existing `apps/web` tests (`DecisionsView*.test.tsx`, `useDecisions.test.ts`, `BuilderCard.test.tsx`, `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`, `App.decisions-tab.test.tsx`, …) pass @@ -282,8 +334,11 @@ default, whose children are exactly the rows the corresponding source view rende with Tower plus the no-workspace row. - [ ] Both panels render correctly in a light, a dark and a high-contrast theme and follow a live theme change. -- [ ] `contributes-*` tests cover the new container, view, commands, menus and their `when` clauses. - The existing `contributes-*` tests pass unmodified apart from additions. +- [ ] `contributes-*` tests cover the new container, view, commands, setting, menus and their + `when` clauses. The existing `contributes-*` tests pass unmodified apart from additions. Other + existing tests that assert on `extension.ts` source text, such as + `worktree-window-1809.test.ts`'s badge-suppression match, may be updated to follow + generalised wiring, provided the behaviour they guard is unchanged. - [ ] **Verified by rendering:** the PR carries screenshots taken from a running extension (the Codev IDE at `/ide/` driven by Playwright, or an equivalent isolated instance). They show the button; the combined panel with N=0, N=1 and N>1 builders; the split with a pending decision; @@ -335,7 +390,12 @@ From the system: - VS Code engine floor `^1.128.0`. No API newer than that. - Webview hardening as in the existing webviews: nonce-gated scripts, a CSP that admits only what the panels load, and every inbound webview message validated by a type guard before it is acted - on. A path from a webview is treated as untrusted and confined to the workspace. + on. A path from a webview is treated as untrusted. It is confined to the workspace by its + canonical, symlink-resolved location, not by string prefix. A URL from a webview is opened + externally only if its scheme is `http:` or `https:`. +- The panels' CSP `img-src` must admit host-delivered workspace images. That means `blob:` if they + are shown as object URLs, as the dashboard does, or `data:` if they are encoded. The existing + precedent is `img-src ${cspSource} https: data:`. It must not add `connect-src` for Tower. - The extension stays under the existing `regCli` / `reg` command-registration guard (#791). - UI changes are verified in a browser via Playwright before being called done (`codev/resources/testing-guide.md`). Verification must not replace or disturb the owner's live @@ -363,12 +423,13 @@ From the system: ### A. The combined panel **A1 — Composite tree over the existing providers (recommended).** One `TreeDataProvider` whose -roots are the three section headers. Each section's children, `getTreeItem`, `getParent` and element -identity delegate to a Workspace / Tower / Builders provider instance over the shared caches. The -rows are the same objects with the same `contextValue`s and `command`s. Menu `when` clauses that name -a source view also name the combined view. The TreeView-bound behaviours (reveal on click, -accordion, active-file reveal, agent cycle, selection hook, badge, count) are generalised from "the -Agents view" to "the view the row is in". +roots are the three section headers. Each section's children, `getTreeItem` and `getParent` +delegate to the combined panel's own Workspace / Tower / Builders provider instances, which read the +same shared caches as the source views. The rows are built by the same code, with the same +`contextValue`s and `command`s. The combined view gets its own menu entries, mirroring the source +views' entries; the existing entries are left as they are. The TreeView-bound behaviours (reveal on +click, accordion, active-file reveal, agent cycle, selection hook, badge, count, periodic-refresh +visibility) are generalised from "the Agents view" to "the view the row is in". - Pros: zero copied row logic; every action works because it is the same row; native tree affordances (keyboard nav, context menus, theming) for free. @@ -426,9 +487,10 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme ### C. What triggers the split - **C1 — First show per window, plus command (recommended).** Auto-arranges the first time the - container becomes visible in a window, including on a restore with the container visible. After - that only *Arrange Cockpit* does it. Predictable: re-showing the sidebar (Cmd+B, switching back - from Explorer) never rearranges tabs the user has since changed. + container is visible in a window session, including on a restore with the container visible. + After that only *Arrange Cockpit* does it, and `codev.cockpit.autoArrange` turns the auto-arrange + off. Predictable: re-showing the sidebar (Cmd+B, switching back from Explorer) never rearranges + tabs the user has since changed. - **C2 — Every show (idempotent).** Closest to "clicking the button gives you the layout". But VS Code cannot tell a click from a sidebar toggle, so tabs the user rearranged, or a panel they closed on purpose, keep coming back. @@ -479,10 +541,14 @@ confirmation at this gate. **Unit / contribution (vitest, existing harness):** -1. `contributes-*`: new container after `codev`, the rotated icon file, the combined view with no - `when` (always present), the new commands with palette `when`s (hidden in worktree windows where - specified), and menu entries. Each existing source-view menu entry has a combined-view - counterpart (generated check). +1. `contributes-*`: + - the new container after `codev`, the rotated icon file, and the combined view with no `when` + (always present); + - the new commands, which stay in the palette everywhere, and the `codev.cockpit.autoArrange` + setting; + - the title-bar entries (*Arrange Cockpit* hidden in worktree and no-workspace windows); + - menu parity, a generated check that every existing source-view row entry has a combined-view + counterpart while the existing entries themselves are unchanged. 2. Rotated SVG: same `d` path as `codev.svg`, wrapped in `rotate(90 400 400)`. 3. Composite provider: - section roots and order; @@ -492,42 +558,57 @@ confirmation at this gate. - id uniqueness across sections; - worktree-window and no-workspace variants. 4. Generalised tree behaviours: accordion, click-expands and reveal act on the view a row belongs - to, both for the Agents view (regression) and the combined view. -5. Host message contract: every inbound message guard rejects malformed input; file-open paths - outside the workspace and `..` escapes are refused. -6. Host decisions bridge: document, refusal (structured code/message preserved), transport error, + to, both for the Agents view (regression) and the combined view. Periodic-refresh visibility: + with only the combined view (or only the Work panel) visible the timer runs; with none visible it + stops. +5. Host message contract: + - every inbound message guard rejects malformed input; + - file-open paths outside the workspace, `..` escapes and symlinks resolving outside are refused; + - external-open accepts only `http:`/`https:`; + - a response landing after its panel is disposed is dropped. +6. Auto-arrange trigger: fires once per window session, including when the view is already visible + at creation; does not fire again on later shows; does not fire with `codev.cockpit.autoArrange` + off, in a worktree window or in a no-workspace window. In those windows the commands explain why + instead of acting. +7. Host decisions bridge: document, refusal (structured code/message preserved), transport error, image bytes / not-loaded; not-found maps to the empty state. -7. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no +8. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no substitute); single-instance panels; idempotent re-run. -8. Shared components: the existing `apps/web` tests pass against the moved components through the +9. Shared components: the existing `apps/web` tests pass against the moved components through the dashboard adapter. New tests run the same components with a fake host adapter, asserting that dropped affordances are absent and mapped actions call the adapter. **Rendered (Playwright against a running extension, isolated from the owner's live IDE):** -9. Button: rotated icon directly below Codev; the existing Codev container unchanged. -10. Combined panel with N=0, N=1 and N>1 builders. A builder row's context menu shows the same +10. Button: rotated icon directly below Codev; the existing Codev container unchanged. +11. Combined panel with N=0, N=1 and N>1 builders. A builder row's context menu shows the same entries as in Agents. Approve, open terminal and view diff work from it. A Tower row opens or deactivates a workspace. -11. Arrange on a window with pre-existing editors (one dirty) → the layout appears and the dirty +12. Arrange on a window with pre-existing editors (one dirty) → the layout appears and the dirty editor survives with its content. Arrange again → nothing changes, and a typed Decisions draft persists. -12. `main` not live → warning; Work and Decisions still render. -13. Decisions: rule a pending item → file updated, card shows the ruling, architect notified. A +13. `main` not live → warning; Work and Decisions still render. +14. Decisions: rule a pending item → file updated, card shows the ruling, architect notified. A stale fingerprint gives a refusal with the draft kept. Workspace and http(s) images render; full-size view opens and closes. -14. No decisions file → empty state. Run `afx decisions init` → items appear. -15. Work: Open / + Shell / Refresh / artifact link / external link each do what the mapping table +15. No decisions file → empty state. Run `afx decisions init` → items appear. +16. Work: Open / + Shell / Refresh / artifact link / external link each do what the mapping table says. -16. Light, dark and high-contrast themes, and a live theme switch. -17. Builder-worktree window and no-workspace window variants. -18. Dashboard regression: the browser dashboard's Work and Decisions tabs render and rule as before. +17. Light, dark and high-contrast themes, and a live theme switch. +18. Window variants and degraded states: + - builder-worktree window and no-workspace window, including the commands' explanations; + - Codev container hidden, Cockpit visible: a builder change made in the fixture workspace + appears in the Agents section within one refresh interval. + - Tower unreachable: both panels keep their content under a not-connected notice and recover + when it returns. This is simulated against the isolated instance's own Tower endpoint; the + owner's Tower is never stopped. +19. Dashboard regression: the browser dashboard's Work and Decisions tabs render and rule as before. **Non-functional:** -19. Tower request rate with the combined panel open is unchanged from the source views alone. The +20. Tower request rate with the combined panel open is unchanged from the source views alone. The Decisions poll stops while its panel is hidden. -20. Neither webview opens a network connection to Tower (CSP has no `connect-src` to Tower; the key +21. Neither webview opens a network connection to Tower (CSP has no `connect-src` to Tower; the key is not present in webview state). ## Risks and Mitigation @@ -537,6 +618,10 @@ confirmation at this gate. | The layout command closes or discards a user editor | Low | High | Spike the layout primitive first (Assumptions). The invariant is tested with dirty, untitled and modified editors. If the primitive removes groups unsafely, only add or reuse groups | | Generalising `buildersView`-bound wiring regresses the existing Agents view | Medium | High | Keep the existing Agents view tests as the regression net, add per-view tests for each behaviour, and render both views in verification | | A menu entry is missed in the combined view (dead or absent action) | Medium | Medium | A generated test cross-checks every source-view `view/item/context` and `view/title` entry against a combined-view counterpart | +| The combined panel goes stale because periodic refresh is gated on the Codev-container views' visibility | High if missed | Medium | The combined view and the Work panel count toward the existing visibility gate (a success criterion and tests) | +| Tests that match `extension.ts` source text (e.g. `worktree-window-1809.test.ts`) break when wiring is generalised, and the breakage is misread as a regression | Medium | Low | Named in Success Criteria: such tests are updated to follow the wiring, with the guarded behaviour unchanged | +| Auto-arrange or the `terminalPosition` override is unwelcome for some users | Medium | Low | `codev.cockpit.autoArrange` turns auto-arrange off; the override applies only to the arrange action | +| A webview-supplied path or URL is used to open something outside the workspace or a non-web scheme | Low | High | Canonical-path containment, including symlink resolution, and an `http:`/`https:` allowlist, both enforced and tested host-side | | Moving components changes the dashboard's look or behaviour | Medium | Medium | Thin dashboard wrappers with the current fetch adapter, the existing `apps/web` tests unchanged in intent, and a dashboard render check in verification | | A Decisions draft is lost by the layout or by hiding the panel | Low | High | `retainContextWhenHidden`; arrangement reuses panels and never recreates them; tested. Loss on explicit panel close or reload is parity with the dashboard and stated | | The new button does not sit under Codev for an existing profile (VS Code persists activity-bar order) | Medium | Low | Register directly after `codev`. Verify on a fresh profile and an existing one, and note in the PR if VS Code places it elsewhere for existing profiles (the user can drag it) | From 96939d9e36315e8d2565100326dd0129a03234d0 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:28:14 -0800 Subject: [PATCH 005/140] chore(porch): 1963 spec-approval gate-requested --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index dd94df7af..e9c53f1f3 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -7,6 +7,7 @@ current_plan_phase: null gates: spec-approval: status: pending + requested_at: '2026-11-24T01:28:14.248Z' plan-approval: status: pending pr: @@ -17,4 +18,4 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T01:21:49.325Z' +updated_at: '2026-11-24T01:28:14.248Z' From 365740b3d14da0da548d9c3744d293f25148e146 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:28:24 -0800 Subject: [PATCH 006/140] [Spec 1963] Thread: spec consultation and gate --- codev/state/spir-1963_thread.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index d3a32cb31..5e687a0ec 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -24,3 +24,18 @@ Findings that shaped the spec: Open points resolved with recommendations, for confirmation at spec-approval: trigger = first show per window + command; `terminalPosition: panel` overridden for the arrange action; no split/Work/ Decisions in a builder-worktree window (#1809). + +## 2026-11-23 — Spec consultation (iter 1) → spec-approval + +Codex COMMENT, Claude REQUEST_CHANGES — all points accepted, none disputed (rebuttal in +`codev/projects/1963-*/1963-specify-iter1-rebuttals.md`). Main changes: +- Menus: existing source-view entries left byte-for-byte; the combined view gets mirrored entries + guarded by a generated parity test (widening `when`s would have broken `contributes-tower.test.ts`). +- Freshness: the combined view and the Work panel count toward the existing periodic-overview + visibility gate — otherwise the Cockpit freezes whenever the Codev container is hidden. +- Own provider instances over shared caches (per-view accordion/reveal state). +- Added `codev.cockpit.autoArrange` (default on); defined "window session" (ends at reload); + connection/failure states; canonical-path + http(s)-only host checks; commands stay in the + palette in worktree/no-workspace windows and explain themselves. + +Stopped at spec-approval. From 49db12cd65ad79af8c725e1feb25946776941a37 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:28:35 -0800 Subject: [PATCH 007/140] [Spec 1963] Rebuttal for spec review iteration 1 --- .../1963-specify-iter1-rebuttals.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-specify-iter1-rebuttals.md diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-specify-iter1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-specify-iter1-rebuttals.md new file mode 100644 index 000000000..9b9abb08f --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-specify-iter1-rebuttals.md @@ -0,0 +1,53 @@ +# Spec 1963 — iteration 1 rebuttals + +All points from both reviewers were accepted. Nothing is disputed. Changes are in commit +`[Spec 1963] Specification with multi-agent review`. + +## Claude (REQUEST_CHANGES) + +1. **Menu `when` contradiction (must fix).** Accepted. The spec now chooses option (b): existing + `view/item/context` / `view/title` entries for `codev.workspace` / `codev.agents` / `codev.tower` + stay byte-for-byte. The combined view gets its own mirrored entries, and a generated parity test + fails if any source-view row entry lacks a combined-view counterpart. A1's wording no longer says + clauses are widened. This keeps `contributes-tower.test.ts:47` and the "additions only" criterion + true together. +2. **Freshness gap (must fix).** Accepted. Desired State now says the combined view (and the Work + panel) count toward the existing periodic overview refresh gate. The "no new polling" criterion + is reworded to "no *second* poll loop or SSE subscription; it takes part in the existing ones". + A new criterion, a unit scenario (4) and a rendered scenario (18) check that the overview + refreshes with the Codev container hidden and only the Cockpit visible. A new risk row covers + it too. +3. **Provider instances vs row identity.** Accepted. The spec now commits to *own provider instances + over shared caches*: rows are built by the same code (same labels, `contextValue`s and + `command`s) but are distinct objects. Per-view state (accordion, group-parent map, expansion) + therefore stays per view. +4. **`worktree-window-1809.test.ts` asserts on source text.** Accepted. It is named in Success + Criteria (such tests may be updated to follow generalised wiring, with behaviour unchanged) and + in Risks. +5. **Auto-arrange escape hatch.** Accepted. Added `codev.cockpit.autoArrange` (default on), covered + by a criterion, unit scenario 6, the contributes test and a risk row. +6. **Footprint in every window.** Accepted. A *Footprint* bullet states the button appears in every + window where the extension activates, and that today's Codev and Codev Tower containers already + do. +7. **Restore path for the trigger.** Accepted. The trigger now runs the check when the view is + created as well as on visibility change; unit scenario 6 tests it. +8. **`img-src` needs `blob:`.** Accepted. It is in Constraints: `blob:` for object URLs or `data:` + if encoded, and no `connect-src` for Tower. + +## Codex (COMMENT) + +1. **"First show" across reload / restored panels.** Accepted. A window session is now defined as + ending at reload; the next first show arranges again. Arranging is idempotent, so an intact + restored layout changes nothing visible, and the architect terminal (not restored by VS Code) is + reopened on the left. +2. **Connection, transport and disposal states.** Accepted. A *Connection and failure states* + bullet covers them: loading before first data; last-known-good with a not-connected notice while + Tower is unreachable; Decisions' existing error state and failed-submit behaviour; late + responses dropped after panel close. There is a criterion and a rendered scenario, simulated in + the isolated instance and never by stopping the owner's Tower. +3. **Canonical-path containment and http(s)-only external opens.** Accepted. This is in Constraints + (symlink-resolved containment, not string prefix; `http:`/`https:` allowlist), the Work mapping + table, a criterion, unit scenario 5 and a risk row. +4. **Arrange command invocable where the title action is hidden.** Accepted. *Arrange Cockpit*, + *Open Work* and *Open Decisions* stay in the palette in builder-worktree and no-workspace + windows. Invoking one there shows why it does nothing. Only the title-bar action is hidden. From 76e1dc4980ac2d0a47dd88330c4d9f47451cf323 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:44:56 -0800 Subject: [PATCH 008/140] =?UTF-8?q?[Spec=201963]=20Specification=20with=20?= =?UTF-8?q?user=20feedback:=20single=20Tower=20=E2=86=92=20workspaces=20?= =?UTF-8?q?=E2=86=92=20architects=20+=20Decisions=20=E2=86=92=20builders?= =?UTF-8?q?=20hierarchy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1963-vscode-alternative-layout-seco.md | 507 +++++++++++++----- 1 file changed, 359 insertions(+), 148 deletions(-) diff --git a/codev/specs/1963-vscode-alternative-layout-seco.md b/codev/specs/1963-vscode-alternative-layout-seco.md index 20c982f4d..601d59383 100644 --- a/codev/specs/1963-vscode-alternative-layout-seco.md +++ b/codev/specs/1963-vscode-alternative-layout-seco.md @@ -21,9 +21,10 @@ and two layouts: decision from VS Code today the owner has to leave the editor for the browser dashboard. The owner wants a second, alternative layout for the same extension. It opens from a new button -under the Codev button. It shows one combined left-hand panel (Workspace, Tower and Agents together) -and an editor-area split, with the `main` architect's terminal on the left and Work and Decisions on -the right. The existing Codev container and its views stay as they are. This is an **addition**, not +under the Codev button. It shows one combined left-hand panel, a single hierarchy of Tower → +workspaces → architects and Decisions → the builders each architect spawned, that brings together +what the Workspace, Agents and Tower views show today. It also shows an editor-area split, with the +`main` architect's terminal on the left and Work and Decisions on the right. The existing Codev container and its views stay as they are. This is an **addition**, not a replacement. Affected: the owner (and any Codev user who runs an architect from VS Code or the Codev IDE), in @@ -80,6 +81,23 @@ Pain points today: Menus target the source views by id (`view == codev.agents && viewItem =~ …`), so a row rendered in any other view today would lose its inline and context actions. +**What the extension knows about other workspaces.** + +- `TowerFleetCache` already calls `client.getOverview(path)` for **every active workspace** on each + fleet refresh (SSE-triggered with a 300 ms debounce, plus a 20 s fallback poll). + - Each overview carries that workspace's live `architects` and its `builders`, each with + `spawnedByArchitect`, state, gate and worktree path. + - The cache keeps only the derived `AttentionSummary` and discards the overview. + - Dormant workspaces are not fetched. +- No overview carries anything about the decisions file. Its presence is only in `/api/state`'s + `decisionsEnabled`, and its open count is only in `/api/decisions` itself. +- The extension's *actions* are single-workspace: + - `TerminalManager` builds terminal URLs from the window's workspace path and keys its cache by + unqualified names (`architect:main`, `builder-`); + - `codev.openArchitectTerminal` and every builder-row command (approve, diff, artifacts, worktree, + dev) resolve the target against `connectionManager.getWorkspacePath()`; + - `BuilderDiffCache` is keyed by builder id alone. + **Editor-area placement** (`terminal-manager.ts`): with `codev.terminalPosition: "editor"` (the default) the architect terminal opens in editor group 1. Builder and shell terminals open in group 2 if it exists, else group 1. With `"panel"` they open in the bottom panel. `open-architect.ts` holds @@ -127,54 +145,145 @@ A new activity-bar container, working name **"Codev Cockpit"**, registered direc as `icons/codev.svg` in `transform="rotate(90 400 400)"` (clockwise). The shape is not redrawn. The existing `codev`, `codev-tower` and `codevPanel` containers and every view in them are unchanged. -### 2. One combined left-hand panel - -The container holds **one tree view** with three top-level **sections**: *Workspace*, *Tower* and -*Agents* (that order; see Open Questions). Each section is a collapsible header row, expanded by -default, whose children are exactly the rows the corresponding source view renders today: - -- **Same data, same rows.** Sections read the existing providers' row-building logic over the - existing caches (`OverviewCache`, `TowerFleetCache`, `BuilderDiffCache`, the Workspace provider's - Tower reads). There is no second fetch path, no second SSE subscription and no copied grouping or - ordering logic. - - **Provider instances:** the combined panel has its **own provider instances** over the - **shared caches**. Its rows are built by the same code as the source views' rows, so they have - the same labels, `contextValue`s and `command`s, but they are distinct objects. Per-view state - (accordion versioning, the group-parent map used by `reveal`, expansion) therefore stays per - view, and a row always belongs to exactly one view. - - **Freshness:** the combined panel takes part in the existing refresh paths, rather than adding - new ones. While it is visible it counts toward the periodic overview refresh - (`codev.overviewRefreshSeconds`) exactly as the Codev-container views do. So with the Codev - container hidden and only the Cockpit visible, Workspace and Agents stay current. The Tower - section rides `TowerFleetCache`'s existing poll and SSE. -- **Same actions.** Every click, inline action and context-menu entry a row has in its source view - works on the same row in the combined panel with the same effect. Tree behaviours bound to the - source view follow the view the row is in: click-expands, accordion, active-file reveal (when the - combined panel is the visible one), agent-cycle selection and the `builder-active` hook. +### 2. One combined left-hand panel: a single hierarchy + +The container holds **one tree view** with **one hierarchy**. In the owner's words, at the spec +gate: *"towers -> workspaces -> architects / decisions -> builders"*. This supersedes the issue +body's reading of step 2 as three side-by-side sections (issue #1963, owner revision comment). + +``` +Tower ← root: this machine's Tower +├─ codev current · 1 gate ← workspace (Tower view's set, labels, order) +│ ├─ MAIN (3) waiting for input ← architect (its own Spec 1595 state) +│ │ ├─ ⚠ spir-1963 [PLAN] … ← builder spawned by MAIN +│ │ │ └─ src/views/cockpit.ts ← changed files (this window's workspace only) +│ │ └─ ● bugfix-1970 … 2 held +│ ├─ WEB (0) ← architect with no builders (leaf) +│ └─ Decisions ← that workspace's Decisions screen +├─ marketmaker 2 waiting +│ ├─ MAIN (1) +│ │ └─ ◐ air-88 … +│ └─ Decisions +└─ Dormant (4) + └─ old-project +``` + +**Levels:** + +1. **Tower.** One root row for the machine's Tower, expanded by default. While there is nothing to + list it holds Tower's existing state rows (*Connecting to Tower…*, *No workspaces registered*). +2. **Workspaces.** Exactly the Tower view's workspaces, with the same labels (so twelve workspaces' + `MAIN`s are told apart by their parent row), urgency order, *current* marker, icons, attention + summary in the description, inline *Open* / *Deactivate*, and the collapsed *Dormant (N)* group. + This reuses `orderFleet` and `TowerProvider`'s row building. The window's own workspace and every + workspace that needs attention start expanded; quiet ones start collapsed. A dormant workspace + has no children, because it has no live session, as today. +3. **Architects + Decisions.** Under an active workspace: + - its live architects, `main` first, then siblings alphabetically. Two or more idle siblings roll + up into *Idle Architects*. This is the Agents view's architect-axis rendering + (`architectGrouping`, `partitionArchitectGroups`); + - then a **Decisions** entry for that workspace's decisions file. +4. **Builders.** Under each architect, the builders that architect spawned (`spawnedByArchitect`), + in the Agents view's order (blocked, then waiting, then active) and with the architect axis's + `[stage]` prefix. + - A builder with **no recorded spawning architect** sits under `main` (architectGrouping's + existing fold). + - A builder whose recorded architect is **not live** gets that architect's row anyway, as the + architect axis does today. Clicking that row gives the existing "No '' architect found" + warning. + - An **architect with no builders** is a leaf row with no chevron. +5. **Changed files.** Under a builder of the window's own workspace, its changed files, flat or as a + folder tree, exactly as in the Agents view. + +**Data.** There are no Tower route changes, no new requests and no new poll loop: + +- **The window's own workspace** reads `OverviewCache`, as the Agents view does. While visible, the + combined view counts toward the periodic overview refresh (`codev.overviewRefreshSeconds`) the + way the Codev-container views do. So with the Codev container hidden and only the Cockpit + visible, this workspace's rows stay current. +- **Every other active workspace** reads the overview `TowerFleetCache` *already fetches* for it on + each fleet refresh (`client.getOverview(path)` in its fan-out). Today the cache derives attention + from each overview and discards it. It will keep it, last-known-good like the attention it keeps. + These rows refresh when the Tower view's do: on SSE events (debounced) and on the existing 20 s + fallback poll. +- **Decisions:** the overview carries nothing about the decisions file, neither presence nor an + open count, so the Decisions entry carries **no pending count**. It is shown under every active + workspace. Opening it for a workspace with no decisions file shows the Decisions empty state + (section 3). A count, or hiding the entry when there is no file, would need an additive overview + field; see Open Questions. + +**Where rows act: this window's workspace vs the rest.** Every `TerminalManager` key +(`architect:`, `builder-`), the #1497 architect resolution, and every builder command +(approve, view diff, spec/plan/review, worktree window/folder, setup, dev) resolve against **this +window's** workspace today. So: + +- **Rows of the window's own workspace act here, fully.** Every action listed below works, with the + same commands and the same effects as in the source views. The Decisions entry opens, or reveals, + that workspace's Decisions panel (single instance; section 3) without arranging the split. +- **Rows of any other workspace show state and navigate.** Its architects, builders and Decisions + entry display what the overview says (glyphs, labels, descriptions). Clicking one opens that + workspace's window, using the Tower view's existing *Open Workspace* action, where the same rows + are fully actionable. These rows carry no other actions and do not expand to changed files. + Acting on another workspace from this window is a separate, larger change; see Open Questions. + +**Placement of everything the three source views do.** Nothing is dropped: + +| Today | In the hierarchy | +|---|---| +| Workspace: *Spawn Builder*, *New Shell* | Inline and context-menu actions on this window's workspace row | +| Workspace: *Add Architect* (inline on the *Architects* root) | Inline and context-menu action on this window's workspace row | +| Workspace: *Remove Architect* (sibling context menu) | Context menu on a sibling architect row of this window's workspace | +| Workspace: architect rows (click opens the terminal) | The architect level. Click runs `codev.openArchitectTerminal(name)`, under the #1497 invariant | +| Workspace: *Open Web Interface* | Context menu on this window's workspace row | +| Workspace: *Start Dev* / *Stop Dev* | Context menu on this window's workspace row, offering whichever one the Workspace view would show (same single-slot rules) | +| Workspace: one row per `worktree.devUrls` entry | *Open Dev URL…* on this window's workspace row's context menu. It opens the only URL, or picks among several (the existing palette path of `codev.openDevUrl`). This is the one Workspace affordance that goes from one click to a menu entry | +| Agents: builder rows: click (open terminal + expand), inline *Approve Gate*, context menu (open terminal, approve, view spec/plan/review, view diff, open worktree window/folder, run setup, run/stop dev) | Builder rows of this window's workspace: identical | +| Agents: changed-files expansion (flat/tree), file click → diff | Identical, for this window's workspace | +| Agents: architect-axis headers (click opens architect), *Idle Architects* container | They are the architect level | +| Agents: stage / area grouping axes, group-by cycle | **Not in the combined panel.** The hierarchy fixes the architect axis. Stage and area grouping stay in the Agents view, and the architect axis's `[stage]` row prefix stays | +| Agents: refresh, accordion toggle, file-tree toggle (title bar) | The combined view's title bar | +| Agents: live count in the title | Each architect row's builder count. The workspace row's attention summary | +| Agents: activity badge | The combined view's badge (same count and suppression, as ruled at the gate) | +| Tower: workspace rows, *current* marker, urgency order, inline *Open* / *Deactivate*, *Dormant* group | The workspace level: identical | +| Tower: refresh (title bar) | The combined view's *Refresh*, which refreshes both caches | +| Tower attention row: pending gate | The blocked builder row (gate glyph + wait time) under its architect | +| Tower attention row: waits (needs input / idle / dead) | The builder row's state glyph and label | +| Tower attention row: architect at a prompt / agent dead (Spec 1595) | The architect row's description and glyph (the same wait text the attention row uses) | +| Tower attention row: held mail for a builder | The builder row's description (*N held*) | +| Tower attention row: held mail not attributed to a builder | The workspace row's description (*N held*, *escalated*) | +| Tower attention row: queued feedback | The builder row's description (*N queued*) | +| Tower: machine-wide badge | Stays on the Codev Tower container | + +The same state rendering applies to other workspaces' rows (from their overviews), so a gate or +wait anywhere on the machine is visible on the row it concerns. + +**Other requirements:** + +- **Provider instances.** The combined panel has its own provider instances over the shared caches. + Its rows are built by the same code as the source views' rows, with the same labels, + `contextValue`s and `command`s, but they are distinct objects. Per-view state (accordion + versioning, the parent map used by `reveal`, expansion) stays per view, and a row belongs to + exactly one view. Tree-item ids are qualified by workspace, so two workspaces' `main` or a + builder id that appears in two workspaces never collide. +- **Tree behaviours follow the view a row is in.** Click-expands, the accordion, active-file reveal + (when the combined panel is the visible one), agent-cycle selection and the `builder-active` hook + act on the combined panel's rows for this window's workspace. - **Menu contributions are added, not edited.** The existing `view/item/context` and `view/title` - entries for `codev.workspace`, `codev.agents` and `codev.tower` stay byte-for-byte as they are. The - combined view gets its own entries, scoped to it, with the same commands, `viewItem` patterns, - extra `when` terms and groups. A generated parity test fails if any source-view row entry has no - combined-view counterpart, so the two sets cannot drift. -- **Section-level actions.** Each source view's title-bar actions (Agents: refresh, group-by cycle, - accordion toggle, file-tree toggle; Tower: refresh) are available in the combined panel, attached - to the section they act on. The combined view's own title bar carries *Arrange Cockpit* (below) - and *Refresh*. -- **Section headers** show the same live summary the source view's title does (*Agents (N)*). + entries for `codev.workspace`, `codev.agents` and `codev.tower` stay byte-for-byte. The combined + view gets its own entries, scoped to it, at the placements in the table above. A generated parity + test checks every source-view entry against its counterpart, so the two cannot drift. - **Badge.** The combined view badges the new activity-bar button with the same workspace "needs me" - count as the Codev button (`composeActivityBadge`), under the same suppression rules. The Tower - container keeps its machine-wide badge. -- **Empty and degraded states:** - - an Agents section with no builders shows a single *No active builders* row, not an empty header; - - Tower's *Connecting to Tower…* and *No workspaces registered* rows appear as they do today; - - in a **builder-worktree window** the Agents section is absent (as `codev.agents` is today), - Workspace shows its worktree-scoped rows, and Tower shows the fleet; - - in a **window with no Codev workspace** the Tower section is shown, and in place of Workspace - and Agents a single row says no Codev workspace is open, with the open-folder action. + count as the Codev button (`composeActivityBadge`), under the same suppression rules. +- **Degraded windows:** + - In a **builder-worktree window**, the parent workspace's row is marked current but behaves like + another workspace's row: its architects, builders and Decisions entry navigate to the parent's + window and act on nothing here (#1809, and the gate ruling that Decisions is not offered there). + The worktree-scoped actions the Workspace view shows in such a window (*Open Web Interface*, + *Start* / *Stop Dev*, dev URLs) sit on that row's context menu. + - In a **window with no Codev workspace**, every workspace's rows navigate; none acts here. - **Footprint.** The combined view has no `when`, so the new button appears in every window where - the extension activates (`onStartupFinished`), including non-Codev windows. That follows from the - no-workspace requirement, and matches today's Codev and Codev Tower containers, which also appear - there (Agents with its welcome content, Tower with the fleet). + the extension activates (`onStartupFinished`), including non-Codev windows, as the owner ruled at + the gate. This matches today's Codev and Codev Tower containers, which also appear there. ### 3. Work and Decisions in the extension, in a split with the `main` architect @@ -230,9 +339,14 @@ default, whose children are exactly the rows the corresponding source view rende - **Themed by VS Code.** Both panels take their colours, fonts and focus styles from VS Code theme variables, so they read correctly in light, dark and high-contrast themes and follow a theme change live. -- **Single instance.** One Work panel and one Decisions panel per window. Opening either again - reveals the existing panel and never creates a second one or reloads the first. Each can also be - opened on its own from the Command Palette (*Codev: Open Work*, *Codev: Open Decisions*). +- **Single instance.** One Work panel and one Decisions panel per window, both for the window's own + workspace. Opening either again reveals the existing panel and never creates a second one or + reloads the first. Each can also be opened on its own, from the Command Palette (*Codev: Open + Work*, *Codev: Open Decisions*). Decisions also opens from the hierarchy's Decisions entry under + the window's own workspace. +- **Restored after reload.** An open Work or Decisions panel comes back after a window reload in the + group it was in, using VS Code's webview restore. Decisions drafts do not survive a reload, as + they do not survive a dashboard page reload. **The split (*Arrange Cockpit*):** @@ -281,17 +395,33 @@ default, whose children are exactly the rows the corresponding source view rende - [ ] The existing `codev`, `codev-tower` and `codevPanel` containers, their views, view ids, menu entries and badges are byte-for-byte unchanged in `package.json` (additions only), and behave as before. -- [ ] Clicking the new button opens one tree view with Workspace, Tower and Agents sections showing - the same rows as the three source views for the same data. -- [ ] Every row click, inline action and context-menu entry of the three source views is present - and works on the same row in the combined panel. This is checked against a list generated from - `package.json` menus, so none is missed. +- [ ] Clicking the new button opens one tree view with one hierarchy: Tower → workspaces (the Tower + view's set, labels, order, *current* marker, Dormant group) → each active workspace's live + architects plus a Decisions entry → the builders each architect spawned → (this window's + workspace only) their changed files. +- [ ] Builders with no recorded spawning architect appear under `main`. An architect with no + builders is a leaf. Two or more idle siblings roll up into *Idle Architects*. A builder whose + recorded architect is not live keeps that architect's row. +- [ ] Every item in the placement table (Desired State §2) is where the table says, and works there. + Every source-view row click, inline action and context-menu entry for this window's workspace + has its counterpart. This is checked by a test generated from `package.json` menus against + that table, so none is missed. +- [ ] Every Tower attention signal (pending gate, wait, architect at a prompt or dead, held mail per + builder and unattributed, queued feedback) is visible on the row it concerns, for this + workspace and for others. +- [ ] Rows of another workspace show state and, when clicked, open that workspace's window through + the existing *Open Workspace* action. They run no other action here and do not expand to + changed files. +- [ ] Two workspaces with an architect named `main`, and a builder id present in two workspaces, + render as distinct rows with no tree-id collision. - [ ] Builder-row click-expands, the accordion, active-file reveal and agent-cycle selection act on - the combined panel's rows when it is the visible view. -- [ ] Source-view title-bar actions are reachable from the combined panel on their sections. -- [ ] No second poll loop or SSE subscription is added for the combined panel. It takes part in the - existing ones, so the Tower request count while it is open equals the count with the source - views open. + the combined panel's rows for this window's workspace when it is the visible view. +- [ ] The Agents and Tower title-bar actions other than group-by (refresh, accordion toggle, + file-tree toggle) are on the combined view's title bar. Stage and area grouping stay only in + the Agents view, and the combined panel ignores `codev.buildersGroupBy`. +- [ ] No second poll loop, SSE subscription or new Tower route is added for the combined panel. + Other workspaces' rows come from the overviews `TowerFleetCache` already fetches, so the Tower + request count while the Cockpit is open equals the count with the source views open. - [ ] With the Codev container hidden and only the Cockpit visible, the overview still refreshes on the `codev.overviewRefreshSeconds` cadence. With neither visible (nor the Work panel), the periodic refresh stops, as today. @@ -329,9 +459,13 @@ default, whose children are exactly the rows the corresponding source view rende `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`, `App.decisions-tab.test.tsx`, …) pass unchanged in intent. - [ ] No React component used by Work or Decisions exists in two copies in the repo. -- [ ] In a builder-worktree window: the button and combined panel work (no Agents section), and the - split, Work and Decisions are not offered. In a no-workspace window: the button and panel work, - with Tower plus the no-workspace row. +- [ ] In a builder-worktree window: the button and combined panel work. The parent workspace's rows + navigate to the parent's window, the worktree-scoped actions are on its row, and the split, + Work and Decisions are not offered. In a no-workspace window: the button and panel work, and + every workspace's rows navigate. +- [ ] The Decisions entry under this window's workspace opens, or reveals, the single Decisions + panel without arranging the split. For a workspace without a decisions file it opens the empty + state. - [ ] Both panels render correctly in a light, a dark and a high-contrast theme and follow a live theme change. - [ ] `contributes-*` tests cover the new container, view, commands, setting, menus and their @@ -341,8 +475,8 @@ default, whose children are exactly the rows the corresponding source view rende generalised wiring, provided the behaviour they guard is unchanged. - [ ] **Verified by rendering:** the PR carries screenshots taken from a running extension (the Codev IDE at `/ide/` driven by Playwright, or an equivalent isolated instance). They show the - button; the combined panel with N=0, N=1 and N>1 builders; the split with a pending decision; - and light and dark themes. + button; the combined hierarchy with N=0, N=1 and N>1 builders and with two or more workspaces; + the split with a pending decision; and light and dark themes. - [ ] Lint, type-check and the full `apps/vscode`, `apps/web` and shared-package test suites pass. ## Constraints @@ -373,10 +507,24 @@ From the issue body: removed or moved. - The icon is a new SVG rotating the same path (`transform="rotate(90 400 400)"`), not a redrawn shape. -- "A single panel" is one view with three sections, not three stacked views sharing a container. - One source of truth: the combined panel reuses `views/workspace.ts`, `views/builders.ts`, `views/tower.ts`, `overview-data.ts` and `tower-cache.ts`, with no second copy of fetch or grouping logic. + +From the owner at the spec gate (issue #1963 comments; supersedes the issue body's "one view with +three sections"): + +- *"towers -> workspaces -> architects / decisions -> builders."* The combined panel is one + hierarchy: Tower → workspaces → architects and a Decisions entry → the builders each architect + spawned. +- Nothing the three source views do may silently disappear. Each is placed in the hierarchy or + deliberately left to the existing views (the placement table). +- No per-workspace poll loop is added to supply hierarchy data, and the "no Tower route changes" + constraint is not dropped quietly. Any need for data Tower does not serve is a gate question. +- Otherwise the spec as drafted stands ("Other than that spec sounds good"): first-show trigger and + `codev.cockpit.autoArrange`; the `terminalPosition` override; no split in worktree windows; the + new shared package; name, rotation and badge; the button in every window; builder-terminal + placement left to #1671. - The architect goes through `open-architect.ts` / `TerminalManager`, and the #1497 invariant holds. @@ -422,35 +570,63 @@ From the system: ### A. The combined panel -**A1 — Composite tree over the existing providers (recommended).** One `TreeDataProvider` whose -roots are the three section headers. Each section's children, `getTreeItem` and `getParent` -delegate to the combined panel's own Workspace / Tower / Builders provider instances, which read the -same shared caches as the source views. The rows are built by the same code, with the same -`contextValue`s and `command`s. The combined view gets its own menu entries, mirroring the source -views' entries; the existing entries are left as they are. The TreeView-bound behaviours (reveal on -click, accordion, active-file reveal, agent cycle, selection hook, badge, count, periodic-refresh -visibility) are generalised from "the Agents view" to "the view the row is in". +**A1 — A hierarchical composite over the existing row builders, acting only on this window's +workspace (recommended).** One `TreeDataProvider` renders the hierarchy: + +- the Tower root; +- workspace rows from `TowerProvider`'s row building and `orderFleet`; +- under this window's workspace, the architect-axis rows built by `BuildersProvider` over + `OverviewCache`, then the Decisions entry; +- under each other active workspace, the same architect-axis rows, built by the same pure functions + (`orderForDisplay`, `architectGrouping`, `partitionArchitectGroups`, `builderRowLabel`, + `classifyBuilderRow`) over the overview `TowerFleetCache` already fetched and now keeps. These + rows are navigate-only. + +Tower's attention signals fold onto the rows they concern, using `deriveAttention`'s summary and the +existing `describeWait` / `gateIconFor` text and glyphs. The combined view gets its own menu entries +at the placement table's positions; the existing entries are untouched. The TreeView-bound +behaviours (reveal on click, accordion, active-file reveal, agent cycle, selection hook, badge, +periodic-refresh visibility) are generalised from "the Agents view" to "the view the row is in". + +- Pros: the owner's hierarchy, with no Tower change and no new requests. No copied fetch, grouping + or row logic. Every action of this window's workspace works because the rows are built by the + same code. The rule "act here only for this window's workspace" matches #1809, the gate ruling on + worktree windows, and the Tower view's existing click-to-open behaviour. +- Cons: + - `extension.ts` wiring that today closes over `buildersView` must be generalised; + - `TowerFleetCache` keeps each overview (memory for N overviews, bounded by the number of active + workspaces); + - tree ids must be workspace-qualified; + - Tower's workspace-row node type and `vscode.TreeItem` rows make the element type a union; + - another workspace's rows navigate rather than act. +- Risk: medium. + +**A2 — The same hierarchy, fully actionable for every workspace in this window.** Clicking another +workspace's architect or builder opens its terminal here, its context menu works here, and its +Decisions entry opens its Decisions panel here. This needs no Tower route changes (terminal and +decisions routes are already workspace-scoped), but it is a large extension change: -- Pros: zero copied row logic; every action works because it is the same row; native tree - affordances (keyboard nav, context menus, theming) for free. -- Cons: `extension.ts` wiring that today closes over `buildersView` must be generalised. Element ids - must stay unique across sections. Tower's non-`TreeItem` node type means the composite element is - a union. -- Risk: medium. The generalisation touches well-tested behaviour, and existing tests guard the - source views. +- `TerminalManager` keys and URLs qualified by workspace; +- the #1497 invariant restated over (workspace, architect name); +- the reference-injection commands, agent cycling and terminal pruning made workspace-aware; +- every builder command (approve, diff, artifacts, worktree, setup, dev) and `BuilderDiffCache` + made workspace-aware; +- per-workspace Decisions panel instances. -**A2 — A webview that renders all three sections.** One React webview drawing the rows as HTML. +Pros: one window drives the whole fleet. Cons: doubles the change's surface and reopens a +recently fixed invariant. Not recommended in this spec; offered at the gate as a follow-up. -- Pros: full layout freedom. -- Cons: re-implements every row, glyph, ordering and menu in HTML: a second copy of row behaviour, - which the issue forbids. Native context menus, keyboard navigation and tree theming are lost. -- Risk: high. Rejected. +**A3 — Keep Tower's attention rows under each workspace, beside the architects.** Pros: the +attention list stays scannable as a list. Cons: every gate and wait appears twice (once as an +attention row, once on its builder row), which is the duplication a single hierarchy is meant to +remove. Not recommended. -**A3 — Three views in one container.** Register Workspace, Tower and Agents views again under the -new container. +**A4 — A webview that renders the tree.** Re-implements every row, glyph, ordering and menu in HTML, +a second copy of row behaviour, and loses native context menus, keyboard navigation and tree +theming. Rejected. -- Pros: least code. -- Cons: the issue explicitly reads "a single panel" as one view with three sections. Rejected. +*(The draft's three-section composite, one section per source view, is superseded by the owner's +hierarchy ruling.)* ### B. Sharing Work and Decisions @@ -507,35 +683,51 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme ## Open Questions -**Critical (blocks progress):** none. The issue's five working assumptions are adopted below, for -confirmation at this gate. - -**Important (shapes design), recommendation given; confirm at the gate:** - -1. **Trigger semantics.** The issue assumes "showing the new container arranges the split". This - spec narrows that to *the first show per window*, plus the command (C1 over C2). Confirm. -2. **`codev.terminalPosition: "panel"`.** This spec has *Arrange Cockpit* put the architect in the - left editor group regardless of the setting (moving an already-open panel terminal into the - editor), because the user explicitly asked for the layout. The alternative is to honour the - setting and leave the left column without the architect. Confirm. -3. **Builder-worktree window.** This spec does not offer the split, Work or Decisions there, - following #1809's "parent-acting surfaces stay in the parent's window". The combined panel still - works (Workspace worktree rows + Tower). The alternative is to show the parent's Work and - Decisions there too. Confirm. -4. **Shared package location/name.** Recommendation: a new `packages/` workspace package bundled by - both hosts (B1). The plan names it. +**Ruled at the spec gate (owner, 2026-11-24; recorded here, not reopened):** + +- **Trigger:** first show per window session, plus *Arrange Cockpit*, plus + `codev.cockpit.autoArrange`. +- **`terminalPosition: "panel"`:** *Arrange Cockpit* puts the architect in the left editor group + anyway. Every other open path honours the setting. +- **Builder-worktree windows:** no split, Work or Decisions. +- **Shared code:** a new `packages/` workspace package bundled by both hosts (B1). The plan names it. +- **Name, rotation, badge:** "Codev Cockpit"; clockwise; the workspace "needs me" count. +- **Footprint:** the button is present in every window. +- **Builder terminals:** placement over the Work group is left to #1671. +- **Reload persistence:** Work and Decisions panels are restored after a window reload, as specced. +- **Combined panel:** one hierarchy, Tower → workspaces → architects + Decisions → builders. Section + order is therefore moot. + +**Important (shapes scope); for the owner at the gate, nothing assumed:** + +1. **Acting on other workspaces from this window.** This spec makes another workspace's rows + navigate: clicking opens that workspace's window (A1). Making them fully actionable here (A2) + needs no Tower route changes but is a large extension change. It requires workspace-qualified + terminal keys, the #1497 invariant over (workspace, name), every builder command made + workspace-aware, and per-workspace Decisions panels. **Recommendation:** A1 now, A2 as a + follow-up if wanted. + - A narrower middle option: opening *another workspace's Decisions screen* in this window + (decisions routes are workspace-scoped; no terminal changes) while terminals still navigate. + Its cost is per-workspace Decisions panels and their single-instance rule. Not specced unless + ruled in. +2. **Decisions pending count / file presence.** The overview carries neither, so the Decisions + entry shows no count and appears for every active workspace (opening it shows the empty state + when there is no file). + - Showing a count, or hiding the entry when there is no file, needs an **additive Tower change**: + a decisions summary (present, open count) in the overview payload. The existing fleet fan-out + would then carry it with no new requests. + - **Recommendation:** no count in this spec; the additive field as a separate change if wanted. + This spec keeps "no Tower route changes". **Nice-to-know:** -5. **Container name.** "Codev Cockpit" (working title) unless the owner prefers another. -6. **Rotation direction.** Clockwise (`rotate(90 …)`), as assumed. -7. **Section order.** Workspace, Tower, Agents (the owner's spoken order). Workspace, Agents, Tower - is the alternative. -8. **Badge source.** The workspace "needs me" count (same as the Codev button) rather than Tower's - machine-wide count. -9. **Reload persistence.** Whether Work and Decisions panels are restored after a window reload - (webview serializer) or re-created by the next arrange. Recommendation: restore them. Decisions - drafts are lost on reload either way, as they are on a dashboard page reload. +3. **Ordering of this window's workspace.** It keeps its urgency slot, as in the Tower view (#1566), + and starts expanded. Pinning it first is the alternative. +4. **Decisions entry position.** After the architects, per the owner's order ("architects / + decisions"). First under the workspace is the alternative. +5. **Dev URLs.** They become one context-menu entry (*Open Dev URL…*) on the workspace row instead + of one row each. Keeping them as rows under the workspace is the alternative, at the cost of + hierarchy clutter. ## Test Scenarios @@ -547,68 +739,83 @@ confirmation at this gate. - the new commands, which stay in the palette everywhere, and the `codev.cockpit.autoArrange` setting; - the title-bar entries (*Arrange Cockpit* hidden in worktree and no-workspace windows); - - menu parity, a generated check that every existing source-view row entry has a combined-view - counterpart while the existing entries themselves are unchanged. + - menu parity, a generated check that every existing source-view entry has its counterpart at + the placement table's position in the combined view, while the existing entries themselves are + unchanged. 2. Rotated SVG: same `d` path as `codev.svg`, wrapped in `rotate(90 400 400)`. -3. Composite provider: - - section roots and order; - - children equal the source providers' children for the same cache state (N=0, N=1, N>1 - builders; each group-by axis); - - `getParent` chains for reveal; - - id uniqueness across sections; - - worktree-window and no-workspace variants. -4. Generalised tree behaviours: accordion, click-expands and reveal act on the view a row belongs +3. Hierarchy provider: + - Tower root, then workspaces in the Tower view's order, labels, *current* marker and Dormant + group, for the same `TowerFleetCache` state; + - this window's workspace: architect rows and builders equal the Agents view's architect-axis + rows for the same `OverviewCache` state (N=0, N=1, N>1 builders; idle siblings rolled up; + builders with no recorded architect under `main`; a non-live recorded architect; an architect + with no builders), then the Decisions entry; + - another workspace: the same shape from its retained fleet overview, with navigate-only commands + and no changed-files expansion; + - each attention signal lands on the row the placement table names; + - `getParent` chains for reveal; id uniqueness with two workspaces that each have `main` and a + shared builder id; + - worktree-window and no-workspace variants; + - `codev.buildersGroupBy` set to stage or area leaves the hierarchy unchanged. +4. `TowerFleetCache`: it keeps each active workspace's overview from the fetch it already makes, + with no additional request, last-known-good on a failed fetch, dropped when a workspace leaves + the list or goes dormant; the Tower view's rendering is unchanged. +5. Generalised tree behaviours: accordion, click-expands and reveal act on the view a row belongs to, both for the Agents view (regression) and the combined view. Periodic-refresh visibility: with only the combined view (or only the Work panel) visible the timer runs; with none visible it stops. -5. Host message contract: +6. Host message contract: - every inbound message guard rejects malformed input; - file-open paths outside the workspace, `..` escapes and symlinks resolving outside are refused; - external-open accepts only `http:`/`https:`; - a response landing after its panel is disposed is dropped. -6. Auto-arrange trigger: fires once per window session, including when the view is already visible +7. Auto-arrange trigger: fires once per window session, including when the view is already visible at creation; does not fire again on later shows; does not fire with `codev.cockpit.autoArrange` off, in a worktree window or in a no-workspace window. In those windows the commands explain why instead of acting. -7. Host decisions bridge: document, refusal (structured code/message preserved), transport error, +8. Host decisions bridge: document, refusal (structured code/message preserved), transport error, image bytes / not-loaded; not-found maps to the empty state. -8. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no +9. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no substitute); single-instance panels; idempotent re-run. -9. Shared components: the existing `apps/web` tests pass against the moved components through the +10. Shared components: the existing `apps/web` tests pass against the moved components through the dashboard adapter. New tests run the same components with a fake host adapter, asserting that dropped affordances are absent and mapped actions call the adapter. **Rendered (Playwright against a running extension, isolated from the owner's live IDE):** -10. Button: rotated icon directly below Codev; the existing Codev container unchanged. -11. Combined panel with N=0, N=1 and N>1 builders. A builder row's context menu shows the same - entries as in Agents. Approve, open terminal and view diff work from it. A Tower row opens or - deactivates a workspace. -12. Arrange on a window with pre-existing editors (one dirty) → the layout appears and the dirty +11. Button: rotated icon directly below Codev; the existing Codev container unchanged. +12. Combined hierarchy with two or more active workspaces and N=0, N=1 and N>1 builders: + - this workspace's builder row context menu shows the same entries as in Agents, and approve, + open terminal and view diff work from it; + - the workspace row's actions work (Spawn Builder, New Shell, Add Architect, Open Web + Interface, Start/Stop Dev, Open Dev URL…), and the Decisions entry opens Decisions; + - another workspace's architect or builder row opens that workspace's window; + - a workspace row opens or deactivates as in the Tower view. +13. Arrange on a window with pre-existing editors (one dirty) → the layout appears and the dirty editor survives with its content. Arrange again → nothing changes, and a typed Decisions draft persists. -13. `main` not live → warning; Work and Decisions still render. -14. Decisions: rule a pending item → file updated, card shows the ruling, architect notified. A +14. `main` not live → warning; Work and Decisions still render. +15. Decisions: rule a pending item → file updated, card shows the ruling, architect notified. A stale fingerprint gives a refusal with the draft kept. Workspace and http(s) images render; full-size view opens and closes. -15. No decisions file → empty state. Run `afx decisions init` → items appear. -16. Work: Open / + Shell / Refresh / artifact link / external link each do what the mapping table +16. No decisions file → empty state. Run `afx decisions init` → items appear. +17. Work: Open / + Shell / Refresh / artifact link / external link each do what the mapping table says. -17. Light, dark and high-contrast themes, and a live theme switch. -18. Window variants and degraded states: +18. Light, dark and high-contrast themes, and a live theme switch. +19. Window variants and degraded states: - builder-worktree window and no-workspace window, including the commands' explanations; - Codev container hidden, Cockpit visible: a builder change made in the fixture workspace - appears in the Agents section within one refresh interval. + appears under its architect in the combined hierarchy within one refresh interval. - Tower unreachable: both panels keep their content under a not-connected notice and recover when it returns. This is simulated against the isolated instance's own Tower endpoint; the owner's Tower is never stopped. -19. Dashboard regression: the browser dashboard's Work and Decisions tabs render and rule as before. +20. Dashboard regression: the browser dashboard's Work and Decisions tabs render and rule as before. **Non-functional:** -20. Tower request rate with the combined panel open is unchanged from the source views alone. The +21. Tower request rate with the combined panel open is unchanged from the source views alone. The Decisions poll stops while its panel is hidden. -21. Neither webview opens a network connection to Tower (CSP has no `connect-src` to Tower; the key +22. Neither webview opens a network connection to Tower (CSP has no `connect-src` to Tower; the key is not present in webview state). ## Risks and Mitigation @@ -617,7 +824,11 @@ confirmation at this gate. |------|-------------|--------|------------| | The layout command closes or discards a user editor | Low | High | Spike the layout primitive first (Assumptions). The invariant is tested with dirty, untitled and modified editors. If the primitive removes groups unsafely, only add or reuse groups | | Generalising `buildersView`-bound wiring regresses the existing Agents view | Medium | High | Keep the existing Agents view tests as the regression net, add per-view tests for each behaviour, and render both views in verification | -| A menu entry is missed in the combined view (dead or absent action) | Medium | Medium | A generated test cross-checks every source-view `view/item/context` and `view/title` entry against a combined-view counterpart | +| A menu entry is missed in the combined view (dead or absent action) | Medium | Medium | A generated test cross-checks every source-view `view/item/context` and `view/title` entry against its counterpart at the placement table's position | +| Users expect another workspace's rows to act here and find they navigate | Medium | Low | The rows say so (tooltip names the workspace and that clicking opens its window). Full cross-workspace action (A2) is a gate question / follow-up | +| Tree-id collisions across workspaces (two `main`s, a shared builder id) break reveal or expansion | Medium | Medium | Ids are workspace-qualified, tested with colliding names | +| Keeping every active workspace's overview grows memory | Low | Low | Bounded by active workspaces. The cache already holds their attention, and it drops an overview when its workspace goes dormant or leaves the list | +| Other workspaces' rows lag this workspace's | Medium | Low | They refresh when the Tower view does today (SSE, debounced, plus the 20 s poll); this is stated, not hidden | | The combined panel goes stale because periodic refresh is gated on the Codev-container views' visibility | High if missed | Medium | The combined view and the Work panel count toward the existing visibility gate (a success criterion and tests) | | Tests that match `extension.ts` source text (e.g. `worktree-window-1809.test.ts`) break when wiring is generalised, and the breakage is misread as a regression | Medium | Low | Named in Success Criteria: such tests are updated to follow the wiring, with the guarded behaviour unchanged | | Auto-arrange or the `terminalPosition` override is unwelcome for some users | Medium | Low | `codev.cockpit.autoArrange` turns auto-arrange off; the override applies only to the arrange action | From af957cf379700e8ddd4372fd53f7bf6fb95dbc35 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:45:12 -0800 Subject: [PATCH 009/140] [Spec 1963] Thread: hierarchy revision --- codev/state/spir-1963_thread.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 5e687a0ec..99c7c0ff4 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -39,3 +39,22 @@ Codex COMMENT, Claude REQUEST_CHANGES — all points accepted, none disputed (re palette in worktree/no-workspace windows and explain themselves. Stopped at spec-approval. + +## 2026-11-24 — Owner revision at the gate: one hierarchy + +Owner: combined panel is ONE hierarchy — "towers -> workspaces -> architects / decisions -> +builders" — not three sections. Spec otherwise approved as drafted ("Other than that spec sounds +good"); porch approve is waiting on the architect's go after checking the revision. + +What the data check found: +- TowerFleetCache already fetches getOverview(path) for every active workspace and discards it + after deriving attention — retaining it gives every workspace's architects + builders + (spawnedByArchitect) with no new requests or routes. +- Overview has nothing about the decisions file → no pending count without an additive Tower field. +- All actions (TerminalManager keys/URLs, #1497 resolution, every builder command, diff cache) are + scoped to the window's own workspace → spec makes other workspaces' rows navigate (open that + workspace's window); fully cross-workspace action is offered as a gate question / follow-up. +- Attention rows fold onto the rows they concern; stage/area grouping stays in the Agents view; + dev URLs move to an "Open Dev URL…" context entry on the workspace row. + +Revision committed; re-consult (codex + claude, manual — porch is at the gate) running. From f18ec4f8820cd9d80358d248e89710c11e336598 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:52:06 -0800 Subject: [PATCH 010/140] [Spec 1963] Hierarchy revision: address re-consultation feedback --- .../1963-specify-revision1-rebuttals.md | 61 ++++++++ .../1963-vscode-alternative-layout-seco.md | 147 +++++++++++++----- codev/state/spir-1963_thread.md | 11 ++ 3 files changed, 183 insertions(+), 36 deletions(-) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-specify-revision1-rebuttals.md diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-specify-revision1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-specify-revision1-rebuttals.md new file mode 100644 index 000000000..35c2e3465 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-specify-revision1-rebuttals.md @@ -0,0 +1,61 @@ +# Spec 1963 — hierarchy revision, review round 1: rebuttals + +Reviews of commit `76e1dc498`, the owner's single-hierarchy revision. During the review, HEAD moved +only by the thread-log commit `af957cf37`, which touched no spec text, so both reviews apply to the +spec as committed. + +All points were accepted except the two items addressed to the architect (Claude 9, and Claude 7, +which is offered rather than specced). Nothing is disputed. + +## Codex (REQUEST_CHANGES) + +1. **Images vs CSP vs "no Tower request".** Accepted. Remote item images are **direct webview + `` loads**, as in the dashboard. + - The CSP `img-src` is `${cspSource} blob: http: https:` (`data:` only if the plan encodes + images). There is no `connect-src`. + - The criterion now reads "no fetch / XHR / WebSocket to Tower; the only webview network loads + are http(s) `` sources written in items". A Tower URL image gets 401 without the key and + shows the "Image not loaded" note, as does an `http:` image blocked by mixed content in the IDE. + - Constraints, §3, the criterion and scenario 22 are aligned. +2. **Source `contextValue`s vs navigate-only remote rows.** Accepted. Source `contextValue`s and + commands apply to this window's workspace rows only. Other workspaces' rows get distinct + navigate-only `contextValue`s, and the parity test fails if one matches a builder or architect + menu's `viewItem`. +3. **Parity oracle.** Accepted. A checked-in mapping holds one record per source entry: same + command at a combined-view `viewItem`, relocated to a named entry, or excluded with a reason. Only + the three `codev.agentsCycleGroupFrom*` title entries are excluded. The relocations are named. +4. **Gate date.** Accepted. It is labelled as UTC, as relayed by the architect, and recorded on + issue #1963. The relay messages are timestamped `2026-11-24T01:38Z`. + +## Claude (COMMENT) + +1. **Increments.** Accepted. A new *Increments* subsection names three independently shippable + slices: button + hierarchy, then the shared package + panels, then *Arrange Cockpit*. The plan + phases against them. +2. **The workspace level is not identical.** Accepted. Clicking an active workspace row now expands + it, and *Open* is the inline/context action; dormant rows keep click-to-open. This is stated in + §2 Levels and in the placement table, and tested in scenario 5. +3. **Global toggle settings.** Accepted. `codev.buildersAutoCollapse` and + `codev.buildersFileViewAsTree` are shared and global. Only row-id versioning, the reveal map and + expansion are per view. +4. **`architectCount`.** Accepted as a stated divergence. VS Code counts live architects; the + dashboard counts registered ones. +5. **"Connecting…" forever.** Accepted, with a correction found while applying it: + `ConnectionManager` never gives up; it retries with backoff indefinitely. So the Tower root shows + *Connecting to Tower…* only on the first attempt. After that it shows *Not connected to Tower*, + which is clickable and runs `codev.reconnect`. It is a state row rather than `viewsWelcome`, so + it sits inside the same tree. +6. **Own workspace before its overview.** Accepted. A single *Loading…* child shows until the + overview arrives, for any active workspace. +7. **First auto-arrange notice.** Not specced, because the trigger is owner-ruled and a notice is + new behaviour. Added as Open Question 6 (nice-to-know) for the owner. +8. **Test gaps.** Accepted: + - badge parity and suppression are added to scenario 5; + - `localResourceRoots` narrowed to `dist` is added to Constraints. +9. **Verify the owner's ruling.** For the architect. The ruling was relayed by the architect, who + is checking this revision against the owner's words before giving the go for `porch approve`. + +Factual corrections also folded in: + +- `requestPreservingBody` is named as the precedent; +- B2 notes that `apps/web` exports only `./src/*.ts`. diff --git a/codev/specs/1963-vscode-alternative-layout-seco.md b/codev/specs/1963-vscode-alternative-layout-seco.md index 601d59383..7aba45f5f 100644 --- a/codev/specs/1963-vscode-alternative-layout-seco.md +++ b/codev/specs/1963-vscode-alternative-layout-seco.md @@ -135,6 +135,8 @@ interfaces and themes through `--codev-canvas-*` tokens. `TowerClient` (`@cluesmith/codev-sdk`), which carries the key and the workspace-scoped route prefix. The SDK has no decisions methods today. Its generic `request()` drops the response body on a non-2xx status, so it would lose the decisions routes' structured refusal (`{ ok: false, code, message }`). +The precedent for keeping it is the client's existing private `requestPreservingBody`, written so +canvas commands keep a machine-readable `code` across a non-2xx. ## Desired State @@ -171,13 +173,27 @@ Tower ← root: this machine's Tower **Levels:** 1. **Tower.** One root row for the machine's Tower, expanded by default. While there is nothing to - list it holds Tower's existing state rows (*Connecting to Tower…*, *No workspaces registered*). + list, it holds a state row that follows the connection: + - *Connecting to Tower…* during the first connection attempt; + - *Not connected to Tower* once an attempt has failed. `ConnectionManager` is then + `disconnected` or `reconnecting`: it keeps retrying with backoff and never gives up. The row + is clickable and runs the existing *Reconnect to Tower* command (`codev.reconnect`) to retry + now. So a window where Tower is not running never sits on "Connecting…" indefinitely; + - *No workspaces registered* when Tower lists none. 2. **Workspaces.** Exactly the Tower view's workspaces, with the same labels (so twelve workspaces' `MAIN`s are told apart by their parent row), urgency order, *current* marker, icons, attention summary in the description, inline *Open* / *Deactivate*, and the collapsed *Dormant (N)* group. - This reuses `orderFleet` and `TowerProvider`'s row building. The window's own workspace and every - workspace that needs attention start expanded; quiet ones start collapsed. A dormant workspace - has no children, because it has no live session, as today. + This reuses `orderFleet` and `TowerProvider`'s row building, with one behavioural difference: + - **Clicking a workspace row.** In the Tower view, a quiet active workspace is a leaf whose click + opens it. In the hierarchy, every active workspace has children, so clicking its row expands or + collapses it, and *Open* is reached only through the row's inline and context-menu action. + - **Dormant workspaces** have no children, because they have no live session. They keep + click-to-open, as today. + - **Initial expansion.** The window's own workspace and every workspace that needs attention + start expanded; quiet ones start collapsed. + - **Before data arrives.** Until its overview arrives, the window's own workspace shows a single + *Loading…* child, as does any other active workspace whose overview the fleet cache has not + yet fetched, so a row never sprouts its chevron late. 3. **Architects + Decisions.** Under an active workspace: - its live architects, `main` first, then siblings alphabetically. Two or more idle siblings roll up into *Idle Architects*. This is the Agents view's architect-axis rendering @@ -223,8 +239,14 @@ window's** workspace today. So: - **Rows of any other workspace show state and navigate.** Its architects, builders and Decisions entry display what the overview says (glyphs, labels, descriptions). Clicking one opens that workspace's window, using the Tower view's existing *Open Workspace* action, where the same rows - are fully actionable. These rows carry no other actions and do not expand to changed files. - Acting on another workspace from this window is a separate, larger change; see Open Questions. + are fully actionable. Their tooltip says so. + - They carry their own **navigate-only `contextValue`s**, distinct from the source rows', so none + of this window's builder or architect menus can attach to them. Their only action is + *Open Workspace*, and they do not expand to changed files. + - This is not a regression against the issue's "every action on a row today works on the same + row". Rows of other workspaces' architects and builders do not exist anywhere in the extension + today, and Tower's attention rows carry no actions. + - Acting on another workspace from this window is a separate, larger change; see Open Questions. **Placement of everything the three source views do.** Nothing is dropped: @@ -241,10 +263,10 @@ window's** workspace today. So: | Agents: changed-files expansion (flat/tree), file click → diff | Identical, for this window's workspace | | Agents: architect-axis headers (click opens architect), *Idle Architects* container | They are the architect level | | Agents: stage / area grouping axes, group-by cycle | **Not in the combined panel.** The hierarchy fixes the architect axis. Stage and area grouping stay in the Agents view, and the architect axis's `[stage]` row prefix stays | -| Agents: refresh, accordion toggle, file-tree toggle (title bar) | The combined view's title bar | +| Agents: refresh, accordion toggle, file-tree toggle (title bar) | The combined view's title bar. The toggles write the same global settings (`codev.buildersAutoCollapse`, `codev.buildersFileViewAsTree`), so flipping one in either view changes both | | Agents: live count in the title | Each architect row's builder count. The workspace row's attention summary | | Agents: activity badge | The combined view's badge (same count and suppression, as ruled at the gate) | -| Tower: workspace rows, *current* marker, urgency order, inline *Open* / *Deactivate*, *Dormant* group | The workspace level: identical | +| Tower: workspace rows, *current* marker, urgency order, inline *Open* / *Deactivate*, *Dormant* group | The workspace level: the same, except that clicking an active workspace's row expands it (it now has children), so *Open* is the inline/context action; dormant rows keep click-to-open | | Tower: refresh (title bar) | The combined view's *Refresh*, which refreshes both caches | | Tower attention row: pending gate | The blocked builder row (gate glyph + wait time) under its architect | | Tower attention row: waits (needs input / idle / dead) | The builder row's state glyph and label | @@ -260,18 +282,32 @@ wait anywhere on the machine is visible on the row it concerns. **Other requirements:** - **Provider instances.** The combined panel has its own provider instances over the shared caches. - Its rows are built by the same code as the source views' rows, with the same labels, - `contextValue`s and `command`s, but they are distinct objects. Per-view state (accordion - versioning, the parent map used by `reveal`, expansion) stays per view, and a row belongs to - exactly one view. Tree-item ids are qualified by workspace, so two workspaces' `main` or a - builder id that appears in two workspaces never collide. + - **This window's workspace:** its rows are built by the same code as the source views' rows, + with the same labels, `contextValue`s and `command`s, but they are distinct objects. + - **Other workspaces:** their rows use the same labels and glyphs, with navigate-only + `contextValue`s and commands (above). + - **Per-view state:** row-id versioning for the accordion, the parent map used by `reveal`, and + expansion stay per view, and a row belongs to exactly one view. The *settings* behind the + title-bar toggles are shared and global. + - **Ids:** tree-item ids are qualified by workspace, so two workspaces' `main` or a builder id + that appears in two workspaces never collide. - **Tree behaviours follow the view a row is in.** Click-expands, the accordion, active-file reveal (when the combined panel is the visible one), agent-cycle selection and the `builder-active` hook act on the combined panel's rows for this window's workspace. - **Menu contributions are added, not edited.** The existing `view/item/context` and `view/title` entries for `codev.workspace`, `codev.agents` and `codev.tower` stay byte-for-byte. The combined - view gets its own entries, scoped to it, at the placements in the table above. A generated parity - test checks every source-view entry against its counterpart, so the two cannot drift. + view gets its own entries, scoped to it, at the placements in the table above. + - **The parity test's oracle** is a checked-in mapping, one record per existing source-view + entry. Each record says either *same command at a combined-view `viewItem`* (the builder, + architect, file and Tower workspace rows of this window's workspace) or *relocated to* a named + combined-view entry. + - **Relocations:** Workspace-view row entries move to this window's workspace row. Agents and + Tower `view/title` entries move to the combined title bar. Dev-URL rows become *Open Dev URL…*. + - **Excluded,** with the reason recorded: the three `codev.agentsCycleGroupFrom*` title entries + (the hierarchy fixes the axis). + - **What fails the test:** an unmapped source entry, or a mapped counterpart missing from + `package.json`. A navigate-only `contextValue` that matches any builder or architect menu + entry's `viewItem` pattern also fails it. - **Badge.** The combined view badges the new activity-bar button with the same workspace "needs me" count as the Codev button (`composeActivityBadge`), under the same suppression rules. - **Degraded windows:** @@ -304,7 +340,12 @@ wait anywhere on the machine is visible on the row it concerns. the panel being hidden or moved between groups; - a ruling round-trips: Submit → Tower writes the file → the card shows the written ruling, and Tower's ruling notice to the hub architect (#1828) is sent as it is from the dashboard; - - workspace-path item images load through the host; http(s) images load as in the dashboard; + - workspace-path item images load through the host, as bytes the panel shows as object URLs; + - an item image given as an http(s) URL is loaded by the webview itself as a plain ``, as + the dashboard loads it. This is an image load with no key and no script access, not a data + request. A URL the browser refuses (for example an `http:` image inside the IDE served over + `https:`, which mixed-content rules block, or a Tower URL, which answers 401 without the key) + shows the existing "Image not loaded" note; - an http(s) link opens in the user's browser; - clicking an image shows it full size inside the panel, because a webview cannot open browser tabs. @@ -387,6 +428,17 @@ wait anywhere on the machine is visible on the row it concerns. and issue previews that target "group 2" land in the Work group, per today's placement rules. Changing those rules is #1671's scope. +### Increments + +The three steps are independently shippable, in this order. Each one leaves the extension complete +and usable, so the work can be cut after any of them; the plan phases against these boundaries. + +1. **The button and the combined hierarchy.** This includes the `TowerFleetCache` overview + retention and the generalised tree wiring. The Decisions entry is not added yet. +2. **The shared component package and the Work and Decisions panels.** They are openable from the + palette and, now added, from the hierarchy's Decisions entry. +3. ***Arrange Cockpit*.** The split, its triggers and `codev.cockpit.autoArrange`. + ## Success Criteria - [ ] A new activity-bar button with the rotated Codev icon (same path, `rotate(90 400 400)`) appears @@ -437,15 +489,18 @@ wait anywhere on the machine is visible on the row it concerns. card shows it, and the hub architect receives the ruling notice, the same as from the dashboard. - [ ] Decisions: a refused ruling (e.g. `item-changed`) shows the server's message on the card and keeps the draft. -- [ ] Decisions: a workspace-path image and an http(s) image both render. A missing image shows the - "Image not loaded" note. Clicking an image shows it full size in the panel. +- [ ] Decisions: a workspace-path image (through the host) and an http(s) image (a direct `` + load) both render. A missing or browser-refused image shows the "Image not loaded" note. + Clicking an image shows it full size in the panel. - [ ] Decisions: a workspace without a decisions file shows the empty state, not an error. Creating the file makes its items appear without reopening the panel. - [ ] Work: builders, Needs Attention, Backlog and Recently Closed render from the overview. *Open* opens the builder's terminal, *+ Shell* opens a Tower shell, *Refresh* refreshes, artifact links open the file, and http(s) links open the browser. No dropped affordance is rendered. -- [ ] Neither webview makes a network request to Tower, and the Tower key is absent from webview - state and messages. +- [ ] Neither webview fetches from or opens a connection to Tower (no `fetch`, XHR or WebSocket; + the CSP has no `connect-src` beyond what VS Code itself requires). Every Tower request is the + host's, and the Tower key is absent from webview state and messages. The only network loads + a webview makes are http(s) `` sources written in decision items, as in the dashboard. - [ ] The host opens externally only `http:`/`https:` URLs from a webview, and opens a file from a webview only when its canonical path is inside the workspace. A symlink escape, `..`, an absolute path outside the workspace or another URL scheme is refused. @@ -537,13 +592,17 @@ From the system: - No Tower or decisions-route changes: the Spec 1819 / #1938 routes are consumed as they are. - VS Code engine floor `^1.128.0`. No API newer than that. - Webview hardening as in the existing webviews: nonce-gated scripts, a CSP that admits only what - the panels load, and every inbound webview message validated by a type guard before it is acted - on. A path from a webview is treated as untrusted. It is confined to the workspace by its + the panels load, `localResourceRoots` narrowed to the extension's bundled `dist` (as the + contextual panel and markdown preview do), and every inbound webview message validated by a type + guard before it is acted on. A path from a webview is treated as untrusted. It is confined to the workspace by its canonical, symlink-resolved location, not by string prefix. A URL from a webview is opened externally only if its scheme is `http:` or `https:`. -- The panels' CSP `img-src` must admit host-delivered workspace images. That means `blob:` if they - are shown as object URLs, as the dashboard does, or `data:` if they are encoded. The existing - precedent is `img-src ${cspSource} https: data:`. It must not add `connect-src` for Tower. +- The panels' CSP `img-src` is `${cspSource}` plus: + - `blob:`, for host-delivered workspace images shown as object URLs, as the dashboard does (or + `data:`, if the plan encodes them instead); + - `http:` and `https:`, for remote images written in items. Dashboard parity: it loads both. + The existing webviews' `img-src ${cspSource} https: data:` is the starting point. The CSP adds no + `connect-src`, so a webview cannot fetch from Tower or anywhere else. - The extension stays under the existing `regCli` / `reg` command-registration guard (#791). - UI changes are verified in a browser via Playwright before being called done (`codev/resources/testing-guide.md`). Verification must not replace or disturb the owner's live @@ -559,8 +618,11 @@ From the system: the editor area, without ending its session. Same spike. - Webview `postMessage` can carry image bytes, or an equivalent encoding, efficiently enough for images up to Tower's 10 MB image cap. -- `OverviewData.architects` gives the Work view what the dashboard's `DashboardState` gave it - (architect count for builder attribution), so Work needs no `/api/state` read. +- `OverviewData.architects` stands in for the dashboard's `DashboardState.architects` as Work's + architect count, so Work needs no `/api/state` read. They differ: the overview lists *live* + architects, `DashboardState` all registered ones. In VS Code the builder-attribution tag + (shown when the count is above 1) therefore counts live architects. That is an accepted, + harmless divergence: a stale registration no longer turns the tag on. - The Codev IDE at `/ide/` can be driven by Playwright with a build of this branch loaded in an isolated extensions dir or server instance, so verification never touches the owner's live IDE. - A fixture workspace, with builder entries but no real agents, can produce the N=0 / N=1 / N>1 @@ -648,8 +710,9 @@ slots rather than moved. components or retarget the wrappers. - Risk: medium. -**B2 — `apps/vscode` imports from `@cluesmith/codev-web`.** `apps/web` already exports `./*` source -files. +**B2 — `apps/vscode` imports from `@cluesmith/codev-web`.** `apps/web` exports `"./*": +"./src/*.ts"`, which covers `.ts` modules only, so even its `.tsx` components would need export +changes. - Pros: no move. - Cons: an app depending on an app. The components still hard-import `lib/api.ts` (relative URLs, @@ -683,7 +746,8 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme ## Open Questions -**Ruled at the spec gate (owner, 2026-11-24; recorded here, not reopened):** +**Ruled at the spec gate (owner, 2026-11-24 UTC, relayed by the architect and recorded on issue +#1963; recorded here, not reopened):** - **Trigger:** first show per window session, plus *Arrange Cockpit*, plus `codev.cockpit.autoArrange`. @@ -728,6 +792,10 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme 5. **Dev URLs.** They become one context-menu entry (*Open Dev URL…*) on the workspace row instead of one row each. Keeping them as rows under the workspace is the alternative, at the cost of hierarchy clutter. +6. **A notice on the first auto-arrange.** VS Code has no "undo layout". A one-time notification + on the first auto-arrange, with a *Don't arrange automatically* action that turns + `codev.cockpit.autoArrange` off, would make the one surprising reshuffle dismissible. Not + specced, because it is not ruled; offered. ## Test Scenarios @@ -760,10 +828,17 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme 4. `TowerFleetCache`: it keeps each active workspace's overview from the fetch it already makes, with no additional request, last-known-good on a failed fetch, dropped when a workspace leaves the list or goes dormant; the Tower view's rendering is unchanged. -5. Generalised tree behaviours: accordion, click-expands and reveal act on the view a row belongs - to, both for the Agents view (regression) and the combined view. Periodic-refresh visibility: - with only the combined view (or only the Work panel) visible the timer runs; with none visible it - stops. +5. Generalised tree behaviours: + - accordion, click-expands and reveal act on the view a row belongs to, both for the Agents view + (regression) and the combined view; + - periodic-refresh visibility: with only the combined view (or only the Work panel) visible the + timer runs, and with none visible it stops; + - the badge: the combined view's badge equals the Codev button's for the same data, and is + suppressed in a builder-worktree window and when disconnected; + - Tower root state rows: connecting, then not connected with *Reconnect* (which runs + `codev.reconnect`), then no workspaces; + - workspace rows: clicking an active row expands it rather than opening it, a dormant row opens + on click, and an overview that has not loaded shows *Loading…*. 6. Host message contract: - every inbound message guard rejects malformed input; - file-open paths outside the workspace, `..` escapes and symlinks resolving outside are refused; @@ -815,8 +890,8 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme 21. Tower request rate with the combined panel open is unchanged from the source views alone. The Decisions poll stops while its panel is hidden. -22. Neither webview opens a network connection to Tower (CSP has no `connect-src` to Tower; the key - is not present in webview state). +22. Neither webview fetches from or connects to Tower: the CSP has no `connect-src`, and the key + is not present in webview state. Remote item images are the only webview network loads. ## Risks and Mitigation diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 99c7c0ff4..f92abc82c 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -58,3 +58,14 @@ What the data check found: dev URLs move to an "Open Dev URL…" context entry on the workspace row. Revision committed; re-consult (codex + claude, manual — porch is at the gate) running. + +## 2026-11-24 — Hierarchy revision re-consult + +Codex REQUEST_CHANGES, Claude COMMENT on 76e1dc498; all accepted (rebuttal: +`1963-specify-revision1-rebuttals.md`). Main changes: remote item images are direct `` loads +(CSP img-src gains `http:`; no connect-src), other workspaces' rows get navigate-only +contextValues, the parity test has a checked-in mapping oracle, an Increments subsection (button + +hierarchy → shared package + panels → arrange), active workspace rows click-expand (Open moves to +the inline action), Tower root shows "Not connected to Tower" + Reconnect after the first failed +attempt (ConnectionManager retries forever, never gives up), Loading… child before an overview. +New owner question offered, not specced: a one-time notice on the first auto-arrange. From 95029fd660dcd75d65ee2957e144b8c84482e4d4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 21:59:38 -0800 Subject: [PATCH 011/140] [Spec 1963] Record spec-gate rulings; add first auto-arrange notice --- .../1963-vscode-alternative-layout-seco.md | 70 +++++++++---------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/codev/specs/1963-vscode-alternative-layout-seco.md b/codev/specs/1963-vscode-alternative-layout-seco.md index 7aba45f5f..4d43dd6f4 100644 --- a/codev/specs/1963-vscode-alternative-layout-seco.md +++ b/codev/specs/1963-vscode-alternative-layout-seco.md @@ -414,7 +414,15 @@ wait anywhere on the machine is visible on the row it concerns. - *Arrange Cockpit* (Command Palette and the combined view's title bar) arranges on demand at any time, and is idempotent: running it on an already-arranged window changes nothing visible; - a setting, `codev.cockpit.autoArrange` (default on), turns the first-show auto-arrange off. With - it off, only the command arranges. + it off, only the command arranges; + - **a one-time notice on the first auto-arrange** (ruled at the spec gate). VS Code has no + "undo layout", so the first time an auto-arrange happens for this user, an information + notification says the editor area was arranged for the Cockpit. It offers a *Don't arrange + automatically* action, which sets `codev.cockpit.autoArrange` to `false` at the user (global) + level. + - "First" is per user profile: a flag in the extension's global state is set when the notice is + shown, whatever the user does with it, so it never appears again in any window or workspace. + - *Arrange Cockpit* run by hand never shows it, and it is not shown while auto-arrange is off. - **Where it is offered:** - in a **builder-worktree window** the split is not offered. There is no auto-arrange and the title-bar action is hidden. This follows #1809: surfaces that act on the parent workspace stay @@ -509,6 +517,10 @@ and usable, so the work can be cut after any of them; the plan phases against th isolated verification instance, never by stopping the owner's Tower. - [ ] With `codev.cockpit.autoArrange` off, showing the container never arranges, and the command still does. +- [ ] The first auto-arrange for a user profile shows a one-time notice with *Don't arrange + automatically*. Choosing it sets `codev.cockpit.autoArrange` to `false` globally. The notice + does not appear again, in that or any other window, whether it was acted on or dismissed. It + never appears for a manual *Arrange Cockpit*. - [ ] The dashboard's Work and Decisions views look and behave as before. Existing `apps/web` tests (`DecisionsView*.test.tsx`, `useDecisions.test.ts`, `BuilderCard.test.tsx`, `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`, `App.decisions-tab.test.tsx`, …) pass @@ -762,40 +774,22 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme - **Combined panel:** one hierarchy, Tower → workspaces → architects + Decisions → builders. Section order is therefore moot. -**Important (shapes scope); for the owner at the gate, nothing assumed:** - -1. **Acting on other workspaces from this window.** This spec makes another workspace's rows - navigate: clicking opens that workspace's window (A1). Making them fully actionable here (A2) - needs no Tower route changes but is a large extension change. It requires workspace-qualified - terminal keys, the #1497 invariant over (workspace, name), every builder command made - workspace-aware, and per-workspace Decisions panels. **Recommendation:** A1 now, A2 as a - follow-up if wanted. - - A narrower middle option: opening *another workspace's Decisions screen* in this window - (decisions routes are workspace-scoped; no terminal changes) while terminals still navigate. - Its cost is per-workspace Decisions panels and their single-instance rule. Not specced unless - ruled in. -2. **Decisions pending count / file presence.** The overview carries neither, so the Decisions - entry shows no count and appears for every active workspace (opening it shows the empty state - when there is no file). - - Showing a count, or hiding the entry when there is no file, needs an **additive Tower change**: - a decisions summary (present, open count) in the overview payload. The existing fleet fan-out - would then carry it with no new requests. - - **Recommendation:** no count in this spec; the additive field as a separate change if wanted. - This spec keeps "no Tower route changes". - -**Nice-to-know:** - -3. **Ordering of this window's workspace.** It keeps its urgency slot, as in the Tower view (#1566), - and starts expanded. Pinning it first is the alternative. -4. **Decisions entry position.** After the architects, per the owner's order ("architects / - decisions"). First under the workspace is the alternative. -5. **Dev URLs.** They become one context-menu entry (*Open Dev URL…*) on the workspace row instead - of one row each. Keeping them as rows under the workspace is the alternative, at the cost of - hierarchy clutter. -6. **A notice on the first auto-arrange.** VS Code has no "undo layout". A one-time notification - on the first auto-arrange, with a *Don't arrange automatically* action that turns - `codev.cockpit.autoArrange` off, would make the one surprising reshuffle dismissible. Not - specced, because it is not ruled; offered. +Scope and nice-to-know questions, ruled at the same gate (owner: "go with your recommendation" +on all four; recorded on issue #1963): + +- **Acting on other workspaces from this window:** not in this spec. Other workspaces' rows show + state and navigate (A1). Acting on them in place (A2, including the Decisions-only middle option) + is follow-up issue #1969. +- **Decisions pending count / file presence:** no count; the entry appears under every active + workspace. The additive overview field that a count would need is follow-up issue #1970. This + spec keeps "no Tower route changes". +- **Dev URLs:** one *Open Dev URL…* context entry on the workspace row, as specced. +- **First auto-arrange notice:** added as a requirement, with a criterion and a test (section 3, + *Triggers*). +- **Nice-to-know defaults stand:** this window's workspace keeps its urgency slot (#1566) and + starts expanded, and the Decisions entry comes after the architects. + +No questions remain open. ## Test Scenarios @@ -848,6 +842,10 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme at creation; does not fire again on later shows; does not fire with `codev.cockpit.autoArrange` off, in a worktree window or in a no-workspace window. In those windows the commands explain why instead of acting. + - First-arrange notice: shown on the first auto-arrange when the global-state flag is unset, and + the flag is then set. Not shown when the flag is set, for a manual *Arrange Cockpit*, or with + auto-arrange off. *Don't arrange automatically* writes `codev.cockpit.autoArrange = false` at + `ConfigurationTarget.Global`, and dismissing the notice leaves the setting unchanged. 8. Host decisions bridge: document, refusal (structured code/message preserved), transport error, image bytes / not-loaded; not-found maps to the empty state. 9. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no @@ -906,7 +904,7 @@ markdown artifacts. Work and Decisions are workspace-state surfaces. Not recomme | Other workspaces' rows lag this workspace's | Medium | Low | They refresh when the Tower view does today (SSE, debounced, plus the 20 s poll); this is stated, not hidden | | The combined panel goes stale because periodic refresh is gated on the Codev-container views' visibility | High if missed | Medium | The combined view and the Work panel count toward the existing visibility gate (a success criterion and tests) | | Tests that match `extension.ts` source text (e.g. `worktree-window-1809.test.ts`) break when wiring is generalised, and the breakage is misread as a regression | Medium | Low | Named in Success Criteria: such tests are updated to follow the wiring, with the guarded behaviour unchanged | -| Auto-arrange or the `terminalPosition` override is unwelcome for some users | Medium | Low | `codev.cockpit.autoArrange` turns auto-arrange off; the override applies only to the arrange action | +| Auto-arrange or the `terminalPosition` override is unwelcome for some users | Medium | Low | `codev.cockpit.autoArrange` turns auto-arrange off, and the one-time first-arrange notice offers that in one click; the override applies only to the arrange action | | A webview-supplied path or URL is used to open something outside the workspace or a non-web scheme | Low | High | Canonical-path containment, including symlink resolution, and an `http:`/`https:` allowlist, both enforced and tested host-side | | Moving components changes the dashboard's look or behaviour | Medium | Medium | Thin dashboard wrappers with the current fetch adapter, the existing `apps/web` tests unchanged in intent, and a dashboard render check in verification | | A Decisions draft is lost by the layout or by hiding the panel | Low | High | `retainContextWhenHidden`; arrangement reuses panels and never recreates them; tested. Loss on explicit panel close or reload is parity with the dashboard and stated | From 1cb3000ee429beab4a2adc62293c669bfd287494 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 21:59:41 -0800 Subject: [PATCH 012/140] chore(porch): 1963 spec-approval gate-approved --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index e9c53f1f3..ee7eec5cf 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -6,8 +6,9 @@ plan_phases: [] current_plan_phase: null gates: spec-approval: - status: pending + status: approved requested_at: '2026-11-24T01:28:14.248Z' + approved_at: '2026-11-24T05:59:40.990Z' plan-approval: status: pending pr: @@ -18,4 +19,4 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T01:28:14.248Z' +updated_at: '2026-11-24T05:59:40.992Z' From 29ac171ae5f039947d2155123ec049c289762c95 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 21:59:46 -0800 Subject: [PATCH 013/140] chore(porch): 1963 plan phase-transition --- .../1963-vscode-alternative-layout-seco/status.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index ee7eec5cf..70f584966 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -1,7 +1,7 @@ id: '1963' title: vscode-alternative-layout-seco protocol: spir -phase: specify +phase: plan plan_phases: [] current_plan_phase: null gates: @@ -16,7 +16,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T05:59:40.992Z' +updated_at: '2026-11-24T05:59:46.569Z' From 9475ca9503730fdfbf57c1acc5b9ee10b137d8ea Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:05:35 -0800 Subject: [PATCH 014/140] [Spec 1963] Initial implementation plan --- .../1963-vscode-alternative-layout-seco.md | 804 ++++++++++++++++++ 1 file changed, 804 insertions(+) create mode 100644 codev/plans/1963-vscode-alternative-layout-seco.md diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md new file mode 100644 index 000000000..9cf023060 --- /dev/null +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -0,0 +1,804 @@ +# Plan: VS Code alternative layout ("Codev Cockpit") + +**Specification**: [codev/specs/1963-vscode-alternative-layout-seco.md](../specs/1963-vscode-alternative-layout-seco.md) + +## Executive Summary + +This plan implements the approved spec in its three shippable increments, in eight phases. Each +phase is one commit on `builder/spir-1963`, and all of them go into one PR. + +1. **Button + hierarchy** (Phases 1–4). This uses spec approach **A1**: one tree view over the + existing row-building code. Its single hierarchy is the owner's *"towers -> workspaces -> + architects / decisions -> builders"*. Rows of this window's workspace act; rows of other + workspaces navigate. + - Other workspaces' rows come from the overviews `TowerFleetCache` already fetches. They are kept + instead of discarded, so the hierarchy needs no new requests and no Tower change. + - The architect-axis row building moves out of `BuildersProvider` into a reusable builder, + scoped by workspace. The Agents view and the Cockpit both use it, so there is no second copy + of row logic. +2. **Shared Work and Decisions** (Phases 5–7). This uses approach **B1**: a new workspace package, + `@cluesmith/codev-workspace-views` (`packages/workspace-views`). + - The dashboard's `WorkView`, `DecisionsView`, `useDecisions` and their sub-components move + there. They take their I/O from a host adapter and their colours from `--codev-wv-*` tokens. + - The dashboard keeps thin wrappers with its fetch adapter. + - The extension hosts two editor-area webview panels whose host side relays to Tower through + `ConnectionManager`'s client. +3. ***Arrange Cockpit*** (Phase 8). This uses approaches **C1** (first show per window, plus the + command and `codev.cockpit.autoArrange`) and **D1** (Work stacked over Decisions). It also adds + the one-time first-auto-arrange notice ruled at the gate. Before any arrange code is written, the + phase starts with the spike the spec's Assumptions require. + +Rendered verification sits at the end of each increment: Phase 4, Phase 7 and Phase 8. It runs +against an isolated harness (described below), so the work can be cut after any increment with what +has shipped already verified. + +## Phases (Machine Readable) + +```json +{ + "phases": [ + {"id": "fleet_overviews", "title": "Fleet cache keeps every active workspace's overview"}, + {"id": "architect_tree_builder", "title": "Reusable, workspace-scoped architect-axis row builder"}, + {"id": "cockpit_hierarchy", "title": "Cockpit button and the Tower → workspaces → architects → builders tree"}, + {"id": "cockpit_actions", "title": "Placement-table actions on the hierarchy, parity mapping, increment-1 verification"}, + {"id": "workspace_views_package", "title": "Shared Work/Decisions package; dashboard moved onto it unchanged"}, + {"id": "decisions_panel", "title": "Decisions panel in VS Code, its host bridge, and the hierarchy's Decisions entry"}, + {"id": "work_panel", "title": "Work panel in VS Code, increment-2 verification"}, + {"id": "arrange_cockpit", "title": "Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification"} + ] +} +``` + +## Phase Breakdown + +### Phase 1: Fleet cache keeps every active workspace's overview + +**Dependencies**: None + +#### Objective + +Make every active workspace's architects and builders available to the extension, with no new +request. `TowerFleetCache.fetchFleet()` already calls `client.getOverview(path)` for each active +workspace and throws the result away after `deriveAttention`; this phase keeps it. + +#### Files to Create / Modify + +- `apps/vscode/src/views/tower-cache.ts`: + - `FleetEntry` gains `overview: OverviewData | null`; + - a `lastOverview` map gives last-known-good per path, alongside the existing `lastAttention`; + - a `getOverview(path)` accessor. +- `apps/vscode/src/__tests__/tower-cache.test.ts`: extended. + +#### Deliverables + +- [ ] On a successful fetch, each active entry carries its overview. +- [ ] On a failed fetch (`null`), the entry keeps its previous overview, as it keeps its attention. +- [ ] A dormant workspace's entry has `overview: null`, and its retained overview is dropped. A + workspace that leaves the list has its overview dropped. +- [ ] Attention derivation, ordering, the sequence guard and request counts are unchanged. + +#### Acceptance Criteria + +- [ ] The Tower view renders exactly as before. The existing `tower-cache.test.ts`, + `tower-provider.test.ts` and `fleet-current-workspace.test.ts` pass. +- [ ] Per refresh, the number of `getOverview` calls equals the number of active workspaces, as + today. +- [ ] `pnpm --filter codev-vscode check-types`, `lint` and `test:unit` pass. + +#### Test Plan + +Unit tests with a fake client: + +- the overview is retained on success; +- last-known-good is kept on `null`; +- it is dropped when a workspace goes dormant or is removed; +- a stale (out-of-sequence) fan-out does not overwrite a newer overview; +- the call count is unchanged. + +### Phase 2: Reusable, workspace-scoped architect-axis row builder + +**Dependencies**: None (Phase 1 is not needed; ordered here so the hierarchy phase has both) + +#### Objective + +Move the row building that `BuildersProvider` does privately into a reusable class. The Cockpit +needs one instance per workspace, so it must be able to build the same rows with ids that cannot +collide, and to build *navigate-only* rows for other workspaces. This is a pure refactor for the +Agents view: same rows, same ids, same behaviour. + +#### Files to Create / Modify + +- **New `apps/vscode/src/views/architect-tree.ts`:** `ArchitectTreeBuilder`. It receives: + - `getData(): OverviewData | null`; + - `grouping(): BuilderGrouping`. The Agents view passes its active axis; the Cockpit always + passes `architectGrouping()`; + - `scope: string`, an id prefix. It is `''` for the Agents view, so every existing id is + unchanged; + - `mode: 'act' | 'navigate'`; + - for `navigate`, the `WorkspaceTarget` to open; + - for `act`, the `BuilderDiffCache`. + + It owns what today lives in `BuildersProvider`: + - row-id versioning (`AccordionRowIds`) and the group-parent map; + - `makeGroupRow`, `makeBuilderRow`, the architect-root partition, the *Idle Architects* rows and + rows-for-group; + - changed-file children and their parent reconstruction; + - `findFileItem`, `revealTargetForAgent` and `agentCycleOrder`. + + In `navigate` mode: + - builder rows are leaves (no changed files); + - architect rows still expand to their builders; + - every row's `command` is `codev.tower.openWorkspace` with the workspace target; + - `contextValue`s are `cockpit-remote-architect` and `cockpit-remote-builder`; + - the tooltip names the workspace and says a click opens its window. +- `apps/vscode/src/views/builders.ts`: `BuildersProvider` delegates to one + `ArchitectTreeBuilder` (scope `''`, mode `act`). Stage/area rendering and the lone-Uncategorized + flatten stay where they are. They already use the same `makeGroupRow`/`makeBuilderRow`, now + reached through the builder. +- `apps/vscode/src/views/builder-tree-item.ts` and the group, idle-container, folder and file + item classes: + - each takes an optional `scope` that prefixes its id; + - each carries `scope` as a property, so command handlers can tell which view and workspace a + row belongs to; + - with `scope = ''`, ids are byte-identical to today's. +- **New tests:** `apps/vscode/src/__tests__/architect-tree.test.ts`. + +#### Deliverables + +- [ ] `ArchitectTreeBuilder` with `act` and `navigate` modes and scoped ids. +- [ ] `BuildersProvider` rebuilt on it, with no behaviour change. +- [ ] A builder option, `attentionCounts`, which is off for the Agents view, appends *N held* and + *N queued* to builder-row descriptions. The counts come from the same `deriveAttention` + summary the Tower view uses. Builder rows show neither today, so the Agents view keeps its + labels byte-for-byte and only the Cockpit turns the option on (the placement table's held + and queued rows). + +#### Acceptance Criteria + +- [ ] All existing Agents tests pass unmodified: + - `builders.test.ts`, `builders-accordion.test.ts`, `builders-autoreveal.test.ts`; + - `builders-click-expands.test.ts`, `builders-idle-architects-group.test.ts`; + - `builders-childless-architect-header.test.ts`, `builders-architect-header-command.test.ts`; + - `agent-cycle-order.test.ts`, `area-grouping.test.ts`, `builder-file-tree-item.test.ts`. +- [ ] With scope `''`, every id the builder produces equals the id produced before the refactor + (asserted over N=0/1/>1 builders, on all three axes, in flat and tree file modes). +- [ ] Two builders with scopes `A` and `B` over data where both have `main` and a builder `x` + produce disjoint id sets. +- [ ] Navigate-mode rows: + - have no changed-files children; + - carry only `cockpit-remote-*` context values, none of which matches any existing `viewItem` + pattern in `package.json`; + - click to `codev.tower.openWorkspace`. +- [ ] Type-check, lint and unit tests pass. + +#### Test Plan + +Unit tests on `ArchitectTreeBuilder`: + +- id equivalence against a snapshot taken from the pre-refactor provider in the same commit; +- scope disjointness; +- navigate-mode shape; +- the fold of null `spawnedByArchitect` into `main`; +- the childless-architect leaf; +- the idle roll-up; +- a non-live recorded architect; +- `getParent` chains for builder, idle-sibling header, folder and file rows. + +### Phase 3: Cockpit button and the Tower → workspaces → architects → builders tree + +**Dependencies**: Phase 1, Phase 2 + +#### Objective + +Ship the new activity-bar button and its single hierarchy, with this window's builder rows +behaving as they do in Agents: click, accordion, reveal, cycle selection and activity hook. This is +the first user-visible slice. Context-menu actions arrive in Phase 4. + +#### Files to Create / Modify + +- **New `apps/vscode/icons/codev-cockpit.svg`:** `codev.svg`'s `` wrapped in + ``. Same `d`, same viewBox. +- **`apps/vscode/package.json`** (additions only): + - the container `codev-cockpit` ("Codev Cockpit", the icon above), placed directly after + `codev`; + - the view `codev.cockpit`, a tree with no `when`; + - the command `codev.cockpit.refresh`, with its `view/title` entry. +- **New `apps/vscode/src/views/cockpit.ts`:** `CockpitProvider`. Its node union is: + `tower-root` | `message` | `workspace` | `dormant-group` | `loading` | rows from an + `ArchitectTreeBuilder`. + - **Root:** one *Tower* row, expanded. Its state rows follow `ConnectionManager` and + `TowerFleetCache`: + - *Connecting to Tower…* only before the first attempt fails; + - *Not connected to Tower* once an attempt has failed (`disconnected` / `reconnecting`). Its + command is `codev.reconnect`; + - *No workspaces registered* when the fleet list is empty. + - **Workspaces:** `orderFleet` order, labels and *current* marker; a *Dormant (N)* group. + - Row construction is shared with `TowerProvider` through a function extracted from + `TowerProvider.workspaceItem`, with a `hasChildren` option. `TowerProvider` keeps its exact + output. + - In the Cockpit, every active workspace is collapsible and has no click command; *Open* is + added in Phase 4. + - Dormant rows keep click-to-open. + - Initial expansion: this window's workspace and any with non-empty attention start + `Expanded`; the rest start `Collapsed`. + - **Architects → builders:** one `ArchitectTreeBuilder` per active workspace, cached by path and + pruned when a workspace leaves. + - This window's workspace: mode `act`, data from `OverviewCache.getData()`, scope + `ws:|`. + - Every other workspace: mode `navigate`, data from `towerCache.getOverview(path)`. + - In a builder-worktree window or a no-workspace window, every workspace is `navigate` (the + spec's degraded windows). + - **Loading:** an active workspace whose overview is not yet available shows one *Loading…* + child. + - **Attention on rows:** + - architect rows get `describeWait` text and glyph from the workspace's + `AttentionSummary.architects`; + - builder rows get their glyph, gate and held/queued (Phase 2); + - the workspace row's description keeps `describeAttention`, which already covers + unattributed held mail and escalation. + - **Re-render:** on `overviewCache.onDidChange`, `towerCache.onDidChange` and + `connectionManager.onStateChange`. +- **`apps/vscode/src/extension.ts`:** + - create `cockpitView`; + - generalise the `buildersView`-bound wiring into a small registry, `AgentTreeHosts` + (`apps/vscode/src/views/agent-tree-hosts.ts`), that maps a row's `scope` to its + `{ view, builder }`: + - `codev.openBuilderRow` reveals in the row's own view; + - each view gets its own `onDidExpandElement` accordion with its own `AccordionGate`; + - active-file reveal and agent-cycle selection reveal in every visible host that holds the + row; + - selection in either view fires `builder-active`; + - the activity-badge value is computed once and assigned to both `buildersView` and + `cockpitView`, with the same suppression; + - `cockpitView.visible` joins `anyVisible()` and its visibility event joins `reconcile` in + `setupPeriodicOverviewRefresh`; + - `codev.cockpit.refresh` refreshes `overviewCache` and `towerCache`. +- **Tests:** + - new `apps/vscode/src/__tests__/cockpit-provider.test.ts`; + - new `apps/vscode/src/__tests__/cockpit-wiring.test.ts`; + - `apps/vscode/src/__tests__/contributes-cockpit.test.ts`; + - `apps/vscode/src/__tests__/cockpit-icon.test.ts`. + +#### Deliverables + +- [ ] Container, view, icon and refresh command. +- [ ] `CockpitProvider` with every level, state row and fold rule in spec §2. +- [ ] Generalised tree behaviours, the badge on both views, and periodic refresh with the Cockpit + counted. +- [ ] Tests listed below. + +#### Acceptance Criteria + +- [ ] The spec's success criteria for structure, folds, attention on rows, navigate-only rows, id + distinctness, tree behaviours and the refresh gate hold in unit tests. +- [ ] `contributes-*`: the new container sits after `codev`, the view has no `when`, and the icon + path exists. The existing `codev`, `codev-tower` and `codevPanel` entries are byte-identical + (a snapshot of those keys). +- [ ] Existing tests that assert on `extension.ts` source text (`worktree-window-1809.test.ts`) + either pass or are updated only to follow the generalised wiring, with the guarded behaviour + (badge suppressed in a worktree window) asserted on both views. +- [ ] Type-check, lint and unit tests pass. + +#### Test Plan + +- **`cockpit-provider.test.ts`**, with fake caches: + - root state rows, including *Not connected* → `codev.reconnect`; + - workspace order, labels, *current* and the Dormant group, compared with `TowerProvider` over + the same fleet; + - expansion defaults; + - click: an active workspace has no command, a dormant one opens; + - *Loading…*; + - own workspace rows equal the Agents architect-axis rows for the same `OverviewCache` state + (N=0/1/>1, idle roll-up, null owner → `main`, non-live owner, childless leaf); + - other workspaces navigate-only; + - worktree and no-workspace variants; + - colliding names across two workspaces; + - `codev.buildersGroupBy = stage|area` leaves the tree unchanged; + - every attention kind lands on its row. +- **`cockpit-wiring.test.ts`:** + - `openBuilderRow` reveals in the owning view; + - accordion per view; + - the visibility gate runs with only the Cockpit visible and stops with nothing visible; + - the badge is equal on both views and suppressed when disconnected and in a worktree window. +- **`cockpit-icon.test.ts`:** same `d` attribute as `codev.svg`, wrapped in `rotate(90 400 400)`. + +### Phase 4: Placement-table actions on the hierarchy, parity mapping, increment-1 verification + +**Dependencies**: Phase 3 + +#### Objective + +Make every row of this window's workspace act exactly as it does in the source views, put every +source-view affordance where the spec's placement table says, and prove that nothing was missed +with a test generated from `package.json`. This phase closes increment 1, including its rendered +verification and docs. + +#### Files to Create / Modify + +**`apps/vscode/package.json`** (additions only): + +- `view/item/context` entries for `view == codev.cockpit`: + - builder rows of this window's workspace: the same commands, groups and `viewItem` patterns as + the 13 Agents row entries; + - architect rows: *Remove Architect* on siblings; + - workspace rows: + - *Open* / *Deactivate* inline, as in Tower; + - on the current row, inline *Spawn Builder*, *New Shell* and *Add Architect*; + - on the current row's context menu, those three plus *Open Web Interface*, *Start Dev* or + *Stop Dev*, and *Open Dev URL…*. +- `view/title` entries for `view == codev.cockpit`: + - *Refresh* (`codev.cockpit.refresh`); + - the accordion toggles and file-tree toggles, reusing the existing commands, keyed on the same + global context keys. +- **New command `codev.cockpit.openWebInterface`.** The Workspace view's *Open Web Interface* is a + row whose command is `vscode.open` with no command id of its own. It opens the same URL via the + shared `buildDashboardUrl`, extracted from `WorkspaceProvider`. + +**Context values on the current workspace row** encode what the Workspace view decides for this +window: + +- `cockpit-workspace-current` plus a dev-slot suffix: `-dev-start`, `-dev-stop` or + `-dev-stop-other`. It is computed by a function extracted from `WorkspaceProvider`'s dev-row + logic, so the two cannot disagree; +- a `-devurls` suffix when `worktree.devUrls` is non-empty. + +**Builder-worktree window:** + +- the parent's row is `cockpit-workspace-parent`; +- it carries *Open Web Interface*, the worktree *Start Dev* / *Stop Dev* and *Open Dev URL…* (the + worktree-scoped actions the Workspace view shows there); +- it carries no spawn, shell or architect actions. + +**Other files:** + +- `apps/vscode/src/views/workspace.ts`: the extracted `buildDashboardUrl` and dev-slot functions, + used by both providers. The Workspace view's output is unchanged. +- **New `apps/vscode/src/views/cockpit-menu-map.ts`:** the checked-in mapping oracle. It has one + record per existing `view/item/context` and `view/title` entry for `codev.workspace`, + `codev.agents` and `codev.tower` (27 today), each one of: + - `{ same: }`; + - `{ relocated: }`; + - `{ excluded: }`. Only the three `codev.agentsCycleGroupFrom*` title entries are + excluded. + + It also has one record per Workspace-view row click: Open Web Interface, Spawn Builder, New + Shell, Start/Stop Dev, dev URLs and architect rows. +- **New `apps/vscode/src/__tests__/cockpit-menu-parity.test.ts`.** +- **Docs:** + - the `apps/vscode/README.md` Cockpit section; + - `codev/resources/arch.md`, *VS Code Extension*: the Cockpit container, `ArchitectTreeBuilder`, + fleet-overview retention and the act/navigate rule; + - `CHANGELOG` entry for `apps/vscode`. + +#### Deliverables + +- [ ] All placement-table entries for increment 1 (the Decisions entry is Phase 6). +- [ ] The mapping oracle and the parity test. +- [ ] Rendered verification of increment 1 and docs. + +#### Acceptance Criteria + +- [ ] The parity test fails if any of these holds: + - a source entry has no record; + - a mapped Cockpit entry is missing from `package.json`; + - a `cockpit-remote-*` or `cockpit-workspace-parent` value matches a builder or architect + entry's `viewItem`; + - an existing source entry differs from its snapshot. +- [ ] From the Cockpit, in the harness, these work on this window's workspace: + - every builder context action; + - Approve Gate inline; + - every workspace-row action; + - Remove Architect. +- [ ] Another workspace's architect or builder row opens that workspace's window. +- [ ] **Rendered** (see the harness below), with screenshots: + - the button under Codev; + - the hierarchy with N=0, N=1 and N>1 builders and two or more workspaces; + - the Dormant group; + - *Not connected* → reconnect; + - light and dark themes. +- [ ] Type-check, lint and unit tests pass. The existing `contributes-*` tests are unmodified + apart from additions. + +#### Test Plan + +- Unit: the parity test, the dev-slot function (shared cases with `workspace.test.ts`), and + context values on the current, parent and remote workspace rows. +- Rendered: spec scenarios 11, 12 (hierarchy part) and 19 (worktree and no-workspace windows; + Cockpit-only freshness). + +### Phase 5: Shared Work/Decisions package; dashboard moved onto it unchanged + +**Dependencies**: None (independent of Phases 1–4; ordered for the increment boundary) + +#### Objective + +Create the one shared home for the Work and Decisions React code, and move the dashboard onto it +with no visible change. After this phase the components exist once, behind a host adapter that a +second host can implement. + +#### Files to Create / Modify + +**New package `packages/workspace-views` (`@cluesmith/codev-workspace-views`, private, not +npm-published):** + +- **Source-exported:** `exports: { ".": "./src/index.ts", "./styles.css": "./src/styles.css" }`. + Each host's bundler compiles it: Vite in `apps/web`, esbuild in `apps/vscode`. There is no build + step, so CI build ordering is unchanged. +- **Own files:** `tsconfig.json` (`jsx: react-jsx`), `vitest.config.ts` (jsdom), and `test` and + `check-types` scripts. +- **Dependencies:** `@cluesmith/codev-types`, `@cluesmith/codev-sdk` (the environment-agnostic + `builder-helpers` only), `@cluesmith/codev-artifact-canvas`, and React as a peer dependency. +- **`src/host.ts`:** the `WorkspaceViewsHost` adapter. Its members are optional unless stated: + - `overview` (required): a subscribe/refresh source; + - `decisions`: `read()`, `rule(req)`, `image(path)`; + - `openBuilder(id)`; + - `newShell()`; + - `refresh()`; + - `openArtifact(path)`; + - `openExternal(url)`; + - `showImage(src)`. + + A control renders only when its action is provided. +- **Moved here from `apps/web/src`:** + - `components/WorkView.tsx`, keeping its core sections. The dashboard-only pieces become optional + slots: `FileTree`, `OpenFilesShellsSection` and `TipBanner`; + - `components/DecisionsView.tsx`, `hooks/useDecisions.ts`; + - `components/BuilderCard.tsx`, `NeedsAttentionList.tsx`, `BacklogList.tsx`, + `RecentlyClosedList.tsx`; + - the `issueRef` part of `lib/issueIds.ts`. `findBuilderTab` stays in the dashboard; it is + dashboard tab logic. +- **`src/styles.css`:** the Work and Decisions CSS rules moved from `apps/web/src/index.css` + (`.work-*`, `.backlog-*`, the builder-card, needs-attention, recently-closed and `.decisions-*` + rules). They are rewritten against `--codev-wv-*` tokens, each with a default equal to today's + dashboard value. +- **Tests:** the existing `apps/web` tests for these components, moved into the package, with + their assertions unchanged in intent: + - `BuilderCard.test.tsx`, `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`; + - `DecisionsView*.test.tsx`, `useDecisions.test.ts`, `issueIds.test.ts` (the `issueRef` part). + + Where a test mocked `lib/api.ts`, it now passes a fake host. + +**`apps/web`:** + +- thin wrappers `src/components/WorkView.tsx` and `src/components/DecisionsView.tsx` build a + fetch-based host from `lib/api.ts` (unchanged) and pass the dashboard slots; +- `index.css` maps `--codev-wv-*` to its palette and imports the package styles; +- the package is added to `package.json`; +- tests that exercise the dashboard integration stay in `apps/web`: `App.decisions-tab.test.tsx`, + `App.workview-scroll.test.tsx`, `fetchDecisions.test.ts`, `useTabs.decisions.test.ts` and + `useOverview.stability.test.ts`. + +**Repo wiring:** + +- `pnpm-workspace.yaml` already globs `packages/*`; +- `.github/workflows/test.yml` gains a step that runs the package's tests and type-check; +- `scripts/bump-all.sh` is left alone, because the package is private and versionless like + `apps/web`. + +#### Deliverables + +- [ ] The package, its adapter, its styles and the moved tests. +- [ ] The dashboard on the package, through wrappers. +- [ ] No component used by Work or Decisions left in `apps/web`. A repo check proves there is + one copy. + +#### Acceptance Criteria + +- [ ] `apps/web` `test`, `check-types` and `build` pass. `App.decisions-tab` and + `App.workview-scroll` pass unchanged. +- [ ] The package's `test` and `check-types` pass. +- [ ] **Rendered:** in the harness's Tower dashboard, Work and Decisions look and behave as before + (spec scenario 20, compared with screenshots taken on `main` beforehand). A ruling round-trips. +- [ ] A grep check in the package tests asserts that the moved component files exist only in + `packages/workspace-views/src`. + +#### Test Plan + +- The moved unit tests. +- New fake-host tests: + - an absent `openBuilder` hides the *Open* button; + - an absent `newShell` hides *+ Shell*; + - slots render only when passed; + - `rule()` refusals render the server message. +- Dashboard render comparison in the harness. + +### Phase 6: Decisions panel in VS Code, its host bridge, and the hierarchy's Decisions entry + +**Dependencies**: Phase 3 (for the Decisions entry), Phase 5 + +#### Objective + +Let the owner rule on decisions without leaving VS Code. The panel is the shared `DecisionsView` +in an editor-area webview, with every Tower call made by the host. This phase also builds the +webview infrastructure that Phase 7 reuses. + +#### Files to Create / Modify + +**`packages/sdk/src/tower-client.ts`:** + +- `getDecisions(workspacePath)`, `ruleDecision(workspacePath, req)` and + `getDecisionImage(workspacePath, path)`. They use the existing private `requestPreservingBody`, + so `{ ok:false, code, message }` survives a non-2xx; +- the image result carries bytes and a content type. + +Tests go in `packages/sdk/src/__tests__/tower-client.decisions.test.ts`, and the SDK boundary tests +stay green. + +**New `apps/vscode/src/workspace-views/` (host side):** + +- `messages.ts`: the host↔webview contract, with an `is*Message` guard for every inbound message; +- `security.ts`: canonical, symlink-resolved workspace containment via `fs.realpath`, and an + `http:`/`https:` allowlist for external opens; +- `panel-template.ts`: the nonce CSP. + - `script-src 'nonce-…'`; + - `style-src ${cspSource}`; + - `img-src ${cspSource} blob: http: https:`; + - no `connect-src`; + - `localResourceRoots` set to `dist`. +- `decisions-panel.ts`, a single-instance `WebviewPanel` (`retainContextWhenHidden`): + - polls through the host every 2 s while visible and stops while hidden; + - drops responses for a disposed panel; + - supports not-connected, last-known-good and empty states; + - workspace images are sent as bytes and shown as object URLs; + - http(s) links open externally through the allowlist; + - the full-size image is shown in the panel; + - it registers a `WebviewPanelSerializer` for reload restore. + +**New `apps/vscode/src/workspace-views/webview/decisions-main.tsx`:** mounts the shared +`DecisionsView` with a postMessage-backed host, plus `webview/vscode-theme.css`, which maps +`--codev-wv-*` to `--vscode-*`. + +**Build:** + +- `apps/vscode/esbuild.js`: a new entry, `dist/webview/decisions.{js,css}`; +- `tsconfig.webview.json`: adds `jsx: react-jsx` and the new webview directory; +- `apps/vscode/package.json`: the dependency on `@cluesmith/codev-workspace-views` (and + `prepublish-workspace-deps.test.ts` updated if it enumerates workspace dependencies). + +**Commands and entry:** + +- `codev.openDecisions` (*Codev: Open Decisions*), via `regCli`; +- in builder-worktree and no-workspace windows it shows the explanation instead of acting; +- `CockpitProvider` gains the **Decisions** entry after the architects of every active workspace: + - under this window's workspace it opens or reveals the panel, without arranging; + - elsewhere it navigates, as the other rows do; +- the mapping oracle and parity test are updated for the new entry. + +#### Deliverables + +- [ ] SDK methods; the host bridge; the security helpers; the Decisions panel; the command; the + Decisions entry. +- [ ] Unit tests for each. + +#### Acceptance Criteria + +- [ ] Spec scenarios 6 (host message contract), 8 (decisions bridge), 15, 16 and 22 pass. The + rendered ones (15, 16) are run in the harness at this phase's end, with screenshots, because + Phase 7's verification focuses on Work. +- [ ] The Tower key never appears in any message sent to the webview (asserted on the message log + in a host test). +- [ ] Type-check (host and webview configs), lint, unit tests and the SDK boundary tests pass. + +#### Test Plan + +- **Host unit tests:** + - the guard rejects malformed messages; + - containment refuses `..`, absolute-outside and symlink escapes (a real temporary directory + with a symlink); + - the allowlist refuses `javascript:`, `file:` and `vscode:`; + - a refusal passes through with its code and message; + - transport errors are handled; + - not-found maps to the empty state; + - polling stops when hidden; + - a late response after dispose is dropped; + - single instance. +- **Webview unit tests** (jsdom): mounting with a fake bridge renders items, and Submit posts the + right message. +- **Rendered:** + - rule an item, and check the file and the hub notice; + - a stale fingerprint is refused and the draft kept; + - images: a workspace image, an https image, a refused image, and the full-size view; + - with no file, the empty state, then `afx decisions init` in the fixture makes items appear; + - the Decisions entry from the hierarchy. + +### Phase 7: Work panel in VS Code, increment-2 verification + +**Dependencies**: Phase 6 (shared webview infrastructure) + +#### Objective + +Put the dashboard's Work view in VS Code, fed from the same `OverviewCache` as the sidebar, with +every kept affordance mapped to a VS Code action and every dropped one absent. + +#### Files to Create / Modify + +- **New `apps/vscode/src/workspace-views/work-panel.ts`:** a single-instance `WebviewPanel` + (`retainContextWhenHidden`). + - It pushes `OverviewCache` data and connection state to the webview. + - Its visibility counts toward `setupPeriodicOverviewRefresh`. The gate is extended from + TreeViews to "TreeViews or the Work panel". + - It maps the dashboard actions as follows: + - *Open* → `terminalManager.openBuilderByRoleOrId`; + - *+ Shell* → `codev.newShell`; + - *Refresh* → `client.refreshOverview()` (the SDK's existing `POST /api/overview/refresh`), + then `overviewCache.refresh()`; + - artifact links → `openArtifact`, checked by containment; + - external links → the allowlist. + - It registers a serializer for reload restore. +- **New `apps/vscode/src/workspace-views/webview/work-main.tsx`:** mounts the shared `WorkView` + with no dashboard slots. +- `apps/vscode/esbuild.js`: a `dist/webview/work.{js,css}` entry. +- `codev.openWork` (*Codev: Open Work*), with the same window rules as `codev.openDecisions`. +- **Docs:** the README Work/Decisions section; `arch.md` (the shared package and the host-adapter + pattern, extending the canvas precedent); the CHANGELOG. + +#### Deliverables + +- [ ] The Work panel, the command, the refresh-gate extension, tests and docs. +- [ ] Rendered verification of increment 2. + +#### Acceptance Criteria + +- [ ] The spec's Work criteria hold: + - builders, Needs Attention, Backlog and Recently Closed render; + - each mapped action does what the table says; + - no dropped affordance renders. +- [ ] Periodic refresh runs with only the Work panel visible. +- [ ] **Rendered:** + - spec scenarios 17 (Work actions), 18 (light, dark and high-contrast themes, and a live switch) + and 19 (the Tower-unreachable part, simulated by stopping the *harness's* Tower); + - screenshots. +- [ ] Type-check, lint and all unit suites pass. + +#### Test Plan + +- **Unit:** the action mapping; the refresh gate with only the Work panel visible; a refused + artifact path; an external URL scheme refused; dropped slots absent. +- **Rendered:** as above. + +### Phase 8: Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification + +**Dependencies**: Phase 3, Phase 6, Phase 7 + +#### Objective + +The one-click layout: `main` architect | (Work over Decisions). It arranges automatically on the +first show per window session, and on demand. It never closes or discards a user's editor. + +#### Files to Create / Modify + +**Spike first, in the harness, recorded in the thread and the review.** It confirms: + +- (a) `vscode.setEditorLayout` with + `{ orientation: 0, groups: [{}, { groups: [{}, {}] }] }` merges editors from groups it removes + into remaining groups. Dirty, untitled and modified editors survive, with their content; +- (b) an editor-area terminal tab moves between groups without ending its session, using + `terminal.show()` then `workbench.action.moveEditorToFirstGroup`; +- (c) a panel terminal moves into the editor area through `workbench.action.terminal.moveToEditor`; +- (d) `WebviewPanel.reveal(viewColumn)` moves a retained panel without reloading it. + +If (a) does not hold, arrange only **adds or reuses** groups and never removes one, as the spec +already allows. If (b) or (c) does not hold, the plan stops and the architect is told before +another approach is chosen. + +**New `apps/vscode/src/cockpit/arrange.ts`, `arrangeCockpit()`:** + +- shapes the layout, preserving editors per the spike; +- resolves `main` through `openResolvedArchitect`. A non-live `main` gets the existing warning and + no substitute; +- reuses an open architect terminal and moves it to group 1, even with `terminalPosition: panel` + (this path only); +- opens or reveals the Work panel in the top-right group and Decisions in the bottom-right; +- makes each of the three the active tab in its group; +- is idempotent. + +**New `apps/vscode/src/cockpit/auto-arrange.ts`:** + +- runs the first-show check on view creation and on visibility change, once per window session; +- respects `codev.cockpit.autoArrange`; +- does nothing in builder-worktree and no-workspace windows; +- **the one-time notice:** + - when `globalState['codev.cockpit.autoArrangeNoticeShown']` is unset on an auto-arrange, it is + set and an information message is shown with *Don't arrange automatically*; + - choosing that action writes `codev.cockpit.autoArrange = false` at + `ConfigurationTarget.Global`; + - a manual arrange never shows the notice. + +**`apps/vscode/package.json`:** + +- the command `codev.cockpit.arrange` (*Codev: Arrange Cockpit*); +- a title-bar entry, hidden when `codev.isBuilderWorktree || !codev.hasWorkspace`; +- the setting `codev.cockpit.autoArrange` (boolean, default `true`). + +The command stays in the palette everywhere and explains itself where it does nothing. + +**Also in this phase:** + +- `apps/vscode/src/extension.ts`: wiring; +- tests: `cockpit-arrange.test.ts`, `cockpit-auto-arrange.test.ts`, and + `contributes-cockpit.test.ts` extended; +- docs: the README *Arrange Cockpit* section, the setting, and that builder placement follows + #1671; `arch.md`; the CHANGELOG. + +#### Deliverables + +- [ ] The spike result recorded; arrange; triggers; the setting; the notice; the explanations; + tests; docs. +- [ ] Rendered verification of increment 3 and the PR's screenshot set. + +#### Acceptance Criteria + +- [ ] Spec scenarios 7 (trigger and notice), 9 (arrange), 13 (dirty, untitled and modified + editors survive; re-run changes nothing; the Decisions draft persists) and 14 (`main` not + live) pass. +- [ ] The notice criterion holds: it appears once per profile, its action turns the setting off + globally, dismissing changes nothing, and it never appears on a manual arrange. +- [ ] **Rendered:** the split with a pending decision, in light and dark themes, on a fresh profile + and on an existing profile (activity-bar order noted in the PR if VS Code places the button + elsewhere). +- [ ] Type-check, lint, all unit suites, the `apps/web` tests and the package tests pass. + +#### Test Plan + +- **Unit**, with mocked `vscode` commands, `tabGroups` and `globalState`: + - the trigger once per session, including when visible at creation; + - the setting off; + - worktree and no-workspace windows; + - the notice set and shown once, the action writes Global, dismiss leaves it unchanged, manual + arrange shows nothing; + - arrange delegates to `openResolvedArchitect`; + - panels reused; + - idempotent. +- **Rendered:** as above. + +## Verification harness (Phases 4, 5, 6, 7, 8) + +The spec requires that verification never touches the owner's live IDE or Tower. Each rendered +checkpoint runs, and then stops, this harness: + +- **Isolated Tower:** the branch's built CLI starts a Tower on a non-default port (for example + `4199`) with `CODEV_AGENT_FARM_DIR` pointing at a fresh directory under the session scratchpad. + It has its own `global.db`, key and registry. +- **Isolated VS Code:** `code serve-web` on its own port, with its own `--server-data-dir`, + `--user-data-dir` and `--extensions-dir` under the scratchpad. The branch's vsix is installed + there, and the setting `codev.towerPort` is set to the isolated Tower's port. +- **Fixture workspaces:** two or more small git repos under the scratchpad, registered only with + the isolated Tower. + - `.builders/` entries give the N=0 / N=1 / N>1 builder states without spawning agents. Tower's + overview discovers builders by scanning `.builders/`. + - A second architect appears through `afx` against the isolated Tower. + - A `codev/decisions.md` comes from `afx decisions init`. +- **Driver:** Python/Node Playwright, headless Chromium, with screenshots saved to the scratchpad + and attached to the PR. + +The harness is one extra Tower process and one VS Code web server, with no builders. The architect +is told before its first start. Anything that would touch port 4100, `~/.agent-farm` or the owner's +`/ide/` is out of bounds. + +## Risks and Mitigation + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| The row-builder extraction (Phase 2) changes an Agents id or behaviour | Medium | High | An id-equivalence snapshot taken from the pre-refactor provider in the same commit, plus every existing Agents test unmodified | +| Generalised wiring regresses accordion, reveal or cycle in Agents | Medium | High | Per-view hosts with the Agents path unchanged; existing behaviour tests plus new per-view tests; rendered check of both views | +| The layout primitive closes or discards an editor | Low | High | The Phase 8 spike before any arrange code, with the add/reuse-only rule from the spec if it fails; the dirty/untitled/modified scenario rendered | +| Moving components changes the dashboard | Medium | Medium | Wrappers keep `lib/api.ts`; the moved tests are unchanged in intent; the dashboard integration tests stay; a rendered before/after comparison | +| A source-exported TSX package does not type-check under one host's config | Low | Medium | `jsx: react-jsx` added to the webview tsconfig; if a host still cannot consume it, the package gains a `tsdown` build like `codev-artifact-canvas`. That is a build-wiring change, not scope, and it is named in the PR | +| The harness accidentally touches the owner's Tower or IDE | Low | High | Non-default port, isolated `CODEV_AGENT_FARM_DIR` and VS Code data dirs, no `afx` against :4100; the architect is told before the first start | +| CSS moved out of `index.css` misses a rule, so the dashboard looks different | Medium | Low | A selector inventory before the move, and the rendered dashboard comparison | +| `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 6, and build the vsix in the harness from Phase 4 onward | + +## Documentation Updates + +- `apps/vscode/README.md`: the Cockpit button and hierarchy (Phase 4), the Work and Decisions panels + (Phase 7), *Arrange Cockpit* and `codev.cockpit.autoArrange` (Phase 8). +- `codev/resources/arch.md`, *VS Code Extension*: + - the Cockpit container and act/navigate rule; + - `ArchitectTreeBuilder` and fleet-overview retention (Phase 4); + - the shared `@cluesmith/codev-workspace-views` package and host adapter (Phase 7); + - the arrange flow (Phase 8). + + Hot-tier files are not touched unless the review step routes a fact there. +- `apps/vscode/CHANGELOG.md`: one entry per increment. +- The review (`codev/reviews/1963-…`) at the end records the spike result and the + lessons-learned candidates. From 125157c1c859cb8727436fca4f4cdbf0f58c316a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:05:36 -0800 Subject: [PATCH 015/140] chore(porch): 1963 plan build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 70f584966..330174e64 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -16,7 +16,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T05:59:46.569Z' +updated_at: '2026-11-24T06:05:35.969Z' From 3958e4d0cde8abda23804ad4036fd2dfb898f53e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:05:55 -0800 Subject: [PATCH 016/140] [Spec 1963] Thread: spec approved, plan drafted --- codev/state/spir-1963_thread.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index f92abc82c..b08a2b628 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -69,3 +69,25 @@ hierarchy → shared package + panels → arrange), active workspace rows click- the inline action), Tower root shows "Not connected to Tower" + Reconnect after the first failed attempt (ConnectionManager retries forever, never gives up), Loading… child before an overview. New owner question offered, not specced: a one-time notice on the first auto-arrange. + +## 2026-11-24 — Spec approved → plan + +Owner approved the spec ("go with your recommendation" on all four): other workspaces navigate-only +(acting in place → #1969), no Decisions pending count (→ #1970), dev URLs as "Open Dev URL…", and +ADD the one-time first-auto-arrange notice. Rulings recorded in the spec (95029fd66); ran +`porch approve 1963 spec-approval` on the architect's relay. + +Plan gate is pre-approved by the owner for a plan that implements the approved spec; I still wait +for the architect's go (after their check) before `porch approve 1963 plan-approval`. + +Plan (9475ca950): 8 phases on the spec's 3 increments — +1 fleet-cache overview retention · 2 `ArchitectTreeBuilder` extracted from BuildersProvider +(scoped ids, act/navigate modes; Agents ids byte-identical) · 3 Cockpit container + hierarchy + +generalised tree wiring · 4 placement-table menus + parity mapping oracle + rendered check · +5 `@cluesmith/codev-workspace-views` (source-exported, host adapter, `--codev-wv-*` tokens), +dashboard on wrappers · 6 SDK decisions methods + Decisions panel + Decisions entry · 7 Work panel · +8 spike then Arrange Cockpit + triggers + notice. +Verification harness: isolated Tower (non-default port, own CODEV_AGENT_FARM_DIR) + `code serve-web` +with isolated data/extension dirs + fixture repos — never :4100 or the owner's /ide/. +Finding while planning: builder rows show no held/queued today, so those counts are Cockpit-only +(an `attentionCounts` option) to keep Agents byte-for-byte. From 08699b0b2a5b870f8b155e7a4b9a09a1eaf591d3 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:11:23 -0800 Subject: [PATCH 017/140] [Spec 1963] Plan with multi-agent review --- .../1963-vscode-alternative-layout-seco.md | 136 +++++++++++++++--- .../1963-plan-iter1-rebuttals.md | 62 ++++++++ 2 files changed, 179 insertions(+), 19 deletions(-) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-rebuttals.md diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index 9cf023060..d4f3043bd 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -238,6 +238,14 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. unattributed held mail and escalation. - **Re-render:** on `overviewCache.onDidChange`, `towerCache.onDidChange` and `connectionManager.onStateChange`. + - **Ids:** the Tower root, workspace rows and the Dormant group get explicit stable ids: + `cockpit-tower`, `cockpit-ws:` and `cockpit-dormant`. `TowerProvider` sets none today, + but a Cockpit row must keep its expansion across refreshes and be matchable by `reveal`. + - **`getParent` across the whole chain**, over the union element type: + file → folder(s) → builder → architect → (*Idle Architects*) → workspace → Tower root. The + builder answers up to its architect row. The Cockpit bridges each scoped architect row (and + the *Idle Architects* container) to its workspace node, and each workspace node to the root + or the Dormant group. Active-file reveal and agent-cycle selection depend on this. - **`apps/vscode/src/extension.ts`:** - create `cockpitView`; - generalise the `buildersView`-bound wiring into a small registry, `AgentTreeHosts` @@ -252,6 +260,9 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. `cockpitView`, with the same suppression; - `cockpitView.visible` joins `anyVisible()` and its visibility event joins `reconcile` in `setupPeriodicOverviewRefresh`; + - the config listeners serve both views. The `codev.buildersFileViewAsTree` listener refreshes + the Cockpit provider as well as `buildersProvider`. The `codev.buildersAutoCollapse` listener + updates both views' `AccordionGate`s, and sets the context key that both title bars read; - `codev.cockpit.refresh` refreshes `overviewCache` and `towerCache`. - **Tests:** - new `apps/vscode/src/__tests__/cockpit-provider.test.ts`; @@ -265,6 +276,9 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. - [ ] `CockpitProvider` with every level, state row and fold rule in spec §2. - [ ] Generalised tree behaviours, the badge on both views, and periodic refresh with the Cockpit counted. +- [ ] Stable ids for the Cockpit's own nodes, and a `getParent` chain that reaches the Tower root + from every row. +- [ ] Config listeners that redraw and re-gate both views. - [ ] Tests listed below. #### Acceptance Criteria @@ -294,12 +308,17 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. - worktree and no-workspace variants; - colliding names across two workspaces; - `codev.buildersGroupBy = stage|area` leaves the tree unchanged; - - every attention kind lands on its row. + - every attention kind lands on its row; + - `getParent` from a file row of this window's workspace (flat and tree modes), from a builder, + from an idle-sibling architect and from an architect row returns the chain to `cockpit-tower`. + `reveal` then succeeds on a fake TreeView that walks `getParent`. - **`cockpit-wiring.test.ts`:** - `openBuilderRow` reveals in the owning view; - accordion per view; - the visibility gate runs with only the Cockpit visible and stops with nothing visible; - - the badge is equal on both views and suppressed when disconnected and in a worktree window. + - the badge is equal on both views and suppressed when disconnected and in a worktree window; + - toggling `codev.buildersFileViewAsTree` refreshes both providers, and toggling + `codev.buildersAutoCollapse` re-gates both accordions. - **`cockpit-icon.test.ts`:** same `d` attribute as `codev.svg`, wrapped in `rotate(90 400 400)`. ### Phase 4: Placement-table actions on the hierarchy, parity mapping, increment-1 verification @@ -319,7 +338,7 @@ verification and docs. - `view/item/context` entries for `view == codev.cockpit`: - builder rows of this window's workspace: the same commands, groups and `viewItem` patterns as - the 13 Agents row entries; + the 12 Agents `view/item/context` entries; - architect rows: *Remove Architect* on siblings; - workspace rows: - *Open* / *Deactivate* inline, as in Tower; @@ -370,9 +389,21 @@ window: fleet-overview retention and the act/navigate rule; - `CHANGELOG` entry for `apps/vscode`. +**`codev.removeArchitect` handler (`extension.ts`).** It resolves the name from an id starting +`workspace-architect-`, else from `arg.label`. A Cockpit architect row is a group row whose label +is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect(ws, 'WEB (0)')`. + +- **Change:** a `BuilderGroupTreeItem` argument resolves to its `groupName`. The Workspace-view and + string paths are unchanged. +- **Accepted difference:** the Cockpit's architect rows come from the overview's `architects`, as + the Agents architect axis does. The Workspace view lists architects from the workspace status's + terminals. Any difference between the two sets is accepted, as it is today between Workspace and + Agents. + #### Deliverables - [ ] All placement-table entries for increment 1 (the Decisions entry is Phase 6). +- [ ] The `removeArchitect` argument resolution for Cockpit architect rows, with a unit test. - [ ] The mapping oracle and the parity test. - [ ] Rendered verification of increment 1 and docs. @@ -516,10 +547,17 @@ webview infrastructure that Phase 7 reuses. **`packages/sdk/src/tower-client.ts`:** -- `getDecisions(workspacePath)`, `ruleDecision(workspacePath, req)` and - `getDecisionImage(workspacePath, path)`. They use the existing private `requestPreservingBody`, - so `{ ok:false, code, message }` survives a non-2xx; -- the image result carries bytes and a content type. +- `getDecisions(workspacePath)` and `ruleDecision(workspacePath, req)` use the existing private + `requestPreservingBody`, so `{ ok:false, code, message }` survives a non-2xx. +- `getDecisionImage(workspacePath, path)` cannot use it: that helper reads `response.text()` and + JSON-parses the body, which destroys binary bytes and drops `Content-Type`. It uses a new private + `requestBinary(path)` instead: + - an authenticated `fetchFn` call (same key header, base URL and timeout); + - it returns `{ status, bytes: Uint8Array, contentType }` on 2xx; + - on a non-2xx it returns `{ status, body }`, the JSON-parsed body, so a refusal keeps its code + and message; + - like every method on this client, it never rejects. A transport failure comes back as + `status: 0`. Tests go in `packages/sdk/src/__tests__/tower-client.decisions.test.ts`, and the SDK boundary tests stay green. @@ -527,8 +565,13 @@ stay green. **New `apps/vscode/src/workspace-views/` (host side):** - `messages.ts`: the host↔webview contract, with an `is*Message` guard for every inbound message; -- `security.ts`: canonical, symlink-resolved workspace containment via `fs.realpath`, and an - `http:`/`https:` allowlist for external opens; +- `security.ts`: + - canonical, symlink-resolved workspace containment. Both sides go through `fs.realpath`, then + `path.relative(root, target)` is taken. The target is inside only if the result is not + absolute, is not `..`, and does not start with `..` followed by a separator. There is no + string-prefix check, so on Windows drive-letter case and `\` / `/` are normalised by the + same calls; + - an `http:`/`https:` allowlist for external opens. - `panel-template.ts`: the nonce CSP. - `script-src 'nonce-…'`; - `style-src ${cspSource}`; @@ -536,7 +579,15 @@ stay green. - no `connect-src`; - `localResourceRoots` set to `dist`. - `decisions-panel.ts`, a single-instance `WebviewPanel` (`retainContextWhenHidden`): - - polls through the host every 2 s while visible and stops while hidden; + - **Polling has one owner:** the shared `useDecisions` hook, with its existing 2 s cadence. Each + tick calls the host adapter's `read()`, and the host makes one Tower request per call. The host + runs no timer of its own. + - Hidden means the *panel* is hidden. A retained, hidden webview's iframe still reports + `document.visibilityState === 'visible'`, so the hook's page-visibility gate never fires + there. + - So the host relays `onDidChangeViewState` as a `{ type: 'visibility', visible }` message, + and the webview passes it as the hook's existing `isActive` input. Polling stops while the + panel is hidden and resumes when it is shown; - drops responses for a disposed panel; - supports not-connected, last-known-good and empty states; - workspace images are sent as bytes and shown as object URLs; @@ -550,8 +601,16 @@ stay green. **Build:** -- `apps/vscode/esbuild.js`: a new entry, `dist/webview/decisions.{js,css}`; -- `tsconfig.webview.json`: adds `jsx: react-jsx` and the new webview directory; +- `apps/vscode/esbuild.js`: a new entry, `dist/webview/decisions.{js,css}`. + - It sets `jsx: 'automatic'` explicitly, with `tsconfig: 'tsconfig.webview.json'`. The existing + webview entries are `.ts` (their JSX lives in canvas's prebuilt `dist`), and esbuild otherwise + reads the nearest `tsconfig.json`, which sets no `jsx`. These are the first TSX sources + compiled under `apps/vscode`. + - A bundle smoke test loads the built `dist/webview/decisions.js` in jsdom and asserts it mounts. +- `tsconfig.webview.json`: adds `jsx: react-jsx` and the new `src/workspace-views/webview` + directory; +- `apps/vscode/tsconfig.json`: adds `src/workspace-views/webview` to `exclude`, alongside the two + existing webview directories, so the host `tsc --noEmit` never compiles browser TSX; - `apps/vscode/package.json`: the dependency on `@cluesmith/codev-workspace-views` (and `prepublish-workspace-deps.test.ts` updated if it enumerates workspace dependencies). @@ -578,6 +637,10 @@ stay green. - [ ] The Tower key never appears in any message sent to the webview (asserted on the message log in a host test). - [ ] Type-check (host and webview configs), lint, unit tests and the SDK boundary tests pass. +- [ ] **Windows.** This phase adds path code: canonical-path containment that resolves symlinks. + The on-demand Windows workflow is dispatched on the branch and its run is linked in the PR: + `gh workflow run windows.yml --ref builder/spir-1963 -f purpose='Spec 1963: webview path + containment (realpath/relative, junctions)' -f suites=true`. #### Test Plan @@ -585,11 +648,20 @@ stay green. - the guard rejects malformed messages; - containment refuses `..`, absolute-outside and symlink escapes (a real temporary directory with a symlink); + - **Windows path cases.** These run as `path.win32` table tests on every OS, and for real in the + Windows workflow: + - drive-letter case (`c:\ws` vs `C:\ws`); + - mixed separators; + - a different drive; + - a UNC root (`\\server\share`) against a local root; + - a prefix sibling (`C:\ws-other` vs `C:\ws`); + - on the Windows runner, a directory junction pointing outside the workspace; - the allowlist refuses `javascript:`, `file:` and `vscode:`; - a refusal passes through with its code and message; - transport errors are handled; - not-found maps to the empty state; - - polling stops when hidden; + - polling stops when hidden: after a `visibility: false` message, no `read` request reaches + the host until `visibility: true`; - a late response after dispose is dropped; - single instance. - **Webview unit tests** (jsdom): mounting with a fake bridge renders items, and Submit posts the @@ -599,7 +671,8 @@ stay green. - a stale fingerprint is refused and the draft kept; - images: a workspace image, an https image, a refused image, and the full-size view; - with no file, the empty state, then `afx decisions init` in the fixture makes items appear; - - the Decisions entry from the hierarchy. + - the Decisions entry from the hierarchy; + - spec scenario 18 for Decisions: light, dark and high-contrast themes, and a live switch. ### Phase 7: Work panel in VS Code, increment-2 verification @@ -621,7 +694,8 @@ every kept affordance mapped to a VS Code action and every dropped one absent. - *Open* → `terminalManager.openBuilderByRoleOrId`; - *+ Shell* → `codev.newShell`; - *Refresh* → `client.refreshOverview()` (the SDK's existing `POST /api/overview/refresh`), - then `overviewCache.refresh()`; + then `overviewCache.refresh()`. That route is machine-global, with no workspace argument, + unlike every other Work action. It is the same call the dashboard's *Refresh* makes; - artifact links → `openArtifact`, checked by containment; - external links → the allowlist. - It registers a serializer for reload restore. @@ -764,12 +838,34 @@ checkpoint runs, and then stops, this harness: there, and the setting `codev.towerPort` is set to the isolated Tower's port. - **Fixture workspaces:** two or more small git repos under the scratchpad, registered only with the isolated Tower. - - `.builders/` entries give the N=0 / N=1 / N>1 builder states without spawning agents. Tower's - overview discovers builders by scanning `.builders/`. - - A second architect appears through `afx` against the isolated Tower. - - A `codev/decisions.md` comes from `afx decisions init`. + - Each fixture's `.codev/config.json` sets `shell.architect` and `shell.builder` to a plain + shell. So activating a workspace, or adding an architect, starts a shell session, never an AI + agent. + - **Builders need a live terminal.** `/api/overview` lists a discovered `.builders/` worktree + only when Tower's terminal registry holds a live builder session for its role id + (`activeBuilderRoleIds`). Directories alone render zero builders. So each fixture builder is: + - a real `git worktree add` under `.builders//`, with its porch `status.yaml` for + phase/gate; + - a builder terminal registered through Tower's existing `POST /api/terminals`, with + `type: 'builder'`, `roleId: 'builder-'`, the fixture's `workspacePath`, `cwd` set to the + worktree, and a harmless long-running shell command; + - this gives the N=0 / N=1 / N>1 states, a blocked gate, a waiting builder, and + `spawnedByArchitect` values including a null one. + - **Validated before any screenshot.** The first checkpoint asserts that the isolated Tower's + `/api/overview` for each fixture returns the expected builders and architects. If the registry + path does not produce them, verification stops and the architect is told; it does not fall back + to faked data. + - **Driving the harness.** It goes through Tower's HTTP API (activation, terminals, + add-architect), using the isolated key. Where the CLI is needed (a second architect, or creating + the decisions file as `afx decisions init` does), the branch's built CLI runs with `cwd` in a + fixture repo and the isolated port and `CODEV_AGENT_FARM_DIR`. It never runs from this + worktree or against :4100. - **Driver:** Python/Node Playwright, headless Chromium, with screenshots saved to the scratchpad and attached to the PR. + - **Never `playwright install` on this machine.** It hangs at extraction and wedges the shared + browser cache. + - Use the Chromium already in the Playwright cache. If none is usable, install it by hand with + `curl -L` + `unzip` + the `INSTALLATION_COMPLETE` marker, and ask first. The harness is one extra Tower process and one VS Code web server, with no builders. The architect is told before its first start. Anything that would touch port 4100, `~/.agent-farm` or the owner's @@ -787,6 +883,8 @@ is told before its first start. Anything that would touch port 4100, `~/.agent-f | The harness accidentally touches the owner's Tower or IDE | Low | High | Non-default port, isolated `CODEV_AGENT_FARM_DIR` and VS Code data dirs, no `afx` against :4100; the architect is told before the first start | | CSS moved out of `index.css` misses a rule, so the dashboard looks different | Medium | Low | A selector inventory before the move, and the rendered dashboard comparison | | `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 6, and build the vsix in the harness from Phase 4 onward | +| Fixture builders do not appear because Tower lists only builders with a live terminal | High if missed | Medium | Each fixture builder gets a real worktree plus a registered builder terminal, and `/api/overview` is asserted before any screenshot (harness section) | +| Path containment behaves differently on Windows (case, separators, UNC, junctions) | Medium | High | `realpath` + `path.relative` (no prefix compare), `path.win32` table tests, and the on-demand Windows workflow linked in the PR | ## Documentation Updates diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-rebuttals.md new file mode 100644 index 000000000..462a41494 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-rebuttals.md @@ -0,0 +1,62 @@ +# Plan 1963 — iteration 1 rebuttals + +Both reviews were accepted in full and nothing is disputed. I checked each factual claim against the +code before changing the plan. During the reviews HEAD moved only by porch's build-complete commit +and the thread-log commit, and the working-tree change Claude saw was my own edit for Codex's points. + +## Codex (REQUEST_CHANGES) + +1. **Decision images can't use `requestPreservingBody`.** + - **Confirmed:** it calls `response.text()` and parses JSON (`tower-client.ts:1025`). + - **Change:** Phase 6 adds a private `requestBinary` with the same key, base URL and timeout. It + returns bytes and a content type on 2xx, keeps the JSON body on a non-2xx, and never rejects. + Reads and rulings stay on `requestPreservingBody`. +2. **`.builders/` directories alone give zero builders.** + - **Confirmed:** `/api/overview` filters discovered worktrees against `activeBuilderRoleIds`, + taken from the rehydrated terminal registry (`tower-routes.ts:1440`, `overview.ts:1098`). + - **Change:** each fixture builder is a real worktree plus a builder terminal registered through + the existing `POST /api/terminals` (`type: 'builder'`, `roleId`, `workspacePath`, `cwd`, + harmless shell command). + - Each fixture's `shell.architect` and `shell.builder` are a plain shell, so no agent ever + starts. + - The harness asserts `/api/overview` before any screenshot and stops without faking data if it + does not hold. +3. **Path code needs Windows coverage.** + - **Change:** containment is `realpath` + `path.relative`, with no prefix compare. + - `path.win32` table tests cover drive-letter case, separators, a different drive, UNC and + prefix siblings. A junction case runs on the Windows runner. + - The on-demand `windows.yml` run is dispatched on the branch and linked in the PR. + +## Claude (COMMENT) + +1. **`removeArchitect` on a Cockpit row.** + - **Confirmed:** `extension.ts:1209` falls back to the label, `WEB (0)`. + - **Change:** Phase 4 resolves a `BuilderGroupTreeItem` to its `groupName`, as an explicit + deliverable with a unit test. The difference between the two architect sources (overview vs + workspace terminals) is stated as accepted. +2. **Who owns the Decisions poll.** + - **Confirmed:** `useDecisions` owns a 2 s interval gated on `isActive` and + `document.visibilityState`. + - **Change:** the hook stays the one owner. The host relays `onDidChangeViewState` as a + visibility message, which drives `isActive`. A test asserts that no read happens while the + panel is hidden. +3. **Build wiring.** + - Phase 6 adds `src/workspace-views/webview` to `apps/vscode/tsconfig.json`'s `exclude`. + - The new esbuild entries set `jsx: 'automatic'` with `tsconfig: 'tsconfig.webview.json'`. + - A jsdom smoke test asserts the built bundle mounts. +4. **The Cockpit's `getParent` chain and ids.** + - **Change:** Phase 3 gives the Tower root, workspace rows and the Dormant group stable ids. + - `getParent` bridges each architect and idle container to its workspace, and each workspace to + the root. + - Tests cover the chain from file, builder, idle-sibling and architect rows, and a `reveal` that + walks it. Both are listed as deliverables. +5. **Config listeners.** + - **Change:** in Phase 3, the file-tree listener refreshes both providers. The accordion + listener re-gates both views. Tests cover both. + +Minor points, all accepted: + +- 12 Agents item entries, not 13; +- the theme and live-switch scenario also runs for Decisions, in Phase 6; +- no `playwright install` in the harness (manual Chromium path, ask first); +- *Refresh* is noted as machine-global. From 6efe704481bf767b8b49093ea44707445c89e44b Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:11:23 -0800 Subject: [PATCH 018/140] chore(porch): 1963 plan re-iter (iter 2) --- .../status.yaml | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 330174e64..f7c69c9c9 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -15,8 +15,19 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true -history: [] +iteration: 2 +build_complete: false +history: + - iteration: 1 + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-codex.txt + - model: claude + verdict: COMMENT + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:05:35.969Z' +updated_at: '2026-11-24T06:11:23.685Z' From 80fc8dfa2597225304920218667c7fa0c52dfb43 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:11:36 -0800 Subject: [PATCH 019/140] chore(porch): 1963 plan build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index f7c69c9c9..4ed6967da 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -16,7 +16,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 build_output: '' @@ -30,4 +30,4 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:11:23.685Z' +updated_at: '2026-11-24T06:11:36.225Z' From 5e74a52be061e2a8c35b9575e5f7aa43b4a1c4b9 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:16:46 -0800 Subject: [PATCH 020/140] [Spec 1963] Plan with multi-agent review (iteration 2) --- .../1963-vscode-alternative-layout-seco.md | 106 ++++++++++++++---- .../1963-plan-iter2-rebuttals.md | 51 +++++++++ 2 files changed, 137 insertions(+), 20 deletions(-) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter2-rebuttals.md diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index d4f3043bd..c5faa028c 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -125,6 +125,11 @@ Agents view: same rows, same ids, same behaviour. - changed-file children and their parent reconstruction; - `findFileItem`, `revealTargetForAgent` and `agentCycleOrder`. + Architect rows in `act` mode carry the Agents view's `group-builder` contextValue when the scope + is `''`, so the Agents view is unchanged. A scoped (Cockpit) builder gives them + `cockpit-architect-main` or `cockpit-architect-sibling`, so a menu entry can tell `main` from a + sibling. + In `navigate` mode: - builder rows are leaves (no changed files); - architect rows still expand to their builders; @@ -135,6 +140,12 @@ Agents view: same rows, same ids, same behaviour. `ArchitectTreeBuilder` (scope `''`, mode `act`). Stage/area rendering and the lone-Uncategorized flatten stay where they are. They already use the same `makeGroupRow`/`makeBuilderRow`, now reached through the builder. + - `builders.ts` keeps exporting every symbol that moves: `partitionArchitectGroups`, + `agentTargetIsFocused`, `agentCycleAttemptOrder`, `AgentTarget`, `AccordionRowIds`, + `AccordionGate`, `findParentNode`, `runBuilderRowClick` and `orderForDisplay`, re-exported from + their new home where they move. + - So existing tests importing from `../views/builders.js` (for example + `agent-cycle-order.test.ts`) need no edit. - `apps/vscode/src/views/builder-tree-item.ts` and the group, idle-container, folder and file item classes: - each takes an optional `scope` that prefixes its id; @@ -339,7 +350,8 @@ verification and docs. - `view/item/context` entries for `view == codev.cockpit`: - builder rows of this window's workspace: the same commands, groups and `viewItem` patterns as the 12 Agents `view/item/context` entries; - - architect rows: *Remove Architect* on siblings; + - architect rows: *Remove Architect* on `viewItem == cockpit-architect-sibling` only, never on + `cockpit-architect-main`; - workspace rows: - *Open* / *Deactivate* inline, as in Tower; - on the current row, inline *Spawn Builder*, *New Shell* and *Add Architect*; @@ -354,7 +366,22 @@ verification and docs. shared `buildDashboardUrl`, extracted from `WorkspaceProvider`. **Context values on the current workspace row** encode what the Workspace view decides for this -window: +window. The data behind them follows the Workspace view's own sources: + +- **Worktree config.** It is async: `loadWorktreeConfig` awaits `client.getWorktreeConfig(...)`. + The Cockpit resolves it in its async `getChildren` for the Tower root, as `WorkspaceProvider` + does in its `getChildren`, and does not cache it across renders. +- **Re-render signals.** The Cockpit re-renders on the same signals `WorkspaceProvider` subscribes + to: + - `terminalManager.onDidChangeDevTerminals`, so *Start Dev* / *Stop Dev* stays honest across + every start, stop and cleanup path; + - the `codev-config-updated` SSE envelope, for `devUrls` and dev-command edits; + - the `architects-updated` SSE envelope, for add and remove from the CLI. + + These are in addition to the three Phase 3 signals. They need no new connection: the envelopes + come from `connectionManager.onSSEEvent`. + +The values themselves: - `cockpit-workspace-current` plus a dev-slot suffix: `-dev-start`, `-dev-stop` or `-dev-stop-other`. It is computed by a function extracted from `WorkspaceProvider`'s dev-row @@ -414,6 +441,7 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect - a mapped Cockpit entry is missing from `package.json`; - a `cockpit-remote-*` or `cockpit-workspace-parent` value matches a builder or architect entry's `viewItem`; + - *Remove Architect*'s `when` matches `cockpit-architect-main`; - an existing source entry differs from its snapshot. - [ ] From the Cockpit, in the harness, these work on this window's workspace: - every builder context action; @@ -421,6 +449,15 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect - every workspace-row action; - Remove Architect. - [ ] Another workspace's architect or builder row opens that workspace's window. +- [ ] **Request count** (spec scenario 21). The isolated Tower's request log is compared for two + cases: + - the Cockpit alone visible; + - the Workspace, Agents and Tower views alone visible. + + They match: the overview, the fleet fan-out, and one `getWorktreeConfig` per workspace-row + render, the same call the Workspace view makes per render. With both sets visible at once, the + only addition is that second view's own `getWorktreeConfig`. No poll, SSE stream or route is + added. - [ ] **Rendered** (see the harness below), with screenshots: - the button under Codev; - the hierarchy with N=0, N=1 and N>1 builders and two or more workspaces; @@ -432,8 +469,15 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect #### Test Plan -- Unit: the parity test, the dev-slot function (shared cases with `workspace.test.ts`), and - context values on the current, parent and remote workspace rows. +- Unit: + - the parity test; + - the dev-slot function (shared cases with `workspace.test.ts`); + - context values on the current, parent and remote workspace rows; + - main versus sibling architect context values; + - the Cockpit re-renders on a dev-terminal change and on `codev-config-updated` and + `architects-updated` envelopes; + - *Stop Dev* replaces *Start Dev* after a dev starts from a builder's menu; + - `removeArchitect` given a Cockpit sibling row removes that architect by `groupName`. - Rendered: spec scenarios 11, 12 (hierarchy part) and 19 (worktree and no-workspace windows; Cockpit-only freshness). @@ -461,7 +505,12 @@ npm-published):** `builder-helpers` only), `@cluesmith/codev-artifact-canvas`, and React as a peer dependency. - **`src/host.ts`:** the `WorkspaceViewsHost` adapter. Its members are optional unless stated: - `overview` (required): a subscribe/refresh source; - - `decisions`: `read()`, `rule(req)`, `image(path)`; + - `decisions`: `read()`, `rule(req)`, `image(path, signal?)`. + - `DecisionsView` keeps its per-image `AbortController`. The dashboard adapter passes the + signal to `fetch`, as today. + - The VS Code adapter tags each image request with an id. On abort it ignores the reply for + that id; the host's fetch may still finish and is discarded. A test covers an aborted image + whose reply arrives late; - `openBuilder(id)`; - `newShell()`; - `refresh()`; @@ -574,7 +623,12 @@ stay green. - an `http:`/`https:` allowlist for external opens. - `panel-template.ts`: the nonce CSP. - `script-src 'nonce-…'`; - - `style-src ${cspSource}`; + - `style-src ${cspSource} 'unsafe-inline'`, the same as the existing webviews + (`contextual-panel/panel-template.ts`, `markdown-preview/preview-template.ts`). + - The shared components set React `style` attributes. For example, `BuilderCard`'s progress + bar uses `style={{ width: … }}`. A `style-src` without `'unsafe-inline'` would silently drop + those. + - Scripts stay nonce-only. Inline *styles* do not run code; - `img-src ${cspSource} blob: http: https:`; - no `connect-src`; - `localResourceRoots` set to `dist`. @@ -719,7 +773,9 @@ every kept affordance mapped to a VS Code action and every dropped one absent. - no dropped affordance renders. - [ ] Periodic refresh runs with only the Work panel visible. - [ ] **Rendered:** - - spec scenarios 17 (Work actions), 18 (light, dark and high-contrast themes, and a live switch) + - spec scenarios 17 (Work actions, including a builder's progress bar rendering at its width + under the real webview CSP; jsdom does not enforce CSP), 18 (light, dark and high-contrast + themes, and a live switch) and 19 (the Tower-unreachable part, simulated by stopping the *harness's* Tower); - screenshots. - [ ] Type-check, lint and all unit suites pass. @@ -841,20 +897,30 @@ checkpoint runs, and then stops, this harness: - Each fixture's `.codev/config.json` sets `shell.architect` and `shell.builder` to a plain shell. So activating a workspace, or adding an architect, starts a shell session, never an AI agent. - - **Builders need a live terminal.** `/api/overview` lists a discovered `.builders/` worktree - only when Tower's terminal registry holds a live builder session for its role id - (`activeBuilderRoleIds`). Directories alone render zero builders. So each fixture builder is: - - a real `git worktree add` under `.builders//`, with its porch `status.yaml` for - phase/gate; - - a builder terminal registered through Tower's existing `POST /api/terminals`, with - `type: 'builder'`, `roleId: 'builder-'`, the fixture's `workspacePath`, `cwd` set to the - worktree, and a harmless long-running shell command; - - this gives the N=0 / N=1 / N>1 states, a blocked gate, a waiting builder, and - `spawnedByArchitect` values including a null one. + - **What makes a builder appear.** `/api/overview` lists a `.builders/` worktree only when: + - Tower's terminal registry holds a live builder session for its role id + (`activeBuilderRoleIds`). Directories alone render zero builders; + - its `spawnedByArchitect` is read from the isolated `global.db` `builders` row + (`spawned_by_architect`). `discoverBuilders` itself always emits `null`, so a builder with no + row folds into `main`. + - **So fixture builders are spawned for real by the branch's CLI** (`afx spawn --task "…"`, which + needs no GitHub issue): + - it runs with `cwd` in a fixture repo, against the isolated Tower; + - it sets `CODEV_ARCHITECT_NAME=` per spawn, the variable Tower injects into + architect terminals and `spawn.ts` records as `spawned_by_architect`; + - with the fixture's `shell.builder` set to a plain shell, this creates the worktree, the + `builders` row with its attribution, and a live builder terminal, and never starts an agent; + - this gives N=0, N=1 and N>1 builders under `main` and under a second architect, across two + workspaces; + - blocked-gate and waiting states come from the fixture builders' porch state, which is + synthetic test data in scratch repos, never a real project's; + - the null-attribution fold, which no spawn can produce, is covered by unit tests rather than + screenshots. - **Validated before any screenshot.** The first checkpoint asserts that the isolated Tower's - `/api/overview` for each fixture returns the expected builders and architects. If the registry - path does not produce them, verification stops and the architect is told; it does not fall back - to faked data. + `/api/overview` for each fixture returns the expected builders, **with their expected + `spawnedByArchitect` values**, and the expected architects. + - If spawning does not produce them, verification stops and the architect is told. + - It does not fall back to faked data, nor to hand-written database rows. - **Driving the harness.** It goes through Tower's HTTP API (activation, terminals, add-architect), using the isolated key. Where the CLI is needed (a second architect, or creating the decisions file as `afx decisions init` does), the branch's built CLI runs with `cwd` in a diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter2-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter2-rebuttals.md new file mode 100644 index 000000000..b97838e0c --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter2-rebuttals.md @@ -0,0 +1,51 @@ +# Plan 1963 — iteration 2 rebuttals + +Both reviewers returned COMMENT. Every point was checked against the code and accepted; nothing is +disputed. The working-tree change Claude saw was my edit for Codex's CSP point. + +## Codex (COMMENT) + +1. **`BuilderCard`'s inline `style` vs `style-src`.** + - **Confirmed:** `BuilderCard.tsx:135` uses `style={{ width }}`. + - **Change:** the panels' CSP is `style-src ${cspSource} 'unsafe-inline'`, the same as both + existing webviews (`panel-template.ts:25`, `preview-template.ts:50`). Scripts stay nonce-only. + - Phase 7's rendered check asserts the progress bar's width under the real webview CSP, since + jsdom does not enforce CSP. + +## Claude (COMMENT) + +1. **The harness can't produce `spawnedByArchitect`.** + - **Confirmed:** the attribution is read only from `global.db`'s `builders` table + (`overview.ts:698`). `discoverBuilders` emits `null`, and `spawn.ts` records + `CODEV_ARCHITECT_NAME`. + - **Change:** fixture builders are real `afx spawn --task` runs by the branch's CLI. + - They run with `cwd` in a fixture repo, against the isolated Tower, with + `CODEV_ARCHITECT_NAME` set per spawn. The plain-shell `shell.builder` means no agent runs. + - The pre-screenshot gate asserts the `spawnedByArchitect` values as well as builder + presence. + - The null fold, which no spawn can produce, is unit-tested. + - There are no hand-written database rows and no faked data. If spawning fails, verification + stops and the architect is told. +2. **Workspace-row data sources.** + - **Confirmed:** `WorkspaceProvider` re-renders on `onDidChangeDevTerminals` and on the + `codev-config-updated` and `architects-updated` envelopes (`workspace.ts:27–53`), and the + worktree config is async. + - **Change:** the Cockpit resolves the config in its async root `getChildren`, uncached, and + subscribes to the same three signals. Tests cover each signal, and the *Stop Dev* swap after a + dev starts from a builder menu. +3. **Main vs sibling architect `contextValue`.** + - **Confirmed:** `AreaGroupTreeItem` sets a flat `group-builder`. + - **Change:** a scoped (Cockpit) builder gives `cockpit-architect-main` / `-sibling`, while the + Agents view keeps `group-builder`. *Remove Architect* targets the sibling value only, and the + parity test fails if its `when` matches main. +4. **Re-exports.** + - **Change:** `builders.ts` keeps exporting every moved symbol, so the existing tests' + imports need no edit. + +Minor points, both accepted: + +- **Image abort.** The adapter takes `image(path, signal?)`. The VS Code adapter ignores a reply + whose request was aborted, and a test covers it. +- **Request count.** Phase 4 measures it on the isolated Tower's request log, comparing the Cockpit + alone with the source views alone. The `getWorktreeConfig` per workspace-row render, the same call + the Workspace view makes, is accounted for. From 0d109a4e799add06c4d9078b1602a2f546cfaaaa Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:16:46 -0800 Subject: [PATCH 021/140] chore(porch): 1963 plan-approval gate-requested --- .../status.yaml | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 4ed6967da..c4d24b7c3 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -11,23 +11,13 @@ gates: approved_at: '2026-11-24T05:59:40.990Z' plan-approval: status: pending + requested_at: '2026-11-24T06:16:46.617Z' pr: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true -history: - - iteration: 1 - build_output: '' - reviews: - - model: codex - verdict: REQUEST_CHANGES - file: >- - /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-codex.txt - - model: claude - verdict: COMMENT - file: >- - /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-iter1-claude.txt +iteration: 1 +build_complete: false +history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:11:36.225Z' +updated_at: '2026-11-24T06:16:46.617Z' From d9fc55d5cfa500ba08079e59d2c56439c3090f04 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:17:02 -0800 Subject: [PATCH 022/140] [Spec 1963] Thread: plan consultation, plan-approval --- codev/state/spir-1963_thread.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index b08a2b628..d9158b09b 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -91,3 +91,21 @@ Verification harness: isolated Tower (non-default port, own CODEV_AGENT_FARM_DIR with isolated data/extension dirs + fixture repos — never :4100 or the owner's /ide/. Finding while planning: builder rows show no held/queued today, so those counts are Cockpit-only (an `attentionCounts` option) to keep Agents byte-for-byte. + +## 2026-11-24 — Plan consultation → plan-approval + +Iter 1: Codex REQUEST_CHANGES, Claude COMMENT. Iter 2: both COMMENT. All points accepted (rebuttals +`1963-plan-iter{1,2}-rebuttals.md`). Things the reviews caught that the code confirmed: +- `requestPreservingBody` reads text → decision images need a binary request path. +- `/api/overview` lists only builders with a LIVE builder terminal, and `spawnedByArchitect` comes + only from global.db's `builders` row → the harness spawns fixture builders for real + (`afx spawn --task`, `CODEV_ARCHITECT_NAME`, plain-shell `shell.builder`) against an isolated + Tower; gate asserts attribution before screenshots. +- `removeArchitect` falls back to the display label (`WEB (0)`); Cockpit architect rows need + main/sibling context values. +- Hidden retained webviews still report `visibilityState === 'visible'` → host relays panel + visibility into `useDecisions`' `isActive`. +- Existing webviews use `style-src 'unsafe-inline'`; BuilderCard needs it. +- Windows path cases + windows.yml dispatch for the containment code. + +At plan-approval. Owner pre-approved the plan; waiting on the architect's check and go. From c1030da165ffb817d99f9912603539c0eb8c5b67 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:22:58 -0800 Subject: [PATCH 023/140] [Spec 1963] Plan: harness reaches only the isolated Tower (no Tower-contacting CLI), pre-flight and tripwire --- .../1963-vscode-alternative-layout-seco.md | 187 +++++++++++++----- 1 file changed, 137 insertions(+), 50 deletions(-) diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index c5faa028c..15a64597d 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -448,6 +448,12 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect - Approve Gate inline; - every workspace-row action; - Remove Architect. + + The actions that shell out to the CLI (*Spawn Builder* → `afx spawn`, *Approve Gate* → + `porch approve`) are verified through the harness's recording stubs. The check is that the + extension invoked the right command line, in the right cwd, from the Cockpit row, the same + as from the Agents and Workspace rows. A real CLI run would reach `:4100`. Every other action + runs for real against the isolated Tower. - [ ] Another workspace's architect or builder row opens that workspace's window. - [ ] **Request count** (spec scenario 21). The isolated Tower's request log is compared for two cases: @@ -883,59 +889,140 @@ The command stays in the palette everywhere and explains itself where it does no ## Verification harness (Phases 4, 5, 6, 7, 8) -The spec requires that verification never touches the owner's live IDE or Tower. Each rendered -checkpoint runs, and then stops, this harness: - -- **Isolated Tower:** the branch's built CLI starts a Tower on a non-default port (for example - `4199`) with `CODEV_AGENT_FARM_DIR` pointing at a fresh directory under the session scratchpad. - It has its own `global.db`, key and registry. -- **Isolated VS Code:** `code serve-web` on its own port, with its own `--server-data-dir`, - `--user-data-dir` and `--extensions-dir` under the scratchpad. The branch's vsix is installed - there, and the setting `codev.towerPort` is set to the isolated Tower's port. -- **Fixture workspaces:** two or more small git repos under the scratchpad, registered only with - the isolated Tower. - - Each fixture's `.codev/config.json` sets `shell.architect` and `shell.builder` to a plain - shell. So activating a workspace, or adding an architect, starts a shell session, never an AI - agent. - - **What makes a builder appear.** `/api/overview` lists a `.builders/` worktree only when: - - Tower's terminal registry holds a live builder session for its role id - (`activeBuilderRoleIds`). Directories alone render zero builders; - - its `spawnedByArchitect` is read from the isolated `global.db` `builders` row - (`spawned_by_architect`). `discoverBuilders` itself always emits `null`, so a builder with no - row folds into `main`. - - **So fixture builders are spawned for real by the branch's CLI** (`afx spawn --task "…"`, which - needs no GitHub issue): - - it runs with `cwd` in a fixture repo, against the isolated Tower; - - it sets `CODEV_ARCHITECT_NAME=` per spawn, the variable Tower injects into - architect terminals and `spawn.ts` records as `spawned_by_architect`; - - with the fixture's `shell.builder` set to a plain shell, this creates the worktree, the - `builders` row with its attribution, and a live builder terminal, and never starts an agent; - - this gives N=0, N=1 and N>1 builders under `main` and under a second architect, across two - workspaces; - - blocked-gate and waiting states come from the fixture builders' porch state, which is - synthetic test data in scratch repos, never a real project's; - - the null-attribution fold, which no spawn can produce, is covered by unit tests rather than - screenshots. - - **Validated before any screenshot.** The first checkpoint asserts that the isolated Tower's - `/api/overview` for each fixture returns the expected builders, **with their expected - `spawnedByArchitect` values**, and the expected architects. - - If spawning does not produce them, verification stops and the architect is told. - - It does not fall back to faked data, nor to hand-written database rows. - - **Driving the harness.** It goes through Tower's HTTP API (activation, terminals, - add-architect), using the isolated key. Where the CLI is needed (a second architect, or creating - the decisions file as `afx decisions init` does), the branch's built CLI runs with `cwd` in a - fixture repo and the isolated port and `CODEV_AGENT_FARM_DIR`. It never runs from this - worktree or against :4100. -- **Driver:** Python/Node Playwright, headless Chromium, with screenshots saved to the scratchpad - and attached to the PR. +The spec requires that verification never touches the owner's live IDE or Tower. Every step that +creates state is listed below with **how it reaches the isolated Tower**, as checked against the +code. Nothing here relies on a default port. + +### Why not `afx spawn` (or any Tower-contacting CLI command) + +The CLI has no way to target a non-default Tower for spawning: + +- `spawn.ts:110` and `spawn-worktree.ts:738` call `getTowerClient()` with no port; +- the CLI client falls back to `DEFAULT_TOWER_PORT`, a literal `4100` (`packages/sdk/src/constants.ts`); +- there is no env override (`CODEV_TOWER_PORT` is read only by the lifecycle reporter), and + `afx spawn` has no `--port`. + +`getTowerClient(port)` does cache a non-default client, so an in-process driver could pre-seed it. +That still leaks: + +- spawn shells out to `porch init` (`spawn-worktree.ts:490`); +- porch's CLI dispatcher then posts `refreshOverview` through `new TowerClient()`, which has no port + and so goes to `:4100` (`commands/porch/index.ts:1505`, `init` is in `MUTATING_COMMANDS`); +- and the `porch` it runs is whatever is first on `PATH`. + +The same default-port `getTowerClient()` / `new TowerClient()` is used by +`workspace-add-architect.ts:51`, `start.ts:31` and `notifications.ts:82`. So **the harness runs no +`afx` / `porch` CLI command that talks to Tower.** It uses only: + +- explicit HTTP calls to the isolated port; +- the product's own in-process state writers; +- one file-only CLI command. + +This needs no product change. + +### Isolated Tower + +Started directly, the way the isolation e2e test does (`bugfix-1515-tower-isolation.e2e.test.ts:87`): + +``` +node packages/codev/dist/agent-farm/servers/tower-server.js -p $PORT +``` + +It runs with this environment: + +- `CODEV_AGENT_FARM_DIR=/af`: its own `global.db`, `local-key` (`core/src/auth.ts:6`) and + registry; +- `SHELLPER_SOCKET_DIR=/run`: the default is the owner's `~/.codev/run` + (`tower-server.ts:599`), so it must be overridden. + +It is not started with `afx tower start`, because `start.ts` checks through the default-port client. + +### Fixtures, and how each is created + +| What | How | Reaches the isolated Tower by | +|---|---|---| +| Workspace activation (starts `main`) | `POST http://127.0.0.1:$PORT/api/workspaces//activate` (`tower-routes.ts:955`) with the isolated key | explicit port | +| A second architect | `POST …:$PORT/api/workspaces//architects` `{ name }` (`tower-routes.ts:791`), not `afx workspace add-architect` | explicit port | +| A builder's worktree | `git worktree add` in the fixture repo | no Tower contact | +| A builder's porch state (phase, a pending gate for the blocked state) | porch's in-process `createInitialState` / `writeState` (`commands/porch/state.ts:229,159`), not the porch CLI, whose dispatcher posts to `:4100` | no Tower contact | +| A builder's `builders` row, with `spawned_by_architect` | the product's in-process `upsertBuilder` (`agent-farm/state.ts:193`), the call `spawn` itself makes, in a driver process whose `CODEV_AGENT_FARM_DIR` is the isolated dir (`db/index.ts` resolves `global.db` from it at import). No hand-written SQL | isolated `global.db` | +| A builder's live terminal | `POST …:$PORT/api/terminals` `{ type: 'builder', roleId: 'builder-', workspacePath, cwd, command }` with a plain shell command (`tower-routes.ts:1032-1093`, which registers `entry.builders`) | explicit port | +| A decisions file | `node packages/codev/bin/afx.js decisions init`, with `cwd` in the fixture. `decisions.ts` imports only fs, path, config and the template, and the decisions e2e does the same (`decisions-tab.test.ts:390`) | no Tower contact | + +Each fixture's `.codev/config.json` sets `shell.architect` and `shell.builder` to a plain shell, so +every session is a shell, never an agent. + +This yields N=0, N=1 and N>1 builders under `main` and under a second architect, across two +workspaces, plus a blocked and a waiting builder. The null-attribution fold, which only a legacy row +can produce, is unit-tested. + +### Isolated VS Code + +`code serve-web` runs on its own port, with `--server-data-dir`, `--user-data-dir` and +`--extensions-dir` all under the scratchpad, and the branch's vsix installed there. + +- **Settings** in that profile: + - `codev.towerPort = $PORT`; + - `codev.autoStartTower = false`. Auto-start runs `afx tower start`, which would target `:4100`. +- **Environment** of the serve-web process: + - `CODEV_TOWER_KEY=`. Without it the extension reads `~/.agent-farm/local-key` + (`sdk/src/node/local-key.ts:20,34`); + - `PATH` prefixed with a stub directory holding **recording stubs** for `afx`, `porch` and + `codev`. The extension shells out to these via `PATH` (`resolveSpawnable` in + `cli-process.ts`), for `afx spawn` (`commands/spawn.ts:46`), `porch approve` + (`commands/approve.ts:357`), `afx cleanup` (`commands/cleanup.ts:48`), Tower auto-start, and + preflight's `codev --version` (`preflight/preflight-core.ts:50`). + - Each stub appends its argv and cwd to a log and exits 0. `codev --version` prints the branch's + version, so preflight passes. +- **Everything else the extension does** goes through `ConnectionManager`'s client, which follows + `codev.towerPort`: overview, fleet, terminals, dev, architects, decisions and activation. + +So in the harness, *Spawn Builder*, *Approve Gate* and *Cleanup* are verified as "the extension +invoked the CLI with the right arguments and cwd", from the stub log. The CLI is not changed by this +project. + +### Pre-flight (run before anything creates state; any failure stops the run) + +1. `$PORT` is set, numeric and **not 4100**, and nothing is listening on it before the start. +2. `CODEV_AGENT_FARM_DIR` and `SHELLPER_SOCKET_DIR` are set, resolve under the session scratchpad, + and are not `~/.agent-farm` or `~/.codev/run`. +3. The driver imports `AGENT_FARM_DIR` from the branch's built `@cluesmith/codev-core/constants` + and asserts that it equals the isolated dir. This proves the in-process `upsertBuilder` and + porch writes land there. +4. After the start, the listener on `$PORT` (`lsof`) is the PID the harness spawned, and + `GET http://127.0.0.1:$PORT/api/version` answers with the isolated key. +5. The serve-web profile's `settings.json` holds `codev.towerPort = $PORT` and + `codev.autoStartTower = false`, and in the serve-web environment `afx`, `porch` and `codev` + resolve to the stubs. +6. Before any screenshot, the isolated Tower's `/api/overview` for each fixture returns the + expected builders, **with their expected `spawnedByArchitect` values**, and the expected + architects. If not, verification stops and the architect is told. There is no fallback to faked + data. + +### During and after + +- **Tripwire.** Throughout the run, the harness samples established TCP connections to `:4100` + (`lsof -nP -iTCP:4100 -sTCP:ESTABLISHED`). It fails the run if any belongs to its own process + tree: the driver, the isolated Tower and its shellpers, serve-web and its extension host. The + owner's `:4100` is never probed or requested. +- **"Tower unreachable" scenario.** It stops the *harness's* Tower by the PID the harness started. + Auto-start is off and stubbed, so nothing restarts a Tower. +- **Teardown.** It kills only: + - the isolated Tower PID; + - the shellper PIDs that the isolated Tower lists at `GET :$PORT/api/terminals`, whose sockets + are in the isolated socket dir; + - the serve-web PID. + + Nothing is killed by name pattern. The scratch dirs are removed afterwards. +- **Driver.** Python/Node Playwright drives headless Chromium. Screenshots go to the scratchpad and + are attached to the PR. - **Never `playwright install` on this machine.** It hangs at extraction and wedges the shared browser cache. - Use the Chromium already in the Playwright cache. If none is usable, install it by hand with `curl -L` + `unzip` + the `INSTALLATION_COMPLETE` marker, and ask first. -The harness is one extra Tower process and one VS Code web server, with no builders. The architect -is told before its first start. Anything that would touch port 4100, `~/.agent-farm` or the owner's -`/ide/` is out of bounds. +The harness is one extra Tower process and one VS Code web server, with no agents. The architect is +told before its first start. ## Risks and Mitigation @@ -946,10 +1033,10 @@ is told before its first start. Anything that would touch port 4100, `~/.agent-f | The layout primitive closes or discards an editor | Low | High | The Phase 8 spike before any arrange code, with the add/reuse-only rule from the spec if it fails; the dirty/untitled/modified scenario rendered | | Moving components changes the dashboard | Medium | Medium | Wrappers keep `lib/api.ts`; the moved tests are unchanged in intent; the dashboard integration tests stay; a rendered before/after comparison | | A source-exported TSX package does not type-check under one host's config | Low | Medium | `jsx: react-jsx` added to the webview tsconfig; if a host still cannot consume it, the package gains a `tsdown` build like `codev-artifact-canvas`. That is a build-wiring change, not scope, and it is named in the PR | -| The harness accidentally touches the owner's Tower or IDE | Low | High | Non-default port, isolated `CODEV_AGENT_FARM_DIR` and VS Code data dirs, no `afx` against :4100; the architect is told before the first start | +| The harness accidentally touches the owner's Tower or IDE | Medium (several CLI paths default to `:4100`) | High | No Tower-contacting CLI commands. Every state-creating step names its route to the isolated port (harness table). Extension shell-outs are recording stubs, and auto-start is off. `CODEV_TOWER_KEY` is set, as are isolated state, socket and VS Code dirs. A pre-flight refuses 4100 and checks the listener PID, and a `:4100` connection tripwire runs throughout. The architect is told before the first start | | CSS moved out of `index.css` misses a rule, so the dashboard looks different | Medium | Low | A selector inventory before the move, and the rendered dashboard comparison | | `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 6, and build the vsix in the harness from Phase 4 onward | -| Fixture builders do not appear because Tower lists only builders with a live terminal | High if missed | Medium | Each fixture builder gets a real worktree plus a registered builder terminal, and `/api/overview` is asserted before any screenshot (harness section) | +| Fixture builders do not appear, or appear without attribution | High if missed | Medium | Each fixture builder gets a real worktree, porch state, a `builders` row through the product's `upsertBuilder`, and a registered builder terminal. `/api/overview` is asserted, attribution included, before any screenshot | | Path containment behaves differently on Windows (case, separators, UNC, junctions) | Medium | High | `realpath` + `path.relative` (no prefix compare), `path.win32` table tests, and the on-demand Windows workflow linked in the PR | ## Documentation Updates From 1e0378b1e8f5ca8224611ccd558f02c20ad7dc31 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:33:54 -0800 Subject: [PATCH 024/140] [Spec 1963] Plan: harness becomes Phase 1 with the layout spike; review fixes (config cache, db path, WorkView state, test deps) --- .../1963-vscode-alternative-layout-seco.md | 297 +++++++++++++----- .../1963-plan-harness-rebuttals.md | 96 ++++++ 2 files changed, 321 insertions(+), 72 deletions(-) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index 15a64597d..7a4c2fb3f 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -4,10 +4,15 @@ ## Executive Summary -This plan implements the approved spec in its three shippable increments, in eight phases. Each +This plan implements the approved spec in its three shippable increments, in nine phases. Each phase is one commit on `builder/spir-1963`, and all of them go into one PR. -1. **Button + hierarchy** (Phases 1–4). This uses spec approach **A1**: one tree view over the +0. **Verification harness and layout spike** (Phase 1). This is the isolated harness every rendered + checkpoint uses (section *Verification harness*), proven safe on an empty fixture. It also runs + the editor-layout spike the spec's Assumptions require, so its result is known before any + increment-1 code. If the spike shows that the arrangement needs an owner decision, the owner + gets it early. +1. **Button + hierarchy** (Phases 2–5). This uses spec approach **A1**: one tree view over the existing row-building code. Its single hierarchy is the owner's *"towers -> workspaces -> architects / decisions -> builders"*. Rows of this window's workspace act; rows of other workspaces navigate. @@ -16,27 +21,29 @@ phase is one commit on `builder/spir-1963`, and all of them go into one PR. - The architect-axis row building moves out of `BuildersProvider` into a reusable builder, scoped by workspace. The Agents view and the Cockpit both use it, so there is no second copy of row logic. -2. **Shared Work and Decisions** (Phases 5–7). This uses approach **B1**: a new workspace package, +2. **Shared Work and Decisions** (Phases 6–8). This uses approach **B1**: a new workspace package, `@cluesmith/codev-workspace-views` (`packages/workspace-views`). - The dashboard's `WorkView`, `DecisionsView`, `useDecisions` and their sub-components move there. They take their I/O from a host adapter and their colours from `--codev-wv-*` tokens. - The dashboard keeps thin wrappers with its fetch adapter. - The extension hosts two editor-area webview panels whose host side relays to Tower through `ConnectionManager`'s client. -3. ***Arrange Cockpit*** (Phase 8). This uses approaches **C1** (first show per window, plus the +3. ***Arrange Cockpit*** (Phase 9). This uses approaches **C1** (first show per window, plus the command and `codev.cockpit.autoArrange`) and **D1** (Work stacked over Decisions). It also adds - the one-time first-auto-arrange notice ruled at the gate. Before any arrange code is written, the - phase starts with the spike the spec's Assumptions require. + the one-time first-auto-arrange notice ruled at the gate. It builds on the Phase 1 spike result, + and writes no arrange code while a spike case is unresolved. -Rendered verification sits at the end of each increment: Phase 4, Phase 7 and Phase 8. It runs -against an isolated harness (described below), so the work can be cut after any increment with what -has shipped already verified. +Rendered verification sits at the end of each increment: Phase 5, Phase 8 and Phase 9. It also +runs at Phase 6 (the dashboard comparison) and Phase 7 (Decisions). It uses the isolated harness +built in Phase 1, so the work can be cut after any increment with what has shipped already +verified. ## Phases (Machine Readable) ```json { "phases": [ + {"id": "verification_harness", "title": "Isolated verification harness and editor-layout spike"}, {"id": "fleet_overviews", "title": "Fleet cache keeps every active workspace's overview"}, {"id": "architect_tree_builder", "title": "Reusable, workspace-scoped architect-axis row builder"}, {"id": "cockpit_hierarchy", "title": "Cockpit button and the Tower → workspaces → architects → builders tree"}, @@ -51,7 +58,92 @@ has shipped already verified. ## Phase Breakdown -### Phase 1: Fleet cache keeps every active workspace's overview +### Phase 1: Isolated verification harness and editor-layout spike + +**Dependencies**: None + +#### Objective + +Build, once, the isolated environment every rendered checkpoint runs in, and prove it cannot reach +the owner's Tower or IDE before it is used for anything. Then use it to run the editor-layout spike, +so the arrangement's feasibility is known before increment-1 code is written. + +#### Files to Create / Modify + +**New `apps/vscode/scripts/cockpit-harness/`.** It is dev-only: it is excluded from the vsix through +`.vscodeignore` and is not run in CI. It holds: + +- `harness.mjs`: start, seed, check and stop, per the *Verification harness* section; +- `preflight.mjs`; +- `tripwire.mjs`; +- `fixtures.mjs`, the fixture driver: in-process `upsertBuilder` and porch state, plus explicit-port + HTTP calls; +- `stubs/` holding `afx`, `porch` and `codev`; +- `README.md`. + +Scripts load the branch's built `packages/codev/dist`. They never use a globally installed CLI. + +**The spike is not committed.** It is a throwaway extension in the session scratchpad, loaded into +the harness's isolated VS Code. Its result is recorded in the thread, and later in the review, with +screenshots. It checks: + +- (a) `vscode.setEditorLayout` with `{ orientation: 0, groups: [{}, { groups: [{}, {}] }] }`, run + over three or more existing groups, merges the editors of the groups it removes into the remaining + groups. Dirty, untitled and modified editors survive with their content; +- (b) an editor-area terminal tab moves between groups without ending its session. The method is + `terminal.show()`, then `workbench.action.moveEditorToFirstGroup`, then a check that the PTY still + echoes; +- (c) a panel terminal moves into the editor area through `workbench.action.terminal.moveToEditor`, + with the session intact; +- (d) `WebviewPanel.reveal(viewColumn)` moves a retained panel to another group without reloading it + (a counter in the webview survives the move). + +**Outcomes:** + +- **(a) fails:** arrange only adds or reuses groups and never removes one. The spec already + provides this, so no decision is needed. +- **(b), (c) or (d) fails:** the spec does not provide a fallback, and every candidate fallback + changes ruled behaviour. Examples: leaving the architect where it is, or not honouring the + `terminalPosition` override. + - **The result goes to the architect at once, with the options**, and Phase 9 waits for the + owner's ruling. + - Phases 2–8 do not depend on it and continue. + +#### Deliverables + +- [ ] The harness scripts, stubs and README. +- [ ] The spike run, with its result recorded in the thread. +- [ ] Harness self-tests. + +#### Acceptance Criteria + +- [ ] On an empty fixture, `harness.mjs check` passes: + - every pre-flight gate; + - the isolated Tower is up on `$PORT`, owned by the harness PID; + - the isolated VS Code is serving the branch vsix; + - the stubs resolve. + + `harness.mjs stop` leaves no process of its own behind (checked by PID). +- [ ] **Each pre-flight gate is shown to refuse:** + - `PORT=4100`; + - an `AGENT_FARM_DIR` or socket dir outside the scratchpad; + - a mismatched db path (a `NODE_ENV=test` driver against a production-mode Tower); + - a listener PID that is not the harness's. + + Each refuses before any state is created. +- [ ] **The tripwire is shown to fire**, without touching `:4100`. Its port is a parameter, and the + self-test points it at a throwaway local listener the test opens, connects to it from a + harness child process, and expects a failure. +- [ ] The spike result is recorded, and the architect is told if (b), (c) or (d) failed. + +#### Test Plan + +- `harness.mjs selftest`: the refusals and the tripwire above. +- A seeded fixture (one workspace, one builder) appears in the isolated Tower's `/api/overview` + with its `spawnedByArchitect`. +- The spike, as above. + +### Phase 2: Fleet cache keeps every active workspace's overview **Dependencies**: None @@ -95,9 +187,9 @@ Unit tests with a fake client: - a stale (out-of-sequence) fan-out does not overwrite a newer overview; - the call count is unchanged. -### Phase 2: Reusable, workspace-scoped architect-axis row builder +### Phase 3: Reusable, workspace-scoped architect-axis row builder -**Dependencies**: None (Phase 1 is not needed; ordered here so the hierarchy phase has both) +**Dependencies**: None (Phase 2 is not needed; ordered here so the hierarchy phase has both) #### Objective @@ -159,8 +251,11 @@ Agents view: same rows, same ids, same behaviour. - [ ] `ArchitectTreeBuilder` with `act` and `navigate` modes and scoped ids. - [ ] `BuildersProvider` rebuilt on it, with no behaviour change. - [ ] A builder option, `attentionCounts`, which is off for the Agents view, appends *N held* and - *N queued* to builder-row descriptions. The counts come from the same `deriveAttention` - summary the Tower view uses. Builder rows show neither today, so the Agents view keeps its + *N queued* to builder-row descriptions. The counts come from `deriveAttention`: + - for this window's workspace, run over `overviewCache.getData()`, so they never lag that + workspace's own rows; + - for other workspaces, run over the fleet cache's retained overview, the summary the Tower + view uses. Builder rows show neither today, so the Agents view keeps its labels byte-for-byte and only the Cockpit turns the option on (the placement table's held and queued rows). @@ -195,15 +290,15 @@ Unit tests on `ArchitectTreeBuilder`: - a non-live recorded architect; - `getParent` chains for builder, idle-sibling header, folder and file rows. -### Phase 3: Cockpit button and the Tower → workspaces → architects → builders tree +### Phase 4: Cockpit button and the Tower → workspaces → architects → builders tree -**Dependencies**: Phase 1, Phase 2 +**Dependencies**: Phase 2, Phase 3 #### Objective Ship the new activity-bar button and its single hierarchy, with this window's builder rows behaving as they do in Agents: click, accordion, reveal, cycle selection and activity hook. This is -the first user-visible slice. Context-menu actions arrive in Phase 4. +the first user-visible slice. Context-menu actions arrive in Phase 5. #### Files to Create / Modify @@ -228,7 +323,7 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. `TowerProvider.workspaceItem`, with a `hasChildren` option. `TowerProvider` keeps its exact output. - In the Cockpit, every active workspace is collapsible and has no click command; *Open* is - added in Phase 4. + added in Phase 5. - Dormant rows keep click-to-open. - Initial expansion: this window's workspace and any with non-empty attention start `Expanded`; the rest start `Collapsed`. @@ -244,7 +339,7 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. - **Attention on rows:** - architect rows get `describeWait` text and glyph from the workspace's `AttentionSummary.architects`; - - builder rows get their glyph, gate and held/queued (Phase 2); + - builder rows get their glyph, gate and held/queued (Phase 3); - the workspace row's description keeps `describeAttention`, which already covers unattributed held mail and escalation. - **Re-render:** on `overviewCache.onDidChange`, `towerCache.onDidChange` and @@ -332,9 +427,9 @@ the first user-visible slice. Context-menu actions arrive in Phase 4. `codev.buildersAutoCollapse` re-gates both accordions. - **`cockpit-icon.test.ts`:** same `d` attribute as `codev.svg`, wrapped in `rotate(90 400 400)`. -### Phase 4: Placement-table actions on the hierarchy, parity mapping, increment-1 verification +### Phase 5: Placement-table actions on the hierarchy, parity mapping, increment-1 verification -**Dependencies**: Phase 3 +**Dependencies**: Phase 4 #### Objective @@ -369,8 +464,17 @@ verification and docs. window. The data behind them follows the Workspace view's own sources: - **Worktree config.** It is async: `loadWorktreeConfig` awaits `client.getWorktreeConfig(...)`. - The Cockpit resolves it in its async `getChildren` for the Tower root, as `WorkspaceProvider` - does in its `getChildren`, and does not cache it across renders. + - The Cockpit re-renders far more often than the Workspace view does: on every fleet and overview + change, including the fleet's 20 s fallback poll. So it **holds the resolved config** instead of + fetching per render. + - It resolves the config once, in its async root `getChildren`, and drops it on: + - the `codev-config-updated` envelope, the signal that exists for exactly this; + - a connection-state change; + - a workspace change. + + The next render then fetches it again. + - A test asserts that N fleet and overview changes cause no `getWorktreeConfig` call, and that + one `codev-config-updated` causes exactly one. - **Re-render signals.** The Cockpit re-renders on the same signals `WorkspaceProvider` subscribes to: - `terminalManager.onDidChangeDevTerminals`, so *Start Dev* / *Stop Dev* stays honest across @@ -378,7 +482,7 @@ window. The data behind them follows the Workspace view's own sources: - the `codev-config-updated` SSE envelope, for `devUrls` and dev-command edits; - the `architects-updated` SSE envelope, for add and remove from the CLI. - These are in addition to the three Phase 3 signals. They need no new connection: the envelopes + These are in addition to the three Phase 4 signals. They need no new connection: the envelopes come from `connectionManager.onSSEEvent`. The values themselves: @@ -429,7 +533,7 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect #### Deliverables -- [ ] All placement-table entries for increment 1 (the Decisions entry is Phase 6). +- [ ] All placement-table entries for increment 1 (the Decisions entry is Phase 7). - [ ] The `removeArchitect` argument resolution for Cockpit architect rows, with a unit test. - [ ] The mapping oracle and the parity test. - [ ] Rendered verification of increment 1 and docs. @@ -443,6 +547,15 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect entry's `viewItem`; - *Remove Architect*'s `when` matches `cockpit-architect-main`; - an existing source entry differs from its snapshot. +- [ ] **Each relocated command handles a Cockpit tree element as its argument**, because VS Code + passes the clicked element to every menu entry. A unit test invokes each handler with the + Cockpit node its entry is attached to and asserts it acts on that node's target: + - *Remove Architect* resolves the name from the Cockpit row, not from `arg.label`; + - *Open Dev URL…* falls through to its QuickPick; + - *Spawn Builder*'s `extractIssueId` yields no id from a workspace node; + - *Add Architect*, *Start Dev* and *Stop Dev* ignore the argument. + + A future handler change then fails the test instead of regressing silently. - [ ] From the Cockpit, in the harness, these work on this window's workspace: - every builder context action; - Approve Gate inline; @@ -460,10 +573,11 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect - the Cockpit alone visible; - the Workspace, Agents and Tower views alone visible. - They match: the overview, the fleet fan-out, and one `getWorktreeConfig` per workspace-row - render, the same call the Workspace view makes per render. With both sets visible at once, the - only addition is that second view's own `getWorktreeConfig`. No poll, SSE stream or route is - added. + Each case is measured over the same idle window plus one scripted burst: a builder state + change and one `codev-config-updated`. They match: the overview, the fleet fan-out, and + `getWorktreeConfig` only on load and on `codev-config-updated`, never per fleet tick. With + both sets visible at once, the only addition is the Workspace view's own `getWorktreeConfig` + on its own renders. No poll, SSE stream or route is added. - [ ] **Rendered** (see the harness below), with screenshots: - the button under Codev; - the hierarchy with N=0, N=1 and N>1 builders and two or more workspaces; @@ -487,9 +601,9 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect - Rendered: spec scenarios 11, 12 (hierarchy part) and 19 (worktree and no-workspace windows; Cockpit-only freshness). -### Phase 5: Shared Work/Decisions package; dashboard moved onto it unchanged +### Phase 6: Shared Work/Decisions package; dashboard moved onto it unchanged -**Dependencies**: None (independent of Phases 1–4; ordered for the increment boundary) +**Dependencies**: None (independent of Phases 2–5; ordered for the increment boundary) #### Objective @@ -509,6 +623,15 @@ npm-published):** `check-types` scripts. - **Dependencies:** `@cluesmith/codev-types`, `@cluesmith/codev-sdk` (the environment-agnostic `builder-helpers` only), `@cluesmith/codev-artifact-canvas`, and React as a peer dependency. +- **Its own devDependencies**, declared here rather than borrowed from `apps/web` under pnpm's strict + layout, at the versions `apps/web` uses: + - `react` and `react-dom`; + - `@types/react` and `@types/react-dom`; + - `@testing-library/react` and `@testing-library/jest-dom`; + - `jsdom`, `vitest` and `typescript`. + + `pnpm-lock.yaml` is updated in the same commit. The package's `test` runs in CI's existing + workspace test step, and Phase 6 checks that it does. - **`src/host.ts`:** the `WorkspaceViewsHost` adapter. Its members are optional unless stated: - `overview` (required): a subscribe/refresh source; - `decisions`: `read()`, `rule(req)`, `image(path, signal?)`. @@ -526,8 +649,22 @@ npm-published):** A control renders only when its action is provided. - **Moved here from `apps/web/src`:** - - `components/WorkView.tsx`, keeping its core sections. The dashboard-only pieces become optional - slots: `FileTree`, `OpenFilesShellsSection` and `TipBanner`; + - `components/WorkView.tsx`, keeping its core sections. + - **Its `state: DashboardState | null` prop is removed from the shared surface.** `state` feeds + three things today: the loading gate, `architectCount` from `state.architects`, and + `findBuilderTab`'s builder list. In the package: + - the loading gate keys on the overview; + - `architectCount` comes from `OverviewData.architects`, as the spec's Assumptions rule; + - builder opening goes through the host's `openBuilder(id)`. The dashboard wrapper maps it + to `findBuilderTab(builder, state.builders)` and `onSelectTab`, as today. + + The dashboard wrapper keeps reading `/api/state` for its own pieces. + - The dashboard-only pieces become optional slots: the **whole file panel**, + `OpenFilesShellsSection` and `TipBanner`. + - The file panel slot is the `work-file-panel` wrapper (toggle, label, search input and + `FileTree`), together with the root's `file-panel-open` class, not `FileTree` alone. With + the slot absent nothing of it renders, so there is no empty strip and no dead search box. + - A test asserts this in the VS Code host; - `components/DecisionsView.tsx`, `hooks/useDecisions.ts`; - `components/BuilderCard.tsx`, `NeedsAttentionList.tsx`, `BacklogList.tsx`, `RecentlyClosedList.tsx`; @@ -588,15 +725,15 @@ npm-published):** - `rule()` refusals render the server message. - Dashboard render comparison in the harness. -### Phase 6: Decisions panel in VS Code, its host bridge, and the hierarchy's Decisions entry +### Phase 7: Decisions panel in VS Code, its host bridge, and the hierarchy's Decisions entry -**Dependencies**: Phase 3 (for the Decisions entry), Phase 5 +**Dependencies**: Phase 4 (for the Decisions entry), Phase 6 #### Objective Let the owner rule on decisions without leaving VS Code. The panel is the shared `DecisionsView` in an editor-area webview, with every Tower call made by the host. This phase also builds the -webview infrastructure that Phase 7 reuses. +webview infrastructure that Phase 8 reuses. #### Files to Create / Modify @@ -666,7 +803,13 @@ stay green. webview entries are `.ts` (their JSX lives in canvas's prebuilt `dist`), and esbuild otherwise reads the nearest `tsconfig.json`, which sets no `jsx`. These are the first TSX sources compiled under `apps/vscode`. - - A bundle smoke test loads the built `dist/webview/decisions.js` in jsdom and asserts it mounts. + - A bundle smoke test asserts the bundle mounts in jsdom. It does not depend on a prior `dist`: + - CI's `apps/vscode` step runs `check-types` then `test:unit`, and no esbuild run; + - so the test builds the entry itself in `beforeAll`, through esbuild's API into a temp dir, + using the same options object `esbuild.js` uses. That object is exported from a small + `esbuild.webview.mjs` both import. + + It therefore runs under `pnpm test:unit`, locally and in CI, on a clean tree. - `tsconfig.webview.json`: adds `jsx: react-jsx` and the new `src/workspace-views/webview` directory; - `apps/vscode/tsconfig.json`: adds `src/workspace-views/webview` to `exclude`, alongside the two @@ -693,7 +836,7 @@ stay green. - [ ] Spec scenarios 6 (host message contract), 8 (decisions bridge), 15, 16 and 22 pass. The rendered ones (15, 16) are run in the harness at this phase's end, with screenshots, because - Phase 7's verification focuses on Work. + Phase 8's verification focuses on Work. - [ ] The Tower key never appears in any message sent to the webview (asserted on the message log in a host test). - [ ] Type-check (host and webview configs), lint, unit tests and the SDK boundary tests pass. @@ -734,9 +877,9 @@ stay green. - the Decisions entry from the hierarchy; - spec scenario 18 for Decisions: light, dark and high-contrast themes, and a live switch. -### Phase 7: Work panel in VS Code, increment-2 verification +### Phase 8: Work panel in VS Code, increment-2 verification -**Dependencies**: Phase 6 (shared webview infrastructure) +**Dependencies**: Phase 7 (shared webview infrastructure) #### Objective @@ -792,9 +935,9 @@ every kept affordance mapped to a VS Code action and every dropped one absent. artifact path; an external URL scheme refused; dropped slots absent. - **Rendered:** as above. -### Phase 8: Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification +### Phase 9: Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification -**Dependencies**: Phase 3, Phase 6, Phase 7 +**Dependencies**: Phase 1 (the spike result), Phase 4, Phase 7, Phase 8 #### Objective @@ -803,19 +946,9 @@ first show per window session, and on demand. It never closes or discards a user #### Files to Create / Modify -**Spike first, in the harness, recorded in the thread and the review.** It confirms: - -- (a) `vscode.setEditorLayout` with - `{ orientation: 0, groups: [{}, { groups: [{}, {}] }] }` merges editors from groups it removes - into remaining groups. Dirty, untitled and modified editors survive, with their content; -- (b) an editor-area terminal tab moves between groups without ending its session, using - `terminal.show()` then `workbench.action.moveEditorToFirstGroup`; -- (c) a panel terminal moves into the editor area through `workbench.action.terminal.moveToEditor`; -- (d) `WebviewPanel.reveal(viewColumn)` moves a retained panel without reloading it. - -If (a) does not hold, arrange only **adds or reuses** groups and never removes one, as the spec -already allows. If (b) or (c) does not hold, the plan stops and the architect is told before -another approach is chosen. +**The Phase 1 spike result decides the mechanics.** If (a) failed, arrange only adds or reuses +groups. If (b), (c) or (d) failed, this phase starts only after the owner's ruling on the options +the architect was given. **New `apps/vscode/src/cockpit/arrange.ts`, `arrangeCockpit()`:** @@ -887,7 +1020,7 @@ The command stays in the palette everywhere and explains itself where it does no - idempotent. - **Rendered:** as above. -## Verification harness (Phases 4, 5, 6, 7, 8) +## Verification harness (Phases 1, 5, 6, 7, 8, 9) The spec requires that verification never touches the owner's live IDE or Tower. Every step that creates state is listed below with **how it reaches the isolated Tower**, as checked against the @@ -958,8 +1091,15 @@ can produce, is unit-tested. ### Isolated VS Code -`code serve-web` runs on its own port, with `--server-data-dir`, `--user-data-dir` and -`--extensions-dir` all under the scratchpad, and the branch's vsix installed there. +`code serve-web` (`/usr/local/bin/code` on this machine) runs on its own port, with +`--server-data-dir`, `--user-data-dir` and `--extensions-dir` all under the scratchpad, and the +branch's vsix installed there. + +- **Fallback:** if `serve-web` cannot run, the harness launches the IDE server binary that Tower's + IDE support uses (`ide-server.ts`). It is launched **directly**, with the same flags + `ide-server.ts` passes (`--host 127.0.0.1`, `--port`, `--server-base-path`, `--extensions-dir`), + all pointed at scratch dirs and its own port. +- It never goes through any Tower's `/api/ide`, and never through the owner's `/ide/`. - **Settings** in that profile: - `codev.towerPort = $PORT`; @@ -986,9 +1126,19 @@ project. 1. `$PORT` is set, numeric and **not 4100**, and nothing is listening on it before the start. 2. `CODEV_AGENT_FARM_DIR` and `SHELLPER_SOCKET_DIR` are set, resolve under the session scratchpad, and are not `~/.agent-farm` or `~/.codev/run`. -3. The driver imports `AGENT_FARM_DIR` from the branch's built `@cluesmith/codev-core/constants` - and asserts that it equals the isolated dir. This proves the in-process `upsertBuilder` and - porch writes land there. +3. **The driver and the Tower agree on the database file.** + - `getGlobalDbPath()` resolves under `AGENT_FARM_DIR`, but switches to `AF_TEST_DB`, or + `test.db`, when `NODE_ENV=test` (`db/index.ts:123`). + - So the harness pins `NODE_ENV` and `AF_TEST_DB` to the same values for the Tower and for the + driver. It runs neither under vitest. + - The driver imports `AGENT_FARM_DIR` and `getGlobalDbPath` from the branch's built + `packages/codev/dist`, and asserts two things: + - `AGENT_FARM_DIR` equals the isolated dir; + - `getGlobalDbPath()` equals the file the isolated Tower opened. The Tower logs its dir when + it claims ownership (`tower-server.ts:578`), and the harness checks `lsof -p ` + for the `.db` path. + + This proves the in-process `upsertBuilder` writes land where the isolated Tower reads. 4. After the start, the listener on `$PORT` (`lsof`) is the PID the harness spawned, and `GET http://127.0.0.1:$PORT/api/version` answers with the isolated key. 5. The serve-web profile's `settings.json` holds `codev.towerPort = $PORT` and @@ -1003,8 +1153,10 @@ project. - **Tripwire.** Throughout the run, the harness samples established TCP connections to `:4100` (`lsof -nP -iTCP:4100 -sTCP:ESTABLISHED`). It fails the run if any belongs to its own process - tree: the driver, the isolated Tower and its shellpers, serve-web and its extension host. The - owner's `:4100` is never probed or requested. + tree: the driver, the isolated Tower and its shellpers, serve-web and its extension host. + - The owner's `:4100` is never probed or requested. + - The watched port is a parameter, so the Phase 1 self-test proves the tripwire fires by aiming it + at a throwaway listener, not at `:4100`. - **"Tower unreachable" scenario.** It stops the *harness's* Tower by the PID the harness started. Auto-start is off and stubbed, so nothing restarts a Tower. - **Teardown.** It kills only: @@ -1028,26 +1180,27 @@ told before its first start. | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| -| The row-builder extraction (Phase 2) changes an Agents id or behaviour | Medium | High | An id-equivalence snapshot taken from the pre-refactor provider in the same commit, plus every existing Agents test unmodified | +| The row-builder extraction (Phase 3) changes an Agents id or behaviour | Medium | High | An id-equivalence snapshot taken from the pre-refactor provider in the same commit, plus every existing Agents test unmodified | | Generalised wiring regresses accordion, reveal or cycle in Agents | Medium | High | Per-view hosts with the Agents path unchanged; existing behaviour tests plus new per-view tests; rendered check of both views | -| The layout primitive closes or discards an editor | Low | High | The Phase 8 spike before any arrange code, with the add/reuse-only rule from the spec if it fails; the dirty/untitled/modified scenario rendered | +| The layout primitive closes or discards an editor | Low | High | The Phase 1 spike, run before any increment code. If it fails, the spec's add/reuse-only rule applies. The dirty/untitled/modified scenario is rendered | +| A terminal or retained-webview move fails in the spike (cases b–d) | Low | Medium | The spec gives no fallback, so the result goes to the architect from Phase 1 with the options. Phase 9 waits for the owner, and Phases 2–8 continue | | Moving components changes the dashboard | Medium | Medium | Wrappers keep `lib/api.ts`; the moved tests are unchanged in intent; the dashboard integration tests stay; a rendered before/after comparison | -| A source-exported TSX package does not type-check under one host's config | Low | Medium | `jsx: react-jsx` added to the webview tsconfig; if a host still cannot consume it, the package gains a `tsdown` build like `codev-artifact-canvas`. That is a build-wiring change, not scope, and it is named in the PR | +| A source-exported TSX package does not type-check under one host's config | Medium | Medium | `codev-artifact-canvas` is a *built* package (`tsdown` → `dist`), so the closer precedent is `apps/web`'s own source exports. The risk sits in `apps/web`'s `tsc -b`, which type-checks the package's `.tsx` under the dashboard's config, and in the extension's webview tsconfig (`jsx: react-jsx` added). Phase 6 runs both type-checks before moving anything. If a host still cannot consume the source, the package gains a `tsdown` build like canvas. That is a build-wiring change, not scope, and it is named in the PR | | The harness accidentally touches the owner's Tower or IDE | Medium (several CLI paths default to `:4100`) | High | No Tower-contacting CLI commands. Every state-creating step names its route to the isolated port (harness table). Extension shell-outs are recording stubs, and auto-start is off. `CODEV_TOWER_KEY` is set, as are isolated state, socket and VS Code dirs. A pre-flight refuses 4100 and checks the listener PID, and a `:4100` connection tripwire runs throughout. The architect is told before the first start | | CSS moved out of `index.css` misses a rule, so the dashboard looks different | Medium | Low | A selector inventory before the move, and the rendered dashboard comparison | -| `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 6, and build the vsix in the harness from Phase 4 onward | +| `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 7, and build the vsix in the harness from Phase 1 onward | | Fixture builders do not appear, or appear without attribution | High if missed | Medium | Each fixture builder gets a real worktree, porch state, a `builders` row through the product's `upsertBuilder`, and a registered builder terminal. `/api/overview` is asserted, attribution included, before any screenshot | | Path containment behaves differently on Windows (case, separators, UNC, junctions) | Medium | High | `realpath` + `path.relative` (no prefix compare), `path.win32` table tests, and the on-demand Windows workflow linked in the PR | ## Documentation Updates -- `apps/vscode/README.md`: the Cockpit button and hierarchy (Phase 4), the Work and Decisions panels - (Phase 7), *Arrange Cockpit* and `codev.cockpit.autoArrange` (Phase 8). +- `apps/vscode/README.md`: the Cockpit button and hierarchy (Phase 5), the Work and Decisions panels + (Phase 8), *Arrange Cockpit* and `codev.cockpit.autoArrange` (Phase 9). - `codev/resources/arch.md`, *VS Code Extension*: - the Cockpit container and act/navigate rule; - - `ArchitectTreeBuilder` and fleet-overview retention (Phase 4); - - the shared `@cluesmith/codev-workspace-views` package and host adapter (Phase 7); - - the arrange flow (Phase 8). + - `ArchitectTreeBuilder` and fleet-overview retention (Phase 5); + - the shared `@cluesmith/codev-workspace-views` package and host adapter (Phase 8); + - the arrange flow (Phase 9). Hot-tier files are not touched unless the review step routes a fact there. - `apps/vscode/CHANGELOG.md`: one entry per increment. diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md new file mode 100644 index 000000000..4fe01976b --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md @@ -0,0 +1,96 @@ +# Plan 1963: harness revision, review responses + +This round reviewed the harness rewrite, made at the architect's request because `afx spawn` +cannot target a non-default Tower. + +- Codex: REQUEST_CHANGES. +- Claude: COMMENT. + +I checked every point against the code. All are accepted except one, Codex 1, which is partly +accepted (below). + +## Codex (REQUEST_CHANGES) + +1. **The spike must be run before plan approval.** Partly accepted. + - **The spec's wording.** Spec §Assumptions says the layout behaviour is "to be confirmed in + the plan by a spike against a running instance", and gives a fallback only for (a). + - **Why it is not run now.** The architect has already checked this plan against the spec, + with the spike scheduled inside implementation. Running it now would also mean starting a + VS Code server before the harness exists, or the architect is told. + - **Change:** + - The spike moves out of the last phase into **Phase 1**, so it runs before any + increment-1 code. + - The outcomes are now explicit. If (a) fails, the spec's add/reuse-only rule applies. If + (b), (c) or (d) fails, the architect gets the result at once, with the options. Phase 9 + waits for the owner, and Phases 2–8 continue. + - **Offered to the architect:** running the spike before the plan is approved, if they want + the strict reading. +2. **The bundle smoke test needs `dist`, which CI never builds.** + - **Confirmed:** CI's `apps/vscode` step runs `check-types` and `test:unit` only + (`.github/workflows/test.yml:102-107`). + - **Change:** the smoke test builds its own entry in `beforeAll` through esbuild's API, into + a temp dir. It uses the options object `esbuild.js` uses, shared from `esbuild.webview.mjs`. +3. **The package's test devDependencies and lockfile.** + - **Change:** the package declares its own devDependencies, at `apps/web`'s versions: + - `react` and `react-dom`; + - `@types/react` and `@types/react-dom`; + - `@testing-library/react` and `@testing-library/jest-dom`; + - `jsdom`, `vitest` and `typescript`. + - `pnpm-lock.yaml` is updated in the same commit, and the package's tests are checked to run + in CI's workspace test step. + +## Claude (COMMENT) + +1. **An uncached `getWorktreeConfig` breaks request-count parity.** + - **Confirmed:** + - the fleet re-emits on every non-heartbeat SSE event and on a 20 s poll + (`tower-cache.ts:53-64`); + - the Cockpit re-renders on those, and the Workspace view does not; + - `loadWorktreeConfig` is a bare call. + - **Change:** + - The Cockpit holds the resolved config. It drops it on `codev-config-updated`, on a + connection-state change and on a workspace change. + - A test asserts that fleet ticks cause no fetch, and that one `codev-config-updated` causes + exactly one. + - The request-count criterion now measures an idle window plus a scripted burst. +2. **The driver and the Tower can disagree on the db file.** + - **Confirmed:** `getGlobalDbPath()` switches to `AF_TEST_DB` or `test.db` under + `NODE_ENV=test` (`db/index.ts:123-129`). + - **Change:** + - `NODE_ENV` and `AF_TEST_DB` are pinned the same for both, and the driver never runs under + vitest. + - Pre-flight 3 asserts that the driver's `getGlobalDbPath()` equals the `.db` file the + isolated Tower holds open (`lsof`). + - Phase 1's self-test proves the mismatch is refused. +3. **A fallback host for the isolated VS Code.** + - **Confirmed:** `code` is on PATH here. + - **Change:** + - `serve-web` stays the primary. + - The fallback is the IDE server binary, launched directly with `ide-server.ts`'s flags, + scratch dirs and its own port. It never goes through any Tower's `/api/ide`. +4. **WorkView's `DashboardState` coupling and the file-panel chrome.** + - **Confirmed:** + - `state` feeds the loading gate, `architectCount` and `findBuilderTab` + (`WorkView.tsx:15,35,41,53`); + - the file panel is a wrapper with its own toggle, label and search box (`:151-176`). + - **Change:** + - `state` leaves the shared prop surface. The loading gate keys on the overview, + `architectCount` comes from `OverviewData.architects`, and builder opening goes through + the host's `openBuilder`. + - The slot is the whole `work-file-panel` wrapper plus the root class, and a test covers it. +5. **Smaller points**, all accepted: + - **Held and queued counts** for this window's workspace come from + `deriveAttention(overviewCache.getData())`. Other workspaces use the fleet's retained + overview. + - **Relocated commands get a Cockpit tree node.** A unit test invokes each handler with the + Cockpit node its entry is attached to. + - **Package shape:** + - the risk row now says canvas is a built package; + - the risk sits in `apps/web`'s `tsc -b` and in the webview tsconfig; + - Phase 6 runs both type-checks before moving anything. + - **Phase sizing:** the harness is now **Phase 1** and has its own acceptance criteria: + - green on an empty fixture; + - every pre-flight gate shown to refuse; + - the tripwire shown to fire, aimed at a throwaway listener and never at `:4100`. + + The spike runs in it. The phases renumber from 1–8 to 1–9. From 43b79aef5c832c686f62e51a2fb69ce24b870258 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:34:14 -0800 Subject: [PATCH 025/140] [Spec 1963] Thread: harness revision --- codev/state/spir-1963_thread.md | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index d9158b09b..cf4f8d7bc 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -109,3 +109,48 @@ Iter 1: Codex REQUEST_CHANGES, Claude COMMENT. Iter 2: both COMMENT. All points - Windows path cases + windows.yml dispatch for the containment code. At plan-approval. Owner pre-approved the plan; waiting on the architect's check and go. + +## 2026-11-24 — Harness revision (architect: "no go yet") + +The architect caught that the plan's `afx spawn --task` "against the isolated Tower" could not have +worked, and the code confirms it: +- `spawn.ts:110` and `spawn-worktree.ts:738` use `getTowerClient()` with no port, so they go to the + literal 4100; +- there is no env override and no `--port`. + +Seeding a ported client in-process doesn't save it either: +- spawn shells out to `porch init` (`spawn-worktree.ts:490`); +- porch's dispatcher then posts `refreshOverview` via `new TowerClient()` to :4100 (`porch/index.ts:1505`). + +Other default-port paths: +- `afx tower start`, `workspace add-architect` and notifications; +- the extension, which shells out to `afx` and `porch` (spawn, approve, cleanup, auto-start); +- the extension reads `~/.agent-farm/local-key` unless `CODEV_TOWER_KEY` is set. + +**Chosen mechanism: harness-only, no product change.** The harness runs no Tower-contacting CLI +command: +- **Tower:** `tower-server.js -p $PORT` directly, with `CODEV_AGENT_FARM_DIR` and + `SHELLPER_SOCKET_DIR` (the default socket dir is the owner's `~/.codev/run`). +- **Fixtures:** + - activation and add-architect over HTTP to the explicit port; + - porch state and `upsertBuilder` in-process, with the db path pinned and checked; + - builder terminals via `POST :$PORT/api/terminals`; + - `afx decisions init`, which is file-only. +- **VS Code:** + - `CODEV_TOWER_KEY`, `codev.towerPort` and `autoStartTower=false`; + - recording PATH stubs for `afx`, `porch` and `codev`, so CLI-shelling actions are verified by + their recorded argv. +- **Safety checks:** a pre-flight that refuses 4100 and checks the listener PID, plus a :4100 + connection tripwire. + +**Re-review:** Codex REQUEST_CHANGES, Claude COMMENT. Changes taken: +- the harness became **Phase 1**, with self-tests proving every refusal and the tripwire; +- the layout spike moved into Phase 1 (Codex wanted it before plan approval; offered to the + architect). b/c/d failures go to the owner, and Phase 9 waits; +- the Cockpit holds the worktree config off `codev-config-updated`, so the request count matches; +- WorkView's `DashboardState` prop leaves the shared surface, and the file-panel slot is the whole + wrapper; +- the package declares its own test devDependencies and the lockfile changes with them; +- the smoke test builds its own bundle, since CI never builds `dist`. + +Phases are now 1–9. Rebuttals are in `1963-plan-harness-rebuttals.md`. From d8c38734f9885358ea3c0cd4fa9aad9c79a74b78 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:36:55 -0800 Subject: [PATCH 026/140] [Spec 1963] Plan: webview CSP default-src 'none' and scenario-22 tests --- .../1963-vscode-alternative-layout-seco.md | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index 7a4c2fb3f..efde9eb58 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -765,6 +765,9 @@ stay green. same calls; - an `http:`/`https:` allowlist for external opens. - `panel-template.ts`: the nonce CSP. + - `default-src 'none'` first, as both existing webviews have it (`panel-template.ts:22`, + `preview-template.ts:47`). Without it, leaving out `connect-src` restricts nothing: `fetch`, + XHR, WebSocket and EventSource fall back to `default-src`, so `'none'` is what blocks them; - `script-src 'nonce-…'`; - `style-src ${cspSource} 'unsafe-inline'`, the same as the existing webviews (`contextual-panel/panel-template.ts`, `markdown-preview/preview-template.ts`). @@ -773,8 +776,25 @@ stay green. those. - Scripts stay nonce-only. Inline *styles* do not run code; - `img-src ${cspSource} blob: http: https:`; - - no `connect-src`; + - no `connect-src`, so connections fall back to `default-src 'none'`; - `localResourceRoots` set to `dist`. + - **A static CSP test** (`panel-template.test.ts`) parses the generated policy and asserts: + - `default-src 'none'` is present; + - there is no `connect-src`; + - `script-src` is exactly the nonce, with no `'unsafe-inline'` or `'unsafe-eval'`; + - `img-src` and `style-src` are exactly as listed. +- **Spec scenario 22** (no webview contact with Tower) is tested at three levels: + - **Source:** an ESLint `no-restricted-globals` / `no-restricted-properties` rule bans `fetch`, + `XMLHttpRequest`, `WebSocket`, `EventSource` and `navigator.sendBeacon` in + `packages/workspace-views/src` and `apps/vscode/src/workspace-views/webview`. All I/O goes + through the host adapter. The dashboard's fetch adapter lives in `apps/web`, outside the rule. + - **State:** a unit test asserts that no message the host posts to a webview carries the Tower + key, a Tower URL or a port. It checks each message type's payload against the key and the + configured base URL. + - **Rendered:** in the harness, Playwright records every request from the webview frames. + - The run passes only if each request is a `vscode-resource`/`cspSource` asset, a `blob:` URL, + or a remote `http(s)` item image from the fixture's decisions file. + - No request may go to the isolated Tower's port, and none may carry the key header. - `decisions-panel.ts`, a single-instance `WebviewPanel` (`retainContextWhenHidden`): - **Polling has one owner:** the shared `useDecisions` hook, with its existing 2 s cadence. Each tick calls the host adapter's `read()`, and the host makes one Tower request per call. The host From 922aee1eb456844eb16f839df5e6229b4c47498b Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:40:04 -0800 Subject: [PATCH 027/140] [Spec 1963] Plan: confirmation-round fixes (issue-id parity, import boundary, CJS esbuild options, status tokens, viewsWelcome) --- .../1963-vscode-alternative-layout-seco.md | 61 ++++++++++++++++--- .../1963-plan-harness-rebuttals.md | 45 +++++++++++++- 2 files changed, 96 insertions(+), 10 deletions(-) diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index efde9eb58..8fc9848ea 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -431,6 +431,14 @@ the first user-visible slice. Context-menu actions arrive in Phase 5. **Dependencies**: Phase 4 +This phase is large, so it lands as **two commits** within the one phase: +- **5a:** menu entries, the two `WorkspaceProvider` extractions, context values and the + worktree-config hold; +- **5b:** the mapping oracle, the parity and handler-argument tests, rendered verification and + docs. + +The increment boundary is unchanged. + #### Objective Make every row of this window's workspace act exactly as it does in the source views, put every @@ -513,6 +521,14 @@ The values themselves: It also has one record per Workspace-view row click: Open Web Interface, Spawn Builder, New Shell, Start/Stop Dev, dev URLs and architect rows. + + It also has one record per `viewsWelcome` entry of the three views: `codev.agents` has three + today (`package.json:1168-1184`), including the no-workspace "Open Folder" / "Get Started" + links. A no-workspace window is one where the Cockpit appears, so each entry is recorded: + - mapped to the Tower root's state rows, which carry the same links; + - or `{ excluded: }`. + + Nothing disappears silently. - **New `apps/vscode/src/__tests__/cockpit-menu-parity.test.ts`.** - **Docs:** - the `apps/vscode/README.md` Cockpit section; @@ -583,7 +599,11 @@ is display text (`WEB (0)`), so the menu entry alone would call `removeArchitect - the hierarchy with N=0, N=1 and N>1 builders and two or more workspaces; - the Dormant group; - *Not connected* → reconnect; - - light and dark themes. + - light and dark themes; + - **active-file reveal with the workspace and architect rows collapsed.** The Cockpit's chain is + two levels deeper than Agents' (Tower → workspace → architect → builder → folder → file). + The fake-TreeView unit test cannot show that the real `TreeView.reveal` expands collapsed + ancestors. - [ ] Type-check, lint and unit tests pass. The existing `contributes-*` tests are unmodified apart from additions. @@ -630,8 +650,8 @@ npm-published):** - `@testing-library/react` and `@testing-library/jest-dom`; - `jsdom`, `vitest` and `typescript`. - `pnpm-lock.yaml` is updated in the same commit. The package's `test` runs in CI's existing - workspace test step, and Phase 6 checks that it does. + `pnpm-lock.yaml` is updated in the same commit. CI enumerates packages by hand + (`.github/workflows/test.yml:36-121`), so the package gets its own step under *Repo wiring*. - **`src/host.ts`:** the `WorkspaceViewsHost` adapter. Its members are optional unless stated: - `overview` (required): a subscribe/refresh source; - `decisions`: `read()`, `rule(req)`, `image(path, signal?)`. @@ -668,12 +688,32 @@ npm-published):** - `components/DecisionsView.tsx`, `hooks/useDecisions.ts`; - `components/BuilderCard.tsx`, `NeedsAttentionList.tsx`, `BacklogList.tsx`, `RecentlyClosedList.tsx`; - - the `issueRef` part of `lib/issueIds.ts`. `findBuilderTab` stays in the dashboard; it is - dashboard tab logic. + - the `issueRef` part of `lib/issueIds.ts`, with `CANONICAL_KEY_SOURCE`. `findBuilderTab` stays + in the dashboard; it is dashboard tab logic. +- **`packages/codev/src/__tests__/issue-id-parity.test.ts` is updated in the same commit:** + - line 21 reads `CANONICAL_KEY_SOURCE` from `apps/web/src/lib/issueIds.ts`, and `exportedSource` + throws when the constant is absent. It is repointed at the package's file; + - the hand-written-grammar guard on `apps/web/src/components/WorkView.tsx` (line 37) is + repointed at the package's `WorkView.tsx`, the real renderer. It is kept on the wrapper too. +- **New `src/__tests__/import-boundary.test.ts`**, copied from + `packages/artifact-canvas/src/__tests__/import-boundary.test.ts`. It scans every non-test + `.ts`/`.tsx` and forbids: + - `vscode`, `node:*` and bare `fs`; + - `fetch(`, `XMLHttpRequest`, `WebSocket`, `EventSource` and `sendBeacon`. + + This enforces the spec's boundary constraint and the no-direct-I/O rule in CI. + `DecisionsView` fetches through `lib/api.ts` today, so this is the rule the move most needs. - **`src/styles.css`:** the Work and Decisions CSS rules moved from `apps/web/src/index.css` (`.work-*`, `.backlog-*`, the builder-card, needs-attention, recently-closed and `.decisions-*` rules). They are rewritten against `--codev-wv-*` tokens, each with a default equal to today's - dashboard value. + dashboard value. **There are two token families:** + - chrome colours: background, foreground, border, muted, accent and link; + - **semantic status colours**, today's `--status-*` (50 uses in `index.css`; for example, + `NeedsAttentionList.test.tsx:300` checks `--status-implementing` and `--status-error`). These + become `--codev-wv-status-*`. + + Each host maps both families. The VS Code host maps status colours to `--vscode-charts-*` / + `--vscode-testing-*` equivalents, with each mapping listed in the token table. - **Tests:** the existing `apps/web` tests for these components, moved into the package, with their assertions unchanged in intent: - `BuilderCard.test.tsx`, `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`; @@ -709,7 +749,8 @@ npm-published):** - [ ] `apps/web` `test`, `check-types` and `build` pass. `App.decisions-tab` and `App.workview-scroll` pass unchanged. -- [ ] The package's `test` and `check-types` pass. +- [ ] The package's `test` and `check-types` pass, including `import-boundary.test.ts`. +- [ ] `packages/codev`'s suite passes, in particular `issue-id-parity.test.ts`. - [ ] **Rendered:** in the harness's Tower dashboard, Work and Decisions look and behave as before (spec scenario 20, compared with screenshots taken on `main` beforehand). A ruling round-trips. - [ ] A grep check in the package tests asserts that the moved component files exist only in @@ -827,7 +868,9 @@ stay green. - CI's `apps/vscode` step runs `check-types` then `test:unit`, and no esbuild run; - so the test builds the entry itself in `beforeAll`, through esbuild's API into a temp dir, using the same options object `esbuild.js` uses. That object is exported from a small - `esbuild.webview.mjs` both import. + `esbuild.webview.cjs`: `esbuild.js` is CommonJS and `apps/vscode` has no + `"type": "module"`, so `esbuild.js` can `require` it, and vitest imports it as CJS. It is added to + `.vscodeignore` next to `esbuild.js`. It therefore runs under `pnpm test:unit`, locally and in CI, on a clean tree. - `tsconfig.webview.json`: adds `jsx: react-jsx` and the new `src/workspace-views/webview` @@ -1208,7 +1251,7 @@ told before its first start. | A source-exported TSX package does not type-check under one host's config | Medium | Medium | `codev-artifact-canvas` is a *built* package (`tsdown` → `dist`), so the closer precedent is `apps/web`'s own source exports. The risk sits in `apps/web`'s `tsc -b`, which type-checks the package's `.tsx` under the dashboard's config, and in the extension's webview tsconfig (`jsx: react-jsx` added). Phase 6 runs both type-checks before moving anything. If a host still cannot consume the source, the package gains a `tsdown` build like canvas. That is a build-wiring change, not scope, and it is named in the PR | | The harness accidentally touches the owner's Tower or IDE | Medium (several CLI paths default to `:4100`) | High | No Tower-contacting CLI commands. Every state-creating step names its route to the isolated port (harness table). Extension shell-outs are recording stubs, and auto-start is off. `CODEV_TOWER_KEY` is set, as are isolated state, socket and VS Code dirs. A pre-flight refuses 4100 and checks the listener PID, and a `:4100` connection tripwire runs throughout. The architect is told before the first start | | CSS moved out of `index.css` misses a rule, so the dashboard looks different | Medium | Low | A selector inventory before the move, and the rendered dashboard comparison | -| `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 7, and build the vsix in the harness from Phase 1 onward | +| `prepublish-workspace-deps.test.ts` or the vsix packaging misses the new workspace dependency | Medium | Medium | Run it at Phase 7, and build the vsix in the harness from Phase 1 onward. `vscode:prepublish` runs `pnpm --filter 'codev-vscode^...' build`. The package has no `build` script, which pnpm skips, and Phase 7 confirms that with a real `package` run | | Fixture builders do not appear, or appear without attribution | High if missed | Medium | Each fixture builder gets a real worktree, porch state, a `builders` row through the product's `upsertBuilder`, and a registered builder terminal. `/api/overview` is asserted, attribution included, before any screenshot | | Path containment behaves differently on Windows (case, separators, UNC, junctions) | Medium | High | `realpath` + `path.relative` (no prefix compare), `path.win32` table tests, and the on-demand Windows workflow linked in the PR | diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md index 4fe01976b..f49b3cdff 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md @@ -29,7 +29,8 @@ accepted (below). - **Confirmed:** CI's `apps/vscode` step runs `check-types` and `test:unit` only (`.github/workflows/test.yml:102-107`). - **Change:** the smoke test builds its own entry in `beforeAll` through esbuild's API, into - a temp dir. It uses the options object `esbuild.js` uses, shared from `esbuild.webview.mjs`. + a temp dir. It uses the options object `esbuild.js` uses, shared from `esbuild.webview.cjs`. + (The confirmation round corrected `.mjs` to `.cjs`.) 3. **The package's test devDependencies and lockfile.** - **Change:** the package declares its own devDependencies, at `apps/web`'s versions: - `react` and `react-dom`; @@ -94,3 +95,45 @@ accepted (below). - the tripwire shown to fire, aimed at a throwaway listener and never at `:4100`. The spike runs in it. The phases renumber from 1–8 to 1–9. + +## Confirmation round + +- Codex: REQUEST_CHANGES. +- Claude: COMMENT. + +Both points from each were checked against the code and accepted. + +### Codex + +1. **CSP lacks `default-src 'none'`.** + - **Confirmed:** without it, leaving out `connect-src` restricts nothing. Both existing webviews + set it (`panel-template.ts:22`, `preview-template.ts:47`). + - **Change:** it is added, with a static CSP test. +2. **Scenario 22 has no decisive test.** + - **Change:** it is tested three ways: + - an ESLint ban on `fetch`/XHR/WebSocket/EventSource/`sendBeacon` in the webview sources; + - a unit test that no host-to-webview message carries the key or the Tower URL; + - in the harness, Playwright records the webview frames' requests: assets, `blob:` and + fixture item images only, with nothing to the Tower port and no key header. + +### Claude + +1. **`issue-id-parity.test.ts` breaks.** + - **Confirmed:** `exportedSource` throws when `CANONICAL_KEY_SOURCE` is absent (line 21), and the + line-37 guard watches the wrapper. + - **Change:** both are repointed in Phase 6, and `packages/codev`'s suite is added to Phase 6's + acceptance. +2. **No import-boundary test.** + - **Change:** canvas's `import-boundary.test.ts` is copied into the package, extended to forbid + `fetch(`, XHR, WebSocket, EventSource and `sendBeacon`. +3. **A shared `.mjs` can't be `require`d.** + - **Confirmed:** `esbuild.js` is CommonJS, and `apps/vscode` has no `"type": "module"`. + - **Change:** the file is `esbuild.webview.cjs`, and it is added to `.vscodeignore`. +4. **Comments.** All accepted: + - Phase 5 lands as two commits, 5a and 5b; + - `--status-*` is named as a second token family, `--codev-wv-status-*`; + - the rendered check covers active-file reveal with the rows collapsed; + - `viewsWelcome` entries are recorded in the oracle; + - the "existing CI step" sentence is replaced: `test.yml` enumerates packages, so the package + gets its own step; + - `vscode:prepublish` is confirmed at Phase 7 with a real `package` run. From f04c694fd253c12ebda2f22a885b8992ae34c651 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:55:15 -0800 Subject: [PATCH 028/140] =?UTF-8?q?[Spec=201963]=20Plan:=20layout=20spike?= =?UTF-8?q?=20run=20before=20approval=20=E2=80=94=20all=20four=20cases=20h?= =?UTF-8?q?old;=20Phase=209=20outcome=20recorded?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1963-vscode-alternative-layout-seco.md | 126 +++++---- .../1963-plan-harness-rebuttals.md | 5 + .../layout-spike/driver.mjs | 46 ++++ .../layout-spike/results.json | 258 ++++++++++++++++++ .../layout-spike/spike-extension.js | 207 ++++++++++++++ codev/state/spir-1963_thread.md | 26 ++ 6 files changed, 616 insertions(+), 52 deletions(-) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/layout-spike/driver.mjs create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/layout-spike/results.json create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/layout-spike/spike-extension.js diff --git a/codev/plans/1963-vscode-alternative-layout-seco.md b/codev/plans/1963-vscode-alternative-layout-seco.md index 8fc9848ea..20aef2179 100644 --- a/codev/plans/1963-vscode-alternative-layout-seco.md +++ b/codev/plans/1963-vscode-alternative-layout-seco.md @@ -7,11 +7,12 @@ This plan implements the approved spec in its three shippable increments, in nine phases. Each phase is one commit on `builder/spir-1963`, and all of them go into one PR. -0. **Verification harness and layout spike** (Phase 1). This is the isolated harness every rendered - checkpoint uses (section *Verification harness*), proven safe on an empty fixture. It also runs - the editor-layout spike the spec's Assumptions require, so its result is known before any - increment-1 code. If the spike shows that the arrangement needs an owner decision, the owner - gets it early. +0. **Verification harness** (Phase 1). This is the isolated harness every rendered checkpoint + uses (section *Verification harness*), proven safe on an empty fixture. + + The editor-layout spike the spec's Assumptions require **has already been run**, before plan + approval, on 2026-11-24 against VS Code 1.147.0. All four cases held; see *Layout spike result* + below. No owner decision is needed for the arrangement. 1. **Button + hierarchy** (Phases 2–5). This uses spec approach **A1**: one tree view over the existing row-building code. Its single hierarchy is the owner's *"towers -> workspaces -> architects / decisions -> builders"*. Rows of this window's workspace act; rows of other @@ -30,20 +31,58 @@ phase is one commit on `builder/spir-1963`, and all of them go into one PR. `ConnectionManager`'s client. 3. ***Arrange Cockpit*** (Phase 9). This uses approaches **C1** (first show per window, plus the command and `codev.cockpit.autoArrange`) and **D1** (Work stacked over Decisions). It also adds - the one-time first-auto-arrange notice ruled at the gate. It builds on the Phase 1 spike result, - and writes no arrange code while a spike case is unresolved. + the one-time first-auto-arrange notice ruled at the gate. It is built on the spike result + recorded below. Rendered verification sits at the end of each increment: Phase 5, Phase 8 and Phase 9. It also runs at Phase 6 (the dashboard comparison) and Phase 7 (Decisions). It uses the isolated harness built in Phase 1, so the work can be cut after any increment with what has shipped already verified. +## Layout spike result (run before plan approval) + +The spec says the layout assumptions are "to be confirmed in the plan by a spike against a running +instance". At the architect's direction, the spike was run on **2026-11-24, before plan approval**. + +**Setup:** +- a throwaway extension in an isolated `code serve-web`, VS Code **1.147.0**, on port 18763; +- the CLI, server, user and extensions dirs were all under the session scratchpad; +- the browser was headless Chromium from the existing Playwright cache, with no install; +- no Tower was involved, and nothing in the serve-web process tree connected to `:4100`; +- every process was stopped by PID afterwards. + +The raw results, the spike source and screenshots are committed in +`codev/projects/1963-vscode-alternative-layout-seco/layout-spike/`. + +| Case | What was checked | Result | +|---|---|---| +| **(a)** `vscode.setEditorLayout` `{ orientation: 0, groups: [{}, { groups: [{}, {}] }] }` over **5** groups | Groups 5 → 3, and `vscode.getEditorLayout` shows left \| (top / bottom). No document closed (`onDidCloseTextDocument` was empty). All 7 editors are still open with identical text: 2 untitled-with-content, 3 modified files and 2 clean files. Every dirty editor stayed dirty. Applying it again with 3 groups changed nothing | **Holds** | +| **(b)** editor-area terminal, group 3 → group 1, via `terminal.show()` + `workbench.action.moveEditorToFirstGroup` | It is in group 1 afterwards, with `exitStatus` unset and the same `processId`. The same shell (same `$$`) answered before and after the move | **Holds** | +| **(c)** panel terminal → editor area via `workbench.action.terminal.moveToEditor`, then to group 1 as in (b) | It became an editor tab and then sat in group 1. Same PID, same shell, session intact | **Holds** | +| **(d)** `retainContextWhenHidden` webview moved with `WebviewPanel.reveal(viewColumn)` | It moved from group 2 to 3 while visible, then from 3 to 1 **while hidden** under another editor. The webview's random load id was identical at all three pings, and its counter kept advancing. No reload | **Holds** | + +**What this fixes in the design:** + +- **Merge target.** Editors from groups that `setEditorLayout` removes are merged into the **last** + remaining group, which is the bottom-right one, where Decisions goes. Arrange therefore opens or + reveals Decisions there *after* the layout call, and makes it the active tab. The user's moved + editors sit behind it as tabs, never closed. +- **No group-count special case.** The layout call is idempotent, so arrange always applies it. + A window that already has three groups is left as it is. + +**What the harness needs (found by the spike, now in the harness section):** + +- VS Code for the Web defaults `files.autoSave` to `afterDelay`. The first run silently wrote the + "modified" fixture files to disk, so the harness profile sets `files.autoSave: off`. +- Restricted Mode raises a "Trust Folder & Continue" modal when a terminal is created. That modal + stalled the first run, so the harness trusts its fixture folders before any scenario. + ## Phases (Machine Readable) ```json { "phases": [ - {"id": "verification_harness", "title": "Isolated verification harness and editor-layout spike"}, + {"id": "verification_harness", "title": "Isolated verification harness"}, {"id": "fleet_overviews", "title": "Fleet cache keeps every active workspace's overview"}, {"id": "architect_tree_builder", "title": "Reusable, workspace-scoped architect-axis row builder"}, {"id": "cockpit_hierarchy", "title": "Cockpit button and the Tower → workspaces → architects → builders tree"}, @@ -58,15 +97,15 @@ verified. ## Phase Breakdown -### Phase 1: Isolated verification harness and editor-layout spike +### Phase 1: Isolated verification harness **Dependencies**: None #### Objective Build, once, the isolated environment every rendered checkpoint runs in, and prove it cannot reach -the owner's Tower or IDE before it is used for anything. Then use it to run the editor-layout spike, -so the arrangement's feasibility is known before increment-1 code is written. +the owner's Tower or IDE before it is used for anything. (The editor-layout spike is already done; +see *Layout spike result*.) #### Files to Create / Modify @@ -83,36 +122,9 @@ so the arrangement's feasibility is known before increment-1 code is written. Scripts load the branch's built `packages/codev/dist`. They never use a globally installed CLI. -**The spike is not committed.** It is a throwaway extension in the session scratchpad, loaded into -the harness's isolated VS Code. Its result is recorded in the thread, and later in the review, with -screenshots. It checks: - -- (a) `vscode.setEditorLayout` with `{ orientation: 0, groups: [{}, { groups: [{}, {}] }] }`, run - over three or more existing groups, merges the editors of the groups it removes into the remaining - groups. Dirty, untitled and modified editors survive with their content; -- (b) an editor-area terminal tab moves between groups without ending its session. The method is - `terminal.show()`, then `workbench.action.moveEditorToFirstGroup`, then a check that the PTY still - echoes; -- (c) a panel terminal moves into the editor area through `workbench.action.terminal.moveToEditor`, - with the session intact; -- (d) `WebviewPanel.reveal(viewColumn)` moves a retained panel to another group without reloading it - (a counter in the webview survives the move). - -**Outcomes:** - -- **(a) fails:** arrange only adds or reuses groups and never removes one. The spec already - provides this, so no decision is needed. -- **(b), (c) or (d) fails:** the spec does not provide a fallback, and every candidate fallback - changes ruled behaviour. Examples: leaving the architect where it is, or not honouring the - `terminalPosition` override. - - **The result goes to the architect at once, with the options**, and Phase 9 waits for the - owner's ruling. - - Phases 2–8 do not depend on it and continue. - #### Deliverables - [ ] The harness scripts, stubs and README. -- [ ] The spike run, with its result recorded in the thread. - [ ] Harness self-tests. #### Acceptance Criteria @@ -134,14 +146,12 @@ screenshots. It checks: - [ ] **The tripwire is shown to fire**, without touching `:4100`. Its port is a parameter, and the self-test points it at a throwaway local listener the test opens, connects to it from a harness child process, and expects a failure. -- [ ] The spike result is recorded, and the architect is told if (b), (c) or (d) failed. #### Test Plan - `harness.mjs selftest`: the refusals and the tripwire above. - A seeded fixture (one workspace, one builder) appears in the isolated Tower's `/api/overview` with its `spawnedByArchitect`. -- The spike, as above. ### Phase 2: Fleet cache keeps every active workspace's overview @@ -1000,7 +1010,7 @@ every kept affordance mapped to a VS Code action and every dropped one absent. ### Phase 9: Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification -**Dependencies**: Phase 1 (the spike result), Phase 4, Phase 7, Phase 8 +**Dependencies**: Phase 4, Phase 7, Phase 8 #### Objective @@ -1009,13 +1019,19 @@ first show per window session, and on demand. It never closes or discards a user #### Files to Create / Modify -**The Phase 1 spike result decides the mechanics.** If (a) failed, arrange only adds or reuses -groups. If (b), (c) or (d) failed, this phase starts only after the owner's ruling on the options -the architect was given. +**Outcome that applies: all four spike cases held** (see *Layout spike result*). So: +- arrange uses `vscode.setEditorLayout`, removing groups where needed. The spec's add/reuse-only + fallback is not used; +- it moves the architect terminal with `show()` + `moveEditorToFirstGroup`. A panel terminal goes + through `workbench.action.terminal.moveToEditor` first; +- it moves the retained panels with `reveal(viewColumn)`. + +No owner decision is pending. **New `apps/vscode/src/cockpit/arrange.ts`, `arrangeCockpit()`:** -- shapes the layout, preserving editors per the spike; +- applies the layout. Editors from removed groups merge into the last (bottom-right) group, so + Decisions is opened or revealed there after the layout call and made the active tab; - resolves `main` through `openResolvedArchitect`. A non-live `main` gets the existing warning and no substitute; - reuses an open architect terminal and moves it to group 1, even with `terminalPosition: panel` @@ -1054,8 +1070,7 @@ The command stays in the palette everywhere and explains itself where it does no #### Deliverables -- [ ] The spike result recorded; arrange; triggers; the setting; the notice; the explanations; - tests; docs. +- [ ] Arrange; triggers; the setting; the notice; the explanations; tests; docs. - [ ] Rendered verification of increment 3 and the PR's screenshot set. #### Acceptance Criteria @@ -1155,8 +1170,16 @@ can produce, is unit-tested. ### Isolated VS Code `code serve-web` (`/usr/local/bin/code` on this machine) runs on its own port, with -`--server-data-dir`, `--user-data-dir` and `--extensions-dir` all under the scratchpad, and the -branch's vsix installed there. +`--cli-data-dir`, `--server-data-dir`, `--user-data-dir` and `--extensions-dir` all under the +scratchpad, and the branch's vsix installed there. The layout spike ran exactly this way. + +- **Profile settings:** + - `files.autoSave: off`. Web defaults to `afterDelay`, which would silently save the + dirty-editor fixtures; + - the fixture folders are trusted before any scenario. Otherwise Restricted Mode blocks terminal + creation behind a modal. +- **Driver:** Chromium from the existing Playwright cache, through the main checkout's + `playwright-core`. The spike used revision 1217 with `playwright-core` 1.59.1, with no install. - **Fallback:** if `serve-web` cannot run, the harness launches the IDE server binary that Tower's IDE support uses (`ide-server.ts`). It is launched **directly**, with the same flags @@ -1245,8 +1268,7 @@ told before its first start. |------|-------------|--------|------------| | The row-builder extraction (Phase 3) changes an Agents id or behaviour | Medium | High | An id-equivalence snapshot taken from the pre-refactor provider in the same commit, plus every existing Agents test unmodified | | Generalised wiring regresses accordion, reveal or cycle in Agents | Medium | High | Per-view hosts with the Agents path unchanged; existing behaviour tests plus new per-view tests; rendered check of both views | -| The layout primitive closes or discards an editor | Low | High | The Phase 1 spike, run before any increment code. If it fails, the spec's add/reuse-only rule applies. The dirty/untitled/modified scenario is rendered | -| A terminal or retained-webview move fails in the spike (cases b–d) | Low | Medium | The spec gives no fallback, so the result goes to the architect from Phase 1 with the options. Phase 9 waits for the owner, and Phases 2–8 continue | +| The layout primitive closes or discards an editor | Low | High | The spike before plan approval showed it merges and closes nothing (VS Code 1.147.0). Phase 9 still renders the dirty/untitled/modified scenario on the branch build. If a later VS Code regresses this, the spec's add/reuse-only rule is the fallback | | Moving components changes the dashboard | Medium | Medium | Wrappers keep `lib/api.ts`; the moved tests are unchanged in intent; the dashboard integration tests stay; a rendered before/after comparison | | A source-exported TSX package does not type-check under one host's config | Medium | Medium | `codev-artifact-canvas` is a *built* package (`tsdown` → `dist`), so the closer precedent is `apps/web`'s own source exports. The risk sits in `apps/web`'s `tsc -b`, which type-checks the package's `.tsx` under the dashboard's config, and in the extension's webview tsconfig (`jsx: react-jsx` added). Phase 6 runs both type-checks before moving anything. If a host still cannot consume the source, the package gains a `tsdown` build like canvas. That is a build-wiring change, not scope, and it is named in the PR | | The harness accidentally touches the owner's Tower or IDE | Medium (several CLI paths default to `:4100`) | High | No Tower-contacting CLI commands. Every state-creating step names its route to the isolated port (harness table). Extension shell-outs are recording stubs, and auto-start is off. `CODEV_TOWER_KEY` is set, as are isolated state, socket and VS Code dirs. A pre-flight refuses 4100 and checks the listener PID, and a `:4100` connection tripwire runs throughout. The architect is told before the first start | @@ -1267,5 +1289,5 @@ told before its first start. Hot-tier files are not touched unless the review step routes a fact there. - `apps/vscode/CHANGELOG.md`: one entry per increment. -- The review (`codev/reviews/1963-…`) at the end records the spike result and the +- The review (`codev/reviews/1963-…`) at the end records the spike result (from *Layout spike result*) and the lessons-learned candidates. diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md index f49b3cdff..11daa6a26 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-plan-harness-rebuttals.md @@ -25,6 +25,11 @@ accepted (below). waits for the owner, and Phases 2–8 continue. - **Offered to the architect:** running the spike before the plan is approved, if they want the strict reading. + - **Update: the architect took the strict reading, and the spike has now run before approval.** + - Run on 2026-11-24, VS Code 1.147.0, isolated serve-web. All four cases held. + - The result is in the plan (*Layout spike result*). Phase 9 states the outcome that applies, + and the evidence is in `layout-spike/`. + - Codex 1 is now fully met. 2. **The bundle smoke test needs `dist`, which CI never builds.** - **Confirmed:** CI's `apps/vscode` step runs `check-types` and `test:unit` only (`.github/workflows/test.yml:102-107`). diff --git a/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/driver.mjs b/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/driver.mjs new file mode 100644 index 000000000..5870ee004 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/driver.mjs @@ -0,0 +1,46 @@ +// Headless driver for the layout spike: loads the isolated serve-web workbench, screenshots each +// stage the spike extension announces, and acks it. Never touches :4100 or the owner's /ide/. +import { chromium } from '/Users/mwk/Development/cluesmith/codev/node_modules/.pnpm/playwright-core@1.59.1/node_modules/playwright-core/index.mjs'; +import fs from 'node:fs'; +import path from 'node:path'; + +const SK = path.dirname(new URL(import.meta.url).pathname); +const OUT = path.join(SK, 'out'); +const SHOTS = path.join(SK, 'shots'); +const PORT = Number(process.env.SPIKE_PORT); +if (!PORT || PORT === 4100) throw new Error('SPIKE_PORT must be set and must not be 4100'); +const url = `http://127.0.0.1:${PORT}/?folder=${encodeURIComponent(path.join(SK, 'ws'))}`; + +const browser = await chromium.launch({ headless: true }); +const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); +const consoleLog = fs.createWriteStream(path.join(OUT, 'browser-console.log')); +page.on('console', (m) => consoleLog.write(`[${m.type()}] ${m.text()}\n`)); +page.on('request', (r) => { const u = r.url(); if (u.includes(':4100')) { consoleLog.write(`!!! REQUEST TO 4100: ${u}\n`); } }); + +console.log('goto', url); +await page.goto(url, { timeout: 240000, waitUntil: 'domcontentloaded' }); +await page.waitForSelector('.monaco-workbench', { timeout: 240000 }); +console.log('workbench up'); +await page.screenshot({ path: path.join(SHOTS, '00-workbench.png') }); + +const deadline = Date.now() + 5 * 60 * 1000; +let trustClicked = false; +while (Date.now() < deadline) { + const btn = page.getByRole('button', { name: /Yes, I trust|Trust Folder/i }); + if (await btn.count()) { await btn.first().click(); trustClicked = true; console.log('trust prompt accepted'); } + for (const f of fs.readdirSync(OUT)) { + if (!f.startsWith('stage-') || f.endsWith('.ack')) continue; + const ack = path.join(OUT, `${f}.ack`); + if (fs.existsSync(ack)) continue; + await page.waitForTimeout(700); + await page.screenshot({ path: path.join(SHOTS, `${f.slice(6)}.png`) }); + fs.writeFileSync(ack, ''); + console.log('shot', f); + if (f === 'stage-done') { await browser.close(); process.exit(0); } + } + await page.waitForTimeout(500); +} +console.log('timed out waiting for the spike'); +await page.screenshot({ path: path.join(SHOTS, 'timeout.png') }); +await browser.close(); +process.exit(2); diff --git a/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/results.json b/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/results.json new file mode 100644 index 000000000..372bc2d94 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/results.json @@ -0,0 +1,258 @@ +{ + "started": "2026-11-24T06:52:47.035Z", + "vscodeVersion": "1.147.0", + "autoSave": "off", + "trusted": false, + "a": { + "groupsBefore": 5, + "tabsBefore": [ + { + "viewColumn": 1, + "tabs": [ + { + "label": "a.txt", + "kind": "text", + "dirty": false, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/a.txt" + } + ] + }, + { + "viewColumn": 2, + "tabs": [ + { + "label": "b.txt", + "kind": "text", + "dirty": true, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/b.txt" + } + ] + }, + { + "viewColumn": 3, + "tabs": [ + { + "label": "c.txt", + "kind": "text", + "dirty": false, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/c.txt" + } + ] + }, + { + "viewColumn": 4, + "tabs": [ + { + "label": "d.txt", + "kind": "text", + "dirty": true, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/d.txt" + }, + { + "label": "UNTITLED-in-4", + "kind": "text", + "dirty": true, + "uri": "untitled:Untitled-1" + } + ] + }, + { + "viewColumn": 5, + "tabs": [ + { + "label": "e.txt", + "kind": "text", + "dirty": true, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/e.txt" + }, + { + "label": "UNTITLED-in-5", + "kind": "text", + "dirty": true, + "uri": "untitled:Untitled-2" + } + ] + } + ], + "groupsAfter": 3, + "layoutAfter": { + "orientation": 0, + "groups": [ + { + "size": 547 + }, + { + "size": 547, + "groups": [ + { + "size": 453 + }, + { + "size": 452 + } + ] + } + ] + }, + "tabsAfter": [ + { + "viewColumn": 1, + "tabs": [ + { + "label": "a.txt", + "kind": "text", + "dirty": false, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/a.txt" + } + ] + }, + { + "viewColumn": 2, + "tabs": [ + { + "label": "b.txt", + "kind": "text", + "dirty": true, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/b.txt" + } + ] + }, + { + "viewColumn": 3, + "tabs": [ + { + "label": "c.txt", + "kind": "text", + "dirty": false, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/c.txt" + }, + { + "label": "d.txt", + "kind": "text", + "dirty": true, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/d.txt" + }, + { + "label": "UNTITLED-in-4", + "kind": "text", + "dirty": true, + "uri": "untitled:Untitled-1" + }, + { + "label": "e.txt", + "kind": "text", + "dirty": true, + "uri": "file:///private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/ws/e.txt" + }, + { + "label": "UNTITLED-in-5", + "kind": "text", + "dirty": true, + "uri": "untitled:Untitled-2" + } + ] + } + ], + "perDoc": { + "a": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": false, + "dirtyAfter": false, + "textPreserved": true + }, + "b": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": true, + "dirtyAfter": true, + "textPreserved": true + }, + "c": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": false, + "dirtyAfter": false, + "textPreserved": true + }, + "d": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": true, + "dirtyAfter": true, + "textPreserved": true + }, + "e": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": true, + "dirtyAfter": true, + "textPreserved": true + }, + "UNTITLED-in-4": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": true, + "dirtyAfter": true, + "textPreserved": true + }, + "UNTITLED-in-5": { + "tabStillOpen": true, + "docStillOpen": true, + "dirtyBefore": true, + "dirtyAfter": true, + "textPreserved": true + } + }, + "closedDocsDuringLayout": [], + "pass": true, + "idempotent": true + }, + "d": { + "columnBefore": 2, + "columnAfterReveal": 3, + "visibleMove": { + "sameLoad": true, + "ticksAdvanced": true, + "p1": { + "loadId": "agcdhyakwmh", + "n": 6 + }, + "p2": { + "loadId": "agcdhyakwmh", + "n": 21 + } + }, + "hiddenBeforeReveal": true, + "columnAfterHiddenReveal": 1, + "hiddenMove": { + "sameLoad": true, + "ticksAdvanced": true, + "p3": { + "loadId": "agcdhyakwmh", + "n": 44 + } + }, + "pass": true + }, + "b": { + "columnBefore": 3, + "columnAfter": 1, + "exitStatus": null, + "pidBefore": 55514, + "pidAfter": 55514, + "log": "B1-55514\nB2-55514\n", + "pass": true + }, + "c": { + "columnBefore": null, + "columnAfterMoveToEditor": 1, + "columnAfterFirstGroup": 1, + "exitStatus": null, + "pidBefore": 55728, + "pidAfter": 55728, + "log": "C1-55728\nC2-55728\n", + "pass": true + }, + "finished": "2026-11-24T06:53:20.512Z" +} \ No newline at end of file diff --git a/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/spike-extension.js b/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/spike-extension.js new file mode 100644 index 000000000..1c7122ed1 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/layout-spike/spike-extension.js @@ -0,0 +1,207 @@ +// Throwaway spike for Spec 1963 Phase 1: checks (a)-(d) of the editor-layout assumptions. +// Writes stage markers + results into OUT; a Playwright driver screenshots each stage. +const vscode = require('vscode'); +const fs = require('fs'); +const path = require('path'); + +const OUT = '/private/tmp/claude-501/-Users-mwk-Development-cluesmith-codev--builders-spir-1963/b220eadf-5293-4c67-95a3-546bd584cc12/scratchpad/spike/out'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const results = { started: new Date().toISOString(), vscodeVersion: vscode.version }; +const log = (m) => fs.appendFileSync(path.join(OUT, 'spike.log'), `${new Date().toISOString()} ${m}\n`); + +async function stage(name) { + fs.writeFileSync(path.join(OUT, `stage-${name}`), ''); + const ack = path.join(OUT, `stage-${name}.ack`); + for (let i = 0; i < 60 && !fs.existsSync(ack); i++) await sleep(500); +} + +function tabKind(t) { + const i = t.input; + if (i instanceof vscode.TabInputText) return 'text'; + if (i instanceof vscode.TabInputTerminal) return 'terminal'; + if (i instanceof vscode.TabInputWebview) return 'webview'; + return 'other'; +} +function snapshot() { + return vscode.window.tabGroups.all.map((g) => ({ + viewColumn: g.viewColumn, + tabs: g.tabs.map((t) => ({ label: t.label, kind: tabKind(t), dirty: t.isDirty, uri: t.input && t.input.uri ? t.input.uri.toString() : undefined })), + })); +} +function terminalTabColumn(label) { + for (const g of vscode.window.tabGroups.all) for (const t of g.tabs) if (tabKind(t) === 'terminal' && t.label === label) return g.viewColumn; + return null; +} +const RUN = Date.now().toString(36); +const withTimeout = (p, ms, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(`${what} timed out`)), ms))]); +const LAYOUT = { orientation: 0, groups: [{}, { groups: [{}, {}] }] }; + +async function caseA(ws) { + const r = {}; + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + await sleep(500); + const docs = {}; + for (const [n, col] of [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]) { + const doc = await vscode.workspace.openTextDocument(vscode.Uri.joinPath(ws, `${n}.txt`)); + const ed = await vscode.window.showTextDocument(doc, { viewColumn: col, preview: false }); + if (n === 'b' || n === 'd' || n === 'e') await ed.edit((e) => e.insert(new vscode.Position(0, 0), `MODIFIED-${n} `)); + docs[n] = doc; + } + for (const [label, col] of [['UNTITLED-in-4', 4], ['UNTITLED-in-5', 5]]) { + const doc = await vscode.workspace.openTextDocument({ content: label, language: 'plaintext' }); + await vscode.window.showTextDocument(doc, { viewColumn: col, preview: false }); + docs[label] = doc; + } + await sleep(800); + const before = Object.fromEntries(Object.entries(docs).map(([k, d]) => [k, { uri: d.uri.toString(), dirty: d.isDirty, text: d.getText() }])); + r.groupsBefore = vscode.window.tabGroups.all.length; + r.tabsBefore = snapshot(); + await stage('a-before'); + const closed = []; + const sub = vscode.workspace.onDidCloseTextDocument((d) => closed.push(d.uri.toString())); + await vscode.commands.executeCommand('vscode.setEditorLayout', LAYOUT); + await sleep(1500); + sub.dispose(); + r.groupsAfter = vscode.window.tabGroups.all.length; + r.layoutAfter = await vscode.commands.executeCommand('vscode.getEditorLayout'); + r.tabsAfter = snapshot(); + const afterTabUris = new Set(r.tabsAfter.flatMap((g) => g.tabs.map((t) => t.uri))); + r.perDoc = {}; + for (const [k, b] of Object.entries(before)) { + const d = vscode.workspace.textDocuments.find((x) => x.uri.toString() === b.uri); + r.perDoc[k] = { + tabStillOpen: afterTabUris.has(b.uri), + docStillOpen: !!d, + dirtyBefore: b.dirty, dirtyAfter: d ? d.isDirty : null, + textPreserved: d ? d.getText() === b.text : false, + }; + } + r.closedDocsDuringLayout = closed; + r.pass = r.groupsAfter === 3 && closed.length === 0 && Object.values(r.perDoc).every((p) => p.tabStillOpen && p.docStillOpen && p.textPreserved && p.dirtyAfter === p.dirtyBefore); + await stage('a-after'); + // idempotency: applying again with 3 groups changes nothing + const snapBefore = JSON.stringify(snapshot()); + await vscode.commands.executeCommand('vscode.setEditorLayout', LAYOUT); + await sleep(800); + r.idempotent = JSON.stringify(snapshot()) === snapBefore; + return r; +} + +async function caseD(ws) { + const r = {}; + const panel = vscode.window.createWebviewPanel('spikeD', 'Spike D', { viewColumn: vscode.ViewColumn.Two, preserveFocus: false }, { enableScripts: true, retainContextWhenHidden: true }); + panel.webview.html = `
0
`; + const ping = () => new Promise((res, rej) => { + const t = setTimeout(() => rej(new Error('ping timeout')), 5000); + const s = panel.webview.onDidReceiveMessage((m) => { clearTimeout(t); s.dispose(); res(m); }); + panel.webview.postMessage('ping'); + }); + await sleep(1500); + const p1 = await ping(); + r.columnBefore = panel.viewColumn; + panel.reveal(vscode.ViewColumn.Three); + await sleep(1500); + const p2 = await ping(); + r.columnAfterReveal = panel.viewColumn; + r.visibleMove = { sameLoad: p1.loadId === p2.loadId, ticksAdvanced: p2.n > p1.n, p1, p2 }; + // hidden move: cover the panel with a text editor in its group, then reveal into group 1 + const doc = await vscode.workspace.openTextDocument(vscode.Uri.joinPath(ws, 'a.txt')); + await vscode.window.showTextDocument(doc, { viewColumn: vscode.ViewColumn.Three, preview: false }); + await sleep(800); + r.hiddenBeforeReveal = !panel.visible; + panel.reveal(vscode.ViewColumn.One); + await sleep(1500); + const p3 = await ping(); + r.columnAfterHiddenReveal = panel.viewColumn; + r.hiddenMove = { sameLoad: p1.loadId === p3.loadId, ticksAdvanced: p3.n > p2.n, p3 }; + r.pass = r.columnAfterReveal === 3 && r.visibleMove.sameLoad && r.visibleMove.ticksAdvanced && r.columnAfterHiddenReveal === 1 && r.hiddenMove.sameLoad; + await stage('d-after'); + r.panel = panel; + return r; +} + +async function makeTerminal(name, location) { + const t = vscode.window.createTerminal({ name, shellPath: '/bin/bash', shellArgs: ['--noprofile', '--norc'], location }); + const pid = await withTimeout(t.processId, 20000, `processId of ${name}`); + await sleep(1500); + return { t, pid }; +} +function readLog(f) { try { return fs.readFileSync(f, 'utf8'); } catch { return ''; } } + +async function caseB() { + const r = {}; + const logf = path.join(OUT, 'b.log'); + const { t, pid } = await makeTerminal(`spikeB-${RUN}`, { viewColumn: vscode.ViewColumn.Three }); + t.sendText(`echo B1-$$ >> '${logf}'`); + await sleep(1000); + r.columnBefore = terminalTabColumn(`spikeB-${RUN}`); + t.show(false); + await sleep(500); + await vscode.commands.executeCommand('workbench.action.moveEditorToFirstGroup'); + await sleep(1500); + r.columnAfter = terminalTabColumn(`spikeB-${RUN}`); + r.exitStatus = t.exitStatus ? t.exitStatus.code : null; + r.pidBefore = pid; r.pidAfter = await withTimeout(t.processId, 10000, 'processId after'); + t.sendText(`echo B2-$$ >> '${logf}'`); + await sleep(1000); + r.log = readLog(logf); + const lines = r.log.trim().split('\n'); + r.pass = r.columnBefore === 3 && r.columnAfter === 1 && r.exitStatus === null && r.pidBefore === r.pidAfter + && lines.length === 2 && lines[0].startsWith('B1-') && lines[1].startsWith('B2-') && lines[0].slice(3) === lines[1].slice(3); + await stage('b-after'); + return r; +} + +async function caseC() { + const r = {}; + const logf = path.join(OUT, 'c.log'); + const { t, pid } = await makeTerminal(`spikeC-${RUN}`, vscode.TerminalLocation.Panel); + t.sendText(`echo C1-$$ >> '${logf}'`); + await sleep(1000); + r.columnBefore = terminalTabColumn(`spikeC-${RUN}`); // null = in the panel, not an editor tab + t.show(false); + await sleep(500); + await vscode.commands.executeCommand('workbench.action.terminal.moveToEditor'); + await sleep(1500); + r.columnAfterMoveToEditor = terminalTabColumn(`spikeC-${RUN}`); + t.show(false); + await sleep(500); + await vscode.commands.executeCommand('workbench.action.moveEditorToFirstGroup'); + await sleep(1500); + r.columnAfterFirstGroup = terminalTabColumn(`spikeC-${RUN}`); + r.exitStatus = t.exitStatus ? t.exitStatus.code : null; + r.pidBefore = pid; r.pidAfter = await withTimeout(t.processId, 10000, 'processId after'); + t.sendText(`echo C2-$$ >> '${logf}'`); + await sleep(1000); + r.log = readLog(logf); + const lines = r.log.trim().split('\n'); + r.pass = r.columnBefore === null && r.columnAfterMoveToEditor !== null && r.columnAfterFirstGroup === 1 && r.exitStatus === null + && r.pidBefore === r.pidAfter && lines.length === 2 && lines[0].slice(3) === lines[1].slice(3); + await stage('c-after'); + return r; +} + +async function run() { + const ws = vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders[0].uri; + log(`activated; ws=${ws} run=${RUN}`); + await vscode.workspace.getConfiguration('files').update('autoSave', 'off', vscode.ConfigurationTarget.Global); + results.autoSave = vscode.workspace.getConfiguration('files').get('autoSave'); + results.trusted = vscode.workspace.isTrusted; + for (const t of vscode.window.terminals) t.dispose(); + log(`autoSave=${results.autoSave} trusted=${results.trusted}`); + for (const [k, fn] of [['a', caseA], ['d', caseD], ['b', caseB], ['c', caseC]]) { + try { const r = await fn(ws); delete r.panel; results[k] = r; log(`case ${k} pass=${r.pass}`); } + catch (e) { results[k] = { error: String(e && e.stack || e) }; log(`case ${k} ERROR ${e}`); } + fs.writeFileSync(path.join(OUT, 'results.json'), JSON.stringify(results, null, 2)); + } + results.finished = new Date().toISOString(); + fs.writeFileSync(path.join(OUT, 'results.json'), JSON.stringify(results, null, 2)); + await stage('done'); +} + +exports.activate = () => { setTimeout(() => run().catch((e) => log(`run failed ${e}`)), 4000); }; +exports.deactivate = () => {}; diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index cf4f8d7bc..338e8a0dc 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -154,3 +154,29 @@ command: - the smoke test builds its own bundle, since CI never builds `dist`. Phases are now 1–9. Rebuttals are in `1963-plan-harness-rebuttals.md`. + +## 2026-11-24 — Layout spike, run before plan approval (architect: strict reading) + +Setup: an isolated `code serve-web` on :18763, VS Code 1.147.0. The CLI, server, user and +extensions dirs were all in the scratchpad. A throwaway extension was driven by headless Chromium +from the existing Playwright cache, with no install. There was no Tower, and the serve-web tree had +no :4100 connection. All processes were stopped by PID. + +**All four cases held:** +- **(a)** `setEditorLayout` over 5 groups gave 3 (left | top/bottom). Nothing closed, all text was + intact and dirty stayed dirty. It is idempotent. +- **(b)** An editor terminal moved from group 3 to group 1 with the same PID and shell. +- **(c)** A panel terminal went to the editor area (`moveToEditor`) and then to group 1, intact. +- **(d)** A retained webview moved while visible and while hidden, with no reload (same load id). + +**Design fact:** removed groups merge into the LAST group (bottom-right = Decisions). So arrange +reveals Decisions after the layout call. + +**Harness lessons from the first run:** +- web defaults `files.autoSave` to afterDelay, which silently saved the "modified" fixtures; +- Restricted Mode raises a trust modal on terminal creation, which hung case b. + +Both are now in the harness section. A side gotcha: zsh doesn't word-split `$PIDS`, so a +`kill $PIDS` silently did nothing. I killed per PID instead. + +The evidence is in `codev/projects/1963-…/layout-spike/`. From 33d0ddd5ee24466a1bdd13a1d68daf1c55fd34a5 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:55:43 -0800 Subject: [PATCH 029/140] chore(porch): 1963 plan-approval gate-approved --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index c4d24b7c3..fd86a9a15 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -10,8 +10,9 @@ gates: requested_at: '2026-11-24T01:28:14.248Z' approved_at: '2026-11-24T05:59:40.990Z' plan-approval: - status: pending + status: approved requested_at: '2026-11-24T06:16:46.617Z' + approved_at: '2026-11-24T06:55:42.976Z' pr: status: pending verify-approval: @@ -20,4 +21,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:16:46.617Z' +updated_at: '2026-11-24T06:55:42.977Z' From 5b9e19b77ad21c99b231be03fcf49f84d9d9492e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:55:48 -0800 Subject: [PATCH 030/140] chore(porch): 1963 plan build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index fd86a9a15..980ad0413 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -18,7 +18,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:55:42.977Z' +updated_at: '2026-11-24T06:55:48.002Z' From 045552e67564e345905351a332857666cc8fefd4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:55:50 -0800 Subject: [PATCH 031/140] chore(porch): 1963 implement phase-transition --- .../status.yaml | 40 ++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 980ad0413..173f61265 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -1,9 +1,36 @@ id: '1963' title: vscode-alternative-layout-seco protocol: spir -phase: plan -plan_phases: [] -current_plan_phase: null +phase: implement +plan_phases: + - id: verification_harness + title: Isolated verification harness + status: in_progress + - id: fleet_overviews + title: Fleet cache keeps every active workspace's overview + status: pending + - id: architect_tree_builder + title: Reusable, workspace-scoped architect-axis row builder + status: pending + - id: cockpit_hierarchy + title: Cockpit button and the Tower → workspaces → architects → builders tree + status: pending + - id: cockpit_actions + title: Placement-table actions on the hierarchy, parity mapping, increment-1 verification + status: pending + - id: workspace_views_package + title: Shared Work/Decisions package; dashboard moved onto it unchanged + status: pending + - id: decisions_panel + title: Decisions panel in VS Code, its host bridge, and the hierarchy's Decisions entry + status: pending + - id: work_panel + title: Work panel in VS Code, increment-2 verification + status: pending + - id: arrange_cockpit + title: 'Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification' + status: pending +current_plan_phase: verification_harness gates: spec-approval: status: approved @@ -18,7 +45,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:55:48.002Z' +updated_at: '2026-11-24T06:55:50.289Z' +context_refreshes: + - boundary: enter:implement + at: '2026-11-24T06:55:50.288Z' From 72e90154201d160d79dc3d7369fe4e3e2015b277 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 22:56:42 -0800 Subject: [PATCH 032/140] chore(porch): 1963 acknowledge context refresh --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 173f61265..09771e514 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -48,7 +48,8 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:55:50.289Z' +updated_at: '2026-11-24T06:56:42.376Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' + acknowledged_at: '2026-11-24T06:56:42.376Z' From 241218017fefffa903d95eb91749a5462bb7d937 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:17:09 -0800 Subject: [PATCH 033/140] [Spec 1963][Phase: verification_harness] feat: isolated verification harness (Tower + serve-web, pre-flight gates, tripwire, recording stubs, self-test) --- apps/vscode/.vscodeignore | 1 + apps/vscode/scripts/cockpit-harness/README.md | 89 +++ .../scripts/cockpit-harness/fixtures.mjs | 188 +++++ .../scripts/cockpit-harness/harness.mjs | 748 ++++++++++++++++++ .../scripts/cockpit-harness/preflight.mjs | 180 +++++ apps/vscode/scripts/cockpit-harness/procs.mjs | 125 +++ apps/vscode/scripts/cockpit-harness/stubs/afx | 3 + .../scripts/cockpit-harness/stubs/codev | 3 + .../scripts/cockpit-harness/stubs/porch | 3 + .../scripts/cockpit-harness/stubs/record.mjs | 31 + .../scripts/cockpit-harness/tripwire.mjs | 102 +++ .../scripts/cockpit-harness/workbench.mjs | 135 ++++ codev/state/spir-1963_thread.md | 40 + 13 files changed, 1648 insertions(+) create mode 100644 apps/vscode/scripts/cockpit-harness/README.md create mode 100644 apps/vscode/scripts/cockpit-harness/fixtures.mjs create mode 100644 apps/vscode/scripts/cockpit-harness/harness.mjs create mode 100644 apps/vscode/scripts/cockpit-harness/preflight.mjs create mode 100644 apps/vscode/scripts/cockpit-harness/procs.mjs create mode 100755 apps/vscode/scripts/cockpit-harness/stubs/afx create mode 100755 apps/vscode/scripts/cockpit-harness/stubs/codev create mode 100755 apps/vscode/scripts/cockpit-harness/stubs/porch create mode 100644 apps/vscode/scripts/cockpit-harness/stubs/record.mjs create mode 100644 apps/vscode/scripts/cockpit-harness/tripwire.mjs create mode 100644 apps/vscode/scripts/cockpit-harness/workbench.mjs diff --git a/apps/vscode/.vscodeignore b/apps/vscode/.vscodeignore index 159277f02..aafc700ad 100644 --- a/apps/vscode/.vscodeignore +++ b/apps/vscode/.vscodeignore @@ -12,3 +12,4 @@ vsc-extension-quickstart.md **/*.map **/*.ts **/.vscode-test.* +scripts/cockpit-harness/** diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md new file mode 100644 index 000000000..7338dea09 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -0,0 +1,89 @@ +# Cockpit verification harness + +Dev-only. Excluded from the vsix (`.vscodeignore`) and not run in CI. + +This harness gives Spec 1963's rendered checkpoints an isolated Tower and an isolated VS Code +(`code serve-web`) running the branch's vsix. Neither can reach the owner's Tower (`:4100`), +`~/.agent-farm`, `~/.codev/run` or IDE (`/ide/`). The plan's *Verification harness* section is the +design; this file covers how to run it. + +## Running it + +```sh +export COCKPIT_SCRATCH= # must be under a temp root +export COCKPIT_TOWER_PORT=18764 COCKPIT_WEB_PORT=18765 +H=apps/vscode/scripts/cockpit-harness/harness.mjs + +node $H selftest # prove every pre-flight refusal and the tripwire +node $H build-vsix # vsce package → $COCKPIT_SCRATCH/cockpit-harness/codev-vscode.vsix +node $H start # pre-flight, Tower, `empty` fixture, serve-web, tripwire +node $H seed one-builder # seed a scenario; gate 6 asserts its overview +node $H check # gates 3-5 again, plus the extension running against the Tower +node $H stop # kill the harness's own PIDs; remove runtime dirs +``` + +Prerequisites: +- `packages/codev` is built, because the Tower and the fixture driver load its `dist`; +- `pnpm install` has run, because the browser driver resolves `playwright` from `packages/codev`. + +Never run `playwright install`. The driver uses the Chromium already in +`~/Library/Caches/ms-playwright`. + +## What runs, and how it is kept away from the owner's + +| Piece | How it is isolated | +|---|---| +| Tower | Started as `node packages/codev/dist/agent-farm/servers/tower-server.js -p $COCKPIT_TOWER_PORT`, never through `afx tower start`.
Its environment is built from an allowlist: `CODEV_AGENT_FARM_DIR` and `HOME` are in the scratchpad, and `NODE_ENV`, `AF_TEST_DB` and `CODEV_TOWER_KEY` are unset. | +| Shellper sockets | They live in `/run`, reached through a short `/tmp/cckp-` symlink.
macOS caps a socket path at 104 bytes, and the scratchpad path alone is longer. Gate 2 checks the link's real path, and every teardown removes the link. | +| Fixture driver (`fixtures.mjs`) | Runs in the isolated environment. Creates state only through:
  • explicit-port HTTP calls (activation, builder terminals);
  • the dist's in-process writers (porch `writeState`, `upsertBuilder`);
  • git.
It runs no Tower-contacting `afx` or `porch` command. | +| Fixture sessions | Architects and builders are `/bin/bash --noprofile --norc`, through a no-op custom harness in each fixture's `.codev/config.json`. They are never agents. | +| VS Code | `code serve-web` on `$COCKPIT_WEB_PORT`, with the CLI, server, user and extensions dirs all under the root.
  • Machine settings: `codev.towerPort=$COCKPIT_TOWER_PORT`, `codev.autoStartTower=false`, `files.autoSave=off`.
  • Environment: `CODEV_TOWER_KEY` is the isolated key, `HOME` is the scratch home, and `stubs/` comes first on `PATH`.
| +| Stubs (`stubs/afx`, `porch`, `codev`) | Each call appends `{ tool, argv, cwd, caller }` to `/logs/stub-calls.jsonl` and exits 0, so CLI-shelling actions are verified by their recorded argv.
`codev --version` prints the branch version.
The stubs are on the Tower's `PATH` too. | +| Browser (`workbench.mjs`) | Headless Chromium with a persistent profile under the root, so the folder-trust decision holds. Any request to `:4100` fails the check. | +| Tripwire (`tripwire.mjs`) | Samples `lsof` for ESTABLISHED connections on `:4100` once a second. It fails the run (writes `tripwire.tripped`, exits 3) if one belongs to the harness tree:
  • the PIDs in `/pids/`;
  • holders of sockets in the run dir;
  • descendants of either.
It never connects to `:4100`. | + +## Pre-flight gates + +These match the plan's numbering. Any refusal exits with code 2. + +1. Each port is set, numeric and not 4100, and has no listener before the start. +2. `COCKPIT_SCRATCH` is under a temp root. The agent-farm dir and socket dir resolve under it, never + into `~/.agent-farm` or `~/.codev`. A shellper socket path also fits the Unix-socket limit. + - Gates 1 and 2 run before anything is created. +3. The fixture driver's `AGENT_FARM_DIR` is the isolated dir, and its `getGlobalDbPath()` is the + one `.db` file the isolated Tower has open (`lsof`). + - The driver re-checks this before every seed, and refuses before writing. +4. The only listener on the Tower port is the PID the harness spawned. `/api/version` answers the + isolated key, and a wrong key gets 401. +5. The serve-web Machine settings pin the port and turn auto-start off, and `afx`, `porch` and + `codev` resolve to the stubs in the serve-web environment. +6. After a seed, each fixture workspace's `/api/overview` lists exactly the expected builders (with + `spawnedByArchitect`) and architects. There is no fallback to faked data. + +## Teardown + +`stop` kills, by PID only: +- the recorded roots, each re-verified by its command line; +- the shellpers holding sockets in the run dir; +- previously recorded descendants whose command line is unchanged; +- all live descendants of those. + +It then checks that none of them is still alive. It also removes: +- the socket symlink; +- the runtime dirs (`af`, `run`, `home`, `fixtures`, `pids`, the VS Code server, user and + extensions dirs, and the browser profile); +- the state record. + +It keeps `logs/`, `shots/`, the vsix and the downloaded VS Code server cache (`cache/`). A failed +`start` runs the same teardown. + +If the tripwire fires, or a pre-flight gate refuses in a real run, stop and tell the architect +before retrying. + +## Scenarios + +`fixtures.mjs` defines them in `SCENARIOS`: +- `empty`: workspace `alpha`, not activated. `start` seeds it. +- `one-builder`: `alpha` activated, plus builder `spir-101` spawned by `main`. + +Later phases add scenarios here. diff --git a/apps/vscode/scripts/cockpit-harness/fixtures.mjs b/apps/vscode/scripts/cockpit-harness/fixtures.mjs new file mode 100644 index 000000000..e554c5d1c --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/fixtures.mjs @@ -0,0 +1,188 @@ +#!/usr/bin/env node +// Fixture driver for the cockpit harness. harness.mjs runs it as a child process whose environment +// is the isolated one (CODEV_AGENT_FARM_DIR, scratch HOME, NODE_ENV/AF_TEST_DB pinned), because the +// branch's dist resolves its database from the environment at import time. +// +// It creates state only through: +// - explicit-port HTTP calls to the isolated Tower (workspace activation, builder terminals); +// - the product's own in-process writers from the branch's built dist (porch state, the +// `builders` row through `upsertBuilder`, as `afx spawn` writes it); +// - git, in fixture repos under the harness's fixtures dir. +// It runs no Tower-contacting `afx` / `porch` command: those default to :4100. +// +// node fixtures.mjs probe → JSON { agentFarmDir, globalDbPath } (writes nothing) +// node fixtures.mjs seed → re-checks gate 3, then seeds the scenario +// +// SCENARIOS is also imported by harness.mjs (for the gate-6 expectations); the dist modules are +// imported lazily so that import loads nothing from the product. + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { REFUSAL_EXIT_CODE, Refusal, gateDbAgreement } from './preflight.mjs'; +import { run } from './procs.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const REPO = path.resolve(HERE, '../../../..'); +export const CODEV_DIST = path.join(REPO, 'packages/codev/dist'); + +/** Every fixture session is a plain shell: never an agent. */ +export const PLAIN_SHELL = ['/bin/bash', '--noprofile', '--norc']; +const PLAIN_HARNESS = 'cockpit-plain-shell'; + +/** + * Scenarios. A workspace is a git repo under the fixtures dir; `activate` starts it in the isolated + * Tower (which starts `main`). A builder gets a worktree, porch state, a live builder terminal and + * a `builders` row carrying `architect` as spawned_by_architect. + */ +export const SCENARIOS = { + empty: { + workspaces: [{ name: 'alpha', activate: false, architects: [], builders: [] }], + }, + 'one-builder': { + workspaces: [{ + name: 'alpha', + activate: true, + architects: ['main'], + builders: [{ project: '101', slug: 'fixture-one', architect: 'main' }], + }], + }, +}; + +export const roleIdFor = (builder) => `builder-spir-${builder.project}`; + +/** The gate-6 expectation for a scenario workspace. */ +export function expectedOverview(ws) { + return { + architects: ws.architects, + builders: ws.builders.map((b) => ({ roleId: roleIdFor(b), spawnedByArchitect: b.architect })), + }; +} + +function requireEnv(name) { + const value = process.env[name]; + if (!value) throw new Error(`${name} is not set (fixtures.mjs runs only under harness.mjs)`); + return value; +} + +async function loadDist(rel) { + return import(pathToFileURL(path.join(CODEV_DIST, rel)).href); +} + +/** What the branch's dist resolves in this process's environment. Writes nothing. */ +async function probe() { + const { AGENT_FARM_DIR } = await loadDist('agent-farm/lib/tower-client.js'); + const { getGlobalDbPath } = await loadDist('agent-farm/db/index.js'); + return { agentFarmDir: AGENT_FARM_DIR, globalDbPath: getGlobalDbPath() }; +} + +function git(cwd, args) { + const r = run('git', ['-c', 'user.name=cockpit-harness', '-c', 'user.email=cockpit-harness@localhost', ...args], { cwd }); + if (r.status !== 0) throw new Error(`git ${args.join(' ')} in ${cwd} failed: ${r.stderr}`); + return r.stdout; +} + +function ensureWorkspaceRepo(dir) { + if (fs.existsSync(path.join(dir, '.git'))) return; + fs.mkdirSync(path.join(dir, 'codev', 'projects'), { recursive: true }); + fs.mkdirSync(path.join(dir, '.codev'), { recursive: true }); + const shell = PLAIN_SHELL.join(' '); + const config = { + shell: { + architect: shell, + builder: shell, + shell, + architectHarness: PLAIN_HARNESS, + builderHarness: PLAIN_HARNESS, + }, + harness: { [PLAIN_HARNESS]: { roleArgs: [], roleScriptFragment: '' } }, + }; + fs.writeFileSync(path.join(dir, '.codev', 'config.json'), `${JSON.stringify(config, null, 2)}\n`); + fs.writeFileSync(path.join(dir, 'codev', 'README.md'), `# ${path.basename(dir)}\n\nCockpit-harness fixture workspace.\n`); + fs.writeFileSync(path.join(dir, '.gitignore'), '.builders/\n.architect-role.md\n'); + git(dir, ['init', '-q', '-b', 'main']); + git(dir, ['add', '.gitignore', '.codev/config.json', 'codev/README.md']); + git(dir, ['commit', '-q', '-m', 'fixture']); +} + +function tower() { + const port = Number(requireEnv('COCKPIT_TOWER_PORT')); + const key = requireEnv('COCKPIT_TOWER_KEY'); + return async (method, route, body) => { + const res = await fetch(`http://127.0.0.1:${port}${route}`, { + method, + headers: { 'codev-tower-key': key, 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await res.text(); + if (!res.ok) throw new Error(`${method} ${route} answered ${res.status}: ${text}`); + return text ? JSON.parse(text) : {}; + }; +} + +async function activate(call, dir) { + const enc = Buffer.from(dir).toString('base64url'); + const result = await call('POST', `/api/workspaces/${enc}/activate`, {}); + if (!result.success) throw new Error(`activating ${dir} failed: ${JSON.stringify(result)}`); + if (result.adopted) throw new Error(`activating ${dir} ran codev adopt; the fixture should already be a codev workspace`); +} + +async function seedBuilder(call, wsDir, builder) { + const name = `spir-${builder.project}`; + const worktree = path.join(wsDir, '.builders', name); + const branch = `builder/${name}`; + if (fs.existsSync(worktree)) throw new Error(`${worktree} already exists; seed scenarios onto a fresh harness`); + git(wsDir, ['worktree', 'add', '-q', '-b', branch, worktree]); + + const { loadProtocol } = await loadDist('commands/porch/protocol.js'); + const { createInitialState, getStatusPath, writeState } = await loadDist('commands/porch/state.js'); + const protocol = loadProtocol(worktree, 'spir'); + writeState(getStatusPath(worktree, builder.project, builder.slug), createInitialState(protocol, builder.project, builder.slug, worktree)); + + const roleId = roleIdFor(builder); + const [command, ...args] = PLAIN_SHELL; + const terminal = await call('POST', '/api/terminals', { + command, args, cwd: worktree, type: 'builder', roleId, workspacePath: wsDir, persistent: true, label: `Builder ${name}`, + }); + if (terminal.persistent !== true) throw new Error(`builder terminal for ${roleId} is not shellper-backed: ${JSON.stringify(terminal)}`); + + const { upsertBuilder } = await loadDist('agent-farm/state.js'); + upsertBuilder({ + id: roleId, name: builder.slug, status: 'implementing', phase: 'init', + worktree, branch, type: 'spec', issueNumber: builder.project, terminalId: terminal.id, + spawnedByArchitect: builder.architect, + }); +} + +async function seed(scenarioName) { + const scenario = SCENARIOS[scenarioName]; + if (!scenario) throw new Error(`unknown scenario '${scenarioName}' (known: ${Object.keys(SCENARIOS).join(', ')})`); + + // Gate 3, re-checked in this process before it writes anything. + const driver = await probe(); + gateDbAgreement({ driver, agentFarmDir: requireEnv('COCKPIT_EXPECT_AGENT_FARM_DIR'), towerPid: Number(requireEnv('COCKPIT_TOWER_PID')) }); + + const fixturesDir = requireEnv('COCKPIT_FIXTURES_DIR'); + const call = tower(); + for (const ws of scenario.workspaces) { + const dir = path.join(fixturesDir, ws.name); + ensureWorkspaceRepo(dir); + if (ws.activate) await activate(call, dir); + for (const builder of ws.builders) await seedBuilder(call, dir, builder); + } + const { closeAllDbs } = await loadDist('agent-farm/db/index.js'); + closeAllDbs(); +} + +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + const [cmd, arg] = process.argv.slice(2); + const main = async () => { + if (cmd === 'probe') console.log(JSON.stringify(await probe())); + else if (cmd === 'seed') await seed(arg); + else throw new Error('usage: fixtures.mjs probe | seed '); + }; + main().catch((err) => { + console.error(err instanceof Refusal ? err.message : `fixtures error: ${err.stack ?? err}`); + process.exit(err instanceof Refusal ? REFUSAL_EXIT_CODE : 1); + }); +} diff --git a/apps/vscode/scripts/cockpit-harness/harness.mjs b/apps/vscode/scripts/cockpit-harness/harness.mjs new file mode 100644 index 000000000..4a0c543c4 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/harness.mjs @@ -0,0 +1,748 @@ +#!/usr/bin/env node +// Cockpit verification harness: an isolated Tower + an isolated VS Code (serve-web) running the +// branch's vsix, for rendered verification that never touches the owner's Tower (:4100), agent-farm +// dir, socket dir or IDE. See README.md. +// +// node harness.mjs build-vsix build the branch vsix into the harness root +// node harness.mjs start pre-flight, isolated Tower, `empty` fixture, serve-web, tripwire +// node harness.mjs seed seed a fixture scenario, then assert gate 6 on its overview +// node harness.mjs check re-run gates 3-5 and prove the extension runs against the Tower +// node harness.mjs stop kill only the harness's own PIDs; remove the runtime dirs +// node harness.mjs selftest prove every refusal and the tripwire +// +// Inputs (environment): COCKPIT_SCRATCH (the session scratchpad), COCKPIT_TOWER_PORT, +// COCKPIT_WEB_PORT; optional CODEV_AGENT_FARM_DIR / SHELLPER_SOCKET_DIR overrides (still gated). + +import { spawn, spawnSync } from 'node:child_process'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + OWNER_TOWER_PORT, REFUSAL_EXIT_CODE, Refusal, gateDbAgreement, gateDirs, gateListener, gateOverview, + gatePort, gateVscodeProfile, isWithin, realpathLoose, +} from './preflight.mjs'; +import { descendants, isAlive, killPids, listenerPids, processTable, run, tcpOn, unixSocketHolders } from './procs.mjs'; +import { CODEV_DIST, REPO, SCENARIOS, expectedOverview } from './fixtures.mjs'; +import { TRIPWIRE_EXIT_CODE, sample } from './tripwire.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const STUBS = path.join(HERE, 'stubs'); +const VSCODE_APP = path.join(REPO, 'apps/vscode'); +const TOWER_SERVER = path.join(CODEV_DIST, 'agent-farm/servers/tower-server.js'); +const CODE_BIN = process.env.COCKPIT_CODE_BIN || '/usr/local/bin/code'; +const REAL_HOME = os.homedir(); +const PLAYWRIGHT_BROWSERS = path.join(REAL_HOME, 'Library/Caches/ms-playwright'); +/** The vsix's inputs: what has to be unchanged since build-vsix for the install to be "the branch's". */ +const VSIX_INPUTS = ['apps/vscode', ':(exclude)apps/vscode/scripts/cockpit-harness', 'packages', 'pnpm-lock.yaml']; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// --------------------------------------------------------------------------------------------- +// Layout and environment +// --------------------------------------------------------------------------------------------- + +/** Every path the harness owns, under `/cockpit-harness`. */ +function layout(scratch) { + const root = path.join(scratch, 'cockpit-harness'); + const vscode = path.join(root, 'vscode'); + return { + scratch, root, vscode, + af: path.join(root, 'af'), + run: path.join(root, 'run'), + home: path.join(root, 'home'), + fixtures: path.join(root, 'fixtures'), + pids: path.join(root, 'pids'), + logs: path.join(root, 'logs'), + shots: path.join(root, 'shots'), + vscodeCli: path.join(root, 'cache', 'vscode-cli'), + vscodeServer: path.join(vscode, 'server'), + vscodeUser: path.join(vscode, 'user'), + vscodeExt: path.join(vscode, 'ext'), + browserProfile: path.join(root, 'browser-profile'), + state: path.join(root, 'state.json'), + tripMarker: path.join(root, 'tripwire.tripped'), + stubLog: path.join(root, 'logs', 'stub-calls.jsonl'), + vsix: path.join(root, 'codev-vscode.vsix'), + vsixMeta: path.join(root, 'codev-vscode.vsix.json'), + }; +} + +/** Runtime dirs `stop` removes. Logs, screenshots, the vsix and the VS Code server cache stay. */ +const RUNTIME_DIRS = ['af', 'run', 'home', 'fixtures', 'pids', 'vscode', 'browserProfile']; + +function scratchFromEnv() { + const raw = process.env.COCKPIT_SCRATCH; + if (!raw) throw new Refusal(2, 'COCKPIT_SCRATCH is not set'); + if (!fs.existsSync(raw) || !fs.statSync(raw).isDirectory()) throw new Refusal(2, `COCKPIT_SCRATCH=${raw} is not a directory`); + const scratch = fs.realpathSync(raw); + const tempRoots = ['/private/tmp', '/private/var/folders', fs.realpathSync(os.tmpdir())]; + if (!tempRoots.some((t) => isWithin(scratch, t))) throw new Refusal(2, `COCKPIT_SCRATCH=${scratch} is not under a temp root`); + return scratch; +} + +function codevVersion() { + return JSON.parse(fs.readFileSync(path.join(REPO, 'packages/codev/package.json'), 'utf-8')).version; +} + +/** + * A child environment built from an allowlist, never the caller's whole environment: no + * CODEV_*, CLAUDE_CODE_*, VSCODE_*, NODE_ENV, AF_TEST_DB, BRIDGE_* or token variables leak in. + * HOME is the harness's scratch home; the stubs come first on PATH. + */ +function childEnv(L, caller, extra = {}) { + const env = { + PATH: `${STUBS}:${process.env.PATH}`, + HOME: L.home, + USER: process.env.USER, + LOGNAME: process.env.LOGNAME, + LANG: process.env.LANG || 'en_US.UTF-8', + TMPDIR: process.env.TMPDIR, + SHELL: '/bin/bash', + TERM: 'xterm-256color', + COCKPIT_STUB_LOG: L.stubLog, + COCKPIT_STUB_CALLER: caller, + COCKPIT_CODEV_VERSION: codevVersion(), + ...extra, + }; + for (const k of Object.keys(env)) if (env[k] === undefined) delete env[k]; + return env; +} + +function towerEnv(L, run) { + return childEnv(L, 'tower', { CODEV_AGENT_FARM_DIR: run.agentFarmDir, SHELLPER_SOCKET_DIR: run.socketDir }); +} + +function driverEnv(L, run, st, extra = {}) { + return childEnv(L, 'driver', { + CODEV_AGENT_FARM_DIR: run.agentFarmDir, + COCKPIT_EXPECT_AGENT_FARM_DIR: run.agentFarmDir, + COCKPIT_TOWER_PORT: String(run.towerPort), + COCKPIT_TOWER_PID: String(st.towerPid), + COCKPIT_TOWER_KEY: readKey(run), + COCKPIT_FIXTURES_DIR: L.fixtures, + ...extra, + }); +} + +function webEnv(L, run) { + return childEnv(L, 'vscode', { CODEV_TOWER_KEY: readKey(run) }); +} + +function readKey(run) { + const keyFile = path.join(run.agentFarmDir, 'local-key'); + if (!fs.existsSync(keyFile)) throw new Error(`the isolated Tower has not written ${keyFile}`); + return fs.readFileSync(keyFile, 'utf-8').trim(); +} + +// --------------------------------------------------------------------------------------------- +// State and pid files +// --------------------------------------------------------------------------------------------- + +function loadState(L) { + if (!fs.existsSync(L.state)) throw new Error(`no harness recorded at ${L.state} (run start)`); + return JSON.parse(fs.readFileSync(L.state, 'utf-8')); +} + +function saveState(L, st) { + fs.writeFileSync(L.state, `${JSON.stringify(st, null, 2)}\n`); +} + +/** Record a launched process: the tripwire watches it and `stop` may kill it once `markers` match. */ +function writePid(L, name, pid, markers) { + fs.mkdirSync(L.pids, { recursive: true }); + fs.writeFileSync(path.join(L.pids, `${name}.json`), JSON.stringify({ pid, markers })); +} + +function removePid(L, name) { + fs.rmSync(path.join(L.pids, `${name}.json`), { force: true }); +} + +function readPidFiles(L) { + if (!fs.existsSync(L.pids)) return []; + return fs.readdirSync(L.pids).filter((f) => f.endsWith('.json')) + .map((f) => ({ name: f.slice(0, -5), ...JSON.parse(fs.readFileSync(path.join(L.pids, f), 'utf-8')) })); +} + +/** Snapshot every live process the harness owns, so `stop` can find one even if its parent died. */ +function recordKnownPids(L, st) { + const { pids, table } = ownedPids(L, st); + st.knownPids = [...pids].map((pid) => ({ pid, command: table.get(pid)?.command ?? '' })); + saveState(L, st); +} + +/** Every spelling under which a harness shellper socket can appear in lsof. */ +function socketPrefixes(L, st) { + const prefixes = [L.run]; + if (st?.socketDir) { + prefixes.push(st.socketDir); + if (st.socketDir.startsWith('/tmp/')) prefixes.push(`/private${st.socketDir}`); + } + return prefixes; +} + +/** + * The harness's live processes: pid-file roots whose command still carries their markers, the + * shellpers (holders of a Unix socket in the harness's socket dir), previously recorded processes + * whose command is unchanged, and all descendants. The calling CLI process is never included. + */ +function ownedPids(L, st) { + const table = processTable(); + const roots = new Set(); + const skipped = []; + for (const rec of readPidFiles(L)) { + if (rec.name.startsWith('cli-')) continue; + const cmd = table.get(rec.pid)?.command; + if (cmd && rec.markers.every((m) => cmd.includes(m))) roots.add(rec.pid); + else if (cmd) skipped.push(`${rec.name}: pid ${rec.pid} now runs '${cmd}'`); + } + if (st) for (const pid of unixSocketHolders(socketPrefixes(L, st))) roots.add(pid); + for (const known of st?.knownPids ?? []) { + if (table.get(known.pid)?.command === known.command) roots.add(known.pid); + } + const pids = descendants(roots, table); + for (const pid of [process.pid, process.ppid]) pids.delete(pid); + return { pids, table, skipped }; +} + +// --------------------------------------------------------------------------------------------- +// Process launch helpers +// --------------------------------------------------------------------------------------------- + +function launch(L, name, cmd, args, { env, cwd, markers }) { + fs.mkdirSync(L.logs, { recursive: true }); + const out = fs.openSync(path.join(L.logs, `${name}.log`), 'a'); + const child = spawn(cmd, args, { env, cwd, detached: true, stdio: ['ignore', out, out] }); + fs.closeSync(out); + child.unref(); + if (!child.pid) throw new Error(`failed to launch ${name}`); + writePid(L, name, child.pid, markers); + return child.pid; +} + +async function waitForListener(port, owner, timeoutMs, what) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (!isAlive(owner)) throw new Error(`${what} (pid ${owner}) exited before listening on ${port}`); + if (listenerPids(port).length) return; + await sleep(500); + } + throw new Error(`${what} did not listen on ${port} within ${timeoutMs / 1000}s`); +} + +/** Run the fixture driver synchronously in the isolated environment. */ +function runDriver(L, runCfg, st, args, extraEnv = {}) { + const r = spawnSync(process.execPath, [path.join(HERE, 'fixtures.mjs'), ...args], { + env: driverEnv(L, runCfg, st, extraEnv), cwd: L.home, encoding: 'utf-8', timeout: 180_000, + }); + if (r.error) throw r.error; + return { status: r.status, stdout: r.stdout, stderr: r.stderr }; +} + +function probeDriver(L, runCfg, st) { + const r = runDriver(L, runCfg, st, ['probe']); + if (r.status !== 0) throw new Error(`fixture driver probe failed: ${r.stderr}`); + return JSON.parse(r.stdout); +} + +// --------------------------------------------------------------------------------------------- +// Planning (pure: gates 1 and 2 plus input checks, nothing created) +// --------------------------------------------------------------------------------------------- + +function planRun({ needWeb }) { + const scratch = scratchFromEnv(); + const L = layout(scratch); + const towerPort = gatePort('COCKPIT_TOWER_PORT', process.env.COCKPIT_TOWER_PORT); + let webPort = null; + if (needWeb) { + webPort = gatePort('COCKPIT_WEB_PORT', process.env.COCKPIT_WEB_PORT); + if (webPort === towerPort) throw new Refusal(1, 'COCKPIT_WEB_PORT equals COCKPIT_TOWER_PORT'); + } + const agentFarmDir = process.env.CODEV_AGENT_FARM_DIR || L.af; + const socketLink = process.env.SHELLPER_SOCKET_DIR ? null : `/tmp/cckp-${crypto.randomBytes(4).toString('hex')}`; + const socketDir = process.env.SHELLPER_SOCKET_DIR || socketLink; + gateDirs({ scratch, agentFarmDir, socketDir, socketLinkTarget: socketLink ? L.run : undefined }); + if (fs.existsSync(L.state)) throw new Error(`a harness is already recorded at ${L.state}; run stop first`); + if (!fs.existsSync(TOWER_SERVER)) throw new Error(`${TOWER_SERVER} is missing: build packages/codev first`); + if (needWeb) { + if (!fs.existsSync(L.vsix)) throw new Error(`no vsix at ${L.vsix}: run build-vsix first`); + if (!fs.existsSync(CODE_BIN)) throw new Error(`no VS Code CLI at ${CODE_BIN} (set COCKPIT_CODE_BIN)`); + } + return { L, towerPort, webPort, agentFarmDir, socketDir, socketLink }; +} + +// --------------------------------------------------------------------------------------------- +// Bring-up +// --------------------------------------------------------------------------------------------- + +/** Create the state record and dirs, then the isolated Tower; gates 2 (again), 4 and 3. */ +async function bringUpTower(runCfg) { + const { L } = runCfg; + for (const dir of [L.root, L.af, L.run, L.home, L.fixtures, L.pids, L.logs, L.shots]) fs.mkdirSync(dir, { recursive: true }); + const st = { + startedAt: new Date().toISOString(), + towerPort: runCfg.towerPort, webPort: runCfg.webPort, + agentFarmDir: runCfg.agentFarmDir, socketDir: runCfg.socketDir, socketLink: runCfg.socketLink, + towerPid: null, webPid: null, tripwirePid: null, knownPids: [], + }; + saveState(L, st); + if (runCfg.socketLink) { + fs.symlinkSync(L.run, runCfg.socketLink); + gateDirs({ scratch: L.scratch, agentFarmDir: runCfg.agentFarmDir, socketDir: runCfg.socketDir }); + } + st.towerPid = launch(L, 'tower', process.execPath, [TOWER_SERVER, '-p', String(runCfg.towerPort)], { + env: towerEnv(L, runCfg), cwd: L.home, markers: ['tower-server.js', `-p ${runCfg.towerPort}`], + }); + saveState(L, st); + await waitForListener(runCfg.towerPort, st.towerPid, 30_000, 'isolated Tower'); + st.towerVersion = await gateListener({ port: runCfg.towerPort, pid: st.towerPid, key: readKey(runCfg) }); + st.globalDb = gateDbAgreement({ driver: probeDriver(L, runCfg, st), agentFarmDir: runCfg.agentFarmDir, towerPid: st.towerPid }); + saveState(L, st); + return st; +} + +/** Unpack the vsix as an installed extension (as the spike installed its extension). */ +function installVsix(L) { + const pkg = JSON.parse(fs.readFileSync(path.join(VSCODE_APP, 'package.json'), 'utf-8')); + const id = `${pkg.publisher}.${pkg.name}`; + const folder = `${id}-${pkg.version}`; + const dest = path.join(L.vscodeExt, folder); + const unpack = path.join(L.vscodeExt, '.unpack'); + fs.rmSync(unpack, { recursive: true, force: true }); + fs.mkdirSync(unpack, { recursive: true }); + const r = run('unzip', ['-q', L.vsix, 'extension/*', '-d', unpack]); + if (r.status !== 0) throw new Error(`unzip ${L.vsix} failed: ${r.stderr}`); + fs.rmSync(dest, { recursive: true, force: true }); + fs.renameSync(path.join(unpack, 'extension'), dest); + fs.rmSync(unpack, { recursive: true, force: true }); + const installed = JSON.parse(fs.readFileSync(path.join(dest, 'package.json'), 'utf-8')); + if (installed.version !== pkg.version || installed.name !== pkg.name) { + throw new Error(`the vsix holds ${installed.name}@${installed.version}, not the branch's ${pkg.name}@${pkg.version}`); + } + const entry = { identifier: { id }, version: pkg.version, location: { $mid: 1, path: dest, scheme: 'file' }, relativeLocation: folder }; + fs.writeFileSync(path.join(L.vscodeExt, 'extensions.json'), JSON.stringify([entry])); + return { id, version: pkg.version, dest, vsixSha256: sha256(L.vsix) }; +} + +function sha256(file) { + return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); +} + +function writeMachineSettings(L, towerPort) { + const dir = path.join(L.vscodeUser, 'Machine'); + fs.mkdirSync(dir, { recursive: true }); + const settings = { 'codev.towerPort': towerPort, 'codev.autoStartTower': false, 'files.autoSave': 'off' }; + const file = path.join(dir, 'settings.json'); + fs.writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`); + return file; +} + +async function bringUpVscode(runCfg, st) { + const { L } = runCfg; + st.extension = installVsix(L); + st.settingsPath = writeMachineSettings(L, runCfg.towerPort); + const env = webEnv(L, runCfg); + gateVscodeProfile({ settingsPath: st.settingsPath, port: runCfg.towerPort, env, stubsDir: STUBS }); + fs.mkdirSync(L.vscodeCli, { recursive: true }); + st.webPid = launch(L, 'serve-web', CODE_BIN, [ + 'serve-web', '--host', '127.0.0.1', '--port', String(runCfg.webPort), + '--without-connection-token', '--accept-server-license-terms', + '--cli-data-dir', L.vscodeCli, '--server-data-dir', L.vscodeServer, + '--user-data-dir', L.vscodeUser, '--extensions-dir', L.vscodeExt, + ], { env, cwd: L.home, markers: ['serve-web', `--port ${runCfg.webPort}`] }); + saveState(L, st); + await waitForListener(runCfg.webPort, st.webPid, 300_000, 'serve-web'); + saveState(L, st); +} + +function startTripwire(L, st) { + st.tripwirePid = launch(L, 'tripwire', process.execPath, [ + path.join(HERE, 'tripwire.mjs'), 'watch', '--port', String(OWNER_TOWER_PORT), '--pids', L.pids, + '--marker', L.tripMarker, ...socketPrefixes(L, st).flatMap((p) => ['--socket-prefix', p]), '--interval', '1000', + ], { env: childEnv(L, 'tripwire'), cwd: L.home, markers: ['tripwire.mjs', 'watch'] }); + saveState(L, st); +} + +function runCfgFromState(L, st) { + return { L, towerPort: st.towerPort, webPort: st.webPort, agentFarmDir: st.agentFarmDir, socketDir: st.socketDir, socketLink: st.socketLink }; +} + +// --------------------------------------------------------------------------------------------- +// Commands +// --------------------------------------------------------------------------------------------- + +async function cmdStart() { + const runCfg = planRun({ needWeb: true }); + const { L } = runCfg; + let st; + try { + st = await bringUpTower(runCfg); + writePid(L, `cli-${process.pid}`, process.pid, []); + console.log(`isolated Tower ${st.towerVersion} up on :${runCfg.towerPort} (pid ${st.towerPid}), db ${st.globalDb}`); + startTripwire(L, st); + await seedScenario(L, runCfg, st, 'empty'); + await bringUpVscode(runCfg, st); + console.log(`serve-web up on :${runCfg.webPort} (pid ${st.webPid}) with ${st.extension.id}@${st.extension.version}`); + assertTripwireClean(L, st); + recordKnownPids(L, st); + removePid(L, `cli-${process.pid}`); + console.log(`harness started; workbench: ${workbenchUrl(L, st)}`); + } catch (err) { + console.error(`start failed: ${err.message}; tearing down`); + await teardown(L); + throw err; + } +} + +function workbenchUrl(L, st) { + return `http://127.0.0.1:${st.webPort}/?folder=${encodeURIComponent(path.join(L.fixtures, 'alpha'))}`; +} + +async function seedScenario(L, runCfg, st, name) { + const scenario = SCENARIOS[name]; + if (!scenario) throw new Error(`unknown scenario '${name}' (known: ${Object.keys(SCENARIOS).join(', ')})`); + const r = runDriver(L, runCfg, st, ['seed', name]); + if (r.status !== 0) { + const err = r.status === REFUSAL_EXIT_CODE ? new Refusal(3, r.stderr.trim()) : new Error(`seeding '${name}' failed: ${r.stderr}`); + throw err; + } + const key = readKey(runCfg); + for (const ws of scenario.workspaces) { + const dir = path.join(L.fixtures, ws.name); + const want = expectedOverview(ws); + await gateOverview({ port: runCfg.towerPort, key, workspace: dir, ...want }); + console.log(`gate 6: ${ws.name} overview has builders ${JSON.stringify(want.builders)} and architects ${JSON.stringify(want.architects)}`); + } +} + +async function cmdSeed(name) { + const L = layout(scratchFromEnv()); + const st = loadState(L); + assertTripwireClean(L, st); + writePid(L, `cli-${process.pid}`, process.pid, []); + try { + await seedScenario(L, runCfgFromState(L, st), st, name); + } finally { + removePid(L, `cli-${process.pid}`); + } + assertTripwireClean(L, st); + recordKnownPids(L, st); +} + +function assertTripwireClean(L, st) { + if (fs.existsSync(L.tripMarker)) throw new Error(`TRIPWIRE FIRED: ${fs.readFileSync(L.tripMarker, 'utf-8')}`); + if (!st.tripwirePid || !isAlive(st.tripwirePid)) throw new Error(`the tripwire (pid ${st.tripwirePid}) is not running`); +} + +/** git: the vsix's inputs are unchanged since build-vsix (committed and in the working tree). */ +function vsixIsCurrent(L) { + if (!fs.existsSync(L.vsixMeta)) return `no build record ${L.vsixMeta}`; + const meta = JSON.parse(fs.readFileSync(L.vsixMeta, 'utf-8')); + if (meta.sha256 !== sha256(L.vsix)) return 'the vsix changed after build-vsix recorded it'; + const committed = run('git', ['diff', '--quiet', meta.head, 'HEAD', '--', ...VSIX_INPUTS], { cwd: REPO }); + if (committed.status !== 0) return `vsix inputs changed between ${meta.head.slice(0, 8)} and HEAD`; + const working = run('git', ['diff', '--quiet', 'HEAD', '--', ...VSIX_INPUTS], { cwd: REPO }); + if (working.status !== 0) return 'vsix inputs have uncommitted changes'; + return null; +} + +async function cmdCheck() { + const L = layout(scratchFromEnv()); + const st = loadState(L); + const runCfg = runCfgFromState(L, st); + const results = []; + const item = async (name, fn) => { + try { + const detail = await fn(); + results.push({ name, ok: true, detail }); + } catch (err) { + results.push({ name, ok: false, detail: err.message }); + } + }; + writePid(L, `cli-${process.pid}`, process.pid, []); + try { + await item('tripwire running and not tripped', () => { assertTripwireClean(L, st); return `pid ${st.tripwirePid}`; }); + await item('gate 4: Tower on its port is the harness pid and answers the isolated key', async () => + `pid ${st.towerPid}, version ${await gateListener({ port: st.towerPort, pid: st.towerPid, key: readKey(runCfg) })}`); + await item('gate 3: fixture driver and Tower agree on the db', () => + gateDbAgreement({ driver: probeDriver(L, runCfg, st), agentFarmDir: st.agentFarmDir, towerPid: st.towerPid })); + await item('gate 5: profile pins the Tower port, auto-start off, stubs resolve', () => { + gateVscodeProfile({ settingsPath: st.settingsPath, port: st.towerPort, env: webEnv(L, runCfg), stubsDir: STUBS }); + return st.settingsPath; + }); + await item('serve-web listener belongs to the harness', () => { + const tree = descendants([st.webPid]); + const listeners = listenerPids(st.webPort); + if (!listeners.length || !listeners.every((p) => tree.has(p))) throw new Error(`listeners ${listeners} not in serve-web tree`); + return `pid ${listeners.join(', ')}`; + }); + await item('installed extension is the branch vsix', () => { + const stale = vsixIsCurrent(L); + if (stale) throw new Error(stale); + const entries = JSON.parse(fs.readFileSync(path.join(L.vscodeExt, 'extensions.json'), 'utf-8')); + const codev = entries.filter((e) => e.identifier.id === st.extension.id); + if (codev.length !== 1 || codev[0].location.path !== st.extension.dest) { + throw new Error(`extensions.json lists ${JSON.stringify(codev)}`); + } + return `${st.extension.id}@${st.extension.version}, vsix ${st.extension.vsixSha256.slice(0, 12)}`; + }); + await item('workbench loads and the Codev extension activates', () => runWorkbenchCheck(L, st, 'check-workbench')); + await item('extension host is connected to the isolated Tower', async () => { + const deadline = Date.now() + 30_000; + for (;;) { + const tree = descendants([st.webPid]); + const conns = tcpOn(st.towerPort, 'ESTABLISHED').filter((p) => tree.has(p.pid)); + if (conns.length) return `pids ${[...new Set(conns.map((c) => c.pid))].join(', ')}`; + if (Date.now() > deadline) throw new Error(`no serve-web process holds a connection to :${st.towerPort}`); + await sleep(1000); + } + }); + await item('extension preflight ran the codev stub', () => { + const calls = fs.existsSync(L.stubLog) ? fs.readFileSync(L.stubLog, 'utf-8').trim().split('\n').filter(Boolean).map(JSON.parse) : []; + const hit = calls.find((c) => c.caller === 'vscode' && c.tool === 'codev' && c.argv.join(' ') === '--version'); + if (!hit) throw new Error(`no 'codev --version' from the vscode caller in ${calls.length} recorded calls`); + return `${calls.length} recorded call(s)`; + }); + await item('tripwire sample now: nothing of ours on :4100', () => { + const { treeSize, violations } = sample({ port: OWNER_TOWER_PORT, pidsDir: L.pids, socketPrefixes: socketPrefixes(L, st) }); + if (violations.length) throw new Error(JSON.stringify(violations)); + assertTripwireClean(L, st); + return `tree of ${treeSize}`; + }); + } finally { + removePid(L, `cli-${process.pid}`); + } + recordKnownPids(L, st); + for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name}${r.detail ? ` — ${r.detail}` : ''}`); + const failed = results.filter((r) => !r.ok).length; + console.log(failed ? `check FAILED (${failed} of ${results.length})` : `check passed (${results.length} items)`); + if (failed) process.exitCode = 1; +} + +/** Drive the workbench headless; returns a detail string or throws with the driver's error. */ +function runWorkbenchCheck(L, st, name) { + const out = path.join(L.logs, `${name}.json`); + const shot = path.join(L.shots, `${name}.png`); + const r = spawnSync(process.execPath, [ + path.join(HERE, 'workbench.mjs'), 'check', '--url', workbenchUrl(L, st), '--profile', L.browserProfile, + '--shot', shot, '--out', out, '--owner-port', String(OWNER_TOWER_PORT), + ], { env: childEnv(L, 'workbench', { PLAYWRIGHT_BROWSERS_PATH: PLAYWRIGHT_BROWSERS }), cwd: L.home, encoding: 'utf-8', timeout: 420_000 }); + if (r.error) throw r.error; + const result = fs.existsSync(out) ? JSON.parse(fs.readFileSync(out, 'utf-8')) : null; + if (r.status !== 0 || !result?.ok) throw new Error(`workbench check failed: ${result?.error ?? r.stderr}`); + return `screenshot ${shot}${result.trustAccepted ? ' (trust prompt accepted)' : ''}`; +} + +/** + * Kill only the harness's own processes (by PID, each re-verified), remove the socket symlink + * (always, even after a failed start), and, when nothing survived, the runtime dirs and state + * record. Logs, screenshots and a tripwire marker are kept. Returns survivors. + */ +async function teardown(L) { + const st = fs.existsSync(L.state) ? JSON.parse(fs.readFileSync(L.state, 'utf-8')) : null; + const { pids, skipped } = ownedPids(L, st); + for (const s of skipped) console.log(`not killing ${s}`); + if (st?.towerPid && isAlive(st.towerPid)) { + // Cross-check: the terminals the isolated Tower lists should all be in the kill set. + try { + const res = await fetch(`http://127.0.0.1:${st.towerPort}/api/terminals`, { headers: { 'codev-tower-key': readKey(runCfgFromState(L, st)) } }); + const { terminals } = await res.json(); + for (const t of terminals ?? []) if (t.pid && !pids.has(t.pid)) console.log(`warning: Tower lists terminal pid ${t.pid} outside the owned set`); + } catch (err) { + console.log(`warning: could not list the isolated Tower's terminals: ${err.message}`); + } + } + const survivors = await killPids([...pids]); + if (st?.socketLink && fs.lstatSync(st.socketLink, { throwIfNoEntry: false })?.isSymbolicLink()) fs.unlinkSync(st.socketLink); + const after = ownedPids(L, st).pids; + const left = [...new Set([...survivors, ...after])]; + console.log(`teardown: killed ${pids.size} pid(s)${left.length ? `; STILL ALIVE: ${left.join(', ')}` : '; none left'}`); + if (!left.length) { + for (const key of RUNTIME_DIRS) fs.rmSync(L[key], { recursive: true, force: true }); + fs.rmSync(L.state, { force: true }); + } + return left; +} + +async function cmdStop() { + const L = layout(scratchFromEnv()); + const tripped = fs.existsSync(L.tripMarker) ? fs.readFileSync(L.tripMarker, 'utf-8') : null; + const left = await teardown(L); + if (tripped) console.log(`NOTE: the tripwire had fired during this run:\n${tripped}`); + if (left.length) process.exitCode = 1; +} + +async function cmdBuildVsix() { + const L = layout(scratchFromEnv()); + fs.mkdirSync(L.root, { recursive: true }); + const head = run('git', ['rev-parse', 'HEAD'], { cwd: REPO }).stdout.trim(); + const dirty = run('git', ['diff', '--quiet', 'HEAD', '--', ...VSIX_INPUTS], { cwd: REPO }).status !== 0; + const r = spawnSync('pnpm', ['exec', 'vsce', 'package', '--no-dependencies', '--out', L.vsix], { cwd: VSCODE_APP, stdio: 'inherit' }); + if (r.status !== 0) throw new Error(`vsce package failed (${r.status})`); + fs.writeFileSync(L.vsixMeta, `${JSON.stringify({ head, dirtyAtBuild: dirty, sha256: sha256(L.vsix), builtAt: new Date().toISOString() }, null, 2)}\n`); + console.log(`built ${L.vsix} at ${head.slice(0, 8)}${dirty ? ' (with uncommitted input changes)' : ''}`); +} + +// --------------------------------------------------------------------------------------------- +// Self-test +// --------------------------------------------------------------------------------------------- + +/** A throwaway listener in a separate process; resolves with { pid, port, kill }. */ +function foreignListener() { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['-e', + "const s=require('net').createServer(c=>{}).listen(0,'127.0.0.1',()=>console.log(s.address().port))"], { stdio: ['ignore', 'pipe', 'inherit'] }); + child.stdout.once('data', (d) => resolve({ pid: child.pid, port: Number(String(d).trim()), kill: () => child.kill('SIGKILL') })); + child.once('error', reject); + }); +} + +async function selftest() { + const scratch = scratchFromEnv(); + const towerPort = gatePort('COCKPIT_TOWER_PORT', process.env.COCKPIT_TOWER_PORT); + const webPort = gatePort('COCKPIT_WEB_PORT', process.env.COCKPIT_WEB_PORT); + const base = path.join(scratch, 'cockpit-harness-selftest'); + fs.rmSync(base, { recursive: true, force: true }); + fs.mkdirSync(base, { recursive: true }); + const results = []; + const record = (name, ok, detail) => { + results.push({ name, ok, detail }); + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); + }; + + // --- Gates 1 and 2: `start` refuses before creating anything. --- + const busy = await foreignListener(); + const outsideAf = path.join(REPO, 'tmp-cockpit-selftest-af'); + const outsideSock = `/tmp/cckp-selftest-${crypto.randomBytes(3).toString('hex')}`; + const longSockName = 'socket-dir-with-a-deliberately-long-name-to-exceed-the-unix-socket-path-limit'; + const cases = [ + ['gate 1 refuses COCKPIT_TOWER_PORT=4100', { COCKPIT_TOWER_PORT: '4100' }, 1], + ['gate 1 refuses a non-numeric port', { COCKPIT_TOWER_PORT: '18x64' }, 1], + ['gate 1 refuses a port that already has a listener', { COCKPIT_TOWER_PORT: String(busy.port) }, 1], + ['gate 2 refuses CODEV_AGENT_FARM_DIR=~/.agent-farm', { CODEV_AGENT_FARM_DIR: path.join(REAL_HOME, '.agent-farm') }, 2], + ['gate 2 refuses an agent-farm dir outside the scratchpad', { CODEV_AGENT_FARM_DIR: outsideAf }, 2], + ['gate 2 refuses SHELLPER_SOCKET_DIR=~/.codev/run', { SHELLPER_SOCKET_DIR: path.join(REAL_HOME, '.codev', 'run') }, 2], + ['gate 2 refuses a socket dir outside the scratchpad', { SHELLPER_SOCKET_DIR: outsideSock }, 2], + ['gate 2 refuses a socket dir too long for a Unix socket', (caseScratch) => ({ SHELLPER_SOCKET_DIR: path.join(caseScratch, longSockName) }), 2], + ]; + let n = 0; + for (const [name, overridesFor, gate] of cases) { + const caseScratch = path.join(base, `case-${++n}`); + fs.mkdirSync(caseScratch); + const overrides = typeof overridesFor === 'function' ? overridesFor(caseScratch) : overridesFor; + const env = { ...process.env, COCKPIT_SCRATCH: caseScratch, COCKPIT_TOWER_PORT: String(towerPort), COCKPIT_WEB_PORT: String(webPort), ...overrides }; + for (const k of ['CODEV_AGENT_FARM_DIR', 'SHELLPER_SOCKET_DIR']) if (!(k in overrides)) delete env[k]; + const r = spawnSync(process.execPath, [path.join(HERE, 'harness.mjs'), 'start'], { env, encoding: 'utf-8', timeout: 60_000 }); + const problems = []; + if (r.status !== REFUSAL_EXIT_CODE) problems.push(`exit ${r.status}, expected ${REFUSAL_EXIT_CODE}`); + if (!r.stderr.includes(`pre-flight gate ${gate} refused`)) problems.push(`stderr lacks 'gate ${gate} refused': ${r.stderr.trim()}`); + if (fs.readdirSync(caseScratch).length) problems.push(`created ${fs.readdirSync(caseScratch).join(', ')}`); + for (const p of [outsideAf, outsideSock]) if (fs.existsSync(p)) problems.push(`created ${p}`); + for (const p of [towerPort, webPort]) if (listenerPids(p).length) problems.push(`something listens on ${p}`); + record(name, !problems.length, problems.join('; ') || r.stderr.trim().split('\n').pop()); + } + busy.kill(); + + // --- Gates 3 and 4 against a real isolated Tower. --- + process.env.COCKPIT_SCRATCH = path.join(base, 'tower'); + fs.mkdirSync(process.env.COCKPIT_SCRATCH); + delete process.env.CODEV_AGENT_FARM_DIR; + delete process.env.SHELLPER_SOCKET_DIR; + const runCfg = planRun({ needWeb: false }); + const { L } = runCfg; + try { + const st = await bringUpTower(runCfg); + record('isolated Tower passes gates 2-4 (positive control)', true, `pid ${st.towerPid}, db ${st.globalDb}`); + + const r = runDriver(L, runCfg, st, ['seed', 'one-builder'], { NODE_ENV: 'test' }); + const testDb = path.join(runCfg.agentFarmDir, 'test.db'); + const problems = []; + if (r.status !== REFUSAL_EXIT_CODE) problems.push(`exit ${r.status}: ${r.stderr.trim()}`); + if (!r.stderr.includes('pre-flight gate 3 refused')) problems.push(`stderr: ${r.stderr.trim()}`); + if (fs.existsSync(testDb)) problems.push(`created ${testDb}`); + if (fs.readdirSync(L.fixtures).length) problems.push(`created fixtures ${fs.readdirSync(L.fixtures).join(', ')}`); + record('gate 3 refuses a NODE_ENV=test driver against the production-mode Tower', !problems.length, problems.join('; ') || r.stderr.trim()); + + const foreign = await foreignListener(); + try { + await gateListener({ port: foreign.port, pid: st.towerPid, key: readKey(runCfg) }); + record('gate 4 refuses a listener that is not the harness\'s', false, 'gate 4 passed'); + } catch (err) { + record('gate 4 refuses a listener that is not the harness\'s', err instanceof Refusal && err.gate === 4, err.message); + } finally { + foreign.kill(); + } + } catch (err) { + record('isolated Tower bring-up', false, err.message); + } finally { + const left = await teardown(L); + const linkGone = !runCfg.socketLink || !fs.lstatSync(runCfg.socketLink, { throwIfNoEntry: false }); + record('selftest Tower torn down by PID, socket link removed', !left.length && linkGone, + left.length ? `alive: ${left.join(', ')}` : (linkGone ? '' : `${runCfg.socketLink} remains`)); + } + + // --- Tripwire fires on a connection from the harness tree, and only from it. --- + await tripwireSelftest(base, record); + + fs.rmSync(base, { recursive: true, force: true }); + const failed = results.filter((r) => !r.ok).length; + console.log(failed ? `selftest FAILED (${failed} of ${results.length})` : `selftest passed (${results.length} cases)`); + if (failed) process.exitCode = 1; +} + +async function tripwireSelftest(base, record) { + const dir = path.join(base, 'tripwire'); + const pidsDir = path.join(dir, 'pids'); + const marker = path.join(dir, 'tripped.json'); + fs.mkdirSync(pidsDir, { recursive: true }); + const server = net.createServer(() => {}); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const port = server.address().port; + // The "harness child": connects to the throwaway listener when told to on stdin, then holds. + const child = spawn(process.execPath, ['-e', + `process.stdin.once('data',()=>{require('net').connect(${port},'127.0.0.1');});setInterval(()=>{},1000);`], { stdio: ['pipe', 'ignore', 'inherit'] }); + fs.writeFileSync(path.join(pidsDir, 'child.json'), JSON.stringify({ pid: child.pid, markers: [] })); + const tw = spawn(process.execPath, [path.join(HERE, 'tripwire.mjs'), 'watch', '--port', String(port), '--pids', pidsDir, + '--marker', marker, '--interval', '200'], { stdio: ['ignore', 'pipe', 'inherit'] }); + const twExit = new Promise((r) => tw.once('exit', (code) => r(code))); + try { + // Control: a connection from a process outside the tree (this one) must not trip it. + const outsider = net.connect(port, '127.0.0.1'); + await sleep(2000); + const quiet = tw.exitCode === null && !fs.existsSync(marker); + record('tripwire ignores a connection from outside the harness tree', quiet, quiet ? '' : 'it fired'); + outsider.destroy(); + + child.stdin.write('go\n'); + const code = await Promise.race([twExit, sleep(10_000).then(() => 'timeout')]); + const hit = fs.existsSync(marker) ? JSON.parse(fs.readFileSync(marker, 'utf-8')) : null; + const ok = code === TRIPWIRE_EXIT_CODE && hit?.violations.some((v) => v.pid === child.pid); + record('tripwire fires on a connection from a harness child', ok, `exit ${code}, ${hit ? `flagged pid ${hit.violations.map((v) => v.pid).join(', ')}` : 'no marker'}`); + } finally { + if (tw.exitCode === null) tw.kill('SIGKILL'); + child.kill('SIGKILL'); + server.close(); + } +} + +// --------------------------------------------------------------------------------------------- + +const COMMANDS = { + 'build-vsix': cmdBuildVsix, + start: cmdStart, + seed: cmdSeed, + check: cmdCheck, + stop: cmdStop, + selftest, +}; + +const [cmd, ...args] = process.argv.slice(2); +if (!COMMANDS[cmd]) { + console.error(`usage: harness.mjs ${Object.keys(COMMANDS).join(' | ')}`); + process.exit(64); +} +COMMANDS[cmd](...args).catch((err) => { + console.error(err instanceof Refusal ? err.message : `harness error: ${err.stack ?? err}`); + process.exit(err instanceof Refusal ? REFUSAL_EXIT_CODE : 1); +}); diff --git a/apps/vscode/scripts/cockpit-harness/preflight.mjs b/apps/vscode/scripts/cockpit-harness/preflight.mjs new file mode 100644 index 000000000..3fdb20294 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/preflight.mjs @@ -0,0 +1,180 @@ +// Pre-flight gates for the cockpit harness. Each gate throws a Refusal naming itself; the harness +// runs gates 1 and 2 before it creates anything, and stops (tearing down what it started) on any +// later refusal. Gate numbers match the plan's *Verification harness → Pre-flight* list. + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { listenerPids, openFiles, run } from './procs.mjs'; + +export const OWNER_TOWER_PORT = 4100; +export const REFUSAL_EXIT_CODE = 2; +/** macOS sun_path is 104 bytes including the NUL. */ +export const MAX_SOCKET_PATH = 103; +/** The longest name Tower gives a shellper socket: `shellper-.sock`. */ +export const SHELLPER_SOCKET_NAME_LENGTH = 'shellper-00000000-0000-0000-0000-000000000000.sock'.length; + +export class Refusal extends Error { + constructor(gate, message) { + super(`pre-flight gate ${gate} refused: ${message}`); + this.gate = gate; + } +} + +/** + * The real path of `p`, even when `p` (or its tail) does not exist yet: the longest existing + * ancestor is resolved and the rest appended, so a symlinked ancestor cannot hide where a + * not-yet-created directory will land. + */ +export function realpathLoose(p) { + const abs = path.resolve(p); + let head = abs; + const tail = []; + while (!fs.existsSync(head)) { + const parent = path.dirname(head); + if (parent === head) break; + tail.unshift(path.basename(head)); + head = parent; + } + return path.join(fs.realpathSync(head), ...tail); +} + +/** True when `child` is `parent` or inside it (both already real paths). */ +export function isWithin(child, parent) { + const rel = path.relative(parent, child); + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); +} + +/** Gate 1: the port is set, numeric, not the owner's Tower, and nothing listens on it. */ +export function gatePort(label, raw) { + if (raw === undefined || raw === '') throw new Refusal(1, `${label} is not set`); + if (!/^\d+$/.test(String(raw))) throw new Refusal(1, `${label}=${raw} is not numeric`); + const port = Number(raw); + if (port === OWNER_TOWER_PORT) throw new Refusal(1, `${label}=${port} is the owner's Tower port`); + if (port < 1024 || port > 65535) throw new Refusal(1, `${label}=${port} is outside 1024-65535`); + const listeners = listenerPids(port); + if (listeners.length) throw new Refusal(1, `${label}=${port} already has a listener (pid ${listeners.join(', ')})`); + return port; +} + +/** + * Gate 2: the agent-farm dir and the shellper socket dir resolve under the session scratchpad and + * are not the owner's `~/.agent-farm` or `~/.codev/run`; and a shellper socket path fits the + * platform's Unix-socket limit when addressed through `socketDir` as given. + * + * `socketLinkTarget` is set when the harness is about to create `socketDir` as a short symlink: + * the link must not exist yet, and its target is what has to resolve under the scratchpad. + */ +export function gateDirs({ scratch, agentFarmDir, socketDir, socketLinkTarget }) { + const home = fs.realpathSync(os.homedir()); + const ownerDirs = [path.join(home, '.agent-farm'), path.join(home, '.codev')]; + const scratchReal = fs.realpathSync(scratch); + if (socketLinkTarget && fs.existsSync(socketDir)) throw new Refusal(2, `socket link ${socketDir} already exists`); + for (const [label, dir] of [['CODEV_AGENT_FARM_DIR', agentFarmDir], ['SHELLPER_SOCKET_DIR', socketDir]]) { + if (!dir) throw new Refusal(2, `${label} is not set`); + const real = realpathLoose(label === 'SHELLPER_SOCKET_DIR' && socketLinkTarget ? socketLinkTarget : dir); + for (const owner of ownerDirs) { + if (isWithin(real, owner)) throw new Refusal(2, `${label}=${dir} resolves into the owner's ${owner}`); + } + if (!isWithin(real, scratchReal) || real === scratchReal) { + throw new Refusal(2, `${label}=${dir} resolves to ${real}, outside the scratchpad ${scratchReal}`); + } + } + const longest = path.join(socketDir, 'x').length - 1 + SHELLPER_SOCKET_NAME_LENGTH; + if (longest > MAX_SOCKET_PATH) { + throw new Refusal(2, `SHELLPER_SOCKET_DIR=${socketDir} gives ${longest}-byte socket paths (limit ${MAX_SOCKET_PATH})`); + } +} + +/** The `.db` files `pid` has open (WAL and SHM companions excluded). */ +export function openDbFiles(pid) { + return [...new Set(openFiles(pid).filter((n) => n.endsWith('.db')))]; +} + +/** + * Gate 3: the fixture driver and the isolated Tower agree on the database file. `driver` is what + * the driver resolved in its own environment, from the branch's built dist. + */ +export function gateDbAgreement({ driver, agentFarmDir, towerPid }) { + const expectedDir = realpathLoose(agentFarmDir); + if (realpathLoose(driver.agentFarmDir) !== expectedDir) { + throw new Refusal(3, `driver AGENT_FARM_DIR ${driver.agentFarmDir} is not the isolated ${expectedDir}`); + } + const towerDbs = openDbFiles(towerPid).map(realpathLoose); + if (towerDbs.length !== 1) { + throw new Refusal(3, `isolated Tower (pid ${towerPid}) has ${towerDbs.length} .db files open: ${towerDbs.join(', ') || 'none'}`); + } + const driverDb = realpathLoose(driver.globalDbPath); + if (driverDb !== towerDbs[0]) { + throw new Refusal(3, `driver would write ${driverDb}; the isolated Tower opened ${towerDbs[0]}`); + } + return towerDbs[0]; +} + +/** + * Gate 4: the only listener on `port` is the PID the harness spawned, and the Tower there answers + * with the isolated key (and rejects any other key on a key-gated route). + */ +export async function gateListener({ port, pid, key }) { + const listeners = listenerPids(port); + if (listeners.length !== 1 || listeners[0] !== pid) { + throw new Refusal(4, `listener on ${port} is pid ${listeners.join(', ') || 'none'}, not the harness's ${pid}`); + } + const base = `http://127.0.0.1:${port}`; + const version = await fetch(`${base}/api/version`, { headers: { 'codev-tower-key': key } }); + if (!version.ok) throw new Refusal(4, `GET /api/version with the isolated key answered ${version.status}`); + const body = await version.json(); + if (typeof body.version !== 'string') throw new Refusal(4, `GET /api/version body has no version: ${JSON.stringify(body)}`); + const keyed = await fetch(`${base}/api/workspaces`, { headers: { 'codev-tower-key': key } }); + if (!keyed.ok) throw new Refusal(4, `GET /api/workspaces with the isolated key answered ${keyed.status}`); + await keyed.body?.cancel(); + const wrong = await fetch(`${base}/api/workspaces`, { headers: { 'codev-tower-key': 'not-the-isolated-key' } }); + await wrong.body?.cancel(); + if (wrong.status !== 401) throw new Refusal(4, `GET /api/workspaces with a wrong key answered ${wrong.status}, not 401`); + return body.version; +} + +/** + * Gate 5: the serve-web profile pins the extension to the isolated Tower with auto-start off, and + * `afx`, `porch` and `codev` resolve to the recording stubs in the serve-web environment. + */ +export function gateVscodeProfile({ settingsPath, port, env, stubsDir }) { + if (!fs.existsSync(settingsPath)) throw new Refusal(5, `${settingsPath} does not exist`); + const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); + if (settings['codev.towerPort'] !== port) { + throw new Refusal(5, `codev.towerPort is ${settings['codev.towerPort']}, not ${port}`); + } + if (settings['codev.autoStartTower'] !== false) { + throw new Refusal(5, `codev.autoStartTower is ${settings['codev.autoStartTower']}, not false`); + } + for (const tool of ['afx', 'porch', 'codev']) { + const r = run('/bin/sh', ['-c', `command -v ${tool}`], { env }); + const resolved = r.stdout.trim(); + if (r.status !== 0 || path.dirname(resolved) !== stubsDir) { + throw new Refusal(5, `${tool} resolves to '${resolved || 'nothing'}', not the stub in ${stubsDir}`); + } + } +} + +/** + * Gate 6: the isolated Tower's overview for `workspace` lists exactly the expected builders (by + * role id, with their `spawnedByArchitect`) and the expected architects. + */ +export async function gateOverview({ port, key, workspace, builders, architects }) { + const url = `http://127.0.0.1:${port}/api/overview?workspace=${encodeURIComponent(workspace)}`; + const res = await fetch(url, { headers: { 'codev-tower-key': key } }); + if (!res.ok) throw new Refusal(6, `GET /api/overview for ${workspace} answered ${res.status}`); + const data = await res.json(); + const got = (data.builders ?? []) + .map((b) => ({ roleId: b.roleId, spawnedByArchitect: b.spawnedByArchitect })) + .sort((a, b) => a.roleId.localeCompare(b.roleId)); + const want = [...builders].sort((a, b) => a.roleId.localeCompare(b.roleId)); + if (JSON.stringify(got) !== JSON.stringify(want)) { + throw new Refusal(6, `overview builders for ${workspace} are ${JSON.stringify(got)}, expected ${JSON.stringify(want)}`); + } + const gotArchitects = (data.architects ?? []).map((a) => a.name).sort(); + if (JSON.stringify(gotArchitects) !== JSON.stringify([...architects].sort())) { + throw new Refusal(6, `overview architects for ${workspace} are ${JSON.stringify(gotArchitects)}, expected ${JSON.stringify(architects)}`); + } + return data; +} diff --git a/apps/vscode/scripts/cockpit-harness/procs.mjs b/apps/vscode/scripts/cockpit-harness/procs.mjs new file mode 100644 index 000000000..238b9653f --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/procs.mjs @@ -0,0 +1,125 @@ +// Process and socket inspection for the cockpit harness: the process table, `lsof` readings, +// and kill-by-PID. Nothing here matches processes by name: every PID the harness acts on is one +// it started, a descendant of one, or one holding a socket in the harness's own socket dir. + +import { spawnSync } from 'node:child_process'; + +/** Run a command synchronously; never throws for a non-zero exit. */ +export function run(cmd, args, opts = {}) { + const r = spawnSync(cmd, args, { encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024, ...opts }); + if (r.error) throw new Error(`${cmd} ${args.join(' ')} failed to run: ${r.error.message}`); + return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }; +} + +/** pid → { ppid, command } for every process on the machine. */ +export function processTable() { + const r = run('ps', ['-A', '-o', 'pid=,ppid=,command=']); + if (r.status !== 0) throw new Error(`ps failed: ${r.stderr}`); + const table = new Map(); + for (const line of r.stdout.split('\n')) { + const m = line.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/); + if (m) table.set(Number(m[1]), { ppid: Number(m[2]), command: m[3] }); + } + return table; +} + +/** The live members of `roots` plus all their live descendants. */ +export function descendants(roots, table = processTable()) { + const children = new Map(); + for (const [pid, { ppid }] of table) { + if (!children.has(ppid)) children.set(ppid, []); + children.get(ppid).push(pid); + } + const out = new Set(); + const stack = [...roots].filter((pid) => table.has(pid)); + while (stack.length) { + const pid = stack.pop(); + if (out.has(pid)) continue; + out.add(pid); + for (const child of children.get(pid) ?? []) stack.push(child); + } + return out; +} + +export function isAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (err) { + return err.code === 'EPERM'; + } +} + +/** Parse `lsof -F p…n…` output into [{ pid, command, names[] }]. */ +function parseLsofFields(stdout) { + const procs = []; + let cur = null; + for (const line of stdout.split('\n')) { + if (!line) continue; + const tag = line[0]; + const val = line.slice(1); + if (tag === 'p') { + cur = { pid: Number(val), command: '', names: [] }; + procs.push(cur); + } else if (cur && tag === 'c') { + cur.command = val; + } else if (cur && tag === 'n') { + cur.names.push(val); + } + } + return procs; +} + +/** lsof exits 1 when nothing matches; anything else non-zero with no output is an error. */ +function lsof(args) { + const r = run('lsof', args); + if (r.status !== 0 && r.status !== 1) throw new Error(`lsof ${args.join(' ')} failed (${r.status}): ${r.stderr}`); + if (r.status === 1 && r.stdout.trim() === '') return []; + return parseLsofFields(r.stdout); +} + +/** Processes with a TCP socket on `port` (either end) in the given state. */ +export function tcpOn(port, state) { + return lsof(['-nP', `-iTCP:${port}`, `-sTCP:${state}`, '-Fpcn']); +} + +/** PIDs listening on `port`. */ +export function listenerPids(port) { + return [...new Set(tcpOn(port, 'LISTEN').map((p) => p.pid))]; +} + +/** PIDs holding a Unix socket whose path starts with one of `prefixes`. */ +export function unixSocketHolders(prefixes) { + const out = new Set(); + for (const proc of lsof(['-U', '-Fpcn'])) { + if (proc.names.some((n) => prefixes.some((p) => n.startsWith(p)))) out.add(proc.pid); + } + return out; +} + +/** Paths of the regular files `pid` has open. */ +export function openFiles(pid) { + const procs = lsof(['-nP', '-p', String(pid), '-Fpcn']); + return procs.flatMap((p) => p.names); +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** + * SIGTERM every pid, wait up to `graceMs`, SIGKILL the rest, and return the pids still alive + * afterwards (an empty array is a clean teardown). + */ +export async function killPids(pids, { graceMs = 5000 } = {}) { + const targets = [...new Set(pids)].filter(isAlive); + for (const pid of targets) { + try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } + } + const deadline = Date.now() + graceMs; + while (Date.now() < deadline && targets.some(isAlive)) await sleep(200); + for (const pid of targets.filter(isAlive)) { + try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } + } + const killDeadline = Date.now() + 3000; + while (Date.now() < killDeadline && targets.some(isAlive)) await sleep(100); + return targets.filter(isAlive); +} diff --git a/apps/vscode/scripts/cockpit-harness/stubs/afx b/apps/vscode/scripts/cockpit-harness/stubs/afx new file mode 100755 index 000000000..24ecb96d7 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/stubs/afx @@ -0,0 +1,3 @@ +#!/bin/sh +# Cockpit-harness recording stub for `afx`: logs argv and cwd, runs nothing. See ../README.md. +exec node "$(dirname "$0")/record.mjs" afx "$@" diff --git a/apps/vscode/scripts/cockpit-harness/stubs/codev b/apps/vscode/scripts/cockpit-harness/stubs/codev new file mode 100755 index 000000000..dd6bda287 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/stubs/codev @@ -0,0 +1,3 @@ +#!/bin/sh +# Cockpit-harness recording stub for `codev`: logs argv and cwd, runs nothing. See ../README.md. +exec node "$(dirname "$0")/record.mjs" codev "$@" diff --git a/apps/vscode/scripts/cockpit-harness/stubs/porch b/apps/vscode/scripts/cockpit-harness/stubs/porch new file mode 100755 index 000000000..3f6724069 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/stubs/porch @@ -0,0 +1,3 @@ +#!/bin/sh +# Cockpit-harness recording stub for `porch`: logs argv and cwd, runs nothing. See ../README.md. +exec node "$(dirname "$0")/record.mjs" porch "$@" diff --git a/apps/vscode/scripts/cockpit-harness/stubs/record.mjs b/apps/vscode/scripts/cockpit-harness/stubs/record.mjs new file mode 100644 index 000000000..3cb2f973b --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/stubs/record.mjs @@ -0,0 +1,31 @@ +// Shared body of the afx / porch / codev recording stubs. Appends one JSON line per call to +// $COCKPIT_STUB_LOG and exits 0 without doing anything else, so a CLI-shelling action is verified +// by its recorded argv and cwd. `codev --version` prints $COCKPIT_CODEV_VERSION so the extension's +// preflight passes. Outside the harness (no log configured) it refuses loudly. + +import fs from 'node:fs'; + +const [tool, ...argv] = process.argv.slice(2); +const log = process.env.COCKPIT_STUB_LOG; +if (!log) { + console.error(`cockpit-harness stub '${tool}' was invoked outside the harness (COCKPIT_STUB_LOG unset)`); + process.exit(97); +} + +const entry = { + at: new Date().toISOString(), + tool, + argv, + cwd: process.cwd(), + caller: process.env.COCKPIT_STUB_CALLER ?? 'unknown', +}; +fs.appendFileSync(log, `${JSON.stringify(entry)}\n`); + +if (tool === 'codev' && argv.length === 1 && argv[0] === '--version') { + const version = process.env.COCKPIT_CODEV_VERSION; + if (!version) { + console.error('cockpit-harness stub: COCKPIT_CODEV_VERSION is unset'); + process.exit(97); + } + console.log(version); +} diff --git a/apps/vscode/scripts/cockpit-harness/tripwire.mjs b/apps/vscode/scripts/cockpit-harness/tripwire.mjs new file mode 100644 index 000000000..f631f8661 --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/tripwire.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +// Tripwire: samples established TCP connections on a watched port (the owner's :4100 in a real +// run) and fails if any belongs to the harness's own process tree. It never connects to the +// watched port; it only reads the kernel's socket table through lsof. +// +// The harness's tree is: every PID recorded in the pids dir (one JSON file per process the harness +// launched), every process holding a Unix socket under the harness's socket dir (the shellpers, +// which can outlive their parent Tower), and all live descendants of both. +// +// node tripwire.mjs watch --port --pids --marker [--socket-prefix ]... +// [--interval ] +// +// On a hit it writes the marker (JSON: the offending pids and commands) and exits 3. + +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { descendants, isAlive, processTable, tcpOn, unixSocketHolders } from './procs.mjs'; + +export const TRIPWIRE_EXIT_CODE = 3; + +/** PIDs recorded in `pidsDir` (files `.json` holding `{ pid }`) that are still alive. */ +export function recordedPids(pidsDir) { + if (!fs.existsSync(pidsDir)) return []; + const pids = []; + for (const f of fs.readdirSync(pidsDir)) { + if (!f.endsWith('.json')) continue; + try { + const { pid } = JSON.parse(fs.readFileSync(path.join(pidsDir, f), 'utf-8')); + if (Number.isInteger(pid) && isAlive(pid)) pids.push(pid); + } catch { + // A pid file being written right now; the next sample reads it. + } + } + return pids; +} + +/** The harness's process tree right now. */ +export function harnessTree({ pidsDir, socketPrefixes = [] }) { + const table = processTable(); + const roots = new Set(recordedPids(pidsDir)); + if (socketPrefixes.length) for (const pid of unixSocketHolders(socketPrefixes)) roots.add(pid); + return { tree: descendants(roots, table), table }; +} + +/** One sample: established connections on `port` owned by a process in the harness's tree. */ +export function sample({ port, pidsDir, socketPrefixes = [] }) { + const { tree, table } = harnessTree({ pidsDir, socketPrefixes }); + const violations = tcpOn(port, 'ESTABLISHED') + .filter((p) => tree.has(p.pid)) + .map((p) => ({ pid: p.pid, command: table.get(p.pid)?.command ?? p.command, sockets: p.names })); + return { treeSize: tree.size, violations }; +} + +function parseArgs(argv) { + const opts = { socketPrefixes: [], interval: 1000 }; + for (let i = 0; i < argv.length; i++) { + const flag = argv[i]; + const value = argv[++i]; + if (value === undefined) throw new Error(`${flag} needs a value`); + if (flag === '--port') opts.port = Number(value); + else if (flag === '--pids') opts.pidsDir = value; + else if (flag === '--marker') opts.marker = value; + else if (flag === '--socket-prefix') opts.socketPrefixes.push(value); + else if (flag === '--interval') opts.interval = Number(value); + else throw new Error(`unknown flag ${flag}`); + } + if (!Number.isInteger(opts.port) || opts.port <= 0) throw new Error('--port is required'); + if (!opts.pidsDir) throw new Error('--pids is required'); + if (!opts.marker) throw new Error('--marker is required'); + return opts; +} + +async function watch(opts) { + const stamp = () => new Date().toISOString(); + console.log(`${stamp()} tripwire watching :${opts.port} for pids in ${opts.pidsDir} (+ socket holders under ${opts.socketPrefixes.join(', ') || 'none'})`); + let samples = 0; + for (;;) { + const { treeSize, violations } = sample(opts); + samples++; + if (violations.length) { + const record = { at: stamp(), port: opts.port, samples, violations }; + fs.writeFileSync(opts.marker, `${JSON.stringify(record, null, 2)}\n`); + console.log(`${stamp()} TRIPPED: ${JSON.stringify(violations)}`); + process.exit(TRIPWIRE_EXIT_CODE); + } + if (samples % 60 === 1) console.log(`${stamp()} sample ${samples}: tree of ${treeSize}, no connection on :${opts.port}`); + await new Promise((r) => setTimeout(r, opts.interval)); + } +} + +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + const [cmd, ...rest] = process.argv.slice(2); + if (cmd !== 'watch') { + console.error('usage: tripwire.mjs watch --port --pids --marker [--socket-prefix ]... [--interval ]'); + process.exit(64); + } + watch(parseArgs(rest)).catch((err) => { + console.error(`tripwire error: ${err.stack ?? err}`); + process.exit(1); + }); +} diff --git a/apps/vscode/scripts/cockpit-harness/workbench.mjs b/apps/vscode/scripts/cockpit-harness/workbench.mjs new file mode 100644 index 000000000..66537455b --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/workbench.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +// Headless driver for the harness's isolated VS Code (serve-web). It uses the Chromium already in +// the Playwright cache through the workspace's own playwright install: never `playwright install`. +// The browser profile is persistent (under the harness root), so the folder-trust decision made +// on the first load holds for every later scenario. +// +// node workbench.mjs check --url --profile --shot --out +// --owner-port +// +// `check` loads the workbench, accepts the Restricted Mode trust prompt if it appears, and waits +// for the Codev activity-bar container (the extension under test has activated). Any browser +// request to the owner's port fails the check. + +import fs from 'node:fs'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const REPO = path.resolve(HERE, '../../../..'); + +async function loadChromium() { + const require = createRequire(path.join(REPO, 'packages/codev/package.json')); + const mod = await import(pathToFileURL(require.resolve('playwright')).href); + return mod.chromium ?? mod.default.chromium; +} + +function parseArgs(argv) { + const opts = {}; + for (let i = 0; i < argv.length; i += 2) { + const [flag, value] = [argv[i], argv[i + 1]]; + if (value === undefined) throw new Error(`${flag} needs a value`); + opts[flag.replace(/^--/, '')] = value; + } + for (const k of ['url', 'profile', 'shot', 'out', 'owner-port']) { + if (!opts[k]) throw new Error(`--${k} is required`); + } + return opts; +} + +const TRUST_BUTTON = /Yes, I trust the authors|Trust Folder & Continue|Trust Folder/i; + +/** + * Trust the opened folder when the window is in Restricted Mode, through the Workspace Trust + * editor the status-bar item opens; otherwise terminal creation later stalls behind a modal. + * The decision persists in the harness's browser profile and server user dir. + */ +async function ensureTrusted(page, result) { + // The status bar fills in after the activity bar; the Codev status item is the cue that the + // trust item, if any, has rendered too. + await page.locator('[id="cluesmith.codev-vscode"]').waitFor({ timeout: 120_000 }); + await page.waitForTimeout(2000); + const trustItem = page.locator('[id="status.workspaceTrust"]'); + const banner = page.locator('.part.banner', { hasText: 'Restricted Mode' }); + const isRestricted = async () => (await trustItem.count()) > 0 || (await banner.count()) > 0; + if (!(await isRestricted())) return true; + await trustItem.first().click(); + await page.getByRole('button', { name: /^Trust$/ }).first().click({ timeout: 30_000 }); + const deadline = Date.now() + 60_000; + while (Date.now() < deadline) { + const confirm = page.getByRole('button', { name: TRUST_BUTTON }); + if (await confirm.count()) await confirm.first().click(); + if (!(await isRestricted())) { + result.trustAccepted = true; + // The Workspace Trust editor opens as a modal editor; it blocks the workbench until closed. + const modal = page.locator('.monaco-modal-editor-block'); + for (let i = 0; i < 10 && (await modal.count()); i++) { + await page.keyboard.press('Escape'); + await page.waitForTimeout(500); + } + if (await modal.count()) throw new Error('the Workspace Trust modal editor did not close'); + return true; + } + await page.waitForTimeout(500); + } + return false; +} + +async function check(opts) { + const chromium = await loadChromium(); + const result = { ok: false, trustAccepted: false, ownerPortRequests: [], consoleErrors: [], error: null }; + const context = await chromium.launchPersistentContext(opts.profile, { + headless: true, + viewport: { width: 1600, height: 1000 }, + }); + try { + context.on('request', (r) => { + if (URL.canParse(r.url()) && new URL(r.url()).port === opts['owner-port']) result.ownerPortRequests.push(r.url()); + }); + const page = context.pages()[0] ?? await context.newPage(); + page.on('console', (m) => { if (m.type() === 'error') result.consoleErrors.push(m.text()); }); + await page.goto(opts.url, { timeout: 240_000, waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.monaco-workbench', { timeout: 240_000 }); + + const codevItem = page.locator('.activitybar .action-item a[aria-label^="Codev"]').first(); + const deadline = Date.now() + 120_000; + while (Date.now() < deadline) { + const trust = page.getByRole('button', { name: TRUST_BUTTON }); + if (await trust.count()) { + await trust.first().click(); + result.trustAccepted = true; + } + if (await codevItem.count()) break; + await page.waitForTimeout(500); + } + if (!(await codevItem.count())) throw new Error('the Codev activity-bar container never appeared'); + result.trusted = await ensureTrusted(page, result); + if (!result.trusted) throw new Error('the fixture folder is still in Restricted Mode'); + await codevItem.click(); + await page.waitForTimeout(3000); + await page.screenshot({ path: opts.shot }); + if (result.ownerPortRequests.length) throw new Error(`the browser requested the owner's port: ${result.ownerPortRequests.join(', ')}`); + result.ok = true; + } catch (err) { + result.error = String(err.message ?? err); + } finally { + await context.close(); + fs.writeFileSync(opts.out, `${JSON.stringify(result, null, 2)}\n`); + } + return result.ok; +} + +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + const [cmd, ...rest] = process.argv.slice(2); + if (cmd !== 'check') { + console.error('usage: workbench.mjs check --url --profile --shot --out --owner-port '); + process.exit(64); + } + check(parseArgs(rest)) + .then((ok) => process.exit(ok ? 0 : 1)) + .catch((err) => { + console.error(`workbench error: ${err.stack ?? err}`); + process.exit(1); + }); +} diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 338e8a0dc..5b7c57cdc 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -180,3 +180,43 @@ Both are now in the harness section. A side gotcha: zsh doesn't word-split `$PID `kill $PIDS` silently did nothing. I killed per PID instead. The evidence is in `codev/projects/1963-…/layout-spike/`. + +## 2026-11-24 — Phase 1 (verification_harness): harness built, self-test green + +I told the architect before the first isolated Tower start. Their OK came at 07:02Z, and they +accepted two deviations: +- **Scratch HOME** for every harness child (Tower, driver, serve-web, browser). This is an extra + layer beyond the plan. +- **The socket dir is a short `/tmp/cckp-` symlink** to `/cockpit-harness/run`. + macOS caps a Unix-socket path at 104 bytes, and the scratchpad path alone is 135, so a socket dir + literally under the scratchpad cannot work. + - Gate 2 checks the realpath, and also checks the socket-path length. + - Teardown removes the link even after a failed start (the architect's condition). + - Standing order: if pre-flight or the tripwire fires in a real run, stop and tell the + architect before retrying. + +Findings that shaped the code: +- **Plain-shell fixtures.** A `bash` architect auto-detects the **claude** harness and would be + handed claude's session and role args. So each fixture's `.codev/config.json` names a no-op custom + harness (`roleArgs: []`, `roleScriptFragment: ""`). +- **No adopt.** `launchInstance` runs `npx codev adopt` when `codev/` is missing, so fixtures always + carry `codev/`. The driver fails if activation reports `adopted`. +- **Builder terminals.** `POST /api/terminals` only registers a builder (shellper-backed) with + `persistent: true`, which the plan table omitted. The driver requires `persistent === true` in + the response. +- **Machine settings.** User settings in serve-web live in the browser, so the harness writes + `/Machine/settings.json`. Restricted Mode ignores the `codev.tower*` settings only + from *workspace* settings, so Machine settings still apply. +- **Allowlisted environments.** Child environments are built from an allowlist, so no `CLAUDE_CODE_*`, + `VSCODE_*`, `CODEV_*`, `NODE_ENV` or token variables leak in. + +`harness.mjs selftest` passes all 14 cases: +- gate 1: port 4100, a non-numeric port, and a port that already has a listener; +- gate 2: `~/.agent-farm`, an agent-farm dir outside the scratchpad, `~/.codev/run`, a socket dir + outside the scratchpad, and an over-long socket dir. Each refuses with nothing created; +- gate 3: a `NODE_ENV=test` driver against a real production-mode isolated Tower refuses, and no + `test.db` or fixture is created; +- gate 4: a foreign listener refuses; +- teardown by PID, with the link removed; +- the tripwire ignores a connection from outside the tree, and fires (exit 3) on one from a harness + child. From 84ed62e04d3d85a864e70ae984d6caf0147e574a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:20:30 -0800 Subject: [PATCH 034/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 09771e514..3a8010b52 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,10 +45,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T06:56:42.376Z' +updated_at: '2026-11-24T07:20:30.451Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From ef05107432787ba88c2fae232730493118c972a5 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:27:08 -0800 Subject: [PATCH 035/140] [Spec 1963][Phase: verification_harness] fix: ide-server VS Code mode, earlier tripwire, review notes --- apps/vscode/scripts/cockpit-harness/README.md | 33 ++++-- .../scripts/cockpit-harness/harness.mjs | 102 +++++++++++++----- ...63-verification_harness-iter1-rebuttals.md | 48 +++++++++ codev/state/spir-1963_thread.md | 32 ++++++ 4 files changed, 183 insertions(+), 32 deletions(-) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-rebuttals.md diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index 7338dea09..4cf8e3412 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -3,7 +3,7 @@ Dev-only. Excluded from the vsix (`.vscodeignore`) and not run in CI. This harness gives Spec 1963's rendered checkpoints an isolated Tower and an isolated VS Code -(`code serve-web`) running the branch's vsix. Neither can reach the owner's Tower (`:4100`), +(`code serve-web`, or the IDE server binary) running the branch's vsix. Neither can reach the owner's Tower (`:4100`), `~/.agent-farm`, `~/.codev/run` or IDE (`/ide/`). The plan's *Verification harness* section is the design; this file covers how to run it. @@ -16,18 +16,24 @@ H=apps/vscode/scripts/cockpit-harness/harness.mjs node $H selftest # prove every pre-flight refusal and the tripwire node $H build-vsix # vsce package → $COCKPIT_SCRATCH/cockpit-harness/codev-vscode.vsix -node $H start # pre-flight, Tower, `empty` fixture, serve-web, tripwire +node $H start # pre-flight, Tower, `empty` fixture, VS Code, tripwire node $H seed one-builder # seed a scenario; gate 6 asserts its overview node $H check # gates 3-5 again, plus the extension running against the Tower node $H stop # kill the harness's own PIDs; remove runtime dirs ``` +If `code serve-web` cannot run, start with the IDE server binary instead: + +```sh +COCKPIT_VSCODE=ide-server COCKPIT_IDE_SERVER_BIN= node $H start +``` + Prerequisites: - `packages/codev` is built, because the Tower and the fixture driver load its `dist`; - `pnpm install` has run, because the browser driver resolves `playwright` from `packages/codev`. Never run `playwright install`. The driver uses the Chromium already in -`~/Library/Caches/ms-playwright`. +`~/Library/Caches/ms-playwright`, or in `PLAYWRIGHT_BROWSERS_PATH` when that is set. ## What runs, and how it is kept away from the owner's @@ -37,11 +43,19 @@ Never run `playwright install`. The driver uses the Chromium already in | Shellper sockets | They live in `/run`, reached through a short `/tmp/cckp-` symlink.
macOS caps a socket path at 104 bytes, and the scratchpad path alone is longer. Gate 2 checks the link's real path, and every teardown removes the link. | | Fixture driver (`fixtures.mjs`) | Runs in the isolated environment. Creates state only through:
  • explicit-port HTTP calls (activation, builder terminals);
  • the dist's in-process writers (porch `writeState`, `upsertBuilder`);
  • git.
It runs no Tower-contacting `afx` or `porch` command. | | Fixture sessions | Architects and builders are `/bin/bash --noprofile --norc`, through a no-op custom harness in each fixture's `.codev/config.json`. They are never agents. | -| VS Code | `code serve-web` on `$COCKPIT_WEB_PORT`, with the CLI, server, user and extensions dirs all under the root.
  • Machine settings: `codev.towerPort=$COCKPIT_TOWER_PORT`, `codev.autoStartTower=false`, `files.autoSave=off`.
  • Environment: `CODEV_TOWER_KEY` is the isolated key, `HOME` is the scratch home, and `stubs/` comes first on `PATH`.
| +| VS Code | Runs on `$COCKPIT_WEB_PORT` in one of two modes, set by `COCKPIT_VSCODE`:
  • `serve-web` (default): `code serve-web`, with the CLI, server, user and extensions dirs all under the root.
  • `ide-server`: the plan's alternative for when serve-web cannot run. It launches the VS Code Server binary Tower's IDE support uses (`COCKPIT_IDE_SERVER_BIN`) **directly**, never through any Tower's `/api/ide`. It passes the flags `ide-server.ts` passes (`--host 127.0.0.1`, `--port`, `--server-base-path /ide`, `--connection-token-file`, `--extensions-dir`), plus `--server-data-dir` and `--user-data-dir`, all in the scratchpad.
The mode is chosen explicitly. A serve-web failure fails the start; it does not switch modes by itself.
  • Machine settings: `codev.towerPort=$COCKPIT_TOWER_PORT`, `codev.autoStartTower=false`, `files.autoSave=off`.
  • Environment: `CODEV_TOWER_KEY` is the isolated key, `HOME` is the scratch home, and `stubs/` comes first on `PATH`.
| | Stubs (`stubs/afx`, `porch`, `codev`) | Each call appends `{ tool, argv, cwd, caller }` to `/logs/stub-calls.jsonl` and exits 0, so CLI-shelling actions are verified by their recorded argv.
`codev --version` prints the branch version.
The stubs are on the Tower's `PATH` too. | | Browser (`workbench.mjs`) | Headless Chromium with a persistent profile under the root, so the folder-trust decision holds. Any request to `:4100` fails the check. | | Tripwire (`tripwire.mjs`) | Samples `lsof` for ESTABLISHED connections on `:4100` once a second. It fails the run (writes `tripwire.tripped`, exits 3) if one belongs to the harness tree:
  • the PIDs in `/pids/`;
  • holders of sockets in the run dir;
  • descendants of either.
It never connects to `:4100`. | +The tripwire **detects**; it does not enforce. It samples once a second, so a connect, request +and close to `:4100` that completes between two samples would escape it. Isolation is enforced by +the layers above: +- no Tower-contacting CLI; +- recording stubs on `PATH`; +- `codev.autoStartTower=false` and the pinned `codev.towerPort`; +- the isolated `CODEV_TOWER_KEY`, so a stray request to the owner's Tower would get a 401. + ## Pre-flight gates These match the plan's numbering. Any refusal exits with code 2. @@ -55,8 +69,8 @@ These match the plan's numbering. Any refusal exits with code 2. - The driver re-checks this before every seed, and refuses before writing. 4. The only listener on the Tower port is the PID the harness spawned. `/api/version` answers the isolated key, and a wrong key gets 401. -5. The serve-web Machine settings pin the port and turn auto-start off, and `afx`, `porch` and - `codev` resolve to the stubs in the serve-web environment. +5. The VS Code Machine settings pin the port and turn auto-start off, and `afx`, `porch` and + `codev` resolve to the stubs in the VS Code server's environment. 6. After a seed, each fixture workspace's `/api/overview` lists exactly the expected builders (with `spawnedByArchitect`) and architects. There is no fallback to faked data. @@ -87,3 +101,10 @@ before retrying. - `one-builder`: `alpha` activated, plus builder `spir-101` spawned by `main`. Later phases add scenarios here. + +Seed each scenario once per `start`. Re-seeding is not supported, for two reasons: +- `seedBuilder` refuses an existing worktree. +- The extension activates `alpha` on the isolated Tower by itself when the workbench first + loads, so `empty`'s "no architects" expectation stops holding after the first `check`. + +To get a different scenario, `stop` and `start` again. diff --git a/apps/vscode/scripts/cockpit-harness/harness.mjs b/apps/vscode/scripts/cockpit-harness/harness.mjs index 4a0c543c4..7f54df4e9 100644 --- a/apps/vscode/scripts/cockpit-harness/harness.mjs +++ b/apps/vscode/scripts/cockpit-harness/harness.mjs @@ -1,17 +1,19 @@ #!/usr/bin/env node -// Cockpit verification harness: an isolated Tower + an isolated VS Code (serve-web) running the -// branch's vsix, for rendered verification that never touches the owner's Tower (:4100), agent-farm -// dir, socket dir or IDE. See README.md. +// Cockpit verification harness: an isolated Tower + an isolated VS Code (serve-web, or the VS Code +// Server binary Tower's IDE support runs) with the branch's vsix installed, for rendered +// verification that never touches the owner's Tower (:4100), agent-farm dir, socket dir or IDE. +// See README.md. // // node harness.mjs build-vsix build the branch vsix into the harness root -// node harness.mjs start pre-flight, isolated Tower, `empty` fixture, serve-web, tripwire +// node harness.mjs start pre-flight, isolated Tower, `empty` fixture, VS Code, tripwire // node harness.mjs seed seed a fixture scenario, then assert gate 6 on its overview // node harness.mjs check re-run gates 3-5 and prove the extension runs against the Tower // node harness.mjs stop kill only the harness's own PIDs; remove the runtime dirs // node harness.mjs selftest prove every refusal and the tripwire // // Inputs (environment): COCKPIT_SCRATCH (the session scratchpad), COCKPIT_TOWER_PORT, -// COCKPIT_WEB_PORT; optional CODEV_AGENT_FARM_DIR / SHELLPER_SOCKET_DIR overrides (still gated). +// COCKPIT_WEB_PORT; optional CODEV_AGENT_FARM_DIR / SHELLPER_SOCKET_DIR overrides (still gated); +// COCKPIT_VSCODE=serve-web (default) | ide-server, the latter with COCKPIT_IDE_SERVER_BIN. import { spawn, spawnSync } from 'node:child_process'; import crypto from 'node:crypto'; @@ -22,7 +24,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { OWNER_TOWER_PORT, REFUSAL_EXIT_CODE, Refusal, gateDbAgreement, gateDirs, gateListener, gateOverview, - gatePort, gateVscodeProfile, isWithin, realpathLoose, + gatePort, gateVscodeProfile, isWithin, } from './preflight.mjs'; import { descendants, isAlive, killPids, listenerPids, processTable, run, tcpOn, unixSocketHolders } from './procs.mjs'; import { CODEV_DIST, REPO, SCENARIOS, expectedOverview } from './fixtures.mjs'; @@ -33,8 +35,12 @@ const STUBS = path.join(HERE, 'stubs'); const VSCODE_APP = path.join(REPO, 'apps/vscode'); const TOWER_SERVER = path.join(CODEV_DIST, 'agent-farm/servers/tower-server.js'); const CODE_BIN = process.env.COCKPIT_CODE_BIN || '/usr/local/bin/code'; +/** How the isolated VS Code is served: `serve-web` (default) or `ide-server`. */ +const VSCODE_MODES = ['serve-web', 'ide-server']; +/** The base path Tower's IDE support serves under; ide-server mode mirrors it. */ +const IDE_BASE_PATH = '/ide'; const REAL_HOME = os.homedir(); -const PLAYWRIGHT_BROWSERS = path.join(REAL_HOME, 'Library/Caches/ms-playwright'); +const PLAYWRIGHT_BROWSERS = process.env.PLAYWRIGHT_BROWSERS_PATH || path.join(REAL_HOME, 'Library/Caches/ms-playwright'); /** The vsix's inputs: what has to be unchanged since build-vsix for the install to be "the branch's". */ const VSIX_INPUTS = ['apps/vscode', ':(exclude)apps/vscode/scripts/cockpit-harness', 'packages', 'pnpm-lock.yaml']; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -60,6 +66,7 @@ function layout(scratch) { vscodeServer: path.join(vscode, 'server'), vscodeUser: path.join(vscode, 'user'), vscodeExt: path.join(vscode, 'ext'), + vscodeToken: path.join(vscode, 'connection-token'), browserProfile: path.join(root, 'browser-profile'), state: path.join(root, 'state.json'), tripMarker: path.join(root, 'tripwire.tripped'), @@ -265,18 +272,31 @@ function planRun({ needWeb }) { gateDirs({ scratch, agentFarmDir, socketDir, socketLinkTarget: socketLink ? L.run : undefined }); if (fs.existsSync(L.state)) throw new Error(`a harness is already recorded at ${L.state}; run stop first`); if (!fs.existsSync(TOWER_SERVER)) throw new Error(`${TOWER_SERVER} is missing: build packages/codev first`); + let vscodeMode = null; + let ideServerBin = null; if (needWeb) { if (!fs.existsSync(L.vsix)) throw new Error(`no vsix at ${L.vsix}: run build-vsix first`); - if (!fs.existsSync(CODE_BIN)) throw new Error(`no VS Code CLI at ${CODE_BIN} (set COCKPIT_CODE_BIN)`); + vscodeMode = process.env.COCKPIT_VSCODE || 'serve-web'; + if (!VSCODE_MODES.includes(vscodeMode)) throw new Error(`COCKPIT_VSCODE=${vscodeMode} is not one of ${VSCODE_MODES.join(', ')}`); + if (vscodeMode === 'serve-web' && !fs.existsSync(CODE_BIN)) throw new Error(`no VS Code CLI at ${CODE_BIN} (set COCKPIT_CODE_BIN)`); + if (vscodeMode === 'ide-server') { + ideServerBin = process.env.COCKPIT_IDE_SERVER_BIN; + if (!ideServerBin || !fs.existsSync(ideServerBin)) { + throw new Error(`COCKPIT_VSCODE=ide-server needs COCKPIT_IDE_SERVER_BIN, the VS Code Server binary Tower's IDE support runs (got '${ideServerBin ?? ''}')`); + } + } } - return { L, towerPort, webPort, agentFarmDir, socketDir, socketLink }; + return { L, towerPort, webPort, agentFarmDir, socketDir, socketLink, vscodeMode, ideServerBin }; } // --------------------------------------------------------------------------------------------- // Bring-up // --------------------------------------------------------------------------------------------- -/** Create the state record and dirs, then the isolated Tower; gates 2 (again), 4 and 3. */ +/** + * Create the state record and dirs, enrol this CLI process and start the tripwire, then the + * isolated Tower; gates 2 (again), 4 and 3. The tripwire is up before anything the harness launches. + */ async function bringUpTower(runCfg) { const { L } = runCfg; for (const dir of [L.root, L.af, L.run, L.home, L.fixtures, L.pids, L.logs, L.shots]) fs.mkdirSync(dir, { recursive: true }); @@ -291,6 +311,8 @@ async function bringUpTower(runCfg) { fs.symlinkSync(L.run, runCfg.socketLink); gateDirs({ scratch: L.scratch, agentFarmDir: runCfg.agentFarmDir, socketDir: runCfg.socketDir }); } + writePid(L, `cli-${process.pid}`, process.pid, []); + startTripwire(L, st); st.towerPid = launch(L, 'tower', process.execPath, [TOWER_SERVER, '-p', String(runCfg.towerPort)], { env: towerEnv(L, runCfg), cwd: L.home, markers: ['tower-server.js', `-p ${runCfg.towerPort}`], }); @@ -338,21 +360,39 @@ function writeMachineSettings(L, towerPort) { return file; } +/** + * Start the isolated VS Code. `serve-web` runs `code serve-web`. `ide-server` is the plan's + * alternative for when serve-web cannot run: it launches the VS Code Server binary Tower's IDE + * support uses, directly (never through any Tower's /api/ide), with the flags ide-server.ts passes + * (--host, --port, --server-base-path, --connection-token-file, --extensions-dir) plus the server + * and user data dirs, all in the scratchpad. The mode is chosen explicitly; a serve-web failure + * fails the start rather than switching modes on its own. + */ async function bringUpVscode(runCfg, st) { const { L } = runCfg; + st.vscodeMode = runCfg.vscodeMode; st.extension = installVsix(L); st.settingsPath = writeMachineSettings(L, runCfg.towerPort); const env = webEnv(L, runCfg); gateVscodeProfile({ settingsPath: st.settingsPath, port: runCfg.towerPort, env, stubsDir: STUBS }); - fs.mkdirSync(L.vscodeCli, { recursive: true }); - st.webPid = launch(L, 'serve-web', CODE_BIN, [ - 'serve-web', '--host', '127.0.0.1', '--port', String(runCfg.webPort), - '--without-connection-token', '--accept-server-license-terms', - '--cli-data-dir', L.vscodeCli, '--server-data-dir', L.vscodeServer, - '--user-data-dir', L.vscodeUser, '--extensions-dir', L.vscodeExt, - ], { env, cwd: L.home, markers: ['serve-web', `--port ${runCfg.webPort}`] }); + if (runCfg.vscodeMode === 'serve-web') { + fs.mkdirSync(L.vscodeCli, { recursive: true }); + st.webPid = launch(L, 'vscode', CODE_BIN, [ + 'serve-web', '--host', '127.0.0.1', '--port', String(runCfg.webPort), + '--without-connection-token', '--accept-server-license-terms', + '--cli-data-dir', L.vscodeCli, '--server-data-dir', L.vscodeServer, + '--user-data-dir', L.vscodeUser, '--extensions-dir', L.vscodeExt, + ], { env, cwd: L.home, markers: ['serve-web', `--port ${runCfg.webPort}`] }); + } else { + fs.writeFileSync(L.vscodeToken, crypto.randomBytes(24).toString('hex'), { mode: 0o600 }); + st.webPid = launch(L, 'vscode', runCfg.ideServerBin, [ + '--host', '127.0.0.1', '--port', String(runCfg.webPort), '--server-base-path', IDE_BASE_PATH, + '--connection-token-file', L.vscodeToken, '--extensions-dir', L.vscodeExt, + '--server-data-dir', L.vscodeServer, '--user-data-dir', L.vscodeUser, '--accept-server-license-terms', + ], { env, cwd: L.home, markers: [`--port ${runCfg.webPort}`, `--connection-token-file ${L.vscodeToken}`] }); + } saveState(L, st); - await waitForListener(runCfg.webPort, st.webPid, 300_000, 'serve-web'); + await waitForListener(runCfg.webPort, st.webPid, 300_000, runCfg.vscodeMode); saveState(L, st); } @@ -365,7 +405,10 @@ function startTripwire(L, st) { } function runCfgFromState(L, st) { - return { L, towerPort: st.towerPort, webPort: st.webPort, agentFarmDir: st.agentFarmDir, socketDir: st.socketDir, socketLink: st.socketLink }; + return { + L, towerPort: st.towerPort, webPort: st.webPort, agentFarmDir: st.agentFarmDir, socketDir: st.socketDir, + socketLink: st.socketLink, vscodeMode: st.vscodeMode, + }; } // --------------------------------------------------------------------------------------------- @@ -378,12 +421,10 @@ async function cmdStart() { let st; try { st = await bringUpTower(runCfg); - writePid(L, `cli-${process.pid}`, process.pid, []); console.log(`isolated Tower ${st.towerVersion} up on :${runCfg.towerPort} (pid ${st.towerPid}), db ${st.globalDb}`); - startTripwire(L, st); await seedScenario(L, runCfg, st, 'empty'); await bringUpVscode(runCfg, st); - console.log(`serve-web up on :${runCfg.webPort} (pid ${st.webPid}) with ${st.extension.id}@${st.extension.version}`); + console.log(`${st.vscodeMode} up on :${runCfg.webPort} (pid ${st.webPid}) with ${st.extension.id}@${st.extension.version}`); assertTripwireClean(L, st); recordKnownPids(L, st); removePid(L, `cli-${process.pid}`); @@ -396,7 +437,12 @@ async function cmdStart() { } function workbenchUrl(L, st) { - return `http://127.0.0.1:${st.webPort}/?folder=${encodeURIComponent(path.join(L.fixtures, 'alpha'))}`; + const folder = `folder=${encodeURIComponent(path.join(L.fixtures, 'alpha'))}`; + if (st.vscodeMode === 'ide-server') { + const token = fs.readFileSync(L.vscodeToken, 'utf-8').trim(); + return `http://127.0.0.1:${st.webPort}${IDE_BASE_PATH}/?${folder}&tkn=${token}`; + } + return `http://127.0.0.1:${st.webPort}/?${folder}`; } async function seedScenario(L, runCfg, st, name) { @@ -471,10 +517,10 @@ async function cmdCheck() { gateVscodeProfile({ settingsPath: st.settingsPath, port: st.towerPort, env: webEnv(L, runCfg), stubsDir: STUBS }); return st.settingsPath; }); - await item('serve-web listener belongs to the harness', () => { + await item(`${st.vscodeMode} listener belongs to the harness`, () => { const tree = descendants([st.webPid]); const listeners = listenerPids(st.webPort); - if (!listeners.length || !listeners.every((p) => tree.has(p))) throw new Error(`listeners ${listeners} not in serve-web tree`); + if (!listeners.length || !listeners.every((p) => tree.has(p))) throw new Error(`listeners ${listeners} not in the ${st.vscodeMode} tree`); return `pid ${listeners.join(', ')}`; }); await item('installed extension is the branch vsix', () => { @@ -494,7 +540,7 @@ async function cmdCheck() { const tree = descendants([st.webPid]); const conns = tcpOn(st.towerPort, 'ESTABLISHED').filter((p) => tree.has(p.pid)); if (conns.length) return `pids ${[...new Set(conns.map((c) => c.pid))].join(', ')}`; - if (Date.now() > deadline) throw new Error(`no serve-web process holds a connection to :${st.towerPort}`); + if (Date.now() > deadline) throw new Error(`no ${st.vscodeMode} process holds a connection to :${st.towerPort}`); await sleep(1000); } }); @@ -618,7 +664,9 @@ async function selftest() { const longSockName = 'socket-dir-with-a-deliberately-long-name-to-exceed-the-unix-socket-path-limit'; const cases = [ ['gate 1 refuses COCKPIT_TOWER_PORT=4100', { COCKPIT_TOWER_PORT: '4100' }, 1], + ['gate 1 refuses an unset port', { COCKPIT_TOWER_PORT: '' }, 1], ['gate 1 refuses a non-numeric port', { COCKPIT_TOWER_PORT: '18x64' }, 1], + ['gate 1 refuses the web port equal to the Tower port', { COCKPIT_WEB_PORT: String(towerPort) }, 1], ['gate 1 refuses a port that already has a listener', { COCKPIT_TOWER_PORT: String(busy.port) }, 1], ['gate 2 refuses CODEV_AGENT_FARM_DIR=~/.agent-farm', { CODEV_AGENT_FARM_DIR: path.join(REAL_HOME, '.agent-farm') }, 2], ['gate 2 refuses an agent-farm dir outside the scratchpad', { CODEV_AGENT_FARM_DIR: outsideAf }, 2], @@ -654,6 +702,8 @@ async function selftest() { try { const st = await bringUpTower(runCfg); record('isolated Tower passes gates 2-4 (positive control)', true, `pid ${st.towerPid}, db ${st.globalDb}`); + assertTripwireClean(L, st); + record('tripwire is running before the Tower launch and stays clean', true, `pid ${st.tripwirePid}`); const r = runDriver(L, runCfg, st, ['seed', 'one-builder'], { NODE_ENV: 'test' }); const testDb = path.join(runCfg.agentFarmDir, 'test.db'); diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-rebuttals.md new file mode 100644 index 000000000..9c2f05fe0 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-rebuttals.md @@ -0,0 +1,48 @@ +# Phase 1 (verification_harness), iteration 1: review responses + +Reviews: Codex **REQUEST_CHANGES**, Claude **APPROVE**. + +## Codex: the plan's IDE-server alternative to serve-web was missing — **accepted, implemented** + +Codex is right. The plan's *Isolated VS Code* section says that if `serve-web` cannot run, the +harness launches the IDE server binary Tower's IDE support uses, directly. `planRun()` only knew +`serve-web`. (Claude suggested leaving it out because `serve-web` works here. I followed the +approved plan instead.) + +**What changed.** A `COCKPIT_VSCODE` mode, `serve-web` by default or `ide-server`. +- `ide-server` requires `COCKPIT_IDE_SERVER_BIN`. It launches that VS Code Server binary + **directly**, never through any Tower's `/api/ide`. +- It passes the flags `ide-server.ts` passes: `--host 127.0.0.1`, `--port`, + `--server-base-path /ide`, `--connection-token-file`, `--extensions-dir` and + `--accept-server-license-terms`. +- It adds `--server-data-dir` and `--user-data-dir`, so nothing falls back to `~/.vscode-server`. +- Every path, including the token file, is under the scratchpad. +- The workbench URL carries `/ide/` and `tkn=`. + +**One deliberate difference from the plan's wording.** The mode is chosen explicitly. A +`serve-web` failure fails the start (and tears down) instead of switching launchers by itself. +The owner's standing development rule is "fail fast, never implement fallbacks". An explicit, +tested alternative keeps what the plan asks for — a way to run when serve-web cannot — without a +silent switch. The README documents both modes. + +**Verified.** I ran `start`, `check` and `stop` with `COCKPIT_VSCODE=ide-server`, using the VS Code +Server binary serve-web had downloaded into the harness cache. +- `check` passed 10/10. The extension activated, connected to the isolated Tower only, and + called the stub, and the tripwire stayed clean. +- `stop` killed 10 PIDs with none left; no link or listener remained. + +## Claude: non-blocking items — all taken + +1. **The tripwire window opened late.** `bringUpTower` now enrols the CLI process and starts the + tripwire right after the socket link, *before* the Tower launch and the first gate-3 probe. The + self-test asserts the tripwire is running and clean after bring-up. +2. **The tripwire is a detector, not the enforcement.** The README says so: it samples at 1 s, and + lists the layers that actually enforce isolation. +3. **The IDE-server alternative.** Implemented, per Codex (above). +4. **Seeding is once per `start`.** The README *Scenarios* section now says so, and why: the + extension self-activates `alpha`, and `seedBuilder` refuses an existing worktree. +5. **The `realpathLoose` import in `harness.mjs` was unused.** Removed. +6. **The Playwright browsers path was hardcoded.** It now honours `PLAYWRIGHT_BROWSERS_PATH`, with + the existing cache as the default. +7. **Self-test gaps.** Added two gate-1 cases: an unset port, and a web port equal to the Tower + port. The self-test now has 17 cases. diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 5b7c57cdc..cd424ac33 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -220,3 +220,35 @@ Findings that shaped the code: - teardown by PID, with the link removed; - the tripwire ignores a connection from outside the tree, and fires (exit 3) on one from a harness child. + +**Acceptance run from the committed tree (541d60aa0).** I rebuilt the vsix, then ran selftest +(14/14), start, check (10/10), `seed one-builder` (gate 6 shows `builder-spir-101` spawned by +`main`), check again (10/10), and stop (15 PIDs killed, none left, link removed, no listeners). The +workbench renders Agents (1) → SPECIFY → #101 fixture-one from the isolated Tower. + +Two things the first live checks caught: +- The trust banner and status item render after the Codev activity-bar item, so trust is now + detected by `#status.workspaceTrust` once the Codev status item has appeared. +- In 1.147 the Workspace Trust editor is a *modal* editor that blocks clicks, so it is closed with + Escape. + +Separately, the extension activates `alpha` on the isolated Tower by itself when it loads, so +`main` exists before any seed. That is expected and harmless. + +### Phase 1 review, iteration 1 (2026-11-24) + +- Checks: `porch done` ran the full suite once (build 17.1s, tests 54.0s), and it passed. +- Codex asked for changes. The plan's IDE-server alternative to serve-web was missing. I added + `COCKPIT_VSCODE=ide-server` with `COCKPIT_IDE_SERVER_BIN`. It launches the VS Code Server + binary directly with `ide-server.ts`'s flags, all under the scratchpad. The mode is explicit, + never an automatic fallback, per the fail-fast rule. Verified `start`, `check` 10/10 and + `stop` (10 PIDs, none left) in that mode. +- Claude approved, with non-blocking notes, and I took them all: + - the tripwire now starts before the Tower launch; + - the README now says the tripwire is a detector, not the enforcement; + - the README now says seeding is once per `start`; + - removed an unused import; + - honour `PLAYWRIGHT_BROWSERS_PATH`; + - two new gate-1 self-test cases. +- Re-verified in serve-web mode. Self-test 17/17, `start`, `check` 10/10, `seed one-builder` + (gate 6: `builder-spir-101` spawned by `main`), `check` 10/10, `stop` (15 PIDs, none left). From 2417bb57791fe9d4f2e5e3a2df57370b872789b1 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:29:03 -0800 Subject: [PATCH 036/140] chore(porch): 1963 implement re-iter (iter 2) --- .../status.yaml | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 3a8010b52..ac78dfa5c 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -44,11 +44,23 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true -history: [] +iteration: 2 +build_complete: false +history: + - iteration: 1 + plan_phase: verification_harness + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:20:30.451Z' +updated_at: '2026-11-24T07:29:03.758Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 21397fe9ceb9be324d17381c1dd3a137bb0c1fcb Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:31:24 -0800 Subject: [PATCH 037/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index ac78dfa5c..3fdd22076 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:29:03.758Z' +updated_at: '2026-11-24T07:31:24.088Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 67d907699e342143d4807d52293a0d179192340c Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:40:41 -0800 Subject: [PATCH 038/140] [Spec 1963][Phase: verification_harness] fix: content-digest vsix freshness, lighter tripwire sampling --- apps/vscode/scripts/cockpit-harness/README.md | 19 ++++++--- .../scripts/cockpit-harness/harness.mjs | 40 +++++++++++++++---- apps/vscode/scripts/cockpit-harness/procs.mjs | 4 +- .../scripts/cockpit-harness/tripwire.mjs | 33 ++++++++++----- codev/state/spir-1963_thread.md | 21 ++++++++++ 5 files changed, 93 insertions(+), 24 deletions(-) diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index 4cf8e3412..87e24b083 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -3,8 +3,8 @@ Dev-only. Excluded from the vsix (`.vscodeignore`) and not run in CI. This harness gives Spec 1963's rendered checkpoints an isolated Tower and an isolated VS Code -(`code serve-web`, or the IDE server binary) running the branch's vsix. Neither can reach the owner's Tower (`:4100`), -`~/.agent-farm`, `~/.codev/run` or IDE (`/ide/`). The plan's *Verification harness* section is the +(`code serve-web`, or the IDE server binary) running the branch's vsix. Neither can reach the +owner's Tower (`:4100`), `~/.agent-farm`, `~/.codev/run` or IDE (`/ide/`). The plan's *Verification harness* section is the design; this file covers how to run it. ## Running it @@ -22,6 +22,14 @@ node $H check # gates 3-5 again, plus the extension running agains node $H stop # kill the harness's own PIDs; remove runtime dirs ``` +`selftest` needs both ports set and free, even though it serves no web. Its refusal cases run real +`start` processes, and each must refuse for the gate under test, not for a missing port. + +`build-vsix` records a digest of every tracked or untracked file the vsix is built from. `check` +treats the installed vsix as the branch's only while that digest still matches, so an +uncommitted edit that was built in passes, and any edit since the build fails until you run +`build-vsix` again. The loop while iterating is: edit, `build-vsix`, `stop`, `start`, `check`. + If `code serve-web` cannot run, start with the IDE server binary instead: ```sh @@ -46,10 +54,11 @@ Never run `playwright install`. The driver uses the Chromium already in | VS Code | Runs on `$COCKPIT_WEB_PORT` in one of two modes, set by `COCKPIT_VSCODE`:
  • `serve-web` (default): `code serve-web`, with the CLI, server, user and extensions dirs all under the root.
  • `ide-server`: the plan's alternative for when serve-web cannot run. It launches the VS Code Server binary Tower's IDE support uses (`COCKPIT_IDE_SERVER_BIN`) **directly**, never through any Tower's `/api/ide`. It passes the flags `ide-server.ts` passes (`--host 127.0.0.1`, `--port`, `--server-base-path /ide`, `--connection-token-file`, `--extensions-dir`), plus `--server-data-dir` and `--user-data-dir`, all in the scratchpad.
The mode is chosen explicitly. A serve-web failure fails the start; it does not switch modes by itself.
  • Machine settings: `codev.towerPort=$COCKPIT_TOWER_PORT`, `codev.autoStartTower=false`, `files.autoSave=off`.
  • Environment: `CODEV_TOWER_KEY` is the isolated key, `HOME` is the scratch home, and `stubs/` comes first on `PATH`.
| | Stubs (`stubs/afx`, `porch`, `codev`) | Each call appends `{ tool, argv, cwd, caller }` to `/logs/stub-calls.jsonl` and exits 0, so CLI-shelling actions are verified by their recorded argv.
`codev --version` prints the branch version.
The stubs are on the Tower's `PATH` too. | | Browser (`workbench.mjs`) | Headless Chromium with a persistent profile under the root, so the folder-trust decision holds. Any request to `:4100` fails the check. | -| Tripwire (`tripwire.mjs`) | Samples `lsof` for ESTABLISHED connections on `:4100` once a second. It fails the run (writes `tripwire.tripped`, exits 3) if one belongs to the harness tree:
  • the PIDs in `/pids/`;
  • holders of sockets in the run dir;
  • descendants of either.
It never connects to `:4100`. | +| Tripwire (`tripwire.mjs`) | Samples `lsof` for ESTABLISHED connections on `:4100` every 2 s. The machine-wide socket-holder scan runs on every 5th sample only. It fails the run (writes `tripwire.tripped`, exits 3) if one belongs to the harness tree:
  • the PIDs in `/pids/`;
  • holders of sockets in the run dir;
  • descendants of either.
It never connects to `:4100`. | -The tripwire **detects**; it does not enforce. It samples once a second, so a connect, request -and close to `:4100` that completes between two samples would escape it. Isolation is enforced by +The tripwire **detects**; it does not enforce. It samples every 2 s, so a connect, request and +close to `:4100` that completes between two samples would escape it. (The extension's Tower +connection is a long-lived event stream, so a misdirected one would not.) Isolation is enforced by the layers above: - no Tower-contacting CLI; - recording stubs on `PATH`; diff --git a/apps/vscode/scripts/cockpit-harness/harness.mjs b/apps/vscode/scripts/cockpit-harness/harness.mjs index 7f54df4e9..5afb33bd2 100644 --- a/apps/vscode/scripts/cockpit-harness/harness.mjs +++ b/apps/vscode/scripts/cockpit-harness/harness.mjs @@ -399,7 +399,7 @@ async function bringUpVscode(runCfg, st) { function startTripwire(L, st) { st.tripwirePid = launch(L, 'tripwire', process.execPath, [ path.join(HERE, 'tripwire.mjs'), 'watch', '--port', String(OWNER_TOWER_PORT), '--pids', L.pids, - '--marker', L.tripMarker, ...socketPrefixes(L, st).flatMap((p) => ['--socket-prefix', p]), '--interval', '1000', + '--marker', L.tripMarker, ...socketPrefixes(L, st).flatMap((p) => ['--socket-prefix', p]), '--interval', '2000', ], { env: childEnv(L, 'tripwire'), cwd: L.home, markers: ['tripwire.mjs', 'watch'] }); saveState(L, st); } @@ -482,14 +482,35 @@ function assertTripwireClean(L, st) { } /** git: the vsix's inputs are unchanged since build-vsix (committed and in the working tree). */ +/** + * A digest of what the vsix is built from, as it is on disk now: every tracked or untracked (not + * ignored) file under VSIX_INPUTS, by path and content. Comparing digests rather than commits means + * an uncommitted edit that was built in counts as current, and a new untracked file counts as a + * change. + */ +function vsixInputsDigest() { + const r = run('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', ...VSIX_INPUTS], { cwd: REPO }); + if (r.status !== 0) throw new Error(`git ls-files failed: ${r.stderr.trim()}`); + const hash = crypto.createHash('sha256'); + for (const rel of [...new Set(r.stdout.split('\0').filter(Boolean))].sort()) { + const abs = path.join(REPO, rel); + const stat = fs.lstatSync(abs, { throwIfNoEntry: false }); + let content; + if (!stat) content = 'missing'; + else if (stat.isSymbolicLink()) content = `link:${fs.readlinkSync(abs)}`; + else if (stat.isFile()) content = sha256(abs); + else content = `mode:${stat.mode}`; + hash.update(`${rel}\0${content}\n`); + } + return hash.digest('hex'); +} + function vsixIsCurrent(L) { if (!fs.existsSync(L.vsixMeta)) return `no build record ${L.vsixMeta}`; const meta = JSON.parse(fs.readFileSync(L.vsixMeta, 'utf-8')); if (meta.sha256 !== sha256(L.vsix)) return 'the vsix changed after build-vsix recorded it'; - const committed = run('git', ['diff', '--quiet', meta.head, 'HEAD', '--', ...VSIX_INPUTS], { cwd: REPO }); - if (committed.status !== 0) return `vsix inputs changed between ${meta.head.slice(0, 8)} and HEAD`; - const working = run('git', ['diff', '--quiet', 'HEAD', '--', ...VSIX_INPUTS], { cwd: REPO }); - if (working.status !== 0) return 'vsix inputs have uncommitted changes'; + if (!meta.inputsDigest) return 'the build record has no inputs digest; run build-vsix again'; + if (meta.inputsDigest !== vsixInputsDigest()) return 'vsix inputs changed since build-vsix; run it again'; return null; } @@ -623,11 +644,14 @@ async function cmdBuildVsix() { const L = layout(scratchFromEnv()); fs.mkdirSync(L.root, { recursive: true }); const head = run('git', ['rev-parse', 'HEAD'], { cwd: REPO }).stdout.trim(); - const dirty = run('git', ['diff', '--quiet', 'HEAD', '--', ...VSIX_INPUTS], { cwd: REPO }).status !== 0; + const dirty = run('git', ['status', '--porcelain', '--', ...VSIX_INPUTS], { cwd: REPO }).stdout.trim() !== ''; + // Digest the inputs before packaging: an edit made during the build then reads as a change. + const inputsDigest = vsixInputsDigest(); const r = spawnSync('pnpm', ['exec', 'vsce', 'package', '--no-dependencies', '--out', L.vsix], { cwd: VSCODE_APP, stdio: 'inherit' }); if (r.status !== 0) throw new Error(`vsce package failed (${r.status})`); - fs.writeFileSync(L.vsixMeta, `${JSON.stringify({ head, dirtyAtBuild: dirty, sha256: sha256(L.vsix), builtAt: new Date().toISOString() }, null, 2)}\n`); - console.log(`built ${L.vsix} at ${head.slice(0, 8)}${dirty ? ' (with uncommitted input changes)' : ''}`); + const meta = { head, dirtyAtBuild: dirty, inputsDigest, sha256: sha256(L.vsix), builtAt: new Date().toISOString() }; + fs.writeFileSync(L.vsixMeta, `${JSON.stringify(meta, null, 2)}\n`); + console.log(`built ${L.vsix} at ${head.slice(0, 8)}${dirty ? ' (with uncommitted or untracked input changes)' : ''}`); } // --------------------------------------------------------------------------------------------- diff --git a/apps/vscode/scripts/cockpit-harness/procs.mjs b/apps/vscode/scripts/cockpit-harness/procs.mjs index 238b9653f..2d6afe48c 100644 --- a/apps/vscode/scripts/cockpit-harness/procs.mjs +++ b/apps/vscode/scripts/cockpit-harness/procs.mjs @@ -90,9 +90,11 @@ export function listenerPids(port) { /** PIDs holding a Unix socket whose path starts with one of `prefixes`. */ export function unixSocketHolders(prefixes) { + const dirs = prefixes.map((p) => p.replace(/\/+$/, '')); + const under = (n) => dirs.some((d) => n === d || n.startsWith(`${d}/`)); const out = new Set(); for (const proc of lsof(['-U', '-Fpcn'])) { - if (proc.names.some((n) => prefixes.some((p) => n.startsWith(p)))) out.add(proc.pid); + if (proc.names.some(under)) out.add(proc.pid); } return out; } diff --git a/apps/vscode/scripts/cockpit-harness/tripwire.mjs b/apps/vscode/scripts/cockpit-harness/tripwire.mjs index f631f8661..22b67b17d 100644 --- a/apps/vscode/scripts/cockpit-harness/tripwire.mjs +++ b/apps/vscode/scripts/cockpit-harness/tripwire.mjs @@ -7,8 +7,12 @@ // launched), every process holding a Unix socket under the harness's socket dir (the shellpers, // which can outlive their parent Tower), and all live descendants of both. // +// The socket-holder scan is a machine-wide `lsof -U`, the costliest probe, so `watch` runs it on +// the first sample and then every `--socket-scan-every` samples. Shellpers are also descendants of +// the live isolated Tower, so the pid path covers them between scans. +// // node tripwire.mjs watch --port --pids --marker [--socket-prefix ]... -// [--interval ] +// [--interval ] [--socket-scan-every ] // // On a hit it writes the marker (JSON: the offending pids and commands) and exits 3. @@ -35,17 +39,21 @@ export function recordedPids(pidsDir) { return pids; } -/** The harness's process tree right now. */ -export function harnessTree({ pidsDir, socketPrefixes = [] }) { +/** + * The harness's process tree right now. `socketHolders`, when given, is a recent socket-holder + * scan to reuse; otherwise the holders under `socketPrefixes` are scanned now. + */ +export function harnessTree({ pidsDir, socketPrefixes = [], socketHolders }) { const table = processTable(); const roots = new Set(recordedPids(pidsDir)); - if (socketPrefixes.length) for (const pid of unixSocketHolders(socketPrefixes)) roots.add(pid); + const holders = socketHolders ?? (socketPrefixes.length ? unixSocketHolders(socketPrefixes) : []); + for (const pid of holders) roots.add(pid); return { tree: descendants(roots, table), table }; } /** One sample: established connections on `port` owned by a process in the harness's tree. */ -export function sample({ port, pidsDir, socketPrefixes = [] }) { - const { tree, table } = harnessTree({ pidsDir, socketPrefixes }); +export function sample({ port, pidsDir, socketPrefixes = [], socketHolders }) { + const { tree, table } = harnessTree({ pidsDir, socketPrefixes, socketHolders }); const violations = tcpOn(port, 'ESTABLISHED') .filter((p) => tree.has(p.pid)) .map((p) => ({ pid: p.pid, command: table.get(p.pid)?.command ?? p.command, sockets: p.names })); @@ -53,7 +61,7 @@ export function sample({ port, pidsDir, socketPrefixes = [] }) { } function parseArgs(argv) { - const opts = { socketPrefixes: [], interval: 1000 }; + const opts = { socketPrefixes: [], interval: 2000, socketScanEvery: 5 }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; const value = argv[++i]; @@ -63,11 +71,14 @@ function parseArgs(argv) { else if (flag === '--marker') opts.marker = value; else if (flag === '--socket-prefix') opts.socketPrefixes.push(value); else if (flag === '--interval') opts.interval = Number(value); + else if (flag === '--socket-scan-every') opts.socketScanEvery = Number(value); else throw new Error(`unknown flag ${flag}`); } if (!Number.isInteger(opts.port) || opts.port <= 0) throw new Error('--port is required'); if (!opts.pidsDir) throw new Error('--pids is required'); if (!opts.marker) throw new Error('--marker is required'); + if (!Number.isInteger(opts.interval) || opts.interval <= 0) throw new Error('--interval must be a positive integer'); + if (!Number.isInteger(opts.socketScanEvery) || opts.socketScanEvery <= 0) throw new Error('--socket-scan-every must be a positive integer'); return opts; } @@ -75,8 +86,10 @@ async function watch(opts) { const stamp = () => new Date().toISOString(); console.log(`${stamp()} tripwire watching :${opts.port} for pids in ${opts.pidsDir} (+ socket holders under ${opts.socketPrefixes.join(', ') || 'none'})`); let samples = 0; + let socketHolders = []; for (;;) { - const { treeSize, violations } = sample(opts); + if (opts.socketPrefixes.length && samples % opts.socketScanEvery === 0) socketHolders = [...unixSocketHolders(opts.socketPrefixes)]; + const { treeSize, violations } = sample({ ...opts, socketHolders }); samples++; if (violations.length) { const record = { at: stamp(), port: opts.port, samples, violations }; @@ -84,7 +97,7 @@ async function watch(opts) { console.log(`${stamp()} TRIPPED: ${JSON.stringify(violations)}`); process.exit(TRIPWIRE_EXIT_CODE); } - if (samples % 60 === 1) console.log(`${stamp()} sample ${samples}: tree of ${treeSize}, no connection on :${opts.port}`); + if (samples % 30 === 1) console.log(`${stamp()} sample ${samples}: tree of ${treeSize}, no connection on :${opts.port}`); await new Promise((r) => setTimeout(r, opts.interval)); } } @@ -92,7 +105,7 @@ async function watch(opts) { if (import.meta.url === pathToFileURL(process.argv[1]).href) { const [cmd, ...rest] = process.argv.slice(2); if (cmd !== 'watch') { - console.error('usage: tripwire.mjs watch --port --pids --marker [--socket-prefix ]... [--interval ]'); + console.error('usage: tripwire.mjs watch --port --pids --marker [--socket-prefix ]... [--interval ] [--socket-scan-every ]'); process.exit(64); } watch(parseArgs(rest)).catch((err) => { diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index cd424ac33..c2b5c10c9 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -252,3 +252,24 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when - two new gate-1 self-test cases. - Re-verified in serve-web mode. Self-test 17/17, `start`, `check` 10/10, `seed one-builder` (gate 6: `builder-spir-101` spawned by `main`), `check` 10/10, `stop` (15 PIDs, none left). + +### Phase 1 review, iteration 2 (2026-11-24) + +- Both reviewers approved (Codex with no issues). I took Claude's non-blocking notes before + advancing, because one would have broken later phases: + - **vsix freshness.** `check` called any uncommitted input edit stale and missed untracked + files. So every edit, `build-vsix`, `check` cycle in Phases 5, 8 and 9 would have shown a + spurious FAIL. `build-vsix` now records a content digest of every tracked or untracked input + file, and `check` compares it. Verified all four cases: clean build passes; a file added after + the build fails only the vsix item; a change built in passes; removing it fails again. + - **Tripwire cost.** One sample is about 0.3 s of `ps` plus two `lsof` calls, so sampling at + 1 s kept about a third of a core busy. Now it samples every 2 s and runs the machine-wide + `lsof -U` every 5th sample. Shellpers stay covered between scans as descendants of the live + Tower. + - The socket-prefix match now needs a trailing `/`. + - The README now explains why `selftest` needs the web port (its refusal cases run real `start`). +- Full suite: the architect's standing rule (decision ide-1, 07:27Z) allows `porch done`'s suite + without asking when the 1-minute load is under 6 and no other vitest is running, checked right + before. + - Iteration-1 rebuttal run: load 2.55, passed. + - Iteration-2 run: I waited out a load of 8.18; at 4.85 it passed. From 8e192e471eb17011d87e09c9ea53f75dd9517936 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:40:44 -0800 Subject: [PATCH 039/140] =?UTF-8?q?chore(porch):=201963=20advance=20plan?= =?UTF-8?q?=20phase=20=E2=86=92=20fleet=5Foverviews?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 3fdd22076..e4a4c79b7 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -5,10 +5,10 @@ phase: implement plan_phases: - id: verification_harness title: Isolated verification harness - status: in_progress + status: complete - id: fleet_overviews title: Fleet cache keeps every active workspace's overview - status: pending + status: in_progress - id: architect_tree_builder title: Reusable, workspace-scoped architect-axis row builder status: pending @@ -30,7 +30,7 @@ plan_phases: - id: arrange_cockpit title: 'Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification' status: pending -current_plan_phase: verification_harness +current_plan_phase: fleet_overviews gates: spec-approval: status: approved @@ -44,8 +44,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -60,8 +60,10 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:31:24.088Z' +updated_at: '2026-11-24T07:40:44.236Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' acknowledged_at: '2026-11-24T06:56:42.376Z' + - boundary: plan-phase:fleet_overviews + at: '2026-11-24T07:40:44.236Z' From 0f53ccfc9b7786cb1573bf361e848d83922859cf Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:41:39 -0800 Subject: [PATCH 040/140] chore(porch): 1963 acknowledge context refresh --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index e4a4c79b7..dadfa5924 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -60,10 +60,11 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:40:44.236Z' +updated_at: '2026-11-24T07:41:39.051Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' acknowledged_at: '2026-11-24T06:56:42.376Z' - boundary: plan-phase:fleet_overviews at: '2026-11-24T07:40:44.236Z' + acknowledged_at: '2026-11-24T07:41:39.051Z' From acd2a931b7241131fdf332cee2f96f9b287e1e1a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:43:46 -0800 Subject: [PATCH 041/140] [Spec 1963][Phase: fleet_overviews] feat: keep each active workspace's overview in the fleet cache TowerFleetCache already fetches every active workspace's overview to derive attention, then discarded it. FleetEntry now carries that overview (last-known-good across a failed fetch, null when dormant or never fetched), with a lastOverview map and a getOverview(path) accessor. Dormant and departed workspaces drop their retained overview. No new requests; attention, ordering and the sequence guard are unchanged. The two test helpers that build FleetEntry literals gain the new field. --- .../src/__tests__/switch-workspace.test.ts | 2 +- apps/vscode/src/__tests__/tower-cache.test.ts | 173 ++++++++++++++++++ .../src/__tests__/tower-provider.test.ts | 2 +- apps/vscode/src/views/tower-cache.ts | 52 +++++- 4 files changed, 217 insertions(+), 12 deletions(-) diff --git a/apps/vscode/src/__tests__/switch-workspace.test.ts b/apps/vscode/src/__tests__/switch-workspace.test.ts index eda91391c..a0f23d517 100644 --- a/apps/vscode/src/__tests__/switch-workspace.test.ts +++ b/apps/vscode/src/__tests__/switch-workspace.test.ts @@ -102,7 +102,7 @@ function quiet(): OverviewData { return { builders: [], backlog: [], pendingPRs: [], recentlyClosed: [], architects: [], heldCount: 0, mailboxEscalated: false, queuedFeedback: {}, feedbackMode: 'forward' } as unknown as OverviewData; } function entry(ws: TowerWorkspace, overview: OverviewData | null): FleetEntry { - return { workspace: ws, attention: deriveAttention(overview) }; + return { workspace: ws, attention: deriveAttention(overview), overview }; } describe('buildWorkspacePicks', () => { diff --git a/apps/vscode/src/__tests__/tower-cache.test.ts b/apps/vscode/src/__tests__/tower-cache.test.ts index bfb8589d5..666e0a8f5 100644 --- a/apps/vscode/src/__tests__/tower-cache.test.ts +++ b/apps/vscode/src/__tests__/tower-cache.test.ts @@ -238,3 +238,176 @@ describe('TowerFleetCache', () => { expect(listWorkspaces).not.toHaveBeenCalled(); }); }); + +/** + * Spec 1963 Phase 2: the fan-out's overviews are kept (last-known-good), not discarded after + * `deriveAttention`, so the Cockpit hierarchy can render other workspaces' architects and builders + * with no additional request. + */ +describe('TowerFleetCache overview retention', () => { + afterEach(() => { vi.useRealTimers(); }); + + function entryFor(cache: InstanceType, name: string) { + const entry = cache.getFleet().find((e) => e.workspace.name === name); + if (!entry) { throw new Error(`no fleet entry named ${name}`); } + return entry; + } + + it('keeps each active workspace’s overview on success; a dormant one has none', async () => { + const overviewA = blockedOverview(); + const overviewB = quietOverview(); + const listWorkspaces = vi.fn().mockResolvedValue([ + ws('/ws/a', 'a', true), + ws('/ws/b', 'b', true), + ws('/ws/dormant', 'dormant', false), + ]); + const getOverview = vi.fn(async (path: string) => (path === '/ws/a' ? overviewA : overviewB)); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + + expect(entryFor(cache, 'a').overview).toBe(overviewA); + expect(entryFor(cache, 'b').overview).toBe(overviewB); + expect(entryFor(cache, 'dormant').overview).toBeNull(); + expect(cache.getOverview('/ws/a')).toBe(overviewA); + expect(cache.getOverview('/ws/b')).toBe(overviewB); + expect(cache.getOverview('/ws/dormant')).toBeNull(); + expect(cache.getOverview('/ws/unknown')).toBeNull(); + cache.dispose(); + }); + + it('keeps the last-known-good overview when a later fetch fails (null)', async () => { + const first = blockedOverview(); + const listWorkspaces = vi.fn().mockResolvedValue([ws('/ws/a', 'a', true)]); + const getOverview = vi.fn().mockResolvedValueOnce(first).mockResolvedValueOnce(null); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + expect(cache.getOverview('/ws/a')).toBe(first); + + await cache.refresh(); // transient failure + expect(entryFor(cache, 'a').overview).toBe(first); + expect(cache.getOverview('/ws/a')).toBe(first); + expect(entryFor(cache, 'a').attention.isEmpty).toBe(false); // attention retained alongside + cache.dispose(); + }); + + it('replaces the overview with the newer one on the next successful fetch', async () => { + const first = blockedOverview(); + const second = quietOverview(); + const listWorkspaces = vi.fn().mockResolvedValue([ws('/ws/a', 'a', true)]); + const getOverview = vi.fn().mockResolvedValueOnce(first).mockResolvedValueOnce(second); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + await cache.refresh(); + expect(cache.getOverview('/ws/a')).toBe(second); + expect(entryFor(cache, 'a').attention.isEmpty).toBe(true); + cache.dispose(); + }); + + it('has no overview for an active workspace whose first fetch fails', async () => { + const listWorkspaces = vi.fn().mockResolvedValue([ws('/ws/a', 'a', true)]); + const getOverview = vi.fn().mockResolvedValue(null); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + expect(entryFor(cache, 'a').overview).toBeNull(); + expect(cache.getOverview('/ws/a')).toBeNull(); + cache.dispose(); + }); + + it('drops the retained overview when a workspace goes dormant, and does not revive it on reactivation failure', async () => { + const listWorkspaces = vi.fn() + .mockResolvedValueOnce([ws('/ws/a', 'a', true)]) + .mockResolvedValueOnce([ws('/ws/a', 'a', false)]) + .mockResolvedValueOnce([ws('/ws/a', 'a', true)]); + const getOverview = vi.fn().mockResolvedValueOnce(blockedOverview()).mockResolvedValueOnce(null); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + expect(cache.getOverview('/ws/a')).not.toBeNull(); + + await cache.refresh(); // now dormant + expect(entryFor(cache, 'a').overview).toBeNull(); + expect(cache.getOverview('/ws/a')).toBeNull(); + + // Reactivated, but its first fetch fails: the pre-dormancy overview must not come back. + await cache.refresh(); + expect(entryFor(cache, 'a').overview).toBeNull(); + expect(cache.getOverview('/ws/a')).toBeNull(); + cache.dispose(); + }); + + it('drops the retained overview when a workspace leaves the list', async () => { + const listWorkspaces = vi.fn() + .mockResolvedValueOnce([ws('/ws/a', 'a', true), ws('/ws/b', 'b', true)]) + .mockResolvedValueOnce([ws('/ws/b', 'b', true)]); + const getOverview = vi.fn().mockResolvedValue(quietOverview()); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + expect(cache.getOverview('/ws/a')).not.toBeNull(); + + await cache.refresh(); + expect(cache.getFleet().map((e) => e.workspace.name)).toEqual(['b']); + expect(cache.getOverview('/ws/a')).toBeNull(); + expect(cache.getOverview('/ws/b')).not.toBeNull(); + cache.dispose(); + }); + + it('keeps the overview when the list momentarily returns empty', async () => { + const overview = blockedOverview(); + const listWorkspaces = vi.fn().mockResolvedValueOnce([ws('/ws/a', 'a', true)]).mockResolvedValueOnce([]); + const getOverview = vi.fn().mockResolvedValue(overview); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + await cache.refresh(); // transient list failure surfaces as [] + expect(cache.getOverview('/ws/a')).toBe(overview); + cache.dispose(); + }); + + it('does not let a stale (out-of-sequence) fan-out overwrite a newer overview', async () => { + // `refresh()` serialises fan-outs, so two never overlap through the public API; the sequence + // guard is the backstop. Drive the private fan-out directly to pin that the guard covers the + // retained overview as well as attention. + const stale = blockedOverview(); + const fresh = quietOverview(); + let resolveStale: (v: OverviewData | null) => void = () => {}; + const listWorkspaces = vi.fn().mockResolvedValue([ws('/ws/a', 'a', true)]); + const getOverview = vi.fn() + .mockImplementationOnce(() => new Promise((res) => { resolveStale = res; })) + .mockResolvedValueOnce(fresh); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + const fanOut = (cache as unknown as { fetchFleet(): Promise }).fetchFleet.bind(cache); + + const older = fanOut(); + // Let the older fan-out reach its pending getOverview before the newer one starts. + await vi.waitFor(() => { expect(getOverview).toHaveBeenCalledTimes(1); }); + await fanOut(); // newer fan-out lands first + expect(cache.getOverview('/ws/a')).toBe(fresh); + + resolveStale(stale); // older fan-out lands late + await older; + expect(cache.getOverview('/ws/a')).toBe(fresh); + expect(entryFor(cache, 'a').overview).toBe(fresh); + expect(entryFor(cache, 'a').attention.isEmpty).toBe(true); + cache.dispose(); + }); + + it('makes no extra requests: one getOverview per active workspace per refresh, none from the accessor', async () => { + const listWorkspaces = vi.fn().mockResolvedValue([ + ws('/ws/a', 'a', true), + ws('/ws/b', 'b', true), + ws('/ws/c', 'c', true), + ws('/ws/dormant', 'dormant', false), + ]); + const getOverview = vi.fn().mockResolvedValue(quietOverview()); + const cache = new TowerFleetCache(makeFake(listWorkspaces, getOverview).cm); + await cache.refresh(); + expect(getOverview).toHaveBeenCalledTimes(3); + expect(listWorkspaces).toHaveBeenCalledTimes(1); + + for (const path of ['/ws/a', '/ws/b', '/ws/c', '/ws/dormant', '/ws/unknown']) { cache.getOverview(path); } + expect(getOverview).toHaveBeenCalledTimes(3); + + await cache.refresh(); + expect(getOverview).toHaveBeenCalledTimes(6); + expect(listWorkspaces).toHaveBeenCalledTimes(2); + cache.dispose(); + }); +}); diff --git a/apps/vscode/src/__tests__/tower-provider.test.ts b/apps/vscode/src/__tests__/tower-provider.test.ts index 2f7babe14..12622225f 100644 --- a/apps/vscode/src/__tests__/tower-provider.test.ts +++ b/apps/vscode/src/__tests__/tower-provider.test.ts @@ -78,7 +78,7 @@ function agents(builderState: string, architectState: string, since: string): Ov } function entry(ws: TowerWorkspace, overview: OverviewData | null): FleetEntry { - return { workspace: ws, attention: deriveAttention(overview) }; + return { workspace: ws, attention: deriveAttention(overview), overview }; } function fakeCache(fleet: FleetEntry[], loaded = true) { diff --git a/apps/vscode/src/views/tower-cache.ts b/apps/vscode/src/views/tower-cache.ts index 64b92f19a..c5c0c8f3e 100644 --- a/apps/vscode/src/views/tower-cache.ts +++ b/apps/vscode/src/views/tower-cache.ts @@ -2,12 +2,22 @@ import * as vscode from 'vscode'; import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; import type { AttentionSummary } from '@cluesmith/codev-sdk/builder-helpers'; import type { TowerWorkspace } from '@cluesmith/codev-sdk/tower-client'; +import type { OverviewData } from '@cluesmith/codev-types'; import type { ConnectionManager } from '../connection-manager.js'; -/** A workspace paired with its derived attention roll-up (the Tower view's per-row datum). */ +/** + * A workspace paired with its derived attention roll-up (the Tower view's per-row datum) and the + * overview that attention was derived from. + */ export interface FleetEntry { workspace: TowerWorkspace; attention: AttentionSummary; + /** + * The workspace's last-known-good overview: the latest successful fetch, kept across a failed + * one. `null` for a dormant workspace (never fetched) and for an active one whose overview has + * not yet been fetched successfully. + */ + overview: OverviewData | null; } /** How often the fallback poll re-fetches the fleet when SSE isn't delivering (ms). */ @@ -30,12 +40,16 @@ const REFRESH_DEBOUNCE_MS = 300; * Refresh triggers: every non-heartbeat SSE event; a manual `refresh()` the activate/deactivate * actions call (workspace activation emits no SSE, so the list must be re-polled); and a * low-frequency fallback poll for when SSE isn't delivering. `getOverview` failures never clobber a - * workspace's last-known attention, and out-of-order fan-out landings are dropped by a sequence - * guard (the #916 last-write-wins pattern, at per-workspace granularity). + * workspace's last-known attention or overview, and out-of-order fan-out landings are dropped by a + * sequence guard (the #916 last-write-wins pattern, at per-workspace granularity). + * + * Each active workspace's overview is kept, not just its attention, so other views can render any + * workspace's architects and builders from the fan-out this cache already makes — no extra request. */ export class TowerFleetCache { private entries: FleetEntry[] = []; private lastAttention = new Map(); + private lastOverview = new Map(); private latestSeq = 0; private loaded = false; @@ -84,6 +98,15 @@ export class TowerFleetCache { return this.entries; } + /** + * The last-known-good overview of the workspace at `path` (Tower's spelling, as in + * `FleetEntry.workspace.path`). `null` when the workspace is dormant, not in the fleet, or has + * not yet been fetched successfully. + */ + getOverview(path: string): OverviewData | null { + return this.lastOverview.get(path) ?? null; + } + /** True once the first successful fetch has populated the cache (drives the loading vs empty state). */ isLoaded(): boolean { return this.loaded; @@ -126,8 +149,9 @@ export class TowerFleetCache { * an out-of-order landing is discarded. A transient list failure — `listWorkspaces()` returns `[]` * for any HTTP/timeout error, indistinguishable from a genuinely empty registry — is not allowed to * blank a populated fleet; only the first load may commit an empty list. A dormant workspace - * contributes an empty summary without a fetch; an active workspace whose overview fetch fails - * keeps its previous attention. + * contributes an empty summary and a `null` overview without a fetch; an active workspace whose + * overview fetch fails keeps its previous attention and overview. Workspaces that are dormant or + * gone from the list drop their retained overview with the commit. */ private async fetchFleet(): Promise { const client = this.connectionManager.getClient(); @@ -146,21 +170,29 @@ export class TowerFleetCache { const entries = await Promise.all(workspaces.map(async (workspace): Promise => { if (!workspace.active) { - return { workspace, attention: deriveAttention(null) }; + return { workspace, attention: deriveAttention(null), overview: null }; } const overview = await client.getOverview(workspace.path); if (overview === null) { - // Transient fetch failure — retain this workspace's last-known attention rather than - // flipping it to quiet on a blip. + // Transient fetch failure — retain this workspace's last-known attention and overview + // rather than flipping it to quiet (or emptying its rows) on a blip. const previous = this.lastAttention.get(workspace.path); - return { workspace, attention: previous ?? deriveAttention(null) }; + return { + workspace, + attention: previous ?? deriveAttention(null), + overview: this.lastOverview.get(workspace.path) ?? null, + }; } - return { workspace, attention: deriveAttention(overview) }; + return { workspace, attention: deriveAttention(overview), overview }; })); if (mySeq !== this.latestSeq) { return; } this.entries = entries; this.lastAttention = new Map(entries.map((e) => [e.workspace.path, e.attention])); + this.lastOverview = new Map(); + for (const entry of entries) { + if (entry.overview !== null) { this.lastOverview.set(entry.workspace.path, entry.overview); } + } this.loaded = true; this.changeEmitter.fire(); } From dafe95a01f3d3ebd441aa0364e18a98c4df00d92 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:45:00 -0800 Subject: [PATCH 042/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index dadfa5924..fd8f397c4 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:41:39.051Z' +updated_at: '2026-11-24T07:45:00.610Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 17ec98bb3a7335be9a4a82ebc426ef13ef447613 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:45:09 -0800 Subject: [PATCH 043/140] [Spec 1963][Phase: fleet_overviews] docs: thread entry for Phase 2 --- codev/state/spir-1963_thread.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index c2b5c10c9..6b1fce3a0 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -273,3 +273,31 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when before. - Iteration-1 rebuttal run: load 2.55, passed. - Iteration-2 run: I waited out a load of 8.18; at 4.85 it passed. + +### Phase 2 (`fleet_overviews`), iteration 1 (2026-11-24) + +- `TowerFleetCache` now keeps the overview it already fetched for each active workspace, instead + of discarding it after `deriveAttention`. + - `FleetEntry` gains `overview: OverviewData | null`. + - A new `lastOverview` map holds the last-known-good overview, next to `lastAttention`. + - A new `getOverview(path)` accessor returns it. +- Behaviour: + - A failed (`null`) fetch keeps the previous overview. + - A dormant workspace gets `null` and drops what it had. A reactivated workspace whose first + fetch fails does not get its pre-dormancy overview back. + - A workspace that leaves the list is dropped. + - A transiently empty list keeps everything, as before. +- No new requests: per refresh there is still one `getOverview` call per active workspace. +- I changed two files outside the plan's list, `tower-provider.test.ts` and + `switch-workspace.test.ts`. Their `entry()` helpers build `FleetEntry` literals, and `tsc` + type-checks the tests, so the helpers needed the new required field. It was a one-line change + in each. +- The stale-fan-out test calls the private `fetchFleet` directly. `refresh()` serialises + fan-outs, so through the public API the sequence guard is only a backstop and the race cannot + be reached. +- Mutation-checked: removing the sequence guard, the map rebuild, or the retain-on-null each makes + its matching test fail. +- `check-types` and `lint` are clean, apart from the two pre-existing `curly` warnings. + `porch done` checks passed: build 15.6 s, tests 56.4 s, at a 1-minute load of 3.44 with no other + vitest running. + `test:unit` passed 1293/1293. From d21d998ba31e58777bee8b44051a123ba6b3d422 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:46:58 -0800 Subject: [PATCH 044/140] [Spec 1963][Phase: fleet_overviews] docs: retained overview is shared and read-only; review notes --- apps/vscode/src/views/tower-cache.ts | 6 ++++-- codev/state/spir-1963_thread.md | 14 ++++++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/apps/vscode/src/views/tower-cache.ts b/apps/vscode/src/views/tower-cache.ts index c5c0c8f3e..8625660d0 100644 --- a/apps/vscode/src/views/tower-cache.ts +++ b/apps/vscode/src/views/tower-cache.ts @@ -15,7 +15,8 @@ export interface FleetEntry { /** * The workspace's last-known-good overview: the latest successful fetch, kept across a failed * one. `null` for a dormant workspace (never fetched) and for an active one whose overview has - * not yet been fetched successfully. + * not yet been fetched successfully. The object is the cache's own copy, shared by every reader: + * treat it as read-only (copy before sorting or otherwise mutating). */ overview: OverviewData | null; } @@ -101,7 +102,8 @@ export class TowerFleetCache { /** * The last-known-good overview of the workspace at `path` (Tower's spelling, as in * `FleetEntry.workspace.path`). `null` when the workspace is dormant, not in the fleet, or has - * not yet been fetched successfully. + * not yet been fetched successfully. Returned by reference, the same object as the fleet entry's + * `overview`: read-only for callers. */ getOverview(path: string): OverviewData | null { return this.lastOverview.get(path) ?? null; diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 6b1fce3a0..82eb6a259 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -298,6 +298,16 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when - Mutation-checked: removing the sequence guard, the map rebuild, or the retain-on-null each makes its matching test fail. - `check-types` and `lint` are clean, apart from the two pre-existing `curly` warnings. - `porch done` checks passed: build 15.6 s, tests 56.4 s, at a 1-minute load of 3.44 with no other - vitest running. `test:unit` passed 1293/1293. +- `porch done` checks passed: build 15.6 s, tests 56.4 s, at a 1-minute load of 3.44 with no other + vitest running. +- Review: Codex and Claude both approved with high confidence, and neither raised a blocking issue. + - Taken now: Claude's note that the accessor hands out the cached object by reference. The doc + comments on `FleetEntry.overview` and `getOverview` now say it is read-only. + - Carried into Phase 4, not changed here: + - The window's own workspace is retained twice, in `OverviewCache` and in the fleet cache. The + Cockpit must keep reading `OverviewCache` for it, as the spec says. Reading the fleet copy + would lag. + - The fleet cache keys by Tower's path spelling. Phase 4's current-workspace match must use + the existing `isSameWorkspacePath` (`fleet-order.ts`), as `orderFleet` does, and a test should + assert it. From a89159cf38742e8da62a080c1d33814cfb095497 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:47:00 -0800 Subject: [PATCH 045/140] =?UTF-8?q?chore(porch):=201963=20advance=20plan?= =?UTF-8?q?=20phase=20=E2=86=92=20architect=5Ftree=5Fbuilder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1963-vscode-alternative-layout-seco/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index fd8f397c4..503f52f61 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -8,10 +8,10 @@ plan_phases: status: complete - id: fleet_overviews title: Fleet cache keeps every active workspace's overview - status: in_progress + status: complete - id: architect_tree_builder title: Reusable, workspace-scoped architect-axis row builder - status: pending + status: in_progress - id: cockpit_hierarchy title: Cockpit button and the Tower → workspaces → architects → builders tree status: pending @@ -30,7 +30,7 @@ plan_phases: - id: arrange_cockpit title: 'Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification' status: pending -current_plan_phase: fleet_overviews +current_plan_phase: architect_tree_builder gates: spec-approval: status: approved @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:45:00.610Z' +updated_at: '2026-11-24T07:47:00.222Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -68,3 +68,5 @@ context_refreshes: - boundary: plan-phase:fleet_overviews at: '2026-11-24T07:40:44.236Z' acknowledged_at: '2026-11-24T07:41:39.051Z' + - boundary: plan-phase:architect_tree_builder + at: '2026-11-24T07:47:00.222Z' From 252491c769d352ec511dfd3202fb1065e3dd24aa Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:47:49 -0800 Subject: [PATCH 046/140] chore(porch): 1963 acknowledge context refresh --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 503f52f61..d9d2a0313 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:47:00.222Z' +updated_at: '2026-11-24T07:47:49.148Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -70,3 +70,4 @@ context_refreshes: acknowledged_at: '2026-11-24T07:41:39.051Z' - boundary: plan-phase:architect_tree_builder at: '2026-11-24T07:47:00.222Z' + acknowledged_at: '2026-11-24T07:47:49.148Z' From 57963d08e7ebcc35d11c0da752e14efd487d04fa Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:57:58 -0800 Subject: [PATCH 047/140] [Spec 1963][Phase: architect_tree_builder] feat: reusable, workspace-scoped ArchitectTreeBuilder behind the Agents view --- .../__snapshots__/architect-tree.test.ts.snap | 347 +++++++ .../src/__tests__/architect-tree.test.ts | 542 +++++++++++ apps/vscode/src/views/architect-tree.ts | 861 ++++++++++++++++++ .../src/views/builder-file-tree-item.ts | 9 +- .../src/views/builder-folder-tree-item.ts | 6 +- apps/vscode/src/views/builder-tree-item.ts | 19 +- apps/vscode/src/views/builders.ts | 705 +------------- codev/state/spir-1963_thread.md | 65 ++ 8 files changed, 1876 insertions(+), 678 deletions(-) create mode 100644 apps/vscode/src/__tests__/__snapshots__/architect-tree.test.ts.snap create mode 100644 apps/vscode/src/__tests__/architect-tree.test.ts create mode 100644 apps/vscode/src/views/architect-tree.ts diff --git a/apps/vscode/src/__tests__/__snapshots__/architect-tree.test.ts.snap b/apps/vscode/src/__tests__/__snapshots__/architect-tree.test.ts.snap new file mode 100644 index 000000000..bd7f8af33 --- /dev/null +++ b/apps/vscode/src/__tests__/__snapshots__/architect-tree.test.ts.snap @@ -0,0 +1,347 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=0 · architect axis · flat files 1`] = ` +{ + "cycle": [ + "architect:main", + ], + "rows": [ + "id=builder-group:main | label=MAIN (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("main") | tip="No builders" | parent=root", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=0 · architect axis · tree files 1`] = ` +{ + "cycle": [ + "architect:main", + ], + "rows": [ + "id=builder-group:main | label=MAIN (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("main") | tip="No builders" | parent=root", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=0 · area axis · flat files 1`] = ` +{ + "cycle": [], + "rows": [], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=0 · area axis · tree files 1`] = ` +{ + "cycle": [], + "rows": [], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=0 · stage axis · flat files 1`] = ` +{ + "cycle": [], + "rows": [], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=0 · stage axis · tree files 1`] = ` +{ + "cycle": [], + "rows": [], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=1 · architect axis · flat files 1`] = ` +{ + "cycle": [ + "architect:main", + "builder:pir-1", + "architect:reviewer", + ], + "rows": [ + "id=builder-group:main | label=MAIN (1) | desc=- | ctx=group-builder | state=2 | icon=circle-filled/testing.iconPassed | cmd=codev.openArchitectTerminal("main") | tip="0 blocked · 0 waiting · 1 active" | parent=root", + " id=pir-1#0 | label=[implement] #1 solo | desc=- | ctx=builder-pir | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%" | parent=builder-group:main", + " id=pir-1::src/only.ts | label=only.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/only.ts" | parent=pir-1#0", + "id=builder-group:reviewer | label=REVIEWER (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("reviewer") | tip="No builders" | parent=root", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=1 · architect axis · tree files 1`] = ` +{ + "cycle": [ + "architect:main", + "builder:pir-1", + "architect:reviewer", + ], + "rows": [ + "id=builder-group:main | label=MAIN (1) | desc=- | ctx=group-builder | state=2 | icon=circle-filled/testing.iconPassed | cmd=codev.openArchitectTerminal("main") | tip="0 blocked · 0 waiting · 1 active" | parent=root", + " id=pir-1#0 | label=[implement] #1 solo | desc=- | ctx=builder-pir | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%" | parent=builder-group:main", + " id=pir-1::folder::src | label=src | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=pir-1#0", + " id=pir-1::src/only.ts | label=only.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/only.ts" | parent=pir-1::folder::src", + "id=builder-group:reviewer | label=REVIEWER (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("reviewer") | tip="No builders" | parent=root", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=1 · area axis · flat files 1`] = ` +{ + "cycle": [ + "builder:pir-1", + ], + "rows": [ + "id=pir-1#0 | label=[implement] #1 solo | desc=- | ctx=builder-pir | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%" | parent=root", + " id=pir-1::src/only.ts | label=only.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/only.ts" | parent=pir-1#0", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=1 · area axis · tree files 1`] = ` +{ + "cycle": [ + "builder:pir-1", + ], + "rows": [ + "id=pir-1#0 | label=[implement] #1 solo | desc=- | ctx=builder-pir | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%" | parent=root", + " id=pir-1::folder::src | label=src | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=pir-1#0", + " id=pir-1::src/only.ts | label=only.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/only.ts" | parent=pir-1::folder::src", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=1 · stage axis · flat files 1`] = ` +{ + "cycle": [ + "builder:pir-1", + ], + "rows": [ + "id=builder-group:implement | label=IMPLEMENT (1) | desc=- | ctx=group-builder | state=2 | icon=circle-filled/testing.iconPassed | cmd=- | tip="0 blocked · 0 waiting · 1 active" | parent=root", + " id=pir-1#0 | label=#1 solo | desc=- | ctx=builder-pir | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%" | parent=builder-group:implement", + " id=pir-1::src/only.ts | label=only.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/only.ts" | parent=pir-1#0", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N=1 · stage axis · tree files 1`] = ` +{ + "cycle": [ + "builder:pir-1", + ], + "rows": [ + "id=builder-group:implement | label=IMPLEMENT (1) | desc=- | ctx=group-builder | state=2 | icon=circle-filled/testing.iconPassed | cmd=- | tip="0 blocked · 0 waiting · 1 active" | parent=root", + " id=pir-1#0 | label=#1 solo | desc=- | ctx=builder-pir | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%" | parent=builder-group:implement", + " id=pir-1::folder::src | label=src | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=pir-1#0", + " id=pir-1::src/only.ts | label=only.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/only.ts" | parent=pir-1::folder::src", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N>1 · architect axis · flat files 1`] = ` +{ + "cycle": [ + "architect:main", + "builder:spir-10", + "builder:air-11", + "architect:ghost", + "builder:pir-13", + "architect:web", + "builder:aspir-14", + "builder:bugfix-12", + "architect:demos", + "architect:reviewer", + ], + "rows": [ + "id=builder-group:main | label=MAIN (2) | desc=- | ctx=group-builder | state=2 | icon=bell/notificationsWarningIcon.foreground | cmd=codev.openArchitectTerminal("main") | tip="1 blocked · 1 waiting · 0 active" | parent=root", + " id=spir-10#0 | label=[plan] #10 gated blocked on plan review [2h] | desc=- | ctx=blocked-builder-spir | state=1 | icon=checklist/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: spir | Mode: strict | Progress: 0%\\nBlocked on plan review" | parent=builder-group:main", + " id=spir-10::README.md | label=README.md | desc= | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · README.md" | parent=spir-10#0", + " id=spir-10::src/views/a.ts | label=a.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/a.ts" | parent=spir-10#0", + " id=spir-10::src/views/b.ts | label=b.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/b.ts" | parent=spir-10#0", + " id=spir-10::src/extension.ts | label=extension.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/extension.ts" | parent=spir-10#0", + " id=air-11#0 | label=[implement] #11 orphan turn ended [30m] | desc=- | ctx=awaiting-builder-air | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: air | Mode: strict | Progress: 0%\\nTurn ended" | parent=builder-group:main", + " id=- | label=Diff unavailable | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip="git failed" | parent=root", + "id=builder-group:ghost | label=GHOST (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openArchitectTerminal("ghost") | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=pir-13#0 | label=[review] #13 asks asking a question [5m] | desc=- | ctx=awaiting-builder-pir | state=1 | icon=question/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%\\nAsking a question" | parent=builder-group:ghost", + " id=- | label=No worktree on record | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:web | label=WEB (2) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openArchitectTerminal("web") | tip="0 blocked · 1 waiting · 1 active" | parent=root", + " id=aspir-14#0 | label=[specify] #14 quiet waiting on input [10h silent] | desc=- | ctx=awaiting-builder-aspir | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: aspir | Mode: strict | Progress: 0%\\nWaiting on input" | parent=builder-group:web", + " id=- | label=No changes yet | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + " id=bugfix-12#0 | label=[pr] #12 busy | desc=- | ctx=builder-bugfix | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: bugfix | Mode: strict | Progress: 0%" | parent=builder-group:web", + " id=bugfix-12::packages/x/y.ts | label=y.ts | desc=packages/x | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · packages/x/y.ts" | parent=bugfix-12#0", + "id=idle-architects-group | label=Idle Architects (2) | desc=- | ctx=group-idle-architects | state=1 | icon=circle-outline/disabledForeground | cmd=- | tip="2 idle architects · no builders attached" | parent=root", + " id=builder-group:demos | label=DEMOS (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("demos") | tip="No builders" | parent=idle-architects-group", + " id=builder-group:reviewer | label=REVIEWER (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("reviewer") | tip="No builders" | parent=idle-architects-group", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N>1 · architect axis · tree files 1`] = ` +{ + "cycle": [ + "architect:main", + "builder:spir-10", + "builder:air-11", + "architect:ghost", + "builder:pir-13", + "architect:web", + "builder:aspir-14", + "builder:bugfix-12", + "architect:demos", + "architect:reviewer", + ], + "rows": [ + "id=builder-group:main | label=MAIN (2) | desc=- | ctx=group-builder | state=2 | icon=bell/notificationsWarningIcon.foreground | cmd=codev.openArchitectTerminal("main") | tip="1 blocked · 1 waiting · 0 active" | parent=root", + " id=spir-10#0 | label=[plan] #10 gated blocked on plan review [2h] | desc=- | ctx=blocked-builder-spir | state=1 | icon=checklist/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: spir | Mode: strict | Progress: 0%\\nBlocked on plan review" | parent=builder-group:main", + " id=spir-10::folder::src | label=src | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=spir-10#0", + " id=spir-10::folder::src/views | label=views | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=spir-10::folder::src", + " id=spir-10::src/views/a.ts | label=a.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/a.ts" | parent=spir-10::folder::src/views", + " id=spir-10::src/views/b.ts | label=b.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/b.ts" | parent=spir-10::folder::src/views", + " id=spir-10::src/extension.ts | label=extension.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/extension.ts" | parent=spir-10::folder::src", + " id=spir-10::README.md | label=README.md | desc= | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · README.md" | parent=spir-10#0", + " id=air-11#0 | label=[implement] #11 orphan turn ended [30m] | desc=- | ctx=awaiting-builder-air | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: air | Mode: strict | Progress: 0%\\nTurn ended" | parent=builder-group:main", + " id=- | label=Diff unavailable | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip="git failed" | parent=root", + "id=builder-group:ghost | label=GHOST (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openArchitectTerminal("ghost") | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=pir-13#0 | label=[review] #13 asks asking a question [5m] | desc=- | ctx=awaiting-builder-pir | state=1 | icon=question/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%\\nAsking a question" | parent=builder-group:ghost", + " id=- | label=No worktree on record | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:web | label=WEB (2) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openArchitectTerminal("web") | tip="0 blocked · 1 waiting · 1 active" | parent=root", + " id=aspir-14#0 | label=[specify] #14 quiet waiting on input [10h silent] | desc=- | ctx=awaiting-builder-aspir | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: aspir | Mode: strict | Progress: 0%\\nWaiting on input" | parent=builder-group:web", + " id=- | label=No changes yet | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + " id=bugfix-12#0 | label=[pr] #12 busy | desc=- | ctx=builder-bugfix | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: bugfix | Mode: strict | Progress: 0%" | parent=builder-group:web", + " id=bugfix-12::folder::packages/x | label=packages/x | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=bugfix-12#0", + " id=bugfix-12::packages/x/y.ts | label=y.ts | desc=packages/x | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · packages/x/y.ts" | parent=bugfix-12::folder::packages/x", + "id=idle-architects-group | label=Idle Architects (2) | desc=- | ctx=group-idle-architects | state=1 | icon=circle-outline/disabledForeground | cmd=- | tip="2 idle architects · no builders attached" | parent=root", + " id=builder-group:demos | label=DEMOS (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("demos") | tip="No builders" | parent=idle-architects-group", + " id=builder-group:reviewer | label=REVIEWER (0) | desc=- | ctx=group-builder | state=0 | icon=circle-outline/disabledForeground | cmd=codev.openArchitectTerminal("reviewer") | tip="No builders" | parent=idle-architects-group", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N>1 · area axis · flat files 1`] = ` +{ + "cycle": [ + "builder:air-11", + "builder:aspir-14", + "builder:spir-10", + "builder:bugfix-12", + "builder:pir-13", + ], + "rows": [ + "id=builder-group:porch | label=PORCH (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=air-11#0 | label=[implement] #11 orphan turn ended [30m] | desc=- | ctx=awaiting-builder-air | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: air | Mode: strict | Progress: 0%\\nTurn ended" | parent=builder-group:porch", + " id=- | label=Diff unavailable | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip="git failed" | parent=root", + "id=builder-group:tower | label=TOWER (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=aspir-14#0 | label=[specify] #14 quiet waiting on input [10h silent] | desc=- | ctx=awaiting-builder-aspir | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: aspir | Mode: strict | Progress: 0%\\nWaiting on input" | parent=builder-group:tower", + " id=- | label=No changes yet | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:vscode | label=VSCODE (2) | desc=- | ctx=group-builder | state=2 | icon=bell/notificationsWarningIcon.foreground | cmd=- | tip="1 blocked · 0 waiting · 1 active" | parent=root", + " id=spir-10#0 | label=[plan] #10 gated blocked on plan review [2h] | desc=- | ctx=blocked-builder-spir | state=1 | icon=checklist/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: spir | Mode: strict | Progress: 0%\\nBlocked on plan review" | parent=builder-group:vscode", + " id=spir-10::README.md | label=README.md | desc= | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · README.md" | parent=spir-10#0", + " id=spir-10::src/views/a.ts | label=a.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/a.ts" | parent=spir-10#0", + " id=spir-10::src/views/b.ts | label=b.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/b.ts" | parent=spir-10#0", + " id=spir-10::src/extension.ts | label=extension.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/extension.ts" | parent=spir-10#0", + " id=bugfix-12#0 | label=[pr] #12 busy | desc=- | ctx=builder-bugfix | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: bugfix | Mode: strict | Progress: 0%" | parent=builder-group:vscode", + " id=bugfix-12::packages/x/y.ts | label=y.ts | desc=packages/x | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · packages/x/y.ts" | parent=bugfix-12#0", + "id=builder-group:Uncategorized | label=UNCATEGORIZED (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=pir-13#0 | label=[review] #13 asks asking a question [5m] | desc=- | ctx=awaiting-builder-pir | state=1 | icon=question/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%\\nAsking a question" | parent=builder-group:Uncategorized", + " id=- | label=No worktree on record | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N>1 · area axis · tree files 1`] = ` +{ + "cycle": [ + "builder:air-11", + "builder:aspir-14", + "builder:spir-10", + "builder:bugfix-12", + "builder:pir-13", + ], + "rows": [ + "id=builder-group:porch | label=PORCH (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=air-11#0 | label=[implement] #11 orphan turn ended [30m] | desc=- | ctx=awaiting-builder-air | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: air | Mode: strict | Progress: 0%\\nTurn ended" | parent=builder-group:porch", + " id=- | label=Diff unavailable | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip="git failed" | parent=root", + "id=builder-group:tower | label=TOWER (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=aspir-14#0 | label=[specify] #14 quiet waiting on input [10h silent] | desc=- | ctx=awaiting-builder-aspir | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: aspir | Mode: strict | Progress: 0%\\nWaiting on input" | parent=builder-group:tower", + " id=- | label=No changes yet | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:vscode | label=VSCODE (2) | desc=- | ctx=group-builder | state=2 | icon=bell/notificationsWarningIcon.foreground | cmd=- | tip="1 blocked · 0 waiting · 1 active" | parent=root", + " id=spir-10#0 | label=[plan] #10 gated blocked on plan review [2h] | desc=- | ctx=blocked-builder-spir | state=1 | icon=checklist/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: spir | Mode: strict | Progress: 0%\\nBlocked on plan review" | parent=builder-group:vscode", + " id=spir-10::folder::src | label=src | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=spir-10#0", + " id=spir-10::folder::src/views | label=views | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=spir-10::folder::src", + " id=spir-10::src/views/a.ts | label=a.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/a.ts" | parent=spir-10::folder::src/views", + " id=spir-10::src/views/b.ts | label=b.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/b.ts" | parent=spir-10::folder::src/views", + " id=spir-10::src/extension.ts | label=extension.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/extension.ts" | parent=spir-10::folder::src", + " id=spir-10::README.md | label=README.md | desc= | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · README.md" | parent=spir-10#0", + " id=bugfix-12#0 | label=[pr] #12 busy | desc=- | ctx=builder-bugfix | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: bugfix | Mode: strict | Progress: 0%" | parent=builder-group:vscode", + " id=bugfix-12::folder::packages/x | label=packages/x | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=bugfix-12#0", + " id=bugfix-12::packages/x/y.ts | label=y.ts | desc=packages/x | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · packages/x/y.ts" | parent=bugfix-12::folder::packages/x", + "id=builder-group:Uncategorized | label=UNCATEGORIZED (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=pir-13#0 | label=[review] #13 asks asking a question [5m] | desc=- | ctx=awaiting-builder-pir | state=1 | icon=question/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%\\nAsking a question" | parent=builder-group:Uncategorized", + " id=- | label=No worktree on record | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N>1 · stage axis · flat files 1`] = ` +{ + "cycle": [ + "builder:aspir-14", + "builder:spir-10", + "builder:air-11", + "builder:pir-13", + "builder:bugfix-12", + ], + "rows": [ + "id=builder-group:specify | label=SPECIFY (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=aspir-14#0 | label=[tower] #14 quiet waiting on input [10h silent] | desc=- | ctx=awaiting-builder-aspir | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: aspir | Mode: strict | Progress: 0%\\nWaiting on input" | parent=builder-group:specify", + " id=- | label=No changes yet | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:plan | label=PLAN (1) | desc=- | ctx=group-builder | state=2 | icon=bell/notificationsWarningIcon.foreground | cmd=- | tip="1 blocked · 0 waiting · 0 active" | parent=root", + " id=spir-10#0 | label=[vscode] #10 gated blocked on plan review [2h] | desc=- | ctx=blocked-builder-spir | state=1 | icon=checklist/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: spir | Mode: strict | Progress: 0%\\nBlocked on plan review" | parent=builder-group:plan", + " id=spir-10::README.md | label=README.md | desc= | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · README.md" | parent=spir-10#0", + " id=spir-10::src/views/a.ts | label=a.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/a.ts" | parent=spir-10#0", + " id=spir-10::src/views/b.ts | label=b.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/b.ts" | parent=spir-10#0", + " id=spir-10::src/extension.ts | label=extension.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/extension.ts" | parent=spir-10#0", + "id=builder-group:implement | label=IMPLEMENT (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=air-11#0 | label=[porch] #11 orphan turn ended [30m] | desc=- | ctx=awaiting-builder-air | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: air | Mode: strict | Progress: 0%\\nTurn ended" | parent=builder-group:implement", + " id=- | label=Diff unavailable | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip="git failed" | parent=root", + "id=builder-group:review | label=REVIEW (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=pir-13#0 | label=#13 asks asking a question [5m] | desc=- | ctx=awaiting-builder-pir | state=1 | icon=question/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%\\nAsking a question" | parent=builder-group:review", + " id=- | label=No worktree on record | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:pr | label=PR (1) | desc=- | ctx=group-builder | state=2 | icon=circle-filled/testing.iconPassed | cmd=- | tip="0 blocked · 0 waiting · 1 active" | parent=root", + " id=bugfix-12#0 | label=[vscode] #12 busy | desc=- | ctx=builder-bugfix | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: bugfix | Mode: strict | Progress: 0%" | parent=builder-group:pr", + " id=bugfix-12::packages/x/y.ts | label=y.ts | desc=packages/x | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · packages/x/y.ts" | parent=bugfix-12#0", + ], +} +`; + +exports[`Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider) > N>1 · stage axis · tree files 1`] = ` +{ + "cycle": [ + "builder:aspir-14", + "builder:spir-10", + "builder:air-11", + "builder:pir-13", + "builder:bugfix-12", + ], + "rows": [ + "id=builder-group:specify | label=SPECIFY (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=aspir-14#0 | label=[tower] #14 quiet waiting on input [10h silent] | desc=- | ctx=awaiting-builder-aspir | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: aspir | Mode: strict | Progress: 0%\\nWaiting on input" | parent=builder-group:specify", + " id=- | label=No changes yet | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:plan | label=PLAN (1) | desc=- | ctx=group-builder | state=2 | icon=bell/notificationsWarningIcon.foreground | cmd=- | tip="1 blocked · 0 waiting · 0 active" | parent=root", + " id=spir-10#0 | label=[vscode] #10 gated blocked on plan review [2h] | desc=- | ctx=blocked-builder-spir | state=1 | icon=checklist/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: spir | Mode: strict | Progress: 0%\\nBlocked on plan review" | parent=builder-group:plan", + " id=spir-10::folder::src | label=src | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=spir-10#0", + " id=spir-10::folder::src/views | label=views | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=spir-10::folder::src", + " id=spir-10::src/views/a.ts | label=a.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/a.ts" | parent=spir-10::folder::src/views", + " id=spir-10::src/views/b.ts | label=b.ts | desc=src/views | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/views/b.ts" | parent=spir-10::folder::src/views", + " id=spir-10::src/extension.ts | label=extension.ts | desc=src | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · src/extension.ts" | parent=spir-10::folder::src", + " id=spir-10::README.md | label=README.md | desc= | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · README.md" | parent=spir-10#0", + "id=builder-group:implement | label=IMPLEMENT (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=air-11#0 | label=[porch] #11 orphan turn ended [30m] | desc=- | ctx=awaiting-builder-air | state=1 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: air | Mode: strict | Progress: 0%\\nTurn ended" | parent=builder-group:implement", + " id=- | label=Diff unavailable | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip="git failed" | parent=root", + "id=builder-group:review | label=REVIEW (1) | desc=- | ctx=group-builder | state=2 | icon=comment-discussion/notificationsInfoIcon.foreground | cmd=- | tip="0 blocked · 1 waiting · 0 active" | parent=root", + " id=pir-13#0 | label=#13 asks asking a question [5m] | desc=- | ctx=awaiting-builder-pir | state=1 | icon=question/notificationsWarningIcon.foreground | cmd=codev.openBuilderRow() | tip="Protocol: pir | Mode: strict | Progress: 0%\\nAsking a question" | parent=builder-group:review", + " id=- | label=No worktree on record | desc=- | ctx=builder-file-none | state=- | icon=circle-slash/disabledForeground | cmd=- | tip=null | parent=root", + "id=builder-group:pr | label=PR (1) | desc=- | ctx=group-builder | state=2 | icon=circle-filled/testing.iconPassed | cmd=- | tip="0 blocked · 0 waiting · 1 active" | parent=root", + " id=bugfix-12#0 | label=[vscode] #12 busy | desc=- | ctx=builder-bugfix | state=1 | icon=circle-filled/testing.iconPassed | cmd=codev.openBuilderRow() | tip="Protocol: bugfix | Mode: strict | Progress: 0%" | parent=builder-group:pr", + " id=bugfix-12::folder::packages/x | label=packages/x | desc=- | ctx=builder-file-folder | state=2 | icon=folder/- | cmd=- | tip=null | parent=bugfix-12#0", + " id=bugfix-12::packages/x/y.ts | label=y.ts | desc=packages/x | ctx=builder-file | state=- | icon=- | cmd=codev.openBuilderFileDiff() | tip="Modified · packages/x/y.ts" | parent=bugfix-12::folder::packages/x", + ], +} +`; diff --git a/apps/vscode/src/__tests__/architect-tree.test.ts b/apps/vscode/src/__tests__/architect-tree.test.ts new file mode 100644 index 000000000..2d0908d76 --- /dev/null +++ b/apps/vscode/src/__tests__/architect-tree.test.ts @@ -0,0 +1,542 @@ +/** + * Spec 1963 Phase 3: the Agents view's row building, moved out of `BuildersProvider` into the + * reusable, workspace-scoped `ArchitectTreeBuilder` (`views/architect-tree.ts`). + * + * The equivalence block walks the whole Agents tree — every row, its parent, and the agent-cycle + * roster — over N=0/1/>1 builders, on all three grouping axes, in flat and tree file modes. Its + * snapshot (`__snapshots__/architect-tree.test.ts.snap`) was recorded from the pre-refactor + * `BuildersProvider` in the same commit, so any change to an id, label, contextValue, command or + * parent the Agents view renders fails here. + * + * Mocks `vscode` per the established `__tests__` pattern (see builders-autoreveal.test.ts). + */ + +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; +import type * as vscode from 'vscode'; +import type { ArchitectState, OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; +import type { BuilderFileChange } from '../views/builder-diff-cache.js'; +import { readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +/** A worktree path that does not exist: the review-file probe (existsSync) finds nothing. */ +const MISSING_WORKTREE = join(tmpdir(), 'codev-test-missing-worktree'); + +/** Fixed clock, so wait-time suffixes in labels are deterministic. */ +const NOW = Date.parse('2026-11-24T12:00:00.000Z'); +const ago = (minutes: number) => new Date(NOW - minutes * 60_000).toISOString(); + +/** Per-test config overrides the mocked `workspace.getConfiguration` reads. */ +const configValues: Record = {}; + +vi.mock('vscode', () => { + class FakeEventEmitter { + private listeners: Array<(e: T) => void> = []; + readonly event = (listener: (e: T) => void): { dispose: () => void } => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter((l) => l !== listener); } }; + }; + fire = vi.fn((e: T) => { this.listeners.forEach((l) => l(e)); }); + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + resourceUri?: unknown; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { + static readonly Folder = new ThemeIcon('folder'); + constructor(public id: string, public color?: unknown) {} + } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter: FakeEventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + Uri: { from: (parts: unknown) => ({ ...(parts as object), toString: () => JSON.stringify(parts) }) }, + workspace: { + getConfiguration: () => ({ + get: (key: string, def: unknown) => (key in configValues ? configValues[key] : def), + }), + }, + }; +}); + +const { BuildersProvider } = await import('../views/builders.js'); +const { ArchitectTreeBuilder, REMOTE_CONTEXT } = await import('../views/architect-tree.js'); +const { architectGrouping } = await import('../views/builder-grouping.js'); +const { BuilderTreeItem, BuilderGroupTreeItem, IdleArchitectsGroupTreeItem } = await import('../views/builder-tree-item.js'); +const { BuilderFileTreeItem } = await import('../views/builder-file-tree-item.js'); +const { BuilderFolderTreeItem } = await import('../views/builder-folder-tree-item.js'); + +// ── Fixtures ────────────────────────────────────────────────────────────────── + +function builder(overrides: Partial): OverviewBuilder { + return { + id: 'pir-1', issueId: '1', issueTitle: 't', phase: 'implement', protocolPhase: 'implement', + mode: 'strict', gates: {}, worktreePath: MISSING_WORKTREE, roleId: null, protocol: 'pir', + planPhases: [], progress: 0, blocked: null, blockedGate: null, blockedSince: null, + startedAt: null, idleMs: 0, lastDataAt: null, spawnedByArchitect: null, + area: 'Uncategorized', prReady: false, + ...overrides, + } as OverviewBuilder; +} + +function architect(name: string): ArchitectState { + return { name, port: 0, pid: 0 } as ArchitectState; +} + +function overview( + builders: OverviewBuilder[], + architects: ArchitectState[], + extra: Partial = {}, +): OverviewData { + return { + builders, architects, backlog: [], pendingPRs: [], recentlyClosed: [], + heldCount: 0, mailboxEscalated: false, queuedFeedback: {}, + ...extra, + } as unknown as OverviewData; +} + +function mk(relPath: string): BuilderFileChange { + return { + change: { status: 'M', oldPath: null, path: relPath }, + plan: { resourcePath: relPath, left: { kind: 'base', path: relPath }, right: { kind: 'file', path: relPath } }, + } as BuilderFileChange; +} + +/** Diff cache double: a fixed file list per builder id, or an error. */ +function fakeDiffCache(filesById: Record) { + return { + getDiff: async (builderId: string) => { + const files = filesById[builderId]; + if (files instanceof Error) { return { baseRef: 'main', files: [], error: files.message }; } + return { baseRef: 'main', files: files ?? [] }; + }, + } as never; +} + +const DIFFS = fakeDiffCache({ + 'spir-10': [mk('README.md'), mk('src/views/a.ts'), mk('src/views/b.ts'), mk('src/extension.ts')], + 'air-11': new Error('git failed'), + 'bugfix-12': [mk('packages/x/y.ts')], + 'pir-1': [mk('src/only.ts')], +}); + +/** + * N>1: every row kind the Agents tree renders. + * - `spir-10`: blocked at a gate, owned by `main`. + * - `air-11`: null owner (folds into `main`), served idle; its diff errors. + * - `bugfix-12`: owned by sibling `web`, active, with held mail and queued feedback. + * - `pir-13`: owned by `ghost`, an architect that is not live; needs input; no worktree. + * - `aspir-14`: owned by `web`, PTY-silent past the threshold. + * - roster: `main`, `web`, and two idle siblings (`demos`, `reviewer`) → the Idle Architects roll-up. + */ +const MANY = overview( + [ + builder({ id: 'spir-10', issueId: '10', issueTitle: 'gated', protocol: 'spir', protocolPhase: 'plan', + spawnedByArchitect: 'main', area: 'vscode', blocked: 'plan review', blockedGate: 'plan-approval', + blockedSince: ago(120) }), + builder({ id: 'air-11', issueId: '11', issueTitle: 'orphan', protocol: 'air', protocolPhase: 'implement', + spawnedByArchitect: null, area: 'porch', + agentState: { state: 'idle', since: ago(30), source: 'harness', alive: true, activity: null, + activityAt: null, backgroundWork: false } }), + builder({ id: 'bugfix-12', issueId: '12', issueTitle: 'busy', protocol: 'bugfix', protocolPhase: 'pr', + spawnedByArchitect: 'web', area: 'vscode', heldCount: 2 }), + builder({ id: 'pir-13', issueId: '13', issueTitle: 'asks', protocol: 'pir', protocolPhase: 'review', + spawnedByArchitect: 'ghost', worktreePath: '', + agentState: { state: 'needs-input', since: ago(5), source: 'harness', alive: true, + activity: 'needs-input', activityAt: ago(5), backgroundWork: false, + needsInput: { kind: 'question' } } as never }), + builder({ id: 'aspir-14', issueId: '14', issueTitle: 'quiet', protocol: 'aspir', protocolPhase: 'specify', + spawnedByArchitect: 'web', area: 'tower', lastDataAt: ago(600) }), + ], + [architect('main'), architect('web'), architect('demos'), architect('reviewer')], + { heldCount: 3, queuedFeedback: { 'bugfix-12': 4 } }, +); + +const ONE = overview( + [builder({ id: 'pir-1', issueId: '1', issueTitle: 'solo', spawnedByArchitect: 'main' })], + [architect('main'), architect('reviewer')], +); + +const NONE = overview([], [architect('main')]); + +const SCENARIOS: Array<[string, OverviewData]> = [['N=0', NONE], ['N=1', ONE], ['N>1', MANY]]; +const AXES = ['stage', 'area', 'architect'] as const; +const FILE_MODES: Array<[string, boolean]> = [['flat', false], ['tree', true]]; + +// ── Tree walk ───────────────────────────────────────────────────────────────── + +interface TreeSource { + getChildren(element?: vscode.TreeItem): Promise; + getParent(element: vscode.TreeItem): vscode.ProviderResult; +} + +/** One line per rendered field, so a snapshot diff names exactly what moved. */ +function describeRow(item: vscode.TreeItem): string { + const icon = item.iconPath as { id: string; color?: { id: string } } | undefined; + const command = item.command as { command: string; arguments?: unknown[] } | undefined; + let commandText = '-'; + if (command) { + const args = (command.arguments ?? []).map(a => (a === item ? '' : JSON.stringify(a))); + commandText = `${command.command}(${args.join(', ')})`; + } + return [ + `id=${item.id ?? '-'}`, + `label=${String(item.label)}`, + `desc=${item.description ?? '-'}`, + `ctx=${item.contextValue ?? '-'}`, + `state=${item.collapsibleState ?? '-'}`, + `icon=${icon ? `${icon.id}/${icon.color?.id ?? '-'}` : '-'}`, + `cmd=${commandText}`, + `tip=${JSON.stringify(item.tooltip ?? null)}`, + ].join(' | '); +} + +/** + * Every row of the tree, depth-first, each with the id `getParent` answers for it. Expands every + * row that has a chevron (collapsed builder rows included), so changed-file rows are walked too. + */ +async function walk(source: TreeSource): Promise { + const lines: string[] = []; + const visit = async (element: vscode.TreeItem | undefined, depth: number): Promise => { + for (const child of await source.getChildren(element)) { + const parent = (await source.getParent(child)) as vscode.TreeItem | undefined; + lines.push(`${' '.repeat(depth)}${describeRow(child)} | parent=${parent?.id ?? 'root'}`); + if (child.collapsibleState) { await visit(child, depth + 1); } + } + }; + await visit(undefined, 0); + return lines; +} + +beforeAll(() => { vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(NOW); }); +afterAll(() => { vi.useRealTimers(); }); + +function withConfig(values: Record, run: () => Promise): Promise { + Object.assign(configValues, values); + return run().finally(() => { for (const key of Object.keys(values)) { delete configValues[key]; } }); +} + +function agentsProvider(data: OverviewData) { + const cache = { getData: () => data, onDidChange: () => ({ dispose() {} }) } as never; + return new BuildersProvider(cache, DIFFS); +} + +// ── Equivalence with the pre-refactor Agents view ───────────────────────────── + +describe('Agents view rows are unchanged by the refactor (snapshot from the pre-refactor provider)', () => { + for (const [scenario, data] of SCENARIOS) { + for (const axis of AXES) { + for (const [fileMode, asTree] of FILE_MODES) { + it(`${scenario} · ${axis} axis · ${fileMode} files`, async () => { + const rendered = await withConfig( + { buildersGroupBy: axis, buildersFileViewAsTree: asTree }, + async () => { + const provider = agentsProvider(data); + return { + rows: await walk(provider), + cycle: provider.agentCycleOrder().map(t => (t.kind === 'builder' ? `builder:${t.id}` : `architect:${t.name}`)), + }; + }, + ); + expect(rendered).toMatchSnapshot(); + }); + } + } + } +}); + +// ── ArchitectTreeBuilder ────────────────────────────────────────────────────── + +type TreeOptions = ConstructorParameters[0]; + +/** A Cockpit-style builder for this window's workspace: architect axis, acting rows. */ +function actTree(data: OverviewData, scope: string, extra: Partial = {}) { + return new ArchitectTreeBuilder({ + mode: 'act', scope, getData: () => data, grouping: architectGrouping, diffCache: DIFFS, ...extra, + } as TreeOptions); +} + +const TARGET = { path: '/work/other', active: true, name: 'other', isCurrent: false }; + +/** A builder for another workspace's rows: navigate-only. */ +function navigateTree(data: OverviewData, scope: string, target: () => typeof TARGET = () => TARGET) { + return new ArchitectTreeBuilder({ mode: 'navigate', scope, getData: () => data, target }); +} + +/** Every row of a builder's tree, depth-first (expanding everything with a chevron). */ +async function allRows(tree: InstanceType): Promise { + const rows: vscode.TreeItem[] = []; + const visit = async (element: vscode.TreeItem | undefined): Promise => { + for (const child of await tree.getChildren(element)) { + rows.push(child); + if (child.collapsibleState) { await visit(child); } + } + }; + await visit(undefined); + return rows; +} + +function ids(rows: vscode.TreeItem[]): string[] { + return rows.map(r => r.id).filter((id): id is string => id !== undefined); +} + +function find(rows: vscode.TreeItem[], id: string): T { + const row = rows.find(r => r.id === id); + if (!row) { throw new Error(`no row ${id} in ${ids(rows).join(', ')}`); } + return row as T; +} + +/** Every `viewItem` test in `package.json`'s menus, as a predicate over a contextValue. */ +function viewItemMatchers(): Array<{ when: string; matches: (value: string) => boolean }> { + const pkg = JSON.parse(readFileSync(resolve(__dirname, '../../package.json'), 'utf8')); + const matchers: Array<{ when: string; matches: (value: string) => boolean }> = []; + for (const entries of Object.values(pkg.contributes.menus as Record>)) { + for (const entry of entries) { + const when = entry.when ?? ''; + for (const m of when.matchAll(/viewItem\s*==\s*([\w.-]+)/g)) { + matchers.push({ when, matches: v => v === m[1] }); + } + for (const m of when.matchAll(/viewItem\s*=~\s*\/((?:[^/\\]|\\.)+)\/(\w*)/g)) { + const re = new RegExp(m[1], m[2]); + matchers.push({ when, matches: v => re.test(v) }); + } + } + } + return matchers; +} + +describe('row classes without a scope keep their pre-refactor ids', () => { + it('builder, group, idle-container, folder and file rows', () => { + const file = mk('src/a.ts'); + const node = { name: 'src', fullPath: 'src', children: [] }; + expect(new BuilderGroupTreeItem('main', 1, 2, { blocked: 0, idle: 0, active: 1 }).id).toBe('builder-group:main'); + expect(new IdleArchitectsGroupTreeItem(2).id).toBe('idle-architects-group'); + expect(new BuilderFolderTreeItem('pir-1', '/wt', 'main', node).id).toBe('pir-1::folder::src'); + expect(new BuilderFileTreeItem('pir-1', '/wt', 'main', file.change, file.plan).id).toBe('pir-1::src/a.ts'); + for (const row of [ + new BuilderTreeItem('pir-1', 'label'), new BuilderGroupTreeItem('main', 1, 2, { blocked: 0, idle: 0, active: 1 }), + new IdleArchitectsGroupTreeItem(2), new BuilderFolderTreeItem('pir-1', '/wt', 'main', node), + new BuilderFileTreeItem('pir-1', '/wt', 'main', file.change, file.plan), + ]) { + expect(row.scope).toBe(''); + } + }); +}); + +describe('ArchitectTreeBuilder: scoped ids', () => { + it('prefixes every row id with its scope, including changed-file and folder rows', async () => { + await withConfig({ buildersFileViewAsTree: true }, async () => { + const rows = await allRows(actTree(MANY, 'ws:/a|')); + expect(ids(rows).length).toBeGreaterThan(10); + for (const id of ids(rows)) { expect(id.startsWith('ws:/a|')).toBe(true); } + expect(ids(rows)).toEqual(expect.arrayContaining([ + 'ws:/a|builder-group:main', 'ws:/a|spir-10#0', 'ws:/a|spir-10::folder::src', + 'ws:/a|spir-10::src/views/a.ts', 'ws:/a|idle-architects-group', + ])); + for (const row of rows) { + if ('scope' in row) { expect((row as { scope: string }).scope).toBe('ws:/a|'); } + } + }); + }); + + it('two scopes over workspaces that share `main` and a builder id produce disjoint ids', async () => { + const shared = (owner: string) => overview( + [builder({ id: 'x', spawnedByArchitect: owner }), builder({ id: 'pir-1', spawnedByArchitect: null })], + [architect('main'), architect('web'), architect('demos'), architect('reviewer')], + ); + for (const asTree of [false, true]) { + await withConfig({ buildersFileViewAsTree: asTree }, async () => { + const a = ids(await allRows(actTree(shared('main'), 'ws:/a|'))); + const b = ids(await allRows(actTree(shared('main'), 'ws:/b|'))); + const remote = ids(await allRows(navigateTree(shared('web'), 'ws:/c|'))); + expect(a.length).toBeGreaterThan(0); + expect(a.filter(id => b.includes(id))).toEqual([]); + expect(a.filter(id => remote.includes(id))).toEqual([]); + expect(b.filter(id => remote.includes(id))).toEqual([]); + }); + } + }); + + it('the accordion re-versions scoped rows without stacking the prefix', async () => { + const tree = actTree(MANY, 'ws:/a|'); + const before = await tree.getChildren(find(await tree.getChildren(), 'ws:/a|builder-group:main')); + const open = find>(before, 'ws:/a|spir-10#0'); + tree.keepOnlyOpen(open); + const after = await tree.getChildren(find(await tree.getChildren(), 'ws:/a|builder-group:main')); + expect(ids(after)).toEqual(['ws:/a|spir-10#0', 'ws:/a|air-11#1']); + }); +}); + +describe('ArchitectTreeBuilder: act mode, scoped (this window in the Cockpit)', () => { + it('names main vs a sibling in the architect rows\' contextValue; rows otherwise match the Agents view', async () => { + const rows = await allRows(actTree(MANY, 'ws:/a|')); + expect(find(rows, 'ws:/a|builder-group:main').contextValue).toBe('cockpit-architect-main'); + for (const name of ['web', 'ghost', 'demos', 'reviewer']) { + const row = find(rows, `ws:/a|builder-group:${name}`); + expect(row.contextValue).toBe('cockpit-architect-sibling'); + expect(row.command).toEqual({ command: 'codev.openArchitectTerminal', title: 'Open Architect Terminal', arguments: [name] }); + } + // Builder and file rows keep the Agents view's contextValues and commands. + const gated = find(rows, 'ws:/a|spir-10#0'); + expect(gated.contextValue).toBe('blocked-builder-spir'); + expect(gated.command).toEqual({ command: 'codev.openBuilderRow', title: 'Open Builder Terminal', arguments: [gated] }); + expect(find(rows, 'ws:/a|bugfix-12#0').contextValue).toBe('builder-bugfix'); + expect(find(rows, 'ws:/a|bugfix-12::packages/x/y.ts').contextValue).toBe('builder-file'); + }); + + it('folds a builder with no recorded architect into main, and keeps a non-live architect\'s row', async () => { + const tree = actTree(MANY, 'ws:/a|'); + const roots = await tree.getChildren(); + expect(ids(roots)).toEqual([ + 'ws:/a|builder-group:main', 'ws:/a|builder-group:ghost', 'ws:/a|builder-group:web', 'ws:/a|idle-architects-group', + ]); + expect(ids(await tree.getChildren(find(roots, 'ws:/a|builder-group:main')))).toEqual(['ws:/a|spir-10#0', 'ws:/a|air-11#0']); + // `ghost` is not in the live roster, but its builder still gets the row (and its click warns). + const ghost = find(roots, 'ws:/a|builder-group:ghost'); + expect(String(ghost.label)).toBe('GHOST (1)'); + expect(ids(await tree.getChildren(ghost))).toEqual(['ws:/a|pir-13#0']); + }); + + it('rolls two idle siblings into Idle Architects, and a childless architect is a leaf', async () => { + const tree = actTree(MANY, 'ws:/a|'); + const container = find>(await tree.getChildren(), 'ws:/a|idle-architects-group'); + expect(container).toBeInstanceOf(IdleArchitectsGroupTreeItem); + expect(container.contextValue).toBe('group-idle-architects'); + const idle = await tree.getChildren(container); + expect(ids(idle)).toEqual(['ws:/a|builder-group:demos', 'ws:/a|builder-group:reviewer']); + for (const row of idle) { expect(row.collapsibleState).toBe(0); } + + // One idle sibling stays a top-level leaf. + const lone = find(await actTree(ONE, 'ws:/a|').getChildren(), 'ws:/a|builder-group:reviewer'); + expect(lone.collapsibleState).toBe(0); + expect(lone.contextValue).toBe('cockpit-architect-sibling'); + }); + + it('getParent chains file → folder → builder → architect, and idle sibling → container', async () => { + await withConfig({ buildersFileViewAsTree: true }, async () => { + const tree = actTree(MANY, 'ws:/a|'); + await tree.getChildren(); // the root render records each builder's architect row + const file = await tree.findFileItem('spir-10', 'src/views/a.ts'); + expect(file?.id).toBe('ws:/a|spir-10::src/views/a.ts'); + const folder = (await tree.getParent(file!)) as InstanceType; + expect(folder).toBeInstanceOf(BuilderFolderTreeItem); + expect(folder.id).toBe('ws:/a|spir-10::folder::src/views'); + const outer = (await tree.getParent(folder)) as vscode.TreeItem; + expect(outer.id).toBe('ws:/a|spir-10::folder::src'); + const row = (await tree.getParent(outer)) as vscode.TreeItem; + expect(row).toBeInstanceOf(BuilderTreeItem); + expect(row.id).toBe('ws:/a|spir-10#0'); + expect(((await tree.getParent(row)) as vscode.TreeItem).id).toBe('ws:/a|builder-group:main'); + expect(await tree.getParent(find(await tree.getChildren(), 'ws:/a|builder-group:main'))).toBeUndefined(); + + const demos = new BuilderGroupTreeItem('demos', 0, 0, { blocked: 0, idle: 0, active: 0 }, 'ws:/a|'); + expect(((await tree.getParent(demos)) as vscode.TreeItem).id).toBe('ws:/a|idle-architects-group'); + }); + await withConfig({ buildersFileViewAsTree: false }, async () => { + const tree = actTree(MANY, 'ws:/a|'); + const file = await tree.findFileItem('spir-10', 'src/views/a.ts'); + expect(((await tree.getParent(file!)) as vscode.TreeItem).id).toBe('ws:/a|spir-10#0'); + }); + }); + + it('reveals agent-cycle targets as scoped rows', async () => { + const tree = actTree(MANY, 'ws:/a|'); + expect(tree.revealTargetForAgent({ kind: 'builder', id: 'bugfix-12' })?.id).toBe('ws:/a|bugfix-12#0'); + expect(tree.revealTargetForAgent({ kind: 'architect', name: 'web' })?.id).toBe('ws:/a|builder-group:web'); + expect(tree.agentCycleOrder()[0]).toEqual({ kind: 'architect', name: 'main' }); + }); +}); + +describe('ArchitectTreeBuilder: navigate mode (another workspace\'s rows)', () => { + it('builder rows are leaves; architect rows still expand to their builders', async () => { + const tree = navigateTree(MANY, 'ws:/other|'); + const roots = await tree.getChildren(); + const main = find(roots, 'ws:/other|builder-group:main'); + expect(main.collapsibleState).toBe(2); + const builders = await tree.getChildren(main); + expect(ids(builders)).toEqual(['ws:/other|spir-10#0', 'ws:/other|air-11#0']); + for (const row of builders) { + expect(row.collapsibleState).toBe(0); + expect(await tree.getChildren(row)).toEqual([]); + } + expect(await tree.findFileItem('spir-10', 'README.md')).toBeUndefined(); + expect(tree.revealTargetForAgent({ kind: 'builder', id: 'spir-10' })).toBeUndefined(); + }); + + it('every row clicks to open the workspace, and its tooltip names that workspace', async () => { + const rows = await allRows(navigateTree(MANY, 'ws:/other|')); + const clickable = rows.filter(r => !(r instanceof IdleArchitectsGroupTreeItem)); + expect(clickable.length).toBe(MANY.builders.length + 5); // 5 builders, 5 architect rows + for (const row of clickable) { + expect(row.command).toEqual({ command: 'codev.tower.openWorkspace', title: 'Open Workspace', arguments: [TARGET] }); + expect(String(row.tooltip)).toContain('In workspace other. Click to open its window'); + } + // Same labels and glyphs as the acting rows. + const acting = await allRows(actTree(MANY, 'ws:/other|')); + const visible = (r: vscode.TreeItem) => `${String(r.label)} ${JSON.stringify(r.iconPath)}`; + expect(clickable.map(visible)).toEqual(acting.filter(r => r.id && !(r instanceof IdleArchitectsGroupTreeItem) + && !(r instanceof BuilderFileTreeItem) && !(r instanceof BuilderFolderTreeItem)).map(visible)); + }); + + it('carries only navigate-only contextValues, none matched by any package.json menu', async () => { + const rows = await allRows(navigateTree(MANY, 'ws:/other|')); + const values = new Set(rows.map(r => r.contextValue)); + expect([...values].sort()).toEqual([REMOTE_CONTEXT.architect, REMOTE_CONTEXT.builder, REMOTE_CONTEXT.idleArchitects].sort()); + const matchers = viewItemMatchers(); + expect(matchers.length).toBeGreaterThan(20); + for (const value of Object.values(REMOTE_CONTEXT)) { + expect(value.startsWith('cockpit-remote-')).toBe(true); + expect(matchers.filter(m => m.matches(value)).map(m => m.when)).toEqual([]); + } + }); + + it('reads the target on every render, so a relabelled workspace stays current', async () => { + let target = TARGET; + const tree = navigateTree(ONE, 'ws:/other|', () => target); + const first = find(await tree.getChildren(), 'ws:/other|builder-group:main'); + expect((first.command as { arguments: unknown[] }).arguments).toEqual([TARGET]); + target = { ...TARGET, name: 'other (2)' }; + const second = find(await tree.getChildren(), 'ws:/other|builder-group:main'); + expect((second.command as { arguments: unknown[] }).arguments).toEqual([target]); + expect(String(second.tooltip)).toContain('In workspace other (2).'); + }); +}); + +describe('ArchitectTreeBuilder: attentionCounts', () => { + it('appends held and queued counts to builder-row descriptions only when on', async () => { + const on = await allRows(actTree(MANY, 'ws:/a|', { attentionCounts: true })); + expect(find(on, 'ws:/a|bugfix-12#0').description).toBe('2 held · 4 queued'); + for (const id of ['ws:/a|spir-10#0', 'ws:/a|air-11#0', 'ws:/a|pir-13#0', 'ws:/a|aspir-14#0']) { + expect(find(on, id).description).toBeUndefined(); + } + const off = await allRows(actTree(MANY, 'ws:/a|')); + expect(find(off, 'ws:/a|bugfix-12#0').description).toBeUndefined(); + + const remote = await allRows(new ArchitectTreeBuilder({ + mode: 'navigate', scope: 'ws:/b|', getData: () => MANY, target: () => TARGET, attentionCounts: true, + })); + expect(find(remote, 'ws:/b|bugfix-12#0').description).toBe('2 held · 4 queued'); + }); + + it('shows one count alone, and follows a new overview', async () => { + let data = overview( + [builder({ id: 'q', spawnedByArchitect: 'main' })], [architect('main')], { queuedFeedback: { q: 1 } }, + ); + const tree = actTree(data, '', { getData: () => data, attentionCounts: true } as Partial); + const row = async () => (await tree.getChildren(find(await tree.getChildren(), 'builder-group:main')))[0]; + expect((await row()).description).toBe('1 queued'); + data = overview( + [builder({ id: 'q', spawnedByArchitect: 'main', heldCount: 3 })], [architect('main')], { heldCount: 3 }, + ); + expect((await row()).description).toBe('3 held'); + }); +}); diff --git a/apps/vscode/src/views/architect-tree.ts b/apps/vscode/src/views/architect-tree.ts new file mode 100644 index 000000000..f5111c4db --- /dev/null +++ b/apps/vscode/src/views/architect-tree.ts @@ -0,0 +1,861 @@ +import * as vscode from 'vscode'; +import { existsSync, readdirSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; +import { UNCATEGORIZED_AREA } from '@cluesmith/codev-sdk/constants'; +import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; +import { builderWithWorktree, type OverviewBuilderWithWorktree } from '../builder-lookup.js'; +import { readBuildersFileViewAsTree } from '../builders-config.js'; +import { BuilderGroupTreeItem, BuilderTreeItem, IdleArchitectsGroupTreeItem } from './builder-tree-item.js'; +import { BuilderFileTreeItem } from './builder-file-tree-item.js'; +import { BuilderFolderTreeItem } from './builder-folder-tree-item.js'; +import { buildFilePathTree, type FilePathNode } from './file-path-tree.js'; +import type { BuilderDiffCache } from './builder-diff-cache.js'; +import { architectGrouping, type BuilderGroup, type BuilderGrouping } from './builder-grouping.js'; +import { + builderRowLabel, + builderRowTooltip, + classifyBuilderRow, + gateIconFor, + rollupGroupState, + BUILDER_STATE_GLYPH, + type BuilderState, +} from './builder-row.js'; +import { OPEN_WORKSPACE_COMMAND, type WorkspaceTarget } from './tower.js'; + +/** + * Builder state → `contextValue` family prefix. Drives menu `when`-clause + * scoping (Approve Gate inline only on `blocked-builder-*`; the rest apply to + * all three families). Keyed by the same `BuilderState` the icon uses so a + * row's menu and glyph never disagree. + */ +const CONTEXT_FAMILY: Record = { + blocked: 'blocked-builder', + 'needs-input': 'awaiting-builder', + idle: 'awaiting-builder', + dead: 'awaiting-builder', + active: 'builder', +}; + +/** + * `contextValue`s of navigate-only rows (another workspace's architects and builders, Spec 1963). + * Deliberately outside every builder/architect menu's `viewItem` pattern, so none of this window's + * row menus can attach to a row that does not belong to this window. + */ +export const REMOTE_CONTEXT = { + architect: 'cockpit-remote-architect', + builder: 'cockpit-remote-builder', + idleArchitects: 'cockpit-remote-idle-architects', +} as const; + +/** + * Order builders for the Builders tree: three buckets, top-down. + * 1. **blocked** (formal gate awaiting approval) — longest-waiting first. + * 2. **waiting** (`classifyBuilderRow`: needs-input, idle or dead, from the + * served agent state or, without one, PTY silence past the threshold). + * 3. **active** — everything else; overview order. + * Blocked rows with no `blockedSince` sort last within the blocked group + * (we don't pretend to know their wait time). Waiting and active + * rows preserve Tower's source order within each bucket. + */ +export function orderForDisplay(builders: OverviewBuilder[], now: number = Date.now()): OverviewBuilder[] { + const ms = (iso: string | null) => iso ? new Date(iso).getTime() : Infinity; + const blocked = builders + .filter(b => b.blocked) + .sort((a, b) => ms(a.blockedSince) - ms(b.blockedSince)); + const rest = builders.filter(b => !b.blocked); + const waiting = rest.filter(b => classifyBuilderRow(b, now) !== 'active'); + const active = rest.filter(b => classifyBuilderRow(b, now) === 'active'); + return [...blocked, ...waiting, ...active]; +} + +/** + * One entry in the agent-terminal cycle (`codev.focusNext/PreviousAgentTerminal`, + * #1563): either an architect (addressed by name) or a builder (addressed by id) — + * the two openable agent kinds the Agents tree renders. Non-agent rows (group + * headers on the stage/area axes, changed-file rows) and non-agent terminals (the + * dev PTY, shells) are never `AgentTarget`s. + */ +export type AgentTarget = + | { kind: 'architect'; name: string } + | { kind: 'builder'; id: string }; + +/** + * Split architect-axis groups into the top-level rows and the idle siblings, in + * render order — the single ordering rule shared by `architectRootRows` (which + * builds tree rows) and `agentCycleOrder` (which builds the cycle roster), so the + * two cannot drift (the shared-function lesson, #818). `groups` arrives from + * `architectGrouping` already `main`-first then alphabetical; `topLevel` keeps that + * order (`main` and every populated sibling), and the idle siblings (zero builders, + * not `main`) are peeled off to be rendered/cycled last. + */ +export function partitionArchitectGroups( + groups: BuilderGroup[], +): { topLevel: BuilderGroup[]; idleSiblings: BuilderGroup[] } { + const topLevel: BuilderGroup[] = []; + const idleSiblings: BuilderGroup[] = []; + for (const g of groups) { + if (g.key !== 'main' && g.items.length === 0) { + idleSiblings.push(g); + } else { + topLevel.push(g); + } + } + return { topLevel, idleSiblings }; +} + +/** What an `ArchitectTreeBuilder` needs whatever its mode. */ +interface ArchitectTreeCommonOptions { + /** The overview the rows are built from (read on every render, never cached across one). */ + getData(): OverviewData | null; + /** + * Prefix for every row id, so two builders over different workspaces never collide. `''` for + * the Agents view, which keeps every id byte-identical to the pre-refactor provider's. + */ + scope: string; + /** + * Append *N held* / *N queued* (from `deriveAttention` over `getData()`) to builder-row + * descriptions. Off for the Agents view, whose builder rows carry no description. + */ + attentionCounts?: boolean; +} + +/** Rows that act in this window: open terminals, expand to changed files, carry the source menus. */ +export interface ArchitectTreeActOptions extends ArchitectTreeCommonOptions { + mode: 'act'; + /** The grouping axis. The Agents view passes its active axis; the Cockpit, the architect axis. */ + grouping(): BuilderGrouping; + diffCache: BuilderDiffCache; +} + +/** + * Rows of a workspace this window does not own: they show state and navigate to that workspace's + * window. Always on the architect axis. + */ +export interface ArchitectTreeNavigateOptions extends ArchitectTreeCommonOptions { + mode: 'navigate'; + /** The workspace a click opens (read per render, so a relabelled workspace stays current). */ + target(): WorkspaceTarget; +} + +export type ArchitectTreeOptions = ArchitectTreeActOptions | ArchitectTreeNavigateOptions; + +/** + * Builds the Agents tree's rows — architect / stage / area group headers, builder rows, the + * *Idle Architects* roll-up and changed-file children — for one workspace (Spec 1963). + * + * The Agents view holds one (scope `''`, mode `act`). The Cockpit holds one per active workspace, + * scoped by workspace so ids never collide: this window's workspace acts, every other workspace + * navigates. Per-view state — accordion row-id versioning and the builder → group parent map — + * lives here, so each view (and each workspace inside the Cockpit) owns its own. + * + * Every row carries `scope`, so a caller holding several builders can route `getChildren` / + * `getParent` and command handlers to the builder that made the row. + */ +export class ArchitectTreeBuilder { + // Populated each time `rootRows()` returns groups; consulted by `getParent` + // so the accordion's `reveal(builderItem)` can walk the parent chain in + // grouping mode. Empty in the single-`Uncategorized` flatten case (area + // mode only — builders are root again), so `getParent` returns `undefined` + // and the accordion works unchanged on that branch. + private readonly groupParentByBuilderId = new Map(); + // Accordion row-id versioning (#913) — see AccordionRowIds. + private readonly rowIds: AccordionRowIds; + // The architect axis, for navigate mode (which has no `grouping` option). + private readonly architectAxis = architectGrouping(); + // `attentionCounts`: per-builder counts, derived once per overview object. + private attention: { data: OverviewData; counts: Map } | null = null; + + constructor(private readonly options: ArchitectTreeOptions) { + this.rowIds = new AccordionRowIds(options.scope); + } + + get scope(): string { + return this.options.scope; + } + + get mode(): ArchitectTreeOptions['mode'] { + return this.options.mode; + } + + /** + * Accordion (#913): hold `item` open at its exact id and re-version every + * other builder row to a fresh, never-seen id, which VSCode renders with the + * default `Collapsed` state. Group headers carry no version suffix, so the + * accordion can't touch them. The caller fires its view's change event. + */ + keepOnlyOpen(item: BuilderTreeItem): void { + this.rowIds.keepOnly(item.builderId, item.id); + } + + private grouping(): BuilderGrouping { + if (this.options.mode === 'act') { return this.options.grouping(); } + return this.architectAxis; + } + + /** The active axis's groups over `data`, in display order. */ + private groupsOf(data: OverviewData, now: number): BuilderGroup[] { + // The registered-architect roster (live sessions, main-first) — sourced from + // the overview the builder already reads, no second fetch. Only the + // architect axis consumes it, to emit a header for every architect including + // childless ones (Issue 1174); the other axes ignore the arg. Guard `??` for + // a pre-roster overview payload so `.map` never throws. + const roster = (data.architects ?? []).map(a => a.name); + return this.grouping().group(orderForDisplay(data.builders, now), roster); + } + + /** + * The children of `element`, or the root rows when it is `undefined`. `element` must be a row + * this builder made (same `scope`). + */ + async getChildren(element?: vscode.TreeItem): Promise { + // Second level: a builder's changed files. VSCode only calls this for + // an *expanded* builder, so collapsed builders cost no git. Navigate-mode + // builder rows are leaves. + if (element instanceof BuilderTreeItem) { + if (this.options.mode !== 'act') { return []; } + return this.fileChildren(element.builderId); + } + // Folder rows (tree-mode only) expand to their child folders/files. + if (element instanceof BuilderFolderTreeItem) { + return element.node.children!.map(child => + materialiseNode(element.builderId, element.worktreePath, element.baseRef, child, this.scope), + ); + } + // File rows are leaves. + if (element instanceof BuilderFileTreeItem) { + return []; + } + // The Idle Architects container (architect axis, Issue 1182) expands to the + // individual idle-sibling architect rows. + if (element instanceof IdleArchitectsGroupTreeItem) { + return this.idleArchitectRows(Date.now()); + } + // Group rows expand to their builders. + if (element instanceof BuilderGroupTreeItem) { + return this.rowsForGroup(element.groupName); + } + return this.rootRows(); + } + + // The accordion's `reveal(builderItem)` and the active-file sync's + // `reveal(fileItem)` (#1066) both need the parent chain. + // - Builder rows return their cached group (or undefined in the + // single-Uncategorized flatten case — VSCode treats them as roots). + // - File / folder rows reconstruct their chain: file → folder(s) (tree + // mode) → builder → group. Async because tree-mode reconstruction reads + // the (cached) diff to rebuild the folder hierarchy; VSCode's `getParent` + // accepts a Thenable. + // - Group rows themselves are roots, except an idle sibling folded into the + // Idle Architects container. + // A root answer (`undefined`) is root *within this builder*: a host that nests + // the builder's rows under its own nodes bridges from there. + getParent(element: vscode.TreeItem): vscode.ProviderResult { + if (element instanceof BuilderTreeItem) { + return this.groupParentByBuilderId.get(element.builderId); + } + if (element instanceof BuilderFileTreeItem || element instanceof BuilderFolderTreeItem) { + return this.parentForFileNode(element); + } + if (element instanceof BuilderGroupTreeItem) { + // An idle-sibling architect header is rendered INSIDE the collapsed "Idle + // Architects" container (#1182), not at root, so return that container as its + // parent — otherwise `reveal` treats the header as a root, never expands the + // container, and can't select the row (#1563). Top-level headers (main, + // populated siblings, a lone idle sibling) have no parent. + return this.idleArchitectsContainerParent(element.groupName); + } + // Other group rows (the container itself, etc.) are roots. + return undefined; + } + + /** + * The "Idle Architects" container that renders `architectName` as a child, or + * `undefined` when the architect is not a folded idle sibling (wrong axis, fewer + * than two idle siblings so it renders top-level, or a populated / `main` + * architect). The returned container carries the stable `idle-architects-group` + * id, so `reveal` matches the rendered container and expands it (#1563). + */ + private idleArchitectsContainerParent(architectName: string): IdleArchitectsGroupTreeItem | undefined { + const data = this.options.getData(); + if (!data) { return undefined; } + if (this.grouping().id !== 'architect') { return undefined; } + const { idleSiblings } = partitionArchitectGroups(this.groupsOf(data, Date.now())); + // Fewer than two idle siblings → the lone one renders as its own top-level row. + if (idleSiblings.length < 2) { return undefined; } + if (!idleSiblings.some(g => g.key === architectName)) { return undefined; } + return this.makeIdleContainer(idleSiblings.length); + } + + /** + * The builder with this id, but only if it has a worktree on record — the + * shared precondition for the changed-file methods (`fileChildren`, + * `parentForFileNode`, `findFileItem`). The return type narrows + * `worktreePath` to a non-null `string`, so callers can pass it to + * `diffCache.getDiff` without re-guarding. + */ + private builderWithWorktree(builderId: string): OverviewBuilderWithWorktree | undefined { + return builderWithWorktree(this.options.getData(), builderId); + } + + /** + * Reconstruct the parent of a file or folder row so `reveal` can build the + * chain up to the root (#1066). Reconstruction (not a getChildren-populated + * map) is required because `reveal` walks parents while the subtree is still + * collapsed — `getChildren` for a file only runs once its builder is expanded. + * + * - **Flat-list mode**: a file's parent is the builder row directly. + * - **Tree mode**: rebuild the compacted folder tree (same `buildFilePathTree` + * the rows were rendered from, off the 15s-TTL diff cache) and return the + * enclosing folder row, or the builder row when the node sits at top level. + * + * The reconstructed builder row carries the current accordion-versioned id + * (`makeBuilderRow` → `rowIds.idFor`), and folder rows carry the same + * `::folder::` id `materialiseNode` produces, so the + * chain matches what `getChildren` renders. + */ + private async parentForFileNode( + element: BuilderFileTreeItem | BuilderFolderTreeItem, + ): Promise { + if (this.options.mode !== 'act') { return undefined; } + const builderId = element.builderId; + const builder = this.builderWithWorktree(builderId); + if (!builder) { return undefined; } + const builderRow = this.makeBuilderRow(builder, Date.now()); + + if (!readBuildersFileViewAsTree()) { + // Flat list: folders don't exist here, so any file's parent is the builder. + return builderRow; + } + + const result = await this.options.diffCache.getDiff(builderId, builder.worktreePath); + if (result.error) { return builderRow; } + const targetPath = element instanceof BuilderFolderTreeItem + ? element.node.fullPath + : element.plan.resourcePath; + const parentNode = findParentNode(buildFilePathTree(result.files), targetPath); + if (!parentNode) { + // Top-level node: parent is the builder row. + return builderRow; + } + return new BuilderFolderTreeItem(builderId, builder.worktreePath, result.baseRef, parentNode, this.scope); + } + + /** + * Build the `BuilderFileTreeItem` matching `(builderId, relPath)` so the + * active-file sync can hand it to the view's `reveal` (#1066). Returns + * `undefined` if the builder or file is no longer present, or in navigate + * mode (no changed-file rows). The constructed item's id matches the rendered + * row, so `reveal` + `getParent` locate and highlight the correct row (incl. + * the right builder when two builders share a relative path). + */ + async findFileItem(builderId: string, relPath: string): Promise { + if (this.options.mode !== 'act') { return undefined; } + const builder = this.builderWithWorktree(builderId); + if (!builder) { return undefined; } + const result = await this.options.diffCache.getDiff(builderId, builder.worktreePath); + if (result.error) { return undefined; } + const file = result.files.find(f => f.plan.resourcePath === relPath); + if (!file) { return undefined; } + return new BuilderFileTreeItem(builderId, builder.worktreePath, result.baseRef, file.change, file.plan, this.scope); + } + + /** Root rows for the active axis. Resets the builder → group parent map. */ + rootRows(): vscode.TreeItem[] { + this.groupParentByBuilderId.clear(); + + const data = this.options.getData(); + if (!data) { + return []; + } + + const now = Date.now(); + const grouping = this.grouping(); + const groups = this.groupsOf(data, now); + + // A repo that doesn't use `area/*` labels yields a single `Uncategorized` + // group; in area mode its header adds no information, so flatten to root rows + // — zero visual regression for unlabeled repos. Stage and architect modes + // opt out of this (their lone group always carries information). + if (grouping.flattenLoneUncategorized && groups.length === 1 && groups[0].key === UNCATEGORIZED_AREA) { + return groups[0].items.map(b => this.makeBuilderRow(b, now)); + } + + // The architect axis rolls idle siblings into an "Idle Architects" container + // (Issue 1182), so it renders through its own method. Stage/area render every + // group as its own header. + if (grouping.id === 'architect') { + return this.architectRootRows(groups, now); + } + // Populated groups render Expanded (#913) — no persisted state. VSCode's + // native per-id memory keeps a user-collapsed group collapsed for the + // rest of the session; on a fresh session this default applies again. + // Stage/area groups always hold ≥1 builder (no empty groups on these axes), + // so they never carry a command — they name no launchable entity. + return groups.map(g => this.makeGroupRow(g, now, false)); + } + + /** + * Root rows for the architect axis (Issue 1182). `main` and every populated + * sibling render as their own top-level group (unchanged from #1174); idle + * siblings (zero builders, not `main`) roll up under a single collapsed + * "Idle Architects" container — but only when ≥ 2 are idle. A lone idle + * sibling keeps its own row (the group would save no space for one row and + * only adds a click). Ordering: `main` first, then populated siblings, then + * the idle container / lone idle sibling at the bottom — "primary work first, + * roster second." + * + * `groups` arrives from `architectGrouping` already ordered `main`-first then + * the rest alphabetically. Iterating it preserves that order for the rows that + * stay top-level; the idle siblings are peeled off and re-emitted last. + * + * `main` is always its own row regardless of builder count: it is the + * always-present workspace home base (created by `launchInstance` on any + * workspace; every sibling is opt-in via `add-architect`), so burying it + * behind a chevron is a bad trade for one row of vertical space. + */ + private architectRootRows(groups: BuilderGroup[], now: number): vscode.TreeItem[] { + const { topLevel, idleSiblings } = partitionArchitectGroups(groups); + const rows: vscode.TreeItem[] = topLevel.map(g => this.makeGroupRow(g, now, true)); + if (idleSiblings.length >= 2) { + rows.push(this.makeIdleContainer(idleSiblings.length)); + } else { + // 0 → nothing; 1 → the lone idle sibling renders as its own top-level row. + for (const g of idleSiblings) { + rows.push(this.makeGroupRow(g, now, true)); + } + } + return rows; + } + + /** + * The agent-terminal cycle roster (#1563), flattened top-to-bottom in the SAME + * order the tree renders, so `codev.focusNext/PreviousAgentTerminal` mirror + * the sidebar exactly and stay grouping-aware. Built from the same primitives the + * renderer uses — `orderForDisplay` + the active grouping strategy — so there is no + * parallel ordering to drift (#818). + * + * The roster is axis-dependent, matching what each axis actually renders: + * - **stage / area** (incl. the lone-`Uncategorized` flatten): only builder rows + * are agents; architects render no rows on these axes, so they are not cycled. + * - **architect**: architect headers are first-class agents (their rows carry the + * open-terminal command), interleaved with their builders in top-level order via + * the shared `partitionArchitectGroups`; idle siblings (zero builders) render — + * and so cycle — last. + * + * Non-agent terminals (the dev PTY, shells) are never in the roster because only + * architects and builders appear here. + */ + agentCycleOrder(): AgentTarget[] { + const data = this.options.getData(); + if (!data) { return []; } + const groups = this.groupsOf(data, Date.now()); + + if (this.grouping().id !== 'architect') { + return groups.flatMap(g => g.items.map((b): AgentTarget => ({ kind: 'builder', id: b.id }))); + } + + // Emit each architect header followed by its builders, in render order: + // top-level groups first, then the idle siblings last (the "Idle Architects" + // container at the bottom). Idle siblings carry zero builders by construction, so + // the inner loop is simply empty for them — no separate pass needed. + const { topLevel, idleSiblings } = partitionArchitectGroups(groups); + const architectOrder = [...topLevel, ...idleSiblings]; + const targets: AgentTarget[] = []; + for (const g of architectOrder) { + targets.push({ kind: 'architect', name: g.key }); + for (const b of g.items) { targets.push({ kind: 'builder', id: b.id }); } + } + return targets; + } + + /** + * The tree item to `reveal({ select: true })` so the sidebar selection follows the + * agent-cycle commands (#1563) the same way a row click highlights the clicked row. + * Returns `undefined` when the agent is no longer in the overview, and always in + * navigate mode: the cycle walks this window's agents, which navigate rows are not. + * + * - **builder**: the same versioned row `makeBuilderRow` renders, so `reveal` matches + * it by id and expands its group ancestor to bring it into view. + * - **architect**: a header carrying the stable `builder-group:` id, which + * matches the rendered architect header. For an idle-sibling architect folded into + * the "Idle Architects" container, `getParent` returns that container (via + * `idleArchitectsContainerParent`), so `reveal` expands the container and selects + * the row rather than leaving it hidden. + */ + revealTargetForAgent(target: AgentTarget): vscode.TreeItem | undefined { + if (this.options.mode !== 'act') { return undefined; } + const data = this.options.getData(); + if (!data) { return undefined; } + if (target.kind === 'builder') { + const builder = data.builders.find(b => b.id === target.id); + if (!builder) { return undefined; } + return this.makeBuilderRow(builder, Date.now()); + } + // Architect header: only the id is consulted by `reveal`, so the count / state + // passed here are placeholders — they never render. + return new BuilderGroupTreeItem( + target.name, 0, vscode.TreeItemCollapsibleState.None, { blocked: 0, idle: 0, active: 0 }, this.scope); + } + + /** + * The individual idle-sibling architect rows shown when the "Idle Architects" + * container is expanded (Issue 1182). Each is a childless + * `BuilderGroupTreeItem` — the same leaf-like `(0)` row #1174 renders at top + * level — carrying its own click command, so clicking a name inside the group + * opens that architect's terminal (or, navigating, its workspace). Recomputed + * from the overview (not cached from `rootRows`) so it stays correct across + * overview ticks; harmlessly returns `[]` if the axis is no longer `architect`. + */ + private idleArchitectRows(now: number): vscode.TreeItem[] { + const data = this.options.getData(); + if (!data) { return []; } + if (this.grouping().id !== 'architect') { return []; } + return this.groupsOf(data, now) + .filter(g => g.key !== 'main' && g.items.length === 0) + .map(g => this.makeGroupRow(g, now, true)); + } + + /** The "Idle Architects (N)" container (Issue 1182). */ + private makeIdleContainer(count: number): IdleArchitectsGroupTreeItem { + const container = new IdleArchitectsGroupTreeItem(count, this.scope); + if (this.options.mode === 'navigate') { + container.contextValue = REMOTE_CONTEXT.idleArchitects; + } + return container; + } + + /** + * Build one group header row. `isArchitectAxis` headers get a + * click-to-open-terminal `command` (#1108): the architect is first-class in + * this mode, so its header matches the builder-row affordance (row click opens + * the terminal; the chevron still toggles expand/collapse — VSCode routes the + * two gestures independently). A childless architect group (Issue 1174) has no + * builders to expand into, so it renders as a leaf-like row (`None`) rather + * than an empty accordion; the command still fires on the row body. Populated + * groups render Expanded (#913). Stage/area headers stay command-less + * containers. Registers each builder's parent group for `getParent`. + * + * A scoped (Cockpit) architect row names `main` vs a sibling in its + * `contextValue`, so a menu entry can tell them apart. A navigate-mode + * architect row opens its workspace's window instead of a terminal. + */ + private makeGroupRow(g: BuilderGroup, now: number, isArchitectAxis: boolean): BuilderGroupTreeItem { + let collapsibleState: vscode.TreeItemCollapsibleState; + if (g.items.length === 0) { + collapsibleState = vscode.TreeItemCollapsibleState.None; + } else { + collapsibleState = vscode.TreeItemCollapsibleState.Expanded; + } + const groupItem = new BuilderGroupTreeItem( + g.key, + g.items.length, + collapsibleState, + rollupGroupState(g.items, now), + this.scope, + ); + if (this.options.mode === 'navigate') { + const target = this.options.target(); + groupItem.contextValue = REMOTE_CONTEXT.architect; + groupItem.tooltip = navigateTooltip(String(groupItem.tooltip ?? ''), target); + groupItem.command = openWorkspaceCommand(target); + } else if (isArchitectAxis) { + // The `g.key` (architect name; null owners folded into `main` by + // architectGrouping) is the optional name arg `codev.openArchitectTerminal` + // already accepts; it warns gracefully on a stale owner not in the roster. + groupItem.command = { + command: 'codev.openArchitectTerminal', + title: 'Open Architect Terminal', + arguments: [g.key], + }; + if (this.scope !== '') { + groupItem.contextValue = g.key === 'main' ? 'cockpit-architect-main' : 'cockpit-architect-sibling'; + } + } + for (const b of g.items) { + this.groupParentByBuilderId.set(b.id, groupItem); + } + return groupItem; + } + + private rowsForGroup(key: string): vscode.TreeItem[] { + const data = this.options.getData(); + if (!data) { return []; } + + const now = Date.now(); + const group = this.groupsOf(data, now).find(g => g.key === key); + if (!group) { return []; } + + return group.items.map(b => this.makeBuilderRow(b, now)); + } + + private makeBuilderRow(b: OverviewBuilder, now: number): BuilderTreeItem { + // Classify once; the state drives the label, the tooltip, the contextValue + // family (menu scoping) and the icon. + const state = classifyBuilderRow(b, now); + const item = new BuilderTreeItem(b.id, builderRowLabel(b, state, now, this.grouping().rowPrefix(b)), this.scope); + // Versioned id (#913). The base `b.id` is stable (not the churning label) so + // VSCode preserves a row's expansion across the frequent overview-poll + // refreshes; the `#` suffix is the accordion lever (see + // AccordionRowIds). Group ids carry no suffix, so the accordion can't touch + // them. + item.id = this.rowIds.idFor(b.id); + // Icon: the shared per-state glyph (single source of truth in + // builder-row.ts). A blocked row overrides the shape with the gate-specific + // `gateIconFor` codicon while keeping the shared warning color. + const { icon, color } = BUILDER_STATE_GLYPH[state]; + let iconName = icon; + if (state === 'blocked') { iconName = gateIconFor(b.blockedGate); } + item.iconPath = new vscode.ThemeIcon(iconName, new vscode.ThemeColor(color)); + const counts = this.attentionCountsText(b.id); + if (counts) { item.description = counts; } + + if (this.options.mode === 'navigate') { + // Another workspace's builder: a leaf (no changed files) whose click opens + // that workspace's window, where the row is fully actionable. + const target = this.options.target(); + item.collapsibleState = vscode.TreeItemCollapsibleState.None; + item.tooltip = navigateTooltip(builderRowTooltip(b, state), target); + item.contextValue = REMOTE_CONTEXT.builder; + item.command = openWorkspaceCommand(target); + return item; + } + + // Expandable so the second-level changed-files list can hang off it. + // The row keeps its open-terminal command (single click); the chevron + // toggles the file list. + item.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed; + // A plain string, never a MarkdownString: the needs-input summary renders literally (SC19). + item.tooltip = builderRowTooltip(b, state); + // contextValue encodes the row's state-family + protocol so menus + // can scope by either (Approve Gate inline only on + // blocked-builder-*; everything else applies to all three + // families). The optional `-review` suffix signals that the + // builder has committed a review file on disk — the + // `codev.viewReviewFile` menu entry's `when` clause keys off it so + // PIR rows hide the entry until the review phase produces the file. + const protocol = b.protocol || 'unknown'; + const reviewSuffix = builderHasReviewFile(b) ? '-review' : ''; + item.contextValue = `${CONTEXT_FAMILY[state]}-${protocol}${reviewSuffix}`; + // The row click runs `codev.openBuilderRow` — a wrapper that opens the + // builder terminal and, when `codev.buildersClickExpands` is on (the + // default), also expands the row (the file list). Pass the item itself so + // the handler can call the view's `reveal(...)` against this row. Other + // callers (terminal-link clicks, etc.) still use `codev.openBuilderById` + // directly with just the id and don't trigger expansion. + item.command = { + command: 'codev.openBuilderRow', + title: 'Open Builder Terminal', + arguments: [item], + }; + return item; + } + + /** + * `N held · N queued` for a builder row when `attentionCounts` is on, or + * `undefined` when it is off or the builder has neither. The counts are the + * Tower view's own (`deriveAttention`), derived once per overview object. + */ + private attentionCountsText(builderId: string): string | undefined { + if (!this.options.attentionCounts) { return undefined; } + const data = this.options.getData(); + if (!data) { return undefined; } + if (this.attention?.data !== data) { + const summary = deriveAttention(data); + const counts = new Map(); + const entry = (id: string) => { + let found = counts.get(id); + if (!found) { + found = { held: 0, queued: 0 }; + counts.set(id, found); + } + return found; + }; + for (const item of summary.heldMail) { entry(item.builderId).held = item.count; } + for (const item of summary.queuedFeedback) { entry(item.builderId).queued = item.count; } + this.attention = { data, counts }; + } + const found = this.attention.counts.get(builderId); + if (!found) { return undefined; } + const parts: string[] = []; + if (found.held > 0) { parts.push(`${found.held} held`); } + if (found.queued > 0) { parts.push(`${found.queued} queued`); } + return parts.join(' · '); + } + + /** + * Changed-file rows for one builder, rendered as a flat list or a + * folder tree depending on the `codev.buildersFileViewAsTree` setting. + * The diff data and the leaf shape (BuilderFileTreeItem) are identical + * in both modes — only the grouping around the leaves differs. + */ + private async fileChildren(builderId: string): Promise { + if (this.options.mode !== 'act') { return []; } + const builder = this.builderWithWorktree(builderId); + if (!builder) { + return [placeholder('No worktree on record')]; + } + + const result = await this.options.diffCache.getDiff(builderId, builder.worktreePath); + if (result.error) { + const row = placeholder('Diff unavailable'); + row.tooltip = result.error; + return [row]; + } + if (result.files.length === 0) { + return [placeholder('No changes yet')]; + } + + if (readBuildersFileViewAsTree()) { + // Tree mode: group by folder, compact single-child folder chains. + // Top-level nodes may be folders or root-level files (e.g. README). + return buildFilePathTree(result.files).map(node => + materialiseNode(builderId, builder.worktreePath, result.baseRef, node, this.scope), + ); + } + // List mode (today's behaviour): flat, one row per changed file. + return result.files.map( + f => new BuilderFileTreeItem(builderId, builder.worktreePath, result.baseRef, f.change, f.plan, this.scope), + ); + } +} + +/** The click command of a navigate-only row: open its workspace (the Tower view's action). */ +function openWorkspaceCommand(target: WorkspaceTarget): vscode.Command { + return { command: OPEN_WORKSPACE_COMMAND, title: 'Open Workspace', arguments: [target] }; +} + +/** A navigate-only row's tooltip: what the row shows, then which workspace a click opens. */ +function navigateTooltip(base: string, target: WorkspaceTarget): string { + const where = `In workspace ${target.name}. Click to open its window, where this row can act.`; + if (base === '') { return where; } + return `${base}\n${where}`; +} + +/** + * Render one tree-mode node as either a folder row (if it has children) + * or a file row (if it carries a leaf). Folders carry the worktreePath + * + baseRef forward so the renderer can construct file children on + * subsequent expansion without re-fetching from the diff cache. + */ +function materialiseNode( + builderId: string, + worktreePath: string, + baseRef: string, + node: FilePathNode, + scope: string, +): vscode.TreeItem { + if (node.children) { + return new BuilderFolderTreeItem(builderId, worktreePath, baseRef, node, scope); + } + // Leaf: must have a file (folder-without-children shouldn't be reachable + // from buildFilePathTree, but the type allows it — guard defensively). + if (!node.file) { + return placeholder(node.name); + } + return new BuilderFileTreeItem(builderId, worktreePath, baseRef, node.file.change, node.file.plan, scope); +} + +/** + * Walk a (compacted) file-path tree and return the parent node of the node + * whose `fullPath` matches `targetPath`, or `undefined` when the target sits at + * top level (no parent folder) or isn't found. Used by `getParent` to + * reconstruct a file/folder row's enclosing folder for `reveal` (#1066). + * + * Folder fullPaths are compacted (`packages/codev/src`), and a file leaf's + * `fullPath` equals its `plan.resourcePath` (leaves aren't compacted), so a + * direct `fullPath` match resolves both row kinds. + * + * Returns `undefined` for both "top-level node (no parent folder)" and "not + * found"; the caller treats both as "parent is the builder row". Recursive + * calls always pass a defined `parent`, so a node found below the top level + * never resolves to `undefined`. + */ +export function findParentNode( + nodes: FilePathNode[], + targetPath: string, + parent?: FilePathNode, +): FilePathNode | undefined { + for (const node of nodes) { + if (node.fullPath === targetPath) { return parent; } + if (node.children) { + const found = findParentNode(node.children, targetPath, node); + if (found !== undefined) { return found; } + } + } + return undefined; +} + +/** + * Sync-check whether a builder has committed a review file on disk. + * + * Mirrors the prefix filter in `commands/view-artifact.ts`: a file + * counts if it lives in `/codev/reviews/`, ends in `.md`, and + * either starts with `-` or is exactly `.md`. Used by the + * builder-row builder to suffix `contextValue` with `-review` so + * PIR rows can hide `codev.viewReviewFile` until the review phase emits + * the file (non-PIR protocols always show the entry — they fall back to + * the missing-file toast in `view-artifact.ts`). + * + * One `readdirSync` per builder per render — the reviews dir is small, + * local, and only inspected when overview data changes. Cheaper than + * the diff-cache work the row triggers on expansion. + */ +function builderHasReviewFile(b: OverviewBuilder): boolean { + if (!b.worktreePath) { return false; } + const dir = resolve(b.worktreePath, 'codev/reviews'); + if (!existsSync(dir)) { return false; } + const prefix = `${b.id}-`; + try { + return readdirSync(dir).some( + f => f.endsWith('.md') && (f.startsWith(prefix) || f === `${b.id}.md`), + ); + } catch { + return false; + } +} + +/** + * Builder-row id versioning for the accordion (#913). VSCode has no "collapse + * this row" API and replays its remembered expand-state for any id it has seen, + * so the only way to force a row collapsed is to render it under a never-seen + * id. Every row id is `#`; bumping the version + * (`keepOnly`) hands every row a fresh — hence collapsed — id, except the one + * being held open, which keeps the exact id it was clicked at so VSCode keeps it + * expanded. + * + * The open row's id is stored verbatim (not reconstructed from a number), so a + * render that lands between a bump and the next click can't leave the open row + * pointing at a stale version. `prefix` is the builder's scope (`''` for the + * Agents view, so its ids are unchanged). + */ +export class AccordionRowIds { + private version = 0; + private openBuilderId: string | undefined; + private openRowId: string | undefined; + + constructor(private readonly prefix: string = '') {} + + /** The id to render for `builderId` this pass. */ + idFor(builderId: string): string { + if (builderId === this.openBuilderId && this.openRowId) { + return this.openRowId; + } + return `${this.prefix}${builderId}#${this.version}`; + } + + /** Hold `builderId` open at its current `rowId`; re-version everyone else. */ + keepOnly(builderId: string, rowId: string | undefined): void { + this.openBuilderId = builderId; + this.openRowId = rowId; + this.version += 1; + } +} + +/** Non-clickable informational leaf (no worktree / no changes / error). */ +function placeholder(label: string): vscode.TreeItem { + const item = new vscode.TreeItem(label); + item.contextValue = 'builder-file-none'; + item.iconPath = new vscode.ThemeIcon('circle-slash', new vscode.ThemeColor('disabledForeground')); + return item; +} diff --git a/apps/vscode/src/views/builder-file-tree-item.ts b/apps/vscode/src/views/builder-file-tree-item.ts index 57408d328..cd1a782db 100644 --- a/apps/vscode/src/views/builder-file-tree-item.ts +++ b/apps/vscode/src/views/builder-file-tree-item.ts @@ -14,7 +14,7 @@ import type { ChangeEntry, ChangeStatus, ResourcePlan } from '../commands/view-d * file-type icon show, and `BuilderFileDecorationProvider` adds the * SCM-style colored status-letter badge, mirroring VSCode's Git decorator. * - * Used by views/builders.ts. + * Used by views/architect-tree.ts. */ /** @@ -82,6 +82,8 @@ export class BuilderFileTreeItem extends vscode.TreeItem { public readonly baseRef: string, public readonly change: ChangeEntry, public readonly plan: ResourcePlan, + /** The tree builder that made the row (see `BuilderTreeItem.scope`); prefixes the id. */ + public readonly scope: string = '', ) { const rel = plan.resourcePath; super(path.basename(rel)); @@ -92,8 +94,9 @@ export class BuilderFileTreeItem extends vscode.TreeItem { // prefix keeps two builders that changed the same relative path distinct // (same reason `resourceUri` carries the worktree path, above). Distinct // from folder ids (`::folder::<...>`) and builder-row ids - // (`#`). - this.id = `${builderId}::${rel}`; + // (`#`). The scope prefix (empty in the Agents view) + // keeps the same builder's row distinct across workspaces in the Cockpit. + this.id = `${scope}${builderId}::${rel}`; const dir = path.dirname(rel); const dirLabel = dir === '.' ? '' : dir; diff --git a/apps/vscode/src/views/builder-folder-tree-item.ts b/apps/vscode/src/views/builder-folder-tree-item.ts index 3a5c270f1..ff3dbce42 100644 --- a/apps/vscode/src/views/builder-folder-tree-item.ts +++ b/apps/vscode/src/views/builder-folder-tree-item.ts @@ -10,7 +10,8 @@ import type { FilePathNode } from './file-path-tree.js'; * Expanded by default — mirrors VSCode SCM, where the file-tree opens * out under each repository. A stable `id` (`::folder::`) * lets VSCode persist user expand/collapse across the overview-poll - * refreshes; without it the tree would reset on every tick. + * refreshes; without it the tree would reset on every tick. `scope` (the tree + * builder that made the row, `''` in the Agents view) prefixes that id. */ export class BuilderFolderTreeItem extends vscode.TreeItem { constructor( @@ -18,9 +19,10 @@ export class BuilderFolderTreeItem extends vscode.TreeItem { public readonly worktreePath: string, public readonly baseRef: string, public readonly node: FilePathNode, + public readonly scope: string = '', ) { super(node.name, vscode.TreeItemCollapsibleState.Expanded); - this.id = `${builderId}::folder::${node.fullPath}`; + this.id = `${scope}${builderId}::folder::${node.fullPath}`; this.iconPath = vscode.ThemeIcon.Folder; this.contextValue = 'builder-file-folder'; // No `command` — folder rows have no click action. diff --git a/apps/vscode/src/views/builder-tree-item.ts b/apps/vscode/src/views/builder-tree-item.ts index 0808b8c50..b26ebb241 100644 --- a/apps/vscode/src/views/builder-tree-item.ts +++ b/apps/vscode/src/views/builder-tree-item.ts @@ -13,12 +13,18 @@ import { BUILDER_STATE_GLYPH, worstBuilderState, type GroupRollup } from './buil * builder rows with this class and the command handlers narrow via * `instanceof BuilderTreeItem` to read `.builderId` safely. * - * Used by views/builders.ts. + * `scope` names the tree builder that made the row (`ArchitectTreeBuilder`): + * `''` for the Agents view, a workspace-qualified prefix in the Cockpit. The + * builder prefixes the row's id with it, and handlers read it to tell which + * view and workspace a row belongs to. + * + * Used by views/architect-tree.ts. */ export class BuilderTreeItem extends vscode.TreeItem { constructor( public readonly builderId: string, label: string, + public readonly scope: string = '', ) { super(label); } @@ -43,6 +49,9 @@ export class BuilderTreeItem extends vscode.TreeItem { * hold builders at different gates — the yellow color is the group-level "needs * attention" signal. The triple is spelled out in the tooltip. Set here in the * subclass, not the shared base, because the Backlog view rolls up differently. + * + * `scope` prefixes the id (`builder-group:`), so two workspaces' + * `main` headers never collide; `''` keeps the Agents view's ids unchanged. */ export class BuilderGroupTreeItem extends AreaGroupTreeItem { constructor( @@ -50,8 +59,10 @@ export class BuilderGroupTreeItem extends AreaGroupTreeItem { count: number, collapsibleState: vscode.TreeItemCollapsibleState, rollup: GroupRollup, + public readonly scope: string = '', ) { super(groupName, 'builder', count, collapsibleState); + this.id = `${scope}${this.id}`; // An empty rollup means a childless group — only the architect axis produces // one (a registered architect with no builders, Issue 1174). Short-circuit // the worst-of tri-state, which would read all-zero as green `active`, and @@ -85,12 +96,12 @@ export class BuilderGroupTreeItem extends AreaGroupTreeItem { * expansion off the stable `id`, so a user who expands it stays expanded until * they collapse. The rollup glyph is the same neutral idle glyph a childless * architect carries — idle architects have no builders, so there is no - * attention state to roll up. + * attention state to roll up. `scope` prefixes the id, as on the other rows. */ export class IdleArchitectsGroupTreeItem extends vscode.TreeItem { - constructor(count: number) { + constructor(count: number, public readonly scope: string = '') { super(`Idle Architects (${count})`, vscode.TreeItemCollapsibleState.Collapsed); - this.id = 'idle-architects-group'; + this.id = `${scope}idle-architects-group`; this.contextValue = 'group-idle-architects'; this.iconPath = new vscode.ThemeIcon('circle-outline', new vscode.ThemeColor('disabledForeground')); this.tooltip = `${count} idle architects · no builders attached`; diff --git a/apps/vscode/src/views/builders.ts b/apps/vscode/src/views/builders.ts index 91bb59233..7a5b32604 100644 --- a/apps/vscode/src/views/builders.ts +++ b/apps/vscode/src/views/builders.ts @@ -1,80 +1,27 @@ import * as vscode from 'vscode'; -import { existsSync, readdirSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { OverviewBuilder } from '@cluesmith/codev-types'; import { resolveAgentName } from '@cluesmith/codev-sdk/agent-names'; -import { UNCATEGORIZED_AREA } from '@cluesmith/codev-sdk/constants'; import type { OverviewCache } from './overview-data.js'; -import { builderWithWorktree, type OverviewBuilderWithWorktree } from '../builder-lookup.js'; -import { readBuildersFileViewAsTree } from '../builders-config.js'; -import { BuilderGroupTreeItem, BuilderTreeItem, IdleArchitectsGroupTreeItem } from './builder-tree-item.js'; -import { BuilderFileTreeItem } from './builder-file-tree-item.js'; -import { BuilderFolderTreeItem } from './builder-folder-tree-item.js'; -import { buildFilePathTree, type FilePathNode } from './file-path-tree.js'; +import type { BuilderTreeItem } from './builder-tree-item.js'; +import type { BuilderFileTreeItem } from './builder-file-tree-item.js'; import type { BuilderDiffCache } from './builder-diff-cache.js'; import { - type BuilderGroup, type BuilderGrouping, type BuildersGroupBy, stageGrouping, areaGrouping, architectGrouping, } from './builder-grouping.js'; -import { - builderRowLabel, - builderRowTooltip, - classifyBuilderRow, - gateIconFor, - rollupGroupState, - BUILDER_STATE_GLYPH, - type BuilderState, -} from './builder-row.js'; - -/** - * Builder state → `contextValue` family prefix. Drives menu `when`-clause - * scoping (Approve Gate inline only on `blocked-builder-*`; the rest apply to - * all three families). Keyed by the same `BuilderState` the icon uses so a - * row's menu and glyph never disagree. - */ -const CONTEXT_FAMILY: Record = { - blocked: 'blocked-builder', - 'needs-input': 'awaiting-builder', - idle: 'awaiting-builder', - dead: 'awaiting-builder', - active: 'builder', -}; - -/** - * Order builders for the Builders tree: three buckets, top-down. - * 1. **blocked** (formal gate awaiting approval) — longest-waiting first. - * 2. **waiting** (`classifyBuilderRow`: needs-input, idle or dead, from the - * served agent state or, without one, PTY silence past the threshold). - * 3. **active** — everything else; overview order. - * Blocked rows with no `blockedSince` sort last within the blocked group - * (we don't pretend to know their wait time). Waiting and active - * rows preserve Tower's source order within each bucket. - */ -export function orderForDisplay(builders: OverviewBuilder[], now: number = Date.now()): OverviewBuilder[] { - const ms = (iso: string | null) => iso ? new Date(iso).getTime() : Infinity; - const blocked = builders - .filter(b => b.blocked) - .sort((a, b) => ms(a.blockedSince) - ms(b.blockedSince)); - const rest = builders.filter(b => !b.blocked); - const waiting = rest.filter(b => classifyBuilderRow(b, now) !== 'active'); - const active = rest.filter(b => classifyBuilderRow(b, now) === 'active'); - return [...blocked, ...waiting, ...active]; -} - -/** - * One entry in the agent-terminal cycle (`codev.focusNext/PreviousAgentTerminal`, - * #1563): either an architect (addressed by name) or a builder (addressed by id) — - * the two openable agent kinds the Agents tree renders. Non-agent rows (group - * headers on the stage/area axes, changed-file rows) and non-agent terminals (the - * dev PTY, shells) are never `AgentTarget`s. - */ -export type AgentTarget = - | { kind: 'architect'; name: string } - | { kind: 'builder'; id: string }; +import { ArchitectTreeBuilder, type AgentTarget } from './architect-tree.js'; + +// The row building moved to `architect-tree.ts` (Spec 1963) so the Cockpit can reuse it per +// workspace. Re-exported so existing importers of this module keep working unchanged. +export { + orderForDisplay, + partitionArchitectGroups, + findParentNode, + AccordionRowIds, + type AgentTarget, +} from './architect-tree.js'; /** * Does a cycle entry address the currently-focused agent terminal (#1563)? The @@ -141,30 +88,6 @@ export function agentCycleAttemptOrder( return attempts; } -/** - * Split architect-axis groups into the top-level rows and the idle siblings, in - * render order — the single ordering rule shared by `architectRootChildren` (which - * builds tree rows) and `agentCycleOrder` (which builds the cycle roster), so the - * two cannot drift (the shared-function lesson, #818). `groups` arrives from - * `architectGrouping` already `main`-first then alphabetical; `topLevel` keeps that - * order (`main` and every populated sibling), and the idle siblings (zero builders, - * not `main`) are peeled off to be rendered/cycled last. - */ -export function partitionArchitectGroups( - groups: BuilderGroup[], -): { topLevel: BuilderGroup[]; idleSiblings: BuilderGroup[] } { - const topLevel: BuilderGroup[] = []; - const idleSiblings: BuilderGroup[] = []; - for (const g of groups) { - if (g.key !== 'main' && g.items.length === 0) { - idleSiblings.push(g); - } else { - topLevel.push(g); - } - } - return { topLevel, idleSiblings }; -} - /** * Unified Builders view, with a switchable grouping axis (`codev.buildersGroupBy`, * #952), toggled via the title-bar button: @@ -196,24 +119,26 @@ export class BuildersProvider implements vscode.TreeDataProvider; - // Populated each time `rootChildren()` returns groups; consulted by - // `getParent` so the accordion's `reveal(builderItem)` can walk the - // parent chain in grouping mode. Empty in the single-`Uncategorized` - // flatten case (area mode only — builders are root again), so `getParent` - // returns `undefined` and the accordion works unchanged on that branch. - private groupParentByBuilderId = new Map(); - // Accordion row-id versioning (#913) — see AccordionRowIds. - private readonly rowIds = new AccordionRowIds(); + // The rows themselves: built by the same `ArchitectTreeBuilder` the Cockpit + // uses (Spec 1963), unscoped so every id is the one this view always had. + private readonly tree: ArchitectTreeBuilder; constructor( - private cache: OverviewCache, - private readonly diffCache: BuilderDiffCache, + cache: OverviewCache, + diffCache: BuilderDiffCache, ) { this.groupings = { stage: stageGrouping(), area: areaGrouping(), architect: architectGrouping(), }; + this.tree = new ArchitectTreeBuilder({ + mode: 'act', + scope: '', + getData: () => cache.getData(), + grouping: () => this.active(), + diffCache, + }); cache.onDidChange(() => this.changeEmitter.fire()); } @@ -225,7 +150,7 @@ export class BuildersProvider implements vscode.TreeDataProvider { - if (element instanceof BuilderTreeItem) { - // Builder → its group node (or undefined in the lone-Uncategorized flatten - // case — VSCode treats those builders as roots). - return this.groupParentByBuilderId.get(element.builderId); - } - if (element instanceof BuilderFileTreeItem || element instanceof BuilderFolderTreeItem) { - return this.parentForFileNode(element); - } - if (element instanceof BuilderGroupTreeItem) { - // An idle-sibling architect header is rendered INSIDE the collapsed "Idle - // Architects" container (#1182), not at root, so return that container as its - // parent — otherwise `reveal` treats the header as a root, never expands the - // container, and can't select the row (#1563). Top-level headers (main, - // populated siblings, a lone idle sibling) have no parent. - return this.idleArchitectsContainerParent(element.groupName); - } - // Other group rows (the container itself, etc.) are roots. - return undefined; - } - - /** - * The "Idle Architects" container that renders `architectName` as a child, or - * `undefined` when the architect is not a folded idle sibling (wrong axis, fewer - * than two idle siblings so it renders top-level, or a populated / `main` - * architect). The returned container carries the stable `idle-architects-group` - * id, so `reveal` matches the rendered container and expands it (#1563). - */ - private idleArchitectsContainerParent(architectName: string): IdleArchitectsGroupTreeItem | undefined { - const data = this.cache.getData(); - if (!data) { return undefined; } - const grouping = this.active(); - if (grouping.id !== 'architect') { return undefined; } - const roster = (data.architects ?? []).map(a => a.name); - const groups = grouping.group(orderForDisplay(data.builders, Date.now()), roster); - const { idleSiblings } = partitionArchitectGroups(groups); - // Fewer than two idle siblings → the lone one renders as its own top-level row. - if (idleSiblings.length < 2) { return undefined; } - if (!idleSiblings.some(g => g.key === architectName)) { return undefined; } - return new IdleArchitectsGroupTreeItem(idleSiblings.length); - } - - /** - * Reconstruct the parent of a file or folder row so `reveal` can build the - * chain up to the root (#1066). Reconstruction (not a getChildren-populated - * map) is required because `reveal` walks parents while the subtree is still - * collapsed — `getChildren` for a file only runs once its builder is expanded. - * - * - **Flat-list mode**: a file's parent is the builder row directly. - * - **Tree mode**: rebuild the compacted folder tree (same `buildFilePathTree` - * the rows were rendered from, off the 15s-TTL diff cache) and return the - * enclosing folder row, or the builder row when the node sits at top level. - * - * The reconstructed builder row carries the current accordion-versioned id - * (`makeBuilderRow` → `rowIds.idFor`), and folder rows carry the same - * `::folder::` id `materialiseNode` produces, so the - * chain matches what `getChildren` renders. - */ - /** - * The builder with this id, but only if it has a worktree on record — the - * shared precondition for the changed-file methods (`fileChildren`, - * `parentForFileNode`, `findFileItem`). The return type narrows - * `worktreePath` to a non-null `string`, so callers can pass it to - * `diffCache.getDiff` without re-guarding. - */ - private builderWithWorktree(builderId: string): OverviewBuilderWithWorktree | undefined { - return builderWithWorktree(this.cache.getData(), builderId); - } - - private async parentForFileNode( - element: BuilderFileTreeItem | BuilderFolderTreeItem, - ): Promise { - const builderId = element.builderId; - const builder = this.builderWithWorktree(builderId); - if (!builder) { return undefined; } - const builderRow = this.makeBuilderRow(builder, Date.now()); - - if (!this.viewAsTree()) { - // Flat list: folders don't exist here, so any file's parent is the builder. - return builderRow; - } - - const result = await this.diffCache.getDiff(builderId, builder.worktreePath); - if (result.error) { return builderRow; } - const targetPath = element instanceof BuilderFolderTreeItem - ? element.node.fullPath - : element.plan.resourcePath; - const parentNode = findParentNode(buildFilePathTree(result.files), targetPath); - if (!parentNode) { - // Top-level node: parent is the builder row. - return builderRow; - } - return new BuilderFolderTreeItem(builderId, builder.worktreePath, result.baseRef, parentNode); + return this.tree.getParent(element); } - /** - * Build the `BuilderFileTreeItem` matching `(builderId, relPath)` so the - * active-file sync can hand it to `buildersView.reveal` (#1066). Returns - * `undefined` if the builder or file is no longer present. The constructed - * item's id matches the rendered row, so `reveal` + `getParent` locate and - * highlight the correct row (incl. the right builder when two builders share - * a relative path). - */ - async findFileItem(builderId: string, relPath: string): Promise { - const builder = this.builderWithWorktree(builderId); - if (!builder) { return undefined; } - const result = await this.diffCache.getDiff(builderId, builder.worktreePath); - if (result.error) { return undefined; } - const file = result.files.find(f => f.plan.resourcePath === relPath); - if (!file) { return undefined; } - return new BuilderFileTreeItem(builderId, builder.worktreePath, result.baseRef, file.change, file.plan); - } - - async getChildren(element?: vscode.TreeItem): Promise { - // Second level: a builder's changed files. VSCode only calls this for - // an *expanded* builder, so collapsed builders cost no git. - if (element instanceof BuilderTreeItem) { - return this.fileChildren(element.builderId); - } - // Folder rows (tree-mode only) expand to their child folders/files. - if (element instanceof BuilderFolderTreeItem) { - return element.node.children!.map(child => - materialiseNode(element.builderId, element.worktreePath, element.baseRef, child), - ); - } - // File rows are leaves. - if (element instanceof BuilderFileTreeItem) { - return []; - } - // The Idle Architects container (architect axis, Issue 1182) expands to the - // individual idle-sibling architect rows. - if (element instanceof IdleArchitectsGroupTreeItem) { - return this.idleArchitectRows(Date.now()); - } - // Group rows expand to their builders. - if (element instanceof BuilderGroupTreeItem) { - return this.rowsForGroup(element.groupName); - } - // Root: group headers (one per active-axis group), or the lone-Uncategorized - // flatten case (area mode, unlabeled repos). - return this.rootChildren(); - } - - private rootChildren(): vscode.TreeItem[] { - this.groupParentByBuilderId.clear(); - - const data = this.cache.getData(); - if (!data) { - return []; - } - - const now = Date.now(); - const grouping = this.active(); - // The registered-architect roster (live sessions, main-first) — sourced from - // the overview cache the provider already holds, no second fetch. Only the - // architect axis consumes it, to emit a header for every architect including - // childless ones (Issue 1174); the other axes ignore the arg. Guard `??` for - // a pre-roster overview payload so `.map` never throws. - const roster = (data.architects ?? []).map(a => a.name); - const groups = grouping.group(orderForDisplay(data.builders, now), roster); - - // A repo that doesn't use `area/*` labels yields a single `Uncategorized` - // group; in area mode its header adds no information, so flatten to root rows - // — zero visual regression for unlabeled repos. Stage and architect modes - // opt out of this (their lone group always carries information). - if (grouping.flattenLoneUncategorized && groups.length === 1 && groups[0].key === UNCATEGORIZED_AREA) { - return groups[0].items.map(b => this.makeBuilderRow(b, now)); - } - - // The architect axis rolls idle siblings into an "Idle Architects" container - // (Issue 1182), so it renders through its own method. Stage/area render every - // group as its own header. - if (grouping.id === 'architect') { - return this.architectRootChildren(groups, now); - } - // Populated groups render Expanded (#913) — no persisted state. VSCode's - // native per-id memory keeps a user-collapsed group collapsed for the - // rest of the session; on a fresh session this default applies again. - // Stage/area groups always hold ≥1 builder (no empty groups on these axes), - // so they never carry a command — they name no launchable entity. - return groups.map(g => this.makeGroupRow(g, now, false)); + getChildren(element?: vscode.TreeItem): Promise { + return this.tree.getChildren(element); } - /** - * Root rows for the architect axis (Issue 1182). `main` and every populated - * sibling render as their own top-level group (unchanged from #1174); idle - * siblings (zero builders, not `main`) roll up under a single collapsed - * "Idle Architects" container — but only when ≥ 2 are idle. A lone idle - * sibling keeps its own row (the group would save no space for one row and - * only adds a click). Ordering: `main` first, then populated siblings, then - * the idle container / lone idle sibling at the bottom — "primary work first, - * roster second." - * - * `groups` arrives from `architectGrouping` already ordered `main`-first then - * the rest alphabetically. Iterating it preserves that order for the rows that - * stay top-level; the idle siblings are peeled off and re-emitted last. - * - * `main` is always its own row regardless of builder count: it is the - * always-present workspace home base (created by `launchInstance` on any - * workspace; every sibling is opt-in via `add-architect`), so burying it - * behind a chevron is a bad trade for one row of vertical space. - */ - private architectRootChildren(groups: BuilderGroup[], now: number): vscode.TreeItem[] { - const { topLevel, idleSiblings } = partitionArchitectGroups(groups); - const rows: vscode.TreeItem[] = topLevel.map(g => this.makeGroupRow(g, now, true)); - if (idleSiblings.length >= 2) { - rows.push(new IdleArchitectsGroupTreeItem(idleSiblings.length)); - } else { - // 0 → nothing; 1 → the lone idle sibling renders as its own top-level row. - for (const g of idleSiblings) { - rows.push(this.makeGroupRow(g, now, true)); - } - } - return rows; + /** The changed-file row for `(builderId, relPath)`, for the active-file reveal (#1066). */ + findFileItem(builderId: string, relPath: string): Promise { + return this.tree.findFileItem(builderId, relPath); } - /** - * The agent-terminal cycle roster (#1563), flattened top-to-bottom in the SAME - * order the Agents tree renders, so `codev.focusNext/PreviousAgentTerminal` mirror - * the sidebar exactly and stay grouping-aware. Built from the same primitives the - * renderer uses — `orderForDisplay` + the active grouping strategy — so there is no - * parallel ordering to drift (#818). - * - * The roster is axis-dependent, matching what each axis actually renders: - * - **stage / area** (incl. the lone-`Uncategorized` flatten): only builder rows - * are agents; architects render no rows on these axes, so they are not cycled. - * - **architect**: architect headers are first-class agents (their rows carry the - * open-terminal command), interleaved with their builders in top-level order via - * the shared `partitionArchitectGroups`; idle siblings (zero builders) render — - * and so cycle — last. - * - * Non-agent terminals (the dev PTY, shells) are never in the roster because only - * architects and builders appear here. - */ + /** The agent-cycle roster in render order (#1563). */ agentCycleOrder(): AgentTarget[] { - const data = this.cache.getData(); - if (!data) { return []; } - const now = Date.now(); - const grouping = this.active(); - const roster = (data.architects ?? []).map(a => a.name); - const groups = grouping.group(orderForDisplay(data.builders, now), roster); - - if (grouping.id !== 'architect') { - return groups.flatMap(g => g.items.map((b): AgentTarget => ({ kind: 'builder', id: b.id }))); - } - - // Emit each architect header followed by its builders, in render order: - // top-level groups first, then the idle siblings last (the "Idle Architects" - // container at the bottom). Idle siblings carry zero builders by construction, so - // the inner loop is simply empty for them — no separate pass needed. - const { topLevel, idleSiblings } = partitionArchitectGroups(groups); - const architectOrder = [...topLevel, ...idleSiblings]; - const targets: AgentTarget[] = []; - for (const g of architectOrder) { - targets.push({ kind: 'architect', name: g.key }); - for (const b of g.items) { targets.push({ kind: 'builder', id: b.id }); } - } - return targets; + return this.tree.agentCycleOrder(); } - /** - * The tree item to `reveal({ select: true })` so the sidebar selection follows the - * agent-cycle commands (#1563) the same way a row click highlights the clicked row. - * Returns `undefined` when the agent is no longer in the cache. - * - * - **builder**: the same versioned row `makeBuilderRow` renders, so `reveal` matches - * it by id and expands its group ancestor to bring it into view. - * - **architect**: a header carrying the stable `builder-group:` id, which - * matches the rendered architect header. For an idle-sibling architect folded into - * the "Idle Architects" container, `getParent` returns that container (via - * `idleArchitectsContainerParent`), so `reveal` expands the container and selects - * the row rather than leaving it hidden. - */ + /** The row to select when the agent cycle lands on `target` (#1563). */ revealTargetForAgent(target: AgentTarget): vscode.TreeItem | undefined { - const data = this.cache.getData(); - if (!data) { return undefined; } - if (target.kind === 'builder') { - const builder = data.builders.find(b => b.id === target.id); - if (!builder) { return undefined; } - return this.makeBuilderRow(builder, Date.now()); - } - // Architect header: only the id is consulted by `reveal`, so the count / state - // passed here are placeholders — they never render. - return new BuilderGroupTreeItem( - target.name, 0, vscode.TreeItemCollapsibleState.None, { blocked: 0, idle: 0, active: 0 }); - } - - /** - * The individual idle-sibling architect rows shown when the "Idle Architects" - * container is expanded (Issue 1182). Each is a childless - * `BuilderGroupTreeItem` — the same leaf-like `(0)` row #1174 renders at top - * level — carrying its own `codev.openArchitectTerminal` command, so clicking a - * name inside the group opens that architect's terminal. Recomputed from the - * cache (not cached from `rootChildren`) so it stays correct across overview - * ticks; harmlessly returns `[]` if the axis is no longer `architect`. - */ - private idleArchitectRows(now: number): vscode.TreeItem[] { - const data = this.cache.getData(); - if (!data) { return []; } - const grouping = this.active(); - if (grouping.id !== 'architect') { return []; } - const roster = (data.architects ?? []).map(a => a.name); - const groups = grouping.group(orderForDisplay(data.builders, now), roster); - return groups - .filter(g => g.key !== 'main' && g.items.length === 0) - .map(g => this.makeGroupRow(g, now, true)); - } - - /** - * Build one group header row. `isArchitectAxis` headers get a - * click-to-open-terminal `command` (#1108): the architect is first-class in - * this mode, so its header matches the builder-row affordance (row click opens - * the terminal; the chevron still toggles expand/collapse — VSCode routes the - * two gestures independently). A childless architect group (Issue 1174) has no - * builders to expand into, so it renders as a leaf-like row (`None`) rather - * than an empty accordion; the command still fires on the row body. Populated - * groups render Expanded (#913). Stage/area headers stay command-less - * containers. Registers each builder's parent group for `getParent`. - */ - private makeGroupRow(g: BuilderGroup, now: number, isArchitectAxis: boolean): BuilderGroupTreeItem { - let collapsibleState: vscode.TreeItemCollapsibleState; - if (g.items.length === 0) { - collapsibleState = vscode.TreeItemCollapsibleState.None; - } else { - collapsibleState = vscode.TreeItemCollapsibleState.Expanded; - } - const groupItem = new BuilderGroupTreeItem( - g.key, - g.items.length, - collapsibleState, - rollupGroupState(g.items, now), - ); - if (isArchitectAxis) { - // The `g.key` (architect name; null owners folded into `main` by - // architectGrouping) is the optional name arg `codev.openArchitectTerminal` - // already accepts; it warns gracefully on a stale owner not in the roster. - groupItem.command = { - command: 'codev.openArchitectTerminal', - title: 'Open Architect Terminal', - arguments: [g.key], - }; - } - for (const b of g.items) { - this.groupParentByBuilderId.set(b.id, groupItem); - } - return groupItem; - } - - private rowsForGroup(key: string): vscode.TreeItem[] { - const data = this.cache.getData(); - if (!data) { return []; } - - const now = Date.now(); - const ordered = orderForDisplay(data.builders, now); - const roster = (data.architects ?? []).map(a => a.name); - const group = this.active().group(ordered, roster).find(g => g.key === key); - if (!group) { return []; } - - return group.items.map(b => this.makeBuilderRow(b, now)); - } - - private makeBuilderRow(b: OverviewBuilder, now: number): BuilderTreeItem { - // Classify once; the state drives the label, the tooltip, the contextValue - // family (menu scoping) and the icon. - const state = classifyBuilderRow(b, now); - const item = new BuilderTreeItem(b.id, builderRowLabel(b, state, now, this.active().rowPrefix(b))); - // Versioned id (#913). The base `b.id` is stable (not the churning label) so - // VSCode preserves a row's expansion across the frequent overview-poll - // refreshes; the `#` suffix is the accordion lever (see - // AccordionRowIds). Group ids carry no suffix, so the accordion can't touch - // them. - item.id = this.rowIds.idFor(b.id); - // Expandable so the second-level changed-files list can hang off it. - // The row keeps its open-terminal command (single click); the chevron - // toggles the file list. - item.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed; - // A plain string, never a MarkdownString: the needs-input summary renders literally (SC19). - item.tooltip = builderRowTooltip(b, state); - // contextValue encodes the row's state-family + protocol so menus - // can scope by either (Approve Gate inline only on - // blocked-builder-*; everything else applies to all three - // families). The optional `-review` suffix signals that the - // builder has committed a review file on disk — the - // `codev.viewReviewFile` menu entry's `when` clause keys off it so - // PIR rows hide the entry until the review phase produces the file. - const protocol = b.protocol || 'unknown'; - const reviewSuffix = builderHasReviewFile(b) ? '-review' : ''; - item.contextValue = `${CONTEXT_FAMILY[state]}-${protocol}${reviewSuffix}`; - // Icon: the shared per-state glyph (single source of truth in - // builder-row.ts). A blocked row overrides the shape with the gate-specific - // `gateIconFor` codicon while keeping the shared warning color. - const { icon, color } = BUILDER_STATE_GLYPH[state]; - let iconName = icon; - if (state === 'blocked') { iconName = gateIconFor(b.blockedGate); } - item.iconPath = new vscode.ThemeIcon(iconName, new vscode.ThemeColor(color)); - // The row click runs `codev.openBuilderRow` — a wrapper that opens the - // builder terminal and, when `codev.buildersClickExpands` is on (the - // default), also expands the row (the file list). Pass the item itself so - // the handler can call `buildersView.reveal(...)` against this row. Other - // callers (terminal-link clicks, etc.) still use `codev.openBuilderById` - // directly with just the id and don't trigger expansion. - item.command = { - command: 'codev.openBuilderRow', - title: 'Open Builder Terminal', - arguments: [item], - }; - return item; - } - - /** - * Changed-file rows for one builder, rendered as a flat list or a - * folder tree depending on the `codev.buildersFileViewAsTree` setting. - * The diff data and the leaf shape (BuilderFileTreeItem) are identical - * in both modes — only the grouping around the leaves differs. - */ - private async fileChildren(builderId: string): Promise { - const builder = this.builderWithWorktree(builderId); - if (!builder) { - return [placeholder('No worktree on record')]; - } - - const result = await this.diffCache.getDiff(builderId, builder.worktreePath); - if (result.error) { - const row = placeholder('Diff unavailable'); - row.tooltip = result.error; - return [row]; - } - if (result.files.length === 0) { - return [placeholder('No changes yet')]; - } - - if (this.viewAsTree()) { - // Tree mode: group by folder, compact single-child folder chains. - // Top-level nodes may be folders or root-level files (e.g. README). - return buildFilePathTree(result.files).map(node => - materialiseNode(builderId, builder.worktreePath, result.baseRef, node), - ); - } - // List mode (today's behaviour): flat, one row per changed file. - return result.files.map( - f => new BuilderFileTreeItem(builderId, builder.worktreePath, result.baseRef, f.change, f.plan), - ); - } - - /** Read the file-view-as-tree setting; falls back to the spec default. */ - private viewAsTree(): boolean { - return readBuildersFileViewAsTree(); - } -} - -/** - * Render one tree-mode node as either a folder row (if it has children) - * or a file row (if it carries a leaf). Folders carry the worktreePath - * + baseRef forward so the renderer can construct file children on - * subsequent expansion without re-fetching from the diff cache. - */ -function materialiseNode( - builderId: string, - worktreePath: string, - baseRef: string, - node: FilePathNode, -): vscode.TreeItem { - if (node.children) { - return new BuilderFolderTreeItem(builderId, worktreePath, baseRef, node); - } - // Leaf: must have a file (folder-without-children shouldn't be reachable - // from buildFilePathTree, but the type allows it — guard defensively). - if (!node.file) { - return placeholder(node.name); - } - return new BuilderFileTreeItem(builderId, worktreePath, baseRef, node.file.change, node.file.plan); -} - -/** - * Walk a (compacted) file-path tree and return the parent node of the node - * whose `fullPath` matches `targetPath`, or `undefined` when the target sits at - * top level (no parent folder) or isn't found. Used by `getParent` to - * reconstruct a file/folder row's enclosing folder for `reveal` (#1066). - * - * Folder fullPaths are compacted (`packages/codev/src`), and a file leaf's - * `fullPath` equals its `plan.resourcePath` (leaves aren't compacted), so a - * direct `fullPath` match resolves both row kinds. - * - * Returns `undefined` for both "top-level node (no parent folder)" and "not - * found"; the caller treats both as "parent is the builder row". Recursive - * calls always pass a defined `parent`, so a node found below the top level - * never resolves to `undefined`. - */ -export function findParentNode( - nodes: FilePathNode[], - targetPath: string, - parent?: FilePathNode, -): FilePathNode | undefined { - for (const node of nodes) { - if (node.fullPath === targetPath) { return parent; } - if (node.children) { - const found = findParentNode(node.children, targetPath, node); - if (found !== undefined) { return found; } - } - } - return undefined; -} - -/** - * Sync-check whether a builder has committed a review file on disk. - * - * Mirrors the prefix filter in `commands/view-artifact.ts`: a file - * counts if it lives in `/codev/reviews/`, ends in `.md`, and - * either starts with `-` or is exactly `.md`. Used by the - * Builders tree row builder to suffix `contextValue` with `-review` so - * PIR rows can hide `codev.viewReviewFile` until the review phase emits - * the file (non-PIR protocols always show the entry — they fall back to - * the missing-file toast in `view-artifact.ts`). - * - * One `readdirSync` per builder per render — the reviews dir is small, - * local, and only inspected when overview data changes. Cheaper than - * the diff-cache work the row triggers on expansion. - */ -function builderHasReviewFile(b: OverviewBuilder): boolean { - if (!b.worktreePath) { return false; } - const dir = resolve(b.worktreePath, 'codev/reviews'); - if (!existsSync(dir)) { return false; } - const prefix = `${b.id}-`; - try { - return readdirSync(dir).some( - f => f.endsWith('.md') && (f.startsWith(prefix) || f === `${b.id}.md`), - ); - } catch { - return false; - } -} - -/** - * Builder-row id versioning for the accordion (#913). VSCode has no "collapse - * this row" API and replays its remembered expand-state for any id it has seen, - * so the only way to force a row collapsed is to render it under a never-seen - * id. Every row id is `#`; bumping the version (`keepOnly`) - * hands every row a fresh — hence collapsed — id, except the one being held - * open, which keeps the exact id it was clicked at so VSCode keeps it expanded. - * - * The open row's id is stored verbatim (not reconstructed from a number), so a - * render that lands between a bump and the next click can't leave the open row - * pointing at a stale version. - */ -export class AccordionRowIds { - private version = 0; - private openBuilderId: string | undefined; - private openRowId: string | undefined; - - /** The id to render for `builderId` this pass. */ - idFor(builderId: string): string { - if (builderId === this.openBuilderId && this.openRowId) { - return this.openRowId; - } - return `${builderId}#${this.version}`; - } - - /** Hold `builderId` open at its current `rowId`; re-version everyone else. */ - keepOnly(builderId: string, rowId: string | undefined): void { - this.openBuilderId = builderId; - this.openRowId = rowId; - this.version += 1; + return this.tree.revealTargetForAgent(target); } } @@ -902,11 +277,3 @@ export async function runBuilderRowClick( // Benign if the row is no longer present (e.g. mid-cleanup). } } - -/** Non-clickable informational leaf (no worktree / no changes / error). */ -function placeholder(label: string): vscode.TreeItem { - const item = new vscode.TreeItem(label); - item.contextValue = 'builder-file-none'; - item.iconPath = new vscode.ThemeIcon('circle-slash', new vscode.ThemeColor('disabledForeground')); - return item; -} diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 82eb6a259..b3f8f0d40 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -311,3 +311,68 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when - The fleet cache keys by Tower's path spelling. Phase 4's current-workspace match must use the existing `isSameWorkspacePath` (`fleet-order.ts`), as `orderFleet` does, and a test should assert it. + +### Phase 3 (`architect_tree_builder`), iteration 1 (2026-11-24): row building moved into `ArchitectTreeBuilder` + +- New `apps/vscode/src/views/architect-tree.ts`. `ArchitectTreeBuilder` now owns what + `BuildersProvider` did privately: + - row-id versioning (`AccordionRowIds`, now with a scope prefix) and the builder → group parent + map; + - group, builder, *Idle Architects* and changed-file rows, and their `getParent` reconstruction; + - `findFileItem`, `revealTargetForAgent` and `agentCycleOrder`. +- `BuildersProvider` is a thin provider over one builder with scope `''`, mode `act` and its + active axis. `builders.ts` re-exports every symbol that moved (`orderForDisplay`, + `partitionArchitectGroups`, `findParentNode`, `AccordionRowIds`, `AgentTarget`), so no importer + changed. `agentTargetIsFocused`, `agentCycleAttemptOrder`, `AccordionGate` and + `runBuilderRowClick` stay in `builders.ts`: they are view wiring, not row building. +- The five row classes take an optional trailing `scope` that prefixes their id and is kept as a + property. With `''` every id is the one it was. +- Modes: + - `act` + scope `''` (Agents): unchanged. + - `act` + a scope (this window in the Cockpit): architect rows get `cockpit-architect-main` or + `cockpit-architect-sibling`. Builder, file and folder rows keep the Agents contextValues and + commands. + - `navigate`: builder rows are leaves; architect rows still expand. Every architect and builder + row clicks to `codev.tower.openWorkspace` with the target, and its tooltip names the workspace. + contextValues are `REMOTE_CONTEXT` (`cockpit-remote-architect`, `-builder`, + `-idle-architects`). `findFileItem` and `revealTargetForAgent` answer `undefined`, because the + agent cycle and the active-file reveal are about this window's agents only. + - `attentionCounts`: appends `N held · N queued` to builder-row descriptions, from + `deriveAttention` over the builder's own `getData()`, recomputed when the overview object + changes. It is off for the Agents view. +- Deviations from the plan's wording, behaviour unchanged: + - The stage/area root branch and the lone-`Uncategorized` flatten moved into + `ArchitectTreeBuilder.rootRows()` with the architect branch. The plan said they would stay in + the provider. All three branches depend on the parent-map reset the builder owns, and the + builder already receives the active axis. Leaving them in the provider would have meant a + "reset, then call back in" protocol across two classes. The snapshot covers all three axes. + - Navigate options take no `grouping`: navigate mode is always the architect axis, so the type + rules out the other axes. + - Navigate `target` is a function, read on every render, so a workspace whose label changes + (disambiguation) never shows a stale name or target. + - The *Idle Architects* container in navigate mode has no click command, as in the Agents view: + clicking it toggles it. It carries `cockpit-remote-idle-architects`. +- Three of the tests the plan names live in the Electron suite (`src/test/`), not `__tests__/`: + `builders.test.ts`, `area-grouping.test.ts` and `builder-file-tree-item.test.ts`. `check-types` + compiles them, and their imports and constructor calls are unchanged. They were not run, because + they need the vscode-test Electron harness. +- Tests: `apps/vscode/src/__tests__/architect-tree.test.ts`, 33 tests. + - Equivalence: the walk covers N=0/1/>1 builders × 3 axes × flat/tree file modes (18 cases). It + records every row's id, label, description, contextValue, collapsible state, icon, command and + tooltip, its `getParent` answer, and the agent-cycle roster. The snapshot + (`__snapshots__/architect-tree.test.ts.snap`) was recorded from the **pre-refactor** provider + before any source change, and it matches after. + - Builder tests: scoped ids and disjointness, including two acting scopes and one navigating + scope over shared `main` and builder ids, in both file modes. Also: accordion re-versioning + under a scope, main/sibling contextValues, the null-owner fold, the non-live architect, the idle + roll-up, a childless leaf, `getParent` chains (file → folder → folder → builder → architect, + and idle sibling → container), and agent-cycle targets. + - Navigate tests: leaf shape, the click command, tooltips, labels and glyphs equal to the acting + rows, a target read on every render, and attention counts in both modes. Every `viewItem` + pattern in `package.json` is parsed, and none of them matches a `REMOTE_CONTEXT` value. + - Mutation-checked: unscoping each id kind, a non-leaf navigate builder, a remote contextValue + that a builder menu matches, dropping the cockpit-architect contextValues, a stale counts cache, + and the folder's default scope each fail a test. Giving the Agents view the cockpit contextValue + or an empty description fails the snapshot. +- `check-types` is clean. `lint` shows only the two pre-existing `curly` warnings. `test:unit` + passed 1326/1326 (1293 + 33). `esbuild` bundles. From fd11b549b29971c8416f9542aec3999ff063b652 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 23:59:52 -0800 Subject: [PATCH 048/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index d9d2a0313..7b214abfe 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:47:49.148Z' +updated_at: '2026-11-24T07:59:52.245Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 5954466813aedb1848509edbca2fe3bec2f447ff Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:05:13 -0800 Subject: [PATCH 049/140] =?UTF-8?q?[Spec=201963][Phase:=20architect=5Ftree?= =?UTF-8?q?=5Fbuilder]=20fix:=20review=20notes=20=E2=80=94=20navigate=20bu?= =?UTF-8?q?ilders=20stay=20out=20of=20the=20agent=20cycle;=20mis-routed=20?= =?UTF-8?q?rows=20throw?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/__tests__/architect-tree.test.ts | 28 +++++++++++++++++++ apps/vscode/src/views/architect-tree.ts | 28 +++++++++++++++++-- codev/state/spir-1963_thread.md | 24 ++++++++++++++++ 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/apps/vscode/src/__tests__/architect-tree.test.ts b/apps/vscode/src/__tests__/architect-tree.test.ts index 2d0908d76..2b0b46bf1 100644 --- a/apps/vscode/src/__tests__/architect-tree.test.ts +++ b/apps/vscode/src/__tests__/architect-tree.test.ts @@ -374,6 +374,32 @@ describe('ArchitectTreeBuilder: scoped ids', () => { const after = await tree.getChildren(find(await tree.getChildren(), 'ws:/a|builder-group:main')); expect(ids(after)).toEqual(['ws:/a|spir-10#0', 'ws:/a|air-11#1']); }); + + it('keeps accordion state per builder: re-versioning one leaves another untouched', async () => { + const a = actTree(MANY, 'ws:/a|'); + const b = actTree(MANY, 'ws:/b|'); + const mainRows = async (tree: typeof a, scope: string) => + ids(await tree.getChildren(find(await tree.getChildren(), `${scope}builder-group:main`))); + a.keepOnlyOpen(find(await a.getChildren(find(await a.getChildren(), 'ws:/a|builder-group:main')), 'ws:/a|spir-10#0')); + expect(await mainRows(a, 'ws:/a|')).toEqual(['ws:/a|spir-10#0', 'ws:/a|air-11#1']); + expect(await mainRows(b, 'ws:/b|')).toEqual(['ws:/b|spir-10#0', 'ws:/b|air-11#0']); + }); + + it('refuses a row another builder made, in getChildren and getParent', async () => { + const a = actTree(MANY, 'ws:/a|'); + const b = actTree(MANY, 'ws:/b|'); + const foreignGroup = find(await b.getChildren(), 'ws:/b|builder-group:main'); + const foreignBuilder = find(await b.getChildren(foreignGroup), 'ws:/b|spir-10#0'); + await expect(a.getChildren(foreignGroup)).rejects.toThrow("row of scope 'ws:/b|' routed here"); + await expect(a.getChildren(foreignBuilder)).rejects.toThrow("row of scope 'ws:/b|' routed here"); + expect(() => a.getParent(foreignBuilder)).toThrow("row of scope 'ws:/b|' routed here"); + }); + + it('refuses an unrecognised row instead of rendering the root again', async () => { + const tree = actTree(MANY, 'ws:/a|'); + const stray = { label: 'stray' } as vscode.TreeItem; + await expect(tree.getChildren(stray)).rejects.toThrow("no children for unrecognised row 'stray'"); + }); }); describe('ArchitectTreeBuilder: act mode, scoped (this window in the Cockpit)', () => { @@ -470,6 +496,8 @@ describe('ArchitectTreeBuilder: navigate mode (another workspace\'s rows)', () = } expect(await tree.findFileItem('spir-10', 'README.md')).toBeUndefined(); expect(tree.revealTargetForAgent({ kind: 'builder', id: 'spir-10' })).toBeUndefined(); + // The agent cycle opens this window's terminals; another workspace's agents are not in it. + expect(tree.agentCycleOrder()).toEqual([]); }); it('every row clicks to open the workspace, and its tooltip names that workspace', async () => { diff --git a/apps/vscode/src/views/architect-tree.ts b/apps/vscode/src/views/architect-tree.ts index f5111c4db..8b1b5b678 100644 --- a/apps/vscode/src/views/architect-tree.ts +++ b/apps/vscode/src/views/architect-tree.ts @@ -206,9 +206,13 @@ export class ArchitectTreeBuilder { /** * The children of `element`, or the root rows when it is `undefined`. `element` must be a row - * this builder made (same `scope`). + * this builder made (same `scope`); anything else is a routing bug and throws. */ async getChildren(element?: vscode.TreeItem): Promise { + if (element === undefined) { + return this.rootRows(); + } + this.assertOwnRow(element); // Second level: a builder's changed files. VSCode only calls this for // an *expanded* builder, so collapsed builders cost no git. Navigate-mode // builder rows are leaves. @@ -235,7 +239,21 @@ export class ArchitectTreeBuilder { if (element instanceof BuilderGroupTreeItem) { return this.rowsForGroup(element.groupName); } - return this.rootRows(); + // Placeholders are leaves, so VSCode never asks for their children. + throw new Error(`ArchitectTreeBuilder: no children for unrecognised row '${String(element.label)}'`); + } + + /** + * Throw when `element` is a row another builder made. A host holding several + * builders (the Cockpit) routes each row by its `scope`; a row that reaches the + * wrong builder would otherwise render that builder's rows, or answer another + * workspace's parent, without any sign of the mistake. + */ + private assertOwnRow(element: vscode.TreeItem): void { + const scope = (element as { scope?: unknown }).scope; + if (typeof scope === 'string' && scope !== this.scope) { + throw new Error(`ArchitectTreeBuilder '${this.scope}': row of scope '${scope}' routed here`); + } } // The accordion's `reveal(builderItem)` and the active-file sync's @@ -251,6 +269,7 @@ export class ArchitectTreeBuilder { // A root answer (`undefined`) is root *within this builder*: a host that nests // the builder's rows under its own nodes bridges from there. getParent(element: vscode.TreeItem): vscode.ProviderResult { + this.assertOwnRow(element); if (element instanceof BuilderTreeItem) { return this.groupParentByBuilderId.get(element.builderId); } @@ -444,9 +463,12 @@ export class ArchitectTreeBuilder { * and so cycle — last. * * Non-agent terminals (the dev PTY, shells) are never in the roster because only - * architects and builders appear here. + * architects and builders appear here. Empty in navigate mode: the cycle opens + * terminals through this window's `TerminalManager`, and another workspace's + * agents are not there. */ agentCycleOrder(): AgentTarget[] { + if (this.options.mode !== 'act') { return []; } const data = this.options.getData(); if (!data) { return []; } const groups = this.groupsOf(data, Date.now()); diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index b3f8f0d40..681328a77 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -376,3 +376,27 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when or an empty description fails the snapshot. - `check-types` is clean. `lint` shows only the two pre-existing `curly` warnings. `test:unit` passed 1326/1326 (1293 + 33). `esbuild` bundles. +- Review, iteration 1: Codex and Claude both approved with HIGH confidence, and neither raised a + blocking issue. + - Taken now, from Claude's non-blocking notes: + - `agentCycleOrder()` returns `[]` in navigate mode, as `findFileItem` and + `revealTargetForAgent` already did. The cycle opens terminals through this window's + `TerminalManager`, so another workspace's agents must never enter it. + - `getChildren` and `getParent` throw on a row whose `scope` is another builder's. + `getChildren` also throws on an unrecognised row, where it used to fall through and render + the root again. A Phase 4 routing mistake now fails loudly instead of duplicating rows. + - A new test asserts that two builders' accordion versioning is independent. + - Each of the three was mutation-checked. `test:unit` passed 1329/1329. + - Carried into Phase 4, not changed here: + - Rendering this window's builder rows probes the disk for a review file + (`builderHasReviewFile`). The Cockpit will render on fleet ticks as well as overview changes, + which roughly doubles those probes. Keep that in mind when Phase 4 chooses its re-render + signals. Navigate rows do no fs work. + - `architect-tree.ts` imports `views/tower.ts` for `OPEN_WORKSPACE_COMMAND` and + `WorkspaceTarget`. There is no cycle and nothing touches `vscode` at load time. The import is + cosmetic and stays as it is. + - Snapshot provenance: Claude could not confirm from git that the snapshot predates the refactor, + because both landed in one commit. The order was: test written, snapshot recorded + (`Snapshots 18 written`) against the untouched `BuildersProvider`, then the source changes, + after which the snapshot matched unchanged. The mutation runs also show the snapshot is not + self-confirming: giving the Agents view a cockpit contextValue or a description fails it. From 7763f1dab4d90b6c2da35d64370f29afe9a92d43 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:05:13 -0800 Subject: [PATCH 050/140] =?UTF-8?q?chore(porch):=201963=20advance=20plan?= =?UTF-8?q?=20phase=20=E2=86=92=20cockpit=5Fhierarchy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1963-vscode-alternative-layout-seco/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 7b214abfe..3352b00bd 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -11,10 +11,10 @@ plan_phases: status: complete - id: architect_tree_builder title: Reusable, workspace-scoped architect-axis row builder - status: in_progress + status: complete - id: cockpit_hierarchy title: Cockpit button and the Tower → workspaces → architects → builders tree - status: pending + status: in_progress - id: cockpit_actions title: Placement-table actions on the hierarchy, parity mapping, increment-1 verification status: pending @@ -30,7 +30,7 @@ plan_phases: - id: arrange_cockpit title: 'Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification' status: pending -current_plan_phase: architect_tree_builder +current_plan_phase: cockpit_hierarchy gates: spec-approval: status: approved @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T07:59:52.245Z' +updated_at: '2026-11-24T08:05:13.344Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -71,3 +71,5 @@ context_refreshes: - boundary: plan-phase:architect_tree_builder at: '2026-11-24T07:47:00.222Z' acknowledged_at: '2026-11-24T07:47:49.148Z' + - boundary: plan-phase:cockpit_hierarchy + at: '2026-11-24T08:05:13.344Z' From 39ae22aee501331710f2c2cebd1487a999c2db1e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:05:18 -0800 Subject: [PATCH 051/140] chore(porch): 1963 acknowledge context refresh --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 3352b00bd..629db231b 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T08:05:13.344Z' +updated_at: '2026-11-24T08:05:18.924Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -73,3 +73,4 @@ context_refreshes: acknowledged_at: '2026-11-24T07:47:49.148Z' - boundary: plan-phase:cockpit_hierarchy at: '2026-11-24T08:05:13.344Z' + acknowledged_at: '2026-11-24T08:05:18.924Z' From 18f10db34fc9b27d9de316d59ede7665b990a989 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:28:09 -0800 Subject: [PATCH 052/140] =?UTF-8?q?[Spec=201963][Phase:=20cockpit=5Fhierar?= =?UTF-8?q?chy]=20feat:=20Codev=20Cockpit=20button=20and=20the=20Tower=20?= =?UTF-8?q?=E2=86=92=20workspaces=20=E2=86=92=20architects=20=E2=86=92=20b?= =?UTF-8?q?uilders=20tree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New activity-bar container `codev-cockpit` (rotated Codev icon) holding one view, `codev.cockpit`, with a title-bar Refresh. - `CockpitProvider`: Tower root with connection-state rows, the Tower view's workspace rows and Dormant group, and per active workspace an `ArchitectTreeBuilder` — this window's workspace acts (the Agents view's architect-axis rows, scoped ids), every other workspace navigates to its own window. `getParent` reaches the Tower root from every row. - `AgentTreeHosts` generalises the Agents view's row click, accordion, follow-reveals, builder-active hook and badge over both views; `OverviewRefreshGate` keeps the periodic overview refresh running while only the Cockpit is visible; `workspaceActivityBadge` computes the shared badge. - `ArchitectTreeBuilder`: architect wait text and glyph behind the `attention` option, and `getParent` builds the root rows when a builder's group is not yet known. --- apps/vscode/icons/codev-cockpit.svg | 1 + apps/vscode/package.json | 18 + .../contributes-cockpit.test.ts.snap | 559 ++++++++++++ .../src/__tests__/architect-tree.test.ts | 8 +- .../vscode/src/__tests__/cockpit-icon.test.ts | 41 + .../src/__tests__/cockpit-provider.test.ts | 809 ++++++++++++++++++ .../src/__tests__/cockpit-wiring.test.ts | 445 ++++++++++ .../src/__tests__/contributes-cockpit.test.ts | 86 ++ .../__tests__/worktree-window-1809.test.ts | 16 +- apps/vscode/src/extension.ts | 208 +++-- apps/vscode/src/mailbox-indicators.ts | 27 +- apps/vscode/src/views/agent-tree-hosts.ts | 176 ++++ apps/vscode/src/views/architect-tree.ts | 71 +- apps/vscode/src/views/builders.ts | 5 + apps/vscode/src/views/cockpit.ts | 400 +++++++++ .../vscode/src/views/overview-refresh-gate.ts | 74 ++ apps/vscode/src/views/tower.ts | 111 ++- codev/state/spir-1963_thread.md | 63 ++ 18 files changed, 2942 insertions(+), 176 deletions(-) create mode 100644 apps/vscode/icons/codev-cockpit.svg create mode 100644 apps/vscode/src/__tests__/__snapshots__/contributes-cockpit.test.ts.snap create mode 100644 apps/vscode/src/__tests__/cockpit-icon.test.ts create mode 100644 apps/vscode/src/__tests__/cockpit-provider.test.ts create mode 100644 apps/vscode/src/__tests__/cockpit-wiring.test.ts create mode 100644 apps/vscode/src/__tests__/contributes-cockpit.test.ts create mode 100644 apps/vscode/src/views/agent-tree-hosts.ts create mode 100644 apps/vscode/src/views/cockpit.ts create mode 100644 apps/vscode/src/views/overview-refresh-gate.ts diff --git a/apps/vscode/icons/codev-cockpit.svg b/apps/vscode/icons/codev-cockpit.svg new file mode 100644 index 000000000..a61eb9a6a --- /dev/null +++ b/apps/vscode/icons/codev-cockpit.svg @@ -0,0 +1 @@ + diff --git a/apps/vscode/package.json b/apps/vscode/package.json index 8788986e9..6e2ffb771 100644 --- a/apps/vscode/package.json +++ b/apps/vscode/package.json @@ -91,6 +91,11 @@ "title": "Codev: Refresh Tower", "icon": "$(refresh)" }, + { + "command": "codev.cockpit.refresh", + "title": "Codev: Refresh Cockpit", + "icon": "$(refresh)" + }, { "command": "codev.helloWorld", "title": "Codev: Show Connection State" @@ -868,6 +873,11 @@ "when": "view == codev.tower", "group": "navigation@1" }, + { + "command": "codev.cockpit.refresh", + "when": "view == codev.cockpit", + "group": "navigation@1" + }, { "command": "codev.refreshOverview", "when": "view == codev.agents", @@ -1131,6 +1141,11 @@ "id": "codev", "title": "Codev", "icon": "icons/codev.svg" + }, + { + "id": "codev-cockpit", + "title": "Codev Cockpit", + "icon": "icons/codev-cockpit.svg" } ], "secondarySidebar": [ @@ -1163,6 +1178,9 @@ ], "codev-tower": [ { "id": "codev.tower", "name": "Codev Tower" } + ], + "codev-cockpit": [ + { "id": "codev.cockpit", "name": "Codev Cockpit" } ] }, "viewsWelcome": [ diff --git a/apps/vscode/src/__tests__/__snapshots__/contributes-cockpit.test.ts.snap b/apps/vscode/src/__tests__/__snapshots__/contributes-cockpit.test.ts.snap new file mode 100644 index 000000000..eb692fa2a --- /dev/null +++ b/apps/vscode/src/__tests__/__snapshots__/contributes-cockpit.test.ts.snap @@ -0,0 +1,559 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`existing containers, views and menus are unchanged > every menu entry outside the Cockpit 1`] = ` +{ + "commandPalette": [ + { + "command": "codev.tower.deactivateWorkspace", + "when": "false", + }, + { + "command": "codev.openBuilderFileLocation", + "when": "false", + }, + { + "command": "codev.tower.openWorkspace", + "when": "false", + }, + { + "command": "codev.openMarkdownPreview", + "when": "resourceLangId == markdown && resourcePath =~ /\\/codev\\/(plans|specs|reviews)\\//", + }, + { + "command": "codev.markdownPreview.increaseFontSize", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.markdownPreview.decreaseFontSize", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.markdownPreview.resetFontSize", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.markdownPreview.readingAids", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.agentsCycleGroupFromStage", + "when": "false", + }, + { + "command": "codev.agentsCycleGroupFromArea", + "when": "false", + }, + { + "command": "codev.agentsCycleGroupFromArchitect", + "when": "false", + }, + { + "command": "codev.forwardSelectionToBuilder", + "when": "false", + }, + { + "command": "codev.commentSelectionForBuilder", + "when": "false", + }, + { + "command": "codev.diffCodelensUseForward", + "when": "false", + }, + { + "command": "codev.diffCodelensUseComment", + "when": "false", + }, + { + "command": "codev.submitBuilderComment", + "when": "false", + }, + { + "command": "codev.forwardBuilderComment", + "when": "false", + }, + { + "command": "codev.cancelBuilderComment", + "when": "false", + }, + { + "command": "codev.deleteBuilderComment", + "when": "false", + }, + { + "command": "codev.startEditBuilderComment", + "when": "false", + }, + { + "command": "codev.saveEditBuilderComment", + "when": "false", + }, + { + "command": "codev.cancelEditBuilderComment", + "when": "false", + }, + { + "command": "codev.openBuilderById", + "when": "false", + }, + { + "command": "codev.openBuilderRow", + "when": "false", + }, + { + "command": "codev.viewBacklogIssue", + "when": "false", + }, + { + "command": "codev.referenceIssueInArchitect", + "when": "false", + }, + { + "command": "codev.referencePRInArchitect", + "when": "false", + }, + { + "command": "codev.removeArchitect", + "when": "false", + }, + { + "command": "codev.openBacklogIssue", + "when": "false", + }, + { + "command": "codev.copyBacklogIssueNumber", + "when": "false", + }, + { + "command": "codev.openBuilderFileDiff", + "when": "false", + }, + { + "command": "codev.viewSpecFile", + "when": "false", + }, + { + "command": "codev.viewPlanFile", + "when": "false", + }, + { + "command": "codev.viewReviewFile", + "when": "false", + }, + { + "command": "codev.addReviewComment", + "when": "editorLangId == 'markdown'", + }, + { + "command": "codev.submitReviewComment", + "when": "false", + }, + { + "command": "codev.deleteReviewComment", + "when": "false", + }, + { + "command": "codev.runWorkspaceDev", + "when": "codev.hasDevCommand", + }, + { + "command": "codev.stopWorkspaceDev", + "when": "codev.hasDevCommand", + }, + { + "command": "codev.runWorktreeDev", + "when": "false", + }, + { + "command": "codev.stopWorktreeDev", + "when": "false", + }, + { + "command": "codev.dev.stop", + "when": "codev.devRunning", + }, + { + "command": "codev.dev.restart", + "when": "codev.devRunning", + }, + { + "command": "codev.dev.switchTarget", + "when": "codev.hasDevCommand", + }, + ], + "comments/comment/context": [ + { + "command": "codev.saveEditReviewComment", + "group": "inline@2", + "when": "commentController == codev-review", + }, + { + "command": "codev.cancelEditReviewComment", + "group": "inline@1", + "when": "commentController == codev-review", + }, + { + "command": "codev.saveEditBuilderComment", + "group": "inline@2", + "when": "commentController == codev-builder-review", + }, + { + "command": "codev.cancelEditBuilderComment", + "group": "inline@1", + "when": "commentController == codev-builder-review", + }, + ], + "comments/comment/title": [ + { + "command": "codev.startEditReviewComment", + "group": "group@1", + "when": "commentController == codev-review && comment == inline-review", + }, + { + "command": "codev.startEditBuilderComment", + "group": "group@1", + "when": "commentController == codev-builder-review && comment == pending-builder-comment", + }, + ], + "comments/commentThread/context": [ + { + "command": "codev.submitReviewComment", + "group": "inline", + "when": "commentController == codev-review && commentThreadIsEmpty", + }, + { + "command": "codev.submitBuilderComment", + "group": "inline@1", + "when": "commentController == codev-builder-review && commentThreadIsEmpty && codev.diffCodelensMode == 'comment'", + }, + { + "command": "codev.forwardBuilderComment", + "group": "inline@1", + "when": "commentController == codev-builder-review && commentThreadIsEmpty && codev.diffCodelensMode != 'comment'", + }, + { + "command": "codev.cancelBuilderComment", + "group": "inline@2", + "when": "commentController == codev-builder-review && commentThreadIsEmpty", + }, + ], + "comments/commentThread/title": [ + { + "command": "codev.deleteReviewComment", + "group": "inline@1", + "when": "commentController == codev-review && commentThread == inline-review", + }, + { + "command": "codev.deleteBuilderComment", + "group": "inline@1", + "when": "commentController == codev-builder-review && commentThread == pending-builder-comment", + }, + ], + "editor/context": [ + { + "command": "codev.commentSelectionForBuilder", + "group": "codev@1", + "when": "codev.activeEditorIsBuilderFile", + }, + { + "command": "codev.forwardSelectionToBuilder", + "group": "codev@2", + "when": "codev.activeEditorIsBuilderFile", + }, + ], + "editor/title": [ + { + "command": "codev.openMarkdownPreview", + "group": "navigation", + "when": "resourceLangId == markdown && resourcePath =~ /\\/codev\\/(plans|specs|reviews)\\//", + }, + { + "command": "codev.markdownPreview.decreaseFontSize", + "group": "navigation@1", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.markdownPreview.increaseFontSize", + "group": "navigation@2", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.markdownPreview.resetFontSize", + "group": "1_run", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.markdownPreview.readingAids", + "group": "1_run", + "when": "activeCustomEditorId == codev.markdownPreview", + }, + { + "command": "codev.diffCodelensUseForward", + "group": "navigation", + "when": "codev.activeEditorIsBuilderFile && codev.diffCodelensMode == 'comment'", + }, + { + "command": "codev.diffCodelensUseComment", + "group": "navigation", + "when": "codev.activeEditorIsBuilderFile && codev.diffCodelensMode == 'forward'", + }, + ], + "view/item/context": [ + { + "command": "codev.tower.openWorkspace", + "group": "inline@1", + "when": "view == codev.tower && viewItem =~ /^tower-workspace-(active|dormant)$/", + }, + { + "command": "codev.tower.deactivateWorkspace", + "group": "inline@2", + "when": "view == codev.tower && viewItem == tower-workspace-active", + }, + { + "command": "codev.recheckCli", + "group": "inline@1", + "when": "view == codev.status && viewItem =~ /^codev-cli-(missing|outdated)$/", + }, + { + "command": "codev.removeArchitect", + "group": "1_primary@1", + "when": "view == codev.workspace && viewItem == workspace-architect-sibling", + }, + { + "command": "codev.addArchitect", + "group": "inline@1", + "when": "view == codev.workspace && viewItem == workspace-architects-root", + }, + { + "command": "codev.approveGate", + "group": "inline@1", + "when": "view == codev.agents && viewItem =~ /^blocked-builder-/", + }, + { + "command": "codev.openBuilderById", + "group": "1_primary@1", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + }, + { + "command": "codev.approveGate", + "group": "1_primary@2", + "when": "view == codev.agents && viewItem =~ /^blocked-builder-/", + }, + { + "command": "codev.viewSpecFile", + "group": "1_primary@3", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir)(-review)?$/", + }, + { + "command": "codev.viewPlanFile", + "group": "1_primary@4", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir|pir)(-review)?$/", + }, + { + "command": "codev.viewReviewFile", + "group": "1_primary@5", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-((spir|aspir|air)(-review)?|pir-review)$/", + }, + { + "command": "codev.viewDiff", + "group": "2_worktree@0", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + }, + { + "command": "codev.openWorktreeWindow", + "group": "2_worktree@1", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + }, + { + "command": "codev.openWorktreeFolder", + "group": "2_worktree@2", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + }, + { + "command": "codev.runWorktreeSetup", + "group": "3_dev@1", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + }, + { + "command": "codev.runWorktreeDev", + "group": "3_dev@2", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/ && codev.hasDevCommand", + }, + { + "command": "codev.stopWorktreeDev", + "group": "3_dev@3", + "when": "view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/ && codev.hasDevCommand", + }, + { + "command": "codev.runWorkspaceDev", + "group": "1_primary@1", + "when": "view == codev.workspace && viewItem == workspace-dev-start", + }, + { + "command": "codev.stopWorkspaceDev", + "group": "1_primary@1", + "when": "view == codev.workspace && viewItem == workspace-dev-stop", + }, + { + "command": "codev.referenceIssueInArchitect", + "group": "inline@1", + "when": "view == codev.backlog && viewItem == backlog-item", + }, + { + "command": "codev.referencePRInArchitect", + "group": "inline@1", + "when": "view == codev.pullRequests && viewItem == pull-request", + }, + { + "command": "codev.viewBacklogIssue", + "group": "1_primary@1", + "when": "view == codev.backlog && viewItem == backlog-item", + }, + { + "command": "codev.spawnBuilder", + "group": "1_primary@2", + "when": "view == codev.backlog && viewItem == backlog-item", + }, + { + "command": "codev.openBacklogIssue", + "group": "1_primary@3", + "when": "view == codev.backlog && viewItem == backlog-item", + }, + { + "command": "codev.copyBacklogIssueNumber", + "group": "1_primary@4", + "when": "view == codev.backlog && viewItem == backlog-item", + }, + ], + "view/title": [ + { + "command": "codev.tower.refresh", + "group": "navigation@1", + "when": "view == codev.tower", + }, + { + "command": "codev.refreshOverview", + "group": "navigation@2", + "when": "view == codev.agents", + }, + { + "command": "codev.disableBuildersAutoCollapse", + "group": "navigation@3", + "when": "view == codev.agents && codev.buildersAutoCollapse", + }, + { + "command": "codev.enableBuildersAutoCollapse", + "group": "navigation@3", + "when": "view == codev.agents && !codev.buildersAutoCollapse", + }, + { + "command": "codev.disableBuildersFileTreeMode", + "group": "navigation@4", + "when": "view == codev.agents && codev.buildersFileViewAsTree", + }, + { + "command": "codev.enableBuildersFileTreeMode", + "group": "navigation@4", + "when": "view == codev.agents && !codev.buildersFileViewAsTree", + }, + { + "command": "codev.agentsCycleGroupFromStage", + "group": "navigation@1", + "when": "view == codev.agents && (!codev.buildersGroupBy || codev.buildersGroupBy == 'stage')", + }, + { + "command": "codev.agentsCycleGroupFromArea", + "group": "navigation@1", + "when": "view == codev.agents && codev.buildersGroupBy == 'area'", + }, + { + "command": "codev.agentsCycleGroupFromArchitect", + "group": "navigation@1", + "when": "view == codev.agents && codev.buildersGroupBy == 'architect'", + }, + { + "command": "codev.refreshOverview", + "group": "navigation", + "when": "view == codev.pullRequests", + }, + { + "command": "codev.openBacklogSearch", + "group": "navigation@0", + "when": "view == codev.backlog", + }, + { + "command": "codev.refreshOverview", + "group": "navigation", + "when": "view == codev.backlog", + }, + { + "command": "codev.showBacklogAll", + "group": "navigation", + "when": "view == codev.backlog && !codev.backlogShowAll", + }, + { + "command": "codev.showBacklogMineOnly", + "group": "navigation", + "when": "view == codev.backlog && codev.backlogShowAll", + }, + { + "command": "codev.refreshOverview", + "group": "navigation", + "when": "view == codev.recentlyClosed", + }, + { + "command": "codev.refreshTeam", + "group": "navigation", + "when": "view == codev.team", + }, + { + "command": "codev.reconnect", + "group": "navigation", + "when": "view == codev.status", + }, + ], +} +`; + +exports[`existing containers, views and menus are unchanged > their views 1`] = ` +[ + { + "id": "codev.workspace", + "name": "Workspace", + "when": "codev.hasWorkspace", + }, + { + "id": "codev.agents", + "name": "Agents", + "when": "!codev.isBuilderWorktree", + }, + { + "id": "codev.backlog", + "name": "Backlog", + "when": "codev.hasWorkspace", + }, + { + "id": "codev.pullRequests", + "name": "Pull Requests", + "visibility": "collapsed", + "when": "codev.hasWorkspace", + }, + { + "id": "codev.recentlyClosed", + "name": "Recently Closed", + "visibility": "collapsed", + "when": "codev.hasWorkspace", + }, + { + "id": "codev.team", + "name": "Team", + "visibility": "collapsed", + "when": "codev.teamEnabled && codev.hasWorkspace", + }, + { + "id": "codev.status", + "name": "Status", + "visibility": "collapsed", + "when": "codev.hasWorkspace || codev.ideMode", + }, +] +`; diff --git a/apps/vscode/src/__tests__/architect-tree.test.ts b/apps/vscode/src/__tests__/architect-tree.test.ts index 2b0b46bf1..4690fb854 100644 --- a/apps/vscode/src/__tests__/architect-tree.test.ts +++ b/apps/vscode/src/__tests__/architect-tree.test.ts @@ -539,9 +539,9 @@ describe('ArchitectTreeBuilder: navigate mode (another workspace\'s rows)', () = }); }); -describe('ArchitectTreeBuilder: attentionCounts', () => { +describe('ArchitectTreeBuilder: attention', () => { it('appends held and queued counts to builder-row descriptions only when on', async () => { - const on = await allRows(actTree(MANY, 'ws:/a|', { attentionCounts: true })); + const on = await allRows(actTree(MANY, 'ws:/a|', { attention: true })); expect(find(on, 'ws:/a|bugfix-12#0').description).toBe('2 held · 4 queued'); for (const id of ['ws:/a|spir-10#0', 'ws:/a|air-11#0', 'ws:/a|pir-13#0', 'ws:/a|aspir-14#0']) { expect(find(on, id).description).toBeUndefined(); @@ -550,7 +550,7 @@ describe('ArchitectTreeBuilder: attentionCounts', () => { expect(find(off, 'ws:/a|bugfix-12#0').description).toBeUndefined(); const remote = await allRows(new ArchitectTreeBuilder({ - mode: 'navigate', scope: 'ws:/b|', getData: () => MANY, target: () => TARGET, attentionCounts: true, + mode: 'navigate', scope: 'ws:/b|', getData: () => MANY, target: () => TARGET, attention: true, })); expect(find(remote, 'ws:/b|bugfix-12#0').description).toBe('2 held · 4 queued'); }); @@ -559,7 +559,7 @@ describe('ArchitectTreeBuilder: attentionCounts', () => { let data = overview( [builder({ id: 'q', spawnedByArchitect: 'main' })], [architect('main')], { queuedFeedback: { q: 1 } }, ); - const tree = actTree(data, '', { getData: () => data, attentionCounts: true } as Partial); + const tree = actTree(data, '', { getData: () => data, attention: true } as Partial); const row = async () => (await tree.getChildren(find(await tree.getChildren(), 'builder-group:main')))[0]; expect((await row()).description).toBe('1 queued'); data = overview( diff --git a/apps/vscode/src/__tests__/cockpit-icon.test.ts b/apps/vscode/src/__tests__/cockpit-icon.test.ts new file mode 100644 index 000000000..f38c5855e --- /dev/null +++ b/apps/vscode/src/__tests__/cockpit-icon.test.ts @@ -0,0 +1,41 @@ +/** + * Spec 1963: the Codev Cockpit's activity-bar icon is the Codev icon rotated 90° clockwise — the + * same path, wrapped in `rotate(90 400 400)`, not a redrawn shape. + */ + +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const ICONS = resolve(__dirname, '../../icons'); +const codev = readFileSync(resolve(ICONS, 'codev.svg'), 'utf8'); +const cockpit = readFileSync(resolve(ICONS, 'codev-cockpit.svg'), 'utf8'); + +/** The `` open tag. */ +function svgTag(svg: string): string { + const match = svg.match(/^]*>/); + if (!match) { throw new Error('no open tag'); } + return match[0]; +} + +/** Every `d` attribute in the file. */ +function paths(svg: string): string[] { + return [...svg.matchAll(/\bd="([^"]*)"/g)].map(m => m[1]); +} + +describe('icons/codev-cockpit.svg', () => { + it('has the same canvas as codev.svg', () => { + expect(svgTag(cockpit)).toBe(svgTag(codev)); + }); + + it('carries exactly codev.svg path, unchanged', () => { + expect(paths(codev)).toHaveLength(1); + expect(paths(cockpit)).toEqual(paths(codev)); + }); + + it('wraps that path, and only it, in a clockwise quarter turn about the centre', () => { + const pathElement = codev.match(/]*\/>/)?.[0]; + expect(pathElement).toBeDefined(); + expect(cockpit).toBe(`${svgTag(codev)}${pathElement}\n`); + }); +}); diff --git a/apps/vscode/src/__tests__/cockpit-provider.test.ts b/apps/vscode/src/__tests__/cockpit-provider.test.ts new file mode 100644 index 000000000..4dc5290c8 --- /dev/null +++ b/apps/vscode/src/__tests__/cockpit-provider.test.ts @@ -0,0 +1,809 @@ +/** + * Spec 1963 Phase 4: the Codev Cockpit's single hierarchy (`views/cockpit.ts`), + * Tower → workspaces → architects → builders → (this window's workspace only) changed files. + * + * Fake caches stand in for `ConnectionManager`, `TowerFleetCache` and `OverviewCache`; the row + * building underneath is the real `ArchitectTreeBuilder` and the real `TowerProvider` row code, so + * the comparisons below are against what the Agents and Tower views actually render. + * + * Mocks `vscode` per the established `__tests__` pattern (see architect-tree.test.ts). + */ + +import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'; +import type * as vscode from 'vscode'; +import type { ArchitectState, OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; +import type { TowerWorkspace } from '@cluesmith/codev-sdk/tower-client'; +import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; +import type { FleetEntry } from '../views/tower-cache.js'; +import type { BuilderFileChange } from '../views/builder-diff-cache.js'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const MISSING_WORKTREE = join(tmpdir(), 'codev-test-missing-worktree'); +const NOW = Date.parse('2026-11-24T12:00:00.000Z'); +const ago = (minutes: number) => new Date(NOW - minutes * 60_000).toISOString(); + +const configValues: Record = {}; + +vi.mock('vscode', () => { + class FakeEventEmitter { + private listeners: Array<(e: T) => void> = []; + readonly event = (listener: (e: T) => void): { dispose: () => void } => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter((l) => l !== listener); } }; + }; + fire = vi.fn((e: T) => { this.listeners.forEach((l) => l(e)); }); + dispose = vi.fn(); + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + resourceUri?: unknown; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { + static readonly Folder = new ThemeIcon('folder'); + constructor(public id: string, public color?: unknown) {} + } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter: FakeEventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + Uri: { from: (parts: unknown) => ({ ...(parts as object), toString: () => JSON.stringify(parts) }) }, + workspace: { + getConfiguration: () => ({ + get: (key: string, def: unknown) => (key in configValues ? configValues[key] : def), + }), + }, + }; +}); + +const { CockpitProvider, COCKPIT_IDS, cockpitScope } = await import('../views/cockpit.js'); +const { TowerProvider, OPEN_WORKSPACE_COMMAND } = await import('../views/tower.js'); +const { BuildersProvider } = await import('../views/builders.js'); +const { REMOTE_CONTEXT } = await import('../views/architect-tree.js'); +const { BuilderTreeItem, BuilderGroupTreeItem, IdleArchitectsGroupTreeItem } = await import('../views/builder-tree-item.js'); +const { BuilderFileTreeItem } = await import('../views/builder-file-tree-item.js'); +const { BuilderFolderTreeItem } = await import('../views/builder-folder-tree-item.js'); + +type Provider = InstanceType; +type Node = Parameters[0]; + +beforeAll(() => { vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(NOW); }); +afterAll(() => { vi.useRealTimers(); }); +afterEach(() => { for (const key of Object.keys(configValues)) { delete configValues[key]; } }); + +// ── Fixtures ────────────────────────────────────────────────────────────────── + +function builder(overrides: Partial): OverviewBuilder { + return { + id: 'pir-1', issueId: '1', issueTitle: 't', phase: 'implement', protocolPhase: 'implement', + mode: 'strict', gates: {}, worktreePath: MISSING_WORKTREE, roleId: null, protocol: 'pir', + planPhases: [], progress: 0, blocked: null, blockedGate: null, blockedSince: null, + startedAt: null, idleMs: 0, lastDataAt: null, spawnedByArchitect: null, + area: 'Uncategorized', prReady: false, + ...overrides, + } as OverviewBuilder; +} + +function servedState(state: string, since: string) { + return { state, since, source: 'harness', alive: state !== 'dead', activity: null, activityAt: since, backgroundWork: false }; +} + +function architect(name: string, state?: string, since = ago(7)): ArchitectState { + if (!state) { return { name, port: 0, pid: 0 } as ArchitectState; } + return { name, port: 0, pid: 0, terminalId: 't', lastDataAt: since, agentState: servedState(state, since) } as unknown as ArchitectState; +} + +function overview(builders: OverviewBuilder[], architects: ArchitectState[], extra: Partial = {}): OverviewData { + return { + builders, architects, backlog: [], pendingPRs: [], recentlyClosed: [], + heldCount: 0, mailboxEscalated: false, queuedFeedback: {}, + ...extra, + } as unknown as OverviewData; +} + +function mk(relPath: string): BuilderFileChange { + return { + change: { status: 'M', oldPath: null, path: relPath }, + plan: { resourcePath: relPath, left: { kind: 'base', path: relPath }, right: { kind: 'file', path: relPath } }, + } as BuilderFileChange; +} + +const DIFFS = { + getDiff: async (builderId: string) => { + const files: Record = { + 'spir-10': [mk('README.md'), mk('src/views/a.ts'), mk('src/views/b.ts')], + 'pir-1': [mk('src/only.ts')], + 'bugfix-12': [mk('packages/x/y.ts')], + }; + return { baseRef: 'main', files: files[builderId] ?? [] }; + }, +} as never; + +/** + * N>1: a gated builder of `main`, a null-owner builder (folds into `main`), a sibling `web` with a + * held + queued builder and a silent one, a builder of a non-live architect `ghost`, and two idle + * siblings (`demos`, `reviewer`) that roll up into *Idle Architects*. + */ +const MANY = overview( + [ + builder({ id: 'spir-10', issueId: '10', issueTitle: 'gated', protocol: 'spir', protocolPhase: 'plan', + spawnedByArchitect: 'main', blocked: 'plan review', blockedGate: 'plan-approval', blockedSince: ago(120) }), + builder({ id: 'air-11', issueId: '11', issueTitle: 'orphan', protocol: 'air', spawnedByArchitect: null, + agentState: servedState('idle', ago(30)) as never }), + builder({ id: 'bugfix-12', issueId: '12', issueTitle: 'busy', protocol: 'bugfix', protocolPhase: 'pr', + spawnedByArchitect: 'web', heldCount: 2 }), + builder({ id: 'pir-13', issueId: '13', issueTitle: 'asks', protocol: 'pir', spawnedByArchitect: 'ghost', + worktreePath: '', agentState: servedState('needs-input', ago(5)) as never }), + builder({ id: 'aspir-14', issueId: '14', issueTitle: 'quiet', protocol: 'aspir', spawnedByArchitect: 'web', + lastDataAt: ago(600) }), + ], + [architect('main'), architect('web'), architect('demos'), architect('reviewer')], + { heldCount: 3, queuedFeedback: { 'bugfix-12': 4 } }, +); +const ONE = overview([builder({ id: 'pir-1', issueTitle: 'solo', spawnedByArchitect: 'main' })], [architect('main'), architect('reviewer')]); +const NONE = overview([], [architect('main')]); +const QUIET = overview([], [architect('main')]); + +function wsRow(path: string, name: string, active: boolean): TowerWorkspace { + return { path, name, active, proxyUrl: `http://localhost/${name}`, terminals: active ? 1 : 0 }; +} + +function entry(ws: TowerWorkspace, data: OverviewData | null): FleetEntry { + return { workspace: ws, attention: deriveAttention(data), overview: data }; +} + +const HERE = '/work/codev'; +const OTHER = '/work/market'; + +type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting'; + +interface WorldOptions { + fleet?: FleetEntry[]; + loaded?: boolean; + here?: OverviewData | null; + windowPath?: string | null; + state?: ConnectionState; + worktreeWindow?: boolean; + connects?: boolean; +} + +/** The mutable state the fakes read, and the events the Cockpit subscribes to. */ +interface World { + fleet: FleetEntry[]; + loaded: boolean; + here: OverviewData | null; + windowPath: string | null; + state: ConnectionState; + fireFleet(): void; + fireOverview(): void; + setState(state: ConnectionState): void; + provider: Provider; +} + +/** A Cockpit over fake caches whose state a test can change. */ +function world(opts: WorldOptions = {}): World { + const listeners = { fleet: [] as Array<() => void>, overview: [] as Array<() => void>, state: [] as Array<(s: string) => void> }; + const sub = (list: T[], l: T) => { list.push(l); return { dispose() { list.splice(list.indexOf(l), 1); } }; }; + const w: World = { + fleet: opts.fleet ?? [], + loaded: opts.loaded ?? true, + here: opts.here === undefined ? null : opts.here, + windowPath: opts.windowPath === undefined ? HERE : opts.windowPath, + state: opts.state ?? 'connected', + fireFleet: () => listeners.fleet.forEach(l => l()), + fireOverview: () => listeners.overview.forEach(l => l()), + setState: (s: ConnectionState) => { w.state = s; listeners.state.forEach(l => l(s)); }, + provider: undefined as unknown as Provider, + }; + w.provider = new CockpitProvider({ + connectionManager: { + getState: () => w.state, + getWorkspacePath: () => w.windowPath, + onStateChange: (l: (s: string) => void) => sub(listeners.state, l), + } as never, + towerCache: { + getFleet: () => w.fleet, + isLoaded: () => w.loaded, + getOverview: (path: string) => w.fleet.find(e => e.workspace.path === path)?.overview ?? null, + onDidChange: (l: () => void) => sub(listeners.fleet, l), + } as never, + overviewCache: { + getData: () => w.here, + onDidChange: (l: () => void) => sub(listeners.overview, l), + } as never, + diffCache: DIFFS, + builderWorktreeWindow: opts.worktreeWindow ?? false, + connects: opts.connects ?? true, + }); + return w; +} + +// ── Walk helpers ────────────────────────────────────────────────────────────── + +const item = (p: Provider, n: Node) => p.getTreeItem(n); +const labelOf = (p: Provider, n: Node) => String(item(p, n).label); + +async function towerRows(p: Provider): Promise { + const [root] = await p.getChildren(); + return p.getChildren(root); +} + +/** The workspace node with this label, among the Tower root's (and Dormant's) children. */ +async function workspaceNode(p: Provider, label: string): Promise { + for (const n of await towerRows(p)) { + if (labelOf(p, n) === label) { return n; } + if (item(p, n).id === COCKPIT_IDS.dormant) { + const inside = (await p.getChildren(n)).find(d => labelOf(p, d) === label); + if (inside) { return inside; } + } + } + throw new Error(`no workspace row '${label}'`); +} + +/** Every row under `node`, depth-first, expanding everything with a chevron. */ +async function subtree(p: Provider, node: Node): Promise> { + const rows: Array<{ node: Node; depth: number }> = []; + const visit = async (n: Node, depth: number): Promise => { + for (const child of await p.getChildren(n)) { + rows.push({ node: child, depth }); + if (item(p, child).collapsibleState) { await visit(child, depth + 1); } + } + }; + await visit(node, 0); + return rows; +} + +/** The whole tree, depth-first, as items. */ +async function wholeTree(p: Provider): Promise { + const [root] = await p.getChildren(); + return [item(p, root), ...(await subtree(p, root)).map(r => item(p, r.node))]; +} + +/** + * What VS Code's `TreeView.reveal` does with a provider: walk `getParent` to the root, then + * descend from the root matching each ancestor among its parent's children by id. Returns the id + * path, or throws where the chain breaks. + */ +async function revealPath(p: Provider, element: Node): Promise { + const chain: Node[] = []; + let current: Node = element; + for (;;) { + const parent = await p.getParent(current); + if (!parent) { break; } + chain.unshift(parent); + current = parent; + } + const path: string[] = []; + let level = await p.getChildren(); + for (const node of [...chain, element]) { + const id = item(p, node).id; + const match = level.find(n => item(p, n).id === id); + if (!id || !match) { + throw new Error(`reveal: '${id}' is not among the children of '${path.at(-1) ?? 'root'}' (${level.map(n => item(p, n).id).join(', ')})`); + } + path.push(id); + level = await p.getChildren(match); + } + return path; +} + +function stripScope(id: string | undefined, scope: string): string | undefined { + if (id === undefined) { return undefined; } + expect(id.startsWith(scope)).toBe(true); + return id.slice(scope.length); +} + +/** A row's rendered shape, minus the description (the Cockpit adds attention counts there). */ +function shape(row: vscode.TreeItem, scope: string) { + const command = row.command as { command: string; arguments?: unknown[] } | undefined; + return { + id: stripScope(row.id, scope), + label: row.label, + state: row.collapsibleState, + icon: row.iconPath, + tooltip: row.tooltip, + command: command?.command, + commandArgs: command?.arguments?.map(a => (a === row ? '' : a)), + }; +} + +// ── Tower root ──────────────────────────────────────────────────────────────── + +describe('Tower root and its state rows', () => { + it('is one expanded Tower row with a stable id', async () => { + const w = world({ fleet: [], loaded: true }); + const roots = await w.provider.getChildren(); + expect(roots).toHaveLength(1); + const root = item(w.provider, roots[0]); + expect(root).toMatchObject({ label: 'Tower', id: COCKPIT_IDS.tower, collapsibleState: 2 }); + expect(await w.provider.getParent(roots[0])).toBeUndefined(); + }); + + it('says Connecting… during the first attempt, and while connected before the fleet loads', async () => { + const w = world({ loaded: false, state: 'disconnected' }); + expect((await towerRows(w.provider)).map(n => labelOf(w.provider, n))).toEqual(['Connecting to Tower…']); + w.setState('connecting'); + expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Connecting to Tower…'); + w.setState('connected'); + expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Connecting to Tower…'); + }); + + it('says Not connected once an attempt fails, with Reconnect on click, and keeps saying it while retrying', async () => { + const w = world({ loaded: false, state: 'connecting' }); + w.setState('disconnected'); + const [row] = await towerRows(w.provider); + expect(item(w.provider, row)).toMatchObject({ + label: 'Not connected to Tower', + command: { command: 'codev.reconnect', title: 'Reconnect to Tower' }, + }); + w.setState('reconnecting'); + expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Not connected to Tower'); + // A backoff retry is another attempt, not the first: the row does not flip back. + w.setState('connecting'); + expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Not connected to Tower'); + expect(await w.provider.getParent(row)).toEqual({ kind: 'tower-root' }); + // Connected again, before the fleet's first load lands: connecting, not "not connected". + w.setState('connected'); + expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Connecting to Tower…'); + }); + + it('knows an attempt already failed when created while reconnecting', async () => { + const w = world({ loaded: false, state: 'reconnecting' }); + expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Not connected to Tower'); + }); + + it('says Not connected, with no dead Reconnect, in a window that never connects', async () => { + const w = world({ loaded: false, state: 'disconnected', connects: false }); + const row = item(w.provider, (await towerRows(w.provider))[0]); + expect(row.label).toBe('Not connected to Tower'); + expect(row.command).toBeUndefined(); + }); + + it('says No workspaces registered when Tower lists none', async () => { + const w = world({ fleet: [], loaded: true }); + expect((await towerRows(w.provider)).map(n => labelOf(w.provider, n))).toEqual(['No workspaces registered']); + }); + + it('lists workspaces, not a state row, once the fleet is loaded, even if the connection drops', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE)], here: ONE }); + w.setState('disconnected'); + expect((await towerRows(w.provider)).map(n => labelOf(w.provider, n))).toEqual(['codev']); + }); +}); + +// ── Workspaces ──────────────────────────────────────────────────────────────── + +const FLEET = [ + entry(wsRow('/work/zeta', 'zeta', true), QUIET), + entry(wsRow(OTHER, 'marketmaker', true), overview([], [], { heldCount: 2 })), + entry(wsRow(HERE, 'codev', true), ONE), + entry(wsRow('/work/old', 'old', false), null), + entry(wsRow('/work/older', 'older', false), null), + entry(wsRow('/elsewhere/codev', 'codev', true), QUIET), +]; + +describe('workspace rows', () => { + it('match the Tower view: order, labels, current marker, icons, descriptions, tooltips and the Dormant group', async () => { + const w = world({ fleet: FLEET, here: ONE }); + const tower = new TowerProvider( + { getFleet: () => FLEET, isLoaded: () => true, onDidChange: () => ({ dispose() {} }) } as never, + { getWorkspacePath: () => HERE } as never, + ); + const towerTop = tower.getChildren().map(n => tower.getTreeItem(n)); + const cockpitTop = (await towerRows(w.provider)).map(n => item(w.provider, n)); + const visible = (row: vscode.TreeItem) => ({ + label: row.label, description: row.description, icon: row.iconPath, tooltip: row.tooltip, contextValue: row.contextValue, + }); + expect(cockpitTop.map(visible)).toEqual(towerTop.map(visible)); + // Disambiguated labels, as in the Tower view, and the current marker on this window's own. + expect(cockpitTop.map(r => r.label)).toEqual(['marketmaker', 'elsewhere/codev', 'work/codev', 'zeta', 'Dormant (2)']); + expect(cockpitTop[2].description).toBe('current'); + + const towerDormant = tower.getChildren(tower.getChildren().at(-1)).map(n => tower.getTreeItem(n)); + const cockpitDormant = (await w.provider.getChildren((await towerRows(w.provider)).at(-1))).map(n => item(w.provider, n)); + expect(cockpitDormant.map(visible)).toEqual(towerDormant.map(visible)); + }); + + it('give the Tower root, workspace rows and the Dormant group stable ids', async () => { + const w = world({ fleet: FLEET, here: ONE }); + const top = (await towerRows(w.provider)).map(n => item(w.provider, n).id); + expect(top).toEqual([ + COCKPIT_IDS.workspace(OTHER), COCKPIT_IDS.workspace('/elsewhere/codev'), COCKPIT_IDS.workspace(HERE), + COCKPIT_IDS.workspace('/work/zeta'), COCKPIT_IDS.dormant, + ]); + expect(COCKPIT_IDS.workspace(HERE)).toBe('cockpit-ws:/work/codev'); + const dormant = await w.provider.getChildren((await towerRows(w.provider)).at(-1)); + expect(dormant.map(n => item(w.provider, n).id)).toEqual([COCKPIT_IDS.workspace('/work/old'), COCKPIT_IDS.workspace('/work/older')]); + }); + + it('start expanded for this window and for any that needs attention, collapsed when quiet', async () => { + const w = world({ fleet: FLEET, here: ONE }); + const state = async (label: string) => item(w.provider, await workspaceNode(w.provider, label)).collapsibleState; + expect(await state('work/codev')).toBe(2); + expect(await state('marketmaker')).toBe(2); + expect(await state('zeta')).toBe(1); + expect(await state('elsewhere/codev')).toBe(1); + }); + + it('toggle on click when active (no command), open on click when dormant', async () => { + const w = world({ fleet: FLEET, here: ONE }); + for (const label of ['work/codev', 'marketmaker', 'zeta']) { + expect(item(w.provider, await workspaceNode(w.provider, label)).command).toBeUndefined(); + } + const old = item(w.provider, await workspaceNode(w.provider, 'old')); + expect(old.collapsibleState).toBe(0); + expect(old.command).toEqual({ + command: OPEN_WORKSPACE_COMMAND, title: 'Open Workspace', + arguments: [{ path: '/work/old', active: false, name: 'old', isCurrent: false }], + }); + expect(await w.provider.getChildren(await workspaceNode(w.provider, 'old'))).toEqual([]); + }); + + it('show Loading… until a workspace overview is available', async () => { + const w = world({ + fleet: [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', true), null)], + here: null, + }); + for (const label of ['codev', 'marketmaker']) { + const ws = await workspaceNode(w.provider, label); + const children = await w.provider.getChildren(ws); + expect(children.map(n => labelOf(w.provider, n))).toEqual(['Loading…']); + expect(await w.provider.getParent(children[0])).toEqual(ws); + expect(item(w.provider, children[0]).collapsibleState).toBeUndefined(); + } + w.here = ONE; + w.fireOverview(); + const here = await w.provider.getChildren(await workspaceNode(w.provider, 'codev')); + expect(here.map(n => labelOf(w.provider, n))).toEqual(['MAIN (1)', 'REVIEWER (0)']); + }); +}); + +// ── This window's workspace ─────────────────────────────────────────────────── + +describe("this window's workspace: the Agents view's architect-axis rows", () => { + const scope = cockpitScope(HERE); + + for (const [name, data] of [['N=0', NONE], ['N=1', ONE], ['N>1', MANY]] as const) { + for (const asTree of [false, true]) { + it(`${name}, ${asTree ? 'tree' : 'flat'} files: same rows as Agents (architect axis), scoped ids`, async () => { + Object.assign(configValues, { buildersGroupBy: 'architect', buildersFileViewAsTree: asTree }); + const agents = new BuildersProvider({ getData: () => data, onDidChange: () => ({ dispose() {} }) } as never, DIFFS); + const agentRows: vscode.TreeItem[] = []; + const visitAgents = async (el?: vscode.TreeItem) => { + for (const child of await agents.getChildren(el)) { + agentRows.push(child); + if (child.collapsibleState) { await visitAgents(child); } + } + }; + await visitAgents(); + + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), data)], here: data }); + const cockpitRows = (await subtree(w.provider, await workspaceNode(w.provider, 'codev'))).map(r => item(w.provider, r.node)); + + expect(cockpitRows.map(r => shape(r, scope))).toEqual(agentRows.map(r => shape(r, ''))); + // Context values match, except that architect rows name main vs a sibling. + const contexts = (rows: vscode.TreeItem[]) => rows.map(r => r.contextValue); + expect(contexts(cockpitRows)).toEqual(agentRows.map((r) => { + if (!(r instanceof BuilderGroupTreeItem)) { return r.contextValue; } + return r.groupName === 'main' ? 'cockpit-architect-main' : 'cockpit-architect-sibling'; + })); + for (const row of cockpitRows) { + if (row.id) { expect(row.id.startsWith(scope)).toBe(true); } + } + }); + } + } + + it('folds a null owner into main, keeps a non-live owner, rolls up idle siblings and leaves a childless main a leaf', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), MANY)], here: MANY }); + const top = await w.provider.getChildren(await workspaceNode(w.provider, 'codev')); + expect(top.map(n => labelOf(w.provider, n))).toEqual(['MAIN (2)', 'GHOST (1)', 'WEB (2)', 'Idle Architects (2)']); + const mainRows = await w.provider.getChildren(top[0]); + expect(mainRows.map(n => (n as InstanceType).builderId)).toEqual(['spir-10', 'air-11']); + expect(item(w.provider, top[1]).command).toEqual({ command: 'codev.openArchitectTerminal', title: 'Open Architect Terminal', arguments: ['ghost'] }); + const idle = await w.provider.getChildren(top[3]); + expect(idle.map(n => labelOf(w.provider, n))).toEqual(['DEMOS (0)', 'REVIEWER (0)']); + + const w0 = world({ fleet: [entry(wsRow(HERE, 'codev', true), NONE)], here: NONE }); + const [main] = await w0.provider.getChildren(await workspaceNode(w0.provider, 'codev')); + expect(item(w0.provider, main)).toMatchObject({ label: 'MAIN (0)', collapsibleState: 0 }); + }); + + it('reads OverviewCache, not the lagging fleet copy', async () => { + const stale = overview([], [architect('main')]); + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), stale)], here: ONE }); + const top = await w.provider.getChildren(await workspaceNode(w.provider, 'codev')); + expect(top.map(n => labelOf(w.provider, n))).toEqual(['MAIN (1)', 'REVIEWER (0)']); + }); + + it('matches the window to its Tower row with isSameWorkspacePath (Windows drive-letter case)', async () => { + const platform = Object.getOwnPropertyDescriptor(process, 'platform')!; + Object.defineProperty(process, 'platform', { value: 'win32' }); + try { + const w = world({ fleet: [entry(wsRow('C:\\work\\codev', 'codev', true), QUIET)], here: ONE, windowPath: 'c:\\work\\codev' }); + const ws = item(w.provider, await workspaceNode(w.provider, 'codev')); + expect(ws.description).toBe('current'); + expect(w.provider.actingScope()).toBe(cockpitScope('C:\\work\\codev')); + const top = await w.provider.getChildren(await workspaceNode(w.provider, 'codev')); + expect(top.map(n => labelOf(w.provider, n))).toEqual(['MAIN (1)', 'REVIEWER (0)']); + } finally { + Object.defineProperty(process, 'platform', platform); + } + }); + + it('ignores codev.buildersGroupBy: stage and area render the same tree as architect', async () => { + const render = async (axis: string) => { + Object.assign(configValues, { buildersGroupBy: axis }); + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), MANY), entry(wsRow(OTHER, 'marketmaker', true), ONE)], here: MANY }); + return (await wholeTree(w.provider)).map(r => [r.id, r.label, r.contextValue, r.description]); + }; + const architect = await render('architect'); + expect(await render('stage')).toEqual(architect); + expect(await render('area')).toEqual(architect); + }); +}); + +// ── Other workspaces ────────────────────────────────────────────────────────── + +describe('other workspaces: state and navigate only', () => { + const target = { path: OTHER, active: true, name: 'marketmaker', isCurrent: false }; + + it('render the same architect / builder shape from the fleet overview, every row opening that workspace', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', true), MANY)], here: ONE }); + const rows = (await subtree(w.provider, await workspaceNode(w.provider, 'marketmaker'))).map(r => item(w.provider, r.node)); + expect(rows.map(r => r.label)).toEqual([ + 'MAIN (2)', expect.stringContaining('#10'), expect.stringContaining('#11'), 'GHOST (1)', expect.stringContaining('#13'), + 'WEB (2)', expect.stringContaining('#14'), expect.stringContaining('#12'), 'Idle Architects (2)', 'DEMOS (0)', 'REVIEWER (0)', + ]); + for (const row of rows) { + expect(Object.values(REMOTE_CONTEXT)).toContain(row.contextValue); + if (row instanceof IdleArchitectsGroupTreeItem) { expect(row.command).toBeUndefined(); continue; } + expect(row.command).toEqual({ command: OPEN_WORKSPACE_COMMAND, title: 'Open Workspace', arguments: [target] }); + expect(String(row.tooltip)).toContain('In workspace marketmaker. Click to open its window'); + } + // Builder rows are leaves: no changed-files expansion. + for (const row of rows.filter(r => r instanceof BuilderTreeItem)) { + expect(row.collapsibleState).toBe(0); + expect(await w.provider.getChildren(row)).toEqual([]); + } + expect(rows.some(r => r instanceof BuilderFileTreeItem || r instanceof BuilderFolderTreeItem)).toBe(false); + }); + + it('act on nothing here: the Cockpit acts only for its own workspace scope', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', true), MANY)], here: ONE }); + expect(w.provider.actingScope()).toBe(cockpitScope(HERE)); + expect(w.provider.revealTargetForAgent({ kind: 'builder', id: 'spir-10' })).toBeUndefined(); + }); + + it('keep two workspaces apart: shared architect names and a shared builder id never collide', async () => { + const shared = overview([builder({ id: 'pir-1', spawnedByArchitect: 'main' })], [architect('main'), architect('web')]); + const w = world({ + fleet: [entry(wsRow(HERE, 'codev', true), shared), entry(wsRow(OTHER, 'marketmaker', true), shared), entry(wsRow('/work/zeta', 'zeta', true), shared)], + here: shared, + }); + // Expand every builder row of this window (changed files included) and walk everything. + const ids = (await wholeTree(w.provider)).map(r => r.id).filter((id): id is string => id !== undefined); + expect(new Set(ids).size).toBe(ids.length); + expect(ids.filter(id => id.endsWith('builder-group:main'))).toHaveLength(3); + expect(ids.filter(id => /pir-1#\d+$/.test(id))).toHaveLength(3); + }); + + it('drop their row builders when the workspace leaves the fleet', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', true), MANY)], here: ONE }); + // The cache itself is the requirement (one builder per active workspace, pruned on leave). + const scopes = () => [...(w.provider as unknown as { trees: Map }).trees.keys()].sort(); + const [main] = await w.provider.getChildren(await workspaceNode(w.provider, 'marketmaker')); + await w.provider.getChildren(await workspaceNode(w.provider, 'codev')); + expect(scopes()).toEqual([cockpitScope(HERE), cockpitScope(OTHER)].sort()); + expect(await w.provider.getChildren(main)).toHaveLength(2); + w.fleet = [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', false), null)]; + w.fireFleet(); + await towerRows(w.provider); + expect(scopes()).toEqual([cockpitScope(HERE)]); + expect(await w.provider.getChildren(main)).toEqual([]); + expect(await w.provider.getParent(main)).toBeUndefined(); + }); +}); + +// ── Degraded windows ────────────────────────────────────────────────────────── + +describe('degraded windows', () => { + it("builder-worktree window: the parent is marked current but navigates, opening the parent's window", async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE)], here: ONE, worktreeWindow: true }); + const ws = await workspaceNode(w.provider, 'codev'); + expect(item(w.provider, ws).description).toBe('current'); + expect(item(w.provider, ws).collapsibleState).toBe(2); + const rows = (await subtree(w.provider, ws)).map(r => item(w.provider, r.node)); + expect(rows.length).toBeGreaterThan(0); + for (const row of rows) { + expect(Object.values(REMOTE_CONTEXT)).toContain(row.contextValue); + if (row.command) { + expect(row.command).toEqual({ + command: OPEN_WORKSPACE_COMMAND, title: 'Open Workspace', + arguments: [{ path: HERE, active: true, name: 'codev', isCurrent: false }], + }); + } + } + expect(w.provider.actingScope()).toBeUndefined(); + }); + + it('no-workspace window: nothing is current and every workspace navigates', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', true), MANY)], here: null, windowPath: null }); + const rows = await wholeTree(w.provider); + expect(rows.some(r => String(r.description).includes('current'))).toBe(false); + for (const row of rows.filter(r => r instanceof BuilderTreeItem || r instanceof BuilderGroupTreeItem)) { + expect(Object.values(REMOTE_CONTEXT)).toContain(row.contextValue); + } + expect(w.provider.actingScope()).toBeUndefined(); + }); +}); + +// ── Attention on rows ───────────────────────────────────────────────────────── + +describe('every attention signal lands on the row it concerns', () => { + const ATTENTION = overview( + [ + builder({ id: 'spir-20', issueId: '20', protocol: 'spir', spawnedByArchitect: 'main', + blocked: 'plan review', blockedGate: 'plan-approval', blockedSince: ago(9) }), + builder({ id: 'air-21', issueId: '21', protocol: 'air', spawnedByArchitect: 'main', + agentState: servedState('needs-input', ago(4)) as never }), + builder({ id: 'bugfix-22', issueId: '22', protocol: 'bugfix', spawnedByArchitect: 'web', + agentState: servedState('dead', ago(3)) as never, heldCount: 2 }), + builder({ id: 'pir-23', issueId: '23', protocol: 'pir', spawnedByArchitect: 'web' }), + ], + [architect('main', 'needs-input', ago(6)), architect('web', 'dead', ago(2)), architect('ops')], + { heldCount: 5, mailboxEscalated: true, queuedFeedback: { 'pir-23': 3 } }, + ); + + const cases: Array<[string, string, WorldOptions]> = [ + ['this window', 'codev', { fleet: [entry(wsRow(HERE, 'codev', true), ATTENTION)], here: ATTENTION }], + ['another workspace', 'marketmaker', { fleet: [entry(wsRow(HERE, 'codev', true), QUIET), entry(wsRow(OTHER, 'marketmaker', true), ATTENTION)], here: QUIET }], + ]; + for (const [where, label, setup] of cases) { + it(where, async () => { + const w = world(setup); + const ws = await workspaceNode(w.provider, label); + const rows = (await subtree(w.provider, ws)).map(r => item(w.provider, r.node)); + const row = (match: (r: vscode.TreeItem) => boolean) => { + const found = rows.find(match); + if (!found) { throw new Error('row not found'); } + return found; + }; + const builderRow = (id: string) => row(r => r instanceof BuilderTreeItem && r.builderId === id); + const architectRow = (name: string) => row(r => r instanceof BuilderGroupTreeItem && r.groupName === name); + const icon = (r: vscode.TreeItem) => r.iconPath as { id: string; color?: { id: string } }; + + // Pending gate: the blocked builder's gate glyph and wait time. + expect(icon(builderRow('spir-20')).id).toBe('checklist'); + expect(String(builderRow('spir-20').label)).toContain('9m'); + // Waits: the builder row's state glyph. + expect(icon(builderRow('air-21')).id).toBe('question'); + expect(icon(builderRow('bugfix-22')).id).toBe('debug-disconnect'); + // Architect at a prompt / agent dead: its own row's wait text and glyph. + expect(architectRow('main').description).toBe('needs input · 6m'); + expect(icon(architectRow('main'))).toEqual({ id: 'question', color: { id: 'list.warningForeground' } }); + expect(architectRow('web').description).toBe('agent exited · 2m'); + expect(icon(architectRow('web'))).toEqual({ id: 'debug-disconnect', color: { id: 'list.errorForeground' } }); + expect(architectRow('ops').description).toBeUndefined(); + // Held mail per builder, queued feedback per builder. + expect(builderRow('bugfix-22').description).toBe('2 held'); + expect(builderRow('pir-23').description).toBe('3 queued'); + // The workspace row keeps the Tower view's summary: its most urgent signal. + expect(item(w.provider, ws).description).toContain('plan review · 9m'); + }); + } + + it('unattributed held mail and escalation read on the workspace row', async () => { + const heldOnly = overview([], [architect('main')], { heldCount: 4, mailboxEscalated: true }); + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), QUIET), entry(wsRow(OTHER, 'marketmaker', true), heldOnly)], here: QUIET }); + expect(item(w.provider, await workspaceNode(w.provider, 'marketmaker')).description).toBe('4 held · escalated'); + }); +}); + +// ── getParent and reveal ────────────────────────────────────────────────────── + +describe('getParent reaches the Tower root from every row, and reveal finds the row', () => { + const fleet = [entry(wsRow(HERE, 'codev', true), MANY), entry(wsRow(OTHER, 'marketmaker', true), MANY), entry(wsRow('/work/old', 'old', false), null)]; + const scope = cockpitScope(HERE); + + for (const asTree of [false, true]) { + it(`a changed-file row of this window (${asTree ? 'tree' : 'flat'} mode), with nothing expanded yet`, async () => { + Object.assign(configValues, { buildersFileViewAsTree: asTree }); + const w = world({ fleet, here: MANY }); + // A fresh provider: VS Code has never asked for the workspace's children. + const file = await w.provider.findFileItem('spir-10', 'src/views/a.ts'); + expect(file).toBeDefined(); + const path = await revealPath(w.provider, file!); + expect(path[0]).toBe(COCKPIT_IDS.tower); + expect(path[1]).toBe(COCKPIT_IDS.workspace(HERE)); + expect(path[2]).toBe(`${scope}builder-group:main`); + expect(path[3]).toMatch(new RegExp(`^${scope.replace(/[|/]/g, '\\$&')}spir-10#\\d+$`)); + if (asTree) { expect(path[4]).toBe(`${scope}spir-10::folder::src/views`); } + expect(path.at(-1)).toBe(`${scope}spir-10::src/views/a.ts`); + }); + } + + it('a builder row and an architect row (agent-cycle targets), with nothing expanded yet', async () => { + const w = world({ fleet, here: MANY }); + const builderRow = w.provider.revealTargetForAgent({ kind: 'builder', id: 'bugfix-12' })!; + expect(await revealPath(w.provider, builderRow)).toEqual([ + COCKPIT_IDS.tower, COCKPIT_IDS.workspace(HERE), `${scope}builder-group:web`, builderRow.id, + ]); + const architectRow = w.provider.revealTargetForAgent({ kind: 'architect', name: 'web' })!; + expect(await revealPath(w.provider, architectRow)).toEqual([COCKPIT_IDS.tower, COCKPIT_IDS.workspace(HERE), `${scope}builder-group:web`]); + }); + + it('an idle sibling folded into Idle Architects', async () => { + const w = world({ fleet, here: MANY }); + const idle = w.provider.revealTargetForAgent({ kind: 'architect', name: 'demos' })!; + expect(await revealPath(w.provider, idle)).toEqual([ + COCKPIT_IDS.tower, COCKPIT_IDS.workspace(HERE), `${scope}idle-architects-group`, `${scope}builder-group:demos`, + ]); + }); + + it("another workspace's rows and a dormant workspace", async () => { + const w = world({ fleet, here: MANY }); + const rows = await subtree(w.provider, await workspaceNode(w.provider, 'marketmaker')); + for (const { node } of rows) { + const path = await revealPath(w.provider, node); + expect(path.slice(0, 2)).toEqual([COCKPIT_IDS.tower, COCKPIT_IDS.workspace(OTHER)]); + } + const old = await workspaceNode(w.provider, 'old'); + expect(await revealPath(w.provider, old)).toEqual([COCKPIT_IDS.tower, COCKPIT_IDS.dormant, COCKPIT_IDS.workspace('/work/old')]); + }); + + it('every rendered row walks to the Tower root', async () => { + const w = world({ fleet, here: MANY }); + const [root] = await w.provider.getChildren(); + for (const { node } of await subtree(w.provider, root)) { + if (item(w.provider, node).id === undefined) { continue; } // placeholders and messages are never revealed + expect((await revealPath(w.provider, node))[0]).toBe(COCKPIT_IDS.tower); + } + }); +}); + +// ── Re-render and the accordion ─────────────────────────────────────────────── + +describe('re-render signals and per-view accordion state', () => { + it('redraws on an overview change, a fleet change and a connection-state change', () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE)], here: ONE }); + const fired = vi.fn(); + w.provider.onDidChangeTreeData(fired); + w.fireOverview(); + w.fireFleet(); + w.setState('reconnecting'); + expect(fired).toHaveBeenCalledTimes(3); + }); + + it("collapseBuildersExcept re-versions only this window's builder rows and redraws", async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), MANY), entry(wsRow(OTHER, 'marketmaker', true), MANY)], here: MANY }); + const idsOf = async (label: string) => (await subtree(w.provider, await workspaceNode(w.provider, label))) + .map(r => item(w.provider, r.node)).filter(r => r instanceof BuilderTreeItem).map(r => r.id); + const before = await idsOf('codev'); + const otherBefore = await idsOf('marketmaker'); + const fired = vi.fn(); + w.provider.onDidChangeTreeData(fired); + const open = w.provider.revealTargetForAgent({ kind: 'builder', id: 'spir-10' }) as InstanceType; + w.provider.collapseBuildersExcept(open); + expect(fired).toHaveBeenCalledTimes(1); + const after = await idsOf('codev'); + expect(after.find(id => id!.includes('spir-10#'))).toBe(open.id); + expect(after.filter(id => !id!.includes('spir-10#')).every(id => !before.includes(id))).toBe(true); + expect(await idsOf('marketmaker')).toEqual(otherBefore); + }); + + it('a row with no workspace scope is a routing bug and throws', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), ONE)], here: ONE }); + const stray = new BuilderTreeItem('pir-1', 'x'); + await expect(w.provider.getChildren(stray)).rejects.toThrow(/carries no workspace scope/); + }); +}); diff --git a/apps/vscode/src/__tests__/cockpit-wiring.test.ts b/apps/vscode/src/__tests__/cockpit-wiring.test.ts new file mode 100644 index 000000000..95ad26672 --- /dev/null +++ b/apps/vscode/src/__tests__/cockpit-wiring.test.ts @@ -0,0 +1,445 @@ +/** + * Spec 1963 Phase 4: the tree behaviours the Agents view owned alone, generalised over the two + * views that render this window's agents (`views/agent-tree-hosts.ts`): row-click expand, the + * per-view accordion, the follow-reveals, `builder-active`, the shared badge and the shared + * settings. Also the periodic overview refresh's visibility gate (`views/overview-refresh-gate.ts`). + * + * The providers are the real `BuildersProvider` and `CockpitProvider`; only the tree views are + * fakes, recording what the hosts ask of them. `extension.ts` cannot be activated in a unit test, + * so its wiring is pinned at the source level (the convention workspace.test.ts uses). + */ + +import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'; +import type * as vscode from 'vscode'; +import type { ArchitectState, OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; +import type { TowerWorkspace } from '@cluesmith/codev-sdk/tower-client'; +import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; +import type { FleetEntry } from '../views/tower-cache.js'; +import type { BuilderFileChange } from '../views/builder-diff-cache.js'; +import { readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const MISSING_WORKTREE = join(tmpdir(), 'codev-test-missing-worktree'); +const NOW = Date.parse('2026-11-24T12:00:00.000Z'); +const configValues: Record = {}; + +vi.mock('vscode', () => { + class FakeEventEmitter { + private listeners: Array<(e: T) => void> = []; + readonly event = (listener: (e: T) => void): { dispose: () => void } => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter((l) => l !== listener); } }; + }; + fire = vi.fn((e: T) => { this.listeners.forEach((l) => l(e)); }); + dispose = vi.fn(); + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + resourceUri?: unknown; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { + static readonly Folder = new ThemeIcon('folder'); + constructor(public id: string, public color?: unknown) {} + } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter: FakeEventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + Uri: { from: (parts: unknown) => ({ ...(parts as object), toString: () => JSON.stringify(parts) }) }, + workspace: { + getConfiguration: () => ({ + get: (key: string, def: unknown) => (key in configValues ? configValues[key] : def), + }), + }, + }; +}); + +const { AgentTreeHosts } = await import('../views/agent-tree-hosts.js'); +const { OverviewRefreshGate } = await import('../views/overview-refresh-gate.js'); +const { CockpitProvider, cockpitScope } = await import('../views/cockpit.js'); +const { BuildersProvider } = await import('../views/builders.js'); +const { BuilderTreeItem } = await import('../views/builder-tree-item.js'); +const { workspaceActivityBadge } = await import('../mailbox-indicators.js'); + +beforeAll(() => { vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(NOW); }); +afterAll(() => { vi.useRealTimers(); }); +afterEach(() => { for (const key of Object.keys(configValues)) { delete configValues[key]; } }); + +// ── Fixtures ────────────────────────────────────────────────────────────────── + +function builder(id: string, owner: string): OverviewBuilder { + return { + id, issueId: id.split('-')[1], issueTitle: id, phase: 'implement', protocolPhase: 'implement', + mode: 'strict', gates: {}, worktreePath: MISSING_WORKTREE, roleId: null, protocol: 'pir', + planPhases: [], progress: 0, blocked: null, blockedGate: null, blockedSince: null, + startedAt: null, idleMs: 0, lastDataAt: null, spawnedByArchitect: owner, + area: 'Uncategorized', prReady: false, + } as unknown as OverviewBuilder; +} + +const DATA = { + builders: [builder('pir-1', 'main'), builder('pir-2', 'main')], + architects: [{ name: 'main', port: 0, pid: 0 } as ArchitectState], + backlog: [], pendingPRs: [], recentlyClosed: [], heldCount: 0, mailboxEscalated: false, queuedFeedback: {}, +} as unknown as OverviewData; + +const FILE: BuilderFileChange = { + change: { status: 'M', oldPath: null, path: 'src/a.ts' }, + plan: { resourcePath: 'src/a.ts', left: { kind: 'base', path: 'src/a.ts' }, right: { kind: 'file', path: 'src/a.ts' } }, +} as BuilderFileChange; +const DIFFS = { getDiff: async () => ({ baseRef: 'main', files: [FILE] }) } as never; + +const HERE = '/work/codev'; +const OTHER = '/work/market'; + +function wsRow(path: string, name: string): TowerWorkspace { + return { path, name, active: true, proxyUrl: '', terminals: 1 }; +} +function entry(ws: TowerWorkspace, data: OverviewData): FleetEntry { + return { workspace: ws, attention: deriveAttention(data), overview: data }; +} + +const noEvent = () => ({ dispose() {} }); + +/** A fake tree view: records reveals, lets a test fire expand / selection events. */ +function fakeView(visible = false) { + const expandListeners: Array<(e: { element: unknown }) => void> = []; + const selectListeners: Array<(e: { selection: readonly unknown[] }) => void> = []; + const visibilityListeners: Array<(e: unknown) => void> = []; + const view = { + visible, + badge: undefined as vscode.ViewBadge | undefined, + reveal: vi.fn(async (_element: unknown, _options?: unknown) => {}), + onDidExpandElement: (l: (e: { element: unknown }) => void) => { expandListeners.push(l); return { dispose() {} }; }, + onDidChangeSelection: (l: (e: { selection: readonly unknown[] }) => void) => { selectListeners.push(l); return { dispose() {} }; }, + onDidChangeVisibility: (l: (e: unknown) => void) => { visibilityListeners.push(l); return { dispose() {} }; }, + expand: (element: unknown) => expandListeners.forEach(l => l({ element })), + select: (element: unknown) => selectListeners.forEach(l => l({ selection: [element] })), + setVisible: (on: boolean) => { view.visible = on; visibilityListeners.forEach(l => l({ visible: on })); }, + }; + return view; +} + +/** The two real providers over one window, with fake views and the hosts between them. */ +function setup(opts: { worktreeWindow?: boolean; agentsVisible?: boolean; cockpitVisible?: boolean; accordion?: boolean } = {}) { + const overviewCache = { getData: () => DATA, onDidChange: noEvent }; + const agents = new BuildersProvider(overviewCache as never, DIFFS); + const fleet = [entry(wsRow(HERE, 'codev'), DATA), entry(wsRow(OTHER, 'marketmaker'), DATA)]; + const cockpit = new CockpitProvider({ + connectionManager: { getState: () => 'connected', getWorkspacePath: () => HERE, onStateChange: noEvent } as never, + towerCache: { + getFleet: () => fleet, isLoaded: () => true, onDidChange: noEvent, + getOverview: (path: string) => fleet.find(e => e.workspace.path === path)?.overview ?? null, + } as never, + overviewCache: overviewCache as never, + diffCache: DIFFS, + builderWorktreeWindow: opts.worktreeWindow ?? false, + connects: true, + }); + const agentsView = fakeView(opts.agentsVisible ?? false); + const cockpitView = fakeView(opts.cockpitVisible ?? false); + const hosts = new AgentTreeHosts([ + { view: agentsView, rows: agents, revealWhenNoneVisible: true }, + { view: cockpitView, rows: cockpit }, + ], opts.accordion ?? true); + hosts.wireAccordion(); + return { agents, cockpit, agentsView, cockpitView, hosts }; +} + +/** Every row under `node` in the Cockpit, depth-first. */ +async function cockpitRows(cockpit: InstanceType): Promise { + const rows: vscode.TreeItem[] = []; + const visit = async (node?: Parameters[0]): Promise => { + for (const child of await cockpit.getChildren(node)) { + const item = cockpit.getTreeItem(child); + rows.push(item); + if (item.collapsibleState) { await visit(child); } + } + }; + await visit(); + return rows; +} + +async function cockpitBuilderRow(cockpit: InstanceType, scope: string, id: string) { + const row = (await cockpitRows(cockpit)).find(r => r instanceof BuilderTreeItem && r.scope === scope && r.builderId === id); + if (!row) { throw new Error(`no ${scope}${id} row`); } + return row as InstanceType; +} + +const EXT_SRC = readFileSync(resolve(__dirname, '../extension.ts'), 'utf8'); + +// ── Row click ───────────────────────────────────────────────────────────────── + +describe('codev.openBuilderRow expands the row in its own view', () => { + it('an Agents row in the Agents view, a Cockpit row in the Cockpit', async () => { + const { agents, cockpit, agentsView, cockpitView, hosts } = setup(); + const agentsRow = agents.revealTargetForAgent({ kind: 'builder', id: 'pir-1' }) as InstanceType; + await hosts.expandRow(agentsRow); + expect(agentsView.reveal).toHaveBeenCalledWith(agentsRow, { expand: true, select: false, focus: false }); + expect(cockpitView.reveal).not.toHaveBeenCalled(); + + agentsView.reveal.mockClear(); + const cockpitRow = await cockpitBuilderRow(cockpit, cockpitScope(HERE), 'pir-1'); + await hosts.expandRow(cockpitRow); + expect(cockpitView.reveal).toHaveBeenCalledWith(cockpitRow, { expand: true, select: false, focus: false }); + expect(agentsView.reveal).not.toHaveBeenCalled(); + }); + + it("another workspace's row belongs to no acting host, so nothing expands", async () => { + const { cockpit, agentsView, cockpitView, hosts } = setup(); + const remote = await cockpitBuilderRow(cockpit, cockpitScope(OTHER), 'pir-1'); + await hosts.expandRow(remote); + expect(agentsView.reveal).not.toHaveBeenCalled(); + expect(cockpitView.reveal).not.toHaveBeenCalled(); + }); + + it('extension.ts routes the click through the hosts', () => { + expect(EXT_SRC).toMatch(/expandRow: \(\) => hosts\.expandRow\(item\)/); + }); +}); + +// ── Accordion ───────────────────────────────────────────────────────────────── + +describe('the accordion runs per view', () => { + it("expanding a Cockpit builder re-versions the Cockpit's rows only, and vice versa", async () => { + const { agents, cockpit, agentsView, cockpitView } = setup(); + const agentsCollapse = vi.spyOn(agents, 'collapseBuildersExcept'); + const cockpitCollapse = vi.spyOn(cockpit, 'collapseBuildersExcept'); + + const cockpitRow = await cockpitBuilderRow(cockpit, cockpitScope(HERE), 'pir-1'); + cockpitView.expand(cockpitRow); + expect(cockpitCollapse).toHaveBeenCalledWith(cockpitRow); + expect(agentsCollapse).not.toHaveBeenCalled(); + + // The same builder in the Agents view: its own gate has not seen it, so it collapses there. + const agentsRow = agents.revealTargetForAgent({ kind: 'builder', id: 'pir-1' }) as InstanceType; + agentsView.expand(agentsRow); + expect(agentsCollapse).toHaveBeenCalledWith(agentsRow); + expect(cockpitCollapse).toHaveBeenCalledTimes(1); + + // Each gate suppresses the re-fire of its own open row. + cockpitView.expand(cockpitRow); + agentsView.expand(agentsRow); + expect(cockpitCollapse).toHaveBeenCalledTimes(1); + expect(agentsCollapse).toHaveBeenCalledTimes(1); + }); + + it('a row expanded in the wrong view, or a remote row, is ignored', async () => { + const { agents, cockpit, agentsView, cockpitView } = setup(); + const cockpitCollapse = vi.spyOn(cockpit, 'collapseBuildersExcept'); + const agentsCollapse = vi.spyOn(agents, 'collapseBuildersExcept'); + agentsView.expand(await cockpitBuilderRow(cockpit, cockpitScope(HERE), 'pir-1')); + cockpitView.expand(await cockpitBuilderRow(cockpit, cockpitScope(OTHER), 'pir-1')); + expect(cockpitCollapse).not.toHaveBeenCalled(); + expect(agentsCollapse).not.toHaveBeenCalled(); + }); + + it('codev.buildersAutoCollapse re-gates both views', async () => { + const { agents, cockpit, agentsView, cockpitView, hosts } = setup(); + const agentsCollapse = vi.spyOn(agents, 'collapseBuildersExcept'); + const cockpitCollapse = vi.spyOn(cockpit, 'collapseBuildersExcept'); + const agentsRow = agents.revealTargetForAgent({ kind: 'builder', id: 'pir-1' }) as InstanceType; + const cockpitRow = await cockpitBuilderRow(cockpit, cockpitScope(HERE), 'pir-1'); + + hosts.setAccordionEnabled(false); + agentsView.expand(agentsRow); + cockpitView.expand(cockpitRow); + expect(agentsCollapse).not.toHaveBeenCalled(); + expect(cockpitCollapse).not.toHaveBeenCalled(); + + hosts.setAccordionEnabled(true); + agentsView.expand(agentsRow); + cockpitView.expand(cockpitRow); + expect(agentsCollapse).toHaveBeenCalledTimes(1); + expect(cockpitCollapse).toHaveBeenCalledTimes(1); + }); + + it('extension.ts wires the accordion and its setting through the hosts', () => { + expect(EXT_SRC).toMatch(/\.\.\.hosts\.wireAccordion\(\)/); + expect(EXT_SRC).toMatch(/affectsConfiguration\('codev\.buildersAutoCollapse'\)[\s\S]{0,120}hosts\.setAccordionEnabled\(on\);/); + expect(EXT_SRC).not.toMatch(/new AccordionGate\(/); + }); +}); + +// ── Shared settings ─────────────────────────────────────────────────────────── + +describe('codev.buildersFileViewAsTree redraws both views', () => { + it('refreshAll fires both providers', () => { + const { agents, cockpit, hosts } = setup(); + const agentsFired = vi.fn(); + const cockpitFired = vi.fn(); + agents.onDidChangeTreeData(agentsFired); + cockpit.onDidChangeTreeData(cockpitFired); + hosts.refreshAll(); + expect(agentsFired).toHaveBeenCalledTimes(1); + expect(cockpitFired).toHaveBeenCalledTimes(1); + }); + + it('extension.ts calls it from the setting listener', () => { + expect(EXT_SRC).toMatch(/affectsConfiguration\('codev\.buildersFileViewAsTree'\)[\s\S]{0,300}hosts\.refreshAll\(\);/); + }); +}); + +// ── Follow-reveals ──────────────────────────────────────────────────────────── + +describe('active-file and agent-cycle reveals follow the visible view', () => { + it('only the Cockpit visible: reveal there, not in the hidden Agents view', async () => { + const { agentsView, cockpitView, hosts } = setup({ cockpitVisible: true }); + await hosts.revealFile('pir-1', 'src/a.ts', () => true); + await hosts.revealAgent({ kind: 'builder', id: 'pir-2' }); + expect(agentsView.reveal).not.toHaveBeenCalled(); + const revealed = cockpitView.reveal.mock.calls.map(c => (c[0] as vscode.TreeItem).id); + expect(revealed).toEqual([`${cockpitScope(HERE)}pir-1::src/a.ts`, expect.stringMatching(/^ws:\/work\/codev\|pir-2#\d+$/)]); + }); + + it('both visible: reveal in both', async () => { + const { agentsView, cockpitView, hosts } = setup({ agentsVisible: true, cockpitVisible: true }); + await hosts.revealAgent({ kind: 'architect', name: 'main' }); + expect((agentsView.reveal.mock.calls[0][0] as vscode.TreeItem).id).toBe('builder-group:main'); + expect((cockpitView.reveal.mock.calls[0][0] as vscode.TreeItem).id).toBe(`${cockpitScope(HERE)}builder-group:main`); + }); + + it('none visible: the Agents view reveals, as before the Cockpit', async () => { + const { agentsView, cockpitView, hosts } = setup(); + await hosts.revealFile('pir-1', 'src/a.ts', () => true); + expect((agentsView.reveal.mock.calls[0][0] as vscode.TreeItem).id).toBe('pir-1::src/a.ts'); + expect(cockpitView.reveal).not.toHaveBeenCalled(); + }); + + it('a Cockpit with nothing acting here (worktree window) is skipped even when visible', async () => { + const { agentsView, cockpitView, hosts } = setup({ worktreeWindow: true, cockpitVisible: true }); + await hosts.revealAgent({ kind: 'builder', id: 'pir-1' }); + expect(cockpitView.reveal).not.toHaveBeenCalled(); + expect(agentsView.reveal).toHaveBeenCalledTimes(1); + }); + + it('a newer active editor stops a slow lookup from revealing', async () => { + const { cockpitView, hosts } = setup({ cockpitVisible: true }); + await hosts.revealFile('pir-1', 'src/a.ts', () => false); + expect(cockpitView.reveal).not.toHaveBeenCalled(); + }); + + it('extension.ts routes both reveals through the hosts', () => { + expect(EXT_SRC).toMatch(/await hosts\.revealFile\(entry\.builderId, entry\.relPath,/); + expect(EXT_SRC).toMatch(/await hosts\.revealAgent\(target\);/); + }); +}); + +// ── builder-active ──────────────────────────────────────────────────────────── + +describe('selection fires builder-active in either view, for acting rows only', () => { + it('Agents and Cockpit acting rows fire; another workspace row does not', async () => { + const { agents, cockpit, agentsView, cockpitView, hosts } = setup(); + const fired = vi.fn(); + hosts.wireSelection(fired); + agentsView.select(agents.revealTargetForAgent({ kind: 'builder', id: 'pir-1' })); + cockpitView.select(await cockpitBuilderRow(cockpit, cockpitScope(HERE), 'pir-2')); + cockpitView.select(await cockpitBuilderRow(cockpit, cockpitScope(OTHER), 'pir-1')); + cockpitView.select(cockpit.revealTargetForAgent({ kind: 'architect', name: 'main' })); + expect(fired.mock.calls).toEqual([['pir-1'], ['pir-2']]); + }); +}); + +// ── Badge ───────────────────────────────────────────────────────────────────── + +describe('the activity badge', () => { + const blocked = { ...DATA, builders: [{ ...builder('pir-9', 'main'), blocked: 'plan review', blockedGate: 'plan-approval' }] } as OverviewData; + + it('is the same value on both views', () => { + const { agentsView, cockpitView, hosts } = setup(); + const badge = workspaceActivityBadge(blocked, { connected: true, builderWorktreeWindow: false }); + expect(badge).toEqual({ value: 1, tooltip: '1 builder blocked at a human-approval gate' }); + hosts.setBadge(badge); + expect(agentsView.badge).toBe(badge); + expect(cockpitView.badge).toBe(badge); + hosts.setBadge(undefined); + expect(agentsView.badge).toBeUndefined(); + expect(cockpitView.badge).toBeUndefined(); + }); + + it('is suppressed when disconnected, with no data, and in a builder-worktree window', () => { + expect(workspaceActivityBadge(blocked, { connected: false, builderWorktreeWindow: false })).toBeUndefined(); + expect(workspaceActivityBadge(null, { connected: true, builderWorktreeWindow: false })).toBeUndefined(); + expect(workspaceActivityBadge(blocked, { connected: true, builderWorktreeWindow: true })).toBeUndefined(); + }); +}); + +// ── Periodic overview refresh ───────────────────────────────────────────────── + +describe('the periodic overview refresh counts the Cockpit', () => { + function gate(views: ReturnType[], seconds = 60) { + const onTick = vi.fn(); + const onResume = vi.fn(); + const g = new OverviewRefreshGate(views, () => seconds, onTick, onResume); + g.wire(); + return { g, onTick, onResume }; + } + + it('runs with only the Cockpit visible and stops when nothing is', () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'Date'] }); + try { + const agents = fakeView(false); + const lists = [fakeView(false), fakeView(false), fakeView(false)]; + const cockpit = fakeView(false); + const { g, onTick, onResume } = gate([agents, ...lists, cockpit]); + g.reconcile(); + expect(g.isRunning()).toBe(false); + + cockpit.setVisible(true); + expect(g.isRunning()).toBe(true); + expect(onResume).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(60_000); + expect(onTick).toHaveBeenCalledTimes(1); + + cockpit.setVisible(false); + expect(g.isRunning()).toBe(false); + vi.advanceTimersByTime(120_000); + expect(onTick).toHaveBeenCalledTimes(1); + } finally { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(NOW); + } + }); + + it('stays off at a 0 s cadence, and restarts at a new cadence', () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'Date'] }); + try { + const view = fakeView(true); + let seconds = 0; + const onTick = vi.fn(); + const g = new OverviewRefreshGate([view], () => seconds, onTick, () => {}); + g.reconcile(); + expect(g.isRunning()).toBe(false); + seconds = 60; + g.restart(); + expect(g.isRunning()).toBe(true); + // Changing the cadence while running replaces the 60 s timer with a 10 s one. + seconds = 10; + g.restart(); + vi.advanceTimersByTime(10_000); + expect(onTick).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(50_000); + expect(onTick).toHaveBeenCalledTimes(6); + g.dispose(); + expect(g.isRunning()).toBe(false); + } finally { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(NOW); + } + }); + + it('extension.ts gates on the four list views and the Cockpit', () => { + expect(EXT_SRC).toMatch(/new OverviewRefreshGate\(\s*\[buildersView, pullRequestsView, backlogView, recentlyClosedView, cockpitView\],/); + expect(EXT_SRC).toMatch(/\.\.\.overviewRefreshGate\.wire\(\)/); + }); +}); diff --git a/apps/vscode/src/__tests__/contributes-cockpit.test.ts b/apps/vscode/src/__tests__/contributes-cockpit.test.ts new file mode 100644 index 000000000..38e5ce0eb --- /dev/null +++ b/apps/vscode/src/__tests__/contributes-cockpit.test.ts @@ -0,0 +1,86 @@ +/** + * Spec 1963 Phase 4: the Codev Cockpit's contributions. The new activity-bar container sits + * directly after `codev`, its single tree view has no `when` (the button appears in every window + * the extension activates in), the icon file exists, and the refresh command has its title-bar + * entry. The existing `codev`, `codev-tower` and `codevPanel` entries are unchanged: their + * containers, views and menu entries are pinned to their pre-Cockpit text. + */ + +import { describe, it, expect } from 'vitest'; +import { existsSync, readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const ROOT = resolve(__dirname, '../..'); +const PKG = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8')); +const EXT_SRC = readFileSync(resolve(ROOT, 'src/extension.ts'), 'utf8'); + +interface Container { id: string; title: string; icon: string } +interface View { id: string; name: string; when?: string } +interface Menu { command: string; when?: string; group?: string } + +const containers = PKG.contributes.viewsContainers as Record; +const views = PKG.contributes.views as Record; +const menus = PKG.contributes.menus as Record; + +describe('Codev Cockpit container and view', () => { + it('registers the container directly after the Codev container in the activity bar', () => { + const ids = containers.activitybar.map(c => c.id); + expect(ids.indexOf('codev-cockpit')).toBe(ids.indexOf('codev') + 1); + expect(containers.activitybar.find(c => c.id === 'codev-cockpit')).toEqual({ + id: 'codev-cockpit', title: 'Codev Cockpit', icon: 'icons/codev-cockpit.svg', + }); + }); + + it('ships the icon file it names', () => { + expect(existsSync(resolve(ROOT, 'icons/codev-cockpit.svg'))).toBe(true); + }); + + it('holds one tree view, codev.cockpit, with no when clause', () => { + expect(views['codev-cockpit']).toEqual([{ id: 'codev.cockpit', name: 'Codev Cockpit' }]); + // The view lives only in its own container. + for (const [container, list] of Object.entries(views)) { + if (container === 'codev-cockpit') { continue; } + expect(list.some(v => v.id === 'codev.cockpit')).toBe(false); + } + }); + + it('declares the refresh command, with a title-bar entry scoped to the Cockpit', () => { + const commands = PKG.contributes.commands as Array<{ command: string; title: string; icon?: string }>; + expect(commands.find(c => c.command === 'codev.cockpit.refresh')).toEqual({ + command: 'codev.cockpit.refresh', title: 'Codev: Refresh Cockpit', icon: '$(refresh)', + }); + const entry = menus['view/title'].find(m => m.command === 'codev.cockpit.refresh'); + expect(entry).toEqual({ command: 'codev.cockpit.refresh', when: 'view == codev.cockpit', group: 'navigation@1' }); + }); + + it('creates the tree view and registers the refresh command in extension.ts', () => { + expect(EXT_SRC).toMatch(/createTreeView\(COCKPIT_VIEW_ID, \{ treeDataProvider: cockpitProvider \}\)/); + expect(EXT_SRC).toMatch(/reg\('codev\.cockpit\.refresh', \(\) => Promise\.all\(\[overviewCache\.refresh\(\), towerCache\.refresh\(\)\]\)\)/); + }); +}); + +/** + * The pre-Cockpit text of every contribution the Cockpit must not touch. Recorded from + * `package.json` at the Phase 3 commit (`git show d1714a740:apps/vscode/package.json`). + */ +describe('existing containers, views and menus are unchanged', () => { + it('the codev, codev-tower and codevPanel containers', () => { + expect(containers.activitybar.find(c => c.id === 'codev')).toEqual({ id: 'codev', title: 'Codev', icon: 'icons/codev.svg' }); + expect(containers.secondarySidebar).toEqual([{ id: 'codev-tower', title: 'Codev Tower', icon: 'icons/tower.svg' }]); + expect(containers.panel).toEqual([{ id: 'codevPanel', title: 'Codev', icon: 'icons/codev.svg' }]); + }); + + it('their views', () => { + expect(views.codev).toMatchSnapshot(); + expect(views['codev-tower']).toEqual([{ id: 'codev.tower', name: 'Codev Tower' }]); + expect(views.codevPanel).toEqual([{ id: 'codev.contextualPanel', name: 'Codev', type: 'webview' }]); + }); + + it('every menu entry outside the Cockpit', () => { + const notCockpit: Record = {}; + for (const [location, entries] of Object.entries(menus)) { + notCockpit[location] = entries.filter(m => !(m.when ?? '').includes('codev.cockpit') && !m.command.startsWith('codev.cockpit.')); + } + expect(notCockpit).toMatchSnapshot(); + }); +}); diff --git a/apps/vscode/src/__tests__/worktree-window-1809.test.ts b/apps/vscode/src/__tests__/worktree-window-1809.test.ts index 442b327a2..054b6baf5 100644 --- a/apps/vscode/src/__tests__/worktree-window-1809.test.ts +++ b/apps/vscode/src/__tests__/worktree-window-1809.test.ts @@ -25,6 +25,7 @@ vi.mock('vscode', () => ({ const { resolveWorkspaceDevTarget } = await import('../commands/dev-shared.js'); const { fireActivity, setActivityHooks, setActivityHooksSuppressed } = await import('../activity-hooks.js'); +const { workspaceActivityBadge } = await import('../mailbox-indicators.js'); describe('resolveWorkspaceDevTarget', () => { it('targets the builder for a worktree window root', () => { @@ -95,6 +96,19 @@ describe('parent-scoped surfaces in a builder-worktree window', () => { it('shows no parent builder counts in the status bar or the activity-bar badge', () => { expect(EXT_SRC).toMatch(/const updateStatusBarCounts = \(\) => \{[\s\S]*?if \(isBuilderWorktreeWindow\) \{ return; \}/); - expect(EXT_SRC).toMatch(/if \(isBuilderWorktreeWindow \|\| connectionManager\?\.getState\(\) !== 'connected' \|\| !data\) \{\s*buildersView\.badge = undefined;/); + // Spec 1963: the badge is computed once, with the worktree-window flag, and assigned to every + // view that renders this window's agents (the Agents view and the Cockpit). + expect(EXT_SRC).toMatch(/agentTreeHosts\?\.setBadge\(workspaceActivityBadge\(overviewCache\.getData\(\), \{\s*connected: connectionManager\?\.getState\(\) === 'connected',\s*builderWorktreeWindow: isBuilderWorktreeWindow,/); + expect(EXT_SRC).toMatch(/\{ view: buildersView, rows: buildersProvider, revealWhenNoneVisible: true \},\s*\{ view: cockpitView, rows: cockpitProvider \},/); + expect(EXT_SRC).not.toMatch(/(buildersView|cockpitView)\.badge = /); + }); + + it('suppresses the badge value itself in a worktree window, whatever the data', () => { + const data = { + builders: [{ id: 'b', blocked: 'plan review', lastDataAt: null }], + architects: [], heldCount: 2, mailboxEscalated: false, queuedFeedback: {}, + } as never; + expect(workspaceActivityBadge(data, { connected: true, builderWorktreeWindow: false })).toBeDefined(); + expect(workspaceActivityBadge(data, { connected: true, builderWorktreeWindow: true })).toBeUndefined(); }); }); diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index 60c0fb1d6..0b1520d99 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -36,7 +36,7 @@ import { listCronTasks } from './commands/cron.js'; import { addReviewComment } from './commands/review.js'; import { activateGateToasts } from './notifications/gate-toast.js'; import { activateMailboxEscalationToasts } from './notifications/mailbox-escalation-toast.js'; -import { composeStatusBarText, composeStatusBarTooltip, composeActivityBadge } from './mailbox-indicators.js'; +import { composeStatusBarText, composeStatusBarTooltip, workspaceActivityBadge } from './mailbox-indicators.js'; import { activateReviewDecorations } from './review-decorations.js'; import { activateReviewComments } from './comments/plan-review.js'; import { activateBuilderReviewComments } from './comments/builder-review.js'; @@ -63,7 +63,10 @@ import { computeBuildersToClose, roleIdsFromBuilders } from './prune-builder-ter import { buildBuilderPickRows } from './builder-pick-rows.js'; import { readBuildersFileViewAsTree } from './builders-config.js'; import { deriveAttention, isIdleWaiting } from '@cluesmith/codev-sdk/builder-helpers'; -import { BuildersProvider, AccordionGate, runBuilderRowClick, agentTargetIsFocused, agentCycleAttemptOrder, type AgentTarget } from './views/builders.js'; +import { BuildersProvider, runBuilderRowClick, agentTargetIsFocused, agentCycleAttemptOrder, type AgentTarget } from './views/builders.js'; +import { AgentTreeHosts } from './views/agent-tree-hosts.js'; +import { CockpitProvider, COCKPIT_VIEW_ID, type CockpitNode } from './views/cockpit.js'; +import { OverviewRefreshGate } from './views/overview-refresh-gate.js'; // Codev Tower (#1566): the cross-workspace navigation hub — its own activity-bar container. import { TowerFleetCache } from './views/tower-cache.js'; import { TowerProvider } from './views/tower.js'; @@ -552,31 +555,20 @@ export async function activate(context: vscode.ExtensionContext) { if (recentlyClosedView) { recentlyClosedView.title = withCount('Recently Closed', data?.recentlyClosed.length); } }; - // Activity-bar badge — paint the "needs me" count on the Codev icon. - // Combines both signals: blocked (formal gate) + idle-waiting (PTY - // silent past threshold). VSCode has no container-level badge API; - // per-view `TreeView.badge` bubbles up to the activity-bar icon - // when the sidebar is hidden, so badging `buildersView` is how - // we paint the icon. Badge only set when there's at least one - // item needing the user. + // Activity-bar badge — paint the "needs me" count on the Codev icon and, with + // the same value, on the Cockpit's (Spec 1963). Combines blocked (formal gate), + // idle-waiting (PTY silent past threshold), held mail and waiting architects. + // VSCode has no container-level badge API; per-view `TreeView.badge` bubbles up + // to the activity-bar icon when the sidebar is hidden, so badging the Agents and + // Cockpit views is how we paint the two icons. The count, and its suppression + // (disconnected, no data, builder-worktree window #1809), is computed once in + // the pure `workspaceActivityBadge` and assigned to every agent view. + let agentTreeHosts: AgentTreeHosts | undefined; const updateActivityBadge = () => { - if (!buildersView) { return; } - const data = overviewCache.getData(); - if (isBuilderWorktreeWindow || connectionManager?.getState() !== 'connected' || !data) { - buildersView.badge = undefined; - return; - } - const now = Date.now(); - const blockedCount = data.builders.filter(b => b.blocked).length; - const idleCount = data.builders.filter(b => isIdleWaiting(b, now)).length; - // Spec 1595: architects at a prompt or with their agent dead fold in by name. - const waitingArchitects = deriveAttention(data, now).architects.map(a => a.architect); - // Spec 1313 Phase 8: fold the workspace held-mail count into the badge so the - // activity-bar icon reflects it even when the sidebar is collapsed. Held is a - // count only (not a per-builder "needs me" gate); the tooltip disambiguates it - // from the blocked/idle signals. The fold + tooltip composition (and the - // undefined-when-empty clear) is pure + unit-tested in `composeActivityBadge`. - buildersView.badge = composeActivityBadge(blockedCount, idleCount, data.heldCount, waitingArchitects); + agentTreeHosts?.setBadge(workspaceActivityBadge(overviewCache.getData(), { + connected: connectionManager?.getState() === 'connected', + builderWorktreeWindow: isBuilderWorktreeWindow, + })); }; // Close builder/dev terminal tabs when their builder disappears from the @@ -631,17 +623,51 @@ export async function activate(context: vscode.ExtensionContext) { context.workspaceState.update('codev.buildersStageGroupExpansion', undefined); } + // The machine-wide fleet cache (#1566). Created here, ahead of the Tower view + // below, because the Cockpit reads it too: other workspaces' rows come from the + // overviews it already fetches (Spec 1963). + const towerCache = new TowerFleetCache(connectionManager); + context.subscriptions.push({ dispose: () => towerCache.dispose() }); + // List views use createTreeView so their title can carry a live item // count; the rest stay on registerTreeDataProvider. const buildersProvider = new BuildersProvider(overviewCache, builderDiffCache); buildersView = vscode.window.createTreeView('codev.agents', { treeDataProvider: buildersProvider }); - // Publish a builder-active event when a builder row is selected in the sidebar. + // The Codev Cockpit (Spec 1963): one tree, Tower → workspaces → architects → + // builders. This window's workspace acts (same rows as Agents, scoped ids); + // every other workspace navigates to its own window. + const cockpitProvider = new CockpitProvider({ + connectionManager, + towerCache, + overviewCache, + diffCache: builderDiffCache, + builderWorktreeWindow: isBuilderWorktreeWindow, + connects: policy.initializeConnection, + }); + const cockpitView: vscode.TreeView = vscode.window.createTreeView(COCKPIT_VIEW_ID, { treeDataProvider: cockpitProvider }); + // Builders accordion (#913), row-click expand, follow-reveals, the + // builder-active hook and the badge act on whichever of the two views a row + // belongs to. The accordion is toggled via the header button / + // `codev.buildersAutoCollapse`; expanding one builder auto-collapses the OTHER + // builder rows of the same view, so a reviewer can't have diffs from unrelated + // worktrees open at once. Group headers are left alone. + const readAccordion = () => + vscode.workspace.getConfiguration('codev').get('buildersAutoCollapse', true); + agentTreeHosts = new AgentTreeHosts([ + { view: buildersView, rows: buildersProvider, revealWhenNoneVisible: true }, + { view: cockpitView, rows: cockpitProvider }, + ], readAccordion()); + const hosts = agentTreeHosts; + // Publish a builder-active event when a builder row is selected in either view. // Builder tree items carry `builderId` (= OverviewBuilder.id); selecting a // builder's root node or a file row re-targets any configured hook. - context.subscriptions.push(buildersView.onDidChangeSelection((e) => { - const sel = e.selection[0] as { builderId?: string } | undefined; - if (sel?.builderId) { fireActivity(connectionManager?.getWorkspacePath() ?? null, 'builder-active', { builder: sel.builderId }); } - })); + context.subscriptions.push( + cockpitView, + cockpitProvider, + ...hosts.wireSelection((builderId) => { + fireActivity(connectionManager?.getWorkspacePath() ?? null, 'builder-active', { builder: builderId }); + }), + ); pullRequestsView = vscode.window.createTreeView('codev.pullRequests', { treeDataProvider: new PullRequestsProvider(overviewCache) }); const backlogProvider = new BacklogProvider(overviewCache, context.workspaceState); backlogView = vscode.window.createTreeView('codev.backlog', { treeDataProvider: backlogProvider }); @@ -741,26 +767,15 @@ export async function activate(context: vscode.ExtensionContext) { context.globalState.update(PANEL_REVEALED_KEY, true); } - // Builders accordion: expanding one builder auto-collapses the OTHER builder - // rows so a reviewer can't have diffs from unrelated worktrees open at once. - // It deliberately leaves group headers alone (#913) — `collapseBuildersExcept` - // only re-ids builder rows, never the group rows. Toggle via the header - // button / `codev.buildersAutoCollapse`. - const readAccordion = () => - vscode.workspace.getConfiguration('codev').get('buildersAutoCollapse', true); - const accordion = new AccordionGate(readAccordion()); + // Builders accordion, per view (see `agentTreeHosts` above). The context key + // drives the toggle buttons in both title bars. vscode.commands.executeCommand('setContext', 'codev.buildersAutoCollapse', readAccordion()); context.subscriptions.push( - buildersView.onDidExpandElement((e) => { - if (!(e.element instanceof BuilderTreeItem)) { return; } - if (accordion.shouldCollapseOthers(e.element.builderId)) { - buildersProvider.collapseBuildersExcept(e.element); - } - }), + ...hosts.wireAccordion(), vscode.workspace.onDidChangeConfiguration((e) => { if (!e.affectsConfiguration('codev.buildersAutoCollapse')) { return; } const on = readAccordion(); - accordion.setEnabled(on); + hosts.setAccordionEnabled(on); vscode.commands.executeCommand('setContext', 'codev.buildersAutoCollapse', on); }), ); @@ -795,16 +810,12 @@ export async function activate(context: vscode.ExtensionContext) { // hijacking the sidebar selection. (Checking "plain text tab" rather than // "diff tab" avoids TabInputTextMultiDiff, absent from stable @types/vscode.) if (isStandaloneTextTab(vscode.window.tabGroups.activeTabGroup?.activeTab?.input)) { return; } - const item = await buildersProvider.findFileItem(entry.builderId, entry.relPath); - if (!item) { return; } - // The active editor may have changed during the await (rapid navigation); - // don't let a slow lookup override a newer file's reveal. - if (vscode.window.activeTextEditor?.document.uri.fsPath !== fsPath) { return; } - try { - await buildersView!.reveal(item, { select: true, expand: true, focus: false }); - } catch { - // Benign if the row is no longer present (e.g. mid-cleanup). - } + // Reveal in every visible agent view that holds the row (the Agents view + // alone when none is visible, as before the Cockpit). The active editor may + // change during a lookup (rapid navigation); a slow lookup must not + // override a newer file's reveal. + await hosts.revealFile(entry.builderId, entry.relPath, + () => vscode.window.activeTextEditor?.document.uri.fsPath === fsPath); }; // Publish a builder-active event when a builder diff is under review, so a // configured hook can follow it. The diff session entry already carries the @@ -835,7 +846,8 @@ export async function activate(context: vscode.ExtensionContext) { vscode.workspace.onDidChangeConfiguration((e) => { if (!e.affectsConfiguration('codev.buildersFileViewAsTree')) { return; } vscode.commands.executeCommand('setContext', 'codev.buildersFileViewAsTree', readBuildersFileViewAsTree()); - buildersProvider.refresh(); + // Both views render changed files (Agents and the Cockpit). + hosts.refreshAll(); }), ); @@ -874,48 +886,27 @@ export async function activate(context: vscode.ExtensionContext) { }), ); - // Periodic overview refresh. VSCode has no timer-based refresh (event-only), - // so an idle workspace never sees externally-merged PRs / new issues. Mirror - // the dashboard's poll idiom: refresh on a cadence while the Codev sidebar is - // visible, paused when it isn't. The shared Tower-side 30s cache throttles gh - // cost across windows; refresh() is last-write-wins so periodic + event-driven - // refreshes coexist without flicker. - const setupPeriodicOverviewRefresh = () => { - let timer: ReturnType | undefined; - const readIntervalSeconds = (): number => { - const s = vscode.workspace.getConfiguration('codev').get('overviewRefreshSeconds', 60); - return typeof s === 'number' && Number.isFinite(s) && s > 0 ? s : 0; - }; - const anyVisible = (): boolean => - !!buildersView?.visible || !!pullRequestsView?.visible - || !!backlogView?.visible || !!recentlyClosedView?.visible; - const stop = () => { - if (timer) { clearInterval(timer); timer = undefined; } - }; - const reconcile = () => { - const seconds = readIntervalSeconds(); - if (seconds === 0 || !anyVisible()) { stop(); return; } - if (!timer) { - timer = setInterval(() => { - if (connectionManager?.getState() === 'connected') { void overviewCache.refresh(); } - }, seconds * 1000); - void overviewCache.refresh(); // resume → immediate refresh - } - }; - - context.subscriptions.push( - buildersView!.onDidChangeVisibility(reconcile), - pullRequestsView!.onDidChangeVisibility(reconcile), - backlogView!.onDidChangeVisibility(reconcile), - recentlyClosedView!.onDidChangeVisibility(reconcile), - vscode.workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('codev.overviewRefreshSeconds')) { stop(); reconcile(); } - }), - { dispose: stop }, - ); - reconcile(); + // Periodic overview refresh while any overview-backed view is visible + // (`OverviewRefreshGate`): the Codev container's list views and the Cockpit, + // so with only the Cockpit visible this workspace's rows stay current. + const readOverviewRefreshSeconds = (): number => { + const s = vscode.workspace.getConfiguration('codev').get('overviewRefreshSeconds', 60); + return typeof s === 'number' && Number.isFinite(s) && s > 0 ? s : 0; }; - setupPeriodicOverviewRefresh(); + const overviewRefreshGate = new OverviewRefreshGate( + [buildersView, pullRequestsView, backlogView, recentlyClosedView, cockpitView], + readOverviewRefreshSeconds, + () => { if (connectionManager?.getState() === 'connected') { void overviewCache.refresh(); } }, + () => { void overviewCache.refresh(); }, // resume → immediate refresh + ); + context.subscriptions.push( + ...overviewRefreshGate.wire(), + vscode.workspace.onDidChangeConfiguration(e => { + if (e.affectsConfiguration('codev.overviewRefreshSeconds')) { overviewRefreshGate.restart(); } + }), + overviewRefreshGate, + ); + overviewRefreshGate.reconcile(); // Refresh overview on connect + set team visibility connectionManager.onStateChange(async (state) => { @@ -970,8 +961,6 @@ export async function activate(context: vscode.ExtensionContext) { // (connectionManager.onSSEEvent) — no second EventSource. The container icon's badge carries the // machine-wide needs-attention count (only this container badges — the badge means machine-scope). // Registered here (after reg/regCli) so its commands route through the CLI-preflight guard. - const towerCache = new TowerFleetCache(connectionManager); - context.subscriptions.push({ dispose: () => towerCache.dispose() }); const towerProvider = new TowerProvider(towerCache, connectionManager); context.subscriptions.push(towerProvider); const towerView = vscode.window.createTreeView('codev.tower', { @@ -992,6 +981,8 @@ export async function activate(context: vscode.ExtensionContext) { towerView, towerCache.onDidChange(updateTowerBadge), reg('codev.tower.refresh', () => towerCache.refresh()), + // The Cockpit reads both caches: this window's overview and the fleet. + reg('codev.cockpit.refresh', () => Promise.all([overviewCache.refresh(), towerCache.refresh()])), ); // Populate as soon as Tower is reachable; refreshes thereafter ride the shared SSE + poll. towerCache.refresh(); @@ -1055,16 +1046,10 @@ export async function activate(context: vscode.ExtensionContext) { } for (const target of attempts) { if (!(await openAgentTarget(target))) { continue; } - // Mirror a row click: select the agent's sidebar row so the tree highlight - // follows the focused terminal. `focus: false` keeps the terminal focused. - const item = buildersProvider.revealTargetForAgent(target); - if (item) { - try { - await buildersView?.reveal(item, { select: true, focus: false }); - } catch { - // Benign: the row may have changed between open and reveal. - } - } + // Mirror a row click: select the agent's row in the visible agent view(s) + // so the tree highlight follows the focused terminal. `focus: false` + // keeps the terminal focused. + await hosts.revealAgent(target); return; } }; @@ -1322,7 +1307,8 @@ export async function activate(context: vscode.ExtensionContext) { vscode.workspace.getConfiguration('codev').get('buildersClickExpands', true); await runBuilderRowClick(clickExpands, { openTerminal: () => terminalManager?.openBuilderByRoleOrId(item.builderId, true), - expandRow: () => buildersView!.reveal(item, { expand: true, select: false, focus: false }), + // Expand in the row's own view (Agents or the Cockpit). + expandRow: () => hosts.expandRow(item), }); }), reg('codev.focusNextAgentTerminal', () => cycleAgentTerminal(1)), diff --git a/apps/vscode/src/mailbox-indicators.ts b/apps/vscode/src/mailbox-indicators.ts index b48c9da2c..62623e723 100644 --- a/apps/vscode/src/mailbox-indicators.ts +++ b/apps/vscode/src/mailbox-indicators.ts @@ -12,8 +12,9 @@ */ import * as path from 'node:path'; -import type { MailboxEscalationPayload } from '@cluesmith/codev-types'; +import type { MailboxEscalationPayload, OverviewData } from '@cluesmith/codev-types'; import { formatVerdict } from '@cluesmith/codev-sdk/hold-verdict'; +import { deriveAttention, isIdleWaiting } from '@cluesmith/codev-sdk/builder-helpers'; /** * Status-bar segment for held mail, e.g. ` · $(mail) 2 held`. Returns the empty @@ -140,6 +141,30 @@ export function composeActivityBadge( return { value: total, tooltip }; } +/** + * This window's workspace "needs me" badge, the one every view that renders its agents carries + * (the Agents view and the Cockpit, Spec 1963): blocked + idle-waiting builders, held mail and + * waiting architects (`composeActivityBadge`). `undefined`, clearing the badge, when not connected, + * with no overview yet, and always in a builder-worktree window, whose overview is the PARENT's + * builders: the parent's own window carries them (#1809). + */ +export function workspaceActivityBadge( + data: OverviewData | null, + window: { connected: boolean; builderWorktreeWindow: boolean }, + now: number = Date.now(), +): BadgeValue | undefined { + if (window.builderWorktreeWindow || !window.connected || !data) { + return undefined; + } + const blockedCount = data.builders.filter(b => b.blocked).length; + const idleCount = data.builders.filter(b => isIdleWaiting(b, now)).length; + // Spec 1595: architects at a prompt or with their agent dead fold in by name. + const waitingArchitects = deriveAttention(data, now).architects.map(a => a.architect); + // Spec 1313 Phase 8: the workspace held-mail count folds in, so the activity-bar + // icon reflects it even when the sidebar is collapsed. + return composeActivityBadge(blockedCount, idleCount, data.heldCount, waitingArchitects); +} + /** * Human-facing text for the `mailbox-escalation` toast. Metadata only — the * payload never carries a message body (spec redaction rule), so neither does diff --git a/apps/vscode/src/views/agent-tree-hosts.ts b/apps/vscode/src/views/agent-tree-hosts.ts new file mode 100644 index 000000000..b32f06862 --- /dev/null +++ b/apps/vscode/src/views/agent-tree-hosts.ts @@ -0,0 +1,176 @@ +import type * as vscode from 'vscode'; +import { BuilderTreeItem } from './builder-tree-item.js'; +import { AccordionGate } from './builders.js'; +import type { AgentTarget } from './architect-tree.js'; + +/** + * What a provider offers for the rows of this window's workspace that act here (Spec 1963). The + * Agents view's `BuildersProvider` and the Cockpit's `CockpitProvider` both implement it. + */ +export interface ActingRows { + /** + * The `scope` every acting row of this provider carries (`''` for the Agents view), or + * `undefined` while the provider has none (the Cockpit before Tower lists this window's + * workspace, and always in a builder-worktree or no-workspace window). + */ + actingScope(): string | undefined; + /** The changed-file row for `(builderId, relPath)`, for the active-file reveal (#1066). */ + findFileItem(builderId: string, relPath: string): Promise; + /** The row to select when the agent cycle lands on `target` (#1563). */ + revealTargetForAgent(target: AgentTarget): vscode.TreeItem | undefined; + /** Accordion (#913): hold `item` open, collapse every other builder row, and redraw. */ + collapseBuildersExcept(item: BuilderTreeItem): void; + /** Redraw the whole view (a setting the rows read changed). */ + refresh(): void; +} + +/** The parts of a `vscode.TreeView` the hosts use, whatever the view's element type. */ +export interface HostView { + readonly visible: boolean; + badge?: vscode.ViewBadge | undefined; + reveal(element: vscode.TreeItem, options?: { select?: boolean; focus?: boolean; expand?: boolean | number }): Thenable; + readonly onDidExpandElement: vscode.Event<{ readonly element: unknown }>; + readonly onDidChangeSelection: vscode.Event<{ readonly selection: readonly unknown[] }>; +} + +/** One tree view that renders this window's agents, and the provider behind it. */ +export interface AgentTreeHost { + readonly view: HostView; + readonly rows: ActingRows; + /** + * Follow-reveals (active file, agent cycle) land here when no host is visible. Set on the Agents + * view only, so with the Cockpit hidden the Agents view reveals exactly as it did before it. + */ + readonly revealWhenNoneVisible?: boolean; +} + +/** The `scope` a tree row carries, or `undefined` for a row that names none. */ +function scopeOf(row: unknown): string | undefined { + if (row === null || typeof row !== 'object') { return undefined; } + const scope = (row as { scope?: unknown }).scope; + if (typeof scope === 'string') { return scope; } + return undefined; +} + +/** + * The tree behaviours the Agents view used to own alone — row-click expand, the accordion, the + * active-file and agent-cycle reveals, the `builder-active` hook and the activity badge — + * generalised over every view that renders this window's agents (Spec 1963): the Agents view and + * the Cockpit. + * + * A row belongs to exactly one view. Its `scope` says which: each host's provider reports the + * scope of its acting rows, and only those rows act. Another workspace's rows in the Cockpit + * (navigate-only) never match, so they never expand, reveal, or fire `builder-active`. + */ +export class AgentTreeHosts { + private readonly gates = new Map(); + + constructor(private readonly hosts: readonly AgentTreeHost[], accordionEnabled: boolean) { + for (const host of hosts) { + this.gates.set(host, new AccordionGate(accordionEnabled)); + } + } + + /** The host whose acting rows include `row` (matched by `scope`), or `undefined`. */ + hostOf(row: unknown): AgentTreeHost | undefined { + const scope = scopeOf(row); + if (scope === undefined) { return undefined; } + return this.hosts.find(host => host.rows.actingScope() === scope); + } + + /** + * Subscribe each view's own accordion (#913): expanding a builder row collapses the other builder + * rows of the same view, gated by that view's own `AccordionGate`. + */ + wireAccordion(): vscode.Disposable[] { + return this.hosts.map(host => host.view.onDidExpandElement(e => this.onExpand(host, e.element))); + } + + private onExpand(host: AgentTreeHost, element: unknown): void { + if (!(element instanceof BuilderTreeItem)) { return; } + if (this.hostOf(element) !== host) { return; } + if (this.gates.get(host)!.shouldCollapseOthers(element.builderId)) { + host.rows.collapseBuildersExcept(element); + } + } + + /** `codev.buildersAutoCollapse` changed: re-gate every view's accordion. */ + setAccordionEnabled(enabled: boolean): void { + for (const gate of this.gates.values()) { gate.setEnabled(enabled); } + } + + /** `codev.buildersFileViewAsTree` changed: redraw every view. */ + refreshAll(): void { + for (const host of this.hosts) { host.rows.refresh(); } + } + + /** + * Publish `builder-active` when an acting builder row (or one of its file rows) is selected, in + * whichever view it is selected. + */ + wireSelection(onBuilderSelected: (builderId: string) => void): vscode.Disposable[] { + return this.hosts.map(host => host.view.onDidChangeSelection((e) => { + const selected = e.selection[0] as { builderId?: unknown } | undefined; + if (typeof selected?.builderId !== 'string' || selected.builderId === '') { return; } + if (this.hostOf(selected) !== host) { return; } + onBuilderSelected(selected.builderId); + })); + } + + /** + * The row-click expand (`codev.openBuilderRow`): reveal `item` expanded in its own view. A row + * no host owns (its workspace left the Cockpit mid-click) has nothing to expand. + */ + async expandRow(item: BuilderTreeItem): Promise { + const host = this.hostOf(item); + if (!host) { return; } + await host.view.reveal(item, { expand: true, select: false, focus: false }); + } + + /** The same badge on every view, so each one's activity-bar button carries it. */ + setBadge(badge: vscode.ViewBadge | undefined): void { + for (const host of this.hosts) { host.view.badge = badge; } + } + + /** + * The hosts a follow-reveal lands in: every visible view with acting rows, or, when none is + * visible, the view flagged `revealWhenNoneVisible` (the Agents view's behaviour before Spec 1963). + */ + private followHosts(): AgentTreeHost[] { + const withRows = this.hosts.filter(host => host.rows.actingScope() !== undefined); + const visible = withRows.filter(host => host.view.visible); + if (visible.length > 0) { return visible; } + return withRows.filter(host => host.revealWhenNoneVisible === true); + } + + /** + * Active-file reveal (#1066): select the changed-file row of `(builderId, relPath)` in each + * follow host. `stillCurrent` is re-checked after each lookup, so a slow lookup never overrides a + * newer file's reveal. + */ + async revealFile(builderId: string, relPath: string, stillCurrent: () => boolean): Promise { + for (const host of this.followHosts()) { + const item = await host.rows.findFileItem(builderId, relPath); + if (!item) { continue; } + if (!stillCurrent()) { return; } + try { + await host.view.reveal(item, { select: true, expand: true, focus: false }); + } catch { + // Benign if the row is no longer present (e.g. mid-cleanup). + } + } + } + + /** Agent-cycle selection (#1563): select the agent's row in each follow host. */ + async revealAgent(target: AgentTarget): Promise { + for (const host of this.followHosts()) { + const item = host.rows.revealTargetForAgent(target); + if (!item) { continue; } + try { + await host.view.reveal(item, { select: true, focus: false }); + } catch { + // Benign: the row may have changed between open and reveal. + } + } + } +} diff --git a/apps/vscode/src/views/architect-tree.ts b/apps/vscode/src/views/architect-tree.ts index 8b1b5b678..0acd4c846 100644 --- a/apps/vscode/src/views/architect-tree.ts +++ b/apps/vscode/src/views/architect-tree.ts @@ -3,7 +3,7 @@ import { existsSync, readdirSync } from 'node:fs'; import { resolve } from 'node:path'; import type { OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; import { UNCATEGORIZED_AREA } from '@cluesmith/codev-sdk/constants'; -import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; +import { deriveAttention, type AttentionSummary } from '@cluesmith/codev-sdk/builder-helpers'; import { builderWithWorktree, type OverviewBuilderWithWorktree } from '../builder-lookup.js'; import { readBuildersFileViewAsTree } from '../builders-config.js'; import { BuilderGroupTreeItem, BuilderTreeItem, IdleArchitectsGroupTreeItem } from './builder-tree-item.js'; @@ -22,6 +22,7 @@ import { type BuilderState, } from './builder-row.js'; import { OPEN_WORKSPACE_COMMAND, type WorkspaceTarget } from './tower.js'; +import { describeWait } from './attention-format.js'; /** * Builder state → `contextValue` family prefix. Drives menu `when`-clause @@ -114,10 +115,12 @@ interface ArchitectTreeCommonOptions { */ scope: string; /** - * Append *N held* / *N queued* (from `deriveAttention` over `getData()`) to builder-row - * descriptions. Off for the Agents view, whose builder rows carry no description. + * Show the Tower view's attention signals on the rows they concern, from `deriveAttention` over + * `getData()`: *N held* / *N queued* in builder-row descriptions, and an architect at a prompt + * or with its agent dead as its row's wait text and glyph (Spec 1595). Off for the Agents view, + * whose rows carry neither. */ - attentionCounts?: boolean; + attention?: boolean; } /** Rows that act in this window: open terminals, expand to changed files, carry the source menus. */ @@ -163,8 +166,8 @@ export class ArchitectTreeBuilder { private readonly rowIds: AccordionRowIds; // The architect axis, for navigate mode (which has no `grouping` option). private readonly architectAxis = architectGrouping(); - // `attentionCounts`: per-builder counts, derived once per overview object. - private attention: { data: OverviewData; counts: Map } | null = null; + // `attention`: the summary and per-builder counts, derived once per overview object. + private attentionCache: { data: OverviewData; summary: AttentionSummary; counts: Map } | null = null; constructor(private readonly options: ArchitectTreeOptions) { this.rowIds = new AccordionRowIds(options.scope); @@ -271,6 +274,11 @@ export class ArchitectTreeBuilder { getParent(element: vscode.TreeItem): vscode.ProviderResult { this.assertOwnRow(element); if (element instanceof BuilderTreeItem) { + // The group map is filled when the root rows render. A host that nests these + // rows under a node VS Code has not expanded yet (the Cockpit's workspace row) + // asks before that render, so build the root rows now rather than answer + // "root" for a builder that sits under an architect. + if (!this.groupParentByBuilderId.has(element.builderId)) { this.rootRows(); } return this.groupParentByBuilderId.get(element.builderId); } if (element instanceof BuilderFileTreeItem || element instanceof BuilderFolderTreeItem) { @@ -594,12 +602,33 @@ export class ArchitectTreeBuilder { groupItem.contextValue = g.key === 'main' ? 'cockpit-architect-main' : 'cockpit-architect-sibling'; } } + this.applyArchitectAttention(groupItem, g.key); for (const b of g.items) { this.groupParentByBuilderId.set(b.id, groupItem); } return groupItem; } + /** + * With `attention` on, an architect at a prompt or with its agent dead shows it on its own row: + * the wait text (the Tower view's attention-row text) as the description and its glyph as the + * icon. Only architect-axis rows name an architect, so other axes' headers never match. + */ + private applyArchitectAttention(row: BuilderGroupTreeItem, architectName: string): void { + if (this.grouping().id !== 'architect') { return; } + const summary = this.attentionSummary(); + if (!summary) { return; } + const waiting = summary.architects.find(a => a.architect === architectName); + if (!waiting) { return; } + const glance = describeWait(waiting.state, waiting.since); + row.description = glance.text; + if (glance.color) { + row.iconPath = new vscode.ThemeIcon(glance.icon, new vscode.ThemeColor(glance.color)); + } else { + row.iconPath = new vscode.ThemeIcon(glance.icon); + } + } + private rowsForGroup(key: string): vscode.TreeItem[] { const data = this.options.getData(); if (!data) { return []; } @@ -674,15 +703,14 @@ export class ArchitectTreeBuilder { } /** - * `N held · N queued` for a builder row when `attentionCounts` is on, or - * `undefined` when it is off or the builder has neither. The counts are the - * Tower view's own (`deriveAttention`), derived once per overview object. + * The attention summary of `getData()` when `attention` is on, else `undefined`. Derived once per + * overview object, with the per-builder held / queued counts alongside. */ - private attentionCountsText(builderId: string): string | undefined { - if (!this.options.attentionCounts) { return undefined; } + private attentionOf(): { summary: AttentionSummary; counts: Map } | undefined { + if (!this.options.attention) { return undefined; } const data = this.options.getData(); if (!data) { return undefined; } - if (this.attention?.data !== data) { + if (this.attentionCache?.data !== data) { const summary = deriveAttention(data); const counts = new Map(); const entry = (id: string) => { @@ -695,9 +723,24 @@ export class ArchitectTreeBuilder { }; for (const item of summary.heldMail) { entry(item.builderId).held = item.count; } for (const item of summary.queuedFeedback) { entry(item.builderId).queued = item.count; } - this.attention = { data, counts }; + this.attentionCache = { data, summary, counts }; } - const found = this.attention.counts.get(builderId); + return this.attentionCache; + } + + private attentionSummary(): AttentionSummary | undefined { + return this.attentionOf()?.summary; + } + + /** + * `N held · N queued` for a builder row when `attention` is on, or `undefined` + * when it is off or the builder has neither. The counts are the Tower view's + * own (`deriveAttention`). + */ + private attentionCountsText(builderId: string): string | undefined { + const attention = this.attentionOf(); + if (!attention) { return undefined; } + const found = attention.counts.get(builderId); if (!found) { return undefined; } const parts: string[] = []; if (found.held > 0) { parts.push(`${found.held} held`); } diff --git a/apps/vscode/src/views/builders.ts b/apps/vscode/src/views/builders.ts index 7a5b32604..01c954b2c 100644 --- a/apps/vscode/src/views/builders.ts +++ b/apps/vscode/src/views/builders.ts @@ -193,6 +193,11 @@ export class BuildersProvider implements vscode.TreeDataProvider { return this.tree.findFileItem(builderId, relPath); diff --git a/apps/vscode/src/views/cockpit.ts b/apps/vscode/src/views/cockpit.ts new file mode 100644 index 000000000..d86f46a12 --- /dev/null +++ b/apps/vscode/src/views/cockpit.ts @@ -0,0 +1,400 @@ +import * as vscode from 'vscode'; +import type { OverviewData } from '@cluesmith/codev-types'; +import type { ConnectionManager } from '../connection-manager.js'; +import type { TowerFleetCache } from './tower-cache.js'; +import type { OverviewCache } from './overview-data.js'; +import type { BuilderDiffCache } from './builder-diff-cache.js'; +import { orderFleet, type LabelledEntry, type OrderedFleet } from './fleet-order.js'; +import { dormantGroupRow, targetOf, workspaceRow, type WorkspaceTarget } from './tower.js'; +import { ArchitectTreeBuilder, type AgentTarget } from './architect-tree.js'; +import { architectGrouping } from './builder-grouping.js'; +import { BuilderGroupTreeItem, BuilderTreeItem, IdleArchitectsGroupTreeItem } from './builder-tree-item.js'; +import type { ActingRows } from './agent-tree-hosts.js'; + +/** The Cockpit's tree view id (Spec 1963). */ +export const COCKPIT_VIEW_ID = 'codev.cockpit'; + +/** Stable ids of the Cockpit's own rows, so expansion survives a refresh and `reveal` can match them. */ +export const COCKPIT_IDS = { + tower: 'cockpit-tower', + dormant: 'cockpit-dormant', + workspace: (path: string) => `cockpit-ws:${path}`, + loading: (path: string) => `cockpit-loading:${path}`, +} as const; + +/** The id prefix of every architect and builder row under one workspace. */ +export function cockpitScope(path: string): string { + return `ws:${path}|`; +} + +/** + * The Cockpit's own nodes. Architect, builder and changed-file rows under a workspace are the + * `vscode.TreeItem`s its `ArchitectTreeBuilder` makes. A workspace node has the Tower view's + * `{ kind: 'workspace', ws }` shape, so the Tower view's Open / Deactivate handlers accept it. + */ +export type CockpitOwnNode = + | { kind: 'tower-root' } + | { kind: 'message'; text: string; icon: string; command?: vscode.Command; tooltip?: string } + | { kind: 'workspace'; ws: LabelledEntry } + | { kind: 'dormant-group'; rows: LabelledEntry[] } + | { kind: 'loading'; ws: LabelledEntry }; + +export type CockpitNode = CockpitOwnNode | vscode.TreeItem; + +export interface CockpitProviderOptions { + connectionManager: Pick; + towerCache: Pick; + overviewCache: Pick; + diffCache: BuilderDiffCache; + /** + * A builder-worktree window (#1809): the parent workspace is marked current, but its rows act on + * nothing here, so every workspace navigates. + */ + builderWorktreeWindow: boolean; + /** + * Whether this window connects to Tower at all. A dormant window (guest mode, no Codev + * workspace, #1144) never does, so it says *Not connected* rather than *Connecting…* forever. + */ + connects: boolean; +} + +/** One workspace's row builder, and the workspace as it was last listed. */ +interface WorkspaceTree { + tree: ArchitectTreeBuilder; + ws: LabelledEntry; +} + +const ARCHITECT_AXIS = architectGrouping(); + +/** + * The Codev Cockpit (Spec 1963): one tree with one hierarchy, *Tower → workspaces → architects → + * builders → (this window's workspace only) changed files*. + * + * - **Tower root.** While there is nothing to list it holds one state row that follows the + * connection: *Connecting to Tower…* until an attempt fails, then *Not connected to Tower* + * (click: *Reconnect*), or *No workspaces registered*. + * - **Workspaces.** The Tower view's set, labels, urgency order, *current* marker and *Dormant (N)* + * group (`orderFleet`, rows from `workspaceRow`). Every active workspace has children, so a click + * toggles it; dormant rows keep click-to-open. + * - **Architects → builders.** One `ArchitectTreeBuilder` per active workspace, on the architect + * axis whatever `codev.buildersGroupBy` says. This window's workspace acts, reading + * `OverviewCache` as the Agents view does; every other workspace navigates, reading the overview + * `TowerFleetCache` already fetched for it. No request of its own. + * + * Re-renders on the overview, the fleet and the connection state. + */ +export class CockpitProvider implements vscode.TreeDataProvider, ActingRows { + private readonly changeEmitter = new vscode.EventEmitter(); + readonly onDidChangeTreeData = this.changeEmitter.event; + private readonly subscriptions: vscode.Disposable[] = []; + /** Row builders by scope, one per active workspace; pruned when a workspace leaves. */ + private readonly trees = new Map(); + /** True once a connection attempt has failed (or a connection dropped). */ + private attemptFailed: boolean; + + constructor(private readonly options: CockpitProviderOptions) { + const { connectionManager, towerCache, overviewCache } = options; + this.attemptFailed = connectionManager.getState() === 'reconnecting'; + this.subscriptions.push( + overviewCache.onDidChange(() => this.refresh()), + towerCache.onDidChange(() => this.refresh()), + connectionManager.onStateChange((state) => { + if (state === 'disconnected' || state === 'reconnecting') { this.attemptFailed = true; } + this.refresh(); + }), + ); + } + + dispose(): void { + for (const sub of this.subscriptions) { sub.dispose(); } + this.changeEmitter.dispose(); + } + + /** Redraw the whole tree. */ + refresh(): void { + this.changeEmitter.fire(); + } + + // ── TreeDataProvider ────────────────────────────────────────────────────── + + getTreeItem(node: CockpitNode): vscode.TreeItem { + if (node instanceof vscode.TreeItem) { return node; } + switch (node.kind) { + case 'tower-root': { + const item = new vscode.TreeItem('Tower', vscode.TreeItemCollapsibleState.Expanded); + item.id = COCKPIT_IDS.tower; + item.iconPath = new vscode.ThemeIcon('radio-tower'); + item.tooltip = "This machine's Tower and the workspaces it serves"; + item.contextValue = 'cockpit-tower'; + return item; + } + case 'message': { + const item = new vscode.TreeItem(node.text); + item.iconPath = new vscode.ThemeIcon(node.icon); + if (node.command) { item.command = node.command; } + if (node.tooltip) { item.tooltip = node.tooltip; } + return item; + } + case 'workspace': { + const item = workspaceRow(node.ws, this.workspaceChildren(node.ws)); + item.id = COCKPIT_IDS.workspace(node.ws.entry.workspace.path); + return item; + } + case 'dormant-group': { + const item = dormantGroupRow(node.rows.length); + item.id = COCKPIT_IDS.dormant; + return item; + } + case 'loading': { + const item = new vscode.TreeItem('Loading…'); + item.id = COCKPIT_IDS.loading(node.ws.entry.workspace.path); + item.iconPath = new vscode.ThemeIcon('sync~spin'); + return item; + } + } + } + + async getChildren(node?: CockpitNode): Promise { + if (node === undefined) { return [{ kind: 'tower-root' }]; } + if (node instanceof vscode.TreeItem) { + const tree = this.treeOfRow(node); + if (!tree) { return []; } + return tree.getChildren(node); + } + switch (node.kind) { + case 'tower-root': + return this.towerChildren(); + case 'workspace': + return this.workspaceNodeChildren(node.ws); + case 'dormant-group': + return node.rows.map((ws): CockpitNode => ({ kind: 'workspace', ws })); + case 'message': + case 'loading': + return []; + } + } + + /** + * The parent of any row, up to the Tower root: file → folder(s) → builder → architect → + * (*Idle Architects*) → workspace → (*Dormant*) → Tower. The row builder answers within its + * workspace; the Cockpit bridges its top rows to the workspace node. + */ + async getParent(node: CockpitNode): Promise { + if (node instanceof vscode.TreeItem) { + const entry = this.entryOfRow(node); + if (!entry) { return undefined; } + const parent = await entry.tree.getParent(node); + if (parent) { return parent; } + if (node instanceof BuilderGroupTreeItem || node instanceof IdleArchitectsGroupTreeItem) { + const ws = this.findWorkspace(entry.ws.entry.workspace.path); + if (!ws) { return undefined; } + return { kind: 'workspace', ws }; + } + return undefined; + } + switch (node.kind) { + case 'tower-root': + return undefined; + case 'message': + case 'dormant-group': + return { kind: 'tower-root' }; + case 'workspace': { + if (node.ws.entry.workspace.active) { return { kind: 'tower-root' }; } + return { kind: 'dormant-group', rows: this.ordered().dormant }; + } + case 'loading': + return { kind: 'workspace', ws: node.ws }; + } + } + + // ── ActingRows (this window's workspace) ────────────────────────────────── + + actingScope(): string | undefined { + return this.actTree()?.scope; + } + + async findFileItem(builderId: string, relPath: string): Promise { + return this.actTree()?.findFileItem(builderId, relPath); + } + + revealTargetForAgent(target: AgentTarget): vscode.TreeItem | undefined { + return this.actTree()?.revealTargetForAgent(target); + } + + collapseBuildersExcept(item: BuilderTreeItem): void { + const tree = this.treeOfRow(item); + if (!tree) { return; } + tree.keepOnlyOpen(item); + this.refresh(); + } + + /** + * The acting row builder of this window's workspace, or `undefined` when nothing acts here: Tower + * has not listed this workspace (yet), it is dormant, or the window is a builder-worktree or + * no-workspace window. + */ + private actTree(): ArchitectTreeBuilder | undefined { + const ws = this.ordered().active.find(entry => this.actsHere(entry)); + if (!ws) { return undefined; } + return this.treeFor(ws); + } + + // ── Levels ──────────────────────────────────────────────────────────────── + + /** The Tower root's children: a state row while there is nothing to list, else the workspaces. */ + private towerChildren(): CockpitNode[] { + if (!this.options.towerCache.isLoaded()) { + return [this.connectionStateRow()]; + } + if (this.options.towerCache.getFleet().length === 0) { + return [{ kind: 'message', text: 'No workspaces registered', icon: 'info' }]; + } + const { active, dormant } = this.ordered(); + this.pruneTrees(active); + const nodes: CockpitNode[] = active.map((ws): CockpitNode => ({ kind: 'workspace', ws })); + if (dormant.length > 0) { + nodes.push({ kind: 'dormant-group', rows: dormant }); + } + return nodes; + } + + /** + * *Connecting to Tower…* until an attempt has failed (also while connected but before the first + * fleet load lands); *Not connected to Tower* after one, with *Reconnect* on click. + * `ConnectionManager` keeps retrying with backoff, so this never claims it gave up. + */ + private connectionStateRow(): CockpitOwnNode { + const { connectionManager, connects } = this.options; + if (!connects) { + return { + kind: 'message', text: 'Not connected to Tower', icon: 'debug-disconnect', + tooltip: 'This window has no Codev workspace, so it does not connect to Tower.', + }; + } + if (connectionManager.getState() === 'connected' || !this.attemptFailed) { + return { kind: 'message', text: 'Connecting to Tower…', icon: 'sync~spin' }; + } + return { + kind: 'message', + text: 'Not connected to Tower', + icon: 'debug-disconnect', + tooltip: 'Click to reconnect to Tower now. Codev keeps retrying in the background.', + command: { command: 'codev.reconnect', title: 'Reconnect to Tower' }, + }; + } + + /** + * How a workspace row starts: an active one always has children (expanded when it is this + * window's own or needs attention, collapsed when quiet); a dormant one is a leaf that opens on + * click. + */ + private workspaceChildren(ws: LabelledEntry): 'none' | 'collapsed' | 'expanded' { + if (!ws.entry.workspace.active) { return 'none'; } + if (ws.isCurrent || !ws.entry.attention.isEmpty) { return 'expanded'; } + return 'collapsed'; + } + + /** An active workspace's architects (with their builders), or *Loading…* until its overview lands. */ + private async workspaceNodeChildren(ws: LabelledEntry): Promise { + if (!ws.entry.workspace.active) { return []; } + const tree = this.treeFor(ws); + if (this.dataFor(ws) === null) { + return [{ kind: 'loading', ws }]; + } + return tree.getChildren(undefined); + } + + // ── Row builders ────────────────────────────────────────────────────────── + + /** + * Whether `ws`'s rows act in this window: it is this window's workspace, and this window is not + * a builder worktree (whose parent is marked current but acts on nothing here, #1809). + */ + private actsHere(ws: LabelledEntry): boolean { + return ws.isCurrent && ws.entry.workspace.active && !this.options.builderWorktreeWindow; + } + + /** + * The overview `ws`'s rows are built from: `OverviewCache` for this window's workspace (as the + * Agents view, so the two never disagree), the fleet's retained copy for any other. + */ + private dataFor(ws: LabelledEntry): OverviewData | null { + if (this.actsHere(ws)) { return this.options.overviewCache.getData(); } + return this.options.towerCache.getOverview(ws.entry.workspace.path); + } + + /** The row builder for `ws`, made on first use and remade if `ws` changes between act and navigate. */ + private treeFor(ws: LabelledEntry): ArchitectTreeBuilder { + const path = ws.entry.workspace.path; + const scope = cockpitScope(path); + const mode = this.actsHere(ws) ? 'act' : 'navigate'; + const existing = this.trees.get(scope); + if (existing && existing.tree.mode === mode) { + existing.ws = ws; + return existing.tree; + } + let tree: ArchitectTreeBuilder; + if (mode === 'act') { + tree = new ArchitectTreeBuilder({ + mode: 'act', + scope, + getData: () => this.options.overviewCache.getData(), + grouping: () => ARCHITECT_AXIS, + diffCache: this.options.diffCache, + attention: true, + }); + } else { + tree = new ArchitectTreeBuilder({ + mode: 'navigate', + scope, + getData: () => this.options.towerCache.getOverview(path), + target: () => this.navigateTarget(scope), + attention: true, + }); + } + this.trees.set(scope, { tree, ws }); + return tree; + } + + /** + * What a navigate-only row opens: its workspace's window. `isCurrent` is always false, because a + * navigating row's workspace is never this window's own: in a builder-worktree window the parent + * is *marked* current, yet opening it must still reach the parent's window. + */ + private navigateTarget(scope: string): WorkspaceTarget { + const ws = this.trees.get(scope)!.ws; + return { ...targetOf(ws), isCurrent: false }; + } + + /** Drop the row builders of workspaces no longer active in the fleet. */ + private pruneTrees(active: readonly LabelledEntry[]): void { + const live = new Set(active.map(ws => cockpitScope(ws.entry.workspace.path))); + for (const scope of this.trees.keys()) { + if (!live.has(scope)) { this.trees.delete(scope); } + } + } + + /** The row builder entry that made `row`, by its `scope`; `undefined` once its workspace left. */ + private entryOfRow(row: vscode.TreeItem): WorkspaceTree | undefined { + const scope = (row as { scope?: unknown }).scope; + if (typeof scope !== 'string' || scope === '') { + throw new Error(`CockpitProvider: row '${String(row.label)}' carries no workspace scope`); + } + return this.trees.get(scope); + } + + private treeOfRow(row: vscode.TreeItem): ArchitectTreeBuilder | undefined { + return this.entryOfRow(row)?.tree; + } + + /** The fleet in the Tower view's order, labelled, with this window's workspace marked. */ + private ordered(): OrderedFleet { + return orderFleet(this.options.towerCache.getFleet(), this.options.connectionManager.getWorkspacePath()); + } + + /** The current listing of the workspace at `path` (Tower's spelling), if it is still listed. */ + private findWorkspace(path: string): LabelledEntry | undefined { + const { active, dormant } = this.ordered(); + return [...active, ...dormant].find(ws => ws.entry.workspace.path === path); + } +} diff --git a/apps/vscode/src/views/overview-refresh-gate.ts b/apps/vscode/src/views/overview-refresh-gate.ts new file mode 100644 index 000000000..5c4a9a147 --- /dev/null +++ b/apps/vscode/src/views/overview-refresh-gate.ts @@ -0,0 +1,74 @@ +import type * as vscode from 'vscode'; + +/** A view whose visibility keeps the periodic overview refresh running. */ +export interface GatedView { + readonly visible: boolean; + readonly onDidChangeVisibility: vscode.Event; +} + +/** + * Periodic overview refresh (`codev.overviewRefreshSeconds`). VS Code has no timer-based refresh + * (event-only), so an idle workspace would never see externally-merged PRs or new issues. Mirror + * the dashboard's poll idiom: refresh on a cadence while any overview-backed view is visible, + * paused when none is. The shared Tower-side 30 s cache throttles gh cost across windows, and + * `OverviewCache.refresh()` is last-write-wins, so periodic and event-driven refreshes coexist. + * + * Every view that renders this window's overview is one of `views` — the Codev container's list + * views and, since Spec 1963, the Cockpit — so with only the Cockpit visible the timer still runs. + */ +export class OverviewRefreshGate implements vscode.Disposable { + private timer: ReturnType | undefined; + + /** + * @param views the views whose visibility keeps the timer running. + * @param intervalSeconds the configured cadence; `0` turns the refresh off. + * @param onTick runs on each interval. + * @param onResume runs once when the timer starts (an immediate refresh on becoming visible). + */ + constructor( + private readonly views: readonly GatedView[], + private readonly intervalSeconds: () => number, + private readonly onTick: () => void, + private readonly onResume: () => void, + ) {} + + /** Re-check on every view's visibility change. */ + wire(): vscode.Disposable[] { + return this.views.map(view => view.onDidChangeVisibility(() => this.reconcile())); + } + + /** True while the periodic refresh is running. */ + isRunning(): boolean { + return this.timer !== undefined; + } + + /** Start the timer if a view is visible and the cadence is on; stop it otherwise. */ + reconcile(): void { + const seconds = this.intervalSeconds(); + if (seconds === 0 || !this.views.some(view => view.visible)) { + this.stop(); + return; + } + if (this.timer === undefined) { + this.timer = setInterval(() => this.onTick(), seconds * 1000); + this.onResume(); + } + } + + /** The cadence setting changed: start over at the new interval. */ + restart(): void { + this.stop(); + this.reconcile(); + } + + dispose(): void { + this.stop(); + } + + private stop(): void { + if (this.timer !== undefined) { + clearInterval(this.timer); + this.timer = undefined; + } + } +} diff --git a/apps/vscode/src/views/tower.ts b/apps/vscode/src/views/tower.ts index 1915a9eb8..9240a4655 100644 --- a/apps/vscode/src/views/tower.ts +++ b/apps/vscode/src/views/tower.ts @@ -31,7 +31,7 @@ type TowerNode = | { kind: 'attention'; label: string; description: string; icon: string; color?: string }; /** The `WorkspaceTarget` for a labelled row. */ -function targetOf(ws: LabelledEntry): WorkspaceTarget { +export function targetOf(ws: LabelledEntry): WorkspaceTarget { return { path: ws.entry.workspace.path, active: ws.entry.workspace.active, name: ws.label, isCurrent: ws.isCurrent }; } @@ -88,14 +88,16 @@ export class TowerProvider implements vscode.TreeDataProvider { item.iconPath = new vscode.ThemeIcon(node.icon); return item; } - case 'dormant-group': { - const item = new vscode.TreeItem(`Dormant (${node.rows.length})`, vscode.TreeItemCollapsibleState.Collapsed); - item.iconPath = new vscode.ThemeIcon('circle-outline'); - item.contextValue = 'tower-dormant-group'; - return item; + case 'dormant-group': + return dormantGroupRow(node.rows.length); + case 'workspace': { + // Expandable only when there are attention rows to show; a quiet row is a leaf whose + // click opens it. + const hasDetail = !node.ws.entry.attention.isEmpty && node.ws.entry.workspace.active; + let children: WorkspaceRowChildren = 'none'; + if (hasDetail) { children = 'collapsed'; } + return workspaceRow(node.ws, children); } - case 'workspace': - return this.workspaceItem(node.ws); case 'attention': { const item = new vscode.TreeItem(node.label); item.description = node.description; @@ -133,48 +135,67 @@ export class TowerProvider implements vscode.TreeDataProvider { } return nodes; } +} - private workspaceItem(ws: LabelledEntry): vscode.TreeItem { - const { entry, label, isCurrent } = ws; - const state = describeAttention(entry.attention); - const hasDetail = !entry.attention.isEmpty && entry.workspace.active; - - let collapsibleState = vscode.TreeItemCollapsibleState.None; - if (hasDetail) { collapsibleState = vscode.TreeItemCollapsibleState.Collapsed; } - const item = new vscode.TreeItem(label, collapsibleState); - - const descriptionParts: string[] = []; - if (isCurrent) { descriptionParts.push('current'); } - if (state) { descriptionParts.push(state.text); } - item.description = descriptionParts.join(' · '); - - if (entry.workspace.active) { - if (state) { item.iconPath = iconFor(state.icon, state.color); } - // The current window's workspace is the folder that's open here — an opened folder, distinct - // from the plain `folder` other active workspaces use (and not a map-pin). - else if (isCurrent) { item.iconPath = new vscode.ThemeIcon('folder-opened'); } - else { item.iconPath = new vscode.ThemeIcon('folder'); } - } else { - item.iconPath = new vscode.ThemeIcon('circle-outline'); - } +/** + * Whether a workspace row has children, and how it starts: `none` makes it a leaf whose click + * opens the workspace; `collapsed` / `expanded` make it a container that a click toggles. + */ +export type WorkspaceRowChildren = 'none' | 'collapsed' | 'expanded'; + +/** The *Dormant (N)* group row, shared by the Tower view and the Cockpit. */ +export function dormantGroupRow(count: number): vscode.TreeItem { + const item = new vscode.TreeItem(`Dormant (${count})`, vscode.TreeItemCollapsibleState.Collapsed); + item.iconPath = new vscode.ThemeIcon('circle-outline'); + item.contextValue = 'tower-dormant-group'; + return item; +} - item.tooltip = `${label}\n${entry.workspace.path}`; +/** + * A workspace row: label, *current* marker and attention summary in the description, icon, + * tooltip and the `contextValue` the Open / Deactivate menus key on. Shared by the Tower view and + * the Cockpit (Spec 1963), which differ only in whether the row has children. + */ +export function workspaceRow(ws: LabelledEntry, children: WorkspaceRowChildren): vscode.TreeItem { + const { entry, label, isCurrent } = ws; + const state = describeAttention(entry.attention); + + let collapsibleState = vscode.TreeItemCollapsibleState.None; + if (children === 'collapsed') { collapsibleState = vscode.TreeItemCollapsibleState.Collapsed; } + if (children === 'expanded') { collapsibleState = vscode.TreeItemCollapsibleState.Expanded; } + const item = new vscode.TreeItem(label, collapsibleState); + + const descriptionParts: string[] = []; + if (isCurrent) { descriptionParts.push('current'); } + if (state) { descriptionParts.push(state.text); } + item.description = descriptionParts.join(' · '); + + if (entry.workspace.active) { + if (state) { item.iconPath = iconFor(state.icon, state.color); } + // The current window's workspace is the folder that's open here — an opened folder, distinct + // from the plain `folder` other active workspaces use (and not a map-pin). + else if (isCurrent) { item.iconPath = new vscode.ThemeIcon('folder-opened'); } + else { item.iconPath = new vscode.ThemeIcon('folder'); } + } else { + item.iconPath = new vscode.ThemeIcon('circle-outline'); + } - // contextValue gates the row's inline menu (open / deactivate) in package.json. - let contextValue = 'tower-workspace-dormant'; - if (entry.workspace.active) { - contextValue = 'tower-workspace-active'; - if (isCurrent) { contextValue = 'tower-workspace-active-current'; } - } - item.contextValue = contextValue; + item.tooltip = `${label}\n${entry.workspace.path}`; - // Click-to-open ONLY on rows with nothing to expand — otherwise a single click that means - // "expand this" would also fire openFolder. Expandable rows open via the inline button instead. - if (!hasDetail) { - item.command = { command: OPEN_WORKSPACE_COMMAND, title: 'Open Workspace', arguments: [targetOf(ws)] }; - } - return item; + // contextValue gates the row's inline menu (open / deactivate) in package.json. + let contextValue = 'tower-workspace-dormant'; + if (entry.workspace.active) { + contextValue = 'tower-workspace-active'; + if (isCurrent) { contextValue = 'tower-workspace-active-current'; } + } + item.contextValue = contextValue; + + // Click-to-open ONLY on rows with nothing to expand — otherwise a single click that means + // "expand this" would also fire openFolder. Expandable rows open via the inline button instead. + if (children === 'none') { + item.command = { command: OPEN_WORKSPACE_COMMAND, title: 'Open Workspace', arguments: [targetOf(ws)] }; } + return item; } /** The expanded per-workspace attention rows, in the summary's own order. */ diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 681328a77..be71b563c 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -400,3 +400,66 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when (`Snapshots 18 written`) against the untouched `BuildersProvider`, then the source changes, after which the snapshot matched unchanged. The mutation runs also show the snapshot is not self-confirming: giving the Agents view a cockpit contextValue or a description fails it. + +### Phase 4 (`cockpit_hierarchy`), iteration 1 (2026-11-24): the Cockpit button and its tree + +- The button: `codev-cockpit` sits directly after `codev` in the activity bar, with + `icons/codev-cockpit.svg` (`codev.svg`'s path wrapped in `rotate(90 400 400)`). It holds one + view, `codev.cockpit`, with no `when`, and a title-bar *Refresh* (`codev.cockpit.refresh`, which + refreshes the overview and the fleet). Checked: the whole `contributes` block minus these + additions is byte-identical to the Phase 3 commit's. +- `views/cockpit.ts`, `CockpitProvider`. Tower root → state rows (*Connecting…* until an attempt + fails, then *Not connected* → `codev.reconnect`; *No workspaces registered*) or the workspaces + in the Tower view's order, labels, *current* marker and *Dormant (N)* group. Then one + `ArchitectTreeBuilder` per active workspace, cached by scope `ws:|` and pruned on leave: + this window's workspace acts on `OverviewCache`; every other one navigates on the fleet's + retained overview. *Loading…* until a workspace's overview lands. `getParent` reaches the Tower + root from every row. +- Shared row code: `workspaceRow(ws, 'none' | 'collapsed' | 'expanded')` and `dormantGroupRow` + are extracted from `TowerProvider`, whose output is unchanged (its tests pass unmodified). +- `views/agent-tree-hosts.ts`, `AgentTreeHosts`: the Agents view and the Cockpit are two hosts. + The row click, the per-view accordion (one `AccordionGate` each), the follow-reveals, the + `builder-active` selection hook and the badge act on whichever view a row belongs to, matched by + its `scope`. Another workspace's rows never act. +- `views/overview-refresh-gate.ts`, `OverviewRefreshGate`: the periodic overview refresh, lifted + out of `extension.ts` unchanged, with the Cockpit added to its view list. It is a new module so + the visibility gate is unit-testable; Phase 8 adds the Work panel to the same list. +- `mailbox-indicators.ts`, `workspaceActivityBadge`: the badge computation, lifted out of + `extension.ts` as a pure function. It is assigned to both views. +- Decisions taken here, each small (raise any at review): + - Follow-reveals (active file, agent cycle) land in every *visible* host. When none is visible + they land in the Agents view, exactly as before. Revealing in a hidden view opens its + container, so revealing in both would flip the sidebar between them. + - A navigate row's target always has `isCurrent: false`. In a builder-worktree window the + parent is marked current, and `openOrActivateWorkspace` returns early on `isCurrent`, so the + click would do nothing. Its window is not this one. + - A dormant window (guest mode, no Codev workspace) never connects, so the root says *Not + connected to Tower* with no Reconnect command (the command is a no-op there) instead of + *Connecting…* forever. + - Once the fleet has loaded, a dropped connection keeps listing the last-known workspaces. The + spec puts the state row on the root only "while there is nothing to list". + - The architect rows' attention (Spec 1595 wait text and glyph) lives in `ArchitectTreeBuilder` + behind the Phase 3 option, renamed `attentionCounts` → `attention`. It is off for Agents, so the + Phase 3 snapshot still matches. + - `ArchitectTreeBuilder.getParent` builds the root rows when it does not yet know a builder's + group. The Cockpit asks before its workspace node was ever expanded (the active-file reveal + with collapsed ancestors), and the old answer, "root", broke the chain. The Agents view is + unchanged: its root always renders first. +- Re-render cost, as carried from the Phase 3 review: the Cockpit redraws on every fleet tick as + well as every overview change, so this window's builder rows run `builderHasReviewFile` (one + `readdirSync` each) about twice as often as the Agents view, and an expanded builder row may + re-read its 15 s-TTL diff on a fleet tick. Accepted: it is a handful of small local reads. +- Observation, not changed: an idle sibling at a prompt is folded inside the collapsed *Idle + Architects* container, so its wait text is one click down. The workspace row's summary still + shows it. +- Tests: + - `cockpit-provider.test.ts` (40); + - `cockpit-wiring.test.ts` (21); + - `contributes-cockpit.test.ts` (8), with snapshots of the `codev` views and every non-Cockpit + menu entry, checked against the Phase 3 commit; + - `cockpit-icon.test.ts` (3); + - `worktree-window-1809.test.ts`: its badge match now follows the generalised wiring and asserts + both views, plus a behavioural check on `workspaceActivityBadge`. + - Mutation-checked, 45 mutations across the provider, the hosts, the gate, the badge, the tower + extraction and the `extension.ts` wiring; every one is killed. Three survivors on the first pass + (connected-before-load, pruning, `restart()`) got stronger tests. From ecb0812056a4821b3d1f1bf4b3b8fdd6405616c1 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:39:22 -0800 Subject: [PATCH 053/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 629db231b..387be8f1c 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -60,7 +60,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T08:05:18.924Z' +updated_at: '2026-11-24T08:39:22.811Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 6cefa055e2a0e5f2dddcf4462fb3a181d007f96a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:47:23 -0800 Subject: [PATCH 054/140] =?UTF-8?q?[Spec=201963][Phase:=20cockpit=5Fhierar?= =?UTF-8?q?chy]=20fix:=20review=20notes=20=E2=80=94=20badge=20follows=20th?= =?UTF-8?q?e=20connection,=20autoConnect=20off,=20dormant=20window=20stays?= =?UTF-8?q?=20inert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Badge: repaint on every connection-state change, so both activity-bar buttons clear during a Tower outage (OverviewCache keeps its data and emits nothing on a disconnect). This also changes the existing Codev button's badge in an outage. - Cockpit connection mode auto | manual | none: with codev.autoConnect off the root says Not connected (Reconnect) instead of Connecting… forever. - Dormant window (#1144, architect ruling A): the state row gives the reason and Open Folder and never initialises the connection; new test proves no client, SSE, auto-start or fetch while the Cockpit is shown. - navigateTarget throws a named error instead of a bare non-null assertion. --- .../__tests__/cockpit-dormant-1144.test.ts | 186 ++++++++++++++++++ .../src/__tests__/cockpit-provider.test.ts | 40 +++- .../src/__tests__/cockpit-wiring.test.ts | 27 ++- apps/vscode/src/extension.ts | 11 +- apps/vscode/src/views/cockpit.ts | 61 ++++-- .../1963-cockpit_hierarchy-iter1-rebuttals.md | 94 +++++++++ codev/state/spir-1963_thread.md | 35 ++++ 7 files changed, 432 insertions(+), 22 deletions(-) create mode 100644 apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md diff --git a/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts b/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts new file mode 100644 index 000000000..193cb8281 --- /dev/null +++ b/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts @@ -0,0 +1,186 @@ +/** + * Spec 1963 × #1144: a dormant window (guest mode, no Codev workspace) stays exactly as inert as if + * Codev never activated, even with the Codev Cockpit shown. Architect ruling at Phase 4: the Cockpit + * shows the *Not connected to Tower* row (with its reason and *Open Folder*) and never initialises + * the connection. + * + * The window is assembled from the real objects `activate()` builds for it — `ConnectionManager` + * (never initialised: the dormant policy's `initializeConnection` is false), `OverviewCache`, + * `TowerFleetCache`, `CockpitProvider` and the `OverviewRefreshGate` that counts the Cockpit. Every + * route to Tower is a recording mock: the SDK's `TowerClient`, the SSE client, the Tower auto-starter + * and global `fetch`. Showing the Cockpit, rendering it, running its Refresh and letting every poll + * timer fire must record nothing. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +const { recorded } = vi.hoisted(() => ({ + recorded: { clients: 0, clientCalls: [] as string[], sse: 0, autoStart: 0 }, +})); + +vi.mock('vscode', () => { + class EventEmitter { + private listeners: Array<(e: T) => void> = []; + event = (listener: (e: T) => void) => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter(l => l !== listener); } }; + }; + fire(e: T) { for (const l of this.listeners) { l(e); } } + dispose() {} + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { constructor(public id: string, public color?: unknown) {} } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + window: { showErrorMessage: vi.fn() }, + workspace: { + workspaceFolders: undefined, + getConfiguration: () => ({ get: (_key: string, fallback?: T) => fallback }), + }, + }; +}); + +vi.mock('@cluesmith/codev-sdk/tower-client', () => ({ + TowerClient: class { + constructor() { + recorded.clients++; + return new Proxy({}, { + get: (_target, method) => (...args: unknown[]) => { + recorded.clientCalls.push(`${String(method)}(${JSON.stringify(args)})`); + return Promise.resolve(null); + }, + }); + } + }, +})); +vi.mock('../tower-starter.js', () => ({ + autoStartTower: vi.fn(async () => { recorded.autoStart++; return false; }), +})); +vi.mock('../sse-client.js', () => ({ + SSEClient: class { + constructor() { recorded.sse++; } + onEvent() { return { dispose: () => {} }; } + connect() {} + dispose() {} + }, +})); +vi.mock('../auth-wrapper.js', () => ({ + AuthWrapper: class { + initialize = vi.fn(async () => {}); + getKeySync = () => null; + }, +})); + +const { ConnectionManager } = await import('../connection-manager.js'); +const { OverviewCache } = await import('../views/overview-data.js'); +const { TowerFleetCache } = await import('../views/tower-cache.js'); +const { CockpitProvider, cockpitConnectionMode } = await import('../views/cockpit.js'); +const { OverviewRefreshGate } = await import('../views/overview-refresh-gate.js'); +const { activationPolicy, decideActivationTier } = await import('../ide-mode.js'); + +const fetchSpy = vi.fn(async () => { throw new Error('a dormant window must not fetch'); }); + +beforeEach(() => { + recorded.clients = 0; + recorded.clientCalls = []; + recorded.sse = 0; + recorded.autoStart = 0; + fetchSpy.mockClear(); + vi.stubGlobal('fetch', fetchSpy); + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +function fakeView() { + const listeners: Array<(e: unknown) => void> = []; + const view = { + visible: false, + onDidChangeVisibility: (l: (e: unknown) => void) => { listeners.push(l); return { dispose() {} }; }, + show: () => { view.visible = true; listeners.forEach(l => l({ visible: true })); }, + }; + return view; +} + +describe('a dormant window with the Cockpit shown (#1144)', () => { + it('makes no Tower request: no client, no SSE, no auto-start, no fetch', async () => { + const tier = decideActivationTier({ ideMode: false, hasCodevWorkspace: false }); + expect(tier).toBe('dormant'); + const policy = activationPolicy(tier); + expect(policy.initializeConnection).toBe(false); + + // What activate() builds; `connectionManager.initialize()` is never called for this policy. + const connectionManager = new ConnectionManager({ secrets: {} } as never, { appendLine: vi.fn() } as never); + const overviewCache = new OverviewCache(connectionManager); + const towerCache = new TowerFleetCache(connectionManager); + const cockpit = new CockpitProvider({ + connectionManager, + towerCache, + overviewCache, + diffCache: { getDiff: async () => { throw new Error('no diff in a dormant window'); } } as never, + builderWorktreeWindow: false, + connection: cockpitConnectionMode(policy.initializeConnection, true), + }); + const cockpitView = fakeView(); + const gate = new OverviewRefreshGate( + [cockpitView], + () => 60, + () => { if (connectionManager.getState() === 'connected') { void overviewCache.refresh(); } }, + () => { void overviewCache.refresh(); }, + ); + gate.wire(); + gate.reconcile(); + + // The user opens the Cockpit: the refresh gate starts and resumes with an immediate refresh. + cockpitView.show(); + expect(gate.isRunning()).toBe(true); + + // VS Code renders it. + const [root] = await cockpit.getChildren(); + const rows = (await cockpit.getChildren(root)).map(n => cockpit.getTreeItem(n)); + expect(rows.map(r => r.label)).toEqual(['Not connected to Tower']); + expect(rows[0].command).toEqual({ command: 'workbench.action.files.openFolder', title: 'Open Folder' }); + + // The title-bar Refresh (`codev.cockpit.refresh`), then every poll timer, several times over. + await Promise.all([overviewCache.refresh(), towerCache.refresh()]); + await vi.advanceTimersByTimeAsync(5 * 60_000); + + expect(connectionManager.getState()).toBe('disconnected'); + expect(connectionManager.getClient()).toBeNull(); + expect(recorded).toEqual({ clients: 0, clientCalls: [], sse: 0, autoStart: 0 }); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(towerCache.isLoaded()).toBe(false); + expect(overviewCache.getData()).toBeNull(); + + gate.dispose(); + towerCache.dispose(); + overviewCache.dispose(); + cockpit.dispose(); + }); + + it('the recording mocks do see a window that connects (the control)', async () => { + const connectionManager = new ConnectionManager({ secrets: {} } as never, { appendLine: vi.fn() } as never); + const initializing = connectionManager.initialize(); + await vi.advanceTimersByTimeAsync(0); + await initializing; + expect(recorded.clients).toBe(1); + expect(recorded.clientCalls.some(call => call.startsWith('getHealth('))).toBe(true); + connectionManager.dispose(); + }); +}); diff --git a/apps/vscode/src/__tests__/cockpit-provider.test.ts b/apps/vscode/src/__tests__/cockpit-provider.test.ts index 4dc5290c8..66ac76e3f 100644 --- a/apps/vscode/src/__tests__/cockpit-provider.test.ts +++ b/apps/vscode/src/__tests__/cockpit-provider.test.ts @@ -65,7 +65,7 @@ vi.mock('vscode', () => { }; }); -const { CockpitProvider, COCKPIT_IDS, cockpitScope } = await import('../views/cockpit.js'); +const { CockpitProvider, COCKPIT_IDS, cockpitScope, cockpitConnectionMode } = await import('../views/cockpit.js'); const { TowerProvider, OPEN_WORKSPACE_COMMAND } = await import('../views/tower.js'); const { BuildersProvider } = await import('../views/builders.js'); const { REMOTE_CONTEXT } = await import('../views/architect-tree.js'); @@ -173,7 +173,7 @@ interface WorldOptions { windowPath?: string | null; state?: ConnectionState; worktreeWindow?: boolean; - connects?: boolean; + connection?: 'auto' | 'manual' | 'none'; } /** The mutable state the fakes read, and the events the Cockpit subscribes to. */ @@ -222,7 +222,7 @@ function world(opts: WorldOptions = {}): World { } as never, diffCache: DIFFS, builderWorktreeWindow: opts.worktreeWindow ?? false, - connects: opts.connects ?? true, + connection: opts.connection ?? 'auto', }); return w; } @@ -361,11 +361,39 @@ describe('Tower root and its state rows', () => { expect(labelOf(w.provider, (await towerRows(w.provider))[0])).toBe('Not connected to Tower'); }); - it('says Not connected, with no dead Reconnect, in a window that never connects', async () => { - const w = world({ loaded: false, state: 'disconnected', connects: false }); + it('says Not connected, with the reason and Open Folder instead of a dead Reconnect, in a window that never connects', async () => { + const w = world({ loaded: false, state: 'disconnected', connection: 'none' }); const row = item(w.provider, (await towerRows(w.provider))[0]); expect(row.label).toBe('Not connected to Tower'); - expect(row.command).toBeUndefined(); + expect(row.tooltip).toMatch(/^This window has no Codev workspace, so it does not connect to Tower\./); + expect(row.command).toEqual({ command: 'workbench.action.files.openFolder', title: 'Open Folder' }); + }); + + it('with codev.autoConnect off, says Not connected with Reconnect until an attempt runs, then Connecting…', async () => { + const w = world({ loaded: false, state: 'disconnected', connection: 'manual' }); + const row = async () => item(w.provider, (await towerRows(w.provider))[0]); + expect(await row()).toMatchObject({ + label: 'Not connected to Tower', + tooltip: 'Automatic connection is off (codev.autoConnect). Click to connect to Tower.', + command: { command: 'codev.reconnect', title: 'Reconnect to Tower' }, + }); + // Reconnect runs: ConnectionManager goes disconnected → connecting. + w.setState('connecting'); + expect((await row()).label).toBe('Connecting to Tower…'); + // That attempt fails: the ordinary not-connected row, retrying in the background. + w.setState('disconnected'); + expect(await row()).toMatchObject({ + label: 'Not connected to Tower', + tooltip: 'Click to reconnect to Tower now. Codev keeps retrying in the background.', + command: { command: 'codev.reconnect', title: 'Reconnect to Tower' }, + }); + }); + + it('derives the connection mode from the activation policy and codev.autoConnect', () => { + expect(cockpitConnectionMode(true, true)).toBe('auto'); + expect(cockpitConnectionMode(true, false)).toBe('manual'); + expect(cockpitConnectionMode(false, true)).toBe('none'); + expect(cockpitConnectionMode(false, false)).toBe('none'); }); it('says No workspaces registered when Tower lists none', async () => { diff --git a/apps/vscode/src/__tests__/cockpit-wiring.test.ts b/apps/vscode/src/__tests__/cockpit-wiring.test.ts index 95ad26672..8cb394d22 100644 --- a/apps/vscode/src/__tests__/cockpit-wiring.test.ts +++ b/apps/vscode/src/__tests__/cockpit-wiring.test.ts @@ -144,7 +144,7 @@ function setup(opts: { worktreeWindow?: boolean; agentsVisible?: boolean; cockpi overviewCache: overviewCache as never, diffCache: DIFFS, builderWorktreeWindow: opts.worktreeWindow ?? false, - connects: true, + connection: 'auto', }); const agentsView = fakeView(opts.agentsVisible ?? false); const cockpitView = fakeView(opts.cockpitVisible ?? false); @@ -367,6 +367,31 @@ describe('the activity badge', () => { expect(cockpitView.badge).toBeUndefined(); }); + it('clears on a disconnect and repaints on reconnect, though the overview keeps its data', () => { + const { agentsView, cockpitView, hosts } = setup(); + // What extension.ts's `updateActivityBadge` does, driven by the connection state alone. + let state = 'connected'; + const update = () => hosts.setBadge(workspaceActivityBadge(blocked, { connected: state === 'connected', builderWorktreeWindow: false })); + update(); + expect(agentsView.badge?.value).toBe(1); + expect(cockpitView.badge?.value).toBe(1); + state = 'reconnecting'; + update(); + expect(agentsView.badge).toBeUndefined(); + expect(cockpitView.badge).toBeUndefined(); + state = 'connected'; + update(); + expect(cockpitView.badge?.value).toBe(1); + }); + + it('extension.ts repaints the badge on every connection-state change', () => { + expect(EXT_SRC).toMatch(/context\.subscriptions\.push\(connectionManager\.onStateChange\(\(\) => updateActivityBadge\(\)\)\);/); + }); + + it('extension.ts gives the Cockpit its connection mode from the policy and codev.autoConnect', () => { + expect(EXT_SRC).toMatch(/connection: cockpitConnectionMode\(\s*policy\.initializeConnection,\s*vscode\.workspace\.getConfiguration\('codev'\)\.get\('autoConnect', true\),\s*\),/); + }); + it('is suppressed when disconnected, with no data, and in a builder-worktree window', () => { expect(workspaceActivityBadge(blocked, { connected: false, builderWorktreeWindow: false })).toBeUndefined(); expect(workspaceActivityBadge(null, { connected: true, builderWorktreeWindow: false })).toBeUndefined(); diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index 0b1520d99..7c8d89eff 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -65,7 +65,7 @@ import { readBuildersFileViewAsTree } from './builders-config.js'; import { deriveAttention, isIdleWaiting } from '@cluesmith/codev-sdk/builder-helpers'; import { BuildersProvider, runBuilderRowClick, agentTargetIsFocused, agentCycleAttemptOrder, type AgentTarget } from './views/builders.js'; import { AgentTreeHosts } from './views/agent-tree-hosts.js'; -import { CockpitProvider, COCKPIT_VIEW_ID, type CockpitNode } from './views/cockpit.js'; +import { CockpitProvider, COCKPIT_VIEW_ID, cockpitConnectionMode, type CockpitNode } from './views/cockpit.js'; import { OverviewRefreshGate } from './views/overview-refresh-gate.js'; // Codev Tower (#1566): the cross-workspace navigation hub — its own activity-bar container. import { TowerFleetCache } from './views/tower-cache.js'; @@ -642,7 +642,10 @@ export async function activate(context: vscode.ExtensionContext) { overviewCache, diffCache: builderDiffCache, builderWorktreeWindow: isBuilderWorktreeWindow, - connects: policy.initializeConnection, + connection: cockpitConnectionMode( + policy.initializeConnection, + vscode.workspace.getConfiguration('codev').get('autoConnect', true), + ), }); const cockpitView: vscode.TreeView = vscode.window.createTreeView(COCKPIT_VIEW_ID, { treeDataProvider: cockpitProvider }); // Builders accordion (#913), row-click expand, follow-reveals, the @@ -678,6 +681,10 @@ export async function activate(context: vscode.ExtensionContext) { // Seed the badge so it's correct immediately if overview data is already // cached, instead of waiting for the next onDidChange tick. updateActivityBadge(); + // And follow the connection: `OverviewCache` keeps its last-known data and + // emits nothing on a disconnect, so without this both buttons would keep a + // stale badge through a Tower outage. + context.subscriptions.push(connectionManager.onStateChange(() => updateActivityBadge())); const teamProvider = new TeamProvider(connectionManager); // A tree view (not a bare provider registration) so the provider can skip // fetches while the Team view is hidden (#1919). diff --git a/apps/vscode/src/views/cockpit.ts b/apps/vscode/src/views/cockpit.ts index d86f46a12..8d5949f2b 100644 --- a/apps/vscode/src/views/cockpit.ts +++ b/apps/vscode/src/views/cockpit.ts @@ -52,10 +52,27 @@ export interface CockpitProviderOptions { */ builderWorktreeWindow: boolean; /** - * Whether this window connects to Tower at all. A dormant window (guest mode, no Codev - * workspace, #1144) never does, so it says *Not connected* rather than *Connecting…* forever. + * How this window connects to Tower, decided at activation: + * - `auto`: `ConnectionManager.initialize()` makes the first attempt by itself; + * - `manual`: `codev.autoConnect` is off, so no attempt starts until *Reconnect*; + * - `none`: a dormant window (guest mode, no Codev workspace, #1144) never connects. + * + * Only `auto` may say *Connecting…* before any attempt has started; the others would say it + * forever. */ - connects: boolean; + connection: CockpitConnectionMode; +} + +/** See `CockpitProviderOptions.connection`. */ +export type CockpitConnectionMode = 'auto' | 'manual' | 'none'; + +/** + * The window's connection mode, from the activation policy's `initializeConnection` and the + * `codev.autoConnect` setting `ConnectionManager.initialize()` reads at the same moment. + */ +export function cockpitConnectionMode(initializeConnection: boolean, autoConnect: boolean): CockpitConnectionMode { + if (!initializeConnection) { return 'none'; } + return autoConnect ? 'auto' : 'manual'; } /** One workspace's row builder, and the workspace as it was last listed. */ @@ -259,26 +276,40 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac } /** - * *Connecting to Tower…* until an attempt has failed (also while connected but before the first - * fleet load lands); *Not connected to Tower* after one, with *Reconnect* on click. - * `ConnectionManager` keeps retrying with backoff, so this never claims it gave up. + * *Connecting to Tower…* during the first attempt (also while connected but before the first + * fleet load lands); *Not connected to Tower* once one has failed, with *Reconnect* on click. + * `ConnectionManager` keeps retrying with backoff, so this never claims it gave up. With + * `codev.autoConnect` off no attempt starts by itself, so the row is *Not connected* (with + * *Reconnect*) until one does. */ private connectionStateRow(): CockpitOwnNode { - const { connectionManager, connects } = this.options; - if (!connects) { + const { connectionManager, connection } = this.options; + if (connection === 'none') { + // A dormant window stays as inert as if Codev never activated (#1144): no connection, ever. + // The row says why and offers the Agents view's welcome action for such a window. return { kind: 'message', text: 'Not connected to Tower', icon: 'debug-disconnect', - tooltip: 'This window has no Codev workspace, so it does not connect to Tower.', + tooltip: 'This window has no Codev workspace, so it does not connect to Tower. ' + + 'Click to open a folder containing a Codev project. ' + + 'To set up Codev in a project, run `codev init` in its root.', + command: { command: 'workbench.action.files.openFolder', title: 'Open Folder' }, }; } - if (connectionManager.getState() === 'connected' || !this.attemptFailed) { + const state = connectionManager.getState(); + // Connected but the fleet has not loaded yet; or the first attempt is under way (`auto` makes + // one by itself; `manual` once *Reconnect* runs). + const firstAttempt = !this.attemptFailed && (state === 'connecting' || connection === 'auto'); + if (state === 'connected' || firstAttempt) { return { kind: 'message', text: 'Connecting to Tower…', icon: 'sync~spin' }; } + const tooltip = this.attemptFailed + ? 'Click to reconnect to Tower now. Codev keeps retrying in the background.' + : 'Automatic connection is off (codev.autoConnect). Click to connect to Tower.'; return { kind: 'message', text: 'Not connected to Tower', icon: 'debug-disconnect', - tooltip: 'Click to reconnect to Tower now. Codev keeps retrying in the background.', + tooltip, command: { command: 'codev.reconnect', title: 'Reconnect to Tower' }, }; } @@ -362,8 +393,12 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac * is *marked* current, yet opening it must still reach the parent's window. */ private navigateTarget(scope: string): WorkspaceTarget { - const ws = this.trees.get(scope)!.ws; - return { ...targetOf(ws), isCurrent: false }; + // `treeFor` stores the entry before building any row, so a miss is a routing bug: say so. + const entry = this.trees.get(scope); + if (!entry) { + throw new Error(`CockpitProvider: no workspace tree for scope '${scope}' while building a navigate row`); + } + return { ...targetOf(entry.ws), isCurrent: false }; } /** Drop the row builders of workspaces no longer active in the fleet. */ diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md new file mode 100644 index 000000000..eeb459847 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md @@ -0,0 +1,94 @@ +# Phase 4 (`cockpit_hierarchy`), iteration 1: responses to the reviews + +Codex: REQUEST_CHANGES (3 points). Claude: APPROVE (5 non-blocking notes). I checked every claim +against the code before acting on it. + +## Codex + +### 1. Non-Codev (dormant) windows cannot show the fleet: kept, by architect ruling (option A) + +The claim holds. In a dormant window (guest mode, a folder without Codev; `ide-mode.ts` tier +`dormant`), `activationPolicy('dormant').initializeConnection` is false, so `ConnectionManager` never +initialises. The Cockpit then shows *Not connected to Tower* instead of navigate-only workspace +rows. + +That inertness is deliberate and older than this spec. #1144 says a dormant window "must remain +exactly as inert as if activation had never fired: no Tower process, no UI mutation, no state +writes". Listing the fleet would mean that window connects to Tower. + +I put the conflict to the architect with three options: +- **A:** keep #1144; +- **B:** connect read-only when the Cockpit is first shown; +- **C:** connect after a click. + +The architect ruled **A**. B and C weaken #1144, so they are the owner's call, and neither is built. +The ruling, as built: +- **Dormant row.** It keeps *Not connected to Tower*, now with the reason and *Open Folder*: click + runs `workbench.action.files.openFolder`. The tooltip carries the Agents view's welcome text for + such a window (`codev init`). It never initialises the connection. +- **Where the criterion holds.** The spec's no-workspace criterion holds in the window the owner + uses without a workspace: the Codev IDE's `ide-empty` tier, which connects and shows the fleet. + For the dormant tier it is a recorded deviation. The architect noted it on issue #1963 and will + raise it at the PR gate. The approved spec is not edited; the PR description and the review state + the deviation. +- **New test, `cockpit-dormant-1144.test.ts`.** It assembles a dormant window from the real + `ConnectionManager` (never initialised), `OverviewCache`, `TowerFleetCache`, `CockpitProvider` and + `OverviewRefreshGate`. Every route to Tower is a recording mock: the SDK `TowerClient`, the SSE + client, the Tower auto-starter and global `fetch`. The test shows the Cockpit, renders it, runs + its Refresh and advances every poll timer five minutes. It asserts no client was constructed, no + client call, no SSE, no auto-start and no fetch. A control case shows the same mocks do record a + window that connects. + +### 2. The badge is not cleared when Tower disconnects: fixed + +The claim holds. `updateActivityBadge` ran only at startup and on `OverviewCache.onDidChange`. +`OverviewCache` keeps last-known-good data and emits nothing on a disconnect, so both buttons kept a +stale count through an outage. This was already true of the Codev button on `main`. + +- **Fix.** `extension.ts` now subscribes `connectionManager.onStateChange(() => updateActivityBadge())`. + The pure `workspaceActivityBadge` already returned `undefined` when not connected. +- **Tests (`cockpit-wiring.test.ts`).** A connected-with-badge → reconnecting → connected sequence + on both views, plus a source check of the subscription. +- **Effect on the existing Codev button.** This changes it: during an outage its badge now clears + rather than keeping the last count. The PR description says so, because "existing views behave as + before" is an acceptance criterion. The architect accepted the fix in place. + +### 3. `codev.autoConnect: false` leaves *Connecting to Tower…* forever: fixed + +The claim holds. With auto-connect off, `initialize()` never attempts a connection, the state stays +at its initial `disconnected`, and no event follows. + +- **Fix.** The Cockpit's `connects: boolean` became a `connection: 'auto' | 'manual' | 'none'` mode. + `cockpitConnectionMode(policy.initializeConnection, codev.autoConnect)` derives it at activation, + reading the same setting `initialize()` reads at that moment. +- **What each mode shows:** + - Only `auto` shows *Connecting…* before any attempt has started. + - `manual` shows *Not connected to Tower*, with *Reconnect* and a tooltip naming + `codev.autoConnect`, until an attempt runs. `reconnect()` moves the state from `disconnected` to + `connecting`, which shows *Connecting…*. + - A failed attempt gives the ordinary not-connected row. +- **Tests (`cockpit-provider.test.ts`).** The `manual` sequence, the mode derivation, and a source + check of the `extension.ts` wiring. +- **Mutation check.** Six mutations across the mode, the row logic and the wiring are all caught. + +## Claude (APPROVE): notes + +1. **An active workspace whose overview has no architects and no builders shows a chevron that + expands to nothing.** Agreed, and left as is. Phase 7 adds the Decisions entry under every active + workspace, so the node is never empty after that. Recorded in the thread so it is not fixed twice. +2. **The dormant-tier deviation should be recorded.** Done; see Codex 1. The architect ruled, and it + goes in the PR description and the review. +3. **`navigateTarget`'s `this.trees.get(scope)!`.** Changed, but not to the suggested fallback. The + project rule is to fail fast, not fall back. `treeFor` stores the entry before building any row, + so a miss is a routing bug, and it now throws a named error instead of a bare `TypeError`. +4. **`entryOfRow` throws for unscoped rows; return `[]` instead?** Kept as a throw. This was a + Phase 3 review decision: mis-routed rows throw (`d1714a740`). The unscoped rows are the + placeholder rows (*No changes yet*, *Diff unavailable*, *No worktree on record*). They are leaves + with no id, so VS Code calls neither `getChildren` nor `getParent` (reveal) on them. Returning + `[]` would hide a real routing bug as an empty subtree. +5. **A workspace node is a snapshot of its fleet entry.** Agreed, the impact is negligible. Each + `getChildren` call reads the live caches, and `isCurrent` and `active` rarely change. Recorded as + an observation for the Phase 5 rendered run. + +The "working tree changed during the review" warning on Claude's output refers to my own fixes for +Codex 2 and 3, made while that review was running. diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index be71b563c..2981fdcac 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -463,3 +463,38 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when - Mutation-checked, 45 mutations across the provider, the hosts, the gate, the badge, the tower extraction and the `extension.ts` wiring; every one is killed. Three survivors on the first pass (connected-before-load, pruning, `restart()`) got stronger tests. + +### Phase 4: `porch done` tests check failed (2026-11-24) + +- Ran when load was 5.90 with no vitest running. `build` passed; `tests` (`packages/codev`, 68.5 s) + failed. porch printed only npm warnings as the tail and kept no log, so the failing test names + are unknown. +- Standing order 6: no re-run. Pushed `43f34f0f4` and opened draft PR #1971. Told the architect, + with options: CI names the failures and I run those files alone; one re-run with a reporter; + or a CI-stands-in ruling. +- The branch changes nothing under `packages/`. Every change so far is in `apps/vscode`. + +### Phase 4 review, iteration 1 (2026-11-24) + +- Codex: REQUEST_CHANGES (3). Claude: APPROVE with 5 notes. Answers in + `1963-cockpit_hierarchy-iter1-rebuttals.md`. +- Architect ruling (option A) on dormant windows (guest mode, no Codev workspace). They keep #1144 + inertness: the Cockpit shows *Not connected to Tower* with the reason and *Open Folder*, and never + initialises the connection. This is a deviation from the spec's no-workspace criterion for that one + window type. The architect recorded it on #1963 and will raise it with the owner at the PR gate. + The spec is not edited. **The PR description and the review must state it.** New test: + `cockpit-dormant-1144.test.ts`, with no client, SSE, auto-start or fetch while the Cockpit is shown. +- Fixed in place: + - The badge now follows connection-state changes. **This also changes the existing Codev + button**: during an outage its badge clears instead of keeping the stale count. The PR must say + so ("existing views behave as before" is a criterion). + - `codev.autoConnect: false` no longer shows *Connecting…* forever. The Cockpit's connection mode + is now `auto`, `manual` or `none`. +- Claude's notes: + - `navigateTarget` throws a named error instead of a bare `!`. + - `entryOfRow` keeps its throw (Phase 3 decision). + - An active workspace with an empty roster shows an empty chevron until Phase 7 adds the Decisions + entry. Leave it; don't fix it twice. +- The Phase 4 `porch done` before this used the architect's one-time main-32 tests skip (GitHub + green on `43f34f0f`; `bugfix-1267-launch-loop.test.ts` passed alone, 7/7). The skip was removed + straight afterwards and is noted on PR #1971. From 8df51c2336d690838d38731d3c5a7a1a2de3df3f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:52:23 -0800 Subject: [PATCH 055/140] [Spec 1963][Phase: cockpit_hierarchy] docs: entryOfRow's throw is the builder's own Phase 3 decision, not an architect ruling --- .../1963-cockpit_hierarchy-iter1-rebuttals.md | 5 +++-- codev/state/spir-1963_thread.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md index eeb459847..c65722900 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-rebuttals.md @@ -81,8 +81,9 @@ at its initial `disconnected`, and no event follows. 3. **`navigateTarget`'s `this.trees.get(scope)!`.** Changed, but not to the suggested fallback. The project rule is to fail fast, not fall back. `treeFor` stores the entry before building any row, so a miss is a routing bug, and it now throws a named error instead of a bare `TypeError`. -4. **`entryOfRow` throws for unscoped rows; return `[]` instead?** Kept as a throw. This was a - Phase 3 review decision: mis-routed rows throw (`d1714a740`). The unscoped rows are the +4. **`entryOfRow` throws for unscoped rows; return `[]` instead?** Kept as a throw. This is my + own decision from Phase 3, the builder's, made while answering that phase's review notes: + mis-routed rows throw (`d1714a740`). It is not an architect ruling. The unscoped rows are the placeholder rows (*No changes yet*, *Diff unavailable*, *No worktree on record*). They are leaves with no id, so VS Code calls neither `getChildren` nor `getParent` (reveal) on them. Returning `[]` would hide a real routing bug as an empty subtree. diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 2981fdcac..9191490f3 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -492,7 +492,8 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when is now `auto`, `manual` or `none`. - Claude's notes: - `navigateTarget` throws a named error instead of a bare `!`. - - `entryOfRow` keeps its throw (Phase 3 decision). + - `entryOfRow` keeps its throw. That is my own Phase 3 decision, not an architect ruling; the + architect agrees (fail fast, no silent `[]`). - An active workspace with an empty roster shows an empty chevron until Phase 7 adds the Decisions entry. Leave it; don't fix it twice. - The Phase 4 `porch done` before this used the architect's one-time main-32 tests skip (GitHub From f0148bcca92e433633d67d77abeedf70fd0b62cd Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:52:27 -0800 Subject: [PATCH 056/140] chore(porch): 1963 implement re-iter (iter 2) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 387be8f1c..44ca04b9a 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -44,8 +44,8 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true +iteration: 2 +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -59,8 +59,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-verification_harness-iter1-claude.txt + - iteration: 1 + plan_phase: cockpit_hierarchy + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T08:39:22.811Z' +updated_at: '2026-11-24T08:52:27.800Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From d211f1693c60336f385db5d66889a281bc36849b Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:53:51 -0800 Subject: [PATCH 057/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 44ca04b9a..8ba44e1c0 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -72,7 +72,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T08:52:27.800Z' +updated_at: '2026-11-24T08:53:51.477Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From a3a1837bcbec764d3821d81143977d032426b2b4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:58:40 -0800 Subject: [PATCH 058/140] =?UTF-8?q?[Spec=201963][Phase:=20cockpit=5Fhierar?= =?UTF-8?q?chy]=20docs:=20thread=20=E2=80=94=20iteration=202=20approvals?= =?UTF-8?q?=20and=20notes=20carried=20to=20Phase=205?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/state/spir-1963_thread.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 9191490f3..96099b040 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -499,3 +499,22 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when - The Phase 4 `porch done` before this used the architect's one-time main-32 tests skip (GitHub green on `43f34f0f`; `bugfix-1267-launch-loop.test.ts` passed alone, 7/7). The skip was removed straight afterwards and is noted on PR #1971. + +### Phase 4 review, iteration 2 (2026-11-24): both APPROVE + +- Before the reviews, the iteration-2 `porch done` passed build (15.2 s) and the full local tests + (49.5 s) with no skip, starting at load 3.26. +- Codex APPROVE, no issues. Claude APPROVE. It verified the iteration-1 fixes against + `connection-manager.ts` and `ide-mode.ts` itself, and left non-blocking notes, carried into Phase 5: + 1. **Agent cycle in a Cockpit-only window (decide in Phase 5).** The cycle roster comes from + `buildersProvider.agentCycleOrder()`, which follows `codev.buildersGroupBy`. With the default + `stage` it holds builders only, so Cmd-cycling never lands on an architect, and its order is not + the Cockpit's top-to-bottom order. No Phase 4 criterion is broken: selection does act on Cockpit + rows. Raised with the architect. + 2. **Polish, at the start of Phase 5.** In `cockpit-provider.test.ts`, the parity `shape()` + compares `iconPath`, but the Cockpit deliberately overrides a waiting architect's icon + (`applyArchitectAttention`). Exclude `icon` for `BuilderGroupTreeItem`, as `description` already + is, or comment the fixture, so a future waiting-architect fixture doesn't read as a regression. + 3. **Polish, at the start of Phase 5.** `pruneTrees` runs only from `towerChildren()`, so departed + workspaces' builders survive while the Tower root is collapsed. That is bounded and harmless; + say so in its doc comment. From e5e9f766217198099f7572398735bfdbb68a9b03 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:58:42 -0800 Subject: [PATCH 059/140] =?UTF-8?q?chore(porch):=201963=20advance=20plan?= =?UTF-8?q?=20phase=20=E2=86=92=20cockpit=5Factions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 8ba44e1c0..ba87e64c7 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -14,10 +14,10 @@ plan_phases: status: complete - id: cockpit_hierarchy title: Cockpit button and the Tower → workspaces → architects → builders tree - status: in_progress + status: complete - id: cockpit_actions title: Placement-table actions on the hierarchy, parity mapping, increment-1 verification - status: pending + status: in_progress - id: workspace_views_package title: Shared Work/Decisions package; dashboard moved onto it unchanged status: pending @@ -30,7 +30,7 @@ plan_phases: - id: arrange_cockpit title: 'Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification' status: pending -current_plan_phase: cockpit_hierarchy +current_plan_phase: cockpit_actions gates: spec-approval: status: approved @@ -44,8 +44,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -72,7 +72,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T08:53:51.477Z' +updated_at: '2026-11-24T08:58:42.816Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -86,3 +86,5 @@ context_refreshes: - boundary: plan-phase:cockpit_hierarchy at: '2026-11-24T08:05:13.344Z' acknowledged_at: '2026-11-24T08:05:18.924Z' + - boundary: plan-phase:cockpit_actions + at: '2026-11-24T08:58:42.816Z' From cbce2b1f37b79b33263b74c179d7354722ea75c4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:58:57 -0800 Subject: [PATCH 060/140] chore(porch): 1963 acknowledge context refresh --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index ba87e64c7..dd63e110b 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -72,7 +72,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-cockpit_hierarchy-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T08:58:42.816Z' +updated_at: '2026-11-24T08:58:57.075Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -88,3 +88,4 @@ context_refreshes: acknowledged_at: '2026-11-24T08:05:18.924Z' - boundary: plan-phase:cockpit_actions at: '2026-11-24T08:58:42.816Z' + acknowledged_at: '2026-11-24T08:58:57.074Z' From 8cecfe8480b05b7194b4f16174c66fd973f89365 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 00:59:26 -0800 Subject: [PATCH 061/140] [Spec 1963] Thread: architect ruling (b) on the agent cycle for Phase 5 --- codev/state/spir-1963_thread.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 96099b040..b70db8679 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -518,3 +518,20 @@ Separately, the extension activates `alpha` on the isolated Tower by itself when 3. **Polish, at the start of Phase 5.** `pruneTrees` runs only from `towerChildren()`, so departed workspaces' builders survive while the Tower root is collapsed. That is bounded and harmless; say so in its doc comment. + +### Architect ruling for Phase 5: agent cycle (2026-11-24T08:59Z) + +- **Option (b).** The approved spec already says "tree behaviours follow the view a row is in", so + this needs no owner ruling. +- **Cockpit visible, Agents view not:** the agent cycle runs in the Cockpit's own visible order, + architects and their builders. The roster is **this window's workspace only**; other workspaces' + rows never enter the cycle. +- **Agents view visible, or neither visible:** the existing order from + `buildersProvider.agentCycleOrder()` applies **unchanged**. Not (c): existing behaviour must not + move. +- **To do in Phase 5:** + - tests for all three cases (Cockpit-only visible, Agents visible, neither visible); + - one line in the PR #1971 description. +- Also opening Phase 5, from Claude's iteration-2 notes (see above): + - the parity `shape()` icon boundary; + - the `pruneTrees` doc comment. From 063a4718767b2a627b28f97c7fa3806c43f632e1 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 01:12:55 -0800 Subject: [PATCH 062/140] =?UTF-8?q?[Spec=201963][Phase:=20cockpit=5Faction?= =?UTF-8?q?s]=20feat:=20Cockpit=20row=20actions=20=E2=80=94=20menus,=20wor?= =?UTF-8?q?kspace-row=20context=20values,=20held=20worktree=20config,=20ag?= =?UTF-8?q?ent=20cycle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 5a of Phase 5: - package.json: Cockpit view/item/context entries (the 12 Agents builder entries, Remove Architect on sibling rows only, Tower's Open/Deactivate, and this window's workspace row: inline Spawn Builder / New Shell / Add Architect, context menu with those plus Open Web Interface, Start/Stop Dev and Open Dev URL); title-bar accordion and file-tree toggles; new codev.cockpit.openWebInterface; icons for spawnBuilder and newShell. - workspace.ts: buildDashboardUrl and workspaceDevSlot extracted, shared by the Workspace view (output unchanged) and the Cockpit. - cockpit.ts: cockpit-workspace-current/-parent context values with the dev-slot and -devurls suffixes; the worktree config is fetched once and held, dropped on codev-config-updated, a connection-state change or a workspace change; re-renders on dev terminals, codev-config-updated and architects-updated; agentCycleOrder() in the Cockpit's own order. - Agent cycle, architect ruling (b): agentCycleRoster uses the Cockpit's order while it is visible, acts here and the Agents view is not visible; otherwise the Agents order, unchanged. - commands/command-args.ts: the argument resolvers moved out of extension.ts; Remove Architect resolves a Cockpit architect row to its groupName. openDevUrl takes the raw argument and falls through to its QuickPick for a row. - Phase 4 notes: parity shape() ignores the architect-row icon; pruneTrees doc comment. --- apps/vscode/package.json | 165 +++++++++++- .../__tests__/cockpit-dormant-1144.test.ts | 4 + .../src/__tests__/cockpit-provider.test.ts | 251 +++++++++++++++++- .../src/__tests__/cockpit-wiring.test.ts | 53 +++- .../vscode/src/__tests__/command-args.test.ts | 67 +++++ .../extension-architect-commands.test.ts | 11 +- .../src/__tests__/workspace-dev-slot.test.ts | 134 ++++++++++ apps/vscode/src/commands/command-args.ts | 85 ++++++ apps/vscode/src/commands/open-dev-url.ts | 5 +- apps/vscode/src/extension.ts | 111 +++----- apps/vscode/src/views/agent-tree-hosts.ts | 19 ++ apps/vscode/src/views/cockpit.ts | 138 +++++++++- apps/vscode/src/views/workspace.ts | 100 ++++--- 13 files changed, 1013 insertions(+), 130 deletions(-) create mode 100644 apps/vscode/src/__tests__/command-args.test.ts create mode 100644 apps/vscode/src/__tests__/workspace-dev-slot.test.ts create mode 100644 apps/vscode/src/commands/command-args.ts diff --git a/apps/vscode/package.json b/apps/vscode/package.json index 6e2ffb771..2a6d27e0d 100644 --- a/apps/vscode/package.json +++ b/apps/vscode/package.json @@ -96,6 +96,11 @@ "title": "Codev: Refresh Cockpit", "icon": "$(refresh)" }, + { + "command": "codev.cockpit.openWebInterface", + "title": "Codev: Open Web Interface", + "icon": "$(globe)" + }, { "command": "codev.helloWorld", "title": "Codev: Show Connection State" @@ -170,11 +175,13 @@ }, { "command": "codev.newShell", - "title": "Codev: New Shell" + "title": "Codev: New Shell", + "icon": "$(terminal-new)" }, { "command": "codev.spawnBuilder", - "title": "Codev: Spawn Builder" + "title": "Codev: Spawn Builder", + "icon": "$(rocket)" }, { "command": "codev.sendMessage", @@ -726,6 +733,10 @@ { "command": "codev.dev.switchTarget", "when": "codev.hasDevCommand" + }, + { + "command": "codev.cockpit.openWebInterface", + "when": "false" } ], "editor/context": [ @@ -865,6 +876,136 @@ "command": "codev.copyBacklogIssueNumber", "when": "view == codev.backlog && viewItem == backlog-item", "group": "1_primary@4" + }, + { + "command": "codev.approveGate", + "when": "view == codev.cockpit && viewItem =~ /^blocked-builder-/", + "group": "inline@1" + }, + { + "command": "codev.openBuilderById", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "1_primary@1" + }, + { + "command": "codev.approveGate", + "when": "view == codev.cockpit && viewItem =~ /^blocked-builder-/", + "group": "1_primary@2" + }, + { + "command": "codev.viewSpecFile", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir)(-review)?$/", + "group": "1_primary@3" + }, + { + "command": "codev.viewPlanFile", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir|pir)(-review)?$/", + "group": "1_primary@4" + }, + { + "command": "codev.viewReviewFile", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-((spir|aspir|air)(-review)?|pir-review)$/", + "group": "1_primary@5" + }, + { + "command": "codev.viewDiff", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "2_worktree@0" + }, + { + "command": "codev.openWorktreeWindow", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "2_worktree@1" + }, + { + "command": "codev.openWorktreeFolder", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "2_worktree@2" + }, + { + "command": "codev.runWorktreeSetup", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "3_dev@1" + }, + { + "command": "codev.runWorktreeDev", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/ && codev.hasDevCommand", + "group": "3_dev@2" + }, + { + "command": "codev.stopWorktreeDev", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/ && codev.hasDevCommand", + "group": "3_dev@3" + }, + { + "command": "codev.removeArchitect", + "when": "view == codev.cockpit && viewItem == cockpit-architect-sibling", + "group": "1_primary@1" + }, + { + "command": "codev.tower.openWorkspace", + "when": "view == codev.cockpit && viewItem =~ /^tower-workspace-(active|dormant)$/", + "group": "inline@1" + }, + { + "command": "codev.tower.deactivateWorkspace", + "when": "view == codev.cockpit && viewItem == tower-workspace-active", + "group": "inline@2" + }, + { + "command": "codev.spawnBuilder", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "inline@3" + }, + { + "command": "codev.newShell", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "inline@4" + }, + { + "command": "codev.addArchitect", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "inline@5" + }, + { + "command": "codev.spawnBuilder", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "1_workspace@1" + }, + { + "command": "codev.newShell", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "1_workspace@2" + }, + { + "command": "codev.addArchitect", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "1_workspace@3" + }, + { + "command": "codev.cockpit.openWebInterface", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)(-.*)?$/", + "group": "2_web@1" + }, + { + "command": "codev.runWorkspaceDev", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)-dev-start(-devurls)?$/", + "group": "3_dev@1" + }, + { + "command": "codev.stopWorkspaceDev", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)-dev-stop(-devurls)?$/", + "group": "3_dev@1" + }, + { + "command": "codev.stopWorktreeDev", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)-dev-stop-other(-devurls)?$/", + "group": "3_dev@1" + }, + { + "command": "codev.openDevUrl", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)(-.*)?-devurls$/", + "group": "3_dev@2" } ], "view/title": [ @@ -878,6 +1019,26 @@ "when": "view == codev.cockpit", "group": "navigation@1" }, + { + "command": "codev.disableBuildersAutoCollapse", + "when": "view == codev.cockpit && codev.buildersAutoCollapse", + "group": "navigation@2" + }, + { + "command": "codev.enableBuildersAutoCollapse", + "when": "view == codev.cockpit && !codev.buildersAutoCollapse", + "group": "navigation@2" + }, + { + "command": "codev.disableBuildersFileTreeMode", + "when": "view == codev.cockpit && codev.buildersFileViewAsTree", + "group": "navigation@3" + }, + { + "command": "codev.enableBuildersFileTreeMode", + "when": "view == codev.cockpit && !codev.buildersFileViewAsTree", + "group": "navigation@3" + }, { "command": "codev.refreshOverview", "when": "view == codev.agents", diff --git a/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts b/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts index 193cb8281..622064ac7 100644 --- a/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts +++ b/apps/vscode/src/__tests__/cockpit-dormant-1144.test.ts @@ -88,6 +88,7 @@ const { ConnectionManager } = await import('../connection-manager.js'); const { OverviewCache } = await import('../views/overview-data.js'); const { TowerFleetCache } = await import('../views/tower-cache.js'); const { CockpitProvider, cockpitConnectionMode } = await import('../views/cockpit.js'); +const { loadWorktreeConfig } = await import('../load-worktree-config.js'); const { OverviewRefreshGate } = await import('../views/overview-refresh-gate.js'); const { activationPolicy, decideActivationTier } = await import('../ide-mode.js'); @@ -131,6 +132,9 @@ describe('a dormant window with the Cockpit shown (#1144)', () => { const towerCache = new TowerFleetCache(connectionManager); const cockpit = new CockpitProvider({ connectionManager, + terminalManager: { listDevTerminals: () => [], onDidChangeDevTerminals: () => ({ dispose() {} }) }, + // The real loader: it must make no request in a window that never connects. + loadWorktreeConfig: () => loadWorktreeConfig(connectionManager), towerCache, overviewCache, diffCache: { getDiff: async () => { throw new Error('no diff in a dormant window'); } } as never, diff --git a/apps/vscode/src/__tests__/cockpit-provider.test.ts b/apps/vscode/src/__tests__/cockpit-provider.test.ts index 66ac76e3f..80bea07c0 100644 --- a/apps/vscode/src/__tests__/cockpit-provider.test.ts +++ b/apps/vscode/src/__tests__/cockpit-provider.test.ts @@ -16,6 +16,8 @@ import type { TowerWorkspace } from '@cluesmith/codev-sdk/tower-client'; import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; import type { FleetEntry } from '../views/tower-cache.js'; import type { BuilderFileChange } from '../views/builder-diff-cache.js'; +import type { ResolvedWorktreeConfig } from '../load-worktree-config.js'; +import type { AgentTarget } from '../views/architect-tree.js'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -65,7 +67,7 @@ vi.mock('vscode', () => { }; }); -const { CockpitProvider, COCKPIT_IDS, cockpitScope, cockpitConnectionMode } = await import('../views/cockpit.js'); +const { CockpitProvider, COCKPIT_IDS, cockpitScope, cockpitConnectionMode, cockpitWorkspaceContext } = await import('../views/cockpit.js'); const { TowerProvider, OPEN_WORKSPACE_COMMAND } = await import('../views/tower.js'); const { BuildersProvider } = await import('../views/builders.js'); const { REMOTE_CONTEXT } = await import('../views/architect-tree.js'); @@ -174,6 +176,10 @@ interface WorldOptions { state?: ConnectionState; worktreeWindow?: boolean; connection?: 'auto' | 'manual' | 'none'; + /** The folder this window is rooted at (a worktree's own path in a builder-worktree window). */ + windowRoot?: string | null; + config?: ResolvedWorktreeConfig | null; + devs?: Array<{ builderId: string; terminalId: string }>; } /** The mutable state the fakes read, and the events the Cockpit subscribes to. */ @@ -183,15 +189,33 @@ interface World { here: OverviewData | null; windowPath: string | null; state: ConnectionState; + /** What the next `loadWorktreeConfig` resolves to. */ + config: ResolvedWorktreeConfig | null; + /** The dev terminals running now. */ + devs: Array<{ builderId: string; terminalId: string }>; + loadWorktreeConfig: ReturnType; + /** How many times the Cockpit asked its view to redraw. */ + redraws(): number; fireFleet(): void; fireOverview(): void; setState(state: ConnectionState): void; + /** Deliver one SSE envelope of this `type`, as Tower sends it (JSON in `data`, no event name). */ + fireSSE(type: string): void; + /** Deliver one SSE event with this raw `data`. */ + fireRawSSE(data: string): void; + fireDevTerminals(): void; provider: Provider; } /** A Cockpit over fake caches whose state a test can change. */ function world(opts: WorldOptions = {}): World { - const listeners = { fleet: [] as Array<() => void>, overview: [] as Array<() => void>, state: [] as Array<(s: string) => void> }; + const listeners = { + fleet: [] as Array<() => void>, + overview: [] as Array<() => void>, + state: [] as Array<(s: string) => void>, + sse: [] as Array<(e: { type: string; data: string }) => void>, + devs: [] as Array<() => void>, + }; const sub = (list: T[], l: T) => { list.push(l); return { dispose() { list.splice(list.indexOf(l), 1); } }; }; const w: World = { fleet: opts.fleet ?? [], @@ -199,17 +223,32 @@ function world(opts: WorldOptions = {}): World { here: opts.here === undefined ? null : opts.here, windowPath: opts.windowPath === undefined ? HERE : opts.windowPath, state: opts.state ?? 'connected', + config: opts.config ?? null, + devs: opts.devs ?? [], + loadWorktreeConfig: vi.fn(async () => w.config), + redraws: () => redraws, fireFleet: () => listeners.fleet.forEach(l => l()), fireOverview: () => listeners.overview.forEach(l => l()), setState: (s: ConnectionState) => { w.state = s; listeners.state.forEach(l => l(s)); }, + fireSSE: (type: string) => w.fireRawSSE(JSON.stringify({ type })), + fireRawSSE: (data: string) => listeners.sse.forEach(l => l({ type: '', data })), + fireDevTerminals: () => listeners.devs.forEach(l => l()), provider: undefined as unknown as Provider, }; + let redraws = 0; w.provider = new CockpitProvider({ connectionManager: { getState: () => w.state, getWorkspacePath: () => w.windowPath, + getWindowRoot: () => (opts.windowRoot === undefined ? w.windowPath : opts.windowRoot), onStateChange: (l: (s: string) => void) => sub(listeners.state, l), + onSSEEvent: (l: (e: { type: string; data: string }) => void) => sub(listeners.sse, l), } as never, + terminalManager: { + listDevTerminals: () => w.devs, + onDidChangeDevTerminals: (l: () => void) => sub(listeners.devs, l), + }, + loadWorktreeConfig: w.loadWorktreeConfig as never, towerCache: { getFleet: () => w.fleet, isLoaded: () => w.loaded, @@ -224,6 +263,7 @@ function world(opts: WorldOptions = {}): World { builderWorktreeWindow: opts.worktreeWindow ?? false, connection: opts.connection ?? 'auto', }); + w.provider.onDidChangeTreeData(() => { redraws += 1; }); return w; } @@ -302,14 +342,20 @@ function stripScope(id: string | undefined, scope: string): string | undefined { return id.slice(scope.length); } -/** A row's rendered shape, minus the description (the Cockpit adds attention counts there). */ +/** + * A row's rendered shape, minus what the Cockpit's `attention` option may change on purpose: the + * description (attention counts) on every row, and an architect row's icon (a waiting architect + * shows its wait glyph, `applyArchitectAttention`). Builder and file rows keep the Agents icon. + */ function shape(row: vscode.TreeItem, scope: string) { const command = row.command as { command: string; arguments?: unknown[] } | undefined; + let icon: vscode.TreeItem['iconPath'] | '' = row.iconPath; + if (row instanceof BuilderGroupTreeItem) { icon = ''; } return { id: stripScope(row.id, scope), label: row.label, state: row.collapsibleState, - icon: row.iconPath, + icon, tooltip: row.tooltip, command: command?.command, commandArgs: command?.arguments?.map(a => (a === row ? '' : a)), @@ -431,7 +477,12 @@ describe('workspace rows', () => { const visible = (row: vscode.TreeItem) => ({ label: row.label, description: row.description, icon: row.iconPath, tooltip: row.tooltip, contextValue: row.contextValue, }); - expect(cockpitTop.map(visible)).toEqual(towerTop.map(visible)); + // Every row matches, except that this window's own row carries the Cockpit's own value (Phase 5: + // its menu offers this window's workspace actions; the Tower view's current row has none). + const towerShown = towerTop.map(visible); + towerShown[2] = { ...towerShown[2], contextValue: 'cockpit-workspace-current' }; + expect(towerTop[2].contextValue).toBe('tower-workspace-active-current'); + expect(cockpitTop.map(visible)).toEqual(towerShown); // Disambiguated labels, as in the Tower view, and the current marker on this window's own. expect(cockpitTop.map(r => r.label)).toEqual(['marketmaker', 'elsewhere/codev', 'work/codev', 'zeta', 'Dormant (2)']); expect(cockpitTop[2].description).toBe('current'); @@ -835,3 +886,193 @@ describe('re-render signals and per-view accordion state', () => { await expect(w.provider.getChildren(stray)).rejects.toThrow(/carries no workspace scope/); }); }); + +// ── Phase 5: this window's workspace row, its held config and its signals ───── + +function config(overrides: Partial = {}): ResolvedWorktreeConfig { + return { symlinks: [], postSpawn: [], devCommand: null, devUrls: [], ...overrides }; +} + +const WITH_DEV = config({ devCommand: 'pnpm dev' }); +const WITH_URLS = config({ devCommand: 'pnpm dev', devUrls: [{ label: 'App', url: 'http://localhost:3000' }] }); +const WORKTREE_ROOT = `${HERE}/.builders/spir-7`; + +/** The `contextValue` of every top-level workspace row, by label (Dormant's rows included). */ +async function workspaceContexts(p: Provider): Promise> { + const out: Record = {}; + for (const n of await towerRows(p)) { + const row = item(p, n); + if (row.id === COCKPIT_IDS.dormant) { + for (const d of await p.getChildren(n)) { out[labelOf(p, d)] = item(p, d).contextValue; } + continue; + } + out[String(row.label)] = row.contextValue; + } + return out; +} + +const TWO = [entry(wsRow(HERE, 'codev', true), ONE), entry(wsRow(OTHER, 'marketmaker', true), MANY), entry(wsRow('/work/old', 'old', false), null)]; + +describe("this window's workspace row: what the Workspace view decides for this window", () => { + it('encodes role, dev slot and dev URLs in its context value', () => { + expect(cockpitWorkspaceContext('current', 'none', false)).toBe('cockpit-workspace-current'); + expect(cockpitWorkspaceContext('current', 'start', false)).toBe('cockpit-workspace-current-dev-start'); + expect(cockpitWorkspaceContext('current', 'stop', true)).toBe('cockpit-workspace-current-dev-stop-devurls'); + expect(cockpitWorkspaceContext('parent', 'stop-other', false)).toBe('cockpit-workspace-parent-dev-stop-other'); + expect(cockpitWorkspaceContext('parent', 'none', true)).toBe('cockpit-workspace-parent-devurls'); + }); + + it('current row: no dev command, a runnable one, dev URLs; other rows keep the Tower values', async () => { + const bare = world({ fleet: TWO, here: ONE }); + expect(await workspaceContexts(bare.provider)).toEqual({ + codev: 'cockpit-workspace-current', marketmaker: 'tower-workspace-active', old: 'tower-workspace-dormant', + }); + const dev = world({ fleet: TWO, here: ONE, config: WITH_DEV }); + expect((await workspaceContexts(dev.provider)).codev).toBe('cockpit-workspace-current-dev-start'); + const urls = world({ fleet: TWO, here: ONE, config: WITH_URLS }); + expect((await workspaceContexts(urls.provider)).codev).toBe('cockpit-workspace-current-dev-start-devurls'); + // `"devCommand": ""` is no dev command, as in the Workspace view. + const blank = world({ fleet: TWO, here: ONE, config: config({ devCommand: ' ' }) }); + expect((await workspaceContexts(blank.provider)).codev).toBe('cockpit-workspace-current'); + }); + + it("current row: Stop Dev for this window's own dev, the other-target Stop Dev for anyone else's", async () => { + const own = world({ fleet: TWO, here: ONE, config: WITH_DEV, devs: [{ builderId: 'main', terminalId: 't1' }] }); + expect((await workspaceContexts(own.provider)).codev).toBe('cockpit-workspace-current-dev-stop'); + const other = world({ fleet: TWO, here: ONE, config: WITH_URLS, devs: [{ builderId: 'spir-10', terminalId: 't2' }] }); + expect((await workspaceContexts(other.provider)).codev).toBe('cockpit-workspace-current-dev-stop-other-devurls'); + }); + + it("builder-worktree window: the parent row is `parent`, with the worktree's own dev slot", async () => { + const start = world({ fleet: TWO, here: ONE, worktreeWindow: true, windowRoot: WORKTREE_ROOT, config: WITH_URLS }); + expect(await workspaceContexts(start.provider)).toEqual({ + codev: 'cockpit-workspace-parent-dev-start-devurls', marketmaker: 'tower-workspace-active', old: 'tower-workspace-dormant', + }); + // The worktree's dev (target = the builder id) is this window's own. + const stop = world({ + fleet: TWO, here: ONE, worktreeWindow: true, windowRoot: WORKTREE_ROOT, config: WITH_DEV, + devs: [{ builderId: 'spir-7', terminalId: 't3' }], + }); + expect((await workspaceContexts(stop.provider)).codev).toBe('cockpit-workspace-parent-dev-stop'); + }); + + it('no-workspace window: no row is this window\'s, so none carries an own value', async () => { + const w = world({ fleet: TWO, here: null, windowPath: null, windowRoot: null, config: WITH_URLS }); + expect(await workspaceContexts(w.provider)).toEqual({ + codev: 'tower-workspace-active', marketmaker: 'tower-workspace-active', old: 'tower-workspace-dormant', + }); + }); + + it('a dormant own workspace keeps the Tower value (nothing acts on it here)', async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', false), null)], here: null, config: WITH_URLS }); + expect(await workspaceContexts(w.provider)).toEqual({ codev: 'tower-workspace-dormant' }); + }); +}); + +describe('the held worktree config: fetched once, dropped only on its own signals', () => { + it('N fleet and overview changes fetch nothing more; one codev-config-updated fetches exactly once', async () => { + const w = world({ fleet: TWO, here: ONE, config: WITH_DEV }); + await workspaceContexts(w.provider); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(1); + for (let i = 0; i < 5; i += 1) { + w.fireFleet(); + w.fireOverview(); + await workspaceContexts(w.provider); + } + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(1); + + w.config = WITH_URLS; + w.fireSSE('codev-config-updated'); + await workspaceContexts(w.provider); + await workspaceContexts(w.provider); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(2); + expect((await workspaceContexts(w.provider)).codev).toBe('cockpit-workspace-current-dev-start-devurls'); + }); + + it('a connection-state change drops it; so does a different workspace path', async () => { + const w = world({ fleet: TWO, here: ONE, config: WITH_DEV }); + await workspaceContexts(w.provider); + w.setState('reconnecting'); + w.setState('connected'); + await workspaceContexts(w.provider); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(2); + w.windowPath = OTHER; + await workspaceContexts(w.provider); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(3); + }); + + it('other envelopes, and malformed ones, fetch nothing', async () => { + const w = world({ fleet: TWO, here: ONE, config: WITH_DEV }); + await workspaceContexts(w.provider); + w.fireSSE('architects-updated'); + w.fireSSE('overview-changed'); + w.fireRawSSE('{not json'); + await workspaceContexts(w.provider); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(1); + }); + + it('concurrent renders share one request', async () => { + const w = world({ fleet: TWO, here: ONE, config: WITH_DEV }); + await Promise.all([workspaceContexts(w.provider), workspaceContexts(w.provider), workspaceContexts(w.provider)]); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(1); + }); +}); + +describe("re-renders on the Workspace view's own signals", () => { + it('redraws on a dev-terminal change and on codev-config-updated and architects-updated envelopes', () => { + const w = world({ fleet: TWO, here: ONE }); + const before = w.redraws(); + w.fireDevTerminals(); + expect(w.redraws()).toBe(before + 1); + w.fireSSE('codev-config-updated'); + expect(w.redraws()).toBe(before + 2); + w.fireSSE('architects-updated'); + expect(w.redraws()).toBe(before + 3); + }); + + it('ignores any other envelope and a malformed one', () => { + const w = world({ fleet: TWO, here: ONE }); + const before = w.redraws(); + w.fireSSE('overview-changed'); + w.fireRawSSE('not json'); + expect(w.redraws()).toBe(before); + }); + + it("Stop Dev replaces Start Dev once a dev starts from a builder's menu", async () => { + const w = world({ fleet: TWO, here: ONE, config: WITH_DEV }); + expect((await workspaceContexts(w.provider)).codev).toBe('cockpit-workspace-current-dev-start'); + const before = w.redraws(); + w.devs = [{ builderId: 'spir-10', terminalId: 't9' }]; + w.fireDevTerminals(); + expect(w.redraws()).toBe(before + 1); + expect((await workspaceContexts(w.provider)).codev).toBe('cockpit-workspace-current-dev-stop-other'); + // Stopped: back to Start, with no config fetch for any of it. + w.devs = []; + w.fireDevTerminals(); + expect((await workspaceContexts(w.provider)).codev).toBe('cockpit-workspace-current-dev-start'); + expect(w.loadWorktreeConfig).toHaveBeenCalledTimes(1); + }); +}); + +describe('the agent-cycle roster in the Cockpit\'s own order', () => { + it("is this window's architects, each followed by its builders, never another workspace's", async () => { + const w = world({ fleet: [entry(wsRow(HERE, 'codev', true), MANY), entry(wsRow(OTHER, 'marketmaker', true), ONE)], here: MANY }); + // The rendered order of this workspace's agent rows, top to bottom (Idle Architects expanded). + const rendered = (await subtree(w.provider, await workspaceNode(w.provider, 'codev'))).flatMap(({ node }): AgentTarget[] => { + if (node instanceof BuilderTreeItem) { return [{ kind: 'builder', id: node.builderId }]; } + if (node instanceof BuilderGroupTreeItem) { return [{ kind: 'architect', name: node.groupName }]; } + return []; + }); + expect(rendered.map(t => (t.kind === 'architect' ? t.name : t.id))).toEqual([ + 'main', 'spir-10', 'air-11', 'ghost', 'pir-13', 'web', 'aspir-14', 'bugfix-12', 'demos', 'reviewer', + ]); + expect(w.provider.agentCycleOrder()).toEqual(rendered); + }); + + it('is empty where nothing acts here: a builder-worktree window, and before Tower lists this workspace', () => { + const worktree = world({ fleet: [entry(wsRow(HERE, 'codev', true), MANY)], here: MANY, worktreeWindow: true }); + expect(worktree.provider.agentCycleOrder()).toEqual([]); + const unlisted = world({ fleet: [entry(wsRow(OTHER, 'marketmaker', true), MANY)], here: MANY }); + expect(unlisted.provider.agentCycleOrder()).toEqual([]); + }); +}); diff --git a/apps/vscode/src/__tests__/cockpit-wiring.test.ts b/apps/vscode/src/__tests__/cockpit-wiring.test.ts index 8cb394d22..2aae1c000 100644 --- a/apps/vscode/src/__tests__/cockpit-wiring.test.ts +++ b/apps/vscode/src/__tests__/cockpit-wiring.test.ts @@ -64,7 +64,7 @@ vi.mock('vscode', () => { }; }); -const { AgentTreeHosts } = await import('../views/agent-tree-hosts.js'); +const { AgentTreeHosts, agentCycleRoster } = await import('../views/agent-tree-hosts.js'); const { OverviewRefreshGate } = await import('../views/overview-refresh-gate.js'); const { CockpitProvider, cockpitScope } = await import('../views/cockpit.js'); const { BuildersProvider } = await import('../views/builders.js'); @@ -136,7 +136,11 @@ function setup(opts: { worktreeWindow?: boolean; agentsVisible?: boolean; cockpi const agents = new BuildersProvider(overviewCache as never, DIFFS); const fleet = [entry(wsRow(HERE, 'codev'), DATA), entry(wsRow(OTHER, 'marketmaker'), DATA)]; const cockpit = new CockpitProvider({ - connectionManager: { getState: () => 'connected', getWorkspacePath: () => HERE, onStateChange: noEvent } as never, + connectionManager: { + getState: () => 'connected', getWorkspacePath: () => HERE, getWindowRoot: () => HERE, onStateChange: noEvent, onSSEEvent: noEvent, + } as never, + terminalManager: { listDevTerminals: () => [], onDidChangeDevTerminals: noEvent }, + loadWorktreeConfig: async () => null, towerCache: { getFleet: () => fleet, isLoaded: () => true, onDidChange: noEvent, getOverview: (path: string) => fleet.find(e => e.workspace.path === path)?.overview ?? null, @@ -468,3 +472,48 @@ describe('the periodic overview refresh counts the Cockpit', () => { expect(EXT_SRC).toMatch(/\.\.\.overviewRefreshGate\.wire\(\)/); }); }); + +/** + * The agent cycle's roster (#1563) by which agent view is visible: architect ruling (b) for Spec 1963 + * Phase 5. The Agents view's default `stage` axis holds builders only; the Cockpit's own order puts + * each architect before its builders, so the two rosters tell the cases apart. + */ +describe('agent cycle: whose order the roster follows', () => { + const AGENTS_ORDER = [{ kind: 'builder', id: 'pir-1' }, { kind: 'builder', id: 'pir-2' }]; + const COCKPIT_ORDER = [{ kind: 'architect', name: 'main' }, { kind: 'builder', id: 'pir-1' }, { kind: 'builder', id: 'pir-2' }]; + + /** The roster `cycleAgentTerminal` reads, built as extension.ts builds it. */ + function roster(w: ReturnType) { + return agentCycleRoster( + { visible: w.agentsView.visible, agentCycleOrder: () => w.agents.agentCycleOrder() }, + { visible: w.cockpitView.visible, acting: w.cockpit.actingScope() !== undefined, agentCycleOrder: () => w.cockpit.agentCycleOrder() }, + ); + } + + it('the Cockpit visible and the Agents view not: the Cockpit\'s own order', async () => { + const w = setup({ cockpitVisible: true }); + expect(w.agents.agentCycleOrder()).toEqual(AGENTS_ORDER); + expect(roster(w)).toEqual(COCKPIT_ORDER); + }); + + it('the Agents view visible (with or without the Cockpit): the Agents order, unchanged', async () => { + expect(roster(setup({ agentsVisible: true }))).toEqual(AGENTS_ORDER); + expect(roster(setup({ agentsVisible: true, cockpitVisible: true }))).toEqual(AGENTS_ORDER); + }); + + it('neither visible: the Agents order, unchanged', async () => { + expect(roster(setup())).toEqual(AGENTS_ORDER); + }); + + it('a Cockpit with nothing acting here (builder-worktree window) has no roster of its own', async () => { + const w = setup({ cockpitVisible: true, worktreeWindow: true }); + expect(w.cockpit.agentCycleOrder()).toEqual([]); + expect(roster(w)).toEqual(AGENTS_ORDER); + }); + + it('extension.ts builds the roster through agentCycleRoster from both views', () => { + const block = EXT_SRC.split('const cycleAgentTerminal = async')[1] ?? ''; + expect(block).toMatch(/const order = agentCycleRoster\(\s*\{ visible: buildersView\?\.visible \?\? false, agentCycleOrder: \(\) => buildersProvider\.agentCycleOrder\(\) \},/); + expect(block).toMatch(/visible: cockpitView\.visible,\s*acting: cockpitProvider\.actingScope\(\) !== undefined,\s*agentCycleOrder: \(\) => cockpitProvider\.agentCycleOrder\(\),/); + }); +}); diff --git a/apps/vscode/src/__tests__/command-args.test.ts b/apps/vscode/src/__tests__/command-args.test.ts new file mode 100644 index 000000000..174206db1 --- /dev/null +++ b/apps/vscode/src/__tests__/command-args.test.ts @@ -0,0 +1,67 @@ +/** + * How commands resolve their target from the argument VS Code passes them (`commands/command-args.ts`). + * A `view/item/context` entry passes the tree element itself, so each resolver is pinned for the + * Codev views' rows and for the Cockpit's (Spec 1963). + */ + +import { describe, it, expect, vi } from 'vitest'; + +vi.mock('vscode', () => { + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { constructor(public id: string, public color?: unknown) {} } + class ThemeColor { constructor(public id: string) {} } + return { TreeItem, ThemeIcon, ThemeColor, TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 } }; +}); + +const vscode = await import('vscode'); +const { architectNameFromArg, extractBuilderId, extractIssueId } = await import('../commands/command-args.js'); +const { BuilderGroupTreeItem, BuilderTreeItem } = await import('../views/builder-tree-item.js'); + +const NO_BUILDERS = { blocked: 0, idle: 0, active: 0 }; + +describe('architectNameFromArg (codev.removeArchitect)', () => { + it("a Cockpit sibling architect row resolves to its groupName, not its display label", () => { + const row = new BuilderGroupTreeItem('web', 0, vscode.TreeItemCollapsibleState.None, NO_BUILDERS, 'ws:/work/codev|'); + row.contextValue = 'cockpit-architect-sibling'; + expect(row.label).toBe('WEB (0)'); + expect(architectNameFromArg(row)).toBe('web'); + }); + + it('a Workspace-view architect row resolves from its id (Issue 841 Gap 3), then its label', () => { + const row = new vscode.TreeItem('WEB'); + row.id = 'workspace-architect-web'; + expect(architectNameFromArg(row)).toBe('web'); + const noId = new vscode.TreeItem('reviewer'); + expect(architectNameFromArg(noId)).toBe('reviewer'); + }); + + it('a string is the name; anything else resolves to nothing', () => { + expect(architectNameFromArg('demos')).toBe('demos'); + expect(architectNameFromArg(undefined)).toBeUndefined(); + expect(architectNameFromArg({ kind: 'workspace' })).toBeUndefined(); + }); +}); + +describe('extractIssueId / extractBuilderId', () => { + it('a Cockpit workspace node carries no issue id, so Spawn Builder opens its full picker', () => { + const node = { kind: 'workspace', ws: { label: 'codev', isCurrent: true, entry: {} } }; + expect(extractIssueId(node)).toBeUndefined(); + expect(extractIssueId('42')).toBe('42'); + expect(extractIssueId({ issueId: '7', issueTitle: 't' })).toBe('7'); + }); + + it("a Cockpit builder row resolves to its builder id, as an Agents row does", () => { + const row = new BuilderTreeItem('spir-10', 'spir-10 gated', 'ws:/work/codev|'); + expect(extractBuilderId(row)).toBe('spir-10'); + expect(extractBuilderId('air-11')).toBe('air-11'); + expect(extractBuilderId({ kind: 'workspace' })).toBeUndefined(); + }); +}); diff --git a/apps/vscode/src/__tests__/extension-architect-commands.test.ts b/apps/vscode/src/__tests__/extension-architect-commands.test.ts index 71dcd0909..b7990dfc8 100644 --- a/apps/vscode/src/__tests__/extension-architect-commands.test.ts +++ b/apps/vscode/src/__tests__/extension-architect-commands.test.ts @@ -28,6 +28,10 @@ const EXT_SRC = readFileSync( resolve(__dirname, '../extension.ts'), 'utf8', ); +const ARGS_SRC = readFileSync( + resolve(__dirname, '../commands/command-args.ts'), + 'utf8', +); describe('Spec 786 Phase 6 — extension.ts architect commands', () => { it('codev.openArchitectTerminal accepts an optional architectName arg', () => { @@ -111,9 +115,12 @@ describe('Spec 786 Phase 6 — extension.ts architect commands', () => { // so removeArchitect MUST read the raw name from item.id // (`workspace-architect-`). Reading the label would DELETE a name // Tower doesn't know (e.g. 'WEB' vs 'web'). + // Spec 1963 moved the resolution into `architectNameFromArg` (behaviour pinned in + // command-args.test.ts); the handler must still go through it. const removeBlock = EXT_SRC.split("regCli('codev.removeArchitect'")[1] ?? ''; - expect(removeBlock).toMatch(/workspace-architect-/); - expect(removeBlock).toMatch(/arg\.id/); + expect(removeBlock).toMatch(/^, async \(arg: unknown\) => \{\s*\/\/[^\n]*\n\s*const name = architectNameFromArg\(arg\);/); + expect(ARGS_SRC).toMatch(/workspace-architect-/); + expect(ARGS_SRC).toMatch(/arg\.id/); }); it('codev.removeArchitect is registered', () => { diff --git a/apps/vscode/src/__tests__/workspace-dev-slot.test.ts b/apps/vscode/src/__tests__/workspace-dev-slot.test.ts new file mode 100644 index 000000000..e614c306c --- /dev/null +++ b/apps/vscode/src/__tests__/workspace-dev-slot.test.ts @@ -0,0 +1,134 @@ +/** + * The dev slot (Spec 1963 Phase 5): one decision, `workspaceDevSlot`, read by the Workspace view's dev + * row and by the Cockpit's workspace-row menu. One table of cases drives all three, so the two + * views cannot disagree about whether to offer *Start Dev*, *Stop Dev* or the other-target + * *Stop Dev*. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; +import type { ResolvedWorktreeConfig } from '../load-worktree-config.js'; + +vi.mock('vscode', () => { + class FakeEventEmitter { + private listeners: Array<(e: T) => void> = []; + readonly event = (listener: (e: T) => void) => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter(l => l !== listener); } }; + }; + fire = (e: T) => { this.listeners.forEach(l => l(e)); }; + dispose = () => {}; + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { constructor(public id: string, public color?: unknown) {} } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter: FakeEventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + Uri: { parse: (s: string) => ({ toString: () => s }) }, + workspace: { getConfiguration: () => ({ get: (_key: string, def: unknown) => def }) }, + }; +}); + +const { WorkspaceProvider, workspaceDevSlot } = await import('../views/workspace.js'); +const { CockpitProvider, cockpitWorkspaceContext } = await import('../views/cockpit.js'); + +const HERE = '/work/codev'; +const WORKTREE = `${HERE}/.builders/spir-7`; +const noEvent = () => ({ dispose() {} }); + +function config(devCommand: string | null): ResolvedWorktreeConfig { + return { symlinks: [], postSpawn: [], devCommand, devUrls: [] }; +} + +interface Case { + name: string; + windowRoot: string; + devs: string[]; + config: ResolvedWorktreeConfig | null; + slot: 'start' | 'stop' | 'stop-other' | 'none'; +} + +const CASES: Case[] = [ + { name: 'nothing configured, nothing running', windowRoot: HERE, devs: [], config: null, slot: 'none' }, + { name: 'a blank devCommand is no dev command', windowRoot: HERE, devs: [], config: config(' '), slot: 'none' }, + { name: 'a runnable devCommand, nothing running', windowRoot: HERE, devs: [], config: config('pnpm dev'), slot: 'start' }, + { name: "this window's own dev (main) running", windowRoot: HERE, devs: ['main'], config: config('pnpm dev'), slot: 'stop' }, + { name: 'own dev running after devCommand was cleared', windowRoot: HERE, devs: ['main'], config: null, slot: 'stop' }, + { name: "a builder's dev running (started from its menu)", windowRoot: HERE, devs: ['spir-10'], config: config('pnpm dev'), slot: 'stop-other' }, + { name: 'worktree window, its own dev running', windowRoot: WORKTREE, devs: ['spir-7'], config: null, slot: 'stop' }, + { name: "worktree window, main's dev running", windowRoot: WORKTREE, devs: ['main'], config: config('pnpm dev'), slot: 'stop-other' }, + { name: 'worktree window, nothing running', windowRoot: WORKTREE, devs: [], config: config('pnpm dev'), slot: 'start' }, +]; + +/** The Workspace view's `contextValue` for each slot (`undefined`: no dev row at all). */ +const WORKSPACE_ROW: Record = { + start: 'workspace-dev-start', + stop: 'workspace-dev-stop', + 'stop-other': 'workspace-dev-stop-other', + none: undefined, +}; + +function managers(c: Case) { + const worktree = c.windowRoot === WORKTREE ? { builderId: 'spir-7', worktreePath: WORKTREE } : null; + const connectionManager = { + getState: () => 'connected', + getWorkspacePath: () => HERE, + getWindowRoot: () => c.windowRoot, + getBuilderWorktree: () => worktree, + getClient: () => ({ getWorktreeConfig: async () => c.config, getWorkspaceStatus: async () => null }), + onStateChange: noEvent, + onSSEEvent: noEvent, + }; + const terminalManager = { + listDevTerminals: () => c.devs.map((builderId, i) => ({ builderId, terminalId: `t${i}` })), + onDidChangeDevTerminals: noEvent, + }; + return { connectionManager, terminalManager, worktree }; +} + +describe('workspaceDevSlot: one decision for the Workspace view and the Cockpit', () => { + for (const c of CASES) { + it(c.name, async () => { + const { connectionManager, terminalManager, worktree } = managers(c); + + expect(workspaceDevSlot(connectionManager, terminalManager, c.config).kind).toBe(c.slot); + + const workspaceView = new WorkspaceProvider(connectionManager as never, terminalManager as never); + const rows = await workspaceView.getChildren(); + const devRow = rows.find(r => /^workspace-dev-(start|stop|stop-other)$/.test(r.contextValue ?? '')); + expect(devRow?.contextValue).toBe(WORKSPACE_ROW[c.slot]); + + const cockpit = new CockpitProvider({ + connectionManager: connectionManager as never, + terminalManager, + loadWorktreeConfig: async () => c.config, + towerCache: { + getFleet: () => [{ workspace: { path: HERE, name: 'codev', active: true, proxyUrl: '', terminals: 1 }, attention: deriveAttention(null), overview: null }], + isLoaded: () => true, + getOverview: () => null, + onDidChange: noEvent, + } as never, + overviewCache: { getData: () => null, onDidChange: noEvent } as never, + diffCache: {} as never, + builderWorktreeWindow: worktree !== null, + connection: 'auto', + }); + const [root] = await cockpit.getChildren(); + const [own] = await cockpit.getChildren(root); + const role = worktree ? 'parent' : 'current'; + expect(cockpit.getTreeItem(own).contextValue).toBe(cockpitWorkspaceContext(role, c.slot, false)); + }); + } +}); diff --git a/apps/vscode/src/commands/command-args.ts b/apps/vscode/src/commands/command-args.ts new file mode 100644 index 000000000..bd16d4b82 --- /dev/null +++ b/apps/vscode/src/commands/command-args.ts @@ -0,0 +1,85 @@ +/** + * How a command resolves its target from the argument VS Code passes it. A row's click passes its + * `command.arguments`; a `view/item/context` menu entry passes the tree element itself, whichever + * view it is in (the Codev views, or the Cockpit's, Spec 1963). Pure over that argument, so each + * resolution is unit-testable without activating the extension. + */ + +import * as vscode from 'vscode'; +import { BacklogTreeItem } from '../views/backlog-tree-item.js'; +import { BuilderGroupTreeItem, BuilderTreeItem } from '../views/builder-tree-item.js'; + +/** A builder row's id (from the Agents view or the Cockpit), or a row click's id string. */ +export function extractBuilderId(arg: unknown): string | undefined { + if (typeof arg === 'string') { return arg; } + if (arg instanceof BuilderTreeItem) { return arg.builderId; } + return undefined; +} + +/** + * Argument shape accepted by the backlog issue commands. Beyond the sidebar's + * `TreeItem` and the row-click `string`, the Search Backlog webview (#920) + * passes a plain `{ issueId, issueTitle }` object so its inline "reference in + * architect" action can carry the title (which a bare id string can't). + */ +export type IssueCommandArg = + | vscode.TreeItem + | string + | { issueId: string; issueTitle?: string } + | undefined; + +/** + * Resolve an issue number from a command argument. + * + * Backlog row-click passes the issue id as a string via + * `item.command.arguments`; right-click context-menu invocations pass the + * BacklogTreeItem itself; command-palette invocations pass nothing → + * undefined → spawnBuilder falls back to its full quick-pick flow. So does a + * Cockpit workspace row's *Spawn Builder* (a `{ kind: 'workspace' }` node). + */ +export function extractIssueId(arg: unknown): string | undefined { + if (typeof arg === 'string') { return arg; } + if (arg instanceof BacklogTreeItem) { return arg.issueId; } + if (arg && typeof arg === 'object' && 'issueId' in arg && typeof arg.issueId === 'string') { return arg.issueId; } + return undefined; +} + +/** + * Resolve an issue title from a command argument. + * + * Only `BacklogTreeItem` carries the title; string args (used by row-click + * which only passes the id) and undefined return undefined so callers can + * fall back. An empty title is normalised to undefined so the fallback + * branch handles it identically to a missing title. + */ +export function extractIssueTitle(arg: IssueCommandArg): string | undefined { + if (arg instanceof BacklogTreeItem) { + return arg.issueTitle || undefined; + } + if (arg && typeof arg === 'object' && 'issueId' in arg) { + return arg.issueTitle || undefined; + } + return undefined; +} + +/** + * The architect `codev.removeArchitect` acts on: + * - a string is the name itself; + * - a Cockpit architect row (Spec 1963) is a group row whose label is display text (`WEB (0)`), so + * the name is its `groupName`; + * - a Workspace-view architect row's label is UPPERCASE display text (Issue 841 Gap 3), so the + * raw lowercase name comes from its id (`workspace-architect-`), which that tree sets for + * exactly this reason, and only failing that from the label. + */ +export function architectNameFromArg(arg: unknown): string | undefined { + if (typeof arg === 'string') { return arg; } + if (arg instanceof BuilderGroupTreeItem) { return arg.groupName; } + if (arg instanceof vscode.TreeItem) { + const id = arg.id; + if (typeof id === 'string' && id.startsWith('workspace-architect-')) { + return id.slice('workspace-architect-'.length); + } + if (typeof arg.label === 'string') { return arg.label; } + } + return undefined; +} diff --git a/apps/vscode/src/commands/open-dev-url.ts b/apps/vscode/src/commands/open-dev-url.ts index 7c07bcb82..aa9552dcf 100644 --- a/apps/vscode/src/commands/open-dev-url.ts +++ b/apps/vscode/src/commands/open-dev-url.ts @@ -24,9 +24,10 @@ import { loadWorktreeConfig } from '../load-worktree-config.js'; export async function openDevUrl( connectionManager: ConnectionManager, - urlArg?: string, + urlArg?: unknown, ): Promise { - // Direct invocation: a row click passes its URL; just open it. + // Direct invocation: a row click passes its URL; just open it. Anything else (the palette passes + // nothing; a Cockpit workspace row's menu passes the row) resolves from the config below. if (typeof urlArg === 'string' && urlArg.trim()) { await vscode.env.openExternal(vscode.Uri.parse(urlArg)); return; diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index 7c8d89eff..eb6d9c570 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -22,6 +22,7 @@ import { stopWorktreeDev } from './commands/stop-worktree-dev.js'; import { runWorkspaceDev, stopWorkspaceDev } from './commands/run-workspace-dev.js'; import { stopDev, restartDev, switchDevTarget } from './commands/dev-actions.js'; import { openDevUrl } from './commands/open-dev-url.js'; +import { architectNameFromArg, extractBuilderId, extractIssueId, extractIssueTitle, type IssueCommandArg } from './commands/command-args.js'; import { pasteImage } from './commands/paste-image.js'; import { openWorktreeFolder } from './commands/open-worktree-folder.js'; import { runWorktreeSetup } from './commands/run-worktree-setup.js'; @@ -64,7 +65,7 @@ import { buildBuilderPickRows } from './builder-pick-rows.js'; import { readBuildersFileViewAsTree } from './builders-config.js'; import { deriveAttention, isIdleWaiting } from '@cluesmith/codev-sdk/builder-helpers'; import { BuildersProvider, runBuilderRowClick, agentTargetIsFocused, agentCycleAttemptOrder, type AgentTarget } from './views/builders.js'; -import { AgentTreeHosts } from './views/agent-tree-hosts.js'; +import { AgentTreeHosts, agentCycleRoster } from './views/agent-tree-hosts.js'; import { CockpitProvider, COCKPIT_VIEW_ID, cockpitConnectionMode, type CockpitNode } from './views/cockpit.js'; import { OverviewRefreshGate } from './views/overview-refresh-gate.js'; // Codev Tower (#1566): the cross-workspace navigation hub — its own activity-bar container. @@ -79,7 +80,7 @@ import { TeamProvider } from './views/team.js'; import { StatusProvider } from './views/status.js'; import { ContextualPanelProvider } from './contextual-panel/panel-provider.js'; import { formatTargetName } from './views/dev-format.js'; -import { WorkspaceProvider } from './views/workspace.js'; +import { WorkspaceProvider, buildDashboardUrl } from './views/workspace.js'; import { displayArchitectName, sortArchitectsForPicker } from './views/architect-display.js'; import { validateArchitectName } from '@cluesmith/codev-sdk/architect-name'; import { resolveMainArchitect, addArchitectRequestMessage, ADD_ARCHITECT_RECIPIENT } from './commands/add-architect.js'; @@ -110,64 +111,6 @@ let devChipItem: vscode.StatusBarItem | null = null; // empty-window launch of the Codev IDE. const IDE_FIRST_RUN_KEY = 'codev.ideFirstRunShown'; -/** - * Resolve a builder id from a command argument. - * - * Tree-item context-menu invocations pass a BuilderTreeItem; command-palette - * invocations pass nothing; programmatic invocations may pass a string id. - * Anything else → undefined → the command falls back to its quick-pick. - */ -function extractBuilderId(arg: vscode.TreeItem | string | undefined): string | undefined { - if (typeof arg === 'string') { return arg; } - if (arg instanceof BuilderTreeItem) { return arg.builderId; } - return undefined; -} - -/** - * Resolve an issue number from a command argument. - * - * Backlog row-click passes the issue id as a string via - * `item.command.arguments`; right-click context-menu invocations pass the - * BacklogTreeItem itself; command-palette invocations pass nothing → - * undefined → spawnBuilder falls back to its full quick-pick flow. - */ -/** - * Argument shape accepted by the backlog issue commands. Beyond the sidebar's - * `TreeItem` and the row-click `string`, the Search Backlog webview (#920) - * passes a plain `{ issueId, issueTitle }` object so its inline "reference in - * architect" action can carry the title (which a bare id string can't). - */ -type IssueCommandArg = - | vscode.TreeItem - | string - | { issueId: string; issueTitle?: string } - | undefined; - -function extractIssueId(arg: IssueCommandArg): string | undefined { - if (typeof arg === 'string') { return arg; } - if (arg instanceof BacklogTreeItem) { return arg.issueId; } - if (arg && typeof arg === 'object' && 'issueId' in arg) { return arg.issueId; } - return undefined; -} - -/** - * Resolve an issue title from a command argument. - * - * Only `BacklogTreeItem` carries the title; string args (used by row-click - * which only passes the id) and undefined return undefined so callers can - * fall back. An empty title is normalised to undefined so the fallback - * branch handles it identically to a missing title. - */ -function extractIssueTitle(arg: IssueCommandArg): string | undefined { - if (arg instanceof BacklogTreeItem) { - return arg.issueTitle || undefined; - } - if (arg && typeof arg === 'object' && 'issueId' in arg) { - return arg.issueTitle || undefined; - } - return undefined; -} - /** Map the pure `ConfigScope` onto the VS Code `ConfigurationTarget` enum (#1070). */ function configTargetFor(scope: ConfigScope): vscode.ConfigurationTarget { if (scope === 'workspaceFolder') { @@ -638,6 +581,8 @@ export async function activate(context: vscode.ExtensionContext) { // every other workspace navigates to its own window. const cockpitProvider = new CockpitProvider({ connectionManager, + terminalManager: terminalManager!, + loadWorktreeConfig: () => loadWorktreeConfig(connectionManager!), towerCache, overviewCache, diffCache: builderDiffCache, @@ -990,6 +935,16 @@ export async function activate(context: vscode.ExtensionContext) { reg('codev.tower.refresh', () => towerCache.refresh()), // The Cockpit reads both caches: this window's overview and the fleet. reg('codev.cockpit.refresh', () => Promise.all([overviewCache.refresh(), towerCache.refresh()])), + // The Workspace view's *Open Web Interface* row, as an action on this window's workspace row. + // The row's menu passes the row; the URL is always this window's workspace. + reg('codev.cockpit.openWebInterface', async () => { + const url = buildDashboardUrl(connectionManager!); + if (!url) { + vscode.window.showErrorMessage('Codev: This window has no Codev workspace, so there is no web interface to open.'); + return; + } + await vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(url)); + }), ); // Populate as soon as Tower is reachable; refreshes thereafter ride the shared SSE + poll. towerCache.refresh(); @@ -1027,7 +982,16 @@ export async function activate(context: vscode.ExtensionContext) { }; const cycleAgentTerminal = async (direction: 1 | -1): Promise => { - const order = buildersProvider.agentCycleOrder(); + // The Cockpit's own order while it is the visible agent view (Spec 1963); else the Agents + // view's order, unchanged. + const order = agentCycleRoster( + { visible: buildersView?.visible ?? false, agentCycleOrder: () => buildersProvider.agentCycleOrder() }, + { + visible: cockpitView.visible, + acting: cockpitProvider.actingScope() !== undefined, + agentCycleOrder: () => cockpitProvider.agentCycleOrder(), + }, + ); // Current position = the focused agent terminal (builder id, else architect name). // VSCode keeps `activeTerminal` set from an editor too, so this resumes from the // last-focused agent; nothing focused starts at the ends. @@ -1198,23 +1162,9 @@ export async function activate(context: vscode.ExtensionContext) { // from Phase 4. Wired to the right-click context menu on sibling // entries (`viewItem == workspace-architect-sibling`) — see // package.json's menus contribution. Refuses to remove `main`. - regCli('codev.removeArchitect', async (arg: vscode.TreeItem | string | undefined) => { - let name: string | undefined; - if (typeof arg === 'string') { - name = arg; - } else if (arg instanceof vscode.TreeItem) { - // Issue 841 Gap 3: the row label is now UPPERCASE (display-only), - // so it no longer equals the canonical name. Resolve the raw - // lowercase name from `item.id` (`workspace-architect-`), - // which the Architects tree sets for exactly this reason. Fall - // back to the label only if the id is somehow absent. - const id = arg.id; - if (typeof id === 'string' && id.startsWith('workspace-architect-')) { - name = id.slice('workspace-architect-'.length); - } else if (typeof arg.label === 'string') { - name = arg.label; - } - } + regCli('codev.removeArchitect', async (arg: unknown) => { + // A Workspace-view row, a Cockpit architect row (Spec 1963) or a name. + const name = architectNameFromArg(arg); if (!name) { vscode.window.showErrorMessage('Codev: Could not determine which architect to remove.'); return; @@ -1618,8 +1568,9 @@ export async function activate(context: vscode.ExtensionContext) { // The dev status-bar chip's click target (#1049 removed the Codev Dev panel it used to focus). reg('codev.dev.reveal', () => terminalManager!.revealDevTerminal()), - reg('codev.openDevUrl', (urlArg?: unknown) => - openDevUrl(connectionManager!, typeof urlArg === 'string' ? urlArg : undefined)), + // A dev-URL row passes its URL; the palette and a Cockpit row's menu pass none (or the + // row), which `openDevUrl` resolves from the config. + reg('codev.openDevUrl', (urlArg?: unknown) => openDevUrl(connectionManager!, urlArg)), reg('codev.pasteImage', () => pasteImage(connectionManager!, terminalManager!)), reg('codev.refreshTeam', () => teamProvider.refresh()), diff --git a/apps/vscode/src/views/agent-tree-hosts.ts b/apps/vscode/src/views/agent-tree-hosts.ts index b32f06862..5c1d737a8 100644 --- a/apps/vscode/src/views/agent-tree-hosts.ts +++ b/apps/vscode/src/views/agent-tree-hosts.ts @@ -44,6 +44,25 @@ export interface AgentTreeHost { readonly revealWhenNoneVisible?: boolean; } +/** One view's agent-cycle roster, and whether that view is visible now. */ +export interface CycleRosterSource { + readonly visible: boolean; + agentCycleOrder(): AgentTarget[]; +} + +/** + * The agent-cycle roster (#1563) of this window (Spec 1963, architect ruling (b) for Phase 5): + * - **the Cockpit visible and the Agents view not:** the Cockpit's own order, this window's + * architects each followed by their builders. Only while the Cockpit has rows that act here; a + * Cockpit with none (a builder-worktree window, or before Tower lists this workspace) has no + * roster of its own, and the existing order applies; + * - **the Agents view visible, or neither:** the Agents view's order, unchanged. + */ +export function agentCycleRoster(agents: CycleRosterSource, cockpit: CycleRosterSource & { acting: boolean }): AgentTarget[] { + if (cockpit.visible && !agents.visible && cockpit.acting) { return cockpit.agentCycleOrder(); } + return agents.agentCycleOrder(); +} + /** The `scope` a tree row carries, or `undefined` for a row that names none. */ function scopeOf(row: unknown): string | undefined { if (row === null || typeof row !== 'object') { return undefined; } diff --git a/apps/vscode/src/views/cockpit.ts b/apps/vscode/src/views/cockpit.ts index 8d5949f2b..b1efe0126 100644 --- a/apps/vscode/src/views/cockpit.ts +++ b/apps/vscode/src/views/cockpit.ts @@ -1,6 +1,8 @@ import * as vscode from 'vscode'; import type { OverviewData } from '@cluesmith/codev-types'; import type { ConnectionManager } from '../connection-manager.js'; +import type { TerminalManager } from '../terminal-manager.js'; +import type { ResolvedWorktreeConfig } from '../load-worktree-config.js'; import type { TowerFleetCache } from './tower-cache.js'; import type { OverviewCache } from './overview-data.js'; import type { BuilderDiffCache } from './builder-diff-cache.js'; @@ -10,6 +12,7 @@ import { ArchitectTreeBuilder, type AgentTarget } from './architect-tree.js'; import { architectGrouping } from './builder-grouping.js'; import { BuilderGroupTreeItem, BuilderTreeItem, IdleArchitectsGroupTreeItem } from './builder-tree-item.js'; import type { ActingRows } from './agent-tree-hosts.js'; +import { workspaceDevSlot, type WorkspaceDevSlot } from './workspace.js'; /** The Cockpit's tree view id (Spec 1963). */ export const COCKPIT_VIEW_ID = 'codev.cockpit'; @@ -41,8 +44,45 @@ export type CockpitOwnNode = export type CockpitNode = CockpitOwnNode | vscode.TreeItem; +/** + * Whose row this window's workspace row is: + * - `current`: this window's workspace, which acts here (Spawn Builder, New Shell, Add Architect, + * Open Web Interface, dev, dev URLs); + * - `parent`: the parent workspace of a builder-worktree window (#1809). It carries only the + * worktree-scoped actions the Workspace view shows there: Open Web Interface, dev, dev URLs. + */ +export type CockpitWorkspaceRole = 'current' | 'parent'; + +/** The `contextValue` suffix of each dev slot; `none` offers no dev action. */ +const DEV_SLOT_SUFFIX: Record = { + stop: '-dev-stop', + 'stop-other': '-dev-stop-other', + start: '-dev-start', + none: '', +}; + +/** Every dev-slot kind, for callers that enumerate the context values. */ +export const DEV_SLOT_KINDS = Object.keys(DEV_SLOT_SUFFIX) as Array; + +/** + * The `contextValue` of this window's workspace row, encoding what the Workspace view decides for + * this window, so the menus can offer exactly that: + * `cockpit-workspace-`, then the dev slot (`-dev-start`, `-dev-stop`, `-dev-stop-other`, or + * nothing), then `-devurls` when `worktree.devUrls` is non-empty. Every other workspace row keeps + * the Tower view's `tower-workspace-*` value, so the Tower menus' `viewItem` patterns apply as-is. + */ +export function cockpitWorkspaceContext(role: CockpitWorkspaceRole, devSlot: WorkspaceDevSlot['kind'], hasDevUrls: boolean): string { + let value = `cockpit-workspace-${role}${DEV_SLOT_SUFFIX[devSlot]}`; + if (hasDevUrls) { value += '-devurls'; } + return value; +} + export interface CockpitProviderOptions { - connectionManager: Pick; + connectionManager: Pick; + /** The dev slot (*Start Dev* / *Stop Dev*) follows the dev terminals, as in the Workspace view. */ + terminalManager: Pick; + /** This window's resolved worktree config (`loadWorktreeConfig`); the Cockpit holds the result. */ + loadWorktreeConfig: () => Promise; towerCache: Pick; overviewCache: Pick; diffCache: BuilderDiffCache; @@ -81,6 +121,22 @@ interface WorkspaceTree { ws: LabelledEntry; } +/** The worktree config fetched for one workspace path: the request, then its result. */ +interface HeldWorktreeConfig { + path: string | null; + request: Promise; + value: ResolvedWorktreeConfig | null; +} + +/** The type inside one of Tower's SSE envelopes, or `undefined` for a malformed one. */ +function envelopeType(data: string): unknown { + try { + return (JSON.parse(data) as { type?: unknown }).type; + } catch { + return undefined; + } +} + const ARCHITECT_AXIS = architectGrouping(); /** @@ -98,7 +154,15 @@ const ARCHITECT_AXIS = architectGrouping(); * `OverviewCache` as the Agents view does; every other workspace navigates, reading the overview * `TowerFleetCache` already fetched for it. No request of its own. * - * Re-renders on the overview, the fleet and the connection state. + * - **This window's workspace row** carries the Workspace view's actions for this window + * (`cockpitWorkspaceContext`). Its dev slot and dev URLs come from the worktree config, which the + * Cockpit fetches once and holds: it re-renders on every fleet and overview change, including + * the fleet's 20 s fallback poll, so fetching per render would add requests the Workspace view + * does not make. The held config is dropped on `codev-config-updated`, a connection-state change + * or a workspace change, and the next render fetches it again. + * + * Re-renders on the overview, the fleet and the connection state, and on the Workspace view's own + * signals: the dev terminals, `codev-config-updated` and `architects-updated`. */ export class CockpitProvider implements vscode.TreeDataProvider, ActingRows { private readonly changeEmitter = new vscode.EventEmitter(); @@ -108,17 +172,32 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac private readonly trees = new Map(); /** True once a connection attempt has failed (or a connection dropped). */ private attemptFailed: boolean; + /** See `resolveWorktreeConfig`; `undefined` until fetched, and again once dropped. */ + private worktreeConfig: HeldWorktreeConfig | undefined; constructor(private readonly options: CockpitProviderOptions) { - const { connectionManager, towerCache, overviewCache } = options; + const { connectionManager, terminalManager, towerCache, overviewCache } = options; this.attemptFailed = connectionManager.getState() === 'reconnecting'; this.subscriptions.push( overviewCache.onDidChange(() => this.refresh()), towerCache.onDidChange(() => this.refresh()), connectionManager.onStateChange((state) => { if (state === 'disconnected' || state === 'reconnecting') { this.attemptFailed = true; } + this.worktreeConfig = undefined; this.refresh(); }), + // Start / Stop Dev stays honest across every start, stop and cleanup path. + terminalManager.onDidChangeDevTerminals(() => this.refresh()), + // Tower sends each event as a JSON envelope with no SSE `event:` name, so the type is inside. + connectionManager.onSSEEvent(({ data }) => { + const type = envelopeType(data); + if (type === 'codev-config-updated') { + this.worktreeConfig = undefined; + this.refresh(); + } else if (type === 'architects-updated') { + this.refresh(); + } + }), ); } @@ -155,6 +234,8 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac case 'workspace': { const item = workspaceRow(node.ws, this.workspaceChildren(node.ws)); item.id = COCKPIT_IDS.workspace(node.ws.entry.workspace.path); + const role = this.workspaceRole(node.ws); + if (role) { item.contextValue = this.ownWorkspaceContext(role); } return item; } case 'dormant-group': { @@ -180,6 +261,7 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac } switch (node.kind) { case 'tower-root': + await this.resolveWorktreeConfig(); return this.towerChildren(); case 'workspace': return this.workspaceNodeChildren(node.ws); @@ -245,6 +327,15 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac this.refresh(); } + /** + * The agent-cycle roster in the Cockpit's own order: this window's architects, each followed by + * its builders, top to bottom (#1563). Only this window's workspace: other workspaces' rows + * navigate and never enter the cycle. Empty while nothing acts here. + */ + agentCycleOrder(): AgentTarget[] { + return this.actTree()?.agentCycleOrder() ?? []; + } + /** * The acting row builder of this window's workspace, or `undefined` when nothing acts here: Tower * has not listed this workspace (yet), it is dormant, or the window is a builder-worktree or @@ -256,6 +347,40 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac return this.treeFor(ws); } + // ── This window's workspace row ─────────────────────────────────────────── + + /** + * `ws`'s role when it is this window's workspace row: `current` when it acts here, `parent` in a + * builder-worktree window. `undefined` for every other row, which keeps the Tower view's value. + */ + private workspaceRole(ws: LabelledEntry): CockpitWorkspaceRole | undefined { + if (!ws.isCurrent || !ws.entry.workspace.active) { return undefined; } + if (this.options.builderWorktreeWindow) { return 'parent'; } + return 'current'; + } + + private ownWorkspaceContext(role: CockpitWorkspaceRole): string { + const config = this.worktreeConfig?.value ?? null; + const slot = workspaceDevSlot(this.options.connectionManager, this.options.terminalManager, config); + const hasDevUrls = (config?.devUrls ?? []).length > 0; + return cockpitWorkspaceContext(role, slot.kind, hasDevUrls); + } + + /** + * Fetch this window's worktree config unless it is already held for this workspace path. The + * rows are built synchronously in `getTreeItem`, so the root's async `getChildren` resolves the + * config first. Concurrent renders share the one request. + */ + private async resolveWorktreeConfig(): Promise { + const path = this.options.connectionManager.getWorkspacePath(); + let held = this.worktreeConfig; + if (!held || held.path !== path) { + held = { path, request: this.options.loadWorktreeConfig(), value: null }; + this.worktreeConfig = held; + } + held.value = await held.request; + } + // ── Levels ──────────────────────────────────────────────────────────────── /** The Tower root's children: a state row while there is nothing to list, else the workspaces. */ @@ -401,7 +526,12 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac return { ...targetOf(entry.ws), isCurrent: false }; } - /** Drop the row builders of workspaces no longer active in the fleet. */ + /** + * Drop the row builders of workspaces no longer active in the fleet. Runs only when the Tower + * root's children are listed, so while the root is collapsed a departed workspace's builder + * lingers until the next expand. That is bounded (one builder per workspace ever listed) and + * harmless: nothing renders or routes to it, since no row of that workspace is shown. + */ private pruneTrees(active: readonly LabelledEntry[]): void { const live = new Set(active.map(ws => cockpitScope(ws.entry.workspace.path))); for (const scope of this.trees.keys()) { diff --git a/apps/vscode/src/views/workspace.ts b/apps/vscode/src/views/workspace.ts index e506b597b..19e0f1fc1 100644 --- a/apps/vscode/src/views/workspace.ts +++ b/apps/vscode/src/views/workspace.ts @@ -3,10 +3,63 @@ import { encodeWorkspacePath } from '@cluesmith/codev-sdk/workspace'; import type { ConnectionManager } from '../connection-manager.js'; import type { TerminalManager } from '../terminal-manager.js'; import { getTowerAddress } from '../workspace-detector.js'; -import { resolveWorkspaceDevTarget } from '../commands/dev-shared.js'; -import { loadWorktreeConfig, hasRunnableDevCommand } from '../load-worktree-config.js'; +import { resolveWorkspaceDevTarget, type DevTarget } from '../commands/dev-shared.js'; +import { loadWorktreeConfig, hasRunnableDevCommand, type ResolvedWorktreeConfig } from '../load-worktree-config.js'; import { displayArchitectName } from './architect-display.js'; +/** + * The Tower dashboard URL of this window's workspace, or `null` with no workspace. Shared by the + * Workspace view's *Open Web Interface* row and the Cockpit's *Open Web Interface* action. + */ +export function buildDashboardUrl(connectionManager: Pick): string | null { + const workspacePath = connectionManager.getWorkspacePath(); + if (!workspacePath) { return null; } + const { host, port } = getTowerAddress(); + return `http://${host}:${port}/workspace/${encodeWorkspacePath(workspacePath)}/`; +} + +/** + * Which dev control this window offers, under the single-slot model (one dev at a time across main + * and every builder, `dev-shared.ts`): + * - `stop`: this window's own target is the running dev; + * - `stop-other`: a dev is running for a different target; + * - `start`: no dev is running and a runnable `worktree.devCommand` is configured; + * - `none`: no dev is running and there is nothing to run. + * + * The Workspace view's dev row and the Cockpit's workspace-row menu both read it, so they never + * disagree. + */ +export type WorkspaceDevSlot = + | { kind: 'stop'; target: DevTarget } + | { kind: 'stop-other'; runningFor: string } + | { kind: 'start'; target: DevTarget | null; devCommand: string } + | { kind: 'none' }; + +/** + * This window's dev slot. The target is whatever folder the window is rooted at: the main checkout + * → `main`, a `.builders//` worktree → that builder. It is read from the window root, not the + * Tower workspace path, which is the parent root in a worktree window (#1809). + */ +export function workspaceDevSlot( + connectionManager: Pick, + terminalManager: Pick, + worktreeConfig: ResolvedWorktreeConfig | null, +): WorkspaceDevSlot { + const windowRoot = connectionManager.getWindowRoot(); + const devTarget = windowRoot ? resolveWorkspaceDevTarget(windowRoot) : null; + const allDevs = terminalManager.listDevTerminals(); + if (devTarget && allDevs.some(d => d.builderId === devTarget.id)) { return { kind: 'stop', target: devTarget }; } + const otherDev = allDevs[0]; // single-slot ⇒ at most one + if (otherDev) { return { kind: 'stop-other', runningFor: otherDev.builderId }; } + // Gating on hasRunnableDevCommand (not `devCommand !== null`) also treats `"devCommand": ""` as + // absent, matching dev-shared.ts's runnability check. + const devCommand = worktreeConfig?.devCommand ?? null; + if (devCommand !== null && hasRunnableDevCommand(worktreeConfig)) { + return { kind: 'start', target: devTarget, devCommand }; + } + return { kind: 'none' }; +} + /** * Workspace-level entry points: architect terminal, Tower web dashboard, * spawn builder, and new shell. Sits at the top of the Codev sidebar so @@ -90,7 +143,7 @@ export class WorkspaceProvider implements vscode.TreeDataProvider/` worktree → that builder. The - // label stays generic; the tooltip names the resolved target. Read from - // the window root, not the Tower workspace path, which is the parent - // root in a worktree window (#1809). - const windowRoot = this.connectionManager.getWindowRoot(); - const devTarget = windowRoot ? resolveWorkspaceDevTarget(windowRoot) : null; - // Resolved worktree config (Tower-merged across all 5 layers). One // fetch drives both the dev row's visibility (gated on // devCommand presence) and the Open Dev URL row(s) below. const worktreeConfig = await loadWorktreeConfig(this.connectionManager); - const devCommand = worktreeConfig?.devCommand ?? null; const devUrls = worktreeConfig?.devUrls ?? []; // Mutually exclusive: show Start when no dev is running anywhere, Stop @@ -138,25 +182,22 @@ export class WorkspaceProvider implements vscode.TreeDataProvider d.builderId === devTarget.id) : undefined; - const otherDev = !targetDev ? allDevs[0] : undefined; // single-slot ⇒ at most one + // devCommand isn't configured" footgun. The decision itself is + // `workspaceDevSlot`, shared with the Cockpit's workspace-row menu. + const slot = workspaceDevSlot(this.connectionManager, this.terminalManager, worktreeConfig); - if (targetDev) { + if (slot.kind === 'stop') { // This workspace's own dev is the running one. Today's Stop row. const stopDev = new vscode.TreeItem('Stop Dev'); stopDev.iconPath = new vscode.ThemeIcon('debug-stop'); - stopDev.tooltip = `Stop the dev for this workspace (target: ${devTarget!.id})`; + stopDev.tooltip = `Stop the dev for this workspace (target: ${slot.target.id})`; stopDev.contextValue = 'workspace-dev-stop'; stopDev.command = { command: 'codev.stopWorkspaceDev', title: 'Stop Dev', }; items.push(stopDev); - } else if (otherDev) { + } else if (slot.kind === 'stop-other') { // A dev is running, but for a different target — surface it so the // user can see/stop it without leaving the Workspace view. Goes // through codev.stopWorktreeDev which targets the dev slot directly @@ -164,20 +205,20 @@ export class WorkspaceProvider implements vscode.TreeDataProvider Date: Tue, 24 Nov 2026 01:17:59 -0800 Subject: [PATCH 063/140] [Spec 1963][Phase: cockpit_actions] test: menu-parity oracle, parity test and handler-argument test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 5b (part 1) of Phase 5: - views/cockpit-menu-map.ts: the checked-in oracle. One record per source menu entry of codev.workspace / codev.agents / codev.tower (27: same, relocated, or excluded — only the three group-by cycle buttons), one per Workspace-view row click, and one per viewsWelcome entry (two mapped to the Tower root's state rows, the IDE-empty welcome excluded with reason). - cockpit-menu-parity.test.ts: holds package.json and the providers to the oracle — unrecorded or edited source entries, missing or unrecorded Cockpit entries, navigate-only/workspace values reaching builder or architect menus, spawn/shell/architect actions on the worktree parent row, Remove Architect on main, and the dev-slot/dev-URL offer matrix. Nine mutations, each caught. - cockpit-handler-args.test.ts: each command a Cockpit row entry runs, given the real Cockpit node it attaches to. Four mutations, each caught. --- .../__tests__/cockpit-handler-args.test.ts | 235 +++++++++++++ .../src/__tests__/cockpit-menu-parity.test.ts | 327 ++++++++++++++++++ apps/vscode/src/views/cockpit-menu-map.ts | 242 +++++++++++++ 3 files changed, 804 insertions(+) create mode 100644 apps/vscode/src/__tests__/cockpit-handler-args.test.ts create mode 100644 apps/vscode/src/__tests__/cockpit-menu-parity.test.ts create mode 100644 apps/vscode/src/views/cockpit-menu-map.ts diff --git a/apps/vscode/src/__tests__/cockpit-handler-args.test.ts b/apps/vscode/src/__tests__/cockpit-handler-args.test.ts new file mode 100644 index 000000000..618b6aa53 --- /dev/null +++ b/apps/vscode/src/__tests__/cockpit-handler-args.test.ts @@ -0,0 +1,235 @@ +/** + * Spec 1963 Phase 5: every command a Cockpit menu entry runs handles the Cockpit tree element VS Code + * passes it. A `view/item/context` entry passes the clicked element, and the Cockpit's elements are + * not the source views' (its workspace rows are `{ kind: 'workspace' }` nodes, its architect rows + * group rows labelled `WEB (0)`). Each command is given the real node its entry attaches to, taken + * from a real `CockpitProvider`, and must act on that node's target. Handlers registered inline in + * `extension.ts` are held to their argument resolver at the source level; the resolvers themselves + * run here. + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; +import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; + +const ui = vi.hoisted(() => ({ + showQuickPick: vi.fn(), + openExternal: vi.fn(), + showWarningMessage: vi.fn(), +})); + +vi.mock('vscode', () => { + class FakeEventEmitter { + private listeners: Array<(e: T) => void> = []; + readonly event = (listener: (e: T) => void) => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter(l => l !== listener); } }; + }; + fire = (e: T) => { this.listeners.forEach(l => l(e)); }; + dispose = () => {}; + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + resourceUri?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { + static readonly Folder = new ThemeIcon('folder'); + constructor(public id: string, public color?: unknown) {} + } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter: FakeEventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + Uri: { parse: (s: string) => ({ url: s }), from: (parts: object) => parts }, + window: { showQuickPick: ui.showQuickPick, showWarningMessage: ui.showWarningMessage }, + env: { openExternal: ui.openExternal }, + workspace: { getConfiguration: () => ({ get: (_key: string, def: unknown) => def }) }, + }; +}); + +const { CockpitProvider } = await import('../views/cockpit.js'); +const { BuilderTreeItem, BuilderGroupTreeItem } = await import('../views/builder-tree-item.js'); +const { MENU_RECORDS, COCKPIT_ENTRIES } = await import('../views/cockpit-menu-map.js'); +const { architectNameFromArg, extractBuilderId, extractIssueId } = await import('../commands/command-args.js'); +const { openDevUrl } = await import('../commands/open-dev-url.js'); +const { toWorkspaceTarget } = await import('../views/tower.js'); + +const EXT_SRC = readFileSync(resolve(__dirname, '../extension.ts'), 'utf8'); +const SWITCH_SRC = readFileSync(resolve(__dirname, '../commands/switch-workspace.ts'), 'utf8'); + +const HERE = '/work/codev'; +const OTHER = '/work/market'; +const noEvent = () => ({ dispose() {} }); + +function builder(id: string, architect: string): OverviewBuilder { + return { + id, issueId: id.split('-')[1], issueTitle: id, phase: 'implement', protocolPhase: 'implement', mode: 'strict', + gates: {}, worktreePath: '', roleId: null, protocol: id.split('-')[0], planPhases: [], progress: 0, + blocked: null, blockedGate: null, blockedSince: null, startedAt: null, idleMs: 0, lastDataAt: null, + spawnedByArchitect: architect, area: 'Uncategorized', prReady: false, + } as unknown as OverviewBuilder; +} + +const DATA = { + builders: [builder('spir-10', 'main'), builder('air-11', 'web')], + architects: [{ name: 'main' }, { name: 'web' }], + backlog: [], pendingPRs: [], recentlyClosed: [], heldCount: 0, mailboxEscalated: false, queuedFeedback: {}, +} as unknown as OverviewData; + +const fleet = [ + { workspace: { path: HERE, name: 'codev', active: true, proxyUrl: '', terminals: 1 }, attention: deriveAttention(DATA), overview: DATA }, + { workspace: { path: OTHER, name: 'marketmaker', active: true, proxyUrl: '', terminals: 1 }, attention: deriveAttention(DATA), overview: DATA }, +]; + +const cockpit = new CockpitProvider({ + connectionManager: { + getState: () => 'connected', getWorkspacePath: () => HERE, getWindowRoot: () => HERE, onStateChange: noEvent, onSSEEvent: noEvent, + } as never, + terminalManager: { listDevTerminals: () => [], onDidChangeDevTerminals: noEvent }, + loadWorktreeConfig: async () => null, + towerCache: { getFleet: () => fleet, isLoaded: () => true, getOverview: () => DATA, onDidChange: noEvent } as never, + overviewCache: { getData: () => DATA, onDidChange: noEvent } as never, + diffCache: { getDiff: async () => ({ baseRef: 'main', files: [] }) } as never, + builderWorktreeWindow: false, + connection: 'auto', +}); + +/** The Cockpit's nodes: this window's workspace node, another's, and this window's agent rows. */ +async function nodes() { + const [root] = await cockpit.getChildren(); + const workspaces = await cockpit.getChildren(root); + const own = workspaces.find(n => cockpit.getTreeItem(n).contextValue?.startsWith('cockpit-workspace-current')); + const other = workspaces.find(n => cockpit.getTreeItem(n).contextValue === 'tower-workspace-active'); + const architects = await cockpit.getChildren(own); + const sibling = architects.find(n => cockpit.getTreeItem(n).contextValue === 'cockpit-architect-sibling'); + const main = architects.find(n => cockpit.getTreeItem(n).contextValue === 'cockpit-architect-main'); + const [builderRow] = await cockpit.getChildren(main); + if (!own || !other || !sibling || !main || !(builderRow instanceof BuilderTreeItem) || !(sibling instanceof BuilderGroupTreeItem)) { + throw new Error('fixture: a Cockpit node is missing'); + } + return { own, other, sibling, builderRow }; +} + +/** The text of one command's registration in `src`, from its id to the next registration. */ +function registration(src: string, command: string): string { + const start = src.search(new RegExp(`reg(?:Cli)?\\('${command.replace(/\./g, '\\.')}'`)); + if (start < 0) { throw new Error(`no registration for ${command}`); } + const rest = src.slice(start + 1); + const next = rest.search(/\n\t\treg(?:Cli)?\(/); + return next < 0 ? rest : rest.slice(0, next); +} + +beforeEach(() => { + ui.showQuickPick.mockReset(); + ui.openExternal.mockReset(); + ui.showWarningMessage.mockReset(); +}); + +describe("this window's builder rows: the Agents commands, identical", () => { + const builderCommands = [...new Set(MENU_RECORDS + .filter(r => 'same' in r.cockpit && r.source.when.startsWith('view == codev.agents')) + .map(r => r.source.command))]; + + it('cover every Agents builder-row command', () => { + expect(builderCommands.sort()).toEqual([ + 'codev.approveGate', 'codev.openBuilderById', 'codev.openWorktreeFolder', 'codev.openWorktreeWindow', + 'codev.runWorktreeDev', 'codev.runWorktreeSetup', 'codev.stopWorktreeDev', 'codev.viewDiff', + 'codev.viewPlanFile', 'codev.viewReviewFile', 'codev.viewSpecFile', + ]); + }); + + for (const command of builderCommands) { + it(`${command} resolves a Cockpit builder row to its builder id (or ignores it)`, async () => { + const { builderRow } = await nodes(); + const handler = registration(EXT_SRC, command); + if (command === 'codev.stopWorktreeDev') { + // Stops the single dev slot, whichever row asked. + expect(handler).toMatch(/^[^(]*\(\s*'codev\.stopWorktreeDev', \(\) =>/); + return; + } + expect(handler).toMatch(/extractBuilderId\(arg\)/); + // The Cockpit row's id is workspace-scoped; the resolver reads the builder id, not the row id. + expect(builderRow.id).toMatch(/^ws:\/work\/codev\|/); + expect(extractBuilderId(builderRow)).toBe('spir-10'); + }); + } +}); + +describe('relocated commands, given the Cockpit node their entry attaches to', () => { + it('Remove Architect resolves the name from the Cockpit sibling row, not from its label', async () => { + const { sibling } = await nodes(); + expect(cockpit.getTreeItem(sibling).label).toBe('WEB (1)'); + expect(architectNameFromArg(sibling)).toBe('web'); + expect(registration(EXT_SRC, 'codev.removeArchitect')).toMatch(/async \(arg: unknown\) => \{[^]*?const name = architectNameFromArg\(arg\);/); + }); + + it('Open Dev URL… falls through to its QuickPick for the workspace row (or opens the only URL)', async () => { + const { own } = await nodes(); + const two = [{ label: 'App', url: 'http://localhost:3000' }, { label: 'Admin', url: 'http://localhost:3001' }]; + const manager = (devUrls: typeof two) => ({ + getClient: () => ({ getWorktreeConfig: async () => ({ symlinks: [], postSpawn: [], devCommand: null, devUrls }) }), + getWorkspacePath: () => HERE, + getState: () => 'connected', + }) as never; + + ui.showQuickPick.mockResolvedValue({ url: 'http://localhost:3001' }); + await openDevUrl(manager(two), own); + expect(ui.showQuickPick).toHaveBeenCalledWith( + [{ label: 'App', description: 'http://localhost:3000', url: 'http://localhost:3000' }, + { label: 'Admin', description: 'http://localhost:3001', url: 'http://localhost:3001' }], + { placeHolder: 'Open which dev URL?' }, + ); + expect(ui.openExternal).toHaveBeenCalledWith({ url: 'http://localhost:3001' }); + + ui.openExternal.mockReset(); + await openDevUrl(manager([two[0]]), own); + expect(ui.openExternal).toHaveBeenCalledWith({ url: 'http://localhost:3000' }); + + // The registration hands the raw argument over; a dev-URL row's string still opens directly. + expect(registration(EXT_SRC, 'codev.openDevUrl')).toMatch(/\(urlArg\?: unknown\) => openDevUrl\(connectionManager!, urlArg\)/); + ui.openExternal.mockReset(); + await openDevUrl(manager(two), 'http://localhost:4000'); + expect(ui.openExternal).toHaveBeenCalledWith({ url: 'http://localhost:4000' }); + }); + + it("Spawn Builder's extractIssueId yields no id from a workspace node, so the full picker opens", async () => { + const { own } = await nodes(); + expect(extractIssueId(own)).toBeUndefined(); + expect(registration(EXT_SRC, 'codev.spawnBuilder')).toMatch(/spawnBuilder\(extractIssueId\(arg\)\)/); + }); + + it("Add Architect, New Shell, Start Dev, Stop Dev and Open Web Interface ignore the argument (this window's workspace)", () => { + for (const command of ['codev.addArchitect', 'codev.newShell', 'codev.runWorkspaceDev', 'codev.stopWorkspaceDev', + 'codev.stopWorktreeDev', 'codev.cockpit.openWebInterface']) { + expect(registration(EXT_SRC, command), command).toMatch(new RegExp(`^[^(]*\\(\\s*'${command.replace(/\./g, '\\.')}', (async )?\\(\\) =>`)); + } + }); + + it("Open and Deactivate act on the Cockpit workspace node's own workspace", async () => { + const { other } = await nodes(); + expect(toWorkspaceTarget(other)).toEqual({ path: OTHER, active: true, name: 'marketmaker', isCurrent: false }); + for (const command of ['OPEN_WORKSPACE_COMMAND', "'codev.tower.deactivateWorkspace'"]) { + const start = SWITCH_SRC.indexOf(`regCli(${command}`); + expect(start, command).toBeGreaterThan(-1); + expect(SWITCH_SRC.slice(start, start + 200)).toMatch(/\(arg: unknown\) => \{\s*const target = toWorkspaceTarget\(arg\);/); + } + }); + + it('every relocated row entry runs one of the commands checked above (title-bar entries pass no element)', () => { + const checked = new Set(['codev.removeArchitect', 'codev.openDevUrl', 'codev.spawnBuilder', 'codev.addArchitect', 'codev.newShell', + 'codev.runWorkspaceDev', 'codev.stopWorkspaceDev', 'codev.stopWorktreeDev', 'codev.cockpit.openWebInterface']); + const rowEntries = Object.values(COCKPIT_ENTRIES).filter(e => e.location === 'view/item/context'); + expect(rowEntries.map(e => e.command).filter(c => !checked.has(c))).toEqual([]); + }); +}); diff --git a/apps/vscode/src/__tests__/cockpit-menu-parity.test.ts b/apps/vscode/src/__tests__/cockpit-menu-parity.test.ts new file mode 100644 index 000000000..101861b68 --- /dev/null +++ b/apps/vscode/src/__tests__/cockpit-menu-parity.test.ts @@ -0,0 +1,327 @@ +/** + * Spec 1963 Phase 5: the Cockpit's menu parity. `views/cockpit-menu-map.ts` is the checked-in oracle: + * one record per source-view menu entry, Workspace-view row click and `viewsWelcome` entry. This test + * holds `package.json` and the providers to it. It fails when: + * - a source entry has no record, or differs from its record's snapshot; + * - a mapped Cockpit entry is missing from `package.json` (or a Cockpit entry maps to no record); + * - a navigate-only value (`cockpit-remote-*`, another workspace's `tower-workspace-*`) or this + * window's workspace row value matches a builder or architect entry's `viewItem`; + * - the builder-worktree parent row could reach Spawn Builder, New Shell or Add Architect; + * - *Remove Architect*'s `when` matches `cockpit-architect-main`; + * - a Workspace-view row click or a welcome entry has no record. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { OverviewData } from '@cluesmith/codev-types'; +import { deriveAttention } from '@cluesmith/codev-sdk/builder-helpers'; +import type { ResolvedWorktreeConfig } from '../load-worktree-config.js'; + +vi.mock('vscode', () => { + class FakeEventEmitter { + private listeners: Array<(e: T) => void> = []; + readonly event = (listener: (e: T) => void) => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter(l => l !== listener); } }; + }; + fire = (e: T) => { this.listeners.forEach(l => l(e)); }; + dispose = () => {}; + } + class TreeItem { + id?: string; + tooltip?: string; + description?: string; + contextValue?: string; + iconPath?: unknown; + command?: unknown; + constructor(public label: string, public collapsibleState?: number) {} + } + class ThemeIcon { constructor(public id: string, public color?: unknown) {} } + class ThemeColor { constructor(public id: string) {} } + return { + EventEmitter: FakeEventEmitter, + TreeItem, + ThemeIcon, + ThemeColor, + TreeItemCollapsibleState: { None: 0, Collapsed: 1, Expanded: 2 }, + Uri: { parse: (s: string) => ({ toString: () => s }) }, + workspace: { getConfiguration: () => ({ get: (_key: string, def: unknown) => def }) }, + }; +}); + +const { MENU_RECORDS, ROW_CLICK_RECORDS, WELCOME_RECORDS, COCKPIT_ENTRIES } = await import('../views/cockpit-menu-map.js'); +const { CockpitProvider, cockpitWorkspaceContext, DEV_SLOT_KINDS } = await import('../views/cockpit.js'); +const { WorkspaceProvider } = await import('../views/workspace.js'); +const { REMOTE_CONTEXT } = await import('../views/architect-tree.js'); + +type MenuEntry = (typeof MENU_RECORDS)[number]['source']; +type CockpitProviderType = InstanceType; + +const PKG = JSON.parse(readFileSync(resolve(__dirname, '../../package.json'), 'utf8')); +const LOCATIONS = ['view/item/context', 'view/title'] as const; +const ALL_ENTRIES: MenuEntry[] = LOCATIONS.flatMap(location => + (PKG.contributes.menus[location] as Array>).map(e => ({ location, ...e }))); +const SOURCE_VIEW = /^view == codev\.(workspace|agents|tower)( |$)/; +const SOURCE_ENTRIES = ALL_ENTRIES.filter(e => SOURCE_VIEW.test(e.when)); +const COCKPIT_MENU = ALL_ENTRIES.filter(e => /^view == codev\.cockpit( |$)/.test(e.when)); + +const key = (e: MenuEntry) => JSON.stringify([e.location, e.command, e.when, e.group ?? null]); +const COCKPIT_KEYS = new Set(COCKPIT_MENU.map(key)); + +/** The Cockpit entry a `same` record names: the source entry at the Cockpit's view. */ +function sameAtCockpit(source: MenuEntry): MenuEntry { + return { ...source, when: source.when.replace(SOURCE_VIEW, 'view == codev.cockpit$2') }; +} + +/** Whether a `when` clause's `viewItem` condition accepts `value` (`false` when it has none). */ +function viewItemMatches(when: string, value: string): boolean { + const regex = when.match(/viewItem =~ \/(.+?)\/(?: |$)/); + if (regex) { return new RegExp(regex[1]).test(value); } + const exact = when.match(/viewItem == (\S+)/); + if (exact) { return exact[1] === value; } + return false; +} + +// Every contextValue a Cockpit row can carry, by who owns the row. +const ROLES = ['current', 'parent'] as const; +const ownValues = (role: (typeof ROLES)[number]) => + DEV_SLOT_KINDS.flatMap(slot => [false, true].map(urls => cockpitWorkspaceContext(role, slot, urls))); +const CURRENT_VALUES = ownValues('current'); +const PARENT_VALUES = ownValues('parent'); +const OTHER_WORKSPACE_VALUES = ['tower-workspace-active', 'tower-workspace-dormant']; +const NAVIGATE_VALUES = Object.values(REMOTE_CONTEXT); + +/** Cockpit entries that act on this window's builder or architect rows. */ +const AGENT_ROW_ENTRIES = [ + ...MENU_RECORDS.filter(r => r.source.when.startsWith('view == codev.agents') && r.source.location === 'view/item/context') + .map(r => sameAtCockpit(r.source)), + COCKPIT_ENTRIES.removeArchitect, +]; + +// ── Menu entries ───────────────────────────────────────────────────────────── + +describe('every source-view menu entry has exactly one record, and matches its snapshot', () => { + it('27 source entries today: 18 row entries and 9 title-bar entries', () => { + expect(SOURCE_ENTRIES.filter(e => e.location === 'view/item/context')).toHaveLength(18); + expect(SOURCE_ENTRIES.filter(e => e.location === 'view/title')).toHaveLength(9); + expect(MENU_RECORDS).toHaveLength(27); + }); + + for (const entry of SOURCE_ENTRIES) { + it(`${entry.location} ${entry.command} (${entry.group})`, () => { + const records = MENU_RECORDS.filter(r => key(r.source) === key(entry)); + expect(records, 'no record for this entry, or it differs from its record\'s snapshot').toHaveLength(1); + }); + } + + it('no record names an entry that package.json no longer has', () => { + const live = new Set(SOURCE_ENTRIES.map(key)); + expect(MENU_RECORDS.filter(r => !live.has(key(r.source))).map(r => r.source)).toEqual([]); + }); +}); + +describe("every record's Cockpit placement is in package.json", () => { + for (const record of MENU_RECORDS) { + const { source, cockpit } = record; + if ('same' in cockpit) { + it(`same: ${source.command} (${source.group}) at ${cockpit.same}`, () => { + const expected = sameAtCockpit(source); + expect(COCKPIT_KEYS.has(key(expected)), `missing ${JSON.stringify(expected)}`).toBe(true); + expect(expected.when).toContain(cockpit.same); + }); + } else if ('relocated' in cockpit) { + it(`relocated: ${source.command} (${source.group})`, () => { + for (const target of cockpit.relocated) { + expect(COCKPIT_KEYS.has(key(target)), `missing ${JSON.stringify(target)}`).toBe(true); + } + }); + } + } + + it('only the three group-by cycle buttons are excluded, each with its reason', () => { + const excluded = MENU_RECORDS.filter(r => 'excluded' in r.cockpit); + expect(excluded.map(r => r.source.command).sort()).toEqual([ + 'codev.agentsCycleGroupFromArchitect', 'codev.agentsCycleGroupFromArea', 'codev.agentsCycleGroupFromStage', + ]); + for (const r of excluded) { expect((r.cockpit as { excluded: string }).excluded.length).toBeGreaterThan(20); } + }); + + it('every Cockpit menu entry is one some record maps to (no unrecorded additions)', () => { + const mapped = new Set(); + for (const { source, cockpit } of MENU_RECORDS) { + if ('same' in cockpit) { mapped.add(key(sameAtCockpit(source))); } + if ('relocated' in cockpit) { cockpit.relocated.forEach(e => mapped.add(key(e))); } + } + for (const { cockpit } of ROW_CLICK_RECORDS) { + if ('relocated' in cockpit) { cockpit.relocated.forEach(e => mapped.add(key(e))); } + } + expect(COCKPIT_MENU.filter(e => !mapped.has(key(e)))).toEqual([]); + }); +}); + +// ── contextValues: nothing attaches where it must not ──────────────────────── + +describe('context values: menus attach only to the rows they belong to', () => { + it('no navigate-only row or workspace row matches a builder or architect entry', () => { + const forbidden = [...NAVIGATE_VALUES, ...OTHER_WORKSPACE_VALUES, ...CURRENT_VALUES, ...PARENT_VALUES]; + const hits = AGENT_ROW_ENTRIES.flatMap(e => forbidden.filter(v => viewItemMatches(e.when, v)).map(v => `${e.command} ← ${v}`)); + expect(hits).toEqual([]); + }); + + it("the builder-worktree parent row reaches no spawn, shell or architect action; other workspaces' rows no own-row action", () => { + const ownOnly = [COCKPIT_ENTRIES.spawnInline, COCKPIT_ENTRIES.shellInline, COCKPIT_ENTRIES.addArchitectInline, + COCKPIT_ENTRIES.spawn, COCKPIT_ENTRIES.shell, COCKPIT_ENTRIES.addArchitect]; + const parentHits = ownOnly.flatMap(e => PARENT_VALUES.filter(v => viewItemMatches(e.when, v)).map(v => `${e.command} ← ${v}`)); + expect(parentHits).toEqual([]); + const workspaceRowEntries = [...ownOnly, COCKPIT_ENTRIES.openWebInterface, COCKPIT_ENTRIES.startDev, + COCKPIT_ENTRIES.stopDev, COCKPIT_ENTRIES.stopOtherDev, COCKPIT_ENTRIES.openDevUrl]; + const remoteHits = workspaceRowEntries.flatMap(e => + [...NAVIGATE_VALUES, ...OTHER_WORKSPACE_VALUES].filter(v => viewItemMatches(e.when, v)).map(v => `${e.command} ← ${v}`)); + expect(remoteHits).toEqual([]); + }); + + it("Remove Architect attaches to a sibling architect row, never to main's", () => { + expect(viewItemMatches(COCKPIT_ENTRIES.removeArchitect.when, 'cockpit-architect-sibling')).toBe(true); + expect(viewItemMatches(COCKPIT_ENTRIES.removeArchitect.when, 'cockpit-architect-main')).toBe(false); + for (const entry of COCKPIT_MENU.filter(e => e.command === 'codev.removeArchitect')) { + expect(viewItemMatches(entry.when, 'cockpit-architect-main')).toBe(false); + } + }); + + it("this window's row offers exactly what the Workspace view offers for its dev slot and dev URLs", () => { + const rowEntries = { + spawn: COCKPIT_ENTRIES.spawn, shell: COCKPIT_ENTRIES.shell, addArchitect: COCKPIT_ENTRIES.addArchitect, + web: COCKPIT_ENTRIES.openWebInterface, start: COCKPIT_ENTRIES.startDev, stop: COCKPIT_ENTRIES.stopDev, + 'stop-other': COCKPIT_ENTRIES.stopOtherDev, urls: COCKPIT_ENTRIES.openDevUrl, + }; + for (const role of ROLES) { + for (const slot of DEV_SLOT_KINDS) { + for (const urls of [false, true]) { + const value = cockpitWorkspaceContext(role, slot, urls); + const offered = Object.entries(rowEntries).filter(([, e]) => viewItemMatches(e.when, value)).map(([name]) => name).sort(); + const expected = ['web']; + if (role === 'current') { expected.push('spawn', 'shell', 'addArchitect'); } + if (slot !== 'none') { expected.push(slot); } + if (urls) { expected.push('urls'); } + expect(offered, value).toEqual(expected.sort()); + } + } + } + }); +}); + +// ── Workspace-view row clicks ──────────────────────────────────────────────── + +const HERE = '/work/codev'; +const noEvent = () => ({ dispose() {} }); +const ALL_ON: ResolvedWorktreeConfig = { + symlinks: [], postSpawn: [], devCommand: 'pnpm dev', + devUrls: [{ label: 'App', url: 'http://localhost:3000' }, { label: 'Admin', url: 'http://localhost:3001' }], +}; + +/** Every row the Workspace view renders with `devs` running, Architects expanded. */ +async function workspaceViewRows(devs: string[]) { + const connectionManager = { + getState: () => 'connected', + getWorkspacePath: () => HERE, + getWindowRoot: () => HERE, + getBuilderWorktree: () => null, + getClient: () => ({ + getWorktreeConfig: async () => ALL_ON, + getWorkspaceStatus: async () => ({ + terminals: [{ type: 'architect', architectName: 'main' }, { type: 'architect', architectName: 'web' }], + }), + }), + onStateChange: noEvent, + onSSEEvent: noEvent, + }; + const terminalManager = { + listDevTerminals: () => devs.map((builderId, i) => ({ builderId, terminalId: `t${i}` })), + onDidChangeDevTerminals: noEvent, + }; + const view = new WorkspaceProvider(connectionManager as never, terminalManager as never); + const top = await view.getChildren(); + const architects = await view.getChildren(top.find(r => r.id === 'workspace-architects-root')); + return [...top, ...architects]; +} + +/** A Cockpit over one active workspace (this window's) whose overview lists `main` and a sibling. */ +function cockpitWith(opts: { fleetLoaded?: boolean; connection?: 'auto' | 'manual' | 'none'; state?: string } = {}): CockpitProviderType { + const data = { builders: [], architects: [{ name: 'main' }, { name: 'web' }], backlog: [], pendingPRs: [], recentlyClosed: [] } as unknown as OverviewData; + return new CockpitProvider({ + connectionManager: { + getState: () => opts.state ?? 'connected', + getWorkspacePath: () => HERE, + getWindowRoot: () => HERE, + onStateChange: noEvent, + onSSEEvent: noEvent, + } as never, + terminalManager: { listDevTerminals: () => [], onDidChangeDevTerminals: noEvent }, + loadWorktreeConfig: async () => null, + towerCache: { + getFleet: () => [{ workspace: { path: HERE, name: 'codev', active: true, proxyUrl: '', terminals: 1 }, attention: deriveAttention(data), overview: data }], + isLoaded: () => opts.fleetLoaded ?? true, + getOverview: () => data, + onDidChange: noEvent, + } as never, + overviewCache: { getData: () => data, onDidChange: noEvent } as never, + diffCache: {} as never, + builderWorktreeWindow: false, + connection: opts.connection ?? 'auto', + }); +} + +describe('every Workspace-view row click has a record', () => { + it('across the three dev states, every clickable row and its command is recorded', async () => { + const seen = new Map(); + for (const devs of [[], ['main'], ['spir-10']]) { + for (const row of await workspaceViewRows(devs)) { + const command = (row.command as { command?: string } | undefined)?.command; + if (command && row.contextValue) { seen.set(row.contextValue, command); } + } + } + expect([...seen.entries()].sort()).toEqual(ROW_CLICK_RECORDS.map(r => [r.row, r.command]).sort()); + }); + + it("architect rows' click moves onto the Cockpit's architect rows, main and sibling", async () => { + const cockpit = cockpitWith(); + const [root] = await cockpit.getChildren(); + const [ws] = await cockpit.getChildren(root); + const architects = (await cockpit.getChildren(ws)).map(n => cockpit.getTreeItem(n)); + for (const record of ROW_CLICK_RECORDS) { + if (!('rowClick' in record.cockpit)) { continue; } + const { contextValue, command } = record.cockpit.rowClick; + const rows = architects.filter(r => contextValue.test(r.contextValue ?? '')); + expect(rows.length, `${record.row} → a Cockpit row matching ${contextValue}`).toBeGreaterThan(0); + for (const row of rows) { expect((row.command as { command: string }).command).toBe(command); } + } + }); +}); + +// ── viewsWelcome ───────────────────────────────────────────────────────────── + +describe("every viewsWelcome entry of the three views has a record", () => { + it('the records snapshot exactly the welcome entries package.json declares for them', () => { + const welcome = (PKG.contributes.viewsWelcome as Array<{ view: string; contents: string; when: string }>) + .filter(w => /^codev\.(workspace|agents|tower)$/.test(w.view)); + expect(welcome).toEqual(WELCOME_RECORDS.map(r => r.source)); + }); + + it("each mapped welcome is a state row the Cockpit's Tower root shows in that kind of window", async () => { + for (const { cockpit } of WELCOME_RECORDS) { + if (!('stateRow' in cockpit)) { + expect('excluded' in cockpit && cockpit.excluded.length > 20).toBe(true); + continue; + } + const { window, label, command } = cockpit.stateRow; + const provider = window === 'dormant' + ? cockpitWith({ fleetLoaded: false, connection: 'none', state: 'disconnected' }) + : cockpitWith({ fleetLoaded: false, connection: 'auto', state: 'connecting' }); + const [root] = await provider.getChildren(); + const [row] = (await provider.getChildren(root)).map(n => provider.getTreeItem(n)); + expect(row.label).toBe(label); + if (command) { expect((row.command as { command: string }).command).toBe(command); } + } + }); +}); diff --git a/apps/vscode/src/views/cockpit-menu-map.ts b/apps/vscode/src/views/cockpit-menu-map.ts new file mode 100644 index 000000000..67261e01b --- /dev/null +++ b/apps/vscode/src/views/cockpit-menu-map.ts @@ -0,0 +1,242 @@ +/** + * The Cockpit's menu-parity oracle (Spec 1963): where every affordance of the three source views + * (`codev.workspace`, `codev.agents`, `codev.tower`) lives in the Cockpit. Checked in, so a change on + * either side is a reviewed diff here; `cockpit-menu-parity.test.ts` holds `package.json` to it. + * + * Three kinds of record, one per source affordance: + * - **menu entries**: every `view/item/context` and `view/title` entry of the source views, with its + * text as a snapshot; + * - **row clicks**: every Workspace-view row that runs a command when clicked; + * - **welcome content**: every `viewsWelcome` entry of the source views. + * + * Each record says where the affordance went: `same` (the same command, group and `when` at the + * Cockpit's own view, matching the given `viewItem` clause), `relocated` (to named Cockpit menu + * entries, or to a Cockpit row's own click), or `excluded` (with the reason). Nothing disappears + * silently. Pure data, no `vscode` import. + */ + +/** A `view/item/context` or `view/title` entry as `package.json` declares it. */ +export interface MenuEntry { + location: 'view/item/context' | 'view/title'; + command: string; + when: string; + group?: string; +} + +/** Where a source affordance lives in the Cockpit. */ +export type CockpitPlacement = + /** The same entry at `view == codev.cockpit`, keyed on this `viewItem` clause. */ + | { same: string } + /** Moved to these Cockpit menu entries. */ + | { relocated: MenuEntry[] } + /** Moved to a Cockpit row's own click: rows with this `contextValue` run this command. */ + | { rowClick: { contextValue: RegExp; command: string } } + /** Moved to a Tower-root state row the Cockpit shows in the same kind of window. */ + | { stateRow: { window: 'auto-connecting' | 'dormant'; label: string; command?: string } } + /** Not in the Cockpit, and why. */ + | { excluded: string }; + +export interface MenuRecord { + source: MenuEntry; + cockpit: CockpitPlacement; +} + +export interface RowClickRecord { + /** The Workspace-view row, by its `contextValue`. */ + row: string; + command: string; + cockpit: CockpitPlacement; +} + +export interface WelcomeRecord { + source: { view: string; contents: string; when: string }; + cockpit: CockpitPlacement; +} + +// ── The Cockpit's own entries the records point at ────────────────────────── + +const VIEW = 'view == codev.cockpit'; +const CURRENT_ROW = `${VIEW} && viewItem =~ /^cockpit-workspace-current(-.*)?$/`; +const ownRow = (rest: string) => `${VIEW} && viewItem =~ /^cockpit-workspace-(current|parent)${rest}$/`; + +const ctx = (command: string, when: string, group: string): MenuEntry => ({ location: 'view/item/context', command, when, group }); +const title = (command: string, when: string, group: string): MenuEntry => ({ location: 'view/title', command, when, group }); + +export const COCKPIT_ENTRIES = { + removeArchitect: ctx('codev.removeArchitect', `${VIEW} && viewItem == cockpit-architect-sibling`, '1_primary@1'), + spawnInline: ctx('codev.spawnBuilder', CURRENT_ROW, 'inline@3'), + shellInline: ctx('codev.newShell', CURRENT_ROW, 'inline@4'), + addArchitectInline: ctx('codev.addArchitect', CURRENT_ROW, 'inline@5'), + spawn: ctx('codev.spawnBuilder', CURRENT_ROW, '1_workspace@1'), + shell: ctx('codev.newShell', CURRENT_ROW, '1_workspace@2'), + addArchitect: ctx('codev.addArchitect', CURRENT_ROW, '1_workspace@3'), + openWebInterface: ctx('codev.cockpit.openWebInterface', ownRow('(-.*)?'), '2_web@1'), + startDev: ctx('codev.runWorkspaceDev', ownRow('-dev-start(-devurls)?'), '3_dev@1'), + stopDev: ctx('codev.stopWorkspaceDev', ownRow('-dev-stop(-devurls)?'), '3_dev@1'), + stopOtherDev: ctx('codev.stopWorktreeDev', ownRow('-dev-stop-other(-devurls)?'), '3_dev@1'), + openDevUrl: ctx('codev.openDevUrl', ownRow('(-.*)?-devurls'), '3_dev@2'), + refresh: title('codev.cockpit.refresh', VIEW, 'navigation@1'), + accordionOff: title('codev.disableBuildersAutoCollapse', `${VIEW} && codev.buildersAutoCollapse`, 'navigation@2'), + accordionOn: title('codev.enableBuildersAutoCollapse', `${VIEW} && !codev.buildersAutoCollapse`, 'navigation@2'), + fileListView: title('codev.disableBuildersFileTreeMode', `${VIEW} && codev.buildersFileViewAsTree`, 'navigation@3'), + fileTreeView: title('codev.enableBuildersFileTreeMode', `${VIEW} && !codev.buildersFileViewAsTree`, 'navigation@3'), +} as const satisfies Record; + +/** The `viewItem` clause every builder-row entry of the Agents view keys on (all three families). */ +const ANY_BUILDER = 'viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/'; +const AXIS_EXCLUDED = 'The Cockpit fixes the architect axis (Tower → workspaces → architects → builders), so there is ' + + 'no grouping axis to cycle. Stage and area grouping stay in the Agents view.'; + +// ── Menu entries: 18 `view/item/context` + 9 `view/title` ────────────────── + +export const MENU_RECORDS: readonly MenuRecord[] = [ + // Tower workspace rows: the Cockpit's other workspaces keep the Tower view's contextValues. + { + source: ctx('codev.tower.openWorkspace', 'view == codev.tower && viewItem =~ /^tower-workspace-(active|dormant)$/', 'inline@1'), + cockpit: { same: 'viewItem =~ /^tower-workspace-(active|dormant)$/' }, + }, + { + source: ctx('codev.tower.deactivateWorkspace', 'view == codev.tower && viewItem == tower-workspace-active', 'inline@2'), + cockpit: { same: 'viewItem == tower-workspace-active' }, + }, + // Workspace view. + { + source: ctx('codev.removeArchitect', 'view == codev.workspace && viewItem == workspace-architect-sibling', '1_primary@1'), + cockpit: { relocated: [COCKPIT_ENTRIES.removeArchitect] }, + }, + { + source: ctx('codev.addArchitect', 'view == codev.workspace && viewItem == workspace-architects-root', 'inline@1'), + cockpit: { relocated: [COCKPIT_ENTRIES.addArchitectInline, COCKPIT_ENTRIES.addArchitect] }, + }, + { + source: ctx('codev.runWorkspaceDev', 'view == codev.workspace && viewItem == workspace-dev-start', '1_primary@1'), + cockpit: { relocated: [COCKPIT_ENTRIES.startDev] }, + }, + { + source: ctx('codev.stopWorkspaceDev', 'view == codev.workspace && viewItem == workspace-dev-stop', '1_primary@1'), + cockpit: { relocated: [COCKPIT_ENTRIES.stopDev] }, + }, + // Agents builder rows: identical on this window's builder rows. + { + source: ctx('codev.approveGate', 'view == codev.agents && viewItem =~ /^blocked-builder-/', 'inline@1'), + cockpit: { same: 'viewItem =~ /^blocked-builder-/' }, + }, + { + source: ctx('codev.openBuilderById', `view == codev.agents && ${ANY_BUILDER}`, '1_primary@1'), + cockpit: { same: ANY_BUILDER }, + }, + { + source: ctx('codev.approveGate', 'view == codev.agents && viewItem =~ /^blocked-builder-/', '1_primary@2'), + cockpit: { same: 'viewItem =~ /^blocked-builder-/' }, + }, + { + source: ctx('codev.viewSpecFile', 'view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir)(-review)?$/', '1_primary@3'), + cockpit: { same: 'viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir)(-review)?$/' }, + }, + { + source: ctx('codev.viewPlanFile', 'view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir|pir)(-review)?$/', '1_primary@4'), + cockpit: { same: 'viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir|pir)(-review)?$/' }, + }, + { + source: ctx('codev.viewReviewFile', 'view == codev.agents && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-((spir|aspir|air)(-review)?|pir-review)$/', '1_primary@5'), + cockpit: { same: 'viewItem =~ /^(builder|blocked-builder|awaiting-builder)-((spir|aspir|air)(-review)?|pir-review)$/' }, + }, + { source: ctx('codev.viewDiff', `view == codev.agents && ${ANY_BUILDER}`, '2_worktree@0'), cockpit: { same: ANY_BUILDER } }, + { source: ctx('codev.openWorktreeWindow', `view == codev.agents && ${ANY_BUILDER}`, '2_worktree@1'), cockpit: { same: ANY_BUILDER } }, + { source: ctx('codev.openWorktreeFolder', `view == codev.agents && ${ANY_BUILDER}`, '2_worktree@2'), cockpit: { same: ANY_BUILDER } }, + { source: ctx('codev.runWorktreeSetup', `view == codev.agents && ${ANY_BUILDER}`, '3_dev@1'), cockpit: { same: ANY_BUILDER } }, + { + source: ctx('codev.runWorktreeDev', `view == codev.agents && ${ANY_BUILDER} && codev.hasDevCommand`, '3_dev@2'), + cockpit: { same: ANY_BUILDER }, + }, + { + source: ctx('codev.stopWorktreeDev', `view == codev.agents && ${ANY_BUILDER} && codev.hasDevCommand`, '3_dev@3'), + cockpit: { same: ANY_BUILDER }, + }, + // Title bars. + { source: title('codev.tower.refresh', 'view == codev.tower', 'navigation@1'), cockpit: { relocated: [COCKPIT_ENTRIES.refresh] } }, + { source: title('codev.refreshOverview', 'view == codev.agents', 'navigation@2'), cockpit: { relocated: [COCKPIT_ENTRIES.refresh] } }, + { + source: title('codev.disableBuildersAutoCollapse', 'view == codev.agents && codev.buildersAutoCollapse', 'navigation@3'), + cockpit: { relocated: [COCKPIT_ENTRIES.accordionOff] }, + }, + { + source: title('codev.enableBuildersAutoCollapse', 'view == codev.agents && !codev.buildersAutoCollapse', 'navigation@3'), + cockpit: { relocated: [COCKPIT_ENTRIES.accordionOn] }, + }, + { + source: title('codev.disableBuildersFileTreeMode', 'view == codev.agents && codev.buildersFileViewAsTree', 'navigation@4'), + cockpit: { relocated: [COCKPIT_ENTRIES.fileListView] }, + }, + { + source: title('codev.enableBuildersFileTreeMode', 'view == codev.agents && !codev.buildersFileViewAsTree', 'navigation@4'), + cockpit: { relocated: [COCKPIT_ENTRIES.fileTreeView] }, + }, + { + source: title('codev.agentsCycleGroupFromStage', "view == codev.agents && (!codev.buildersGroupBy || codev.buildersGroupBy == 'stage')", 'navigation@1'), + cockpit: { excluded: AXIS_EXCLUDED }, + }, + { + source: title('codev.agentsCycleGroupFromArea', "view == codev.agents && codev.buildersGroupBy == 'area'", 'navigation@1'), + cockpit: { excluded: AXIS_EXCLUDED }, + }, + { + source: title('codev.agentsCycleGroupFromArchitect', "view == codev.agents && codev.buildersGroupBy == 'architect'", 'navigation@1'), + cockpit: { excluded: AXIS_EXCLUDED }, + }, +]; + +// ── Workspace-view row clicks ────────────────────────────────────────────── + +export const ROW_CLICK_RECORDS: readonly RowClickRecord[] = [ + { + row: 'workspace-architect-main', + command: 'codev.openArchitectTerminal', + cockpit: { rowClick: { contextValue: /^cockpit-architect-main$/, command: 'codev.openArchitectTerminal' } }, + }, + { + row: 'workspace-architect-sibling', + command: 'codev.openArchitectTerminal', + cockpit: { rowClick: { contextValue: /^cockpit-architect-sibling$/, command: 'codev.openArchitectTerminal' } }, + }, + { row: 'workspace-web', command: 'vscode.open', cockpit: { relocated: [COCKPIT_ENTRIES.openWebInterface] } }, + { row: 'workspace-spawn', command: 'codev.spawnBuilder', cockpit: { relocated: [COCKPIT_ENTRIES.spawnInline, COCKPIT_ENTRIES.spawn] } }, + { row: 'workspace-shell', command: 'codev.newShell', cockpit: { relocated: [COCKPIT_ENTRIES.shellInline, COCKPIT_ENTRIES.shell] } }, + { row: 'workspace-dev-start', command: 'codev.runWorkspaceDev', cockpit: { relocated: [COCKPIT_ENTRIES.startDev] } }, + { row: 'workspace-dev-stop', command: 'codev.stopWorkspaceDev', cockpit: { relocated: [COCKPIT_ENTRIES.stopDev] } }, + { row: 'workspace-dev-stop-other', command: 'codev.stopWorktreeDev', cockpit: { relocated: [COCKPIT_ENTRIES.stopOtherDev] } }, + // One row per `worktree.devUrls` entry becomes one *Open Dev URL…* entry: it opens the only URL, + // or picks among several. + { row: 'workspace-dev-url', command: 'codev.openDevUrl', cockpit: { relocated: [COCKPIT_ENTRIES.openDevUrl] } }, +]; + +// ── viewsWelcome: `codev.agents` has three; `codev.workspace` and `codev.tower` none ───────── + +export const WELCOME_RECORDS: readonly WelcomeRecord[] = [ + { + source: { view: 'codev.agents', contents: 'Loading Codev…', when: '!codev.stateKnown' }, + cockpit: { stateRow: { window: 'auto-connecting', label: 'Connecting to Tower…' } }, + }, + { + source: { + view: 'codev.agents', + contents: 'Open a folder containing a Codev project to get started.\n[Open Folder](command:workbench.action.files.openFolder)\nTo set up Codev in a project, run `codev init` in its root.', + when: 'codev.stateKnown && !codev.hasWorkspace && !codev.ideMode', + }, + // A dormant window (#1144): the state row carries the same link, and its tooltip the same + // `codev init` hint. + cockpit: { stateRow: { window: 'dormant', label: 'Not connected to Tower', command: 'workbench.action.files.openFolder' } }, + }, + { + source: { + view: 'codev.agents', + contents: 'Welcome to Codev.\nOpen a project to spawn your first builder.\n[Open Folder](command:workbench.action.files.openFolder)\n[Open Recent](command:workbench.action.openRecent)\nNew here? Install the Codev CLI and learn the spawn flow.\n[Get Started](command:codev.openGettingStarted)', + when: 'codev.stateKnown && !codev.hasWorkspace && codev.ideMode', + }, + cockpit: { + excluded: 'An empty Codev IDE window connects to Tower, so the Cockpit lists every workspace Tower knows, each ' + + "with Open (inline) to open that workspace's window: that is the Cockpit's way into a project. The " + + "welcome's onboarding links (Open Folder, Open Recent, Get Started) stay on the Agents view, in the same window.", + }, + }, +]; From 67fda9e25975ae819d349920ef576b18a5e67067 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 02:59:00 -0800 Subject: [PATCH 064/140] [Spec 1963][Phase: cockpit_actions] fix: Spawn Builder runs afx spawn in this window's workspace spawnBuilder passed no cwd, so afx spawn resolved its workspace from the extension host's own directory (Tower's, in the Codev IDE): a window could spawn into another project. Found by the Cockpit harness's afx stub. It now runs in detectWorkspacePath() (the parent workspace in a builder-worktree window), as Run Worktree Setup and Approve Gate do, and refuses before prompting when the window has no workspace. --- .../__tests__/cockpit-handler-args.test.ts | 2 +- .../__tests__/spawn-builder-not-found.test.ts | 26 ++++++++++++++++--- apps/vscode/src/commands/spawn.ts | 17 +++++++++--- apps/vscode/src/extension.ts | 2 +- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/apps/vscode/src/__tests__/cockpit-handler-args.test.ts b/apps/vscode/src/__tests__/cockpit-handler-args.test.ts index 618b6aa53..1c458c841 100644 --- a/apps/vscode/src/__tests__/cockpit-handler-args.test.ts +++ b/apps/vscode/src/__tests__/cockpit-handler-args.test.ts @@ -206,7 +206,7 @@ describe('relocated commands, given the Cockpit node their entry attaches to', ( it("Spawn Builder's extractIssueId yields no id from a workspace node, so the full picker opens", async () => { const { own } = await nodes(); expect(extractIssueId(own)).toBeUndefined(); - expect(registration(EXT_SRC, 'codev.spawnBuilder')).toMatch(/spawnBuilder\(extractIssueId\(arg\)\)/); + expect(registration(EXT_SRC, 'codev.spawnBuilder')).toMatch(/spawnBuilder\(extractIssueId\(arg\), detectWorkspacePath\(\)\)/); }); it("Add Architect, New Shell, Start Dev, Stop Dev and Open Web Interface ignore the argument (this window's workspace)", () => { diff --git a/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts b/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts index 9844955b9..f9356316b 100644 --- a/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts +++ b/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts @@ -35,8 +35,8 @@ describe('Spawn Builder when afx cannot start', () => { it('says afx was not found on PATH for ENOENT', async () => { const child = fakeChild(); cli.spawnCodevCli.mockReturnValue(child); - await spawnBuilder('42'); - expect(cli.spawnCodevCli).toHaveBeenCalledWith('afx', ['spawn', '42', '--protocol', 'pir'], { detached: true, stdio: 'ignore' }); + await spawnBuilder('42', '/ws'); + expect(cli.spawnCodevCli).toHaveBeenCalledWith('afx', ['spawn', '42', '--protocol', 'pir'], { cwd: '/ws', detached: true, stdio: 'ignore' }); child.emit('error', Object.assign(new Error('spawn afx ENOENT'), { code: 'ENOENT' })); expect(vscodeMock.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining('afx was not found on PATH')); @@ -45,9 +45,29 @@ describe('Spawn Builder when afx cannot start', () => { it('shows the error message for any other failure', async () => { const child = fakeChild(); cli.spawnCodevCli.mockReturnValue(child); - await spawnBuilder('42'); + await spawnBuilder('42', '/ws'); child.emit('error', Object.assign(new Error('spawn EACCES'), { code: 'EACCES' })); expect(vscodeMock.window.showErrorMessage).toHaveBeenCalledWith('Codev: could not run afx: spawn EACCES'); }); }); + +/** + * `afx spawn` resolves its workspace from its cwd. Run in the extension host's + * own cwd (Tower's, in the Codev IDE) it would spawn into whichever project + * that is, so it runs in this window's workspace, and refuses without one. + */ +describe('Spawn Builder runs afx in this window\'s workspace', () => { + it('passes the workspace path as cwd', async () => { + cli.spawnCodevCli.mockReturnValue(fakeChild()); + await spawnBuilder('42', '/path/to/workspace'); + expect(cli.spawnCodevCli.mock.calls[0][2]).toMatchObject({ cwd: '/path/to/workspace' }); + }); + + it('refuses before prompting when the window has no workspace', async () => { + await spawnBuilder(undefined, null); + expect(vscodeMock.window.showErrorMessage).toHaveBeenCalledWith('Codev: Spawn Builder needs a Codev workspace open in this window.'); + expect(vscodeMock.window.showInputBox).not.toHaveBeenCalled(); + expect(cli.spawnCodevCli).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/vscode/src/commands/spawn.ts b/apps/vscode/src/commands/spawn.ts index 1d44f95af..700039202 100644 --- a/apps/vscode/src/commands/spawn.ts +++ b/apps/vscode/src/commands/spawn.ts @@ -10,8 +10,17 @@ import { spawnCodevCli } from '../cli-process.js'; * already known, so jump straight to the protocol pick and spawn. The * branch prompt is skipped too — starting work on a backlog issue means * a fresh branch. + * + * `afx spawn` resolves its workspace from its cwd, so it runs in + * `workspacePath`, this window's Tower workspace (the parent workspace in a + * builder-worktree window). Without one it refuses before prompting: in the + * extension host's own cwd it would spawn into whichever project that is. */ -export async function spawnBuilder(issueArg?: string): Promise { +export async function spawnBuilder(issueArg: string | undefined, workspacePath: string | null): Promise { + if (!workspacePath) { + vscode.window.showErrorMessage('Codev: Spawn Builder needs a Codev workspace open in this window.'); + return; + } let issueNumber = issueArg; if (!issueNumber) { issueNumber = await vscode.window.showInputBox({ @@ -39,11 +48,11 @@ export async function spawnBuilder(issueArg?: string): Promise { } } - runAfxCommand(args); + runAfxCommand(args, workspacePath); } -function runAfxCommand(args: string[]): void { - const child = spawnCodevCli('afx', args, { detached: true, stdio: 'ignore' }); +function runAfxCommand(args: string[], cwd: string): void { + const child = spawnCodevCli('afx', args, { cwd, detached: true, stdio: 'ignore' }); child.on('error', (err: NodeJS.ErrnoException) => { const reason = err.code === 'ENOENT' ? 'afx was not found on PATH (install @cluesmith/codev)' : err.message; vscode.window.showErrorMessage(`Codev: could not run afx: ${reason}`); diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index eb6d9c570..71ab54bff 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -1271,7 +1271,7 @@ export async function activate(context: vscode.ExtensionContext) { reg('codev.focusNextAgentTerminal', () => cycleAgentTerminal(1)), reg('codev.focusPreviousAgentTerminal', () => cycleAgentTerminal(-1)), regCli('codev.spawnBuilder', (arg: vscode.TreeItem | string | undefined) => - spawnBuilder(extractIssueId(arg))), + spawnBuilder(extractIssueId(arg), detectWorkspacePath())), reg('codev.openBacklogIssue', (arg: vscode.TreeItem | undefined) => { if (arg instanceof BacklogTreeItem) { void vscode.env.openExternal(vscode.Uri.parse(arg.issueUrl)); From af390da8777a714aad6a5ab7273d3c8cb41b5830 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 02:59:10 -0800 Subject: [PATCH 065/140] [Spec 1963][Phase: cockpit_actions] test: increment-1 rendered verification, request counts, docs - cockpit-verify.mjs: scripted checks (render, reveal, windows, requests, actions, reconnect) run by harness.mjs verify against the isolated harness. 43 checks pass; results and screenshots in codev/projects/1963-.../verification-increment1/. - Request count (spec scenario 21): the Cockpit alone, the source views alone, and both at once, each asserted on screen and measured in a freshly restarted VS Code server. The Cockpit adds no poll, stream or route; both at once adds only one getWorktreeConfig on a config change. - Harness: fixture workspaces in a marked mkdtemp dir under the per-user temp dir (Tower's /api/workspaces hides /tmp workspaces), removed by stop only after realpath/parent/name/marker-token checks; a request log preloaded into the isolated Tower; tower-down/tower-up and vscode-restart; gate 6 asserts the fleet listing. - Docs: README Cockpit section, CHANGELOG, arch.md Key Design Decision. - Thread: Phase 5 decisions and findings. --- apps/vscode/CHANGELOG.md | 10 + apps/vscode/README.md | 27 + apps/vscode/scripts/cockpit-harness/README.md | 51 +- .../cockpit-harness/cockpit-verify.mjs | 1355 +++++++++++++++++ .../scripts/cockpit-harness/fixtures.mjs | 86 +- .../scripts/cockpit-harness/harness.mjs | 320 +++- .../scripts/cockpit-harness/preflight.mjs | 19 + .../scripts/cockpit-harness/request-log.cjs | 19 + .../scripts/cockpit-harness/workbench.mjs | 6 +- codev/resources/arch.md | 1 + codev/state/spir-1963_thread.md | 102 ++ 11 files changed, 1976 insertions(+), 20 deletions(-) create mode 100644 apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs create mode 100644 apps/vscode/scripts/cockpit-harness/request-log.cjs diff --git a/apps/vscode/CHANGELOG.md b/apps/vscode/CHANGELOG.md index b48292c2f..303e417b8 100644 --- a/apps/vscode/CHANGELOG.md +++ b/apps/vscode/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## [Unreleased] + +### What's new + +- **Codev Cockpit: the whole fleet in one tree.** A new button below Codev opens Tower → workspaces → architects → builders → changed files. This window's workspace keeps every action of the Workspace and Agents views, and another workspace's rows open that workspace's window (#1963). + +### Fixes + +- **Spawn Builder runs in this window's workspace.** It ran `afx spawn` in the extension host's own directory (Tower's, in the Codev IDE), so it could spawn into another project, or fail where that directory is no project. It now runs in this window's workspace, the parent workspace in a builder-worktree window, and without a workspace it says so instead of prompting. + ## [3.3.6] - 2026-10-29 ### What's new diff --git a/apps/vscode/README.md b/apps/vscode/README.md index f249bfced..e8f257fb7 100644 --- a/apps/vscode/README.md +++ b/apps/vscode/README.md @@ -40,6 +40,33 @@ The Codev sidebar contains seven collapsible views: - **Team** — per-member counts (`Assigned: N`, `Open PRs: N`, `Last 7d: X merged, Y closed`). Manual refresh from the title bar. - **Status** — connection state; click to reconnect if Tower drops. +## Codev Cockpit + +The **Codev Cockpit** button sits directly below Codev in the Activity Bar. It opens one tree holding the machine's whole fleet: + +``` +Tower +├─ my-project (current) ← this window's workspace +│ ├─ MAIN +│ │ └─ #42 builder … ← changed files below each builder +│ └─ WEB +└─ other-project + └─ MAIN + └─ #7 builder … +Dormant (2) +``` + +- **Workspaces** are the Tower view's rows, in the same urgency order and with the same labels, *current* marker and attention summary. Every active workspace expands to its architects; dormant workspaces fold into *Dormant (N)*. +- **This window's workspace acts here.** Its builder rows carry the Agents view's full right-click menu and the inline Approve Gate. A sibling architect carries *Remove Architect*; `main` never does. The workspace row carries inline *Spawn Builder*, *New Shell* and *Add Architect*. Its right-click menu adds *Open Web Interface*, *Start Dev* or *Stop Dev*, and *Open Dev URL…* when `worktree.devUrls` is set. +- **Other workspaces navigate.** Clicking another workspace's architect or builder opens that workspace's window. Their rows carry no actions that would act from this window. Their workspace rows keep the Tower view's inline *Open* and *Deactivate*. +- **In a builder-worktree window**, the parent workspace's row carries only *Open Web Interface*, the worktree's *Start Dev* / *Stop Dev* and *Open Dev URL…*. It has no spawn, shell or architect actions. +- **Title bar:** Refresh, plus the same accordion and tree-vs-list toggles as Agents. +- **Following the active file:** a builder diff in the editor reveals its file row in the Cockpit, expanding the workspace, architect and builder rows above it. +- **Agent cycling** (`ctrl+alt+n` / `ctrl+alt+p`) follows the Cockpit's order while the Cockpit is visible, Agents is not, and the Cockpit shows this window's agents. Otherwise it keeps the Agents order, as before (for example in a builder-worktree window). +- **Before the first load** the Tower row holds a state row: *Connecting to Tower…*, then *Not connected to Tower* (click to reconnect) if the attempt fails. Once loaded, the tree keeps its last content through a Tower drop and refreshes when Tower returns. + +The Cockpit reads what the Codev and Tower views already fetch. It adds no poll or stream of its own. + ## Builder actions (right-click) Right-click any builder in the Agents view for three grouped action menus: diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index 87e24b083..1a5cb8a0e 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -19,6 +19,9 @@ node $H build-vsix # vsce package → $COCKPIT_SCRATCH/cockpit-harness/ node $H start # pre-flight, Tower, `empty` fixture, VS Code, tripwire node $H seed one-builder # seed a scenario; gate 6 asserts its overview node $H check # gates 3-5 again, plus the extension running against the Tower +node $H verify render # a scripted rendered check (cockpit-verify.mjs); see below +node $H tower-down # stop only the isolated Tower (by PID); tower-up starts it again +node $H vscode-restart # restart only the isolated VS Code (by PID) node $H stop # kill the harness's own PIDs; remove runtime dirs ``` @@ -47,9 +50,10 @@ Never run `playwright install`. The driver uses the Chromium already in | Piece | How it is isolated | |---|---| -| Tower | Started as `node packages/codev/dist/agent-farm/servers/tower-server.js -p $COCKPIT_TOWER_PORT`, never through `afx tower start`.
Its environment is built from an allowlist: `CODEV_AGENT_FARM_DIR` and `HOME` are in the scratchpad, and `NODE_ENV`, `AF_TEST_DB` and `CODEV_TOWER_KEY` are unset. | +| Tower | Started as `node --require request-log.cjs packages/codev/dist/agent-farm/servers/tower-server.js -p $COCKPIT_TOWER_PORT`, never through `afx tower start`.
Its environment is built from an allowlist: `CODEV_AGENT_FARM_DIR`, `HOME` and `TMPDIR` are in the scratchpad, and `NODE_ENV`, `AF_TEST_DB` and `CODEV_TOWER_KEY` are unset.
`request-log.cjs` appends each HTTP request and WebSocket upgrade it receives to `/logs/tower-requests.jsonl` (for the request-count check). | | Shellper sockets | They live in `/run`, reached through a short `/tmp/cckp-` symlink.
macOS caps a socket path at 104 bytes, and the scratchpad path alone is longer. Gate 2 checks the link's real path, and every teardown removes the link. | | Fixture driver (`fixtures.mjs`) | Runs in the isolated environment. Creates state only through:
  • explicit-port HTTP calls (activation, builder terminals);
  • the dist's in-process writers (porch `writeState`, `upsertBuilder`);
  • git.
It runs no Tower-contacting `afx` or `porch` command. | +| Fixture workspaces | Git repos in a fresh `cockpit-fixtures-*` dir (`mkdtemp`) under the real per-user temp dir (`/private/var/folders/…/T`), **not** the scratchpad. Tower's `/api/workspaces` drops every workspace under `/tmp`, `/private/tmp` or its own `os.tmpdir()` (`isTempDirectory`), and the scratchpad is under `/private/tmp`, so fixtures there never reach the fleet the Tower and Cockpit views list. The Tower's own `TMPDIR` points into the scratchpad, so this dir is not its temp dir. `start` writes a marker holding a per-run token in it; see *Teardown*. | | Fixture sessions | Architects and builders are `/bin/bash --noprofile --norc`, through a no-op custom harness in each fixture's `.codev/config.json`. They are never agents. | | VS Code | Runs on `$COCKPIT_WEB_PORT` in one of two modes, set by `COCKPIT_VSCODE`:
  • `serve-web` (default): `code serve-web`, with the CLI, server, user and extensions dirs all under the root.
  • `ide-server`: the plan's alternative for when serve-web cannot run. It launches the VS Code Server binary Tower's IDE support uses (`COCKPIT_IDE_SERVER_BIN`) **directly**, never through any Tower's `/api/ide`. It passes the flags `ide-server.ts` passes (`--host 127.0.0.1`, `--port`, `--server-base-path /ide`, `--connection-token-file`, `--extensions-dir`), plus `--server-data-dir` and `--user-data-dir`, all in the scratchpad.
The mode is chosen explicitly. A serve-web failure fails the start; it does not switch modes by itself.
  • Machine settings: `codev.towerPort=$COCKPIT_TOWER_PORT`, `codev.autoStartTower=false`, `files.autoSave=off`.
  • Environment: `CODEV_TOWER_KEY` is the isolated key, `HOME` is the scratch home, and `stubs/` comes first on `PATH`.
| | Stubs (`stubs/afx`, `porch`, `codev`) | Each call appends `{ tool, argv, cwd, caller }` to `/logs/stub-calls.jsonl` and exits 0, so CLI-shelling actions are verified by their recorded argv.
`codev --version` prints the branch version.
The stubs are on the Tower's `PATH` too. | @@ -81,7 +85,8 @@ These match the plan's numbering. Any refusal exits with code 2. 5. The VS Code Machine settings pin the port and turn auto-start off, and `afx`, `porch` and `codev` resolve to the stubs in the VS Code server's environment. 6. After a seed, each fixture workspace's `/api/overview` lists exactly the expected builders (with - `spawnedByArchitect`) and architects. There is no fallback to faked data. + `spawnedByArchitect`) and architects, and `/api/workspaces` lists each activated workspace as + active or dormant as seeded. There is no fallback to faked data. ## Teardown @@ -93,8 +98,16 @@ These match the plan's numbering. Any refusal exits with code 2. It then checks that none of them is still alive. It also removes: - the socket symlink; -- the runtime dirs (`af`, `run`, `home`, `fixtures`, `pids`, the VS Code server, user and +- the runtime dirs (`af`, `run`, `home`, `tmp`, `pids`, the VS Code server, user and extensions dirs, and the browser profile); +- the fixtures dir, which is outside the scratchpad, **only if every check holds**: + - it is a real directory, not a symlink, and its realpath is the recorded path; + - the realpath's parent is the per-user temp dir; + - its basename is `cockpit-fixtures-*`; + - it holds the `.cockpit-harness-fixtures` marker `start` wrote, with this run's token. + + Otherwise `stop` deletes nothing there, prints `REFUSED … deleted nothing: `, keeps the + state record and exits 1. `selftest` proves each refusal; - the state record. It keeps `logs/`, `shots/`, the vsix and the downloaded VS Code server cache (`cache/`). A failed @@ -108,8 +121,13 @@ before retrying. `fixtures.mjs` defines them in `SCENARIOS`: - `empty`: workspace `alpha`, not activated. `start` seeds it. - `one-builder`: `alpha` activated, plus builder `spir-101` spawned by `main`. - -Later phases add scenarios here. +- `fleet` (Phase 5): four workspaces. + - `alpha` is activated with a sibling architect `web` and a dev config (`devCommand` and two + `devUrls`). It has three builders: `#101` (spawned by `main`, blocked on spec approval, with a + committed spec and a changed file), `#102` (`main`) and `#103` (`web`). + - `beta` has one builder, `#201`. + - `gamma` has none. + - `delta` is activated and then deactivated, so it is dormant. Seed each scenario once per `start`. Re-seeding is not supported, for two reasons: - `seedBuilder` refuses an existing worktree. @@ -117,3 +135,26 @@ Seed each scenario once per `start`. Re-seeding is not supported, for two reason loads, so `empty`'s "no architects" expectation stops holding after the first `check`. To get a different scenario, `stop` and `start` again. + +## Scripted Cockpit checks (`verify`) + +`node $H verify `); + }); + + it('allows images from the bundle, blob: and http(s), and styles from the bundle plus inline', () => { + const policy = policyOf(render()); + expect(policy.get('img-src')).toEqual([CSP_SOURCE, 'blob:', 'http:', 'https:']); + expect(policy.get('style-src')).toEqual([CSP_SOURCE, "'unsafe-inline'"]); + expect([...policy.keys()].sort()).toEqual(['default-src', 'img-src', 'script-src', 'style-src']); + }); + + it('draws a fresh nonce for every render', () => { + const nonce = (html: string) => policyOf(html).get('script-src')![0]; + expect(nonce(render())).not.toBe(nonce(render())); + }); + + it('links the stylesheet, mounts on #root and carries the title', () => { + const html = render(); + expect(html).toContain(``); + expect(html).toContain('
'); + expect(html).toContain('Decisions'); + }); + + it('builds the same policy directly', () => { + expect(workspaceViewCsp('vscode-resource:', 'abc')).toBe( + "default-src 'none'; script-src 'nonce-abc'; style-src vscode-resource: 'unsafe-inline'; img-src vscode-resource: blob: http: https:", + ); + }); +}); diff --git a/apps/vscode/src/__tests__/workspace-views-security.test.ts b/apps/vscode/src/__tests__/workspace-views-security.test.ts new file mode 100644 index 000000000..9f8856f71 --- /dev/null +++ b/apps/vscode/src/__tests__/workspace-views-security.test.ts @@ -0,0 +1,148 @@ +/** + * Spec 1963 scenario 6: a path or URL from a Work or Decisions webview is untrusted. A file opens + * only when its canonical, symlink-resolved location is inside the workspace (decided by + * `path.relative`, never a string prefix); a URL opens only when it is http(s). + * + * The Windows cases run as `path.win32` table tests on every OS, and for real (with a directory + * junction) in the on-demand Windows workflow. + */ + +import { afterAll, beforeAll, describe, it, expect } from 'vitest'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { isAllowedExternalUrl, isWithin, resolveWorkspaceFile } from '../workspace-views/security.js'; + +describe('isWithin (canonical paths)', () => { + it.each([ + ['/ws', '/ws', true], + ['/ws', '/ws/codev/specs/1.md', true], + ['/ws', '/ws/..hidden/file', true], + ['/ws', '/ws/../etc/passwd', false], + ['/ws', '/', false], + ['/ws', '/ws-other/file', false], + ['/ws', '/elsewhere/file', false], + ])('posix: %s contains %s → %s', (root, target, inside) => { + expect(isWithin(root, target, path.posix)).toBe(inside); + }); + + it.each([ + ['drive-letter case', 'c:\\ws', 'C:\\ws\\codev\\a.md', true], + ['mixed separators', 'C:\\ws', 'C:/ws/codev/a.md', true], + ['the root itself, other spelling', 'C:\\ws', 'c:/ws/', true], + ['a different drive', 'C:\\ws', 'D:\\ws\\a.md', false], + ['a UNC root against a local root', 'C:\\ws', '\\\\server\\share\\ws\\a.md', false], + ['a local path against a UNC root', '\\\\server\\share\\ws', 'C:\\ws\\a.md', false], + ['inside a UNC root', '\\\\server\\share\\ws', '\\\\server\\share\\ws\\a.md', true], + ['a prefix sibling', 'C:\\ws', 'C:\\ws-other\\a.md', false], + ['a parent escape', 'C:\\ws', 'C:\\ws\\..\\secrets.txt', false], + ])('win32: %s', (_name, root, target, inside) => { + expect(isWithin(root, target, path.win32)).toBe(inside); + }); +}); + +describe('resolveWorkspaceFile (real files and symlinks)', () => { + let base: string; + let root: string; + let outside: string; + + beforeAll(() => { + base = realpathSync(mkdtempSync(path.join(tmpdir(), 'codev-wv-security-'))); + root = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + mkdirSync(path.join(root, 'codev', 'specs'), { recursive: true }); + mkdirSync(outside); + writeFileSync(path.join(root, 'codev', 'specs', '1.md'), '# spec'); + writeFileSync(path.join(outside, 'secret.md'), 'secret'); + // A link inside the workspace to a file inside it, and links that escape it. + symlinkSync(path.join(root, 'codev', 'specs', '1.md'), path.join(root, 'inner-link.md')); + symlinkSync(path.join(outside, 'secret.md'), path.join(root, 'escape-link.md')); + // A junction on Windows (no privilege needed), a plain directory symlink elsewhere. + symlinkSync(outside, path.join(root, 'escape-dir'), 'junction'); + // A sibling whose name starts with the workspace's. + mkdirSync(`${root}-other`); + writeFileSync(path.join(`${root}-other`, 'a.md'), 'sibling'); + }); + + afterAll(() => { + rmSync(base, { recursive: true, force: true }); + }); + + it('resolves a relative path inside the workspace to its canonical path', async () => { + expect(await resolveWorkspaceFile(root, 'codev/specs/1.md')).toEqual({ ok: true, path: path.join(root, 'codev', 'specs', '1.md') }); + }); + + it('accepts an absolute path inside the workspace, and a link that stays inside', async () => { + expect(await resolveWorkspaceFile(root, path.join(root, 'codev', 'specs', '1.md'))).toMatchObject({ ok: true }); + expect(await resolveWorkspaceFile(root, 'inner-link.md')).toEqual({ ok: true, path: path.join(root, 'codev', 'specs', '1.md') }); + }); + + it.each([ + ['a .. escape', '../outside/secret.md'], + ['an absolute path outside', '/etc/hosts'], + ['a prefix sibling', '../ws-other/a.md'], + ['a file symlink leading outside', 'escape-link.md'], + ['a directory symlink leading outside', 'escape-dir/secret.md'], + ])('refuses %s', async (_name, requested) => { + expect(await resolveWorkspaceFile(root, requested)).toEqual({ ok: false, reason: 'outside-workspace' }); + }); + + it('says not-found for a path that does not exist, and for one with a NUL byte', async () => { + expect(await resolveWorkspaceFile(root, 'codev/specs/missing.md')).toEqual({ ok: false, reason: 'not-found' }); + expect(await resolveWorkspaceFile(root, 'codev/specs/1.md\0.txt')).toEqual({ ok: false, reason: 'not-found' }); + }); + + it('resolves the workspace root through its own symlink, so a linked workspace still contains its files', async () => { + const linkedRoot = path.join(base, 'ws-link'); + symlinkSync(root, linkedRoot, 'junction'); + expect(await resolveWorkspaceFile(linkedRoot, 'codev/specs/1.md')).toEqual({ ok: true, path: path.join(root, 'codev', 'specs', '1.md') }); + expect(await resolveWorkspaceFile(linkedRoot, 'escape-link.md')).toEqual({ ok: false, reason: 'outside-workspace' }); + }); +}); + +describe.runIf(process.platform === 'win32')('resolveWorkspaceFile on Windows paths', () => { + let base: string; + let root: string; + + beforeAll(() => { + base = realpathSync(mkdtempSync(path.join(tmpdir(), 'codev-wv-win-'))); + root = path.join(base, 'ws'); + mkdirSync(path.join(root, 'codev'), { recursive: true }); + writeFileSync(path.join(root, 'codev', 'a.md'), 'a'); + }); + + afterAll(() => { + rmSync(base, { recursive: true, force: true }); + }); + + it('accepts the workspace spelled with the other drive-letter case and with forward slashes', async () => { + const flipped = root[0] === root[0].toUpperCase() ? root[0].toLowerCase() + root.slice(1) : root[0].toUpperCase() + root.slice(1); + expect(await resolveWorkspaceFile(flipped, 'codev\\a.md')).toMatchObject({ ok: true }); + expect(await resolveWorkspaceFile(root.replace(/\\/g, '/'), 'codev/a.md')).toMatchObject({ ok: true }); + }); +}); + +describe('isAllowedExternalUrl', () => { + it.each([ + 'https://github.com/cluesmith/codev/issues/1963', + 'http://localhost:3000/', + 'HTTPS://EXAMPLE.COM/a', + ])('allows %s', (url) => { + expect(isAllowedExternalUrl(url)).toBe(true); + }); + + it.each([ + 'javascript:alert(1)', + 'file:///etc/passwd', + 'vscode://cluesmith.codev-vscode/x', + 'vscode-webview://abc/index.html', + 'command:workbench.action.terminal.new', + 'data:text/html,', + 'mailto:someone@example.com', + '//github.com/x', + '/relative/path', + 'not a url', + ])('refuses %s', (url) => { + expect(isAllowedExternalUrl(url)).toBe(false); + }); +}); diff --git a/apps/vscode/src/__tests__/workspace-views-theme.test.ts b/apps/vscode/src/__tests__/workspace-views-theme.test.ts new file mode 100644 index 000000000..ebd13504f --- /dev/null +++ b/apps/vscode/src/__tests__/workspace-views-theme.test.ts @@ -0,0 +1,66 @@ +/** + * Spec 1963 scenario 18: the Work and Decisions panels take their colours and fonts from VS Code's + * theme. The shared views' stylesheet colours everything through `--codev-wv-*` tokens whose + * defaults are the dashboard's dark palette, so a token the VS Code stylesheet leaves unmapped would + * stay dark in a light or high-contrast theme. This holds `vscode-theme.css` to the full token list + * read from the shared stylesheet, so a token added there fails here until it is mapped. + */ + +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const SHARED = readFileSync(resolve(__dirname, '../../../../packages/workspace-views/src/styles.css'), 'utf8'); +const THEME = readFileSync(resolve(__dirname, '../workspace-views/webview/vscode-theme.css'), 'utf8'); + +const withoutComments = (css: string) => css.replace(/\/\*[\s\S]*?\*\//g, ''); + +/** Every token the shared stylesheet reads. */ +const used = [...new Set([...withoutComments(SHARED).matchAll(/var\((--codev-wv-[a-z0-9-]+)/g)].map(m => m[1]))].sort(); + +/** The VS Code stylesheet's `:root` mappings, token → value. */ +function mappings(): Map { + const root = withoutComments(THEME).match(/:root\s*\{([^}]*)\}/); + expect(root, 'vscode-theme.css has a :root block').not.toBeNull(); + const out = new Map(); + for (const m of root![1].matchAll(/(--codev-wv-[a-z0-9-]+)\s*:\s*([^;]+);/g)) { + expect(out.has(m[1]), `${m[1]} is mapped once`).toBe(false); + out.set(m[1], m[2].trim()); + } + return out; +} + +describe('vscode-theme.css', () => { + it('reads the token list from the shared stylesheet', () => { + expect(used.length).toBeGreaterThanOrEqual(28); + }); + + it('maps every token the shared stylesheet uses, and no other', () => { + expect([...mappings().keys()].sort()).toEqual(used); + }); + + it("maps each to VS Code's theme: a --vscode-* variable, directly or through another mapped token", () => { + const map = mappings(); + // Follows token references down to the --vscode-* variables they end in. + const reachesVscode = (value: string, seen: Set): boolean => { + if (/var\(--vscode-[A-Za-z0-9-]+/.test(value)) { return true; } + return [...value.matchAll(/var\((--codev-wv-[a-z0-9-]+)/g)].some(([, ref]) => { + expect(map.has(ref), `${ref} is mapped`).toBe(true); + if (seen.has(ref)) { return false; } + return reachesVscode(map.get(ref)!, new Set([...seen, ref])); + }); + }; + for (const [token, value] of map) { + expect(reachesVscode(value, new Set([token])), token).toBe(true); + } + }); + + it('uses no literal colour of its own anywhere', () => { + const literal = /#[0-9a-f]{3,8}\b|\b(rgba?|hsla?)\(|\b(white|black)\b/i; + const declarations = [...withoutComments(THEME).matchAll(/([a-z-]+)\s*:\s*([^;{}]+);/g)] + .filter(([, prop]) => prop !== 'white-space') + .filter(([, , value]) => literal.test(value)) + .map(([declaration]) => declaration); + expect(declarations).toEqual([]); + }); +}); diff --git a/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts b/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts new file mode 100644 index 000000000..8aa1cbafd --- /dev/null +++ b/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts @@ -0,0 +1,56 @@ +/** + * Spec 1963 scenario 22 (source): the panels' webview code does no I/O of its own. Every Tower call + * is a message to the extension host; the webview has no `fetch`, XHR, WebSocket, EventSource or + * beacon, and opens no window. The shared package holds the same rule for its own sources + * (`packages/workspace-views/src/__tests__/import-boundary.test.ts`). ESLint flags the same globals + * here while editing (`eslint.config.mjs`); this test is what CI runs. + * + * The webview's tests are excluded: they are not shipped. + */ + +import { describe, it, expect } from 'vitest'; +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +const WEBVIEW = resolve(__dirname, '../workspace-views/webview'); + +function sources(dir: string): string[] { + const out: string[] = []; + for (const name of readdirSync(dir)) { + const full = join(dir, name); + if (statSync(full).isDirectory()) { + if (name !== '__tests__') { out.push(...sources(full)); } + } else if (/\.(ts|tsx)$/.test(name)) { + out.push(full); + } + } + return out; +} + +const FORBIDDEN: Array<{ label: string; pattern: RegExp }> = [ + { label: 'fetch()', pattern: /\bfetch\s*\(/ }, + { label: 'XMLHttpRequest', pattern: /\bXMLHttpRequest\b/ }, + { label: 'WebSocket', pattern: /\bWebSocket\b/ }, + { label: 'EventSource', pattern: /\bEventSource\b/ }, + { label: 'sendBeacon', pattern: /\bsendBeacon\b/ }, + { label: 'window.open', pattern: /\bwindow\.open\s*\(/ }, + { label: 'vscode', pattern: /from\s+['"]vscode['"]/ }, +]; + +describe('the workspace-views webview sources', () => { + const files = sources(WEBVIEW); + + it('finds the sources', () => { + expect(files.map(f => f.slice(WEBVIEW.length + 1))).toEqual( + expect.arrayContaining(['DecisionsApp.tsx', 'decisions-host.ts', 'decisions-main.tsx']), + ); + }); + + it('do no network I/O and open no window', () => { + const violations = files.flatMap(file => { + const text = readFileSync(file, 'utf8'); + return FORBIDDEN.filter(({ pattern }) => pattern.test(text)).map(({ label }) => `${file}: ${label}`); + }); + expect(violations).toEqual([]); + }); +}); diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index 71ab54bff..0c88b8fca 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -67,6 +67,10 @@ import { deriveAttention, isIdleWaiting } from '@cluesmith/codev-sdk/builder-hel import { BuildersProvider, runBuilderRowClick, agentTargetIsFocused, agentCycleAttemptOrder, type AgentTarget } from './views/builders.js'; import { AgentTreeHosts, agentCycleRoster } from './views/agent-tree-hosts.js'; import { CockpitProvider, COCKPIT_VIEW_ID, cockpitConnectionMode, type CockpitNode } from './views/cockpit.js'; +import { DecisionsPanels } from './workspace-views/decisions-panel.js'; +import { DecisionsBridge } from './workspace-views/decisions-bridge.js'; +import { DECISIONS_VIEW_TYPE } from './workspace-views/messages.js'; +import { workspaceViewUnavailableReason } from './workspace-views/availability.js'; import { OverviewRefreshGate } from './views/overview-refresh-gate.js'; // Codev Tower (#1566): the cross-workspace navigation hub — its own activity-bar container. import { TowerFleetCache } from './views/tower-cache.js'; @@ -593,6 +597,18 @@ export async function activate(context: vscode.ExtensionContext) { ), }); const cockpitView: vscode.TreeView = vscode.window.createTreeView(COCKPIT_VIEW_ID, { treeDataProvider: cockpitProvider }); + // The Decisions panel (Spec 1963): one per window, for this window's workspace, with every Tower + // call made here. Its serializer restores an open panel after a window reload. + const decisionsPanels = new DecisionsPanels({ + extensionUri: context.extensionUri, + bridge: new DecisionsBridge(connectionManager), + unavailableReason: () => workspaceViewUnavailableReason('Decisions', { + builderWorktreeWindow: isBuilderWorktreeWindow, + workspacePath: connectionManager?.getWorkspacePath() ?? null, + }), + log: (line) => outputChannel?.appendLine(line), + }); + context.subscriptions.push(vscode.window.registerWebviewPanelSerializer(DECISIONS_VIEW_TYPE, decisionsPanels)); // Builders accordion (#913), row-click expand, follow-reveals, the // builder-active hook and the badge act on whichever of the two views a row // belongs to. The accordion is toggled via the header button / @@ -1287,6 +1303,9 @@ export async function activate(context: vscode.ExtensionContext) { viewBacklogIssue(connectionManager!, extractIssueId(arg))), reg('codev.openBacklogSearch', () => BacklogSearchPanel.createOrShow(connectionManager!, overviewCache, context.extensionUri)), + // The Decisions panel (Spec 1963): the palette and the Cockpit's Decisions entry. Where it is + // not offered (a builder-worktree or no-workspace window) it says why. + regCli('codev.openDecisions', () => decisionsPanels.show()), reg('codev.searchBacklog', () => searchBacklog(connectionManager!, overviewCache)), reg('codev.openIssueById', () => openIssueById(connectionManager!, () => overviewCache.getData())), reg('codev.openPRById', () => openPRById(connectionManager!)), diff --git a/apps/vscode/src/views/architect-tree.ts b/apps/vscode/src/views/architect-tree.ts index 0acd4c846..bd79d011e 100644 --- a/apps/vscode/src/views/architect-tree.ts +++ b/apps/vscode/src/views/architect-tree.ts @@ -39,14 +39,15 @@ const CONTEXT_FAMILY: Record `cockpit-ws:${path}`, loading: (path: string) => `cockpit-loading:${path}`, + decisions: (path: string) => `cockpit-decisions:${path}`, } as const; +/** + * The `contextValue` of this window's Decisions entry. Another workspace's entry navigates and + * carries `REMOTE_CONTEXT.decisions`. No menu entry keys on either: a click is the row's one action. + */ +export const COCKPIT_DECISIONS_CONTEXT = 'cockpit-decisions'; + +/** The command this window's Decisions entry runs: open, or reveal, the Decisions panel. */ +export const OPEN_DECISIONS_COMMAND = 'codev.openDecisions'; + /** The id prefix of every architect and builder row under one workspace. */ export function cockpitScope(path: string): string { return `ws:${path}|`; @@ -40,7 +50,8 @@ export type CockpitOwnNode = | { kind: 'message'; text: string; icon: string; command?: vscode.Command; tooltip?: string } | { kind: 'workspace'; ws: LabelledEntry } | { kind: 'dormant-group'; rows: LabelledEntry[] } - | { kind: 'loading'; ws: LabelledEntry }; + | { kind: 'loading'; ws: LabelledEntry } + | { kind: 'decisions'; ws: LabelledEntry }; export type CockpitNode = CockpitOwnNode | vscode.TreeItem; @@ -249,6 +260,8 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac item.iconPath = new vscode.ThemeIcon('sync~spin'); return item; } + case 'decisions': + return this.decisionsRow(node.ws); } } @@ -269,6 +282,7 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac return node.rows.map((ws): CockpitNode => ({ kind: 'workspace', ws })); case 'message': case 'loading': + case 'decisions': return []; } } @@ -302,6 +316,7 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac return { kind: 'dormant-group', rows: this.ordered().dormant }; } case 'loading': + case 'decisions': return { kind: 'workspace', ws: node.ws }; } } @@ -450,14 +465,41 @@ export class CockpitProvider implements vscode.TreeDataProvider, Ac return 'collapsed'; } - /** An active workspace's architects (with their builders), or *Loading…* until its overview lands. */ + /** + * An active workspace's architects (with their builders), then its Decisions entry; or *Loading…* + * until its overview lands. + */ private async workspaceNodeChildren(ws: LabelledEntry): Promise { if (!ws.entry.workspace.active) { return []; } const tree = this.treeFor(ws); if (this.dataFor(ws) === null) { return [{ kind: 'loading', ws }]; } - return tree.getChildren(undefined); + return [...await tree.getChildren(undefined), { kind: 'decisions', ws }]; + } + + /** + * A workspace's Decisions entry. The overview says nothing about the decisions file, so the entry + * is under every active workspace and carries no count. This window's opens (or reveals) the + * Decisions panel without arranging anything, and a workspace with no file opens its empty state. + * Another workspace's (and, in a builder-worktree window, the parent's) navigates to its window. + */ + private decisionsRow(ws: LabelledEntry): vscode.TreeItem { + const item = new vscode.TreeItem('Decisions', vscode.TreeItemCollapsibleState.None); + item.id = COCKPIT_IDS.decisions(ws.entry.workspace.path); + item.iconPath = new vscode.ThemeIcon('law'); + const about = "This workspace's decisions file: the questions waiting for your ruling."; + if (this.actsHere(ws)) { + item.contextValue = COCKPIT_DECISIONS_CONTEXT; + item.tooltip = `${about}\nClick to open the Decisions panel.`; + item.command = { command: OPEN_DECISIONS_COMMAND, title: 'Open Decisions' }; + } else { + const target: WorkspaceTarget = { ...targetOf(ws), isCurrent: false }; + item.contextValue = REMOTE_CONTEXT.decisions; + item.tooltip = navigateTooltip(about, target); + item.command = openWorkspaceCommand(target); + } + return item; } // ── Row builders ────────────────────────────────────────────────────────── diff --git a/apps/vscode/src/workspace-views/availability.ts b/apps/vscode/src/workspace-views/availability.ts new file mode 100644 index 000000000..c01ad5b36 --- /dev/null +++ b/apps/vscode/src/workspace-views/availability.ts @@ -0,0 +1,24 @@ +/** + * Where the Work and Decisions panels are offered (Spec 1963): only in a window of a Codev + * workspace, and not in a builder-worktree window (#1809: surfaces that act on the parent workspace + * stay in the parent's window). Elsewhere their commands stay in the Command Palette and say why + * they do nothing, instead of being silently absent. No `vscode` import. + */ + +export interface WorkspaceViewsWindow { + /** The window is rooted at a builder worktree (#1809). */ + builderWorktreeWindow: boolean; + /** This window's Codev workspace, or null when it has none. */ + workspacePath: string | null; +} + +/** Why `surface` is not offered in this window, or null when it is. */ +export function workspaceViewUnavailableReason(surface: string, window: WorkspaceViewsWindow): string | null { + if (window.builderWorktreeWindow) { + return `Codev: ${surface} is not offered in a builder-worktree window. Open it from the parent workspace's window.`; + } + if (window.workspacePath === null) { + return `Codev: ${surface} needs a Codev workspace, and this window has none. Open a folder containing a Codev project.`; + } + return null; +} diff --git a/apps/vscode/src/workspace-views/decisions-bridge.ts b/apps/vscode/src/workspace-views/decisions-bridge.ts new file mode 100644 index 000000000..91932deb9 --- /dev/null +++ b/apps/vscode/src/workspace-views/decisions-bridge.ts @@ -0,0 +1,85 @@ +/** + * The Decisions panel's Tower calls (Spec 1963): read, rule and image, made by the extension host + * with this window's Tower connection, and turned into the results the shared Decisions view shows. + * The mapping is the dashboard's (`apps/web/src/lib/api.ts`), so a card shows the same text in both: + * - a refusal keeps Tower's `code` and `message`; + * - not-found on a read is the empty state (no decisions file), with a hint to create one; + * - "Tower was not reached" and "Tower answered with something else" each say so. + * + * Never throws. While this window is not connected to Tower nothing is requested, and each call + * says it is not connected: the view keeps the last document it read, under that notice. + * No `vscode` import. + */ + +import type { DecisionsRuleRequest } from '@cluesmith/codev-types'; +import type { DecisionImageRouteResult, TowerClient } from '@cluesmith/codev-sdk/tower-client'; +import type { DecisionRulingResult, DecisionsFetchResult } from '@cluesmith/codev-workspace-views/host'; +import type { ConnectionState } from '../connection-manager.js'; +import type { DecisionsImagePayload } from './messages.js'; + +/** What the bridge needs of this window's connection (`ConnectionManager`). */ +export interface DecisionsConnection { + getState(): ConnectionState; + getClient(): Pick | null; + /** The workspace whose decisions file the panel shows. */ + getWorkspacePath(): string | null; +} + +export const NOT_CONNECTED_MESSAGE = 'Not connected to Tower.'; + +/** Appended to Tower's not-found message: how a workspace gets a decisions file. */ +export const DECISIONS_INIT_HINT = 'To start one, run afx decisions init in this workspace.'; + +function unanswered(result: { kind: 'unreachable'; error: string } | { kind: 'unreadable'; status: number }): string { + return result.kind === 'unreachable' + ? `Could not reach Tower: ${result.error}` + : `Unexpected response from Tower (HTTP ${result.status})`; +} + +export class DecisionsBridge { + constructor(private readonly connection: DecisionsConnection) {} + + /** The client and workspace to call, or null while this window is not connected. */ + private target(): { client: NonNullable>; workspacePath: string } | null { + if (this.connection.getState() !== 'connected') { return null; } + const client = this.connection.getClient(); + const workspacePath = this.connection.getWorkspacePath(); + if (!client || !workspacePath) { return null; } + return { client, workspacePath }; + } + + async read(): Promise { + const target = this.target(); + if (!target) { return { kind: 'error', message: NOT_CONNECTED_MESSAGE }; } + const result = await target.client.getDecisions(target.workspacePath); + if (result.kind !== 'verdict') { return { kind: 'error', message: unanswered(result) }; } + const { verdict } = result; + if (verdict.ok) { return { kind: 'document', document: verdict.document }; } + if (verdict.code === 'not-found') { return { kind: 'not-found', message: `${verdict.message} ${DECISIONS_INIT_HINT}` }; } + return { kind: 'error', message: verdict.message }; + } + + async rule(request: DecisionsRuleRequest): Promise { + const target = this.target(); + if (!target) { return { kind: 'error', message: `${NOT_CONNECTED_MESSAGE} The ruling was not sent.` }; } + const result = await target.client.ruleDecision(target.workspacePath, request); + if (result.kind !== 'verdict') { return { kind: 'error', message: unanswered(result) }; } + const { verdict } = result; + if (verdict.ok) { return { kind: 'document', document: verdict.document }; } + return { kind: 'refused', code: verdict.code, message: verdict.message }; + } + + async image(imagePath: string): Promise { + const target = this.target(); + if (!target) { return { kind: 'not-loaded', message: NOT_CONNECTED_MESSAGE }; } + const result: DecisionImageRouteResult = await target.client.getDecisionImage(target.workspacePath, imagePath); + switch (result.kind) { + case 'image': + return { kind: 'image', bytes: result.bytes, contentType: result.contentType }; + case 'verdict': + return { kind: 'not-loaded', message: result.verdict.message }; + default: + return { kind: 'not-loaded', message: unanswered(result) }; + } + } +} diff --git a/apps/vscode/src/workspace-views/decisions-panel.ts b/apps/vscode/src/workspace-views/decisions-panel.ts new file mode 100644 index 000000000..ec48eeae9 --- /dev/null +++ b/apps/vscode/src/workspace-views/decisions-panel.ts @@ -0,0 +1,164 @@ +/** + * The Decisions panel (Spec 1963): the shared Decisions view in an editor-area webview, for this + * window's workspace. One panel per window: opening it again reveals it, and never creates a + * second one or reloads the first. A window reload restores it through the panel serializer. + * + * The webview never contacts Tower. It asks the host, which calls Tower through `DecisionsBridge`: + * - **Polling has one owner:** the shared `useDecisions` hook, at its 2 s cadence. Each tick is one + * `decisions/read` message, and the host makes one Tower request per message. The host runs no + * timer. It relays the panel's own visibility (`onDidChangeViewState`), which the webview passes + * to the hook as `isActive`, so polling stops while the panel is hidden: a retained, hidden + * webview still reports its page as visible. + * - **A reply for a closed panel is dropped** silently: no post, no toast, no new panel. + * - **Links** open in the user's browser, http(s) only. **Images** a decision item names by + * workspace path come back as bytes, which the webview shows as object URLs. + */ + +import * as vscode from 'vscode'; +import { renderWorkspaceViewHtml } from './panel-template.js'; +import { isAllowedExternalUrl } from './security.js'; +import type { DecisionsBridge } from './decisions-bridge.js'; +import { + DECISIONS_VIEW_TYPE, + isDecisionsImageMessage, + isDecisionsReadMessage, + isDecisionsRuleMessage, + isOpenExternalMessage, + isReadyMessage, + ruleRequestOf, + type DecisionsHostMessage, +} from './messages.js'; + +export interface DecisionsPanelsOptions { + extensionUri: vscode.Uri; + bridge: Pick; + /** Why the panel is not offered in this window (`availability.ts`), or null when it is. */ + unavailableReason: () => string | null; + log: (line: string) => void; +} + +const PANEL_TITLE = 'Decisions'; + +/** What the webview may load: the bundle under `dist`, and nothing else from the extension. */ +function webviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions { + return { enableScripts: true, localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist')] }; +} + +/** The window's one Decisions panel, and its serializer. */ +export class DecisionsPanels implements vscode.WebviewPanelSerializer { + private current: DecisionsPanelSession | undefined; + + constructor(private readonly options: DecisionsPanelsOptions) {} + + /** + * *Codev: Open Decisions* and the Cockpit's Decisions entry: reveal the panel where it is, or open + * it in the active editor group. Where the panel is not offered, say why instead. + */ + show(): void { + const reason = this.options.unavailableReason(); + if (reason) { + void vscode.window.showInformationMessage(reason); + return; + } + if (this.current) { + this.current.panel.reveal(); + return; + } + const panel = vscode.window.createWebviewPanel( + DECISIONS_VIEW_TYPE, + PANEL_TITLE, + vscode.ViewColumn.Active, + { ...webviewOptions(this.options.extensionUri), retainContextWhenHidden: true }, + ); + this.adopt(panel); + } + + /** The panel, if one is open. */ + get panel(): vscode.WebviewPanel | undefined { + return this.current?.panel; + } + + /** + * A window reload restores an open panel in its group. Drafts are not restored, as a dashboard page + * reload loses them too. A second panel, or one in a window where Decisions is not offered, is closed. + */ + async deserializeWebviewPanel(panel: vscode.WebviewPanel): Promise { + if (this.current || this.options.unavailableReason()) { + panel.dispose(); + return; + } + panel.webview.options = webviewOptions(this.options.extensionUri); + this.adopt(panel); + } + + private adopt(panel: vscode.WebviewPanel): void { + const session = new DecisionsPanelSession(panel, this.options, () => { + if (this.current === session) { this.current = undefined; } + }); + this.current = session; + } +} + +/** One panel's webview, from creation until it is closed. */ +class DecisionsPanelSession { + private disposed = false; + private readonly subscriptions: vscode.Disposable[] = []; + + constructor( + readonly panel: vscode.WebviewPanel, + private readonly options: DecisionsPanelsOptions, + onDisposed: () => void, + ) { + const { webview } = panel; + const bundle = vscode.Uri.joinPath(options.extensionUri, 'dist', 'webview'); + webview.html = renderWorkspaceViewHtml({ + cspSource: webview.cspSource, + scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(bundle, 'decisions.js')).toString(), + styleUri: webview.asWebviewUri(vscode.Uri.joinPath(bundle, 'decisions.css')).toString(), + title: PANEL_TITLE, + }); + this.subscriptions.push( + webview.onDidReceiveMessage((message: unknown) => { void this.onMessage(message); }), + panel.onDidChangeViewState(() => this.postVisibility()), + panel.onDidDispose(() => { + this.disposed = true; + for (const subscription of this.subscriptions) { subscription.dispose(); } + onDisposed(); + }), + ); + } + + private post(message: DecisionsHostMessage): void { + // A reply that lands after the panel closed has nowhere to go. + if (this.disposed) { return; } + void this.panel.webview.postMessage(message); + } + + private postVisibility(): void { + this.post({ type: 'visibility', visible: this.panel.visible }); + } + + private async onMessage(message: unknown): Promise { + const { bridge } = this.options; + if (isReadyMessage(message)) { + this.postVisibility(); + } else if (isDecisionsReadMessage(message)) { + const result = await bridge.read(); + this.post({ type: 'decisions/read-result', requestId: message.requestId, result }); + } else if (isDecisionsRuleMessage(message)) { + const result = await bridge.rule(ruleRequestOf(message)); + this.post({ type: 'decisions/rule-result', requestId: message.requestId, result }); + } else if (isDecisionsImageMessage(message)) { + const result = await bridge.image(message.path); + this.post({ type: 'decisions/image-result', requestId: message.requestId, result }); + } else if (isOpenExternalMessage(message)) { + if (isAllowedExternalUrl(message.url)) { + void vscode.env.openExternal(vscode.Uri.parse(message.url)); + } else { + this.options.log(`Decisions panel: did not open ${message.url}; only http(s) links open from a panel.`); + } + } else { + this.options.log('Decisions panel: ignored a malformed message from its webview.'); + } + } +} diff --git a/apps/vscode/src/workspace-views/messages.ts b/apps/vscode/src/workspace-views/messages.ts new file mode 100644 index 000000000..bb2e26993 --- /dev/null +++ b/apps/vscode/src/workspace-views/messages.ts @@ -0,0 +1,161 @@ +/** + * The host ↔ webview contract of the Work and Decisions panels (Spec 1963). + * + * The webviews never contact Tower: every read and action is a message to the extension host, + * which makes the Tower call with its own connection and posts the result back. A request carries + * a `requestId` the reply echoes, so the webview can match replies to requests it still waits on. + * + * Webview → host messages are untrusted: the host acts on one only after its `is*Message` guard + * accepts it. Pure types and guards, no `vscode` import, so the webview bundle shares them. + */ + +import type { DecisionsRuleRequest } from '@cluesmith/codev-types'; +import type { DecisionRulingResult, DecisionsFetchResult } from '@cluesmith/codev-workspace-views/host'; + +/** The Decisions panel's webview type, as its serializer and restore know it. */ +export const DECISIONS_VIEW_TYPE = 'codev.decisions'; + +// ── Webview → host ────────────────────────────────────────────────────────── + +/** The webview has mounted: the host answers with the panel's visibility. */ +export interface ReadyMessage { + type: 'ready'; +} + +/** Read the workspace's decisions document. */ +export interface DecisionsReadMessage { + type: 'decisions/read'; + requestId: number; +} + +/** Write the owner's ruling. */ +export interface DecisionsRuleMessage { + type: 'decisions/rule'; + requestId: number; + request: DecisionsRuleRequest; +} + +/** Load an image an item names by its workspace path, as written in the item. */ +export interface DecisionsImageMessage { + type: 'decisions/image'; + requestId: number; + path: string; +} + +/** Open a link in the user's browser. The host opens only http(s) URLs. */ +export interface OpenExternalMessage { + type: 'open-external'; + url: string; +} + +export type DecisionsWebviewMessage = + | ReadyMessage + | DecisionsReadMessage + | DecisionsRuleMessage + | DecisionsImageMessage + | OpenExternalMessage; + +// ── Host → webview ────────────────────────────────────────────────────────── + +/** + * Whether the panel is on screen. A retained, hidden webview still reports + * `document.visibilityState === 'visible'`, so the panel's own visibility comes from the host. + */ +export interface VisibilityMessage { + type: 'visibility'; + visible: boolean; +} + +export interface DecisionsReadResultMessage { + type: 'decisions/read-result'; + requestId: number; + result: DecisionsFetchResult; +} + +export interface DecisionsRuleResultMessage { + type: 'decisions/rule-result'; + requestId: number; + result: DecisionRulingResult; +} + +/** An image as the host delivers it: its bytes and type, which the webview shows as an object URL. */ +export type DecisionsImagePayload = + | { kind: 'image'; bytes: Uint8Array; contentType: string } + | { kind: 'not-loaded'; message: string }; + +export interface DecisionsImageResultMessage { + type: 'decisions/image-result'; + requestId: number; + result: DecisionsImagePayload; +} + +export type DecisionsHostMessage = + | VisibilityMessage + | DecisionsReadResultMessage + | DecisionsRuleResultMessage + | DecisionsImageResultMessage; + +// ── Guards (webview → host is untrusted) ──────────────────────────────────── + +/** The longest image path or URL a webview may send; item markdown never needs more. */ +export const MAX_WEBVIEW_STRING = 4096; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isRequestId(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; +} + +function isBoundedString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_WEBVIEW_STRING; +} + +function isOptionalString(value: unknown): value is string | undefined { + return value === undefined || typeof value === 'string'; +} + +export function isReadyMessage(message: unknown): message is ReadyMessage { + return isRecord(message) && message.type === 'ready'; +} + +export function isDecisionsReadMessage(message: unknown): message is DecisionsReadMessage { + return isRecord(message) && message.type === 'decisions/read' && isRequestId(message.requestId); +} + +/** + * A ruling request of the shape Tower's rule route takes: a non-empty `id` and `fingerprint`, + * and `word` and `comment` strings when present. Tower checks the content. + */ +function isRuleRequest(value: unknown): value is DecisionsRuleRequest { + return isRecord(value) + && typeof value.id === 'string' && value.id.length > 0 + && typeof value.fingerprint === 'string' && value.fingerprint.length > 0 + && isOptionalString(value.word) + && isOptionalString(value.comment); +} + +export function isDecisionsRuleMessage(message: unknown): message is DecisionsRuleMessage { + return isRecord(message) && message.type === 'decisions/rule' + && isRequestId(message.requestId) && isRuleRequest(message.request); +} + +export function isDecisionsImageMessage(message: unknown): message is DecisionsImageMessage { + return isRecord(message) && message.type === 'decisions/image' + && isRequestId(message.requestId) && isBoundedString(message.path) && !message.path.includes('\0'); +} + +/** The message's shape only: whether its URL may be opened is `security.ts`'s decision. */ +export function isOpenExternalMessage(message: unknown): message is OpenExternalMessage { + return isRecord(message) && message.type === 'open-external' && isBoundedString(message.url); +} + +/** Only the fields Tower's rule route reads, so nothing else a webview adds is forwarded. */ +export function ruleRequestOf(message: DecisionsRuleMessage): DecisionsRuleRequest { + const { id, fingerprint, word, comment } = message.request; + const request: DecisionsRuleRequest = { id, fingerprint }; + if (word !== undefined) { request.word = word; } + if (comment !== undefined) { request.comment = comment; } + return request; +} diff --git a/apps/vscode/src/workspace-views/panel-template.ts b/apps/vscode/src/workspace-views/panel-template.ts new file mode 100644 index 000000000..2d748f72c --- /dev/null +++ b/apps/vscode/src/workspace-views/panel-template.ts @@ -0,0 +1,68 @@ +/** + * The HTML document of a Work or Decisions panel webview (Spec 1963), with its Content Security + * Policy. Pure string building; the panel resolves the webview URIs and the CSP source. + * + * The policy admits only what the panels load: + * - `default-src 'none'` first, so anything not listed is refused. In particular there is no + * `connect-src`, so `fetch`, XHR, WebSocket and EventSource fall back to `'none'`: a panel cannot + * reach Tower, or anywhere else; + * - `script-src` is the per-render nonce only: no `'unsafe-inline'`, no `'unsafe-eval'`; + * - `style-src` adds `'unsafe-inline'`, as the existing webviews do: the shared components set + * React `style` attributes (a progress bar's width), which a stricter policy would silently drop. + * Inline styles run no code; + * - `img-src` admits the bundle's own origin, `blob:` (workspace images the host delivers as bytes, + * shown as object URLs) and `http:`/`https:` (remote images written in decision items, as the + * dashboard loads them). + */ + +import { randomBytes } from 'node:crypto'; + +export interface WorkspaceViewHtmlOptions { + /** `webview.cspSource`: the origin the bundle's script, stylesheet and images load from. */ + cspSource: string; + /** `asWebviewUri(...)` of the bundled script, stringified. */ + scriptUri: string; + /** `asWebviewUri(...)` of the bundled stylesheet, stringified. */ + styleUri: string; + /** The document title. */ + title: string; +} + +/** The policy for a given CSP source and nonce. */ +export function workspaceViewCsp(cspSource: string, nonce: string): string { + return [ + `default-src 'none'`, + `script-src 'nonce-${nonce}'`, + `style-src ${cspSource} 'unsafe-inline'`, + `img-src ${cspSource} blob: http: https:`, + ].join('; '); +} + +/** A fresh nonce: 18 random bytes, base64 (24 characters, no padding). */ +function createNonce(): string { + return randomBytes(18).toString('base64'); +} + +function escapeAttribute(value: string): string { + return value.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>'); +} + +/** The webview document, with a fresh nonce bound into the policy and the script tag. */ +export function renderWorkspaceViewHtml(opts: WorkspaceViewHtmlOptions): string { + const nonce = createNonce(); + const csp = workspaceViewCsp(opts.cspSource, nonce); + return /* html */ ` + + + + + + + ${escapeAttribute(opts.title)} + + +
+ + +`; +} diff --git a/apps/vscode/src/workspace-views/security.ts b/apps/vscode/src/workspace-views/security.ts new file mode 100644 index 000000000..08d86126c --- /dev/null +++ b/apps/vscode/src/workspace-views/security.ts @@ -0,0 +1,59 @@ +/** + * What a Work or Decisions webview may make the host do outside it (Spec 1963). A path or URL + * from a webview is untrusted: + * - a file opens only when its canonical (symlink-resolved) location is inside the workspace; + * - a URL opens in the user's browser only when its scheme is `http:` or `https:`. + * + * Containment is decided by `path.relative` between canonical paths, never by a string prefix, so + * `/ws-other` is not inside `/ws`, and on Windows the drive-letter case and `\` / `/` spellings are + * normalised by the same calls. No `vscode` import. + */ + +import { promises as fsp } from 'node:fs'; +import * as path from 'node:path'; + +/** + * Whether `target` is `root` or lies below it. Both must already be canonical (`fs.realpath`). + * `pathImpl` is the platform's `path` (`path.win32` in the Windows table tests). + */ +export function isWithin(root: string, target: string, pathImpl: path.PlatformPath = path): boolean { + const relative = pathImpl.relative(root, target); + if (relative === '') { return true; } + if (pathImpl.isAbsolute(relative)) { return false; } + return relative !== '..' && !relative.startsWith(`..${pathImpl.sep}`); +} + +/** Where a requested workspace file is, or why it may not be opened. */ +export type WorkspaceFileResolution = + | { ok: true; path: string } + | { ok: false; reason: 'outside-workspace' | 'not-found' }; + +/** + * The canonical path of `requested` when it is inside the workspace at `root`. A relative + * `requested` is resolved against the workspace. Both the workspace and the target go through + * `fs.realpath`, so a symlink (or a Windows junction) that leads outside is refused, and a path that + * does not exist is `not-found`. + */ +export async function resolveWorkspaceFile(root: string, requested: string): Promise { + let canonicalRoot: string; + let canonicalTarget: string; + try { + canonicalRoot = await fsp.realpath(root); + canonicalTarget = await fsp.realpath(path.resolve(canonicalRoot, requested)); + } catch { + return { ok: false, reason: 'not-found' }; + } + if (!isWithin(canonicalRoot, canonicalTarget)) { return { ok: false, reason: 'outside-workspace' }; } + return { ok: true, path: canonicalTarget }; +} + +/** Whether a URL from a webview may be opened in the user's browser: `http:` or `https:` only. */ +export function isAllowedExternalUrl(url: string): boolean { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return false; + } + return parsed.protocol === 'http:' || parsed.protocol === 'https:'; +} diff --git a/apps/vscode/src/workspace-views/webview/DecisionsApp.tsx b/apps/vscode/src/workspace-views/webview/DecisionsApp.tsx new file mode 100644 index 000000000..4d1b061cb --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/DecisionsApp.tsx @@ -0,0 +1,94 @@ +/** + * The Decisions panel's webview UI (Spec 1963): the shared Decisions view, active while the panel is + * on screen, and the full-size image view over it. + * + * - `isActive` follows the panel's own visibility, which the extension host relays. A retained, + * hidden webview still reports its page as visible, so the view's page-visibility check alone + * would keep polling while the panel is hidden. + * - Clicking an image in an item shows it full size here, over the view, because a webview cannot + * open a browser tab. The view stays mounted under it, so drafts are kept. *Close*, Escape or a + * click beside the image closes it. + */ + +import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'; +import { DecisionsView } from '@cluesmith/codev-workspace-views'; +import type { FullSizeImage, WebviewDecisionsHost } from './decisions-host.js'; + +export interface PanelState { + /** Whether the panel is on screen; false until the extension host says otherwise. */ + visible: boolean; + /** The image shown full size, or null. */ + fullSize: FullSizeImage | null; +} + +/** The panel's UI state, outside React so the host's messages can set it. */ +export class PanelStore { + private state: PanelState = { visible: false, fullSize: null }; + private readonly listeners = new Set<() => void>(); + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => { this.listeners.delete(listener); }; + }; + + readonly getSnapshot = (): PanelState => this.state; + + setVisible(visible: boolean): void { + if (this.state.visible === visible) { return; } + this.update({ ...this.state, visible }); + } + + showImage(image: FullSizeImage): void { + this.update({ ...this.state, fullSize: image }); + } + + closeImage(): void { + if (this.state.fullSize === null) { return; } + this.update({ ...this.state, fullSize: null }); + } + + private update(state: PanelState): void { + this.state = state; + for (const listener of this.listeners) { listener(); } + } +} + +function FullSizeView({ image, onClose }: { image: FullSizeImage; onClose: () => void }) { + const closeButton = useRef(null); + + useEffect(() => { + closeButton.current?.focus(); + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') { onClose(); } + }; + window.addEventListener('keydown', onKeyDown); + return () => window.removeEventListener('keydown', onKeyDown); + }, [onClose]); + + const title = image.alt || 'Image'; + return ( +
+
+ {title} + +
+
{ if (event.target === event.currentTarget) { onClose(); } }} + > + {image.alt} +
+
+ ); +} + +export function DecisionsApp({ host, store }: { host: WebviewDecisionsHost; store: PanelStore }) { + const { visible, fullSize } = useSyncExternalStore(store.subscribe, store.getSnapshot); + const closeImage = useCallback(() => store.closeImage(), [store]); + return ( + <> + + {fullSize && } + + ); +} diff --git a/apps/vscode/src/workspace-views/webview/__tests__/DecisionsApp.test.tsx b/apps/vscode/src/workspace-views/webview/__tests__/DecisionsApp.test.tsx new file mode 100644 index 000000000..f17a32190 --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/__tests__/DecisionsApp.test.tsx @@ -0,0 +1,250 @@ +// @vitest-environment jsdom +/** + * Spec 1963 scenarios 15, 16 and 21 (webview side): the Decisions panel's UI, run through its real + * postMessage host with a fake extension host answering each request as the bridge would. + * - Nothing is read until the extension host says the panel is on screen; the poll runs while it + * is and stops while it is hidden, though the page itself still reports `visible`. + * - Submit sends one `decisions/rule` message with the card's id, fingerprint, word and comment; + * a refusal shows its message on the card and keeps the draft. + * - A workspace image arrives as bytes and is shown through an object URL; clicking it opens the + * panel's own full-size view, which Close, Escape or a click beside the image closes. + * - An http(s) link is handed to the extension host to open. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import type { DecisionItem, DecisionsDocument } from '@cluesmith/codev-types'; +import type { DecisionsHostMessage, DecisionsWebviewMessage } from '../../messages.js'; +import { DecisionsApp, PanelStore } from '../DecisionsApp.js'; +import { WebviewDecisionsHost } from '../decisions-host.js'; + +type Answer = Exclude['result']; + +function item(id: string, question: string, overrides: Partial = {}): DecisionItem { + return { + id, + stamp: null, + question, + bodyMarkdown: '', + options: [ + { word: 'accept', description: 'merge as is', recommended: true }, + { word: 'rework', description: 'send back', recommended: false }, + ], + currentRuling: '', + qa: [], + fingerprint: `fp-${id}`, + problems: [], + writable: true, + ...overrides, + }; +} + +function documentOf(version: string, ...items: DecisionItem[]): DecisionsDocument { + return { path: 'codev/state/pending-decisions.md', version, items, ruledMarkdown: '', problems: [] }; +} + +const MERGE = item('main-12', 'Merge the onboarding scan fix?'); + +/** The extension host's side: records what the webview posts and answers each request. */ +function mount(answers: { + read?: () => Answer; + rule?: () => Answer; + image?: (path: string) => Answer; +} = {}) { + const posted: DecisionsWebviewMessage[] = []; + const store = new PanelStore(); + let host!: WebviewDecisionsHost; + const reply = (message: DecisionsWebviewMessage) => { + const answer = (result: Answer, type: Exclude['type']) => { + void Promise.resolve().then(() => act(() => host.receive({ type, requestId: (message as { requestId: number }).requestId, result }))); + }; + if (message.type === 'decisions/read' && answers.read) { answer(answers.read(), 'decisions/read-result'); } + if (message.type === 'decisions/rule' && answers.rule) { answer(answers.rule(), 'decisions/rule-result'); } + if (message.type === 'decisions/image' && answers.image) { answer(answers.image(message.path), 'decisions/image-result'); } + }; + host = new WebviewDecisionsHost(message => { posted.push(message); reply(message); }, image => store.showImage(image)); + render(); + const show = () => act(() => store.setVisible(true)); + const hide = () => act(() => store.setVisible(false)); + const reads = () => posted.filter(m => m.type === 'decisions/read').length; + return { posted, store, host, show, hide, reads }; +} + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +describe('reading and polling', () => { + it('reads nothing until the extension host says the panel is on screen, then shows the items', async () => { + const app = mount({ read: () => ({ kind: 'document', document: documentOf('v1', MERGE) }) }); + expect(app.posted).toEqual([]); + app.show(); + expect(app.posted).toEqual([{ type: 'decisions/read', requestId: 0 }]); + expect(await screen.findByRole('article', { name: MERGE.question })).toBeTruthy(); + }); + + it('polls while on screen and stops while hidden, though the page itself still reports visible', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const app = mount({ read: () => ({ kind: 'document', document: documentOf('v1', MERGE) }) }); + expect(document.visibilityState).toBe('visible'); + app.show(); + await screen.findByRole('article', { name: MERGE.question }); + expect(app.reads()).toBe(1); + + await act(async () => { vi.advanceTimersByTime(2000); }); + await waitFor(() => expect(app.reads()).toBe(2)); + + app.hide(); + await act(async () => { vi.advanceTimersByTime(20_000); }); + expect(app.reads()).toBe(2); + + app.show(); + await waitFor(() => expect(app.reads()).toBe(3)); + }); + + it("shows the extension host's message for no decisions file", async () => { + const message = 'There is no decisions file at codev/state/pending-decisions.md. To start one, run afx decisions init in this workspace.'; + const app = mount({ read: () => ({ kind: 'not-found', message }) }); + app.show(); + expect((await screen.findByRole('status')).textContent).toBe(message); + }); +}); + +describe('ruling', () => { + const choose = (word: string) => { + const radio = within(screen.getByRole('article', { name: MERGE.question })) + .getAllByRole('radio').find(r => r.value === word)!; + fireEvent.click(radio); + }; + const comment = (text: string) => fireEvent.change( + within(screen.getByRole('article', { name: MERGE.question })).getByRole('textbox', { name: 'Comment or question' }), + { target: { value: text } }, + ); + const submit = () => fireEvent.click(within(screen.getByRole('article', { name: MERGE.question })).getByRole('button', { name: /^Submit/ })); + + it("posts one ruling with the card's id, fingerprint, word and comment, and shows the document it returns", async () => { + const ruled = item('main-12', MERGE.question, { currentRuling: 'accept — ship it', writable: true }); + const app = mount({ + read: () => ({ kind: 'document', document: documentOf('v1', MERGE) }), + rule: () => ({ kind: 'document', document: documentOf('v2', ruled) }), + }); + app.show(); + await screen.findByRole('article', { name: MERGE.question }); + choose('accept'); + comment(' ship it '); + submit(); + const rulings = app.posted.filter(m => m.type === 'decisions/rule'); + expect(rulings).toEqual([{ + type: 'decisions/rule', requestId: 1, request: { id: 'main-12', fingerprint: 'fp-main-12', word: 'accept', comment: 'ship it' }, + }]); + await waitFor(() => expect(screen.getByRole('article', { name: MERGE.question }).textContent).toContain('accept — ship it')); + }); + + it('shows a refusal on the card and keeps the draft', async () => { + const message = 'main-12 has changed since you read it, so nothing was written. Review it and rule again.'; + const app = mount({ + read: () => ({ kind: 'document', document: documentOf('v1', MERGE) }), + rule: () => ({ kind: 'refused', code: 'item-changed', message }), + }); + app.show(); + await screen.findByRole('article', { name: MERGE.question }); + choose('rework'); + comment('needs tests'); + submit(); + const card = screen.getByRole('article', { name: MERGE.question }); + expect((await within(card).findByRole('alert')).textContent).toBe(message); + expect(within(card).getByRole('textbox', { name: 'Comment or question' }).value).toBe('needs tests'); + expect(within(card).getAllByRole('radio').find(r => r.checked)?.value).toBe('rework'); + }); +}); + +describe('images and links', () => { + let createObjectURL: ReturnType string>>; + let revokeObjectURL: ReturnType void>>; + + beforeEach(() => { + let next = 0; + createObjectURL = vi.fn(() => `blob:vscode-webview://panel/${++next}`); + revokeObjectURL = vi.fn(); + Object.assign(URL, { createObjectURL, revokeObjectURL }); + }); + + const withImage = item('ui-4', 'Ship the compact layout?', { bodyMarkdown: '![Compact layout](decision-assets/compact.png)' }); + + it('asks the extension host for a workspace image and shows its bytes through an object URL', async () => { + const app = mount({ + read: () => ({ kind: 'document', document: documentOf('v1', withImage) }), + image: () => ({ kind: 'image', bytes: new Uint8Array([0x89, 0x50, 0x4e, 0x47]), contentType: 'image/png' }), + }); + app.show(); + const image = await screen.findByRole('img', { name: 'Compact layout' }); + await waitFor(() => expect(image.getAttribute('src')).toBe('blob:vscode-webview://panel/1')); + expect(app.posted.filter(m => m.type === 'decisions/image')).toEqual([{ type: 'decisions/image', requestId: 1, path: 'decision-assets/compact.png' }]); + const blob = createObjectURL.mock.calls[0][0]; + expect(blob.type).toBe('image/png'); + expect(blob.size).toBe(4); + }); + + it("shows why an image was not loaded, in the image's place", async () => { + const message = 'The image ../../x.png is outside the workspace, so it was not read.'; + const app = mount({ + read: () => ({ kind: 'document', document: documentOf('v1', item('ui-5', 'Q?', { bodyMarkdown: '![x](../../x.png)' })) }), + image: () => ({ kind: 'not-loaded', message }), + }); + app.show(); + const note = await waitFor(() => { + const found = screen.getByRole('article', { name: 'Q?' }).querySelector('.decisions-image-missing'); + expect(found).not.toBeNull(); + return found!; + }); + expect(note.textContent).toContain('Image not loaded'); + expect(note.textContent).toContain('../../x.png'); + expect(note.title).toBe(message); + expect(createObjectURL).not.toHaveBeenCalled(); + }); + + it('opens a loaded image full size over the view; Close, Escape and a click beside it each close it', async () => { + const app = mount({ + read: () => ({ kind: 'document', document: documentOf('v1', withImage) }), + image: () => ({ kind: 'image', bytes: new Uint8Array([1]), contentType: 'image/png' }), + }); + app.show(); + const image = await screen.findByRole('img', { name: 'Compact layout' }); + await waitFor(() => expect(image.getAttribute('src')).toMatch(/^blob:/)); + const open = () => { + fireEvent.click(image); + return screen.getByRole('dialog', { name: 'Compact layout' }); + }; + + let dialog = open(); + expect(within(dialog).getByRole('img').getAttribute('src')).toBe(image.getAttribute('src')); + expect(document.activeElement).toBe(within(dialog).getByRole('button', { name: 'Close' })); + fireEvent.click(within(dialog).getByRole('button', { name: 'Close' })); + expect(screen.queryByRole('dialog')).toBeNull(); + + open(); + fireEvent.keyDown(window, { key: 'Escape' }); + expect(screen.queryByRole('dialog')).toBeNull(); + + dialog = open(); + fireEvent.click(within(dialog).getByRole('img')); + expect(screen.queryByRole('dialog')).not.toBeNull(); + fireEvent.click(dialog.querySelector('.wv-fullsize-body')!); + expect(screen.queryByRole('dialog')).toBeNull(); + // The view stayed mounted under it. + expect(screen.getByRole('article', { name: withImage.question })).toBeTruthy(); + expect(app.store.getSnapshot().fullSize).toBeNull(); + }); + + it('hands an http(s) link to the extension host and navigates nowhere', async () => { + const linked = item('ops-3', 'Raise the timeout?', { bodyMarkdown: 'See [the PR](https://github.com/cluesmith/codev/pull/1971).' }); + const app = mount({ read: () => ({ kind: 'document', document: documentOf('v1', linked) }) }); + app.show(); + const link = await screen.findByRole('link', { name: 'the PR' }); + const event = new MouseEvent('click', { bubbles: true, cancelable: true }); + link.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + expect(app.posted.filter(m => m.type === 'open-external')).toEqual([{ type: 'open-external', url: 'https://github.com/cluesmith/codev/pull/1971' }]); + }); +}); diff --git a/apps/vscode/src/workspace-views/webview/__tests__/decisions-host.test.ts b/apps/vscode/src/workspace-views/webview/__tests__/decisions-host.test.ts new file mode 100644 index 000000000..1a1ec6fa9 --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/__tests__/decisions-host.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment jsdom +/** + * Spec 1963: the webview side of the Decisions panel's messaging. Each request is one message with + * a fresh `requestId`, resolved by the reply carrying it; nothing ever rejects or hangs on a reply + * of the wrong shape; an image the view stops waiting for resolves at once and its late reply is + * ignored. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { DecisionsDocument } from '@cluesmith/codev-types'; +import type { DecisionsWebviewMessage } from '../../messages.js'; +import { visibilityOf, WebviewDecisionsHost } from '../decisions-host.js'; + +const DOC: DecisionsDocument = { path: 'codev/decisions.md', version: 'v1', items: [], ruledMarkdown: '', problems: [] }; + +/** jsdom's Blob has no `arrayBuffer()`; FileReader reads it. */ +function bytesOf(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as ArrayBuffer); + reader.onerror = () => reject(reader.error); + reader.readAsArrayBuffer(blob); + }); +} + +function setup() { + const posted: DecisionsWebviewMessage[] = []; + const shown = vi.fn(); + const host = new WebviewDecisionsHost(message => posted.push(message), shown); + return { host, posted, shown }; +} + +describe('requests and replies', () => { + it('numbers each request and resolves it with the reply that carries its id, in any order', async () => { + const { host, posted } = setup(); + const first = host.read(); + const second = host.rule({ id: 'D-1', fingerprint: 'f', word: 'ship' }); + expect(posted).toEqual([ + { type: 'decisions/read', requestId: 0 }, + { type: 'decisions/rule', requestId: 1, request: { id: 'D-1', fingerprint: 'f', word: 'ship' } }, + ]); + host.receive({ type: 'decisions/rule-result', requestId: 1, result: { kind: 'refused', code: 'item-changed', message: 'changed' } }); + host.receive({ type: 'decisions/read-result', requestId: 0, result: { kind: 'document', document: DOC } }); + expect(await first).toEqual({ kind: 'document', document: DOC }); + expect(await second).toEqual({ kind: 'refused', code: 'item-changed', message: 'changed' }); + }); + + it('ignores a duplicate reply, a reply for no request, and anything that is not a reply', async () => { + const { host } = setup(); + const read = host.read(); + for (const noise of [null, 'x', { type: 'decisions/read-result' }, { type: 'decisions/read-result', requestId: 9, result: { kind: 'document', document: DOC } }, + { type: 'decisions/read-result', requestId: 0, result: 'document' }, { type: 'visibility', visible: true }]) { + expect(() => host.receive(noise)).not.toThrow(); + } + host.receive({ type: 'decisions/read-result', requestId: 0, result: { kind: 'error', message: 'first' } }); + host.receive({ type: 'decisions/read-result', requestId: 0, result: { kind: 'error', message: 'second' } }); + expect(await read).toEqual({ kind: 'error', message: 'first' }); + }); + + it('resolves a reply of the wrong type as an error, never leaving the request waiting', async () => { + const { host } = setup(); + const read = host.read(); + const image = host.image('a.png', new AbortController().signal); + host.receive({ type: 'decisions/rule-result', requestId: 0, result: { kind: 'document', document: DOC } }); + host.receive({ type: 'decisions/read-result', requestId: 1, result: { kind: 'document', document: DOC } }); + expect(await read).toEqual({ kind: 'error', message: 'The extension answered this request with decisions/rule-result.' }); + expect(await image).toEqual({ kind: 'not-loaded', message: 'The extension answered this request with decisions/read-result.' }); + }); +}); + +describe('images', () => { + it('turns the bytes into a Blob of their type', async () => { + const { host, posted } = setup(); + const image = host.image('shots/a.png', new AbortController().signal); + expect(posted).toEqual([{ type: 'decisions/image', requestId: 0, path: 'shots/a.png' }]); + host.receive({ type: 'decisions/image-result', requestId: 0, result: { kind: 'image', bytes: new Uint8Array([1, 2, 3]), contentType: 'image/svg+xml' } }); + const result = await image; + expect(result.kind).toBe('image'); + const blob = (result as { blob: Blob }).blob; + expect(blob.type).toBe('image/svg+xml'); + expect(new Uint8Array(await bytesOf(blob))).toEqual(new Uint8Array([1, 2, 3])); + }); + + it('passes on why an image was not loaded', async () => { + const { host } = setup(); + const image = host.image('../x.png', new AbortController().signal); + host.receive({ type: 'decisions/image-result', requestId: 0, result: { kind: 'not-loaded', message: 'outside the workspace' } }); + expect(await image).toEqual({ kind: 'not-loaded', message: 'outside the workspace' }); + }); + + it('stops waiting when the view aborts, and ignores the late reply', async () => { + const { host } = setup(); + const controller = new AbortController(); + const image = host.image('a.png', controller.signal); + controller.abort(); + expect(await image).toEqual({ kind: 'not-loaded', message: 'The image is no longer shown.' }); + expect(() => host.receive({ type: 'decisions/image-result', requestId: 0, result: { kind: 'image', bytes: new Uint8Array([1]), contentType: 'image/png' } })).not.toThrow(); + }); + + it('posts nothing for an image already aborted', async () => { + const { host, posted } = setup(); + const controller = new AbortController(); + controller.abort(); + expect(await host.image('a.png', controller.signal)).toEqual({ kind: 'not-loaded', message: 'The image is no longer shown.' }); + expect(posted).toEqual([]); + }); +}); + +describe('the host actions the view calls', () => { + it('asks the extension host to open a link, and shows an image in the panel itself', () => { + const { host, posted, shown } = setup(); + host.openExternal('https://github.com/cluesmith/codev'); + host.showImage({ src: 'blob:x', alt: 'shot' }); + expect(posted).toEqual([{ type: 'open-external', url: 'https://github.com/cluesmith/codev' }]); + expect(shown).toHaveBeenCalledWith({ src: 'blob:x', alt: 'shot' }); + }); + + it('reads a visibility message, and nothing else, as visibility', () => { + expect(visibilityOf({ type: 'visibility', visible: true })).toBe(true); + expect(visibilityOf({ type: 'visibility', visible: false })).toBe(false); + for (const other of [null, { type: 'visibility' }, { type: 'visibility', visible: 'true' }, { type: 'decisions/read-result', visible: true }]) { + expect(visibilityOf(other)).toBeNull(); + } + }); +}); diff --git a/apps/vscode/src/workspace-views/webview/decisions-host.ts b/apps/vscode/src/workspace-views/webview/decisions-host.ts new file mode 100644 index 000000000..bc688dc11 --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/decisions-host.ts @@ -0,0 +1,140 @@ +/** + * The Decisions view's host inside the VS Code webview (Spec 1963): every read, ruling and image is + * a message to the extension host, which makes the Tower call and posts the result back. Nothing + * here contacts Tower or anywhere else; the webview's CSP has no `connect-src`. + * + * - Each request carries a `requestId`; its reply resolves the request's promise. A reply for no + * pending request (a duplicate, or one for an image the view stopped waiting for) is ignored. + * - Never rejects, as the view's host contract requires. + * - An image the view aborts stops waiting at once and resolves as not loaded; the view ignores a + * result after its abort anyway. + * - `showImage` opens the panel's own full-size view (a webview cannot open browser tabs); + * `openExternal` asks the host, which opens only http(s) URLs. + * + * One instance per webview, passed to the view on every render: the view keys image loads on it. + */ + +import type { DecisionsRuleRequest } from '@cluesmith/codev-types'; +import type { + DecisionImageResult, + DecisionRulingResult, + DecisionsFetchResult, + DecisionsViewHost, +} from '@cluesmith/codev-workspace-views/host'; +import type { + DecisionsHostMessage, + DecisionsImagePayload, + DecisionsWebviewMessage, +} from '../messages.js'; + +type Reply = Exclude; + +/** A full-size image the panel shows over the view. */ +export interface FullSizeImage { + src: string; + alt: string; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +const REPLY_TYPES: ReadonlySet = new Set(['decisions/read-result', 'decisions/rule-result', 'decisions/image-result']); + +/** A reply from the host, by its shape. The result inside is the host's, which the view renders. */ +function isReply(message: unknown): message is Reply { + return isRecord(message) && typeof message.type === 'string' && REPLY_TYPES.has(message.type) + && typeof message.requestId === 'number' && isRecord(message.result) && typeof message.result.kind === 'string'; +} + +/** A visibility message from the host, or null. */ +export function visibilityOf(message: unknown): boolean | null { + if (isRecord(message) && message.type === 'visibility' && typeof message.visible === 'boolean') { + return message.visible; + } + return null; +} + +export class WebviewDecisionsHost implements DecisionsViewHost { + private nextRequestId = 0; + private readonly pending = new Map void>(); + + constructor( + private readonly post: (message: DecisionsWebviewMessage) => void, + private readonly onShowImage: (image: FullSizeImage) => void, + ) {} + + /** Deliver a message from the extension host. Anything that is not a pending request's reply is ignored. */ + receive(message: unknown): void { + if (!isReply(message)) { return; } + const resolve = this.pending.get(message.requestId); + if (!resolve) { return; } + this.pending.delete(message.requestId); + resolve(message); + } + + read(): Promise { + return this.request( + requestId => ({ type: 'decisions/read', requestId }), + reply => (reply.type === 'decisions/read-result' ? reply.result : { kind: 'error', message: mismatch(reply) }), + ); + } + + rule(request: DecisionsRuleRequest): Promise { + return this.request( + requestId => ({ type: 'decisions/rule', requestId, request }), + reply => (reply.type === 'decisions/rule-result' ? reply.result : { kind: 'error', message: mismatch(reply) }), + ); + } + + image(path: string, signal: AbortSignal): Promise { + const aborted: DecisionImageResult = { kind: 'not-loaded', message: 'The image is no longer shown.' }; + if (signal.aborted) { return Promise.resolve(aborted); } + let requestId = -1; + const result = this.request( + id => { + requestId = id; + return { type: 'decisions/image', requestId: id, path }; + }, + reply => (reply.type === 'decisions/image-result' ? imageResult(reply.result) : { kind: 'not-loaded', message: mismatch(reply) }), + ); + return new Promise(resolve => { + const onAbort = () => { + this.pending.delete(requestId); + resolve(aborted); + }; + signal.addEventListener('abort', onAbort, { once: true }); + void result.then(value => { + signal.removeEventListener('abort', onAbort); + resolve(value); + }); + }); + } + + openExternal(url: string): void { + this.post({ type: 'open-external', url }); + } + + showImage(image: FullSizeImage): void { + this.onShowImage(image); + } + + private request(message: (requestId: number) => DecisionsWebviewMessage, toResult: (reply: Reply) => T): Promise { + const requestId = this.nextRequestId++; + return new Promise(resolve => { + this.pending.set(requestId, reply => resolve(toResult(reply))); + this.post(message(requestId)); + }); + } +} + +/** A workspace image as the view takes it: a `Blob` of the bytes the host delivered. */ +function imageResult(payload: DecisionsImagePayload): DecisionImageResult { + if (payload.kind === 'not-loaded') { return payload; } + return { kind: 'image', blob: new Blob([payload.bytes as Uint8Array], { type: payload.contentType }) }; +} + +/** A reply of the wrong type for its request: a host bug, shown where the result would be. */ +function mismatch(reply: Reply): string { + return `The extension answered this request with ${reply.type}.`; +} diff --git a/apps/vscode/src/workspace-views/webview/decisions-main.tsx b/apps/vscode/src/workspace-views/webview/decisions-main.tsx new file mode 100644 index 000000000..ecbd57d3b --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/decisions-main.tsx @@ -0,0 +1,36 @@ +/** + * Webview entry of the Decisions panel (Spec 1963): mounts the shared Decisions view with a + * postMessage-backed host, so every Tower call is the extension host's. Bundled by esbuild as a + * browser IIFE (`dist/webview/decisions.{js,css}`) and type-checked by `tsconfig.webview.json`. + * + * Styles: the shared views' stylesheet, the markdown theme the dashboard also loads, and + * `vscode-theme.css`, which maps the views' `--codev-wv-*` tokens to VS Code's theme. + */ + +import { createRoot } from 'react-dom/client'; +import '@cluesmith/codev-artifact-canvas/default-theme.css'; +import '@cluesmith/codev-workspace-views/styles.css'; +import './vscode-theme.css'; +import type { DecisionsWebviewMessage } from '../messages.js'; +import { visibilityOf, WebviewDecisionsHost } from './decisions-host.js'; +import { DecisionsApp, PanelStore } from './DecisionsApp.js'; + +declare function acquireVsCodeApi(): { postMessage(message: DecisionsWebviewMessage): void }; + +const vscodeApi = acquireVsCodeApi(); +const store = new PanelStore(); +const host = new WebviewDecisionsHost(message => vscodeApi.postMessage(message), image => store.showImage(image)); + +window.addEventListener('message', (event: MessageEvent) => { + const visible = visibilityOf(event.data); + if (visible !== null) { + store.setVisible(visible); + return; + } + host.receive(event.data); +}); + +const container = document.getElementById('root'); +if (!container) { throw new Error('Decisions panel: the webview document has no #root element'); } +createRoot(container).render(); +vscodeApi.postMessage({ type: 'ready' }); diff --git a/apps/vscode/src/workspace-views/webview/vscode-theme.css b/apps/vscode/src/workspace-views/webview/vscode-theme.css new file mode 100644 index 000000000..3a7618dfd --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/vscode-theme.css @@ -0,0 +1,123 @@ +/* + * The Work and Decisions panels' theme in VS Code (Spec 1963): every `--codev-wv-*` token of the + * shared views' stylesheet (packages/workspace-views/src/styles.css) mapped to VS Code's theme + * variables, so the panels read correctly in light, dark and high-contrast themes and follow a + * theme change live. `workspace-views-theme.test.ts` holds this file to that stylesheet: a token + * left unmapped would keep the dashboard's dark default in every theme. + */ + +:root { + /* Chrome */ + --codev-wv-bg: var(--vscode-editor-background); + --codev-wv-bg-secondary: var(--vscode-editorWidget-background); + --codev-wv-bg-tertiary: var(--vscode-textCodeBlock-background); + --codev-wv-bg-hover: var(--vscode-list-hoverBackground); + --codev-wv-fg: var(--vscode-foreground); + --codev-wv-fg-secondary: var(--vscode-descriptionForeground); + --codev-wv-fg-muted: var(--vscode-disabledForeground); + --codev-wv-border: var(--vscode-panel-border, var(--vscode-contrastBorder)); + /* Buttons and accents use the button pair, so their text keeps its contrast in every theme. */ + --codev-wv-accent: var(--vscode-button-background, var(--vscode-focusBorder)); + --codev-wv-accent-hover: var(--vscode-button-hoverBackground, var(--vscode-focusBorder)); + --codev-wv-on-accent: var(--vscode-button-foreground); + --codev-wv-accent-tint: color-mix(in srgb, var(--codev-wv-accent) 8%, transparent); + --codev-wv-accent-tint-hover: color-mix(in srgb, var(--codev-wv-accent) 18%, transparent); + --codev-wv-accent-tint-border: color-mix(in srgb, var(--codev-wv-accent) 20%, transparent); + --codev-wv-link: var(--vscode-textLink-foreground); + --codev-wv-font-family: var(--vscode-font-family); + --codev-wv-font-mono: var(--vscode-editor-font-family); + + /* Status */ + --codev-wv-status-active: var(--vscode-charts-green); + --codev-wv-status-waiting: var(--vscode-charts-yellow); + --codev-wv-status-error: var(--vscode-errorForeground); + --codev-wv-status-implementing: var(--vscode-charts-orange); + --codev-wv-status-waiting-tint: color-mix(in srgb, var(--vscode-charts-yellow) 10%, transparent); + --codev-wv-status-error-tint: color-mix(in srgb, var(--vscode-errorForeground) 10%, transparent); + --codev-wv-tag-bug-bg: color-mix(in srgb, var(--vscode-errorForeground) 15%, transparent); + --codev-wv-tag-project: var(--vscode-charts-purple); + --codev-wv-tag-project-bg: color-mix(in srgb, var(--vscode-charts-purple) 12%, transparent); + --codev-wv-tag-spike: var(--vscode-charts-blue); + --codev-wv-tag-spike-bg: color-mix(in srgb, var(--vscode-charts-blue) 12%, transparent); +} + +/* The panel fills the editor; the view scrolls inside it. VS Code's webview body has side padding. */ +html, +body, +#root { + height: 100%; +} + +body { + margin: 0; + padding: 0; + background: var(--vscode-editor-background); + color: var(--vscode-foreground); + font-family: var(--vscode-font-family); +} + +/* Keyboard focus follows VS Code's focus colour. */ +button:focus-visible, +textarea:focus-visible, +input:focus-visible, +select:focus-visible, +a:focus-visible, +summary:focus-visible { + outline: 1px solid var(--vscode-focusBorder); + outline-offset: 1px; +} + +/* The full-size image, shown over the view (a webview cannot open a browser tab). */ +.wv-fullsize { + position: fixed; + inset: 0; + z-index: 10; + display: flex; + flex-direction: column; + background: var(--vscode-editor-background); +} + +.wv-fullsize-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 6px 12px; + border-bottom: 1px solid var(--vscode-panel-border, var(--vscode-contrastBorder)); +} + +.wv-fullsize-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--vscode-descriptionForeground); +} + +.wv-fullsize-close { + padding: 4px 12px; + border: 1px solid var(--vscode-button-border, transparent); + border-radius: 2px; + background: var(--vscode-button-secondaryBackground); + color: var(--vscode-button-secondaryForeground); + font: inherit; + cursor: pointer; +} + +.wv-fullsize-close:hover { + background: var(--vscode-button-secondaryHoverBackground); +} + +.wv-fullsize-body { + flex: 1; + overflow: auto; + display: flex; + align-items: safe center; + justify-content: safe center; + padding: 12px; +} + +/* Full size: the image's own size, scrolled when larger than the panel. */ +.wv-fullsize-body img { + max-width: none; + max-height: none; +} diff --git a/apps/vscode/tsconfig.json b/apps/vscode/tsconfig.json index fb29725e7..a21c01d49 100644 --- a/apps/vscode/tsconfig.json +++ b/apps/vscode/tsconfig.json @@ -8,5 +8,5 @@ "declarationMap": false, "types": ["node", "mocha"] }, - "exclude": ["node_modules", "out", "dist", "vitest.config.ts", "src/markdown-preview/webview", "src/contextual-panel/webview"] + "exclude": ["node_modules", "out", "dist", "vitest.config.ts", "src/markdown-preview/webview", "src/contextual-panel/webview", "src/workspace-views/webview"] } diff --git a/apps/vscode/tsconfig.webview.json b/apps/vscode/tsconfig.webview.json index ec415ad4a..d4d9cf259 100644 --- a/apps/vscode/tsconfig.webview.json +++ b/apps/vscode/tsconfig.webview.json @@ -10,7 +10,9 @@ "types": [], "noEmit": true, "declaration": false, - "declarationMap": false + "declarationMap": false, + // The Work and Decisions panels (Spec 1963) are TSX; the other webviews are .ts. + "jsx": "react-jsx" }, - "include": ["src/markdown-preview/webview", "src/contextual-panel/webview"] + "include": ["src/markdown-preview/webview", "src/contextual-panel/webview", "src/workspace-views/webview"] } diff --git a/apps/vscode/vitest.config.ts b/apps/vscode/vitest.config.ts index a16d5b8b7..357276b3c 100644 --- a/apps/vscode/vitest.config.ts +++ b/apps/vscode/vitest.config.ts @@ -11,8 +11,13 @@ import { defineConfig } from 'vitest/config'; * which is the vscode-test integration suite). */ export default defineConfig({ + // The webview TSX (Spec 1963) uses the automatic runtime, as `tsconfig.webview.json` and esbuild's + // bundle do. Vite reads the nearest tsconfig.json, the host's, which sets no `jsx`. + esbuild: { jsx: 'automatic' }, test: { environment: 'node', - include: ['src/__tests__/**/*.test.ts'], + // The webview tests (Spec 1963) are TSX, type-checked with the webview config, so they live + // beside the webview sources that the host tsconfig excludes. + include: ['src/__tests__/**/*.test.ts', 'src/workspace-views/webview/__tests__/**/*.test.{ts,tsx}'], }, }); diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 0894f37e3..3b4dd417f 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -770,3 +770,48 @@ host-side. Pass the Decisions view a stable host object (it keys image loads on compares the class string. - `one-copy.test.ts`'s `statSync` would throw on a dangling symlink: none exist under `apps/` or `packages/`. + +### Phase 7: decisions_panel, implementation (2026-11-24) + +The Decisions panel in VS Code: the shared `DecisionsView` in an editor-area webview, with every +Tower call made by the extension host. Built: +- **SDK** (`tower-client.ts`): `getDecisions`, `ruleDecision`, `getDecisionImage`. A refusal stays + structured as `{code, message}` and is never flattened. Image bytes come through a new + `requestBinary`, which sets no Content-Type on the GET. +- **Host** (`apps/vscode/src/workspace-views/`): + - `messages.ts`: the requestId contract and guards for untrusted webview messages; + - `security.ts`: realpath + `path.relative` containment, and an http(s)-only allowlist; + - `panel-template.ts`: nonce CSP with no `connect-src`; + - `decisions-bridge.ts`: maps each Tower outcome to the view's result; + - `availability.ts`; + - `decisions-panel.ts`: single instance, serializer, and the visibility relay. +- **Webview** (`webview/`): `WebviewDecisionsHost` (postMessage, never rejects, image abort), + `DecisionsApp` (`isActive` = the relayed visibility, full-size image overlay), and + `vscode-theme.css` mapping all 28 `--codev-wv-*` tokens. +- **Cockpit:** a "Decisions" leaf after the architects under every active workspace. This window's + entry runs `codev.openDecisions`; any other entry (another workspace, a worktree window, a + no-workspace window) navigates via Open Workspace. + +**Builder decisions / deviations (mine, not the architect's):** +- `@cluesmith/codev-workspace-views/host` is a new subpath export. Host-side code imports the view + types from it, because the package index pulls in TSX, which the host tsconfig (no `jsx`) would + then compile. +- The no-I/O rule for webview code: an ESLint `no-restricted-globals/properties` rule on + `src/workspace-views/webview/**`, plus `workspace-views-webview-source.test.ts`, which is what CI + runs. The shared package has no ESLint; its existing `import-boundary.test.ts` already bans + fetch, XHR, WebSocket, EventSource and sendBeacon there. +- The panel opens in `ViewColumn.Active`. +- The "no decisions file" empty state appends the `afx decisions init` hint host-side, as plain + text after Tower's message. +- Vitest compiles TSX with `esbuild: { jsx: 'automatic' }`. Vite reads the host tsconfig.json, + which sets no `jsx`. +- `decisions-webview-bundle.test.ts` builds the real bundle from `esbuild.webview.cjs` and boots + it in its own JSDOM window, from a node-environment test, because esbuild refuses to run inside + vitest's jsdom environment (TextEncoder realm check). +- The Windows workflow's unit job gained a step that runs `workspace-views-security.test.ts` on + Windows. Its directory links are junctions, which need no privilege; a `win32`-only describe + covers drive-letter case and separators on real paths. + +**Still to do in Phase 7:** the rendered harness check (scenarios 15, 16, 18), including whether +Uint8Array image bytes survive `webview.postMessage` in VS Code and in /ide/, and how the +high-contrast theme looks; then the Windows dispatch. diff --git a/packages/sdk/src/__tests__/tower-client.decisions.test.ts b/packages/sdk/src/__tests__/tower-client.decisions.test.ts new file mode 100644 index 000000000..fe4b71efa --- /dev/null +++ b/packages/sdk/src/__tests__/tower-client.decisions.test.ts @@ -0,0 +1,186 @@ +/** + * The decisions routes (Spec 1819, #1938) through the client (Spec 1963). The VS Code extension + * serves its Decisions panel through these, so the contract under test is that nothing the + * dashboard shows is lost on the way: a refusal keeps its `code` and `message` whatever its HTTP + * status, an image keeps its bytes and type, and "Tower answered with something else" stays + * distinct from "Tower was not reached". None of the three ever rejects. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { TowerClient } from '../tower-client.js'; +import { encodeWorkspacePath } from '../workspace.js'; + +interface Scripted { + status: number; + /** A JSON body; or `text` for a raw one; or `bytes` for a binary one. */ + body?: unknown; + text?: string; + bytes?: Uint8Array; + contentType?: string; +} + +/** A client whose transport answers with `response`, capturing what it sent. */ +function clientWith(response: Scripted | Error, key: string | null = 'secret-key') { + const calls: Array<{ url: string; init: RequestInit }> = []; + const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(url), init: init ?? {} }); + if (response instanceof Error) throw response; + const text = response.text ?? (response.body === undefined ? '' : JSON.stringify(response.body)); + const bytes = response.bytes ?? new TextEncoder().encode(text); + const headers = new Headers(); + if (response.contentType) headers.set('Content-Type', response.contentType); + return { + ok: response.status >= 200 && response.status < 300, + status: response.status, + headers, + text: async () => text, + json: async () => JSON.parse(text), + arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), + } as unknown as Response; + }); + const client = new TowerClient({ port: 4100, getAuthKey: () => key, fetchFn: fetchFn as unknown as typeof fetch }); + return { client, calls }; +} + +const WS = '/Users/me/project'; +const BASE = `http://localhost:4100/workspace/${encodeWorkspacePath(WS)}/api/decisions`; + +const DOCUMENT = { path: 'codev/decisions.md', version: 'v1', items: [], ruledMarkdown: '', problems: [] }; + +function refusedConnection(): Error { + return Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNREFUSED' } }); +} + +function headersOf(init: RequestInit): Record { + return init.headers as Record; +} + +describe('getDecisions', () => { + it("reads the workspace's decisions route with the key and returns the document", async () => { + const { client, calls } = clientWith({ status: 200, body: { ok: true, document: DOCUMENT } }); + + const result = await client.getDecisions(WS); + + expect(result).toEqual({ kind: 'verdict', status: 200, verdict: { ok: true, document: DOCUMENT } }); + expect(calls[0].url).toBe(BASE); + expect(headersOf(calls[0].init)['codev-tower-key']).toBe('secret-key'); + }); + + it('keeps the not-found refusal (no decisions file) with its code and message', async () => { + const refusal = { ok: false, code: 'not-found', message: 'There is no decisions file at codev/decisions.md.' }; + const { client } = clientWith({ status: 404, body: refusal }); + + expect(await client.getDecisions(WS)).toEqual({ kind: 'verdict', status: 404, verdict: refusal }); + }); + + it("is unreadable when the body is not a decisions body (a 401's plain text)", async () => { + const { client } = clientWith({ status: 401, text: 'Unauthorized' }); + + expect(await client.getDecisions(WS)).toEqual({ kind: 'unreadable', status: 401 }); + }); + + it('is unreadable when a success body lacks the document fields the view needs', async () => { + const { client } = clientWith({ status: 200, body: { ok: true, document: { path: 'x' } } }); + + expect(await client.getDecisions(WS)).toEqual({ kind: 'unreadable', status: 200 }); + }); + + it('is unreachable, not a verdict, when the connection is refused', async () => { + const { client } = clientWith(refusedConnection()); + + expect(await client.getDecisions(WS)).toEqual({ kind: 'unreachable', error: 'Tower not running' }); + }); + + it('is unreachable with the transport message for any other failure', async () => { + const { client } = clientWith(new Error('socket hang up')); + + expect(await client.getDecisions(WS)).toEqual({ kind: 'unreachable', error: 'socket hang up' }); + }); +}); + +describe('ruleDecision', () => { + const REQUEST = { id: 'D-1', fingerprint: 'abc', word: 'ship', comment: 'Looks right.' }; + + it('posts the ruling as JSON to the rule route and returns the re-parsed document', async () => { + const { client, calls } = clientWith({ status: 200, body: { ok: true, document: DOCUMENT } }); + + const result = await client.ruleDecision(WS, REQUEST); + + expect(result).toEqual({ kind: 'verdict', status: 200, verdict: { ok: true, document: DOCUMENT } }); + expect(calls[0].url).toBe(`${BASE}/rule`); + expect(calls[0].init.method).toBe('POST'); + expect(JSON.parse(calls[0].init.body as string)).toEqual(REQUEST); + expect(headersOf(calls[0].init)['Content-Type']).toBe('application/json'); + expect(headersOf(calls[0].init)['codev-tower-key']).toBe('secret-key'); + }); + + it.each([ + [409, 'item-changed', 'D-1 changed since you opened it; nothing was written.'], + [400, 'comment-heading', 'A comment cannot contain a heading.'], + [500, 'write-failed', 'codev/decisions.md could not be written; the file is unchanged.'], + ])('keeps a %i refusal (%s) with its code and message', async (status, code, message) => { + const { client } = clientWith({ status, body: { ok: false, code, message } }); + + expect(await client.ruleDecision(WS, REQUEST)).toEqual({ kind: 'verdict', status, verdict: { ok: false, code, message } }); + }); + + it('is unreachable when Tower is down', async () => { + const { client } = clientWith(refusedConnection()); + + expect(await client.ruleDecision(WS, REQUEST)).toEqual({ kind: 'unreachable', error: 'Tower not running' }); + }); +}); + +describe('getDecisionImage', () => { + const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff]); + + it('returns the bytes and type unchanged, asking for the path as written, with the key', async () => { + const { client, calls } = clientWith({ status: 200, bytes: PNG, contentType: 'image/png' }); + + const result = await client.getDecisionImage(WS, '../shots/my shot.png'); + + expect(result).toEqual({ kind: 'image', bytes: PNG, contentType: 'image/png' }); + expect(calls[0].url).toBe(`${BASE}/image?path=${encodeURIComponent('../shots/my shot.png')}`); + expect(headersOf(calls[0].init)['codev-tower-key']).toBe('secret-key'); + // A GET of bytes: no JSON content type is forced on it. + expect(headersOf(calls[0].init)['Content-Type']).toBeUndefined(); + }); + + it('sends no key header when there is no key', async () => { + const { client, calls } = clientWith({ status: 200, bytes: PNG, contentType: 'image/png' }, null); + + await client.getDecisionImage(WS, 'a.png'); + + expect(headersOf(calls[0].init)['codev-tower-key']).toBeUndefined(); + }); + + it('is unreadable when a 2xx answer is not an image', async () => { + const { client } = clientWith({ status: 200, text: '', contentType: 'text/html' }); + + expect(await client.getDecisionImage(WS, 'a.png')).toEqual({ kind: 'unreadable', status: 200 }); + }); + + it.each([ + [404, 'not-found', 'There is no image at a.png.'], + [400, 'outside-workspace', 'The image ../../etc/x.png is outside the workspace, so it was not read.'], + [413, 'image-too-large', 'The image a.png is 20000000 bytes, over the 10485760-byte limit, so it was not read.'], + [415, 'not-an-image', 'a.txt is not a png, jpg, jpeg, gif, webp, svg image, so it was not read.'], + ])('keeps a %i refusal (%s) with its code and message', async (status, code, message) => { + const { client } = clientWith({ status, body: { ok: false, code, message }, contentType: 'application/json' }); + + expect(await client.getDecisionImage(WS, 'a.png')).toEqual({ kind: 'verdict', status, verdict: { ok: false, code, message } }); + }); + + it('is unreadable when a refusal body is not a decisions refusal', async () => { + const { client } = clientWith({ status: 401, text: 'Unauthorized' }); + + expect(await client.getDecisionImage(WS, 'a.png')).toEqual({ kind: 'unreadable', status: 401 }); + }); + + it('is unreachable when the connection is refused, and when the request times out', async () => { + expect(await clientWith(refusedConnection()).client.getDecisionImage(WS, 'a.png')) + .toEqual({ kind: 'unreachable', error: 'Tower not running' }); + expect(await clientWith(new Error('The operation was aborted due to timeout')).client.getDecisionImage(WS, 'a.png')) + .toEqual({ kind: 'unreachable', error: 'Request timeout' }); + }); +}); diff --git a/packages/sdk/src/tower-client.ts b/packages/sdk/src/tower-client.ts index fa93b9ecb..7a35352a1 100644 --- a/packages/sdk/src/tower-client.ts +++ b/packages/sdk/src/tower-client.ts @@ -13,7 +13,7 @@ * the read-only reader for standalone Node controllers). */ -import type { DashboardState, OverviewData, IssueView, PRView, IssueSearchResponse, ResolvedWorktreeConfig, ResolvedActivityHooks, TowerVersionInfo, CommandRequest, CanvasCommand, CanvasCommandRequest, CanvasCommandResult, CanvasCommandClientResult, CanvasCommandErrorCode } from '@cluesmith/codev-types'; +import type { DashboardState, OverviewData, IssueView, PRView, IssueSearchResponse, ResolvedWorktreeConfig, ResolvedActivityHooks, TowerVersionInfo, CommandRequest, CanvasCommand, CanvasCommandRequest, CanvasCommandResult, CanvasCommandClientResult, CanvasCommandErrorCode, DecisionsDocument, DecisionsReadResponse, DecisionsRefusalCode, DecisionsRuleRequest, DecisionsRuleResponse } from '@cluesmith/codev-types'; import { DEFAULT_TOWER_PORT } from './constants.js'; import { parseSseText, type SseEnvelope } from './sse.js'; @@ -247,6 +247,62 @@ export interface TowerTerminal { // ── Client Options ───────────────────────────────────────────── +/** + * The answer of a decisions route (Spec 1819), or why there was none. Never thrown: + * - `verdict`: Tower answered with a decisions body, a document or a refusal with its `code` and + * `message`, whatever the HTTP status; + * - `unreachable`: no answer at all (Tower down, a timeout, a reset); + * - `unreadable`: an answer that is not a decisions body, such as a 401's plain text. + */ +export type DecisionsRouteResult = + | { kind: 'verdict'; status: number; verdict: T } + | { kind: 'unreachable'; error: string } + | { kind: 'unreadable'; status: number }; + +/** A decisions route's refusal: its machine `code` and the message the owner reads. */ +export interface DecisionsRefusal { + ok: false; + code: DecisionsRefusalCode; + message: string; +} + +/** + * The answer of the decisions image route (#1938): the image's bytes and type, Tower's refusal, + * or why there was none (as in {@link DecisionsRouteResult}). Never thrown. + */ +export type DecisionImageRouteResult = + | { kind: 'image'; bytes: Uint8Array; contentType: string } + | { kind: 'verdict'; status: number; verdict: DecisionsRefusal } + | { kind: 'unreachable'; error: string } + | { kind: 'unreadable'; status: number }; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +/** A decisions refusal body, or null. */ +function asDecisionsRefusal(body: unknown): DecisionsRefusal | null { + if (isRecord(body) && body.ok === false && typeof body.code === 'string' && typeof body.message === 'string') { + return { ok: false, code: body.code as DecisionsRefusalCode, message: body.message }; + } + return null; +} + +/** + * A decisions document or refusal body, checked as far as the dashboard checks it (the document's + * `version` and `items`), or null. + */ +function asDecisionsVerdict(body: unknown): DecisionsReadResponse | null { + if (isRecord(body) && body.ok === true) { + const doc = body['document']; + if (isRecord(doc) && typeof doc.version === 'string' && Array.isArray(doc.items)) { + return { ok: true, document: doc as unknown as DecisionsDocument }; + } + return null; + } + return asDecisionsRefusal(body); +} + export interface TowerClientOptions { port?: number; host?: string; @@ -1056,6 +1112,94 @@ export class TowerClient { } } + /** + * Like `requestPreservingBody`, for a route that answers with bytes (an image). That helper + * reads the body as text, which would destroy binary bytes and drop the `Content-Type`. Same key + * header, base URL and timeout as every other request. A 2xx comes back as its bytes and type; any + * other status as its JSON-parsed body (null when it is not JSON), so a refusal keeps its code and + * message. Never throws: a transport failure comes back as `status: 0`. + */ + private async requestBinary( + path: string, + ): Promise<{ status: number; bytes: Uint8Array; contentType: string } | { status: number; body: unknown; error?: string }> { + try { + const authKey = this.getAuthKey(); + const headers: Record = {}; + if (authKey) { + headers['codev-tower-key'] = authKey; + } + const response = await this.fetchFn(`${this.baseUrl}${path}`, { + headers, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + if (response.ok) { + const bytes = new Uint8Array(await response.arrayBuffer()); + return { status: response.status, bytes, contentType: response.headers.get('Content-Type') ?? '' }; + } + const text = await response.text(); + let body: unknown = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; // an unparseable body is reported by the caller as an unusable answer + } + return { status: response.status, body }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (isConnectionRefused(err)) return { status: 0, body: null, error: 'Tower not running' }; + if (message.includes('timeout')) return { status: 0, body: null, error: 'Request timeout' }; + return { status: 0, body: null, error: message }; + } + } + + /** One decisions document route's answer, as a {@link DecisionsRouteResult}. */ + private async requestDecisions(path: string, options: RequestInit = {}): Promise> { + const outcome = await this.requestPreservingBody(path, options); + if (outcome.status === 0) return { kind: 'unreachable', error: outcome.error ?? 'Tower unreachable' }; + const verdict = asDecisionsVerdict(outcome.body); + if (!verdict) return { kind: 'unreadable', status: outcome.status }; + return { kind: 'verdict', status: outcome.status, verdict }; + } + + /** + * GET /workspace//api/decisions: the workspace's decisions document, or Tower's refusal + * (`not-found` when there is no decisions file) with its code and message (Spec 1819). + */ + async getDecisions(workspacePath: string): Promise> { + return this.requestDecisions(`/workspace/${encodeWorkspacePath(workspacePath)}/api/decisions`); + } + + /** + * POST /workspace//api/decisions/rule: write the owner's ruling into the decisions file. + * Success carries the document re-parsed from the bytes written; a refusal keeps its code and + * message (Spec 1819). Tower then tells the hub architect (#1828). + */ + async ruleDecision(workspacePath: string, request: DecisionsRuleRequest): Promise> { + return this.requestDecisions(`/workspace/${encodeWorkspacePath(workspacePath)}/api/decisions/rule`, { + method: 'POST', + body: JSON.stringify(request), + }); + } + + /** + * GET /workspace//api/decisions/image?path=: one image a decisions item references (#1938), + * as bytes and type. `imagePath` is as written in the item: relative to the decisions file, or + * `/`-rooted at the workspace. Tower contains it to the workspace; a refusal keeps its code and + * message. A 2xx answer that is not an image is `unreadable`. + */ + async getDecisionImage(workspacePath: string, imagePath: string): Promise { + const encoded = encodeWorkspacePath(workspacePath); + const outcome = await this.requestBinary(`/workspace/${encoded}/api/decisions/image?path=${encodeURIComponent(imagePath)}`); + if ('bytes' in outcome) { + if (!outcome.contentType.toLowerCase().startsWith('image/')) return { kind: 'unreadable', status: outcome.status }; + return { kind: 'image', bytes: outcome.bytes, contentType: outcome.contentType }; + } + if (outcome.status === 0) return { kind: 'unreachable', error: outcome.error ?? 'Tower unreachable' }; + const refusal = asDecisionsRefusal(outcome.body); + if (!refusal) return { kind: 'unreadable', status: outcome.status }; + return { kind: 'verdict', status: outcome.status, verdict: refusal }; + } + /** * POST /api/canvas/command: drive one open artifact-canvas view (spec 1401). * diff --git a/packages/workspace-views/package.json b/packages/workspace-views/package.json index c3ea03be8..c2f2a1b1a 100644 --- a/packages/workspace-views/package.json +++ b/packages/workspace-views/package.json @@ -6,6 +6,7 @@ "type": "module", "exports": { ".": "./src/index.ts", + "./host": "./src/host.ts", "./styles.css": "./src/styles.css" }, "scripts": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 43dbde0a7..de207d7e1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -50,6 +50,9 @@ importers: '@cluesmith/codev-types': specifier: workspace:* version: link:../../packages/types + '@cluesmith/codev-workspace-views': + specifier: workspace:* + version: link:../../packages/workspace-views react: specifier: ^19.0.0 version: 19.2.5 @@ -60,6 +63,9 @@ importers: specifier: ^8.18.0 version: 8.20.0 devDependencies: + '@testing-library/react': + specifier: ^16.0.0 + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) '@types/mocha': specifier: ^10.0.10 version: 10.0.10 @@ -93,6 +99,9 @@ importers: eslint: specifier: ^9.39.1 version: 9.39.4 + jsdom: + specifier: ^26.0.0 + version: 26.1.0 typescript: specifier: 'catalog:' version: 6.0.3 @@ -101,7 +110,7 @@ importers: version: 8.58.2(eslint@9.39.4)(typescript@6.0.3) vitest: specifier: ^4.0.15 - version: 4.1.4(@types/node@22.19.17)(@vitest/coverage-v8@4.1.4)(jsdom@28.1.0)(vite@6.4.2(@types/node@22.19.17)(tsx@4.21.0)) + version: 4.1.4(@types/node@22.19.17)(@vitest/coverage-v8@4.1.4)(jsdom@26.1.0)(vite@6.4.2(@types/node@22.19.17)(tsx@4.21.0)) apps/web: dependencies: From 55b29443370c187cda4386d5bed107275488d340 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:30:28 -0800 Subject: [PATCH 079/140] [Spec 1963][Phase: decisions_panel] fix: reload restore and high-contrast accent; rendered verification Rendered verification in the isolated harness (new `verify decisions` script, 15/15 on this build; evidence in verification-phase7/): scenarios 15, 16, 18, 19 (Decisions), 21 (hidden-panel polling) and 22. It found two bugs, fixed here: - Reload restore closed the panel: availability read the connection manager's workspace, which is null until its async initialize(), and a restore reaches the serializer first. It now reads the window's folders (detectWorkspacePath()), as the CLI preflight does. - High contrast hid accent text: the accent was VS Code's button background, black in HC Dark, and the accent is also text on the page. Accent is now the link colour, with the editor background drawn on accent fills (contrast is symmetric). The harness measures WCAG contrast of an item id and of Submit's text in four themes (6.3 to 9). Adjacent: .vscodeignore drops **/tsconfig.*.json (the vsix shipped tsconfig.webview.json). --- apps/vscode/.vscodeignore | 1 + apps/vscode/scripts/cockpit-harness/README.md | 1 + .../cockpit-harness/cockpit-verify.mjs | 397 ++++++++++++++++++ .../src/__tests__/contributes-cockpit.test.ts | 8 + .../__tests__/workspace-views-theme.test.ts | 11 + apps/vscode/src/extension.ts | 5 +- .../workspace-views/webview/vscode-theme.css | 14 +- codev/state/spir-1963_thread.md | 60 ++- 8 files changed, 489 insertions(+), 8 deletions(-) diff --git a/apps/vscode/.vscodeignore b/apps/vscode/.vscodeignore index 33da2ab1a..e6e1799f7 100644 --- a/apps/vscode/.vscodeignore +++ b/apps/vscode/.vscodeignore @@ -9,6 +9,7 @@ esbuild.js esbuild.webview.cjs vsc-extension-quickstart.md **/tsconfig.json +**/tsconfig.*.json **/eslint.config.mjs **/*.map **/*.ts diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index 4d034712d..c6a36f02d 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -160,6 +160,7 @@ state, so run them in this order, once per `start`: | `requests` | Spec scenario 21. Tower request counts in three layouts: the Cockpit alone; the Workspace, Agents and Tower views alone; and both at once (the Cockpit moved to the panel with *View: Move View*, undone with *Reset View Locations*). Each layout asserts what the side bar, secondary side bar and panel show before measuring. Each counts a 60 s idle window plus a 15 s burst (`#103`'s gate and a `codev-config-updated`), started 2 s after a fleet poll tick so no poll tick lands in it. Each runs in a freshly restarted VS Code server (`vscode-restart`), because VS Code keeps a closed window's extension host alive for its reconnection grace period, and those hosts would keep polling the Tower. It fails if the Cockpit alone makes anything the source views do not, if fleet or overview counts differ across layouts, if `getWorktreeConfig` runs while idle, if both at once add anything but `getWorktreeConfig`, or if a window opens more than one event stream | | `actions` | Every builder context action, Approve Gate inline (it relays to the spawning architect through `/api/send`, #1494, so the check asserts that and no porch call), every workspace-row action (Spawn Builder's `afx spawn` checked in the stub log, with its cwd), and Remove Architect: offered on siblings only. A childless sibling, added through Tower, loses its row. A sibling that spawned a builder keeps its header as that builder's owner, as in Agents. Other workspaces' rows navigate; their workspace rows keep Open and Deactivate. It sets #102's and #103's gates back to unrequested first, because `windows` and `requests` request them | | `dashboard` | Spec scenario 20, on **its own** `start` + `seed fleet` (it rules `main-1` and opens a shell in `alpha`). The browser dashboard the isolated Tower serves for `alpha`, in headless Chromium, not VS Code. It refreshes the overview first, because Tower caches the forge failure from the extension's activation before the seed. Five checks: Work renders every section with rows; Decisions renders both cards and loads the image as a blob; a link and a full-size image open in a new tab (the link's URL, the image's blob page); a ruling round-trips to the file; and Work's actions (Open, + Shell, an artifact link, an issue link, Refresh) do what they did. It writes `shots/dashboard-snapshot.json`: every element under the two views, with its classes, its own text (ages masked) and its computed colour, type and box. With `COCKPIT_BASELINE=` it adds a sixth check that fails on any difference from that snapshot. To compare a change against its base, run once on the base's build, keep the snapshot, then run again on the change's build with `COCKPIT_BASELINE` pointing at it | +| `decisions` | Spec scenarios 15, 16, 18, 19 (Decisions part), 21 (hidden-panel polling) and 22, Phase 7. On **its own** `start` + `seed fleet`: it adds `main-2` to alpha's file (an https image, answered by the browser's route for `example.com`, and an image outside the workspace), rules `main-1`, edits `main-2` under the panel, and creates gamma's file. It checks: a **Decisions** entry under every active workspace and none under the dormant one; another workspace's entry opens that window; this workspace's opens one panel with the items; the workspace image renders from an object URL (bytes through the host), the https image renders, the outside image shows why it was not loaded; the full-size view opens and closes; a link opens through the host; a ruling writes the file, shows on the card and reaches `main` (Tower's `Decisions notice` log line); a stale fingerprint is refused with the draft kept; no reads while the panel is hidden; four themes switched live without reloading the webview; the panel restored after a reload; the explanations in a builder-worktree and a no-workspace window; gamma's empty state, then the real `afx decisions init` (it only writes the template), then an item appears; and a request audit: no browser request to the Tower port or carrying the key, and webview frames load only VS Code's webview host page, extension resources, blobs and the remote item image | | `reconnect` | **Run last.** A loaded Cockpit keeps its content with Tower down; a fresh window shows *Not connected to Tower*; Tower up + the row's Reconnect restores it. Stops and restarts only the isolated Tower, by PID (`tower-down` / `tower-up`) | A restarted Tower does not reconnect the fixture sessions: its startup reconciliation skips, and diff --git a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs index 19af00ae1..ea76a1900 100644 --- a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs +++ b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs @@ -15,6 +15,9 @@ // requests request count: Cockpit alone vs Workspace + Agents + Tower alone (scenario 21) // dashboard the browser dashboard's Work and Decisions tabs render, act and rule as before // (scenario 20); with --baseline, styles and DOM identical to a run on main's build +// decisions the VS Code Decisions panel (Phase 7): the hierarchy's entries, images, full size, +// a link, a ruling and its notice, a stale refusal, hidden-panel polling, themes, +// reload restore, the unavailable windows, empty state → init, network audit // // Every result is recorded in --out as { script, results: [{ name, ok, detail, shots }] }. Any // browser request to the owner's port fails the run. @@ -1525,6 +1528,400 @@ SCRIPTS.dashboard = async (R, context, page) => { } }; +// ── decisions (Phase 7) ────────────────────────────────────────────────────────────────────── + +const DECISIONS_PATH = 'codev/state/pending-decisions.md'; +const REMOTE_IMAGE = 'https://example.com/fixture/remote-board.svg'; +const REMOTE_SVG = ''; +const OUTSIDE_SVG = ''; + +/** + * `main-2`, added to alpha's file by this script: an https image, which the webview loads itself, + * and an image outside the workspace, which Tower refuses. It is also the item the stale-fingerprint + * check edits under the panel. + */ +const MAIN_2 = `### main-2 · 2026-11-21 10:00 UTC · Which board image should the fixture keep? + +- **Context:** an image from the web, and one from outside the workspace. + +![Remote board](${REMOTE_IMAGE}) + +![Outside image](../../../outside.svg) + +**Your word:** \`remote\` / \`local\` + +`; + +/** An item for gamma's new file, added the way the hub adds one. */ +const GAMMA_1 = `### main-1 · 2026-11-24 12:00 UTC · Adopt the Decisions panel in gamma? + +- **Context:** added by the hub after \`afx decisions init\`. + +**Your word:** \`adopt\` / \`wait\` + +`; + +/** Add `item` at the top of a decisions file's Open section, and set its status line. */ +function addOpenItem(file, item, status) { + const text = fs.readFileSync(file, 'utf-8'); + if (!text.includes('## Open\n\n')) throw new Error(`${file} has no "## Open" section`); + fs.writeFileSync(file, text.replace('## Open\n\n', `## Open\n\n${item}`).replace(/^_Status: .*_$/m, `_Status: ${status}_`)); +} + +/** The Decisions panel's document: VS Code nests a webview's page two iframes down. */ +async function decisionsFrame(page, timeout = 60_000) { + return waitFor('the Decisions webview', async () => { + for (const frame of page.frames()) { + if (frame === page.mainFrame()) continue; + if (await frame.locator('.decisions-view').count().catch(() => 0)) return frame; + } + return null; + }, timeout); +} + +const decisionCard = (frame, id) => frame.locator('.decisions-card', { has: frame.locator('.decisions-item-id', { hasText: new RegExp(`^${escapeRe(id)}$`) }) }); + +/** GETs of a decisions document the Tower received after request-log line `from`. */ +const decisionsReads = (R, from) => R.towerRequests().slice(from) + .filter((r) => r.method === 'GET' && (r.url ?? '').split('?')[0].endsWith('/api/decisions')); + +/** The isolated Tower's notices to a hub architect, from its log. */ +function rulingNotices(R) { + const log = path.join(path.dirname(R.opts['request-log']), 'tower.log'); + if (!fs.existsSync(log)) return []; + return fs.readFileSync(log, 'utf-8').split('\n').filter((l) => /Decisions notice .* → main @ /.test(l)); +} + +const hexToRgb = (hex) => { + const h = hex.replace('#', ''); + const n = (i) => parseInt(h.slice(i, i + 2), 16); + return h.length >= 6 ? `rgb(${n(0)}, ${n(2)}, ${n(4)})` : hex; +}; + +SCRIPTS.decisions = async (R, context, page) => { + const alphaFile = path.join(R.opts.fixtures, 'alpha', DECISIONS_PATH); + addOpenItem(alphaFile, MAIN_2, '3 open — main-2, main-1, web-1.'); + fs.writeFileSync(path.join(R.opts.fixtures, 'outside.svg'), OUTSIDE_SVG); + // Item links and the remote image point at example.com: answer them here, so nothing leaves the machine. + await context.route(/^https?:\/\/example\.com\//, (route) => (route.request().url() === REMOTE_IMAGE + ? route.fulfill({ status: 200, contentType: 'image/svg+xml', body: REMOTE_SVG }) + : route.fulfill({ status: 200, contentType: 'text/html', body: '

fixture link

' }))); + + // Every request the browser makes, with the frame that made it, for scenario 22. + const requests = []; + context.on('request', (r) => { + let frame = 'other'; + try { + const f = r.frame(); + frame = f === f.page().mainFrame() ? 'main' : f.url(); + } catch { /* a service worker's request, or a popup's first navigation */ } + requests.push({ url: r.url(), frame, key: Object.keys(r.headers()).some((h) => h.toLowerCase() === 'codev-tower-key') }); + }); + + let cockpit; + let frame; + const DRAFT = 'Draft that must survive a refusal.'; + + await R.check('scenario 12: a Decisions entry under every active workspace, none under the dormant one', async () => { + await loadWorkbench(page, R.folderUrl('alpha')); + cockpit = await openCockpit(page); + await waitRow(cockpit, A_MAIN, 60_000); + const got = {}; + for (const [name, spec] of [['alpha', ALPHA], ['beta', BETA], ['gamma', GAMMA]]) { + await setExpanded(cockpit, spec, true); + const t = await subtree(cockpit, spec); + got[name] = t.rows.filter((r) => r.level === t.head.level + 1).map((r) => r.text); + } + await setExpanded(cockpit, ['Tower', /^Dormant \(1\)$/], true); + const dormant = await subtree(cockpit, ['Tower', /^Dormant \(1\)$/]); + const problems = []; + for (const [name, children] of Object.entries(got)) { + if (children.at(-1) !== 'Decisions') problems.push(`${name}'s last child is "${children.at(-1)}"`); + if (children.filter((c) => c === 'Decisions').length !== 1) problems.push(`${name} has ${children.filter((c) => c === 'Decisions').length} Decisions entries`); + } + const delta = dormant.rows.find((r) => r.text === 'delta'); + if (!delta || delta.expanded !== null) problems.push('the dormant delta row is missing or expandable'); + if (problems.length) throw new Error(`${problems.join('; ')} — ${JSON.stringify(got)}`); + return { detail: `${JSON.stringify(got)}; Dormant: delta, a leaf (beta and gamma have no decisions file)`, shots: [await R.shot(page, 'entries')] }; + }); + + await R.check("scenario 12: another workspace's Decisions entry opens that workspace's window", async () => { + const entry = await waitRow(cockpit, [...BETA, 'Decisions']); + const url = await nextPopup(R, context, () => entry.loc.click()); + if (!decodeURIComponent(new URL(url).searchParams.get('folder') ?? '').endsWith('/beta')) throw new Error(`opened ${url}`); + return `beta's entry → ${url}`; + }); + + await R.check("scenario 12: this workspace's Decisions entry opens the panel, which renders the items", async () => { + const entry = await waitRow(cockpit, [...ALPHA, 'Decisions']); + await entry.loc.click(); + await waitFor('the Decisions editor tab', async () => /^Decisions/.test(await activeEditorTab(page) ?? ''), 20_000); + frame = await decisionsFrame(page); + await waitFor('three decision cards', async () => (await frame.locator('.decisions-card').count()) === 3, 30_000); + const problems = []; + const count = (await frame.locator('.decisions-count').textContent())?.trim(); + if (count !== '3 open') problems.push(`the count reads "${count}"`); + const words = await decisionCard(frame, 'main-1').locator('input[type="radio"]').evaluateAll((els) => els.map((e) => e.value)); + if (JSON.stringify(words) !== JSON.stringify(['compact', 'stacked', 'hold'])) problems.push(`main-1 offers ${JSON.stringify(words)}`); + if (!/Written under this item/.test(await decisionCard(frame, 'web-1').textContent())) problems.push('web-1 does not show its written ruling'); + // Clicking the entry again reveals the same panel: still one Decisions tab. + await entry.loc.click(); + await page.waitForTimeout(1000); + const tabs = (await editorTabs(page)).filter((t) => /^Decisions/.test(t ?? '')); + if (tabs.length !== 1) problems.push(`${tabs.length} Decisions tabs after a second click`); + if (problems.length) throw new Error(problems.join('; ')); + return { detail: `tab "${await activeEditorTab(page)}"; ${count}; main-1 offers ${words.join(' / ')}; one tab after a second click`, shots: [await R.shot(page, 'panel')] }; + }); + + await R.check('scenario 15: a workspace image (bytes through the host), an https image, and a refused image', async () => { + const local = decisionCard(frame, 'main-1').locator('img[alt="Compact board"]'); + const remote = decisionCard(frame, 'main-2').locator('img[alt="Remote board"]'); + const loaded = (img) => img.evaluate((el) => el.complete && el.naturalWidth > 0).catch(() => false); + await waitFor('the workspace image to render from an object URL', async () => (await local.getAttribute('src'))?.startsWith('blob:') && loaded(local), 20_000); + await waitFor('the https image to render', async () => (await remote.getAttribute('src')) === REMOTE_IMAGE && loaded(remote), 20_000); + const missing = decisionCard(frame, 'main-2').locator('.decisions-image-missing'); + await waitFor('the refused image\'s note', async () => (await missing.count()) === 1, 20_000); + const note = (await missing.textContent()).replace(/\s+/g, ' ').trim(); + const reason = await missing.getAttribute('title'); + if (!/Image not loaded/.test(note) || !/outside\.svg/.test(note)) throw new Error(`the note reads "${note}"`); + if (!/outside/i.test(reason ?? '')) throw new Error(`the reason is "${reason}"`); + const size = await local.evaluate((el) => `${el.naturalWidth}×${el.naturalHeight}`); + return { detail: `workspace SVG ${size} from blob:; https image loaded; refused: "${note}" (${reason})`, shots: [await R.shot(page, 'images')] }; + }); + + await R.check('scenario 15: the full-size view opens over the panel; Escape and Close each close it', async () => { + const local = decisionCard(frame, 'main-1').locator('img[alt="Compact board"]'); + const overlay = frame.locator('.wv-fullsize[role="dialog"]'); + await local.click(); + await overlay.waitFor({ timeout: 10_000 }); + const src = await overlay.locator('img').getAttribute('src'); + if (src !== await local.getAttribute('src')) throw new Error(`the full-size image is ${src}`); + const shot = await R.shot(page, 'full-size'); + await page.keyboard.press('Escape'); + await waitFor('Escape to close the full-size view', async () => (await overlay.count()) === 0, 5000); + await local.click(); + await overlay.waitFor({ timeout: 10_000 }); + await overlay.locator('button', { hasText: 'Close' }).click(); + await waitFor('Close to close the full-size view', async () => (await overlay.count()) === 0, 5000); + return { detail: `opened on ${src.slice(0, 5)}…; Escape closed it; Close closed it`, shots: [shot] }; + }); + + await R.check('scenario 15: an http(s) link opens in the browser, through the extension host', async () => { + const link = decisionCard(frame, 'main-1').locator('a', { hasText: 'https://example.com/fixture/main-1' }); + let asked = null; + const url = await nextPopup(R, context, async () => { + await link.click(); + // VS Code asks before opening a domain it does not trust yet. + if (await page.locator('.monaco-dialog-box').waitFor({ timeout: 5000 }).then(() => true, () => false)) asked = await dialogButton(page, 'Open'); + }); + if (url !== 'https://example.com/fixture/main-1') throw new Error(`opened ${url}`); + return `→ ${url}${asked ? ` (after VS Code's prompt: "${asked.slice(0, 80)}")` : ''}`; + }); + + await R.check('scenario 15: rule an item — the file is updated, the card shows the ruling, the architect is notified', async () => { + const main1 = decisionCard(frame, 'main-1'); + const noticesBefore = rulingNotices(R).length; + await main1.locator('input[type="radio"][value="stacked"]').check(); + await main1.locator('textarea.decisions-comment').fill('Fixture comment from the VS Code panel.'); + const formShot = await R.shot(page, 'draft'); + await main1.locator('button.decisions-submit-btn').click(); + await waitFor('main-1 to show the written ruling', async () => /Written under this item/.test(await main1.textContent()), 20_000); + const shown = (await main1.locator('.decisions-ruling-text').textContent()) ?? ''; + const want = 'stacked\n\nFixture comment from the VS Code panel.'; + if (shown !== want) throw new Error(`the card shows ${JSON.stringify(shown)}`); + const file = fs.readFileSync(alphaFile, 'utf-8'); + if (!file.includes(`**Your word:** \`compact\` / \`stacked\` / \`hold\`\n${want}\n`)) throw new Error('the file does not hold the ruling under main-1'); + const notice = await waitFor('Tower\'s notice to main', async () => rulingNotices(R).slice(noticesBefore)[0] ?? null, 20_000); + return { detail: `file updated; card shows it; Tower: ${notice.replace(/^\[[^\]]*\] \[INFO\] /, '')}`, shots: [formShot, await R.shot(page, 'ruled')] }; + }); + + await R.check('scenario 15: a stale fingerprint is refused, and the draft is kept', async () => { + const main2 = decisionCard(frame, 'main-2'); + await main2.locator('input[type="radio"][value="local"]').check(); + await main2.locator('textarea.decisions-comment').fill(DRAFT); + const submit = main2.locator('button.decisions-submit-btn'); + await submit.hover(); + // Edit main-2 just after a poll, so Submit lands before the next one can read the edit. + const from = R.towerRequests().length; + await waitFor('a Decisions poll', async () => decisionsReads(R, from).length > 0, 10_000, 50); + fs.writeFileSync(alphaFile, fs.readFileSync(alphaFile, 'utf-8').replace('one from outside the workspace.', 'one from outside the workspace (edited under the panel).')); + await submit.click(); + const alert = main2.locator('[role="alert"]'); + await waitFor('the refusal on main-2', async () => (await alert.count()) === 1, 10_000); + const message = (await alert.textContent()).trim(); + const draft = await main2.locator('textarea.decisions-comment').inputValue(); + const word = await main2.locator('input[type="radio"]:checked').getAttribute('value'); + const problems = []; + if (!/changed/i.test(message)) problems.push(`the refusal reads "${message}"`); + if (draft !== DRAFT) problems.push(`the comment box holds ${JSON.stringify(draft)}`); + if (word !== 'local') problems.push(`the chosen word is ${word}`); + const section = fs.readFileSync(alphaFile, 'utf-8').split('### main-2')[1]?.split('### main-1')[0] ?? ''; + if (!section.endsWith('**Your word:** `remote` / `local`\n\n')) problems.push(`main-2's section now ends ${JSON.stringify(section.slice(-60))}`); + if (problems.length) throw new Error(problems.join('; ')); + return { detail: `"${message}"; draft and word kept`, shots: [await R.shot(page, 'stale-refused')] }; + }); + + await R.check('scenario 21: the Decisions poll stops while its panel is hidden, and resumes when shown', async () => { + const t0 = R.towerRequests().length; + await page.waitForTimeout(6000); + const shown = decisionsReads(R, t0).length; + await runCommand(page, 'File: New Untitled Text File'); + await waitFor('the untitled editor in front', async () => /^Untitled/.test(await activeEditorTab(page) ?? ''), 10_000); + await page.waitForTimeout(1000); + const t1 = R.towerRequests().length; + await page.waitForTimeout(8000); + const hidden = decisionsReads(R, t1).length; + await runCommand(page, 'View: Close Editor'); + await waitFor('the Decisions editor in front again', async () => /^Decisions/.test(await activeEditorTab(page) ?? ''), 10_000); + const t2 = R.towerRequests().length; + await waitFor('a read once shown again', async () => decisionsReads(R, t2).length > 0, 6000); + if (shown < 2 || hidden !== 0) throw new Error(`reads: ${shown} in 6 s shown, ${hidden} in 8 s hidden`); + const kept = await decisionCard(frame, 'main-2').locator('textarea.decisions-comment').inputValue(); + if (kept !== DRAFT) throw new Error(`the draft did not survive hiding: ${JSON.stringify(kept)}`); + return `${shown} reads in 6 s shown; ${hidden} in 8 s hidden; reading again once shown; draft kept (retained context)`; + }); + + await R.check('scenario 18: light, dark and high-contrast themes, switched live with the panel open', async () => { + await frame.evaluate(() => { window.__codevMarker = 'kept'; }); + const shots = []; + const seen = {}; + const themes = [['Dark Modern', 'vs-dark'], ['Dark High Contrast', 'hc-black'], ['Light High Contrast', 'hc-light'], ['Light Modern', 'vs']]; + for (const [theme, cls] of themes) { + await setTheme(page, theme); + const applied = await page.locator('.monaco-workbench').evaluate((el, c) => el.classList.contains(c), cls); + if (!applied) throw new Error(`the workbench is not ${cls} after choosing ${theme}`); + await page.waitForTimeout(800); + seen[theme] = await frame.evaluate(() => { + const root = getComputedStyle(document.documentElement); + const card = document.querySelector('.decisions-card'); + // WCAG contrast of two computed rgb() colours. + const lum = (c) => { + const [r, g, b] = c.match(/[\d.]+/g).slice(0, 3).map(Number).map((v) => v / 255) + .map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + }; + const contrast = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((m, n) => n - m); return Math.round(((x + 0.05) / (y + 0.05)) * 10) / 10; }; + const page = getComputedStyle(document.body).backgroundColor; + const id = document.querySelector('.decisions-item-id'); + const submit = [...document.querySelectorAll('.decisions-submit-btn')].find((b) => !b.disabled); + return { + marker: window.__codevMarker ?? null, + body: page, + text: getComputedStyle(document.body).color, + editorBg: root.getPropertyValue('--vscode-editor-background').trim(), + card: card ? getComputedStyle(card).borderTopColor : null, + accent: root.getPropertyValue('--codev-wv-accent').trim(), + // Text drawn in the accent on the page, and on an accent-filled button. + idContrast: id ? contrast(getComputedStyle(id).color, page) : null, + submitContrast: submit ? contrast(getComputedStyle(submit).color, getComputedStyle(submit).backgroundColor) : null, + }; + }); + shots.push(await R.shot(page, `theme-${cls}`)); + } + const problems = []; + for (const [theme, s] of Object.entries(seen)) { + if (s.marker !== 'kept') problems.push(`${theme}: the webview reloaded`); + if (s.body !== hexToRgb(s.editorBg)) problems.push(`${theme}: body ${s.body} is not the editor background ${s.editorBg}`); + if (!s.accent) problems.push(`${theme}: --codev-wv-accent resolves to nothing`); + if (!(s.idContrast >= 4.5)) problems.push(`${theme}: an item id's contrast is ${s.idContrast}`); + if (!(s.submitContrast >= 4.5)) problems.push(`${theme}: Submit's text contrast is ${s.submitContrast}`); + } + const tuples = new Set(Object.values(seen).map((s) => `${s.body}|${s.text}|${s.card}`)); + if (tuples.size !== themes.length) problems.push(`only ${tuples.size} distinct looks across ${themes.length} themes`); + const draft = await decisionCard(frame, 'main-2').locator('textarea.decisions-comment').inputValue(); + if (draft !== DRAFT) problems.push('the draft did not survive the switches'); + if (problems.length) throw new Error(`${problems.join('; ')} — ${JSON.stringify(seen)}`); + return { detail: Object.entries(seen).map(([t, s]) => `${t}: body ${s.body}, text ${s.text}, card border ${s.card}, contrast id ${s.idContrast} / Submit ${s.submitContrast}`).join('; '), shots }; + }); + + await R.check('the panel is restored after a window reload', async () => { + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.monaco-workbench', { timeout: 240_000 }); + frame = await decisionsFrame(page, 120_000); + await waitFor('the restored panel\'s cards', async () => (await frame.locator('.decisions-card').count()) === 3, 60_000); + const tabs = (await editorTabs(page)).filter((t) => /^Decisions/.test(t ?? '')); + if (tabs.length !== 1) throw new Error(`${tabs.length} Decisions tabs after the reload`); + return { detail: 'one Decisions tab, its cards rendered', shots: [await R.shot(page, 'restored')] }; + }); + + await R.check('scenario 19: in a builder-worktree window, Open Decisions explains, and the entry navigates to the parent', async () => { + const wt = fs.readdirSync(path.join(R.opts.fixtures, 'alpha', '.builders')).find((d) => d.includes('101')); + await loadWorkbench(page, R.folderUrl('alpha', '.builders', wt)); + await runCommand(page, 'Codev: Open Decisions'); + const note = await waitForNotification(page, /not offered in a builder-worktree window/); + const shot = await R.shot(page, 'worktree-explains'); + const wtCockpit = await openCockpit(page); + await setExpanded(wtCockpit, ALPHA, true); + const entry = await waitRow(wtCockpit, [...ALPHA, 'Decisions']); + const url = await nextPopup(R, context, () => entry.loc.click()); + if (!decodeURIComponent(new URL(url).searchParams.get('folder') ?? '').endsWith('/alpha')) throw new Error(`the entry opened ${url}`); + if ((await editorTabs(page)).some((t) => /^Decisions/.test(t ?? ''))) throw new Error('a Decisions panel opened in the worktree window'); + return { detail: `"${note}"; entry → ${url}`, shots: [shot] }; + }); + + await R.check('scenario 19: in a no-workspace window, Open Decisions explains', async () => { + await loadWorkbench(page, R.url('ew=true'), { needCodev: false }); + await page.waitForTimeout(3000); + await runCommand(page, 'Codev: Open Decisions'); + const note = await waitForNotification(page, /needs a Codev workspace/); + return { detail: `"${note}"`, shots: [await R.shot(page, 'no-workspace-explains')] }; + }); + + await R.check('scenario 16: no decisions file shows the empty state; afx decisions init, then an item, and it appears', async () => { + await loadWorkbench(page, R.folderUrl('gamma')); + const gammaCockpit = await openCockpit(page); + await waitRow(gammaCockpit, GAMMA, 60_000); + await setExpanded(gammaCockpit, GAMMA, true); + await (await waitRow(gammaCockpit, [...GAMMA, 'Decisions'])).loc.click(); + frame = await decisionsFrame(page); + const status = frame.locator('.decisions-notice[role="status"]'); + await waitFor('the empty state', async () => (await status.count()) === 1, 20_000); + const empty = (await status.textContent()).trim(); + if (!/^There is no decisions file/.test(empty) || !/afx decisions init/.test(empty)) throw new Error(`the empty state reads "${empty}"`); + const emptyShot = await R.shot(page, 'empty-state'); + + // The real CLI, run in the fixture: `decisions init` only writes the template (no Tower call). + const gamma = path.join(R.opts.fixtures, 'gamma'); + const init = spawnSync(process.execPath, [path.join(REPO, 'packages/codev/bin/afx.js'), 'decisions', 'init'], { cwd: gamma, env: process.env, encoding: 'utf-8', timeout: 60_000 }); + if (init.status !== 0) throw new Error(`afx decisions init exited ${init.status}: ${init.stderr || init.stdout}`); + await waitFor('the new file in place of the empty state', async () => (await status.count()) === 0 && /0 open/.test(await frame.locator('.decisions-count').textContent().catch(() => '')), 15_000); + const initShot = await R.shot(page, 'initialized'); + addOpenItem(path.join(gamma, DECISIONS_PATH), GAMMA_1, '1 open — main-1.'); + await waitFor('gamma\'s first item', async () => (await decisionCard(frame, 'main-1').count()) === 1, 15_000); + const words = await decisionCard(frame, 'main-1').locator('input[type="radio"]').evaluateAll((els) => els.map((e) => e.value)); + return { + detail: `"${empty}" → afx decisions init: "${init.stdout.split('\n').find((l) => /Created/.test(l))?.trim()}" → 0 open → main-1 appears (${words.join(' / ')})`, + shots: [emptyShot, initShot, await R.shot(page, 'item-appears')], + }; + }); + + await R.check('scenario 22: the webview never contacts Tower; the key is in no request; remote item images are its only network loads', async () => { + const towerPort = R.opts['tower-port']; + const problems = []; + const toTower = requests.filter((r) => URL.canParse(r.url) && new URL(r.url).port === towerPort); + if (toTower.length) problems.push(`${toTower.length} browser request(s) to the Tower port: ${toTower.slice(0, 3).map((r) => r.url).join(', ')}`); + const keyed = requests.filter((r) => r.key); + if (keyed.length) problems.push(`${keyed.length} request(s) carry the key header`); + const webview = requests.filter((r) => /\/webview\/browser\/pre\//.test(r.frame)); + const kinds = {}; + for (const r of webview) { + const origin = URL.canParse(r.frame) ? new URL(r.frame).origin : ''; + const kind = r.url === REMOTE_IMAGE ? 'remote item image' + : /^(blob|data):/.test(r.url) ? 'blob/data' + : URL.canParse(r.url) && /\.vscode-resource\./.test(new URL(r.url).hostname) ? 'extension resource' + : URL.canParse(r.url) && new URL(r.url).origin === origin ? "VS Code's webview host page" + : null; + if (!kind) problems.push(`unexpected webview request ${r.url}`); + else kinds[kind] = (kinds[kind] ?? 0) + 1; + } + if (!kinds['remote item image']) problems.push('the audit saw no webview request at all for the remote image (is it attributing frames?)'); + const html = await frame.content(); + if (html.includes(process.env.COCKPIT_TOWER_KEY) || html.includes(`:${towerPort}`)) problems.push('the webview document holds the key or the Tower port'); + if (problems.length) throw new Error(problems.slice(0, 8).join('; ')); + return `${requests.length} browser requests, none to :${towerPort}, none keyed; webview frames: ${JSON.stringify(kinds)}`; + }); +}; + async function main() { const [script, ...rest] = process.argv.slice(2); if (!SCRIPTS[script]) { diff --git a/apps/vscode/src/__tests__/contributes-cockpit.test.ts b/apps/vscode/src/__tests__/contributes-cockpit.test.ts index f65e1cb49..4b7f1cf4a 100644 --- a/apps/vscode/src/__tests__/contributes-cockpit.test.ts +++ b/apps/vscode/src/__tests__/contributes-cockpit.test.ts @@ -104,6 +104,14 @@ describe('the Decisions panel (Phase 7)', () => { expect(EXT_SRC).toMatch(/registerWebviewPanelSerializer\(DECISIONS_VIEW_TYPE, decisionsPanels\)/); }); + it("decides availability from the window's folders, so a reload's restore is not closed before Tower connects", () => { + // The connection manager's workspace is null until its async initialize() runs, and a restored + // panel reaches the serializer before that (found by the harness's reload check). + const wiring = EXT_SRC.slice(EXT_SRC.indexOf('new DecisionsPanels({'), EXT_SRC.indexOf('registerWebviewPanelSerializer(DECISIONS_VIEW_TYPE')); + expect(wiring).toMatch(/workspacePath: detectWorkspacePath\(\),/); + expect(wiring).not.toMatch(/getWorkspacePath\(\)/); + }); + it('ships the built webview: dist is packaged, the build script is not', () => { const ignored = readFileSync(resolve(ROOT, '.vscodeignore'), 'utf8').split('\n').map(line => line.trim()); expect(ignored).toContain('esbuild.webview.cjs'); diff --git a/apps/vscode/src/__tests__/workspace-views-theme.test.ts b/apps/vscode/src/__tests__/workspace-views-theme.test.ts index ebd13504f..5a91cfdec 100644 --- a/apps/vscode/src/__tests__/workspace-views-theme.test.ts +++ b/apps/vscode/src/__tests__/workspace-views-theme.test.ts @@ -55,6 +55,17 @@ describe('vscode-theme.css', () => { } }); + it("takes the accent from the link colour, and draws on it in the page colour (never the button's)", () => { + // High-contrast themes make the button background black, and the accent is also text on the + // page (item ids, links): with the button pair it vanished on a black page (found rendered). + // The link colour reads on the editor background in every theme; contrast is symmetric, so the + // editor background reads on an accent fill. + const map = mappings(); + expect(map.get('--codev-wv-accent')).toBe('var(--vscode-textLink-foreground)'); + expect(map.get('--codev-wv-on-accent')).toBe('var(--vscode-editor-background)'); + expect([...map.values()].some(v => v.includes('--vscode-button-background'))).toBe(false); + }); + it('uses no literal colour of its own anywhere', () => { const literal = /#[0-9a-f]{3,8}\b|\b(rgba?|hsla?)\(|\b(white|black)\b/i; const declarations = [...withoutComments(THEME).matchAll(/([a-z-]+)\s*:\s*([^;{}]+);/g)] diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index 0c88b8fca..5111a4ef3 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -599,12 +599,15 @@ export async function activate(context: vscode.ExtensionContext) { const cockpitView: vscode.TreeView = vscode.window.createTreeView(COCKPIT_VIEW_ID, { treeDataProvider: cockpitProvider }); // The Decisions panel (Spec 1963): one per window, for this window's workspace, with every Tower // call made here. Its serializer restores an open panel after a window reload. + // Whether the window has a workspace is read from its folders, not from the connection manager: + // a reload's restore reaches the serializer before `initialize()` has set the manager's workspace, + // and a null there would close the restored panel. const decisionsPanels = new DecisionsPanels({ extensionUri: context.extensionUri, bridge: new DecisionsBridge(connectionManager), unavailableReason: () => workspaceViewUnavailableReason('Decisions', { builderWorktreeWindow: isBuilderWorktreeWindow, - workspacePath: connectionManager?.getWorkspacePath() ?? null, + workspacePath: detectWorkspacePath(), }), log: (line) => outputChannel?.appendLine(line), }); diff --git a/apps/vscode/src/workspace-views/webview/vscode-theme.css b/apps/vscode/src/workspace-views/webview/vscode-theme.css index 3a7618dfd..cfbe86b92 100644 --- a/apps/vscode/src/workspace-views/webview/vscode-theme.css +++ b/apps/vscode/src/workspace-views/webview/vscode-theme.css @@ -16,10 +16,16 @@ --codev-wv-fg-secondary: var(--vscode-descriptionForeground); --codev-wv-fg-muted: var(--vscode-disabledForeground); --codev-wv-border: var(--vscode-panel-border, var(--vscode-contrastBorder)); - /* Buttons and accents use the button pair, so their text keeps its contrast in every theme. */ - --codev-wv-accent: var(--vscode-button-background, var(--vscode-focusBorder)); - --codev-wv-accent-hover: var(--vscode-button-hoverBackground, var(--vscode-focusBorder)); - --codev-wv-on-accent: var(--vscode-button-foreground); + /* + * The accent is text and borders on the page (item ids, links, selected options) as well as the + * fill of the primary buttons. VS Code's button background cannot be it: high-contrast themes + * make that black, which hides accent text on a black page. The link colour is made to read on + * the editor background in every theme, and contrast is symmetric, so the editor background + * reads on an accent-filled button just as well. + */ + --codev-wv-accent: var(--vscode-textLink-foreground); + --codev-wv-accent-hover: var(--vscode-textLink-activeForeground, var(--vscode-textLink-foreground)); + --codev-wv-on-accent: var(--vscode-editor-background); --codev-wv-accent-tint: color-mix(in srgb, var(--codev-wv-accent) 8%, transparent); --codev-wv-accent-tint-hover: color-mix(in srgb, var(--codev-wv-accent) 18%, transparent); --codev-wv-accent-tint-border: color-mix(in srgb, var(--codev-wv-accent) 20%, transparent); diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 3b4dd417f..be66e8ef0 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -812,6 +812,60 @@ Tower call made by the extension host. Built: Windows. Its directory links are junctions, which need no privilege; a `win32`-only describe covers drive-letter case and separators on real paths. -**Still to do in Phase 7:** the rendered harness check (scenarios 15, 16, 18), including whether -Uint8Array image bytes survive `webview.postMessage` in VS Code and in /ide/, and how the -high-contrast theme looks; then the Windows dispatch. +### Phase 7: rendered verification (2026-11-24) + +New harness script, `verify decisions`: 15 checks, each run on its own `start` + `seed fleet`. +It adds `main-2` to alpha's file (an https image served by the browser's route, and an image +outside the workspace) and creates gamma's file. + +**Two bugs found and fixed:** +1. **Reload restore closed the panel** (run 1, 14/15). + - `deserializeWebviewPanel` asked `unavailableReason()`, which read + `connectionManager.getWorkspacePath()`. That is null until the async `initialize()` runs, and + a restore reaches the serializer first, so the restored panel was disposed as "no workspace". + - **Fix:** availability now comes from the window's folders, `detectWorkspacePath()`, the same + thing the CLI preflight already uses for the same reason. + - A source test in `contributes-cockpit.test.ts` pins it. +2. **High contrast hid accent text.** + - I had mapped `--codev-wv-accent` to VS Code's button background. HC Dark makes that black, and + the accent is also text and borders on the page (item ids, links, the selected option), so the + ids vanished on the black page. + - **Fix:** accent → `--vscode-textLink-foreground`, on-accent → `--vscode-editor-background`. + Contrast is symmetric, so text on an accent-filled button keeps the link's contrast. The + shared package is unchanged. + - The theme unit test pins the mapping. The rendered theme check now measures WCAG contrast: + item id on the page, and Submit's text on its fill, both ≥ 4.5 in all four themes (measured + 6.3 to 9). + +**Final run (cycle 3, the committed build): 15/15.** +Evidence: `codev/projects/1963-…/verification-phase7/`. +- Entries: a Decisions entry under alpha, beta and gamma (beta and gamma have no file), none under + dormant delta. Beta's entry opens beta's window. +- Alpha's entry opens one panel; a second click reveals the same panel. +- Images: + - the workspace SVG renders from a `blob:` URL, so **Uint8Array bytes survive + `webview.postMessage` in serve-web**; + - the https image renders; + - the outside image shows "Image not loaded", with Tower's reason. +- The full-size view opens; Escape and Close each close it. +- The link opens after VS Code's own "open external website?" prompt. +- Ruling `main-1`: the file is updated, the card shows the ruling, and Tower logs `Decisions notice + held (no-profile) → main @ alpha`. The notice is persisted to main's mailbox and held, because + the fixture architect is a bash shell, not an agent; the Codev panel shows "1 held". +- A stale fingerprint is refused ("Item main-2 changed since it was shown…"), with the draft and + word kept. +- Polling: 3 reads in 6 s while shown, 0 in 8 s while hidden, and reads resume when shown again. +- Four themes switched live: the webview never reloaded and the draft was kept. +- The panel is restored after a reload. +- Explanations show in a worktree window and a no-workspace window, and the worktree window's + entry navigates to the parent. +- Gamma: the empty state, then the real `afx decisions init` (it only writes the template; I + checked the CLI path: no Tower call), "0 open", then an added item appears. +- The audit: 205 browser requests, none to the Tower port, none carrying the key. Webview frames + loaded only extension resources and the remote item image. + +**Not run:** the `/ide/` (ide-server) mode. It serves the same VS Code web workbench and webview +code as serve-web. + +**Adjacent:** `.vscodeignore` now drops `**/tsconfig.*.json`. The vsix had been shipping +`tsconfig.webview.json` since the markdown preview added it. From c1bd6becacaf688c4c8580e5637cfe4611f705bd Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:32:01 -0800 Subject: [PATCH 080/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index be0b8edaf..6449b0ed4 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -84,7 +84,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-workspace_views_package-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T11:49:53.636Z' +updated_at: '2026-11-24T12:32:01.351Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 5d15ce0484eeb8b29dc988cc9c853d97fb04759d Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:49:42 -0800 Subject: [PATCH 081/140] [Spec 1963][Phase: decisions_panel] fix: refused remote images, readable text in every theme, Windows test paths From the Phase 7 review (Codex REQUEST_CHANGES, Claude APPROVE) and the Windows run: - A remote (http(s)) image the browser refuses now shows "Image not loaded", as the spec requires (mixed content, a Tower URL's 401, a 404). It was left a broken image. The listener is removed on cleanup. This is in the shared view, so the dashboard gains the note too. - The option words were invisible in Light High Contrast: VS Code's webview colours every `code` for its own code background, and `.decisions-option-word` paints its own. It now sets `color: inherit`, a no-op in a browser. - The rendered theme check measures the contrast of every visible text in the panel. That found three wrong mappings for text, now changed: - muted text was the disabled-control colour (2.1:1 in Light Modern), now VS Code's placeholder grey; - error text measured 2.8:1 and waiting text 2.9:1; both now take VS Code's list text colours, with the old ones as the high-contrast fallback. Every text is now at least 4.1:1 in all four themes. - Windows: the containment test compared against an 8.3 short temp path, and used /etc/hosts as an outside file; the test is fixed, the code is unchanged. - Comments on why the ruling guard leaves word/comment unbounded (Tower refuses them with a reason), and why an aborted image request is collected. Harness `verify decisions`: 15/15 on this build; evidence replaced. --- apps/vscode/scripts/cockpit-harness/README.md | 2 +- .../cockpit-harness/cockpit-verify.mjs | 86 +++++++++++++++---- .../workspace-views-security.test.ts | 13 ++- .../__tests__/workspace-views-theme.test.ts | 14 +++ apps/vscode/src/workspace-views/messages.ts | 4 + .../workspace-views/webview/decisions-host.ts | 2 + .../workspace-views/webview/vscode-theme.css | 21 +++-- codev/state/spir-1963_thread.md | 66 ++++++++++++++ .../__tests__/DecisionsView.images.test.tsx | 25 ++++++ .../src/components/DecisionsView.tsx | 11 ++- packages/workspace-views/src/styles.css | 3 + 11 files changed, 215 insertions(+), 32 deletions(-) diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index c6a36f02d..378794ce4 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -160,7 +160,7 @@ state, so run them in this order, once per `start`: | `requests` | Spec scenario 21. Tower request counts in three layouts: the Cockpit alone; the Workspace, Agents and Tower views alone; and both at once (the Cockpit moved to the panel with *View: Move View*, undone with *Reset View Locations*). Each layout asserts what the side bar, secondary side bar and panel show before measuring. Each counts a 60 s idle window plus a 15 s burst (`#103`'s gate and a `codev-config-updated`), started 2 s after a fleet poll tick so no poll tick lands in it. Each runs in a freshly restarted VS Code server (`vscode-restart`), because VS Code keeps a closed window's extension host alive for its reconnection grace period, and those hosts would keep polling the Tower. It fails if the Cockpit alone makes anything the source views do not, if fleet or overview counts differ across layouts, if `getWorktreeConfig` runs while idle, if both at once add anything but `getWorktreeConfig`, or if a window opens more than one event stream | | `actions` | Every builder context action, Approve Gate inline (it relays to the spawning architect through `/api/send`, #1494, so the check asserts that and no porch call), every workspace-row action (Spawn Builder's `afx spawn` checked in the stub log, with its cwd), and Remove Architect: offered on siblings only. A childless sibling, added through Tower, loses its row. A sibling that spawned a builder keeps its header as that builder's owner, as in Agents. Other workspaces' rows navigate; their workspace rows keep Open and Deactivate. It sets #102's and #103's gates back to unrequested first, because `windows` and `requests` request them | | `dashboard` | Spec scenario 20, on **its own** `start` + `seed fleet` (it rules `main-1` and opens a shell in `alpha`). The browser dashboard the isolated Tower serves for `alpha`, in headless Chromium, not VS Code. It refreshes the overview first, because Tower caches the forge failure from the extension's activation before the seed. Five checks: Work renders every section with rows; Decisions renders both cards and loads the image as a blob; a link and a full-size image open in a new tab (the link's URL, the image's blob page); a ruling round-trips to the file; and Work's actions (Open, + Shell, an artifact link, an issue link, Refresh) do what they did. It writes `shots/dashboard-snapshot.json`: every element under the two views, with its classes, its own text (ages masked) and its computed colour, type and box. With `COCKPIT_BASELINE=
` it adds a sixth check that fails on any difference from that snapshot. To compare a change against its base, run once on the base's build, keep the snapshot, then run again on the change's build with `COCKPIT_BASELINE` pointing at it | -| `decisions` | Spec scenarios 15, 16, 18, 19 (Decisions part), 21 (hidden-panel polling) and 22, Phase 7. On **its own** `start` + `seed fleet`: it adds `main-2` to alpha's file (an https image, answered by the browser's route for `example.com`, and an image outside the workspace), rules `main-1`, edits `main-2` under the panel, and creates gamma's file. It checks: a **Decisions** entry under every active workspace and none under the dormant one; another workspace's entry opens that window; this workspace's opens one panel with the items; the workspace image renders from an object URL (bytes through the host), the https image renders, the outside image shows why it was not loaded; the full-size view opens and closes; a link opens through the host; a ruling writes the file, shows on the card and reaches `main` (Tower's `Decisions notice` log line); a stale fingerprint is refused with the draft kept; no reads while the panel is hidden; four themes switched live without reloading the webview; the panel restored after a reload; the explanations in a builder-worktree and a no-workspace window; gamma's empty state, then the real `afx decisions init` (it only writes the template), then an item appears; and a request audit: no browser request to the Tower port or carrying the key, and webview frames load only VS Code's webview host page, extension resources, blobs and the remote item image | +| `decisions` | Spec scenarios 15, 16, 18, 19 (Decisions part), 21 (hidden-panel polling) and 22, Phase 7. On **its own** `start` + `seed fleet`: it adds `main-2` to alpha's file (an https image and one answered 404, both from the browser's route for `example.com`, and an image outside the workspace), rules `main-1`, edits `main-2` under the panel, and creates gamma's file. It checks: a **Decisions** entry under every active workspace and none under the dormant one; another workspace's entry opens that window; this workspace's opens one panel with the items; the workspace image renders from an object URL (bytes through the host), the https image renders, the 404 image and the outside image each show *Image not loaded* with the reason; the full-size view opens and closes; a link opens through the host; a ruling writes the file, shows on the card and reaches `main` (Tower's `Decisions notice` log line); a stale fingerprint is refused with the draft kept; no reads while the panel is hidden; four themes switched live without reloading the webview, with the contrast of every visible text in the panel measured against its composited background (none under 3:1; the item id, Submit and an option word at least 4.5:1; every text under 4.5:1 listed in the evidence); the panel restored after a reload; the explanations in a builder-worktree and a no-workspace window; gamma's empty state, then the real `afx decisions init` (it only writes the template), then an item appears; and a request audit: no browser request to the Tower port or carrying the key, and webview frames load only VS Code's webview host page, extension resources, blobs and the remote item images | | `reconnect` | **Run last.** A loaded Cockpit keeps its content with Tower down; a fresh window shows *Not connected to Tower*; Tower up + the row's Reconnect restores it. Stops and restarts only the isolated Tower, by PID (`tower-down` / `tower-up`) | A restarted Tower does not reconnect the fixture sessions: its startup reconciliation skips, and diff --git a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs index ea76a1900..a814d79dd 100644 --- a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs +++ b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs @@ -1532,13 +1532,15 @@ SCRIPTS.dashboard = async (R, context, page) => { const DECISIONS_PATH = 'codev/state/pending-decisions.md'; const REMOTE_IMAGE = 'https://example.com/fixture/remote-board.svg'; +/** A remote image the browser fails to load: the route answers 404. */ +const REMOTE_GONE = 'https://example.com/fixture/gone-board.svg'; const REMOTE_SVG = ''; const OUTSIDE_SVG = ''; /** - * `main-2`, added to alpha's file by this script: an https image, which the webview loads itself, - * and an image outside the workspace, which Tower refuses. It is also the item the stale-fingerprint - * check edits under the panel. + * `main-2`, added to alpha's file by this script: an https image, which the webview loads itself; + * an https image the browser fails to load (404); and an image outside the workspace, which Tower + * refuses. It is also the item the stale-fingerprint check edits under the panel. */ const MAIN_2 = `### main-2 · 2026-11-21 10:00 UTC · Which board image should the fixture keep? @@ -1546,6 +1548,8 @@ const MAIN_2 = `### main-2 · 2026-11-21 10:00 UTC · Which board image should t ![Remote board](${REMOTE_IMAGE}) +![Gone board](${REMOTE_GONE}) + ![Outside image](../../../outside.svg) **Your word:** \`remote\` / \`local\` @@ -1605,7 +1609,9 @@ SCRIPTS.decisions = async (R, context, page) => { // Item links and the remote image point at example.com: answer them here, so nothing leaves the machine. await context.route(/^https?:\/\/example\.com\//, (route) => (route.request().url() === REMOTE_IMAGE ? route.fulfill({ status: 200, contentType: 'image/svg+xml', body: REMOTE_SVG }) - : route.fulfill({ status: 200, contentType: 'text/html', body: '

fixture link

' }))); + : route.request().url() === REMOTE_GONE + ? route.fulfill({ status: 404, contentType: 'text/plain', body: 'not found' }) + : route.fulfill({ status: 200, contentType: 'text/html', body: '

fixture link

' }))); // Every request the browser makes, with the frame that made it, for scenario 22. const requests = []; @@ -1673,20 +1679,22 @@ SCRIPTS.decisions = async (R, context, page) => { return { detail: `tab "${await activeEditorTab(page)}"; ${count}; main-1 offers ${words.join(' / ')}; one tab after a second click`, shots: [await R.shot(page, 'panel')] }; }); - await R.check('scenario 15: a workspace image (bytes through the host), an https image, and a refused image', async () => { + await R.check('scenario 15: a workspace image (bytes through the host), an https image, and two not loaded (the browser\'s 404, Tower\'s refusal)', async () => { const local = decisionCard(frame, 'main-1').locator('img[alt="Compact board"]'); const remote = decisionCard(frame, 'main-2').locator('img[alt="Remote board"]'); const loaded = (img) => img.evaluate((el) => el.complete && el.naturalWidth > 0).catch(() => false); await waitFor('the workspace image to render from an object URL', async () => (await local.getAttribute('src'))?.startsWith('blob:') && loaded(local), 20_000); await waitFor('the https image to render', async () => (await remote.getAttribute('src')) === REMOTE_IMAGE && loaded(remote), 20_000); const missing = decisionCard(frame, 'main-2').locator('.decisions-image-missing'); - await waitFor('the refused image\'s note', async () => (await missing.count()) === 1, 20_000); - const note = (await missing.textContent()).replace(/\s+/g, ' ').trim(); - const reason = await missing.getAttribute('title'); - if (!/Image not loaded/.test(note) || !/outside\.svg/.test(note)) throw new Error(`the note reads "${note}"`); - if (!/outside/i.test(reason ?? '')) throw new Error(`the reason is "${reason}"`); + await waitFor('two not-loaded notes', async () => (await missing.count()) === 2, 20_000); + const notes = await missing.evaluateAll((els) => els.map((el) => ({ text: el.textContent.replace(/\s+/g, ' ').trim(), reason: el.title }))); + const gone = notes.find((n) => n.text.includes(REMOTE_GONE)); + const outside = notes.find((n) => /outside\.svg/.test(n.text)); + if (!gone || !/^Image not loaded Gone board/.test(gone.text)) throw new Error(`no note for the 404 image: ${JSON.stringify(notes)}`); + if (!outside || !/^Image not loaded/.test(outside.text) || !/outside/i.test(outside.reason)) throw new Error(`no note for the refused image: ${JSON.stringify(notes)}`); + if (await decisionCard(frame, 'main-2').locator('img[alt="Gone board"]').count()) throw new Error('the 404 image is still a (broken) img'); const size = await local.evaluate((el) => `${el.naturalWidth}×${el.naturalHeight}`); - return { detail: `workspace SVG ${size} from blob:; https image loaded; refused: "${note}" (${reason})`, shots: [await R.shot(page, 'images')] }; + return { detail: `workspace SVG ${size} from blob:; https image loaded; 404: "${gone.text}" (${gone.reason}); refused: "${outside.text}" (${outside.reason})`, shots: [await R.shot(page, 'images')] }; }); await R.check('scenario 15: the full-size view opens over the panel; Escape and Close each close it', async () => { @@ -1794,16 +1802,45 @@ SCRIPTS.decisions = async (R, context, page) => { seen[theme] = await frame.evaluate(() => { const root = getComputedStyle(document.documentElement); const card = document.querySelector('.decisions-card'); - // WCAG contrast of two computed rgb() colours. - const lum = (c) => { - const [r, g, b] = c.match(/[\d.]+/g).slice(0, 3).map(Number).map((v) => v / 255) - .map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); - return 0.2126 * r + 0.7152 * g + 0.0722 * b; + // WCAG contrast of computed colours: rgb()/rgba(), or color(srgb …) from a color-mix(). + const parse = (c) => { + const n = (c.match(/-?[\d.]+(?:e-?\d+)?/g) ?? []).map(Number); + const k = c.startsWith('color(') ? 255 : 1; + return c === 'transparent' ? { r: 0, g: 0, b: 0, a: 0 } : { r: n[0] * k, g: n[1] * k, b: n[2] * k, a: n.length > 3 ? n[3] : 1 }; + }; + const over = (top, under) => ({ r: top.a * top.r + (1 - top.a) * under.r, g: top.a * top.g + (1 - top.a) * under.g, b: top.a * top.b + (1 - top.a) * under.b, a: 1 }); + // What an element's text is drawn on: its own and its ancestors' backgrounds, composited. + const backdrop = (el) => { + const layers = []; + for (let e = el; e; e = e.parentElement) { + const bg = parse(getComputedStyle(e).backgroundColor); + if (bg.a > 0) layers.push(bg); + if (bg.a >= 1) break; + } + let base = layers.at(-1)?.a >= 1 ? layers.pop() : { r: 255, g: 255, b: 255, a: 1 }; + for (const layer of layers.reverse()) base = over(layer, base); + return base; + }; + const lum = ({ r, g, b }) => { + const [R, G, B] = [r, g, b].map((v) => v / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; }; - const contrast = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((m, n) => n - m); return Math.round(((x + 0.05) / (y + 0.05)) * 10) / 10; }; + const ratio = (fg, bg) => { const [x, y] = [lum(fg), lum(bg)].sort((m, n) => n - m); return Math.round(((x + 0.05) / (y + 0.05)) * 10) / 10; }; + const textContrast = (el) => { const bg = backdrop(el); return ratio(over(parse(getComputedStyle(el).color), bg), bg); }; + const contrast = (a, b) => ratio(parse(a), parse(b)); const page = getComputedStyle(document.body).backgroundColor; const id = document.querySelector('.decisions-item-id'); const submit = [...document.querySelectorAll('.decisions-submit-btn')].find((b) => !b.disabled); + const word = document.querySelector('.decisions-option-word'); + const badge = document.querySelector('.decisions-badge'); + // Every rendered element in the panel with text of its own, on what it is drawn on. + const texts = [...document.querySelectorAll('.decisions-view *')] + .filter((el) => el.getClientRects().length && [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())) + .map((el) => { + const kind = `${el.tagName.toLowerCase()}${[...el.classList].map((c) => `.${c}`).join('')}`; + return { kind, what: `${kind} "${el.textContent.trim().slice(0, 24)}"`, contrast: textContrast(el) }; + }) + .sort((a, b) => a.contrast - b.contrast); return { marker: window.__codevMarker ?? null, body: page, @@ -1814,6 +1851,12 @@ SCRIPTS.decisions = async (R, context, page) => { // Text drawn in the accent on the page, and on an accent-filled button. idContrast: id ? contrast(getComputedStyle(id).color, page) : null, submitContrast: submit ? contrast(getComputedStyle(submit).color, getComputedStyle(submit).backgroundColor) : null, + wordContrast: word ? textContrast(word) : null, + badgeContrast: badge ? textContrast(badge) : null, + scanned: texts.length, + lowest: texts.slice(0, 3).map(({ what, contrast: c }) => ({ what, contrast: c })), + // Every kind of text under 4.5:1, at its lowest: shown in the evidence, not only failed on. + under45: [...new Map(texts.filter((t) => t.contrast < 4.5).reverse().map((t) => [t.kind, t.contrast])).entries()].map(([k, c]) => `${c} ${k}`), }; }); shots.push(await R.shot(page, `theme-${cls}`)); @@ -1825,13 +1868,18 @@ SCRIPTS.decisions = async (R, context, page) => { if (!s.accent) problems.push(`${theme}: --codev-wv-accent resolves to nothing`); if (!(s.idContrast >= 4.5)) problems.push(`${theme}: an item id's contrast is ${s.idContrast}`); if (!(s.submitContrast >= 4.5)) problems.push(`${theme}: Submit's text contrast is ${s.submitContrast}`); + if (!(s.wordContrast >= 4.5)) problems.push(`${theme}: an option word's contrast is ${s.wordContrast}`); + if (!(s.badgeContrast >= 3)) problems.push(`${theme}: the Recommended badge's contrast is ${s.badgeContrast}`); + // No text in the panel below 3:1, the floor for anything a reader is meant to see. + const faint = s.lowest.filter((t) => !(t.contrast >= 3)); + if (faint.length) problems.push(`${theme}: faint text ${JSON.stringify(faint)}`); } const tuples = new Set(Object.values(seen).map((s) => `${s.body}|${s.text}|${s.card}`)); if (tuples.size !== themes.length) problems.push(`only ${tuples.size} distinct looks across ${themes.length} themes`); const draft = await decisionCard(frame, 'main-2').locator('textarea.decisions-comment').inputValue(); if (draft !== DRAFT) problems.push('the draft did not survive the switches'); if (problems.length) throw new Error(`${problems.join('; ')} — ${JSON.stringify(seen)}`); - return { detail: Object.entries(seen).map(([t, s]) => `${t}: body ${s.body}, text ${s.text}, card border ${s.card}, contrast id ${s.idContrast} / Submit ${s.submitContrast}`).join('; '), shots }; + return { detail: Object.entries(seen).map(([t, s]) => `${t}: body ${s.body}, text ${s.text}, card border ${s.card}, contrast id ${s.idContrast} / Submit ${s.submitContrast} / option word ${s.wordContrast} / badge ${s.badgeContrast}; lowest of ${s.scanned} texts ${s.lowest.map((x) => `${x.contrast} ${x.what}`).join(', ')}; under 4.5: ${s.under45.join(', ') || 'none'}`).join('; '), shots }; }); await R.check('the panel is restored after a window reload', async () => { @@ -1906,7 +1954,7 @@ SCRIPTS.decisions = async (R, context, page) => { const kinds = {}; for (const r of webview) { const origin = URL.canParse(r.frame) ? new URL(r.frame).origin : ''; - const kind = r.url === REMOTE_IMAGE ? 'remote item image' + const kind = r.url === REMOTE_IMAGE || r.url === REMOTE_GONE ? 'remote item image' : /^(blob|data):/.test(r.url) ? 'blob/data' : URL.canParse(r.url) && /\.vscode-resource\./.test(new URL(r.url).hostname) ? 'extension resource' : URL.canParse(r.url) && new URL(r.url).origin === origin ? "VS Code's webview host page" diff --git a/apps/vscode/src/__tests__/workspace-views-security.test.ts b/apps/vscode/src/__tests__/workspace-views-security.test.ts index 9f8856f71..1105245eb 100644 --- a/apps/vscode/src/__tests__/workspace-views-security.test.ts +++ b/apps/vscode/src/__tests__/workspace-views-security.test.ts @@ -47,7 +47,9 @@ describe('resolveWorkspaceFile (real files and symlinks)', () => { let outside: string; beforeAll(() => { - base = realpathSync(mkdtempSync(path.join(tmpdir(), 'codev-wv-security-'))); + // The native realpath, which `fs.promises.realpath` in the code under test is: on Windows the + // JS one keeps an 8.3 short name (C:\Users\RUNNER~1\…) where the native one gives the long name. + base = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'codev-wv-security-'))); root = path.join(base, 'ws'); outside = path.join(base, 'outside'); mkdirSync(path.join(root, 'codev', 'specs'), { recursive: true }); @@ -79,12 +81,15 @@ describe('resolveWorkspaceFile (real files and symlinks)', () => { it.each([ ['a .. escape', '../outside/secret.md'], - ['an absolute path outside', '/etc/hosts'], + // A file that exists on every platform: one that does not is not-found, as on POSIX. + ['an absolute path outside', () => path.join(outside, 'secret.md')], ['a prefix sibling', '../ws-other/a.md'], ['a file symlink leading outside', 'escape-link.md'], ['a directory symlink leading outside', 'escape-dir/secret.md'], - ])('refuses %s', async (_name, requested) => { - expect(await resolveWorkspaceFile(root, requested)).toEqual({ ok: false, reason: 'outside-workspace' }); + ] as Array<[string, string | (() => string)]>)('refuses %s', async (_name, requested) => { + // A function for a path built from the fixture, which does not exist when the table is read. + const target = typeof requested === 'function' ? requested() : requested; + expect(await resolveWorkspaceFile(root, target)).toEqual({ ok: false, reason: 'outside-workspace' }); }); it('says not-found for a path that does not exist, and for one with a NUL byte', async () => { diff --git a/apps/vscode/src/__tests__/workspace-views-theme.test.ts b/apps/vscode/src/__tests__/workspace-views-theme.test.ts index 5a91cfdec..2065e945d 100644 --- a/apps/vscode/src/__tests__/workspace-views-theme.test.ts +++ b/apps/vscode/src/__tests__/workspace-views-theme.test.ts @@ -66,6 +66,20 @@ describe('vscode-theme.css', () => { expect([...map.values()].some(v => v.includes('--vscode-button-background'))).toBe(false); }); + it('draws muted text in a colour meant to be read, not the disabled-control colour', () => { + // Light Modern draws disabledForeground at half alpha: section labels measured 2.1:1 rendered. + const map = mappings(); + expect(map.get('--codev-wv-fg-muted')).toMatch(/^var\(--vscode-input-placeholderForeground/); + expect([...map.values()].some(v => v.includes('--vscode-disabledForeground'))).toBe(false); + }); + + it("draws waiting and error text in VS Code's list colours, which are made to be read", () => { + // Light themes' chart yellow and error foreground measured under 3:1 as text, rendered. + const map = mappings(); + expect(map.get('--codev-wv-status-waiting')).toMatch(/^var\(--vscode-list-warningForeground,/); + expect(map.get('--codev-wv-status-error')).toMatch(/^var\(--vscode-list-errorForeground,/); + }); + it('uses no literal colour of its own anywhere', () => { const literal = /#[0-9a-f]{3,8}\b|\b(rgba?|hsla?)\(|\b(white|black)\b/i; const declarations = [...withoutComments(THEME).matchAll(/([a-z-]+)\s*:\s*([^;{}]+);/g)] diff --git a/apps/vscode/src/workspace-views/messages.ts b/apps/vscode/src/workspace-views/messages.ts index bb2e26993..0bb63b265 100644 --- a/apps/vscode/src/workspace-views/messages.ts +++ b/apps/vscode/src/workspace-views/messages.ts @@ -127,6 +127,10 @@ export function isDecisionsReadMessage(message: unknown): message is DecisionsRe /** * A ruling request of the shape Tower's rule route takes: a non-empty `id` and `fingerprint`, * and `word` and `comment` strings when present. Tower checks the content. + * + * Unlike `path` and `url`, these are not held to {@link MAX_WEBVIEW_STRING}, on purpose: the host + * only forwards them, and Tower bounds the body and refuses a comment over its limit with a reason + * the panel shows. A bound here would drop a long comment silently instead. */ function isRuleRequest(value: unknown): value is DecisionsRuleRequest { return isRecord(value) diff --git a/apps/vscode/src/workspace-views/webview/decisions-host.ts b/apps/vscode/src/workspace-views/webview/decisions-host.ts index bc688dc11..2f38f65d1 100644 --- a/apps/vscode/src/workspace-views/webview/decisions-host.ts +++ b/apps/vscode/src/workspace-views/webview/decisions-host.ts @@ -99,6 +99,8 @@ export class WebviewDecisionsHost implements DecisionsViewHost { reply => (reply.type === 'decisions/image-result' ? imageResult(reply.result) : { kind: 'not-loaded', message: mismatch(reply) }), ); return new Promise(resolve => { + // On abort the request's resolver leaves `pending`, so `result` can never settle; with that + // resolver gone nothing references `result`, and it is collected with its `then` below. const onAbort = () => { this.pending.delete(requestId); resolve(aborted); diff --git a/apps/vscode/src/workspace-views/webview/vscode-theme.css b/apps/vscode/src/workspace-views/webview/vscode-theme.css index cfbe86b92..e232565c8 100644 --- a/apps/vscode/src/workspace-views/webview/vscode-theme.css +++ b/apps/vscode/src/workspace-views/webview/vscode-theme.css @@ -14,7 +14,9 @@ --codev-wv-bg-hover: var(--vscode-list-hoverBackground); --codev-wv-fg: var(--vscode-foreground); --codev-wv-fg-secondary: var(--vscode-descriptionForeground); - --codev-wv-fg-muted: var(--vscode-disabledForeground); + /* Muted text is still read (section labels, counts, hints): VS Code's readable muted grey, not + its disabled-control colour, which a light theme draws at half alpha (2.1:1, found rendered). */ + --codev-wv-fg-muted: var(--vscode-input-placeholderForeground, var(--vscode-descriptionForeground)); --codev-wv-border: var(--vscode-panel-border, var(--vscode-contrastBorder)); /* * The accent is text and borders on the page (item ids, links, selected options) as well as the @@ -33,14 +35,19 @@ --codev-wv-font-family: var(--vscode-font-family); --codev-wv-font-mono: var(--vscode-editor-font-family); - /* Status */ + /* + * Status. Waiting and error are text as well as marks (a refusal, "Image not loaded"), so they + * take VS Code's list colours, which are made to be read as text. Light themes' chart yellow and + * error foreground measured 2.9:1 and 2.8:1 rendered. High-contrast themes leave the list + * colours unset, so the fallbacks apply there. + */ --codev-wv-status-active: var(--vscode-charts-green); - --codev-wv-status-waiting: var(--vscode-charts-yellow); - --codev-wv-status-error: var(--vscode-errorForeground); + --codev-wv-status-waiting: var(--vscode-list-warningForeground, var(--vscode-charts-yellow)); + --codev-wv-status-error: var(--vscode-list-errorForeground, var(--vscode-errorForeground)); --codev-wv-status-implementing: var(--vscode-charts-orange); - --codev-wv-status-waiting-tint: color-mix(in srgb, var(--vscode-charts-yellow) 10%, transparent); - --codev-wv-status-error-tint: color-mix(in srgb, var(--vscode-errorForeground) 10%, transparent); - --codev-wv-tag-bug-bg: color-mix(in srgb, var(--vscode-errorForeground) 15%, transparent); + --codev-wv-status-waiting-tint: color-mix(in srgb, var(--codev-wv-status-waiting) 10%, transparent); + --codev-wv-status-error-tint: color-mix(in srgb, var(--codev-wv-status-error) 10%, transparent); + --codev-wv-tag-bug-bg: color-mix(in srgb, var(--codev-wv-status-error) 15%, transparent); --codev-wv-tag-project: var(--vscode-charts-purple); --codev-wv-tag-project-bg: color-mix(in srgb, var(--vscode-charts-purple) 12%, transparent); --codev-wv-tag-spike: var(--vscode-charts-blue); diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index be66e8ef0..379bf1676 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -869,3 +869,69 @@ code as serve-web. **Adjacent:** `.vscodeignore` now drops `**/tsconfig.*.json`. The vsix had been shipping `tsconfig.webview.json` since the markdown preview added it. + +### Phase 7: review, iteration 1 (2026-11-24) + +`porch done` passed (build 17.6 s, tests 49.6 s, no skip). The 2-way review followed: Codex +REQUEST_CHANGES and Claude APPROVE, each with points that held up. + +**Codex: a refused http(s) image was a broken image, not "Image not loaded".** +- The spec requires the note for an http(s) image the browser refuses (mixed content, a Tower + URL's 401). The shared view only handled failures of host-loaded images, and my harness only + tested Tower's refusal. +- **Fix (in the shared package):** an error listener on every direct http(s) image, removed on + cleanup through the effect's abort signal. Package tests cover the refusal, and that a late + error on a detached image does nothing; that test fails without the signal. +- The harness now adds a remote image the route answers 404 for, and checks that its note is + rendered. +- **This changes the dashboard too:** a refused remote image there now shows the note instead of + a broken image, as the spec describes. No fixture of Phase 6's dashboard snapshot has a remote + image, so that comparison is unaffected. + +**Claude: the option words looked faint in Light High Contrast. They were invisible.** +- **Cause:** VS Code's webview stylesheet colours every `code` with its preformat foreground. + `.decisions-option-word` is a `code` that paints its own background but set no colour, so in + HC Light it drew near-white text on a light background. +- **Fix (in the package):** that rule sets `color: inherit`. It is a no-op in a browser, so the + dashboard is unchanged. +- **Wider check:** following Claude's "coverage is not contrast", the theme check now measures + every visible text element in the panel (62) in all four themes, against its composited + background. It fails below 3:1, requires 4.5:1 for the item id, Submit and the option word, + and lists every text under 4.5:1 in the evidence. That found three more mappings of mine that + were wrong for text: + - `fg-muted` → `disabledForeground`, a disabled-control colour that Light Modern draws at half + alpha: section labels measured 2.1:1. It is now `input.placeholderForeground`, VS Code's + readable muted grey. + - The error colour: VS Code's `errorForeground` is `#F85149` in Light Modern, and the refusal + measured 2.8:1. + - The waiting colour: `charts.yellow`, "Image not loaded" measured 2.9:1. + + The error and waiting colours now take `list.errorForeground` / `list.warningForeground`, + VS Code's colours for text. High-contrast themes leave those unset, so the fallbacks apply. + The tints follow the same colours. +- **Result:** every text is at least 4.1:1 in all four themes. Under 4.5:1, only in Light + Modern: the section labels at 4.3 (VS Code's own placeholder grey) and the Recommended badge + at 4.1 (`charts.green`), left as they are and recorded. +- **Not yet measured:** the Work view's status colours (implementing orange, the tags). That + panel is Phase 8, whose rendered check should run the same scan. + +**Claude's minor notes:** +- The ruling guard's `word`/`comment` are unbounded on purpose: Tower caps the body and refuses + an over-long comment with a reason the panel shows, whereas a host cap would drop it silently. + This is now said in the guard's comment. +- The "leak" on an aborted image is not one: once the resolver leaves `pending`, nothing + references the inner promise and it is collected. A comment now says so. +- The Windows run: dispatched and linked in the PR (run 45394199925). + +**Final harness run (cycle 7): 15/15.** Evidence in `verification-phase7/` is replaced by that +run. + +**Windows run on `36f7c4acd`:** the new path-containment step failed 4 of 39, all on the test side. +- **Three:** the test canonicalized its temp dir with the JS `realpathSync`, which on Windows keeps + the runner's 8.3 short name (`RUNNER~1`). The code uses `fs.promises.realpath`, the native one, + which gives the long name. The test now uses `realpathSync.native`. +- **One:** the "absolute path outside" case used `/etc/hosts`, which does not exist on Windows, so + `not-found` was correct. It now names the fixture's own outside file. +- The code under test is unchanged, and `resolveWorkspaceFile` has no production caller yet. +- The other suites, CLI tests, probes and install verification passed. The run is re-dispatched + after this commit. diff --git a/packages/workspace-views/src/__tests__/DecisionsView.images.test.tsx b/packages/workspace-views/src/__tests__/DecisionsView.images.test.tsx index 2b8e18ebc..59187fd53 100644 --- a/packages/workspace-views/src/__tests__/DecisionsView.images.test.tsx +++ b/packages/workspace-views/src/__tests__/DecisionsView.images.test.tsx @@ -175,6 +175,31 @@ describe('DecisionsView images (#1938)', () => { expect(host.image).not.toHaveBeenCalled(); }); + it('shows an http(s) image the browser refuses as not loaded, not as a broken image', () => { + // Mixed content inside an https IDE, a Tower URL answering 401 without the key, a 404 (spec 1963). + show({ bodyMarkdown: '![remote](https://example.com/gone.png) ![kept](https://example.com/ok.png)' }); + fireEvent.error(screen.getByRole('img', { name: 'remote' })); + const note = screen.getByText('Image not loaded').parentElement; + expect(note).toHaveTextContent('Image not loaded remote https://example.com/gone.png'); + expect(note).toHaveAttribute('title', 'The browser could not load this image from its address.'); + expect(screen.queryByRole('img', { name: 'remote' })).toBeNull(); + expect(screen.getByRole('img', { name: 'kept' })).toHaveAttribute('src', 'https://example.com/ok.png'); + expect(host.image).not.toHaveBeenCalled(); + }); + + it('stops listening for a remote image\'s error once the markdown changes', () => { + const { rerender } = show({ bodyMarkdown: '![first](https://example.com/one.png)' }); + const first = screen.getByRole('img', { name: 'first' }); + const parent = first.parentElement!; + mockUseDecisions.mockReturnValue({ state: { status: 'ready', document: makeDocument({ bodyMarkdown: '![second](https://example.com/two.png)' }) }, applyDocument: () => {} }); + rerender(); + expect(first.isConnected).toBe(false); + // A late error on the old, detached image finds no listener: it is not replaced by a note. + fireEvent.error(first); + expect(first.parentElement).toBe(parent); + expect(screen.getByRole('img', { name: 'second' })).toBeInTheDocument(); + }); + it('revokes the object URL when the markdown changes and when the card goes', async () => { const { rerender, unmount } = show({ bodyMarkdown: '![first](first.png)' }); await waitFor(() => expect(screen.getByRole('img', { name: 'first' })).toHaveAttribute('src', 'blob:http://dashboard.test/1')); diff --git a/packages/workspace-views/src/components/DecisionsView.tsx b/packages/workspace-views/src/components/DecisionsView.tsx index b243b73a9..d5735df79 100644 --- a/packages/workspace-views/src/components/DecisionsView.tsx +++ b/packages/workspace-views/src/components/DecisionsView.tsx @@ -191,7 +191,8 @@ function showNotLoaded(image: HTMLImageElement, source: string, reason: string) /** * The shared markdown renderer, with the view's rules applied to what it renders. An http(s) link * opens in a new tab and any other link loses its `href`, so the rule also holds for a - * middle-click, the context menu or the keyboard. An http(s) image loads as the browser would; any + * middle-click, the context menu or the keyboard. An http(s) image loads as the browser would, and + * one it refuses becomes a note; any * other image source is a workspace path the host's `image` loads and the view shows as an object * URL, revoked when the markdown changes or leaves, or it is a note saying the image was not loaded. */ @@ -215,6 +216,14 @@ function DecisionsMarkdown({ source }: { source: string }) { } const controller = new AbortController(); const objectUrls: string[] = []; + // An http(s) image the browser refuses (mixed content, a 401 or 404, not an image) is a note, + // not a broken image. Its error is queued as a task, so a listener added here, in the commit + // that inserted it, does not miss it. + for (const image of root.querySelectorAll(`img:not([${PARKED_SRC}])`)) { + const src = image.getAttribute('src') ?? ''; + if (!EXTERNAL_LINK_RE.test(src)) continue; + image.addEventListener('error', () => showNotLoaded(image, src, 'The browser could not load this image from its address.'), { once: true, signal: controller.signal }); + } for (const image of root.querySelectorAll(`img[${PARKED_SRC}]`)) { const written = image.getAttribute(PARKED_SRC) ?? ''; const path = workspaceImagePath(written); diff --git a/packages/workspace-views/src/styles.css b/packages/workspace-views/src/styles.css index 368ba1277..c2a561ba3 100644 --- a/packages/workspace-views/src/styles.css +++ b/packages/workspace-views/src/styles.css @@ -845,6 +845,9 @@ a.attention-row { .decisions-option-word { font-family: var(--codev-wv-font-mono, monospace); + /* It paints its own background, so it owns its text colour too: a host may colour every `code` + for that host's own code background (VS Code's webview does), which this background is not. */ + color: inherit; background: var(--codev-wv-bg-tertiary, #2a2a2a); padding: 0 4px; border-radius: 3px; From 550ba20ec38fcf4572f92054878018d654fa2acf Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:50:28 -0800 Subject: [PATCH 082/140] [Spec 1963][Phase: decisions_panel] docs: iteration 1 review responses --- .../1963-decisions_panel-iter1-rebuttals.md | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-rebuttals.md diff --git a/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-rebuttals.md b/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-rebuttals.md new file mode 100644 index 000000000..2b0967d84 --- /dev/null +++ b/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-rebuttals.md @@ -0,0 +1,102 @@ +# Phase 7 (`decisions_panel`), iteration 1: responses to the reviews + +The reviews: +- **Codex:** REQUEST_CHANGES, with one key issue. +- **Claude:** APPROVE, with one key observation and three minor notes. + +I checked each claim against the spec and the code, and the rendered claims in the harness. Codex's issue and Claude's observation were both real, and both are fixed. Claude's observation led to a wider contrast check, which found three more theme-mapping errors of mine; those are fixed too. + +The Windows run, dispatched after the reviews, failed in the new containment step. That was the test, not the code, and it is fixed. All of this is in `b758f8ffb`. + +## Codex + +### 1. A refused http(s) image stays a broken image: fixed + +**The claim holds.** +- The spec says that an http(s) image the browser refuses shows the existing "Image not loaded" note. Its examples are mixed content inside an https IDE, and a Tower URL answering 401 without the key. +- The shared view gave an `error` handler only to images loaded through the host. A direct remote image that failed was left as a broken ``. +- My rendered check did not catch this: its "refused" image was one Tower refuses, not one the browser fails to load. + +**Fixed, in `packages/workspace-views/src/components/DecisionsView.tsx`:** +- Every direct http(s) image gets an `error` listener that replaces it with the note, and its reason reads "The browser could not load this image from its address." +- The listener is registered with the effect's abort signal, so it is removed when the markdown changes or the card goes. +- The error event is queued as a task, so a listener added in the commit that inserted the image cannot miss it. + +**Tests:** +- Package: a refused remote image becomes the note, with its alt text, source and reason, while a working remote image beside it is untouched. +- Package: a late error on a detached old image does nothing. This test fails without the abort signal; I checked that by removing the signal. +- Harness: `main-2` now carries a remote image that the browser's route answers with 404. The check requires its note, *Image not loaded Gone board https://example.com/fixture/gone-board.svg*, and that no `` is left for it. The 404 image counts as a remote item image in the scenario 22 audit. The check is in `decisions-03-images.png`. + +**Effect on the dashboard:** the view is shared, so a refused remote image in the dashboard now shows the note too, instead of a broken image. That is the behaviour the spec describes. The Phase 6 snapshot comparison is unaffected, because no item in its fixture has a remote image. + +## Claude + +### Observation 1. Option words faint in Light High Contrast: fixed (they were invisible) + +**Confirmed in the screenshot.** In HC Light, `remote` and `local` were near-white on a light background. + +**Cause:** +- VS Code injects a default stylesheet into every webview that colours every `code` element with `--vscode-textPreformat-foreground`. That colour is tuned for VS Code's own code background. +- `.decisions-option-word` is a `code` element that paints its own background (`--codev-wv-bg-tertiary`) but set no text colour. +- In the dashboard the browser does not colour `code`, so the word inherited the page colour and read fine. + +**Fix, in `packages/workspace-views/src/styles.css`:** +- The rule now sets `color: inherit`, with a comment: it paints its own background, so it owns its text colour. +- In a browser that is a no-op, so the dashboard is unchanged. + +**Following "coverage is not contrast":** +- The rendered theme check no longer samples two elements; it measures **every visible text element in the panel (62)** in all four themes. +- Each is measured against its composited background: its own and its ancestors' backgrounds, alpha-blended, with `color-mix()` results parsed. +- It fails below 3:1. It requires 4.5:1 for the item id, Submit and an option word, and 3:1 for the Recommended badge. +- It lists every text under 4.5:1 in the evidence, so nothing between 3 and 4.5 hides behind the floor. + +That scan found three more mappings of mine in `vscode-theme.css` that were wrong for text: + +| Token | Was | Measured (Light Modern) | Now | +|---|---|---|---| +| `--codev-wv-fg-muted` | `--vscode-disabledForeground`, a disabled-control colour, drawn at half alpha | section labels 2.1:1 | `--vscode-input-placeholderForeground`, VS Code's readable muted grey | +| `--codev-wv-status-error` | `--vscode-errorForeground` (`#F85149` in Light Modern) | the stale-fingerprint refusal 2.8:1 | `--vscode-list-errorForeground`, with the old token as fallback | +| `--codev-wv-status-waiting` | `--vscode-charts-yellow` | "Image not loaded" 2.9:1 | `--vscode-list-warningForeground`, with the old token as fallback | + +- VS Code's list colours are the ones it uses for error and warning *text*. High-contrast themes leave them unset, so the fallbacks apply there; those themes measure 5.5:1 and up. +- The error, waiting and bug tints now mix from the same tokens, so a tint always matches its text. +- The theme unit test pins all three mappings, with the reason. + +**Final measurements (cycle 7):** + +| Theme | Lowest text | +|---|---| +| Dark Modern | 5.5 | +| Dark High Contrast | 6.6 | +| Light High Contrast | 5.5 | +| Light Modern | 4.1 | + +The only texts under 4.5:1 are in Light Modern: +- the section labels, at 4.3 (VS Code's own placeholder grey); +- the Recommended badge, at 4.1 (`charts.green`, 10 px uppercase with a border). + +I left both as VS Code's colours and recorded them in `verify-decisions.json`. + +**Not measured yet:** the Work view uses the implementing orange and the tag colours. It has no VS Code panel until Phase 8, and Phase 8's rendered check should run the same scan. + +### Note 2. `word`/`comment` unbounded in the guard: intentional, now documented + +Tower caps the ruling body (`MAX_RULE_BODY_BYTES`). It refuses a comment over `MAX_COMMENT_LENGTH` with `comment-too-long` and a reason the panel shows (`servers/decisions/routes.ts`, `splice.ts`). A host-side bound would instead drop a long comment silently, because the guard ignores a message it rejects. The guard's doc comment now says this. + +### Note 3. An aborted image leaves a never-settling promise: not a leak, now commented + +On abort, the request's resolver is deleted from `pending`. After that, nothing references the inner promise: the abort listener is `once`, and the outer promise has resolved. So the promise and its `then` reaction are garbage-collected, not retained for the panel's lifetime. A comment at the abort handler now says so. + +### Note 4. The Windows run must be dispatched and linked: done + +- The first run, on `36f7c4acd`, failed the new containment step, 4 of 39 tests. The other jobs passed: CLI tests, probes and install verification. Both causes were in the test: + - The test canonicalized its temp dir with the JS `realpathSync`, which keeps the runner's 8.3 short name (`RUNNER~1`). The code uses `fs.promises.realpath`, the native call, which gives the long name. The test now uses `realpathSync.native`. + - The "absolute path outside" case used `/etc/hosts`, which does not exist on Windows, so `not-found` was the right answer. The case now names the fixture's own outside file, which exists on every platform. +- The code under test is unchanged. The run is re-dispatched on `b758f8ffb` and linked in the PR. + +## Verification after the changes + +- **Harness:** `verify decisions` passed 15/15 on the final build (cycle 7). The evidence in `verification-phase7/` is replaced by that run. +- **apps/vscode:** 127 files, 1686 tests pass (1 Windows-only skip). Type-check is clean for the host and webview configs. Lint shows only the two existing `curly` warnings. +- **packages/workspace-views:** 195 tests pass. +- **apps/web:** 459 tests pass. From 80d8af29dba62b976ec7db3d9aabca9b279281db Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:51:42 -0800 Subject: [PATCH 083/140] chore(porch): 1963 implement re-iter (iter 2) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 6449b0ed4..8b1e95cb5 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -44,8 +44,8 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true +iteration: 2 +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -83,8 +83,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-workspace_views_package-iter1-claude.txt + - iteration: 1 + plan_phase: decisions_panel + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T12:32:01.351Z' +updated_at: '2026-11-24T12:51:42.492Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From f388b5a55ccca580b976c09cd0110d1c5f0566b4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:55:08 -0800 Subject: [PATCH 084/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 8b1e95cb5..a88d2de8a 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -96,7 +96,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T12:51:42.492Z' +updated_at: '2026-11-24T12:55:08.151Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From 70c7f360a7ceacec4b8f4939e320979643ed81c6 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:58:17 -0800 Subject: [PATCH 085/140] =?UTF-8?q?chore(porch):=201963=20advance=20plan?= =?UTF-8?q?=20phase=20=E2=86=92=20work=5Fpanel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index a88d2de8a..100b5e9b4 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -23,14 +23,14 @@ plan_phases: status: complete - id: decisions_panel title: Decisions panel in VS Code, its host bridge, and the hierarchy's Decisions entry - status: in_progress + status: complete - id: work_panel title: Work panel in VS Code, increment-2 verification - status: pending + status: in_progress - id: arrange_cockpit title: 'Arrange Cockpit: split, triggers, autoArrange, first-arrange notice, increment-3 verification' status: pending -current_plan_phase: decisions_panel +current_plan_phase: work_panel gates: spec-approval: status: approved @@ -44,8 +44,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: verification_harness @@ -96,7 +96,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T12:55:08.151Z' +updated_at: '2026-11-24T12:58:17.405Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -119,3 +119,5 @@ context_refreshes: - boundary: plan-phase:decisions_panel at: '2026-11-24T11:48:47.217Z' acknowledged_at: '2026-11-24T11:49:53.635Z' + - boundary: plan-phase:work_panel + at: '2026-11-24T12:58:17.405Z' From 20fe8eba8208c3fa71e3fb2a4c2a2faaeb2d32db Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 04:58:38 -0800 Subject: [PATCH 086/140] =?UTF-8?q?[Spec=201963][Phase:=20decisions=5Fpane?= =?UTF-8?q?l]=20docs:=20thread=20=E2=80=94=20iteration=202=20approvals,=20?= =?UTF-8?q?Windows=20re-run,=20notes=20carried=20to=20Phase=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/state/spir-1963_thread.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 379bf1676..dffcbc727 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -935,3 +935,24 @@ run. - The code under test is unchanged, and `resolveWorkspaceFile` has no production caller yet. - The other suites, CLI tests, probes and install verification passed. The run is re-dispatched after this commit. + +### Phase 7: review, iteration 2: approved (2026-11-24) + +- `porch done` (iteration 2) passed: build 15.4 s and tests 47.8 s, no skip, run once the load + was back under 6 (it spiked to 14.9). +- **Codex APPROVE:** both iteration-1 issues are addressed. +- **Claude APPROVE.** Two non-blocking notes, carried to Phase 8: + - the Light Modern Recommended badge is 4.1:1 at 10 px; give it a small bump if Phase 8 + touches badge styling; + - `resolveWorkspaceFile` gets its first caller in Phase 8. +- **Windows on `b758f8ffb`:** the containment step passes on Node 22 and 24, 39/39. Node 22 + passed everything. +- **Node 24 failed one test outside this branch's code:** `ide-server-stub.windows.test.ts` > + 'npm-style shim': "IDE server on port … was not stopped: the port query failed". + - This branch changes nothing in packages/codev except `issue-id-parity.test.ts`. The test + passed on Node 22 in the same run, and on main's run that morning. + - I re-ran only the failed job (attempt 2) to tell a flake from a failure. +- **Carried to Phase 8 (Work panel):** + - run the full-panel contrast scan on the Work view: implementing orange and the tag colours + are unmeasured; + - `resolveWorkspaceFile` gets its caller there. From 0bd7b0d6f7c6729001828560547c5b06715c51c8 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:05:26 -0800 Subject: [PATCH 087/140] =?UTF-8?q?[Spec=201963][Phase:=20decisions=5Fpane?= =?UTF-8?q?l]=20docs:=20thread=20=E2=80=94=20two=20pre-existing=20Windows?= =?UTF-8?q?=20flakes=20named?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codev/state/spir-1963_thread.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index dffcbc727..131348a5b 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -956,3 +956,10 @@ run. - run the full-panel contrast scan on the Work view: implementing orange and the tag colours are unmeasured; - `resolveWorkspaceFile` gets its caller there. +- **Windows attempt 2 (Node 24):** `ide-server-stub` 'npm-style shim' passed. A different test + failed: `pir-1233-session-launch-loop.test.ts` > "resumes the spawn-pinned session after an + unnatural exit…" (start.sh command failed). It passed in attempt 1, and the same file failed on + spir-1940's Windows run. + - Both are pre-existing flakes in code this branch does not touch. They are left running, named + under "Flaky tests" in PR #1971, and reported to the architect. + - **The review file's `## Flaky Tests` section must carry both.** From 6b340c6d4ba5ac4f228d78c2fb8ccd3e40d2a255 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:06:56 -0800 Subject: [PATCH 088/140] chore(porch): 1963 acknowledge context refresh --- codev/projects/1963-vscode-alternative-layout-seco/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index 100b5e9b4..e3ad1693c 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -96,7 +96,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T12:58:17.405Z' +updated_at: '2026-11-24T13:06:56.199Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' @@ -121,3 +121,4 @@ context_refreshes: acknowledged_at: '2026-11-24T11:49:53.635Z' - boundary: plan-phase:work_panel at: '2026-11-24T12:58:17.405Z' + acknowledged_at: '2026-11-24T13:06:56.199Z' From a9b148b021ab84956c847ab2ededd16a6e5bf9d1 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:17:08 -0800 Subject: [PATCH 089/140] [Spec 1963][Phase: work_panel] feat: Work panel in VS Code, fed from the overview cache - WorkPanels: one retained editor-area panel per window, restored after reload, pushing OverviewCache data and connection state (loading, last-known-good under a not-connected notice). Open -> builder terminal, + Shell -> New Shell, Refresh -> POST /api/overview/refresh then the cache, spec/plan/review links -> the file when its canonical path is inside the workspace, issue/PR links -> browser (http(s) only). No dashboard slots, so dropped affordances are absent. - The panel counts toward OverviewRefreshGate with the sidebar views. - single-panel.ts: the single-instance/serializer/visibility base both panels now share; DecisionsPanels moved onto it with its behaviour unchanged. - codev.openWork (palette everywhere, explains itself where not offered), onWebviewPanel:codev.work, dist/webview/work.{js,css}. - Docs: README Work and Decisions section, CHANGELOG, arch.md. --- apps/vscode/CHANGELOG.md | 1 + apps/vscode/README.md | 11 + apps/vscode/esbuild.js | 10 +- apps/vscode/esbuild.webview.cjs | 28 +- apps/vscode/package.json | 7 +- .../src/__tests__/cockpit-wiring.test.ts | 4 +- .../src/__tests__/contributes-cockpit.test.ts | 25 + .../src/__tests__/decisions-panel.test.ts | 1 + apps/vscode/src/__tests__/work-panel.test.ts | 480 ++++++++++++++++++ .../src/__tests__/work-webview-bundle.test.ts | 114 +++++ .../workspace-views-messages.test.ts | 54 +- .../workspace-views-webview-source.test.ts | 2 +- apps/vscode/src/extension.ts | 41 +- .../vscode/src/views/overview-refresh-gate.ts | 5 +- .../src/workspace-views/decisions-panel.ts | 119 +---- apps/vscode/src/workspace-views/messages.ts | 67 ++- .../src/workspace-views/single-panel.ts | 171 +++++++ .../src/workspace-views/webview/WorkApp.tsx | 63 +++ .../webview/__tests__/WorkApp.test.tsx | 193 +++++++ .../src/workspace-views/webview/work-main.tsx | 30 ++ apps/vscode/src/workspace-views/work-panel.ts | 172 +++++++ codev/resources/arch.md | 2 + 22 files changed, 1472 insertions(+), 128 deletions(-) create mode 100644 apps/vscode/src/__tests__/work-panel.test.ts create mode 100644 apps/vscode/src/__tests__/work-webview-bundle.test.ts create mode 100644 apps/vscode/src/workspace-views/single-panel.ts create mode 100644 apps/vscode/src/workspace-views/webview/WorkApp.tsx create mode 100644 apps/vscode/src/workspace-views/webview/__tests__/WorkApp.test.tsx create mode 100644 apps/vscode/src/workspace-views/webview/work-main.tsx create mode 100644 apps/vscode/src/workspace-views/work-panel.ts diff --git a/apps/vscode/CHANGELOG.md b/apps/vscode/CHANGELOG.md index 303e417b8..7d98ca81e 100644 --- a/apps/vscode/CHANGELOG.md +++ b/apps/vscode/CHANGELOG.md @@ -5,6 +5,7 @@ ### What's new - **Codev Cockpit: the whole fleet in one tree.** A new button below Codev opens Tower → workspaces → architects → builders → changed files. This window's workspace keeps every action of the Workspace and Agents views, and another workspace's rows open that workspace's window (#1963). +- **Work and Decisions in VS Code.** `Codev: Open Work` and `Codev: Open Decisions` (or the Cockpit's Decisions entry) open the dashboard's Work and Decisions views in the editor area, in your color theme. Rule on decisions, open a builder's terminal, start a shell, and follow issue, PR and spec links without leaving the editor (#1963). ### Fixes diff --git a/apps/vscode/README.md b/apps/vscode/README.md index e8f257fb7..66ea366b5 100644 --- a/apps/vscode/README.md +++ b/apps/vscode/README.md @@ -67,6 +67,17 @@ Dormant (2) The Cockpit reads what the Codev and Tower views already fetch. It adds no poll or stream of its own. +## Work and Decisions + +The dashboard's **Work** and **Decisions** views open in the editor area, for this window's workspace: + +- **Codev: Open Work** shows builders, Needs Attention, Backlog and Recently Closed. A builder's *Open* shows its terminal, *+ Shell* opens a new Tower shell, and *Refresh* re-reads the overview from Tower. Issue and PR links open in your browser; *spec*, *plan* and *review* links open the file in an editor. +- **Codev: Open Decisions**, or the *Decisions* entry under this window's workspace in the Cockpit, lets you rule on pending decisions as in the dashboard. Item images load inside the panel; click one to see it full size. A workspace without a decisions file shows how to start one (`afx decisions init`). +- Each panel is one per window: opening it again brings it forward. It comes back after a window reload, and follows your color theme, including high contrast. A Decisions draft survives the panel being hidden or moved, but not a window reload. +- While Tower is not connected, each panel keeps what it last showed, under a notice, and recovers when Tower returns. +- Neither is offered in a builder-worktree window or a window with no Codev workspace. There, the commands say why. +- Left out from the dashboard: *Open Files & Shells* (VS Code's editor tabs and terminal list do this), the *Files* panel (the Explorer does) and the tip of the day. + ## Builder actions (right-click) Right-click any builder in the Agents view for three grouped action menus: diff --git a/apps/vscode/esbuild.js b/apps/vscode/esbuild.js index 9dee422cc..2f0f6dcbf 100644 --- a/apps/vscode/esbuild.js +++ b/apps/vscode/esbuild.js @@ -1,5 +1,5 @@ const esbuild = require("esbuild"); -const { decisionsWebviewConfig } = require('./esbuild.webview.cjs'); +const { decisionsWebviewConfig, workWebviewConfig } = require('./esbuild.webview.cjs'); const production = process.argv.includes('--production'); const watch = process.argv.includes('--watch'); @@ -90,8 +90,14 @@ const decisionsPanelWebviewConfig = { plugins: [esbuildProblemMatcherPlugin], }; +/** The Work panel's webview bundle (Spec 1963): `dist/webview/work.{js,css}`. */ +const workPanelWebviewConfig = { + ...workWebviewConfig({ production }), + plugins: [esbuildProblemMatcherPlugin], +}; + async function main() { - const configs = [extensionConfig, webviewConfig, contextualPanelWebviewConfig, decisionsPanelWebviewConfig]; + const configs = [extensionConfig, webviewConfig, contextualPanelWebviewConfig, decisionsPanelWebviewConfig, workPanelWebviewConfig]; if (watch) { const contexts = await Promise.all(configs.map((c) => esbuild.context(c))); await Promise.all(contexts.map((c) => c.watch())); diff --git a/apps/vscode/esbuild.webview.cjs b/apps/vscode/esbuild.webview.cjs index a5c73145c..81e56c5b9 100644 --- a/apps/vscode/esbuild.webview.cjs +++ b/apps/vscode/esbuild.webview.cjs @@ -1,29 +1,33 @@ /** * The Work and Decisions panels' webview bundles (Spec 1963), as esbuild options. A module of its - * own so `esbuild.js` builds from it and `decisions-webview-bundle.test.ts` builds the very same - * bundle, with no `dist` from an earlier build: CI runs the unit tests without one. + * own so `esbuild.js` builds from it and the bundle tests (`decisions-webview-bundle.test.ts`, + * `work-webview-bundle.test.ts`) build the very same bundles, with no `dist` from an earlier build: + * CI runs the unit tests without one. * * - `jsx: 'automatic'` is explicit: these are the first TSX sources under `apps/vscode`, and * esbuild would otherwise read the nearest `tsconfig.json`, which sets no `jsx`; - * - the imported stylesheets (the shared views', the markdown theme and `vscode-theme.css`) are - * emitted next to the script as one `.css`; + * - the imported stylesheets (the shared views', `vscode-theme.css` and, for Decisions, the + * markdown theme) are emitted next to the script as one `.css`; * - `process.env.NODE_ENV` is defined so React's dev/prod branch resolves in the browser. */ const path = require('node:path'); -/** @param {{ production: boolean }} options @returns {import('esbuild').BuildOptions} */ -function decisionsWebviewConfig({ production }) { +/** + * One panel's bundle: `src/workspace-views/webview/-main.tsx` → `dist/webview/.{js,css}`. + * @param {string} name @param {{ production: boolean }} options @returns {import('esbuild').BuildOptions} + */ +function workspaceViewWebviewConfig(name, { production }) { return { absWorkingDir: __dirname, - entryPoints: ['src/workspace-views/webview/decisions-main.tsx'], + entryPoints: [`src/workspace-views/webview/${name}-main.tsx`], bundle: true, format: 'iife', minify: production, sourcemap: !production, sourcesContent: false, platform: 'browser', - outfile: 'dist/webview/decisions.js', + outfile: `dist/webview/${name}.js`, loader: { '.css': 'css' }, jsx: 'automatic', tsconfig: path.join(__dirname, 'tsconfig.webview.json'), @@ -32,4 +36,10 @@ function decisionsWebviewConfig({ production }) { }; } -module.exports = { decisionsWebviewConfig }; +/** The Decisions panel's bundle. @param {{ production: boolean }} options */ +const decisionsWebviewConfig = (options) => workspaceViewWebviewConfig('decisions', options); + +/** The Work panel's bundle. @param {{ production: boolean }} options */ +const workWebviewConfig = (options) => workspaceViewWebviewConfig('work', options); + +module.exports = { decisionsWebviewConfig, workWebviewConfig }; diff --git a/apps/vscode/package.json b/apps/vscode/package.json index 3a09ad6a1..84268dcbe 100644 --- a/apps/vscode/package.json +++ b/apps/vscode/package.json @@ -43,7 +43,8 @@ "workspaceContains:.codev", "workspaceContains:codev", "onStartupFinished", - "onWebviewPanel:codev.decisions" + "onWebviewPanel:codev.decisions", + "onWebviewPanel:codev.work" ], "main": "./dist/extension.js", "capabilities": { @@ -107,6 +108,10 @@ "title": "Codev: Open Decisions", "icon": "$(law)" }, + { + "command": "codev.openWork", + "title": "Codev: Open Work" + }, { "command": "codev.helloWorld", "title": "Codev: Show Connection State" diff --git a/apps/vscode/src/__tests__/cockpit-wiring.test.ts b/apps/vscode/src/__tests__/cockpit-wiring.test.ts index 2aae1c000..5f22c1da1 100644 --- a/apps/vscode/src/__tests__/cockpit-wiring.test.ts +++ b/apps/vscode/src/__tests__/cockpit-wiring.test.ts @@ -467,8 +467,8 @@ describe('the periodic overview refresh counts the Cockpit', () => { } }); - it('extension.ts gates on the four list views and the Cockpit', () => { - expect(EXT_SRC).toMatch(/new OverviewRefreshGate\(\s*\[buildersView, pullRequestsView, backlogView, recentlyClosedView, cockpitView\],/); + it('extension.ts gates on the four list views, the Cockpit and the Work panel', () => { + expect(EXT_SRC).toMatch(/new OverviewRefreshGate\(\s*\[buildersView, pullRequestsView, backlogView, recentlyClosedView, cockpitView, workPanels\],/); expect(EXT_SRC).toMatch(/\.\.\.overviewRefreshGate\.wire\(\)/); }); }); diff --git a/apps/vscode/src/__tests__/contributes-cockpit.test.ts b/apps/vscode/src/__tests__/contributes-cockpit.test.ts index 4b7f1cf4a..de44f9c77 100644 --- a/apps/vscode/src/__tests__/contributes-cockpit.test.ts +++ b/apps/vscode/src/__tests__/contributes-cockpit.test.ts @@ -118,3 +118,28 @@ describe('the Decisions panel (Phase 7)', () => { expect(ignored.some(line => line.startsWith('dist'))).toBe(false); }); }); + +describe('the Work panel (Phase 8)', () => { + const commands = PKG.contributes.commands as Array<{ command: string; title: string; icon?: string }>; + + it('declares Codev: Open Work, and keeps it in the command palette', () => { + expect(commands.find(c => c.command === 'codev.openWork')).toEqual({ command: 'codev.openWork', title: 'Codev: Open Work' }); + expect((menus.commandPalette ?? []).some(m => m.command === 'codev.openWork')).toBe(false); + }); + + it('activates to restore the panel after a reload', () => { + expect(PKG.activationEvents).toContain('onWebviewPanel:codev.work'); + }); + + it('registers the command and the serializer for the panel in extension.ts', () => { + expect(EXT_SRC).toMatch(/regCli\('codev\.openWork', \(\) => workPanels\.show\(\)\)/); + expect(EXT_SRC).toMatch(/registerWebviewPanelSerializer\(WORK_VIEW_TYPE, workPanels\)/); + }); + + it("decides availability from the window's folders, as Decisions does", () => { + const wiring = EXT_SRC.slice(EXT_SRC.indexOf('new WorkPanels({'), EXT_SRC.indexOf('registerWebviewPanelSerializer(WORK_VIEW_TYPE')); + expect(wiring).toMatch(/unavailableReason: \(\) => workspaceViewUnavailableReason\('Work', \{/); + expect(wiring).toMatch(/workspacePath: detectWorkspacePath\(\),/); + expect(wiring).not.toMatch(/getWorkspacePath\(\)/); + }); +}); diff --git a/apps/vscode/src/__tests__/decisions-panel.test.ts b/apps/vscode/src/__tests__/decisions-panel.test.ts index ca5dab763..6d8431370 100644 --- a/apps/vscode/src/__tests__/decisions-panel.test.ts +++ b/apps/vscode/src/__tests__/decisions-panel.test.ts @@ -72,6 +72,7 @@ const showInformationMessage = vi.fn(); const openExternal = vi.fn(async (_uri: unknown) => true); vi.mock('vscode', () => ({ + EventEmitter: class extends FakeEmitter { dispose() {} }, window: { createWebviewPanel, showInformationMessage }, env: { openExternal }, ViewColumn: { Active: -1 }, diff --git a/apps/vscode/src/__tests__/work-panel.test.ts b/apps/vscode/src/__tests__/work-panel.test.ts new file mode 100644 index 000000000..314bebe7c --- /dev/null +++ b/apps/vscode/src/__tests__/work-panel.test.ts @@ -0,0 +1,480 @@ +/** + * Spec 1963 scenarios 5, 6, 17 and 22 (host side): the Work panel. + * - One panel per window: opening again reveals it; where it is not offered, the command says why. + * - Its visibility counts toward the periodic overview refresh: with only the Work panel visible + * the timer runs, and with it hidden or closed the timer stops. + * - The overview is pushed from the cache on `ready`, on every overview change and on every + * connection change: loading, last-known-good, and the not-connected notice. + * - Each kept dashboard action does what the spec's mapping table says; a refused artifact path, a + * non-http(s) URL and an unknown builder are not acted on; a malformed message is ignored. + * - Nothing is posted after the panel closed. A reload restores the panel through its serializer. + * - No message the host posts carries the Tower key, Tower's URL or its port. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { OverviewBuilder, OverviewData } from '@cluesmith/codev-types'; + +type Listener = (event: T) => void; + +class FakeEmitter { + private listeners: Array> = []; + readonly event = (listener: Listener) => { + this.listeners.push(listener); + return { dispose: () => { this.listeners = this.listeners.filter(l => l !== listener); } }; + }; + fire(event: T) { for (const l of [...this.listeners]) { l(event); } } + get count() { return this.listeners.length; } +} + +class FakePanel { + visible = true; + disposed = false; + readonly posted: unknown[] = []; + readonly received = new FakeEmitter(); + readonly viewState = new FakeEmitter(); + readonly disposal = new FakeEmitter(); + readonly reveal = vi.fn(); + readonly webview = { + html: '', + options: {} as unknown, + cspSource: 'https://webview.vscode-cdn.net', + asWebviewUri: (uri: { path: string }) => ({ toString: () => `https://webview.vscode-cdn.net${uri.path}` }), + postMessage: vi.fn(async (message: unknown) => { + if (this.disposed) { throw new Error('Webview is disposed'); } + this.posted.push(message); + return true; + }), + onDidReceiveMessage: this.received.event, + }; + readonly onDidChangeViewState = this.viewState.event; + readonly onDidDispose = this.disposal.event; + dispose() { + if (this.disposed) { return; } + this.disposed = true; + this.disposal.fire(); + } + /** The webview posts `message` to the host; resolves once the host has handled it. */ + async send(message: unknown) { + this.received.fire(message); + await new Promise(resolve => setTimeout(resolve, 0)); + } + setVisible(visible: boolean) { + this.visible = visible; + this.viewState.fire(); + } +} + +const panels: FakePanel[] = []; +const createWebviewPanel = vi.fn((_viewType: string, _title: string, _column: number, _options: unknown) => { + const panel = new FakePanel(); + panels.push(panel); + return panel; +}); +const showInformationMessage = vi.fn(); +const openExternal = vi.fn(async (_uri: unknown) => true); + +vi.mock('vscode', () => ({ + EventEmitter: class extends FakeEmitter { dispose() {} }, + window: { createWebviewPanel, showInformationMessage }, + env: { openExternal }, + ViewColumn: { Active: -1 }, + Uri: { + parse: (value: string) => ({ toString: () => value }), + joinPath: (base: { path: string }, ...parts: string[]) => ({ path: [base.path, ...parts].join('/') }), + }, +})); + +const { WorkPanels, workOverviewState } = await import('../workspace-views/work-panel.js'); +const { OverviewRefreshGate } = await import('../views/overview-refresh-gate.js'); +const { NOT_CONNECTED_MESSAGE } = await import('../workspace-views/decisions-bridge.js'); +const { TowerClient } = await import('@cluesmith/codev-sdk/tower-client'); +type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting'; + +const EXTENSION = { path: '/ext' }; + +function builder(id: string): OverviewBuilder { + return { + id, + issueId: id.replace(/\D/g, '') || null, + issueTitle: `Builder ${id}`, + phase: 'implement', + mode: 'strict', + gates: {}, + worktreePath: `/work/codev/.builders/${id}`, + protocol: 'spir', + planPhases: [], + progress: 40, + blocked: null, + startedAt: null, + idleMs: 0, + } as unknown as OverviewBuilder; +} + +function overviewOf(...builders: OverviewBuilder[]): OverviewData { + return { builders, pendingPRs: [], backlog: [], recentlyClosed: [] } as unknown as OverviewData; +} + +function setup(opts: { reason?: string | null; data?: OverviewData | null; state?: ConnectionState; root?: string | null } = {}) { + const overviewChanged = new FakeEmitter(); + const stateChanged = new FakeEmitter(); + const cache = { data: opts.data === undefined ? overviewOf(builder('spir-1963')) : opts.data }; + const connection = { state: opts.state ?? 'connected' as ConnectionState }; + const calls: string[] = []; + const client = { refreshOverview: vi.fn(async () => { calls.push('tower refresh'); return true; }) }; + const overview = { + getData: () => cache.data, + onDidChange: overviewChanged.event, + refresh: vi.fn(async () => { calls.push('cache refresh'); }), + }; + const actions = { + openBuilder: vi.fn(async (_id: string) => 'spir-1963'), + newShell: vi.fn(async () => undefined), + openFile: vi.fn(async (_path: string) => undefined), + warn: vi.fn(), + }; + const log = vi.fn(); + const reason = { value: opts.reason ?? null }; + const manager = new WorkPanels({ + extensionUri: EXTENSION as never, + overview, + connection: { + getState: () => connection.state, + onStateChange: stateChanged.event, + getClient: () => client, + }, + actions, + workspacePath: () => (opts.root === undefined ? '/work/codev' : opts.root), + unavailableReason: () => reason.value, + log, + }); + return { + manager, cache, connection, client, overview, actions, log, reason, calls, + setData(data: OverviewData | null) { cache.data = data; overviewChanged.fire(); }, + setState(state: ConnectionState) { connection.state = state; stateChanged.fire(state); }, + overviewChanged, stateChanged, + }; +} + +beforeEach(() => { + panels.length = 0; + createWebviewPanel.mockClear(); + showInformationMessage.mockClear(); + openExternal.mockClear(); +}); + +describe('opening the panel', () => { + it('creates one retained, script-enabled panel in the active group, loading only the Work bundle under dist', () => { + const { manager } = setup(); + manager.show(); + expect(createWebviewPanel).toHaveBeenCalledTimes(1); + expect(createWebviewPanel).toHaveBeenCalledWith('codev.work', 'Work', -1, { + enableScripts: true, retainContextWhenHidden: true, localResourceRoots: [{ path: '/ext/dist' }], + }); + const { html } = panels[0].webview; + expect(html).toContain('src="https://webview.vscode-cdn.net/ext/dist/webview/work.js"'); + expect(html).toContain('href="https://webview.vscode-cdn.net/ext/dist/webview/work.css"'); + expect(html).toContain("default-src 'none'"); + expect(html).not.toContain('connect-src'); + expect(manager.panel).toBe(panels[0]); + }); + + it('reveals the open panel instead of creating a second one, and never reloads it', () => { + const { manager } = setup(); + manager.show(); + const html = panels[0].webview.html; + manager.show(); + expect(createWebviewPanel).toHaveBeenCalledTimes(1); + expect(panels[0].reveal).toHaveBeenCalledTimes(1); + expect(panels[0].webview.html).toBe(html); + }); + + it('says why, and opens nothing, where Work is not offered', () => { + const { manager } = setup({ reason: 'Codev: Work is not offered in a builder-worktree window.' }); + manager.show(); + expect(createWebviewPanel).not.toHaveBeenCalled(); + expect(showInformationMessage).toHaveBeenCalledWith('Codev: Work is not offered in a builder-worktree window.'); + }); +}); + +describe('the periodic overview refresh counts the Work panel (scenario 5)', () => { + it('reports its visibility, and fires on open, show, hide and close', () => { + const { manager } = setup(); + const fired = vi.fn(); + manager.onDidChangeVisibility(fired); + expect(manager.visible).toBe(false); + manager.show(); + expect(manager.visible).toBe(true); + expect(fired).toHaveBeenCalledTimes(1); + panels[0].setVisible(false); + expect(manager.visible).toBe(false); + panels[0].setVisible(true); + panels[0].dispose(); + expect(manager.visible).toBe(false); + expect(fired).toHaveBeenCalledTimes(4); + }); + + it('runs the timer with only the Work panel visible, and stops it when hidden or closed', () => { + vi.useFakeTimers(); + try { + const { manager } = setup(); + const tick = vi.fn(); + const resume = vi.fn(); + const hiddenTree = { visible: false, onDidChangeVisibility: new FakeEmitter().event }; + const gate = new OverviewRefreshGate([hiddenTree, manager], () => 60, tick, resume); + gate.wire(); + gate.reconcile(); + expect(gate.isRunning()).toBe(false); + + manager.show(); + expect(gate.isRunning()).toBe(true); + expect(resume).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(120_000); + expect(tick).toHaveBeenCalledTimes(2); + + panels[0].setVisible(false); + expect(gate.isRunning()).toBe(false); + panels[0].setVisible(true); + expect(gate.isRunning()).toBe(true); + panels[0].dispose(); + expect(gate.isRunning()).toBe(false); + gate.dispose(); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('what the Work view is shown', () => { + const DATA = overviewOf(builder('spir-1963')); + + it.each<[string, OverviewData | null, ConnectionState, unknown]>([ + ['loading while connecting', null, 'connecting', null], + ['loading while connected, before the first overview', null, 'connected', null], + ['the notice with nothing to keep while disconnected', null, 'disconnected', { data: null, error: NOT_CONNECTED_MESSAGE }], + ['the notice with nothing to keep while reconnecting', null, 'reconnecting', { data: null, error: NOT_CONNECTED_MESSAGE }], + ['the overview while connected', DATA, 'connected', { data: DATA, error: null }], + ['the last overview under the notice while reconnecting', DATA, 'reconnecting', { data: DATA, error: NOT_CONNECTED_MESSAGE }], + ['the last overview under the notice while disconnected', DATA, 'disconnected', { data: DATA, error: NOT_CONNECTED_MESSAGE }], + ['the last overview under the notice while connecting again', DATA, 'connecting', { data: DATA, error: NOT_CONNECTED_MESSAGE }], + ])('%s', (_label, data, state, expected) => { + expect(workOverviewState(data, state)).toEqual(expected); + }); + + it('is pushed on ready, on every overview change and on every connection change', async () => { + const harness = setup({ data: null, state: 'connecting' }); + harness.manager.show(); + const panel = panels[0]; + await panel.send({ type: 'ready' }); + harness.setState('connected'); + harness.setData(DATA); + harness.setState('reconnecting'); + harness.setState('connected'); + expect(panel.posted).toEqual([ + { type: 'work/overview', overview: null }, + { type: 'work/overview', overview: null }, + { type: 'work/overview', overview: { data: DATA, error: null } }, + { type: 'work/overview', overview: { data: DATA, error: NOT_CONNECTED_MESSAGE } }, + { type: 'work/overview', overview: { data: DATA, error: null } }, + ]); + }); + + it('posts nothing after the panel closed, and stops listening', async () => { + const harness = setup(); + harness.manager.show(); + const panel = panels[0]; + panel.dispose(); + harness.setData(DATA); + harness.setState('reconnecting'); + expect(panel.webview.postMessage).not.toHaveBeenCalled(); + expect(harness.overviewChanged.count).toBe(0); + expect(harness.stateChanged.count).toBe(0); + expect(panel.received.count).toBe(0); + expect(panel.viewState.count).toBe(0); + }); +}); + +describe('the mapped actions (scenario 17)', () => { + it("Open opens the builder's terminal", async () => { + const { manager, actions } = setup(); + manager.show(); + await panels[0].send({ type: 'work/open-builder', builderId: 'spir-1963' }); + expect(actions.openBuilder).toHaveBeenCalledWith('spir-1963'); + }); + + it('Open does nothing for a builder the overview does not show', async () => { + const { manager, actions, log } = setup(); + manager.show(); + await panels[0].send({ type: 'work/open-builder', builderId: 'main' }); + expect(actions.openBuilder).not.toHaveBeenCalled(); + expect(log).toHaveBeenCalledWith(expect.stringContaining('did not open builder main')); + }); + + it('+ Shell runs New Shell', async () => { + const { manager, actions } = setup(); + manager.show(); + await panels[0].send({ type: 'work/new-shell' }); + expect(actions.newShell).toHaveBeenCalledTimes(1); + }); + + it("Refresh drops Tower's overview cache, then re-reads this window's overview", async () => { + const { manager, calls } = setup(); + manager.show(); + await panels[0].send({ type: 'work/refresh' }); + expect(calls).toEqual(['tower refresh', 'cache refresh']); + }); + + it('Refresh asks nothing of Tower while not connected', async () => { + const { manager, client, overview } = setup({ state: 'reconnecting' }); + manager.show(); + await panels[0].send({ type: 'work/refresh' }); + expect(client.refreshOverview).not.toHaveBeenCalled(); + expect(overview.refresh).toHaveBeenCalledTimes(1); + }); + + it('opens http(s) links in the browser and refuses every other scheme', async () => { + const { manager, log } = setup(); + manager.show(); + await panels[0].send({ type: 'open-external', url: 'https://github.com/cluesmith/codev/issues/1963' }); + for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'vscode://cluesmith.codev-vscode/x', 'command:workbench.action.reloadWindow']) { + await panels[0].send({ type: 'open-external', url }); + } + expect(openExternal.mock.calls.map(([uri]) => String(uri))).toEqual(['https://github.com/cluesmith/codev/issues/1963']); + expect(log).toHaveBeenCalledTimes(4); + }); + + it('ignores a malformed message, saying so in the log', async () => { + const { manager, actions, overview, log } = setup(); + manager.show(); + for (const bad of [null, 'refresh', { type: 'work/open-builder' }, { type: 'work/open-builder', builderId: '' }, + { type: 'work/open-artifact', path: 'a\0b' }, { type: 'work/open-artifact', path: 'x'.repeat(5000) }, { type: 'work/delete' }]) { + await panels[0].send(bad); + } + expect(actions.openBuilder).not.toHaveBeenCalled(); + expect(actions.openFile).not.toHaveBeenCalled(); + expect(overview.refresh).not.toHaveBeenCalled(); + expect(panels[0].posted).toEqual([]); + expect(log).toHaveBeenCalledTimes(7); + }); +}); + +describe('artifact links open a workspace file, and nothing outside it', () => { + let base: string; + let root: string; + + beforeEach(() => { + base = realpathSync.native(mkdtempSync(join(tmpdir(), 'codev-work-panel-'))); + root = join(base, 'ws'); + mkdirSync(join(root, 'codev', 'specs'), { recursive: true }); + writeFileSync(join(root, 'codev', 'specs', '1963-cockpit.md'), '# spec'); + writeFileSync(join(base, 'outside.md'), '# outside'); + symlinkSync(join(base, 'outside.md'), join(root, 'codev', 'specs', 'escape.md')); + }); + + afterEach(() => { + rmSync(base, { recursive: true, force: true }); + }); + + it('opens a spec by its workspace-relative path, at its canonical location', async () => { + const { manager, actions } = setup({ root }); + manager.show(); + await panels[0].send({ type: 'work/open-artifact', path: 'codev/specs/1963-cockpit.md' }); + expect(actions.openFile).toHaveBeenCalledWith(join(root, 'codev', 'specs', '1963-cockpit.md')); + expect(actions.warn).not.toHaveBeenCalled(); + }); + + it.each([ + ['a .. escape', '../outside.md'], + ['an absolute path outside', 'OUTSIDE'], + ['a symlink that leads outside', 'codev/specs/escape.md'], + ])('refuses %s, and says so', async (_label, requested) => { + const path = requested === 'OUTSIDE' ? join(base, 'outside.md') : requested; + const { manager, actions } = setup({ root }); + manager.show(); + await panels[0].send({ type: 'work/open-artifact', path }); + expect(actions.openFile).not.toHaveBeenCalled(); + expect(actions.warn).toHaveBeenCalledWith(`Codev: ${path} was not opened: it is outside this workspace.`); + }); + + it('says a missing file was not found', async () => { + const { manager, actions } = setup({ root }); + manager.show(); + await panels[0].send({ type: 'work/open-artifact', path: 'codev/specs/gone.md' }); + expect(actions.openFile).not.toHaveBeenCalled(); + expect(actions.warn).toHaveBeenCalledWith('Codev: codev/specs/gone.md was not found in this workspace.'); + }); +}); + +describe('restore after a window reload', () => { + it('adopts the restored panel: it renders the view and answers its webview', async () => { + const { manager } = setup(); + const restored = new FakePanel(); + await manager.deserializeWebviewPanel(restored as never); + expect(restored.webview.options).toEqual({ enableScripts: true, localResourceRoots: [{ path: '/ext/dist' }] }); + expect(restored.webview.html).toContain('work.js'); + await restored.send({ type: 'ready' }); + expect(restored.posted).toHaveLength(1); + expect(manager.visible).toBe(true); + manager.show(); + expect(createWebviewPanel).not.toHaveBeenCalled(); + expect(restored.reveal).toHaveBeenCalledTimes(1); + }); + + it('closes a second restored panel, and one restored where Work is not offered', async () => { + const { manager, reason } = setup(); + const first = new FakePanel(); + const second = new FakePanel(); + await manager.deserializeWebviewPanel(first as never); + await manager.deserializeWebviewPanel(second as never); + expect(first.disposed).toBe(false); + expect(second.disposed).toBe(true); + + first.dispose(); + reason.value = 'Codev: Work needs a Codev workspace, and this window has none.'; + const third = new FakePanel(); + await manager.deserializeWebviewPanel(third as never); + expect(third.disposed).toBe(true); + }); +}); + +describe('the Tower key, URL and port never reach the webview (scenario 22, state)', () => { + it('across a refresh and the overview it pushes', async () => { + const KEY = 'tower-key-1963-do-not-leak'; + const PORT = 18764; + const requests: Array<{ url: string; headers: Record }> = []; + const fetchFn = vi.fn(async (url: string, init: RequestInit) => { + requests.push({ url, headers: init.headers as Record }); + const text = JSON.stringify({ ok: true }); + return { ok: true, status: 200, headers: new Headers({ 'Content-Type': 'application/json' }), text: async () => text, json: async () => ({ ok: true }) } as unknown as Response; + }); + const client = new TowerClient({ port: PORT, getAuthKey: () => KEY, fetchFn: fetchFn as never }); + const changed = new FakeEmitter(); + const data = overviewOf(builder('spir-1963')); + const manager = new WorkPanels({ + extensionUri: EXTENSION as never, + overview: { getData: () => data, onDidChange: changed.event, refresh: async () => { changed.fire(); } }, + connection: { getState: () => 'connected', onStateChange: new FakeEmitter().event, getClient: () => client }, + actions: { openBuilder: vi.fn(), newShell: vi.fn(), openFile: vi.fn(), warn: vi.fn() }, + workspacePath: () => '/work/codev', + unavailableReason: () => null, + log: vi.fn(), + }); + manager.show(); + const panel = panels[0]; + await panel.send({ type: 'ready' }); + await panel.send({ type: 'work/refresh' }); + + // The host did make a keyed request to Tower's port... + expect(requests).toHaveLength(1); + expect(requests[0].url).toBe(`http://localhost:${PORT}/api/overview/refresh`); + expect(requests[0].headers['codev-tower-key']).toBe(KEY); + // ...and none of it reached the webview. + expect(panel.posted.map(m => (m as { type: string }).type)).toEqual(['work/overview', 'work/overview']); + const everything = JSON.stringify(panel.posted) + panel.webview.html; + for (const secret of [KEY, 'codev-tower-key', `localhost:${PORT}`, String(PORT)]) { + expect(everything, secret).not.toContain(secret); + } + }); +}); diff --git a/apps/vscode/src/__tests__/work-webview-bundle.test.ts b/apps/vscode/src/__tests__/work-webview-bundle.test.ts new file mode 100644 index 000000000..06d4c9fce --- /dev/null +++ b/apps/vscode/src/__tests__/work-webview-bundle.test.ts @@ -0,0 +1,114 @@ +/** + * Spec 1963: the Work panel's webview bundle, built the way `esbuild.js` builds it (from the same + * options in `esbuild.webview.cjs`) and booted in a jsdom window of its own with a fake + * `acquireVsCodeApi`, as `decisions-webview-bundle.test.ts` boots the Decisions bundle. + * Unit tests import the sources; this is what proves the shipped bundle starts: it mounts, says it + * is ready, renders the overview the extension host pushes, and posts its actions. It also holds the + * bundle to one copy of React and to emitting its stylesheet. + * + * Built into a temporary directory, never `dist`: CI runs the unit tests without a build. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { build, type Metafile } from 'esbuild'; + +const require = createRequire(import.meta.url); +const { workWebviewConfig } = require('../../esbuild.webview.cjs') as { + workWebviewConfig: (options: { production: boolean }) => Parameters[0]; +}; + +/** The part of a jsdom window this test uses (the package ships no types of its own). */ +interface BundleElement { + textContent: string | null; + click(): void; +} +interface BundleWindow { + eval(code: string): unknown; + dispatchEvent(event: unknown): boolean; + MessageEvent: new (type: string, init: { data: unknown }) => unknown; + document: { + querySelector(selector: string): BundleElement | null; + querySelectorAll(selector: string): ArrayLike; + }; + acquireVsCodeApi?: () => { postMessage(message: unknown): void }; + close(): void; +} +const { JSDOM } = require('jsdom') as { + JSDOM: new (html: string, options: { runScripts: 'outside-only'; pretendToBeVisual: boolean }) => { window: BundleWindow }; +}; + +const OVERVIEW = { + builders: [{ + id: 'spir-1963', issueId: '1963', issueTitle: 'Cockpit layout', phase: 'implement', protocolPhase: 'implement', mode: 'strict', + gates: {}, worktreePath: '/ws/.builders/spir-1963', roleId: 'builder-spir-1963', protocol: 'spir', planPhases: [], progress: 40, + blocked: null, blockedGate: null, blockedSince: null, startedAt: null, idleMs: 0, lastDataAt: null, spawnedByArchitect: 'main', + prReady: false, area: '', + }], + pendingPRs: [], + backlog: [], + recentlyClosed: [], + architects: [{ name: 'main' }], +}; + +let outDir: string; +let metafile: Metafile; +let win: BundleWindow; +const posted: unknown[] = []; + +const fromHost = (data: unknown) => win.dispatchEvent(new win.MessageEvent('message', { data })); + +beforeAll(async () => { + outDir = mkdtempSync(join(tmpdir(), 'codev-work-bundle-')); + const result = await build({ + ...workWebviewConfig({ production: false }), + outfile: join(outDir, 'work.js'), + sourcemap: false, + metafile: true, + }); + metafile = result.metafile!; + const script = readFileSync(join(outDir, 'work.js'), 'utf8'); + + win = new JSDOM('
', { runScripts: 'outside-only', pretendToBeVisual: true }).window; + // Copied out of the window's realm, as postMessage's structured clone would. + win.acquireVsCodeApi = () => ({ postMessage: (message: unknown) => posted.push(JSON.parse(JSON.stringify(message))) }); + win.eval(script); +}, 60_000); + +afterAll(() => { + win?.close(); + if (outDir) { rmSync(outDir, { recursive: true, force: true }); } +}); + +describe('the Work webview bundle', () => { + it('mounts in its loading state and tells the extension host it is ready', async () => { + expect(posted).toEqual([{ type: 'ready' }]); + await vi.waitFor(() => expect(win.document.querySelector('.work-loading')?.textContent).toBe('Loading...')); + }); + + it('renders the overview the extension host pushes, and posts Open', async () => { + fromHost({ type: 'work/overview', overview: { data: OVERVIEW, error: null } }); + await vi.waitFor(() => expect(win.document.querySelector('.builder-table')?.textContent).toContain('Cockpit layout')); + win.document.querySelector('.builder-row-open')!.click(); + expect(posted).toContainEqual({ type: 'work/open-builder', builderId: 'spir-1963' }); + }); + + it('bundles one copy of React and of React DOM', () => { + const copies = (name: string) => new Set(Object.keys(metafile.inputs) + .map(input => input.replace(/\\/g, '/').match(new RegExp(`^(.*(?:^|/)node_modules/${name}/)`))?.[1]) + .filter((root): root is string => root !== undefined)); + expect(copies('react').size).toBe(1); + expect(copies('react-dom').size).toBe(1); + }); + + it("emits one stylesheet holding the shared views' styles and the VS Code theme mapping", () => { + const outputs = Object.keys(metafile.outputs).map(output => output.replace(/\\/g, '/')); + expect(outputs.filter(output => output.endsWith('.css'))).toHaveLength(1); + const css = readFileSync(join(outDir, 'work.css'), 'utf8'); + expect(css).toContain('.builder-table'); + expect(css).toContain('--codev-wv-accent: var(--vscode-'); + }); +}); diff --git a/apps/vscode/src/__tests__/workspace-views-messages.test.ts b/apps/vscode/src/__tests__/workspace-views-messages.test.ts index 238bb4ed4..26856227b 100644 --- a/apps/vscode/src/__tests__/workspace-views-messages.test.ts +++ b/apps/vscode/src/__tests__/workspace-views-messages.test.ts @@ -1,5 +1,5 @@ /** - * Spec 1963 scenario 6: the Decisions panel's host ↔ webview contract. Webview → host messages are + * Spec 1963 scenario 6: the Work and Decisions panels' host ↔ webview contract. Webview → host messages are * untrusted, so every guard must reject anything malformed before the host acts on it. */ @@ -11,6 +11,10 @@ import { isDecisionsRuleMessage, isOpenExternalMessage, isReadyMessage, + isWorkNewShellMessage, + isWorkOpenArtifactMessage, + isWorkOpenBuilderMessage, + isWorkRefreshMessage, ruleRequestOf, } from '../workspace-views/messages.js'; @@ -106,3 +110,51 @@ describe('isOpenExternalMessage', () => { expect(isOpenExternalMessage(message)).toBe(false); }); }); + +describe('isWorkOpenBuilderMessage', () => { + it('accepts a builder id', () => { + expect(isWorkOpenBuilderMessage({ type: 'work/open-builder', builderId: 'spir-1963' })).toBe(true); + }); + + it.each<[string, unknown]>([ + ...NOT_OBJECTS.map((v): [string, unknown] => [JSON.stringify(v) ?? 'undefined', v]), + ['no id', { type: 'work/open-builder' }], + ['an empty id', { type: 'work/open-builder', builderId: '' }], + ['a numeric id', { type: 'work/open-builder', builderId: 1963 }], + ['an over-long id', { type: 'work/open-builder', builderId: 'a'.repeat(MAX_WEBVIEW_STRING + 1) }], + ['another type', { type: 'open-builder', builderId: 'spir-1963' }], + ])('rejects %s', (_name, message) => { + expect(isWorkOpenBuilderMessage(message)).toBe(false); + }); +}); + +describe('isWorkNewShellMessage and isWorkRefreshMessage', () => { + it('accept their type only', () => { + expect(isWorkNewShellMessage({ type: 'work/new-shell' })).toBe(true); + expect(isWorkRefreshMessage({ type: 'work/refresh' })).toBe(true); + for (const bad of [...NOT_OBJECTS, {}, { type: 'work/refresh' }, { type: 'new-shell' }]) { + expect(isWorkNewShellMessage(bad), JSON.stringify(bad)).toBe(false); + } + for (const bad of [...NOT_OBJECTS, {}, { type: 'work/new-shell' }, { type: 'refresh' }]) { + expect(isWorkRefreshMessage(bad), JSON.stringify(bad)).toBe(false); + } + }); +}); + +describe('isWorkOpenArtifactMessage', () => { + it('accepts a path as the overview names it (whether it may be opened is security.ts’s decision)', () => { + expect(isWorkOpenArtifactMessage({ type: 'work/open-artifact', path: 'codev/specs/1963-cockpit.md' })).toBe(true); + expect(isWorkOpenArtifactMessage({ type: 'work/open-artifact', path: '../outside.md' })).toBe(true); + }); + + it.each<[string, unknown]>([ + ...NOT_OBJECTS.map((v): [string, unknown] => [JSON.stringify(v) ?? 'undefined', v]), + ['no path', { type: 'work/open-artifact' }], + ['an empty path', { type: 'work/open-artifact', path: '' }], + ['a NUL byte', { type: 'work/open-artifact', path: 'codev/specs/a\0.md' }], + ['an over-long path', { type: 'work/open-artifact', path: 'a'.repeat(MAX_WEBVIEW_STRING + 1) }], + ['a non-string path', { type: 'work/open-artifact', path: ['codev'] }], + ])('rejects %s', (_name, message) => { + expect(isWorkOpenArtifactMessage(message)).toBe(false); + }); +}); diff --git a/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts b/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts index 8aa1cbafd..8b031c514 100644 --- a/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts +++ b/apps/vscode/src/__tests__/workspace-views-webview-source.test.ts @@ -42,7 +42,7 @@ describe('the workspace-views webview sources', () => { it('finds the sources', () => { expect(files.map(f => f.slice(WEBVIEW.length + 1))).toEqual( - expect.arrayContaining(['DecisionsApp.tsx', 'decisions-host.ts', 'decisions-main.tsx']), + expect.arrayContaining(['DecisionsApp.tsx', 'decisions-host.ts', 'decisions-main.tsx', 'WorkApp.tsx', 'work-main.tsx']), ); }); diff --git a/apps/vscode/src/extension.ts b/apps/vscode/src/extension.ts index 5111a4ef3..94b5ea809 100644 --- a/apps/vscode/src/extension.ts +++ b/apps/vscode/src/extension.ts @@ -69,7 +69,8 @@ import { AgentTreeHosts, agentCycleRoster } from './views/agent-tree-hosts.js'; import { CockpitProvider, COCKPIT_VIEW_ID, cockpitConnectionMode, type CockpitNode } from './views/cockpit.js'; import { DecisionsPanels } from './workspace-views/decisions-panel.js'; import { DecisionsBridge } from './workspace-views/decisions-bridge.js'; -import { DECISIONS_VIEW_TYPE } from './workspace-views/messages.js'; +import { WorkPanels } from './workspace-views/work-panel.js'; +import { DECISIONS_VIEW_TYPE, WORK_VIEW_TYPE } from './workspace-views/messages.js'; import { workspaceViewUnavailableReason } from './workspace-views/availability.js'; import { OverviewRefreshGate } from './views/overview-refresh-gate.js'; // Codev Tower (#1566): the cross-workspace navigation hub — its own activity-bar container. @@ -611,7 +612,34 @@ export async function activate(context: vscode.ExtensionContext) { }), log: (line) => outputChannel?.appendLine(line), }); - context.subscriptions.push(vscode.window.registerWebviewPanelSerializer(DECISIONS_VIEW_TYPE, decisionsPanels)); + context.subscriptions.push( + decisionsPanels, + vscode.window.registerWebviewPanelSerializer(DECISIONS_VIEW_TYPE, decisionsPanels), + ); + // The Work panel (Spec 1963): one per window, fed from this window's OverviewCache (the + // sidebar's source), with each kept dashboard action mapped to its VS Code equivalent. Its + // availability is read from the window's folders, as Decisions' is. + const workPanels = new WorkPanels({ + extensionUri: context.extensionUri, + overview: overviewCache, + connection: connectionManager, + actions: { + openBuilder: async (builderId) => terminalManager?.openBuilderByRoleOrId(builderId, true), + newShell: async () => vscode.commands.executeCommand('codev.newShell'), + openFile: async (fsPath) => vscode.commands.executeCommand('vscode.open', vscode.Uri.file(fsPath)), + warn: (message) => { void vscode.window.showWarningMessage(message); }, + }, + workspacePath: () => detectWorkspacePath(), + unavailableReason: () => workspaceViewUnavailableReason('Work', { + builderWorktreeWindow: isBuilderWorktreeWindow, + workspacePath: detectWorkspacePath(), + }), + log: (line) => outputChannel?.appendLine(line), + }); + context.subscriptions.push( + workPanels, + vscode.window.registerWebviewPanelSerializer(WORK_VIEW_TYPE, workPanels), + ); // Builders accordion (#913), row-click expand, follow-reveals, the // builder-active hook and the badge act on whichever of the two views a row // belongs to. The accordion is toggled via the header button / @@ -858,14 +886,15 @@ export async function activate(context: vscode.ExtensionContext) { ); // Periodic overview refresh while any overview-backed view is visible - // (`OverviewRefreshGate`): the Codev container's list views and the Cockpit, - // so with only the Cockpit visible this workspace's rows stay current. + // (`OverviewRefreshGate`): the Codev container's list views, the Cockpit and + // the Work panel, so with only the Cockpit or only Work visible this + // workspace's overview stays current. const readOverviewRefreshSeconds = (): number => { const s = vscode.workspace.getConfiguration('codev').get('overviewRefreshSeconds', 60); return typeof s === 'number' && Number.isFinite(s) && s > 0 ? s : 0; }; const overviewRefreshGate = new OverviewRefreshGate( - [buildersView, pullRequestsView, backlogView, recentlyClosedView, cockpitView], + [buildersView, pullRequestsView, backlogView, recentlyClosedView, cockpitView, workPanels], readOverviewRefreshSeconds, () => { if (connectionManager?.getState() === 'connected') { void overviewCache.refresh(); } }, () => { void overviewCache.refresh(); }, // resume → immediate refresh @@ -1309,6 +1338,8 @@ export async function activate(context: vscode.ExtensionContext) { // The Decisions panel (Spec 1963): the palette and the Cockpit's Decisions entry. Where it is // not offered (a builder-worktree or no-workspace window) it says why. regCli('codev.openDecisions', () => decisionsPanels.show()), + // The Work panel (Spec 1963): the palette. Where it is not offered it says why. + regCli('codev.openWork', () => workPanels.show()), reg('codev.searchBacklog', () => searchBacklog(connectionManager!, overviewCache)), reg('codev.openIssueById', () => openIssueById(connectionManager!, () => overviewCache.getData())), reg('codev.openPRById', () => openPRById(connectionManager!)), diff --git a/apps/vscode/src/views/overview-refresh-gate.ts b/apps/vscode/src/views/overview-refresh-gate.ts index 5c4a9a147..59f996bb6 100644 --- a/apps/vscode/src/views/overview-refresh-gate.ts +++ b/apps/vscode/src/views/overview-refresh-gate.ts @@ -1,6 +1,6 @@ import type * as vscode from 'vscode'; -/** A view whose visibility keeps the periodic overview refresh running. */ +/** A view (or editor-area panel) whose visibility keeps the periodic overview refresh running. */ export interface GatedView { readonly visible: boolean; readonly onDidChangeVisibility: vscode.Event; @@ -14,7 +14,8 @@ export interface GatedView { * `OverviewCache.refresh()` is last-write-wins, so periodic and event-driven refreshes coexist. * * Every view that renders this window's overview is one of `views` — the Codev container's list - * views and, since Spec 1963, the Cockpit — so with only the Cockpit visible the timer still runs. + * views and, since Spec 1963, the Cockpit and the Work panel — so with only one of those visible the + * timer still runs. */ export class OverviewRefreshGate implements vscode.Disposable { private timer: ReturnType | undefined; diff --git a/apps/vscode/src/workspace-views/decisions-panel.ts b/apps/vscode/src/workspace-views/decisions-panel.ts index ec48eeae9..47cb6b2dd 100644 --- a/apps/vscode/src/workspace-views/decisions-panel.ts +++ b/apps/vscode/src/workspace-views/decisions-panel.ts @@ -1,7 +1,6 @@ /** * The Decisions panel (Spec 1963): the shared Decisions view in an editor-area webview, for this - * window's workspace. One panel per window: opening it again reveals it, and never creates a - * second one or reloads the first. A window reload restores it through the panel serializer. + * window's workspace. One panel per window, restored after a reload (`single-panel.ts`). * * The webview never contacts Tower. It asks the host, which calls Tower through `DecisionsBridge`: * - **Polling has one owner:** the shared `useDecisions` hook, at its 2 s cadence. Each tick is one @@ -14,9 +13,8 @@ * workspace path come back as bytes, which the webview shows as object URLs. */ -import * as vscode from 'vscode'; -import { renderWorkspaceViewHtml } from './panel-template.js'; -import { isAllowedExternalUrl } from './security.js'; +import type * as vscode from 'vscode'; +import { PanelSession, SingleWebviewPanel, type SinglePanelOptions } from './single-panel.js'; import type { DecisionsBridge } from './decisions-bridge.js'; import { DECISIONS_VIEW_TYPE, @@ -29,116 +27,35 @@ import { type DecisionsHostMessage, } from './messages.js'; -export interface DecisionsPanelsOptions { - extensionUri: vscode.Uri; +export interface DecisionsPanelsOptions extends SinglePanelOptions { bridge: Pick; - /** Why the panel is not offered in this window (`availability.ts`), or null when it is. */ - unavailableReason: () => string | null; - log: (line: string) => void; } const PANEL_TITLE = 'Decisions'; -/** What the webview may load: the bundle under `dist`, and nothing else from the extension. */ -function webviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions { - return { enableScripts: true, localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist')] }; -} - /** The window's one Decisions panel, and its serializer. */ -export class DecisionsPanels implements vscode.WebviewPanelSerializer { - private current: DecisionsPanelSession | undefined; - - constructor(private readonly options: DecisionsPanelsOptions) {} - - /** - * *Codev: Open Decisions* and the Cockpit's Decisions entry: reveal the panel where it is, or open - * it in the active editor group. Where the panel is not offered, say why instead. - */ - show(): void { - const reason = this.options.unavailableReason(); - if (reason) { - void vscode.window.showInformationMessage(reason); - return; - } - if (this.current) { - this.current.panel.reveal(); - return; - } - const panel = vscode.window.createWebviewPanel( - DECISIONS_VIEW_TYPE, - PANEL_TITLE, - vscode.ViewColumn.Active, - { ...webviewOptions(this.options.extensionUri), retainContextWhenHidden: true }, - ); - this.adopt(panel); - } - - /** The panel, if one is open. */ - get panel(): vscode.WebviewPanel | undefined { - return this.current?.panel; - } - - /** - * A window reload restores an open panel in its group. Drafts are not restored, as a dashboard page - * reload loses them too. A second panel, or one in a window where Decisions is not offered, is closed. - */ - async deserializeWebviewPanel(panel: vscode.WebviewPanel): Promise { - if (this.current || this.options.unavailableReason()) { - panel.dispose(); - return; - } - panel.webview.options = webviewOptions(this.options.extensionUri); - this.adopt(panel); +export class DecisionsPanels extends SingleWebviewPanel { + constructor(private readonly options: DecisionsPanelsOptions) { + super({ viewType: DECISIONS_VIEW_TYPE, title: PANEL_TITLE, bundle: 'decisions' }, options); } - private adopt(panel: vscode.WebviewPanel): void { - const session = new DecisionsPanelSession(panel, this.options, () => { - if (this.current === session) { this.current = undefined; } - }); - this.current = session; + protected attach(panel: vscode.WebviewPanel): void { + new DecisionsPanelSession(panel, this.options); } } /** One panel's webview, from creation until it is closed. */ -class DecisionsPanelSession { - private disposed = false; - private readonly subscriptions: vscode.Disposable[] = []; - - constructor( - readonly panel: vscode.WebviewPanel, - private readonly options: DecisionsPanelsOptions, - onDisposed: () => void, - ) { - const { webview } = panel; - const bundle = vscode.Uri.joinPath(options.extensionUri, 'dist', 'webview'); - webview.html = renderWorkspaceViewHtml({ - cspSource: webview.cspSource, - scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(bundle, 'decisions.js')).toString(), - styleUri: webview.asWebviewUri(vscode.Uri.joinPath(bundle, 'decisions.css')).toString(), - title: PANEL_TITLE, - }); - this.subscriptions.push( - webview.onDidReceiveMessage((message: unknown) => { void this.onMessage(message); }), - panel.onDidChangeViewState(() => this.postVisibility()), - panel.onDidDispose(() => { - this.disposed = true; - for (const subscription of this.subscriptions) { subscription.dispose(); } - onDisposed(); - }), - ); - } - - private post(message: DecisionsHostMessage): void { - // A reply that lands after the panel closed has nowhere to go. - if (this.disposed) { return; } - void this.panel.webview.postMessage(message); +class DecisionsPanelSession extends PanelSession { + constructor(panel: vscode.WebviewPanel, private readonly options: DecisionsPanelsOptions) { + super(panel, PANEL_TITLE, options.log); + this.track(panel.onDidChangeViewState(() => this.postVisibility())); } private postVisibility(): void { this.post({ type: 'visibility', visible: this.panel.visible }); } - private async onMessage(message: unknown): Promise { + protected async onMessage(message: unknown): Promise { const { bridge } = this.options; if (isReadyMessage(message)) { this.postVisibility(); @@ -152,13 +69,9 @@ class DecisionsPanelSession { const result = await bridge.image(message.path); this.post({ type: 'decisions/image-result', requestId: message.requestId, result }); } else if (isOpenExternalMessage(message)) { - if (isAllowedExternalUrl(message.url)) { - void vscode.env.openExternal(vscode.Uri.parse(message.url)); - } else { - this.options.log(`Decisions panel: did not open ${message.url}; only http(s) links open from a panel.`); - } + this.openExternal(message.url); } else { - this.options.log('Decisions panel: ignored a malformed message from its webview.'); + this.log('ignored a malformed message from its webview.'); } } } diff --git a/apps/vscode/src/workspace-views/messages.ts b/apps/vscode/src/workspace-views/messages.ts index 0bb63b265..146f8cec8 100644 --- a/apps/vscode/src/workspace-views/messages.ts +++ b/apps/vscode/src/workspace-views/messages.ts @@ -10,11 +10,14 @@ */ import type { DecisionsRuleRequest } from '@cluesmith/codev-types'; -import type { DecisionRulingResult, DecisionsFetchResult } from '@cluesmith/codev-workspace-views/host'; +import type { DecisionRulingResult, DecisionsFetchResult, OverviewState } from '@cluesmith/codev-workspace-views/host'; /** The Decisions panel's webview type, as its serializer and restore know it. */ export const DECISIONS_VIEW_TYPE = 'codev.decisions'; +/** The Work panel's webview type, as its serializer and restore know it. */ +export const WORK_VIEW_TYPE = 'codev.work'; + // ── Webview → host ────────────────────────────────────────────────────────── /** The webview has mounted: the host answers with the panel's visibility. */ @@ -55,6 +58,36 @@ export type DecisionsWebviewMessage = | DecisionsImageMessage | OpenExternalMessage; +/** A builder row's *Open*: show that builder's terminal. */ +export interface WorkOpenBuilderMessage { + type: 'work/open-builder'; + builderId: string; +} + +/** *+ Shell*: open a new Tower shell. */ +export interface WorkNewShellMessage { + type: 'work/new-shell'; +} + +/** *Refresh*: re-read the overview, bypassing Tower's overview cache. */ +export interface WorkRefreshMessage { + type: 'work/refresh'; +} + +/** A *spec* / *plan* / *review* link: open that workspace file, as the overview names it. */ +export interface WorkOpenArtifactMessage { + type: 'work/open-artifact'; + path: string; +} + +export type WorkWebviewMessage = + | ReadyMessage + | WorkOpenBuilderMessage + | WorkNewShellMessage + | WorkRefreshMessage + | WorkOpenArtifactMessage + | OpenExternalMessage; + // ── Host → webview ────────────────────────────────────────────────────────── /** @@ -95,9 +128,21 @@ export type DecisionsHostMessage = | DecisionsRuleResultMessage | DecisionsImageResultMessage; +/** + * The overview the Work view shows, pushed whenever this window's overview or its connection + * changes: null while loading; otherwise the last overview read, with the not-connected notice + * as its `error` while Tower is not connected. + */ +export interface WorkOverviewMessage { + type: 'work/overview'; + overview: OverviewState | null; +} + +export type WorkHostMessage = WorkOverviewMessage; + // ── Guards (webview → host is untrusted) ──────────────────────────────────── -/** The longest image path or URL a webview may send; item markdown never needs more. */ +/** The longest path, URL or builder id a webview may send; nothing a panel shows needs more. */ export const MAX_WEBVIEW_STRING = 4096; function isRecord(value: unknown): value is Record { @@ -150,6 +195,24 @@ export function isDecisionsImageMessage(message: unknown): message is DecisionsI && isRequestId(message.requestId) && isBoundedString(message.path) && !message.path.includes('\0'); } +export function isWorkOpenBuilderMessage(message: unknown): message is WorkOpenBuilderMessage { + return isRecord(message) && message.type === 'work/open-builder' && isBoundedString(message.builderId); +} + +export function isWorkNewShellMessage(message: unknown): message is WorkNewShellMessage { + return isRecord(message) && message.type === 'work/new-shell'; +} + +export function isWorkRefreshMessage(message: unknown): message is WorkRefreshMessage { + return isRecord(message) && message.type === 'work/refresh'; +} + +/** The message's shape only: whether the file may be opened is `security.ts`'s decision. */ +export function isWorkOpenArtifactMessage(message: unknown): message is WorkOpenArtifactMessage { + return isRecord(message) && message.type === 'work/open-artifact' + && isBoundedString(message.path) && !message.path.includes('\0'); +} + /** The message's shape only: whether its URL may be opened is `security.ts`'s decision. */ export function isOpenExternalMessage(message: unknown): message is OpenExternalMessage { return isRecord(message) && message.type === 'open-external' && isBoundedString(message.url); diff --git a/apps/vscode/src/workspace-views/single-panel.ts b/apps/vscode/src/workspace-views/single-panel.ts new file mode 100644 index 000000000..52ecea50d --- /dev/null +++ b/apps/vscode/src/workspace-views/single-panel.ts @@ -0,0 +1,171 @@ +/** + * What the Work and Decisions panels have in common (Spec 1963): each is one editor-area webview + * panel per window, for this window's workspace. + * + * - **One per window.** Opening it again reveals it where it is, and never creates a second one or + * reloads the first. Where it is not offered (`availability.ts`) its command says why instead. + * - **Restored after a reload** through its serializer. A second restored panel, or one restored + * where the panel is not offered, is closed. + * - **Retained.** `retainContextWhenHidden` keeps the webview's state (a Decisions draft) while the + * panel is hidden or moved between groups. + * - **Its visibility is observable** (`visible`, `onDidChangeVisibility`), so a panel can count + * toward the periodic overview refresh as the sidebar's views do. + * + * A `PanelSession` is one panel's webview from creation until it is closed: it answers the + * webview's messages and drops any reply that lands after the panel closed. + */ + +import * as vscode from 'vscode'; +import { renderWorkspaceViewHtml } from './panel-template.js'; +import { isAllowedExternalUrl } from './security.js'; + +/** What every panel is given. */ +export interface SinglePanelOptions { + extensionUri: vscode.Uri; + /** Why the panel is not offered in this window (`availability.ts`), or null when it is. */ + unavailableReason: () => string | null; + log: (line: string) => void; +} + +/** Which panel: its restore type, its title, and its bundle `dist/webview/.{js,css}`. */ +export interface PanelKind { + viewType: string; + title: string; + bundle: string; +} + +/** What the webview may load: the bundle under `dist`, and nothing else from the extension. */ +function webviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions { + return { enableScripts: true, localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist')] }; +} + +/** The window's one panel of a kind, and its serializer. */ +export abstract class SingleWebviewPanel implements vscode.WebviewPanelSerializer, vscode.Disposable { + private current: vscode.WebviewPanel | undefined; + private readonly visibilityEmitter = new vscode.EventEmitter(); + /** Fires when the panel opens, closes, or is shown or hidden. */ + readonly onDidChangeVisibility = this.visibilityEmitter.event; + + protected constructor(private readonly kind: PanelKind, private readonly base: SinglePanelOptions) {} + + /** Reveal the panel where it is, or open it in the active editor group. Where it is not offered, say why. */ + show(): void { + const reason = this.base.unavailableReason(); + if (reason) { + void vscode.window.showInformationMessage(reason); + return; + } + if (this.current) { + this.current.reveal(); + return; + } + const panel = vscode.window.createWebviewPanel( + this.kind.viewType, + this.kind.title, + vscode.ViewColumn.Active, + { ...webviewOptions(this.base.extensionUri), retainContextWhenHidden: true }, + ); + this.adopt(panel); + } + + /** The panel, if one is open. */ + get panel(): vscode.WebviewPanel | undefined { + return this.current; + } + + /** Whether the panel is open and on screen. */ + get visible(): boolean { + return this.current?.visible ?? false; + } + + /** + * A window reload restores an open panel in its group. Webview state is not restored (a Decisions + * draft, as a dashboard page reload loses it too). A second panel, or one in a window where the + * panel is not offered, is closed. + */ + async deserializeWebviewPanel(panel: vscode.WebviewPanel): Promise { + if (this.current || this.base.unavailableReason()) { + panel.dispose(); + return; + } + panel.webview.options = webviewOptions(this.base.extensionUri); + this.adopt(panel); + } + + dispose(): void { + this.visibilityEmitter.dispose(); + } + + /** Start the session that answers a new or restored panel's webview. */ + protected abstract attach(panel: vscode.WebviewPanel): void; + + private adopt(panel: vscode.WebviewPanel): void { + const { webview } = panel; + const bundle = vscode.Uri.joinPath(this.base.extensionUri, 'dist', 'webview'); + webview.html = renderWorkspaceViewHtml({ + cspSource: webview.cspSource, + scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(bundle, `${this.kind.bundle}.js`)).toString(), + styleUri: webview.asWebviewUri(vscode.Uri.joinPath(bundle, `${this.kind.bundle}.css`)).toString(), + title: this.kind.title, + }); + this.current = panel; + const subscriptions = [ + panel.onDidChangeViewState(() => this.visibilityEmitter.fire()), + panel.onDidDispose(() => { + if (this.current === panel) { this.current = undefined; } + for (const subscription of subscriptions) { subscription.dispose(); } + this.visibilityEmitter.fire(); + }), + ]; + this.attach(panel); + this.visibilityEmitter.fire(); + } +} + +/** One panel's webview, from creation until the panel is closed. */ +export abstract class PanelSession { + private disposed = false; + private readonly subscriptions: vscode.Disposable[] = []; + + /** `label` names the panel in the log. */ + protected constructor( + protected readonly panel: vscode.WebviewPanel, + private readonly label: string, + private readonly logLine: (line: string) => void, + ) { + this.track( + panel.webview.onDidReceiveMessage((message: unknown) => { void this.onMessage(message); }), + panel.onDidDispose(() => { + this.disposed = true; + for (const subscription of this.subscriptions) { subscription.dispose(); } + }), + ); + } + + /** Answer one message from the webview. Messages are untrusted: act only on what a guard accepts. */ + protected abstract onMessage(message: unknown): Promise; + + /** Keep `subscriptions` until the panel closes. */ + protected track(...subscriptions: vscode.Disposable[]): void { + this.subscriptions.push(...subscriptions); + } + + /** Post to the webview. A reply that lands after the panel closed has nowhere to go, and is dropped. */ + protected post(message: HostMessage): void { + if (this.disposed) { return; } + void this.panel.webview.postMessage(message); + } + + protected log(line: string): void { + this.logLine(`${this.label} panel: ${line}`); + } + + /** Open a link from the webview in the user's browser: http(s) only. */ + protected openExternal(url: string): void { + if (isAllowedExternalUrl(url)) { + void vscode.env.openExternal(vscode.Uri.parse(url)); + } else { + this.log(`did not open ${url}; only http(s) links open from a panel.`); + } + } +} diff --git a/apps/vscode/src/workspace-views/webview/WorkApp.tsx b/apps/vscode/src/workspace-views/webview/WorkApp.tsx new file mode 100644 index 000000000..85efdee7f --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/WorkApp.tsx @@ -0,0 +1,63 @@ +/** + * The Work panel's webview UI (Spec 1963): the shared Work view, fed by the overview the extension + * host pushes, with every action a message to the host. + * + * - The view gets no dashboard slots, so the affordances VS Code drops (Open Files & Shells, the + * file panel, the tip of the day) are not rendered. + * - Links are the host's: an issue or PR link and a *spec* / *plan* / *review* link each become a + * message, so the webview opens nothing itself. + */ + +import { useMemo, useSyncExternalStore } from 'react'; +import { WorkView } from '@cluesmith/codev-workspace-views'; +import type { OverviewState, WorkViewHost } from '@cluesmith/codev-workspace-views/host'; +import type { WorkWebviewMessage } from '../messages.js'; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +/** The overview in a `work/overview` message from the host, or undefined for any other message. */ +export function workOverviewOf(message: unknown): OverviewState | null | undefined { + if (!isRecord(message) || message.type !== 'work/overview' || !('overview' in message)) { return undefined; } + const { overview } = message; + if (overview === null) { return null; } + if (isRecord(overview) && 'data' in overview && 'error' in overview) { return overview as unknown as OverviewState; } + return undefined; +} + +/** The overview the host last pushed, outside React so the host's messages can set it. */ +export class WorkStore { + private overview: OverviewState | null = null; + private readonly listeners = new Set<() => void>(); + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => { this.listeners.delete(listener); }; + }; + + readonly getSnapshot = (): OverviewState | null => this.overview; + + setOverview(overview: OverviewState | null): void { + this.overview = overview; + for (const listener of this.listeners) { listener(); } + } +} + +/** The Work view's host: the pushed overview, and a message to the extension host for each action. */ +export function webviewWorkHost(overview: OverviewState | null, post: (message: WorkWebviewMessage) => void): WorkViewHost { + return { + overview, + openBuilder: builder => post({ type: 'work/open-builder', builderId: builder.id }), + newShell: () => post({ type: 'work/new-shell' }), + refresh: () => post({ type: 'work/refresh' }), + openArtifact: path => post({ type: 'work/open-artifact', path }), + openExternal: url => post({ type: 'open-external', url }), + }; +} + +export function WorkApp({ store, post }: { store: WorkStore; post: (message: WorkWebviewMessage) => void }) { + const overview = useSyncExternalStore(store.subscribe, store.getSnapshot); + const host = useMemo(() => webviewWorkHost(overview, post), [overview, post]); + return ; +} diff --git a/apps/vscode/src/workspace-views/webview/__tests__/WorkApp.test.tsx b/apps/vscode/src/workspace-views/webview/__tests__/WorkApp.test.tsx new file mode 100644 index 000000000..4bc1b45b0 --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/__tests__/WorkApp.test.tsx @@ -0,0 +1,193 @@ +// @vitest-environment jsdom +/** + * Spec 1963 scenarios 10 and 17 (webview side): the Work panel's UI, fed through its store as the + * extension host's `work/overview` messages feed it. + * - Loading until the first overview; then builders, Needs Attention, Backlog and Recently Closed; + * the last overview stays under the not-connected notice. + * - Every kept control is a message to the extension host: *Open*, *+ Shell*, *Refresh*, a + * *spec* / *plan* / *review* link, and an issue or PR link, which the webview does not follow. + * - The affordances VS Code drops (Open Files & Shells, the file panel, the tip of the day) are + * not rendered. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import type { OverviewBacklogItem, OverviewBuilder, OverviewData, OverviewPR, OverviewRecentlyClosed } from '@cluesmith/codev-types'; +import type { WorkWebviewMessage } from '../../messages.js'; +import { WorkApp, WorkStore, workOverviewOf } from '../WorkApp.js'; + +afterEach(() => { + cleanup(); +}); + +function builder(overrides: Partial = {}): OverviewBuilder { + return { + id: 'spir-1963', + issueId: '1963', + issueTitle: 'Cockpit layout', + phase: 'implement', + protocolPhase: 'implement', + mode: 'strict', + gates: {}, + worktreePath: '/ws/.builders/spir-1963', + roleId: 'builder-spir-1963', + protocol: 'spir', + planPhases: [], + progress: 40, + blocked: null, + blockedGate: null, + blockedSince: null, + startedAt: null, + idleMs: 0, + lastDataAt: null, + spawnedByArchitect: 'main', + prReady: false, + area: '', + ...overrides, + }; +} + +const BACKLOG: OverviewBacklogItem = { + id: '401', title: 'Backlog feature', url: 'https://github.com/cluesmith/codev/issues/401', type: 'project', priority: 'high', area: '', + hasSpec: true, hasPlan: true, hasReview: false, hasBuilder: false, createdAt: new Date().toISOString(), + specPath: 'codev/specs/401-backlog-feature.md', planPath: 'codev/plans/401-backlog-feature.md', +}; + +const CLOSED: OverviewRecentlyClosed = { + id: '399', title: 'Closed feature', url: 'https://github.com/cluesmith/codev/issues/399', type: 'project', + closedAt: new Date().toISOString(), reviewPath: 'codev/reviews/399-closed-feature.md', prUrl: 'https://github.com/cluesmith/codev/pull/398', +}; + +const PR: OverviewPR = { + id: '301', title: 'A human-authored change', url: 'https://github.com/cluesmith/codev/pull/301', reviewStatus: 'REVIEW_REQUIRED', + linkedIssue: null, createdAt: new Date().toISOString(), reviewRequests: [], isDraft: false, +}; + +const DATA = { + builders: [builder()], + pendingPRs: [PR], + backlog: [BACKLOG], + recentlyClosed: [CLOSED], + architects: [{ name: 'main' }], + heldCount: 0, + mailboxEscalated: false, + queuedFeedback: {}, + feedbackMode: 'forward', +} as unknown as OverviewData; + +function mount() { + const posted: WorkWebviewMessage[] = []; + const store = new WorkStore(); + const post = (message: WorkWebviewMessage) => { posted.push(message); }; + const view = render(); + const push = (message: unknown) => { + const overview = workOverviewOf(message); + if (overview !== undefined) { act(() => store.setOverview(overview)); } + }; + return { posted, push, ...view }; +} + +describe('what the Work panel shows', () => { + it('shows its loading state until the extension host pushes an overview', () => { + const { push } = mount(); + expect(screen.getByText('Loading...')).toBeTruthy(); + push({ type: 'work/overview', overview: null }); + expect(screen.getByText('Loading...')).toBeTruthy(); + }); + + it('renders builders, Needs Attention, Backlog and Recently Closed from the overview', () => { + const { push, container } = mount(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + expect(screen.getByRole('heading', { name: 'Work' })).toBeTruthy(); + for (const section of ['Builders', 'Needs Attention', 'Backlog', 'Recently Closed']) { + expect(screen.getByRole('heading', { name: section })).toBeTruthy(); + } + expect(screen.getByText('Cockpit layout')).toBeTruthy(); + expect(screen.getByText('A human-authored change')).toBeTruthy(); + expect(screen.getByText('Backlog feature')).toBeTruthy(); + expect(screen.getByText('Closed feature')).toBeTruthy(); + // The progress bar is drawn at its width by an inline style, which the panel's CSP admits. + expect(container.querySelector('[style*="width"]')?.style.width).toBe('40%'); + }); + + it('keeps the last overview under the not-connected notice, and drops the notice on reconnect', () => { + const { push } = mount(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + push({ type: 'work/overview', overview: { data: DATA, error: 'Not connected to Tower.' } }); + expect(screen.getByText('Failed to load overview: Not connected to Tower.')).toBeTruthy(); + expect(screen.getByText('Cockpit layout')).toBeTruthy(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + expect(screen.queryByText(/Not connected to Tower/)).toBeNull(); + }); + + it('renders none of the dropped dashboard affordances', () => { + const { push, container } = mount(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + expect(screen.queryByText(/Open Files/i)).toBeNull(); + expect(screen.queryByText(/tip/i)).toBeNull(); + expect(container.querySelector('.work-view')?.className).not.toContain('file-panel-open'); + // The only buttons are the mapped ones. + expect(screen.getAllByRole('button').map(b => b.textContent)).toEqual(['+ Shell', 'Refresh', 'Open', 'spec', 'plan', 'review']); + }); +}); + +describe('every control is a message to the extension host', () => { + it('Open, + Shell and Refresh', () => { + const { push, posted } = mount(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + fireEvent.click(screen.getByRole('button', { name: 'Open' })); + fireEvent.click(screen.getByRole('button', { name: '+ Shell' })); + fireEvent.click(screen.getByRole('button', { name: 'Refresh' })); + expect(posted).toEqual([ + { type: 'work/open-builder', builderId: 'spir-1963' }, + { type: 'work/new-shell' }, + { type: 'work/refresh' }, + ]); + }); + + it('spec, plan and review links name the file as the overview does', () => { + const { push, posted } = mount(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + for (const name of ['spec', 'plan', 'review']) { + fireEvent.click(screen.getByRole('button', { name })); + } + expect(posted).toEqual([ + { type: 'work/open-artifact', path: 'codev/specs/401-backlog-feature.md' }, + { type: 'work/open-artifact', path: 'codev/plans/401-backlog-feature.md' }, + { type: 'work/open-artifact', path: 'codev/reviews/399-closed-feature.md' }, + ]); + }); + + it('an issue or PR link goes to the extension host, and the webview does not follow it', () => { + const { push, posted } = mount(); + push({ type: 'work/overview', overview: { data: DATA, error: null } }); + for (const text of ['A human-authored change', 'Backlog feature', 'Closed feature']) { + const link = screen.getByText(text).closest('a'); + expect(link, text).not.toBeNull(); + const followed = fireEvent.click(link!); + expect(followed, `${text}: default prevented`).toBe(false); + } + expect(posted).toEqual([ + { type: 'open-external', url: 'https://github.com/cluesmith/codev/pull/301' }, + { type: 'open-external', url: 'https://github.com/cluesmith/codev/issues/401' }, + { type: 'open-external', url: 'https://github.com/cluesmith/codev/issues/399' }, + ]); + }); +}); + +describe('workOverviewOf: what the webview takes from the host', () => { + it('takes a pushed overview, or null for loading', () => { + expect(workOverviewOf({ type: 'work/overview', overview: null })).toBeNull(); + expect(workOverviewOf({ type: 'work/overview', overview: { data: DATA, error: null } })).toEqual({ data: DATA, error: null }); + }); + + it.each<[string, unknown]>([ + ['null', null], + ['another type', { type: 'visibility', visible: true }], + ['no overview', { type: 'work/overview' }], + ['an overview missing its error', { type: 'work/overview', overview: { data: null } }], + ['a string overview', { type: 'work/overview', overview: 'loading' }], + ])('ignores %s', (_label, message) => { + expect(workOverviewOf(message)).toBeUndefined(); + }); +}); diff --git a/apps/vscode/src/workspace-views/webview/work-main.tsx b/apps/vscode/src/workspace-views/webview/work-main.tsx new file mode 100644 index 000000000..f7955b855 --- /dev/null +++ b/apps/vscode/src/workspace-views/webview/work-main.tsx @@ -0,0 +1,30 @@ +/** + * Webview entry of the Work panel (Spec 1963): mounts the shared Work view on the overview the + * extension host pushes, with every action a message to the host. Bundled by esbuild as a browser + * IIFE (`dist/webview/work.{js,css}`) and type-checked by `tsconfig.webview.json`. + * + * Styles: the shared views' stylesheet and `vscode-theme.css`, which maps the views' `--codev-wv-*` + * tokens to VS Code's theme. + */ + +import { createRoot } from 'react-dom/client'; +import '@cluesmith/codev-workspace-views/styles.css'; +import './vscode-theme.css'; +import type { WorkWebviewMessage } from '../messages.js'; +import { WorkApp, WorkStore, workOverviewOf } from './WorkApp.js'; + +declare function acquireVsCodeApi(): { postMessage(message: WorkWebviewMessage): void }; + +const vscodeApi = acquireVsCodeApi(); +const store = new WorkStore(); +const post = (message: WorkWebviewMessage) => vscodeApi.postMessage(message); + +window.addEventListener('message', (event: MessageEvent) => { + const overview = workOverviewOf(event.data); + if (overview !== undefined) { store.setOverview(overview); } +}); + +const container = document.getElementById('root'); +if (!container) { throw new Error('Work panel: the webview document has no #root element'); } +createRoot(container).render(); +vscodeApi.postMessage({ type: 'ready' }); diff --git a/apps/vscode/src/workspace-views/work-panel.ts b/apps/vscode/src/workspace-views/work-panel.ts new file mode 100644 index 000000000..ddba0d6db --- /dev/null +++ b/apps/vscode/src/workspace-views/work-panel.ts @@ -0,0 +1,172 @@ +/** + * The Work panel (Spec 1963): the shared Work view in an editor-area webview, for this window's + * workspace. One panel per window, restored after a reload (`single-panel.ts`). + * + * The webview never contacts Tower: + * - **Its data is pushed** from the host's `OverviewCache`, the same source the sidebar uses, on + * every overview or connection change. The panel adds no poll of its own; while it is visible it + * counts toward the periodic overview refresh (`OverviewRefreshGate`), as the sidebar views do. + * - **Last-known-good.** While Tower is not connected the panel keeps the last overview under a + * not-connected notice. Before the first overview it shows its loading state. + * - **Every kept dashboard action is mapped** to its VS Code equivalent: + * - *Open* (a builder row) opens the builder's terminal, as clicking its Agents row does; + * - *+ Shell* runs *New Shell* (a Tower shell opened by the terminal manager); + * - *Refresh* asks Tower to drop its overview cache (`POST /api/overview/refresh`, the call the + * dashboard's *Refresh* makes, which is machine-wide), then re-reads this window's overview; + * - a *spec* / *plan* / *review* link opens that file in an editor, only when its canonical + * (symlink-resolved) location is inside the workspace; + * - an issue or PR link opens in the user's browser, http(s) only. + * + * The dropped ones (Open Files & Shells, the file panel, the tip of the day) are not rendered: + * the webview passes the view no slots. + */ + +import * as vscode from 'vscode'; +import type { OverviewData } from '@cluesmith/codev-types'; +import type { TowerClient } from '@cluesmith/codev-sdk/tower-client'; +import type { OverviewState } from '@cluesmith/codev-workspace-views/host'; +import type { ConnectionState } from '../connection-manager.js'; +import { PanelSession, SingleWebviewPanel, type SinglePanelOptions } from './single-panel.js'; +import { resolveWorkspaceFile } from './security.js'; +import { NOT_CONNECTED_MESSAGE } from './decisions-bridge.js'; +import { + WORK_VIEW_TYPE, + isOpenExternalMessage, + isReadyMessage, + isWorkNewShellMessage, + isWorkOpenArtifactMessage, + isWorkOpenBuilderMessage, + isWorkRefreshMessage, + type WorkHostMessage, +} from './messages.js'; + +/** This window's overview (`OverviewCache`). */ +export interface WorkOverviewSource { + getData(): OverviewData | null; + readonly onDidChange: vscode.Event; + refresh(): Promise; +} + +/** This window's Tower connection (`ConnectionManager`). */ +export interface WorkConnection { + getState(): ConnectionState; + readonly onStateChange: vscode.Event; + getClient(): Pick | null; +} + +/** The VS Code actions the panel's controls map to. */ +export interface WorkActions { + /** Open a builder's terminal (`TerminalManager.openBuilderByRoleOrId`). */ + openBuilder(builderId: string): Promise; + /** *New Shell* (`codev.newShell`). */ + newShell(): Promise; + /** Open a file, already checked to be inside the workspace, in an editor. */ + openFile(fsPath: string): Promise; + /** Tell the user why a link they clicked did not open. */ + warn(message: string): void; +} + +export interface WorkPanelsOptions extends SinglePanelOptions { + overview: WorkOverviewSource; + connection: WorkConnection; + actions: WorkActions; + /** The workspace whose files an artifact link may open. */ + workspacePath: () => string | null; +} + +const PANEL_TITLE = 'Work'; + +/** + * What the Work view shows for this window's overview and connection: + * - null (its loading state) until the first overview, unless Tower is known to be unreachable; + * - otherwise the last overview read, under the not-connected notice while Tower is not connected. + */ +export function workOverviewState(data: OverviewData | null, state: ConnectionState): OverviewState | null { + const notConnected = state === 'disconnected' || state === 'reconnecting'; + if (data === null) { + return notConnected ? { data: null, error: NOT_CONNECTED_MESSAGE } : null; + } + return { data, error: state === 'connected' ? null : NOT_CONNECTED_MESSAGE }; +} + +/** The window's one Work panel, and its serializer. */ +export class WorkPanels extends SingleWebviewPanel { + constructor(private readonly options: WorkPanelsOptions) { + super({ viewType: WORK_VIEW_TYPE, title: PANEL_TITLE, bundle: 'work' }, options); + } + + protected attach(panel: vscode.WebviewPanel): void { + new WorkPanelSession(panel, this.options); + } +} + +/** One panel's webview, from creation until it is closed. */ +class WorkPanelSession extends PanelSession { + constructor(panel: vscode.WebviewPanel, private readonly options: WorkPanelsOptions) { + super(panel, PANEL_TITLE, options.log); + this.track( + options.overview.onDidChange(() => this.postOverview()), + options.connection.onStateChange(() => this.postOverview()), + ); + } + + private postOverview(): void { + const { overview, connection } = this.options; + this.post({ type: 'work/overview', overview: workOverviewState(overview.getData(), connection.getState()) }); + } + + protected async onMessage(message: unknown): Promise { + const { actions } = this.options; + if (isReadyMessage(message)) { + this.postOverview(); + } else if (isWorkOpenBuilderMessage(message)) { + await this.openBuilder(message.builderId); + } else if (isWorkNewShellMessage(message)) { + await actions.newShell(); + } else if (isWorkRefreshMessage(message)) { + await this.refresh(); + } else if (isWorkOpenArtifactMessage(message)) { + await this.openArtifact(message.path); + } else if (isOpenExternalMessage(message)) { + this.openExternal(message.url); + } else { + this.log('ignored a malformed message from its webview.'); + } + } + + /** Only a builder the panel shows: its row is the only place an id comes from. */ + private async openBuilder(builderId: string): Promise { + const builders = this.options.overview.getData()?.builders ?? []; + if (!builders.some(builder => builder.id === builderId)) { + this.log(`did not open builder ${builderId}: it is not in this workspace's overview.`); + return; + } + await this.options.actions.openBuilder(builderId); + } + + /** Drop Tower's overview cache, then re-read this window's overview, as the dashboard's *Refresh* does. */ + private async refresh(): Promise { + const { connection, overview } = this.options; + const client = connection.getState() === 'connected' ? connection.getClient() : null; + if (client) { await client.refreshOverview(); } + await overview.refresh(); + } + + private async openArtifact(requested: string): Promise { + const { actions, workspacePath } = this.options; + const root = workspacePath(); + if (root === null) { + this.log(`did not open ${requested}: this window has no workspace.`); + return; + } + const resolved = await resolveWorkspaceFile(root, requested); + if (resolved.ok) { + await actions.openFile(resolved.path); + return; + } + this.log(`did not open ${requested}: ${resolved.reason}.`); + actions.warn(resolved.reason === 'not-found' + ? `Codev: ${requested} was not found in this workspace.` + : `Codev: ${requested} was not opened: it is outside this workspace.`); + } +} diff --git a/codev/resources/arch.md b/codev/resources/arch.md index d214533e0..ff9e398a5 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -1270,6 +1270,7 @@ live in `packages/`; end-user client surfaces live in `apps/`: | `packages/types` | `@cluesmith/codev-types` | Shared TypeScript types: WebSocket protocol, API shapes, SSE events (dev dependency only) | | `packages/config` | `@cluesmith/codev-config` | Shared tsconfig base (cross-project) | | `packages/artifact-canvas` | `@cluesmith/codev-artifact-canvas` | Reusable React surface for rendering/reviewing Codev markdown artifacts | +| `packages/workspace-views` | `@cluesmith/codev-workspace-views` (private, source-exported) | The Work and Decisions React views, shared by the dashboard and the VS Code extension; each host supplies its I/O through a host adapter (#1963) | | `apps/web` | `@cluesmith/codev-web` | React dashboard SPA (built into codev package) | | `apps/vscode` | `codev-vscode` (Marketplace: `cluesmith.codev-vscode`) | VS Code extension | | `apps/streamdeck` | `@cluesmith/codev-streamdeck` (private; Elgato plugin UUID `com.cluesmith.codev`) | Stream Deck plugin — outside-in controller: overview reads + SSE + command-relay verbs via the sdk's `controller`/`node` subpaths. Imported from codev-integrations under #1347; packs on demand into a `.sdPlugin` Marketplace bundle (not yet Marketplace-distributed — initial Maker Console submission is a tracked follow-up), versioned in workspace lockstep (manifest `Version` = package version + build segment, pinned by a version-sync test) | @@ -1378,6 +1379,7 @@ The VS Code extension (`apps/vscode`) is a thin client over Tower's existing API - **Codev Tower — cross-workspace navigation hub (#1566)**: A SEPARATE view container (`codev-tower`, view `codev.tower`), machine-scope, distinct from the workspace-scope `codev` container. It defaults to the **secondary side bar** (`viewsContainers.secondarySidebar`, a contribution point stable since VS Code 1.106 — so `engines.vscode` must stay ≥1.106; `tower-engine-guard.test.ts` enforces that and that `@types/vscode` ≤ the floor). Tower is a window-bound VS Code view reading **machine-global** Tower data: the window's existing shared `TowerClient` + the **one** shared SSE (`connectionManager.onSSEEvent`, never a second EventSource — #1211) drive a cross-workspace cache (`views/tower-cache.ts`) that fans out `listWorkspaces()` + per-workspace `getOverview(path)`, with a 300ms debounce, single-in-flight + trailing-rerun, per-workspace last-known-good on transient/empty reads, and a 20s poll fallback (activation emits no SSE, so the list must be re-polled). Attention is **consumed, never re-derived**: `deriveAttention`/`isIdleWaiting` project it, `compareAttention` is the canonical cross-client urgency order, and `formatAge` the canonical relative-age — all in `@cluesmith/codev-sdk/builder-helpers` (client UI policy, NOT `codev-types` wire contracts), shared by the Tower tree AND the contextual panel so the two can't drift. The hub stops at the workspace boundary: a row switch invokes the existing `codev.focusWorkspaceWindow` (focus-or-new-window, never replace-in-place — VS Code windows are folder-bound, so other workspaces' terminals/views are reachable only by switching to their window); activating a dormant workspace confirms the server-side `codev adopt` write first via a client `fs.existsSync(codev/)` pre-check. A one-time first-run reveal opens the hidden-by-default secondary side bar for discovery (globalState-gated, #1144 tier policy). - **Codev Cockpit — one hierarchy over the fleet (#1963)**: A third activity-bar container (`codev-cockpit`, view `codev.cockpit`, placed directly below `codev`) whose `CockpitProvider` (`views/cockpit.ts`) renders Tower → workspaces → architects → builders → changed files. It **reads, never fetches**: workspace rows come from `TowerFleetCache` through the row builder shared with the Tower view (`orderFleet` order, same labels and `tower-workspace-*` context values for other workspaces). Architect, builder and file rows come from **`ArchitectTreeBuilder`** (`views/architect-tree.ts`), the Agents view's row logic lifted into a class: Agents holds one (scope `''`), and the Cockpit holds one per active workspace with scope `ws:|`, so tree ids never collide across workspaces (twelve `main`s), and accordion versioning and the builder → group map are per view and per workspace. **Fleet-overview retention:** `TowerFleetCache` keeps each active workspace's last overview (`getOverview(path)`), not only its attention summary. A transient fetch failure keeps the last one, and a workspace that goes dormant or leaves the list drops it. This window's workspace instead reads `OverviewCache`, as Agents does, so the two views cannot disagree. **Act/navigate rule:** only this window's workspace, and only when this window is not a builder worktree (#1809), builds rows in `act` mode. Those carry the Agents context values, so the 12 builder `view/item/context` entries are duplicated with `view == codev.cockpit` and act unchanged. Every other workspace's rows are `navigate`: `REMOTE_CONTEXT` values (`cockpit-remote-*`) that no builder or architect menu matches, and a click that runs the Tower view's `codev.tower.openWorkspace` (focus-or-new-window). The current workspace row's `cockpit-workspace-(current|parent)[-dev-start|-dev-stop|-dev-stop-other][-devurls]` context value comes from `workspaceDevSlot`, extracted from `WorkspaceProvider`, so the two views' dev affordances cannot disagree. The worktree config behind it is **held**: it is fetched once per workspace path and dropped only on `codev-config-updated`, a connection-state change or a path change, never per fleet tick. `views/cockpit-menu-map.ts` is the checked-in oracle mapping every source-view menu entry, row click and welcome to its Cockpit placement, and `cockpit-menu-parity.test.ts` fails on any unmapped or drifted entry. The agent-cycle keys follow the Cockpit's rendered order only while it is visible, Agents is not, and it has acting rows (`agentCycleRoster`). +- **Work and Decisions panels — one set of React views, two hosts (#1963)**: The dashboard's Work and Decisions views live once, in `packages/workspace-views`, which both `apps/web` and `apps/vscode` bundle (`one-copy.test.ts` fails on a second copy). It extends the artifact-canvas precedent: **the package does no I/O.** Every read and action goes through a **host adapter** (`host.ts`: `WorkViewHost`, `DecisionsViewHost`). An optional action renders its control only when the host provides it, so no host shows a dead button, and dashboard-only pieces (Open Files & Shells, the file panel, the tip banner) are **slots** only the dashboard passes. Theme is the `--codev-wv-*` tokens: the dashboard keeps its defaults, and VS Code maps every token to a `--vscode-*` variable (`workspace-views/webview/vscode-theme.css`, held complete by `workspace-views-theme.test.ts`). In VS Code each view is a **single-instance, retained editor-area `WebviewPanel`** (`workspace-views/single-panel.ts`: reveal instead of recreate, serializer restore, observable visibility). **Its webview never contacts Tower:** the CSP is `default-src 'none'` with no `connect-src` (`panel-template.ts`); a lint rule and a source test ban `fetch`/XHR/WebSocket/EventSource in the webview and package sources; and every request is a typed message (`messages.ts`, an `is*Message` guard on everything inbound) that the host answers with `ConnectionManager`'s client, so the Tower key never enters a webview. **Decisions** keeps the shared `useDecisions` hook as its poll's only owner (one host Tower call per webview `decisions/read`). The host relays the panel's own visibility, because a retained, hidden webview still reports `visible`. Refusals keep their `{ code, message }` through the SDK's `requestPreservingBody`, and workspace images come back as bytes (`requestBinary`) shown as object URLs. **Work is pushed:** the host posts `OverviewCache` data with the connection state (`workOverviewState`: loading, then last-known-good under a not-connected notice), adds no poll, and the panel counts toward `OverviewRefreshGate` as the sidebar views do. **Links are the host's** in both: only http(s) goes to `openExternal`, and a workspace file opens only when `resolveWorkspaceFile` (canonical `realpath` both sides, then `path.relative`, never a string prefix) puts it inside the workspace. Availability (`availability.ts`) is read from the window's folders (`detectWorkspacePath()`), never from the connection manager, because a reload's serializer runs before `initialize()`. - **Hover reading aid draws in a separate layer, never in the body (#1802)**: the canvas body is imperatively owned (cards, composer host and `data-line` anchoring depend on its exact DOM), so the hover highlight never wraps words or writes inside it. `useHoverWordHighlight` appends one `position: fixed; z-index: -1` layer to the canvas root, which is `isolation: isolate`; that paints the shapes above the root's background but behind in-flow text, cards, the composer and every fixed overlay. Words are resolved per animation frame with `caretPositionFromPoint`/`caretRangeFromPoint` + `Intl.Segmenter` and drawn from `Range.getClientRects()` in client coordinates, so a capture-phase document `scroll` listener re-resolves under a still pointer in both reading modes. Style vocabulary (`none | word | wordLine | wordLineParagraph | line | lineParagraph`, default `lineParagraph`) and cursor (`arrow | iBeam | hand`) are canvas props; VS Code bootstraps them as `#root` data attributes from `codev.markdownPreview.hoverHighlight` / `readingCursor` (same path as `data-reading-mode`), and the host's `reading-aids.ts` vocabulary is compile-checked against the canvas types. Dark themes get stronger line/paragraph strengths in the VS Code template via `body.vscode-dark` and `body.vscode-high-contrast:not(.vscode-high-contrast-light)`; the `:not` clause is required because the webview preamble also stamps plain `vscode-high-contrast` on light high-contrast themes. ## Repository Dual Nature From bb3e257bcba51a897c9005c2cbc2dddeb190eb89 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:37:10 -0800 Subject: [PATCH 090/140] [Spec 1963][Phase: work_panel] fix: Work readable and whole in a half-width group and in Light Modern; verify work - Implementing orange is mixed from the error and waiting text colours: Light Modern's chart orange measured 2.9:1 as text, rendered. - VS Code-only container queries: as the Work panel narrows, Elapsed, the reviewer and assignee labels, then Progress go first; issue, title, state and Open always fit. - Harness: a verify work script (scenarios 17, 18, 19, 22, reload restore, the increment-2 side-by-side shot with a half-width fit check, Tower down for both panels). - work-panel.test: the real-filesystem containment tests wait for their outcome. --- apps/vscode/scripts/cockpit-harness/README.md | 1 + .../cockpit-harness/cockpit-verify.mjs | 405 ++++++++++++++++++ apps/vscode/src/__tests__/work-panel.test.ts | 9 +- .../__tests__/workspace-views-theme.test.ts | 4 + .../workspace-views/webview/vscode-theme.css | 44 +- 5 files changed, 459 insertions(+), 4 deletions(-) diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index 378794ce4..c59a6583f 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -161,6 +161,7 @@ state, so run them in this order, once per `start`: | `actions` | Every builder context action, Approve Gate inline (it relays to the spawning architect through `/api/send`, #1494, so the check asserts that and no porch call), every workspace-row action (Spawn Builder's `afx spawn` checked in the stub log, with its cwd), and Remove Architect: offered on siblings only. A childless sibling, added through Tower, loses its row. A sibling that spawned a builder keeps its header as that builder's owner, as in Agents. Other workspaces' rows navigate; their workspace rows keep Open and Deactivate. It sets #102's and #103's gates back to unrequested first, because `windows` and `requests` request them | | `dashboard` | Spec scenario 20, on **its own** `start` + `seed fleet` (it rules `main-1` and opens a shell in `alpha`). The browser dashboard the isolated Tower serves for `alpha`, in headless Chromium, not VS Code. It refreshes the overview first, because Tower caches the forge failure from the extension's activation before the seed. Five checks: Work renders every section with rows; Decisions renders both cards and loads the image as a blob; a link and a full-size image open in a new tab (the link's URL, the image's blob page); a ruling round-trips to the file; and Work's actions (Open, + Shell, an artifact link, an issue link, Refresh) do what they did. It writes `shots/dashboard-snapshot.json`: every element under the two views, with its classes, its own text (ages masked) and its computed colour, type and box. With `COCKPIT_BASELINE=
` it adds a sixth check that fails on any difference from that snapshot. To compare a change against its base, run once on the base's build, keep the snapshot, then run again on the change's build with `COCKPIT_BASELINE` pointing at it | | `decisions` | Spec scenarios 15, 16, 18, 19 (Decisions part), 21 (hidden-panel polling) and 22, Phase 7. On **its own** `start` + `seed fleet`: it adds `main-2` to alpha's file (an https image and one answered 404, both from the browser's route for `example.com`, and an image outside the workspace), rules `main-1`, edits `main-2` under the panel, and creates gamma's file. It checks: a **Decisions** entry under every active workspace and none under the dormant one; another workspace's entry opens that window; this workspace's opens one panel with the items; the workspace image renders from an object URL (bytes through the host), the https image renders, the 404 image and the outside image each show *Image not loaded* with the reason; the full-size view opens and closes; a link opens through the host; a ruling writes the file, shows on the card and reaches `main` (Tower's `Decisions notice` log line); a stale fingerprint is refused with the draft kept; no reads while the panel is hidden; four themes switched live without reloading the webview, with the contrast of every visible text in the panel measured against its composited background (none under 3:1; the item id, Submit and an option word at least 4.5:1; every text under 4.5:1 listed in the evidence); the panel restored after a reload; the explanations in a builder-worktree and a no-workspace window; gamma's empty state, then the real `afx decisions init` (it only writes the template), then an item appears; and a request audit: no browser request to the Tower port or carrying the key, and webview frames load only VS Code's webview host page, extension resources, blobs and the remote item images | +| `work` | Spec scenarios 17, 18, 19 (Tower-down for both panels, and Work's window variants) and 22, Phase 8. On **its own** `start` + `seed fleet` (it opens a shell, opens a terminal and stops the Tower). It refreshes alpha's overview first, as `dashboard` does. It checks: *Codev: Open Work* opens one panel (a second run reveals it) with every section and alpha's rows, and none of the dashboard-only pieces (Files panel, tip banner, Open Files & Shells); each progress bar is drawn at its width under the panel's CSP; *Open* opens #102's terminal; *+ Shell* opens a Tower shell; *Refresh* sends `POST /api/overview/refresh` and then a read; #401's spec link opens the file; an issue and a PR link open in the browser through the host; four themes switched live without reloading the webview, with every visible text's contrast measured (none under 3:1; every text under 4.5:1 listed), plus two colours the fixture never draws (a PIR dev-approval row's orange and the spike tag), drawn as probe elements in the real webview for the measurement; the Cockpit's Decisions entries beside Work and Decisions in two groups (the increment-2 shot, dark and light), with the half-width Work view held to fit (no sideways scroll, every *Open* whole, no row label over its links); the panel restored after a reload; the request audit; the isolated Tower stopped (Work keeps its last overview and Decisions its cards, each under *Not connected to Tower*, with no error toast) and started again (Work shows the restarted Tower's overview, which no longer has the fixture's builders; Decisions' notice clears); and the explanations in a builder-worktree and a no-workspace window | | `reconnect` | **Run last.** A loaded Cockpit keeps its content with Tower down; a fresh window shows *Not connected to Tower*; Tower up + the row's Reconnect restores it. Stops and restarts only the isolated Tower, by PID (`tower-down` / `tower-up`) | A restarted Tower does not reconnect the fixture sessions: its startup reconciliation skips, and diff --git a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs index a814d79dd..0e30c8c6e 100644 --- a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs +++ b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs @@ -18,6 +18,10 @@ // decisions the VS Code Decisions panel (Phase 7): the hierarchy's entries, images, full size, // a link, a ruling and its notice, a stale refusal, hidden-panel polling, themes, // reload restore, the unavailable windows, empty state → init, network audit +// work the VS Code Work panel (Phase 8): every section, the progress bar under the CSP, +// Open / + Shell / Refresh / a spec link / issue and PR links, themes and contrast, +// both panels beside the Cockpit's Decisions entries, reload restore, network audit, +// Tower down and back, the unavailable windows // // Every result is recorded in --out as { script, results: [{ name, ok, detail, shots }] }. Any // browser request to the owner's port fails the run. @@ -1970,6 +1974,407 @@ SCRIPTS.decisions = async (R, context, page) => { }); }; +// ── work ───────────────────────────────────────────────────────────────────────────────────── +// The VS Code Work panel (Phase 8): spec scenarios 17 (each mapped action), 18 (themes, live +// switch, contrast), 19 (the unavailable windows; Tower unreachable, then back) and 22 (network +// audit), plus the increment-2 shot of the Cockpit's Decisions entries beside both panels. + +/** The Work panel's document: VS Code nests a webview's page two iframes down. */ +async function workFrame(page, timeout = 60_000) { + return waitFor('the Work webview', async () => { + for (const frame of page.frames()) { + if (frame === page.mainFrame()) continue; + if (await frame.locator('.work-view').count().catch(() => 0)) return frame; + } + return null; + }, timeout); +} + +/** Requests the Tower received after request-log line `from` whose path ends with `suffix`. */ +const towerHits = (R, from, method, suffix) => R.towerRequests().slice(from) + .filter((r) => r.method === method && (r.url ?? '').split('?')[0].endsWith(suffix)); + +/** + * Run in a panel's frame: the WCAG contrast of every rendered text in `rootSelector`, on what it is + * drawn on (its own and its ancestors' backgrounds, composited), lowest first. The same probe as the + * Decisions theme check: rgb()/rgba() and color(srgb …) (a color-mix()) are both parsed. + * `probes` are [label, className, text]: each is drawn for the measurement inside the view's + * content, as the view would draw it, then removed (colours the fixture's data never shows). + */ +function textContrasts({ rootSelector, probes }) { + const parse = (c) => { + const n = (c.match(/-?[\d.]+(?:e-?\d+)?/g) ?? []).map(Number); + const k = c.startsWith('color(') ? 255 : 1; + return c === 'transparent' ? { r: 0, g: 0, b: 0, a: 0 } : { r: n[0] * k, g: n[1] * k, b: n[2] * k, a: n.length > 3 ? n[3] : 1 }; + }; + const over = (top, under) => ({ r: top.a * top.r + (1 - top.a) * under.r, g: top.a * top.g + (1 - top.a) * under.g, b: top.a * top.b + (1 - top.a) * under.b, a: 1 }); + const backdrop = (el) => { + const layers = []; + for (let e = el; e; e = e.parentElement) { + const bg = parse(getComputedStyle(e).backgroundColor); + if (bg.a > 0) layers.push(bg); + if (bg.a >= 1) break; + } + let base = layers.at(-1)?.a >= 1 ? layers.pop() : { r: 255, g: 255, b: 255, a: 1 }; + for (const layer of layers.reverse()) base = over(layer, base); + return base; + }; + const lum = ({ r, g, b }) => { + const [R, G, B] = [r, g, b].map((v) => v / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }; + const ratio = (fg, bg) => { const [x, y] = [lum(fg), lum(bg)].sort((m, n) => n - m); return Math.round(((x + 0.05) / (y + 0.05)) * 10) / 10; }; + const textContrast = (el) => { const bg = backdrop(el); return ratio(over(parse(getComputedStyle(el).color), bg), bg); }; + const root = document.querySelector(rootSelector); + const host = document.querySelector('.work-content') ?? root; + const probed = probes.map(([label, className, text]) => { + const el = document.createElement('span'); + el.className = className; + el.textContent = text; + host.appendChild(el); + const contrast = textContrast(el); + el.remove(); + return { label, contrast }; + }); + const texts = [...root.querySelectorAll('*')] + .filter((el) => el.getClientRects().length && [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())) + .map((el) => { + const kind = `${el.tagName.toLowerCase()}${[...el.classList].map((c) => `.${c}`).join('')}`; + return { kind, what: `${kind} "${el.textContent.trim().slice(0, 24)}"`, contrast: textContrast(el) }; + }) + .sort((a, b) => a.contrast - b.contrast); + return { + marker: window.__codevMarker ?? null, + body: getComputedStyle(document.body).backgroundColor, + text: getComputedStyle(document.body).color, + editorBg: getComputedStyle(document.documentElement).getPropertyValue('--vscode-editor-background').trim(), + scanned: texts.length, + lowest: texts.slice(0, 3).map(({ what, contrast }) => ({ what, contrast })), + under45: [...new Map(texts.filter((t) => t.contrast < 4.5).reverse().map((t) => [t.kind, t.contrast])).entries()].map(([k, c]) => `${c} ${k}`), + probed, + }; +} + +/** Colours the fixture never shows, drawn for the measurement: a PIR dev-approval row's orange, and the spike tag. */ +const WORK_PROBES = [ + ['implementing orange (attention-kind--dev)', 'attention-kind attention-kind--dev', 'dev review'], + ['spike tag', 'backlog-type-tag type-tag--spike', 'spike'], +]; + +SCRIPTS.work = async (R, context, page) => { + // Issue and PR links point at example.com: answer them here, so no request leaves the machine. + await context.route(/^https?:\/\/example\.com\//, (route) => route.fulfill({ status: 200, contentType: 'text/html', body: '

fixture link

' })); + // Every request the browser makes, with the frame that made it, for scenario 22. + const requests = []; + context.on('request', (r) => { + let frame = 'other'; + try { + const f = r.frame(); + frame = f === f.page().mainFrame() ? 'main' : f.url(); + } catch { /* a service worker's request, or a popup's first navigation */ } + requests.push({ url: r.url(), frame, key: Object.keys(r.headers()).some((h) => h.toLowerCase() === 'codev-tower-key') }); + }); + + let frame; + const work = () => frame.locator('.work-view'); + const builderRow = (id) => frame.locator('.builder-row', { has: frame.locator('.builder-col-id', { hasText: new RegExp(`^#${id}\\b`) }) }); + + await R.check('scenario 17: Open Work opens one panel; builders, Needs Attention, Backlog and Recently Closed render; no dropped affordance', async () => { + // The overview Tower computed when VS Code first opened alpha (before the seed wrote its forge + // config) is cached with the forge concepts failed: drop it, and wait for one with every list. + const ws = Buffer.from(path.join(R.opts.fixtures, 'alpha')).toString('base64url'); + await R.tower('POST', `/workspace/${ws}/api/overview/refresh`); + await waitFor('alpha\'s overview with its forge lists', async () => { + const o = await R.overview('alpha'); + return !o.errors && o.pendingPRs?.length && o.backlog?.length && o.recentlyClosed?.length; + }, 60_000); + await loadWorkbench(page, R.folderUrl('alpha')); + await runCommand(page, 'Codev: Open Work'); + await waitFor('the Work editor tab', async () => /^Work/.test(await activeEditorTab(page) ?? ''), 20_000); + frame = await workFrame(page); + await waitFor('three builder rows and the forge lists', async () => (await frame.locator('.builder-table tbody tr').count()) === 3 + && (await frame.locator('.backlog-rows .backlog-row').count()) === 2, 60_000); + const problems = []; + const ids = await frame.locator('.builder-table .builder-col-id').allTextContents(); + for (const id of ['#101', '#102', '#103']) if (!ids.some((t) => t.startsWith(id))) problems.push(`no builder row ${id}`); + if (await frame.locator('.builder-table .builder-row-open').count() !== 3) problems.push('not three Open buttons'); + const buttons = (await work().locator('button').allTextContents()).map((t) => t.trim()); + const headings = (await work().locator('h2, h3').allTextContents()).map((t) => t.trim()); + if (JSON.stringify(headings) !== JSON.stringify(['Work', 'Builders', 'Needs Attention', 'Backlog', 'Recently Closed'])) problems.push(`headings ${JSON.stringify(headings)}`); + const attention = (await frame.locator('.attention-rows .attention-row').allTextContents()).join(' | '); + if (!/#101.*spec review/.test(attention)) problems.push(`Needs Attention lacks #101's spec review: "${attention}"`); + if (await frame.locator('a.attention-row', { hasText: '#301' }).getAttribute('href').catch(() => null) !== 'https://example.com/fixture/pull/301') problems.push('Needs Attention lacks PR #301 as a link'); + const backlog = (await frame.locator('.backlog-rows .backlog-row').allTextContents()).join(' | '); + if (!/#401/.test(backlog) || !/#402/.test(backlog) || /#10[123]/.test(backlog)) problems.push(`Backlog is "${backlog}"`); + const artifacts = (await frame.locator('.backlog-row', { hasText: '#401' }).locator('.backlog-artifact-link').allTextContents()).map((t) => t.trim()); + if (JSON.stringify(artifacts) !== JSON.stringify(['spec', 'plan'])) problems.push(`#401 offers ${JSON.stringify(artifacts)}`); + const closedLinks = (await frame.locator('.recently-closed-row', { hasText: '#399' }).locator('.backlog-artifact-link').allTextContents()).map((t) => t.trim()); + if (JSON.stringify(closedLinks) !== JSON.stringify(['review', 'PR'])) problems.push(`#399 offers ${JSON.stringify(closedLinks)}`); + // The dashboard-only pieces are absent: Open Files & Shells, the Files panel, the tip of the day. + for (const [what, selector] of [['the Files panel', '.work-file-panel'], ['the tip banner', '.tip-banner'], ['Open Files & Shells', '.open-files-shells, .work-open-files']]) { + if (await frame.locator(selector).count()) problems.push(`${what} renders`); + } + if (/Open Files|Shells/i.test(await work().textContent())) problems.push('an Open Files & Shells section renders'); + if ((await work().getAttribute('class')).includes('file-panel-open')) problems.push('the view is laid out for a file panel'); + // Running the command again reveals the same panel. + await runCommand(page, 'Codev: Open Work'); + await page.waitForTimeout(800); + const tabs = (await editorTabs(page)).filter((t) => /^Work/.test(t ?? '')); + if (tabs.length !== 1) problems.push(`${tabs.length} Work tabs after a second Open Work`); + if (problems.length) throw new Error(problems.join('; ')); + return { detail: `builders ${ids.join(', ')}; headings ${headings.join(' / ')}; buttons ${buttons.join(', ')}; one tab after a second Open Work`, shots: [await R.shot(page, 'panel')] }; + }); + + await R.check("scenario 17: a builder's progress bar is drawn at its width under the panel's CSP", async () => { + const bars = await frame.locator('.builder-row').evaluateAll((trs) => trs.map((tr) => { + const fill = tr.querySelector('.progress-fill'); + const bar = tr.querySelector('.progress-bar'); + return { + id: tr.querySelector('.builder-col-id')?.textContent?.trim().slice(0, 5), + pct: tr.querySelector('.progress-pct')?.textContent?.trim(), + inline: fill?.style.width, + fill: fill ? Math.round(fill.getBoundingClientRect().width) : null, + bar: bar ? Math.round(bar.getBoundingClientRect().width) : null, + }; + })); + const problems = bars.filter((b) => b.inline !== b.pct || Math.abs(b.fill - (b.bar * parseFloat(b.pct)) / 100) > 1); + if (!bars.length || problems.length) throw new Error(`bars ${JSON.stringify(bars)}`); + return bars.map((b) => `${b.id} ${b.pct}: ${b.fill}px of ${b.bar}px`).join('; '); + }); + + await R.check("scenario 17: Open opens the builder's terminal", async () => { + const e = await effects(R, context, page, () => builderRow(102).locator('.builder-row-open').click()); + if (!e.tabs.some((t) => /102|second-main/.test(t))) throw new Error(`no builder terminal tab: ${describe(e)}`); + return { detail: describe(e), shots: [await R.shot(page, 'open-builder')] }; + }); + + // Back to the panel for each action: Open left a terminal in front. + const showWork = async () => { + await runCommand(page, 'Codev: Open Work'); + await waitFor('the Work editor in front', async () => /^Work/.test(await activeEditorTab(page) ?? ''), 10_000); + }; + + await R.check('scenario 17: + Shell opens a Tower shell', async () => { + await showWork(); + const e = await effects(R, context, page, () => work().locator('.work-actions .work-btn', { hasText: '+ Shell' }).click()); + if (!e.terminals.length) throw new Error(`no shell terminal: ${describe(e)}`); + return { detail: describe(e), shots: [await R.shot(page, 'new-shell')] }; + }); + + await R.check("scenario 17: Refresh drops Tower's overview cache, then re-reads the overview", async () => { + await showWork(); + const from = R.towerRequests().length; + await work().locator('.work-actions .work-btn', { hasText: 'Refresh' }).click(); + const post = await waitFor('POST …/api/overview/refresh', async () => towerHits(R, from, 'POST', '/api/overview/refresh')[0] ?? null, 10_000); + const reads = await waitFor('a GET of the overview after it', async () => { + const after = R.towerRequests().slice(from); + const at = after.indexOf(post); + const gets = after.slice(at + 1).filter((r) => r.method === 'GET' && (r.url ?? '').split('?')[0].endsWith('/api/overview')); + return gets.length ? gets : null; + }, 10_000); + return `${post.method} ${post.url}, then ${reads.length} GET ${reads[0].url}`; + }); + + await R.check('scenario 17: a spec link opens the workspace file in an editor', async () => { + const e = await effects(R, context, page, () => frame.locator('.backlog-row', { hasText: '#401' }).locator('.backlog-artifact-link', { hasText: 'spec' }).click(), { wait: 3000 }); + if (!e.tabs.some((t) => /401-fixture-backlog\.md/.test(t))) throw new Error(`no spec tab: ${describe(e)}`); + return { detail: describe(e), shots: [await R.shot(page, 'spec-link')] }; + }); + + await R.check('scenario 17: an issue link and a PR link open in the browser, through the extension host', async () => { + await showWork(); + const opened = []; + for (const link of [frame.locator('.backlog-row', { hasText: '#402' }).locator('a.backlog-row-main'), frame.locator('a.attention-row', { hasText: '#301' })]) { + let asked = null; + const url = await nextPopup(R, context, async () => { + await link.click(); + // VS Code asks before opening a domain it does not trust yet. + if (await page.locator('.monaco-dialog-box').waitFor({ timeout: 5000 }).then(() => true, () => false)) asked = await dialogButton(page, 'Open'); + }); + opened.push(`${url}${asked ? ' (after VS Code\'s prompt)' : ''}`); + } + if (!/^https:\/\/example\.com\/fixture\/issues\/402\b/.test(opened[0]) || !/^https:\/\/example\.com\/fixture\/pull\/301\b/.test(opened[1])) throw new Error(`opened ${JSON.stringify(opened)}`); + // The webview did not follow the link itself: the panel is still the Work view. + if (!await frame.locator('.work-view').count()) throw new Error('the Work webview navigated away'); + return opened.join('; '); + }); + + await R.check('scenario 18: light, dark and high-contrast themes, switched live with the panel open', async () => { + await showWork(); + await frame.evaluate(() => { window.__codevMarker = 'kept'; }); + const shots = []; + const seen = {}; + const themes = [['Dark Modern', 'vs-dark'], ['Dark High Contrast', 'hc-black'], ['Light High Contrast', 'hc-light'], ['Light Modern', 'vs']]; + for (const [theme, cls] of themes) { + await setTheme(page, theme); + const applied = await page.locator('.monaco-workbench').evaluate((el, c) => el.classList.contains(c), cls); + if (!applied) throw new Error(`the workbench is not ${cls} after choosing ${theme}`); + await page.waitForTimeout(800); + seen[theme] = await frame.evaluate(textContrasts, { rootSelector: '.work-view', probes: WORK_PROBES }); + shots.push(await R.shot(page, `theme-${cls}`)); + } + const problems = []; + for (const [theme, s] of Object.entries(seen)) { + if (s.marker !== 'kept') problems.push(`${theme}: the webview reloaded`); + if (s.body !== hexToRgb(s.editorBg)) problems.push(`${theme}: body ${s.body} is not the editor background ${s.editorBg}`); + // No text in the panel below 3:1, the floor for anything a reader is meant to see. + const faint = [...s.lowest, ...s.probed.map((p) => ({ what: p.label, contrast: p.contrast }))].filter((t) => !(t.contrast >= 3)); + if (faint.length) problems.push(`${theme}: faint text ${JSON.stringify(faint)}`); + } + const looks = new Set(Object.values(seen).map((s) => `${s.body}|${s.text}`)); + if (looks.size !== themes.length) problems.push(`only ${looks.size} distinct looks across ${themes.length} themes`); + if (problems.length) throw new Error(`${problems.join('; ')} — ${JSON.stringify(seen)}`); + return { + detail: Object.entries(seen).map(([t, s]) => `${t}: body ${s.body}, text ${s.text}; lowest of ${s.scanned} texts ${s.lowest.map((x) => `${x.contrast} ${x.what}`).join(', ')}; probes ${s.probed.map((p) => `${p.label} ${p.contrast}`).join(', ')}; under 4.5: ${s.under45.join(', ') || 'none'}`).join('; '), + shots, + }; + }); + + await R.check('increment 2: the Cockpit\'s Decisions entries, with the Work and Decisions panels side by side', async () => { + await setTheme(page, 'Dark Modern'); + const cockpit = await openCockpit(page); + await waitRow(cockpit, A_MAIN, 60_000); + for (const spec of [ALPHA, BETA, GAMMA]) await setExpanded(cockpit, spec, true); + // One group first (the builder terminal may have opened a second): merges, closes nothing. + await runCommand(page, 'View: Single Column Editor Layout'); + await (await waitRow(cockpit, [...ALPHA, 'Decisions'])).loc.click(); + await waitFor('the Decisions editor tab', async () => /^Decisions/.test(await activeEditorTab(page) ?? ''), 20_000); + await decisionsFrame(page); + await runCommand(page, 'Codev: Open Work'); + await waitFor('the Work editor in front', async () => /^Work/.test(await activeEditorTab(page) ?? ''), 10_000); + await runCommand(page, 'View: Move Editor into Next Group'); + await page.waitForTimeout(1500); + // Each group's active tab, left to right. + const groups = await page.locator('.editor-group-container').evaluateAll((els) => els.map((g) => g.querySelector('.tabs-container .tab.active')?.getAttribute('aria-label') ?? null)); + if (groups.length !== 2 || !/^Decisions/.test(groups[0] ?? '') || !/^Work/.test(groups[1] ?? '')) throw new Error(`active tabs by group ${JSON.stringify(groups)}`); + frame = await workFrame(page); + // In a half-width group the view fits: nothing scrolls sideways, each Open is whole, and no + // backlog or recently-closed label runs into the links after it. + const fit = await frame.evaluate(() => { + const content = document.querySelector('.work-content'); + const right = content.getBoundingClientRect().right; + const opens = [...document.querySelectorAll('.builder-row-open')].map((b) => Math.round(b.getBoundingClientRect().right)); + const overlaps = [...document.querySelectorAll('.backlog-row, .recently-closed-row')].flatMap((row) => { + const main = row.querySelector('.backlog-row-main, .recently-closed-row-main'); + const links = row.querySelector('.backlog-artifacts'); + if (!main || !links) return []; + const drawn = [...main.children].filter((c) => c.getClientRects().length).map((c) => c.getBoundingClientRect().right); + const last = Math.min(Math.max(...drawn), main.getBoundingClientRect().right); + return last > links.getBoundingClientRect().left + 0.5 ? [row.textContent.trim().slice(0, 30)] : []; + }); + return { + width: Math.round(content.clientWidth), + sideways: content.scrollWidth - content.clientWidth, + opens, right: Math.round(right), + hidden: ['.builder-col-elapsed', '.builder-col-progress', '.backlog-row-author'].filter((sel) => { + const el = document.querySelector(sel); + return el && getComputedStyle(el).display === 'none'; + }), + overlaps, + }; + }); + if (fit.sideways > 0 || fit.opens.length !== 3 || fit.opens.some((r) => r > fit.right) || fit.overlaps.length) throw new Error(`the half-width Work view does not fit: ${JSON.stringify(fit)}`); + const shots = [await R.shot(page, 'both-panels-dark')]; + await setTheme(page, 'Light Modern'); + shots.push(await R.shot(page, 'both-panels-light')); + return { detail: `active tabs by group ${JSON.stringify(groups)}; alpha, beta and gamma expanded to their Decisions entries; Work at ${fit.width} px: no sideways scroll, Open buttons end by ${Math.max(...fit.opens)} of ${fit.right}, hidden ${fit.hidden.join(', ') || 'nothing'}, no label overlaps`, shots }; + }); + + await R.check('the panel is restored after a window reload', async () => { + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.monaco-workbench', { timeout: 240_000 }); + frame = await workFrame(page, 120_000); + await waitFor('the restored panel\'s builder rows', async () => (await frame.locator('.builder-table tbody tr').count()) === 3, 60_000); + const tabs = (await editorTabs(page)).filter((t) => /^Work/.test(t ?? '')); + if (tabs.length !== 1) throw new Error(`${tabs.length} Work tabs after the reload`); + return { detail: 'one Work tab, its builder rows rendered', shots: [await R.shot(page, 'restored')] }; + }); + + await R.check('scenario 22: the webview never contacts Tower; the key is in no request', async () => { + const towerPort = R.opts['tower-port']; + const problems = []; + const toTower = requests.filter((r) => URL.canParse(r.url) && new URL(r.url).port === towerPort); + if (toTower.length) problems.push(`${toTower.length} browser request(s) to the Tower port: ${toTower.slice(0, 3).map((r) => r.url).join(', ')}`); + const keyed = requests.filter((r) => r.key); + if (keyed.length) problems.push(`${keyed.length} request(s) carry the key header`); + const webview = requests.filter((r) => /\/webview\/browser\/pre\//.test(r.frame)); + const kinds = {}; + for (const r of webview) { + const origin = URL.canParse(r.frame) ? new URL(r.frame).origin : ''; + const kind = /^(blob|data):/.test(r.url) ? 'blob/data' + : URL.canParse(r.url) && /\.vscode-resource\./.test(new URL(r.url).hostname) ? 'extension resource' + : URL.canParse(r.url) && new URL(r.url).origin === origin ? "VS Code's webview host page" + : null; + if (!kind) problems.push(`unexpected webview request ${r.url}`); + else kinds[kind] = (kinds[kind] ?? 0) + 1; + } + if (!kinds['extension resource']) problems.push('the audit saw no extension resource load from a webview (is it attributing frames?)'); + const html = await frame.content(); + if (html.includes(process.env.COCKPIT_TOWER_KEY) || html.includes(`:${towerPort}`)) problems.push('the webview document holds the key or the Tower port'); + if (problems.length) throw new Error(problems.slice(0, 8).join('; ')); + return `${requests.length} browser requests, none to :${towerPort}, none keyed; webview frames: ${JSON.stringify(kinds)}`; + }); + + await R.check('scenario 19: Tower unreachable — both panels keep their content under a not-connected notice, no error toast, and recover', async () => { + await closeNotifications(page); + // Decisions is open beside Work (restored with it after the reload), on screen, so it polls. + const dframe = await decisionsFrame(page); + const cards = await dframe.locator('.decisions-card').count(); + const dAlert = dframe.locator('.decisions-content > .decisions-error[role="alert"]'); + const notice = work().locator('.work-error'); + R.harness('tower-down'); + await waitFor('the not-connected notice', async () => /Not connected to Tower/.test(await notice.textContent().catch(() => '') ?? ''), 60_000); + await waitFor('Decisions\' not-connected notice', async () => /Not connected to Tower/.test(await dAlert.textContent().catch(() => '') ?? ''), 20_000); + const kept = await frame.locator('.builder-table tbody tr').count(); + const keptCards = await dframe.locator('.decisions-card').count(); + const text = (await notice.textContent()).trim(); + const dText = (await dAlert.textContent()).trim(); + const downShot = await R.shot(page, 'tower-down'); + const toasts = (await notifications(page)).filter((n) => /overview|work|error|failed/i.test(n)); + R.harness('tower-up'); + let reconnected = 'by itself'; + try { + await waitFor('the notice to clear', async () => (await notice.count()) === 0, 60_000); + } catch { + await runCommand(page, 'Codev: Reconnect'); + reconnected = 'after Codev: Reconnect'; + await waitFor('the notice to clear', async () => (await notice.count()) === 0, 60_000); + } + // A restarted Tower does not keep the fixture's sessions (see the README), so the overview it + // serves now has its own builder count: the panel shows that one, under no notice. + const now = (await R.overview('alpha')).builders?.length ?? 0; + await waitFor(`the panel to show Tower's ${now} builder(s)`, async () => (now === 0 + ? (await frame.locator('.work-empty', { hasText: 'No active builders' }).count()) === 1 + : (await frame.locator('.builder-table tbody tr').count()) === now), 30_000); + await waitFor('Decisions\' notice to clear', async () => (await dAlert.count()) === 0, 30_000); + const cardsAfter = await dframe.locator('.decisions-card').count(); + if (kept !== 3) throw new Error(`${kept} builder rows kept while down`); + if (!cards || keptCards !== cards || cardsAfter !== cards) throw new Error(`decision cards: ${cards} before, ${keptCards} while down, ${cardsAfter} after`); + if (toasts.length) throw new Error(`error toasts while down: ${JSON.stringify(toasts)}`); + return { + detail: `Work: "${text}" over ${kept} kept rows; Decisions: "${dText}" over ${keptCards} kept cards; no toast; recovered ${reconnected}: Work shows the restarted Tower's overview (${now} builders), Decisions its ${cardsAfter} cards under no notice`, + shots: [downShot, await R.shot(page, 'tower-back')], + }; + }); + + await R.check('scenario 19: in a builder-worktree window, Open Work explains', async () => { + const wt = fs.readdirSync(path.join(R.opts.fixtures, 'alpha', '.builders')).find((d) => d.includes('101')); + await loadWorkbench(page, R.folderUrl('alpha', '.builders', wt)); + await runCommand(page, 'Codev: Open Work'); + const note = await waitForNotification(page, /Work is not offered in a builder-worktree window/); + if ((await editorTabs(page)).some((t) => /^Work/.test(t ?? ''))) throw new Error('a Work panel opened in the worktree window'); + return { detail: `"${note}"`, shots: [await R.shot(page, 'worktree-explains')] }; + }); + + await R.check('scenario 19: in a no-workspace window, Open Work explains', async () => { + await loadWorkbench(page, R.url('ew=true'), { needCodev: false }); + await page.waitForTimeout(3000); + await runCommand(page, 'Codev: Open Work'); + const note = await waitForNotification(page, /Work needs a Codev workspace/); + return { detail: `"${note}"`, shots: [await R.shot(page, 'no-workspace-explains')] }; + }); +}; + async function main() { const [script, ...rest] = process.argv.slice(2); if (!SCRIPTS[script]) { diff --git a/apps/vscode/src/__tests__/work-panel.test.ts b/apps/vscode/src/__tests__/work-panel.test.ts index 314bebe7c..5e1be03e0 100644 --- a/apps/vscode/src/__tests__/work-panel.test.ts +++ b/apps/vscode/src/__tests__/work-panel.test.ts @@ -377,11 +377,14 @@ describe('artifact links open a workspace file, and nothing outside it', () => { rmSync(base, { recursive: true, force: true }); }); + // These resolve real paths (fs.promises.realpath, on libuv's thread pool), so they wait for the + // outcome: one turn of the event loop is not always enough under a loaded full-suite run. + it('opens a spec by its workspace-relative path, at its canonical location', async () => { const { manager, actions } = setup({ root }); manager.show(); await panels[0].send({ type: 'work/open-artifact', path: 'codev/specs/1963-cockpit.md' }); - expect(actions.openFile).toHaveBeenCalledWith(join(root, 'codev', 'specs', '1963-cockpit.md')); + await vi.waitFor(() => expect(actions.openFile).toHaveBeenCalledWith(join(root, 'codev', 'specs', '1963-cockpit.md'))); expect(actions.warn).not.toHaveBeenCalled(); }); @@ -394,16 +397,16 @@ describe('artifact links open a workspace file, and nothing outside it', () => { const { manager, actions } = setup({ root }); manager.show(); await panels[0].send({ type: 'work/open-artifact', path }); + await vi.waitFor(() => expect(actions.warn).toHaveBeenCalledWith(`Codev: ${path} was not opened: it is outside this workspace.`)); expect(actions.openFile).not.toHaveBeenCalled(); - expect(actions.warn).toHaveBeenCalledWith(`Codev: ${path} was not opened: it is outside this workspace.`); }); it('says a missing file was not found', async () => { const { manager, actions } = setup({ root }); manager.show(); await panels[0].send({ type: 'work/open-artifact', path: 'codev/specs/gone.md' }); + await vi.waitFor(() => expect(actions.warn).toHaveBeenCalledWith('Codev: codev/specs/gone.md was not found in this workspace.')); expect(actions.openFile).not.toHaveBeenCalled(); - expect(actions.warn).toHaveBeenCalledWith('Codev: codev/specs/gone.md was not found in this workspace.'); }); }); diff --git a/apps/vscode/src/__tests__/workspace-views-theme.test.ts b/apps/vscode/src/__tests__/workspace-views-theme.test.ts index 2065e945d..58f5e6f49 100644 --- a/apps/vscode/src/__tests__/workspace-views-theme.test.ts +++ b/apps/vscode/src/__tests__/workspace-views-theme.test.ts @@ -78,6 +78,10 @@ describe('vscode-theme.css', () => { const map = mappings(); expect(map.get('--codev-wv-status-waiting')).toMatch(/^var\(--vscode-list-warningForeground,/); expect(map.get('--codev-wv-status-error')).toMatch(/^var\(--vscode-list-errorForeground,/); + // Implementing sits between them, mixed from the two: the chart orange measured 2.9:1 as text + // on Light Modern's white, rendered. + expect(map.get('--codev-wv-status-implementing')) + .toBe('color-mix(in srgb, var(--codev-wv-status-error) 50%, var(--codev-wv-status-waiting))'); }); it('uses no literal colour of its own anywhere', () => { diff --git a/apps/vscode/src/workspace-views/webview/vscode-theme.css b/apps/vscode/src/workspace-views/webview/vscode-theme.css index e232565c8..18900ad93 100644 --- a/apps/vscode/src/workspace-views/webview/vscode-theme.css +++ b/apps/vscode/src/workspace-views/webview/vscode-theme.css @@ -44,7 +44,10 @@ --codev-wv-status-active: var(--vscode-charts-green); --codev-wv-status-waiting: var(--vscode-list-warningForeground, var(--vscode-charts-yellow)); --codev-wv-status-error: var(--vscode-list-errorForeground, var(--vscode-errorForeground)); - --codev-wv-status-implementing: var(--vscode-charts-orange); + /* Implementing (a dev-approval row) is orange between the error red and the waiting yellow, the + dashboard's red → orange → yellow gate progression. It is mixed from those two text colours, so + it reads as text where they do: Light Modern's chart orange measured 2.9:1 on white, rendered. */ + --codev-wv-status-implementing: color-mix(in srgb, var(--codev-wv-status-error) 50%, var(--codev-wv-status-waiting)); --codev-wv-status-waiting-tint: color-mix(in srgb, var(--codev-wv-status-waiting) 10%, transparent); --codev-wv-status-error-tint: color-mix(in srgb, var(--codev-wv-status-error) 10%, transparent); --codev-wv-tag-bug-bg: color-mix(in srgb, var(--codev-wv-status-error) 15%, transparent); @@ -134,3 +137,42 @@ summary:focus-visible { max-width: none; max-height: none; } + +/* + * Narrow panels. The dashboard's Work view fills a browser page; in VS Code it is often a + * half-width editor group, beside Decisions. There the builders table's fixed columns overran the + * panel, cutting off each row's Open button, and a backlog row's reviewer and assignee labels ran + * over its spec / plan links (found rendered at about 470 px). These rules are VS + * Code's own, so the dashboard keeps its layout: as the panel narrows, the secondary columns and + * labels go first, and the issue, title, state and Open always fit. + */ +.work-view { + container: work-view / inline-size; +} + +@container work-view (max-width: 760px) { + .builder-table thead th:nth-child(5), + .builder-col-elapsed, + .backlog-row-author, + .backlog-row-assignees { + display: none; + } +} + +@container work-view (max-width: 600px) { + .builder-table thead th:nth-child(4), + .builder-col-progress { + display: none; + } + + .builder-col-state { + width: auto; + white-space: normal; + } +} + +/* Whatever is left in a backlog or recently-closed row clips at its edge, never overlaps the links after it. */ +.backlog-row-main, +.recently-closed-row-main { + overflow: hidden; +} From 432d706c0fa942aef34c0918a9671c15388c466c Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:42:40 -0800 Subject: [PATCH 091/140] [Spec 1963][Phase: work_panel] fix: progress track visible in Light Modern The track's tertiary background is the row's own colour in Light Modern, so only the fill showed. VS Code's stylesheet draws it as a faint mix of the text colour; verify work's theme check now fails when a track does not show on its row. --- apps/vscode/scripts/cockpit-harness/README.md | 2 +- apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs | 9 ++++++++- apps/vscode/src/workspace-views/webview/vscode-theme.css | 7 +++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index c59a6583f..56ce549b3 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -161,7 +161,7 @@ state, so run them in this order, once per `start`: | `actions` | Every builder context action, Approve Gate inline (it relays to the spawning architect through `/api/send`, #1494, so the check asserts that and no porch call), every workspace-row action (Spawn Builder's `afx spawn` checked in the stub log, with its cwd), and Remove Architect: offered on siblings only. A childless sibling, added through Tower, loses its row. A sibling that spawned a builder keeps its header as that builder's owner, as in Agents. Other workspaces' rows navigate; their workspace rows keep Open and Deactivate. It sets #102's and #103's gates back to unrequested first, because `windows` and `requests` request them | | `dashboard` | Spec scenario 20, on **its own** `start` + `seed fleet` (it rules `main-1` and opens a shell in `alpha`). The browser dashboard the isolated Tower serves for `alpha`, in headless Chromium, not VS Code. It refreshes the overview first, because Tower caches the forge failure from the extension's activation before the seed. Five checks: Work renders every section with rows; Decisions renders both cards and loads the image as a blob; a link and a full-size image open in a new tab (the link's URL, the image's blob page); a ruling round-trips to the file; and Work's actions (Open, + Shell, an artifact link, an issue link, Refresh) do what they did. It writes `shots/dashboard-snapshot.json`: every element under the two views, with its classes, its own text (ages masked) and its computed colour, type and box. With `COCKPIT_BASELINE=
` it adds a sixth check that fails on any difference from that snapshot. To compare a change against its base, run once on the base's build, keep the snapshot, then run again on the change's build with `COCKPIT_BASELINE` pointing at it | | `decisions` | Spec scenarios 15, 16, 18, 19 (Decisions part), 21 (hidden-panel polling) and 22, Phase 7. On **its own** `start` + `seed fleet`: it adds `main-2` to alpha's file (an https image and one answered 404, both from the browser's route for `example.com`, and an image outside the workspace), rules `main-1`, edits `main-2` under the panel, and creates gamma's file. It checks: a **Decisions** entry under every active workspace and none under the dormant one; another workspace's entry opens that window; this workspace's opens one panel with the items; the workspace image renders from an object URL (bytes through the host), the https image renders, the 404 image and the outside image each show *Image not loaded* with the reason; the full-size view opens and closes; a link opens through the host; a ruling writes the file, shows on the card and reaches `main` (Tower's `Decisions notice` log line); a stale fingerprint is refused with the draft kept; no reads while the panel is hidden; four themes switched live without reloading the webview, with the contrast of every visible text in the panel measured against its composited background (none under 3:1; the item id, Submit and an option word at least 4.5:1; every text under 4.5:1 listed in the evidence); the panel restored after a reload; the explanations in a builder-worktree and a no-workspace window; gamma's empty state, then the real `afx decisions init` (it only writes the template), then an item appears; and a request audit: no browser request to the Tower port or carrying the key, and webview frames load only VS Code's webview host page, extension resources, blobs and the remote item images | -| `work` | Spec scenarios 17, 18, 19 (Tower-down for both panels, and Work's window variants) and 22, Phase 8. On **its own** `start` + `seed fleet` (it opens a shell, opens a terminal and stops the Tower). It refreshes alpha's overview first, as `dashboard` does. It checks: *Codev: Open Work* opens one panel (a second run reveals it) with every section and alpha's rows, and none of the dashboard-only pieces (Files panel, tip banner, Open Files & Shells); each progress bar is drawn at its width under the panel's CSP; *Open* opens #102's terminal; *+ Shell* opens a Tower shell; *Refresh* sends `POST /api/overview/refresh` and then a read; #401's spec link opens the file; an issue and a PR link open in the browser through the host; four themes switched live without reloading the webview, with every visible text's contrast measured (none under 3:1; every text under 4.5:1 listed), plus two colours the fixture never draws (a PIR dev-approval row's orange and the spike tag), drawn as probe elements in the real webview for the measurement; the Cockpit's Decisions entries beside Work and Decisions in two groups (the increment-2 shot, dark and light), with the half-width Work view held to fit (no sideways scroll, every *Open* whole, no row label over its links); the panel restored after a reload; the request audit; the isolated Tower stopped (Work keeps its last overview and Decisions its cards, each under *Not connected to Tower*, with no error toast) and started again (Work shows the restarted Tower's overview, which no longer has the fixture's builders; Decisions' notice clears); and the explanations in a builder-worktree and a no-workspace window | +| `work` | Spec scenarios 17, 18, 19 (Tower-down for both panels, and Work's window variants) and 22, Phase 8. On **its own** `start` + `seed fleet` (it opens a shell, opens a terminal and stops the Tower). It refreshes alpha's overview first, as `dashboard` does. It checks: *Codev: Open Work* opens one panel (a second run reveals it) with every section and alpha's rows, and none of the dashboard-only pieces (Files panel, tip banner, Open Files & Shells); each progress bar is drawn at its width under the panel's CSP; *Open* opens #102's terminal; *+ Shell* opens a Tower shell; *Refresh* sends `POST /api/overview/refresh` and then a read; #401's spec link opens the file; an issue and a PR link open in the browser through the host; four themes switched live without reloading the webview, with every visible text's contrast measured (none under 3:1; every text under 4.5:1 listed), plus two colours the fixture never draws (a PIR dev-approval row's orange and the spike tag), drawn as probe elements in the real webview for the measurement; and a progress bar's track shown on its row (1.2:1 or more; the fill's contrast on it is reported); the Cockpit's Decisions entries beside Work and Decisions in two groups (the increment-2 shot, dark and light), with the half-width Work view held to fit (no sideways scroll, every *Open* whole, no row label over its links); the panel restored after a reload; the request audit; the isolated Tower stopped (Work keeps its last overview and Decisions its cards, each under *Not connected to Tower*, with no error toast) and started again (Work shows the restarted Tower's overview, which no longer has the fixture's builders; Decisions' notice clears); and the explanations in a builder-worktree and a no-workspace window | | `reconnect` | **Run last.** A loaded Cockpit keeps its content with Tower down; a fresh window shows *Not connected to Tower*; Tower up + the row's Reconnect restores it. Stops and restarts only the isolated Tower, by PID (`tower-down` / `tower-up`) | A restarted Tower does not reconnect the fixture sessions: its startup reconciliation skips, and diff --git a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs index 0e30c8c6e..fb819f2be 100644 --- a/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs +++ b/apps/vscode/scripts/cockpit-harness/cockpit-verify.mjs @@ -2043,7 +2043,12 @@ function textContrasts({ rootSelector, probes }) { return { kind, what: `${kind} "${el.textContent.trim().slice(0, 24)}"`, contrast: textContrast(el) }; }) .sort((a, b) => a.contrast - b.contrast); + // A progress bar's track against its row, and its fill against the track (null when no bar). + const bar = root.querySelector('.progress-bar'); + const fill = bar?.querySelector('.progress-fill'); + const track = bar ? { onRow: ratio(backdrop(bar), backdrop(bar.parentElement)), fill: fill ? ratio(backdrop(fill), backdrop(bar)) : null } : null; return { + track, marker: window.__codevMarker ?? null, body: getComputedStyle(document.body).backgroundColor, text: getComputedStyle(document.body).color, @@ -2220,12 +2225,14 @@ SCRIPTS.work = async (R, context, page) => { // No text in the panel below 3:1, the floor for anything a reader is meant to see. const faint = [...s.lowest, ...s.probed.map((p) => ({ what: p.label, contrast: p.contrast }))].filter((t) => !(t.contrast >= 3)); if (faint.length) problems.push(`${theme}: faint text ${JSON.stringify(faint)}`); + // The track must show on its row (Light Modern once drew it in the row's own colour). + if (!s.track || !(s.track.onRow >= 1.2)) problems.push(`${theme}: progress track ${JSON.stringify(s.track)}`); } const looks = new Set(Object.values(seen).map((s) => `${s.body}|${s.text}`)); if (looks.size !== themes.length) problems.push(`only ${looks.size} distinct looks across ${themes.length} themes`); if (problems.length) throw new Error(`${problems.join('; ')} — ${JSON.stringify(seen)}`); return { - detail: Object.entries(seen).map(([t, s]) => `${t}: body ${s.body}, text ${s.text}; lowest of ${s.scanned} texts ${s.lowest.map((x) => `${x.contrast} ${x.what}`).join(', ')}; probes ${s.probed.map((p) => `${p.label} ${p.contrast}`).join(', ')}; under 4.5: ${s.under45.join(', ') || 'none'}`).join('; '), + detail: Object.entries(seen).map(([t, s]) => `${t}: body ${s.body}, text ${s.text}; lowest of ${s.scanned} texts ${s.lowest.map((x) => `${x.contrast} ${x.what}`).join(', ')}; probes ${s.probed.map((p) => `${p.label} ${p.contrast}`).join(', ')}; progress track on its row ${s.track.onRow}, fill on track ${s.track.fill}; under 4.5: ${s.under45.join(', ') || 'none'}`).join('; '), shots, }; }); diff --git a/apps/vscode/src/workspace-views/webview/vscode-theme.css b/apps/vscode/src/workspace-views/webview/vscode-theme.css index 18900ad93..95d22d349 100644 --- a/apps/vscode/src/workspace-views/webview/vscode-theme.css +++ b/apps/vscode/src/workspace-views/webview/vscode-theme.css @@ -176,3 +176,10 @@ summary:focus-visible { .recently-closed-row-main { overflow: hidden; } + +/* A progress bar's track. The dashboard draws it in the tertiary background, which Light Modern + maps to the row's own colour: only the fill showed, a dash rather than a bar (found rendered). + A faint mix of the text colour shows on every theme's row. */ +.progress-bar { + background: color-mix(in srgb, var(--codev-wv-fg) 18%, transparent); +} From 22d28d43405c85116810114fa77e5a7184f44544 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:47:10 -0800 Subject: [PATCH 092/140] [Spec 1963][Phase: work_panel] docs: Phase 8 rendered evidence (verify work 14/14, verify decisions 15/15 at b9e5af0f); thread --- codev/state/spir-1963_thread.md | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md index 131348a5b..0cf3a2133 100644 --- a/codev/state/spir-1963_thread.md +++ b/codev/state/spir-1963_thread.md @@ -963,3 +963,58 @@ run. - Both are pre-existing flakes in code this branch does not touch. They are left running, named under "Flaky tests" in PR #1971, and reported to the architect. - **The review file's `## Flaky Tests` section must carry both.** + +### Phase 8: Work panel (2026-11-24) + +- **Feature commit `d96d9c00b`.** `WorkPanels` (`workspace-views/work-panel.ts`): one retained + editor-area panel per window, restored after reload, pushing `OverviewCache` data and the + connection state. `workOverviewState` gives loading until the first overview, then the last + overview under "Not connected to Tower." while not connected. The mapped actions: + - Open → `openBuilderByRoleOrId(id, true)`, only for a builder the overview shows; + - + Shell → `codev.newShell`; + - Refresh → `client.refreshOverview()` (machine-wide POST) then `overviewCache.refresh()`; + - spec/plan/review → `resolveWorkspaceFile` (its first production caller) → `vscode.open`; + a refusal or a missing file warns the user, since they clicked; + - issue/PR links → `openExternal`, http(s) only. + + No dashboard slots are passed, so the dropped affordances are absent. +- **A builder decision, not a plan instruction:** `single-panel.ts` now holds what Work and + Decisions share (single instance, serializer, reveal, observable visibility, the session's + post-after-dispose drop and the http(s) gate). `DecisionsPanels` moved onto it. Its 13 tests + pass unchanged apart from an `EventEmitter` in the `vscode` mock. Phase 9's arrange needs + both panels to take a view column, so one place to add it. +- **Refresh gate:** `workPanels` is a `GatedView`. An existing source-text test + (`cockpit-wiring.test.ts`) pinned the gate's view list and was updated to include it (the + spec allows that for wiring tests when the guarded behaviour is unchanged). +- **Verified:** apps/vscode 130 files / 1764 tests, `tsc` host + webview clean, lint only the 2 + existing `curly` warnings. +- **Harness:** a `verify work` script (scenarios 17, 18, 19 Tower-down part, 22, reload + restore, the unavailable windows, and an increment-2 shot of the Cockpit's Decisions entries + beside both panels). Implementing orange (only `.attention-kind--dev`, a PIR gate the fixture + has no builder for) and the spike tag are measured by drawing a probe element in the real + webview; project and bug tags are in the fixture's rows. +- **What rendering found (fixed in `f03eade1b`).** The first `verify work` run passed 12 of 14: + - Light Modern's chart orange (implementing, a PIR dev-approval row) measured 2.9:1 as + text. `--codev-wv-status-implementing` is now mixed 50/50 from the error and waiting text + colours (VS Code's list colours, made to be read): it stays between red and yellow, as the + dashboard's gate progression has it, and measured 6.7:1 on Dark Modern. + - The Tower-down check expected the fixture's 3 builders back after the restart. A restarted + Tower does not keep fixture sessions (harness README), so the check now compares with + the restarted Tower's own overview. + - The increment-2 shot showed Work broken in a half-width group (~470 px): every *Open* cut + off, backlog reviewer/assignee labels over the spec/plan links. VS Code-only container + queries in `vscode-theme.css` now drop Elapsed and the labels under 760 px, and Progress + under 600 px; row labels clip. The dashboard's layout is untouched. The side-by-side check + now fails on sideways scroll, a cut *Open*, or a label over its links. + - Scenario 19 says *both* panels keep their content under a not-connected notice; the check + covered only Work. It now also holds Decisions to its cards under "Not connected to Tower. + Showing the last version read." and to the notice clearing on recovery. It passed first time. +- **A test race of my own:** the four real-filesystem containment tests in `work-panel.test.ts` + waited one `setTimeout(0)` for `fs.promises.realpath`; two failed under the loaded full suite + (harness running alongside) and passed alone. They now `vi.waitFor` the outcome. Not a + pre-existing flake, so not named as one. +- **One more from looking at the shots (`b9e5af0f6`):** in Light Modern the progress bar's + track vanished (its tertiary background is the row's own colour there), so a bar read as a + dash. VS Code's stylesheet now draws the track as an 18% mix of the text colour, and the + theme check fails if a track does not show on its row (≥ 1.2:1), reporting the fill's + contrast on it. From 30fdcd07b852c5d1ae7a96d948bfe6246f5debe0 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:48:32 -0800 Subject: [PATCH 093/140] chore(porch): 1963 implement build-complete --- .../projects/1963-vscode-alternative-layout-seco/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml index e3ad1693c..d7eff9abb 100644 --- a/codev/projects/1963-vscode-alternative-layout-seco/status.yaml +++ b/codev/projects/1963-vscode-alternative-layout-seco/status.yaml @@ -45,7 +45,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: verification_harness @@ -96,7 +96,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1963/codev/projects/1963-vscode-alternative-layout-seco/1963-decisions_panel-iter1-claude.txt started_at: '2026-11-24T01:12:47.024Z' -updated_at: '2026-11-24T13:06:56.199Z' +updated_at: '2026-11-24T13:48:32.766Z' context_refreshes: - boundary: enter:implement at: '2026-11-24T06:55:50.288Z' From d51e28eeae94a9cee3fe188315c824c51f8f54f7 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 05:52:26 -0800 Subject: [PATCH 094/140] [Spec 1963][Phase: work_panel] fix: panels sized and toned like the workbench (architect review) - Decisions' no-file state is plain description text in VS Code, not the amber notice (an empty state, not a warning); a modifier class lets the host style it, and the dashboard keeps its look. - Font sizes are a --codev-wv-font-size-* type scale (defaults the dashboard's sizes); VS Code maps it to --vscode-font-size, so rows sit at the tree's 13px. Both panel headings share one size. - Work's State column stays on one line in a half-width group; the title gives way. - Harness: shots taken with the pointer parked and hover tooltips closed; the half-width check holds each state to one line; scenario 16 measures the no-file state's colour. --- apps/vscode/scripts/cockpit-harness/README.md | 7 +- .../cockpit-harness/cockpit-verify.mjs | 29 ++++- .../__tests__/workspace-views-theme.test.ts | 18 +++ .../workspace-views/webview/vscode-theme.css | 40 ++++++ .../src/__tests__/DecisionsView.test.tsx | 2 + .../src/__tests__/styles-tokens.test.ts | 19 ++- .../src/components/DecisionsView.tsx | 2 +- packages/workspace-views/src/styles.css | 120 ++++++++++-------- 8 files changed, 171 insertions(+), 66 deletions(-) diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md index 56ce549b3..f99c74b8c 100644 --- a/apps/vscode/scripts/cockpit-harness/README.md +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -148,7 +148,8 @@ To get a different scenario, `stop` and `start` again. ## Scripted Cockpit checks (`verify`) `node $H verify "; + var comment = "", empty = ""; + var re = /^