@dxos/test-utils 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/test-utils",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Test utilities",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -35,10 +35,10 @@
35
35
  "src"
36
36
  ],
37
37
  "dependencies": {
38
+ "@dxos/async": "0.17.0",
39
+ "@dxos/node-std": "0.17.0",
38
40
  "@playwright/test": "1.63.0",
39
- "pkg-up": "^3.1.0",
40
- "@dxos/async": "0.16.0",
41
- "@dxos/node-std": "0.16.0"
41
+ "pkg-up": "^3.1.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "vitest": "4.1.10"
@@ -4,6 +4,9 @@
4
4
 
5
5
  import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process';
6
6
  import { randomUUID } from 'node:crypto';
7
+ import { mkdtempSync, rmSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { join } from 'node:path';
7
10
 
8
11
  /**
9
12
  * Drives one long-lived `claude --print` process in stream-json mode: prompts go in on stdin as
@@ -24,6 +27,14 @@ export type ClaudeAgentOptions = {
24
27
  model: string;
25
28
  /** Tools the agent may use without a prompt. Anything else is denied outright. */
26
29
  allowedTools: string[];
30
+ /** Plugin directories to load; with `--bare` no installed plugin loads, so these are the only ones. */
31
+ pluginDirs?: string[];
32
+ /**
33
+ * `--bare` (the default) also cuts the toolset to Bash, Edit and Read, so a plugin's skills cannot
34
+ * load. When false, the agent runs with the full toolset against an empty config directory, which
35
+ * isolates it from the developer's settings, plugins, CLAUDE.md and memory instead.
36
+ */
37
+ bare?: boolean;
27
38
  /** Ceiling for one turn, in ms. */
28
39
  timeout?: number;
29
40
  };
@@ -84,10 +95,12 @@ export class ClaudeAgent {
84
95
  #onEvent?: (event: StreamEvent) => void;
85
96
  #onFail?: (error: Error) => void;
86
97
  #exited?: Error;
98
+ #configDir?: string;
87
99
 
88
- private constructor(child: ChildProcessWithoutNullStreams, timeout: number) {
100
+ private constructor(child: ChildProcessWithoutNullStreams, timeout: number, configDir?: string) {
89
101
  this.#child = child;
90
102
  this.#timeout = timeout;
103
+ this.#configDir = configDir;
91
104
  this.#child.stdout.on('data', (chunk) => this.#consume(String(chunk)));
92
105
  this.#child.stderr.on('data', (chunk) => {
93
106
  this.#stderr += String(chunk);
@@ -120,6 +133,8 @@ export class ClaudeAgent {
120
133
  apiKey,
121
134
  model,
122
135
  allowedTools,
136
+ pluginDirs = [],
137
+ bare = true,
123
138
  timeout = DEFAULT_TIMEOUT,
124
139
  }: ClaudeAgentOptions): ClaudeAgent {
125
140
  // Every CLAUDE_* variable is dropped: run from inside another Claude Code session they name
@@ -130,6 +145,7 @@ export class ClaudeAgent {
130
145
  string,
131
146
  ][],
132
147
  );
148
+ const configDir = bare ? undefined : mkdtempSync(join(tmpdir(), 'claude-agent-config-'));
133
149
 
134
150
  const child = spawn(
135
151
  'claude',
@@ -142,8 +158,9 @@ export class ClaudeAgent {
142
158
  // Required by the CLI alongside stream-json output.
143
159
  '--verbose',
144
160
  // A repo CLAUDE.md, the developer's settings and any installed plugin would each change
145
- // what the agent does; without this the suite's failures are not reproducible.
146
- '--bare',
161
+ // what the agent does; either mode keeps them out, or the suite's failures are not
162
+ // reproducible. The empty config directory carries the unbare mode's isolation.
163
+ ...(bare ? ['--bare'] : ['--setting-sources', 'project']),
147
164
  // Fresh conversation per run, and never one the caller is also writing to.
148
165
  '--session-id',
149
166
  randomUUID(),
@@ -157,6 +174,7 @@ export class ClaudeAgent {
157
174
  // Nobody is at the keyboard: anything not pre-allowed is denied rather than hanging.
158
175
  '--permission-prompts',
159
176
  'none',
177
+ ...pluginDirs.flatMap((dir) => ['--plugin-dir', dir]),
160
178
  // Variadic, so an empty list would swallow whatever followed it — and the CLI then reads
161
179
  // no prompt at all and produces not one event.
162
180
  ...(allowedTools.length > 0 ? ['--allowedTools', ...allowedTools] : []),
@@ -168,6 +186,7 @@ export class ClaudeAgent {
168
186
  // `claude` reads ANTHROPIC_API_KEY; the suite sources the value from
169
187
  // DX_ANTHROPIC_API_KEY so a developer's interactive login is never what it spends.
170
188
  ANTHROPIC_API_KEY: apiKey,
189
+ ...(configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}),
171
190
  },
172
191
  stdio: ['pipe', 'pipe', 'pipe'],
173
192
  // Its own group: `claude` spawns the MCP server, and killing only `claude` orphans that
@@ -176,7 +195,7 @@ export class ClaudeAgent {
176
195
  },
177
196
  );
178
197
 
179
- return new ClaudeAgent(child, timeout);
198
+ return new ClaudeAgent(child, timeout, configDir);
180
199
  }
181
200
 
182
201
  /**
@@ -243,18 +262,21 @@ export class ClaudeAgent {
243
262
  */
244
263
  async close(): Promise<void> {
245
264
  // A process that never spawned emits no `exit`, so awaiting one here would hang cleanup.
246
- if (this.#child.pid === undefined || this.#child.exitCode !== null || this.#child.signalCode !== null) {
247
- return;
265
+ if (this.#child.pid !== undefined && this.#child.exitCode === null && this.#child.signalCode === null) {
266
+ const exited = new Promise<void>((resolve) => this.#child.once('exit', () => resolve()));
267
+ this.#child.stdin.end();
268
+ try {
269
+ // The whole group, so the MCP server `claude` spawned goes with it.
270
+ process.kill(-this.#child.pid, 'SIGKILL');
271
+ } catch {
272
+ this.#child.kill('SIGKILL');
273
+ }
274
+ await exited;
248
275
  }
249
- const exited = new Promise<void>((resolve) => this.#child.once('exit', () => resolve()));
250
- this.#child.stdin.end();
251
- try {
252
- // The whole group, so the MCP server `claude` spawned goes with it.
253
- process.kill(-this.#child.pid, 'SIGKILL');
254
- } catch {
255
- this.#child.kill('SIGKILL');
276
+ if (this.#configDir) {
277
+ rmSync(this.#configDir, { recursive: true, force: true });
278
+ this.#configDir = undefined;
256
279
  }
257
- await exited;
258
280
  }
259
281
 
260
282
  #tail(start: number): string {
package/src/playwright.ts CHANGED
@@ -184,7 +184,9 @@ const webKitLaunchEnv = (workspaceRoot: string): Record<string, string> => {
184
184
  /**
185
185
  * WebKit keeps OPFS under the browser's data directory, and an ephemeral context has none, so every
186
186
  * `navigator.storage` call there fails and no app backed by OPFS boots. A persistent context has one.
187
- * Its temporary directory is per context, which keeps the isolation a fresh context gives.
187
+ * Its temporary directory is per context, which keeps the isolation a fresh context gives. On macOS
188
+ * WebKit puts OPFS under the home directory instead, shared by every context and kept across runs,
189
+ * so the home directory is pointed at the context's directory too.
188
190
  */
189
191
  const createContext = async (browser: Browser): Promise<{ context: BrowserContext; page?: Page }> => {
190
192
  const browserType = browser.browserType();
@@ -194,7 +196,10 @@ const createContext = async (browser: Browser): Promise<{ context: BrowserContex
194
196
 
195
197
  const userDataDir = mkdtempSync(join(tmpdir(), 'dxos-webkit-'));
196
198
  const context = await browserType.launchPersistentContext(userDataDir, {
197
- env: webKitLaunchEnv(findWorkspaceRoot(process.cwd())),
199
+ env: {
200
+ ...webKitLaunchEnv(findWorkspaceRoot(process.cwd())),
201
+ ...(process.platform === 'darwin' ? { CFFIXED_USER_HOME: userDataDir } : {}),
202
+ },
198
203
  });
199
204
  context.once('close', () => rmSync(userDataDir, { recursive: true, force: true }));
200
205
  // A persistent context opens with a page; taking it leaves no blank page behind.
@@ -274,6 +279,24 @@ export const setupPage = async (browser: Browser | BrowserContext, options: Setu
274
279
  }
275
280
  };
276
281
 
282
+ /**
283
+ * Opens `url` once and waits for `ready`, so Storybook's on-demand compile of the story (about 50 s on a
284
+ * 4 vCPU runner) is paid outside every test's own budget. Call from `test.beforeAll` after raising its
285
+ * timeout with `test.setTimeout`.
286
+ */
287
+ export const warmStory = async (
288
+ browser: Browser,
289
+ url: string,
290
+ ready: (page: Page) => Promise<unknown>,
291
+ ): Promise<void> => {
292
+ const { page, close } = await setupPage(browser, { url });
293
+ try {
294
+ await ready(page);
295
+ } finally {
296
+ await close();
297
+ }
298
+ };
299
+
277
300
  export const storybookUrl = (storyId: string, port = 9009) =>
278
301
  `http://localhost:${port}/iframe.html?id=${storyId}&viewMode=story`;
279
302
 
@@ -284,6 +307,8 @@ export const storybookUrl = (storyId: string, port = 9009) =>
284
307
  */
285
308
  export const storybookWebServer = (port: number) => ({
286
309
  command: `pnpm storybook dev --ci --quiet --port=${port} --config-dir=.storybook`,
310
+ // Playwright starts the server beside the config (`<package>/src/playwright`); `.storybook` is at the package root.
311
+ cwd: '../..',
287
312
  url: `http://localhost:${port}`,
288
313
  reuseExistingServer: false,
289
314
  });
@@ -3,11 +3,11 @@
3
3
  Three workarounds for bugs in Playwright's WebKit build, applied by `e2ePreset` and `setupPage` in
4
4
  [`playwright.ts`](./playwright.ts). All are off when `DX_E2E_WEBKIT_WORKAROUNDS=0`.
5
5
 
6
- | Workaround | What it is | Why |
7
- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
8
- | Persistent WebKit context | `setupPage` launches WebKit against a per-context temporary data directory instead of taking an ephemeral context. | WebKit serves OPFS only out of a browser data directory, and an ephemeral context has none, so `navigator.storage.getDirectory()` rejects with `UnknownError` and nothing backed by OPFS boots. Chromium and Firefox serve OPFS from an ephemeral context. |
9
- | [`errno-shim.ts`](./errno-shim.ts) | An `LD_PRELOAD` shared object that interposes `sigaction` and restores `errno` around each handler the process installs. | `WTF::Thread::signalHandlerSuspendResume` returns from `sigsuspend` without restoring `errno`, so an errno-checked parse on a thread JavaScriptCore suspended fails: `RTCIceCandidateFields` aborts, `SyntaxError: The port number is invalid` on a valid offer, and GLib `getauxval () failed: Interrupted system call`. |
10
- | `JSC_useWasmIPInt=false` (x86_64 only) | Turns off WebKit's wasm in-place interpreter. | Every captured boot crash faulted in IPInt with a corrupted locals base or wasm PC. |
6
+ | Workaround | What it is | Why |
7
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
8
+ | Persistent WebKit context | `setupPage` launches WebKit against a per-context temporary data directory instead of taking an ephemeral context. On macOS it also sets `CFFIXED_USER_HOME` to that directory. | WebKit serves OPFS only out of a browser data directory, and an ephemeral context has none, so `navigator.storage.getDirectory()` rejects with `UnknownError` and nothing backed by OPFS boots. Chromium and Firefox serve OPFS from an ephemeral context. macOS WebKit keeps OPFS under `~/Library/WebKit/org.webkit.Playwright/WebsiteData/Default` whatever the data directory, so without the home override every context, and every run, opens the same OPFS, and a second peer boots with the first one's identity. |
9
+ | [`errno-shim.ts`](./errno-shim.ts) | An `LD_PRELOAD` shared object that interposes `sigaction` and restores `errno` around each handler the process installs. | `WTF::Thread::signalHandlerSuspendResume` returns from `sigsuspend` without restoring `errno`, so an errno-checked parse on a thread JavaScriptCore suspended fails: `RTCIceCandidateFields` aborts, `SyntaxError: The port number is invalid` on a valid offer, and GLib `getauxval () failed: Interrupted system call`. |
10
+ | `JSC_useWasmIPInt=false` (x86_64 only) | Turns off WebKit's wasm in-place interpreter. | Every captured boot crash faulted in IPInt with a corrupted locals base or wasm PC. |
11
11
 
12
12
  ## Why WebKit e2e needs a recent Playwright
13
13
 
@@ -41,5 +41,5 @@ too. Then delete `errno-shim.ts`, its test, the `JSC_useWasmIPInt` line, the per
41
41
  branch in `setupPage` and this file.
42
42
 
43
43
  A CI sample is broader but needs a way to pass the variable to the e2e job: add it to the `Test`
44
- step's `env` in `.depot/workflows/check.yml` on a throwaway branch, dispatch Check with `only=e2e`,
44
+ step's `env` in `.github/workflows/check.yml` on a throwaway branch, dispatch Check with `only=e2e`,
45
45
  and drop the branch afterwards.