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

threads-atoms.test.ts

452 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 inboundFrames: Effect.succeed(0),
104 closed: Effect.never,
105 };
106 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
107 target: TARGET,
108 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
109 session: yield* SubscriptionRef.make(Option.some(session)),
110 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
111 Option.some({
112 environmentId: TARGET.environmentId,
113 label: TARGET.label,
114 httpBaseUrl: TARGET.httpBaseUrl,
115 socketUrl: TARGET.wsBaseUrl,
116 httpAuthorization: null,
117 target: TARGET,
118 }),
119 ),
120 connect: Effect.void,
121 disconnect: Effect.void,
122 retryNow: Effect.void,
123 });
124 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
125 entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
126 new Map(),
127 ),
128 networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
129 start: Effect.void,
130 register: () => Effect.die("Unexpected environment registration"),
131 assertKnownAddress: () => Effect.die("Unexpected address check"),
132 reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),
133 remove: () => Effect.die("Unexpected environment removal"),
134 removeRoute: () => Effect.die("Unexpected route removal"),
135 reorderRoutes: () => Effect.die("Unexpected route reorder"),
136 removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
137 retryNow: () => Effect.void,
138 setEnabled: () => Effect.die("Unexpected environment toggle"),
139 setCompatibility: () => Effect.die("Unexpected compatibility update"),
140 state: () => SubscriptionRef.get(supervisor.state),
141 stateChanges: () => SubscriptionRef.changes(supervisor.state),
142 run: (_environmentId, effect) =>
143 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
144 runStream: (_environmentId, stream) =>
145 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
146 followStream: (_environmentId, stream) =>
147 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
148 });
149 const historyController = yield* Effect.service(
150 ThreadHistoryController.ThreadHistoryController,
151 ).pipe(Effect.provide(ThreadHistoryController.layer));
152 const historyHttpClient = HttpClient.make((request, url) =>
153 Effect.gen(function* () {
154 const response = yield* Deferred.make<OrchestrationV2ThreadHistoryPage>();
155 const closed = yield* Deferred.make<void>();
156 yield* Effect.addFinalizer(() => Deferred.succeed(closed, undefined));
157 yield* Queue.offer(olderLoads, { cursor: url.searchParams.get("cursor"), response, closed });
158 const page = yield* Deferred.await(response);
159 return HttpClientResponse.fromWeb(request, Response.json(page));
160 }).pipe(Effect.scoped),
161 );
162 const runtime = Atom.runtime(
163 Layer.mergeAll(
164 Layer.succeed(ThreadHistoryController.ThreadHistoryController, historyController),
165 Layer.succeed(HttpClient.HttpClient, historyHttpClient),
166 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
167 Layer.succeed(
168 Persistence.EnvironmentCacheStore,
169 Persistence.EnvironmentCacheStore.of({
170 loadShell: () => Effect.succeedNone,
171 saveShell: () => Effect.void,
172 loadThread: () =>
173 Effect.sync(() => {
174 diskLoads += 1;
175 return Option.none();
176 }),
177 saveThread: () => Effect.void,
178 removeThread: () => Effect.void,
179 loadServerConfig: () => Effect.succeedNone,
180 saveServerConfig: () => Effect.void,
181 loadVcsRefs: () => Effect.succeedNone,
182 saveVcsRefs: () => Effect.void,
183 removeVcsRefs: () => Effect.void,
184 clearVcsRefs: () => Effect.void,
185 clear: () => Effect.void,
186 }),
187 ),
188 Layer.succeed(
189 ThreadSnapshotLoader.ThreadSnapshotLoader,
190 ThreadSnapshotLoader.ThreadSnapshotLoader.of({
191 load: () =>
192 Effect.sync(() => {
193 httpLoads += 1;
194 if (options?.snapshotUnavailable === true) {
195 return { _tag: "unavailable" as const };
196 }
197 return {
198 _tag: "present" as const,
199 snapshot,
200 ...(snapshot.historyCursor === undefined
201 ? {}
202 : {
203 history: {
204 historyCursor: snapshot.historyCursor,
205 hasMoreHistory: snapshot.hasMoreHistory ?? false,
206 latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null,
207 },
208 }),
209 };
210 }),
211 }),
212 ),
213 ),
214 );
215 const raw = createEnvironmentThreadStateAtoms(runtime);
216 const details = createEnvironmentThreadDetailAtoms(raw.stateAtom);
217 const ref = { environmentId: TARGET.environmentId, threadId: THREAD_ID };
218 const stateAtom = details.stateAtom(ref);
219 const makeRegistry = Effect.acquireRelease(
220 Effect.sync(() => AtomRegistry.make({ defaultIdleTTL: 60_000, timeoutResolution: 1 })),
221 (registry) => Effect.sync(() => registry.dispose()),
222 );
223 const registry = yield* makeRegistry;
224​
225 return {
226 registry,
227 makeRegistry,
228 rawAtoms: raw,
229 stateAtom,
230 details,
231 ref,
232 subscriptions,
233 olderLoads,
234 loadEarlier: () => historyController.loadEarlier(TARGET.environmentId, THREAD_ID),
235 counts: () => ({ httpLoads, diskLoads, opened, active }),
236 };
237});
238​
239function observeState(
240 registry: AtomRegistry.AtomRegistry,
241 atom: Atom.Atom<EnvironmentThreadState>,
242 predicate: (state: EnvironmentThreadState) => boolean,
243) {
244 return AtomRegistry.toStream(registry, atom).pipe(
245 Stream.filter(predicate),
246 Stream.runHead,
247 Effect.map(Option.getOrThrow),
248 );
250​
251function currentThread(
252 registry: AtomRegistry.AtomRegistry,
253 atom: Atom.Atom<EnvironmentThreadState>,
254) {
255 return Option.getOrThrow(registry.get(atom).data);
257​
258describe("createEnvironmentThreadStateAtoms", () => {
259 afterEach(() => {
260 vi.useRealTimers();
261 vi.restoreAllMocks();
262 });
263​
264 it.effect("keeps warm data and resumes a completed cursor without loading another snapshot", () =>
265 Effect.gen(function* () {
266 const h = yield* makeHarness();
267 const unmount = h.registry.mount(h.stateAtom);
268 const first = yield* Queue.take(h.subscriptions);
269 yield* Queue.offer(first.events, {
270 kind: "event",
271 sequence: 8,
272 event: {
273 id: EventId.make("metadata-1"),
274 type: "thread.metadata-updated",
275 threadId: THREAD_ID,
276 occurredAt: THREAD.thread.updatedAt,
277 payload: { ...THREAD.thread, title: "Retained title" },
278 },
279 });
280 yield* Queue.offer(first.events, { kind: "synchronized" });
281 yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");
282 const before = currentThread(h.registry, h.stateAtom);
283 unmount();
284 yield* Deferred.await(first.closed);
285 const remount = h.registry.mount(h.stateAtom);
286 expect(currentThread(h.registry, h.stateAtom)).toBe(before);
287 const next = yield* Queue.take(h.subscriptions);
288 expect(next.afterSequence).toBe(8);
289 expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 2, active: 1 });
290 remount();
291 yield* Deferred.await(next.closed);
292 }),
293 );
294​
295 it.effect("cancels older-page work on unmount and permits it again on a warm return", () =>
296 Effect.gen(function* () {
297 const h = yield* makeHarness({
298 snapshot: {
299 ...SNAPSHOT,
300 historyCursor: "older-1",
301 hasMoreHistory: true,
302 },
303 });
304 const unmount = h.registry.mount(h.stateAtom);
305 const first = yield* Queue.take(h.subscriptions);
306 const loading = yield* h.loadEarlier().pipe(Effect.forkScoped);
307 const older = yield* Queue.take(h.olderLoads);
308 expect(h.registry.get(h.stateAtom).history.loading).toBe(true);
309 unmount();
310 yield* Deferred.await(first.closed);
311 yield* Deferred.await(older.closed);
312 yield* Fiber.await(loading);
313 const remount = h.registry.mount(h.stateAtom);
314 const next = yield* Queue.take(h.subscriptions);
315 expect(h.registry.get(h.stateAtom).history.loading).toBe(false);
316 const retrying = yield* h.loadEarlier().pipe(Effect.forkScoped);
317 const retried = yield* Queue.take(h.olderLoads);
318 expect(retried.cursor).toBe("older-1");
319 expect(h.counts().httpLoads).toBe(1);
320 remount();
321 yield* Deferred.await(next.closed);
322 yield* Deferred.await(retried.closed);
323 yield* Fiber.await(retrying);
324 }),
325 );
326​
327 it.effect(
328 "merges older history after an HTTP failure falls back to a bounded socket snapshot",
329 () =>
330 Effect.gen(function* () {
331 const h = yield* makeHarness({ snapshotUnavailable: true });
332 const unmount = h.registry.mount(h.stateAtom);
333 const subscription = yield* Queue.take(h.subscriptions);
334 expect(subscription.afterSequence).toBeUndefined();
335​
336 yield* Queue.offer(subscription.events, {
337 kind: "snapshot",
338 snapshotSequence: 12,
339 projection: THREAD,
340 historyCursor: "socket-older-1",
341 hasMoreHistory: true,
342 latestLocalTurnOrdinal: 4,
343 });
344 yield* Queue.offer(subscription.events, { kind: "synchronized" });
345 yield* observeState(
346 h.registry,
347 h.stateAtom,
348 (state) => state.status === "live" && state.history.historyCursor === "socket-older-1",
349 );
350​
351 const loading = yield* h.loadEarlier().pipe(Effect.forkScoped);
352 const request = yield* Queue.take(h.olderLoads);
353 expect(request.cursor).toBe("socket-older-1");
354 const olderItem = {
355 id: TurnItemId.make("socket-fallback-older-item"),
356 type: "command_execution" as const,
357 threadId: THREAD_ID,
358 runId: null,
359 nodeId: null,
360 providerThreadId: null,
361 providerTurnId: null,
362 nativeItemRef: null,
363 parentItemId: null,
364 ordinal: 1,
365 status: "completed" as const,
366 title: "Earlier command",
367 input: "pwd",
368 output: "/workspace",
369 exitCode: 0,
370 startedAt: THREAD.thread.createdAt,
371 completedAt: THREAD.thread.createdAt,
372 updatedAt: THREAD.thread.createdAt,
373 };
374 yield* Deferred.succeed(request.response, {
375 snapshotSequence: 12,
376 items: [
377 {
378 position: 0,
379 visibility: "local",
380 sourceThreadId: THREAD_ID,
381 sourceItemId: olderItem.id,
382 item: olderItem,
383 },
384 ],
385 nextCursor: null,
386 hasMoreHistory: false,
387 });
388 expect(yield* Fiber.join(loading)).toEqual({ _tag: "loaded" });
389​
390 const state = h.registry.get(h.stateAtom);
391 expect(
392 Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId),
393 ).toEqual([olderItem.id]);
394 expect(state.history).toMatchObject({
395 historyCursor: null,
396 hasMoreHistory: false,
397 loading: false,
398 error: null,
399 expanded: true,
400 latestLocalTurnOrdinal: 4,
401 });
402 expect(h.counts().httpLoads).toBe(1);
403​
404 unmount();
405 yield* Deferred.await(subscription.closed);
406 }),
407 );
408});
409​
410it.effect("keeps snapshot boundaries and completion markers ordered inside a replay batch", () =>
411 Effect.gen(function* () {
412 const h = yield* makeHarness();
413 const unmount = h.registry.mount(h.stateAtom);
414 const first = yield* Queue.take(h.subscriptions);
415 const title = (sequence: number, value: string): OrchestrationV2ThreadStreamItem => ({
416 kind: "event",
417 sequence,
418 event: {
419 id: EventId.make(`batch-title-${sequence}`),
420 type: "thread.metadata-updated",
421 threadId: THREAD_ID,
422 occurredAt: THREAD.thread.updatedAt,
423 payload: { ...THREAD.thread, title: value },
424 },
425 });
426 yield* Queue.offerAll(first.events, [
427 title(8, "Before snapshot"),
428 {
429 kind: "snapshot",
430 snapshotSequence: 20,
431 projection: THREAD,
432 historyCursor: "older-batch",
433 hasMoreHistory: true,
434 latestLocalTurnOrdinal: 10,
435 },
436 title(21, "After snapshot"),
437 title(19, "Stale replay"),
438 { kind: "synchronized" },
439 ]);
440 const state = yield* observeState(h.registry, h.stateAtom, (value) => value.status === "live");
441 expect(Option.getOrThrow(state.data).thread.title).toBe("After snapshot");
442 expect(state.history.historyCursor).toBe("older-batch");
443 expect(state.history.latestLocalTurnOrdinal).toBe(10);
444 unmount();
445 yield* Deferred.await(first.closed);
446 const remount = h.registry.mount(h.stateAtom);
447 const next = yield* Queue.take(h.subscriptions);
448 expect(next.afterSequence).toBe(21);
449 remount();
450 yield* Deferred.await(next.closed);
451 }),
452);