Open History to see the last commit
1import {
2 EnvironmentId,
3 ORCHESTRATION_V2_WS_METHODS,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as Option from "effect/Option";
13import * as Queue from "effect/Queue";
14import * as Ref from "effect/Ref";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18
19import {
20 AVAILABLE_CONNECTION_STATE,
21 PrimaryConnectionTarget,
22 type PreparedConnection,
23} from "../connection/model.ts";
24import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25import * as ConnectionWakeups from "../connection/wakeups.ts";
26import * as Persistence from "../platform/persistence.ts";
27import * as RpcSession from "../rpc/session.ts";
28import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
29import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
30import { v2Project, v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
31
32const TARGET = new PrimaryConnectionTarget({
33 environmentId: EnvironmentId.make("environment-1"),
34 label: "Test environment",
35 httpBaseUrl: "https://environment.example.test",
36 wsBaseUrl: "wss://environment.example.test",
37});
38
39const PREPARED: PreparedConnection = {
40 environmentId: TARGET.environmentId,
41 label: TARGET.label,
42 httpBaseUrl: TARGET.httpBaseUrl,
43 socketUrl: TARGET.wsBaseUrl,
44 httpAuthorization: null,
45 target: TARGET,
46};
47
48const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
49 ...v2ShellSnapshot,
50 snapshotSequence: 1,
51};
52
53function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
54 return {
55 client,
56 initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
57 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
58 ready: Effect.void,
59 probe: Effect.void,
60 closed: Effect.never,
61 };
62}
63
64describe("environment shell synchronization", () => {
65 it.effect("publishes live state before persistence and preserves it when ready", () =>
66 Effect.gen(function* () {
67 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
68 const client = {
69 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
70 } as unknown as WsRpcProtocolClient;
71 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
72 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
73 Option.some(session(client)),
74 );
75 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
76 target: TARGET,
77 state: supervisorState,
78 session: activeSession,
79 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
80 connect: Effect.void,
81 disconnect: Effect.void,
82 retryNow: Effect.void,
83 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
84 const cache = Persistence.EnvironmentCacheStore.of({
85 loadShell: () => Effect.succeed(Option.none()),
86 saveShell: () => Effect.void,
87 loadThread: () => Effect.succeed(Option.none()),
88 saveThread: () => Effect.void,
89 removeThread: () => Effect.void,
90 loadServerConfig: () => Effect.succeed(Option.none()),
91 saveServerConfig: () => Effect.void,
92 loadVcsRefs: () => Effect.succeed(Option.none()),
93 saveVcsRefs: () => Effect.void,
94 removeVcsRefs: () => Effect.void,
95 clearVcsRefs: () => Effect.void,
96 clear: () => Effect.void,
97 });
98 // Cold cache with no HTTP snapshot available → falls back to the
99 // socket-embedded snapshot.
100 const snapshotLoader = ShellSnapshotLoader.of({
101 load: () => Effect.succeed(Option.none()),
102 });
103 const shellState = yield* makeEnvironmentShellState().pipe(
104 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
105 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
106 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
107 );
108
109 yield* SubscriptionRef.set(supervisorState, {
110 desired: true,
111 network: "online",
112 phase: "connecting",
113 stage: "synchronizing",
114 attempt: 1,
115 generation: 0,
116 lastFailure: null,
117 retryAt: null,
118 });
119 yield* Queue.offer(events, {
120 kind: "snapshot",
121 snapshot: LIVE_SHELL_SNAPSHOT,
122 });
123 const synchronizing = yield* SubscriptionRef.changes(shellState).pipe(
124 Stream.filter((state) => state.status === "synchronizing" && Option.isSome(state.snapshot)),
125 Stream.runHead,
126 );
127 expect(Option.getOrThrow(Option.getOrThrow(synchronizing).snapshot)).toEqual(
128 LIVE_SHELL_SNAPSHOT,
129 );
130
131 yield* Queue.offer(events, { kind: "synchronized" });
132 yield* SubscriptionRef.changes(shellState).pipe(
133 Stream.filter((state) => state.status === "live"),
134 Stream.runHead,
135 );
136
137 yield* SubscriptionRef.set(supervisorState, {
138 desired: true,
139 network: "online",
140 phase: "connected",
141 stage: null,
142 attempt: 1,
143 generation: 1,
144 lastFailure: null,
145 retryAt: null,
146 });
147 for (let index = 0; index < 10; index += 1) {
148 yield* Effect.yieldNow;
149 }
150
151 const state = yield* SubscriptionRef.get(shellState);
152 expect(state.status).toBe("live");
153 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
154 }),
155 );
156
157 it.effect("refreshes a warm shell cache from HTTP before resuming", () =>
158 Effect.gen(function* () {
159 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
160 ...v2ShellSnapshot,
161 snapshotSequence: 5,
162 };
163 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
164 const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
165 const capturedCompletionMarker = yield* Ref.make(false);
166 const loaderCalls = yield* SubscriptionRef.make(0);
167 const httpSnapshot: OrchestrationV2ShellSnapshot = {
168 ...v2ShellSnapshot,
169 snapshotSequence: 9,
170 };
171 const client = {
172 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: {
173 readonly afterSequence?: number;
174 readonly requestCompletionMarker?: true;
175 }) =>
176 Stream.unwrap(
177 Effect.all([
178 Ref.set(capturedCompletionMarker, input.requestCompletionMarker === true),
179 SubscriptionRef.set(capturedAfterSequence, input.afterSequence),
180 ]).pipe(Effect.as(Stream.fromQueue(events))),
181 ),
182 } as unknown as WsRpcProtocolClient;
183 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
184 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
185 Option.some(session(client)),
186 );
187 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
188 target: TARGET,
189 state: supervisorState,
190 session: activeSession,
191 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
192 connect: Effect.void,
193 disconnect: Effect.void,
194 retryNow: Effect.void,
195 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
196 const cache = Persistence.EnvironmentCacheStore.of({
197 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
198 saveShell: () => Effect.void,
199 loadThread: () => Effect.succeed(Option.none()),
200 saveThread: () => Effect.void,
201 removeThread: () => Effect.void,
202 loadServerConfig: () => Effect.succeed(Option.none()),
203 saveServerConfig: () => Effect.void,
204 loadVcsRefs: () => Effect.succeed(Option.none()),
205 saveVcsRefs: () => Effect.void,
206 removeVcsRefs: () => Effect.void,
207 clearVcsRefs: () => Effect.void,
208 clear: () => Effect.void,
209 });
210 const snapshotLoader = ShellSnapshotLoader.of({
211 load: () =>
212 SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(
213 Effect.as(Option.some(httpSnapshot)),
214 ),
215 });
216 const shellState = yield* makeEnvironmentShellState().pipe(
217 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
218 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
219 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
220 );
221
222 // Wait until the subscription is established from the warm cache.
223 yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
224 Stream.filter((value) => value !== undefined),
225 Stream.runHead,
226 );
227
228 expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(9);
229 expect(yield* Ref.get(capturedCompletionMarker)).toBe(true);
230 expect(yield* SubscriptionRef.get(loaderCalls)).toBe(1);
231 const synchronizing = yield* SubscriptionRef.get(shellState);
232 expect(synchronizing.status).toBe("synchronizing");
233 expect(Option.getOrThrow(synchronizing.snapshot)).toEqual(httpSnapshot);
234
235 yield* Queue.offer(events, { kind: "synchronized" });
236 yield* SubscriptionRef.changes(shellState).pipe(
237 Stream.filter((value) => value.status === "live"),
238 Stream.runHead,
239 );
240 }),
241 );
242
243 it.effect("resubscribes from the in-memory shell cursor when the app becomes active", () =>
244 Effect.gen(function* () {
245 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
246 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
247 const loaderCalls = yield* Ref.make(0);
248 const capturedAfterSequences = yield* Ref.make<ReadonlyArray<number | undefined>>([]);
249 const client = {
250 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: {
251 readonly afterSequence?: number;
252 }) =>
253 Stream.unwrap(
254 Ref.update(capturedAfterSequences, (captured) => [
255 ...captured,
256 input.afterSequence,
257 ]).pipe(Effect.as(Stream.fromQueue(events))),
258 ),
259 } as unknown as WsRpcProtocolClient;
260 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
261 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
262 Option.some(session(client)),
263 );
264 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
265 target: TARGET,
266 state: supervisorState,
267 session: activeSession,
268 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
269 connect: Effect.void,
270 disconnect: Effect.void,
271 retryNow: Effect.void,
272 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
273 const cache = Persistence.EnvironmentCacheStore.of({
274 loadShell: () => Effect.succeed(Option.some(LIVE_SHELL_SNAPSHOT)),
275 saveShell: () => Effect.void,
276 loadThread: () => Effect.succeed(Option.none()),
277 saveThread: () => Effect.void,
278 removeThread: () => Effect.void,
279 loadServerConfig: () => Effect.succeed(Option.none()),
280 saveServerConfig: () => Effect.void,
281 loadVcsRefs: () => Effect.succeed(Option.none()),
282 saveVcsRefs: () => Effect.void,
283 removeVcsRefs: () => Effect.void,
284 clearVcsRefs: () => Effect.void,
285 clear: () => Effect.void,
286 });
287 const snapshotLoader = ShellSnapshotLoader.of({
288 load: () =>
289 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
290 Effect.map((count) =>
291 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
292 ),
293 ),
294 });
295 const shellState = yield* makeEnvironmentShellState().pipe(
296 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
297 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
298 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
299 Effect.provideService(
300 ConnectionWakeups.ConnectionWakeups,
301 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
302 ),
303 );
304
305 // A new session starts from an authoritative HTTP snapshot.
306 for (let attempt = 0; attempt < 100; attempt += 1) {
307 if ((yield* Ref.get(capturedAfterSequences)).length >= 1) break;
308 yield* Effect.yieldNow;
309 }
310 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10]);
311 yield* Queue.offer(events, { kind: "synchronized" });
312 yield* SubscriptionRef.changes(shellState).pipe(
313 Stream.filter((value) => value.status === "live"),
314 Stream.runHead,
315 );
316
317 // A newer snapshot arrives on the stream and advances the cursor.
318 yield* Queue.offer(events, {
319 kind: "snapshot",
320 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 40 },
321 });
322 yield* SubscriptionRef.changes(shellState).pipe(
323 Stream.filter(
324 (value) => Option.isSome(value.snapshot) && value.snapshot.value.snapshotSequence === 40,
325 ),
326 Stream.runHead,
327 );
328
329 yield* Queue.offer(wakeups, "application-active");
330 for (let attempt = 0; attempt < 100; attempt += 1) {
331 if ((yield* Ref.get(capturedAfterSequences)).length >= 2) break;
332 yield* Effect.yieldNow;
333 }
334 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40]);
335 yield* Queue.offer(events, { kind: "synchronized" });
336
337 yield* Queue.offer(wakeups, "application-active-probe");
338 for (let attempt = 0; attempt < 100; attempt += 1) {
339 if ((yield* Ref.get(capturedAfterSequences)).length >= 3) break;
340 yield* Effect.yieldNow;
341 }
342 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40]);
343
344 yield* Queue.offer(wakeups, "application-active-reconnect");
345 for (let attempt = 0; attempt < 10; attempt += 1) {
346 yield* Effect.yieldNow;
347 }
348 expect((yield* Ref.get(capturedAfterSequences)).length).toBe(3);
349 expect(yield* Ref.get(loaderCalls)).toBe(1);
350
351 // Replacing the session performs another authoritative refresh.
352 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
353 for (let attempt = 0; attempt < 100; attempt += 1) {
354 if ((yield* Ref.get(capturedAfterSequences)).length >= 4) break;
355 yield* Effect.yieldNow;
356 }
357 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40, 20]);
358 expect(yield* Ref.get(loaderCalls)).toBe(2);
359 }),
360 );
361
362 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
363 Effect.gen(function* () {
364 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
365 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
366 const saveStarted = yield* Deferred.make<void>();
367 const releaseSave = yield* Deferred.make<void>();
368 const client = {
369 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
370 } as unknown as WsRpcProtocolClient;
371 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
372 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
373 Option.some(session(client)),
374 );
375 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
376 target: TARGET,
377 state: supervisorState,
378 session: activeSession,
379 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
380 connect: Effect.void,
381 disconnect: Effect.void,
382 retryNow: Effect.void,
383 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
384 const cache = Persistence.EnvironmentCacheStore.of({
385 loadShell: () => Effect.succeed(Option.none()),
386 saveShell: (_environmentId, snapshot) =>
387 Deferred.succeed(saveStarted, undefined).pipe(
388 Effect.andThen(Deferred.await(releaseSave)),
389 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
390 ),
391 loadThread: () => Effect.succeed(Option.none()),
392 saveThread: () => Effect.void,
393 removeThread: () => Effect.void,
394 loadServerConfig: () => Effect.succeed(Option.none()),
395 saveServerConfig: () => Effect.void,
396 loadVcsRefs: () => Effect.succeed(Option.none()),
397 saveVcsRefs: () => Effect.void,
398 removeVcsRefs: () => Effect.void,
399 clearVcsRefs: () => Effect.void,
400 clear: () => Effect.void,
401 });
402 const snapshotLoader = ShellSnapshotLoader.of({
403 load: () => Effect.succeed(Option.none()),
404 });
405
406 const shellState = yield* makeEnvironmentShellState().pipe(
407 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
408 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
409 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
410 );
411
412 yield* SubscriptionRef.set(supervisorState, {
413 desired: true,
414 network: "online",
415 phase: "connecting",
416 stage: "synchronizing",
417 attempt: 1,
418 generation: 0,
419 lastFailure: null,
420 retryAt: null,
421 });
422 yield* Queue.offer(events, {
423 kind: "snapshot",
424 snapshot: LIVE_SHELL_SNAPSHOT,
425 });
426 yield* Queue.offer(events, { kind: "synchronized" });
427 yield* SubscriptionRef.changes(shellState).pipe(
428 Stream.filter((state) => state.status === "live"),
429 Stream.runHead,
430 );
431
432 yield* SubscriptionRef.set(supervisorState, {
433 desired: true,
434 network: "online",
435 phase: "connecting",
436 stage: "synchronizing",
437 attempt: 2,
438 generation: 1,
439 lastFailure: null,
440 retryAt: null,
441 });
442 yield* SubscriptionRef.set(supervisorState, {
443 desired: false,
444 network: "online",
445 phase: "available",
446 stage: null,
447 attempt: 2,
448 generation: 2,
449 lastFailure: null,
450 retryAt: null,
451 });
452 yield* Deferred.await(saveStarted);
453
454 yield* SubscriptionRef.set(supervisorState, {
455 desired: true,
456 network: "online",
457 phase: "connecting",
458 stage: "synchronizing",
459 attempt: 3,
460 generation: 3,
461 lastFailure: null,
462 retryAt: null,
463 });
464 for (let index = 0; index < 100; index += 1) {
465 if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
466 yield* Effect.yieldNow;
467 }
468
469 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
470 expect(yield* Ref.get(saved)).toEqual([]);
471
472 yield* Deferred.succeed(releaseSave, undefined);
473 for (let index = 0; index < 100; index += 1) {
474 if ((yield* Ref.get(saved)).length > 0) break;
475 yield* Effect.yieldNow;
476 }
477
478 expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
479 }),
480 );
481
482 it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
483 Effect.gen(function* () {
484 const repositoryIdentity = {
485 canonicalKey: "github.com/example/repo",
486 locator: {
487 source: "git-remote" as const,
488 remoteName: "origin",
489 remoteUrl: "https://github.com/example/repo.git",
490 },
491 };
492 const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
493 ...LIVE_SHELL_SNAPSHOT,
494 snapshotSequence: 1,
495 projects: [{ ...v2Project, repositoryIdentity: null }],
496 };
497 const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
498 ...LIVE_SHELL_SNAPSHOT,
499 snapshotSequence: 1,
500 projects: [{ ...v2Project, repositoryIdentity }],
501 };
502
503 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
504 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
505 const unenrichedSaveStarted = yield* Deferred.make<void>();
506 const releaseUnenrichedSave = yield* Deferred.make<void>();
507 const client = {
508 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
509 } as unknown as WsRpcProtocolClient;
510 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
511 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
512 Option.some(session(client)),
513 );
514 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
515 target: TARGET,
516 state: supervisorState,
517 session: activeSession,
518 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
519 connect: Effect.void,
520 disconnect: Effect.void,
521 retryNow: Effect.void,
522 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
523 const cache = Persistence.EnvironmentCacheStore.of({
524 loadShell: () => Effect.succeed(Option.none()),
525 saveShell: (_environmentId, snapshot) =>
526 Effect.gen(function* () {
527 if (snapshot.projects[0]?.repositoryIdentity == null) {
528 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
529 yield* Deferred.await(releaseUnenrichedSave);
530 }
531 yield* Ref.update(saved, (values) => [...values, snapshot]);
532 }),
533 loadThread: () => Effect.succeed(Option.none()),
534 saveThread: () => Effect.void,
535 removeThread: () => Effect.void,
536 loadServerConfig: () => Effect.succeed(Option.none()),
537 saveServerConfig: () => Effect.void,
538 loadVcsRefs: () => Effect.succeed(Option.none()),
539 saveVcsRefs: () => Effect.void,
540 removeVcsRefs: () => Effect.void,
541 clearVcsRefs: () => Effect.void,
542 clear: () => Effect.void,
543 });
544 const snapshotLoader = ShellSnapshotLoader.of({
545 load: () => Effect.succeed(Option.none()),
546 });
547
548 const shellState = yield* makeEnvironmentShellState().pipe(
549 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
550 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
551 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
552 );
553
554 yield* SubscriptionRef.set(supervisorState, {
555 desired: true,
556 network: "online",
557 phase: "connecting",
558 stage: "synchronizing",
559 attempt: 1,
560 generation: 0,
561 lastFailure: null,
562 retryAt: null,
563 });
564 yield* Queue.offer(events, {
565 kind: "snapshot",
566 snapshot: unenrichedSnapshot,
567 });
568 yield* Queue.offer(events, { kind: "synchronized" });
569 yield* SubscriptionRef.changes(shellState).pipe(
570 Stream.filter((state) => state.status === "live"),
571 Stream.runHead,
572 );
573
574 // Disconnect flush starts an immediate persist of the unenriched snapshot
575 // (debounced path needs TestClock advancement; flush does not).
576 yield* SubscriptionRef.set(supervisorState, {
577 desired: false,
578 network: "online",
579 phase: "available",
580 stage: null,
581 attempt: 1,
582 generation: 1,
583 lastFailure: null,
584 retryAt: null,
585 });
586 yield* Deferred.await(unenrichedSaveStarted);
587
588 // Same sequence, different content. Session stays open so the stream can
589 // still apply enrichment while the older save is in flight.
590 yield* Queue.offer(events, {
591 kind: "snapshot",
592 snapshot: enrichedSnapshot,
593 });
594 yield* SubscriptionRef.changes(shellState).pipe(
595 Stream.filter(
596 (state) =>
597 Option.isSome(state.snapshot) &&
598 state.snapshot.value.projects[0]?.repositoryIdentity != null,
599 ),
600 Stream.runHead,
601 );
602
603 // Completing the older same-sequence save must re-persist the latest object.
604 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
605 for (let index = 0; index < 100; index += 1) {
606 const values = yield* Ref.get(saved);
607 if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
608 break;
609 }
610 yield* Effect.yieldNow;
611 }
612
613 const finalSaved = (yield* Ref.get(saved)).at(-1);
614 expect(finalSaved?.snapshotSequence).toBe(1);
615 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
616 }),
617 );
618
619 it.effect("scope teardown flush stays stable while a save is blocked", () =>
620 Effect.gen(function* () {
621 const lateSnapshot: OrchestrationV2ShellSnapshot = {
622 ...LIVE_SHELL_SNAPSHOT,
623 snapshotSequence: 2,
624 projects: [{ ...v2Project, title: "Late stream event" }],
625 };
626 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
627 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
628 const saveStarted = yield* Deferred.make<void>();
629 const releaseSave = yield* Deferred.make<void>();
630 const client = {
631 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
632 } as unknown as WsRpcProtocolClient;
633 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
634 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
635 Option.some(session(client)),
636 );
637 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
638 target: TARGET,
639 state: supervisorState,
640 session: activeSession,
641 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
642 connect: Effect.void,
643 disconnect: Effect.void,
644 retryNow: Effect.void,
645 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
646 const cache = Persistence.EnvironmentCacheStore.of({
647 loadShell: () => Effect.succeed(Option.none()),
648 saveShell: (_environmentId, snapshot) =>
649 Deferred.succeed(saveStarted, undefined).pipe(
650 Effect.andThen(Deferred.await(releaseSave)),
651 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
652 ),
653 loadThread: () => Effect.succeed(Option.none()),
654 saveThread: () => Effect.void,
655 removeThread: () => Effect.void,
656 loadServerConfig: () => Effect.succeed(Option.none()),
657 saveServerConfig: () => Effect.void,
658 loadVcsRefs: () => Effect.succeed(Option.none()),
659 saveVcsRefs: () => Effect.void,
660 removeVcsRefs: () => Effect.void,
661 clearVcsRefs: () => Effect.void,
662 clear: () => Effect.void,
663 });
664 const snapshotLoader = ShellSnapshotLoader.of({
665 load: () => Effect.succeed(Option.none()),
666 });
667
668 const scope = yield* Scope.make();
669 const shellState = yield* makeEnvironmentShellState().pipe(
670 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
671 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
672 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
673 Scope.provide(scope),
674 );
675
676 yield* SubscriptionRef.set(supervisorState, {
677 desired: true,
678 network: "online",
679 phase: "connecting",
680 stage: "synchronizing",
681 attempt: 1,
682 generation: 0,
683 lastFailure: null,
684 retryAt: null,
685 });
686 yield* Queue.offer(events, {
687 kind: "snapshot",
688 snapshot: LIVE_SHELL_SNAPSHOT,
689 });
690 yield* Queue.offer(events, { kind: "synchronized" });
691 yield* SubscriptionRef.changes(shellState).pipe(
692 Stream.filter((state) => state.status === "live"),
693 Stream.runHead,
694 );
695
696 // Close scope so the finalizer flush blocks on save. Workers must be
697 // interrupted before that flush; late stream events must not extend it.
698 const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
699 yield* Deferred.await(saveStarted);
700 yield* Queue.offer(events, {
701 kind: "snapshot",
702 snapshot: lateSnapshot,
703 });
704 for (let index = 0; index < 50; index += 1) {
705 yield* Effect.yieldNow;
706 }
707 yield* Deferred.succeed(releaseSave, undefined);
708 yield* Fiber.join(closeFiber);
709
710 const values = yield* Ref.get(saved);
711 expect(values.length).toBeGreaterThan(0);
712 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
713 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
714 true,
715 );
716 }),
717 );
718
719 it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
720 Effect.gen(function* () {
721 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
722 ...v2ShellSnapshot,
723 snapshotSequence: 20,
724 projects: [{ ...v2Project, title: "Client ahead" }],
725 };
726 const httpSnapshot: OrchestrationV2ShellSnapshot = {
727 ...v2ShellSnapshot,
728 snapshotSequence: 4,
729 projects: [{ ...v2Project, title: "Server reset" }],
730 };
731 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
732 const client = {
733 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
734 } as unknown as WsRpcProtocolClient;
735 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
736 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
737 target: TARGET,
738 state: supervisorState,
739 session: yield* SubscriptionRef.make(Option.some(session(client))),
740 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
741 connect: Effect.void,
742 disconnect: Effect.void,
743 retryNow: Effect.void,
744 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
745 const cache = Persistence.EnvironmentCacheStore.of({
746 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
747 saveShell: () => Effect.void,
748 loadThread: () => Effect.succeed(Option.none()),
749 saveThread: () => Effect.void,
750 removeThread: () => Effect.void,
751 loadServerConfig: () => Effect.succeed(Option.none()),
752 saveServerConfig: () => Effect.void,
753 loadVcsRefs: () => Effect.succeed(Option.none()),
754 saveVcsRefs: () => Effect.void,
755 removeVcsRefs: () => Effect.void,
756 clearVcsRefs: () => Effect.void,
757 clear: () => Effect.void,
758 });
759 const snapshotLoader = ShellSnapshotLoader.of({
760 load: () => Effect.succeed(Option.some(httpSnapshot)),
761 });
762 const shellState = yield* makeEnvironmentShellState().pipe(
763 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
764 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
765 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
766 );
767
768 yield* SubscriptionRef.changes(shellState).pipe(
769 Stream.filter(
770 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
771 ),
772 Stream.runHead,
773 );
774
775 const state = yield* SubscriptionRef.get(shellState);
776 expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
777 expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
778 }),
779 );
780});