Skip to content

Commit 1d5093b

Browse files
committed
fix(mobile): keep reconnect hardening scoped to client sessions
Keep advisory interface probes and activity reports after reconnect. Leave server socket idle timeouts unchanged. Test report recovery and the short probe timeout.
1 parent 1dd03a1 commit 1d5093b

12 files changed

Lines changed: 181 additions & 63 deletions

File tree

‎apps/mobile/src/connection/background-activity.test.ts‎

Lines changed: 126 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,139 @@
1-
import { EnvironmentId, WS_METHODS } from "@t3tools/contracts";
1+
import {
2+
AVAILABLE_CONNECTION_STATE,
3+
type ConnectionCatalogEntry,
4+
EnvironmentRegistry,
5+
EnvironmentSupervisor,
6+
type NetworkStatus,
7+
type PreparedConnection,
8+
RelayConnectionTarget,
9+
type SupervisorConnectionState,
10+
} from "@t3tools/client-runtime/connection";
11+
import type { RpcSession, WsRpcProtocolClient } from "@t3tools/client-runtime/rpc";
12+
import { type ClientActivityReportInput, EnvironmentId, WS_METHODS } from "@t3tools/contracts";
213
import { describe, expect, it } from "@effect/vitest";
14+
import * as Clock from "effect/Clock";
15+
import * as Duration from "effect/Duration";
316
import * as Effect from "effect/Effect";
17+
import * as Fiber from "effect/Fiber";
18+
import * as Layer from "effect/Layer";
19+
import * as Option from "effect/Option";
20+
import * as Queue from "effect/Queue";
21+
import * as Stream from "effect/Stream";
22+
import * as SubscriptionRef from "effect/SubscriptionRef";
23+
import * as TestClock from "effect/testing/TestClock";
24+
import { vi } from "vite-plus/test";
425

26+
import { MobileStorage } from "../persistence/mobile-storage";
27+
import { mobileBackgroundActivityReporterLayer } from "./background-activity";
528
import {
629
onRetainedMobileBackgroundScopesChange,
730
observeMobileBackgroundActivitySubscription,
831
retainedMobileBackgroundScopes,
932
} from "./background-activity-scopes";
1033

34+
vi.mock("react-native", () => ({
35+
AppState: { currentState: "active", addEventListener: () => ({ remove: () => {} }) },
36+
}));
37+
vi.mock("expo-secure-store", () => ({}));
38+
1139
describe("mobile background activity", () => {
40+
it.effect("reports activity after reconnect when the initial report had no session", () =>
41+
Effect.gen(function* () {
42+
const environmentId = EnvironmentId.make("reconnecting-environment");
43+
const target = new RelayConnectionTarget({ environmentId, label: "Test environment" });
44+
const reports = yield* Queue.unbounded<ClientActivityReportInput>();
45+
const attempts = yield* Queue.unbounded<void>();
46+
const debounceArmed = yield* Queue.sliding<void>(1);
47+
const clock = yield* Clock.Clock;
48+
const reporterClock = {
49+
...clock,
50+
sleep: Effect.fn("TestMobileActivity.sleep")(function* (duration: Duration.Duration) {
51+
if (Duration.toMillis(duration) !== 250) return yield* clock.sleep(duration);
52+
const timer = yield* clock
53+
.sleep(duration)
54+
.pipe(Effect.forkChild({ startImmediately: true }));
55+
yield* Queue.offer(debounceArmed, undefined);
56+
yield* Fiber.join(timer);
57+
}),
58+
};
59+
const state = yield* SubscriptionRef.make<SupervisorConnectionState>({
60+
...AVAILABLE_CONNECTION_STATE,
61+
desired: true,
62+
network: "online",
63+
phase: "connecting",
64+
});
65+
const session = yield* SubscriptionRef.make<Option.Option<RpcSession>>(Option.none());
66+
const supervisor = EnvironmentSupervisor.of({
67+
target,
68+
state,
69+
session,
70+
prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
71+
connect: Effect.void,
72+
disconnect: Effect.void,
73+
retryNow: Effect.void,
74+
});
75+
const registryLayer = Layer.mock(EnvironmentRegistry, {
76+
entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
77+
new Map([[environmentId, { target, profile: Option.none() }]]),
78+
),
79+
networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
80+
run: (_environmentId, effect) =>
81+
Effect.provideService(effect, EnvironmentSupervisor, supervisor).pipe(
82+
Effect.ensuring(Queue.offer(attempts, undefined)),
83+
),
84+
followStream: (_environmentId, stream) =>
85+
Stream.provideService(stream, EnvironmentSupervisor, supervisor),
86+
});
87+
yield* Layer.build(
88+
mobileBackgroundActivityReporterLayer.pipe(
89+
Layer.provide(registryLayer),
90+
Layer.provide(
91+
Layer.mock(MobileStorage, {
92+
loadOrCreateAgentAwarenessDeviceId: Effect.succeed("test-device"),
93+
}),
94+
),
95+
),
96+
).pipe(Effect.provideService(Clock.Clock, reporterClock));
97+
98+
yield* Queue.take(debounceArmed);
99+
yield* TestClock.adjust("250 millis");
100+
yield* Queue.take(attempts);
101+
yield* Queue.clear(debounceArmed);
102+
expect(yield* Queue.size(reports)).toBe(0);
103+
104+
const client = {
105+
[WS_METHODS.serverReportClientActivity]: (input: ClientActivityReportInput) =>
106+
Queue.offer(reports, input).pipe(Effect.asVoid),
107+
} satisfies Pick<WsRpcProtocolClient, typeof WS_METHODS.serverReportClientActivity>;
108+
yield* SubscriptionRef.set(
109+
session,
110+
Option.some({
111+
client: client as unknown as WsRpcProtocolClient,
112+
initialConfig: Effect.die("Activity reports do not read server config."),
113+
subscribeServerConfig: () => Stream.empty,
114+
ready: Effect.void,
115+
probe: Effect.void,
116+
closed: Effect.never,
117+
}),
118+
);
119+
yield* SubscriptionRef.update(state, (current) => ({
120+
...current,
121+
phase: "connected" as const,
122+
generation: 1,
123+
}));
124+
yield* Queue.take(debounceArmed);
125+
yield* TestClock.adjust("250 millis");
126+
expect(yield* Queue.take(reports)).toMatchObject({
127+
environmentId,
128+
clientId: "mobile-test-device",
129+
visible: true,
130+
focused: true,
131+
appState: "active",
132+
scopes: [{ type: "provider-status" }],
133+
});
134+
}).pipe(Effect.provide(TestClock.layer())),
135+
);
136+
12137
it.effect("retains VCS demand only while the mobile subscription is active", () =>
13138
Effect.gen(function* () {
14139
const environmentId = EnvironmentId.make("mobile-environment");

‎apps/mobile/src/connection/background-activity.ts‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,9 @@ export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
103103
Stream.runForEach(() => Effect.sync(requestReport)),
104104
Effect.forkScoped,
105105
);
106-
// Re-report on every newly connected session generation. The AppState
107-
// report races the reconnect (the RPC fails while the socket is down and
108-
// is ignored), so without this the server's lease can lag a resume by up
109-
// to REPORT_INTERVAL_MS, keeping provider/VCS work paused. The generation
110-
// dedup lives inside the per-supervisor stream because a replacement
111-
// supervisor restarts generations; switchMap (default concurrency)
112-
// interrupts the previous subscription set on environment changes.
106+
// A resume report can fail before the socket reconnects. Report again when
107+
// it connects. Each supervisor has its own generation counter, so restart
108+
// deduplication when the registry replaces the supervisor.
113109
const connectedGenerations = (environmentId: EnvironmentId) =>
114110
registry.followStream(
115111
environmentId,
@@ -123,10 +119,7 @@ export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
123119
),
124120
),
125121
);
126-
yield* Stream.concat(
127-
Stream.fromEffect(SubscriptionRef.get(registry.entries)),
128-
SubscriptionRef.changes(registry.entries),
129-
).pipe(
122+
yield* SubscriptionRef.changes(registry.entries).pipe(
130123
Stream.map((entries) => [...entries.keys()].sort()),
131124
Stream.changesWith((a, b) => a.length === b.length && a.every((id, i) => id === b[i])),
132125
Stream.switchMap((environmentIds) =>

‎apps/mobile/src/connection/platform.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,9 @@ const wakeupsLayer = Wakeups.layer({
109109
backgroundedAtMs = null;
110110
}
111111
});
112-
// WiFi <-> cellular keeps isConnected true while invalidating the
113-
// socket's path, so the coarse online/offline signal never fires.
114-
// Emit an advisory wakeup on interface-type changes while active;
115-
// the supervisor probes the session rather than blindly replacing
116-
// it, which keeps flapping paths cheap. Seed the current type so
117-
// the first flip after startup is detected; the listener only
118-
// reports changes.
112+
// Wi-Fi/cellular changes can keep isConnected true while the socket
113+
// stops working. Probe active sessions when the interface changes.
114+
// Seed the baseline because the listener only reports changes.
119115
let networkPath = UNKNOWN_NETWORK_PATH;
120116
void Network.getNetworkStateAsync()
121117
.then((current) => {

‎apps/server/src/httpServerOptions.test.ts‎

Lines changed: 0 additions & 13 deletions
This file was deleted.

‎apps/server/src/httpServerOptions.ts‎

Lines changed: 0 additions & 16 deletions
This file was deleted.

‎apps/server/src/server.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
1010
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
1111
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
1212
import * as ServerConfig from "./config.ts";
13-
import { bunWebSocketOptions } from "./httpServerOptions.ts";
1413
import {
1514
otlpTracesProxyRouteLayer,
1615
assetRouteLayer,
@@ -205,7 +204,20 @@ const HttpServerLive = Layer.unwrap(
205204
port: config.port,
206205
hostname: config.host ?? "127.0.0.1",
207206
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
208-
websocket: bunWebSocketOptions,
207+
websocket: {
208+
// Negotiate permessage-deflate with clients that offer it; clients
209+
// that don't still get uncompressed frames on their connection. A
210+
// dedicated compressor keeps a per-connection sliding window
211+
// (context takeover) so the compression dictionary is shared across
212+
// server-to-client frames. Decompression uses the shared
213+
// decompressor: uWebSockets' dedicated decompressor path can abort
214+
// connections (close 1006) on valid DEFLATE input — see
215+
// https://github.com/uNetworking/uWebSockets.js/issues/633.
216+
perMessageDeflate: {
217+
compress: "dedicated",
218+
decompress: "shared",
219+
},
220+
},
209221
});
210222
} else {
211223
const [NodeHttpServer, NodeHttp] = yield* Effect.all([

‎docs/internals/connection-runtime.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,17 @@ Wakeup handling differs by phase, in [supervisor.ts][supervisor]:
8080
mobile's `application-active-probe`) rather than reconnecting; a healthy
8181
session survives foregrounding. `application-active-reconnect` skips the probe
8282
and replaces the lease outright.
83+
- Mobile emits `network-path-changed` when the active network interface changes
84+
while the app is active and online. A connected supervisor probes its current
85+
session with a three-second timeout. Other phases ignore this advisory wakeup,
86+
so repeated interface changes do not shorten backoff. A failed probe uses the
87+
existing immediate reconnect path. It does not request a shell resubscription.
88+
89+
Mobile sends an activity report after each newly connected session generation.
90+
This restores the server's activity lease if the foreground report failed while
91+
the socket was down, without waiting for the 25-second reporting interval.
92+
Reports use the existing 250-millisecond debounce. Generation deduplication is
93+
per supervisor because replacement supervisors restart their counters.
8394

8495
The UI derives `available`, `offline`, `connecting`, `reconnecting`,
8596
`connected`, and `error` from supervisor state plus explicit data-sync state.

‎docs/user/remote-access.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,14 @@ With mise, asdf, fnm, or nodenv, make sure the tool's shim directory is installe
167167

168168
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
169169

170+
## Mobile network changes
171+
172+
When your phone switches between Wi-Fi and cellular while the app is active, T3 Code checks each
173+
connected environment and reconnects if it does not respond. After reconnecting, the app sends
174+
your current activity state so provider status and repository updates can resume.
175+
176+
A server at a local network address still requires access to that network.
177+
170178
## Updating a Remote Server
171179

172180
When the T3 Code web or desktop app and a remote server use different versions, a warning appears in

‎packages/client-runtime/src/connection/supervisor.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1098,7 +1098,10 @@ describe("EnvironmentSupervisor", () => {
10981098
}).pipe(Effect.provide(TestClock.layer())),
10991099
);
11001100

1101-
it.effect("quickly times out a stalled mobile foreground liveness probe", () =>
1101+
it.effect.each([
1102+
{ reason: "application-active-probe" as const },
1103+
{ reason: "network-path-changed" as const },
1104+
])("quickly times out a stalled $reason probe", ({ reason }) =>
11021105
Effect.gen(function* () {
11031106
const probeStarted = yield* Deferred.make<void>();
11041107
const harness = yield* makeHarness({
@@ -1112,7 +1115,7 @@ describe("EnvironmentSupervisor", () => {
11121115
}).pipe(Effect.provide(harness.dependencies));
11131116

11141117
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1115-
yield* harness.wake("application-active-probe");
1118+
yield* harness.wake(reason);
11161119
yield* Deferred.await(probeStarted);
11171120
yield* TestClock.adjust("3 seconds");
11181121
// The timed-out wake probe reconnects immediately without a backoff

‎packages/client-runtime/src/connection/wakeups.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,9 @@ export type ConnectionWakeup =
66
| "application-active"
77
| "application-active-probe"
88
| "application-active-reconnect"
9-
// Advisory: the network path changed shape (e.g. WiFi to cellular) while
10-
// still nominally online. The old socket often survives in appearance only,
11-
// so the supervisor probes it instead of waiting for a ping timeout. It is
12-
// ignored outside the connected state: a flapping interface must not cut
13-
// backoff delays short.
9+
// Mobile interface changes can leave the socket open on a dead route.
10+
// Probe connected sessions only. Do not shorten backoff or retry blocked
11+
// connections for this advisory wakeup.
1412
| "network-path-changed"
1513
| "credentials-changed";
1614

0 commit comments

Comments
 (0)