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