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

threads-atoms.test.ts

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