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