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