diff --git a/AGENTS.md b/AGENTS.md index 7e48580..c2528fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,7 @@ owner/repo/workflow filename, not the npm name). | `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract | | `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting | | `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths | +| `docs/testing.md` | test architecture, performance tuning, hybrid core CPU guidelines | | `docs/releasing.md` | npm Trusted Publishing, the bootstrap phases, verification | | `README.md` | install paths, `:PiWeb`, binding & pairing | | `.agents/skills/release/` | how to cut and verify a release | diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..305c80e --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,87 @@ +# Testing & Performance Guide + +This document describes the testing architecture for `pi2d` (both daemon and web console), +along with performance tuning strategies for local development and CI. + +--- + +## 1. Test Architecture + +The repository maintains two independent test suites across two lockfiles: + +| Scope | Path | Runner | Environment | Isolation | Focus | +|---|---|---|---|---|---| +| **Daemon** | `test/` | Vitest (root) | `node` | per-file forks | CLI, routing, auth, instances, IPC, protocol conformance | +| **Web Console** | `web/tests/` | Vitest (web) | `jsdom` | shared worker (`isolate: false`) | React 19 UI, pages, TanStack router/query, token contracts | + +--- + +## 2. Web Test Performance & CPU Optimization + +Web unit tests use React 19, `@testing-library/react` and `jsdom`. + +### 2.1 The DOM Isolation Overhead (`isolate: false`) +* **Problem**: By default, Vitest destroys and rebuilds a clean DOM environment for every single test file. In a suite with 35+ test files, recreating `jsdom` accounted for **52% of total CPU tracking time** (~240s CPU time per run). +* **Optimization**: Set `isolate: false` in `web/vite.config.ts`. + - Environment instances are reused across files within each worker. + - Test files maintain clean state using standard teardown hooks in `tests/setup.ts` (`cleanup()`, `localStorage.clear()`, theme reset). + - **Result**: Wall clock time drops by ~37%, and total CPU time is reduced by ~40% with 100% test pass rate. + +### 2.2 Worker Concurrency on Hybrid Core Architectures +* On modern CPUs with Performance and Efficient cores (e.g., Intel 12th+ Gen like i7-12700H with 6P + 8E cores): + - Vitest defaults to spawning workers matching total logical threads (e.g. 20 workers). + - This saturates E-cores, leading to high thermal throttling, CPU lockup, and system unresponsiveness. + - **Recommendation for heavy multi-tasking / laptops**: + ```bash + pnpm --dir web exec vitest run --maxWorkers=6 + ``` + Confining workers to P-core count keeps tests fast while leaving headroom for Neovim and the desktop compositor. + +### 2.3 JSDOM Stubs vs. Virtual Console Noise +* `jsdom` includes incomplete stubs (e.g., `window.scrollTo` and `HTMLCanvasElement.getContext`) that write noisy "Not implemented" warnings to stderr on every call. +* These stubs are explicitly overridden in `web/tests/setup.ts`: + ```typescript + if (typeof window !== "undefined") { + window.scrollTo = vi.fn(); + } + if (typeof HTMLCanvasElement !== "undefined") { + HTMLCanvasElement.prototype.getContext = vi.fn(); + } + ``` + This eliminates thousands of lines of terminal I/O overhead and keeps test logs readable. + +### 2.4 Why JSDOM over Happy-DOM +* While `happy-dom` is slightly faster, real-world evaluation in `pi2-web` revealed subtle incompatibilities with TanStack Router navigation microtasks and React 19 asynchronous `act(...)` scheduling (causing failures in `ConnectPage` and `StatusPage`). +* We retain `jsdom` with `isolate: false` to preserve 100% browser behavior fidelity while achieving near-identical speed. + +### 2.5 Timeout Defensive Line +* Set `testTimeout: 15000` in `web/vite.config.ts` to prevent transient timeouts when the host CPU is under heavy background load. + +--- + +## 3. Daily Development Workflow + +### 3.1 Incremental Test Runs (Recommended) +Avoid running all 35+ tests on every keystroke. Run only what changed: + +```bash +# Run only test files related to uncommitted git changes +pnpm --dir web exec vitest run --changed + +# Run a specific test file +pnpm --dir web exec vitest run tests/chat.composer.test.tsx +``` + +### 3.2 Watch Mode +Vitest's HMR-powered watch mode tracks module dependency graphs and re-runs only the affected test tree: + +```bash +pnpm --dir web test +``` + +### 3.3 Pre-commit Full Gate +Before submitting or tagging releases, run the comprehensive verification chain: + +```bash +pnpm typecheck && pnpm test && pnpm --dir web typecheck && pnpm --dir web exec vitest run +``` diff --git a/web/README.md b/web/README.md new file mode 100644 index 0000000..b2671aa --- /dev/null +++ b/web/README.md @@ -0,0 +1,25 @@ +# pi2-web + +React port of the pi2 web UI prototype, built into `web/dist` and served statically by `pi2 daemon`. + +## Development + +```bash +# Start dev server with proxy to daemon (:7676) +pnpm --dir web dev + +# Typecheck +pnpm --dir web typecheck + +# Run test suite +pnpm --dir web exec vitest run + +# Run only changed tests or specific file +pnpm --dir web exec vitest run --changed +pnpm --dir web exec vitest run tests/chat.composer.test.tsx + +# Watch mode +pnpm --dir web test +``` + +For performance tuning, concurrency settings, and DOM environment details, see [docs/testing.md](../docs/testing.md). diff --git a/web/tests/setup.ts b/web/tests/setup.ts index 920398b..cb5aea0 100644 --- a/web/tests/setup.ts +++ b/web/tests/setup.ts @@ -4,25 +4,38 @@ import { afterEach, vi } from "vitest"; afterEach(() => { cleanup(); - localStorage.clear(); - document.documentElement.removeAttribute("data-theme"); + if (typeof localStorage !== "undefined") { + localStorage.clear(); + } + if (typeof document !== "undefined") { + document.documentElement.removeAttribute("data-theme"); + } }); -// next-themes / responsive helpers expect these in jsdom. -if (!window.matchMedia) { - Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query: string) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), - removeListener: vi.fn(), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), - }); +if (typeof window !== "undefined") { + // next-themes / responsive helpers expect these in jsdom. + if (!window.matchMedia) { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query: string) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); + } + + // jsdom ships stubs that print "Not implemented: ..." errors to stderr. + // Replace them with silent vi.fn() mocks. + window.scrollTo = vi.fn(); +} + +if (typeof HTMLCanvasElement !== "undefined") { + HTMLCanvasElement.prototype.getContext = vi.fn(); } if (!globalThis.ResizeObserver) { @@ -34,6 +47,6 @@ if (!globalThis.ResizeObserver) { globalThis.ResizeObserver = ResizeObserverStub; } -if (!Element.prototype.scrollIntoView) { +if (typeof Element !== "undefined") { Element.prototype.scrollIntoView = vi.fn(); } diff --git a/web/vite.config.ts b/web/vite.config.ts index 78cae35..f882e7e 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -5,6 +5,25 @@ import { defineConfig } from "vitest/config"; const DAEMON = "http://127.0.0.1:7676"; const REPO_ROOT = path.resolve(import.meta.dirname, ".."); +/** + * Dev/preview proxy for one daemon surface. + * + * `changeOrigin` rewrites `Host` only, so the browser's own `Origin` + * (`http://localhost:5173`) reaches the daemon — whose allowlist is derived from + * the daemon's own port — and every POST/WS upgrade would be rejected with + * `403 origin is not allowed`. Presenting the daemon's own origin (always in that + * derived allowlist) keeps `pnpm --dir web dev` working without `PI2_ORIGINS`, + * and keeps the daemon's Origin check on rather than bypassing it. + */ +function daemonProxy({ ws = false } = {}) { + return { + target: DAEMON, + changeOrigin: true, + headers: { origin: DAEMON }, + ...(ws ? { ws: true } : {}), + }; +} + export default defineConfig({ plugins: [react()], resolve: { @@ -22,21 +41,14 @@ export default defineConfig({ port: 5173, strictPort: false, proxy: { - "/api": { - target: DAEMON, - changeOrigin: true, - }, - "/ws": { - target: DAEMON, - changeOrigin: true, - ws: true, - }, + "/api": daemonProxy(), + "/ws": daemonProxy({ ws: true }), }, }, preview: { proxy: { - "/api": { target: DAEMON, changeOrigin: true }, - "/ws": { target: DAEMON, changeOrigin: true, ws: true }, + "/api": daemonProxy(), + "/ws": daemonProxy({ ws: true }), }, }, test: { @@ -45,6 +57,10 @@ export default defineConfig({ setupFiles: ["./tests/setup.ts"], include: ["tests/**/*.test.{ts,tsx}"], css: true, + // Reuse environment instances across test files within workers to avoid + // recreating jsdom 35 times (which accounted for ~52% of CPU time). + isolate: false, + testTimeout: 15000, restoreMocks: true, }, });