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