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

shell-sync.test.ts

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