The best way to control Claude Code, Codex and more from any computer or phone
test: remove the timing races behind recurring CI and release failures (#22523)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 20, 2026 at 16:08 UTC
f9dd25914dbd5f061f2685965bcbe2db8cfb912e
13 files changed
+176
-87
apps/server/integration/transferBudgetV2.integration.test.ts
+10
-2
@@ -1,5 +1,6 @@
1
// @effect-diagnostics nodeBuiltinImport:off - Measures real local HTTP/WebSocket sockets.
2
import * as NodeHttp from "node:http";
3
+import * as NodeUtil from "node:util";
4
import { assert, it } from "@effect/vitest";
5
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
6
import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
@@ -299,9 +300,16 @@ it.live(
300
const events = turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT, true);
301
const stored = yield* sink.write({ events });
302
const last = stored.at(-1)!;
302
- const terminal = (item: StreamItem) =>
303
+ const threadTerminal = (item: StreamItem) =>
304
"sequence" in item && item.sequence >= last.sequence;
304
- for (const queue of [tq, sq, ttq, ssq]) yield* collectUntil(queue, terminal);
305
+ // Shell items carry the shell read when their batch is projected, and unchanged
306
+ // shells are skipped, so a turn split across batches may never yield an item at
307
+ // the last sequence. Wait for the final shell instead.
308
+ const finalShell = yield* projection.getThreadShell(THREAD_ID);
309
+ const shellTerminal = (item: StreamItem) =>
310
+ item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell);
311
+ for (const queue of [tq, ttq]) yield* collectUntil(queue, threadTerminal);
312
+ for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal);
313
const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore);
314
const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore);
315
const measuredTurnSecondClientWebSocket = difference(
apps/server/scripts/acp-mock-agent.ts
+12
-5
@@ -1383,6 +1383,7 @@ const program = Effect.gen(function* () {
1383
(emitRunningCommandThenHangOnFirstPrompt && promptCount === 1)
1384
) {
1385
const toolCallId = "tool-call-running-1";
1386
+ let runningCommandPublished: Promise<void> = Promise.resolve();
1387
if (runningCommandPidPath !== undefined) {
1388
const command = runningCommandIgnoresTerm
1389
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s\n" "$$" "$child" > "$1"; wait "$child"'
@@ -1390,19 +1391,24 @@ const program = Effect.gen(function* () {
1391
if (runningCommandSeparateSession) {
1392
const launcher = [
1393
'const { spawn } = require("node:child_process");',
1393
- "const child = spawn(process.argv[1], process.argv.slice(2), { stdio: 'ignore' });",
1394
+ "const child = spawn(process.argv[1], process.argv.slice(2), { stdio: ['ignore', 'inherit', 'ignore'] });",
1395
"child.once('exit', (code, signal) => process.exitCode = code ?? (signal ? 1 : 0));",
1396
].join(" ");
1397
const detachedCommand = runningCommandIgnoresTerm
1397
- ? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; wait "$child"'
1398
- : 'sleep 120 & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; wait "$child"';
1398
+ ? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; echo published; wait "$child"'
1399
+ : 'sleep 120 & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; echo published; wait "$child"';
1400
// Nested bash publishes "$PPID $$ $child" once it starts. Do not
1401
// write the launcher PID alone here: that races with bash and can
1401
- // clobber the triple that interrupt tests wait for.
1402
+ // clobber the triple that interrupt tests wait for. It then prints a
1403
+ // line, so an agent that exits after launch only exits once the
1404
+ // triple exists instead of racing a slow launcher start.
1405
const detachedLauncher = NodeChildProcess.spawn(
1406
process.execPath,
1407
["-e", launcher, "bash", "-c", detachedCommand, "bash", runningCommandPidPath],
1405
- { detached: true, stdio: "ignore" },
1408
+ { detached: true, stdio: ["ignore", "pipe", "ignore"] },
1409
+ );
1410
+ runningCommandPublished = new Promise((resolve) =>
1411
+ detachedLauncher.stdout.once("data", () => resolve()),
1412
);
1413
detachedLauncher.unref();
1414
} else {
@@ -1460,6 +1466,7 @@ const program = Effect.gen(function* () {
1466
},
1467
});
1468
if (exitAfterRunningCommandLaunch) {
1469
+ yield* Effect.promise(() => runningCommandPublished);
1470
yield* Effect.sleep("100 millis");
1471
return yield* Effect.sync(() => process.exit(0));
1472
}
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+15
-22
@@ -17499,11 +17499,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
17499
const NESTED_TOOL_USE_ID = "toolu-steer-nested";
17500
const FINISHED_TOOL_USE_ID = "toolu-steer-finished";
17501
const calls: Array<string> = [];
17502
+ const backgroundRequested = yield* Deferred.make<void>();
17503
let beforeAnswer: Effect.Effect<void> = Effect.void;
17504
const lateAnswer = yield* Deferred.make<void>();
17505
const harness = yield* makeWakeHarnessWithOptions({
17506
backgroundTasks: (toolUseId) =>
17507
Effect.sync(() => calls.push(toolUseId)).pipe(
17508
+ Effect.andThen(Deferred.succeed(backgroundRequested, undefined)),
17509
Effect.andThen(
17510
backgrounding === "answers after the turn ended" ||
17511
backgrounding === "answers after the subagent ran again"
@@ -17671,29 +17673,19 @@ describe("ClaudeAdapterV2 background wake turns", () => {
17673
),
17674
);
17675
}
17674
- // The steer arms its 5-second backgrounding timeout after the request
17675
- // starts on another fiber, so one TestClock.adjust can land before that
17676
- // timer exists and leave the steer waiting forever. Tick until it ends.
17677
- const awaitSteerTimeout = <A, E>(fiber: Fiber.Fiber<A, E>) =>
17678
- Effect.gen(function* () {
17679
- for (let tick = 0; tick < 100 && fiber.pollUnsafe() === undefined; tick++) {
17680
- yield* TestClock.adjust("1 second");
17681
- yield* Effect.yieldNow;
17682
- }
17683
- if (fiber.pollUnsafe() === undefined) {
17684
- return yield* Effect.die("Timed out waiting for the steer.");
17685
- }
17686
- return yield* Fiber.await(fiber);
17687
- });
17688
- const steering = yield* Effect.forkScoped(steer);
17689
- const timesOut =
17676
+ // Started at once so the steer reads its backgrounding deadline before
17677
+ // this test moves the clock. Its message is built with real file I/O,
17678
+ // so a scheduled start could read the clock after the moves below.
17679
+ const steering = yield* Effect.forkScoped(steer, { startImmediately: true });
17680
+ if (
17681
backgrounding === "never answers" ||
17691
- backgrounding === "answers after the steer went out";
17692
- if (timesOut) {
17693
- yield* awaitUntil(() => calls.length === 1, "background request");
17682
+ backgrounding === "answers after the steer went out"
17683
+ ) {
17684
+ yield* Deferred.await(backgroundRequested);
17685
assert.equal(harness.offeredMessages.length, offered);
17686
+ yield* TestClock.adjust("5 seconds");
17687
}
17696
- const steered = yield* timesOut ? awaitSteerTimeout(steering) : Fiber.await(steering);
17688
+ const steered = yield* Fiber.await(steering);
17689
17690
assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
17691
if (backgrounding === "answers after the turn ended") {
@@ -17706,8 +17698,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
17698
assert.equal(harness.offeredMessages.at(-1)?.priority, "now");
17699
if (backgrounding === "never answers") {
17700
for (let repeat = 1; repeat <= 2; repeat++) {
17709
- const again = yield* Effect.forkScoped(steer);
17710
- assert.isTrue(Exit.isSuccess(yield* awaitSteerTimeout(again)));
17701
+ const again = yield* Effect.forkScoped(steer, { startImmediately: true });
17702
+ yield* TestClock.adjust("5 seconds");
17703
+ assert.isTrue(Exit.isSuccess(yield* Fiber.await(again)));
17704
assert.equal(harness.offeredMessages.length, offered + 1 + repeat);
17705
}
17706
assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+13
-2
@@ -97,6 +97,7 @@ import {
97
} from "@t3tools/contracts";
98
99
import * as Cause from "effect/Cause";
100
+import * as Clock from "effect/Clock";
101
import * as Context from "effect/Context";
102
import * as Crypto from "effect/Crypto";
103
import * as DateTime from "effect/DateTime";
@@ -304,6 +305,9 @@ const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
305
// reply can land after the progress frame that settles it. Its transcript
306
// stays the source of its answer this long after it settles.
307
const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
308
+// A steer waits at most this long, from its request, for its foreground
309
+// subagents to move to the background before it is sent.
310
+const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;
311
312
/**
313
* When the CLI exits it stops the MCP servers it started, but not their children: a plugin's
@@ -9684,6 +9688,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9688
// its result arrives as a task notification like any background agent.
9689
const backgroundForegroundSubagents = Effect.fnUntraced(function* (
9690
live: ClaudeLiveQueryContext,
9691
+ deadline: number,
9692
) {
9693
const foreground: Array<{
9694
readonly taskId: string;
@@ -9739,11 +9744,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9744
backgroundMovesByToolUseId.set(toolUseId, move);
9745
moves.push(move);
9746
}
9742
- yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption("5 seconds"));
9747
+ const remaining = deadline - (yield* Clock.currentTimeMillis);
9748
+ yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption(Math.max(0, remaining)));
9749
});
9750
9751
const steerTurn = Effect.fn("ClaudeAdapterV2.steerTurn")(
9752
function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
9753
+ // Measured from the request, not from when the moves are forked:
9754
+ // building the message and the moves can take clock time a timer
9755
+ // started later would not count, and the steer would wait past it.
9756
+ const backgroundDeadline =
9757
+ (yield* Clock.currentTimeMillis) + BACKGROUND_MOVE_TIMEOUT_MS;
9758
const existing = yield* Ref.get(queryContext);
9759
if (existing === null) {
9760
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
@@ -9769,7 +9780,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9780
fileSystem,
9781
skills: yield* userInvocableSkills(currentTurn.input.runtimePolicy.cwd),
9782
});
9772
- yield* backgroundForegroundSubagents(existing);
9783
+ yield* backgroundForegroundSubagents(existing, backgroundDeadline);
9784
// The turn can end while the moves are answered. A steer offered
9785
// then would start a new turn the orchestrator never asked for, so
9786
// the steer fails and the orchestrator starts the follow-up turn.
apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
+1
-3
@@ -77,9 +77,7 @@ it("keeps only the usage limit attached while an active goal waits in the collap
77
const limit = page.getByText("Usage limit reached", { exact: true });
78
const goal = page.getByText("Goal active", { exact: true });
79
80
- // A retained pointer can expand the stack as it mounts; start outside the hover target.
81
- await userEvent.hover(limit);
82
- await expect.poll(visibleBanners).toHaveLength(1);
80
+ expect(visibleBanners()).toHaveLength(1);
81
await expect.element(limit).toBeVisible();
82
await expect.element(goal).not.toBeVisible();
83
expect(container.querySelector('[data-slot="composer-banner-attachment"]')?.textContent).toBe(
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+9
@@ -43,6 +43,15 @@ vi.mock(import("~/state/query"), async (original) => ({
43
})) as never,
44
}));
45
46
+// The first Mermaid render loads the library and its flowchart chunks, which took over
47
+// 10 seconds on a busy release runner. Pay that while the file loads, not inside a test.
48
+{
49
+ const { default: mermaid } = await import("mermaid");
50
+ mermaid.initialize({ startOnLoad: false });
51
+ await mermaid.render("mermaid-warmup", "flowchart LR\n A --> B");
52
+ document.getElementById("dmermaid-warmup")?.remove();
53
+}
54
+
55
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
56
const CREATED_AT = "2026-03-17T19:12:28.000Z";
57
apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
+50
-28
@@ -1,4 +1,4 @@
1
-import { act, render, fakeTimers } from "../../../test/render";
1
+import { act, render, fakeTimers, type Screen } from "../../../test/render";
2
import {
3
CodeView,
4
FileDiff,
@@ -146,9 +146,16 @@ function renderViews(count: number) {
146
);
147
}
148
149
-const codeFile = (name: string) =>
150
- document.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
151
-const loadingViews = () => document.querySelectorAll('[role="status"]').length;
149
+// Pierre rejects a pool whose workers take 10s to start. Real workers share the runner with the
150
+// rest of the suite, so outside the test of that limit the test's own timeout is the only deadline.
151
+const UNLIMITED_WORKER_STARTUP_MS = 120_000;
152
+
153
+// Queries stay inside the test's own container: a timed-out test keeps running and leaves its
154
+// views mounted while the next test starts.
155
+const codeFile = (container: HTMLElement, name: string) =>
156
+ container.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
157
+const loadingViews = (container: HTMLElement) =>
158
+ container.querySelectorAll('[role="status"]').length;
159
160
describe("code-view worker lifecycle", () => {
161
function setup() {
@@ -165,7 +172,7 @@ describe("code-view worker lifecycle", () => {
172
// Worker startup runs on real time, so only the idle expiry checks use this clock.
173
// Faking startup too would let advancing the idle clock time out a worker startup.
174
const idleClock = () => fakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
168
- async function workerEnvironment() {
175
+ async function workerEnvironment({ startupLimit = UNLIMITED_WORKER_STARTUP_MS } = {}) {
176
await using stack = new AsyncDisposableStack();
177
// Pins the pool at two workers whatever machine runs the suite.
178
stack.use(vi.spyOn(navigator, "hardwareConcurrency", "get").mockReturnValue(2));
@@ -175,6 +182,9 @@ describe("code-view worker lifecycle", () => {
182
this: WorkerPoolManager,
183
...args
184
) {
185
+ // The provider builds the pool without this option, so it is set before startup reads it.
186
+ const options: { workerInitializationTimeout?: number } = Reflect.get(this, "options");
187
+ options.workerInitializationTimeout = startupLimit;
188
const pending = initialize.apply(this, args);
189
testState.pools.set(this, pending);
190
return pending;
@@ -200,12 +210,13 @@ describe("code-view worker lifecycle", () => {
210
};
211
}
212
203
- // Two cold starts can each use Pierre's 10-second initialization budget.
213
+ // Two cold starts of real workers can outlast the default timeout on a loaded runner.
214
it("starts workers on demand and expires idle pools", { timeout: 30_000 }, async () => {
215
setup();
216
await using workers = await workerEnvironment();
217
const view = await workers.render(renderViews(0));
208
- const button = document.querySelector("button")!;
218
+ const { container } = view;
219
+ const button = container.querySelector("button")!;
220
expect(testState.workers).toHaveLength(0);
221
expect(testState.pools.size).toBe(0);
222
await act(async () => button.click());
@@ -214,7 +225,9 @@ describe("code-view worker lifecycle", () => {
225
await act(async () => testState.pools.get(pool));
226
expect(pool.isInitialized()).toBe(true);
227
expect(testState.workers).toHaveLength(2);
217
- await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
228
+ await vi.waitFor(() =>
229
+ expect(codeFile(container, "notes.txt")).toContain("Plain text is ready."),
230
+ );
231
expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
232
233
await view.rerender(renderViews(2));
@@ -223,7 +236,7 @@ describe("code-view worker lifecycle", () => {
236
expect(testState.workers).toHaveLength(2);
237
expect(new Set(testState.renderPools)).toEqual(new Set([pool]));
238
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
226
- await vi.waitFor(() => expect(codeFile("answer.ts")).toContain("answer"));
239
+ await vi.waitFor(() => expect(codeFile(container, "answer.ts")).toContain("answer"));
240
241
{
242
using _idleClock = idleClock();
@@ -238,7 +251,7 @@ describe("code-view worker lifecycle", () => {
251
await view.rerender(renderViews(1));
252
expect(testState.pools.size).toBe(1);
253
expect(testState.workers).toHaveLength(2);
241
- expect(loadingViews()).toBe(0);
254
+ expect(loadingViews(container)).toBe(0);
255
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
256
await vi.advanceTimersByTimeAsync(30_000);
257
expect(pool.getStats().totalWorkers).toBe(2);
@@ -254,16 +267,18 @@ describe("code-view worker lifecycle", () => {
267
await act(async () => testState.pools.get(reopenedPool));
268
expect(reopenedPool.isInitialized()).toBe(true);
269
expect(testState.workers).toHaveLength(4);
257
- expect(document.querySelector("button")).toBe(button);
270
+ expect(container.querySelector("button")).toBe(button);
271
expect(button.textContent).toBe("Edited draft");
259
- await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
272
+ await vi.waitFor(() =>
273
+ expect(codeFile(container, "notes.txt")).toContain("Plain text is ready."),
274
+ );
275
});
276
277
it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
278
setup();
279
await using workers = await workerEnvironment();
280
testState.failWorkers = true;
266
- await workers.render(renderViews(1));
281
+ const { container } = await workers.render(renderViews(1));
282
const pool = [...testState.pools.keys()][0]!;
283
await act(async () => {
284
await expect(testState.pools.get(pool)).rejects.toMatchObject({ _tag: "DiffWorkerError" });
@@ -275,13 +290,16 @@ describe("code-view worker lifecycle", () => {
290
});
291
expect(pool.isWorkingPool()).toBe(false);
292
expect(testState.workers).toHaveLength(0);
278
- await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
293
+ await vi.waitFor(() =>
294
+ expect(codeFile(container, "notes.txt")).toContain("Plain text is ready."),
295
+ );
296
});
297
298
it("keeps an initializing pool until its last view closes and ignores late responses", async () => {
299
setup();
300
using _idleClock = idleClock();
284
- await using workers = await workerEnvironment();
301
+ // Runs Pierre's own startup limit on the fake clock.
302
+ await using workers = await workerEnvironment({ startupLimit: 10_000 });
303
testState.holdInitialization = true;
304
const held = new Promise<void>((resolve) => {
305
testState.onInitializationHeld = resolve;
@@ -292,14 +310,14 @@ describe("code-view worker lifecycle", () => {
310
await held;
311
expect(pool.isInitialized()).toBe(false);
312
expect(testState.pools.size).toBe(1);
295
- expect(loadingViews()).toBe(2);
313
+ expect(loadingViews(view.container)).toBe(2);
314
expect(testState.renderPools).toHaveLength(0);
315
316
await view.rerender(renderViews(1));
317
expect(pool.getStats().totalWorkers).toBe(2);
318
expect(testState.terminations).toBe(0);
319
await view.rerender(renderViews(0));
302
- // Pierre gives up on a held startup after 10 seconds; the idle timer then tears the pool down.
320
+ // Pierre gives up on the held startup after 10 seconds; the idle timer then tears the pool down.
321
const timedOut = expect(pending).rejects.toThrow("worker initialization timed out");
322
await vi.advanceTimersByTimeAsync(30_000);
323
await timedOut;
@@ -310,7 +328,7 @@ describe("code-view worker lifecycle", () => {
328
expect(testState.workers).toHaveLength(2);
329
expect(testState.terminations).toBe(2);
330
expect(testState.renderPools).toHaveLength(0);
313
- expect(document.querySelectorAll("pre")).toHaveLength(0);
331
+ expect(view.container.querySelectorAll("pre")).toHaveLength(0);
332
});
333
});
334
@@ -346,7 +364,11 @@ describe("collapsed diff content", () => {
364
testState.failWorkers = false;
365
testState.holdInitialization = false;
366
const pool = new WorkerPoolManager(
349
- { workerFactory: () => new DiffsWorker(), poolSize: 1 },
367
+ {
368
+ workerFactory: () => new DiffsWorker(),
369
+ poolSize: 1,
370
+ workerInitializationTimeout: UNLIMITED_WORKER_STARTUP_MS,
371
+ },
372
{ theme: "pierre-dark", langs: ["typescript"], preferredHighlighter: "shiki-wasm" },
373
);
374
stack.defer(() => pool.terminate());
@@ -569,7 +591,7 @@ function RevealViews({
591
}
592
593
describe("code-view file reveals", () => {
572
- const reveal = () => act(async () => document.querySelector("button")!.click());
594
+ const reveal = (view: Screen) => act(async () => view.container.querySelector("button")!.click());
595
596
function setup() {
597
revealCalls.length = 0;
@@ -580,7 +602,7 @@ describe("code-view file reveals", () => {
602
await using view = await render(
603
<RevealViews scope="first" visible selectedFile="external-a" />,
604
);
583
- await reveal();
605
+ await reveal(view);
606
expect(revealCalls.at(-1)?.fileKey).toBe("tree-file");
607
revealCalls.length = 0;
608
@@ -597,7 +619,7 @@ describe("code-view file reveals", () => {
619
await using view = await render(
620
<RevealViews scope="diff" visible={false} selectedFile="external" />,
621
);
600
- await reveal();
622
+ await reveal(view);
623
expect(revealCalls).toEqual([]);
624
625
await view.rerender(<RevealViews scope="diff" visible selectedFile="external" />);
@@ -612,7 +634,7 @@ describe("code-view file reveals", () => {
634
revealCalls.length = 0;
635
// A click that lands in the same update that hides the viewer waits for it to return.
636
await act(async () => {
615
- document.querySelector("button")!.click();
637
+ view.container.querySelector("button")!.click();
638
await view.rerender(<RevealViews scope="diff" visible={false} selectedFile="external" />);
639
});
640
expect(revealCalls).toEqual([]);
@@ -628,7 +650,7 @@ describe("code-view file reveals", () => {
650
await using view = await render(
651
<RevealViews scope="first" visible={false} selectedFile="external-a" />,
652
);
631
- await reveal();
653
+ await reveal(view);
654
await view.rerender(
655
<RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
656
);
@@ -636,7 +658,7 @@ describe("code-view file reveals", () => {
658
revealCalls.length = 0;
659
660
await view.rerender(<RevealViews scope="first" visible={false} />);
639
- await reveal();
661
+ await reveal(view);
662
await view.rerender(<RevealViews scope="second" visible={false} />);
663
await view.rerender(<RevealViews scope="first" visible />);
664
expect(revealCalls).toEqual([]);
@@ -644,9 +666,9 @@ describe("code-view file reveals", () => {
666
667
it("reveals after a collapsed file expands and honors another click on the same file", async () => {
668
setup();
647
- await using _view = await render(<RevealViews scope="diff" visible />);
648
- await reveal();
649
- await reveal();
669
+ await using view = await render(<RevealViews scope="diff" visible />);
670
+ await reveal(view);
671
+ await reveal(view);
672
expect(revealCalls).toEqual([
673
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
674
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
+9
-2
@@ -153,6 +153,14 @@ vi.mock(import("./PullRequestSummaryTab"), async (original) => {
153
}) as never,
154
};
155
});
156
+// The Code tab waits for the diff worker pool, and a cold pool starts real Shiki workers that
157
+// a loaded runner can keep past Pierre's 10s startup limit. These tests are about the panel,
158
+// so the pool falls back to main-thread highlighting at once.
159
+vi.mock("@pierre/diffs/worker/worker.js?worker", () => ({
160
+ default: function UnavailableDiffsWorker() {
161
+ throw new Error("Diff workers are disabled in panel tests");
162
+ },
163
+}));
164
vi.mock(import("../ui/toast"), async (original) => {
165
const actual = await original();
166
return {
@@ -398,7 +406,6 @@ describe.each([
406
);
407
});
408
401
- // The first Code-tab action starts real diff workers as well as driving the panel.
409
it.each([
410
"Resolve conflicts",
411
"Ask a question",
@@ -406,7 +413,7 @@ describe.each([
413
"Fix findings in this thread",
414
"Fix check",
415
"Add to agent",
409
- ])("%s writes to the correct composer", { timeout: 30_000 }, async (action) => {
416
+ ])("%s writes to the correct composer", async (action) => {
417
setup();
418
// Cover both a host without inline comments and an account that cannot write them.
419
currentDetail =
apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx
+6
-1
@@ -129,9 +129,14 @@ const imageUrl = `data:image/svg+xml,${encodeURIComponent(
129
'<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect width="8" height="8" fill="red"/></svg>',
130
)}`;
131
132
+// The registry drops an unsubscribed atom on its next task. A row calls createUrl while it
133
+// renders but subscribes only after React commits, so on a busy runner a URL published
134
+// in between would be dropped. A server keeps its answer; keepAlive models that.
135
function addFiles(paths: string[]) {
136
state.entries = paths.map((path) => ({ path, kind: "file" }));
134
- for (const path of paths) state.assets.set(path, Atom.make<AssetResult>(AsyncResult.initial()));
137
+ for (const path of paths) {
138
+ state.assets.set(path, Atom.make<AssetResult>(AsyncResult.initial()).pipe(Atom.keepAlive));
139
+ }
140
}
141
142
function fileRow(path: string) {
apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
+18
-17
@@ -429,35 +429,36 @@ describe("project settings permissions", () => {
429
});
430
431
describe("project settings scope", () => {
432
- it("offers project checkout environments while keeping unselected and unknown projects recoverable", async () => {
432
+ const environmentMenu = () => page.getByRole("button", { name: /^Environment scope:/ });
433
+ const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
434
+ const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
435
+
436
+ it("offers every environment while no project is selected", async () => {
437
setup();
438
state.projects = state.projects.filter((project) => project.environmentId === primaryId);
435
- const key = projectKey();
436
- await using screen = await mountSettings({});
437
- const environmentMenu = () => page.getByRole("button", { name: /^Environment scope:/ });
438
- const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
439
- const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
439
+ await using _screen = await mountSettings({});
440
441
await userEvent.click(environmentMenu());
442
await expect.element(primaryOption()).toBeVisible();
443
await expect.element(remoteOption()).toBeVisible();
444
- await userEvent.keyboard("{Escape}");
444
+ });
445
+
446
+ it("offers only the selected project's checkout environments", async () => {
447
+ setup();
448
+ state.projects = state.projects.filter((project) => project.environmentId === primaryId);
449
+ await using _screen = await mountSettings({ project: projectKey() });
450
446
- await act(async () =>
447
- screen.router.navigate({ to: "/settings/projects", search: () => ({ project: key }) }),
448
- );
451
await expect.element(page.getByRole("textbox", { name: "Project name" })).toBeVisible();
452
await userEvent.click(environmentMenu());
453
await expect.element(primaryOption()).toBeVisible();
454
await expect.element(remoteOption()).not.toBeInTheDocument();
453
- await userEvent.keyboard("{Escape}");
455
+ });
456
+
457
+ it("keeps an unknown project recoverable from any environment", async () => {
458
+ setup();
459
+ state.projects = state.projects.filter((project) => project.environmentId === primaryId);
460
+ await using screen = await mountSettings({ project: "removed-project" });
461
455
- await act(async () =>
456
- screen.router.navigate({
457
- to: "/settings/projects",
458
- search: () => ({ project: "removed-project" }),
459
- }),
460
- );
462
await userEvent.click(environmentMenu());
463
await expect.element(primaryOption()).toBeVisible();
464
await expect.element(remoteOption()).toBeVisible();
apps/web/test/render.tsx
+12
-1
@@ -8,12 +8,19 @@ import {
8
import { act as reactAct, createContext, use, type ReactNode } from "react";
9
import { createRoot } from "react-dom/client";
10
import { vi } from "vite-plus/test";
11
-import { page, utils, type Locator, type LocatorSelectors } from "vite-plus/test/browser";
11
+import { commands, page, utils, type Locator, type LocatorSelectors } from "vite-plus/test/browser";
12
13
declare global {
14
var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;
15
}
16
17
+declare module "vite-plus/test/browser" {
18
+ interface BrowserCommands {
19
+ /** Defined in vite.config.ts. Moves Playwright's mouse off the page. */
20
+ resetPointer: () => Promise<void>;
21
+ }
22
+}
23
+
24
// React warns about every update outside act() while this flag is on, and a real
25
// browser drives updates from userEvent, timers and network that act() cannot wrap.
26
// So it is on only while act() runs, and nested calls restore the outer value.
@@ -97,6 +104,10 @@ export async function render(
104
await unmount();
105
} finally {
106
container.remove();
107
+ // The real mouse outlives the test, and whatever the next test mounts under it
108
+ // starts hovered. Parking it here keeps render() itself free of awaits before
109
+ // the first mount, which tests rely on.
110
+ await commands.resetPointer();
111
}
112
},
113
};
apps/web/vite.config.ts
+7
@@ -108,6 +108,13 @@ const browserTestProject = {
108
provider: playwright(),
109
instances: [{ browser: "chromium" }],
110
screenshotFailures: false,
111
+ commands: {
112
+ // Playwright's mouse outlives each test, so whatever mounts under its last
113
+ // position starts hovered. test/render.tsx parks it off the page after each test.
114
+ resetPointer: async ({ page }) => {
115
+ await page.mouse.move(-1, -1);
116
+ },
117
+ },
118
},
119
},
120
} satisfies TestProjectInlineConfiguration;
packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts
+14
-4
@@ -28,9 +28,14 @@ const groupExists = (pgid: number) => {
28
}
29
};
30
31
+// A group of zombies can be reaped between a check and the kill, so ESRCH just means it is gone.
32
const killGroup = (pgid: number) =>
33
Effect.sync(() => {
33
- if (groupExists(pgid)) process.kill(-pgid, "SIGKILL");
34
+ try {
35
+ process.kill(-pgid, "SIGKILL");
36
+ } catch (cause) {
37
+ if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH")) throw cause;
38
+ }
39
});
40
41
const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") =>
@@ -38,13 +43,15 @@ const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") =>
43
Effect.gen(function* () {
44
const child = NodeChildProcess.spawn("/bin/sh", ["-c", script, ...args], {
45
detached: true,
41
- stdio: "ignore",
46
+ stdio: ["ignore", "pipe", "ignore"],
47
});
48
const exited = yield* Deferred.make<NodeJS.Signals | null>();
49
+ const printed = yield* Deferred.make<void>();
50
child.once("exit", (_code, signal) => Deferred.doneUnsafe(exited, Effect.succeed(signal)));
51
+ child.stdout.once("data", () => Deferred.doneUnsafe(printed, Effect.void));
52
const pid = child.pid;
53
if (pid === undefined) return yield* Effect.die("spawn failed");
47
- return { pid, exited: Deferred.await(exited) };
54
+ return { pid, exited: Deferred.await(exited), printed: Deferred.await(printed) };
55
}),
56
({ pid }) => killGroup(pid),
57
);
@@ -96,11 +103,14 @@ describe.each(observedPlatforms)("OpenCodeServerLedger observing as %s", (platfo
103
const fs = yield* FileSystem.FileSystem;
104
const path = yield* Path.Path;
105
const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
106
+ // The inner shell prints once it has exec'd. Until then it still carries the wrapper's
107
+ // command line, and recording that would make the reaper skip the group as recycled.
108
const wrapper = yield* spawnGroup(
109
SERVE_ARGS,
101
- '/bin/sh -c "sleep 600 & wait" "$0" "$@" & exit 0',
110
+ '/bin/sh -c "echo ready; sleep 600 & wait" "$0" "$@" & exit 0',
111
);
112
yield* wrapper.exited;
113
+ yield* wrapper.printed;
114
expect(groupExists(wrapper.pid)).toBe(true);
115
116
yield* recordFromDeadServer(stateDir, wrapper);