Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit aeed4f9dc17797963a3deb90ea4fda63c74dd85e
parent f32bde13160d276d512fc9e86dbaa74b42644a09
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 16:28:59 -0400

Merge r24/e2e-speed (release 24 Lane B: e2e S4 suites side by side, S5a test paths, S5b a server per worker) into r24/integration

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
M.gitignore | 4++++
MAGENTS.md | 33+++++++++++++++++++++------------
MENVIRONMENT.md | 11+++++++----
MWORKTREES.md | 141++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mcommon/lib/envVars.test.ts | 6++++--
Mcommon/lib/envVars.ts | 11+++++++----
Meditor/CHANGELOG.md | 3+++
Meditor/e2e/aliases.spec.ts | 6+++---
Meditor/e2e/attribution.spec.ts | 5+++--
Meditor/e2e/audio-check-scenarios.spec.ts | 3++-
Meditor/e2e/auto-queue.spec.ts | 39++++++++++++++++++++-------------------
Meditor/e2e/auto-refresh.spec.ts | 6+++---
Meditor/e2e/auto-report-refresh.spec.ts | 6+++---
Meditor/e2e/auto-subs-replace.spec.ts | 5+++--
Meditor/e2e/availability-backfill.spec.ts | 17+++++++++--------
Meditor/e2e/availability.spec.ts | 9+++++----
Meditor/e2e/backfill.spec.ts | 29+++++++++++++++--------------
Meditor/e2e/build.spec.ts | 11++++++-----
Meditor/e2e/bulk-actions.spec.ts | 5+++--
Meditor/e2e/cadence-ui.spec.ts | 17+++++++++--------
Meditor/e2e/cancel.spec.ts | 3++-
Meditor/e2e/channel-build-toggle.spec.ts | 7++++---
Meditor/e2e/channel-groups.spec.ts | 5+++--
Meditor/e2e/channel-line.spec.ts | 3++-
Meditor/e2e/channel-priority.spec.ts | 4++--
Meditor/e2e/channel-rename.spec.ts | 5+++--
Meditor/e2e/channel-site-membership.spec.ts | 3++-
Meditor/e2e/channel-storage.spec.ts | 57+++++++++++++++++++++++++++++----------------------------
Meditor/e2e/channel-work.spec.ts | 8++++----
Meditor/e2e/channels-storage-columns.spec.ts | 9+++++----
Meditor/e2e/channels.spec.ts | 11++++++-----
Meditor/e2e/chat-only.spec.ts | 9+++++----
Meditor/e2e/chough.spec.ts | 3++-
Meditor/e2e/cleanup-actionable.spec.ts | 4++--
Meditor/e2e/cleanup-holds.spec.ts | 7++++---
Meditor/e2e/cleanup-page.spec.ts | 6+++---
Meditor/e2e/cookies-mode.spec.ts | 7++++---
Meditor/e2e/cut-release.spec.ts | 4++--
Meditor/e2e/dashboard-answers.spec.ts | 15++++++++-------
Meditor/e2e/dashboard-paths.spec.ts | 4++--
Meditor/e2e/dashboard.spec.ts | 4++--
Meditor/e2e/diagnostics-retry-log.spec.ts | 3++-
Meditor/e2e/diarization.spec.ts | 5+++--
Meditor/e2e/digest.spec.ts | 17+++++++++--------
Meditor/e2e/disk-space.spec.ts | 9+++++----
Meditor/e2e/do-not-clean.spec.ts | 5+++--
Meditor/e2e/download-format-guard.spec.ts | 15++++++++-------
Meditor/e2e/download-part-files.spec.ts | 5+++--
Meditor/e2e/duplicate-shorts.spec.ts | 11++++++-----
Meditor/e2e/exclude-from-counts.spec.ts | 7++++---
Meditor/e2e/export-search.spec.ts | 4++--
Meditor/e2e/exportOutLink.ts | 6++++--
Meditor/e2e/fetch-window.spec.ts | 9+++++----
Meditor/e2e/forms-keep-input.spec.ts | 11++++++-----
Meditor/e2e/globalSetup.ts | 34+++++++++++++++++++++++++++++++++-
Meditor/e2e/globalTeardown.ts | 4++++
Meditor/e2e/helpers.ts | 20++++++++++++--------
Meditor/e2e/import-video.spec.ts | 15++++++++-------
Meditor/e2e/incomplete-transcript.spec.ts | 7++++---
Meditor/e2e/jobs-batch-tasks-drain.spec.ts | 5+++--
Meditor/e2e/jobs-filters.spec.ts | 4++--
Meditor/e2e/jobs-reorder.spec.ts | 3++-
Meditor/e2e/jobs-retry.spec.ts | 7++++---
Meditor/e2e/lane-runner.spec.ts | 5+++--
Meditor/e2e/maybe-missing.spec.ts | 3++-
Meditor/e2e/metadata-scan-botcheck.spec.ts | 3++-
Meditor/e2e/metadata-scan-softblock.spec.ts | 4++--
Meditor/e2e/new-channel-onboarding.spec.ts | 6+++---
Meditor/e2e/no-orphan-fixtures.spec.ts | 3++-
Meditor/e2e/no-subs-fallback.spec.ts | 5+++--
Meditor/e2e/operation-settings.spec.ts | 12++++++------
Meditor/e2e/ops-api.spec.ts | 35++++++++++++++++++-----------------
Meditor/e2e/ops-cut-release.spec.ts | 6+++---
Meditor/e2e/pacing.spec.ts | 8++++----
Meditor/e2e/parakeet-partial.spec.ts | 13+++++++------
Meditor/e2e/parakeet.spec.ts | 3++-
Meditor/e2e/partial-downloads-bucket.spec.ts | 3++-
Meditor/e2e/persist-youtube-handling.spec.ts | 4++--
Meditor/e2e/pipeline.spec.ts | 17+++++++++--------
Meditor/e2e/pre-clean-availability.spec.ts | 3++-
Meditor/e2e/publish-lane.spec.ts | 10+++++-----
Meditor/e2e/publish.spec.ts | 17+++++++++--------
Meditor/e2e/queues.spec.ts | 5+++--
Meditor/e2e/rate-limit.spec.ts | 11++++++-----
Meditor/e2e/reconcile.spec.ts | 4++--
Meditor/e2e/reconstruct-download-url.spec.ts | 4++--
Meditor/e2e/regional-vtt-fallback.spec.ts | 5+++--
Meditor/e2e/retry-bucket.spec.ts | 7++++---
Meditor/e2e/review.spec.ts | 6+++---
Meditor/e2e/rumble-sweep.spec.ts | 5+++--
Meditor/e2e/saved-videos.spec.ts | 9+++++----
Meditor/e2e/scheduler.spec.ts | 8++++----
Aeditor/e2e/serial.ts | 38++++++++++++++++++++++++++++++++++++++
Aeditor/e2e/servers.ts | 369+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/e2e/servers.unit.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/settings.spec.ts | 8++++----
Meditor/e2e/shard.spec.ts | 25+++++++++++++------------
Meditor/e2e/site-scope.spec.ts | 4++--
Meditor/e2e/sites-crud.spec.ts | 34+++++++++++++++++-----------------
Meditor/e2e/sites-homepage.spec.ts | 7++++---
Meditor/e2e/skip-live.spec.ts | 3++-
Meditor/e2e/social-channel.spec.ts | 22+++++++++++-----------
Meditor/e2e/social-fetcher-picker.spec.ts | 6+++---
Meditor/e2e/storage-locations.spec.ts | 37+++++++++++++++++++------------------
Meditor/e2e/sync-break-on-existing.spec.ts | 3++-
Meditor/e2e/sync-deep.spec.ts | 3++-
Meditor/e2e/tags.spec.ts | 8++++----
Aeditor/e2e/testPaths.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/title-filter.spec.ts | 3++-
Meditor/e2e/transcript-source.spec.ts | 3++-
Meditor/e2e/truncated-check.spec.ts | 6+++---
Meditor/e2e/undownloaded.spec.ts | 3++-
Meditor/e2e/video-filter-combine.spec.ts | 3++-
Meditor/e2e/video-page.spec.ts | 41+++++++++++++++++++++--------------------
Meditor/e2e/video-titles.spec.ts | 3++-
Meditor/e2e/whisper-video.spec.ts | 24++++++++++++------------
Meditor/e2e/whisper.spec.ts | 29+++++++++++++++--------------
Meditor/e2e/widget.spec.ts | 5+++--
Meditor/e2e/worker-remote.spec.ts | 7++++---
Meditor/e2e/workers.spec.ts | 11++++++-----
Meditor/e2e/x-session.spec.ts | 10+++++-----
Meditor/package.json | 8++++----
Meditor/playwright.config.ts | 220+++++++++++++++++++++++++++++++++++--------------------------------------------
Mexport/next.config.ts | 6++++++
Mexport/package.json | 8++++----
Mhomepage/package.json | 2+-
Mpackage.json | 1+
Mplans/e2e-speed.md | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/e2e-all.mjs | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/e2e-all.test.mjs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/e2e-stamp.mjs | 8+++++---
Mscripts/e2e-timings-reporter.mjs | 6+++---
Mscripts/e2e-timings.mjs | 13++++++++++++-
Mscripts/e2e-timings.test.mjs | 10++++++++++
Mscripts/queue-lock.mjs | 668++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mscripts/queue-lock.test.mjs | 300++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/package.json | 2+-
137 files changed, 2803 insertions(+), 775 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -117,6 +117,8 @@ yarn-error.log* # editor e2e fixtures and ephemeral state /editor/test-transcripts/ +# the other e2e worker slots' data roots and server logs (editor/e2e/servers.ts) +/editor/.e2e-workers/ /editor/test-settings.json # Disposable changelogs for the cut-release e2e (EDITOR_CHANGELOG_FILE and # EXPORT_CHANGELOG_FILE in dev:test/start:test). Keep those specs — and @@ -125,6 +127,8 @@ yarn-error.log* /editor/test-export-changelog.md /editor/playwright-report/ /editor/test-results/ +# pnpm e2e:all's per-suite logs (scripts/e2e-all.mjs) +/test-results-e2e-all/ /editor/blob-report/ # An operator's symlink out of the repo (plans/FACTS.md, "editor/content is a # symlink out of the repo"): Tailwind's source detection follows it, Turbopack diff --git a/AGENTS.md b/AGENTS.md @@ -20,12 +20,16 @@ To run more than one checkout at once, use git worktrees with per-worktree non-c ports. `pnpm wt add <branch>` creates one; `pnpm wt list` shows each worktree's port block. `pnpm dev:editor` auto-assigns ports per worktree, so dev servers run in parallel. -**e2e does not run in parallel.** Every e2e entry point takes a machine-global lock, so one -suite runs at a time and the rest wait. If `pnpm e2e` prints `waiting for the e2e queue — -held by …` and sits there, **that is working as intended, not a hung command** — the serial -suite is ~24 minutes. A run that wins the lock but finds its ports already bound aborts and -names the offending pid, instead of silently driving another session's server. Bypasses: -`E2E_QUEUE=0`, `E2E_PORT_CHECK=0`, `E2E_QUEUE_TIMEOUT=<seconds>`. +**Each e2e suite runs one at a time; different suites run side by side.** Every e2e entry +point takes a machine-global lock named for its package (`e2e-editor`, `e2e-export`, +`e2e-homepage`, `e2e-umtool`), so the same suite never runs twice at once and the second +run waits. If `pnpm e2e` prints `waiting for the e2e queue — held by …` and sits there, +**that is working as intended, not a hung command** — the editor suite is ~20 minutes. A +run that wins the lock but finds its ports already bound aborts and names the offending +pid, instead of silently driving another session's server. Bypasses: `E2E_QUEUE=0`, +`E2E_PORT_CHECK=0`, `E2E_QUEUE_TIMEOUT=<seconds>`. **`pnpm e2e:all` runs every suite at +once** (one lane per package, each through its own script and lock) and prints one summary; +per-suite logs land in `test-results-e2e-all/`. **`pnpm e2e` at the root is the EDITOR suite**, whatever spec name you append to it: the script is `pnpm --filter editor run e2e`, so `pnpm run e2e clip-bench.spec.ts` takes the @@ -51,12 +55,17 @@ specs that judge a clip read it through `e2e/capabilities.ts` and skip themselve capability is a directory that exists, decided once by the builder — not re-guessed per spec. -**Heavy work takes the heavy slot.** e2e, the publish stages' `next build` and video renders -share ONE machine-global slot and start only above a 6000 MB MemAvailable floor (two OOMs -took the desktop session down). e2e and the publish builds take it on their own; a render or -any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting for the heavy slot -— held by …` or `heavy: waiting for memory …` is the gate working, not a hang. Bypasses: -`HEAVY=0`, `HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`. +**Heavy work takes the heavy slot.** e2e, `next build`s and video renders go through ONE +machine-global slot that admits by memory (two OOMs took the desktop session down). A job +that declares an estimate — an e2e suite 1.5 GB (`--estimate`), a build capped by +`systemd-run -p MemoryMax=5G` its cap — runs beside others while MemAvailable minus the +running jobs' estimates stays ≥ 6000 MB, and **one `next build` at a time stays hard**. A +job that declares nothing (a render, a hand `pnpm heavy -- <cmd>`, an uncapped publish +build) runs ALONE above the 6000 MB floor, as before. e2e and the builds take it on their +own; a render or any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting +for the heavy slot — held by …`, `heavy: waiting for memory …` or `heavy: waiting for the +build slot …` is the gate working, not a hang. Bypasses: `HEAVY=0`, +`HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`. See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, and the shared-data caveat. diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -184,16 +184,19 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one |---|---|---|---| | `E2E_TEST_ROUTES` | off | `1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else. | editor/app/api/test/_guard.ts, editor/instrumentation.ts | | `E2E_MODE` | `start` | `start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`. | editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs | -| `E2E_NEXT_DIST_DIR` | `.next` | The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server. | editor/next.config.ts | +| `E2E_NEXT_DIST_DIR` | `.next` | The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir). | editor/next.config.ts, export/next.config.ts | +| `E2E_DATA_ROOT` | the editor directory | Where the editor test server's data lives: `test-transcripts/`, `test-settings.json` and the disposable changelogs sit under it. The test server's scripts and the specs' `testPaths()` read the same variable, so they agree by construction. E2E_-prefixed, never TRANSCRIPTS_DIR: a `--share-data` worktree's `.worktree-env` points that at the real corpus. | editor/package.json (dev:test, start:test), editor/e2e/testPaths.ts | +| `E2E_WORKERS` | 1 | How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker. | editor/playwright.config.ts (editor/e2e/servers.ts) | +| `E2E_SERIAL_LAST` | — | Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole. | editor/playwright.config.ts | | `E2E_BUILD_CHECKED` | — | Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again. | editor/playwright.config.ts, umtool/playwright.config.ts | | `E2E_QUEUE` | on | `0` skips the machine-global e2e queue (the port check still runs). | scripts/queue-lock.mjs | | `E2E_PORT_CHECK` | on | `0` skips the pre-run check that the suite's ports are free. | scripts/queue-lock.mjs | | `E2E_QUEUE_TIMEOUT` | wait forever | Seconds to wait for the queue before giving up. | scripts/queue-lock.mjs | | `E2E_PORT_GRACE_MS` | `3000` | How long the port check waits for a just-freed port. | scripts/queue-lock.mjs | -| `E2E_QUEUE_LOCK_FILE` | one per machine | The queue's lock file; the queue's own tests point it elsewhere. | scripts/queue-lock.mjs | +| `E2E_QUEUE_LOCK_FILE` | one per machine | The legacy queue's lock file (a named suite's is `<file>.<name>`); the queue's own tests point it elsewhere. | scripts/queue-lock.mjs | | `QUEUE_LOCK_HELD` | — | Set by the queue for the command it runs, so a nested wrapper passes through. | scripts/queue-lock.mjs | -| `HEAVY_HELD` | — | Set by the heavy slot for the command it runs, so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through. | scripts/queue-lock.mjs | -| `HEAVY_LOCK_FILE` | one per machine | The heavy slot's lock file; the gate's own tests point it elsewhere. | scripts/queue-lock.mjs | +| `HEAVY_HELD` | — | Set by the heavy slot for the command it runs (`build` inside a build), so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through — except a build inside a non-build, which still waits for the build slot. | scripts/queue-lock.mjs | +| `HEAVY_LOCK_FILE` | one per machine | The heavy slot's lock file (its line, build slot and job tickets sit beside it: `.admit`, `.build`, `.jobs/`); the gate's own tests point it elsewhere. | scripts/queue-lock.mjs | | `HEAVY_MEMINFO_FILE` | `/proc/meminfo` | Where the memory floor reads MemAvailable; the gate's tests hand it a fake. | scripts/queue-lock.mjs | | `HEAVY_POLL_MS` | `5000` | How often a run waiting for the memory floor re-reads it. | scripts/queue-lock.mjs | | `PLAYWRIGHT_BASE_URL` | `http://localhost:<PORT>` | The editor test server's URL; the worktree injector sets it. | editor/playwright.config.ts, editor/e2e/baseUrl.ts | diff --git a/WORKTREES.md b/WORKTREES.md @@ -4,8 +4,10 @@ Git worktrees let you check out several branches at once, each in its own direct sharing one `.git`. This repo supports running multiple worktrees **simultaneously** by giving each worktree its own non-colliding block of ports. -That applies to **dev servers**. **e2e suites are deliberately serialized**: one run at a -time across the whole machine, everyone else waits in line. See [The e2e queue](#the-e2e-queue). +That applies to **dev servers**. **e2e suites are queued per suite**: one run of each suite +(editor, export, homepage, umtool) at a time across the whole machine — a second run of the +same suite waits in line — while different suites run side by side, admitted by memory. +See [The e2e queue](#the-e2e-queue). The helper is `scripts/worktree.mjs`, exposed as `pnpm wt`. @@ -58,37 +60,70 @@ pnpm wt add feature-x # creates ../feature-x, prints its ports, seeds s # terminal B (../feature-x): pnpm dev:editor -> http://localhost:3101 # both run at once, no EADDRINUSE -# e2e is queued, not parallel — start it anywhere, it waits its turn: +# the same suite is queued — start it anywhere, it waits its turn: pnpm e2e # main: runs now cd ../feature-x && pnpm e2e # feature-x: prints "waiting …", starts when main finishes +# a different suite runs beside it (when memory allows): +pnpm --filter umtool run e2e # main: runs now, beside the editor suite ``` ## The e2e queue -Every e2e entry point takes a machine-global lock before it runs, so **exactly one suite -runs at a time**. Starting a second one is not an error — it prints who holds the queue and -blocks until its turn: +Every e2e entry point takes a machine-global lock named for its package, so **one run of +each suite at a time** — the same suite started again waits; a different suite does not. +Starting a second run of a suite is not an error — it prints who holds the queue and blocks +until its turn: ``` queue-lock: waiting for the e2e queue — held by yt-dlp-transcript-browser (main, pid 2401494) for 4m12s - (one e2e run at a time, machine-wide; E2E_QUEUE=0 to bypass) + (one run of each e2e suite at a time, machine-wide; E2E_QUEUE=0 to bypass) queue-lock: still waiting (5m00s) ``` -**A long wait here is normal, not a hang** — the serial suite is ~24 minutes. - -Queued: `pnpm e2e`, `pnpm e2e:sharded` (including its `docker build`), export's `e2e`, -`e2e:hub`, `e2e:2origin`, `e2e:report`, and homepage's and umtool's `e2e`. Wrapping is at the *package* -level, so `pnpm --filter editor run e2e` is covered too, and a nested invocation passes -through instead of deadlocking. Not queued on purpose: a raw `pnpm --filter editor exec -playwright test`, the escape hatch for debugging a single spec, and the `e2e:ui` +**A long wait here is normal, not a hang** — the editor suite is ~20 minutes. + +| Suite | Queue (`--name`) | Entry points | +|---|---|---| +| editor | `e2e-editor` | `pnpm e2e` (root), `pnpm --filter editor run e2e` | +| export | `e2e-export` | export's `e2e`, `e2e:hub`, `e2e:2origin`, `e2e:report` — one at a time among themselves | +| homepage | `e2e-homepage` | homepage's `e2e` | +| umtool | `e2e-umtool` | umtool's `e2e` | +| sharded | `e2e` | `pnpm e2e:sharded` (including its `docker build`) — the legacy one-for-all name, and it runs ALONE in the heavy slot | + +Their ports (`common/lib/ports.mjs`) and fixture files are disjoint, which is what lets two +different suites run at once. The editor suite's own export dev server builds into +`export/.next/e2e-editor` (`E2E_NEXT_DIST_DIR`), because Next allows one `next dev` per +dist dir and the export suite's server may be running beside it. Wrapping is at the +*package* level, so `pnpm --filter editor run e2e` is covered too, and a nested invocation +passes through instead of deadlocking. Not queued on purpose: a raw `pnpm --filter editor +exec playwright test`, the escape hatch for debugging a single spec, and the `e2e:ui` interactive sessions. +A suite's order of business: its queue, the port preflight, its start-mode build +(`--prebuild`: `scripts/e2e-stamp.mjs ensure <pkg>`, a 5 GB build admitted as one — editor +and umtool), then its own admission to the heavy slot (`--estimate 1500`), then the run. + +### Every suite at once: `pnpm e2e:all` + +```sh +pnpm e2e:all # editor, export (×4), homepage, umtool — side by side +pnpm e2e:all --only editor,umtool # a package, or one suite id (export-hub, …) +``` + +`scripts/e2e-all.mjs` starts one lane per package at once (export's four configs run in +order in theirs), each suite through its own package script — the queue, the preflight, the +build and every bypass behave exactly as when it runs alone. It prints a line as each suite +starts and ends, writes each suite's output to `test-results-e2e-all/<suite>.log`, and ends +with one summary: per suite passed / failed / flaky / skipped (from the suite's own json +report — only one written by this run counts), its test time, how long it waited for its +turn, and every failed test by `file:line`; then the wall time against the sum of the +suites' own. Exit 0 only when every suite passed. The release gate's e2e in one command. + ### Root `pnpm e2e` is the editor's, and only the editor's The root script is `pnpm --filter editor run e2e`, so a spec name appended to it goes to the **editor's** playwright: `pnpm run e2e clip-bench.spec.ts` matches nothing there, holds -the machine-global lock for the whole ~24-minute editor suite, and never runs the spec you +the editor suite's machine-global lock for the whole ~20-minute suite, and never runs the spec you meant. Every other package's suite goes through its own filter: | Suite | Command | @@ -104,9 +139,10 @@ data — `umtool/song/paths.mjs`'s `SONG_DATA`, which is `SONG_DIR` if set and directory — the fixture is an empty-state copy with the heavy audio symlinked in — and a machine without the data builds an empty fixture whose song-data specs skip. -The lock lives at `<git-common-dir>/e2e-queue.lock`, which resolves to the same file from -every worktree. The kernel releases it when the holding process's fd closes, so a `kill -9` -or a crashed run can never strand the queue — there is no stale-lock recovery to run. +The locks live at `<git-common-dir>/<name>-queue.lock` (`e2e-editor-queue.lock`, …), which +resolve to the same files from every worktree. The kernel releases a lock when the holding +process's fd closes, so a `kill -9` or a crashed run can never strand the queue — there is no +stale-lock recovery to run. ### Aborting on a busy port @@ -148,46 +184,69 @@ Verify the queue with `pnpm test:scripts`. ## The heavy slot (`pnpm heavy`) -An e2e suite, a `next build` and a video render each want several GB, and two of them at -once is how this machine OOMed (taking the desktop session with it). So all three go -through ONE more machine-global lock, the **heavy slot**, and start only once -`/proc/meminfo`'s MemAvailable is at least a floor (6000 MB): +An e2e suite, a `next build` and a video render each want several GB, and the wrong two at +once is how this machine OOMed (taking the desktop session with it). So all of them go +through ONE more machine-global gate, the **heavy slot**, which admits a job **by memory**: + +- A job that **declares an estimate** is admitted while + `MemAvailable − Σ(estimates of the jobs already running) ≥ HEAVY_MIN_FREE_MB` (6000 MB). + An e2e suite declares 1.5 GB (`--estimate 1500` in each package's script — the editor's + per worker, `--scale-by E2E_WORKERS`, `auto` counting as 3); a `next build` + run under `systemd-run … -p MemoryMax=5G` declares its cap (the e2e build does). +- **One `next build` at a time stays a hard rule**, whatever the memory: a build waits for + the build slot, including one started from inside an admitted run. +- A job that **declares nothing runs ALONE**, once MemAvailable is at least the floor — as + every heavy job did before release 24: a render, a hand `pnpm heavy -- <cmd>`, a publish + stage's (uncapped) build. It waits for the running jobs to finish, and none is admitted + beside it. ```sh -pnpm heavy -- <cmd…> # any heavy command, by hand -pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … # a render +pnpm heavy -- <cmd…> # alone (no estimate) +pnpm heavy -- systemd-run --user --scope -p MemoryMax=5G -p MemorySwapMax=0 \ + pnpm --filter editor exec next build # a build, 5 GB: beside suites, never beside a build +node scripts/queue-lock.mjs --heavy --estimate 2000 -- <cmd…> # declare an estimate by hand +pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … # a render (alone) ``` Who takes it, and in what order: -- **Every e2e entry point** (the same ones the e2e queue covers): the heavy slot FIRST, - then the e2e queue. One order everywhere, so nothing can deadlock — and a heavy command - that starts another (`pnpm heavy -- pnpm e2e`, a build stage run by an e2e suite's - editor) passes straight through (`HEAVY_HELD`), as a nested e2e run always has. +- **Every e2e entry point**: its suite's queue first, then its build (if any), then its own + admission. A heavy command that starts another (`pnpm heavy -- pnpm e2e`, a build stage + run by an e2e suite's editor) passes straight through (`HEAVY_HELD`) — except a build, + which still takes the build slot. The legacy `e2e` queue (the sharded runner) keeps the + old order: the slot first, then the queue. - **The publish stages' `next build`** — a site's, the hub's, the homepage's - (`common/publish/build.ts`, `heavyGated`). The wait shows in the stage's log, and a - Cancel still stops the build (the gate forwards SIGTERM). In a docker-runner container - the slot is the container's own; the floor still reads the host's memory, which - throttles a fan-out when the host runs low. + (`common/publish/build.ts`, `heavyGated`): uncapped, so alone. The wait shows in the + stage's log, and a Cancel still stops the build (the gate forwards SIGTERM). In a + docker-runner container the slot is the container's own; the floor still reads the host's + memory, which throttles a fan-out when the host runs low. - **A render**, by hand, as above. -The slot is taken before the floor is waited for, so nobody slips in while the holder -waits for memory. A waiter is told what it waits behind: +Waiting is in one line, so nobody slips in ahead: the job at the head keeps its place while +it waits for memory. A waiter is told what it waits behind: ``` -queue-lock: waiting for the heavy slot — held by feature-x (feature-x, pid 31337) for 2m10s: playwright test -heavy: waiting for memory — 4210 MB available, the floor is 6000 MB +queue-lock: waiting for the heavy slot — held by feature-x (feature-x, pid 31337, 1500 MB) for 2m10s: playwright test +heavy: waiting for memory — 7200 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB +heavy: waiting for the build slot — one next build at a time; running: main (main, pid 4242, 5120 MB, a build) … +heavy: admitted beside 1 running job (9100 MB available, 1500 MB promised to them, the floor is 6000 MB) ``` -The lock is `<git-common-dir>/heavy-queue.lock`, released by the kernel like the e2e one. -A machine whose MemTotal is under the floor is told so and runs; with no usable `flock` the -gate warns and runs on the floor alone — it is a safety net, not a correctness lock. +The pieces sit in the git common dir: `heavy-queue.lock` (the slot — held SHARED by an +admitted weighted job, EXCLUSIVELY by a job that runs alone, so an older checkout's copy of +the gate, which always takes it exclusively, still waits for every new-style job and is +never joined by one), `heavy-queue.lock.admit` (the line), `heavy-queue.lock.build` (the +build slot) and `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its +estimate and what it is; a ticket whose process is gone is dropped). The kernel releases +every lock when its holder's fd closes. A machine whose MemTotal is under the floor is told +so and runs one job at a time; with no usable `flock` the gate warns and runs on the floor +alone — it is a safety net, not a correctness lock. | Variable | Effect | |---|---| | `HEAVY=0` | Skip the heavy slot AND the memory floor | -| `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off) | -| `HEAVY_TIMEOUT=<seconds>` | Give up waiting (slot, then floor) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | +| `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off; the build rule still holds) | +| `HEAVY_TIMEOUT=<seconds>` | Give up waiting (line, slot, memory) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | ### A render and the transcription lane diff --git a/common/lib/envVars.test.ts b/common/lib/envVars.test.ts @@ -21,8 +21,10 @@ const SKIP_DIRS = new Set(["node_modules", ".next", "out", "public", "test-resul // The platform's own variables: read here, documented by node, Next, a shell, // Playwright (TEST_WORKER_INDEX, which it sets in each worker process; the -// two-origin config reads it to stage only in the runner). -const PLATFORM = new Set(["CI", "NODE_ENV", "NEXT_RUNTIME", "LD_LIBRARY_PATH", "PATH", "HOME", "NODE_OPTIONS", "TEST_WORKER_INDEX"]); +// two-origin config reads it to stage only in the runner — and +// TEST_PARALLEL_INDEX, the worker's slot, which the editor suite reads to find +// its own servers and data root). +const PLATFORM = new Set(["CI", "NODE_ENV", "NEXT_RUNTIME", "LD_LIBRARY_PATH", "PATH", "HOME", "NODE_OPTIONS", "TEST_WORKER_INDEX", "TEST_PARALLEL_INDEX"]); function codeFiles(): string[] { const out: string[] = []; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -182,16 +182,19 @@ const DECLARED: EnvVarDecl[] = [ // ── test: harnesses, fakes and test-mode branches ────────────────────── { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." }, { name: "E2E_MODE", audience: "test", default: "`start`", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs", doc: "`start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`." }, - { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server." }, + { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts, export/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir)." }, + { name: "E2E_DATA_ROOT", audience: "test", default: "the editor directory", readBy: "editor/package.json (dev:test, start:test), editor/e2e/testPaths.ts", doc: "Where the editor test server's data lives: `test-transcripts/`, `test-settings.json` and the disposable changelogs sit under it. The test server's scripts and the specs' `testPaths()` read the same variable, so they agree by construction. E2E_-prefixed, never TRANSCRIPTS_DIR: a `--share-data` worktree's `.worktree-env` points that at the real corpus." }, + { name: "E2E_WORKERS", audience: "test", default: "1", readBy: "editor/playwright.config.ts (editor/e2e/servers.ts)", doc: "How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker." }, + { name: "E2E_SERIAL_LAST", audience: "test", default: "—", readBy: "editor/playwright.config.ts", doc: "Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole." }, { name: "E2E_BUILD_CHECKED", audience: "test", default: "—", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts", doc: "Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again." }, { name: "E2E_QUEUE", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the machine-global e2e queue (the port check still runs)." }, { name: "E2E_PORT_CHECK", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the pre-run check that the suite's ports are free." }, { name: "E2E_QUEUE_TIMEOUT", audience: "test", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds to wait for the queue before giving up." }, { name: "E2E_PORT_GRACE_MS", audience: "test", default: "`3000`", readBy: "scripts/queue-lock.mjs", doc: "How long the port check waits for a just-freed port." }, - { name: "E2E_QUEUE_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The queue's lock file; the queue's own tests point it elsewhere." }, + { name: "E2E_QUEUE_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The legacy queue's lock file (a named suite's is `<file>.<name>`); the queue's own tests point it elsewhere." }, { name: "QUEUE_LOCK_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the queue for the command it runs, so a nested wrapper passes through." }, - { name: "HEAVY_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the heavy slot for the command it runs, so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through." }, - { name: "HEAVY_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The heavy slot's lock file; the gate's own tests point it elsewhere." }, + { name: "HEAVY_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the heavy slot for the command it runs (`build` inside a build), so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through — except a build inside a non-build, which still waits for the build slot." }, + { name: "HEAVY_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The heavy slot's lock file (its line, build slot and job tickets sit beside it: `.admit`, `.build`, `.jobs/`); the gate's own tests point it elsewhere." }, { name: "HEAVY_MEMINFO_FILE", audience: "test", default: "`/proc/meminfo`", readBy: "scripts/queue-lock.mjs", doc: "Where the memory floor reads MemAvailable; the gate's tests hand it a fake." }, { name: "HEAVY_POLL_MS", audience: "test", default: "`5000`", readBy: "scripts/queue-lock.mjs", doc: "How often a run waiting for the memory floor re-reads it." }, { name: "PLAYWRIGHT_BASE_URL", audience: "test", default: "`http://localhost:<PORT>`", readBy: "editor/playwright.config.ts, editor/e2e/baseUrl.ts", doc: "The editor test server's URL; the worktree injector sets it." }, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -136,6 +136,9 @@ - **An agent can answer the operator's notes in umtool, and its replies say they are an agent's.** The MCP's `notes` tool now writes a reply (`action: "reply"`, with `note_id`, `text` and `resolve`) in umtool instead of answering with the `umtool notes reply` command to run; umtool stamps it "agent" and badges it on the page. umtool takes an agent's write only with the editor's `WORKER_TOKEN` as a bearer token — from its own environment, else the editor's `editor/.env` — and refuses any other token (401); a write from umtool's own page is the operator's as before. Register the MCP with `UMTOOL_URL` and `WORKER_TOKEN`. Needs a rebuild and restart of umtool, and a restart of the MCP server. - **Captions the index re-read under the newer caption-track rule now reach the stats and charts.** When the index re-reads a video's captions without any of its files changing — as it did once for videos whose served `en` track had parsed to nothing — the stats behind the homepage, the hub and the sites' charts kept the old figures (no transcript, the old cue count) until something else about the video changed. The stats now follow the captions the index holds, and the first stats build after updating corrects the videos already affected. Needs a rebuild and restart of the editor, then a stats build (or a site, hub or homepage build). - **Every e2e run records its own per-spec timings.** The editor, umtool, homepage and export suites now record each run in the branch's timing history the moment it ends (`scripts/e2e-timings-reporter.mjs`), so re-running a few specs no longer loses the record of the full run before it; `node scripts/e2e-timings.mjs` still prints a run against the last one. umtool's suite skips, with the reason, the face-detector tests on a machine without the detector and the chunk-twin check when the data has no twins, instead of failing. +- **Different e2e suites run side by side, and `pnpm e2e:all` runs them all with one summary.** Each package's suite now waits only for another run of the SAME suite (`e2e-editor`, `e2e-export`, `e2e-homepage`, `e2e-umtool`), so the editor, export, homepage and umtool suites can run at once. `pnpm e2e:all` starts one per package, writes each suite's output to `test-results-e2e-all/`, and ends with one table — passed, failed, flaky and skipped per suite, how long each waited, every failed test by file and line — and the wall time against the sum of the suites' own. +- **The heavy slot admits jobs by memory, one build at a time.** An e2e suite (1.5 GB) or a capped `next build` (its 5 GB cap) now starts beside other heavy work while the memory left after what the running jobs were promised stays above the 6000 MB floor; two `next build`s still never run at once. A job that declares no estimate — a render, a hand `pnpm heavy -- …`, a publish stage's build — runs alone, as before. A waiter is told what it waits for (`waiting for memory — … MB promised to 2 running jobs`, `waiting for the build slot`). +- **The editor suite can run on several workers, each with servers of its own.** `E2E_WORKERS=2` (or `auto`, from memory, up to 3) gives every worker its own editor, export server and Ollama stub over its own data directory; specs that write into the checkout's build outputs or time a wall clock run afterwards on one worker. One worker stays the default until the parallel runs are measured. ## [0.11.0] - 2026-09-30 - **Transcripts that arrived after a video was first seen are counted.** The stats behind the homepage, the hub and every site's charts were cached per video and refreshed only when the video's metadata changed, so a transcript that came later — a Whisper run days after the download, or a video downloaded after the last index build — never reached them, and a video with YouTube captions alone had no transcription date. Counts and charts were low; the homepage could show a site with 0 transcripts, 0 channels and 0 hours while it served its videos. A stat is now also redone whenever the index re-reads the video, every transcript has a date, and a captioned video is dated by when its captions arrived rather than by a later Normalize run, so its place on "Transcribed over time" can move. **After updating, rebuild and restart the editor before anything else:** until then, **Build stats dataset** runs the old code and would undo the new stats, while a site, hub or homepage build already runs the new code — and the first stats build of any kind re-reads every video once (about 10–30 minutes on a large archive; it can be stopped and picks up where it stopped). Then build the index, the stats, the homepage, the hub, and the sites. diff --git a/editor/e2e/aliases.spec.ts b/editor/e2e/aliases.spec.ts @@ -1,5 +1,5 @@ import { expect, test } from "@playwright/test"; -import { resetData, writeSite, readJson } from "./helpers"; +import { resetData, writeSite, readJson, testPaths } from "./helpers"; // Search-aliases authoring on the site's Search aliases tab: the global // dictionary and the site's overrides, both. Global aliases seed with defaults; @@ -42,7 +42,7 @@ test.describe("search aliases authoring", () => { await expect(async () => { const cfg = await readJson<AliasFile>( - "test-transcripts/sites/testsite/search-aliases.json", + `${testPaths().transcriptsDir}/sites/testsite/search-aliases.json`, ); const entry = cfg.aliases.find((a) => a.id === "testconcept"); expect(entry).toBeTruthy(); @@ -62,7 +62,7 @@ test.describe("search aliases authoring", () => { await expect(async () => { const cfg = await readJson<AliasFile & { aliases: { suggestion: string }[] }>( - "test-transcripts/search-aliases.json", + `${testPaths().transcriptsDir}/search-aliases.json`, ); expect(cfg.aliases[0].suggestion).toBe("\\bCHANGED\\b"); }).toPass({ timeout: 5000 }); diff --git a/editor/e2e/attribution.spec.ts b/editor/e2e/attribution.spec.ts @@ -12,6 +12,7 @@ import { writeChannelConfig, writeDigestVideo, writeSettings, + testPaths, } from "./helpers"; import type { AttributionRecord } from "../../common/lib/attribution"; @@ -48,7 +49,7 @@ const TEXTONLY = "attrvid0002"; const SLOW = 120_000; function dataRel(videoId: string, file: string): string { - return join("test-transcripts", "channels", CHANNEL, "data", videoId, file); + return join(testPaths().transcriptsDir, "channels", CHANNEL, "data", videoId, file); } const DIARIZED_AT = "2026-08-06T00:00:00.000Z"; @@ -405,7 +406,7 @@ test("the stage card and the operation pages show attribution beside diarization test.setTimeout(SLOW); await seedChannel(); await writeSettings(attributionSettings()); - await rm(resolvePath(`test-transcripts/channels/${CHANNEL}/snapshot.json`), { + await rm(resolvePath(`${testPaths().transcriptsDir}/channels/${CHANNEL}/snapshot.json`), { force: true, }); await generateReport(page, CHANNEL); diff --git a/editor/e2e/audio-check-scenarios.spec.ts b/editor/e2e/audio-check-scenarios.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; import type { @@ -14,7 +15,7 @@ import type { } from "../../common/lib/downloadOutcome"; const CHANNEL = "test-audio-check"; -const CHANNEL_ROOT = `test-transcripts/channels/${CHANNEL}`; +const CHANNEL_ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; // urlIdYouTube on "https://odysee.com/abc123" returns "abc123". const VIDEO_ID = "abc123"; diff --git a/editor/e2e/auto-queue.spec.ts b/editor/e2e/auto-queue.spec.ts @@ -8,6 +8,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -53,7 +54,7 @@ const TWO_WORKERS = [ ]; async function makeChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -108,7 +109,7 @@ function downloadAutoQueue(root: Group, maxWorkers: number | null = null) { // channels so the runner's per-platform gate serializes downloads → a // deterministic cross-channel order. async function makeDownloadChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -205,7 +206,7 @@ function pickOrder( async function allTranscribed(slug: string, ids: string[]): Promise<boolean> { for (const id of ids) { if ( - !(await pathExists(`test-transcripts/channels/${slug}/data/${id}/transcript.json`)) + !(await pathExists(`${testPaths().transcriptsDir}/channels/${slug}/data/${id}/transcript.json`)) ) { return false; } @@ -281,9 +282,9 @@ test("respects the saved worker default: a disabled worker is never used", async // (.worker-defaults.json) enables only gpu — cpu must stay disabled, and the // runner must honor that (regression for the boot-time reconfigure() bug that // bypassed applyDefaults()). - await mkdir(resolvePath("test-transcripts/.workers"), { recursive: true }); + await mkdir(resolvePath(`${testPaths().transcriptsDir}/.workers`), { recursive: true }); await writeFile( - resolvePath("test-transcripts/.workers/defaults.json"), + resolvePath(`${testPaths().transcriptsDir}/.workers/defaults.json`), JSON.stringify({ enabledWorkerIds: ["gpu"] }), ); @@ -312,7 +313,7 @@ test("respects the saved worker default: a disabled worker is never used", async // Every transcription ran on gpu — cpu (disabled by the saved default) was never used. for (const id of ids) { const outcome = await readJson<{ worker?: { id?: string } }>( - `test-transcripts/channels/alpha/data/${id}/transcribe-outcome.json`, + `${testPaths().transcriptsDir}/channels/alpha/data/${id}/transcribe-outcome.json`, ); expect(outcome.worker?.id).toBe("gpu"); } @@ -398,7 +399,7 @@ test("UI: build a policy in the editor, save it, and start the runner", async ({ // The policy persisted to settings. const settings = await readJson<{ autoQueue: { transcription: { enabled: boolean; root: { children: { match?: { value?: string } }[] } } }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(settings.autoQueue.transcription.enabled).toBe(true); expect( settings.autoQueue.transcription.root.children.some( @@ -475,7 +476,7 @@ test("UI: Move to top jumps a rule to the front of its siblings", async ({ autoQueue: { transcription: { root: { children: { match?: { value?: string } }[] } }; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect( settings.autoQueue.transcription.root.children.map((c) => c.match?.value), ).toEqual(["gamma", "alpha", "beta"]); @@ -635,7 +636,7 @@ test("Drain completes when an auto-transcribe unit is parked behind a busy worke // fixture runs ~50s when the video id contains "slowop", so a manual transcribe // holds the only worker long enough for the auto unit to park and for us to // drain. "alpha": a normal pending video the auto-runner will pick. - const busy = resolvePath("test-transcripts/channels/busy"); + const busy = resolvePath(`${testPaths().transcriptsDir}/channels/busy`); await mkdir(`${busy}/data/slowop1`, { recursive: true }); await writeFile( `${busy}/config.json`, @@ -739,7 +740,7 @@ test("Drain completes (and lets the unit finish) when an auto-transcribe unit is ) .toBe(true); expect( - await pathExists("test-transcripts/channels/alpha/data/slowop1/transcript.json"), + await pathExists(`${testPaths().transcriptsDir}/channels/alpha/data/slowop1/transcript.json`), ).toBe(false); // 2) Drain the runner. Pre-fix this hung forever (event-loop starvation); @@ -814,7 +815,7 @@ async function makeFilteredDownloadChannel( ids: string[], unscanned: number, ) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -873,13 +874,13 @@ test("the download lane scans a filtered channel before it downloads from it", a await startRunner(request, "download"); const invocationsPath = - "test-transcripts/channels/filtered/fake-ytdlp.invocations"; + `${testPaths().transcriptsDir}/channels/filtered/fake-ytdlp.invocations`; await expect .poll( async () => (await readText(invocationsPath)).includes("prefetch:") || (await pathExists( - "test-transcripts/channels/filtered/data/guestvid0001/transcript.en.vtt", + `${testPaths().transcriptsDir}/channels/filtered/data/guestvid0001/transcript.en.vtt`, )), { timeout: 60_000 }, ) @@ -899,7 +900,7 @@ test("the download lane scans a filtered channel before it downloads from it", a // that window is a race with the regen, not a fact about the feature. The // settlement itself is pinned in title-filter.spec.ts. const scan = await readJson<{ entries: Record<string, unknown> }>( - "test-transcripts/channels/filtered/metadata-scan.json", + `${testPaths().transcriptsDir}/channels/filtered/metadata-scan.json`, ); expect(Object.keys(scan.entries).sort()).toEqual([ "guestvid0001", @@ -979,7 +980,7 @@ test("UI: the order select round-trips through save", async ({ page }) => { async () => { const s = await readJson<{ autoQueue?: { transcription?: { order?: string } }; - }>("test-settings.json").catch(() => null); + }>(testPaths().settingsFile).catch(() => null); return s?.autoQueue?.transcription?.order ?? null; }, { timeout: 10_000 }, @@ -1320,7 +1321,7 @@ test("UI: each operation page carries its own lane, and the rail as context", as const downloadsPaused = async () => ( await readJson<{ autoQueue?: { download?: { held?: boolean } } }>( - "test-settings.json", + testPaths().settingsFile, ).catch(() => ({}) as { autoQueue?: { download?: { held?: boolean } } }) ).autoQueue?.download?.held ?? false; const pause = download.getByRole("button", { name: "Pause Downloads" }); @@ -1421,7 +1422,7 @@ test("the digest lane offers Shortest first, and has no Reach axis", async ({ ( await readJson<{ autoQueue?: { digest?: { held?: boolean } }; - }>("test-settings.json").catch(() => null) + }>(testPaths().settingsFile).catch(() => null) )?.autoQueue?.digest?.held ?? null, { timeout: 15_000 }, ) @@ -1439,7 +1440,7 @@ test("the digest lane offers Shortest first, and has no Reach axis", async ({ const s = await readJson<{ autoQueue?: { digest?: { order?: string; held?: boolean } }; digest?: { recencyOrder?: string; recencyReach?: string }; - }>("test-settings.json").catch(() => null); + }>(testPaths().settingsFile).catch(() => null); return [ s?.autoQueue?.digest?.order, s?.digest?.recencyOrder ?? "gone", @@ -1505,7 +1506,7 @@ test("a retired pause field holds nothing, and does not survive a write", async const s = await readJson<{ autoQueue?: { digest?: { held?: boolean } }; digest?: { digestsPaused?: boolean }; - }>("test-settings.json").catch(() => null); + }>(testPaths().settingsFile).catch(() => null); if (!s) return null; return `held=${String(s.autoQueue?.digest?.held)}/retired=${String( "digestsPaused" in (s.digest ?? {}), diff --git a/editor/e2e/auto-refresh.spec.ts b/editor/e2e/auto-refresh.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readJson, resetData, writeSettings } from "./helpers"; +import { readJson, resetData, writeSettings, testPaths } from "./helpers"; // Covers the global passive auto-refresh: the Settings field (default 5s, // persists, accepts 0=off, rejects out-of-range) and the runtime behavior — @@ -23,7 +23,7 @@ test.describe("auto-refresh setting", () => { ).toBeVisible(); const saved = await readJson<{ autoRefreshIntervalSeconds?: number }>( - "test-settings.json", + testPaths().settingsFile, ); expect(saved.autoRefreshIntervalSeconds).toBe(12); @@ -40,7 +40,7 @@ test.describe("auto-refresh setting", () => { ).toBeVisible(); const saved = await readJson<{ autoRefreshIntervalSeconds?: number }>( - "test-settings.json", + testPaths().settingsFile, ); expect(saved.autoRefreshIntervalSeconds).toBe(0); }); diff --git a/editor/e2e/auto-report-refresh.spec.ts b/editor/e2e/auto-report-refresh.spec.ts @@ -1,6 +1,6 @@ import { writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { readJson, resetData, resolvePath, generateReport } from "./helpers"; +import { readJson, resetData, resolvePath, generateReport, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; // Verifies the global debounced snapshot scheduler: a direct (non-managed) @@ -8,10 +8,10 @@ import { baseUrl } from "./baseUrl"; // its own, without visiting the channel page or clicking "Refresh report". const SLUG = "test-transcribe"; -const SNAPSHOT_REL = `test-transcripts/channels/${SLUG}/snapshot.json`; +const SNAPSHOT_REL = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; function dataRel(videoId: string, file: string): string { - return `test-transcripts/channels/${SLUG}/data/${videoId}/${file}`; + return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } async function seedTranscript(videoId: string): Promise<void> { diff --git a/editor/e2e/auto-subs-replace.spec.ts b/editor/e2e/auto-subs-replace.spec.ts @@ -24,11 +24,12 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; const SLUG = "test-auto-subs"; -const ROOT = `test-transcripts/channels/${SLUG}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${SLUG}`; const SNAPSHOT_REL = `${ROOT}/snapshot.json`; // Shaped after real yt-dlp --write-auto-subs output. @@ -423,7 +424,7 @@ test("the auto-queue opt-in is off by default and persists when enabled", async async () => { const settings = await readJson<{ autoQueue?: { transcription?: { replaceAutoSubs?: boolean } }; - }>("test-settings.json").catch(() => null); + }>(testPaths().settingsFile).catch(() => null); return settings?.autoQueue?.transcription?.replaceAutoSubs ?? null; }, { timeout: 10_000 }, diff --git a/editor/e2e/availability-backfill.spec.ts b/editor/e2e/availability-backfill.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; type AvailabilityFile = { @@ -22,12 +23,12 @@ async function seedVideo( metadata: Record<string, unknown>, ): Promise<void> { const dir = resolvePath( - `test-transcripts/channels/${CHANNEL}/data/${id}`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${id}`, ); await mkdir(dir, { recursive: true }); await writeFile( resolvePath( - `test-transcripts/channels/${CHANNEL}/data/${id}/metadata.info.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${id}/metadata.info.json`, ), JSON.stringify({ id, @@ -59,11 +60,11 @@ test("download backfills availability.json from metadata", async ({ page }) => { // Seeded videos should now have availability.json written from metadata. expect( await pathExists( - `test-transcripts/channels/${CHANNEL}/data/seededPrivate1/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/seededPrivate1/availability.json`, ), ).toBe(true); const priv = await readJson<AvailabilityFile>( - `test-transcripts/channels/${CHANNEL}/data/seededPrivate1/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/seededPrivate1/availability.json`, ); expect(priv.availability).toBe("private"); expect(priv.webpageUrl).toBe( @@ -71,14 +72,14 @@ test("download backfills availability.json from metadata", async ({ page }) => { ); const plain = await readJson<AvailabilityFile>( - `test-transcripts/channels/${CHANNEL}/data/seededPlain1/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/seededPlain1/availability.json`, ); expect(plain.availability).toBe("public"); // A newly-fetched video also gets a sidecar from its metadata. expect( await pathExists( - `test-transcripts/channels/${CHANNEL}/data/fake00000001/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/fake00000001/availability.json`, ), ).toBe(true); }); @@ -92,7 +93,7 @@ test("backfill skips videos that already have an availability sidecar", async ({ // backfill (which would otherwise infer "private" from metadata). await writeFile( resolvePath( - `test-transcripts/channels/${CHANNEL}/data/seededPrivate1/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/seededPrivate1/availability.json`, ), JSON.stringify({ availability: "deleted", @@ -108,7 +109,7 @@ test("backfill skips videos that already have an availability sidecar", async ({ }); const after = await readJson<AvailabilityFile>( - `test-transcripts/channels/${CHANNEL}/data/seededPrivate1/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/seededPrivate1/availability.json`, ); expect(after.availability).toBe("deleted"); expect(after.checkedAt).toBe("2099-01-01T00:00:00.000Z"); diff --git a/editor/e2e/availability.spec.ts b/editor/e2e/availability.spec.ts @@ -9,6 +9,7 @@ import { resetData, resolvePath, writeSite, + testPaths, } from "./helpers"; const CHANNEL = "availability-test"; @@ -31,7 +32,7 @@ type AvailabilityFile = { }; function availabilityPath(id: string): string { - return `test-transcripts/channels/${CHANNEL}/data/${id}/availability.json`; + return `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${id}/availability.json`; } async function readAvailability(id: string): Promise<AvailabilityFile> { @@ -174,13 +175,13 @@ test("build index marks deleted videos in the export summaries", async ({ const { writeFile } = await import("node:fs/promises"); await writeFile( resolvePath( - `test-transcripts/channels/${CHANNEL}/data/vidpublic1/transcript.en.vtt`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/vidpublic1/transcript.en.vtt`, ), "WEBVTT\n\n00:00:00.000 --> 00:00:05.000\nhello\n", ); await writeFile( resolvePath( - `test-transcripts/channels/${CHANNEL}/data/viddeleted1/transcript.en.vtt`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/viddeleted1/transcript.en.vtt`, ), "WEBVTT\n\n00:00:00.000 --> 00:00:05.000\nhello deleted\n", ); @@ -192,7 +193,7 @@ test("build index marks deleted videos in the export summaries", async ({ const pageJson = await readJson< Array<{ id: string; isDeleted: boolean }> - >("test-transcripts/.export-index/sites/testsite/summaries/page-0000.json"); + >(`${testPaths().transcriptsDir}/.export-index/sites/testsite/summaries/page-0000.json`); const byId = new Map(pageJson.map((s) => [s.id, s])); expect(byId.get("vidpublic1")?.isDeleted).toBe(false); expect(byId.get("viddeleted1")?.isDeleted).toBe(true); diff --git a/editor/e2e/backfill.spec.ts b/editor/e2e/backfill.spec.ts @@ -11,6 +11,7 @@ import { resolvePath, writeDigestVideo, writeSettings, + testPaths, } from "./helpers"; // Active jobs, straight off the JSON API. Reloading /jobs costs hundreds of @@ -45,7 +46,7 @@ async function activeJobs( const SLUG = "test-transcribe"; function dataRel(videoId: string, file: string): string { - return `test-transcripts/channels/${SLUG}/data/${videoId}/${file}`; + return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } const BASE_SETTINGS = { @@ -106,7 +107,7 @@ async function seedTranscript(videoId: string): Promise<void> { // Real audio files in a video dir — what the re-download specs measure. async function audioFiles(videoId: string): Promise<string[]> { const dir = resolvePath( - `test-transcripts/channels/${SLUG}/data/${videoId}`, + `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}`, ); const entries = await readdir(dir).catch(() => [] as string[]); return entries.filter( @@ -126,7 +127,7 @@ type LanePolicy = { async function backfillLane(): Promise<LanePolicy> { const s = await readJson<{ autoQueue?: { backfill?: LanePolicy } }>( - "test-settings.json", + testPaths().settingsFile, ).catch(() => ({}) as { autoQueue?: { backfill?: LanePolicy } }); return s.autoQueue?.backfill ?? {}; } @@ -154,7 +155,7 @@ test("the stage card separates reachable work from what needs its media back", a await rm(resolvePath(dataRel("vidB", f)), { force: true }); } - await rm(resolvePath(`test-transcripts/channels/${SLUG}/snapshot.json`), { + await rm(resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`), { force: true, }); await generateReport(page, SLUG); @@ -575,7 +576,7 @@ test("a backfill runs concurrently with a transcription", async ({ await seedTranscript("vidA"); // Transcription work that LASTS: a fresh dir with audio and no transcript. const slowDir = resolvePath( - `test-transcripts/channels/${SLUG}/data/slowop1`, + `${testPaths().transcriptsDir}/channels/${SLUG}/data/slowop1`, ); await mkdir(slowDir, { recursive: true }); await writeFile(`${slowDir}/audio.mp3`, "fake audio slowop1\n"); @@ -664,7 +665,7 @@ test("a digest runs concurrently with a backfill, not behind it", async ({ for (const id of ["vidA", "vidB"]) await seedTranscript(id); for (let i = 0; i < 40; i++) { const id = `slowdiar${String(i).padStart(2, "0")}`; - const dir = resolvePath(`test-transcripts/channels/${SLUG}/data/${id}`); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/data/${id}`); await mkdir(dir, { recursive: true }); await writeFile(`${dir}/audio.m4a`, `fake audio ${id}\n`); await writeFile( @@ -748,7 +749,7 @@ test("the diarization page shows the channel and both populations", async ({ for (const f of await audioFiles("vidB")) { await rm(resolvePath(dataRel("vidB", f)), { force: true }); } - await rm(resolvePath(`test-transcripts/channels/${SLUG}/snapshot.json`), { + await rm(resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`), { force: true, }); await generateReport(page, SLUG); @@ -793,7 +794,7 @@ test("the dashboard pauses and resumes the backfill lane", async ({ page }) => { const laneHeld = async () => ( await readJson<{ autoQueue?: { backfill?: { held?: boolean } } }>( - "test-settings.json", + testPaths().settingsFile, ).catch(() => ({}) as { autoQueue?: { backfill?: { held?: boolean } } }) ).autoQueue?.backfill?.held ?? false; @@ -839,7 +840,7 @@ test("an operation page holds the same lane the dashboard does", async ({ const laneHeld = async () => ( await readJson<{ autoQueue?: { backfill?: { held?: boolean } } }>( - "test-settings.json", + testPaths().settingsFile, ).catch(() => ({}) as { autoQueue?: { backfill?: { held?: boolean } } }) ).autoQueue?.backfill?.held ?? false; @@ -879,7 +880,7 @@ test("an operation page holds the same lane the dashboard does", async ({ // Both halves are pinned here: the transcribe override that makes there be audio // at all, and the re-normalize that keeps the cues fresh afterwards. const YT_SLUG = "test-yt-subs"; -const YT_ROOT = `test-transcripts/channels/${YT_SLUG}`; +const YT_ROOT = `${testPaths().transcriptsDir}/channels/${YT_SLUG}`; function ytRel(videoId: string, file: string): string { return `${YT_ROOT}/data/${videoId}/${file}`; @@ -1176,7 +1177,7 @@ test("a digest entry in the snapshot does not move the backfill instrument", asy await rm(resolvePath(dataRel("vidB", f)), { force: true }); } - await rm(resolvePath(`test-transcripts/channels/${SLUG}/snapshot.json`), { + await rm(resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`), { force: true, }); await generateReport(page, SLUG); @@ -1188,7 +1189,7 @@ test("a digest entry in the snapshot does not move the backfill instrument", asy { missing?: number; ids?: string[]; eligible?: number; blocked?: number } >; buckets?: Record<string, unknown>; - }>(`test-transcripts/channels/${SLUG}/snapshot.json`); + }>(`${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`); // ONE definition of the digest work list. The writer used to keep a second // one, `buckets.noDigest`, whose answer disagreed with this entry by 11,777 // videos corpus-wide (it had no cues-staleness gate and no transcript gate). @@ -1283,14 +1284,14 @@ test("the bucket lanes' work lists land in the snapshot and move no band", async test.setTimeout(SLOW); await resetData("one-transcribe-channel-with-audio"); await writeSettings(backfillSettings()); - await rm(resolvePath(`test-transcripts/channels/${SLUG}/snapshot.json`), { + await rm(resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`), { force: true, }); await generateReport(page, SLUG); // HALF ONE: the entries are really there. Without this the invariance below // would pass vacuously over a feature that never shipped. - const snapRel = `test-transcripts/channels/${SLUG}/snapshot.json`; + const snapRel = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; type Snap = { backfill?: Record< string, diff --git a/editor/e2e/build.spec.ts b/editor/e2e/build.spec.ts @@ -5,6 +5,7 @@ import { readJson, resetData, writeSite, + testPaths, } from "./helpers"; test("build index against an empty site writes a 0-transcript manifest", async ({ @@ -14,7 +15,7 @@ test("build index against an empty site writes a 0-transcript manifest", async ( await writeSite("testsite", { channels: [] }); await buildIndex(page); const manifest = await readJson<{ totalCount: number; siteId: string }>( - "test-transcripts/.export-index/sites/testsite/summaries/manifest.json", + `${testPaths().transcriptsDir}/.export-index/sites/testsite/summaries/manifest.json`, ); expect(manifest.totalCount).toBe(0); expect(manifest.siteId).toBe("testsite"); @@ -31,13 +32,13 @@ test("build index ingests synthetic video data into shared + per-site output", a const manifest = await readJson<{ totalCount: number; channels: { name: string }[]; - }>("test-transcripts/.export-index/sites/testsite/summaries/manifest.json"); + }>(`${testPaths().transcriptsDir}/.export-index/sites/testsite/summaries/manifest.json`); expect(manifest.totalCount).toBe(1); expect(manifest.channels.map((c) => c.name)).toContain("Test YouTube Channel"); // Per-channel transcript pages are written ONCE to the shared tree. expect( await pathExists( - "test-transcripts/.export-index/shared/transcripts/test-youtube/page-0000.json", + `${testPaths().transcriptsDir}/.export-index/shared/transcripts/test-youtube/page-0000.json`, ), ).toBe(true); }); @@ -52,10 +53,10 @@ test("two sites over a shared pool get isolated, differently-filtered summaries" await writeSite("without-channel", { channels: [] }); await buildIndex(page); const withChannel = await readJson<{ totalCount: number }>( - "test-transcripts/.export-index/sites/with-channel/summaries/manifest.json", + `${testPaths().transcriptsDir}/.export-index/sites/with-channel/summaries/manifest.json`, ); const without = await readJson<{ totalCount: number }>( - "test-transcripts/.export-index/sites/without-channel/summaries/manifest.json", + `${testPaths().transcriptsDir}/.export-index/sites/without-channel/summaries/manifest.json`, ); expect(withChannel.totalCount).toBe(1); expect(without.totalCount).toBe(0); diff --git a/editor/e2e/bulk-actions.spec.ts b/editor/e2e/bulk-actions.spec.ts @@ -7,6 +7,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; // The channel video list's checkbox bulk bar must queue like every other batch @@ -122,9 +123,9 @@ test("bulk retry download submits a single retry-bucket job on the platform queu await expect(newest).toContainText("platform:odysee"); }); -const dataDir = "test-transcripts/channels/test-transcribe/data"; +const dataDir = `${testPaths().transcriptsDir}/channels/test-transcribe/data`; const failedTranscriptionsFile = - "test-transcripts/channels/test-transcribe/failed-transcriptions"; + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`; // Delete directories and Clear failed markers are synchronous, summary-style // actions (no queued job) — the point of bulk delete is to clear failed diff --git a/editor/e2e/cadence-ui.spec.ts b/editor/e2e/cadence-ui.spec.ts @@ -6,6 +6,7 @@ import { resetData, writeChannelConfig, writeSettings, + testPaths, } from "./helpers"; // The cadence UI: every interval in the app is now set as an amount plus a unit @@ -19,7 +20,7 @@ import { // parser had to change — these specs assert on the stored integers. const CHANNEL = "cadence-test"; -const CONFIG = `test-transcripts/channels/${CHANNEL}/config.json`; +const CONFIG = `${testPaths().transcriptsDir}/channels/${CHANNEL}/config.json`; type CadenceConfig = { syncIntervalMinutes?: number; @@ -132,7 +133,7 @@ test("the sync page round-trips the full-sweep cadence and confirm cap", async ( fullSweepConfirmMaxSuspects: number; keepLatestCheckIntervalMinutes: number; }; - }>("test-settings.json").then((s) => s.syncScheduler), + }>(testPaths().settingsFile).then((s) => s.syncScheduler), ) .toMatchObject({ fullSweepIntervalMinutes: 4320, @@ -170,7 +171,7 @@ test("an unrelated settings save no longer resets the keep-latest interval", asy readJson<{ adminTitle: string; syncScheduler: { keepLatestCheckIntervalMinutes: number }; - }>("test-settings.json"), + }>(testPaths().settingsFile), ) .toMatchObject({ adminTitle: "Renamed Admin", @@ -203,7 +204,7 @@ test("the sync page's save writes its block and nothing else", async ({ readJson<{ adminTitle: string; syncScheduler: { maxConcurrentSyncs: number }; - }>("test-settings.json"), + }>(testPaths().settingsFile), ) .toMatchObject({ adminTitle: "Keep Me", @@ -237,16 +238,16 @@ test("bulk apply retunes selected channels and leaves the rest alone", async ({ await expect .poll(async () => - readJson<CadenceConfig>("test-transcripts/channels/bulk-a/config.json"), + readJson<CadenceConfig>(`${testPaths().transcriptsDir}/channels/bulk-a/config.json`), ) .toMatchObject({ fullSweepIntervalMinutes: 10080, syncIntervalMinutes: 30 }); await expect .poll(async () => - readJson<CadenceConfig>("test-transcripts/channels/bulk-b/config.json"), + readJson<CadenceConfig>(`${testPaths().transcriptsDir}/channels/bulk-b/config.json`), ) .toMatchObject({ fullSweepIntervalMinutes: 10080, syncIntervalMinutes: 30 }); const c = await readJson<Record<string, unknown>>( - "test-transcripts/channels/bulk-c/config.json", + `${testPaths().transcriptsDir}/channels/bulk-c/config.json`, ); expect("fullSweepIntervalMinutes" in c).toBe(false); }); @@ -258,7 +259,7 @@ test("the Full sweep button forces a sweep the cadence would have skipped", asyn // passes fullSweep through rather than relying on the cadence gate. await resetData("availability-baseline"); const slug = "availability-test"; - const configRel = `test-transcripts/channels/${slug}/config.json`; + const configRel = `${testPaths().transcriptsDir}/channels/${slug}/config.json`; await generateReport(page, slug); await page.goto(channelStage(slug, "playlist")); diff --git a/editor/e2e/cancel.spec.ts b/editor/e2e/cancel.spec.ts @@ -4,6 +4,7 @@ import { generateReport, pathExists, resetData, + testPaths, } from "./helpers"; test("cancels a running pipeline job from the channel page", async ({ page }) => { @@ -26,7 +27,7 @@ test("cancels a running pipeline job from the channel page", async ({ page }) => // No data dir was written. expect( - await pathExists("test-transcripts/channels/slow-channel/data"), + await pathExists(`${testPaths().transcriptsDir}/channels/slow-channel/data`), ).toBe(false); }); diff --git a/editor/e2e/channel-build-toggle.spec.ts b/editor/e2e/channel-build-toggle.spec.ts @@ -5,6 +5,7 @@ import { readJson, resetData, writeSite, + testPaths, } from "./helpers"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; @@ -13,11 +14,11 @@ import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; // the existing top-level cleanup loops in buildIndex remove its per-channel // output dirs. Toggling back re-includes it on the next build. -const CONFIG_PATH = "test-transcripts/channels/test-youtube/config.json"; +const CONFIG_PATH = `${testPaths().transcriptsDir}/channels/test-youtube/config.json`; const MANIFEST_PATH = - "test-transcripts/.export-index/sites/testsite/summaries/manifest.json"; + `${testPaths().transcriptsDir}/.export-index/sites/testsite/summaries/manifest.json`; const CHANNEL_OUT_DIR = - "test-transcripts/.export-index/shared/transcripts/test-youtube"; + `${testPaths().transcriptsDir}/.export-index/shared/transcripts/test-youtube`; test("toggling a channel off skips it from the build; toggling back restores it", async ({ page, diff --git a/editor/e2e/channel-groups.spec.ts b/editor/e2e/channel-groups.spec.ts @@ -9,6 +9,7 @@ import { resolvePath, writeChannelConfig, writeSite, + testPaths, } from "./helpers"; // /channels renders as one table SECTIONED by the active site's channel groups, @@ -235,7 +236,7 @@ test("a youtube group's Transcribe counts and queues its auto-caption-only video test.setTimeout(120_000); await seed(); const id = "asrgrp0001"; - const dataRel = `test-transcripts/channels/slow-b/data/${id}`; + const dataRel = `${testPaths().transcriptsDir}/channels/slow-b/data/${id}`; const dir = resolvePath(dataRel); await mkdir(dir, { recursive: true }); await writeFile(`${dir}/transcript.en.vtt`, ASR_VTT); @@ -254,7 +255,7 @@ test("a youtube group's Transcribe counts and queues its auto-caption-only video ); await writeFile(`${dir}/audio.mp3`, `fake audio ${id}\n`); await writeFile( - resolvePath("test-transcripts/channels/slow-b/playlist"), + resolvePath(`${testPaths().transcriptsDir}/channels/slow-b/playlist`), `https://www.youtube.com/watch?v=${id}\n`, ); await generateReport(page, "slow-b"); diff --git a/editor/e2e/channel-line.spec.ts b/editor/e2e/channel-line.spec.ts @@ -7,6 +7,7 @@ import { resolvePath, writeChannelConfig, writeSettings, + testPaths, } from "./helpers"; // THE CHANNEL LINE. @@ -27,7 +28,7 @@ import { // drawn as a line. const SLUG = "line-chan"; -const ROOT = `test-transcripts/channels/${SLUG}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${SLUG}`; type Entry = Record<string, unknown>; diff --git a/editor/e2e/channel-priority.spec.ts b/editor/e2e/channel-priority.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readJson, resetData, writeSettings, writeSite } from "./helpers"; +import { readJson, resetData, writeSettings, writeSite, testPaths } from "./helpers"; // THE /channels PRIORITY CONTROLS, asserted against what lands on disk. // @@ -31,7 +31,7 @@ type Settings = { >; }; -const settings = () => readJson<Settings>("test-settings.json"); +const settings = () => readJson<Settings>(testPaths().settingsFile); // Every channel in this fixture, and the pool view: with exactly one site // configured /channels scopes to it, and the focus-site test needs a site whose diff --git a/editor/e2e/channel-rename.spec.ts b/editor/e2e/channel-rename.spec.ts @@ -9,6 +9,7 @@ import { resolvePath, writeChannelConfig, writeSite, + testPaths, } from "./helpers"; // Renaming a channel's slug lives in the Danger zone and requires typing the @@ -56,7 +57,7 @@ test("rename requires the exact current slug and then moves the channel", async // The site membership was retargeted to the new slug. const site = await readJson<{ channels: { slug: string }[] }>( - "test-transcripts/sites/mysite/site.json", + `${testPaths().transcriptsDir}/sites/mysite/site.json`, ); expect(site.channels.map((c) => c.slug)).toEqual([NEW]); }); @@ -80,7 +81,7 @@ test("a social channel renames from its Danger zone and keeps its posts", async name: "Fake Tester (X)", url: "https://x.com/faketester", }); - const posts = resolvePath(`test-transcripts/channels/${OLD_X}/posts`); + const posts = resolvePath(`${testPaths().transcriptsDir}/channels/${OLD_X}/posts`); await mkdir(posts, { recursive: true }); await writeFile( `${posts}/2026-05.jsonl`, diff --git a/editor/e2e/channel-site-membership.spec.ts b/editor/e2e/channel-site-membership.spec.ts @@ -5,6 +5,7 @@ import { readJson, resetData, writeSite, + testPaths, } from "./helpers"; // The channel form's "Sites" membership section: per-site checkbox + group @@ -37,7 +38,7 @@ async function seed() { } const readSite = (id: string) => - readJson<SiteFile>(`test-transcripts/sites/${id}/site.json`); + readJson<SiteFile>(`${testPaths().transcriptsDir}/sites/${id}/site.json`); // The membership inputs are controlled React state that the edit page also // server-renders, so a pre-hydration click can be silently swallowed (see the diff --git a/editor/e2e/channel-storage.spec.ts b/editor/e2e/channel-storage.spec.ts @@ -25,6 +25,7 @@ import { writeChannelConfig, writeDigestVideo, writeSettings, + testPaths, } from "./helpers"; // MOVING A CHANNEL'S MEDIA TO ANOTHER DIRECTORY, AND BACK. @@ -60,8 +61,8 @@ import { const SLUG = "test-youtube"; const VIDEO = "20240101_test1234567"; -const dataDir = () => resolvePath(`test-transcripts/channels/${SLUG}/data`); -const mediaLink = () => resolvePath(`test-transcripts/channels/${SLUG}/media`); +const dataDir = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/data`); +const mediaLink = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/media`); const videoFile = (name: string) => join(dataDir(), VIDEO, name); // A small audio file — the route streams bytes, it does not decode them. @@ -197,18 +198,18 @@ test("relocate a channel's media to another root, and move it back", async ({ expect((await lstat(videoFile("transcript.en.vtt"))).isFile()).toBe(true); expect(await existsAbs(join(target, VIDEO, "audio.mp3"))).toBe(true); const config = await readJson<{ mediaDir?: string; dataDir?: string }>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ); expect(config.mediaDir).toBe(target); expect(config.dataDir).toBe(undefined); // The source was reclaimed: no parked copy left holding a second copy of the // media on the volume the move exists to free, and no marker. const siblings = await readdir( - resolvePath(`test-transcripts/channels/${SLUG}`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`), ); expect(siblings.filter((n) => n.startsWith("media."))).toEqual([]); expect( - await pathExists(`test-transcripts/channels/${SLUG}/.relocating.json`), + await pathExists(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), ).toBe(false); // --- NOTHING ELSE NOTICED ---------------------------------------------- @@ -303,7 +304,7 @@ test("relocate a channel's media to another root, and move it back", async ({ expect( ( await readJson<{ mediaDir?: string }>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ) ).mediaDir, ).toBe(undefined); @@ -384,7 +385,7 @@ test("the /channels bulk move queues one job per channel and skips the rest", as const preVideo = "20240102_pre1234567"; await mkdir(join(preTarget, preVideo), { recursive: true }); await writeFile(join(preTarget, preVideo, "audio.mp3"), AUDIO); - const preData = resolvePath(`test-transcripts/channels/${PRE}/data/${preVideo}`); + const preData = resolvePath(`${testPaths().transcriptsDir}/channels/${PRE}/data/${preVideo}`); await mkdir(preData, { recursive: true }); await writeFile( join(preData, "transcript.en.vtt"), @@ -397,7 +398,7 @@ test("the /channels bulk move queues one job per channel and skips the rest", as await writeChannelConfig(PRE, { mediaDir: preTarget }); await symlink( preTarget, - resolvePath(`test-transcripts/channels/${PRE}/media`), + resolvePath(`${testPaths().transcriptsDir}/channels/${PRE}/media`), ); await page.goto("/channels"); @@ -454,7 +455,7 @@ test("the /channels bulk move queues one job per channel and skips the rest", as expect( ( await readJson<{ mediaDir?: string }>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ) ).mediaDir, ).toBe(join(root, SLUG, "media")); @@ -467,17 +468,17 @@ test("the /channels bulk move queues one job per channel and skips the rest", as expect( ( await readJson<{ mediaDir?: string }>( - `test-transcripts/channels/${PRE}/config.json`, + `${testPaths().transcriptsDir}/channels/${PRE}/config.json`, ) ).mediaDir, ).toBe(preTarget); expect( ( - await lstat(resolvePath(`test-transcripts/channels/${PRE}/media`)) + await lstat(resolvePath(`${testPaths().transcriptsDir}/channels/${PRE}/media`)) ).isSymbolicLink(), ).toBe(true); expect( - await pathExists(`test-transcripts/channels/${PRE}/.relocating.json`), + await pathExists(`${testPaths().transcriptsDir}/channels/${PRE}/.relocating.json`), ).toBe(false); }); @@ -522,13 +523,13 @@ test("a bulk move puts every job on one queue and skips a channel with nothing t }); await mkdir( resolvePath( - `test-transcripts/channels/${SECOND}/data/20240103_second12345`, + `${testPaths().transcriptsDir}/channels/${SECOND}/data/20240103_second12345`, ), { recursive: true }, ); await writeFile( resolvePath( - `test-transcripts/channels/${SECOND}/data/20240103_second12345/transcript.en.vtt`, + `${testPaths().transcriptsDir}/channels/${SECOND}/data/20240103_second12345/transcript.en.vtt`, ), "WEBVTT\n\n00:00.000 --> 00:01.000\nhello\n", ); @@ -643,7 +644,7 @@ test("the Storage panel moves to a location picked by name", async ({ expect( ( await readJson<{ mediaDir?: string }>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ) ).mediaDir, ).toBe(target); @@ -698,7 +699,7 @@ test("Resume move finishes an interrupted move and clears its marker", async ({ await writeFile(join(scratch, "meta.json"), "{}"); await writeFile(join(scratch, "win-0000.json"), "[]"); await writeFile( - resolvePath(`test-transcripts/channels/${SLUG}/.relocating.json`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), JSON.stringify( { target, @@ -736,13 +737,13 @@ test("Resume move finishes an interrupted move and clears its marker", async ({ // Finished like any other move: link, config, no marker. expect( - await pathExists(`test-transcripts/channels/${SLUG}/.relocating.json`), + await pathExists(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), ).toBe(false); expect((await lstat(mediaLink())).isSymbolicLink()).toBe(true); expect( ( await readJson<{ mediaDir?: string }>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ) ).mediaDir, ).toBe(target); @@ -842,7 +843,7 @@ test("a move that starts while a job writes into the channel refuses, naming the // NOTHING WAS TOUCHED: no marker, no copy, no `media` made, the text a real // directory. expect( - await pathExists(`test-transcripts/channels/${SLUG}/.relocating.json`), + await pathExists(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), ).toBe(false); expect(await existsAbs(join(root, SLUG))).toBe(false); expect(await existsAbs(mediaLink())).toBe(false); @@ -940,7 +941,7 @@ test("the rack and the Storage panel show the hold while a marker stands, and it await quiet(page); const target = join(testInfo.outputPath("hold-root"), SLUG, "media"); await writeFile( - resolvePath(`test-transcripts/channels/${SLUG}/.relocating.json`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), JSON.stringify({ target, direction: "out", @@ -975,7 +976,7 @@ test("the rack and the Storage panel show the hold while a marker stands, and it await expect(async () => { if (await clear.isVisible()) await clear.click({ timeout: 2_000 }); expect( - await pathExists(`test-transcripts/channels/${SLUG}/.relocating.json`), + await pathExists(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), ).toBe(false); }).toPass({ timeout: 20_000 }); await forgetCaches(); @@ -1022,7 +1023,7 @@ test("Reconcile and resume settles an extra and a changed file on the destinatio '[{"stale":true,"from":"an older copy"}]', ); await writeFile( - resolvePath(`test-transcripts/channels/${SLUG}/.relocating.json`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), JSON.stringify({ target, direction: "out", @@ -1052,7 +1053,7 @@ test("Reconcile and resume settles an extra and a changed file on the destinatio // Finished: link, config, no marker; the copy is the source's two files. expect( - await pathExists(`test-transcripts/channels/${SLUG}/.relocating.json`), + await pathExists(`${testPaths().transcriptsDir}/channels/${SLUG}/.relocating.json`), ).toBe(false); expect((await lstat(mediaLink())).isSymbolicLink()).toBe(true); expect(await existsAbs(scratch)).toBe(false); @@ -1149,7 +1150,7 @@ test("the Storage panel evicts this channel's old clip windows", async ({ await resetData("one-youtube-channel-with-data"); await writeSettings({ minFreeDiskGB: 0 }); const clipsDir = resolvePath( - `test-transcripts/channels/${SLUG}/data/${VIDEO}/clips`, + `${testPaths().transcriptsDir}/channels/${SLUG}/data/${VIDEO}/clips`, ); await mkdir(clipsDir, { recursive: true }); const old = join(clipsDir, "10.00-40.00.mp4"); @@ -1175,7 +1176,7 @@ test("the Storage panel evicts this channel's old clip windows", async ({ const clipsBytesOf = async () => ( await readJson<{ totalClipsBytes?: number }>( - `test-transcripts/channels/${SLUG}/snapshot.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`, ) ).totalClipsBytes ?? 0; const before = await clipsBytesOf(); @@ -1332,12 +1333,12 @@ test("a digest runs on a channel whose media drive is away", async ({ await writeDigestVideo({ channelSlug: CHANNEL, videoId: DIGEST_VIDEO }); await symlink( target, - resolvePath(`test-transcripts/channels/${CHANNEL}/media`), + resolvePath(`${testPaths().transcriptsDir}/channels/${CHANNEL}/media`), ); await symlink( join("..", "..", "media", DIGEST_VIDEO, "audio.mp3"), resolvePath( - `test-transcripts/channels/${CHANNEL}/data/${DIGEST_VIDEO}/audio.mp3`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${DIGEST_VIDEO}/audio.mp3`, ), ); await forgetCaches(); @@ -1355,7 +1356,7 @@ test("a digest runs on a channel whose media drive is away", async ({ ); expect( await pathExists( - `test-transcripts/channels/${CHANNEL}/data/${DIGEST_VIDEO}/ai-digest.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${DIGEST_VIDEO}/ai-digest.json`, ), ).toBe(true); }); diff --git a/editor/e2e/channel-work.spec.ts b/editor/e2e/channel-work.spec.ts @@ -1,17 +1,17 @@ import { mkdir, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import { test, expect } from "@playwright/test"; -import { resetData, resolvePath, readJson, jobRowByKind, generateReport} from "./helpers"; +import { resetData, resolvePath, readJson, jobRowByKind, generateReport, testPaths } from "./helpers"; // The channel-work tables on the operation pages, and the report controls on // /channels. This file was actionable.spec.ts: /actionable rendered all of it // on one page, and slice 4 sent each section to the page that owns the work. const YT_SNAPSHOT_REL = - "test-transcripts/channels/test-youtube/snapshot.json"; -const YT_CONFIG_REL = "test-transcripts/channels/test-youtube/config.json"; + `${testPaths().transcriptsDir}/channels/test-youtube/snapshot.json`; +const YT_CONFIG_REL = `${testPaths().transcriptsDir}/channels/test-youtube/config.json`; const TR_SNAPSHOT_REL = - "test-transcripts/channels/test-transcribe/snapshot.json"; + `${testPaths().transcriptsDir}/channels/test-transcribe/snapshot.json`; async function writeJson(relPath: string, value: unknown): Promise<void> { const full = resolvePath(relPath); diff --git a/editor/e2e/channels-storage-columns.spec.ts b/editor/e2e/channels-storage-columns.spec.ts @@ -9,6 +9,7 @@ import { resolvePath, writeChannelConfig, writeSettings, + testPaths, } from "./helpers"; // /channels AS THE STORAGE WORKING SURFACE. @@ -38,7 +39,7 @@ const VIDEO = "20240101_test1234567"; // chat, what a move carries. The fixture has none, so one is written. async function giveAudio(slug: string, id: string, bytes = 4096) { await writeFile( - resolvePath(`test-transcripts/channels/${slug}/data/${id}/audio.mp3`), + resolvePath(`${testPaths().transcriptsDir}/channels/${slug}/data/${id}/audio.mp3`), "x".repeat(bytes), ); } @@ -50,7 +51,7 @@ async function giveAudio(slug: string, id: string, bytes = 4096) { // rather than by running a move — what is under test is the COLUMN, and a real // rsync buys nothing here. async function relocateOnDisk(slug: string, root: string): Promise<string> { - const channelDir = resolvePath(`test-transcripts/channels/${slug}`); + const channelDir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); const target = join(root, slug, "media"); await mkdir(target, { recursive: true }); for (const id of await readdir(join(channelDir, "data"))) { @@ -70,7 +71,7 @@ async function relocateOnDisk(slug: string, root: string): Promise<string> { } await symlink(target, join(channelDir, "media")); const config = await readJson<Record<string, unknown>>( - `test-transcripts/channels/${slug}/config.json`, + `${testPaths().transcriptsDir}/channels/${slug}/config.json`, ); await writeChannelConfig(slug, { ...config, mediaDir: target }); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); @@ -155,7 +156,7 @@ test("filter by volume, sort by size, and free up N GB", async ({ url: "https://www.youtube.com/@second", }); await mkdir( - resolvePath(`test-transcripts/channels/${SECOND}/data/20240102_second0001`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SECOND}/data/20240102_second0001`), { recursive: true }, ); await giveAudio(SLUG, VIDEO); diff --git a/editor/e2e/channels.spec.ts b/editor/e2e/channels.spec.ts @@ -5,6 +5,7 @@ import { pathExists, readJson, resetData, + testPaths, } from "./helpers"; test("shows empty state with no channels", async ({ page }) => { @@ -25,7 +26,7 @@ test("creates a youtube channel", async ({ page }) => { await page.getByRole("button", { name: /create channel/i }).click(); await page.waitForURL("**/channels/new-test", { timeout: 10_000 }); expect( - await readJson("test-transcripts/channels/new-test/config.json"), + await readJson(`${testPaths().transcriptsDir}/channels/new-test/config.json`), ).toEqual({ handling: "youtube", name: "New Test Channel", @@ -44,7 +45,7 @@ test("auto-detects twitch platform from URL", async ({ page }) => { await page.getByRole("button", { name: /create channel/i }).click(); await page.waitForURL("**/channels/twitch-test", { timeout: 10_000 }); const config = await readJson<{ platform?: string; url?: string }>( - "test-transcripts/channels/twitch-test/config.json", + `${testPaths().transcriptsDir}/channels/twitch-test/config.json`, ); expect(config.platform).toBe("twitch"); }); @@ -76,7 +77,7 @@ test("edits an existing channel", async ({ page }) => { await page.getByRole("button", { name: /save changes/i }).click(); await expect(page.getByText("Renamed Channel").first()).toBeVisible(); const config = await readJson<{ name?: string }>( - "test-transcripts/channels/test-youtube/config.json", + `${testPaths().transcriptsDir}/channels/test-youtube/config.json`, ); expect(config.name).toBe("Renamed Channel"); }); @@ -91,12 +92,12 @@ test("requires typed-confirmation to delete", async ({ page }) => { await page.getByLabel("confirm slug to delete").fill("wrong-slug"); await page.getByRole("button", { name: /delete channel/i }).click(); await expect(page.getByText(/type the channel slug/i)).toBeVisible(); - expect(await pathExists("test-transcripts/channels/test-youtube")).toBe(true); + expect(await pathExists(`${testPaths().transcriptsDir}/channels/test-youtube`)).toBe(true); await page.getByLabel("confirm slug to delete").fill("test-youtube"); await page.getByRole("button", { name: /delete channel/i }).click(); await page.waitForURL("**/channels", { timeout: 10_000 }); - expect(await pathExists("test-transcripts/channels/test-youtube")).toBe(false); + expect(await pathExists(`${testPaths().transcriptsDir}/channels/test-youtube`)).toBe(false); }); test("hides transcribe form fields for youtube channels (cosmetic)", async ({ diff --git a/editor/e2e/chat-only.spec.ts b/editor/e2e/chat-only.spec.ts @@ -9,6 +9,7 @@ import { resetData, resolvePath, writeSite, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -27,7 +28,7 @@ import { baseUrl } from "./baseUrl"; // missingNeverFetched and enter the published site as blank pages. const CHANNEL = "test-filter"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const GUEST = ["guestvid0001", "guestvid0002"]; const PLAIN = ["plainvid0001", "plainvid0002"]; // The fixture's cookie-gated video. Its METADATA SCAN is refused without @@ -241,7 +242,7 @@ test("before the chat lands it is chatOnlyPending, which is download-lane work", // admitted, published with its chat track, and carries no cues. const INDEX_CHANNEL = "test-youtube"; const INDEX_DIR = "20240101_test1234567"; -const INDEX_DATA = `test-transcripts/channels/${INDEX_CHANNEL}/data/${INDEX_DIR}`; +const INDEX_DATA = `${testPaths().transcriptsDir}/channels/${INDEX_CHANNEL}/data/${INDEX_DIR}`; test("the export publishes a chat-only video as a chat track with no captions", async ({ page, @@ -279,7 +280,7 @@ test("the export publishes a chat-only video as a chat track with no captions", const subsPage = await readJson< Array<{ id: string; tracks?: Record<string, unknown[]> }> - >(`test-transcripts/.export-index/shared/subs/${INDEX_CHANNEL}/page-0000.json`); + >(`${testPaths().transcriptsDir}/.export-index/shared/subs/${INDEX_CHANNEL}/page-0000.json`); const detail = subsPage.find((d) => d.id === INDEX_DIR); expect(detail).toBeDefined(); expect(Object.keys(detail?.tracks ?? {})).toEqual(["live_chat"]); @@ -288,7 +289,7 @@ test("the export publishes a chat-only video as a chat track with no captions", // And no captions: the transcripts shard carries the video (it has metadata) // with no cues at all. const transcriptsPage = await readJson<Array<{ id: string; cues?: unknown[] }>>( - `test-transcripts/.export-index/shared/transcripts/${INDEX_CHANNEL}/page-0000.json`, + `${testPaths().transcriptsDir}/.export-index/shared/transcripts/${INDEX_CHANNEL}/page-0000.json`, ); const t = transcriptsPage.find((d) => d.id === INDEX_DIR); expect(t).toBeDefined(); diff --git a/editor/e2e/chough.spec.ts b/editor/e2e/chough.spec.ts @@ -7,10 +7,11 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; const CHANNEL = "test-transcribe"; -const DATA = `test-transcripts/channels/${CHANNEL}/data`; +const DATA = `${testPaths().transcriptsDir}/channels/${CHANNEL}/data`; // Minimal metadata so transcribeOne's normalize pass runs (it needs // metadata.info.json) and writes transcript.cues.json. diff --git a/editor/e2e/cleanup-actionable.spec.ts b/editor/e2e/cleanup-actionable.spec.ts @@ -1,11 +1,11 @@ import { mkdir, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import { test, expect } from "@playwright/test"; -import { resetData, resolvePath, jobRowByKind } from "./helpers"; +import { resetData, resolvePath, jobRowByKind, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; const SLUG = "test-transcribe"; -const SNAPSHOT_REL = `test-transcripts/channels/${SLUG}/snapshot.json`; +const SNAPSHOT_REL = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; async function writeJson(relPath: string, value: unknown): Promise<void> { const full = resolvePath(relPath); diff --git a/editor/e2e/cleanup-holds.spec.ts b/editor/e2e/cleanup-holds.spec.ts @@ -7,6 +7,7 @@ import { resolvePath, writeChannelConfig, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -22,10 +23,10 @@ import { baseUrl } from "./baseUrl"; const SLUG = "test-transcribe"; const STALE = "stale-report"; -const SNAPSHOT_REL = `test-transcripts/channels/${SLUG}/snapshot.json`; +const SNAPSHOT_REL = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; function dataRel(videoId: string, file: string): string { - return `test-transcripts/channels/${SLUG}/data/${videoId}/${file}`; + return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } async function seedTranscript(videoId: string): Promise<void> { @@ -184,7 +185,7 @@ test("a report written before the hold accounting renders '—', not a zero nobo await writeChannelConfig(STALE); // Exactly what an older snapshot looks like: reclaim estimate, no accounting. await writeFile( - resolvePath(`test-transcripts/channels/${STALE}/snapshot.json`), + resolvePath(`${testPaths().transcriptsDir}/channels/${STALE}/snapshot.json`), JSON.stringify({ generatedAt: "2026-01-01T00:00:00.000Z", totals: { videos: 1, transcribed: 1, downloaded: 1 }, diff --git a/editor/e2e/cleanup-page.spec.ts b/editor/e2e/cleanup-page.spec.ts @@ -1,6 +1,6 @@ import { writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { readJson, resetData, resolvePath, generateReport } from "./helpers"; +import { readJson, resetData, resolvePath, generateReport, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; @@ -10,10 +10,10 @@ import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; // total without disabling its sweeps. See editor/app/cleanup/*. const SLUG = "test-transcribe"; -const CONFIG_REL = `test-transcripts/channels/${SLUG}/config.json`; +const CONFIG_REL = `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`; function dataRel(videoId: string, file: string): string { - return `test-transcripts/channels/${SLUG}/data/${videoId}/${file}`; + return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } async function seedTranscript(videoId: string): Promise<void> { diff --git a/editor/e2e/cookies-mode.spec.ts b/editor/e2e/cookies-mode.spec.ts @@ -10,6 +10,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; // Configurable cookies-from-browser: global + per-channel value, and a cookie @@ -21,7 +22,7 @@ import { const CHANNEL = "test-cookies"; const FIXTURE = "cookies-mode-channel"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const COOKIES = "firefox:test"; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -45,7 +46,7 @@ async function defaultSettings(): Promise<Record<string, unknown>> { async function readInvocations(): Promise<string> { try { return await readFile( - path.join(here, "..", ROOT, "fake-ytdlp.invocations"), + path.join(ROOT, "fake-ytdlp.invocations"), "utf8", ); } catch { @@ -87,7 +88,7 @@ test("settings: cookie value + mode round-trip through the form", async ({ const saved = await readJson<{ cookiesFromBrowser?: string; cookieMode?: string; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.cookiesFromBrowser).toBe(COOKIES); expect(saved.cookieMode).toBe("always"); diff --git a/editor/e2e/cut-release.spec.ts b/editor/e2e/cut-release.spec.ts @@ -1,6 +1,6 @@ import { readFile, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { resolvePath } from "./helpers"; +import { resolvePath, testPaths } from "./helpers"; // This spec drives a flow that REWRITES a changelog file and can make a real // git commit. It used to point at the repo's own tracked editor/CHANGELOG.md, @@ -14,7 +14,7 @@ import { resolvePath } from "./helpers"; // same file the /changelog page reads (common/lib/paths.ts editorChangelogFile). // "Commit changelog" is unchecked in every test below: none of them assert // anything about git, and leaving it on would try to `git add` an ignored file. -const CHANGELOG_PATH = resolvePath("test-changelog.md"); +const CHANGELOG_PATH = resolvePath(testPaths().editorChangelog); const WITH_UNRELEASED = "# Changelog\n" + diff --git a/editor/e2e/dashboard-answers.spec.ts b/editor/e2e/dashboard-answers.spec.ts @@ -8,6 +8,7 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; // THE DASHBOARD ANSWERS WHILE A REPORT REGENERATES (release 17 slice D0). @@ -53,7 +54,7 @@ const BIG = ["big-channel-a", "big-channel-b"]; const BIG_VIDEOS = 600; async function seedBigChannel(slug: string): Promise<void> { - const channelDir = resolvePath(`test-transcripts/channels/${slug}`); + const channelDir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); const dataDir = join(channelDir, "data"); await mkdir(dataDir, { recursive: true }); await writeFile( @@ -74,7 +75,7 @@ async function seedBigChannel(slug: string): Promise<void> { { url: "seg1", duration: 6 }, ], })); - const template = resolvePath(`test-transcripts/.${slug}-meta.json`); + const template = resolvePath(`${testPaths().transcriptsDir}/.${slug}-meta.json`); await writeFile( template, JSON.stringify({ id: "native", title: "A long VOD", duration: 3600, formats }), @@ -169,7 +170,7 @@ test("/ and /jobs answer while two large reports regenerate, one after the other expect(done.body.jobIds).toHaveLength(2); const ended = async (): Promise<boolean> => { for (const id of done.body.jobIds ?? []) { - const m = await readFile(resolvePath(`test-transcripts/.jobs/${id}.meta.json`), "utf8") + const m = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${id}.meta.json`), "utf8") .then((raw) => JSON.parse(raw) as JobMetaOnDisk) .catch(() => null); if (!m || m.status === "queued" || m.status === "running") return false; @@ -197,7 +198,7 @@ test("/ and /jobs answer while two large reports regenerate, one after the other for (const slug of BIG) { const snapshot = JSON.parse( await readFile( - resolvePath(`test-transcripts/channels/${slug}/snapshot.json`), + resolvePath(`${testPaths().transcriptsDir}/channels/${slug}/snapshot.json`), "utf8", ), ) as { totals: { videos: number } }; @@ -212,7 +213,7 @@ test("/ and /jobs answer while two large reports regenerate, one after the other (done.body.jobIds ?? []).map( async (id) => JSON.parse( - await readFile(resolvePath(`test-transcripts/.jobs/${id}.meta.json`), "utf8"), + await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${id}.meta.json`), "utf8"), ) as JobMetaOnDisk, ), ); @@ -280,7 +281,7 @@ async function quiet(page: Page): Promise<void> { // leaves it: queued and started an hour ago, its log last written then. async function plantGhost(pid: number): Promise<string> { const id = ulid(Date.now() - 60 * 60 * 1000); - const jobsDir = resolvePath("test-transcripts/.jobs"); + const jobsDir = resolvePath(`${testPaths().transcriptsDir}/.jobs`); await mkdir(jobsDir, { recursive: true }); const at = Date.now() - 60 * 60 * 1000; await writeFile( @@ -305,7 +306,7 @@ async function plantGhost(pid: number): Promise<string> { async function metaOf(id: string): Promise<{ status: string; cancelReason?: string }> { return JSON.parse( - await readFile(resolvePath(`test-transcripts/.jobs/${id}.meta.json`), "utf8"), + await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${id}.meta.json`), "utf8"), ); } diff --git a/editor/e2e/dashboard-paths.spec.ts b/editor/e2e/dashboard-paths.spec.ts @@ -1,11 +1,11 @@ import { test, expect } from "@playwright/test"; -import { resetData, resolvePath } from "./helpers"; +import { resetData, resolvePath, testPaths } from "./helpers"; test("dashboard does not display 'transcripts dir' or the actual path", async ({ page, }) => { await resetData("empty"); - const abs = resolvePath("test-transcripts"); + const abs = resolvePath(testPaths().transcriptsDir); await page.goto("/"); const body = page.locator("body"); await expect(body).not.toContainText("transcripts dir"); diff --git a/editor/e2e/dashboard.spec.ts b/editor/e2e/dashboard.spec.ts @@ -5,7 +5,7 @@ // persisted downloads pause blocking a manual sync. import { test, expect } from "@playwright/test"; -import { resetData, writeSettings, readJson, generateReport} from "./helpers"; +import { resetData, writeSettings, readJson, generateReport, testPaths } from "./helpers"; const ONE_WORKER = { workers: [ @@ -96,7 +96,7 @@ test("pausing downloads persists and blocks a manual sync", async ({ page }) => .poll(async () => { const s = await readJson<{ autoQueue?: { download?: { held?: boolean } }; - }>("test-settings.json"); + }>(testPaths().settingsFile); return s.autoQueue?.download?.held; }) .toBe(true); diff --git a/editor/e2e/diagnostics-retry-log.spec.ts b/editor/e2e/diagnostics-retry-log.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; // A DIAGNOSTICS RETRY KEEPS ITS LOG WHEN ITS BUCKET EMPTIES (release 13 slice @@ -25,7 +26,7 @@ import { const CHANNEL = "availability-test"; const FIXTURE = "availability-baseline"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; type Snapshot = { buckets?: { noMetadata?: string[] }; diff --git a/editor/e2e/diarization.spec.ts b/editor/e2e/diarization.spec.ts @@ -8,6 +8,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -20,10 +21,10 @@ import { baseUrl } from "./baseUrl"; // in the dev:test / start:test scripts the way every other fake binary is. const SLUG = "test-transcribe"; -const SNAPSHOT_REL = `test-transcripts/channels/${SLUG}/snapshot.json`; +const SNAPSHOT_REL = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; function dataRel(videoId: string, file: string): string { - return `test-transcripts/channels/${SLUG}/data/${videoId}/${file}`; + return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } async function seedTranscript(videoId: string): Promise<void> { diff --git a/editor/e2e/digest.spec.ts b/editor/e2e/digest.spec.ts @@ -23,6 +23,7 @@ import { writeChannelConfig, writeDigestVideo, writeSettings, + testPaths, } from "./helpers"; // The digest lane, end to end through the real job path. @@ -42,12 +43,12 @@ const CHANNEL = "digest-channel"; const VIDEO = "digestvid0001"; function digestPath(channel: string, video: string): string { - return join("test-transcripts", "channels", channel, "data", video, "ai-digest.json"); + return join(testPaths().transcriptsDir, "channels", channel, "data", video, "ai-digest.json"); } function overridesPath(channel: string, video: string): string { return join( - "test-transcripts", + testPaths().transcriptsDir, "channels", channel, "data", @@ -235,7 +236,7 @@ async function writeDuplicateReport(clusters: ClusterFixture[]) { })), }; await writeFile( - resolvePath(join("test-transcripts", "duplicates.json")), + resolvePath(join(testPaths().transcriptsDir, "duplicates.json")), JSON.stringify(report, null, 2), ); } @@ -342,7 +343,7 @@ test("a human canonical override beats the rule", async ({ page }) => { }, ]); await writeFile( - resolvePath(join("test-transcripts", "duplicates.overrides.json")), + resolvePath(join(testPaths().transcriptsDir, "duplicates.overrides.json")), JSON.stringify({ version: 1, clusters: { @@ -547,10 +548,10 @@ test("bad engine output is recorded in warnings and never reaches items", async test.afterAll(async () => { // duplicates.json / duplicates.overrides.json live at the transcripts ROOT, so // they survive a channel-scoped reset and would leak into unrelated specs. - await rm(resolvePath(join("test-transcripts", "duplicates.json")), { + await rm(resolvePath(join(testPaths().transcriptsDir, "duplicates.json")), { force: true, }); - await rm(resolvePath(join("test-transcripts", "duplicates.overrides.json")), { + await rm(resolvePath(join(testPaths().transcriptsDir, "duplicates.overrides.json")), { force: true, }); }); @@ -774,7 +775,7 @@ async function regenerateReport( page: import("@playwright/test").Page, slug: string, ): Promise<void> { - await rm(resolvePath(`test-transcripts/channels/${slug}/snapshot.json`), { + await rm(resolvePath(`${testPaths().transcriptsDir}/channels/${slug}/snapshot.json`), { force: true, }); await generateReport(page, slug); @@ -794,7 +795,7 @@ test("a transcript with no cues.json is deferred, and Normalize transcripts make }); const cuesRel = join( - "test-transcripts", + testPaths().transcriptsDir, "channels", CHANNEL, "data", diff --git a/editor/e2e/disk-space.spec.ts b/editor/e2e/disk-space.spec.ts @@ -7,6 +7,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -46,7 +47,7 @@ test("prevents a download from starting when free disk is below the floor", asyn // Nothing was downloaded. expect( await pathExists( - "test-transcripts/channels/test-pipeline/data/fake00000001/metadata.info.json", + `${testPaths().transcriptsDir}/channels/test-pipeline/data/fake00000001/metadata.info.json`, ), ).toBe(false); }); @@ -73,7 +74,7 @@ test("lets downloads proceed when the gate is disabled (0)", async ({ ).toContainText("Managed download complete", { timeout: 60_000 }); expect( await pathExists( - "test-transcripts/channels/test-pipeline/data/fake00000001/metadata.info.json", + `${testPaths().transcriptsDir}/channels/test-pipeline/data/fake00000001/metadata.info.json`, ), ).toBe(true); }); @@ -81,7 +82,7 @@ test("lets downloads proceed when the gate is disabled (0)", async ({ // A YouTube channel with undownloaded videos, enough for the auto-download // runner to have something to pick. Mirrors auto-queue.spec's fixture. async function makeDownloadChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -171,7 +172,7 @@ test("the unattended auto-download runner idles below the floor", async ({ expect(body.download.picks).toHaveLength(0); // And nothing landed on disk. expect( - await pathExists("test-transcripts/channels/alpha/data/d1"), + await pathExists(`${testPaths().transcriptsDir}/channels/alpha/data/d1`), ).toBe(false); } finally { await request.post(`${baseUrl}/api/auto-queue/control`, { diff --git a/editor/e2e/do-not-clean.spec.ts b/editor/e2e/do-not-clean.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -21,10 +22,10 @@ function formatBytes(bytes: number): string { } const SLUG = "test-transcribe"; -const SNAPSHOT_REL = `test-transcripts/channels/${SLUG}/snapshot.json`; +const SNAPSHOT_REL = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; function dataRel(videoId: string, file: string): string { - return `test-transcripts/channels/${SLUG}/data/${videoId}/${file}`; + return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`; } // Give vidA and vidB a whisper transcript so both qualify for the diff --git a/editor/e2e/download-format-guard.spec.ts b/editor/e2e/download-format-guard.spec.ts @@ -22,6 +22,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; type DownloadOutcome = { @@ -44,7 +45,7 @@ async function makeChannel( ids: string[], config: Record<string, unknown> = {}, ): Promise<void> { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -74,7 +75,7 @@ async function downloadAll(page: import("@playwright/test").Page, slug: string) async function outcome(slug: string, id: string): Promise<DownloadOutcome> { return readJson<DownloadOutcome>( - `test-transcripts/channels/${slug}/data/${id}/download-outcome.json`, + `${testPaths().transcriptsDir}/channels/${slug}/data/${id}/download-outcome.json`, ); } @@ -117,11 +118,11 @@ test("duration guard flags a source-truncated download and keeps the stub", asyn expect(truncOutcome.shortAudio?.expectedDurationSec).toBe(6000); expect(truncOutcome.shortAudio?.audioDurationSec).toBe(120); expect( - await pathExists(`test-transcripts/channels/${SLUG}/data/${TRUNC}/audio.mp3`), + await pathExists(`${testPaths().transcriptsDir}/channels/${SLUG}/data/${TRUNC}/audio.mp3`), ).toBe(true); expect( await pathExists( - `test-transcripts/channels/${SLUG}/data/${TRUNC}/transcript.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/data/${TRUNC}/transcript.json`, ), ).toBe(false); @@ -180,7 +181,7 @@ test("the short-audio re-download's log survives the refresh that clears the ban await makeChannel(SLUG, [ID]); // Seed the flagged state directly (the kept short stub plus the guard's // sidecar) rather than re-running a truncated download for it. - const dir = resolvePath(`test-transcripts/channels/${SLUG}/data/${ID}`); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/data/${ID}`); await mkdir(dir, { recursive: true }); await writeFile(`${dir}/audio.mp3`, "fake truncated audio __DUR=120__\n"); await writeFile( @@ -241,7 +242,7 @@ test("download format: Odysee auto picks original; YouTube uses bestaudio; chann await waitForOutcome(SLUG, YT); const invocations = await readFile( - resolvePath(`test-transcripts/channels/${SLUG}/fake-ytdlp.invocations`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/fake-ytdlp.invocations`), "utf8", ); expect(invocations).toContain("format:original/bestaudio/worst"); @@ -254,7 +255,7 @@ test("download format: Odysee auto picks original; YouTube uses bestaudio; chann await downloadAll(page, SLUG2); await waitForOutcome(SLUG2, YT2); const inv2 = await readFile( - resolvePath(`test-transcripts/channels/${SLUG2}/fake-ytdlp.invocations`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG2}/fake-ytdlp.invocations`), "utf8", ); expect(inv2).toContain("format:original/bestaudio/worst"); diff --git a/editor/e2e/download-part-files.spec.ts b/editor/e2e/download-part-files.spec.ts @@ -5,6 +5,7 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; // `.part` files are yt-dlp's in-progress download placeholders. They should @@ -19,10 +20,10 @@ test("audio.<ext>.part doesn't count as a complete audio file", async ({ // Turn vidA's only audio file into a .part — should now look undownloaded. await rename( resolvePath( - "test-transcripts/channels/test-transcribe/data/vidA/audio.m4a", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/audio.m4a`, ), resolvePath( - "test-transcripts/channels/test-transcribe/data/vidA/audio.m4a.part", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/audio.m4a.part`, ), ); diff --git a/editor/e2e/duplicate-shorts.spec.ts b/editor/e2e/duplicate-shorts.spec.ts @@ -6,6 +6,7 @@ import { resetData, resolvePath, writeSite, + testPaths, } from "./helpers"; // Cross-platform duplicate shorts detection. Seeds four channels with shorts @@ -146,7 +147,7 @@ const PLATFORM_KEY: Record<Seed["platform"], string> = { async function seed(seeds: Seed[] = SEEDS): Promise<void> { const channels = new Set(seeds.map((s) => s.channel)); for (const channel of channels) { - const dir = resolvePath(`test-transcripts/channels/${channel}`); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${channel}`); await mkdir(dir, { recursive: true }); await writeFile( `${dir}/config.json`, @@ -154,7 +155,7 @@ async function seed(seeds: Seed[] = SEEDS): Promise<void> { ); } for (const s of seeds) { - const dir = resolvePath(`test-transcripts/channels/${s.channel}/data/${s.id}`); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${s.channel}/data/${s.id}`); await mkdir(dir, { recursive: true }); await writeFile( `${dir}/metadata.info.json`, @@ -210,7 +211,7 @@ test("clusters cross-platform near-duplicate shorts (incl. plain VTT) and ignore timeout: 30_000, }); - const report = await readJson<DuplicateReport>("test-transcripts/duplicates.json"); + const report = await readJson<DuplicateReport>(`${testPaths().transcriptsDir}/duplicates.json`); expect(report.runConfig.thresholdSeconds).toBe(180); // The three near-identical shorts cluster together, across platform + channel. @@ -290,7 +291,7 @@ test("all-durations run pulls a long video into the short's cluster via containm timeout: 30_000, }); - const report = await readJson<DuplicateReport>("test-transcripts/duplicates.json"); + const report = await readJson<DuplicateReport>(`${testPaths().transcriptsDir}/duplicates.json`); expect(report.runConfig.thresholdSeconds).toBeNull(); const cluster = clusterWith(report, "yt-a/shorta"); @@ -345,7 +346,7 @@ test("title blocking confirms matching content, rejects differing content, and q timeout: 30_000, }); - const report = await readJson<DuplicateReport>("test-transcripts/duplicates.json"); + const report = await readJson<DuplicateReport>(`${testPaths().transcriptsDir}/duplicates.json`); expect(report.runConfig.blocking).toBe("title"); // (1) CONFIRMED — the content agreed, so this is a real cluster that may share. diff --git a/editor/e2e/exclude-from-counts.spec.ts b/editor/e2e/exclude-from-counts.spec.ts @@ -6,6 +6,7 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "test-transcribe"; @@ -22,7 +23,7 @@ type AvailabilityStatus = async function writeAvailability(id: string, status: AvailabilityStatus) { const path = resolvePath( - `test-transcripts/channels/${CHANNEL}/data/${id}/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${id}/availability.json`, ); await mkdir(dirname(path), { recursive: true }); await writeFile( @@ -62,7 +63,7 @@ test("members-only video is hidden from the Failed transcriptions list", async ( await resetData(FIXTURE); await writeAvailability("vidA", "members_only"); await writeFile( - resolvePath(`test-transcripts/channels/${CHANNEL}/failed-transcriptions`), + resolvePath(`${testPaths().transcriptsDir}/channels/${CHANNEL}/failed-transcriptions`), "vidA\nvidB\n", ); @@ -84,7 +85,7 @@ test("stage badge counts exclude members-only videos", async ({ page }) => { // vidB: stays in both buckets (no availability sidecar). await writeAvailability("vidA", "members_only"); await writeFile( - resolvePath(`test-transcripts/channels/${CHANNEL}/failed-transcriptions`), + resolvePath(`${testPaths().transcriptsDir}/channels/${CHANNEL}/failed-transcriptions`), "vidA\nvidB\n", ); diff --git a/editor/e2e/export-search.spec.ts b/editor/e2e/export-search.spec.ts @@ -1,7 +1,7 @@ import { test, expect, type Page } from "@playwright/test"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { PROJECT_URL } from "../../common/lib/project"; -import { readJson, writeSettings } from "./helpers"; +import { readJson, writeSettings, testPaths } from "./helpers"; const EXPORT_BASE = `http://localhost:${portFor("EXPORT_PORT")}`; @@ -618,7 +618,7 @@ test.describe("export footer", () => { // overrides it instead of showing the global one. Restore afterwards so we // don't leak settings into later tests. const original = await readJson<Record<string, unknown>>( - "test-settings.json", + testPaths().settingsFile, ); try { await writeSettings({ diff --git a/editor/e2e/exportOutLink.ts b/editor/e2e/exportOutLink.ts @@ -10,16 +10,18 @@ import { lstat, readlink, rm } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { testPaths } from "./helpers"; const editorDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const exportOut = path.resolve(editorDir, "..", "export", "out"); -const testTranscripts = path.join(editorDir, "test-transcripts"); +// Every slot's data root (testPaths.ts): slot 0's, and the other workers'. +const testRoots = [testPaths().transcriptsDir, path.join(editorDir, ".e2e-workers")]; export async function dropTestExportOutLink(when: "setup" | "teardown"): Promise<void> { const st = await lstat(exportOut).catch(() => null); if (!st?.isSymbolicLink()) return; const target = path.resolve(path.dirname(exportOut), await readlink(exportOut)); - if (target !== testTranscripts && !target.startsWith(`${testTranscripts}${path.sep}`)) return; + if (!testRoots.some((root) => target === root || target.startsWith(`${root}${path.sep}`))) return; await rm(exportOut, { force: true }); console.log(`[e2e ${when}] removed export/out → ${path.relative(editorDir, target)} (a test bundle)`); } diff --git a/editor/e2e/fetch-window.spec.ts b/editor/e2e/fetch-window.spec.ts @@ -18,6 +18,7 @@ import { resolvePath, writeChannelConfig, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -28,7 +29,7 @@ const AUTH = { authorization: `Bearer ${TOKEN}` }; // no-info-json rule has to leave untouched. const SLUG = "test-youtube"; const VIDEO = "fake00000002"; -const rel = (p: string) => `test-transcripts/channels/${SLUG}/${p}`; +const rel = (p: string) => `${testPaths().transcriptsDir}/channels/${SLUG}/${p}`; const clipRel = (name: string) => rel(`data/${VIDEO}/clips/${name}`); async function exists(relPath: string): Promise<boolean> { @@ -301,7 +302,7 @@ test("a 429 fails the job and puts the platform in cooldown", async ({ // Nothing half-written is left under the window's name. expect( - await exists(`test-transcripts/channels/${SLUG}/data/ratelimitvid1/clips/5.00-10.00.mp4`), + await exists(`${testPaths().transcriptsDir}/channels/${SLUG}/data/ratelimitvid1/clips/5.00-10.00.mp4`), ).toBe(false); // The cooldown the auto-download runner and a clicked sync both honour. The @@ -376,7 +377,7 @@ test("a batch skips what is cached, survives one 403, and fetches the rest", asy const finished = await pollJob(request, body.jobId, 90_000); expect(finished.status).toBe("failed"); const jobLog = await readFile( - resolvePath(`test-transcripts/.jobs/${body.jobs[0].jobId}.log`), + resolvePath(`${testPaths().transcriptsDir}/.jobs/${body.jobs[0].jobId}.log`), "utf8", ); expect(jobLog.match(/Sleeping \d+s before the next fetch/g)).toEqual([ @@ -391,7 +392,7 @@ test("a batch skips what is cached, survives one 403, and fetches the rest", asy ); expect(sidecar).toMatchObject({ requestedBy: "umtool", manifest: "demo-batch", clipId: "c03" }); expect( - await exists(`test-transcripts/channels/${SLUG}/data/win403vid1/clips/5.00-10.00.mp4`), + await exists(`${testPaths().transcriptsDir}/channels/${SLUG}/data/win403vid1/clips/5.00-10.00.mp4`), ).toBe(false); // One 403 did not back the platform off: the next ask is not refused. diff --git a/editor/e2e/forms-keep-input.spec.ts b/editor/e2e/forms-keep-input.spec.ts @@ -8,6 +8,7 @@ import { resolvePath, writeSettings, writeSite, + testPaths, } from "./helpers"; // A FORM THAT FAILS KEEPS WHAT WAS TYPED (release 16, slice FK). @@ -29,7 +30,7 @@ import { // (EISDIR) and the action returns its error. The file is back before the test // ends, whatever happens. -const SETTINGS = resolvePath("test-settings.json"); +const SETTINGS = resolvePath(testPaths().settingsFile); async function withSettingsUnwritable(fn: () => Promise<void>): Promise<void> { const aside = `${SETTINGS}.fk-aside`; @@ -160,7 +161,7 @@ test("SiteForm edit: a refused Public URL keeps every field", async ({ await expect(named(form, "transcriptDownloads")).not.toBeChecked(); // Nothing was written. const site = await readJson<{ siteTitle: string }>( - "test-transcripts/sites/alpha/site.json", + `${testPaths().transcriptsDir}/sites/alpha/site.json`, ); expect(site.siteTitle).toBe("Alpha Site"); }); @@ -225,7 +226,7 @@ test("SettingsForm: a refused page size keeps every field, and a save after it s ).toBeVisible(); await expect(async () => { const saved = await readJson<{ cookieMode: string; adminTitle: string }>( - "test-settings.json", + testPaths().settingsFile, ); expect(saved.cookieMode).toBe("defer"); expect(saved.adminTitle).toBe("Typed Admin"); @@ -403,7 +404,7 @@ test("ChannelForm edit: a refused filter keeps every field", async ({ await expect(named(form, "downloadFilterExclude")).toHaveValue("(unclosed"); await expect(named(form, "cookieMode")).toHaveValue("defer"); const config = await readJson<{ name: string }>( - "test-transcripts/channels/test-youtube/config.json", + `${testPaths().transcriptsDir}/channels/test-youtube/config.json`, ); expect(config.name).not.toBe("Edited Name"); }); @@ -529,7 +530,7 @@ test("CutReleaseForm: a bad version keeps it and the commit box", async ({ }) => { // The disposable test changelog cut-release.spec.ts drives (never the // repo's own); left with no [Unreleased] heading, as that spec leaves it. - const changelog = resolvePath("test-changelog.md"); + const changelog = resolvePath(testPaths().editorChangelog); const before = await readFile(changelog, "utf8").catch(() => null); await writeFile( changelog, diff --git a/editor/e2e/globalSetup.ts b/editor/e2e/globalSetup.ts @@ -10,10 +10,42 @@ // So this cannot clear a stale dev server ahead of the new one booting — it only // reaps fixture children, which is what actually eats the CPU. +// +// WORKER SLOTS (plans/e2e-speed.md S5). With more than one worker, slot 0's +// servers are the webServer entries; this starts slots 1…'s (e2e/servers.ts), +// each over its own data root, and globalTeardown stops them. + +import type { FullConfig } from "@playwright/test"; import { dropTestExportOutLink } from "./exportOutLink"; import { sweepFixtureProcesses } from "./fixtureProcs"; +import { resolveE2EMode, startSlot, type SlotHandle } from "./servers"; + +declare global { + // eslint-disable-next-line no-var + var __e2eSlotServers: SlotHandle[] | undefined; +} -export default async function globalSetup() { +export default async function globalSetup(config: FullConfig) { await sweepFixtureProcesses("setup"); await dropTestExportOutLink("setup"); + const workers = config.workers; + if (workers <= 1) return; + const mode = resolveE2EMode(); + const t0 = Date.now(); + const settled = await Promise.allSettled( + Array.from({ length: workers - 1 }, (_, i) => startSlot(i + 1, mode)), + ); + globalThis.__e2eSlotServers = settled.flatMap((r) => (r.status === "fulfilled" ? [r.value] : [])); + const failed = settled.find((r): r is PromiseRejectedResult => r.status === "rejected"); + if (failed) { + await stopSlotServers(); + throw failed.reason; + } + console.log(`[e2e setup] ${workers} workers: slots 1–${workers - 1}'s servers up in ${Math.round((Date.now() - t0) / 1000)}s`); +} + +export async function stopSlotServers(): Promise<void> { + const handles = globalThis.__e2eSlotServers ?? []; + globalThis.__e2eSlotServers = []; + await Promise.all(handles.map((h) => h.stop())); } diff --git a/editor/e2e/globalTeardown.ts b/editor/e2e/globalTeardown.ts @@ -12,8 +12,12 @@ import { dropTestExportOutLink } from "./exportOutLink"; import { sweepFixtureProcesses } from "./fixtureProcs"; +import { stopSlotServers } from "./globalSetup"; export default async function globalTeardown() { + // Slots 1…'s servers first (globalSetup's), so their fixtures are gone + // before the sweep looks for strays. + await stopSlotServers(); await sweepFixtureProcesses("teardown"); await dropTestExportOutLink("teardown"); } diff --git a/editor/e2e/helpers.ts b/editor/e2e/helpers.ts @@ -11,12 +11,15 @@ import { } from "node:fs/promises"; import { expect, type Page } from "@playwright/test"; import { baseUrl } from "./baseUrl"; +import { testPaths } from "./testPaths"; + +// Every path a spec touches under the test server's data comes from here +// (testPaths() — the worker's own root once there is one per worker). +export { testPaths } from "./testPaths"; const here = dirname(fileURLToPath(import.meta.url)); const editorRoot = resolve(here, ".."); const fixturesRoot = resolve(editorRoot, "e2e", "fixtures"); -const testTranscriptsDir = resolve(editorRoot, "test-transcripts"); -const testSettingsFile = resolve(editorRoot, "test-settings.json"); const defaultTestSettingsFile = resolve( fixturesRoot, "test-settings.default.json", @@ -64,6 +67,7 @@ export async function resetData(fixtureName: string | null = null) { // start-mode gate run lost channel-work.spec:208 to exactly that ("EEXIST: // file already exists, mkdir '…/test-transcripts/channels'"), and an earlier // run no-subs-fallback.spec:114. Quiesce again, clear again, copy again. + const { transcriptsDir: testTranscriptsDir, settingsFile: testSettingsFile } = testPaths(); for (let attempt = 1; ; attempt++) { await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); await rm(testTranscriptsDir, { @@ -140,7 +144,7 @@ export async function writeSettings(settings: SettingsPatch) { merged[key] = { ...base[key], ...value }; } } - await writeFile(testSettingsFile, JSON.stringify(merged, null, 2)); + await writeFile(testPaths().settingsFile, JSON.stringify(merged, null, 2)); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); } @@ -151,7 +155,7 @@ export async function writeSite( siteId: string, site: Record<string, unknown> = {}, ) { - const dir = join(testTranscriptsDir, "sites", siteId); + const dir = join(testPaths().transcriptsDir, "sites", siteId); await mkdir(dir, { recursive: true }); const full = { siteId, @@ -213,7 +217,7 @@ export async function generateReport( page: Page, slug: string, ): Promise<void> { - const snapshotRel = `test-transcripts/channels/${slug}/snapshot.json`; + const snapshotRel = `${testPaths().transcriptsDir}/channels/${slug}/snapshot.json`; if (await pathExists(snapshotRel)) return; await page.goto(`/channels/${slug}`); const button = page.getByRole("button", { name: /refresh report/i }); @@ -244,7 +248,7 @@ export async function copyFixture(name: string) { const dst = join(fixturesRoot, "test-transcripts", name); await rm(dst, { recursive: true, force: true }); await mkdir(dst, { recursive: true }); - await cp(testTranscriptsDir, dst, { recursive: true }); + await cp(testPaths().transcriptsDir, dst, { recursive: true }); } // --------------------------------------------------------------------------- @@ -312,7 +316,7 @@ export async function writeDigestVideo(opts: { startOffsetSeconds = 0, skipCuesJson = false, } = opts; - const dir = join(testTranscriptsDir, "channels", channelSlug, "data", videoId); + const dir = join(testPaths().transcriptsDir, "channels", channelSlug, "data", videoId); await mkdir(dir, { recursive: true }); // Every cue's words are GLOBALLY UNIQUE. measureAlignment anchors on 8-word @@ -454,7 +458,7 @@ export async function writeChannelConfig( channelSlug: string, config: Record<string, unknown> = {}, ) { - const dir = join(testTranscriptsDir, "channels", channelSlug); + const dir = join(testPaths().transcriptsDir, "channels", channelSlug); await mkdir(dir, { recursive: true }); await writeFile( join(dir, "config.json"), diff --git a/editor/e2e/import-video.spec.ts b/editor/e2e/import-video.spec.ts @@ -6,6 +6,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; // The Playlist stage's "Import single video" panel fetches one off-playlist @@ -41,7 +42,7 @@ test("import single video by URL fetches it and appends to the archive", async ( .poll( () => pathExists( - "test-transcripts/channels/test-pipeline/data/oneoff00001/metadata.info.json", + `${testPaths().transcriptsDir}/channels/test-pipeline/data/oneoff00001/metadata.info.json`, ), { timeout: 30_000 }, ) @@ -50,7 +51,7 @@ test("import single video by URL fetches it and appends to the archive", async ( // And it's recorded in the channel archive so a later sync won't re-fetch it. await expect(async () => { const archive = await readFile( - resolvePath("test-transcripts/channels/test-pipeline/archive"), + resolvePath(`${testPaths().transcriptsDir}/channels/test-pipeline/archive`), "utf8", ); expect(archive).toContain("youtube oneoff00001"); @@ -100,14 +101,14 @@ test("a BitChute import runs on BitChute's queue and pace, and is never fetched }); await expect(log).toContainText("--sleep-requests 3"); - const metaPath = `test-transcripts/channels/test-transcribe/data/${id}/metadata.info.json`; + const metaPath = `${testPaths().transcriptsDir}/channels/test-transcribe/data/${id}/metadata.info.json`; await expect.poll(() => pathExists(metaPath), { timeout: 30_000 }).toBe(true); const meta = JSON.parse(await readFile(resolvePath(metaPath), "utf8")); expect(meta.extractor_key).toBe("BitChute"); // The job ran on BitChute's queue, not the channel's. await expect(async () => { - const dir = resolvePath("test-transcripts/.jobs"); + const dir = resolvePath(`${testPaths().transcriptsDir}/.jobs`); const queues: string[] = []; for (const name of await readdir(dir)) { if (!name.endsWith(".meta.json")) continue; @@ -120,7 +121,7 @@ test("a BitChute import runs on BitChute's queue and pace, and is never fetched // WAIT ON THE JOB, NOT THE PAGE: the second import can only be refused once // the first has finished and written its archive entry. await expect(async () => { - const dir = resolvePath("test-transcripts/.jobs"); + const dir = resolvePath(`${testPaths().transcriptsDir}/.jobs`); const statuses: string[] = []; for (const name of await readdir(dir)) { if (!name.endsWith(".meta.json")) continue; @@ -144,9 +145,9 @@ test("a BitChute import runs on BitChute's queue and pace, and is never fetched }).toPass({ timeout: 30_000 }); // However many clicks that took, BitChute was asked once. const imports: string[] = []; - for (const name of await readdir(resolvePath("test-transcripts/.jobs"))) { + for (const name of await readdir(resolvePath(`${testPaths().transcriptsDir}/.jobs`))) { if (!name.endsWith(".meta.json")) continue; - const m = JSON.parse(await readFile(resolvePath(`test-transcripts/.jobs/${name}`), "utf8")); + const m = JSON.parse(await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${name}`), "utf8")); if (m.kind === "import-one" && m.videoId === id) imports.push(m.id); } expect(imports).toHaveLength(1); diff --git a/editor/e2e/incomplete-transcript.spec.ts b/editor/e2e/incomplete-transcript.spec.ts @@ -18,10 +18,11 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "test-transcribe"; -const DATA = `test-transcripts/channels/${CHANNEL}/data`; +const DATA = `${testPaths().transcriptsDir}/channels/${CHANNEL}/data`; // Non-empty whisper transcript so the video reads as transcribed (and isn't // flagged untranscribable for being empty). @@ -172,7 +173,7 @@ test("the fix run's log survives the refresh that clears the banner", async ({ await resetData(); const slug = "incomplete-log"; const id = "vidVttTrunc"; - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); const dir = `${root}/data/${id}`; await mkdir(dir, { recursive: true }); await writeFile( @@ -273,7 +274,7 @@ test("channel bulk bar: clear incomplete resets the video and enables auto-runne transcription: { enabled: boolean }; download: { enabled: boolean }; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(settings.autoQueue.transcription.enabled).toBe(true); expect(settings.autoQueue.download.enabled).toBe(true); diff --git a/editor/e2e/jobs-batch-tasks-drain.spec.ts b/editor/e2e/jobs-batch-tasks-drain.spec.ts @@ -12,6 +12,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -22,7 +23,7 @@ async function invalidateCache() { // Build a transcribe-handling channel with `count` slow videos (each has only // audio.mp3 on disk, so "Transcribe missing" will run whisper on all of them). async function makeTranscribeChannel(slug: string, name: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, @@ -43,7 +44,7 @@ async function transcriptCount(slug: string, ids: string[]): Promise<number> { let n = 0; for (const id of ids) { if ( - await pathExists(`test-transcripts/channels/${slug}/data/${id}/transcript.json`) + await pathExists(`${testPaths().transcriptsDir}/channels/${slug}/data/${id}/transcript.json`) ) { n++; } diff --git a/editor/e2e/jobs-filters.spec.ts b/editor/e2e/jobs-filters.spec.ts @@ -1,6 +1,6 @@ import { mkdir, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { resetData, resolvePath } from "./helpers"; +import { resetData, resolvePath, testPaths } from "./helpers"; // The /jobs screen reads `.log` files in TRANSCRIPTS_DIR/.jobs and enriches any // not in the in-memory registry from a `<id>.meta.json` sidecar (see @@ -8,7 +8,7 @@ import { resetData, resolvePath } from "./helpers"; // the registry, so writing a log + sidecar pair gives a deterministic // "archived" row — exercising both the metadata-read path and giving rows with // known kinds/statuses for the client-side filter bar. -const JOBS_DIR = "test-transcripts/.jobs"; +const JOBS_DIR = `${testPaths().transcriptsDir}/.jobs`; type SeedJob = { id: string; diff --git a/editor/e2e/jobs-reorder.spec.ts b/editor/e2e/jobs-reorder.spec.ts @@ -10,6 +10,7 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -20,7 +21,7 @@ async function invalidateCache() { // A channel whose Sync runs slowly (fake-ytdlp honors --test-slow), so it stays // "running"/"queued" long enough to reorder. async function makeSlowChannel(slug: string, name: string) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, diff --git a/editor/e2e/jobs-retry.spec.ts b/editor/e2e/jobs-retry.spec.ts @@ -12,6 +12,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -20,7 +21,7 @@ async function invalidateCache() { } async function makeSlowChannel(slug: string, name: string) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, @@ -39,7 +40,7 @@ async function writeArchivedJob( id: string, meta: Record<string, unknown>, ): Promise<void> { - const dir = resolvePath("test-transcripts/.jobs"); + const dir = resolvePath(`${testPaths().transcriptsDir}/.jobs`); await mkdir(dir, { recursive: true }); await writeFile(`${dir}/${id}.log`, `archived log for ${id}\n`); await writeFile(`${dir}/${id}.meta.json`, JSON.stringify({ id, ...meta })); @@ -105,7 +106,7 @@ test("Retry on an archived bucket job re-derives the bucket's current members", }) => { test.setTimeout(90_000); const CHANNEL = "test-transcribe"; - const ROOT = `test-transcripts/channels/${CHANNEL}`; + const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; await resetData("one-transcribe-channel-with-audio"); // The retry flow reads the playlist to resolve each id's URL. Slug-style URLs // keep extractVideoId() === the id without needing platform claim ids. diff --git a/editor/e2e/lane-runner.spec.ts b/editor/e2e/lane-runner.spec.ts @@ -12,6 +12,7 @@ import { writeChannelConfig, writeDigestVideo, writeSettings, + testPaths, } from "./helpers"; // THE AUTO-QUEUE RUNNER, DRIVING THE OPERATION LANES. @@ -81,7 +82,7 @@ const CATCH_ALL: Group = { }; function dataRel(videoId: string, file: string): string { - return join("test-transcripts", "channels", CHANNEL, "data", videoId, file); + return join(testPaths().transcriptsDir, "channels", CHANNEL, "data", videoId, file); } // Settings with both engines named and the lanes' own gates OPEN. `autoQueue` @@ -448,7 +449,7 @@ type HeldByLane = Record<string, boolean | null>; async function heldByLane(): Promise<HeldByLane> { const s = await readJson<{ autoQueue?: Record<string, { held?: boolean }>; - }>("test-settings.json").catch(() => ({}) as { autoQueue?: undefined }); + }>(testPaths().settingsFile).catch(() => ({}) as { autoQueue?: undefined }); return Object.fromEntries( ["transcription", "download", "digest", "backfill"].map((lane) => [ lane, diff --git a/editor/e2e/maybe-missing.spec.ts b/editor/e2e/maybe-missing.spec.ts @@ -6,6 +6,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "availability-test"; @@ -22,7 +23,7 @@ const BASELINE_IDS = [ "vidneedsauth1", ]; -const channelRoot = `test-transcripts/channels/${CHANNEL}`; +const channelRoot = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; function dataDir(id: string): string { return `${channelRoot}/data/${id}`; diff --git a/editor/e2e/metadata-scan-botcheck.spec.ts b/editor/e2e/metadata-scan-botcheck.spec.ts @@ -6,6 +6,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; // THE BOT CHECK, AND THE COOKIES THE SCAN WAS NOT USING. @@ -19,7 +20,7 @@ import { // A block on a cookie-less pass is not a refusal. It is the one thing we have // not tried yet. const CHANNEL = "test-botcheck"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const ALL = [ "botcheck0001", "guestvid0001", diff --git a/editor/e2e/metadata-scan-softblock.spec.ts b/editor/e2e/metadata-scan-softblock.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { channelStage, generateReport, readJson, resetData } from "./helpers"; +import { channelStage, generateReport, readJson, resetData, testPaths } from "./helpers"; // THE SOFT BLOCK. Measured on a real channel: after ~100 good records YouTube // answered "Video unavailable" for 545 CONSECUTIVE videos, all of which fetched @@ -10,7 +10,7 @@ import { channelStage, generateReport, readJson, resetData } from "./helpers"; // The fixture is the same shape, small: one genuinely members-only video, two // readable ones, then a run of soft-blocked ids. const CHANNEL = "test-softblock"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; type MetadataScan = { entries: Record<string, { title: string }>; diff --git a/editor/e2e/new-channel-onboarding.spec.ts b/editor/e2e/new-channel-onboarding.spec.ts @@ -15,7 +15,7 @@ // select). Only the textbox has the exact accessible name "URL". import { test, expect } from "@playwright/test"; -import { resetData, readJson, pathExists, generateReport } from "./helpers"; +import { resetData, readJson, pathExists, generateReport, testPaths } from "./helpers"; test("derives platform, handling, slug and queue from a YouTube URL offline", async ({ page, @@ -102,7 +102,7 @@ test("creating with 'Fetch playlist now' stores the playlist", async ({ await expect .poll( () => - pathExists("test-transcripts/channels/playlist-chan/playlist"), + pathExists(`${testPaths().transcriptsDir}/channels/playlist-chan/playlist`), { timeout: 15000 }, ) .toBe(true); @@ -147,7 +147,7 @@ test("'Add to top of auto-queue' takes the first rank and enables the runner", a root?: { children?: { id?: string; children?: { id?: string }[] }[] }; }; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); const dl = s.autoQueue?.download; return { enabled: dl?.enabled ?? false, diff --git a/editor/e2e/no-orphan-fixtures.spec.ts b/editor/e2e/no-orphan-fixtures.spec.ts @@ -26,11 +26,12 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { listFixtureProcesses } from "./fixtureProcs"; async function makeTranscribeChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, diff --git a/editor/e2e/no-subs-fallback.spec.ts b/editor/e2e/no-subs-fallback.spec.ts @@ -9,10 +9,11 @@ import { readJson, resetData, writeSettings, + testPaths, } from "./helpers"; const CHANNEL = "test-livechat"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const here = path.dirname(fileURLToPath(import.meta.url)); type DownloadOutcome = { @@ -74,7 +75,7 @@ test("default off: live_chat-only video downloads audio but defers whisper", asy // The fallback should reuse the metadata.info.json the primary attempt // wrote, not re-query the extractor. const invocations = await readFile( - path.join(here, "..", ROOT, "fake-ytdlp.invocations"), + path.join(ROOT, "fake-ytdlp.invocations"), "utf8", ); expect(invocations).toMatch( diff --git a/editor/e2e/operation-settings.spec.ts b/editor/e2e/operation-settings.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readJson, resetData } from "./helpers"; +import { readJson, resetData, testPaths } from "./helpers"; // PER-OPERATION SETTINGS, on the operation's own page. // @@ -47,7 +47,7 @@ test("digest settings round-trip through the form", async ({ page }) => { sections: string[]; apps: Record<string, { numCtx?: number }>; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.digest?.timestampMode).toBe("absolute"); expect(saved.digest?.promptVariant).toBe("bakeoff-r3"); expect(saved.digest?.spendCapUsd).toBe(12.5); @@ -95,7 +95,7 @@ test("a save on /settings does not reset the digest prompt shape", async ({ const saved = await readJson<{ adminTitle: string; digest?: { timestampMode: string; promptVariant: string }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.adminTitle).toBe("Unrelated Change"); expect(saved.digest?.timestampMode).toBe("absolute"); expect(saved.digest?.promptVariant).toBe("keepme"); @@ -132,7 +132,7 @@ test("the lane's switch survives a save of the operation form beside it", async const saved = await readJson<{ autoQueue?: { backfill?: { held?: boolean } }; diarization?: { enabled: boolean }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.autoQueue?.backfill?.held).toBe(false); expect(saved.diarization?.enabled).toBe(true); }); @@ -174,7 +174,7 @@ test("the sortformer engine settings round-trip through the form", async ({ segModel: string; threshold: number; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.diarization?.engine).toBe("sortformer"); expect(saved.diarization?.backend).toBe("cpu"); expect(saved.diarization?.sortformerBin).toBe("/opt/sortformer/diarize-file"); @@ -209,7 +209,7 @@ test("attribution settings round-trip on the text-only operation's page", async textOnlyEnabled: boolean; model: string; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.attribution?.enabled).toBe(true); expect(saved.attribution?.textOnlyEnabled).toBe(true); expect(saved.attribution?.model).toBe("qwen2.5:14b"); diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts @@ -28,6 +28,7 @@ import { writeChannelConfig, writeSettings, writeSite, + testPaths, } from "./helpers"; const TOKEN = "test-worker-token"; @@ -78,7 +79,7 @@ test("a channel's lifecycle over ops: create on a site, list, re-site, rename, d await resetData("empty"); await settings(); await writeSite("mysite", { channels: [] }); - const SITE = "test-transcripts/sites/mysite/site.json"; + const SITE = `${testPaths().transcriptsDir}/sites/mysite/site.json`; const list = async () => { const res = await request.get(`${baseUrl}/api/ops/channels`, { headers: AUTH }); expect(res.status()).toBe(200); @@ -100,7 +101,7 @@ test("a channel's lifecycle over ops: create on a site, list, re-site, rename, d }); expect(made.body).toEqual({ ok: true, slug: "made-x", jobIds: [] }); const cfg = await readJson<Record<string, unknown>>( - "test-transcripts/channels/made-x/config.json", + `${testPaths().transcriptsDir}/channels/made-x/config.json`, ); expect(cfg.sourceKind).toBe("social"); expect(cfg.socialHandle).toBe("made_user"); @@ -133,7 +134,7 @@ test("a channel's lifecycle over ops: create on a site, list, re-site, rename, d expect(renamed.status).toBe(200); expect((renamed.body as { slug?: string }).slug).toBe("made-renamed-x"); expect((await list()).map((c) => c.slug)).toEqual(["made-renamed-x"]); - expect(await pathExists("test-transcripts/channels/made-x")).toBe(false); + expect(await pathExists(`${testPaths().transcriptsDir}/channels/made-x`)).toBe(false); const refused = await ops(request, "delete-channel", { slug: "made-renamed-x", @@ -159,7 +160,7 @@ test("channel-config round-trips a download filter and refuses a bad regex", asy await resetData("title-filter-channel"); await settings(); const SLUG = "test-filter"; - const CONFIG = `test-transcripts/channels/${SLUG}/config.json`; + const CONFIG = `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`; // TWO FIELDS THE CLEAR-THEN-LAYER PATH ACTUALLY THREATENS. name/handling/url // survive a patch trivially — they are re-posted by the serializer because // parseChannelForm requires the first two and CHANNEL_FORM_FIELDS spares @@ -271,7 +272,7 @@ test("channel-priority writes a per-operation override", async ({ request }) => channelPriority?: { channels?: Record<string, { overrides?: Record<string, string> }>; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); return s.channelPriority?.channels?.[SLUG]?.overrides?.download ?? null; }) .toBe("paused"); @@ -297,7 +298,7 @@ test("channel-priority writes a per-operation override", async ({ request }) => channelPriority?: { channels?: Record<string, { overrides?: Record<string, string> }>; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); return s.channelPriority?.channels?.[SLUG]?.overrides?.download ?? null; }) .toBe(null); @@ -326,7 +327,7 @@ test("metadata-scan starts a job, and the job says it is a metadata-scan", async // THE ROUTE DOES NOT STREAM, so the id is the whole contract: the caller // follows the same log endpoint the editor's own panel polls. // The sidecar is written with a `void` promise right after enqueue, so poll. - const metaPath = `test-transcripts/.jobs/${body.jobId}.meta.json`; + const metaPath = `${testPaths().transcriptsDir}/.jobs/${body.jobId}.meta.json`; await expect .poll(async () => { const meta = await readJson<{ kind: string; channelSlug: string }>( @@ -380,7 +381,7 @@ test("a sync queued behind another platform job ends done, not failed", async ({ type Meta = { status: string; queueKey?: string }; const meta = (id: string) => - readJson<Meta>(`test-transcripts/.jobs/${id}.meta.json`).catch(() => null); + readJson<Meta>(`${testPaths().transcriptsDir}/.jobs/${id}.meta.json`).catch(() => null); const hold = await request.get( `${baseUrl}/api/test/stuck-job?queue=${encodeURIComponent("platform:youtube")}&releaseAfterMs=10000`, @@ -416,7 +417,7 @@ test("refresh-report regenerates snapshot.json", async ({ request }) => { await resetData("title-filter-channel"); await settings(); const SLUG = "test-filter"; - const SNAP = `test-transcripts/channels/${SLUG}/snapshot.json`; + const SNAP = `${testPaths().transcriptsDir}/channels/${SLUG}/snapshot.json`; // Removed rather than assumed absent: a debounced regen armed by the previous // spec can land between resetData's copy and here, and the point of the // assertion below is the ROUTE's effect, not the scheduler's. @@ -434,7 +435,7 @@ test("refresh-report regenerates snapshot.json", async ({ request }) => { async () => ( await readJson<{ status: string }>( - `test-transcripts/.jobs/${jobId}.meta.json`, + `${testPaths().transcriptsDir}/.jobs/${jobId}.meta.json`, ).catch(() => null) )?.status ?? null, { timeout: 30_000 }, @@ -560,7 +561,7 @@ test("lane flips a hold, and /api/auto-queue/status agrees", async ({ .poll(async () => { const s = await readJson<{ autoQueue?: Record<string, { enabled?: boolean }>; - }>("test-settings.json"); + }>(testPaths().settingsFile); return s.autoQueue?.download?.enabled ?? null; }) .toBe(true); @@ -674,7 +675,7 @@ test("tags defines a vocabulary, and tag-videos writes pins with their source", string, { manual?: string[]; sources?: Record<string, { source: string }> } >; - }>("test-transcripts/tags.json"); + }>(`${testPaths().transcriptsDir}/tags.json`); expect(file.tags[0].id).toBe("eva-collab"); expect(file.assignments[`${slug}/${id}`].manual).toEqual(["eva-collab"]); // A CALL ARRIVING HERE IS NOT THE BROWSER, and the default provenance says so @@ -730,7 +731,7 @@ test("tags defines a vocabulary, and tag-videos writes pins with their source", }); expect((unpin.body as { changed?: number }).changed).toBe(1); const after = await readJson<{ assignments: Record<string, unknown> }>( - "test-transcripts/tags.json", + `${testPaths().transcriptsDir}/tags.json`, ); expect(after.assignments).toEqual({}); @@ -745,7 +746,7 @@ test("tags defines a vocabulary, and tag-videos writes pins with their source", const left = await readJson<{ tags: unknown[]; assignments: Record<string, { suppressed?: string[] }>; - }>("test-transcripts/tags.json"); + }>(`${testPaths().transcriptsDir}/tags.json`); expect(left.tags).toEqual([]); expect(left.assignments[`${slug}/${id}`].suppressed).toEqual(["eva-collab"]); }); @@ -763,7 +764,7 @@ test("keep-videos marks the matching video only, after a dry run that writes not const slug = "test-youtube"; const kept = "20240102_keepme12345"; const other = "20240101_test1234567"; // "Synthetic Test Video" — no needle - const channel = `test-transcripts/channels/${slug}`; + const channel = `${testPaths().transcriptsDir}/channels/${slug}`; await mkdir(resolvePath(`${channel}/data/${kept}`), { recursive: true }); await writeFile( resolvePath(`${channel}/data/${kept}/metadata.info.json`), @@ -858,7 +859,7 @@ test("build-site with a bare siteId starts its build stage (the index first: the await expect .poll(async () => { const meta = await readJson<{ kind: string }>( - `test-transcripts/.jobs/${jobId}.meta.json`, + `${testPaths().transcriptsDir}/.jobs/${jobId}.meta.json`, ).catch(() => null); return meta?.kind ?? null; }) @@ -895,7 +896,7 @@ test("publish: each verb enqueues its run of stages on the publish queue; a dupl expect(index.jobs?.map((j) => [j.kind, j.target])).toEqual([["update-index", "_index"]]); expect(index.jobId).toBe(index.jobs?.[0].jobId); const meta = await readJson<{ kind: string; queueKey: string; status: string }>( - `test-transcripts/.jobs/${index.jobId}.meta.json`, + `${testPaths().transcriptsDir}/.jobs/${index.jobId}.meta.json`, ); expect([meta.kind, meta.queueKey, meta.status]).toEqual(["publish-update-index", "publish", "queued"]); diff --git a/editor/e2e/ops-cut-release.spec.ts b/editor/e2e/ops-cut-release.spec.ts @@ -17,10 +17,10 @@ import { readFile, writeFile } from "node:fs/promises"; import { test, expect, type APIRequestContext } from "@playwright/test"; import { baseUrl } from "./baseUrl"; -import { resolvePath } from "./helpers"; +import { resolvePath, testPaths } from "./helpers"; -const EDITOR_CHANGELOG = resolvePath("test-changelog.md"); -const EXPORT_CHANGELOG = resolvePath("test-export-changelog.md"); +const EDITOR_CHANGELOG = resolvePath(testPaths().editorChangelog); +const EXPORT_CHANGELOG = resolvePath(testPaths().exportChangelog); const AUTH = { authorization: "Bearer test-worker-token" }; type CutResponse = { diff --git a/editor/e2e/pacing.spec.ts b/editor/e2e/pacing.spec.ts @@ -1,6 +1,6 @@ import { mkdir, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { readJson, resetData, resolvePath, writeSettings } from "./helpers"; +import { readJson, resetData, resolvePath, writeSettings, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; // YouTube lane pacing (release 7): a rate-limited video is DEFERRED for 6 h as @@ -27,11 +27,11 @@ const ONE_WORKER = [ }, ]; -const STATE_FILE = "test-transcripts/.auto-queue/state.json"; +const STATE_FILE = `${testPaths().transcriptsDir}/.auto-queue/state.json`; // Copied from auto-queue.spec.ts: a YouTube channel with undownloaded videos. async function makeDownloadChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -148,7 +148,7 @@ test("a deferred video is skipped by auto-download, and the lane says so", async }) => { await setup(["a1", "a2"]); // Seed a live deferral on a1 — as if its download had just answered 429. - await mkdir(resolvePath("test-transcripts/.auto-queue"), { recursive: true }); + await mkdir(resolvePath(`${testPaths().transcriptsDir}/.auto-queue`), { recursive: true }); await writeFile( resolvePath(STATE_FILE), JSON.stringify({ diff --git a/editor/e2e/parakeet-partial.spec.ts b/editor/e2e/parakeet-partial.spec.ts @@ -13,10 +13,11 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; async function makeTranscribeChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, @@ -47,7 +48,7 @@ test("Stop & keep progress pauses a parakeet run, caches the window, and resumes ], }); await makeTranscribeChannel("partial-chan", ["slowoppk1"]); - const dir = "test-transcripts/channels/partial-chan/data/slowoppk1"; + const dir = `${testPaths().transcriptsDir}/channels/partial-chan/data/slowoppk1`; const cachedWindow = `${dir}/.audio.mp3.parakeet/win-0000.json`; const transcript = `${dir}/transcript.json`; @@ -94,7 +95,7 @@ test("Pause Transcriptions stops a parakeet run after the current segment, cache ], }); await makeTranscribeChannel("gpause-chan", ["slowoppk1"]); - const dir = "test-transcripts/channels/gpause-chan/data/slowoppk1"; + const dir = `${testPaths().transcriptsDir}/channels/gpause-chan/data/slowoppk1`; const cachedWindow = `${dir}/.audio.mp3.parakeet/win-0000.json`; const transcript = `${dir}/transcript.json`; @@ -164,9 +165,9 @@ test("Stop & keep progress on a force-killed parakeet run is NOT recorded as a f // force-SIGKILLed — `await child` REJECTS. The bug recorded that rejection in // failed-transcriptions (blacklisting the video forever); it must be a skip. await makeTranscribeChannel("hangterm-chan", ["hangtermpk1"]); - const dir = "test-transcripts/channels/hangterm-chan/data/hangtermpk1"; + const dir = `${testPaths().transcriptsDir}/channels/hangterm-chan/data/hangtermpk1`; const transcript = `${dir}/transcript.json`; - const failedFile = "test-transcripts/channels/hangterm-chan/failed-transcriptions"; + const failedFile = `${testPaths().transcriptsDir}/channels/hangterm-chan/failed-transcriptions`; await generateReport(page, "hangterm-chan"); await page.goto(channelStage("hangterm-chan", "transcribe")); @@ -216,7 +217,7 @@ test("a parakeet worker's device is configurable and persists", async ({ const saved = await readJson<{ workers?: { appId?: string; config?: { device?: string } }[]; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.workers?.[0].appId).toBe("parakeet"); expect(saved.workers?.[0].config?.device).toBe("CUDA0"); }); diff --git a/editor/e2e/parakeet.spec.ts b/editor/e2e/parakeet.spec.ts @@ -7,10 +7,11 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; const CHANNEL = "test-transcribe"; -const DATA = `test-transcripts/channels/${CHANNEL}/data`; +const DATA = `${testPaths().transcriptsDir}/channels/${CHANNEL}/data`; // Minimal metadata so transcribeOne's normalize pass runs (it needs // metadata.info.json) and writes transcript.cues.json. diff --git a/editor/e2e/partial-downloads-bucket.spec.ts b/editor/e2e/partial-downloads-bucket.spec.ts @@ -11,10 +11,11 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "test-transcribe"; -const CHANNEL_ROOT = `test-transcripts/channels/${CHANNEL}`; +const CHANNEL_ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; test("partial download surfaces in a bucket on the channel page", async ({ page, diff --git a/editor/e2e/persist-youtube-handling.spec.ts b/editor/e2e/persist-youtube-handling.spec.ts @@ -15,11 +15,11 @@ import { readFile, readdir, stat, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { readJson, resetData, resolvePath, writeSettings } from "./helpers"; +import { readJson, resetData, resolvePath, writeSettings, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; const SLUG = "test-youtube"; -const rel = (p: string) => `test-transcripts/channels/${SLUG}/${p}`; +const rel = (p: string) => `${testPaths().transcriptsDir}/channels/${SLUG}/${p}`; // The fixture's downloaded video: metadata.info.json + transcript.en.vtt. const HAS_TRANSCRIPT = "fake00000001"; // In the playlist, never downloaded. diff --git a/editor/e2e/pipeline.spec.ts b/editor/e2e/pipeline.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; test("store playlist writes a playlist file with 5 URLs", async ({ page }) => { @@ -19,7 +20,7 @@ test("store playlist writes a playlist file with 5 URLs", async ({ page }) => { { timeout: 20_000 }, ); expect( - await pathExists("test-transcripts/channels/test-pipeline/playlist"), + await pathExists(`${testPaths().transcriptsDir}/channels/test-pipeline/playlist`), ).toBe(true); }); @@ -52,18 +53,18 @@ test("download from playlist fetches all 5 URLs and writes the archive", async ( for (let i = 1; i <= 5; i++) { expect( await pathExists( - `test-transcripts/channels/test-pipeline/data/fake0000000${i}/metadata.info.json`, + `${testPaths().transcriptsDir}/channels/test-pipeline/data/fake0000000${i}/metadata.info.json`, ), ).toBe(true); } // Each managed download writes a per-video log alongside the data. expect( await pathExists( - "test-transcripts/channels/test-pipeline/data/fake00000001/download.log", + `${testPaths().transcriptsDir}/channels/test-pipeline/data/fake00000001/download.log`, ), ).toBe(true); const config = await readJson<{ lastFullDownloadAt?: string }>( - "test-transcripts/channels/test-pipeline/config.json", + `${testPaths().transcriptsDir}/channels/test-pipeline/config.json`, ); expect(typeof config.lastFullDownloadAt).toBe("string"); }); @@ -109,12 +110,12 @@ test("sync enumerates the channel, downloads new entries, writes lastSyncedAt", for (let i = 1; i <= 5; i++) { expect( await pathExists( - `test-transcripts/channels/test-pipeline/data/fake0000000${i}/metadata.info.json`, + `${testPaths().transcriptsDir}/channels/test-pipeline/data/fake0000000${i}/metadata.info.json`, ), ).toBe(true); } const config = await readJson<{ lastSyncedAt?: string }>( - "test-transcripts/channels/test-pipeline/config.json", + `${testPaths().transcriptsDir}/channels/test-pipeline/config.json`, ); expect(typeof config.lastSyncedAt).toBe("string"); }); @@ -123,7 +124,7 @@ test("download videos skips a transcribed video even when its audio was cleaned page, }) => { await resetData("one-transcribe-channel-with-audio"); - const channelRoot = "test-transcripts/channels/test-transcribe"; + const channelRoot = `${testPaths().transcriptsDir}/channels/test-transcribe`; // vidA: transcribed, audio cleaned up — should be skipped via transcript.json. await writeFile( @@ -171,7 +172,7 @@ test("channel list sync button runs the platform-queue sync", async ({ timeout: 30_000, }); const config = await readJson<{ lastSyncedAt?: string }>( - "test-transcripts/channels/test-pipeline/config.json", + `${testPaths().transcriptsDir}/channels/test-pipeline/config.json`, ); expect(typeof config.lastSyncedAt).toBe("string"); }); diff --git a/editor/e2e/pre-clean-availability.spec.ts b/editor/e2e/pre-clean-availability.spec.ts @@ -10,6 +10,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -25,7 +26,7 @@ import { baseUrl } from "./baseUrl"; const here = dirname(fileURLToPath(import.meta.url)); const CHANNEL = "availability-test"; const FIXTURE = "availability-baseline"; -const channelRoot = `test-transcripts/channels/${CHANNEL}`; +const channelRoot = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; function dataRel(id: string, file: string): string { return `${channelRoot}/data/${id}/${file}`; diff --git a/editor/e2e/publish-lane.spec.ts b/editor/e2e/publish-lane.spec.ts @@ -10,17 +10,17 @@ import { readdir } from "node:fs/promises"; import { test, expect, type Page } from "@playwright/test"; import { baseUrl } from "./baseUrl"; -import { readJson, resetData, resolvePath, writeSettings, writeSite } from "./helpers"; +import { readJson, resetData, resolvePath, writeSettings, writeSite, testPaths } from "./helpers"; type Meta = { id: string; kind: string; status: string; spec?: { params?: { runId?: string } } }; async function metasOf(kind: string): Promise<Meta[]> { - const files = (await readdir(resolvePath("test-transcripts/.jobs")).catch(() => [])).filter((f) => + const files = (await readdir(resolvePath(`${testPaths().transcriptsDir}/.jobs`)).catch(() => [])).filter((f) => f.endsWith(".meta.json"), ); const out: Meta[] = []; for (const f of files) { - const m = await readJson<Meta>(`test-transcripts/.jobs/${f}`).catch(() => null); + const m = await readJson<Meta>(`${testPaths().transcriptsDir}/.jobs/${f}`).catch(() => null); if (m?.kind === kind) out.push(m); } return out; @@ -65,7 +65,7 @@ test("the settings form saves settings.publish, and Start says why when the lane await form.getByRole("button", { name: "Save publish settings" }).click(); await expect(form.getByRole("status")).toHaveText("Saved."); await expect(async () => { - const s = await readJson<{ publish?: Record<string, unknown> }>("test-settings.json"); + const s = await readJson<{ publish?: Record<string, unknown> }>(testPaths().settingsFile); expect(s.publish).toMatchObject({ checkEveryMinutes: 5, previewBranch: "lane-prev", hub: "build", enabled: false }); }).toPass({ timeout: 10_000 }); @@ -105,7 +105,7 @@ test("enabled and started, the lane updates the index; a hold mid-stage stops th await page.getByRole("button", { name: "pause publishing" }).click(); await expect(page.getByRole("button", { name: "resume publishing" })).toBeVisible(); expect((await publishStatus(request)).lane.held).toBe(true); - const settings = await readJson<{ publish?: { held?: boolean } }>("test-settings.json"); + const settings = await readJson<{ publish?: { held?: boolean } }>(testPaths().settingsFile); expect(settings.publish?.held).toBe(true); // The stage is still queued behind the holder; let the holder go. expect((await metasOf("publish-update-index"))[0]?.status).not.toBe("done"); diff --git a/editor/e2e/publish.spec.ts b/editor/e2e/publish.spec.ts @@ -28,9 +28,10 @@ import { resolvePath, writeSettings, writeSite, + testPaths, } from "./helpers"; -const BUILDS = "test-transcripts/.export-builds"; +const BUILDS = `${testPaths().transcriptsDir}/.export-builds`; const SITE = "pubsite"; const PROJECT = "pubproj"; @@ -40,12 +41,12 @@ const chip = (page: Page, name: string, id = SITE) => row(page, id).locator(`[da type Meta = { id: string; kind: string; queueKey?: string; status: string; spec?: { params?: { runId?: string } } }; async function publishMetas(): Promise<Meta[]> { - const files = (await readdir(resolvePath("test-transcripts/.jobs")).catch(() => [])).filter((f) => + const files = (await readdir(resolvePath(`${testPaths().transcriptsDir}/.jobs`)).catch(() => [])).filter((f) => f.endsWith(".meta.json"), ); const out: Meta[] = []; for (const f of files) { - const m = await readJson<Meta>(`test-transcripts/.jobs/${f}`).catch(() => null); + const m = await readJson<Meta>(`${testPaths().transcriptsDir}/.jobs/${f}`).catch(() => null); if (m?.kind.startsWith("publish-")) out.push(m); } return out.sort((a, b) => a.id.localeCompare(b.id)); @@ -56,7 +57,7 @@ async function logOf(kind: string): Promise<string> { const last = metas[metas.length - 1]; if (!last) return ""; const { readFile } = await import("node:fs/promises"); - return readFile(resolvePath(`test-transcripts/.jobs/${last.id}.log`), "utf8").catch(() => ""); + return readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${last.id}.log`), "utf8").catch(() => ""); } type Invocation = { argv: string[]; project: string; branch: string; outDir: string; files: number }; @@ -97,11 +98,11 @@ test("the index: no stamp, then the Pool's Build index writes it and every row's await openSites(page); await expect(chip(page, "index")).toContainText("no index yet"); await expect(chip(page, "built")).toContainText("update the index first"); - expect(await pathExists("test-transcripts/.export-index/stamp.json")).toBe(false); + expect(await pathExists(`${testPaths().transcriptsDir}/.export-index/stamp.json`)).toBe(false); await buildIndex(page); const stamp = await readJson<{ v: number; stampId: string; sites: Record<string, unknown>; settingsSig?: string }>( - "test-transcripts/.export-index/stamp.json", + `${testPaths().transcriptsDir}/.export-index/stamp.json`, ); expect(stamp.v).toBe(1); expect(Object.keys(stamp.sites)).toEqual([SITE]); @@ -291,7 +292,7 @@ test("the site form's publish policy: preview without a Pages project is refused await expect( page.getByRole("alert").filter({ hasText: 'publish.auto "preview" deploys the site, and it has no cloudflareProject' }), ).toBeVisible(); - const site = await readJson<Record<string, unknown>>("test-transcripts/sites/noproj/site.json"); + const site = await readJson<Record<string, unknown>>(`${testPaths().transcriptsDir}/sites/noproj/site.json`); expect("publish" in site).toBe(false); // Build is allowed without a project, and is written. @@ -299,7 +300,7 @@ test("the site form's publish policy: preview without a Pages project is refused await page.getByRole("button", { name: /save site/i }).click(); await expect(page.getByRole("status").filter({ hasText: "Saved" })).toBeVisible(); await expect(async () => { - const saved = await readJson<{ publish?: { auto: string } }>("test-transcripts/sites/noproj/site.json"); + const saved = await readJson<{ publish?: { auto: string } }>(`${testPaths().transcriptsDir}/sites/noproj/site.json`); expect(saved.publish?.auto).toBe("build"); }).toPass({ timeout: 10_000 }); }); diff --git a/editor/e2e/queues.spec.ts b/editor/e2e/queues.spec.ts @@ -5,6 +5,7 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; async function setQueueViaCustom( @@ -45,8 +46,8 @@ test("Sync is refused while its platform is in a rate-limit cooldown", async ({ // if auto-download or a prior sync had just hit a 429. A manual Sync must // refuse rather than re-storm the source. const until = Date.now() + 5 * 60_000; - const stateFile = resolvePath("test-transcripts/.auto-queue/state.json"); - await mkdir(resolvePath("test-transcripts/.auto-queue"), { recursive: true }); + const stateFile = resolvePath(`${testPaths().transcriptsDir}/.auto-queue/state.json`); + await mkdir(resolvePath(`${testPaths().transcriptsDir}/.auto-queue`), { recursive: true }); await writeFile( stateFile, JSON.stringify({ diff --git a/editor/e2e/rate-limit.spec.ts b/editor/e2e/rate-limit.spec.ts @@ -6,6 +6,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -26,13 +27,13 @@ import { baseUrl } from "./baseUrl"; type Leaf = { id: string; match: { type: string; value?: string } }; type Group = { id: string; mode: string; children: (Group | Leaf)[] }; -const STATE_FILE = "test-transcripts/.auto-queue/state.json"; +const STATE_FILE = `${testPaths().transcriptsDir}/.auto-queue/state.json`; const TOKEN = "test-worker-token"; const AUTH = { authorization: `Bearer ${TOKEN}` }; // Copied from pacing.spec.ts: a YouTube channel with undownloaded videos. async function makeDownloadChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(`${root}/data`, { recursive: true }); await writeFile( `${root}/config.json`, @@ -99,7 +100,7 @@ async function setup( }, }); if (seed) { - await mkdir(resolvePath("test-transcripts/.auto-queue"), { recursive: true }); + await mkdir(resolvePath(`${testPaths().transcriptsDir}/.auto-queue`), { recursive: true }); await writeFile( resolvePath(STATE_FILE), JSON.stringify({ @@ -178,7 +179,7 @@ test("a subtitle 429 downloads the media, defers only the subtitles, and backs n expect(d?.subtitleDeferrals?.dl429sub1?.channelSlug).toBe("alpha"); // The media is on disk, no subtitles, and the outcome is a success that says why. - const dir = "test-transcripts/channels/alpha/data/dl429sub1"; + const dir = `${testPaths().transcriptsDir}/channels/alpha/data/dl429sub1`; expect(await pathExists(`${dir}/audio.mp3`)).toBe(true); expect(await pathExists(`${dir}/transcript.en.vtt`)).toBe(false); const outcome = await readJson<{ status: string; failureClass?: string }>( @@ -294,7 +295,7 @@ test("a probe that comes back clean clears the hold and the backoff", async ({ ) .toEqual({ held: false, backoff: false }); expect((await getStatus(request)).download.picks.map((p) => p.videoId)).toEqual(["a1"]); - expect(await pathExists("test-transcripts/channels/alpha/data/a1/transcript.en.vtt")).toBe( + expect(await pathExists(`${testPaths().transcriptsDir}/channels/alpha/data/a1/transcript.en.vtt`)).toBe( true, ); }); diff --git a/editor/e2e/reconcile.spec.ts b/editor/e2e/reconcile.spec.ts @@ -1,6 +1,6 @@ import { mkdir, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { pathExists, resetData, resolvePath, generateReport } from "./helpers"; +import { pathExists, resetData, resolvePath, generateReport, testPaths } from "./helpers"; // yt-dlp names Twitch VOD dirs `v<id>` (its extractor id) while the app keys // videos by the canonical URL id `<id>`, so the audio/metadata land in @@ -13,7 +13,7 @@ import { pathExists, resetData, resolvePath, generateReport } from "./helpers"; // subject here was always reconcileVideoDirs, not what happened to invoke it. const CHANNEL = "twitch-reconcile"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; async function write(rel: string, contents: string): Promise<void> { const full = resolvePath(`${ROOT}/${rel}`); diff --git a/editor/e2e/reconstruct-download-url.spec.ts b/editor/e2e/reconstruct-download-url.spec.ts @@ -6,10 +6,10 @@ import { readFile, rm } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { pathExists, resetData, resolvePath } from "./helpers"; +import { pathExists, resetData, resolvePath, testPaths } from "./helpers"; const CHANNEL = "test-transcribe"; -const CHANNEL_ROOT = `test-transcripts/channels/${CHANNEL}`; +const CHANNEL_ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; test("download pipeline reconstructs the URL when metadata + playlist are missing", async ({ page, diff --git a/editor/e2e/regional-vtt-fallback.spec.ts b/editor/e2e/regional-vtt-fallback.spec.ts @@ -6,6 +6,7 @@ import { resetData, resolvePath, writeSite, + testPaths, } from "./helpers"; const CHANNEL = "test-youtube"; @@ -14,8 +15,8 @@ const VIDEO_DIR = "20240101_test1234567"; // keeps equal to its directory name (see that file — a mismatch made snapshot // generation rename the directory mid-spec). const VIDEO_ID = VIDEO_DIR; -const DATA = `test-transcripts/channels/${CHANNEL}/data/${VIDEO_DIR}`; -const TRANSCRIPTS_PAGE = `test-transcripts/.export-index/shared/transcripts/${CHANNEL}/page-0000.json`; +const DATA = `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${VIDEO_DIR}`; +const TRANSCRIPTS_PAGE = `${testPaths().transcriptsDir}/.export-index/shared/transcripts/${CHANNEL}/page-0000.json`; // parseVtt only emits cues from lines carrying YouTube's inline word-timing // tags, so the body needs <hh:mm:ss.mmm> markers to produce a real cue. const VTT = diff --git a/editor/e2e/retry-bucket.spec.ts b/editor/e2e/retry-bucket.spec.ts @@ -7,6 +7,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "availability-test"; @@ -27,7 +28,7 @@ async function writeAvailability( opts: { error?: string } = {}, ) { const path = resolvePath( - `test-transcripts/channels/${CHANNEL}/data/${id}/availability.json`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/${id}/availability.json`, ); await mkdir(dirname(path), { recursive: true }); const record = { @@ -91,7 +92,7 @@ test("clicking retry on needs_auth re-downloads the listed video", async ({ await writeAvailability("vidneedsauth1", "needs_auth"); // retry-bucket reads the channel playlist file to know which URL to fetch. await writeFile( - resolvePath(`test-transcripts/channels/${CHANNEL}/playlist`), + resolvePath(`${testPaths().transcriptsDir}/channels/${CHANNEL}/playlist`), "https://www.youtube.com/watch?v=vidneedsauth1\n", ); @@ -113,7 +114,7 @@ test("clicking retry on needs_auth re-downloads the listed video", async ({ expect( await pathExists( - `test-transcripts/channels/${CHANNEL}/data/vidneedsauth1/transcript.en.vtt`, + `${testPaths().transcriptsDir}/channels/${CHANNEL}/data/vidneedsauth1/transcript.en.vtt`, ), ).toBe(true); }); diff --git a/editor/e2e/review.spec.ts b/editor/e2e/review.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readJson, resetData, writeSettings } from "./helpers"; +import { readJson, resetData, writeSettings, testPaths } from "./helpers"; // /review is the page for the findings a PERSON decides about: duplicate // clusters and media-integrity findings. Both are flag-only and both carry a @@ -97,7 +97,7 @@ test("an auto-paused channel is listed with its reason", async ({ page }) => { channelPriority?: { channels: Record<string, { tier?: string; autoPaused?: unknown }>; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); return s.channelPriority?.channels["test-youtube"]; }, { timeout: 20_000 }, @@ -107,7 +107,7 @@ test("an auto-paused channel is listed with its reason", async ({ page }) => { channelPriority?: { channels: Record<string, { autoPaused?: unknown }>; }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect( after.channelPriority?.channels["test-youtube"]?.autoPaused, ).toBe(undefined); diff --git a/editor/e2e/rumble-sweep.spec.ts b/editor/e2e/rumble-sweep.spec.ts @@ -7,6 +7,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; // Release 5 slice R. A Rumble channel's full sweep that hits HTTP 429 part-way @@ -25,7 +26,7 @@ import { const CHANNEL = "availability-test"; const FIXTURE = "availability-baseline"; -const channelRoot = `test-transcripts/channels/${CHANNEL}`; +const channelRoot = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const RUMBLE_URL = "https://rumble.com/c/sweep429"; const ALL_IDS = [ @@ -144,7 +145,7 @@ test("a Rumble sweep that 429s mid-listing is incomplete: paged walk, cooldown, // The rumble cooldown is recorded where the Sync gate and the runner read it. const state = await readJson<AutoQueueStateFile>( - "test-transcripts/.auto-queue/state.json", + `${testPaths().transcriptsDir}/.auto-queue/state.json`, ); expect(state.download.platformBackoff.rumble?.until).toBeGreaterThan( Date.now(), diff --git a/editor/e2e/saved-videos.spec.ts b/editor/e2e/saved-videos.spec.ts @@ -6,6 +6,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -21,7 +22,7 @@ async function seedSavedVideo( sha256?: string, ): Promise<void> { const storeDir = resolvePath( - `test-transcripts/saved-videos/${SLUG}/${videoId}`, + `${testPaths().transcriptsDir}/saved-videos/${SLUG}/${videoId}`, ); await mkdir(storeDir, { recursive: true }); await writeFile(`${storeDir}/source-media.mp4`, "x".repeat(bytes)); @@ -34,7 +35,7 @@ async function seedSavedVideo( ...(sha256 ? { sha256 } : {}), }; await writeFile( - resolvePath(`test-transcripts/channels/${SLUG}/data/${videoId}/saved-video.json`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/saved-video.json`), JSON.stringify(pointer, null, 2) + "\n", ); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); @@ -74,7 +75,7 @@ test("Saved Videos page saves the backup configuration", async ({ page }) => { // The setting persisted to test-settings.json. const settings = await readJson<{ savedVideoBackup?: { dest?: string; enabled?: boolean }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(settings.savedVideoBackup?.dest).toBe("/tmp/ttb-e2e-backup-dest"); expect(settings.savedVideoBackup?.enabled).toBe(true); @@ -134,7 +135,7 @@ test("the persist run's log survives the refresh that lands the pointer", async // redownloadToArchiveAction resolves the source URL from metadata.info.json // or the playlist, and this fixture ships neither. await writeFile( - resolvePath(`test-transcripts/channels/${SLUG}/playlist`), + resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/playlist`), "https://www.youtube.com/watch?v=vidA\n", ); await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); diff --git a/editor/e2e/scheduler.spec.ts b/editor/e2e/scheduler.spec.ts @@ -1,7 +1,7 @@ import { test, expect } from "@playwright/test"; import { writeFile } from "node:fs/promises"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; -import { readJson, resetData, resolvePath, writeSettings } from "./helpers"; +import { readJson, resetData, resolvePath, writeSettings, testPaths } from "./helpers"; // End-to-end coverage for the cron-driven sync scheduler. Uses the two-slow // channels (their mock sync hangs long enough to stay "running"), drives the @@ -12,8 +12,8 @@ import { readJson, resetData, resolvePath, writeSettings } from "./helpers"; // already-running dedup — plus the sync operation's console at // /operations/sync (the page that was /scheduler before sync was catalogued). -const SLOW_A_CONFIG = "test-transcripts/channels/slow-a/config.json"; -const SLOW_B_CONFIG = "test-transcripts/channels/slow-b/config.json"; +const SLOW_A_CONFIG = `${testPaths().transcriptsDir}/channels/slow-a/config.json`; +const SLOW_B_CONFIG = `${testPaths().transcriptsDir}/channels/slow-b/config.json`; async function writeChannelConfig(rel: string, config: ChannelConfig) { await writeFile(resolvePath(rel), JSON.stringify(config, null, 2)); @@ -298,7 +298,7 @@ test("schedule page edits the global controls", async ({ page }) => { const settings = await readJson<{ syncScheduler: { enabled: boolean; defaultIntervalMinutes: number }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(settings.syncScheduler.enabled).toBe(true); expect(settings.syncScheduler.defaultIntervalMinutes).toBe(120); diff --git a/editor/e2e/serial.ts b/editor/e2e/serial.ts @@ -0,0 +1,38 @@ +// THE @serial SPECS (plans/e2e-speed.md S5): with more than one worker these +// run in a project of their own, AFTER the parallel one (its `teardown`, which +// Playwright runs even when a parallel test failed), on one worker. With one +// worker there is one project and this list changes nothing. +// +// Two reasons put a file here, and only these: +// - it writes into the CHECKOUT, not its slot's data root: a site's or the +// hub's build stage makes `export/out` (EXPORT_NEXT_BIN's fake copies the +// composed bundle there), a homepage build `homepage/out` — one each for +// every slot; +// - it times wall-clock behaviour that contention bends (a cooldown, a +// pacing gap, an audio check's interval), or was a load flake in a gate +// run (release 19/20 records: storage-locations, sites-crud, whisper). +// The first full runs at 2 and 3 workers decide what else belongs; a file that +// passes alone and fails beside others joins with its reason. +export const SERIAL_SPECS: readonly string[] = [ + // the checkout's build outputs + "build.spec.ts", + "deploy-page.spec.ts", + "publish.spec.ts", + "publish-lane.spec.ts", + "site-publish-preview.spec.ts", + "sites-crud.spec.ts", + "sites-homepage.spec.ts", + // timing under contention + "pacing.spec.ts", + "rate-limit.spec.ts", + "audio-check-scenarios.spec.ts", + "fetch-window.spec.ts", + "channel-storage.spec.ts", + "storage-locations.spec.ts", + "whisper.spec.ts", +]; + +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +/** Matches a serial spec file's path (Playwright's testMatch/testIgnore). */ +export const SERIAL_SPEC_PATTERN = new RegExp(`(^|/)(${SERIAL_SPECS.map(escape).join("|")})$`); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -0,0 +1,369 @@ +// A SERVER SET PER WORKER (plans/e2e-speed.md S5). +// +// The suite ran on one worker because its shared state lives in ONE Next server +// (the job registry, worker pool, scheduler, auto-runner and auto-queue state +// are globalThis singletons there) over one data root. A directory per worker +// cannot fix the singletons; a server per worker does. So each worker slot gets +// its own set — the editor test server, the export dev server it links to, and +// the Ollama stub — over its own data root (testPaths.ts): +// +// slot 0 the config's webServer entries, on the suite's own ports (PORT, +// EXPORT_PORT, OLLAMA_STUB_PORT), over the editor directory — the +// one-worker suite, unchanged +// slot n started by globalSetup on `slotPorts(n)`, over +// `.e2e-workers/w<n>`, stopped by globalTeardown +// +// The worker finds its own: Playwright evaluates the config again in every +// worker with TEST_PARALLEL_INDEX already set, so `baseURL`, +// PLAYWRIGHT_BASE_URL, EXPORT_PORT and testPaths() are the slot's before any +// spec is loaded. Specs change nothing. +// +// How many workers: E2E_WORKERS — a number (1–8), or `auto` for what memory +// allows at start, floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB) capped +// at 3. Unset: 1, until the full runs at 1, 2 and 3 workers say the suite is +// green in parallel (then the default becomes `auto`). + +import { spawn, execFileSync, type ChildProcess } from "node:child_process"; +import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs"; +import net from "node:net"; +import { join } from "node:path"; +import { PORT_BASES, portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { EDITOR_ROOT, slotRoot, testPathsFor } from "./testPaths"; + +// THE TEST-ONLY SERVER ENVIRONMENT (the config's header documents each key). +export const E2E_SERVER_ENV: Record<string, string> = { + E2E_TEST_ROUTES: "1", + E2E_AUDIO_CHECK_INTERVAL_MS: "300", + E2E_AUDIO_CHECK_SIZE_GATE: "4096", + E2E_AUDIO_CHECK_INTERVAL_FLOOR_MS: "50", + E2E_AUDIO_CHECK_RECOVER_STEP_MS: "100", + E2E_AUDIO_CHECK_RECOVER_AFTER: "2", + E2E_BACKOFF_BASE_MS: "20000", + E2E_CLIP_WINDOW_GAP_MS: "2000", + E2E_LIVE_CHECK: "skip", + WRANGLER_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-wrangler.mjs"), + ARCHILYZER_BRANCH: "main", + CLOUDFLARE_API_TOKEN: "e2e-fake-token-never-sent", + EXPORT_NEXT_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-next.mjs"), +}; + +/** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */ +export const E2E_DIST_DIR = ".next/e2e"; +const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites"); +const DEFAULT_SETTINGS = join(EDITOR_ROOT, "e2e", "fixtures", "test-settings.default.json"); + +export type E2EMode = "start" | "dev"; +/** An environment to read (process.env, or a test's plain object). */ +export type Env = Readonly<Record<string, string | undefined>>; + +export function resolveE2EMode(env: Env = process.env): E2EMode { + const raw = (env.E2E_MODE ?? "").trim().toLowerCase(); + if (raw === "" || raw === "start") return "start"; + if (raw === "dev") return "dev"; + throw new Error(`E2E_MODE=${env.E2E_MODE} is not a mode: use start (the default) or dev`); +} + +// ------------------------------------------------------------------ workers + +export const AUTO_WORKER_CAP = 3; +export const MAX_WORKERS = 8; +export const WORKER_ESTIMATE_MB = 1500; + +function memAvailableMb(): number | null { + try { + const m = /^MemAvailable:\s+(\d+)\s*kB/m.exec(readFileSync("/proc/meminfo", "utf8")); + return m ? Math.floor(Number(m[1]) / 1024) : null; + } catch { + return null; + } +} + +/** + * How many workers (= server sets) this run uses. `E2E_WORKERS`: a number, or + * `auto` — floor((MemAvailable − floor) / 1.5 GB), 1 to 3. Unset: 1. + */ +export function resolveWorkers( + env: Env = process.env, + readAvailable: () => number | null = memAvailableMb, +): number { + const raw = (env.E2E_WORKERS ?? "").trim().toLowerCase(); + if (raw === "" || raw === "1") return 1; + if (raw === "auto") { + const avail = readAvailable(); + const floorRaw = Number(env.HEAVY_MIN_FREE_MB); + const floor = env.HEAVY_MIN_FREE_MB != null && env.HEAVY_MIN_FREE_MB !== "" && floorRaw >= 0 ? floorRaw : 6000; + if (avail == null) return 1; + return Math.max(1, Math.min(AUTO_WORKER_CAP, Math.floor((avail - floor) / WORKER_ESTIMATE_MB))); + } + const n = Number(raw); + if (!Number.isInteger(n) || n < 1) throw new Error(`E2E_WORKERS=${env.E2E_WORKERS}: a number of workers, or auto`); + return Math.min(MAX_WORKERS, n); +} + +// ------------------------------------------------------- a focused run + +// Options of `playwright test` that take a value (1.59, `playwright test --help`). +const VALUE_OPTIONS = new Set([ + "--browser", "-c", "--config", "--global-timeout", "-j", "--workers", "--max-failures", "--output", + "--repeat-each", "--reporter", "--retries", "--run-agents", "--timeout", "--trace", "--tsconfig", + "--ui-host", "--ui-port", "--update-source-method", +]); +// …that narrow WHICH tests run (with or without a value). +const FILTER_OPTIONS = new Set([ + "-g", "--grep", "--grep-invert", "--project", "--last-failed", "--only-changed", "--shard", + "--test-list", "--test-list-invert", +]); +// …whose value is optional, given only as one of these words. +const OPTIONAL_VALUES: Record<string, ReadonlySet<string>> = { + "--debug": new Set(["inspector", "cli"]), + "-u": new Set(["all", "changed", "missing", "none"]), + "--update-snapshots": new Set(["all", "changed", "missing", "none"]), +}; + +/** + * Whether this `playwright test` command line narrows the run — a spec file or + * a filter. Playwright applies those to TOP-LEVEL projects only: a `teardown` + * project runs whole, so a focused run must not make the serial project one + * (`pnpm e2e pacing.spec.ts` would run every @serial file). Unsure means + * focused, which only gives up the ordering. + */ +export function isFocusedRun(argv: readonly string[] = process.argv): boolean { + const at = argv.indexOf("test"); + if (at < 0) return true; + for (let i = at + 1; i < argv.length; i++) { + const arg = argv[i]; + const name = arg.startsWith("-") ? arg.split("=")[0] : null; + if (name == null) return true; // a positional: a spec filter + if (FILTER_OPTIONS.has(name)) return true; + if (arg.includes("=")) continue; + if (VALUE_OPTIONS.has(name)) i++; + else if (OPTIONAL_VALUES[name]?.has(argv[i + 1] ?? "")) i++; + } + return false; +} + +// -------------------------------------------------------------------- ports + +export type SlotPorts = { editor: number; export: number; ollama: number }; + +// The Fetch standard's "bad ports" at or above 3000: a browser refuses them, +// and so does `next start` ("Bad port: "5060" is reserved for sip"). Worktree +// #20's block (50xx) has two of them where slot 1 would sit. +export const UNSAFE_PORTS: ReadonlySet<number> = new Set([ + 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080, +]); + +/** + * A slot's three ports. Slot 0 is the suite's own (common/lib/ports.mjs, with + * the worktree's offset). Slot n takes the next three from the unused top of + * the worktree's block — from `x060` up, skipping a bad port — so no other + * worktree's ports, and no other suite's, are ever touched. + */ +export function slotPorts(slot: number, env: Env = process.env): SlotPorts { + if (slot <= 0) { + return { + editor: portFor("PORT", env), + export: portFor("EXPORT_PORT", env), + ollama: portFor("OLLAMA_STUB_PORT", env), + }; + } + const offset = portFor("PORT", env) - PORT_BASES.PORT; + const usable: number[] = []; + for (let p = PORT_BASES.PORT + 49 + offset; usable.length < 3 * slot; p++) { + if (!UNSAFE_PORTS.has(p)) usable.push(p); + } + const [editor, exportPort, ollama] = usable.slice(3 * (slot - 1)); + return { editor, export: exportPort, ollama }; +} + +// ------------------------------------------------------------------ servers + +export type ServerSpec = { + name: "editor" | "export" | "ollama"; + /** A shell command line, run in EDITOR_ROOT. */ + command: string; + env: Record<string, string>; + /** Ready once this answers. */ + url: string; +}; + +/** The three servers of a slot — the one definition the config and globalSetup share. */ +export function slotServers(slot: number, mode: E2EMode, env: Env = process.env): ServerSpec[] { + const ports = slotPorts(slot, env); + const paths = testPathsFor(slotRoot(slot)); + const editorEnv: Record<string, string> = { ...E2E_SERVER_ENV }; + // A start-mode server runs the stamped build (shared, read-only); a second + // `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`). + if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR; + else if (mode === "dev" && slot > 0) editorEnv.E2E_NEXT_DIST_DIR = `.next/e2e-dev-w${slot}`; + if (slot > 0) { + Object.assign(editorEnv, { + PORT: String(ports.editor), + EXPORT_PORT: String(ports.export), + OLLAMA_STUB_PORT: String(ports.ollama), + E2E_DATA_ROOT: paths.root, + }); + } + return [ + { + name: "editor", + command: mode === "start" ? "pnpm start:test" : "pnpm dev:test", + env: editorEnv, + url: `http://localhost:${ports.editor}`, + }, + { + // The export server stays `next dev` in both modes (a static export + // bakes test-settings.json in at build time; see the config). Its own + // dist dir per slot: Next allows one `next dev` per dist dir, and the + // export suite's server may be running beside this suite. + name: "export", + command: `pnpm --filter export run dev --port ${ports.export}`, + env: { + SETTINGS_FILE: paths.settingsFile, + SITES_DIR: EXPORT_SITES_DIR, + SITE_ID: "testsite", + E2E_NEXT_DIST_DIR: slot > 0 ? `.next/e2e-editor-w${slot}` : ".next/e2e-editor", + }, + url: `http://localhost:${ports.export}`, + }, + { + name: "ollama", + command: `node ${join(EDITOR_ROOT, "e2e", "fixtures", "ollama-stub.mjs")}`, + env: { OLLAMA_STUB_PORT: String(ports.ollama) }, + // /api/tags is the endpoint digestApps.ts probes, so readiness and the + // app's reachability check agree. + url: `http://127.0.0.1:${ports.ollama}/api/tags`, + }, + ]; +} + +// ------------------------------------------------- slot servers (globalSetup) + +export type SlotHandle = { slot: number; stop: () => Promise<void> }; + +function portBusy(port: number): Promise<boolean> { + return new Promise((resolve) => { + const server = net.createServer(); + server.once("error", (err: NodeJS.ErrnoException) => resolve(err.code === "EADDRINUSE")); + server.listen({ port, host: "0.0.0.0", exclusive: true }, () => server.close(() => resolve(false))); + }); +} + +function culprit(port: number): string { + try { + const out = execFileSync("ss", ["-ltnpH", `sport = :${port}`], { encoding: "utf8" }); + const pid = /pid=(\d+)/.exec(out)?.[1]; + return pid ? `pid ${pid} (kill ${pid})` : "owner unknown — ss -ltnp"; + } catch { + return "owner unknown — ss -ltnp"; + } +} + +async function waitUntilUp(url: string, child: ChildProcess, timeoutMs: number, log: string): Promise<void> { + const t0 = Date.now(); + for (;;) { + if (child.exitCode != null || child.signalCode != null) { + throw new Error(`e2e servers: ${url} exited before it answered (${child.exitCode ?? child.signalCode}); see ${log}`); + } + try { + const res = await fetch(url, { signal: AbortSignal.timeout(5_000) }); + await res.arrayBuffer().catch(() => {}); + return; + } catch { + /* not up yet */ + } + if (Date.now() - t0 > timeoutMs) throw new Error(`e2e servers: ${url} did not answer in ${timeoutMs / 1000}s; see ${log}`); + await new Promise((r) => setTimeout(r, 500)); + } +} + +function stopGroup(child: ChildProcess): Promise<void> { + return new Promise((resolve) => { + if (child.exitCode != null || child.signalCode != null || !child.pid) return resolve(); + const kill = (sig: NodeJS.Signals) => { + try { + process.kill(-child.pid!, sig); // the whole group: pnpm, next, its workers + } catch { + /* gone */ + } + }; + const hard = setTimeout(() => kill("SIGKILL"), 10_000); + child.once("exit", () => { + clearTimeout(hard); + resolve(); + }); + kill("SIGTERM"); + }); +} + +/** + * Start slot `slot`'s servers over its own data root and wait until each + * answers. Refuses (naming the pid) a port that is already bound: nothing + * else may answer as this slot's server. + */ +export async function startSlot(slot: number, mode: E2EMode, timeoutMs = 120_000): Promise<SlotHandle> { + const specs = slotServers(slot, mode); + const ports = slotPorts(slot); + for (const p of [ports.editor, ports.export, ports.ollama]) { + if (await portBusy(p)) { + throw new Error(`e2e servers: slot ${slot}'s port ${p} is already in use — ${culprit(p)}; a leftover from a killed run?`); + } + } + const paths = testPathsFor(slotRoot(slot)); + mkdirSync(join(paths.transcriptsDir, "channels"), { recursive: true }); + if (!existsSync(paths.settingsFile)) copyFileSync(DEFAULT_SETTINGS, paths.settingsFile); + const children: ChildProcess[] = []; + const stop = async () => { + await Promise.all(children.map(stopGroup)); + }; + try { + await Promise.all( + specs.map(async (s) => { + const log = join(paths.root, `server-${s.name}.log`); + const fd = openSync(log, "w"); + const child = spawn("sh", ["-c", s.command], { + cwd: EDITOR_ROOT, + env: { ...process.env, ...s.env }, + stdio: ["ignore", fd, fd], + detached: true, // its own process group, so stop() reaps the tree + }); + closeSync(fd); + children.push(child); + await waitUntilUp(s.url, child, timeoutMs, log); + }), + ); + } catch (err) { + await stop(); + throw err; + } + armWatchdog(children.flatMap((c) => (c.pid ? [c.pid] : []))); + return { slot, stop }; +} + +// A run killed outright (SIGKILL, an OOM) never reaches globalTeardown, and a +// slot's servers are process groups of their own — they would outlive it, and +// the next run would find their ports bound. So each slot gets a watchdog, as +// detached as its servers: it polls the runner and, once the runner is gone, +// takes the groups down (TERM, then KILL) and exits. It also exits once the +// groups are gone (a clean teardown). +const WATCHDOG = ` +const [runner, ...groups] = process.argv.slice(1).map(Number); +const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } }; +const kill = (sig) => { for (const g of groups) { try { process.kill(-g, sig); } catch {} } }; +const tick = setInterval(() => { + if (!groups.some((g) => alive(g))) process.exit(0); + if (alive(runner)) return; + clearInterval(tick); + kill("SIGTERM"); + setTimeout(() => { kill("SIGKILL"); process.exit(0); }, 5000); +}, 2000); +`; + +function armWatchdog(groups: number[]): void { + if (!groups.length) return; + const dog = spawn(process.execPath, ["-e", WATCHDOG, String(process.pid), ...groups.map(String)], { + stdio: "ignore", + detached: true, + }); + dog.unref(); +} diff --git a/editor/e2e/servers.unit.ts b/editor/e2e/servers.unit.ts @@ -0,0 +1,113 @@ +// Unit tests for the per-worker server sets (e2e/servers.ts), the data roots +// (e2e/testPaths.ts) and the @serial list (e2e/serial.ts). Named `.unit.ts` so +// Playwright's own testMatch never collects it; run by `pnpm --filter editor test`. +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; +import { SERIAL_SPECS, SERIAL_SPEC_PATTERN } from "./serial"; +import { isFocusedRun, resolveWorkers, slotPorts, slotServers } from "./servers"; +import { EDITOR_ROOT, slotRoot, testPaths } from "./testPaths"; + +test("resolveWorkers: 1 by default, a number capped at 8, auto from memory capped at 3", () => { + assert.equal(resolveWorkers({}), 1); + assert.equal(resolveWorkers({ E2E_WORKERS: "2" }), 2); + assert.equal(resolveWorkers({ E2E_WORKERS: "99" }), 8); + assert.throws(() => resolveWorkers({ E2E_WORKERS: "two" }), /a number of workers, or auto/); + const auto = (mb: number | null, env: Record<string, string> = {}) => + resolveWorkers({ E2E_WORKERS: "auto", ...env }, () => mb); + assert.equal(auto(12_000), 3); // (12000 − 6000) / 1500 = 4, capped + assert.equal(auto(9_100), 2); + assert.equal(auto(7_400), 1); + assert.equal(auto(3_000), 1); + assert.equal(auto(null), 1); + assert.equal(auto(9_100, { HEAVY_MIN_FREE_MB: "3000" }), 3); +}); + +test("slotPorts: slot 0 is the suite's own; slot n takes three from the top of the worktree's block", () => { + assert.deepEqual(slotPorts(0, {}), { editor: 3011, export: 3010, ollama: 11435 }); + assert.deepEqual(slotPorts(1, {}), { editor: 3060, export: 3061, ollama: 3062 }); + assert.deepEqual(slotPorts(2, {}), { editor: 3063, export: 3064, ollama: 3065 }); + // A worktree at offset 2000 (PORT=5011, the injector's): its own block. + const wt = { PORT: "5011", EXPORT_PORT: "5010", OLLAMA_STUB_PORT: "13435" }; + assert.deepEqual(slotPorts(0, wt), { editor: 5011, export: 5010, ollama: 13435 }); + // 5060 and 5061 are bad ports (SIP): `next start` refuses them. + assert.deepEqual(slotPorts(1, wt), { editor: 5062, export: 5063, ollama: 5064 }); + assert.deepEqual(slotPorts(3, wt), { editor: 5068, export: 5069, ollama: 5070 }); + // Eight slots stay inside the block of a hundred, past every bad port. + assert.ok(slotPorts(8, {}).ollama < 3100); + const wt66 = { PORT: "9611" }; // worktree #66: 6665–6669 are bad + for (let s = 1; s <= 8; s++) { + const p = slotPorts(s, { PORT: "6611" }); + assert.ok(![p.editor, p.export, p.ollama].some((n) => n >= 6665 && n <= 6669), `slot ${s}`); + assert.ok(p.ollama < 6700, `slot ${s} left the block`); + } + assert.ok(slotPorts(1, wt66).editor === 9660); +}); + +test("slotServers: slot 0 is the webServer of before; slot n is its own data root, ports and dist dirs", () => { + const [editor0, export0, ollama0] = slotServers(0, "start", {}); + assert.equal(editor0.command, "pnpm start:test"); + assert.equal(editor0.url, "http://localhost:3011"); + assert.equal(editor0.env.E2E_NEXT_DIST_DIR, ".next/e2e"); + assert.equal(editor0.env.E2E_DATA_ROOT, undefined); + assert.equal(editor0.env.PORT, undefined); + assert.equal(export0.env.SETTINGS_FILE, join(EDITOR_ROOT, "test-settings.json")); + assert.equal(export0.env.E2E_NEXT_DIST_DIR, ".next/e2e-editor"); + assert.equal(ollama0.url, "http://127.0.0.1:11435/api/tags"); + + const [editor2, export2, ollama2] = slotServers(2, "dev", {}); + assert.equal(editor2.command, "pnpm dev:test"); + assert.equal(editor2.env.E2E_DATA_ROOT, join(EDITOR_ROOT, ".e2e-workers", "w2")); + assert.equal(editor2.env.PORT, "3063"); + assert.equal(editor2.env.OLLAMA_STUB_PORT, "3065"); + assert.equal(editor2.env.E2E_NEXT_DIST_DIR, ".next/e2e-dev-w2"); + assert.equal(export2.command, "pnpm --filter export run dev --port 3064"); + assert.equal(export2.env.SETTINGS_FILE, join(EDITOR_ROOT, ".e2e-workers", "w2", "test-settings.json")); + assert.equal(export2.env.E2E_NEXT_DIST_DIR, ".next/e2e-editor-w2"); + assert.equal(ollama2.env.OLLAMA_STUB_PORT, "3065"); + // A start-mode slot serves the one stamped build. + assert.equal(slotServers(2, "start", {})[0].env.E2E_NEXT_DIST_DIR, ".next/e2e"); +}); + +test("testPaths: the editor directory for slot 0, the slot's own root for a worker, E2E_DATA_ROOT over both", () => { + const saved = { idx: process.env.TEST_PARALLEL_INDEX, root: process.env.E2E_DATA_ROOT }; + try { + delete process.env.E2E_DATA_ROOT; + delete process.env.TEST_PARALLEL_INDEX; + assert.equal(testPaths().transcriptsDir, join(EDITOR_ROOT, "test-transcripts")); + process.env.TEST_PARALLEL_INDEX = "0"; + assert.equal(testPaths().settingsFile, join(EDITOR_ROOT, "test-settings.json")); + process.env.TEST_PARALLEL_INDEX = "2"; + assert.equal(testPaths().root, slotRoot(2)); + assert.equal(testPaths().transcriptsDir, join(EDITOR_ROOT, ".e2e-workers", "w2", "test-transcripts")); + process.env.E2E_DATA_ROOT = "/somewhere/else"; + assert.equal(testPaths().settingsFile, "/somewhere/else/test-settings.json"); + } finally { + if (saved.idx == null) delete process.env.TEST_PARALLEL_INDEX; + else process.env.TEST_PARALLEL_INDEX = saved.idx; + if (saved.root == null) delete process.env.E2E_DATA_ROOT; + else process.env.E2E_DATA_ROOT = saved.root; + } +}); + +test("the @serial list names spec files that exist, and matches whole names only", () => { + for (const f of SERIAL_SPECS) assert.ok(existsSync(join(EDITOR_ROOT, "e2e", f)), f); + assert.ok(SERIAL_SPEC_PATTERN.test("/x/editor/e2e/pacing.spec.ts")); + assert.ok(!SERIAL_SPEC_PATTERN.test("/x/editor/e2e/my-pacing.spec.ts")); + assert.ok(!SERIAL_SPEC_PATTERN.test("/x/editor/e2e/build.spec.tsx")); +}); + +test("isFocusedRun: a spec file or a filter narrows the run; options with values do not", () => { + const pw = (...args: string[]) => ["node", "/x/playwright/cli.js", "test", ...args]; + assert.equal(isFocusedRun(pw()), false); + assert.equal(isFocusedRun(pw("--workers", "2", "--reporter", "list", "--retries=1")), false); + assert.equal(isFocusedRun(pw("-u", "all", "--debug", "--headed")), false); + assert.equal(isFocusedRun(pw("pacing.spec.ts")), true); + assert.equal(isFocusedRun(pw("--workers", "2", "pacing.spec.ts", "whisper.spec.ts")), true); + assert.equal(isFocusedRun(pw("-g", "lane")), true); + assert.equal(isFocusedRun(pw("--grep=lane")), true); + assert.equal(isFocusedRun(pw("--last-failed")), true); + assert.equal(isFocusedRun(pw("--project", "serial")), true); + assert.equal(isFocusedRun(["node", "something-else"]), true); // unsure: focused +}); diff --git a/editor/e2e/settings.spec.ts b/editor/e2e/settings.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readJson, resetData } from "./helpers"; +import { readJson, resetData, testPaths } from "./helpers"; test.beforeEach(async () => { await resetData("empty"); @@ -24,7 +24,7 @@ test("saves settings via the form", async ({ page }) => { adminTitle: string; siteTitle?: string; groups?: unknown; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.adminTitle).toBe("Cypress Admin"); // Operational-only: branding/groups must NOT round-trip into settings.json. expect(saved.siteTitle).toBeUndefined(); @@ -51,7 +51,7 @@ test("saves global default social links", async ({ page }) => { const saved = await readJson<{ socialLinks?: { label: string; url: string; svg: string; featured?: boolean }[]; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.socialLinks).toHaveLength(1); expect(saved.socialLinks?.[0].label).toBe("GitHub"); // "Keep in header on small screens" is stored as featured: true. @@ -85,7 +85,7 @@ test("saves build pipeline settings (concurrency, image), and has no mode", asyn const saved = await readJson<{ buildPipeline?: Record<string, unknown>; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.buildPipeline?.maxParallelBuilds).toBe(4); expect(saved.buildPipeline?.dockerImage).toBe("my-build-image"); expect(saved.buildPipeline && "mode" in saved.buildPipeline).toBe(false); diff --git a/editor/e2e/shard.spec.ts b/editor/e2e/shard.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; const AVAILABILITY_CHANNEL = "availability-test"; @@ -42,7 +43,7 @@ test.describe("Availability check sharding", () => { // 6 fixture videos sorted lex; shard 1 of 2 (0-based index 0) takes 3. const cfg = await readJson<ShardFile>( - `test-transcripts/channels/${AVAILABILITY_CHANNEL}/shard-availability.json`, + `${testPaths().transcriptsDir}/channels/${AVAILABILITY_CHANNEL}/shard-availability.json`, ); expect(cfg.totalShards).toBe(2); expect(cfg.shardIndex).toBe(0); @@ -60,7 +61,7 @@ test.describe("Availability check sharding", () => { ]) { if ( await pathExists( - `test-transcripts/channels/${AVAILABILITY_CHANNEL}/data/${id}/availability.json`, + `${testPaths().transcriptsDir}/channels/${AVAILABILITY_CHANNEL}/data/${id}/availability.json`, ) ) { written++; @@ -102,7 +103,7 @@ test.describe("Availability check sharding", () => { expect( await pathExists( - `test-transcripts/channels/${AVAILABILITY_CHANNEL}/shard-availability.json`, + `${testPaths().transcriptsDir}/channels/${AVAILABILITY_CHANNEL}/shard-availability.json`, ), ).toBe(true); @@ -117,7 +118,7 @@ test.describe("Availability check sharding", () => { ).toBeVisible({ timeout: 10_000 }); expect( await pathExists( - `test-transcripts/channels/${AVAILABILITY_CHANNEL}/shard-availability.json`, + `${testPaths().transcriptsDir}/channels/${AVAILABILITY_CHANNEL}/shard-availability.json`, ), ).toBe(false); }); @@ -154,7 +155,7 @@ test.describe("Transcribe missing sharding", () => { await expect(log).toContainText("succeeded", { timeout: 30_000 }); const cfg = await readJson<ShardFile>( - "test-transcripts/channels/test-transcribe/shard-transcribe-missing.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/shard-transcribe-missing.json`, ); expect(cfg.totalShards).toBe(2); expect(cfg.shardIndex).toBe(1); @@ -172,7 +173,7 @@ test.describe("Transcribe missing sharding", () => { for (const id of ["vidA", "vidB", "vidC"]) { if ( await pathExists( - `test-transcripts/channels/test-transcribe/data/${id}/transcript.json`, + `${testPaths().transcriptsDir}/channels/test-transcribe/data/${id}/transcript.json`, ) ) { transcribed++; @@ -189,7 +190,7 @@ test.describe("Transcribe missing sharding", () => { // own 2 items (the remaining set), never 3 (the whole channel). await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/data/vidB/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidB/transcript.json`, ), JSON.stringify({ cues: [] }), ); @@ -204,7 +205,7 @@ test.describe("Transcribe missing sharding", () => { ).toBeVisible({ timeout: 10_000 }); const cfg = await readJson<ShardFile>( - "test-transcripts/channels/test-transcribe/shard-transcribe-missing.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/shard-transcribe-missing.json`, ); // The remaining set is {vidA, vidC} — vidB is already transcribed. expect(cfg.items).toHaveLength(2); @@ -232,7 +233,7 @@ test.describe("Save shard (no run)", () => { ).toBeVisible({ timeout: 10_000 }); const cfg = await readJson<ShardFile>( - "test-transcripts/channels/test-transcribe/shard-transcribe-missing.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/shard-transcribe-missing.json`, ); expect(cfg.totalShards).toBe(2); expect(cfg.shardIndex).toBe(1); @@ -244,7 +245,7 @@ test.describe("Save shard (no run)", () => { for (const id of ["vidA", "vidB", "vidC"]) { if ( await pathExists( - `test-transcripts/channels/test-transcribe/data/${id}/transcript.json`, + `${testPaths().transcriptsDir}/channels/test-transcribe/data/${id}/transcript.json`, ) ) { transcribed++; @@ -279,7 +280,7 @@ test.describe("Save shard (no run)", () => { for (const id of ["vidA", "vidB", "vidC"]) { if ( await pathExists( - `test-transcripts/channels/test-transcribe/data/${id}/transcript.json`, + `${testPaths().transcriptsDir}/channels/test-transcribe/data/${id}/transcript.json`, ) ) { transcribed++; @@ -290,7 +291,7 @@ test.describe("Save shard (no run)", () => { }); test.describe("Download missing sharding", () => { - const channelRoot = "test-transcripts/channels/test-transcribe"; + const channelRoot = `${testPaths().transcriptsDir}/channels/test-transcribe`; // Make all three videos missing (clear their audio) and set a 3-URL playlist. // The shard slices the *missing* set: vidA/vidB/vidC sorted, shard 1 of 2 diff --git a/editor/e2e/site-scope.spec.ts b/editor/e2e/site-scope.spec.ts @@ -1,7 +1,7 @@ import { test, expect, type Page } from "@playwright/test"; import { activeSiteCookieName } from "../app/lib/activeSite"; import { baseUrl } from "./baseUrl"; -import { readJson, resetData, writeSettings, writeSite } from "./helpers"; +import { readJson, resetData, writeSettings, writeSite, testPaths } from "./helpers"; type SiteFile = { channels: { slug: string }[] }; @@ -143,7 +143,7 @@ test("creating a channel under a site adds it to that site's membership", async await page.waitForURL("**/channels/gamma", { timeout: 10_000 }); const site = await readJson<SiteFile>( - "test-transcripts/sites/alpha/site.json", + `${testPaths().transcriptsDir}/sites/alpha/site.json`, ); expect(site.channels.map((c) => c.slug)).toContain("gamma"); diff --git a/editor/e2e/sites-crud.spec.ts b/editor/e2e/sites-crud.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { pathExists, readJson, resetData, writeSite } from "./helpers"; +import { pathExists, readJson, resetData, writeSite, testPaths } from "./helpers"; type SiteFile = { siteId: string; @@ -41,7 +41,7 @@ test("create a site with channel membership via the UI", async ({ page }) => { ).toBeVisible(); const site = await readJson<SiteFile>( - "test-transcripts/sites/jeralyzer/site.json", + `${testPaths().transcriptsDir}/sites/jeralyzer/site.json`, ); expect(site.siteTitle).toBe("Jeralyzer"); expect(site.channels.map((c) => c.slug)).toContain("test-youtube"); @@ -55,7 +55,7 @@ test("a cited-only channel saves to citedChannels, shows on the list, and Includ }) => { await resetData("one-youtube-channel-with-data"); type CitedSiteFile = SiteFile & { citedChannels?: { slug: string }[] }; - const file = "test-transcripts/sites/citing/site.json"; + const file = `${testPaths().transcriptsDir}/sites/citing/site.json`; const include = page.getByRole("checkbox", { name: /include test youtube channel/i }); const citedOnly = page.getByRole("checkbox", { name: "Cited only: Test YouTube Channel" }); const save = async (name: RegExp) => { @@ -117,7 +117,7 @@ test("list shows configured sites and edit updates branding", async ({ // persisted file until the rename completes rather than reading it once. await expect(async () => { const site = await readJson<SiteFile>( - "test-transcripts/sites/alpha/site.json", + `${testPaths().transcriptsDir}/sites/alpha/site.json`, ); expect(site.siteTitle).toBe("Alpha Renamed"); }).toPass({ timeout: 10_000 }); @@ -132,7 +132,7 @@ test("delete removes the site config", async ({ page }) => { await page.getByRole("button", { name: /delete/i }).click(); await expect(page.getByText("Doomed")).toHaveCount(0); - expect(await pathExists("test-transcripts/sites/doomed/site.json")).toBe( + expect(await pathExists(`${testPaths().transcriptsDir}/sites/doomed/site.json`)).toBe( false, ); }); @@ -153,7 +153,7 @@ test("new site inherits the global social links by default (no socialLinks key)" ).toBeVisible(); const site = await readJson<SocialSiteFile>( - "test-transcripts/sites/inheritsite/site.json", + `${testPaths().transcriptsDir}/sites/inheritsite/site.json`, ); // Inheriting = the key is absent so resolveSocialLinks falls back to global. expect("socialLinks" in site).toBe(false); @@ -180,7 +180,7 @@ test("unchecking inherit and adding a link writes the site's own socialLinks", a ).toBeVisible(); const site = await readJson<SocialSiteFile>( - "test-transcripts/sites/ownlinks/site.json", + `${testPaths().transcriptsDir}/sites/ownlinks/site.json`, ); expect(site.socialLinks).toHaveLength(1); expect(site.socialLinks?.[0].label).toBe("Mastodon"); @@ -204,7 +204,7 @@ test("unchecking inherit with no links writes an empty socialLinks override", as ).toBeVisible(); const site = await readJson<SocialSiteFile>( - "test-transcripts/sites/nolinks/site.json", + `${testPaths().transcriptsDir}/sites/nolinks/site.json`, ); // Explicit empty override = show no links even if a global default exists. expect(site.socialLinks).toEqual([]); @@ -253,7 +253,7 @@ test("public URL and a featured related-sites group round-trip to disk", async ( ).toBeVisible(); const site = await readJson<RelatedSiteFile>( - "test-transcripts/sites/beta/site.json", + `${testPaths().transcriptsDir}/sites/beta/site.json`, ); expect(site.siteUrl).toBe("https://beta.example"); expect(site.relatedSites).toEqual([ @@ -319,7 +319,7 @@ test("inline-chips flag round-trips; seeded default group has it on", async ({ // Poll: the "Saved" status and the on-disk write can land slightly apart. await expect(async () => { const site = await readJson<GroupsSiteFile>( - "test-transcripts/sites/chipsite/site.json", + `${testPaths().transcriptsDir}/sites/chipsite/site.json`, ); expect(site.groups[0].inline).toBe(true); // Flag-off groups serialize without the key at all. @@ -340,7 +340,7 @@ test("archives + per-video transcript downloads opt-outs round-trip", async ({ await writeSite("optout", { siteTitle: "Opt Out" }); type OptOutSiteFile = { archives?: boolean; transcriptDownloads?: boolean }; - const file = "test-transcripts/sites/optout/site.json"; + const file = `${testPaths().transcriptsDir}/sites/optout/site.json`; const archives = page.getByRole("checkbox", { name: /generate downloadable archive zips/i, }); @@ -395,7 +395,7 @@ test("the search switch round-trips; a legacy publish: cited reads as off and sa await writeSite("reportonly", { siteTitle: "Report Only", publish: "cited" }); type SearchSiteFile = { search?: boolean; publish?: string }; - const file = "test-transcripts/sites/reportonly/site.json"; + const file = `${testPaths().transcriptsDir}/sites/reportonly/site.json`; const search = page.getByRole("checkbox", { name: "Search", exact: true }); const save = async () => { await page.getByRole("button", { name: /save site/i }).click(); @@ -444,7 +444,7 @@ test("the listed opt-out round-trips, and a save of another field keeps it", asy }); type ListedSiteFile = { siteTitle?: string; listed?: boolean }; - const file = "test-transcripts/sites/fixture-unlisted/site.json"; + const file = `${testPaths().transcriptsDir}/sites/fixture-unlisted/site.json`; const listed = page.getByRole("checkbox", { name: "List on the Archilyzer homepage and hub", }); @@ -493,7 +493,7 @@ test("the hub form's per-video transcript downloads opt-out round-trips to homep }) => { await resetData("empty"); type HomepageFile = { siteTitle?: string; transcriptDownloads?: boolean }; - const file = "test-transcripts/sites/_homepage/homepage.json"; + const file = `${testPaths().transcriptsDir}/sites/_homepage/homepage.json`; // The hub form is the one on /sites whose submit is "Save config". const form = page .locator("form") @@ -551,7 +551,7 @@ test("brand accent radio group + wordmark lead round-trip to site.json", async ( await writeSite("brandy", { siteTitle: "Brandyalyzer" }); type BrandSiteFile = { accent?: string; wordmarkLead?: string }; - const file = "test-transcripts/sites/brandy/site.json"; + const file = `${testPaths().transcriptsDir}/sites/brandy/site.json`; const accents = page.getByRole("group", { name: "Brand accent" }); const radio = (name: string | RegExp) => accents.getByRole("radio", { name, exact: typeof name === "string" }); @@ -636,7 +636,7 @@ test("a private site saves its audience, and every deploy refuses it before any await expect(page.getByRole("status").filter({ hasText: "Saved" })).toBeVisible(); await expect(async () => { const site = await readJson<{ audience?: string; cloudflareProject?: string }>( - "test-transcripts/sites/privsite/site.json", + `${testPaths().transcriptsDir}/sites/privsite/site.json`, ); expect(site.audience).toBe("private"); expect(site.cloudflareProject).toBe("never-real"); @@ -659,7 +659,7 @@ test("a private site saves its audience, and every deploy refuses it before any await audience.selectOption("public"); await page.getByRole("button", { name: /save site/i }).click(); await expect(async () => { - const site = await readJson<Record<string, unknown>>("test-transcripts/sites/privsite/site.json"); + const site = await readJson<Record<string, unknown>>(`${testPaths().transcriptsDir}/sites/privsite/site.json`); expect("audience" in site).toBe(false); }).toPass({ timeout: 10_000 }); }); diff --git a/editor/e2e/sites-homepage.spec.ts b/editor/e2e/sites-homepage.spec.ts @@ -28,6 +28,7 @@ import { resolvePath, writeSettings, writeSite, + testPaths, } from "./helpers"; const group = (page: Page) => @@ -63,11 +64,11 @@ type Meta = { async function metasOfKind(kind: string): Promise<Meta[]> { const files = ( - await readdir(resolvePath("test-transcripts/.jobs")).catch(() => []) + await readdir(resolvePath(`${testPaths().transcriptsDir}/.jobs`)).catch(() => []) ).filter((f) => f.endsWith(".meta.json")); const metas: Meta[] = []; for (const f of files) { - const meta = await readJson<Meta>(`test-transcripts/.jobs/${f}`).catch( + const meta = await readJson<Meta>(`${testPaths().transcriptsDir}/.jobs/${f}`).catch( () => null, ); if (meta?.kind === kind) metas.push(meta); @@ -204,7 +205,7 @@ test("Build homepage enqueues the index update, then build-homepage, on the publ const log = (await res.json()) as { status: string; content: string }; expect(log.status).toBe("cancelled"); expect(log.content).toBe(""); - expect(await pathExists(`test-transcripts/.jobs/${job.id}.log`)).toBe(false); + expect(await pathExists(`${testPaths().transcriptsDir}/.jobs/${job.id}.log`)).toBe(false); // …and its sidecar says so too (release 13 slice W1). A job cancelled while // queued used to keep the "queued" its enqueue wrote: the cancel path never // rewrote the meta, so a restart's boot pass could re-queue a job the diff --git a/editor/e2e/skip-live.spec.ts b/editor/e2e/skip-live.spec.ts @@ -10,11 +10,12 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; const CHANNEL = "test-live"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const here = path.dirname(fileURLToPath(import.meta.url)); type DownloadOutcome = { diff --git a/editor/e2e/social-channel.spec.ts b/editor/e2e/social-channel.spec.ts @@ -10,7 +10,7 @@ import { test, expect } from "@playwright/test"; import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { resetData, readJson, pathExists, resolvePath, generateReport } from "./helpers"; +import { resetData, readJson, pathExists, resolvePath, generateReport, testPaths } from "./helpers"; import { THREAD_URL as FORUM_THREAD_URL, threadPage, @@ -102,9 +102,9 @@ test("creating a social channel round-trips through parseChannelConfig", async ( await expect .poll( async () => - (await pathExists("test-transcripts/channels/faketester/config.json")) + (await pathExists(`${testPaths().transcriptsDir}/channels/faketester/config.json`)) ? await readJson<ChannelConfig>( - "test-transcripts/channels/faketester/config.json", + `${testPaths().transcriptsDir}/channels/faketester/config.json`, ) : null, { timeout: 15_000 }, @@ -135,10 +135,10 @@ test("fetch-posts writes month-sharded JSONL + a posts-archive, and re-running i await expect .poll( async () => - (await pathExists("test-transcripts/channels/faketester/posts-archive")) + (await pathExists(`${testPaths().transcriptsDir}/channels/faketester/posts-archive`)) ? ( await readFile( - resolvePath("test-transcripts/channels/faketester/posts-archive"), + resolvePath(`${testPaths().transcriptsDir}/channels/faketester/posts-archive`), "utf8", ) ) @@ -150,10 +150,10 @@ test("fetch-posts writes month-sharded JSONL + a posts-archive, and re-running i .toBe(3); const june = await readJsonl( - "test-transcripts/channels/faketester/posts/2026-06.jsonl", + `${testPaths().transcriptsDir}/channels/faketester/posts/2026-06.jsonl`, ); const may = await readJsonl( - "test-transcripts/channels/faketester/posts/2026-05.jsonl", + `${testPaths().transcriptsDir}/channels/faketester/posts/2026-05.jsonl`, ); expect(june).toHaveLength(2); expect(may).toHaveLength(1); @@ -179,11 +179,11 @@ test("fetch-posts writes month-sharded JSONL + a posts-archive, and re-running i .poll( async () => { const june2 = await readJsonl( - "test-transcripts/channels/faketester/posts/2026-06.jsonl", + `${testPaths().transcriptsDir}/channels/faketester/posts/2026-06.jsonl`, ); const archive = ( await readFile( - resolvePath("test-transcripts/channels/faketester/posts-archive"), + resolvePath(`${testPaths().transcriptsDir}/channels/faketester/posts-archive`), "utf8", ) ) @@ -219,7 +219,7 @@ test("a forum thread URL makes a forum-thread channel, and saved pages import in await page.locator('input[name="fetchPostsNow"]').uncheck(); await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); - const configPath = "test-transcripts/channels/the-teapot-collectors-thread/config.json"; + const configPath = `${testPaths().transcriptsDir}/channels/the-teapot-collectors-thread/config.json`; await expect .poll(async () => ((await pathExists(configPath)) ? await readJson<ChannelConfig>(configPath) : null), { timeout: 15_000, @@ -253,7 +253,7 @@ test("a forum thread URL makes a forum-thread channel, and saved pages import in await page.getByLabel("saved pages path").fill(saves); await page.getByRole("button", { name: "import saved pages" }).click(); - const archive = "test-transcripts/channels/the-teapot-collectors-thread/posts-archive"; + const archive = `${testPaths().transcriptsDir}/channels/the-teapot-collectors-thread/posts-archive`; await expect .poll( async () => diff --git a/editor/e2e/social-fetcher-picker.spec.ts b/editor/e2e/social-fetcher-picker.spec.ts @@ -3,12 +3,12 @@ // the channel page. import { test, expect } from "@playwright/test"; import { mkdir, writeFile } from "node:fs/promises"; -import { resetData, readJson, resolvePath } from "./helpers"; +import { resetData, readJson, resolvePath, testPaths } from "./helpers"; type Cfg = { postFetcher?: string; platform?: string }; async function makeSocialChannel(slug: string, platform: string, fetcher: string) { - const dir = resolvePath(`test-transcripts/channels/${slug}`); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(dir, { recursive: true }); await writeFile( `${dir}/config.json`, @@ -44,7 +44,7 @@ test("an X channel offers every X scraping method and switching persists", async // The choice is persisted to the channel config, not just local state. await expect - .poll(async () => (await readJson<Cfg>("test-transcripts/channels/x-chan/config.json")).postFetcher, + .poll(async () => (await readJson<Cfg>(`${testPaths().transcriptsDir}/channels/x-chan/config.json`)).postFetcher, { timeout: 10_000 }) .toBe("x-nitter"); diff --git a/editor/e2e/storage-locations.spec.ts b/editor/e2e/storage-locations.spec.ts @@ -18,6 +18,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; // STORAGE LOCATIONS: the page, and the one click that follows a disk. @@ -42,9 +43,9 @@ const SLUG = "test-youtube"; const VIDEO = "20240101_test1234567"; const UUID = "e2e-platter-uuid"; -const channelDir = () => resolvePath(`test-transcripts/channels/${SLUG}`); +const channelDir = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`); const mediaLink = () => join(channelDir(), "media"); -const controlFile = () => resolvePath("test-transcripts/.fake-findmnt.json"); +const controlFile = () => resolvePath(`${testPaths().transcriptsDir}/.fake-findmnt.json`); async function writeControl(control: { mounts?: Array<Record<string, unknown>>; @@ -71,7 +72,7 @@ async function relocateOnDisk(root: string): Promise<string> { ); await symlink(target, mediaLink()); const config = await readJson<Record<string, unknown>>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ); await writeFile( join(channelDir(), "config.json"), @@ -84,7 +85,7 @@ async function relocateOnDisk(root: string): Promise<string> { async function storedVolumeUuid(id: string): Promise<string | undefined> { const s = await readJson<{ storage: { locations: Array<{ id: string; volume?: { uuid?: string } }> }; - }>("test-settings.json"); + }>(testPaths().settingsFile); return s.storage.locations.find((l) => l.id === id)?.volume?.uuid; } @@ -181,7 +182,7 @@ test("the page lists a location with its status, counts and refusals", async ({ // It landed in settings.json, opt-in included. const settings = await readJson<{ storage: { locations: Array<Record<string, unknown>> }; - }>("test-settings.json"); + }>(testPaths().settingsFile); const stored = settings.storage.locations.find((l) => l.id === "warm"); expect(stored?.root).toBe(second); expect(stored?.autoRepoint).toBe(true); @@ -276,14 +277,14 @@ test("a volume that came up somewhere else is re-pointed in one click", async ({ expect( ( await readJson<{ mediaDir?: string }>( - `test-transcripts/channels/${SLUG}/config.json`, + `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`, ) ).mediaDir, ).toBe(targetB); // ...and so does the location. const settings = await readJson<{ storage: { locations: Array<{ id: string; root: string }> }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(settings.storage.locations.find((l) => l.id === "cold")?.root).toBe( rootB, ); @@ -383,7 +384,7 @@ test("the saved-video store moves onto a location, and back", async ({ const root = testInfo.outputPath("platter"); await mkdir(root, { recursive: true }); // Something to move. The store is <root>/<slug>/<videoId>/<container>. - const storeDir = resolvePath("test-transcripts/saved-videos"); + const storeDir = resolvePath(`${testPaths().transcriptsDir}/saved-videos`); await mkdir(join(storeDir, SLUG, VIDEO), { recursive: true }); await writeFile( join(storeDir, SLUG, VIDEO, "source-media.mp4"), @@ -424,7 +425,7 @@ test("the saved-video store moves onto a location, and back", async ({ expect(await readlink(storeDir)).toBe(target); const after = await readJson<{ storage: { savedVideosLocationId?: string }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(after.storage.savedVideosLocationId).toBe("cold"); // EVERY READER KEEPS WORKING, THROUGH THE LINK, UNCHANGED — which is the @@ -457,10 +458,10 @@ test("the saved-video store moves onto a location, and back", async ({ ); const back = await readJson<{ storage: { savedVideosLocationId?: string }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(back.storage.savedVideosLocationId).toBe(undefined); // The target was reclaimed, and the store is a real directory again. - expect(await pathExists("test-transcripts/saved-videos/" + SLUG)).toBe(true); + expect(await pathExists(`${testPaths().transcriptsDir}/saved-videos/` + SLUG)).toBe(true); }); // A KILLED COPY LEAVES A MARKER NOTHING WILL EVER CLEAR, and without Resume the @@ -472,7 +473,7 @@ test("an interrupted store move is resumable from the page", async ({ await resetData("one-youtube-channel-with-data"); const root = testInfo.outputPath("platter"); await mkdir(root, { recursive: true }); - const storeDir = resolvePath("test-transcripts/saved-videos"); + const storeDir = resolvePath(`${testPaths().transcriptsDir}/saved-videos`); await mkdir(join(storeDir, SLUG, VIDEO), { recursive: true }); await writeFile( join(storeDir, SLUG, VIDEO, "source-media.mp4"), @@ -490,7 +491,7 @@ test("an interrupted store move is resumable from the page", async ({ const target = join(root, "saved-videos"); await mkdir(join(target, SLUG, VIDEO), { recursive: true }); await writeFile( - resolvePath("test-transcripts/.relocating-saved-videos.json"), + resolvePath(`${testPaths().transcriptsDir}/.relocating-saved-videos.json`), JSON.stringify( { target, @@ -516,7 +517,7 @@ test("an interrupted store move is resumable from the page", async ({ ); expect(await readlink(storeDir)).toBe(target); expect( - await pathExists("test-transcripts/.relocating-saved-videos.json"), + await pathExists(`${testPaths().transcriptsDir}/.relocating-saved-videos.json`), ).toBe(false); }); @@ -537,7 +538,7 @@ test("a store move to an unmounted root refuses before it creates anything", asy await resetData("one-youtube-channel-with-data"); // The root the location names is NOT created — that is the whole point. const root = join(testInfo.outputPath("never-mounted"), "platter"); - const storeDir = resolvePath("test-transcripts/saved-videos"); + const storeDir = resolvePath(`${testPaths().transcriptsDir}/saved-videos`); await mkdir(join(storeDir, SLUG, VIDEO), { recursive: true }); await writeFile( join(storeDir, SLUG, VIDEO, "source-media.mp4"), @@ -570,7 +571,7 @@ test("a store move to an unmounted root refuses before it creates anything", asy ).toBe("not really an mp4"); const settings = await readJson<{ storage: { savedVideosLocationId?: string }; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(settings.storage.savedVideosLocationId ?? "").toBe(""); }); @@ -588,7 +589,7 @@ test("Evict fetched windows removes an old one and leaves a recent one", async ( test.setTimeout(120_000); await resetData("one-youtube-channel-with-data"); const clipsDir = resolvePath( - `test-transcripts/channels/${SLUG}/data/${VIDEO}/clips`, + `${testPaths().transcriptsDir}/channels/${SLUG}/data/${VIDEO}/clips`, ); await mkdir(clipsDir, { recursive: true }); const old = join(clipsDir, "10.00-40.00.mp4"); @@ -705,7 +706,7 @@ test("evicting at any age needs the tick as well as the preview", async ({ async function storedHealth(): Promise<Record<string, unknown> | undefined> { const s = await readJson<{ storage?: { health?: Record<string, unknown> } }>( - "test-settings.json", + testPaths().settingsFile, ); return s.storage?.health; } diff --git a/editor/e2e/sync-break-on-existing.spec.ts b/editor/e2e/sync-break-on-existing.spec.ts @@ -4,6 +4,7 @@ import { generateReport, readJson, resetData, + testPaths, } from "./helpers"; test("treats yt-dlp exit code 101 as success and updates lastSyncedAt", async ({ @@ -28,7 +29,7 @@ test("treats yt-dlp exit code 101 as success and updates lastSyncedAt", async ({ // Config now has lastSyncedAt set to a parseable ISO string. const config = await readJson<{ lastSyncedAt?: string }>( - "test-transcripts/channels/archived-channel/config.json", + `${testPaths().transcriptsDir}/channels/archived-channel/config.json`, ); expect(typeof config.lastSyncedAt).toBe("string"); expect(Number.isNaN(Date.parse(config.lastSyncedAt!))).toBe(false); diff --git a/editor/e2e/sync-deep.spec.ts b/editor/e2e/sync-deep.spec.ts @@ -7,6 +7,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; // The sync FULL SWEEP: one full listing enumeration that refreshes the stored @@ -21,7 +22,7 @@ import { const CHANNEL = "availability-test"; const FIXTURE = "availability-baseline"; -const channelRoot = `test-transcripts/channels/${CHANNEL}`; +const channelRoot = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; // The baseline fixture's on-disk video dirs (canonical ids). const ALL_IDS = [ diff --git a/editor/e2e/tags.spec.ts b/editor/e2e/tags.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type Page } from "@playwright/test"; -import { buildIndex, readJson, resetData, writeSite } from "./helpers"; +import { buildIndex, readJson, resetData, writeSite, testPaths } from "./helpers"; // Curated tags — the vocabulary, the rules, and the three writers. // @@ -49,7 +49,7 @@ type TagsFile = { >; }; -const tagsFile = () => readJson<TagsFile>("test-transcripts/tags.json"); +const tagsFile = () => readJson<TagsFile>(`${testPaths().transcriptsDir}/tags.json`); async function withIndex(page: Page) { await writeSite("testsite", { @@ -490,7 +490,7 @@ test("a site overlays presentation and cannot touch rules, assignments or a labe await expect(page.getByTestId("site-tags-saved")).toBeVisible(); const site = await readJson<TagsFile>( - "test-transcripts/sites/testsite/tags.json", + `${testPaths().transcriptsDir}/sites/testsite/tags.json`, ); // The row holds ONLY what this site said. No label — not even a copy of the // corpus one — because the site file is coerced at the site layer, where a @@ -521,7 +521,7 @@ test("a site overlays presentation and cannot touch rules, assignments or a labe .getByLabel("label for eva-collab", { exact: true }), ).toHaveAttribute("placeholder", "On mic"); expect( - (await readJson<TagsFile>("test-transcripts/sites/testsite/tags.json")) + (await readJson<TagsFile>(`${testPaths().transcriptsDir}/sites/testsite/tags.json`)) .tags[0].label, ).toBeUndefined(); }); diff --git a/editor/e2e/testPaths.ts b/editor/e2e/testPaths.ts @@ -0,0 +1,69 @@ +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +// WHERE A TEST SERVER'S DATA LIVES — one function, for the specs, the helpers +// and the config (plans/e2e-speed.md S5: a server per worker needs every path a +// spec touches to come from the worker's own root, not a literal). +// +// The root is the editor directory for the first worker (slot 0), and +// `.e2e-workers/w<slot>` for the others (one server set per worker, started by +// globalSetup — e2e/servers.ts); E2E_DATA_ROOT, when set, wins. Under it sit +// the same names the suite has always used. `dev:test` / `start:test` read the +// same variable (`${E2E_DATA_ROOT:-$(pwd)}`), so a server and the specs that +// drive it agree by construction. One worker: the editor directory, exactly +// the paths of before. +// +// The slot is Playwright's TEST_PARALLEL_INDEX (0 … workers−1, kept by a +// restarted worker; not TEST_WORKER_INDEX, which grows with every restart). It +// is set before the worker loads anything, so a spec's top-level constant +// built from testPaths() is already its worker's. +// +// E2E_-prefixed on purpose, never TRANSCRIPTS_DIR / SETTINGS_FILE: a +// `--share-data` worktree's `.worktree-env` sets TRANSCRIPTS_DIR to the REAL +// corpus, and resetData() deletes this directory. + +const here = dirname(fileURLToPath(import.meta.url)); +export const EDITOR_ROOT = resolve(here, ".."); + +export type TestPaths = { + /** The data root: the editor directory, or E2E_DATA_ROOT. */ + root: string; + /** TRANSCRIPTS_DIR of the test server — what resetData() replaces. */ + transcriptsDir: string; + /** SETTINGS_FILE of the test server (and of the editor suite's export server). */ + settingsFile: string; + /** EXPORT_PUBLIC_DIR of the test server. */ + exportPublicDir: string; + /** EDITOR_CHANGELOG_FILE / EXPORT_CHANGELOG_FILE: the cut-release specs' disposable changelogs. */ + editorChangelog: string; + exportChangelog: string; +}; + +export function testPathsFor(root: string): TestPaths { + const transcriptsDir = join(root, "test-transcripts"); + return { + root, + transcriptsDir, + settingsFile: join(root, "test-settings.json"), + exportPublicDir: join(transcriptsDir, ".export-public"), + editorChangelog: join(root, "test-changelog.md"), + exportChangelog: join(root, "test-export-changelog.md"), + }; +} + +/** The data root of a worker slot: the editor directory for slot 0. */ +export function slotRoot(slot: number): string { + return slot > 0 ? join(EDITOR_ROOT, ".e2e-workers", `w${slot}`) : EDITOR_ROOT; +} + +/** This process's worker slot (0 outside a Playwright worker). */ +export function currentSlot(env: Readonly<Record<string, string | undefined>> = process.env): number { + const n = Number(env.TEST_PARALLEL_INDEX); + return Number.isInteger(n) && n > 0 ? n : 0; +} + +/** This process's test data paths (read per call, so a worker's env applies). */ +export function testPaths(): TestPaths { + const root = process.env.E2E_DATA_ROOT?.trim(); + return testPathsFor(root ? resolve(root) : slotRoot(currentSlot())); +} diff --git a/editor/e2e/title-filter.spec.ts b/editor/e2e/title-filter.spec.ts @@ -7,6 +7,7 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -18,7 +19,7 @@ import { baseUrl } from "./baseUrl"; // `needsauthvid01` is the sentinel the fake refuses without cookies, so the scan // has one video it cannot read. const CHANNEL = "test-filter"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const GUEST = ["guestvid0001", "guestvid0002"]; const PLAIN = ["plainvid0001", "plainvid0002"]; const NEEDS_AUTH = "needsauthvid01"; diff --git a/editor/e2e/transcript-source.spec.ts b/editor/e2e/transcript-source.spec.ts @@ -6,11 +6,12 @@ import { readJson, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "test-youtube"; const VIDEO_DIR = "20240101_test1234567"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const DATA = `${ROOT}/data/${VIDEO_DIR}`; const VIDEO_URL = `/channels/${CHANNEL}/videos/${VIDEO_DIR}`; const VTT = "WEBVTT\n\n00:00:00.000 --> 00:00:05.000\nhello\n"; diff --git a/editor/e2e/truncated-check.spec.ts b/editor/e2e/truncated-check.spec.ts @@ -7,12 +7,12 @@ import { mkdir, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { pathExists, readJson, resetData, resolvePath, generateReport } from "./helpers"; +import { pathExists, readJson, resetData, resolvePath, generateReport, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; const CHANNEL = "test-transcribe"; -const DATA = `test-transcripts/channels/${CHANNEL}/data`; -const SNAPSHOT_REL = `test-transcripts/channels/${CHANNEL}/snapshot.json`; +const DATA = `${testPaths().transcriptsDir}/channels/${CHANNEL}/data`; +const SNAPSHOT_REL = `${testPaths().transcriptsDir}/channels/${CHANNEL}/snapshot.json`; const MARKER_REL = `${DATA}/vidTrunc/exclude-truncated-check.json`; const WHISPER = JSON.stringify({ transcription: [{ text: "hello" }] }); diff --git a/editor/e2e/undownloaded.spec.ts b/editor/e2e/undownloaded.spec.ts @@ -4,6 +4,7 @@ import { generateReport, pathExists, resetData, + testPaths, } from "./helpers"; test("shows empty state when there is no playlist", async ({ page }) => { @@ -73,7 +74,7 @@ test("undownloaded list shrinks after a one-click whisper completes", async ({ expect( await pathExists( - "test-transcripts/channels/test-youtube/data/fake00000002/transcript.json", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000002/transcript.json`, ), ).toBe(true); diff --git a/editor/e2e/video-filter-combine.spec.ts b/editor/e2e/video-filter-combine.spec.ts @@ -10,10 +10,11 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "test-transcribe"; -const DATA = `test-transcripts/channels/${CHANNEL}/data`; +const DATA = `${testPaths().transcriptsDir}/channels/${CHANNEL}/data`; // A non-empty whisper transcript so the video reads as transcribed (and isn't // flagged untranscribable for being empty). diff --git a/editor/e2e/video-page.spec.ts b/editor/e2e/video-page.spec.ts @@ -6,6 +6,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; test("per-video page renders metadata and file list", async ({ page }) => { @@ -46,7 +47,7 @@ test("WhisperPanel renders failure list as links to per-video pages", async ({ await resetData("one-transcribe-channel-with-audio"); await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "vidA\nvidB\n", ); @@ -65,7 +66,7 @@ test("failed entry stays in the list across reloads (skip semantics)", async ({ await resetData("one-transcribe-channel-with-audio"); await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "vidA\n", ); @@ -87,7 +88,7 @@ test("failed entry stays in the list across reloads (skip semantics)", async ({ // …and it stays on the failed list (skip semantics persist). const failList = await readFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "utf8", ); @@ -111,7 +112,7 @@ test("transcribe-one writes transcript.json for a specific audio file", async ({ .poll( () => pathExists( - "test-transcripts/channels/test-transcribe/data/vidA/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/transcript.json`, ), { timeout: 30_000 }, ) @@ -149,13 +150,13 @@ test("transcode keeps source and writes audio.<target>", async ({ page }) => { ).toContainText("wrote", { timeout: 30_000 }); expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidA/audio.mp3", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/audio.mp3`, ), ).toBe(true); // Source file still on disk. expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidA/audio.m4a", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/audio.m4a`, ), ).toBe(true); }); @@ -167,7 +168,7 @@ test("audio + whisper for a YouTube video with no auto-subs", async ({ // Stage a video dir whose name matches the URL id so fake-ytdlp's audio // output (data/<id>/audio.<fmt>) lands back in the same dir we navigate to. const dir = resolvePath( - "test-transcripts/channels/test-youtube/data/test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/test1234567`, ); await mkdir(dir, { recursive: true }); await writeFile( @@ -189,7 +190,7 @@ test("audio + whisper for a YouTube video with no auto-subs", async ({ ).toContainText("Transcribe test1234567 done", { timeout: 30_000 }); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/test1234567/audio.mp3", + `${testPaths().transcriptsDir}/channels/test-youtube/data/test1234567/audio.mp3`, ), ).toBe(true); }); @@ -221,7 +222,7 @@ test("Delete file removes a single file from the directory", async ({ page }) => page.on("dialog", (d) => d.accept()); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/20240101_test1234567/transcript.en.vtt", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567/transcript.en.vtt`, ), ).toBe(true); await page.getByLabel("delete file transcript.en.vtt").click(); @@ -230,7 +231,7 @@ test("Delete file removes a single file from the directory", async ({ page }) => await expect(page.getByLabel("file name metadata.info.json")).toBeVisible(); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/20240101_test1234567/transcript.en.vtt", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567/transcript.en.vtt`, ), ).toBe(false); }); @@ -254,7 +255,7 @@ test("Delete directory wrong-id confirmation shows an error", async ({ ); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/20240101_test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567`, ), ).toBe(true); }); @@ -272,7 +273,7 @@ test("Delete directory removes the dir and redirects to the channel page", async await expect(page).toHaveURL("/channels/test-youtube"); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/20240101_test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567`, ), ).toBe(false); }); @@ -283,7 +284,7 @@ test("Mark untranscribable writes empty transcript and prunes failure list", asy await resetData("one-transcribe-channel-with-audio"); await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "vidA\nvidOther\n", ); @@ -295,7 +296,7 @@ test("Mark untranscribable writes empty transcript and prunes failure list", asy const raw = await readFile( resolvePath( - "test-transcripts/channels/test-transcribe/data/vidA/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/transcript.json`, ), "utf8", ); @@ -303,7 +304,7 @@ test("Mark untranscribable writes empty transcript and prunes failure list", asy const list = await readFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "utf8", ); @@ -325,7 +326,7 @@ test("Mark untranscribable button is absent when transcript already exists", asy test("text files render a preview, not the audio player", async ({ page }) => { await resetData("one-youtube-channel-with-data"); const dir = resolvePath( - "test-transcripts/channels/test-youtube/data/20240101_test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567`, ); // Stage misleadingly-named text files plus a real audio.mp3 in the same // video dir. Old code matched name.startsWith("audio.") and would render @@ -367,7 +368,7 @@ test("text files render a preview, not the audio player", async ({ page }) => { test("JSON preview pretty-prints minified content", async ({ page }) => { await resetData("one-youtube-channel-with-data"); const dir = resolvePath( - "test-transcripts/channels/test-youtube/data/20240101_test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567`, ); await writeFile(`${dir}/nested.json`, '{"a":1,"b":[2,3],"c":{"d":"e"}}\n'); @@ -386,7 +387,7 @@ test("JSON preview falls back to raw text when the file is not valid JSON", asyn }) => { await resetData("one-youtube-channel-with-data"); const dir = resolvePath( - "test-transcripts/channels/test-youtube/data/20240101_test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567`, ); const raw = "not valid json {{{"; await writeFile(`${dir}/broken.json`, raw); @@ -405,7 +406,7 @@ test("JSON preview falls back to raw text when the file is not valid JSON", asyn test("audioFiles count excludes audio.vtt and audio.json", async ({ page }) => { await resetData("one-youtube-channel-with-data"); const dir = resolvePath( - "test-transcripts/channels/test-youtube/data/20240101_test1234567", + `${testPaths().transcriptsDir}/channels/test-youtube/data/20240101_test1234567`, ); await writeFile(`${dir}/audio.vtt`, "WEBVTT\n"); await writeFile(`${dir}/audio.json`, "{}\n"); @@ -441,7 +442,7 @@ test("Transcode card lists a kept source video (audio.mp4) so it can be re-extra // appeared and the user could not overwrite the truncated mp3 from the UI. await resetData("one-transcribe-channel-with-audio"); const dir = resolvePath( - "test-transcripts/channels/test-transcribe/data/vidA", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA`, ); await writeFile(`${dir}/audio.mp4`, "fake source container"); await writeFile(`${dir}/audio.mp3`, "truncated extraction"); diff --git a/editor/e2e/video-titles.spec.ts b/editor/e2e/video-titles.spec.ts @@ -15,10 +15,11 @@ import { generateReport, resetData, resolvePath, + testPaths, } from "./helpers"; const CHANNEL = "test-youtube"; -const ROOT = `test-transcripts/channels/${CHANNEL}`; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; const DOWNLOADED = "fake00000001"; const SCANNED = "fake00000002"; const BARE = "fake00000003"; diff --git a/editor/e2e/whisper-video.spec.ts b/editor/e2e/whisper-video.spec.ts @@ -1,6 +1,6 @@ import { readFile, rm, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; -import { pathExists, resetData, resolvePath } from "./helpers"; +import { pathExists, resetData, resolvePath, testPaths } from "./helpers"; test("one-click whisper downloads audio then transcribes a YouTube video", async ({ page, @@ -10,7 +10,7 @@ test("one-click whisper downloads audio then transcribes a YouTube video", async // page treats it as untranscribed. await rm( resolvePath( - "test-transcripts/channels/test-youtube/data/fake00000001/transcript.en.vtt", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/transcript.en.vtt`, ), ); @@ -26,12 +26,12 @@ test("one-click whisper downloads audio then transcribes a YouTube video", async expect( await pathExists( - "test-transcripts/channels/test-youtube/data/fake00000001/audio.mp3", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/audio.mp3`, ), ).toBe(true); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/fake00000001/transcript.json", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/transcript.json`, ), ).toBe(true); }); @@ -51,14 +51,14 @@ test("one-click whisper skips download when audio is already on disk", async ({ expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidA/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/transcript.json`, ), ).toBe(true); // The fake-ytdlp script appends each invocation to fake-ytdlp.invocations // in the channel root. Confirm no download-one entry was written for vidA. const invocationsPath = resolvePath( - "test-transcripts/channels/test-transcribe/fake-ytdlp.invocations", + `${testPaths().transcriptsDir}/channels/test-transcribe/fake-ytdlp.invocations`, ); const invocations = await readFile(invocationsPath, "utf8").catch(() => ""); expect(invocations).not.toContain("download-one:"); @@ -75,12 +75,12 @@ test("one-click whisper ignores a leftover live-chat .part sidecar", async ({ await resetData("youtube-with-playlist"); await rm( resolvePath( - "test-transcripts/channels/test-youtube/data/fake00000001/transcript.en.vtt", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/transcript.en.vtt`, ), ); await writeFile( resolvePath( - "test-transcripts/channels/test-youtube/data/fake00000001/audio.live_chat.json.part", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/audio.live_chat.json.part`, ), "[]", ); @@ -99,12 +99,12 @@ test("one-click whisper ignores a leftover live-chat .part sidecar", async ({ expect( await pathExists( - "test-transcripts/channels/test-youtube/data/fake00000001/audio.mp3", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/audio.mp3`, ), ).toBe(true); expect( await pathExists( - "test-transcripts/channels/test-youtube/data/fake00000001/transcript.json", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/transcript.json`, ), ).toBe(true); }); @@ -118,12 +118,12 @@ test("one-click whisper ignores a completed live-chat sidecar", async ({ await resetData("youtube-with-playlist"); await rm( resolvePath( - "test-transcripts/channels/test-youtube/data/fake00000001/transcript.en.vtt", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/transcript.en.vtt`, ), ); await writeFile( resolvePath( - "test-transcripts/channels/test-youtube/data/fake00000001/audio.live_chat.json", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/audio.live_chat.json`, ), "[]", ); diff --git a/editor/e2e/whisper.spec.ts b/editor/e2e/whisper.spec.ts @@ -7,6 +7,7 @@ import { pathExists, resetData, resolvePath, + testPaths, } from "./helpers"; // A video the downloader couldn't produce real audio for: the dir exists but the @@ -14,7 +15,7 @@ import { // `failed-corrupt-source` outcome. Helper writes that state plus a stale // failed-transcriptions entry (the bug being fixed wrongly left these behind). async function writeCorruptSourceVideo(id: string, alreadyFailed: boolean) { - const dir = `test-transcripts/channels/test-transcribe/data/${id}`; + const dir = `${testPaths().transcriptsDir}/channels/test-transcribe/data/${id}`; await mkdir(resolvePath(dir), { recursive: true }); await writeFile(resolvePath(`${dir}/audio.m4a.part`), "partial-bytes"); await writeFile( @@ -30,7 +31,7 @@ async function writeCorruptSourceVideo(id: string, alreadyFailed: boolean) { if (alreadyFailed) { await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), `${id}\n`, ); @@ -49,7 +50,7 @@ test("transcribes every audio file with no transcript", async ({ page }) => { for (const id of ["vidA", "vidB", "vidC"]) { expect( await pathExists( - `test-transcripts/channels/test-transcribe/data/${id}/transcript.json`, + `${testPaths().transcriptsDir}/channels/test-transcribe/data/${id}/transcript.json`, ), ).toBe(true); } @@ -71,7 +72,7 @@ test("Transcribe missing excludes VTT-only videos instead of failing them", asyn ); const failPath = - "test-transcripts/channels/test-youtube/failed-transcriptions"; + `${testPaths().transcriptsDir}/channels/test-youtube/failed-transcriptions`; if (await pathExists(failPath)) { const raw = await readFile(resolvePath(failPath), "utf8"); expect(raw).not.toContain("fake00000001"); @@ -79,7 +80,7 @@ test("Transcribe missing excludes VTT-only videos instead of failing them", asyn expect( await pathExists( - "test-transcripts/channels/test-youtube/data/fake00000001/transcript.json", + `${testPaths().transcriptsDir}/channels/test-youtube/data/fake00000001/transcript.json`, ), ).toBe(false); }); @@ -103,14 +104,14 @@ test("Transcribe missing skips corrupt-source videos and auto-prunes them from t // must not have been transcribed or re-recorded as failed. const raw = await readFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "utf8", ); expect(raw).not.toContain("vidBad"); expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidBad/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidBad/transcript.json`, ), ).toBe(false); }); @@ -167,7 +168,7 @@ test("Retry failures button is gone; Clear failure list takes its place", async await resetData("one-transcribe-channel-with-audio"); await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "vidA\nvidB\n", ); @@ -187,7 +188,7 @@ test("clearing the failure list lets the next Transcribe missing retry them", as await resetData("one-transcribe-channel-with-audio"); await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "vidA\nvidB\n", ); @@ -209,7 +210,7 @@ test("clearing the failure list lets the next Transcribe missing retry them", as expect( await readFile( resolvePath( - "test-transcripts/channels/test-transcribe/failed-transcriptions", + `${testPaths().transcriptsDir}/channels/test-transcribe/failed-transcriptions`, ), "utf8", ), @@ -231,7 +232,7 @@ test("Clean audio removes audio files only from transcribed videos", async ({ // vidA gets a transcript so its audio should be cleaned. await writeFile( resolvePath( - "test-transcripts/channels/test-transcribe/data/vidA/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/transcript.json`, ), JSON.stringify({ result: { language: "en" }, transcription: [] }), ); @@ -245,18 +246,18 @@ test("Clean audio removes audio files only from transcribed videos", async ({ // vidA's audio is gone, transcript stays. expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidA/audio.m4a", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/audio.m4a`, ), ).toBe(false); expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidA/transcript.json", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidA/transcript.json`, ), ).toBe(true); // vidB has no transcript, its audio is left alone. expect( await pathExists( - "test-transcripts/channels/test-transcribe/data/vidB/audio.m4a", + `${testPaths().transcriptsDir}/channels/test-transcribe/data/vidB/audio.m4a`, ), ).toBe(true); }); diff --git a/editor/e2e/widget.spec.ts b/editor/e2e/widget.spec.ts @@ -17,6 +17,7 @@ import { writeSettings, writeChannelConfig, generateReport, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -28,7 +29,7 @@ async function seedCleanableChannel( slug: string = CLEAN_SLUG, bytes: number = 2_621_440, ): Promise<void> { - const full = resolvePath(`test-transcripts/channels/${slug}/snapshot.json`); + const full = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}/snapshot.json`); await mkdir(dirname(full), { recursive: true }); await writeFile( full, @@ -807,7 +808,7 @@ test("the widget's controls hold and release the backfill lane", async ({ const laneHeld = async () => ( await readJson<{ autoQueue?: { backfill?: { held?: boolean } } }>( - "test-settings.json", + testPaths().settingsFile, ).catch(() => ({}) as { autoQueue?: { backfill?: { held?: boolean } } }) ).autoQueue?.backfill?.held ?? false; diff --git a/editor/e2e/worker-remote.spec.ts b/editor/e2e/worker-remote.spec.ts @@ -15,13 +15,14 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; const TOKEN = "test-worker-token"; async function makeTranscribeChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, @@ -149,7 +150,7 @@ test("a batch dispatched to a remote worker transcribes via the HTTP round-trip" .poll( () => pathExists( - "test-transcripts/channels/remote-chan/data/vidremote1/transcript.json", + `${testPaths().transcriptsDir}/channels/remote-chan/data/vidremote1/transcript.json`, ), { timeout: 30_000 }, ) @@ -179,7 +180,7 @@ test("an unreachable remote is auto-disabled and the video fails over to a local .poll( () => pathExists( - "test-transcripts/channels/failover-chan/data/vidfo1/transcript.json", + `${testPaths().transcriptsDir}/channels/failover-chan/data/vidfo1/transcript.json`, ), { timeout: 30_000 }, ) diff --git a/editor/e2e/workers.spec.ts b/editor/e2e/workers.spec.ts @@ -13,6 +13,7 @@ import { resetData, resolvePath, writeSettings, + testPaths, } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -25,7 +26,7 @@ async function relaunchPool() { } async function makeTranscribeChannel(slug: string, ids: string[]) { - const root = resolvePath(`test-transcripts/channels/${slug}`); + const root = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); await mkdir(root, { recursive: true }); await writeFile( `${root}/config.json`, @@ -46,7 +47,7 @@ async function transcriptCount(slug: string, ids: string[]): Promise<number> { let n = 0; for (const id of ids) { if ( - await pathExists(`test-transcripts/channels/${slug}/data/${id}/transcript.json`) + await pathExists(`${testPaths().transcriptsDir}/channels/${slug}/data/${id}/transcript.json`) ) { n++; } @@ -216,7 +217,7 @@ test("Set as default persists the enabled workers and re-applies them on relaunc // Persisted to the worker-defaults file as just the GPU id. const saved = await readJson<{ enabledWorkerIds: string[] }>( - "test-transcripts/.workers/defaults.json", + `${testPaths().transcriptsDir}/.workers/defaults.json`, ); expect(saved.enabledWorkerIds).toEqual(["gpu"]); @@ -297,7 +298,7 @@ test.describe("worker configuration", () => { const saved = await readJson<{ workers?: { name: string; appId?: string; priority: number }[]; - }>("test-settings.json"); + }>(testPaths().settingsFile); expect(saved.workers).toHaveLength(3); expect(saved.workers?.[2].name).toBe("CPU chough"); expect(saved.workers?.[2].appId).toBe("chough"); @@ -325,7 +326,7 @@ test.describe("worker configuration", () => { const saved = await readJson<{ workers?: { appId?: string; config?: { remoteUrl?: string } }[]; - }>("test-settings.json"); + }>(testPaths().settingsFile); const choughs = (saved.workers ?? []).filter((w) => w.appId === "chough"); expect(choughs.length).toBe(2); expect(choughs.every((w) => w.config?.remoteUrl === "http://localhost:8165")).toBe( diff --git a/editor/e2e/x-session.spec.ts b/editor/e2e/x-session.spec.ts @@ -5,7 +5,7 @@ // under the test corpus, never a real browser profile. import { test, expect } from "@playwright/test"; -import { readJson, resetData, resolvePath, writeSettings } from "./helpers"; +import { readJson, resetData, resolvePath, writeSettings, testPaths } from "./helpers"; // By relative path: a runtime import of the package specifier does not resolve // under playwright's loader (digest.spec.ts says why). import { writeFirefoxCookieStore } from "../../common/social/__fixtures__/firefoxCookieStore"; @@ -29,7 +29,7 @@ test("settings page renders the X session section", async ({ page }) => { test("the login source select persists, and Check shows a status line", async ({ page }) => { await resetData("empty"); - const profileDir = resolvePath("test-transcripts/firefox-fixture/xl.default-release"); + const profileDir = resolvePath(`${testPaths().transcriptsDir}/firefox-fixture/xl.default-release`); await writeFirefoxCookieStore(profileDir, [ { host: ".x.com", @@ -61,7 +61,7 @@ test("the login source select persists, and Check shows a status line", async ({ await select.selectOption("profile"); await expect(section.getByRole("status")).toHaveText("Login source saved."); await expect(inUse).toHaveText("In use: Connected profile"); - expect((await readJson<{ social?: unknown }>("test-settings.json")).social).toEqual({ + expect((await readJson<{ social?: unknown }>(testPaths().settingsFile)).social).toEqual({ x: { cookieSource: "profile" }, }); @@ -74,7 +74,7 @@ test("the login source select persists, and Check shows a status line", async ({ // Back to automatic: nothing stored, the default decides again. await select.selectOption("auto"); await expect(inUse).toHaveText(`In use: Browser login (${spec}) (automatic)`); - expect((await readJson<{ social?: unknown }>("test-settings.json")).social).toEqual({ x: {} }); + expect((await readJson<{ social?: unknown }>(testPaths().settingsFile)).social).toEqual({ x: {} }); }); // Where X posts appear — `social.x.visibility` (release 17 slice XP). The two X @@ -86,7 +86,7 @@ test("where X posts appear persists, beside the login source and without it", as const visibility = page.getByLabel("Where X posts appear"); const source = page.getByLabel("x cookie source", { exact: true }); const social = async () => - (await readJson<{ social?: unknown }>("test-settings.json")).social; + (await readJson<{ social?: unknown }>(testPaths().settingsFile)).social; await expect(visibility).toHaveValue("public"); await expect(page.locator("[data-x-posts-visibility]")).toContainText( diff --git a/editor/package.json b/editor/package.json @@ -5,12 +5,12 @@ "type": "module", "scripts": { "dev": "next dev --port ${EDITOR_PORT:-3001}", - "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=$(pwd)/test-transcripts EXPORT_PUBLIC_DIR=$(pwd)/test-transcripts/.export-public SETTINGS_FILE=$(pwd)/test-settings.json EDITOR_CHANGELOG_FILE=$(pwd)/test-changelog.md EXPORT_CHANGELOG_FILE=$(pwd)/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", - "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=$(pwd)/test-transcripts EXPORT_PUBLIC_DIR=$(pwd)/test-transcripts/.export-public SETTINGS_FILE=$(pwd)/test-settings.json EDITOR_CHANGELOG_FILE=$(pwd)/test-changelog.md EXPORT_CHANGELOG_FILE=$(pwd)/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", + "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", + "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", "build": "next build", "start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", - "test": "tsx --test \"app/**/*.test.ts\"", - "e2e": "node ../scripts/queue-lock.mjs --ports PORT:3011,EXPORT_PORT:3010,OLLAMA_STUB_PORT:11435 -- playwright test", + "test": "tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"", + "e2e": "node ../scripts/queue-lock.mjs --name e2e-editor --estimate 1500 --scale-by E2E_WORKERS --prebuild editor --ports PORT:3011,EXPORT_PORT:3010,OLLAMA_STUB_PORT:11435 -- playwright test", "e2e:ui": "playwright test --ui" }, "dependencies": { diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -1,12 +1,14 @@ import { spawnSync } from "node:child_process"; import path from "node:path"; import { defineConfig, devices } from "@playwright/test"; -import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { SERIAL_SPEC_PATTERN } from "./e2e/serial"; +import { isFocusedRun, resolveE2EMode, resolveWorkers, slotPorts, slotServers } from "./e2e/servers"; +import { currentSlot } from "./e2e/testPaths"; // THE TEST-ONLY ENVIRONMENT, declared here (one-core Phase 4 slice 3). Every // variable only a harness reads carries the E2E_ prefix; the ones this config -// sets for the editor's test server are E2E_SERVER_ENV (passed as the -// webServer's env below), and the rest are knobs a spec or a person sets: +// sets for the editor's test server are E2E_SERVER_ENV (e2e/servers.ts, the +// env of every slot's editor), and the rest are knobs a spec or a person sets: // // E2E_TEST_ROUTES=1 opens /api/test/* (api/test/_guard.ts) and makes // the boot settle a test server's leftover jobs @@ -40,6 +42,16 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // E2E_BUILD_CHECKED set below once the stamp was checked, so the // config's second load (a worker's) does not check // again +// E2E_DATA_ROOT where the test server's data lives (default: +// this directory) — `test-transcripts/`, +// `test-settings.json`, the disposable changelogs. +// Read by `dev:test`/`start:test` and by the +// specs' testPaths() (e2e/testPaths.ts) +// E2E_WORKERS how many workers, each with its own server set +// (e2e/servers.ts): a number, or `auto` for what +// memory allows (cap 3). Default 1 +// E2E_SERIAL_LAST set below by the runner for its workers: whether +// the @serial project runs last (a whole run) // E2E_RACK_SHOTS=1 run the /channels rack screenshot audit // E2E_FAKE_YTDLP_AUDIO_CHECK_MODE, E2E_FAKE_YTDLP_CHUNK_DELAY_MS, // E2E_FAKE_YTDLP_CORRUPT_AFTER_CHUNK, E2E_FAKE_YTDLP_CORRUPT_RUNS, @@ -88,44 +100,19 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // worktree by scripts/worktree.mjs and named in queue-lock's --ports list. Nor // are the queue's own E2E_QUEUE / E2E_PORT_CHECK / E2E_QUEUE_TIMEOUT (read by // scripts/queue-lock.mjs, shared machine-wide). ENVIRONMENT.md lists them all. -const E2E_SERVER_ENV = { - E2E_TEST_ROUTES: "1", - E2E_AUDIO_CHECK_INTERVAL_MS: "300", - E2E_AUDIO_CHECK_SIZE_GATE: "4096", - E2E_AUDIO_CHECK_INTERVAL_FLOOR_MS: "50", - E2E_AUDIO_CHECK_RECOVER_STEP_MS: "100", - E2E_AUDIO_CHECK_RECOVER_AFTER: "2", - E2E_BACKOFF_BASE_MS: "20000", - E2E_CLIP_WINDOW_GAP_MS: "2000", - E2E_LIVE_CHECK: "skip", - WRANGLER_BIN: path.resolve(process.cwd(), "e2e", "fixtures", "bin", "fake-wrangler.mjs"), - ARCHILYZER_BRANCH: "main", - CLOUDFLARE_API_TOKEN: "e2e-fake-token-never-sent", - EXPORT_NEXT_BIN: path.resolve(process.cwd(), "e2e", "fixtures", "bin", "fake-next.mjs"), -}; - -const PORT = portFor("PORT"); -const baseURL = `http://localhost:${PORT}`; -// Expose the assigned base URL to node-side spec code (fetches to the editor's -// test API). Keeps offset-port worktrees working even when run directly without -// the worktree wrapper. See e2e/baseUrl.ts. -process.env.PLAYWRIGHT_BASE_URL = baseURL; +// The servers' environment, ports and commands live in e2e/servers.ts — one +// definition for slot 0 (the webServer entries below) and for every other +// worker slot (globalSetup). +const E2E_MODE = resolveE2EMode(); +const STAMPED_BUILD = E2E_MODE === "start" && !process.env.CI; // START MODE BY DEFAULT (plans/e2e-speed.md, S1): the same tests took 0.32× the // time under `next start` — a polled route recompiles under `next dev`. Before // any server starts, scripts/e2e-stamp.mjs compares the build's stamp with the // tree and rebuilds when they differ (it says which, and why), so a start-mode // run cannot serve a stale build. CI — the sharded image, which runs its own -// `next build` into `.next` — keeps that build and skips the stamp. -const E2E_MODE = (() => { - const raw = (process.env.E2E_MODE ?? "").trim().toLowerCase(); - if (raw === "" || raw === "start") return "start"; - if (raw === "dev") return "dev"; - throw new Error(`E2E_MODE=${process.env.E2E_MODE} is not a mode: use start (the default) or dev`); -})(); -const STAMPED_BUILD = E2E_MODE === "start" && !process.env.CI; -// The same directory as scripts/e2e-stamp.mjs PACKAGES.editor.distDir. -const E2E_DIST_DIR = ".next/e2e"; +// `next build` into `.next` — keeps that build and skips the stamp. A run +// through queue-lock's `--prebuild` has ensured it already (E2E_BUILD_CHECKED). if (STAMPED_BUILD && !process.env.E2E_BUILD_CHECKED) { const ensured = spawnSync( process.execPath, @@ -140,35 +127,63 @@ if (STAMPED_BUILD && !process.env.E2E_BUILD_CHECKED) { } process.env.E2E_BUILD_CHECKED = "1"; } -const webServerCommand = E2E_MODE === "start" ? "pnpm start:test" : "pnpm dev:test"; -const webServerEnv: Record<string, string> = STAMPED_BUILD - ? { ...E2E_SERVER_ENV, E2E_NEXT_DIST_DIR: E2E_DIST_DIR } - : E2E_SERVER_ENV; -// The digest lane's local engine is reached over HTTP, not spawned, so it gets a -// webServer entry instead of a fake binary in e2e/fixtures/bin/. Its port is -// exported so the editor's dev:test / start:test scripts point OLLAMA_URL at the -// same place, and so an offset-port worktree does not collide. -const OLLAMA_STUB_PORT = portFor("OLLAMA_STUB_PORT"); -process.env.OLLAMA_STUB_PORT = String(OLLAMA_STUB_PORT); +// WORKERS (plans/e2e-speed.md S5): one server set per worker slot. This file +// is evaluated again in every worker with TEST_PARALLEL_INDEX set, so from here +// on the ports, the base URL and the data root are the slot's (e2e/servers.ts). +const WORKERS = resolveWorkers(); +// Pinned for the workers, which evaluate this file again: `auto` read twice +// could read different memory, and a worker's project list must be the +// runner's. +process.env.E2E_WORKERS = String(WORKERS); +const SLOT = currentSlot(); +const ports = slotPorts(SLOT); +const baseURL = `http://localhost:${ports.editor}`; +// Node-side spec code (fetches to the editor's test API, e2e/baseUrl.ts) and +// the export specs (portFor("EXPORT_PORT")) read these. +process.env.PLAYWRIGHT_BASE_URL = baseURL; +process.env.EXPORT_PORT = String(ports.export); +// The digest lane's local engine is reached over HTTP, not spawned, so it gets +// a server instead of a fake binary in e2e/fixtures/bin/. Exported so the +// editor's dev:test / start:test scripts point OLLAMA_URL at the same place. +process.env.OLLAMA_STUB_PORT = String(ports.ollama); + +// Slot 0's servers: the webServer entries Playwright starts (and reuses, out of +// CI). Slots 1… are globalSetup's. +const slot0 = slotServers(0, E2E_MODE); +const webServer = slot0.map((s) => ({ + command: s.command, + url: s.url, + timeout: s.name === "ollama" ? 30_000 : 120_000, + reuseExistingServer: !process.env.CI, + env: s.env, +})); -const EXPORT_PORT = portFor("EXPORT_PORT"); -const exportBaseURL = `http://localhost:${EXPORT_PORT}`; -// Share the editor's test-settings.json with the export server so the -// footer (and any other server-rendered settings consumers) can be -// driven from a single fixture file during E2E. -const exportSettingsFile = path.resolve( - process.cwd(), - "test-settings.json", -); -// Footer/branding on the export server now come from a per-site config -// (currentSite()), so point it at a fixture site for deterministic E2E. -const exportSitesDir = path.resolve( - process.cwd(), - "e2e", - "fixtures", - "sites", -); +// @serial: spec files that time wall-clock behaviour under contention, or +// write into the checkout's own build outputs (export/out, homepage/out — +// shared by every slot), run on one worker (e2e/serial.ts) — in a whole run, +// AFTER the parallel project (its `teardown`, which runs even when a parallel +// test failed). A focused run (spec files, a grep) keeps the one-worker limit +// but not the order: Playwright runs a teardown project whole, whatever the +// filter. Decided once, by the runner, and pinned for the workers (their +// argv is not the command line). With one worker there is one project. +if (SLOT === 0 && process.env.TEST_PARALLEL_INDEX == null) { + process.env.E2E_SERIAL_LAST = isFocusedRun() ? "0" : "1"; +} +const SERIAL_LAST = process.env.E2E_SERIAL_LAST === "1"; +const browser = { ...devices["Desktop Chrome"] }; +const projects = + WORKERS > 1 + ? [ + { + name: "chromium", + use: browser, + testIgnore: SERIAL_SPEC_PATTERN, + ...(SERIAL_LAST ? { teardown: "serial" } : {}), + }, + { name: "serial", use: browser, testMatch: SERIAL_SPEC_PATTERN, workers: 1 }, + ] + : [{ name: "chromium", use: browser }]; export default defineConfig({ testDir: "./e2e", @@ -176,7 +191,8 @@ export default defineConfig({ // Reap fixture binaries that outlived their run — before this one starts (a // SIGKILLed run never gets to clean up after itself) and again after it ends. // Both log anything they find, because by construction they should find - // nothing. See e2e/fixtureProcs.ts. + // nothing. See e2e/fixtureProcs.ts. With more than one worker, globalSetup + // also starts slots 1…'s servers, and globalTeardown stops them. globalSetup: "./e2e/globalSetup.ts", globalTeardown: "./e2e/globalTeardown.ts", // The sharded runner sets CI=true for `reuseExistingServer: !CI` below, not @@ -195,73 +211,31 @@ export default defineConfig({ ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }], ], outputDir: "test-results/", - // Serial, one worker — deliberate, and not a performance oversight. Three - // pieces of shared mutable state are global to the whole run, so two workers - // corrupt each other's fixtures rather than merely running slower: + // ONE WORKER BY DEFAULT; E2E_WORKERS for more (e2e/servers.ts). Two workers + // over ONE server corrupt each other's fixtures rather than merely running + // slower: // - // 1. One hardcoded data root (e2e/helpers.ts:17) that 303 resetData() calls - // across 83 of the 87 spec files destroy and recreate — mostly from - // *inside* test bodies (e2e/helpers.ts:33-48), not just in beforeEach. - // 2. One shared test-settings.json (e2e/helpers.ts:18) that the export - // webServer below also reads as SETTINGS_FILE (see exportSettingsFile) — - // so resetData's rm+cp deletes a file a second live server is reading. - // 3. Four globalThis singletons inside the single Next server — job - // registry, worker pool, scheduler, auto-runner — cleared on every - // resetData/writeSettings via - // app/api/test/invalidate-cache/route.ts:24,32,38,44. + // 1. One data root that resetData() destroys and recreates — mostly from + // *inside* test bodies, not just in beforeEach. + // 2. One test-settings.json that the export server also reads as + // SETTINGS_FILE — so resetData's rm+cp deletes a file a second live + // server is reading. + // 3. The globalThis singletons inside the Next server — job registry, + // worker pool, scheduler, auto-runner — cleared on every + // resetData/writeSettings via app/api/test/invalidate-cache/route.ts. // - // (3) is the blocker that per-worker TRANSCRIPTS_DIR/SETTINGS_FILE cannot - // fix: the singletons live in the server process, so isolation needs a - // *server per worker*, not a directory per worker. That is why parallelism - // here is one container per shard (scripts/run-sharded-e2e.mjs, which gives - // each shard its own servers) rather than workers > 1 in this config. + // (3) is why per-worker directories alone cannot fix it: the singletons live + // in the server process, so each worker gets a SERVER of its own (and its own + // data root and settings file — testPaths.ts). Files stay whole per worker + // (fullyParallel: false): a spec's tests share its data in order. fullyParallel: false, - workers: 1, - webServer: [ - { - command: webServerCommand, - url: baseURL, - timeout: 120_000, - reuseExistingServer: !process.env.CI, - env: webServerEnv, - }, - { - // The export server stays `next dev` in both modes. The export is a - // STATIC export (output: "export"): a build bakes test-settings.json and - // the fixture site in at build time, so export-search.spec's settings - // rewrite would be asserted against a page that cannot see it; and the - // two spec files that use this server ran 42 s in all in release 19's - // start-mode run — less than one export build costs. - command: `pnpm --filter export run dev --port ${EXPORT_PORT}`, - url: exportBaseURL, - timeout: 120_000, - reuseExistingServer: !process.env.CI, - env: { - SETTINGS_FILE: exportSettingsFile, - SITES_DIR: exportSitesDir, - SITE_ID: "testsite", - }, - }, - { - command: `node ${path.resolve(process.cwd(), "e2e", "fixtures", "ollama-stub.mjs")}`, - // /api/tags is the same endpoint digestApps.ts probes, so playwright's - // readiness check and the app's own reachability check agree. - url: `http://127.0.0.1:${OLLAMA_STUB_PORT}/api/tags`, - timeout: 30_000, - reuseExistingServer: !process.env.CI, - env: { OLLAMA_STUB_PORT: String(OLLAMA_STUB_PORT) }, - }, - ], + workers: WORKERS, + webServer, use: { baseURL, trace: "on-first-retry", screenshot: "only-on-failure", video: "retain-on-failure", }, - projects: [ - { - name: "chromium", - use: { ...devices["Desktop Chrome"] }, - }, - ], + projects, }); diff --git a/export/next.config.ts b/export/next.config.ts @@ -9,6 +9,12 @@ const nextConfig: NextConfig = { // resolves outside the project and `next dev` fails to boot at all. Nothing // in this repo lives above the monorepo root, so pinning it costs nothing. turbopack: { root: path.join(__dirname, "..") }, + // The editor e2e suite's export dev server builds into `.next/e2e-editor`: + // Next refuses a second `next dev` over one dist dir (`<distDir>/dev/lock`), + // and since release 24 the export suite's own server can run beside it + // (plans/e2e-speed.md S4). Inside the ignored `.next/`, so Tailwind never + // scans it. Unset everywhere else. + distDir: process.env.E2E_NEXT_DIST_DIR || ".next", output: "export", trailingSlash: true, images: { unoptimized: true }, diff --git a/export/package.json b/export/package.json @@ -17,10 +17,10 @@ "start": "node scripts/serve-out.mjs out ${EXPORT_DEV_PORT:-3000}", "lint": "eslint", "test": "tsx --test \"app/**/*.test.ts\"", - "e2e": "node ../scripts/queue-lock.mjs --ports EXPORT_E2E_PORT:3020 -- playwright test", - "e2e:hub": "node ../scripts/queue-lock.mjs --ports HUB_PORT:3041 -- playwright test --config playwright.hub.config.ts", - "e2e:2origin": "node ../scripts/queue-lock.mjs --ports ORIGIN_B_PORT:4610,HUB_A_PORT:4611 -- playwright test --config playwright.2origin.config.ts", - "e2e:report": "node ../scripts/queue-lock.mjs --ports REPORT_SITE_E2E_PORT:3042 -- playwright test --config playwright.report.config.ts", + "e2e": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports EXPORT_E2E_PORT:3020 -- playwright test", + "e2e:hub": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports HUB_PORT:3041 -- playwright test --config playwright.hub.config.ts", + "e2e:2origin": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports ORIGIN_B_PORT:4610,HUB_A_PORT:4611 -- playwright test --config playwright.2origin.config.ts", + "e2e:report": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports REPORT_SITE_E2E_PORT:3042 -- playwright test --config playwright.report.config.ts", "build:report-fixture": "tsx e2e-report/stage.ts", "e2e:ui": "playwright test --ui", "deploy": "tsx ../common/bin/archilyzer.ts deploy site" diff --git a/homepage/package.json b/homepage/package.json @@ -14,7 +14,7 @@ "start": "serve out -l ${HOMEPAGE_PORT:-3031}", "lint": "eslint", "test": "tsx --test \"app/**/*.test.ts\"", - "e2e": "node ../scripts/queue-lock.mjs --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", + "e2e": "node ../scripts/queue-lock.mjs --name e2e-homepage --estimate 1500 --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", "e2e:ui": "playwright test --ui", "deploy": "tsx ../common/bin/archilyzer.ts deploy homepage" }, diff --git a/package.json b/package.json @@ -23,6 +23,7 @@ "heavy": "node scripts/queue-lock.mjs --heavy --", "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", + "e2e:all": "node scripts/e2e-all.mjs", "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", diff --git a/plans/e2e-speed.md b/plans/e2e-speed.md @@ -235,3 +235,128 @@ the reporter (`.git/e2e-timings/umtool/r23_fixes.json`). The first run of the th passed, 9 failed (triage's page check looked for a `link`), 6 skipped — recorded too, which is the point. `E2E_MODE=dev pnpm e2e import-video.spec.ts` 3 passed, 33.9 s; the same in start mode (the editor's e2e build rebuilt through the heavy slot, 42 s) 3 passed, 12.2 s. + +### S4, as shipped (release 24, `r24/e2e-speed`) + +**Each package's suite queues under its own name.** `scripts/queue-lock.mjs --name e2e-<pkg>`: `e2e-editor`, +`e2e-export` (all four export configs — one at a time among themselves), `e2e-homepage`, `e2e-umtool`. The same suite +never runs twice machine-wide; two different suites run at once. The unnamed default `e2e` (the sharded runner) keeps +the one-for-all queue and the old order (the slot, then the queue). A named suite's order: its queue, the port +preflight, its start-mode build (`--prebuild <pkg>` → `e2e-stamp.mjs ensure`, a build admitted as a build, so a +rebuild is never inside the suite's estimate; the config then trusts `E2E_BUILD_CHECKED`), then its own admission. +`E2E_QUEUE_LOCK_FILE` names the legacy queue's file; a named suite's sits beside it (`<file>.<name>`). + +**The heavy slot admits by memory.** A job declares an estimate (`--estimate <MB>`; a `systemd-run … -p MemoryMax=…` +cap is one, so the e2e build is 5120 MB with no change to `e2e-stamp.mjs`; `--build`, or `next build` in the command, +makes it a build) and is admitted while `MemAvailable − Σ(running estimates) ≥ HEAVY_MIN_FREE_MB`. One build at a time +stays hard: a build in line only TRIES the build slot; a build nested in an admitted run waits for it +(`HEAVY_HELD=build` inside a build passes through). Ruled: **a job that declares nothing runs alone**, as before — +renders, a hand `pnpm heavy -- …`, the publish stages' uncapped `next build`, preparePlayable's ffmpeg, the sharded +runner. The pieces, beside the slot's lock in the git common dir: `heavy-queue.lock` (held SHARED by a weighted job, +EXCLUSIVELY by a lone one — so a checkout on older code, which always takes it exclusively, still waits for every +new-style job and is never joined by one), `.admit` (the line; held only until admitted, so nobody slips in while the +head waits for memory), `.build`, `.jobs/<pid>.json` (tickets; pid + start time, a dead one dropped). Every suite's +script declares `--estimate 1500`; the editor's is per worker (`--scale-by E2E_WORKERS`, `auto` = 3). + +**`pnpm e2e:all`** (`scripts/e2e-all.mjs`): one lane per package, all at once, each suite through its own package +script (through `worktree.mjs run`, so a worktree's ports); a line per suite start/end; logs in +`test-results-e2e-all/<suite>.log`; one summary — per suite passed/failed/flaky/skipped from its own json report (only a +report started after this run's launch counts), its test time, how long it waited, every failure by `file:line`; the +wall against the sum. `--only <pkg|suite>,…`. + +**Found on the way.** Next 16 refuses a second `next dev` over one dist dir (`<distDir>/dev/lock`), so the editor +suite's export dev server and the export suite's own could not run at once: `export/next.config.ts` reads +`E2E_NEXT_DIST_DIR` like the editor's, and the editor suite's export server builds into `.next/e2e-editor`. A waiter +killed while it waited (`timeout`, Ctrl-C) left its holder file naming a dead pid: the signal handlers are now installed +before the wait and exit through `process.exit`. + +A build waiting for the build slot keeps its place in line (the suites behind it wait too) — ruled: holding the build +slot while waiting for memory could wait in a cycle with a nested rebuild, and a minute of head-of-line is the cheaper +cost. Verified against the real locks while release 23 gated: a new-style run waits behind an old-style holder +("held by r23-integration … playwright test") and is admitted once it ends; a killed waiter leaves no holder file. + +**Runs** (single specs; the two-suite and whole runs are the orchestrator's): +- `pnpm e2e cookies-mode.spec.ts no-subs-fallback.spec.ts`: 10 passed, 35.9 s. The prebuild built the editor (no stamp + in the worktree yet) as a 5120 MB build through the real slot, 207 s, after 2m34s behind another lane's umtool run; + the suite then waited 3m40s behind an exclusive old-style build, and ran. +- `pnpm --filter umtool run e2e dashboard.spec.ts`: prebuild 25 s (`.next-e2e-start`), 7 passed, 14.2 s. + +### S5a, as shipped (release 24, `r24/e2e-speed`) + +Every spec's test-data paths come from `testPaths()` (`editor/e2e/testPaths.ts`, re-exported by `helpers.ts`): +`transcriptsDir`, `settingsFile`, `exportPublicDir`, `editorChangelog`, `exportChangelog`, under one root. +`dev:test` / `start:test` take the same root as `${E2E_DATA_ROOT:-$(pwd)}`. Ruled: **one E2E_-prefixed root, not +`TRANSCRIPTS_DIR` / `SETTINGS_FILE` from the env** — a `--share-data` worktree's `.worktree-env` sets +`TRANSCRIPTS_DIR` to the real corpus, and `resetData()` deletes the test data directory. Mechanical, by a script over +string literals, then read line by line: `git grep` over `editor/e2e/*.ts` — before, 108 files and 451 literal +occurrences (`test-transcripts` 386, `test-settings.json` 60, `test-changelog.md` 4, `test-export-changelog.md` 1); +after, two in code (`fixturesRoot/test-transcripts/<fixture>`, the fixture SOURCE, rightly literal) and the rest in +comments; 443 `testPaths()` calls in 108 files. Three joins the script could not see were fixed by hand +(`path.join(here, "..", ROOT, …)` in cookies-mode and no-subs-fallback, `exportOutLink.ts`). + +### S5b, as shipped (release 24, `r24/e2e-speed`) — ready to measure + +A server set per worker. With `E2E_WORKERS` > 1 each worker slot has its own editor test server, export dev server and +Ollama stub over its own data root: slot 0 is the config's `webServer` entries over the editor directory, as before; +slot n (`editor/.e2e-workers/w<n>`, gitignored) is started by `globalSetup` on three ports from the unused top of the +worktree's block (`x060 + 3(n−1)`…), refused naming the pid when one is bound, and stopped (the process group, +TERM then KILL) by `globalTeardown`. Ruled: **servers per SLOT from globalSetup, not a worker-scoped fixture** — the +config is evaluated again in every worker with `TEST_PARALLEL_INDEX` set (verified on Playwright 1.59), so +`baseURL`, `PLAYWRIGHT_BASE_URL`, `EXPORT_PORT` and `testPaths()` are the slot's before a spec loads and no spec's +`test` import changes; a restarted worker keeps its slot's servers. One definition of the servers +(`editor/e2e/servers.ts`) serves the config and globalSetup. A second `next dev` gets its own dist dir +(`.next/e2e-dev-w<n>`, `.next/e2e-editor-w<n>`); start-mode slots share the stamped `.next/e2e`. + +`E2E_WORKERS`: a number (≤ 8) or `auto` = floor((MemAvailable − floor) / 1.5 GB), 1 to 3; the runner pins the result +for its workers. Ruled: **the default stays 1** until the full runs at 1, 2 and 3 workers are green — then it becomes +`auto` (one line in `resolveWorkers`). `@serial`: the files in `editor/e2e/serial.ts` — the checkout's build outputs +(`export/out`, `homepage/out`: build, deploy-page, publish, publish-lane, site-publish-preview, sites-crud, +sites-homepage) and timing under contention (pacing, rate-limit, audio-check-scenarios, fetch-window, channel-storage, +storage-locations, whisper) — run in a `serial` project that is the parallel project's `teardown` (Playwright runs a +teardown even when a parallel test failed, where a dependent project would be skipped — verified), on one worker. With +one worker there is one project, as before. 590 tests parallel, 107 serial at `E2E_WORKERS=3` (`--list`). + +Three things the first real two-worker runs found, all fixed: +- **Bad ports.** `next start` refuses 5060 ("reserved for sip"), where this worktree's slot 1 sat (block 50xx). Slot + ports walk up from `x060` past the Fetch standard's bad ports (5060, 5061, 6000, 6665–6669, …). +- **A focused run ran every @serial file.** Playwright applies spec and grep filters to top-level projects only and + runs a `teardown` project whole. The runner decides once from its command line (`isFocusedRun`) and pins it for the + workers (`E2E_SERIAL_LAST`): a whole run keeps the serial project last; a focused one keeps only its one-worker limit. +- **A killed run left its slot servers.** A SIGKILLed runner never reaches globalTeardown, and a slot's servers are + process groups of their own. Each slot now has a detached watchdog that polls the runner and takes the groups down + (TERM, then KILL) once it is gone. (Slot 0's webServer entries leak as they always did; the port preflight catches + them.) + +The editor suite's heavy-slot estimate is per worker (`--scale-by E2E_WORKERS`: 1500 × workers, `auto` as 3). + +**Runs.** `E2E_WORKERS=2 pnpm e2e publish-lane.spec.ts channel-work.spec.ts` (a serial file and a parallel one, both +projects at once on a focused run): `[e2e setup] 2 workers: slots 1–1's servers up in 5s`, 13 passed, 23.6 s, nothing +left running after. An earlier attempt, killed by my 590 s `timeout` while it ran every serial file (the focused-run +bug), had `publish-lane.spec:78` red ("resume publishing" not seen in 5 s after the pause click) — it passed in the +run above; recorded, not yet called a flake. + +**Found on the way.** `playwright test --list` was recorded by release 23 F5's timing reporter as a run (a report whose +tests have no results); it now records nothing. + +| Commit | What | +|---|---| +| `5e44ce89` | S4: per-suite queues, the memory-weighted heavy slot, `--prebuild`, `pnpm e2e:all`, the docs | +| `1c96695b` | S5a: every spec's paths through `testPaths()`; `dev:test`/`start:test` read `E2E_DATA_ROOT` | +| `407be185` | the timing reporter skips `--list` | +| `75cdc23f` | S5b: a server set per worker slot, `E2E_WORKERS`, `e2e/serial.ts` | +| `50b7b26b` | a waiter stopped by a signal cleans up its holder file | +| `d3c5d255` | the editor's estimate × `E2E_WORKERS` | +| `db84b181` | slot ports skip the bad ports | +| `b7718149` | a focused run keeps the serial project top-level | +| `15a9df5d` | `E2E_SERIAL_LAST` declared; `TEST_PARALLEL_INDEX` is Playwright's | +| `d7587aad` | the slot watchdog | + +**Gates.** tsc clean at every code commit (46–108 s). `test:scripts` 788 passed + 3 skipped (791; was 770 + 2 at +release 23 F5): `queue-lock.test` 36 (+15: resolveJob, the admission rule, waitForAdmission, tickets, side by side, +builds never overlap, a lone job, nested builds, named suites, the package scripts' names, `--prebuild`, a signalled +waiter, `--scale-by`), `e2e-all.test` 4 (new), `e2e-timings.test` 11 (the `--list` case). Editor unit 252/252 +(+6, `e2e/servers.unit.ts`). common 3702/3702; `envVars.test` 9/9 (caught `TEST_PARALLEL_INDEX` and +`E2E_SERIAL_LAST`); ENVIRONMENT.md regenerated, `docs env --check` clean. `playwright test --list`: 697 tests in 130 +files at one worker; 590 parallel + 107 serial at `E2E_WORKERS=3`. Not run here, by the brief: the two-suite run, the +whole `pnpm e2e:all`, and the full editor suite at 1, 2 and 3 workers — the orchestrator's (commands in the lane +report). diff --git a/scripts/e2e-all.mjs b/scripts/e2e-all.mjs @@ -0,0 +1,245 @@ +#!/usr/bin/env node +// EVERY E2E SUITE, SIDE BY SIDE, ONE SUMMARY (release 24, plans/e2e-speed.md +// S4) — the release gate's e2e in one command: +// +// pnpm e2e:all [--only editor,umtool] [--logs <dir>] +// +// Each package's suite queues under its own name (`queue-lock.mjs --name +// e2e-<pkg>`), so they no longer wait for one another — only for the heavy +// slot, which admits each by its memory estimate (an e2e suite 1.5 GB; a +// start-mode rebuild is a 5 GB build, one at a time). This starts one LANE per +// package at once; a lane runs its package's suites in order (export has four +// configs, which share one queue). Every suite still goes through its own +// package script, so the queue, the port preflight, the start-mode build and +// every bypass (E2E_QUEUE=0, HEAVY=0, E2E_MODE=dev, …) behave exactly as when +// it is run alone. The wall time becomes the longest lane, not the sum. +// +// Output: one line as each suite starts and ends; each suite's full output in +// `<logs>/<suite>.log` (default `test-results-e2e-all/`, gitignored); then one +// summary — per suite: passed / failed / flaky / skipped from its own json +// report (only a report written by THIS run counts), its wall time, how long +// it waited for the queue and the slot, and every failed test by file:line. +// Exit 0 only when every suite exited 0. +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const SELF = fileURLToPath(import.meta.url); +export const REPO_ROOT = path.resolve(path.dirname(SELF), ".."); +export const DEFAULT_LOG_DIR = "test-results-e2e-all"; + +// The suites, by lane. `report` is the json reporter's outputFile, relative +// to the repo root (each config's `["json", { outputFile }]`). +export const LANES = Object.freeze([ + { pkg: "editor", suites: [{ id: "editor", script: "e2e", report: "editor/test-results/timings.json" }] }, + { + pkg: "export", + suites: [ + { id: "export", script: "e2e", report: "export/test-results/timings.json" }, + { id: "export-hub", script: "e2e:hub", report: "export/test-results-hub/timings.json" }, + { id: "export-2origin", script: "e2e:2origin", report: "export/test-results-2origin/timings.json" }, + { id: "export-report", script: "e2e:report", report: "export/test-results-report/timings.json" }, + ], + }, + { pkg: "homepage", suites: [{ id: "homepage", script: "e2e", report: "homepage/test-results/timings.json" }] }, + { pkg: "umtool", suites: [{ id: "umtool", script: "e2e", report: "umtool/test-results/timings.json" }] }, +]); + +/** The lanes `--only` names (a package, or a suite id); all of them by default. */ +export function selectLanes(only, lanes = LANES) { + if (!only || !only.length) return lanes; + const want = new Set(only); + const out = []; + for (const lane of lanes) { + const suites = want.has(lane.pkg) ? lane.suites : lane.suites.filter((s) => want.has(s.id)); + if (suites.length) out.push({ ...lane, suites }); + } + const known = new Set(lanes.flatMap((l) => [l.pkg, ...l.suites.map((s) => s.id)])); + const unknown = only.filter((o) => !known.has(o)); + if (unknown.length) throw new Error(`e2e:all: no suite named ${unknown.join(", ")} (one of: ${[...known].join(", ")})`); + return out; +} + +/** + * A Playwright json report → counts and failures. `startedAfter` (ms) rejects + * a report left by an earlier run: a suite that died before writing its own + * would otherwise be summarised from last week's. + */ +export function readReport(report, { startedAfter = 0 } = {}) { + if (!report?.stats) return null; + const start = Date.parse(report.stats.startTime ?? ""); + if (startedAfter && !(start >= startedAfter - 1000)) return null; + const failures = []; + const walk = (suite) => { + for (const spec of suite.specs ?? []) { + for (const t of spec.tests ?? []) { + if (t.status === "unexpected") { + failures.push(`${spec.file ?? suite.file ?? "?"}:${spec.line ?? "?"} ${spec.title}`); + } + } + } + for (const child of suite.suites ?? []) walk({ ...child, file: child.file ?? suite.file }); + }; + for (const s of report.suites ?? []) walk(s); + return { + passed: Number(report.stats.expected) || 0, + failed: Number(report.stats.unexpected) || 0, + flaky: Number(report.stats.flaky) || 0, + skipped: Number(report.stats.skipped) || 0, + durationMs: Number(report.stats.duration) || 0, + startMs: Number.isFinite(start) ? start : null, + failures, + }; +} + +export function humanMs(ms) { + if (ms == null || !Number.isFinite(ms)) return "—"; + const s = Math.max(0, Math.round(ms / 1000)); + return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`; +} + +/** + * The summary, from one result per suite: + * `{id, code, launchedMs, endedMs, report: readReport(…)|null, log}`. + */ +export function renderSummary(results, { wallMs } = {}) { + const rows = [["suite", "result", "passed", "failed", "flaky", "skipped", "tests", "waited", "log"]]; + for (const r of results) { + const rep = r.report; + const result = r.code === 0 ? "ok" : rep ? `FAIL (exit ${r.code})` : `FAIL (exit ${r.code}, no report)`; + const waited = rep?.startMs != null && r.launchedMs != null ? rep.startMs - r.launchedMs : null; + rows.push([ + r.id, + result, + rep ? String(rep.passed) : "—", + rep ? String(rep.failed) : "—", + rep ? String(rep.flaky) : "—", + rep ? String(rep.skipped) : "—", + rep ? humanMs(rep.durationMs) : humanMs(r.endedMs - r.launchedMs), + humanMs(waited), + r.log ?? "", + ]); + } + const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length))); + const lines = rows.map((row) => row.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd()); + lines.splice(1, 0, widths.map((w) => "-".repeat(w)).join(" ")); + const total = (k) => results.reduce((n, r) => n + (r.report?.[k] ?? 0), 0); + const sumMs = results.reduce((n, r) => n + (r.report?.durationMs ?? r.endedMs - r.launchedMs), 0); + const ok = results.every((r) => r.code === 0); + lines.push(""); + lines.push( + `e2e:all ${ok ? "PASSED" : "FAILED"} — ${total("passed")} passed, ${total("failed")} failed, ` + + `${total("flaky")} flaky, ${total("skipped")} skipped; wall ${humanMs(wallMs)} ` + + `(the suites' own times add up to ${humanMs(sumMs)})`, + ); + const failed = results.filter((r) => r.report?.failures?.length); + for (const r of failed) { + lines.push(""); + lines.push(`${r.id} — failed:`); + for (const f of r.report.failures.slice(0, 20)) lines.push(` ${f}`); + if (r.report.failures.length > 20) lines.push(` … and ${r.report.failures.length - 20} more`); + } + return `${lines.join("\n")}\n`; +} + +// ------------------------------------------------------------------ the run + +function parseArgs(argv) { + const opts = { only: null, logs: DEFAULT_LOG_DIR }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--only") opts.only = String(argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean); + else if (a === "--logs") opts.logs = argv[++i]; + else if (a === "--help" || a === "-h") opts.help = true; + else throw new Error(`e2e:all: unknown argument '${a}'`); + } + return opts; +} + +const children = new Set(); + +function runSuite(lane, suite, logDir) { + const log = path.join(logDir, `${suite.id}.log`); + const out = fs.openSync(log, "w"); + const launchedMs = Date.now(); + process.stdout.write(`e2e:all: ${suite.id} started (pnpm --filter ${lane.pkg} run ${suite.script}) — ${path.relative(REPO_ROOT, log)}\n`); + // Through the worktree wrapper, so a worktree's suites use its own ports. + const child = spawn( + process.execPath, + [path.join(REPO_ROOT, "scripts", "worktree.mjs"), "run", "--", "pnpm", "--filter", lane.pkg, "run", suite.script], + { cwd: REPO_ROOT, stdio: ["ignore", out, out], env: process.env }, + ); + children.add(child); + return new Promise((resolve) => { + const done = (code) => { + children.delete(child); + fs.closeSync(out); + const endedMs = Date.now(); + let report = null; + try { + report = readReport(JSON.parse(fs.readFileSync(path.join(REPO_ROOT, suite.report), "utf8")), { + startedAfter: launchedMs, + }); + } catch { + /* no report: the suite died before writing one */ + } + const counts = report ? `${report.passed} passed, ${report.failed} failed, ${report.skipped} skipped` : "no report"; + process.stdout.write( + `e2e:all: ${suite.id} ${code === 0 ? "done" : `FAILED (exit ${code})`} in ${humanMs(endedMs - launchedMs)} — ${counts}\n`, + ); + resolve({ id: suite.id, code, launchedMs, endedMs, report, log: path.relative(REPO_ROOT, log) }); + }; + child.on("error", () => done(1)); + child.on("exit", (code, signal) => done(signal ? 1 : (code ?? 1))); + }); +} + +async function runLane(lane, logDir) { + const results = []; + for (const suite of lane.suites) results.push(await runSuite(lane, suite, logDir)); + return results; +} + +async function main(argv) { + const opts = parseArgs(argv); + if (opts.help) { + process.stdout.write("usage: pnpm e2e:all [--only <pkg|suite>,…] [--logs <dir>]\n"); + return 0; + } + const lanes = selectLanes(opts.only); + const logDir = path.resolve(REPO_ROOT, opts.logs); + fs.mkdirSync(logDir, { recursive: true }); + // A terminal's Ctrl-C reaches every suite already (one process group); a + // SIGTERM sent to this process alone is passed on, so nothing is orphaned. + for (const sig of ["SIGTERM", "SIGHUP"]) { + process.on(sig, () => { + for (const c of children) { + try { + c.kill(sig); + } catch { + /* already gone */ + } + } + }); + } + process.on("SIGINT", () => process.stdout.write("\ne2e:all: SIGINT — waiting for the suites to stop\n")); + const t0 = Date.now(); + const results = (await Promise.all(lanes.map((lane) => runLane(lane, logDir)))).flat(); + process.stdout.write(`\n${renderSummary(results, { wallMs: Date.now() - t0 })}`); + for (const r of results.filter((x) => x.code !== 0 && !x.report)) { + const tail = fs.readFileSync(path.join(REPO_ROOT, r.log), "utf8").trimEnd().split("\n").slice(-12); + process.stdout.write(`\n${r.id} — last lines of ${r.log}:\n${tail.map((l) => ` ${l}`).join("\n")}\n`); + } + return results.every((r) => r.code === 0) ? 0 : 1; +} + +if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF)) { + main(process.argv.slice(2)).then( + (code) => process.exit(code), + (err) => { + process.stderr.write(`${err?.message ?? err}\n`); + process.exit(2); + }, + ); +} diff --git a/scripts/e2e-all.test.mjs b/scripts/e2e-all.test.mjs @@ -0,0 +1,84 @@ +// Tests for `pnpm e2e:all` (scripts/e2e-all.mjs): which suites, what a report +// says, and the one summary. The run itself is the suites' own scripts. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { LANES, REPO_ROOT, readReport, renderSummary, selectLanes } from "./e2e-all.mjs"; + +test("every lane names its package's real e2e scripts and their json reports", () => { + for (const lane of LANES) { + const scripts = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, lane.pkg, "package.json"), "utf8")).scripts; + for (const s of lane.suites) { + assert.ok(scripts[s.script]?.includes("queue-lock.mjs"), `${lane.pkg} run ${s.script} is not a queued suite`); + const config = /--config (\S+)/.exec(scripts[s.script])?.[1] ?? "playwright.config.ts"; + const text = fs.readFileSync(path.join(REPO_ROOT, lane.pkg, config), "utf8"); + const out = path.relative(lane.pkg, s.report); + assert.ok(text.includes(`["json", { outputFile: "${out}" }]`), `${lane.pkg}/${config} does not write ${out}`); + } + } + // Every queued e2e script of every package is in a lane. + for (const pkg of ["editor", "export", "homepage", "umtool"]) { + const scripts = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, pkg, "package.json"), "utf8")).scripts; + const queued = Object.keys(scripts).filter((k) => scripts[k].includes("queue-lock.mjs")); + const lane = LANES.find((l) => l.pkg === pkg); + assert.deepEqual(lane.suites.map((s) => s.script).sort(), queued.sort(), pkg); + } +}); + +test("--only picks packages or single suites, and refuses a name it does not know", () => { + assert.deepEqual(selectLanes(null).map((l) => l.pkg), ["editor", "export", "homepage", "umtool"]); + assert.deepEqual( + selectLanes(["umtool", "export-hub"]).map((l) => [l.pkg, l.suites.map((s) => s.id)]), + [["export", ["export-hub"]], ["umtool", ["umtool"]]], + ); + assert.throws(() => selectLanes(["editr"]), /no suite named editr/); +}); + +const report = (over = {}) => ({ + stats: { startTime: "2026-10-10T10:00:00.000Z", duration: 125_000, expected: 10, unexpected: 1, flaky: 1, skipped: 2, ...over }, + suites: [ + { + file: "a.spec.ts", + specs: [{ title: "passes", file: "a.spec.ts", line: 3, tests: [{ status: "expected" }] }], + suites: [{ specs: [{ title: "breaks", file: "a.spec.ts", line: 9, tests: [{ status: "unexpected" }] }] }], + }, + ], +}); + +test("readReport counts, lists failures by file:line, and rejects an earlier run's report", () => { + const r = readReport(report()); + assert.deepEqual( + { ...r, failures: r.failures }, + { + passed: 10, + failed: 1, + flaky: 1, + skipped: 2, + durationMs: 125_000, + startMs: Date.parse("2026-10-10T10:00:00.000Z"), + failures: ["a.spec.ts:9 breaks"], + }, + ); + assert.equal(readReport(report(), { startedAfter: Date.parse("2026-10-10T11:00:00.000Z") }), null); + assert.ok(readReport(report(), { startedAfter: Date.parse("2026-10-10T09:59:00.000Z") })); + assert.equal(readReport({}), null); +}); + +test("the summary: one row per suite, totals, the wall against the sum, and the failures", () => { + const launched = Date.parse("2026-10-10T09:58:00.000Z"); + const out = renderSummary( + [ + { id: "editor", code: 1, launchedMs: launched, endedMs: launched + 300_000, report: readReport(report()), log: "test-results-e2e-all/editor.log" }, + { id: "homepage", code: 0, launchedMs: launched, endedMs: launched + 60_000, report: readReport(report({ unexpected: 0, flaky: 0 })), log: "h.log" }, + { id: "umtool", code: 1, launchedMs: launched, endedMs: launched + 20_000, report: null, log: "u.log" }, + ], + { wallMs: 300_000 }, + ); + assert.match(out, /^suite\s+result\s+passed\s+failed\s+flaky\s+skipped\s+tests\s+waited\s+log$/m); + assert.match(out, /^editor\s+FAIL \(exit 1\)\s+10\s+1\s+1\s+2\s+2m05s\s+2m00s\s+test-results-e2e-all\/editor\.log$/m); + assert.match(out, /^homepage\s+ok\s+10\s+0\s+0\s+2\s+2m05s/m); + assert.match(out, /^umtool\s+FAIL \(exit 1, no report\)\s+—\s+—\s+—\s+—\s+20s\s+—\s+u\.log$/m); + assert.match(out, /e2e:all FAILED — 20 passed, 1 failed, 1 flaky, 4 skipped; wall 5m00s \(the suites' own times add up to 4m30s\)/); + assert.match(out, /editor — failed:\n {2}a\.spec\.ts:9 breaks/); +}); diff --git a/scripts/e2e-stamp.mjs b/scripts/e2e-stamp.mjs @@ -20,9 +20,11 @@ // // THE BUILD GOES THROUGH THE HEAVY SLOT under a 5 GB cap (AGENTS.md, "Heavy // work takes the heavy slot"): `queue-lock.mjs --heavy -- systemd-run --user -// --scope -p MemoryMax=5G -p MemorySwapMax=0 …`. Inside an e2e run the slot is -// already this run's (HEAVY_HELD), so it passes through; run by hand it waits -// for the slot and the memory floor like any build. +// --scope -p MemoryMax=5G -p MemorySwapMax=0 …`, its cap its estimate: admitted +// beside running e2e suites when memory allows, never beside another build. A +// suite's `queue-lock.mjs --prebuild` runs `ensure` before the suite's own +// admission (release 24); a rebuild from inside a running suite (the config's +// check, the tree moved since) waits only for the build slot. // // IT BUILDS INTO ITS OWN DIRECTORY, never `.next`: the primary checkout's // `.next` is what the live editor and umtool serve from, and replacing it under diff --git a/scripts/e2e-timings-reporter.mjs b/scripts/e2e-timings-reporter.mjs @@ -16,8 +16,8 @@ // its own run's json. // // It never fails a run: a report it cannot read or a history it cannot write -// is one line on stderr. A run with no tests (`--list`, a filter that matched -// nothing) records nothing. +// is one line on stderr. A run where no test ran (`--list`, whose report lists +// tests with no results, or a filter that matched nothing) records nothing. // // reporter: [["list"], ["json", { outputFile: "test-results/timings.json" }], // ["../scripts/e2e-timings-reporter.mjs", { outputFile: "test-results/timings.json" }]] @@ -51,7 +51,7 @@ export default class E2eTimingsReporter { top: this.options.top ?? 10, skipEmpty: true, }); - if (out.run.totals.tests === 0) return; + if (!out.lines.length) return; // nothing ran (`--list`, an empty filter) process.stdout.write(`\n${out.lines.join("\n")}\n${out.note ? `${out.note}\n` : ""}`); } catch (err) { process.stderr.write(`e2e-timings: not recorded (${err?.code ?? err?.message ?? err})\n`); diff --git a/scripts/e2e-timings.mjs b/scripts/e2e-timings.mjs @@ -72,6 +72,14 @@ export function summarize(report) { }; } +/** Whether any test in a Playwright JSON report has a result (it ran). */ +export function anyResults(report) { + const walk = (suite) => + (suite.specs ?? []).some((spec) => (spec.tests ?? []).some((t) => (t.results ?? []).length > 0)) || + (suite.suites ?? []).some(walk); + return (report.suites ?? []).some(walk); +} + // ------------------------------------------------------------------ history function gitOut(args, cwd) { @@ -222,7 +230,10 @@ export function recordReport(report, opts = {}) { const branch = opts.branch ?? gitOut(["rev-parse", "--abbrev-ref", "HEAD"], cwd) ?? "unknown"; const head = gitOut(["rev-parse", "HEAD"], cwd); const run = { ...summarize(json), head }; - if (opts.skipEmpty && run.totals.tests === 0) return { lines: [], note: "", recorded: false, run }; + // `--list` writes a report whose tests never ran (no results): not a run. + if (opts.skipEmpty && (run.totals.tests === 0 || !anyResults(json))) { + return { lines: [], note: "", recorded: false, run }; + } const dir = opts.historyDir ?? defaultHistoryDir(cwd); let earlier = []; let note = ""; diff --git a/scripts/e2e-timings.test.mjs b/scripts/e2e-timings.test.mjs @@ -196,6 +196,16 @@ test("recordReport records a run once; an empty run is neither recorded nor rend const empty = recordReport(file, { historyDir: hist, branch: "r23/x", skipEmpty: true }); assert.deepEqual([empty.recorded, empty.lines], [false, []]); assert.equal(readHistory(historyFile(hist, "editor", "r23/x")).length, 1); + + // `playwright test --list` writes every test with no results: nothing ran. + const listed = { + stats: { startTime: "2026-10-10T18:06:29.075Z", duration: 2914 }, + suites: [{ file: "a.spec.ts", specs: [{ title: "t", file: "a.spec.ts", tests: [{ status: "skipped", results: [] }] }] }], + }; + fs.writeFileSync(file, JSON.stringify(listed)); + const list = recordReport(file, { historyDir: hist, branch: "r23/x", skipEmpty: true }); + assert.deepEqual([list.recorded, list.lines], [false, []]); + assert.equal(readHistory(historyFile(hist, "editor", "r23/x")).length, 1); }); test("the reporter records at onExit: a full run, then a re-run of one spec, are BOTH in the history", async () => { diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs @@ -1,38 +1,52 @@ #!/usr/bin/env node -// Global e2e queue: exactly one e2e run at a time, machine-wide — and the -// HEAVY SLOT: one heavy job (an e2e run, a `next build`, a video render) at a -// time, machine-wide, started only above a free-memory floor. +// Global e2e queue: one run of each e2e SUITE at a time, machine-wide — and +// the HEAVY SLOT: heavy jobs (an e2e run, a `next build`, a video render) +// admitted by memory, one build at a time, machine-wide. // -// Every checkout of this repo shares one lock file, so a suite started in a -// second worktree waits for the first to finish instead of racing it. That is -// both a resource decision (the serial suite is ~24 min and e2e:sharded fans -// out to 4 containers) and a correctness one: playwright.config's +// Every checkout of this repo shares one lock file per suite, so a suite +// started in a second worktree waits for the first to finish instead of racing +// it. Each package's suite queues under its own name (`--name e2e-editor`, +// `e2e-export`, `e2e-homepage`, `e2e-umtool`; release 24, plans/e2e-speed.md +// S4): their ports (common/lib/ports.mjs) and fixtures are disjoint, so two +// DIFFERENT suites run side by side, and the same suite never runs twice. The +// unnamed default (`e2e`, the sharded runner) keeps the old one-for-all queue. +// The queue is also a correctness lock: playwright.config's // `reuseExistingServer: !CI` means a second run that finds port 3011 already // bound silently drives the *other* worktree's test server, and resetData() // then wipes that session's fixtures with no error at all. // -// node scripts/queue-lock.mjs [--name e2e] [--ports PORT:3011,...] -- <cmd...> -// node scripts/queue-lock.mjs --heavy -- <cmd...> (`pnpm heavy -- <cmd>`) +// node scripts/queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] +// [--ports PORT:3011,...] -- <cmd...> +// node scripts/queue-lock.mjs --heavy [--estimate <MB>] [--build] -- <cmd...> +// (`pnpm heavy -- <cmd>`) // // THE HEAVY SLOT. Two OOMs on this machine (2026-10-08) took Xwayland and dbus // with them: two `next build`s, or a build beside an e2e suite, or a render -// beside either. So every heavy entry point goes through `withHeavy`: one -// machine-wide lock (`heavy-queue.lock`, beside the e2e one), and once it is -// held, a wait until /proc/meminfo's MemAvailable is at least -// HEAVY_MIN_FREE_MB (6000 by default). The slot is taken FIRST, then the floor -// is waited for, so a later contender cannot slip in while the holder waits -// for memory. Callers: +// beside either. So every heavy entry point goes through `withHeavy`, which +// waits in one machine-wide line and admits a job by its declared memory (see +// "the weighted admission" below): a job with an estimate runs beside others +// while MemAvailable − Σ(running estimates) ≥ HEAVY_MIN_FREE_MB (6000 by +// default) and no other build runs; a job with none runs ALONE once +// MemAvailable is at least the floor, as every heavy job did before. Callers: // - every e2e entry point (this file's CLI and run-sharded-e2e.mjs, through -// `withQueue`): the heavy slot first, then the e2e queue. One order -// everywhere, so nesting cannot deadlock: an e2e run holds both, and a -// `pnpm heavy -- pnpm e2e` passes through its own slot (HEAVY_HELD). -// - the publish stages' `next build` (common/publish/build.ts, heavyGated). -// - a render: `pnpm heavy -- node umtool/report-to-video/build-video.mjs …`. +// `withQueue`): a named suite takes its queue, builds what it serves +// (`--prebuild`), then is admitted with its `--estimate` (1500 MB in the +// package scripts). The legacy `e2e` name takes the slot first, then the +// queue. A command run inside the slot that starts another heavy one +// passes through (HEAVY_HELD) — except a build, which still takes the +// build slot. +// - the publish stages' `next build` (common/publish/build.ts, heavyGated): +// uncapped, so alone. +// - the e2e build (scripts/e2e-stamp.mjs): capped at 5 GB by systemd-run, +// and a cap is an estimate — a build beside suites, never beside a build. +// - a render: `pnpm heavy -- node umtool/report-to-video/build-video.mjs …`: +// alone. // Bypasses: HEAVY=0 (no slot, no floor), HEAVY_MIN_FREE_MB=0 (no floor), // HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue; // the floor still applies. A machine whose MemTotal is under the floor is not -// made to wait forever: it is told, and runs. The slot is a safety net, not a -// correctness lock: with no usable `flock` it warns and runs on the floor alone. +// made to wait forever: it is told, and runs one job at a time. The slot is a +// safety net, not a correctness lock: with no usable `flock` it warns and runs +// on the floor alone. // // WHY THE LOCK IS HELD BY A SEPARATE CHILD. // flock(1) deliberately keeps its lock fd open across exec — that is what the @@ -98,6 +112,15 @@ function parseArgv(argv) { portSpec: null, hold: false, heavy: false, + // The heavy slot's admission (S4): a job's memory estimate in MB, whether + // it is a `next build`, and the package whose e2e build to ensure first. + // Unset means "infer from the command" (resolveJob). + estimateMb: undefined, + // `--scale-by E2E_WORKERS`: the estimate is per worker, times that + // variable's number of workers (`auto`: the editor's cap, 3). + scaleBy: null, + build: undefined, + prebuild: null, // Unset unless --timeout: the e2e queue defaults it from E2E_QUEUE_TIMEOUT, // the heavy slot from HEAVY_TIMEOUT. timeoutMs: undefined, @@ -111,6 +134,16 @@ function parseArgv(argv) { else if (f === "--ports") opts.portSpec = flags[++i]; else if (f === "--timeout") opts.timeoutMs = Number(flags[++i]) * 1000; else if (f === "--port-grace") opts.portGraceMs = Number(flags[++i]); + else if (f === "--estimate") { + opts.estimateMb = Number(flags[++i]); + if (!(opts.estimateMb > 0)) { + process.stderr.write(`queue-lock: --estimate wants a size in MB, not '${flags[i]}'\n`); + process.exit(2); + } + } + else if (f === "--build") opts.build = true; + else if (f === "--scale-by") opts.scaleBy = flags[++i]; + else if (f === "--prebuild") opts.prebuild = flags[++i]; else { process.stderr.write(`queue-lock: unknown flag '${f}'\n`); process.exit(2); @@ -172,7 +205,9 @@ function lockFileFor(name) { name === HEAVY_NAME ? process.env.HEAVY_LOCK_FILE : process.env.E2E_QUEUE_LOCK_FILE; - if (override) return override; + // The queue's override names the legacy queue's file; a named suite's sits + // beside it (`<file>.e2e-editor`), so the tests can run two suites at once. + if (override) return name === HEAVY_NAME || name === "e2e" ? override : `${override}.${name}`; const dir = gitOut(["rev-parse", "--path-format=absolute", "--git-common-dir"]) ?? os.tmpdir(); @@ -266,11 +301,17 @@ function runHolder() { // ------------------------------------------------------------ acquire/release -function flockArgs(lock, timeoutMs) { +function flockArgs(lock, timeoutMs, { shared = false, nonblock = false } = {}) { // -F/--no-fork execs directly, so the spawned process IS the holder and we // can talk to it over its own stdio. const args = ["-F"]; - if (timeoutMs > 0) { + // -s: a SHARED hold of the heavy slot, which is how a weighted job runs + // beside others while an exclusive one (an undeclared job, or a run of an + // older copy of this file, which takes it exclusively) waits for them all. + if (shared) args.push("-s"); + if (nonblock) { + args.push("-n", "-E", String(PROBE_HELD_EXIT)); + } else if (timeoutMs > 0) { args.push("-w", String(Math.ceil(timeoutMs / 1000)), "-E", String(WAIT_TIMEOUT_EXIT)); } args.push(lock, process.execPath, SELF, "--hold"); @@ -279,9 +320,10 @@ function flockArgs(lock, timeoutMs) { // Non-blocking probe, purely so the banner can name who is ahead of us. A // false "free" here is harmless: the blocking acquire below is the real gate. -function isHeld(lock) { +function isHeld(lock, { shared = false } = {}) { try { - execFileSync("flock", ["-n", "-E", String(PROBE_HELD_EXIT), lock, "true"], { + const mode = shared ? ["-s"] : []; + execFileSync("flock", [...mode, "-n", "-E", String(PROBE_HELD_EXIT), lock, "true"], { stdio: "ignore", }); return false; @@ -298,8 +340,8 @@ function missingFlock() { ); } -function acquire(lock, timeoutMs) { - const holder = spawn("flock", flockArgs(lock, timeoutMs), { +function acquire(lock, timeoutMs, mode = {}) { + const holder = spawn("flock", flockArgs(lock, timeoutMs, mode), { stdio: ["pipe", "pipe", "inherit"], }); return new Promise((resolve, reject) => { @@ -329,6 +371,8 @@ function acquire(lock, timeoutMs) { } if (code === WAIT_TIMEOUT_EXIT) { reject(Object.assign(new Error("queue-lock: timed out waiting"), { timeout: true })); + } else if (code === PROBE_HELD_EXIT && mode.nonblock) { + reject(Object.assign(new Error("queue-lock: held"), { busy: true })); } else { reject(new Error(`queue-lock: flock exited ${code} before acquiring`)); } @@ -457,20 +501,23 @@ async function preflight(ports, graceMs) { // ---------------------------------------------------------------- run + wait -function runCommand(cmd, name, { forwardTerm = false } = {}) { +function runCommand(cmd, name, { forwardTerm = false, env = null } = {}) { return new Promise((resolve) => { const child = spawn(cmd[0], cmd.slice(1), { stdio: "inherit", // A heavy-only run (name null) leaves QUEUE_LOCK_HELD alone: it holds no // e2e queue for a nested e2e run to pass through. - env: name ? { ...process.env, [HELD_ENV]: name } : { ...process.env }, + env: env ?? (name ? { ...process.env, [HELD_ENV]: name } : { ...process.env }), }); - installSignalHandlers(() => child, forwardTerm); + activeChild = child; + activeForwardTerm = forwardTerm; + installSignalHandlers(); child.on("error", (err) => { process.stderr.write(`queue-lock: ${err.message}\n`); resolve(1); }); child.on("exit", (code, signal) => { + if (activeChild === child) activeChild = null; // Never re-raise onto ourselves the way worktree.mjs's cmdRun does: we // have handlers installed, so re-raising would loop. resolve(signal ? 128 + (os.constants.signals[signal] ?? 0) : (code ?? 1)); @@ -478,19 +525,30 @@ function runCommand(cmd, name, { forwardTerm = false } = {}) { }); } +// One set of handlers per process, whatever it runs in turn (an e2e run's +// build first, then its suite): installing them per child would count one +// Ctrl-C twice, and the second count is "force". let signalHits = 0; +let activeChild = null; +let activeForwardTerm = false; +let handlersInstalled = false; // `forwardTerm`: a heavy-slot run is usually started by a PROCESS, not a // terminal — a publish stage whose Cancel SIGTERMs this wrapper alone, then // SIGKILLs it, which would orphan the `next build` under it. So a heavy run // passes SIGTERM/SIGHUP on to its command (a terminal's SIGINT already reached // the whole group, and is still never forwarded). -function installSignalHandlers(getChild, forwardTerm = false) { +function installSignalHandlers() { + if (handlersInstalled) return; + handlersInstalled = true; for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) { process.on(sig, () => { + const child = activeChild; + // Between two commands (waiting for the heavy slot after an e2e run's + // build) there is nothing to wait for: stop, as an unhandled signal would. + if (!child) process.exit(128 + (os.constants.signals[sig] ?? 0)); signalHits++; - const child = getChild(); if (signalHits === 1) { - if (forwardTerm && sig !== "SIGINT") { + if (activeForwardTerm && sig !== "SIGINT") { try { child?.kill(sig); } catch { @@ -519,9 +577,9 @@ function installSignalHandlers(getChild, forwardTerm = false) { function startWaitBanner(lock, what = E2E_LOCK) { const t0 = Date.now(); + const who = what.describe ? what.describe() : describeHolder(lock, what.showCmd); process.stderr.write( - `queue-lock: waiting for ${what.label} — held by ${describeHolder(lock, what.showCmd)}\n` + - ` ${what.hint}\n`, + `queue-lock: waiting for ${what.label} — held by ${who}\n` + ` ${what.hint}\n`, ); const timer = setInterval(() => { process.stderr.write( @@ -537,11 +595,11 @@ function startWaitBanner(lock, what = E2E_LOCK) { }; } -// ------------------------------------------------------------ the two locks +// ------------------------------------------------------------ the locks const E2E_LOCK = { label: "the e2e queue", - hint: "(one e2e run at a time, machine-wide; E2E_QUEUE=0 to bypass)", + hint: "(one run of each e2e suite at a time, machine-wide; E2E_QUEUE=0 to bypass)", timeoutHint: "Raise or unset E2E_QUEUE_TIMEOUT, or set E2E_QUEUE=0 to bypass the queue.", showCmd: false, @@ -550,21 +608,31 @@ const E2E_LOCK = { const HEAVY_LOCK = { label: "the heavy slot", hint: - "(one heavy job — an e2e run, a next build, a render — at a time, machine-wide; HEAVY=0 to bypass)", + "(heavy jobs — e2e runs, next builds, renders — are admitted by memory, one build at a time, machine-wide; HEAVY=0 to bypass)", + timeoutHint: "Raise or unset HEAVY_TIMEOUT, or set HEAVY=0 to bypass the heavy slot.", + showCmd: true, +}; + +const BUILD_LOCK = { + label: "the build slot", + hint: "(one next build at a time, machine-wide; HEAVY=0 to bypass)", timeoutHint: "Raise or unset HEAVY_TIMEOUT, or set HEAVY=0 to bypass the heavy slot.", showCmd: true, }; // Take `lock`, announcing whom we wait behind; returns the release function. // A timeout exits EXIT_TIMEOUT, as it always has for the e2e queue. -async function holdLock(lock, name, cmd, timeoutMs, what) { +// `mode.shared` takes it shared (the heavy slot, for a weighted job); +// `mode.nonblock` returns null at once when it is held. +async function holdLock(lock, name, cmd, timeoutMs, what, mode = {}) { let stopBanner = null; - if (isHeld(lock)) stopBanner = startWaitBanner(lock, what); + if (!mode.nonblock && isHeld(lock, mode)) stopBanner = startWaitBanner(lock, what); let holder; try { - holder = await acquire(lock, timeoutMs); + holder = await acquire(lock, timeoutMs, mode); } catch (err) { + if (err.busy) return null; if (err.timeout) { process.stderr.write( `\nqueue-lock: gave up after ${humanDuration(timeoutMs)} waiting for ${lock}\n` + @@ -576,13 +644,20 @@ async function holdLock(lock, name, cmd, timeoutMs, what) { } stopBanner?.(); + // A shared hold has company: the file names the newest holder (an older + // copy of this script reads it to say whom it waits behind), and only the + // run that wrote it removes it. const holderFile = writeHolderJson(lock, name, cmd); - const cleanup = () => { + const dropHolderFile = () => { try { - fs.rmSync(holderFile, { force: true }); + const info = JSON.parse(fs.readFileSync(holderFile, "utf8")); + if (info.pid === process.pid) fs.rmSync(holderFile, { force: true }); } catch { /* best effort */ } + }; + const cleanup = () => { + dropHolderFile(); try { holder.kill("SIGKILL"); } catch { @@ -592,11 +667,7 @@ async function holdLock(lock, name, cmd, timeoutMs, what) { process.on("exit", cleanup); return async () => { process.off("exit", cleanup); - try { - fs.rmSync(holderFile, { force: true }); - } catch { - /* best effort */ - } + dropHolderFile(); await release(holder); }; } @@ -714,54 +785,439 @@ async function memoryFloorOrExit(timeoutMs) { } } -// ------------------------------------------------------------ the entry points +// ------------------------------------------------- the weighted admission (S4) +// +// The heavy slot was ONE job at a time. Since release 24 it admits by memory: +// a job declares an estimate (an e2e suite ~1.5 GB, a capped `next build` its +// 5 GB cap) and is admitted while +// +// MemAvailable − Σ(estimates of the jobs already running) ≥ HEAVY_MIN_FREE_MB +// +// and, for a build, while no other build runs (one `next build` at a time stays +// a hard rule). A job that declares nothing runs ALONE, exactly as before — a +// render, a hand `pnpm heavy -- …`, an uncapped publish build. The two OOMs the +// slot exists for were builds and renders, not suites. +// +// The pieces, all beside the heavy lock (`<git-common-dir>/heavy-queue.lock`): +// heavy-queue.lock the slot itself. A weighted job holds it SHARED, an +// exclusive one EXCLUSIVELY — so an exclusive job (or +// a run of an older copy of this file, which always +// took it exclusively) waits for every weighted job, +// and none is admitted beside it. +// heavy-queue.lock.admit the line: one contender at a time decides, and keeps +// its place while it waits for memory, so a later one +// cannot slip in. Held only until admitted. +// heavy-queue.lock.build the build slot, held for a build's whole run. A +// build in line only TRIES it (never waits on it while +// holding the line); a build nested in an admitted run +// (an e2e config's stale-stamp rebuild) waits for it. +// heavy-queue.lock.jobs/ one ticket per running job, `<pid>.json`: its +// estimate, whether it builds, what it is. A ticket +// whose process is gone is stale and is dropped. +// Nothing an admitted job holds is waited on by another admitted job, and the +// line is only ever waited on by contenders holding nothing the running jobs +// need — so the order cannot deadlock. + +export const DEFAULT_BUILD_ESTIMATE_MB = 5000; +export const DEFAULT_E2E_ESTIMATE_MB = 1500; + +function admitLockFor(heavyLock) { + return `${heavyLock}.admit`; +} +function buildLockFor(heavyLock) { + return `${heavyLock}.build`; +} +function jobsDirFor(heavyLock) { + return `${heavyLock}.jobs`; +} + +// `systemd-run … -p MemoryMax=5G …` → 5120; none → null. +export function memoryCapMb(cmd = []) { + const units = { "": 1 / (1024 * 1024), K: 1 / 1024, M: 1, G: 1024, T: 1024 * 1024 }; + for (const arg of cmd) { + const m = /MemoryMax=(\d+(?:\.\d+)?)([KMGT]?)$/i.exec(String(arg)); + if (m) return Math.round(Number(m[1]) * units[m[2].toUpperCase()]); + } + return null; +} + +// `… next build …`, by the words (pnpm exec next build, node_modules/.bin/next build). +export function isNextBuild(cmd = []) { + return cmd.some( + (arg, i) => path.basename(String(arg)) === "next" && cmd[i + 1] === "build", + ); +} /** - * Run `fn` in the heavy slot: one heavy job machine-wide, started only once - * MemAvailable is at or above the floor. `opts.cmd` names the work in the - * holder file (what a waiter is told it waits behind). + * What a heavy job is, for admission: `{estimateMb, build, exclusive}`. + * An explicit estimate wins; else the command's memory cap is its estimate. + * A declared build (`--build`) with neither is 5 GB. Anything with no estimate + * is exclusive — it runs alone, as every heavy job did before release 24. */ -export async function withHeavy(opts, fn) { - if (process.env.HEAVY === "0" || process.env[HEAVY_HELD_ENV]) return fn(); - const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs("HEAVY_TIMEOUT"); - const cmd = opts.cmd ?? [HEAVY_NAME]; +export function resolveJob({ estimateMb, build } = {}, cmd = []) { + const isBuild = build ?? isNextBuild(cmd); + let est = Number(estimateMb) > 0 ? Number(estimateMb) : memoryCapMb(cmd); + if (est == null && build === true) est = DEFAULT_BUILD_ESTIMATE_MB; + if (est == null) return { estimateMb: null, build: isBuild, exclusive: true }; + return { estimateMb: est, build: isBuild, exclusive: false }; +} + +/** + * The admission rule, pure. `running` is the live tickets of the OTHER jobs; + * `mem` is `{availableMb, totalMb}` or null. Returns `{admit, reservedMb, …}` + * and, when not admitted, what it waits for: "build" (another build runs), + * "memory" (the headroom is under the floor), "serial" (a machine whose + * MemTotal is under the floor runs one job at a time, as it always did). + */ +export function admissionDecision({ mem, minMb, running = [], job }) { + const reservedMb = running.reduce((n, r) => n + (Number(r.estimateMb) || 0), 0); + const base = { reservedMb, runningCount: running.length }; + if (job.build && running.some((r) => r.build)) return { ...base, admit: false, wait: "build" }; + if (running.some((r) => r.exclusive)) return { ...base, admit: false, wait: "exclusive" }; + if (!(minMb > 0)) return { ...base, admit: true, why: "floor-off" }; + if (!mem) return { ...base, admit: true, why: "unreadable" }; + if (mem.totalMb < minMb) { + return running.length + ? { ...base, admit: false, wait: "serial" } + : { ...base, admit: true, why: "total" }; + } + const headroomMb = mem.availableMb - reservedMb; + return headroomMb >= minMb + ? { ...base, admit: true, headroomMb } + : { ...base, admit: false, wait: "memory", headroomMb }; +} + +// /proc/<pid>/stat's start time (field 22), so a reused pid is not mistaken +// for the job that wrote a ticket. Null off Linux. +function pidStartTime(pid) { + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); + return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null; + } catch { + return null; + } +} - let releaseSlot = null; +function ticketAlive(t) { try { - releaseSlot = await holdLock( - lockFileFor(HEAVY_NAME), - HEAVY_NAME, - cmd, - timeoutMs, - HEAVY_LOCK, + process.kill(t.pid, 0); + } catch (err) { + if (err.code !== "EPERM") return false; + } + return t.pidStart == null || pidStartTime(t.pid) === t.pidStart; +} + +/** The live tickets in `dir` (a stale one is removed); `isAlive` is the tests' seam. */ +export function readTickets(dir, { isAlive = ticketAlive, exceptPid = null } = {}) { + let names; + try { + names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")); + } catch { + return []; + } + const live = []; + for (const n of names) { + const file = path.join(dir, n); + let t; + try { + t = JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + continue; // half-written by a peer, or not ours: never fatal + } + if (!Number.isInteger(t.pid)) continue; + if (!isAlive(t)) { + try { + fs.rmSync(file, { force: true }); + } catch { + /* best effort */ + } + continue; + } + if (t.pid !== exceptPid) live.push(t); + } + return live; +} + +function writeTicket(dir, job, cmd) { + const info = { + pid: process.pid, + pidStart: pidStartTime(process.pid), + estimateMb: job.estimateMb, + build: Boolean(job.build), + exclusive: Boolean(job.exclusive), + worktree: gitOut(["rev-parse", "--show-toplevel"]) ?? process.cwd(), + branch: gitOut(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "?", + cmd: cmd.join(" "), + startedAt: new Date().toISOString(), + }; + const file = path.join(dir, `${process.pid}.json`); + try { + fs.mkdirSync(dir, { recursive: true }); + const tmp = `${file}.tmp`; + fs.writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`); + fs.renameSync(tmp, file); + } catch { + /* informational for the arithmetic — a missing ticket undercounts, never blocks */ + } + const drop = () => { + try { + fs.rmSync(file, { force: true }); + } catch { + /* best effort */ + } + }; + process.on("exit", drop); + return () => { + process.off("exit", drop); + drop(); + }; +} + +function describeTicket(t) { + const where = t.worktree ? path.basename(t.worktree) : "?"; + const age = t.startedAt ? ` for ${humanAge(Date.parse(t.startedAt))}` : ""; + const est = `${t.estimateMb ? `, ${t.estimateMb} MB` : t.exclusive ? ", alone" : ""}${t.build ? ", a build" : ""}`; + return `${where} (${t.branch}, pid ${t.pid}${est})${age}: ${String(t.cmd ?? "").slice(0, 100)}`; +} + +// Whom the slot is held by: the running jobs' tickets, or (a run of an older +// copy of this file, which writes no ticket) the lock's holder file. +function describeSlot(heavyLock, { exceptPid = process.pid } = {}) { + const tickets = readTickets(jobsDirFor(heavyLock), { exceptPid }); + if (!tickets.length) return describeHolder(heavyLock, true); + const shown = tickets.slice(0, 3).map(describeTicket).join("; "); + return tickets.length > 3 ? `${shown}; and ${tickets.length - 3} more` : shown; +} + +function plural(n, one, many = `${one}s`) { + return `${n} ${n === 1 ? one : many}`; +} + +/** + * Wait in line until `job` is admitted (admissionDecision), then — for a + * build — take the build slot. Every input is injectable for the unit tests. + * Resolves `{decision, waitedMs, releaseBuild}`; throws `{timeout: true}` past + * `timeoutMs` (0 = never). + */ +export async function waitForAdmission({ + job, + minMb = minFreeMb(), + read = readMeminfo, + tickets = () => [], + tryBuild = async () => async () => {}, + describe = () => "", + pollMs = memPollMs(), + tickMs = TICK_MS, + timeoutMs = 0, + log = (line) => process.stderr.write(line), + now = Date.now, + sleep = (ms) => new Promise((r) => setTimeout(r, ms)), +}) { + const t0 = now(); + let lastTick = t0; + let lastWait = null; + for (;;) { + const running = tickets(); + const mem = read(); + let d = admissionDecision({ mem, minMb, running, job }); + let releaseBuild = null; + if (d.admit && job.build) { + releaseBuild = await tryBuild(); + if (!releaseBuild) d = { ...d, admit: false, wait: "build" }; + } + const waited = now() - t0; + if (d.admit) { + if (lastWait) { + log(`heavy: ${mem?.availableMb ?? "?"} MB available after ${humanDuration(waited)} — admitted\n`); + } else if (d.runningCount) { + log( + `heavy: admitted beside ${plural(d.runningCount, "running job")} ` + + `(${mem?.availableMb ?? "?"} MB available, ${d.reservedMb} MB promised to them, the floor is ${minMb} MB)\n`, + ); + } + return { decision: d, waitedMs: waited, releaseBuild }; + } + if (d.wait !== lastWait) { + lastWait = d.wait; + log(waitLine(d, mem, minMb, describe)); + } else if (now() - lastTick >= tickMs) { + lastTick = now(); + log(`heavy: still waiting (${d.wait}, ${humanDuration(waited)}; ${mem?.availableMb ?? "?"} MB available)\n`); + } + if (timeoutMs > 0 && waited >= timeoutMs) { + throw Object.assign( + new Error(`heavy: gave up after ${humanDuration(waited)} waiting to be admitted (${d.wait})`), + { timeout: true }, + ); + } + await sleep(pollMs); + } +} + +function waitLine(d, mem, minMb, describe) { + const who = describe(); + if (d.wait === "build") { + return `heavy: waiting for the build slot — one next build at a time; running: ${who}\n`; + } + if (d.wait === "exclusive") return `heavy: waiting for a job that runs alone: ${who}\n`; + if (d.wait === "serial") { + return ( + `heavy: this machine has ${mem.totalMb} MB in all, under the ${minMb} MB floor — ` + + `one heavy job at a time; waiting for: ${who}\n` ); + } + const promised = d.reservedMb + ? `, ${d.reservedMb} MB promised to ${plural(d.runningCount, "running job")}` + : ""; + return ( + `heavy: waiting for memory — ${mem.availableMb} MB available${promised}, the floor is ${minMb} MB\n` + + (d.reservedMb ? ` running: ${who}\n` : "") + + " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)\n" + ); +} + +async function admitOrExit(opts) { + try { + return await waitForAdmission(opts); } catch (err) { - // No usable flock (a container image without util-linux): the slot is a - // safety net, so run on the floor alone rather than not at all. + if (!err.timeout) throw err; process.stderr.write( - `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, + `\n${err.message}\n Raise or unset the timeout, lower HEAVY_MIN_FREE_MB, or set HEAVY=0.\n`, ); + process.exit(EXIT_TIMEOUT); } +} + +// ------------------------------------------------------------ the entry points + +/** + * Run `fn` in the heavy slot. `opts.estimateMb` / `opts.build` declare the job + * (resolveJob; inferred from `opts.cmd` when unset): a weighted job is admitted + * by memory beside others, an undeclared one runs alone once MemAvailable is at + * or above the floor. `opts.cmd` names the work (what a waiter is told). + */ +export async function withHeavy(opts, fn) { + if (process.env.HEAVY === "0") return fn(); + const cmd = opts.cmd ?? [HEAVY_NAME]; + const job = resolveJob(opts, cmd); + const heavyLock = lockFileFor(HEAVY_NAME); + const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs("HEAVY_TIMEOUT"); + + // Inside an admitted run: pass through — except a build, which still waits + // for the build slot (one build at a time is hard), and says so. + if (process.env[HEAVY_HELD_ENV]) { + // A build inside a build already holds the build slot (HEAVY_HELD=build). + if (!job.build || process.env[HEAVY_HELD_ENV] === "build") return fn(); + let releaseBuild = null; + try { + releaseBuild = await holdLock(buildLockFor(heavyLock), "heavy-build", cmd, timeoutMs, { + ...BUILD_LOCK, + describe: () => describeHolder(buildLockFor(heavyLock), true), + }); + } catch (err) { + process.stderr.write(`heavy: the build slot is not held (${err?.message ?? err})\n`); + } + const dropTicket = writeTicket(jobsDirFor(heavyLock), job, cmd); + const outer = process.env[HEAVY_HELD_ENV]; + process.env[HEAVY_HELD_ENV] = "build"; + try { + return await fn(); + } finally { + process.env[HEAVY_HELD_ENV] = outer; + dropTicket(); + await releaseBuild?.(); + } + } + + const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0; + const remaining = () => (deadline ? Math.max(1000, deadline - Date.now()) : 0); + const releases = []; try { - await memoryFloorOrExit(timeoutMs); - process.env[HEAVY_HELD_ENV] = "1"; + let releaseLine = null; + try { + releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, timeoutMs, { + ...HEAVY_LOCK, + describe: () => + `${describeSlot(heavyLock)}; next in line: ${describeHolder(admitLockFor(heavyLock), true)}`, + }); + } catch (err) { + // No usable flock (a container image without util-linux): the slot is a + // safety net, so run on the floor alone rather than not at all. + process.stderr.write( + `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, + ); + await memoryFloorOrExit(timeoutMs); + process.env[HEAVY_HELD_ENV] = "1"; + return await fn(); + } + try { + const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) }; + if (job.exclusive) { + releases.push(await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait)); + await memoryFloorOrExit(remaining()); + } else { + releases.push( + await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait, { shared: true }), + ); + const { releaseBuild } = await admitOrExit({ + job, + timeoutMs: remaining(), + tickets: () => readTickets(jobsDirFor(heavyLock), { exceptPid: process.pid }), + describe: () => describeSlot(heavyLock), + tryBuild: () => + holdLock(buildLockFor(heavyLock), "heavy-build", cmd, 0, BUILD_LOCK, { nonblock: true }), + }); + if (releaseBuild) releases.push(releaseBuild); + } + releases.push(writeTicket(jobsDirFor(heavyLock), job, cmd)); + } finally { + await releaseLine(); + } + process.env[HEAVY_HELD_ENV] = job.build ? "build" : "1"; return await fn(); } finally { delete process.env[HEAVY_HELD_ENV]; - await releaseSlot?.(); + for (const release of releases.reverse()) await release(); } } +// How many server sets a suite runs: `--scale-by E2E_WORKERS` reads the +// editor suite's worker count (a number; `auto` counts as its cap, 3 — +// editor/e2e/servers.ts — since the count is decided after admission). +export function workerScale(envVar, env = process.env) { + if (!envVar) return 1; + const raw = String(env[envVar] ?? "").trim().toLowerCase(); + if (raw === "auto") return 3; + const n = Number(raw); + return Number.isInteger(n) && n > 1 ? Math.min(n, 8) : 1; +} + +// The default queue name, and the one older copies of this file use. A run +// under it keeps the old order — the heavy slot first, then the queue — so it +// can never wait in a cycle with an older run that holds the slot and waits +// for this queue. +export const LEGACY_QUEUE_NAME = "e2e"; + /** * Run `fn` with the global queue lock held, after checking `ports` are free. * Used both by the CLI below and directly by scripts/run-sharded-e2e.mjs. - * Unless `opts.heavySlot === false`, the run takes the heavy slot first. + * Unless `opts.heavySlot === false`, the run takes the heavy slot too. + * + * A NAMED suite (`--name e2e-<pkg>`) takes its own queue first — the same + * suite never runs twice, different suites run side by side — then builds what + * it serves (`opts.prebuild`, scripts/e2e-stamp.mjs, a build admitted as one), + * then is admitted to the heavy slot with its estimate. */ export async function withQueue(opts, fn) { - const name = opts.name ?? "e2e"; + const name = opts.name ?? LEGACY_QUEUE_NAME; const ports = parsePorts(opts.portSpec ?? null); const graceMs = opts.portGraceMs ?? Number(process.env.E2E_PORT_GRACE_MS ?? DEFAULT_PORT_GRACE_MS); const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs(); + const heavyOpts = { + timeoutMs, + cmd: opts.cmd ?? [name], + estimateMb: opts.estimateMb && opts.estimateMb * workerScale(opts.scaleBy), + }; // A nested invocation: the parent holds the queue (and the slot) already. if (process.env[HELD_ENV] === name) { @@ -779,39 +1235,67 @@ export async function withQueue(opts, fn) { return fn(); } - const queued = async () => { - const releaseQueue = await holdLock( - lockFileFor(name), - name, - opts.cmd ?? [name], - timeoutMs, - E2E_LOCK, - ); - try { - await preflight(ports, graceMs); - return await fn(); - } finally { - await releaseQueue(); + const holdQueue = () => + holdLock(lockFileFor(name), name, opts.cmd ?? [name], timeoutMs, E2E_LOCK); + + if (name === LEGACY_QUEUE_NAME) { + const queued = async () => { + const releaseQueue = await holdQueue(); + try { + await preflight(ports, graceMs); + return await fn(); + } finally { + await releaseQueue(); + } + }; + return opts.heavySlot === false ? queued() : withHeavy(heavyOpts, queued); + } + + const releaseQueue = await holdQueue(); + try { + await preflight(ports, graceMs); + if (opts.prebuild) { + const code = await prebuild(opts.prebuild); + if (code !== 0) return code; } - }; - if (opts.heavySlot === false) return queued(); - return withHeavy({ timeoutMs, cmd: opts.cmd ?? [name] }, queued); + return opts.heavySlot === false ? await fn() : await withHeavy(heavyOpts, fn); + } finally { + await releaseQueue(); + } +} + +// The suite's start-mode build, BEFORE its own admission: a rebuild is a build +// (5 GB, one at a time), not part of the suite's 1.5 GB. The playwright config +// then finds the stamp fresh and does not check again (E2E_BUILD_CHECKED). +// CI (the sharded image) builds its own `.next` and is left alone. +async function prebuild(pkg) { + if (process.env.CI) return 0; + const stamp = path.join(path.dirname(SELF), "e2e-stamp.mjs"); + const env = { ...process.env }; + delete env[HEAVY_HELD_ENV]; + const code = await runCommand([process.execPath, stamp, "ensure", pkg], null, { env }); + if (code === 0) process.env.E2E_BUILD_CHECKED = "1"; + else process.stderr.write(`queue-lock: the ${pkg} e2e build failed (exit ${code}) — not running the suite\n`); + return code; } async function main() { const { opts, cmd: rawCmd } = parseArgv(process.argv.slice(2)); if (opts.hold) return runHolder(); + // While waiting (no command yet) a signal exits through process.exit, so the + // 'exit' cleanups run: no holder file is left naming a dead waiter. + installSignalHandlers(); // `pnpm heavy -- <cmd>` may hand the separator through as the first word. const cmd = opts.heavy && rawCmd[0] === "--" ? rawCmd.slice(1) : rawCmd; if (cmd.length === 0) { process.stderr.write( - "usage: queue-lock.mjs [--name e2e] [--ports PORT:3011,...] -- <cmd...>\n" + - " queue-lock.mjs --heavy [--timeout <s>] -- <cmd...>\n", + "usage: queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] [--ports PORT:3011,...] -- <cmd...>\n" + + " queue-lock.mjs --heavy [--estimate <MB>] [--build] [--timeout <s>] -- <cmd...>\n", ); process.exit(2); } const code = opts.heavy - ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd }, () => + ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build }, () => runCommand(cmd, null, { forwardTerm: true }), ) : await withQueue({ ...opts, cmd }, () => runCommand(cmd, opts.name)); diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -13,7 +13,17 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { parseMeminfo, waitForMemory } from "./queue-lock.mjs"; +import { + admissionDecision, + isNextBuild, + memoryCapMb, + parseMeminfo, + readTickets, + resolveJob, + workerScale, + waitForAdmission, + waitForMemory, +} from "./queue-lock.mjs"; const SCRIPT = fileURLToPath(new URL("./queue-lock.mjs", import.meta.url)); @@ -490,3 +500,291 @@ test("SIGTERM to a heavy wrapper alone stops its command (a stage's Cancel)", as assert.equal(res.code, 128 + os.constants.signals.SIGTERM); assert.throws(() => process.kill(cmdPid, 0), "the command survived the wrapper's SIGTERM"); }); + +// ------------------------------------------- the weighted admission (release 24) + +test("resolveJob: an estimate wins, a cap is an estimate, an undeclared job runs alone", () => { + assert.deepEqual(resolveJob({ estimateMb: 1500 }, ["playwright", "test"]), { + estimateMb: 1500, + build: false, + exclusive: false, + }); + const capped = ["systemd-run", "--user", "--scope", "-q", "-p", "MemoryMax=5G", "-p", "MemorySwapMax=0", + "pnpm", "--filter", "editor", "exec", "next", "build"]; + assert.deepEqual(resolveJob({}, capped), { estimateMb: 5120, build: true, exclusive: false }); + // A publish stage's build is uncapped: alone, as before. + assert.deepEqual(resolveJob({}, ["pnpm", "exec", "next", "build"]), { estimateMb: null, build: true, exclusive: true }); + assert.deepEqual(resolveJob({ build: true }, ["make"]), { estimateMb: 5000, build: true, exclusive: false }); + assert.deepEqual(resolveJob({}, ["node", "build-video.mjs"]), { estimateMb: null, build: false, exclusive: true }); + assert.equal(memoryCapMb(["-p", "MemoryMax=512M"]), 512); + assert.equal(memoryCapMb(["MemoryMax=2.5G"]), 2560); + assert.equal(memoryCapMb(["MemoryMax=infinity"]), null); + assert.equal(isNextBuild(["/x/node_modules/.bin/next", "build"]), true); + assert.equal(isNextBuild(["next", "start"]), false); +}); + +test("admissionDecision: MemAvailable − Σ(running estimates) ≥ floor; one build at a time", () => { + const mem = (availableMb, totalMb = 16_000) => ({ availableMb, totalMb }); + const suite = { estimateMb: 1500, build: false, exclusive: false }; + const build = { estimateMb: 5000, build: true, exclusive: false }; + assert.equal(admissionDecision({ mem: mem(9000), minMb: 6000, running: [], job: suite }).admit, true); + const two = [{ estimateMb: 1500 }, { estimateMb: 1500 }]; + assert.deepEqual(admissionDecision({ mem: mem(9000), minMb: 6000, running: two, job: suite }), { + reservedMb: 3000, + runningCount: 2, + admit: true, + headroomMb: 6000, + }); + const d = admissionDecision({ mem: mem(8999), minMb: 6000, running: two, job: suite }); + assert.equal(d.admit, false); + assert.equal(d.wait, "memory"); + // A build beside a suite is a memory question; beside a build, never. + assert.equal(admissionDecision({ mem: mem(20_000), minMb: 6000, running: [{ estimateMb: 1500 }], job: build }).admit, true); + assert.equal( + admissionDecision({ mem: mem(20_000), minMb: 6000, running: [{ estimateMb: 5000, build: true }], job: build }).wait, + "build", + ); + // A suite beside a build is fine when memory is. + assert.equal( + admissionDecision({ mem: mem(20_000), minMb: 6000, running: [{ estimateMb: 5000, build: true }], job: suite }).admit, + true, + ); + // Floor off, meminfo unreadable: admitted (the build rule still holds). + assert.equal(admissionDecision({ mem: mem(10), minMb: 0, running: two, job: suite }).admit, true); + assert.equal(admissionDecision({ mem: null, minMb: 6000, running: two, job: suite }).admit, true); + assert.equal( + admissionDecision({ mem: null, minMb: 6000, running: [{ estimateMb: 5000, build: true }], job: build }).admit, + false, + ); + // A machine under the floor in all runs one job at a time, as it always did. + assert.equal(admissionDecision({ mem: mem(3000, 4000), minMb: 6000, running: [], job: suite }).admit, true); + assert.equal(admissionDecision({ mem: mem(3000, 4000), minMb: 6000, running: two, job: suite }).wait, "serial"); +}); + +test("waitForAdmission waits while the headroom is short, then admits; a build waits for the build slot", async () => { + let clock = 0; + const lines = []; + const common = { + minMb: 6000, + pollMs: 1000, + tickMs: 60_000, + log: (l) => lines.push(l), + now: () => clock, + sleep: async (ms) => { + clock += ms; + }, + describe: () => "wt (main, pid 1, 1500 MB): playwright test", + }; + const runningSets = [[{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }]]; + const res = await waitForAdmission({ + ...common, + job: { estimateMb: 1500, build: false, exclusive: false }, + read: () => ({ availableMb: 8000, totalMb: 16_000 }), + tickets: () => runningSets.shift() ?? [], + }); + assert.equal(res.waitedMs, 2000); + assert.match(lines[0], /waiting for memory — 8000 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB/); + assert.match(lines.at(-1), /8000 MB available after 2s — admitted/); + + lines.length = 0; + clock = 0; + let tries = 0; + const built = await waitForAdmission({ + ...common, + job: { estimateMb: 5000, build: true, exclusive: false }, + read: () => ({ availableMb: 20_000, totalMb: 32_000 }), + tickets: () => [], + tryBuild: async () => (++tries < 3 ? null : async () => {}), + }); + assert.equal(tries, 3); + assert.equal(typeof built.releaseBuild, "function"); + assert.match(lines[0], /waiting for the build slot — one next build at a time/); + + clock = 0; + await assert.rejects( + waitForAdmission({ + ...common, + timeoutMs: 3000, + job: { estimateMb: 1500, build: false, exclusive: false }, + read: () => ({ availableMb: 1000, totalMb: 16_000 }), + }), + (err) => err.timeout === true, + ); +}); + +test("readTickets keeps the live and drops the stale", () => { + const dir = tmpDir(); + fs.writeFileSync(path.join(dir, "1.json"), JSON.stringify({ pid: 1, estimateMb: 1500 })); + fs.writeFileSync(path.join(dir, "2.json"), JSON.stringify({ pid: 2, estimateMb: 5000, build: true })); + fs.writeFileSync(path.join(dir, "3.json"), "{half-writ"); + const live = readTickets(dir, { isAlive: (t) => t.pid === 2 }); + assert.deepEqual(live.map((t) => t.pid), [2]); + assert.equal(fs.existsSync(path.join(dir, "1.json")), false, "a stale ticket is removed"); + assert.equal(fs.existsSync(path.join(dir, "3.json")), true, "an unreadable one is left alone"); + assert.deepEqual(readTickets(path.join(dir, "absent")), []); +}); + +// Both ran at once: the second started before the first ended. +function overlapped(order) { + return /^S\wS\w/.test(order); +} + +test("two weighted jobs run side by side; a third waits for headroom, named in the banner", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + meminfo(env.HEAVY_MEMINFO_FILE, 8000); + const jobs = path.join(dir, "heavy.lock.jobs"); + const tickets = () => (fs.existsSync(jobs) ? fs.readdirSync(jobs).filter((n) => n.endsWith(".json")).length : 0); + const a = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "a", 1500)], env); + await until(() => tickets() === 1); + const b = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "b", 1500)], env); + await until(() => tickets() === 2); + const c = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "c", 50)], env); + await c.waitFor(/waiting for memory — 8000 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB/); + const [ra, rb, rc] = await Promise.all([a.done, b.done, c.done]); + assert.equal(ra.code, 0, ra.stderr); + assert.equal(rb.code, 0, rb.stderr); + assert.equal(rc.code, 0, rc.stderr); + const order = fs.readFileSync(log, "utf8"); + assert.ok(overlapped(order), `a and b did not overlap: ${order}`); + assert.ok(order.indexOf("Sc") > Math.min(order.indexOf("Ea"), order.indexOf("Eb")), `c started too soon: ${order}`); + assert.match(rb.stderr, /admitted beside 1 running job/); + assert.match(rc.stderr, /admitted/); + assert.equal(tickets(), 0, "every ticket is removed at the end"); +}); + +test("two builds never overlap, whatever the memory; the second waits for the build slot", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const first = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "1", 600)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.build.holder.json`)); + const second = await runLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "2", 50)], env); + assert.equal((await first.done).code, 0); + assert.equal(second.code, 0, second.stderr); + assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); + assert.match(second.stderr, /waiting for the build slot — one next build at a time; running: .*pid \d+, 100 MB, a build\)/); +}); + +test("an undeclared job runs alone: it waits for the weighted ones, and none starts beside it", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const weighted = startLock(["--heavy", "--estimate", "100", "--", ...markerCmd(log, "w", 600)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.jobs`) && fs.readdirSync(`${env.HEAVY_LOCK_FILE}.jobs`).length > 0); + const alone = startLock(["--heavy", "--", ...markerCmd(log, "x", 600)], env); + await alone.waitFor(/waiting for the heavy slot — held by .*pid \d+, 100 MB/); + const later = startLock(["--heavy", "--estimate", "100", "--", ...markerCmd(log, "l", 50)], env); + for (const r of await Promise.all([weighted.done, alone.done, later.done])) assert.equal(r.code, 0, r.stderr); + assert.equal(fs.readFileSync(log, "utf8"), "SwEwSxExSlEl"); +}); + +test("a build nested in an admitted run waits for the build slot (one build at a time is hard)", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const outer = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "1", 700)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.build.holder.json`)); + // The shape of an e2e config's rebuild inside a running suite: HEAVY_HELD set. + const nested = await runLock(["--heavy", "--build", "--", ...markerCmd(log, "2", 50)], { ...env, HEAVY_HELD: "1" }); + assert.equal(nested.code, 0, nested.stderr); + await outer.done; + assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); + assert.match(nested.stderr, /waiting for the build slot/); + // A build inside a build (HEAVY_HELD=build) already holds the slot: through. + const outer2 = startLock(["--heavy", "--build", "--estimate", "100", "--", "sh", "-c", + `${JSON.stringify(process.execPath)} ${JSON.stringify(SCRIPT)} --heavy --build -- true && echo inner-ok`], env); + const r2 = await outer2.done; + assert.equal(r2.code, 0, r2.stderr); + assert.match(r2.stdout, /inner-ok/); + // A nested non-build still passes straight through. + const t0 = Date.now(); + assert.equal((await runLock(["--heavy", "--", "true"], { ...env, HEAVY_HELD: "1" })).code, 0); + assert.ok(Date.now() - t0 < 3000); +}); + +test("named suites run side by side; the same suite never runs twice", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") }); + const suite = (name, id, ms) => + startLock(["--name", name, "--estimate", "100", "--", ...markerCmd(log, id, ms)], env); + const a = suite("e2e-editor", "a", 900); + await until(() => fs.existsSync(path.join(dir, "q.lock.e2e-editor.holder.json"))); + const b = suite("e2e-umtool", "b", 900); + const order = () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8") : ""); + await until(() => order().includes("Sb") || order().includes("Ea")); + const again = suite("e2e-editor", "c", 50); + await again.waitFor(/waiting for the e2e queue — held by .*pid \d+/); + for (const r of await Promise.all([a.done, b.done, again.done])) assert.equal(r.code, 0, r.stderr); + const ran = order(); + assert.ok(overlapped(ran), `editor and umtool did not overlap: ${ran}`); + assert.ok(ran.indexOf("Sc") > ran.indexOf("Ea"), `the second editor run overlapped the first: ${ran}`); +}); + +test("every package's e2e scripts queue under the package's own name, with an estimate", () => { + const root = path.resolve(path.dirname(SCRIPT), ".."); + const seen = new Map(); + for (const pkg of ["editor", "export", "homepage", "umtool"]) { + const scripts = JSON.parse(fs.readFileSync(path.join(root, pkg, "package.json"), "utf8")).scripts; + const queued = Object.entries(scripts).filter(([, cmd]) => cmd.includes("queue-lock.mjs")); + assert.ok(queued.length > 0, `${pkg} has no queued e2e script`); + for (const [name, cmd] of queued) { + assert.match(cmd, new RegExp(`--name e2e-${pkg} `), `${pkg}'s ${name} does not queue as e2e-${pkg}`); + assert.match(cmd, /--estimate \d+ /, `${pkg}'s ${name} declares no estimate`); + seen.set(`e2e-${pkg}`, pkg); + } + // The start-mode suites build before their admission. + if (pkg === "editor" || pkg === "umtool") assert.match(scripts.e2e, new RegExp(`--prebuild ${pkg} `)); + } + assert.equal(seen.size, 4); +}); + +test("--prebuild ensures the suite's build before its admission, and the config is told", async () => { + const dir = tmpDir(); + const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock"), E2E_MODE: "dev" }); + const cmd = [process.execPath, "-e", "console.log('checked=' + process.env.E2E_BUILD_CHECKED)"]; + // E2E_MODE=dev: `ensure` builds nothing (no test may build the real editor). + const ok = await runLock(["--name", "e2e-x", "--estimate", "100", "--prebuild", "editor", "--", ...cmd], env); + assert.equal(ok.code, 0, ok.stderr); + assert.match(ok.stderr, /E2E_MODE=dev — editor runs under next dev, no build/); + assert.match(ok.stdout, /checked=1/); + // A failed build (here: no such package) stops the run before the suite. + const bad = await runLock(["--name", "e2e-x", "--estimate", "100", "--prebuild", "nope", "--", ...cmd], env); + assert.notEqual(bad.code, 0); + assert.doesNotMatch(bad.stdout, /checked=/); + assert.match(bad.stderr, /the nope e2e build failed/); +}); + +test("a waiter stopped by SIGTERM leaves no holder file behind", async () => { + const dir = tmpDir(); + const env = heavyEnv(dir); + const first = startLock(["--heavy", "--", process.execPath, "-e", "setTimeout(()=>{},1500)"], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`)); + const waiter = startLock(["--heavy", "--", "true"], env); + await waiter.waitFor(/waiting for the heavy slot/); + assert.ok(fs.existsSync(`${env.HEAVY_LOCK_FILE}.admit.holder.json`), "the waiter holds the line"); + waiter.child.kill("SIGTERM"); + const res = await waiter.done; + assert.equal(res.code, 128 + os.constants.signals.SIGTERM); + assert.equal(fs.existsSync(`${env.HEAVY_LOCK_FILE}.admit.holder.json`), false); + assert.equal((await first.done).code, 0); +}); + +test("--scale-by: an estimate per worker, times the editor suite's E2E_WORKERS", async () => { + assert.equal(workerScale(null, { E2E_WORKERS: "3" }), 1); + assert.equal(workerScale("E2E_WORKERS", {}), 1); + assert.equal(workerScale("E2E_WORKERS", { E2E_WORKERS: "2" }), 2); + assert.equal(workerScale("E2E_WORKERS", { E2E_WORKERS: "auto" }), 3); + assert.equal(workerScale("E2E_WORKERS", { E2E_WORKERS: "99" }), 8); + const dir = tmpDir(); + const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock"), E2E_WORKERS: "3" }); + const jobs = path.join(dir, "heavy.lock.jobs"); + const cmd = [process.execPath, "-e", "setTimeout(()=>{},400)"]; + const run = startLock(["--name", "e2e-x", "--estimate", "1500", "--scale-by", "E2E_WORKERS", "--", ...cmd], env); + await until(() => fs.existsSync(jobs) && fs.readdirSync(jobs).some((n) => n.endsWith(".json"))); + const ticket = JSON.parse(fs.readFileSync(path.join(jobs, fs.readdirSync(jobs).find((n) => n.endsWith(".json"))), "utf8")); + assert.equal(ticket.estimateMb, 4500); + assert.equal((await run.done).code, 0); +}); diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" + "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { "class-variance-authority": "^0.7.1",