Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell-sync.test.ts

758 lines30.1 KB

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 { type EnvironmentShellState, 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 };
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("opts in to idle-child omission and counts authoritative snapshots and removals", () =>
482 Effect.gen(function* () {
483 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
484 const subscribeInput = yield* Deferred.make<unknown>();
485 const loadOptions = yield* Ref.make<ReadonlyArray<unknown>>([]);
486 const client = {
487 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: unknown) =>
488 Stream.unwrap(
489 Deferred.succeed(subscribeInput, input).pipe(Effect.as(Stream.fromQueue(events))),
490 ),
491 } as unknown as WsRpcProtocolClient;
492 const familySession: RpcSession.RpcSession = {
493 ...session(client),
494 initialConfig: Effect.succeed({
495 shellResumeCompletionMarker: true,
496 shellThreadFamilies: true,
497 } as never),
498 };
499 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
500 target: TARGET,
501 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
502 session: yield* SubscriptionRef.make(Option.some(familySession)),
503 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
504 connect: Effect.void,
505 disconnect: Effect.void,
506 retryNow: Effect.void,
507 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
508 const cache = Persistence.EnvironmentCacheStore.of({
509 loadShell: () => Effect.succeed(Option.none()),
510 saveShell: () => Effect.void,
511 loadThread: () => Effect.succeed(Option.none()),
512 saveThread: () => Effect.void,
513 removeThread: () => Effect.void,
514 loadServerConfig: () => Effect.succeed(Option.none()),
515 saveServerConfig: () => Effect.void,
516 loadVcsRefs: () => Effect.succeed(Option.none()),
517 saveVcsRefs: () => Effect.void,
518 removeVcsRefs: () => Effect.void,
519 clearVcsRefs: () => Effect.void,
520 clear: () => Effect.void,
521 });
522 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
523 load: (_prepared, options) =>
524 Ref.update(loadOptions, (all) => [...all, options]).pipe(
525 Effect.as(Option.some(LIVE_SHELL_SNAPSHOT)),
526 ),
527 });
528 const shellState = yield* makeEnvironmentShellState().pipe(
529 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
530 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
531 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
532 );
533 const stateWhere = (predicate: (state: EnvironmentShellState) => boolean) =>
534 SubscriptionRef.changes(shellState).pipe(Stream.filter(predicate), Stream.runHead);
535​
536 // Both transports must omit, or omitted children would come back through the socket.
537 expect(yield* Deferred.await(subscribeInput)).toMatchObject({
538 afterSequence: 1,
539 omitIdleSubagents: true,
540 });
541 expect(yield* Ref.get(loadOptions)).toEqual([{ omitIdleSubagents: true }]);
542 const loaded = Option.getOrThrow(yield* stateWhere((state) => state.generation > 0));
543 expect(loaded.removedAt.size).toBe(0);
544​
545 const gone = ThreadId.make("thread-gone");
546 yield* Queue.offer(events, {
547 kind: "snapshot",
548 snapshot: { ...LIVE_SHELL_SNAPSHOT, threads: [] },
549 resolvedRepositoryIdentityRoots: [],
550 });
551 yield* Queue.offer(events, {
552 kind: "thread.removed",
553 sequence: 2,
554 location: "active",
555 threadId: gone,
556 });
557 const removed = Option.getOrThrow(yield* stateWhere((state) => state.removedAt.size > 0));
558 // An enrichment refresh is not authoritative.
559 expect(removed.generation).toBe(loaded.generation);
560 expect(removed.removedAt.get(gone)).toBe(2);
561​
562 yield* Queue.offer(events, {
563 kind: "snapshot",
564 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 5 },
565 });
566 const reset = Option.getOrThrow(
567 yield* stateWhere((state) => state.generation > loaded.generation),
568 );
569 expect(reset.removedAt.size).toBe(0);
570 }),
571 );
572​
573 it.effect("fills deferred cached pull request links without overwriting newer rows", () =>
574 Effect.gen(function* () {
575 const link = (number: number): ThreadPullRequestLink => ({
576 host: "github.com",
577 repository: "pingdotgg/t3code",
578 number,
579 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
580 source: "agent",
581 linkedAt: "2026-06-20T00:00:00.000Z",
582 snapshot: null,
583 stack: null,
584 });
585 const otherThreadId = ThreadId.make("thread-other");
586 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
587 ...v2ShellSnapshot,
588 snapshotSequence: 5,
589 threads: [v2ThreadShell, { ...v2ThreadShell, id: otherThreadId }],
590 };
591 const linksReady = yield* Deferred.make<void>();
592 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
593 const client = {
594 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
595 } as unknown as WsRpcProtocolClient;
596 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
597 target: TARGET,
598 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
599 session: yield* SubscriptionRef.make(Option.some(session(client))),
600 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
601 connect: Effect.void,
602 disconnect: Effect.void,
603 retryNow: Effect.void,
604 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
605 const cache = Persistence.EnvironmentCacheStore.of({
606 loadShell: () =>
607 Effect.succeedSome({
608 ...cachedSnapshot,
609 loadPullRequests: Deferred.await(linksReady).pipe(
610 Effect.as(
611 new Map([
612 [v2ThreadShell.id, [link(1)]],
613 [otherThreadId, [link(2)]],
614 ]),
615 ),
616 ),
617 }),
618 saveShell: () => Effect.void,
619 loadThread: () => Effect.succeedNone,
620 saveThread: () => Effect.void,
621 removeThread: () => Effect.void,
622 loadServerConfig: () => Effect.succeedNone,
623 saveServerConfig: () => Effect.void,
624 loadVcsRefs: () => Effect.succeedNone,
625 saveVcsRefs: () => Effect.void,
626 removeVcsRefs: () => Effect.void,
627 clearVcsRefs: () => Effect.void,
628 clear: () => Effect.void,
629 });
630 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
631 load: () => Effect.succeedNone,
632 });
633 const shellState = yield* makeEnvironmentShellState().pipe(
634 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
635 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
636 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
637 );
638​
639 const threadsOf = (state: {
640 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
641 }) => Option.getOrThrow(state.snapshot).threads;
642 expect(threadsOf(yield* SubscriptionRef.get(shellState))).toEqual(cachedSnapshot.threads);
643​
644 const serverRow = { ...v2ThreadShell, title: "From server", pullRequests: [link(9)] };
645 yield* Queue.offer(events, {
646 kind: "thread.updated",
647 sequence: 6,
648 location: "active",
649 thread: serverRow,
650 });
651 yield* SubscriptionRef.changes(shellState).pipe(
652 Stream.filter((state) => threadsOf(state)[0]?.title === "From server"),
653 Stream.runHead,
654 );
655​
656 yield* Deferred.succeed(linksReady, undefined);
657 const filled = yield* SubscriptionRef.changes(shellState).pipe(
658 Stream.map(threadsOf),
659 Stream.filter((threads) => threads[1]?.pullRequests !== undefined),
660 Stream.runHead,
661 Effect.map(Option.getOrThrow),
662 );
663 expect(filled[0]).toBe(serverRow);
664 expect(filled[1]?.pullRequests).toEqual([link(2)]);
665 }),
666 );
667​
668 it.effect("drops an older snapshot's links once a newer snapshot reuses its rows", () =>
669 Effect.gen(function* () {
670 const link = (number: number): ThreadPullRequestLink => ({
671 host: "github.com",
672 repository: "pingdotgg/t3code",
673 number,
674 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
675 source: "agent",
676 linkedAt: "2026-06-20T00:00:00.000Z",
677 snapshot: null,
678 stack: null,
679 });
680 const firstLinks = yield* Deferred.make<void>();
681 const secondLinks = yield* Deferred.make<void>();
682 const firstFillStarted = yield* Deferred.make<void>();
683 const loads = yield* Ref.make(0);
684 const subscriptions = yield* Ref.make(0);
685 const client = {
686 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
687 Stream.unwrap(Ref.update(subscriptions, (n) => n + 1).pipe(Effect.as(Stream.never))),
688 } as unknown as WsRpcProtocolClient;
689 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
690 Option.some(session(client)),
691 );
692 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
693 target: TARGET,
694 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
695 session: activeSession,
696 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
697 connect: Effect.void,
698 disconnect: Effect.void,
699 retryNow: Effect.void,
700 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
701 const cache = Persistence.EnvironmentCacheStore.of({
702 loadShell: () => Effect.succeedNone,
703 saveShell: () => Effect.void,
704 loadThread: () => Effect.succeedNone,
705 saveThread: () => Effect.void,
706 removeThread: () => Effect.void,
707 loadServerConfig: () => Effect.succeedNone,
708 saveServerConfig: () => Effect.void,
709 loadVcsRefs: () => Effect.succeedNone,
710 saveVcsRefs: () => Effect.void,
711 removeVcsRefs: () => Effect.void,
712 clearVcsRefs: () => Effect.void,
713 clear: () => Effect.void,
714 });
715 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
716 load: () =>
717 Ref.updateAndGet(loads, (n) => n + 1).pipe(
718 Effect.map((n) =>
719 Option.some({
720 ...v2ShellSnapshot,
721 snapshotSequence: n,
722 loadPullRequests: (n === 1
723 ? Deferred.succeed(firstFillStarted, undefined).pipe(
724 Effect.andThen(Deferred.await(firstLinks)),
725 )
726 : Deferred.await(secondLinks)
727 ).pipe(Effect.as(new Map([[v2ThreadShell.id, [link(n)]]]))),
728 }),
729 ),
730 ),
731 });
732 const shellState = yield* makeEnvironmentShellState().pipe(
733 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
734 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
735 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
736 );
737 yield* Deferred.await(firstFillStarted);
738​
739 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
740 yield* SubscriptionRef.changes(shellState).pipe(
741 Stream.filter(
742 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 2,
743 ),
744 Stream.runHead,
745 );
746​
747 yield* Deferred.succeed(firstLinks, undefined);
748 yield* Deferred.succeed(secondLinks, undefined);
749 const filled = yield* SubscriptionRef.changes(shellState).pipe(
750 Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]?.pullRequests),
751 Stream.filter((links) => links !== undefined),
752 Stream.runHead,
753 Effect.map(Option.getOrThrow),
754 );
755 expect(filled).toEqual([link(2)]);
756 }),
757 );
758});