fix(mobile): reconnect saved environments after resume
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
d17343e41b
commit
5e4309dd12
5 files changed
+127
-4
No files matched your search
@@ -15,10 +15,15 @@ const mocks = vi.hoisted(() => {
|
||||
};
|
||||
const sessionConnection = {
|
||||
dispose: vi.fn(() => Promise.resolve()),
|
||||
reconnect: vi.fn(() => Promise.resolve()),
|
||||
};
|
||||
const sessionClient = {
|
||||
isHeartbeatFresh: vi.fn(() => false),
|
||||
};
|
||||
return {
|
||||
environmentConnection,
|
||||
sessionConnection,
|
||||
sessionClient,
|
||||
createEnvironmentConnection: vi.fn(() => environmentConnection),
|
||||
createKnownEnvironment: vi.fn((input: unknown) => input),
|
||||
createWsRpcClient: vi.fn(() => ({ rpc: true })),
|
||||
@@ -37,6 +42,7 @@ const mocks = vi.hoisted(() => {
|
||||
Promise.resolve("wss://desktop.example/ws?wsTicket=token"),
|
||||
),
|
||||
removeEnvironmentSession: vi.fn(() => null),
|
||||
getEnvironmentSession: vi.fn(() => null),
|
||||
setEnvironmentSession: vi.fn(),
|
||||
notifyEnvironmentConnectionListeners: vi.fn(),
|
||||
stopAgentAwarenessForEnvironment: vi.fn(),
|
||||
@@ -60,6 +66,10 @@ vi.mock("react-native", () => ({
|
||||
Alert: {
|
||||
alert: vi.fn(),
|
||||
},
|
||||
AppState: {
|
||||
currentState: "active",
|
||||
addEventListener: vi.fn(() => ({ remove: vi.fn() })),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
@@ -102,6 +112,7 @@ vi.mock("../lib/runtime", () => ({
|
||||
|
||||
vi.mock("./environment-session-registry", () => ({
|
||||
drainEnvironmentSessions: vi.fn(() => []),
|
||||
getEnvironmentSession: mocks.getEnvironmentSession,
|
||||
notifyEnvironmentConnectionListeners: mocks.notifyEnvironmentConnectionListeners,
|
||||
removeEnvironmentSession: mocks.removeEnvironmentSession,
|
||||
setEnvironmentSession: mocks.setEnvironmentSession,
|
||||
@@ -151,7 +162,11 @@ vi.mock("./use-terminal-session", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { connectSavedEnvironment, disconnectEnvironment } from "./use-remote-environment-registry";
|
||||
import {
|
||||
connectSavedEnvironment,
|
||||
disconnectEnvironment,
|
||||
reconnectEnvironmentConnectionsAfterAppResume,
|
||||
} from "./use-remote-environment-registry";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
const environmentId = EnvironmentId.make("env-mobile-test");
|
||||
@@ -173,7 +188,10 @@ describe("mobile remote environment registry effects", () => {
|
||||
mocks.environmentConnection.ensureBootstrapped.mockResolvedValue(undefined);
|
||||
mocks.environmentConnection.dispose.mockResolvedValue(undefined);
|
||||
mocks.sessionConnection.dispose.mockResolvedValue(undefined);
|
||||
mocks.sessionConnection.reconnect.mockResolvedValue(undefined);
|
||||
mocks.sessionClient.isHeartbeatFresh.mockReturnValue(false);
|
||||
mocks.removeEnvironmentSession.mockReturnValue(null);
|
||||
mocks.getEnvironmentSession.mockReturnValue(null);
|
||||
mocks.mobileRunPromise.mockResolvedValue("wss://desktop.example/ws?wsTicket=token");
|
||||
mocks.createDpopProof.mockReturnValue(Effect.succeed("dpop-proof"));
|
||||
mocks.refreshCloudEnvironmentConnection.mockReturnValue(Effect.die("unexpected refresh"));
|
||||
@@ -366,6 +384,32 @@ describe("mobile remote environment registry effects", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reconnects a stale saved environment session after app resume", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* connectSavedEnvironment(connection);
|
||||
vi.clearAllMocks();
|
||||
mocks.getEnvironmentSession.mockReturnValue({
|
||||
client: mocks.sessionClient,
|
||||
connection: mocks.sessionConnection,
|
||||
} as never);
|
||||
|
||||
reconnectEnvironmentConnectionsAfterAppResume("test");
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(() => {
|
||||
expect(mocks.sessionConnection.reconnect).toHaveBeenCalledTimes(1);
|
||||
}),
|
||||
);
|
||||
expect(mocks.shellSnapshotMarkPending).toHaveBeenCalledWith({
|
||||
environmentId: connection.environmentId,
|
||||
});
|
||||
expect(mocks.environmentRuntimePatch).toHaveBeenCalledWith(
|
||||
{ environmentId: connection.environmentId },
|
||||
expect.any(Function),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("disconnects and removes persisted managed endpoint state when requested", () =>
|
||||
Effect.gen(function* () {
|
||||
mocks.removeEnvironmentSession.mockReturnValue({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { Alert } from "react-native";
|
||||
import { Alert, AppState } from "react-native";
|
||||
|
||||
import {
|
||||
type EnvironmentRuntimeState,
|
||||
@@ -44,6 +44,7 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { mobileRuntime } from "../lib/runtime";
|
||||
import {
|
||||
drainEnvironmentSessions,
|
||||
getEnvironmentSession,
|
||||
notifyEnvironmentConnectionListeners,
|
||||
removeEnvironmentSession,
|
||||
setEnvironmentSession,
|
||||
@@ -70,6 +71,8 @@ import { subscribeTerminalMetadata, terminalSessionManager } from "./use-termina
|
||||
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
|
||||
const environmentConnectionAttempts = createEnvironmentConnectionAttemptRegistry();
|
||||
const SAVED_CONNECTION_BOOTSTRAP_TIMEOUT_MS = 8_000;
|
||||
const APP_RESUME_RECONNECT_COOLDOWN_MS = 2_000;
|
||||
let lastAppResumeReconnectAt = Number.NEGATIVE_INFINITY;
|
||||
|
||||
interface RemoteEnvironmentLocalState {
|
||||
readonly isLoadingSavedConnection: boolean;
|
||||
@@ -456,6 +459,71 @@ export function connectSavedEnvironment(
|
||||
});
|
||||
}
|
||||
|
||||
export function reconnectEnvironmentConnectionsAfterAppResume(reason: string): void {
|
||||
const now = Date.now();
|
||||
if (now - lastAppResumeReconnectAt < APP_RESUME_RECONNECT_COOLDOWN_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const connection of Object.values(getSavedConnectionsById())) {
|
||||
const session = getEnvironmentSession(connection.environmentId);
|
||||
if (session?.client.isHeartbeatFresh()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
lastAppResumeReconnectAt = now;
|
||||
terminalDebugLog("registry:app-resume-reconnect", {
|
||||
environmentId: connection.environmentId,
|
||||
reason,
|
||||
hasSession: session !== null,
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
void mobileRuntime
|
||||
.runPromise(
|
||||
connectSavedEnvironment(connection, {
|
||||
persist: false,
|
||||
suppressBootstrapError: true,
|
||||
}),
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
terminalDebugLog("registry:app-resume-reconnect-failed", {
|
||||
environmentId: connection.environmentId,
|
||||
reason,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
setEnvironmentConnectionStatus(connection.environmentId, "reconnecting", null);
|
||||
shellSnapshotManager.markPending({ environmentId: connection.environmentId });
|
||||
void session.connection.reconnect().catch((error: unknown) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to reconnect remote environment.";
|
||||
setEnvironmentConnectionStatus(connection.environmentId, "disconnected", message);
|
||||
terminalDebugLog("registry:app-resume-reconnect-failed", {
|
||||
environmentId: connection.environmentId,
|
||||
reason,
|
||||
error: message,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeAppResumeReconnects(): () => void {
|
||||
let previousAppState = AppState.currentState;
|
||||
const subscription = AppState.addEventListener("change", (nextAppState) => {
|
||||
const wasInactive = previousAppState !== "active";
|
||||
previousAppState = nextAppState;
|
||||
if (nextAppState === "active" && wasInactive) {
|
||||
reconnectEnvironmentConnectionsAfterAppResume("appstate");
|
||||
}
|
||||
});
|
||||
|
||||
return () => subscription.remove();
|
||||
}
|
||||
|
||||
const environmentsSortOrder = Order.mapInput(
|
||||
Order.Struct({
|
||||
environmentLabel: Order.String,
|
||||
@@ -488,6 +556,7 @@ function deriveConnectedEnvironments(
|
||||
export function useRemoteEnvironmentBootstrap() {
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const unsubscribeAppResumeReconnects = subscribeAppResumeReconnects();
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
@@ -537,6 +606,7 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribeAppResumeReconnects();
|
||||
for (const session of drainEnvironmentSessions()) {
|
||||
void session.connection.dispose();
|
||||
}
|
||||
|
||||
@@ -11,6 +11,14 @@ describe("isTransportConnectionErrorMessage", () => {
|
||||
expect(isTransportConnectionErrorMessage("SocketOpenError: ECONNREFUSED")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for React Native disconnected socket errors", () => {
|
||||
expect(
|
||||
isTransportConnectionErrorMessage(
|
||||
"The operation couldn't be completed. Socket is not connected",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for the T3 server WebSocket message", () => {
|
||||
expect(isTransportConnectionErrorMessage("Unable to connect to the T3 server WebSocket.")).toBe(
|
||||
true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const TRANSPORT_ERROR_PATTERNS = [
|
||||
/\bSocketCloseError\b/i,
|
||||
/\bSocketOpenError\b/i,
|
||||
/\bSocket is not connected\b/i,
|
||||
/Unable to connect to the T3 server WebSocket\./i,
|
||||
/\bping timeout\b/i,
|
||||
] as const;
|
||||
|
||||
@@ -788,7 +788,7 @@ describe("WsTransport", () => {
|
||||
() =>
|
||||
Stream.suspend(() => {
|
||||
attempts += 1;
|
||||
return Stream.fail(new Error("SocketCloseError: WebSocket closed"));
|
||||
return Stream.fail(new Error("Socket is not connected"));
|
||||
}),
|
||||
vi.fn(),
|
||||
{ retryDelay: 10 },
|
||||
@@ -805,7 +805,7 @@ describe("WsTransport", () => {
|
||||
});
|
||||
|
||||
expect(warnSpy).toHaveBeenCalledWith("WebSocket RPC subscription disconnected", {
|
||||
error: "SocketCloseError: WebSocket closed",
|
||||
error: "Socket is not connected",
|
||||
});
|
||||
|
||||
unsubscribe();
|
||||
|
||||
Reference in new issue
Block a user