The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,975 lines 76.1 KB
Raw
1 import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ServerSelfUpdateError,
5 ProviderInstanceId,
6 type ProviderInstallState,
7 type ProviderSetupInput,
8 ServerObservability,
9 EnvironmentThemeId,
10 UsageLimitSourceId,
11 type ServerConfig,
12 type ServerConfigStreamEvent,
13 type ServerLifecycleStreamEvent,
14 type ServerLifecycleWelcomePayload,
15 type ServerSelfUpdateOutcome,
16 WS_METHODS,
17 } from "@t3tools/contracts";
18 import { describe, expect, it } from "@effect/vitest";
19 import { vi } from "vite-plus/test";
20 import * as Cause from "effect/Cause";
21 import * as Clock from "effect/Clock";
22 import * as Deferred from "effect/Deferred";
23 import * as Duration from "effect/Duration";
24 import * as Effect from "effect/Effect";
25 import * as Exit from "effect/Exit";
26 import * as Fiber from "effect/Fiber";
27 import * as Layer from "effect/Layer";
28 import * as Option from "effect/Option";
29 import * as Queue from "effect/Queue";
30 import * as Ref from "effect/Ref";
31 import * as Scheduler from "effect/Scheduler";
32 import * as Schema from "effect/Schema";
33 import * as Stream from "effect/Stream";
34 import * as SubscriptionRef from "effect/SubscriptionRef";
35 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
36 import * as TestClock from "effect/testing/TestClock";
37 import { RpcClientError } from "effect/rpc";
38 import * as Socket from "effect/socket/Socket";
39
40 import {
41 AVAILABLE_CONNECTION_STATE,
42 PrimaryConnectionTarget,
43 type PreparedConnection,
44 type SupervisorConnectionState,
45 } from "../connection/model.ts";
46 import * as EnvironmentRegistry from "../connection/registry.ts";
47 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
48 import { RpcPermissionGuard } from "../rpc/client.ts";
49 import * as Persistence from "../platform/persistence.ts";
50 import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
51 import type { RpcSession } from "../rpc/session.ts";
52 import {
53 applyServerWelcomeEvent,
54 createServerEnvironmentAtoms,
55 type FetchedMachineCatalog,
56 makeEnvironmentServerWelcomeState,
57 makeEnvironmentServerConfigState,
58 isLegacyUpdateHandoffLoss,
59 recordFetchedWorkspaceSnapshot,
60 withFetchedWorkspaceSnapshots,
61 matchesServerUpdateReadyEvent,
62 matchesServerUpdateResumeEvent,
63 nudgeReconnectDuringUpdateRestart,
64 resolveServerConfigValue,
65 resolveServerWelcomeState,
66 resolveServerUpdateProgressResult,
67 serverUpdateStateForProgressEvent,
68 serverUpdateStateAtom,
69 serverUpdateFailureText,
70 serverUpdateStateForServerVersion,
71 validateServerUpdateReadyEvent,
72 waitForNextEnvironmentReconnect,
73 waitForDesktopUpdateTarget,
74 runDesktopCommitWithReconnectObserver,
75 } from "./server.ts";
76 import { errorDisplayMessage, errorI18nMessage } from "../errors/translatable.ts";
77 import { runAtomCommand } from "./runtime.ts";
78 import { applyServerConfigProjection } from "./serverConfigProjection.ts";
79
80 const CONFIG = {
81 availableEditors: [],
82 issues: [],
83 keybindings: {},
84 keybindingsConfigPath: null,
85 observability: null,
86 providers: [],
87 settings: {},
88 environment: { capabilities: { environmentThemes: true } },
89 } as unknown as ServerConfig;
90
91 const snapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
92 version: 1,
93 type: "snapshot",
94 config,
95 });
96
97 const TARGET = new PrimaryConnectionTarget({
98 environmentId: EnvironmentId.make("environment-1"),
99 label: "Test environment",
100 httpBaseUrl: "https://environment.example.test",
101 wsBaseUrl: "wss://environment.example.test",
102 });
103
104 function session(client: WsRpcProtocolClient): RpcSession {
105 return {
106 client,
107 initialConfig: Effect.succeed(CONFIG),
108 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
109 ready: Effect.void,
110 probe: Effect.void,
111 inboundFrames: Effect.succeed(0),
112 closed: Effect.never,
113 };
114 }
115
116 describe("update restart reconnect nudges", () => {
117 it.effect("retries a desktop commit that was lost before delivery", () =>
118 Effect.gen(function* () {
119 const readyEvents =
120 yield* Queue.unbounded<Parameters<typeof matchesServerUpdateReadyEvent>[1]>();
121 const ready = (serverVersion: string) =>
122 ({
123 version: 1 as const,
124 sequence: 1,
125 type: "ready" as const,
126 payload: {
127 at: "2026-09-01T00:00:00.000Z",
128 environment: { serverVersion },
129 },
130 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
131 yield* Queue.offerAll(readyEvents, [ready("0.0.30"), ready("0.0.31")]);
132 const retries = yield* Ref.make(0);
133 const disconnect = new RpcClientError.RpcClientError({
134 reason: new Socket.SocketCloseError({ code: 1006 }),
135 });
136
137 const result = yield* waitForDesktopUpdateTarget(
138 "0.0.31",
139 Queue.take(readyEvents),
140 Ref.update(retries, (count) => count + 1).pipe(Effect.andThen(Effect.fail(disconnect))),
141 );
142
143 expect(result.payload.environment.serverVersion).toBe("0.0.31");
144 expect(yield* Ref.get(retries)).toBe(1);
145 }),
146 );
147 it.effect("observes a fast reconnect even when the caller awaits it later", () =>
148 Effect.gen(function* () {
149 const states = yield* Queue.unbounded<{ readonly phase: string }>();
150 const reconnected = yield* waitForNextEnvironmentReconnect(Stream.fromQueue(states)).pipe(
151 Effect.forkChild,
152 );
153 yield* Queue.offerAll(states, [
154 { phase: "connected" },
155 { phase: "backoff" },
156 { phase: "connected" },
157 ]);
158
159 yield* Fiber.join(reconnected);
160 }),
161 );
162 it.effect("arms the retry observer before a commit can disconnect", () =>
163 Effect.gen(function* () {
164 const allowSubscription = yield* Deferred.make<void>();
165 const subscriptionStarted = yield* Deferred.make<void>();
166 const states = yield* Queue.unbounded<{ readonly phase: string }>();
167 const commits = yield* Ref.make(0);
168 const disconnect = new RpcClientError.RpcClientError({
169 reason: new Socket.SocketCloseError({ code: 1006 }),
170 });
171 const stateChanges = Stream.unwrap(
172 Deferred.succeed(subscriptionStarted, undefined).pipe(
173 Effect.andThen(Deferred.await(allowSubscription)),
174 Effect.as(Stream.fromQueue(states)),
175 ),
176 );
177 const retry = yield* runDesktopCommitWithReconnectObserver(
178 stateChanges,
179 Ref.update(commits, (count) => count + 1).pipe(
180 Effect.andThen(Queue.offerAll(states, [{ phase: "backoff" }, { phase: "connected" }])),
181 Effect.andThen(Effect.fail(disconnect)),
182 ),
183 ).pipe(Effect.flip, Effect.forkChild);
184
185 yield* Deferred.await(subscriptionStarted);
186 expect(yield* Ref.get(commits)).toBe(0);
187 yield* Deferred.succeed(allowSubscription, undefined);
188 yield* Queue.offer(states, { phase: "connected" });
189
190 expect(yield* Fiber.join(retry)).toBe(disconnect);
191 expect(yield* Ref.get(commits)).toBe(1);
192 }),
193 );
194 it.effect("retries once per backoff entry instead of only the first", () =>
195 Effect.gen(function* () {
196 const retries = yield* Ref.make(0);
197 const states = [
198 { phase: "backoff" },
199 { phase: "connecting" },
200 { phase: "backoff" },
201 { phase: "backoff" },
202 ];
203
204 yield* nudgeReconnectDuringUpdateRestart({
205 stateChanges: Stream.fromIterable(states),
206 retryNow: Ref.update(retries, (count) => count + 1),
207 interval: Duration.zero,
208 });
209
210 expect(yield* Ref.get(retries)).toBe(3);
211 }),
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
239 describe("accepted server update recovery", () => {
240 it.effect.each([
241 { loss: "interrupt", resumes: true },
242 { loss: "socket", resumes: true },
243 { loss: "server_error", resumes: false },
244 { loss: "track_mismatch", method: "desktop-managed", resumes: false },
245 { loss: "track_mismatch", method: "desktop-managed", unary: true, resumes: false },
246 { loss: "no_progress", resumes: false },
247 { loss: "cancel", resumes: false },
248 { loss: "socket", method: "respawn", resumes: true },
249 { loss: "socket", method: "desktop-managed", resumes: false },
250 ] as const)("handles $loss with $method, unary=$unary and recovery=$resumes", (scenario) =>
251 Effect.gen(function* () {
252 const { loss, resumes } = scenario;
253 const method = "method" in scenario ? scenario.method : "boot-service";
254 const trackMismatch = new ServerSelfUpdateError({
255 reason:
256 "This Stable build can't update from the Nightly track on its own. Switch the update track back to Stable, or use Review beside Update track to retry the switch to Nightly.",
257 trackMismatch: { buildChannel: "latest", savedChannel: "nightly" },
258 });
259 const observing = yield* Deferred.make<void>();
260 const cancelFiber = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
261 const oldReadyObserved = yield* Deferred.make<void>();
262 const readyEvents =
263 yield* Queue.unbounded<Parameters<typeof matchesServerUpdateReadyEvent>[1]>();
264 const config = {
265 ...CONFIG,
266 environment: {
267 ...CONFIG.environment,
268 serverVersion: "0.0.30",
269 capabilities: {
270 serverSelfUpdate: method,
271 serverSelfUpdateProgress: !("unary" in scenario),
272 },
273 },
274 } as ServerConfig;
275 const ready = (serverVersion: string) =>
276 ({
277 version: 1,
278 sequence: 1,
279 type: "ready",
280 payload: { at: "2026-09-01T00:00:00.000Z", environment: { serverVersion } },
281 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
282 let requested = false;
283 const client = {
284 [WS_METHODS.subscribeServerConfig]: () => Stream.never,
285 // Before the request, a boot-service update reads the accepting server's ready.
286 [WS_METHODS.subscribeServerLifecycle]: () =>
287 requested
288 ? Stream.fromEffect(Deferred.succeed(observing, undefined)).pipe(
289 Stream.drain,
290 Stream.concat(Stream.fromQueue(readyEvents)),
291 Stream.tap((event) =>
292 event.payload.environment.serverVersion === "0.0.30"
293 ? Deferred.succeed(oldReadyObserved, undefined)
294 : Effect.void,
295 ),
296 )
297 : Stream.make(ready("0.0.30")).pipe(Stream.concat(Stream.never)),
298 [WS_METHODS.serverUpdateServer]: () => Effect.fail(trackMismatch),
299 [WS_METHODS.serverUpdateServerWithProgress]: () =>
300 Stream.unwrap(
301 Effect.sync(() => {
302 requested = true;
303 return loss === "no_progress"
304 ? Stream.empty
305 : Stream.make({ type: "progress" as const, stage: "downloading" as const });
306 }),
307 ).pipe(
308 Stream.concat(
309 Stream.fromEffect(
310 loss === "cancel"
311 ? Effect.fiber.pipe(
312 Effect.flatMap((fiber) => Deferred.succeed(cancelFiber, fiber)),
313 Effect.andThen(Effect.never),
314 )
315 : loss === "interrupt"
316 ? Effect.interrupt
317 : Effect.fail(
318 loss === "server_error"
319 ? new ServerSelfUpdateError({
320 reason: "Archive verification failed.",
321 })
322 : loss === "track_mismatch"
323 ? trackMismatch
324 : new RpcClientError.RpcClientError({
325 reason: new Socket.SocketCloseError({ code: 1006 }),
326 }),
327 ),
328 ),
329 ),
330 ),
331 } as unknown as WsRpcProtocolClient;
332 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
333 target: TARGET,
334 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
335 session: yield* SubscriptionRef.make(Option.some(session(client))),
336 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
337 connect: Effect.void,
338 disconnect: Effect.void,
339 retryNow: Effect.void,
340 });
341 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_id, effect) =>
342 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
343 const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = (
344 _id,
345 stream,
346 ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
347 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
348 run,
349 runStream,
350 followStream: runStream,
351 stateChanges: () => Stream.never,
352 retryNow: () => Effect.void,
353 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
354 const runtime = Atom.runtime(
355 Layer.mergeAll(
356 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
357 Layer.succeed(RpcPermissionGuard, { authorize: () => Effect.void }),
358 Layer.succeed(Persistence.EnvironmentCacheStore, {
359 loadServerConfig: () => Effect.succeedNone,
360 } as unknown as Persistence.EnvironmentCacheStore["Service"]),
361 ),
362 );
363 const atoms = createServerEnvironmentAtoms(runtime, {
364 initialConfigValueAtom: () => Atom.make(config),
365 });
366 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>
367 Effect.sync(() => value.dispose()),
368 );
369 // The registry drops an unmounted atom's value while the update is still running.
370 yield* AtomRegistry.mount(registry, serverUpdateStateAtom(TARGET.environmentId));
371 const pending = runAtomCommand(
372 registry,
373 atoms.updateServer,
374 { environmentId: TARGET.environmentId, input: { targetVersion: "0.0.31" } },
375 { reportFailure: false, reportDefect: false },
376 );
377 if (loss === "cancel") {
378 yield* Fiber.interrupt(yield* Deferred.await(cancelFiber));
379 const cancelled = yield* Effect.promise(() => pending);
380 expect(cancelled._tag).toBe("Failure");
381 if (cancelled._tag === "Failure")
382 expect(Cause.hasInterruptsOnly(cancelled.cause)).toBe(true);
383 expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toEqual({
384 status: "idle",
385 });
386 expect(yield* Deferred.isDone(observing)).toBe(false);
387 return;
388 }
389 const first = yield* Effect.raceFirst(
390 Effect.promise(() => pending).pipe(Effect.as("settled")),
391 Deferred.await(observing).pipe(Effect.as("observing")),
392 );
393 if (!resumes) {
394 expect(first).toBe("settled");
395 const failure = yield* Effect.promise(() => pending);
396 expect(AsyncResult.isFailure(failure)).toBe(true);
397 const failed = registry.get(serverUpdateStateAtom(TARGET.environmentId));
398 expect(failed).toMatchObject({ status: "failed" });
399 if (
400 loss === "track_mismatch" &&
401 AsyncResult.isFailure(failure) &&
402 failed.status === "failed"
403 ) {
404 const cause = Cause.squash(failure.cause);
405 const marked = errorI18nMessage(cause);
406 expect(marked).toHaveLength(2);
407 expect(failed.i18nMessage).toEqual(marked);
408 expect(errorDisplayMessage(cause)).toBe(trackMismatch.message);
409 expect(serverUpdateFailureText(failed)).toBe(trackMismatch.message);
410 }
411 return;
412 }
413 expect(first).toBe("observing");
414 expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject({
415 status: "running",
416 stage: "resuming",
417 });
418 yield* Queue.offer(readyEvents, ready("0.0.30"));
419 yield* Deferred.await(oldReadyObserved);
420 expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toMatchObject({
421 status: "running",
422 });
423 yield* Queue.offer(readyEvents, ready("0.0.31"));
424 expect(AsyncResult.isSuccess(yield* Effect.promise(() => pending))).toBe(true);
425 expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toEqual({
426 status: "idle",
427 });
428 }),
429 );
430 });
431
432 const makeConfigPersistenceHarness = Effect.fn("test.makeConfigPersistenceHarness")(function* (
433 saveServerConfig: Persistence.EnvironmentCacheStore["Service"]["saveServerConfig"],
434 machineCatalogs?: Stream.Stream<ReadonlyArray<FetchedMachineCatalog>>,
435 ) {
436 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
437 const client = {
438 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
439 } as unknown as WsRpcProtocolClient;
440 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
441 target: TARGET,
442 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
443 session: yield* SubscriptionRef.make(Option.some(session(client))),
444 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
445 connect: Effect.void,
446 disconnect: Effect.void,
447 retryNow: Effect.void,
448 });
449 const cache = Persistence.EnvironmentCacheStore.of({
450 loadShell: () => Effect.succeedNone,
451 saveShell: () => Effect.void,
452 loadThread: () => Effect.succeedNone,
453 saveThread: () => Effect.void,
454 removeThread: () => Effect.void,
455 loadServerConfig: () => Effect.succeedSome(CONFIG),
456 saveServerConfig,
457 loadVcsRefs: () => Effect.succeedNone,
458 saveVcsRefs: () => Effect.void,
459 removeVcsRefs: () => Effect.void,
460 clearVcsRefs: () => Effect.void,
461 clear: () => Effect.void,
462 });
463 const state = yield* makeEnvironmentServerConfigState(
464 { environmentThemes: true, usageLimitSources: true },
465 machineCatalogs,
466 ).pipe(
467 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
468 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
469 );
470 const send = Effect.fn("test.sendConfigEvent")(function* (event: ServerConfigStreamEvent) {
471 yield* Queue.offer(events, event);
472 return yield* SubscriptionRef.changes(state).pipe(
473 Stream.filter(Option.isSome),
474 Stream.map((value) => value.value),
475 Stream.filter((projection) => projection.latestEvent === event),
476 Stream.runHead,
477 Effect.map(Option.getOrThrow),
478 );
479 });
480 return { send, state };
481 });
482
483 describe("server state projection", () => {
484 it.effect("skips duplicate keybinding saves but persists changed keybindings", () =>
485 Effect.gen(function* () {
486 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
487 const keybindingsEvent = (key: string): ServerConfigStreamEvent => ({
488 version: 1,
489 type: "keybindingsUpdated",
490 payload: {
491 keybindings: [
492 {
493 command: "terminal.toggle",
494 shortcut: {
495 key,
496 metaKey: false,
497 ctrlKey: false,
498 shiftKey: false,
499 altKey: false,
500 modKey: true,
501 },
502 },
503 ],
504 issues: [],
505 },
506 });
507 yield* Effect.scoped(
508 Effect.gen(function* () {
509 const h = yield* makeConfigPersistenceHarness((_id, config) =>
510 Ref.update(saved, (values) => [...values, config]),
511 );
512 const first = yield* h.send(keybindingsEvent("p"));
513 yield* TestClock.adjust("500 millis");
514 expect(yield* Ref.get(saved)).toEqual([first.config]);
515
516 yield* h.send(keybindingsEvent("p"));
517 yield* TestClock.adjust("10 seconds");
518 expect(yield* Ref.get(saved)).toEqual([first.config]);
519
520 const changed = yield* h.send(keybindingsEvent("q"));
521 yield* TestClock.adjust("10 seconds");
522 expect(yield* Ref.get(saved)).toEqual([first.config, changed.config]);
523 }),
524 );
525 }),
526 );
527
528 it.effect(
529 "compares nested durable values independently of key order and omitted undefined fields",
530 () =>
531 Effect.gen(function* () {
532 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
533 const observability = {
534 logsDirectoryPath: "/synthetic/logs",
535 localTracingEnabled: false,
536 otlpTracesEnabled: false,
537 otlpMetricsEnabled: false,
538 otlpLogsEnabled: false,
539 };
540 yield* Effect.scoped(
541 Effect.gen(function* () {
542 const h = yield* makeConfigPersistenceHarness((_id, config) =>
543 Ref.update(saved, (values) => [...values, config]),
544 );
545 const first = yield* h.send(snapshotEvent({ ...CONFIG, observability }));
546 yield* TestClock.adjust("500 millis");
547 const reordered = Object.fromEntries(
548 Object.entries(observability).toReversed(),
549 ) as typeof observability;
550 for (const next of [
551 { ...CONFIG, observability: reordered },
552 { ...CONFIG, observability: { ...reordered, otlpTracesUrl: undefined } },
553 { ...CONFIG, observability: { ...observability } },
554 ]) {
555 const encode = Schema.encodeEffect(Schema.fromJsonString(ServerObservability));
556 expect(JSON.parse(yield* encode(next.observability))).toEqual(
557 JSON.parse(yield* encode(observability)),
558 );
559 const projection = yield* h.send(snapshotEvent(next));
560 expect(projection.config.observability).toEqual(next.observability);
561 yield* TestClock.adjust("10 seconds");
562 expect.soft(yield* Ref.get(saved)).toEqual([first.config]);
563 }
564 const writesBeforeChange = (yield* Ref.get(saved)).length;
565 const changed = yield* h.send(
566 snapshotEvent({
567 ...CONFIG,
568 observability: { ...observability, otlpTracesUrl: "https://traces.example.test" },
569 }),
570 );
571 yield* TestClock.adjust("10 seconds");
572 expect((yield* Ref.get(saved)).length).toBe(writesBeforeChange + 1);
573 expect((yield* Ref.get(saved)).at(-1)).toEqual(changed.config);
574 }),
575 );
576 }),
577 );
578
579 it.effect("saves once across transient themes, usage sources and stall updates", () =>
580 Effect.gen(function* () {
581 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
582 yield* Effect.scoped(
583 Effect.gen(function* () {
584 const h = yield* makeConfigPersistenceHarness((_id, config) =>
585 Ref.update(saved, (values) => [...values, config]),
586 );
587 yield* h.send(snapshotEvent(CONFIG));
588 yield* TestClock.adjust("500 millis");
589 expect((yield* Ref.get(saved)).length).toBe(1);
590 for (const event of [
591 {
592 version: 1,
593 type: "environmentThemesUpdated",
594 payload: {
595 themes: [
596 {
597 id: EnvironmentThemeId.make("theme-test"),
598 name: "Test theme",
599 appearance: "dark",
600 },
601 ],
602 },
603 },
604 {
605 version: 1,
606 type: "usageLimitSourcesUpdated",
607 payload: {
608 sources: [
609 {
610 id: UsageLimitSourceId.make("source-test"),
611 kind: "cliproxy",
612 label: "Test source",
613 checkedAt: "2026-10-20T07:50:37.633Z",
614 accounts: [],
615 },
616 ],
617 },
618 },
619 snapshotEvent({
620 ...CONFIG,
621 lastEventLoopStall: {
622 detectedAt: "2026-10-20T07:50:37.633Z",
623 durationMs: 1000,
624 loadAverage: 1,
625 cpuCount: 8,
626 },
627 }),
628 ] satisfies ReadonlyArray<ServerConfigStreamEvent>) {
629 const projection = yield* h.send(event);
630 expect(projection.latestEvent).toBe(event);
631 if (event.type === "environmentThemesUpdated")
632 expect(projection.config.environmentThemes).toEqual(event.payload.themes);
633 if (event.type === "usageLimitSourcesUpdated")
634 expect(projection.config.usageLimitSources).toEqual(event.payload.sources);
635 yield* TestClock.adjust("10 seconds");
636 }
637 }),
638 );
639 expect(yield* Ref.get(saved)).toEqual([CONFIG]);
640 }),
641 );
642
643 it.effect("caches the lists a cwd snapshot loaded for a catalog digest", () =>
644 Effect.gen(function* () {
645 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
646 const catalogs = yield* Queue.unbounded<ReadonlyArray<FetchedMachineCatalog>>();
647 const instanceId = ProviderInstanceId.make("claudeAgent");
648 const otherInstanceId = ProviderInstanceId.make("codex");
649 const thirdInstanceId = ProviderInstanceId.make("cursor");
650 const slashCommands = [{ name: "compact" }];
651 // What the server sends: a digest in place of the two lists.
652 const snapshot = (catalogDigest = "d1") =>
653 snapshotEvent({
654 ...CONFIG,
655 providers: [
656 { instanceId, slashCommands: [], skills: [], catalogDigest },
657 { instanceId: otherInstanceId, slashCommands: [], skills: [], catalogDigest: "c1" },
658 { instanceId: thirdInstanceId, slashCommands: [], skills: [], catalogDigest: "t1" },
659 ],
660 } as unknown as ServerConfig);
661 yield* Effect.scoped(
662 Effect.gen(function* () {
663 const h = yield* makeConfigPersistenceHarness(
664 (_id, config) => Ref.update(saved, (values) => [...values, config]),
665 Stream.fromQueue(catalogs),
666 );
667 yield* h.send(snapshot());
668 yield* Queue.offer(catalogs, [{ instanceId, digest: "d1", slashCommands, skills: [] }]);
669 const loaded = yield* SubscriptionRef.changes(h.state).pipe(
670 Stream.map((value) => Option.getOrThrow(value).config.providers[0]),
671 Stream.filter((provider) => provider?.loadedCatalogDigest === "d1"),
672 Stream.runHead,
673 );
674 expect(Option.getOrThrow(loaded)?.slashCommands).toEqual(slashCommands);
675
676 yield* TestClock.adjust("10 seconds");
677 expect((yield* Ref.get(saved)).at(-1)?.providers[0]).toMatchObject({
678 slashCommands,
679 loadedCatalogDigest: "d1",
680 });
681
682 // A reconnect sends the digest again, and the loaded lists stay.
683 const reconnected = yield* h.send(snapshot());
684 expect(reconnected.config.providers[0]).toMatchObject({
685 slashCommands,
686 loadedCatalogDigest: "d1",
687 });
688
689 // A reply for an older catalog that lands late does not replace the current lists.
690 const late = { instanceId, digest: "d0", slashCommands: [{ name: "old" }], skills: [] };
691 yield* Queue.offer(catalogs, [late]);
692 yield* Queue.offer(catalogs, [
693 late,
694 { instanceId: otherInstanceId, digest: "c1", slashCommands: [], skills: [] },
695 ]);
696 const settled = yield* SubscriptionRef.changes(h.state).pipe(
697 Stream.map((value) => Option.getOrThrow(value).config.providers),
698 Stream.filter((providers) => providers[1]?.loadedCatalogDigest === "c1"),
699 Stream.runHead,
700 );
701 expect(Option.getOrThrow(settled)[0]).toMatchObject({
702 slashCommands,
703 loadedCatalogDigest: "d1",
704 });
705
706 // A reply for a newer catalog can land before the config names its digest. It is
707 // kept, and applies when the config does.
708 const newer = { instanceId, digest: "d2", slashCommands: [{ name: "new" }], skills: [] };
709 yield* Queue.offer(catalogs, [
710 newer,
711 { instanceId: thirdInstanceId, digest: "t1", slashCommands: [], skills: [] },
712 ]);
713 const kept = yield* SubscriptionRef.changes(h.state).pipe(
714 Stream.map((value) => Option.getOrThrow(value).config.providers),
715 Stream.filter((providers) => providers[2]?.loadedCatalogDigest === "t1"),
716 Stream.runHead,
717 );
718 expect(Option.getOrThrow(kept)[0]).toMatchObject({ loadedCatalogDigest: "d1" });
719 const advanced = yield* h.send(snapshot("d2"));
720 expect(advanced.config.providers[0]).toMatchObject({
721 slashCommands: newer.slashCommands,
722 loadedCatalogDigest: "d2",
723 });
724 }),
725 );
726 }),
727 );
728
729 it.effect("flushes pending durable changes after a transient event", () =>
730 Effect.gen(function* () {
731 const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
732 const changed = { ...CONFIG, keybindingsConfigPath: "/changed/keybindings.json" };
733 yield* Effect.scoped(
734 Effect.gen(function* () {
735 const h = yield* makeConfigPersistenceHarness((_id, config) =>
736 Ref.update(saved, (values) => [...values, config]),
737 );
738 yield* h.send(snapshotEvent(CONFIG));
739 yield* TestClock.adjust("500 millis");
740 yield* h.send(snapshotEvent(changed));
741 yield* h.send({ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } });
742 }),
743 );
744 expect(yield* Ref.get(saved)).toEqual([CONFIG, changed]);
745 }),
746 );
747
748 it.effect("retries a failed durable save on a transient event", () =>
749 Effect.gen(function* () {
750 const attempts = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);
751 yield* Effect.scoped(
752 Effect.gen(function* () {
753 const h = yield* makeConfigPersistenceHarness((_id, config) =>
754 Effect.gen(function* () {
755 const values = yield* Ref.updateAndGet(attempts, (values) => [...values, config]);
756 if (values.length === 1)
757 return yield* new Persistence.ConnectionPersistenceError({
758 operation: "save-server-config",
759 message: "test failure",
760 });
761 }),
762 );
763 yield* h.send(snapshotEvent(CONFIG));
764 yield* TestClock.adjust("500 millis");
765 yield* h.send({ version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } });
766 yield* TestClock.adjust("10 seconds");
767 }),
768 );
769 expect(yield* Ref.get(attempts)).toEqual([CONFIG, CONFIG]);
770 }),
771 );
772
773 it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
774 expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
775 expect(
776 isLegacyUpdateHandoffLoss(
777 Cause.fail(
778 new RpcClientError.RpcClientError({
779 reason: new Socket.SocketCloseError({ code: 1006 }),
780 }),
781 ),
782 ),
783 ).toBe(true);
784 expect(
785 isLegacyUpdateHandoffLoss(
786 Cause.fail(
787 new RpcClientError.RpcClientError({
788 reason: new Socket.SocketOpenError({
789 kind: "Unknown",
790 cause: new Error("connection refused"),
791 }),
792 }),
793 ),
794 ),
795 ).toBe(false);
796 expect(
797 isLegacyUpdateHandoffLoss(
798 Cause.fail(
799 new RpcClientError.RpcClientError({
800 reason: new RpcClientError.RpcClientDefect({
801 message: "incompatible protocol",
802 cause: new Error("invalid response"),
803 }),
804 }),
805 ),
806 ),
807 ).toBe(false);
808 expect(isLegacyUpdateHandoffLoss(Cause.fail(new Error("Install failed.")))).toBe(false);
809 });
810
811 it.effect("resumes after the progress stream disconnects following completion", () => {
812 const result = {
813 targetVersion: "0.0.31",
814 method: "respawn" as const,
815 };
816 const disconnect = new RpcClientError.RpcClientError({
817 reason: new Socket.SocketCloseError({ code: 1006 }),
818 });
819
820 return Effect.gen(function* () {
821 const resumed = yield* resolveServerUpdateProgressResult(
822 result.targetVersion,
823 Option.some(result),
824 Exit.fail(disconnect),
825 );
826 expect(resumed).toEqual(result);
827 });
828 });
829
830 it("projects streamed update milestones into the shared operation state", () => {
831 expect(
832 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
833 type: "progress",
834 stage: "installing",
835 }),
836 ).toEqual({
837 status: "running",
838 stage: "installing",
839 fromVersion: "0.0.30",
840 targetVersion: "0.0.31",
841 });
842 expect(
843 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
844 type: "complete",
845 result: { targetVersion: "0.0.31", method: "respawn" },
846 }),
847 ).toEqual({
848 status: "running",
849 stage: "resuming",
850 fromVersion: "0.0.30",
851 targetVersion: "0.0.31",
852 });
853 expect(
854 serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
855 type: "complete",
856 result: { targetVersion: "0.0.31", method: "desktop-app", desktopUpdateToken: "token" },
857 }).stage,
858 ).toBe("installing");
859 });
860
861 it("keeps active update state and hides stale failures after a version change", () => {
862 const running = {
863 status: "running" as const,
864 stage: "resuming" as const,
865 fromVersion: "0.0.30",
866 targetVersion: "0.0.31",
867 };
868 const failed = {
869 status: "failed" as const,
870 stage: "installing" as const,
871 fromVersion: "0.0.30",
872 targetVersion: "0.0.31",
873 message: "Install failed.",
874 };
875
876 expect(serverUpdateStateForServerVersion(running, "0.0.31")).toBe(running);
877 expect(serverUpdateStateForServerVersion(failed, "0.0.30")).toBe(failed);
878 expect(serverUpdateStateForServerVersion(failed, null)).toBe(failed);
879 expect(serverUpdateStateForServerVersion(failed, "0.0.31")).toEqual({ status: "idle" });
880 });
881
882 it.effect("correlates launcher outcomes and fails immediately after rollback", () =>
883 Effect.gen(function* () {
884 const result = {
885 targetVersion: "0.0.31",
886 method: "boot-service" as const,
887 updateId: "update-1",
888 };
889 const ready = (status: "committed" | "rolled-back") =>
890 ({
891 version: 1 as const,
892 sequence: 1,
893 type: "ready" as const,
894 payload: {
895 at: "2026-08-01T00:00:00.000Z",
896 environment: { serverVersion: status === "committed" ? "0.0.31" : "0.0.30" },
897 updateOutcome: {
898 id: "update-1",
899 fromVersion: "0.0.30",
900 targetVersion: "0.0.31",
901 status,
902 ...(status === "rolled-back" ? { reason: "prepared-timeout" } : {}),
903 },
904 },
905 }) as Parameters<typeof matchesServerUpdateReadyEvent>[1];
906
907 expect(matchesServerUpdateReadyEvent(result, ready("committed"))).toBe(true);
908 yield* validateServerUpdateReadyEvent(result, ready("committed"));
909 const rollback = yield* Effect.flip(
910 validateServerUpdateReadyEvent(result, ready("rolled-back")),
911 );
912 expect(rollback.message).toBe("prepared-timeout");
913 const foreign = ready("rolled-back");
914 const foreignRollback = yield* Effect.flip(
915 validateServerUpdateReadyEvent(result, {
916 ...foreign,
917 payload: {
918 ...foreign.payload,
919 updateOutcome: { ...foreign.payload.updateOutcome!, id: "manual-1" },
920 },
921 }),
922 );
923 expect(foreignRollback).toMatchObject({
924 status: "failed",
925 reason: "The service launcher resumed without committing the requested server version.",
926 });
927 }),
928 );
929
930 it("requires tokenless desktop updates to reach the target version", () => {
931 const ready = (serverVersion: string) =>
932 ({
933 version: 1 as const,
934 sequence: 1,
935 type: "ready" as const,
936 payload: {
937 at: "2026-09-01T00:00:00.000Z",
938 environment: { serverVersion },
939 },
940 }) as Parameters<typeof matchesServerUpdateResumeEvent>[1];
941
942 expect(
943 matchesServerUpdateResumeEvent(
944 { targetVersion: "0.0.31", method: "desktop-app" },
945 ready("0.0.30"),
946 ),
947 ).toBe(false);
948 expect(
949 matchesServerUpdateResumeEvent(
950 {
951 targetVersion: "0.0.31",
952 method: "desktop-app",
953 desktopUpdateToken: "update-1",
954 },
955 ready("0.0.30"),
956 ),
957 ).toBe(true);
958 });
959
960 it("keeps published themes across a reconnect snapshot", () => {
961 const themes = [
962 {
963 id: "nightfall",
964 name: "Nightfall",
965 appearance: "dark",
966 canvas: "#1a1b26",
967 accent: "#7aa2f7",
968 },
969 ] as const;
970
971 const withThemes = applyServerConfigProjection(
972 applyServerConfigProjection(Option.none(), { version: 1, type: "snapshot", config: CONFIG }),
973 { version: 1, type: "environmentThemesUpdated", payload: { themes } },
974 );
975 expect(Option.getOrThrow(withThemes).config.environmentThemes).toEqual(themes);
976
977 const afterReconnect = applyServerConfigProjection(withThemes, {
978 version: 1,
979 type: "snapshot",
980 config: CONFIG,
981 });
982 expect(Option.getOrThrow(afterReconnect).config.environmentThemes).toEqual(themes);
983 });
984
985 it("keeps a current welcome on ready and rejects a buffered welcome from the old session", () => {
986 const firstSession = session({} as WsRpcProtocolClient);
987 const secondSession = session({} as WsRpcProtocolClient);
988 const welcome = {
989 environment: {} as ServerLifecycleWelcomePayload["environment"],
990 cwd: "/repo",
991 projectName: "repo",
992 } as ServerLifecycleWelcomePayload;
993 const initial = {
994 currentSession: firstSession,
995 welcomeSession: firstSession,
996 welcome: null,
997 };
998 const afterWelcome = applyServerWelcomeEvent(initial, firstSession, {
999 type: "welcome",
1000 payload: welcome,
1001 });
1002 const afterReady = applyServerWelcomeEvent(afterWelcome, firstSession, {
1003 type: "ready",
1004 payload: {},
1005 });
1006 const afterSwitch = { ...afterReady, currentSession: secondSession };
1007 const afterBufferedOldWelcome = applyServerWelcomeEvent(afterSwitch, firstSession, {
1008 type: "welcome",
1009 payload: { ...welcome, cwd: "/stale" },
1010 });
1011
1012 expect(afterReady).toBe(afterWelcome);
1013 expect(resolveServerWelcomeState(afterReady)).toBe(welcome);
1014 expect(afterBufferedOldWelcome).toBe(afterSwitch);
1015 expect(resolveServerWelcomeState(afterBufferedOldWelcome)).toBeNull();
1016 });
1017
1018 it.effect("checks the authoritative session before accepting a buffered welcome", () =>
1019 Effect.gen(function* () {
1020 const firstEvents = yield* Queue.unbounded<{
1021 readonly type: "welcome" | "ready";
1022 readonly payload: unknown;
1023 }>();
1024 const firstSubscribed = yield* Deferred.make<void>();
1025 const firstClient = {
1026 [WS_METHODS.subscribeServerLifecycle]: () =>
1027 Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe(
1028 Stream.drain,
1029 Stream.concat(Stream.fromQueue(firstEvents)),
1030 ),
1031 } as unknown as WsRpcProtocolClient;
1032 const firstSession = session(firstClient);
1033 const secondSession = session({} as WsRpcProtocolClient);
1034 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
1035 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1036 target: TARGET,
1037 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1038 session: supervisorSession,
1039 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1040 connect: Effect.void,
1041 disconnect: Effect.void,
1042 retryNow: Effect.void,
1043 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1044 const staleWelcome = {
1045 environment: {} as ServerLifecycleWelcomePayload["environment"],
1046 cwd: "/stale",
1047 projectName: "stale",
1048 } as ServerLifecycleWelcomePayload;
1049
1050 yield* Effect.scoped(
1051 Effect.gen(function* () {
1052 const state = yield* makeEnvironmentServerWelcomeState().pipe(
1053 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1054 );
1055 yield* Deferred.await(firstSubscribed);
1056
1057 supervisorSession.value = Option.some(secondSession);
1058 const handled = yield* SubscriptionRef.changes(state).pipe(
1059 Stream.filter(
1060 (value) => value.currentSession === secondSession || value.welcome === staleWelcome,
1061 ),
1062 Stream.runHead,
1063 Effect.map(Option.getOrThrow),
1064 Effect.forkChild,
1065 );
1066 yield* Queue.offer(firstEvents, { type: "welcome", payload: staleWelcome });
1067
1068 const next = yield* Fiber.join(handled);
1069 expect(next.currentSession).toBe(secondSession);
1070 expect(resolveServerWelcomeState(next)).toBeNull();
1071 }),
1072 );
1073 }),
1074 );
1075
1076 it.effect("reads the authoritative session after waiting for the welcome state lock", () =>
1077 Effect.gen(function* () {
1078 const firstSubscribed = yield* Deferred.make<void>();
1079 const firstClient = {
1080 [WS_METHODS.subscribeServerLifecycle]: () =>
1081 Stream.fromEffect(Deferred.succeed(firstSubscribed, undefined)).pipe(Stream.drain),
1082 } as unknown as WsRpcProtocolClient;
1083 const secondClient = {
1084 [WS_METHODS.subscribeServerLifecycle]: () => Stream.never,
1085 } as unknown as WsRpcProtocolClient;
1086 const firstSession = session(firstClient);
1087 const secondSession = session(secondClient);
1088 const thirdSession = session({} as WsRpcProtocolClient);
1089 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
1090 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1091 target: TARGET,
1092 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1093 session: supervisorSession,
1094 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1095 connect: Effect.void,
1096 disconnect: Effect.void,
1097 retryNow: Effect.void,
1098 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1099
1100 yield* Effect.scoped(
1101 Effect.gen(function* () {
1102 const state = yield* makeEnvironmentServerWelcomeState().pipe(
1103 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1104 );
1105 yield* Deferred.await(firstSubscribed);
1106 const changed = yield* SubscriptionRef.changes(state).pipe(
1107 Stream.filter((value) => value.currentSession !== firstSession),
1108 Stream.runHead,
1109 Effect.map(Option.getOrThrow),
1110 Effect.forkChild,
1111 );
1112
1113 yield* state.semaphore.withPermit(
1114 Effect.gen(function* () {
1115 yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession));
1116 yield* Effect.yieldNow;
1117 yield* Effect.yieldNow;
1118 yield* Effect.yieldNow;
1119 supervisorSession.value = Option.some(thirdSession);
1120 }),
1121 );
1122
1123 expect((yield* Fiber.join(changed)).currentSession).toBe(thirdSession);
1124 }),
1125 );
1126 }),
1127 );
1128
1129 it.effect("clears a welcome until the reconnected session sends its own", () =>
1130 Effect.gen(function* () {
1131 const firstEvents = yield* Queue.unbounded<{
1132 readonly type: "welcome" | "ready";
1133 readonly payload: unknown;
1134 }>();
1135 const secondEvents = yield* Queue.unbounded<{
1136 readonly type: "welcome" | "ready";
1137 readonly payload: unknown;
1138 }>();
1139 const firstClient = {
1140 [WS_METHODS.subscribeServerLifecycle]: () => Stream.fromQueue(firstEvents),
1141 } as unknown as WsRpcProtocolClient;
1142 const secondClient = {
1143 [WS_METHODS.subscribeServerLifecycle]: () => Stream.fromQueue(secondEvents),
1144 } as unknown as WsRpcProtocolClient;
1145 const firstSession = session(firstClient);
1146 const secondSession = session(secondClient);
1147 const supervisorSession = yield* SubscriptionRef.make(Option.some(firstSession));
1148 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1149 target: TARGET,
1150 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1151 session: supervisorSession,
1152 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1153 connect: Effect.void,
1154 disconnect: Effect.void,
1155 retryNow: Effect.void,
1156 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1157 const firstWelcome = {
1158 environment: {} as ServerLifecycleWelcomePayload["environment"],
1159 cwd: "/first",
1160 projectName: "first",
1161 } as ServerLifecycleWelcomePayload;
1162 const secondWelcome = {
1163 environment: {} as ServerLifecycleWelcomePayload["environment"],
1164 cwd: "/second",
1165 projectName: "second",
1166 } as ServerLifecycleWelcomePayload;
1167
1168 yield* Effect.scoped(
1169 Effect.gen(function* () {
1170 const state = yield* makeEnvironmentServerWelcomeState().pipe(
1171 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1172 );
1173 const nextResolved = (
1174 predicate: (value: ServerLifecycleWelcomePayload | null) => boolean,
1175 ) =>
1176 SubscriptionRef.changes(state).pipe(
1177 Stream.map(resolveServerWelcomeState),
1178 Stream.filter(predicate),
1179 Stream.runHead,
1180 Effect.map(Option.getOrThrow),
1181 );
1182
1183 const first = yield* nextResolved((value) => value === firstWelcome).pipe(
1184 Effect.forkChild,
1185 );
1186 yield* Queue.offer(firstEvents, { type: "welcome", payload: firstWelcome });
1187 expect(yield* Fiber.join(first)).toBe(firstWelcome);
1188
1189 const cleared = yield* nextResolved((value) => value === null).pipe(Effect.forkChild);
1190 yield* SubscriptionRef.set(supervisorSession, Option.some(secondSession));
1191 expect(yield* Fiber.join(cleared)).toBeNull();
1192 expect(resolveServerWelcomeState(yield* SubscriptionRef.get(state))).toBeNull();
1193
1194 const second = yield* nextResolved((value) => value === secondWelcome).pipe(
1195 Effect.forkChild,
1196 );
1197 yield* Queue.offer(secondEvents, { type: "welcome", payload: secondWelcome });
1198 expect(yield* Fiber.join(second)).toBe(secondWelcome);
1199 }),
1200 );
1201 }),
1202 );
1203
1204 it("prefers an active session config over cache until a live event arrives", () => {
1205 const config = (source: string, serverVersion: string) =>
1206 ({
1207 ...CONFIG,
1208 environment: { serverVersion },
1209 settings: { source },
1210 }) as unknown as ServerConfig;
1211 const cached = config("cache", "0.0.29");
1212 const staleLive = config("stale-live", "0.0.29");
1213 const initial = config("session", "0.0.30");
1214 const live = config("live", "0.0.30");
1215
1216 expect(
1217 resolveServerConfigValue(
1218 {
1219 config: cached,
1220 latestEvent: snapshotEvent(cached),
1221 source: "cache",
1222 },
1223 initial,
1224 ),
1225 ).toBe(initial);
1226 expect(
1227 resolveServerConfigValue(
1228 {
1229 config: staleLive,
1230 latestEvent: snapshotEvent(staleLive),
1231 source: "live",
1232 },
1233 initial,
1234 ),
1235 ).toBe(initial);
1236 expect(
1237 resolveServerConfigValue(
1238 {
1239 config: live,
1240 latestEvent: snapshotEvent(live),
1241 source: "live",
1242 },
1243 initial,
1244 ),
1245 ).toBe(live);
1246 });
1247
1248 it("merges fetched workspace snapshots only from servers that omit them", () => {
1249 const claude = ProviderInstanceId.make("claudeAgent");
1250 const codex = ProviderInstanceId.make("codex");
1251 const snapshot = (cwd: string, command: string) => ({
1252 cwd,
1253 checkedAt: "2026-10-25T00:00:00.000Z",
1254 slashCommands: [{ name: command }],
1255 skills: [],
1256 });
1257 const provider = (
1258 instanceId: ProviderInstanceId,
1259 workspaceSnapshots?: ReadonlyArray<ReturnType<typeof snapshot>>,
1260 slashCommands: ReadonlyArray<{ readonly name: string }> = [],
1261 ) =>
1262 ({
1263 instanceId,
1264 enabled: true,
1265 slashCommands,
1266 skills: [],
1267 ...(workspaceSnapshots ? { workspaceSnapshots } : {}),
1268 }) as unknown as ServerConfig["providers"][number];
1269 const configWith = (onDemand: boolean, providers: ServerConfig["providers"]) =>
1270 ({
1271 ...CONFIG,
1272 environment: { capabilities: { providerWorkspaceSnapshotsOnDemand: onDemand } },
1273 providers,
1274 }) as unknown as ServerConfig;
1275 const claudeA = snapshot("/a", "claude");
1276 const record = (
1277 current: Parameters<typeof recordFetchedWorkspaceSnapshot>[0],
1278 instanceId: ProviderInstanceId,
1279 fresh: boolean,
1280 reply: ServerConfig["providers"],
1281 ) =>
1282 recordFetchedWorkspaceSnapshot(
1283 current,
1284 { instanceId, cwd: "/a", fresh },
1285 reply,
1286 provider(instanceId),
1287 );
1288
1289 let fetched = record([], claude, false, [provider(claude, [claudeA])]);
1290 fetched = record(fetched, codex, false, [provider(codex, [snapshot("/a", "codex")])]);
1291 const merged = withFetchedWorkspaceSnapshots(
1292 configWith(true, [provider(claude), provider(codex)]),
1293 fetched,
1294 );
1295 expect(merged.providers[0]?.workspaceSnapshots).toEqual([claudeA]);
1296 // An unchanged answer keeps the cache, so config readers do not re-render.
1297 expect(
1298 record(fetched, claude, false, [
1299 provider(claude, [JSON.parse(JSON.stringify(claudeA)) as typeof claudeA]),
1300 ]),
1301 ).toBe(fetched);
1302
1303 // Health checks and usage updates leave the snapshot in place.
1304 expect(
1305 withFetchedWorkspaceSnapshots(
1306 configWith(true, [
1307 { ...provider(claude), checkedAt: "2026-10-25T00:09:00.000Z", usageLimits: {} },
1308 ] as unknown as ServerConfig["providers"]),
1309 fetched,
1310 ).providers[0]?.workspaceSnapshots,
1311 ).toEqual([claudeA]);
1312
1313 // New provider-wide commands, such as a live session's, retire the old snapshot.
1314 expect(
1315 withFetchedWorkspaceSnapshots(
1316 configWith(true, [provider(claude, undefined, [{ name: "live" }])]),
1317 fetched,
1318 ).providers[0]?.workspaceSnapshots,
1319 ).toBeUndefined();
1320
1321 // A server rescan that changed the skills retires the snapshot fetched before it.
1322 expect(
1323 withFetchedWorkspaceSnapshots(
1324 configWith(true, [
1325 { ...provider(claude), workspaceRescannedAt: "2026-10-25T00:09:00.000Z" },
1326 ] as unknown as ServerConfig["providers"]),
1327 fetched,
1328 ).providers[0]?.workspaceSnapshots,
1329 ).toBeUndefined();
1330
1331 // A catalog digest stands for the lists: loading them keeps the snapshot, a new digest retires it.
1332 const digested = (catalogDigest: string, slashCommands: ReadonlyArray<{ name: string }> = []) =>
1333 ({ ...provider(claude, undefined, slashCommands), catalogDigest }) as ReturnType<
1334 typeof provider
1335 >;
1336 const fetchedByDigest = recordFetchedWorkspaceSnapshot(
1337 [],
1338 { instanceId: claude, cwd: "/a", fresh: false },
1339 [provider(claude, [claudeA])],
1340 digested("d1"),
1341 );
1342 const snapshotsFor = (current: ReturnType<typeof provider>) =>
1343 withFetchedWorkspaceSnapshots(configWith(true, [current]), fetchedByDigest).providers[0]
1344 ?.workspaceSnapshots;
1345 expect(snapshotsFor(digested("d1", [{ name: "loaded" }]))).toEqual([claudeA]);
1346 expect(snapshotsFor(digested("d2"))).toBeUndefined();
1347
1348 // Older servers send every snapshot and every drop; their config stands.
1349 const legacy = configWith(false, [provider(claude)]);
1350 expect(withFetchedWorkspaceSnapshots(legacy, fetched)).toBe(legacy);
1351
1352 // A fresh scan drops the cwd's other provider snapshots, as the server does.
1353 expect(record(fetched, claude, true, [])).toEqual([]);
1354 });
1355
1356 it.effect("starts from cached configuration and persists the live projection", () =>
1357 Effect.gen(function* () {
1358 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
1359 const client = {
1360 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
1361 } as unknown as WsRpcProtocolClient;
1362 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1363 target: TARGET,
1364 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1365 session: yield* SubscriptionRef.make(Option.some(session(client))),
1366 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1367 connect: Effect.void,
1368 disconnect: Effect.void,
1369 retryNow: Effect.void,
1370 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1371 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
1372 const cache = Persistence.EnvironmentCacheStore.of({
1373 loadShell: () => Effect.succeedNone,
1374 saveShell: () => Effect.void,
1375 loadThread: () => Effect.succeedNone,
1376 saveThread: () => Effect.void,
1377 removeThread: () => Effect.void,
1378 loadServerConfig: () => Effect.succeedSome(CONFIG),
1379 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
1380 loadVcsRefs: () => Effect.succeedNone,
1381 saveVcsRefs: () => Effect.void,
1382 removeVcsRefs: () => Effect.void,
1383 clearVcsRefs: () => Effect.void,
1384 clear: () => Effect.void,
1385 });
1386
1387 yield* Effect.scoped(
1388 Effect.gen(function* () {
1389 const state = yield* makeEnvironmentServerConfigState({}).pipe(
1390 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1391 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1392 );
1393 expect(Option.getOrThrow(yield* SubscriptionRef.get(state)).config).toBe(CONFIG);
1394
1395 const providers: ServerConfig["providers"] = [];
1396 yield* Queue.offer(events, {
1397 version: 1,
1398 type: "providerStatuses",
1399 payload: { providers },
1400 });
1401 const projected = yield* SubscriptionRef.changes(state).pipe(
1402 Stream.filter((value) =>
1403 Option.match(value, {
1404 onNone: () => false,
1405 onSome: (projection) => projection.latestEvent.type === "providerStatuses",
1406 }),
1407 ),
1408 Stream.runHead,
1409 );
1410 expect(Option.getOrThrow(Option.getOrThrow(projected)).config.providers).toEqual(
1411 providers,
1412 );
1413 }),
1414 );
1415
1416 expect((yield* Queue.take(savedConfigs)).providers).toEqual([]);
1417 }),
1418 );
1419
1420 it.effect("shows a reported stall but never caches it", () =>
1421 Effect.gen(function* () {
1422 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
1423 const client = {
1424 [WS_METHODS.subscribeServerConfig]: () => Stream.fromQueue(events),
1425 } as unknown as WsRpcProtocolClient;
1426 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1427 target: TARGET,
1428 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1429 session: yield* SubscriptionRef.make(Option.some(session(client))),
1430 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1431 connect: Effect.void,
1432 disconnect: Effect.void,
1433 retryNow: Effect.void,
1434 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1435 const savedConfigs = yield* Queue.unbounded<ServerConfig>();
1436 const cache = Persistence.EnvironmentCacheStore.of({
1437 loadShell: () => Effect.succeedNone,
1438 saveShell: () => Effect.void,
1439 loadThread: () => Effect.succeedNone,
1440 saveThread: () => Effect.void,
1441 removeThread: () => Effect.void,
1442 loadServerConfig: () => Effect.succeedSome(CONFIG),
1443 saveServerConfig: (_environmentId, config) => Queue.offer(savedConfigs, config),
1444 loadVcsRefs: () => Effect.succeedNone,
1445 saveVcsRefs: () => Effect.void,
1446 removeVcsRefs: () => Effect.void,
1447 clearVcsRefs: () => Effect.void,
1448 clear: () => Effect.void,
1449 });
1450
1451 yield* Effect.scoped(
1452 Effect.gen(function* () {
1453 const state = yield* makeEnvironmentServerConfigState({}).pipe(
1454 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1455 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1456 );
1457 expect(Option.getOrThrow(yield* SubscriptionRef.get(state)).config).toBe(CONFIG);
1458
1459 const lastEventLoopStall = {
1460 detectedAt: "2026-10-20T07:50:37.633Z",
1461 durationMs: 12_422,
1462 loadAverage: 219.4,
1463 cpuCount: 18,
1464 };
1465 yield* Queue.offer(events, {
1466 version: 1,
1467 type: "snapshot",
1468 config: { ...CONFIG, lastEventLoopStall },
1469 });
1470 const projected = yield* SubscriptionRef.changes(state).pipe(
1471 Stream.filter((value) =>
1472 Option.match(value, {
1473 onNone: () => false,
1474 onSome: (projection) => projection.source === "live",
1475 }),
1476 ),
1477 Stream.runHead,
1478 );
1479 expect(Option.getOrThrow(Option.getOrThrow(projected)).config.lastEventLoopStall).toEqual(
1480 lastEventLoopStall,
1481 );
1482 }),
1483 );
1484
1485 // Cached, it would read as a fresh freeze on the next launch.
1486 expect(yield* Queue.take(savedConfigs)).not.toHaveProperty("lastEventLoopStall");
1487 }),
1488 );
1489 });
1490
1491 describe("launcher update resume", () => {
1492 const UPDATE_CONFIG = {
1493 ...CONFIG,
1494 environment: {
1495 serverVersion: "0.0.30",
1496 capabilities: { serverSelfUpdate: "boot-service", serverSelfUpdateProgress: true },
1497 },
1498 } as unknown as ServerConfig;
1499
1500 const ready = (at: string, serverVersion: string, updateOutcome?: ServerSelfUpdateOutcome) =>
1501 ({
1502 version: 1,
1503 sequence: 1,
1504 type: "ready",
1505 payload: { at, environment: { serverVersion }, ...(updateOutcome ? { updateOutcome } : {}) },
1506 }) as ServerLifecycleStreamEvent;
1507 const after = (delay: Duration.Input, event: ServerLifecycleStreamEvent) =>
1508 Stream.fromEffect(Effect.as(Effect.sleep(delay), event));
1509 const committed = (id: string, fromVersion: string, targetVersion: string) => ({
1510 id,
1511 fromVersion,
1512 targetVersion,
1513 status: "committed" as const,
1514 });
1515 const ACCEPTING = ready("2026-08-01T00:00:00.000Z", "0.0.30");
1516 const REPLACEMENT = ready("2026-08-01T00:05:00.000Z", "0.0.31");
1517
1518 // Lifecycle subscriptions opened before the update is acknowledged reach the accepting
1519 // process; later ones reach whatever the host has become.
1520 const launchUpdate = Effect.fn("ServerUpdateTest.launchUpdate")(function* (host: {
1521 readonly accepting: Stream.Stream<ServerLifecycleStreamEvent>;
1522 readonly resumed: Stream.Stream<ServerLifecycleStreamEvent>;
1523 readonly reconnectAfterBaseline?: boolean;
1524 }) {
1525 const started = yield* Deferred.make<void>();
1526 const resumeSubscribed = yield* Deferred.make<void>();
1527 let acknowledged = false;
1528 const client = {
1529 [WS_METHODS.subscribeServerConfig]: () => Stream.never,
1530 [WS_METHODS.serverUpdateServerWithProgress]: () =>
1531 Stream.fromEffect(
1532 Deferred.succeed(started, undefined).pipe(
1533 Effect.andThen(
1534 Effect.sync(() => {
1535 acknowledged = true;
1536 return {
1537 type: "complete" as const,
1538 result: {
1539 targetVersion: "0.0.31",
1540 method: "boot-service" as const,
1541 updateId: "update-1",
1542 },
1543 };
1544 }),
1545 ),
1546 ),
1547 ),
1548 [WS_METHODS.subscribeServerLifecycle]: () => {
1549 const events = acknowledged
1550 ? Deferred.succeed(resumeSubscribed, undefined).pipe(Effect.as(host.resumed))
1551 : Effect.succeed(host.accepting);
1552 const reconnect =
1553 !acknowledged && host.reconnectAfterBaseline === true
1554 ? SubscriptionRef.set(supervisor.session, Option.some(updateSession()))
1555 : Effect.void;
1556 return Stream.unwrap(
1557 Deferred.succeed(started, undefined).pipe(Effect.andThen(events)),
1558 ).pipe(Stream.concat(Stream.never), Stream.ensuring(reconnect));
1559 },
1560 } as unknown as WsRpcProtocolClient;
1561 const updateSession = (): RpcSession => ({
1562 ...session(client),
1563 initialConfig: Effect.succeed(UPDATE_CONFIG),
1564 });
1565 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1566 target: TARGET,
1567 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1568 session: yield* SubscriptionRef.make(Option.some(updateSession())),
1569 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1570 connect: Effect.void,
1571 disconnect: Effect.void,
1572 retryNow: Effect.void,
1573 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1574 type Environments = EnvironmentRegistry.EnvironmentRegistry["Service"];
1575 const run: Environments["run"] = (_environmentId, effect) =>
1576 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
1577 const runStream: Environments["runStream"] = (_environmentId, stream) =>
1578 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
1579 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
1580 run,
1581 runStream,
1582 followStream: runStream,
1583 stateChanges: () => Stream.never,
1584 retryNow: () => Effect.void,
1585 } as unknown as Environments);
1586 const cache = Persistence.EnvironmentCacheStore.of({
1587 loadShell: () => Effect.succeedNone,
1588 saveShell: () => Effect.void,
1589 loadThread: () => Effect.succeedNone,
1590 saveThread: () => Effect.void,
1591 removeThread: () => Effect.void,
1592 loadServerConfig: () => Effect.succeedNone,
1593 saveServerConfig: () => Effect.void,
1594 loadVcsRefs: () => Effect.succeedNone,
1595 saveVcsRefs: () => Effect.void,
1596 removeVcsRefs: () => Effect.void,
1597 clearVcsRefs: () => Effect.void,
1598 clear: () => Effect.void,
1599 });
1600 // Share the test clock so the command's timers and the host's restart run on TestClock.
1601 const runtime = Atom.runtime(
1602 Layer.mergeAll(
1603 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments),
1604 Layer.succeed(Persistence.EnvironmentCacheStore, cache),
1605 Layer.succeed(Clock.Clock, yield* Clock.Clock),
1606 Layer.succeed(Scheduler.Scheduler, yield* Scheduler.Scheduler),
1607 ),
1608 );
1609 const initialConfigValueAtom = Atom.make(UPDATE_CONFIG);
1610 const atoms = createServerEnvironmentAtoms(runtime, {
1611 initialConfigValueAtom: () => initialConfigValueAtom,
1612 });
1613 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
1614 Effect.sync(() => registry.dispose()),
1615 );
1616 const updateStateAtom = serverUpdateStateAtom(TARGET.environmentId);
1617 yield* AtomRegistry.mount(registry, updateStateAtom);
1618
1619 yield* Effect.promise((signal) =>
1620 runAtomCommand(
1621 registry,
1622 atoms.updateServer,
1623 { environmentId: TARGET.environmentId, input: { targetVersion: "0.0.31" } },
1624 { reportFailure: false, reportDefect: false, signal },
1625 ),
1626 ).pipe(Effect.forkScoped);
1627 return {
1628 // The host saw its first call: the update request or a lifecycle subscription.
1629 started: Deferred.await(started),
1630 resumeSubscribed: Deferred.await(resumeSubscribed),
1631 state: () => registry.get(updateStateAtom),
1632 };
1633 });
1634
1635 const UNCOMMITTED_RESUME = {
1636 status: "failed",
1637 stage: "resuming",
1638 fromVersion: "0.0.30",
1639 targetVersion: "0.0.31",
1640 message: "The service launcher resumed without committing the requested server version.",
1641 };
1642
1643 it.effect("fails promptly when a server the launcher did not start comes back", () =>
1644 Effect.gen(function* () {
1645 const update = yield* launchUpdate({
1646 accepting: Stream.make(ACCEPTING),
1647 resumed: after("1 second", ACCEPTING).pipe(Stream.concat(after("1 minute", REPLACEMENT))),
1648 });
1649 yield* update.resumeSubscribed;
1650
1651 yield* TestClock.adjust("1 second");
1652 expect(update.state()).toMatchObject({ status: "running", stage: "resuming" });
1653 yield* TestClock.adjust("1 minute");
1654 expect(update.state()).toEqual(UNCOMMITTED_RESUME);
1655 }),
1656 );
1657
1658 it.effect(
1659 "fails promptly when the accepting server's replay arrives after a quick acknowledgement",
1660 () =>
1661 Effect.gen(function* () {
1662 const update = yield* launchUpdate({
1663 accepting: after("3 seconds", ACCEPTING),
1664 resumed: after("1 second", REPLACEMENT),
1665 });
1666 yield* update.started;
1667 yield* TestClock.adjust("3 seconds");
1668 yield* update.resumeSubscribed;
1669
1670 yield* TestClock.adjust("1 minute");
1671 expect(update.state()).toEqual(UNCOMMITTED_RESUME);
1672 }),
1673 );
1674
1675 it.effect(
1676 "waits for this update's outcome when a reconnect lands between the baseline and the request",
1677 () =>
1678 Effect.gen(function* () {
1679 const update = yield* launchUpdate({
1680 reconnectAfterBaseline: true,
1681 accepting: Stream.make(ACCEPTING),
1682 // The process that accepted the update over the new session replays its own ready first.
1683 resumed: after("1 second", ready("2026-08-01T00:01:00.000Z", "0.0.30")).pipe(
1684 Stream.concat(
1685 after(
1686 "1 minute",
1687 ready(
1688 "2026-08-01T00:05:00.000Z",
1689 "0.0.31",
1690 committed("update-1", "0.0.30", "0.0.31"),
1691 ),
1692 ),
1693 ),
1694 ),
1695 });
1696 yield* update.resumeSubscribed;
1697
1698 yield* TestClock.adjust("1 second");
1699 expect(update.state()).toMatchObject({ status: "running", stage: "resuming" });
1700 yield* TestClock.adjust("1 minute");
1701 expect(update.state()).toMatchObject({ status: "idle" });
1702 }),
1703 );
1704
1705 it.effect(
1706 "sends the update without a baseline when the accepting server never replays ready",
1707 () =>
1708 Effect.gen(function* () {
1709 const update = yield* launchUpdate({
1710 accepting: Stream.never,
1711 resumed: after(
1712 "1 second",
1713 ready("2026-08-01T00:05:00.000Z", "0.0.31", committed("update-1", "0.0.30", "0.0.31")),
1714 ),
1715 });
1716 yield* update.started;
1717
1718 yield* TestClock.adjust("5 seconds");
1719 yield* TestClock.adjust("1 second");
1720 expect(update.state()).toMatchObject({ status: "idle" });
1721 }),
1722 );
1723 });
1724
1725 describe("provider setup commands", () => {
1726 it.effect("starts installs for two instances in one environment separately", () =>
1727 Effect.gen(function* () {
1728 const requested = yield* Queue.unbounded<ProviderInstanceId>();
1729 const release = yield* Deferred.make<void>();
1730 const installState = (driver: string): ProviderInstallState => ({
1731 driver: ProviderDriverKind.make(driver),
1732 operationId: null,
1733 phase: "downloading",
1734 downloadedBytes: 0,
1735 totalBytes: null,
1736 version: null,
1737 installedVersion: null,
1738 canRemove: false,
1739 message: null,
1740 });
1741 const client = {
1742 [WS_METHODS.providerInstallStart]: ({ instanceId }: ProviderSetupInput) =>
1743 Queue.offer(requested, instanceId).pipe(
1744 Effect.andThen(Deferred.await(release)),
1745 Effect.as(installState(instanceId)),
1746 ),
1747 } as unknown as WsRpcProtocolClient;
1748 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1749 target: TARGET,
1750 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1751 session: yield* SubscriptionRef.make(Option.some(session(client))),
1752 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1753 connect: Effect.void,
1754 disconnect: Effect.void,
1755 retryNow: Effect.void,
1756 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1757 const runtime = Atom.runtime(
1758 Layer.merge(
1759 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
1760 run: (_environmentId, effect) =>
1761 Effect.provideService(
1762 effect,
1763 EnvironmentSupervisor.EnvironmentSupervisor,
1764 supervisor,
1765 ),
1766 } as EnvironmentRegistry.EnvironmentRegistry["Service"]),
1767 Layer.succeed(
1768 Persistence.EnvironmentCacheStore,
1769 {} as Persistence.EnvironmentCacheStore["Service"],
1770 ),
1771 ),
1772 );
1773 const atoms = createServerEnvironmentAtoms(runtime, {
1774 initialConfigValueAtom: () => Atom.make(CONFIG),
1775 });
1776 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
1777 Effect.sync(() => registry.dispose()),
1778 );
1779 const install = (instanceId: string) =>
1780 Effect.forkChild(
1781 Effect.exit(
1782 atoms.startProviderInstall.run(registry, {
1783 environmentId: TARGET.environmentId,
1784 input: { instanceId: ProviderInstanceId.make(instanceId) },
1785 }),
1786 ),
1787 { startImmediately: true },
1788 );
1789
1790 const codex = yield* install("codex");
1791 expect(yield* Queue.take(requested)).toBe("codex");
1792 const duplicateCodex = yield* install("codex");
1793 const antigravity = yield* install("antigravity");
1794 yield* Deferred.succeed(release, undefined);
1795
1796 expect(yield* Fiber.join(codex)).toMatchObject({
1797 _tag: "Success",
1798 value: { driver: "codex" },
1799 });
1800 expect(yield* Fiber.join(duplicateCodex)).toEqual(yield* Fiber.join(codex));
1801 expect(yield* Fiber.join(antigravity)).toMatchObject({
1802 _tag: "Success",
1803 value: { driver: "antigravity" },
1804 });
1805 expect(yield* Queue.takeAll(requested)).toEqual(["antigravity"]);
1806 }),
1807 );
1808
1809 it.effect("toggles a provider while another provider's update is still running", () =>
1810 Effect.gen(function* () {
1811 const updateStarted = yield* Deferred.make<void>();
1812 const settingsSaved = yield* Deferred.make<void>();
1813 const client = {
1814 [WS_METHODS.serverUpdateProvider]: () =>
1815 Deferred.succeed(updateStarted, undefined).pipe(Effect.andThen(Effect.never)),
1816 [WS_METHODS.serverUpdateSettings]: () =>
1817 Deferred.succeed(settingsSaved, undefined).pipe(Effect.as(CONFIG.settings)),
1818 } as unknown as WsRpcProtocolClient;
1819 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1820 target: TARGET,
1821 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1822 session: yield* SubscriptionRef.make(Option.some(session(client))),
1823 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1824 connect: Effect.void,
1825 disconnect: Effect.void,
1826 retryNow: Effect.void,
1827 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1828 const runtime = Atom.runtime(
1829 Layer.merge(
1830 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
1831 run: (_environmentId, effect) =>
1832 Effect.provideService(
1833 effect,
1834 EnvironmentSupervisor.EnvironmentSupervisor,
1835 supervisor,
1836 ),
1837 } as EnvironmentRegistry.EnvironmentRegistry["Service"]),
1838 Layer.succeed(
1839 Persistence.EnvironmentCacheStore,
1840 {} as Persistence.EnvironmentCacheStore["Service"],
1841 ),
1842 ),
1843 );
1844 const atoms = createServerEnvironmentAtoms(runtime, {
1845 initialConfigValueAtom: () => Atom.make(CONFIG),
1846 });
1847 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
1848 Effect.sync(() => registry.dispose()),
1849 );
1850
1851 yield* Effect.forkChild(
1852 atoms.updateProvider.run(registry, {
1853 environmentId: TARGET.environmentId,
1854 input: { provider: ProviderDriverKind.make("opencode") },
1855 }),
1856 { startImmediately: true },
1857 );
1858 yield* Deferred.await(updateStarted);
1859 yield* Effect.forkChild(
1860 atoms.mutateProviderInstance.run(registry, {
1861 environmentId: TARGET.environmentId,
1862 input: {
1863 patch: {},
1864 providerInstanceMutation: {
1865 operation: "upsert",
1866 instanceId: ProviderInstanceId.make("codex"),
1867 instance: { driver: ProviderDriverKind.make("codex"), enabled: false },
1868 },
1869 },
1870 }),
1871 { startImmediately: true },
1872 );
1873
1874 const saved = yield* Deferred.await(settingsSaved).pipe(
1875 Effect.as(true),
1876 Effect.timeoutOrElse({
1877 duration: Duration.seconds(1),
1878 orElse: () => Effect.succeed(false),
1879 }),
1880 Effect.forkChild,
1881 );
1882 yield* TestClock.adjust(Duration.seconds(1));
1883 expect(yield* Fiber.join(saved)).toBe(true);
1884 }),
1885 );
1886 });
1887
1888 describe("resource telemetry history", () => {
1889 it.effect.each([
1890 ["resourceTelemetryHistory", WS_METHODS.serverGetResourceTelemetryHistory],
1891 ["processResourceHistory", WS_METHODS.serverGetProcessResourceHistory],
1892 ] as const)(
1893 "%s refreshes an initially empty history while mounted and stops after unmount",
1894 ([atomKey, method]) =>
1895 Effect.gen(function* () {
1896 vi.useFakeTimers();
1897 try {
1898 yield* Effect.scoped(
1899 Effect.gen(function* () {
1900 let reads = 0;
1901 const client = {
1902 [method]: () =>
1903 Effect.sync(() => ({
1904 retainedSampleCount: reads++,
1905 })),
1906 } as unknown as WsRpcProtocolClient;
1907 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1908 target: TARGET,
1909 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
1910 ...AVAILABLE_CONNECTION_STATE,
1911 phase: "connected",
1912 }),
1913 session: yield* SubscriptionRef.make(Option.some(session(client))),
1914 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
1915 connect: Effect.void,
1916 disconnect: Effect.void,
1917 retryNow: Effect.void,
1918 });
1919 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
1920 run: (_id, effect) =>
1921 Effect.provideService(
1922 effect,
1923 EnvironmentSupervisor.EnvironmentSupervisor,
1924 supervisor,
1925 ),
1926 followStream: (_id, stream) =>
1927 Stream.provideService(
1928 stream,
1929 EnvironmentSupervisor.EnvironmentSupervisor,
1930 supervisor,
1931 ),
1932 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
1933 const runtime = Atom.runtime(
1934 Layer.merge(
1935 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments),
1936 Layer.succeed(Persistence.EnvironmentCacheStore, {
1937 loadServerConfig: () => Effect.succeedNone,
1938 } as unknown as Persistence.EnvironmentCacheStore["Service"]),
1939 ),
1940 );
1941 const atoms = createServerEnvironmentAtoms(runtime, {
1942 initialConfigValueAtom: () => Atom.make(CONFIG),
1943 });
1944 const registry = yield* Effect.acquireRelease(
1945 Effect.sync(AtomRegistry.make),
1946 (value) => Effect.sync(() => value.dispose()),
1947 );
1948 const history: Atom.Atom<
1949 AsyncResult.AsyncResult<{ readonly retainedSampleCount: number }, Error>
1950 > = atoms[atomKey]({
1951 environmentId: TARGET.environmentId,
1952 input: { windowMs: 900_000, bucketMs: 30_000 },
1953 });
1954 const unmount = registry.mount(history);
1955 const initial = yield* AtomRegistry.getResult(registry, history, {
1956 suspendOnWaiting: true,
1957 });
1958 expect(initial.retainedSampleCount).toBe(0);
1959 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(5_000));
1960 expect(reads).toBe(2);
1961 const updated = yield* AtomRegistry.getResult(registry, history, {
1962 suspendOnWaiting: true,
1963 });
1964 expect(updated.retainedSampleCount).toBe(1);
1965 unmount();
1966 yield* Effect.promise(() => vi.advanceTimersByTimeAsync(10_000));
1967 expect(reads).toBe(2);
1968 }),
1969 );
1970 } finally {
1971 vi.useRealTimers();
1972 }
1973 }),
1974 );
1975 });