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

shell-sync.test.ts

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