Open History to see the last commit
1import {
2 EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "@effect/vitest";
9import * as Cause from "effect/Cause";
10import * as Duration from "effect/Duration";
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 Stream from "effect/Stream";
18import * as SubscriptionRef from "effect/SubscriptionRef";
19import * as TestClock from "effect/testing/TestClock";
20import { RpcClientError } from "effect/unstable/rpc";
21import * as Socket from "effect/unstable/socket/Socket";
22
23import {
24 AVAILABLE_CONNECTION_STATE,
25 PrimaryConnectionTarget,
26 type PreparedConnection,
27} from "../connection/model.ts";
28import * as EnvironmentSupervisor from "../connection/supervisor.ts";
29import * as Persistence from "../platform/persistence.ts";
30import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
31import type { RpcSession } from "../rpc/session.ts";
32import {
33 makeEnvironmentServerConfigState,
34 isLegacyUpdateHandoffLoss,
35 matchesServerUpdateReadyEvent,
36 nudgeReconnectDuringUpdateRestart,
37 projectServerWelcome,
38 resolveServerConfigValue,
39 resolveServerUpdateProgressResult,
40 serverUpdateStateForProgressEvent,
41 serverUpdateStateForServerVersion,
42 validateServerUpdateReadyEvent,
43} from "./server.ts";
44import { applyServerConfigProjection } from "./serverConfigProjection.ts";
45
46const CONFIG = {
47 availableEditors: [],
48 issues: [],
49 keybindings: {},
50 keybindingsConfigPath: null,
51 observability: null,
52 providers: [],
53 settings: {},
54 // Capabilities drive version-skew behaviour in the projection, so the
55 // fixture carries them rather than leaving the field absent.
56 environment: { capabilities: { environmentThemes: true } },
57} as unknown as ServerConfig;
58
59const snapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
60 version: 1,
61 type: "snapshot",
62 config,
63});
64
65const TARGET = new PrimaryConnectionTarget({
66 environmentId: EnvironmentId.make("environment-1"),
67 label: "Test environment",
68 httpBaseUrl: "https://environment.example.test",
69 wsBaseUrl: "wss://environment.example.test",
70});
71
72function session(client: WsRpcProtocolClient): RpcSession {
73 return {
74 client,
75 initialConfig: Effect.succeed(CONFIG),
76 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
77 ready: Effect.void,
78 probe: Effect.void,
79 closed: Effect.never,
80 };
81}
82
83describe("update restart reconnect nudges", () => {
84 it.effect("retries once per backoff entry instead of only the first", () =>
85 Effect.gen(function* () {
86 const retries = yield* Ref.make(0);
87 const states = [
88 { phase: "backoff" },
89 { phase: "connecting" },
90 { phase: "backoff" },
91 { phase: "backoff" },
92 ];
93
94 yield* nudgeReconnectDuringUpdateRestart({
95 stateChanges: Stream.fromIterable(states),
96 retryNow: Ref.update(retries, (count) => count + 1),
97 interval: Duration.zero,
98 });
99
100 // Three backoff entries, three nudges. The old one-shot behavior fired
101 // once and then let the supervisor's ladder stretch to 16-second gaps.
102 expect(yield* Ref.get(retries)).toBe(3);
103 }),
104 );
105
106 it.effect("paces nudges so a fast-failing connection cannot spin", () =>
107 Effect.gen(function* () {
108 const retries = yield* Ref.make(0);
109
110 const fiber = yield* Effect.forkChild(
111 nudgeReconnectDuringUpdateRestart({
112 stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
113 retryNow: Ref.update(retries, (count) => count + 1),
114 }),
115 { startImmediately: true },
116 );
117
118 // Each nudge waits out the interval first, so nothing fires immediately.
119 yield* TestClock.adjust(Duration.millis(999));
120 expect(yield* Ref.get(retries)).toBe(0);
121
122 yield* TestClock.adjust(Duration.millis(1));
123 expect(yield* Ref.get(retries)).toBe(1);
124
125 yield* TestClock.adjust(Duration.seconds(1));
126 expect(yield* Ref.get(retries)).toBe(2);
127
128 yield* Fiber.join(fiber);
129 }).pipe(Effect.provide(TestClock.layer())),
130 );
131
132 it.effect("retries rejected credentials only while the update restart is in progress", () =>
133 Effect.gen(function* () {
134 const retries = yield* Ref.make(0);
135
136 yield* nudgeReconnectDuringUpdateRestart({
137 stateChanges: Stream.fromIterable([
138 { phase: "blocked", lastFailure: { reason: "permission" } },
139 {
140 phase: "blocked",
141 lastFailure: {
142 reason: "authentication",
143 detail: "The environment credential is invalid.",
144 },
145 },
146 { phase: "blocked", lastFailure: { reason: "configuration" } },
147 ]),
148 retryNow: Ref.update(retries, (count) => count + 1),
149 interval: Duration.zero,
150 });
151
152 expect(yield* Ref.get(retries)).toBe(1);
153 }),
154 );
155});
156
157describe("server state projection", () => {
158 it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
159 expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
160 expect(
161 isLegacyUpdateHandoffLoss(
162 Cause.fail(
163 new RpcClientError.RpcClientError({
164 reason: new Socket.SocketCloseError({ code: 1006 }),
165 }),
166 ),
167 ),
168 ).toBe(true);
169 expect(
170 isLegacyUpdateHandoffLoss(
171 Cause.fail(
172 new RpcClientError.RpcClientError({
173 reason: new Socket.SocketOpenError({
174 kind: "Unknown",
175 cause: new Error("connection refused"),
176 }),
177 }),
178 ),
179 ),
180 ).toBe(false);
181 expect(
182 isLegacyUpdateHandoffLoss(
183 Cause.fail(
184 new RpcClientError.RpcClientError({
185 reason: new RpcClientError.RpcClientDefect({
186 message: "incompatible protocol",
187 cause: new Error("invalid response"),
188 }),
189 }),
190 ),
191 ),
192 ).toBe(false);
193 expect(isLegacyUpdateHandoffLoss(Cause.fail(new Error("Install failed.")))).toBe(false);
194 });
195
196 it.effect("resumes after the progress stream disconnects following completion", () => {
197 const result = {
198 targetVersion: "0.0.31",
199 method: "respawn" as const,
200 };
201 const disconnect = new RpcClientError.RpcClientError({
202 reason: new Socket.SocketCloseError({ code: 1006 }),
203 });
204
205 return Effect.gen(function* () {
206 const resumed = yield* resolveServerUpdateProgressResult(
207 result.targetVersion,
208 Option.some(result),
209 Exit.fail(disconnect),
210 );
211 expect(resumed).toEqual(result);
212 });
213 });
214
215 it("projects streamed update milestones into the shared operation state", () => {
216 expect(
217 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
218 type: "progress",
219 stage: "installing",
220 }),
221 ).toEqual({
222 status: "running",
223 stage: "installing",
224 fromVersion: "0.0.30",
225 targetVersion: "0.0.31",
226 });
227 expect(
228 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
229 type: "complete",
230 result: { targetVersion: "0.0.31", method: "respawn" },
231 }),
232 ).toEqual({
233 status: "running",
234 stage: "resuming",
235 fromVersion: "0.0.30",
236 targetVersion: "0.0.31",
237 });
238 });
239
240 it("keeps active update state and hides stale failures after a version change", () => {
241 const running = {
242 status: "running" as const,
243 stage: "resuming" as const,
244 fromVersion: "0.0.30",
245 targetVersion: "0.0.31",
246 };
247 const failed = {
248 status: "failed" as const,
249 stage: "installing" as const,
250 fromVersion: "0.0.30",
251 targetVersion: "0.0.31",
252 message: "Install failed.",
253 };
254
255 expect(serverUpdateStateForServerVersion(running, "0.0.31")).toBe(running);
256 expect(serverUpdateStateForServerVersion(failed, "0.0.30")).toBe(failed);
257 expect(serverUpdateStateForServerVersion(failed, null)).toBe(failed);
258 expect(serverUpdateStateForServerVersion(failed, "0.0.31")).toEqual({ status: "idle" });
259 });
260
261 it.effect("correlates launcher outcomes and fails immediately after rollback", () =>
262 Effect.gen(function* () {
263 const result = {
264 targetVersion: "0.0.31",
265 method: "boot-service" as const,
266 updateId: "update-1",
267 };
268 const ready = (status: "committed" | "rolled-back") =>
269 ({
270 version: 1 as const,
271 sequence: 1,
272 type: "ready" as const,
273 payload: {
274 at: "2026-08-01T00:00:00.000Z",
275 environment: { serverVersion: status === "committed" ? "0.0.31" : "0.0.30" },
276 updateOutcome: {
277 id: "update-1",
278 fromVersion: "0.0.30",
279 targetVersion: "0.0.31",
280 status,
281 ...(status === "rolled-back" ? { reason: "prepared-timeout" } : {}),
282 },
283 },
284 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
285
286 expect(matchesServerUpdateReadyEvent(result, ready("committed"))).toBe(true);
287 yield* validateServerUpdateReadyEvent(result, ready("committed"));
288 const rollback = yield* Effect.flip(
289 validateServerUpdateReadyEvent(result, ready("rolled-back")),
290 );
291 expect(rollback.message).toBe("prepared-timeout");
292 }),
293 );
294
295 it("applies every config category to the projected snapshot", () => {
296 const snapshot = applyServerConfigProjection(Option.none(), {
297 version: 1,
298 type: "snapshot",
299 config: CONFIG,
300 });
301 const settings = { ...CONFIG.settings };
302 const projected = applyServerConfigProjection(snapshot, {
303 version: 1,
304 type: "settingsUpdated",
305 payload: { settings },
306 });
307
308 const result = Option.getOrThrow(projected);
309 expect(result.config.settings).toBe(settings);
310 expect(result.latestEvent.type).toBe("settingsUpdated");
311 });
312
313 it("carries published environment themes in and out of the projected snapshot", () => {
314 const snapshot = applyServerConfigProjection(Option.none(), {
315 version: 1,
316 type: "snapshot",
317 config: CONFIG,
318 });
319 const themes = [
320 {
321 id: "nightfall",
322 name: "Nightfall",
323 appearance: "dark",
324 canvas: "#1a1b26",
325 accent: "#7aa2f7",
326 },
327 ] as const;
328
329 const published = applyServerConfigProjection(snapshot, {
330 version: 1,
331 type: "environmentThemesUpdated",
332 payload: { themes },
333 });
334 expect(Option.getOrThrow(published).config.environmentThemes).toEqual(themes);
335
336 // A machine that stops publishing has to clear the palettes, not freeze
337 // clients on the last set it sent.
338 const unpublished = applyServerConfigProjection(published, {
339 version: 1,
340 type: "environmentThemesUpdated",
341 payload: { themes: [] },
342 });
343 expect(Option.getOrThrow(unpublished).config.environmentThemes).toBeUndefined();
344 });
345
346 // A snapshot never carries published themes, so taking it wholesale would
347 // clear them on every reconnect and repaint anyone wearing one.
348 it("keeps published themes across a reconnect snapshot", () => {
349 const themes = [
350 {
351 id: "nightfall",
352 name: "Nightfall",
353 appearance: "dark",
354 canvas: "#1a1b26",
355 accent: "#7aa2f7",
356 },
357 ] as const;
358
359 const withThemes = applyServerConfigProjection(
360 applyServerConfigProjection(Option.none(), { version: 1, type: "snapshot", config: CONFIG }),
361 { version: 1, type: "environmentThemesUpdated", payload: { themes } },
362 );
363 expect(Option.getOrThrow(withThemes).config.environmentThemes).toEqual(themes);
364
365 const afterReconnect = applyServerConfigProjection(withThemes, {
366 version: 1,
367 type: "snapshot",
368 config: CONFIG,
369 });
370 expect(Option.getOrThrow(afterReconnect).config.environmentThemes).toEqual(themes);
371
372 // A server that predates the feature never sends another theme event, so
373 // carrying the set forward would leave a palette nothing can update.
374 const downgraded = applyServerConfigProjection(withThemes, {
375 version: 1,
376 type: "snapshot",
377 config: {
378 ...CONFIG,
379 environment: { capabilities: {} },
380 } as unknown as ServerConfig,
381 });
382 expect(Option.getOrThrow(downgraded).config.environmentThemes).toBeUndefined();
383 });
384
385 it("retains welcome when a ready event follows in the same stream chunk", () => {
386 const welcome = {
387 environment: {} as ServerLifecycleWelcomePayload["environment"],
388 cwd: "/repo",
389 projectName: "repo",
390 } as ServerLifecycleWelcomePayload;
391 const [afterWelcome] = projectServerWelcome(Option.none(), {
392 type: "welcome",
393 payload: welcome,
394 });
395 const [afterReady, emitted] = projectServerWelcome(afterWelcome, {
396 type: "ready",
397 payload: {},
398 });
399
400 expect(Option.getOrThrow(afterReady)).toBe(welcome);
401 expect(emitted).toEqual([]);
402 });
403
404 it("prefers an active session config over cache until a live event arrives", () => {
405 const config = (source: string, serverVersion: string) =>
406 ({
407 ...CONFIG,
408 environment: { serverVersion },
409 settings: { source },
410 }) as unknown as ServerConfig;
411 const cached = config("cache", "0.0.29");
412 const staleLive = config("stale-live", "0.0.29");
413 const initial = config("session", "0.0.30");
414 const live = config("live", "0.0.30");
415
416 expect(
417 resolveServerConfigValue(
418 {
419 config: cached,
420 latestEvent: snapshotEvent(cached),
421 source: "cache",
422 },
423 initial,
424 ),
425 ).toBe(initial);
426 expect(
427 resolveServerConfigValue(
428 {
429 config: staleLive,
430 latestEvent: snapshotEvent(staleLive),
431 source: "live",
432 },
433 initial,
434 ),
435 ).toBe(initial);
436 expect(
437 resolveServerConfigValue(
438 {
439 config: live,
440 latestEvent: snapshotEvent(live),
441 source: "live",
442 },
443 initial,
444 ),
445 ).toBe(live);
446 });
447
448 it.effect("starts from cached configuration and persists the live projection", () =>
449 Effect.gen(function* () {
450 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
451 const client = {
452 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
453 } as unknown as WsRpcProtocolClient;
454 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
455 target: TARGET,
456 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
457 session: yield* SubscriptionRef.make(Option.some(session(client))),
458 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
459 connect: Effect.void,
460 disconnect: Effect.void,
461 retryNow: Effect.void,
462 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
463 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
464 const cache = Persistence.EnvironmentCacheStore.of({
465 loadShell: () => Effect.succeed(Option.none()),
466 saveShell: () => Effect.void,
467 loadThread: () => Effect.succeed(Option.none()),
468 saveThread: () => Effect.void,
469 removeThread: () => Effect.void,
470 loadServerConfig: () => Effect.succeed(Option.some(CONFIG)),
471 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
472 loadVcsRefs: () => Effect.succeed(Option.none()),
473 saveVcsRefs: () => Effect.void,
474 removeVcsRefs: () => Effect.void,
475 clearVcsRefs: () => Effect.void,
476 clear: () => Effect.void,
477 });
478
479 yield* Effect.scoped(
480 Effect.gen(function* () {
481 const state = yield* makeEnvironmentServerConfigState().pipe(
482 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
483 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
484 );
485 expect(Option.getOrThrow(yield* SubscriptionRef.get(state)).config).toBe(CONFIG);
486
487 const providers: ServerConfig["providers"] = [];
488 yield* Queue.offer(events, {
489 version: 1,
490 type: "providerStatuses",
491 payload: { providers },
492 });
493 const projected = yield* SubscriptionRef.changes(state).pipe(
494 Stream.filter((value) =>
495 Option.match(value, {
496 onNone: () => false,
497 onSome: (projection) => projection.latestEvent.type === "providerStatuses",
498 }),
499 ),
500 Stream.runHead,
501 );
502 expect(Option.getOrThrow(Option.getOrThrow(projected)).config.providers).toBe(providers);
503 }),
504 );
505
506 expect((yield* Queue.take(savedConfigs)).providers).toEqual([]);
507 }),
508 );
509
510 it.effect("does not rewrite cached configuration when no live update arrives", () =>
511 Effect.gen(function* () {
512 const client = {
513 [WS_METHODS.subscribeServerConfig]: () => Stream.empty,
514 } as unknown as WsRpcProtocolClient;
515 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
516 target: TARGET,
517 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
518 session: yield* SubscriptionRef.make(Option.some(session(client))),
519 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
520 connect: Effect.void,
521 disconnect: Effect.void,
522 retryNow: Effect.void,
523 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
524 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
525 const cache = Persistence.EnvironmentCacheStore.of({
526 loadShell: () => Effect.succeed(Option.none()),
527 saveShell: () => Effect.void,
528 loadThread: () => Effect.succeed(Option.none()),
529 saveThread: () => Effect.void,
530 removeThread: () => Effect.void,
531 loadServerConfig: () => Effect.succeed(Option.some(CONFIG)),
532 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
533 loadVcsRefs: () => Effect.succeed(Option.none()),
534 saveVcsRefs: () => Effect.void,
535 removeVcsRefs: () => Effect.void,
536 clearVcsRefs: () => Effect.void,
537 clear: () => Effect.void,
538 });
539
540 yield* Effect.scoped(
541 makeEnvironmentServerConfigState().pipe(
542 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
543 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
544 ),
545 );
546
547 expect(yield* Queue.poll(savedConfigs)).toEqual(Option.none());
548 }),
549 );
550});