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