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