Skip to content

Commit c0291d6

Browse files
committed
fix(overlay): keep a page that reconnects in a background tab alive
When the link dropped, `leave()` stopped the refresher. On reconnect, `onVisibility()` returned early in its hidden branch because the refresher was gone, so a page still in a background tab never reported itself hidden and never started its hidden heartbeat. The server could then expire it and drop its data. The hidden branch now checks whether the page is already marked hidden instead. A second drop during the `restored` calls (claim-page, redaction) no longer restarts the heartbeat, refresher and collectors while offline: the handler stands down when the link dropped again in between.
1 parent a7cb0c6 commit c0291d6

3 files changed

Lines changed: 225 additions & 3 deletions

File tree

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// @vitest-environment jsdom
2+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3+
4+
interface FakeClient {
5+
status: string;
6+
readonly isTrusted: boolean;
7+
calls: { name: string; args: unknown[] }[];
8+
set(status: string): void;
9+
}
10+
11+
const clients: FakeClient[] = [];
12+
let nextStatus = 'connected';
13+
/** While set, `claim-page` waits for it, so a test can drop the link during the call. */
14+
let claimGate: Promise<void> | null = null;
15+
const configs = { pangular: { inspectors: { analog: false, router: false } } };
16+
17+
function fakeClient(status: string): FakeClient {
18+
const listeners = new Set<(status: string) => void>();
19+
const client = {
20+
status,
21+
get isTrusted() {
22+
return client.status === 'connected';
23+
},
24+
calls: [] as { name: string; args: unknown[] }[],
25+
connectionMeta: { backend: 'websocket', configs },
26+
events: {
27+
on: (event: string, listener: (status: string) => void) => {
28+
if (event !== 'connection:status') return () => {};
29+
listeners.add(listener);
30+
return () => listeners.delete(listener);
31+
},
32+
},
33+
scope: () => ({
34+
rpc: {
35+
call: async (name: string, ...args: unknown[]) => {
36+
client.calls.push({ name, args });
37+
if (name === 'claim-page' && claimGate) await claimGate;
38+
if (client.status !== 'connected') {
39+
throw new Error('[devframe] Not connected to the devframe server');
40+
}
41+
return undefined;
42+
},
43+
register: () => {},
44+
},
45+
}),
46+
close: () => {},
47+
set(next: string) {
48+
client.status = next;
49+
for (const listener of [...listeners]) listener(next);
50+
},
51+
};
52+
return client;
53+
}
54+
55+
vi.mock('devframe/client', () => ({
56+
connectDevframe: async () => {
57+
const client = fakeClient(nextStatus);
58+
clients.push(client);
59+
return client;
60+
},
61+
}));
62+
63+
/** Change-detection watchers (the overlay's refresher) that are started and not stopped. */
64+
let watching = 0;
65+
vi.mock('../change-detection.ts', async (importOriginal) => {
66+
const actual = await importOriginal<typeof import('../change-detection.ts')>();
67+
return {
68+
...actual,
69+
watchChangeDetection: (options: Parameters<typeof actual.watchChangeDetection>[0]) => {
70+
const scheduler = actual.watchChangeDetection(options);
71+
watching++;
72+
let stopped = false;
73+
const stop = scheduler.stop;
74+
scheduler.stop = () => {
75+
if (!stopped) watching--;
76+
stopped = true;
77+
stop();
78+
};
79+
return scheduler;
80+
},
81+
};
82+
});
83+
84+
let hidden = false;
85+
const stops: (() => void)[] = [];
86+
87+
async function start() {
88+
vi.resetModules();
89+
const { initOverlay } = await import('../overlay.ts');
90+
const pending = initOverlay();
91+
await vi.advanceTimersByTimeAsync(200);
92+
stops.push(await pending);
93+
}
94+
95+
function setHidden(value: boolean) {
96+
hidden = value;
97+
document.dispatchEvent(new Event('visibilitychange'));
98+
}
99+
100+
const named = (client: FakeClient, name: string) => client.calls.filter((c) => c.name === name);
101+
const visibility = (client: FakeClient) =>
102+
named(client, 'report-page-visibility').map((call) => call.args[0]);
103+
104+
describe.sequential('overlay reconnect and page visibility', () => {
105+
beforeEach(() => {
106+
clients.length = 0;
107+
nextStatus = 'connected';
108+
claimGate = null;
109+
watching = 0;
110+
hidden = false;
111+
vi.stubGlobal('BroadcastChannel', undefined);
112+
Object.defineProperty(document, 'visibilityState', {
113+
configurable: true,
114+
get: () => (hidden ? 'hidden' : 'visible'),
115+
});
116+
vi.useFakeTimers({
117+
toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'],
118+
});
119+
});
120+
121+
afterEach(() => {
122+
stops.splice(0).forEach((stop) => stop());
123+
vi.useRealTimers();
124+
vi.unstubAllGlobals();
125+
sessionStorage.clear();
126+
});
127+
128+
it('reports a page that reconnects in a background tab as hidden and keeps it marked', async () => {
129+
await start();
130+
const [first] = clients;
131+
await vi.advanceTimersByTimeAsync(2000);
132+
setHidden(true);
133+
await vi.advanceTimersByTimeAsync(0);
134+
expect(visibility(first).at(-1)).toMatchObject({ hidden: true });
135+
136+
// The server restarts while the tab is in the background.
137+
first.set('disconnected');
138+
await vi.advanceTimersByTimeAsync(1000);
139+
const live = clients.at(-1)!;
140+
expect(live).not.toBe(first);
141+
expect(named(live, 'claim-page').length).toBe(1);
142+
143+
// The new server hears that the page is hidden, so it does not expire it.
144+
expect(visibility(live).at(-1)).toMatchObject({ hidden: true });
145+
expect(watching).toBe(0);
146+
live.calls.length = 0;
147+
await vi.advanceTimersByTimeAsync(130_000);
148+
const reports = visibility(live);
149+
expect(reports.length).toBeGreaterThanOrEqual(2);
150+
expect(reports.every((report) => (report as { hidden: boolean }).hidden)).toBe(true);
151+
expect(named(live, 'push-component-tree')).toEqual([]);
152+
153+
// Back to the tab: it reports and collects as usual.
154+
live.calls.length = 0;
155+
setHidden(false);
156+
await vi.advanceTimersByTimeAsync(0);
157+
expect(visibility(live).at(-1)).toMatchObject({ hidden: false });
158+
expect(watching).toBe(1);
159+
await vi.advanceTimersByTimeAsync(10_000);
160+
expect(named(live, 'page-heartbeat').length).toBeGreaterThan(0);
161+
});
162+
163+
it('stays quiet when the link drops again while the page is being claimed', async () => {
164+
await start();
165+
const [first] = clients;
166+
await vi.advanceTimersByTimeAsync(2000);
167+
expect(watching).toBe(1);
168+
169+
let openGate = () => {};
170+
claimGate = new Promise<void>((resolve) => (openGate = resolve));
171+
first.set('disconnected');
172+
expect(watching).toBe(0);
173+
await vi.advanceTimersByTimeAsync(1000);
174+
const second = clients.at(-1)!;
175+
expect(named(second, 'claim-page').length).toBe(1);
176+
177+
// The new connection drops before the claim answers, and the server stays down.
178+
nextStatus = 'error';
179+
second.set('disconnected');
180+
openGate();
181+
await vi.advanceTimersByTimeAsync(0);
182+
expect(watching).toBe(0);
183+
await vi.advanceTimersByTimeAsync(20_000);
184+
expect(watching).toBe(0);
185+
186+
// When the server is back, the page reports as usual.
187+
claimGate = null;
188+
nextStatus = 'connected';
189+
await vi.advanceTimersByTimeAsync(60_000);
190+
const live = clients.at(-1)!;
191+
expect(live.status).toBe('connected');
192+
expect(named(live, 'claim-page').length).toBe(1);
193+
expect(watching).toBe(1);
194+
expect(named(live, 'push-component-tree').length).toBeGreaterThan(0);
195+
});
196+
});

‎packages/devtools/src/__tests__/overlay-visibility.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,19 @@ describe.sequential('overlay keepalive and background tabs', () => {
140140
await vi.advanceTimersByTimeAsync(0);
141141
expect(sent('report-page-visibility').at(-1)?.args[0]).toMatchObject({ hidden: true });
142142
});
143+
144+
it('keeps a hidden tab marked when it comes back from the back/forward cache still hidden', async () => {
145+
await start();
146+
setHidden(true);
147+
await vi.advanceTimersByTimeAsync(0);
148+
window.dispatchEvent(new Event('pagehide'));
149+
await vi.advanceTimersByTimeAsync(0);
150+
calls.length = 0;
151+
window.dispatchEvent(new Event('pageshow'));
152+
await vi.advanceTimersByTimeAsync(130_000);
153+
const reports = sent('report-page-visibility').map((call) => call.args[0]);
154+
expect(reports.length).toBeGreaterThanOrEqual(2);
155+
expect(reports).not.toContainEqual(expect.objectContaining({ hidden: false }));
156+
expect(sent('push-component-tree')).toEqual([]);
157+
});
143158
});

‎packages/devtools/src/overlay.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -833,10 +833,12 @@ async function startOverlay(
833833
const onVisibility = () => {
834834
if (left) return;
835835
if (document.visibilityState === 'hidden') {
836-
if (!refresher) return;
837836
heartbeat.pause();
838-
refresher.stop();
837+
refresher?.stop();
839838
refresher = undefined;
839+
// Already marked hidden. A page that reconnects in the background has no
840+
// refresher but is not marked yet, so this checks the mark, not the refresher.
841+
if (stillHidden !== undefined) return;
840842
reportVisibility(true);
841843
stillHidden = outsideAngular(() =>
842844
setInterval(() => reportVisibility(true), HIDDEN_HEARTBEAT_MS),
@@ -846,6 +848,7 @@ async function startOverlay(
846848
outsideAngular(heartbeat.start);
847849
if (refresher) return;
848850
clearInterval(stillHidden);
851+
stillHidden = undefined;
849852
reportVisibility(false);
850853
pushAll();
851854
refresher = watch();
@@ -1045,6 +1048,7 @@ async function startOverlay(
10451048
refresher?.stop();
10461049
refresher = undefined;
10471050
clearInterval(stillHidden);
1051+
stillHidden = undefined;
10481052
reportVisibility(false);
10491053
pipes?.pause();
10501054
forms?.leave();
@@ -1091,12 +1095,19 @@ async function startOverlay(
10911095
};
10921096
addEventListener('pageshow', resendConfig);
10931097
// After a server restart: stop sending, then claim the page and send everything again.
1098+
let drops = 0;
10941099
link.follow({
1095-
dropped: leave,
1100+
dropped: () => {
1101+
drops++;
1102+
leave();
1103+
},
10961104
restored: async () => {
1105+
const at = drops;
10971106
await claimPageOnServer(my.rpc, pageId, pageKey);
10981107
// A failed call keeps the config the page already has.
10991108
const next = await serverRedaction(my.rpc, fallbackRedaction);
1109+
// The link dropped again during the calls: stay quiet until the next `restored`.
1110+
if (drops !== at) return;
11001111
if (next) setRedaction(next);
11011112
resendConfig();
11021113
},

0 commit comments

Comments
 (0)