Open History to see the last commit
1import {
2 EnvironmentId,
3 ORCHESTRATION_V2_WS_METHODS,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6 ThreadId,
7 type ThreadPullRequestLink,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "@effect/vitest";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Fiber from "effect/Fiber";
14import * as Option from "effect/Option";
15import * as Queue from "effect/Queue";
16import * as Ref from "effect/Ref";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import * as TestClock from "effect/testing/TestClock";
21
22import {
23 AVAILABLE_CONNECTION_STATE,
24 PrimaryConnectionTarget,
25 type PreparedConnection,
26} from "../connection/model.ts";
27import * as EnvironmentSupervisor from "../connection/supervisor.ts";
28import * as ConnectionWakeups from "../connection/wakeups.ts";
29import * as Persistence from "../platform/persistence.ts";
30import * as RpcSession from "../rpc/session.ts";
31import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
32import { makeEnvironmentShellState } from "./shell.ts";
33import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
34import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.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});
42
43const PREPARED: PreparedConnection = {
44 environmentId: TARGET.environmentId,
45 label: TARGET.label,
46 httpBaseUrl: TARGET.httpBaseUrl,
47 socketUrl: TARGET.wsBaseUrl,
48 httpAuthorization: null,
49 target: TARGET,
50};
51
52const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
53 ...v2ShellSnapshot,
54 snapshotSequence: 1,
55};
56
57function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
58 return {
59 client,
60 initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
61 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
62 ready: Effect.void,
63 probe: Effect.void,
64 closed: Effect.never,
65 };
66}
67
68describe("environment shell synchronization", () => {
69 it.effect("publishes live state before persistence and preserves it when ready", () =>
70 Effect.gen(function* () {
71 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
72 const client = {
73 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
74 } as unknown as WsRpcProtocolClient;
75 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
76 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
77 Option.some(session(client)),
78 );
79 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
80 target: TARGET,
81 state: supervisorState,
82 session: activeSession,
83 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
84 connect: Effect.void,
85 disconnect: Effect.void,
86 retryNow: Effect.void,
87 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
88 const cache = Persistence.EnvironmentCacheStore.of({
89 loadShell: () => Effect.succeed(Option.none()),
90 saveShell: () => Effect.void,
91 loadThread: () => Effect.succeed(Option.none()),
92 saveThread: () => Effect.void,
93 removeThread: () => Effect.void,
94 loadServerConfig: () => Effect.succeedNone,
95 saveServerConfig: () => Effect.void,
96 loadVcsRefs: () => Effect.succeedNone,
97 saveVcsRefs: () => Effect.void,
98 removeVcsRefs: () => Effect.void,
99 clearVcsRefs: () => Effect.void,
100 clear: () => Effect.void,
101 });
102 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
103 load: () => Effect.succeedNone,
104 });
105 const shellState = yield* makeEnvironmentShellState().pipe(
106 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
107 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
108 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
109 );
110
111 yield* SubscriptionRef.set(supervisorState, {
112 desired: true,
113 network: "online",
114 phase: "connecting",
115 stage: "synchronizing",
116 attempt: 1,
117 generation: 0,
118 lastFailure: null,
119 retryAt: null,
120 });
121 yield* Queue.offer(events, {
122 kind: "snapshot",
123 snapshot: LIVE_SHELL_SNAPSHOT,
124 });
125 const synchronizing = yield* SubscriptionRef.changes(shellState).pipe(
126 Stream.filter((state) => state.status === "synchronizing" && Option.isSome(state.snapshot)),
127 Stream.runHead,
128 );
129 expect(Option.getOrThrow(Option.getOrThrow(synchronizing).snapshot)).toEqual(
130 LIVE_SHELL_SNAPSHOT,
131 );
132
133 yield* Queue.offer(events, { kind: "synchronized" });
134 yield* SubscriptionRef.changes(shellState).pipe(
135 Stream.filter((state) => state.status === "live"),
136 Stream.runHead,
137 );
138
139 yield* SubscriptionRef.set(supervisorState, {
140 desired: true,
141 network: "online",
142 phase: "connected",
143 stage: null,
144 attempt: 1,
145 generation: 1,
146 lastFailure: null,
147 retryAt: null,
148 });
149 for (let index = 0; index < 10; index += 1) {
150 yield* Effect.yieldNow;
151 }
152
153 const state = yield* SubscriptionRef.get(shellState);
154 expect(state.status).toBe("live");
155 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
156 }),
157 );
158
159 it.live.each([
160 { bufferSize: Infinity, expectedSequences: [51] },
161 // RpcClient defaults to a 16-event buffer, which splits larger server chunks.
162 { bufferSize: 16, expectedSequences: [17, 33, 49, 51] },
163 ])("batches live events with a $bufferSize event buffer", ({ bufferSize, expectedSequences }) =>
164 Effect.gen(function* () {
165 const events = yield* Queue.bounded<OrchestrationV2ShellStreamItem>(bufferSize);
166 const batchSnapshot = { ...LIVE_SHELL_SNAPSHOT, threads: [] };
167 const client = {
168 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
169 } as unknown as WsRpcProtocolClient;
170 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
171 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
172 Option.some(session(client)),
173 );
174 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
175 target: TARGET,
176 state: supervisorState,
177 session: activeSession,
178 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
179 connect: Effect.void,
180 disconnect: Effect.void,
181 retryNow: Effect.void,
182 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
183 const cache = Persistence.EnvironmentCacheStore.of({
184 loadShell: () => Effect.succeed(Option.none()),
185 saveShell: () => Effect.void,
186 loadThread: () => Effect.succeed(Option.none()),
187 saveThread: () => Effect.void,
188 removeThread: () => Effect.void,
189 loadServerConfig: () => Effect.succeed(Option.none()),
190 saveServerConfig: () => Effect.void,
191 loadVcsRefs: () => Effect.succeed(Option.none()),
192 saveVcsRefs: () => Effect.void,
193 removeVcsRefs: () => Effect.void,
194 clearVcsRefs: () => Effect.void,
195 clear: () => Effect.void,
196 });
197 const shellState = yield* makeEnvironmentShellState().pipe(
198 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
199 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
200 Effect.provideService(
201 ShellSnapshotLoader.ShellSnapshotLoader,
202 ShellSnapshotLoader.ShellSnapshotLoader.of({ load: () => Effect.succeed(Option.none()) }),
203 ),
204 );
205 yield* SubscriptionRef.set(supervisorState, {
206 desired: true,
207 network: "online",
208 phase: "connected",
209 stage: null,
210 attempt: 1,
211 generation: 1,
212 lastFailure: null,
213 retryAt: null,
214 });
215 yield* Queue.offer(events, { kind: "snapshot", snapshot: batchSnapshot });
216 yield* Queue.offer(events, { kind: "synchronized" });
217 yield* SubscriptionRef.changes(shellState).pipe(
218 Stream.filter((state) => state.status === "live"),
219 Stream.runHead,
220 );
221
222 const observed = yield* SubscriptionRef.changes(shellState).pipe(
223 Stream.drop(1),
224 Stream.takeUntil(
225 (state) => Option.isSome(state.snapshot) && state.snapshot.value.threads.length === 50,
226 ),
227 Stream.runCollect,
228 Effect.forkScoped({ startImmediately: true }),
229 );
230 yield* Queue.offerAll(
231 events,
232 Array.from({ length: 50 }, (_, index) => ({
233 kind: "thread.updated" as const,
234 sequence: 2 + index,
235 location: "active" as const,
236 thread: { ...v2ShellSnapshot.threads[0]!, id: `thread-${index}` } as never,
237 })),
238 );
239 const states = yield* Fiber.join(observed);
240 const snapshots = states.map((state) => Option.getOrThrow(state.snapshot));
241 expect(snapshots.map((snapshot) => snapshot.snapshotSequence)).toEqual(expectedSequences);
242 expect(snapshots.at(-1)!.threads.map((thread) => thread.id)).toEqual(
243 Array.from({ length: 50 }, (_, index) => `thread-${index}`),
244 );
245 }).pipe(Effect.scoped),
246 );
247
248 it.effect("refreshes a warm shell cache from HTTP before resuming", () =>
249 Effect.gen(function* () {
250 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
251 ...v2ShellSnapshot,
252 snapshotSequence: 5,
253 };
254 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
255 const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
256 const capturedCompletionMarker = yield* Ref.make(false);
257 const loaderCalls = yield* SubscriptionRef.make(0);
258 const httpSnapshot: OrchestrationV2ShellSnapshot = {
259 ...v2ShellSnapshot,
260 snapshotSequence: 9,
261 };
262 const client = {
263 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: {
264 readonly afterSequence?: number;
265 readonly requestCompletionMarker?: true;
266 }) =>
267 Stream.unwrap(
268 Effect.all([
269 Ref.set(capturedCompletionMarker, input.requestCompletionMarker === true),
270 SubscriptionRef.set(capturedAfterSequence, input.afterSequence),
271 ]).pipe(Effect.as(Stream.fromQueue(events))),
272 ),
273 } as unknown as WsRpcProtocolClient;
274 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
275 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
276 Option.some(session(client)),
277 );
278 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
279 target: TARGET,
280 state: supervisorState,
281 session: activeSession,
282 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
283 connect: Effect.void,
284 disconnect: Effect.void,
285 retryNow: Effect.void,
286 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
287 const cache = Persistence.EnvironmentCacheStore.of({
288 loadShell: () => Effect.succeedSome(cachedSnapshot),
289 saveShell: () => Effect.void,
290 loadThread: () => Effect.succeedNone,
291 saveThread: () => Effect.void,
292 removeThread: () => Effect.void,
293 loadServerConfig: () => Effect.succeedNone,
294 saveServerConfig: () => Effect.void,
295 loadVcsRefs: () => Effect.succeedNone,
296 saveVcsRefs: () => Effect.void,
297 removeVcsRefs: () => Effect.void,
298 clearVcsRefs: () => Effect.void,
299 clear: () => Effect.void,
300 });
301 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
302 load: () =>
303 SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(
304 Effect.as(Option.some(httpSnapshot)),
305 ),
306 });
307 const shellState = yield* makeEnvironmentShellState().pipe(
308 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
309 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
310 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
311 );
312
313 yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
314 Stream.filter((value) => value !== undefined),
315 Stream.runHead,
316 );
317
318 expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(9);
319 expect(yield* Ref.get(capturedCompletionMarker)).toBe(true);
320 expect(yield* SubscriptionRef.get(loaderCalls)).toBe(1);
321 const synchronizing = yield* SubscriptionRef.get(shellState);
322 expect(synchronizing.status).toBe("synchronizing");
323 expect(Option.getOrThrow(synchronizing.snapshot)).toEqual(httpSnapshot);
324
325 yield* Queue.offer(events, { kind: "synchronized" });
326 yield* SubscriptionRef.changes(shellState).pipe(
327 Stream.filter((value) => value.status === "live"),
328 Stream.runHead,
329 );
330 }),
331 );
332
333 it.effect("resubscribes from the in-memory shell cursor when the app becomes active", () =>
334 Effect.gen(function* () {
335 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
336 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
337 const loaderCalls = yield* Ref.make(0);
338 const capturedAfterSequences = yield* Ref.make<ReadonlyArray<number | undefined>>([]);
339 const client = {
340 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: {
341 readonly afterSequence?: number;
342 }) =>
343 Stream.unwrap(
344 Ref.update(capturedAfterSequences, (captured) => [
345 ...captured,
346 input.afterSequence,
347 ]).pipe(Effect.as(Stream.fromQueue(events))),
348 ),
349 } as unknown as WsRpcProtocolClient;
350 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
351 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
352 Option.some(session(client)),
353 );
354 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
355 target: TARGET,
356 state: supervisorState,
357 session: activeSession,
358 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
359 connect: Effect.void,
360 disconnect: Effect.void,
361 retryNow: Effect.void,
362 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
363 const cache = Persistence.EnvironmentCacheStore.of({
364 loadShell: () => Effect.succeedSome(LIVE_SHELL_SNAPSHOT),
365 saveShell: () => Effect.void,
366 loadThread: () => Effect.succeedNone,
367 saveThread: () => Effect.void,
368 removeThread: () => Effect.void,
369 loadServerConfig: () => Effect.succeedNone,
370 saveServerConfig: () => Effect.void,
371 loadVcsRefs: () => Effect.succeedNone,
372 saveVcsRefs: () => Effect.void,
373 removeVcsRefs: () => Effect.void,
374 clearVcsRefs: () => Effect.void,
375 clear: () => Effect.void,
376 });
377 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
378 load: () =>
379 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
380 Effect.map((count) =>
381 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
382 ),
383 ),
384 });
385 const shellState = yield* makeEnvironmentShellState().pipe(
386 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
387 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
388 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
389 Effect.provideService(
390 ConnectionWakeups.ConnectionWakeups,
391 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
392 ),
393 );
394
395 for (let attempt = 0; attempt < 100; attempt += 1) {
396 if ((yield* Ref.get(capturedAfterSequences)).length >= 1) break;
397 yield* Effect.yieldNow;
398 }
399 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10]);
400 yield* Queue.offer(events, { kind: "synchronized" });
401 yield* SubscriptionRef.changes(shellState).pipe(
402 Stream.filter((value) => value.status === "live"),
403 Stream.runHead,
404 );
405
406 yield* Queue.offer(events, {
407 kind: "snapshot",
408 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 40 },
409 });
410 yield* SubscriptionRef.changes(shellState).pipe(
411 Stream.filter(
412 (value) => Option.isSome(value.snapshot) && value.snapshot.value.snapshotSequence === 40,
413 ),
414 Stream.runHead,
415 );
416
417 yield* Queue.offer(wakeups, "application-active");
418 for (let attempt = 0; attempt < 100; attempt += 1) {
419 if ((yield* Ref.get(capturedAfterSequences)).length >= 2) break;
420 yield* Effect.yieldNow;
421 }
422 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40]);
423 yield* Queue.offer(events, { kind: "synchronized" });
424
425 yield* Queue.offer(wakeups, "application-active-probe");
426 for (let attempt = 0; attempt < 100; attempt += 1) {
427 if ((yield* Ref.get(capturedAfterSequences)).length >= 3) break;
428 yield* Effect.yieldNow;
429 }
430 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40]);
431
432 yield* Queue.offer(wakeups, "application-active-reconnect");
433 for (let attempt = 0; attempt < 10; attempt += 1) {
434 yield* Effect.yieldNow;
435 }
436 expect((yield* Ref.get(capturedAfterSequences)).length).toBe(3);
437 expect(yield* Ref.get(loaderCalls)).toBe(1);
438
439 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
440 for (let attempt = 0; attempt < 100; attempt += 1) {
441 if ((yield* Ref.get(capturedAfterSequences)).length >= 4) break;
442 yield* Effect.yieldNow;
443 }
444 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40, 20]);
445 expect(yield* Ref.get(loaderCalls)).toBe(2);
446 }),
447 );
448
449 it.effect("throttles shell writes and flushes the latest snapshot on disconnect", () =>
450 Effect.gen(function* () {
451 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
452 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
453 const client = {
454 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
455 } as unknown as WsRpcProtocolClient;
456 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
457 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
458 Option.some(session(client)),
459 );
460 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
461 target: TARGET,
462 state: supervisorState,
463 session: activeSession,
464 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
465 connect: Effect.void,
466 disconnect: Effect.void,
467 retryNow: Effect.void,
468 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
469 const cache = Persistence.EnvironmentCacheStore.of({
470 loadShell: () => Effect.succeed(Option.none()),
471 saveShell: (_environmentId, snapshot) =>
472 Ref.update(saved, (values) => [...values, snapshot]),
473 loadThread: () => Effect.succeed(Option.none()),
474 saveThread: () => Effect.void,
475 removeThread: () => Effect.void,
476 loadServerConfig: () => Effect.succeed(Option.none()),
477 saveServerConfig: () => Effect.void,
478 loadVcsRefs: () => Effect.succeed(Option.none()),
479 saveVcsRefs: () => Effect.void,
480 removeVcsRefs: () => Effect.void,
481 clearVcsRefs: () => Effect.void,
482 clear: () => Effect.void,
483 });
484 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
485 load: () => Effect.succeed(Option.none()),
486 });
487
488 const shellState = yield* makeEnvironmentShellState().pipe(
489 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
490 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
491 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
492 );
493
494 const sendSnapshot = Effect.fn(function* (sequence: number) {
495 yield* Queue.offer(events, {
496 kind: "snapshot",
497 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: sequence },
498 });
499 yield* SubscriptionRef.changes(shellState).pipe(
500 Stream.filter(
501 (state) =>
502 Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === sequence,
503 ),
504 Stream.runHead,
505 );
506 });
507 yield* sendSnapshot(1);
508 yield* TestClock.adjust("500 millis");
509 for (let sequence = 2; sequence <= 10; sequence++) {
510 yield* sendSnapshot(sequence);
511 yield* TestClock.adjust("1 second");
512 }
513 expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);
514 yield* TestClock.adjust("1 second");
515 expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1, 10]);
516 yield* sendSnapshot(11);
517 yield* SubscriptionRef.set(supervisorState, {
518 ...AVAILABLE_CONNECTION_STATE,
519 desired: false,
520 });
521 yield* SubscriptionRef.changes(shellState).pipe(
522 Stream.filter((state) => state.status === "cached"),
523 Stream.runHead,
524 );
525 yield* TestClock.adjust("0 millis");
526 expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([
527 1, 10, 11,
528 ]);
529 }),
530 );
531
532 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
533 Effect.gen(function* () {
534 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
535 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
536 const saveStarted = yield* Deferred.make<void>();
537 const releaseSave = yield* Deferred.make<void>();
538 const client = {
539 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
540 } as unknown as WsRpcProtocolClient;
541 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
542 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
543 Option.some(session(client)),
544 );
545 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
546 target: TARGET,
547 state: supervisorState,
548 session: activeSession,
549 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
550 connect: Effect.void,
551 disconnect: Effect.void,
552 retryNow: Effect.void,
553 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
554 const cache = Persistence.EnvironmentCacheStore.of({
555 loadShell: () => Effect.succeed(Option.none()),
556 saveShell: (_environmentId, snapshot) =>
557 Deferred.succeed(saveStarted, undefined).pipe(
558 Effect.andThen(Deferred.await(releaseSave)),
559 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
560 ),
561 loadThread: () => Effect.succeed(Option.none()),
562 saveThread: () => Effect.void,
563 removeThread: () => Effect.void,
564 loadServerConfig: () => Effect.succeed(Option.none()),
565 saveServerConfig: () => Effect.void,
566 loadVcsRefs: () => Effect.succeed(Option.none()),
567 saveVcsRefs: () => Effect.void,
568 removeVcsRefs: () => Effect.void,
569 clearVcsRefs: () => Effect.void,
570 clear: () => Effect.void,
571 });
572 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
573 load: () => Effect.succeed(Option.none()),
574 });
575
576 const shellState = yield* makeEnvironmentShellState().pipe(
577 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
578 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
579 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
580 );
581
582 yield* SubscriptionRef.set(supervisorState, {
583 desired: true,
584 network: "online",
585 phase: "connecting",
586 stage: "synchronizing",
587 attempt: 1,
588 generation: 0,
589 lastFailure: null,
590 retryAt: null,
591 });
592 yield* Queue.offer(events, {
593 kind: "snapshot",
594 snapshot: LIVE_SHELL_SNAPSHOT,
595 });
596 yield* Queue.offer(events, { kind: "synchronized" });
597 yield* SubscriptionRef.changes(shellState).pipe(
598 Stream.filter((state) => state.status === "live"),
599 Stream.runHead,
600 );
601
602 yield* SubscriptionRef.set(supervisorState, {
603 desired: true,
604 network: "online",
605 phase: "connecting",
606 stage: "synchronizing",
607 attempt: 2,
608 generation: 1,
609 lastFailure: null,
610 retryAt: null,
611 });
612 yield* SubscriptionRef.set(supervisorState, {
613 desired: false,
614 network: "online",
615 phase: "available",
616 stage: null,
617 attempt: 2,
618 generation: 2,
619 lastFailure: null,
620 retryAt: null,
621 });
622 yield* Deferred.await(saveStarted);
623
624 yield* SubscriptionRef.set(supervisorState, {
625 desired: true,
626 network: "online",
627 phase: "connecting",
628 stage: "synchronizing",
629 attempt: 3,
630 generation: 3,
631 lastFailure: null,
632 retryAt: null,
633 });
634 for (let index = 0; index < 100; index += 1) {
635 if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
636 yield* Effect.yieldNow;
637 }
638
639 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
640 expect(yield* Ref.get(saved)).toEqual([]);
641
642 yield* Deferred.succeed(releaseSave, undefined);
643 for (let index = 0; index < 100; index += 1) {
644 if ((yield* Ref.get(saved)).length > 0) break;
645 yield* Effect.yieldNow;
646 }
647
648 expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
649 }),
650 );
651
652 it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
653 Effect.gen(function* () {
654 const repositoryIdentity = {
655 canonicalKey: "github.com/example/repo",
656 locator: {
657 source: "git-remote" as const,
658 remoteName: "origin",
659 remoteUrl: "https://github.com/example/repo.git",
660 },
661 };
662 const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
663 ...LIVE_SHELL_SNAPSHOT,
664 snapshotSequence: 1,
665 projects: [{ ...v2Project, repositoryIdentity: null }],
666 };
667 const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
668 ...LIVE_SHELL_SNAPSHOT,
669 snapshotSequence: 1,
670 projects: [{ ...v2Project, repositoryIdentity }],
671 };
672
673 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
674 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
675 const unenrichedSaveStarted = yield* Deferred.make<void>();
676 const releaseUnenrichedSave = yield* Deferred.make<void>();
677 const client = {
678 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
679 } as unknown as WsRpcProtocolClient;
680 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
681 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
682 Option.some(session(client)),
683 );
684 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
685 target: TARGET,
686 state: supervisorState,
687 session: activeSession,
688 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
689 connect: Effect.void,
690 disconnect: Effect.void,
691 retryNow: Effect.void,
692 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
693 const cache = Persistence.EnvironmentCacheStore.of({
694 loadShell: () => Effect.succeed(Option.none()),
695 saveShell: (_environmentId, snapshot) =>
696 Effect.gen(function* () {
697 if (snapshot.projects[0]?.repositoryIdentity == null) {
698 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
699 yield* Deferred.await(releaseUnenrichedSave);
700 }
701 yield* Ref.update(saved, (values) => [...values, snapshot]);
702 }),
703 loadThread: () => Effect.succeed(Option.none()),
704 saveThread: () => Effect.void,
705 removeThread: () => Effect.void,
706 loadServerConfig: () => Effect.succeed(Option.none()),
707 saveServerConfig: () => Effect.void,
708 loadVcsRefs: () => Effect.succeed(Option.none()),
709 saveVcsRefs: () => Effect.void,
710 removeVcsRefs: () => Effect.void,
711 clearVcsRefs: () => Effect.void,
712 clear: () => Effect.void,
713 });
714 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
715 load: () => Effect.succeed(Option.none()),
716 });
717
718 const shellState = yield* makeEnvironmentShellState().pipe(
719 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
720 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
721 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
722 );
723
724 yield* SubscriptionRef.set(supervisorState, {
725 desired: true,
726 network: "online",
727 phase: "connecting",
728 stage: "synchronizing",
729 attempt: 1,
730 generation: 0,
731 lastFailure: null,
732 retryAt: null,
733 });
734 yield* Queue.offer(events, {
735 kind: "snapshot",
736 snapshot: unenrichedSnapshot,
737 });
738 yield* Queue.offer(events, { kind: "synchronized" });
739 yield* SubscriptionRef.changes(shellState).pipe(
740 Stream.filter((state) => state.status === "live"),
741 Stream.runHead,
742 );
743
744 // Disconnect flush starts an immediate persist of the unenriched snapshot
745 // (debounced path needs TestClock advancement; flush does not).
746 yield* SubscriptionRef.set(supervisorState, {
747 desired: false,
748 network: "online",
749 phase: "available",
750 stage: null,
751 attempt: 1,
752 generation: 1,
753 lastFailure: null,
754 retryAt: null,
755 });
756 yield* Deferred.await(unenrichedSaveStarted);
757
758 yield* Queue.offer(events, {
759 kind: "snapshot",
760 snapshot: enrichedSnapshot,
761 });
762 yield* SubscriptionRef.changes(shellState).pipe(
763 Stream.filter(
764 (state) =>
765 Option.isSome(state.snapshot) &&
766 state.snapshot.value.projects[0]?.repositoryIdentity != null,
767 ),
768 Stream.runHead,
769 );
770
771 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
772 for (let index = 0; index < 100; index += 1) {
773 const values = yield* Ref.get(saved);
774 if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
775 break;
776 }
777 yield* Effect.yieldNow;
778 }
779
780 const finalSaved = (yield* Ref.get(saved)).at(-1);
781 expect(finalSaved?.snapshotSequence).toBe(1);
782 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
783 }),
784 );
785
786 it.effect("scope teardown flush stays stable while a save is blocked", () =>
787 Effect.gen(function* () {
788 const lateSnapshot: OrchestrationV2ShellSnapshot = {
789 ...LIVE_SHELL_SNAPSHOT,
790 snapshotSequence: 2,
791 projects: [{ ...v2Project, title: "Late stream event" }],
792 };
793 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
794 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
795 const saveStarted = yield* Deferred.make<void>();
796 const releaseSave = yield* Deferred.make<void>();
797 const client = {
798 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
799 } as unknown as WsRpcProtocolClient;
800 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
801 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
802 Option.some(session(client)),
803 );
804 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
805 target: TARGET,
806 state: supervisorState,
807 session: activeSession,
808 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
809 connect: Effect.void,
810 disconnect: Effect.void,
811 retryNow: Effect.void,
812 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
813 const cache = Persistence.EnvironmentCacheStore.of({
814 loadShell: () => Effect.succeed(Option.none()),
815 saveShell: (_environmentId, snapshot) =>
816 Deferred.succeed(saveStarted, undefined).pipe(
817 Effect.andThen(Deferred.await(releaseSave)),
818 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
819 ),
820 loadThread: () => Effect.succeed(Option.none()),
821 saveThread: () => Effect.void,
822 removeThread: () => Effect.void,
823 loadServerConfig: () => Effect.succeed(Option.none()),
824 saveServerConfig: () => Effect.void,
825 loadVcsRefs: () => Effect.succeed(Option.none()),
826 saveVcsRefs: () => Effect.void,
827 removeVcsRefs: () => Effect.void,
828 clearVcsRefs: () => Effect.void,
829 clear: () => Effect.void,
830 });
831 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
832 load: () => Effect.succeed(Option.none()),
833 });
834
835 const scope = yield* Scope.make();
836 const shellState = yield* makeEnvironmentShellState().pipe(
837 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
838 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
839 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
840 Scope.provide(scope),
841 );
842
843 yield* SubscriptionRef.set(supervisorState, {
844 desired: true,
845 network: "online",
846 phase: "connecting",
847 stage: "synchronizing",
848 attempt: 1,
849 generation: 0,
850 lastFailure: null,
851 retryAt: null,
852 });
853 yield* Queue.offer(events, {
854 kind: "snapshot",
855 snapshot: LIVE_SHELL_SNAPSHOT,
856 });
857 yield* Queue.offer(events, { kind: "synchronized" });
858 yield* SubscriptionRef.changes(shellState).pipe(
859 Stream.filter((state) => state.status === "live"),
860 Stream.runHead,
861 );
862
863 const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
864 yield* Deferred.await(saveStarted);
865 yield* Queue.offer(events, {
866 kind: "snapshot",
867 snapshot: lateSnapshot,
868 });
869 for (let index = 0; index < 50; index += 1) {
870 yield* Effect.yieldNow;
871 }
872 yield* Deferred.succeed(releaseSave, undefined);
873 yield* Fiber.join(closeFiber);
874
875 const values = yield* Ref.get(saved);
876 expect(values.length).toBeGreaterThan(0);
877 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
878 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
879 true,
880 );
881 }),
882 );
883
884 it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
885 Effect.gen(function* () {
886 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
887 ...v2ShellSnapshot,
888 snapshotSequence: 20,
889 projects: [{ ...v2Project, title: "Client ahead" }],
890 };
891 const httpSnapshot: OrchestrationV2ShellSnapshot = {
892 ...v2ShellSnapshot,
893 snapshotSequence: 4,
894 projects: [{ ...v2Project, title: "Server reset" }],
895 };
896 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
897 const client = {
898 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
899 } as unknown as WsRpcProtocolClient;
900 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
901 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
902 target: TARGET,
903 state: supervisorState,
904 session: yield* SubscriptionRef.make(Option.some(session(client))),
905 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
906 connect: Effect.void,
907 disconnect: Effect.void,
908 retryNow: Effect.void,
909 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
910 const cache = Persistence.EnvironmentCacheStore.of({
911 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
912 saveShell: () => Effect.void,
913 loadThread: () => Effect.succeed(Option.none()),
914 saveThread: () => Effect.void,
915 removeThread: () => Effect.void,
916 loadServerConfig: () => Effect.succeed(Option.none()),
917 saveServerConfig: () => Effect.void,
918 loadVcsRefs: () => Effect.succeed(Option.none()),
919 saveVcsRefs: () => Effect.void,
920 removeVcsRefs: () => Effect.void,
921 clearVcsRefs: () => Effect.void,
922 clear: () => Effect.void,
923 });
924 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
925 load: () => Effect.succeed(Option.some(httpSnapshot)),
926 });
927 const shellState = yield* makeEnvironmentShellState().pipe(
928 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
929 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
930 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
931 );
932
933 yield* SubscriptionRef.changes(shellState).pipe(
934 Stream.filter(
935 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
936 ),
937 Stream.runHead,
938 );
939
940 const state = yield* SubscriptionRef.get(shellState);
941 expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
942 expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
943 }),
944 );
945
946 it.effect("fills deferred cached pull request links without overwriting newer rows", () =>
947 Effect.gen(function* () {
948 const link = (number: number): ThreadPullRequestLink => ({
949 host: "github.com",
950 repository: "pingdotgg/t3code",
951 number,
952 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
953 source: "agent",
954 linkedAt: "2026-06-20T00:00:00.000Z",
955 snapshot: null,
956 stack: null,
957 });
958 const otherThreadId = ThreadId.make("thread-other");
959 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
960 ...v2ShellSnapshot,
961 snapshotSequence: 5,
962 threads: [v2ThreadShell, { ...v2ThreadShell, id: otherThreadId }],
963 };
964 const linksReady = yield* Deferred.make<void>();
965 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
966 const client = {
967 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
968 } as unknown as WsRpcProtocolClient;
969 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
970 target: TARGET,
971 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
972 session: yield* SubscriptionRef.make(Option.some(session(client))),
973 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
974 connect: Effect.void,
975 disconnect: Effect.void,
976 retryNow: Effect.void,
977 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
978 const cache = Persistence.EnvironmentCacheStore.of({
979 loadShell: () =>
980 Effect.succeedSome({
981 ...cachedSnapshot,
982 loadPullRequests: Deferred.await(linksReady).pipe(
983 Effect.as(
984 new Map([
985 [v2ThreadShell.id, [link(1)]],
986 [otherThreadId, [link(2)]],
987 ]),
988 ),
989 ),
990 }),
991 saveShell: () => Effect.void,
992 loadThread: () => Effect.succeedNone,
993 saveThread: () => Effect.void,
994 removeThread: () => Effect.void,
995 loadServerConfig: () => Effect.succeedNone,
996 saveServerConfig: () => Effect.void,
997 loadVcsRefs: () => Effect.succeedNone,
998 saveVcsRefs: () => Effect.void,
999 removeVcsRefs: () => Effect.void,
1000 clearVcsRefs: () => Effect.void,
1001 clear: () => Effect.void,
1002 });
1003 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
1004 load: () => Effect.succeedNone,
1005 });
1006 const shellState = yield* makeEnvironmentShellState().pipe(
1007 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1008 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1009 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
1010 );
1011
1012 const threadsOf = (state: {
1013 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
1014 }) => Option.getOrThrow(state.snapshot).threads;
1015 expect(threadsOf(yield* SubscriptionRef.get(shellState))).toEqual(cachedSnapshot.threads);
1016
1017 const serverRow = { ...v2ThreadShell, title: "From server", pullRequests: [link(9)] };
1018 yield* Queue.offer(events, {
1019 kind: "thread.updated",
1020 sequence: 6,
1021 location: "active",
1022 thread: serverRow,
1023 });
1024 yield* SubscriptionRef.changes(shellState).pipe(
1025 Stream.filter((state) => threadsOf(state)[0]?.title === "From server"),
1026 Stream.runHead,
1027 );
1028
1029 yield* Deferred.succeed(linksReady, undefined);
1030 const filled = yield* SubscriptionRef.changes(shellState).pipe(
1031 Stream.map(threadsOf),
1032 Stream.filter((threads) => threads[1]?.pullRequests !== undefined),
1033 Stream.runHead,
1034 Effect.map(Option.getOrThrow),
1035 );
1036 expect(filled[0]).toBe(serverRow);
1037 expect(filled[1]?.pullRequests).toEqual([link(2)]);
1038 }),
1039 );
1040
1041 it.effect("shows HTTP rows before their pull request links and saves them once filled", () =>
1042 Effect.gen(function* () {
1043 const link: ThreadPullRequestLink = {
1044 host: "github.com",
1045 repository: "pingdotgg/t3code",
1046 number: 7,
1047 url: "https://github.com/pingdotgg/t3code/pull/7",
1048 source: "agent",
1049 linkedAt: "2026-06-20T00:00:00.000Z",
1050 snapshot: null,
1051 stack: null,
1052 };
1053 const httpSnapshot: OrchestrationV2ShellSnapshot = {
1054 ...v2ShellSnapshot,
1055 snapshotSequence: 3,
1056 };
1057 const linksReady = yield* Deferred.make<void>();
1058 const saved = yield* Queue.unbounded<OrchestrationV2ShellSnapshot>();
1059 const client = {
1060 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.never,
1061 } as unknown as WsRpcProtocolClient;
1062 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1063 target: TARGET,
1064 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1065 session: yield* SubscriptionRef.make(Option.some(session(client))),
1066 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
1067 connect: Effect.void,
1068 disconnect: Effect.void,
1069 retryNow: Effect.void,
1070 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1071 const cache = Persistence.EnvironmentCacheStore.of({
1072 loadShell: () => Effect.succeedNone,
1073 saveShell: (_environmentId, snapshot) => Queue.offer(saved, snapshot),
1074 loadThread: () => Effect.succeedNone,
1075 saveThread: () => Effect.void,
1076 removeThread: () => Effect.void,
1077 loadServerConfig: () => Effect.succeedNone,
1078 saveServerConfig: () => Effect.void,
1079 loadVcsRefs: () => Effect.succeedNone,
1080 saveVcsRefs: () => Effect.void,
1081 removeVcsRefs: () => Effect.void,
1082 clearVcsRefs: () => Effect.void,
1083 clear: () => Effect.void,
1084 });
1085 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
1086 load: () =>
1087 Effect.succeedSome({
1088 ...httpSnapshot,
1089 loadPullRequests: Deferred.await(linksReady).pipe(
1090 Effect.as(new Map([[v2ThreadShell.id, [link]]])),
1091 ),
1092 }),
1093 });
1094 const shellState = yield* makeEnvironmentShellState().pipe(
1095 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1096 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1097 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
1098 );
1099
1100 const rows = yield* SubscriptionRef.changes(shellState).pipe(
1101 Stream.filter((state) => Option.isSome(state.snapshot)),
1102 Stream.runHead,
1103 Effect.map((state) => Option.getOrThrow(Option.getOrThrow(state).snapshot)),
1104 );
1105 expect(rows.threads[0]?.pullRequests).toBeUndefined();
1106 expect(rows).not.toHaveProperty("loadPullRequests");
1107
1108 yield* Deferred.succeed(linksReady, undefined);
1109 const filled = yield* SubscriptionRef.changes(shellState).pipe(
1110 Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]),
1111 Stream.filter((thread) => thread?.pullRequests !== undefined),
1112 Stream.runHead,
1113 Effect.map(Option.getOrThrow),
1114 );
1115 expect(filled?.pullRequests).toEqual([link]);
1116
1117 yield* TestClock.adjust("30 seconds");
1118 const saves = yield* Queue.takeAll(saved);
1119 expect(saves.at(-1)?.threads[0]?.pullRequests).toEqual([link]);
1120 }),
1121 );
1122
1123 it.effect("does not save rows whose deferred links are still pending", () =>
1124 Effect.gen(function* () {
1125 const link: ThreadPullRequestLink = {
1126 host: "github.com",
1127 repository: "pingdotgg/t3code",
1128 number: 8,
1129 url: "https://github.com/pingdotgg/t3code/pull/8",
1130 source: "agent",
1131 linkedAt: "2026-06-20T00:00:00.000Z",
1132 snapshot: null,
1133 stack: null,
1134 };
1135 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
1136 const client = {
1137 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.never,
1138 } as unknown as WsRpcProtocolClient;
1139 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1140 target: TARGET,
1141 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1142 session: yield* SubscriptionRef.make(Option.some(session(client))),
1143 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
1144 connect: Effect.void,
1145 disconnect: Effect.void,
1146 retryNow: Effect.void,
1147 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1148 const cache = Persistence.EnvironmentCacheStore.of({
1149 loadShell: () => Effect.succeedNone,
1150 saveShell: (_environmentId, snapshot) => Ref.update(saved, (all) => [...all, snapshot]),
1151 loadThread: () => Effect.succeedNone,
1152 saveThread: () => Effect.void,
1153 removeThread: () => Effect.void,
1154 loadServerConfig: () => Effect.succeedNone,
1155 saveServerConfig: () => Effect.void,
1156 loadVcsRefs: () => Effect.succeedNone,
1157 saveVcsRefs: () => Effect.void,
1158 removeVcsRefs: () => Effect.void,
1159 clearVcsRefs: () => Effect.void,
1160 clear: () => Effect.void,
1161 });
1162 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
1163 load: () =>
1164 Effect.succeedSome({
1165 ...v2ShellSnapshot,
1166 snapshotSequence: 3,
1167 loadPullRequests: Effect.never.pipe(Effect.as(new Map([[v2ThreadShell.id, [link]]]))),
1168 }),
1169 });
1170 const scope = yield* Scope.make();
1171 const shellState = yield* makeEnvironmentShellState().pipe(
1172 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1173 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1174 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
1175 Scope.provide(scope),
1176 );
1177 yield* SubscriptionRef.changes(shellState).pipe(
1178 Stream.filter((state) => Option.isSome(state.snapshot)),
1179 Stream.runHead,
1180 );
1181
1182 yield* TestClock.adjust("30 seconds");
1183 yield* Scope.close(scope, Exit.void);
1184 expect(yield* Ref.get(saved)).toEqual([]);
1185 }),
1186 );
1187
1188 it.effect("drops an older snapshot's links once a newer snapshot reuses its rows", () =>
1189 Effect.gen(function* () {
1190 const link = (number: number): ThreadPullRequestLink => ({
1191 host: "github.com",
1192 repository: "pingdotgg/t3code",
1193 number,
1194 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
1195 source: "agent",
1196 linkedAt: "2026-06-20T00:00:00.000Z",
1197 snapshot: null,
1198 stack: null,
1199 });
1200 const firstLinks = yield* Deferred.make<void>();
1201 const secondLinks = yield* Deferred.make<void>();
1202 const firstFillStarted = yield* Deferred.make<void>();
1203 const loads = yield* Ref.make(0);
1204 const subscriptions = yield* Ref.make(0);
1205 const client = {
1206 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
1207 Stream.unwrap(Ref.update(subscriptions, (n) => n + 1).pipe(Effect.as(Stream.never))),
1208 } as unknown as WsRpcProtocolClient;
1209 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
1210 Option.some(session(client)),
1211 );
1212 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1213 target: TARGET,
1214 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1215 session: activeSession,
1216 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
1217 connect: Effect.void,
1218 disconnect: Effect.void,
1219 retryNow: Effect.void,
1220 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1221 const cache = Persistence.EnvironmentCacheStore.of({
1222 loadShell: () => Effect.succeedNone,
1223 saveShell: () => Effect.void,
1224 loadThread: () => Effect.succeedNone,
1225 saveThread: () => Effect.void,
1226 removeThread: () => Effect.void,
1227 loadServerConfig: () => Effect.succeedNone,
1228 saveServerConfig: () => Effect.void,
1229 loadVcsRefs: () => Effect.succeedNone,
1230 saveVcsRefs: () => Effect.void,
1231 removeVcsRefs: () => Effect.void,
1232 clearVcsRefs: () => Effect.void,
1233 clear: () => Effect.void,
1234 });
1235 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
1236 load: () =>
1237 Ref.updateAndGet(loads, (n) => n + 1).pipe(
1238 Effect.map((n) =>
1239 Option.some({
1240 ...v2ShellSnapshot,
1241 snapshotSequence: n,
1242 loadPullRequests: (n === 1
1243 ? Deferred.succeed(firstFillStarted, undefined).pipe(
1244 Effect.andThen(Deferred.await(firstLinks)),
1245 )
1246 : Deferred.await(secondLinks)
1247 ).pipe(Effect.as(new Map([[v2ThreadShell.id, [link(n)]]]))),
1248 }),
1249 ),
1250 ),
1251 });
1252 const shellState = yield* makeEnvironmentShellState().pipe(
1253 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1254 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1255 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
1256 );
1257 yield* Deferred.await(firstFillStarted);
1258
1259 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
1260 yield* SubscriptionRef.changes(shellState).pipe(
1261 Stream.filter(
1262 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 2,
1263 ),
1264 Stream.runHead,
1265 );
1266
1267 yield* Deferred.succeed(firstLinks, undefined);
1268 yield* Deferred.succeed(secondLinks, undefined);
1269 const filled = yield* SubscriptionRef.changes(shellState).pipe(
1270 Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]?.pullRequests),
1271 Stream.filter((links) => links !== undefined),
1272 Stream.runHead,
1273 Effect.map(Option.getOrThrow),
1274 );
1275 expect(filled).toEqual([link(2)]);
1276 }),
1277 );
1278});