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

shell-sync.test.ts

913 lines35.9 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 closed: Effect.never,
64 };
66​
67const makePersistenceHarness = Effect.fn("test.makeShellPersistenceHarness")(function* (
68 saveShell: Persistence.EnvironmentCacheStore["Service"]["saveShell"],
69) {
70 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
71 const client = {
72 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
73 } as unknown as WsRpcProtocolClient;
74 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
75 target: TARGET,
76 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
77 session: yield* SubscriptionRef.make(Option.some(session(client))),
78 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
79 connect: Effect.void,
80 disconnect: Effect.void,
81 retryNow: Effect.void,
82 });
83 const cache = Persistence.EnvironmentCacheStore.of({
84 loadShell: () => Effect.succeedNone,
85 saveShell,
86 loadThread: () => Effect.succeedNone,
87 saveThread: () => Effect.void,
88 removeThread: () => Effect.void,
89 loadServerConfig: () => Effect.succeedNone,
90 saveServerConfig: () => Effect.void,
91 loadVcsRefs: () => Effect.succeedNone,
92 saveVcsRefs: () => Effect.void,
93 removeVcsRefs: () => Effect.void,
94 clearVcsRefs: () => Effect.void,
95 clear: () => Effect.void,
96 });
97 const state = yield* makeEnvironmentShellState().pipe(
98 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
99 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
100 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, {
101 load: () => Effect.succeedNone,
102 }),
103 );
104 const send = Effect.fn("test.sendShellItem")(function* (
105 item: OrchestrationV2ShellStreamItem,
106 ready: (snapshot: OrchestrationV2ShellSnapshot) => boolean,
107 ) {
108 const previous = yield* SubscriptionRef.get(state);
109 yield* Queue.offer(events, item);
110 return yield* SubscriptionRef.changes(state).pipe(
111 Stream.filter((value) => value !== previous),
112 Stream.map((value) => value.snapshot),
113 Stream.filter(Option.isSome),
114 Stream.map((value) => value.value),
115 Stream.filter(ready),
116 Stream.runHead,
117 Effect.map(Option.getOrThrow),
118 );
119 });
120 yield* send({ kind: "snapshot", snapshot: LIVE_SHELL_SNAPSHOT }, () => true);
121 return { state, send };
122});
123​
124describe("environment shell synchronization", () => {
125 it.effect("skips unchanged shell writes, persists resets and flushes changed rows", () =>
126 Effect.gen(function* () {
127 const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
128 yield* Effect.scoped(
129 Effect.gen(function* () {
130 const h = yield* makePersistenceHarness((_id, snapshot) =>
131 SubscriptionRef.update(saved, (values) => [...values, snapshot]),
132 );
133 yield* TestClock.adjust("500 millis");
134 yield* h.send(
135 { kind: "thread.updated", sequence: 10, location: "active", thread: v2ThreadShell },
136 (snapshot) => snapshot.snapshotSequence === 10,
137 );
138 yield* TestClock.adjust("10 seconds");
139 expect(
140 (yield* SubscriptionRef.get(saved)).map((snapshot) => snapshot.snapshotSequence),
141 ).toEqual([1]);
142 const live = Option.getOrThrow((yield* SubscriptionRef.get(h.state)).snapshot);
143 expect(live.snapshotSequence).toBe(10);
144 const enriched = yield* h.send(
145 {
146 kind: "snapshot",
147 snapshot: { ...live, projects: live.projects.map((project) => ({ ...project })) },
148 resolvedRepositoryIdentityRoots: live.projects.map(
149 (project) => project.workspaceRoot,
150 ),
151 },
152 () => true,
153 );
154 expect(enriched.projects).toEqual(live.projects);
155 expect(enriched.snapshotSequence).toBe(10);
156 yield* TestClock.adjust("10 seconds");
157 expect(
158 (yield* SubscriptionRef.get(saved)).map((snapshot) => snapshot.snapshotSequence),
159 ).toEqual([1]);
160 yield* h.send(
161 { kind: "snapshot", snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 4 } },
162 (snapshot) => snapshot.snapshotSequence === 4,
163 );
164 yield* TestClock.adjust("10 seconds");
165 yield* h.send(
166 {
167 kind: "snapshot",
168 snapshot: {
169 ...LIVE_SHELL_SNAPSHOT,
170 snapshotSequence: 4,
171 projects: [{ ...v2Project, title: "Changed at same sequence" }],
172 },
173 },
174 (snapshot) => snapshot.projects[0]?.title === "Changed at same sequence",
175 );
176 }),
177 );
178 expect(
179 (yield* SubscriptionRef.get(saved)).map((snapshot) => [
180 snapshot.snapshotSequence,
181 snapshot.projects[0]?.title,
182 ]),
183 ).toEqual([
184 [1, v2Project.title],
185 [4, v2Project.title],
186 [4, "Changed at same sequence"],
187 ]);
188 }),
189 );
190​
191 it.effect("retries a failed shell save after a cursor-only update", () =>
192 Effect.gen(function* () {
193 const attempts = yield* Ref.make<ReadonlyArray<number>>([]);
194 yield* Effect.scoped(
195 Effect.gen(function* () {
196 const h = yield* makePersistenceHarness((_id, snapshot) =>
197 Effect.gen(function* () {
198 const values = yield* Ref.updateAndGet(attempts, (values) => [
199 ...values,
200 snapshot.snapshotSequence,
201 ]);
202 if (values.length === 1)
203 return yield* new Persistence.ConnectionPersistenceError({
204 operation: "save-shell",
205 message: "test failure",
206 });
207 }),
208 );
209 yield* TestClock.adjust("500 millis");
210 yield* h.send(
211 { kind: "thread.updated", sequence: 2, location: "active", thread: v2ThreadShell },
212 (snapshot) => snapshot.snapshotSequence === 2,
213 );
214 yield* TestClock.adjust("10 seconds");
215 }),
216 );
217 expect(yield* Ref.get(attempts)).toEqual([1, 2]);
218 }),
219 );
220​
221 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
222 Effect.gen(function* () {
223 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
224 const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
225 const saveStarted = yield* Deferred.make<void>();
226 const releaseSave = yield* Deferred.make<void>();
227 const client = {
228 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
229 } as unknown as WsRpcProtocolClient;
230 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
231 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
232 Option.some(session(client)),
233 );
234 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
235 target: TARGET,
236 state: supervisorState,
237 session: activeSession,
238 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
239 connect: Effect.void,
240 disconnect: Effect.void,
241 retryNow: Effect.void,
242 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
243 const cache = Persistence.EnvironmentCacheStore.of({
244 loadShell: () => Effect.succeedNone,
245 saveShell: (_environmentId, snapshot) =>
246 Deferred.succeed(saveStarted, undefined).pipe(
247 Effect.andThen(Deferred.await(releaseSave)),
248 Effect.andThen(SubscriptionRef.update(saved, (values) => [...values, snapshot])),
249 ),
250 loadThread: () => Effect.succeedNone,
251 saveThread: () => Effect.void,
252 removeThread: () => Effect.void,
253 loadServerConfig: () => Effect.succeedNone,
254 saveServerConfig: () => Effect.void,
255 loadVcsRefs: () => Effect.succeedNone,
256 saveVcsRefs: () => Effect.void,
257 removeVcsRefs: () => Effect.void,
258 clearVcsRefs: () => Effect.void,
259 clear: () => Effect.void,
260 });
261 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
262 load: () => Effect.succeedNone,
263 });
264​
265 const shellState = yield* makeEnvironmentShellState().pipe(
266 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
267 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
268 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
269 );
270​
271 yield* SubscriptionRef.set(supervisorState, {
272 desired: true,
273 network: "online",
274 phase: "connecting",
275 stage: "synchronizing",
276 attempt: 1,
277 generation: 0,
278 lastFailure: null,
279 retryAt: null,
280 });
281 yield* Queue.offer(events, {
282 kind: "snapshot",
283 snapshot: LIVE_SHELL_SNAPSHOT,
284 });
285 yield* Queue.offer(events, { kind: "synchronized" });
286 yield* SubscriptionRef.changes(shellState).pipe(
287 Stream.filter((state) => state.status === "live"),
288 Stream.runHead,
289 );
290​
291 yield* SubscriptionRef.set(supervisorState, {
292 desired: true,
293 network: "online",
294 phase: "connecting",
295 stage: "synchronizing",
296 attempt: 2,
297 generation: 1,
298 lastFailure: null,
299 retryAt: null,
300 });
301 yield* SubscriptionRef.set(supervisorState, {
302 desired: false,
303 network: "online",
304 phase: "available",
305 stage: null,
306 attempt: 2,
307 generation: 2,
308 lastFailure: null,
309 retryAt: null,
310 });
311 yield* Deferred.await(saveStarted);
312​
313 yield* SubscriptionRef.set(supervisorState, {
314 desired: true,
315 network: "online",
316 phase: "connecting",
317 stage: "synchronizing",
318 attempt: 3,
319 generation: 3,
320 lastFailure: null,
321 retryAt: null,
322 });
323 yield* SubscriptionRef.changes(shellState).pipe(
324 Stream.filter((state) => state.status === "synchronizing"),
325 Stream.runHead,
326 );
327​
328 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
329 expect(yield* SubscriptionRef.get(saved)).toEqual([]);
330​
331 yield* Deferred.succeed(releaseSave, undefined);
332 yield* SubscriptionRef.changes(saved).pipe(
333 Stream.filter((values) => values.length > 0),
334 Stream.runHead,
335 );
336​
337 expect(yield* SubscriptionRef.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
338 }),
339 );
340​
341 it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
342 Effect.gen(function* () {
343 const repositoryIdentity = {
344 canonicalKey: "github.com/example/repo",
345 locator: {
346 source: "git-remote" as const,
347 remoteName: "origin",
348 remoteUrl: "https://github.com/example/repo.git",
349 },
350 };
351 const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
352 ...LIVE_SHELL_SNAPSHOT,
353 snapshotSequence: 1,
354 projects: [{ ...v2Project, repositoryIdentity: null }],
355 };
356 const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
357 ...LIVE_SHELL_SNAPSHOT,
358 snapshotSequence: 1,
359 projects: [{ ...v2Project, repositoryIdentity }],
360 };
361​
362 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
363 const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
364 const unenrichedSaveStarted = yield* Deferred.make<void>();
365 const releaseUnenrichedSave = yield* Deferred.make<void>();
366 const client = {
367 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
368 } as unknown as WsRpcProtocolClient;
369 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
370 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
371 Option.some(session(client)),
372 );
373 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
374 target: TARGET,
375 state: supervisorState,
376 session: activeSession,
377 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
378 connect: Effect.void,
379 disconnect: Effect.void,
380 retryNow: Effect.void,
381 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
382 const cache = Persistence.EnvironmentCacheStore.of({
383 loadShell: () => Effect.succeedNone,
384 saveShell: (_environmentId, snapshot) =>
385 Effect.gen(function* () {
386 if (snapshot.projects[0]?.repositoryIdentity == null) {
387 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
388 yield* Deferred.await(releaseUnenrichedSave);
389 }
390 yield* SubscriptionRef.update(saved, (values) => [...values, snapshot]);
391 }),
392 loadThread: () => Effect.succeedNone,
393 saveThread: () => Effect.void,
394 removeThread: () => Effect.void,
395 loadServerConfig: () => Effect.succeedNone,
396 saveServerConfig: () => Effect.void,
397 loadVcsRefs: () => Effect.succeedNone,
398 saveVcsRefs: () => Effect.void,
399 removeVcsRefs: () => Effect.void,
400 clearVcsRefs: () => Effect.void,
401 clear: () => Effect.void,
402 });
403 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
404 load: () => Effect.succeedNone,
405 });
406​
407 const shellState = yield* makeEnvironmentShellState().pipe(
408 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
409 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
410 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
411 );
412​
413 yield* SubscriptionRef.set(supervisorState, {
414 desired: true,
415 network: "online",
416 phase: "connecting",
417 stage: "synchronizing",
418 attempt: 1,
419 generation: 0,
420 lastFailure: null,
421 retryAt: null,
422 });
423 yield* Queue.offer(events, {
424 kind: "snapshot",
425 snapshot: unenrichedSnapshot,
426 });
427 yield* Queue.offer(events, { kind: "synchronized" });
428 yield* SubscriptionRef.changes(shellState).pipe(
429 Stream.filter((state) => state.status === "live"),
430 Stream.runHead,
431 );
432​
433 // Disconnect flush starts an immediate persist of the unenriched snapshot
434 // (debounced path needs TestClock advancement; flush does not).
435 yield* SubscriptionRef.set(supervisorState, {
436 desired: false,
437 network: "online",
438 phase: "available",
439 stage: null,
440 attempt: 1,
441 generation: 1,
442 lastFailure: null,
443 retryAt: null,
444 });
445 yield* Deferred.await(unenrichedSaveStarted);
446​
447 yield* Queue.offer(events, {
448 kind: "snapshot",
449 snapshot: enrichedSnapshot,
450 });
451 yield* SubscriptionRef.changes(shellState).pipe(
452 Stream.filter(
453 (state) =>
454 Option.isSome(state.snapshot) &&
455 state.snapshot.value.projects[0]?.repositoryIdentity != null,
456 ),
457 Stream.runHead,
458 );
459​
460 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
461 yield* SubscriptionRef.changes(saved).pipe(
462 Stream.filter((values) => values.at(-1)?.projects[0]?.repositoryIdentity != null),
463 Stream.runHead,
464 );
465​
466 const finalSaved = (yield* SubscriptionRef.get(saved)).at(-1);
467 expect(finalSaved?.snapshotSequence).toBe(1);
468 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
469 }),
470 );
471​
472 it.effect("scope teardown flush stays stable while a save is blocked", () =>
473 Effect.gen(function* () {
474 const lateSnapshot: OrchestrationV2ShellSnapshot = {
475 ...LIVE_SHELL_SNAPSHOT,
476 snapshotSequence: 2,
477 projects: [{ ...v2Project, title: "Late stream event" }],
478 };
479 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
480 const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
481 const saveStarted = yield* Deferred.make<void>();
482 const releaseSave = yield* Deferred.make<void>();
483 const client = {
484 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
485 } as unknown as WsRpcProtocolClient;
486 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
487 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
488 Option.some(session(client)),
489 );
490 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
491 target: TARGET,
492 state: supervisorState,
493 session: activeSession,
494 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
495 connect: Effect.void,
496 disconnect: Effect.void,
497 retryNow: Effect.void,
498 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
499 const cache = Persistence.EnvironmentCacheStore.of({
500 loadShell: () => Effect.succeedNone,
501 saveShell: (_environmentId, snapshot) =>
502 Deferred.succeed(saveStarted, undefined).pipe(
503 Effect.andThen(Deferred.await(releaseSave)),
504 Effect.andThen(SubscriptionRef.update(saved, (values) => [...values, snapshot])),
505 ),
506 loadThread: () => Effect.succeedNone,
507 saveThread: () => Effect.void,
508 removeThread: () => Effect.void,
509 loadServerConfig: () => Effect.succeedNone,
510 saveServerConfig: () => Effect.void,
511 loadVcsRefs: () => Effect.succeedNone,
512 saveVcsRefs: () => Effect.void,
513 removeVcsRefs: () => Effect.void,
514 clearVcsRefs: () => Effect.void,
515 clear: () => Effect.void,
516 });
517 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
518 load: () => Effect.succeedNone,
519 });
520​
521 const scope = yield* Scope.make();
522 const shellState = yield* makeEnvironmentShellState().pipe(
523 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
524 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
525 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
526 Scope.provide(scope),
527 );
528​
529 yield* SubscriptionRef.set(supervisorState, {
530 desired: true,
531 network: "online",
532 phase: "connecting",
533 stage: "synchronizing",
534 attempt: 1,
535 generation: 0,
536 lastFailure: null,
537 retryAt: null,
538 });
539 yield* Queue.offer(events, {
540 kind: "snapshot",
541 snapshot: LIVE_SHELL_SNAPSHOT,
542 });
543 yield* Queue.offer(events, { kind: "synchronized" });
544 yield* SubscriptionRef.changes(shellState).pipe(
545 Stream.filter((state) => state.status === "live"),
546 Stream.runHead,
547 );
548​
549 const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
550 yield* Deferred.await(saveStarted);
551 yield* Queue.offer(events, {
552 kind: "snapshot",
553 snapshot: lateSnapshot,
554 });
555 for (let index = 0; index < 50; index += 1) {
556 yield* Effect.yieldNow;
557 }
558 yield* Deferred.succeed(releaseSave, undefined);
559 yield* Fiber.join(closeFiber);
560​
561 const values = yield* SubscriptionRef.get(saved);
562 expect(values.length).toBeGreaterThan(0);
563 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
564 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
565 true,
566 );
567 }),
568 );
569​
570 it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
571 Effect.gen(function* () {
572 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
573 ...v2ShellSnapshot,
574 snapshotSequence: 20,
575 projects: [{ ...v2Project, title: "Client ahead" }],
576 };
577 const httpSnapshot: OrchestrationV2ShellSnapshot = {
578 ...v2ShellSnapshot,
579 snapshotSequence: 4,
580 projects: [{ ...v2Project, title: "Server reset" }],
581 };
582 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
583 const client = {
584 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
585 } as unknown as WsRpcProtocolClient;
586 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
587 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
588 target: TARGET,
589 state: supervisorState,
590 session: yield* SubscriptionRef.make(Option.some(session(client))),
591 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
592 connect: Effect.void,
593 disconnect: Effect.void,
594 retryNow: Effect.void,
595 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
596 const cache = Persistence.EnvironmentCacheStore.of({
597 loadShell: () => Effect.succeedSome(cachedSnapshot),
598 saveShell: () => Effect.void,
599 loadThread: () => Effect.succeedNone,
600 saveThread: () => Effect.void,
601 removeThread: () => Effect.void,
602 loadServerConfig: () => Effect.succeedNone,
603 saveServerConfig: () => Effect.void,
604 loadVcsRefs: () => Effect.succeedNone,
605 saveVcsRefs: () => Effect.void,
606 removeVcsRefs: () => Effect.void,
607 clearVcsRefs: () => Effect.void,
608 clear: () => Effect.void,
609 });
610 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
611 load: () => Effect.succeedSome(httpSnapshot),
612 });
613 const shellState = yield* makeEnvironmentShellState().pipe(
614 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
615 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
616 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
617 );
618​
619 yield* SubscriptionRef.changes(shellState).pipe(
620 Stream.filter(
621 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
622 ),
623 Stream.runHead,
624 );
625​
626 const state = yield* SubscriptionRef.get(shellState);
627 expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
628 expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
629 }),
630 );
631​
632 it.effect("opts in to shell omissions and counts authoritative snapshots and removals", () =>
633 Effect.gen(function* () {
634 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
635 const subscribeInput = yield* Deferred.make<unknown>();
636 const loadOptions = yield* Ref.make<ReadonlyArray<unknown>>([]);
637 const client = {
638 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: unknown) =>
639 Stream.unwrap(
640 Deferred.succeed(subscribeInput, input).pipe(Effect.as(Stream.fromQueue(events))),
641 ),
642 } as unknown as WsRpcProtocolClient;
643 const familySession: RpcSession.RpcSession = {
644 ...session(client),
645 initialConfig: Effect.succeed({
646 shellResumeCompletionMarker: true,
647 shellThreadFamilies: true,
648 shellOlderSettled: true,
649 } as never),
650 };
651 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
652 target: TARGET,
653 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
654 session: yield* SubscriptionRef.make(Option.some(familySession)),
655 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
656 connect: Effect.void,
657 disconnect: Effect.void,
658 retryNow: Effect.void,
659 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
660 const cache = Persistence.EnvironmentCacheStore.of({
661 loadShell: () => Effect.succeedNone,
662 saveShell: () => Effect.void,
663 loadThread: () => Effect.succeedNone,
664 saveThread: () => Effect.void,
665 removeThread: () => Effect.void,
666 loadServerConfig: () => Effect.succeedNone,
667 saveServerConfig: () => Effect.void,
668 loadVcsRefs: () => Effect.succeedNone,
669 saveVcsRefs: () => Effect.void,
670 removeVcsRefs: () => Effect.void,
671 clearVcsRefs: () => Effect.void,
672 clear: () => Effect.void,
673 });
674 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
675 load: (_prepared, options) =>
676 Ref.update(loadOptions, (all) => [...all, options]).pipe(
677 Effect.as(Option.some(LIVE_SHELL_SNAPSHOT)),
678 ),
679 });
680 const shellState = yield* makeEnvironmentShellState().pipe(
681 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
682 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
683 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
684 );
685 const stateWhere = (predicate: (state: EnvironmentShellState) => boolean) =>
686 SubscriptionRef.changes(shellState).pipe(Stream.filter(predicate), Stream.runHead);
687​
688 // Both transports must omit, or omitted children would come back through the socket.
689 expect(yield* Deferred.await(subscribeInput)).toMatchObject({
690 afterSequence: 1,
691 omitIdleSubagents: true,
692 omitOlderSettled: true,
693 });
694 expect(yield* Ref.get(loadOptions)).toEqual([
695 { omitIdleSubagents: true, omitOlderSettled: true },
696 ]);
697 const loaded = Option.getOrThrow(yield* stateWhere((state) => state.generation > 0));
698 expect(loaded.removedAt.size).toBe(0);
699​
700 const gone = ThreadId.make("thread-gone");
701 yield* Queue.offer(events, {
702 kind: "snapshot",
703 snapshot: { ...LIVE_SHELL_SNAPSHOT, threads: [] },
704 resolvedRepositoryIdentityRoots: [],
705 });
706 yield* Queue.offer(events, {
707 kind: "thread.removed",
708 sequence: 2,
709 location: "active",
710 threadId: gone,
711 });
712 const removed = Option.getOrThrow(yield* stateWhere((state) => state.removedAt.size > 0));
713 // An enrichment refresh is not authoritative.
714 expect(removed.generation).toBe(loaded.generation);
715 expect(removed.removedAt.get(gone)).toBe(2);
716​
717 yield* Queue.offer(events, {
718 kind: "snapshot",
719 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 5 },
720 });
721 const reset = Option.getOrThrow(
722 yield* stateWhere((state) => state.generation > loaded.generation),
723 );
724 expect(reset.removedAt.size).toBe(0);
725 }),
726 );
727​
728 it.effect("fills deferred cached pull request links without overwriting newer rows", () =>
729 Effect.gen(function* () {
730 const link = (number: number): ThreadPullRequestLink => ({
731 host: "github.com",
732 repository: "pingdotgg/t3code",
733 number,
734 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
735 source: "agent",
736 linkedAt: "2026-06-20T00:00:00.000Z",
737 snapshot: null,
738 stack: null,
739 });
740 const otherThreadId = ThreadId.make("thread-other");
741 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
742 ...v2ShellSnapshot,
743 snapshotSequence: 5,
744 threads: [v2ThreadShell, { ...v2ThreadShell, id: otherThreadId }],
745 };
746 const linksReady = yield* Deferred.make<void>();
747 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
748 const client = {
749 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
750 } as unknown as WsRpcProtocolClient;
751 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
752 target: TARGET,
753 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
754 session: yield* SubscriptionRef.make(Option.some(session(client))),
755 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
756 connect: Effect.void,
757 disconnect: Effect.void,
758 retryNow: Effect.void,
759 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
760 const cache = Persistence.EnvironmentCacheStore.of({
761 loadShell: () =>
762 Effect.succeedSome({
763 ...cachedSnapshot,
764 loadPullRequests: Deferred.await(linksReady).pipe(
765 Effect.as(
766 new Map([
767 [v2ThreadShell.id, [link(1)]],
768 [otherThreadId, [link(2)]],
769 ]),
770 ),
771 ),
772 }),
773 saveShell: () => Effect.void,
774 loadThread: () => Effect.succeedNone,
775 saveThread: () => Effect.void,
776 removeThread: () => Effect.void,
777 loadServerConfig: () => Effect.succeedNone,
778 saveServerConfig: () => Effect.void,
779 loadVcsRefs: () => Effect.succeedNone,
780 saveVcsRefs: () => Effect.void,
781 removeVcsRefs: () => Effect.void,
782 clearVcsRefs: () => Effect.void,
783 clear: () => Effect.void,
784 });
785 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
786 load: () => Effect.succeedNone,
787 });
788 const shellState = yield* makeEnvironmentShellState().pipe(
789 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
790 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
791 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
792 );
793​
794 const threadsOf = (state: {
795 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
796 }) => Option.getOrThrow(state.snapshot).threads;
797 expect(threadsOf(yield* SubscriptionRef.get(shellState))).toEqual(cachedSnapshot.threads);
798​
799 const serverRow = { ...v2ThreadShell, title: "From server", pullRequests: [link(9)] };
800 yield* Queue.offer(events, {
801 kind: "thread.updated",
802 sequence: 6,
803 location: "active",
804 thread: serverRow,
805 });
806 yield* SubscriptionRef.changes(shellState).pipe(
807 Stream.filter((state) => threadsOf(state)[0]?.title === "From server"),
808 Stream.runHead,
809 );
810​
811 yield* Deferred.succeed(linksReady, undefined);
812 const filled = yield* SubscriptionRef.changes(shellState).pipe(
813 Stream.map(threadsOf),
814 Stream.filter((threads) => threads[1]?.pullRequests !== undefined),
815 Stream.runHead,
816 Effect.map(Option.getOrThrow),
817 );
818 expect(filled[0]).toBe(serverRow);
819 expect(filled[1]?.pullRequests).toEqual([link(2)]);
820 }),
821 );
822​
823 it.effect("drops an older snapshot's links once a newer snapshot reuses its rows", () =>
824 Effect.gen(function* () {
825 const link = (number: number): ThreadPullRequestLink => ({
826 host: "github.com",
827 repository: "pingdotgg/t3code",
828 number,
829 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
830 source: "agent",
831 linkedAt: "2026-06-20T00:00:00.000Z",
832 snapshot: null,
833 stack: null,
834 });
835 const firstLinks = yield* Deferred.make<void>();
836 const secondLinks = yield* Deferred.make<void>();
837 const firstFillStarted = yield* Deferred.make<void>();
838 const loads = yield* Ref.make(0);
839 const subscriptions = yield* Ref.make(0);
840 const client = {
841 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
842 Stream.unwrap(Ref.update(subscriptions, (n) => n + 1).pipe(Effect.as(Stream.never))),
843 } as unknown as WsRpcProtocolClient;
844 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
845 Option.some(session(client)),
846 );
847 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
848 target: TARGET,
849 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
850 session: activeSession,
851 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
852 connect: Effect.void,
853 disconnect: Effect.void,
854 retryNow: Effect.void,
855 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
856 const cache = Persistence.EnvironmentCacheStore.of({
857 loadShell: () => Effect.succeedNone,
858 saveShell: () => Effect.void,
859 loadThread: () => Effect.succeedNone,
860 saveThread: () => Effect.void,
861 removeThread: () => Effect.void,
862 loadServerConfig: () => Effect.succeedNone,
863 saveServerConfig: () => Effect.void,
864 loadVcsRefs: () => Effect.succeedNone,
865 saveVcsRefs: () => Effect.void,
866 removeVcsRefs: () => Effect.void,
867 clearVcsRefs: () => Effect.void,
868 clear: () => Effect.void,
869 });
870 const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
871 load: () =>
872 Ref.updateAndGet(loads, (n) => n + 1).pipe(
873 Effect.map((n) =>
874 Option.some({
875 ...v2ShellSnapshot,
876 snapshotSequence: n,
877 loadPullRequests: (n === 1
878 ? Deferred.succeed(firstFillStarted, undefined).pipe(
879 Effect.andThen(Deferred.await(firstLinks)),
880 )
881 : Deferred.await(secondLinks)
882 ).pipe(Effect.as(new Map([[v2ThreadShell.id, [link(n)]]]))),
883 }),
884 ),
885 ),
886 });
887 const shellState = yield* makeEnvironmentShellState().pipe(
888 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
889 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
890 Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
891 );
892 yield* Deferred.await(firstFillStarted);
893​
894 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
895 yield* SubscriptionRef.changes(shellState).pipe(
896 Stream.filter(
897 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 2,
898 ),
899 Stream.runHead,
900 );
901​
902 yield* Deferred.succeed(firstLinks, undefined);
903 yield* Deferred.succeed(secondLinks, undefined);
904 const filled = yield* SubscriptionRef.changes(shellState).pipe(
905 Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]?.pullRequests),
906 Stream.filter((links) => links !== undefined),
907 Stream.runHead,
908 Effect.map(Option.getOrThrow),
909 );
910 expect(filled).toEqual([link(2)]);
911 }),
912 );
913});