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

threads-atoms.test.ts

956 lines37.6 KB

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