Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): trigger revalidation on page reactivation edges only (#1528)

Call White5b376e0a954d
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 06d9b3af9..3b6cdb222 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -63,6 +63,7 @@ import {
shouldDeferRemoteAuthRedirect,
} from './lib/remoteAuth';
import { useIsDesktop } from './lib/useIsDesktop';
+import { onPageReactivated } from './lib/pageActivity';
// Apps layer pages are lazy: they share their chunk with the windowed app bodies
// (registry.tsx) instead of being pulled into the main entry by these routes, so
@@ -334,17 +335,11 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
if (guardStatus !== 'remote-login-required' || !shouldDeferRemoteAuthRedirect()) return;
let recheckStarted = false;
- const recheckAfterLogin = () => {
- if (document.visibilityState !== 'visible' || recheckStarted) return;
+ return onPageReactivated(() => {
+ if (recheckStarted) return;
recheckStarted = true;
setAuthCheckVersion((version) => version + 1);
- };
- document.addEventListener('visibilitychange', recheckAfterLogin);
- window.addEventListener('focus', recheckAfterLogin);
- return () => {
- document.removeEventListener('visibilitychange', recheckAfterLogin);
- window.removeEventListener('focus', recheckAfterLogin);
- };
+ });
}, [guardStatus]);
useEffect(() => {
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index 84bc6cb09..fc73df93e 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -25,6 +25,7 @@ import {
useApi,
} from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
+import { onPageReactivated } from '../lib/pageActivity';
import { getTunnelQualityDisplayState, getTunnelRequestPathDisplayState } from '../lib/tunnelQuality';
import { CompactField } from './settings/SettingsPrimitives';
import { Button } from './ui/button';
@@ -112,13 +113,11 @@ export const RemoteAccess: React.FC = () => {
if (document.visibilityState === 'visible') refresh(true).catch(() => undefined);
};
const interval = window.setInterval(refreshVisible, 30_000);
- document.addEventListener('visibilitychange', refreshVisible);
- window.addEventListener('focus', refreshVisible);
+ const stopReactivation = onPageReactivated(refreshVisible);
return () => {
disconnect();
window.clearInterval(interval);
- document.removeEventListener('visibilitychange', refreshVisible);
- window.removeEventListener('focus', refreshVisible);
+ stopReactivation();
};
}, [api, refresh]);
diff --git a/ui/src/components/workbench/AgentGraphTriggerDetail.tsx b/ui/src/components/workbench/AgentGraphTriggerDetail.tsx
index ab5511b45..3bcec37e9 100644
--- a/ui/src/components/workbench/AgentGraphTriggerDetail.tsx
+++ b/ui/src/components/workbench/AgentGraphTriggerDetail.tsx
@@ -9,6 +9,7 @@ import type { HarnessRun, HarnessTask, HarnessWatch } from '../../context/ApiCon
import { useToast } from '../../context/ToastContext';
import { Button } from '../ui/button';
import { Switch } from '../ui/switch';
+import { onPageReactivated } from '../../lib/pageActivity';
import { formatLocalDateTime } from '../../lib/datetime';
import { formatRelativeTime } from '../../lib/relativeTime';
import {
@@ -210,7 +211,7 @@ export const AgentGraphTriggerDetail: React.FC<AgentGraphTriggerDetailProps> = (
void refresh(false);
// Skip ticks while the tab is hidden — an idle backgrounded panel must not
// keep issuing unpaginated list reads every 4s (matches AgentGraphTab's
- // visibility-gated poll) — and refresh at once when visibility returns.
+ // visibility-gated poll) — and refresh at once when the page comes back.
let timer: number | undefined;
const tick = () => {
if (stopped) return;
@@ -218,15 +219,12 @@ export const AgentGraphTriggerDetail: React.FC<AgentGraphTriggerDetailProps> = (
timer = window.setTimeout(tick, TRIGGER_DETAIL_POLL_MS);
};
timer = window.setTimeout(tick, TRIGGER_DETAIL_POLL_MS);
- const onVisibility = () => {
- if (document.visibilityState === 'visible') void refresh(true);
- };
- document.addEventListener('visibilitychange', onVisibility);
+ const stopReactivation = onPageReactivated(() => void refresh(true));
return () => {
stopped = true;
if (timer !== undefined) window.clearTimeout(timer);
- document.removeEventListener('visibilitychange', onVisibility);
+ stopReactivation();
};
}, [api, definitionId, isWatch, chipEnabled]);
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index de3a4581b..c45ed5a34 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -47,6 +47,7 @@ import type { ComboboxOption } from '../ui/combobox';
import { Textarea } from '../ui/textarea';
import { EditorDialog } from '../ui/editor-dialog';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
+import { onPageReactivated } from '../../lib/pageActivity';
import { estimateTokens } from '../../lib/tokenEstimate';
import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';
import { resolveEffortOptions } from '../../lib/effortOptions';
@@ -271,18 +272,12 @@ export const AgentsPage: React.FC = () => {
timer = window.setTimeout(tick, intervalMs);
};
- const refreshNow = () => {
- if (document.visibilityState === 'visible') void tick();
- };
-
timer = window.setTimeout(tick, intervalMs);
- document.addEventListener('visibilitychange', refreshNow);
- window.addEventListener('focus', refreshNow);
+ const stopReactivation = onPageReactivated(() => void tick());
return () => {
cancelled = true;
window.clearTimeout(timer);
- document.removeEventListener('visibilitychange', refreshNow);
- window.removeEventListener('focus', refreshNow);
+ stopReactivation();
};
}, [capabilities.can_use_agents, eventBridgeConnected, fetchRunningActiveCount]);
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index a80dda1bd..0555ed79f 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -38,7 +38,7 @@ import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/fi
import { recentPathLabel } from '../../lib/editorRecents';
import type { LocalFileLinkTarget } from '../../lib/localFileLinks';
import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';
-import { canMarkConversationRead, readPageActivity } from '../../lib/pageActivity';
+import { canMarkConversationRead, onPageReactivated, usePageActive } from '../../lib/pageActivity';
import { isDesktopViewport, useIsDesktop } from '../../lib/useIsDesktop';
import { resultFooterParts } from '../../lib/resultFooter';
import {
@@ -244,22 +244,7 @@ export const ChatPage: React.FC = () => {
const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox();
const { focusedId: foregroundAppWindowId, focusCanvas } = useWindowManager();
const isDesktop = useIsDesktop();
- const [pageActive, setPageActive] = useState(() => readPageActivity());
- useEffect(() => {
- const syncPageActivity = () => setPageActive(readPageActivity());
- document.addEventListener('visibilitychange', syncPageActivity);
- window.addEventListener('focus', syncPageActivity);
- window.addEventListener('blur', syncPageActivity);
- window.addEventListener('pageshow', syncPageActivity);
- window.addEventListener('pagehide', syncPageActivity);
- return () => {
- document.removeEventListener('visibilitychange', syncPageActivity);
- window.removeEventListener('focus', syncPageActivity);
- window.removeEventListener('blur', syncPageActivity);
- window.removeEventListener('pageshow', syncPageActivity);
- window.removeEventListener('pagehide', syncPageActivity);
- };
- }, []);
+ const pageActive = usePageActive();
// The mobile chat surface is a fixed full-screen flex column; this keeps the
// composer glued to the iOS keyboard (settle-then-correct; see the hook).
const chatSurfaceRef = useRef<HTMLDivElement>(null);
@@ -1506,8 +1491,8 @@ export const ChatPage: React.FC = () => {
// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the
// SSE feed can be suspended without a clean reconnect, dropping the reply.
- // Reconcile when the page becomes visible again so the answer + working state
- // catch up to durable storage.
+ // Reconcile when the page comes back so the answer + working state catch up
+ // to durable storage.
useEffect(() => {
if (!sessionId) return;
const resync = () => {
@@ -1519,13 +1504,12 @@ export const ChatPage: React.FC = () => {
void syncTurnState({ quiet: true });
void refreshSessionRow();
};
- document.addEventListener('visibilitychange', resync);
+ // Regaining the network is its own gap, independent of the page coming back.
+ const stopReactivation = onPageReactivated(resync);
window.addEventListener('online', resync);
- window.addEventListener('focus', resync);
return () => {
- document.removeEventListener('visibilitychange', resync);
+ stopReactivation();
window.removeEventListener('online', resync);
- window.removeEventListener('focus', resync);
};
}, [sessionId, reconcile, refreshQueue, syncTurnState, refreshSessionRow]);
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index 0127510cc..12314f214 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -10,6 +10,7 @@ import { Button } from '../ui/button';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { VaultLockIndicator } from '../ui/vault-lock-indicator';
+import { onPageReactivated } from '../../lib/pageActivity';
import { cn } from '../../lib/utils';
import { partitionTags } from '../../lib/vaultTags';
import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';
@@ -600,18 +601,12 @@ export const VaultsPage: React.FC = () => {
timer = window.setTimeout(tick, 5000);
};
- const refreshNow = () => {
- if (document.visibilityState === 'visible') void tick();
- };
-
void tick();
- document.addEventListener('visibilitychange', refreshNow);
- window.addEventListener('focus', refreshNow);
+ const stopReactivation = onPageReactivated(() => void tick());
return () => {
cancelled = true;
window.clearTimeout(timer);
- document.removeEventListener('visibilitychange', refreshNow);
- window.removeEventListener('focus', refreshNow);
+ stopReactivation();
};
}, [eventBridgeConnected, refresh]);
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d0539bd5d..2a25310fe 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -6,6 +6,7 @@ import { apiFetch, recoverRemoteAuthFromSessionProbe } from '../lib/apiFetch';
import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';
import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';
+import { onPageReactivated } from '../lib/pageActivity';
import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';
import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
@@ -3024,14 +3025,13 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
wakeWorkbenchEventsRef.current();
syncSessionDraftsRef.current();
};
- document.addEventListener('visibilitychange', wakeIfVisible);
+ // Regaining the network is its own gap, independent of the page coming back.
+ const stopReactivation = onPageReactivated(wakeIfVisible);
window.addEventListener('online', wakeIfVisible);
- window.addEventListener('focus', wakeIfVisible);
if (document.visibilityState === 'visible') syncSessionDraftsRef.current();
return () => {
- document.removeEventListener('visibilitychange', wakeIfVisible);
+ stopReactivation();
window.removeEventListener('online', wakeIfVisible);
- window.removeEventListener('focus', wakeIfVisible);
stopWorkbenchEventsRef.current();
};
}, []);
diff --git a/ui/src/context/StatusProvider.tsx b/ui/src/context/StatusProvider.tsx
index bfe1c19bd..59c7c3b0f 100644
--- a/ui/src/context/StatusProvider.tsx
+++ b/ui/src/context/StatusProvider.tsx
@@ -1,5 +1,6 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { apiFetch } from '../lib/apiFetch';
+import { onPageReactivated } from '../lib/pageActivity';
import { StatusContext, type RuntimeStatus } from './StatusContext';
// Polling cadence for GET /status. The probe is cheap server-side (it reads a
@@ -158,22 +159,15 @@ export const StatusProvider: React.FC<{ children: React.ReactNode }> = ({ childr
void tick();
- const handleVisibilityChange = () => {
- if (document.visibilityState === 'visible') refreshNow();
- };
- // Wrap so the DOM event object is not forwarded as `enterRestartWindow`: a
- // truthy Event would otherwise wrongly open the fast restart window.
- const handleFocus = () => refreshNow();
-
- document.addEventListener('visibilitychange', handleVisibilityChange);
- window.addEventListener('focus', handleFocus);
+ // Wrap so the reactivation callback's arguments are not forwarded as
+ // `enterRestartWindow`, which would wrongly open the fast restart window.
+ const stopReactivation = onPageReactivated(() => refreshNow());
return () => {
cancelled = true;
wakePollRef.current = null;
window.clearTimeout(timer);
- document.removeEventListener('visibilitychange', handleVisibilityChange);
- window.removeEventListener('focus', handleFocus);
+ stopReactivation();
};
}, [refreshStatus]);
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index b0a9a022c..28288d215 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -6,6 +6,7 @@ import type { InboxSession } from './ApiContext';
import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext';
import { sessionActivityInboxAction } from '../lib/inboxActivity';
import { syncFaviconBadge } from '../lib/faviconBadge';
+import { onPageReactivated } from '../lib/pageActivity';
import {
createWorkbenchSessionReadOwnership,
type WorkbenchSessionReadStamp,
@@ -583,19 +584,18 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// Recover after the OS suspended us. A backgrounded mobile PWA has its page
// frozen and its SSE socket dropped, and the broker never replays the gap;
// iOS can leave EventSource in a zombie OPEN state without onerror. ApiContext
- // reopens the shared stream on visibility, online, and focus; independently
- // reconcile the durable feed here so missed events never gate data freshness.
+ // reopens the shared stream when the page comes back and when the network
+ // returns; independently reconcile the durable feed here so missed events
+ // never gate data freshness.
useEffect(() => {
const resync = () => {
if (document.visibilityState === 'visible') void reconcile();
};
- document.addEventListener('visibilitychange', resync);
+ const stopReactivation = onPageReactivated(resync);
window.addEventListener('online', resync);
- window.addEventListener('focus', resync);
return () => {
- document.removeEventListener('visibilitychange', resync);
+ stopReactivation();
window.removeEventListener('online', resync);
- window.removeEventListener('focus', resync);
};
}, [reconcile]);
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 79ebcf01f..4cba755fd 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -106,14 +106,33 @@ function settle() {
});
}
+// The inbox reconciles when the page comes back, which is an edge rather than a
+// level: the shared page-activity sampler ignores a `focus` event on a page that
+// never left. Simulate a real gap by hiding the document and revealing it again.
+function simulatePageResume() {
+ const setVisibility = (state: DocumentVisibilityState) => {
+ Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });
+ document.dispatchEvent(new Event('visibilitychange'));
+ };
+ setVisibility('hidden');
+ setVisibility('visible');
+ // Drop the shadowing property so the rest of the suite reads jsdom's own getter.
+ Reflect.deleteProperty(document, 'visibilityState');
+}
+
describe('Workbench session read ownership', () => {
beforeEach(() => {
apiRef.current = null;
+ // jsdom never reports window focus, so no reading would ever count as "the
+ // page is presented". Model a focused window and let visibility carry the
+ // transitions `simulatePageResume` needs.
+ document.hasFocus = () => true;
});
afterEach(() => {
cleanup();
apiRef.current = null;
+ Reflect.deleteProperty(document, 'hasFocus');
});
it('does not let a bootstrap issued before hide repopulate the projects tree', async () => {
@@ -1253,7 +1272,7 @@ describe('Workbench session read ownership', () => {
);
await settle();
act(() => {
- window.dispatchEvent(new Event('focus'));
+ simulatePageResume();
});
await settle();
act(() => {
@@ -1319,7 +1338,7 @@ describe('Workbench session read ownership', () => {
);
await settle();
act(() => {
- window.dispatchEvent(new Event('focus'));
+ simulatePageResume();
});
await settle();
act(() => {
@@ -1409,7 +1428,7 @@ describe('Workbench session read ownership', () => {
);
await settle();
act(() => {
- window.dispatchEvent(new Event('focus'));
+ simulatePageResume();
});
await settle();
act(() => {
@@ -1505,7 +1524,7 @@ describe('Workbench session read ownership', () => {
await settle();
act(() => {
void inbox?.loadMore();
- window.dispatchEvent(new Event('focus'));
+ simulatePageResume();
});
await settle();
expect(listInbox).toHaveBeenCalledTimes(2);
@@ -1573,8 +1592,8 @@ describe('Workbench session read ownership', () => {
);
await settle();
act(() => {
- document.dispatchEvent(new Event('visibilitychange'));
- window.dispatchEvent(new Event('focus'));
+ simulatePageResume();
+ simulatePageResume();
});
await settle();
expect(listInbox).toHaveBeenCalledTimes(2);
diff --git a/ui/src/lib/avibeFetch.ts b/ui/src/lib/avibeFetch.ts
index 0ffc4bfbe..a6ef306a2 100644
--- a/ui/src/lib/avibeFetch.ts
+++ b/ui/src/lib/avibeFetch.ts
@@ -13,6 +13,7 @@
// - fallback: before any cloud request, throws CloudUnavailableError when no
// token can be obtained so callers may use the local relay instead
import { apiFetch } from './apiFetch';
+import { onPageReactivated } from './pageActivity';
export type CloudToken = { token: string; baseUrl: string; expiresAt: number };
@@ -74,11 +75,8 @@ const bindActivityListeners = (): void => {
const topUp = (): void => {
if (!isFresh(current)) void mint().catch(() => undefined);
};
- window.addEventListener('focus', topUp);
+ onPageReactivated(topUp);
window.addEventListener('online', topUp);
- document.addEventListener('visibilitychange', () => {
- if (document.visibilityState === 'visible') topUp();
- });
};
// Single-flight: concurrent callers share one in-flight /api/cloud/token request.
diff --git a/ui/src/lib/pageActivity.test.ts b/ui/src/lib/pageActivity.test.ts
index 25853ec90..ab30ad0f6 100644
--- a/ui/src/lib/pageActivity.test.ts
+++ b/ui/src/lib/pageActivity.test.ts
@@ -1,6 +1,14 @@
-import { describe, expect, it } from 'vitest';
+// @vitest-environment jsdom
-import { canMarkConversationRead, isPageActive } from './pageActivity';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ canMarkConversationRead,
+ createPageActivityTracker,
+ isPageActive,
+ onPageReactivated,
+ type PageActivitySnapshot,
+} from './pageActivity';
describe('isPageActive', () => {
it('requires both a visible document and window focus', () => {
@@ -10,6 +18,281 @@ describe('isPageActive', () => {
});
});
+describe('createPageActivityTracker', () => {
+ const observeAll = (initial: boolean, snapshots: PageActivitySnapshot[]): boolean[] => {
+ const tracker = createPageActivityTracker(initial);
+ return snapshots.map((snapshot) => tracker.observe(isPageActive(snapshot)));
+ };
+
+ it('reports the inactive -> active edge once per gap', () => {
+ expect(
+ observeAll(true, [
+ { visibilityState: 'hidden', hasFocus: false },
+ { visibilityState: 'visible', hasFocus: true },
+ { visibilityState: 'visible', hasFocus: true },
+ ]),
+ ).toEqual([false, true, false]);
+ });
+
+ it('reports a return of window focus without a visibility change', () => {
+ expect(
+ observeAll(true, [
+ { visibilityState: 'visible', hasFocus: false },
+ { visibilityState: 'visible', hasFocus: true },
+ ]),
+ ).toEqual([false, true]);
+ });
+
+ it('waits for focus when a revealed tab is not focused yet', () => {
+ expect(
+ observeAll(true, [
+ { visibilityState: 'hidden', hasFocus: false },
+ { visibilityState: 'visible', hasFocus: false },
+ { visibilityState: 'visible', hasFocus: true },
+ ]),
+ ).toEqual([false, false, true]);
+ });
+
+ it('stays silent while focus moves inside a page that never left', () => {
+ // Focusing an embedded Show Page iframe blurs the parent window, but the
+ // parent document stays visible and keeps `document.hasFocus()`.
+ expect(
+ observeAll(true, [
+ { visibilityState: 'visible', hasFocus: true },
+ { visibilityState: 'visible', hasFocus: true },
+ ]),
+ ).toEqual([false, false]);
+ });
+
+ it('does not treat a first active reading as a return when it starts active', () => {
+ const tracker = createPageActivityTracker(true);
+ expect(tracker.isActive()).toBe(true);
+ expect(tracker.observe(true)).toBe(false);
+ });
+
+ it('treats becoming active for the first time as a return when it starts inactive', () => {
+ const tracker = createPageActivityTracker(false);
+ expect(tracker.observe(true)).toBe(true);
+ expect(tracker.isActive()).toBe(true);
+ });
+});
+
+// Every way a page can hand focus to an embedded context, so the partition the
+// sampler rests on — walkable chains stay exact, unwalkable ones fail toward one
+// redundant revalidation — is asserted member by member rather than assumed.
+describe('onPageReactivated', () => {
+ const created: Element[] = [];
+ const shadowed: Array<Document | ShadowRoot> = [];
+ const stops: Array<() => void> = [];
+
+ // Unsubscribing from a cleanup rather than the end of each test keeps a failed
+ // assertion from leaving the shared sampler attached for the next one.
+ const listen = (): ReturnType<typeof vi.fn> => {
+ const reactivated = vi.fn();
+ stops.push(onPageReactivated(reactivated));
+ return reactivated;
+ };
+
+ // jsdom never moves focus into a frame, so put it there by hand: `activeElement`
+ // is how the sampler finds the window that owns focus events, and `hasFocus` is
+ // the system-focus truth those events are read against.
+ const focusIn = (root: Document | ShadowRoot, element: Element | null) => {
+ Object.defineProperty(root, 'activeElement', { value: element, configurable: true });
+ if (!shadowed.includes(root)) shadowed.push(root);
+ };
+
+ const addFrame = (parent: Document = document): HTMLIFrameElement => {
+ const element = parent.createElement('iframe');
+ (parent.body ?? parent.documentElement).appendChild(element);
+ created.push(element);
+ return element;
+ };
+
+ const focusFrame = (): HTMLIFrameElement => {
+ const frame = addFrame();
+ focusIn(document, frame);
+ // The parent window blurs as focus enters the frame; nothing left the page.
+ window.dispatchEvent(new Event('blur'));
+ return frame;
+ };
+
+ const focusParent = () => focusIn(document, document.body);
+
+ // An application switch reaches whichever window currently owns focus.
+ const switchAwayAndBack = (target: Window) => {
+ document.hasFocus = () => false;
+ target.dispatchEvent(new Event('blur'));
+ document.hasFocus = () => true;
+ target.dispatchEvent(new Event('focus'));
+ };
+
+ afterEach(() => {
+ for (const stop of stops) stop();
+ stops.length = 0;
+ for (const root of shadowed) Reflect.deleteProperty(root, 'activeElement');
+ shadowed.length = 0;
+ Reflect.deleteProperty(document, 'hasFocus');
+ for (const element of created) element.remove();
+ created.length = 0;
+ });
+
+ it('reports a system focus loss that arrived at the frame holding focus', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const frame = focusFrame();
+ expect(reactivated).not.toHaveBeenCalled();
+
+ switchAwayAndBack(frame.contentWindow as Window);
+
+ expect(reactivated).toHaveBeenCalledTimes(1);
+ });
+
+ it('stays silent while focus only moves between the page and its frame', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const frame = focusFrame();
+
+ // Clicking workbench chrome blurs the frame and focuses the parent again.
+ (frame.contentWindow as Window).dispatchEvent(new Event('blur'));
+ focusParent();
+ window.dispatchEvent(new Event('focus'));
+
+ expect(reactivated).not.toHaveBeenCalled();
+ });
+
+ it('stops listening to a frame that no longer holds focus', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const frame = focusFrame();
+ focusParent();
+ window.dispatchEvent(new Event('focus'));
+
+ // A stale frame must not be able to report the page inactive from the side.
+ switchAwayAndBack(frame.contentWindow as Window);
+
+ expect(reactivated).not.toHaveBeenCalled();
+ });
+
+ it('rebinds onto the window a navigation put behind the focused frame', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const frame = focusFrame();
+ const before = frame.contentWindow as Window;
+
+ // Navigating a frame keeps its `WindowProxy` identity while replacing the
+ // document — and with it every listener registered on the old window.
+ const carrier = addFrame();
+ const after = carrier.contentWindow as Window;
+ Object.defineProperty(frame, 'contentWindow', { value: after, configurable: true });
+ Object.defineProperty(frame, 'contentDocument', {
+ value: carrier.contentDocument,
+ configurable: true,
+ });
+ frame.dispatchEvent(new Event('load'));
+
+ switchAwayAndBack(after);
+ expect(reactivated).toHaveBeenCalledTimes(1);
+
+ // The window the navigation discarded must no longer speak for the page.
+ switchAwayAndBack(before);
+ expect(reactivated).toHaveBeenCalledTimes(1);
+ });
+
+ it('follows focus into a frame nested inside the focused frame', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const outer = addFrame();
+ const outerDocument = outer.contentDocument as Document;
+ const inner = addFrame(outerDocument);
+
+ focusIn(outerDocument, inner);
+ focusIn(document, outer);
+ window.dispatchEvent(new Event('blur'));
+
+ switchAwayAndBack(inner.contentWindow as Window);
+
+ expect(reactivated).toHaveBeenCalledTimes(1);
+ });
+
+ it('follows focus into a frame behind a shadow root', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ created.push(host);
+ const shadow = host.attachShadow({ mode: 'open' });
+ const frame = document.createElement('iframe');
+ shadow.appendChild(frame);
+ // jsdom gives no browsing context to a frame inside a shadow tree, so lend
+ // it one; what is under test is the walk descending through the shadow root.
+ const carrier = addFrame();
+ const frameWindow = carrier.contentWindow as Window;
+ Object.defineProperty(frame, 'contentWindow', { value: frameWindow, configurable: true });
+ Object.defineProperty(frame, 'contentDocument', {
+ value: carrier.contentDocument,
+ configurable: true,
+ });
+
+ focusIn(shadow, frame);
+ focusIn(document, host);
+ window.dispatchEvent(new Event('blur'));
+
+ switchAwayAndBack(frameWindow);
+
+ expect(reactivated).toHaveBeenCalledTimes(1);
+ });
+
+ const focusCrossOriginFrame = (): HTMLIFrameElement => {
+ const frame = addFrame();
+ const refuse = () => {
+ throw new Error('cross-origin');
+ };
+ Object.defineProperty(frame, 'contentDocument', { get: refuse, configurable: true });
+ Object.defineProperty(frame, 'contentWindow', { get: refuse, configurable: true });
+ focusIn(document, frame);
+ window.dispatchEvent(new Event('blur'));
+ return frame;
+ };
+
+ it('stays silent while an out-of-sight frame reloads without giving focus back', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ const frame = focusCrossOriginFrame();
+
+ // The sandboxed preview, Vault surface, or Show Page reloads itself while it
+ // still owns focus. Being unable to see the page is what the sampler has
+ // been told; only seeing it again is news.
+ frame.dispatchEvent(new Event('load'));
+ frame.dispatchEvent(new Event('load'));
+
+ expect(reactivated).not.toHaveBeenCalled();
+ });
+
+ it('treats coming back from a cross-origin frame as coming back', () => {
+ document.hasFocus = () => true;
+
+ const reactivated = listen();
+ focusCrossOriginFrame();
+ expect(reactivated).not.toHaveBeenCalled();
+
+ // A switch away and back while the frame owns focus reaches neither window.
+ // Clicking the workbench is the first thing this document can observe, and
+ // it cannot vouch for the gap, so it revalidates rather than assume nothing
+ // happened.
+ focusParent();
+ window.dispatchEvent(new Event('focus'));
+
+ expect(reactivated).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('canMarkConversationRead', () => {
it('requires the visible chat transcript to be current and active', () => {
const visibleTranscript = {
diff --git a/ui/src/lib/pageActivity.ts b/ui/src/lib/pageActivity.ts
index e5360f14c..2053c5741 100644
--- a/ui/src/lib/pageActivity.ts
+++ b/ui/src/lib/pageActivity.ts
@@ -1,3 +1,5 @@
+import { useSyncExternalStore } from 'react';
+
export type PageActivitySnapshot = {
visibilityState: DocumentVisibilityState;
hasFocus: boolean;
@@ -40,3 +42,245 @@ export function readPageActivity(): boolean {
hasFocus: typeof document.hasFocus !== 'function' || document.hasFocus(),
});
}
+
+export type PageActivityTracker = {
+ isActive: () => boolean;
+ /** Fold one reading in; true only on the inactive -> active edge. */
+ observe: (nextActive: boolean) => boolean;
+};
+
+/**
+ * Edge detector over `isPageActive`. A reactivation is the moment a page that
+ * really was away — hidden, or with window focus gone elsewhere — becomes
+ * active again. A page that never left reports nothing.
+ *
+ * That distinction is what a raw `focus` listener cannot make. An embedded
+ * browsing context (a Show Page iframe) is focused and blurred independently of
+ * its parent, so clicking workbench chrome fires `blur`/`focus` on the parent
+ * window while `document.visibilityState` stays `visible` and
+ * `document.hasFocus()` stays `true` the whole time. Level-triggered listeners
+ * read that as "the user came back" and each revalidate; this tracker sees no
+ * transition at all.
+ */
+export function createPageActivityTracker(initialActive: boolean): PageActivityTracker {
+ let active = initialActive;
+ return {
+ isActive: () => active,
+ observe: (nextActive) => {
+ const reactivated = nextActive && !active;
+ active = nextActive;
+ return reactivated;
+ },
+ };
+}
+
+// One sampler for the whole app. Consumers subscribe to the derived facts —
+// "the page is active" and "the page just came back" — rather than each binding
+// its own focus/visibility listeners and re-deriving them.
+
+const activeListeners = new Set<() => void>();
+const reactivationListeners = new Set<() => void>();
+
+let tracker: PageActivityTracker | null = null;
+let detach: (() => void) | null = null;
+
+// Copy first: a listener may unsubscribe while the set is being walked.
+const notify = (listeners: Set<() => void>) => {
+ for (const listener of [...listeners]) listener();
+};
+
+const sample = () => {
+ if (!tracker) return;
+ const wasActive = tracker.isActive();
+ const wasOutOfSight = focusOutOfSight;
+ const active = readPageActivity();
+ // Re-walk before deciding: what makes an unobservable gap a return is
+ // regaining sight of the page, not merely having lost it. An out-of-sight
+ // frame reloading itself samples too, and it never left.
+ syncFocusChain();
+ const regainedSight = wasOutOfSight && !focusOutOfSight;
+ // Either edge is a return: one this document watched happen, or one it could
+ // only have missed while focus sat where it cannot look.
+ const reactivated = tracker.observe(active) || (active && regainedSight);
+ if (tracker.isActive() !== wasActive) notify(activeListeners);
+ if (reactivated) notify(reactivationListeners);
+};
+
+// Focus events go to the window that holds focus, and Chrome hands focus to an
+// embedded browsing context while blurring ours: from then on a system focus
+// loss is delivered there and never here. Following focus one level down is not
+// enough, because a frame can navigate, nest another frame, sit behind a shadow
+// root, or be cross-origin — each a separate way for the page to lose focus out
+// of this document's sight, and the list of embedding shapes has no end.
+//
+// So partition rather than enumerate. Walk the focus chain as far as this
+// document is allowed to see and listen on every window in it; a chain that
+// ends somewhere it cannot enter means the page went out of sight, and coming
+// back from an unobservable context counts as a return by definition. Every
+// topology is then either walkable, where the edge detector stays exact, or
+// not, where it fails toward one redundant revalidation instead of toward
+// silently stale data.
+const FRAME_FOCUS_EVENTS = ['focus', 'blur', 'pagehide'] as const;
+
+// A focus chain deeper than this is pathological. Stopping counts as losing
+// sight, so the cap fails toward revalidating rather than toward silence.
+const MAX_FOCUS_DEPTH = 10;
+
+type FocusChain = {
+ /** Same-origin windows along the chain, innermost last. */
+ windows: Window[];
+ /** The frame elements that own them, watched for navigation. */
+ frames: Element[];
+ /** The chain ended at a context this document cannot look into. */
+ outOfSight: boolean;
+};
+
+const isFrameElement = (element: Element): boolean =>
+ // Cross-realm elements fail `instanceof`, so compare the tag instead.
+ element.tagName === 'IFRAME' || element.tagName === 'FRAME';
+
+const walkFocusChain = (): FocusChain => {
+ const windows: Window[] = [];
+ const frames: Element[] = [];
+ let root: Document | ShadowRoot = document;
+ for (let depth = 0; depth < MAX_FOCUS_DEPTH; depth += 1) {
+ // Annotated because the loop feeds `root` from this value, and inference
+ // would otherwise chase its own tail through the narrowing of `root`.
+ const focused: Element | null = root.activeElement;
+ // No delegation left: focus rests on an element of this document.
+ if (!focused) return { windows, frames, outOfSight: false };
+ if (focused.shadowRoot) {
+ root = focused.shadowRoot;
+ continue;
+ }
+ if (!isFrameElement(focused)) return { windows, frames, outOfSight: false };
+ frames.push(focused);
+ let frameDocument: Document | null = null;
+ let frameWindow: Window | null = null;
+ try {
+ frameDocument = (focused as HTMLIFrameElement).contentDocument;
+ frameWindow = (focused as HTMLIFrameElement).contentWindow;
+ } catch {
+ // A cross-origin frame refuses both, which is the out-of-sight case.
+ }
+ if (!frameDocument || !frameWindow) return { windows, frames, outOfSight: true };
+ windows.push(frameWindow);
+ root = frameDocument;
+ }
+ return { windows, frames, outOfSight: true };
+};
+
+const boundWindows = new Set<Window>();
+const boundFrames = new Set<Element>();
+let focusOutOfSight = false;
+
+const releaseFocusChain = () => {
+ for (const frameWindow of boundWindows) {
+ try {
+ for (const type of FRAME_FOCUS_EVENTS) frameWindow.removeEventListener(type, sample);
+ } catch {
+ // The window was torn down with its frame; nothing left to detach.
+ }
+ }
+ boundWindows.clear();
+ for (const frame of boundFrames) frame.removeEventListener('load', sample);
+ boundFrames.clear();
+ focusOutOfSight = false;
+};
+
+const syncFocusChain = () => {
+ const chain = walkFocusChain();
+ const nextWindows = new Set(chain.windows);
+ const nextFrames = new Set(chain.frames);
+
+ for (const frameWindow of boundWindows) {
+ if (nextWindows.has(frameWindow)) continue;
+ try {
+ for (const type of FRAME_FOCUS_EVENTS) frameWindow.removeEventListener(type, sample);
+ } catch {
+ // Same as above: a discarded window needs no detaching.
+ }
+ boundWindows.delete(frameWindow);
+ }
+ for (const frame of boundFrames) {
+ if (nextFrames.has(frame)) continue;
+ frame.removeEventListener('load', sample);
+ boundFrames.delete(frame);
+ }
+
+ // Re-registering an identical listener is a no-op, so one pass both binds new
+ // windows and reinstalls on a window whose document a navigation replaced —
+ // navigation keeps the `WindowProxy` identity but empties its listener table.
+ for (const frameWindow of nextWindows) {
+ try {
+ for (const type of FRAME_FOCUS_EVENTS) frameWindow.addEventListener(type, sample);
+ boundWindows.add(frameWindow);
+ } catch {
+ // Lost same-origin access mid-walk; the chain reading below covers it.
+ }
+ }
+ // `load` fires on the element for same-origin and cross-origin frames alike,
+ // which is what makes a navigated frame rebind before it can be focused again.
+ for (const frame of nextFrames) {
+ frame.addEventListener('load', sample);
+ boundFrames.add(frame);
+ }
+
+ focusOutOfSight = chain.outOfSight;
+};
+
+const attach = () => {
+ tracker = createPageActivityTracker(readPageActivity());
+ // `pageshow`/`pagehide` cover bfcache restores, which resume a page without
+ // a visibility change.
+ document.addEventListener('visibilitychange', sample);
+ window.addEventListener('focus', sample);
+ window.addEventListener('blur', sample);
+ window.addEventListener('pageshow', sample);
+ window.addEventListener('pagehide', sample);
+ detach = () => {
+ document.removeEventListener('visibilitychange', sample);
+ window.removeEventListener('focus', sample);
+ window.removeEventListener('blur', sample);
+ window.removeEventListener('pageshow', sample);
+ window.removeEventListener('pagehide', sample);
+ releaseFocusChain();
+ tracker = null;
+ detach = null;
+ };
+ // Fold the current reading in once, so a page that mounts while an embedded
+ // frame already holds focus starts watching that chain without waiting for an
+ // event it would never receive.
+ sample();
+};
+
+const subscribe = (listeners: Set<() => void>, listener: () => void): (() => void) => {
+ if (typeof document === 'undefined' || typeof window === 'undefined') return () => {};
+ listeners.add(listener);
+ if (!detach) attach();
+ return () => {
+ listeners.delete(listener);
+ if (activeListeners.size === 0 && reactivationListeners.size === 0) detach?.();
+ };
+};
+
+const getPageActive = (): boolean => (tracker ? tracker.isActive() : readPageActivity());
+
+const subscribePageActive = (listener: () => void): (() => void) =>
+ subscribe(activeListeners, listener);
+
+/**
+ * Run `listener` each time the page comes back after being hidden or after
+ * losing window focus, and returns the unsubscribe. This is the trigger for
+ * revalidating data that may have gone stale during the gap; a bare `focus`
+ * listener over-fires because it cannot tell a return from a focus move that
+ * never left the page.
+ */
+export function onPageReactivated(listener: () => void): () => void {
+ return subscribe(reactivationListeners, listener);
+}
+
+/** Whether the page is presented right now, kept live by the shared sampler. */
+export function usePageActive(): boolean {
+ return useSyncExternalStore(subscribePageActive, getPageActive, () => false);
+}
diff --git a/ui/src/lib/useVaultRequestRefresh.ts b/ui/src/lib/useVaultRequestRefresh.ts
index 3c7e0db20..704044526 100644
--- a/ui/src/lib/useVaultRequestRefresh.ts
+++ b/ui/src/lib/useVaultRequestRefresh.ts
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react';
import { useApi } from '@/context/ApiContext';
+import { onPageReactivated } from './pageActivity';
+
const FALLBACK_POLL_INTERVAL_MS = 5000;
export function shouldPollVaultRequests(eventBridgeConnected: boolean): boolean {
@@ -62,18 +64,12 @@ export function useVaultRequestRefresh(refresh: () => void | Promise<void>): voi
timer = window.setTimeout(tick, FALLBACK_POLL_INTERVAL_MS);
};
- const refreshNow = () => {
- if (document.visibilityState === 'visible') void tick();
- };
-
void tick();
- document.addEventListener('visibilitychange', refreshNow);
- window.addEventListener('focus', refreshNow);
+ const stopReactivation = onPageReactivated(() => void tick());
return () => {
cancelled = true;
window.clearTimeout(timer);
- document.removeEventListener('visibilitychange', refreshNow);
- window.removeEventListener('focus', refreshNow);
+ stopReactivation();
};
}, [eventBridgeConnected, refresh]);
}