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 Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import { Atom, AtomRegistry } from "effect/unstable/reactivity";
22
23import type { ConnectionCatalogEntry } from "../connection/catalog.ts";
24import { EnvironmentRegistry } from "../connection/registry.ts";
25import {
26 AVAILABLE_CONNECTION_STATE,
27 PrimaryConnectionTarget,
28 type NetworkStatus,
29 type PreparedConnection,
30} from "../connection/model.ts";
31import { EnvironmentSupervisor } from "../connection/supervisor.ts";
32import { EnvironmentCacheStore } from "../platform/persistence.ts";
33import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
34import type { RpcSession } from "../rpc/session.ts";
35import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
36import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";
37import type { ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
38import {
39 createEnvironmentThreadStateAtoms,
40 requestOlderThreadTurns,
41 ThreadSnapshotLoader,
42 type EnvironmentThreadState,
43} from "./threads.ts";
44
45const TARGET = new PrimaryConnectionTarget({
46 environmentId: EnvironmentId.make("environment-1"),
47 label: "Test environment",
48 httpBaseUrl: "https://environment.example.test",
49 wsBaseUrl: "wss://environment.example.test",
50});
51const THREAD_ID = ThreadId.make("thread-1");
52const THREAD: OrchestrationThread = {
53 id: THREAD_ID,
54 projectId: ProjectId.make("project-1"),
55 title: "Cached thread",
56 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
57 runtimeMode: "full-access",
58 interactionMode: "default",
59 branch: "main",
60 worktreePath: null,
61 latestTurn: null,
62 createdAt: "2026-04-01T00:00:00.000Z",
63 updatedAt: "2026-04-01T00:00:00.000Z",
64 archivedAt: null,
65 settledOverride: null,
66 settledAt: null,
67 deletedAt: null,
68 messages: [],
69 proposedPlans: [],
70 activities: [],
71 checkpoints: [],
72 session: null,
73};
74const SNAPSHOT: OrchestrationThreadDetailSnapshot = { snapshotSequence: 7, thread: THREAD };
75
76const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?: {
77 readonly snapshot?: OrchestrationThreadDetailSnapshot;
78}) {
79 const subscriptions = yield* Queue.unbounded<{
80 readonly afterSequence: number | undefined;
81 readonly events: Queue.Queue<OrchestrationThreadStreamItem>;
82 readonly closed: Deferred.Deferred<void>;
83 }>();
84 const olderLoads = yield* Queue.unbounded<{
85 readonly window: ThreadSnapshotWindow;
86 readonly response: Deferred.Deferred<Option.Option<OrchestrationThreadDetailSnapshot>>;
87 readonly closed: Deferred.Deferred<void>;
88 }>();
89 const snapshot = options?.snapshot ?? SNAPSHOT;
90 let httpLoads = 0;
91 let diskLoads = 0;
92 let opened = 0;
93 let active = 0;
94 const client = {
95 [ORCHESTRATION_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) =>
96 Stream.unwrap(
97 Effect.gen(function* () {
98 const events = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
99 const closed = yield* Deferred.make<void>();
100 yield* Effect.acquireRelease(
101 Effect.sync(() => {
102 opened += 1;
103 active += 1;
104 }),
105 () =>
106 Effect.sync(() => {
107 active -= 1;
108 }).pipe(Effect.andThen(Deferred.succeed(closed, undefined))),
109 );
110 yield* Queue.offer(subscriptions, { afterSequence: input.afterSequence, events, closed });
111 return Stream.fromQueue(events);
112 }),
113 ),
114 } as unknown as WsRpcProtocolClient;
115 const session: RpcSession = {
116 client,
117 initialConfig: Effect.succeed({
118 threadResumeCompletionMarker: true,
119 threadSnapshotPagination: true,
120 } as never),
121 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
122 ready: Effect.void,
123 probe: Effect.void,
124 closed: Effect.never,
125 };
126 const supervisor = EnvironmentSupervisor.of({
127 target: TARGET,
128 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
129 session: yield* SubscriptionRef.make(Option.some(session)),
130 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
131 Option.some({
132 environmentId: TARGET.environmentId,
133 label: TARGET.label,
134 httpBaseUrl: TARGET.httpBaseUrl,
135 socketUrl: TARGET.wsBaseUrl,
136 httpAuthorization: null,
137 target: TARGET,
138 }),
139 ),
140 connect: Effect.void,
141 disconnect: Effect.void,
142 retryNow: Effect.void,
143 });
144 const environmentRegistry = EnvironmentRegistry.of({
145 entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
146 new Map(),
147 ),
148 networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
149 start: Effect.void,
150 register: () => Effect.die("Unexpected environment registration"),
151 registerPlatform: () => Effect.die("Unexpected environment registration"),
152 reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),
153 remove: () => Effect.die("Unexpected environment removal"),
154 removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
155 retryNow: () => Effect.void,
156 state: () => SubscriptionRef.get(supervisor.state),
157 stateChanges: () => SubscriptionRef.changes(supervisor.state),
158 run: (_environmentId, effect) =>
159 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
160 runStream: (_environmentId, stream) =>
161 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
162 followStream: (_environmentId, stream) =>
163 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
164 });
165 const runtime = Atom.runtime(
166 Layer.mergeAll(
167 Layer.succeed(EnvironmentRegistry, environmentRegistry),
168 Layer.succeed(
169 EnvironmentCacheStore,
170 EnvironmentCacheStore.of({
171 loadShell: () => Effect.succeed(Option.none()),
172 saveShell: () => Effect.void,
173 loadThread: () =>
174 Effect.sync(() => {
175 diskLoads += 1;
176 return Option.none();
177 }),
178 saveThread: () => Effect.void,
179 removeThread: () => Effect.void,
180 loadServerConfig: () => Effect.succeed(Option.none()),
181 saveServerConfig: () => Effect.void,
182 loadVcsRefs: () => Effect.succeed(Option.none()),
183 saveVcsRefs: () => Effect.void,
184 removeVcsRefs: () => Effect.void,
185 clearVcsRefs: () => Effect.void,
186 clear: () => Effect.void,
187 }),
188 ),
189 Layer.succeed(
190 ThreadSnapshotLoader,
191 ThreadSnapshotLoader.of({
192 load: (_prepared, _threadId, window) => {
193 if (window?.beforeCursor === undefined) {
194 return Effect.sync(() => {
195 httpLoads += 1;
196 return Option.some(snapshot);
197 });
198 }
199 return Effect.gen(function* () {
200 const response =
201 yield* Deferred.make<Option.Option<OrchestrationThreadDetailSnapshot>>();
202 const closed = yield* Deferred.make<void>();
203 yield* Effect.addFinalizer(() => Deferred.succeed(closed, undefined));
204 yield* Queue.offer(olderLoads, { window, response, closed });
205 return yield* Deferred.await(response);
206 }).pipe(Effect.scoped);
207 },
208 }),
209 ),
210 ),
211 );
212 const raw = createEnvironmentThreadStateAtoms(runtime);
213 const details = createEnvironmentThreadDetailAtoms(raw.stateAtom);
214 const ref = { environmentId: TARGET.environmentId, threadId: THREAD_ID };
215 const stateAtom = details.stateAtom(ref);
216 const makeRegistry = Effect.acquireRelease(
217 Effect.sync(() => AtomRegistry.make({ defaultIdleTTL: 60_000, timeoutResolution: 1 })),
218 (registry) => Effect.sync(() => registry.dispose()),
219 );
220 const registry = yield* makeRegistry;
221
222 return {
223 registry,
224 makeRegistry,
225 rawAtoms: raw,
226 stateAtom,
227 details,
228 ref,
229 subscriptions,
230 olderLoads,
231 counts: () => ({ httpLoads, diskLoads, opened, active }),
232 };
233});
234
235function observeState(
236 registry: AtomRegistry.AtomRegistry,
237 atom: Atom.Atom<EnvironmentThreadState>,
238 predicate: (state: EnvironmentThreadState) => boolean,
239) {
240 return AtomRegistry.toStream(registry, atom).pipe(
241 Stream.filter(predicate),
242 Stream.runHead,
243 Effect.map(Option.getOrThrow),
244 );
245}
246
247function currentThread(
248 registry: AtomRegistry.AtomRegistry,
249 atom: Atom.Atom<EnvironmentThreadState>,
250) {
251 return Option.getOrThrow(registry.get(atom).data);
252}
253
254describe("createEnvironmentThreadStateAtoms", () => {
255 afterEach(() => {
256 vi.useRealTimers();
257 vi.restoreAllMocks();
258 });
259
260 it.effect("shares one live stream and closes it after the last detail consumer leaves", () =>
261 Effect.gen(function* () {
262 const h = yield* makeHarness();
263 const unmountMessages = h.registry.mount(h.details.messagesAtom(h.ref));
264 const first = yield* Queue.take(h.subscriptions);
265 const unmountStatus = h.registry.mount(h.details.statusAtom(h.ref));
266 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 1, active: 1 });
267 unmountMessages();
268 yield* Queue.offer(first.events, { kind: "synchronized" });
269 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
270 expect(h.counts().active).toBe(1);
271 unmountStatus();
272 yield* Deferred.await(first.closed);
273 expect(h.counts().active).toBe(0);
274 }),
275 );
276
277 it.effect("keeps warm data and resumes a completed cursor without loading another snapshot", () =>
278 Effect.gen(function* () {
279 const h = yield* makeHarness();
280 const unmount = h.registry.mount(h.stateAtom);
281 const first = yield* Queue.take(h.subscriptions);
282 yield* Queue.offer(first.events, {
283 kind: "event",
284 event: {
285 type: "thread.message-sent",
286 sequence: 8,
287 eventId: EventId.make("message-1"),
288 aggregateKind: "thread",
289 aggregateId: THREAD_ID,
290 occurredAt: THREAD.createdAt,
291 commandId: null,
292 causationEventId: null,
293 correlationId: null,
294 metadata: {},
295 payload: {
296 threadId: THREAD_ID,
297 messageId: MessageId.make("message-1"),
298 role: "assistant",
299 text: "Retained text",
300 turnId: null,
301 streaming: true,
302 createdAt: THREAD.createdAt,
303 updatedAt: THREAD.createdAt,
304 },
305 },
306 });
307 yield* Queue.offer(first.events, { kind: "synchronized" });
308 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
309 const before = currentThread(h.registry, h.stateAtom);
310 unmount();
311 yield* Deferred.await(first.closed);
312 const remount = h.registry.mount(h.stateAtom);
313 expect(currentThread(h.registry, h.stateAtom)).toBe(before);
314 const next = yield* Queue.take(h.subscriptions);
315 expect(next.afterSequence).toBe(8);
316 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
317 remount();
318 yield* Deferred.await(next.closed);
319 }),
320 );
321
322 it.effect("keeps warm data when the raw atom family's weak entry is collected", () =>
323 Effect.gen(function* () {
324 const h = yield* makeHarness();
325 const oldRaw = h.rawAtoms.stateAtom(TARGET.environmentId, THREAD_ID);
326 const unmount = h.registry.mount(h.stateAtom);
327 const first = yield* Queue.take(h.subscriptions);
328 const latest = { ...THREAD, title: "Newer cached thread" };
329 yield* Queue.offer(first.events, {
330 kind: "snapshot",
331 snapshot: { snapshotSequence: 8, thread: latest },
332 });
333 yield* Queue.offer(first.events, { kind: "synchronized" });
334 yield* observeState(h.registry, h.stateAtom, (value) => value.status === "live");
335 unmount();
336 yield* Deferred.await(first.closed);
337
338 // Force the weak-family miss without depending on host GC timing.
339 const deref = WeakRef.prototype.deref;
340 vi.spyOn(WeakRef.prototype, "deref").mockImplementation(function (this: WeakRef<object>) {
341 const value = deref.call(this);
342 return value === oldRaw ? undefined : value;
343 });
344 const remount = h.registry.mount(h.stateAtom);
345 expect(currentThread(h.registry, h.stateAtom)).toBe(latest);
346 const next = yield* Queue.take(h.subscriptions);
347 expect(next.afterSequence).toBe(8);
348 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
349 remount();
350 yield* Deferred.await(next.closed);
351 }),
352 );
353
354 it.effect("keeps cached snapshots local to each registry", () =>
355 Effect.gen(function* () {
356 const h = yield* makeHarness();
357 const unmount = h.registry.mount(h.stateAtom);
358 const first = yield* Queue.take(h.subscriptions);
359 unmount();
360 yield* Deferred.await(first.closed);
361 const otherRegistry = yield* h.makeRegistry;
362 const unmountOther = otherRegistry.mount(h.stateAtom);
363 const other = yield* Queue.take(h.subscriptions);
364 expect(h.counts()).toEqual({ httpLoads: 2, diskLoads: 2, opened: 2, active: 1 });
365 unmountOther();
366 yield* Deferred.await(other.closed);
367 }),
368 );
369
370 it.effect("expires the plain snapshot after five idle minutes", () =>
371 Effect.gen(function* () {
372 vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
373 const h = yield* makeHarness();
374 const unmount = h.registry.mount(h.stateAtom);
375 const first = yield* Queue.take(h.subscriptions);
376 unmount();
377 yield* Deferred.await(first.closed);
378 yield* Effect.yieldNow;
379 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(THREAD_SNAPSHOT_IDLE_TTL_MS + 1));
380 const remount = h.registry.mount(h.stateAtom);
381 const next = yield* Queue.take(h.subscriptions);
382 expect(h.counts()).toEqual({ httpLoads: 2, diskLoads: 2, opened: 2, active: 1 });
383 remount();
384 yield* Deferred.await(next.closed);
385 }),
386 );
387
388 it.effect("cancels older-page work on unmount and permits it again on a warm return", () =>
389 Effect.gen(function* () {
390 const h = yield* makeHarness({
391 snapshot: {
392 ...SNAPSHOT,
393 page: { beforeCursor: "older-1", hasMore: true, snapshotSequence: 7 },
394 },
395 });
396 const unmount = h.registry.mount(h.stateAtom);
397 const first = yield* Queue.take(h.subscriptions);
398 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
399 const older = yield* Queue.take(h.olderLoads);
400 expect(Option.getOrThrow(h.registry.get(h.stateAtom).page).loadingOlder).toBe(true);
401 unmount();
402 yield* Deferred.await(first.closed);
403 yield* Deferred.await(older.closed);
404 const remount = h.registry.mount(h.stateAtom);
405 const next = yield* Queue.take(h.subscriptions);
406 expect(Option.getOrThrow(h.registry.get(h.stateAtom).page).loadingOlder).toBe(false);
407 expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
408 const retried = yield* Queue.take(h.olderLoads);
409 expect(retried.window.beforeCursor).toBe("older-1");
410 expect(h.counts().httpLoads).toBe(1);
411 remount();
412 yield* Deferred.await(next.closed);
413 yield* Deferred.await(retried.closed);
414 }),
415 );
416});