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