test(e2e): add the full web-console end-to-end gate

- API/WS driver A0–A12: auth/pairing, workspaces, instances, session create,
  real model streaming, abort, model/thinking, history paging, resync,
  multi-workspace isolation, subagents and a deterministic attention/diff
  trigger (attention-ext.ts).
- Playwright driver B1–B14 + C1–C4: guard/pairing, workspaces, chat streaming,
  abort, panels, attention, status/devices, reconnect, deep links, i18n/theme,
  responsive overflow and console errors.
- lib.sh isolates every run (runtime/data/state/agent dirs, ephemeral port,
  fresh workspaces) and reaps by /proc env; run-all.sh builds both sides.
  Document the plan and the 31/31 acceptance run.
This commit is contained in:
yuez committed 2026-10-21 20:42:34 +08:00
1 parent 0ef019f58d
commit b02f4e9070
11 files changed
+7119

No files matched your search

+18
View File
@@ -35,3 +35,21 @@ The plugin starts the daemon lazily when it is not running; you normally do not
| `src/cli/` | `pi2d` (daemon) and `pi2` (attach/status/doctor) | | `src/cli/` | `pi2d` (daemon) and `pi2` (attach/status/doctor) |
| `fixtures/` | golden event streams + expected session state (shared with pi2.nvim tests) | | `fixtures/` | golden event streams + expected session state (shared with pi2.nvim tests) |
| `docs/protocol.md` | the wire contract (browser ↔ daemon ↔ plugin) | | `docs/protocol.md` | the wire contract (browser ↔ daemon ↔ plugin) |
## Testing
Unit contracts are hermetic (`pnpm test` → `vitest run`; `pnpm lint` typechecks). The web-console
gate is end-to-end and real: a daemon, one headless nvim per workspace, a real `pi --mode rpc`
behind it and, for the browser layer, Playwright against the built bundle.
```bash
pnpm test # unit: daemon + web (vitest)
bash scripts/e2e/run-api.sh # A0–A12: API/WS against a real backend
bash scripts/e2e/run-ui.sh # B1–B14, C1–C4: Playwright against web/dist
bash scripts/e2e/run-all.sh # both, API first
```
Every suite runs in its own `mktemp` root with isolated runtime/data/state/agent dirs and
`pi` sessions redirected away from `~/.pi/agent`; `E2E_SKIP_BUILD=1` reuses an existing build
and `E2E_KEEP=1` keeps the artifacts (report, logs, screenshots). Scenario ids, isolation
details, skip conditions and report paths: [docs/e2e.md](docs/e2e.md).
+148
View File
@@ -0,0 +1,148 @@
# Web console v1 — end-to-end acceptance report
- Date: 2026-10-21
- Gate: `bash scripts/e2e/run-all.sh`
- Result: **GREEN — 31/31 scenarios PASS, 0 FAIL, 0 SKIP** (4m13s)
- Plan: [`docs/e2e.md`](e2e.md)
## Environment
| Component | Version |
|---|---|
| node | v22.23.1 |
| nvim | 0.12.6 |
| pi | 1.3.0 |
| daemon | `pi2d` @ `31f3630` + working-tree fixes |
| plugin | `pi2.nvim` `feat/web-console` @ `ffec47c` + working-tree fixes |
| browser | Chrome (Playwright 1.63, headless) |
| model | `cliproxyapi` (real turns; `deepseek-v4-pro` in the browser run) |
Every suite starts an isolated daemon on an ephemeral port with throwaway
`PI2_RUNTIME_DIR` / `PI2_DATA_DIR` / `PI2_STATE_DIR` / `PI_CODING_AGENT_DIR`
and a fresh workspace; real pi turns are used for streaming, abort, subagent,
attention/diff and history. No user state or the user's daemon on `:7676` is
touched.
## Results
### API/WS suite (`scripts/e2e/api-e2e.mjs`) — 13/13 PASS (49.1s)
A0 bootstrap/auth · A1 workspaces · A2 instance lifecycle · A3 session create +
snapshot · A4 prompt + streaming · A5 abort · A6 model/thinking · A7 history
pagination · A8 reconnect/resync · A9 multi-workspace isolation · A10 subagents ·
A11 attention/diff review · A12 error matrix.
A11 is deterministic: `scripts/e2e/attention-ext.ts` registers an `e2e_request`
tool that emits a diff-shaped `extension_ui_request`; the test asserts the file is
absent before consent, accepts the review, and verifies the file plus a second
answer returning `E_ATTENTION_RESOLVED`.
### Browser suite (`scripts/e2e/ui-e2e.mjs`) — 18/18 PASS (180.1s)
B1 guard · B2 manual pair · B3 paste-link pair · B4 workspaces/add · B5 session
tree/create/rename/close · B6 prompt + streaming · B7 abort · B8 model/thinking ·
B9 panels/subagent dispatch/preview/tasks · B10 attention dialog · B11 status/
devices/revoke/disconnect · B12 reconnect · B13 valid + unknown deep links ·
B14 i18n/theme · C1 responsive (1440/768/380) · C2 breakpoint navigation ·
C3 dark/light screenshots · C4 zero unexpected console errors/pageerrors.
## Bugs found by the E2E pass and fixed
### Plugin (`pi2.nvim`)
- `session.create`/`open` acked the placeholder `tmp-N`; the backend id migrated
~2 s later with no announcement, so the daemon could not route `prompt.send`
(`E_SESSION_NOT_FOUND`) and the browser went dark. Commands now wait for the
real id (≤5 s, `pending` on timeout), keep an alias, announce
`pi2:session{sessionId,previousSessionId}` on the old id, and refresh
`instance_state`.
- Attention leaked: resolution was only emitted from `send_response`, the snapshot
cleared only non-empty queues, projections dropped title/options/timeout/payload,
and a locally-open dialog removed the entry (blocking web answers). Every
removal path now emits `pi2:attention_resolved`; requests default to 120 s;
snapshots always project `attention[]`; diff requests are `method="diff"` with
the files payload; a locally-open request stays answerable (first answer wins).
- Snapshots carried no entries; the reducer grew without bound. Snapshots now
carry the newest ≤50 entries / ≤256 KB, the reducer retains 500.
- `text_delta` seq could regress when coalesced; seq is assigned at flush time.
- Unknown commands returned `E_INTERNAL`; the bridge routes them through
`commands.dispatch` (`E_METHOD_NOT_ALLOWED`).
- `session.setThinking`/`setModel` accepted invalid values; both now validate
(thinking levels; model against the workspace models cache).
- `queue.remove`/`setSteer` now accept the wire queue ids / mode; `task.output`
is implemented; `subagent.dispatch` accepts the canonical `items[]` shape;
`attention.respond` accepts the structured response table.
### Daemon (`pi2d`)
- Workspaces outside `PI2_WORKSPACE_ROOTS` returned `500 E_INTERNAL`; now
`403 E_FORBIDDEN`.
- Snapshot `entries` tails were dropped (only `state` forwarded); the cache and
the WS frame now preserve `{state, entries}` for cached and cold subscribes.
- The first WS subscribe for a fresh session sent no snapshot; snapshots are
forwarded from the plugin bus and awaited on cold subscribe.
- `cli.token` was rotated before the singleton lock, invalidating a running
daemon; it is now minted only after the lock is held.
- `/api/v1/info` gained additive `hostname`, `os`, `version`, `uptimeMs`, `pid`,
`port`; `/health` reflects instance/workspace/auth state.
### Web (`pi2d/web`)
- Pairing posted `pair.redeem` to the bearer-gated `/api/v1/cmd` → every pairing
401. The manual/scan flows now redeem the public `POST /api/v1/pair`
(`{code,kind,deviceName}`), persist scopes, and keep the `next` deep link.
- WebSocket auth sent `Bearer <token>` while the daemon hashes the raw token;
the client now strips the prefix on every socket.
- Duplicate assistant messages / `PONGONG`: snapshot tails and REST history had
different id spaces, and coalesced deltas could arrive after `message_end`.
Merge is now one-to-one with a text/ts fallback; late deltas for a done entry
are dropped.
- Dialogs were unclickable (content behind the Radix overlay); fixed in the
component + CSS.
- Chat commands used the wrong shapes for setModel, attention responses, diff
accept/reject, subagent dispatch, queue remove/steer, task output and WS
resume. All now match the plugin contract.
- Status devices read `{devices}` while the daemon returns an array; devices now
list, revoke and disappear correctly; the WS state, identity fields and a live
pairing code/QR are rendered.
- `/chat/<unknown>` silently fell back to `sessions[0]`; it now shows
“Session not found” + Retry + back link and never renders another session.
## Non-blocking notes (accepted)
- A4 may warn that a coalesced `text_delta` is written after `agent_settled`
(the 50 ms flush timer outlives the turn); the browser drops stale deltas.
- A6/B8 note that the selected model clamps `thinking=low` to a supported level
(`high` here). The command is accepted and the UI reflects the clamped level;
this is model capability, not a plugin failure.
- `diagnostics.eventRate` / `slowQueries` remain constants (no metric source).
- Attention `input`/`editor` methods still have no free-text web field (cancel
only); tracked as a follow-up.
- `scripts/e2e/full-e2e.sh` and `visual.sh` predate the new harness; `run-all.sh`
is the gate. They are kept for ad-hoc debugging.
## Reproduction
```bash
cd /home/yuez/Workspace/Neovim/pi2d
bash scripts/e2e/run-all.sh # builds daemon + web, runs API then browser
# individual suites
bash scripts/e2e/run-api.sh
bash scripts/e2e/run-ui.sh
```
`E2E_KEEP=1` keeps the temp root (logs, `report/api-results.json`,
`report/ui-e2e.json`, `screens/*.png`); `E2E_SKIP_BUILD=1` reuses existing
`dist/` builds for a fast rerun.
## Residual risk
- The browser suite drives one real model (provider-dependent timing). Waits are
bounded (120 s turns, 15 s instances) and the run is green, but a slow provider
can still push a turn past the budget.
- The E2E harness is Linux-specific (`/proc`-based reaping) and expects
`jq`, `nvim`, `pi`, node ≥22 and Playwright/Chrome available.
- Cross-source message dedupe is text/timestamp based for synthetic-id vs raw-id
entries; identical repeated replies rely on one-to-one pairing and closest-ts
ordering (message counts/text stay correct; ids may attach to the other copy).
+401
View File
@@ -0,0 +1,401 @@
# End-to-end test plan (web console v1)
Status: **authoritative for the v1 web-console E2E gate**. This plan covers the three
processes that make the console real, and describes the harness that implements it:
`scripts/e2e/lib.sh` (lifecycle, isolation) plus the `run-api.sh` / `run-ui.sh` /
`run-all.sh` drivers (see §2, §3 and §7).
```
browser (React in web/dist)
│ HTTP + WS
▼
pi2d (src/) ── JSONL unix socket ──▶ headless nvim + pi2.nvim web layer
└── pi --mode rpc (real model)
```
Authority, highest first:
1. `docs/protocol.md` + `src/protocol/types.ts` (wire contract)
2. `pi2.nvim` `lua/pi/web/**` (state/command authority)
3. `lint`/`vitest` suites (unit contracts)
4. `pi2-web-ui-design/design/DESIGN-SPEC.md` + `web/ACCEPTANCE.md` (UI intent; some
details are stale, see the design recon)
The static prototype repo is a **visual reference only**. Assertions in this plan target
the real daemon/plugin/browser, never `MOCK.*` data.
## 1. What “complete” means
The v1 gate is green when:
- **A0–A12** (API/WS against a real headless nvim + real pi) pass.
- **B1–B14** (Playwright against the daemon-served production bundle) pass.
- **C1–C4** (responsive, theme, language, no console errors) pass.
- `tsc --noEmit`, `vitest run` (daemon), `vitest run` (web) stay green.
- Every failure found while running this plan is either fixed and re-verified, or
recorded as an explicit, justified non-blocking gap in the report.
Real model calls are allowed and expected (one short turn plus one abort turn, one
subagent turn). The suite must still be deterministic: each run uses a fresh workspace,
a fresh pairing code, ephemeral ports and isolated state directories.
## 2. Harness topology and isolation
Four scripts, not one: **`scripts/e2e/lib.sh`** is the lifecycle library (source, then call
`e2e_init <suite>`), and the three drivers are thin wrappers over it — **`run-api.sh`** (A*),
**`run-ui.sh`** (B*/C*), **`run-all.sh`** (both, API first, aggregating the exit code).
`e2e_init` creates a temp root per suite, so `run-all.sh` never shares state between the two
runs:
| Resource | Value |
|---|---|
| `E2E_ROOT` | `mktemp -d /tmp/pi2-e2e-<suite>.XXXXXX` — `api` and `ui` get separate roots |
| `PI2_RUNTIME_DIR` | `$E2E_ROOT/run` (`cli.token`, `daemon.json`, instance sockets) |
| `PI2_DATA_DIR` | `$E2E_ROOT/data` (devices, workspaces) |
| `PI2_STATE_DIR` | `$E2E_ROOT/state` (daemon + instance logs) |
| `PI_CODING_AGENT_DIR` **and** `PI2_CODING_AGENT_DIR` | `$E2E_ROOT/agent` — both names are exported: `pi` and daemon discovery each read one of them, so neither can fall back to `~/.pi/agent` |
| `PI2_WORKSPACE_ROOTS` | `$E2E_ROOT/workspaces` (only the test workspaces under it are addable) |
| `PI2_PORT` | `0` (ephemeral; the real port is read from `run/daemon.json`) |
| `PI2_STATIC_DIR` | `<repo>/web/dist` (rebuilt before the UI suite unless `E2E_SKIP_BUILD=1`) |
| `PI2_NVIM_INIT` | `<repo>/scripts/e2e/host-init.lua` |
| `PI2_E2E_PLUGIN` | plugin worktree (default `/home/yuez/Workspace/Neovim/pi2.nvim-web`; must contain `lua/pi/web/`) |
| `PI2_NVIM_BIN` | `nvim` from `PATH`, overridable |
Overridable knobs:
| Variable | Effect |
|---|---|
| `E2E_SKIP_BUILD=1` | Skip `e2e_build` (no `tsc`, no `pnpm -s build` in `web/`); requires a current `dist/` and `web/dist` |
| `E2E_KEEP=1` | Keep the temp root instead of deleting it; a **failing** suite forces it and prints the path |
| `E2E_REPO` | Repository root (default: two levels up from `lib.sh`) |
| `PI2_E2E_PLAYWRIGHT_MODULE` | Explicit `playwright` module path; otherwise `require("playwright")`, then the mise `npm-playwright` installs are tried |
| `PI2_E2E_CHROME` | Chrome binary for Playwright (default `/usr/bin/google-chrome-stable`, bundled Chromium when absent) |
| `PI2_LOG_LEVEL` | Daemon log level (default `info`) |
`scripts/e2e/host-init.lua` is the headless instance's `-u` init: it prepends the plugin under
test to `runtimepath`, disables swapfile/shada, and calls
`require("pi").setup({ web = { enabled = true, log = true, auto_start = false }, cli = { args = { "--extension", <dir>/attention-ext.ts } } })`.
The test-only extension (`scripts/e2e/attention-ext.ts`, asserted readable at init) is how A11
and B10 get a real `extension_ui_request`: it registers an `e2e_request` tool plus a
`before_agent_start` trigger keyed on the `[[e2e-attention]]` / `[[e2e-attention-reject]]`
markers, so the diff review does not depend on the model choosing to call the tool.
Rules:
- Before anything starts, `e2e_init` requires `node`, `nvim`, `pi`, `jq` and `curl`, a plugin
worktree with `lua/pi/web/commands.lua`, a built `dist/cli/pi2d.js`, and `host-init.lua`.
Missing pieces exit 2 with the artifacts path.
- Never touch a daemon already running in the default runtime dir. `e2e_stop` terminates the
daemon it started, then reaps every process whose command line contains `$E2E_ROOT`
(headless nvim hosts and their `pi --mode rpc` children). No machine-wide `pkill`.
- Pairing codes are single-use and expire (600 s); one per suite.
- Workspaces are fresh empty dirs under the suite root. No previous-run workspace is reused.
- Browser language is pinned to `en` (`pi2-lang`) before the app boots; theme/width
are set per case. Text assertions use the English catalog.
- Every wait is bounded: instance `ready` ≤ 20 s, model turn ≤ 120 s, abort settle ≤ 10 s,
WS `hello_ack` ≤ 10 s.
## 3. Layers
| Layer | Runner | Covers |
|---|---|---|
| API/WS | `scripts/e2e/api-e2e.mjs` (Node, `ws`) | A* — protocol, commands, events, reducer-visible state |
| Browser | `scripts/e2e/ui-e2e.mjs` (Playwright, Chromium) | B* — pairing, pages, real interactions, streaming DOM |
| Visual/responsive | same browser script, `screens/` | C* — overflow, screenshots, theme, i18n, console errors |
`run-all.sh` runs the API suite first (it proves the backend the browser suite depends on)
then the browser suite, each in its own temp root. Both drivers are standalone when the
`E2E_*`/`PI2_*` environment is already set (`ui-e2e.mjs` additionally needs `E2E_BASE` and
`E2E_CLI_TOKEN`).
## 4. Scenarios
All scenario ids below are implemented in the two drivers: `scenario("A0", …)` … `scenario("A12", …)`
in `api-e2e.mjs`, `scenario("B1", …)` … `scenario("B14", …)` and `scenario("C1", …)` …
`scenario("C4", …)` in `ui-e2e.mjs`. A driver exits non-zero only on **FAIL**; SKIP is
tolerant, and every skip is printed with its reason and written into the report.
Known SKIP paths (deterministic by design, not failures):
- dependent scenarios when their prerequisite produced nothing (e.g. `A4`–`A12` skip when
`A3` created no session);
- `A5` when the slow turn streamed no delta inside the abort window;
- `A11` when no `pi2:attention_request` and no `attention[]` entry arrives within 45 s — the
skip message still says host init “enables only pi.web”, but `host-init.lua` does load
`attention-ext.ts`; the scenario now skips only if the request genuinely never surfaces;
- `B8` when the workspace reports no models to switch to;
- `B10` when no attention dialog appears within 45 s (it notes whether the file was written
without consent);
- `B12`/`B13` when `B6` produced no session to reuse;
- any scenario not reached because the suite's total runtime budget was exhausted.
The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** still applies.
### 4.1 A — API/WS suite
**A0 Bootstrap & auth**
- daemon starts on an ephemeral port, writes `daemon.json`, `cli.token` is 0600.
- `GET /api/v1/info` → `v=1`, `daemonId`/`capabilities` present.
- `GET /api/v1/health` → `ok=true`, `static` item ok (web/dist served).
- `GET /` → 200 HTML containing the app root.
- unauthenticated `GET /api/v1/workspaces` → 401 `E_UNAUTHORIZED`; bogus bearer → 401.
- `POST /api/v1/pair` redeem: valid code → `{token, device}`; same code again → 401;
the token authorizes the API; `DELETE /api/v1/devices/:id` revokes it (next call 401).
**A1 Workspaces**
- `workspace.add {cwd, trust:true}` for W1/W2 → 202, 16-hex `workspaceId`, `trusted`.
- re-adding the same cwd returns the same id (idempotent).
- a cwd outside `PI2_WORKSPACE_ROOTS` → 4xx, no workspace created.
- `GET /api/v1/workspaces` shape: `workspaceId,cwd,name,sessionCount,liveCount,instance`.
**A2 Instance lifecycle**
- `instance.ensure {workspaceId}` (W1) → 202; poll `GET /workspaces` until
`instance.status === "ready"` ≤ 15 s.
- `instance.ensure` is idempotent.
- `GET /api/v1/workspaces/:id/sessions` → `{sessions:[…]}` (object, not array).
**A3 Session create + snapshot**
- `session.create {workspaceId:W1}` → 202 with a non-placeholder `sessionId`.
- WS: `auth` → `hello_ack`; `subscribe {sessionIds:[sid]}` → `snapshot` with
`sessionId/epoch/seq/state`; state has `sessionId,workspaceId,cwd,status,model,
thinking,usage,contextUsage,queue,todos,tasks,batches,subagents,attention,entries`.
- `seq` is monotonic; every subsequent event has the same epoch and `seq+1`.
- the sessions REST record shows the new session as `live:true`.
**A4 Prompt + streaming (real model)**
- `prompt.send {text:"Reply with exactly the word PONG and nothing else."}`.
- WS events: `message_start`/`message_update` deltas for the assistant, no locally
invented user entry (the user entry arrives as an event), `message_end` replaces the
assistant blocks, `agent_settled` → status `idle`.
- final assistant text, trimmed and lowercased, is exactly `pong`; exactly one assistant
entry for the turn; no duplicate entry ids; usage/contextUsage updated.
- `GET entries?limit=50` returns the same entry ids in the same order as the snapshot.
**A5 Abort**
- start a slow turn (`"Count from 1 to 200, one number per line."`); wait for the first
assistant delta; `prompt.abort`; within 10 s `agent_settled{aborted:true}` and status
`idle`; no assistant delta after the settle; a second abort is harmless (no error
state; 2xx or idempotent error code).
**A6 Model / thinking**
- `GET /api/v1/models?workspaceId=W1` → `{providers:[{provider,models:[…]}]}`.
- `session.setThinking {level:"low"}` → ack; snapshot/session reports `thinking=low`.
- `session.setModel {model:{provider,id}}` with a listed model → ack; session reports
that provider/id; the next snapshot preserves it.
- invalid level/model → 400 with a stable error code, no state change.
**A7 History pagination**
- after A4, fetch `entries?limit=2&workspaceId=W1&sessionFile=<file>` → `{entries,
nextCursor|hasMore}`; the second page (`before=<cursor>`) returns different entries;
concatenation has no duplicate ids and ends at the oldest entry; `hasMore=false` at
the end; ordering is stable.
**A8 Reconnect / resync**
- open a second WS, subscribe to the session, close it mid-turn, reconnect with the
daemon's resume shape (`payload.since={sessionId,epoch,seq}`).
- response is a `snapshot` (or `resync_required` followed by one); the final state
contains the same entry ids as a fresh subscribe; no seq regression.
**A9 Multi-workspace isolation**
- create a session in W2 and send a short prompt; W1's session query never lists the W2
session; a WS subscribed only to W1 receives no W2 events; W1 models query remains
workspace-scoped.
**A10 Subagents**
- `subagent.dispatch {items:[{task:"Reply with exactly the word SUB and nothing else.",
name:"e2e-sub"}]}` → ack; within 120 s `pi2:batch` (running → completed) and
`pi2:subagents` with the child (active/completed); the child session is listed/queryable;
`subagent.stop {targets:[<child>]}` → ack and child becomes `dormant`/`completed`;
replaying the same `clientRequestId` does not create a second batch.
**A11 Attention / diff review (pre-execution)**
- host init enables diff review for `write`/`edit`; prompt the model to create
`e2e-attention.txt` with content `hello-e2e`.
- before answering: `pi2:attention_request` arrives with `requestId/method/title/options/
payload.files`, `attention[]` in the snapshot contains it, and the file does **not**
exist yet.
- `attention.respond {requestId, response:{value: <JSON string {result:"Accepted"}>}}`
→ ack; `pi2:attention_resolved`; the file exists with the requested content; the tool
block is accepted; a second respond gets `E_ATTENTION_RESOLVED`.
- reject case: another file is requested; respond `{cancelled:true}` (or Rejected);
the file does not exist and the turn continues/settles without error state.
**A12 Errors**
- unknown session id → `E_SESSION_NOT_FOUND`; malformed `cmd` → `E_BAD_REQUEST`;
unknown method → `E_METHOD_NOT_ALLOWED`; oversized/malformed JSON does not kill the
daemon (next request still 200).
- every error is a JSON body with `code`, `message`, `retryable`.
### 4.2 B — Browser suite (Playwright, daemon-served bundle)
**B1 Unpaired guard**
- empty storage → `/workspaces` redirects to `/connect?next=%2Fworkspaces`; the connect
page has **no** nav/rail/tabbar and no server chip; `/status` and `/chat` behave the same.
- `next` with an external URL is rejected; after pairing the user returns to the
allow-listed `next`.
**B2 Pairing (manual)**
- enter host/port/pairing code/device name → `POST /api/v1/pair` succeeds; the summary
shows server/endpoint/device/scopes; localStorage keys are written; redirect to `next`.
- wrong code → inline localized error, still unpaired, form stays usable.
- while paired, `/connect` shows the summary, not the form; disconnect asks for
confirmation and clears the connection (returns to `/connect`).
**B3 Pairing (QR/deep link)**
- paste a `pi2://pair?host=…&port=…&code=…` link in the scan fallback → confirmation
modal shows the masked token → confirm pairs; cancel changes nothing.
- the daemon's own `http://host:port/pair/<code>` URL is accepted by the parser.
**B4 Workspaces**
- seeded W1/W2 render as `[data-workspace-id]` rows, pinned/last-active order, context
bar counts equal the API counts, no server selector.
- “Open new workspace” validates an empty path inline, then adds a real workspace via
the API, shows a toast, and navigates into `/chat?workspace=<id>`.
- empty state and API-error + retry render without a white screen.
**B5 Chat: session tree**
- `/chat?workspace=W1` lists sessions from the API; a live session has a status dot;
selecting a row navigates to `/chat/<sid>?workspace=W1`.
- “New session” creates a real session, routes to it, and the tree gains the row.
- rename persists through the plugin; close asks for confirmation and removes the row.
- the workspace selector switches trees (W1 → W2) without leaking rows.
**B6 Chat: prompt + streaming**
- send “Reply with exactly the word PONG and nothing else.” via Enter.
- exactly one user entry appears (sourced from the server), then an assistant entry
grows while streaming and settles with exactly `PONG`; the composer send button
returns from Abort to Send; status badge returns to idle; no console errors.
- Shift+Enter inserts a newline and does not send.
**B7 Chat: abort**
- start a slow prompt; while busy the send button is Abort; click it; within 10 s the
status is idle, partial text remains, no further text arrives.
**B8 Chat: model/thinking**
- change the thinking select to `low` → API command sent, state/toast update, value
survives a reload; change the model select → the same, and the tree subtitle updates.
**B9 Chat: panels (Subagents / Todo / Tasks)**
- panel tabs switch; each renders either real data or its empty state; no mock copy.
- Dispatch modal creates a real batch (`items[]`), the subagent row/batch appears, and
the preview modal opens (real tail or an explicit empty state); “Back to parent” works.
- Tasks tab shows real tasks or the empty state; the task output modal shows the real
output tail or an explicit unsupported state (no fake pid).
**B10 Attention**
- with a real diff request in flight, the blocking dialog appears with server-provided
title/options; Accept writes the file; the dialog closes; a second client cannot answer.
**B11 Status**
- `/status` renders info/health/resources/models/tasks/devices/connection cards from the
API; no server/workspace selector; resources refresh; health items show pass/fail.
- paired devices come from the API and can be revoked with confirmation; a revoked
device token stops working.
- disconnect clears connection and returns to `/connect`.
**B12 Reconnect**
- take the browser offline (or restart the daemon) and restore it; the connection state
indicator reflects reconnecting → open, history reloads/resyncs, and the composer is
usable again; no duplicate entries.
**B13 Deep links**
- `/chat/<sid>?workspace=W1` and `/chat?workspace=W1` land on the intended
workspace/session; an unknown session shows an error + retry, not a blank page.
**B14 i18n / theme**
- switch language via the topbar menu: `<html lang>` and visible copy change; switching
back restores English; no missing-key placeholder.
- switch theme light/dark/system: `<html data-theme>` changes and persists.
### 4.3 C — Responsive / visual
- **C1** 1440×900, 768×1024, 380×780 on `/workspaces`, `/chat`, `/status`, `/connect`
(unpaired): `documentElement.scrollWidth <= innerWidth + 1`; no element overflowing
the viewport; screenshots saved to `$E2E_ROOT/screens/`.
- **C2** connect has no bottom tab bar; nav pages have exactly three navigation items at
every breakpoint (tabbar <600, rail 600–839, sidebar ≥840).
- **C3** dark and light screenshots of each page are non-blank (>10 kB, >500 unique
colors) and contain the page heading.
- **C4** no `pageerror` and no console `error` on any page load or interaction (allowlist
only known-benign browser messages, recorded in the report).
## 5. Failure triage and fix ownership
For every failed assertion:
1. Record `scenario ID`, the exact command/UI step, observed vs expected, and the
relevant daemon/instance/plugin log tail in `$E2E_ROOT/report/`.
2. Classify:
- **harness bug** (flaky wait, wrong selector) → fix the harness, not the product.
- **contract mismatch** (web sends a different shape than the plugin/daemon accepts)
→ align on the protocol shape; prefer fixing the web client when the plugin/daemon
already matches `docs/protocol.md`.
- **product bug** (state never emits, file written before consent, missing handler)
→ fix the owning layer.
3. Fix in one layer at a time, with exclusive file ownership per subagent; never let two
agents edit the same file concurrently.
4. Re-run the failed scenario, then the full suite. Unit tests (`vitest` in `pi2d` and
`pi2d/web`) must stay green after every fix.
5. Do not mark a scenario PASS from a static grep or a screenshot alone; assert the
observable behavior described above.
## 6. Report format
Both drivers write machine-readable + human-readable artifacts into `$E2E_ROOT/report/`:
| Suite | Files |
|---|---|
| API/WS | `report/api-results.json` (scenario, status, duration, checks, notes, evidence) and `report/summary.md` |
| Browser | `report/ui-e2e.json` and `report/ui-e2e.md`, screenshots in `screens/*.png` (`b10-no-attention.png` and per-failure shots included) |
`report/summary.md` (API) contains a per-scenario table, each failed assertion with
expected/observed, notes, an evidence block, a “Suspected product bugs” section built from
`DEVIATIONS`, and the daemon/plugin log tails. `ui-e2e.md` adds the seeded workspace ids,
the Playwright module/Chrome actually used, and one section per scenario with every
assertion. `ui-e2e.mjs` also copies its markdown to `/tmp/pi2-e2e-recon/e2e-ui-run.md`.
Logs live in `$E2E_ROOT/logs/`: `<suite>.log` (build output + driver stderr) and
`pi2d.log` / `pi2d.stdout` for the daemon.
The summary must state which scenarios passed, which failed with observed vs expected,
which were skipped and why (non-blocking only), and the command that reproduces the run.
## 7. Commands
```bash
cd /home/yuez/Workspace/Neovim/pi2d
# backend only (A0–A12): tsc, then daemon + headless nvim + real pi
bash scripts/e2e/run-api.sh
# browser (B1–B14, C1–C4): also builds web/dist (pnpm), then Playwright
bash scripts/e2e/run-ui.sh
# both, API first; exit 0 only when neither suite failed
bash scripts/e2e/run-all.sh
```
Both suites rebuild by default; when the build is already current:
```bash
E2E_SKIP_BUILD=1 bash scripts/e2e/run-api.sh
E2E_SKIP_BUILD=1 bash scripts/e2e/run-ui.sh
```
Artifacts: `$E2E_ROOT/{run,data,state,agent,workspaces,logs,screens,report}`. `E2E_KEEP=1`
keeps the temp root and prints its path; the default removes it after the report is written
(a failing suite forces `E2E_KEEP=1`).
Auxiliary scripts (not part of the gate): `scripts/e2e/full-e2e.sh` is the earlier single-run
smoke (daemon → headless nvim → pi → REST) that predates `lib.sh`, and
`scripts/e2e/visual.sh` only boots daemon + plugin and captures the four pages for design
review.
## 8. Non-goals (v1)
- Multi-server aggregation (single-server invariant; out of scope by contract).
- Golden-image pixel diffs (screenshots are artifacts + blank/overflow checks only).
- Load/backpressure benchmarks (P2; separate task).
- TUI ↔ browser live-sync timing (needs a GUI nvim; covered separately by the plugin's
own e2e suites).
- Mobile camera scanning (no camera in CI; the paste fallback is tested instead).
File diff suppressed because it is too large. Load diff
+134
View File
@@ -0,0 +1,134 @@
/**
* Test-only pi extension for the pi2d API/WS end-to-end suite (docs/e2e.md A11).
*
* The suite must prove the pre-execution attention/diff contract without a real
* terminal UI:
*
* pi2:attention_request (method "diff", payload.files)
* → attention.respond {value: '{"result":"Accepted"}'}
* → file written, pi2:attention_resolved, second respond E_ATTENTION_RESOLVED
*
* `e2e_request` is a model-callable tool whose `execute()` blocks in
* `ctx.ui.select(title, ["Accept", "Reject"])`. In RPC mode that becomes an
* `extension_ui_request` frame with `method: "select"`, which pi.nvim's
* `pi.attention` decodes: a `title` that is JSON with `toolName: "write"|"edit"`
* is treated as a diff review (`pi.attention.decode_diff_payload`), so the
* request surfaces as `method: "diff"` with the decoded `payload` (see
* `pi2.nvim-web/lua/pi/web/instance.lua:project_attention_entry`).
*
* The title payload uses the web console's documented diff shape
* `{toolName, files:[{path, before, after}]}` (see
* `pi2d/web/src/features/chat/diff.ts:diffFilesFromPayload`), so the same JSON
* drives both the plugin's attention classification and the web diff view.
*
* Determinism: the select is issued from the tool call (no timing tricks). A
* `before_agent_start` fallback keyed on the marker `[[e2e-attention]]` /
* `[[e2e-attention-reject]]` makes the trigger independent of whether the model
* actually calls the tool: the marker fires the request once per turn, and a
* model-initiated `e2e_request` call in the same turn reuses that decision
* instead of opening a second dialog.
*
* Loaded only by `scripts/e2e/host-init.lua` via `cli.args = {"--extension", …}`.
*/
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { Type } from "typebox";
const ACCEPT_MARKER = "[[e2e-attention]]";
const REJECT_MARKER = "[[e2e-attention-reject]]";
const ACCEPT_FILE = "e2e-attention.txt";
const REJECT_FILE = "e2e-attention-reject.txt";
const CONTENT = "hello-e2e";
interface Decision {
accepted: boolean;
path: string;
raw: unknown;
}
/** The diff payload the plugin classifies as attention kind `diff`. */
function diffTitle(path: string, after: string): string {
return JSON.stringify({ toolName: "write", files: [{ path, before: "", after }] });
}
/**
* Interpret an `extension_ui_response.value` as an accept/reject verdict.
* Accepts the pi.nvim diff-review encoding (`'{"result":"Accepted"}'`), a bare
* option label, or an already-decoded object. `undefined`/`null` (cancelled or
* timeout) counts as a reject.
*/
function verdictOf(value: unknown): boolean {
if (value === undefined || value === null) return false;
if (typeof value === "string") {
const text = value.trim();
if (text === "") return false;
if (/^accept/i.test(text)) return true;
if (/^(reject|cancel|deny)/i.test(text)) return false;
try {
return verdictOf(JSON.parse(text));
} catch {
return /accept/i.test(text);
}
}
if (typeof value === "object") {
const record = value as { result?: unknown; cancelled?: unknown; confirmed?: unknown };
if (record.cancelled === true) return false;
if (typeof record.result === "string") return /^accept/i.test(record.result);
if (typeof record.confirmed === "boolean") return record.confirmed;
}
return false;
}
export default function attentionExtension(pi: ExtensionAPI) {
/** Decision taken for the current turn, so one turn never opens two dialogs. */
let turn: Decision | null = null;
let requests = 0;
async function request(ctx: ExtensionContext, file: string): Promise<Decision> {
requests += 1;
const raw = await ctx.ui.select(diffTitle(file, CONTENT), ["Accept", "Reject"]);
const accepted = verdictOf(raw);
if (accepted) {
writeFileSync(join(ctx.cwd, file), CONTENT);
}
return { accepted, path: file, raw };
}
pi.registerTool({
name: "e2e_request",
label: "E2E Attention Request",
description:
"Request user approval for a pending write through the pre-execution attention/diff review path. " +
"Call it exactly once when the user asks for it, then report whether it was accepted or rejected.",
promptGuidelines: [
"When a user message asks you to call e2e_request, call it once before you reply.",
],
parameters: Type.Object({}),
executionMode: "sequential",
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
const decision = turn ?? (await request(ctx, ACCEPT_FILE));
turn = decision;
return {
content: [
{
type: "text",
text: `${decision.accepted ? "Accepted" : "Rejected"} ${decision.path} (attention request ${requests})`,
},
],
details: { accepted: decision.accepted, path: decision.path },
};
},
});
pi.on("before_agent_start", async (event, ctx) => {
turn = null;
const prompt = typeof event.prompt === "string" ? event.prompt : "";
if (prompt.includes(REJECT_MARKER)) {
turn = await request(ctx, REJECT_FILE);
} else if (prompt.includes(ACCEPT_MARKER)) {
turn = await request(ctx, ACCEPT_FILE);
}
return undefined;
});
}
+17
View File
@@ -2,7 +2,23 @@
-- Minimal, hermetic: only the plugin under test on the runtimepath, with the -- Minimal, hermetic: only the plugin under test on the runtimepath, with the
-- web console enabled and diagnostics enabled. Setting up the plugin here also -- web console enabled and diagnostics enabled. Setting up the plugin here also
-- makes `pi.host` skip its own `setup()` call. -- makes `pi.host` skip its own `setup()` call.
--
-- `cli.args` reaches every `pi --mode rpc` process the plugin spawns, so the
-- test-only attention extension (`scripts/e2e/attention-ext.ts`) is present in
-- the session the daemon drives (docs/e2e.md A11 — pre-execution diff review
-- needs something that emits `extension_ui_request`).
local function here()
local source = debug.getinfo(1, "S").source
if source:sub(1, 1) == "@" then
source = source:sub(2)
end
return vim.fn.fnamemodify(source, ":p:h")
end
local plugin = vim.env.PI2_E2E_PLUGIN or "/home/yuez/Workspace/Neovim/pi2.nvim-web" local plugin = vim.env.PI2_E2E_PLUGIN or "/home/yuez/Workspace/Neovim/pi2.nvim-web"
local attention_ext = here() .. "/attention-ext.ts"
assert(vim.fn.filereadable(attention_ext) == 1, "e2e attention extension missing: " .. attention_ext)
vim.opt.runtimepath:prepend(plugin) vim.opt.runtimepath:prepend(plugin)
vim.opt.swapfile = false vim.opt.swapfile = false
vim.opt.shadafile = "NONE" vim.opt.shadafile = "NONE"
@@ -10,4 +26,5 @@ vim.g.mapleader = " "
require("pi").setup({ require("pi").setup({
web = { enabled = true, log = true, auto_start = false }, web = { enabled = true, log = true, auto_start = false },
cli = { args = { "--extension", attention_ext } },
}) })
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env bash
# Shared lifecycle for the web-console end-to-end suites.
#
# Source this file, then:
# e2e_init api # temp dirs + trap + report dir + prereq checks
# e2e_build # tsc (and optionally the web bundle)
# e2e_start_daemon # ephemeral port, isolated runtime/data/state/agent dirs
# e2e_pair # CLI-token pair.create -> device token (exported)
# e2e_add_workspace ... # workspace.add + instance.ensure, prints the workspace id
# e2e_stop # kill the daemon and every process started from E2E_ROOT
#
# Everything the suite starts is reachable from $E2E_ROOT: the daemon's runtime
# dir is in the nvim `--listen` path and the workspace cwd is in the pi cmdline,
# so cleanup never needs a machine-wide pkill.
#
# shellcheck shell=bash
E2E_REPO="${E2E_REPO:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
E2E_PLUGIN="${PI2_E2E_PLUGIN:-/home/yuez/Workspace/Neovim/pi2.nvim-web}"
E2E_NVIM_BIN="${PI2_NVIM_BIN:-$(command -v nvim || true)}"
E2E_PLAYWRIGHT_MODULE="${PI2_E2E_PLAYWRIGHT_MODULE:-}"
e2e_log() { printf '%s\n' "$*" >&2; }
e2e_fail() {
e2e_log "FATAL: $*"
e2e_log "artifacts: ${E2E_ROOT:-<uninitialised>}"
exit 2
}
e2e_need() {
command -v "$1" >/dev/null 2>&1 || e2e_fail "missing required command: $1"
}
e2e_init() {
local suite="${1:?suite name}"
E2E_SUITE="$suite"
E2E_ROOT="$(mktemp -d "/tmp/pi2-e2e-${suite}.XXXXXX")"
export E2E_ROOT
export E2E_REPO E2E_PLUGIN E2E_NVIM_BIN E2E_PLAYWRIGHT_MODULE
export PI2_RUNTIME_DIR="$E2E_ROOT/run"
export PI2_DATA_DIR="$E2E_ROOT/data"
export PI2_STATE_DIR="$E2E_ROOT/state"
# The daemon (`src/core/paths.ts`) reads PI_CODING_AGENT_DIR; `pi` itself
# reads the same variable. Keep both names in sync so discovery cannot see
# the user's real ~/.pi/agent sessions.
export PI_CODING_AGENT_DIR="$E2E_ROOT/agent"
export PI2_CODING_AGENT_DIR="$E2E_ROOT/agent"
export PI2_WORKSPACE_ROOTS="$E2E_ROOT/workspaces"
export PI2_PORT=0
export PI2_LOG_LEVEL="${PI2_LOG_LEVEL:-info}"
export PI2_STATIC_DIR="${PI2_STATIC_DIR:-$E2E_REPO/web/dist}"
export PI2_NVIM_INIT="${PI2_NVIM_INIT:-$E2E_REPO/scripts/e2e/host-init.lua}"
export PI2_E2E_PLUGIN="$E2E_PLUGIN"
export PI2_NVIM_BIN="$E2E_NVIM_BIN"
mkdir -p "$PI2_RUNTIME_DIR" "$PI2_DATA_DIR" "$PI2_STATE_DIR" \
"$PI2_CODING_AGENT_DIR" "$PI2_WORKSPACE_ROOTS" \
"$E2E_ROOT/logs" "$E2E_ROOT/screens" "$E2E_ROOT/report"
E2E_LOG="$E2E_ROOT/logs/$suite.log"
: >"$E2E_LOG"
trap e2e_stop EXIT INT TERM
e2e_need node
e2e_need nvim
e2e_need pi
e2e_need jq
e2e_need curl
[ -n "$E2E_NVIM_BIN" ] || e2e_fail "nvim not found"
[ -f "$E2E_PLUGIN/lua/pi/web/commands.lua" ] ||
e2e_fail "plugin worktree has no web layer: $E2E_PLUGIN"
[ -f "$E2E_REPO/dist/cli/pi2d.js" ] ||
e2e_fail "dist/cli/pi2d.js missing; run e2e_build"
[ -f "$E2E_REPO/scripts/e2e/host-init.lua" ] || e2e_fail "host-init.lua missing"
e2e_log "==> $suite root: $E2E_ROOT"
e2e_log " plugin: $E2E_PLUGIN ($(git -C "$E2E_PLUGIN" rev-parse --short HEAD 2>/dev/null || echo '?'))"
e2e_log " daemon: $E2E_REPO ($(git -C "$E2E_REPO" rev-parse --short HEAD 2>/dev/null || echo '?'))"
}
e2e_build() {
local web="${1:-0}"
e2e_log "==> build daemon"
(cd "$E2E_REPO" && ./node_modules/.bin/tsc -p tsconfig.json) >>"$E2E_LOG" 2>&1 ||
e2e_fail "daemon build failed (see $E2E_LOG)"
if [ "$web" = "1" ]; then
e2e_log "==> build web bundle"
(cd "$E2E_REPO/web" && npm_config_verify_deps_before_run=false pnpm -s build) >>"$E2E_LOG" 2>&1 ||
e2e_fail "web build failed (see $E2E_LOG)"
[ -f "$E2E_REPO/web/dist/index.html" ] || e2e_fail "web/dist/index.html missing"
fi
}
# Wait until the daemon publishes run/daemon.json, then environment-ready.
e2e_start_daemon() {
local log="$E2E_ROOT/logs/pi2d.log"
: >"$log"
e2e_log "==> starting pi2d (isolated, port 0)"
# `exec` makes $! the node process itself, not the wrapping subshell, so
# the trap can actually stop the daemon.
(cd "$E2E_REPO" && exec node dist/cli/pi2d.js --foreground >"$E2E_ROOT/logs/pi2d.stdout" 2>"$log") &
E2E_DAEMON_PID=$!
export E2E_DAEMON_PID
local _
for _ in $(seq 1 200); do
[ -f "$PI2_RUNTIME_DIR/daemon.json" ] && break
kill -0 "$E2E_DAEMON_PID" 2>/dev/null || {
tail -40 "$log" >&2 || true
e2e_fail "pi2d exited before writing daemon.json"
}
sleep 0.05
done
[ -f "$PI2_RUNTIME_DIR/daemon.json" ] || e2e_fail "daemon.json was not written"
E2E_PORT="$(jq -r '.port' "$PI2_RUNTIME_DIR/daemon.json")"
E2E_BASE="http://127.0.0.1:$E2E_PORT"
E2E_CLI_TOKEN="$(tr -d '\n' <"$PI2_RUNTIME_DIR/cli.token")"
export E2E_PORT E2E_BASE E2E_CLI_TOKEN
for _ in $(seq 1 100); do
if curl -fsS --max-time 2 "$E2E_BASE/api/v1/health" >/dev/null 2>&1; then
break
fi
sleep 0.05
done
curl -fsS --max-time 3 "$E2E_BASE/api/v1/health" >/dev/null 2>&1 ||
e2e_fail "daemon did not answer /api/v1/health"
e2e_log " listening on $E2E_BASE"
}
e2e_api() { # e2e_api <method> <path> [curl args...]
local method="$1" path="$2"
shift 2
curl -sS --max-time 30 -X "$method" \
-H "Authorization: Bearer $E2E_CLI_TOKEN" \
-H 'Content-Type: application/json' "$@" "$E2E_BASE$path"
}
e2e_cmd() { # e2e_cmd '<json>'
e2e_api POST /api/v1/cmd -d "${1:?json body}"
}
e2e_http_status() { # e2e_http_status <method> <path> [curl args...]
local method="$1" path="$2"
shift 2
curl -sS --max-time 30 -o /dev/null -w '%{http_code}' -X "$method" \
-H "Authorization: Bearer $E2E_CLI_TOKEN" \
-H 'Content-Type: application/json' "$@" "$E2E_BASE$path"
}
e2e_pair() {
local name="${1:-E2E browser}"
local created code token
created="$(e2e_cmd '{"method":"pair.create","params":{"ttlSec":600}}')" ||
e2e_fail "pair.create failed"
code="$(jq -r '.code // empty' <<<"$created")"
[ -n "$code" ] || e2e_fail "pair.create returned no code: $created"
token="$(curl -sS --max-time 10 -X POST -H 'Content-Type: application/json' \
-d "{\"code\":\"$code\",\"deviceName\":\"$name\",\"kind\":\"laptop\"}" \
"$E2E_BASE/api/v1/pair" | jq -r '.token // empty')"
[ -n "$token" ] || e2e_fail "pair redeem failed"
E2E_DEVICE_TOKEN="$token"
E2E_PAIR_CODE="$code"
export E2E_DEVICE_TOKEN E2E_PAIR_CODE
e2e_log " paired device ${token:0:8}…"
}
e2e_add_workspace() { # e2e_add_workspace <dir> -> workspace id on stdout
local dir="$1" resp id
mkdir -p "$dir"
resp="$(e2e_cmd "$(jq -nc --arg cwd "$dir" '{method:"workspace.add",params:{cwd:$cwd,trust:true}}')")" ||
e2e_fail "workspace.add failed for $dir"
id="$(jq -r '.workspace.workspaceId // .workspaceId // empty' <<<"$resp")"
[ -n "$id" ] || e2e_fail "workspace.add returned no id: $resp"
printf '%s' "$id"
}
e2e_ensure_instance() { # e2e_ensure_instance <workspaceId> [timeout-seconds]
local id="$1" timeout="${2:-20}" status
e2e_cmd "$(jq -nc --arg id "$id" '{method:"instance.ensure",params:{workspaceId:$id}}')" >/dev/null ||
e2e_fail "instance.ensure failed for $id"
for _ in $(seq 1 $((timeout * 10))); do
status="$(e2e_api GET /api/v1/workspaces |
jq -r --arg id "$id" '.[] | select(.workspaceId==$id) | .instance.status // empty')"
case "$status" in
ready) return 0 ;;
degraded | stopped) e2e_fail "instance $id became $status" ;;
esac
sleep 0.1
done
e2e_fail "instance $id was not ready within ${timeout}s (last: ${status:-unknown})"
}
# PIDs that belong to this run. The daemon does not carry E2E_ROOT in argv,
# so also match its environment (PI2_RUNTIME_DIR is inherited by the managed
# nvim hosts and their pi children).
e2e_pids() {
local pid
{
ps -eo pid=,args= | grep -F -- "$E2E_ROOT" | grep -v -F -- 'grep -F' | awk '{print $1}' || true
for pid in $(pgrep -f 'pi2d|pi\.host|pi --mode rpc|nvim --headless' 2>/dev/null || true); do
if tr '\0' '\n' <"/proc/$pid/environ" 2>/dev/null |
grep -Fxq "PI2_RUNTIME_DIR=$PI2_RUNTIME_DIR"; then
echo "$pid"
fi
done
} | sort -u
}
# Kill every process that belongs to this run (daemon, managed nvim hosts and
# their pi children), then verify nothing is left behind.
e2e_reap() {
local pids pid
pids="$(e2e_pids)"
for pid in $pids; do
kill -TERM "$pid" 2>/dev/null || true
done
sleep 0.2
pids="$(e2e_pids)"
for pid in $pids; do
kill -KILL "$pid" 2>/dev/null || true
done
sleep 0.1
pids="$(e2e_pids)"
if [ -n "$pids" ]; then
e2e_log "WARN: processes still reference $E2E_ROOT: $pids"
fi
}
e2e_stop() {
local code=$?
trap - EXIT INT TERM
if [ -n "${E2E_DAEMON_PID:-}" ]; then
kill -TERM "$E2E_DAEMON_PID" 2>/dev/null || true
for _ in $(seq 1 100); do
kill -0 "$E2E_DAEMON_PID" 2>/dev/null || break
sleep 0.05
done
kill -KILL "$E2E_DAEMON_PID" 2>/dev/null || true
wait "$E2E_DAEMON_PID" 2>/dev/null || true
fi
e2e_reap
if [ "${E2E_KEEP:-0}" = "1" ]; then
e2e_log "artifacts kept: $E2E_ROOT"
else
rm -rf "$E2E_ROOT"
fi
exit "$code"
}
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Full web-console E2E gate: API/WS suite, then the browser suite.
# Each suite gets its own isolated temp root (see lib.sh).
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
overall=0
echo "==> [1/2] API/WS suite"
if ! bash "$HERE/run-api.sh"; then
overall=1
echo "==> API/WS suite FAILED"
fi
echo "==> [2/2] browser suite"
if ! bash "$HERE/run-ui.sh"; then
overall=1
echo "==> browser suite FAILED"
fi
if [ "$overall" -eq 0 ]; then
echo "E2E OK"
else
echo "E2E FAILED (see the artifacts printed above)"
fi
exit "$overall"
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# A0–A12: protocol/API/WS end-to-end against daemon + headless nvim + real pi.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=lib.sh
source "$HERE/lib.sh"
e2e_init api
if [ "${E2E_SKIP_BUILD:-0}" != "1" ]; then e2e_build 0; fi
e2e_start_daemon
e2e_pair "E2E API"
set +e
node "$HERE/api-e2e.mjs"
rc=$?
set -e
if [ "$rc" -ne 0 ]; then
E2E_KEEP=1
e2e_log "API suite FAILED (exit $rc); artifacts: $E2E_ROOT"
fi
exit "$rc"
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# B1–B14 + C1–C4: Playwright against the daemon-served production bundle.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=lib.sh
source "$HERE/lib.sh"
e2e_init ui
if [ "${E2E_SKIP_BUILD:-0}" != "1" ]; then e2e_build 1; fi
e2e_start_daemon
e2e_pair "E2E browser"
# The browser suite creates its own workspaces (through the API and through the
# UI), so lib.sh only provides the paired daemon here.
set +e
node "$HERE/ui-e2e.mjs"
rc=$?
set -e
if [ "$rc" -ne 0 ]; then
E2E_KEEP=1
e2e_log "UI suite FAILED (exit $rc); artifacts: $E2E_ROOT"
fi
exit "$rc"
File diff suppressed because it is too large. Load diff