Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex eff1bf76aa fix(mobile): preserve startup network path changes
Co-authored-by: codex <[email protected]>
2026-08-10 13:10:11 +02:00
Julius Marmingeandcodex 68b85b9050 test(connection): make reconnect hardening deterministic
Co-authored-by: codex <[email protected]>
2026-08-10 12:58:27 +02:00
b603bacfd0 fix(mobile): probe on network path changes, report leases on reconnect
Rebuilt on main after #5561 and #5404 landed overlapping reconnect
work. What main already covers is dropped from this branch: the backoff
ladder rework replaces our jitter, wakeProbeFailed replaces our
probe-failure fast path, and the authoritative-session guard replaces
our shell warm-cache short-circuit.

What remains is the mobile-specific delta:

- New advisory `network-path-changed` wakeup: WiFi<->cellular keeps
  isConnected true while invalidating the socket's path, so the mobile
  adapter emits a wakeup on interface-type changes while active and the
  supervisor probes the session (3s bound) instead of waiting for the
  ping timeout. A failed probe rides main's wakeProbeFailed fast path;
  flapping interfaces cannot cut backoff delays short.
- Client activity is re-reported on every newly connected session
  generation; the AppState-triggered report races the reconnect and is
  dropped, leaving provider/VCS work paused server-side for up to 25s
  after a resume. Generation dedup is per-supervisor since replacements
  restart the counter.
- The RPC onPingTimeout hook is wired to logging so zombie-socket
  disconnects are distinguishable from ordinary closes.
- Server websocket idleTimeout drops to 30s from Bun's 120s default
  (clients ping every 5s, so live connections never idle), releasing a
  suspended phone's half-dead socket and buffers four times sooner.

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-10 12:58:27 +02:00
12 changed files with 344 additions and 72 deletions

No files matched your search

@@ -1,4 +1,4 @@
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
import {
type BackgroundScope,
@@ -103,6 +103,40 @@ export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
Stream.runForEach(() => Effect.sync(requestReport)),
Effect.forkScoped,
);
// Re-report on every newly connected session generation. The AppState
// report races the reconnect (the RPC fails while the socket is down and
// is ignored), so without this the server's lease can lag a resume by up
// to REPORT_INTERVAL_MS, keeping provider/VCS work paused. The generation
// dedup lives inside the per-supervisor stream because a replacement
// supervisor restarts generations; switchMap (default concurrency)
// interrupts the previous subscription set on environment changes.
const connectedGenerations = (environmentId: EnvironmentId) =>
registry.followStream(
environmentId,
Stream.unwrap(
Effect.map(EnvironmentSupervisor, (supervisor) =>
SubscriptionRef.changes(supervisor.state).pipe(
Stream.filter((state) => state.phase === "connected"),
Stream.map((state) => state.generation),
Stream.changes,
),
),
),
);
yield* Stream.concat(
Stream.fromEffect(SubscriptionRef.get(registry.entries)),
SubscriptionRef.changes(registry.entries),
).pipe(
Stream.map((entries) => [...entries.keys()].sort()),
Stream.changesWith((a, b) => a.length === b.length && a.every((id, i) => id === b[i])),
Stream.switchMap((environmentIds) =>
Stream.mergeAll(environmentIds.map(connectedGenerations), {
concurrency: "unbounded",
}),
),
Stream.runForEach(() => Effect.sync(requestReport)),
Effect.forkScoped,
);
yield* Stream.fromQueue(reportRequests).pipe(
Stream.debounce("250 millis"),
Stream.runForEach(() => report),
@@ -0,0 +1,42 @@
import { describe, expect, it } from "@effect/vitest";
import {
observeNetworkPath,
seedNetworkPathBaseline,
UNKNOWN_NETWORK_PATH,
} from "./network-path-change";
describe("network path change detection", () => {
it("does not probe when the listener matches the seeded interface", () => {
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
expect(observeNetworkPath(seeded, "WIFI")).toEqual({
baseline: { known: true, type: "WIFI" },
shouldProbe: false,
});
});
it("probes when a known interface changes", () => {
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
expect(observeNetworkPath(seeded, "CELLULAR").shouldProbe).toBe(true);
});
it("probes when the listener wins the race with the async seed", () => {
const observed = observeNetworkPath(UNKNOWN_NETWORK_PATH, "CELLULAR");
expect(observed.shouldProbe).toBe(true);
expect(seedNetworkPathBaseline(observed.baseline, "WIFI")).toEqual({
known: true,
type: "CELLULAR",
});
});
it("probes on the first known interface after an unknown observation", () => {
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
const unknown = observeNetworkPath(seeded, null);
expect(unknown.shouldProbe).toBe(false);
expect(observeNetworkPath(unknown.baseline, "CELLULAR").shouldProbe).toBe(true);
});
});
@@ -0,0 +1,41 @@
export interface NetworkPathBaseline {
readonly known: boolean;
readonly type: string | null;
}
export const UNKNOWN_NETWORK_PATH: NetworkPathBaseline = {
known: false,
type: null,
};
export function seedNetworkPathBaseline(
baseline: NetworkPathBaseline,
type: string | null,
): NetworkPathBaseline {
if (baseline.known || type === null) {
return baseline;
}
return { known: true, type };
}
export function observeNetworkPath(
baseline: NetworkPathBaseline,
type: string | null,
): {
readonly baseline: NetworkPathBaseline;
readonly shouldProbe: boolean;
} {
if (type === null) {
return {
baseline: UNKNOWN_NETWORK_PATH,
shouldProbe: false,
};
}
return {
baseline: { known: true, type },
// If the initial async seed has not landed, the first listener event may
// itself be the WiFi/cellular transition. A cheap advisory probe is safer
// than losing that transition and waiting for the socket ping timeout.
shouldProbe: !baseline.known || baseline.type !== type,
};
}
+39 -2
View File
@@ -31,6 +31,11 @@ import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
import {
observeNetworkPath,
seedNetworkPathBaseline,
UNKNOWN_NETWORK_PATH,
} from "./network-path-change";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -87,11 +92,13 @@ const connectivityLayer = Connectivity.layer({
const wakeupsLayer = Wakeups.layer({
changes: Stream.merge(
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
Stream.callback<
"application-active-probe" | "application-active-reconnect" | "network-path-changed"
>((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
return AppState.addEventListener("change", (state) => {
const appStateSubscription = AppState.addEventListener("change", (state) => {
if (state === "background") {
backgroundedAtMs = Date.now();
return;
@@ -101,6 +108,36 @@ const wakeupsLayer = Wakeups.layer({
backgroundedAtMs = null;
}
});
// WiFi <-> cellular keeps isConnected true while invalidating the
// socket's path, so the coarse online/offline signal never fires.
// Emit an advisory wakeup on interface-type changes while active;
// the supervisor probes the session rather than blindly replacing
// it, which keeps flapping paths cheap. Seed the current type so
// the first flip after startup is detected; the listener only
// reports changes.
let networkPath = UNKNOWN_NETWORK_PATH;
void Network.getNetworkStateAsync()
.then((current) => {
networkPath = seedNetworkPathBaseline(networkPath, current.type ?? null);
})
.catch(() => undefined);
const networkSubscription = Network.addNetworkStateListener((state) => {
const observation = observeNetworkPath(networkPath, state.type ?? null);
networkPath = observation.baseline;
if (
observation.shouldProbe &&
state.isConnected === true &&
AppState.currentState === "active"
) {
Queue.offerUnsafe(queue, "network-path-changed");
}
});
return {
remove: () => {
appStateSubscription.remove();
networkSubscription.remove();
},
};
}),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
+13
View File
@@ -0,0 +1,13 @@
import { expect, it } from "@effect/vitest";
import { bunWebSocketOptions } from "./httpServerOptions.ts";
it("reaps Bun websocket connections after six missed client ping windows", () => {
expect(bunWebSocketOptions).toEqual({
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
idleTimeout: 30,
});
});
+16
View File
@@ -0,0 +1,16 @@
export const bunWebSocketOptions = {
// Negotiate permessage-deflate with clients that offer it; clients that
// don't still get uncompressed frames on their connection. A dedicated
// compressor keeps a per-connection sliding window (context takeover) so the
// compression dictionary is shared across server-to-client frames.
// Decompression uses the shared decompressor: uWebSockets' dedicated
// decompressor path can abort connections (close 1006) on valid DEFLATE
// input — see https://github.com/uNetworking/uWebSockets.js/issues/633.
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
// RPC clients ping every 5s. Reaping a connection after six missed ping
// windows releases suspended-mobile sockets well before Bun's 120s default.
idleTimeout: 30,
} as const;
+2 -14
View File
@@ -10,6 +10,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
import * as ServerConfig from "./config.ts";
import { bunWebSocketOptions } from "./httpServerOptions.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
@@ -185,20 +186,7 @@ const HttpServerLive = Layer.unwrap(
port: config.port,
hostname: config.host ?? "127.0.0.1",
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
websocket: {
// Negotiate permessage-deflate with clients that offer it; clients
// that don't still get uncompressed frames on their connection. A
// dedicated compressor keeps a per-connection sliding window
// (context takeover) so the compression dictionary is shared across
// server-to-client frames. Decompression uses the shared
// decompressor: uWebSockets' dedicated decompressor path can abort
// connections (close 1006) on valid DEFLATE input — see
// https://github.com/uNetworking/uWebSockets.js/issues/633.
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
},
websocket: bunWebSocketOptions,
});
} else {
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
@@ -5,6 +5,7 @@ import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
@@ -122,13 +123,10 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
const prepareCount = yield* Ref.make(0);
const sessionCount = yield* Ref.make(0);
const releaseCount = yield* Ref.make(0);
const wakeups = yield* SubscriptionRef.make<{
readonly sequence: number;
const wakeups = yield* Queue.unbounded<{
readonly reason: ConnectionWakeups.ConnectionWakeup;
}>({
sequence: 0,
reason: "application-active",
});
readonly consumed: Deferred.Deferred<void>;
}>();
const closedSessions = yield* Ref.make<
ReadonlyArray<Deferred.Deferred<never, ConnectionTransientError>>
>([]);
@@ -180,8 +178,8 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
Layer.succeed(
ConnectionWakeups.ConnectionWakeups,
ConnectionWakeups.ConnectionWakeups.of({
changes: SubscriptionRef.changes(wakeups).pipe(
Stream.drop(1),
changes: Stream.fromQueue(wakeups).pipe(
Stream.tap((event) => Deferred.succeed(event.consumed, undefined)),
Stream.map((event) => event.reason),
),
}),
@@ -198,11 +196,13 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
sessionCount,
releaseCount,
setNetworkStatus: (status: NetworkStatus) => SubscriptionRef.set(networkStatus, status),
wake: (reason: ConnectionWakeups.ConnectionWakeup) =>
SubscriptionRef.update(wakeups, (event) => ({
sequence: event.sequence + 1,
reason,
})),
wake: Effect.fn("TestConnectionHarness.wake")(function* (
reason: ConnectionWakeups.ConnectionWakeup,
) {
const consumed = yield* Deferred.make<void>();
yield* Queue.offer(wakeups, { reason, consumed });
yield* Deferred.await(consumed);
}),
closeLatestSession: Effect.fn("TestConnectionHarness.closeLatestSession")(function* (
error = transient("Session closed."),
) {
@@ -873,6 +873,82 @@ describe("EnvironmentSupervisor", () => {
}),
);
it.effect("probes the active session when the network path changes", () =>
Effect.gen(function* () {
const probeCount = yield* Ref.make(0);
const probeCalled = yield* Deferred.make<void>();
const harness = yield* makeHarness({
probe: () =>
Ref.update(probeCount, (count) => count + 1).pipe(
Effect.andThen(Deferred.succeed(probeCalled, undefined)),
),
});
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
yield* harness.wake("network-path-changed");
yield* Deferred.await(probeCalled);
expect(yield* Ref.get(probeCount)).toBe(1);
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
}),
);
it.effect("reconnects without backoff when a probe after a path change fails", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
probe: (attempt) =>
attempt === 1
? Effect.fail(transient("The path changed under the socket."))
: Effect.void,
});
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
yield* harness.wake("network-path-changed");
// The failed wake probe skips the first backoff rung (wakeProbeFailed),
// so the replacement connects without a TestClock advance.
yield* awaitState(
supervisor.state,
(state) => state.phase === "connected" && state.generation === 2,
);
expect(yield* Ref.get(harness.sessionCount)).toBe(2);
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
}),
);
it.effect("does not cut backoff short when the network path flaps", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
prepare: () => Effect.fail(transient()),
});
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));
yield* awaitState(
supervisor.state,
(state) => state.phase === "backoff" && state.attempt === 1,
);
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
// Advisory path-change wakeups have no session to probe during backoff
// and must not trigger an early retry.
yield* harness.wake("network-path-changed");
yield* harness.wake("network-path-changed");
yield* TestClock.adjust("2999 millis");
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("backoff");
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("immediately replaces a mobile session after a long background resume", () =>
Effect.gen(function* () {
const probeCount = yield* Ref.make(0);
@@ -995,8 +1071,12 @@ describe("EnvironmentSupervisor", () => {
it.effect("uses the full tolerance window for a stalled desktop foreground probe", () =>
Effect.gen(function* () {
const probeStarted = yield* Deferred.make<void>();
const harness = yield* makeHarness({
probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
probe: (attempt) =>
attempt === 1
? Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never))
: Effect.void,
});
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
initiallyDesired: true,
@@ -1004,6 +1084,7 @@ describe("EnvironmentSupervisor", () => {
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
yield* harness.wake("application-active");
yield* Deferred.await(probeStarted);
yield* TestClock.adjust("14999 millis");
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
yield* TestClock.adjust("1 milli");
@@ -1018,8 +1099,12 @@ describe("EnvironmentSupervisor", () => {
it.effect("quickly times out a stalled mobile foreground liveness probe", () =>
Effect.gen(function* () {
const probeStarted = yield* Deferred.make<void>();
const harness = yield* makeHarness({
probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
probe: (attempt) =>
attempt === 1
? Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never))
: Effect.void,
});
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
initiallyDesired: true,
@@ -1027,6 +1112,7 @@ describe("EnvironmentSupervisor", () => {
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
yield* harness.wake("application-active-probe");
yield* Deferred.await(probeStarted);
yield* TestClock.adjust("3 seconds");
// The timed-out wake probe reconnects immediately without a backoff
// sleep: no further clock advance is needed.
@@ -418,13 +418,17 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
// replaces that lease and starts a fresh attempt without backoff.
return true;
}
if (next.reason === "application-active" || next.reason === "application-active-probe") {
if (
next.reason === "application-active" ||
next.reason === "application-active-probe" ||
next.reason === "network-path-changed"
) {
const probe = yield* lease.session.probe.pipe(
Effect.timeoutOrElse({
duration:
next.reason === "application-active-probe"
? MOBILE_CONNECTION_PROBE_TIMEOUT
: CONNECTION_PROBE_TIMEOUT,
next.reason === "application-active"
? CONNECTION_PROBE_TIMEOUT
: MOBILE_CONNECTION_PROBE_TIMEOUT,
orElse: () =>
Effect.fail(
new ConnectionTransientError({
@@ -622,6 +626,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
const next = yield* Queue.take(signals);
switch (next._tag) {
case "Wakeup":
// Path-change wakeups are advisory (probe a connected session)
// and must not cut backoff delays short on a flapping interface.
if (next.reason === "network-path-changed") {
break;
}
return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
case "ConnectRequested":
case "DisconnectRequested":
@@ -634,11 +643,16 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
);
});
const waitForSignal = Queue.take(signals).pipe(
Effect.map(
(next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
),
);
const waitForSignal = Effect.gen(function* () {
for (;;) {
const next = yield* Queue.take(signals);
if (next._tag === "Wakeup" && next.reason === "network-path-changed") {
// Advisory only; see waitForRetrySignal.
continue;
}
return next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason);
}
});
const run = Effect.fnUntraced(function* () {
let failureCount = 0;
@@ -6,6 +6,12 @@ export type ConnectionWakeup =
| "application-active"
| "application-active-probe"
| "application-active-reconnect"
// Advisory: the network path changed shape (e.g. WiFi to cellular) while
// still nominally online. The old socket often survives in appearance only,
// so the supervisor probes it instead of waiting for a ping timeout. It is
// ignored outside the connected state: a flapping interface must not cut
// backoff delays short.
| "network-path-changed"
| "credentials-changed";
export function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
@@ -91,6 +91,14 @@ export const make = Effect.gen(function* () {
),
Effect.asVoid,
),
// Distinguishes zombie-socket disconnects (missed pong after suspension
// or a silent path change) from ordinary closes in logs and telemetry.
onPingTimeout: Effect.logInfo("Connection ping timed out; treating the socket as dead.").pipe(
Effect.annotateLogs({
environmentId: connection.environmentId,
connectionLabel: connection.label,
}),
),
});
const socketLayer = Socket.layerWebSocket(connection.socketUrl, {
openTimeout: SOCKET_OPEN_TIMEOUT,
@@ -252,14 +252,13 @@ describe("environment shell synchronization", () => {
const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
const loaderCalls = yield* Ref.make(0);
const capturedAfterSequences = yield* Ref.make<ReadonlyArray<number | undefined>>([]);
const subscriptionReceipts = yield* Queue.unbounded<number | undefined>();
const client = {
[ORCHESTRATION_WS_METHODS.subscribeShell]: (input: { readonly afterSequence?: number }) =>
Stream.unwrap(
Ref.update(capturedAfterSequences, (captured) => [
...captured,
input.afterSequence,
]).pipe(Effect.as(Stream.fromQueue(events))),
Queue.offer(subscriptionReceipts, input.afterSequence).pipe(
Effect.as(Stream.fromQueue(events)),
),
),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
@@ -306,11 +305,7 @@ describe("environment shell synchronization", () => {
);
// A new session starts from an authoritative HTTP snapshot.
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(capturedAfterSequences)).length >= 1) break;
yield* Effect.yieldNow;
}
expect(yield* Ref.get(capturedAfterSequences)).toEqual([10]);
expect(yield* Queue.take(subscriptionReceipts)).toBe(10);
yield* Queue.offer(events, { kind: "synchronized" });
yield* SubscriptionRef.changes(shellState).pipe(
Stream.filter((value) => value.status === "live"),
@@ -330,35 +325,27 @@ describe("environment shell synchronization", () => {
);
yield* Queue.offer(wakeups, "application-active");
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(capturedAfterSequences)).length >= 2) break;
yield* Effect.yieldNow;
}
expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40]);
expect(yield* Queue.take(subscriptionReceipts)).toBe(40);
yield* Queue.offer(events, { kind: "synchronized" });
yield* Queue.offer(wakeups, "application-active-probe");
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(capturedAfterSequences)).length >= 3) break;
yield* Effect.yieldNow;
}
expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40]);
yield* Queue.offer(wakeups, "application-active-reconnect");
for (let attempt = 0; attempt < 10; attempt += 1) {
yield* Effect.yieldNow;
}
expect((yield* Ref.get(capturedAfterSequences)).length).toBe(3);
expect(yield* Queue.take(subscriptionReceipts)).toBe(40);
expect(yield* Ref.get(loaderCalls)).toBe(1);
// Replacing the session performs another authoritative refresh.
yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((yield* Ref.get(capturedAfterSequences)).length >= 4) break;
yield* Effect.yieldNow;
}
expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40, 20]);
expect(yield* Queue.take(subscriptionReceipts)).toBe(20);
expect(yield* Ref.get(loaderCalls)).toBe(2);
}),
);
it("only resubscribes for foreground wakeups that keep the current session", () => {
expect(ConnectionWakeups.shouldResubscribeAfterWakeup("application-active")).toBe(true);
expect(ConnectionWakeups.shouldResubscribeAfterWakeup("application-active-probe")).toBe(true);
expect(ConnectionWakeups.shouldResubscribeAfterWakeup("application-active-reconnect")).toBe(
false,
);
expect(ConnectionWakeups.shouldResubscribeAfterWakeup("network-path-changed")).toBe(false);
expect(ConnectionWakeups.shouldResubscribeAfterWakeup("credentials-changed")).toBe(false);
});
});