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