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