Skip to content

Commit 978d35a

Browse files
test: restore the real-clock wait rewrites dropped by the #22557 rebase
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a16d37d commit 978d35a

6 files changed

Lines changed: 70 additions & 79 deletions

File tree

‎apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -405,15 +405,24 @@ describe("makeRelayDeviceRegistrationRequest", () => {
405405
yield* Effect.promise(() => oldRequestArrived);
406406

407407
tokenListener?.({ pushToken: "rotated-activity-token" });
408-
const listenerRegistration = yield* Effect.forkChild(runBackgroundOperations());
409-
for (let pass = 0; pass < 5; pass++) {
410-
yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
411-
}
408+
const deviceIdLookups = vi.mocked(loadOrCreateAgentAwarenessDeviceId).mock.calls.length;
409+
const rotated = backgroundRuntime.pending.shift()!;
410+
// Starting immediately runs the listener's registration until it suspends: on the
411+
// activity lock, or, without one, at its device-id lookup.
412+
const rotatedRegistration = yield* Effect.forkChild(
413+
Effect.exit(
414+
rotated.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
415+
),
416+
{ startImmediately: true },
417+
);
418+
expect(vi.mocked(loadOrCreateAgentAwarenessDeviceId).mock.calls).toHaveLength(
419+
deviceIdLookups,
420+
);
412421
expect(arrivals).toEqual(["activity-token"]);
413422

414423
openOldRequest?.();
415424
yield* Fiber.join(lookup);
416-
yield* Fiber.join(listenerRegistration);
425+
rotated.resolve(yield* Fiber.join(rotatedRegistration));
417426
expect(arrivals).toEqual(["activity-token", "rotated-activity-token"]);
418427
}).pipe(
419428
Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -390,13 +390,20 @@ it.live.each([
390390
});
391391
const navigation = yield* viewer.input(message).pipe(Effect.forkScoped);
392392
yield* Effect.promise(() => started.promise);
393+
const cdp = contexts[0]!.sessions.at(-1)!;
394+
const send = cdp.send.getMockImplementation()!;
395+
const typed = Promise.withResolvers<void>();
396+
cdp.send.mockImplementation(async (operation, input) => {
397+
if (operation === "Input.insertText") typed.resolve();
398+
return send(operation, input);
399+
});
393400
const correction = yield* Effect.gen(function* () {
394401
yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" });
395402
yield* viewer.input({ type: "text", text: "hello" });
396403
}).pipe(Effect.forkScoped);
397404
yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
398-
// Check after runnable promises drain, without waiting for navigation or a timeout.
399-
yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
405+
// The text reaches the page while the first navigation is still uncommitted.
406+
yield* Effect.promise(() => typed.promise);
400407
expect(page.goto).toHaveBeenLastCalledWith(
401408
"http://localhost:5173/fixed",
402409
expect.objectContaining({ waitUntil: "commit" }),

‎apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts‎

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import * as Fiber from "effect/Fiber";
77
import * as FileSystem from "effect/FileSystem";
88
import * as Layer from "effect/Layer";
99
import * as Ref from "effect/Ref";
10-
import * as Schedule from "effect/Schedule";
10+
import * as Queue from "effect/Queue";
11+
import * as Tracer from "effect/Tracer";
1112
import {
1213
ProjectId,
1314
GitCommandError,
@@ -223,18 +224,33 @@ const layerBase = Layer.mergeAll(
223224

224225
type Repositories = Effect.Success<typeof makeRepositories>;
225226

226-
const awaitRunFailure = (
227-
service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
228-
input: PullRequestRef,
229-
) =>
230-
service.get(input).pipe(
231-
Effect.flatMap((result) =>
232-
result.run?._tag === "Failed"
233-
? Effect.succeed(result.run.detail)
234-
: Effect.fail("still running" as const),
235-
),
236-
Effect.retry(Schedule.spaced("20 millis")),
237-
);
227+
// A run forks into the service's scope, so a test learns it settled when the run's `write` span
228+
// ends; the run records its outcome synchronously right after.
229+
const watchRuns = Effect.gen(function* () {
230+
const ended = yield* Queue.unbounded<void>();
231+
const tracer = Tracer.make({
232+
span: (options) => {
233+
const span = new Tracer.NativeSpan(options);
234+
if (options.name !== "PullRequestReviewGuideService.write") return span;
235+
const end = span.end.bind(span);
236+
span.end = (endTime, exit) => {
237+
end(endTime, exit);
238+
Queue.offerUnsafe(ended, undefined);
239+
};
240+
return span;
241+
},
242+
});
243+
return {
244+
generate: (
245+
service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
246+
input: PullRequestRef,
247+
) => service.generate(input).pipe(Effect.withTracer(tracer)),
248+
settled: (
249+
service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
250+
input: PullRequestRef,
251+
) => Queue.take(ended).pipe(Effect.andThen(service.get(input))),
252+
};
253+
});
238254

239255
const startSingleBranchRun = (input: {
240256
readonly repositoryName: string;
@@ -330,7 +346,8 @@ const startSingleBranchRun = (input: {
330346
PullRequestReviewGuideService.PullRequestReviewGuideService,
331347
);
332348
const guideReference = { ...reference, repository: `acme/${input.repositoryName}` };
333-
yield* service.generate(guideReference);
349+
const runs = yield* watchRuns;
350+
yield* runs.generate(service, guideReference);
334351
return {
335352
repositories,
336353
reportedHead,
@@ -339,10 +356,10 @@ const startSingleBranchRun = (input: {
339356
stored,
340357
fetchedRefs,
341358
observed,
359+
settled: runs.settled(service, guideReference),
342360
};
343361
});
344362

345-
// Runs drive real git, which the test clock does not advance, so waits use real time.
346363
it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
347364
it.effect.each([
348365
{
@@ -393,10 +410,10 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
393410
Effect.asVoid,
394411
),
395412
});
396-
const detail = yield* Effect.raceFirst(
397-
awaitRunFailure(run.service, run.reference),
398-
Deferred.await(run.stored).pipe(Effect.andThen(Effect.die("a guide was written"))),
399-
);
413+
const result = yield* run.settled;
414+
assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
415+
assert.strictEqual(result.run?._tag, "Failed");
416+
const detail = result.run?._tag === "Failed" ? result.run.detail : "";
400417
for (const part of expected) assert.include(detail, part);
401418
assert.deepStrictEqual(run.observed, []);
402419
assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));

‎apps/server/src/terminal/Manager.test.ts‎

Lines changed: 9 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,16 @@ import {
1212
TerminalProviderInstanceNotFoundError,
1313
} from "@t3tools/contracts";
1414
import * as HostProcess from "@t3tools/shared/HostProcess";
15-
import * as Data from "effect/Data";
1615
import * as Deferred from "effect/Deferred";
17-
import * as Duration from "effect/Duration";
1816
import * as Effect from "effect/Effect";
1917
import * as Base64Url from "effect/encoding/Base64Url";
2018
import * as Exit from "effect/Exit";
2119
import * as Fiber from "effect/Fiber";
2220
import * as FileSystem from "effect/FileSystem";
2321
import * as Layer from "effect/Layer";
24-
import * as Option from "effect/Option";
2522
import * as PlatformError from "effect/PlatformError";
2623
import * as Path from "effect/Path";
2724
import * as Ref from "effect/Ref";
28-
import * as Schedule from "effect/Schedule";
2925
import * as Schema from "effect/Schema";
3026
import * as Scope from "effect/Scope";
3127
import * as Stream from "effect/Stream";
@@ -50,10 +46,6 @@ vi.mock("effect/SynchronizedRef", async (importOriginal) => {
5046

5147
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
5248

53-
class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
54-
readonly message: string;
55-
}> {}
56-
5749
class FakePtyProcess implements PtyAdapter.PtyProcess {
5850
readonly writes: string[] = [];
5951
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
@@ -205,26 +197,6 @@ class GatedPtyAdapter extends FakePtyAdapter {
205197
}
206198
}
207199

208-
const waitFor = <E, R>(
209-
predicate: Effect.Effect<boolean, E, R>,
210-
timeout: Duration.Input = 800,
211-
): Effect.Effect<void, WaitForConditionError | E, R> =>
212-
predicate.pipe(
213-
Effect.filterOrFail(
214-
(done) => done,
215-
() => new WaitForConditionError({ message: "Condition not met" }),
216-
),
217-
Effect.retry(Schedule.spaced("15 millis")),
218-
Effect.timeoutOption(timeout),
219-
Effect.flatMap((result) =>
220-
Option.match(result, {
221-
onNone: () =>
222-
Effect.fail(new WaitForConditionError({ message: "Timed out waiting for condition" })),
223-
onSome: () => Effect.void,
224-
}),
225-
),
226-
);
227-
228200
function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
229201
return {
230202
threadId: "thread-1",
@@ -773,14 +745,21 @@ it.layer(
773745
Effect.gen(function* () {
774746
const ptyAdapter = new FakePtyAdapter();
775747
let duringCheck: (pid: number) => Effect.Effect<void> = () => Effect.void;
776-
const { manager, getEvents } = yield* createManager(5, {
748+
const { manager } = yield* createManager(5, {
777749
ptyAdapter,
778750
subprocessPollIntervalMs: 60_000,
779751
subprocessInspector: (pid) =>
780752
duringCheck(pid).pipe(
781753
Effect.as({ hasRunningSubprocess: false, childCommand: null, processIds: [] }),
782754
),
783755
});
756+
const outputSeen = yield* Deferred.make<void>();
757+
const unsubscribeOutput = yield* manager.subscribe((event) =>
758+
event.type === "output"
759+
? Deferred.succeed(outputSeen, undefined).pipe(Effect.asVoid)
760+
: Effect.void,
761+
);
762+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribeOutput));
784763
yield* manager.open(openInput({ terminalId: "typed" }));
785764
yield* manager.open(openInput({ terminalId: "echoed" }));
786765
const [typed, echoed] = ptyAdapter.processes;
@@ -791,9 +770,7 @@ it.layer(
791770
.pipe(Effect.orDie)
792771
: Effect.gen(function* () {
793772
echoed!.emitData("make build\r\n");
794-
yield* waitFor(
795-
Effect.map(getEvents, (events) => events.some((event) => event.type === "output")),
796-
);
773+
yield* Deferred.await(outputSeen);
797774
}).pipe(Effect.orDie);
798775

799776
yield* manager.closeIdle({ threadId: "thread-1" });

‎packages/provider-opencode/src/server/status.test.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import * as NodeSqlite from "node:sqlite";
44
import * as NodeServices from "@effect/platform-node/NodeServices";
55
import { it } from "@effect/vitest";
66
import * as Deferred from "effect/Deferred";
7-
import * as Duration from "effect/Duration";
87
import * as Effect from "effect/Effect";
98
import * as Fiber from "effect/Fiber";
109
import * as FileSystem from "effect/FileSystem";
@@ -288,7 +287,6 @@ const runtimeMock = {
288287
state: {
289288
runVersionError: null as Error | null,
290289
runVersionPending: false,
291-
runVersionDelay: null as Duration.Input | null,
292290
versionStdout: DEFAULT_VERSION_STDOUT,
293291
inventoryError: null as Error | null,
294292
connectionError: null as Error | null,
@@ -309,7 +307,6 @@ const runtimeMock = {
309307
reset() {
310308
this.state.runVersionError = null;
311309
this.state.runVersionPending = false;
312-
this.state.runVersionDelay = null;
313310
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
314311
this.state.inventoryError = null;
315312
this.state.connectionError = null;
@@ -384,11 +381,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
384381
cause: runtimeMock.state.runVersionError,
385382
}),
386383
)
387-
: runtimeMock.state.runVersionDelay
388-
? Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }).pipe(
389-
Effect.delay(runtimeMock.state.runVersionDelay),
390-
)
391-
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
384+
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
392385
createOpenCodeSdkClient: (input) => {
393386
runtimeMock.state.sdkClientInputs.push(input);
394387
return {} as unknown as ReturnType<

‎packages/provider-pi/src/server/status.test.ts‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, describe, it } from "@effect/vitest";
33
import * as Cause from "effect/Cause";
4-
import * as Deferred from "effect/Deferred";
5-
import * as Duration from "effect/Duration";
64
import * as Effect from "effect/Effect";
75
import * as Queue from "effect/Queue";
86
import * as Schema from "effect/Schema";
@@ -54,13 +52,7 @@ function piProbeSpawner(version: string) {
5452
});
5553
}
5654

57-
const piDiscoverySpawner = (
58-
inventory: unknown,
59-
slowStartup?: {
60-
readonly delay: Duration.Input;
61-
readonly getStateReceived: Deferred.Deferred<void>;
62-
},
63-
) =>
55+
const piDiscoverySpawner = (inventory: unknown) =>
6456
Effect.gen(function* () {
6557
const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
6658
let stdinBuffer = "";
@@ -74,10 +66,6 @@ const piDiscoverySpawner = (
7466
stdinBuffer = stdinBuffer.slice(newline + 1);
7567
if (line.length === 0) continue;
7668
const request = decodeRpcRequest(line);
77-
if (request.type === "get_state" && slowStartup !== undefined) {
78-
yield* Deferred.succeed(slowStartup.getStateReceived, undefined);
79-
yield* Effect.sleep(slowStartup.delay);
80-
}
8169
const data =
8270
request.type === "get_available_models"
8371
? inventory

0 commit comments

Comments
 (0)