Open History to see the last commit
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 "@v12/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 };
88}
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 );
99}
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 loadServerConfig: () => Effect.succeed(Option.none()),
174 saveServerConfig: () => Effect.void,
175 loadVcsRefs: () => Effect.succeed(Option.none()),
176 saveVcsRefs: () => Effect.void,
177 clear: () => Effect.void,
178 });
179 const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
180 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
181 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
182 Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
183 );
184 yield* SubscriptionRef.changes(threadState).pipe(
185 Stream.runForEach((state) =>
186 Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
187 ),
188 Effect.forkScoped,
189 );
190
191 return {
192 inputs,
193 observed,
194 latest,
195 retryCount,
196 subscriptionCount,
197 loaderCalls,
198 lastSubscribeAfterSequence,
199 supervisorState,
200 supervisorSession,
201 savedThreads,
202 removedThreads,
203 replaceSession: SubscriptionRef.set(supervisorSession, Option.some(testSession(client))),
204 };
205});
206
207const snapshot = (thread: OrchestrationThread): OrchestrationThreadStreamItem => ({
208 kind: "snapshot",
209 snapshot: {
210 snapshotSequence: 1,
211 thread,
212 },
213});
214
215const titleUpdated = (title: string, sequence = 2): OrchestrationThreadStreamItem => ({
216 kind: "event",
217 event: {
218 eventId: EventId.make("event-title"),
219 sequence,
220 occurredAt: "2026-04-01T01:00:00.000Z",
221 commandId: null,
222 causationEventId: null,
223 correlationId: null,
224 metadata: {},
225 aggregateKind: "thread",
226 aggregateId: THREAD_ID,
227 type: "thread.meta-updated",
228 payload: {
229 threadId: THREAD_ID,
230 title,
231 updatedAt: "2026-04-01T01:00:00.000Z",
232 },
233 },
234});
235
236const deleted = (): OrchestrationThreadStreamItem => ({
237 kind: "event",
238 event: {
239 eventId: EventId.make("event-deleted"),
240 sequence: 3,
241 occurredAt: "2026-04-01T02:00:00.000Z",
242 commandId: null,
243 causationEventId: null,
244 correlationId: null,
245 metadata: {},
246 aggregateKind: "thread",
247 aggregateId: THREAD_ID,
248 type: "thread.deleted",
249 payload: {
250 threadId: THREAD_ID,
251 deletedAt: "2026-04-01T02:00:00.000Z",
252 },
253 },
254});
255
256describe("EnvironmentThreads", () => {
257 it.effect("publishes cached data immediately from a warm cache", () =>
258 Effect.gen(function* () {
259 const harness = yield* makeHarness({ cached: BASE_THREAD });
260 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
261
262 expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
263 expect(Option.isNone(state.error)).toBe(true);
264 }),
265 );
266
267 it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
268 Effect.gen(function* () {
269 const harness = yield* makeHarness({ cached: BASE_THREAD });
270
271 // The warm cache reaches live from the cached data, and a live event
272 // applies on top of it.
273 yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
274 yield* awaitThreadState(
275 harness.observed,
276 (value) =>
277 value.status === "live" &&
278 Option.isSome(value.data) &&
279 value.data.value.title === "Live title",
280 );
281
282 // The subscription resumed from the cached sequence and never fetched the
283 // full snapshot over HTTP.
284 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
285 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
286 }),
287 );
288
289 it.effect("reduces live events and persists the latest thread", () =>
290 Effect.gen(function* () {
291 const harness = yield* makeHarness({ cached: BASE_THREAD });
292 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
293 yield* Queue.offer(harness.inputs, titleUpdated("Live title"));
294
295 const state = yield* awaitThreadState(
296 harness.observed,
297 (value) =>
298 value.status === "live" &&
299 Option.isSome(value.data) &&
300 value.data.value.title === "Live title",
301 );
302 yield* TestClock.adjust("500 millis");
303 yield* Effect.yieldNow;
304
305 expect(Option.getOrThrow(state.data).title).toBe("Live title");
306 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.thread.title).toBe("Live title");
307 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
308 }),
309 );
310
311 it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
312 Effect.gen(function* () {
313 const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
314 const harness = yield* makeHarness({
315 httpSnapshot: Option.some({ snapshotSequence: 1, thread: httpThread }),
316 });
317 // No socket snapshot is pushed; only a live event arrives over the socket.
318 // It can only be applied if the HTTP snapshot already seeded the thread.
319 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
320
321 const state = yield* awaitThreadState(
322 harness.observed,
323 (value) =>
324 value.status === "live" &&
325 Option.isSome(value.data) &&
326 value.data.value.title === "Live title",
327 );
328
329 expect(Option.getOrThrow(state.data).title).toBe("Live title");
330 // Cold cache: the full snapshot was loaded over HTTP and the socket
331 // resumed from that snapshot's sequence.
332 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
333 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
334 }),
335 );
336
337 it.effect("ignores replayed thread events at or below the snapshot sequence", () =>
338 Effect.gen(function* () {
339 const harness = yield* makeHarness({ cached: BASE_THREAD });
340 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
341 yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1));
342 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
343
344 const state = yield* awaitThreadState(
345 harness.observed,
346 (value) =>
347 value.status === "live" &&
348 Option.isSome(value.data) &&
349 value.data.value.title === "Live title",
350 );
351
352 expect(Option.getOrThrow(state.data).title).toBe("Live title");
353 }),
354 );
355
356 it.effect("removes cached data when the thread is deleted", () =>
357 Effect.gen(function* () {
358 const harness = yield* makeHarness({ cached: BASE_THREAD });
359 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
360 yield* Queue.offer(harness.inputs, deleted());
361
362 const state = yield* awaitThreadState(
363 harness.observed,
364 (value) => value.status === "deleted",
365 );
366
367 expect(Option.isNone(state.data)).toBe(true);
368 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
369 }),
370 );
371
372 it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
373 Effect.gen(function* () {
374 const harness = yield* makeHarness({ cached: BASE_THREAD });
375 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
376 yield* Queue.offer(harness.inputs, new Error("stream failed"));
377
378 const state = yield* awaitThreadState(harness.observed, (value) =>
379 Option.isSome(value.error),
380 );
381
382 expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
383 expect(Option.getOrThrow(state.error)).toBe("stream failed");
384 expect(yield* Ref.get(harness.retryCount)).toBe(0);
385
386 yield* harness.replaceSession;
387 for (let attempt = 0; attempt < 100; attempt += 1) {
388 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
389 break;
390 }
391 yield* Effect.yieldNow;
392 }
393 yield* Queue.offer(
394 harness.inputs,
395 snapshot({
396 ...BASE_THREAD,
397 title: "Recovered thread",
398 }),
399 );
400 const recovered = yield* awaitThreadState(
401 harness.observed,
402 (value) =>
403 value.status === "live" &&
404 Option.isSome(value.data) &&
405 value.data.value.title === "Recovered thread",
406 );
407
408 expect(Option.isNone(recovered.error)).toBe(true);
409 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
410 }),
411 );
412
413 it.effect("recovers from a transient domain failure without replacing the session", () =>
414 Effect.gen(function* () {
415 const harness = yield* makeHarness();
416 yield* Queue.offer(harness.inputs, new Error("thread not found yet"));
417
418 const failed = yield* awaitThreadState(harness.observed, (value) =>
419 Option.isSome(value.error),
420 );
421 expect(Option.getOrThrow(failed.error)).toBe("thread not found yet");
422 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
423
424 yield* TestClock.adjust("250 millis");
425 for (let attempt = 0; attempt < 100; attempt += 1) {
426 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
427 break;
428 }
429 yield* Effect.yieldNow;
430 }
431 yield* Queue.offer(
432 harness.inputs,
433 snapshot({
434 ...BASE_THREAD,
435 title: "Materialized thread",
436 }),
437 );
438
439 const recovered = yield* awaitThreadState(
440 harness.observed,
441 (value) =>
442 value.status === "live" &&
443 Option.isSome(value.data) &&
444 value.data.value.title === "Materialized thread",
445 );
446
447 expect(Option.isNone(recovered.error)).toBe(true);
448 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
449 expect(yield* Ref.get(harness.retryCount)).toBe(0);
450 }),
451 );
452
453 it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () =>
454 Effect.gen(function* () {
455 const harness = yield* makeHarness({ cached: BASE_THREAD });
456 yield* SubscriptionRef.set(harness.supervisorState, {
457 desired: true,
458 network: "online",
459 phase: "connecting",
460 stage: "synchronizing",
461 attempt: 1,
462 generation: 0,
463 lastFailure: null,
464 retryAt: null,
465 });
466 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
467 yield* awaitThreadState(harness.observed, (value) => value.status === "live");
468
469 yield* SubscriptionRef.set(harness.supervisorState, {
470 desired: true,
471 network: "online",
472 phase: "connected",
473 stage: null,
474 attempt: 1,
475 generation: 1,
476 lastFailure: null,
477 retryAt: null,
478 });
479 for (let index = 0; index < 10; index += 1) {
480 yield* Effect.yieldNow;
481 }
482
483 expect((yield* Ref.get(harness.latest)).status).toBe("live");
484 }),
485 );
486});