Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runtime.test.ts

1,491 lines54.9 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 ORCHESTRATION_V2_WS_METHODS,
5 ThreadId,
6 type ReviewDiffPreviewInput,
7 type PreviewEvent,
8 type TerminalAttachInput,
9 type TerminalAttachStreamEvent,
10 type TerminalMetadataStreamEvent,
11 type TerminalSummary,
12 WS_METHODS,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as DateTime from "effect/DateTime";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Latch from "effect/Latch";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Schema from "effect/Schema";
24import * as Stream from "effect/Stream";
25import * as SubscriptionRef from "effect/SubscriptionRef";
26import type { HttpClient } from "effect/http";
27import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
28​
29import {
30 AVAILABLE_CONNECTION_STATE,
31 ConnectionBlockedError,
32 ConnectionTransientError,
33 PrimaryConnectionTarget,
34 type PreparedConnection,
35 type SupervisorConnectionState,
36} from "../connection/model.ts";
37import * as EnvironmentRegistry from "../connection/registry.ts";
38import * as EnvironmentSupervisor from "../connection/supervisor.ts";
39import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
40import type * as RpcSession from "../rpc/session.ts";
41import { createOrchestrationEnvironmentAtoms } from "./orchestration.ts";
42import { createReviewEnvironmentAtoms } from "./review.ts";
43import { createPreviewEnvironmentAtoms } from "./preview.ts";
44import type { QueryPersistence } from "./queryPersistence.ts";
45import type { EnvironmentShellState } from "./shell.ts";
46import { createTerminalEnvironmentAtoms } from "./terminal.ts";
47import {
48 createAtomCommandScheduler,
49 createEnvironmentQueryAtomFamily,
50 selectEnvironmentQueryData,
51 createEnvironmentSubscriptionAtomFamily,
52 createRuntimeCommand,
53 environmentSessionGenerationAtom,
54 scheduleAtomCommandEffect,
55 executeAtomQuery,
56 type QueryAnswerHandler,
57} from "./runtime.ts";
58​
59const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({
60 environmentId: EnvironmentId.make("query-environment"),
61 label: "Query environment",
62 httpBaseUrl: "https://query.example.test",
63 wsBaseUrl: "wss://query.example.test",
64});
65​
66const QUERY_RPC_SESSION = {} as RpcSession.RpcSession;
67​
68class TestQueryError extends Schema.TaggedError<TestQueryError>()("TestQueryError", {
69 message: Schema.String,
70}) {}
71​
72const OFFLINE_QUERY_FAILURE = new ConnectionTransientError({
73 reason: "transport",
74 detail: "Relay is unavailable.",
75});
76​
77const BLOCKED_QUERY_FAILURE = new ConnectionBlockedError({
78 reason: "permission",
79 detail: "Access denied.",
80});
81​
82function queryConnectionState(
83 overrides: Partial<SupervisorConnectionState> = {},
84): SupervisorConnectionState {
85 return {
86 ...AVAILABLE_CONNECTION_STATE,
87 desired: true,
88 network: "online",
89 phase: "connected",
90 attempt: 1,
91 generation: 1,
92 ...overrides,
93 };
95​
96const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness")(function* <A, E>(
97 execute: Effect.Effect<A, E>,
98 {
99 refreshTrigger,
100 idleTtlMs,
101 persistence,
102 initialState,
103 rpcSession,
104 isFinal,
105 onAnswer,
106 }: {
107 readonly refreshTrigger?: Atom.Atom<unknown>;
108 readonly onAnswer?: QueryAnswerHandler<undefined, A>;
109 readonly isFinal?: (value: A) => boolean;
110 readonly idleTtlMs?: number;
111 readonly persistence?: QueryPersistence<A>;
112 readonly initialState?: SupervisorConnectionState;
113 readonly rpcSession?: RpcSession.RpcSession;
114 } = {},
115) {
116 const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());
117 const supervisorSession = yield* SubscriptionRef.make(
118 Option.some(rpcSession ?? QUERY_RPC_SESSION),
119 );
120 const streamGeneration = yield* SubscriptionRef.make(0);
121 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
122 target: QUERY_ENVIRONMENT,
123 state: supervisorState,
124 session: supervisorSession,
125 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
126 connect: Effect.void,
127 disconnect: Effect.void,
128 retryNow: Effect.void,
129 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
130 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_environmentId, effect) =>
131 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
132 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
133 _environmentId,
134 stream,
135 ) =>
136 SubscriptionRef.changes(streamGeneration).pipe(
137 Stream.switchMap(() =>
138 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
139 ),
140 );
141 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
142 run,
143 followStream,
144 stateChanges: () => SubscriptionRef.changes(supervisorState),
145 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
146 const runtime = Atom.runtime(
147 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
148 );
149 const family = createEnvironmentQueryAtomFamily(runtime, {
150 label: "test.environment-query",
151 staleTimeMs: 60_000,
152 ...(persistence === undefined ? {} : { persistence }),
153 execute: () => execute,
154 ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }),
155 ...(idleTtlMs === undefined ? {} : { idleTtlMs }),
156 ...(isFinal === undefined ? {} : { isFinal }),
157 ...(onAnswer === undefined ? {} : { onAnswer }),
158 });
159​
160 return {
161 runtime,
162 atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),
163 supervisorSession,
164 supervisorState,
165 streamGeneration,
166 };
167});
168​
169/**
170 * `getResult` resumes from inside the query's listener, so it only unsubscribes
171 * once the reader yields.
172 */
173const readEnvironmentQuery = <A, E>(
174 registry: AtomRegistry.AtomRegistry,
175 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
176) =>
177 AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe(
178 Effect.tap(() => Effect.yieldNow),
179 );
180​
181const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function* <A, E>(
182 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
183) {
184 const registry = AtomRegistry.make();
185 const unmount = registry.mount(atom);
186 yield* Effect.addFinalizer(() =>
187 Effect.sync(() => {
188 unmount();
189 registry.dispose();
190 }),
191 );
192 return registry;
193});
194​
195it.effect("keeps complete review metadata visible while a refresh is held", () =>
196 Effect.scoped(
197 Effect.gen(function* () {
198 const started = yield* Deferred.make<void>();
199 const release = yield* Deferred.make<void>();
200 let fullReads = 0;
201 const rpcSession = {
202 client: {
203 [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) =>
204 Effect.gen(function* () {
205 if (!input.trackedOnly && ++fullReads > 1) {
206 yield* Deferred.succeed(started, undefined);
207 yield* Deferred.await(release);
208 }
209 return {
210 cwd: input.cwd,
211 generatedAt: DateTime.makeUnsafe(0),
212 ...(input.trackedOnly ? { incomplete: true } : {}),
213 sources: [
214 {
215 id: "working-tree",
216 kind: "working-tree" as const,
217 title: "Uncommitted",
218 baseRef: "HEAD",
219 headRef: null,
220 diff: "",
221 diffHash: String(fullReads),
222 truncated: false,
223 patchesDeferred: true,
224 files: (input.trackedOnly ? ["tracked"] : ["tracked", "untracked"]).map(
225 (path) => ({ path, previousPath: null, additions: 1, deletions: 0 }),
226 ),
227 },
228 ],
229 };
230 }),
231 },
232 } as unknown as RpcSession.RpcSession;
233 const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession });
234 const atom = createReviewEnvironmentAtoms(harness.runtime).diffPreview({
235 environmentId: QUERY_ENVIRONMENT.environmentId,
236 input: { cwd: "/project", sourceKind: "working-tree", metadataOnly: true },
237 });
238 const registry = yield* mountEnvironmentQuery(atom);
239 expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.files).toHaveLength(2);
240 registry.refresh(atom);
241 yield* Deferred.await(started);
242 yield* Effect.sync(() => {
243 const value = AsyncResult.getOrElse(registry.get(atom), () => null);
244 expect(value?.incomplete).not.toBe(true);
245 expect(value?.sources[0]!.files).toHaveLength(2);
246 }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
247 expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.diffHash).toBe("2");
248 }),
249 ),
250);
251​
252describe("preview event subscriptions", () => {
253 it.effect("delivers every open and close when RPC events arrive in batches", () =>
254 Effect.scoped(
255 Effect.gen(function* () {
256 const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({
257 type: "opened",
258 threadId,
259 tabId: `tab-${index}`,
260 serverEpoch: "epoch-1",
261 revision: index + 1,
262 createdAt: "2026-10-02T00:00:00.000Z",
263 snapshot: {
264 threadId,
265 tabId: `tab-${index}`,
266 navStatus: { _tag: "Idle" },
267 canGoBack: false,
268 canGoForward: false,
269 updatedAt: "2026-10-02T00:00:00.000Z",
270 },
271 }));
272 const closed: PreviewEvent[] = opened.map((event, index) => ({
273 type: "closed",
274 threadId: event.threadId,
275 tabId: event.tabId,
276 serverEpoch: event.serverEpoch,
277 revision: opened.length + index + 1,
278 createdAt: event.createdAt,
279 }));
280 const releaseEvents = yield* Deferred.make<void>();
281 // Each iterable is one RPC chunk; separate emissions would hide lost events.
282 const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe(
283 Stream.flatMap(() =>
284 Stream.fromIterable(opened).pipe(
285 Stream.concat(Stream.fromIterable(closed)),
286 Stream.concat(Stream.never),
287 ),
288 ),
289 );
290 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
291 rpcSession: {
292 client: { [WS_METHODS.subscribePreviewEvents]: () => stream },
293 } as unknown as RpcSession.RpcSession,
294 });
295 const atom = createPreviewEnvironmentAtoms(harness.runtime).events({
296 environmentId: QUERY_ENVIRONMENT.environmentId,
297 input: {},
298 });
299 const registry = AtomRegistry.make();
300 const observed: PreviewEvent[] = [];
301 const sawLast = yield* Deferred.make<void>();
302 const unsubscribe = registry.subscribe(
303 atom,
304 (result) => {
305 if (!AsyncResult.isSuccess(result)) return;
306 observed.push(result.value);
307 if (result.value === closed[closed.length - 1]) {
308 Deferred.doneUnsafe(sawLast, Exit.void);
309 }
310 },
311 { immediate: true },
312 );
313 yield* Effect.addFinalizer(() =>
314 Effect.sync(() => {
315 unsubscribe();
316 registry.dispose();
317 }),
318 );
319​
320 yield* Deferred.succeed(releaseEvents, undefined);
321 yield* Deferred.await(sawLast);
322 expect(observed).toEqual([...opened, ...closed]);
323 }),
324 ),
325 );
326});
327​
328describe("finite environment subscription lifecycle", () => {
329 it.effect(
330 "exposes early values and settles on the terminal value without waiting for a reconnect",
331 () =>
332 Effect.scoped(
333 Effect.gen(function* () {
334 const releaseFinal = yield* Deferred.make<void>();
335 const sawEarly = yield* Deferred.make<void>();
336 const sawFinal = yield* Deferred.make<void>();
337 const closed = yield* Deferred.make<void>();
338 const stream = Stream.concat(
339 Stream.succeed({ complete: false, count: 1 }),
340 Stream.fromEffect(
341 Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })),
342 ),
343 ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined)));
344 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
345 followStream: (_environmentId: EnvironmentId, source: typeof stream) =>
346 Stream.concat(source, Stream.never),
347 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
348 const runtime = Atom.runtime(
349 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
350 );
351 const family = createEnvironmentSubscriptionAtomFamily(runtime, {
352 label: "test.finite-subscription",
353 subscribe: () => stream,
354 completeWhen: (value) => value.complete,
355 idleTtlMs: 0,
356 });
357 const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });
358 const registry = AtomRegistry.make();
359 const observed: Array<
360 AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown>
361 > = [];
362 const unsubscribe = registry.subscribe(
363 atom,
364 (result) => {
365 observed.push(result);
366 if (AsyncResult.isSuccess(result)) {
367 if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void);
368 if (result.value.complete && !result.waiting)
369 Deferred.doneUnsafe(sawFinal, Exit.void);
370 }
371 },
372 { immediate: true },
373 );
374 yield* Effect.addFinalizer(() =>
375 Effect.sync(() => {
376 unsubscribe();
377 registry.dispose();
378 }),
379 );
380 yield* Deferred.await(sawEarly);
381 const early = registry.get(atom);
382 expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1);
383 expect(early.waiting).toBe(true);
384 yield* Deferred.succeed(releaseFinal, undefined);
385 yield* Deferred.await(sawFinal);
386 yield* Deferred.await(closed);
387 const final = registry.get(atom);
388 expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123);
389 expect(final.waiting).toBe(false);
390 expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false);
391 }),
392 ),
393 );
394});
395​
396describe("environment query lifecycle", () => {
397 it.effect(
398 "terminal metadata waits for snapshots and retains known sessions across restarts",
399 () =>
400 Effect.gen(function* () {
401 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
402 const started = yield* Queue.unbounded<void>();
403 const events = yield* Queue.unbounded<TerminalMetadataStreamEvent>();
404 const receivedCheckout = yield* Deferred.make<void>();
405 const receivedEmpty = yield* Deferred.make<void>();
406 const checkout: TerminalSummary = {
407 threadId: "thread-1",
408 terminalId: "terminal-1",
409 cwd: "/repo/root/packages/app",
410 worktreePath: null,
411 status: "running",
412 pid: 123,
413 exitCode: null,
414 exitSignal: null,
415 hasRunningSubprocess: false,
416 label: "Terminal 1",
417 updatedAt: "2026-04-01T00:00:00.000Z",
418 };
419 const client = {
420 [WS_METHODS.subscribeTerminalMetadata]: () =>
421 Stream.fromEffect(Queue.offer(started, undefined)).pipe(
422 Stream.drain,
423 Stream.concat(Stream.fromQueue(events)),
424 ),
425 } as unknown as RpcSession.RpcSession["client"];
426 const session = { ...QUERY_RPC_SESSION, client };
427 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session));
428 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
429 const atom = atoms.metadata({
430 environmentId: QUERY_ENVIRONMENT.environmentId,
431 input: null,
432 });
433 const registry = AtomRegistry.make();
434 const observed: Array<ReadonlyArray<TerminalSummary>> = [];
435 const unsubscribe = registry.subscribe(
436 atom,
437 (result) => {
438 if (!AsyncResult.isSuccess(result)) return;
439 observed.push(result.value);
440 if (result.value.length > 0) Deferred.doneUnsafe(receivedCheckout, Exit.void);
441 else Deferred.doneUnsafe(receivedEmpty, Exit.void);
442 },
443 { immediate: true },
444 );
445 yield* Effect.addFinalizer(() =>
446 Effect.sync(() => {
447 unsubscribe();
448 registry.dispose();
449 }),
450 );
451​
452 yield* Queue.take(started);
453 expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull();
454 expect(observed).toEqual([]);
455​
456 yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] });
457 yield* Deferred.await(receivedCheckout);
458 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
459​
460 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session }));
461 yield* Queue.take(started);
462 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
463​
464 yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
465 yield* Queue.take(started);
466 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
467​
468 yield* Queue.offer(events, { type: "snapshot", terminals: [] });
469 yield* Deferred.await(receivedEmpty);
470 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]);
471 }),
472 );
473​
474 it.effect("terminal attach resubscribes with resume only after the stream replied", () =>
475 Effect.gen(function* () {
476 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
477 const inputs = yield* Queue.unbounded<TerminalAttachInput>();
478 const events = yield* Queue.unbounded<TerminalAttachStreamEvent>();
479 const received = yield* Deferred.make<void>();
480 const client = {
481 [WS_METHODS.terminalAttach]: (input: TerminalAttachInput) =>
482 Stream.fromEffect(Queue.offer(inputs, input)).pipe(
483 Stream.drain,
484 Stream.concat(Stream.fromQueue(events)),
485 ),
486 } as unknown as RpcSession.RpcSession["client"];
487 const firstSession = { ...QUERY_RPC_SESSION, client };
488 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(firstSession));
489 const input = {
490 threadId: "thread-1",
491 terminalId: "terminal-1",
492 cwd: "/tmp/project",
493 restartIfNotRunning: true,
494 };
495 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
496 const registry = AtomRegistry.make();
497 const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input });
498 const unmount = registry.subscribe(
499 atom,
500 (result) => {
501 if (AsyncResult.isSuccess(result) && result.value.version > 0) {
502 Deferred.doneUnsafe(received, Exit.void);
503 }
504 },
505 { immediate: true },
506 );
507 yield* Effect.addFinalizer(() =>
508 Effect.sync(() => {
509 unmount();
510 registry.dispose();
511 }),
512 );
513​
514 expect(yield* Queue.take(inputs)).toEqual(input);
515 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
516 expect(yield* Queue.take(inputs)).toEqual(input);
517 yield* Queue.offer(events, {
518 type: "closed",
519 threadId: input.threadId,
520 terminalId: input.terminalId,
521 });
522 yield* Deferred.await(received);
523​
524 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
525 expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });
526 // Catalog replacements rerun the same stream through followStream's switchMap.
527 yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
528 expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });
529​
530 unmount();
531 registry.dispose();
532 const remountedRegistry = AtomRegistry.make();
533 const remount = remountedRegistry.subscribe(atom, () => {}, { immediate: true });
534 yield* Effect.addFinalizer(() =>
535 Effect.sync(() => {
536 remount();
537 remountedRegistry.dispose();
538 }),
539 );
540 expect(yield* Queue.take(inputs)).toEqual(input);
541 }),
542 );
543​
544 it.effect(
545 "hides a session replacement, reports the relay backoff, and recovers on reconnect",
546 () =>
547 Effect.scoped(
548 Effect.gen(function* () {
549 const firstStarted = Latch.makeUnsafe();
550 const failFirst = Latch.makeUnsafe();
551 const firstSettled = Latch.makeUnsafe();
552 const unavailable = new EnvironmentRpcUnavailableError({
553 environmentId: QUERY_ENVIRONMENT.environmentId,
554 message: "Query environment is not connected.",
555 });
556 let executions = 0;
557 const execute = Effect.suspend(() => {
558 executions += 1;
559 if (executions > 1) {
560 return Effect.succeed("recovered");
561 }
562 firstStarted.openUnsafe();
563 return failFirst.await.pipe(
564 Effect.andThen(Effect.fail(unavailable)),
565 Effect.ensuring(
566 Effect.sync(() => {
567 firstSettled.openUnsafe();
568 }),
569 ),
570 );
571 });
572 const harness = yield* makeEnvironmentQueryHarness(execute);
573 const registry = AtomRegistry.make();
574 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
575 const unsubscribe = registry.subscribe(
576 harness.atom,
577 (result) => {
578 observed.push(result);
579 },
580 { immediate: true },
581 );
582 yield* Effect.addFinalizer(() =>
583 Effect.sync(() => {
584 unsubscribe();
585 registry.dispose();
586 }),
587 );
588​
589 yield* firstStarted.await;
590 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
591 yield* Effect.yieldNow;
592 failFirst.openUnsafe();
593 yield* firstSettled.await;
594 yield* Effect.yieldNow;
595​
596 expect(observed.some(AsyncResult.isFailure)).toBe(false);
597​
598 yield* SubscriptionRef.set(
599 harness.supervisorState,
600 queryConnectionState({ phase: "connecting", stage: "preparing" }),
601 );
602 yield* Effect.yieldNow;
603 const relayFailure = new ConnectionTransientError({
604 reason: "transport",
605 detail: "Relay session is reconnecting.",
606 });
607 yield* SubscriptionRef.set(
608 harness.supervisorState,
609 queryConnectionState({
610 phase: "backoff",
611 stage: null,
612 lastFailure: relayFailure,
613 retryAt: 1,
614 }),
615 );
616 yield* Effect.yieldNow;
617 // The query has never answered, so it reports why the environment is retrying.
618 const backingOff = registry.get(harness.atom);
619 expect(backingOff.waiting).toBe(false);
620 expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe(
621 relayFailure,
622 );
623​
624 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
625 yield* SubscriptionRef.set(
626 harness.supervisorState,
627 queryConnectionState({ generation: 2 }),
628 );
629 yield* Effect.yieldNow;
630 expect(
631 yield* AtomRegistry.getResult(registry, harness.atom, {
632 suspendOnWaiting: true,
633 }),
634 ).toBe("recovered");
635 }),
636 ),
637 );
638​
639 it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
640 Effect.scoped(
641 Effect.gen(function* () {
642 const firstStarted = Latch.makeUnsafe();
643 const failFirst = Latch.makeUnsafe();
644 const firstSettled = Latch.makeUnsafe();
645 let executions = 0;
646 const execute = Effect.suspend(() => {
647 executions += 1;
648 if (executions > 1) {
649 return Effect.succeed("recovered");
650 }
651 firstStarted.openUnsafe();
652 return failFirst.await.pipe(
653 Effect.andThen(
654 Effect.fail(
655 new EnvironmentRpcUnavailableError({
656 environmentId: QUERY_ENVIRONMENT.environmentId,
657 message: "Query environment is not connected.",
658 }),
659 ),
660 ),
661 Effect.ensuring(
662 Effect.sync(() => {
663 firstSettled.openUnsafe();
664 }),
665 ),
666 );
667 });
668 const harness = yield* makeEnvironmentQueryHarness(execute);
669 const registry = AtomRegistry.make();
670 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
671 const unsubscribe = registry.subscribe(
672 harness.atom,
673 (result) => {
674 observed.push(result);
675 },
676 { immediate: true },
677 );
678 yield* Effect.addFinalizer(() =>
679 Effect.sync(() => {
680 unsubscribe();
681 registry.dispose();
682 }),
683 );
684​
685 yield* firstStarted.await;
686 // No yield before the failure: the request finds its session gone
687 // before the atom has processed the session change.
688 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
689 failFirst.openUnsafe();
690 yield* firstSettled.await;
691 yield* Effect.yieldNow;
692​
693 expect(observed.some(AsyncResult.isFailure)).toBe(false);
694​
695 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
696 yield* SubscriptionRef.set(
697 harness.supervisorState,
698 queryConnectionState({ generation: 2 }),
699 );
700 expect(
701 yield* AtomRegistry.getResult(registry, harness.atom, {
702 suspendOnWaiting: true,
703 }),
704 ).toBe("recovered");
705 expect(observed.some(AsyncResult.isFailure)).toBe(false);
706 }),
707 ),
708 );
709​
710 it.effect("fails a query that reports unavailable while its session is still live", () =>
711 Effect.scoped(
712 Effect.gen(function* () {
713 const unavailable = new EnvironmentRpcUnavailableError({
714 environmentId: QUERY_ENVIRONMENT.environmentId,
715 message: "The environment did not respond to the request.",
716 });
717 const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
718 const registry = yield* mountEnvironmentQuery(harness.atom);
719​
720 const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
721 suspendOnWaiting: true,
722 }).pipe(Effect.exit);
723​
724 expect(exit).toStrictEqual(Exit.fail(unavailable));
725 }),
726 ),
727 );
728​
729 it.effect.each([
730 {
731 condition: "after a manual disconnect",
732 state: queryConnectionState({
733 desired: false,
734 phase: "available",
735 stage: null,
736 attempt: 0,
737 }),
738 expectedFailure: null,
739 },
740 {
741 condition: "while the environment is offline",
742 state: queryConnectionState({
743 network: "offline",
744 phase: "offline",
745 stage: null,
746 lastFailure: OFFLINE_QUERY_FAILURE,
747 }),
748 expectedFailure: OFFLINE_QUERY_FAILURE,
749 },
750 {
751 condition: "when connection recovery is blocked",
752 state: queryConnectionState({
753 phase: "blocked",
754 stage: null,
755 lastFailure: BLOCKED_QUERY_FAILURE,
756 }),
757 expectedFailure: BLOCKED_QUERY_FAILURE,
758 },
759 ] as const)("settles as unavailable $condition", ({ state, expectedFailure }) =>
760 Effect.scoped(
761 Effect.gen(function* () {
762 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
763 const registry = yield* mountEnvironmentQuery(harness.atom);
764​
765 expect(
766 yield* AtomRegistry.getResult(registry, harness.atom, {
767 suspendOnWaiting: true,
768 }),
769 ).toBe("connected");
770​
771 yield* SubscriptionRef.set(harness.supervisorState, state);
772 yield* Effect.yieldNow;
773​
774 const result = registry.get(harness.atom);
775 expect(AsyncResult.isFailure(result)).toBe(true);
776 expect(result.waiting).toBe(false);
777 if (AsyncResult.isFailure(result) && expectedFailure !== null) {
778 expect(Cause.squash(result.cause)).toBe(expectedFailure);
779 }
780 }),
781 ),
782 );
783​
784 it.effect.each([
785 { phase: "backoff", stage: null, retryAt: 1 },
786 { phase: "connecting", stage: "opening", retryAt: null },
787 ] as const)(
788 "settles a query it never answered while its environment retries ($phase)",
789 (retrying) =>
790 Effect.scoped(
791 Effect.gen(function* () {
792 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
793 initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }),
794 });
795 const registry = yield* mountEnvironmentQuery(harness.atom);
796 yield* Effect.yieldNow;
797​
798 const result = registry.get(harness.atom);
799 expect(result.waiting).toBe(false);
800 expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe(
801 OFFLINE_QUERY_FAILURE,
802 );
803​
804 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
805 yield* Effect.yieldNow;
806 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected");
807 }),
808 ),
809 );
810​
811 it.effect("a refresh started on a new session generation answers from that session", () =>
812 Effect.scoped(
813 Effect.gen(function* () {
814 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
815 initialState: queryConnectionState({
816 phase: "backoff",
817 stage: null,
818 lastFailure: OFFLINE_QUERY_FAILURE,
819 retryAt: 1,
820 }),
821 });
822 const registry = yield* mountEnvironmentQuery(harness.atom);
823 // Callers hold the failure a read got while the environment was retrying.
824 const failed = yield* Effect.promise(() =>
825 executeAtomQuery(registry, harness.atom, { reportFailure: false }),
826 );
827 expect(AsyncResult.isFailure(failed)).toBe(true);
828​
829 const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
830 const sessionGeneration = environmentSessionGenerationAtom(
831 harness.runtime,
832 QUERY_ENVIRONMENT.environmentId,
833 );
834 const unmount = registry.mount(sessionGeneration);
835 const unsubscribe = registry.subscribe(sessionGeneration, () => {
836 void executeAtomQuery(registry, harness.atom, {
837 refresh: true,
838 reportFailure: false,
839 }).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
840 });
841 yield* Effect.addFinalizer(() =>
842 Effect.sync(() => {
843 unsubscribe();
844 unmount();
845 }),
846 );
847 yield* Effect.yieldNow;
848​
849 yield* SubscriptionRef.set(
850 harness.supervisorSession,
851 Option.some({} as RpcSession.RpcSession),
852 );
853 yield* SubscriptionRef.set(
854 harness.supervisorState,
855 queryConnectionState({ generation: 2 }),
856 );
857 expect(yield* Deferred.await(answered)).toMatchObject({
858 _tag: "Success",
859 value: "connected",
860 });
861 }),
862 ),
863 );
864​
865 it.effect("keeps a genuine query failure settled while reconnecting", () =>
866 Effect.scoped(
867 Effect.gen(function* () {
868 const expectedFailure = new TestQueryError({ message: "Query failed." });
869 const firstStarted = Latch.makeUnsafe();
870 const failFirst = Latch.makeUnsafe();
871 const refreshStarted = Latch.makeUnsafe();
872 const finishRefresh = Latch.makeUnsafe();
873 let executions = 0;
874 const execute = Effect.suspend(() => {
875 executions += 1;
876 if (executions === 1) {
877 firstStarted.openUnsafe();
878 return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
879 }
880 refreshStarted.openUnsafe();
881 return finishRefresh.await.pipe(Effect.as("recovered"));
882 });
883 const harness = yield* makeEnvironmentQueryHarness(execute);
884 const registry = yield* mountEnvironmentQuery(harness.atom);
885​
886 yield* firstStarted.await;
887 failFirst.openUnsafe();
888 const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
889 suspendOnWaiting: true,
890 }).pipe(Effect.exit);
891 expect(Exit.isFailure(initial)).toBe(true);
892 if (Exit.isFailure(initial)) {
893 expect(Cause.squash(initial.cause)).toBe(expectedFailure);
894 }
895​
896 yield* SubscriptionRef.set(
897 harness.supervisorState,
898 queryConnectionState({ phase: "connecting", stage: "opening" }),
899 );
900 yield* Effect.yieldNow;
901​
902 const refreshing = registry.get(harness.atom);
903 expect(AsyncResult.isFailure(refreshing)).toBe(true);
904 expect(refreshing.waiting).toBe(true);
905 if (AsyncResult.isFailure(refreshing)) {
906 expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
907 }
908​
909 yield* SubscriptionRef.set(
910 harness.supervisorState,
911 queryConnectionState({ generation: 2 }),
912 );
913 yield* refreshStarted.await;
914 finishRefresh.openUnsafe();
915 expect(
916 yield* AtomRegistry.getResult(registry, harness.atom, {
917 suspendOnWaiting: true,
918 }),
919 ).toBe("recovered");
920 }),
921 ),
922 );
923​
924 it.effect("retains the last successful value while reconnecting", () =>
925 Effect.scoped(
926 Effect.gen(function* () {
927 const refreshStarted = Latch.makeUnsafe();
928 const finishRefresh = Latch.makeUnsafe();
929 let executions = 0;
930 const execute = Effect.suspend(() => {
931 executions += 1;
932 if (executions === 1) {
933 return Effect.succeed("cached");
934 }
935 refreshStarted.openUnsafe();
936 return finishRefresh.await.pipe(Effect.as("updated"));
937 });
938 const harness = yield* makeEnvironmentQueryHarness(execute);
939 const registry = yield* mountEnvironmentQuery(harness.atom);
940​
941 expect(
942 yield* AtomRegistry.getResult(registry, harness.atom, {
943 suspendOnWaiting: true,
944 }),
945 ).toBe("cached");
946​
947 yield* SubscriptionRef.set(
948 harness.supervisorState,
949 queryConnectionState({ phase: "connecting", stage: "opening" }),
950 );
951 yield* Effect.yieldNow;
952 expect(registry.get(harness.atom)).toMatchObject({
953 _tag: "Success",
954 value: "cached",
955 waiting: true,
956 });
957​
958 yield* SubscriptionRef.set(
959 harness.supervisorState,
960 queryConnectionState({
961 phase: "backoff",
962 stage: null,
963 lastFailure: new ConnectionTransientError({
964 reason: "transport",
965 detail: "Retrying.",
966 }),
967 retryAt: 1,
968 }),
969 );
970 yield* Effect.yieldNow;
971 expect(registry.get(harness.atom)).toMatchObject({
972 _tag: "Success",
973 value: "cached",
974 waiting: true,
975 });
976​
977 yield* SubscriptionRef.set(
978 harness.supervisorState,
979 queryConnectionState({ generation: 2 }),
980 );
981 yield* refreshStarted.await;
982 expect(registry.get(harness.atom)).toMatchObject({
983 _tag: "Success",
984 value: "cached",
985 waiting: true,
986 });
987​
988 finishRefresh.openUnsafe();
989 expect(
990 yield* AtomRegistry.getResult(registry, harness.atom, {
991 suspendOnWaiting: true,
992 }),
993 ).toBe("updated");
994 }),
995 ),
996 );
997​
998 it.effect("refreshes on its trigger while read, and once on its next read when idle", () =>
999 Effect.scoped(
1000 Effect.gen(function* () {
1001 let executions = 0;
1002 const trigger = Atom.make(0).pipe(Atom.keepAlive);
1003 const harness = yield* makeEnvironmentQueryHarness(
1004 Effect.sync(() => (executions += 1)),
1005 { refreshTrigger: trigger },
1006 );
1007 const registry = AtomRegistry.make();
1008 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1009 const read = readEnvironmentQuery(registry, harness.atom);
1010​
1011 const unmount = registry.mount(harness.atom);
1012 expect(yield* read).toBe(1);
1013 registry.set(trigger, 1);
1014 expect(yield* read).toBe(2);
1015​
1016 unmount();
1017 registry.set(trigger, 2);
1018 registry.set(trigger, 3);
1019 expect(executions).toBe(2);
1020​
1021 expect(yield* read).toBe(3);
1022 }),
1023 ),
1024 );
1025​
1026 it.effect("re-checks thread titles when one of their threads leaves the shell", () =>
1027 Effect.scoped(
1028 Effect.gen(function* () {
1029 const requests = yield* Queue.unbounded<Deferred.Deferred<Record<string, string>>>();
1030 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1031 rpcSession: {
1032 client: {
1033 [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: () =>
1034 Effect.gen(function* () {
1035 const answer = yield* Deferred.make<Record<string, string>>();
1036 yield* Queue.offer(requests, answer);
1037 return yield* Deferred.await(answer);
1038 }),
1039 },
1040 } as unknown as RpcSession.RpcSession,
1041 });
1042 const shellState = Atom.make<Pick<EnvironmentShellState, "removedAt">>({
1043 removedAt: new Map(),
1044 }).pipe(Atom.keepAlive);
1045 const removed = (entries: ReadonlyArray<readonly [string, number]>) => ({
1046 removedAt: new Map(entries.map(([id, sequence]) => [ThreadId.make(id), sequence])),
1047 });
1048 // Thread titles never use the HTTP client.
1049 const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1050 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1051 >;
1052 const atom = createOrchestrationEnvironmentAtoms(runtime, {
1053 shellState: () => shellState,
1054 }).threadTitles({
1055 environmentId: QUERY_ENVIRONMENT.environmentId,
1056 input: { threadIds: [ThreadId.make("fork")] },
1057 });
1058 const registry = yield* mountEnvironmentQuery(atom);
1059 const settled: Array<Record<string, string>> = [];
1060 const unsubscribe = registry.subscribe(atom, (result) => {
1061 if (AsyncResult.isSuccess(result) && !result.waiting) settled.push(result.value);
1062 });
1063 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1064​
1065 yield* Deferred.succeed(yield* Queue.take(requests), { fork: "Fork" });
1066 expect(yield* readEnvironmentQuery(registry, atom)).toEqual({ fork: "Fork" });
1067​
1068 registry.set(shellState, removed([["other", 5]]));
1069 expect(registry.get(atom).waiting).toBe(false);
1070​
1071 // Archiving and then deleting the fork both remove it from the shell.
1072 registry.set(shellState, removed([["fork", 6]]));
1073 const beforeDelete = yield* Queue.take(requests);
1074 registry.set(shellState, removed([["fork", 7]]));
1075 const afterDelete = yield* Queue.take(requests);
1076 yield* Deferred.succeed(beforeDelete, { fork: "Fork" });
1077 yield* Deferred.succeed(afterDelete, {});
1078 expect(yield* readEnvironmentQuery(registry, atom)).toEqual({});
1079 expect(settled).toEqual([{ fork: "Fork" }, {}]);
1080 }),
1081 ),
1082 );
1083});
1084​
1085describe("executeAtomQuery", () => {
1086 it("keeps concurrent query results correlated to their atoms", async () => {
1087 const firstLatch = Latch.makeUnsafe();
1088 const secondLatch = Latch.makeUnsafe();
1089 const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first")));
1090 const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second")));
1091 const registry = AtomRegistry.make();
1092​
1093 const firstResult = executeAtomQuery(registry, firstAtom);
1094 const secondResult = executeAtomQuery(registry, secondAtom);
1095​
1096 secondLatch.openUnsafe();
1097 firstLatch.openUnsafe();
1098​
1099 const [first, second] = await Promise.all([firstResult, secondResult]);
1100 expect(first._tag).toBe("Success");
1101 expect(second._tag).toBe("Success");
1102 if (first._tag === "Success" && second._tag === "Success") {
1103 expect(first.value).toBe("first");
1104 expect(second.value).toBe("second");
1106​
1107 registry.dispose();
1108 });
1109​
1110 it("settles when its caller aborts a waiting query", async () => {
1111 const registry = AtomRegistry.make();
1112 const controller = new AbortController();
1113 const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {
1114 reportDefect: false,
1115 signal: controller.signal,
1116 });
1117​
1118 controller.abort();
1119​
1120 const result = await resultPromise;
1121 expect(result._tag).toBe("Failure");
1122 if (result._tag === "Failure") {
1123 expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);
1125 registry.dispose();
1126 });
1127});
1128​
1129describe("runtime command runner", () => {
1130 it("settles generated command scheduler defects from direct callers", async () => {
1131 const defect = new Error("invalid command key");
1132 const runtime = Atom.runtime(Layer.empty);
1133 const command = createRuntimeCommand(runtime, {
1134 label: "test.invalid-key",
1135 concurrency: {
1136 mode: "serial",
1137 key: () => {
1138 throw defect;
1139 },
1140 },
1141 execute: () => Effect.void,
1142 });
1143 const registry = AtomRegistry.make();
1144​
1145 const result = await command.run(registry, undefined);
1146 expect(result._tag).toBe("Failure");
1147 if (result._tag === "Failure") {
1148 expect(Cause.hasDies(result.cause)).toBe(true);
1149 expect(Cause.squash(result.cause)).toBe(defect);
1151 registry.dispose();
1152 });
1153​
1154 it("serializes commands that share a scheduler and lane", async () => {
1155 const firstLatch = Latch.makeUnsafe();
1156 const events: string[] = [];
1157 const runtime = Atom.runtime(Layer.empty);
1158 const scheduler = createAtomCommandScheduler();
1159 const concurrency = { mode: "serial" as const, key: () => "shared" };
1160 const firstCommand = createRuntimeCommand(runtime, {
1161 label: "test.first",
1162 scheduler,
1163 concurrency,
1164 execute: () =>
1165 Effect.sync(() => events.push("first:start")).pipe(
1166 Effect.andThen(firstLatch.await),
1167 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
1168 ),
1169 });
1170 const secondCommand = createRuntimeCommand(runtime, {
1171 label: "test.second",
1172 scheduler,
1173 concurrency,
1174 execute: () => Effect.sync(() => events.push("second:start")),
1175 });
1176 const registry = AtomRegistry.make();
1177​
1178 const first = firstCommand.run(registry, undefined);
1179 const second = secondCommand.run(registry, undefined);
1180 await Promise.resolve();
1181 expect(events).toEqual(["first:start"]);
1182​
1183 firstLatch.openUnsafe();
1184 await Promise.all([first, second]);
1185 expect(events).toEqual(["first:start", "first:end", "second:start"]);
1186 registry.dispose();
1187 });
1188​
1189 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
1190 Effect.gen(function* () {
1191 const handoffStarted = Latch.makeUnsafe();
1192 const handoffComplete = Latch.makeUnsafe();
1193 const resumeComplete = Latch.makeUnsafe();
1194 const runtime = Atom.runtime(Layer.empty);
1195 const scheduler = createAtomCommandScheduler();
1196 const concurrency = { mode: "serial" as const, key: () => "shared" };
1197 const updateCommand = createRuntimeCommand(runtime, {
1198 label: "test.update",
1199 execute: (_input: void, registry) =>
1200 scheduleAtomCommandEffect(
1201 registry,
1202 scheduler,
1203 concurrency,
1204 undefined,
1205 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
1206 Effect.andThen(handoffComplete.await),
1207 ),
1208 ).pipe(Effect.andThen(resumeComplete.await)),
1209 });
1210 const configCommand = createRuntimeCommand(runtime, {
1211 label: "test.config",
1212 scheduler,
1213 concurrency,
1214 execute: () => Effect.succeed("configured"),
1215 });
1216 const registry = AtomRegistry.make();
1217​
1218 const update = updateCommand.run(registry, undefined);
1219 yield* handoffStarted.await;
1220 const config = configCommand.run(registry, undefined);
1221 handoffComplete.openUnsafe();
1222​
1223 expect(yield* Effect.promise(() => config)).toMatchObject({
1224 _tag: "Success",
1225 value: "configured",
1226 waiting: false,
1227 });
1228 resumeComplete.openUnsafe();
1229 expect(yield* Effect.promise(() => update)).toMatchObject({
1230 _tag: "Success",
1231 waiting: false,
1232 });
1233 registry.dispose();
1234 }),
1235 );
1236​
1237 it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () =>
1238 Effect.gen(function* () {
1239 const commitStarting = yield* Deferred.make<void>();
1240 const observerArmed = yield* Deferred.make<void>();
1241 const reconnected = yield* Deferred.make<void>();
1242 const states = yield* Queue.unbounded<{ readonly phase: string }>();
1243 yield* Queue.offer(states, { phase: "connected" });
1244 const runtime = Atom.runtime(Layer.empty);
1245 const scheduler = createAtomCommandScheduler();
1246 const concurrency = { mode: "serial" as const, key: () => "shared" };
1247 const command = createRuntimeCommand(runtime, {
1248 label: "test.desktop-update-handoff",
1249 execute: (_input: void, registry) =>
1250 Effect.gen(function* () {
1251 yield* Deferred.await(commitStarting).pipe(
1252 Effect.andThen(
1253 Stream.fromQueue(states).pipe(
1254 Stream.tap(() => Deferred.succeed(observerArmed, undefined)),
1255 Stream.dropWhile((state) => state.phase === "connected"),
1256 Stream.filter((state) => state.phase === "connected"),
1257 Stream.runHead,
1258 ),
1259 ),
1260 Effect.andThen(Deferred.succeed(reconnected, undefined)),
1261 Effect.forkChild,
1262 );
1263 yield* scheduleAtomCommandEffect(
1264 registry,
1265 scheduler,
1266 concurrency,
1267 undefined,
1268 Deferred.succeed(commitStarting, undefined).pipe(
1269 Effect.andThen(Deferred.await(observerArmed)),
1270 ),
1271 );
1272 yield* Queue.offer(states, { phase: "backoff" });
1273 yield* Queue.offer(states, { phase: "connected" });
1274 yield* Deferred.await(reconnected);
1275 }),
1276 });
1277 const registry = AtomRegistry.make();
1278​
1279 expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({
1280 _tag: "Success",
1281 });
1282 registry.dispose();
1283 }),
1284 );
1285​
1286 it("deduplicates single-flight commands by key", async () => {
1287 const latch = Latch.makeUnsafe();
1288 let executions = 0;
1289 const runtime = Atom.runtime(Layer.empty);
1290 const command = createRuntimeCommand(runtime, {
1291 label: "test.single-flight",
1292 concurrency: { mode: "singleFlight", key: (key: string) => key },
1293 execute: () =>
1294 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1295 });
1296 const registry = AtomRegistry.make();
1297​
1298 const first = command.run(registry, "same");
1299 const second = command.run(registry, "same");
1300 latch.openUnsafe();
1301​
1302 expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1303 expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1304 expect(executions).toBe(1);
1305 registry.dispose();
1306 });
1307​
1308 it("coalesces pending latest-value commands without interrupting the active call", async () => {
1309 const firstLatch = Latch.makeUnsafe();
1310 const executed: number[] = [];
1311 const runtime = Atom.runtime(Layer.empty);
1312 const command = createRuntimeCommand(runtime, {
1313 label: "test.latest",
1314 concurrency: { mode: "latest", key: () => "shared" },
1315 execute: (value: number) =>
1316 Effect.sync(() => executed.push(value)).pipe(
1317 Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
1318 Effect.as(value),
1319 ),
1320 });
1321 const registry = AtomRegistry.make();
1322​
1323 const first = command.run(registry, 1);
1324 await Promise.resolve();
1325 const second = command.run(registry, 2);
1326 const third = command.run(registry, 3);
1327 firstLatch.openUnsafe();
1328​
1329 expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
1330 expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1331 expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1332 expect(executed).toEqual([1, 3]);
1333 registry.dispose();
1334 });
1335});
1336​
1337describe("persisted environment queries", () => {
1338 it.effect("keeps an in-memory cached page pending until revalidation settles", () =>
1339 Effect.scoped(
1340 Effect.gen(function* () {
1341 const refreshStarted = Latch.makeUnsafe();
1342 const finishRefresh = Latch.makeUnsafe();
1343 let executions = 0;
1344 const harness = yield* makeEnvironmentQueryHarness(
1345 Effect.suspend(() => {
1346 if (++executions === 1) return Effect.succeed("cached");
1347 refreshStarted.openUnsafe();
1348 return finishRefresh.await.pipe(Effect.as("fresh"));
1349 }),
1350 { persistence: { load: () => Effect.succeedNone, save: () => Effect.void } },
1351 );
1352 const registry = yield* mountEnvironmentQuery(harness.atom);
1353 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1354 registry.refresh(harness.atom);
1355 yield* refreshStarted.await;
1356 expect(registry.get(harness.atom)).toMatchObject({
1357 _tag: "Success",
1358 value: "cached",
1359 waiting: true,
1360 });
1361 finishRefresh.openUnsafe();
1362 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1363 }),
1364 ),
1365 );
1366​
1367 it.effect(
1368 "restores cached data in a new registry while offline, then refreshes on reconnect",
1369 () =>
1370 Effect.scoped(
1371 Effect.gen(function* () {
1372 let saved = Option.none<string>();
1373 const saves = yield* Queue.unbounded<string>();
1374 const persistence: QueryPersistence<string> = {
1375 load: () => Effect.sync(() => saved),
1376 save: (_environmentId, _key, value) =>
1377 Effect.sync(() => {
1378 saved = Option.some(value);
1379 }).pipe(Effect.andThen(Queue.offer(saves, value))),
1380 };
1381 const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1382 persistence,
1383 });
1384 const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1385 expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1386 expect(yield* Queue.take(saves)).toBe("first");
1387​
1388 const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1389 persistence,
1390 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1391 });
1392 const registry = yield* mountEnvironmentQuery(restarted.atom);
1393 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1394 yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1395 yield* Effect.yieldNow;
1396 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1397 expect(yield* Queue.take(saves)).toBe("updated");
1398 }),
1399 ),
1400 );
1401​
1402 it.effect("answers readers while its save is pending, and ends the save with the query", () =>
1403 Effect.scoped(
1404 Effect.gen(function* () {
1405 const saveEnded = Latch.makeUnsafe();
1406 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), {
1407 persistence: {
1408 load: () => Effect.succeedNone,
1409 // The registry's scheduler stops on dispose, so signal synchronously.
1410 save: () =>
1411 Effect.never.pipe(
1412 Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe())),
1413 ),
1414 },
1415 });
1416 yield* Effect.scoped(
1417 Effect.gen(function* () {
1418 const registry = yield* mountEnvironmentQuery(harness.atom);
1419 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1420 }),
1421 );
1422 yield* saveEnded.await;
1423 }),
1424 ),
1425 );
1426​
1427 it.effect("hands each server answer to onAnswer before readers see it", () =>
1428 Effect.scoped(
1429 Effect.gen(function* () {
1430 const answers: Array<readonly [string, string | null]> = [];
1431 let served = 0;
1432 const recorded = Atom.make<string | null>(null).pipe(Atom.keepAlive);
1433 const harness = yield* makeEnvironmentQueryHarness(
1434 Effect.sync(() => `answer-${++served}`),
1436 onAnswer: (_target, value, registry) =>
1437 Effect.sync(() => {
1438 answers.push([value, registry.get(recorded)]);
1439 registry.set(recorded, value);
1440 }),
1441 },
1442 );
1443 const registry = yield* mountEnvironmentQuery(harness.atom);
1444 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1");
1445 expect(registry.get(recorded)).toBe("answer-1");
1446 registry.refresh(harness.atom);
1447 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2");
1448 expect(answers).toEqual([
1449 ["answer-1", null],
1450 ["answer-2", "answer-1"],
1451 ]);
1452 }),
1453 ),
1454 );
1455​
1456 it.effect("does not hand a value restored from persistence to onAnswer", () =>
1457 Effect.scoped(
1458 Effect.gen(function* () {
1459 const answers: Array<string> = [];
1460 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), {
1461 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1462 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1463 onAnswer: (_target, value) => Effect.sync(() => answers.push(value)),
1464 });
1465 const registry = yield* mountEnvironmentQuery(harness.atom);
1466 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1467 expect(answers).toEqual([]);
1468 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1469 yield* Effect.yieldNow;
1470 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server");
1471 expect(answers).toEqual(["server"]);
1472 }),
1473 ),
1474 );
1475​
1476 it.effect("keeps cached content available when revalidation fails", () =>
1477 Effect.scoped(
1478 Effect.gen(function* () {
1479 const harness = yield* makeEnvironmentQueryHarness(
1480 Effect.fail(new TestQueryError({ message: "failed" })),
1482 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1483 },
1484 );
1485 const registry = yield* mountEnvironmentQuery(harness.atom);
1486 yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1487 expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached");
1488 }),
1489 ),
1490 );
1491});