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

registry.test.ts

1,459 lines55.4 KB

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