Open History to see the last commit
1import {
2 EnvironmentId,
3 ORCHESTRATION_WS_METHODS,
4 type OrchestrationShellSnapshot,
5 type OrchestrationShellStreamItem,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Stream from "effect/Stream";
12import * as SubscriptionRef from "effect/SubscriptionRef";
13
14import {
15 AVAILABLE_CONNECTION_STATE,
16 PrimaryConnectionTarget,
17 type PreparedConnection,
18} from "../connection/model.ts";
19import * as EnvironmentSupervisor from "../connection/supervisor.ts";
20import * as Persistence from "../platform/persistence.ts";
21import * as RpcSession from "../rpc/session.ts";
22import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
23import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
24
25const TARGET = new PrimaryConnectionTarget({
26 environmentId: EnvironmentId.make("environment-1"),
27 label: "Test environment",
28 httpBaseUrl: "https://environment.example.test",
29 wsBaseUrl: "wss://environment.example.test",
30});
31
32const PREPARED: PreparedConnection = {
33 environmentId: TARGET.environmentId,
34 label: TARGET.label,
35 httpBaseUrl: TARGET.httpBaseUrl,
36 socketUrl: TARGET.wsBaseUrl,
37 httpAuthorization: null,
38 target: TARGET,
39};
40
41const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
42 snapshotSequence: 1,
43 projects: [],
44 threads: [],
45 updatedAt: "2026-06-06T00:00:00.000Z",
46};
47
48function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
49 return {
50 client,
51 initialConfig: Effect.never,
52 ready: Effect.void,
53 probe: Effect.void,
54 closed: Effect.never,
55 };
56}
57
58describe("environment shell synchronization", () => {
59 it.effect("publishes live state before persistence and preserves it when ready", () =>
60 Effect.gen(function* () {
61 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
62 const client = {
63 [ORCHESTRATION_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
64 } as unknown as WsRpcProtocolClient;
65 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
66 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
67 Option.some(session(client)),
68 );
69 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
70 target: TARGET,
71 state: supervisorState,
72 session: activeSession,
73 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
74 connect: Effect.void,
75 disconnect: Effect.void,
76 retryNow: Effect.void,
77 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
78 const cache = Persistence.EnvironmentCacheStore.of({
79 loadShell: () => Effect.succeed(Option.none()),
80 saveShell: () => Effect.never,
81 loadThread: () => Effect.succeed(Option.none()),
82 saveThread: () => Effect.void,
83 removeThread: () => Effect.void,
84 clear: () => Effect.void,
85 });
86 // Cold cache with no HTTP snapshot available → falls back to the
87 // socket-embedded snapshot.
88 const snapshotLoader = ShellSnapshotLoader.of({
89 load: () => Effect.succeed(Option.none()),
90 });
91 const shellState = yield* makeEnvironmentShellState().pipe(
92 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
93 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
94 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
95 );
96
97 yield* SubscriptionRef.set(supervisorState, {
98 desired: true,
99 network: "online",
100 phase: "connecting",
101 stage: "synchronizing",
102 attempt: 1,
103 generation: 0,
104 lastFailure: null,
105 retryAt: null,
106 });
107 yield* Queue.offer(events, {
108 kind: "snapshot",
109 snapshot: LIVE_SHELL_SNAPSHOT,
110 });
111 yield* SubscriptionRef.changes(shellState).pipe(
112 Stream.filter((state) => state.status === "live"),
113 Stream.runHead,
114 );
115
116 yield* SubscriptionRef.set(supervisorState, {
117 desired: true,
118 network: "online",
119 phase: "connected",
120 stage: null,
121 attempt: 1,
122 generation: 1,
123 lastFailure: null,
124 retryAt: null,
125 });
126 for (let index = 0; index < 10; index += 1) {
127 yield* Effect.yieldNow;
128 }
129
130 const state = yield* SubscriptionRef.get(shellState);
131 expect(state.status).toBe("live");
132 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
133 }),
134 );
135
136 it.effect("resumes a warm shell cache via afterSequence without an HTTP fetch", () =>
137 Effect.gen(function* () {
138 const cachedSnapshot: OrchestrationShellSnapshot = {
139 snapshotSequence: 5,
140 projects: [],
141 threads: [],
142 updatedAt: "2026-06-06T00:00:00.000Z",
143 };
144 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
145 const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
146 const loaderCalls = yield* SubscriptionRef.make(0);
147 const client = {
148 [ORCHESTRATION_WS_METHODS.subscribeShell]: (input: { readonly afterSequence?: number }) =>
149 Stream.unwrap(
150 SubscriptionRef.set(capturedAfterSequence, input.afterSequence).pipe(
151 Effect.as(Stream.fromQueue(events)),
152 ),
153 ),
154 } as unknown as WsRpcProtocolClient;
155 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
156 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
157 Option.some(session(client)),
158 );
159 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
160 target: TARGET,
161 state: supervisorState,
162 session: activeSession,
163 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
164 connect: Effect.void,
165 disconnect: Effect.void,
166 retryNow: Effect.void,
167 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
168 const cache = Persistence.EnvironmentCacheStore.of({
169 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
170 saveShell: () => Effect.void,
171 loadThread: () => Effect.succeed(Option.none()),
172 saveThread: () => Effect.void,
173 removeThread: () => Effect.void,
174 clear: () => Effect.void,
175 });
176 const snapshotLoader = ShellSnapshotLoader.of({
177 load: () =>
178 SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(Effect.as(Option.none())),
179 });
180 yield* makeEnvironmentShellState().pipe(
181 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
182 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
183 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
184 );
185
186 // Wait until the subscription is established from the warm cache.
187 yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
188 Stream.filter((value) => value !== undefined),
189 Stream.runHead,
190 );
191
192 expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(5);
193 expect(yield* SubscriptionRef.get(loaderCalls)).toBe(0);
194 }),
195 );
196});