Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.test.ts

662 lines22.4 KB

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