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

threads-atoms.test.ts

829 lines32.2 KB

1import {
2 EnvironmentId,
3 EventId,
4 MessageId,
5 ORCHESTRATION_WS_METHODS,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9 type OrchestrationThread,
10 type OrchestrationThreadDetailSnapshot,
11 type OrchestrationThreadStreamItem,
12} from "@t3tools/contracts";
13import { afterEach, describe, expect, it, vi } from "@effect/vitest";
14import * as Cause from "effect/Cause";
15import * as Clock from "effect/Clock";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Stream from "effect/Stream";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23import * as TestClock from "effect/testing/TestClock";
24import { Atom, AtomRegistry } from "effect/unstable/reactivity";
25import { RpcClientError } from "effect/unstable/rpc";
26import { Socket } from "effect/unstable/socket";
27​
28import type { ConnectionCatalogEntry } from "../connection/catalog.ts";
29import { EnvironmentRegistry } from "../connection/registry.ts";
30import {
31 AVAILABLE_CONNECTION_STATE,
32 PrimaryConnectionTarget,
33 type NetworkStatus,
34 type PreparedConnection,
35 type SupervisorConnectionState,
36} from "../connection/model.ts";
37import { EnvironmentSupervisor } from "../connection/supervisor.ts";
38import { ConnectionWakeups, type ConnectionWakeup } from "../connection/wakeups.ts";
39import { EnvironmentCacheStore } from "../platform/persistence.ts";
40import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
41import type { RpcSession } from "../rpc/session.ts";
42import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
43import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";
44import type { ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
45import {
46 createEnvironmentThreadStateAtoms,
47 makeEnvironmentThreadState,
48 requestOlderThreadTurns,
49 ThreadSnapshotLoader,
50 type EnvironmentThreadState,
51} from "./threads.ts";
52​
53const TARGET = new PrimaryConnectionTarget({
54 environmentId: EnvironmentId.make("environment-1"),
55 label: "Test environment",
56 httpBaseUrl: "https://environment.example.test",
57 wsBaseUrl: "wss://environment.example.test",
58});
59const THREAD_ID = ThreadId.make("thread-1");
60const THREAD: OrchestrationThread = {
61 id: THREAD_ID,
62 projectId: ProjectId.make("project-1"),
63 title: "Cached thread",
64 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "ModelA" },
65 runtimeMode: "full-access",
66 interactionMode: "default",
67 branch: "main",
68 worktreePath: null,
69 latestTurn: null,
70 createdAt: "2026-04-01T00:00:00.000Z",
71 updatedAt: "2026-04-01T00:00:00.000Z",
72 archivedAt: null,
73 settledOverride: null,
74 settledAt: null,
75 deletedAt: null,
76 messages: [],
77 proposedPlans: [],
78 activities: [],
79 checkpoints: [],
80 session: null,
81};
82const SNAPSHOT: OrchestrationThreadDetailSnapshot = { snapshotSequence: 7, thread: THREAD };
83​
84const CONNECTED_STATE: SupervisorConnectionState = {
85 ...AVAILABLE_CONNECTION_STATE,
86 desired: true,
87 network: "online",
88 phase: "connected",
89 attempt: 1,
90 generation: 1,
91};
92​
93const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?: {
94 readonly snapshot?: OrchestrationThreadDetailSnapshot;
95 readonly connected?: boolean;
96 readonly httpNone?: boolean;
97 readonly initialLoad?: Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
98 readonly stream?: Stream.Stream<OrchestrationThreadStreamItem, Error>;
99}) {
100 const clock = yield* Clock.Clock;
101 const wakeups = yield* Queue.unbounded<ConnectionWakeup>();
102 const subscriptions = yield* Queue.unbounded<{
103 readonly afterSequence: number | undefined;
104 readonly events: Queue.Queue<OrchestrationThreadStreamItem, Error>;
105 readonly closed: Deferred.Deferred<void>;
106 }>();
107 const olderLoads = yield* Queue.unbounded<{
108 readonly window: ThreadSnapshotWindow;
109 readonly response: Deferred.Deferred<Option.Option<OrchestrationThreadDetailSnapshot>>;
110 readonly closed: Deferred.Deferred<void>;
111 }>();
112 const snapshot = options?.snapshot ?? SNAPSHOT;
113 let httpLoads = 0;
114 let diskLoads = 0;
115 let opened = 0;
116 let active = 0;
117 const client = {
118 [ORCHESTRATION_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) =>
119 Stream.unwrap(
120 Effect.gen(function* () {
121 const events = yield* Queue.unbounded<OrchestrationThreadStreamItem, Error>();
122 const closed = yield* Deferred.make<void>();
123 yield* Effect.acquireRelease(
124 Effect.sync(() => {
125 opened += 1;
126 active += 1;
127 }),
128 () =>
129 Effect.sync(() => {
130 active -= 1;
131 }).pipe(Effect.andThen(Deferred.succeed(closed, undefined))),
132 );
133 yield* Queue.offer(subscriptions, { afterSequence: input.afterSequence, events, closed });
134 return options?.stream ?? Stream.fromQueue(events);
135 }),
136 ),
137 } as unknown as WsRpcProtocolClient;
138 const session: RpcSession = {
139 client,
140 initialConfig: Effect.succeed({
141 threadResumeCompletionMarker: true,
142 threadSnapshotPagination: true,
143 } as never),
144 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
145 ready: Effect.void,
146 probe: Effect.void,
147 closed: Effect.never,
148 };
149 const connectionState = yield* SubscriptionRef.make(
150 options?.connected ? CONNECTED_STATE : AVAILABLE_CONNECTION_STATE,
151 );
152 const sessionRef = yield* SubscriptionRef.make(Option.some(session));
153 const supervisor = EnvironmentSupervisor.of({
154 target: TARGET,
155 state: connectionState,
156 session: sessionRef,
157 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
158 Option.some({
159 environmentId: TARGET.environmentId,
160 label: TARGET.label,
161 httpBaseUrl: TARGET.httpBaseUrl,
162 socketUrl: TARGET.wsBaseUrl,
163 httpAuthorization: null,
164 target: TARGET,
165 }),
166 ),
167 connect: Effect.void,
168 disconnect: Effect.void,
169 retryNow: Effect.void,
170 });
171 const environmentRegistry = EnvironmentRegistry.of({
172 entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
173 new Map(),
174 ),
175 networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
176 start: Effect.void,
177 register: () => Effect.die("Unexpected environment registration"),
178 registerPlatform: () => Effect.die("Unexpected environment registration"),
179 reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),
180 remove: () => Effect.die("Unexpected environment removal"),
181 removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
182 retryNow: () => Effect.void,
183 state: () => SubscriptionRef.get(supervisor.state),
184 stateChanges: () => SubscriptionRef.changes(supervisor.state),
185 run: (_environmentId, effect) =>
186 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
187 runStream: (_environmentId, stream) =>
188 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
189 followStream: (_environmentId, stream) =>
190 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
191 });
192 const runtime = Atom.runtime(
193 Layer.mergeAll(
194 Layer.succeed(Clock.Clock, clock),
195 Layer.succeed(ConnectionWakeups, { changes: Stream.fromQueue(wakeups) }),
196 Layer.succeed(EnvironmentRegistry, environmentRegistry),
197 Layer.succeed(
198 EnvironmentCacheStore,
199 EnvironmentCacheStore.of({
200 loadShell: () => Effect.succeed(Option.none()),
201 saveShell: () => Effect.void,
202 loadThread: () =>
203 Effect.sync(() => {
204 diskLoads += 1;
205 return Option.none();
206 }),
207 saveThread: () => Effect.void,
208 removeThread: () => Effect.void,
209 loadServerConfig: () => Effect.succeed(Option.none()),
210 saveServerConfig: () => Effect.void,
211 loadVcsRefs: () => Effect.succeed(Option.none()),
212 saveVcsRefs: () => Effect.void,
213 removeVcsRefs: () => Effect.void,
214 clearVcsRefs: () => Effect.void,
215 clear: () => Effect.void,
216 }),
217 ),
218 Layer.succeed(
219 ThreadSnapshotLoader,
220 ThreadSnapshotLoader.of({
221 load: (_prepared, _threadId, window) => {
222 if (window?.beforeCursor === undefined) {
223 return Effect.sync(() => {
224 httpLoads += 1;
225 }).pipe(
226 Effect.andThen(
227 options?.initialLoad ??
228 Effect.succeed(options?.httpNone ? Option.none() : Option.some(snapshot)),
229 ),
230 );
231 }
232 return Effect.gen(function* () {
233 const response =
234 yield* Deferred.make<Option.Option<OrchestrationThreadDetailSnapshot>>();
235 const closed = yield* Deferred.make<void>();
236 yield* Effect.addFinalizer(() => Deferred.succeed(closed, undefined));
237 yield* Queue.offer(olderLoads, { window, response, closed });
238 return yield* Deferred.await(response);
239 }).pipe(Effect.scoped);
240 },
241 }),
242 ),
243 ),
244 );
245 const raw = createEnvironmentThreadStateAtoms(runtime);
246 const details = createEnvironmentThreadDetailAtoms(raw.stateAtom);
247 const ref = { environmentId: TARGET.environmentId, threadId: THREAD_ID };
248 const stateAtom = details.stateAtom(ref);
249 const makeRegistry = Effect.acquireRelease(
250 Effect.sync(() => AtomRegistry.make({ defaultIdleTTL: 60_000, timeoutResolution: 1 })),
251 (registry) => Effect.sync(() => registry.dispose()),
252 );
253 const registry = yield* makeRegistry;
254​
255 return {
256 runtime,
257 supervisor,
258 registry,
259 makeRegistry,
260 rawAtoms: raw,
261 stateAtom,
262 details,
263 ref,
264 subscriptions,
265 olderLoads,
266 connectionState,
267 session,
268 sessionRef,
269 wakeups,
270 counts: () => ({ httpLoads, diskLoads, opened, active }),
271 };
272});
273​
274function observeState(
275 registry: AtomRegistry.AtomRegistry,
276 atom: Atom.Atom<EnvironmentThreadState>,
277 predicate: (state: EnvironmentThreadState) => boolean,
278) {
279 return AtomRegistry.toStream(registry, atom).pipe(
280 Stream.filter(predicate),
281 Stream.runHead,
282 Effect.map(Option.getOrThrow),
283 );
285​
286function currentThread(
287 registry: AtomRegistry.AtomRegistry,
288 atom: Atom.Atom<EnvironmentThreadState>,
289) {
290 return Option.getOrThrow(registry.get(atom).data);
292​
293describe("createEnvironmentThreadStateAtoms", () => {
294 afterEach(() => {
295 vi.useRealTimers();
296 vi.restoreAllMocks();
297 });
298​
299 it.effect("exposes snapshot loader defects before the RPC subscription starts", () =>
300 Effect.gen(function* () {
301 const completed = yield* Deferred.make<void>();
302 const h = yield* makeHarness({
303 connected: true,
304 initialLoad: Effect.die(
305 new Error("SYNTHETIC_RAW_SNAPSHOT_DEFECT_SHOULD_NOT_REACH_THREAD_UI"),
306 ).pipe(Effect.ensuring(Deferred.succeed(completed, undefined))),
307 });
308 const unmount = h.registry.mount(h.stateAtom);
309 yield* Deferred.await(completed);
310 const failed = yield* observeState(h.registry, h.stateAtom, (state) =>
311 Option.isSome(state.error),
312 );
313 expect(failed.status).toBe("empty");
314 expect(failed.error).toEqual(Option.some("Could not synchronize the thread."));
315 expect(failed.data).toEqual(Option.none());
316 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 0, active: 0 });
317 yield* TestClock.adjust("1 second");
318 expect(h.registry.get(h.stateAtom)).toEqual(failed);
319 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 0, active: 0 });
320 unmount();
321 }),
322 );
323​
324 it.effect.each([
325 { kind: "protocol", httpNone: true },
326 { kind: "protocol", httpNone: false },
327 { kind: "fatal", httpNone: true },
328 { kind: "fatal", httpNone: false },
329 ] as const)(
330 "retains a terminated $kind load diagnostic across connection updates (empty: $httpNone)",
331 ({ kind, httpNone }) =>
332 Effect.gen(function* () {
333 const h = yield* makeHarness({ connected: true, httpNone });
334 const unmount = h.registry.mount(h.stateAtom);
335 const first = yield* Queue.take(h.subscriptions);
336 const error = new Error("SYNTHETIC_RAW_DEFECT_SHOULD_NOT_REACH_THREAD_UI");
337 yield* Queue.failCause(
338 first.events,
339 kind === "fatal"
340 ? Cause.die(error)
341 : Cause.fail(
342 new RpcClientError.RpcClientError({
343 reason: new RpcClientError.RpcClientDefect({
344 message: error.message,
345 cause: error,
346 }),
347 }),
348 ),
349 );
350 yield* Deferred.await(first.closed);
351 // The real finalizer has run; advancing the atom runtime's test clock
352 // also verifies that a defect does not enter the domain retry loop.
353 yield* TestClock.adjust("1 second");
354 const failed = h.registry.get(h.stateAtom);
355 expect(failed.status).toBe(httpNone ? "empty" : "cached");
356 expect(failed.error).toEqual(Option.some("Could not synchronize the thread."));
357 expect(failed.data).toEqual(httpNone ? Option.none() : Option.some(THREAD));
358 expect(h.counts().opened).toBe(1);
359 expect(h.counts().active).toBe(0);
360​
361 // Session publication can precede connected, and a fatal child cannot
362 // restart just because its supervisor reconnects.
363 for (const connection of [
364 AVAILABLE_CONNECTION_STATE,
365 { ...CONNECTED_STATE, phase: "connecting" as const },
366 CONNECTED_STATE,
367 ]) {
368 yield* SubscriptionRef.set(h.connectionState, connection);
369 yield* TestClock.adjust("0 millis");
370 expect(h.registry.get(h.stateAtom)).toEqual(failed);
371 }
372 yield* SubscriptionRef.set(h.sessionRef, Option.some({ ...h.session }));
373 if (kind === "fatal") {
374 yield* TestClock.adjust("1 second");
375 expect(h.counts().opened).toBe(1);
376 expect(h.registry.get(h.stateAtom)).toEqual(failed);
377 unmount();
378 return;
379 }
380 const next = yield* Queue.take(h.subscriptions);
381 expect(h.registry.get(h.stateAtom).error).toEqual(Option.none());
382 expect(h.registry.get(h.stateAtom).status).toBe("synchronizing");
383 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
384 yield* Queue.offer(next.events, { kind: "synchronized" });
385 const recovered = yield* observeState(
386 h.registry,
387 h.stateAtom,
388 (state) => state.status === "live",
389 );
390 expect(recovered.error).toEqual(Option.none());
391 expect(recovered.data).toEqual(Option.some(THREAD));
392 unmount();
393 yield* Deferred.await(next.closed);
394 }),
395 );
396​
397 it.effect("retries a protocol failure on foreground without replacing the session", () =>
398 Effect.gen(function* () {
399 const h = yield* makeHarness({ connected: true, httpNone: true });
400 const unmount = h.registry.mount(h.stateAtom);
401 const first = yield* Queue.take(h.subscriptions);
402 yield* Queue.fail(
403 first.events,
404 new RpcClientError.RpcClientError({
405 reason: new RpcClientError.RpcClientDefect({
406 message: "incompatible snapshot",
407 cause: new Error("incompatible snapshot"),
408 }),
409 }),
410 );
411 yield* Deferred.await(first.closed);
412 yield* TestClock.adjust("0 millis");
413 expect(Option.isSome(h.registry.get(h.stateAtom).error)).toBe(true);
414 yield* Queue.offer(h.wakeups, "application-active");
415 const next = yield* Queue.take(h.subscriptions);
416 expect(h.registry.get(h.stateAtom).error).toEqual(Option.none());
417 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
418 yield* Queue.offer(next.events, { kind: "synchronized" });
419 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
420 unmount();
421 yield* Deferred.await(next.closed);
422 }),
423 );
424​
425 it.effect("keeps transport loss nonterminal and recovers with a replacement session", () =>
426 Effect.gen(function* () {
427 const h = yield* makeHarness({ connected: true, httpNone: true });
428 const unmount = h.registry.mount(h.stateAtom);
429 const first = yield* Queue.take(h.subscriptions);
430 yield* Queue.fail(
431 first.events,
432 new RpcClientError.RpcClientError({
433 reason: new Socket.SocketCloseError({ code: 1006, closeReason: "connection lost" }),
434 }),
435 );
436 yield* Deferred.await(first.closed);
437 yield* TestClock.adjust("1 second");
438 expect(h.registry.get(h.stateAtom)).toMatchObject({
439 status: "synchronizing",
440 error: Option.none(),
441 data: Option.none(),
442 });
443 expect(h.counts().opened).toBe(1);
444 yield* SubscriptionRef.set(h.sessionRef, Option.some({ ...h.session }));
445 const next = yield* Queue.take(h.subscriptions);
446 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
447 yield* Queue.offer(next.events, { kind: "synchronized" });
448 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
449 unmount();
450 yield* Deferred.await(next.closed);
451 }),
452 );
453​
454 it.effect("retains ordinary domain error reporting and same-session retries", () =>
455 Effect.gen(function* () {
456 const h = yield* makeHarness({ connected: true, httpNone: true });
457 const unmount = h.registry.mount(h.stateAtom);
458 const first = yield* Queue.take(h.subscriptions);
459 yield* Queue.fail(first.events, new Error("thread not found yet"));
460 yield* Deferred.await(first.closed);
461 const failed = yield* observeState(h.registry, h.stateAtom, (state) =>
462 Option.isSome(state.error),
463 );
464 expect(failed.error).toEqual(Option.some("thread not found yet"));
465 yield* TestClock.adjust("250 millis");
466 const next = yield* Queue.take(h.subscriptions);
467 expect(h.counts().opened).toBe(2);
468 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
469 yield* Queue.offer(next.events, { kind: "synchronized" });
470 const recovered = yield* observeState(
471 h.registry,
472 h.stateAtom,
473 (state) => state.status === "live",
474 );
475 expect(recovered.error).toEqual(Option.none());
476 unmount();
477 yield* Deferred.await(next.closed);
478 }),
479 );
480​
481 it.effect.each([
482 { kind: "protocol", deleted: false },
483 { kind: "fatal", deleted: false },
484 { kind: "domain", deleted: false },
485 { kind: "protocol", deleted: true },
486 ] as const)(
487 "keeps buffered outcomes after a $kind failure (deleted: $deleted)",
488 ({ kind, deleted }) =>
489 Effect.gen(function* () {
490 const burst = yield* Deferred.make<void>();
491 const error = new Error(
492 kind === "domain"
493 ? "buffered thread failure"
494 : "SYNTHETIC_BUFFERED_DEFECT_SHOULD_NOT_REACH_THREAD_UI",
495 );
496 const items: OrchestrationThreadStreamItem[] = [
497 { kind: "snapshot", snapshot: SNAPSHOT },
498 { kind: "synchronized" },
499 {
500 kind: "event",
501 event: {
502 eventId: EventId.make("buffered-event"),
503 commandId: null,
504 causationEventId: null,
505 correlationId: null,
506 metadata: {},
507 sequence: 8,
508 occurredAt: THREAD.createdAt,
509 aggregateKind: "thread",
510 aggregateId: THREAD_ID,
511 type: "thread.meta-updated",
512 payload: {
513 threadId: THREAD_ID,
514 title: "Buffer drained",
515 updatedAt: THREAD.createdAt,
516 },
517 },
518 },
519 ];
520 if (deleted) {
521 items.push({
522 kind: "event",
523 event: {
524 eventId: EventId.make("buffered-deletion"),
525 commandId: null,
526 causationEventId: null,
527 correlationId: null,
528 metadata: {},
529 sequence: 9,
530 occurredAt: THREAD.createdAt,
531 aggregateKind: "thread",
532 aggregateId: THREAD_ID,
533 type: "thread.deleted",
534 payload: { threadId: THREAD_ID, deletedAt: THREAD.createdAt },
535 },
536 });
537 }
538 const failure =
539 kind === "fatal"
540 ? Cause.die(error)
541 : Cause.fail(
542 kind === "domain"
543 ? error
544 : new RpcClientError.RpcClientError({
545 reason: new RpcClientError.RpcClientDefect({
546 message: error.message,
547 cause: error,
548 }),
549 }),
550 );
551 const h = yield* makeHarness({
552 connected: true,
553 httpNone: true,
554 stream: Stream.fromEffect(Deferred.await(burst)).pipe(
555 Stream.flatMap(() => Stream.fromIterable(items)),
556 Stream.concat(Stream.failCause(failure)),
557 ),
558 });
559 yield* Effect.gen(function* () {
560 const state = yield* makeEnvironmentThreadState(THREAD_ID);
561 const initial = yield* Deferred.make<void>();
562 const drained = yield* Deferred.make<void>();
563 yield* SubscriptionRef.changes(state).pipe(
564 Stream.runForEach((value) =>
565 Deferred.succeed(initial, undefined).pipe(
566 Effect.andThen(
567 (
568 deleted
569 ? value.status === "deleted"
570 : Option.getOrNull(value.data)?.title === "Buffer drained"
571 )
572 ? Deferred.succeed(drained, undefined)
573 : Effect.void,
574 ),
575 ),
576 ),
577 Effect.forkScoped,
578 );
579 yield* Deferred.await(initial);
580 const subscription = yield* Queue.take(h.subscriptions);
581 yield* Deferred.succeed(burst, undefined);
582 yield* Deferred.await(subscription.closed);
583 yield* Deferred.await(drained);
584 const final = yield* SubscriptionRef.get(state);
585 if (deleted) {
586 expect(final.status).toBe("deleted");
587 expect(final.data).toEqual(Option.none());
588 expect(final.error).toEqual(Option.none());
589 return;
590 }
591 expect(Option.getOrThrow(final.data).title).toBe("Buffer drained");
592 expect(final.error).toEqual(
593 Option.some(kind === "domain" ? error.message : "Could not synchronize the thread."),
594 );
595 expect(final.status).toBe("cached");
596 }).pipe(
597 Effect.provideService(EnvironmentSupervisor, h.supervisor),
598 Effect.provide(h.registry.get(h.runtime.layer)),
599 Effect.scoped,
600 );
601 }),
602 );
603​
604 it.effect("shares one live stream and closes it after the last detail consumer leaves", () =>
605 Effect.gen(function* () {
606 const h = yield* makeHarness();
607 const unmountMessages = h.registry.mount(h.details.messagesAtom(h.ref));
608 const first = yield* Queue.take(h.subscriptions);
609 const unmountStatus = h.registry.mount(h.details.statusAtom(h.ref));
610 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 1, active: 1 });
611 unmountMessages();
612 yield* Queue.offer(first.events, { kind: "synchronized" });
613 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
614 expect(h.counts().active).toBe(1);
615 unmountStatus();
616 yield* Deferred.await(first.closed);
617 expect(h.counts().active).toBe(0);
618 }),
619 );
620​
621 it.effect("keeps warm data and resumes a completed cursor without loading another snapshot", () =>
622 Effect.gen(function* () {
623 const h = yield* makeHarness();
624 const unmount = h.registry.mount(h.stateAtom);
625 const first = yield* Queue.take(h.subscriptions);
626 yield* Queue.offer(first.events, {
627 kind: "event",
628 event: {
629 type: "thread.message-sent",
630 sequence: 8,
631 eventId: EventId.make("message-1"),
632 aggregateKind: "thread",
633 aggregateId: THREAD_ID,
634 occurredAt: THREAD.createdAt,
635 commandId: null,
636 causationEventId: null,
637 correlationId: null,
638 metadata: {},
639 payload: {
640 threadId: THREAD_ID,
641 messageId: MessageId.make("message-1"),
642 role: "assistant",
643 text: "Retained text",
644 turnId: null,
645 streaming: true,
646 createdAt: THREAD.createdAt,
647 updatedAt: THREAD.createdAt,
648 },
649 },
650 });
651 yield* Queue.offer(first.events, { kind: "synchronized" });
652 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
653 const before = currentThread(h.registry, h.stateAtom);
654 unmount();
655 yield* Deferred.await(first.closed);
656 const remount = h.registry.mount(h.stateAtom);
657 expect(currentThread(h.registry, h.stateAtom)).toBe(before);
658 const next = yield* Queue.take(h.subscriptions);
659 expect(next.afterSequence).toBe(8);
660 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
661 remount();
662 yield* Deferred.await(next.closed);
663 }),
664 );
665​
666 it.effect.each([
667 { replayed: false, statuses: ["live"] },
668 { replayed: true, statuses: ["live", "synchronizing", "live"] },
669 ])(
670 "keeps a warm resume live until it replays events (replayed: $replayed)",
671 ({ replayed, statuses }) =>
672 Effect.gen(function* () {
673 const h = yield* makeHarness({ connected: true });
674 const unmount = h.registry.mount(h.stateAtom);
675 const first = yield* Queue.take(h.subscriptions);
676 yield* Queue.offer(first.events, { kind: "synchronized" });
677 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
678 unmount();
679 yield* Deferred.await(first.closed);
680​
681 const observed: Array<EnvironmentThreadState["status"]> = [];
682 const stop = h.registry.subscribe(h.stateAtom, (state) => observed.push(state.status), {
683 immediate: true,
684 });
685 const remount = h.registry.mount(h.stateAtom);
686 const next = yield* Queue.take(h.subscriptions);
687 expect(next.afterSequence).toBe(7);
688 if (replayed) {
689 yield* Queue.offer(next.events, {
690 kind: "snapshot",
691 snapshot: { snapshotSequence: 9, thread: { ...THREAD, title: "Replayed" } },
692 });
693 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "synchronizing");
694 }
695 yield* Queue.offer(next.events, { kind: "synchronized" });
696 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
697 expect(observed.filter((status, index) => observed[index - 1] !== status)).toEqual(
698 statuses,
699 );
700 stop();
701 remount();
702 yield* Deferred.await(next.closed);
703 }),
704 );
705​
706 it.effect("downgrades a warm resume when the connection dropped while away", () =>
707 Effect.gen(function* () {
708 const h = yield* makeHarness({ connected: true });
709 const unmount = h.registry.mount(h.stateAtom);
710 const first = yield* Queue.take(h.subscriptions);
711 yield* Queue.offer(first.events, { kind: "synchronized" });
712 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
713 unmount();
714 yield* Deferred.await(first.closed);
715​
716 yield* SubscriptionRef.set(h.sessionRef, Option.none());
717 yield* SubscriptionRef.set(h.connectionState, AVAILABLE_CONNECTION_STATE);
718 const remount = h.registry.mount(h.stateAtom);
719 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "cached");
720 expect(currentThread(h.registry, h.stateAtom)).toBe(THREAD);
721 expect(h.counts().opened).toBe(1);
722​
723 yield* SubscriptionRef.set(h.connectionState, CONNECTED_STATE);
724 yield* SubscriptionRef.set(h.sessionRef, Option.some(h.session));
725 const next = yield* Queue.take(h.subscriptions);
726 expect(next.afterSequence).toBe(7);
727 expect(h.registry.get(h.stateAtom).status).toBe("synchronizing");
728 yield* Queue.offer(next.events, { kind: "synchronized" });
729 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
730 remount();
731 yield* Deferred.await(next.closed);
732 }),
733 );
734​
735 it.effect("keeps warm data when the raw atom family's weak entry is collected", () =>
736 Effect.gen(function* () {
737 const h = yield* makeHarness();
738 const oldRaw = h.rawAtoms.stateAtom(TARGET.environmentId, THREAD_ID);
739 const unmount = h.registry.mount(h.stateAtom);
740 const first = yield* Queue.take(h.subscriptions);
741 const latest = { ...THREAD, title: "Newer cached thread" };
742 yield* Queue.offer(first.events, {
743 kind: "snapshot",
744 snapshot: { snapshotSequence: 8, thread: latest },
745 });
746 yield* Queue.offer(first.events, { kind: "synchronized" });
747 yield* observeState(h.registry, h.stateAtom, (value) => value.status === "live");
748 unmount();
749 yield* Deferred.await(first.closed);
750​
751 // Force the weak-family miss without depending on host GC timing.
752 const deref = WeakRef.prototype.deref;
753 vi.spyOn(WeakRef.prototype, "deref").mockImplementation(function (this: WeakRef<object>) {
754 const value = deref.call(this);
755 return value === oldRaw ? undefined : value;
756 });
757 const remount = h.registry.mount(h.stateAtom);
758 expect(currentThread(h.registry, h.stateAtom)).toBe(latest);
759 const next = yield* Queue.take(h.subscriptions);
760 expect(next.afterSequence).toBe(8);
761 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
762 remount();
763 yield* Deferred.await(next.closed);
764 }),
765 );
766​
767 it.effect("keeps cached snapshots local to each registry", () =>
768 Effect.gen(function* () {
769 const h = yield* makeHarness();
770 const unmount = h.registry.mount(h.stateAtom);
771 const first = yield* Queue.take(h.subscriptions);
772 unmount();
773 yield* Deferred.await(first.closed);
774 const otherRegistry = yield* h.makeRegistry;
775 const unmountOther = otherRegistry.mount(h.stateAtom);
776 const other = yield* Queue.take(h.subscriptions);
777 expect(h.counts()).toEqual({ httpLoads: 2, diskLoads: 2, opened: 2, active: 1 });
778 unmountOther();
779 yield* Deferred.await(other.closed);
780 }),
781 );
782​
783 it.effect("expires the plain snapshot after five idle minutes", () =>
784 Effect.gen(function* () {
785 vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
786 const h = yield* makeHarness();
787 const unmount = h.registry.mount(h.stateAtom);
788 const first = yield* Queue.take(h.subscriptions);
789 unmount();
790 yield* Deferred.await(first.closed);
791 yield* Effect.yieldNow;
792 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(THREAD_SNAPSHOT_IDLE_TTL_MS + 1));
793 const remount = h.registry.mount(h.stateAtom);
794 const next = yield* Queue.take(h.subscriptions);
795 expect(h.counts()).toEqual({ httpLoads: 2, diskLoads: 2, opened: 2, active: 1 });
796 remount();
797 yield* Deferred.await(next.closed);
798 }),
799 );
800​
801 it.effect("cancels older-page work on unmount and permits it again on a warm return", () =>
802 Effect.gen(function* () {
803 const h = yield* makeHarness({
804 snapshot: {
805 ...SNAPSHOT,
806 page: { beforeCursor: "older-1", hasMore: true, snapshotSequence: 7 },
807 },
808 });
809 const unmount = h.registry.mount(h.stateAtom);
810 const first = yield* Queue.take(h.subscriptions);
811 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
812 const older = yield* Queue.take(h.olderLoads);
813 expect(Option.getOrThrow(h.registry.get(h.stateAtom).page).loadingOlder).toBe(true);
814 unmount();
815 yield* Deferred.await(first.closed);
816 yield* Deferred.await(older.closed);
817 const remount = h.registry.mount(h.stateAtom);
818 const next = yield* Queue.take(h.subscriptions);
819 expect(Option.getOrThrow(h.registry.get(h.stateAtom).page).loadingOlder).toBe(false);
820 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
821 const retried = yield* Queue.take(h.olderLoads);
822 expect(retried.window.beforeCursor).toBe("older-1");
823 expect(h.counts().httpLoads).toBe(1);
824 remount();
825 yield* Deferred.await(next.closed);
826 yield* Deferred.await(retried.closed);
827 }),
828 );
829});