@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,981 lines 75.1 KB
Raw
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodeV8 from "node:v8";
3 import * as NodeVM from "node:vm";
4 import { vi } from "vite-plus/test";
5 import {
6 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
7 EnvironmentId,
8 type FilesystemBrowseEntry,
9 type IssueListInput,
10 type IssueListResult,
11 ORCHESTRATION_V2_WS_METHODS,
12 type OrchestrationV2ArchivedShellSnapshot,
13 ThreadId,
14 ProjectId,
15 type ReviewDiffPreviewInput,
16 type PreviewEvent,
17 type TerminalAttachInput,
18 type TerminalAttachStreamEvent,
19 type TerminalMetadataStreamEvent,
20 type TerminalSummary,
21 WS_METHODS,
22 } from "@t3tools/contracts";
23 import * as Cause from "effect/Cause";
24 import * as Clock from "effect/Clock";
25 import * as DateTime from "effect/DateTime";
26 import * as Deferred from "effect/Deferred";
27 import * as Effect from "effect/Effect";
28 import * as Exit from "effect/Exit";
29 import * as Fiber from "effect/Fiber";
30 import * as Latch from "effect/Latch";
31 import * as Layer from "effect/Layer";
32 import * as Option from "effect/Option";
33 import * as Queue from "effect/Queue";
34 import * as Schema from "effect/Schema";
35 import * as Stream from "effect/Stream";
36 import * as SubscriptionRef from "effect/SubscriptionRef";
37 import * as TestClock from "effect/testing/TestClock";
38 import type { HttpClient } from "effect/http";
39 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
40
41 import {
42 AVAILABLE_CONNECTION_STATE,
43 ConnectionBlockedError,
44 ConnectionTransientError,
45 PrimaryConnectionTarget,
46 type PreparedConnection,
47 type SupervisorConnectionState,
48 } from "../connection/model.ts";
49 import * as EnvironmentRegistry from "../connection/registry.ts";
50 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
51 import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
52 import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
53 import type * as RpcSession from "../rpc/session.ts";
54 import { createOrchestrationEnvironmentAtoms } from "./orchestration.ts";
55 import { createReviewEnvironmentAtoms } from "./review.ts";
56 import { createPreviewEnvironmentAtoms } from "./preview.ts";
57 import { createFilesystemEnvironmentAtoms } from "./filesystem.ts";
58 import { createIssueEnvironmentAtoms, createMergedIssueListAtoms } from "./issues.ts";
59 import type { QueryPersistence } from "./queryPersistence.ts";
60 import type { EnvironmentShellState } from "./shell.ts";
61 import { v2Now, v2Project, v2ThreadId, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
62 import { createTerminalEnvironmentAtoms } from "./terminal.ts";
63 import {
64 createAtomCommandScheduler,
65 createEnvironmentQueryAtomFamily,
66 createEnvironmentRpcSubscriptionAtomFamily,
67 selectEnvironmentQueryData,
68 createEnvironmentSubscriptionAtomFamily,
69 createRuntimeCommand,
70 environmentSessionGenerationAtom,
71 executeAtomQuery,
72 type QueryAnswerHandler,
73 } from "./runtime.ts";
74
75 const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({
76 environmentId: EnvironmentId.make("query-environment"),
77 label: "Query environment",
78 httpBaseUrl: "https://query.example.test",
79 wsBaseUrl: "wss://query.example.test",
80 });
81
82 const decodeNumber = Schema.decodeUnknownEffect(Schema.Number);
83
84 const QUERY_RPC_SESSION = {} as RpcSession.RpcSession;
85
86 class TestQueryError extends Schema.TaggedError<TestQueryError>()("TestQueryError", {
87 message: Schema.String,
88 }) {}
89
90 const OFFLINE_QUERY_FAILURE = new ConnectionTransientError({
91 reason: "transport",
92 detail: "Relay is unavailable.",
93 });
94
95 const BLOCKED_QUERY_FAILURE = new ConnectionBlockedError({
96 reason: "permission",
97 detail: "Access denied.",
98 });
99
100 function queryConnectionState(
101 overrides: Partial<SupervisorConnectionState> = {},
102 ): SupervisorConnectionState {
103 return {
104 ...AVAILABLE_CONNECTION_STATE,
105 desired: true,
106 network: "online",
107 phase: "connected",
108 attempt: 1,
109 generation: 1,
110 ...overrides,
111 };
112 }
113
114 const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness")(function* <A, E>(
115 execute: Effect.Effect<A, E>,
116 {
117 refreshTrigger,
118 idleTtlMs,
119 persistence,
120 initialState,
121 rpcSession,
122 isFinal,
123 onAnswer,
124 }: {
125 readonly refreshTrigger?: Atom.Atom<unknown>;
126 readonly onAnswer?: QueryAnswerHandler<undefined, A>;
127 readonly isFinal?: (value: A) => boolean;
128 readonly idleTtlMs?: number;
129 readonly persistence?: QueryPersistence<A>;
130 readonly initialState?: SupervisorConnectionState;
131 readonly rpcSession?: RpcSession.RpcSession;
132 } = {},
133 ) {
134 const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());
135 const supervisorSession = yield* SubscriptionRef.make(
136 Option.some(rpcSession ?? QUERY_RPC_SESSION),
137 );
138 const streamGeneration = yield* SubscriptionRef.make(0);
139 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
140 target: QUERY_ENVIRONMENT,
141 state: supervisorState,
142 session: supervisorSession,
143 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
144 connect: Effect.void,
145 disconnect: Effect.void,
146 retryNow: Effect.void,
147 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
148 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_environmentId, effect) =>
149 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
150 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
151 _environmentId,
152 stream,
153 ) =>
154 SubscriptionRef.changes(streamGeneration).pipe(
155 Stream.switchMap(() =>
156 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
157 ),
158 );
159 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
160 run,
161 followStream,
162 stateChanges: () => SubscriptionRef.changes(supervisorState),
163 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
164 const runtime = Atom.runtime(
165 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
166 );
167 const family = createEnvironmentQueryAtomFamily(runtime, {
168 label: "test.environment-query",
169 staleTimeMs: 60_000,
170 ...(persistence === undefined ? {} : { persistence }),
171 execute: () => execute,
172 ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }),
173 ...(idleTtlMs === undefined ? {} : { idleTtlMs }),
174 ...(isFinal === undefined ? {} : { isFinal }),
175 ...(onAnswer === undefined ? {} : { onAnswer }),
176 });
177
178 return {
179 runtime,
180 family,
181 atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),
182 supervisorSession,
183 supervisorState,
184 streamGeneration,
185 };
186 });
187
188 /**
189 * `getResult` resumes from inside the query's listener, so it only unsubscribes
190 * once the reader yields.
191 */
192 const readEnvironmentQuery = <A, E>(
193 registry: AtomRegistry.AtomRegistry,
194 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
195 ) =>
196 AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe(
197 Effect.tap(() => Effect.yieldNow),
198 );
199
200 const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function* <A>(
201 atom: Atom.Atom<A>,
202 ) {
203 const registry = AtomRegistry.make();
204 const unmount = registry.mount(atom);
205 yield* Effect.addFinalizer(() =>
206 Effect.sync(() => {
207 unmount();
208 registry.dispose();
209 }),
210 );
211 return registry;
212 });
213
214 it.effect("keeps complete review metadata visible while a refresh is held", () =>
215 Effect.gen(function* () {
216 const started = yield* Deferred.make<void>();
217 const release = yield* Deferred.make<void>();
218 let fullReads = 0;
219 const rpcSession = {
220 client: {
221 [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) =>
222 Effect.gen(function* () {
223 if (!input.trackedOnly && ++fullReads > 1) {
224 yield* Deferred.succeed(started, undefined);
225 yield* Deferred.await(release);
226 }
227 return {
228 cwd: input.cwd,
229 generatedAt: DateTime.makeUnsafe(0),
230 ...(input.trackedOnly ? { incomplete: true } : {}),
231 sources: [
232 {
233 id: "working-tree",
234 kind: "working-tree" as const,
235 title: "Uncommitted",
236 baseRef: "HEAD",
237 headRef: null,
238 diff: "",
239 diffHash: String(fullReads),
240 truncated: false,
241 patchesDeferred: true,
242 files: (input.trackedOnly ? ["tracked"] : ["tracked", "untracked"]).map(
243 (path) => ({ path, previousPath: null, additions: 1, deletions: 0 }),
244 ),
245 },
246 ],
247 };
248 }),
249 },
250 } as unknown as RpcSession.RpcSession;
251 const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession });
252 const atom = createReviewEnvironmentAtoms(harness.runtime).diffPreview({
253 environmentId: QUERY_ENVIRONMENT.environmentId,
254 input: { cwd: "/project", sourceKind: "working-tree", metadataOnly: true },
255 });
256 const registry = yield* mountEnvironmentQuery(atom);
257 expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.files).toHaveLength(2);
258 registry.refresh(atom);
259 yield* Deferred.await(started);
260 yield* Effect.sync(() => {
261 const value = AsyncResult.getOrElse(registry.get(atom), () => null);
262 expect(value?.incomplete).not.toBe(true);
263 expect(value?.sources[0]!.files).toHaveLength(2);
264 }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
265 expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.diffHash).toBe("2");
266 }),
267 );
268
269 it.effect("keeps manual Issues refresh intent through an overlapping write", () =>
270 Effect.gen(function* () {
271 const requests = yield* Queue.unbounded<IssueListInput>();
272 const release = yield* Deferred.make<void>();
273 const answer: IssueListResult = {
274 viewers: {},
275 trackers: [],
276 entries: [],
277 errors: [],
278 nextCursors: {},
279 };
280 const rpcSession = {
281 client: {
282 [WS_METHODS.issuesList]: (input: IssueListInput) =>
283 Queue.offer(requests, input).pipe(
284 Effect.andThen(input.refresh ? Deferred.await(release) : Effect.void),
285 Effect.as(answer),
286 ),
287 },
288 } as unknown as RpcSession.RpcSession;
289 const { runtime } = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession });
290 const issues = createIssueEnvironmentAtoms(runtime);
291 const listings = createMergedIssueListAtoms(issues, String);
292 const target = {
293 environmentId: QUERY_ENVIRONMENT.environmentId,
294 input: { state: "all" },
295 } as const;
296 const registry = yield* mountEnvironmentQuery(listings.atom([target]));
297 expect(yield* Queue.take(requests)).toEqual({ state: "all" });
298 yield* readEnvironmentQuery(registry, issues.list(target));
299
300 listings.refresh(registry, [target], "manual");
301 expect(yield* Queue.take(requests)).toEqual({ state: "all", refresh: true });
302
303 listings.refreshEnvironment(registry, target.environmentId);
304 expect(yield* Queue.take(requests)).toEqual({ state: "all", refresh: true });
305
306 yield* Deferred.succeed(release, undefined);
307 yield* readEnvironmentQuery(registry, issues.list(target));
308 listings.refreshEnvironment(registry, target.environmentId);
309 expect(yield* Queue.take(requests)).toEqual({ state: "all" });
310 }),
311 );
312
313 describe("preview event subscriptions", () => {
314 it.effect("delivers every open and close when RPC events arrive in batches", () =>
315 Effect.gen(function* () {
316 const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({
317 type: "opened",
318 threadId,
319 tabId: `tab-${index}`,
320 serverEpoch: "epoch-1",
321 revision: index + 1,
322 createdAt: "2026-10-02T00:00:00.000Z",
323 snapshot: {
324 threadId,
325 tabId: `tab-${index}`,
326 navStatus: { _tag: "Idle" },
327 canGoBack: false,
328 canGoForward: false,
329 updatedAt: "2026-10-02T00:00:00.000Z",
330 },
331 }));
332 const closed: PreviewEvent[] = opened.map((event, index) => ({
333 type: "closed",
334 threadId: event.threadId,
335 tabId: event.tabId,
336 serverEpoch: event.serverEpoch,
337 revision: opened.length + index + 1,
338 createdAt: event.createdAt,
339 }));
340 const releaseEvents = yield* Deferred.make<void>();
341 // Each iterable is one RPC chunk; separate emissions would hide lost events.
342 const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe(
343 Stream.flatMap(() =>
344 Stream.fromIterable(opened).pipe(
345 Stream.concat(Stream.fromIterable(closed)),
346 Stream.concat(Stream.never),
347 ),
348 ),
349 );
350 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
351 rpcSession: {
352 client: { [WS_METHODS.subscribePreviewEvents]: () => stream },
353 } as unknown as RpcSession.RpcSession,
354 });
355 const atom = createPreviewEnvironmentAtoms(harness.runtime).events({
356 environmentId: QUERY_ENVIRONMENT.environmentId,
357 input: {},
358 });
359 const registry = AtomRegistry.make();
360 const observed: PreviewEvent[] = [];
361 const sawLast = yield* Deferred.make<void>();
362 const unsubscribe = registry.subscribe(
363 atom,
364 (result) => {
365 if (!AsyncResult.isSuccess(result)) return;
366 observed.push(result.value);
367 if (result.value === closed[closed.length - 1]) {
368 Deferred.doneUnsafe(sawLast, Exit.void);
369 }
370 },
371 { immediate: true },
372 );
373 yield* Effect.addFinalizer(() =>
374 Effect.sync(() => {
375 unsubscribe();
376 registry.dispose();
377 }),
378 );
379
380 yield* Deferred.succeed(releaseEvents, undefined);
381 yield* Deferred.await(sawLast);
382 expect(observed).toEqual([...opened, ...closed]);
383 }),
384 );
385 });
386
387 describe("finite environment subscription lifecycle", () => {
388 it.effect(
389 "exposes early values and settles on the terminal value without waiting for a reconnect",
390 () =>
391 Effect.gen(function* () {
392 const releaseFinal = yield* Deferred.make<void>();
393 const sawEarly = yield* Deferred.make<void>();
394 const sawFinal = yield* Deferred.make<void>();
395 const closed = yield* Deferred.make<void>();
396 const stream = Stream.concat(
397 Stream.succeed({ complete: false, count: 1 }),
398 Stream.fromEffect(
399 Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })),
400 ),
401 ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined)));
402 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
403 followStream: (_environmentId: EnvironmentId, source: typeof stream) =>
404 Stream.concat(source, Stream.never),
405 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
406 const runtime = Atom.runtime(
407 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
408 );
409 const family = createEnvironmentSubscriptionAtomFamily(runtime, {
410 label: "test.finite-subscription",
411 subscribe: () => stream,
412 completeWhen: (value) => value.complete,
413 idleTtlMs: 0,
414 });
415 const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });
416 const registry = AtomRegistry.make();
417 const observed: Array<
418 AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown>
419 > = [];
420 const unsubscribe = registry.subscribe(
421 atom,
422 (result) => {
423 observed.push(result);
424 if (AsyncResult.isSuccess(result)) {
425 if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void);
426 if (result.value.complete && !result.waiting)
427 Deferred.doneUnsafe(sawFinal, Exit.void);
428 }
429 },
430 { immediate: true },
431 );
432 yield* Effect.addFinalizer(() =>
433 Effect.sync(() => {
434 unsubscribe();
435 registry.dispose();
436 }),
437 );
438 yield* Deferred.await(sawEarly);
439 const early = registry.get(atom);
440 expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1);
441 expect(early.waiting).toBe(true);
442 yield* Deferred.succeed(releaseFinal, undefined);
443 yield* Deferred.await(sawFinal);
444 yield* Deferred.await(closed);
445 const final = registry.get(atom);
446 expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123);
447 expect(final.waiting).toBe(false);
448 expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false);
449 }),
450 );
451 it.effect(
452 "surfaces a decode defect from a finite RPC subscription instead of resubscribing",
453 () =>
454 Effect.scoped(
455 Effect.gen(function* () {
456 const firstSubscribed = yield* Deferred.make<void>();
457 const resubscribed = yield* Deferred.make<void>();
458 const surfaced = yield* Deferred.make<Cause.Cause<unknown>>();
459 let subscriptions = 0;
460 // Mirrors RpcClient, which decodes each chunk with `Effect.orDie`.
461 const decodeDefect = decodeNumber("not a number").pipe(Effect.orDie);
462 const client = {
463 [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: () => {
464 subscriptions += 1;
465 Deferred.doneUnsafe(subscriptions === 1 ? firstSubscribed : resubscribed, Exit.void);
466 return Stream.fromEffect(decodeDefect).pipe(Stream.drain);
467 },
468 } as unknown as WsRpcProtocolClient;
469 const rpcSession = {
470 client,
471 initialConfig: Effect.never,
472 subscribeServerConfig: () => Stream.never,
473 ready: Effect.void,
474 probe: Effect.void,
475 closed: Effect.never,
476 } as unknown as RpcSession.RpcSession;
477 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
478 target: QUERY_ENVIRONMENT,
479 state: yield* SubscriptionRef.make(queryConnectionState()),
480 session: yield* SubscriptionRef.make(Option.some(rpcSession)),
481 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
482 connect: Effect.void,
483 disconnect: Effect.void,
484 retryNow: Effect.void,
485 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
486 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
487 followStream: (_environmentId: EnvironmentId, stream: Stream.Stream<unknown>) =>
488 Stream.provideService(
489 stream,
490 EnvironmentSupervisor.EnvironmentSupervisor,
491 supervisor,
492 ),
493 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
494 // Atoms run their own fibers; share the test clock so a pending retry is driven by it.
495 const runtime = Atom.runtime(
496 Layer.mergeAll(
497 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
498 Layer.succeed(Clock.Clock, yield* Clock.Clock),
499 ),
500 );
501 // Same options as the progressive thread find in orchestration.ts.
502 const family = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
503 label: "test.finite-rpc-subscription",
504 tag: ORCHESTRATION_V2_WS_METHODS.searchThreadStream,
505 completeWhen: (result) => result.complete !== false,
506 idleTtlMs: 0,
507 });
508 const atom = family({
509 environmentId: QUERY_ENVIRONMENT.environmentId,
510 input: {} as never,
511 });
512 const registry = AtomRegistry.make();
513 const unsubscribe = registry.subscribe(
514 atom,
515 (result) => {
516 if (AsyncResult.isFailure(result))
517 Deferred.doneUnsafe(surfaced, Exit.succeed(result.cause));
518 },
519 { immediate: true },
520 );
521 yield* Effect.addFinalizer(() =>
522 Effect.sync(() => {
523 unsubscribe();
524 registry.dispose();
525 }),
526 );
527 yield* Deferred.await(firstSubscribed);
528 // Lets any same-session retry run, so its resubscription can win the race below.
529 yield* TestClock.adjust("1 minute");
530 const outcome = yield* Effect.raceFirst(
531 Deferred.await(surfaced).pipe(
532 Effect.map((cause) => ({ _tag: "surfaced", cause }) as const),
533 ),
534 Deferred.await(resubscribed).pipe(Effect.as({ _tag: "resubscribed" } as const)),
535 );
536
537 expect(
538 outcome._tag,
539 "finite subscription resubscribed after a decode defect instead of failing its consumer",
540 ).toBe("surfaced");
541 if (outcome._tag === "surfaced") {
542 expect(Cause.hasDies(outcome.cause)).toBe(true);
543 expect(Schema.isSchemaError(Cause.squash(outcome.cause))).toBe(true);
544 }
545 expect(subscriptions).toBe(1);
546 }),
547 ),
548 );
549 it.effect.each([
550 { completedTtlMs: undefined, subscriptions: 2 },
551 { completedTtlMs: 60_000, subscriptions: 1 },
552 ])(
553 "reopening a completed subscription subscribes $subscriptions time(s) with completedTtlMs $completedTtlMs",
554 ({ completedTtlMs, subscriptions }) =>
555 Effect.gen(function* () {
556 let subscribed = 0;
557 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
558 followStream: (_environmentId: EnvironmentId, source: Stream.Stream<unknown>) => source,
559 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
560 const runtime = Atom.runtime(
561 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
562 );
563 const family = createEnvironmentSubscriptionAtomFamily(runtime, {
564 label: "test.completed-subscription",
565 subscribe: () =>
566 Stream.suspend(() => {
567 subscribed += 1;
568 return Stream.make({ complete: false }, { complete: true });
569 }),
570 completeWhen: (value) => value.complete,
571 idleTtlMs: 0,
572 ...(completedTtlMs === undefined ? {} : { completedTtlMs }),
573 });
574 const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });
575 // Flushed after each close: idle removals have run by the time a user reopens a row.
576 const scheduled: Array<() => void> = [];
577 const registry = AtomRegistry.make({
578 scheduleTask: (task) => {
579 scheduled.push(task);
580 return () => undefined;
581 },
582 });
583 const open = Effect.gen(function* () {
584 const settled = yield* Deferred.make<boolean>();
585 const unsubscribe = registry.subscribe(
586 atom,
587 (result) => {
588 if (AsyncResult.isSuccess(result) && !result.waiting) {
589 Deferred.doneUnsafe(settled, Exit.succeed(result.value.complete));
590 }
591 },
592 { immediate: true },
593 );
594 const complete = yield* Deferred.await(settled);
595 unsubscribe();
596 for (const task of scheduled.splice(0)) task();
597 return complete;
598 });
599
600 expect(yield* open).toBe(true);
601 expect(yield* open).toBe(true);
602 expect(subscribed).toBe(subscriptions);
603 registry.dispose();
604 }),
605 );
606 });
607
608 describe("environment query lifecycle", () => {
609 it.effect(
610 "terminal metadata retains known sessions until a new snapshot and keeps the manager identity",
611 () =>
612 Effect.gen(function* () {
613 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
614 const started = yield* Queue.unbounded<void>();
615 const events = yield* Queue.unbounded<TerminalMetadataStreamEvent>();
616 const receivedCheckout = yield* Deferred.make<void>();
617 const receivedEmpty = yield* Deferred.make<void>();
618 const checkout: TerminalSummary = {
619 threadId: "thread-1",
620 terminalId: "terminal-1",
621 cwd: "/repo/root/packages/app",
622 worktreePath: null,
623 status: "running",
624 pid: 123,
625 exitCode: null,
626 exitSignal: null,
627 hasRunningSubprocess: false,
628 label: "Terminal 1",
629 updatedAt: "2026-04-01T00:00:00.000Z",
630 };
631 const client = {
632 [WS_METHODS.subscribeTerminalMetadata]: () =>
633 Stream.fromEffect(Queue.offer(started, undefined)).pipe(
634 Stream.drain,
635 Stream.concat(Stream.fromQueue(events)),
636 ),
637 } as unknown as RpcSession.RpcSession["client"];
638 const session = { ...QUERY_RPC_SESSION, client };
639 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session));
640 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
641 const target = { environmentId: QUERY_ENVIRONMENT.environmentId, input: null };
642 const atom = atoms.metadata(target);
643 const feed = atoms.metadataFeed(target);
644 const registry = AtomRegistry.make();
645 const observed: Array<ReadonlyArray<TerminalSummary>> = [];
646 const unsubscribe = registry.subscribe(
647 atom,
648 (result) => {
649 if (!AsyncResult.isSuccess(result)) return;
650 observed.push(result.value);
651 if (result.value.length > 0) Deferred.doneUnsafe(receivedCheckout, Exit.void);
652 else Deferred.doneUnsafe(receivedEmpty, Exit.void);
653 },
654 { immediate: true },
655 );
656 yield* Effect.addFinalizer(() =>
657 Effect.sync(() => {
658 unsubscribe();
659 registry.dispose();
660 }),
661 );
662
663 yield* Queue.take(started);
664 expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull();
665 expect(observed).toEqual([]);
666
667 yield* Queue.offer(events, {
668 type: "snapshot",
669 terminals: [checkout],
670 managerId: "manager-1",
671 });
672 yield* Deferred.await(receivedCheckout);
673 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
674 const initialSnapshotId = selectEnvironmentQueryData(registry.get(feed))?.snapshotId;
675 expect(initialSnapshotId).toBe("manager-1");
676
677 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session }));
678 yield* Queue.take(started);
679 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
680
681 yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
682 yield* Queue.take(started);
683 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
684
685 yield* Queue.offer(events, { type: "snapshot", terminals: [], managerId: "manager-1" });
686 yield* Deferred.await(receivedEmpty);
687 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]);
688 expect(selectEnvironmentQueryData(registry.get(feed))?.snapshotId).toBe(initialSnapshotId);
689 }),
690 );
691
692 it.effect("terminal attach resubscribes with resume only after the stream replied", () =>
693 Effect.gen(function* () {
694 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
695 const inputs = yield* Queue.unbounded<TerminalAttachInput>();
696 const events = yield* Queue.unbounded<TerminalAttachStreamEvent>();
697 const received = yield* Deferred.make<void>();
698 const client = {
699 [WS_METHODS.terminalAttach]: (input: TerminalAttachInput) =>
700 Stream.fromEffect(Queue.offer(inputs, input)).pipe(
701 Stream.drain,
702 Stream.concat(Stream.fromQueue(events)),
703 ),
704 } as unknown as RpcSession.RpcSession["client"];
705 const firstSession = { ...QUERY_RPC_SESSION, client };
706 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(firstSession));
707 const input = {
708 threadId: "thread-1",
709 terminalId: "terminal-1",
710 cwd: "/tmp/project",
711 restartIfNotRunning: true,
712 };
713 const sent = { ...input, maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES };
714 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
715 const registry = AtomRegistry.make();
716 const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input });
717 const unmount = registry.subscribe(
718 atom,
719 (result) => {
720 if (AsyncResult.isSuccess(result) && result.value.version > 0) {
721 Deferred.doneUnsafe(received, Exit.void);
722 }
723 },
724 { immediate: true },
725 );
726 yield* Effect.addFinalizer(() =>
727 Effect.sync(() => {
728 unmount();
729 registry.dispose();
730 }),
731 );
732
733 expect(yield* Queue.take(inputs)).toEqual(sent);
734 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
735 expect(yield* Queue.take(inputs)).toEqual(sent);
736 yield* Queue.offer(events, {
737 type: "closed",
738 threadId: input.threadId,
739 terminalId: input.terminalId,
740 });
741 yield* Deferred.await(received);
742
743 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
744 expect(yield* Queue.take(inputs)).toEqual({ ...sent, resume: true });
745 // Catalog replacements rerun the same stream through followStream's switchMap.
746 yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
747 expect(yield* Queue.take(inputs)).toEqual({ ...sent, resume: true });
748
749 unmount();
750 registry.dispose();
751 const remountedRegistry = AtomRegistry.make();
752 const remount = remountedRegistry.subscribe(atom, () => {}, { immediate: true });
753 yield* Effect.addFinalizer(() =>
754 Effect.sync(() => {
755 remount();
756 remountedRegistry.dispose();
757 }),
758 );
759 expect(yield* Queue.take(inputs)).toEqual(sent);
760 }),
761 );
762
763 // The server sizes a shared PTY to every attached viewer, so a lingering attach pins its grid.
764 it.effect("terminal attach detaches as soon as its last viewer leaves", () =>
765 Effect.gen(function* () {
766 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
767 const attached = yield* Deferred.make<void>();
768 const detached = yield* Deferred.make<void>();
769 const client = {
770 [WS_METHODS.terminalAttach]: () =>
771 Stream.fromEffect(Deferred.succeed(attached, undefined)).pipe(
772 Stream.drain,
773 Stream.concat(Stream.never),
774 Stream.ensuring(Deferred.succeed(detached, undefined)),
775 ),
776 } as unknown as RpcSession.RpcSession["client"];
777 yield* SubscriptionRef.set(
778 harness.supervisorSession,
779 Option.some({ ...QUERY_RPC_SESSION, client }),
780 );
781 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
782 const registry = AtomRegistry.make();
783 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
784 const unsubscribe = registry.subscribe(
785 atoms.attach({
786 environmentId: QUERY_ENVIRONMENT.environmentId,
787 input: { threadId: "thread-1", terminalId: "terminal-1", cwd: "/tmp/project" },
788 }),
789 () => {},
790 { immediate: true },
791 );
792 yield* Deferred.await(attached);
793
794 unsubscribe();
795 yield* Deferred.await(detached);
796 }),
797 );
798
799 it.effect(
800 "hides a session replacement, reports the relay backoff, and recovers on reconnect",
801 () =>
802 Effect.gen(function* () {
803 const firstStarted = Latch.makeUnsafe();
804 const failFirst = Latch.makeUnsafe();
805 const firstSettled = Latch.makeUnsafe();
806 const unavailable = new EnvironmentRpcUnavailableError({
807 environmentId: QUERY_ENVIRONMENT.environmentId,
808 message: "Query environment is not connected.",
809 });
810 let executions = 0;
811 const execute = Effect.suspend(() => {
812 executions += 1;
813 if (executions > 1) {
814 return Effect.succeed("recovered");
815 }
816 firstStarted.openUnsafe();
817 return failFirst.await.pipe(
818 Effect.andThen(Effect.fail(unavailable)),
819 Effect.ensuring(
820 Effect.sync(() => {
821 firstSettled.openUnsafe();
822 }),
823 ),
824 );
825 });
826 const harness = yield* makeEnvironmentQueryHarness(execute);
827 const registry = AtomRegistry.make();
828 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
829 const unsubscribe = registry.subscribe(
830 harness.atom,
831 (result) => {
832 observed.push(result);
833 },
834 { immediate: true },
835 );
836 yield* Effect.addFinalizer(() =>
837 Effect.sync(() => {
838 unsubscribe();
839 registry.dispose();
840 }),
841 );
842
843 yield* firstStarted.await;
844 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
845 yield* Effect.yieldNow;
846 failFirst.openUnsafe();
847 yield* firstSettled.await;
848 yield* Effect.yieldNow;
849
850 expect(observed.some(AsyncResult.isFailure)).toBe(false);
851
852 yield* SubscriptionRef.set(
853 harness.supervisorState,
854 queryConnectionState({ phase: "connecting", stage: "preparing" }),
855 );
856 yield* Effect.yieldNow;
857 const relayFailure = new ConnectionTransientError({
858 reason: "transport",
859 detail: "Relay session is reconnecting.",
860 });
861 yield* SubscriptionRef.set(
862 harness.supervisorState,
863 queryConnectionState({
864 phase: "backoff",
865 stage: null,
866 lastFailure: relayFailure,
867 retryAt: 1,
868 }),
869 );
870 yield* Effect.yieldNow;
871 // The query has never answered, so it reports why the environment is retrying.
872 const backingOff = registry.get(harness.atom);
873 expect(backingOff.waiting).toBe(false);
874 expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe(
875 relayFailure,
876 );
877
878 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
879 yield* SubscriptionRef.set(
880 harness.supervisorState,
881 queryConnectionState({ generation: 2 }),
882 );
883 yield* Effect.yieldNow;
884 expect(
885 yield* AtomRegistry.getResult(registry, harness.atom, {
886 suspendOnWaiting: true,
887 }),
888 ).toBe("recovered");
889 }),
890 );
891
892 it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
893 Effect.gen(function* () {
894 const firstStarted = Latch.makeUnsafe();
895 const failFirst = Latch.makeUnsafe();
896 const firstSettled = Latch.makeUnsafe();
897 let executions = 0;
898 const execute = Effect.suspend(() => {
899 executions += 1;
900 if (executions > 1) {
901 return Effect.succeed("recovered");
902 }
903 firstStarted.openUnsafe();
904 return failFirst.await.pipe(
905 Effect.andThen(
906 Effect.fail(
907 new EnvironmentRpcUnavailableError({
908 environmentId: QUERY_ENVIRONMENT.environmentId,
909 message: "Query environment is not connected.",
910 }),
911 ),
912 ),
913 Effect.ensuring(
914 Effect.sync(() => {
915 firstSettled.openUnsafe();
916 }),
917 ),
918 );
919 });
920 const harness = yield* makeEnvironmentQueryHarness(execute);
921 const registry = AtomRegistry.make();
922 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
923 const unsubscribe = registry.subscribe(
924 harness.atom,
925 (result) => {
926 observed.push(result);
927 },
928 { immediate: true },
929 );
930 yield* Effect.addFinalizer(() =>
931 Effect.sync(() => {
932 unsubscribe();
933 registry.dispose();
934 }),
935 );
936
937 yield* firstStarted.await;
938 // No yield before the failure: the request finds its session gone
939 // before the atom has processed the session change.
940 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
941 failFirst.openUnsafe();
942 yield* firstSettled.await;
943 yield* Effect.yieldNow;
944
945 expect(observed.some(AsyncResult.isFailure)).toBe(false);
946
947 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
948 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
949 expect(
950 yield* AtomRegistry.getResult(registry, harness.atom, {
951 suspendOnWaiting: true,
952 }),
953 ).toBe("recovered");
954 expect(observed.some(AsyncResult.isFailure)).toBe(false);
955 }),
956 );
957
958 it.effect("fails a query that reports unavailable while its session is still live", () =>
959 Effect.gen(function* () {
960 const unavailable = new EnvironmentRpcUnavailableError({
961 environmentId: QUERY_ENVIRONMENT.environmentId,
962 message: "The environment did not respond to the request.",
963 });
964 const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
965 const registry = yield* mountEnvironmentQuery(harness.atom);
966
967 const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
968 suspendOnWaiting: true,
969 }).pipe(Effect.exit);
970
971 expect(exit).toStrictEqual(Exit.fail(unavailable));
972 }),
973 );
974
975 it.effect.each([
976 {
977 condition: "after a manual disconnect",
978 state: queryConnectionState({
979 desired: false,
980 phase: "available",
981 stage: null,
982 attempt: 0,
983 }),
984 expectedFailure: null,
985 },
986 {
987 condition: "while the environment is offline",
988 state: queryConnectionState({
989 network: "offline",
990 phase: "offline",
991 stage: null,
992 lastFailure: OFFLINE_QUERY_FAILURE,
993 }),
994 expectedFailure: OFFLINE_QUERY_FAILURE,
995 },
996 {
997 condition: "when connection recovery is blocked",
998 state: queryConnectionState({
999 phase: "blocked",
1000 stage: null,
1001 lastFailure: BLOCKED_QUERY_FAILURE,
1002 }),
1003 expectedFailure: BLOCKED_QUERY_FAILURE,
1004 },
1005 ] as const)("settles as unavailable $condition", ({ state, expectedFailure }) =>
1006 Effect.gen(function* () {
1007 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
1008 const registry = yield* mountEnvironmentQuery(harness.atom);
1009
1010 expect(
1011 yield* AtomRegistry.getResult(registry, harness.atom, {
1012 suspendOnWaiting: true,
1013 }),
1014 ).toBe("connected");
1015
1016 yield* SubscriptionRef.set(harness.supervisorState, state);
1017 yield* Effect.yieldNow;
1018
1019 const result = registry.get(harness.atom);
1020 expect(AsyncResult.isFailure(result)).toBe(true);
1021 expect(result.waiting).toBe(false);
1022 if (AsyncResult.isFailure(result) && expectedFailure !== null) {
1023 expect(Cause.squash(result.cause)).toBe(expectedFailure);
1024 }
1025 }),
1026 );
1027
1028 it.effect.each([
1029 { phase: "backoff", stage: null, retryAt: 1 },
1030 { phase: "connecting", stage: "opening", retryAt: null },
1031 ] as const)(
1032 "settles a query it never answered while its environment retries ($phase)",
1033 (retrying) =>
1034 Effect.gen(function* () {
1035 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
1036 initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }),
1037 });
1038 const registry = yield* mountEnvironmentQuery(harness.atom);
1039 yield* Effect.yieldNow;
1040
1041 const result = registry.get(harness.atom);
1042 expect(result.waiting).toBe(false);
1043 expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe(
1044 OFFLINE_QUERY_FAILURE,
1045 );
1046
1047 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1048 yield* Effect.yieldNow;
1049 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected");
1050 }),
1051 );
1052
1053 it.effect("a refresh started on a new session generation answers from that session", () =>
1054 Effect.gen(function* () {
1055 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
1056 initialState: queryConnectionState({
1057 phase: "backoff",
1058 stage: null,
1059 lastFailure: OFFLINE_QUERY_FAILURE,
1060 retryAt: 1,
1061 }),
1062 });
1063 const registry = yield* mountEnvironmentQuery(harness.atom);
1064 // Callers hold the failure a read got while the environment was retrying.
1065 const failed = yield* Effect.promise(() =>
1066 executeAtomQuery(registry, harness.atom, { reportFailure: false }),
1067 );
1068 expect(AsyncResult.isFailure(failed)).toBe(true);
1069
1070 const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
1071 const sessionGeneration = environmentSessionGenerationAtom(
1072 harness.runtime,
1073 QUERY_ENVIRONMENT.environmentId,
1074 );
1075 const unmount = registry.mount(sessionGeneration);
1076 const unsubscribe = registry.subscribe(sessionGeneration, () => {
1077 void executeAtomQuery(registry, harness.atom, {
1078 refresh: true,
1079 reportFailure: false,
1080 }).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
1081 });
1082 yield* Effect.addFinalizer(() =>
1083 Effect.sync(() => {
1084 unsubscribe();
1085 unmount();
1086 }),
1087 );
1088 yield* Effect.yieldNow;
1089
1090 yield* SubscriptionRef.set(
1091 harness.supervisorSession,
1092 Option.some({} as RpcSession.RpcSession),
1093 );
1094 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
1095 expect(yield* Deferred.await(answered)).toMatchObject({
1096 _tag: "Success",
1097 value: "connected",
1098 });
1099 }),
1100 );
1101
1102 it.effect("keeps a genuine query failure settled while reconnecting", () =>
1103 Effect.gen(function* () {
1104 const expectedFailure = new TestQueryError({ message: "Query failed." });
1105 const firstStarted = Latch.makeUnsafe();
1106 const failFirst = Latch.makeUnsafe();
1107 const refreshStarted = Latch.makeUnsafe();
1108 const finishRefresh = Latch.makeUnsafe();
1109 let executions = 0;
1110 const execute = Effect.suspend(() => {
1111 executions += 1;
1112 if (executions === 1) {
1113 firstStarted.openUnsafe();
1114 return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
1115 }
1116 refreshStarted.openUnsafe();
1117 return finishRefresh.await.pipe(Effect.as("recovered"));
1118 });
1119 const harness = yield* makeEnvironmentQueryHarness(execute);
1120 const registry = yield* mountEnvironmentQuery(harness.atom);
1121
1122 yield* firstStarted.await;
1123 failFirst.openUnsafe();
1124 const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
1125 suspendOnWaiting: true,
1126 }).pipe(Effect.exit);
1127 expect(Exit.isFailure(initial)).toBe(true);
1128 if (Exit.isFailure(initial)) {
1129 expect(Cause.squash(initial.cause)).toBe(expectedFailure);
1130 }
1131
1132 yield* SubscriptionRef.set(
1133 harness.supervisorState,
1134 queryConnectionState({ phase: "connecting", stage: "opening" }),
1135 );
1136 yield* Effect.yieldNow;
1137
1138 const refreshing = registry.get(harness.atom);
1139 expect(AsyncResult.isFailure(refreshing)).toBe(true);
1140 expect(refreshing.waiting).toBe(true);
1141 if (AsyncResult.isFailure(refreshing)) {
1142 expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
1143 }
1144
1145 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
1146 yield* refreshStarted.await;
1147 finishRefresh.openUnsafe();
1148 expect(
1149 yield* AtomRegistry.getResult(registry, harness.atom, {
1150 suspendOnWaiting: true,
1151 }),
1152 ).toBe("recovered");
1153 }),
1154 );
1155
1156 it.effect("retains the last successful value while reconnecting", () =>
1157 Effect.gen(function* () {
1158 const refreshStarted = Latch.makeUnsafe();
1159 const finishRefresh = Latch.makeUnsafe();
1160 let executions = 0;
1161 const execute = Effect.suspend(() => {
1162 executions += 1;
1163 if (executions === 1) {
1164 return Effect.succeed("cached");
1165 }
1166 refreshStarted.openUnsafe();
1167 return finishRefresh.await.pipe(Effect.as("updated"));
1168 });
1169 const harness = yield* makeEnvironmentQueryHarness(execute);
1170 const registry = yield* mountEnvironmentQuery(harness.atom);
1171
1172 expect(
1173 yield* AtomRegistry.getResult(registry, harness.atom, {
1174 suspendOnWaiting: true,
1175 }),
1176 ).toBe("cached");
1177
1178 yield* SubscriptionRef.set(
1179 harness.supervisorState,
1180 queryConnectionState({ phase: "connecting", stage: "opening" }),
1181 );
1182 yield* Effect.yieldNow;
1183 expect(registry.get(harness.atom)).toMatchObject({
1184 _tag: "Success",
1185 value: "cached",
1186 waiting: true,
1187 });
1188
1189 yield* SubscriptionRef.set(
1190 harness.supervisorState,
1191 queryConnectionState({
1192 phase: "backoff",
1193 stage: null,
1194 lastFailure: new ConnectionTransientError({
1195 reason: "transport",
1196 detail: "Retrying.",
1197 }),
1198 retryAt: 1,
1199 }),
1200 );
1201 yield* Effect.yieldNow;
1202 expect(registry.get(harness.atom)).toMatchObject({
1203 _tag: "Success",
1204 value: "cached",
1205 waiting: true,
1206 });
1207
1208 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
1209 yield* refreshStarted.await;
1210 expect(registry.get(harness.atom)).toMatchObject({
1211 _tag: "Success",
1212 value: "cached",
1213 waiting: true,
1214 });
1215
1216 finishRefresh.openUnsafe();
1217 expect(
1218 yield* AtomRegistry.getResult(registry, harness.atom, {
1219 suspendOnWaiting: true,
1220 }),
1221 ).toBe("updated");
1222 }),
1223 );
1224
1225 it.effect("filesystem browse lists the directory afresh when a picker reopens it", () =>
1226 Effect.gen(function* () {
1227 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
1228 const entry = (name: string): FilesystemBrowseEntry => ({
1229 name,
1230 fullPath: `/tmp/t3-11476-repro/${name}`,
1231 });
1232 let onDisk = [entry("existing")];
1233 const client = {
1234 [WS_METHODS.filesystemBrowse]: () =>
1235 Effect.sync(() => ({ parentPath: "/tmp/t3-11476-repro/", entries: onDisk })),
1236 } as unknown as RpcSession.RpcSession["client"];
1237 yield* SubscriptionRef.set(
1238 harness.supervisorSession,
1239 Option.some({ ...QUERY_RPC_SESSION, client }),
1240 );
1241 const atom = createFilesystemEnvironmentAtoms(harness.runtime).browse({
1242 environmentId: QUERY_ENVIRONMENT.environmentId,
1243 input: { partialPath: "/tmp/t3-11476-repro/" },
1244 });
1245 const registry = AtomRegistry.make();
1246 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1247 // Stale-while-revalidate refreshes from a task on the registry scheduler;
1248 // queue behind it so the read sees the revalidation instead of racing it.
1249 const afterScheduledTasks = Effect.callback<void>((resume) => {
1250 registry.schedulerAsync.makeDispatcher().scheduleTask(() => resume(Effect.void), 0);
1251 });
1252 const listNames = afterScheduledTasks.pipe(
1253 Effect.andThen(readEnvironmentQuery(registry, atom)),
1254 Effect.map((result) => result.entries.map((browseEntry) => browseEntry.name)),
1255 );
1256
1257 const closePicker = registry.mount(atom);
1258 expect(yield* listNames).toEqual(["existing"]);
1259 closePicker();
1260 // A closed picker stays closed past the registry's scheduled node
1261 // removal; a remount within the same tick keeps the live node.
1262 yield* afterScheduledTasks;
1263
1264 onDisk = [entry("created-externally"), entry("existing")];
1265 registry.mount(atom);
1266 expect(yield* listNames).toEqual(["created-externally", "existing"]);
1267 }),
1268 );
1269
1270 it.effect("refreshes on its trigger while read, and once on its next read when idle", () =>
1271 Effect.gen(function* () {
1272 let executions = 0;
1273 const trigger = Atom.make(0).pipe(Atom.keepAlive);
1274 const harness = yield* makeEnvironmentQueryHarness(
1275 Effect.sync(() => (executions += 1)),
1276 { refreshTrigger: trigger },
1277 );
1278 const registry = AtomRegistry.make();
1279 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1280 const read = readEnvironmentQuery(registry, harness.atom);
1281
1282 const unmount = registry.mount(harness.atom);
1283 expect(yield* read).toBe(1);
1284 registry.set(trigger, 1);
1285 expect(yield* read).toBe(2);
1286
1287 unmount();
1288 registry.set(trigger, 2);
1289 registry.set(trigger, 3);
1290 expect(executions).toBe(2);
1291
1292 expect(yield* read).toBe(3);
1293 }),
1294 );
1295
1296 it.effect("refetches a stale query on remount while another view keeps the cache live", () =>
1297 Effect.gen(function* () {
1298 let now = 0;
1299 using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1300 let contents = "before edit";
1301 let fetches = 0;
1302 const harness = yield* makeEnvironmentQueryHarness(
1303 Effect.sync(() => {
1304 fetches += 1;
1305 return contents;
1306 }),
1307 );
1308 const registry = AtomRegistry.make();
1309 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1310 const sidebar = harness.family(
1311 { environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined },
1312 "sidebar",
1313 );
1314 registry.mount(sidebar);
1315 const read = readEnvironmentQuery(registry, harness.atom);
1316 const remount = Effect.gen(function* () {
1317 const unmount = registry.mount(harness.atom);
1318 yield* Effect.yieldNow;
1319 const value = yield* read;
1320 unmount();
1321 yield* Effect.yieldNow;
1322 return value;
1323 });
1324
1325 expect(yield* remount).toBe("before edit");
1326 contents = "after edit";
1327
1328 // Inside the harness's 60s stale time: the cached value stands.
1329 now = 30_000;
1330 expect(yield* remount).toBe("before edit");
1331 expect(fetches).toBe(1);
1332
1333 // Past the stale time, well inside the default 5 minute idle TTL.
1334 now = 61_000;
1335 expect(yield* remount).toBe("after edit");
1336 expect(yield* readEnvironmentQuery(registry, sidebar)).toBe("after edit");
1337 expect(fetches).toBe(2);
1338 }),
1339 );
1340
1341 it.effect("keeps its cache when collected while unmounted, inside its stale time", () =>
1342 Effect.gen(function* () {
1343 NodeV8.setFlagsFromString("--expose-gc");
1344 const gc = NodeVM.runInNewContext("gc") as () => void;
1345 using _now = vi.spyOn(Date, "now").mockReturnValue(0);
1346 let fetches = 0;
1347 const harness = yield* makeEnvironmentQueryHarness(
1348 Effect.sync(() => {
1349 fetches += 1;
1350 return fetches;
1351 }),
1352 );
1353 const registry = AtomRegistry.make();
1354 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1355 // `Atom.family` holds members weakly, so the test must hold none: another environment
1356 // than `harness.atom`'s, which the harness holds.
1357 const environmentId = EnvironmentId.make("unheld-environment");
1358 const query = () => harness.family({ environmentId, input: undefined });
1359 const first = new WeakRef(query());
1360 const remount = Effect.gen(function* () {
1361 const unmount = registry.mount(query());
1362 yield* Effect.yieldNow;
1363 const value = yield* readEnvironmentQuery(registry, query());
1364 unmount();
1365 return value;
1366 });
1367 // A WeakRef target survives until the current job ends, so collect after it.
1368 const collect = Effect.yieldNow.pipe(Effect.andThen(Effect.sync(gc)));
1369
1370 expect(yield* remount).toBe(1);
1371 yield* collect;
1372 expect(yield* remount).toBe(1);
1373 yield* collect;
1374 expect(first.deref()).toBe(query());
1375 expect(fetches).toBe(1);
1376 }),
1377 );
1378
1379 it.effect.each([true, false])("loads thread link metadata with server support %s", (supported) =>
1380 Effect.gen(function* () {
1381 const projectId = ProjectId.make("project");
1382 const tag = supported
1383 ? ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata
1384 : ORCHESTRATION_V2_WS_METHODS.getThreadTitles;
1385 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1386 rpcSession: {
1387 initialConfig: Effect.succeed({ threadLinkMetadata: supported }),
1388 client: {
1389 [tag]: () =>
1390 Effect.succeed(supported ? { fork: { title: "Fork", projectId } } : { fork: "Fork" }),
1391 },
1392 } as unknown as RpcSession.RpcSession,
1393 });
1394 const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1395 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1396 >;
1397 const atom = createOrchestrationEnvironmentAtoms(runtime).threadLinkMetadata({
1398 environmentId: QUERY_ENVIRONMENT.environmentId,
1399 input: { threadIds: [ThreadId.make("fork")] },
1400 });
1401 const registry = yield* mountEnvironmentQuery(atom);
1402 expect(yield* readEnvironmentQuery(registry, atom)).toEqual({
1403 fork: { title: "Fork", projectId: supported ? projectId : null },
1404 });
1405 }),
1406 );
1407
1408 it.effect("re-checks thread titles when one of their threads leaves the shell", () =>
1409 Effect.gen(function* () {
1410 const requests = yield* Queue.unbounded<Deferred.Deferred<Record<string, string>>>();
1411 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1412 rpcSession: {
1413 client: {
1414 [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: () =>
1415 Effect.gen(function* () {
1416 const answer = yield* Deferred.make<Record<string, string>>();
1417 yield* Queue.offer(requests, answer);
1418 return yield* Deferred.await(answer);
1419 }),
1420 },
1421 } as unknown as RpcSession.RpcSession,
1422 });
1423 const shellState = Atom.make<Pick<EnvironmentShellState, "removedAt">>({
1424 removedAt: new Map(),
1425 }).pipe(Atom.keepAlive);
1426 const removed = (entries: ReadonlyArray<readonly [string, number]>) => ({
1427 removedAt: new Map(entries.map(([id, sequence]) => [ThreadId.make(id), sequence])),
1428 });
1429 // Thread titles never use the HTTP client.
1430 const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1431 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1432 >;
1433 const atom = createOrchestrationEnvironmentAtoms(runtime, {
1434 shellState: () => shellState,
1435 }).threadTitles({
1436 environmentId: QUERY_ENVIRONMENT.environmentId,
1437 input: { threadIds: [ThreadId.make("fork")] },
1438 });
1439 const registry = yield* mountEnvironmentQuery(atom);
1440 const settled: Array<Record<string, string>> = [];
1441 const unsubscribe = registry.subscribe(atom, (result) => {
1442 if (AsyncResult.isSuccess(result) && !result.waiting) settled.push(result.value);
1443 });
1444 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1445
1446 yield* Deferred.succeed(yield* Queue.take(requests), { fork: "Fork" });
1447 expect(yield* readEnvironmentQuery(registry, atom)).toEqual({ fork: "Fork" });
1448
1449 registry.set(shellState, removed([["other", 5]]));
1450 expect(registry.get(atom).waiting).toBe(false);
1451
1452 // Archiving and then deleting the fork both remove it from the shell.
1453 registry.set(shellState, removed([["fork", 6]]));
1454 const beforeDelete = yield* Queue.take(requests);
1455 registry.set(shellState, removed([["fork", 7]]));
1456 const afterDelete = yield* Queue.take(requests);
1457 yield* Deferred.succeed(beforeDelete, { fork: "Fork" });
1458 yield* Deferred.succeed(afterDelete, {});
1459 expect(yield* readEnvironmentQuery(registry, atom)).toEqual({});
1460 expect(settled).toEqual([{ fork: "Fork" }, {}]);
1461 }),
1462 );
1463
1464 it.effect("re-reads an open archive when a thread leaves the shell", () =>
1465 Effect.gen(function* () {
1466 const requests =
1467 yield* Queue.unbounded<Deferred.Deferred<OrchestrationV2ArchivedShellSnapshot>>();
1468 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1469 rpcSession: {
1470 client: {
1471 [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: () =>
1472 Effect.gen(function* () {
1473 const answer = yield* Deferred.make<OrchestrationV2ArchivedShellSnapshot>();
1474 yield* Queue.offer(requests, answer);
1475 return yield* Deferred.await(answer);
1476 }),
1477 },
1478 } as unknown as RpcSession.RpcSession,
1479 });
1480 const shellState = Atom.make<Pick<EnvironmentShellState, "removedAt">>({
1481 removedAt: new Map(),
1482 }).pipe(Atom.keepAlive);
1483 const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1484 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1485 >;
1486 const atom = createOrchestrationEnvironmentAtoms(runtime, {
1487 shellState: () => shellState,
1488 }).archivedShellSnapshot({ environmentId: QUERY_ENVIRONMENT.environmentId, input: {} });
1489 const page = (threads: OrchestrationV2ArchivedShellSnapshot["threads"]) => ({
1490 schemaVersion: 1,
1491 snapshotSequence: 1,
1492 projects: [v2Project],
1493 threads,
1494 });
1495 const registry = yield* mountEnvironmentQuery(atom);
1496 const archivedIds = Effect.map(readEnvironmentQuery(registry, atom), (snapshot) =>
1497 snapshot.threads.map((thread) => thread.id),
1498 );
1499 yield* Deferred.succeed(yield* Queue.take(requests), page([]));
1500 expect(yield* archivedIds).toEqual([]);
1501
1502 // Another client archives the thread, then deletes it from the archive.
1503 registry.set(shellState, { removedAt: new Map([[v2ThreadId, 2]]) });
1504 expect(registry.get(atom).waiting).toBe(true);
1505 yield* Deferred.succeed(
1506 yield* Queue.take(requests),
1507 page([{ ...v2ThreadShell, archivedAt: v2Now }]),
1508 );
1509 expect(yield* archivedIds).toEqual([v2ThreadId]);
1510 registry.set(shellState, { removedAt: new Map([[v2ThreadId, 3]]) });
1511 yield* Deferred.succeed(yield* Queue.take(requests), page([]));
1512 expect(yield* archivedIds).toEqual([]);
1513 }),
1514 );
1515 });
1516
1517 describe("executeAtomQuery", () => {
1518 it("keeps concurrent query results correlated to their atoms", async () => {
1519 const firstLatch = Latch.makeUnsafe();
1520 const secondLatch = Latch.makeUnsafe();
1521 const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first")));
1522 const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second")));
1523 const registry = AtomRegistry.make();
1524
1525 const firstResult = executeAtomQuery(registry, firstAtom);
1526 const secondResult = executeAtomQuery(registry, secondAtom);
1527
1528 secondLatch.openUnsafe();
1529 firstLatch.openUnsafe();
1530
1531 const [first, second] = await Promise.all([firstResult, secondResult]);
1532 expect(first._tag).toBe("Success");
1533 expect(second._tag).toBe("Success");
1534 if (first._tag === "Success" && second._tag === "Success") {
1535 expect(first.value).toBe("first");
1536 expect(second.value).toBe("second");
1537 }
1538
1539 registry.dispose();
1540 });
1541
1542 it("settles when its caller aborts a waiting query", async () => {
1543 const registry = AtomRegistry.make();
1544 const controller = new AbortController();
1545 const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {
1546 reportDefect: false,
1547 signal: controller.signal,
1548 });
1549
1550 controller.abort();
1551
1552 const result = await resultPromise;
1553 expect(result._tag).toBe("Failure");
1554 if (result._tag === "Failure") {
1555 expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);
1556 }
1557 registry.dispose();
1558 });
1559 });
1560
1561 describe("runtime command runner", () => {
1562 const start = <A, E>(effect: Effect.Effect<A, E>) =>
1563 Effect.forkChild(Effect.exit(effect), { startImmediately: true });
1564
1565 it.effect("fails the run with a defect when its lane key throws", () =>
1566 Effect.gen(function* () {
1567 const defect = new Error("invalid command key");
1568 const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1569 label: "test.invalid-key",
1570 concurrency: {
1571 mode: "serial",
1572 key: () => {
1573 throw defect;
1574 },
1575 },
1576 execute: () => Effect.void,
1577 });
1578 const registry = AtomRegistry.make();
1579
1580 const exit = yield* Effect.exit(command.run(registry, undefined));
1581 expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toBe(defect);
1582 registry.dispose();
1583 }),
1584 );
1585
1586 it.effect("stops a command when its caller is interrupted", () =>
1587 Effect.gen(function* () {
1588 const started = Latch.makeUnsafe();
1589 let stopped = false;
1590 const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1591 label: "test.interrupt",
1592 execute: () =>
1593 Effect.sync(() => started.openUnsafe()).pipe(
1594 Effect.andThen(Effect.never),
1595 Effect.onInterrupt(() =>
1596 Effect.sync(() => {
1597 stopped = true;
1598 }),
1599 ),
1600 ),
1601 });
1602 const registry = AtomRegistry.make();
1603
1604 const run = yield* start(command.run(registry, undefined));
1605 yield* started.await;
1606 yield* Fiber.interrupt(run);
1607
1608 expect(stopped).toBe(true);
1609 registry.dispose();
1610 }),
1611 );
1612
1613 it.effect("serializes a lane, and skips a queued command its caller stopped waiting for", () =>
1614 Effect.gen(function* () {
1615 const firstStarted = Latch.makeUnsafe();
1616 const firstLatch = Latch.makeUnsafe();
1617 const events: string[] = [];
1618 const runtime = Atom.runtime(Layer.empty);
1619 const scheduler = createAtomCommandScheduler();
1620 const concurrency = { mode: "serial" as const, key: () => "shared" };
1621 const firstCommand = createRuntimeCommand(runtime, {
1622 label: "test.first",
1623 scheduler,
1624 concurrency,
1625 execute: () =>
1626 Effect.sync(() => {
1627 events.push("first:start");
1628 firstStarted.openUnsafe();
1629 }).pipe(
1630 Effect.andThen(firstLatch.await),
1631 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
1632 ),
1633 });
1634 const queuedCommand = createRuntimeCommand(runtime, {
1635 label: "test.queued",
1636 scheduler,
1637 concurrency,
1638 execute: (name: string) => Effect.sync(() => events.push(`${name}:start`)),
1639 });
1640 const registry = AtomRegistry.make();
1641
1642 const first = yield* start(firstCommand.run(registry, undefined));
1643 yield* firstStarted.await;
1644 const abandoned = yield* start(queuedCommand.run(registry, "abandoned"));
1645 const third = yield* start(queuedCommand.run(registry, "third"));
1646 yield* Fiber.interrupt(abandoned);
1647 expect(events).toEqual(["first:start"]);
1648
1649 firstLatch.openUnsafe();
1650 yield* Fiber.join(first);
1651 yield* Fiber.join(third);
1652 expect(events).toEqual(["first:start", "first:end", "third:start"]);
1653 registry.dispose();
1654 }),
1655 );
1656
1657 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
1658 Effect.gen(function* () {
1659 const handoffStarted = Latch.makeUnsafe();
1660 const handoffComplete = Latch.makeUnsafe();
1661 const resumeComplete = Latch.makeUnsafe();
1662 const runtime = Atom.runtime(Layer.empty);
1663 const scheduler = createAtomCommandScheduler();
1664 const concurrency = { mode: "serial" as const, key: () => "shared" };
1665 const updateCommand = createRuntimeCommand(runtime, {
1666 label: "test.update",
1667 execute: (_input: void, registry) =>
1668 scheduler
1669 .schedule(
1670 registry,
1671 concurrency,
1672 undefined,
1673 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
1674 Effect.andThen(handoffComplete.await),
1675 ),
1676 )
1677 .pipe(Effect.andThen(resumeComplete.await)),
1678 });
1679 const configCommand = createRuntimeCommand(runtime, {
1680 label: "test.config",
1681 scheduler,
1682 concurrency,
1683 execute: () => Effect.succeed("configured"),
1684 });
1685 const registry = AtomRegistry.make();
1686
1687 const update = yield* start(updateCommand.run(registry, undefined));
1688 yield* handoffStarted.await;
1689 const config = yield* start(configCommand.run(registry, undefined));
1690 handoffComplete.openUnsafe();
1691
1692 expect(yield* Fiber.join(config)).toEqual(Exit.succeed("configured"));
1693 resumeComplete.openUnsafe();
1694 expect(Exit.isSuccess(yield* Fiber.join(update))).toBe(true);
1695 registry.dispose();
1696 }),
1697 );
1698
1699 it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () =>
1700 Effect.gen(function* () {
1701 const commitStarting = yield* Deferred.make<void>();
1702 const observerArmed = yield* Deferred.make<void>();
1703 const reconnected = yield* Deferred.make<void>();
1704 const states = yield* Queue.unbounded<{ readonly phase: string }>();
1705 yield* Queue.offer(states, { phase: "connected" });
1706 const scheduler = createAtomCommandScheduler();
1707 const concurrency = { mode: "serial" as const, key: () => "shared" };
1708 const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1709 label: "test.desktop-update-handoff",
1710 execute: (_input: void, registry) =>
1711 Effect.gen(function* () {
1712 yield* Deferred.await(commitStarting).pipe(
1713 Effect.andThen(
1714 Stream.fromQueue(states).pipe(
1715 Stream.tap(() => Deferred.succeed(observerArmed, undefined)),
1716 Stream.dropWhile((state) => state.phase === "connected"),
1717 Stream.filter((state) => state.phase === "connected"),
1718 Stream.runHead,
1719 ),
1720 ),
1721 Effect.andThen(Deferred.succeed(reconnected, undefined)),
1722 Effect.forkChild,
1723 );
1724 yield* scheduler.schedule(
1725 registry,
1726 concurrency,
1727 undefined,
1728 Deferred.succeed(commitStarting, undefined).pipe(
1729 Effect.andThen(Deferred.await(observerArmed)),
1730 ),
1731 );
1732 yield* Queue.offer(states, { phase: "backoff" });
1733 yield* Queue.offer(states, { phase: "connected" });
1734 yield* Deferred.await(reconnected);
1735 }),
1736 });
1737 const registry = AtomRegistry.make();
1738
1739 yield* command.run(registry, undefined);
1740 registry.dispose();
1741 }),
1742 );
1743
1744 it.effect("shares a single-flight run, which stops once its last caller stops waiting", () =>
1745 Effect.gen(function* () {
1746 const started = Latch.makeUnsafe();
1747 let executions = 0;
1748 let stopped = false;
1749 const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1750 label: "test.single-flight",
1751 concurrency: { mode: "singleFlight", key: (key: string) => key },
1752 execute: () =>
1753 Effect.sync(() => {
1754 executions++;
1755 started.openUnsafe();
1756 }).pipe(
1757 Effect.andThen(Effect.never),
1758 Effect.onInterrupt(() =>
1759 Effect.sync(() => {
1760 stopped = true;
1761 }),
1762 ),
1763 ),
1764 });
1765 const registry = AtomRegistry.make();
1766
1767 const first = yield* start(command.run(registry, "same"));
1768 const second = yield* start(command.run(registry, "same"));
1769 yield* started.await;
1770 yield* Fiber.interrupt(first);
1771 expect({ executions, stopped }).toEqual({ executions: 1, stopped: false });
1772
1773 yield* Fiber.interrupt(second);
1774 expect(stopped).toBe(true);
1775 registry.dispose();
1776 }),
1777 );
1778
1779 it.effect("gives every single-flight caller the shared result", () =>
1780 Effect.gen(function* () {
1781 const latch = Latch.makeUnsafe();
1782 let executions = 0;
1783 const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1784 label: "test.single-flight",
1785 concurrency: { mode: "singleFlight", key: (key: string) => key },
1786 execute: () =>
1787 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1788 });
1789 const registry = AtomRegistry.make();
1790
1791 const first = yield* start(command.run(registry, "same"));
1792 const second = yield* start(command.run(registry, "same"));
1793 latch.openUnsafe();
1794
1795 expect(yield* Fiber.join(first)).toEqual(Exit.succeed("done"));
1796 expect(yield* Fiber.join(second)).toEqual(Exit.succeed("done"));
1797 expect(executions).toBe(1);
1798 registry.dispose();
1799 }),
1800 );
1801
1802 it.effect("coalesces queued latest-value commands, and drops one nobody waits for", () =>
1803 Effect.gen(function* () {
1804 const firstStarted = Latch.makeUnsafe();
1805 const firstLatch = Latch.makeUnsafe();
1806 const executed: number[] = [];
1807 const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1808 label: "test.latest",
1809 concurrency: { mode: "latest", key: () => "shared" },
1810 execute: (value: number) =>
1811 Effect.sync(() => {
1812 executed.push(value);
1813 firstStarted.openUnsafe();
1814 }).pipe(Effect.andThen(value === 1 ? firstLatch.await : Effect.void), Effect.as(value)),
1815 });
1816 const registry = AtomRegistry.make();
1817
1818 const first = yield* start(command.run(registry, 1));
1819 yield* firstStarted.await;
1820 const second = yield* start(command.run(registry, 2));
1821 const third = yield* start(command.run(registry, 3));
1822 firstLatch.openUnsafe();
1823
1824 expect(yield* Fiber.join(first)).toEqual(Exit.succeed(1));
1825 expect(yield* Fiber.join(second)).toEqual(Exit.succeed(3));
1826 expect(yield* Fiber.join(third)).toEqual(Exit.succeed(3));
1827 expect(executed).toEqual([1, 3]);
1828
1829 firstLatch.closeUnsafe();
1830 const running = yield* start(command.run(registry, 1));
1831 const abandoned = yield* start(command.run(registry, 4));
1832 yield* Fiber.interrupt(abandoned);
1833 firstLatch.openUnsafe();
1834 yield* Fiber.join(running);
1835 expect(executed).toEqual([1, 3, 1]);
1836 registry.dispose();
1837 }),
1838 );
1839 });
1840
1841 describe("persisted environment queries", () => {
1842 it.effect("keeps an in-memory cached page pending until revalidation settles", () =>
1843 Effect.gen(function* () {
1844 const refreshStarted = Latch.makeUnsafe();
1845 const finishRefresh = Latch.makeUnsafe();
1846 let executions = 0;
1847 const harness = yield* makeEnvironmentQueryHarness(
1848 Effect.suspend(() => {
1849 if (++executions === 1) return Effect.succeed("cached");
1850 refreshStarted.openUnsafe();
1851 return finishRefresh.await.pipe(Effect.as("fresh"));
1852 }),
1853 { persistence: { load: () => Effect.succeedNone, save: () => Effect.void } },
1854 );
1855 const registry = yield* mountEnvironmentQuery(harness.atom);
1856 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1857 registry.refresh(harness.atom);
1858 yield* refreshStarted.await;
1859 expect(registry.get(harness.atom)).toMatchObject({
1860 _tag: "Success",
1861 value: "cached",
1862 waiting: true,
1863 });
1864 finishRefresh.openUnsafe();
1865 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1866 }),
1867 );
1868
1869 it.effect(
1870 "restores cached data in a new registry while offline, then refreshes on reconnect",
1871 () =>
1872 Effect.gen(function* () {
1873 let saved = Option.none<string>();
1874 const saves = yield* Queue.unbounded<string>();
1875 const persistence: QueryPersistence<string> = {
1876 load: () => Effect.sync(() => saved),
1877 save: (_environmentId, _key, value) =>
1878 Effect.sync(() => {
1879 saved = Option.some(value);
1880 }).pipe(Effect.andThen(Queue.offer(saves, value))),
1881 };
1882 const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1883 persistence,
1884 });
1885 const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1886 expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1887 expect(yield* Queue.take(saves)).toBe("first");
1888
1889 const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1890 persistence,
1891 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1892 });
1893 const registry = yield* mountEnvironmentQuery(restarted.atom);
1894 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1895 yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1896 yield* Effect.yieldNow;
1897 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1898 expect(yield* Queue.take(saves)).toBe("updated");
1899 }),
1900 );
1901
1902 it.effect("answers readers while its save is pending, and ends the save with the query", () =>
1903 Effect.gen(function* () {
1904 const saveEnded = Latch.makeUnsafe();
1905 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), {
1906 persistence: {
1907 load: () => Effect.succeedNone,
1908 // The registry's scheduler stops on dispose, so signal synchronously.
1909 save: () =>
1910 Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe()))),
1911 },
1912 });
1913 yield* Effect.scoped(
1914 Effect.gen(function* () {
1915 const registry = yield* mountEnvironmentQuery(harness.atom);
1916 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1917 }),
1918 );
1919 yield* saveEnded.await;
1920 }),
1921 );
1922
1923 it.effect("hands each server answer to onAnswer before readers see it", () =>
1924 Effect.gen(function* () {
1925 const answers: Array<readonly [string, string | null]> = [];
1926 let served = 0;
1927 const recorded = Atom.make<string | null>(null).pipe(Atom.keepAlive);
1928 const harness = yield* makeEnvironmentQueryHarness(
1929 Effect.sync(() => `answer-${++served}`),
1930 {
1931 onAnswer: (_target, value, registry) =>
1932 Effect.sync(() => {
1933 answers.push([value, registry.get(recorded)]);
1934 registry.set(recorded, value);
1935 }),
1936 },
1937 );
1938 const registry = yield* mountEnvironmentQuery(harness.atom);
1939 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1");
1940 expect(registry.get(recorded)).toBe("answer-1");
1941 registry.refresh(harness.atom);
1942 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2");
1943 expect(answers).toEqual([
1944 ["answer-1", null],
1945 ["answer-2", "answer-1"],
1946 ]);
1947 }),
1948 );
1949
1950 it.effect("does not hand a value restored from persistence to onAnswer", () =>
1951 Effect.gen(function* () {
1952 const answers: Array<string> = [];
1953 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), {
1954 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1955 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1956 onAnswer: (_target, value) => Effect.sync(() => answers.push(value)),
1957 });
1958 const registry = yield* mountEnvironmentQuery(harness.atom);
1959 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1960 expect(answers).toEqual([]);
1961 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1962 yield* Effect.yieldNow;
1963 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server");
1964 expect(answers).toEqual(["server"]);
1965 }),
1966 );
1967
1968 it.effect("keeps cached content available when revalidation fails", () =>
1969 Effect.gen(function* () {
1970 const harness = yield* makeEnvironmentQueryHarness(
1971 Effect.fail(new TestQueryError({ message: "failed" })),
1972 {
1973 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1974 },
1975 );
1976 const registry = yield* mountEnvironmentQuery(harness.atom);
1977 yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1978 expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached");
1979 }),
1980 );
1981 });