The best way to control Claude Code, Codex and more from any computer or phone
fix(client-runtime): iOS resume keeps live sockets and drops dead ones 4x faster (#25824)
Co-authored-by: Omar <76748259+omar9848492@users.noreply.github.com> Co-authored-by: Carlos D. Escobar-Valbuena <carlosdavidescobar@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 27, 2026 at 01:58 UTC
e5f2e5dbbc5c7864aefdeccaca18284d023edc37
23 files changed
+569
-64
apps/mobile/src/connection/app-state-wakeups.ts
+4
-4
@@ -1,10 +1,10 @@
1
import type { Wakeups } from "@t3tools/client-runtime/connection";
2
3
-export const MOBILE_BACKGROUND_RECONNECT_AFTER_MS = 10_000;
3
+export const MOBILE_LONG_BACKGROUND_AFTER_MS = 10_000;
4
5
export type MobileApplicationActiveWakeup = Extract<
6
Wakeups.ConnectionWakeup,
7
- "application-active-probe" | "application-active-reconnect"
7
+ "application-active-probe" | "application-active-long"
8
>;
9
10
export function mobileApplicationActiveWakeup(
@@ -12,7 +12,7 @@ export function mobileApplicationActiveWakeup(
12
activeAtMs: number,
13
): MobileApplicationActiveWakeup {
14
return backgroundedAtMs !== null &&
15
- activeAtMs - backgroundedAtMs >= MOBILE_BACKGROUND_RECONNECT_AFTER_MS
16
- ? "application-active-reconnect"
15
+ activeAtMs - backgroundedAtMs >= MOBILE_LONG_BACKGROUND_AFTER_MS
16
+ ? "application-active-long"
17
: "application-active-probe";
18
}
apps/mobile/src/connection/platform.ts
+1
-1
@@ -118,7 +118,7 @@ const networkPathChanges = Stream.callback<"network-changed">((queue) =>
118
const layerWakeups = Wakeups.layer({
119
changes: Stream.mergeAll(
120
[
121
- Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
121
+ Stream.callback<"application-active-probe" | "application-active-long">((queue) =>
122
Effect.acquireRelease(
123
Effect.sync(() => {
124
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
apps/web/src/cloud/linkEnvironment.test.ts
+1
@@ -85,6 +85,7 @@ function layerRegistry(options?: {
85
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
86
ready: Effect.void,
87
probe: Effect.void,
88
+ inboundFrames: Effect.succeed(0),
89
closed: Effect.never,
90
};
91
const target = new PrimaryConnectionTarget({
apps/web/test/fakeEnvironment.ts
+2
@@ -377,6 +377,7 @@ const session: EnvironmentConnectionLease["session"] = {
377
subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]),
378
ready: Effect.void,
379
probe: Effect.void,
380
+ inboundFrames: Effect.succeed(0),
381
closed: Effect.never,
382
};
383
@@ -398,6 +399,7 @@ export const fakeDriver = {
399
}),
400
checkRoute: () => Effect.succeed<RouteCheck>("answered"),
401
preflight: () => Effect.succeed(true),
402
+ checkHost: () => Effect.succeed<RouteCheck>("unchecked"),
403
};
404
export type FakeDriver = typeof fakeDriver;
405
docs/internals/connection-runtime.md
+17
-8
@@ -16,14 +16,23 @@ client of a restarted server reconnects in the same second; with a short cap, a
16
client that can never connect retries all day. Offline states and authentication
17
failures wait for a wakeup instead of spending attempts on unchanged conditions.
18
19
-Foregrounding, an explicit retry, and an offline report probe the established
20
-session, and only a failed probe reconnects. Offline reports are often wrong, for
21
-example for a loopback server. A long mobile background suspension is the one
22
-exception: it replaces the session at once, because the OS can kill a socket
23
-without reporting closure, and a probe would hold a dead socket in "Resuming"
24
-until it times out. That fresh attempt runs even while the network reports
25
-offline. Foregrounding also wakes a pending retry immediately and
26
-leaves an ordinary in-flight attempt alone.
19
+Foregrounding, a network change, an explicit retry, and an offline report probe
20
+the established session, and only a failed probe reconnects. Offline reports are
21
+often wrong, for example for a loopback server. The OS can kill a suspended
22
+socket without a close event, so a probe still unanswered after 500 ms asks the
23
+host for its public descriptor over a fresh request, again each second until it
24
+answers. If the host answers while the socket delivers no frame, the socket is
25
+dead and is replaced, even while the network reports offline: at once on
26
+loopback and LAN, and 2.5 seconds after the check starts elsewhere, where one
27
+lost packet can stall a live socket. Without that evidence the probe deadline
28
+decides: 3 seconds on loopback and LAN routes and after a long mobile
29
+suspension, when the data on screen is stale; 15 seconds elsewhere, because a
30
+tailnet over DERP or a VPN can be slower than that on a live socket. A long
31
+suspension's probe that times out also replaces the socket regardless of the
32
+network report. The web and desktop foreground probe skips the fresh request,
33
+because a busy host can answer it before a queued probe. Foregrounding also
34
+wakes a pending retry immediately. A long suspension restarts an in-flight
35
+attempt; a short one leaves it alone.
36
37
The [registry](../../packages/client-runtime/src/connection/registry.ts) scopes
38
connections by environment. An involuntary disconnect retains the registration
packages/client-runtime/src/connection/driver.ts
+24
-8
@@ -4,6 +4,7 @@ import * as Exit from "effect/Exit";
4
import * as Fiber from "effect/Fiber";
5
import * as Layer from "effect/Layer";
6
import * as Scope from "effect/Scope";
7
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
8
import * as HttpClient from "effect/http/HttpClient";
9
10
import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
@@ -61,6 +62,8 @@ export class ConnectionDriver extends Context.Service<
62
entry: ConnectionCatalogEntry,
63
route: ConnectionRoute,
64
) => Effect.Effect<boolean>;
65
+ /** Asks the host behind a live session to answer a fresh request on the session's own origin. */
66
+ readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;
67
}
68
>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
69
@@ -142,26 +145,39 @@ export const make = Effect.gen(function* () {
145
const sessions = yield* RpcSession.RpcSessionFactory;
146
const httpClient = yield* HttpClient.HttpClient;
147
145
- const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
146
- const httpBaseUrl = routeHttpBaseUrl(route);
147
- if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
148
- // The descriptor is public, so this sends no credential to whatever
149
- // answers at a saved LAN address on a different network.
150
- return fetchRemoteEnvironmentDescriptor({
148
+ // The descriptor is public, so this sends no credential to whatever
149
+ // answers at a saved LAN address on a different network.
150
+ const checkDescriptor = (httpBaseUrl: string, environmentId: string) =>
151
+ fetchRemoteEnvironmentDescriptor({
152
httpBaseUrl,
153
timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
154
}).pipe(
155
Effect.map((descriptor): RouteCheck =>
155
- descriptor.environmentId === entry.target.environmentId ? "answered" : "silent",
156
+ descriptor.environmentId === environmentId ? "answered" : "silent",
157
),
158
Effect.orElseSucceed((): RouteCheck => "silent"),
159
+ // A cached descriptor would answer for a host that cannot be reached.
160
+ Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
161
Effect.provideService(HttpClient.HttpClient, httpClient),
162
+ );
163
+
164
+ const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
165
+ const httpBaseUrl = routeHttpBaseUrl(route);
166
+ if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
167
+ return checkDescriptor(httpBaseUrl, entry.target.environmentId).pipe(
168
Effect.withSpan("ConnectionDriver.checkRoute", {
169
attributes: { "connection.target.kind": route.target._tag },
170
}),
171
);
172
};
173
174
+ const checkHost = (prepared: PreparedConnection) =>
175
+ checkDescriptor(prepared.httpBaseUrl, prepared.environmentId).pipe(
176
+ Effect.withSpan("ConnectionDriver.checkHost", {
177
+ attributes: { "connection.target.kind": prepared.target._tag },
178
+ }),
179
+ );
180
+
181
const connect = Effect.fn("ConnectionDriver.connect")(function* (
182
entry: ConnectionCatalogEntry,
183
reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
@@ -203,7 +219,7 @@ export const make = Effect.gen(function* () {
219
Effect.withSpan("ConnectionDriver.preflight"),
220
);
221
206
- return ConnectionDriver.of({ connect, checkRoute, preflight });
222
+ return ConnectionDriver.of({ connect, checkRoute, preflight, checkHost });
223
});
224
225
export const layer = Layer.effect(ConnectionDriver, make);
packages/client-runtime/src/connection/registry.test.ts
+2
@@ -413,6 +413,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
413
Stream.die(new Error("Config is not used by registry tests.")),
414
ready: Effect.void,
415
probe: Effect.void,
416
+ inboundFrames: Effect.succeed(0),
417
closed: Deferred.await(closed),
418
} satisfies RpcSession.RpcSession),
419
() => Ref.update(releasedSessions, (count) => count + 1),
@@ -432,6 +433,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
433
checkRoute: (_entry, route) => checkRoute(route),
434
preflight: (_entry, route) =>
435
checkRoute(route).pipe(Effect.map((check) => check === "answered")),
436
+ checkHost: () => Effect.succeed<ConnectionDriver.RouteCheck>("unchecked"),
437
});
438
439
const layerCache = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore);
packages/client-runtime/src/connection/supervisor.test.ts
+332
-20
@@ -98,6 +98,16 @@ const LAN_THEN_RELAY_ENTRY: ConnectionCatalogEntry = {
98
enabled: true,
99
};
100
101
+const LAN_ENTRY: ConnectionCatalogEntry = {
102
+ target: LAN_ROUTE.target,
103
+ profile: LAN_ROUTE.profile,
104
+ enabled: true,
105
+};
106
+
107
+const PROBE_CAPABLE_CONFIG = {
108
+ environment: { capabilities: { connectionProbe: true } },
109
+} as ServerConfig;
110
+
111
function preparedFor(target: ConnectionTarget): PreparedConnection {
112
return { ...PREPARED_CONNECTION, target };
113
}
@@ -137,6 +147,8 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
147
readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
148
readonly initialConfig?: (attempt: number) => Effect.Effect<ServerConfig, ConnectionAttemptError>;
149
readonly checkRoute?: (route: ConnectionRoute) => Effect.Effect<ConnectionDriver.RouteCheck>;
150
+ readonly checkHost?: (prepared: PreparedConnection) => Effect.Effect<ConnectionDriver.RouteCheck>;
151
+ readonly inboundFrames?: Effect.Effect<number>;
152
}) {
153
const networkStatus = yield* SubscriptionRef.make<NetworkStatus>(
154
options?.networkStatus ?? "online",
@@ -191,6 +203,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
203
subscribeServerConfig: (input) => TEST_RPC_CLIENT.subscribeServerConfig(input),
204
ready: options?.ready?.(attempt) ?? Effect.void,
205
probe: options?.probe?.(attempt) ?? Effect.void,
206
+ inboundFrames: options?.inboundFrames ?? Effect.succeed(0),
207
closed: Deferred.await(closed),
208
} satisfies RpcSession.RpcSession),
209
() => Ref.update(releaseCount, (count) => count + 1),
@@ -233,6 +246,9 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
246
checkRoute: (_entry, route) => checkRoute(route),
247
preflight: (_entry, route) =>
248
checkRoute(route).pipe(Effect.map((check) => check === "answered")),
249
+ checkHost: (prepared) =>
250
+ options?.checkHost?.(prepared) ??
251
+ Effect.succeed<ConnectionDriver.RouteCheck>("unchecked"),
252
}),
253
),
254
);
@@ -540,10 +556,15 @@ describe("EnvironmentSupervisor", () => {
556
}).pipe(Effect.provide(TestClock.layer())),
557
);
558
543
- it.effect("restarts the retry ladder when a long resume replaces a connected session", () =>
559
+ it.effect("restarts the retry ladder when a resume replaces a silent socket", () =>
560
Effect.gen(function* () {
545
- const harness = yield* makeHarness();
546
- const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
561
+ const harness = yield* makeHarness({
562
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
563
+ initialConfig: () => Effect.succeed(PROBE_CAPABLE_CONFIG),
564
+ probe: (attempt) => (attempt === 2 ? Effect.never : Effect.void),
565
+ checkHost: () => Effect.succeed("answered"),
566
+ });
567
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
568
initiallyDesired: true,
569
}).pipe(Effect.provide(harness.dependencies));
570
@@ -559,7 +580,8 @@ describe("EnvironmentSupervisor", () => {
580
(state) => state.phase === "connected" && state.generation === 2 && state.attempt === 2,
581
);
582
562
- yield* harness.wake("application-active-reconnect");
583
+ yield* harness.wake("application-active-long");
584
+ yield* TestClock.adjust("500 millis");
585
yield* awaitState(
586
supervisor.state,
587
(state) => state.phase === "connected" && state.generation === 3 && state.attempt === 1,
@@ -588,7 +610,7 @@ describe("EnvironmentSupervisor", () => {
610
(state) => state.phase === "connecting" && state.attempt === 2,
611
);
612
591
- yield* harness.wake("application-active-reconnect");
613
+ yield* harness.wake("application-active-long");
614
yield* awaitState(
615
supervisor.state,
616
(state) => state.phase === "connected" && state.generation === 2 && state.attempt === 1,
@@ -621,7 +643,7 @@ describe("EnvironmentSupervisor", () => {
643
}),
644
);
645
624
- it.effect("immediately replaces a mobile session after a long background resume", () =>
646
+ it.effect("keeps a live mobile session after a long background resume", () =>
647
Effect.gen(function* () {
648
const probeCount = yield* Ref.make(0);
649
const harness = yield* makeHarness({
@@ -631,46 +653,336 @@ describe("EnvironmentSupervisor", () => {
653
initiallyDesired: true,
654
}).pipe(Effect.provide(harness.dependencies));
655
656
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
657
+ yield* harness.wake("application-active-long");
658
+ yield* TestClock.adjust("5 seconds");
659
+
660
+ expect(yield* Ref.get(probeCount)).toBe(1);
661
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
662
+ expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
663
+ phase: "connected",
664
+ generation: 1,
665
+ });
666
+ }).pipe(Effect.provide(TestClock.layer())),
667
+ );
668
+
669
+ const makeSilentSocketHarness = (options?: {
670
+ readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
671
+ readonly checkHost?: (check: number) => ConnectionDriver.RouteCheck;
672
+ }) =>
673
+ Effect.gen(function* () {
674
+ const hostChecks = yield* Ref.make<ReadonlyArray<string>>([]);
675
+ const harness = yield* makeHarness({
676
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
677
+ initialConfig: () => Effect.succeed(PROBE_CAPABLE_CONFIG),
678
+ probe: options?.probe ?? ((attempt) => (attempt === 1 ? Effect.never : Effect.void)),
679
+ checkHost: (prepared) =>
680
+ Ref.updateAndGet(hostChecks, (checks) => [...checks, prepared.target._tag]).pipe(
681
+ Effect.map((checks) => options?.checkHost?.(checks.length) ?? "answered"),
682
+ ),
683
+ });
684
+ return { ...harness, hostChecks };
685
+ });
686
+
687
+ it.effect.each(["application-active-probe", "application-active-long"] as const)(
688
+ "replaces a LAN socket that stays silent while its host answers afresh (%s)",
689
+ (wakeup) =>
690
+ Effect.gen(function* () {
691
+ const harness = yield* makeSilentSocketHarness();
692
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
693
+ initiallyDesired: true,
694
+ }).pipe(Effect.provide(harness.dependencies));
695
+
696
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
697
+ yield* harness.wake(wakeup);
698
+ yield* TestClock.adjust("499 millis");
699
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
700
+
701
+ yield* TestClock.adjust("1 millis");
702
+ yield* awaitState(
703
+ supervisor.state,
704
+ (state) => state.phase === "connected" && state.generation === 2,
705
+ );
706
+ expect(yield* Ref.get(harness.hostChecks)).toEqual(["BearerConnectionTarget"]);
707
+ expect(yield* Ref.get(harness.releaseCount)).toBe(1);
708
+ }).pipe(Effect.provide(TestClock.layer())),
709
+ );
710
+
711
+ it.effect("replaces a remote socket only after 2.5 seconds of silence", () =>
712
+ Effect.gen(function* () {
713
+ const harness = yield* makeSilentSocketHarness();
714
+ const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
715
+ initiallyDesired: true,
716
+ }).pipe(Effect.provide(harness.dependencies));
717
+
718
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
719
+ yield* harness.wake("application-active-probe");
720
+ yield* TestClock.adjust("2499 millis");
721
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
722
+
723
+ yield* TestClock.adjust("1 millis");
724
yield* awaitState(
725
supervisor.state,
636
- (state) => state.phase === "connected" && state.generation === 1,
726
+ (state) => state.phase === "connected" && state.generation === 2,
727
);
638
- yield* harness.wake("application-active-reconnect");
728
+ expect(yield* Ref.get(harness.hostChecks)).toEqual(["RelayConnectionTarget"]);
729
+ }).pipe(Effect.provide(TestClock.layer())),
730
+ );
731
+
732
+ it.effect("replaces a silent socket even while the network reports offline", () =>
733
+ Effect.gen(function* () {
734
+ const harness = yield* makeSilentSocketHarness();
735
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
736
+ initiallyDesired: true,
737
+ }).pipe(Effect.provide(harness.dependencies));
738
+
739
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
740
+ yield* harness.setNetworkStatus("offline");
741
+ yield* TestClock.adjust("500 millis");
742
yield* awaitState(
743
supervisor.state,
744
(state) => state.phase === "connected" && state.generation === 2,
745
);
746
+ }).pipe(Effect.provide(TestClock.layer())),
747
+ );
748
644
- expect(yield* Ref.get(probeCount)).toBe(0);
645
- expect(yield* Ref.get(harness.sessionCount)).toBe(2);
646
- expect(yield* Ref.get(harness.releaseCount)).toBe(1);
647
- }),
749
+ it.effect("replaces a remote socket after a long resume while the network reports offline", () =>
750
+ Effect.gen(function* () {
751
+ const harness = yield* makeSilentSocketHarness();
752
+ const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
753
+ initiallyDesired: true,
754
+ }).pipe(Effect.provide(harness.dependencies));
755
+
756
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
757
+ yield* harness.setNetworkStatus("offline");
758
+ yield* harness.wake("application-active-long");
759
+ yield* TestClock.adjust("2500 millis");
760
+ yield* awaitState(
761
+ supervisor.state,
762
+ (state) => state.phase === "connected" && state.generation === 2,
763
+ );
764
+ }).pipe(Effect.provide(TestClock.layer())),
765
);
766
650
- it.effect("replaces a mobile session when a long resume interrupts an active probe", () =>
767
+ it.effect("checks the host afresh when the network changes after a frame", () =>
768
Effect.gen(function* () {
769
+ const frames = yield* Ref.make(0);
770
const harness = yield* makeHarness({
771
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
772
+ initialConfig: () => Effect.succeed(PROBE_CAPABLE_CONFIG),
773
probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
774
+ inboundFrames: Ref.get(frames),
775
+ checkHost: () => Effect.succeed("answered"),
776
});
655
- const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
777
+ const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
778
initiallyDesired: true,
779
}).pipe(Effect.provide(harness.dependencies));
780
781
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
782
+ yield* harness.wake("application-active-probe");
783
+ yield* TestClock.adjust("1 second");
784
+ yield* Ref.update(frames, (count) => count + 1);
785
+ yield* TestClock.adjust("1 second");
786
+ yield* harness.wake("network-changed");
787
+ // The running check sees the frame at 2.5 s, so a fresh one starts then.
788
+ yield* TestClock.adjust("2999 millis");
789
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
790
+
791
+ yield* TestClock.adjust("1 millis");
792
yield* awaitState(
793
supervisor.state,
661
- (state) => state.phase === "connected" && state.generation === 1,
794
+ (state) => state.phase === "connected" && state.generation === 2,
795
+ );
796
+ }).pipe(Effect.provide(TestClock.layer())),
797
+ );
798
+
799
+ it.effect("keeps a running check's window when the network changes during a long resume", () =>
800
+ Effect.gen(function* () {
801
+ const harness = yield* makeSilentSocketHarness();
802
+ const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
803
+ initiallyDesired: true,
804
+ }).pipe(Effect.provide(harness.dependencies));
805
+
806
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
807
+ yield* harness.wake("application-active-long");
808
+ yield* TestClock.adjust("1 second");
809
+ yield* harness.wake("network-changed");
810
+ yield* harness.setNetworkStatus("offline");
811
+ yield* TestClock.adjust("1500 millis");
812
+ yield* awaitState(
813
+ supervisor.state,
814
+ (state) => state.phase === "connected" && state.generation === 2,
815
+ );
816
+ }).pipe(Effect.provide(TestClock.layer())),
817
+ );
818
+
819
+ it.effect("checks the host again when one check goes unanswered", () =>
820
+ Effect.gen(function* () {
821
+ const harness = yield* makeSilentSocketHarness({
822
+ checkHost: (check) => (check === 1 ? "silent" : "answered"),
823
+ });
824
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
825
+ initiallyDesired: true,
826
+ }).pipe(Effect.provide(harness.dependencies));
827
+
828
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
829
+ yield* harness.wake("application-active-probe");
830
+ yield* TestClock.adjust("1499 millis");
831
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
832
+
833
+ yield* TestClock.adjust("1 millis");
834
+ yield* awaitState(
835
+ supervisor.state,
836
+ (state) => state.phase === "connected" && state.generation === 2,
837
+ );
838
+ expect(yield* Ref.get(harness.hostChecks)).toHaveLength(2);
839
+ }).pipe(Effect.provide(TestClock.layer())),
840
+ );
841
+
842
+ it.effect("leaves a web or desktop foreground probe to its own deadline", () =>
843
+ Effect.gen(function* () {
844
+ const harness = yield* makeSilentSocketHarness({
845
+ probe: (attempt) => (attempt === 1 ? Effect.sleep("4 seconds") : Effect.void),
846
+ });
847
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
848
+ initiallyDesired: true,
849
+ }).pipe(Effect.provide(harness.dependencies));
850
+
851
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
852
+ yield* harness.wake("application-active");
853
+ yield* TestClock.adjust("20 seconds");
854
+
855
+ expect(yield* Ref.get(harness.hostChecks)).toEqual([]);
856
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
857
+ }).pipe(Effect.provide(TestClock.layer())),
858
+ );
859
+
860
+ it.effect("checks the host when a network change arrives during a foreground probe", () =>
861
+ Effect.gen(function* () {
862
+ const harness = yield* makeSilentSocketHarness();
863
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
864
+ initiallyDesired: true,
865
+ }).pipe(Effect.provide(harness.dependencies));
866
+
867
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
868
+ yield* harness.wake("application-active");
869
+ yield* TestClock.adjust("100 millis");
870
+ yield* harness.wake("network-changed");
871
+ yield* TestClock.adjust("499 millis");
872
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
873
+
874
+ yield* TestClock.adjust("1 millis");
875
+ yield* awaitState(
876
+ supervisor.state,
877
+ (state) => state.phase === "connected" && state.generation === 2,
878
);
879
+ }).pipe(Effect.provide(TestClock.layer())),
880
+ );
881
+
882
+ it.effect("keeps waiting for the probe when a frame arrives during the host check", () =>
883
+ Effect.gen(function* () {
884
+ const frames = yield* Ref.make(0);
885
+ const harness = yield* makeHarness({
886
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
887
+ initialConfig: () => Effect.succeed(PROBE_CAPABLE_CONFIG),
888
+ probe: (attempt) => (attempt === 1 ? Effect.sleep("2 seconds") : Effect.void),
889
+ inboundFrames: Ref.get(frames),
890
+ checkHost: () => Ref.update(frames, (count) => count + 1).pipe(Effect.as("answered")),
891
+ });
892
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
893
+ initiallyDesired: true,
894
+ }).pipe(Effect.provide(harness.dependencies));
895
+
896
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
897
yield* harness.wake("application-active-probe");
664
- yield* Effect.yieldNow;
665
- yield* harness.wake("application-active-reconnect");
898
+ yield* TestClock.adjust("5 seconds");
899
+
900
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
901
+ expect((yield* SubscriptionRef.get(supervisor.state)).generation).toBe(1);
902
+ }).pipe(Effect.provide(TestClock.layer())),
903
+ );
904
+
905
+ it.effect.each([
906
+ { name: "the host does not answer a fresh request", check: "silent", capable: true },
907
+ {
908
+ name: "an older host answers probes with its full config",
909
+ check: "answered",
910
+ capable: false,
911
+ },
912
+ ] as const)("waits out a LAN resume probe when $name", ({ check, capable }) =>
913
+ Effect.gen(function* () {
914
+ const harness = yield* makeHarness({
915
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
916
+ initialConfig: () =>
917
+ Effect.succeed(
918
+ capable
919
+ ? PROBE_CAPABLE_CONFIG
920
+ : ({ environment: { capabilities: {} } } as ServerConfig),
921
+ ),
922
+ probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
923
+ checkHost: () => Effect.succeed(check),
924
+ });
925
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_ENTRY, {
926
+ initiallyDesired: true,
927
+ }).pipe(Effect.provide(harness.dependencies));
928
+
929
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
930
+ yield* harness.wake("application-active-probe");
931
+ yield* TestClock.adjust("2999 millis");
932
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
933
+
934
+ yield* TestClock.adjust("1 millis");
935
yield* awaitState(
936
supervisor.state,
937
(state) => state.phase === "connected" && state.generation === 2,
938
);
939
+ }).pipe(Effect.provide(TestClock.layer())),
940
+ );
941
671
- expect(yield* Ref.get(harness.sessionCount)).toBe(2);
672
- expect(yield* Ref.get(harness.releaseCount)).toBe(1);
673
- }),
942
+ it.effect.each(["application-active-probe", "network-changed"] as const)(
943
+ "gives a live remote socket 15 seconds to answer a %s probe",
944
+ (wakeup) =>
945
+ Effect.gen(function* () {
946
+ // A slow path delays the fresh request as much as the probe.
947
+ const harness = yield* makeSilentSocketHarness({
948
+ probe: (attempt) => (attempt === 1 ? Effect.sleep("4 seconds") : Effect.void),
949
+ checkHost: () => "silent",
950
+ });
951
+ const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
952
+ initiallyDesired: true,
953
+ }).pipe(Effect.provide(harness.dependencies));
954
+
955
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
956
+ yield* harness.wake(wakeup);
957
+ yield* TestClock.adjust("20 seconds");
958
+
959
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
960
+ expect((yield* SubscriptionRef.get(supervisor.state)).generation).toBe(1);
961
+ }).pipe(Effect.provide(TestClock.layer())),
962
+ );
963
+
964
+ it.effect("replaces an unanswered long resume probe even while the network reports offline", () =>
965
+ Effect.gen(function* () {
966
+ const harness = yield* makeHarness({
967
+ probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
968
+ });
969
+ const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
970
+ initiallyDesired: true,
971
+ }).pipe(Effect.provide(harness.dependencies));
972
+
973
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
974
+ yield* harness.wake("application-active-long");
975
+ yield* harness.setNetworkStatus("offline");
976
+ yield* TestClock.adjust("2999 millis");
977
+ expect(yield* Ref.get(harness.sessionCount)).toBe(1);
978
+
979
+ yield* TestClock.adjust("1 millis");
980
+ const reconnected = yield* awaitState(
981
+ supervisor.state,
982
+ (state) => state.phase === "connected" && state.generation === 2,
983
+ );
984
+ expect(reconnected.lastFailure).toBeNull();
985
+ }).pipe(Effect.provide(TestClock.layer())),
986
);
987
988
it.effect("reconnects immediately when the session closes during a resume probe", () =>
packages/client-runtime/src/connection/supervisor.ts
+139
-18
@@ -34,6 +34,7 @@ import {
34
connectionRouteId,
35
connectionRouteKind,
36
connectionRoutes,
37
+ type ConnectionRouteKind,
38
entryWithRoutes,
39
type ReportedEndpoint,
40
} from "./routes.ts";
@@ -47,6 +48,15 @@ const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_T
48
const synchronizationTimeout = Duration.fromInputUnsafe("75 seconds");
49
const CONNECTION_PROBE_TIMEOUT = "15 seconds";
50
const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
51
+// A probe still unanswered this long checks the host with a fresh request. If
52
+// the host answers while the socket stays silent, the socket is dead.
53
+const SILENT_SOCKET_CHECK_AFTER = "500 millis";
54
+const SILENT_SOCKET_RECHECK_EVERY = "1 second";
55
+// Off the LAN one lost packet can stall a live socket for a second, so a remote
56
+// socket must stay silent this long. It must end before
57
+// QUICK_CONNECTION_PROBE_TIMEOUT so a long resume replaces a silent socket
58
+// instead of timing out.
59
+const REMOTE_SILENT_SOCKET_AFTER = "2500 millis";
60
const BACKOFF_RESET_AFTER_MS = 30_000;
61
const BETTER_ROUTE_CHECK_INTERVAL = "60 seconds";
62
// A better route that answered the check but then failed to connect is not
@@ -521,7 +531,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
531
case "BetterRouteAvailable":
532
break;
533
case "Wakeup":
524
- if (next.reason === "application-active-reconnect") {
534
+ // An attempt that ran into a long suspension is likely stuck.
535
+ if (next.reason === "application-active-long") {
536
return true;
537
}
538
if (next.reason === "credentials-changed" && usesRelay) {
@@ -547,24 +558,35 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
558
yield* Ref.set(preferredRouteId, Option.some(next.routeId));
559
return "reset" as const;
560
}
550
- if (next._tag !== "Wakeup") {
551
- return undefined;
552
- }
553
- if (next.reason === "application-active-reconnect") {
554
- // Mobile operating systems often kill a suspended socket without a close
555
- // event. A probe would show a dead socket as "Resuming" until it times
556
- // out, so a long background resume replaces the session at once.
557
- return "reset" as const;
558
- }
561
// Only a session over T3 Connect holds the old account's credential.
560
- if (next.reason === "credentials-changed" && isRelayLease(lease)) {
562
+ if (next._tag === "Wakeup" && next.reason === "credentials-changed" && isRelayLease(lease)) {
563
yield* logManagedRelayAccountChange;
564
return "end" as const;
565
}
566
return undefined;
567
});
568
567
- const probeTimeoutFor = (next: SupervisorSignal): Duration.Input | undefined => {
569
+ const leaseRouteKind = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
570
+ currentRoutes.pipe(
571
+ Effect.map((routes) => {
572
+ const route = routes.find(
573
+ (candidate) =>
574
+ connectionRouteId(candidate.target) === connectionRouteId(lease.prepared.target),
575
+ );
576
+ return route === undefined ? undefined : connectionRouteKind(route);
577
+ }),
578
+ );
579
+
580
+ const isLongResume = (signal: SupervisorSignal) =>
581
+ signal._tag === "Wakeup" && signal.reason === "application-active-long";
582
+
583
+ const answersQuickly = (routeKind: ConnectionRouteKind | undefined) =>
584
+ routeKind === "loopback" || routeKind === "lan";
585
+
586
+ const probeTimeoutFor = (
587
+ next: SupervisorSignal,
588
+ routeKind: ConnectionRouteKind | undefined,
589
+ ): Duration.Input | undefined => {
590
switch (next._tag) {
591
case "RetryRequested":
592
return QUICK_CONNECTION_PROBE_TIMEOUT;
@@ -574,9 +596,21 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
596
if (next.reason === "application-active") {
597
return CONNECTION_PROBE_TIMEOUT;
598
}
577
- return next.reason === "application-active-probe" || next.reason === "network-changed"
599
+ // After a long suspension the data on screen is stale, so a slow
600
+ // answer reconnects as quickly as a missing one, even on a remote
601
+ // route where a reconnect takes longer than the wait it replaces.
602
+ if (next.reason === "application-active-long") {
603
+ return QUICK_CONNECTION_PROBE_TIMEOUT;
604
+ }
605
+ if (next.reason !== "application-active-probe" && next.reason !== "network-changed") {
606
+ return undefined;
607
+ }
608
+ // Only loopback and LAN answer within 3 seconds reliably. A tailnet
609
+ // over DERP, a VPN, or the relay can spike past it on a live socket;
610
+ // a dead one is still caught early by the silent socket check.
611
+ return answersQuickly(routeKind)
612
? QUICK_CONNECTION_PROBE_TIMEOUT
579
- : undefined;
613
+ : CONNECTION_PROBE_TIMEOUT;
614
case "ConnectRequested":
615
case "DisconnectRequested":
616
case "BetterRouteAvailable":
@@ -584,6 +618,42 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
618
}
619
};
620
621
+ // Ends "silent" when the host answers a fresh request while the socket
622
+ // delivers nothing, as when iOS kills a suspended socket without a close
623
+ // event, and "alive" once the socket delivers a frame. A slow or
624
+ // unreachable host never ends it.
625
+ const awaitSilentSocket = Effect.fn("EnvironmentSupervisor.awaitSilentSocket")(function* (
626
+ lease: ConnectionDriver.EnvironmentConnectionLease,
627
+ routeKind: ConnectionRouteKind | undefined,
628
+ ) {
629
+ const startedAt = yield* Clock.monotonicTimeNanos;
630
+ yield* Effect.sleep(SILENT_SOCKET_CHECK_AFTER);
631
+ // An older host answers probes with its full config, which can be slow
632
+ // enough to lose to a fresh request on a healthy socket.
633
+ const answersCheapProbe = yield* lease.session.initialConfig.pipe(
634
+ Effect.map((config) => config.environment.capabilities.connectionProbe === true),
635
+ Effect.catchCause(() => Effect.succeed(false)),
636
+ );
637
+ if (!answersCheapProbe) return yield* Effect.never;
638
+ // Frames that queued while the app was suspended have drained by now, so
639
+ // a later frame shows the path still works.
640
+ const framesBefore = yield* lease.session.inboundFrames;
641
+ const socketSilent = lease.session.inboundFrames.pipe(
642
+ Effect.map((frames) => frames === framesBefore),
643
+ );
644
+ // A radio still waking up or a stale pooled connection can fail one check.
645
+ while ((yield* driver.checkHost(lease.prepared)) !== "answered") {
646
+ if (!(yield* socketSilent)) return "alive" as const;
647
+ yield* Effect.sleep(SILENT_SOCKET_RECHECK_EVERY);
648
+ }
649
+ if (!answersQuickly(routeKind)) {
650
+ const silentFor = (yield* Clock.monotonicTimeNanos) - startedAt;
651
+ const remaining = Duration.toNanosUnsafe(REMOTE_SILENT_SOCKET_AFTER) - silentFor;
652
+ if (remaining > 0n) yield* Effect.sleep(Duration.nanos(remaining));
653
+ }
654
+ return (yield* socketSilent) ? ("silent" as const) : ("alive" as const);
655
+ });
656
+
657
// Returning to the app, an explicit retry, and the network reporting offline
658
// all probe the live session instead of replacing it, so a healthy socket is
659
// not torn down (the offline report is often wrong, for example for a
@@ -605,6 +675,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
675
Stream.runForEach(() => requestBetterRouteCheck(lease)),
676
Effect.forkScoped,
677
);
678
+ const routeKind = yield* leaseRouteKind(lease);
679
for (;;) {
680
const next = yield* takeSignal;
681
const end = yield* connectedLeaseEnd(next, lease);
@@ -617,12 +688,38 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
688
) {
689
yield* requestBetterRouteCheck(lease);
690
}
620
- const probeTimeout = probeTimeoutFor(next);
691
+ const probeTimeout = probeTimeoutFor(next, routeKind);
692
if (probeTimeout === undefined) {
693
continue;
694
}
695
yield* Ref.set(probeUnanswered, true);
696
const probe = yield* Effect.forkChild(lease.session.probe);
697
+ let silentSocket: Fiber.Fiber<"silent" | "alive"> | undefined;
698
+ // A signal during a running check, such as a network change that kills
699
+ // the socket, needs a fresh check only if the running one sees a frame.
700
+ let recheck = false;
701
+ let longResume = isLongResume(next);
702
+ const startSilentSocketCheck = Effect.gen(function* () {
703
+ silentSocket = yield* Effect.forkChild(awaitSilentSocket(lease, routeKind));
704
+ recheck = false;
705
+ });
706
+ // The web and desktop foreground probe allows a busy host 15 seconds,
707
+ // and a busy host can answer a fresh request before a queued probe.
708
+ const armSilentSocketCheck = Effect.fnUntraced(function* (signal: SupervisorSignal) {
709
+ if (signal._tag === "Wakeup" && signal.reason === "application-active") return;
710
+ if (silentSocket !== undefined) {
711
+ recheck = true;
712
+ return;
713
+ }
714
+ yield* startSilentSocketCheck;
715
+ });
716
+ yield* armSilentSocketCheck(next);
717
+ const stopProbe = Effect.suspend(() =>
718
+ Effect.all(
719
+ [Fiber.interrupt(probe), silentSocket ? Fiber.interrupt(silentSocket) : Effect.void],
720
+ { discard: true },
721
+ ),
722
+ );
723
let deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
724
for (;;) {
725
const remaining = deadline - (yield* Clock.monotonicTimeNanos);
@@ -634,15 +731,37 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
731
Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
732
Effect.as({ _tag: "TimedOut" as const }),
733
),
734
+ (silentSocket ? Fiber.join(silentSocket) : Effect.never).pipe(
735
+ Effect.map((check) =>
736
+ check === "silent"
737
+ ? { _tag: "SocketSilent" as const }
738
+ : { _tag: "SocketAlive" as const },
739
+ ),
740
+ ),
741
]);
742
+ if (probeEvent._tag === "SocketAlive") {
743
+ silentSocket = undefined;
744
+ if (recheck) yield* startSilentSocketCheck;
745
+ continue;
746
+ }
747
+ if (probeEvent._tag === "SocketSilent") {
748
+ // The host is reachable, so replace the socket at once, even while
749
+ // the network reports offline.
750
+ yield* stopProbe;
751
+ return true;
752
+ }
753
if (probeEvent._tag === "TimedOut") {
639
- yield* Fiber.interrupt(probe);
754
+ yield* stopProbe;
755
+ // A long suspension leaves the socket suspect even when the network
756
+ // reports offline, so it is replaced like a silent one.
757
+ if (longResume) return true;
758
return yield* new ConnectionTransientError({
759
reason: "timeout",
760
detail: `${target.label} did not respond to a connection health check.`,
761
});
762
}
763
if (probeEvent._tag === "ProbeCompleted") {
764
+ if (silentSocket) yield* Fiber.interrupt(silentSocket);
765
if (Exit.isSuccess(probeEvent.exit)) {
766
yield* Ref.set(probeUnanswered, false);
767
}
@@ -651,11 +770,13 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
770
}
771
const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
772
if (endDuringProbe !== undefined) {
654
- yield* Fiber.interrupt(probe);
773
+ yield* stopProbe;
774
return endDuringProbe === "reset";
775
}
657
- const signalTimeout = probeTimeoutFor(probeEvent.signal);
776
+ const signalTimeout = probeTimeoutFor(probeEvent.signal, routeKind);
777
if (signalTimeout !== undefined) {
778
+ yield* armSilentSocketCheck(probeEvent.signal);
779
+ longResume ||= isLongResume(probeEvent.signal);
780
const signalDeadline =
781
(yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
782
if (signalDeadline < deadline) deadline = signalDeadline;
packages/client-runtime/src/connection/wakeups.ts
+3
-4
@@ -5,7 +5,7 @@ import type * as Stream from "effect/Stream";
5
export type ConnectionWakeup =
6
| "application-active"
7
| "application-active-probe"
8
- | "application-active-reconnect"
8
+ | "application-active-long"
9
| "credentials-changed"
10
| "network-changed";
11
@@ -13,7 +13,7 @@ function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
13
return (
14
reason === "application-active" ||
15
reason === "application-active-probe" ||
16
- reason === "application-active-reconnect"
16
+ reason === "application-active-long"
17
);
18
}
19
@@ -21,9 +21,8 @@ export function resetsRetryBackoff(reason: ConnectionWakeup): boolean {
21
return isApplicationActiveWakeup(reason) || reason === "network-changed";
22
}
23
24
-// A long resume replaces the session, and the new session subscribes on its own.
24
export function shouldResubscribeAfterWakeup(reason: ConnectionWakeup): boolean {
26
- return reason === "application-active" || reason === "application-active-probe";
25
+ return isApplicationActiveWakeup(reason);
26
}
27
28
export class ConnectionWakeups extends Context.Service<
packages/client-runtime/src/operations/commands.performance.test.ts
+1
@@ -177,6 +177,7 @@ const makeSupervisor = Effect.fn("CommandPerformance.makeSupervisor")(function*
177
subscribeServerConfig: (requestInput) => client.subscribeServerConfig(requestInput),
178
ready: Effect.void,
179
probe: Effect.void,
180
+ inboundFrames: Effect.succeed(0),
181
closed: Effect.never,
182
};
183
return EnvironmentSupervisor.EnvironmentSupervisor.of({
packages/client-runtime/src/operations/commands.test.ts
+1
@@ -123,6 +123,7 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
123
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
124
ready: Effect.void,
125
probe: Effect.void,
126
+ inboundFrames: Effect.succeed(0),
127
closed: Effect.never,
128
};
129
return EnvironmentSupervisor.EnvironmentSupervisor.of({
packages/client-runtime/src/rpc/client.test.ts
+1
@@ -51,6 +51,7 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
51
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
52
ready: Effect.void,
53
probe: Effect.void,
54
+ inboundFrames: Effect.succeed(0),
55
closed: Effect.never,
56
};
57
}
packages/client-runtime/src/rpc/session.test.ts
+17
@@ -346,6 +346,23 @@ describe("RpcSessionFactory", () => {
346
}),
347
);
348
349
+ it.effect("counts every inbound frame, including ones that answer no request", () =>
350
+ Effect.gen(function* () {
351
+ const { factory, sockets } = yield* makeFactory();
352
+ const session = yield* factory.connect(PREPARED);
353
+ const readyFiber = yield* Effect.forkChild(session.ready);
354
+ const socket = yield* awaitSocket(sockets);
355
+ socket.open();
356
+ yield* completeInitialConfig(socket);
357
+ yield* Fiber.join(readyFiber);
358
+ const before = yield* session.inboundFrames;
359
+
360
+ socket.serverMessage(encodeJson({ _tag: "Pong" }));
361
+
362
+ expect(yield* session.inboundFrames).toBe(before + 1);
363
+ }),
364
+ );
365
+
366
it.effect("closes the websocket when the session scope is released", () =>
367
Effect.gen(function* () {
368
const { factory, sockets } = yield* makeFactory();
packages/client-runtime/src/rpc/session.ts
+16
-1
@@ -53,6 +53,8 @@ export interface RpcSession {
53
) => ServerConfigSubscription;
54
readonly ready: Effect.Effect<void, ConnectionAttemptError>;
55
readonly probe: Effect.Effect<void, ConnectionAttemptError>;
56
+ /** Frames received so far: proof the socket is alive that needs no reply. */
57
+ readonly inboundFrames: Effect.Effect<number>;
58
readonly closed: Effect.Effect<never, ConnectionAttemptError>;
59
}
60
@@ -211,9 +213,21 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
213
Effect.asVoid,
214
),
215
});
216
+ // The protocol never reopens its socket, so every frame counted here came
217
+ // from this session's one socket.
218
+ let inboundFrames = 0;
219
+ const countingWebSocketConstructor: typeof webSocketConstructor = (url, options) => {
220
+ const socket = webSocketConstructor(url, options);
221
+ socket.addEventListener("message", () => {
222
+ inboundFrames += 1;
223
+ });
224
+ return socket;
225
+ };
226
const layerSocket = Socket.layerWebSocket(connection.socketUrl, {
227
openTimeout: SOCKET_OPEN_TIMEOUT,
216
- }).pipe(Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)));
228
+ }).pipe(
229
+ Layer.provide(Layer.succeed(Socket.WebSocketConstructor, countingWebSocketConstructor)),
230
+ );
231
const layerProtocol = Layer.effect(
232
RpcClient.Protocol,
233
RpcClient.makeProtocolSocket({
@@ -417,6 +431,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
431
Effect.raceFirst(Deferred.await(disconnected)),
432
),
433
probe,
434
+ inboundFrames: Effect.sync(() => inboundFrames),
435
closed: Effect.raceFirst(
436
Deferred.await(disconnected),
437
Deferred.await(configSubscriptionClosed),
packages/client-runtime/src/state/pullRequests.test.ts
+1
@@ -513,6 +513,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
513
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
514
ready: Effect.void,
515
probe: Effect.void,
516
+ inboundFrames: Effect.succeed(0),
517
closed: Effect.never,
518
};
519
}
packages/client-runtime/src/state/server.test.ts
+1
@@ -88,6 +88,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
88
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
89
ready: Effect.void,
90
probe: Effect.void,
91
+ inboundFrames: Effect.succeed(0),
92
closed: Effect.never,
93
};
94
}
packages/client-runtime/src/state/serverUsage.test.ts
+1
@@ -135,6 +135,7 @@ const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* (
135
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
136
ready: Effect.void,
137
probe: Effect.void,
138
+ inboundFrames: Effect.succeed(0),
139
closed: Effect.never,
140
};
141
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
packages/client-runtime/src/state/shell-sync.test.ts
+1
@@ -60,6 +60,7 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
60
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
61
ready: Effect.void,
62
probe: Effect.void,
63
+ inboundFrames: Effect.succeed(0),
64
closed: Effect.never,
65
};
66
}
packages/client-runtime/src/state/threads-atoms.test.ts
+1
@@ -100,6 +100,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
100
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
101
ready: Effect.void,
102
probe: Effect.void,
103
+ inboundFrames: Effect.succeed(0),
104
closed: Effect.never,
105
};
106
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
packages/client-runtime/src/state/threads-sync.test.ts
+1
@@ -94,6 +94,7 @@ function testSession(
94
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
95
ready: Effect.void,
96
probe: Effect.void,
97
+ inboundFrames: Effect.succeed(0),
98
closed: Effect.never,
99
};
100
}
packages/client-runtime/src/state/vcs.test.ts
+1
@@ -94,6 +94,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
94
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
95
ready: Effect.void,
96
probe: Effect.void,
97
+ inboundFrames: Effect.succeed(0),
98
closed: Effect.never,
99
};
100
}
packages/client-runtime/src/state/vcsAction.test.ts
+1
@@ -89,6 +89,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
89
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
90
ready: Effect.void,
91
probe: Effect.void,
92
+ inboundFrames: Effect.succeed(0),
93
closed: Effect.never,
94
};
95
}