Skip to content

Commit 7f7b5d4

Browse files
fix(ui): recover suspended tabs after gateway updates
Worked on by: - @Takhoffman Co-authored-by: Takhoffman <[email protected]>
1 parent 00d542d commit 7f7b5d4

9 files changed

Lines changed: 383 additions & 53 deletions

‎ui/public/sw.js‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,26 @@ async function markClientReload(client) {
3333
guardUrl.searchParams.set("client", client.id);
3434
const guardRequest = new Request(guardUrl);
3535
if (await cache.match(guardRequest)) {
36-
return false;
36+
return null;
3737
}
3838
// Persist before navigation so repeated activation of the same build cannot
3939
// loop a document that keeps receiving stale HTML.
4040
await cache.put(guardRequest, new Response(CACHE_VERSION));
41-
return true;
41+
return { cache, guardRequest };
42+
}
43+
44+
async function navigateSuspendedClient(client) {
45+
const reloadClaim = await markClientReload(client);
46+
if (!reloadClaim) {
47+
return;
48+
}
49+
// Navigation can stay pending for the lifetime of a suspended document, so
50+
// it must not keep the replacement service worker's activation alive.
51+
void client.navigate(client.url).catch(() => {
52+
// A suspended WebKit document can reject navigation. Release ownership so
53+
// the next activation can retry instead of stranding this build forever.
54+
void reloadClaim.cache.delete(reloadClaim.guardRequest).catch(() => undefined);
55+
});
4256
}
4357

4458
function readClientVersion(client) {
@@ -91,14 +105,15 @@ self.addEventListener("activate", (event) => {
91105
windowClients
92106
.filter((client) => isControlUiChatClient(client.url))
93107
.map(async (client) => {
94-
if (
95-
(await readClientVersion(client)) !== CACHE_VERSION &&
96-
(await markClientReload(client))
97-
) {
98-
// Navigation starts synchronously; activation must not stay alive
99-
// indefinitely waiting for a document that never finishes loading.
100-
void client.navigate(client.url).catch(() => undefined);
108+
const clientVersion = await readClientVersion(client);
109+
if (clientVersion === CACHE_VERSION) {
110+
return;
111+
}
112+
if (clientVersion !== null) {
113+
client.postMessage({ type: "sw-updated", version: CACHE_VERSION }, []);
114+
return;
101115
}
116+
await navigateSuspendedClient(client);
102117
}),
103118
);
104119
})(),
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { buildDeviceAuthPayload, type ConnectParams } from "@openclaw/gateway-client/browser";
2+
import { loadOrCreateDeviceIdentity, signDevicePayload } from "../lib/nodes/index.ts";
3+
4+
export async function buildGatewayConnectDevice(params: {
5+
deviceIdentity: Awaited<ReturnType<typeof loadOrCreateDeviceIdentity>> | null;
6+
client: ConnectParams["client"];
7+
role: string;
8+
scopes: string[];
9+
authToken?: string;
10+
connectNonce: string | null;
11+
connectChallengeTs: number | null | undefined;
12+
}): Promise<NonNullable<ConnectParams["device"]> | undefined> {
13+
const { deviceIdentity } = params;
14+
if (!deviceIdentity) {
15+
return undefined;
16+
}
17+
if (params.connectChallengeTs === null) {
18+
throw new Error("gateway connect challenge timestamp invalid");
19+
}
20+
// The Control UI alone supports pre-challenge Gateways; that timeout fallback has no server time.
21+
const signedAtMs = params.connectChallengeTs ?? Date.now();
22+
const nonce = params.connectNonce ?? "";
23+
const payload = buildDeviceAuthPayload({
24+
deviceId: deviceIdentity.deviceId,
25+
clientId: params.client.id,
26+
clientMode: params.client.mode,
27+
role: params.role,
28+
scopes: params.scopes,
29+
signedAtMs,
30+
token: params.authToken ?? null,
31+
nonce,
32+
});
33+
const signature = await signDevicePayload(deviceIdentity.privateKey, payload);
34+
return {
35+
id: deviceIdentity.deviceId,
36+
publicKey: deviceIdentity.publicKey,
37+
signature,
38+
signedAt: signedAtMs,
39+
nonce,
40+
};
41+
}

‎ui/src/api/gateway.ts‎

Lines changed: 14 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {
22
buildGatewayConnectAuth,
3-
buildDeviceAuthPayload,
43
ConnectErrorDetailCodes,
54
GATEWAY_CLIENT_MODES,
65
GATEWAY_CLIENT_NAMES,
@@ -48,10 +47,10 @@ import {
4847
loadDeviceAuthToken,
4948
storeDeviceAuthToken,
5049
loadOrCreateDeviceIdentity,
51-
signDevicePayload,
5250
} from "../lib/nodes/index.ts";
5351
import { generateUUID } from "../lib/uuid.ts";
5452
import { createBrowserGatewaySocket } from "./gateway-browser-socket.ts";
53+
import { buildGatewayConnectDevice } from "./gateway-connect-device.ts";
5554
import {
5655
enrichProtocolMismatchDetails,
5756
resolveGatewayErrorDetailCode,
@@ -229,51 +228,13 @@ async function deriveLegacyV4RecoveryScope(material: string | undefined): Promis
229228
}
230229
}
231230

232-
async function buildGatewayConnectDevice(params: {
233-
deviceIdentity: Awaited<ReturnType<typeof loadOrCreateDeviceIdentity>> | null;
234-
client: ConnectParams["client"];
235-
role: string;
236-
scopes: string[];
237-
authToken?: string;
238-
connectNonce: string | null;
239-
connectChallengeTs: number | null | undefined;
240-
}): Promise<NonNullable<ConnectParams["device"]> | undefined> {
241-
const { deviceIdentity } = params;
242-
if (!deviceIdentity) {
243-
return undefined;
244-
}
245-
if (params.connectChallengeTs === null) {
246-
throw new Error("gateway connect challenge timestamp invalid");
247-
}
248-
// The Control UI alone supports pre-challenge Gateways; that timeout fallback has no server time.
249-
const signedAtMs = params.connectChallengeTs ?? Date.now();
250-
const nonce = params.connectNonce ?? "";
251-
const payload = buildDeviceAuthPayload({
252-
deviceId: deviceIdentity.deviceId,
253-
clientId: params.client.id,
254-
clientMode: params.client.mode,
255-
role: params.role,
256-
scopes: params.scopes,
257-
signedAtMs,
258-
token: params.authToken ?? null,
259-
nonce,
260-
});
261-
const signature = await signDevicePayload(deviceIdentity.privateKey, payload);
262-
return {
263-
id: deviceIdentity.deviceId,
264-
publicKey: deviceIdentity.publicKey,
265-
signature,
266-
signedAt: signedAtMs,
267-
nonce,
268-
};
269-
}
270-
271231
export class GatewayBrowserClient {
272232
private readonly client: GatewayProtocolClient<ConnectPlan>;
273233
private maxPayloadBytes: number | undefined;
274234
private scopeUpgradeRuntime: Promise<GatewayScopeUpgrade> | null = null;
275235
inboundActivitySeq = 0;
276236
private lastInboundActivityAtMs: number | null = null;
237+
private maxInboundSilenceMs: number | null = null;
277238
private tickWatchTimer: ReturnType<typeof setInterval> | null = null;
278239
private pendingDeviceTokenRetry = false;
279240
private deviceTokenRetryBudgetUsed = false;
@@ -388,6 +349,15 @@ export class GatewayBrowserClient {
388349
return this.client.connected;
389350
}
390351

352+
get needsWakeReconnect() {
353+
return (
354+
!this.client.connected ||
355+
(this.lastInboundActivityAtMs !== null &&
356+
this.maxInboundSilenceMs !== null &&
357+
Date.now() - this.lastInboundActivityAtMs > this.maxInboundSilenceMs)
358+
);
359+
}
360+
391361
get recoveryScope() {
392362
return this.recovery.value;
393363
}
@@ -569,12 +539,12 @@ export class GatewayBrowserClient {
569539
: DEFAULT_GATEWAY_TICK_INTERVAL_MS,
570540
{ minMs: MIN_GATEWAY_TICK_WATCH_INTERVAL_MS },
571541
);
542+
this.maxInboundSilenceMs = tickIntervalMs * 2;
572543
this.lastInboundActivityAtMs = Date.now();
573544
this.tickWatchTimer = setInterval(() => {
574-
const lastActivityAtMs = this.lastInboundActivityAtMs;
575545
// Preserve long-running requests while real Gateway heartbeats arrive;
576546
// only a silent socket should enter the shared reconnect lifecycle.
577-
if (lastActivityAtMs !== null && Date.now() - lastActivityAtMs > tickIntervalMs * 2) {
547+
if (this.needsWakeReconnect) {
578548
this.forceReconnect("tick timeout");
579549
}
580550
}, tickIntervalMs);
@@ -586,6 +556,7 @@ export class GatewayBrowserClient {
586556
this.tickWatchTimer = null;
587557
}
588558
this.lastInboundActivityAtMs = null;
559+
this.maxInboundSilenceMs = null;
589560
}
590561

591562
private handleConnectFailure(err: GatewayProtocolRequestError, plan: ConnectPlan) {

‎ui/src/app/bootstrap.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import type {
4848
import { applyControlUiAccent, syncControlUiSystemChrome } from "./control-ui-presentation.ts";
4949
import { syncCustomThemeStyleTag } from "./custom-theme.ts";
5050
import { createScopeUpgradeCapability } from "./device-scope-upgrade.ts";
51+
import { startGatewayPageActivation } from "./gateway-page-activation.ts";
5152
import { createApplicationGateway } from "./gateway-store.ts";
5253
import { createInitialUserMessageHandoff } from "./initial-user-message-handoff.ts";
5354
import { createNativeChatDrafts } from "./native-bridge.ts";
@@ -634,6 +635,7 @@ export function bootstrapApplication(
634635
gateway.start();
635636
return () => gateway.stop();
636637
},
638+
() => startGatewayPageActivation(gateway, document, window),
637639
() => sessionPathBuilderReady,
638640
];
639641
// Resolve first-run setup before routing: the default Chat route owns the
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/* @vitest-environment jsdom */
2+
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { startGatewayPageActivation } from "./gateway-page-activation.ts";
5+
import { refreshControlUiServiceWorker } from "./sw-refresh.runtime.ts";
6+
7+
vi.mock("./sw-refresh.runtime.ts", () => ({
8+
refreshControlUiServiceWorker: vi.fn(async () => false),
9+
}));
10+
11+
afterEach(() => {
12+
vi.mocked(refreshControlUiServiceWorker).mockClear();
13+
vi.restoreAllMocks();
14+
});
15+
16+
describe("Gateway page activation", () => {
17+
it("coalesces foreground signals into one stale-client recovery", async () => {
18+
const connect = vi.fn();
19+
const visibility = vi.spyOn(document, "visibilityState", "get");
20+
visibility.mockReturnValue("hidden");
21+
const dispose = startGatewayPageActivation(
22+
{ snapshot: { client: { needsWakeReconnect: true } }, connect },
23+
document,
24+
window,
25+
);
26+
27+
visibility.mockReturnValue("visible");
28+
document.dispatchEvent(new Event("visibilitychange"));
29+
window.dispatchEvent(new Event("online"));
30+
await Promise.resolve();
31+
32+
expect(connect).toHaveBeenCalledOnce();
33+
await vi.waitFor(() => expect(refreshControlUiServiceWorker).toHaveBeenCalledOnce());
34+
dispose();
35+
});
36+
37+
it("keeps a healthy client mounted when the browser reports online", async () => {
38+
const connect = vi.fn();
39+
const dispose = startGatewayPageActivation(
40+
{ snapshot: { client: { needsWakeReconnect: false } }, connect },
41+
document,
42+
window,
43+
);
44+
45+
window.dispatchEvent(new Event("online"));
46+
await Promise.resolve();
47+
48+
expect(connect).not.toHaveBeenCalled();
49+
await vi.waitFor(() => expect(refreshControlUiServiceWorker).toHaveBeenCalledOnce());
50+
dispose();
51+
});
52+
53+
it("ignores initial pageshow and removes every listener on dispose", async () => {
54+
const connect = vi.fn();
55+
const dispose = startGatewayPageActivation(
56+
{ snapshot: { client: { needsWakeReconnect: true } }, connect },
57+
document,
58+
window,
59+
);
60+
61+
window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: false }));
62+
await Promise.resolve();
63+
expect(connect).not.toHaveBeenCalled();
64+
65+
dispose();
66+
window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }));
67+
window.dispatchEvent(new Event("online"));
68+
await new Promise<void>((resolve) => {
69+
setTimeout(resolve, 0);
70+
});
71+
expect(connect).not.toHaveBeenCalled();
72+
expect(refreshControlUiServiceWorker).not.toHaveBeenCalled();
73+
});
74+
});
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import type { GatewayBrowserClient } from "../api/gateway.ts";
2+
3+
type PageActivationGateway = {
4+
readonly snapshot: { readonly client: Pick<GatewayBrowserClient, "needsWakeReconnect"> | null };
5+
connect: () => void;
6+
};
7+
8+
/** Revalidates process-backed browser state after Safari resumes a suspended tab. */
9+
export function startGatewayPageActivation(
10+
gateway: PageActivationGateway,
11+
documentTarget: Document,
12+
windowTarget: Window,
13+
): () => void {
14+
let disposed = false;
15+
let queued = false;
16+
let forceRecovery = false;
17+
let wasHidden = documentTarget.visibilityState === "hidden";
18+
19+
const schedule = (force: boolean) => {
20+
if (documentTarget.visibilityState === "hidden") {
21+
return;
22+
}
23+
forceRecovery ||= force;
24+
if (queued) {
25+
return;
26+
}
27+
queued = true;
28+
queueMicrotask(() => {
29+
queued = false;
30+
const forceQueuedRecovery = forceRecovery;
31+
forceRecovery = false;
32+
if (disposed || documentTarget.visibilityState === "hidden") {
33+
return;
34+
}
35+
const client = gateway.snapshot.client;
36+
if (client && (forceQueuedRecovery || client.needsWakeReconnect)) {
37+
// Replacing the client retires Safari's ghost socket synchronously. A
38+
// socket close would depend on the suspended transport firing `close`.
39+
gateway.connect();
40+
}
41+
void import("./sw-refresh.runtime.ts")
42+
.then(({ refreshControlUiServiceWorker }) => refreshControlUiServiceWorker())
43+
.catch((error: unknown) => {
44+
console.warn("OpenClaw service worker refresh failed after page activation.", error);
45+
});
46+
});
47+
};
48+
const onVisibilityChange = () => {
49+
if (documentTarget.visibilityState === "hidden") {
50+
wasHidden = true;
51+
return;
52+
}
53+
if (wasHidden) {
54+
wasHidden = false;
55+
schedule(false);
56+
}
57+
};
58+
const onPageShow = (event: PageTransitionEvent) => {
59+
if (event.persisted) {
60+
schedule(true);
61+
}
62+
};
63+
const onOnline = () => schedule(false);
64+
65+
documentTarget.addEventListener("visibilitychange", onVisibilityChange);
66+
windowTarget.addEventListener("pageshow", onPageShow);
67+
windowTarget.addEventListener("online", onOnline);
68+
return () => {
69+
disposed = true;
70+
documentTarget.removeEventListener("visibilitychange", onVisibilityChange);
71+
windowTarget.removeEventListener("pageshow", onPageShow);
72+
windowTarget.removeEventListener("online", onOnline);
73+
};
74+
}

0 commit comments

Comments
 (0)