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

runtime.test.ts

1,313 lines47.3 KB

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