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