Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Speed up and harden the OK browser test tier (#6336)
Nick Gomez13724db483f6
diff --git a/packages/app/tests/foundation/babel-output-cache.node.test.ts b/packages/app/tests/foundation/babel-output-cache.node.test.tsnew file mode 100644index 000000000..806bcb867--- /dev/null+++ b/packages/app/tests/foundation/babel-output-cache.node.test.ts@@ -0,0 +1,368 @@+import { execFile } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import {+ copyFileSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createServer, type Plugin } from 'vite';+import { afterEach, describe, expect, test } from 'vitest';+import {+ APP_BROWSER_BABEL_OUTPUT,+ appBrowserBabelPasses,+ appBrowserVitestConfig,+} from '../../vitest.browser.config';+import {+ BABEL_OUTPUT_KEY_ENV,+ BABEL_OUTPUT_KEY_FILES,+ babelOutputCache,+} from './babel-output-cache';++const APP_ROOT = fileURLToPath(new URL('../../', import.meta.url));+const OK_ROOT = join(APP_ROOT, '..', '..');+const PRODUCT_MODULE = '/src/components/OutlinePanel.tsx';+const TEST_MODULE = '/tests/foundation/outline-panel.browser.test.tsx';++function unseenIds(): [string, string] {+ const probe = randomUUID();+ return [`${PRODUCT_MODULE}?probe=${probe}`, `${TEST_MODULE}?probe=${probe}`];+}+const COMPILE_TIMEOUT_MS = 60_000;++const REQUIRED_KEY_FILES = [+ join(OK_ROOT, 'pnpm-lock.yaml'),+ join(OK_ROOT, 'node_modules', '.pnpm', 'lock.yaml'),+ join(APP_ROOT, 'vite.react-babel.ts'),+ join(APP_ROOT, 'vitest.browser.config.ts'),+ join(APP_ROOT, 'tests', 'foundation', 'browser-node-compat.ts'),+ join(APP_ROOT, 'tests', 'foundation', 'babel-output-cache.ts'),+ join(APP_ROOT, 'lingui.config.ts'),+];++const scratch: string[] = [];++afterEach(() => {+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function scratchDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-babel-output-cache-'));+ scratch.push(dir);+ return dir;+}++function filesUnder(dir: string): string[] {+ return readdirSync(dir, { recursive: true, encoding: 'utf8' })+ .map((entry) => join(dir, entry))+ .filter((path) => statSync(path, { throwIfNoEntry: false })?.isFile());+}++type Call = {+ readonly index: number;+ readonly environment: string;+ readonly moduleType: string;+ readonly id: string;+ readonly code: string;+};++const BASE_CALL: Call = {+ index: 0,+ environment: 'client',+ moduleType: 'tsx',+ id: '/app/src/Example.tsx',+ code: 'export const Example = () => null;',+};++function countingPass() {+ let compiles = 0;+ const plugin = {+ name: 'counting-pass',+ transform: {+ handler: (code: string, id: string) => {+ compiles += 1;+ return { code: `${code}\n//compiled ${id}`, map: { mappings: 'AAAA' } };+ },+ },+ };+ return { plugin, compiles: () => compiles };+}++async function compileOnce(+ cache: ReturnType<typeof babelOutputCache>,+ call: Call = BASE_CALL,+): Promise<{ compiled: boolean; value: unknown; counts: ReturnType<typeof cache.counts> }> {+ const pass = countingPass();+ const plugin = await cache.wrap(pass.plugin, call.index);+ const handler = plugin.transform.handler as unknown as (+ this: unknown,+ code: string,+ id: string,+ options: { moduleType: string },+ ) => Promise<unknown>;+ const value = await handler.call(+ { environment: { name: call.environment } },+ call.code,+ call.id,+ {+ moduleType: call.moduleType,+ },+ );+ return { compiled: pass.compiles() === 1, value, counts: cache.counts(call.index) };+}++function keyedScratch() {+ const dir = scratchDir();+ const directory = join(dir, 'cache');+ const keyFiles = BABEL_OUTPUT_KEY_FILES.map((path, position) => {+ const copy = join(dir, 'inputs', String(position), basename(path));+ mkdirSync(join(dir, 'inputs', String(position)), { recursive: true });+ copyFileSync(path, copy);+ return copy;+ });+ const env: Record<string, string | undefined> = Object.fromEntries(+ BABEL_OUTPUT_KEY_ENV.map((name) => [name, `value-of-${name}`]),+ );+ const fresh = (overrides: { env?: Record<string, string | undefined> } = {}) =>+ babelOutputCache({ directory, keyFiles, env: overrides.env ?? env });+ return { directory, keyFiles, env, fresh };+}++async function transformAll(plugins: Plugin[], ids: readonly string[]): Promise<string[]> {+ const server = await createServer({+ configFile: false,+ root: APP_ROOT,+ logLevel: 'silent',+ plugins,+ resolve: { alias: appBrowserVitestConfig.resolve.alias },+ server: { middlewareMode: true, ws: false, preTransformRequests: false },+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ try {+ const codes: string[] = [];+ for (const id of ids) {+ const result = await server.environments.client.transformRequest(id);+ if (result === null) throw new Error(`${id} produced no transform result`);+ codes.push(result.code);+ }+ return codes;+ } finally {+ await server.close();+ }+}++async function configBabelPasses(): Promise<Plugin[]> {+ const plugins = await Promise.all(appBrowserVitestConfig.plugins.flat());+ return plugins.filter(+ (plugin): plugin is Plugin =>+ typeof plugin === 'object' && plugin !== null && plugin.name === '@rolldown/plugin-babel',+ );+}++describe('the browser tier Babel output cache key', () => {+ test('a second compile of the same module from the same inputs is served from the cache, unchanged', async () => {+ const { fresh } = keyedScratch();+ const first = await compileOnce(fresh());+ const second = await compileOnce(fresh());++ expect(first.compiled).toBe(true);+ expect(second.compiled).toBe(false);+ expect(second.counts).toEqual({ hits: 1, misses: 0, unwritten: 0 });+ expect(second.value).toEqual(first.value);+ });++ test.each(+ REQUIRED_KEY_FILES.map((required) => ({ required, label: relative(OK_ROOT, required) })),+ )('editing $label makes the next compile miss', async ({ required }) => {+ const { keyFiles, fresh } = keyedScratch();+ await compileOnce(fresh());+ const position = BABEL_OUTPUT_KEY_FILES.indexOf(required);+ expect(position).toBeGreaterThanOrEqual(0);+ writeFileSync(keyFiles[position] as string, '\nedited\n', { flag: 'a' });++ expect((await compileOnce(fresh())).compiled).toBe(true);+ });++ test.each(BABEL_OUTPUT_KEY_ENV)(+ 'a different %s value makes the next compile miss, and an unset one too',+ async (name) => {+ const { env, fresh } = keyedScratch();+ await compileOnce(fresh());++ expect((await compileOnce(fresh({ env: { ...env, [name]: 'changed' } }))).compiled).toBe(+ true,+ );+ expect((await compileOnce(fresh({ env: { ...env, [name]: undefined } }))).compiled).toBe(+ true,+ );+ },+ );++ test.each([+ ['Babel pass', { index: 1 }],+ ['Vite environment', { environment: 'ssr' }],+ ['module type', { moduleType: 'ts' }],+ ['module id', { id: '/app/src/Other.tsx' }],+ ['source text reaching the pass', { code: 'export const Example = () => 1;' }],+ ] as const)('a different %s makes the compile miss', async (_label, change) => {+ const { fresh } = keyedScratch();+ await compileOnce(fresh());++ expect((await compileOnce(fresh(), { ...BASE_CALL, ...change })).compiled).toBe(true);+ });+});++describe('the browser tier Babel output cache never fails a run over its own storage', () => {+ test('a cache directory that cannot be created still compiles, and records the entry as unwritten', async () => {+ const dir = scratchDir();+ const blocked = join(dir, 'a-file');+ writeFileSync(blocked, 'not a directory');+ const cache = babelOutputCache({ directory: join(blocked, 'cache'), keyFiles: [], env: {} });++ const run = await compileOnce(cache);++ expect(run.compiled).toBe(true);+ expect(run.value).toEqual({+ code: `${BASE_CALL.code}\n//compiled ${BASE_CALL.id}`,+ map: { mappings: 'AAAA' },+ });+ expect(run.counts).toEqual({ hits: 0, misses: 1, unwritten: 1 });+ });++ test('a corrupt entry is a miss that the compile rewrites', async () => {+ const { directory, fresh } = keyedScratch();+ await compileOnce(fresh());+ const entries = filesUnder(directory);+ expect(entries).toHaveLength(1);+ for (const entry of entries) writeFileSync(entry, '{"schema":');++ expect((await compileOnce(fresh())).compiled).toBe(true);+ expect((await compileOnce(fresh())).compiled).toBe(false);+ });++ test('an entry path that cannot be replaced is a miss, and the failed write leaves no partial file behind', async () => {+ const { directory, fresh } = keyedScratch();+ await compileOnce(fresh());+ const [entry] = filesUnder(directory);+ expect(entry).toBeDefined();+ rmSync(entry as string);+ mkdirSync(join(entry as string, 'occupied'), { recursive: true });++ const run = await compileOnce(fresh());++ expect(run.compiled).toBe(true);+ expect(run.counts).toEqual({ hits: 0, misses: 1, unwritten: 1 });+ expect(filesUnder(directory).filter((path) => path.endsWith('.tmp'))).toEqual([]);+ });+});++describe('the browser config compiles through the cache', () => {+ test(+ 'each of the config’s Babel passes reads and writes the cache, and a warm compile is byte-identical to a fresh one',+ async () => {+ const passes = await configBabelPasses();+ expect(passes).toHaveLength(appBrowserBabelPasses().length);+ const before = passes.map((_, index) => APP_BROWSER_BABEL_OUTPUT.counts(index));++ const ids = unseenIds();++ await transformAll(passes, ids);+ const afterCold = passes.map((_, index) => APP_BROWSER_BABEL_OUTPUT.counts(index));+ const warm = await transformAll(passes, ids);+ const afterWarm = passes.map((_, index) => APP_BROWSER_BABEL_OUTPUT.counts(index));+ const uncached = await transformAll(+ (await Promise.all(appBrowserBabelPasses())) as unknown as Plugin[],+ ids,+ );++ expect(+ afterCold.map((counts, index) => counts.misses - (before[index]?.misses ?? 0)),+ ).toEqual(passes.map(() => 1));+ expect(afterWarm.map((counts, index) => counts.hits - (afterCold[index]?.hits ?? 0))).toEqual(+ passes.map(() => 1),+ );+ expect(warm).toEqual(uncached);+ },+ COMPILE_TIMEOUT_MS,+ );+});++const OBSERVE_ENV_READS = `+const compileReads = new Set();+const configReads = new Set();+let compiling = 0;+let loadingConfig = false;+const note = (name) => {+ if (typeof name !== 'string') return;+ if (compiling > 0) compileReads.add(name);+ if (loadingConfig && /vitest\\.browser\\.config\\.ts\\.timestamp/.test(new Error().stack ?? '')) configReads.add(name);+};+process.env = new Proxy(process.env, {+ get(target, name) { note(name); return Reflect.get(target, name); },+ has(target, name) { note(name); return Reflect.has(target, name); },+});+const { createServer, loadConfigFromFile } = await import('vite');+const root = process.cwd();+const [cacheDir, ...ids] = process.argv.slice(1);+loadingConfig = true;+const loaded = await loadConfigFromFile({ command: 'serve', mode: 'test' }, root + '/vitest.browser.config.ts', root, 'silent');+const plugins = (await Promise.all(loaded.config.plugins.flat())).filter((plugin) => plugin && plugin.name === '@rolldown/plugin-babel');+loadingConfig = false;+for (const plugin of plugins) {+ const inner = plugin.transform.handler;+ plugin.transform.handler = async function (...args) {+ compiling += 1;+ try { return await inner.apply(this, args); } finally { compiling -= 1; }+ };+}+const server = await createServer({ configFile: false, root, cacheDir, logLevel: 'silent', plugins, resolve: { alias: loaded.config.resolve.alias }, server: { middlewareMode: true, ws: false, preTransformRequests: false }, optimizeDeps: { noDiscovery: true, include: [] } });+for (const id of ids) await server.environments.client.transformRequest(id);+await server.close();+process.stdout.write(JSON.stringify({ passes: plugins.length, configReads: [...configReads].sort(), compileReads: [...compileReads].sort() }));+process.exit(0);+`;++function observeEnvReads(): Promise<{+ passes: number;+ configReads: string[];+ compileReads: string[];+}> {+ const dir = scratchDir();+ const cacheDir = join(dir, 'node_modules', '.vite');+ return new Promise((resolve, reject) => {+ execFile(+ process.execPath,+ ['--input-type=module', '--eval', OBSERVE_ENV_READS, cacheDir, ...unseenIds()],+ { cwd: APP_ROOT, env: { ...process.env, TMPDIR: dir }, timeout: COMPILE_TIMEOUT_MS },+ (error, stdout, stderr) => {+ if (error) reject(new Error(`observing the compile failed: ${stderr || error.message}`));+ else resolve(JSON.parse(stdout));+ },+ );+ });+}++describe('the cache key covers every environment value the compile reads', () => {+ test(+ 'the config’s Babel option code and a cold compile of a product and a test module read only keyed environment values',+ async () => {+ const observed = await observeEnvReads();++ expect(observed.passes).toBe(appBrowserBabelPasses().length);+ expect(observed.compileReads).toContain('NODE_ENV');+ expect(observed.configReads.filter((name) => !BABEL_OUTPUT_KEY_ENV.includes(name))).toEqual(+ [],+ );+ expect(observed.compileReads.filter((name) => !BABEL_OUTPUT_KEY_ENV.includes(name))).toEqual(+ [],+ );+ },+ COMPILE_TIMEOUT_MS,+ );+});diff --git a/packages/app/tests/foundation/babel-output-cache.ts b/packages/app/tests/foundation/babel-output-cache.tsnew file mode 100644index 000000000..b9c3f7e05--- /dev/null+++ b/packages/app/tests/foundation/babel-output-cache.ts@@ -0,0 +1,182 @@+import { createHash, randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const APP_ROOT = fileURLToPath(new URL('../../', import.meta.url));+const OK_ROOT = join(APP_ROOT, '..', '..');++export const BABEL_OUTPUT_CACHE_DIR = join(APP_ROOT, 'node_modules', '.cache', 'ok-browser-babel');++export const BABEL_OUTPUT_KEY_FILES: readonly string[] = [+ join(OK_ROOT, 'pnpm-lock.yaml'),+ join(OK_ROOT, 'node_modules', '.pnpm', 'lock.yaml'),+ join(APP_ROOT, 'vite.react-babel.ts'),+ join(APP_ROOT, 'vitest.browser.config.ts'),+ join(APP_ROOT, 'tests', 'foundation', 'browser-node-compat.ts'),+ join(APP_ROOT, 'tests', 'foundation', 'babel-output-cache.ts'),+ join(APP_ROOT, 'lingui.config.ts'),+];++export const BABEL_OUTPUT_KEY_ENV: readonly string[] = [+ 'BABEL_ENV',+ 'BABEL_SHOW_CONFIG_FOR',+ 'BABEL_TYPES_8_BREAKING',+ 'BROWSERSLIST',+ 'BROWSERSLIST_CONFIG',+ 'BROWSERSLIST_DISABLE_CACHE',+ 'BROWSERSLIST_ROOT_PATH',+ 'CI',+ 'DEBUG',+ 'ENABLE_REACT_COMPILER_TIMINGS',+ 'FORCE_COLOR',+ 'JITI_ALIAS',+ 'JITI_CACHE',+ 'JITI_DEBUG',+ 'JITI_ESM_EVAL_TEMP_FILE',+ 'JITI_EXTENSIONS',+ 'JITI_FS_CACHE',+ 'JITI_INTEROP_DEFAULT',+ 'JITI_JSX',+ 'JITI_MODULE_CACHE',+ 'JITI_NATIVE_MODULES',+ 'JITI_REBUILD_FS_CACHE',+ 'JITI_REQUIRE_CACHE',+ 'JITI_SOURCE_MAPS',+ 'JITI_TRANSFORM_MODULES',+ 'JITI_TRY_NATIVE',+ 'JITI_TSCONFIG_PATHS',+ 'LINGUI_CONFIG',+ 'NODE_DEBUG',+ 'NODE_ENV',+ 'NODE_V8_COVERAGE',+ 'NO_COLOR',+ 'TMPDIR',+ 'WATCH_REPORT_DEPENDENCIES',+];++const ENTRY_SCHEMA = 'ok-browser-babel-output-v1';++type TransformResult = { readonly code?: string; readonly map?: unknown } | null | undefined;++type TransformHandler = (+ this: { readonly environment?: { readonly name?: string } },+ code: string,+ id: string,+ options?: { readonly moduleType?: string },+) => TransformResult | Promise<TransformResult>;++export type BabelOutputCacheCounts = { hits: number; misses: number; unwritten: number };++export type BabelOutputCacheOptions = {+ readonly directory?: string;+ readonly keyFiles?: readonly string[];+ readonly env?: Readonly<Record<string, string | undefined>>;+};++function fileDigest(path: string): string {+ try {+ return createHash('sha256').update(readFileSync(path)).digest('hex');+ } catch {+ return 'unreadable';+ }+}++function readEntry(path: string): { value: TransformResult } | undefined {+ try {+ const entry = JSON.parse(readFileSync(path, 'utf8')) as { schema?: unknown; value?: unknown };+ if (entry.schema !== ENTRY_SCHEMA || !('value' in entry)) return undefined;+ return { value: entry.value as TransformResult };+ } catch {+ return undefined;+ }+}++function writeEntry(path: string, value: TransformResult): boolean {+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;+ try {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(temporary, JSON.stringify({ schema: ENTRY_SCHEMA, value: value ?? null }));+ renameSync(temporary, path);+ return true;+ } catch {+ try {+ rmSync(temporary, { force: true });+ } catch {}+ return false;+ }+}++export function babelOutputCache(options: BabelOutputCacheOptions = {}) {+ const directory = options.directory ?? BABEL_OUTPUT_CACHE_DIR;+ const keyFiles = options.keyFiles ?? BABEL_OUTPUT_KEY_FILES;+ const env = options.env ?? process.env;+ const counts = new Map<number, BabelOutputCacheCounts>();+ const countsFor = (index: number) => {+ const entry = counts.get(index) ?? { hits: 0, misses: 0, unwritten: 0 };+ counts.set(index, entry);+ return entry;+ };+ let inputs: string | undefined;+ const keyInputs = () => {+ inputs ??= JSON.stringify([+ ENTRY_SCHEMA,+ keyFiles.map((path) => [path, fileDigest(path)]),+ BABEL_OUTPUT_KEY_ENV.map((name) => [name, env[name] ?? null]),+ ]);+ return inputs;+ };++ async function wrap<P extends { readonly name: string; transform?: unknown }>(+ pending: P | Promise<P>,+ index: number,+ ): Promise<P> {+ const plugin = await pending;+ const transform = plugin.transform as { handler?: unknown } | undefined;+ if (+ typeof transform !== 'object' ||+ transform === null ||+ typeof transform.handler !== 'function'+ ) {+ throw new Error(`the Babel output cache needs a transform handler on ${plugin.name}`);+ }+ const handler = transform.handler as TransformHandler;+ transform.handler = async function cachedBabelTransform(+ this: { readonly environment?: { readonly name?: string } },+ code: string,+ id: string,+ transformOptions?: { readonly moduleType?: string },+ ) {+ const key = createHash('sha256')+ .update(+ JSON.stringify([+ keyInputs(),+ index,+ this.environment?.name ?? null,+ transformOptions?.moduleType ?? null,+ id,+ code,+ ]),+ )+ .digest('hex');+ const path = join(directory, key.slice(0, 2), `${key}.json`);+ const cached = readEntry(path);+ const tally = countsFor(index);+ if (cached !== undefined) {+ tally.hits += 1;+ return cached.value ?? undefined;+ }+ tally.misses += 1;+ const value = await handler.call(this, code, id, transformOptions);+ if (!writeEntry(path, value)) tally.unwritten += 1;+ return value;+ };+ return plugin;+ }++ return {+ directory,+ wrap,+ counts: (index: number): BabelOutputCacheCounts => ({ ...countsFor(index) }),+ };+}diff --git a/packages/app/tests/foundation/browser-dependency-optimizer.ts b/packages/app/tests/foundation/browser-dependency-optimizer.tsnew file mode 100644index 000000000..ac061c2a0--- /dev/null+++ b/packages/app/tests/foundation/browser-dependency-optimizer.ts@@ -0,0 +1,86 @@+import { stripVTControlCharacters } from 'node:util';+import type { Logger, Plugin } from 'vite';+import type { Vitest } from 'vitest/node';++export const BROWSER_OPTIMIZE_DEPS_INCLUDE = [+ '@codemirror/legacy-modes/mode/clike',+ '@codemirror/legacy-modes/mode/diff',+ '@codemirror/legacy-modes/mode/gherkin',+ '@codemirror/legacy-modes/mode/lua',+ '@codemirror/legacy-modes/mode/perl',+ '@codemirror/legacy-modes/mode/properties',+ '@codemirror/legacy-modes/mode/r',+ '@codemirror/legacy-modes/mode/ruby',+ '@codemirror/legacy-modes/mode/sql',+ '@codemirror/legacy-modes/mode/swift',+ '@codemirror/legacy-modes/mode/toml',+ '@dnd-kit/core',+ '@dnd-kit/sortable',+ '@dnd-kit/utilities',+ '@pierre/trees/react',+ '@tiptap/extension-placeholder',+ '@tiptap/pm/history',+ '@tiptap/pm/keymap',+ '@tiptap/react/menus',+ 'codemirror',+ 'date-fns',+ 'frimousse',+ 'lucide-react/dist/esm/icons/bot',+ 'lucide-react/dist/esm/icons/link-2',+ 'lucide-react/dist/esm/icons/package',+ 'react-dom/client',+ 'react-resizable-panels',+] as const;++const INCLUDE_LIST_LOCATION =+ 'BROWSER_OPTIMIZE_DEPS_INCLUDE in packages/app/tests/foundation/browser-dependency-optimizer.ts';+const NEWLY_OPTIMIZED = /new dependenc(?:y|ies) optimized: (.+)$/;+const RELOADING = /optimized dependencies changed\. reloading/;++export function describeDependencyReload(dependencies: readonly string[]): string {+ const named =+ dependencies.length > 0 ? `: ${dependencies.join(', ')}` : ', which the Vite log above names';+ return [+ `The browser tier pre-bundles a fixed dependency list, and this run needed dependencies outside it${named}.`,+ 'Vite bundled them mid-run and reloaded the page, which can fail, hang or rerun tests for no product reason.',+ `Add them to ${INCLUDE_LIST_LOCATION}.`,+ ].join('\n');+}++export function dependencyReloadGuard(): Plugin {+ let vitest: Vitest | undefined;+ let discovered: string[] = [];+ const observe = (message: string) => {+ const text = stripVTControlCharacters(message);+ const optimized = NEWLY_OPTIMIZED.exec(text);+ if (optimized?.[1]) {+ for (const name of optimized[1].split(', ')) {+ if (!discovered.includes(name)) discovered.push(name);+ }+ }+ if (!RELOADING.test(text)) return;+ const reload = new Error(describeDependencyReload(discovered));+ discovered = [];+ if (vitest === undefined) throw reload;+ vitest.state.catchError(reload, 'Unhandled Error');+ };+ return {+ name: 'ok:browser-dependency-reload-guard',+ configureVitest(context) {+ vitest = context.vitest;+ },+ configResolved(config) {+ const logger: Logger = config.logger;+ const info = logger.info.bind(logger);+ const warn = logger.warn.bind(logger);+ logger.info = (message, options) => {+ info(message, options);+ observe(message);+ };+ logger.warn = (message, options) => {+ warn(message, options);+ observe(message);+ };+ },+ };+}diff --git a/packages/app/tests/foundation/dependency-reload-guard.browser.test.ts b/packages/app/tests/foundation/dependency-reload-guard.browser.test.tsnew file mode 100644index 000000000..a8a3a8cfa--- /dev/null+++ b/packages/app/tests/foundation/dependency-reload-guard.browser.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test } from 'vitest';+import { commands } from 'vitest/browser';+import type { BrowserFixtureRun } from './browser-fixture-run';+import { NESTED_RUN_TIMEOUT_MS } from './nested-run-budget';++function fixtureOutcome(run: BrowserFixtureRun, file: string) {+ return {+ exitCode: run.exitCode,+ statuses: run.files?.find((entry) => entry.file === file)?.tests.map((entry) => entry.status),+ output: `${run.stdout}\n${run.stderr}`,+ };+}++describe('a dependency outside the pre-bundled list fails the browser tier instead of reloading it silently', () => {+ test(+ 'a run that needs an unlisted dependency fails and names the dependency and the list to add it to',+ async () => {+ const file = 'dependency-reload-unlisted.fixture.ts';+ const outcome = fixtureOutcome(await commands.runBrowserFixture({ files: [file] }), file);++ expect(outcome.statuses).toEqual(['passed']);+ expect(outcome.output).toContain('optimized dependencies changed. reloading');+ expect(outcome.output).toContain(+ 'this run needed dependencies outside it: @codemirror/legacy-modes/mode/cobol.',+ );+ expect(outcome.output).toContain('Add them to BROWSER_OPTIMIZE_DEPS_INCLUDE');+ expect(outcome.exitCode).toBe(1);+ },+ NESTED_RUN_TIMEOUT_MS,+ );++ test(+ 'a run whose dependencies are all on the list passes without a reload',+ async () => {+ const file = 'dependency-reload-listed.fixture.ts';+ const outcome = fixtureOutcome(await commands.runBrowserFixture({ files: [file] }), file);++ expect(outcome.statuses).toEqual(['passed']);+ expect(outcome.output).not.toContain('optimized dependencies changed. reloading');+ expect(outcome.output).not.toContain('Add them to BROWSER_OPTIMIZE_DEPS_INCLUDE');+ expect(outcome.exitCode).toBe(0);+ },+ NESTED_RUN_TIMEOUT_MS,+ );+});diff --git a/packages/app/tests/foundation/fixtures/dependency-reload-listed.fixture.ts b/packages/app/tests/foundation/fixtures/dependency-reload-listed.fixture.tsnew file mode 100644index 000000000..c50bcd83f--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dependency-reload-listed.fixture.ts@@ -0,0 +1,8 @@+import { expect, test } from 'vitest';++test('a module the dependency scan cannot see loads a dependency on the pre-bundled list', async () => {+ const mode = await import(+ /* @vite-ignore */ new URL('./dependency-reload/listed-mode.ts', import.meta.url).href+ );+ expect(mode.toml.name).toBe('toml');+});diff --git a/packages/app/tests/foundation/fixtures/dependency-reload-unlisted.fixture.ts b/packages/app/tests/foundation/fixtures/dependency-reload-unlisted.fixture.tsnew file mode 100644index 000000000..b4a7ec91c--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dependency-reload-unlisted.fixture.ts@@ -0,0 +1,8 @@+import { expect, test } from 'vitest';++test('a module the dependency scan cannot see loads a dependency outside the pre-bundled list', async () => {+ const mode = await import(+ /* @vite-ignore */ new URL('./dependency-reload/unlisted-mode.ts', import.meta.url).href+ );+ expect(mode.cobol.name).toBe('cobol');+});diff --git a/packages/app/tests/foundation/fixtures/dependency-reload/listed-mode.ts b/packages/app/tests/foundation/fixtures/dependency-reload/listed-mode.tsnew file mode 100644index 000000000..681e4b7e5--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dependency-reload/listed-mode.ts@@ -0,0 +1 @@+export { toml } from '@codemirror/legacy-modes/mode/toml';diff --git a/packages/app/tests/foundation/fixtures/dependency-reload/unlisted-mode.ts b/packages/app/tests/foundation/fixtures/dependency-reload/unlisted-mode.tsnew file mode 100644index 000000000..6ab308f61--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dependency-reload/unlisted-mode.ts@@ -0,0 +1 @@+export { cobol } from '@codemirror/legacy-modes/mode/cobol';diff --git a/packages/app/tests/foundation/owned-server-lost-owner.node.test.ts b/packages/app/tests/foundation/owned-server-lost-owner.node.test.tsnew file mode 100644index 000000000..6ec8f26ff--- /dev/null+++ b/packages/app/tests/foundation/owned-server-lost-owner.node.test.ts@@ -0,0 +1,60 @@+import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { launchOwnedWorkerServer } from '../stress/_helpers/reuse/owned-dev-server.ts';+import { APP_PACKAGE_ROOT } from '../stress/_helpers/seed-key.ts';++const LABEL = 'lost-owner-s0';+const LIFETIME_LOSS =+ 'worker server lifetime closed without completed release (code=1, signal=null)';+const LAUNCH_TIMEOUT_MS = 60_000;+const saved = { TMPDIR: process.env.TMPDIR, NODE_OPTIONS: process.env.NODE_OPTIONS };+const scratchDirs: string[] = [];++afterEach(() => {+ for (const [name, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ for (const dir of scratchDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function viteCacheDirsOf(label: string): string[] {+ const modules = join(APP_PACKAGE_ROOT, 'node_modules');+ if (!existsSync(modules)) return [];+ return readdirSync(modules).filter((name) => name.startsWith(`.vite-${label}-`));+}++describe('an owned server whose lifetime owner is lost before it releases', () => {+ test(+ 'the real lifetime’s loss fails the launch, the release that follows reports the same loss instead of throwing, and nothing the launch created is left',+ async () => {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-owned-lost-owner-')));+ scratchDirs.push(root);+ const tmp = join(root, 'tmp');+ mkdirSync(tmp);+ process.env.TMPDIR = tmp;+ process.env.NODE_OPTIONS = `--require=${join(root, 'no-such-preload.cjs')}`;++ const failure = await launchOwnedWorkerServer({+ label: LABEL,+ workerServerEnv: {},+ serving: { kind: 'dev-server' },+ }).then(+ () => undefined,+ (error: unknown) => error,+ );++ expect(failure).toBeInstanceOf(Error);+ const lines = (failure as Error).message.split('\n');+ expect(lines[0]).toBe(LIFETIME_LOSS);+ expect(lines.at(-1)).toBe(+ `--- cleanup after this failure did not complete: ${LIFETIME_LOSS} ---`,+ );+ expect(readdirSync(tmp)).toEqual([]);+ expect(viteCacheDirsOf(LABEL)).toEqual([]);+ },+ LAUNCH_TIMEOUT_MS,+ );+});diff --git a/packages/app/tests/foundation/supervisor-socket-directory.node.test.ts b/packages/app/tests/foundation/supervisor-socket-directory.node.test.tsnew file mode 100644index 000000000..acbfbbec9--- /dev/null+++ b/packages/app/tests/foundation/supervisor-socket-directory.node.test.ts@@ -0,0 +1,105 @@+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ realpathSync,+ rmSync,+ symlinkSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { WorkerServerSupervisor } from '../stress/_helpers/reuse/server-supervisor.ts';+import {+ type SupervisorEndpoint,+ serveSupervisor,+} from '../stress/_helpers/reuse/supervisor-socket.ts';+import { APP_PACKAGE_ROOT } from '../stress/_helpers/seed-key.ts';++const OK_ROOT = realpathSync(join(APP_PACKAGE_ROOT, '..', '..'));+const scratchDirs: string[] = [];+const endpoints: SupervisorEndpoint[] = [];++afterEach(async () => {+ for (const endpoint of endpoints.splice(0)) await endpoint.close();+ for (const dir of scratchDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function scratch(): string {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-sockdir-')));+ scratchDirs.push(dir);+ return dir;+}++function supervisor(): WorkerServerSupervisor {+ return new WorkerServerSupervisor({+ okRoot: OK_ROOT,+ launch: () => Promise.reject(new Error('no server is launched by these cases')),+ identityTimeoutMs: 2_000,+ });+}++const runningAsRoot = process.getuid?.() === 0;++describe('the reuse supervisor serves only from a socket directory no other user can change', () => {+ test.each([+ ['world-writable', 0o777, '0777'],+ ['group-writable', 0o770, '0770'],+ ])(+ 'a %s socket directory is refused and nothing is created in it',+ async (_kind, mode, shown) => {+ const shared = join(scratch(), 'shared');+ mkdirSync(shared);+ chmodSync(shared, mode);+ const socketPath = join(shared, 'supervisor.sock');++ await expect(serveSupervisor(supervisor(), socketPath)).rejects.toThrow(+ `cannot claim ${socketPath}: its directory ${shared} is group- or world-writable (mode ${shown}), so another user could replace the socket`,+ );+ expect(existsSync(socketPath)).toBe(false);+ },+ );++ test('a socket directory that is a symbolic link is refused, and the link and its target are left alone', async () => {+ const root = scratch();+ const target = join(root, 'real');+ mkdirSync(target, { mode: 0o700 });+ const linked = join(root, 'linked');+ symlinkSync(target, linked);+ const socketPath = join(linked, 'supervisor.sock');++ await expect(serveSupervisor(supervisor(), socketPath)).rejects.toThrow(+ `cannot claim ${socketPath}: its directory ${linked} is a symbolic link, so another user could replace the socket`,+ );+ expect(lstatSync(linked).isSymbolicLink()).toBe(true);+ expect(existsSync(join(target, 'supervisor.sock'))).toBe(false);+ });++ test.skipIf(runningAsRoot)(+ 'a socket directory another user owns is refused even when only its owner can write it',+ async () => {+ const owned = lstatSync('/usr');+ expect(owned.uid).not.toBe(process.getuid?.());+ expect(owned.mode & 0o022).toBe(0);+ const socketPath = '/usr/ok-reuse-supervisor.sock';++ await expect(serveSupervisor(supervisor(), socketPath)).rejects.toThrow(+ `cannot claim ${socketPath}: its directory /usr is owned by uid ${owned.uid}, not by this process's uid ${process.getuid?.()}, so another user could replace the socket`,+ );+ },+ );++ test('a socket directory it creates, and the same directory when it is served again, are accepted', async () => {+ const socketPath = join(scratch(), 'new', 's.sock');++ const first = await serveSupervisor(supervisor(), socketPath);+ expect(lstatSync(join(socketPath, '..')).mode & 0o077).toBe(0);+ await first.close();+ const again = await serveSupervisor(supervisor(), socketPath);+ endpoints.push(again);++ expect(lstatSync(socketPath).isSocket()).toBe(true);+ });+});diff --git a/packages/app/tests/stress/_helpers/reuse/supervisor-socket.ts b/packages/app/tests/stress/_helpers/reuse/supervisor-socket.tsindex 834b4a8d4..ec7145366 100644--- a/packages/app/tests/stress/_helpers/reuse/supervisor-socket.ts+++ b/packages/app/tests/stress/_helpers/reuse/supervisor-socket.ts@@ -58,8 +58,28 @@ function describeEntry(entry: Stats): string {return 'an entry of another kind';}+function unsafeDirectory(directory: string): string | undefined {+ const entry = lstatSync(directory);+ if (entry.isSymbolicLink()) return 'is a symbolic link';+ const uid = process.getuid?.();+ if (uid !== undefined && entry.uid !== uid) {+ return `is owned by uid ${entry.uid}, not by this process's uid ${uid}`;+ }+ if ((entry.mode & 0o022) !== 0) {+ return `is group- or world-writable (mode ${(entry.mode & 0o777).toString(8).padStart(4, '0')})`;+ }+ return undefined;+}+async function claimSocketPath(socketPath: string): Promise<void> {- mkdirSync(dirname(socketPath), { recursive: true, mode: 0o700 });+ const directory = dirname(socketPath);+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ const unsafe = unsafeDirectory(directory);+ if (unsafe !== undefined) {+ throw new Error(+ `cannot claim ${socketPath}: its directory ${directory} ${unsafe}, so another user could replace the socket`,+ );+ }const entry = lstatSync(socketPath, { throwIfNoEntry: false });if (entry === undefined) return;if (!entry.isSocket()) {diff --git a/packages/app/vitest.browser.config.ts b/packages/app/vitest.browser.config.tsindex f2523517b..32a8e472d 100644--- a/packages/app/vitest.browser.config.ts+++ b/packages/app/vitest.browser.config.ts@@ -4,6 +4,11 @@ import react from '@vitejs/plugin-react';import { playwright } from '@vitest/browser-playwright';import { configDefaults, defineConfig, type ViteUserConfig } from 'vitest/config';import { okVitestBase } from '../../test-support/vitest.base';+import { babelOutputCache } from './tests/foundation/babel-output-cache';+import {+ BROWSER_OPTIMIZE_DEPS_INCLUDE,+ dependencyReloadGuard,+} from './tests/foundation/browser-dependency-optimizer';import { runBrowserFixture } from './tests/foundation/browser-fixture-command';import { withMockContracts } from './tests/foundation/browser-mock-provider';import {@@ -30,6 +35,19 @@ const BROWSER_FILE_BRIDGE_ROOTS = [fileURLToPath(new URL('../../test-support/', import.meta.url)),];+export const APP_BROWSER_BABEL_OUTPUT = babelOutputCache();++export function appBrowserBabelPasses() {+ return [+ babel({ ...RENDERER_BABEL_OPTIONS, exclude: [...BROWSER_PRODUCT_MODULE_EXCLUDES] }),+ babel({+ plugins: RENDERER_BABEL_OPTIONS.plugins,+ include: [...BROWSER_TEST_MODULES],+ exclude: [NODE_MODULES],+ }),+ ];+}+export const APP_BROWSER_SETUP_FILES = [fileURLToPath(new URL('./tests/foundation/browser-setup.ts', import.meta.url)),];@@ -40,22 +58,18 @@ export const appBrowserVitestConfig = {plugins: [...okVitestBase.plugins,chromiumGcLaunchEnvGuard(),+ dependencyReloadGuard(),browserCiValue(process.env),browserNodeSubstitutes(BROWSER_FILE_BRIDGE_ROOTS),react(),- babel({ ...RENDERER_BABEL_OPTIONS, exclude: [...BROWSER_PRODUCT_MODULE_EXCLUDES] }),- babel({- plugins: RENDERER_BABEL_OPTIONS.plugins,- include: [...BROWSER_TEST_MODULES],- exclude: [NODE_MODULES],- }),+ ...appBrowserBabelPasses().map((pass, index) => APP_BROWSER_BABEL_OUTPUT.wrap(pass, index)),],resolve: {conditions: ['module', 'browser', 'development'],alias: [{ find: /^@\//, replacement: srcDir }],dedupe: [...RENDERER_DEDUPE],},- optimizeDeps: { force: true },+ optimizeDeps: { force: true, include: [...BROWSER_OPTIMIZE_DEPS_INCLUDE] },test: {testTimeout: okVitestBase.test.testTimeout,hookTimeout: okVitestBase.test.hookTimeout,