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