Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Prevent Playwright dev-server port collisions (#5567)
Nick Gomez28085df6f6fa
diff --git a/packages/app/package.json b/packages/app/package.jsonindex 7715dd9a5..4ac252e40 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -37,7 +37,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/external-link-cue.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts",+ "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/external-link-cue.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/qa019-suffix-precedence.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/harness-port-ownership.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.e2e.ts tests/stress/audit-409-console-record.e2e.ts tests/stress/pagelist-refresh-lifetime.e2e.ts tests/stress/list-keymap.e2e.ts tests/stress/okignore-settings.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/playwright.config.ts b/packages/app/playwright.config.tsindex 7584b4d1e..68cdcb7d2 100644--- a/packages/app/playwright.config.ts+++ b/packages/app/playwright.config.ts@@ -5,9 +5,9 @@ import { SETUP_NON_RESULT_REPORTER } from './tests/stress/_helpers/setup-non-res/*** Per-worker server isolation: there is no `webServer` block — instead a* worker-scoped fixture at `tests/stress/_helpers/fixtures.ts`. Each- * Playwright worker spawns its own `pnpm run dev` process on a- * kernel-allocated port + unique tmpdir, eliminating the cross-worker CPU- * contention that created a structural flake class under shared webServer.+ * Playwright worker spawns its own `pnpm run dev` process with a unique+ * tmpdir, eliminating the cross-worker CPU contention that created a+ * structural flake class under shared webServer.** Per-test `baseURL` comes from the `baseURL` fixture in `fixtures.ts`, which* reads the worker's `workerServer.baseURL`. Consumers usediff --git a/packages/app/src/build/test-server-startup-contract.ts b/packages/app/src/build/test-server-startup-contract.tsnew file mode 100644index 000000000..4ef65f135--- /dev/null+++ b/packages/app/src/build/test-server-startup-contract.ts@@ -0,0 +1,27 @@+export const TEST_SERVER_STARTUP_ENV = 'OK_TEST_VITE_START_REQUEST';+export const TEST_SERVER_IDENTITY_PATH = '/__ok-test-server-identity';+export const TEST_SERVER_CANDIDATE_PORTS = { start: 49152, end: 57344 } as const;+export const TEST_SERVER_HOST_FAMILY = {+ '127.0.0.1': 'IPv4',+ '::1': 'IPv6',+} as const satisfies Record<string, 'IPv4' | 'IPv6'>;++type TestServerHost = keyof typeof TEST_SERVER_HOST_FAMILY;++export function isTestServerHost(value: unknown): value is TestServerHost {+ return typeof value === 'string' && Object.hasOwn(TEST_SERVER_HOST_FAMILY, value);+}++export interface TestServerStartupRequest {+ nonce: string;+ host: TestServerHost;+ candidatePort: number;+ receiptPath: string;+}++export interface TestServerStartupReceipt {+ nonce: string;+ address: string;+ family: (typeof TEST_SERVER_HOST_FAMILY)[TestServerHost];+ port: number;+}diff --git a/packages/app/src/build/test-server-startup-plugin.ts b/packages/app/src/build/test-server-startup-plugin.tsnew file mode 100644index 000000000..499529e66--- /dev/null+++ b/packages/app/src/build/test-server-startup-plugin.ts@@ -0,0 +1,116 @@+import { randomUUID } from 'node:crypto';+import { existsSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import type { AddressInfo } from 'node:net';+import { isAbsolute } from 'node:path';+import type { Plugin } from 'vite';++import {+ isTestServerHost,+ TEST_SERVER_CANDIDATE_PORTS,+ TEST_SERVER_HOST_FAMILY,+ TEST_SERVER_IDENTITY_PATH,+ TEST_SERVER_STARTUP_ENV,+ type TestServerStartupReceipt,+ type TestServerStartupRequest,+} from './test-server-startup-contract';++export function parseTestServerStartupRequest(+ raw: string | undefined,+): TestServerStartupRequest | undefined {+ if (raw === undefined) return undefined;+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch (error) {+ throw new Error(`${TEST_SERVER_STARTUP_ENV} is not valid JSON`, { cause: error });+ }+ if (typeof value !== 'object' || value === null) {+ throw new Error(`${TEST_SERVER_STARTUP_ENV} is not a JSON object`);+ }+ const request = value as Record<string, unknown>;+ if (+ typeof request.nonce !== 'string' ||+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.nonce)+ ) {+ throw new Error(`${TEST_SERVER_STARTUP_ENV} nonce is not a lowercase UUID`);+ }+ if (!isTestServerHost(request.host)) {+ throw new Error(+ `${TEST_SERVER_STARTUP_ENV} host is not one of ${Object.keys(TEST_SERVER_HOST_FAMILY).join(', ')}`,+ );+ }+ if (+ typeof request.candidatePort !== 'number' ||+ !Number.isInteger(request.candidatePort) ||+ request.candidatePort < TEST_SERVER_CANDIDATE_PORTS.start ||+ request.candidatePort >= TEST_SERVER_CANDIDATE_PORTS.end+ ) {+ throw new Error(+ `${TEST_SERVER_STARTUP_ENV} candidatePort is not an integer from ${TEST_SERVER_CANDIDATE_PORTS.start} to ${TEST_SERVER_CANDIDATE_PORTS.end - 1}`,+ );+ }+ if (typeof request.receiptPath !== 'string' || !isAbsolute(request.receiptPath)) {+ throw new Error(`${TEST_SERVER_STARTUP_ENV} receiptPath is not an absolute path`);+ }+ return {+ nonce: request.nonce,+ host: request.host,+ candidatePort: request.candidatePort,+ receiptPath: request.receiptPath,+ };+}++function boundReceipt(+ request: TestServerStartupRequest,+ address: string | AddressInfo | null,+): TestServerStartupReceipt {+ if (+ typeof address !== 'object' ||+ address === null ||+ address.address !== request.host ||+ address.family !== TEST_SERVER_HOST_FAMILY[request.host]+ ) {+ throw new Error('automatic Vite startup bound an unexpected address');+ }+ return {+ nonce: request.nonce,+ address: address.address,+ family: TEST_SERVER_HOST_FAMILY[request.host],+ port: address.port,+ };+}++export function testServerStartupPlugin(request: TestServerStartupRequest): Plugin {+ return {+ name: 'ok:test-server-startup',+ apply: 'serve',+ configureServer(server) {+ const httpServer = server.httpServer;+ if (httpServer === null) {+ throw new Error('automatic Vite startup needs an HTTP server');+ }+ if (server.config.server.host !== request.host) {+ throw new Error('automatic Vite startup host differs from its request');+ }+ server.middlewares.use(TEST_SERVER_IDENTITY_PATH, (_req, res) => {+ const receipt = boundReceipt(request, httpServer.address());+ res.setHeader('Content-Type', 'application/json');+ res.setHeader('Cache-Control', 'no-store');+ res.end(JSON.stringify(receipt));+ });+ httpServer.once('listening', () => {+ const receipt = boundReceipt(request, httpServer.address());+ if (existsSync(request.receiptPath)) {+ throw new Error('automatic Vite startup receipt already exists');+ }+ const temporaryPath = `${request.receiptPath}.${process.pid}.${randomUUID()}`;+ try {+ writeFileSync(temporaryPath, JSON.stringify(receipt), { flag: 'wx', mode: 0o600 });+ renameSync(temporaryPath, request.receiptPath);+ } finally {+ rmSync(temporaryPath, { force: true });+ }+ });+ },+ };+}diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.tsindex 86bb69369..20dbc5b1c 100644--- a/packages/app/tests/integration/e2e-stop-rules.test.ts+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts@@ -108,6 +108,9 @@ const DEV_SERVER_SPAWN_SITES = [] as const;const NON_DEV_SERVER_SPAWN_SITES = ['packages/app/tests/stress/_helpers/i18n-catalog-freshness.ts',+ 'packages/app/tests/stress/_helpers/port-ownership/lifetime-global-setup.ts',+ 'packages/app/tests/stress/_helpers/port-ownership/owner-loss.test-helper.ts',+ 'packages/app/tests/stress/_helpers/port-ownership/run-case.test-helper.ts','packages/app/tests/stress/okf-generated-index-settings.e2e.ts',] as const;const PINNED_SPAWN_SITES = [...DEV_SERVER_SPAWN_SITES, ...NON_DEV_SERVER_SPAWN_SITES].sort();diff --git a/packages/app/tests/meta/port-ownership-lifetime.test.ts b/packages/app/tests/meta/port-ownership-lifetime.test.tsnew file mode 100644index 000000000..488b81600--- /dev/null+++ b/packages/app/tests/meta/port-ownership-lifetime.test.ts@@ -0,0 +1,195 @@+import { createServer as createHttpServer } from 'node:http';+import { createRequire } from 'node:module';+import {+ type AddressInfo,+ createServer as createNetServer,+ type Server,+ type Socket,+} from 'node:net';+import { afterEach, describe, expect, test } from 'vitest';+import { getFreePort } from '../free-port.test-helper.ts';+import { probeOwnedEndpoint } from '../stress/_helpers/port-ownership/run-case.test-helper.ts';++interface HandlerOptions {+ pid: number | null | undefined;+ sendSignal: (pid: number, signal: string) => void;+ exit: (code: number) => void;+ schedule: (callback: () => void, ms: number) => { unref: () => void };+ cleanup: () => void;+ record: (event: string, values?: { message: string }) => void;+}++const require_ = createRequire(import.meta.url);+const { createOwnerLossHandler, OWNER_EXIT_FALLBACK_MS } = require_(+ '../stress/_helpers/port-ownership/owner-lifetime.cjs',+) as {+ createOwnerLossHandler: (options: HandlerOptions) => () => void;+ OWNER_EXIT_FALLBACK_MS: number;+};++function makeRecorder(pid: number | null | undefined) {+ const sends: Array<{ pid: number; signal: string }> = [];+ const exits: number[] = [];+ const records: string[] = [];+ const deadlines: number[] = [];+ let scheduled: (() => void) | undefined;+ let unrefCount = 0;+ let cleanupCount = 0;+ const handle = createOwnerLossHandler({+ pid,+ sendSignal: (target, signal) => sends.push({ pid: target, signal }),+ exit: (code) => exits.push(code),+ schedule: (callback, ms) => {+ scheduled = callback;+ deadlines.push(ms);+ return {+ unref: () => {+ unrefCount += 1;+ },+ };+ },+ cleanup: () => {+ cleanupCount += 1;+ },+ record: (event) => records.push(event),+ });+ return {+ handle,+ sends,+ exits,+ records,+ deadlines,+ scheduled: () => scheduled,+ unrefCount: () => unrefCount,+ cleanupCount: () => cleanupCount,+ };+}++describe('nested runner owner control', () => {+ test('a valid current process receives one termination request and retains a bounded exit fallback', () => {+ const run = makeRecorder(2007);+ run.handle();+ run.handle();+ expect(run.sends).toEqual([{ pid: 2007, signal: 'SIGTERM' }]);+ expect(run.records).toEqual(['owner-control-closed']);+ expect(run.cleanupCount()).toBe(1);+ expect(run.exits).toEqual([]);+ expect(run.deadlines).toEqual([OWNER_EXIT_FALLBACK_MS]);+ expect(run.unrefCount()).toBe(1);+ run.scheduled()?.();+ expect(run.exits).toEqual([0]);+ });++ test.each([null, undefined, 0, 1, -1, Number.NaN, 1.5])(+ 'an invalid process target %s never reaches the signal seam',+ (pid) => {+ const run = makeRecorder(pid);+ run.handle();+ run.handle();+ expect(run.sends).toEqual([]);+ expect(run.exits).toEqual([0]);+ expect(run.cleanupCount()).toBe(1);+ },+ );++ test('a failed termination request exits the current process after recording the failure', () => {+ const records: string[] = [];+ const exits: number[] = [];+ const handle = createOwnerLossHandler({+ pid: 2007,+ sendSignal: () => {+ throw new Error('send refused');+ },+ exit: (code) => exits.push(code),+ schedule: () => ({ unref: () => {} }),+ cleanup: () => {},+ record: (event) => records.push(event),+ });+ handle();+ expect(records).toEqual(['owner-control-closed', 'owner-signal-error']);+ expect(exits).toEqual([0]);+ });++ test('a failed diagnostic write cannot prevent the current process termination request', () => {+ const sends: Array<{ pid: number; signal: string }> = [];+ const exits: number[] = [];+ const handle = createOwnerLossHandler({+ pid: 2007,+ sendSignal: (pid, signal) => {+ sends.push({ pid, signal });+ },+ exit: (code) => {+ exits.push(code);+ },+ schedule: () => ({ unref: () => {} }),+ cleanup: () => {+ throw new Error('scratch already removed');+ },+ record: () => {+ throw new Error('event directory already removed');+ },+ });+ handle();+ handle();+ expect(sends).toEqual([{ pid: 2007, signal: 'SIGTERM' }]);+ expect(exits).toEqual([]);+ });+});++describe('owned endpoint probe', () => {+ const OWNED_NONCE = 'owned-endpoint-nonce';+ const openServers: Server[] = [];+ const acceptedSockets = new Set<Socket>();++ async function listenOnLoopback(server: Server): Promise<number> {+ openServers.push(server);+ server.on('connection', (socket: Socket) => {+ acceptedSockets.add(socket);+ socket.once('close', () => acceptedSockets.delete(socket));+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => resolve());+ });+ return (server.address() as AddressInfo).port;+ }++ afterEach(async () => {+ for (const socket of acceptedSockets) socket.destroy();+ acceptedSockets.clear();+ await Promise.all(+ openServers+ .splice(0)+ .map((server) => new Promise<void>((resolve) => server.close(() => resolve()))),+ );+ });++ test('a listener answering the owned nonce is serving', async () => {+ const port = await listenOnLoopback(+ createHttpServer((_request, response) => response.end(OWNED_NONCE)),+ );+ expect(await probeOwnedEndpoint({ port, nonce: OWNED_NONCE })).toBe(true);+ });++ test('a released port that refuses connections is not serving', async () => {+ const port = await getFreePort();+ expect(await probeOwnedEndpoint({ port, nonce: OWNED_NONCE })).toBe(false);+ });++ test('a bound listener that never answers within the probe bound is still serving', async () => {+ const port = await listenOnLoopback(createNetServer());+ expect(await probeOwnedEndpoint({ port, nonce: OWNED_NONCE })).toBe(true);+ });++ test('a bound listener that drops accepted connections is still serving', async () => {+ const port = await listenOnLoopback(createNetServer((socket) => socket.destroy()));+ expect(await probeOwnedEndpoint({ port, nonce: OWNED_NONCE })).toBe(true);+ });++ test('a listener answering a different identity is not the owned server', async () => {+ const port = await listenOnLoopback(+ createHttpServer((_request, response) => response.end('another-server')),+ );+ expect(await probeOwnedEndpoint({ port, nonce: OWNED_NONCE })).toBe(false);+ });+});diff --git a/packages/app/tests/meta/worker-server-budget.test.ts b/packages/app/tests/meta/worker-server-budget.test.tsindex 00d88ff68..71a546c72 100644--- a/packages/app/tests/meta/worker-server-budget.test.ts+++ b/packages/app/tests/meta/worker-server-budget.test.ts@@ -2898,7 +2898,7 @@ const REQUIRED_ENTRY_NAMES_EXPORT = 'REQUIRED_FIXTURE_ENTRY_NAMES';const OPEN_BUDGET_PHASE_EXPORT = 'openBudgetPhase';const WARMUP_BYPASS_NAVIGATION_CALLEE = 'goto';-const LIVE_BASE_URL = 'started.baseURL';+const LIVE_BASE_URL = 'endpoint.baseURL';const LIVE_WARMUP_CALL = [` await ${WARMUP_FIRST_LOAD_EXPORT}(`,' browser,',diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.tsindex 8dc0ad887..540b880ef 100644--- a/packages/app/tests/stress/_helpers/fixtures.ts+++ b/packages/app/tests/stress/_helpers/fixtures.ts@@ -8,15 +8,19 @@ import { resetContentToFixtureBaseline } from './content-reset.ts';import { gotoWhileLoadProgresses, requireDeadlineAt } from './load-progress.ts';import {APP_PACKAGE_ROOT,+ type BoundViteEndpoint,+ beginViteStartup,checkCollabSync,closeServerLog,- getFreePort,+ createViteStartupRequest,killGracefully,openServerLog,+ type PendingViteStartup,prepareViteCacheDir,requireBoundMs,type ServerLog,tailServerLog,+ waitForBoundViteEndpoint,waitForHttpReady,} from './server-process.ts';import { declareSetupNonResult } from './setup-non-result.ts';@@ -256,14 +260,21 @@ export async function checkApiConfig(baseURL: string, timeoutMs: number): Promis}}-async function waitForServerReady(- baseURL: string,- port: number,- proc: ChildProcess,-): Promise<void> {- await waitForHttpReady(baseURL, WORKER_SERVER_READINESS_BUDGET_MS, proc);+async function waitForServerReady(started: StartedWorkerServer): Promise<BoundViteEndpoint> {+ const { pending } = started;+ const { baseURL, port } = await waitForBoundViteEndpoint(+ pending,+ WORKER_SERVER_READINESS_BUDGET_MS,+ );+ await waitForHttpReady(+ baseURL,+ WORKER_SERVER_READINESS_BUDGET_MS,+ pending.proc,+ pending.startedAt,+ );await checkApiConfig(baseURL, WORKER_SERVER_BUDGET_RESERVES.apiConfig);await checkCollabSync(port, WORKER_SERVER_BUDGET_RESERVES.collabSync);+ return { baseURL, port };}async function settleBeforeDeadline<T>(@@ -427,8 +438,7 @@ function seedRequiredFixtureFiles(contentDir: string): void {}interface StartedWorkerServer {- port: number;- baseURL: string;+ pending: PendingViteStartup;contentDir: string;viteCacheDir: string;serverLog: ServerLog;@@ -436,7 +446,7 @@ interface StartedWorkerServer {}function setupResidueOf(started: StartedWorkerServer): string {- return `the detached dev server on port ${started.port}, the content dir ${started.contentDir} and the vite cache dir ${started.viteCacheDir} are reaped and removed by whichever of the failure path and the teardown path this worker reaches`;+ return `the detached dev server started with candidate port ${started.pending.request.candidatePort}, the content dir ${started.contentDir} and the vite cache dir ${started.viteCacheDir} are reaped and removed by whichever of the failure path and the teardown path this worker reaches`;}export const test = base.extend<TestFixtures, WorkerFixtures>({@@ -451,10 +461,12 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({const releaseSetupResources: Array<() => void | Promise<void>> = [];let openedServerLog: ServerLog | undefined;let started: StartedWorkerServer | undefined;+ let endpoint: BoundViteEndpoint;try {started = await spendOnBudgetPhase(setupOverhead, async () => {- const port = await getFreePort();+ const request = createViteStartupRequest('127.0.0.1');+ releaseSetupResources.push(() => request.dispose());const contentDir = mkdtempSync(join(tmpdir(), `ok-w${workerInfo.workerIndex}-`));releaseSetupResources.push(() => removeAllDuringTeardown(contentDir));@@ -468,13 +480,13 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({openedServerLog = serverLog;releaseSetupResources.push(() => closeServerLog(serverLog));- const proc = spawn('pnpm', ['run', 'dev', '--host', '127.0.0.1'], {+ const proc = spawn('pnpm', ['run', 'dev', '--host', request.host], {cwd: APP_PACKAGE_ROOT,detached: true,env: {...process.env,...workerServerEnv,- VITE_PORT: String(port),+ ...request.environment,OK_TEST_CONTENT_DIR: contentDir,OK_TEST_VITE_CACHE_DIR: viteCacheDir,OK_TEST_SKIP_I18N_COMPILE: '1',@@ -492,8 +504,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({});return {- port,- baseURL: `http://127.0.0.1:${port}`,+ pending: beginViteStartup(request, proc),contentDir,viteCacheDir,serverLog,@@ -504,10 +515,10 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({const residue = setupResidueOf(started);reportBudgetOverrun(setupOverhead, workerInfo.workerIndex, residue);- await waitForServerReady(started.baseURL, started.port, started.proc);+ endpoint = await waitForServerReady(started);await warmupAppFirstLoad(browser,- started.baseURL,+ endpoint.baseURL,setupOverhead,fixtureStartedAt + WORKER_SERVER_SETUP_STARVATION_LINE_MS,);@@ -535,9 +546,9 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({);}- const { port, baseURL, contentDir, viteCacheDir, serverLog, proc } = started;+ const { contentDir, viteCacheDir, serverLog, proc, pending } = started;- await use({ port, baseURL, contentDir });+ await use({ ...endpoint, contentDir });const teardown = openBudgetPhase(TEARDOWN_PHASE_NAME, WORKER_SERVER_BUDGET_RESERVES.teardown);try {@@ -545,13 +556,18 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({} finally {await spendOnBudgetPhase(teardown, () => {closeServerLog(serverLog);- removeAllDuringTeardown(serverLog.path, contentDir, viteCacheDir);+ removeAllDuringTeardown(+ serverLog.path,+ contentDir,+ viteCacheDir,+ pending.request.receiptDir,+ );});}reportBudgetOverrun(teardown,workerInfo.workerIndex,- `the dev server was reaped and ${serverLog.path}, ${contentDir} and ${viteCacheDir} were removed before this report`,+ `the dev server was reaped and ${serverLog.path}, ${contentDir}, ${viteCacheDir} and ${pending.request.receiptDir} were removed before this report`,);},{ scope: 'worker', timeout: WORKER_SERVER_BUDGET_TOTAL_MS },diff --git a/packages/app/tests/stress/_helpers/global-warm-cache.ts b/packages/app/tests/stress/_helpers/global-warm-cache.tsindex d2f9a0b88..a6193f9ab 100644--- a/packages/app/tests/stress/_helpers/global-warm-cache.ts+++ b/packages/app/tests/stress/_helpers/global-warm-cache.ts@@ -11,16 +11,18 @@ import {writeFileSync,} from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import { APP_PACKAGE_ROOT, computeSeedKey } from './seed-key.ts';import {+ beginViteStartup,closeServerLog,- getFreePort,+ createViteStartupRequest,killGracefully,openServerLog,tailServerLog,VITE_E2E_SEED_DIR,+ waitForBoundViteEndpoint,waitForHttpReady,} from './server-process.ts';import { removeAllDuringTeardown } from './teardown-fs.ts';@@ -47,17 +49,18 @@ function depsDirSignature(depsDir: string): string {}async function buildSeedOnce(key: string): Promise<void> {- const port = await getFreePort();const contentDir = mkdtempSync(join(tmpdir(), 'ok-warm-cache-content-'));- mkdirSync(join(APP_PACKAGE_ROOT, 'node_modules'), { recursive: true });- const buildDir = mkdtempSync(join(APP_PACKAGE_ROOT, 'node_modules', '.vite-e2e-seed-building-'));+ const seedParent = dirname(VITE_E2E_SEED_DIR);+ mkdirSync(seedParent, { recursive: true });+ const buildDir = mkdtempSync(join(seedParent, '.vite-e2e-seed-building-'));const log = openServerLog('warm-cache');- const proc = spawn('pnpm', ['run', 'dev', '--host', '127.0.0.1'], {+ const request = createViteStartupRequest('127.0.0.1');+ const proc = spawn('pnpm', ['run', 'dev', '--host', request.host], {cwd: APP_PACKAGE_ROOT,detached: true,env: {...process.env,- VITE_PORT: String(port),+ ...request.environment,OK_TEST_CONTENT_DIR: contentDir,OK_TEST_VITE_CACHE_DIR: buildDir,OK_TEST_SKIP_I18N_COMPILE: '1',@@ -68,9 +71,11 @@ async function buildSeedOnce(key: string): Promise<void> {proc.on('error', (err) => {console.warn('[e2e warm-cache] spawn error:', err);});+ const pending = beginViteStartup(request, proc);let succeeded = false;try {- await waitForHttpReady(`http://127.0.0.1:${port}`, 60_000, proc);+ const { baseURL } = await waitForBoundViteEndpoint(pending, 60_000);+ await waitForHttpReady(baseURL, 60_000, proc, pending.startedAt);const depsDir = join(buildDir, 'deps');const metaPath = join(depsDir, '_metadata.json');const deadline = Date.now() + OPTIMIZER_SETTLE_BUDGET_MS;@@ -107,7 +112,7 @@ async function buildSeedOnce(key: string): Promise<void> {await killGracefully(proc);} finally {closeServerLog(log);- removeAllDuringTeardown(contentDir, ...(succeeded ? [] : [buildDir]));+ removeAllDuringTeardown(contentDir, request.receiptDir, ...(succeeded ? [] : [buildDir]));}}try {diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.tsindex bdd855267..1abc5ac25 100644--- a/packages/app/tests/stress/_helpers/index.ts+++ b/packages/app/tests/stress/_helpers/index.ts@@ -51,14 +51,18 @@ export {export { escapeRegExp } from './regexp.ts';export { matchIsWithinReadableScrollport } from './scrollport.ts';export {+ type BoundViteEndpoint,+ beginViteStartup,checkCollabSync,closeServerLog,+ createViteStartupRequest,getFreePort,killGracefully,openServerLog,prepareViteCacheDir,type ServerLog,tailServerLog,+ waitForBoundViteEndpoint,waitForHttpReady,} from './server-process.ts';export {diff --git a/packages/app/tests/stress/_helpers/port-ownership/expect-owned-server-run.test-helper.ts b/packages/app/tests/stress/_helpers/port-ownership/expect-owned-server-run.test-helper.tsnew file mode 100644index 000000000..a970b926d--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/expect-owned-server-run.test-helper.ts@@ -0,0 +1,49 @@+import { writeFileSync } from 'node:fs';+import { expect, test } from '@playwright/test';+import { type OwnershipCase, runOwnershipCase } from './run-case.test-helper.ts';++export async function expectOwnedServerRun(ownershipCase: OwnershipCase): Promise<void> {+ const run = await runOwnershipCase(ownershipCase);+ const testInfo = test.info();+ expect(run.report, run.transcript).toBeDefined();+ const reportPath = testInfo.outputPath('inner-report.json');+ const eventsPath = testInfo.outputPath('socket-events.json');+ const transcriptPath = testInfo.outputPath('inner-transcript.txt');+ writeFileSync(reportPath, JSON.stringify(run.report));+ writeFileSync(eventsPath, JSON.stringify({ present: run.eventFilePresent, events: run.events }));+ writeFileSync(transcriptPath, run.transcript);+ await testInfo.attach('inner-report', {+ path: reportPath,+ contentType: 'application/json',+ });+ await testInfo.attach('socket-events', {+ path: eventsPath,+ contentType: 'application/json',+ });+ await testInfo.attach('inner-transcript', {+ path: transcriptPath,+ contentType: 'text/plain',+ });+ expect(run.eventFilePresent, run.transcript).toBe(true);+ expect(+ run.events.some(+ (event) =>+ typeof event === 'object' &&+ event !== null &&+ 'event' in event &&+ (event.event === 'occupied' || event.event === 'vite-bind-takeover'),+ ),+ `${run.transcript}\n${JSON.stringify(run.events)}`,+ ).toBe(true);+ expect(run.signal, run.transcript).toBeNull();+ expect(run.stdioClosed, run.transcript).toBe(true);+ expect(run.errors, run.transcript).toEqual([]);+ expect(run.matchingSpecs, run.transcript).toHaveLength(1);+ expect(run.matchingSpecs[0]?.tests, run.transcript).toHaveLength(1);+ expect(run.matchingSpecs[0]?.tests[0]?.results, run.transcript).toHaveLength(1);+ expect(+ run.matchingSpecs[0]?.tests[0]?.results[0]?.status,+ `${run.transcript}\n${JSON.stringify(run.events)}`,+ ).toBe('passed');+ expect(run.exitCode, run.transcript).toBe(0);+}diff --git a/packages/app/tests/stress/_helpers/port-ownership/lifetime-global-setup.ts b/packages/app/tests/stress/_helpers/port-ownership/lifetime-global-setup.tsnew file mode 100644index 000000000..9437e96b8--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/lifetime-global-setup.ts@@ -0,0 +1,33 @@+import { spawn } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { once } from 'node:events';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';++const serverPath = fileURLToPath(new URL('./lifetime-server.cjs', import.meta.url));++export default async function lifetimeGlobalSetup(): Promise<() => Promise<void>> {+ const runDir = process.env.OK_PORT_OWNERSHIP_RUN_DIR;+ if (!runDir) throw new Error('lifetime setup needs a run directory');+ const nonce = randomUUID();+ const child = spawn(process.execPath, [serverPath, nonce], {+ env: process.env,+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],+ });+ const [message] = await once(child, 'message');+ const receipt = message as { port: number; nonce: string; pid: number };+ const response = await fetch(`http://127.0.0.1:${receipt.port}/identity`);+ if ((await response.text()) !== nonce) throw new Error('owned lifetime endpoint did not serve');+ writeFileSync(join(runDir, 'lifetime-receipt.json'), JSON.stringify(receipt));++ if (process.env.OK_PORT_OWNERSHIP_CALLER !== 'lifetime-normal') {+ await new Promise<never>(() => {});+ }++ return async () => {+ const exited = once(child, 'exit');+ child.send('release');+ await exited;+ };+}diff --git a/packages/app/tests/stress/_helpers/port-ownership/lifetime-server.cjs b/packages/app/tests/stress/_helpers/port-ownership/lifetime-server.cjsnew file mode 100644index 000000000..2b75ae67e--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/lifetime-server.cjs@@ -0,0 +1,47 @@+const { writeFileSync } = require('node:fs');+const http = require('node:http');+const { join } = require('node:path');++const nonce = process.argv[2];+const runDir = process.env.OK_PORT_OWNERSHIP_RUN_DIR;+if (!nonce || !runDir) throw new Error('lifetime server needs a nonce and run directory');++const server = http.createServer((request, response) => {+ if (request.url === `/release/${nonce}`) {+ clearTimeout(selfBound);+ writeFileSync(join(runDir, 'lifetime-release'), 'requested');+ response.end(nonce);+ response.once('finish', () => {+ server.closeAllConnections();+ server.close(() => {+ writeFileSync(join(runDir, 'lifetime-closed'), 'released');+ if (process.connected) process.disconnect();+ });+ });+ return;+ }+ response.end(nonce);+});++const selfBound = setTimeout(() => {+ writeFileSync(join(runDir, 'lifetime-self-bound'), 'expired');+ server.closeAllConnections();+ server.close(() => {+ if (process.connected) process.disconnect();+ });+}, 30_000);++server.listen(0, '127.0.0.1', () => {+ process.send({ port: server.address().port, nonce, pid: process.pid });+});++process.on('message', (message) => {+ if (message === 'release') {+ clearTimeout(selfBound);+ server.closeAllConnections();+ server.close(() => {+ writeFileSync(join(runDir, 'lifetime-closed'), 'normal');+ if (process.connected) process.disconnect();+ });+ }+});diff --git a/packages/app/tests/stress/_helpers/port-ownership/lifetime.ownership-case.ts b/packages/app/tests/stress/_helpers/port-ownership/lifetime.ownership-case.tsnew file mode 100644index 000000000..41a904d95--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/lifetime.ownership-case.ts@@ -0,0 +1,5 @@+import { expect, test } from '@playwright/test';++test('nested lifetime control reaches its test body', async () => {+ expect(process.env.OK_PORT_OWNERSHIP_RUN_DIR).toBeTruthy();+});diff --git a/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjs b/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjsnew file mode 100644index 000000000..662de62d0--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjs@@ -0,0 +1,121 @@+const net = require('node:net');+const childProcess = require('node:child_process');+const fs = require('node:fs');+const http = require('node:http');+const { syncBuiltinESMExports } = require('node:module');+const path = require('node:path');+const { createOwnerLossHandler } = require('./owner-lifetime.cjs');++const createServer = net.createServer;+const spawn = childProcess.spawn;+const listenHttp = http.Server.prototype.listen;+const caller = process.env.OK_PORT_OWNERSHIP_CALLER;+const records = process.env.OK_PORT_OWNERSHIP_RECORDS;+const occupants = new Map();+const controlPort = Number(process.env.OK_PORT_OWNERSHIP_CONTROL_PORT);++function record(event, values = {}) {+ if (records)+ fs.appendFileSync(records, `${JSON.stringify({ event, pid: process.pid, ...values })}\n`);+}++if (Number.isInteger(controlPort) && controlPort > 0) {+ const control = net.connect({ port: controlPort, host: '127.0.0.1', allowHalfOpen: true });+ const leave = createOwnerLossHandler({+ pid: process.pid,+ sendSignal: (pid, signal) => process.kill(pid, signal),+ exit: (code) => process.exit(code),+ schedule: (callback, ms) => setTimeout(callback, ms),+ record,+ cleanup: () => {+ const runDir = process.env.OK_PORT_OWNERSHIP_RUN_DIR;+ if (!runDir || fs.existsSync(path.join(runDir, 'owner-release'))) return;+ const tempRoot = fs.realpathSync(process.env.OK_PORT_OWNERSHIP_SYSTEM_TEMP_ROOT);+ const resolved = fs.realpathSync(runDir);+ if (+ path.dirname(resolved) === tempRoot &&+ path.basename(resolved).startsWith('ok-port-ownership-') &&+ !fs.lstatSync(runDir).isSymbolicLink()+ ) {+ try {+ fs.mkdirSync(path.join(runDir, '.owner-cleanup-lock'));+ } catch (error) {+ if (error?.code === 'EEXIST') return;+ throw error;+ }+ fs.rmSync(runDir, { recursive: true, force: true });+ }+ },+ });+ control.once('error', leave);+ control.once('end', leave);+ control.once('close', leave);+ control.unref();+}++net.createServer = function (...args) {+ const server = createServer.apply(this, args);+ if (!caller || !(new Error().stack ?? '').includes(caller)) return server;++ const close = server.close;+ server.close = (callback) => {+ const address = server.address();+ if (!address || typeof address === 'string') return close.call(server, callback);+ return close.call(server, (...closeArgs) => {+ const occupant = createServer((socket) => socket.destroy());+ occupant.once('error', (error) => {+ record('occupant-error', { port: address.port, code: error.code });+ throw error;+ });+ occupant.listen(address.port, address.address, () => {+ occupants.set(address.port, occupant);+ occupant.unref();+ record('occupied', { port: address.port, host: address.address });+ callback(...closeArgs);+ });+ });+ };+ return server;+};++childProcess.spawn = function (...args) {+ const [command, argv, options] = args;+ const port = Number(options?.env?.VITE_PORT);+ const occupant = occupants.get(port);+ if (command === 'pnpm' && argv?.includes('dev') && occupant?.listening) {+ record('dev-spawn', { port, command, argv, occupied: true });+ }+ const child = spawn.apply(this, args);+ if (command === 'pnpm' && argv?.includes('dev') && occupant) {+ child.once('exit', (code, signal) => {+ record('dev-exit', { port, code, signal });+ occupant.close(() => record('released', { port }));+ occupants.delete(port);+ });+ }+ return child;+};++let bindTakeoverAttempted = false;+http.Server.prototype.listen = function (...args) {+ const rawRequest = process.env.OK_TEST_VITE_START_REQUEST;+ if (!rawRequest || bindTakeoverAttempted) return listenHttp.apply(this, args);+ const request = JSON.parse(rawRequest);+ const port = args[0];+ if (port !== request.candidatePort) return listenHttp.apply(this, args);+ bindTakeoverAttempted = true;+ const occupant = createServer((socket) => socket.destroy());+ occupant.once('error', (error) => {+ record('vite-bind-takeover-error', { port, code: error.code });+ listenHttp.apply(this, args);+ });+ occupant.listen(port, request.host, () => {+ occupants.set(port, occupant);+ occupant.unref();+ record('vite-bind-takeover', { port, host: request.host });+ listenHttp.apply(this, args);+ });+ return this;+};++syncBuiltinESMExports();diff --git a/packages/app/tests/stress/_helpers/port-ownership/owner-lifetime.cjs b/packages/app/tests/stress/_helpers/port-ownership/owner-lifetime.cjsnew file mode 100644index 000000000..22211c4b1--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/owner-lifetime.cjs@@ -0,0 +1,34 @@+const OWNER_EXIT_FALLBACK_MS = 30_000;++function createOwnerLossHandler({ pid, sendSignal, exit, schedule, cleanup, record }) {+ let handled = false;+ function safeRecord(event, values) {+ try {+ record(event, values);+ } catch {}+ }+ return () => {+ if (handled) return;+ handled = true;+ safeRecord('owner-control-closed');+ try {+ cleanup();+ } catch (error) {+ safeRecord('owner-cleanup-error', { message: String(error) });+ }+ if (!Number.isInteger(pid) || pid <= 1) {+ exit(0);+ return;+ }+ try {+ const fallback = schedule(() => exit(0), OWNER_EXIT_FALLBACK_MS);+ fallback.unref?.();+ sendSignal(pid, 'SIGTERM');+ } catch (error) {+ safeRecord('owner-signal-error', { message: String(error) });+ exit(0);+ }+ };+}++module.exports = { createOwnerLossHandler, OWNER_EXIT_FALLBACK_MS };diff --git a/packages/app/tests/stress/_helpers/port-ownership/owner-loss-driver.ts b/packages/app/tests/stress/_helpers/port-ownership/owner-loss-driver.tsnew file mode 100644index 000000000..9a8812497--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/owner-loss-driver.ts@@ -0,0 +1,24 @@+import { runOwnershipCase } from './run-case.test-helper.ts';++const runDir = process.argv[2];+if (!runDir) throw new Error('owner-loss driver needs a run directory');++process.on('message', (message) => {+ if (message === 'exit') process.exit(0);+});+process.on('disconnect', () => process.exit(0));++setTimeout(() => process.exit(5), 20_000);++void runOwnershipCase({+ file: 'tests/stress/_helpers/port-ownership/lifetime.ownership-case.ts',+ name: 'nested lifetime control reaches its test body',+ caller: 'lifetime-owner-loss',+ runDir,+}).then(+ () => process.exit(3),+ (error: unknown) => {+ process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);+ process.exit(4);+ },+);diff --git a/packages/app/tests/stress/_helpers/port-ownership/owner-loss.test-helper.ts b/packages/app/tests/stress/_helpers/port-ownership/owner-loss.test-helper.tsnew file mode 100644index 000000000..d084b0429--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/owner-loss.test-helper.ts@@ -0,0 +1,170 @@+import { type ChildProcess, spawn } from 'node:child_process';+import { once } from 'node:events';+import { existsSync, mkdtempSync, readFileSync, rmSync, watch } from 'node:fs';+import { connect } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ type OwnedEndpointRelease,+ probeOwnedEndpoint,+ readOwnershipRecords,+ releaseIfServing,+} from './run-case.test-helper.ts';++const DRIVER = fileURLToPath(new URL('./owner-loss-driver.ts', import.meta.url));+const APP_ROOT = fileURLToPath(new URL('../../../..', import.meta.url));++interface Receipt {+ port: number;+ nonce: string;+ pid: number;+}++export interface OwnerLossRun extends OwnedEndpointRelease {+ driverPid: number | undefined;+ driverExit: number | null;+ driverSignal: NodeJS.Signals | null;+ receipt: Receipt;+ witnessClosed: boolean;+ scratchGone: boolean;+ events: unknown[];+ servingAfterOwnerExit: boolean;+ transcript: string;+}++async function awaitReceipt(runDir: string, child: ChildProcess): Promise<Receipt> {+ const receiptPath = join(runDir, 'lifetime-receipt.json');+ return new Promise<Receipt>((resolve, reject) => {+ const watcher = watch(runDir, check);+ let settled = false;+ function settle(result: Receipt | Error): void {+ if (settled) return;+ settled = true;+ watcher.close();+ child.off('exit', onExit);+ child.off('error', onError);+ watcher.off('error', onError);+ if (result instanceof Error) reject(result);+ else resolve(result);+ }+ function check(): void {+ if (!existsSync(receiptPath)) return;+ let receipt: Receipt;+ try {+ receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) as Receipt;+ } catch (error) {+ settle(error instanceof Error ? error : new Error(String(error)));+ return;+ }+ settle(receipt);+ }+ function onExit(code: number | null, signal: NodeJS.Signals | null): void {+ settle(new Error(`owner exited before lifetime receipt: code=${code} signal=${signal}`));+ }+ function onError(error: Error): void {+ settle(error);+ }+ child.once('exit', onExit);+ child.once('error', onError);+ watcher.once('error', onError);+ if (child.exitCode !== null || child.signalCode !== null) {+ onExit(child.exitCode, child.signalCode);+ } else {+ check();+ }+ });+}++function watchScratchGone(runDir: string): { result: Promise<boolean>; stop: () => void } {+ let finishResult: (gone: boolean) => void = () => {};+ const result = new Promise<boolean>((resolve) => {+ finishResult = resolve;+ });+ let watcher: ReturnType<typeof watch> | undefined;+ let bound: ReturnType<typeof setTimeout> | undefined;+ let settled = false;+ function finish(gone: boolean): void {+ if (settled) return;+ settled = true;+ watcher?.close();+ clearTimeout(bound);+ finishResult(gone);+ }+ if (!existsSync(runDir)) {+ finish(true);+ } else {+ bound = setTimeout(() => finish(false), 30_000);+ try {+ watcher = watch(runDir, () => {+ if (!existsSync(runDir)) finish(true);+ });+ watcher.once('error', () => finish(!existsSync(runDir)));+ } catch {+ finish(!existsSync(runDir));+ }+ if (!existsSync(runDir)) finish(true);+ }+ return { result, stop: () => finish(false) };+}++export async function runOwnerLossControl(): Promise<OwnerLossRun> {+ const runDir = mkdtempSync(join(tmpdir(), 'ok-port-ownership-'));+ const child = spawn(process.execPath, ['--import', 'tsx', DRIVER, runDir], {+ cwd: APP_ROOT,+ env: process.env,+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'] as const,+ });+ let transcript = '';+ let scratchWatcher: ReturnType<typeof watchScratchGone> | undefined;+ child.stdout?.on('data', (chunk: Buffer) => {+ transcript += chunk.toString('utf8');+ });+ child.stderr?.on('data', (chunk: Buffer) => {+ transcript += chunk.toString('utf8');+ });++ try {+ const receipt = await awaitReceipt(runDir, child);+ const witness = connect(receipt.port, '127.0.0.1');+ await once(witness, 'connect');+ scratchWatcher = watchScratchGone(runDir);+ const closed = once(witness, 'close');+ const exited = once(child, 'exit');+ child.send('exit');+ const [driverExit, driverSignal] = (await exited) as [number | null, NodeJS.Signals | null];+ let closeBound: ReturnType<typeof setTimeout> | undefined;+ const witnessClosed = await Promise.race([+ closed.then(() => true),+ new Promise<false>((resolve) => {+ closeBound = setTimeout(() => resolve(false), 10_000);+ }),+ ]).finally(() => clearTimeout(closeBound));+ if (!witnessClosed) witness.destroy();+ const scratchGone = await scratchWatcher.result;+ const eventsPath = join(runDir, 'events.jsonl');+ const events = existsSync(eventsPath) ? readOwnershipRecords(eventsPath) : [];+ const servingAfterOwnerExit = await probeOwnedEndpoint(receipt);+ const release = await releaseIfServing(receipt, servingAfterOwnerExit);+ return {+ driverPid: child.pid,+ driverExit,+ driverSignal,+ receipt,+ witnessClosed,+ scratchGone,+ events,+ servingAfterOwnerExit,+ ...release,+ transcript,+ };+ } finally {+ scratchWatcher?.stop();+ if (child.exitCode === null && child.signalCode === null && child.connected) {+ const exited = once(child, 'exit');+ child.send('exit');+ await exited.catch(() => {});+ }+ if (existsSync(runDir)) rmSync(runDir, { recursive: true, force: true });+ }+}diff --git a/packages/app/tests/stress/_helpers/port-ownership/ownership-run.config.ts b/packages/app/tests/stress/_helpers/port-ownership/ownership-run.config.tsnew file mode 100644index 000000000..7d4a7118f--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/ownership-run.config.ts@@ -0,0 +1,29 @@+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { defineConfig } from '@playwright/test';+import stock from '../../../../playwright.config.ts';++const runDir = process.env.OK_PORT_OWNERSHIP_RUN_DIR;+if (!runDir) throw new Error('OK_PORT_OWNERSHIP_RUN_DIR is required');+const stressDir = fileURLToPath(new URL('../..', import.meta.url));+const warmCacheSetup = fileURLToPath(new URL('../global-warm-cache.ts', import.meta.url));+const lifetimeSetup = fileURLToPath(new URL('./lifetime-global-setup.ts', import.meta.url));+const caller = process.env.OK_PORT_OWNERSHIP_CALLER;++export default defineConfig({+ ...stock,+ testDir: stressDir,+ testMatch: [/.*\.e2e\.ts$/, /.*\.ownership-case\.ts$/],+ globalSetup:+ caller === 'global-warm-cache.ts'+ ? [warmCacheSetup]+ : caller?.startsWith('lifetime-')+ ? [lifetimeSetup]+ : [],+ globalTimeout: caller?.startsWith('lifetime-') ? 5_000 : 110_000,+ outputDir: join(runDir, 'test-results'),+ reporter: [['json', { outputFile: join(runDir, 'results.json') }]],+ retries: 0,+ workers: 2,+ use: { ...stock.use, headless: true },+});diff --git a/packages/app/tests/stress/_helpers/port-ownership/run-case.test-helper.ts b/packages/app/tests/stress/_helpers/port-ownership/run-case.test-helper.tsnew file mode 100644index 000000000..97faefcc7--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/run-case.test-helper.ts@@ -0,0 +1,262 @@+import { spawn } from 'node:child_process';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { createRequire } from 'node:module';+import { createServer, type Socket } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { JSONReport, JSONReportSpec, JSONReportSuite } from '@playwright/test/reporter';++const APP_ROOT = fileURLToPath(new URL('../../../..', import.meta.url));+const SUBTREE_ROOT = fileURLToPath(new URL('../../../../../..', import.meta.url));+const RUN_CONFIG = fileURLToPath(new URL('./ownership-run.config.ts', import.meta.url));+const PRELOAD = fileURLToPath(new URL('./occupy-selected-port.cjs', import.meta.url));+const PLAYWRIGHT_CLI = createRequire(join(APP_ROOT, 'package.json')).resolve(+ '@playwright/test/cli',+);++export interface OwnershipCase {+ file: string;+ name: string;+ caller: string;+ runDir?: string;+}++export interface OwnedEndpointRelease {+ releaseResponse: string | undefined;+ releaseError: string | undefined;+}++export interface OwnershipRun {+ exitCode: number | null;+ signal: NodeJS.Signals | null;+ stdioClosed: boolean;+ transcript: string;+ events: unknown[];+ eventFilePresent: boolean;+ report: JSONReport | undefined;+ matchingSpecs: JSONReportSpec[];+ errors: JSONReport['errors'] | undefined;+ lifetime:+ | (OwnedEndpointRelease & {+ receipt: { port: number; nonce: string; pid: number };+ servingAfterExit: boolean;+ selfBoundFired: boolean;+ })+ | undefined;+}++async function openOwnerControl(): Promise<{ port: number; close: () => Promise<void> }> {+ const clients = new Set<Socket>();+ const server = createServer((socket) => {+ clients.add(socket);+ socket.once('close', () => clients.delete(socket));+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', resolve);+ });+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('owner control has no TCP address');+ let closing: Promise<void> | undefined;+ return {+ port: address.port,+ close: () => {+ if (closing) return closing;+ closing = new Promise<void>((resolve) => {+ for (const socket of clients) socket.end();+ server.close(() => resolve());+ });+ return closing;+ },+ };+}++function specsOf(suites: JSONReportSuite[]): JSONReportSpec[] {+ return suites.flatMap((suite) => [...suite.specs, ...specsOf(suite.suites ?? [])]);+}++function causeCode(error: unknown): unknown {+ if (!(error instanceof Error)) return undefined;+ const { cause } = error;+ return typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined;+}++function isRefusedConnection(error: unknown): boolean {+ return error instanceof TypeError && causeCode(error) === 'ECONNREFUSED';+}++function describeFailure(error: unknown): string {+ if (!(error instanceof Error)) return String(error);+ const code = causeCode(error);+ const summary = `${error.name}: ${error.message}`;+ return code === undefined ? summary : `${summary} (${String(code)})`;+}++export async function probeOwnedEndpoint(receipt: {+ port: number;+ nonce: string;+}): Promise<boolean> {+ try {+ const response = await fetch(`http://127.0.0.1:${receipt.port}/identity`, {+ signal: AbortSignal.timeout(1_000),+ });+ return (await response.text()) === receipt.nonce;+ } catch (error) {+ return !isRefusedConnection(error);+ }+}++export async function releaseIfServing(+ receipt: { port: number; nonce: string },+ serving: boolean,+): Promise<OwnedEndpointRelease> {+ if (!serving) return { releaseResponse: undefined, releaseError: undefined };+ try {+ const response = await fetch(`http://127.0.0.1:${receipt.port}/release/${receipt.nonce}`, {+ signal: AbortSignal.timeout(1_000),+ });+ return { releaseResponse: await response.text(), releaseError: undefined };+ } catch (error) {+ return { releaseResponse: undefined, releaseError: describeFailure(error) };+ }+}++export function readOwnershipRecords(path: string): unknown[] {+ return readFileSync(path, 'utf8')+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line) as unknown);+}++export async function runOwnershipCase(ownershipCase: OwnershipCase): Promise<OwnershipRun> {+ const runDir = ownershipCase.runDir ?? mkdtempSync(join(tmpdir(), 'ok-port-ownership-'));+ const runtimeTmp = join(runDir, 'tmp');+ mkdirSync(runtimeTmp);+ const ownerControl = await openOwnerControl().catch((error: unknown) => {+ rmSync(runDir, { recursive: true, force: true });+ throw error;+ });+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --require=${PRELOAD}`.trim(),+ OK_PORT_OWNERSHIP_CALLER: ownershipCase.caller,+ OK_PORT_OWNERSHIP_RECORDS: join(runDir, 'events.jsonl'),+ OK_PORT_OWNERSHIP_RUN_DIR: runDir,+ OK_PORT_OWNERSHIP_SYSTEM_TEMP_ROOT: realpathSync(tmpdir()),+ OK_PORT_OWNERSHIP_CONTROL_PORT: String(ownerControl.port),+ ...(ownershipCase.caller === 'global-warm-cache.ts'+ ? { OK_TEST_VITE_SEED_DIR: join(runDir, 'seed') }+ : {}),+ TMPDIR: runtimeTmp,+ TURBO_CACHE_DIR: join(SUBTREE_ROOT, '.turbo', 'cache'),+ PLAYWRIGHT_HTML_OPEN: 'never',+ };++ try {+ const child = spawn(+ process.execPath,+ [+ PLAYWRIGHT_CLI,+ 'test',+ '--config',+ RUN_CONFIG,+ ownershipCase.file,+ '--grep',+ ownershipCase.name,+ '--workers=2',+ '--retries=0',+ ],+ { cwd: APP_ROOT, env, stdio: ['ignore', 'pipe', 'pipe'] },+ );+ let transcript = '';+ child.stdout.on('data', (chunk: Buffer) => {+ transcript += chunk.toString('utf8');+ });+ child.stderr.on('data', (chunk: Buffer) => {+ transcript += chunk.toString('utf8');+ });+ const closed = new Promise<true>((resolve) => {+ child.once('close', () => resolve(true));+ });+ const { exitCode, signal } = await new Promise<{+ exitCode: number | null;+ signal: NodeJS.Signals | null;+ }>((resolve, reject) => {+ child.once('error', reject);+ child.once('exit', (code, exitSignal) => {+ try {+ writeFileSync(join(runDir, 'owner-release'), 'child-exit');+ } catch (error) {+ reject(error);+ void ownerControl.close();+ return;+ }+ void ownerControl+ .close()+ .then(() => resolve({ exitCode: code, signal: exitSignal }), reject);+ });+ });+ let closeBound: ReturnType<typeof setTimeout> | undefined;+ const stdioClosed = await Promise.race([+ closed,+ new Promise<false>((resolve) => {+ closeBound = setTimeout(() => resolve(false), 5_000);+ }),+ ]).finally(() => clearTimeout(closeBound));+ if (!stdioClosed) {+ child.stdout.destroy();+ child.stderr.destroy();+ }+ const report = existsSync(join(runDir, 'results.json'))+ ? (JSON.parse(readFileSync(join(runDir, 'results.json'), 'utf8')) as JSONReport)+ : undefined;+ const eventsPath = join(runDir, 'events.jsonl');+ const eventFilePresent = existsSync(eventsPath);+ const events = eventFilePresent ? readOwnershipRecords(eventsPath) : [];+ let lifetime: OwnershipRun['lifetime'];+ if (ownershipCase.caller.startsWith('lifetime-')) {+ const receiptPath = join(runDir, 'lifetime-receipt.json');+ if (existsSync(receiptPath)) {+ const receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) as {+ port: number;+ nonce: string;+ pid: number;+ };+ const servingAfterExit = await probeOwnedEndpoint(receipt);+ const release = await releaseIfServing(receipt, servingAfterExit);+ lifetime = {+ receipt,+ servingAfterExit,+ selfBoundFired: existsSync(join(runDir, 'lifetime-self-bound')),+ ...release,+ };+ }+ }+ return {+ exitCode,+ signal,+ stdioClosed,+ transcript,+ events,+ eventFilePresent,+ report,+ matchingSpecs: specsOf(report?.suites ?? []).filter(+ (spec) => spec.title === ownershipCase.name,+ ),+ errors: report?.errors,+ lifetime,+ };+ } finally {+ await ownerControl.close();+ rmSync(runDir, { recursive: true, force: true });+ }+}diff --git a/packages/app/tests/stress/_helpers/port-ownership/warm-cache.ownership-case.ts b/packages/app/tests/stress/_helpers/port-ownership/warm-cache.ownership-case.tsnew file mode 100644index 000000000..7444f0404--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/warm-cache.ownership-case.ts@@ -0,0 +1,9 @@+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { expect, test } from '@playwright/test';+import { VITE_E2E_SEED_DIR } from '../server-process.ts';++test('warm cache owns a serving endpoint before publishing its seed', async () => {+ expect(existsSync(join(VITE_E2E_SEED_DIR, 'deps', '_metadata.json'))).toBe(true);+ expect(existsSync(join(VITE_E2E_SEED_DIR, '.seed-key'))).toBe(true);+});diff --git a/packages/app/tests/stress/_helpers/port-ownership/worker.ownership-case.ts b/packages/app/tests/stress/_helpers/port-ownership/worker.ownership-case.tsnew file mode 100644index 000000000..921e3f76e--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/worker.ownership-case.ts@@ -0,0 +1,9 @@+import { expect } from '@playwright/test';+import { test } from '../fixtures.ts';++test('worker server owns its advertised endpoint', async ({ workerServer }) => {+ const response = await fetch(`${workerServer.baseURL}/api/config`);+ expect(response.ok).toBe(true);+ const config = (await response.json()) as { port: number };+ expect(config.port).toBe(workerServer.port);+});diff --git a/packages/app/tests/stress/_helpers/server-process.ts b/packages/app/tests/stress/_helpers/server-process.tsindex 7f760a51f..3795ca95e 100644--- a/packages/app/tests/stress/_helpers/server-process.ts+++ b/packages/app/tests/stress/_helpers/server-process.ts@@ -1,4 +1,5 @@import type { ChildProcess } from 'node:child_process';+import { randomInt, randomUUID } from 'node:crypto';import {closeSync,cpSync,@@ -7,6 +8,7 @@ import {mkdtempSync,openSync,readFileSync,+ watch,} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -14,12 +16,21 @@ import { setTimeout as wait } from 'node:timers/promises';import { HocuspocusProvider } from '@hocuspocus/provider';import { SYSTEM_DOC_NAME } from '@inkeep/open-knowledge-core';import * as Y from 'yjs';+import {+ TEST_SERVER_CANDIDATE_PORTS,+ TEST_SERVER_HOST_FAMILY,+ TEST_SERVER_IDENTITY_PATH,+ TEST_SERVER_STARTUP_ENV,+ type TestServerStartupReceipt,+ type TestServerStartupRequest,+} from '../../../src/build/test-server-startup-contract.ts';import { APP_PACKAGE_ROOT } from './seed-key.ts';-import { removeAllStrictDuringTeardown } from './teardown-fs.ts';+import { removeAllDuringTeardown, removeAllStrictDuringTeardown } from './teardown-fs.ts';export { APP_PACKAGE_ROOT };-export const VITE_E2E_SEED_DIR = join(APP_PACKAGE_ROOT, 'node_modules', '.vite-e2e-seed');+export const VITE_E2E_SEED_DIR =+ process.env.OK_TEST_VITE_SEED_DIR ?? join(APP_PACKAGE_ROOT, 'node_modules', '.vite-e2e-seed');export function viteSeedIsReady(): boolean {return existsSync(join(VITE_E2E_SEED_DIR, 'deps', '_metadata.json'));@@ -125,6 +136,234 @@ export async function checkCollabSync(export { getFreePort } from '../../free-port.test-helper.ts';+type TestServerHost = TestServerStartupRequest['host'];++export interface ViteStartupRequest {+ readonly candidatePort: number;+ readonly environment: Record<string, string>;+ readonly receiptDir: string;+ readonly receiptPath: string;+ readonly nonce: string;+ readonly host: TestServerHost;+ dispose(): void;+}++export interface PendingViteStartup {+ readonly request: ViteStartupRequest;+ readonly proc: ChildProcess;+ readonly startedAt: number;+}++export interface BoundViteEndpoint {+ readonly port: number;+ readonly baseURL: string;+}++export function createViteStartupRequest(+ host: TestServerHost,+ candidatePort = randomInt(TEST_SERVER_CANDIDATE_PORTS.start, TEST_SERVER_CANDIDATE_PORTS.end),+): ViteStartupRequest {+ if (+ !Number.isInteger(candidatePort) ||+ candidatePort < TEST_SERVER_CANDIDATE_PORTS.start ||+ candidatePort >= TEST_SERVER_CANDIDATE_PORTS.end+ ) {+ throw new RangeError('automatic Vite startup candidate is outside its supported range');+ }+ const receiptDir = mkdtempSync(join(tmpdir(), 'ok-vite-start-'));+ const receiptPath = join(receiptDir, 'receipt.json');+ const nonce = randomUUID();+ const startupRequest: TestServerStartupRequest = { nonce, host, candidatePort, receiptPath };+ return {+ candidatePort,+ environment: {+ VITE_PORT: String(candidatePort),+ [TEST_SERVER_STARTUP_ENV]: JSON.stringify(startupRequest),+ },+ receiptDir,+ receiptPath,+ nonce,+ host,+ dispose: () => removeAllDuringTeardown(receiptDir),+ };+}++export function beginViteStartup(+ request: ViteStartupRequest,+ proc: ChildProcess,+): PendingViteStartup {+ return { request, proc, startedAt: Date.now() };+}++function parseStartupReceipt(pending: PendingViteStartup): TestServerStartupReceipt {+ let value: unknown;+ try {+ value = JSON.parse(readFileSync(pending.request.receiptPath, 'utf-8'));+ } catch (err) {+ throw new Error(`automatic Vite startup receipt is unreadable: ${String(err)}`);+ }+ if (typeof value !== 'object' || value === null) {+ throw new Error('automatic Vite startup receipt has an invalid shape');+ }+ const receipt = value as Record<string, unknown>;+ const { request } = pending;+ if (+ receipt.nonce !== request.nonce ||+ receipt.address !== request.host ||+ receipt.family !== TEST_SERVER_HOST_FAMILY[request.host] ||+ typeof receipt.port !== 'number' ||+ !Number.isInteger(receipt.port) ||+ receipt.port < request.candidatePort ||+ receipt.port > 65535+ ) {+ throw new Error('automatic Vite startup receipt does not match its request');+ }+ return {+ nonce: request.nonce,+ address: request.host,+ family: TEST_SERVER_HOST_FAMILY[request.host],+ port: receipt.port,+ };+}++function waitForStartupReceipt(+ pending: PendingViteStartup,+ deadlineAt: number,+): Promise<TestServerStartupReceipt> {+ return new Promise((resolve, reject) => {+ let watcher: ReturnType<typeof watch> | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let settled = false;+ const cleanup = () => {+ watcher?.off('error', onWatchError);+ watcher?.close();+ if (timer !== undefined) clearTimeout(timer);+ pending.proc.off('error', onError);+ pending.proc.off('exit', onExit);+ };+ const finish = (result: TestServerStartupReceipt | Error) => {+ if (settled) return;+ settled = true;+ cleanup();+ if (result instanceof Error) reject(result);+ else resolve(result);+ };+ const onError = (err: Error) => {+ finish(new Error(`automatic Vite startup command failed: ${err.message}`));+ };+ const onWatchError = (err: Error) => {+ finish(+ new Error(+ `automatic Vite startup receipt watcher on ${pending.request.receiptDir} failed: ${err.message}`,+ ),+ );+ };+ const onExit = () => {+ finish(+ new Error(+ `automatic Vite startup command exited ${describeExit(pending.proc)} without a receipt`,+ ),+ );+ };+ const readReceipt = () => {+ if (!existsSync(pending.request.receiptPath)) return;+ try {+ finish(parseStartupReceipt(pending));+ } catch (err) {+ finish(err instanceof Error ? err : new Error(String(err)));+ }+ };+ try {+ watcher = watch(pending.request.receiptDir, readReceipt);+ watcher.on('error', onWatchError);+ pending.proc.once('error', onError);+ pending.proc.once('exit', onExit);+ const remainingMs = deadlineAt - Date.now();+ if (remainingMs <= 0) {+ finish(+ new Error('automatic Vite startup exhausted its readiness budget before publication'),+ );+ return;+ }+ timer = setTimeout(+ () =>+ finish(+ new Error(+ 'automatic Vite startup did not publish an endpoint within its readiness budget',+ ),+ ),+ remainingMs,+ );+ readReceipt();+ if (pending.proc.exitCode !== null || pending.proc.signalCode !== null) onExit();+ } catch (err) {+ finish(err instanceof Error ? err : new Error(String(err)));+ }+ });+}++export async function waitForBoundViteEndpoint(+ pending: PendingViteStartup,+ timeoutMs: number,+): Promise<BoundViteEndpoint> {+ requireBoundMs(timeoutMs, 'waitForBoundViteEndpoint');+ const deadlineAt = pending.startedAt + timeoutMs;+ const receipt = await waitForStartupReceipt(pending, deadlineAt);+ const baseURL = endpointBaseURL(receipt);+ await assertViteStartupIdentity(pending, receipt, deadlineAt);+ return { port: receipt.port, baseURL };+}++function endpointBaseURL(receipt: TestServerStartupReceipt): string {+ return `http://${receipt.family === 'IPv6' ? `[${receipt.address}]` : receipt.address}:${receipt.port}`;+}++async function assertViteStartupIdentity(+ pending: PendingViteStartup,+ receipt: TestServerStartupReceipt,+ deadlineAt: number,+): Promise<void> {+ const baseURL = endpointBaseURL(receipt);+ const remainingMs = deadlineAt - Date.now();+ if (remainingMs <= 0) {+ throw new Error(+ 'automatic Vite startup exhausted its readiness budget before identity verification',+ );+ }+ const response = await fetch(`${baseURL}${TEST_SERVER_IDENTITY_PATH}`, {+ signal: AbortSignal.timeout(remainingMs),+ });+ if (response.status !== 200) {+ throw new Error(`automatic Vite startup identity returned status ${response.status}`);+ }+ let identity: unknown;+ try {+ identity = await response.json();+ } catch (err) {+ throw new Error(`automatic Vite startup identity is not JSON: ${String(err)}`);+ }+ if (+ typeof identity !== 'object' ||+ identity === null ||+ (identity as Record<string, unknown>).nonce !== receipt.nonce ||+ (identity as Record<string, unknown>).address !== receipt.address ||+ (identity as Record<string, unknown>).family !== receipt.family ||+ (identity as Record<string, unknown>).port !== receipt.port+ ) {+ throw new Error('automatic Vite startup identity does not match its receipt');+ }+ if (pending.proc.exitCode !== null || pending.proc.signalCode !== null) {+ throw new Error(+ `automatic Vite startup command exited ${describeExit(pending.proc)} after identity verification`,+ );+ }+ if (Date.now() >= deadlineAt) {+ throw new Error(+ 'automatic Vite startup exhausted its readiness budget during identity verification',+ );+ }+}+function describeExit(proc: ChildProcess): string {return proc.signalCode === null ? `with code ${proc.exitCode}` : `on ${proc.signalCode}`;}@@ -133,14 +372,25 @@ export async function waitForHttpReady(baseURL: string,timeoutMs: number,proc?: ChildProcess,+ startedAt = Date.now(),): Promise<void> {requireBoundMs(timeoutMs, 'waitForHttpReady');- const start = Date.now();+ const start = startedAt;let lastErr: unknown;while (Date.now() - start < timeoutMs) {+ const remainingMs = timeoutMs - (Date.now() - start);try {- const res = await fetch(`${baseURL}/`, { signal: AbortSignal.timeout(1000) });- if (res.status === 200 || res.status === 404) return;+ const res = await fetch(`${baseURL}/`, {+ signal: AbortSignal.timeout(Math.min(1000, remainingMs)),+ });+ if (res.status === 200 || res.status === 404) {+ if (proc !== undefined && (proc.exitCode !== null || proc.signalCode !== null)) {+ throw new Error(+ `dev server command for ${baseURL} exited ${describeExit(proc)} before readiness could be accepted`,+ );+ }+ return;+ }lastErr = new Error(`unexpected status ${res.status}`);} catch (err) {lastErr = err;@@ -150,7 +400,7 @@ export async function waitForHttpReady(`dev server command for ${baseURL} exited ${describeExit(proc)} after ${Date.now() - start}ms without becoming ready. Last error: ${String(lastErr)}`,);}- await wait(250);+ await wait(Math.min(250, Math.max(0, timeoutMs - (Date.now() - start))));}throw new Error(`dev server at ${baseURL} did not become ready within ${timeoutMs}ms. Last error: ${String(lastErr)}`,diff --git a/packages/app/tests/stress/harness-port-ownership.e2e.ts b/packages/app/tests/stress/harness-port-ownership.e2e.tsnew file mode 100644index 000000000..0bc0d417b--- /dev/null+++ b/packages/app/tests/stress/harness-port-ownership.e2e.ts@@ -0,0 +1,84 @@+import { writeFileSync } from 'node:fs';+import { expect, test } from '@playwright/test';+import { expectOwnedServerRun } from './_helpers/port-ownership/expect-owned-server-run.test-helper.ts';+import { runOwnerLossControl } from './_helpers/port-ownership/owner-loss.test-helper.ts';+import {+ type OwnershipRun,+ runOwnershipCase,+} from './_helpers/port-ownership/run-case.test-helper.ts';++test.describe.configure({ retries: 0 });+test.use({ trace: 'retain-on-failure' });++async function attachLifetimeRun(run: OwnershipRun): Promise<void> {+ const testInfo = test.info();+ const path = testInfo.outputPath('lifetime-run.json');+ writeFileSync(+ path,+ JSON.stringify({+ exitCode: run.exitCode,+ signal: run.signal,+ lifetime: run.lifetime,+ transcript: run.transcript,+ }),+ );+ await testInfo.attach('lifetime-run', { path, contentType: 'application/json' });+}++test('nested runner releases owned setup resources on timeout', async () => {+ const run = await runOwnershipCase({+ file: 'tests/stress/_helpers/port-ownership/lifetime.ownership-case.ts',+ name: 'nested lifetime control reaches its test body',+ caller: 'lifetime-timeout',+ });+ await attachLifetimeRun(run);+ expect(run.lifetime?.receipt, run.transcript).toBeDefined();+ expect(run.lifetime?.selfBoundFired, run.transcript).toBe(false);+ expect(run.exitCode, run.transcript).toBe(1);+ expect(run.stdioClosed, run.transcript).toBe(true);+ expect(run.lifetime?.servingAfterExit, JSON.stringify(run.lifetime)).toBe(false);+});++test('nested runner releases owned setup resources on normal completion', async () => {+ const run = await runOwnershipCase({+ file: 'tests/stress/_helpers/port-ownership/lifetime.ownership-case.ts',+ name: 'nested lifetime control reaches its test body',+ caller: 'lifetime-normal',+ });+ await attachLifetimeRun(run);+ expect(run.lifetime?.receipt, run.transcript).toBeDefined();+ expect(run.lifetime?.selfBoundFired, run.transcript).toBe(false);+ expect(run.matchingSpecs[0]?.tests[0]?.results[0]?.status, run.transcript).toBe('passed');+ expect(run.exitCode, run.transcript).toBe(0);+ expect(run.stdioClosed, run.transcript).toBe(true);+ expect(run.lifetime?.servingAfterExit, run.transcript).toBe(false);+});++test('nested runner releases owned setup resources when its owner exits', async () => {+ const result = await runOwnerLossControl();+ const path = test.info().outputPath('owner-loss-run.json');+ writeFileSync(path, JSON.stringify(result));+ await test.info().attach('owner-loss-run', { path, contentType: 'application/json' });+ expect(result.receipt.nonce).toBeTruthy();+ expect(result.driverExit, result.transcript).toBe(0);+ expect(result.driverSignal, result.transcript).toBeNull();+ expect(result.witnessClosed, JSON.stringify(result)).toBe(true);+ expect(result.servingAfterOwnerExit, JSON.stringify(result)).toBe(false);+ expect(result.scratchGone, JSON.stringify(result)).toBe(true);+});++test('automatically selected worker server owns its endpoint', async () => {+ await expectOwnedServerRun({+ file: 'tests/stress/_helpers/port-ownership/worker.ownership-case.ts',+ name: 'worker server owns its advertised endpoint',+ caller: 'fixtures.ts',+ });+});++test('automatically selected warm-cache server publishes a seed', async () => {+ await expectOwnedServerRun({+ file: 'tests/stress/_helpers/port-ownership/warm-cache.ownership-case.ts',+ name: 'warm cache owns a serving endpoint before publishing its seed',+ caller: 'global-warm-cache.ts',+ });+});diff --git a/packages/app/vite.config.ts b/packages/app/vite.config.tsindex 6650f067f..31badf881 100644--- a/packages/app/vite.config.ts+++ b/packages/app/vite.config.ts@@ -4,6 +4,11 @@ import { defineConfig } from 'vite';import { injectAppVersionEnv } from './src/build/app-version';import { chromeTokensVitePlugin } from './src/build/chrome-tokens-vite-plugin';import { rejectionLoopGuardPlugin } from './src/build/rejection-loop-guard-plugin';+import { TEST_SERVER_STARTUP_ENV } from './src/build/test-server-startup-contract';+import {+ parseTestServerStartupRequest,+ testServerStartupPlugin,+} from './src/build/test-server-startup-plugin';import { hocuspocusPlugin } from './src/server/hocuspocus-plugin';import { RENDERER_DEDUPE } from './vite.dedupe';import { RENDERER_HTML_ENTRIES, rendererHtmlInput } from './vite.entries';@@ -15,6 +20,13 @@ import { RENDERER_BABEL_OPTIONS } from './vite.react-babel';injectAppVersionEnv();const vitePort = process.env.VITE_PORT ? Number.parseInt(process.env.VITE_PORT, 10) : undefined;+const startupRequest = parseTestServerStartupRequest(process.env[TEST_SERVER_STARTUP_ENV]);+if (+ startupRequest !== undefined &&+ process.env.VITE_PORT !== String(startupRequest.candidatePort)+) {+ throw new Error('automatic Vite startup candidate differs from VITE_PORT');+}// Per-worker Vite optimized-dependency cache dir. Set by the per-worker// Playwright fixture alongside `VITE_PORT` and `OK_TEST_CONTENT_DIR`, so N@@ -62,6 +74,7 @@ export default defineConfig({// options are shared with the Electron renderer build.babel(RENDERER_BABEL_OPTIONS),hocuspocusPlugin(),+ ...(startupRequest === undefined ? [] : [testServerStartupPlugin(startupRequest)]),],resolve: {tsconfigPaths: true,@@ -75,7 +88,7 @@ export default defineConfig({},server: {port: vitePort ?? 5173,- strictPort: vitePort !== undefined,+ strictPort: startupRequest === undefined && vitePort !== undefined,watch: {// Exclude the content/ directory from Vite's HMR watcher.// Markdown files here are managed by the Hocuspocus file watcher + persistence