mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
refactor: run every benchmark with strobe (#60880)
This commit is contained in:
parent
77264eb66e
commit
fe04656465
234 changed files with 3427 additions and 13712 deletions
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: app-e2e-tests
|
||||
description: Use when writing, changing, reviewing, or debugging Playwright e2e tests in packages/app/e2e (regression keepers and user stories). Covers the mocked opencode server harness and the Bun static server, per-test isolation, page-load and route cost, the suite-wide service-worker block, races with first mount, hover, measurement, clock, dialogs and shortcuts, projects, shards and worker scheduling, rehearsing Windows timing locally, and diagnosing a CI flake from its artifacts. Not for component tests (stories mounted on packages/stories) or e2e/performance benchmarks.
|
||||
description: Use when writing, changing, reviewing, or debugging Playwright e2e tests in packages/app/e2e (regression keepers and user stories). Covers the mocked opencode server harness and the Bun static server, per-test isolation, page-load and route cost, the suite-wide service-worker block, races with first mount, hover, measurement, clock, dialogs and shortcuts, projects, shards and worker scheduling, rehearsing Windows timing locally, and diagnosing a CI flake from its artifacts. Not for component tests (stories mounted on packages/stories) or the strobe benchmarks in packages/app/perf.
|
||||
---
|
||||
|
||||
# App e2e tests
|
||||
|
|
@ -12,7 +12,7 @@ All paths below are relative to `packages/app` unless they start with `packages/
|
|||
## What a test runs against
|
||||
|
||||
- **No opencode backend.** Each shard leg runs `bun --cwd packages/app test:e2e:built --shard=<n>/2` (`check-test.yml:287-292`). It builds once and starts one Bun static server, `e2e/utils/serve.ts`, on `127.0.0.1:${PLAYWRIGHT_PORT ?? 3000}`. All 5 workers share it (`playwright.config.ts:23-27`).
|
||||
- `serve.ts` keeps vite preview's SPA fallback rules. Do not move built e2e back to vite preview. On case-insensitive file systems it synchronously reads the whole `dist/_assets` directory (about 3,100 files) for every asset request, so every worker's page loads wait in line. The `e2e/performance` configs still use it to keep their baselines comparable.
|
||||
- `serve.ts` keeps vite preview's SPA fallback rules. Do not move built e2e back to vite preview. On case-insensitive file systems it synchronously reads the whole `dist/_assets` directory (about 3,100 files) for every asset request, so every worker's page loads wait in line.
|
||||
- **The API is an in-memory mock per page,** running in the test worker. `mockOpenCodeServer` (`e2e/utils/mock-server.ts:202`):
|
||||
- answers `page.route("**/api/**")` with an Effect HttpApi handler;
|
||||
- fakes `/api/event` SSE with an init-script `fetch` override;
|
||||
|
|
@ -54,7 +54,7 @@ All paths below are relative to `packages/app` unless they start with `packages/
|
|||
- **Real-time waits cost their full length on every run and retry** (`settings-wsl.spec.ts:268-276` waits out a 10 s health check). Prefer `page.clock`:
|
||||
- install it before the `goto` or `reload` whose timers you need (`timeline-stream.spec.ts:1700`);
|
||||
- keep fast-forwards under the client's 45 s event-stream idle timeout (`packages/client/src/solid/connection.ts:35`).
|
||||
- **Leave benchmark pacing out of regression tests.** The `sendAll` delays and `messageDelay` exist for benchmarks (`timeline.ts:306`, `mock-server.ts:82`). Hold message pages with `beforeMessagesResponse` instead.
|
||||
- **Leave pacing out of regression tests.** The `sendAll` delays (`timeline.ts:326`) pace workloads; tests wait for the resulting UI state. Hold message pages with `beforeMessagesResponse` instead.
|
||||
|
||||
## Wait for state, not time: races CI found
|
||||
|
||||
|
|
@ -118,7 +118,7 @@ Run from `packages/app`:
|
|||
- [ ] Check the cost on a noisy machine. Other agents add load, and local A/Bs at a load average of 20-35 were inconclusive.
|
||||
- Compare the medians of interleaved before/after runs at `--workers=5`, or the step durations in the report (`bun run test:e2e:report`).
|
||||
- Count every `goto` and `reload` you added.
|
||||
- [ ] `bun run typecheck:e2e` reports 4 existing errors: `timeline-stream.spec.ts:1822`, `:1825`, and two `e2e/performance` probes. Add none. If you changed `playwright.config.ts`, update `test-browser/playwright-config.test.ts`.
|
||||
- [ ] `bun run typecheck:e2e` reports 2 existing errors: `timeline-stream.spec.ts:1822` and `:1825`. Add none. If you changed `playwright.config.ts`, update `test-browser/playwright-config.test.ts`.
|
||||
|
||||
## When CI flakes
|
||||
|
||||
|
|
|
|||
18
bun.lock
18
bun.lock
|
|
@ -11,6 +11,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"@ast-grep/cli": "0.44.0",
|
||||
"@hona/strobe": "catalog:",
|
||||
"@opencode/client": "workspace:*",
|
||||
"@oxlint/plugins": "1.60.0",
|
||||
"@tsconfig/bun": "catalog:",
|
||||
|
|
@ -86,6 +87,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"@happy-dom/global-registrator": "20.0.11",
|
||||
"@hona/strobe": "catalog:",
|
||||
"@playwright/test": "catalog:",
|
||||
"@sentry/vite-plugin": "catalog:",
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
|
|
@ -291,6 +293,7 @@
|
|||
"devDependencies": {
|
||||
"@ai-sdk/openai-compatible": "2.0.41",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.301",
|
||||
"@hona/strobe": "catalog:",
|
||||
"@opencode/http-recorder": "workspace:*",
|
||||
"@parcel/watcher-darwin-arm64": "2.5.1",
|
||||
"@parcel/watcher-darwin-x64": "2.5.1",
|
||||
|
|
@ -327,6 +330,7 @@
|
|||
"devDependencies": {
|
||||
"@brendonovich/vite-plugin-opencode": "0.1.3",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@hona/strobe": "catalog:",
|
||||
"@lydell/node-pty": "catalog:",
|
||||
"@opencode/app": "workspace:*",
|
||||
"@opencode/client": "workspace:*",
|
||||
|
|
@ -865,6 +869,7 @@
|
|||
"solid-sonner": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hona/strobe": "catalog:",
|
||||
"@solidjs/meta": "catalog:",
|
||||
"@tsconfig/node22": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
|
|
@ -1050,6 +1055,7 @@
|
|||
"@effect/platform-node-shared": "4.1.0",
|
||||
"@effect/sql-sqlite-bun": "4.1.0",
|
||||
"@effect/sql-sqlite-node": "4.1.0",
|
||||
"@hona/strobe": "0.3.0",
|
||||
"@kobalte/core": "0.13.13",
|
||||
"@lydell/node-pty": "1.2.0-beta.12",
|
||||
"@npmcli/arborist": "9.4.0",
|
||||
|
|
@ -1689,6 +1695,18 @@
|
|||
|
||||
"@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="],
|
||||
|
||||
"@hona/strobe": ["@hona/strobe@0.3.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.3.0", "@hona/strobe-darwin-x64": "0.3.0", "@hona/strobe-linux-arm64": "0.3.0", "@hona/strobe-linux-x64": "0.3.0", "@hona/strobe-win32-x64": "0.3.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-cTtyAlXKevzGbUY/fFf02PufqaBQ0Fdree0A3YdGSa8oIruKWv04hQ3Es2PV5ULQgeMAuXCmXKWexhH2QYYRLA=="],
|
||||
|
||||
"@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.3.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-yiMhlr62ob6YLMlfIEvlDpHeDDYB/SyIYA9zeZTGQNM83ABexChjRXYJ2rEvHdWol+LL/Ood8f4stdNnK6d1DA=="],
|
||||
|
||||
"@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.3.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-hVC8oC3VyP4NPdc/caT2+9HxO68yQAir1jdmVdQgVY5t8f1jqO5cU+5f1aGviPc5IzfOq7PP8p3I3dt++jxEpw=="],
|
||||
|
||||
"@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.3.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-EnphpmsfwNIq+bnyUYzMzxprv8Uhm8BuO8mrrvkgrjndL9Zz3ciE8nF93DKoeRdomc7rpmsCzXYm4y+JlrqUWg=="],
|
||||
|
||||
"@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.3.0", "", { "os": "linux", "cpu": "x64" }, "sha512-J3Ac2+moTFk9H3AX/RIIS6bgi53eBgIn7WvT7YQmDN98DS9O8/eSpWY51nBsq3aJ8a35oqS/9vWBUBJt5aGiEw=="],
|
||||
|
||||
"@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.3.0", "", { "os": "win32", "cpu": "x64" }, "sha512-IIgLYxaYRsPkvVQ6Ji7d7tLG9BcewzL1tAj+RPqDyJpdT/e6QoGH7IEVQpMKBLv5T72ZeaezXV9+b2TX/9Uq/A=="],
|
||||
|
||||
"@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="],
|
||||
|
||||
"@ibm/plex": ["@ibm/plex@6.4.1", "", { "dependencies": { "@ibm/telemetry-js": "^1.5.1" } }, "sha512-fnsipQywHt3zWvsnlyYKMikcVI7E2fEwpiPnIHFqlbByXVfQfANAAeJk1IV4mNnxhppUIDlhU0TzwYwL++Rn2g=="],
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
exact = true
|
||||
# Only install newly resolved package versions published at least 3 days ago.
|
||||
minimumReleaseAge = 259200
|
||||
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta"]
|
||||
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta"]
|
||||
|
||||
[test]
|
||||
root = "./do-not-run-tests-from-root"
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@
|
|||
"dev:console": "ulimit -n 10240 2>/dev/null; bun run --cwd packages/console/app dev",
|
||||
"dev:stats": "bun sst shell --stage=production -- bun run --cwd packages/stats/app dev",
|
||||
"dev:www": "bun run --cwd services/www dev",
|
||||
"bench:devex": "bun run --cwd packages/app test:bench:devex",
|
||||
"lint": "oxlint && ast-grep scan -c script/ast-grep/gui-plugins/sgconfig.yml && bun script/sdk-docs.ts",
|
||||
"lint:changed": "bun script/lint-changed.ts",
|
||||
"lint:effect-patterns": "ast-grep scan -c script/ast-grep/sgconfig.yml packages/util/src packages/core/src packages/server/src packages/protocol/src packages/cli/src",
|
||||
|
|
@ -52,6 +51,7 @@
|
|||
"@effect/sql-sqlite-node": "4.1.0",
|
||||
"@npmcli/arborist": "9.4.0",
|
||||
"@types/bun": "1.4.3",
|
||||
"@hona/strobe": "0.3.0",
|
||||
"@types/cross-spawn": "6.0.6",
|
||||
"@octokit/rest": "22.0.0",
|
||||
"@opentui/core": "0.8.1",
|
||||
|
|
@ -114,6 +114,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"@ast-grep/cli": "0.44.0",
|
||||
"@hona/strobe": "catalog:",
|
||||
"@opencode/client": "workspace:*",
|
||||
"@oxlint/plugins": "1.60.0",
|
||||
"@tsconfig/bun": "catalog:",
|
||||
|
|
|
|||
1
packages/app/.gitignore
vendored
1
packages/app/.gitignore
vendored
|
|
@ -1,6 +1,5 @@
|
|||
src/assets/theme.css
|
||||
e2e/test-results
|
||||
e2e/performance/results/
|
||||
e2e/playwright-report
|
||||
component-tests/test-results
|
||||
component-tests/playwright-report
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
## Priorities
|
||||
|
||||
- Prioritise, in this order: stability, simplicity, performance.
|
||||
- Before changing session or timeline code, record a production benchmark baseline and compare it after the change.
|
||||
- Before changing session or timeline code, benchmark it against `origin/dev` with strobe (`packages/app/perf/README.md`): `strobe bench packages/app/perf/<area>.bench.ts --base origin/dev --head .`.
|
||||
|
||||
## Debugging
|
||||
|
||||
|
|
|
|||
|
|
@ -21,4 +21,5 @@
|
|||
- Build pages with the shared harness in `utils/` (`app.ts`, `workspace.ts`, `mock-server.ts` with `mockServers` and the mock PTY). Do not hand-write routing, storage seeding, or fixtures inside a spec. If the harness lacks something, add it to `utils/` once rather than copying setup.
|
||||
- Files in `utils/` must not end in `.spec.ts` or `.test.ts`, or Playwright runs them as tests.
|
||||
- Assert what the user sees and can do. Assert exact pixels or CSS values only when that measurement is the contract, and then only once, in the owning keeper.
|
||||
- `performance/` holds benchmarks that CI does not run. Never prove correctness with a benchmark, and never copy benchmark code into a regression spec; import it from `utils/`.
|
||||
- Benchmarks live in `packages/app/perf` and run with strobe; CI does not run them. Never prove correctness with a benchmark, and never copy benchmark code into a regression spec; a fixture both need belongs in `utils/`.
|
||||
- `stability/` (layout continuity under CPU stress, `bun run test:stability`) has its own config and stays out of CI. Desktop startup, packaged and `bun dev:desktop`, is a strobe benchmark: `packages/desktop/perf/startup.bench.ts`.
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
- Prioritize stability, then simplicity, then measurement overhead.
|
||||
- Use Playwright for scenario control, isolation, and completion checks.
|
||||
- Use Chrome Performance traces for generic browser profiling.
|
||||
- Use Electron `contentTracing` for packaged multi-process profiling.
|
||||
- Keep custom probes only for product-specific measurements.
|
||||
- Do not duplicate measurements across the harness, probes, and traces.
|
||||
- Run benchmarks serially to avoid cross-test contention.
|
||||
- Run benchmarks against production builds.
|
||||
- Keep detailed profiling opt-in when it changes workload behavior.
|
||||
- Preserve raw diagnostic data or use lossless representations.
|
||||
- Do not enforce machine-dependent performance thresholds.
|
||||
- Assert scenario completion and metric collection only.
|
||||
- Keep normal test discovery free of manual benchmarks.
|
||||
|
|
@ -1,172 +0,0 @@
|
|||
# Manual app performance suite
|
||||
|
||||
The app's high-volume performance diagnostics live under `packages/app/e2e/performance` and are excluded from normal local and CI Playwright discovery. The benchmark config builds the app and serves the production bundle before running scenarios serially.
|
||||
|
||||
The `devex` category is the explicit exception to the production-build rule. It measures development commands from submission through a user-visible ready state and has its own Playwright configuration.
|
||||
|
||||
Run the suite explicitly from `packages/app`:
|
||||
|
||||
```sh
|
||||
bun run test:bench
|
||||
```
|
||||
|
||||
Run the desktop development startup benchmark from the repository root:
|
||||
|
||||
```sh
|
||||
bun run bench:devex
|
||||
```
|
||||
|
||||
It runs five serial samples of the exact `bun dev:desktop` command. Each sample uses a fresh desktop profile, database, service configuration, service registration, and service process; the desktop selects an isolated ephemeral loopback endpoint. It removes desktop build output and the desktop Vite cache before every run; dependencies, Bun's package cache, and Electron remain installed. The harness stops only that sample's service; it does not stop or change the elected global OpenCode service. The measured endpoint is a visible Home page whose empty-state controls pass Playwright actionability checks. The command's Electron installation check remains inside the measured interval.
|
||||
|
||||
Set `DESKTOP_STARTUP_RUNS` only for focused diagnostics:
|
||||
|
||||
```sh
|
||||
DESKTOP_STARTUP_RUNS=1 bun run bench:devex
|
||||
```
|
||||
|
||||
Set `OPENCODE_PERFORMANCE_TRACE_DIR` to capture the renderer's CDP trace from attachment through actionable Home:
|
||||
|
||||
```sh
|
||||
DESKTOP_STARTUP_RUNS=1 OPENCODE_PERFORMANCE_TRACE_DIR=/tmp/opencode-desktop-traces bun run bench:devex
|
||||
```
|
||||
|
||||
PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:PLAYWRIGHT_WORKERS = "1"
|
||||
bun run test:bench
|
||||
```
|
||||
|
||||
The suite contains:
|
||||
|
||||
- cold and hot session-tab timing
|
||||
- home-session click timing split between content and titlebar-tab paint
|
||||
- single-session tab close timing through stable home restoration
|
||||
- cached session repaint and mutation tracing
|
||||
- large-session search scan, first-result reveal, and highlight stabilization
|
||||
- streaming timeline throughput, RAF-gap, long-task, geometry, and remount diagnostics
|
||||
- retained renderer heap with a large model catalog across repeated session navigation
|
||||
|
||||
All benchmarks import the shared `benchmark` fixture. Pages created through Playwright's `page` fixture automatically capture main-frame navigation history and emit a Chrome trace when `OPENCODE_PERFORMANCE_TRACE_DIR` is set. Benchmarks that need isolated browser contexts use `withBenchmarkPage`, which owns the context and the same diagnostics lifecycle.
|
||||
|
||||
New benchmarks should look like normal Playwright tests:
|
||||
|
||||
```ts
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
|
||||
benchmark("measures one interaction", async ({ page, report }) => {
|
||||
// Only scenario-specific setup and interaction belong here.
|
||||
report({ durationMs: 42 })
|
||||
})
|
||||
```
|
||||
|
||||
The fixture requires every benchmark to call `report()`, automatically names and closes traces, captures navigation history, attaches that history when a test fails, and emits metrics as a consistent `BENCHMARK` JSON line.
|
||||
|
||||
```text
|
||||
BENCHMARK {"name":"...","context":{"project":"chromium","platform":"darwin"},"metrics":{...}}
|
||||
```
|
||||
|
||||
Every observed page also emits `BENCHMARK_PAGE` with the same run ID, navigation history, optional trace path, and trace scope before the final status-bearing `BENCHMARK` record. Chrome traces are browser-wide; the default window is page lifetime. Tab-switch traces begin after scenario setup and include explicit interaction markers. Scenario metrics use their own narrower observation windows.
|
||||
|
||||
This follows the stack's own guidance: [Electron recommends repeated Chrome DevTools and Chrome Tracing measurement](https://www.electronjs.org/docs/latest/tutorial/performance), [Chrome DevTools recommends Performance recordings for runtime work](https://developer.chrome.com/docs/devtools/performance), and [Playwright uses traces for test debugging rather than renderer profiling](https://playwright.dev/docs/trace-viewer).
|
||||
|
||||
These Playwright benchmarks profile the shared app renderer in Chromium. A future packaged Electron benchmark that needs main-process and multi-process attribution should use Electron's official [`contentTracing`](https://www.electronjs.org/docs/latest/api/content-tracing/) API rather than extending this renderer harness with bespoke process instrumentation.
|
||||
|
||||
CPU and high-volume visual profiling are disabled by default. Set `TIMELINE_CPU_PROFILE=1` to enable both, or additionally set `TIMELINE_VISUAL_PROFILE=0` for CPU-only profiling.
|
||||
|
||||
The streaming scenario's 30x CPU throttle is a deterministic stress profile, not a simulated end-user device.
|
||||
|
||||
Benchmarks do not assert machine-dependent performance budgets. Streaming processes 160 deltas by default and reports renderer-observed completion time, throughput, RAF callback-gap distributions, frame-budget equivalents, and long tasks through final geometry settlement. Delta count and delivery batch are included in result context when overridden. These are main-thread callback diagnostics, not compositor presentation or dropped-frame measurements. Visual-only and geometry metrics are `null` when their probes are disabled. Tab metrics describe sampled DOM observations. Assertions verify scenario and metric collection completion. Repeated repaint states are run-length grouped, but every original observation timestamp is retained alongside raw mutation batches and layout shifts.
|
||||
|
||||
Committed smoke and regression tests continue to own correctness coverage for pagination, tab paint, context resize, collapse state, and composer spacing.
|
||||
|
||||
Tab-switch timing starts at `mousedown`, when mouse-selected tabs actually navigate, with a `click` fallback for keyboard activation. The probe excludes hidden/transparent content and intersects answers with their virtual-row clip and viewport. The tab workload requires the destination's final answer to be visible with Markdown ready. These results are not directly comparable to older click-start, geometry-only measurements. `stableObservedMs` includes confirmation across three correct samples; `firstCorrectObservedMs` is the first sample meeting all content and geometry checks. Neither is a compositor presentation timestamp.
|
||||
|
||||
Each tab scenario reports one sample, including its raw observations. Use Playwright's `--repeat-each=20` for a baseline distribution. Warm scenarios prepare the destination at the same panel width before leaving it; a separate resized scenario validates reuse after opening the review pane changes that width.
|
||||
|
||||
The tab-switch workload uses two equally long sessions: 200 user/assistant exchanges (400 messages) per tab. Every answer includes headings, emphasis, links, a blockquote, task and nested lists, an eight-row table, and four highlighted code fences (TSX, JSON, SQL, Bash), alongside the stress fixture's reasoning and tools. The mock API deliberately returns all 400 messages in one response so every scenario measures a long loaded history, not a short paginated tail. The viewport is fixed at 1440 x 900. Results include the fixture version, Markdown and serialized-message byte counts, and message-request count. These numbers are not directly comparable to the earlier 12-exchange source / 72-exchange destination fixture.
|
||||
|
||||
Cold means the destination transcript has never loaded or rendered in that fresh browser context. Its measured switch includes one fixture message fetch. Warm means its complex answer was rendered and ready before switching away and back, and asserts no message fetch during the measured switch. Neither includes app startup or the source session's Markdown engine initialization. These cold results are not comparable to older prefetched cold-render results. Setup waits for mounted Markdown to finish and for the review-pane width transition to complete. Service workers are blocked to exclude the web build's background asset precache from this renderer benchmark. Screenshots are attached after measurement for the first repetition; Playwright video and trace recording are disabled for this workload, while opt-in Chrome profiling remains available. For a baseline distribution, use `--repeat-each=20 --retries=0`, keep profiling disabled, and report the median and p95 of `firstCorrectObservedMs` separately from the three-observation `stableObservedMs`.
|
||||
|
||||
```sh
|
||||
bunx playwright test --config e2e/performance/playwright.config.ts \
|
||||
timeline/session-tab-switch-benchmark.spec.ts --repeat-each=20 --retries=0
|
||||
```
|
||||
|
||||
**The tab-switch fixture returns full history, not normal pagination.** Measure cold API navigation, Home-row opening, and restored-but-unvisited tabs separately with normal pagination. Do not combine these entry paths or compare different transports and machine-load periods as one experiment.
|
||||
|
||||
`inactive-tab-prefetch-benchmark.spec.ts` restores eight tabs with normal 20-message pages (44 parts and 139,257 response bytes per page). It gates heavy responses independently until every tab's attention callback has run, then measures selection with ready answer Markdown and bottom anchoring. A separate case closes an inactive tab before releasing the responses. The fixture reports speculative transcript/inbox reads, request concurrency, response bytes, and activation latency. Set `OPENCODE_PERFORMANCE_MEMORY=1` only in separate retention runs; those force GC before selection and must not be mixed into clean timing results. The scope is the production browser renderer, not total desktop memory. Live background events and eviction of previously visited transcripts are separate workloads.
|
||||
|
||||
Keep one-off reports, recorded results, and traces outside git, in the ignored `e2e/performance/results/` directory or an external artifact directory. Preserve raw observations locally and publish anonymized summaries and charts in the PR description, not as committed experiment files.
|
||||
|
||||
For a repeatable tab-switch summary, run from `packages/app`:
|
||||
|
||||
```sh
|
||||
bun run bench:tabs
|
||||
```
|
||||
|
||||
This runs only the tab-switch benchmark against the production build with 20 serial repetitions and no retries. It prints the median (mean of the two middle values for even sample counts) and nearest-rank p95 for `firstCorrectObservedMs` and `stableObservedMs` per scenario. Only records whose benchmark and Playwright statuses are passed and whose two metrics are finite enter the summary. Test and record statuses, missing records, and excluded samples are reported separately.
|
||||
|
||||
For fresh entry paths, run `bun run bench:entry` from `packages/app`. It uses the same production, serial-repetition, and reporting defaults. The cases open an empty draft from the actual Home button, create a draft with the titlebar plus from an active session, and open a cold paginated session from Home. Draft readiness requires a focused editable composer, the expected model, project control, and new tab; typing and absence of backend mutations are checked afterward. Session readiness requires the latest group, ready answer Markdown, and bottom anchoring. These cases are separate from cached tab remounts.
|
||||
|
||||
For milestone charts, rerun frozen builds with one workload and counterbalanced serial order. Do not connect historical medians from different transports, preparation, or machine-load periods. Show samples or ranges, name the checkpoints accurately, and distinguish experimental build snapshots from Git commits.
|
||||
|
||||
Complete original `BENCHMARK` JSON records, including samples, context, and failed records, are saved as `tab-switch-benchmark.jsonl` in Playwright's configured output directory (default: `e2e/test-results/performance`). Standard Playwright flags can override defaults when appended:
|
||||
|
||||
```sh
|
||||
bun run bench:tabs --repeat-each=3 --output=e2e/test-results/tabs-smoke
|
||||
```
|
||||
|
||||
Set `OPENCODE_PERFORMANCE_MEMORY=1` for an opt-in renderer-main-isolate heap and DOM sample after mounted content is ready and an explicit GC completes. Probe DOM references are released before collection. This is not total desktop memory; do not mix these diagnostic runs with unprofiled latency samples. Set `OPENCODE_PERFORMANCE_TRACE_DIR` for a separate Chrome trace of each tab interaction, starting after preparation, with `session-switch:start`, `session-switch:ready`, and `session-switch:stable` markers.
|
||||
|
||||
### Cache-Enabled HTTP Fixture
|
||||
|
||||
The default tab harness uses Playwright routing for API responses. Playwright routing disables the browser HTTP cache, including for unrelated SVG assets. To measure with HTTP caching enabled, the same API handlers and tab data can run on a real loopback HTTP endpoint:
|
||||
|
||||
```sh
|
||||
bun run build
|
||||
bun e2e/performance/tab-switch-server.ts --port 4639 --dist dist
|
||||
```
|
||||
|
||||
With that fixture running, run the benchmark in a separate terminal from `packages/app`:
|
||||
|
||||
```powershell
|
||||
$env:PLAYWRIGHT_BASE_URL = "http://127.0.0.1:4639"
|
||||
$env:OPENCODE_PERFORMANCE_HTTP_FIXTURE = "1"
|
||||
bun run bench:tabs
|
||||
```
|
||||
|
||||
Use `--dist` to select a frozen production bundle when comparing revisions. An explicit `PLAYWRIGHT_BASE_URL` means the benchmark does not rebuild or start another preview. The fixture gives hashed assets immutable cache headers; it serves the deterministic read workload, not the live OpenCode service. Each test still gets a fresh browser context, and source-session setup still occurs before the measured switch. API responses use `no-store`, service workers remain blocked, and no destination Markdown is rendered before a cold switch. Records identify the transport as `http` or `playwright-route`; keep these series separate. Unset `OPENCODE_PERFORMANCE_HTTP_FIXTURE` when returning to the default routed harness.
|
||||
|
||||
## Retained renderer memory
|
||||
|
||||
Run the catalog workload against the production app bundle:
|
||||
|
||||
```sh
|
||||
bunx playwright test --config e2e/performance/playwright.config.ts \
|
||||
timeline/provider-memory-benchmark.spec.ts --repeat-each=3
|
||||
```
|
||||
|
||||
`PROVIDER_MEMORY_MODELS` defaults to 1,200 and `PROVIDER_MEMORY_SWITCHES` defaults to 10. Each sample records Chromium's `Runtime.getHeapUsage` and `Memory.getDOMCounters` after an explicit garbage collection. This measures retained state, not allocation peaks or normal GC timing. It does not include worker heaps, the Electron main/GPU processes, or the OpenCode server, and must not be reported as total desktop RAM. Use identical model counts and navigation sequences for before/after comparisons.
|
||||
|
||||
## Chrome traces
|
||||
|
||||
Set `OPENCODE_PERFORMANCE_TRACE_DIR` to emit a standard Chrome DevTools trace for every benchmark page automatically:
|
||||
|
||||
```sh
|
||||
OPENCODE_PERFORMANCE_TRACE_DIR=/tmp/opencode-performance-traces \
|
||||
bunx playwright test --config e2e/performance/playwright.config.ts \
|
||||
timeline/session-tab-switch-benchmark.spec.ts
|
||||
```
|
||||
|
||||
The emitted JSON is a standard Chrome trace and can be loaded directly into the Chrome DevTools Performance panel. `devtools-tracing` can optionally inspect it from the command line without adding package scripts or dependencies:
|
||||
|
||||
Trace capture follows [Puppeteer's tracing lifecycle](https://pptr.dev/api/puppeteer.tracing), using Chrome's `ReturnAsStream` transfer mode and failing when Chromium reports trace data loss. V8 CPU sample stacks support attribution through the frozen build's source maps. Set `OPENCODE_PERFORMANCE_STACK_TRACE=1` only when per-event timeline stacks are needed; they add substantial overhead. Keep profiled runs separate from latency distributions, including when comparing the stack-capture modes.
|
||||
|
||||
```sh
|
||||
bunx devtools-tracing stats <trace-path-from-BENCHMARK_PAGE>
|
||||
```
|
||||
|
||||
INP analysis requires a trace with a supported navigation/interaction insight. Selector statistics require a trace captured with `OPENCODE_PERFORMANCE_SELECTOR_TRACE=1`.
|
||||
|
||||
`e2e/performance/playwright.uncapped.config.ts` disables Chromium frame-rate limiting for explicit uncapped diagnostics. Native product benchmarks should use the default Playwright configuration.
|
||||
|
|
@ -1,167 +0,0 @@
|
|||
import { expect, test as base, type Browser, type Page, type TestInfo } from "@playwright/test"
|
||||
import { startChromeTrace } from "./chrome-trace"
|
||||
|
||||
type BenchmarkFixtures = {
|
||||
report: (metrics: Record<string, unknown>, context?: Record<string, unknown>) => void
|
||||
reportState: { payload?: { metrics: Record<string, unknown>; context: Record<string, unknown> } }
|
||||
benchmarkResult: void
|
||||
traceScope: "page" | "interaction"
|
||||
}
|
||||
|
||||
export type PerformancePageDiagnostics = {
|
||||
navigations: string[]
|
||||
traceScope: "page" | "interaction"
|
||||
startTrace: () => Promise<void>
|
||||
stop: () => Promise<string | undefined>
|
||||
}
|
||||
|
||||
const pages = new WeakMap<Page, PerformancePageDiagnostics>()
|
||||
|
||||
export const benchmark = base.extend<BenchmarkFixtures>({
|
||||
traceScope: ["page", { option: true }],
|
||||
reportState: async ({}, use) => use({}),
|
||||
report: async ({ reportState }, use) => {
|
||||
await use((metrics, context = {}) => {
|
||||
if (reportState.payload) throw new Error("Benchmark reported metrics more than once")
|
||||
reportState.payload = { metrics, context }
|
||||
})
|
||||
},
|
||||
benchmarkResult: [
|
||||
async ({ reportState }, use, testInfo) => {
|
||||
await use()
|
||||
const missing = !reportState.payload
|
||||
console.log(
|
||||
`BENCHMARK ${JSON.stringify({
|
||||
schemaVersion: 2,
|
||||
runID: process.env.OPENCODE_PERFORMANCE_RUN_ID,
|
||||
name: benchmarkName(testInfo),
|
||||
status: missing ? "failed" : testInfo.status,
|
||||
expectedStatus: testInfo.expectedStatus,
|
||||
retry: testInfo.retry,
|
||||
repeatEachIndex: testInfo.repeatEachIndex,
|
||||
context: {
|
||||
project: testInfo.project.name,
|
||||
platform: process.platform,
|
||||
...reportState.payload?.context,
|
||||
},
|
||||
metrics: reportState.payload?.metrics ?? null,
|
||||
error: missing ? "Benchmark did not report metrics" : undefined,
|
||||
})}`,
|
||||
)
|
||||
|
||||
if (missing && testInfo.status === testInfo.expectedStatus)
|
||||
throw new Error(`Benchmark did not report metrics: ${benchmarkName(testInfo)}`)
|
||||
},
|
||||
{ auto: true },
|
||||
],
|
||||
page: async ({ page, traceScope }, use, testInfo) => {
|
||||
const name = benchmarkName(testInfo)
|
||||
const diagnostics = await observePerformancePage(page, name, traceScope)
|
||||
|
||||
try {
|
||||
await use(page)
|
||||
} finally {
|
||||
try {
|
||||
await reportPerformancePage(name, diagnostics, testInfo)
|
||||
} finally {
|
||||
if (testInfo.status !== testInfo.expectedStatus) {
|
||||
await testInfo.attach("performance-navigations", {
|
||||
body: JSON.stringify(diagnostics.navigations, null, 2),
|
||||
contentType: "application/json",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function benchmarkName(testInfo: TestInfo) {
|
||||
return testInfo.titlePath.slice(1).join(" > ")
|
||||
}
|
||||
|
||||
export { expect }
|
||||
|
||||
async function observePerformancePage(page: Page, name: string, traceScope: "page" | "interaction" = "page") {
|
||||
const navigations: string[] = []
|
||||
|
||||
const onNavigation = (frame: ReturnType<Page["mainFrame"]>) => {
|
||||
if (frame === page.mainFrame()) navigations.push(frame.url())
|
||||
}
|
||||
|
||||
page.on("framenavigated", onNavigation)
|
||||
let stopTrace: Awaited<ReturnType<typeof startChromeTrace>>
|
||||
let stopping: Promise<string | undefined> | undefined
|
||||
|
||||
const diagnostics: PerformancePageDiagnostics = {
|
||||
navigations,
|
||||
traceScope,
|
||||
async startTrace() {
|
||||
stopTrace ??= await startChromeTrace(page, name).catch((error) => {
|
||||
page.off("framenavigated", onNavigation)
|
||||
throw error
|
||||
})
|
||||
},
|
||||
stop() {
|
||||
page.off("framenavigated", onNavigation)
|
||||
|
||||
return (stopping ??= stopTrace?.() ?? Promise.resolve(undefined))
|
||||
},
|
||||
}
|
||||
|
||||
pages.set(page, diagnostics)
|
||||
|
||||
if (traceScope === "page") await diagnostics.startTrace()
|
||||
|
||||
return diagnostics
|
||||
}
|
||||
|
||||
export async function withBenchmarkPage<T>(
|
||||
browser: Browser,
|
||||
name: string,
|
||||
run: (page: Page) => Promise<T>,
|
||||
testInfo?: TestInfo,
|
||||
) {
|
||||
const context = await browser.newContext()
|
||||
|
||||
try {
|
||||
const page = await context.newPage()
|
||||
const diagnostics = await observePerformancePage(page, name)
|
||||
|
||||
try {
|
||||
return await run(page)
|
||||
} finally {
|
||||
await reportPerformancePage(name, diagnostics, testInfo)
|
||||
}
|
||||
} finally {
|
||||
await context.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function reportPerformancePage(name: string, diagnostics: PerformancePageDiagnostics, testInfo?: TestInfo) {
|
||||
const trace = await diagnostics.stop()
|
||||
console.log(
|
||||
`BENCHMARK_PAGE ${JSON.stringify({
|
||||
schemaVersion: 2,
|
||||
runID: process.env.OPENCODE_PERFORMANCE_RUN_ID,
|
||||
name,
|
||||
test: testInfo ? benchmarkName(testInfo) : undefined,
|
||||
retry: testInfo?.retry,
|
||||
repeatEachIndex: testInfo?.repeatEachIndex,
|
||||
context: {
|
||||
platform: process.platform,
|
||||
trace,
|
||||
traceScope: diagnostics.traceScope,
|
||||
selectorTrace: process.env.OPENCODE_PERFORMANCE_SELECTOR_TRACE === "1",
|
||||
},
|
||||
navigations: diagnostics.navigations,
|
||||
})}`,
|
||||
)
|
||||
}
|
||||
|
||||
export function benchmarkDiagnostics(page: Page) {
|
||||
const diagnostics = pages.get(page)
|
||||
|
||||
if (!diagnostics) throw new Error("Performance diagnostics are not installed for this page")
|
||||
|
||||
return diagnostics
|
||||
}
|
||||
|
|
@ -1,107 +0,0 @@
|
|||
import type { CDPSession, Page } from "@playwright/test"
|
||||
import path from "node:path"
|
||||
import { mkdir, open, rename } from "node:fs/promises"
|
||||
import { Buffer } from "node:buffer"
|
||||
import { createHash, randomUUID } from "node:crypto"
|
||||
|
||||
const categories = [
|
||||
"-*",
|
||||
"devtools.timeline",
|
||||
"v8.execute",
|
||||
"disabled-by-default-devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline.frame",
|
||||
"toplevel",
|
||||
"blink.console",
|
||||
"blink.user_timing",
|
||||
"latencyInfo",
|
||||
"disabled-by-default-v8.cpu_profiler",
|
||||
]
|
||||
|
||||
export async function startChromeTrace(page: Page, name: string): Promise<undefined | (() => Promise<string>)> {
|
||||
const directory = process.env.OPENCODE_PERFORMANCE_TRACE_DIR
|
||||
|
||||
if (!directory) return undefined
|
||||
|
||||
const selectors = process.env.OPENCODE_PERFORMANCE_SELECTOR_TRACE === "1"
|
||||
const file = await prepareChromeTrace(directory, name, selectors)
|
||||
const session = await page.context().newCDPSession(page)
|
||||
|
||||
try {
|
||||
await session.send("Tracing.start", {
|
||||
transferMode: "ReturnAsStream",
|
||||
traceConfig: {
|
||||
excludedCategories: categories
|
||||
.filter((category) => category.startsWith("-"))
|
||||
.map((category) => category.slice(1)),
|
||||
includedCategories: [
|
||||
...categories.filter((category) => !category.startsWith("-")),
|
||||
...(process.env.OPENCODE_PERFORMANCE_STACK_TRACE === "1"
|
||||
? ["disabled-by-default-devtools.timeline.stack"]
|
||||
: []),
|
||||
...(selectors
|
||||
? ["disabled-by-default-blink.debug", "disabled-by-default-devtools.timeline.invalidationTracking"]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
await Promise.allSettled([session.detach()])
|
||||
throw error
|
||||
}
|
||||
|
||||
let stopping: Promise<string> | undefined
|
||||
|
||||
return () =>
|
||||
(stopping ??= (async () => {
|
||||
try {
|
||||
const complete = new Promise<{ stream?: string; dataLossOccurred: boolean }>((resolve) =>
|
||||
session.once("Tracing.tracingComplete", resolve),
|
||||
)
|
||||
|
||||
await session.send("Tracing.end")
|
||||
const result = await complete
|
||||
|
||||
if (!result.stream) throw new Error(`Chrome trace stream missing: ${file}`)
|
||||
const partial = `${file}.partial`
|
||||
await writeProtocolStream(session, result.stream, partial)
|
||||
|
||||
if (result.dataLossOccurred) throw new Error(`Chrome trace lost data; partial capture retained: ${partial}`)
|
||||
await rename(partial, file)
|
||||
|
||||
return file
|
||||
} finally {
|
||||
await Promise.allSettled([session.detach()])
|
||||
}
|
||||
})())
|
||||
}
|
||||
|
||||
export async function prepareChromeTrace(
|
||||
directory: string,
|
||||
name: string,
|
||||
selectors: boolean,
|
||||
nonce = randomUUID().slice(0, 8),
|
||||
) {
|
||||
await mkdir(directory, { recursive: true })
|
||||
const run = process.env.OPENCODE_PERFORMANCE_RUN_ID ?? "manual"
|
||||
const hash = createHash("sha256").update(name).digest("hex").slice(0, 8)
|
||||
|
||||
return path.join(
|
||||
directory,
|
||||
`${run}-${name.replace(/[^a-zA-Z0-9_-]/g, "-")}-${hash}-${nonce}${selectors ? "-selectors" : ""}.json`,
|
||||
)
|
||||
}
|
||||
|
||||
async function writeProtocolStream(session: CDPSession, handle: string, file: string) {
|
||||
const output = await open(file, "wx")
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const chunk = await session.send("IO.read", { handle })
|
||||
await (chunk.base64Encoded ? output.write(Buffer.from(chunk.data, "base64")) : output.write(chunk.data))
|
||||
|
||||
if (chunk.eof) break
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled([output.close(), session.send("IO.close", { handle })])
|
||||
}
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
import { benchmark, expect } from "./benchmark"
|
||||
import { openCommandPalette } from "../utils/command-palette"
|
||||
|
||||
benchmark.use({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
serviceWorkers: "block",
|
||||
traceScope: "interaction",
|
||||
trace: "off",
|
||||
video: "off",
|
||||
})
|
||||
|
||||
for (const home of [false, true]) {
|
||||
benchmark(`command lookup from ${home ? "home" : "session"}`, async ({ page, report }) => {
|
||||
const { dialog, input } = await openCommandPalette(page, home)
|
||||
const title = home ? "Open settings" : "Copy Session ID"
|
||||
const query = home ? "open settings" : "copy session"
|
||||
// Measure input-to-selected-result in the renderer, without assertion polling overhead.
|
||||
await input.evaluate((element, title) => {
|
||||
element.addEventListener(
|
||||
"input",
|
||||
() => {
|
||||
performance.mark("palette-input")
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
if (document.querySelectorAll('[role="dialog"] [role="option"]').length !== 1) return
|
||||
const selected = document.querySelector('[role="dialog"] [role="option"][aria-selected="true"]')
|
||||
|
||||
if (!selected?.textContent?.includes(title)) return
|
||||
performance.measure("palette-result", "palette-input")
|
||||
observer.disconnect()
|
||||
})
|
||||
|
||||
observer.observe(document, { subtree: true, childList: true, attributes: true, characterData: true })
|
||||
},
|
||||
{ once: true, capture: true },
|
||||
)
|
||||
}, title)
|
||||
await input.fill(query)
|
||||
await expect(dialog.getByRole("option")).toHaveCount(1)
|
||||
await expect(dialog.getByRole("option", { name: new RegExp(`^${title}(?:$| )`) })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
)
|
||||
|
||||
const result = await page.evaluate(() =>
|
||||
performance.getEntriesByName("palette-result").map((entry) => entry.duration),
|
||||
)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
report({ inputToResultMs: result[0] }, { home, query, data: "fixture; immediate server responses" })
|
||||
})
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
# Composer History Hydration
|
||||
|
||||
Manual benchmark for an empty destination composer. Runs the production
|
||||
`ComposerEditor`, `createComposerEditor`, `createComposerHistory`, persistence
|
||||
codec, and browser IndexedDB draft store. It does not run the surrounding app
|
||||
shell or native desktop IPC.
|
||||
|
||||
Workload: 100 normal prompts with realistic review instructions/code and 100
|
||||
shell commands. Separate cases have no images, 50 unique screenshots, or 50
|
||||
references to 5 screenshots. The fixture generates valid 1440 x 900 PNG code
|
||||
screenshots before timing and reports their exact byte sizes. Each isolated
|
||||
browser context measures a cold URL-cache mount followed by a warm remount.
|
||||
The database was just seeded; this does not simulate a cold disk cache.
|
||||
|
||||
`historyReadyMs` measures the mount action until both production history stores
|
||||
are populated. This is history availability, not time to first editable input
|
||||
(input can be usable before history finishes). The benchmark then verifies
|
||||
ArrowUp recall and a decoded screenshot in the real editor. `recallObservedMs`
|
||||
includes Playwright action/assertion overhead and is reported separately.
|
||||
`mountRecallObservedMs` includes the mount, readiness checks, keyboard action,
|
||||
and correct text/image completion; it also includes Playwright overhead.
|
||||
IndexedDB reads and blob sizes are mechanism metrics, not desktop IPC bytes or
|
||||
process memory. No timing threshold is enforced.
|
||||
|
||||
From `packages/app`, set `OPENCODE_HISTORY_BUILD` and
|
||||
`OPENCODE_HISTORY_OUTPUT` to artifact directories outside Git, then run:
|
||||
|
||||
```sh
|
||||
bun x vite build --config e2e/performance/composer-history/vite.config.ts
|
||||
bun x playwright test --config e2e/performance/composer-history/playwright.config.ts --repeat-each=20
|
||||
```
|
||||
|
||||
The preview server owns port 4783 and is stopped by Playwright. Preserve each
|
||||
build and its revision/hash for comparisons. `BENCHMARK` JSON lines contain all
|
||||
raw samples. Optional Chrome traces use the existing
|
||||
`OPENCODE_PERFORMANCE_TRACE_DIR` setting; keep trace runs separate from clean
|
||||
timing. Screenshots are captured after timing on the first repeat only.
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
|
||||
benchmark.use({ traceScope: "page" })
|
||||
|
||||
for (const shape of ["text", "unique", "repeated"]) {
|
||||
benchmark(`composer global history: ${shape}, cold and warm mounts`, async ({ page, report }, testInfo) => {
|
||||
const errors: string[] = []
|
||||
page.on("pageerror", (error) => errors.push(error.message))
|
||||
await page.goto(`/?shape=${shape}`)
|
||||
const button = page.getByRole("button", { name: "Mount empty composer", exact: true })
|
||||
const input = page.getByRole("textbox", { name: "Prompt", exact: true })
|
||||
const samples = []
|
||||
|
||||
for (const cache of ["cold", "warm"]) {
|
||||
await expect(button).toBeEnabled()
|
||||
const mountStarted = performance.now()
|
||||
await button.click()
|
||||
await expect(page.getByTestId("history-ready")).toHaveText("ready")
|
||||
await expect(input).toBeEditable()
|
||||
await expect(input).toBeEmpty()
|
||||
const result = JSON.parse((await page.getByTestId("history-result").textContent())!)
|
||||
expect(result.documents).toBe(2)
|
||||
expect(result.historyReadyMs).toBeGreaterThan(0)
|
||||
const start = performance.now()
|
||||
await input.press("ArrowUp")
|
||||
await expect(input).toContainText("Review the retry policy in src/network/request-0.ts.")
|
||||
const images = page.getByRole("img", { name: "request-0.png", exact: true })
|
||||
await expect(images).toHaveCount(shape === "text" ? 0 : 1)
|
||||
|
||||
if (shape !== "text")
|
||||
await expect
|
||||
.poll(() => images.evaluate((image: HTMLImageElement) => image.complete && image.naturalWidth === 1440))
|
||||
.toBe(true)
|
||||
samples.push({
|
||||
cache,
|
||||
...result,
|
||||
recallObservedMs: performance.now() - start,
|
||||
mountRecallObservedMs: performance.now() - mountStarted,
|
||||
})
|
||||
}
|
||||
|
||||
expect(errors).toEqual([])
|
||||
report(
|
||||
{ samples },
|
||||
{
|
||||
browser: page.context().browser()!.version(),
|
||||
scope: "production composer editor/history, browser IndexedDB; no native IPC",
|
||||
},
|
||||
)
|
||||
|
||||
if (testInfo.repeatEachIndex === 0) await page.screenshot({ path: testInfo.outputPath(`${shape}.png`) })
|
||||
})
|
||||
}
|
||||
|
|
@ -1,207 +0,0 @@
|
|||
/// <reference types="vite/client" />
|
||||
import { createEffect, Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { render } from "solid-js/web"
|
||||
import { PlatformProvider, type Platform } from "@/runtime/platform/platform"
|
||||
import { createBrowserDraftStore } from "@/runtime/persistence/drafts"
|
||||
import { createComposerHistory } from "@/composer/history/store"
|
||||
import { ComposerEditor } from "@/composer/editor/editor"
|
||||
import { createComposerEditor } from "@/composer/editor/interaction"
|
||||
import type { ComposerPersistedState } from "@/composer/types"
|
||||
import "@/index.css"
|
||||
|
||||
const shape = new URLSearchParams(location.search).get("shape") ?? "text"
|
||||
|
||||
const normal = Array.from({ length: 100 }, (_, index) => {
|
||||
const content =
|
||||
`Review the retry policy in src/network/request-${index}.ts. Preserve cancellation and the existing error messages.\n\n` +
|
||||
`The request should stop after three attempts. Add coverage for a 429 response, a connection reset, and a successful retry. Verify that only idempotent requests are retried.\n\n` +
|
||||
`Report ${index}:\n\`\`\`ts\nexport async function request(input: Request) {\n const response = await fetch(input)\n if (!response.ok) throw new Error(response.statusText)\n return response.json()\n}\n\`\`\``
|
||||
|
||||
return {
|
||||
prompt: [
|
||||
{ type: "text", content, start: 0, end: content.length },
|
||||
...(shape !== "text" && index % 2 === 0
|
||||
? [
|
||||
{
|
||||
type: "image",
|
||||
id: `attachment-${index}`,
|
||||
filename: `request-${index}.png`,
|
||||
mime: "image/png",
|
||||
blob: { id: `screenshot-${shape === "repeated" ? index % 10 : index}` },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
comments: [],
|
||||
}
|
||||
})
|
||||
|
||||
const shell = Array.from({ length: 100 }, (_, index) => {
|
||||
const content = `bun test src/network/request-${index}.test.ts --timeout 30000`
|
||||
|
||||
return { prompt: [{ type: "text", content, start: 0, end: content.length }], comments: [] }
|
||||
})
|
||||
|
||||
// Seed only this Playwright context, before opening the production draft store.
|
||||
const request = indexedDB.open("opencode-drafts", 1)
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
request.result.createObjectStore("documents")
|
||||
request.result.createObjectStore("blobs")
|
||||
}
|
||||
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result)
|
||||
request.onerror = () => reject(request.error)
|
||||
})
|
||||
|
||||
const ids = [...new Set(normal.flatMap((entry) => entry.prompt.flatMap((part) => (part.blob ? [part.blob.id] : []))))]
|
||||
|
||||
const screenshots: { id: string; blob: Blob }[] = []
|
||||
|
||||
for (const id of ids) {
|
||||
const canvas = document.createElement("canvas")
|
||||
canvas.width = 1440
|
||||
canvas.height = 900
|
||||
const context = canvas.getContext("2d")!
|
||||
context.fillStyle = "#15191f"
|
||||
context.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context.font = "16px monospace"
|
||||
context.fillStyle = "#b8c8d8"
|
||||
context.fillText(`request.ts - ${id}`, 30, 35)
|
||||
|
||||
for (let line = 0; line < 38; line++) {
|
||||
context.fillStyle = line % 3 ? "#a8c7ba" : "#d4a882"
|
||||
context.fillText(
|
||||
`${String(line + 1).padStart(3)} const response${line} = await fetch('/api/request/${id}/${line}', { signal, headers });`,
|
||||
30,
|
||||
70 + line * 20,
|
||||
)
|
||||
}
|
||||
|
||||
const blob = await new Promise<Blob>((resolve) => canvas.toBlob((blob) => resolve(blob!), "image/png"))
|
||||
screenshots.push({ id, blob })
|
||||
}
|
||||
|
||||
const transaction = db.transaction(["documents", "blobs"], "readwrite")
|
||||
|
||||
transaction.objectStore("documents").put(JSON.stringify({ entries: normal }), "opencode.global.dat:prompt-history")
|
||||
|
||||
transaction.objectStore("documents").put(JSON.stringify({ entries: shell }), "opencode.global.dat:prompt-history-shell")
|
||||
|
||||
screenshots.forEach(({ id, blob }) => transaction.objectStore("blobs").put(blob, id))
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve()
|
||||
transaction.onerror = () => reject(transaction.error)
|
||||
})
|
||||
|
||||
db.close()
|
||||
|
||||
const metrics = { reads: 0, blobBytes: 0, documents: 0 }
|
||||
|
||||
const originalGet = IDBObjectStore.prototype.get
|
||||
|
||||
IDBObjectStore.prototype.get = function (key) {
|
||||
const request = originalGet.call(this, key)
|
||||
|
||||
if (this.name === "documents") metrics.documents++
|
||||
|
||||
if (this.name === "blobs") {
|
||||
metrics.reads++
|
||||
request.addEventListener("success", () => {
|
||||
metrics.blobBytes += request.result?.size ?? 0
|
||||
})
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
const platform: Platform = {
|
||||
platform: "web",
|
||||
draftStore: createBrowserDraftStore(),
|
||||
openExternal() {},
|
||||
restart: async () => {},
|
||||
notify: async () => {},
|
||||
}
|
||||
|
||||
const [state, setState] = createStore({ mount: 0, ready: false, result: "" })
|
||||
|
||||
const workload = {
|
||||
shape,
|
||||
normalEntries: normal.length,
|
||||
shellEntries: shell.length,
|
||||
imageReferences: shape === "text" ? 0 : 50,
|
||||
uniqueImages: ids.length,
|
||||
storedImageBytes: screenshots.reduce((sum, item) => sum + item.blob.size, 0),
|
||||
documentBytes: [normal, shell].reduce(
|
||||
(sum, entries) => sum + new TextEncoder().encode(JSON.stringify({ entries })).length,
|
||||
0,
|
||||
),
|
||||
screenshotDimensions: [1440, 900],
|
||||
}
|
||||
|
||||
let started = 0
|
||||
|
||||
function mount() {
|
||||
metrics.reads = 0
|
||||
metrics.blobBytes = 0
|
||||
metrics.documents = 0
|
||||
setState({ ready: false, result: "" })
|
||||
started = performance.now()
|
||||
setState("mount", state.mount + 1)
|
||||
}
|
||||
|
||||
function Destination() {
|
||||
// Same history creation and editor mapping as createComposerModel. Destination draft is empty.
|
||||
const history = createComposerHistory()
|
||||
|
||||
const store = createStore<ComposerPersistedState>({
|
||||
prompt: [{ type: "text", content: "", start: 0, end: 0 }],
|
||||
cursor: 0,
|
||||
context: { items: [] },
|
||||
})
|
||||
|
||||
const controller = createComposerEditor({
|
||||
store,
|
||||
commands: () => [],
|
||||
context: () => [],
|
||||
searchContextFiles: () => [],
|
||||
history: {
|
||||
entries: (mode) => history.entries(mode).map((entry) => ({ prompt: entry.prompt, metadata: entry.comments })),
|
||||
add: (prompt, mode) => history.add(prompt, mode, []),
|
||||
},
|
||||
view: {
|
||||
placeholder: () => "Empty destination composer",
|
||||
submit: { stopping: () => false, onSubmit() {}, onStop() {} },
|
||||
},
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
if (history.entries("normal").length !== 100 || history.entries("shell").length !== 100) return
|
||||
setState({
|
||||
ready: true,
|
||||
result: JSON.stringify({ historyReadyMs: performance.now() - started, ...metrics, ...workload }),
|
||||
})
|
||||
})
|
||||
|
||||
return <ComposerEditor controller={controller} />
|
||||
}
|
||||
|
||||
render(
|
||||
() => (
|
||||
<PlatformProvider value={platform}>
|
||||
<main style={{ padding: "40px", width: "900px" }}>
|
||||
<h1>Composer global history: {shape}</h1>
|
||||
<button onClick={mount}>Mount empty composer</button>
|
||||
<output data-testid="history-ready">{state.ready ? "ready" : "idle"}</output>
|
||||
<pre data-testid="history-result">{state.result}</pre>
|
||||
<Show when={state.mount} keyed>
|
||||
{(_mount) => <Destination />}
|
||||
</Show>
|
||||
</main>
|
||||
</PlatformProvider>
|
||||
),
|
||||
document.getElementById("root")!,
|
||||
)
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Composer history benchmark</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./fixture.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
import { defineConfig } from "@playwright/test"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
testMatch: "composer-history.bench.ts",
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
timeout: 60_000,
|
||||
reporter: "line",
|
||||
outputDir: process.env.OPENCODE_HISTORY_OUTPUT,
|
||||
use: { baseURL: "http://127.0.0.1:4783", viewport: { width: 1440, height: 900 }, trace: "off", video: "off" },
|
||||
webServer: {
|
||||
cwd: fileURLToPath(new URL("../../../", import.meta.url)),
|
||||
command:
|
||||
"bun x vite preview --config e2e/performance/composer-history/vite.config.ts --host 127.0.0.1 --port 4783 --strictPort",
|
||||
url: "http://127.0.0.1:4783",
|
||||
reuseExistingServer: false,
|
||||
},
|
||||
})
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
import { defineConfig } from "vite"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import app from "../../../vite"
|
||||
|
||||
export default defineConfig({
|
||||
root: fileURLToPath(new URL(".", import.meta.url)),
|
||||
publicDir: fileURLToPath(new URL("../../../public", import.meta.url)),
|
||||
plugins: [app],
|
||||
build: { target: "esnext", outDir: process.env.OPENCODE_HISTORY_BUILD, emptyOutDir: true },
|
||||
})
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
import { benchmark } from "../benchmark"
|
||||
import {
|
||||
desktopBenchmarkContext,
|
||||
runDesktopStartup,
|
||||
summarizeDesktopStartup,
|
||||
type DesktopStartupSample,
|
||||
} from "./desktop-startup"
|
||||
|
||||
benchmark.describe("devex: desktop startup", () => {
|
||||
benchmark("opens a cold desktop on Home", async ({ report }, testInfo) => {
|
||||
benchmark.setTimeout(15 * 60_000)
|
||||
const runs = Number(process.env.DESKTOP_STARTUP_RUNS ?? 5)
|
||||
|
||||
if (!Number.isSafeInteger(runs) || runs < 1) throw new Error("DESKTOP_STARTUP_RUNS must be a positive integer")
|
||||
|
||||
const samples: DesktopStartupSample[] = []
|
||||
const context = await desktopBenchmarkContext(runs)
|
||||
|
||||
for (let run = 1; run <= runs; run++) {
|
||||
const sample = await runDesktopStartup(run, testInfo).catch((error) => {
|
||||
report(samples.length ? { samples, summary: summarizeDesktopStartup(samples) } : { samples }, context)
|
||||
throw error
|
||||
})
|
||||
|
||||
samples.push(sample)
|
||||
}
|
||||
|
||||
report({ samples, summary: summarizeDesktopStartup(samples) }, context)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,592 +0,0 @@
|
|||
import { Service } from "@opencode/client/service"
|
||||
import { chromium, expect, type Browser, type Page, type TestInfo } from "@playwright/test"
|
||||
import { Schema } from "effect"
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process"
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { startChromeTrace } from "../chrome-trace"
|
||||
|
||||
const repository = resolve(import.meta.dirname, "../../../../..")
|
||||
|
||||
const milestones = [
|
||||
"bunRootScript",
|
||||
"bunDesktopScript",
|
||||
"desktopPrepared",
|
||||
"mainBundleReady",
|
||||
"preloadBundleReady",
|
||||
"rendererDevServerReady",
|
||||
"electronSpawnStarted",
|
||||
"debugEndpointReady",
|
||||
"electronStarted",
|
||||
"layersReady",
|
||||
"windowVisible",
|
||||
"serviceEnsureStarted",
|
||||
"serviceSpawnRequested",
|
||||
"serviceReady",
|
||||
"rendererViteConnected",
|
||||
"homeReady",
|
||||
] as const
|
||||
|
||||
const phases = [
|
||||
"desktopPreparation",
|
||||
"viteMainBundle",
|
||||
"vitePreloadBundle",
|
||||
"rendererServerStartup",
|
||||
"electronStartup",
|
||||
"serviceSpawnWait",
|
||||
"serviceProcessStartup",
|
||||
"rendererStartup",
|
||||
"visibleWindowToHome",
|
||||
] as const
|
||||
|
||||
type Milestone = (typeof milestones)[number]
|
||||
|
||||
type Phase = (typeof phases)[number]
|
||||
|
||||
const ServiceInfo = Schema.Struct({ id: Schema.String, version: Schema.String, url: Schema.String, pid: Schema.Number })
|
||||
|
||||
type ServiceInfo = typeof ServiceInfo.Type
|
||||
|
||||
export type DesktopStartupSample = {
|
||||
run: number
|
||||
commandToHomeReadyMs: number
|
||||
milestonesMs: Record<Milestone, number>
|
||||
phasesMs: Record<Phase, number>
|
||||
service: Omit<ServiceInfo, "id">
|
||||
}
|
||||
|
||||
export async function runDesktopStartup(run: number, testInfo: TestInfo) {
|
||||
const profile = await createColdProfile()
|
||||
|
||||
const desktop = await Promise.resolve()
|
||||
.then(() => startDesktop(profile))
|
||||
.catch(async (error) => {
|
||||
await rm(profile.root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
|
||||
throw error
|
||||
})
|
||||
|
||||
try {
|
||||
const page = await desktop.open()
|
||||
const stopTrace = await startChromeTrace(page, `desktop-startup-${run}`)
|
||||
|
||||
try {
|
||||
await startThemeObservation(page)
|
||||
await waitForHome(page, desktop.mark)
|
||||
await requireStableTheme(page)
|
||||
|
||||
return await desktop.result(run)
|
||||
} finally {
|
||||
await stopTrace?.()
|
||||
}
|
||||
} finally {
|
||||
await desktop.close(testInfo, run)
|
||||
}
|
||||
}
|
||||
|
||||
export async function desktopBenchmarkContext(runs: number) {
|
||||
const pkg = JSON.parse(await readFile(join(repository, "packages/desktop/package.json"), "utf8"))
|
||||
const revision = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repository })
|
||||
|
||||
if (revision.status !== 0) throw new Error("Failed to read the benchmark Git revision")
|
||||
const status = spawnSync("git", ["status", "--porcelain"], { cwd: repository })
|
||||
|
||||
if (status.status !== 0) throw new Error("Failed to read the benchmark Git status")
|
||||
const bun = spawnSync("bun", ["--version"], { cwd: repository })
|
||||
|
||||
if (bun.status !== 0) throw new Error("Failed to read the benchmark Bun version")
|
||||
|
||||
return {
|
||||
arch: process.arch,
|
||||
command: "bun dev:desktop",
|
||||
runs,
|
||||
profile: "fresh",
|
||||
service: "isolated-cold",
|
||||
install: "complete",
|
||||
viteCache: "cold",
|
||||
electronInstall: "present",
|
||||
bunVersion: bun.stdout.toString().trim(),
|
||||
electronVersion: pkg.devDependencies.electron,
|
||||
electronViteVersionRange: pkg.devDependencies["electron-vite"],
|
||||
gitCommit: revision.stdout.toString().trim(),
|
||||
gitDirty: status.stdout.length > 0,
|
||||
trace: Boolean(process.env.OPENCODE_PERFORMANCE_TRACE_DIR),
|
||||
}
|
||||
}
|
||||
|
||||
export function summarizeDesktopStartup(samples: DesktopStartupSample[]) {
|
||||
return {
|
||||
commandToHomeReadyMs: statistics(samples.map((sample) => sample.commandToHomeReadyMs)),
|
||||
milestonesMs: Object.fromEntries(
|
||||
milestones.map((name) => [name, statistics(samples.map((sample) => sample.milestonesMs[name]))]),
|
||||
),
|
||||
phasesMs: Object.fromEntries(
|
||||
phases.map((name) => [name, statistics(samples.map((sample) => sample.phasesMs[name]))]),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export function milestoneForLine(line: string): Milestone | undefined {
|
||||
const text = stripAnsi(line)
|
||||
|
||||
return milestonePatterns.find((item) => text.includes(item.text))?.name
|
||||
}
|
||||
|
||||
const milestonePatterns: ReadonlyArray<{ name: Milestone; text: string }> = [
|
||||
{ name: "bunRootScript", text: "$ bun --cwd packages/desktop dev" },
|
||||
{ name: "bunDesktopScript", text: "$ bun run script/dev.ts" },
|
||||
{ name: "desktopPrepared", text: "Copied dev icons from" },
|
||||
{ name: "mainBundleReady", text: "electron main process built successfully" },
|
||||
{ name: "preloadBundleReady", text: "electron preload scripts built successfully" },
|
||||
{ name: "rendererDevServerReady", text: "dev server running for the electron renderer process at:" },
|
||||
{ name: "electronSpawnStarted", text: "starting electron app..." },
|
||||
{ name: "debugEndpointReady", text: "DevTools listening on ws://" },
|
||||
{ name: "electronStarted", text: "app starting" },
|
||||
{ name: "layersReady", text: "layers ready" },
|
||||
{ name: "windowVisible", text: "main window visible" },
|
||||
{ name: "serviceEnsureStarted", text: "starting v2 background service" },
|
||||
{ name: "serviceSpawnRequested", text: "v2 CLI background service starting" },
|
||||
{ name: "serviceReady", text: "v2 CLI background service ready" },
|
||||
{ name: "rendererViteConnected", text: "[vite] connected." },
|
||||
]
|
||||
|
||||
async function createColdProfile() {
|
||||
await Promise.all(
|
||||
["packages/desktop/node_modules/.vite", "packages/desktop/out"].map((path) =>
|
||||
rm(join(repository, path), { recursive: true, force: true }),
|
||||
),
|
||||
)
|
||||
const root = await mkdtemp(join(tmpdir(), "opencode-desktop-startup-"))
|
||||
|
||||
return initializeColdProfile(root).catch(async (error) => {
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
|
||||
throw error
|
||||
})
|
||||
}
|
||||
|
||||
async function initializeColdProfile(root: string) {
|
||||
await Promise.all(
|
||||
["data", "config", "cache", "state", "desktop", "session", "home"].map((dir) =>
|
||||
mkdir(join(root, dir), { recursive: true }),
|
||||
),
|
||||
)
|
||||
await Promise.all([
|
||||
writeFile(join(root, "desktop", "opencode.settings"), JSON.stringify({ firstLaunchOnboardingComplete: true })),
|
||||
writeFile(join(root, "desktop", "opencode.global.dat"), JSON.stringify({ language: '{"locale":"en"}' })),
|
||||
])
|
||||
const registration = join(root, "desktop", "opencode", "service-local.json")
|
||||
await Service.stop({ file: registration })
|
||||
|
||||
return { root, registration }
|
||||
}
|
||||
|
||||
function startDesktop(profile: Awaited<ReturnType<typeof createColdProfile>>) {
|
||||
const started = performance.now()
|
||||
|
||||
const child = spawn("bun", ["dev:desktop"], {
|
||||
cwd: repository,
|
||||
detached: process.platform !== "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_DIR: join(profile.root, "config"),
|
||||
OPENCODE_DB: join(profile.root, "data", "opencode.db"),
|
||||
OPENCODE_TEST_HOME: join(profile.root, "home"),
|
||||
OPENCODE_TEST_ONBOARDING: "0",
|
||||
OPENCODE_DESKTOP_TEST_ROOT: profile.root,
|
||||
OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT: "0",
|
||||
OPENCODE_DESKTOP_DISABLE_PROTOCOL_REGISTRATION: "1",
|
||||
// The test root also redirects XDG_CACHE_HOME, which would move Bun's transpiler cache and make
|
||||
// every sample transpile the source CLI from scratch. A dev start reuses the developer's cache.
|
||||
BUN_RUNTIME_TRANSPILER_CACHE_PATH: process.env.BUN_RUNTIME_TRANSPILER_CACHE_PATH ?? bunTranspilerCache(),
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
|
||||
if (!child.pid || !child.stdout || !child.stderr) throw new Error("Failed to start the desktop command")
|
||||
const exited = childExit(child)
|
||||
const observed: Partial<Record<Milestone, number>> = {}
|
||||
const endpoint = Promise.withResolvers<string>()
|
||||
const pageErrors: string[] = []
|
||||
let browser: Browser | undefined
|
||||
let service: ServiceInfo | undefined
|
||||
|
||||
const mark = (name: Milestone) => {
|
||||
observed[name] ??= elapsed(started)
|
||||
}
|
||||
|
||||
const record = (line: string) => {
|
||||
const milestone = milestoneForLine(line)
|
||||
|
||||
if (milestone) mark(milestone)
|
||||
const match = stripAnsi(line).match(/DevTools listening on (ws:\/\/\S+)/)
|
||||
|
||||
if (match?.[1]) endpoint.resolve(match[1])
|
||||
}
|
||||
|
||||
const stdout = observeOutput(child.stdout, record)
|
||||
const stderr = observeOutput(child.stderr, record)
|
||||
|
||||
return {
|
||||
mark,
|
||||
async open() {
|
||||
const url = await Promise.race([
|
||||
endpoint.promise,
|
||||
exited.then((code) => {
|
||||
throw new Error(`Desktop command exited with code ${code} before opening its debug endpoint`)
|
||||
}),
|
||||
sleep(120_000).then(() => {
|
||||
throw new Error("Timed out waiting for the desktop debug endpoint")
|
||||
}),
|
||||
])
|
||||
|
||||
// Observe the native appearance and focus instead of applying Playwright's media defaults.
|
||||
browser = await chromium.connectOverCDP(url, { timeout: 120_000, noDefaults: true })
|
||||
const context = browser.contexts()[0]
|
||||
|
||||
if (!context) throw new Error("Electron did not expose a browser context")
|
||||
await expect.poll(() => context.pages().length, { timeout: 120_000 }).toBeGreaterThan(0)
|
||||
const page = context.pages()[0]
|
||||
|
||||
if (!page) throw new Error("Electron did not expose a renderer page")
|
||||
page.on("pageerror", (error) => pageErrors.push(error.stack ?? error.message))
|
||||
|
||||
return page
|
||||
},
|
||||
async result(run: number): Promise<DesktopStartupSample> {
|
||||
if (pageErrors.length) throw new Error(`Desktop renderer reported errors:\n\n${pageErrors.join("\n\n")}`)
|
||||
service = await readService(profile)
|
||||
const milestonesMs = requireMilestones(observed)
|
||||
|
||||
return {
|
||||
run,
|
||||
commandToHomeReadyMs: milestonesMs.homeReady,
|
||||
milestonesMs,
|
||||
phasesMs: calculatePhases(milestonesMs),
|
||||
service: {
|
||||
version: service.version,
|
||||
url: service.url,
|
||||
pid: service.pid,
|
||||
},
|
||||
}
|
||||
},
|
||||
async close(testInfo: TestInfo, run: number) {
|
||||
const errors: unknown[] = []
|
||||
await browser?.close().catch(() => undefined)
|
||||
await stopProcessTree(child, exited).catch((error) => {
|
||||
errors.push(error)
|
||||
child.stdout?.destroy()
|
||||
child.stderr?.destroy()
|
||||
})
|
||||
|
||||
const [stdoutText, stderrText] = await Promise.all([stdout, stderr]).catch((error) => {
|
||||
errors.push(error)
|
||||
|
||||
return ["", ""]
|
||||
})
|
||||
|
||||
await Promise.all([
|
||||
testInfo.attach(`desktop-startup-${run}-stdout`, { body: stdoutText, contentType: "text/plain" }),
|
||||
testInfo.attach(`desktop-startup-${run}-stderr`, { body: stderrText, contentType: "text/plain" }),
|
||||
pageErrors.length
|
||||
? testInfo.attach(`desktop-startup-${run}-page-errors`, {
|
||||
body: pageErrors.join("\n\n"),
|
||||
contentType: "text/plain",
|
||||
})
|
||||
: Promise.resolve(),
|
||||
]).catch((error) => errors.push(error))
|
||||
await Service.stop({ file: profile.registration }).catch((error) => errors.push(error))
|
||||
|
||||
if (service && processAlive(service.pid))
|
||||
errors.push(new Error(`Desktop service process ${service.pid} did not stop`))
|
||||
await rm(profile.root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }).catch((error) =>
|
||||
errors.push(error),
|
||||
)
|
||||
|
||||
if (errors.length) throw new AggregateError(errors, "Desktop benchmark cleanup failed")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Bun's default location for its runtime transpiler cache.
|
||||
function bunTranspilerCache() {
|
||||
if (process.env.XDG_CACHE_HOME) return join(process.env.XDG_CACHE_HOME, "bun", "@t@")
|
||||
|
||||
if (process.platform === "darwin") return join(homedir(), "Library", "Caches", "bun", "@t@")
|
||||
|
||||
return join(homedir(), ".bun", "install", "cache", "@t@")
|
||||
}
|
||||
|
||||
async function waitForHome(page: Page, mark: (name: Milestone) => void) {
|
||||
await expect.poll(() => page.evaluate(() => document.visibilityState), { timeout: 120_000 }).toBe("visible")
|
||||
|
||||
const projects = page.getByRole("complementary", { name: "Projects", exact: true })
|
||||
const sessions = page.getByRole("region", { name: "Recent sessions", exact: true })
|
||||
const search = page.getByRole("textbox", { name: "Search sessions", exact: true })
|
||||
const addProject = projects.locator('button[data-action="home-add-project-row"]')
|
||||
await expect(projects).toBeVisible({ timeout: 120_000 })
|
||||
await expect(sessions).toBeVisible()
|
||||
await expect(search).toBeEditable()
|
||||
await expect(sessions.getByText("Nothing here yet", { exact: true })).toBeVisible()
|
||||
await expect(addProject).toHaveCount(1)
|
||||
await addProject.click({ trial: true })
|
||||
mark("homeReady")
|
||||
}
|
||||
|
||||
type ThemeWindow = Window & {
|
||||
__OPENCODE_THEME_STATES__?: string[]
|
||||
__OPENCODE_THEME_OBSERVER__?: MutationObserver
|
||||
}
|
||||
|
||||
async function startThemeObservation(page: Page) {
|
||||
await page.addInitScript(installThemeObservation)
|
||||
await page.evaluate(installThemeObservation)
|
||||
}
|
||||
|
||||
async function requireStableTheme(page: Page) {
|
||||
const states = await page.evaluate(() => {
|
||||
// SAFETY: only `installThemeObservation` writes these optional globals, in the declared shapes.
|
||||
const target = window as ThemeWindow
|
||||
target.__OPENCODE_THEME_OBSERVER__?.disconnect()
|
||||
|
||||
return target.__OPENCODE_THEME_STATES__ ?? []
|
||||
})
|
||||
|
||||
if (states.length !== 1) throw new Error(`Desktop theme changed during startup: ${states.join(" -> ")}`)
|
||||
}
|
||||
|
||||
function installThemeObservation() {
|
||||
// SAFETY: this function is the only writer of these optional globals, in the declared shapes.
|
||||
const target = window as ThemeWindow
|
||||
|
||||
const observeRoot = () => {
|
||||
const root = document.documentElement
|
||||
|
||||
if (!root) return false
|
||||
|
||||
const state = () => {
|
||||
const theme = root.dataset.theme
|
||||
const scheme = root.dataset.colorScheme
|
||||
|
||||
return theme && scheme ? `${theme}:${scheme}` : undefined
|
||||
}
|
||||
|
||||
const initial = state()
|
||||
target.__OPENCODE_THEME_STATES__ = initial ? [initial] : []
|
||||
target.__OPENCODE_THEME_OBSERVER__ = new MutationObserver(() => {
|
||||
const next = state()
|
||||
|
||||
if (!next) return
|
||||
|
||||
if (target.__OPENCODE_THEME_STATES__?.at(-1) !== next) target.__OPENCODE_THEME_STATES__?.push(next)
|
||||
})
|
||||
target.__OPENCODE_THEME_OBSERVER__.observe(root, {
|
||||
attributes: true,
|
||||
attributeFilter: ["data-theme", "data-color-scheme"],
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (observeRoot()) return
|
||||
|
||||
const documentObserver = new MutationObserver(() => {
|
||||
if (!observeRoot()) return
|
||||
documentObserver.disconnect()
|
||||
})
|
||||
|
||||
target.__OPENCODE_THEME_OBSERVER__ = documentObserver
|
||||
documentObserver.observe(document, { childList: true })
|
||||
}
|
||||
|
||||
async function observeOutput(stream: NodeJS.ReadableStream, record: (line: string) => void) {
|
||||
// The stream decodes UTF-8 itself, keeping characters split across chunks intact.
|
||||
stream.setEncoding("utf8")
|
||||
const output: string[] = []
|
||||
let pending = ""
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const text = String(chunk)
|
||||
output.push(text)
|
||||
pending += text
|
||||
const lines = pending.split(/\r?\n/)
|
||||
pending = lines.pop() ?? ""
|
||||
lines.forEach(record)
|
||||
}
|
||||
|
||||
if (pending) record(pending)
|
||||
|
||||
return output.join("")
|
||||
}
|
||||
|
||||
async function readService(profile: Awaited<ReturnType<typeof createColdProfile>>) {
|
||||
const value = Schema.decodeUnknownSync(Schema.fromJsonString(ServiceInfo))(
|
||||
await readFile(profile.registration, "utf8"),
|
||||
)
|
||||
|
||||
const url = new URL(value.url)
|
||||
const port = Number(url.port)
|
||||
|
||||
// The isolated dev service listens on every interface so paired devices can reach it.
|
||||
if (!["127.0.0.1", "0.0.0.0"].includes(url.hostname) || !Number.isInteger(port) || port <= 0)
|
||||
throw new Error(`Desktop service used unexpected endpoint ${value.url}`)
|
||||
|
||||
if (!value.version.startsWith("2.0.0-local-"))
|
||||
throw new Error(`Desktop service used unexpected version ${value.version}`)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
function requireMilestones(observed: Partial<Record<Milestone, number>>) {
|
||||
const get = (name: Milestone) => {
|
||||
const value = observed[name]
|
||||
|
||||
if (value === undefined) throw new Error(`Desktop startup did not report milestone: ${name}`)
|
||||
|
||||
return round(value)
|
||||
}
|
||||
|
||||
return {
|
||||
bunRootScript: get("bunRootScript"),
|
||||
bunDesktopScript: get("bunDesktopScript"),
|
||||
desktopPrepared: get("desktopPrepared"),
|
||||
mainBundleReady: get("mainBundleReady"),
|
||||
preloadBundleReady: get("preloadBundleReady"),
|
||||
rendererDevServerReady: get("rendererDevServerReady"),
|
||||
electronSpawnStarted: get("electronSpawnStarted"),
|
||||
debugEndpointReady: get("debugEndpointReady"),
|
||||
electronStarted: get("electronStarted"),
|
||||
layersReady: get("layersReady"),
|
||||
windowVisible: get("windowVisible"),
|
||||
serviceEnsureStarted: get("serviceEnsureStarted"),
|
||||
serviceSpawnRequested: get("serviceSpawnRequested"),
|
||||
serviceReady: get("serviceReady"),
|
||||
rendererViteConnected: get("rendererViteConnected"),
|
||||
homeReady: get("homeReady"),
|
||||
}
|
||||
}
|
||||
|
||||
function calculatePhases(value: Record<Milestone, number>): Record<Phase, number> {
|
||||
return {
|
||||
desktopPreparation: value.desktopPrepared,
|
||||
viteMainBundle: round(value.mainBundleReady - value.desktopPrepared),
|
||||
vitePreloadBundle: round(value.preloadBundleReady - value.mainBundleReady),
|
||||
rendererServerStartup: round(value.rendererDevServerReady - value.preloadBundleReady),
|
||||
electronStartup: round(value.electronStarted - value.electronSpawnStarted),
|
||||
serviceSpawnWait: round(value.serviceSpawnRequested - value.serviceEnsureStarted),
|
||||
serviceProcessStartup: round(value.serviceReady - value.serviceSpawnRequested),
|
||||
rendererStartup: round(value.homeReady - value.rendererViteConnected),
|
||||
visibleWindowToHome: round(value.homeReady - value.windowVisible),
|
||||
}
|
||||
}
|
||||
|
||||
function statistics(values: number[]) {
|
||||
if (!values.length) throw new Error("Cannot summarize an empty benchmark")
|
||||
const sorted = values.toSorted((left, right) => left - right)
|
||||
const median = medianOf(sorted)
|
||||
|
||||
return {
|
||||
min: round(sorted[0]),
|
||||
median: round(median),
|
||||
max: round(sorted.at(-1)!),
|
||||
medianAbsoluteDeviation: round(medianOf(sorted.map((value) => Math.abs(value - median)).toSorted((a, b) => a - b))),
|
||||
}
|
||||
}
|
||||
|
||||
function medianOf(sorted: number[]) {
|
||||
const middle = Math.floor(sorted.length / 2)
|
||||
|
||||
if (sorted.length % 2) return sorted[middle]
|
||||
|
||||
return (sorted[middle - 1] + sorted[middle]) / 2
|
||||
}
|
||||
|
||||
async function stopProcessTree(child: ChildProcess, exited: Promise<number | null>) {
|
||||
if (!child.pid) throw new Error("Desktop command has no process ID")
|
||||
|
||||
if (process.platform !== "win32") return stopProcessGroup(child.pid, exited)
|
||||
|
||||
if (child.exitCode !== null || (await exitsWithin(child, exited, 2_000))) return
|
||||
|
||||
const kill = spawn("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], {
|
||||
stdio: "ignore",
|
||||
})
|
||||
|
||||
await childExit(kill)
|
||||
|
||||
if (await exitsWithin(child, exited, 10_000)) return
|
||||
|
||||
if (!(await exitsWithin(child, exited, 5_000))) throw new Error(`Desktop command process ${child.pid} did not stop`)
|
||||
}
|
||||
|
||||
async function stopProcessGroup(pid: number, exited: Promise<number | null>) {
|
||||
await Promise.race([exited, sleep(2_000)])
|
||||
|
||||
if (!processGroupAlive(pid)) return
|
||||
process.kill(-pid, "SIGTERM")
|
||||
|
||||
if (await processGroupStopsWithin(pid, 10_000)) return
|
||||
process.kill(-pid, "SIGKILL")
|
||||
|
||||
if (!(await processGroupStopsWithin(pid, 5_000))) throw new Error(`Desktop command process group ${pid} did not stop`)
|
||||
}
|
||||
|
||||
async function processGroupStopsWithin(pid: number, timeout: number) {
|
||||
const deadline = Date.now() + timeout
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
if (!processGroupAlive(pid)) return true
|
||||
await sleep(50)
|
||||
}
|
||||
|
||||
return !processGroupAlive(pid)
|
||||
}
|
||||
|
||||
function processGroupAlive(pid: number) {
|
||||
try {
|
||||
process.kill(-pid, 0)
|
||||
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function exitsWithin(child: ChildProcess, exited: Promise<number | null>, timeout: number) {
|
||||
if (child.exitCode !== null) return true
|
||||
const result = await Promise.race([exited.then(() => true), sleep(timeout).then(() => false)])
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function childExit(child: ChildProcess) {
|
||||
return new Promise<number | null>((resolve, reject) => {
|
||||
child.once("error", reject)
|
||||
child.once("exit", (code) => resolve(code))
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(milliseconds: number) {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
function processAlive(pid: number) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")
|
||||
}
|
||||
|
||||
function elapsed(started: number) {
|
||||
return round(performance.now() - started)
|
||||
}
|
||||
|
||||
function round(value: number) {
|
||||
return Math.round(value * 100) / 100
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import { defineConfig } from "@playwright/test"
|
||||
|
||||
process.env.OPENCODE_PERFORMANCE_RUN_ID ??= `${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
testMatch: "desktop-startup-benchmark.spec.ts",
|
||||
outputDir: "../../test-results/performance-devex",
|
||||
timeout: 15 * 60_000,
|
||||
expect: {
|
||||
timeout: 120_000,
|
||||
},
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
reporter: [["html", { outputFolder: "../../playwright-report/performance-devex", open: "never" }], ["line"]],
|
||||
projects: [{ name: "desktop" }],
|
||||
})
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
# Timeline Preload Lifetime
|
||||
|
||||
This manual benchmark uses the production app, restored session tabs, the real
|
||||
`MessageTimeline` preload, and the real Markdown worker. Only API data and result
|
||||
delivery timing are fixture-owned. It does not connect to a running OpenCode
|
||||
service or send prompts.
|
||||
|
||||
From `packages/app`, set absolute `MARKDOWN_APP_BUILD_DIR` and
|
||||
`MARKDOWN_RESULTS_DIR` artifact paths, then run:
|
||||
|
||||
```sh
|
||||
bun run build
|
||||
# Copy dist into MARKDOWN_APP_BUILD_DIR before editing production source.
|
||||
bun --bun x playwright test --config e2e/performance/markdown/playwright.config.ts --repeat-each 20
|
||||
```
|
||||
|
||||
Each isolated sample restores two sessions with one user message and one completed
|
||||
assistant text part each. The cold target has a realistic recovery review with
|
||||
either two TypeScript fences (typical) or 36 fences (large). The source has a short
|
||||
completed answer. Target data is prefetched before selection, but its Markdown is
|
||||
not parsed until the target is selected.
|
||||
|
||||
The app's service-worker generator reads `dist`, so use the normal build output
|
||||
and freeze a copy, rather than overriding Vite's build output directory.
|
||||
|
||||
The real worker result is held after admission. The test selects the original
|
||||
session again and releases the held result only after the abandoned timeline row
|
||||
detaches and the selected answer reports production Markdown readiness. This
|
||||
exercises both the timeline preload and the nested Markdown consumer, including
|
||||
the case where either one would otherwise keep a shared parse alive.
|
||||
|
||||
Destination readiness and post-disposal result settlement are separate metrics.
|
||||
The latter is a MessageChannel task after the result's promise microtasks drain.
|
||||
The DOMParser probe counts actual DOMPurify input containing the abandoned answer
|
||||
after disposal, in characters. CDP reports renderer task/script time and JS heap.
|
||||
These are not worker CPU, Electron process RAM, or ungated tab-switch measurements.
|
||||
In particular, this gate releases the result after destination readiness and must
|
||||
not be used to claim a destination-readiness gain from skipping sanitization.
|
||||
|
||||
`MARKDOWN_ASSERT_DISPOSAL=1` enables the no-obsolete-sanitization assertion. Use
|
||||
`MARKDOWN_RETAINED=1` only in separate post-GC runs. The repository trace collector
|
||||
is available through `OPENCODE_PERFORMANCE_TRACE_DIR`, and `MARKDOWN_SCREENSHOT`
|
||||
captures final output after timing. Run serially, preserve frozen builds, and keep
|
||||
all results outside Git.
|
||||
|
|
@ -1,135 +0,0 @@
|
|||
import type { SessionMessageInfo } from "@opencode/client/promise"
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { fixture, installStressSessionTabs, installTimelineSettings } from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { completedAnswer } from "../../../../session-ui/performance/markdown-lifetime/answer"
|
||||
import { installMarkdownGate } from "./probe"
|
||||
|
||||
for (const size of ["typical", "large"]) {
|
||||
benchmark(`timeline preload disposal: ${size}`, async ({ page, report }) => {
|
||||
const answer = completedAnswer(size === "typical" ? 2 : 36)
|
||||
const errors: string[] = []
|
||||
page.on("pageerror", (error) => errors.push(error.message))
|
||||
|
||||
const messages: Record<string, SessionMessageInfo[]> = Object.fromEntries(
|
||||
[fixture.sourceID, fixture.targetID].map((id) => [
|
||||
id,
|
||||
[
|
||||
{
|
||||
id: `msg_1_${id}_user`,
|
||||
type: "user",
|
||||
time: { created: 1700000000000 },
|
||||
text: "Review the recovery boundary.",
|
||||
},
|
||||
{
|
||||
id: `msg_2_${id}_assistant`,
|
||||
type: "assistant",
|
||||
time: { created: 1700000001000, completed: 1700000008000 },
|
||||
model: { id: "claude-opus-4-6", providerID: "opencode" },
|
||||
agent: "build",
|
||||
cost: 0.01,
|
||||
tokens: { input: 100, output: 200, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
finish: "stop",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
id === fixture.targetID
|
||||
? answer
|
||||
: "## Current destination\n\nThe selected session is ready.\n\n```typescript\nconst current = { ready: true }\n```",
|
||||
},
|
||||
],
|
||||
},
|
||||
] satisfies SessionMessageInfo[],
|
||||
]),
|
||||
)
|
||||
|
||||
await mockOpenCodeServer(page, {
|
||||
sessions: fixture.sessions.filter((session) => session.id !== fixture.childID),
|
||||
provider: fixture.provider,
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
pageMessages: (id) => ({ items: messages[id] ?? [] }),
|
||||
})
|
||||
await installTimelineSettings(page)
|
||||
await installStressSessionTabs(page)
|
||||
const targetPart = `msg_2_${fixture.targetID}_assistant:text:0`
|
||||
const sourcePart = `msg_2_${fixture.sourceID}_assistant:text:0`
|
||||
await installMarkdownGate(page, { answer, targetPart, sourcePart, href: sessionHref(fixture.sourceID) })
|
||||
|
||||
const prefetched = page.waitForResponse((response) =>
|
||||
new URL(response.url()).pathname.endsWith(`/session/${fixture.targetID}/message`),
|
||||
)
|
||||
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
await prefetched
|
||||
const source = page.locator(`[data-timeline-part-id="${sourcePart}"] [data-component="markdown"]`)
|
||||
await expect(source).toHaveAttribute("data-markdown-ready", "")
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(fixture.targetID)}"]`).click()
|
||||
await page.waitForFunction(() => window.markdownGate.held)
|
||||
await expect(page.locator(`[data-timeline-part-id="${targetPart}"]`)).toBeAttached()
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
const before = await cdp.send("Performance.getMetrics")
|
||||
await page.evaluate(() => window.markdownGate.arm())
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(fixture.sourceID)}"]`).click()
|
||||
await expect(source).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(source.getByRole("heading", { name: "Current destination" })).toBeVisible()
|
||||
await expect(page.locator(`[data-timeline-part-id="${targetPart}"]`)).toHaveCount(0)
|
||||
await page.waitForFunction(() => window.markdownGate.settled > 0)
|
||||
const after = await cdp.send("Performance.getMetrics")
|
||||
|
||||
const stats = await page.evaluate(() => {
|
||||
const value = window.markdownGate
|
||||
|
||||
return {
|
||||
admitted: value.admitted,
|
||||
responses: value.responses,
|
||||
started: value.started,
|
||||
ready: value.ready,
|
||||
released: value.released,
|
||||
settled: value.settled,
|
||||
sanitizeCalls: value.sanitizeCalls,
|
||||
sanitizeChars: value.sanitizeChars,
|
||||
}
|
||||
})
|
||||
|
||||
expect(stats.admitted).toBe(1)
|
||||
expect(stats.responses).toBe(1)
|
||||
expect(stats.ready).toBeGreaterThan(stats.started)
|
||||
expect(stats.settled).toBeGreaterThan(stats.released)
|
||||
expect(errors).toEqual([])
|
||||
|
||||
if (process.env.MARKDOWN_ASSERT_DISPOSAL === "1") expect(stats.sanitizeCalls).toBe(0)
|
||||
const value = (data: typeof after, name: string) => data.metrics.find((item) => item.name === name)!.value
|
||||
const retained = process.env.MARKDOWN_RETAINED === "1"
|
||||
|
||||
if (retained) await cdp.send("HeapProfiler.collectGarbage")
|
||||
report(
|
||||
{
|
||||
...stats,
|
||||
destinationReadyMs: stats.ready - stats.started,
|
||||
releasedSettledMs: stats.settled - stats.released,
|
||||
taskMs: (value(after, "TaskDuration") - value(before, "TaskDuration")) * 1000,
|
||||
scriptMs: (value(after, "ScriptDuration") - value(before, "ScriptDuration")) * 1000,
|
||||
usedHeapBytes: (await cdp.send("Runtime.getHeapUsage")).usedSize,
|
||||
},
|
||||
{
|
||||
size,
|
||||
retained,
|
||||
answerBytes: Buffer.byteLength(answer),
|
||||
messagesPerSession: 2,
|
||||
partsPerAnswer: 1,
|
||||
fences: size === "typical" ? 2 : 36,
|
||||
browser: page.context().browser()!.version(),
|
||||
transport: "playwright-route",
|
||||
build: process.env.MARKDOWN_APP_BUILD_DIR,
|
||||
},
|
||||
)
|
||||
|
||||
if (process.env.MARKDOWN_SCREENSHOT)
|
||||
await page.screenshot({ path: `${process.env.MARKDOWN_SCREENSHOT}/timeline-${size}.png` })
|
||||
await cdp.detach()
|
||||
})
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
import { defineConfig } from "@playwright/test"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
process.env.PLAYWRIGHT_PORT = "6199"
|
||||
|
||||
process.env.PLAYWRIGHT_SERVER_PORT = "6199"
|
||||
|
||||
process.env.PLAYWRIGHT_SERVER_HOST = "127.0.0.1"
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
testMatch: "*.bench.ts",
|
||||
outputDir: process.env.MARKDOWN_RESULTS_DIR,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
timeout: 60_000,
|
||||
expect: { timeout: 15_000 },
|
||||
reporter: [["line"]],
|
||||
use: { baseURL: "http://127.0.0.1:6199", viewport: { width: 1280, height: 900 }, serviceWorkers: "block" },
|
||||
webServer: {
|
||||
cwd: fileURLToPath(new URL("../../..", import.meta.url)),
|
||||
command: `bun run serve -- --host 127.0.0.1 --port 6199 --strictPort --outDir "${process.env.MARKDOWN_APP_BUILD_DIR}"`,
|
||||
url: "http://127.0.0.1:6199",
|
||||
reuseExistingServer: false,
|
||||
},
|
||||
})
|
||||
|
|
@ -1,121 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import type {
|
||||
MarkdownWorkerRequest,
|
||||
MarkdownWorkerResponse,
|
||||
} from "../../../../session-ui/src/components/markdown-worker-protocol"
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
markdownGate: {
|
||||
admitted: number
|
||||
responses: number
|
||||
held: boolean
|
||||
started: number
|
||||
ready: number
|
||||
released: number
|
||||
settled: number
|
||||
sanitizeCalls: number
|
||||
sanitizeChars: number
|
||||
arm: () => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function installMarkdownGate(
|
||||
page: Page,
|
||||
input: { answer: string; sourcePart: string; targetPart: string; href: string },
|
||||
) {
|
||||
await page.addInitScript(({ answer, sourcePart, targetPart, href }) => {
|
||||
const stats = {
|
||||
admitted: 0,
|
||||
responses: 0,
|
||||
held: false,
|
||||
started: 0,
|
||||
ready: 0,
|
||||
released: 0,
|
||||
settled: 0,
|
||||
sanitizeCalls: 0,
|
||||
sanitizeChars: 0,
|
||||
arm: () => {
|
||||
armed = true
|
||||
},
|
||||
}
|
||||
|
||||
let armed = false
|
||||
let id: number | undefined
|
||||
let release: (() => void) | undefined
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage")!
|
||||
const post = Worker.prototype.postMessage
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
get: descriptor.get,
|
||||
set(callback: (event: MessageEvent<MarkdownWorkerResponse>) => void) {
|
||||
descriptor.set!.call(this, (event: MessageEvent<MarkdownWorkerResponse>) => {
|
||||
if (event.data.type === "parse" && event.data.id === id) {
|
||||
stats.responses++
|
||||
stats.held = true
|
||||
release = () => callback.call(this, event)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
callback.call(this, event)
|
||||
})
|
||||
},
|
||||
})
|
||||
Worker.prototype.postMessage = function (request: MarkdownWorkerRequest) {
|
||||
if (request.type === "parse" && request.text === answer) {
|
||||
id = request.id
|
||||
stats.admitted++
|
||||
}
|
||||
|
||||
post.call(this, request)
|
||||
}
|
||||
|
||||
const parse = DOMParser.prototype.parseFromString
|
||||
DOMParser.prototype.parseFromString = function (text, type) {
|
||||
if (stats.released && String(text).includes("Recovery implementation review")) {
|
||||
stats.sanitizeCalls++
|
||||
stats.sanitizeChars += String(text).length
|
||||
}
|
||||
|
||||
return parse.call(this, text, type)
|
||||
}
|
||||
|
||||
document.addEventListener(
|
||||
"mousedown",
|
||||
(event) => {
|
||||
if (!armed || stats.started) return
|
||||
const target = event.target instanceof Element ? event.target.closest("a") : undefined
|
||||
|
||||
if (target?.getAttribute("href") !== href) return
|
||||
stats.started = performance.now()
|
||||
},
|
||||
true,
|
||||
)
|
||||
// The app can retain the outgoing view until the destination is ready. Release
|
||||
// only after its actual row detaches, rather than assuming click means dispose.
|
||||
new MutationObserver(() => {
|
||||
if (!stats.started || stats.released) return
|
||||
const current = document.querySelector(`[data-timeline-part-id="${sourcePart}"] [data-markdown-ready]`)
|
||||
|
||||
if (!current) return
|
||||
stats.ready ||= performance.now()
|
||||
|
||||
if (document.querySelector(`[data-timeline-part-id="${targetPart}"]`)) return
|
||||
stats.released = performance.now()
|
||||
performance.mark("markdown-timeline-disposed")
|
||||
release!()
|
||||
release = undefined
|
||||
const channel = new MessageChannel()
|
||||
channel.port1.onmessage = () => {
|
||||
stats.settled = performance.now()
|
||||
channel.port1.close()
|
||||
channel.port2.close()
|
||||
}
|
||||
|
||||
channel.port2.postMessage(null)
|
||||
}).observe(document, { childList: true, subtree: true, attributes: true })
|
||||
Object.defineProperty(window, "markdownGate", { value: stats })
|
||||
}, input)
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
# Patch Group Benchmark
|
||||
|
||||
This manual benchmark mounts the production `CurrentFileToolGroup` and `File`
|
||||
components with completed edit results. A separate case mounts `ToolDisplay`
|
||||
with a patch result. It uses four real Core tool source files, with deterministic
|
||||
identifier renames, rather than repeated filler. It does not connect to a server.
|
||||
|
||||
From `packages/app`, set `PATCH_BUILD_DIR` and `PATCH_RESULTS_DIR` to external
|
||||
artifact directories, then run:
|
||||
|
||||
```sh
|
||||
bun x vite build --config e2e/performance/patch-groups/vite.config.ts
|
||||
bun x playwright test --config e2e/performance/patch-groups/playwright.config.ts --repeat-each=20
|
||||
```
|
||||
|
||||
Run under the shared exclusive gate when collecting measurements on a shared
|
||||
machine. The Playwright-owned static server uses `PATCH_PORT` (default 4317),
|
||||
refuses to reuse an existing server, and shuts down after the run.
|
||||
|
||||
Each fresh browser context measures a cold collapsed mount, a warm remount,
|
||||
and opening `edit.ts` through its real accordion. Mount timing covers synchronous
|
||||
component construction through layout. Expansion timing starts at the click and
|
||||
ends at the production file renderer's `onRendered` callback. Assertions check
|
||||
the exact file count, collapsed state, and completed file rendering. Results
|
||||
include payload bytes, source bytes, file/tool counts, and supporting warm
|
||||
`patchFileGroups` timings with and without reading views. No timing thresholds
|
||||
are enforced. This is a browser component workload, not a full desktop memory test.
|
||||
|
||||
Freeze the build before changing production code. Use the same fixture, browser,
|
||||
viewport, sample count, and completion checks for both revisions.
|
||||
|
||||
`PATCH_REVISION=<git-sha>` loads the grouping module and tool renderer from that
|
||||
revision at build time without changing the worktree. This is useful when fixing
|
||||
the harness after freezing a baseline. All other production sources must match
|
||||
between revisions; this switch only covers those two measured modules.
|
||||
|
||||
For a separate diagnostic build, set `PATCH_COUNTERS=1`. Its build-only transform
|
||||
counts grouping, normalization, reconstruction, and line-diff calls with User
|
||||
Timing marks. Do not mix instrumented results with clean timings. Set
|
||||
`OPENCODE_PERFORMANCE_TRACE_DIR` for the existing Chrome trace collector, and
|
||||
`PATCH_SCREENSHOTS=1` for collapsed/expanded screenshots after measurement.
|
||||
|
|
@ -1,153 +0,0 @@
|
|||
/// <reference types="vite/client" />
|
||||
|
||||
import { render } from "solid-js/web"
|
||||
import { Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { ThemeProvider } from "@opencode/ui/theme"
|
||||
import { CurrentSessionProviders } from "../../../../session-ui/src/storybook/current-session-story"
|
||||
import { emptySessionDocument } from "../../../../session-ui/src/storybook/current-session-fixtures"
|
||||
import { CurrentFileToolGroup, ToolDisplay } from "../../../../session-ui/src/tools/tool-renderer"
|
||||
import { patchFileGroups } from "../../../../session-ui/src/components/apply-patch-file"
|
||||
import type { SessionMessageAssistantTool } from "@opencode/client/promise"
|
||||
import { createTwoFilesPatch, diffLines } from "diff"
|
||||
import edit from "../../../../core/src/tool/plugin/edit.ts?raw"
|
||||
import patch from "../../../../core/src/tool/plugin/patch.ts?raw"
|
||||
import read from "../../../../core/src/tool/plugin/read.ts?raw"
|
||||
import shell from "../../../../core/src/tool/plugin/shell.ts?raw"
|
||||
import "../../../src/index.css"
|
||||
|
||||
const scenario = new URLSearchParams(location.search).get("scenario") ?? "complete"
|
||||
|
||||
const sources = [edit, patch, read, shell].map((text) => text.replaceAll("\r\n", "\n"))
|
||||
|
||||
const names = ["edit", "patch", "read", "shell"]
|
||||
|
||||
const changed = (text: string) => text.replaceAll(/\bcontext\b/g, "invocation")
|
||||
|
||||
const entry = (index: number, before: string, after: string) => ({
|
||||
file: `src/tool/plugin/${names[index]}.ts`,
|
||||
patch: createTwoFilesPatch(names[index], names[index], before, after, "", "", {
|
||||
context: scenario === "partial" ? 3 : Infinity,
|
||||
}),
|
||||
...diffLines(before, after).reduce(
|
||||
(counts, item) => ({
|
||||
additions: counts.additions + (item.added ? item.count : 0),
|
||||
deletions: counts.deletions + (item.removed ? item.count : 0),
|
||||
}),
|
||||
{ additions: 0, deletions: 0 },
|
||||
),
|
||||
status: "modified" as const,
|
||||
})
|
||||
|
||||
const files =
|
||||
scenario === "multi"
|
||||
? sources.map((text, index) => entry(index, text, changed(text)))
|
||||
: [
|
||||
entry(0, sources[0], changed(sources[0])),
|
||||
...(scenario === "chained"
|
||||
? [entry(0, changed(sources[0]), changed(sources[0]).replaceAll(/\binput\b/g, "parameters"))]
|
||||
: []),
|
||||
]
|
||||
|
||||
const tools: SessionMessageAssistantTool[] = files.map((file, index) => ({
|
||||
id: `fixture-edit-${index}`,
|
||||
type: "tool",
|
||||
name: "edit",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { path: file.file, oldString: "context", newString: "invocation", replaceAll: true },
|
||||
metadata: { files: [file] },
|
||||
content: [{ type: "text", text: `Edited ${file.file}` }],
|
||||
},
|
||||
time: { created: 1, ran: 2, completed: 3 },
|
||||
}))
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
patchBenchmark: {
|
||||
payloadBytes: number
|
||||
sourceBytes: number
|
||||
files: number
|
||||
tools: number
|
||||
grouping: (expanded: boolean) => { ms: number; groups: number; views: number }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.patchBenchmark = {
|
||||
payloadBytes: new TextEncoder().encode(JSON.stringify(tools)).length,
|
||||
sourceBytes: new TextEncoder().encode(sources.slice(0, scenario === "multi" ? 4 : 1).join("")).length,
|
||||
files: new Set(files.map((file) => file.file)).size,
|
||||
tools: tools.length,
|
||||
grouping(expanded) {
|
||||
const start = performance.now()
|
||||
const groups = patchFileGroups(files)
|
||||
const views = expanded ? groups.reduce((count, file) => count + file.views.length, 0) : 0
|
||||
|
||||
return { ms: performance.now() - start, groups: groups.length, views }
|
||||
},
|
||||
}
|
||||
|
||||
function Fixture() {
|
||||
const [state, setState] = createStore({ mounted: false, duration: 0, rendered: 0 })
|
||||
let start = 0
|
||||
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<section style={{ margin: "24px auto", "max-width": "960px" }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
start = performance.now()
|
||||
setState("mounted", true)
|
||||
document.querySelector("[data-component=apply-patch-tool]")!.getBoundingClientRect()
|
||||
setState("duration", performance.now() - start)
|
||||
}}
|
||||
>
|
||||
Mount tools
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setState({ mounted: false, rendered: 0 })
|
||||
}}
|
||||
>
|
||||
Unmount tools
|
||||
</button>
|
||||
<output data-testid="mount-ms">{state.duration}</output>
|
||||
<output data-testid="rendered">{state.rendered}</output>
|
||||
<div
|
||||
on:click={{
|
||||
capture: true,
|
||||
handleEvent() {
|
||||
start = performance.now()
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Show when={state.mounted}>
|
||||
<CurrentSessionProviders document={emptySessionDocument}>
|
||||
<Show
|
||||
when={scenario === "direct"}
|
||||
fallback={
|
||||
<CurrentFileToolGroup
|
||||
tools={tools}
|
||||
onSizeChange={() => setState("rendered", performance.now() - start)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ToolDisplay
|
||||
id="fixture-patch"
|
||||
tool="patch"
|
||||
input={{}}
|
||||
metadata={{ files }}
|
||||
status="completed"
|
||||
onContentRendered={() => setState("rendered", performance.now() - start)}
|
||||
/>
|
||||
</Show>
|
||||
</CurrentSessionProviders>
|
||||
</Show>
|
||||
</div>
|
||||
</section>
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
render(() => <Fixture />, document.getElementById("root")!)
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Patch groups benchmark</title>
|
||||
</head>
|
||||
<body>
|
||||
<main id="root"></main>
|
||||
<script type="module" src="./fixture.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
|
||||
for (const scenario of ["complete", "partial", "chained", "multi", "direct"]) {
|
||||
benchmark(`patch groups ${scenario}`, async ({ page, report }, info) => {
|
||||
await page.goto(`/?scenario=${scenario}`)
|
||||
await expect(page.getByRole("button", { name: "Mount tools", exact: true })).toBeEnabled()
|
||||
await page.evaluate(() => document.fonts.ready)
|
||||
expect(await page.evaluate(() => document.fonts.check('13px "Inter"'))).toBe(true)
|
||||
|
||||
const shape = await page.evaluate(() => {
|
||||
const { grouping, ...shape } = window.patchBenchmark
|
||||
performance.clearMarks()
|
||||
|
||||
return shape
|
||||
})
|
||||
|
||||
const mount = async () => {
|
||||
await page.getByRole("button", { name: "Mount tools", exact: true }).click()
|
||||
await expect(page.locator('[data-slot="apply-patch-filename"]')).toHaveCount(shape.files)
|
||||
await expect(page.locator('[data-component="file"]')).toHaveCount(0)
|
||||
|
||||
return Number(await page.getByTestId("mount-ms").textContent())
|
||||
}
|
||||
|
||||
const cold = await mount()
|
||||
|
||||
const counters = await page.evaluate(() =>
|
||||
Object.fromEntries(
|
||||
["patchFileGroups", "normalize", "completePatchContents", "diffLines"].map((name) => [
|
||||
name,
|
||||
performance.getEntriesByName(`patch-counter:${name}`).length,
|
||||
]),
|
||||
),
|
||||
)
|
||||
|
||||
await page.getByRole("button", { name: "Unmount tools", exact: true }).click()
|
||||
await expect(page.locator('[data-component="apply-patch-tool"]')).toHaveCount(0)
|
||||
await page.evaluate(() => performance.clearMarks())
|
||||
const warm = await mount()
|
||||
|
||||
const warmCounters = await page.evaluate(() =>
|
||||
Object.fromEntries(
|
||||
["patchFileGroups", "normalize", "completePatchContents", "diffLines"].map((name) => [
|
||||
name,
|
||||
performance.getEntriesByName(`patch-counter:${name}`).length,
|
||||
]),
|
||||
),
|
||||
)
|
||||
|
||||
const file = page.locator('[data-scope="apply-patch"] button').filter({ hasText: "edit.ts" })
|
||||
await expect(file).toHaveAttribute("aria-expanded", "false")
|
||||
await file.click()
|
||||
await expect(file).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(page.getByTestId("rendered")).not.toHaveText("0")
|
||||
await expect(page.locator('[data-component="file"]')).toBeVisible()
|
||||
const expansion = Number(await page.getByTestId("rendered").textContent())
|
||||
|
||||
const grouping = await page.evaluate(() => ({
|
||||
collapsed: window.patchBenchmark.grouping(false),
|
||||
expanded: window.patchBenchmark.grouping(true),
|
||||
}))
|
||||
|
||||
expect(grouping.collapsed.groups).toBe(shape.files)
|
||||
report(
|
||||
{ cold, warm, expansion, grouping, counters, warmCounters },
|
||||
{ scenario, ...shape, scope: "production tool components" },
|
||||
)
|
||||
|
||||
if (process.env.PATCH_SCREENSHOTS === "1") {
|
||||
await page.screenshot({ path: info.outputPath(`${scenario}-expanded.png`) })
|
||||
await file.click()
|
||||
await expect(file).toHaveAttribute("aria-expanded", "false")
|
||||
await page
|
||||
.locator('[data-component="apply-patch-tool"]')
|
||||
.screenshot({ path: info.outputPath(`${scenario}-collapsed.png`) })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
import { defineConfig } from "@playwright/test"
|
||||
|
||||
const baseURL = `http://127.0.0.1:${process.env.PATCH_PORT ?? 4317}`
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
testMatch: "*.bench.ts",
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
timeout: 60_000,
|
||||
outputDir: process.env.PATCH_RESULTS_DIR,
|
||||
reporter: "line",
|
||||
use: { baseURL, viewport: { width: 1366, height: 768 }, colorScheme: "light" },
|
||||
webServer: {
|
||||
command: "bun serve.ts",
|
||||
url: baseURL,
|
||||
reuseExistingServer: false,
|
||||
},
|
||||
})
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import path from "node:path"
|
||||
|
||||
const directory = process.env.PATCH_BUILD_DIR
|
||||
|
||||
if (!directory) throw new Error("PATCH_BUILD_DIR is required")
|
||||
|
||||
Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: Number(process.env.PATCH_PORT ?? 4317),
|
||||
async fetch(request) {
|
||||
const pathname = new URL(request.url).pathname
|
||||
const file = Bun.file(path.join(directory, pathname === "/" ? "index.html" : pathname))
|
||||
|
||||
return (await file.exists()) ? new Response(file) : new Response("Not found", { status: 404 })
|
||||
},
|
||||
})
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
import { defineConfig } from "vite"
|
||||
import solid from "vite-plugin-solid"
|
||||
import tailwindcss from "@tailwindcss/vite"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { execFileSync } from "node:child_process"
|
||||
import path from "node:path"
|
||||
|
||||
export default defineConfig({
|
||||
root: fileURLToPath(new URL(".", import.meta.url)),
|
||||
publicDir: fileURLToPath(new URL("../../../public", import.meta.url)),
|
||||
plugins: [
|
||||
solid(),
|
||||
tailwindcss(),
|
||||
{
|
||||
name: "patch-group-counters",
|
||||
enforce: "pre",
|
||||
load(id) {
|
||||
if (!process.env.PATCH_REVISION) return
|
||||
const root = fileURLToPath(new URL("../../../../..", import.meta.url))
|
||||
const file = path.relative(root, id).replaceAll("\\", "/")
|
||||
|
||||
if (
|
||||
![
|
||||
"packages/session-ui/src/components/apply-patch-file.ts",
|
||||
"packages/session-ui/src/tools/tool-renderer.tsx",
|
||||
].includes(file)
|
||||
)
|
||||
return
|
||||
|
||||
return execFileSync("git", ["show", `${process.env.PATCH_REVISION}:${file}`], { cwd: root, encoding: "utf8" })
|
||||
},
|
||||
transform(code, id) {
|
||||
if (process.env.PATCH_COUNTERS !== "1") return
|
||||
|
||||
const functions = id.replaceAll("\\", "/").endsWith("/apply-patch-file.ts")
|
||||
? ["patchFileGroups"]
|
||||
: id.replaceAll("\\", "/").endsWith("/session-diff.ts")
|
||||
? ["normalize", "completePatchContents"]
|
||||
: id.replaceAll("\\", "/").endsWith("/diff/line.js")
|
||||
? ["diffLines"]
|
||||
: []
|
||||
|
||||
for (const name of functions) {
|
||||
const pattern = new RegExp(`(export function ${name}\\([^)]*\\)[^{]*\\{)`)
|
||||
|
||||
if (!pattern.test(code)) throw new Error(`Missing instrumented function ${name} in ${id}`)
|
||||
code = code.replace(pattern, `$1 performance.mark("patch-counter:${name}");`)
|
||||
}
|
||||
|
||||
return functions.length ? { code, map: null } : undefined
|
||||
},
|
||||
},
|
||||
],
|
||||
resolve: { dedupe: ["solid-js", "@solidjs/meta"] },
|
||||
worker: { format: "es" },
|
||||
build: { outDir: process.env.PATCH_BUILD_DIR, emptyOutDir: true, sourcemap: true },
|
||||
})
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
import config from "../../playwright.config"
|
||||
|
||||
const port = Number(process.env.PLAYWRIGHT_PORT ?? 3000)
|
||||
|
||||
process.env.PLAYWRIGHT_SERVER_PORT = new URL(process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${port}`).port || "80"
|
||||
|
||||
process.env.OPENCODE_PERFORMANCE_RUN_ID ??= `${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`
|
||||
|
||||
export default {
|
||||
...config,
|
||||
testDir: ".",
|
||||
testIgnore: ["unit/**", "devex/**"],
|
||||
outputDir: "../test-results/performance",
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
reporter: [["html", { outputFolder: "../playwright-report/performance", open: "never" }], ["line"]],
|
||||
webServer: config.webServer
|
||||
? {
|
||||
...config.webServer,
|
||||
command: `bun run build && bun run serve -- --host 0.0.0.0 --port ${port} --strictPort`,
|
||||
reuseExistingServer: false,
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
import config from "./playwright.config"
|
||||
|
||||
export default {
|
||||
...config,
|
||||
outputDir: "../test-results/performance-uncapped",
|
||||
reporter: [["html", { outputFolder: "../playwright-report/performance-uncapped", open: "never" }], ["line"]],
|
||||
use: {
|
||||
...config.use,
|
||||
launchOptions: {
|
||||
args: ["--disable-frame-rate-limit", "--disable-gpu-vsync"],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
import type { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult } from "@playwright/test/reporter"
|
||||
import { mkdir, writeFile } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
|
||||
type BenchmarkRecord = {
|
||||
status?: string
|
||||
metrics?: { firstCorrectObservedMs?: unknown; stableObservedMs?: unknown } | null
|
||||
}
|
||||
|
||||
export default class TabSwitchReporter implements Reporter {
|
||||
private output = ""
|
||||
private tests: TestCase[] = []
|
||||
private results: { test: TestCase; status: TestResult["status"]; records: string[] }[] = []
|
||||
|
||||
onBegin(config: FullConfig, suite: Suite) {
|
||||
this.output = config.projects[0].outputDir
|
||||
this.tests = suite.allTests()
|
||||
}
|
||||
|
||||
onTestEnd(test: TestCase, result: TestResult) {
|
||||
this.results.push({
|
||||
test,
|
||||
status: result.status,
|
||||
records: Buffer.concat(result.stdout.map((chunk) => (typeof chunk === "string" ? Buffer.from(chunk) : chunk)))
|
||||
.toString("utf8")
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.startsWith("BENCHMARK "))
|
||||
.map((line) => line.slice("BENCHMARK ".length)),
|
||||
})
|
||||
}
|
||||
|
||||
async onEnd(result: FullResult) {
|
||||
const file = path.join(this.output, "tab-switch-benchmark.jsonl")
|
||||
|
||||
try {
|
||||
await mkdir(this.output, { recursive: true })
|
||||
await writeFile(file, this.results.flatMap((entry) => entry.records.map((raw) => `${raw}\n`)).join(""), "utf8")
|
||||
} catch (error) {
|
||||
console.error("Could not save tab-switch benchmark records:", error)
|
||||
|
||||
return { status: "failed" as const }
|
||||
}
|
||||
|
||||
console.log(`\nTab-switch benchmark: ${result.status}`)
|
||||
Array.from(new Set(this.tests.map((test) => test.title))).forEach((name) => {
|
||||
const results = this.results.filter((entry) => entry.test.title === name)
|
||||
|
||||
const unrun = this.tests.filter(
|
||||
(test) => test.title === name && !results.some((entry) => entry.test.id === test.id),
|
||||
).length
|
||||
|
||||
const records = results.flatMap((entry) =>
|
||||
entry.records.map((raw) => {
|
||||
try {
|
||||
return { status: entry.status, record: JSON.parse(raw) as BenchmarkRecord | null }
|
||||
} catch {
|
||||
return { status: entry.status, record: { status: "invalid JSON", metrics: null } }
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
const passed = records.filter((entry) => entry.status === "passed" && entry.record?.status === "passed")
|
||||
|
||||
const valid = passed
|
||||
.map((entry) => ({
|
||||
firstCorrectObservedMs: entry.record?.metrics?.firstCorrectObservedMs,
|
||||
stableObservedMs: entry.record?.metrics?.stableObservedMs,
|
||||
}))
|
||||
.filter(
|
||||
(metrics): metrics is { firstCorrectObservedMs: number; stableObservedMs: number } =>
|
||||
typeof metrics.firstCorrectObservedMs === "number" &&
|
||||
Number.isFinite(metrics.firstCorrectObservedMs) &&
|
||||
typeof metrics.stableObservedMs === "number" &&
|
||||
Number.isFinite(metrics.stableObservedMs),
|
||||
)
|
||||
|
||||
console.log(`\n${name}`)
|
||||
console.log(` Tests: ${counts(results.map((entry) => entry.status))}; unrun=${unrun}`)
|
||||
console.log(
|
||||
` Records: ${counts(records.map((entry) => entry.record?.status ?? "missing status"))}; ` +
|
||||
`missing=${results.filter((entry) => entry.records.length === 0).length + unrun}; ` +
|
||||
`excluded=${records.length - valid.length}; invalid metrics=${passed.length - valid.length}`,
|
||||
)
|
||||
;(["firstCorrectObservedMs", "stableObservedMs"] as const).forEach((metric) => {
|
||||
const values = valid.map((entry) => entry[metric]).sort((a, b) => a - b)
|
||||
|
||||
if (values.length === 0) {
|
||||
console.log(` ${metric}: n=0, median=n/a, p95=n/a`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const median = (values[Math.floor((values.length - 1) / 2)] + values[Math.floor(values.length / 2)]) / 2
|
||||
const p95 = values[Math.ceil(values.length * 0.95) - 1]
|
||||
console.log(` ${metric}: n=${values.length}, median=${median.toFixed(2)} ms, p95=${p95.toFixed(2)} ms`)
|
||||
})
|
||||
})
|
||||
console.log(`\nRaw BENCHMARK records: ${file}`)
|
||||
}
|
||||
}
|
||||
|
||||
function counts(statuses: string[]) {
|
||||
return (
|
||||
Array.from(new Set(statuses))
|
||||
.map((status) => `${status}=${statuses.filter((value) => value === status).length}`)
|
||||
.join(", ") || "none"
|
||||
)
|
||||
}
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
import path from "node:path"
|
||||
import { parseArgs } from "node:util"
|
||||
import { createMockServerHandler } from "../utils/mock-server"
|
||||
import { fixture } from "../utils/session-fixture"
|
||||
import { messages } from "../utils/markdown-sessions"
|
||||
import { createReviewDiffs } from "./timeline/timeline-test-helpers"
|
||||
|
||||
const args = parseArgs({
|
||||
args: Bun.argv.slice(2),
|
||||
options: { port: { type: "string", default: "4639" }, dist: { type: "string", default: "dist" } },
|
||||
})
|
||||
|
||||
const directory = path.resolve(args.values.dist)
|
||||
|
||||
const api = createMockServerHandler({
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
provider: fixture.provider,
|
||||
sessions: fixture.sessions,
|
||||
pageMessages: (sessionID) => ({ items: messages[sessionID] ?? [] }),
|
||||
vcsDiff: createReviewDiffs(),
|
||||
})
|
||||
|
||||
const server = Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: Number(args.values.port),
|
||||
idleTimeout: 0,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
|
||||
if (url.pathname === "/api/event") {
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(
|
||||
new TextEncoder().encode('data: {"id":"evt_fixture_connected","type":"server.connected","data":{}}\n\n'),
|
||||
)
|
||||
},
|
||||
}),
|
||||
{ headers: { "content-type": "text/event-stream", "cache-control": "no-store" } },
|
||||
)
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith("/api/")) {
|
||||
const response = await api.handler(request)
|
||||
response.headers.set("cache-control", "no-store")
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
const file = Bun.file(path.join(directory, url.pathname))
|
||||
|
||||
if (!url.pathname.endsWith("/") && (await file.exists())) {
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
"cache-control": url.pathname.startsWith("/_assets/") ? "public, max-age=31536000, immutable" : "no-cache",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(Bun.file(path.join(directory, "index.html")), { headers: { "cache-control": "no-cache" } })
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`Tab fixture: ${server.url} (${directory})`)
|
||||
|
||||
const close = async () => {
|
||||
await server.stop(true)
|
||||
await api.dispose()
|
||||
}
|
||||
|
||||
process.once("SIGINT", close)
|
||||
|
||||
process.once("SIGTERM", close)
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import config from "../playwright.config"
|
||||
|
||||
export default {
|
||||
...config,
|
||||
testDir: ".",
|
||||
testMatch: "**/*.spec.ts",
|
||||
outputDir: "../../test-results/timeline-stability",
|
||||
reporter: [["html", { outputFolder: "../../playwright-report/timeline-stability", open: "never" }], ["line"]],
|
||||
retries: 0,
|
||||
workers: 1,
|
||||
use: {
|
||||
...config.use,
|
||||
trace: "retain-on-failure",
|
||||
screenshot: "only-on-failure",
|
||||
video: "retain-on-failure",
|
||||
},
|
||||
}
|
||||
|
|
@ -1,227 +0,0 @@
|
|||
import { base64Encode } from "@opencode/util/encode"
|
||||
import { benchmark, benchmarkDiagnostics, expect } from "../benchmark"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { fixture } from "../../utils/session-fixture"
|
||||
|
||||
const sessionID = "ses_composer_write_batch"
|
||||
|
||||
const title = "Composer persistence workload"
|
||||
|
||||
const addition = " Keep the existing error handling and add coverage."
|
||||
|
||||
const text =
|
||||
Array.from(
|
||||
{ length: 180 },
|
||||
(_, index) =>
|
||||
`Review requirement ${index + 1}: preserve request ordering in src/queue/worker-${index % 12}.ts. ` +
|
||||
`A failed request must retain its payload, report its cause, and remain safe to retry.\n` +
|
||||
`Expected: await queue.flush(); expect(await repository.read(id)).toEqual(accepted);\n`,
|
||||
).join("") + "Implementation notes:"
|
||||
|
||||
const items = Array.from({ length: 8 }, (_, index) => ({
|
||||
type: "file",
|
||||
path: `src/queue/worker-${index}.ts`,
|
||||
selection: { startLine: 10, startChar: 0, endLine: 24, endChar: 0 },
|
||||
commentID: `composer-write-batch-${index}`,
|
||||
comment: `Check retry path ${index}: keep the original request identity and error cause.`,
|
||||
preview: Array.from(
|
||||
{ length: 24 },
|
||||
(_, line) => ` const request${line} = await repository.loadPending("queue-${index}");`,
|
||||
).join("\n"),
|
||||
}))
|
||||
|
||||
const document = {
|
||||
prompt: [{ type: "text", content: text, start: 0, end: text.length }],
|
||||
cursor: text.length,
|
||||
mode: "normal",
|
||||
context: { items },
|
||||
}
|
||||
|
||||
type Probe = { active: boolean; encodes: number; bytes: number; inputs: number; keyups: number }
|
||||
|
||||
type ProbeWindow = typeof window & { composerWriteBatch: Probe }
|
||||
|
||||
benchmark.use({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
video: "off",
|
||||
trace: "off",
|
||||
serviceWorkers: "block",
|
||||
traceScope: "interaction",
|
||||
})
|
||||
|
||||
for (const scenario of ["typing", "cursor-movement", "cursor-noop", "submit-cleanup"] as const) {
|
||||
benchmark(`composer-write-batch: ${scenario}`, async ({ page, report }, testInfo) => {
|
||||
const submitted: Record<string, unknown>[] = []
|
||||
await mockOpenCodeServer(page, {
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
provider: fixture.provider,
|
||||
sessions: [{ ...fixture.sessions[0], id: sessionID, title }],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
onPrompt: (input) => submitted.push(input.body),
|
||||
})
|
||||
await page.addInitScript(
|
||||
({ key, value, counts }) => {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
|
||||
const probe: Probe = { active: false, encodes: 0, bytes: 0, inputs: 0, keyups: 0 }
|
||||
|
||||
;(window as ProbeWindow).composerWriteBatch = probe
|
||||
|
||||
// The draft adapter parses each schema-encoded composer document once before
|
||||
// its asynchronous blob walk. Count at this boundary, not at the IDB write
|
||||
// (which already discards superseded writes). This fixture is ASCII only.
|
||||
if (counts) {
|
||||
const parse = JSON.parse
|
||||
JSON.parse = (value, reviver) => {
|
||||
if (probe.active && typeof value === "string" && value.startsWith('{"prompt":[')) {
|
||||
probe.encodes++
|
||||
probe.bytes += value.length
|
||||
}
|
||||
|
||||
return parse(value, reviver)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("input", (event) => {
|
||||
if (
|
||||
probe.active &&
|
||||
event.target instanceof Element &&
|
||||
event.target.matches('[data-component="composer-editor"]')
|
||||
)
|
||||
probe.inputs++
|
||||
})
|
||||
window.addEventListener("keyup", (event) => {
|
||||
if (
|
||||
probe.active &&
|
||||
event.target instanceof Element &&
|
||||
event.target.matches('[data-component="composer-editor"]')
|
||||
)
|
||||
probe.keyups++
|
||||
})
|
||||
},
|
||||
{
|
||||
key: `${base64Encode(fixture.directory)}/prompt/${sessionID}.v2`,
|
||||
value: document,
|
||||
counts: process.env.OPENCODE_PERSISTENCE_COUNTS === "1",
|
||||
},
|
||||
)
|
||||
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
|
||||
await expectSessionTitle(page, title)
|
||||
const editor = page.getByRole("textbox", { name: "Prompt", exact: true })
|
||||
await expect(editor).toBeEditable()
|
||||
await expect(editor).toHaveText(text)
|
||||
await editor.focus()
|
||||
await editor.press("ControlOrMeta+End")
|
||||
await page.evaluate(() => window.document.fonts.ready)
|
||||
|
||||
const stored = async () =>
|
||||
page.evaluate(async (sessionID) => {
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open("opencode-drafts", 1)
|
||||
request.onsuccess = () => resolve(request.result)
|
||||
request.onerror = () => reject(request.error)
|
||||
})
|
||||
|
||||
try {
|
||||
const transaction = db.transaction("documents")
|
||||
const keys = transaction.objectStore("documents").getAllKeys()
|
||||
const values = transaction.objectStore("documents").getAll()
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve()
|
||||
transaction.onerror = () => reject(transaction.error)
|
||||
})
|
||||
const index = keys.result.findIndex((key) => String(key).endsWith(`session:${sessionID}:prompt`))
|
||||
// Parse after disabling the count so the observation is not part of it.
|
||||
const probe = (window as ProbeWindow).composerWriteBatch
|
||||
const active = probe.active
|
||||
probe.active = false
|
||||
const value = index < 0 ? undefined : JSON.parse(values.result[index])
|
||||
probe.active = active
|
||||
|
||||
return value as { prompt: { content: string }[]; cursor: number; context: { items: unknown[] } } | undefined
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}, sessionID)
|
||||
|
||||
await expect.poll(async () => (await stored())?.cursor).toBe(text.length)
|
||||
expect((await stored())?.context.items).toHaveLength(items.length)
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
await benchmarkDiagnostics(page).startTrace()
|
||||
const before = await cdp.send("Performance.getMetrics")
|
||||
await page.evaluate(() => {
|
||||
;(window as ProbeWindow).composerWriteBatch.active = true
|
||||
performance.mark("composer-write-batch-start")
|
||||
})
|
||||
const start = performance.now()
|
||||
|
||||
if (scenario === "typing") await editor.pressSequentially(addition)
|
||||
|
||||
if (scenario === "cursor-movement") await editor.press("ArrowLeft")
|
||||
|
||||
if (scenario === "cursor-noop") await editor.press("ArrowRight")
|
||||
|
||||
if (scenario === "submit-cleanup") await editor.press("Enter")
|
||||
const expectedText = scenario === "typing" ? text + addition : scenario === "submit-cleanup" ? "" : text
|
||||
|
||||
const expectedCursor =
|
||||
scenario === "typing"
|
||||
? text.length + addition.length
|
||||
: scenario === "submit-cleanup"
|
||||
? 0
|
||||
: text.length - Number(scenario === "cursor-movement")
|
||||
|
||||
await expect(editor).toHaveText(expectedText)
|
||||
await expect.poll(async () => (await stored())?.cursor).toBe(expectedCursor)
|
||||
const elapsedMs = performance.now() - start
|
||||
const after = await cdp.send("Performance.getMetrics")
|
||||
|
||||
const probe = await page.evaluate(() => {
|
||||
performance.mark("composer-write-batch-end")
|
||||
const probe = (window as ProbeWindow).composerWriteBatch
|
||||
probe.active = false
|
||||
|
||||
return probe
|
||||
})
|
||||
|
||||
expect((await stored())?.prompt.map((part) => part.content).join("")).toBe(expectedText)
|
||||
|
||||
if (scenario === "submit-cleanup") {
|
||||
await expect.poll(() => submitted.length).toBe(1)
|
||||
expect(submitted[0].text).toContain(text)
|
||||
expect((await stored())?.context.items).toHaveLength(0)
|
||||
}
|
||||
|
||||
expect(probe.keyups).toBe(scenario === "typing" ? addition.length : 1)
|
||||
expect(probe.inputs).toBe(scenario === "typing" ? addition.length : 0)
|
||||
|
||||
const metric = (name: string) =>
|
||||
1000 *
|
||||
((after.metrics.find((x) => x.name === name)?.value ?? 0) -
|
||||
(before.metrics.find((x) => x.name === name)?.value ?? 0))
|
||||
|
||||
report(
|
||||
{ elapsedMs, taskMs: metric("TaskDuration"), scriptMs: metric("ScriptDuration"), ...probe },
|
||||
{
|
||||
scenario,
|
||||
promptBytes: Buffer.byteLength(text),
|
||||
contextItems: items.length,
|
||||
persistedBytes: Buffer.byteLength(JSON.stringify(document)),
|
||||
typedCharacters: scenario === "typing" ? addition.length : 0,
|
||||
counts: process.env.OPENCODE_PERSISTENCE_COUNTS === "1",
|
||||
browser: page.context().browser()!.version(),
|
||||
build: process.env.OPENCODE_PERSISTENCE_BUILD,
|
||||
transport: "playwright-route",
|
||||
completion: "editor text and committed IDB cursor",
|
||||
},
|
||||
)
|
||||
await benchmarkDiagnostics(page).stop()
|
||||
await cdp.detach()
|
||||
|
||||
if (testInfo.repeatEachIndex === 0) await page.screenshot({ path: testInfo.outputPath(`${scenario}.png`) })
|
||||
})
|
||||
}
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
import { measureFirstNavigation } from "./first-navigation-probe"
|
||||
import {
|
||||
fixture,
|
||||
installStressSessionTabs,
|
||||
installTimelineSettings,
|
||||
mockStressTimeline,
|
||||
} from "../../utils/session-fixture"
|
||||
import { draftHref, sessionHref } from "../../utils/app"
|
||||
import { waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
const contentSelector = '[data-message-id], [data-component="composer-editor"]'
|
||||
|
||||
const draftID = "draft_first_navigation"
|
||||
|
||||
benchmark.describe("performance: first navigation paint", () => {
|
||||
benchmark("opens an unvisited session tab without a blank frame", async ({ page, report }) => {
|
||||
await setup(page)
|
||||
const href = sessionHref(fixture.targetID)
|
||||
|
||||
const result = await measureFirstNavigation(page, {
|
||||
href,
|
||||
destinationPath: href,
|
||||
sourceSelector: messageSelector(fixture.expected.sourceMessageIDs.at(-1)!),
|
||||
destinationSelector: messageSelector(fixture.expected.targetMessageIDs.at(-1)!),
|
||||
contentSelector,
|
||||
navigate: async () => {
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${href}"]`).first().click()
|
||||
await expectSessionTitle(page, fixture.expected.targetTitle)
|
||||
},
|
||||
})
|
||||
|
||||
report(result)
|
||||
expect(result.summary.blankSamples).toBe(0)
|
||||
expect(result.summary.unknownSamples).toBe(0)
|
||||
})
|
||||
|
||||
benchmark("opens the new session page before its lazy module is used", async ({ page, report }) => {
|
||||
await setup(page, draftID)
|
||||
const href = draftHref(draftID)
|
||||
|
||||
const result = await measureFirstNavigation(page, {
|
||||
href,
|
||||
destinationPath: href,
|
||||
sourceSelector: messageSelector(fixture.expected.sourceMessageIDs.at(-1)!),
|
||||
destinationSelector: '[data-component="composer-editor"]',
|
||||
contentSelector,
|
||||
navigate: async () => {
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${href}"]`).first().click()
|
||||
await expect(page.locator('[data-component="composer-editor"]')).toBeVisible()
|
||||
},
|
||||
})
|
||||
|
||||
report(result)
|
||||
expect(result.summary.blankSamples).toBe(0)
|
||||
expect(result.summary.unknownSamples).toBe(0)
|
||||
})
|
||||
|
||||
benchmark("opens a session from the new session page without a blank frame", async ({ page, report }) => {
|
||||
await mockStressTimeline(page)
|
||||
await installTimelineSettings(page)
|
||||
await installStressSessionTabs(page, { draftID })
|
||||
await page.goto("/")
|
||||
|
||||
const draftLink = draftHref(draftID)
|
||||
const draftTab = page.locator(`[data-slot="titlebar-tabs"] a[href="${draftLink}"]`)
|
||||
await expect(draftTab).toHaveCount(1)
|
||||
await draftTab.click()
|
||||
await expect(page.locator('[data-component="new-session"]')).toBeVisible()
|
||||
|
||||
const href = sessionHref(fixture.targetID)
|
||||
const sessionTab = page.locator(`[data-slot="titlebar-tabs"] a[href="${href}"]`)
|
||||
await expect(sessionTab).toHaveCount(1)
|
||||
|
||||
const result = await measureFirstNavigation(page, {
|
||||
href,
|
||||
destinationPath: href,
|
||||
sourceSelector: '[data-component="new-session"]',
|
||||
destinationSelector: messageSelector(fixture.expected.targetMessageIDs.at(-1)!),
|
||||
contentSelector,
|
||||
navigate: async () => {
|
||||
await sessionTab.click()
|
||||
await expectSessionTitle(page, fixture.expected.targetTitle)
|
||||
},
|
||||
})
|
||||
|
||||
report(result)
|
||||
expect(result.summary.blankSamples).toBe(0)
|
||||
expect(result.summary.unknownSamples).toBe(0)
|
||||
})
|
||||
|
||||
benchmark("opens a child session without a blank frame", async ({ page, report }) => {
|
||||
await setup(page)
|
||||
const href = sessionHref(fixture.childID)
|
||||
|
||||
const result = await measureFirstNavigation(page, {
|
||||
href,
|
||||
destinationPath: href,
|
||||
sourceSelector: messageSelector(fixture.expected.sourceMessageIDs.at(-1)!),
|
||||
destinationSelector: messageSelector(fixture.expected.childMessageIDs.at(-1)!),
|
||||
contentSelector,
|
||||
navigate: async () => {
|
||||
await page.locator(`a[href="${href}"]`, { has: page.locator('[data-component="task-tool-card"]') }).click()
|
||||
await expectSessionTitle(page, fixture.expected.childTitle)
|
||||
},
|
||||
})
|
||||
|
||||
report(result)
|
||||
expect(result.summary.blankSamples).toBe(0)
|
||||
expect(result.summary.unknownSamples).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
async function setup(page: Parameters<typeof mockStressTimeline>[0], draft?: string) {
|
||||
await mockStressTimeline(page)
|
||||
await installTimelineSettings(page)
|
||||
await installStressSessionTabs(page, draft ? { draftID: draft } : undefined)
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
}
|
||||
|
||||
function messageSelector(id: string) {
|
||||
return `[data-message-id="${id}"]`
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
export type FirstNavigationSample = {
|
||||
observedAtMs: number
|
||||
source: boolean
|
||||
destination: boolean
|
||||
content: boolean
|
||||
pathname?: string
|
||||
center?: string
|
||||
}
|
||||
|
||||
function category(sample: FirstNavigationSample) {
|
||||
if (sample.destination && !sample.source) return "destination"
|
||||
|
||||
if (sample.source && !sample.destination) return "source"
|
||||
|
||||
if (!sample.content) return "blank"
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
export function summarizeFirstNavigation(samples: FirstNavigationSample[]) {
|
||||
const categories = samples.map(category)
|
||||
|
||||
const stable = categories.findIndex(
|
||||
(value, index) =>
|
||||
value === "destination" && categories[index + 1] === "destination" && categories[index + 2] === "destination",
|
||||
)
|
||||
|
||||
return {
|
||||
samples: samples.length,
|
||||
firstDestinationObservedMs: samples[categories.indexOf("destination")]?.observedAtMs ?? null,
|
||||
stableDestinationObservedMs: stable === -1 ? null : samples[stable + 2]!.observedAtMs,
|
||||
sourceSamples: categories.filter((value) => value === "source").length,
|
||||
blankSamples: categories.filter((value) => value === "blank").length,
|
||||
unknownSamples: categories.filter((value) => value === "unknown").length,
|
||||
destinationSamples: categories.filter((value) => value === "destination").length,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import { summarizeFirstNavigation, type FirstNavigationSample } from "./first-navigation-metrics"
|
||||
|
||||
type FirstNavigationProbe = {
|
||||
samples: FirstNavigationSample[]
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
export async function measureFirstNavigation(
|
||||
page: Page,
|
||||
input: {
|
||||
href: string
|
||||
destinationPath: string
|
||||
sourceSelector: string
|
||||
destinationSelector: string
|
||||
contentSelector: string
|
||||
navigate: () => Promise<void>
|
||||
},
|
||||
) {
|
||||
await page.evaluate(
|
||||
({ href, destinationPath, sourceSelector, destinationSelector, contentSelector }) => {
|
||||
const samples: FirstNavigationSample[] = []
|
||||
let started: number | undefined
|
||||
let running = true
|
||||
|
||||
const visible = (selector: string) =>
|
||||
[...document.querySelectorAll<HTMLElement>(selector)].some((element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
const style = getComputedStyle(element)
|
||||
|
||||
return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none"
|
||||
})
|
||||
|
||||
const sample = () => {
|
||||
if (!running || started === undefined) return
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
if (!running || started === undefined) return
|
||||
samples.push({
|
||||
observedAtMs: performance.now() - started,
|
||||
source: visible(sourceSelector),
|
||||
destination: `${location.pathname}${location.search}` === destinationPath && visible(destinationSelector),
|
||||
content: visible(contentSelector),
|
||||
pathname: `${location.pathname}${location.search}`,
|
||||
center: document.elementFromPoint(innerWidth / 2, innerHeight / 2)?.textContent?.slice(0, 80),
|
||||
})
|
||||
sample()
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
|
||||
document.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const link = event.target instanceof Element ? event.target.closest("a") : undefined
|
||||
|
||||
if (link?.getAttribute("href") !== href) return
|
||||
started = performance.now()
|
||||
sample()
|
||||
},
|
||||
{ capture: true, once: true },
|
||||
)
|
||||
;(window as Window & { __firstNavigationProbe?: FirstNavigationProbe }).__firstNavigationProbe = {
|
||||
samples,
|
||||
stop: () => {
|
||||
running = false
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
href: input.href,
|
||||
destinationPath: input.destinationPath,
|
||||
sourceSelector: input.sourceSelector,
|
||||
destinationSelector: input.destinationSelector,
|
||||
contentSelector: input.contentSelector,
|
||||
},
|
||||
)
|
||||
await input.navigate()
|
||||
await page.waitForFunction(() => {
|
||||
const samples = (window as Window & { __firstNavigationProbe?: FirstNavigationProbe }).__firstNavigationProbe
|
||||
?.samples
|
||||
|
||||
if (!samples) return false
|
||||
|
||||
return samples.length >= 3 && samples.slice(-3).every((sample) => sample.destination && !sample.source)
|
||||
})
|
||||
|
||||
const samples = await page.evaluate(() => {
|
||||
const probe = (window as Window & { __firstNavigationProbe?: FirstNavigationProbe }).__firstNavigationProbe!
|
||||
probe.stop()
|
||||
|
||||
return probe.samples
|
||||
})
|
||||
|
||||
return { summary: summarizeFirstNavigation(samples), samples }
|
||||
}
|
||||
|
|
@ -1,351 +0,0 @@
|
|||
import type { CDPSession, Page } from "@playwright/test"
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { APP_READY_TIMEOUT } from "../../utils/waits"
|
||||
import { SERVER } from "../../utils/app"
|
||||
import { fixture as stress } from "../../utils/session-fixture"
|
||||
import { createHomeIndexFixture, type HomeIndexFixture } from "./home-session-index.fixture"
|
||||
|
||||
// Home fetches the root-session index on mount. These cases hold the visible
|
||||
// output constant (newest 64 rows, same order) while the index size grows, so
|
||||
// bytes, main-thread work, time to actionable rows, and retained heap can be
|
||||
// attributed to index handling rather than to what the user sees.
|
||||
const sizes = (process.env.HOME_INDEX_SIZES ?? "500,5000,10000").split(",").map(Number)
|
||||
|
||||
const churnSize = Number(process.env.HOME_INDEX_CHURN_SIZE ?? 10_000)
|
||||
|
||||
const updates = Number(process.env.HOME_INDEX_UPDATES ?? 20)
|
||||
|
||||
// Forced GC changes timing; retention runs stay separate from clean timing runs.
|
||||
const memory = process.env.OPENCODE_PERFORMANCE_MEMORY === "1"
|
||||
|
||||
const rowContainer = '[data-component="home-session-row-container"]'
|
||||
|
||||
const row = '[data-component="home-session-row"]'
|
||||
|
||||
type Probe = {
|
||||
expected: number
|
||||
rows?: number
|
||||
frame?: number
|
||||
pending: Record<string, string>
|
||||
titles: Record<string, number>
|
||||
}
|
||||
|
||||
type ProbeWindow = Window & {
|
||||
__homeIndexProbe?: Probe
|
||||
__mockServerStreams?: Record<string, { push: (payloads: unknown[]) => void }>
|
||||
}
|
||||
|
||||
// Interaction-scoped tracing keeps the page-lifetime Chrome trace off unless a
|
||||
// scenario starts one; service workers stay out of the renderer measurement.
|
||||
benchmark.use({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
video: "off",
|
||||
trace: "off",
|
||||
serviceWorkers: "block",
|
||||
traceScope: "interaction",
|
||||
})
|
||||
|
||||
benchmark.describe("performance: home session index", () => {
|
||||
for (const count of sizes) {
|
||||
benchmark(`loads home with ${count} root sessions`, async ({ page, report }, testInfo) => {
|
||||
benchmark.setTimeout(180_000)
|
||||
const fixture = createHomeIndexFixture({ count, now: Date.now() })
|
||||
const network = await setup(page, fixture)
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
|
||||
await page.goto("/")
|
||||
const rows = page.locator(row)
|
||||
await expect(rows).toHaveCount(fixture.expected.visible, { timeout: APP_READY_TIMEOUT })
|
||||
const first = page.locator(rowContainer).filter({ hasText: fixture.expected.newestTitle })
|
||||
await expect(first).toHaveAttribute("data-session-id", fixture.expected.newestID)
|
||||
await expect(first.locator(row)).toBeEnabled()
|
||||
// Row order is part of the held-constant output: the DOM must list the
|
||||
// newest session first.
|
||||
await expect(page.locator(rowContainer).nth(0)).toHaveAttribute("data-session-id", fixture.expected.newestID)
|
||||
|
||||
const probe = await readProbe(page)
|
||||
const metrics = await performanceMetrics(cdp)
|
||||
const retained = memory ? await retainedHeap(cdp) : undefined
|
||||
await network.settle()
|
||||
|
||||
if (testInfo.repeatEachIndex === 0) {
|
||||
const path = testInfo.outputPath(`home-${count}.png`)
|
||||
await page.screenshot({ path })
|
||||
await testInfo.attach(`home-${count}`, { path, contentType: "image/png" })
|
||||
}
|
||||
|
||||
report(
|
||||
{
|
||||
listRequests: network.list.requests,
|
||||
listBytes: network.list.bytes,
|
||||
rowsMs: probe.rows,
|
||||
frameMs: probe.frame,
|
||||
listEndMs: probe.listEnd,
|
||||
processMs: probe.rows - probe.listEnd,
|
||||
// ThreadTime is main-thread CPU time; ScriptDuration only covers
|
||||
// Blink-invoked callbacks, so promise continuations are missing from it.
|
||||
threadMs: metrics.ThreadTime * 1000,
|
||||
scriptMs: metrics.ScriptDuration * 1000,
|
||||
taskMs: metrics.TaskDuration * 1000,
|
||||
layoutMs: metrics.LayoutDuration * 1000,
|
||||
styleMs: metrics.RecalcStyleDuration * 1000,
|
||||
heapUsedMB: metrics.JSHeapUsedSize / 1_048_576,
|
||||
heapTotalMB: metrics.JSHeapTotalSize / 1_048_576,
|
||||
nodes: metrics.Nodes,
|
||||
...(retained ? { retainedHeapMB: retained.usedSize / 1_048_576, retainedNodes: retained.nodes } : {}),
|
||||
},
|
||||
{
|
||||
sessions: count,
|
||||
directories: fixture.directories.length,
|
||||
fixtureVersion: fixture.version,
|
||||
fixtureListBytes: fixture.listBytes,
|
||||
visibleRows: fixture.expected.visible,
|
||||
gc: memory ? "explicit" : "none",
|
||||
scope: "renderer main isolate; not total desktop RAM",
|
||||
},
|
||||
)
|
||||
expect(probe.rows).toBeGreaterThan(0)
|
||||
await cdp.detach()
|
||||
})
|
||||
}
|
||||
|
||||
benchmark(
|
||||
`applies ${updates} background session updates on home with ${churnSize} root sessions`,
|
||||
async ({ page, report }) => {
|
||||
benchmark.setTimeout(180_000)
|
||||
const fixture = createHomeIndexFixture({ count: churnSize, now: Date.now() })
|
||||
const target = fixture.sessions[fixture.sessions.length - 1]
|
||||
const network = await setup(page, fixture)
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
|
||||
// Home prefetches the two newest sessions, which makes them locally known
|
||||
// and therefore part of every later index merge, like an open session.
|
||||
const prefetch = page.waitForResponse(
|
||||
(response) => response.request().method() === "GET" && response.url().includes(`/api/session/${target.id}`),
|
||||
)
|
||||
|
||||
await page.goto("/")
|
||||
await expect(page.locator(row)).toHaveCount(fixture.expected.visible, { timeout: APP_READY_TIMEOUT })
|
||||
await prefetch
|
||||
|
||||
const titleLocator = page.locator(
|
||||
`${rowContainer}[data-session-id="${target.id}"] [data-component="home-session-title"]`,
|
||||
)
|
||||
|
||||
await expect(titleLocator).toHaveText(fixture.expected.newestTitle)
|
||||
|
||||
const before = await performanceMetrics(cdp)
|
||||
const samples: number[] = []
|
||||
|
||||
for (let index = 1; index <= updates; index++) {
|
||||
const title = `${fixture.expected.newestTitle} · update ${index}`
|
||||
// The completed run bumps the session's updated time and title on the
|
||||
// server; the client re-reads the session and re-merges the index.
|
||||
target.title = title
|
||||
target.time.updated += 1000
|
||||
target.time.idle = target.time.updated
|
||||
|
||||
const pushed = await page.evaluate(
|
||||
({ id, title, event, server }) => {
|
||||
const host = window as ProbeWindow
|
||||
const stream = host.__mockServerStreams?.[server]
|
||||
|
||||
if (!host.__homeIndexProbe || !stream) throw new Error("Missing Home index probe")
|
||||
host.__homeIndexProbe.pending[id] = title
|
||||
stream.push([event])
|
||||
|
||||
return performance.now()
|
||||
},
|
||||
{
|
||||
id: target.id,
|
||||
title,
|
||||
event: {
|
||||
id: `evt_home_update_${index}`,
|
||||
created: Date.now(),
|
||||
type: "session.execution.succeeded",
|
||||
data: { sessionID: target.id },
|
||||
},
|
||||
server: SERVER,
|
||||
},
|
||||
)
|
||||
|
||||
await expect(titleLocator).toHaveText(title)
|
||||
|
||||
const seen = await page.evaluate(({ title }) => (window as ProbeWindow).__homeIndexProbe?.titles[title], {
|
||||
title,
|
||||
})
|
||||
|
||||
if (seen === undefined) throw new Error(`Probe did not observe title: ${title}`)
|
||||
samples.push(seen - pushed)
|
||||
}
|
||||
|
||||
const after = await performanceMetrics(cdp)
|
||||
await network.settle()
|
||||
const sorted = samples.toSorted((a, b) => a - b)
|
||||
report(
|
||||
{
|
||||
updates,
|
||||
updateMs: sorted,
|
||||
updateMedianMs: median(sorted),
|
||||
updateP95Ms: sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.95) - 1)],
|
||||
threadMs: (after.ThreadTime - before.ThreadTime) * 1000,
|
||||
scriptMs: (after.ScriptDuration - before.ScriptDuration) * 1000,
|
||||
taskMs: (after.TaskDuration - before.TaskDuration) * 1000,
|
||||
layoutMs: (after.LayoutDuration - before.LayoutDuration) * 1000,
|
||||
sessionReads: network.get.requests,
|
||||
},
|
||||
{
|
||||
sessions: churnSize,
|
||||
directories: fixture.directories.length,
|
||||
fixtureVersion: fixture.version,
|
||||
event: "session.execution.succeeded",
|
||||
scope: "renderer main isolate; latency from event push to row title update",
|
||||
},
|
||||
)
|
||||
expect(samples).toHaveLength(updates)
|
||||
await cdp.detach()
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
async function setup(page: Page, fixture: HomeIndexFixture) {
|
||||
const primary = fixture.directories[0]
|
||||
await mockOpenCodeServer(page, {
|
||||
directory: primary.directory,
|
||||
project: {
|
||||
id: primary.projectID,
|
||||
worktree: primary.directory,
|
||||
vcs: "git",
|
||||
name: primary.name,
|
||||
time: { created: fixture.now - 400 * 86_400_000, updated: fixture.now },
|
||||
sandboxes: [],
|
||||
},
|
||||
sessions: fixture.sessions,
|
||||
pageMessages: () => ({ items: [] }),
|
||||
provider: stress.provider,
|
||||
})
|
||||
await page.addInitScript(
|
||||
({ projects }) => {
|
||||
localStorage.setItem(
|
||||
"opencode.global.dat:server",
|
||||
JSON.stringify({
|
||||
projects: { local: projects.map((worktree, index) => ({ worktree, expanded: index === 0 })) },
|
||||
lastProject: { local: projects[0] },
|
||||
}),
|
||||
)
|
||||
},
|
||||
{ projects: fixture.directories.filter((entry) => entry.project).map((entry) => entry.directory) },
|
||||
)
|
||||
await page.addInitScript(
|
||||
({ expected }) => {
|
||||
const host = window as ProbeWindow
|
||||
const probe: Probe = { expected, pending: {}, titles: {} }
|
||||
host.__homeIndexProbe = probe
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
if (probe.rows === undefined) {
|
||||
const count = document.querySelectorAll('[data-component="home-session-row"]').length
|
||||
|
||||
if (count >= probe.expected) {
|
||||
probe.rows = performance.now()
|
||||
requestAnimationFrame((time) => {
|
||||
probe.frame = time
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, title] of Object.entries(probe.pending)) {
|
||||
const element = document.querySelector(
|
||||
`[data-component="home-session-row-container"][data-session-id="${id}"] [data-component="home-session-title"]`,
|
||||
)
|
||||
|
||||
if (element?.textContent !== title) continue
|
||||
probe.titles[title] = performance.now()
|
||||
delete probe.pending[id]
|
||||
}
|
||||
})
|
||||
|
||||
// Init scripts run before <html> exists; the document node itself is always observable.
|
||||
observer.observe(document, { childList: true, subtree: true, characterData: true })
|
||||
},
|
||||
{ expected: fixture.expected.visible },
|
||||
)
|
||||
const list = { requests: 0, bytes: 0 }
|
||||
const get = { requests: 0, bytes: 0 }
|
||||
const pending: Promise<void>[] = []
|
||||
page.on("response", (response) => {
|
||||
const request = response.request()
|
||||
|
||||
if (request.method() !== "GET") return
|
||||
const url = new URL(response.url())
|
||||
const isList = url.pathname === "/api/session"
|
||||
const isGet = /^\/api\/session\/[^/]+$/.test(url.pathname)
|
||||
|
||||
if (!isList && !isGet) return
|
||||
const bucket = isList ? list : get
|
||||
bucket.requests += 1
|
||||
pending.push(
|
||||
response
|
||||
.body()
|
||||
.then((body) => {
|
||||
bucket.bytes += body.byteLength
|
||||
})
|
||||
.catch(() => {}),
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
list,
|
||||
get,
|
||||
settle: () => Promise.all(pending).then(() => {}),
|
||||
}
|
||||
}
|
||||
|
||||
async function readProbe(page: Page) {
|
||||
const probe = await page.evaluate(() => {
|
||||
const host = window as ProbeWindow
|
||||
|
||||
if (!host.__homeIndexProbe) throw new Error("Missing Home index probe")
|
||||
|
||||
// Resource timing marks when the last index page finished arriving, so
|
||||
// rows - listEnd isolates parse, merge, and render from transfer and boot.
|
||||
const listEnd = Math.max(
|
||||
0,
|
||||
...performance
|
||||
.getEntriesByType("resource")
|
||||
.filter((entry) => new URL(entry.name).pathname === "/api/session")
|
||||
.map((entry) => (entry as PerformanceResourceTiming).responseEnd),
|
||||
)
|
||||
|
||||
return { rows: host.__homeIndexProbe.rows, frame: host.__homeIndexProbe.frame, listEnd }
|
||||
})
|
||||
|
||||
if (probe.rows === undefined) throw new Error("Probe did not observe the expected Home rows")
|
||||
|
||||
return { rows: probe.rows, frame: probe.frame, listEnd: probe.listEnd }
|
||||
}
|
||||
|
||||
async function performanceMetrics(cdp: CDPSession) {
|
||||
const result = await cdp.send("Performance.getMetrics")
|
||||
|
||||
return Object.fromEntries(result.metrics.map((metric) => [metric.name, metric.value])) as Record<string, number>
|
||||
}
|
||||
|
||||
async function retainedHeap(cdp: CDPSession) {
|
||||
// GC is an explicit retained-heap measurement, not an application optimization or readiness wait.
|
||||
await cdp.send("HeapProfiler.collectGarbage")
|
||||
const heap = await cdp.send("Runtime.getHeapUsage")
|
||||
const dom = await cdp.send("Memory.getDOMCounters")
|
||||
|
||||
return { usedSize: heap.usedSize, nodes: dom.nodes }
|
||||
}
|
||||
|
||||
function median(sorted: number[]) {
|
||||
if (sorted.length === 0) return undefined
|
||||
const middle = Math.floor(sorted.length / 2)
|
||||
|
||||
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { measureNavigationMilestones } from "./navigation-milestones"
|
||||
import {
|
||||
fixture,
|
||||
installStressSessionTabs,
|
||||
installTimelineSettings,
|
||||
mockStressTimeline,
|
||||
} from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
const homeRow = '[data-component="home-session-row"]'
|
||||
|
||||
const homeShell = '[data-component="home-session-search"]'
|
||||
|
||||
benchmark.describe("performance: home and tab navigation", () => {
|
||||
benchmark("opens a home session and paints its titlebar tab", async ({ page, report }) => {
|
||||
await setup(page, [])
|
||||
await page.goto("/")
|
||||
const row = page.locator(homeRow).filter({ hasText: fixture.expected.targetTitle }).first()
|
||||
await expect(row).toBeVisible()
|
||||
const href = sessionHref(fixture.targetID)
|
||||
|
||||
const result = await measureNavigationMilestones(page, {
|
||||
triggerSelector: homeRow,
|
||||
milestones: {
|
||||
content: { selector: messageSelector(fixture.expected.targetMessageIDs.at(-1)!) },
|
||||
tab: { selector: `[data-slot="titlebar-tabs"] a[href="${href}"]` },
|
||||
},
|
||||
navigate: async () => {
|
||||
await row.click()
|
||||
await expectSessionTitle(page, fixture.expected.targetTitle)
|
||||
},
|
||||
})
|
||||
|
||||
report(result)
|
||||
await expect(page.locator(`[data-slot="titlebar-tabs"] a[href="${href}"]`)).toContainText(
|
||||
fixture.expected.targetTitle,
|
||||
)
|
||||
})
|
||||
|
||||
benchmark("stages the review body after cold session content", async ({ page, report }) => {
|
||||
await setup(page, [])
|
||||
await page.goto("/")
|
||||
const row = page.locator(homeRow).filter({ hasText: fixture.expected.targetTitle }).first()
|
||||
await expect(row).toBeVisible()
|
||||
|
||||
const result = await page.evaluate(
|
||||
({ rowSelector, title, contentSelector }) =>
|
||||
new Promise<{ contentBeforeReview: boolean; samples: number }>((resolve) => {
|
||||
let samples = 0
|
||||
|
||||
const sample = () => {
|
||||
samples++
|
||||
const content = !!document.querySelector(contentSelector)
|
||||
const review = !!document.querySelector('[data-component="session-review"]')
|
||||
|
||||
if (content && !review) {
|
||||
resolve({ contentBeforeReview: true, samples })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (content && review) {
|
||||
resolve({ contentBeforeReview: false, samples })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
}
|
||||
|
||||
const target = [...document.querySelectorAll<HTMLElement>(rowSelector)].find((item) =>
|
||||
item.textContent?.includes(title),
|
||||
)
|
||||
|
||||
if (!target) throw new Error(`Home session row not found: ${title}`)
|
||||
target.click()
|
||||
requestAnimationFrame(sample)
|
||||
}),
|
||||
{
|
||||
rowSelector: homeRow,
|
||||
title: fixture.expected.targetTitle,
|
||||
contentSelector: messageSelector(fixture.expected.targetMessageIDs.at(-1)!),
|
||||
},
|
||||
)
|
||||
|
||||
report(result)
|
||||
expect(result.contentBeforeReview).toBe(true)
|
||||
await expect(page.locator('[data-component="session-review"]')).toBeVisible()
|
||||
})
|
||||
|
||||
benchmark("closes the only session tab and paints home", async ({ page, report }) => {
|
||||
await setup(page, [fixture.sourceID])
|
||||
const href = sessionHref(fixture.sourceID)
|
||||
await page.goto(href)
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
const tab = page.locator(`[data-slot="titlebar-tabs"] a[href="${href}"]`).first()
|
||||
const close = tab.locator("..").locator('[data-component="icon-button-v2"]')
|
||||
await expect(close).toBeVisible()
|
||||
|
||||
const result = await measureNavigationMilestones(page, {
|
||||
triggerSelector: '[data-slot="titlebar-tabs"] [data-component="icon-button-v2"]',
|
||||
milestones: {
|
||||
home: { selector: homeShell },
|
||||
row: { selector: homeRow },
|
||||
tabRemoved: { selector: `[data-slot="titlebar-tabs"] a[href="${href}"]`, visible: false },
|
||||
},
|
||||
navigate: async () => {
|
||||
await close.click()
|
||||
await expect(page).toHaveURL("/")
|
||||
},
|
||||
})
|
||||
|
||||
report(result)
|
||||
})
|
||||
})
|
||||
|
||||
async function setup(page: Parameters<typeof mockStressTimeline>[0], sessionIDs: string[]) {
|
||||
await mockStressTimeline(page)
|
||||
await installTimelineSettings(page)
|
||||
await installStressSessionTabs(page, { sessionIDs })
|
||||
}
|
||||
|
||||
function messageSelector(id: string) {
|
||||
return `[data-message-id="${id}"]`
|
||||
}
|
||||
|
|
@ -1,185 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { fixture, installStressSessionTabs } from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { messages } from "../../utils/markdown-sessions"
|
||||
import { measureSessionSwitch, waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
const sessions = Array.from({ length: 8 }, (_, index) => ({
|
||||
...fixture.sessions[0],
|
||||
id: `ses_prefetch_${index}`,
|
||||
title: `Renderer review ${index}`,
|
||||
}))
|
||||
|
||||
// A normal first page, not the full-history response used by the tab-switch benchmark.
|
||||
const pages = Object.fromEntries(
|
||||
sessions.map((session) => [
|
||||
session.id,
|
||||
messages[fixture.targetID].slice(-20).map((message) => ({ ...message, id: `${message.id}_${session.id}` })),
|
||||
]),
|
||||
)
|
||||
|
||||
const workload = {
|
||||
sessions: sessions.length,
|
||||
messagesPerPage: 20,
|
||||
payloadBytes: Object.fromEntries(
|
||||
sessions.map((session) => [
|
||||
session.id,
|
||||
Buffer.byteLength(JSON.stringify({ data: pages[session.id].toReversed(), cursor: {} })),
|
||||
]),
|
||||
),
|
||||
partsPerPage: pages[sessions[0].id].reduce(
|
||||
(count, message) => count + (message.type === "assistant" ? message.content.length : 1),
|
||||
0,
|
||||
),
|
||||
events: 0,
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__prefetchBodies?: Record<string, number>
|
||||
}
|
||||
}
|
||||
|
||||
benchmark.use({ viewport: { width: 1440, height: 900 }, video: "off", trace: "off", serviceWorkers: "block" })
|
||||
|
||||
for (const close of [false, true]) {
|
||||
benchmark(
|
||||
`inactive tab prefetch: ${close ? "close before response" : "activate after restore"}`,
|
||||
async ({ page, report }, testInfo) => {
|
||||
const gate = Promise.withResolvers<void>()
|
||||
const reads: string[] = []
|
||||
const inboxReads: string[] = []
|
||||
const pending = new Set<string>()
|
||||
const concurrency = { peak: 0 }
|
||||
const mutations: string[] = []
|
||||
const errors: string[] = []
|
||||
page.on("pageerror", (error) => errors.push(error.message))
|
||||
page.on("response", (response) => {
|
||||
if (new URL(response.url()).pathname.startsWith("/api/") && !response.ok())
|
||||
errors.push(`HTTP ${response.status()}: ${response.url()}`)
|
||||
})
|
||||
page.on("request", (request) => {
|
||||
const path = new URL(request.url()).pathname
|
||||
|
||||
if (request.method() === "DELETE" || /\/(interrupt|prompt)$/.test(path)) mutations.push(request.url())
|
||||
const inbox = path.match(/^\/api\/session\/([^/]+)\/inbox$/)
|
||||
|
||||
if (request.method() === "GET" && inbox) inboxReads.push(inbox[1])
|
||||
})
|
||||
await page.addInitScript(() => {
|
||||
window.__prefetchBodies = {}
|
||||
const text = Response.prototype.text
|
||||
Response.prototype.text = async function () {
|
||||
const body = await text.call(this)
|
||||
|
||||
if (this.url) {
|
||||
const path = new URL(this.url).pathname
|
||||
window.__prefetchBodies![path] = (window.__prefetchBodies![path] ?? 0) + 1
|
||||
}
|
||||
|
||||
return body
|
||||
}
|
||||
})
|
||||
await mockOpenCodeServer(page, {
|
||||
...fixture,
|
||||
sessions,
|
||||
pageMessages: (id) => ({ items: pages[id] ?? [] }),
|
||||
beforeMessagesResponse: ({ sessionID }) => (sessionID === sessions[0].id ? Promise.resolve() : gate.promise),
|
||||
onMessages: ({ sessionID, phase }) => {
|
||||
if (phase === "end") return void pending.delete(sessionID)
|
||||
reads.push(sessionID)
|
||||
pending.add(sessionID)
|
||||
concurrency.peak = Math.max(concurrency.peak, pending.size)
|
||||
},
|
||||
})
|
||||
await installStressSessionTabs(page, { sessionIDs: sessions.map((session) => session.id) })
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
await page.goto(sessionHref(sessions[0].id))
|
||||
await expectSessionTitle(page, sessions[0].title)
|
||||
await waitForStableTimeline(page, pages[sessions[0].id].at(-2)!.id)
|
||||
// Every inactive tab's scheduled inbox request must finish. This gates on the
|
||||
// same production callback as prefetch, without a sleep or waiting for a removed read.
|
||||
await page.waitForFunction(
|
||||
(ids) => ids.every((id) => window.__prefetchBodies![`/api/session/${id}/inbox`] > 0),
|
||||
sessions.slice(1).map((session) => session.id),
|
||||
)
|
||||
const speculativeReads = reads.filter((id) => id !== sessions[0].id)
|
||||
const speculativeInboxReads = inboxReads.filter((id) => id !== sessions[0].id).length
|
||||
const closed = sessions.at(-1)!
|
||||
|
||||
if (close) {
|
||||
const tab = page
|
||||
.locator("[data-titlebar-tab-slot]")
|
||||
.filter({ has: page.locator(`a[href="${sessionHref(closed.id)}"]`) })
|
||||
|
||||
await tab.getByRole("button", { name: "Close tab", exact: true }).click()
|
||||
await expect(tab).toHaveCount(0)
|
||||
}
|
||||
|
||||
gate.resolve()
|
||||
await page.waitForFunction(
|
||||
(ids) => ids.every((id) => window.__prefetchBodies![`/api/session/${id}/message`] > 0),
|
||||
reads,
|
||||
)
|
||||
await expectSessionTitle(page, sessions[0].title)
|
||||
|
||||
const heap =
|
||||
process.env.OPENCODE_PERFORMANCE_MEMORY === "1"
|
||||
? await cdp.send("HeapProfiler.collectGarbage").then(() => cdp.send("Runtime.getHeapUsage"))
|
||||
: undefined
|
||||
|
||||
const task =
|
||||
(await cdp.send("Performance.getMetrics")).metrics.find((metric) => metric.name === "TaskDuration")!.value *
|
||||
1000
|
||||
|
||||
const before = reads.length
|
||||
const target = sessions[1]
|
||||
|
||||
const result = await measureSessionSwitch(page, {
|
||||
destinationIDs: pages[target.id].map((message) => message.id),
|
||||
sourceIDs: pages[sessions[0].id].map((message) => message.id),
|
||||
lastID: pages[target.id].at(-2)!.id,
|
||||
requiredPartID: `${pages[target.id].at(-1)!.id}:text:0`,
|
||||
href: sessionHref(target.id),
|
||||
switch: async () => {
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(target.id)}"]`).click()
|
||||
await expectSessionTitle(page, target.title)
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
page.locator(`[data-timeline-part-id="${pages[target.id].at(-1)!.id}:text:0"] [data-component="markdown"]`),
|
||||
).toHaveAttribute("data-markdown-ready", "")
|
||||
expect(result.firstCorrectObservedMs).not.toBeNull()
|
||||
expect(mutations).toEqual([])
|
||||
expect(errors).toEqual([])
|
||||
report(
|
||||
{
|
||||
speculativeReads: speculativeReads.length,
|
||||
speculativeInboxReads,
|
||||
speculativePayloadBytes: speculativeReads.reduce((bytes, id) => bytes + workload.payloadBytes[id], 0),
|
||||
peakMessageRequests: concurrency.peak,
|
||||
closedSessionReads: close ? reads.filter((id) => id === closed.id).length : undefined,
|
||||
activationReads: reads.length - before,
|
||||
startupTaskMs: task,
|
||||
retainedHeap: heap,
|
||||
...result,
|
||||
},
|
||||
{
|
||||
...workload,
|
||||
close,
|
||||
gc: heap ? "forced retention; timing diagnostic only" : "natural; clean timing",
|
||||
transport: "playwright-route",
|
||||
browser: page.context().browser()!.version(),
|
||||
scope: "production app renderer; not total desktop RAM",
|
||||
},
|
||||
)
|
||||
|
||||
if (testInfo.repeatEachIndex === 0) await page.screenshot({ path: testInfo.outputPath("destination.png") })
|
||||
await cdp.detach()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# Session-export load benchmark
|
||||
|
||||
Replay an exported session against a production app build. The two cases compare the default Compact preset with every category ungrouped and details still collapsed.
|
||||
|
||||
From `packages/app` in PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:PLAYWRIGHT_BUILD = '1'
|
||||
$env:PLAYWRIGHT_BASE_URL = 'http://127.0.0.1:4398' # Existing production preview
|
||||
$env:LAGGY_SESSION_FILE = 'C:\path\session.json'
|
||||
$env:LAGGY_SESSION_OUTPUT = 'C:\tmp\opencode\session-load'
|
||||
$env:LAGGY_SESSION_HISTORY = 'paged' # Or 'full' to supply all exported history
|
||||
bun x playwright test --config e2e/performance/playwright.config.ts timeline/laggy-session-benchmark.spec.ts --repeat-each=20 --workers=1 --retries=0
|
||||
bun e2e/performance/timeline/laggy-session-report.ts $env:LAGGY_SESSION_OUTPUT
|
||||
```
|
||||
|
||||
Each test uses a fresh browser context and measures one cold load, switches back to the source session, then measures one warm load. Repetitions therefore interleave `cold → warm` pairs rather than collecting separate cold and warm batches. There are no discarded warm-up switches. The warm member of every pair must issue zero message requests. Each pair is saved in a separate JSON file; compare paired differences as well as the cold and warm distributions when system load varies.
|
||||
|
||||
The report writes `summary.json` and prints the median, p95, maximum, and median paired cold-minus-warm difference. It rejects incomplete or cold-only records instead of mixing them into paired results.
|
||||
|
||||
`--repeat-each=20` collects 20 pairs per grouping mode. `LAGGY_SESSION_COLD_ONLY=1` remains available for focused cold profiling. Screenshots are taken after a pair finishes, not between its measurements.
|
||||
|
||||
The app shell, source session, model control, and fonts are ready before the timed action. These measurements cover session entry, not application startup. `firstCorrectObservedMs` begins at mousedown and ends when the destination is visible at its expected bottom position, including Compact's automatic history fill. `stableObservedMs` includes three-observation confirmation and must not be treated as additional rendering time.
|
||||
|
||||
Set `OPENCODE_PERFORMANCE_TRACE_DIR` for Chrome traces. `LAGGY_TRACE_ITERATION=0` traces the cold load; the default (`1`) traces the warm member of the pair. Profile separately from timing runs.
|
||||
|
||||
`LAGGY_HTTP=1` disables route interception for an external HTTP replay server containing the same export and source fixture. Keep direct HTTP and Playwright-routed cold series separate: routing adds transport overhead. Raw samples, mode settings, viewport, browser version, and screenshots are retained in the output directory. The export itself is not copied into the repository.
|
||||
|
|
@ -1,255 +0,0 @@
|
|||
import { readFileSync, mkdirSync, writeFileSync } from "node:fs"
|
||||
import type { SessionMessageInfo } from "@opencode/client/promise"
|
||||
import { base64Encode } from "@opencode/util/encode"
|
||||
import { timelineCategories, timelinePresets } from "@opencode/session-ui/timeline/detail"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
import { measureSessionSwitch, waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { startChromeTrace } from "../chrome-trace"
|
||||
|
||||
const file = process.env.LAGGY_SESSION_FILE
|
||||
|
||||
const session = file
|
||||
? (JSON.parse(readFileSync(file, "utf8")) as {
|
||||
info: {
|
||||
id: string
|
||||
projectID: string
|
||||
title: string
|
||||
model?: { id: string; providerID: string }
|
||||
location: { directory: string }
|
||||
time: { created: number; updated: number }
|
||||
}
|
||||
messages: SessionMessageInfo[]
|
||||
})
|
||||
: undefined
|
||||
|
||||
const sourceID = "ses_laggy_benchmark_source"
|
||||
|
||||
const sourceMessageID = "msg_laggy_benchmark_source"
|
||||
|
||||
const history = process.env.LAGGY_SESSION_HISTORY ?? "full"
|
||||
|
||||
const viewport = { width: 1440, height: 900 }
|
||||
|
||||
benchmark.use({ viewport, video: "off", trace: "off", serviceWorkers: "block", traceScope: "interaction" })
|
||||
|
||||
for (const mode of ["compact", "ungrouped"] as const) {
|
||||
benchmark(`laggy session: ${mode}`, async ({ page, report }, testInfo) => {
|
||||
benchmark.skip(!session, "Set LAGGY_SESSION_FILE to a session export")
|
||||
|
||||
if (!session) return
|
||||
const output = process.env.LAGGY_SESSION_OUTPUT ?? testInfo.outputPath("session-load")
|
||||
const model = session.info.model ?? { id: "benchmark-model", providerID: "benchmark" }
|
||||
const lastID = session.messages.findLast((message) => message.type === "user")!.id
|
||||
|
||||
const lastText = session.messages.findLast(
|
||||
(message) =>
|
||||
message.type === "assistant" && message.content.some((part) => part.type === "text" && part.text.trim()),
|
||||
)!
|
||||
|
||||
benchmark.setTimeout(Number(process.env.LAGGY_SESSION_TIMEOUT ?? 180_000))
|
||||
const requests: string[] = []
|
||||
const errors: string[] = []
|
||||
page.on("pageerror", (error) => errors.push(error.message))
|
||||
|
||||
if (process.env.LAGGY_HTTP === "1")
|
||||
page.on("request", (request) => {
|
||||
const match = new URL(request.url()).pathname.match(/^\/api\/session\/([^/]+)\/message$/)
|
||||
|
||||
if (request.method() === "GET" && match) requests.push(decodeURIComponent(match[1]))
|
||||
})
|
||||
|
||||
const detail = Object.fromEntries(
|
||||
timelineCategories.map((category) => [
|
||||
category,
|
||||
{
|
||||
...timelinePresets[2].value[category],
|
||||
placement: mode === "compact" ? "grouped" : "separate",
|
||||
},
|
||||
]),
|
||||
)
|
||||
|
||||
const directory = session.info.location.directory
|
||||
|
||||
if (process.env.LAGGY_HTTP !== "1")
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: session.info.projectID,
|
||||
worktree: directory,
|
||||
vcs: "git",
|
||||
name: "session-benchmark",
|
||||
time: session.info.time,
|
||||
sandboxes: [],
|
||||
},
|
||||
provider: {
|
||||
all: [
|
||||
{
|
||||
id: model.providerID,
|
||||
name: model.providerID,
|
||||
models: { [model.id]: { id: model.id, name: model.id, limit: { context: 1_000_000 } } },
|
||||
},
|
||||
],
|
||||
connected: [model.providerID],
|
||||
default: { providerID: model.providerID, modelID: model.id },
|
||||
},
|
||||
sessions: [session.info, { ...session.info, id: sourceID, title: "Benchmark source" }],
|
||||
pageMessages: (id, limit, before) => {
|
||||
if (id !== session.info.id)
|
||||
return {
|
||||
items: [
|
||||
{
|
||||
id: sourceMessageID,
|
||||
type: "user",
|
||||
text: "Benchmark source",
|
||||
time: { created: session.info.time.created },
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
if (history === "full") return { items: session.messages }
|
||||
const end = before ? session.messages.findIndex((message) => message.id === before) : session.messages.length
|
||||
const start = Math.max(0, end - limit)
|
||||
|
||||
return {
|
||||
items: session.messages.slice(start, end),
|
||||
cursor: start > 0 ? session.messages[start].id : undefined,
|
||||
}
|
||||
},
|
||||
onMessages: (request) => {
|
||||
if (request.phase === "start") requests.push(request.sessionID)
|
||||
},
|
||||
})
|
||||
await page.addInitScript(
|
||||
({ detail, directory, server, sessionIDs, dirBase64 }) => {
|
||||
localStorage.setItem("settings.v3", JSON.stringify({ general: { timelineDetail: detail } }))
|
||||
localStorage.setItem(
|
||||
"opencode.global.dat:server",
|
||||
JSON.stringify({
|
||||
projects: { local: [{ worktree: directory, expanded: true }] },
|
||||
lastProject: { local: directory },
|
||||
}),
|
||||
)
|
||||
localStorage.setItem(
|
||||
"opencode.window.browser.dat:tabs",
|
||||
JSON.stringify(sessionIDs.map((sessionId) => ({ type: "session", server, dirBase64, sessionId }))),
|
||||
)
|
||||
},
|
||||
{
|
||||
detail,
|
||||
directory,
|
||||
server: process.env.PLAYWRIGHT_BASE_URL!,
|
||||
sessionIDs: [sourceID, session.info.id],
|
||||
dirBase64: base64Encode(directory),
|
||||
},
|
||||
)
|
||||
await page.goto(sessionHref(sourceID))
|
||||
await expectSessionTitle(page, "Benchmark source")
|
||||
await expect(page.locator('[data-slot="user-message-text"]')).toHaveText("Benchmark source")
|
||||
await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toBeEditable()
|
||||
await expect(page.getByRole("button", { name: model.id, exact: true })).toBeVisible()
|
||||
await page.evaluate(() => document.fonts.ready.then(() => undefined))
|
||||
expect(requests).toEqual([sourceID])
|
||||
const startedAt = new Date().toISOString()
|
||||
const samples = []
|
||||
const phases = process.env.LAGGY_SESSION_COLD_ONLY === "1" ? (["cold"] as const) : (["cold", "warm"] as const)
|
||||
|
||||
for (const [iteration, phase] of phases.entries()) {
|
||||
const before = requests.length
|
||||
|
||||
const stopTrace =
|
||||
iteration === Number(process.env.LAGGY_TRACE_ITERATION ?? 1)
|
||||
? await startChromeTrace(page, `laggy-${history}-${mode}`)
|
||||
: undefined
|
||||
|
||||
const result = await measureSessionSwitch(page, {
|
||||
destinationIDs: session.messages.map((message) => message.id),
|
||||
sourceIDs: [sourceMessageID],
|
||||
lastID,
|
||||
requiredPartID: history === "paged" && mode === "compact" ? `${lastText.id}:text:0` : undefined,
|
||||
requireBottomAnchor: true,
|
||||
href: sessionHref(session.info.id),
|
||||
switch: async () => {
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(session.info.id)}"]`).click()
|
||||
},
|
||||
})
|
||||
|
||||
await stopTrace?.()
|
||||
await expectSessionTitle(page, session.info.title)
|
||||
|
||||
if (history === "full" || mode === "ungrouped") await waitForStableTimeline(page, lastID)
|
||||
await expect(
|
||||
page.locator('[data-timeline-key] [data-component="markdown"]:not([data-markdown-ready])'),
|
||||
).toHaveCount(0)
|
||||
expect(result.firstCorrectObservedMs).not.toBeNull()
|
||||
expect(result.stableObservedMs).not.toBeNull()
|
||||
|
||||
if (phase === "warm") expect(requests.length - before).toBe(0)
|
||||
samples.push({
|
||||
iteration,
|
||||
phase,
|
||||
messageRequests: requests.length - before,
|
||||
messageResources: await page.evaluate((sessionID) => {
|
||||
const start = performance.getEntriesByName("session-switch:start").at(-1)!.startTime
|
||||
|
||||
return (performance.getEntriesByType("resource") as PerformanceResourceTiming[])
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.startTime >= start && new URL(entry.name).pathname === `/api/session/${sessionID}/message`,
|
||||
)
|
||||
.map((entry) => ({
|
||||
limit: Number(new URL(entry.name).searchParams.get("limit")),
|
||||
startMs: entry.startTime - start,
|
||||
durationMs: entry.duration,
|
||||
transferBytes: entry.transferSize,
|
||||
}))
|
||||
}, session.info.id),
|
||||
...result,
|
||||
})
|
||||
|
||||
if (iteration === phases.length - 1) {
|
||||
mkdirSync(output, { recursive: true })
|
||||
|
||||
if (testInfo.repeatEachIndex === 0) await page.screenshot({ path: `${output}/${mode}.png` })
|
||||
break
|
||||
}
|
||||
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(sourceID)}"]`).click()
|
||||
await expectSessionTitle(page, "Benchmark source")
|
||||
await expect(page.locator('[data-slot="user-message-text"]')).toHaveText("Benchmark source")
|
||||
await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toBeEditable()
|
||||
}
|
||||
|
||||
expect(errors).toEqual([])
|
||||
|
||||
const result = {
|
||||
pair: testInfo.repeatEachIndex,
|
||||
startedAt,
|
||||
mode,
|
||||
history,
|
||||
file,
|
||||
messages: session.messages.length,
|
||||
viewport,
|
||||
browser: page.context().browser()!.version(),
|
||||
detail,
|
||||
samples,
|
||||
}
|
||||
|
||||
writeFileSync(`${output}/${mode}-${testInfo.repeatEachIndex}.json`, JSON.stringify(result, null, 2))
|
||||
report(
|
||||
{ samples },
|
||||
{
|
||||
mode,
|
||||
sampling: "cold/warm pair in one browser context",
|
||||
pair: testInfo.repeatEachIndex,
|
||||
messages: session.messages.length,
|
||||
viewport,
|
||||
data: history === "full" ? "full exported history" : "paginated exported history",
|
||||
transport: process.env.LAGGY_HTTP === "1" ? "http" : "playwright-route",
|
||||
inputEvent: "mousedown",
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
export {}
|
||||
|
||||
type Pair = {
|
||||
mode: "compact" | "ungrouped"
|
||||
samples: { phase: string; firstCorrectObservedMs: number | null; messageRequests: number }[]
|
||||
}
|
||||
|
||||
const directory = Bun.argv[2]
|
||||
|
||||
if (!directory) throw new Error("Pass the directory containing session-load pairs")
|
||||
|
||||
const pairs = await Promise.all(
|
||||
[...new Bun.Glob("{compact,ungrouped}-*.json").scanSync(directory)].map(async (file) => {
|
||||
const pair = (await Bun.file(`${directory}/${file}`).json()) as Pair
|
||||
const cold = pair.samples.find((sample) => sample.phase === "cold")
|
||||
const warm = pair.samples.find((sample) => sample.phase === "warm")
|
||||
|
||||
if (cold?.firstCorrectObservedMs == null || warm?.firstCorrectObservedMs == null)
|
||||
throw new Error(`Expected a completed cold/warm pair in ${file}`)
|
||||
|
||||
return {
|
||||
mode: pair.mode,
|
||||
cold: cold.firstCorrectObservedMs,
|
||||
warm: warm.firstCorrectObservedMs,
|
||||
requests: warm.messageRequests,
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
if (!pairs.length) throw new Error(`No session-load pairs found in ${directory}`)
|
||||
|
||||
const result = ["compact", "ungrouped"].flatMap((mode) => {
|
||||
const selected = pairs.filter((pair) => pair.mode === mode)
|
||||
|
||||
if (!selected.length) return []
|
||||
|
||||
return [
|
||||
{
|
||||
mode,
|
||||
cold: { ...stats(selected.map((pair) => pair.cold)), over50ms: selected.filter((pair) => pair.cold > 50).length },
|
||||
warm: { ...stats(selected.map((pair) => pair.warm)), over50ms: selected.filter((pair) => pair.warm > 50).length },
|
||||
pairedColdMinusWarm: stats(selected.map((pair) => pair.cold - pair.warm)),
|
||||
messageRequestsDuringWarm: selected.reduce((total, pair) => total + pair.requests, 0),
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
await Bun.write(`${directory}/summary.json`, JSON.stringify(result, null, 2))
|
||||
|
||||
console.table(
|
||||
result.map((row) => ({
|
||||
mode: row.mode,
|
||||
pairs: row.cold.n,
|
||||
coldMedianMs: Math.round(row.cold.median * 10) / 10,
|
||||
coldP95Ms: Math.round(row.cold.p95 * 10) / 10,
|
||||
warmMedianMs: Math.round(row.warm.median * 10) / 10,
|
||||
warmP95Ms: Math.round(row.warm.p95 * 10) / 10,
|
||||
warmMaxMs: Math.round(row.warm.max * 10) / 10,
|
||||
pairedDifferenceMs: Math.round(row.pairedColdMinusWarm.median * 10) / 10,
|
||||
})),
|
||||
)
|
||||
|
||||
function stats(values: number[]) {
|
||||
const sorted = values.toSorted((left, right) => left - right)
|
||||
|
||||
return {
|
||||
n: sorted.length,
|
||||
median: (sorted[Math.floor((sorted.length - 1) / 2)] + sorted[Math.floor(sorted.length / 2)]) / 2,
|
||||
p95: sorted[Math.ceil(sorted.length * 0.95) - 1],
|
||||
min: sorted[0],
|
||||
max: sorted.at(-1)!,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
import type { NavigationMilestoneSample } from "./navigation-milestones"
|
||||
import { measureNavigationMilestones } from "./navigation-milestones"
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
|
||||
benchmark(
|
||||
"navigation milestones start at mousedown and wait for the expected ready controls",
|
||||
async ({ page, report }) => {
|
||||
await page.setContent('<button id="open">Open</button><input id="editor" disabled><span id="model">Loading</span>')
|
||||
|
||||
const result = await measureNavigationMilestones(page, {
|
||||
triggerSelector: "#open",
|
||||
milestones: { editor: { selector: "#editor:enabled:focus" }, model: { selector: "#model", text: "Ready model" } },
|
||||
navigate: async () => {
|
||||
await page.getByRole("button", { name: "Open", exact: true }).dispatchEvent("mousedown", { button: 0 })
|
||||
await page.locator("#editor").evaluate((element: HTMLInputElement) => {
|
||||
element.disabled = false
|
||||
element.focus()
|
||||
})
|
||||
await page.waitForFunction(() => {
|
||||
const samples = (window as Window & { __navigationMilestones?: { samples: NavigationMilestoneSample[] } })
|
||||
.__navigationMilestones?.samples
|
||||
|
||||
return samples?.some((sample) => sample.milestones.editor && !sample.milestones.model)
|
||||
})
|
||||
await page.locator("#model").evaluate((element) => {
|
||||
element.textContent = "Ready model"
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.summary.all.firstObservedMs).not.toBeNull()
|
||||
expect(result.summary.all.firstObservedMs).toBeGreaterThan(result.summary.milestones.editor.firstObservedMs!)
|
||||
expect(await page.evaluate(() => "__navigationMilestones" in window)).toBe(false)
|
||||
report(result)
|
||||
},
|
||||
)
|
||||
|
|
@ -1,171 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
|
||||
export type NavigationMilestoneSample = {
|
||||
observedAtMs: number
|
||||
milestones: Record<string, boolean>
|
||||
}
|
||||
|
||||
export function summarizeNavigationMilestones(samples: NavigationMilestoneSample[]) {
|
||||
const names = Object.keys(samples[0]?.milestones ?? {})
|
||||
|
||||
const summarize = (matches: (sample: NavigationMilestoneSample) => boolean) => {
|
||||
const first = samples.find(matches)
|
||||
|
||||
const stable = samples.findIndex(
|
||||
(sample, index) =>
|
||||
index + 2 < samples.length && matches(sample) && matches(samples[index + 1]!) && matches(samples[index + 2]!),
|
||||
)
|
||||
|
||||
return {
|
||||
firstObservedMs: first?.observedAtMs ?? null,
|
||||
stableObservedMs: stable === -1 ? null : samples[stable + 2]!.observedAtMs,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
samples: samples.length,
|
||||
milestones: Object.fromEntries(
|
||||
names.map((name) => [name, summarize((sample) => sample.milestones[name] === true)]),
|
||||
),
|
||||
all: summarize((sample) => names.every((name) => sample.milestones[name] === true)),
|
||||
}
|
||||
}
|
||||
|
||||
type NavigationMilestoneProbe = {
|
||||
samples: NavigationMilestoneSample[]
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
export async function measureNavigationMilestones(
|
||||
page: Page,
|
||||
input: {
|
||||
triggerSelector: string
|
||||
milestones: Record<string, { selector: string; visible?: boolean; text?: string }>
|
||||
navigate: () => Promise<void>
|
||||
},
|
||||
) {
|
||||
await page.evaluate(
|
||||
({ triggerSelector, milestones }) => {
|
||||
const samples: NavigationMilestoneSample[] = []
|
||||
const streaks = new Map<string, number>()
|
||||
const marked = new Set<string>()
|
||||
let started: number | undefined
|
||||
let running = true
|
||||
|
||||
const visible = (selector: string, text?: string) =>
|
||||
[...document.querySelectorAll<HTMLElement>(selector)].some((element) => {
|
||||
if (!element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) return false
|
||||
|
||||
if (text !== undefined && element.textContent?.replace(/\s+/g, " ").trim() !== text) return false
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
return (
|
||||
rect.width > 0 &&
|
||||
rect.height > 0 &&
|
||||
rect.bottom > 0 &&
|
||||
rect.top < innerHeight &&
|
||||
rect.right > 0 &&
|
||||
rect.left < innerWidth
|
||||
)
|
||||
})
|
||||
|
||||
const sample = () => {
|
||||
if (!running || started === undefined) return
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
if (!running || started === undefined) return
|
||||
|
||||
const current = Object.fromEntries(
|
||||
Object.entries(milestones).map(([name, milestone]) => [
|
||||
name,
|
||||
milestone.visible === false
|
||||
? !document.querySelector(milestone.selector)
|
||||
: visible(milestone.selector, milestone.text),
|
||||
]),
|
||||
)
|
||||
|
||||
samples.push({
|
||||
observedAtMs: performance.now() - started,
|
||||
milestones: current,
|
||||
})
|
||||
Object.entries(current).forEach(([name, value]) => {
|
||||
if (!value) {
|
||||
streaks.set(name, 0)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (!marked.has(`${name}.first`)) {
|
||||
performance.mark(`opencode.navigation.${name}.first`)
|
||||
marked.add(`${name}.first`)
|
||||
}
|
||||
|
||||
const streak = (streaks.get(name) ?? 0) + 1
|
||||
streaks.set(name, streak)
|
||||
|
||||
if (streak === 3) performance.mark(`opencode.navigation.${name}.stable`)
|
||||
})
|
||||
const all = Object.values(current).every(Boolean)
|
||||
const allStreak = all ? (streaks.get("all") ?? 0) + 1 : 0
|
||||
streaks.set("all", allStreak)
|
||||
|
||||
if (all && !marked.has("all.first")) {
|
||||
performance.mark("opencode.navigation.all.first")
|
||||
marked.add("all.first")
|
||||
}
|
||||
|
||||
if (allStreak === 3) performance.mark("opencode.navigation.all.stable")
|
||||
sample()
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
|
||||
const start = (event: MouseEvent) => {
|
||||
if (started !== undefined || event.button !== 0) return
|
||||
|
||||
if (!(event.target instanceof Element) || !event.target.closest(triggerSelector)) return
|
||||
started = performance.now()
|
||||
performance.mark("opencode.navigation.start")
|
||||
sample()
|
||||
}
|
||||
|
||||
document.addEventListener("mousedown", start, true)
|
||||
document.addEventListener("click", start, true)
|
||||
;(window as Window & { __navigationMilestones?: NavigationMilestoneProbe }).__navigationMilestones = {
|
||||
samples,
|
||||
stop: () => {
|
||||
running = false
|
||||
document.removeEventListener("mousedown", start, true)
|
||||
document.removeEventListener("click", start, true)
|
||||
},
|
||||
}
|
||||
},
|
||||
{ triggerSelector: input.triggerSelector, milestones: input.milestones },
|
||||
)
|
||||
|
||||
try {
|
||||
await input.navigate()
|
||||
await page.waitForFunction(() => {
|
||||
const samples = (window as Window & { __navigationMilestones?: NavigationMilestoneProbe }).__navigationMilestones
|
||||
?.samples
|
||||
|
||||
return (
|
||||
samples &&
|
||||
samples.length >= 3 &&
|
||||
samples.slice(-3).every((sample) => Object.values(sample.milestones).every(Boolean))
|
||||
)
|
||||
})
|
||||
|
||||
const samples = await page.evaluate(
|
||||
() => (window as Window & { __navigationMilestones?: NavigationMilestoneProbe }).__navigationMilestones!.samples,
|
||||
)
|
||||
|
||||
return { summary: summarizeNavigationMilestones(samples), samples }
|
||||
} finally {
|
||||
await page.evaluate(() => {
|
||||
const host = window as Window & { __navigationMilestones?: NavigationMilestoneProbe }
|
||||
host.__navigationMilestones?.stop()
|
||||
delete host.__navigationMilestones
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
import config from "../playwright.config"
|
||||
|
||||
export default {
|
||||
...config,
|
||||
testDir: ".",
|
||||
testMatch: "timeline-projection-benchmark.spec.ts",
|
||||
outputDir: process.env.PROJECTION_OUTPUT,
|
||||
webServer: {
|
||||
...config.webServer,
|
||||
command: `bun run serve -- --host 127.0.0.1 --port ${process.env.PLAYWRIGHT_PORT ?? 3000} --strictPort --outDir ${process.env.PROJECTION_BUNDLE ?? "dist"}`,
|
||||
url: `http://127.0.0.1:${process.env.PLAYWRIGHT_PORT ?? 3000}`,
|
||||
reuseExistingServer: false,
|
||||
},
|
||||
use: { ...config.use, video: "off" as const, trace: "off" as const },
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
import { defineConfig, mergeConfig } from "vite"
|
||||
import config from "../../../vite.config"
|
||||
|
||||
// Benchmark-only instrumentation. Normal production builds contain no probes.
|
||||
export default mergeConfig(
|
||||
config,
|
||||
defineConfig({
|
||||
plugins: [
|
||||
{
|
||||
name: "timeline-projection-measurement",
|
||||
enforce: "pre",
|
||||
transform(source, id) {
|
||||
if (!id.replaceAll("\\", "/").endsWith("/session-ui/src/timeline/projection.ts")) return
|
||||
const start = " type Turn = {"
|
||||
const end = "\n export function constructMessageRows("
|
||||
|
||||
if (!source.includes(start) || !source.includes(end)) throw new Error("Projection probe boundary changed")
|
||||
|
||||
return source
|
||||
.replace(
|
||||
start,
|
||||
`
|
||||
const probe = globalThis.__timelineProjectionProbe
|
||||
const started = probe ? performance.now() : 0
|
||||
try {
|
||||
${start}`,
|
||||
)
|
||||
.replace(
|
||||
end,
|
||||
`
|
||||
finally {
|
||||
if (probe) {
|
||||
probe.calls += 1
|
||||
probe.entries += messages.length
|
||||
probe.ms += performance.now() - started
|
||||
}
|
||||
}
|
||||
}
|
||||
${end}`,
|
||||
)
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { fixture, installStressSessionTabs, installTimelineSettings, pageMessages } from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
import type { ModelUpdated } from "@opencode/client/promise"
|
||||
|
||||
benchmark("measures retained renderer memory with a large model catalog", async ({ page, report }) => {
|
||||
benchmark.setTimeout(120_000)
|
||||
const count = Number(process.env.PROVIDER_MEMORY_MODELS ?? 1200)
|
||||
const switches = Number(process.env.PROVIDER_MEMORY_SWITCHES ?? 10)
|
||||
const provider = fixture.provider.all[0]
|
||||
const selected = { ...provider.models["claude-opus-4-6"] }
|
||||
|
||||
const mock = await mockOpenCodeServer(page, {
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
sessions: fixture.sessions,
|
||||
pageMessages,
|
||||
provider: {
|
||||
...fixture.provider,
|
||||
all: [
|
||||
{
|
||||
...provider,
|
||||
models: {
|
||||
[selected.id]: selected,
|
||||
...Object.fromEntries(
|
||||
Array.from({ length: count - 1 }, (_, index) => {
|
||||
const id = `catalog-model-${index}`
|
||||
|
||||
return [
|
||||
id,
|
||||
{
|
||||
id,
|
||||
name: `Catalog model ${index}`,
|
||||
cost: { input: 1, output: 2 },
|
||||
limit: { context: 200_000, output: 8192 },
|
||||
variants: { high: { reasoningEffort: "high" } },
|
||||
},
|
||||
]
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
await installTimelineSettings(page)
|
||||
await installStressSessionTabs(page)
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
await expect(page.locator('[data-action="composer-model"]')).toContainText("Claude Opus 4.6")
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
const samples = []
|
||||
|
||||
for (let index = 0; index <= switches; index++) {
|
||||
if (index > 0) {
|
||||
const target = index % 2 === 1
|
||||
const id = target ? fixture.targetID : fixture.sourceID
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(id)}"]`).click()
|
||||
await expectSessionTitle(page, target ? fixture.expected.targetTitle : fixture.expected.sourceTitle)
|
||||
await waitForStableTimeline(
|
||||
page,
|
||||
(target ? fixture.expected.targetMessageIDs : fixture.expected.sourceMessageIDs).at(-1)!,
|
||||
)
|
||||
await expect(page.locator('[data-action="composer-model"]')).toContainText("Claude Opus 4.6")
|
||||
}
|
||||
|
||||
// GC is an explicit retained-heap measurement, not an application optimization or readiness wait.
|
||||
await cdp.send("HeapProfiler.collectGarbage")
|
||||
samples.push({
|
||||
switches: index,
|
||||
heap: await cdp.send("Runtime.getHeapUsage"),
|
||||
dom: await cdp.send("Memory.getDOMCounters"),
|
||||
})
|
||||
}
|
||||
|
||||
expect(samples).toHaveLength(switches + 1)
|
||||
expect(samples.every((sample) => sample.heap.usedSize > 0)).toBe(true)
|
||||
selected.name = "Updated catalog model"
|
||||
await mock.push([
|
||||
{
|
||||
id: "evt_model_refresh",
|
||||
created: Date.now(),
|
||||
type: "model.updated",
|
||||
location: { directory: fixture.directory },
|
||||
data: {},
|
||||
} satisfies ModelUpdated,
|
||||
])
|
||||
await expect(page.locator('[data-action="composer-model"]')).toContainText(selected.name)
|
||||
report(
|
||||
{ samples },
|
||||
{ models: count, switches, gc: "explicit", scope: "renderer main isolate; not total desktop RAM" },
|
||||
)
|
||||
await cdp.detach()
|
||||
})
|
||||
|
|
@ -1,372 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
import { benchmarkLocation, setupTimelineBenchmark } from "./session-timeline-benchmark.fixture"
|
||||
|
||||
const changedLinesPerFile = 100
|
||||
|
||||
const linesPerSide = changedLinesPerFile / 2
|
||||
|
||||
const fileCounts = [1, 10, 100, 1_000, 10_000]
|
||||
|
||||
const filesPerDirectory = 100
|
||||
|
||||
const readyFrames = 3
|
||||
|
||||
const completionTimeoutMs = Number(process.env.REVIEW_PANE_COMPLETION_TIMEOUT_MS ?? 900_000)
|
||||
|
||||
type ReviewPaneScalingSample = {
|
||||
observedAtMs: number
|
||||
logicalRows: number
|
||||
treeRows: number
|
||||
fileRows: number
|
||||
diffLines: number
|
||||
header: string
|
||||
ready: boolean
|
||||
}
|
||||
|
||||
type ReviewPaneScalingProbe = {
|
||||
startedAt?: number
|
||||
firstTreeRowMs?: number
|
||||
logicalTreeReadyMs?: number
|
||||
firstDiffRenderMs?: number
|
||||
stableReadyMs?: number
|
||||
samples: ReviewPaneScalingSample[]
|
||||
frameTimesMs: number[]
|
||||
longTasks: { startTime: number; duration: number }[]
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
benchmark.describe("performance: review pane scaling", () => {
|
||||
for (const fileCount of fileCounts) {
|
||||
const changedLines = fileCount * changedLinesPerFile
|
||||
|
||||
benchmark(
|
||||
`${changedLines} changed lines across ${fileCount} ${fileCount === 1 ? "file" : "files"}`,
|
||||
async ({ page, report }) => {
|
||||
benchmark.setTimeout(1_200_000)
|
||||
await page.emulateMedia({ reducedMotion: "reduce" })
|
||||
|
||||
const patchByteLimit = Number(process.env.REVIEW_PANE_PATCH_BYTE_LIMIT ?? Number.POSITIVE_INFINITY)
|
||||
|
||||
if (Number.isNaN(patchByteLimit) || patchByteLimit < 0)
|
||||
throw new Error(`Invalid REVIEW_PANE_PATCH_BYTE_LIMIT: ${process.env.REVIEW_PANE_PATCH_BYTE_LIMIT}`)
|
||||
|
||||
const responseBody = JSON.stringify({
|
||||
location: benchmarkLocation,
|
||||
data: createScalingDiffs(fileCount, patchByteLimit),
|
||||
})
|
||||
|
||||
await setupTimelineBenchmark(page, {
|
||||
historyTurns: 0,
|
||||
eventBatch: 1,
|
||||
})
|
||||
await page.route("**/vcs/diff**", (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
body: responseBody,
|
||||
}),
|
||||
)
|
||||
|
||||
const expectedRows = fileCount + 2 + Math.ceil(fileCount / filesPerDirectory)
|
||||
|
||||
const metrics = await measureReviewPaneLoad(page, {
|
||||
expectedFile: reviewFile(0),
|
||||
expectedRows,
|
||||
})
|
||||
|
||||
const search = await measureBroadReviewSearch(page, fileCount)
|
||||
|
||||
expect(metrics.logicalRows).toBe(expectedRows)
|
||||
expect(metrics.fileRows).toBeGreaterThan(0)
|
||||
expect(metrics.treeRows).toBeGreaterThan(0)
|
||||
expect(metrics.diffLines).toBeGreaterThan(0)
|
||||
expect(search.logicalRows).toBe(fileCount)
|
||||
expect(search.renderedRows).toBeGreaterThan(0)
|
||||
report(
|
||||
{ ...metrics, search },
|
||||
{
|
||||
fileCount,
|
||||
changedLinesPerFile,
|
||||
changedLines,
|
||||
additions: changedLines / 2,
|
||||
deletions: changedLines / 2,
|
||||
patchLines: changedLines,
|
||||
patchByteLimit: Number.isFinite(patchByteLimit) ? patchByteLimit : null,
|
||||
payloadBytes: new TextEncoder().encode(responseBody).byteLength,
|
||||
expectedRows,
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__reviewSearchStartedAt?: number
|
||||
__reviewPaneScalingProbe?: ReviewPaneScalingProbe
|
||||
}
|
||||
}
|
||||
|
||||
async function measureBroadReviewSearch(page: Page, expectedRows: number) {
|
||||
const filter = page.getByRole("searchbox", { name: "Filter files" })
|
||||
await filter.evaluate((element) => {
|
||||
element.addEventListener(
|
||||
"input",
|
||||
() => {
|
||||
window.__reviewSearchStartedAt = performance.now()
|
||||
},
|
||||
{ once: true, capture: true },
|
||||
)
|
||||
})
|
||||
await filter.fill("file-")
|
||||
|
||||
return page.evaluate((expectedRows) => {
|
||||
const startedAt = window.__reviewSearchStartedAt!
|
||||
|
||||
return new Promise<{ stableMs: number; logicalRows: number; renderedRows: number }>((resolve) => {
|
||||
let previous = -1
|
||||
let streak = 0
|
||||
|
||||
const sample = () => {
|
||||
const tree = document.querySelector<HTMLElement>('#review-panel [data-component="file-tree-v2"]')
|
||||
const rows = [...document.querySelectorAll<HTMLElement>('#review-panel [data-slot="file-tree-v2-row"]')]
|
||||
const logicalRows = Number(tree?.dataset.totalRows ?? rows.length)
|
||||
|
||||
const ready =
|
||||
logicalRows === expectedRows && rows.length > 0 && rows.every((row) => row.textContent?.includes("file-"))
|
||||
|
||||
streak = ready && rows.length === previous ? streak + 1 : ready ? 1 : 0
|
||||
previous = rows.length
|
||||
|
||||
if (streak >= 3) {
|
||||
resolve({ stableMs: performance.now() - startedAt, logicalRows, renderedRows: rows.length })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
})
|
||||
}, expectedRows)
|
||||
}
|
||||
|
||||
function createScalingDiffs(fileCount: number, patchByteLimit: number) {
|
||||
const changes = Array.from({ length: linesPerSide }, (_, index) => {
|
||||
const line = String(index).padStart(3, "0")
|
||||
|
||||
return `-export const value_${line} = "before"\n+export const value_${line} = "after"`
|
||||
}).join("\n")
|
||||
|
||||
let patchBytes = 0
|
||||
let capped = false
|
||||
|
||||
return Array.from({ length: fileCount }, (_, index) => {
|
||||
const file = reviewFile(index)
|
||||
|
||||
const fullPatch = [
|
||||
`diff --git a/${file} b/${file}`,
|
||||
`--- a/${file}`,
|
||||
`+++ b/${file}`,
|
||||
`@@ -1,${linesPerSide} +1,${linesPerSide} @@`,
|
||||
changes,
|
||||
].join("\n")
|
||||
|
||||
if (index === 0 && fullPatch.length > patchByteLimit)
|
||||
throw new Error(`REVIEW_PANE_PATCH_BYTE_LIMIT must include the active patch (${fullPatch.length} bytes)`)
|
||||
const patch = !capped && patchBytes + fullPatch.length <= patchByteLimit ? fullPatch : emptyReviewPatch(file)
|
||||
|
||||
if (patch === fullPatch) patchBytes += fullPatch.length
|
||||
else capped = true
|
||||
|
||||
return {
|
||||
file,
|
||||
patch,
|
||||
additions: linesPerSide,
|
||||
deletions: linesPerSide,
|
||||
status: "modified" as const,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function emptyReviewPatch(file: string) {
|
||||
return [`diff --git a/${file} b/${file}`, `--- a/${file}`, `+++ b/${file}`].join("\n")
|
||||
}
|
||||
|
||||
function reviewFile(index: number) {
|
||||
return `src/review/d${String(Math.floor(index / filesPerDirectory)).padStart(5, "0")}/file-${String(index).padStart(5, "0")}.ts`
|
||||
}
|
||||
|
||||
async function measureReviewPaneLoad(page: Page, input: { expectedFile: string; expectedRows: number }) {
|
||||
const toggle = page.getByRole("button", { name: "Toggle review" })
|
||||
await expect(toggle).toBeVisible()
|
||||
await toggle.evaluate((element) => element.setAttribute("data-review-pane-scaling-toggle", ""))
|
||||
await installReviewPaneScalingProbe(page, input)
|
||||
await toggle.click()
|
||||
await page.waitForFunction(
|
||||
() => window.__reviewPaneScalingProbe?.stableReadyMs !== undefined,
|
||||
undefined,
|
||||
{ timeout: completionTimeoutMs },
|
||||
)
|
||||
|
||||
return page.evaluate(() => {
|
||||
const probe = window.__reviewPaneScalingProbe!
|
||||
probe.stop()
|
||||
const startedAt = probe.startedAt!
|
||||
const final = probe.samples.at(-1)!
|
||||
|
||||
const resources = performance
|
||||
.getEntriesByType("resource")
|
||||
.filter(
|
||||
(entry): entry is PerformanceResourceTiming =>
|
||||
entry instanceof PerformanceResourceTiming && entry.name.includes("/vcs/diff"),
|
||||
)
|
||||
|
||||
const resource = resources.at(-1)
|
||||
|
||||
const longTasks = probe.longTasks.filter(
|
||||
(entry) => entry.startTime >= startedAt && entry.startTime <= startedAt + probe.stableReadyMs!,
|
||||
)
|
||||
|
||||
const frameGaps = probe.frameTimesMs.map((time, index) => time - (probe.frameTimesMs[index - 1] ?? 0))
|
||||
|
||||
return {
|
||||
firstTreeRowMs: probe.firstTreeRowMs ?? null,
|
||||
logicalTreeReadyMs: probe.logicalTreeReadyMs ?? null,
|
||||
firstDiffRenderMs: probe.firstDiffRenderMs ?? null,
|
||||
stableReadyMs: probe.stableReadyMs ?? null,
|
||||
responseStartMs: resource ? resource.responseStart - startedAt : null,
|
||||
responseEndMs: resource ? resource.responseEnd - startedAt : null,
|
||||
responseToStableMs: resource ? probe.stableReadyMs! - (resource.responseEnd - startedAt) : null,
|
||||
treeRows: final.treeRows,
|
||||
logicalRows: final.logicalRows,
|
||||
fileRows: final.fileRows,
|
||||
diffLines: final.diffLines,
|
||||
samples: probe.samples.length,
|
||||
maxFrameGapMs: Math.max(0, ...frameGaps),
|
||||
longTaskCount: longTasks.length,
|
||||
longTaskTotalMs: longTasks.reduce((sum, entry) => sum + entry.duration, 0),
|
||||
maxLongTaskMs: Math.max(0, ...longTasks.map((entry) => entry.duration)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function installReviewPaneScalingProbe(page: Page, input: { expectedFile: string; expectedRows: number }) {
|
||||
await page.evaluate(
|
||||
({ expectedFile, expectedRows, stableFrames }) => {
|
||||
let running = true
|
||||
let readyStreak = 0
|
||||
const basename = expectedFile.split("/").at(-1)!
|
||||
|
||||
const longTaskObserver = PerformanceObserver.supportedEntryTypes.includes("longtask")
|
||||
? new PerformanceObserver((list) => {
|
||||
probe.longTasks.push(
|
||||
...list.getEntries().map((entry) => ({ startTime: entry.startTime, duration: entry.duration })),
|
||||
)
|
||||
})
|
||||
: undefined
|
||||
|
||||
const probe: ReviewPaneScalingProbe = {
|
||||
samples: [],
|
||||
frameTimesMs: [],
|
||||
longTasks: [],
|
||||
stop: () => {
|
||||
running = false
|
||||
longTaskObserver?.disconnect()
|
||||
},
|
||||
}
|
||||
|
||||
const sample = (time: number) => {
|
||||
if (!running || probe.startedAt === undefined) return
|
||||
const panel = document.querySelector<HTMLElement>("#review-panel")
|
||||
const tree = panel?.querySelector<HTMLElement>('[data-component="file-tree-v2"]')
|
||||
const shadow = tree?.querySelector("file-tree-container")?.shadowRoot
|
||||
|
||||
const rows = shadow
|
||||
? shadow.querySelectorAll('[data-type="item"]')
|
||||
: (panel?.querySelectorAll('[data-slot="file-tree-v2-row"]') ?? [])
|
||||
|
||||
const fileRows = shadow
|
||||
? shadow.querySelectorAll('button[data-type="item"][data-item-type="file"]')
|
||||
: (panel?.querySelectorAll('button[data-slot="file-tree-v2-row"]') ?? [])
|
||||
|
||||
const header =
|
||||
panel?.querySelector<HTMLElement>('[data-slot="session-review-v2-file-header"]')?.textContent?.trim() ?? ""
|
||||
|
||||
const viewers = panel
|
||||
? [...panel.querySelectorAll<HTMLElement>('[data-component="file"][data-mode="diff"]')]
|
||||
: []
|
||||
|
||||
const diffLines = viewers.reduce(
|
||||
(sum, viewer) =>
|
||||
sum + (viewer.querySelector("diffs-container")?.shadowRoot?.querySelectorAll("[data-line]").length ?? 0),
|
||||
0,
|
||||
)
|
||||
|
||||
const observedAtMs = time - probe.startedAt
|
||||
const logicalRows = Number(tree?.dataset.totalRows ?? rows.length)
|
||||
|
||||
const ready =
|
||||
logicalRows === expectedRows &&
|
||||
fileRows.length > 0 &&
|
||||
header.includes(basename) &&
|
||||
viewers.length === 1 &&
|
||||
diffLines > 0
|
||||
|
||||
const previous = probe.samples.at(-1)
|
||||
|
||||
const stable =
|
||||
ready &&
|
||||
previous?.ready === true &&
|
||||
previous.logicalRows === logicalRows &&
|
||||
previous.treeRows === rows.length &&
|
||||
previous.fileRows === fileRows.length &&
|
||||
previous.diffLines === diffLines &&
|
||||
previous.header === header
|
||||
|
||||
probe.frameTimesMs.push(observedAtMs)
|
||||
probe.samples.push({
|
||||
observedAtMs,
|
||||
logicalRows,
|
||||
treeRows: rows.length,
|
||||
fileRows: fileRows.length,
|
||||
diffLines,
|
||||
header,
|
||||
ready,
|
||||
})
|
||||
|
||||
if (probe.firstTreeRowMs === undefined && rows.length > 0) probe.firstTreeRowMs = observedAtMs
|
||||
|
||||
if (probe.logicalTreeReadyMs === undefined && logicalRows === expectedRows)
|
||||
probe.logicalTreeReadyMs = observedAtMs
|
||||
|
||||
if (probe.firstDiffRenderMs === undefined && diffLines > 0) probe.firstDiffRenderMs = observedAtMs
|
||||
readyStreak = !ready ? 0 : stable ? readyStreak + 1 : 1
|
||||
|
||||
if (readyStreak === stableFrames) probe.stableReadyMs = observedAtMs
|
||||
|
||||
if (probe.stableReadyMs === undefined) requestAnimationFrame(sample)
|
||||
}
|
||||
|
||||
longTaskObserver?.observe({ type: "longtask", buffered: true })
|
||||
document.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const toggle = event.target instanceof Element ? event.target.closest("button") : undefined
|
||||
|
||||
if (!toggle?.hasAttribute("data-review-pane-scaling-toggle")) return
|
||||
probe.startedAt = performance.now()
|
||||
performance.mark("opencode.review-pane-scaling.click")
|
||||
requestAnimationFrame(sample)
|
||||
},
|
||||
{ capture: true, once: true },
|
||||
)
|
||||
window.__reviewPaneScalingProbe = probe
|
||||
},
|
||||
{ ...input, stableFrames: readyFrames },
|
||||
)
|
||||
}
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
import { benchmark, benchmarkDiagnostics, expect } from "../benchmark"
|
||||
import { measureNavigationMilestones } from "./navigation-milestones"
|
||||
import { fixture, installStressSessionTabs, mockStressTimeline } from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { measureSessionSwitch, waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
benchmark.use({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
serviceWorkers: "block",
|
||||
traceScope: "interaction",
|
||||
trace: "off",
|
||||
video: "off",
|
||||
})
|
||||
|
||||
for (const entry of ["home", "session"] as const) {
|
||||
benchmark(`entry: new session from ${entry}`, async ({ page, report }) => {
|
||||
await mockStressTimeline(page)
|
||||
await installStressSessionTabs(page, { sessionIDs: entry === "home" ? [] : [fixture.sourceID] })
|
||||
await page.goto(entry === "home" ? "/" : sessionHref(fixture.sourceID))
|
||||
|
||||
if (entry === "session") await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
const trigger = entry === "home" ? '[data-action="home-new-session"]' : 'button[aria-label="New session"]'
|
||||
await expect(page.locator(trigger)).toBeVisible()
|
||||
await expect(page.locator('[data-component="new-session"]')).toHaveCount(0)
|
||||
const writes: string[] = []
|
||||
page.on("request", (request) => {
|
||||
if (new URL(request.url()).pathname.startsWith("/api/") && !["GET", "HEAD", "OPTIONS"].includes(request.method()))
|
||||
writes.push(request.method())
|
||||
})
|
||||
await benchmarkDiagnostics(page).startTrace()
|
||||
|
||||
const result = await measureNavigationMilestones(page, {
|
||||
triggerSelector: trigger,
|
||||
milestones: {
|
||||
editor: {
|
||||
selector: '[data-component="new-session"] [data-component="composer-editor"][contenteditable="true"]:focus',
|
||||
},
|
||||
model: { selector: '[data-component="new-session"] [data-action="composer-model"]', text: "Claude Opus 4.6" },
|
||||
project: { selector: '[data-component="new-session"] [data-action="prompt-project"]' },
|
||||
tab: { selector: '[data-titlebar-tab-link][href^="/new-session?draftId="]' },
|
||||
},
|
||||
navigate: () => page.locator(trigger).click(),
|
||||
})
|
||||
|
||||
await benchmarkDiagnostics(page).stop()
|
||||
const editor = page.locator('[data-component="new-session"] [data-component="composer-editor"]')
|
||||
await expect(editor).toHaveText("")
|
||||
await page.keyboard.type("Draft input")
|
||||
await expect(editor).toHaveText("Draft input")
|
||||
expect(writes).toEqual([])
|
||||
report(
|
||||
{
|
||||
firstCorrectObservedMs: result.summary.all.firstObservedMs,
|
||||
stableObservedMs: result.summary.all.stableObservedMs,
|
||||
...result,
|
||||
},
|
||||
{ entry, data: "fixture", inputEvent: "mousedown" },
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
benchmark("entry: cold session from Home", async ({ page, report }) => {
|
||||
const requests: string[] = []
|
||||
await mockStressTimeline(page, {
|
||||
onMessages: (request) => {
|
||||
if (request.phase === "start") requests.push(request.sessionID)
|
||||
},
|
||||
})
|
||||
await installStressSessionTabs(page, { sessionIDs: [] })
|
||||
await page.goto("/")
|
||||
const selector = `[data-component="home-session-row-container"][data-session-id="${fixture.targetID}"] [data-component="home-session-row"]`
|
||||
await expect(page.locator(selector)).toBeVisible()
|
||||
expect(requests).not.toContain(fixture.targetID)
|
||||
const href = sessionHref(fixture.targetID)
|
||||
await benchmarkDiagnostics(page).startTrace()
|
||||
|
||||
const result = await measureSessionSwitch(page, {
|
||||
destinationIDs: fixture.messages[fixture.targetID].map((message) => message.id),
|
||||
sourceIDs: [],
|
||||
lastID: fixture.expected.targetMessageIDs.at(-1)!,
|
||||
requiredPartID: fixture.expected.targetPartIDs.at(-1)!,
|
||||
href,
|
||||
triggerSelector: selector,
|
||||
switch: async () => {
|
||||
await page.locator(selector).click()
|
||||
await waitForStableTimeline(page, fixture.expected.targetMessageIDs.at(-1)!)
|
||||
},
|
||||
})
|
||||
|
||||
await benchmarkDiagnostics(page).stop()
|
||||
await expect(
|
||||
page.locator(`[data-titlebar-tab-slot][data-active="true"] [data-titlebar-tab-link][href="${href}"]`),
|
||||
).toHaveCount(1)
|
||||
expect(requests).toContain(fixture.targetID)
|
||||
report(result, { entry: "home", data: "cold paginated fixture", inputEvent: "mousedown" })
|
||||
})
|
||||
|
|
@ -1,184 +0,0 @@
|
|||
import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise"
|
||||
import type { Page } from "@playwright/test"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { benchmark, expect, withBenchmarkPage } from "../benchmark"
|
||||
import { fixture, installStressSessionTabs } from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { measureSessionSwitch, waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
type ParentHydrationBenchmarkMode = "natural" | "candidate"
|
||||
|
||||
const mode = process.env.SESSION_PARENT_HYDRATION_BENCHMARK_MODE ?? "natural"
|
||||
|
||||
if (mode !== "natural" && mode !== "candidate") throw new Error(`Unknown parent hydration benchmark mode: ${mode}`)
|
||||
|
||||
const userID = "msg_parent_hydration_user"
|
||||
|
||||
const userSeed = fixture.messages[fixture.targetID][0] as SessionMessageUser
|
||||
|
||||
const user = {
|
||||
...userSeed,
|
||||
id: userID,
|
||||
time: { created: 1700001000000 },
|
||||
} satisfies SessionMessageInfo
|
||||
|
||||
const assistantSeed = fixture.messages[fixture.targetID][3] as SessionMessageAssistant
|
||||
|
||||
const assistants = Array.from({ length: 14 }, (_, index) => {
|
||||
const messageID = `msg_parent_hydration_${String(index).padStart(2, "0")}`
|
||||
|
||||
return {
|
||||
...assistantSeed,
|
||||
id: messageID,
|
||||
time: { created: 1700001001000 + index * 1_000, completed: 1700001001500 + index * 1_000 },
|
||||
content: assistantSeed.content.map((part, partIndex) =>
|
||||
part.type === "tool"
|
||||
? { ...part, id: `call_parent_hydration_${String(index).padStart(2, "0")}_${partIndex}` }
|
||||
: part,
|
||||
),
|
||||
} satisfies SessionMessageInfo
|
||||
})
|
||||
|
||||
const messages = [user, ...assistants]
|
||||
|
||||
const target = fixture.sessions.find((session) => session.id === fixture.targetID)!
|
||||
|
||||
const lastID = userID
|
||||
|
||||
const lastAssistant = assistants.at(-1)!
|
||||
|
||||
const lastPart = lastAssistant.content.at(-1)!
|
||||
|
||||
const lastPartID =
|
||||
lastPart.type === "tool"
|
||||
? lastPart.id
|
||||
: `${lastAssistant.id}:${lastPart.type}:${lastAssistant.content.filter((part) => part.type === lastPart.type).length - 1}`
|
||||
|
||||
benchmark("hydrates an orphaned latest turn after a cold session click", async ({ browser, report }, testInfo) => {
|
||||
benchmark.setTimeout(180_000)
|
||||
const results = [] as Awaited<ReturnType<typeof trial>>[]
|
||||
|
||||
for (let run = 0; run < 5; run++) {
|
||||
results.push(
|
||||
await withBenchmarkPage(
|
||||
browser,
|
||||
`session-parent-hydration-${mode}-${run}`,
|
||||
(page) => trial(page, mode),
|
||||
testInfo,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const timing = results.map((result) => result.metrics.firstCorrectObservedMs!).sort((a, b) => a - b)
|
||||
report(
|
||||
{
|
||||
results: results.map((result) => ({ ...result.metrics, historyGateCount: result.historyGateCount })),
|
||||
summary: {
|
||||
firstCorrectObservedMs: { min: timing[0], median: timing[2], max: timing.at(-1) },
|
||||
blankSamples: results.map((result) => result.metrics.blankSamples),
|
||||
requestCounts: {
|
||||
list: results.map((result) => result.requestCounts.list),
|
||||
parent: results.map((result) => result.requestCounts.parent),
|
||||
},
|
||||
historyGateCount: results.map((result) => result.historyGateCount),
|
||||
},
|
||||
},
|
||||
{ mode },
|
||||
)
|
||||
})
|
||||
|
||||
async function trial(page: Page, mode: ParentHydrationBenchmarkMode) {
|
||||
const requests: { type: "list" | "parent"; before?: string }[] = []
|
||||
const history = mode === "candidate" ? Promise.withResolvers<void>() : undefined
|
||||
let historyGates = 0
|
||||
await mockOpenCodeServer(page, {
|
||||
sessions: fixture.sessions.filter((session) => session.id === fixture.sourceID),
|
||||
provider: fixture.provider,
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
messageDelay: 50,
|
||||
onMessages: (request) => {
|
||||
if (request.sessionID === fixture.targetID && request.phase === "start")
|
||||
requests.push({ type: "list", before: request.before })
|
||||
},
|
||||
beforeMessagesResponse: (request) => {
|
||||
if (mode !== "candidate" || request.sessionID !== fixture.targetID || !request.before) return Promise.resolve()
|
||||
historyGates++
|
||||
|
||||
return history!.promise
|
||||
},
|
||||
onMessage: (request) => {
|
||||
if (request.sessionID === fixture.targetID && request.messageID === userID) requests.push({ type: "parent" })
|
||||
},
|
||||
message: (sessionID, messageID) => {
|
||||
if (sessionID !== fixture.targetID || messageID !== userID) return
|
||||
|
||||
return user
|
||||
},
|
||||
pageMessages: (sessionID, limit, before) => {
|
||||
const items = sessionID === fixture.targetID ? messages : fixture.messages[fixture.sourceID]
|
||||
const end = before ? items.findIndex((message) => message.id === before) : items.length
|
||||
const start = Math.max(0, end - limit)
|
||||
|
||||
return { items: items.slice(start, end), cursor: start > 0 ? items[start]!.id : undefined }
|
||||
},
|
||||
})
|
||||
await page.route(`**/api/session/${fixture.targetID}`, (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
data: {
|
||||
...target,
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
location: { directory: target.directory },
|
||||
},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
await installStressSessionTabs(page, { sessionIDs: [fixture.sourceID] })
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
|
||||
const href = sessionHref(fixture.targetID)
|
||||
await page.evaluate(
|
||||
({ href, title }) => {
|
||||
const link = document.createElement("a")
|
||||
link.id = "parent-hydration-target"
|
||||
link.href = href
|
||||
link.textContent = title
|
||||
document.body.append(link)
|
||||
},
|
||||
{ href, title: target.title },
|
||||
)
|
||||
|
||||
const metrics = await measureSessionSwitch(page, {
|
||||
destinationIDs: messages.map((message) => message.id),
|
||||
sourceIDs: fixture.messages[fixture.sourceID].map((message) => message.id),
|
||||
lastID,
|
||||
requiredPartID: lastPartID,
|
||||
requireBottomAnchor: false,
|
||||
href,
|
||||
switch: async () => {
|
||||
await page.locator("#parent-hydration-target").click()
|
||||
await expectSessionTitle(page, target.title)
|
||||
},
|
||||
}).finally(() => history?.resolve())
|
||||
|
||||
expect(metrics.firstCorrectObservedMs).not.toBeNull()
|
||||
|
||||
const requestCounts = {
|
||||
list: requests.filter((request) => request.type === "list").length,
|
||||
parent: requests.filter((request) => request.type === "parent").length,
|
||||
}
|
||||
|
||||
if (mode === "candidate") {
|
||||
expect(requestCounts.parent).toBe(0)
|
||||
expect(historyGates).toBe(0)
|
||||
}
|
||||
|
||||
return { metrics, requestCounts, historyGateCount: historyGates }
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import {
|
||||
collectCachedRepaintTrace,
|
||||
compressCachedRepaintTrace,
|
||||
installCachedRepaintProbe,
|
||||
waitForCachedRepaintWindow,
|
||||
} from "./session-tab-repaint-probe"
|
||||
import { waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
import {
|
||||
fixture,
|
||||
installStressSessionTabs,
|
||||
installTimelineSettings,
|
||||
mockStressTimeline,
|
||||
} from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
|
||||
benchmark("samples cached session repaint after the click", async ({ page, report }) => {
|
||||
benchmark.setTimeout(120_000)
|
||||
await mockStressTimeline(page)
|
||||
await installStressSessionTabs(page)
|
||||
await installTimelineSettings(page)
|
||||
await page.goto(sessionHref(fixture.targetID))
|
||||
await expectSessionTitle(page, fixture.expected.targetTitle)
|
||||
await waitForStableTimeline(page, fixture.expected.targetMessageIDs.at(-1)!)
|
||||
await page
|
||||
.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(fixture.sourceID)}"]`)
|
||||
.first()
|
||||
.click()
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
|
||||
await installCachedRepaintProbe(page, {
|
||||
targetHref: sessionHref(fixture.targetID),
|
||||
destination: fixture.messages[fixture.targetID].map((message) => message.id),
|
||||
source: fixture.messages[fixture.sourceID].map((message) => message.id),
|
||||
last: fixture.expected.targetMessageIDs.at(-1)!,
|
||||
windowMs: 1_000,
|
||||
})
|
||||
|
||||
await page
|
||||
.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(fixture.targetID)}"]`)
|
||||
.first()
|
||||
.click()
|
||||
await Promise.all([expectSessionTitle(page, fixture.expected.targetTitle), waitForCachedRepaintWindow(page, 1_000)])
|
||||
const result = await collectCachedRepaintTrace(page)
|
||||
report(compressCachedRepaintTrace(result))
|
||||
expect(result.samples.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
benchmark("loads only the selected restored tab's transcript", async ({ page, report }) => {
|
||||
const loaded = new Set<string>()
|
||||
await mockStressTimeline(page, {
|
||||
onMessages: (input) => {
|
||||
if (!input.before && input.phase === "start") loaded.add(input.sessionID)
|
||||
},
|
||||
})
|
||||
await installStressSessionTabs(page, {
|
||||
sessionIDs: [fixture.sourceID, fixture.targetID, fixture.childID],
|
||||
})
|
||||
await installTimelineSettings(page)
|
||||
|
||||
const attention = Promise.all(
|
||||
[fixture.targetID, fixture.childID].map((id) =>
|
||||
page.waitForResponse((response) => new URL(response.url()).pathname === `/api/session/${id}/form`),
|
||||
),
|
||||
)
|
||||
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
|
||||
await attention
|
||||
await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
expect([...loaded]).toEqual([fixture.sourceID])
|
||||
report({ loaded: [...loaded] })
|
||||
})
|
||||
|
|
@ -1,288 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
|
||||
type CachedRepaintTrace = {
|
||||
timeOriginEpochMs: number
|
||||
startedAtPerformanceMs: number
|
||||
samples: {
|
||||
observedAtMs: number
|
||||
root: number | undefined
|
||||
scrollTop: number
|
||||
scrollHeight: number
|
||||
bottomErrorPx: number | undefined
|
||||
last: boolean
|
||||
rows: { key: string | undefined; node: number; top: number; bottom: number }[]
|
||||
mounted: number
|
||||
center: string | undefined
|
||||
destination: string[]
|
||||
source: string[]
|
||||
}[]
|
||||
mutations: { observedAtMs: number; changed: { type: string; node: number }[] }[]
|
||||
shifts: { occurredAtMs: number; value: number }[]
|
||||
windowMs: number
|
||||
running: boolean
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
export async function installCachedRepaintProbe(
|
||||
page: Page,
|
||||
input: { targetHref: string; destination: string[]; source: string[]; last: string; windowMs: number },
|
||||
) {
|
||||
await page.evaluate(({ targetHref, destination, source, last, windowMs }) => {
|
||||
const destinationIDs = new Set(destination)
|
||||
const sourceIDs = new Set(source)
|
||||
const nodeIDs = new WeakMap<Node, number>()
|
||||
let nextNodeID = 1
|
||||
|
||||
const id = (node: Node) => {
|
||||
const current = nodeIDs.get(node)
|
||||
|
||||
if (current) return current
|
||||
nodeIDs.set(node, nextNodeID)
|
||||
|
||||
return nextNodeID++
|
||||
}
|
||||
|
||||
const state: CachedRepaintTrace = {
|
||||
timeOriginEpochMs: performance.timeOrigin,
|
||||
startedAtPerformanceMs: 0,
|
||||
samples: [],
|
||||
mutations: [],
|
||||
shifts: [],
|
||||
windowMs,
|
||||
running: false,
|
||||
stop: () => {},
|
||||
}
|
||||
|
||||
const recordShifts = (entries: PerformanceEntry[]) => {
|
||||
if (!state.running) return
|
||||
state.shifts.push(
|
||||
...entries
|
||||
.map((entry) => {
|
||||
if (
|
||||
entry.startTime < state.startedAtPerformanceMs ||
|
||||
entry.startTime > state.startedAtPerformanceMs + state.windowMs
|
||||
)
|
||||
return
|
||||
|
||||
return {
|
||||
occurredAtMs: entry.startTime - state.startedAtPerformanceMs,
|
||||
value: (entry as PerformanceEntry & { value: number }).value,
|
||||
}
|
||||
})
|
||||
.filter((entry): entry is { occurredAtMs: number; value: number } => entry !== undefined),
|
||||
)
|
||||
}
|
||||
|
||||
const shiftObserver = new PerformanceObserver((entries) => recordShifts(entries.getEntries()))
|
||||
shiftObserver.observe({ type: "layout-shift" })
|
||||
|
||||
const recordMutations = (entries: MutationRecord[]) => {
|
||||
if (!state.running) return
|
||||
const observedAtMs = performance.now() - state.startedAtPerformanceMs
|
||||
|
||||
if (observedAtMs > state.windowMs) return
|
||||
|
||||
const changed = entries.flatMap((entry) => [
|
||||
...[...entry.addedNodes].map((node) => ({ type: "add", node: id(node) })),
|
||||
...[...entry.removedNodes].map((node) => ({ type: "remove", node: id(node) })),
|
||||
])
|
||||
|
||||
if (changed.length) state.mutations.push({ observedAtMs, changed })
|
||||
}
|
||||
|
||||
const mutationObserver = new MutationObserver(recordMutations)
|
||||
mutationObserver.observe(document.documentElement, { childList: true, subtree: true })
|
||||
state.stop = () => {
|
||||
recordShifts(shiftObserver.takeRecords())
|
||||
recordMutations(mutationObserver.takeRecords())
|
||||
state.running = false
|
||||
shiftObserver.disconnect()
|
||||
mutationObserver.disconnect()
|
||||
}
|
||||
|
||||
const sample = () => {
|
||||
if (!state.running) return
|
||||
setTimeout(() => {
|
||||
if (!state.running) return
|
||||
const observedAtMs = performance.now() - state.startedAtPerformanceMs
|
||||
|
||||
if (observedAtMs > state.windowMs) return
|
||||
|
||||
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
|
||||
element.querySelector("[data-timeline-row]"),
|
||||
)
|
||||
|
||||
if (root) {
|
||||
const view = root.getBoundingClientRect()
|
||||
|
||||
const rows = [...root.querySelectorAll<HTMLElement>("[data-timeline-key]")]
|
||||
.map((element) => ({
|
||||
key: element.dataset.timelineKey,
|
||||
node: id(element),
|
||||
rect: element.getBoundingClientRect(),
|
||||
}))
|
||||
.filter((item) => item.rect.bottom > view.top && item.rect.top < view.bottom)
|
||||
.map((item) => ({
|
||||
key: item.key,
|
||||
node: item.node,
|
||||
top: item.rect.top - view.top,
|
||||
bottom: item.rect.bottom - view.top,
|
||||
}))
|
||||
|
||||
const messages = [...root.querySelectorAll<HTMLElement>("[data-message-id]")]
|
||||
.filter((element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
return rect.bottom > view.top && rect.top < view.bottom
|
||||
})
|
||||
.map((element) => element.dataset.messageId!)
|
||||
|
||||
const spacer = root.querySelector<HTMLElement>('[data-timeline-row="bottom-spacer"]')?.getBoundingClientRect()
|
||||
state.samples.push({
|
||||
observedAtMs,
|
||||
root: id(root),
|
||||
scrollTop: root.scrollTop,
|
||||
scrollHeight: root.scrollHeight,
|
||||
bottomErrorPx: spacer ? spacer.bottom - view.bottom : undefined,
|
||||
last: messages.includes(last),
|
||||
rows,
|
||||
mounted: root.querySelectorAll("[data-timeline-key]").length,
|
||||
center: document
|
||||
.elementFromPoint(view.left + view.width / 2, view.top + view.height / 2)
|
||||
?.textContent?.slice(0, 80),
|
||||
destination: messages.filter((messageID) => destinationIDs.has(messageID)),
|
||||
source: messages.filter((messageID) => sourceIDs.has(messageID)),
|
||||
})
|
||||
} else {
|
||||
state.samples.push({
|
||||
observedAtMs,
|
||||
root: undefined,
|
||||
scrollTop: 0,
|
||||
scrollHeight: 0,
|
||||
bottomErrorPx: undefined,
|
||||
last: false,
|
||||
rows: [],
|
||||
mounted: 0,
|
||||
center: document.elementFromPoint(innerWidth / 2, innerHeight / 2)?.textContent?.slice(0, 80),
|
||||
destination: [],
|
||||
source: [],
|
||||
})
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
document.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const link = event.target instanceof Element ? event.target.closest("a") : undefined
|
||||
|
||||
if (link?.getAttribute("href") !== targetHref) return
|
||||
state.startedAtPerformanceMs = performance.now()
|
||||
state.running = true
|
||||
requestAnimationFrame(sample)
|
||||
},
|
||||
{ capture: true, once: true },
|
||||
)
|
||||
;(window as Window & { __cachedFlash?: CachedRepaintTrace }).__cachedFlash = state
|
||||
}, input)
|
||||
}
|
||||
|
||||
export function layoutShiftSample(entry: Pick<PerformanceEntry, "startTime"> & { value: number }, started: number) {
|
||||
if (entry.startTime < started) return
|
||||
|
||||
return { occurredAtMs: entry.startTime - started, value: entry.value }
|
||||
}
|
||||
|
||||
export async function waitForCachedRepaintWindow(page: Page, durationMs: number) {
|
||||
await page.waitForFunction((durationMs) => {
|
||||
const state = (window as Window & { __cachedFlash?: CachedRepaintTrace }).__cachedFlash
|
||||
|
||||
return !!state?.running && performance.now() - state.startedAtPerformanceMs >= durationMs
|
||||
}, durationMs)
|
||||
}
|
||||
|
||||
export async function collectCachedRepaintTrace(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const state = (window as Window & { __cachedFlash?: CachedRepaintTrace }).__cachedFlash!
|
||||
state.stop()
|
||||
|
||||
return state
|
||||
})
|
||||
}
|
||||
|
||||
export function summarizeCachedRepaintTrace(trace: CachedRepaintTrace) {
|
||||
const roots = trace.samples.map((sample) => sample.root)
|
||||
|
||||
const bottomErrors = trace.samples.flatMap((sample) =>
|
||||
sample.bottomErrorPx === undefined ? [] : [Math.abs(sample.bottomErrorPx)],
|
||||
)
|
||||
|
||||
const category = (sample: CachedRepaintTrace["samples"][number]) => {
|
||||
if (sample.source.length) return "source"
|
||||
|
||||
if (sample.root === undefined || sample.rows.length === 0) return "blank"
|
||||
|
||||
if (!sample.destination.length) return "unknown"
|
||||
|
||||
if (sample.last && Math.abs(sample.bottomErrorPx ?? Infinity) <= 1) return "correct"
|
||||
|
||||
return "wrongDestination"
|
||||
}
|
||||
|
||||
return {
|
||||
samples: trace.samples.length,
|
||||
durationMs: trace.samples.at(-1)?.observedAtMs ?? 0,
|
||||
firstSampleObservedMs: trace.samples[0]?.observedAtMs,
|
||||
firstSampleCorrect: trace.samples[0] ? category(trace.samples[0]) === "correct" : false,
|
||||
blankSamples: trace.samples.filter((sample) => category(sample) === "blank").length,
|
||||
sourceSamples: trace.samples.filter((sample) => category(sample) === "source").length,
|
||||
wrongDestinationSamples: trace.samples.filter((sample) => category(sample) === "wrongDestination").length,
|
||||
unknownSamples: trace.samples.filter((sample) => category(sample) === "unknown").length,
|
||||
rootChanges: roots.slice(1).filter((root, index) => root !== roots[index]).length,
|
||||
mountedMin: trace.samples.length ? Math.min(...trace.samples.map((sample) => sample.mounted)) : 0,
|
||||
mountedMax: Math.max(...trace.samples.map((sample) => sample.mounted)),
|
||||
maxBottomErrorPx: Math.max(0, ...bottomErrors),
|
||||
mutationBatches: trace.mutations.length,
|
||||
addedNodes: trace.mutations.reduce(
|
||||
(sum, batch) => sum + batch.changed.filter((change) => change.type === "add").length,
|
||||
0,
|
||||
),
|
||||
removedNodes: trace.mutations.reduce(
|
||||
(sum, batch) => sum + batch.changed.filter((change) => change.type === "remove").length,
|
||||
0,
|
||||
),
|
||||
layoutShiftValueSum: trace.shifts.reduce((sum, shift) => sum + shift.value, 0),
|
||||
maxLayoutShiftValue: Math.max(0, ...trace.shifts.map((shift) => shift.value)),
|
||||
}
|
||||
}
|
||||
|
||||
export function compressCachedRepaintTrace(trace: CachedRepaintTrace) {
|
||||
const samples: {
|
||||
observedAtMs: number[]
|
||||
state: Omit<CachedRepaintTrace["samples"][number], "observedAtMs">
|
||||
}[] = []
|
||||
|
||||
for (const sample of trace.samples) {
|
||||
const { observedAtMs, ...state } = sample
|
||||
const previous = samples.at(-1)
|
||||
|
||||
if (previous && JSON.stringify(previous.state) === JSON.stringify(state)) {
|
||||
previous.observedAtMs.push(observedAtMs)
|
||||
continue
|
||||
}
|
||||
|
||||
samples.push({ observedAtMs: [observedAtMs], state })
|
||||
}
|
||||
|
||||
return {
|
||||
timeOriginEpochMs: trace.timeOriginEpochMs,
|
||||
startedAtPerformanceMs: trace.startedAtPerformanceMs,
|
||||
windowMs: trace.windowMs,
|
||||
summary: summarizeCachedRepaintTrace(trace),
|
||||
samples,
|
||||
mutations: trace.mutations,
|
||||
shifts: trace.shifts,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { expectSessionTitle } from "../../utils/waits"
|
||||
import { benchmark, benchmarkDiagnostics, expect } from "../benchmark"
|
||||
import { fixture, installStressSessionTabs, installTimelineSettings } from "../../utils/session-fixture"
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { expected, messages } from "../../utils/markdown-sessions"
|
||||
import { workload } from "./session-tab-switch.fixture"
|
||||
import { createReviewDiffs } from "./timeline-test-helpers"
|
||||
import { measureSessionSwitch, waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
const scenarios = [
|
||||
{ cache: "cold", review: "closed" },
|
||||
{ cache: "cold", review: "open" },
|
||||
{ cache: "warm", review: "closed" },
|
||||
{ cache: "warm", review: "open" },
|
||||
{ cache: "warm", review: "resized" },
|
||||
] as const
|
||||
|
||||
const viewport = { width: 1440, height: 900 }
|
||||
|
||||
const reviewDiffs = createReviewDiffs()
|
||||
|
||||
benchmark.use({ viewport, video: "off", trace: "off", serviceWorkers: "block", traceScope: "interaction" })
|
||||
|
||||
scenarios.forEach((scenario) => {
|
||||
benchmark(`tab switch: ${scenario.cache}, review ${scenario.review}`, async ({ page, report }, testInfo) => {
|
||||
const requests = await prepareSessionTabs(page)
|
||||
|
||||
if (scenario.review === "open") await openReviewPane(page)
|
||||
|
||||
if (scenario.cache === "warm") {
|
||||
await switchSession(page, fixture.targetID, fixture.expected.targetTitle)
|
||||
await expectReadyTimeline(page, fixture.targetID)
|
||||
await switchSession(page, fixture.sourceID, fixture.expected.sourceTitle)
|
||||
}
|
||||
|
||||
if (scenario.review === "resized") await openReviewPane(page)
|
||||
await expectReadyTimeline(page, fixture.sourceID)
|
||||
await benchmarkDiagnostics(page).startTrace()
|
||||
const requestsBefore = requests.length
|
||||
|
||||
const result = await measureSessionSwitch(page, {
|
||||
destinationIDs: messages[fixture.targetID].map((message) => message.id),
|
||||
sourceIDs: messages[fixture.sourceID].map((message) => message.id),
|
||||
lastID: expected[fixture.targetID].lastID,
|
||||
requiredPartID: expected[fixture.targetID].answerID,
|
||||
href: sessionHref(fixture.targetID),
|
||||
switch: () => switchSession(page, fixture.targetID, fixture.expected.targetTitle),
|
||||
})
|
||||
|
||||
expect(result.firstCorrectObservedMs).not.toBeNull()
|
||||
expect(result.stableObservedMs).not.toBeNull()
|
||||
expect(requests).toHaveLength(requestsBefore + (scenario.cache === "cold" ? 1 : 0))
|
||||
await expectReadyTimeline(page, fixture.targetID)
|
||||
report(
|
||||
{
|
||||
...result,
|
||||
messageRequestsDuringSwitch: requests.length - requestsBefore,
|
||||
rendererMemory:
|
||||
process.env.OPENCODE_PERFORMANCE_MEMORY === "1" ? await retainedRendererMemory(page) : undefined,
|
||||
},
|
||||
{
|
||||
...scenario,
|
||||
...workload,
|
||||
viewport,
|
||||
browserVersion: page.context().browser()!.version(),
|
||||
serviceWorkers: "blocked",
|
||||
reviewFiles: scenario.review === "closed" ? 0 : reviewDiffs.length,
|
||||
data: scenario.cache === "cold" ? "on-demand" : "cached",
|
||||
transport: process.env.OPENCODE_PERFORMANCE_HTTP_FIXTURE === "1" ? "http" : "playwright-route",
|
||||
inputEvent: "mousedown",
|
||||
requireReadyAnswer: true,
|
||||
},
|
||||
)
|
||||
|
||||
if (testInfo.repeatEachIndex === 0) {
|
||||
await page.screenshot({ path: testInfo.outputPath("destination.png") })
|
||||
await testInfo.attach("destination", { path: testInfo.outputPath("destination.png"), contentType: "image/png" })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
async function prepareSessionTabs(page: Page) {
|
||||
const requests: string[] = []
|
||||
page.on("request", (request) => {
|
||||
if (request.method() !== "GET") return
|
||||
const match = new URL(request.url()).pathname.match(/^\/api\/session\/([^/]+)\/message$/)
|
||||
|
||||
if (match) requests.push(decodeURIComponent(match[1]))
|
||||
})
|
||||
|
||||
if (process.env.OPENCODE_PERFORMANCE_HTTP_FIXTURE !== "1")
|
||||
await mockOpenCodeServer(page, {
|
||||
sessions: fixture.sessions,
|
||||
provider: fixture.provider,
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
// Return the full history so every scenario exercises a long loaded timeline.
|
||||
pageMessages: (sessionID) => ({ items: messages[sessionID] ?? [] }),
|
||||
vcsDiff: reviewDiffs,
|
||||
})
|
||||
await installTimelineSettings(page)
|
||||
await installStressSessionTabs(page)
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
await expectSessionTitle(page, fixture.expected.sourceTitle)
|
||||
await expectReadyTimeline(page, fixture.sourceID)
|
||||
await expect(page.locator(`[data-timeline-part-id="${expected[fixture.targetID].answerID}"]`)).toHaveCount(0)
|
||||
expect(requests).toEqual([fixture.sourceID])
|
||||
|
||||
return requests
|
||||
}
|
||||
|
||||
async function expectReadyTimeline(page: Page, sessionID: string) {
|
||||
const answer = page.locator(`[data-timeline-part-id="${expected[sessionID].answerID}"]`)
|
||||
await expect(answer.locator('[data-component="markdown"]')).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(answer.getByRole("table")).toHaveCount(1)
|
||||
await expect(answer.locator("pre")).toHaveCount(4)
|
||||
await expect
|
||||
.poll(() => answer.evaluate((element) => element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })))
|
||||
.toBe(true)
|
||||
await waitForStableTimeline(page, expected[sessionID].lastID)
|
||||
await expect(page.locator('[data-timeline-key] [data-component="markdown"]:not([data-markdown-ready])')).toHaveCount(
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
async function switchSession(page: Page, sessionID: string, title: string) {
|
||||
const tab = page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(sessionID)}"]`)
|
||||
await expect(tab).toHaveCount(1)
|
||||
await tab.click()
|
||||
await expectSessionTitle(page, title)
|
||||
}
|
||||
|
||||
async function openReviewPane(page: Page) {
|
||||
await page.getByRole("button", { name: "Toggle review" }).click()
|
||||
await expect(page.locator("#review-panel")).toBeVisible()
|
||||
await page.waitForFunction(() => {
|
||||
const text = document.querySelector("#review-panel")?.textContent ?? ""
|
||||
|
||||
return text.includes("generated-000.ts") && text.includes("+3")
|
||||
})
|
||||
await page.locator('[data-slot="session-chat-panel"]').evaluate(async (panel) => {
|
||||
await Promise.all(panel.getAnimations().map((animation) => animation.finished))
|
||||
})
|
||||
}
|
||||
|
||||
async function retainedRendererMemory(page: Page) {
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
|
||||
try {
|
||||
await cdp.send("HeapProfiler.collectGarbage")
|
||||
|
||||
return {
|
||||
heap: await cdp.send("Runtime.getHeapUsage"),
|
||||
dom: await cdp.send("Memory.getDOMCounters"),
|
||||
}
|
||||
} finally {
|
||||
await cdp.detach()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
export type SessionSwitchSample = {
|
||||
observedAtMs: number
|
||||
destination: string[]
|
||||
source: string[]
|
||||
hasVisibleRows: boolean
|
||||
last: boolean
|
||||
requiredPartVisible?: boolean
|
||||
bottomAnchorRequired?: boolean
|
||||
bottomErrorPx?: number
|
||||
review?: {
|
||||
fileHost: boolean
|
||||
fileHostReplaced: boolean
|
||||
header: string
|
||||
replacedLevels: string[]
|
||||
}
|
||||
}
|
||||
|
||||
export function classifySessionSwitch(samples: SessionSwitchSample[]) {
|
||||
const firstDestination = samples.findIndex((sample) => sample.destination.length > 0)
|
||||
const firstCorrect = samples.findIndex(isCorrectDestination)
|
||||
const stable = samples.findIndex((_, index) => isStableSessionSwitch(samples.slice(index, index + 3)))
|
||||
|
||||
return {
|
||||
samples,
|
||||
firstDestinationObservedMs: samples[firstDestination]?.observedAtMs ?? null,
|
||||
firstCorrectObservedMs: samples[firstCorrect]?.observedAtMs ?? null,
|
||||
stableObservedMs: stable < 0 ? null : samples[stable + 2].observedAtMs,
|
||||
wrongDestinationSamples: samples
|
||||
.slice(firstDestination)
|
||||
.filter((sample) => sample.destination.length > 0 && !sample.last).length,
|
||||
blankSamples: samples.filter((sample) => !sample.hasVisibleRows).length,
|
||||
unknownSamples: samples.filter(
|
||||
(sample) => sample.hasVisibleRows && sample.destination.length === 0 && sample.source.length === 0,
|
||||
).length,
|
||||
sourceSamples: samples.filter((sample) => sample.source.length > 0).length,
|
||||
reviewFileHostMissingSamples: samples.filter((sample) => sample.review && !sample.review.fileHost).length,
|
||||
reviewFileHostReplacedSamples: samples.filter((sample) => sample.review?.fileHostReplaced).length,
|
||||
reviewHeaders: [...new Set(samples.flatMap((sample) => (sample.review ? [sample.review.header] : [])))],
|
||||
reviewReplacedLevels: [...new Set(samples.flatMap((sample) => sample.review?.replacedLevels ?? []))],
|
||||
}
|
||||
}
|
||||
|
||||
export function isCorrectDestination(sample: SessionSwitchSample) {
|
||||
return (
|
||||
sample.destination.length > 0 &&
|
||||
sample.source.length === 0 &&
|
||||
sample.last &&
|
||||
sample.requiredPartVisible !== false &&
|
||||
(sample.bottomAnchorRequired === false || Math.abs(sample.bottomErrorPx ?? Infinity) <= 1)
|
||||
)
|
||||
}
|
||||
|
||||
export function isStableSessionSwitch(samples: SessionSwitchSample[]) {
|
||||
return samples.length === 3 && samples.every(isCorrectDestination)
|
||||
}
|
||||
|
||||
export function isStableDestination(samples: Pick<SessionSwitchSample, "last" | "bottomErrorPx">[]) {
|
||||
return (
|
||||
samples.length === 3 && samples.every((sample) => sample.last && Math.abs(sample.bottomErrorPx ?? Infinity) <= 1)
|
||||
)
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
import { measureSessionSwitch } from "./session-tab-switch-probe"
|
||||
import type { SessionSwitchSample } from "./session-tab-switch-metrics"
|
||||
|
||||
for (const tag of ["a", "button"] as const) {
|
||||
benchmark(
|
||||
`starts at ${tag} mousedown and excludes hidden or unfinished destination content`,
|
||||
async ({ page, report }) => {
|
||||
await page.setContent(`
|
||||
<${tag} id="destination" ${tag === "a" ? 'href="/session/destination"' : 'type="button"'}>Destination</${tag}>
|
||||
<div class="scroll-view__viewport" style="height:200px;overflow:auto">
|
||||
<div data-timeline-row="message" data-timeline-key="row" data-message-id="source">
|
||||
<div data-timeline-part-id="answer"><div data-component="markdown">Destination answer</div></div>
|
||||
</div>
|
||||
</div>
|
||||
`)
|
||||
await page.evaluate(() => {
|
||||
document.querySelector("#destination")!.addEventListener("mousedown", () => {
|
||||
const row = document.querySelector<HTMLElement>("[data-message-id]")!
|
||||
row.dataset.messageId = "destination"
|
||||
row.style.visibility = "hidden"
|
||||
})
|
||||
})
|
||||
|
||||
const result = await measureSessionSwitch(page, {
|
||||
destinationIDs: ["destination"],
|
||||
sourceIDs: ["source"],
|
||||
lastID: "destination",
|
||||
requiredPartID: "answer",
|
||||
requireBottomAnchor: false,
|
||||
href: "/session/destination",
|
||||
triggerSelector: tag === "button" ? "#destination" : undefined,
|
||||
switch: async () => {
|
||||
// No click is dispatched: the probe must observe the event that activates tabs.
|
||||
await page
|
||||
.getByRole(tag === "a" ? "link" : "button", { name: "Destination", exact: true })
|
||||
.dispatchEvent("mousedown", { button: 0 })
|
||||
await page.waitForFunction(() => {
|
||||
const host = window as Window & { __sessionSwitchProbe?: { samples: SessionSwitchSample[] } }
|
||||
|
||||
return host.__sessionSwitchProbe?.samples.some((sample) => !sample.hasVisibleRows)
|
||||
})
|
||||
await page.locator("[data-message-id]").evaluate((row) => row.style.removeProperty("visibility"))
|
||||
await page.waitForFunction(() => {
|
||||
const host = window as Window & { __sessionSwitchProbe?: { samples: SessionSwitchSample[] } }
|
||||
|
||||
return host.__sessionSwitchProbe?.samples.some(
|
||||
(sample) => sample.destination.length > 0 && sample.requiredPartVisible === false,
|
||||
)
|
||||
})
|
||||
|
||||
const beforeClip = await page.evaluate(() => {
|
||||
const row = document.querySelector<HTMLElement>("[data-timeline-key]")!
|
||||
row.style.cssText = "height:10px;position:relative;overflow:clip"
|
||||
const answer = row.querySelector<HTMLElement>("[data-timeline-part-id]")!
|
||||
answer.style.cssText = "position:absolute;top:30px;width:150px"
|
||||
answer.querySelector('[data-component="markdown"]')!.setAttribute("data-markdown-ready", "")
|
||||
|
||||
return (
|
||||
(window as Window & { __sessionSwitchProbe?: { samples: SessionSwitchSample[] } }).__sessionSwitchProbe
|
||||
?.samples.length ?? 0
|
||||
)
|
||||
})
|
||||
|
||||
await page.waitForFunction((count) => {
|
||||
const host = window as Window & { __sessionSwitchProbe?: { samples: SessionSwitchSample[] } }
|
||||
|
||||
return host.__sessionSwitchProbe?.samples
|
||||
.slice(count)
|
||||
.some((sample) => sample.requiredPartVisible === false)
|
||||
}, beforeClip)
|
||||
await page.locator("[data-timeline-key]").evaluate((row) => {
|
||||
row.style.height = "100px"
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.blankSamples).toBeGreaterThan(0)
|
||||
expect(result.firstCorrectObservedMs).not.toBeNull()
|
||||
expect(result.stableObservedMs).not.toBeNull()
|
||||
expect(result.firstCorrectObservedMs).toBeGreaterThan(result.firstDestinationObservedMs!)
|
||||
expect(await page.evaluate(() => "__sessionSwitchProbe" in window)).toBe(false)
|
||||
report(result)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
@ -1,292 +0,0 @@
|
|||
import { expect, type Page } from "@playwright/test"
|
||||
import { classifySessionSwitch, isStableDestination, type SessionSwitchSample } from "./session-tab-switch-metrics"
|
||||
|
||||
type SessionSwitchProbe = {
|
||||
samples: SessionSwitchSample[]
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
async function installSessionSwitchProbe(
|
||||
page: Page,
|
||||
input: {
|
||||
destinationIDs: string[]
|
||||
sourceIDs: string[]
|
||||
lastID: string
|
||||
requiredPartID?: string
|
||||
requireBottomAnchor?: boolean
|
||||
triggerSelector?: string
|
||||
href: string
|
||||
},
|
||||
) {
|
||||
await page.evaluate(
|
||||
({ destinationIDs, sourceIDs, lastID, requiredPartID, requireBottomAnchor, triggerSelector, href }) => {
|
||||
const destination = new Set(destinationIDs)
|
||||
const source = new Set(sourceIDs)
|
||||
const samples: SessionSwitchSample[] = []
|
||||
let started: number | undefined
|
||||
let running = true
|
||||
|
||||
const reviewLevels: Record<string, string> = {
|
||||
panel: "#review-panel",
|
||||
tabs: '#review-panel [data-component="tabs"]',
|
||||
body: '#review-panel [data-slot="session-review-v2-body"]',
|
||||
review: '#review-panel [data-component="session-review-v2"]',
|
||||
preview: '#review-panel [data-slot="session-review-v2-preview"]',
|
||||
scroll: '#review-panel [data-slot="session-review-v2-diff-scroll"]',
|
||||
file: '#review-panel [data-component="file"][data-mode="diff"]',
|
||||
}
|
||||
|
||||
const initialReviewNodes: Record<string, Element | null> = {}
|
||||
|
||||
const sample = () => {
|
||||
if (!running || started === undefined) return
|
||||
setTimeout(() => {
|
||||
if (!running || started === undefined) return
|
||||
const reviewPanel = document.querySelector<HTMLElement>("#review-panel")
|
||||
const reviewFile = reviewPanel?.querySelector('[data-component="file"][data-mode="diff"]')
|
||||
const initialReviewFile = initialReviewNodes.file
|
||||
|
||||
const replacedLevels = Object.entries(reviewLevels).flatMap(([name, selector]) => {
|
||||
const initial = initialReviewNodes[name]
|
||||
|
||||
if (!initial) return []
|
||||
const current = document.querySelector(selector)
|
||||
|
||||
return current && current !== initial ? [name] : []
|
||||
})
|
||||
|
||||
const review = reviewPanel
|
||||
? {
|
||||
fileHost: !!reviewFile,
|
||||
fileHostReplaced: !!initialReviewFile && !!reviewFile && reviewFile !== initialReviewFile,
|
||||
header:
|
||||
reviewPanel
|
||||
.querySelector<HTMLElement>('[data-slot="session-review-v2-file-header"]')
|
||||
?.textContent?.trim() ?? "",
|
||||
replacedLevels,
|
||||
}
|
||||
: undefined
|
||||
|
||||
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
|
||||
element.querySelector("[data-timeline-row]"),
|
||||
)
|
||||
|
||||
if (root) {
|
||||
const view = root.getBoundingClientRect()
|
||||
|
||||
const inViewport = (element: HTMLElement) => {
|
||||
if (!element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) return false
|
||||
const rect = element.getBoundingClientRect()
|
||||
const clip = element.closest<HTMLElement>("[data-timeline-key]")?.getBoundingClientRect() ?? view
|
||||
|
||||
return (
|
||||
Math.min(rect.bottom, clip.bottom, view.bottom) > Math.max(rect.top, clip.top, view.top) &&
|
||||
Math.min(rect.right, clip.right, view.right) > Math.max(rect.left, clip.left, view.left)
|
||||
)
|
||||
}
|
||||
|
||||
const visible = [...root.querySelectorAll<HTMLElement>("[data-message-id]")]
|
||||
.filter(inViewport)
|
||||
.map((element) => element.dataset.messageId!)
|
||||
|
||||
const hasVisibleRows = [...root.querySelectorAll<HTMLElement>("[data-timeline-key]")].some(inViewport)
|
||||
|
||||
const requiredPartVisible = requiredPartID
|
||||
? [...root.querySelectorAll<HTMLElement>("[data-timeline-part-id]")].some((element) => {
|
||||
if (element.dataset.timelinePartId !== requiredPartID) return false
|
||||
|
||||
if (!element.textContent?.trim()) return false
|
||||
|
||||
if (element.querySelector('[data-component="markdown"]:not([data-markdown-ready])')) return false
|
||||
|
||||
return inViewport(element)
|
||||
})
|
||||
: undefined
|
||||
|
||||
const spacer = root
|
||||
.querySelector<HTMLElement>('[data-timeline-row="bottom-spacer"]')
|
||||
?.getBoundingClientRect()
|
||||
|
||||
samples.push({
|
||||
observedAtMs: performance.now() - started,
|
||||
destination: visible.filter((id) => destination.has(id)),
|
||||
source: visible.filter((id) => source.has(id)),
|
||||
hasVisibleRows,
|
||||
last: visible.includes(lastID),
|
||||
requiredPartVisible,
|
||||
bottomAnchorRequired: requireBottomAnchor !== false,
|
||||
bottomErrorPx: spacer ? spacer.bottom - view.bottom : undefined,
|
||||
review,
|
||||
})
|
||||
} else {
|
||||
samples.push({
|
||||
observedAtMs: performance.now() - started,
|
||||
destination: [],
|
||||
source: [],
|
||||
hasVisibleRows: false,
|
||||
last: false,
|
||||
requiredPartVisible: requiredPartID ? false : undefined,
|
||||
bottomAnchorRequired: requireBottomAnchor !== false,
|
||||
review,
|
||||
})
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
const start = (event: MouseEvent) => {
|
||||
if (started !== undefined || event.button !== 0) return
|
||||
const trigger = event.target instanceof Element ? event.target.closest(triggerSelector ?? "a") : undefined
|
||||
|
||||
if (!trigger || (!triggerSelector && trigger.getAttribute("href") !== href)) return
|
||||
started = performance.now()
|
||||
performance.mark("session-switch:start", { startTime: started })
|
||||
|
||||
for (const [name, selector] of Object.entries(reviewLevels)) {
|
||||
initialReviewNodes[name] = document.querySelector(selector)
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
}
|
||||
|
||||
// Tabs activate on mousedown; click alone misses the synchronous navigation work.
|
||||
document.addEventListener("mousedown", start, true)
|
||||
document.addEventListener("click", start, true)
|
||||
;(window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe = {
|
||||
samples,
|
||||
stop: () => {
|
||||
running = false
|
||||
document.removeEventListener("mousedown", start, true)
|
||||
document.removeEventListener("click", start, true)
|
||||
Object.keys(initialReviewNodes).forEach((key) => (initialReviewNodes[key] = null))
|
||||
},
|
||||
}
|
||||
},
|
||||
input,
|
||||
)
|
||||
}
|
||||
|
||||
async function waitForStableSessionSwitch(page: Page) {
|
||||
await page.waitForFunction(() => {
|
||||
const samples = (window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe?.samples
|
||||
|
||||
if (!samples) return false
|
||||
|
||||
return samples.some((_, index) => {
|
||||
const stable = samples.slice(index, index + 3)
|
||||
|
||||
return (
|
||||
stable.length === 3 &&
|
||||
stable.every(
|
||||
(sample) =>
|
||||
sample.destination.length > 0 &&
|
||||
sample.source.length === 0 &&
|
||||
sample.last &&
|
||||
sample.requiredPartVisible !== false &&
|
||||
(sample.bottomAnchorRequired === false || Math.abs(sample.bottomErrorPx ?? Infinity) <= 1),
|
||||
)
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function collectSessionSwitchResult(page: Page) {
|
||||
const samples = await page.evaluate(() => {
|
||||
const probe = (window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe!
|
||||
probe.stop()
|
||||
delete (window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe
|
||||
|
||||
return probe.samples
|
||||
})
|
||||
|
||||
const result = classifySessionSwitch(samples)
|
||||
await page.evaluate(({ firstCorrectObservedMs, stableObservedMs }) => {
|
||||
const start = performance.getEntriesByName("session-switch:start").at(-1)!.startTime
|
||||
|
||||
if (firstCorrectObservedMs !== null)
|
||||
performance.mark("session-switch:ready", { startTime: start + firstCorrectObservedMs })
|
||||
|
||||
if (stableObservedMs !== null) performance.mark("session-switch:stable", { startTime: start + stableObservedMs })
|
||||
}, result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export async function measureSessionSwitch(
|
||||
page: Page,
|
||||
input: {
|
||||
destinationIDs: string[]
|
||||
sourceIDs: string[]
|
||||
lastID: string
|
||||
requiredPartID?: string
|
||||
requireBottomAnchor?: boolean
|
||||
triggerSelector?: string
|
||||
href: string
|
||||
switch: () => Promise<void>
|
||||
},
|
||||
) {
|
||||
const { switch: run, ...probe } = input
|
||||
await installSessionSwitchProbe(page, probe)
|
||||
|
||||
try {
|
||||
await run()
|
||||
await waitForStableSessionSwitch(page)
|
||||
|
||||
return await collectSessionSwitchResult(page)
|
||||
} finally {
|
||||
await page.evaluate(() => {
|
||||
;(window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe?.stop()
|
||||
delete (window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function waitForStableTimeline(page: Page, lastID: string) {
|
||||
const samples: Pick<SessionSwitchSample, "last" | "bottomErrorPx">[] = []
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
samples.push(
|
||||
await page.evaluate(
|
||||
(lastID) =>
|
||||
new Promise<Pick<SessionSwitchSample, "last" | "bottomErrorPx">>((resolve) => {
|
||||
requestAnimationFrame(() =>
|
||||
setTimeout(() => {
|
||||
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
|
||||
element.querySelector("[data-timeline-row]"),
|
||||
)
|
||||
|
||||
if (!root) {
|
||||
resolve({ last: false })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const view = root.getBoundingClientRect()
|
||||
|
||||
const last = [...root.querySelectorAll<HTMLElement>("[data-message-id]")].some((element) => {
|
||||
if (element.dataset.messageId !== lastID) return false
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
return rect.bottom > view.top && rect.top < view.bottom
|
||||
})
|
||||
|
||||
const spacer = root
|
||||
.querySelector<HTMLElement>('[data-timeline-row="bottom-spacer"]')
|
||||
?.getBoundingClientRect()
|
||||
|
||||
resolve({ last, bottomErrorPx: spacer ? spacer.bottom - view.bottom : undefined })
|
||||
}, 0),
|
||||
)
|
||||
}),
|
||||
lastID,
|
||||
),
|
||||
)
|
||||
|
||||
return isStableDestination(samples.slice(-3))
|
||||
},
|
||||
{ timeout: 30_000, intervals: [0] },
|
||||
)
|
||||
.toBe(true)
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
import { exchanges, messages } from "../../utils/markdown-sessions"
|
||||
|
||||
export const workload = {
|
||||
fixture: "long-complex-markdown-v1",
|
||||
exchangesPerSession: exchanges,
|
||||
messagesPerSession: exchanges * 2,
|
||||
history: "full fixture history in one response",
|
||||
sessions: Object.fromEntries(
|
||||
Object.entries(messages).map(([sessionID, items]) => [
|
||||
sessionID,
|
||||
{
|
||||
payloadBytes: Buffer.byteLength(JSON.stringify(items)),
|
||||
markdownBytes: items.reduce(
|
||||
(total, message) =>
|
||||
total +
|
||||
(message.type === "assistant"
|
||||
? message.content.reduce(
|
||||
(size, part) => size + (part.type === "text" ? Buffer.byteLength(part.text) : 0),
|
||||
0,
|
||||
)
|
||||
: 0),
|
||||
0,
|
||||
),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}
|
||||
|
|
@ -1,561 +0,0 @@
|
|||
import { base64Encode } from "@opencode/util/encode"
|
||||
import type { JsonValue, OpenCodeEvent, SessionMessageAssistant, SessionMessageInfo } from "@opencode/client/promise"
|
||||
import type { Page } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||
import { expectAppVisible, expectSessionTitle } from "../../utils/waits"
|
||||
import { expect } from "../benchmark"
|
||||
import { createTwoFilesPatch } from "diff"
|
||||
|
||||
const directory = "C:/OpenCode/TimelineStateRegression"
|
||||
|
||||
const projectID = "proj_timeline_state_regression"
|
||||
|
||||
/** The workspace a benchmark response names, in the shape the server's location-scoped routes return. */
|
||||
export const benchmarkLocation = { directory, project: { id: projectID, directory, canonical: directory } }
|
||||
|
||||
const sessionID = "ses_timeline_state_regression"
|
||||
|
||||
const userMessageID = "msg_user_regression"
|
||||
|
||||
const assistantMessageID = "msg_assistant_regression"
|
||||
|
||||
const editPartID = "prt_0001_edit"
|
||||
|
||||
export const textPartID = `${assistantMessageID}:text:0`
|
||||
|
||||
const title = "Timeline collapse state regression"
|
||||
|
||||
const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
|
||||
|
||||
type EventPayload = OpenCodeEvent
|
||||
|
||||
const userMessage = {
|
||||
id: userMessageID,
|
||||
type: "user",
|
||||
time: { created: 1700000000000 },
|
||||
text: "Please edit the file.",
|
||||
} satisfies SessionMessageInfo
|
||||
|
||||
const editPart: ToolSeed = {
|
||||
id: editPartID,
|
||||
type: "tool",
|
||||
name: "edit",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: {
|
||||
path: "src/regression.ts",
|
||||
oldString: "export const value = 'before'",
|
||||
newString: "export const value = 'after'",
|
||||
},
|
||||
content: [{ type: "text", text: "Edited src/regression.ts" }],
|
||||
metadata: {
|
||||
files: [
|
||||
currentFile("src/regression.ts", "export const value = 'before'\n", "export const value = 'after'\n", 1, 1),
|
||||
],
|
||||
},
|
||||
},
|
||||
time: { created: 1700000001000, ran: 1700000001000, completed: 1700000002000 },
|
||||
}
|
||||
|
||||
const assistantMessage = {
|
||||
id: assistantMessageID,
|
||||
type: "assistant",
|
||||
time: { created: 1700000001000 },
|
||||
model: { id: model.modelID, providerID: model.providerID, variant: model.variant },
|
||||
agent: "build",
|
||||
cost: 0.01,
|
||||
tokens: { input: 100, output: 200, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
content: [toolContent(editPart)],
|
||||
} satisfies SessionMessageInfo
|
||||
|
||||
export async function setupTimelineBenchmark(
|
||||
page: Page,
|
||||
options: {
|
||||
historyTurns: number
|
||||
eventBatch: number
|
||||
vcsDiff?: unknown[]
|
||||
turnDiffs?: unknown[]
|
||||
busy?: boolean
|
||||
historyShape?: "mixed" | "tool-heavy"
|
||||
},
|
||||
) {
|
||||
const events: EventPayload[] = []
|
||||
let eventBatch = options.eventBatch
|
||||
|
||||
const currentUserMessage = options.turnDiffs
|
||||
? { ...userMessage, metadata: { diffs: options.turnDiffs as JsonValue } }
|
||||
: userMessage
|
||||
|
||||
const messages = [
|
||||
...Array.from({ length: options.historyTurns }, (_, index) => performanceTurn(index))
|
||||
.flat()
|
||||
.map((message) => {
|
||||
if (options.historyShape !== "tool-heavy" || message.type !== "assistant") return message
|
||||
|
||||
return {
|
||||
...message,
|
||||
content: [
|
||||
...Array.from({ length: 6 }, (_, index) =>
|
||||
toolContent({
|
||||
id: `${message.id}:read:${index}`,
|
||||
type: "tool",
|
||||
name: "read",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { path: `src/session/module-${index}.ts` },
|
||||
content: [{ type: "text", text: historicalSource(index, false) }],
|
||||
metadata: {},
|
||||
},
|
||||
time: {
|
||||
created: message.time.created,
|
||||
ran: message.time.created,
|
||||
completed: message.time.created + 100,
|
||||
},
|
||||
}),
|
||||
),
|
||||
...message.content,
|
||||
],
|
||||
}
|
||||
}),
|
||||
currentUserMessage,
|
||||
assistantMessage,
|
||||
]
|
||||
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: project(),
|
||||
provider: provider(),
|
||||
sessions: [session()],
|
||||
vcsDiff: options.vcsDiff,
|
||||
sessionStatus: options.busy ? { [sessionID]: { type: "busy" } } : undefined,
|
||||
pageMessages: () => ({ items: messages }),
|
||||
events: () => events.splice(0, eventBatch),
|
||||
eventRetry: 16,
|
||||
})
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"settings.v3",
|
||||
JSON.stringify({
|
||||
general: {
|
||||
editToolPartsExpanded: true,
|
||||
shellToolPartsExpanded: true,
|
||||
showReasoningSummaries: true,
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
await page.setViewportSize({ width: 1366, height: 768 })
|
||||
const scroller = page.locator(".scroll-view__viewport", { has: page.locator("[data-timeline-row]") })
|
||||
const text = page.locator(`[data-timeline-part-id="${textPartID}"]`).first()
|
||||
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
|
||||
await expectSessionTitle(page, title)
|
||||
await expectAppVisible(scroller)
|
||||
|
||||
return {
|
||||
workload: {
|
||||
messages: messages.length,
|
||||
parts: messages.reduce((sum, message) => sum + (message.type === "assistant" ? message.content.length : 0), 0),
|
||||
historyBytes: Buffer.byteLength(JSON.stringify(messages)),
|
||||
},
|
||||
scroller,
|
||||
text,
|
||||
transport: {
|
||||
enqueue(payload: EventPayload | EventPayload[]) {
|
||||
events.push(...(Array.isArray(payload) ? payload : [payload]))
|
||||
},
|
||||
pendingCount() {
|
||||
return events.length
|
||||
},
|
||||
releaseAll() {
|
||||
eventBatch = events.length
|
||||
},
|
||||
},
|
||||
async scrollToBottom() {
|
||||
await scroller.evaluate((element) => {
|
||||
element.scrollTop = element.scrollHeight
|
||||
})
|
||||
},
|
||||
async waitForStableGeometry() {
|
||||
await expect
|
||||
.poll(() => scroller.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop))
|
||||
.toBeLessThanOrEqual(1)
|
||||
await page.waitForFunction((partID) => {
|
||||
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
|
||||
element.querySelector(`[data-timeline-part-id="${partID}"]`),
|
||||
)
|
||||
|
||||
if (!root) return false
|
||||
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const height = root.scrollHeight
|
||||
requestAnimationFrame(() =>
|
||||
requestAnimationFrame(() =>
|
||||
resolve(root.scrollHeight === height && root.scrollHeight - root.clientHeight - root.scrollTop <= 1),
|
||||
),
|
||||
)
|
||||
})
|
||||
}, textPartID)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function buildInitialStreamEvent(deltaCount: number): EventPayload[] {
|
||||
return [
|
||||
timelineEvent("session.text.started", { sessionID, assistantMessageID, ordinal: 0 }, true),
|
||||
timelineEvent("session.text.delta", {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
ordinal: 0,
|
||||
delta: `Streaming${streamChunk(0, deltaCount + 1)}\n\n\`\`\`ts\nconst initial = true\n\`\`\``,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
export function buildStreamDeltaEvents(deltaCount: number): EventPayload[] {
|
||||
return Array.from({ length: deltaCount }, (_, index) =>
|
||||
timelineEvent("session.text.delta", {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
ordinal: 0,
|
||||
delta: streamChunk(index + 1, deltaCount + 1),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function performanceTurn(index: number) {
|
||||
const suffix = String(index).padStart(4, "0")
|
||||
const userID = `msg_0000_${suffix}_a_user`
|
||||
const assistantID = `msg_0000_${suffix}_b_assistant`
|
||||
const before = historicalSource(index, false)
|
||||
const after = historicalSource(index, true)
|
||||
|
||||
const parts = [
|
||||
...(index % 5 === 0
|
||||
? [
|
||||
{
|
||||
id: `prt_0000_${suffix}_reasoning`,
|
||||
sessionID,
|
||||
messageID: assistantID,
|
||||
type: "reasoning",
|
||||
text: `Reviewing the existing implementation. ${"constraint analysis ".repeat(20)}`,
|
||||
time: { start: 1690000001000 + index * 2_000, end: 1690000001200 + index * 2_000 },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
id: `prt_0000_${suffix}_assistant`,
|
||||
sessionID,
|
||||
messageID: assistantID,
|
||||
type: "text",
|
||||
text: historicalMarkdown(index),
|
||||
},
|
||||
...(index % 8 === 0
|
||||
? [
|
||||
{
|
||||
id: `prt_0000_${suffix}_edit`,
|
||||
type: "tool",
|
||||
name: "edit",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { path: `src/history-${index}.ts`, oldString: before, newString: after },
|
||||
content: [{ type: "text", text: `Edited src/history-${index}.ts` }],
|
||||
metadata: {
|
||||
files: [currentFile(`src/history-${index}.ts`, before, after, 48, 48)],
|
||||
},
|
||||
},
|
||||
time: {
|
||||
created: 1690000001200 + index * 2_000,
|
||||
ran: 1690000001200 + index * 2_000,
|
||||
completed: 1690000001400 + index * 2_000,
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(index % 12 === 0
|
||||
? [
|
||||
{
|
||||
id: `prt_0000_${suffix}_write`,
|
||||
type: "tool",
|
||||
name: "write",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { path: `src/generated-${index}.tsx`, content: after },
|
||||
content: [{ type: "text", text: `Wrote src/generated-${index}.tsx` }],
|
||||
metadata: { files: [currentFile(`src/generated-${index}.tsx`, "", after, 32, 0)] },
|
||||
},
|
||||
time: {
|
||||
created: 1690000001400 + index * 2_000,
|
||||
ran: 1690000001400 + index * 2_000,
|
||||
completed: 1690000001500 + index * 2_000,
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(index % 16 === 0
|
||||
? [
|
||||
{
|
||||
id: `prt_0000_${suffix}_patch`,
|
||||
type: "tool",
|
||||
name: "patch",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { patchText: realisticPatch(index) },
|
||||
content: [{ type: "text", text: "Success. Updated src/components/SessionCard.tsx" }],
|
||||
metadata: {
|
||||
files: [
|
||||
{
|
||||
...currentFile("src/components/SessionCard.tsx", before, after, 8, 3),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
time: {
|
||||
created: 1690000001500 + index * 2_000,
|
||||
ran: 1690000001500 + index * 2_000,
|
||||
completed: 1690000001700 + index * 2_000,
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
] as unknown as ContentSeed[]
|
||||
|
||||
return [
|
||||
{
|
||||
id: userID,
|
||||
type: "user",
|
||||
time: { created: 1690000000000 + index * 2_000 },
|
||||
text: `Historical prompt ${index}`,
|
||||
},
|
||||
{
|
||||
id: assistantID,
|
||||
type: "assistant",
|
||||
time: { created: 1690000001000 + index * 2_000, completed: 1690000001500 + index * 2_000 },
|
||||
model: { id: model.modelID, providerID: model.providerID, variant: model.variant },
|
||||
agent: "build",
|
||||
cost: 0.01,
|
||||
tokens: { input: 100, output: 200, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
finish: "stop",
|
||||
content: parts.map((part) => {
|
||||
if (part.type === "text") return { type: "text" as const, text: part.text }
|
||||
|
||||
if (part.type === "reasoning")
|
||||
return {
|
||||
type: "reasoning" as const,
|
||||
text: part.text,
|
||||
time: { created: part.time.start, completed: part.time.end },
|
||||
}
|
||||
|
||||
return toolContent(part)
|
||||
}),
|
||||
},
|
||||
] satisfies SessionMessageInfo[]
|
||||
}
|
||||
|
||||
type ToolSeed = {
|
||||
id: string
|
||||
type: "tool"
|
||||
name: string
|
||||
state: {
|
||||
status: "completed"
|
||||
input: Record<string, unknown>
|
||||
content: [{ type: "text"; text: string }]
|
||||
metadata: Record<string, unknown>
|
||||
}
|
||||
time: { created: number; ran: number; completed: number }
|
||||
}
|
||||
|
||||
type ContentSeedBase = { id?: string; sessionID?: string; messageID?: string }
|
||||
|
||||
type ContentSeed =
|
||||
| (ContentSeedBase & { type: "text"; text: string })
|
||||
| (ContentSeedBase & { type: "reasoning"; text: string; time: { start: number; end: number } })
|
||||
| ToolSeed
|
||||
|
||||
function toolContent(part: ToolSeed): SessionMessageAssistant["content"][number] {
|
||||
return {
|
||||
type: "tool",
|
||||
id: part.id,
|
||||
name: part.name,
|
||||
time: part.time,
|
||||
state: {
|
||||
status: "completed",
|
||||
input: part.state.input as Record<string, JsonValue>,
|
||||
content: part.state.content,
|
||||
metadata: part.state.metadata as Record<string, JsonValue>,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let eventSequence = 0
|
||||
|
||||
function timelineEvent<Type extends "session.text.started" | "session.text.delta">(
|
||||
type: Type,
|
||||
data: Extract<OpenCodeEvent, { type: Type }>["data"],
|
||||
durable = false,
|
||||
): Extract<OpenCodeEvent, { type: Type }> {
|
||||
eventSequence++
|
||||
|
||||
return {
|
||||
id: `evt_timeline_benchmark_${eventSequence}`,
|
||||
created: 1700000002000 + eventSequence,
|
||||
type,
|
||||
data,
|
||||
location: { directory },
|
||||
...(durable ? { durable: { aggregateID: sessionID, seq: eventSequence, version: 1 } } : {}),
|
||||
} as unknown as Extract<OpenCodeEvent, { type: Type }>
|
||||
}
|
||||
|
||||
function historicalMarkdown(index: number) {
|
||||
const code = `import { For, Show, createSignal } from "solid-js"
|
||||
|
||||
type SessionRow = { id: string; title: string; active: boolean }
|
||||
|
||||
export function SessionList(props: { rows: SessionRow[] }) {
|
||||
const [selected, setSelected] = createSignal<string>()
|
||||
return (
|
||||
<section aria-label="Sessions">
|
||||
<For each={props.rows}>{(row) => (
|
||||
<button classList={{ active: row.active }} onClick={() => setSelected(row.id)}>
|
||||
<Show when={selected() === row.id} fallback={row.title}>{row.title.toUpperCase()}</Show>
|
||||
</button>
|
||||
)}</For>
|
||||
</section>
|
||||
)
|
||||
}`
|
||||
|
||||
return `## Session renderer review ${index}
|
||||
|
||||
The active session keeps **semantic row identity** while reconciling measured content. See [Solid documentation](https://docs.solidjs.com/) and the inline \`measureElement(node)\` call.
|
||||
|
||||
| Concern | Current behavior | Verification |
|
||||
| --- | --- | --- |
|
||||
| streaming | appends Markdown blocks | painted frames |
|
||||
| geometry | anchors visible rows | DOM coordinates |
|
||||
| tools | preserves expanded state | keyed remount probe |
|
||||
|
||||
> Long sessions combine Markdown, syntax highlighting, tool output, and asynchronously rendered diffs.
|
||||
|
||||
${index % 4 === 0 ? `\`\`\`tsx\n${code}\n\`\`\`\n\n\`\`\`bash\nbun typecheck\nbun test --preload ./happydom.ts ./src/pages/session\ngit diff --check\n\`\`\`` : "- preserve the viewport anchor\n- avoid replacing stable Markdown nodes\n- process provider deltas without blocking input"}`
|
||||
}
|
||||
|
||||
function historicalSource(index: number, updated: boolean) {
|
||||
const method = updated ? "toLocaleUpperCase(props.locale)" : "toUpperCase()"
|
||||
const limit = updated ? 24 : 20
|
||||
|
||||
return `import { createMemo, For } from "solid-js"
|
||||
|
||||
type Message = {
|
||||
id: string
|
||||
role: "user" | "assistant"
|
||||
text: string
|
||||
tokens: { input: number; output: number }
|
||||
}
|
||||
|
||||
export function MessageSummary(props: { messages: Message[]; locale: string }) {
|
||||
const visible = createMemo(() => props.messages.filter((message) => message.text.trim()).slice(-${limit}))
|
||||
const total = createMemo(() => visible().reduce((sum, message) => sum + message.tokens.output, 0))
|
||||
return (
|
||||
<article data-session-index="${index}">
|
||||
<header>{total().toLocaleString(props.locale)} output tokens</header>
|
||||
<For each={visible()}>{(message) => <p data-role={message.role}>{message.text.${method}}</p>}</For>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
`
|
||||
}
|
||||
|
||||
function currentFile(file: string, before: string, after: string, additions: number, deletions: number) {
|
||||
return {
|
||||
file,
|
||||
patch: createTwoFilesPatch(`a/${file}`, `b/${file}`, before, after),
|
||||
additions,
|
||||
deletions,
|
||||
status: before ? (after ? "modified" : "deleted") : "added",
|
||||
}
|
||||
}
|
||||
|
||||
function realisticPatch(index: number) {
|
||||
return `*** Begin Patch
|
||||
*** Update File: src/components/SessionCard.tsx
|
||||
@@
|
||||
-const title = props.session.title.toUpperCase()
|
||||
-const messages = props.messages.slice(-20)
|
||||
+const title = props.session.title.toLocaleUpperCase(props.locale)
|
||||
+const messages = props.messages.filter((message) => message.text.trim()).slice(-24)
|
||||
+const outputTokens = messages.reduce((sum, message) => sum + message.tokens.output, 0)
|
||||
@@
|
||||
- <h2>{title}</h2>
|
||||
+ <h2 data-session-index="${index}">{title}</h2>
|
||||
+ <span>{outputTokens.toLocaleString(props.locale)} output tokens</span>
|
||||
*** End Patch`
|
||||
}
|
||||
|
||||
export function streamChunk(index: number, count: number) {
|
||||
if (index === 0) return `\n\n## Implementation plan\n\nStreaming **bold analysis`
|
||||
|
||||
if (index === count - 1)
|
||||
return `\n\`\`\`\n\n## Verification\n\n- **Typecheck:** passed\n- **Timeline geometry:** stable\n- **Streaming output:** benchmark-complete <!-- stream-${index} -->`
|
||||
|
||||
const section = Math.floor(index / 18) + 1
|
||||
|
||||
const fragments = [
|
||||
` continues across three`,
|
||||
` or four word`,
|
||||
` provider deltas and`,
|
||||
` closes in this fragment**. <!-- stream-${index} -->\n\n`,
|
||||
`| Concern | State`,
|
||||
` | Verification |\n|`,
|
||||
` --- | ---`,
|
||||
` | --- |\n|`,
|
||||
` markdown | incremental |`,
|
||||
` painted frames | <!-- stream-${index} -->\n\n`,
|
||||
`\`\`\`tsx\nconst row: SessionRow`,
|
||||
` = rows[index] ??`,
|
||||
` fallback\nconst title =`,
|
||||
` row.title.toLocaleUpperCase(locale)\n`,
|
||||
`const selected = createMemo(()`,
|
||||
` => row.id ===`,
|
||||
` activeID()) // stream-${index}\n`,
|
||||
`// stream-${index}\n\`\`\`\n\n### Iteration ${section}\n\nStreaming **bold analysis`,
|
||||
]
|
||||
|
||||
return fragments[(index - 1) % fragments.length]!
|
||||
}
|
||||
|
||||
function project() {
|
||||
return {
|
||||
id: projectID,
|
||||
worktree: directory,
|
||||
vcs: "git",
|
||||
name: "timeline-state-regression",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
sandboxes: [],
|
||||
}
|
||||
}
|
||||
|
||||
function session() {
|
||||
return {
|
||||
id: sessionID,
|
||||
slug: "timeline-state-regression",
|
||||
projectID,
|
||||
directory,
|
||||
title,
|
||||
version: "dev",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
}
|
||||
}
|
||||
|
||||
function provider() {
|
||||
return {
|
||||
all: [
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
models: { "claude-opus-4-6": { id: "claude-opus-4-6", name: "Claude Opus 4.6", limit: { context: 200_000 } } },
|
||||
},
|
||||
],
|
||||
connected: ["opencode"],
|
||||
default: { providerID: "opencode", modelID: "claude-opus-4-6" },
|
||||
}
|
||||
}
|
||||
|
|
@ -1,319 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import { benchmark, benchmarkDiagnostics, expect } from "../benchmark"
|
||||
import {
|
||||
buildInitialStreamEvent,
|
||||
buildStreamDeltaEvents,
|
||||
setupTimelineBenchmark,
|
||||
textPartID,
|
||||
} from "./session-timeline-benchmark.fixture"
|
||||
import { startTimelineProfile } from "./session-timeline-profile"
|
||||
import { createReviewDiffs } from "./timeline-test-helpers"
|
||||
import {
|
||||
collectTimelineStreamMetrics,
|
||||
installTimelineStreamProbe,
|
||||
startTimelineStreamProbe,
|
||||
} from "./session-timeline-stream-probe"
|
||||
|
||||
type TimelineStreamOptions = {
|
||||
reviewDiffs?: boolean
|
||||
reviewPane?: boolean
|
||||
}
|
||||
|
||||
type ReviewPaneSample = {
|
||||
observedAtMs: number
|
||||
panelVisible: boolean
|
||||
header: string
|
||||
diffViewers: number
|
||||
diffLines: number
|
||||
codeBlocks: number
|
||||
ready: boolean
|
||||
}
|
||||
|
||||
type ReviewPaneProbe = {
|
||||
samples: ReviewPaneSample[]
|
||||
start: () => void
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
const reviewReadyStreak = 3
|
||||
|
||||
benchmark.describe("performance: session timeline streaming", () => {
|
||||
benchmark("streams assistant text without remounting or oscillating", async ({ page, report }) => {
|
||||
benchmark.setTimeout(Number(process.env.TIMELINE_COMPLETION_TIMEOUT_MS ?? 420_000) + 60_000)
|
||||
const result = await runTimelineStreamBenchmark(page, {})
|
||||
report(result.metrics, result.context)
|
||||
})
|
||||
|
||||
benchmark("streams assistant text with review diffs and pane closed", async ({ page, report }) => {
|
||||
benchmark.setTimeout(Number(process.env.TIMELINE_COMPLETION_TIMEOUT_MS ?? 420_000) + 60_000)
|
||||
const result = await runTimelineStreamBenchmark(page, { reviewDiffs: true })
|
||||
report(result.metrics, result.context)
|
||||
})
|
||||
|
||||
benchmark("streams assistant text with review pane open", async ({ page, report }) => {
|
||||
benchmark.setTimeout(Number(process.env.TIMELINE_COMPLETION_TIMEOUT_MS ?? 420_000) + 60_000)
|
||||
const result = await runTimelineStreamBenchmark(page, { reviewPane: true })
|
||||
report(result.metrics, result.context)
|
||||
})
|
||||
})
|
||||
|
||||
benchmark.describe("performance: review pane", () => {
|
||||
benchmark("loads review diffs and switches active files", async ({ page, report }) => {
|
||||
benchmark.setTimeout(240_000)
|
||||
const historyTurns = Number(process.env.REVIEW_PANE_HISTORY_TURNS ?? 72)
|
||||
const diffs = createReviewDiffs()
|
||||
|
||||
const fixture = await setupTimelineBenchmark(page, {
|
||||
historyTurns,
|
||||
eventBatch: 1,
|
||||
vcsDiff: diffs,
|
||||
})
|
||||
|
||||
fixture.transport.enqueue(buildInitialStreamEvent(1))
|
||||
await expect(fixture.text).toBeVisible()
|
||||
await expect(fixture.text).toContainText("Implementation plan")
|
||||
await fixture.scrollToBottom()
|
||||
await fixture.waitForStableGeometry()
|
||||
|
||||
const open = await measureReviewPaneLoad(page, diffs[0]!.file)
|
||||
const switches = []
|
||||
|
||||
for (const diff of diffs.slice(1, 4)) switches.push(await measureReviewNextFile(page, diff.file))
|
||||
|
||||
report(
|
||||
{
|
||||
open,
|
||||
switches,
|
||||
},
|
||||
{
|
||||
historyTurns,
|
||||
reviewDiffs: diffs.length,
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
async function runTimelineStreamBenchmark(page: Page, options: TimelineStreamOptions) {
|
||||
const completionTimeoutMs = Number(process.env.TIMELINE_COMPLETION_TIMEOUT_MS ?? 420_000)
|
||||
const cpuThrottle = Number(process.env.TIMELINE_CPU_THROTTLE ?? 30)
|
||||
const deltaCount = Number(process.env.TIMELINE_DELTA_COUNT ?? 160)
|
||||
const historyTurns = Number(process.env.TIMELINE_HISTORY_TURNS ?? 320)
|
||||
const eventBatch = Number(process.env.TIMELINE_EVENT_BATCH ?? 1)
|
||||
const minimal = process.env.TIMELINE_MINIMAL === "1"
|
||||
const profileCPU = process.env.TIMELINE_CPU_PROFILE === "1"
|
||||
const profileVisual = !minimal && profileCPU && process.env.TIMELINE_VISUAL_PROFILE !== "0"
|
||||
const diffs = options.reviewDiffs || options.reviewPane ? createReviewDiffs() : undefined
|
||||
|
||||
const fixture = await setupTimelineBenchmark(page, {
|
||||
historyTurns,
|
||||
eventBatch,
|
||||
// Turn diffs exercise timeline data cost; the pane-open scenario serves the same
|
||||
// diffs through the default git mode so it works across review implementations.
|
||||
turnDiffs: options.reviewDiffs ? diffs : undefined,
|
||||
vcsDiff: options.reviewPane ? diffs : undefined,
|
||||
})
|
||||
|
||||
fixture.transport.enqueue(buildInitialStreamEvent(deltaCount))
|
||||
const contentStart = performance.now()
|
||||
await expect(fixture.text).toBeVisible()
|
||||
await expect(fixture.text).toContainText("Implementation plan")
|
||||
const initialContentObservedMs = performance.now() - contentStart
|
||||
await fixture.scrollToBottom()
|
||||
await fixture.waitForStableGeometry()
|
||||
|
||||
const reviewPane = options.reviewPane && diffs ? await measureReviewPaneLoad(page, diffs[0]!.file) : undefined
|
||||
|
||||
if (reviewPane) await fixture.waitForStableGeometry()
|
||||
|
||||
const profile = await startTimelineProfile(page, { cpuThrottle, profileCPU })
|
||||
await installTimelineStreamProbe(page, { textPartID, finalIndex: deltaCount, profileVisual, minimal })
|
||||
const deltas = buildStreamDeltaEvents(deltaCount)
|
||||
await startTimelineStreamProbe(page)
|
||||
fixture.transport.enqueue(deltas)
|
||||
|
||||
await page.waitForFunction(
|
||||
(finalIndex) =>
|
||||
(
|
||||
window as Window & {
|
||||
__timelineStreamBenchmark?: { applied: { index: number }[] }
|
||||
}
|
||||
).__timelineStreamBenchmark?.applied.some((value) => value.index === finalIndex),
|
||||
deltaCount,
|
||||
{ timeout: completionTimeoutMs },
|
||||
)
|
||||
await expect(fixture.text).toContainText("benchmark-complete")
|
||||
await expect(fixture.text).toContainText("Streaming")
|
||||
await fixture.waitForStableGeometry()
|
||||
|
||||
const metrics = await collectTimelineStreamMetrics(page, {
|
||||
textPartID,
|
||||
finalIndex: deltaCount,
|
||||
navigations: benchmarkDiagnostics(page).navigations,
|
||||
})
|
||||
|
||||
const delivered = deltas.length - fixture.transport.pendingCount()
|
||||
await profile.stop()
|
||||
|
||||
const result = {
|
||||
metrics: {
|
||||
endToEndInitialContentObservedMs: initialContentObservedMs,
|
||||
...metrics,
|
||||
deliveredDeltas: delivered,
|
||||
pendingDeltas: fixture.transport.pendingCount(),
|
||||
reviewPane: reviewPane ?? null,
|
||||
},
|
||||
context: {
|
||||
cpuThrottle,
|
||||
profileCPU,
|
||||
profileVisual,
|
||||
minimal,
|
||||
queuedDeltas: deltas.length,
|
||||
historyTurns,
|
||||
eventBatch,
|
||||
reviewPane: options.reviewPane === true ? "open" : "closed",
|
||||
reviewDiffs: diffs?.length ?? 0,
|
||||
},
|
||||
}
|
||||
|
||||
await profile.reset()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async function measureReviewPaneLoad(page: Page, file: string) {
|
||||
// Default git mode reads the mocked /vcs/diff data, so opening the pane is enough
|
||||
// and the flow works across review pane implementations.
|
||||
await installReviewPaneProbe(page, { file })
|
||||
await startReviewPaneProbe(page)
|
||||
await page.getByRole("button", { name: "Toggle review" }).click()
|
||||
await expect(page.locator("#review-panel")).toBeVisible()
|
||||
|
||||
return collectReviewPaneProbe(page)
|
||||
}
|
||||
|
||||
async function measureReviewNextFile(page: Page, file: string) {
|
||||
await installReviewPaneProbe(page, { file })
|
||||
await startReviewPaneProbe(page)
|
||||
await page.getByRole("button", { name: "Next file" }).click()
|
||||
|
||||
return collectReviewPaneProbe(page)
|
||||
}
|
||||
|
||||
async function installReviewPaneProbe(page: Page, input: { file: string }) {
|
||||
await page.evaluate((input) => {
|
||||
const samples: ReviewPaneSample[] = []
|
||||
const basename = input.file.split(/[\\/]/).at(-1) ?? input.file
|
||||
let started: number | undefined
|
||||
let running = true
|
||||
|
||||
const paneState = () => {
|
||||
const panel = document.querySelector<HTMLElement>("#review-panel")
|
||||
const review = panel?.querySelector<HTMLElement>('[data-component="session-review-v2"]')
|
||||
const rect = (review ?? panel)?.getBoundingClientRect()
|
||||
const text = panel?.textContent ?? ""
|
||||
|
||||
const previewHeader = panel?.querySelector<HTMLElement>(
|
||||
'[data-slot="session-review-v2-file-header"]',
|
||||
)?.textContent
|
||||
|
||||
const header = previewHeader ?? text
|
||||
const viewers = panel ? [...panel.querySelectorAll<HTMLElement>('[data-component="file"][data-mode="diff"]')] : []
|
||||
const codeBlocks = panel?.querySelectorAll("code").length ?? 0
|
||||
|
||||
const diffLines = viewers.reduce(
|
||||
(sum, viewer) =>
|
||||
sum +
|
||||
(viewer.shadowRoot?.querySelectorAll("[data-line]").length ?? viewer.querySelectorAll("[data-line]").length),
|
||||
0,
|
||||
)
|
||||
|
||||
const panelVisible =
|
||||
!!panel && panel.getAttribute("aria-hidden") !== "true" && !!rect && rect.width > 0 && rect.height > 0
|
||||
|
||||
return {
|
||||
panelVisible,
|
||||
header: header.slice(0, 500),
|
||||
diffViewers: viewers.length,
|
||||
diffLines,
|
||||
codeBlocks,
|
||||
ready:
|
||||
panelVisible &&
|
||||
header.includes(basename) &&
|
||||
(viewers.length > 0 || text.includes("+3") || diffLines > 0 || codeBlocks > 0),
|
||||
}
|
||||
}
|
||||
|
||||
const sample = () => {
|
||||
if (!running || started === undefined) return
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
if (!running || started === undefined) return
|
||||
samples.push({ observedAtMs: performance.now() - started, ...paneState() })
|
||||
|
||||
if (performance.now() - started < 10_000) sample()
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
|
||||
;(window as Window & { __reviewPaneProbe?: ReviewPaneProbe }).__reviewPaneProbe = {
|
||||
samples,
|
||||
start: () => {
|
||||
started = performance.now()
|
||||
performance.mark("opencode.review-pane.click")
|
||||
sample()
|
||||
},
|
||||
stop: () => {
|
||||
running = false
|
||||
},
|
||||
}
|
||||
}, input)
|
||||
}
|
||||
|
||||
async function startReviewPaneProbe(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
;(window as Window & { __reviewPaneProbe?: ReviewPaneProbe }).__reviewPaneProbe!.start()
|
||||
})
|
||||
}
|
||||
|
||||
async function collectReviewPaneProbe(page: Page) {
|
||||
await page.waitForFunction((streak) => {
|
||||
const samples = (window as Window & { __reviewPaneProbe?: ReviewPaneProbe }).__reviewPaneProbe?.samples
|
||||
|
||||
if (!samples) return false
|
||||
|
||||
return samples.some((_, index) => {
|
||||
const stable = samples.slice(index, index + streak)
|
||||
|
||||
return stable.length === streak && stable.every((sample) => sample.ready)
|
||||
})
|
||||
}, reviewReadyStreak)
|
||||
|
||||
const samples = await page.evaluate(() => {
|
||||
const probe = (window as Window & { __reviewPaneProbe?: ReviewPaneProbe }).__reviewPaneProbe!
|
||||
probe.stop()
|
||||
|
||||
return probe.samples
|
||||
})
|
||||
|
||||
return { summary: summarizeReviewPaneSamples(samples), samples }
|
||||
}
|
||||
|
||||
function summarizeReviewPaneSamples(samples: ReviewPaneSample[]) {
|
||||
const firstReady = samples.find((sample) => sample.ready)
|
||||
|
||||
const stableIndex = samples.findIndex((_, index) => {
|
||||
const stable = samples.slice(index, index + reviewReadyStreak)
|
||||
|
||||
return stable.length === reviewReadyStreak && stable.every((sample) => sample.ready)
|
||||
})
|
||||
|
||||
return {
|
||||
samples: samples.length,
|
||||
firstReadyObservedMs: firstReady?.observedAtMs ?? null,
|
||||
stableReadyObservedMs: stableIndex === -1 ? null : samples[stableIndex + reviewReadyStreak - 1]!.observedAtMs,
|
||||
notReadySamples: samples.filter((sample) => !sample.ready).length,
|
||||
maxDiffViewers: Math.max(0, ...samples.map((sample) => sample.diffViewers)),
|
||||
maxDiffLines: Math.max(0, ...samples.map((sample) => sample.diffLines)),
|
||||
maxCodeBlocks: Math.max(0, ...samples.map((sample) => sample.codeBlocks)),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import path from "node:path"
|
||||
import { mkdir, writeFile } from "node:fs/promises"
|
||||
|
||||
export async function startTimelineProfile(page: Page, options: { cpuThrottle: number; profileCPU: boolean }) {
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
|
||||
if (options.cpuThrottle > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: options.cpuThrottle })
|
||||
|
||||
if (options.profileCPU) {
|
||||
await cdp.send("Profiler.enable")
|
||||
await cdp.send("Profiler.setSamplingInterval", { interval: 100 })
|
||||
await cdp.send("Profiler.start")
|
||||
}
|
||||
|
||||
return {
|
||||
async stop() {
|
||||
if (!options.profileCPU) return
|
||||
const result = await cdp.send("Profiler.stop")
|
||||
const directory = process.env.TIMELINE_CPU_PROFILE_DIR
|
||||
|
||||
if (directory) {
|
||||
await mkdir(directory, { recursive: true })
|
||||
const file = path.join(directory, `${process.env.OPENCODE_PERFORMANCE_RUN_ID ?? "manual"}-timeline.cpuprofile`)
|
||||
await writeFile(file, JSON.stringify(result.profile))
|
||||
console.log("timeline cpu profile file", file)
|
||||
}
|
||||
|
||||
const self = new Map<number, number>()
|
||||
result.profile.samples?.forEach((id, index) => {
|
||||
const duration = (result.profile.timeDeltas?.[index] ?? 0) / 1_000
|
||||
self.set(id, (self.get(id) ?? 0) + duration)
|
||||
})
|
||||
console.log(
|
||||
"timeline cpu profile",
|
||||
JSON.stringify(
|
||||
result.profile.nodes
|
||||
.map((node) => ({
|
||||
function: node.callFrame.functionName || "(anonymous)",
|
||||
url: node.callFrame.url,
|
||||
line: node.callFrame.lineNumber + 1,
|
||||
selfMs: self.get(node.id) ?? 0,
|
||||
}))
|
||||
.filter((node) => node.selfMs > 1)
|
||||
.sort((a, b) => b.selfMs - a.selfMs)
|
||||
.slice(0, 40),
|
||||
),
|
||||
)
|
||||
},
|
||||
async reset() {
|
||||
if (options.cpuThrottle > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
import { benchmark, expect } from "../benchmark"
|
||||
import { buildInitialStreamEvent, setupTimelineBenchmark, textPartID } from "./session-timeline-benchmark.fixture"
|
||||
import {
|
||||
collectTimelineSearchMetrics,
|
||||
installTimelineSearchProbe,
|
||||
waitForStableTimelineSearch,
|
||||
} from "./session-timeline-search-probe"
|
||||
|
||||
benchmark("searches a large virtualized session and reveals the first result", async ({ page, report }) => {
|
||||
benchmark.setTimeout(180_000)
|
||||
const historyTurns = Number(process.env.TIMELINE_SEARCH_HISTORY_TURNS ?? 320)
|
||||
const completionTimeout = Number(process.env.TIMELINE_SEARCH_COMPLETION_TIMEOUT_MS ?? 60_000)
|
||||
const query = "Historical prompt"
|
||||
const targetPartID = "msg_0000_0000_a_user:text:0"
|
||||
const expectedCounter = `1/${historyTurns}`
|
||||
|
||||
const fixture = await setupTimelineBenchmark(page, {
|
||||
historyTurns,
|
||||
eventBatch: 1,
|
||||
})
|
||||
|
||||
fixture.transport.enqueue(buildInitialStreamEvent(1))
|
||||
await expect(fixture.text).toContainText("Implementation plan")
|
||||
await fixture.scrollToBottom()
|
||||
await fixture.waitForStableGeometry()
|
||||
// Chromium reserves the physical shortcut for its native find overlay, so request the same controller path directly.
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("opencode:timeline-search-open")))
|
||||
|
||||
const search = page.locator('[data-component="timeline-search-bar"]')
|
||||
const field = search.getByRole("searchbox", { name: "Find..." })
|
||||
const count = search.locator('[data-slot="timeline-search-count"]')
|
||||
const target = page.locator(`[data-timeline-part-id="${targetPartID}"]`)
|
||||
await expect(field).toBeVisible()
|
||||
await expect(field).toBeFocused()
|
||||
await installTimelineSearchProbe(page, { targetPartID })
|
||||
|
||||
await field.fill(query)
|
||||
await expect(count).toHaveText(expectedCounter)
|
||||
await expect(target).toBeVisible({ timeout: completionTimeout })
|
||||
await waitForStableTimelineSearch(page, { counter: expectedCounter, targetPartID, timeout: completionTimeout })
|
||||
const metrics = await collectTimelineSearchMetrics(page, { counter: expectedCounter, targetPartID })
|
||||
|
||||
expect(metrics.summary.handlerDurationMs).toBeDefined()
|
||||
expect(metrics.summary.firstCountObservedMs).toBeDefined()
|
||||
expect(metrics.summary.firstTargetVisibleMs).toBeDefined()
|
||||
expect(metrics.summary.firstActiveHighlightObservedMs).toBeDefined()
|
||||
expect(metrics.summary.stableResultObservedMs).toBeDefined()
|
||||
expect(metrics.summary.activeHighlightRanges).toBe(1)
|
||||
report(metrics, { historyTurns, query, expectedMatches: historyTurns })
|
||||
|
||||
// Check navigation and the V2 assistant content IDs outside the measured interval.
|
||||
await field.press("Enter")
|
||||
await expect(count).toHaveText(`2/${historyTurns}`)
|
||||
await field.press("Shift+Enter")
|
||||
await expect(count).toHaveText(expectedCounter)
|
||||
await field.fill("Implementation plan")
|
||||
await expect(count).toHaveText("1/1")
|
||||
await expect(fixture.text).toBeInViewport()
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(() => {
|
||||
const range = [...(CSS.highlights.get("timeline-search-hit-active") ?? [])][0]
|
||||
|
||||
return range?.startContainer.parentElement?.closest<HTMLElement>("[data-timeline-part-id]")?.dataset
|
||||
.timelinePartId
|
||||
}),
|
||||
)
|
||||
.toBe(textPartID)
|
||||
await field.press("Escape")
|
||||
await expect(search).toBeHidden()
|
||||
})
|
||||
|
|
@ -1,196 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
|
||||
export type TimelineSearchSample = {
|
||||
observedAtMs: number
|
||||
counter: string
|
||||
targetMounted: boolean
|
||||
targetVisible: boolean
|
||||
targetTopPx?: number
|
||||
activeRanges: number
|
||||
activePartID?: string
|
||||
activeVisible: boolean
|
||||
scrollTopPx: number
|
||||
}
|
||||
|
||||
type TimelineSearchProbe = {
|
||||
samples: TimelineSearchSample[]
|
||||
handlerDurationMs?: number
|
||||
initialScrollTopPx: number
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
export async function installTimelineSearchProbe(page: Page, input: { targetPartID: string }) {
|
||||
await page.evaluate(({ targetPartID }) => {
|
||||
const search = document.querySelector<HTMLElement>('[data-component="timeline-search-bar"]')
|
||||
const field = search?.querySelector<HTMLInputElement>('[data-slot="text-input-v2-input"]')
|
||||
|
||||
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
|
||||
element.querySelector("[data-timeline-row]"),
|
||||
)
|
||||
|
||||
if (!search || !field || !root) throw new Error("missing timeline search benchmark nodes")
|
||||
|
||||
const samples: TimelineSearchSample[] = []
|
||||
const initialScrollTopPx = root.scrollTop
|
||||
let startedAt: number | undefined
|
||||
let handlerDurationMs: number | undefined
|
||||
let frame: number | undefined
|
||||
let running = true
|
||||
|
||||
const visibleInRoot = (rect: DOMRect) => {
|
||||
const viewport = root.getBoundingClientRect()
|
||||
|
||||
return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom
|
||||
}
|
||||
|
||||
const sample = () => {
|
||||
if (!running || startedAt === undefined) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
setTimeout(() => {
|
||||
if (!running || startedAt === undefined) return
|
||||
const target = root.querySelector<HTMLElement>(`[data-timeline-part-id="${targetPartID}"]`)
|
||||
const targetRect = target?.getBoundingClientRect()
|
||||
const highlight = CSS.highlights.get("timeline-search-hit-active")
|
||||
const ranges = highlight ? [...highlight] : []
|
||||
const active = ranges.find((range): range is Range => range instanceof Range)
|
||||
const activeRect = active?.getBoundingClientRect()
|
||||
|
||||
const activeElement =
|
||||
active?.startContainer instanceof Element ? active.startContainer : active?.startContainer.parentElement
|
||||
|
||||
samples.push({
|
||||
observedAtMs: performance.now() - startedAt,
|
||||
counter:
|
||||
search.querySelector<HTMLElement>('[data-slot="timeline-search-count"]')?.textContent?.trim() ?? "",
|
||||
targetMounted: !!target,
|
||||
targetVisible: !!targetRect && visibleInRoot(targetRect),
|
||||
targetTopPx: targetRect?.top,
|
||||
activeRanges: ranges.length,
|
||||
activePartID: activeElement?.closest<HTMLElement>("[data-timeline-part-id]")?.dataset.timelinePartId,
|
||||
activeVisible: !!activeRect && visibleInRoot(activeRect),
|
||||
scrollTopPx: root.scrollTop,
|
||||
})
|
||||
sample()
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
|
||||
const onInputCapture = (event: Event) => {
|
||||
if (event.target !== field || startedAt !== undefined) return
|
||||
startedAt = performance.now()
|
||||
sample()
|
||||
}
|
||||
|
||||
const onInput = (event: Event) => {
|
||||
if (event.target !== field || startedAt === undefined || handlerDurationMs !== undefined) return
|
||||
handlerDurationMs = performance.now() - startedAt
|
||||
}
|
||||
|
||||
document.addEventListener("input", onInputCapture, { capture: true })
|
||||
document.addEventListener("input", onInput)
|
||||
;(window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark = {
|
||||
samples,
|
||||
initialScrollTopPx,
|
||||
get handlerDurationMs() {
|
||||
return handlerDurationMs
|
||||
},
|
||||
stop: () => {
|
||||
running = false
|
||||
document.removeEventListener("input", onInputCapture, { capture: true })
|
||||
document.removeEventListener("input", onInput)
|
||||
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
},
|
||||
}
|
||||
}, input)
|
||||
}
|
||||
|
||||
export async function waitForStableTimelineSearch(
|
||||
page: Page,
|
||||
input: { counter: string; targetPartID: string; timeout: number },
|
||||
) {
|
||||
await page.waitForFunction(
|
||||
({ counter, targetPartID }) => {
|
||||
const samples = (window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark
|
||||
?.samples
|
||||
|
||||
if (!samples) return false
|
||||
|
||||
return samples.some((_, index) => {
|
||||
const stable = samples.slice(index, index + 3)
|
||||
|
||||
if (stable.length !== 3) return false
|
||||
|
||||
return stable.every(
|
||||
(sample, sampleIndex) =>
|
||||
sample.counter === counter &&
|
||||
sample.targetVisible &&
|
||||
sample.activeRanges === 1 &&
|
||||
sample.activePartID === targetPartID &&
|
||||
sample.activeVisible &&
|
||||
(sampleIndex === 0 ||
|
||||
(Math.abs(sample.scrollTopPx - stable[sampleIndex - 1]!.scrollTopPx) <= 1 &&
|
||||
Math.abs((sample.targetTopPx ?? Infinity) - (stable[sampleIndex - 1]!.targetTopPx ?? -Infinity)) <= 1)),
|
||||
)
|
||||
})
|
||||
},
|
||||
{ counter: input.counter, targetPartID: input.targetPartID },
|
||||
{ timeout: input.timeout },
|
||||
)
|
||||
}
|
||||
|
||||
export async function collectTimelineSearchMetrics(page: Page, input: { counter: string; targetPartID: string }) {
|
||||
const result = await page.evaluate(() => {
|
||||
const probe = (window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark
|
||||
|
||||
if (!probe) throw new Error("missing timeline search benchmark probe")
|
||||
probe.stop()
|
||||
|
||||
return {
|
||||
samples: probe.samples,
|
||||
handlerDurationMs: probe.handlerDurationMs,
|
||||
initialScrollTopPx: probe.initialScrollTopPx,
|
||||
}
|
||||
})
|
||||
|
||||
const first = (predicate: (sample: TimelineSearchSample) => boolean) => result.samples.find(predicate)?.observedAtMs
|
||||
|
||||
const stable = result.samples.findIndex((_, index) => {
|
||||
const samples = result.samples.slice(index, index + 3)
|
||||
|
||||
if (samples.length !== 3) return false
|
||||
|
||||
return samples.every(
|
||||
(sample, sampleIndex) =>
|
||||
sample.counter === input.counter &&
|
||||
sample.targetVisible &&
|
||||
sample.activeRanges === 1 &&
|
||||
sample.activePartID === input.targetPartID &&
|
||||
sample.activeVisible &&
|
||||
(sampleIndex === 0 ||
|
||||
(Math.abs(sample.scrollTopPx - samples[sampleIndex - 1]!.scrollTopPx) <= 1 &&
|
||||
Math.abs((sample.targetTopPx ?? Infinity) - (samples[sampleIndex - 1]!.targetTopPx ?? -Infinity)) <= 1)),
|
||||
)
|
||||
})
|
||||
|
||||
const final = result.samples.at(-1)
|
||||
|
||||
return {
|
||||
summary: {
|
||||
handlerDurationMs: result.handlerDurationMs,
|
||||
firstCountObservedMs: first((sample) => sample.counter === input.counter),
|
||||
firstTargetMountedMs: first((sample) => sample.targetMounted),
|
||||
firstTargetVisibleMs: first((sample) => sample.targetVisible),
|
||||
firstActiveHighlightObservedMs: first(
|
||||
(sample) => sample.activeRanges === 1 && sample.activePartID === input.targetPartID && sample.activeVisible,
|
||||
),
|
||||
stableResultObservedMs: stable >= 0 ? result.samples[stable + 2]?.observedAtMs : undefined,
|
||||
initialScrollTopPx: result.initialScrollTopPx,
|
||||
finalScrollTopPx: final?.scrollTopPx,
|
||||
scrollDistancePx: final === undefined ? undefined : Math.abs(result.initialScrollTopPx - final.scrollTopPx),
|
||||
activeHighlightRanges: final?.activeRanges,
|
||||
},
|
||||
samples: result.samples,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,633 +0,0 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
|
||||
const STREAM_MARKER_PATTERN = "stream-(\\d+)"
|
||||
|
||||
const STREAM_FRAGMENT_COUNT = 18
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__timelineStreamBenchmark?: TimelineProbeState
|
||||
}
|
||||
}
|
||||
|
||||
type TimelineProbeState = {
|
||||
started: number
|
||||
ended: number
|
||||
profileVisual: boolean
|
||||
minimal: boolean
|
||||
frames: number[]
|
||||
frameAt: number[]
|
||||
applied: { at: number; index: number }[]
|
||||
geometry: {
|
||||
scrollTop: number
|
||||
scrollHeight: number
|
||||
clientHeight: number
|
||||
distance: number
|
||||
virtualHeight: number
|
||||
headerHeight: number
|
||||
}[]
|
||||
blanks: number
|
||||
longTasks: number[]
|
||||
layoutShifts: number[]
|
||||
visibleMounts: number
|
||||
visibleUnmounts: number
|
||||
visibleRows: Set<Element>
|
||||
visibleSubtreeMounts: string[]
|
||||
visibleSubtreeUnmounts: string[]
|
||||
visibleSubtreeReplacements: number
|
||||
visibleSubtreeDropouts: string[]
|
||||
visibleSubtrees: Map<string, Element>
|
||||
subtreeKeys: WeakMap<Element, string>
|
||||
maxOverlap: number
|
||||
maxGap: number
|
||||
maxPartTopMovement: number
|
||||
previousPartTop: number
|
||||
slowFrames: {
|
||||
duration: number
|
||||
index: number
|
||||
phase: "stream" | "boundary" | "complete" | "unknown"
|
||||
tokenSpans: number
|
||||
blocks: number
|
||||
codeBlocks: number
|
||||
height: number
|
||||
distance: number
|
||||
}[]
|
||||
scroll: {
|
||||
calls: number
|
||||
callNoops: number
|
||||
sameFrameCalls: number
|
||||
assignments: number
|
||||
assignmentNoops: number
|
||||
lastCallFrame: number
|
||||
frame: number
|
||||
}
|
||||
row: HTMLElement
|
||||
markdown: HTMLElement
|
||||
running: boolean
|
||||
previous: number
|
||||
cleanup: () => void
|
||||
start: () => void
|
||||
}
|
||||
|
||||
export async function installTimelineStreamProbe(
|
||||
page: Page,
|
||||
options: { textPartID: string; finalIndex: number; profileVisual: boolean; minimal: boolean },
|
||||
) {
|
||||
await page.evaluate(
|
||||
({ textPartID, finalIndex, profileVisual, minimal, markerPattern, fragmentCount }) => {
|
||||
const part = document.querySelector<HTMLElement>(`[data-timeline-part-id="${textPartID}"]`)
|
||||
const row = part?.closest<HTMLElement>("[data-timeline-row]")
|
||||
const markdown = part?.querySelector<HTMLElement>('[data-component="markdown"]')
|
||||
const root = part?.closest<HTMLElement>(".scroll-view__viewport")
|
||||
|
||||
if (!part || !row || !markdown || !root) throw new Error("missing streaming benchmark nodes")
|
||||
const viewport = root.getBoundingClientRect()
|
||||
|
||||
const state: TimelineProbeState = {
|
||||
started: 0,
|
||||
ended: Infinity,
|
||||
profileVisual,
|
||||
minimal,
|
||||
frames: [],
|
||||
frameAt: [],
|
||||
applied: [],
|
||||
geometry: [],
|
||||
blanks: 0,
|
||||
longTasks: [],
|
||||
layoutShifts: [],
|
||||
visibleMounts: 0,
|
||||
visibleUnmounts: 0,
|
||||
visibleRows: new Set(
|
||||
[...root.querySelectorAll("[data-timeline-key]")].filter((element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
return rect.bottom > viewport.top && rect.top < viewport.bottom
|
||||
}),
|
||||
),
|
||||
visibleSubtreeMounts: [],
|
||||
visibleSubtreeUnmounts: [],
|
||||
visibleSubtreeReplacements: 0,
|
||||
visibleSubtreeDropouts: [],
|
||||
visibleSubtrees: new Map<string, Element>(),
|
||||
subtreeKeys: new WeakMap<Element, string>(),
|
||||
maxOverlap: 0,
|
||||
maxGap: 0,
|
||||
maxPartTopMovement: 0,
|
||||
previousPartTop: part.getBoundingClientRect().top,
|
||||
slowFrames: [],
|
||||
scroll: {
|
||||
calls: 0,
|
||||
callNoops: 0,
|
||||
sameFrameCalls: 0,
|
||||
assignments: 0,
|
||||
assignmentNoops: 0,
|
||||
lastCallFrame: -1,
|
||||
frame: 0,
|
||||
},
|
||||
row,
|
||||
markdown,
|
||||
running: false,
|
||||
previous: 0,
|
||||
cleanup: () => {},
|
||||
start: () => {},
|
||||
}
|
||||
|
||||
window.__timelineStreamBenchmark = state
|
||||
const scrollTo = Element.prototype.scrollTo
|
||||
const scrollToPoint: (this: Element, x: number, y: number) => void = scrollTo
|
||||
const scrollToOptions: (this: Element, options?: ScrollToOptions) => void = scrollTo
|
||||
const scrollTop = Object.getOwnPropertyDescriptor(Element.prototype, "scrollTop")!
|
||||
|
||||
if (profileVisual) {
|
||||
// The two `scrollTo` overloads differ by arity: `(options?)` or `(x, y)`.
|
||||
function measuredScrollTo(this: Element, ...args: [options?: ScrollToOptions] | [x: number, y: number]) {
|
||||
state.scroll.calls += 1
|
||||
const top = args.length === 2 ? args[1] : args[0]?.top
|
||||
|
||||
if (top !== undefined) {
|
||||
const target = Math.min(top, this.scrollHeight - this.clientHeight)
|
||||
|
||||
if (Math.abs(this.scrollTop - target) < 1) state.scroll.callNoops += 1
|
||||
}
|
||||
|
||||
if (state.scroll.lastCallFrame === state.scroll.frame) state.scroll.sameFrameCalls += 1
|
||||
state.scroll.lastCallFrame = state.scroll.frame
|
||||
|
||||
if (args.length === 2) scrollToPoint.call(this, args[0], args[1])
|
||||
else scrollToOptions.call(this, args[0])
|
||||
}
|
||||
|
||||
Element.prototype.scrollTo = measuredScrollTo
|
||||
Object.defineProperty(Element.prototype, "scrollTop", {
|
||||
configurable: true,
|
||||
get: scrollTop.get,
|
||||
set(value) {
|
||||
state.scroll.assignments += 1
|
||||
|
||||
if (Math.abs(this.scrollTop - value) < 1) state.scroll.assignmentNoops += 1
|
||||
scrollTop.set!.call(this, value)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const recordLongTasks = (entries: PerformanceEntry[]) => {
|
||||
if (!state.running) return
|
||||
state.longTasks.push(
|
||||
...entries.flatMap((entry) =>
|
||||
entry.startTime >= state.started && entry.startTime <= state.ended ? [entry.duration] : [],
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const longTaskObserver = new PerformanceObserver((list) => recordLongTasks(list.getEntries()))
|
||||
longTaskObserver.observe({ type: "longtask" })
|
||||
|
||||
const recordLayoutShifts = (entries: PerformanceEntry[]) => {
|
||||
if (!state.running) return
|
||||
state.layoutShifts.push(
|
||||
...entries.flatMap((entry) => {
|
||||
// SAFETY: this observer only subscribes to "layout-shift" entries, which carry `value` and `hadRecentInput`.
|
||||
const shift = entry as LayoutShiftEntry
|
||||
|
||||
if (shift.startTime < state.started || shift.hadRecentInput) return []
|
||||
|
||||
return [shift.value]
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const layoutShiftObserver = profileVisual
|
||||
? new PerformanceObserver((list) => recordLayoutShifts(list.getEntries()))
|
||||
: undefined
|
||||
|
||||
layoutShiftObserver?.observe({ type: "layout-shift", buffered: true })
|
||||
|
||||
const visible = (element: Element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
const viewport = root.getBoundingClientRect()
|
||||
const style = getComputedStyle(element)
|
||||
|
||||
return (
|
||||
element.isConnected &&
|
||||
rect.width > 0 &&
|
||||
rect.height > 0 &&
|
||||
rect.bottom > viewport.top &&
|
||||
rect.top < viewport.bottom &&
|
||||
style.display !== "none" &&
|
||||
style.visibility !== "hidden" &&
|
||||
Number(style.opacity) > 0
|
||||
)
|
||||
}
|
||||
|
||||
const critical = [
|
||||
"[data-timeline-part-id]",
|
||||
'[data-component="edit-content"]',
|
||||
'[data-component="apply-patch-file-diff"]',
|
||||
'[data-component="file"]',
|
||||
'[data-component="markdown-code"]',
|
||||
"[data-markdown-block]",
|
||||
].join(",")
|
||||
|
||||
const describe = (element: Element) => {
|
||||
const cached = state.subtreeKeys.get(element)
|
||||
|
||||
if (!element.isConnected && cached) return cached
|
||||
const part = element.closest<HTMLElement>("[data-timeline-part-id]")?.dataset.timelinePartId ?? "unknown"
|
||||
|
||||
const block = element
|
||||
.closest<HTMLElement>("[data-markdown-key]")
|
||||
?.dataset.markdownKey?.replace(/:(?:code|full|live)$/, "")
|
||||
|
||||
const component =
|
||||
element.getAttribute("data-component") ?? element.getAttribute("data-markdown-block") ?? element.tagName
|
||||
|
||||
const key = `${part}:${block ?? "root"}:${component}`
|
||||
state.subtreeKeys.set(element, key)
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
const recordMutations = (records: MutationRecord[]) => {
|
||||
if (!state.running) return
|
||||
records.forEach((record) => {
|
||||
record.addedNodes.forEach((node) => {
|
||||
if (node instanceof HTMLElement && node.matches("[data-timeline-key]") && visible(node)) {
|
||||
state.visibleMounts += 1
|
||||
state.visibleRows.add(node)
|
||||
}
|
||||
|
||||
if (!(node instanceof Element)) return
|
||||
const added = [node, ...node.querySelectorAll(critical)].filter((element) => element.matches(critical))
|
||||
added.forEach((element) => {
|
||||
if (visible(element)) state.visibleSubtreeMounts.push(describe(element))
|
||||
})
|
||||
})
|
||||
record.removedNodes.forEach((node) => {
|
||||
if (node instanceof HTMLElement && node.matches("[data-timeline-key]") && state.visibleRows.delete(node))
|
||||
state.visibleUnmounts += 1
|
||||
|
||||
if (!(node instanceof Element)) return
|
||||
const removed = [node, ...node.querySelectorAll(critical)].filter((element) => element.matches(critical))
|
||||
removed.forEach((element) => {
|
||||
const key = describe(element)
|
||||
|
||||
if (state.visibleSubtrees.get(key) === element) state.visibleSubtreeUnmounts.push(key)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const mutationObserver = profileVisual ? new MutationObserver(recordMutations) : undefined
|
||||
mutationObserver?.observe(root, { childList: true, subtree: true })
|
||||
const currentPart = () => root.querySelector<HTMLElement>(`[data-timeline-part-id="${textPartID}"]`)
|
||||
|
||||
const observeProgress = (at: number) => {
|
||||
if (!state.running) return
|
||||
const content = currentPart()?.textContent ?? ""
|
||||
|
||||
const index = content.includes("benchmark-complete")
|
||||
? finalIndex
|
||||
: Number(content.match(new RegExp(markerPattern, "g"))?.at(-1)?.match(/\d+/)?.[0] ?? -1)
|
||||
|
||||
if (index >= 0 && index !== state.applied.at(-1)?.index) state.applied.push({ at, index })
|
||||
}
|
||||
|
||||
const progressObserver = new MutationObserver(() => observeProgress(performance.now()))
|
||||
progressObserver.observe(root, { characterData: true, childList: true, subtree: true })
|
||||
state.cleanup = () => {
|
||||
recordLongTasks(longTaskObserver.takeRecords())
|
||||
recordLayoutShifts(layoutShiftObserver?.takeRecords() ?? [])
|
||||
recordMutations(mutationObserver?.takeRecords() ?? [])
|
||||
|
||||
if (progressObserver.takeRecords().length) observeProgress(performance.now())
|
||||
longTaskObserver.disconnect()
|
||||
layoutShiftObserver?.disconnect()
|
||||
mutationObserver?.disconnect()
|
||||
progressObserver.disconnect()
|
||||
|
||||
if (!profileVisual) return
|
||||
Element.prototype.scrollTo = scrollTo
|
||||
Object.defineProperty(Element.prototype, "scrollTop", scrollTop)
|
||||
}
|
||||
|
||||
const sample = (now: number) => {
|
||||
if (!state.running) return
|
||||
state.frameAt.push(now)
|
||||
observeProgress(now)
|
||||
|
||||
if (minimal) {
|
||||
state.frames.push(now - state.previous)
|
||||
state.previous = now
|
||||
requestAnimationFrame(sample)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (!state.running) return
|
||||
state.scroll.frame += 1
|
||||
const duration = now - state.previous
|
||||
state.frames.push(duration)
|
||||
state.previous = now
|
||||
const virtualRoot = root.querySelector<HTMLElement>("[data-timeline-virtual-content]")
|
||||
const header = root.querySelector<HTMLElement>("[data-session-title]")
|
||||
state.geometry.push({
|
||||
scrollTop: root.scrollTop,
|
||||
scrollHeight: root.scrollHeight,
|
||||
clientHeight: root.clientHeight,
|
||||
distance: root.scrollHeight - root.clientHeight - root.scrollTop,
|
||||
virtualHeight: virtualRoot?.getBoundingClientRect().height ?? 0,
|
||||
headerHeight: header?.getBoundingClientRect().height ?? 0,
|
||||
})
|
||||
const viewport = root.getBoundingClientRect()
|
||||
|
||||
if (profileVisual) {
|
||||
const visibleRows = [...root.querySelectorAll<HTMLElement>("[data-timeline-key]")]
|
||||
.flatMap((element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
return rect.bottom > viewport.top && rect.top < viewport.bottom ? [{ element, rect }] : []
|
||||
})
|
||||
.sort((a, b) => a.rect.top - b.rect.top)
|
||||
|
||||
state.visibleRows = new Set(visibleRows.map((item) => item.element))
|
||||
const rows = visibleRows.map((item) => item.rect)
|
||||
rows.slice(1).forEach((rect, index) => {
|
||||
const previous = rows[index]!
|
||||
state.maxOverlap = Math.max(state.maxOverlap, previous.bottom - rect.top)
|
||||
state.maxGap = Math.max(state.maxGap, rect.top - previous.bottom)
|
||||
})
|
||||
const partTop = part.getBoundingClientRect().top
|
||||
state.maxPartTopMovement = Math.max(state.maxPartTopMovement, Math.abs(partTop - state.previousPartTop))
|
||||
state.previousPartTop = partTop
|
||||
}
|
||||
|
||||
const visibleRow = [...root.querySelectorAll<HTMLElement>("[data-timeline-row]")].some((element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
return rect.bottom > viewport.top && rect.top < viewport.bottom
|
||||
})
|
||||
|
||||
if (!visibleRow) state.blanks += 1
|
||||
|
||||
if (profileVisual) {
|
||||
const subtrees = new Map<string, { element: Element; rendered: boolean }>()
|
||||
const visibleSubtrees = new Map<string, Element>()
|
||||
root.querySelectorAll(critical).forEach((element) => {
|
||||
const key = describe(element)
|
||||
const rect = element.getBoundingClientRect()
|
||||
const style = getComputedStyle(element)
|
||||
|
||||
const rendered =
|
||||
element.isConnected &&
|
||||
rect.width > 0 &&
|
||||
rect.height > 0 &&
|
||||
style.display !== "none" &&
|
||||
style.visibility !== "hidden" &&
|
||||
Number(style.opacity) > 0
|
||||
|
||||
subtrees.set(key, { element, rendered })
|
||||
|
||||
if (rendered && rect.bottom > viewport.top && rect.top < viewport.bottom) {
|
||||
const previous = state.visibleSubtrees.get(key)
|
||||
|
||||
if (previous && previous !== element && key.startsWith(`${textPartID}:`))
|
||||
state.visibleSubtreeReplacements += 1
|
||||
visibleSubtrees.set(key, element)
|
||||
}
|
||||
})
|
||||
state.visibleSubtrees.forEach((element, key) => {
|
||||
const current = subtrees.get(key)
|
||||
|
||||
if (key.startsWith(`${textPartID}:`) && !current?.rendered) {
|
||||
const markdown = part.querySelector<HTMLElement>('[data-component="markdown"]')
|
||||
state.visibleSubtreeDropouts.push(
|
||||
`${key}:projection=${markdown?.dataset.markdownProjectionLength}/${markdown?.dataset.markdownProjectionBlocks}:result=${markdown?.dataset.markdownResultLength}/${markdown?.dataset.markdownResultBlocks}:applied=${markdown?.dataset.markdownAppliedBlocks}:dom=${markdown?.children.length}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (element.matches('[data-component="file"]')) {
|
||||
const hadLines = element.hasAttribute("data-profiler-had-lines")
|
||||
const hasLines = element.shadowRoot?.querySelector("[data-line]") != null
|
||||
|
||||
if (hasLines) element.setAttribute("data-profiler-had-lines", "")
|
||||
|
||||
if (hadLines && !hasLines) state.visibleSubtreeDropouts.push(`${key}:shadow-lines`)
|
||||
}
|
||||
})
|
||||
state.visibleSubtrees = visibleSubtrees
|
||||
}
|
||||
|
||||
if (profileVisual && duration > 33.34) {
|
||||
const livePart = currentPart()
|
||||
const content = livePart?.textContent ?? ""
|
||||
const complete = content.includes("benchmark-complete")
|
||||
|
||||
const index = complete
|
||||
? finalIndex
|
||||
: Number(content.match(new RegExp(markerPattern, "g"))?.at(-1)?.match(/\d+/)?.[0] ?? -1)
|
||||
|
||||
state.slowFrames.push({
|
||||
duration,
|
||||
index,
|
||||
phase: complete
|
||||
? "complete"
|
||||
: index >= 0 && index % fragmentCount === 0
|
||||
? "boundary"
|
||||
: index >= 0
|
||||
? "stream"
|
||||
: "unknown",
|
||||
tokenSpans: livePart?.querySelectorAll(".highlights span").length ?? 0,
|
||||
blocks: livePart?.querySelectorAll("[data-markdown-block]").length ?? 0,
|
||||
codeBlocks: livePart?.querySelectorAll('[data-component="markdown-code"]').length ?? 0,
|
||||
height: livePart?.getBoundingClientRect().height ?? 0,
|
||||
distance: root.scrollHeight - root.clientHeight - root.scrollTop,
|
||||
})
|
||||
}
|
||||
|
||||
requestAnimationFrame(sample)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
state.start = () => {
|
||||
state.started = performance.now()
|
||||
state.previous = state.started
|
||||
state.running = true
|
||||
requestAnimationFrame(sample)
|
||||
}
|
||||
},
|
||||
{ ...options, markerPattern: STREAM_MARKER_PATTERN, fragmentCount: STREAM_FRAGMENT_COUNT },
|
||||
)
|
||||
}
|
||||
|
||||
export function startTimelineStreamProbe(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const state = window.__timelineStreamBenchmark
|
||||
|
||||
if (!state) throw new Error("missing streaming benchmark state")
|
||||
state.start()
|
||||
})
|
||||
}
|
||||
|
||||
type LayoutShiftEntry = PerformanceEntry & { value: number; hadRecentInput?: boolean }
|
||||
|
||||
export function layoutShiftValue(
|
||||
entry: Pick<LayoutShiftEntry, "startTime" | "value" | "hadRecentInput">,
|
||||
start: number,
|
||||
) {
|
||||
if (entry.startTime < start || entry.hadRecentInput) return
|
||||
|
||||
return entry.value
|
||||
}
|
||||
|
||||
export function removeVisibleRow<T>(visible: Set<T>, row: T) {
|
||||
return visible.delete(row)
|
||||
}
|
||||
|
||||
export function streamProgress(content: string) {
|
||||
const index = Number(content.match(new RegExp(STREAM_MARKER_PATTERN, "g"))?.at(-1)?.match(/\d+/)?.[0] ?? -1)
|
||||
|
||||
return {
|
||||
index,
|
||||
phase: content.includes("benchmark-complete")
|
||||
? ("complete" as const)
|
||||
: index >= 0 && index % STREAM_FRAGMENT_COUNT === 0
|
||||
? ("boundary" as const)
|
||||
: index >= 0
|
||||
? ("stream" as const)
|
||||
: ("unknown" as const),
|
||||
}
|
||||
}
|
||||
|
||||
export async function collectTimelineStreamMetrics(
|
||||
page: Page,
|
||||
options: { textPartID: string; finalIndex: number; navigations: string[] },
|
||||
) {
|
||||
return page.evaluate(({ textPartID, finalIndex, navigations }) => {
|
||||
const state = window.__timelineStreamBenchmark
|
||||
|
||||
if (!state) throw new Error(`missing streaming benchmark state after navigation: ${JSON.stringify(navigations)}`)
|
||||
state.ended = performance.now()
|
||||
state.cleanup()
|
||||
state.running = false
|
||||
const part = document.querySelector<HTMLElement>(`[data-timeline-part-id="${textPartID}"]`)
|
||||
const row = part?.closest<HTMLElement>("[data-timeline-row]")
|
||||
const markdown = part?.querySelector<HTMLElement>('[data-component="markdown"]')
|
||||
const sorted = state.frames.slice().sort((a, b) => a - b)
|
||||
const duration = state.frames.reduce((sum, value) => sum + value, 0)
|
||||
|
||||
const longestSlowStreak = state.frames.reduce(
|
||||
(result, value) => {
|
||||
const current = value > 33.34 ? result.current + 1 : 0
|
||||
|
||||
return { current, longest: Math.max(result.longest, current) }
|
||||
},
|
||||
{ current: 0, longest: 0 },
|
||||
).longest
|
||||
|
||||
const busyStart = state.applied.at(0)?.at
|
||||
const completion = state.applied.find((value) => value.index === finalIndex)
|
||||
const busyEnd = completion?.at
|
||||
|
||||
const busyFrames =
|
||||
busyStart === undefined || busyEnd === undefined
|
||||
? []
|
||||
: state.frames.filter((_, index) => state.frameAt[index]! >= busyStart && state.frameAt[index]! <= busyEnd)
|
||||
|
||||
const busySorted = busyFrames.slice().sort((a, b) => a - b)
|
||||
const busyDuration = busyFrames.reduce((sum, value) => sum + value, 0)
|
||||
const completionObservedMs = (completion?.at ?? NaN) - state.started
|
||||
|
||||
const visual = state.profileVisual
|
||||
? {
|
||||
layoutShiftValueSum: state.layoutShifts.reduce((sum, value) => sum + value, 0),
|
||||
maxLayoutShiftValue: Math.max(0, ...state.layoutShifts),
|
||||
visibleMounts: state.visibleMounts,
|
||||
visibleUnmounts: state.visibleUnmounts,
|
||||
visibleSubtreeMounts: state.visibleSubtreeMounts,
|
||||
visibleSubtreeUnmounts: [...new Set(state.visibleSubtreeUnmounts)],
|
||||
visibleSubtreeReplacements: state.visibleSubtreeReplacements,
|
||||
visibleSubtreeDropouts: [...new Set(state.visibleSubtreeDropouts)],
|
||||
maxOverlapPx: state.maxOverlap,
|
||||
maxGapPx: state.maxGap,
|
||||
maxPartTopMovementPx: state.maxPartTopMovement,
|
||||
slowestRafGaps: state.slowFrames
|
||||
.sort((a, b) => b.duration - a.duration)
|
||||
.slice(0, 20)
|
||||
.map((frame) => ({
|
||||
durationMs: frame.duration,
|
||||
index: frame.index,
|
||||
phase: frame.phase,
|
||||
tokenSpans: frame.tokenSpans,
|
||||
blocks: frame.blocks,
|
||||
codeBlocks: frame.codeBlocks,
|
||||
heightPx: frame.height,
|
||||
distancePx: frame.distance,
|
||||
})),
|
||||
slowRafGapPhases: Object.fromEntries(
|
||||
["stream", "boundary", "complete", "unknown"].map((phase) => {
|
||||
const frames = state.slowFrames.filter((frame) => frame.phase === phase)
|
||||
|
||||
return [
|
||||
phase,
|
||||
{
|
||||
count: frames.length,
|
||||
totalMs: frames.reduce((sum, frame) => sum + frame.duration, 0),
|
||||
maxMs: Math.max(0, ...frames.map((frame) => frame.duration)),
|
||||
},
|
||||
]
|
||||
}),
|
||||
),
|
||||
scroll: state.scroll,
|
||||
}
|
||||
: null
|
||||
|
||||
const geometry = state.minimal
|
||||
? null
|
||||
: {
|
||||
maxDistancePx: Math.max(0, ...state.geometry.map((sample) => sample.distance)),
|
||||
finalDistancePx: state.geometry.at(-1)?.distance ?? 0,
|
||||
final: state.geometry.at(-1),
|
||||
distanceTransitionsPx: state.geometry
|
||||
.map((sample) => Math.round(sample.distance))
|
||||
.filter((value, index, values) => index === 0 || value !== values[index - 1]),
|
||||
bottomDriftTransitions: state.geometry.slice(1).filter((value, index) => {
|
||||
const previous = state.geometry[index]?.distance ?? 0
|
||||
|
||||
return previous <= 1 && value.distance > 1
|
||||
}).length,
|
||||
blankSamples: state.blanks,
|
||||
}
|
||||
|
||||
return {
|
||||
capabilities: { visual: state.profileVisual, geometry: !state.minimal },
|
||||
completionObservedMs,
|
||||
deltasPerSecond: Number.isFinite(completionObservedMs) ? finalIndex / (completionObservedMs / 1_000) : null,
|
||||
rafGapSamples: state.frames.length,
|
||||
rafCallbackRate: duration ? (state.frames.length * 1000) / duration : 0,
|
||||
observedProgressWindowRafCallbackRate: busyDuration ? (busyFrames.length * 1000) / busyDuration : null,
|
||||
observedProgressWindowRafGapP95Ms: busySorted[Math.floor(busySorted.length * 0.95)] ?? null,
|
||||
observedProgressWindowRafGaps: busyFrames.length,
|
||||
maxObservedProgressIndex: Math.max(-1, ...state.applied.map((value) => value.index)),
|
||||
observedProgressTransitions: state.applied.length,
|
||||
rafGapP50Ms: sorted[Math.floor(sorted.length * 0.5)] ?? 0,
|
||||
rafGapP95Ms: sorted[Math.floor(sorted.length * 0.95)] ?? 0,
|
||||
rafGapP99Ms: sorted[Math.floor(sorted.length * 0.99)] ?? 0,
|
||||
maxRafGapMs: sorted.at(-1) ?? 0,
|
||||
rafGapsOver33Ms: state.frames.filter((value) => value > 33.34).length,
|
||||
rafGapsOver50Ms: state.frames.filter((value) => value > 50).length,
|
||||
missedFrameBudgetEquivalents: state.frames.reduce(
|
||||
(sum, value) => sum + Math.max(0, Math.round(value / 16.67) - 1),
|
||||
0,
|
||||
),
|
||||
longestRafGapOver33MsStreak: longestSlowStreak,
|
||||
longTaskCount: state.longTasks.length,
|
||||
longTaskTimeMs: state.longTasks.reduce((sum, value) => sum + value, 0),
|
||||
visual,
|
||||
geometry,
|
||||
rowReplaced: row !== state.row,
|
||||
markdownReplaced: markdown !== state.markdown,
|
||||
domTextCharacters: part?.textContent?.length ?? 0,
|
||||
}
|
||||
}, options)
|
||||
}
|
||||
|
|
@ -1,197 +0,0 @@
|
|||
import { createServer, type ServerResponse } from "node:http"
|
||||
import type { OpenCodeEvent } from "@opencode/client/promise"
|
||||
import { benchmark, benchmarkDiagnostics, expect } from "../benchmark"
|
||||
import {
|
||||
buildInitialStreamEvent,
|
||||
buildStreamDeltaEvents,
|
||||
setupTimelineBenchmark,
|
||||
textPartID,
|
||||
} from "./session-timeline-benchmark.fixture"
|
||||
|
||||
type Probe = { calls: number; entries: number; ms: number }
|
||||
|
||||
type Measurement = { frames: number[]; started: number; ready: number; rowReplacements: number; stop: () => void }
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__timelineProjectionProbe?: Probe
|
||||
__projectionMeasurement: Measurement
|
||||
}
|
||||
}
|
||||
|
||||
benchmark.use({ traceScope: "interaction" })
|
||||
|
||||
for (const scenario of [
|
||||
{ historyTurns: 40, historyShape: "mixed" },
|
||||
{ historyTurns: 320, historyShape: "mixed" },
|
||||
{ historyTurns: 320, historyShape: "tool-heavy" },
|
||||
] as const) {
|
||||
benchmark(`text projection ${scenario.historyTurns} ${scenario.historyShape}`, async ({ page, report }) => {
|
||||
benchmark.setTimeout(120_000)
|
||||
const responses = new Set<ServerResponse>()
|
||||
|
||||
const source = createServer((request, response) => {
|
||||
response.writeHead(200, {
|
||||
"content-type": "text/event-stream",
|
||||
"access-control-allow-origin": "*",
|
||||
"cache-control": "no-cache",
|
||||
})
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ id: "evt_projection_connected", type: "server.connected", data: {} })}\n\n`,
|
||||
)
|
||||
responses.add(response)
|
||||
request.on("close", () => responses.delete(response))
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve) => source.listen(0, "127.0.0.1", resolve))
|
||||
const address = source.address()
|
||||
|
||||
if (!address || typeof address === "string") throw new Error("Missing fixture SSE address")
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const send = (events: OpenCodeEvent[]) =>
|
||||
responses.forEach((response) => events.forEach((event) => response.write(`data: ${JSON.stringify(event)}\n\n`)))
|
||||
|
||||
try {
|
||||
await page.addInitScript(
|
||||
({ url, counters }) => {
|
||||
Object.assign(window, { __testSseTransport: true })
|
||||
|
||||
if (counters) window.__timelineProjectionProbe = { calls: 0, entries: 0, ms: 0 }
|
||||
const fetch = window.fetch.bind(window)
|
||||
|
||||
const intercept = (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
|
||||
return fetch(
|
||||
new URL(request.url).pathname === "/api/event" ? new Request(url, { signal: request.signal }) : request,
|
||||
)
|
||||
}
|
||||
|
||||
Object.defineProperty(window, "fetch", { configurable: true, writable: true, value: intercept })
|
||||
},
|
||||
{ url: `http://127.0.0.1:${address.port}`, counters: process.env.PROJECTION_COUNTERS === "1" },
|
||||
)
|
||||
const initialStarted = performance.now()
|
||||
const fixture = await setupTimelineBenchmark(page, { ...scenario, busy: true, eventBatch: 1 })
|
||||
await expect.poll(() => responses.size).toBe(1)
|
||||
const deltas = buildStreamDeltaEvents(160)
|
||||
send(buildInitialStreamEvent(160))
|
||||
await expect(fixture.text).toContainText("Implementation plan")
|
||||
await expect(fixture.text.locator('[data-component="markdown"]')).toHaveAttribute("data-markdown-ready", "")
|
||||
const initialReadyMs = performance.now() - initialStarted
|
||||
await fixture.scrollToBottom()
|
||||
await expect(page.getByRole("button", { name: "Stop", exact: true })).toBeVisible()
|
||||
await benchmarkDiagnostics(page).startTrace()
|
||||
await page.evaluate(
|
||||
({ partID, counters }) => {
|
||||
const part = document.querySelector(`[data-timeline-part-id="${partID}"]`)
|
||||
const row = part?.closest("[data-timeline-key]")
|
||||
|
||||
if (!row) throw new Error("Missing active row")
|
||||
|
||||
if (counters) {
|
||||
if (!window.__timelineProjectionProbe?.calls)
|
||||
throw new Error("Projection instrumentation did not observe initial construction")
|
||||
window.__timelineProjectionProbe = { calls: 0, entries: 0, ms: 0 }
|
||||
}
|
||||
|
||||
const measurement: Measurement = {
|
||||
frames: [],
|
||||
started: performance.now(),
|
||||
ready: 0,
|
||||
rowReplacements: 0,
|
||||
stop: () => {},
|
||||
}
|
||||
|
||||
window.__projectionMeasurement = measurement
|
||||
let previous: number | undefined
|
||||
let frame = 0
|
||||
let current = row
|
||||
|
||||
const sample = (now: number) => {
|
||||
if (previous !== undefined) measurement.frames.push(now - previous)
|
||||
previous = now
|
||||
const next = document.querySelector(`[data-timeline-part-id="${partID}"]`)?.closest("[data-timeline-key]")
|
||||
|
||||
if (next && next !== current) {
|
||||
measurement.rowReplacements++
|
||||
current = next
|
||||
}
|
||||
|
||||
const markdown = next?.querySelector('[data-component="markdown"][data-markdown-ready]')
|
||||
|
||||
if (markdown?.textContent?.includes("benchmark-complete")) {
|
||||
measurement.ready = performance.now() - measurement.started
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
frame = requestAnimationFrame(sample)
|
||||
}
|
||||
|
||||
measurement.stop = () => cancelAnimationFrame(frame)
|
||||
frame = requestAnimationFrame(sample)
|
||||
},
|
||||
{ partID: textPartID, counters: process.env.PROJECTION_COUNTERS === "1" },
|
||||
)
|
||||
const emitted: number[] = []
|
||||
const started = performance.now()
|
||||
// The source clock runs in Node, never waiting for a renderer acknowledgement.
|
||||
await new Promise<void>((resolve) => {
|
||||
timer = setInterval(() => {
|
||||
const event = deltas[emitted.length]
|
||||
|
||||
if (!event) throw new Error("Unexpected source overrun")
|
||||
send([event])
|
||||
emitted.push(performance.now() - started)
|
||||
|
||||
if (emitted.length !== deltas.length) return
|
||||
clearInterval(timer)
|
||||
resolve()
|
||||
}, 25)
|
||||
})
|
||||
await expect(fixture.text).toContainText("benchmark-complete")
|
||||
await expect(fixture.text.locator('[data-component="markdown"]')).toHaveAttribute("data-markdown-ready", "")
|
||||
await page.waitForFunction(() => window.__projectionMeasurement.ready > 0)
|
||||
|
||||
const metrics = await page.evaluate(() => {
|
||||
const data = window.__projectionMeasurement
|
||||
data.stop()
|
||||
|
||||
return {
|
||||
frames: data.frames,
|
||||
readyMs: data.ready,
|
||||
rowReplacements: data.rowReplacements,
|
||||
projection: window.__timelineProjectionProbe ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
expect(emitted).toHaveLength(160)
|
||||
expect(metrics.frames.length).toBeGreaterThan(0)
|
||||
await benchmarkDiagnostics(page).stop()
|
||||
report(
|
||||
{ ...metrics, initialReadyMs, emitted },
|
||||
{
|
||||
...scenario,
|
||||
...fixture.workload,
|
||||
deltaBytes: Buffer.byteLength(JSON.stringify(deltas)),
|
||||
counters: process.env.PROJECTION_COUNTERS === "1",
|
||||
intervalMs: 25,
|
||||
deltas: 160,
|
||||
viewport: "1366x768",
|
||||
revision: process.env.PROJECTION_REVISION,
|
||||
},
|
||||
)
|
||||
|
||||
if (process.env.PROJECTION_SCREENSHOT)
|
||||
await page.screenshot({
|
||||
path: `${process.env.PROJECTION_SCREENSHOT}-${scenario.historyTurns}-${scenario.historyShape}.png`,
|
||||
})
|
||||
} finally {
|
||||
clearInterval(timer)
|
||||
source.closeAllConnections()
|
||||
await new Promise<void>((resolve, reject) => source.close((error) => (error ? reject(error) : resolve())))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
# Timeline Text Projection Benchmark
|
||||
|
||||
Run from `packages/app`, against a production bundle. No OpenCode server is needed.
|
||||
The fixture owns its HTTP event source and mocks all other API responses.
|
||||
|
||||
```sh
|
||||
bun run build -- --config e2e/performance/timeline/projection.vite.config.ts
|
||||
PLAYWRIGHT_BUILD=1 playwright test --config e2e/performance/timeline/projection.playwright.config.ts --repeat-each=20 --workers=1 --retries=0 --reporter=line
|
||||
```
|
||||
|
||||
Set `PLAYWRIGHT_PORT` to an unused local port. Set `PROJECTION_BUNDLE` to preview a
|
||||
previously frozen bundle, `PROJECTION_OUTPUT` for test artifacts, and
|
||||
`PROJECTION_REVISION` to label results. Keep all three workloads separate:
|
||||
40 historical user/assistant pairs, 320 pairs, and 320 pairs with six additional
|
||||
completed read tools per assistant. The existing mixed fixture includes Markdown,
|
||||
reasoning, and edit/write/patch output. Results include serialized history bytes,
|
||||
message/part counts, and event bytes.
|
||||
|
||||
Each case opens the real application timeline with a busy session, waits for the
|
||||
initial Markdown to be ready, then sends the same 160 text deltas at a 25 ms source
|
||||
cadence. The Node HTTP source does not wait for renderer acknowledgements. Results
|
||||
retain every source emission time and animation-frame interval. Completion means
|
||||
the final marker is in ready Markdown and has reached an animation-frame callback;
|
||||
it does not claim a compositor presentation timestamp. Row replacements count the
|
||||
active streaming row, not normal virtualizer mounts while scrolling.
|
||||
|
||||
Use `PROJECTION_COUNTERS=1` for separate diagnostic runs. The benchmark build
|
||||
instruments the full-history constructor with its call count, input entries visited,
|
||||
and synchronous elapsed time. The probe is absent from normal builds and disabled
|
||||
in clean timing runs. `OPENCODE_PERFORMANCE_TRACE_DIR` enables the existing Chrome
|
||||
trace collector. Set `PROJECTION_SCREENSHOT` to an output path prefix for screenshots
|
||||
after timing. Do not compare diagnostic timing with clean timing.
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
export function createReviewDiffs() {
|
||||
return Array.from({ length: Number(process.env.REVIEW_PANE_DIFF_COUNT ?? 72) }, (_, index) => {
|
||||
const lines = index % 3 === 0 ? 300 : index % 3 === 1 ? 120 : 38
|
||||
const file = `src/review/generated-${String(index).padStart(3, "0")}.ts`
|
||||
const before = reviewSource(index, lines)
|
||||
|
||||
const after = before
|
||||
.replace(`value_${index}_4`, `updated_${index}_4`)
|
||||
.replace(
|
||||
`value_${index}_${Math.max(8, Math.floor(lines / 2))}`,
|
||||
`updated_${index}_${Math.max(8, Math.floor(lines / 2))}`,
|
||||
)
|
||||
.replace(`value_${index}_${lines - 4}`, `updated_${index}_${lines - 4}`)
|
||||
|
||||
return {
|
||||
file,
|
||||
patch: reviewPatch(file, before, after),
|
||||
additions: 3,
|
||||
deletions: 3,
|
||||
status: "modified" as const,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function reviewSource(seed: number, lines: number) {
|
||||
return Array.from(
|
||||
{ length: lines },
|
||||
(_, index) => `export const value_${seed}_${index} = "${reviewWords(seed + index, index % 5 === 0 ? 180 : 42)}"`,
|
||||
).join("\n")
|
||||
}
|
||||
|
||||
function reviewPatch(file: string, before: string, after: string) {
|
||||
const beforeLines = before.split("\n")
|
||||
const afterLines = after.split("\n")
|
||||
|
||||
return [
|
||||
`diff --git a/${file} b/${file}`,
|
||||
`--- a/${file}`,
|
||||
`+++ b/${file}`,
|
||||
`@@ -1,${beforeLines.length} +1,${afterLines.length} @@`,
|
||||
...beforeLines.flatMap((line, index) => {
|
||||
const next = afterLines[index]!
|
||||
|
||||
if (line === next) return [` ${line}`]
|
||||
|
||||
return [`-${line}`, `+${next}`]
|
||||
}),
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
function reviewWords(seed: number, length: number) {
|
||||
const words = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet"]
|
||||
|
||||
return Array.from({ length: Math.ceil(length / 7) }, (_, index) => words[(seed + index * 3) % words.length]).join(" ")
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import os from "node:os"
|
||||
import { prepareChromeTrace } from "../chrome-trace"
|
||||
|
||||
test("creates the configured trace directory", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "opencode-trace-"))
|
||||
|
||||
try {
|
||||
const file = await prepareChromeTrace(path.join(root, "nested", "traces"), "session/tab", false, "test")
|
||||
expect(file).toEndWith("-session-tab-458ed9e3-test.json")
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import { inlineThemePreload } from "../../../vite.js"
|
||||
import { milestoneForLine, summarizeDesktopStartup, type DesktopStartupSample } from "../devex/desktop-startup"
|
||||
|
||||
describe("desktop startup benchmark", () => {
|
||||
test.each(["/oc-theme-preload.js", "./oc-theme-preload.js"])("inlines %s before the renderer runs", (path) => {
|
||||
const html = inlineThemePreload(`<script id="oc-theme-preload-script" src="${path}"></script>`)
|
||||
expect(html).not.toContain(" src=")
|
||||
expect(html).toContain("opencode-color-scheme")
|
||||
})
|
||||
|
||||
test("recognizes startup milestones in colored output", () => {
|
||||
const cases = [
|
||||
["bunRootScript", "$ bun --cwd packages/desktop dev"],
|
||||
["bunDesktopScript", "$ bun run script/dev.ts"],
|
||||
["desktopPrepared", "Copied dev icons from"],
|
||||
["mainBundleReady", "electron main process built successfully"],
|
||||
["preloadBundleReady", "electron preload scripts built successfully"],
|
||||
["rendererDevServerReady", "dev server running for the electron renderer process at:"],
|
||||
["electronSpawnStarted", "starting electron app..."],
|
||||
["debugEndpointReady", "DevTools listening on ws://"],
|
||||
["electronStarted", "app starting"],
|
||||
["layersReady", "layers ready"],
|
||||
["windowVisible", "main window visible"],
|
||||
["serviceEnsureStarted", "starting v2 background service"],
|
||||
["serviceSpawnRequested", "v2 CLI background service starting"],
|
||||
["serviceReady", "v2 CLI background service ready"],
|
||||
["rendererViteConnected", "[vite] connected."],
|
||||
] as const
|
||||
|
||||
cases.forEach(([milestone, line]) => {
|
||||
expect(milestoneForLine(`\u001b[32m${line}\u001b[39m`)).toBe(milestone)
|
||||
})
|
||||
expect(milestoneForLine("12:30:00.000 › v2 CLI background service ready {")).toBe("serviceReady")
|
||||
expect(milestoneForLine("unrelated output")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("keeps raw samples and reports median absolute deviation", () => {
|
||||
const samples = [24, 20, 22, 28, 26].map((commandToHomeReadyMs, index) => sample(index + 1, commandToHomeReadyMs))
|
||||
expect(summarizeDesktopStartup(samples).commandToHomeReadyMs).toEqual({
|
||||
min: 20,
|
||||
median: 24,
|
||||
max: 28,
|
||||
medianAbsoluteDeviation: 2,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function sample(run: number, commandToHomeReadyMs: number): DesktopStartupSample {
|
||||
const milestonesMs = {
|
||||
bunRootScript: 1,
|
||||
bunDesktopScript: 2,
|
||||
desktopPrepared: 3,
|
||||
mainBundleReady: 4,
|
||||
preloadBundleReady: 5,
|
||||
rendererDevServerReady: 6,
|
||||
electronSpawnStarted: 7,
|
||||
debugEndpointReady: 8,
|
||||
electronStarted: 9,
|
||||
layersReady: 10,
|
||||
windowVisible: 11,
|
||||
serviceEnsureStarted: 12,
|
||||
serviceSpawnRequested: 13,
|
||||
serviceReady: 14,
|
||||
rendererViteConnected: 15,
|
||||
homeReady: commandToHomeReadyMs,
|
||||
}
|
||||
|
||||
return {
|
||||
run,
|
||||
commandToHomeReadyMs,
|
||||
milestonesMs,
|
||||
phasesMs: {
|
||||
desktopPreparation: 3,
|
||||
viteMainBundle: 1,
|
||||
vitePreloadBundle: 1,
|
||||
rendererServerStartup: 1,
|
||||
electronStartup: 2,
|
||||
serviceSpawnWait: 1,
|
||||
serviceProcessStartup: 1,
|
||||
rendererStartup: commandToHomeReadyMs - 15,
|
||||
visibleWindowToHome: commandToHomeReadyMs - 11,
|
||||
},
|
||||
service: { version: "2.0.0-local-test", url: "http://127.0.0.1:3000", pid: run },
|
||||
}
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { summarizeFirstNavigation } from "../timeline/first-navigation-metrics"
|
||||
|
||||
test("reports blank frames before first destination and stable paint", () => {
|
||||
expect(
|
||||
summarizeFirstNavigation([
|
||||
{ observedAtMs: 16, source: true, destination: false, content: true },
|
||||
{ observedAtMs: 32, source: false, destination: false, content: false },
|
||||
{ observedAtMs: 48, source: false, destination: true, content: true },
|
||||
{ observedAtMs: 64, source: false, destination: true, content: true },
|
||||
{ observedAtMs: 80, source: false, destination: true, content: true },
|
||||
]),
|
||||
).toEqual({
|
||||
samples: 5,
|
||||
firstDestinationObservedMs: 48,
|
||||
stableDestinationObservedMs: 80,
|
||||
sourceSamples: 1,
|
||||
blankSamples: 1,
|
||||
unknownSamples: 0,
|
||||
destinationSamples: 3,
|
||||
})
|
||||
})
|
||||
|
||||
test("does not report stability for interrupted destination frames", () => {
|
||||
expect(
|
||||
summarizeFirstNavigation([
|
||||
{ observedAtMs: 16, source: false, destination: true, content: true },
|
||||
{ observedAtMs: 32, source: false, destination: false, content: true },
|
||||
{ observedAtMs: 48, source: false, destination: true, content: true },
|
||||
]).stableDestinationObservedMs,
|
||||
).toBeNull()
|
||||
})
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { createHomeIndexFixture, HOME_INDEX_VISIBLE_LIMIT } from "../timeline/home-session-index.fixture"
|
||||
|
||||
const now = 1_800_000_000_000
|
||||
|
||||
test("generates a deterministic index ordered like the server", () => {
|
||||
const fixture = createHomeIndexFixture({ count: 2_000, now })
|
||||
const again = createHomeIndexFixture({ count: 2_000, now })
|
||||
expect(again.sessions).toEqual(fixture.sessions)
|
||||
expect(fixture.sessions).toHaveLength(2_000)
|
||||
expect(new Set(fixture.sessions.map((session) => session.id)).size).toBe(2_000)
|
||||
const updated = fixture.sessions.map((session) => session.time.updated)
|
||||
expect(updated.every((time, index) => index === 0 || time > updated[index - 1])).toBe(true)
|
||||
expect(updated.every((time) => time <= now)).toBe(true)
|
||||
expect(fixture.sessions.every((session) => session.time.created < session.time.updated)).toBe(true)
|
||||
expect(fixture.expected.newestID).toBe(fixture.sessions[fixture.sessions.length - 1].id)
|
||||
expect(fixture.expected.visible).toBe(HOME_INDEX_VISIBLE_LIMIT)
|
||||
})
|
||||
|
||||
test("spreads sessions across several directories with a skewed head", () => {
|
||||
const fixture = createHomeIndexFixture({ count: 5_000, now })
|
||||
const counts = Object.values(fixture.expected.perDirectory)
|
||||
expect(counts.reduce((sum, count) => sum + count, 0)).toBe(5_000)
|
||||
expect(fixture.directories).toHaveLength(12)
|
||||
expect(fixture.directories.filter((entry) => entry.project)).toHaveLength(8)
|
||||
const largest = Math.max(...counts)
|
||||
expect(largest).toBeGreaterThan(5_000 * 0.15)
|
||||
expect(Math.min(...counts)).toBeGreaterThan(0)
|
||||
expect(fixture.sessions.some((session) => session.time.updated > now - 86_400_000)).toBe(true)
|
||||
// Realistic serialized rows: hundreds of bytes each, not one-character stubs.
|
||||
expect(fixture.listBytes / 5_000).toBeGreaterThan(300)
|
||||
})
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import type { Page, Route } from "@playwright/test"
|
||||
import { createMockServerHandler, mockOpenCodeServer } from "../../utils/mock-server"
|
||||
|
||||
test("serves an empty config document list for composer defaults", async () => {
|
||||
const server = createMockServerHandler({
|
||||
provider: {},
|
||||
directory: "C:/OpenCode",
|
||||
project: {},
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await server.handler(
|
||||
new Request("http://localhost/api/config?location%5Bdirectory%5D=C%3A%2FOpenCode"),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual([])
|
||||
} finally {
|
||||
await server.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("applies message latency after a list response gate is released", async () => {
|
||||
const events: string[] = []
|
||||
const gate = Promise.withResolvers<void>()
|
||||
const started = Promise.withResolvers<void>()
|
||||
let handler: ((route: Route) => Promise<void>) | undefined
|
||||
|
||||
const page = {
|
||||
addInitScript: () => Promise.resolve(),
|
||||
on: () => page,
|
||||
route: (_url: string, callback: (route: Route) => Promise<void>) => {
|
||||
handler = callback
|
||||
|
||||
return Promise.resolve()
|
||||
},
|
||||
} as unknown as Page
|
||||
|
||||
await mockOpenCodeServer(page, {
|
||||
provider: {},
|
||||
directory: "C:/OpenCode",
|
||||
project: {},
|
||||
sessions: [{ id: "session" }],
|
||||
messageDelay: 25,
|
||||
beforeMessagesResponse: () => {
|
||||
events.push("before")
|
||||
started.resolve()
|
||||
|
||||
return gate.promise
|
||||
},
|
||||
onMessages: (request) => events.push(request.phase),
|
||||
pageMessages: () => {
|
||||
events.push("page")
|
||||
|
||||
return { items: [] }
|
||||
},
|
||||
})
|
||||
|
||||
const response = handler!({
|
||||
request: () => ({
|
||||
url: () => "http://127.0.0.1:4096/api/session/session/message",
|
||||
method: () => "GET",
|
||||
headers: () => ({}),
|
||||
postDataBuffer: () => null,
|
||||
}),
|
||||
fulfill: () => {
|
||||
events.push("fulfill")
|
||||
|
||||
return Promise.resolve()
|
||||
},
|
||||
} as unknown as Route)
|
||||
|
||||
await started.promise
|
||||
expect(events).toEqual(["start", "before"])
|
||||
|
||||
const released = performance.now()
|
||||
gate.resolve()
|
||||
await response
|
||||
expect(performance.now() - released).toBeGreaterThanOrEqual(20)
|
||||
expect(events).toEqual(["start", "before", "page", "end", "fulfill"])
|
||||
})
|
||||
|
||||
test("routes requests through the HttpApi contract", async () => {
|
||||
const connected = Promise.withResolvers<{ integrationID: string; body: unknown }>()
|
||||
let handler: ((route: Route) => Promise<void>) | undefined
|
||||
|
||||
const page = {
|
||||
addInitScript: () => Promise.resolve(),
|
||||
on: () => page,
|
||||
route: (_url: string, callback: (route: Route) => Promise<void>) => {
|
||||
handler = callback
|
||||
|
||||
return Promise.resolve()
|
||||
},
|
||||
} as unknown as Page
|
||||
|
||||
await mockOpenCodeServer(page, {
|
||||
provider: {},
|
||||
directory: "C:/OpenCode",
|
||||
project: {},
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
onConnectKey: connected.resolve,
|
||||
})
|
||||
|
||||
const body = Buffer.from(JSON.stringify({ key: "secret" }))
|
||||
let status: number | undefined
|
||||
await handler!({
|
||||
request: () => ({
|
||||
url: () => "http://127.0.0.1:4096/api/integration/anthropic/connect/key",
|
||||
method: () => "POST",
|
||||
headers: () => ({ "content-type": "application/json" }),
|
||||
postDataBuffer: () => body,
|
||||
}),
|
||||
fulfill: (response: Parameters<Route["fulfill"]>[0]) => {
|
||||
status = response?.status
|
||||
|
||||
return Promise.resolve()
|
||||
},
|
||||
} as unknown as Route)
|
||||
|
||||
expect(status).toBe(204)
|
||||
expect(await connected.promise).toEqual({ integrationID: "anthropic", body: { key: "secret" } })
|
||||
})
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { summarizeNavigationMilestones } from "../timeline/navigation-milestones"
|
||||
|
||||
test("reports first and stable paint for each navigation milestone", () => {
|
||||
expect(
|
||||
summarizeNavigationMilestones([
|
||||
{ observedAtMs: 16, milestones: { content: false, tab: false } },
|
||||
{ observedAtMs: 32, milestones: { content: true, tab: false } },
|
||||
{ observedAtMs: 48, milestones: { content: true, tab: true } },
|
||||
{ observedAtMs: 64, milestones: { content: true, tab: true } },
|
||||
{ observedAtMs: 80, milestones: { content: true, tab: true } },
|
||||
]),
|
||||
).toEqual({
|
||||
samples: 5,
|
||||
milestones: {
|
||||
content: { firstObservedMs: 32, stableObservedMs: 64 },
|
||||
tab: { firstObservedMs: 48, stableObservedMs: 80 },
|
||||
},
|
||||
all: { firstObservedMs: 48, stableObservedMs: 80 },
|
||||
})
|
||||
})
|
||||
|
||||
test("reports missing stability when a milestone appears in the final samples", () => {
|
||||
expect(
|
||||
summarizeNavigationMilestones([
|
||||
{ observedAtMs: 16, milestones: { content: false } },
|
||||
{ observedAtMs: 32, milestones: { content: true } },
|
||||
]),
|
||||
).toEqual({
|
||||
samples: 2,
|
||||
milestones: { content: { firstObservedMs: 32, stableObservedMs: null } },
|
||||
all: { firstObservedMs: 32, stableObservedMs: null },
|
||||
})
|
||||
})
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { compressCachedRepaintTrace, layoutShiftSample } from "../timeline/session-tab-repaint-probe"
|
||||
|
||||
test("compresses repeated repaint states without losing frame samples", () => {
|
||||
const state = {
|
||||
root: 1,
|
||||
scrollTop: 10,
|
||||
scrollHeight: 20,
|
||||
bottomErrorPx: 0,
|
||||
last: true,
|
||||
rows: [{ key: "row", node: 2, top: 0, bottom: 10 }],
|
||||
mounted: 1,
|
||||
center: "content",
|
||||
}
|
||||
|
||||
const trace = {
|
||||
timeOriginEpochMs: 1_000,
|
||||
startedAtPerformanceMs: 100,
|
||||
samples: [
|
||||
{ observedAtMs: 16, ...state, destination: ["target"], source: [] },
|
||||
{ observedAtMs: 32, ...state, destination: ["target"], source: [] },
|
||||
{ observedAtMs: 48, ...state, scrollTop: 11, destination: ["target"], source: [] },
|
||||
],
|
||||
mutations: [{ observedAtMs: 20, changed: [{ type: "add", node: 2 }] }],
|
||||
shifts: [{ occurredAtMs: 24, value: 0.1 }],
|
||||
windowMs: 1_000,
|
||||
running: false,
|
||||
stop() {},
|
||||
}
|
||||
|
||||
const compressed = compressCachedRepaintTrace(trace)
|
||||
|
||||
const samples = compressed.samples.flatMap((group) =>
|
||||
group.observedAtMs.map((observedAtMs) => ({ observedAtMs, ...group.state })),
|
||||
)
|
||||
|
||||
expect(samples).toEqual(trace.samples)
|
||||
expect(compressed.mutations).toEqual(trace.mutations)
|
||||
expect(compressed.shifts).toEqual(trace.shifts)
|
||||
})
|
||||
|
||||
test("records layout shifts at occurrence time within the probe window", () => {
|
||||
expect(layoutShiftSample({ startTime: 99, value: 0.1 }, 100)).toBeUndefined()
|
||||
expect(layoutShiftSample({ startTime: 124, value: 0.2 }, 100)).toEqual({ occurredAtMs: 24, value: 0.2 })
|
||||
})
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { classifySessionSwitch } from "../timeline/session-tab-switch-metrics"
|
||||
|
||||
test("counts source and blank samples before the destination is observed", () => {
|
||||
const result = classifySessionSwitch([
|
||||
{ observedAtMs: 16, destination: [], source: ["source"], hasVisibleRows: true, last: false },
|
||||
{ observedAtMs: 32, destination: [], source: [], hasVisibleRows: false, last: false },
|
||||
{ observedAtMs: 48, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
{ observedAtMs: 64, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
{ observedAtMs: 80, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
])
|
||||
|
||||
expect(result.blankSamples).toBe(1)
|
||||
expect(result.sourceSamples).toBe(1)
|
||||
expect(result.unknownSamples).toBe(0)
|
||||
expect(result.firstDestinationObservedMs).toBe(48)
|
||||
expect(result.stableObservedMs).toBe(80)
|
||||
})
|
||||
|
||||
test("does not classify mixed source and destination content as correct", () => {
|
||||
const result = classifySessionSwitch([
|
||||
{
|
||||
observedAtMs: 16,
|
||||
destination: ["destination"],
|
||||
source: ["source"],
|
||||
hasVisibleRows: true,
|
||||
last: true,
|
||||
bottomErrorPx: 0,
|
||||
},
|
||||
{ observedAtMs: 32, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
{ observedAtMs: 48, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
{ observedAtMs: 64, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
])
|
||||
|
||||
expect(result.firstCorrectObservedMs).toBe(32)
|
||||
expect(result.stableObservedMs).toBe(64)
|
||||
})
|
||||
|
||||
test("reports missing correctness without throwing", () => {
|
||||
const result = classifySessionSwitch([
|
||||
{
|
||||
observedAtMs: 16,
|
||||
destination: ["destination"],
|
||||
source: ["source"],
|
||||
hasVisibleRows: true,
|
||||
last: true,
|
||||
bottomErrorPx: 0,
|
||||
},
|
||||
])
|
||||
|
||||
expect(result.firstDestinationObservedMs).toBe(16)
|
||||
expect(result.firstCorrectObservedMs).toBeNull()
|
||||
expect(result.stableObservedMs).toBeNull()
|
||||
})
|
||||
|
||||
test("does not report stability for only two correct samples", () => {
|
||||
const result = classifySessionSwitch([
|
||||
{ observedAtMs: 16, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
{ observedAtMs: 32, destination: ["destination"], source: [], hasVisibleRows: true, last: true, bottomErrorPx: 0 },
|
||||
])
|
||||
|
||||
expect(result.firstCorrectObservedMs).toBe(16)
|
||||
expect(result.stableObservedMs).toBeNull()
|
||||
})
|
||||
|
||||
test("requires an explicitly tracked part to be visible", () => {
|
||||
const result = classifySessionSwitch([
|
||||
{
|
||||
observedAtMs: 16,
|
||||
destination: ["destination"],
|
||||
source: [],
|
||||
hasVisibleRows: true,
|
||||
last: true,
|
||||
requiredPartVisible: false,
|
||||
bottomErrorPx: 0,
|
||||
},
|
||||
])
|
||||
|
||||
expect(result.firstCorrectObservedMs).toBeNull()
|
||||
})
|
||||
|
||||
test("can measure content correctness without requiring a bottom anchor", () => {
|
||||
const result = classifySessionSwitch([
|
||||
{
|
||||
observedAtMs: 16,
|
||||
destination: ["destination"],
|
||||
source: [],
|
||||
hasVisibleRows: true,
|
||||
last: true,
|
||||
requiredPartVisible: true,
|
||||
bottomAnchorRequired: false,
|
||||
},
|
||||
])
|
||||
|
||||
expect(result.firstCorrectObservedMs).toBe(16)
|
||||
})
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import type { Page } from "@playwright/test"
|
||||
import { measureSessionSwitch } from "../timeline/session-tab-switch-probe"
|
||||
|
||||
function testPage(waitFailure?: Error) {
|
||||
const stops: unknown[] = []
|
||||
|
||||
const page = {
|
||||
evaluate: async (_callback: unknown, input?: unknown) => {
|
||||
if (input) return
|
||||
stops.push(undefined)
|
||||
},
|
||||
waitForFunction: async () => {
|
||||
if (waitFailure) throw waitFailure
|
||||
},
|
||||
} as unknown as Page
|
||||
|
||||
return { page, stops }
|
||||
}
|
||||
|
||||
function input(run: () => Promise<void>) {
|
||||
return {
|
||||
destinationIDs: ["destination"],
|
||||
sourceIDs: ["source"],
|
||||
lastID: "destination",
|
||||
href: "/session/destination",
|
||||
switch: run,
|
||||
}
|
||||
}
|
||||
|
||||
test("stops sampling when the session switch fails", async () => {
|
||||
const failure = new Error("switch failed")
|
||||
const context = testPage()
|
||||
|
||||
await expect(
|
||||
measureSessionSwitch(
|
||||
context.page,
|
||||
input(async () => Promise.reject(failure)),
|
||||
),
|
||||
).rejects.toBe(failure)
|
||||
|
||||
expect(context.stops).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("stops sampling when the stable wait fails", async () => {
|
||||
const failure = new Error("stable wait failed")
|
||||
const context = testPage(failure)
|
||||
|
||||
await expect(
|
||||
measureSessionSwitch(
|
||||
context.page,
|
||||
input(async () => {}),
|
||||
),
|
||||
).rejects.toBe(failure)
|
||||
|
||||
expect(context.stops).toHaveLength(1)
|
||||
})
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { streamChunk } from "../timeline/session-timeline-benchmark.fixture"
|
||||
import { streamProgress } from "../timeline/session-timeline-stream-probe"
|
||||
|
||||
test("classifies emitted stream markers using the fixture cycle", () => {
|
||||
expect(streamProgress("before stream-17 after stream-18")).toEqual({ index: 18, phase: "boundary" })
|
||||
expect(streamProgress("before stream-18 after stream-19")).toEqual({ index: 19, phase: "stream" })
|
||||
expect(streamProgress("benchmark-complete stream-36")).toEqual({ index: 36, phase: "complete" })
|
||||
expect(streamProgress("no marker")).toEqual({ index: -1, phase: "unknown" })
|
||||
})
|
||||
|
||||
test("emits progress markers at fixture boundaries", () => {
|
||||
expect(streamProgress(streamChunk(18, 160))).toEqual({ index: 18, phase: "boundary" })
|
||||
})
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { layoutShiftValue, removeVisibleRow } from "../timeline/session-timeline-stream-probe"
|
||||
|
||||
test("excludes layout shifts before the probe window and recent input", () => {
|
||||
expect(layoutShiftValue({ startTime: 9, value: 0.1 }, 10)).toBeUndefined()
|
||||
expect(layoutShiftValue({ startTime: 10, value: 0.2, hadRecentInput: true }, 10)).toBeUndefined()
|
||||
expect(layoutShiftValue({ startTime: 11, value: 0.3 }, 10)).toBe(0.3)
|
||||
})
|
||||
|
||||
test("classifies removed rows from their last painted visibility", () => {
|
||||
const row = {}
|
||||
const visible = new Set([row])
|
||||
|
||||
expect(removeVisibleRow(visible, row)).toBe(true)
|
||||
expect(removeVisibleRow(visible, row)).toBe(false)
|
||||
})
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
import { expect, spyOn, test } from "bun:test"
|
||||
import type { FullConfig, Suite, TestCase, TestResult } from "@playwright/test/reporter"
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import TabSwitchReporter from "../tab-switch-reporter"
|
||||
|
||||
test("summarizes each scenario and saves complete records in the configured output directory", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "tab-switch-reporter-"))
|
||||
const output = path.join(root, "configured-output")
|
||||
const log = spyOn(console, "log").mockImplementation(() => {})
|
||||
|
||||
try {
|
||||
const reporter = new TabSwitchReporter()
|
||||
|
||||
const cases = Array.from(
|
||||
{ length: 23 },
|
||||
(_, index) => ({ id: String(index), title: index < 20 ? "cold" : "warm" }) as TestCase,
|
||||
)
|
||||
|
||||
const records = cases.map((_, index) => {
|
||||
const first = index < 20 ? 20 - index : [40, 0, 20][index - 20]
|
||||
|
||||
return JSON.stringify({
|
||||
status: "passed",
|
||||
metrics: {
|
||||
firstCorrectObservedMs: first,
|
||||
stableObservedMs: first * 2,
|
||||
samples: [{ observedAtMs: first, destination: ["answer"], source: [] }],
|
||||
},
|
||||
extra: { preserved: "\u03b1" },
|
||||
})
|
||||
})
|
||||
|
||||
reporter.onBegin({ projects: [{ outputDir: output }] } as FullConfig, { allTests: () => cases } as Suite)
|
||||
cases.forEach((item, index) => {
|
||||
const bytes = Buffer.from(`BENCHMARK ${records[index]}\r\n`)
|
||||
const split = bytes.indexOf(Buffer.from("\u03b1")) + 1
|
||||
reporter.onTestEnd(item, {
|
||||
status: "passed",
|
||||
stdout:
|
||||
index === 0
|
||||
? [bytes.subarray(0, split), bytes.subarray(split)]
|
||||
: ["other output\nBENCHMARK_PAGE {}\nBENCH", "MARK ", records[index], "\n"],
|
||||
} as TestResult)
|
||||
})
|
||||
await reporter.onEnd({ status: "passed", startTime: new Date(0), duration: 0 })
|
||||
|
||||
expect(await readFile(path.join(output, "tab-switch-benchmark.jsonl"), "utf8")).toBe(`${records.join("\n")}\n`)
|
||||
const summary = log.mock.calls.map((call) => call.join(" ")).join("\n")
|
||||
expect(summary).toContain("cold\n Tests: passed=20; unrun=0")
|
||||
expect(summary).toContain("warm\n Tests: passed=3; unrun=0")
|
||||
expect(summary).toContain("firstCorrectObservedMs: n=20, median=10.50 ms, p95=19.00 ms")
|
||||
expect(summary).toContain("stableObservedMs: n=20, median=21.00 ms, p95=38.00 ms")
|
||||
expect(summary).toContain("firstCorrectObservedMs: n=3, median=20.00 ms, p95=40.00 ms")
|
||||
expect(summary).toContain("stableObservedMs: n=3, median=40.00 ms, p95=80.00 ms")
|
||||
} finally {
|
||||
log.mockRestore()
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("reports failures, missing records, and invalid metrics without discarding raw data", async () => {
|
||||
const output = await mkdtemp(path.join(os.tmpdir(), "tab-switch-reporter-"))
|
||||
const log = spyOn(console, "log").mockImplementation(() => {})
|
||||
|
||||
try {
|
||||
const reporter = new TabSwitchReporter()
|
||||
|
||||
const entries = [
|
||||
{
|
||||
status: "passed",
|
||||
raw: '{"status":"passed","metrics":{"firstCorrectObservedMs":12,"stableObservedMs":24}}',
|
||||
},
|
||||
{
|
||||
status: "failed",
|
||||
raw: '{"status":"passed","metrics":{"firstCorrectObservedMs":900,"stableObservedMs":950}}',
|
||||
},
|
||||
{
|
||||
status: "passed",
|
||||
raw: '{"status":"failed","metrics":{"firstCorrectObservedMs":900,"stableObservedMs":950}}',
|
||||
},
|
||||
{ status: "timedOut", raw: '{"status":"failed","metrics":null,"error":"Benchmark did not report metrics"}' },
|
||||
{
|
||||
status: "passed",
|
||||
raw: '{"status":"passed","metrics":{"firstCorrectObservedMs":null,"stableObservedMs":40}}',
|
||||
},
|
||||
{ status: "failed", raw: '{"status":' },
|
||||
{ status: "skipped", raw: undefined },
|
||||
] as const
|
||||
|
||||
const cases = Array.from(
|
||||
{ length: entries.length + 2 },
|
||||
(_, index) => ({ id: String(index), title: index <= entries.length ? "cold" : "empty" }) as TestCase,
|
||||
)
|
||||
|
||||
reporter.onBegin({ projects: [{ outputDir: output }] } as FullConfig, { allTests: () => cases } as Suite)
|
||||
entries.forEach((entry, index) => {
|
||||
reporter.onTestEnd(cases[index], {
|
||||
status: entry.status,
|
||||
stdout: entry.raw === undefined ? [] : [`BENCHMARK ${entry.raw}\n`],
|
||||
} as TestResult)
|
||||
})
|
||||
await reporter.onEnd({ status: "interrupted", startTime: new Date(0), duration: 0 })
|
||||
|
||||
expect(await readFile(path.join(output, "tab-switch-benchmark.jsonl"), "utf8")).toBe(
|
||||
entries.flatMap((entry) => (entry.raw === undefined ? [] : [`${entry.raw}\n`])).join(""),
|
||||
)
|
||||
const summary = log.mock.calls.map((call) => call.join(" ")).join("\n")
|
||||
expect(summary).toContain("Tab-switch benchmark: interrupted")
|
||||
expect(summary).toContain("Tests: passed=3, failed=2, timedOut=1, skipped=1; unrun=1")
|
||||
expect(summary).toContain("Records: passed=3, failed=2, invalid JSON=1; missing=2; excluded=5; invalid metrics=1")
|
||||
expect(summary).toContain("firstCorrectObservedMs: n=1, median=12.00 ms, p95=12.00 ms")
|
||||
expect(summary).toContain("stableObservedMs: n=1, median=24.00 ms, p95=24.00 ms")
|
||||
expect(summary).toContain("empty\n Tests: none; unrun=1")
|
||||
expect(summary).toContain("Records: none; missing=1; excluded=0; invalid metrics=0")
|
||||
expect(summary).toContain("firstCorrectObservedMs: n=0, median=n/a, p95=n/a")
|
||||
expect(summary).toContain("stableObservedMs: n=0, median=n/a, p95=n/a")
|
||||
} finally {
|
||||
log.mockRestore()
|
||||
await rm(output, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -17,7 +17,7 @@ import {
|
|||
userMessage,
|
||||
waitForVisualSettle,
|
||||
type TimelineMessage,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test.describe("timeline adverse visual stability", () => {
|
||||
test("does not pull a scrolled-away user while an active shell grows", async ({ page }, testInfo) => {
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -15,7 +15,7 @@ import {
|
|||
textPart,
|
||||
userMessage,
|
||||
waitForVisualSettle,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
// Fractional scaling exercises different browser rounding than the baseline.
|
||||
for (const deviceScaleFactor of [1, 1.25]) {
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -16,7 +16,7 @@ import {
|
|||
toolPart,
|
||||
userMessage,
|
||||
waitForVisualSettle,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
const profiles = [
|
||||
{
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -16,7 +16,7 @@ import {
|
|||
toolPart,
|
||||
userMessage,
|
||||
waitForVisualSettle,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test("adds patch files incrementally without resetting outer expansion", async ({ page }, testInfo) => {
|
||||
const patchID = "prt_incremental_01_patch"
|
||||
|
|
@ -65,13 +65,7 @@ test("adds patch files incrementally without resetting outer expansion", async (
|
|||
const third = patchFile("src/old.ts", "deleted")
|
||||
await timeline.send(
|
||||
partUpdated(
|
||||
toolPart(
|
||||
patchID,
|
||||
"patch",
|
||||
"running",
|
||||
{ patchText: "Update files" },
|
||||
{ metadata: { files: [first, second] } },
|
||||
),
|
||||
toolPart(patchID, "patch", "running", { patchText: "Update files" }, { metadata: { files: [first, second] } }),
|
||||
),
|
||||
240,
|
||||
)
|
||||
|
|
@ -7,7 +7,7 @@ import {
|
|||
validateTimelineEvent,
|
||||
validateTimelineMessages,
|
||||
type PartSeed,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
describe("timeline fixture validation", () => {
|
||||
test("accepts a valid timeline", () => {
|
||||
|
|
@ -15,6 +15,7 @@ describe("timeline fixture validation", () => {
|
|||
})
|
||||
|
||||
test("rejects malformed SDK values at runtime", () => {
|
||||
// SAFETY: each value below is malformed on purpose; the validators must reject it at run time.
|
||||
expect(() =>
|
||||
assistantMessage([], {
|
||||
error: { type: "APIError", message: 1 } as never,
|
||||
|
|
@ -28,8 +29,11 @@ describe("timeline fixture validation", () => {
|
|||
data: { sessionID: "ses_timeline_stability", status: { type: "retry", attempt: 1 } },
|
||||
}),
|
||||
).toThrow()
|
||||
// SAFETY: malformed on purpose, as above.
|
||||
expect(() => validateTimelineMessages([{ ...userMessage(), id: "invalid" } as never])).toThrow()
|
||||
// SAFETY: malformed on purpose, as above.
|
||||
expect(() => validateTimelineMessages([{ ...userMessage(), time: { created: "invalid" } } as never])).toThrow()
|
||||
// SAFETY: malformed on purpose, as above.
|
||||
expect(() =>
|
||||
validateTimelineMessages([
|
||||
userMessage(),
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
renderedPartID,
|
||||
|
|
@ -16,7 +16,7 @@ import {
|
|||
toolPart,
|
||||
userMessage,
|
||||
waitForVisualSettle,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test("expands and collapses a long completed shell without overlap", async ({ page }, testInfo) => {
|
||||
const shellID = "prt_interaction_01_shell"
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
completedAssistantInfo,
|
||||
|
|
@ -20,7 +20,7 @@ import {
|
|||
textPart,
|
||||
userMessage,
|
||||
waitForVisualSettle,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test.describe("timeline visual lifecycle stability", () => {
|
||||
test("streams empty, short, and long parallel shells to staggered completion", async ({ page }, testInfo) => {
|
||||
|
|
@ -5,8 +5,8 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
import { assistantMessage, renderedPartID, setupTimeline, textPart, userMessage } from "../../utils/timeline"
|
||||
} from "../utils/visual-stability"
|
||||
import { assistantMessage, renderedPartID, setupTimeline, textPart, userMessage } from "../utils/timeline"
|
||||
|
||||
test("detects blanking caused by ancestor opacity", async ({ page }) => {
|
||||
const partID = "prt_oracle_ancestor_opacity"
|
||||
|
|
@ -58,11 +58,11 @@ test("detects root opacity when probing descendant opacity", async ({ page }) =>
|
|||
|
||||
await startVisualProbe(page, regions)
|
||||
await row.evaluate((element) => {
|
||||
;(element as HTMLElement).style.opacity = "0"
|
||||
element.style.opacity = "0"
|
||||
})
|
||||
await page.waitForTimeout(50)
|
||||
await row.evaluate((element) => {
|
||||
;(element as HTMLElement).style.opacity = "1"
|
||||
element.style.opacity = "1"
|
||||
})
|
||||
await page.waitForTimeout(50)
|
||||
const trace = await stopVisualProbe<keyof typeof regions>(page)
|
||||
|
|
@ -3,10 +3,10 @@ import {
|
|||
analyzeVisualStability,
|
||||
analyzeVisualStabilityByMarker,
|
||||
type VisualStabilityTrace,
|
||||
} from "../../utils/visual-stability"
|
||||
import { analyzeVisualObservations } from "../../utils/visual-stability/analyzer"
|
||||
import { visualPlan, type VisualInvariant } from "../../utils/visual-stability/invariant"
|
||||
import { defineVisualRegions, mapVisualRegions } from "../../utils/visual-stability/regions"
|
||||
} from "../utils/visual-stability"
|
||||
import { analyzeVisualObservations } from "../utils/visual-stability/analyzer"
|
||||
import { visualPlan, type VisualInvariant } from "../utils/visual-stability/invariant"
|
||||
import { defineVisualRegions, mapVisualRegions } from "../utils/visual-stability/regions"
|
||||
|
||||
function trace(samples: VisualStabilityTrace["samples"]): VisualStabilityTrace {
|
||||
return { markers: [], samples }
|
||||
|
|
@ -356,7 +356,11 @@ function frame(
|
|||
changing: VisualStabilityTrace["samples"][number]["regions"][string],
|
||||
following?: VisualStabilityTrace["samples"][number]["regions"][string],
|
||||
) {
|
||||
return { at, regions: { changing, ...(following ? { following } : {}) } }
|
||||
const regions: VisualStabilityTrace["samples"][number]["regions"] = { changing }
|
||||
|
||||
if (following) regions.following = following
|
||||
|
||||
return { at, regions }
|
||||
}
|
||||
|
||||
function region(input: Partial<VisualStabilityTrace["samples"][number]["regions"][string]> = {}) {
|
||||
31
packages/app/e2e/stability/playwright.config.ts
Normal file
31
packages/app/e2e/stability/playwright.config.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import config from "../../playwright.config"
|
||||
|
||||
const port = Number(process.env.PLAYWRIGHT_PORT ?? 3000)
|
||||
|
||||
// The suite runs a production build, which answers on its own origin, so the fixtures mock that origin.
|
||||
process.env.PLAYWRIGHT_SERVER_PORT = new URL(process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${port}`).port || "80"
|
||||
|
||||
export default {
|
||||
...config,
|
||||
testDir: ".",
|
||||
testMatch: "**/*.spec.ts",
|
||||
testIgnore: [],
|
||||
outputDir: "../test-results/stability",
|
||||
reporter: [["html", { outputFolder: "../playwright-report/stability", open: "never" }], ["line"]],
|
||||
fullyParallel: false,
|
||||
retries: 0,
|
||||
workers: 1,
|
||||
webServer: config.webServer
|
||||
? {
|
||||
...config.webServer,
|
||||
command: `bun run build && bun e2e/utils/serve.ts --host 127.0.0.1 --port ${port}`,
|
||||
reuseExistingServer: false,
|
||||
}
|
||||
: undefined,
|
||||
use: {
|
||||
...config.use,
|
||||
trace: "retain-on-failure",
|
||||
screenshot: "only-on-failure",
|
||||
video: "retain-on-failure",
|
||||
},
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -17,7 +17,7 @@ import {
|
|||
toolPart,
|
||||
userMessage,
|
||||
type TimelineMessage,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test("follows an expanded patch that arrives as the user reaches the bottom", async ({ page }) => {
|
||||
const toolID = "prt_bottom_follow_patch"
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -15,7 +15,7 @@ import {
|
|||
textPart,
|
||||
userMessage,
|
||||
waitForVisualSettle,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
const profiles = [
|
||||
{
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
partUpdated,
|
||||
|
|
@ -15,7 +15,7 @@ import {
|
|||
setupTimeline,
|
||||
toolPart,
|
||||
userMessage,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test("adds a subagent child-session link without replacing the row", async ({ page }, testInfo) => {
|
||||
const taskID = "prt_subagent_link"
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
directory,
|
||||
|
|
@ -18,7 +18,7 @@ import {
|
|||
textPart,
|
||||
toolPart,
|
||||
userMessage,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test.describe("timeline tool state stability", () => {
|
||||
test("moves lightweight tools through streaming, running, and completed without replacing rows", async ({
|
||||
|
|
@ -91,12 +91,17 @@ test.describe("timeline tool state stability", () => {
|
|||
)
|
||||
}
|
||||
|
||||
for (const [index, id] of ["skill", "webfetch", "custom", "subagent", "websearch"].entries()) {
|
||||
const key = id as (typeof ids)[number]
|
||||
const metadata = key === "subagent" ? { sessionID: childID } : key === "websearch" ? { provider: "exa" } : {}
|
||||
const metadata: Partial<Record<(typeof ids)[number], { sessionID: string } | { provider: string }>> = {
|
||||
subagent: { sessionID: childID },
|
||||
websearch: { provider: "exa" },
|
||||
}
|
||||
|
||||
for (const [index, key] of (["skill", "webfetch", "custom", "subagent", "websearch"] as const).entries()) {
|
||||
const output = key === "websearch" ? "Result https://example.com/result" : "Completed"
|
||||
await timeline.send(
|
||||
partUpdated(toolPart(`prt_state_${key}`, names[key], "completed", inputs[key], { metadata, output })),
|
||||
partUpdated(
|
||||
toolPart(`prt_state_${key}`, names[key], "completed", inputs[key], { metadata: metadata[key] ?? {}, output }),
|
||||
),
|
||||
[110, 70, 280, 130, 420][index],
|
||||
)
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
startVisualProbe,
|
||||
stopVisualProbe,
|
||||
visualPlan,
|
||||
} from "../../utils/visual-stability"
|
||||
} from "../utils/visual-stability"
|
||||
import {
|
||||
assistantMessage,
|
||||
completedAssistantInfo,
|
||||
|
|
@ -19,7 +19,7 @@ import {
|
|||
textPart,
|
||||
toolPart,
|
||||
userMessage,
|
||||
} from "../../utils/timeline"
|
||||
} from "../utils/timeline"
|
||||
|
||||
test("streams text through growth, canonical replacement, and completion", async ({ page }, testInfo) => {
|
||||
const textID = "prt_text_reconcile"
|
||||
|
|
@ -7,5 +7,5 @@
|
|||
"rootDir": "../..",
|
||||
"types": ["node", "bun"]
|
||||
},
|
||||
"include": ["./**/*.ts", "./**/*.tsx", "../component-tests/**/*.ts", "../src/types.ts"]
|
||||
"include": ["./**/*.ts", "./**/*.tsx", "../component-tests/**/*.ts", "../perf/**/*.ts", "../src/types.ts"]
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue