Skip to content
TypeScript

test: remove the timing races behind recurring CI and release failures (#22523)

Theo Brownef9dd25914dbd
diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts
index 0ec8b1c37b2..b4dd358c17b 100644
--- a/apps/server/integration/transferBudgetV2.integration.test.ts
+++ b/apps/server/integration/transferBudgetV2.integration.test.ts
@@ -1,5 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - Measures real local HTTP/WebSocket sockets.
import * as NodeHttp from "node:http";
+import * as NodeUtil from "node:util";
import { assert, it } from "@effect/vitest";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
@@ -299,9 +300,16 @@ it.live(
const events = turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT, true);
const stored = yield* sink.write({ events });
const last = stored.at(-1)!;
- const terminal = (item: StreamItem) =>
+ const threadTerminal = (item: StreamItem) =>
"sequence" in item && item.sequence >= last.sequence;
- for (const queue of [tq, sq, ttq, ssq]) yield* collectUntil(queue, terminal);
+ // Shell items carry the shell read when their batch is projected, and unchanged
+ // shells are skipped, so a turn split across batches may never yield an item at
+ // the last sequence. Wait for the final shell instead.
+ const finalShell = yield* projection.getThreadShell(THREAD_ID);
+ const shellTerminal = (item: StreamItem) =>
+ item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell);
+ for (const queue of [tq, ttq]) yield* collectUntil(queue, threadTerminal);
+ for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal);
const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore);
const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore);
const measuredTurnSecondClientWebSocket = difference(
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts
index c2d29e98047..ae06aba0355 100644
--- a/apps/server/scripts/acp-mock-agent.ts
+++ b/apps/server/scripts/acp-mock-agent.ts
@@ -1383,6 +1383,7 @@ const program = Effect.gen(function* () {
(emitRunningCommandThenHangOnFirstPrompt && promptCount === 1)
) {
const toolCallId = "tool-call-running-1";
+ let runningCommandPublished: Promise<void> = Promise.resolve();
if (runningCommandPidPath !== undefined) {
const command = runningCommandIgnoresTerm
? '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* () {
if (runningCommandSeparateSession) {
const launcher = [
'const { spawn } = require("node:child_process");',
- "const child = spawn(process.argv[1], process.argv.slice(2), { stdio: 'ignore' });",
+ "const child = spawn(process.argv[1], process.argv.slice(2), { stdio: ['ignore', 'inherit', 'ignore'] });",
"child.once('exit', (code, signal) => process.exitCode = code ?? (signal ? 1 : 0));",
].join(" ");
const detachedCommand = runningCommandIgnoresTerm
- ? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; wait "$child"'
- : 'sleep 120 & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; wait "$child"';
+ ? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; echo published; wait "$child"'
+ : 'sleep 120 & child=$!; printf "%s %s %s\n" "$PPID" "$$" "$child" > "$1"; echo published; wait "$child"';
// Nested bash publishes "$PPID $$ $child" once it starts. Do not
// write the launcher PID alone here: that races with bash and can
- // clobber the triple that interrupt tests wait for.
+ // clobber the triple that interrupt tests wait for. It then prints a
+ // line, so an agent that exits after launch only exits once the
+ // triple exists instead of racing a slow launcher start.
const detachedLauncher = NodeChildProcess.spawn(
process.execPath,
["-e", launcher, "bash", "-c", detachedCommand, "bash", runningCommandPidPath],
- { detached: true, stdio: "ignore" },
+ { detached: true, stdio: ["ignore", "pipe", "ignore"] },
+ );
+ runningCommandPublished = new Promise((resolve) =>
+ detachedLauncher.stdout.once("data", () => resolve()),
);
detachedLauncher.unref();
} else {
@@ -1460,6 +1466,7 @@ const program = Effect.gen(function* () {
},
});
if (exitAfterRunningCommandLaunch) {
+ yield* Effect.promise(() => runningCommandPublished);
yield* Effect.sleep("100 millis");
return yield* Effect.sync(() => process.exit(0));
}
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 9c681f605ae..acdec8cf3d0 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -17499,11 +17499,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const NESTED_TOOL_USE_ID = "toolu-steer-nested";
const FINISHED_TOOL_USE_ID = "toolu-steer-finished";
const calls: Array<string> = [];
+ const backgroundRequested = yield* Deferred.make<void>();
let beforeAnswer: Effect.Effect<void> = Effect.void;
const lateAnswer = yield* Deferred.make<void>();
const harness = yield* makeWakeHarnessWithOptions({
backgroundTasks: (toolUseId) =>
Effect.sync(() => calls.push(toolUseId)).pipe(
+ Effect.andThen(Deferred.succeed(backgroundRequested, undefined)),
Effect.andThen(
backgrounding === "answers after the turn ended" ||
backgrounding === "answers after the subagent ran again"
@@ -17671,29 +17673,19 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
}
- // The steer arms its 5-second backgrounding timeout after the request
- // starts on another fiber, so one TestClock.adjust can land before that
- // timer exists and leave the steer waiting forever. Tick until it ends.
- const awaitSteerTimeout = <A, E>(fiber: Fiber.Fiber<A, E>) =>
- Effect.gen(function* () {
- for (let tick = 0; tick < 100 && fiber.pollUnsafe() === undefined; tick++) {
- yield* TestClock.adjust("1 second");
- yield* Effect.yieldNow;
- }
- if (fiber.pollUnsafe() === undefined) {
- return yield* Effect.die("Timed out waiting for the steer.");
- }
- return yield* Fiber.await(fiber);
- });
- const steering = yield* Effect.forkScoped(steer);
- const timesOut =
+ // Started at once so the steer reads its backgrounding deadline before
+ // this test moves the clock. Its message is built with real file I/O,
+ // so a scheduled start could read the clock after the moves below.
+ const steering = yield* Effect.forkScoped(steer, { startImmediately: true });
+ if (
backgrounding === "never answers" ||
- backgrounding === "answers after the steer went out";
- if (timesOut) {
- yield* awaitUntil(() => calls.length === 1, "background request");
+ backgrounding === "answers after the steer went out"
+ ) {
+ yield* Deferred.await(backgroundRequested);
assert.equal(harness.offeredMessages.length, offered);
+ yield* TestClock.adjust("5 seconds");
}
- const steered = yield* timesOut ? awaitSteerTimeout(steering) : Fiber.await(steering);
+ const steered = yield* Fiber.await(steering);
assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
if (backgrounding === "answers after the turn ended") {
@@ -17706,8 +17698,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
assert.equal(harness.offeredMessages.at(-1)?.priority, "now");
if (backgrounding === "never answers") {
for (let repeat = 1; repeat <= 2; repeat++) {
- const again = yield* Effect.forkScoped(steer);
- assert.isTrue(Exit.isSuccess(yield* awaitSteerTimeout(again)));
+ const again = yield* Effect.forkScoped(steer, { startImmediately: true });
+ yield* TestClock.adjust("5 seconds");
+ assert.isTrue(Exit.isSuccess(yield* Fiber.await(again)));
assert.equal(harness.offeredMessages.length, offered + 1 + repeat);
}
assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 53c71b9eed7..f1795704844 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -97,6 +97,7 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
+import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
@@ -304,6 +305,9 @@ const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
// reply can land after the progress frame that settles it. Its transcript
// stays the source of its answer this long after it settles.
const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
+// A steer waits at most this long, from its request, for its foreground
+// subagents to move to the background before it is sent.
+const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;
/**
* 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* (
// its result arrives as a task notification like any background agent.
const backgroundForegroundSubagents = Effect.fnUntraced(function* (
live: ClaudeLiveQueryContext,
+ deadline: number,
) {
const foreground: Array<{
readonly taskId: string;
@@ -9739,11 +9744,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
backgroundMovesByToolUseId.set(toolUseId, move);
moves.push(move);
}
- yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption("5 seconds"));
+ const remaining = deadline - (yield* Clock.currentTimeMillis);
+ yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption(Math.max(0, remaining)));
});
const steerTurn = Effect.fn("ClaudeAdapterV2.steerTurn")(
function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
+ // Measured from the request, not from when the moves are forked:
+ // building the message and the moves can take clock time a timer
+ // started later would not count, and the steer would wait past it.
+ const backgroundDeadline =
+ (yield* Clock.currentTimeMillis) + BACKGROUND_MOVE_TIMEOUT_MS;
const existing = yield* Ref.get(queryContext);
if (existing === null) {
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
@@ -9769,7 +9780,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
fileSystem,
skills: yield* userInvocableSkills(currentTurn.input.runtimePolicy.cwd),
});
- yield* backgroundForegroundSubagents(existing);
+ yield* backgroundForegroundSubagents(existing, backgroundDeadline);
// The turn can end while the moves are answered. A steer offered
// then would start a new turn the orchestrator never asked for, so
// the steer fails and the orchestrator starts the follow-up turn.
diff --git a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
index 757f3db20c0..c6551d4fcb7 100644
--- a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
+++ b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
@@ -77,9 +77,7 @@ it("keeps only the usage limit attached while an active goal waits in the collap
const limit = page.getByText("Usage limit reached", { exact: true });
const goal = page.getByText("Goal active", { exact: true });
- // A retained pointer can expand the stack as it mounts; start outside the hover target.
- await userEvent.hover(limit);
- await expect.poll(visibleBanners).toHaveLength(1);
+ expect(visibleBanners()).toHaveLength(1);
await expect.element(limit).toBeVisible();
await expect.element(goal).not.toBeVisible();
expect(container.querySelector('[data-slot="composer-banner-attachment"]')?.textContent).toBe(
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 665eb5e16f6..3452282be49 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -43,6 +43,15 @@ vi.mock(import("~/state/query"), async (original) => ({
})) as never,
}));
+// The first Mermaid render loads the library and its flowchart chunks, which took over
+// 10 seconds on a busy release runner. Pay that while the file loads, not inside a test.
+{
+ const { default: mermaid } = await import("mermaid");
+ mermaid.initialize({ startOnLoad: false });
+ await mermaid.render("mermaid-warmup", "flowchart LR\n A --> B");
+ document.getElementById("dmermaid-warmup")?.remove();
+}
+
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const CREATED_AT = "2026-03-17T19:12:28.000Z";
diff --git a/apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx b/apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
index 71dd1e89ee4..62fd79f6706 100644
--- a/apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
+++ b/apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx
@@ -1,4 +1,4 @@
-import { act, render, fakeTimers } from "../../../test/render";
+import { act, render, fakeTimers, type Screen } from "../../../test/render";
import {
CodeView,
FileDiff,
@@ -146,9 +146,16 @@ function renderViews(count: number) {
);
}
-const codeFile = (name: string) =>
- document.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
-const loadingViews = () => document.querySelectorAll('[role="status"]').length;
+// Pierre rejects a pool whose workers take 10s to start. Real workers share the runner with the
+// rest of the suite, so outside the test of that limit the test's own timeout is the only deadline.
+const UNLIMITED_WORKER_STARTUP_MS = 120_000;
+
+// Queries stay inside the test's own container: a timed-out test keeps running and leaves its
+// views mounted while the next test starts.
+const codeFile = (container: HTMLElement, name: string) =>
+ container.querySelector(`[data-code-file="${name}"]`)?.textContent ?? "";
+const loadingViews = (container: HTMLElement) =>
+ container.querySelectorAll('[role="status"]').length;
describe("code-view worker lifecycle", () => {
function setup() {
@@ -165,7 +172,7 @@ describe("code-view worker lifecycle", () => {
// Worker startup runs on real time, so only the idle expiry checks use this clock.
// Faking startup too would let advancing the idle clock time out a worker startup.
const idleClock = () => fakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
- async function workerEnvironment() {
+ async function workerEnvironment({ startupLimit = UNLIMITED_WORKER_STARTUP_MS } = {}) {
await using stack = new AsyncDisposableStack();
// Pins the pool at two workers whatever machine runs the suite.
stack.use(vi.spyOn(navigator, "hardwareConcurrency", "get").mockReturnValue(2));
@@ -175,6 +182,9 @@ describe("code-view worker lifecycle", () => {
this: WorkerPoolManager,
...args
) {
+ // The provider builds the pool without this option, so it is set before startup reads it.
+ const options: { workerInitializationTimeout?: number } = Reflect.get(this, "options");
+ options.workerInitializationTimeout = startupLimit;
const pending = initialize.apply(this, args);
testState.pools.set(this, pending);
return pending;
@@ -200,12 +210,13 @@ describe("code-view worker lifecycle", () => {
};
}
- // Two cold starts can each use Pierre's 10-second initialization budget.
+ // Two cold starts of real workers can outlast the default timeout on a loaded runner.
it("starts workers on demand and expires idle pools", { timeout: 30_000 }, async () => {
setup();
await using workers = await workerEnvironment();
const view = await workers.render(renderViews(0));
- const button = document.querySelector("button")!;
+ const { container } = view;
+ const button = container.querySelector("button")!;
expect(testState.workers).toHaveLength(0);
expect(testState.pools.size).toBe(0);
await act(async () => button.click());
@@ -214,7 +225,9 @@ describe("code-view worker lifecycle", () => {
await act(async () => testState.pools.get(pool));
expect(pool.isInitialized()).toBe(true);
expect(testState.workers).toHaveLength(2);
- await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
+ await vi.waitFor(() =>
+ expect(codeFile(container, "notes.txt")).toContain("Plain text is ready."),
+ );
expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
await view.rerender(renderViews(2));
@@ -223,7 +236,7 @@ describe("code-view worker lifecycle", () => {
expect(testState.workers).toHaveLength(2);
expect(new Set(testState.renderPools)).toEqual(new Set([pool]));
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
- await vi.waitFor(() => expect(codeFile("answer.ts")).toContain("answer"));
+ await vi.waitFor(() => expect(codeFile(container, "answer.ts")).toContain("answer"));
{
using _idleClock = idleClock();
@@ -238,7 +251,7 @@ describe("code-view worker lifecycle", () => {
await view.rerender(renderViews(1));
expect(testState.pools.size).toBe(1);
expect(testState.workers).toHaveLength(2);
- expect(loadingViews()).toBe(0);
+ expect(loadingViews(container)).toBe(0);
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
await vi.advanceTimersByTimeAsync(30_000);
expect(pool.getStats().totalWorkers).toBe(2);
@@ -254,16 +267,18 @@ describe("code-view worker lifecycle", () => {
await act(async () => testState.pools.get(reopenedPool));
expect(reopenedPool.isInitialized()).toBe(true);
expect(testState.workers).toHaveLength(4);
- expect(document.querySelector("button")).toBe(button);
+ expect(container.querySelector("button")).toBe(button);
expect(button.textContent).toBe("Edited draft");
- await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
+ await vi.waitFor(() =>
+ expect(codeFile(container, "notes.txt")).toContain("Plain text is ready."),
+ );
});
it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
setup();
await using workers = await workerEnvironment();
testState.failWorkers = true;
- await workers.render(renderViews(1));
+ const { container } = await workers.render(renderViews(1));
const pool = [...testState.pools.keys()][0]!;
await act(async () => {
await expect(testState.pools.get(pool)).rejects.toMatchObject({ _tag: "DiffWorkerError" });
@@ -275,13 +290,16 @@ describe("code-view worker lifecycle", () => {
});
expect(pool.isWorkingPool()).toBe(false);
expect(testState.workers).toHaveLength(0);
- await vi.waitFor(() => expect(codeFile("notes.txt")).toContain("Plain text is ready."));
+ await vi.waitFor(() =>
+ expect(codeFile(container, "notes.txt")).toContain("Plain text is ready."),
+ );
});
it("keeps an initializing pool until its last view closes and ignores late responses", async () => {
setup();
using _idleClock = idleClock();
- await using workers = await workerEnvironment();
+ // Runs Pierre's own startup limit on the fake clock.
+ await using workers = await workerEnvironment({ startupLimit: 10_000 });
testState.holdInitialization = true;
const held = new Promise<void>((resolve) => {
testState.onInitializationHeld = resolve;
@@ -292,14 +310,14 @@ describe("code-view worker lifecycle", () => {
await held;
expect(pool.isInitialized()).toBe(false);
expect(testState.pools.size).toBe(1);
- expect(loadingViews()).toBe(2);
+ expect(loadingViews(view.container)).toBe(2);
expect(testState.renderPools).toHaveLength(0);
await view.rerender(renderViews(1));
expect(pool.getStats().totalWorkers).toBe(2);
expect(testState.terminations).toBe(0);
await view.rerender(renderViews(0));
- // Pierre gives up on a held startup after 10 seconds; the idle timer then tears the pool down.
+ // Pierre gives up on the held startup after 10 seconds; the idle timer then tears the pool down.
const timedOut = expect(pending).rejects.toThrow("worker initialization timed out");
await vi.advanceTimersByTimeAsync(30_000);
await timedOut;
@@ -310,7 +328,7 @@ describe("code-view worker lifecycle", () => {
expect(testState.workers).toHaveLength(2);
expect(testState.terminations).toBe(2);
expect(testState.renderPools).toHaveLength(0);
- expect(document.querySelectorAll("pre")).toHaveLength(0);
+ expect(view.container.querySelectorAll("pre")).toHaveLength(0);
});
});
@@ -346,7 +364,11 @@ describe("collapsed diff content", () => {
testState.failWorkers = false;
testState.holdInitialization = false;
const pool = new WorkerPoolManager(
- { workerFactory: () => new DiffsWorker(), poolSize: 1 },
+ {
+ workerFactory: () => new DiffsWorker(),
+ poolSize: 1,
+ workerInitializationTimeout: UNLIMITED_WORKER_STARTUP_MS,
+ },
{ theme: "pierre-dark", langs: ["typescript"], preferredHighlighter: "shiki-wasm" },
);
stack.defer(() => pool.terminate());
@@ -569,7 +591,7 @@ function RevealViews({
}
describe("code-view file reveals", () => {
- const reveal = () => act(async () => document.querySelector("button")!.click());
+ const reveal = (view: Screen) => act(async () => view.container.querySelector("button")!.click());
function setup() {
revealCalls.length = 0;
@@ -580,7 +602,7 @@ describe("code-view file reveals", () => {
await using view = await render(
<RevealViews scope="first" visible selectedFile="external-a" />,
);
- await reveal();
+ await reveal(view);
expect(revealCalls.at(-1)?.fileKey).toBe("tree-file");
revealCalls.length = 0;
@@ -597,7 +619,7 @@ describe("code-view file reveals", () => {
await using view = await render(
<RevealViews scope="diff" visible={false} selectedFile="external" />,
);
- await reveal();
+ await reveal(view);
expect(revealCalls).toEqual([]);
await view.rerender(<RevealViews scope="diff" visible selectedFile="external" />);
@@ -612,7 +634,7 @@ describe("code-view file reveals", () => {
revealCalls.length = 0;
// A click that lands in the same update that hides the viewer waits for it to return.
await act(async () => {
- document.querySelector("button")!.click();
+ view.container.querySelector("button")!.click();
await view.rerender(<RevealViews scope="diff" visible={false} selectedFile="external" />);
});
expect(revealCalls).toEqual([]);
@@ -628,7 +650,7 @@ describe("code-view file reveals", () => {
await using view = await render(
<RevealViews scope="first" visible={false} selectedFile="external-a" />,
);
- await reveal();
+ await reveal(view);
await view.rerender(
<RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
);
@@ -636,7 +658,7 @@ describe("code-view file reveals", () => {
revealCalls.length = 0;
await view.rerender(<RevealViews scope="first" visible={false} />);
- await reveal();
+ await reveal(view);
await view.rerender(<RevealViews scope="second" visible={false} />);
await view.rerender(<RevealViews scope="first" visible />);
expect(revealCalls).toEqual([]);
@@ -644,9 +666,9 @@ describe("code-view file reveals", () => {
it("reveals after a collapsed file expands and honors another click on the same file", async () => {
setup();
- await using _view = await render(<RevealViews scope="diff" visible />);
- await reveal();
- await reveal();
+ await using view = await render(<RevealViews scope="diff" visible />);
+ await reveal(view);
+ await reveal(view);
expect(revealCalls).toEqual([
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
index 24e2a1955ee..27eae0e2976 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.browser.test.tsx
@@ -153,6 +153,14 @@ vi.mock(import("./PullRequestSummaryTab"), async (original) => {
}) as never,
};
});
+// The Code tab waits for the diff worker pool, and a cold pool starts real Shiki workers that
+// a loaded runner can keep past Pierre's 10s startup limit. These tests are about the panel,
+// so the pool falls back to main-thread highlighting at once.
+vi.mock("@pierre/diffs/worker/worker.js?worker", () => ({
+ default: function UnavailableDiffsWorker() {
+ throw new Error("Diff workers are disabled in panel tests");
+ },
+}));
vi.mock(import("../ui/toast"), async (original) => {
const actual = await original();
return {
@@ -398,7 +406,6 @@ describe.each([
);
});
- // The first Code-tab action starts real diff workers as well as driving the panel.
it.each([
"Resolve conflicts",
"Ask a question",
@@ -406,7 +413,7 @@ describe.each([
"Fix findings in this thread",
"Fix check",
"Add to agent",
- ])("%s writes to the correct composer", { timeout: 30_000 }, async (action) => {
+ ])("%s writes to the correct composer", async (action) => {
setup();
// Cover both a host without inline comments and an account that cannot write them.
currentDetail =
diff --git a/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx b/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx
index 6d0de80caa4..39aa4a19cc1 100644
--- a/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx
+++ b/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx
@@ -129,9 +129,14 @@ const imageUrl = `data:image/svg+xml,${encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect width="8" height="8" fill="red"/></svg>',
)}`;
+// The registry drops an unsubscribed atom on its next task. A row calls createUrl while it
+// renders but subscribes only after React commits, so on a busy runner a URL published
+// in between would be dropped. A server keeps its answer; keepAlive models that.
function addFiles(paths: string[]) {
state.entries = paths.map((path) => ({ path, kind: "file" }));
- for (const path of paths) state.assets.set(path, Atom.make<AssetResult>(AsyncResult.initial()));
+ for (const path of paths) {
+ state.assets.set(path, Atom.make<AssetResult>(AsyncResult.initial()).pipe(Atom.keepAlive));
+ }
}
function fileRow(path: string) {
diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
index 5f7137ca5b3..8d39c065f57 100644
--- a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
+++ b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
@@ -429,35 +429,36 @@ describe("project settings permissions", () => {
});
describe("project settings scope", () => {
- it("offers project checkout environments while keeping unselected and unknown projects recoverable", async () => {
+ const environmentMenu = () => page.getByRole("button", { name: /^Environment scope:/ });
+ const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
+ const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
+
+ it("offers every environment while no project is selected", async () => {
setup();
state.projects = state.projects.filter((project) => project.environmentId === primaryId);
- const key = projectKey();
- await using screen = await mountSettings({});
- const environmentMenu = () => page.getByRole("button", { name: /^Environment scope:/ });
- const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
- const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
+ await using _screen = await mountSettings({});
await userEvent.click(environmentMenu());
await expect.element(primaryOption()).toBeVisible();
await expect.element(remoteOption()).toBeVisible();
- await userEvent.keyboard("{Escape}");
+ });
+
+ it("offers only the selected project's checkout environments", async () => {
+ setup();
+ state.projects = state.projects.filter((project) => project.environmentId === primaryId);
+ await using _screen = await mountSettings({ project: projectKey() });
- await act(async () =>
- screen.router.navigate({ to: "/settings/projects", search: () => ({ project: key }) }),
- );
await expect.element(page.getByRole("textbox", { name: "Project name" })).toBeVisible();
await userEvent.click(environmentMenu());
await expect.element(primaryOption()).toBeVisible();
await expect.element(remoteOption()).not.toBeInTheDocument();
- await userEvent.keyboard("{Escape}");
+ });
+
+ it("keeps an unknown project recoverable from any environment", async () => {
+ setup();
+ state.projects = state.projects.filter((project) => project.environmentId === primaryId);
+ await using screen = await mountSettings({ project: "removed-project" });
- await act(async () =>
- screen.router.navigate({
- to: "/settings/projects",
- search: () => ({ project: "removed-project" }),
- }),
- );
await userEvent.click(environmentMenu());
await expect.element(primaryOption()).toBeVisible();
await expect.element(remoteOption()).toBeVisible();
diff --git a/apps/web/test/render.tsx b/apps/web/test/render.tsx
index 0ad52c0ec22..05ce93e024b 100644
--- a/apps/web/test/render.tsx
+++ b/apps/web/test/render.tsx
@@ -8,12 +8,19 @@ import {
import { act as reactAct, createContext, use, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { vi } from "vite-plus/test";
-import { page, utils, type Locator, type LocatorSelectors } from "vite-plus/test/browser";
+import { commands, page, utils, type Locator, type LocatorSelectors } from "vite-plus/test/browser";
declare global {
var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;
}
+declare module "vite-plus/test/browser" {
+ interface BrowserCommands {
+ /** Defined in vite.config.ts. Moves Playwright's mouse off the page. */
+ resetPointer: () => Promise<void>;
+ }
+}
+
// React warns about every update outside act() while this flag is on, and a real
// browser drives updates from userEvent, timers and network that act() cannot wrap.
// So it is on only while act() runs, and nested calls restore the outer value.
@@ -97,6 +104,10 @@ export async function render(
await unmount();
} finally {
container.remove();
+ // The real mouse outlives the test, and whatever the next test mounts under it
+ // starts hovered. Parking it here keeps render() itself free of awaits before
+ // the first mount, which tests rely on.
+ await commands.resetPointer();
}
},
};
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 6e550f68146..e58708100d6 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -108,6 +108,13 @@ const browserTestProject = {
provider: playwright(),
instances: [{ browser: "chromium" }],
screenshotFailures: false,
+ commands: {
+ // Playwright's mouse outlives each test, so whatever mounts under its last
+ // position starts hovered. test/render.tsx parks it off the page after each test.
+ resetPointer: async ({ page }) => {
+ await page.mouse.move(-1, -1);
+ },
+ },
},
},
} satisfies TestProjectInlineConfiguration;
diff --git a/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts b/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts
index 040e4ead2b5..90c72cf4913 100644
--- a/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts
+++ b/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts
@@ -28,9 +28,14 @@ const groupExists = (pgid: number) => {
}
};
+// A group of zombies can be reaped between a check and the kill, so ESRCH just means it is gone.
const killGroup = (pgid: number) =>
Effect.sync(() => {
- if (groupExists(pgid)) process.kill(-pgid, "SIGKILL");
+ try {
+ process.kill(-pgid, "SIGKILL");
+ } catch (cause) {
+ if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH")) throw cause;
+ }
});
const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") =>
@@ -38,13 +43,15 @@ const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") =>
Effect.gen(function* () {
const child = NodeChildProcess.spawn("/bin/sh", ["-c", script, ...args], {
detached: true,
- stdio: "ignore",
+ stdio: ["ignore", "pipe", "ignore"],
});
const exited = yield* Deferred.make<NodeJS.Signals | null>();
+ const printed = yield* Deferred.make<void>();
child.once("exit", (_code, signal) => Deferred.doneUnsafe(exited, Effect.succeed(signal)));
+ child.stdout.once("data", () => Deferred.doneUnsafe(printed, Effect.void));
const pid = child.pid;
if (pid === undefined) return yield* Effect.die("spawn failed");
- return { pid, exited: Deferred.await(exited) };
+ return { pid, exited: Deferred.await(exited), printed: Deferred.await(printed) };
}),
({ pid }) => killGroup(pid),
);
@@ -96,11 +103,14 @@ describe.each(observedPlatforms)("OpenCodeServerLedger observing as %s", (platfo
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
+ // The inner shell prints once it has exec'd. Until then it still carries the wrapper's
+ // command line, and recording that would make the reaper skip the group as recycled.
const wrapper = yield* spawnGroup(
SERVE_ARGS,
- '/bin/sh -c "sleep 600 & wait" "$0" "$@" & exit 0',
+ '/bin/sh -c "echo ready; sleep 600 & wait" "$0" "$@" & exit 0',
);
yield* wrapper.exited;
+ yield* wrapper.printed;
expect(groupExists(wrapper.pid)).toBe(true);
yield* recordFromDeadServer(stateDir, wrapper);