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