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