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