Open History to see the last commit
1import {
2 type DesktopSshEnvironmentTarget,
3 EnvironmentId,
4 type OrchestrationShellSnapshot,
5} from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as Context from "effect/Context";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Ref from "effect/Ref";
15import * as Result from "effect/Result";
16import * as Scheduler from "effect/Scheduler";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20
21import * as ClientCapabilities from "../platform/capabilities.ts";
22import * as TokenStore from "../authorization/tokenStore.ts";
23import {
24 BearerConnectionCredential,
25 BearerConnectionProfile,
26 BearerConnectionRegistration,
27 type ConnectionRegistration,
28 PrimaryConnectionRegistration,
29 RelayConnectionRegistration,
30 SshConnectionProfile,
31 type ConnectionCredential,
32 type ConnectionProfile,
33} from "./catalog.ts";
34import * as Connectivity from "./connectivity.ts";
35import * as ConnectionCredentialStore from "./credentialStore.ts";
36import * as ConnectionDriver from "./driver.ts";
37import {
38 ConnectionTransientError,
39 BearerConnectionTarget,
40 PrimaryConnectionTarget,
41 RelayConnectionTarget,
42 SshConnectionTarget,
43 type ConnectionTarget,
44 type PreparedConnection,
45 type SupervisorConnectionState,
46} from "./model.ts";
47import * as Persistence from "../platform/persistence.ts";
48import * as ConnectionProfileStore from "./profileStore.ts";
49import * as EnvironmentRegistry from "./registry.ts";
50import {
51 GitHubRoutingPermissions,
52 makeGitHubRoutingPermissions,
53} from "./githubRoutingPermissions.ts";
54import * as RpcSession from "../rpc/session.ts";
55import * as EnvironmentSupervisor from "./supervisor.ts";
56import * as ConnectionWakeups from "./wakeups.ts";
57import { runDesktopCommitWithReconnectObserver } from "../state/server.ts";
58
59const TARGET = new PrimaryConnectionTarget({
60 environmentId: EnvironmentId.make("environment-1"),
61 label: "Test environment",
62 httpBaseUrl: "https://environment.example.test",
63 wsBaseUrl: "wss://environment.example.test",
64});
65const SECOND_TARGET = new PrimaryConnectionTarget({
66 environmentId: EnvironmentId.make("environment-2"),
67 label: "Second environment",
68 httpBaseUrl: "https://environment-2.example.test",
69 wsBaseUrl: "wss://environment-2.example.test",
70});
71
72const PREPARED: PreparedConnection = {
73 environmentId: TARGET.environmentId,
74 label: TARGET.label,
75 httpBaseUrl: TARGET.httpBaseUrl,
76 socketUrl: "wss://environment.example.test/ws",
77 httpAuthorization: null,
78 target: TARGET,
79};
80
81const RELAY_TARGET = new RelayConnectionTarget({
82 environmentId: EnvironmentId.make("environment-relay"),
83 label: "Relay environment",
84});
85const SECOND_RELAY_TARGET = new RelayConnectionTarget({
86 environmentId: EnvironmentId.make("environment-relay-2"),
87 label: "Second relay environment",
88});
89
90const BEARER_TARGET = new BearerConnectionTarget({
91 environmentId: EnvironmentId.make("environment-bearer"),
92 label: "Bearer environment",
93 connectionId: "bearer-connection",
94});
95const BEARER_PROFILE = new BearerConnectionProfile({
96 connectionId: BEARER_TARGET.connectionId,
97 environmentId: BEARER_TARGET.environmentId,
98 label: BEARER_TARGET.label,
99 httpBaseUrl: "https://bearer.example.test",
100 wsBaseUrl: "wss://bearer.example.test",
101});
102const BEARER_CREDENTIAL = new BearerConnectionCredential({
103 token: "bearer-token",
104});
105
106const SSH_TARGET: DesktopSshEnvironmentTarget = {
107 alias: "test",
108 hostname: "test.example.test",
109 username: "developer",
110 port: 22,
111};
112const SSH_CONNECTION = new SshConnectionTarget({
113 environmentId: EnvironmentId.make("environment-ssh"),
114 label: "SSH environment",
115 connectionId: "ssh-connection",
116});
117const SSH_PROFILE = new SshConnectionProfile({
118 connectionId: SSH_CONNECTION.connectionId,
119 environmentId: SSH_CONNECTION.environmentId,
120 label: SSH_CONNECTION.label,
121 target: SSH_TARGET,
122});
123
124const CACHED_SNAPSHOT: OrchestrationShellSnapshot = {
125 snapshotSequence: 1,
126 projects: [],
127 threads: [],
128 updatedAt: "2026-06-06T00:00:00.000Z",
129};
130
131interface SessionControl {
132 readonly closed: Deferred.Deferred<never, ConnectionTransientError>;
133}
134
135const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
136 initialTargets: ReadonlyArray<ConnectionTarget>,
137 initialProfiles: ReadonlyArray<ConnectionProfile> = [],
138 initialCredentials: ReadonlyArray<readonly [string, ConnectionCredential]> = [],
139 options?: {
140 readonly beforeSessionConnect?: (environmentId: EnvironmentId) => Effect.Effect<void>;
141 readonly beforeRegistrationRegister?: (
142 registration: ConnectionRegistration,
143 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
144 readonly beforeRegistrationRemove?: (
145 target: ConnectionTarget,
146 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
147 readonly initialDisabled?: ReadonlyArray<EnvironmentId>;
148 },
149) {
150 const storedTargets = yield* Ref.make(
151 new Map(initialTargets.map((target) => [target.environmentId, target])),
152 );
153 const shellCache = yield* Ref.make(new Map([[TARGET.environmentId, CACHED_SNAPSHOT]]));
154 const cacheClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]);
155 const ownedDataClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]);
156 const sessions = yield* Ref.make<ReadonlyArray<SessionControl>>([]);
157 const releasedSessions = yield* Ref.make(0);
158 const storedProfiles = yield* Ref.make(
159 new Map(initialProfiles.map((profile) => [profile.connectionId, profile])),
160 );
161 const profileReadCount = yield* Ref.make(0);
162 const storedCredentials = yield* Ref.make(new Map(initialCredentials));
163 const storedRemoteTokens = yield* Ref.make(
164 new Map([
165 [
166 SSH_CONNECTION.environmentId,
167 new TokenStore.RemoteDpopAccessToken({
168 environmentId: SSH_CONNECTION.environmentId,
169 label: SSH_CONNECTION.label,
170 endpoint: {
171 httpBaseUrl: "https://ssh.example.test",
172 wsBaseUrl: "wss://ssh.example.test",
173 providerKind: "cloudflare_tunnel",
174 },
175 accessToken: "cached-token",
176 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
177 dpopThumbprint: "thumbprint",
178 }),
179 ],
180 ]),
181 );
182 const disconnectedSshTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
183
184 const storedDisabled = yield* Ref.make<ReadonlySet<EnvironmentId>>(
185 new Set(options?.initialDisabled ?? []),
186 );
187 const targetStore = Persistence.ConnectionTargetStore.of({
188 list: Ref.get(storedTargets).pipe(Effect.map((targets) => [...targets.values()])),
189 listDisabled: Ref.get(storedDisabled).pipe(Effect.map((ids) => [...ids])),
190 });
191 const registrationStore = Persistence.ConnectionRegistrationStore.of({
192 register: (registration) =>
193 Effect.gen(function* () {
194 yield* options?.beforeRegistrationRegister?.(registration) ?? Effect.void;
195 yield* Ref.update(storedTargets, (current) => {
196 const next = new Map(current);
197 next.set(registration.target.environmentId, registration.target);
198 return next;
199 });
200 switch (registration._tag) {
201 case "RelayConnectionRegistration":
202 return;
203 case "BearerConnectionRegistration":
204 yield* Ref.update(storedProfiles, (current) => {
205 const next = new Map(current);
206 next.set(registration.profile.connectionId, registration.profile);
207 return next;
208 });
209 yield* Ref.update(storedCredentials, (current) => {
210 const next = new Map(current);
211 next.set(registration.target.connectionId, registration.credential);
212 return next;
213 });
214 return;
215 case "SshConnectionRegistration":
216 yield* Ref.update(storedProfiles, (current) => {
217 const next = new Map(current);
218 next.set(registration.profile.connectionId, registration.profile);
219 return next;
220 });
221 }
222 }),
223 remove: (target) =>
224 Effect.gen(function* () {
225 yield* options?.beforeRegistrationRemove?.(target) ?? Effect.void;
226 yield* Ref.update(storedTargets, (current) => {
227 const next = new Map(current);
228 next.delete(target.environmentId);
229 return next;
230 });
231 if (target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget") {
232 yield* Ref.update(storedProfiles, (current) => {
233 const next = new Map(current);
234 next.delete(target.connectionId);
235 return next;
236 });
237 yield* Ref.update(storedCredentials, (current) => {
238 const next = new Map(current);
239 next.delete(target.connectionId);
240 return next;
241 });
242 }
243 yield* Ref.update(storedRemoteTokens, (current) => {
244 const next = new Map(current);
245 next.delete(target.environmentId);
246 return next;
247 });
248 }),
249 setEnabled: (environmentId, enabled) =>
250 Ref.update(storedDisabled, (current) => {
251 const next = new Set(current);
252 if (enabled) {
253 next.delete(environmentId);
254 } else {
255 next.add(environmentId);
256 }
257 return next;
258 }),
259 });
260 const cacheStore = Persistence.EnvironmentCacheStore.of({
261 loadShell: (environmentId) =>
262 Ref.get(shellCache).pipe(
263 Effect.map((cache) => Option.fromUndefinedOr(cache.get(environmentId))),
264 ),
265 saveShell: (environmentId, snapshot) =>
266 Ref.update(shellCache, (current) => {
267 const next = new Map(current);
268 next.set(environmentId, snapshot);
269 return next;
270 }),
271 loadThread: (_environmentId, _threadId) => Effect.succeed(Option.none()),
272 saveThread: (_environmentId, _thread) => Effect.void,
273 removeThread: (_environmentId, _threadId) => Effect.void,
274 loadServerConfig: () => Effect.succeed(Option.none()),
275 saveServerConfig: () => Effect.void,
276 loadVcsRefs: () => Effect.succeed(Option.none()),
277 saveVcsRefs: () => Effect.void,
278 removeVcsRefs: () => Effect.void,
279 clearVcsRefs: () => Effect.void,
280 clear: (environmentId) =>
281 Ref.update(shellCache, (current) => {
282 const next = new Map(current);
283 next.delete(environmentId);
284 return next;
285 }).pipe(
286 Effect.andThen(
287 Ref.update(cacheClears, (environmentIds) => [...environmentIds, environmentId]),
288 ),
289 ),
290 });
291 const ownedDataCleanup = Persistence.EnvironmentOwnedDataCleanup.of({
292 clear: (environmentId) =>
293 Ref.update(ownedDataClears, (environmentIds) => [...environmentIds, environmentId]),
294 });
295 const networkStatus = yield* SubscriptionRef.make<"unknown" | "offline" | "online">("online");
296 const connectivity = Connectivity.Connectivity.of({
297 status: SubscriptionRef.get(networkStatus),
298 changes: SubscriptionRef.changes(networkStatus),
299 });
300 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
301 get: (connectionId) =>
302 Ref.update(profileReadCount, (count) => count + 1).pipe(
303 Effect.andThen(Ref.get(storedProfiles)),
304 Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))),
305 ),
306 put: (profile) =>
307 Ref.update(storedProfiles, (current) => {
308 const next = new Map(current);
309 next.set(profile.connectionId, profile);
310 return next;
311 }),
312 remove: (connectionId) =>
313 Ref.update(storedProfiles, (current) => {
314 const next = new Map(current);
315 next.delete(connectionId);
316 return next;
317 }),
318 });
319 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
320 get: (connectionId) =>
321 Ref.get(storedCredentials).pipe(
322 Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))),
323 ),
324 put: (connectionId, credential) =>
325 Ref.update(storedCredentials, (current) => {
326 const next = new Map(current);
327 next.set(connectionId, credential);
328 return next;
329 }),
330 remove: (connectionId) =>
331 Ref.update(storedCredentials, (current) => {
332 const next = new Map(current);
333 next.delete(connectionId);
334 return next;
335 }),
336 });
337 const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({
338 get: (environmentId) =>
339 Ref.get(storedRemoteTokens).pipe(
340 Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
341 ),
342 put: (token) =>
343 Ref.update(storedRemoteTokens, (current) => {
344 const next = new Map(current);
345 next.set(token.environmentId, token);
346 return next;
347 }),
348 remove: (environmentId) =>
349 Ref.update(storedRemoteTokens, (current) => {
350 const next = new Map(current);
351 next.delete(environmentId);
352 return next;
353 }),
354 });
355 const sshGateway = ClientCapabilities.SshEnvironmentGateway.of({
356 provision: () => Effect.die(new Error("SSH provisioning is not used.")),
357 prepare: () => Effect.die(new Error("SSH preparation is not used.")),
358 disconnect: (target) => Ref.update(disconnectedSshTargets, (current) => [...current, target]),
359 });
360 const driver = ConnectionDriver.ConnectionDriver.of({
361 connect: (entry, reportProgress) =>
362 Effect.gen(function* () {
363 const target = entry.target;
364 const prepared = {
365 ...PREPARED,
366 environmentId: target.environmentId,
367 label: target.label,
368 target,
369 };
370 yield* reportProgress({ stage: "preparing" });
371 yield* reportProgress({ stage: "opening", prepared });
372 yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void;
373 const closed = yield* Deferred.make<never, ConnectionTransientError>();
374 yield* Ref.update(sessions, (current) => [...current, { closed }]);
375 const session = yield* Effect.acquireRelease(
376 Effect.succeed({
377 client: {} as RpcSession.RpcSession["client"],
378 initialConfig: Effect.die(new Error("Config is not used by registry tests.")),
379 subscribeServerConfig: () =>
380 Stream.die(new Error("Config is not used by registry tests.")),
381 ready: Effect.void,
382 probe: Effect.void,
383 closed: Deferred.await(closed),
384 } satisfies RpcSession.RpcSession),
385 () => Ref.update(releasedSessions, (count) => count + 1),
386 );
387 yield* reportProgress({ stage: "synchronizing", prepared });
388 yield* session.ready;
389 return { prepared, session };
390 }),
391 });
392
393 const cacheLayer = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore);
394 const layer = EnvironmentRegistry.layer.pipe(
395 Layer.provide(
396 Layer.mergeAll(
397 Layer.succeed(Persistence.ConnectionTargetStore, targetStore),
398 Layer.succeed(Persistence.ConnectionRegistrationStore, registrationStore),
399 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
400 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
401 Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
402 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, sshGateway),
403 Layer.succeed(Connectivity.Connectivity, connectivity),
404 Layer.succeed(
405 ConnectionWakeups.ConnectionWakeups,
406 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }),
407 ),
408 Layer.succeed(ConnectionDriver.ConnectionDriver, driver),
409 cacheLayer,
410 Layer.succeed(Persistence.EnvironmentOwnedDataCleanup, ownedDataCleanup),
411 ),
412 ),
413 );
414
415 return {
416 layer,
417 storedTargets,
418 shellCache,
419 cacheClears,
420 ownedDataClears,
421 sessions,
422 releasedSessions,
423 storedProfiles,
424 profileReadCount,
425 storedCredentials,
426 storedRemoteTokens,
427 storedDisabled,
428 disconnectedSshTargets,
429 networkStatus,
430 };
431});
432
433function awaitConnectionState(
434 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
435 environmentId: EnvironmentId,
436 predicate: (state: SupervisorConnectionState) => boolean,
437) {
438 return Effect.gen(function* () {
439 const current = yield* registry.state(environmentId);
440 if (predicate(current)) {
441 return current;
442 }
443 return yield* registry
444 .stateChanges(environmentId)
445 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
446 });
447}
448
449describe("EnvironmentRegistry", () => {
450 it.effect("replays connected state when arming a desktop commit observer", () =>
451 Effect.gen(function* () {
452 const harness = yield* makeHarness([TARGET]);
453
454 yield* Effect.gen(function* () {
455 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
456 yield* registry.start;
457 yield* awaitConnectionState(
458 registry,
459 TARGET.environmentId,
460 (state) => state.phase === "connected",
461 );
462
463 const commits = yield* Ref.make(0);
464 const result = yield* runDesktopCommitWithReconnectObserver(
465 registry.stateChanges(TARGET.environmentId),
466 Ref.update(commits, (count) => count + 1).pipe(
467 Effect.andThen(Effect.fail("commit refused")),
468 ),
469 ).pipe(Effect.flip, Effect.timeout("1 second"));
470
471 expect(result).toBe("commit refused");
472 expect(yield* Ref.get(commits)).toBe(1);
473 }).pipe(Effect.provide(harness.layer), Effect.scoped);
474 }),
475 );
476
477 it.effect("does not acquire a session after the registry scope has already closed", () =>
478 Effect.gen(function* () {
479 const harness = yield* makeHarness([TARGET]);
480 const registryScope = yield* Scope.make();
481 const context = yield* Layer.build(harness.layer).pipe(Scope.provide(registryScope));
482 const registry = Context.get(context, EnvironmentRegistry.EnvironmentRegistry);
483 const dispatcher = new Scheduler.MixedScheduler("sync", () => () => {}).makeDispatcher();
484 const scheduler: Scheduler.Scheduler = {
485 executionMode: "sync",
486 shouldYield: () => false,
487 makeDispatcher: () => dispatcher,
488 };
489
490 yield* Scope.close(registryScope, Exit.void);
491 yield* registry.start.pipe(Effect.provideService(Scheduler.Scheduler, scheduler));
492 dispatcher.flush();
493
494 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
495 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
496 }),
497 );
498
499 it.effect("hydrates connection profiles into catalog entries", () =>
500 Effect.gen(function* () {
501 const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
502
503 yield* Effect.gen(function* () {
504 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
505 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
506 SSH_CONNECTION.environmentId,
507 );
508
509 expect(entry?.target).toEqual(SSH_CONNECTION);
510 expect(Option.getOrThrow(entry?.profile ?? Option.none())).toEqual(SSH_PROFILE);
511 }).pipe(Effect.provide(harness.layer), Effect.scoped);
512 }),
513 );
514
515 it.effect("publishes network status changes independently of connection state", () =>
516 Effect.gen(function* () {
517 const harness = yield* makeHarness([]);
518
519 yield* Effect.gen(function* () {
520 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
521 const offline = yield* Effect.forkChild(
522 SubscriptionRef.changes(registry.networkStatus).pipe(
523 Stream.filter((status) => status === "offline"),
524 Stream.runHead,
525 Effect.map(Option.getOrThrow),
526 ),
527 );
528
529 yield* SubscriptionRef.set(harness.networkStatus, "offline");
530
531 expect(yield* Fiber.join(offline)).toBe("offline");
532 expect(yield* SubscriptionRef.get(registry.networkStatus)).toBe("offline");
533 }).pipe(Effect.provide(harness.layer), Effect.scoped);
534 }),
535 );
536
537 it.effect("starts persisted environments independently", () =>
538 Effect.gen(function* () {
539 const bothLoadsStarted = yield* Deferred.make<void>();
540 const releaseLoads = yield* Deferred.make<void>();
541 const loadCount = yield* Ref.make(0);
542 const harness = yield* makeHarness([TARGET, SECOND_TARGET], [], [], {
543 beforeSessionConnect: () =>
544 Ref.updateAndGet(loadCount, (count) => count + 1).pipe(
545 Effect.tap((count) =>
546 count === 2 ? Deferred.succeed(bothLoadsStarted, undefined) : Effect.void,
547 ),
548 Effect.andThen(Deferred.await(releaseLoads)),
549 ),
550 });
551
552 yield* Effect.gen(function* () {
553 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
554 const start = yield* Effect.forkChild(registry.start);
555
556 yield* Deferred.await(bothLoadsStarted).pipe(Effect.timeout("1 second"));
557 yield* Deferred.succeed(releaseLoads, undefined);
558 yield* Fiber.join(start);
559
560 expect(yield* Ref.get(loadCount)).toBe(2);
561 }).pipe(Effect.provide(harness.layer), Effect.scoped);
562 }),
563 );
564
565 it.effect("exposes the current RPC generation to late query subscribers", () =>
566 Effect.gen(function* () {
567 const harness = yield* makeHarness([TARGET]);
568 yield* Effect.gen(function* () {
569 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
570 yield* registry.start;
571 yield* awaitConnectionState(
572 registry,
573 TARGET.environmentId,
574 (state) => state.phase === "connected",
575 );
576
577 const generation = yield* registry
578 .runStream(
579 TARGET.environmentId,
580 Stream.unwrap(
581 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
582 Effect.map((supervisor) =>
583 Stream.concat(
584 Stream.fromEffect(SubscriptionRef.get(supervisor.state)),
585 SubscriptionRef.changes(supervisor.state),
586 ).pipe(
587 Stream.filterMap((state) =>
588 state.phase === "connected"
589 ? Result.succeed(state.generation)
590 : Result.failVoid,
591 ),
592 Stream.changes,
593 ),
594 ),
595 ),
596 ),
597 )
598 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
599
600 expect(generation).toBe(1);
601 }).pipe(Effect.provide(harness.layer), Effect.scoped);
602 }),
603 );
604
605 it.effect("preserves cached data on connection failure and clears it on explicit removal", () =>
606 Effect.gen(function* () {
607 const harness = yield* makeHarness([TARGET]);
608 yield* Effect.gen(function* () {
609 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
610 yield* registry.start;
611 yield* awaitConnectionState(
612 registry,
613 TARGET.environmentId,
614 (state) => state.phase === "connected",
615 );
616 const controls = yield* Ref.get(harness.sessions);
617 expect(controls).toHaveLength(1);
618 const active = controls[0];
619 expect(active).toBeDefined();
620 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
621 CACHED_SNAPSHOT,
622 );
623
624 const retryFiber = yield* Effect.forkChild(
625 awaitConnectionState(
626 registry,
627 TARGET.environmentId,
628 (state) => state.phase === "backoff",
629 ),
630 );
631 yield* Effect.yieldNow;
632 yield* Deferred.fail(
633 active!.closed,
634 new ConnectionTransientError({
635 reason: "transport",
636 detail: "Disconnected.",
637 }),
638 );
639 yield* Fiber.join(retryFiber);
640 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
641 CACHED_SNAPSHOT,
642 );
643
644 yield* registry.remove(TARGET.environmentId);
645 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
646 expect((yield* Ref.get(harness.shellCache)).has(TARGET.environmentId)).toBe(false);
647 expect(yield* Ref.get(harness.cacheClears)).toEqual([TARGET.environmentId]);
648 expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(
649 false,
650 );
651 }).pipe(Effect.provide(harness.layer));
652 }),
653 );
654
655 it.effect("persists and starts a newly registered environment", () =>
656 Effect.gen(function* () {
657 const harness = yield* makeHarness([]);
658
659 yield* Effect.gen(function* () {
660 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
661 yield* registry.register(new RelayConnectionRegistration({ target: RELAY_TARGET }));
662 yield* awaitConnectionState(
663 registry,
664 RELAY_TARGET.environmentId,
665 (state) => state.phase === "connected",
666 );
667
668 expect((yield* Ref.get(harness.storedTargets)).get(RELAY_TARGET.environmentId)).toEqual(
669 RELAY_TARGET,
670 );
671 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
672 }).pipe(Effect.provide(harness.layer));
673 }),
674 );
675
676 it.effect("switching an environment off disconnects it and persists the flag", () =>
677 Effect.gen(function* () {
678 const harness = yield* makeHarness([RELAY_TARGET]);
679
680 yield* Effect.gen(function* () {
681 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
682 yield* registry.start;
683 yield* awaitConnectionState(
684 registry,
685 RELAY_TARGET.environmentId,
686 (state) => state.phase === "connected",
687 );
688
689 yield* registry.setEnabled(RELAY_TARGET.environmentId, false);
690 yield* awaitConnectionState(
691 registry,
692 RELAY_TARGET.environmentId,
693 (state) => state.phase === "available",
694 );
695
696 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
697 RELAY_TARGET.environmentId,
698 );
699 expect(entry?.enabled).toBe(false);
700 expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(true);
701 expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
702 expect(yield* Ref.get(harness.releasedSessions)).toBe(1);
703
704 yield* registry.setEnabled(RELAY_TARGET.environmentId, true);
705 yield* awaitConnectionState(
706 registry,
707 RELAY_TARGET.environmentId,
708 (state) => state.phase === "connected",
709 );
710 expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(
711 false,
712 );
713 }).pipe(Effect.provide(harness.layer));
714 }),
715 );
716
717 it.effect("re-registering a switched-off environment keeps it off", () =>
718 Effect.gen(function* () {
719 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
720 initialDisabled: [RELAY_TARGET.environmentId],
721 });
722
723 yield* Effect.gen(function* () {
724 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
725 yield* registry.start;
726 yield* registry.register(
727 new RelayConnectionRegistration({
728 target: new RelayConnectionTarget({ ...RELAY_TARGET, label: "Renamed" }),
729 }),
730 );
731 yield* Effect.yieldNow;
732
733 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
734 RELAY_TARGET.environmentId,
735 );
736 expect(entry?.target.label).toBe("Renamed");
737 expect(entry?.enabled).toBe(false);
738 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
739 }).pipe(Effect.provide(harness.layer));
740 }),
741 );
742
743 it.effect("switching an SSH environment off tears down its managed backend", () =>
744 Effect.gen(function* () {
745 const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
746
747 yield* Effect.gen(function* () {
748 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
749 yield* registry.start;
750 yield* awaitConnectionState(
751 registry,
752 SSH_CONNECTION.environmentId,
753 (state) => state.phase === "connected",
754 );
755
756 yield* registry.setEnabled(SSH_CONNECTION.environmentId, false);
757 yield* awaitConnectionState(
758 registry,
759 SSH_CONNECTION.environmentId,
760 (state) => state.phase === "available",
761 );
762
763 expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
764 expect((yield* Ref.get(harness.storedTargets)).has(SSH_CONNECTION.environmentId)).toBe(
765 true,
766 );
767 }).pipe(Effect.provide(harness.layer));
768 }),
769 );
770
771 it.effect("does not connect a persisted environment that was switched off", () =>
772 Effect.gen(function* () {
773 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
774 initialDisabled: [RELAY_TARGET.environmentId],
775 });
776
777 yield* Effect.gen(function* () {
778 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
779 yield* registry.start;
780 yield* Effect.yieldNow;
781
782 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
783 RELAY_TARGET.environmentId,
784 );
785 expect(entry?.enabled).toBe(false);
786 expect((yield* registry.state(RELAY_TARGET.environmentId)).phase).toBe("available");
787 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
788 }).pipe(Effect.provide(harness.layer));
789 }),
790 );
791
792 it.effect("moves durable streams to a replacement supervisor", () =>
793 Effect.gen(function* () {
794 const replacement = new RelayConnectionTarget({
795 environmentId: RELAY_TARGET.environmentId,
796 label: "Replacement relay environment",
797 });
798 const harness = yield* makeHarness([RELAY_TARGET]);
799
800 yield* Effect.gen(function* () {
801 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
802 const firstObserved = yield* Deferred.make<void>();
803 const secondObserved = yield* Deferred.make<void>();
804 const labels = yield* Ref.make<ReadonlyArray<string>>([]);
805 yield* registry.start;
806 yield* awaitConnectionState(
807 registry,
808 RELAY_TARGET.environmentId,
809 (state) => state.phase === "connected",
810 );
811
812 const subscription = yield* Effect.forkChild(
813 registry
814 .followStream(
815 RELAY_TARGET.environmentId,
816 Stream.unwrap(
817 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
818 Effect.map((supervisor) =>
819 Stream.concat(Stream.succeed(supervisor.target.label), Stream.never),
820 ),
821 ),
822 ),
823 )
824 .pipe(
825 Stream.tap((label) =>
826 Ref.updateAndGet(labels, (current) => [...current, label]).pipe(
827 Effect.flatMap((current) =>
828 current.length === 1
829 ? Deferred.succeed(firstObserved, undefined)
830 : Deferred.succeed(secondObserved, undefined),
831 ),
832 ),
833 ),
834 Stream.runDrain,
835 ),
836 );
837
838 yield* Deferred.await(firstObserved).pipe(Effect.timeout("1 second"));
839 yield* registry.register(new RelayConnectionRegistration({ target: replacement }));
840 yield* Deferred.await(secondObserved).pipe(Effect.timeout("1 second"));
841 yield* Fiber.interrupt(subscription);
842
843 expect(yield* Ref.get(labels)).toEqual([RELAY_TARGET.label, replacement.label]);
844 }).pipe(Effect.provide(harness.layer), Effect.scoped);
845 }),
846 );
847
848 it.effect("ignores retry signals for environments that are no longer registered", () =>
849 Effect.gen(function* () {
850 const harness = yield* makeHarness([]);
851
852 yield* Effect.gen(function* () {
853 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
854 yield* registry.retryNow(EnvironmentId.make("removed-environment"));
855 }).pipe(Effect.provide(harness.layer), Effect.scoped);
856 }),
857 );
858
859 it.effect("removes all relay-owned data without touching non-cloud connections", () =>
860 Effect.gen(function* () {
861 const harness = yield* makeHarness(
862 [RELAY_TARGET, SECOND_RELAY_TARGET, BEARER_TARGET],
863 [BEARER_PROFILE],
864 [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]],
865 );
866
867 yield* Effect.gen(function* () {
868 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
869 yield* registry.removeRelayEnvironments();
870
871 const targets = yield* Ref.get(harness.storedTargets);
872 expect(targets.has(RELAY_TARGET.environmentId)).toBe(false);
873 expect(targets.has(SECOND_RELAY_TARGET.environmentId)).toBe(false);
874 expect(targets.get(BEARER_TARGET.environmentId)).toEqual(BEARER_TARGET);
875 expect(yield* Ref.get(harness.cacheClears)).toEqual(
876 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
877 );
878 expect(yield* Ref.get(harness.ownedDataClears)).toEqual(
879 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
880 );
881 expect(
882 (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId),
883 ).toBe(true);
884 }).pipe(Effect.provide(harness.layer), Effect.scoped);
885 }),
886 );
887
888 it.effect("keeps the runtime registered when durable removal fails", () =>
889 Effect.gen(function* () {
890 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
891 beforeRegistrationRemove: () =>
892 Effect.fail(
893 new Persistence.ConnectionPersistenceError({
894 operation: "remove-connection",
895 message: "Storage is unavailable.",
896 }),
897 ),
898 });
899
900 yield* Effect.gen(function* () {
901 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
902 yield* registry.start;
903 yield* awaitConnectionState(
904 registry,
905 RELAY_TARGET.environmentId,
906 (state) => state.phase === "connected",
907 );
908
909 const error = yield* Effect.flip(registry.removeRelayEnvironments());
910
911 expect(error._tag).toBe("ConnectionPersistenceError");
912 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
913 expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
914 true,
915 );
916 expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
917 expect(yield* Ref.get(harness.cacheClears)).toEqual([]);
918 expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]);
919 }).pipe(Effect.provide(harness.layer), Effect.scoped);
920 }),
921 );
922
923 it.effect("starts a newly paired bearer environment without re-reading its profile", () =>
924 Effect.gen(function* () {
925 const harness = yield* makeHarness([]);
926
927 yield* Effect.gen(function* () {
928 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
929 yield* registry.register(
930 new BearerConnectionRegistration({
931 target: BEARER_TARGET,
932 profile: BEARER_PROFILE,
933 credential: BEARER_CREDENTIAL,
934 }),
935 );
936 yield* awaitConnectionState(
937 registry,
938 BEARER_TARGET.environmentId,
939 (state) => state.phase === "connected",
940 );
941
942 expect(yield* Ref.get(harness.profileReadCount)).toBe(0);
943 expect(
944 Option.getOrThrow(
945 (yield* SubscriptionRef.get(registry.entries)).get(BEARER_TARGET.environmentId)
946 ?.profile ?? Option.none(),
947 ),
948 ).toEqual(BEARER_PROFILE);
949 }).pipe(Effect.provide(harness.layer), Effect.scoped);
950 }),
951 );
952
953 it.effect("starts platform environments without persisting or removing them", () =>
954 Effect.gen(function* () {
955 const harness = yield* makeHarness([]);
956
957 yield* Effect.gen(function* () {
958 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
959 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
960 yield* awaitConnectionState(
961 registry,
962 TARGET.environmentId,
963 (state) => state.phase === "connected",
964 );
965
966 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
967 expect(
968 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
969 ).toEqual(TARGET);
970
971 const error = yield* Effect.flip(registry.remove(TARGET.environmentId));
972 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
973 expect(
974 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
975 ).toEqual(TARGET);
976 }).pipe(Effect.provide(harness.layer));
977 }),
978 );
979
980 it.effect("gives a primary platform registration precedence over persisted registrations", () =>
981 Effect.gen(function* () {
982 const shadowedTarget = new RelayConnectionTarget({
983 environmentId: TARGET.environmentId,
984 label: "Shadowed relay environment",
985 });
986 const harness = yield* makeHarness([shadowedTarget]);
987 const permissions = yield* makeGitHubRoutingPermissions({
988 read: Effect.succeed([]),
989 write: () => Effect.void,
990 });
991 const shadowedEntry = { target: shadowedTarget, profile: Option.none(), enabled: true };
992 yield* permissions.set(shadowedEntry, "read-write");
993
994 yield* Effect.gen(function* () {
995 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
996 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
997 expect(yield* permissions.get(shadowedEntry)).toBe("off");
998
999 expect(
1000 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1001 ).toEqual(TARGET);
1002 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
1003
1004 yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget }));
1005
1006 expect(
1007 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1008 ).toEqual(TARGET);
1009 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
1010 }).pipe(
1011 Effect.provide(harness.layer),
1012 Effect.provideService(GitHubRoutingPermissions, permissions),
1013 Effect.scoped,
1014 );
1015 }),
1016 );
1017
1018 it.effect("rechecks platform ownership after waiting for the environment lease", () =>
1019 Effect.gen(function* () {
1020 const registrationStarted = yield* Deferred.make<void>();
1021 const continueRegistration = yield* Deferred.make<void>();
1022 const shadowedTarget = new RelayConnectionTarget({
1023 environmentId: TARGET.environmentId,
1024 label: "Shadowed relay environment",
1025 });
1026 const harness = yield* makeHarness([], [], [], {
1027 beforeRegistrationRegister: () =>
1028 Deferred.succeed(registrationStarted, undefined).pipe(
1029 Effect.andThen(Deferred.await(continueRegistration)),
1030 ),
1031 });
1032
1033 yield* Effect.gen(function* () {
1034 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1035 const persistedRegistration = yield* registry
1036 .register(new RelayConnectionRegistration({ target: shadowedTarget }))
1037 .pipe(Effect.forkChild({ startImmediately: true }));
1038 yield* Deferred.await(registrationStarted);
1039
1040 const platformRegistration = yield* registry
1041 .registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }))
1042 .pipe(Effect.forkChild({ startImmediately: true }));
1043 yield* Effect.yieldNow;
1044 const removal = yield* Effect.flip(registry.remove(TARGET.environmentId)).pipe(
1045 Effect.forkChild({ startImmediately: true }),
1046 );
1047
1048 yield* Deferred.succeed(continueRegistration, undefined);
1049 yield* Fiber.join(persistedRegistration);
1050 yield* Fiber.join(platformRegistration);
1051 const error = yield* Fiber.join(removal);
1052
1053 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
1054 expect(
1055 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1056 ).toEqual(TARGET);
1057 }).pipe(Effect.provide(harness.layer), Effect.scoped);
1058 }),
1059 );
1060
1061 it.effect("does not reacquire a runtime while its registration is being removed", () =>
1062 Effect.gen(function* () {
1063 const removalStarted = yield* Deferred.make<void>();
1064 const continueRemoval = yield* Deferred.make<void>();
1065 const harness = yield* makeHarness([TARGET], [], [], {
1066 beforeRegistrationRemove: () =>
1067 Deferred.succeed(removalStarted, undefined).pipe(
1068 Effect.andThen(Deferred.await(continueRemoval)),
1069 ),
1070 });
1071
1072 yield* Effect.gen(function* () {
1073 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1074 yield* registry.start;
1075 yield* awaitConnectionState(
1076 registry,
1077 TARGET.environmentId,
1078 (state) => state.phase === "connected",
1079 );
1080
1081 const removal = yield* Effect.forkChild(registry.remove(TARGET.environmentId));
1082 yield* Deferred.await(removalStarted);
1083
1084 const stateLookup = yield* Effect.forkChild(
1085 Effect.flip(registry.state(TARGET.environmentId)),
1086 );
1087 yield* Effect.yieldNow;
1088 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
1089
1090 yield* Deferred.succeed(continueRemoval, undefined);
1091 yield* Fiber.join(removal);
1092 const error = yield* Fiber.join(stateLookup);
1093 expect(error._tag).toBe("EnvironmentNotRegisteredError");
1094 }).pipe(Effect.provide(harness.layer), Effect.scoped);
1095 }),
1096 );
1097
1098 it.effect("retains a healthy runtime when the platform repeats an identical registration", () =>
1099 Effect.gen(function* () {
1100 const harness = yield* makeHarness([]);
1101 let failWrites = false;
1102 const permissions = yield* makeGitHubRoutingPermissions({
1103 read: Effect.succeed([]),
1104 write: () =>
1105 failWrites
1106 ? Effect.fail(
1107 new ConnectionTransientError({
1108 reason: "remote-unavailable",
1109 detail: "Storage unavailable",
1110 }),
1111 )
1112 : Effect.void,
1113 });
1114 const entry = { target: TARGET, profile: Option.none(), enabled: true };
1115
1116 yield* Effect.gen(function* () {
1117 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1118 const registration = new PrimaryConnectionRegistration({ target: TARGET });
1119 yield* registry.registerPlatform(registration);
1120 yield* awaitConnectionState(
1121 registry,
1122 TARGET.environmentId,
1123 (state) => state.phase === "connected",
1124 );
1125 yield* permissions.set(entry, "read-write");
1126
1127 yield* registry.registerPlatform(registration);
1128
1129 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
1130 expect(yield* permissions.get(entry)).toBe("read-write");
1131
1132 const changedTarget = new PrimaryConnectionTarget({
1133 ...TARGET,
1134 httpBaseUrl: "https://changed.example.test",
1135 });
1136 failWrites = true;
1137 yield* registry.registerPlatform(
1138 new PrimaryConnectionRegistration({ target: changedTarget }),
1139 );
1140 expect(
1141 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1142 ).toEqual(TARGET);
1143 yield* registry.reconcilePlatform([]);
1144 expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(true);
1145
1146 failWrites = false;
1147 yield* registry.registerPlatform(
1148 new PrimaryConnectionRegistration({ target: changedTarget }),
1149 );
1150 expect(yield* permissions.get(entry)).toBe("off");
1151 yield* registry.registerPlatform(registration);
1152 expect(yield* permissions.get(entry)).toBe("off");
1153 yield* permissions.set(entry, "read-write");
1154 yield* registry.reconcilePlatform([]);
1155 yield* registry.registerPlatform(registration);
1156 expect(yield* permissions.get(entry)).toBe("off");
1157 }).pipe(
1158 Effect.provide(harness.layer),
1159 Effect.provideService(GitHubRoutingPermissions, permissions),
1160 Effect.scoped,
1161 );
1162 }),
1163 );
1164
1165 it.effect("removes all owned SSH state only on explicit removal", () =>
1166 Effect.gen(function* () {
1167 const harness = yield* makeHarness(
1168 [SSH_CONNECTION],
1169 [SSH_PROFILE],
1170 [
1171 [
1172 SSH_CONNECTION.connectionId,
1173 new BearerConnectionCredential({ token: "temporary-token" }),
1174 ],
1175 ],
1176 );
1177
1178 yield* Effect.gen(function* () {
1179 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1180 yield* registry.start;
1181 yield* registry.remove(SSH_CONNECTION.environmentId);
1182
1183 expect((yield* Ref.get(harness.storedProfiles)).has(SSH_CONNECTION.connectionId)).toBe(
1184 false,
1185 );
1186 expect((yield* Ref.get(harness.storedCredentials)).has(SSH_CONNECTION.connectionId)).toBe(
1187 false,
1188 );
1189 expect((yield* Ref.get(harness.storedRemoteTokens)).has(SSH_CONNECTION.environmentId)).toBe(
1190 false,
1191 );
1192 expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
1193 }).pipe(Effect.provide(harness.layer));
1194 }),
1195 );
1196});