Open History to see the last commit
1import {
2 EnvironmentId,
3 ServerObservability,
4 EnvironmentThemeId,
5 UsageLimitSourceId,
6 type ServerConfig,
7 type ServerConfigStreamEvent,
8 type ServerLifecycleWelcomePayload,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as Cause from "effect/Cause";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import * as SubscriptionRef from "effect/SubscriptionRef";
24import * as TestClock from "effect/testing/TestClock";
25import { RpcClientError } from "effect/rpc";
26import * as Socket from "effect/socket/Socket";
27
28import {
29 AVAILABLE_CONNECTION_STATE,
30 PrimaryConnectionTarget,
31 type PreparedConnection,
32} from "../connection/model.ts";
33import * as EnvironmentSupervisor from "../connection/supervisor.ts";
34import * as Persistence from "../platform/persistence.ts";
35import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
36import type { RpcSession } from "../rpc/session.ts";
37import {
38 applyServerWelcomeEvent,
39 makeEnvironmentServerWelcomeState,
40 makeEnvironmentServerConfigState,
41 isLegacyUpdateHandoffLoss,
42 matchesServerUpdateReadyEvent,
43 matchesServerUpdateResumeEvent,
44 nudgeReconnectDuringUpdateRestart,
45 resolveServerConfigValue,
46 resolveServerWelcomeState,
47 resolveServerUpdateProgressResult,
48 serverUpdateStateForProgressEvent,
49 serverUpdateStateForServerVersion,
50 validateServerUpdateReadyEvent,
51 waitForNextEnvironmentReconnect,
52 waitForDesktopUpdateTarget,
53 runDesktopCommitWithReconnectObserver,
54} from "./server.ts";
55import { applyServerConfigProjection } from "./serverConfigProjection.ts";
56
57const CONFIG = {
58 availableEditors: [],
59 issues: [],
60 keybindings: {},
61 keybindingsConfigPath: null,
62 observability: null,
63 providers: [],
64 settings: {},
65 environment: { capabilities: { environmentThemes: true } },
66} as unknown as ServerConfig;
67
68const snapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
69 version: 1,
70 type: "snapshot",
71 config,
72});
73
74const TARGET = new PrimaryConnectionTarget({
75 environmentId: EnvironmentId.make("environment-1"),
76 label: "Test environment",
77 httpBaseUrl: "https://environment.example.test",
78 wsBaseUrl: "wss://environment.example.test",
79});
80
81function session(client: WsRpcProtocolClient): RpcSession {
82 return {
83 client,
84 initialConfig: Effect.succeed(CONFIG),
85 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
86 ready: Effect.void,
87 probe: Effect.void,
88 closed: Effect.never,
89 };
90}
91
92describe("update restart reconnect nudges", () => {
93 it.effect("retries a desktop commit that was lost before delivery", () =>
94 Effect.gen(function* () {
95 const readyEvents =
96 yield* Queue.unbounded<Parameters<typeof matchesServerUpdateReadyEvent>[1]>();
97 const ready = (serverVersion: string) =>
98 ({
99 version: 1 as const,
100 sequence: 1,
101 type: "ready" as const,
102 payload: {
103 at: "2026-09-01T00:00:00.000Z",
104 environment: { serverVersion },
105 },
106 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
107 yield* Queue.offerAll(readyEvents, [ready("0.0.30"), ready("0.0.31")]);
108 const retries = yield* Ref.make(0);
109 const disconnect = new RpcClientError.RpcClientError({
110 reason: new Socket.SocketCloseError({ code: 1006 }),
111 });
112
113 const result = yield* waitForDesktopUpdateTarget(
114 "0.0.31",
115 Queue.take(readyEvents),
116 Ref.update(retries, (count) => count + 1).pipe(Effect.andThen(Effect.fail(disconnect))),
117 );
118
119 expect(result.payload.environment.serverVersion).toBe("0.0.31");
120 expect(yield* Ref.get(retries)).toBe(1);
121 }),
122 );
123 it.effect("observes a fast reconnect even when the caller awaits it later", () =>
124 Effect.gen(function* () {
125 const states = yield* Queue.unbounded<{ readonly phase: string }>();
126 const reconnected = yield* waitForNextEnvironmentReconnect(Stream.fromQueue(states)).pipe(
127 Effect.forkChild,
128 );
129 yield* Queue.offerAll(states, [
130 { phase: "connected" },
131 { phase: "backoff" },
132 { phase: "connected" },
133 ]);
134
135 yield* Fiber.join(reconnected);
136 }),
137 );
138 it.effect("arms the retry observer before a commit can disconnect", () =>
139 Effect.gen(function* () {
140 const allowSubscription = yield* Deferred.make<void>();
141 const subscriptionStarted = yield* Deferred.make<void>();
142 const states = yield* Queue.unbounded<{ readonly phase: string }>();
143 const commits = yield* Ref.make(0);
144 const disconnect = new RpcClientError.RpcClientError({
145 reason: new Socket.SocketCloseError({ code: 1006 }),
146 });
147 const stateChanges = Stream.unwrap(
148 Deferred.succeed(subscriptionStarted, undefined).pipe(
149 Effect.andThen(Deferred.await(allowSubscription)),
150 Effect.as(Stream.fromQueue(states)),
151 ),
152 );
153 const retry = yield* runDesktopCommitWithReconnectObserver(
154 stateChanges,
155 Ref.update(commits, (count) => count + 1).pipe(
156 Effect.andThen(Queue.offerAll(states, [{ phase: "backoff" }, { phase: "connected" }])),
157 Effect.andThen(Effect.fail(disconnect)),
158 ),
159 ).pipe(Effect.flip, Effect.forkChild);
160
161 yield* Deferred.await(subscriptionStarted);
162 expect(yield* Ref.get(commits)).toBe(0);
163 yield* Deferred.succeed(allowSubscription, undefined);
164 yield* Queue.offer(states, { phase: "connected" });
165
166 expect(yield* Fiber.join(retry)).toBe(disconnect);
167 expect(yield* Ref.get(commits)).toBe(1);
168 }),
169 );
170 it.effect("retries once per backoff entry instead of only the first", () =>
171 Effect.gen(function* () {
172 const retries = yield* Ref.make(0);
173 const states = [
174 { phase: "backoff" },
175 { phase: "connecting" },
176 { phase: "backoff" },
177 { phase: "backoff" },
178 ];
179
180 yield* nudgeReconnectDuringUpdateRestart({
181 stateChanges: Stream.fromIterable(states),
182 retryNow: Ref.update(retries, (count) => count + 1),
183 interval: Duration.zero,
184 });
185
186 expect(yield* Ref.get(retries)).toBe(3);
187 }),
188 );
189
190 it.effect("retries rejected credentials only while the update restart is in progress", () =>
191 Effect.gen(function* () {
192 const retries = yield* Ref.make(0);
193
194 yield* nudgeReconnectDuringUpdateRestart({
195 stateChanges: Stream.fromIterable([
196 { phase: "blocked", lastFailure: { reason: "permission" } },
197 {
198 phase: "blocked",
199 lastFailure: {
200 reason: "authentication",
201 detail: "The environment credential is invalid.",
202 },
203 },
204 { phase: "blocked", lastFailure: { reason: "configuration" } },
205 ]),
206 retryNow: Ref.update(retries, (count) => count + 1),
207 interval: Duration.zero,
208 });
209
210 expect(yield* Ref.get(retries)).toBe(1);
211 }),
212 );
213});
214
215const makeConfigPersistenceHarness = Effect.fn("test.makeConfigPersistenceHarness")(function* (
216 saveServerConfig: Persistence.EnvironmentCacheStore["Service"]["saveServerConfig"],
217) {
218 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
219 const client = {
220 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
221 } as unknown as WsRpcProtocolClient;
222 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
223 target: TARGET,
224 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
225 session: yield* SubscriptionRef.make(Option.some(session(client))),
226 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
227 connect: Effect.void,
228 disconnect: Effect.void,
229 retryNow: Effect.void,
230 });
231 const cache = Persistence.EnvironmentCacheStore.of({
232 loadShell: () => Effect.succeedNone,
233 saveShell: () => Effect.void,
234 loadThread: () => Effect.succeedNone,
235 saveThread: () => Effect.void,
236 removeThread: () => Effect.void,
237 loadServerConfig: () => Effect.succeedSome(CONFIG),
238 saveServerConfig,
239 loadVcsRefs: () => Effect.succeedNone,
240 saveVcsRefs: () => Effect.void,
241 removeVcsRefs: () => Effect.void,
242 clearVcsRefs: () => Effect.void,
243 clear: () => Effect.void,
244 });
245 const state = yield* makeEnvironmentServerConfigState({
246 environmentThemes: true,
247 usageLimitSources: true,
248 }).pipe(
249 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
250 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
251 );
252 const send = Effect.fn("test.sendConfigEvent")(function* (event: ServerConfigStreamEvent) {
253 yield* Queue.offer(events, event);
254 return yield* SubscriptionRef.changes(state).pipe(
255 Stream.filter(Option.isSome),
256 Stream.map((value) => value.value),
257 Stream.filter((projection) => projection.latestEvent === event),
258 Stream.runHead,
259 Effect.map(Option.getOrThrow),
260 );
261 });
262 return { send };
263});
264
265describe("server state projection", () => {
266 it.effect("skips duplicate keybinding saves but persists changed keybindings", () =>
267 Effect.gen(function* () {
268 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
269 const keybindingsEvent = (key: string): ServerConfigStreamEvent => ({
270 version: 1,
271 type: "keybindingsUpdated",
272 payload: {
273 keybindings: [
274 {
275 command: "terminal.toggle",
276 shortcut: {
277 key,
278 metaKey: false,
279 ctrlKey: false,
280 shiftKey: false,
281 altKey: false,
282 modKey: true,
283 },
284 },
285 ],
286 issues: [],
287 },
288 });
289 yield* Effect.scoped(
290 Effect.gen(function* () {
291 const h = yield* makeConfigPersistenceHarness((_id, config) =>
292 Ref.update(saved, (values) => [...values, config]),
293 );
294 const first = yield* h.send(keybindingsEvent("p"));
295 yield* TestClock.adjust("500 millis");
296 expect(yield* Ref.get(saved)).toEqual([first.config]);
297
298 yield* h.send(keybindingsEvent("p"));
299 yield* TestClock.adjust("10 seconds");
300 expect(yield* Ref.get(saved)).toEqual([first.config]);
301
302 const changed = yield* h.send(keybindingsEvent("q"));
303 yield* TestClock.adjust("10 seconds");
304 expect(yield* Ref.get(saved)).toEqual([first.config, changed.config]);
305 }),
306 );
307 }),
308 );
309
310 it.effect(
311 "compares nested durable values independently of key order and omitted undefined fields",
312 () =>
313 Effect.gen(function* () {
314 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
315 const observability = {
316 logsDirectoryPath: "/synthetic/logs",
317 localTracingEnabled: false,
318 otlpTracesEnabled: false,
319 otlpMetricsEnabled: false,
320 otlpLogsEnabled: false,
321 };
322 yield* Effect.scoped(
323 Effect.gen(function* () {
324 const h = yield* makeConfigPersistenceHarness((_id, config) =>
325 Ref.update(saved, (values) => [...values, config]),
326 );
327 const first = yield* h.send(snapshotEvent({ ...CONFIG, observability }));
328 yield* TestClock.adjust("500 millis");
329 const reordered = Object.fromEntries(
330 Object.entries(observability).toReversed(),
331 ) as typeof observability;
332 for (const next of [
333 { ...CONFIG, observability: reordered },
334 { ...CONFIG, observability: { ...reordered, otlpTracesUrl: undefined } },
335 { ...CONFIG, observability: { ...observability } },
336 ]) {
337 const encode = Schema.encodeEffect(Schema.fromJsonString(ServerObservability));
338 expect(JSON.parse(yield* encode(next.observability))).toEqual(
339 JSON.parse(yield* encode(observability)),
340 );
341 const projection = yield* h.send(snapshotEvent(next));
342 expect(projection.config.observability).toEqual(next.observability);
343 yield* TestClock.adjust("10 seconds");
344 expect.soft(yield* Ref.get(saved)).toEqual([first.config]);
345 }
346 const writesBeforeChange = (yield* Ref.get(saved)).length;
347 const changed = yield* h.send(
348 snapshotEvent({
349 ...CONFIG,
350 observability: { ...observability, otlpTracesUrl: "https://traces.example.test" },
351 }),
352 );
353 yield* TestClock.adjust("10 seconds");
354 expect((yield* Ref.get(saved)).length).toBe(writesBeforeChange + 1);
355 expect((yield* Ref.get(saved)).at(-1)).toEqual(changed.config);
356 }),
357 );
358 }),
359 );
360
361 it.effect("saves once across transient themes, usage sources and stall updates", () =>
362 Effect.gen(function* () {
363 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
364 yield* Effect.scoped(
365 Effect.gen(function* () {
366 const h = yield* makeConfigPersistenceHarness((_id, config) =>
367 Ref.update(saved, (values) => [...values, config]),
368 );
369 yield* h.send(snapshotEvent(CONFIG));
370 yield* TestClock.adjust("500 millis");
371 expect((yield* Ref.get(saved)).length).toBe(1);
372 for (const event of [
373 {
374 version: 1,
375 type: "environmentThemesUpdated",
376 payload: {
377 themes: [
378 {
379 id: EnvironmentThemeId.make("theme-test"),
380 name: "Test theme",
381 appearance: "dark",
382 },
383 ],
384 },
385 },
386 {
387 version: 1,
388 type: "usageLimitSourcesUpdated",
389 payload: {
390 sources: [
391 {
392 id: UsageLimitSourceId.make("source-test"),
393 kind: "cliproxy",
394 label: "Test source",
395 checkedAt: "2026-10-20T07:50:37.633Z",
396 accounts: [],
397 },
398 ],
399 },
400 },
401 snapshotEvent({
402 ...CONFIG,
403 lastEventLoopStall: {
404 detectedAt: "2026-10-20T07:50:37.633Z",
405 durationMs: 1000,
406 loadAverage: 1,
407 cpuCount: 8,
408 },
409 }),
410 ] satisfies ReadonlyArray<ServerConfigStreamEvent>) {
411 const projection = yield* h.send(event);
412 expect(projection.latestEvent).toBe(event);
413 if (event.type === "environmentThemesUpdated")
414 expect(projection.config.environmentThemes).toEqual(event.payload.themes);
415 if (event.type === "usageLimitSourcesUpdated")
416 expect(projection.config.usageLimitSources).toEqual(event.payload.sources);
417 yield* TestClock.adjust("10 seconds");
418 }
419 }),
420 );
421 expect(yield* Ref.get(saved)).toEqual([CONFIG]);
422 }),
423 );
424
425 it.effect("flushes pending durable changes after a transient event", () =>
426 Effect.gen(function* () {
427 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
428 const changed = { ...CONFIG, keybindingsConfigPath: "/changed/keybindings.json" };
429 yield* Effect.scoped(
430 Effect.gen(function* () {
431 const h = yield* makeConfigPersistenceHarness((_id, config) =>
432 Ref.update(saved, (values) => [...values, config]),
433 );
434 yield* h.send(snapshotEvent(CONFIG));
435 yield* TestClock.adjust("500 millis");
436 yield* h.send(snapshotEvent(changed));
437 yield* h.send({ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } });
438 }),
439 );
440 expect(yield* Ref.get(saved)).toEqual([CONFIG, changed]);
441 }),
442 );
443
444 it.effect("retries a failed durable save on a transient event", () =>
445 Effect.gen(function* () {
446 const attempts = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
447 yield* Effect.scoped(
448 Effect.gen(function* () {
449 const h = yield* makeConfigPersistenceHarness((_id, config) =>
450 Effect.gen(function* () {
451 const values = yield* Ref.updateAndGet(attempts, (values) => [...values, config]);
452 if (values.length === 1)
453 return yield* new Persistence.ConnectionPersistenceError({
454 operation: "save-server-config",
455 message: "test failure",
456 });
457 }),
458 );
459 yield* h.send(snapshotEvent(CONFIG));
460 yield* TestClock.adjust("500 millis");
461 yield* h.send({ version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } });
462 yield* TestClock.adjust("10 seconds");
463 }),
464 );
465 expect(yield* Ref.get(attempts)).toEqual([CONFIG, CONFIG]);
466 }),
467 );
468
469 it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
470 expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
471 expect(
472 isLegacyUpdateHandoffLoss(
473 Cause.fail(
474 new RpcClientError.RpcClientError({
475 reason: new Socket.SocketCloseError({ code: 1006 }),
476 }),
477 ),
478 ),
479 ).toBe(true);
480 expect(
481 isLegacyUpdateHandoffLoss(
482 Cause.fail(
483 new RpcClientError.RpcClientError({
484 reason: new Socket.SocketOpenError({
485 kind: "Unknown",
486 cause: new Error("connection refused"),
487 }),
488 }),
489 ),
490 ),
491 ).toBe(false);
492 expect(
493 isLegacyUpdateHandoffLoss(
494 Cause.fail(
495 new RpcClientError.RpcClientError({
496 reason: new RpcClientError.RpcClientDefect({
497 message: "incompatible protocol",
498 cause: new Error("invalid response"),
499 }),
500 }),
501 ),
502 ),
503 ).toBe(false);
504 expect(isLegacyUpdateHandoffLoss(Cause.fail(new Error("Install failed.")))).toBe(false);
505 });
506
507 it.effect("resumes after the progress stream disconnects following completion", () => {
508 const result = {
509 targetVersion: "0.0.31",
510 method: "respawn" as const,
511 };
512 const disconnect = new RpcClientError.RpcClientError({
513 reason: new Socket.SocketCloseError({ code: 1006 }),
514 });
515
516 return Effect.gen(function* () {
517 const resumed = yield* resolveServerUpdateProgressResult(
518 result.targetVersion,
519 Option.some(result),
520 Exit.fail(disconnect),
521 );
522 expect(resumed).toEqual(result);
523 });
524 });
525
526 it("projects streamed update milestones into the shared operation state", () => {
527 expect(
528 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
529 type: "progress",
530 stage: "installing",
531 }),
532 ).toEqual({
533 status: "running",
534 stage: "installing",
535 fromVersion: "0.0.30",
536 targetVersion: "0.0.31",
537 });
538 expect(
539 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
540 type: "complete",
541 result: { targetVersion: "0.0.31", method: "respawn" },
542 }),
543 ).toEqual({
544 status: "running",
545 stage: "resuming",
546 fromVersion: "0.0.30",
547 targetVersion: "0.0.31",
548 });
549 expect(
550 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
551 type: "complete",
552 result: { targetVersion: "0.0.31", method: "desktop-app", desktopUpdateToken: "token" },
553 }).stage,
554 ).toBe("installing");
555 });
556
557 it("keeps active update state and hides stale failures after a version change", () => {
558 const running = {
559 status: "running" as const,
560 stage: "resuming" as const,
561 fromVersion: "0.0.30",
562 targetVersion: "0.0.31",
563 };
564 const failed = {
565 status: "failed" as const,
566 stage: "installing" as const,
567 fromVersion: "0.0.30",
568 targetVersion: "0.0.31",
569 message: "Install failed.",
570 };
571
572 expect(serverUpdateStateForServerVersion(running, "0.0.31")).toBe(running);
573 expect(serverUpdateStateForServerVersion(failed, "0.0.30")).toBe(failed);
574 expect(serverUpdateStateForServerVersion(failed, null)).toBe(failed);
575 expect(serverUpdateStateForServerVersion(failed, "0.0.31")).toEqual({ status: "idle" });
576 });
577
578 it.effect("correlates launcher outcomes and fails immediately after rollback", () =>
579 Effect.gen(function* () {
580 const result = {
581 targetVersion: "0.0.31",
582 method: "boot-service" as const,
583 updateId: "update-1",
584 };
585 const ready = (status: "committed" | "rolled-back") =>
586 ({
587 version: 1 as const,
588 sequence: 1,
589 type: "ready" as const,
590 payload: {
591 at: "2026-08-01T00:00:00.000Z",
592 environment: { serverVersion: status === "committed" ? "0.0.31" : "0.0.30" },
593 updateOutcome: {
594 id: "update-1",
595 fromVersion: "0.0.30",
596 targetVersion: "0.0.31",
597 status,
598 ...(status === "rolled-back" ? { reason: "prepared-timeout" } : {}),
599 },
600 },
601 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
602
603 expect(matchesServerUpdateReadyEvent(result, ready("committed"))).toBe(true);
604 yield* validateServerUpdateReadyEvent(result, ready("committed"));
605 const rollback = yield* Effect.flip(
606 validateServerUpdateReadyEvent(result, ready("rolled-back")),
607 );
608 expect(rollback.message).toBe("prepared-timeout");
609 }),
610 );
611
612 it("requires tokenless desktop updates to reach the target version", () => {
613 const ready = (serverVersion: string) =>
614 ({
615 version: 1 as const,
616 sequence: 1,
617 type: "ready" as const,
618 payload: {
619 at: "2026-09-01T00:00:00.000Z",
620 environment: { serverVersion },
621 },
622 }) as Parameters<typeof matchesServerUpdateResumeEvent>[1];
623
624 expect(
625 matchesServerUpdateResumeEvent(
626 { targetVersion: "0.0.31", method: "desktop-app" },
627 ready("0.0.30"),
628 ),
629 ).toBe(false);
630 expect(
631 matchesServerUpdateResumeEvent(
632 {
633 targetVersion: "0.0.31",
634 method: "desktop-app",
635 desktopUpdateToken: "update-1",
636 },
637 ready("0.0.30"),
638 ),
639 ).toBe(true);
640 });
641
642 it("keeps published themes across a reconnect snapshot", () => {
643 const themes = [
644 {
645 id: "nightfall",
646 name: "Nightfall",
647 appearance: "dark",
648 canvas: "#1a1b26",
649 accent: "#7aa2f7",
650 },
651 ] as const;
652
653 const withThemes = applyServerConfigProjection(
654 applyServerConfigProjection(Option.none(), { version: 1, type: "snapshot", config: CONFIG }),
655 { version: 1, type: "environmentThemesUpdated", payload: { themes } },
656 );
657 expect(Option.getOrThrow(withThemes).config.environmentThemes).toEqual(themes);
658
659 const afterReconnect = applyServerConfigProjection(withThemes, {
660 version: 1,
661 type: "snapshot",
662 config: CONFIG,
663 });
664 expect(Option.getOrThrow(afterReconnect).config.environmentThemes).toEqual(themes);
665
666 const downgraded = applyServerConfigProjection(withThemes, {
667 version: 1,
668 type: "snapshot",
669 config: {
670 ...CONFIG,
671 environment: { capabilities: {} },
672 } as unknown as ServerConfig,
673 });
674 expect(Option.getOrThrow(downgraded).config.environmentThemes).toBeUndefined();
675 });
676
677 it("keeps a current welcome on ready and rejects a buffered welcome from the old session", () => {
678 const firstSession = session({} as WsRpcProtocolClient);
679 const secondSession = session({} as WsRpcProtocolClient);
680 const welcome = {
681 environment: {} as ServerLifecycleWelcomePayload["environment"],
682 cwd: "/repo",
683 projectName: "repo",
684 } as ServerLifecycleWelcomePayload;
685 const initial = {
686 currentSession: firstSession,
687 welcomeSession: firstSession,
688 welcome: null,
689 };
690 const afterWelcome = applyServerWelcomeEvent(initial, firstSession, {
691 type: "welcome",
692 payload: welcome,
693 });
694 const afterReady = applyServerWelcomeEvent(afterWelcome, firstSession, {
695 type: "ready",
696 payload: {},
697 });
698 const afterSwitch = { ...afterReady, currentSession: secondSession };
699 const afterBufferedOldWelcome = applyServerWelcomeEvent(afterSwitch, firstSession, {
700 type: "welcome",
701 payload: { ...welcome, cwd: "/stale" },
702 });
703
704 expect(afterReady).toBe(afterWelcome);
705 expect(resolveServerWelcomeState(afterReady)).toBe(welcome);
706 expect(afterBufferedOldWelcome).toBe(afterSwitch);
707 expect(resolveServerWelcomeState(afterBufferedOldWelcome)).toBeNull();
708 });
709
710 it.effect("checks the authoritative session before accepting a buffered welcome", () =>
711 Effect.gen(function* () {
712 const firstEvents = yield* Queue.unbounded<{
713 readonly type: "welcome" | "ready";
714 readonly payload: unknown;
715 }>();
716 const firstSubscribed = yield* Deferred.make<void>();
717 const firstClient = {
718 [WS_METHODS.subscribeServerLifecycle]: () =>
719 Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe(
720 Stream.drain,
721 Stream.concat(Stream.fromQueue(firstEvents)),
722 ),
723 } as unknown as WsRpcProtocolClient;
724 const firstSession = session(firstClient);
725 const secondSession = session({} as WsRpcProtocolClient);
726 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
727 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
728 target: TARGET,
729 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
730 session: supervisorSession,
731 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
732 connect: Effect.void,
733 disconnect: Effect.void,
734 retryNow: Effect.void,
735 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
736 const staleWelcome = {
737 environment: {} as ServerLifecycleWelcomePayload["environment"],
738 cwd: "/stale",
739 projectName: "stale",
740 } as ServerLifecycleWelcomePayload;
741
742 yield* Effect.scoped(
743 Effect.gen(function* () {
744 const state = yield* makeEnvironmentServerWelcomeState().pipe(
745 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
746 );
747 yield* Deferred.await(firstSubscribed);
748
749 supervisorSession.value = Option.some(secondSession);
750 const handled = yield* SubscriptionRef.changes(state).pipe(
751 Stream.filter(
752 (value) => value.currentSession === secondSession || value.welcome === staleWelcome,
753 ),
754 Stream.runHead,
755 Effect.map(Option.getOrThrow),
756 Effect.forkChild,
757 );
758 yield* Queue.offer(firstEvents, { type: "welcome", payload: staleWelcome });
759
760 const next = yield* Fiber.join(handled);
761 expect(next.currentSession).toBe(secondSession);
762 expect(resolveServerWelcomeState(next)).toBeNull();
763 }),
764 );
765 }),
766 );
767
768 it.effect("reads the authoritative session after waiting for the welcome state lock", () =>
769 Effect.gen(function* () {
770 const firstSubscribed = yield* Deferred.make<void>();
771 const firstClient = {
772 [WS_METHODS.subscribeServerLifecycle]: () =>
773 Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe(Stream.drain),
774 } as unknown as WsRpcProtocolClient;
775 const secondClient = {
776 [WS_METHODS.subscribeServerLifecycle]: () => Stream.never,
777 } as unknown as WsRpcProtocolClient;
778 const firstSession = session(firstClient);
779 const secondSession = session(secondClient);
780 const thirdSession = session({} as WsRpcProtocolClient);
781 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
782 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
783 target: TARGET,
784 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
785 session: supervisorSession,
786 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
787 connect: Effect.void,
788 disconnect: Effect.void,
789 retryNow: Effect.void,
790 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
791
792 yield* Effect.scoped(
793 Effect.gen(function* () {
794 const state = yield* makeEnvironmentServerWelcomeState().pipe(
795 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
796 );
797 yield* Deferred.await(firstSubscribed);
798 const changed = yield* SubscriptionRef.changes(state).pipe(
799 Stream.filter((value) => value.currentSession !== firstSession),
800 Stream.runHead,
801 Effect.map(Option.getOrThrow),
802 Effect.forkChild,
803 );
804
805 yield* state.semaphore.withPermit(
806 Effect.gen(function* () {
807 yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession));
808 yield* Effect.yieldNow;
809 yield* Effect.yieldNow;
810 yield* Effect.yieldNow;
811 supervisorSession.value = Option.some(thirdSession);
812 }),
813 );
814
815 expect((yield* Fiber.join(changed)).currentSession).toBe(thirdSession);
816 }),
817 );
818 }),
819 );
820
821 it.effect("clears a welcome until the reconnected session sends its own", () =>
822 Effect.gen(function* () {
823 const firstEvents = yield* Queue.unbounded<{
824 readonly type: "welcome" | "ready";
825 readonly payload: unknown;
826 }>();
827 const secondEvents = yield* Queue.unbounded<{
828 readonly type: "welcome" | "ready";
829 readonly payload: unknown;
830 }>();
831 const firstClient = {
832 [WS_METHODS.subscribeServerLifecycle]: () => Stream.fromQueue(firstEvents),
833 } as unknown as WsRpcProtocolClient;
834 const secondClient = {
835 [WS_METHODS.subscribeServerLifecycle]: () => Stream.fromQueue(secondEvents),
836 } as unknown as WsRpcProtocolClient;
837 const firstSession = session(firstClient);
838 const secondSession = session(secondClient);
839 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
840 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
841 target: TARGET,
842 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
843 session: supervisorSession,
844 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
845 connect: Effect.void,
846 disconnect: Effect.void,
847 retryNow: Effect.void,
848 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
849 const firstWelcome = {
850 environment: {} as ServerLifecycleWelcomePayload["environment"],
851 cwd: "/first",
852 projectName: "first",
853 } as ServerLifecycleWelcomePayload;
854 const secondWelcome = {
855 environment: {} as ServerLifecycleWelcomePayload["environment"],
856 cwd: "/second",
857 projectName: "second",
858 } as ServerLifecycleWelcomePayload;
859
860 yield* Effect.scoped(
861 Effect.gen(function* () {
862 const state = yield* makeEnvironmentServerWelcomeState().pipe(
863 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
864 );
865 const nextResolved = (
866 predicate: (value: ServerLifecycleWelcomePayload | null) => boolean,
867 ) =>
868 SubscriptionRef.changes(state).pipe(
869 Stream.map(resolveServerWelcomeState),
870 Stream.filter(predicate),
871 Stream.runHead,
872 Effect.map(Option.getOrThrow),
873 );
874
875 const first = yield* nextResolved((value) => value === firstWelcome).pipe(
876 Effect.forkChild,
877 );
878 yield* Queue.offer(firstEvents, { type: "welcome", payload: firstWelcome });
879 expect(yield* Fiber.join(first)).toBe(firstWelcome);
880
881 const cleared = yield* nextResolved((value) => value === null).pipe(Effect.forkChild);
882 yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession));
883 expect(yield* Fiber.join(cleared)).toBeNull();
884 expect(resolveServerWelcomeState(yield* SubscriptionRef.get(state))).toBeNull();
885
886 const second = yield* nextResolved((value) => value === secondWelcome).pipe(
887 Effect.forkChild,
888 );
889 yield* Queue.offer(secondEvents, { type: "welcome", payload: secondWelcome });
890 expect(yield* Fiber.join(second)).toBe(secondWelcome);
891 }),
892 );
893 }),
894 );
895
896 it("prefers an active session config over cache until a live event arrives", () => {
897 const config = (source: string, serverVersion: string) =>
898 ({
899 ...CONFIG,
900 environment: { serverVersion },
901 settings: { source },
902 }) as unknown as ServerConfig;
903 const cached = config("cache", "0.0.29");
904 const staleLive = config("stale-live", "0.0.29");
905 const initial = config("session", "0.0.30");
906 const live = config("live", "0.0.30");
907
908 expect(
909 resolveServerConfigValue(
910 {
911 config: cached,
912 latestEvent: snapshotEvent(cached),
913 source: "cache",
914 },
915 initial,
916 ),
917 ).toBe(initial);
918 expect(
919 resolveServerConfigValue(
920 {
921 config: staleLive,
922 latestEvent: snapshotEvent(staleLive),
923 source: "live",
924 },
925 initial,
926 ),
927 ).toBe(initial);
928 expect(
929 resolveServerConfigValue(
930 {
931 config: live,
932 latestEvent: snapshotEvent(live),
933 source: "live",
934 },
935 initial,
936 ),
937 ).toBe(live);
938 });
939
940 it.effect("starts from cached configuration and persists the live projection", () =>
941 Effect.gen(function* () {
942 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
943 const client = {
944 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
945 } as unknown as WsRpcProtocolClient;
946 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
947 target: TARGET,
948 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
949 session: yield* SubscriptionRef.make(Option.some(session(client))),
950 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
951 connect: Effect.void,
952 disconnect: Effect.void,
953 retryNow: Effect.void,
954 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
955 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
956 const cache = Persistence.EnvironmentCacheStore.of({
957 loadShell: () => Effect.succeedNone,
958 saveShell: () => Effect.void,
959 loadThread: () => Effect.succeedNone,
960 saveThread: () => Effect.void,
961 removeThread: () => Effect.void,
962 loadServerConfig: () => Effect.succeedSome(CONFIG),
963 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
964 loadVcsRefs: () => Effect.succeedNone,
965 saveVcsRefs: () => Effect.void,
966 removeVcsRefs: () => Effect.void,
967 clearVcsRefs: () => Effect.void,
968 clear: () => Effect.void,
969 });
970
971 yield* Effect.scoped(
972 Effect.gen(function* () {
973 const state = yield* makeEnvironmentServerConfigState({}).pipe(
974 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
975 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
976 );
977 expect(Option.getOrThrow(yield* SubscriptionRef.get(state)).config).toBe(CONFIG);
978
979 const providers: ServerConfig["providers"] = [];
980 yield* Queue.offer(events, {
981 version: 1,
982 type: "providerStatuses",
983 payload: { providers },
984 });
985 const projected = yield* SubscriptionRef.changes(state).pipe(
986 Stream.filter((value) =>
987 Option.match(value, {
988 onNone: () => false,
989 onSome: (projection) => projection.latestEvent.type === "providerStatuses",
990 }),
991 ),
992 Stream.runHead,
993 );
994 expect(Option.getOrThrow(Option.getOrThrow(projected)).config.providers).toEqual(
995 providers,
996 );
997 }),
998 );
999
1000 expect((yield* Queue.take(savedConfigs)).providers).toEqual([]);
1001 }),
1002 );
1003
1004 it.effect("shows a reported stall but never caches it", () =>
1005 Effect.gen(function* () {
1006 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
1007 const client = {
1008 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
1009 } as unknown as WsRpcProtocolClient;
1010 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1011 target: TARGET,
1012 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1013 session: yield* SubscriptionRef.make(Option.some(session(client))),
1014 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1015 connect: Effect.void,
1016 disconnect: Effect.void,
1017 retryNow: Effect.void,
1018 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1019 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
1020 const cache = Persistence.EnvironmentCacheStore.of({
1021 loadShell: () => Effect.succeedNone,
1022 saveShell: () => Effect.void,
1023 loadThread: () => Effect.succeedNone,
1024 saveThread: () => Effect.void,
1025 removeThread: () => Effect.void,
1026 loadServerConfig: () => Effect.succeedSome(CONFIG),
1027 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
1028 loadVcsRefs: () => Effect.succeedNone,
1029 saveVcsRefs: () => Effect.void,
1030 removeVcsRefs: () => Effect.void,
1031 clearVcsRefs: () => Effect.void,
1032 clear: () => Effect.void,
1033 });
1034
1035 yield* Effect.scoped(
1036 Effect.gen(function* () {
1037 const state = yield* makeEnvironmentServerConfigState({}).pipe(
1038 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1039 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1040 );
1041 expect(Option.getOrThrow(yield* SubscriptionRef.get(state)).config).toBe(CONFIG);
1042
1043 const lastEventLoopStall = {
1044 detectedAt: "2026-10-20T07:50:37.633Z",
1045 durationMs: 12_422,
1046 loadAverage: 219.4,
1047 cpuCount: 18,
1048 };
1049 yield* Queue.offer(events, {
1050 version: 1,
1051 type: "snapshot",
1052 config: { ...CONFIG, lastEventLoopStall },
1053 });
1054 const projected = yield* SubscriptionRef.changes(state).pipe(
1055 Stream.filter((value) =>
1056 Option.match(value, {
1057 onNone: () => false,
1058 onSome: (projection) => projection.source === "live",
1059 }),
1060 ),
1061 Stream.runHead,
1062 );
1063 expect(Option.getOrThrow(Option.getOrThrow(projected)).config.lastEventLoopStall).toEqual(
1064 lastEventLoopStall,
1065 );
1066 }),
1067 );
1068
1069 // Cached, it would read as a fresh freeze on the next launch.
1070 expect(yield* Queue.take(savedConfigs)).not.toHaveProperty("lastEventLoopStall");
1071 }),
1072 );
1073});