Open History to see the last commit
1import { describe, expect, it, vi } from "@effect/vitest";
2import {
3 EnvironmentId,
4 type TerminalAttachInput,
5 type TerminalAttachStreamEvent,
6 type TerminalMetadataStreamEvent,
7 type TerminalSummary,
8 WS_METHODS,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Latch from "effect/Latch";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Queue from "effect/Queue";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
22
23import {
24 AVAILABLE_CONNECTION_STATE,
25 ConnectionBlockedError,
26 ConnectionTransientError,
27 PrimaryConnectionTarget,
28 type PreparedConnection,
29 type SupervisorConnectionState,
30} from "../connection/model.ts";
31import * as EnvironmentRegistry from "../connection/registry.ts";
32import * as EnvironmentSupervisor from "../connection/supervisor.ts";
33import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
34import type * as RpcSession from "../rpc/session.ts";
35import type { QueryPersistence } from "./queryPersistence.ts";
36import { createTerminalEnvironmentAtoms } from "./terminal.ts";
37import {
38 environmentRpcKey,
39 createAtomCommandScheduler,
40 createEnvironmentQueryAtomFamily,
41 selectEnvironmentQueryData,
42 createEnvironmentSubscriptionAtomFamily,
43 createRuntimeCommand,
44 scheduleAtomCommandEffect,
45 executeAtomCommand,
46 executeAtomQuery,
47 isAtomCommandInterrupted,
48 mapAtomCommandResult,
49 runAtomCommand,
50 settleAsyncResult,
51 settlePromise,
52 squashAtomCommandFailure,
53} from "./runtime.ts";
54
55const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({
56 environmentId: EnvironmentId.make("query-environment"),
57 label: "Query environment",
58 httpBaseUrl: "https://query.example.test",
59 wsBaseUrl: "wss://query.example.test",
60});
61
62const QUERY_RPC_SESSION = {} as RpcSession.RpcSession;
63
64class TestQueryError extends Schema.TaggedError<TestQueryError>()("TestQueryError", {
65 message: Schema.String,
66}) {}
67
68const OFFLINE_QUERY_FAILURE = new ConnectionTransientError({
69 reason: "transport",
70 detail: "Relay is unavailable.",
71});
72
73const BLOCKED_QUERY_FAILURE = new ConnectionBlockedError({
74 reason: "permission",
75 detail: "Access denied.",
76});
77
78function queryConnectionState(
79 overrides: Partial<SupervisorConnectionState> = {},
80): SupervisorConnectionState {
81 return {
82 ...AVAILABLE_CONNECTION_STATE,
83 desired: true,
84 network: "online",
85 phase: "connected",
86 attempt: 1,
87 generation: 1,
88 ...overrides,
89 };
90}
91
92const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness")(function* <A, E>(
93 execute: Effect.Effect<A, E>,
94 {
95 refreshTrigger,
96 idleTtlMs,
97 persistence,
98 initialState,
99 isFinal,
100 }: {
101 readonly refreshTrigger?: Atom.Atom<unknown>;
102 readonly isFinal?: (value: A) => boolean;
103 readonly idleTtlMs?: number;
104 readonly persistence?: QueryPersistence<A>;
105 readonly initialState?: SupervisorConnectionState;
106 } = {},
107) {
108 const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());
109 const supervisorSession = yield* SubscriptionRef.make(Option.some(QUERY_RPC_SESSION));
110 const streamGeneration = yield* SubscriptionRef.make(0);
111 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
112 target: QUERY_ENVIRONMENT,
113 state: supervisorState,
114 session: supervisorSession,
115 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
116 connect: Effect.void,
117 disconnect: Effect.void,
118 retryNow: Effect.void,
119 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
120 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_environmentId, effect) =>
121 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
122 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
123 _environmentId,
124 stream,
125 ) =>
126 SubscriptionRef.changes(streamGeneration).pipe(
127 Stream.switchMap(() =>
128 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
129 ),
130 );
131 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
132 run,
133 followStream,
134 stateChanges: () => SubscriptionRef.changes(supervisorState),
135 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
136 const runtime = Atom.runtime(
137 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
138 );
139 const family = createEnvironmentQueryAtomFamily(runtime, {
140 label: "test.environment-query",
141 staleTimeMs: 60_000,
142 ...(persistence === undefined ? {} : { persistence }),
143 execute: () => execute,
144 ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }),
145 ...(idleTtlMs === undefined ? {} : { idleTtlMs }),
146 ...(isFinal === undefined ? {} : { isFinal }),
147 });
148
149 return {
150 runtime,
151 atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),
152 supervisorSession,
153 supervisorState,
154 streamGeneration,
155 };
156});
157
158/**
159 * `getResult` resumes from inside the query's listener, so it only unsubscribes
160 * once the reader yields.
161 */
162const readEnvironmentQuery = <A, E>(
163 registry: AtomRegistry.AtomRegistry,
164 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
165) =>
166 AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe(
167 Effect.tap(() => Effect.yieldNow),
168 );
169
170const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function* <A, E>(
171 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
172) {
173 const registry = AtomRegistry.make();
174 const unmount = registry.mount(atom);
175 yield* Effect.addFinalizer(() =>
176 Effect.sync(() => {
177 unmount();
178 registry.dispose();
179 }),
180 );
181 return registry;
182});
183
184describe("settleAsyncResult", () => {
185 it("preserves successful values and typed failures", async () => {
186 const success = await settleAsyncResult(() => Promise.resolve(Exit.succeed("done")));
187 expect(AsyncResult.isSuccess(success)).toBe(true);
188 if (AsyncResult.isSuccess(success)) {
189 expect(success.value).toBe("done");
190 }
191
192 const expectedFailure = new Error("request failed");
193 const failure = await settleAsyncResult(() => Promise.resolve(Exit.fail(expectedFailure)));
194 expect(AsyncResult.isFailure(failure)).toBe(true);
195 if (AsyncResult.isFailure(failure)) {
196 expect(Cause.hasDies(failure.cause)).toBe(false);
197 expect(Cause.squash(failure.cause)).toBe(expectedFailure);
198 }
199 });
200
201 it("encodes thrown and rejected promises as defects", async () => {
202 const thrownDefect = new Error("thrown defect");
203 const thrown = await settleAsyncResult<void, never>(() => {
204 throw thrownDefect;
205 });
206 expect(AsyncResult.isFailure(thrown)).toBe(true);
207 if (AsyncResult.isFailure(thrown)) {
208 expect(Cause.hasDies(thrown.cause)).toBe(true);
209 expect(Cause.squash(thrown.cause)).toBe(thrownDefect);
210 }
211
212 const rejectedDefect = new Error("rejected defect");
213 const rejected = await settleAsyncResult<void, never>(() => Promise.reject(rejectedDefect));
214 expect(AsyncResult.isFailure(rejected)).toBe(true);
215 if (AsyncResult.isFailure(rejected)) {
216 expect(Cause.hasDies(rejected.cause)).toBe(true);
217 expect(Cause.squash(rejected.cause)).toBe(rejectedDefect);
218 }
219 });
220});
221
222describe("atom command result helpers", () => {
223 it("maps successful command values", () => {
224 const result = mapAtomCommandResult(AsyncResult.success(2), (value) => value * 3);
225
226 expect(result._tag).toBe("Success");
227 if (result._tag === "Success") {
228 expect(result.value).toBe(6);
229 }
230 });
231
232 it("preserves failures while mapping", () => {
233 const result = mapAtomCommandResult(
234 AsyncResult.failure<number, string>(Cause.fail("nope")),
235 (value) => value * 3,
236 );
237
238 expect(result._tag).toBe("Failure");
239 if (result._tag === "Failure") {
240 expect(Cause.squash(result.cause)).toBe("nope");
241 }
242 });
243
244 it("distinguishes interruption from other failures", () => {
245 const interrupted = AsyncResult.failure(Cause.interrupt(1));
246 const failed = AsyncResult.failure(Cause.fail("nope"));
247
248 expect(isAtomCommandInterrupted(interrupted)).toBe(true);
249 expect(isAtomCommandInterrupted(failed)).toBe(false);
250 expect(squashAtomCommandFailure(failed)).toBe("nope");
251 });
252
253 it("settles raw promise boundaries as successes or defects", async () => {
254 const success = await settlePromise(() => Promise.resolve("done"));
255 expect(success._tag).toBe("Success");
256
257 const defect = new Error("raw promise rejected");
258 const failure = await settlePromise(() => Promise.reject(defect));
259 expect(failure._tag).toBe("Failure");
260 if (failure._tag === "Failure") {
261 expect(Cause.hasDies(failure.cause)).toBe(true);
262 expect(Cause.squash(failure.cause)).toBe(defect);
263 }
264 });
265
266 it("reports expected failures and defects through separate policies", async () => {
267 const warnings: string[] = [];
268 const errors: string[] = [];
269 const reporter = {
270 warn: (message: string) => {
271 warnings.push(message);
272 },
273 error: (message: string) => {
274 errors.push(message);
275 },
276 };
277
278 await executeAtomCommand(() => Promise.resolve(Exit.fail("nope")), { label: "save" }, reporter);
279 await executeAtomCommand(
280 () => Promise.resolve(Exit.fail("ignored")),
281 { label: "quiet save", reportFailure: false },
282 reporter,
283 );
284 await executeAtomCommand(
285 () => Promise.reject(new Error("defect")),
286 { label: "quiet save", reportFailure: false },
287 reporter,
288 );
289 await executeAtomCommand(
290 () => Promise.resolve(Exit.interrupt(1)),
291 { label: "interrupted" },
292 reporter,
293 );
294
295 expect(warnings).toEqual(["[atom-command] save failed"]);
296 expect(errors).toEqual(["[atom-command] quiet save defected"]);
297 });
298});
299
300describe("environmentRpcKey", () => {
301 it("isolates subscription state by environment and cwd", () => {
302 const environmentId = EnvironmentId.make("environment-1");
303 const originalTarget = {
304 environmentId,
305 input: { cwd: "/repo/original" },
306 };
307 const nextTarget = {
308 environmentId,
309 input: { cwd: "/repo/next" },
310 };
311
312 expect(environmentRpcKey(originalTarget)).not.toBe(environmentRpcKey(nextTarget));
313 expect(environmentRpcKey(originalTarget)).toBe(environmentRpcKey({ ...originalTarget }));
314 expect(
315 environmentRpcKey({
316 environmentId: EnvironmentId.make("environment-2"),
317 input: originalTarget.input,
318 }),
319 ).not.toBe(environmentRpcKey(originalTarget));
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("keeps the previous value when a refetch returns equal content", () =>
540 Effect.scoped(
541 Effect.gen(function* () {
542 let checks = [{ name: "ci", status: "passed" }];
543 const execute = Effect.sync(() => ({ checks: checks.map((check) => ({ ...check })) }));
544 const harness = yield* makeEnvironmentQueryHarness(execute);
545 const registry = yield* mountEnvironmentQuery(harness.atom);
546
547 const first = yield* readEnvironmentQuery(registry, harness.atom);
548 registry.refresh(harness.atom);
549 const equal = yield* readEnvironmentQuery(registry, harness.atom);
550 expect(equal).toBe(first);
551
552 checks = [{ name: "ci", status: "failed" }];
553 registry.refresh(harness.atom);
554 const changed = yield* readEnvironmentQuery(registry, harness.atom);
555 expect(changed).not.toBe(first);
556 expect(changed.checks[0]?.status).toBe("failed");
557 }),
558 ),
559 );
560
561 it.effect("does not notify a data-only reader when a refetch returns equal content", () =>
562 Effect.scoped(
563 Effect.gen(function* () {
564 let status = "passed";
565 const execute = Effect.sync(() => ({ checks: [{ name: "ci", status }] }));
566 const harness = yield* makeEnvironmentQueryHarness(execute);
567 const registry = yield* mountEnvironmentQuery(harness.atom);
568 yield* readEnvironmentQuery(registry, harness.atom);
569
570 const data = Atom.map(harness.atom, selectEnvironmentQueryData);
571 const seen: Array<unknown> = [];
572 let resultNotifications = 0;
573 const unsubscribeData = registry.subscribe(data, (value) => seen.push(value), {
574 immediate: true,
575 });
576 yield* Effect.addFinalizer(() => Effect.sync(unsubscribeData));
577 const unsubscribeResult = registry.subscribe(harness.atom, () => resultNotifications++);
578 yield* Effect.addFinalizer(() => Effect.sync(unsubscribeResult));
579
580 registry.refresh(harness.atom);
581 yield* readEnvironmentQuery(registry, harness.atom);
582 // The result itself still moves (timestamp, `waiting`), which SWR relies on.
583 expect(resultNotifications).toBeGreaterThan(0);
584 expect(seen).toHaveLength(1);
585
586 status = "failed";
587 registry.refresh(harness.atom);
588 yield* readEnvironmentQuery(registry, harness.atom);
589 expect(seen).toHaveLength(2);
590 expect(seen[1]).toEqual({ checks: [{ name: "ci", status: "failed" }] });
591 }),
592 ),
593 );
594
595 it.effect(
596 "retries an interrupted query without exposing a failure during session replacement",
597 () =>
598 Effect.scoped(
599 Effect.gen(function* () {
600 const firstStarted = Latch.makeUnsafe();
601 const failFirst = Latch.makeUnsafe();
602 const firstSettled = Latch.makeUnsafe();
603 const unavailable = new EnvironmentRpcUnavailableError({
604 environmentId: QUERY_ENVIRONMENT.environmentId,
605 message: "Query environment is not connected.",
606 });
607 let executions = 0;
608 const execute = Effect.suspend(() => {
609 executions += 1;
610 if (executions > 1) {
611 return Effect.succeed("recovered");
612 }
613 firstStarted.openUnsafe();
614 return failFirst.await.pipe(
615 Effect.andThen(Effect.fail(unavailable)),
616 Effect.ensuring(
617 Effect.sync(() => {
618 firstSettled.openUnsafe();
619 }),
620 ),
621 );
622 });
623 const harness = yield* makeEnvironmentQueryHarness(execute);
624 const registry = AtomRegistry.make();
625 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
626 const unsubscribe = registry.subscribe(
627 harness.atom,
628 (result) => {
629 observed.push(result);
630 },
631 { immediate: true },
632 );
633 yield* Effect.addFinalizer(() =>
634 Effect.sync(() => {
635 unsubscribe();
636 registry.dispose();
637 }),
638 );
639
640 yield* firstStarted.await;
641 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
642 yield* Effect.yieldNow;
643 failFirst.openUnsafe();
644 yield* firstSettled.await;
645 yield* Effect.yieldNow;
646
647 expect(observed.some(AsyncResult.isFailure)).toBe(false);
648
649 yield* SubscriptionRef.set(
650 harness.supervisorState,
651 queryConnectionState({ phase: "connecting", stage: "preparing" }),
652 );
653 yield* Effect.yieldNow;
654 yield* SubscriptionRef.set(
655 harness.supervisorState,
656 queryConnectionState({
657 phase: "backoff",
658 stage: null,
659 lastFailure: new ConnectionTransientError({
660 reason: "transport",
661 detail: "Relay session is reconnecting.",
662 }),
663 retryAt: 1,
664 }),
665 );
666 yield* Effect.yieldNow;
667
668 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
669 yield* SubscriptionRef.set(
670 harness.supervisorState,
671 queryConnectionState({ generation: 2 }),
672 );
673 expect(
674 yield* AtomRegistry.getResult(registry, harness.atom, {
675 suspendOnWaiting: true,
676 }),
677 ).toBe("recovered");
678 }),
679 ),
680 );
681
682 it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
683 Effect.scoped(
684 Effect.gen(function* () {
685 const firstStarted = Latch.makeUnsafe();
686 const failFirst = Latch.makeUnsafe();
687 const firstSettled = Latch.makeUnsafe();
688 let executions = 0;
689 const execute = Effect.suspend(() => {
690 executions += 1;
691 if (executions > 1) {
692 return Effect.succeed("recovered");
693 }
694 firstStarted.openUnsafe();
695 return failFirst.await.pipe(
696 Effect.andThen(
697 Effect.fail(
698 new EnvironmentRpcUnavailableError({
699 environmentId: QUERY_ENVIRONMENT.environmentId,
700 message: "Query environment is not connected.",
701 }),
702 ),
703 ),
704 Effect.ensuring(
705 Effect.sync(() => {
706 firstSettled.openUnsafe();
707 }),
708 ),
709 );
710 });
711 const harness = yield* makeEnvironmentQueryHarness(execute);
712 const registry = AtomRegistry.make();
713 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
714 const unsubscribe = registry.subscribe(
715 harness.atom,
716 (result) => {
717 observed.push(result);
718 },
719 { immediate: true },
720 );
721 yield* Effect.addFinalizer(() =>
722 Effect.sync(() => {
723 unsubscribe();
724 registry.dispose();
725 }),
726 );
727
728 yield* firstStarted.await;
729 // No yield before the failure: the request finds its session gone
730 // before the atom has processed the session change.
731 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
732 failFirst.openUnsafe();
733 yield* firstSettled.await;
734 yield* Effect.yieldNow;
735
736 expect(observed.some(AsyncResult.isFailure)).toBe(false);
737
738 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
739 yield* SubscriptionRef.set(
740 harness.supervisorState,
741 queryConnectionState({ generation: 2 }),
742 );
743 expect(
744 yield* AtomRegistry.getResult(registry, harness.atom, {
745 suspendOnWaiting: true,
746 }),
747 ).toBe("recovered");
748 expect(observed.some(AsyncResult.isFailure)).toBe(false);
749 }),
750 ),
751 );
752
753 it.effect("fails a query that reports unavailable while its session is still live", () =>
754 Effect.scoped(
755 Effect.gen(function* () {
756 const unavailable = new EnvironmentRpcUnavailableError({
757 environmentId: QUERY_ENVIRONMENT.environmentId,
758 message: "The environment did not respond to the request.",
759 });
760 const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
761 const registry = yield* mountEnvironmentQuery(harness.atom);
762
763 const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
764 suspendOnWaiting: true,
765 }).pipe(Effect.exit);
766
767 expect(exit).toStrictEqual(Exit.fail(unavailable));
768 }),
769 ),
770 );
771
772 it.effect.each([
773 {
774 condition: "after a manual disconnect",
775 state: queryConnectionState({
776 desired: false,
777 phase: "available",
778 stage: null,
779 attempt: 0,
780 }),
781 expectedFailure: null,
782 },
783 {
784 condition: "while the environment is offline",
785 state: queryConnectionState({
786 network: "offline",
787 phase: "offline",
788 stage: null,
789 lastFailure: OFFLINE_QUERY_FAILURE,
790 }),
791 expectedFailure: OFFLINE_QUERY_FAILURE,
792 },
793 {
794 condition: "when connection recovery is blocked",
795 state: queryConnectionState({
796 phase: "blocked",
797 stage: null,
798 lastFailure: BLOCKED_QUERY_FAILURE,
799 }),
800 expectedFailure: BLOCKED_QUERY_FAILURE,
801 },
802 ] as const)("settles as unavailable $condition", ({ state, expectedFailure }) =>
803 Effect.scoped(
804 Effect.gen(function* () {
805 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
806 const registry = yield* mountEnvironmentQuery(harness.atom);
807
808 expect(
809 yield* AtomRegistry.getResult(registry, harness.atom, {
810 suspendOnWaiting: true,
811 }),
812 ).toBe("connected");
813
814 yield* SubscriptionRef.set(harness.supervisorState, state);
815 yield* Effect.yieldNow;
816
817 const result = registry.get(harness.atom);
818 expect(AsyncResult.isFailure(result)).toBe(true);
819 expect(result.waiting).toBe(false);
820 if (AsyncResult.isFailure(result) && expectedFailure !== null) {
821 expect(Cause.squash(result.cause)).toBe(expectedFailure);
822 }
823 }),
824 ),
825 );
826
827 it.effect("keeps a genuine query failure settled while reconnecting", () =>
828 Effect.scoped(
829 Effect.gen(function* () {
830 const expectedFailure = new TestQueryError({ message: "Query failed." });
831 const firstStarted = Latch.makeUnsafe();
832 const failFirst = Latch.makeUnsafe();
833 const refreshStarted = Latch.makeUnsafe();
834 const finishRefresh = Latch.makeUnsafe();
835 let executions = 0;
836 const execute = Effect.suspend(() => {
837 executions += 1;
838 if (executions === 1) {
839 firstStarted.openUnsafe();
840 return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
841 }
842 refreshStarted.openUnsafe();
843 return finishRefresh.await.pipe(Effect.as("recovered"));
844 });
845 const harness = yield* makeEnvironmentQueryHarness(execute);
846 const registry = yield* mountEnvironmentQuery(harness.atom);
847
848 yield* firstStarted.await;
849 failFirst.openUnsafe();
850 const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
851 suspendOnWaiting: true,
852 }).pipe(Effect.exit);
853 expect(Exit.isFailure(initial)).toBe(true);
854 if (Exit.isFailure(initial)) {
855 expect(Cause.squash(initial.cause)).toBe(expectedFailure);
856 }
857
858 yield* SubscriptionRef.set(
859 harness.supervisorState,
860 queryConnectionState({ phase: "connecting", stage: "opening" }),
861 );
862 yield* Effect.yieldNow;
863
864 const refreshing = registry.get(harness.atom);
865 expect(AsyncResult.isFailure(refreshing)).toBe(true);
866 expect(refreshing.waiting).toBe(true);
867 if (AsyncResult.isFailure(refreshing)) {
868 expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
869 }
870
871 yield* SubscriptionRef.set(
872 harness.supervisorState,
873 queryConnectionState({ generation: 2 }),
874 );
875 yield* refreshStarted.await;
876 finishRefresh.openUnsafe();
877 expect(
878 yield* AtomRegistry.getResult(registry, harness.atom, {
879 suspendOnWaiting: true,
880 }),
881 ).toBe("recovered");
882 }),
883 ),
884 );
885
886 it.effect("retains the last successful value while reconnecting", () =>
887 Effect.scoped(
888 Effect.gen(function* () {
889 const refreshStarted = Latch.makeUnsafe();
890 const finishRefresh = Latch.makeUnsafe();
891 let executions = 0;
892 const execute = Effect.suspend(() => {
893 executions += 1;
894 if (executions === 1) {
895 return Effect.succeed("cached");
896 }
897 refreshStarted.openUnsafe();
898 return finishRefresh.await.pipe(Effect.as("updated"));
899 });
900 const harness = yield* makeEnvironmentQueryHarness(execute);
901 const registry = yield* mountEnvironmentQuery(harness.atom);
902
903 expect(
904 yield* AtomRegistry.getResult(registry, harness.atom, {
905 suspendOnWaiting: true,
906 }),
907 ).toBe("cached");
908
909 yield* SubscriptionRef.set(
910 harness.supervisorState,
911 queryConnectionState({ phase: "connecting", stage: "opening" }),
912 );
913 yield* Effect.yieldNow;
914 expect(registry.get(harness.atom)).toMatchObject({
915 _tag: "Success",
916 value: "cached",
917 waiting: true,
918 });
919
920 yield* SubscriptionRef.set(
921 harness.supervisorState,
922 queryConnectionState({
923 phase: "backoff",
924 stage: null,
925 lastFailure: new ConnectionTransientError({
926 reason: "transport",
927 detail: "Retrying.",
928 }),
929 retryAt: 1,
930 }),
931 );
932 yield* Effect.yieldNow;
933 expect(registry.get(harness.atom)).toMatchObject({
934 _tag: "Success",
935 value: "cached",
936 waiting: true,
937 });
938
939 yield* SubscriptionRef.set(
940 harness.supervisorState,
941 queryConnectionState({ generation: 2 }),
942 );
943 yield* refreshStarted.await;
944 expect(registry.get(harness.atom)).toMatchObject({
945 _tag: "Success",
946 value: "cached",
947 waiting: true,
948 });
949
950 finishRefresh.openUnsafe();
951 expect(
952 yield* AtomRegistry.getResult(registry, harness.atom, {
953 suspendOnWaiting: true,
954 }),
955 ).toBe("updated");
956 }),
957 ),
958 );
959
960 it.effect("refreshes on its trigger while read, and once on its next read when idle", () =>
961 Effect.scoped(
962 Effect.gen(function* () {
963 let executions = 0;
964 const trigger = Atom.make(0).pipe(Atom.keepAlive);
965 const harness = yield* makeEnvironmentQueryHarness(
966 Effect.sync(() => (executions += 1)),
967 { refreshTrigger: trigger },
968 );
969 const registry = AtomRegistry.make();
970 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
971 const read = readEnvironmentQuery(registry, harness.atom);
972
973 const unmount = registry.mount(harness.atom);
974 expect(yield* read).toBe(1);
975 registry.set(trigger, 1);
976 expect(yield* read).toBe(2);
977
978 unmount();
979 registry.set(trigger, 2);
980 registry.set(trigger, 3);
981 expect(executions).toBe(2);
982
983 expect(yield* read).toBe(3);
984 }),
985 ),
986 );
987
988 it.effect("stops refreshing on its trigger once the value is final", () =>
989 Effect.scoped(
990 Effect.gen(function* () {
991 let executions = 0;
992 const trigger = Atom.make(0).pipe(Atom.keepAlive);
993 const harness = yield* makeEnvironmentQueryHarness(
994 Effect.sync(() => (executions += 1)),
995 { refreshTrigger: trigger, isFinal: (value) => value >= 2 },
996 );
997 const registry = AtomRegistry.make();
998 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
999 const read = readEnvironmentQuery(registry, harness.atom);
1000
1001 registry.mount(harness.atom);
1002 expect(yield* read).toBe(1);
1003 registry.set(trigger, 1);
1004 expect(yield* read).toBe(2);
1005 registry.set(trigger, 2);
1006 expect(yield* read).toBe(2);
1007 expect(executions).toBe(2);
1008 }),
1009 ),
1010 );
1011
1012 it.effect("keeps an idle query when its trigger recomputes to the same value", () =>
1013 Effect.scoped(
1014 Effect.gen(function* () {
1015 let executions = 0;
1016 const settings = Atom.make({ theme: "dark" }).pipe(Atom.keepAlive);
1017 const trigger = Atom.make((get) => JSON.stringify([get(settings) !== null]));
1018 const harness = yield* makeEnvironmentQueryHarness(
1019 Effect.sync(() => (executions += 1)),
1020 { refreshTrigger: trigger },
1021 );
1022 const registry = AtomRegistry.make();
1023 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1024 const read = readEnvironmentQuery(registry, harness.atom);
1025
1026 const unmount = registry.mount(harness.atom);
1027 expect(yield* read).toBe(1);
1028 unmount();
1029 registry.set(settings, { theme: "light" });
1030 expect(yield* read).toBe(1);
1031 expect(executions).toBe(1);
1032 }),
1033 ),
1034 );
1035
1036 it.effect("refreshes an idle query the registry swept and rebuilt after its trigger moved", () =>
1037 Effect.scoped(
1038 Effect.gen(function* () {
1039 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
1040 yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers()));
1041 let executions = 0;
1042 const trigger = Atom.make(0).pipe(Atom.keepAlive);
1043 const harness = yield* makeEnvironmentQueryHarness(
1044 Effect.sync(() => (executions += 1)),
1045 { refreshTrigger: trigger, idleTtlMs: 1_000 },
1046 );
1047 const registry = AtomRegistry.make({ timeoutResolution: 100 });
1048 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1049 const read = readEnvironmentQuery(registry, harness.atom);
1050
1051 const unmount = registry.mount(harness.atom);
1052 expect(yield* read).toBe(1);
1053 unmount();
1054 yield* Effect.yieldNow;
1055 vi.advanceTimersByTime(500);
1056 registry.set(trigger, 1);
1057 yield* Effect.yieldNow;
1058 vi.advanceTimersByTime(700);
1059 expect(executions).toBe(1);
1060
1061 expect(yield* read).toBe(2);
1062 }),
1063 ),
1064 );
1065});
1066
1067describe("executeAtomQuery", () => {
1068 it("keeps concurrent query results correlated to their atoms", async () => {
1069 const firstLatch = Latch.makeUnsafe();
1070 const secondLatch = Latch.makeUnsafe();
1071 const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first")));
1072 const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second")));
1073 const registry = AtomRegistry.make();
1074
1075 const firstResult = executeAtomQuery(registry, firstAtom);
1076 const secondResult = executeAtomQuery(registry, secondAtom);
1077
1078 secondLatch.openUnsafe();
1079 firstLatch.openUnsafe();
1080
1081 const [first, second] = await Promise.all([firstResult, secondResult]);
1082 expect(first._tag).toBe("Success");
1083 expect(second._tag).toBe("Success");
1084 if (first._tag === "Success" && second._tag === "Success") {
1085 expect(first.value).toBe("first");
1086 expect(second.value).toBe("second");
1087 }
1088
1089 registry.dispose();
1090 });
1091
1092 it("settles when its caller aborts a waiting query", async () => {
1093 const registry = AtomRegistry.make();
1094 const controller = new AbortController();
1095 const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {
1096 reportDefect: false,
1097 signal: controller.signal,
1098 });
1099
1100 controller.abort();
1101
1102 const result = await resultPromise;
1103 expect(result._tag).toBe("Failure");
1104 if (result._tag === "Failure") {
1105 expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);
1106 }
1107 registry.dispose();
1108 });
1109});
1110
1111describe("runtime command runner", () => {
1112 it("encodes custom command rejections as defects", async () => {
1113 const defect = new Error("custom command rejected");
1114 const registry = AtomRegistry.make();
1115 const result = await runAtomCommand(
1116 registry,
1117 {
1118 label: "test.rejected-command",
1119 run: () => Promise.reject(defect),
1120 },
1121 undefined,
1122 { reportDefect: false },
1123 );
1124
1125 expect(result._tag).toBe("Failure");
1126 if (result._tag === "Failure") {
1127 expect(Cause.hasDies(result.cause)).toBe(true);
1128 expect(Cause.squash(result.cause)).toBe(defect);
1129 }
1130 registry.dispose();
1131 });
1132
1133 it("settles generated command scheduler defects from direct callers", async () => {
1134 const defect = new Error("invalid command key");
1135 const runtime = Atom.runtime(Layer.empty);
1136 const command = createRuntimeCommand(runtime, {
1137 label: "test.invalid-key",
1138 concurrency: {
1139 mode: "serial",
1140 key: () => {
1141 throw defect;
1142 },
1143 },
1144 execute: () => Effect.void,
1145 });
1146 const registry = AtomRegistry.make();
1147
1148 const result = await command.run(registry, undefined);
1149 expect(result._tag).toBe("Failure");
1150 if (result._tag === "Failure") {
1151 expect(Cause.hasDies(result.cause)).toBe(true);
1152 expect(Cause.squash(result.cause)).toBe(defect);
1153 }
1154 registry.dispose();
1155 });
1156
1157 it("correlates parallel invocation results", async () => {
1158 const firstLatch = Latch.makeUnsafe();
1159 const secondLatch = Latch.makeUnsafe();
1160 const runtime = Atom.runtime(Layer.empty);
1161 const command = createRuntimeCommand(runtime, {
1162 label: "test.parallel",
1163 execute: (id: "first" | "second") =>
1164 (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)),
1165 });
1166 const registry = AtomRegistry.make();
1167
1168 const first = command.run(registry, "first");
1169 const second = command.run(registry, "second");
1170 secondLatch.openUnsafe();
1171 firstLatch.openUnsafe();
1172
1173 expect(await first).toMatchObject({ _tag: "Success", value: "first", waiting: false });
1174 expect(await second).toMatchObject({ _tag: "Success", value: "second", waiting: false });
1175 registry.dispose();
1176 });
1177
1178 it("serializes commands that share a scheduler and lane", async () => {
1179 const firstLatch = Latch.makeUnsafe();
1180 const events: string[] = [];
1181 const runtime = Atom.runtime(Layer.empty);
1182 const scheduler = createAtomCommandScheduler();
1183 const concurrency = { mode: "serial" as const, key: () => "shared" };
1184 const firstCommand = createRuntimeCommand(runtime, {
1185 label: "test.first",
1186 scheduler,
1187 concurrency,
1188 execute: () =>
1189 Effect.sync(() => events.push("first:start")).pipe(
1190 Effect.andThen(firstLatch.await),
1191 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
1192 ),
1193 });
1194 const secondCommand = createRuntimeCommand(runtime, {
1195 label: "test.second",
1196 scheduler,
1197 concurrency,
1198 execute: () => Effect.sync(() => events.push("second:start")),
1199 });
1200 const registry = AtomRegistry.make();
1201
1202 const first = firstCommand.run(registry, undefined);
1203 const second = secondCommand.run(registry, undefined);
1204 await Promise.resolve();
1205 expect(events).toEqual(["first:start"]);
1206
1207 firstLatch.openUnsafe();
1208 await Promise.all([first, second]);
1209 expect(events).toEqual(["first:start", "first:end", "second:start"]);
1210 registry.dispose();
1211 });
1212
1213 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
1214 Effect.gen(function* () {
1215 const handoffStarted = Latch.makeUnsafe();
1216 const handoffComplete = Latch.makeUnsafe();
1217 const resumeComplete = Latch.makeUnsafe();
1218 const runtime = Atom.runtime(Layer.empty);
1219 const scheduler = createAtomCommandScheduler();
1220 const concurrency = { mode: "serial" as const, key: () => "shared" };
1221 const updateCommand = createRuntimeCommand(runtime, {
1222 label: "test.update",
1223 execute: (_input: void, registry) =>
1224 scheduleAtomCommandEffect(
1225 registry,
1226 scheduler,
1227 concurrency,
1228 undefined,
1229 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
1230 Effect.andThen(handoffComplete.await),
1231 ),
1232 ).pipe(Effect.andThen(resumeComplete.await)),
1233 });
1234 const configCommand = createRuntimeCommand(runtime, {
1235 label: "test.config",
1236 scheduler,
1237 concurrency,
1238 execute: () => Effect.succeed("configured"),
1239 });
1240 const registry = AtomRegistry.make();
1241
1242 const update = updateCommand.run(registry, undefined);
1243 yield* handoffStarted.await;
1244 const config = configCommand.run(registry, undefined);
1245 handoffComplete.openUnsafe();
1246
1247 expect(yield* Effect.promise(() => config)).toMatchObject({
1248 _tag: "Success",
1249 value: "configured",
1250 waiting: false,
1251 });
1252 resumeComplete.openUnsafe();
1253 expect(yield* Effect.promise(() => update)).toMatchObject({
1254 _tag: "Success",
1255 waiting: false,
1256 });
1257 registry.dispose();
1258 }),
1259 );
1260
1261 it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () =>
1262 Effect.gen(function* () {
1263 const commitStarting = yield* Deferred.make<void>();
1264 const observerArmed = yield* Deferred.make<void>();
1265 const reconnected = yield* Deferred.make<void>();
1266 const states = yield* Queue.unbounded<{ readonly phase: string }>();
1267 yield* Queue.offer(states, { phase: "connected" });
1268 const runtime = Atom.runtime(Layer.empty);
1269 const scheduler = createAtomCommandScheduler();
1270 const concurrency = { mode: "serial" as const, key: () => "shared" };
1271 const command = createRuntimeCommand(runtime, {
1272 label: "test.desktop-update-handoff",
1273 execute: (_input: void, registry) =>
1274 Effect.gen(function* () {
1275 yield* Deferred.await(commitStarting).pipe(
1276 Effect.andThen(
1277 Stream.fromQueue(states).pipe(
1278 Stream.tap(() => Deferred.succeed(observerArmed, undefined)),
1279 Stream.dropWhile((state) => state.phase === "connected"),
1280 Stream.filter((state) => state.phase === "connected"),
1281 Stream.runHead,
1282 ),
1283 ),
1284 Effect.andThen(Deferred.succeed(reconnected, undefined)),
1285 Effect.forkChild,
1286 );
1287 yield* scheduleAtomCommandEffect(
1288 registry,
1289 scheduler,
1290 concurrency,
1291 undefined,
1292 Deferred.succeed(commitStarting, undefined).pipe(
1293 Effect.andThen(Deferred.await(observerArmed)),
1294 ),
1295 );
1296 yield* Queue.offer(states, { phase: "backoff" });
1297 yield* Queue.offer(states, { phase: "connected" });
1298 yield* Deferred.await(reconnected);
1299 }),
1300 });
1301 const registry = AtomRegistry.make();
1302
1303 expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({
1304 _tag: "Success",
1305 });
1306 registry.dispose();
1307 }),
1308 );
1309
1310 it("deduplicates single-flight commands by key", async () => {
1311 const latch = Latch.makeUnsafe();
1312 let executions = 0;
1313 const runtime = Atom.runtime(Layer.empty);
1314 const command = createRuntimeCommand(runtime, {
1315 label: "test.single-flight",
1316 concurrency: { mode: "singleFlight", key: (key: string) => key },
1317 execute: () =>
1318 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1319 });
1320 const registry = AtomRegistry.make();
1321
1322 const first = command.run(registry, "same");
1323 const second = command.run(registry, "same");
1324 latch.openUnsafe();
1325
1326 expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1327 expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1328 expect(executions).toBe(1);
1329 registry.dispose();
1330 });
1331
1332 it("coalesces pending latest-value commands without interrupting the active call", async () => {
1333 const firstLatch = Latch.makeUnsafe();
1334 const executed: number[] = [];
1335 const runtime = Atom.runtime(Layer.empty);
1336 const command = createRuntimeCommand(runtime, {
1337 label: "test.latest",
1338 concurrency: { mode: "latest", key: () => "shared" },
1339 execute: (value: number) =>
1340 Effect.sync(() => executed.push(value)).pipe(
1341 Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
1342 Effect.as(value),
1343 ),
1344 });
1345 const registry = AtomRegistry.make();
1346
1347 const first = command.run(registry, 1);
1348 await Promise.resolve();
1349 const second = command.run(registry, 2);
1350 const third = command.run(registry, 3);
1351 firstLatch.openUnsafe();
1352
1353 expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
1354 expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1355 expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1356 expect(executed).toEqual([1, 3]);
1357 registry.dispose();
1358 });
1359});
1360
1361describe("persisted environment queries", () => {
1362 it.effect(
1363 "restores cached data in a new registry while offline, then refreshes on reconnect",
1364 () =>
1365 Effect.scoped(
1366 Effect.gen(function* () {
1367 let saved = Option.none<string>();
1368 const persistence: QueryPersistence<string> = {
1369 load: () => Effect.sync(() => saved),
1370 save: (_environmentId, _key, value) =>
1371 Effect.sync(() => {
1372 saved = Option.some(value);
1373 }),
1374 };
1375 const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1376 persistence,
1377 });
1378 const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1379 expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1380 expect(saved).toEqual(Option.some("first"));
1381
1382 const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1383 persistence,
1384 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1385 });
1386 const registry = yield* mountEnvironmentQuery(restarted.atom);
1387 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1388 yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1389 yield* Effect.yieldNow;
1390 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1391 expect(saved).toEqual(Option.some("updated"));
1392 }),
1393 ),
1394 );
1395
1396 it.effect("keeps cached content available when revalidation fails", () =>
1397 Effect.scoped(
1398 Effect.gen(function* () {
1399 const harness = yield* makeEnvironmentQueryHarness(
1400 Effect.fail(new TestQueryError({ message: "failed" })),
1401 {
1402 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1403 },
1404 );
1405 const registry = yield* mountEnvironmentQuery(harness.atom);
1406 yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1407 expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");
1408 }),
1409 ),
1410 );
1411
1412 it.effect("shows persisted data before a live request finishes", () =>
1413 Effect.scoped(
1414 Effect.gen(function* () {
1415 const response = yield* Deferred.make<string>();
1416 const seeded = yield* Deferred.make<void>();
1417 const refreshed = yield* Deferred.make<void>();
1418 const harness = yield* makeEnvironmentQueryHarness(Deferred.await(response), {
1419 persistence: {
1420 load: () => Effect.succeedSome("cached"),
1421 save: () => Effect.void,
1422 },
1423 });
1424 const registry = yield* mountEnvironmentQuery(harness.atom);
1425 const unsubscribe = registry.subscribe(
1426 harness.atom,
1427 (value) => {
1428 if (Option.getOrNull(AsyncResult.value(value)) === "cached")
1429 Deferred.doneUnsafe(seeded, Exit.void);
1430 if (Option.getOrNull(AsyncResult.value(value)) === "fresh")
1431 Deferred.doneUnsafe(refreshed, Exit.void);
1432 },
1433 { immediate: true },
1434 );
1435 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1436 yield* Deferred.await(seeded);
1437 expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");
1438 yield* Deferred.succeed(response, "fresh");
1439 yield* Deferred.await(refreshed);
1440 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1441 }),
1442 ),
1443 );
1444});