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

threads-atoms.test.ts

894 lines34.7 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 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 setEnabled: () => Effect.die("Unexpected environment toggle"),
185 setCompatibility: () => Effect.die("Unexpected compatibility update"),
186 state: () => SubscriptionRef.get(supervisor.state),
187 stateChanges: () => SubscriptionRef.changes(supervisor.state),
188 run: (_environmentId, effect) =>
189 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
190 runStream: (_environmentId, stream) =>
191 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
192 followStream: (_environmentId, stream) =>
193 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
194 });
195 const runtime = Atom.runtime(
196 Layer.mergeAll(
197 Layer.succeed(Clock.Clock, clock),
198 Layer.succeed(ConnectionWakeups, { changes: Stream.fromQueue(wakeups) }),
199 Layer.succeed(EnvironmentRegistry, environmentRegistry),
200 Layer.succeed(
201 EnvironmentCacheStore,
202 EnvironmentCacheStore.of({
203 loadShell: () => Effect.succeedNone,
204 saveShell: () => Effect.void,
205 loadThread: () =>
206 Effect.sync(() => {
207 diskLoads += 1;
208 return Option.none();
209 }),
210 saveThread: () => Effect.void,
211 removeThread: () => Effect.void,
212 loadServerConfig: () => Effect.succeedNone,
213 saveServerConfig: () => Effect.void,
214 loadVcsRefs: () => Effect.succeedNone,
215 saveVcsRefs: () => Effect.void,
216 removeVcsRefs: () => Effect.void,
217 clearVcsRefs: () => Effect.void,
218 clear: () => Effect.void,
219 }),
220 ),
221 Layer.succeed(
222 ThreadSnapshotLoader,
223 ThreadSnapshotLoader.of({
224 load: (_prepared, _threadId, window) => {
225 if (window?.beforeCursor === undefined) {
226 return Effect.sync(() => {
227 httpLoads += 1;
228 }).pipe(
229 Effect.andThen(
230 options?.initialLoad ??
231 Effect.succeed(options?.httpNone ? Option.none() : Option.some(snapshot)),
232 ),
233 );
234 }
235 return Effect.gen(function* () {
236 const response =
237 yield* Deferred.make<Option.Option<OrchestrationThreadDetailSnapshot>>();
238 const closed = yield* Deferred.make<void>();
239 yield* Effect.addFinalizer(() => Deferred.succeed(closed, undefined));
240 yield* Queue.offer(olderLoads, { window, response, closed });
241 return yield* Deferred.await(response);
242 }).pipe(Effect.scoped);
243 },
244 }),
245 ),
246 ),
247 );
248 const raw = createEnvironmentThreadStateAtoms(runtime);
249 const details = createEnvironmentThreadDetailAtoms(raw.stateAtom);
250 const ref = { environmentId: TARGET.environmentId, threadId: THREAD_ID };
251 const stateAtom = details.stateAtom(ref);
252 const makeRegistry = Effect.acquireRelease(
253 Effect.sync(() => AtomRegistry.make({ defaultIdleTTL: 60_000, timeoutResolution: 1 })),
254 (registry) => Effect.sync(() => registry.dispose()),
255 );
256 const registry = yield* makeRegistry;
257​
258 return {
259 runtime,
260 supervisor,
261 registry,
262 makeRegistry,
263 rawAtoms: raw,
264 stateAtom,
265 details,
266 ref,
267 subscriptions,
268 olderLoads,
269 connectionState,
270 session,
271 sessionRef,
272 wakeups,
273 counts: () => ({ httpLoads, diskLoads, opened, active }),
274 };
275});
276​
277function observeState(
278 registry: AtomRegistry.AtomRegistry,
279 atom: Atom.Atom<EnvironmentThreadState>,
280 predicate: (state: EnvironmentThreadState) => boolean,
281) {
282 return AtomRegistry.toStream(registry, atom).pipe(
283 Stream.filter(predicate),
284 Stream.runHead,
285 Effect.map(Option.getOrThrow),
286 );
288​
289function currentThread(
290 registry: AtomRegistry.AtomRegistry,
291 atom: Atom.Atom<EnvironmentThreadState>,
292) {
293 return Option.getOrThrow(registry.get(atom).data);
295​
296describe("createEnvironmentThreadStateAtoms", () => {
297 afterEach(() => {
298 vi.useRealTimers();
299 vi.restoreAllMocks();
300 });
301​
302 it.effect("exposes snapshot loader defects before the RPC subscription starts", () =>
303 Effect.gen(function* () {
304 const completed = yield* Deferred.make<void>();
305 const h = yield* makeHarness({
306 connected: true,
307 initialLoad: Effect.die(
308 new Error("SYNTHETIC_RAW_SNAPSHOT_DEFECT_SHOULD_NOT_REACH_THREAD_UI"),
309 ).pipe(Effect.ensuring(Deferred.succeed(completed, undefined))),
310 });
311 const unmount = h.registry.mount(h.stateAtom);
312 yield* Deferred.await(completed);
313 const failed = yield* observeState(h.registry, h.stateAtom, (state) =>
314 Option.isSome(state.error),
315 );
316 expect(failed.status).toBe("empty");
317 expect(failed.error).toEqual(Option.some("Could not synchronize the thread."));
318 expect(failed.data).toEqual(Option.none());
319 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 0, active: 0 });
320 yield* TestClock.adjust("1 second");
321 expect(h.registry.get(h.stateAtom)).toEqual(failed);
322 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 0, active: 0 });
323 unmount();
324 }),
325 );
326​
327 it.effect.each([
328 { kind: "protocol", httpNone: true },
329 { kind: "protocol", httpNone: false },
330 { kind: "fatal", httpNone: true },
331 { kind: "fatal", httpNone: false },
332 ] as const)(
333 "retains a terminated $kind load diagnostic across connection updates (empty: $httpNone)",
334 ({ kind, httpNone }) =>
335 Effect.gen(function* () {
336 const h = yield* makeHarness({ connected: true, httpNone });
337 const unmount = h.registry.mount(h.stateAtom);
338 const first = yield* Queue.take(h.subscriptions);
339 const error = new Error("SYNTHETIC_RAW_DEFECT_SHOULD_NOT_REACH_THREAD_UI");
340 yield* Queue.failCause(
341 first.events,
342 kind === "fatal"
343 ? Cause.die(error)
344 : Cause.fail(
345 new RpcClientError.RpcClientError({
346 reason: new RpcClientError.RpcClientDefect({
347 message: error.message,
348 cause: error,
349 }),
350 }),
351 ),
352 );
353 yield* Deferred.await(first.closed);
354 // The real finalizer has run; advancing the atom runtime's test clock
355 // also verifies that a defect does not enter the domain retry loop.
356 yield* TestClock.adjust("1 second");
357 const failed = h.registry.get(h.stateAtom);
358 expect(failed.status).toBe(httpNone ? "empty" : "cached");
359 expect(failed.error).toEqual(Option.some("Could not synchronize the thread."));
360 expect(failed.data).toEqual(httpNone ? Option.none() : Option.some(THREAD));
361 expect(h.counts().opened).toBe(1);
362 expect(h.counts().active).toBe(0);
363​
364 // Session publication can precede connected, and a fatal child cannot
365 // restart just because its supervisor reconnects.
366 for (const connection of [
367 AVAILABLE_CONNECTION_STATE,
368 { ...CONNECTED_STATE, phase: "connecting" as const },
369 CONNECTED_STATE,
370 ]) {
371 yield* SubscriptionRef.set(h.connectionState, connection);
372 yield* TestClock.adjust("0 millis");
373 expect(h.registry.get(h.stateAtom)).toEqual(failed);
374 }
375 yield* SubscriptionRef.set(h.sessionRef, Option.some({ ...h.session }));
376 if (kind === "fatal") {
377 yield* TestClock.adjust("1 second");
378 expect(h.counts().opened).toBe(1);
379 expect(h.registry.get(h.stateAtom)).toEqual(failed);
380 unmount();
381 return;
382 }
383 const next = yield* Queue.take(h.subscriptions);
384 expect(h.registry.get(h.stateAtom).error).toEqual(Option.none());
385 expect(h.registry.get(h.stateAtom).status).toBe("synchronizing");
386 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
387 yield* Queue.offer(next.events, { kind: "synchronized" });
388 const recovered = yield* observeState(
389 h.registry,
390 h.stateAtom,
391 (state) => state.status === "live",
392 );
393 expect(recovered.error).toEqual(Option.none());
394 expect(recovered.data).toEqual(Option.some(THREAD));
395 unmount();
396 yield* Deferred.await(next.closed);
397 }),
398 );
399​
400 it.effect("retries a protocol failure on foreground without replacing the session", () =>
401 Effect.gen(function* () {
402 const h = yield* makeHarness({ connected: true, httpNone: true });
403 const unmount = h.registry.mount(h.stateAtom);
404 const first = yield* Queue.take(h.subscriptions);
405 yield* Queue.fail(
406 first.events,
407 new RpcClientError.RpcClientError({
408 reason: new RpcClientError.RpcClientDefect({
409 message: "incompatible snapshot",
410 cause: new Error("incompatible snapshot"),
411 }),
412 }),
413 );
414 yield* Deferred.await(first.closed);
415 yield* TestClock.adjust("0 millis");
416 expect(Option.isSome(h.registry.get(h.stateAtom).error)).toBe(true);
417 yield* Queue.offer(h.wakeups, "application-active");
418 const next = yield* Queue.take(h.subscriptions);
419 expect(h.registry.get(h.stateAtom).error).toEqual(Option.none());
420 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
421 yield* Queue.offer(next.events, { kind: "synchronized" });
422 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
423 unmount();
424 yield* Deferred.await(next.closed);
425 }),
426 );
427​
428 it.effect("keeps transport loss nonterminal and recovers with a replacement session", () =>
429 Effect.gen(function* () {
430 const h = yield* makeHarness({ connected: true, httpNone: true });
431 const unmount = h.registry.mount(h.stateAtom);
432 const first = yield* Queue.take(h.subscriptions);
433 yield* Queue.fail(
434 first.events,
435 new RpcClientError.RpcClientError({
436 reason: new Socket.SocketCloseError({ code: 1006, closeReason: "connection lost" }),
437 }),
438 );
439 yield* Deferred.await(first.closed);
440 yield* TestClock.adjust("1 second");
441 expect(h.registry.get(h.stateAtom)).toMatchObject({
442 status: "synchronizing",
443 error: Option.none(),
444 data: Option.none(),
445 });
446 expect(h.counts().opened).toBe(1);
447 yield* SubscriptionRef.set(h.sessionRef, Option.some({ ...h.session }));
448 const next = yield* Queue.take(h.subscriptions);
449 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
450 yield* Queue.offer(next.events, { kind: "synchronized" });
451 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
452 unmount();
453 yield* Deferred.await(next.closed);
454 }),
455 );
456​
457 it.effect("retains ordinary domain error reporting and same-session retries", () =>
458 Effect.gen(function* () {
459 const h = yield* makeHarness({ connected: true, httpNone: true });
460 const unmount = h.registry.mount(h.stateAtom);
461 const first = yield* Queue.take(h.subscriptions);
462 yield* Queue.fail(first.events, new Error("thread not found yet"));
463 yield* Deferred.await(first.closed);
464 const failed = yield* observeState(h.registry, h.stateAtom, (state) =>
465 Option.isSome(state.error),
466 );
467 expect(failed.error).toEqual(Option.some("thread not found yet"));
468 yield* TestClock.adjust("250 millis");
469 const next = yield* Queue.take(h.subscriptions);
470 expect(h.counts().opened).toBe(2);
471 yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });
472 yield* Queue.offer(next.events, { kind: "synchronized" });
473 const recovered = yield* observeState(
474 h.registry,
475 h.stateAtom,
476 (state) => state.status === "live",
477 );
478 expect(recovered.error).toEqual(Option.none());
479 unmount();
480 yield* Deferred.await(next.closed);
481 }),
482 );
483​
484 it.effect.each([
485 { kind: "protocol", deleted: false },
486 { kind: "fatal", deleted: false },
487 { kind: "domain", deleted: false },
488 { kind: "protocol", deleted: true },
489 ] as const)(
490 "keeps buffered outcomes after a $kind failure (deleted: $deleted)",
491 ({ kind, deleted }) =>
492 Effect.gen(function* () {
493 const burst = yield* Deferred.make<void>();
494 const error = new Error(
495 kind === "domain"
496 ? "buffered thread failure"
497 : "SYNTHETIC_BUFFERED_DEFECT_SHOULD_NOT_REACH_THREAD_UI",
498 );
499 const items: OrchestrationThreadStreamItem[] = [
500 { kind: "snapshot", snapshot: SNAPSHOT },
501 { kind: "synchronized" },
502 {
503 kind: "event",
504 event: {
505 eventId: EventId.make("buffered-event"),
506 commandId: null,
507 causationEventId: null,
508 correlationId: null,
509 metadata: {},
510 sequence: 8,
511 occurredAt: THREAD.createdAt,
512 aggregateKind: "thread",
513 aggregateId: THREAD_ID,
514 type: "thread.meta-updated",
515 payload: {
516 threadId: THREAD_ID,
517 title: "Buffer drained",
518 updatedAt: THREAD.createdAt,
519 },
520 },
521 },
522 ];
523 if (deleted) {
524 items.push({
525 kind: "event",
526 event: {
527 eventId: EventId.make("buffered-deletion"),
528 commandId: null,
529 causationEventId: null,
530 correlationId: null,
531 metadata: {},
532 sequence: 9,
533 occurredAt: THREAD.createdAt,
534 aggregateKind: "thread",
535 aggregateId: THREAD_ID,
536 type: "thread.deleted",
537 payload: { threadId: THREAD_ID, deletedAt: THREAD.createdAt },
538 },
539 });
540 }
541 const failure =
542 kind === "fatal"
543 ? Cause.die(error)
544 : Cause.fail(
545 kind === "domain"
546 ? error
547 : new RpcClientError.RpcClientError({
548 reason: new RpcClientError.RpcClientDefect({
549 message: error.message,
550 cause: error,
551 }),
552 }),
553 );
554 const h = yield* makeHarness({
555 connected: true,
556 httpNone: true,
557 stream: Stream.fromEffect(Deferred.await(burst)).pipe(
558 Stream.flatMap(() => Stream.fromIterable(items)),
559 Stream.concat(Stream.failCause(failure)),
560 ),
561 });
562 yield* Effect.gen(function* () {
563 const state = yield* makeEnvironmentThreadState(THREAD_ID);
564 const initial = yield* Deferred.make<void>();
565 const drained = yield* Deferred.make<void>();
566 yield* SubscriptionRef.changes(state).pipe(
567 Stream.runForEach((value) =>
568 Deferred.succeed(initial, undefined).pipe(
569 Effect.andThen(
570 (
571 deleted
572 ? value.status === "deleted"
573 : Option.getOrNull(value.data)?.title === "Buffer drained"
574 )
575 ? Deferred.succeed(drained, undefined)
576 : Effect.void,
577 ),
578 ),
579 ),
580 Effect.forkScoped,
581 );
582 yield* Deferred.await(initial);
583 const subscription = yield* Queue.take(h.subscriptions);
584 yield* Deferred.succeed(burst, undefined);
585 yield* Deferred.await(subscription.closed);
586 yield* Deferred.await(drained);
587 const final = yield* SubscriptionRef.get(state);
588 if (deleted) {
589 expect(final.status).toBe("deleted");
590 expect(final.data).toEqual(Option.none());
591 expect(final.error).toEqual(Option.none());
592 return;
593 }
594 expect(Option.getOrThrow(final.data).title).toBe("Buffer drained");
595 expect(final.error).toEqual(
596 Option.some(kind === "domain" ? error.message : "Could not synchronize the thread."),
597 );
598 expect(final.status).toBe("cached");
599 }).pipe(
600 Effect.provideService(EnvironmentSupervisor, h.supervisor),
601 Effect.provide(h.registry.get(h.runtime.layer)),
602 Effect.scoped,
603 );
604 }),
605 );
606​
607 it.effect("shares one live stream and closes it after the last detail consumer leaves", () =>
608 Effect.gen(function* () {
609 const h = yield* makeHarness();
610 const unmountMessages = h.registry.mount(h.details.messagesAtom(h.ref));
611 const first = yield* Queue.take(h.subscriptions);
612 const unmountStatus = h.registry.mount(h.details.statusAtom(h.ref));
613 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 1, active: 1 });
614 unmountMessages();
615 yield* Queue.offer(first.events, { kind: "synchronized" });
616 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
617 expect(h.counts().active).toBe(1);
618 unmountStatus();
619 yield* Deferred.await(first.closed);
620 expect(h.counts().active).toBe(0);
621 }),
622 );
623​
624 it.effect.each([1, 16, 500])("publishes each replay batch once (batch size: %i)", (batchSize) =>
625 Effect.gen(function* () {
626 const h = yield* makeHarness();
627 const unmount = h.registry.mount(h.stateAtom);
628 const first = yield* Queue.take(h.subscriptions);
629 let updates = 0;
630 const stop = h.registry.subscribe(h.details.messagesAtom(h.ref), () => updates++, {
631 immediate: true,
632 });
633 updates = 0;
634 const events: OrchestrationThreadStreamItem[] = Array.from({ length: 500 }, (_, index) => ({
635 kind: "event",
636 event: {
637 type: "thread.message-sent",
638 sequence: 8 + index,
639 eventId: EventId.make(`replay-${index}`),
640 aggregateKind: "thread",
641 aggregateId: THREAD_ID,
642 occurredAt: THREAD.createdAt,
643 commandId: null,
644 causationEventId: null,
645 correlationId: null,
646 metadata: {},
647 payload: {
648 threadId: THREAD_ID,
649 messageId: MessageId.make("replayed-message"),
650 role: "assistant",
651 text: `${index},`,
652 turnId: null,
653 streaming: true,
654 createdAt: THREAD.createdAt,
655 updatedAt: THREAD.createdAt,
656 },
657 },
658 }));
659 for (let offset = 0; offset < events.length; offset += batchSize) {
660 yield* Queue.offerAll(first.events, events.slice(offset, offset + batchSize));
661 const last = Math.min(offset + batchSize, events.length) - 1;
662 yield* observeState(
663 h.registry,
664 h.stateAtom,
665 (state) => Option.getOrNull(state.data)?.messages[0]?.text.endsWith(`${last},`) === true,
666 );
667 }
668 yield* Queue.offerAll(first.events, [events[499]!, events[0]!]);
669 yield* Queue.offer(first.events, { kind: "synchronized" });
670 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
671 expect(currentThread(h.registry, h.stateAtom).messages[0]?.text).toBe(
672 Array.from({ length: 500 }, (_, index) => `${index},`).join(""),
673 );
674 expect(updates).toBe(Math.ceil(500 / batchSize));
675 stop();
676 unmount();
677 yield* Deferred.await(first.closed);
678 const remount = h.registry.mount(h.stateAtom);
679 const next = yield* Queue.take(h.subscriptions);
680 expect(next.afterSequence).toBe(507);
681 remount();
682 yield* Deferred.await(next.closed);
683 }),
684 );
685​
686 it.effect("keeps warm data and resumes a completed cursor without loading another snapshot", () =>
687 Effect.gen(function* () {
688 const h = yield* makeHarness();
689 const unmount = h.registry.mount(h.stateAtom);
690 const first = yield* Queue.take(h.subscriptions);
691 yield* Queue.offer(first.events, {
692 kind: "event",
693 event: {
694 type: "thread.message-sent",
695 sequence: 8,
696 eventId: EventId.make("message-1"),
697 aggregateKind: "thread",
698 aggregateId: THREAD_ID,
699 occurredAt: THREAD.createdAt,
700 commandId: null,
701 causationEventId: null,
702 correlationId: null,
703 metadata: {},
704 payload: {
705 threadId: THREAD_ID,
706 messageId: MessageId.make("message-1"),
707 role: "assistant",
708 text: "Retained text",
709 turnId: null,
710 streaming: true,
711 createdAt: THREAD.createdAt,
712 updatedAt: THREAD.createdAt,
713 },
714 },
715 });
716 yield* Queue.offer(first.events, { kind: "synchronized" });
717 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
718 const before = currentThread(h.registry, h.stateAtom);
719 unmount();
720 yield* Deferred.await(first.closed);
721 const remount = h.registry.mount(h.stateAtom);
722 expect(currentThread(h.registry, h.stateAtom)).toBe(before);
723 const next = yield* Queue.take(h.subscriptions);
724 expect(next.afterSequence).toBe(8);
725 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
726 remount();
727 yield* Deferred.await(next.closed);
728 }),
729 );
730​
731 it.effect.each([
732 { replayed: false, statuses: ["live"] },
733 { replayed: true, statuses: ["live", "synchronizing", "live"] },
734 ])(
735 "keeps a warm resume live until it replays events (replayed: $replayed)",
736 ({ replayed, statuses }) =>
737 Effect.gen(function* () {
738 const h = yield* makeHarness({ connected: true });
739 const unmount = h.registry.mount(h.stateAtom);
740 const first = yield* Queue.take(h.subscriptions);
741 yield* Queue.offer(first.events, { kind: "synchronized" });
742 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
743 unmount();
744 yield* Deferred.await(first.closed);
745​
746 const observed: Array<EnvironmentThreadState["status"]> = [];
747 const stop = h.registry.subscribe(h.stateAtom, (state) => observed.push(state.status), {
748 immediate: true,
749 });
750 const remount = h.registry.mount(h.stateAtom);
751 const next = yield* Queue.take(h.subscriptions);
752 expect(next.afterSequence).toBe(7);
753 if (replayed) {
754 yield* Queue.offer(next.events, {
755 kind: "snapshot",
756 snapshot: { snapshotSequence: 9, thread: { ...THREAD, title: "Replayed" } },
757 });
758 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "synchronizing");
759 }
760 yield* Queue.offer(next.events, { kind: "synchronized" });
761 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
762 expect(observed.filter((status, index) => observed[index - 1] !== status)).toEqual(
763 statuses,
764 );
765 stop();
766 remount();
767 yield* Deferred.await(next.closed);
768 }),
769 );
770​
771 it.effect("downgrades a warm resume when the connection dropped while away", () =>
772 Effect.gen(function* () {
773 const h = yield* makeHarness({ connected: true });
774 const unmount = h.registry.mount(h.stateAtom);
775 const first = yield* Queue.take(h.subscriptions);
776 yield* Queue.offer(first.events, { kind: "synchronized" });
777 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
778 unmount();
779 yield* Deferred.await(first.closed);
780​
781 yield* SubscriptionRef.set(h.sessionRef, Option.none());
782 yield* SubscriptionRef.set(h.connectionState, AVAILABLE_CONNECTION_STATE);
783 const remount = h.registry.mount(h.stateAtom);
784 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "cached");
785 expect(currentThread(h.registry, h.stateAtom)).toBe(THREAD);
786 expect(h.counts().opened).toBe(1);
787​
788 yield* SubscriptionRef.set(h.connectionState, CONNECTED_STATE);
789 yield* SubscriptionRef.set(h.sessionRef, Option.some(h.session));
790 const next = yield* Queue.take(h.subscriptions);
791 expect(next.afterSequence).toBe(7);
792 expect(h.registry.get(h.stateAtom).status).toBe("synchronizing");
793 yield* Queue.offer(next.events, { kind: "synchronized" });
794 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
795 remount();
796 yield* Deferred.await(next.closed);
797 }),
798 );
799​
800 it.effect("keeps warm data when the raw atom family's weak entry is collected", () =>
801 Effect.gen(function* () {
802 const h = yield* makeHarness();
803 const oldRaw = h.rawAtoms.stateAtom(TARGET.environmentId, THREAD_ID);
804 const unmount = h.registry.mount(h.stateAtom);
805 const first = yield* Queue.take(h.subscriptions);
806 const latest = { ...THREAD, title: "Newer cached thread" };
807 yield* Queue.offer(first.events, {
808 kind: "snapshot",
809 snapshot: { snapshotSequence: 8, thread: latest },
810 });
811 yield* Queue.offer(first.events, { kind: "synchronized" });
812 yield* observeState(h.registry, h.stateAtom, (value) => value.status === "live");
813 unmount();
814 yield* Deferred.await(first.closed);
815​
816 // Force the weak-family miss without depending on host GC timing.
817 const deref = WeakRef.prototype.deref;
818 vi.spyOn(WeakRef.prototype, "deref").mockImplementation(function (this: WeakRef<object>) {
819 const value = deref.call(this);
820 return value === oldRaw ? undefined : value;
821 });
822 const remount = h.registry.mount(h.stateAtom);
823 expect(currentThread(h.registry, h.stateAtom)).toBe(latest);
824 const next = yield* Queue.take(h.subscriptions);
825 expect(next.afterSequence).toBe(8);
826 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
827 remount();
828 yield* Deferred.await(next.closed);
829 }),
830 );
831​
832 it.effect("keeps cached snapshots local to each registry", () =>
833 Effect.gen(function* () {
834 const h = yield* makeHarness();
835 const unmount = h.registry.mount(h.stateAtom);
836 const first = yield* Queue.take(h.subscriptions);
837 unmount();
838 yield* Deferred.await(first.closed);
839 const otherRegistry = yield* h.makeRegistry;
840 const unmountOther = otherRegistry.mount(h.stateAtom);
841 const other = yield* Queue.take(h.subscriptions);
842 expect(h.counts()).toEqual({ httpLoads: 2, diskLoads: 2, opened: 2, active: 1 });
843 unmountOther();
844 yield* Deferred.await(other.closed);
845 }),
846 );
847​
848 it.effect("expires the plain snapshot after five idle minutes", () =>
849 Effect.gen(function* () {
850 vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
851 const h = yield* makeHarness();
852 const unmount = h.registry.mount(h.stateAtom);
853 const first = yield* Queue.take(h.subscriptions);
854 unmount();
855 yield* Deferred.await(first.closed);
856 yield* Effect.yieldNow;
857 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(THREAD_SNAPSHOT_IDLE_TTL_MS + 1));
858 const remount = h.registry.mount(h.stateAtom);
859 const next = yield* Queue.take(h.subscriptions);
860 expect(h.counts()).toEqual({ httpLoads: 2, diskLoads: 2, opened: 2, active: 1 });
861 remount();
862 yield* Deferred.await(next.closed);
863 }),
864 );
865​
866 it.effect("cancels older-page work on unmount and permits it again on a warm return", () =>
867 Effect.gen(function* () {
868 const h = yield* makeHarness({
869 snapshot: {
870 ...SNAPSHOT,
871 page: { beforeCursor: "older-1", hasMore: true, snapshotSequence: 7 },
872 },
873 });
874 const unmount = h.registry.mount(h.stateAtom);
875 const first = yield* Queue.take(h.subscriptions);
876 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
877 const older = yield* Queue.take(h.olderLoads);
878 expect(Option.getOrThrow(h.registry.get(h.stateAtom).page).loadingOlder).toBe(true);
879 unmount();
880 yield* Deferred.await(first.closed);
881 yield* Deferred.await(older.closed);
882 const remount = h.registry.mount(h.stateAtom);
883 const next = yield* Queue.take(h.subscriptions);
884 expect(Option.getOrThrow(h.registry.get(h.stateAtom).page).loadingOlder).toBe(false);
885 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
886 const retried = yield* Queue.take(h.olderLoads);
887 expect(retried.window.beforeCursor).toBe("older-1");
888 expect(h.counts().httpLoads).toBe(1);
889 remount();
890 yield* Deferred.await(next.closed);
891 yield* Deferred.await(retried.closed);
892 }),
893 );
894});