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

threads-atoms.test.ts

451 lines16.9 KB

1import {
2 EnvironmentId,
3 EventId,
4 ORCHESTRATION_V2_WS_METHODS,
5 TurnItemId,
6 type OrchestrationV2ThreadHistoryPage,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2ThreadDetailSnapshot,
9 type OrchestrationV2ThreadStreamItem,
10} from "@t3tools/contracts";
11import { afterEach, describe, expect, it, vi } from "@effect/vitest";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import { HttpClient, HttpClientResponse } from "effect/http";
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/reactivity";
22​
23import type { ConnectionCatalogEntry } from "../connection/catalog.ts";
24import * as EnvironmentRegistry from "../connection/registry.ts";
25import {
26 AVAILABLE_CONNECTION_STATE,
27 PrimaryConnectionTarget,
28 type NetworkStatus,
29 type PreparedConnection,
30} from "../connection/model.ts";
31import * as EnvironmentSupervisor from "../connection/supervisor.ts";
32import * as Persistence from "../platform/persistence.ts";
33import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
34import type { RpcSession } from "../rpc/session.ts";
35import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
36import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
37import * as ThreadHistoryController from "./threadHistoryController.ts";
38import { createEnvironmentThreadStateAtoms, type EnvironmentThreadState } from "./threads.ts";
39import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
40​
41const TARGET = new PrimaryConnectionTarget({
42 environmentId: EnvironmentId.make("environment-1"),
43 label: "Test environment",
44 httpBaseUrl: "https://environment.example.test",
45 wsBaseUrl: "wss://environment.example.test",
46});
47const THREAD_ID = v2ThreadId;
48const THREAD: OrchestrationV2ThreadProjection = {
49 ...v2Projection,
50 thread: { ...v2Projection.thread, title: "Cached thread" },
51};
52const SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = { snapshotSequence: 7, projection: THREAD };
53​
54const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?: {
55 readonly snapshot?: OrchestrationV2ThreadDetailSnapshot;
56 readonly snapshotUnavailable?: boolean;
57}) {
58 const subscriptions = yield* Queue.unbounded<{
59 readonly afterSequence: number | undefined;
60 readonly events: Queue.Queue<OrchestrationV2ThreadStreamItem>;
61 readonly closed: Deferred.Deferred<void>;
62 }>();
63 const olderLoads = yield* Queue.unbounded<{
64 readonly cursor: string | null;
65 readonly response: Deferred.Deferred<OrchestrationV2ThreadHistoryPage>;
66 readonly closed: Deferred.Deferred<void>;
67 }>();
68 const snapshot = options?.snapshot ?? SNAPSHOT;
69 let httpLoads = 0;
70 let diskLoads = 0;
71 let opened = 0;
72 let active = 0;
73 const client = {
74 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) =>
75 Stream.unwrap(
76 Effect.gen(function* () {
77 const events = yield* Queue.unbounded<OrchestrationV2ThreadStreamItem>();
78 const closed = yield* Deferred.make<void>();
79 yield* Effect.acquireRelease(
80 Effect.sync(() => {
81 opened += 1;
82 active += 1;
83 }),
84 () =>
85 Effect.sync(() => {
86 active -= 1;
87 }).pipe(Effect.andThen(Deferred.succeed(closed, undefined))),
88 );
89 yield* Queue.offer(subscriptions, { afterSequence: input.afterSequence, events, closed });
90 return Stream.fromQueue(events);
91 }),
92 ),
93 } as unknown as WsRpcProtocolClient;
94 const session: RpcSession = {
95 client,
96 initialConfig: Effect.succeed({
97 threadResumeCompletionMarker: true,
98 threadSnapshotPagination: true,
99 } as never),
100 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
101 ready: Effect.void,
102 probe: Effect.void,
103 closed: Effect.never,
104 };
105 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
106 target: TARGET,
107 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
108 session: yield* SubscriptionRef.make(Option.some(session)),
109 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
110 Option.some({
111 environmentId: TARGET.environmentId,
112 label: TARGET.label,
113 httpBaseUrl: TARGET.httpBaseUrl,
114 socketUrl: TARGET.wsBaseUrl,
115 httpAuthorization: null,
116 target: TARGET,
117 }),
118 ),
119 connect: Effect.void,
120 disconnect: Effect.void,
121 retryNow: Effect.void,
122 });
123 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
124 entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
125 new Map(),
126 ),
127 networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
128 start: Effect.void,
129 register: () => Effect.die("Unexpected environment registration"),
130 registerPlatform: () => Effect.die("Unexpected environment registration"),
131 reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),
132 remove: () => Effect.die("Unexpected environment removal"),
133 removeRoute: () => Effect.die("Unexpected route removal"),
134 reorderRoutes: () => Effect.die("Unexpected route reorder"),
135 removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
136 retryNow: () => Effect.void,
137 setEnabled: () => Effect.die("Unexpected environment toggle"),
138 setCompatibility: () => Effect.die("Unexpected compatibility update"),
139 state: () => SubscriptionRef.get(supervisor.state),
140 stateChanges: () => SubscriptionRef.changes(supervisor.state),
141 run: (_environmentId, effect) =>
142 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
143 runStream: (_environmentId, stream) =>
144 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
145 followStream: (_environmentId, stream) =>
146 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
147 });
148 const historyController = yield* Effect.service(
149 ThreadHistoryController.ThreadHistoryController,
150 ).pipe(Effect.provide(ThreadHistoryController.layer));
151 const historyHttpClient = HttpClient.make((request, url) =>
152 Effect.gen(function* () {
153 const response = yield* Deferred.make<OrchestrationV2ThreadHistoryPage>();
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 const page = yield* Deferred.await(response);
158 return HttpClientResponse.fromWeb(request, Response.json(page));
159 }).pipe(Effect.scoped),
160 );
161 const runtime = Atom.runtime(
162 Layer.mergeAll(
163 Layer.succeed(ThreadHistoryController.ThreadHistoryController, historyController),
164 Layer.succeed(HttpClient.HttpClient, historyHttpClient),
165 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
166 Layer.succeed(
167 Persistence.EnvironmentCacheStore,
168 Persistence.EnvironmentCacheStore.of({
169 loadShell: () => Effect.succeedNone,
170 saveShell: () => Effect.void,
171 loadThread: () =>
172 Effect.sync(() => {
173 diskLoads += 1;
174 return Option.none();
175 }),
176 saveThread: () => Effect.void,
177 removeThread: () => Effect.void,
178 loadServerConfig: () => Effect.succeedNone,
179 saveServerConfig: () => Effect.void,
180 loadVcsRefs: () => Effect.succeedNone,
181 saveVcsRefs: () => Effect.void,
182 removeVcsRefs: () => Effect.void,
183 clearVcsRefs: () => Effect.void,
184 clear: () => Effect.void,
185 }),
186 ),
187 Layer.succeed(
188 ThreadSnapshotLoader.ThreadSnapshotLoader,
189 ThreadSnapshotLoader.ThreadSnapshotLoader.of({
190 load: () =>
191 Effect.sync(() => {
192 httpLoads += 1;
193 if (options?.snapshotUnavailable === true) {
194 return { _tag: "unavailable" as const };
195 }
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 );
249​
250function currentThread(
251 registry: AtomRegistry.AtomRegistry,
252 atom: Atom.Atom<EnvironmentThreadState>,
253) {
254 return Option.getOrThrow(registry.get(atom).data);
256​
257describe("createEnvironmentThreadStateAtoms", () => {
258 afterEach(() => {
259 vi.useRealTimers();
260 vi.restoreAllMocks();
261 });
262​
263 it.effect("keeps warm data and resumes a completed cursor without loading another snapshot", () =>
264 Effect.gen(function* () {
265 const h = yield* makeHarness();
266 const unmount = h.registry.mount(h.stateAtom);
267 const first = yield* Queue.take(h.subscriptions);
268 yield* Queue.offer(first.events, {
269 kind: "event",
270 sequence: 8,
271 event: {
272 id: EventId.make("metadata-1"),
273 type: "thread.metadata-updated",
274 threadId: THREAD_ID,
275 occurredAt: THREAD.thread.updatedAt,
276 payload: { ...THREAD.thread, title: "Retained title" },
277 },
278 });
279 yield* Queue.offer(first.events, { kind: "synchronized" });
280 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
281 const before = currentThread(h.registry, h.stateAtom);
282 unmount();
283 yield* Deferred.await(first.closed);
284 const remount = h.registry.mount(h.stateAtom);
285 expect(currentThread(h.registry, h.stateAtom)).toBe(before);
286 const next = yield* Queue.take(h.subscriptions);
287 expect(next.afterSequence).toBe(8);
288 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
289 remount();
290 yield* Deferred.await(next.closed);
291 }),
292 );
293​
294 it.effect("cancels older-page work on unmount and permits it again on a warm return", () =>
295 Effect.gen(function* () {
296 const h = yield* makeHarness({
297 snapshot: {
298 ...SNAPSHOT,
299 historyCursor: "older-1",
300 hasMoreHistory: true,
301 },
302 });
303 const unmount = h.registry.mount(h.stateAtom);
304 const first = yield* Queue.take(h.subscriptions);
305 const loading = yield* h.loadEarlier().pipe(Effect.forkScoped);
306 const older = yield* Queue.take(h.olderLoads);
307 expect(h.registry.get(h.stateAtom).history.loading).toBe(true);
308 unmount();
309 yield* Deferred.await(first.closed);
310 yield* Deferred.await(older.closed);
311 yield* Fiber.await(loading);
312 const remount = h.registry.mount(h.stateAtom);
313 const next = yield* Queue.take(h.subscriptions);
314 expect(h.registry.get(h.stateAtom).history.loading).toBe(false);
315 const retrying = yield* h.loadEarlier().pipe(Effect.forkScoped);
316 const retried = yield* Queue.take(h.olderLoads);
317 expect(retried.cursor).toBe("older-1");
318 expect(h.counts().httpLoads).toBe(1);
319 remount();
320 yield* Deferred.await(next.closed);
321 yield* Deferred.await(retried.closed);
322 yield* Fiber.await(retrying);
323 }),
324 );
325​
326 it.effect(
327 "merges older history after an HTTP failure falls back to a bounded socket snapshot",
328 () =>
329 Effect.gen(function* () {
330 const h = yield* makeHarness({ snapshotUnavailable: true });
331 const unmount = h.registry.mount(h.stateAtom);
332 const subscription = yield* Queue.take(h.subscriptions);
333 expect(subscription.afterSequence).toBeUndefined();
334​
335 yield* Queue.offer(subscription.events, {
336 kind: "snapshot",
337 snapshotSequence: 12,
338 projection: THREAD,
339 historyCursor: "socket-older-1",
340 hasMoreHistory: true,
341 latestLocalTurnOrdinal: 4,
342 });
343 yield* Queue.offer(subscription.events, { kind: "synchronized" });
344 yield* observeState(
345 h.registry,
346 h.stateAtom,
347 (state) => state.status === "live" && state.history.historyCursor === "socket-older-1",
348 );
349​
350 const loading = yield* h.loadEarlier().pipe(Effect.forkScoped);
351 const request = yield* Queue.take(h.olderLoads);
352 expect(request.cursor).toBe("socket-older-1");
353 const olderItem = {
354 id: TurnItemId.make("socket-fallback-older-item"),
355 type: "command_execution" as const,
356 threadId: THREAD_ID,
357 runId: null,
358 nodeId: null,
359 providerThreadId: null,
360 providerTurnId: null,
361 nativeItemRef: null,
362 parentItemId: null,
363 ordinal: 1,
364 status: "completed" as const,
365 title: "Earlier command",
366 input: "pwd",
367 output: "/workspace",
368 exitCode: 0,
369 startedAt: THREAD.thread.createdAt,
370 completedAt: THREAD.thread.createdAt,
371 updatedAt: THREAD.thread.createdAt,
372 };
373 yield* Deferred.succeed(request.response, {
374 snapshotSequence: 12,
375 items: [
376 {
377 position: 0,
378 visibility: "local",
379 sourceThreadId: THREAD_ID,
380 sourceItemId: olderItem.id,
381 item: olderItem,
382 },
383 ],
384 nextCursor: null,
385 hasMoreHistory: false,
386 });
387 expect(yield* Fiber.join(loading)).toEqual({ _tag: "loaded" });
388​
389 const state = h.registry.get(h.stateAtom);
390 expect(
391 Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId),
392 ).toEqual([olderItem.id]);
393 expect(state.history).toMatchObject({
394 historyCursor: null,
395 hasMoreHistory: false,
396 loading: false,
397 error: null,
398 expanded: true,
399 latestLocalTurnOrdinal: 4,
400 });
401 expect(h.counts().httpLoads).toBe(1);
402​
403 unmount();
404 yield* Deferred.await(subscription.closed);
405 }),
406 );
407});
408​
409it.effect("keeps snapshot boundaries and completion markers ordered inside a replay batch", () =>
410 Effect.gen(function* () {
411 const h = yield* makeHarness();
412 const unmount = h.registry.mount(h.stateAtom);
413 const first = yield* Queue.take(h.subscriptions);
414 const title = (sequence: number, value: string): OrchestrationV2ThreadStreamItem => ({
415 kind: "event",
416 sequence,
417 event: {
418 id: EventId.make(`batch-title-${sequence}`),
419 type: "thread.metadata-updated",
420 threadId: THREAD_ID,
421 occurredAt: THREAD.thread.updatedAt,
422 payload: { ...THREAD.thread, title: value },
423 },
424 });
425 yield* Queue.offerAll(first.events, [
426 title(8, "Before snapshot"),
427 {
428 kind: "snapshot",
429 snapshotSequence: 20,
430 projection: THREAD,
431 historyCursor: "older-batch",
432 hasMoreHistory: true,
433 latestLocalTurnOrdinal: 10,
434 },
435 title(21, "After snapshot"),
436 title(19, "Stale replay"),
437 { kind: "synchronized" },
438 ]);
439 const state = yield* observeState(h.registry, h.stateAtom, (value) => value.status === "live");
440 expect(Option.getOrThrow(state.data).thread.title).toBe("After snapshot");
441 expect(state.history.historyCursor).toBe("older-batch");
442 expect(state.history.latestLocalTurnOrdinal).toBe(10);
443 unmount();
444 yield* Deferred.await(first.closed);
445 const remount = h.registry.mount(h.stateAtom);
446 const next = yield* Queue.take(h.subscriptions);
447 expect(next.afterSequence).toBe(21);
448 remount();
449 yield* Deferred.await(next.closed);
450 }),
451);