Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Bound Brain Inbox browser fixture startup by phase and stop its full-app dep scan

Claude7ad54bd75ed9
diff --git a/client/src/components/brain/tabs/InboxTab.browser.test.js b/client/src/components/brain/tabs/InboxTab.browser.test.js
index 7cd978b354..aa9acb57f4 100644
--- a/client/src/components/brain/tabs/InboxTab.browser.test.js
+++ b/client/src/components/brain/tabs/InboxTab.browser.test.js
@@ -1,13 +1,12 @@
// @vitest-environment node
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { existsSync } from 'node:fs';
-import { mkdtemp, rm } from 'node:fs/promises';
import { createRequire } from 'node:module';
-import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createServer } from 'vite';
import react from '@vitejs/plugin-react';
+import { BROWSER_FIXTURE_STARTUP_MS, startBrowserFixture } from '../../../test/browserFixture.js';
// Browser startup/navigation is bounded separately from 5s interactions.
vi.setConfig({ testTimeout: 30000 });
@@ -25,94 +24,91 @@ const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
].find(path => path && existsSync(path));
describe.skipIf(!chrome)('Brain inbox capture geometry', () => {
- let server;
+ let fixture;
let browser;
- let browserTemp;
let origin;
beforeAll(async () => {
- browserTemp = await mkdtemp(join(tmpdir(), 'inbox-chrome-'));
- server = await createServer({
- configFile: false,
- // Concurrent fixtures and linked worktrees must not replace each other's
- // optimized dependencies in the shared node_modules/.vite cache.
- cacheDir: join(browserTemp, 'vite-cache'),
- root: fileURLToPath(new URL('../../../..', import.meta.url)),
- plugins: [react(), {
- name: 'inbox-browser-fixture',
- enforce: 'pre',
- resolveId(id, importer) {
- if (id === '/inbox-fixture.jsx') return '\0inbox-fixture.jsx';
- if (importer?.endsWith('/InboxTab.jsx')) {
- if (id === '../../../services/api') return '\0inbox-api';
- if (id === '../../../services/socket') return '\0inbox-socket';
- if (id === '../../../hooks') return '\0inbox-hooks';
- }
+ // Vite start, Chromium launch and the cold-module warmup are each bounded
+ // inside the hook, so a stall names its phase and cleans up (#10543).
+ fixture = await startBrowserFixture({
+ name: 'inbox-chrome',
+ createServer,
+ chromium,
+ viteConfig: temp => ({
+ configFile: false,
+ // Concurrent fixtures and linked worktrees must not replace each other's
+ // optimized dependencies in the shared node_modules/.vite cache.
+ cacheDir: join(temp, 'vite-cache'),
+ // Pre-bundle only what this fixture renders, not the whole app's graph.
+ optimizeDeps: {
+ entries: ['src/components/brain/tabs/InboxTab.jsx'],
+ include: ['react-dom/client', 'react-router'],
},
- load(id) {
- if (id === '\0inbox-api') return `
- let history;
- export function getBrainInbox() {
- if (!history) history = new Promise(resolve => { window.resolveInboxHistory = resolve; });
- return history;
+ root: fileURLToPath(new URL('../../../..', import.meta.url)),
+ plugins: [react(), {
+ name: 'inbox-browser-fixture',
+ enforce: 'pre',
+ resolveId(id, importer) {
+ if (id === '/inbox-fixture.jsx') return '\0inbox-fixture.jsx';
+ if (importer?.endsWith('/InboxTab.jsx')) {
+ if (id === '../../../services/api') return '\0inbox-api';
+ if (id === '../../../services/socket') return '\0inbox-socket';
+ if (id === '../../../hooks') return '\0inbox-hooks';
}
- export async function captureBrainThought(...args) {
- window.captures = [...(window.captures || []), args];
- return { inboxLog: { id: 'example-thought', status: 'filed', capturedText: args[0] } };
- }
- `;
- if (id === '\0inbox-socket') return 'export default { on() {}, off() {} };';
- if (id === '\0inbox-hooks') return `
- import { useState } from 'react';
- export const useLocalStorageBool = () => useState(false);
- export const useRepoIntake = () => ({ repo: null, options: {}, managedApps: [], providers: [],
- providerOverride: {}, intakeFor() {}, setStudyContext() {}, targetAppId: 'example-app' });
- `;
- if (id !== '\0inbox-fixture.jsx') return;
- return `
- import React from 'react';
- import { createRoot } from 'react-dom/client';
- import { MemoryRouter } from 'react-router';
- import InboxTab from '/src/components/brain/tabs/InboxTab.jsx';
- import '/src/index.css';
- window.SpeechRecognition = function () { throw new Error('Recording must not start'); };
- createRoot(document.getElementById('root')).render(
- React.createElement(MemoryRouter, null, React.createElement(InboxTab))
- );
- `;
- },
- configureServer(vite) {
- vite.middlewares.use('/inbox-test', async (_req, res) => {
- res.setHeader('Content-Type', 'text/html');
- res.end(await vite.transformIndexHtml('/inbox-test',
- '<div id="root" style="padding:16px"></div><script type="module" src="/inbox-fixture.jsx"></script>'));
- });
- },
- }],
- server: { host: '127.0.0.1', port: 0 },
- });
- await server.listen();
- origin = server.resolvedUrls.local[0];
- browser = await chromium.launch({ executablePath: chrome, headless: true, args: ['--mute-audio'],
- env: { ...process.env, TMPDIR: browserTemp, TMP: browserTemp, TEMP: browserTemp },
+ },
+ load(id) {
+ if (id === '\0inbox-api') return `
+ let history;
+ export function getBrainInbox() {
+ if (!history) history = new Promise(resolve => { window.resolveInboxHistory = resolve; });
+ return history;
+ }
+ export async function captureBrainThought(...args) {
+ window.captures = [...(window.captures || []), args];
+ return { inboxLog: { id: 'example-thought', status: 'filed', capturedText: args[0] } };
+ }
+ `;
+ if (id === '\0inbox-socket') return 'export default { on() {}, off() {} };';
+ if (id === '\0inbox-hooks') return `
+ import { useState } from 'react';
+ export const useLocalStorageBool = () => useState(false);
+ export const useRepoIntake = () => ({ repo: null, options: {}, managedApps: [], providers: [],
+ providerOverride: {}, intakeFor() {}, setStudyContext() {}, targetAppId: 'example-app' });
+ `;
+ if (id !== '\0inbox-fixture.jsx') return;
+ return `
+ import React from 'react';
+ import { createRoot } from 'react-dom/client';
+ import { MemoryRouter } from 'react-router';
+ import InboxTab from '/src/components/brain/tabs/InboxTab.jsx';
+ import '/src/index.css';
+ window.SpeechRecognition = function () { throw new Error('Recording must not start'); };
+ createRoot(document.getElementById('root')).render(
+ React.createElement(MemoryRouter, null, React.createElement(InboxTab))
+ );
+ `;
+ },
+ configureServer(vite) {
+ vite.middlewares.use('/inbox-test', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await vite.transformIndexHtml('/inbox-test',
+ '<div id="root" style="padding:16px"></div><script type="module" src="/inbox-fixture.jsx"></script>'));
+ });
+ },
+ }],
+ server: { host: '127.0.0.1', port: 0 },
+ }),
+ launchOptions: { executablePath: chrome, args: ['--mute-audio'] },
+ // Compile the cold Vite module graph inside fixture startup, before timed
+ // interaction cases. This does not resolve history or submit a capture.
+ warmup: async (page, url) => {
+ await page.goto(`${url}inbox-test`, { timeout: 20000 });
+ await page.getByRole('textbox', { name: 'New inbox thought' }).waitFor({ timeout: 5000 });
+ },
});
- // Compile the cold Vite module graph inside fixture startup, before timed
- // interaction cases. This does not resolve history or submit a capture.
- const warmup = await browser.newPage();
- try {
- await warmup.goto(`${origin}inbox-test`, { timeout: 25000 });
- await warmup.getByRole('textbox', { name: 'New inbox thought' }).waitFor({ timeout: 5000 });
- } finally {
- await warmup.close();
- }
- }, 60000);
- afterAll(async () => {
- try {
- await browser?.close();
- } finally {
- await server?.close();
- if (browserTemp) await rm(browserTemp, { recursive: true, force: true });
- }
- }, 60000);
+ ({ browser, origin } = fixture);
+ }, BROWSER_FIXTURE_STARTUP_MS);
+ afterAll(() => fixture?.close(), 60000);
it.each([[360, 800], [390, 844], [768, 1024], [1440, 900]])(
'keeps the complete capture form usable at %ix%i', async (width, height) => {
diff --git a/client/src/test/README.md b/client/src/test/README.md
index ed04dd6d1d..e8212cd3da 100644
--- a/client/src/test/README.md
+++ b/client/src/test/README.md
@@ -10,6 +10,7 @@ a new one.
| --- | --- |
| `actWarnings.js` | React act(...) warning diagnostics — records the test active when a warning was observed, without claiming to identify where asynchronous work began. |
| `ariaRefAssertions.js` | Asserts a rendered tree's `aria-controls`/`aria-labelledby` IDREFs all resolve to a real element. |
+| `browserFixture.js` | `startBrowserFixture` — phase-bounded Vite + Chromium + warmup startup for `*.browser.test.js`, naming the stalled phase and closing everything it started. |
| `classNameScan.js` | Shared string-literal scanner (comment-stripping + literal walk) for the class-string convention guards. |
| `dndKeyboardDrag.js` | Drives a real `@dnd-kit` keyboard drag under happy-dom, stubbing the layout happy-dom can't provide. |
| `downloadPreflightConfirm.js` | `clickStartDownload` — waits for the confirm button to be enabled (built on `enabledBarrier.js`) before clicking, then settles. |
diff --git a/client/src/test/browserFixture.js b/client/src/test/browserFixture.js
new file mode 100644
index 0000000000..608ecb0ef5
--- /dev/null
+++ b/client/src/test/browserFixture.js
@@ -0,0 +1,141 @@
+/**
+ * Phase-bounded startup for the real-Chromium `*.browser.test.js` fixtures.
+ *
+ * A fixture starts three things in sequence: a Vite dev server, a Chromium
+ * process, and a first page that compiles the cold module graph. Bounding them
+ * only with one aggregate `beforeAll` timeout has two faults (#10543):
+ *
+ * - a stall reports a bare "Hook timed out in 60000ms" that names no phase;
+ * - the timed-out hook keeps running, so a Chromium or Vite server that comes
+ * up after the deadline is assigned to a variable `afterAll` already read,
+ * and nobody closes it.
+ *
+ * Here each phase has its own deadline, the deadlines plus the cleanup budget
+ * fit inside `BROWSER_FIXTURE_STARTUP_MS`, and a failure closes everything the
+ * fixture already owns — including a resource whose phase settles after its
+ * deadline — before rejecting with an error naming the phase and the timings
+ * of the phases that completed.
+ *
+ * The phase that actually stalled under load was the warmup, and its cost was
+ * not the fixture's own modules: with `configFile: false` and no
+ * `optimizeDeps.entries`, Vite globs every `.html` under the root, finds `client/index.html`,
+ * crawls the WHOLE app, and pre-bundles three.js, drei, recharts, xterm, … before
+ * it answers the first request. So the config must scope dependency discovery
+ * to what the fixture renders: `entries` names the real source files and
+ * `include` the bare imports of the virtual fixture module (which the scanner
+ * cannot see; leaving them to runtime discovery forces a re-optimize + reload).
+ */
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export const BROWSER_FIXTURE_STARTUP_MS = 60000;
+
+export const BROWSER_FIXTURE_PHASE_MS = Object.freeze({
+ vite: 10000,
+ chromium: 15000,
+ warmup: 25000,
+ cleanup: 5000,
+});
+
+const PHASE_NAMES = { vite: 'Vite server start', chromium: 'Chromium launch', warmup: 'first page warmup' };
+
+const withDeadline = (promise, ms, onTimeout) => {
+ let timer;
+ const deadline = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(onTimeout()), ms);
+ });
+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
+};
+
+/**
+ * @param {object} options
+ * @param {string} options.name - fixture label used in errors and the temp-dir prefix
+ * @param {Function} options.createServer - vite's `createServer`
+ * @param {(temp: string) => object} options.viteConfig - inline Vite config; `temp` is the fixture's private temp dir
+ * @param {object} options.chromium - playwright-core's `chromium`
+ * @param {object} [options.launchOptions] - extra `chromium.launch` options (executablePath, args, …)
+ * @param {(page: object, origin: string) => Promise<void>} [options.warmup] - first navigation; the page is closed afterward
+ * @param {object} [options.phaseMs] - per-phase budgets; defaults to BROWSER_FIXTURE_PHASE_MS
+ * @returns {Promise<{ origin: string, browser: object, server: object, temp: string, close: () => Promise<void> }>}
+ */
+export async function startBrowserFixture({
+ name, createServer, viteConfig, chromium, launchOptions = {}, warmup, phaseMs = BROWSER_FIXTURE_PHASE_MS,
+}) {
+ const budget = phaseMs.vite + phaseMs.chromium + phaseMs.warmup + phaseMs.cleanup;
+ if (budget >= BROWSER_FIXTURE_STARTUP_MS) {
+ throw new Error(`${name} phase budgets (${budget}ms) must fit inside the ${BROWSER_FIXTURE_STARTUP_MS}ms startup hook`);
+ }
+ const temp = await mkdtemp(join(tmpdir(), `${name}-`));
+ const closers = [];
+ const completed = [];
+ let failed = false;
+ // A resource acquired after its phase already failed is closed at once
+ // instead of leaking past the hook that abandoned it.
+ const own = (closer) => {
+ if (failed) closer().catch(() => {});
+ else closers.push(closer);
+ };
+ const closeOwned = async () => {
+ const errors = [];
+ for (const closer of closers.splice(0).reverse()) {
+ await closer().catch(error => errors.push(error.message));
+ }
+ await rm(temp, { recursive: true, force: true });
+ if (errors.length) throw new Error(errors.join('; '));
+ };
+ let phase;
+ const runPhase = async (key, work) => {
+ phase = key;
+ const started = Date.now();
+ const value = await withDeadline(Promise.resolve().then(work), phaseMs[key],
+ () => new Error(`timed out after ${phaseMs[key]}ms`));
+ completed.push(`${PHASE_NAMES[key]} ${Date.now() - started}ms`);
+ return value;
+ };
+
+ try {
+ const server = await runPhase('vite', async () => {
+ const config = viteConfig(temp);
+ if (!config.optimizeDeps?.entries?.length) {
+ throw new Error('viteConfig must set optimizeDeps.entries to the rendered source files, or Vite scans the whole app');
+ }
+ const vite = await createServer(config);
+ own(() => vite.close());
+ await vite.listen();
+ return vite;
+ });
+ const origin = server.resolvedUrls.local[0];
+ const browser = await runPhase('chromium', async () => {
+ // Playwright's own launch timeout kills the child it spawned; the phase
+ // deadline above is the backstop if that kill itself hangs.
+ const launched = await chromium.launch({
+ headless: true,
+ timeout: phaseMs.chromium,
+ ...launchOptions,
+ env: { ...process.env, ...launchOptions.env, TMPDIR: temp, TMP: temp, TEMP: temp },
+ });
+ own(() => launched.close());
+ return launched;
+ });
+ if (warmup) {
+ await runPhase('warmup', async () => {
+ const page = await browser.newPage();
+ try {
+ await warmup(page, origin);
+ } finally {
+ await page.close();
+ }
+ });
+ }
+ return { origin, browser, server, temp, close: closeOwned };
+ } catch (error) {
+ failed = true;
+ const cleanup = await withDeadline(closeOwned().then(() => 'cleaned up'), phaseMs.cleanup,
+ () => new Error(`timed out after ${phaseMs.cleanup}ms`))
+ .catch(cleanupError => `cleanup failed: ${cleanupError.message}`);
+ const done = completed.length ? completed.join(', ') : 'none';
+ throw new Error(`${name} startup failed during ${PHASE_NAMES[phase]}: ${error.message} `
+ + `(completed: ${done}; ${cleanup})`, { cause: error });
+ }
+}
diff --git a/client/src/test/browserFixture.test.js b/client/src/test/browserFixture.test.js
new file mode 100644
index 0000000000..957736fac3
--- /dev/null
+++ b/client/src/test/browserFixture.test.js
@@ -0,0 +1,53 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { startBrowserFixture } from './browserFixture.js';
+
+const PHASE_MS = { vite: 50, chromium: 50, warmup: 50, cleanup: 50 };
+const SCOPED = { optimizeDeps: { entries: ['src/Example.jsx'] } };
+
+const fakeVite = () => {
+ const server = { listen: vi.fn(async () => {}), close: vi.fn(async () => {}),
+ resolvedUrls: { local: ['http://127.0.0.1:1/'] } };
+ return { server, createServer: vi.fn(async () => server) };
+};
+const fakeBrowser = (page) => ({ close: vi.fn(async () => {}), newPage: vi.fn(async () => page) });
+
+describe('startBrowserFixture', () => {
+ it('names a stalled Chromium launch, closes Vite, and closes a browser that arrives late', async () => {
+ const { server, createServer } = fakeVite();
+ const late = fakeBrowser();
+ let arrive;
+ const chromium = { launch: vi.fn(() => new Promise(resolve => { arrive = () => resolve(late); })) };
+ let temp;
+ const viteConfig = vi.fn(dir => { temp = dir; return SCOPED; });
+
+ const error = await startBrowserFixture({ name: 'example', createServer, viteConfig, chromium, phaseMs: PHASE_MS })
+ .catch(caught => caught);
+
+ expect(error.message).toMatch(/^example startup failed during Chromium launch: timed out after 50ms \(completed: Vite server start \d+ms; cleaned up\)$/);
+ expect(server.close).toHaveBeenCalledTimes(1);
+ expect(existsSync(temp)).toBe(false);
+ expect(chromium.launch.mock.calls[0][0]).toMatchObject({ timeout: 50, env: { TMPDIR: temp } });
+
+ arrive();
+ await vi.waitFor(() => expect(late.close).toHaveBeenCalledTimes(1));
+ });
+
+ it('closes the launched browser and Vite when the warmup page fails', async () => {
+ const { server, createServer } = fakeVite();
+ const page = { close: vi.fn(async () => {}) };
+ const browser = fakeBrowser(page);
+ const chromium = { launch: vi.fn(async () => browser) };
+ const cause = new Error('net::ERR_CONNECTION_REFUSED');
+
+ const error = await startBrowserFixture({ name: 'example', createServer, viteConfig: () => SCOPED, chromium,
+ phaseMs: PHASE_MS, warmup: async () => { throw cause; } }).catch(caught => caught);
+
+ expect(error.message).toMatch(/during first page warmup: net::ERR_CONNECTION_REFUSED \(completed: Vite server start \d+ms, Chromium launch \d+ms; cleaned up\)/);
+ expect(error.cause).toBe(cause);
+ expect(page.close).toHaveBeenCalledTimes(1);
+ expect(browser.close).toHaveBeenCalledTimes(1);
+ expect(server.close).toHaveBeenCalledTimes(1);
+ });
+});