Open History to see the last commit
1import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
2import { RelayClientTracer } from "@t3tools/shared/relayTracing";
3import { describe, expect, it } from "@effect/vitest";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Stream from "effect/Stream";
10import * as SubscriptionRef from "effect/SubscriptionRef";
11import * as TestClock from "effect/testing/TestClock";
12import * as Tracer from "effect/Tracer";
13
14import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
15import * as TokenStore from "../authorization/tokenStore.ts";
16import * as ClientCapabilities from "../platform/capabilities.ts";
17import * as ManagedRelay from "../relay/managedRelay.ts";
18import { remoteHttpClientLayer } from "../rpc/http.ts";
19import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
20import { fetchEnvironmentSessionState } from "../state/session.ts";
21import type { ConnectionCatalogEntry } from "./catalog.ts";
22import * as Connectivity from "./connectivity.ts";
23import * as ConnectionDriver from "./driver.ts";
24import {
25 ConnectionBlockedError,
26 ConnectionTransientError,
27 PrimaryConnectionTarget,
28 RelayConnectionTarget,
29 type ConnectionAttemptError,
30 type ConnectionTarget,
31 type NetworkStatus,
32 type PreparedConnection,
33 type SupervisorConnectionState,
34} from "./model.ts";
35import * as RpcSession from "../rpc/session.ts";
36import * as EnvironmentSupervisor from "./supervisor.ts";
37import * as ConnectionWakeups from "./wakeups.ts";
38import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
39
40const TARGET = new PrimaryConnectionTarget({
41 environmentId: EnvironmentId.make("environment-1"),
42 label: "Test environment",
43 httpBaseUrl: "https://environment.example.test",
44 wsBaseUrl: "wss://environment.example.test",
45});
46
47const RELAY_TARGET = new RelayConnectionTarget({
48 environmentId: TARGET.environmentId,
49 label: TARGET.label,
50});
51
52const TARGET_ENTRY: ConnectionCatalogEntry = {
53 target: TARGET,
54 profile: Option.none(),
55 enabled: true,
56};
57
58const RELAY_ENTRY: ConnectionCatalogEntry = {
59 target: RELAY_TARGET,
60 profile: Option.none(),
61 enabled: true,
62};
63
64const PREPARED_CONNECTION: PreparedConnection = {
65 environmentId: TARGET.environmentId,
66 label: TARGET.label,
67 httpBaseUrl: TARGET.httpBaseUrl,
68 socketUrl: "wss://environment.example.test/ws",
69 httpAuthorization: null,
70 target: TARGET,
71};
72
73const TEST_RPC_CLIENT = {} as WsRpcProtocolClient;
74
75function transient(message = "Connection failed.") {
76 return new ConnectionTransientError({
77 reason: "transport",
78 detail: message,
79 });
80}
81
82function blocked(message = "Authentication required.") {
83 return new ConnectionBlockedError({
84 reason: "authentication",
85 detail: message,
86 });
87}
88
89function awaitState(
90 state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
91 predicate: (value: SupervisorConnectionState) => boolean,
92) {
93 return SubscriptionRef.changes(state).pipe(
94 Stream.filter(predicate),
95 Stream.runHead,
96 Effect.map(Option.getOrThrow),
97 );
98}
99
100const eventuallyState = Effect.fn("TestConnectionHarness.eventuallyState")(function* (
101 state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
102 predicate: (value: SupervisorConnectionState) => boolean,
103) {
104 let lastState = yield* SubscriptionRef.get(state);
105 for (let iteration = 0; iteration < 100; iteration += 1) {
106 lastState = yield* SubscriptionRef.get(state);
107 if (predicate(lastState)) {
108 return lastState;
109 }
110 yield* Effect.yieldNow;
111 }
112 return yield* Effect.die(
113 new Error(
114 `Expected supervisor state was not observed. Last state: phase=${lastState.phase}, stage=${lastState.stage ?? "none"}, attempt=${lastState.attempt}, generation=${lastState.generation}`,
115 ),
116 );
117});
118
119const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: {
120 readonly networkStatus?: NetworkStatus;
121 readonly prepare?: (
122 attempt: number,
123 target: ConnectionTarget,
124 ) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
125 readonly ready?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
126 readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
127}) {
128 const networkStatus = yield* SubscriptionRef.make<NetworkStatus>(
129 options?.networkStatus ?? "online",
130 );
131 const prepareCount = yield* Ref.make(0);
132 const sessionCount = yield* Ref.make(0);
133 const releaseCount = yield* Ref.make(0);
134 const wakeups = yield* SubscriptionRef.make<{
135 readonly sequence: number;
136 readonly reason: ConnectionWakeups.ConnectionWakeup;
137 }>({
138 sequence: 0,
139 reason: "application-active",
140 });
141 const closedSessions = yield* Ref.make<
142 ReadonlyArray<Deferred.Deferred<never, ConnectionTransientError>>
143 >([]);
144
145 const connectivity = Connectivity.Connectivity.of({
146 status: SubscriptionRef.get(networkStatus),
147 changes: SubscriptionRef.changes(networkStatus),
148 });
149
150 const prepare = Effect.fn("TestConnectionDriver.prepare")(function* (target: ConnectionTarget) {
151 const attempt = yield* Ref.updateAndGet(prepareCount, (count) => count + 1);
152 if (options?.prepare) {
153 return yield* options.prepare(attempt, target);
154 }
155 return PREPARED_CONNECTION;
156 });
157
158 const connect = Effect.fn("TestConnectionDriver.connect")(function* (
159 entry: ConnectionCatalogEntry,
160 reportProgress: (progress: ConnectionDriver.ConnectionDriverProgress) => Effect.Effect<void>,
161 ) {
162 const target = entry.target;
163 yield* reportProgress({ stage: "preparing" });
164 const prepared = yield* prepare(target);
165 yield* reportProgress({ stage: "opening", prepared });
166
167 const attempt = yield* Ref.updateAndGet(sessionCount, (count) => count + 1);
168 const closed = yield* Deferred.make<never, ConnectionTransientError>();
169 yield* Ref.update(closedSessions, (sessions) => [...sessions, closed]);
170
171 const session = yield* Effect.acquireRelease(
172 Effect.succeed({
173 client: TEST_RPC_CLIENT,
174 initialConfig: Effect.die(new Error("Initial config is not used by supervisor tests.")),
175 subscribeServerConfig: (input) => TEST_RPC_CLIENT.subscribeServerConfig(input),
176 ready: options?.ready?.(attempt) ?? Effect.void,
177 probe: options?.probe?.(attempt) ?? Effect.void,
178 closed: Deferred.await(closed),
179 } satisfies RpcSession.RpcSession),
180 () => Ref.update(releaseCount, (count) => count + 1),
181 );
182
183 yield* reportProgress({ stage: "synchronizing", prepared });
184 yield* session.ready;
185 return { prepared, session } satisfies ConnectionDriver.EnvironmentConnectionLease;
186 });
187
188 const dependencies = Layer.mergeAll(
189 Layer.succeed(Connectivity.Connectivity, connectivity),
190 Layer.succeed(
191 ConnectionWakeups.ConnectionWakeups,
192 ConnectionWakeups.ConnectionWakeups.of({
193 changes: SubscriptionRef.changes(wakeups).pipe(
194 Stream.drop(1),
195 Stream.map((event) => event.reason),
196 ),
197 }),
198 ),
199 Layer.succeed(
200 ConnectionDriver.ConnectionDriver,
201 ConnectionDriver.ConnectionDriver.of({ connect }),
202 ),
203 );
204
205 return {
206 dependencies,
207 prepareCount,
208 sessionCount,
209 releaseCount,
210 setNetworkStatus: (status: NetworkStatus) => SubscriptionRef.set(networkStatus, status),
211 wake: (reason: ConnectionWakeups.ConnectionWakeup) =>
212 SubscriptionRef.update(wakeups, (event) => ({
213 sequence: event.sequence + 1,
214 reason,
215 })),
216 closeLatestSession: Effect.fn("TestConnectionHarness.closeLatestSession")(function* (
217 error = transient("Session closed."),
218 ) {
219 const sessions = yield* Ref.get(closedSessions);
220 const latest = sessions.at(-1);
221 if (latest) {
222 yield* Deferred.fail(latest, error);
223 }
224 }),
225 };
226});
227
228describe("EnvironmentSupervisor", () => {
229 it.effect("exports each relay setup as a standalone linked trace that ends at readiness", () =>
230 Effect.gen(function* () {
231 const spans: Array<Tracer.NativeSpan> = [];
232 const tracer = Tracer.make({
233 span: (options) => {
234 const span = new Tracer.NativeSpan(options);
235 const end = span.end.bind(span);
236 span.end = (endTime, exit) => {
237 end(endTime, exit);
238 spans.push(span);
239 };
240 return span;
241 },
242 });
243 const harness = yield* makeHarness({
244 prepare: (attempt) =>
245 attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
246 });
247 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
248 initiallyDesired: true,
249 }).pipe(
250 Effect.provide(harness.dependencies),
251 Effect.provideService(RelayClientTracer, Option.some(tracer)),
252 );
253
254 yield* awaitState(
255 supervisor.state,
256 (state) => state.phase === "backoff" && state.attempt === 1,
257 );
258 const firstAttempt = spans.find((span) => span.name === "relay.connection.attempt");
259 expect(firstAttempt).toBeDefined();
260
261 yield* TestClock.adjust("3 seconds");
262 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
263
264 const attempts = spans.filter((span) => span.name === "relay.connection.attempt");
265 expect(attempts).toHaveLength(2);
266 expect(attempts[0]?.traceId).not.toBe(attempts[1]?.traceId);
267 expect(attempts[1]?.links.map((link) => link.span.spanId)).toContain(attempts[0]?.spanId);
268 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
269 }).pipe(Effect.provide(TestClock.layer())),
270 );
271
272 it.effect("does not attempt a connection until it is desired", () =>
273 Effect.gen(function* () {
274 const harness = yield* makeHarness();
275 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY).pipe(
276 Effect.provide(harness.dependencies),
277 );
278
279 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("available");
280 expect(yield* Ref.get(harness.prepareCount)).toBe(0);
281 }),
282 );
283
284 it.effect("does not let the initial connect signal cancel the first attempt", () =>
285 Effect.gen(function* () {
286 const harness = yield* makeHarness();
287 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY).pipe(
288 Effect.provide(harness.dependencies),
289 );
290
291 yield* supervisor.connect;
292 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
293
294 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
295 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
296 }),
297 );
298
299 it.effect("waits while offline and connects immediately when the network returns", () =>
300 Effect.gen(function* () {
301 const harness = yield* makeHarness({ networkStatus: "offline" });
302 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
303 initiallyDesired: true,
304 }).pipe(Effect.provide(harness.dependencies));
305
306 yield* awaitState(supervisor.state, (state) => state.phase === "offline");
307 expect(yield* Ref.get(harness.prepareCount)).toBe(0);
308
309 yield* harness.setNetworkStatus("online");
310 const ready = yield* awaitState(supervisor.state, (state) => state.phase === "connected");
311
312 expect(ready).toMatchObject({
313 desired: true,
314 network: "online",
315 phase: "connected",
316 attempt: 1,
317 generation: 1,
318 lastFailure: null,
319 });
320 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
321 }),
322 );
323
324 it.effect("resets retries when activation arrives before the network returns", () =>
325 Effect.gen(function* () {
326 const harness = yield* makeHarness();
327 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
328 initiallyDesired: true,
329 }).pipe(Effect.provide(harness.dependencies));
330
331 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
332 yield* harness.closeLatestSession();
333 yield* awaitState(
334 supervisor.state,
335 (state) => state.phase === "backoff" && state.attempt === 1,
336 );
337 yield* harness.setNetworkStatus("offline");
338 yield* awaitState(
339 supervisor.state,
340 (state) => state.phase === "offline" && state.attempt === 2,
341 );
342
343 yield* harness.wake("application-active-reconnect");
344 yield* awaitState(
345 supervisor.state,
346 (state) => state.phase === "offline" && state.attempt === 1,
347 );
348 yield* harness.setNetworkStatus("online");
349 yield* awaitState(
350 supervisor.state,
351 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
352 );
353 }),
354 );
355
356 it.effect("retries forever with exponential backoff capped at sixteen seconds", () =>
357 Effect.gen(function* () {
358 const harness = yield* makeHarness({
359 prepare: () => Effect.fail(transient()),
360 });
361 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
362 initiallyDesired: true,
363 }).pipe(Effect.provide(harness.dependencies));
364
365 yield* awaitState(
366 supervisor.state,
367 (state) => state.phase === "backoff" && state.attempt === 1,
368 );
369 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
370
371 for (const [index, delay] of [3_000, 4_000, 8_000, 16_000, 16_000, 16_000].entries()) {
372 yield* TestClock.adjust(delay);
373 yield* eventuallyState(
374 supervisor.state,
375 (state) => state.phase === "backoff" && state.attempt === index + 2,
376 );
377 }
378
379 expect(yield* Ref.get(harness.prepareCount)).toBe(7);
380 }).pipe(Effect.provide(TestClock.layer())),
381 );
382
383 it.effect("keeps the latest failure visible throughout the next connection attempt", () =>
384 Effect.gen(function* () {
385 const harness = yield* makeHarness({
386 prepare: (attempt) =>
387 attempt === 1 ? Effect.fail(transient("Relay connection timed out.")) : Effect.never,
388 });
389 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
390 initiallyDesired: true,
391 }).pipe(Effect.provide(harness.dependencies));
392
393 yield* awaitState(
394 supervisor.state,
395 (state) => state.phase === "backoff" && state.attempt === 1,
396 );
397 yield* TestClock.adjust("3 seconds");
398
399 const retrying = yield* awaitState(
400 supervisor.state,
401 (state) =>
402 state.phase === "connecting" && state.stage === "preparing" && state.attempt === 2,
403 );
404 expect(retrying).toMatchObject({
405 phase: "connecting",
406 stage: "preparing",
407 attempt: 2,
408 lastFailure: {
409 _tag: "ConnectionTransientError",
410 reason: "transport",
411 message: "Relay connection timed out.",
412 },
413 });
414 }).pipe(Effect.provide(TestClock.layer())),
415 );
416
417 it.effect("retries when a session never becomes ready", () =>
418 Effect.gen(function* () {
419 const harness = yield* makeHarness({
420 ready: () => Effect.never,
421 });
422 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
423 initiallyDesired: true,
424 }).pipe(Effect.provide(harness.dependencies));
425
426 yield* awaitState(
427 supervisor.state,
428 (state) => state.phase === "connecting" && state.stage === "synchronizing",
429 );
430 yield* TestClock.adjust("14 seconds");
431 expect((yield* SubscriptionRef.get(supervisor.state)).stage).toBe("synchronizing");
432
433 yield* TestClock.adjust("1 second");
434 const retrying = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
435
436 expect(retrying).toMatchObject({
437 phase: "backoff",
438 lastFailure: {
439 _tag: "ConnectionTransientError",
440 reason: "timeout",
441 message: "Test environment did not respond during connection setup.",
442 },
443 });
444 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
445 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
446 }).pipe(Effect.provide(TestClock.layer())),
447 );
448
449 it.effect("interrupts and releases a connection attempt when setup times out", () =>
450 Effect.gen(function* () {
451 const harness = yield* makeHarness({
452 prepare: () => Effect.never,
453 });
454 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
455 initiallyDesired: true,
456 }).pipe(Effect.provide(harness.dependencies));
457
458 yield* awaitState(
459 supervisor.state,
460 (state) => state.phase === "connecting" && state.stage === "preparing",
461 );
462 yield* TestClock.adjust("15 seconds");
463 const retrying = yield* eventuallyState(
464 supervisor.state,
465 (state) => state.phase === "backoff" && state.attempt === 1,
466 );
467
468 expect(retrying).toMatchObject({
469 lastFailure: {
470 _tag: "ConnectionTransientError",
471 reason: "timeout",
472 message: "Test environment did not respond during connection setup.",
473 },
474 });
475 }).pipe(Effect.provide(TestClock.layer())),
476 );
477
478 it.effect(
479 "shows a network hint for a stalled relay connection and clears it after recovery",
480 () =>
481 Effect.gen(function* () {
482 const harness = yield* makeHarness({
483 prepare: (attempt) =>
484 attempt === 1 ? Effect.never : Effect.succeed(PREPARED_CONNECTION),
485 });
486 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
487 initiallyDesired: true,
488 }).pipe(Effect.provide(harness.dependencies));
489
490 yield* awaitState(supervisor.state, (state) => state.phase === "connecting");
491 yield* TestClock.adjust("15 seconds");
492 const failed = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
493 expect(failed.lastFailure?.message).toBe(
494 `Test environment did not respond during connection setup. ${NETWORK_BLOCKING_HINT}`,
495 );
496
497 yield* TestClock.adjust("3 seconds");
498 const recovered = yield* awaitState(
499 supervisor.state,
500 (state) => state.phase === "connected",
501 );
502 expect(recovered.lastFailure).toBeNull();
503 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
504 }).pipe(Effect.provide(TestClock.layer())),
505 );
506
507 it.effect("converts unexpected driver defects into retryable failures", () =>
508 Effect.gen(function* () {
509 const harness = yield* makeHarness({
510 prepare: (attempt) =>
511 attempt === 1
512 ? Effect.die(new Error("Native transport defect."))
513 : Effect.succeed(PREPARED_CONNECTION),
514 });
515 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
516 initiallyDesired: true,
517 }).pipe(Effect.provide(harness.dependencies));
518
519 const failed = yield* awaitState(
520 supervisor.state,
521 (state) => state.phase === "backoff" && state.attempt === 1,
522 );
523 expect(failed).toMatchObject({
524 lastFailure: {
525 _tag: "ConnectionTransientError",
526 reason: "transport",
527 message: "Test environment connection failed unexpectedly.",
528 },
529 });
530
531 yield* TestClock.adjust("3 seconds");
532 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
533 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
534 }).pipe(Effect.provide(TestClock.layer())),
535 );
536
537 it.effect("explicit retry interrupts the current backoff", () =>
538 Effect.gen(function* () {
539 const harness = yield* makeHarness({
540 prepare: (attempt) =>
541 attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
542 });
543 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
544 initiallyDesired: true,
545 }).pipe(Effect.provide(harness.dependencies));
546
547 yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
548 yield* supervisor.retryNow;
549 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
550
551 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
552 }),
553 );
554
555 it.effect("explicit retry starts a fresh backoff sequence", () =>
556 Effect.gen(function* () {
557 const harness = yield* makeHarness({
558 prepare: () => Effect.fail(transient()),
559 });
560 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
561 initiallyDesired: true,
562 }).pipe(Effect.provide(harness.dependencies));
563
564 yield* awaitState(
565 supervisor.state,
566 (state) => state.phase === "backoff" && state.attempt === 1,
567 );
568 yield* TestClock.adjust("3 seconds");
569 yield* eventuallyState(
570 supervisor.state,
571 (state) => state.phase === "backoff" && state.attempt === 2,
572 );
573
574 yield* supervisor.retryNow;
575 yield* eventuallyState(
576 supervisor.state,
577 (state) => state.phase === "backoff" && state.attempt === 1,
578 );
579 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
580
581 yield* TestClock.adjust("2999 millis");
582 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
583 yield* TestClock.adjust("1 milli");
584 yield* eventuallyState(
585 supervisor.state,
586 (state) => state.phase === "backoff" && state.attempt === 2,
587 );
588 expect(yield* Ref.get(harness.prepareCount)).toBe(4);
589 }).pipe(Effect.provide(TestClock.layer())),
590 );
591
592 it.effect("keeps blocked failures idle until an external signal requests another attempt", () =>
593 Effect.gen(function* () {
594 const harness = yield* makeHarness({
595 prepare: (attempt) =>
596 attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION),
597 });
598 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
599 initiallyDesired: true,
600 }).pipe(Effect.provide(harness.dependencies));
601
602 yield* awaitState(supervisor.state, (state) => state.phase === "blocked");
603 yield* TestClock.adjust("1 hour");
604 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
605
606 yield* supervisor.retryNow;
607 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
608 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
609 }).pipe(Effect.provide(TestClock.layer())),
610 );
611
612 it.effect("resets retries when activation wakes a blocked connection", () =>
613 Effect.gen(function* () {
614 const harness = yield* makeHarness({
615 prepare: (attempt) =>
616 attempt === 1
617 ? Effect.fail(transient())
618 : attempt === 2
619 ? Effect.fail(blocked())
620 : Effect.succeed(PREPARED_CONNECTION),
621 });
622 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
623 initiallyDesired: true,
624 }).pipe(Effect.provide(harness.dependencies));
625
626 yield* awaitState(
627 supervisor.state,
628 (state) => state.phase === "backoff" && state.attempt === 1,
629 );
630 yield* TestClock.adjust("3 seconds");
631 yield* awaitState(
632 supervisor.state,
633 (state) => state.phase === "blocked" && state.attempt === 2,
634 );
635
636 yield* harness.wake("application-active-reconnect");
637 yield* awaitState(
638 supervisor.state,
639 (state) => state.phase === "connected" && state.attempt === 1,
640 );
641 }).pipe(Effect.provide(TestClock.layer())),
642 );
643
644 it.effect("releases a live session while offline and starts a new generation when online", () =>
645 Effect.gen(function* () {
646 const harness = yield* makeHarness();
647 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
648 initiallyDesired: true,
649 }).pipe(Effect.provide(harness.dependencies));
650
651 yield* awaitState(
652 supervisor.state,
653 (state) => state.phase === "connected" && state.generation === 1,
654 );
655 yield* harness.setNetworkStatus("offline");
656 yield* awaitState(supervisor.state, (state) => state.phase === "offline");
657
658 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
659 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
660
661 yield* harness.setNetworkStatus("online");
662 yield* awaitState(
663 supervisor.state,
664 (state) => state.phase === "connected" && state.generation === 2,
665 );
666 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
667 }),
668 );
669
670 it.effect("retries a blocked connection when platform credentials change", () =>
671 Effect.gen(function* () {
672 const harness = yield* makeHarness({
673 prepare: (attempt) =>
674 attempt === 1 ? Effect.fail(blocked()) : Effect.succeed(PREPARED_CONNECTION),
675 });
676 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
677 initiallyDesired: true,
678 }).pipe(Effect.provide(harness.dependencies));
679
680 yield* awaitState(supervisor.state, (state) => state.phase === "blocked");
681 yield* harness.wake("credentials-changed");
682 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
683
684 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
685 }),
686 );
687
688 it.effect("does not let platform wakeups reset an in-flight attempt", () =>
689 Effect.gen(function* () {
690 const firstAttemptStarted = yield* Deferred.make<void>();
691 const harness = yield* makeHarness({
692 prepare: () =>
693 Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never)),
694 });
695 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
696 initiallyDesired: true,
697 }).pipe(Effect.provide(harness.dependencies));
698
699 yield* Deferred.await(firstAttemptStarted);
700 yield* Effect.all(
701 [
702 harness.wake("credentials-changed"),
703 harness.wake("application-active"),
704 harness.wake("credentials-changed"),
705 ],
706 { concurrency: "unbounded" },
707 );
708 yield* Effect.yieldNow;
709
710 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
711
712 yield* TestClock.adjust("15 seconds");
713 const retrying = yield* eventuallyState(
714 supervisor.state,
715 (state) => state.phase === "backoff" && state.attempt === 1,
716 );
717
718 expect(retrying).toMatchObject({
719 lastFailure: {
720 _tag: "ConnectionTransientError",
721 reason: "timeout",
722 message: "Test environment did not respond during connection setup.",
723 },
724 });
725 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
726 expect(yield* Ref.get(harness.sessionCount)).toBe(0);
727 }).pipe(Effect.provide(TestClock.layer())),
728 );
729
730 it.effect("treats an involuntary session close as transient and reconnects", () =>
731 Effect.gen(function* () {
732 const harness = yield* makeHarness();
733 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
734 initiallyDesired: true,
735 }).pipe(Effect.provide(harness.dependencies));
736
737 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
738 yield* harness.closeLatestSession();
739 yield* awaitState(
740 supervisor.state,
741 (state) => state.phase === "backoff" && state.attempt === 1,
742 );
743 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
744
745 yield* TestClock.adjust("3 seconds");
746 yield* awaitState(
747 supervisor.state,
748 (state) => state.phase === "connected" && state.generation === 2,
749 );
750
751 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
752 expect(Option.isSome(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
753 }).pipe(Effect.provide(TestClock.layer())),
754 );
755
756 it.effect("keeps escalating backoff when a newly opened session flaps", () =>
757 Effect.gen(function* () {
758 const harness = yield* makeHarness();
759 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
760 initiallyDesired: true,
761 }).pipe(Effect.provide(harness.dependencies));
762
763 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
764 yield* harness.closeLatestSession();
765 yield* awaitState(
766 supervisor.state,
767 (state) => state.phase === "backoff" && state.attempt === 1,
768 );
769
770 yield* TestClock.adjust("3 seconds");
771 yield* awaitState(
772 supervisor.state,
773 (state) => state.phase === "connected" && state.generation === 2,
774 );
775 yield* harness.closeLatestSession();
776 const secondFailure = yield* awaitState(
777 supervisor.state,
778 (state) => state.phase === "backoff" && state.attempt === 2,
779 );
780
781 expect(secondFailure.retryAt).not.toBeNull();
782
783 yield* TestClock.adjust("3 seconds");
784 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
785
786 yield* TestClock.adjust("1 second");
787 yield* awaitState(
788 supervisor.state,
789 (state) => state.phase === "connected" && state.generation === 3,
790 );
791 expect(yield* Ref.get(harness.sessionCount)).toBe(3);
792 }).pipe(Effect.provide(TestClock.layer())),
793 );
794
795 it.effect("restarts the retry ladder when mobile returns to the foreground", () =>
796 Effect.gen(function* () {
797 const harness = yield* makeHarness();
798 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
799 initiallyDesired: true,
800 }).pipe(Effect.provide(harness.dependencies));
801
802 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
803 yield* harness.closeLatestSession();
804 yield* awaitState(
805 supervisor.state,
806 (state) => state.phase === "backoff" && state.attempt === 1,
807 );
808 yield* TestClock.adjust("3 seconds");
809 yield* awaitState(
810 supervisor.state,
811 (state) => state.phase === "connected" && state.generation === 2,
812 );
813 yield* harness.closeLatestSession();
814 yield* awaitState(
815 supervisor.state,
816 (state) => state.phase === "backoff" && state.attempt === 2,
817 );
818
819 yield* harness.wake("application-active-reconnect");
820 yield* awaitState(
821 supervisor.state,
822 (state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
823 );
824 yield* harness.closeLatestSession();
825 yield* awaitState(
826 supervisor.state,
827 (state) => state.phase === "backoff" && state.attempt === 1,
828 );
829
830 expect(yield* Ref.get(harness.sessionCount)).toBe(3);
831 }).pipe(Effect.provide(TestClock.layer())),
832 );
833
834 it.effect("restarts the retry ladder when a long resume replaces a connected session", () =>
835 Effect.gen(function* () {
836 const harness = yield* makeHarness();
837 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
838 initiallyDesired: true,
839 }).pipe(Effect.provide(harness.dependencies));
840
841 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
842 yield* harness.closeLatestSession();
843 yield* awaitState(
844 supervisor.state,
845 (state) => state.phase === "backoff" && state.attempt === 1,
846 );
847 yield* TestClock.adjust("3 seconds");
848 yield* awaitState(
849 supervisor.state,
850 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 2,
851 );
852
853 yield* harness.wake("application-active-reconnect");
854 yield* awaitState(
855 supervisor.state,
856 (state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
857 );
858 }).pipe(Effect.provide(TestClock.layer())),
859 );
860
861 it.effect("restarts the retry ladder when a long resume interrupts connection setup", () =>
862 Effect.gen(function* () {
863 const harness = yield* makeHarness({
864 prepare: (attempt) => (attempt === 2 ? Effect.never : Effect.succeed(PREPARED_CONNECTION)),
865 });
866 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
867 initiallyDesired: true,
868 }).pipe(Effect.provide(harness.dependencies));
869
870 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
871 yield* harness.closeLatestSession();
872 yield* awaitState(
873 supervisor.state,
874 (state) => state.phase === "backoff" && state.attempt === 1,
875 );
876 yield* TestClock.adjust("3 seconds");
877 yield* awaitState(
878 supervisor.state,
879 (state) => state.phase === "connecting" && state.attempt === 2,
880 );
881
882 yield* harness.wake("application-active-reconnect");
883 yield* awaitState(
884 supervisor.state,
885 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
886 );
887 }).pipe(Effect.provide(TestClock.layer())),
888 );
889
890 it.effect("probes the active session without reconnecting on application activation", () =>
891 Effect.gen(function* () {
892 const probeCount = yield* Ref.make(0);
893 const probeCalled = yield* Deferred.make<void>();
894 const harness = yield* makeHarness({
895 probe: () =>
896 Ref.update(probeCount, (count) => count + 1).pipe(
897 Effect.andThen(Deferred.succeed(probeCalled, undefined)),
898 ),
899 });
900 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
901 initiallyDesired: true,
902 }).pipe(Effect.provide(harness.dependencies));
903
904 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
905 yield* harness.wake("application-active");
906 yield* Deferred.await(probeCalled);
907
908 expect(yield* Ref.get(probeCount)).toBe(1);
909 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
910 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
911 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
912 }),
913 );
914
915 it.effect("immediately replaces a mobile session after a long background resume", () =>
916 Effect.gen(function* () {
917 const probeCount = yield* Ref.make(0);
918 const harness = yield* makeHarness({
919 probe: () => Ref.update(probeCount, (count) => count + 1),
920 });
921 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
922 initiallyDesired: true,
923 }).pipe(Effect.provide(harness.dependencies));
924
925 yield* awaitState(
926 supervisor.state,
927 (state) => state.phase === "connected" && state.generation === 1,
928 );
929 yield* harness.wake("application-active-reconnect");
930 yield* awaitState(
931 supervisor.state,
932 (state) => state.phase === "connected" && state.generation === 2,
933 );
934
935 expect(yield* Ref.get(probeCount)).toBe(0);
936 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
937 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
938 }),
939 );
940
941 it.effect("replaces a mobile session when a long resume interrupts an active probe", () =>
942 Effect.gen(function* () {
943 const harness = yield* makeHarness({
944 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
945 });
946 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
947 initiallyDesired: true,
948 }).pipe(Effect.provide(harness.dependencies));
949
950 yield* awaitState(
951 supervisor.state,
952 (state) => state.phase === "connected" && state.generation === 1,
953 );
954 yield* harness.wake("application-active-probe");
955 yield* Effect.yieldNow;
956 yield* harness.wake("application-active-reconnect");
957 yield* awaitState(
958 supervisor.state,
959 (state) => state.phase === "connected" && state.generation === 2,
960 );
961
962 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
963 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
964 }),
965 );
966
967 it.effect("reconnects immediately when the foreground liveness probe fails", () =>
968 Effect.gen(function* () {
969 const allowReconnect = yield* Deferred.make<void>();
970 const harness = yield* makeHarness({
971 prepare: (attempt) =>
972 attempt === 2
973 ? Deferred.await(allowReconnect).pipe(Effect.as(PREPARED_CONNECTION))
974 : Effect.succeed(PREPARED_CONNECTION),
975 probe: (attempt) =>
976 attempt === 1 ? Effect.fail(transient("The live session is stale.")) : Effect.void,
977 });
978 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
979 initiallyDesired: true,
980 }).pipe(Effect.provide(harness.dependencies));
981
982 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
983 yield* harness.wake("application-active");
984 const reconnecting = yield* awaitState(
985 supervisor.state,
986 (state) => state.phase === "connecting",
987 );
988 expect(reconnecting.attempt).toBe(1);
989 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
990
991 // No TestClock advance: a failed wake probe skips the first backoff rung.
992 yield* Deferred.succeed(allowReconnect, undefined);
993 yield* awaitState(
994 supervisor.state,
995 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
996 );
997
998 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
999 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1000 }).pipe(Effect.provide(TestClock.layer())),
1001 );
1002
1003 it.effect("keeps normal backoff when a reconnect after a failed wake probe also fails", () =>
1004 Effect.gen(function* () {
1005 const harness = yield* makeHarness({
1006 prepare: (attempt) =>
1007 attempt === 2 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
1008 probe: (attempt) =>
1009 attempt === 1 ? Effect.fail(transient("The live session is stale.")) : Effect.void,
1010 });
1011 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1012 initiallyDesired: true,
1013 }).pipe(Effect.provide(harness.dependencies));
1014
1015 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1016 yield* harness.wake("application-active");
1017 // The immediate follow-up attempt fails: only the first attempt after
1018 // the wake probe skips the ladder, so this failure backs off normally.
1019 yield* awaitState(
1020 supervisor.state,
1021 (state) => state.phase === "backoff" && state.attempt === 1,
1022 );
1023 yield* TestClock.adjust("2999 millis");
1024 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
1025 yield* TestClock.adjust("1 milli");
1026 yield* eventuallyState(
1027 supervisor.state,
1028 (state) => state.phase === "connected" && state.generation === 2,
1029 );
1030
1031 expect(yield* Ref.get(harness.prepareCount)).toBe(3);
1032 }).pipe(Effect.provide(TestClock.layer())),
1033 );
1034
1035 it.effect("uses the full tolerance window for a stalled desktop foreground probe", () =>
1036 Effect.gen(function* () {
1037 const harness = yield* makeHarness({
1038 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1039 });
1040 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1041 initiallyDesired: true,
1042 }).pipe(Effect.provide(harness.dependencies));
1043
1044 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1045 yield* harness.wake("application-active");
1046 yield* TestClock.adjust("14999 millis");
1047 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1048 yield* TestClock.adjust("1 milli");
1049 yield* awaitState(
1050 supervisor.state,
1051 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
1052 );
1053
1054 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1055 }).pipe(Effect.provide(TestClock.layer())),
1056 );
1057
1058 it.effect("quickly times out a stalled mobile foreground liveness probe", () =>
1059 Effect.gen(function* () {
1060 const harness = yield* makeHarness({
1061 probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1062 });
1063 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1064 initiallyDesired: true,
1065 }).pipe(Effect.provide(harness.dependencies));
1066
1067 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1068 yield* harness.wake("application-active-probe");
1069 yield* TestClock.adjust("3 seconds");
1070 // The timed-out wake probe reconnects immediately without a backoff
1071 // sleep: no further clock advance is needed.
1072 yield* awaitState(
1073 supervisor.state,
1074 (state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
1075 );
1076
1077 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1078 }).pipe(Effect.provide(TestClock.layer())),
1079 );
1080
1081 it.effect("honors an explicit disconnect while a foreground probe is stalled", () =>
1082 Effect.gen(function* () {
1083 const probeStarted = yield* Deferred.make<void>();
1084 const harness = yield* makeHarness({
1085 probe: () => Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)),
1086 });
1087 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1088 initiallyDesired: true,
1089 }).pipe(Effect.provide(harness.dependencies));
1090
1091 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1092 yield* harness.wake("application-active");
1093 yield* Deferred.await(probeStarted);
1094 yield* supervisor.disconnect;
1095 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1096
1097 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1098 }),
1099 );
1100
1101 it.effect("does not churn a healthy session when credentials change", () =>
1102 Effect.gen(function* () {
1103 const harness = yield* makeHarness();
1104 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1105 initiallyDesired: true,
1106 }).pipe(Effect.provide(harness.dependencies));
1107
1108 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1109 yield* harness.wake("credentials-changed");
1110 yield* Effect.yieldNow;
1111
1112 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1113 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
1114 expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
1115 }),
1116 );
1117
1118 it.effect("releases and reconnects a relay session when credentials change", () =>
1119 Effect.gen(function* () {
1120 const harness = yield* makeHarness();
1121 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1122 initiallyDesired: true,
1123 }).pipe(Effect.provide(harness.dependencies));
1124
1125 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1126 yield* harness.wake("credentials-changed");
1127 yield* awaitState(
1128 supervisor.state,
1129 (state) => state.phase === "connected" && state.generation === 2,
1130 );
1131
1132 expect(yield* Ref.get(harness.sessionCount)).toBe(2);
1133 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1134 }),
1135 );
1136
1137 it.effect("keeps a healthy relay session when its HTTP access token expires", () =>
1138 Effect.gen(function* () {
1139 const harness = yield* makeHarness({
1140 prepare: (attempt) =>
1141 Effect.succeed({
1142 ...PREPARED_CONNECTION,
1143 target: RELAY_TARGET,
1144 httpAuthorization: {
1145 _tag: "Dpop",
1146 accessToken: `access-token-${attempt}`,
1147 expiresAtEpochMs: 3_600_000 * attempt,
1148 },
1149 }),
1150 });
1151 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1152 initiallyDesired: true,
1153 }).pipe(Effect.provide(harness.dependencies));
1154
1155 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1156 const session = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
1157
1158 yield* TestClock.adjust("2 hours");
1159
1160 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1161 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
1162 expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(session);
1163 expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
1164 phase: "connected",
1165 generation: 1,
1166 });
1167 }).pipe(Effect.provide(TestClock.layer())),
1168 );
1169
1170 it.effect("refreshes HTTP authorization without replacing the active relay session", () =>
1171 Effect.gen(function* () {
1172 const endpoint = {
1173 httpBaseUrl: TARGET.httpBaseUrl,
1174 wsBaseUrl: TARGET.wsBaseUrl,
1175 providerKind: "cloudflare_tunnel" as const,
1176 };
1177 const token = yield* Ref.make(
1178 Option.some(
1179 new TokenStore.RemoteDpopAccessToken({
1180 environmentId: TARGET.environmentId,
1181 accountId: "test-account",
1182 label: TARGET.label,
1183 endpoint,
1184 accessToken: "access-token-1",
1185 expiresAtEpochMs: 3_600_000,
1186 dpopThumbprint: "test-thumbprint",
1187 }),
1188 ),
1189 );
1190 const bootstrapFails = yield* Ref.make(false);
1191 const bootstrapCalls = yield* Ref.make(0);
1192 const httpPaths: Array<string> = [];
1193 const sessionAuthorizations: Array<string | null> = [];
1194 const fetchFn = ((input, init) => {
1195 const request = new Request(input, init);
1196 const pathname = new URL(request.url).pathname;
1197 httpPaths.push(pathname);
1198 switch (pathname) {
1199 case "/.well-known/t3/environment":
1200 return Promise.resolve(
1201 Response.json({
1202 environmentId: TARGET.environmentId,
1203 label: TARGET.label,
1204 platform: { os: "linux", arch: "x64" },
1205 serverVersion: "0.0.0-test",
1206 capabilities: { repositoryIdentity: true },
1207 }),
1208 );
1209 case "/oauth/token":
1210 return Promise.resolve(
1211 Response.json({
1212 access_token: "access-token-2",
1213 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
1214 token_type: "DPoP",
1215 expires_in: 3_600,
1216 scope: AuthStandardClientScopes.join(" "),
1217 }),
1218 );
1219 case "/api/auth/websocket-ticket":
1220 return Promise.resolve(
1221 Response.json({
1222 ticket: "ws-ticket",
1223 expiresAt: "2026-09-04T01:00:00.000Z",
1224 }),
1225 );
1226 case "/api/auth/session": {
1227 const authorization = request.headers.get("authorization");
1228 sessionAuthorizations.push(authorization);
1229 return Promise.resolve(
1230 Response.json({
1231 authenticated: authorization === "DPoP access-token-2",
1232 auth: {
1233 policy: "loopback-browser",
1234 bootstrapMethods: ["one-time-token"],
1235 sessionMethods: ["dpop-access-token"],
1236 sessionCookieName: "t3_session_test",
1237 },
1238 scopes: AuthStandardClientScopes,
1239 }),
1240 );
1241 }
1242 default:
1243 return Promise.reject(new Error(`Unexpected HTTP request to ${request.url}`));
1244 }
1245 }) satisfies typeof fetch;
1246 const signer = ManagedRelay.ManagedRelayDpopSigner.of({
1247 thumbprint: Effect.succeed("test-thumbprint"),
1248 createProof: () => Effect.succeed("test-proof"),
1249 });
1250 const unused = () => Effect.die("Unexpected relay operation.");
1251 const relay = ManagedRelay.ManagedRelayClient.of({
1252 relayUrl: "https://relay.example.test",
1253 listEnvironments: unused,
1254 listDevices: unused,
1255 createEnvironmentLinkChallenge: unused,
1256 linkEnvironment: unused,
1257 unlinkEnvironment: unused,
1258 getEnvironmentStatus: unused,
1259 connectEnvironment: Effect.fn("TestConnectionHttp.connectEnvironment")(function* () {
1260 yield* Ref.update(bootstrapCalls, (count) => count + 1);
1261 if (yield* Ref.get(bootstrapFails)) {
1262 return yield* new ManagedRelay.ManagedRelayRequestTimeoutError({
1263 activity: "Relay environment connection",
1264 timeoutMs: 6_000,
1265 traceId: null,
1266 });
1267 }
1268 return {
1269 environmentId: TARGET.environmentId,
1270 endpoint,
1271 credential: "relay-bootstrap",
1272 expiresAt: "2026-09-04T01:00:00.000Z",
1273 };
1274 }),
1275 registerDevice: unused,
1276 unregisterDevice: unused,
1277 registerLiveActivity: unused,
1278 getAgentActivitySnapshot: unused,
1279 resetTokenCache: Effect.void,
1280 });
1281 const httpLayer = remoteHttpClientLayer(fetchFn);
1282 const remoteAuthorization = yield* RemoteEnvironmentAuthorization.make.pipe(
1283 Effect.provide(
1284 Layer.mergeAll(
1285 httpLayer,
1286 Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer),
1287 Layer.succeed(ManagedRelay.ManagedRelayClient, relay),
1288 Layer.succeed(ClientCapabilities.CloudSession, {
1289 identity: Effect.succeedSome({ accountId: "test-account" }),
1290 clerkToken: Effect.succeed("clerk-token"),
1291 }),
1292 Layer.succeed(ClientCapabilities.RelayDeviceIdentity, {
1293 deviceId: Effect.succeedNone,
1294 }),
1295 TokenStore.layer({
1296 get: () => Ref.get(token),
1297 put: (value) => Ref.set(token, Option.some(value)),
1298 remove: () => Ref.set(token, Option.none()),
1299 }),
1300 Layer.succeed(ClientCapabilities.ClientPresentation, {
1301 metadata: { label: "Test client", deviceType: "desktop" },
1302 scopes: AuthStandardClientScopes,
1303 }),
1304 ),
1305 ),
1306 );
1307 const harness = yield* makeHarness({
1308 prepare: () =>
1309 remoteAuthorization
1310 .authorizeDpop({ expectedEnvironmentId: TARGET.environmentId })
1311 .pipe(Effect.map((prepared) => ({ ...prepared, target: RELAY_TARGET }))),
1312 });
1313 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1314 initiallyDesired: true,
1315 }).pipe(Effect.provide(harness.dependencies));
1316 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1317 const session = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
1318 const prepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
1319 const readSession = fetchEnvironmentSessionState({
1320 prepared,
1321 signer: Option.some(signer),
1322 remoteAuthorization: Option.some(remoteAuthorization),
1323 }).pipe(Effect.provide(httpLayer));
1324
1325 yield* TestClock.adjust("2 hours");
1326 expect((yield* readSession).authenticated).toBe(true);
1327 expect(sessionAuthorizations).toEqual(["DPoP access-token-2"]);
1328 expect(yield* Ref.get(bootstrapCalls)).toBe(1);
1329 expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(session);
1330 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
1331 expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
1332 phase: "connected",
1333 generation: 1,
1334 });
1335
1336 yield* TestClock.adjust("2 hours");
1337 yield* Ref.set(bootstrapFails, true);
1338 const failure = yield* readSession.pipe(Effect.flip);
1339 expect(failure._tag).toBe("RemoteEnvironmentAuthFetchError");
1340 expect(yield* Ref.get(bootstrapCalls)).toBe(2);
1341 expect(sessionAuthorizations).toEqual(["DPoP access-token-2"]);
1342 expect(httpPaths.filter((path) => path === "/api/auth/websocket-ticket")).toHaveLength(1);
1343 expect(httpPaths.filter((path) => path === "/oauth/token")).toHaveLength(1);
1344 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1345 expect(yield* Ref.get(harness.releaseCount)).toBe(0);
1346 expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(session);
1347 expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
1348 phase: "connected",
1349 generation: 1,
1350 });
1351 }).pipe(Effect.provide(TestClock.layer())),
1352 );
1353
1354 it.effect("interrupts relay setup when credentials change", () =>
1355 Effect.gen(function* () {
1356 const firstAttemptStarted = yield* Deferred.make<void>();
1357 const harness = yield* makeHarness({
1358 prepare: (attempt) =>
1359 attempt === 1
1360 ? Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never))
1361 : Effect.succeed(PREPARED_CONNECTION),
1362 });
1363 const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
1364 initiallyDesired: true,
1365 }).pipe(Effect.provide(harness.dependencies));
1366
1367 yield* Deferred.await(firstAttemptStarted);
1368 yield* harness.wake("credentials-changed");
1369 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1370
1371 expect(yield* Ref.get(harness.prepareCount)).toBe(2);
1372 expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1373 }),
1374 );
1375
1376 it.effect("explicit disconnect releases the session and returns to available", () =>
1377 Effect.gen(function* () {
1378 const harness = yield* makeHarness();
1379 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1380 initiallyDesired: true,
1381 }).pipe(Effect.provide(harness.dependencies));
1382
1383 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1384 yield* supervisor.disconnect;
1385 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1386
1387 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1388 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
1389 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
1390 }),
1391 );
1392
1393 it.effect("does not lose an explicit disconnect among concurrent wakeup signals", () =>
1394 Effect.gen(function* () {
1395 const harness = yield* makeHarness();
1396 const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1397 initiallyDesired: true,
1398 }).pipe(Effect.provide(harness.dependencies));
1399
1400 yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1401 yield* Effect.all(
1402 [
1403 supervisor.disconnect,
1404 harness.wake("credentials-changed"),
1405 harness.wake("application-active"),
1406 harness.wake("credentials-changed"),
1407 ],
1408 { concurrency: "unbounded" },
1409 );
1410 yield* awaitState(supervisor.state, (state) => state.phase === "available");
1411
1412 expect(yield* Ref.get(harness.releaseCount)).toBe(1);
1413 expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
1414 }),
1415 );
1416});