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";
20
21import {
22 AVAILABLE_CONNECTION_STATE,
23 PrimaryConnectionTarget,
24 type PreparedConnection,
25} from "../connection/model.ts";
26import * as EnvironmentSupervisor from "../connection/supervisor.ts";
27import * as Persistence from "../platform/persistence.ts";
28import * as RpcSession from "../rpc/session.ts";
29import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
30import { makeEnvironmentShellState } from "./shell.ts";
31import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
32import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
33
34const TARGET = new PrimaryConnectionTarget({
35 environmentId: EnvironmentId.make("environment-1"),
36 label: "Test environment",
37 httpBaseUrl: "https://environment.example.test",
38 wsBaseUrl: "wss://environment.example.test",
39});
40
41const PREPARED: PreparedConnection = {
42 environmentId: TARGET.environmentId,
43 label: TARGET.label,
44 httpBaseUrl: TARGET.httpBaseUrl,
45 socketUrl: TARGET.wsBaseUrl,
46 httpAuthorization: null,
47 target: TARGET,
48};
49
50const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
51 ...v2ShellSnapshot,
52 snapshotSequence: 1,
53};
54
55function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
56 return {
57 client,
58 initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
59 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
60 ready: Effect.void,
61 probe: Effect.void,
62 closed: Effect.never,
63 };
64}
65
66describe("environment shell synchronization", () => {
67 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
68 Effect.gen(function* () {
69 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
70 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
71 const saveStarted = yield* Deferred.make<void>();
72 const releaseSave = yield* Deferred.make<void>();
73 const client = {
74 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
75 } as unknown as WsRpcProtocolClient;
76 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
77 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
78 Option.some(session(client)),
79 );
80 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
81 target: TARGET,
82 state: supervisorState,
83 session: activeSession,
84 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
85 connect: Effect.void,
86 disconnect: Effect.void,
87 retryNow: Effect.void,
88 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
89 const cache = Persistence.EnvironmentCacheStore.of({
90 loadShell: () => Effect.succeed(Option.none()),
91 saveShell: (_environmentId, snapshot) =>
92 Deferred.succeed(saveStarted, undefined).pipe(
93 Effect.andThen(Deferred.await(releaseSave)),
94 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
95 ),
96 loadThread: () => Effect.succeed(Option.none()),
97 saveThread: () => Effect.void,
98 removeThread: () => Effect.void,
99 loadServerConfig: () => Effect.succeed(Option.none()),
100 saveServerConfig: () => Effect.void,
101 loadVcsRefs: () => Effect.succeed(Option.none()),
102 saveVcsRefs: () => Effect.void,
103 removeVcsRefs: () => Effect.void,
104 clearVcsRefs: () => Effect.void,
105 clear: () => Effect.void,
106 });
107 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
108 load: () => Effect.succeed(Option.none()),
109 });
110
111 const shellState = yield* makeEnvironmentShellState().pipe(
112 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
113 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
114 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
115 );
116
117 yield* SubscriptionRef.set(supervisorState, {
118 desired: true,
119 network: "online",
120 phase: "connecting",
121 stage: "synchronizing",
122 attempt: 1,
123 generation: 0,
124 lastFailure: null,
125 retryAt: null,
126 });
127 yield* Queue.offer(events, {
128 kind: "snapshot",
129 snapshot: LIVE_SHELL_SNAPSHOT,
130 });
131 yield* Queue.offer(events, { kind: "synchronized" });
132 yield* SubscriptionRef.changes(shellState).pipe(
133 Stream.filter((state) => state.status === "live"),
134 Stream.runHead,
135 );
136
137 yield* SubscriptionRef.set(supervisorState, {
138 desired: true,
139 network: "online",
140 phase: "connecting",
141 stage: "synchronizing",
142 attempt: 2,
143 generation: 1,
144 lastFailure: null,
145 retryAt: null,
146 });
147 yield* SubscriptionRef.set(supervisorState, {
148 desired: false,
149 network: "online",
150 phase: "available",
151 stage: null,
152 attempt: 2,
153 generation: 2,
154 lastFailure: null,
155 retryAt: null,
156 });
157 yield* Deferred.await(saveStarted);
158
159 yield* SubscriptionRef.set(supervisorState, {
160 desired: true,
161 network: "online",
162 phase: "connecting",
163 stage: "synchronizing",
164 attempt: 3,
165 generation: 3,
166 lastFailure: null,
167 retryAt: null,
168 });
169 for (let index = 0; index < 100; index += 1) {
170 if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
171 yield* Effect.yieldNow;
172 }
173
174 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
175 expect(yield* Ref.get(saved)).toEqual([]);
176
177 yield* Deferred.succeed(releaseSave, undefined);
178 for (let index = 0; index < 100; index += 1) {
179 if ((yield* Ref.get(saved)).length > 0) break;
180 yield* Effect.yieldNow;
181 }
182
183 expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
184 }),
185 );
186
187 it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
188 Effect.gen(function* () {
189 const repositoryIdentity = {
190 canonicalKey: "github.com/example/repo",
191 locator: {
192 source: "git-remote" as const,
193 remoteName: "origin",
194 remoteUrl: "https://github.com/example/repo.git",
195 },
196 };
197 const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
198 ...LIVE_SHELL_SNAPSHOT,
199 snapshotSequence: 1,
200 projects: [{ ...v2Project, repositoryIdentity: null }],
201 };
202 const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
203 ...LIVE_SHELL_SNAPSHOT,
204 snapshotSequence: 1,
205 projects: [{ ...v2Project, repositoryIdentity }],
206 };
207
208 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
209 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
210 const unenrichedSaveStarted = yield* Deferred.make<void>();
211 const releaseUnenrichedSave = yield* Deferred.make<void>();
212 const client = {
213 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
214 } as unknown as WsRpcProtocolClient;
215 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
216 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
217 Option.some(session(client)),
218 );
219 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
220 target: TARGET,
221 state: supervisorState,
222 session: activeSession,
223 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
224 connect: Effect.void,
225 disconnect: Effect.void,
226 retryNow: Effect.void,
227 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
228 const cache = Persistence.EnvironmentCacheStore.of({
229 loadShell: () => Effect.succeed(Option.none()),
230 saveShell: (_environmentId, snapshot) =>
231 Effect.gen(function* () {
232 if (snapshot.projects[0]?.repositoryIdentity == null) {
233 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
234 yield* Deferred.await(releaseUnenrichedSave);
235 }
236 yield* Ref.update(saved, (values) => [...values, snapshot]);
237 }),
238 loadThread: () => Effect.succeed(Option.none()),
239 saveThread: () => Effect.void,
240 removeThread: () => Effect.void,
241 loadServerConfig: () => Effect.succeed(Option.none()),
242 saveServerConfig: () => Effect.void,
243 loadVcsRefs: () => Effect.succeed(Option.none()),
244 saveVcsRefs: () => Effect.void,
245 removeVcsRefs: () => Effect.void,
246 clearVcsRefs: () => Effect.void,
247 clear: () => Effect.void,
248 });
249 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
250 load: () => Effect.succeed(Option.none()),
251 });
252
253 const shellState = yield* makeEnvironmentShellState().pipe(
254 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
255 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
256 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
257 );
258
259 yield* SubscriptionRef.set(supervisorState, {
260 desired: true,
261 network: "online",
262 phase: "connecting",
263 stage: "synchronizing",
264 attempt: 1,
265 generation: 0,
266 lastFailure: null,
267 retryAt: null,
268 });
269 yield* Queue.offer(events, {
270 kind: "snapshot",
271 snapshot: unenrichedSnapshot,
272 });
273 yield* Queue.offer(events, { kind: "synchronized" });
274 yield* SubscriptionRef.changes(shellState).pipe(
275 Stream.filter((state) => state.status === "live"),
276 Stream.runHead,
277 );
278
279 // Disconnect flush starts an immediate persist of the unenriched snapshot
280 // (debounced path needs TestClock advancement; flush does not).
281 yield* SubscriptionRef.set(supervisorState, {
282 desired: false,
283 network: "online",
284 phase: "available",
285 stage: null,
286 attempt: 1,
287 generation: 1,
288 lastFailure: null,
289 retryAt: null,
290 });
291 yield* Deferred.await(unenrichedSaveStarted);
292
293 yield* Queue.offer(events, {
294 kind: "snapshot",
295 snapshot: enrichedSnapshot,
296 });
297 yield* SubscriptionRef.changes(shellState).pipe(
298 Stream.filter(
299 (state) =>
300 Option.isSome(state.snapshot) &&
301 state.snapshot.value.projects[0]?.repositoryIdentity != null,
302 ),
303 Stream.runHead,
304 );
305
306 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
307 for (let index = 0; index < 100; index += 1) {
308 const values = yield* Ref.get(saved);
309 if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
310 break;
311 }
312 yield* Effect.yieldNow;
313 }
314
315 const finalSaved = (yield* Ref.get(saved)).at(-1);
316 expect(finalSaved?.snapshotSequence).toBe(1);
317 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
318 }),
319 );
320
321 it.effect("scope teardown flush stays stable while a save is blocked", () =>
322 Effect.gen(function* () {
323 const lateSnapshot: OrchestrationV2ShellSnapshot = {
324 ...LIVE_SHELL_SNAPSHOT,
325 snapshotSequence: 2,
326 projects: [{ ...v2Project, title: "Late stream event" }],
327 };
328 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
329 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
330 const saveStarted = yield* Deferred.make<void>();
331 const releaseSave = yield* Deferred.make<void>();
332 const client = {
333 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
334 } as unknown as WsRpcProtocolClient;
335 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
336 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
337 Option.some(session(client)),
338 );
339 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
340 target: TARGET,
341 state: supervisorState,
342 session: activeSession,
343 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
344 connect: Effect.void,
345 disconnect: Effect.void,
346 retryNow: Effect.void,
347 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
348 const cache = Persistence.EnvironmentCacheStore.of({
349 loadShell: () => Effect.succeed(Option.none()),
350 saveShell: (_environmentId, snapshot) =>
351 Deferred.succeed(saveStarted, undefined).pipe(
352 Effect.andThen(Deferred.await(releaseSave)),
353 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
354 ),
355 loadThread: () => Effect.succeed(Option.none()),
356 saveThread: () => Effect.void,
357 removeThread: () => Effect.void,
358 loadServerConfig: () => Effect.succeed(Option.none()),
359 saveServerConfig: () => Effect.void,
360 loadVcsRefs: () => Effect.succeed(Option.none()),
361 saveVcsRefs: () => Effect.void,
362 removeVcsRefs: () => Effect.void,
363 clearVcsRefs: () => Effect.void,
364 clear: () => Effect.void,
365 });
366 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
367 load: () => Effect.succeed(Option.none()),
368 });
369
370 const scope = yield* Scope.make();
371 const shellState = yield* makeEnvironmentShellState().pipe(
372 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
373 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
374 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
375 Scope.provide(scope),
376 );
377
378 yield* SubscriptionRef.set(supervisorState, {
379 desired: true,
380 network: "online",
381 phase: "connecting",
382 stage: "synchronizing",
383 attempt: 1,
384 generation: 0,
385 lastFailure: null,
386 retryAt: null,
387 });
388 yield* Queue.offer(events, {
389 kind: "snapshot",
390 snapshot: LIVE_SHELL_SNAPSHOT,
391 });
392 yield* Queue.offer(events, { kind: "synchronized" });
393 yield* SubscriptionRef.changes(shellState).pipe(
394 Stream.filter((state) => state.status === "live"),
395 Stream.runHead,
396 );
397
398 const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
399 yield* Deferred.await(saveStarted);
400 yield* Queue.offer(events, {
401 kind: "snapshot",
402 snapshot: lateSnapshot,
403 });
404 for (let index = 0; index < 50; index += 1) {
405 yield* Effect.yieldNow;
406 }
407 yield* Deferred.succeed(releaseSave, undefined);
408 yield* Fiber.join(closeFiber);
409
410 const values = yield* Ref.get(saved);
411 expect(values.length).toBeGreaterThan(0);
412 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
413 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
414 true,
415 );
416 }),
417 );
418
419 it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
420 Effect.gen(function* () {
421 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
422 ...v2ShellSnapshot,
423 snapshotSequence: 20,
424 projects: [{ ...v2Project, title: "Client ahead" }],
425 };
426 const httpSnapshot: OrchestrationV2ShellSnapshot = {
427 ...v2ShellSnapshot,
428 snapshotSequence: 4,
429 projects: [{ ...v2Project, title: "Server reset" }],
430 };
431 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
432 const client = {
433 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
434 } as unknown as WsRpcProtocolClient;
435 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
436 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
437 target: TARGET,
438 state: supervisorState,
439 session: yield* SubscriptionRef.make(Option.some(session(client))),
440 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
441 connect: Effect.void,
442 disconnect: Effect.void,
443 retryNow: Effect.void,
444 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
445 const cache = Persistence.EnvironmentCacheStore.of({
446 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
447 saveShell: () => Effect.void,
448 loadThread: () => Effect.succeed(Option.none()),
449 saveThread: () => Effect.void,
450 removeThread: () => Effect.void,
451 loadServerConfig: () => Effect.succeed(Option.none()),
452 saveServerConfig: () => Effect.void,
453 loadVcsRefs: () => Effect.succeed(Option.none()),
454 saveVcsRefs: () => Effect.void,
455 removeVcsRefs: () => Effect.void,
456 clearVcsRefs: () => Effect.void,
457 clear: () => Effect.void,
458 });
459 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
460 load: () => Effect.succeed(Option.some(httpSnapshot)),
461 });
462 const shellState = yield* makeEnvironmentShellState().pipe(
463 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
464 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
465 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
466 );
467
468 yield* SubscriptionRef.changes(shellState).pipe(
469 Stream.filter(
470 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
471 ),
472 Stream.runHead,
473 );
474
475 const state = yield* SubscriptionRef.get(shellState);
476 expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
477 expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
478 }),
479 );
480
481 it.effect("fills deferred cached pull request links without overwriting newer rows", () =>
482 Effect.gen(function* () {
483 const link = (number: number): ThreadPullRequestLink => ({
484 host: "github.com",
485 repository: "pingdotgg/t3code",
486 number,
487 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
488 source: "agent",
489 linkedAt: "2026-06-20T00:00:00.000Z",
490 snapshot: null,
491 stack: null,
492 });
493 const otherThreadId = ThreadId.make("thread-other");
494 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
495 ...v2ShellSnapshot,
496 snapshotSequence: 5,
497 threads: [v2ThreadShell, { ...v2ThreadShell, id: otherThreadId }],
498 };
499 const linksReady = yield* Deferred.make<void>();
500 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
501 const client = {
502 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
503 } as unknown as WsRpcProtocolClient;
504 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
505 target: TARGET,
506 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
507 session: yield* SubscriptionRef.make(Option.some(session(client))),
508 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
509 connect: Effect.void,
510 disconnect: Effect.void,
511 retryNow: Effect.void,
512 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
513 const cache = Persistence.EnvironmentCacheStore.of({
514 loadShell: () =>
515 Effect.succeedSome({
516 ...cachedSnapshot,
517 loadPullRequests: Deferred.await(linksReady).pipe(
518 Effect.as(
519 new Map([
520 [v2ThreadShell.id, [link(1)]],
521 [otherThreadId, [link(2)]],
522 ]),
523 ),
524 ),
525 }),
526 saveShell: () => Effect.void,
527 loadThread: () => Effect.succeedNone,
528 saveThread: () => Effect.void,
529 removeThread: () => Effect.void,
530 loadServerConfig: () => Effect.succeedNone,
531 saveServerConfig: () => Effect.void,
532 loadVcsRefs: () => Effect.succeedNone,
533 saveVcsRefs: () => Effect.void,
534 removeVcsRefs: () => Effect.void,
535 clearVcsRefs: () => Effect.void,
536 clear: () => Effect.void,
537 });
538 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
539 load: () => Effect.succeedNone,
540 });
541 const shellState = yield* makeEnvironmentShellState().pipe(
542 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
543 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
544 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
545 );
546
547 const threadsOf = (state: {
548 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
549 }) => Option.getOrThrow(state.snapshot).threads;
550 expect(threadsOf(yield* SubscriptionRef.get(shellState))).toEqual(cachedSnapshot.threads);
551
552 const serverRow = { ...v2ThreadShell, title: "From server", pullRequests: [link(9)] };
553 yield* Queue.offer(events, {
554 kind: "thread.updated",
555 sequence: 6,
556 location: "active",
557 thread: serverRow,
558 });
559 yield* SubscriptionRef.changes(shellState).pipe(
560 Stream.filter((state) => threadsOf(state)[0]?.title === "From server"),
561 Stream.runHead,
562 );
563
564 yield* Deferred.succeed(linksReady, undefined);
565 const filled = yield* SubscriptionRef.changes(shellState).pipe(
566 Stream.map(threadsOf),
567 Stream.filter((threads) => threads[1]?.pullRequests !== undefined),
568 Stream.runHead,
569 Effect.map(Option.getOrThrow),
570 );
571 expect(filled[0]).toBe(serverRow);
572 expect(filled[1]?.pullRequests).toEqual([link(2)]);
573 }),
574 );
575
576 it.effect("drops an older snapshot's links once a newer snapshot reuses its rows", () =>
577 Effect.gen(function* () {
578 const link = (number: number): ThreadPullRequestLink => ({
579 host: "github.com",
580 repository: "pingdotgg/t3code",
581 number,
582 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
583 source: "agent",
584 linkedAt: "2026-06-20T00:00:00.000Z",
585 snapshot: null,
586 stack: null,
587 });
588 const firstLinks = yield* Deferred.make<void>();
589 const secondLinks = yield* Deferred.make<void>();
590 const firstFillStarted = yield* Deferred.make<void>();
591 const loads = yield* Ref.make(0);
592 const subscriptions = yield* Ref.make(0);
593 const client = {
594 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
595 Stream.unwrap(Ref.update(subscriptions, (n) => n + 1).pipe(Effect.as(Stream.never))),
596 } as unknown as WsRpcProtocolClient;
597 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
598 Option.some(session(client)),
599 );
600 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
601 target: TARGET,
602 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
603 session: activeSession,
604 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
605 connect: Effect.void,
606 disconnect: Effect.void,
607 retryNow: Effect.void,
608 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
609 const cache = Persistence.EnvironmentCacheStore.of({
610 loadShell: () => Effect.succeedNone,
611 saveShell: () => Effect.void,
612 loadThread: () => Effect.succeedNone,
613 saveThread: () => Effect.void,
614 removeThread: () => Effect.void,
615 loadServerConfig: () => Effect.succeedNone,
616 saveServerConfig: () => Effect.void,
617 loadVcsRefs: () => Effect.succeedNone,
618 saveVcsRefs: () => Effect.void,
619 removeVcsRefs: () => Effect.void,
620 clearVcsRefs: () => Effect.void,
621 clear: () => Effect.void,
622 });
623 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
624 load: () =>
625 Ref.updateAndGet(loads, (n) => n + 1).pipe(
626 Effect.map((n) =>
627 Option.some({
628 ...v2ShellSnapshot,
629 snapshotSequence: n,
630 loadPullRequests: (n === 1
631 ? Deferred.succeed(firstFillStarted, undefined).pipe(
632 Effect.andThen(Deferred.await(firstLinks)),
633 )
634 : Deferred.await(secondLinks)
635 ).pipe(Effect.as(new Map([[v2ThreadShell.id, [link(n)]]]))),
636 }),
637 ),
638 ),
639 });
640 const shellState = yield* makeEnvironmentShellState().pipe(
641 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
642 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
643 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
644 );
645 yield* Deferred.await(firstFillStarted);
646
647 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
648 yield* SubscriptionRef.changes(shellState).pipe(
649 Stream.filter(
650 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 2,
651 ),
652 Stream.runHead,
653 );
654
655 yield* Deferred.succeed(firstLinks, undefined);
656 yield* Deferred.succeed(secondLinks, undefined);
657 const filled = yield* SubscriptionRef.changes(shellState).pipe(
658 Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]?.pullRequests),
659 Stream.filter((links) => links !== undefined),
660 Stream.runHead,
661 Effect.map(Option.getOrThrow),
662 );
663 expect(filled).toEqual([link(2)]);
664 }),
665 );
666});