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 Deferred from "effect/Deferred";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Fiber from "effect/Fiber";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Scope from "effect/Scope";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import * as TestClock from "effect/testing/TestClock";
22import { RpcClientError } from "effect/rpc";
23import * as Socket from "effect/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 applyServerWelcomeEvent,
36 makeEnvironmentServerWelcomeState,
37 makeEnvironmentServerConfigState,
38 isLegacyUpdateHandoffLoss,
39 matchesServerUpdateReadyEvent,
40 matchesServerUpdateResumeEvent,
41 nudgeReconnectDuringUpdateRestart,
42 resolveServerConfigValue,
43 resolveServerWelcomeState,
44 resolveServerUpdateProgressResult,
45 serverUpdateStateForProgressEvent,
46 serverUpdateStateForServerVersion,
47 validateServerUpdateReadyEvent,
48 waitForNextEnvironmentReconnect,
49 waitForDesktopUpdateTarget,
50 runDesktopCommitWithReconnectObserver,
51} from "./server.ts";
52import { applyServerConfigProjection } from "./serverConfigProjection.ts";
53
54const CONFIG = {
55 availableEditors: [],
56 issues: [],
57 keybindings: {},
58 keybindingsConfigPath: null,
59 observability: null,
60 providers: [],
61 settings: {},
62 // Capabilities drive version-skew behaviour in the projection, so the
63 // fixture carries them rather than leaving the field absent.
64 environment: { capabilities: { environmentThemes: true } },
65} as unknown as ServerConfig;
66
67const snapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
68 version: 1,
69 type: "snapshot",
70 config,
71});
72
73const TARGET = new PrimaryConnectionTarget({
74 environmentId: EnvironmentId.make("environment-1"),
75 label: "Test environment",
76 httpBaseUrl: "https://environment.example.test",
77 wsBaseUrl: "wss://environment.example.test",
78});
79
80function session(client: WsRpcProtocolClient): RpcSession {
81 return {
82 client,
83 initialConfig: Effect.succeed(CONFIG),
84 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
85 ready: Effect.void,
86 probe: Effect.void,
87 closed: Effect.never,
88 };
89}
90
91describe("update restart reconnect nudges", () => {
92 it.effect("retries a desktop commit that was lost before delivery", () =>
93 Effect.gen(function* () {
94 const readyEvents =
95 yield* Queue.unbounded<Parameters<typeof matchesServerUpdateReadyEvent>[1]>();
96 const ready = (serverVersion: string) =>
97 ({
98 version: 1 as const,
99 sequence: 1,
100 type: "ready" as const,
101 payload: {
102 at: "2026-09-01T00:00:00.000Z",
103 environment: { serverVersion },
104 },
105 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
106 yield* Queue.offerAll(readyEvents, [ready("0.0.30"), ready("0.0.31")]);
107 const retries = yield* Ref.make(0);
108 const disconnect = new RpcClientError.RpcClientError({
109 reason: new Socket.SocketCloseError({ code: 1006 }),
110 });
111
112 const result = yield* waitForDesktopUpdateTarget(
113 "0.0.31",
114 Queue.take(readyEvents),
115 Ref.update(retries, (count) => count + 1).pipe(Effect.andThen(Effect.fail(disconnect))),
116 );
117
118 expect(result.payload.environment.serverVersion).toBe("0.0.31");
119 expect(yield* Ref.get(retries)).toBe(1);
120 }),
121 );
122 it.effect("observes a fast reconnect even when the caller awaits it later", () =>
123 Effect.gen(function* () {
124 const states = yield* Queue.unbounded<{ readonly phase: string }>();
125 const reconnected = yield* waitForNextEnvironmentReconnect(Stream.fromQueue(states)).pipe(
126 Effect.forkChild,
127 );
128 yield* Queue.offerAll(states, [
129 { phase: "connected" },
130 { phase: "backoff" },
131 { phase: "connected" },
132 ]);
133
134 yield* Fiber.join(reconnected);
135 }),
136 );
137 it.effect("arms the retry observer before a commit can disconnect", () =>
138 Effect.gen(function* () {
139 const allowSubscription = yield* Deferred.make<void>();
140 const subscriptionStarted = yield* Deferred.make<void>();
141 const states = yield* Queue.unbounded<{ readonly phase: string }>();
142 const commits = yield* Ref.make(0);
143 const disconnect = new RpcClientError.RpcClientError({
144 reason: new Socket.SocketCloseError({ code: 1006 }),
145 });
146 const stateChanges = Stream.unwrap(
147 Deferred.succeed(subscriptionStarted, undefined).pipe(
148 Effect.andThen(Deferred.await(allowSubscription)),
149 Effect.as(Stream.fromQueue(states)),
150 ),
151 );
152 const retry = yield* runDesktopCommitWithReconnectObserver(
153 stateChanges,
154 Ref.update(commits, (count) => count + 1).pipe(
155 Effect.andThen(Queue.offerAll(states, [{ phase: "backoff" }, { phase: "connected" }])),
156 Effect.andThen(Effect.fail(disconnect)),
157 ),
158 ).pipe(Effect.flip, Effect.forkChild);
159
160 yield* Deferred.await(subscriptionStarted);
161 expect(yield* Ref.get(commits)).toBe(0);
162 yield* Deferred.succeed(allowSubscription, undefined);
163 yield* Queue.offer(states, { phase: "connected" });
164
165 expect(yield* Fiber.join(retry)).toBe(disconnect);
166 expect(yield* Ref.get(commits)).toBe(1);
167 }),
168 );
169 it.effect("retries once per backoff entry instead of only the first", () =>
170 Effect.gen(function* () {
171 const retries = yield* Ref.make(0);
172 const states = [
173 { phase: "backoff" },
174 { phase: "connecting" },
175 { phase: "backoff" },
176 { phase: "backoff" },
177 ];
178
179 yield* nudgeReconnectDuringUpdateRestart({
180 stateChanges: Stream.fromIterable(states),
181 retryNow: Ref.update(retries, (count) => count + 1),
182 interval: Duration.zero,
183 });
184
185 // Three backoff entries, three nudges. The old one-shot behavior fired
186 // once and then let the supervisor's ladder stretch to 16-second gaps.
187 expect(yield* Ref.get(retries)).toBe(3);
188 }),
189 );
190
191 it.effect("paces nudges so a fast-failing connection cannot spin", () =>
192 Effect.gen(function* () {
193 const retries = yield* Ref.make(0);
194
195 const fiber = yield* Effect.forkChild(
196 nudgeReconnectDuringUpdateRestart({
197 stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
198 retryNow: Ref.update(retries, (count) => count + 1),
199 }),
200 { startImmediately: true },
201 );
202
203 // Each nudge waits out the interval first, so nothing fires immediately.
204 yield* TestClock.adjust(Duration.millis(999));
205 expect(yield* Ref.get(retries)).toBe(0);
206
207 yield* TestClock.adjust(Duration.millis(1));
208 expect(yield* Ref.get(retries)).toBe(1);
209
210 yield* TestClock.adjust(Duration.seconds(1));
211 expect(yield* Ref.get(retries)).toBe(2);
212
213 yield* Fiber.join(fiber);
214 }).pipe(Effect.provide(TestClock.layer())),
215 );
216
217 it.effect("retries rejected credentials only while the update restart is in progress", () =>
218 Effect.gen(function* () {
219 const retries = yield* Ref.make(0);
220
221 yield* nudgeReconnectDuringUpdateRestart({
222 stateChanges: Stream.fromIterable([
223 { phase: "blocked", lastFailure: { reason: "permission" } },
224 {
225 phase: "blocked",
226 lastFailure: {
227 reason: "authentication",
228 detail: "The environment credential is invalid.",
229 },
230 },
231 { phase: "blocked", lastFailure: { reason: "configuration" } },
232 ]),
233 retryNow: Ref.update(retries, (count) => count + 1),
234 interval: Duration.zero,
235 });
236
237 expect(yield* Ref.get(retries)).toBe(1);
238 }),
239 );
240});
241
242describe("server state projection", () => {
243 it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
244 expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
245 expect(
246 isLegacyUpdateHandoffLoss(
247 Cause.fail(
248 new RpcClientError.RpcClientError({
249 reason: new Socket.SocketCloseError({ code: 1006 }),
250 }),
251 ),
252 ),
253 ).toBe(true);
254 expect(
255 isLegacyUpdateHandoffLoss(
256 Cause.fail(
257 new RpcClientError.RpcClientError({
258 reason: new Socket.SocketOpenError({
259 kind: "Unknown",
260 cause: new Error("connection refused"),
261 }),
262 }),
263 ),
264 ),
265 ).toBe(false);
266 expect(
267 isLegacyUpdateHandoffLoss(
268 Cause.fail(
269 new RpcClientError.RpcClientError({
270 reason: new RpcClientError.RpcClientDefect({
271 message: "incompatible protocol",
272 cause: new Error("invalid response"),
273 }),
274 }),
275 ),
276 ),
277 ).toBe(false);
278 expect(isLegacyUpdateHandoffLoss(Cause.fail(new Error("Install failed.")))).toBe(false);
279 });
280
281 it.effect("resumes after the progress stream disconnects following completion", () => {
282 const result = {
283 targetVersion: "0.0.31",
284 method: "respawn" as const,
285 };
286 const disconnect = new RpcClientError.RpcClientError({
287 reason: new Socket.SocketCloseError({ code: 1006 }),
288 });
289
290 return Effect.gen(function* () {
291 const resumed = yield* resolveServerUpdateProgressResult(
292 result.targetVersion,
293 Option.some(result),
294 Exit.fail(disconnect),
295 );
296 expect(resumed).toEqual(result);
297 });
298 });
299
300 it("projects streamed update milestones into the shared operation state", () => {
301 expect(
302 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
303 type: "progress",
304 stage: "installing",
305 }),
306 ).toEqual({
307 status: "running",
308 stage: "installing",
309 fromVersion: "0.0.30",
310 targetVersion: "0.0.31",
311 });
312 expect(
313 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
314 type: "complete",
315 result: { targetVersion: "0.0.31", method: "respawn" },
316 }),
317 ).toEqual({
318 status: "running",
319 stage: "resuming",
320 fromVersion: "0.0.30",
321 targetVersion: "0.0.31",
322 });
323 // A prepared desktop app update restarts only after the client commits it.
324 expect(
325 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
326 type: "complete",
327 result: { targetVersion: "0.0.31", method: "desktop-app", desktopUpdateToken: "token" },
328 }).stage,
329 ).toBe("installing");
330 });
331
332 it("keeps active update state and hides stale failures after a version change", () => {
333 const running = {
334 status: "running" as const,
335 stage: "resuming" as const,
336 fromVersion: "0.0.30",
337 targetVersion: "0.0.31",
338 };
339 const failed = {
340 status: "failed" as const,
341 stage: "installing" as const,
342 fromVersion: "0.0.30",
343 targetVersion: "0.0.31",
344 message: "Install failed.",
345 };
346
347 expect(serverUpdateStateForServerVersion(running, "0.0.31")).toBe(running);
348 expect(serverUpdateStateForServerVersion(failed, "0.0.30")).toBe(failed);
349 expect(serverUpdateStateForServerVersion(failed, null)).toBe(failed);
350 expect(serverUpdateStateForServerVersion(failed, "0.0.31")).toEqual({ status: "idle" });
351 });
352
353 it.effect("correlates launcher outcomes and fails immediately after rollback", () =>
354 Effect.gen(function* () {
355 const result = {
356 targetVersion: "0.0.31",
357 method: "boot-service" as const,
358 updateId: "update-1",
359 };
360 const ready = (status: "committed" | "rolled-back") =>
361 ({
362 version: 1 as const,
363 sequence: 1,
364 type: "ready" as const,
365 payload: {
366 at: "2026-08-01T00:00:00.000Z",
367 environment: { serverVersion: status === "committed" ? "0.0.31" : "0.0.30" },
368 updateOutcome: {
369 id: "update-1",
370 fromVersion: "0.0.30",
371 targetVersion: "0.0.31",
372 status,
373 ...(status === "rolled-back" ? { reason: "prepared-timeout" } : {}),
374 },
375 },
376 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
377
378 expect(matchesServerUpdateReadyEvent(result, ready("committed"))).toBe(true);
379 yield* validateServerUpdateReadyEvent(result, ready("committed"));
380 const rollback = yield* Effect.flip(
381 validateServerUpdateReadyEvent(result, ready("rolled-back")),
382 );
383 expect(rollback.message).toBe("prepared-timeout");
384 }),
385 );
386
387 it("requires tokenless desktop updates to reach the target version", () => {
388 const ready = (serverVersion: string) =>
389 ({
390 version: 1 as const,
391 sequence: 1,
392 type: "ready" as const,
393 payload: {
394 at: "2026-09-01T00:00:00.000Z",
395 environment: { serverVersion },
396 },
397 }) as Parameters<typeof matchesServerUpdateResumeEvent>[1];
398
399 expect(
400 matchesServerUpdateResumeEvent(
401 { targetVersion: "0.0.31", method: "desktop-app" },
402 ready("0.0.30"),
403 ),
404 ).toBe(false);
405 expect(
406 matchesServerUpdateResumeEvent(
407 {
408 targetVersion: "0.0.31",
409 method: "desktop-app",
410 desktopUpdateToken: "update-1",
411 },
412 ready("0.0.30"),
413 ),
414 ).toBe(true);
415 });
416
417 it("applies every config category to the projected snapshot", () => {
418 const snapshot = applyServerConfigProjection(Option.none(), {
419 version: 1,
420 type: "snapshot",
421 config: CONFIG,
422 });
423 const settings = { ...CONFIG.settings };
424 const projected = applyServerConfigProjection(snapshot, {
425 version: 1,
426 type: "settingsUpdated",
427 payload: { settings },
428 });
429
430 const result = Option.getOrThrow(projected);
431 expect(result.config.settings).toBe(settings);
432 expect(result.latestEvent.type).toBe("settingsUpdated");
433 });
434
435 it("carries published environment themes in and out of the projected snapshot", () => {
436 const snapshot = applyServerConfigProjection(Option.none(), {
437 version: 1,
438 type: "snapshot",
439 config: CONFIG,
440 });
441 const themes = [
442 {
443 id: "nightfall",
444 name: "Nightfall",
445 appearance: "dark",
446 canvas: "#1a1b26",
447 accent: "#7aa2f7",
448 },
449 ] as const;
450
451 const published = applyServerConfigProjection(snapshot, {
452 version: 1,
453 type: "environmentThemesUpdated",
454 payload: { themes },
455 });
456 expect(Option.getOrThrow(published).config.environmentThemes).toEqual(themes);
457
458 // A machine that stops publishing has to clear the palettes, not freeze
459 // clients on the last set it sent.
460 const unpublished = applyServerConfigProjection(published, {
461 version: 1,
462 type: "environmentThemesUpdated",
463 payload: { themes: [] },
464 });
465 expect(Option.getOrThrow(unpublished).config.environmentThemes).toBeUndefined();
466 });
467
468 // A snapshot never carries published themes, so taking it wholesale would
469 // clear them on every reconnect and repaint anyone wearing one.
470 it("keeps published themes across a reconnect snapshot", () => {
471 const themes = [
472 {
473 id: "nightfall",
474 name: "Nightfall",
475 appearance: "dark",
476 canvas: "#1a1b26",
477 accent: "#7aa2f7",
478 },
479 ] as const;
480
481 const withThemes = applyServerConfigProjection(
482 applyServerConfigProjection(Option.none(), { version: 1, type: "snapshot", config: CONFIG }),
483 { version: 1, type: "environmentThemesUpdated", payload: { themes } },
484 );
485 expect(Option.getOrThrow(withThemes).config.environmentThemes).toEqual(themes);
486
487 const afterReconnect = applyServerConfigProjection(withThemes, {
488 version: 1,
489 type: "snapshot",
490 config: CONFIG,
491 });
492 expect(Option.getOrThrow(afterReconnect).config.environmentThemes).toEqual(themes);
493
494 // A server that predates the feature never sends another theme event, so
495 // carrying the set forward would leave a palette nothing can update.
496 const downgraded = applyServerConfigProjection(withThemes, {
497 version: 1,
498 type: "snapshot",
499 config: {
500 ...CONFIG,
501 environment: { capabilities: {} },
502 } as unknown as ServerConfig,
503 });
504 expect(Option.getOrThrow(downgraded).config.environmentThemes).toBeUndefined();
505 });
506
507 it("keeps a current welcome on ready and rejects a buffered welcome from the old session", () => {
508 const firstSession = session({} as WsRpcProtocolClient);
509 const secondSession = session({} as WsRpcProtocolClient);
510 const welcome = {
511 environment: {} as ServerLifecycleWelcomePayload["environment"],
512 cwd: "/repo",
513 projectName: "repo",
514 } as ServerLifecycleWelcomePayload;
515 const initial = {
516 currentSession: firstSession,
517 welcomeSession: firstSession,
518 welcome: null,
519 };
520 const afterWelcome = applyServerWelcomeEvent(initial, firstSession, {
521 type: "welcome",
522 payload: welcome,
523 });
524 const afterReady = applyServerWelcomeEvent(afterWelcome, firstSession, {
525 type: "ready",
526 payload: {},
527 });
528 const afterSwitch = { ...afterReady, currentSession: secondSession };
529 const afterBufferedOldWelcome = applyServerWelcomeEvent(afterSwitch, firstSession, {
530 type: "welcome",
531 payload: { ...welcome, cwd: "/stale" },
532 });
533
534 expect(afterReady).toBe(afterWelcome);
535 expect(resolveServerWelcomeState(afterReady)).toBe(welcome);
536 expect(afterBufferedOldWelcome).toBe(afterSwitch);
537 expect(resolveServerWelcomeState(afterBufferedOldWelcome)).toBeNull();
538 });
539
540 it.effect("checks the authoritative session before accepting a buffered welcome", () =>
541 Effect.gen(function* () {
542 const firstEvents = yield* Queue.unbounded<{
543 readonly type: "welcome" | "ready";
544 readonly payload: unknown;
545 }>();
546 const firstSubscribed = yield* Deferred.make<void>();
547 const firstClient = {
548 [WS_METHODS.subscribeServerLifecycle]: () =>
549 Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe(
550 Stream.drain,
551 Stream.concat(Stream.fromQueue(firstEvents)),
552 ),
553 } as unknown as WsRpcProtocolClient;
554 const firstSession = session(firstClient);
555 const secondSession = session({} as WsRpcProtocolClient);
556 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
557 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
558 target: TARGET,
559 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
560 session: supervisorSession,
561 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
562 connect: Effect.void,
563 disconnect: Effect.void,
564 retryNow: Effect.void,
565 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
566 const staleWelcome = {
567 environment: {} as ServerLifecycleWelcomePayload["environment"],
568 cwd: "/stale",
569 projectName: "stale",
570 } as ServerLifecycleWelcomePayload;
571
572 yield* Effect.scoped(
573 Effect.gen(function* () {
574 const state = yield* makeEnvironmentServerWelcomeState().pipe(
575 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
576 );
577 yield* Deferred.await(firstSubscribed);
578
579 // Model the point after the ref changed but before either subscriber
580 // processed its publication.
581 supervisorSession.value = Option.some(secondSession);
582 const handled = yield* SubscriptionRef.changes(state).pipe(
583 Stream.filter(
584 (value) => value.currentSession === secondSession || value.welcome === staleWelcome,
585 ),
586 Stream.runHead,
587 Effect.map(Option.getOrThrow),
588 Effect.forkChild,
589 );
590 yield* Queue.offer(firstEvents, { type: "welcome", payload: staleWelcome });
591
592 const next = yield* Fiber.join(handled);
593 expect(next.currentSession).toBe(secondSession);
594 expect(resolveServerWelcomeState(next)).toBeNull();
595 }),
596 );
597 }),
598 );
599
600 it.effect("reads the authoritative session after waiting for the welcome state lock", () =>
601 Effect.gen(function* () {
602 const firstSubscribed = yield* Deferred.make<void>();
603 const firstClient = {
604 [WS_METHODS.subscribeServerLifecycle]: () =>
605 Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe(Stream.drain),
606 } as unknown as WsRpcProtocolClient;
607 const secondClient = {
608 [WS_METHODS.subscribeServerLifecycle]: () => Stream.never,
609 } as unknown as WsRpcProtocolClient;
610 const firstSession = session(firstClient);
611 const secondSession = session(secondClient);
612 const thirdSession = session({} as WsRpcProtocolClient);
613 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
614 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
615 target: TARGET,
616 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
617 session: supervisorSession,
618 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
619 connect: Effect.void,
620 disconnect: Effect.void,
621 retryNow: Effect.void,
622 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
623
624 yield* Effect.scoped(
625 Effect.gen(function* () {
626 const state = yield* makeEnvironmentServerWelcomeState().pipe(
627 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
628 );
629 yield* Deferred.await(firstSubscribed);
630 const changed = yield* SubscriptionRef.changes(state).pipe(
631 Stream.filter((value) => value.currentSession !== firstSession),
632 Stream.runHead,
633 Effect.map(Option.getOrThrow),
634 Effect.forkChild,
635 );
636
637 yield* state.semaphore.withPermit(
638 Effect.gen(function* () {
639 yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession));
640 yield* Effect.yieldNow;
641 yield* Effect.yieldNow;
642 yield* Effect.yieldNow;
643 supervisorSession.value = Option.some(thirdSession);
644 }),
645 );
646
647 expect((yield* Fiber.join(changed)).currentSession).toBe(thirdSession);
648 }),
649 );
650 }),
651 );
652
653 it.effect("clears a welcome until the reconnected session sends its own", () =>
654 Effect.gen(function* () {
655 const firstEvents = yield* Queue.unbounded<{
656 readonly type: "welcome" | "ready";
657 readonly payload: unknown;
658 }>();
659 const secondEvents = yield* Queue.unbounded<{
660 readonly type: "welcome" | "ready";
661 readonly payload: unknown;
662 }>();
663 const firstClient = {
664 [WS_METHODS.subscribeServerLifecycle]: () => Stream.fromQueue(firstEvents),
665 } as unknown as WsRpcProtocolClient;
666 const secondClient = {
667 [WS_METHODS.subscribeServerLifecycle]: () => Stream.fromQueue(secondEvents),
668 } as unknown as WsRpcProtocolClient;
669 const firstSession = session(firstClient);
670 const secondSession = session(secondClient);
671 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
672 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
673 target: TARGET,
674 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
675 session: supervisorSession,
676 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
677 connect: Effect.void,
678 disconnect: Effect.void,
679 retryNow: Effect.void,
680 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
681 const firstWelcome = {
682 environment: {} as ServerLifecycleWelcomePayload["environment"],
683 cwd: "/first",
684 projectName: "first",
685 } as ServerLifecycleWelcomePayload;
686 const secondWelcome = {
687 environment: {} as ServerLifecycleWelcomePayload["environment"],
688 cwd: "/second",
689 projectName: "second",
690 } as ServerLifecycleWelcomePayload;
691
692 yield* Effect.scoped(
693 Effect.gen(function* () {
694 const state = yield* makeEnvironmentServerWelcomeState().pipe(
695 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
696 );
697 const nextResolved = (
698 predicate: (value: ServerLifecycleWelcomePayload | null) => boolean,
699 ) =>
700 SubscriptionRef.changes(state).pipe(
701 Stream.map(resolveServerWelcomeState),
702 Stream.filter(predicate),
703 Stream.runHead,
704 Effect.map(Option.getOrThrow),
705 );
706
707 const first = yield* nextResolved((value) => value === firstWelcome).pipe(
708 Effect.forkChild,
709 );
710 yield* Queue.offer(firstEvents, { type: "welcome", payload: firstWelcome });
711 expect(yield* Fiber.join(first)).toBe(firstWelcome);
712
713 const cleared = yield* nextResolved((value) => value === null).pipe(Effect.forkChild);
714 yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession));
715 expect(yield* Fiber.join(cleared)).toBeNull();
716 expect(resolveServerWelcomeState(yield* SubscriptionRef.get(state))).toBeNull();
717
718 const second = yield* nextResolved((value) => value === secondWelcome).pipe(
719 Effect.forkChild,
720 );
721 yield* Queue.offer(secondEvents, { type: "welcome", payload: secondWelcome });
722 expect(yield* Fiber.join(second)).toBe(secondWelcome);
723 }),
724 );
725 }),
726 );
727
728 it("prefers an active session config over cache until a live event arrives", () => {
729 const config = (source: string, serverVersion: string) =>
730 ({
731 ...CONFIG,
732 environment: { serverVersion },
733 settings: { source },
734 }) as unknown as ServerConfig;
735 const cached = config("cache", "0.0.29");
736 const staleLive = config("stale-live", "0.0.29");
737 const initial = config("session", "0.0.30");
738 const live = config("live", "0.0.30");
739
740 expect(
741 resolveServerConfigValue(
742 {
743 config: cached,
744 latestEvent: snapshotEvent(cached),
745 source: "cache",
746 },
747 initial,
748 ),
749 ).toBe(initial);
750 expect(
751 resolveServerConfigValue(
752 {
753 config: staleLive,
754 latestEvent: snapshotEvent(staleLive),
755 source: "live",
756 },
757 initial,
758 ),
759 ).toBe(initial);
760 expect(
761 resolveServerConfigValue(
762 {
763 config: live,
764 latestEvent: snapshotEvent(live),
765 source: "live",
766 },
767 initial,
768 ),
769 ).toBe(live);
770 });
771
772 it.effect("throttles server configuration writes and flushes the latest on teardown", () =>
773 Effect.gen(function* () {
774 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
775 const client = {
776 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
777 } as unknown as WsRpcProtocolClient;
778 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
779 target: TARGET,
780 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
781 session: yield* SubscriptionRef.make(Option.some(session(client))),
782 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
783 connect: Effect.void,
784 disconnect: Effect.void,
785 retryNow: Effect.void,
786 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
787 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
788 const cache = Persistence.EnvironmentCacheStore.of({
789 loadShell: () => Effect.succeed(Option.none()),
790 saveShell: () => Effect.void,
791 loadThread: () => Effect.succeed(Option.none()),
792 saveThread: () => Effect.void,
793 removeThread: () => Effect.void,
794 loadServerConfig: () => Effect.succeed(Option.some(CONFIG)),
795 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
796 loadVcsRefs: () => Effect.succeed(Option.none()),
797 saveVcsRefs: () => Effect.void,
798 removeVcsRefs: () => Effect.void,
799 clearVcsRefs: () => Effect.void,
800 clear: () => Effect.void,
801 });
802
803 const scope = yield* Scope.make();
804 const state = yield* makeEnvironmentServerConfigState({}).pipe(
805 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
806 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
807 Effect.provideService(Scope.Scope, scope),
808 );
809 const sendConfig = Effect.fn(function* (cwd: string) {
810 yield* Queue.offer(events, { version: 1, type: "snapshot", config: { ...CONFIG, cwd } });
811 yield* SubscriptionRef.changes(state).pipe(
812 Stream.filter((value) => Option.isSome(value) && value.value.config.cwd === cwd),
813 Stream.runHead,
814 );
815 });
816 yield* sendConfig("/first");
817 yield* TestClock.adjust("500 millis");
818 expect((yield* Queue.take(savedConfigs)).cwd).toBe("/first");
819 for (let index = 1; index <= 9; index++) {
820 yield* sendConfig(`/repo-${index}`);
821 yield* TestClock.adjust("1 second");
822 }
823 expect(yield* Queue.poll(savedConfigs)).toEqual(Option.none());
824 yield* TestClock.adjust("1 second");
825 expect((yield* Queue.take(savedConfigs)).cwd).toBe("/repo-9");
826 yield* sendConfig("/final");
827 yield* Scope.close(scope, Exit.void);
828 expect((yield* Queue.take(savedConfigs)).cwd).toBe("/final");
829 expect(yield* Queue.poll(savedConfigs)).toEqual(Option.none());
830 }),
831 );
832
833 it.effect("starts from cached configuration and persists the live projection", () =>
834 Effect.gen(function* () {
835 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
836 const client = {
837 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
838 } as unknown as WsRpcProtocolClient;
839 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
840 target: TARGET,
841 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
842 session: yield* SubscriptionRef.make(Option.some(session(client))),
843 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
844 connect: Effect.void,
845 disconnect: Effect.void,
846 retryNow: Effect.void,
847 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
848 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
849 const cache = Persistence.EnvironmentCacheStore.of({
850 loadShell: () => Effect.succeedNone,
851 saveShell: () => Effect.void,
852 loadThread: () => Effect.succeedNone,
853 saveThread: () => Effect.void,
854 removeThread: () => Effect.void,
855 loadServerConfig: () => Effect.succeedSome(CONFIG),
856 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
857 loadVcsRefs: () => Effect.succeedNone,
858 saveVcsRefs: () => Effect.void,
859 removeVcsRefs: () => Effect.void,
860 clearVcsRefs: () => Effect.void,
861 clear: () => Effect.void,
862 });
863
864 yield* Effect.scoped(
865 Effect.gen(function* () {
866 const state = yield* makeEnvironmentServerConfigState({}).pipe(
867 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
868 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
869 );
870 expect(Option.getOrThrow(yield* SubscriptionRef.get(state)).config).toBe(CONFIG);
871
872 const providers: ServerConfig["providers"] = [];
873 yield* Queue.offer(events, {
874 version: 1,
875 type: "providerStatuses",
876 payload: { providers },
877 });
878 const projected = yield* SubscriptionRef.changes(state).pipe(
879 Stream.filter((value) =>
880 Option.match(value, {
881 onNone: () => false,
882 onSome: (projection) => projection.latestEvent.type === "providerStatuses",
883 }),
884 ),
885 Stream.runHead,
886 );
887 expect(Option.getOrThrow(Option.getOrThrow(projected)).config.providers).toBe(providers);
888 }),
889 );
890
891 expect((yield* Queue.take(savedConfigs)).providers).toEqual([]);
892 }),
893 );
894
895 it.effect("does not rewrite cached configuration when no live update arrives", () =>
896 Effect.gen(function* () {
897 const client = {
898 [WS_METHODS.subscribeServerConfig]: () => Stream.empty,
899 } as unknown as WsRpcProtocolClient;
900 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
901 target: TARGET,
902 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
903 session: yield* SubscriptionRef.make(Option.some(session(client))),
904 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
905 connect: Effect.void,
906 disconnect: Effect.void,
907 retryNow: Effect.void,
908 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
909 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
910 const cache = Persistence.EnvironmentCacheStore.of({
911 loadShell: () => Effect.succeedNone,
912 saveShell: () => Effect.void,
913 loadThread: () => Effect.succeedNone,
914 saveThread: () => Effect.void,
915 removeThread: () => Effect.void,
916 loadServerConfig: () => Effect.succeedSome(CONFIG),
917 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
918 loadVcsRefs: () => Effect.succeedNone,
919 saveVcsRefs: () => Effect.void,
920 removeVcsRefs: () => Effect.void,
921 clearVcsRefs: () => Effect.void,
922 clear: () => Effect.void,
923 });
924
925 yield* Effect.scoped(
926 makeEnvironmentServerConfigState({}).pipe(
927 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
928 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
929 ),
930 );
931
932 expect(yield* Queue.poll(savedConfigs)).toEqual(Option.none());
933 }),
934 );
935});