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

threads-sync.test.ts

482 lines16.0 KB

1import {
2 EnvironmentId,
3 EventId,
4 ORCHESTRATION_WS_METHODS,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 type OrchestrationThread,
9 type OrchestrationThreadDetailSnapshot,
10 type OrchestrationThreadStreamItem,
11} from "@t3tools/contracts";
12import { describe, expect, it } from "@effect/vitest";
13import * as Effect from "effect/Effect";
14import * as Option from "effect/Option";
15import * as Queue from "effect/Queue";
16import * as Ref from "effect/Ref";
17import * as Stream from "effect/Stream";
18import * as SubscriptionRef from "effect/SubscriptionRef";
19import * as TestClock from "effect/testing/TestClock";
20​
21import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
22import {
23 AVAILABLE_CONNECTION_STATE,
24 PrimaryConnectionTarget,
25 type PreparedConnection,
26 type SupervisorConnectionState,
27} from "../connection/model.ts";
28import * as EnvironmentSupervisor from "../connection/supervisor.ts";
29import * as Persistence from "../platform/persistence.ts";
30import * as RpcSession from "../rpc/session.ts";
31import {
32 EMPTY_ENVIRONMENT_THREAD_STATE,
33 makeEnvironmentThreadState,
34 ThreadSnapshotLoader,
35 type EnvironmentThreadState,
36} from "./threads.ts";
37​
38const TARGET = new PrimaryConnectionTarget({
39 environmentId: EnvironmentId.make("environment-1"),
40 label: "Test environment",
41 httpBaseUrl: "https://environment.example.test",
42 wsBaseUrl: "wss://environment.example.test",
43});
44const THREAD_ID = ThreadId.make("thread-1");
45const CACHED_SNAPSHOT_SEQUENCE = 7;
46const PREPARED: PreparedConnection = {
47 environmentId: TARGET.environmentId,
48 label: TARGET.label,
49 httpBaseUrl: TARGET.httpBaseUrl,
50 socketUrl: TARGET.wsBaseUrl,
51 httpAuthorization: null,
52 target: TARGET,
53};
54const BASE_THREAD: OrchestrationThread = {
55 id: THREAD_ID,
56 projectId: ProjectId.make("project-1"),
57 title: "Cached thread",
58 modelSelection: {
59 instanceId: ProviderInstanceId.make("codex"),
60 model: "gpt-5.4",
61 },
62 runtimeMode: "full-access",
63 interactionMode: "default",
64 branch: "main",
65 worktreePath: null,
66 latestTurn: null,
67 createdAt: "2026-04-01T00:00:00.000Z",
68 updatedAt: "2026-04-01T00:00:00.000Z",
69 archivedAt: null,
70 deletedAt: null,
71 messages: [],
72 proposedPlans: [],
73 activities: [],
74 checkpoints: [],
75 session: null,
76};
77​
78type TestThreadInput = OrchestrationThreadStreamItem | Error;
79​
80function testSession(client: WsRpcProtocolClient): RpcSession.RpcSession {
81 return {
82 client,
83 initialConfig: Effect.never,
84 ready: Effect.void,
85 probe: Effect.void,
86 closed: Effect.never,
87 };
89​
90function awaitThreadState(
91 observed: Queue.Queue<EnvironmentThreadState>,
92 predicate: (state: EnvironmentThreadState) => boolean,
93) {
94 return Queue.take(observed).pipe(
95 Effect.repeat({
96 until: predicate,
97 }),
98 );
100​
101const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
102 readonly cached?: OrchestrationThread;
103 readonly httpSnapshot?: Option.Option<OrchestrationThreadDetailSnapshot>;
104}) {
105 const inputs = yield* Queue.unbounded<TestThreadInput>();
106 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
107 const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
108 const retryCount = yield* Ref.make(0);
109 const subscriptionCount = yield* Ref.make(0);
110 const loaderCalls = yield* Ref.make(0);
111 const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
112 const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
113 const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
114 const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
115 AVAILABLE_CONNECTION_STATE,
116 );
117 const streamFrom = (queue: Queue.Queue<TestThreadInput>) =>
118 Stream.fromQueue(queue).pipe(
119 Stream.mapEffect((input) =>
120 input instanceof Error ? Effect.fail(input) : Effect.succeed(input),
121 ),
122 );
123 const client = {
124 [ORCHESTRATION_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) =>
125 Stream.unwrap(
126 Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
127 Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
128 Effect.as(streamFrom(inputs)),
129 ),
130 ),
131 } as unknown as WsRpcProtocolClient;
132 const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
133 Option.some(testSession(client)),
134 );
135 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
136 Option.some(PREPARED),
137 );
138 const snapshotLoader = ThreadSnapshotLoader.of({
139 load: (_prepared, threadId) =>
140 Ref.update(loaderCalls, (count) => count + 1).pipe(
141 Effect.as(
142 threadId === THREAD_ID
143 ? (options?.httpSnapshot ?? Option.none<OrchestrationThreadDetailSnapshot>())
144 : Option.none<OrchestrationThreadDetailSnapshot>(),
145 ),
146 ),
147 });
148 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
149 target: TARGET,
150 state: supervisorState,
151 session: supervisorSession,
152 prepared,
153 connect: Effect.void,
154 disconnect: Effect.void,
155 retryNow: Ref.update(retryCount, (count) => count + 1),
156 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
157 const cache = Persistence.EnvironmentCacheStore.of({
158 loadShell: () => Effect.succeed(Option.none()),
159 saveShell: () => Effect.void,
160 loadThread: (_environmentId, threadId) =>
161 Effect.succeed(
162 threadId === THREAD_ID && options?.cached !== undefined
163 ? Option.some({
164 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
165 thread: options.cached,
166 })
167 : Option.none(),
168 ),
169 saveThread: (_environmentId, thread) =>
170 Ref.update(savedThreads, (current) => [...current, thread]),
171 removeThread: (_environmentId, threadId) =>
172 Ref.update(removedThreads, (current) => [...current, threadId]),
173 clear: () => Effect.void,
174 });
175 const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
176 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
177 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
178 Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
179 );
180 yield* SubscriptionRef.changes(threadState).pipe(
181 Stream.runForEach((state) =>
182 Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
183 ),
184 Effect.forkScoped,
185 );
186​
187 return {
188 inputs,
189 observed,
190 latest,
191 retryCount,
192 subscriptionCount,
193 loaderCalls,
194 lastSubscribeAfterSequence,
195 supervisorState,
196 supervisorSession,
197 savedThreads,
198 removedThreads,
199 replaceSession: SubscriptionRef.set(supervisorSession, Option.some(testSession(client))),
200 };
201});
202​
203const snapshot = (thread: OrchestrationThread): OrchestrationThreadStreamItem => ({
204 kind: "snapshot",
205 snapshot: {
206 snapshotSequence: 1,
207 thread,
208 },
209});
210​
211const titleUpdated = (title: string, sequence = 2): OrchestrationThreadStreamItem => ({
212 kind: "event",
213 event: {
214 eventId: EventId.make("event-title"),
215 sequence,
216 occurredAt: "2026-04-01T01:00:00.000Z",
217 commandId: null,
218 causationEventId: null,
219 correlationId: null,
220 metadata: {},
221 aggregateKind: "thread",
222 aggregateId: THREAD_ID,
223 type: "thread.meta-updated",
224 payload: {
225 threadId: THREAD_ID,
226 title,
227 updatedAt: "2026-04-01T01:00:00.000Z",
228 },
229 },
230});
231​
232const deleted = (): OrchestrationThreadStreamItem => ({
233 kind: "event",
234 event: {
235 eventId: EventId.make("event-deleted"),
236 sequence: 3,
237 occurredAt: "2026-04-01T02:00:00.000Z",
238 commandId: null,
239 causationEventId: null,
240 correlationId: null,
241 metadata: {},
242 aggregateKind: "thread",
243 aggregateId: THREAD_ID,
244 type: "thread.deleted",
245 payload: {
246 threadId: THREAD_ID,
247 deletedAt: "2026-04-01T02:00:00.000Z",
248 },
249 },
250});
251​
252describe("EnvironmentThreads", () => {
253 it.effect("publishes cached data immediately from a warm cache", () =>
254 Effect.gen(function* () {
255 const harness = yield* makeHarness({ cached: BASE_THREAD });
256 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
257​
258 expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
259 expect(Option.isNone(state.error)).toBe(true);
260 }),
261 );
262​
263 it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
264 Effect.gen(function* () {
265 const harness = yield* makeHarness({ cached: BASE_THREAD });
266​
267 // The warm cache reaches live from the cached data, and a live event
268 // applies on top of it.
269 yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
270 yield* awaitThreadState(
271 harness.observed,
272 (value) =>
273 value.status === "live" &&
274 Option.isSome(value.data) &&
275 value.data.value.title === "Live title",
276 );
277​
278 // The subscription resumed from the cached sequence and never fetched the
279 // full snapshot over HTTP.
280 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
281 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
282 }),
283 );
284​
285 it.effect("reduces live events and persists the latest thread", () =>
286 Effect.gen(function* () {
287 const harness = yield* makeHarness({ cached: BASE_THREAD });
288 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
289 yield* Queue.offer(harness.inputs, titleUpdated("Live title"));
290​
291 const state = yield* awaitThreadState(
292 harness.observed,
293 (value) =>
294 value.status === "live" &&
295 Option.isSome(value.data) &&
296 value.data.value.title === "Live title",
297 );
298 yield* TestClock.adjust("500 millis");
299 yield* Effect.yieldNow;
300​
301 expect(Option.getOrThrow(state.data).title).toBe("Live title");
302 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.thread.title).toBe("Live title");
303 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
304 }),
305 );
306​
307 it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
308 Effect.gen(function* () {
309 const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
310 const harness = yield* makeHarness({
311 httpSnapshot: Option.some({ snapshotSequence: 1, thread: httpThread }),
312 });
313 // No socket snapshot is pushed; only a live event arrives over the socket.
314 // It can only be applied if the HTTP snapshot already seeded the thread.
315 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
316​
317 const state = yield* awaitThreadState(
318 harness.observed,
319 (value) =>
320 value.status === "live" &&
321 Option.isSome(value.data) &&
322 value.data.value.title === "Live title",
323 );
324​
325 expect(Option.getOrThrow(state.data).title).toBe("Live title");
326 // Cold cache: the full snapshot was loaded over HTTP and the socket
327 // resumed from that snapshot's sequence.
328 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
329 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
330 }),
331 );
332​
333 it.effect("ignores replayed thread events at or below the snapshot sequence", () =>
334 Effect.gen(function* () {
335 const harness = yield* makeHarness({ cached: BASE_THREAD });
336 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
337 yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1));
338 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
339​
340 const state = yield* awaitThreadState(
341 harness.observed,
342 (value) =>
343 value.status === "live" &&
344 Option.isSome(value.data) &&
345 value.data.value.title === "Live title",
346 );
347​
348 expect(Option.getOrThrow(state.data).title).toBe("Live title");
349 }),
350 );
351​
352 it.effect("removes cached data when the thread is deleted", () =>
353 Effect.gen(function* () {
354 const harness = yield* makeHarness({ cached: BASE_THREAD });
355 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
356 yield* Queue.offer(harness.inputs, deleted());
357​
358 const state = yield* awaitThreadState(
359 harness.observed,
360 (value) => value.status === "deleted",
361 );
362​
363 expect(Option.isNone(state.data)).toBe(true);
364 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
365 }),
366 );
367​
368 it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
369 Effect.gen(function* () {
370 const harness = yield* makeHarness({ cached: BASE_THREAD });
371 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
372 yield* Queue.offer(harness.inputs, new Error("stream failed"));
373​
374 const state = yield* awaitThreadState(harness.observed, (value) =>
375 Option.isSome(value.error),
376 );
377​
378 expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
379 expect(Option.getOrThrow(state.error)).toBe("stream failed");
380 expect(yield* Ref.get(harness.retryCount)).toBe(0);
381​
382 yield* harness.replaceSession;
383 for (let attempt = 0; attempt < 100; attempt += 1) {
384 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
385 break;
386 }
387 yield* Effect.yieldNow;
388 }
389 yield* Queue.offer(
390 harness.inputs,
391 snapshot({
392 ...BASE_THREAD,
393 title: "Recovered thread",
394 }),
395 );
396 const recovered = yield* awaitThreadState(
397 harness.observed,
398 (value) =>
399 value.status === "live" &&
400 Option.isSome(value.data) &&
401 value.data.value.title === "Recovered thread",
402 );
403​
404 expect(Option.isNone(recovered.error)).toBe(true);
405 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
406 }),
407 );
408​
409 it.effect("recovers from a transient domain failure without replacing the session", () =>
410 Effect.gen(function* () {
411 const harness = yield* makeHarness();
412 yield* Queue.offer(harness.inputs, new Error("thread not found yet"));
413​
414 const failed = yield* awaitThreadState(harness.observed, (value) =>
415 Option.isSome(value.error),
416 );
417 expect(Option.getOrThrow(failed.error)).toBe("thread not found yet");
418 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
419​
420 yield* TestClock.adjust("250 millis");
421 for (let attempt = 0; attempt < 100; attempt += 1) {
422 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
423 break;
424 }
425 yield* Effect.yieldNow;
426 }
427 yield* Queue.offer(
428 harness.inputs,
429 snapshot({
430 ...BASE_THREAD,
431 title: "Materialized thread",
432 }),
433 );
434​
435 const recovered = yield* awaitThreadState(
436 harness.observed,
437 (value) =>
438 value.status === "live" &&
439 Option.isSome(value.data) &&
440 value.data.value.title === "Materialized thread",
441 );
442​
443 expect(Option.isNone(recovered.error)).toBe(true);
444 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
445 expect(yield* Ref.get(harness.retryCount)).toBe(0);
446 }),
447 );
448​
449 it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () =>
450 Effect.gen(function* () {
451 const harness = yield* makeHarness({ cached: BASE_THREAD });
452 yield* SubscriptionRef.set(harness.supervisorState, {
453 desired: true,
454 network: "online",
455 phase: "connecting",
456 stage: "synchronizing",
457 attempt: 1,
458 generation: 0,
459 lastFailure: null,
460 retryAt: null,
461 });
462 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
463 yield* awaitThreadState(harness.observed, (value) => value.status === "live");
464​
465 yield* SubscriptionRef.set(harness.supervisorState, {
466 desired: true,
467 network: "online",
468 phase: "connected",
469 stage: null,
470 attempt: 1,
471 generation: 1,
472 lastFailure: null,
473 retryAt: null,
474 });
475 for (let index = 0; index < 10; index += 1) {
476 yield* Effect.yieldNow;
477 }
478​
479 expect((yield* Ref.get(harness.latest)).status).toBe("live");
480 }),
481 );
482});