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