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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): open PWA notifications at their session and refresh badges (#2154)
Call Whiteb1f06bd0464e
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex be0bd487a..338f35449 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -18,6 +18,7 @@ from storage.models import remote_access_authorizationsfrom tests.ui_server_test_helpers import remote_session_cookiefrom vibe import api, model_service, remote_access, ui_serverfrom vibe import runtime+from vibe.ui_compat import g, jsonify@pytest.fixture(autouse=True)@@ -223,6 +224,22 @@ def test_session_cookie_roundtrip() -> None:assert remote_access.validate_session_cookie(config, cookie + "x") is False+def test_background_push_inbox_read_does_not_renew_remote_cookie(monkeypatch):+ config = _config()+ monkeypatch.setattr(ui_server, "_load_remote_access_config", lambda: config)+ monkeypatch.setattr(remote_access, "renew_session_cookie", lambda *_: "renewed-cookie")++ for path, headers, should_renew in (+ ("/api/inbox", {"X-Avibe-Background-Push": "1"}, False),+ ("/api/inbox", {}, True),+ ("/api/session", {"X-Avibe-Background-Push": "1"}, True),+ ):+ with ui_server.app.test_request_context(path, headers=headers):+ g.remote_session_renew = {"sub": "user-1"}+ response = ui_server.renew_remote_access_cookie(jsonify({"ok": True}))+ assert (remote_access.SESSION_COOKIE_NAME in response.headers.get("Set-Cookie", "")) is should_renew++def test_session_cookie_rejects_empty_session_secret() -> None:config = _config()config.remote_access.vibe_cloud.session_secret = ""diff --git a/ui/public/push-sw.js b/ui/public/push-sw.jsindex fe8582a83..d09dfc9e7 100644--- a/ui/public/push-sw.js+++ b/ui/public/push-sw.js@@ -4,9 +4,8 @@// browsers without the API (and non-installed contexts) simply no-op, and a// rejected badge promise must never block the notification from showing.//-// Returns a promise to await, or null when there is nothing to do. `count` is-// the global unread total the server computed for this push; a missing/invalid-// count leaves the existing badge untouched (we don't guess).+// Returns a promise to await, or null when there is nothing to do. A+// missing/invalid count leaves the existing badge untouched (we don't guess).function syncAppBadge(count) {if (!('setAppBadge' in navigator)) return null;if (typeof count !== 'number' || !Number.isFinite(count)) return null;@@ -15,6 +14,88 @@ function syncAppBadge(count) {return op && typeof op.catch === 'function' ? op.catch(() => {}) : null;}+let badgeWrite = Promise.resolve();+let pageBadgeRevision = 0;+let workerBadgeRefresh = 0;++function queueAppBadge(count, refreshId = null, pageRevisionAtStart = null) {+ badgeWrite = badgeWrite.catch(() => {}).then(() => {+ if (refreshId !== null && refreshId !== workerBadgeRefresh) return;+ if (pageRevisionAtStart !== null && pageRevisionAtStart !== pageBadgeRevision) return;+ return syncAppBadge(count);+ });+ return badgeWrite;+}++const APP_SHELL_PATHS = ['/inbox', '/search', '/agents', '/skills', '/harness', '/vaults', '/projects', '/apps', '/settings', '/more', '/chat', '/admin'];++function isAppShellClient(client) {+ try {+ const url = new URL(client.url);+ if (url.origin !== self.location.origin) return false;+ if (url.pathname === '/') return true;+ return APP_SHELL_PATHS.some((path) => url.pathname === path || url.pathname.startsWith(`${path}/`));+ } catch {+ return false;+ }+}++async function appWindowClients() {+ const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });+ return clients.filter(isAppShellClient);+}++function requestForegroundBadgeRefresh(clients) {+ for (const client of clients) {+ // A hidden page's ordinary Inbox read could renew an unattended login.+ if (client.visibilityState !== 'visible') continue;+ try {+ client.postMessage({ type: 'vibe.push-badge-refresh' });+ } catch {+ // A closing window will refresh its Inbox on the next launch.+ }+ }+}++// Push delivery can lag behind a mark-read response. The count embedded when+// the push was sent may already be obsolete by the time this worker runs.+async function refreshAppBadge() {+ if (!('setAppBadge' in navigator)) return;+ const refreshId = ++workerBadgeRefresh;+ const pageRevisionAtStart = pageBadgeRevision;+ try {+ let clients = await appWindowClients();+ if (clients.some((client) => client.visibilityState === 'visible')) {+ requestForegroundBadgeRefresh(clients);+ return;+ }+ const response = await fetch('/api/inbox?platform=avibe&limit=1', {+ credentials: 'same-origin',+ cache: 'no-store',+ headers: { 'X-Avibe-Background-Push': '1' },+ });+ if (!response.ok) return;+ const payload = await response.json();+ clients = await appWindowClients();+ if (clients.some((client) => client.visibilityState === 'visible')) {+ requestForegroundBadgeRefresh(clients);+ return;+ }+ await queueAppBadge(payload?.unread_total, refreshId, pageRevisionAtStart);+ requestForegroundBadgeRefresh(await appWindowClients());+ } catch {+ // An unavailable or unauthenticated read is not evidence that the badge is zero.+ }+}++self.addEventListener('message', (event) => {+ if (event.data?.type !== 'vibe.app-badge-current') return;+ const count = event.data.count;+ if (typeof count !== 'number' || !Number.isFinite(count) || count < 0) return;+ pageBadgeRevision += 1;+ event.waitUntil(queueAppBadge(count));+});+const WEB_PUSH_LAUNCH_CACHE = 'avibe.web-push-launch.v1';const WEB_PUSH_LAUNCH_ENTRY_PATH = '/__avibe/web-push-launch';const WEB_PUSH_ENDPOINT_CACHE = 'avibe.web-push-endpoint.v1';@@ -167,8 +248,14 @@ async function replacementSubscription(event) {// app shell can still prefer the tapped notification over its remembered page.function rememberPendingNotificationLaunch(url) {if (!self.caches) return Promise.resolve();- const entryUrl = new URL(WEB_PUSH_LAUNCH_ENTRY_PATH, self.location.origin).href;- const response = new Response(JSON.stringify({ url, createdAt: Date.now() }), {+ const createdAt = Date.now();+ // Distinct cache keys let a page consume click A without deleting click B+ // if B arrives while A's response body is being read.+ const entryUrl = new URL(+ `${WEB_PUSH_LAUNCH_ENTRY_PATH}/${createdAt}-${Math.random().toString(36).slice(2)}`,+ self.location.origin,+ ).href;+ const response = new Response(JSON.stringify({ url, createdAt }), {headers: { 'content-type': 'application/json' },});return self.caches@@ -177,6 +264,8 @@ function rememberPendingNotificationLaunch(url) {.catch(() => {});}+let notificationClickQueue = Promise.resolve();+self.addEventListener('pushsubscriptionchange', (event) => {event.waitUntil((async () => {@@ -211,8 +300,7 @@ self.addEventListener('push', (event) => {};const tasks = [self.registration.showNotification(title, options)];- const badgeTask = syncAppBadge(payload.badge_count);- if (badgeTask) tasks.push(badgeTask);+ tasks.push(refreshAppBadge());event.waitUntil(Promise.all(tasks));});@@ -227,21 +315,23 @@ self.addEventListener('notificationclick', (event) => {type: 'vibe.notification-click',url: targetUrl.pathname + targetUrl.search + targetUrl.hash,};- const appShellPaths = ['/inbox', '/agents', '/skills', '/harness', '/vaults', '/projects', '/more', '/chat', '/admin'];- const isAppShellClient = (url) => {- if (url.origin !== self.location.origin) return false;- if (url.pathname === '/') return true;- return appShellPaths.some((path) => url.pathname === path || url.pathname.startsWith(`${path}/`));- };-- event.waitUntil(+ // A slow first focus must not post its target after a later tap has posted+ // another one. Keep the handoff, focus, and message in click order.+ const click = notificationClickQueue.then(() =>self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {for (const client of clients) {- if ('focus' in client && isAppShellClient(new URL(client.url))) {- return client.focus().then((focusedClient) => {- (focusedClient || client).postMessage(message);- return focusedClient || client;- });+ if ('focus' in client && isAppShellClient(client)) {+ // A suspended page may miss postMessage even after focus resolves.+ // Persist the target before waking it so the page's resume handler+ // can consume the same one-shot handoff as a cold launch.+ return rememberPendingNotificationLaunch(message.url)+ .then(() => client.focus())+ .then((focusedClient) => {+ const target = focusedClient || client;+ target.postMessage(message);+ return target;+ })+ .catch(() => self.clients.openWindow?.(href));}}if (self.clients.openWindow) {@@ -259,4 +349,6 @@ self.addEventListener('notificationclick', (event) => {return undefined;}),);+ notificationClickQueue = click.catch(() => {});+ event.waitUntil(click);});diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 435b764f5..667140b53 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -102,7 +102,11 @@ import {shouldRestorePwaLaunch,writeLastPwaPath,} from './lib/pwaRouteMemory';-import { takePendingWebPushLaunchPath } from './lib/webPushLaunch';+import {+ createWebPushLaunchNavigation,+ takePendingWebPushLaunchPath,+ takeResumedWebPushLaunchPath,+} from './lib/webPushLaunch';import { applyAppTitle } from './lib/documentTitle';import { useTranslation } from 'react-i18next';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';@@ -252,16 +256,24 @@ const WebPushNotificationNavigator = () => {useEffect(() => {if (!('serviceWorker' in navigator)) return;+ const launchNavigation = createWebPushLaunchNavigation(takeResumedWebPushLaunchPath, navigate);const onMessage = (event: MessageEvent) => {const data = event.data;if (!data || typeof data !== 'object' || data.type !== 'vibe.notification-click') return;const path = notificationClickPath(data.url);- if (path) navigate(path);+ if (path) {+ launchNavigation.notificationClick(path);+ }};+ const unsubscribeResume = onPageReactivated(() => launchNavigation.reactivated());navigator.serviceWorker.addEventListener('message', onMessage);- return () => navigator.serviceWorker.removeEventListener('message', onMessage);+ return () => {+ launchNavigation.dispose();+ unsubscribeResume();+ navigator.serviceWorker.removeEventListener('message', onMessage);+ };}, [navigate]);return null;@@ -635,9 +647,9 @@ const PwaRouteMemory = () => {iosStandalone,locationKey: location.key,location,- pendingNotificationPath: iosStandalone- ? takePendingWebPushLaunchPath()- : Promise.resolve<string | null>(null),+ // Consume a launch handoff even when the browser honored openWindow's+ // exact route, so it cannot redirect a later resume.+ pendingNotificationPath: takePendingWebPushLaunchPath(),};});const [launchRestorePath, setLaunchRestorePath] = useState<string | null | undefined>(diff --git a/ui/src/context/ApiContext.expectedErrors.test.tsx b/ui/src/context/ApiContext.expectedErrors.test.tsxindex ef1c883cd..b8609b8b0 100644--- a/ui/src/context/ApiContext.expectedErrors.test.tsx+++ b/ui/src/context/ApiContext.expectedErrors.test.tsx@@ -69,6 +69,25 @@ const mountApi = async () => {const apiContextSource = () => readFileSync(join(__dirname, 'ApiContext.tsx'), 'utf8');describe('ApiProvider expected error codes', () => {+ it('marks push-triggered Inbox reads as non-renewing without changing interactive reads', async () => {+ const api = await mountApi();+ const inbox = { sessions: [], next_cursor: null, unread_by_session: {} };+ apiFetch.mockImplementation(async () => Response.json(inbox));++ await expect(api.listInbox({ platform: 'avibe', limit: 1, backgroundPush: true })).resolves.toEqual(inbox);+ expect(apiFetch).toHaveBeenLastCalledWith('/api/inbox?platform=avibe&limit=1', {+ headers: { 'X-Avibe-Background-Push': '1' },+ });++ await expect(api.listInbox({ platform: 'avibe', limit: 1, cache: false })).resolves.toEqual(inbox);+ expect(apiFetch).toHaveBeenLastCalledWith('/api/inbox?platform=avibe&limit=1');++ apiFetch.mockResolvedValue(Response.json({ error: 'remote_access_login_required' }, { status: 401 }));+ await expect(api.listInbox({ platform: 'avibe', limit: 1, backgroundPush: true })).rejects.toThrow(+ 'Background Inbox refresh failed (401)',+ );+ });+it('suppresses only the expected refusal for the OpenCode picker POST', async () => {const api = await mountApi();diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex c00f0f379..8ba9c8005 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -798,7 +798,7 @@ export type ApiContextType = {draft: { text: string; updated_at: string | null },) => Promise<void>;recoverSessionDraftAfterRejectedSend: (sessionId: string) => Promise<void>;- listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; onlySession?: string; cache?: boolean; handleError?: boolean }) => Promise<InboxFeedResult>;+ listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; onlySession?: string; cache?: boolean; handleError?: boolean; backgroundPush?: boolean }) => Promise<InboxFeedResult>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;listVibeAgents: (params?: {backend?: string;@@ -4249,6 +4249,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenif (params?.onlySession) search.set('session', params.onlySession);const qs = search.toString();const path = qs ? `/api/inbox?${qs}` : '/api/inbox';+ if (params?.backgroundPush) {+ // A Push-triggered page read is non-interactive just like the worker's+ // own read. Bypass the shared cache and never adopt an error as an empty map.+ return apiFetch(path, { headers: { 'X-Avibe-Background-Push': '1' } }).then(async (response) => {+ if (!response.ok) throw new Error(`Background Inbox refresh failed (${response.status})`);+ return response.json();+ });+ }const options = { handleError: params?.handleError };return params?.cache === false ? getJson(path, options) : getCachedJson(path, 1500, options);},diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex 9d9471427..6ba3cf4c6 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -7,6 +7,7 @@ import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext'import { sessionActivityInboxAction } from '../lib/inboxActivity';import { syncFaviconBadge } from '../lib/faviconBadge';import { useConsumerActivation } from '../lib/useConsumerActivation';+import { onPageReactivated } from '../lib/pageActivity';import {createWorkbenchSessionReadOwnership,type WorkbenchSessionReadStamp,@@ -572,7 +573,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// cursor, so activating the feed later still starts from a real first page.// (The server clamps `limit` to at least 1; a true zero-row read would need an// API change, deliberately out of scope here.)- const refreshUnread = useCallback(async function refreshUnread() {+ const refreshUnread = useCallback(async function refreshUnread(backgroundPush = false) {if (unreadReadInFlightRef.current) {unreadReadPendingRef.current = true;return;@@ -600,6 +601,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>limit: 1,cache: false,handleError: false,+ backgroundPush,});if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {applyWholeUnreadRead(read, result.unread_by_session ?? {});@@ -919,6 +921,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// ``totalUnread`` is just the default 0, and clearing here would wipe a badge// the service worker set while the app was closed if that initial load is slow,// fails, or redirects on an expired session. Once loaded, a real 0 clears it.+ // A fresh authoritative map reasserts the badge even when its numeric sum+ // is unchanged: a worker may have written an older sum between reads.useEffect(() => {const nav = navigator as Navigator & {setAppBadge?: (contents?: number) => Promise<void>;@@ -928,7 +932,34 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>if (!unreadLoaded) return;const op = totalUnread > 0 ? nav.setAppBadge?.(totalUnread) : nav.clearAppBadge?.();void op?.catch?.(() => {});- }, [totalUnread, unreadLoaded]);+ // Fence a background worker read that started before this authoritative+ // map arrived. The worker serializes its own setter after this message, so+ // a late Push response cannot be the final badge write.+ try {+ navigator.serviceWorker?.controller?.postMessage({+ type: 'vibe.app-badge-current',+ count: totalUnread,+ });+ } catch {+ // The direct badge write above still works without a controlling worker.+ }+ }, [unreadBySession, totalUnread, unreadLoaded]);++ // A worker can finish a background badge write after this page's last+ // unread update. Revalidate on its completion signal and whenever the page+ // returns from suspension, even if the local unread total did not change.+ useEffect(() => {+ if (!('serviceWorker' in navigator) || !('setAppBadge' in navigator)) return;+ const onWorkerMessage = (event: MessageEvent) => {+ if (event.data?.type === 'vibe.push-badge-refresh') void refreshUnread(true);+ };+ const unsubscribeResume = onPageReactivated(() => void refreshUnread());+ navigator.serviceWorker.addEventListener('message', onWorkerMessage);+ return () => {+ unsubscribeResume();+ navigator.serviceWorker.removeEventListener('message', onWorkerMessage);+ };+ }, [refreshUnread]);// Browser tabs have no Badging API. Keep their favicon useful while the// Inbox map is authoritative, and restore the original icon after reading.diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsxindex ca11ac86e..4ab2bc5e4 100644--- a/ui/src/context/shellBootstrapDemand.test.tsx+++ b/ui/src/context/shellBootstrapDemand.test.tsx@@ -80,7 +80,7 @@ const inboxPayload = {unread_by_session: { [session.id]: 3 },};-type ListInboxArgs = { platform: string; limit: number; before?: string; onlySession?: string };+type ListInboxArgs = { platform: string; limit: number; before?: string; onlySession?: string; backgroundPush?: boolean };type FakeApi = {getWorkbenchProjectsBootstrap?: () => Promise<unknown>;@@ -769,6 +769,55 @@ describe('Demand-driven shell bootstrap', () => {// deliver the map may fail, be invalidated, or be dropped by the gate, and the// badge still ends up with one.describe('the unread map no route gates', () => {+ it('reapplies an unchanged authoritative badge count after a worker write', async () => {+ const originalSetBadge = Object.getOwnPropertyDescriptor(navigator, 'setAppBadge');+ const originalClearBadge = Object.getOwnPropertyDescriptor(navigator, 'clearAppBadge');+ const originalWorker = Object.getOwnPropertyDescriptor(navigator, 'serviceWorker');+ const setAppBadge = vi.fn(async () => {});+ const clearAppBadge = vi.fn(async () => {});+ const worker = new EventTarget();+ Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: setAppBadge });+ Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: clearAppBadge });+ Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: worker });++ try {+ const listInbox = vi.fn(async (_args: ListInboxArgs) => ({+ sessions: [],+ next_cursor: null,+ unread_by_session: {},+ }));+ apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };+ render(+ <WorkbenchInboxProvider>+ <InboxProbe feed={false} />+ </WorkbenchInboxProvider>,+ );+ await settle();+ expect(clearAppBadge).toHaveBeenCalledOnce();++ // The worker finished a stale write just after the page's last 0.+ await setAppBadge(1);+ await act(async () => {+ worker.dispatchEvent(new MessageEvent('message', {+ data: { type: 'vibe.push-badge-refresh' },+ }));+ });+ await settle();++ expect(listInbox).toHaveBeenCalledTimes(2);+ expect(listInbox.mock.calls[1][0]).toMatchObject({ backgroundPush: true });+ expect(clearAppBadge).toHaveBeenCalledTimes(2);+ } finally {+ cleanup();+ if (originalSetBadge) Object.defineProperty(navigator, 'setAppBadge', originalSetBadge);+ else Reflect.deleteProperty(navigator, 'setAppBadge');+ if (originalClearBadge) Object.defineProperty(navigator, 'clearAppBadge', originalClearBadge);+ else Reflect.deleteProperty(navigator, 'clearAppBadge');+ if (originalWorker) Object.defineProperty(navigator, 'serviceWorker', originalWorker);+ else Reflect.deleteProperty(navigator, 'serviceWorker');+ }+ });+it('reads the counts a dropped feed read was carrying', async () => {const feedRead = deferred<typeof inboxPayload>();const countsOnly = {diff --git a/ui/src/lib/pushServiceWorker.test.ts b/ui/src/lib/pushServiceWorker.test.tsindex 3f0ad7b8d..747e067f6 100644--- a/ui/src/lib/pushServiceWorker.test.ts+++ b/ui/src/lib/pushServiceWorker.test.ts@@ -4,6 +4,144 @@ import { runInNewContext } from 'node:vm';import { describe, expect, it, vi } from 'vitest';describe('push service worker notification launches', () => {+ it('hands a tapped session to a reused app window without hard navigation', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/settings/general',+ focus: vi.fn(async () => client),+ navigate: vi.fn(async (href: string) => ({ url: href })),+ postMessage: vi.fn(),+ };+ const openWindow = vi.fn();+ let storedPayload: unknown;+ const cache = {+ put: vi.fn(async (_request: string, response: Response) => {+ storedPayload = await response.json();+ }),+ };+ const worker = {+ location: { origin: 'https://avibe.local' },+ caches: { open: vi.fn(async () => cache) },+ clients: { matchAll: vi.fn(async () => [client]), openWindow },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, { self: worker, navigator: {}, URL, Response, Date, Number, JSON, Promise });++ let completion: Promise<unknown> | undefined;+ handlers.get('notificationclick')?.({+ notification: { close: vi.fn(), data: { url: '/chat/session-3' } },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(client.focus).toHaveBeenCalledOnce();+ expect(storedPayload).toMatchObject({ url: '/chat/session-3', createdAt: expect.any(Number) });+ expect(cache.put.mock.invocationCallOrder[0]).toBeLessThan(client.focus.mock.invocationCallOrder[0]);+ expect(client.navigate).not.toHaveBeenCalled();+ expect(client.postMessage).toHaveBeenCalledWith({+ type: 'vibe.notification-click',+ url: '/chat/session-3',+ });+ expect(openWindow).not.toHaveBeenCalled();+ });++ it('delivers rapid clicks in tap order even when the first focus is delayed', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ let finishFirstFocus: (client: unknown) => void = () => {};+ const firstFocus = new Promise<unknown>((resolve) => {+ finishFirstFocus = resolve;+ });+ const client = {+ url: 'https://avibe.local/settings/general',+ focus: vi.fn().mockImplementationOnce(() => firstFocus).mockImplementationOnce(async () => client),+ postMessage: vi.fn(),+ };+ const cache = { put: vi.fn(async () => {}) };+ const worker = {+ location: { origin: 'https://avibe.local' },+ caches: { open: vi.fn(async () => cache) },+ clients: { matchAll: vi.fn(async () => [client]) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, { self: worker, navigator: {}, URL, Response, Date, Number, JSON, Promise });++ const click = (url: string) => {+ let completion: Promise<unknown> | undefined;+ handlers.get('notificationclick')?.({+ notification: { close: vi.fn(), data: { url } },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ return completion;+ };+ const first = click('/chat/session-1');+ await vi.waitFor(() => expect(client.focus).toHaveBeenCalledTimes(1));+ const second = click('/chat/session-2');+ expect(client.postMessage).not.toHaveBeenCalled();++ finishFirstFocus(client);+ await Promise.all([first, second]);+ expect(client.postMessage.mock.calls.map(([message]) => message.url)).toEqual([+ '/chat/session-1',+ '/chat/session-2',+ ]);+ });++ it('posts to a reused window without WindowClient.navigate support', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/inbox',+ focus: vi.fn(async () => client),+ navigate: vi.fn(async () => null),+ postMessage: vi.fn(),+ };+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => [client]) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, { self: worker, navigator: {}, URL, Response, Date, Number, JSON, Promise });++ let completion: Promise<unknown> | undefined;+ handlers.get('notificationclick')?.({+ notification: { close: vi.fn(), data: { url: '/chat/session-4' } },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(client.postMessage).toHaveBeenCalledWith({+ type: 'vibe.notification-click',+ url: '/chat/session-4',+ });+ });++ it('opens the target when an existing app window cannot be focused', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/apps/files',+ focus: vi.fn(async () => { throw new Error('window closed'); }),+ };+ const openWindow = vi.fn(async () => null);+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => [client]), openWindow },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, { self: worker, navigator: {}, URL, Response, Date, Number, JSON, Promise });++ let completion: Promise<unknown> | undefined;+ handlers.get('notificationclick')?.({+ notification: { close: vi.fn(), data: { url: '/chat/session-5' } },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(openWindow).toHaveBeenCalledWith('https://avibe.local/chat/session-5');+ });+it('persists and posts the target when no app-shell client is open', async () => {const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');const handlers = new Map<string, (event: unknown) => void>();@@ -39,9 +177,8 @@ describe('push service worker notification launches', () => {await completion;expect(notification.close).toHaveBeenCalledOnce();- expect(cache.put).toHaveBeenCalledWith(- 'https://avibe.local/__avibe/web-push-launch',- expect.any(Response),+ expect(cache.put.mock.calls[0][0]).toMatch(+ /^https:\/\/avibe\.local\/__avibe\/web-push-launch\/\d+-[a-z0-9]+$/,);expect(storedPayload).toMatchObject({ url: '/chat/session-3', createdAt: expect.any(Number) });expect(openWindow).toHaveBeenCalledWith('https://avibe.local/chat/session-3');@@ -51,6 +188,379 @@ describe('push service worker notification launches', () => {});});+ it('uses current server unread count instead of a delayed push count for the app badge', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const setAppBadge = vi.fn(async () => {});+ const clearAppBadge = vi.fn(async () => {});+ const fetchMock = vi.fn(async () => Response.json({ unread_total: 0 }));+ const showNotification = vi.fn(async () => {});+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => []) },+ registration: { showNotification },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: fetchMock,+ navigator: { setAppBadge, clearAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ title: 'Avibe', badge_count: 3 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(showNotification).toHaveBeenCalledOnce();+ expect(fetchMock).toHaveBeenCalledWith('/api/inbox?platform=avibe&limit=1', {+ credentials: 'same-origin',+ cache: 'no-store',+ headers: { 'X-Avibe-Background-Push': '1' },+ });+ expect(clearAppBadge).toHaveBeenCalledOnce();+ expect(setAppBadge).not.toHaveBeenCalled();+ });++ it('leaves the badge alone when the current unread count cannot be verified', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const setAppBadge = vi.fn(async () => {});+ const clearAppBadge = vi.fn(async () => {});+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => []) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: vi.fn(async () => new Response(null, { status: 401 })),+ navigator: { setAppBadge, clearAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 3 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(setAppBadge).not.toHaveBeenCalled();+ expect(clearAppBadge).not.toHaveBeenCalled();+ });++ it('sets a verified nonzero badge count while the app is closed', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const setAppBadge = vi.fn(async () => {});+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => []) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: vi.fn(async () => Response.json({ unread_total: 2 })),+ navigator: { setAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 1 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(setAppBadge).toHaveBeenCalledWith(2);+ });++ it('lets a visible app refresh its own badge instead of writing from the worker', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/chat/session-1',+ visibilityState: 'visible',+ postMessage: vi.fn(),+ };+ const setAppBadge = vi.fn(async () => {});+ const fetchMock = vi.fn();+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => [client]) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: fetchMock,+ navigator: { setAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 2 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(fetchMock).not.toHaveBeenCalled();+ expect(setAppBadge).not.toHaveBeenCalled();+ expect(client.postMessage).toHaveBeenCalledWith({ type: 'vibe.push-badge-refresh' });+ });++ it('does not ask a hidden page to make an interactive Inbox read after Push', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/inbox',+ visibilityState: 'hidden',+ postMessage: vi.fn(),+ };+ const setAppBadge = vi.fn(async () => {});+ const fetchMock = vi.fn(async () => Response.json({ unread_total: 2 }));+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => [client]) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: fetchMock,+ navigator: { setAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 1 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(fetchMock).toHaveBeenCalledWith('/api/inbox?platform=avibe&limit=1', {+ credentials: 'same-origin',+ cache: 'no-store',+ headers: { 'X-Avibe-Background-Push': '1' },+ });+ expect(setAppBadge).toHaveBeenCalledWith(2);+ expect(client.postMessage).not.toHaveBeenCalled();+ });++ it('notifies a page that becomes visible while the worker writes a badge', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/inbox',+ visibilityState: 'hidden',+ postMessage: vi.fn(),+ };+ const setAppBadge = vi.fn(async () => {+ client.visibilityState = 'visible';+ });+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => [client]) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: vi.fn(async () => Response.json({ unread_total: 2 })),+ navigator: { setAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 1 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await completion;++ expect(setAppBadge).toHaveBeenCalledWith(2);+ expect(client.postMessage).toHaveBeenCalledWith({ type: 'vibe.push-badge-refresh' });+ });++ it('does not apply a fetched count after the app becomes visible', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const client = {+ url: 'https://avibe.local/inbox',+ visibilityState: 'hidden',+ postMessage: vi.fn(),+ };+ const setAppBadge = vi.fn(async () => {});+ let releaseFetch: (response: Response) => void = () => {};+ const fetchPending = new Promise<Response>((resolve) => { releaseFetch = resolve; });+ let fetchStarted: () => void = () => {};+ const started = new Promise<void>((resolve) => { fetchStarted = resolve; });+ const fetchMock = vi.fn(() => {+ fetchStarted();+ return fetchPending;+ });+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => [client]) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: fetchMock,+ navigator: { setAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let completion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 3 }) },+ waitUntil: (promise: Promise<unknown>) => { completion = promise; },+ });+ await started;+ client.visibilityState = 'visible';+ releaseFetch(Response.json({ unread_total: 3 }));+ await completion;++ expect(setAppBadge).not.toHaveBeenCalled();+ expect(client.postMessage).toHaveBeenCalledWith({ type: 'vibe.push-badge-refresh' });+ });++ it('does not restore an older push count after the page clears the badge', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ const setAppBadge = vi.fn(async () => {});+ const clearAppBadge = vi.fn(async () => {});+ let releaseFetch: (response: Response) => void = () => {};+ const fetchPending = new Promise<Response>((resolve) => { releaseFetch = resolve; });+ let fetchStarted: () => void = () => {};+ const started = new Promise<void>((resolve) => { fetchStarted = resolve; });+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => []) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: vi.fn(() => { fetchStarted(); return fetchPending; }),+ navigator: { setAppBadge, clearAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let pushCompletion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 3 }) },+ waitUntil: (promise: Promise<unknown>) => { pushCompletion = promise; },+ });+ await started;+ let pageCompletion: Promise<unknown> | undefined;+ handlers.get('message')?.({+ data: { type: 'vibe.app-badge-current', count: 0 },+ waitUntil: (promise: Promise<unknown>) => { pageCompletion = promise; },+ });+ await pageCompletion;+ releaseFetch(Response.json({ unread_total: 3 }));+ await pushCompletion;++ expect(clearAppBadge).toHaveBeenCalledOnce();+ expect(setAppBadge).not.toHaveBeenCalled();+ });++ it('serializes a page clear after a worker badge write already started', async () => {+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');+ const handlers = new Map<string, (event: unknown) => void>();+ let releaseSet: () => void = () => {};+ const setPending = new Promise<void>((resolve) => { releaseSet = resolve; });+ let setStarted: () => void = () => {};+ const started = new Promise<void>((resolve) => { setStarted = resolve; });+ const setAppBadge = vi.fn(() => { setStarted(); return setPending; });+ const clearAppBadge = vi.fn(async () => {});+ const worker = {+ location: { origin: 'https://avibe.local' },+ clients: { matchAll: vi.fn(async () => []) },+ registration: { showNotification: vi.fn(async () => {}) },+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),+ };+ runInNewContext(source, {+ self: worker,+ fetch: vi.fn(async () => Response.json({ unread_total: 3 })),+ navigator: { setAppBadge, clearAppBadge },+ URL,+ Response,+ Date,+ Number,+ JSON,+ Promise,+ });++ let pushCompletion: Promise<unknown> | undefined;+ handlers.get('push')?.({+ data: { json: () => ({ badge_count: 3 }) },+ waitUntil: (promise: Promise<unknown>) => { pushCompletion = promise; },+ });+ await started;+ let pageCompletion: Promise<unknown> | undefined;+ handlers.get('message')?.({+ data: { type: 'vibe.app-badge-current', count: 0 },+ waitUntil: (promise: Promise<unknown>) => { pageCompletion = promise; },+ });+ releaseSet();+ await Promise.all([pushCompletion, pageCompletion]);++ expect(setAppBadge).toHaveBeenCalledWith(3);+ expect(clearAppBadge).toHaveBeenCalledOnce();+ expect(setAppBadge.mock.invocationCallOrder[0]).toBeLessThan(clearAppBadge.mock.invocationCallOrder[0]);+ });+it('syncs a replacement subscription and retires the old endpoint', async () => {const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');const handlers = new Map<string, (event: unknown) => void>();diff --git a/ui/src/lib/webPushLaunch.test.ts b/ui/src/lib/webPushLaunch.test.tsindex 2a44a9f05..f8ad2822a 100644--- a/ui/src/lib/webPushLaunch.test.ts+++ b/ui/src/lib/webPushLaunch.test.ts@@ -2,11 +2,52 @@ import { describe, expect, it, vi } from 'vitest';import {createPendingWebPushLaunchReader,+ createResumedWebPushLaunchReader,+ createWebPushLaunchNavigation,parsePendingWebPushLaunch,WEB_PUSH_LAUNCH_MAX_AGE_MS,} from './webPushLaunch';describe('pending web-push launches', () => {+ it('does not let a delayed resume read override a later click message', async () => {+ let finishResume: (path: string | null) => void = () => {};+ const resume = new Promise<string | null>((resolve) => {+ finishResume = resolve;+ });+ const read = vi.fn((expectedPath?: string) => expectedPath ? Promise.resolve(null) : resume);+ const navigate = vi.fn();+ const navigation = createWebPushLaunchNavigation(read, navigate);++ navigation.reactivated();+ navigation.notificationClick('/chat/session-2');+ finishResume('/chat/session-1');+ await resume;+ await Promise.resolve();++ expect(navigate).toHaveBeenCalledTimes(1);+ expect(navigate).toHaveBeenCalledWith('/chat/session-2');+ expect(read).toHaveBeenCalledWith('/chat/session-2');+ navigation.dispose();+ });++ it('keeps only the newest of two overlapping resume reads', async () => {+ const finish: Array<(path: string | null) => void> = [];+ const read = vi.fn(() => new Promise<string | null>((resolve) => finish.push(resolve)));+ const navigate = vi.fn();+ const navigation = createWebPushLaunchNavigation(read, navigate);++ navigation.reactivated();+ navigation.reactivated();+ finish[1]('/chat/session-2');+ await Promise.resolve();+ finish[0]('/chat/session-1');+ await Promise.resolve();++ expect(navigate).toHaveBeenCalledTimes(1);+ expect(navigate).toHaveBeenCalledWith('/chat/session-2');+ navigation.dispose();+ });+it('accepts only fresh canonical app paths', () => {const now = 1_000_000;expect(parsePendingWebPushLaunch({ url: '/chat/session-1?from=push', createdAt: now - 1 }, now)).toBe(@@ -23,8 +64,9 @@ describe('pending web-push launches', () => {it('consumes the cached target once and shares the result across StrictMode reads', async () => {const now = 2_000_000;- const entryUrl = 'https://avibe.local/__avibe/web-push-launch';+ const entryUrl = 'https://avibe.local/__avibe/web-push-launch/click-1';const cache = {+ keys: vi.fn(async () => [entryUrl]),match: vi.fn(async () => new Response(JSON.stringify({ url: '/chat/session-2', createdAt: now }))),delete: vi.fn(async () => true),};@@ -45,4 +87,100 @@ describe('pending web-push launches', () => {const read = createPendingWebPushLaunchReader(() => null);await expect(read()).resolves.toBeNull();});++ it('reads a new target on resume and keeps a newer one when an older message arrives', async () => {+ const now = 2_000_000;+ const entryUrl = 'https://avibe.local/__avibe/web-push-launch/click-1';+ let payload: { url: string; createdAt: number } | null = null;+ const cache = {+ keys: vi.fn(async () => payload ? [entryUrl] : []),+ match: vi.fn(async () => payload ? Response.json(payload) : undefined),+ delete: vi.fn(async () => { payload = null; return true; }),+ };+ const read = createResumedWebPushLaunchReader(() => ({+ cacheStorage: { open: async () => cache },+ origin: 'https://avibe.local',+ now: () => now,+ }));++ payload = { url: '/chat/session-2', createdAt: now };+ await expect(read('/chat/session-1')).resolves.toBeNull();+ expect(cache.delete).not.toHaveBeenCalled();+ await expect(read()).resolves.toBe('/chat/session-2');+ expect(cache.delete).toHaveBeenCalledWith(entryUrl);++ payload = { url: '/chat/session-3', createdAt: now };+ await expect(read('/chat/session-3?from=push')).resolves.toBe('/chat/session-3');+ expect(cache.delete).toHaveBeenCalledTimes(2);+ });++ it('does not delete a second click stored while the first response is being read', async () => {+ const now = 2_000_000;+ const firstUrl = 'https://avibe.local/__avibe/web-push-launch/click-1';+ const secondUrl = 'https://avibe.local/__avibe/web-push-launch/click-2';+ const stored = new Map<string, { url: string; createdAt: number }>([+ [firstUrl, { url: '/chat/session-1', createdAt: now - 1 }],+ ]);+ let releaseFirst: (payload: { url: string; createdAt: number }) => void = () => {};+ let firstMatched: () => void = () => {};+ const firstBody = new Promise<{ url: string; createdAt: number }>((resolve) => {+ releaseFirst = resolve;+ });+ const matched = new Promise<void>((resolve) => {+ firstMatched = resolve;+ });+ const cache = {+ keys: vi.fn(async () => [...stored.keys()]),+ match: vi.fn(async (key: string) => {+ if (key === firstUrl) {+ firstMatched();+ return { json: () => firstBody } as Response;+ }+ const payload = stored.get(key);+ return payload ? Response.json(payload) : undefined;+ }),+ delete: vi.fn(async (key: string) => stored.delete(key)),+ };+ const read = createResumedWebPushLaunchReader(() => ({+ cacheStorage: { open: async () => cache },+ origin: 'https://avibe.local',+ now: () => now,+ }));++ const firstRead = read();+ await matched;+ stored.set(secondUrl, { url: '/chat/session-2', createdAt: now });+ releaseFirst({ url: '/chat/session-1', createdAt: now - 1 });+ await expect(firstRead).resolves.toBe('/chat/session-1');+ expect(stored.has(secondUrl)).toBe(true);+ expect(cache.delete).toHaveBeenCalledWith(firstUrl);+ expect(cache.delete).not.toHaveBeenCalledWith(secondUrl);++ await expect(read()).resolves.toBe('/chat/session-2');+ expect(stored.size).toBe(0);+ });++ it('takes the newest clicked session and drains older handoffs from the same snapshot', async () => {+ const now = 2_000_000;+ const firstUrl = 'https://avibe.local/__avibe/web-push-launch/click-1';+ const secondUrl = 'https://avibe.local/__avibe/web-push-launch/click-2';+ const stored = new Map<string, { url: string; createdAt: number }>([+ [secondUrl, { url: '/chat/session-2', createdAt: now }],+ [firstUrl, { url: '/chat/session-1', createdAt: now - 1 }],+ ]);+ const cache = {+ keys: vi.fn(async () => [...stored.keys()]),+ match: vi.fn(async (key: string) => Response.json(stored.get(key))),+ delete: vi.fn(async (key: string) => stored.delete(key)),+ };+ const read = createResumedWebPushLaunchReader(() => ({+ cacheStorage: { open: async () => cache },+ origin: 'https://avibe.local',+ now: () => now,+ }));++ await expect(read()).resolves.toBe('/chat/session-2');+ expect(stored.size).toBe(0);+ await expect(read()).resolves.toBeNull();+ });});diff --git a/ui/src/lib/webPushLaunch.ts b/ui/src/lib/webPushLaunch.tsindex e734fbfa7..c957a0142 100644--- a/ui/src/lib/webPushLaunch.ts+++ b/ui/src/lib/webPushLaunch.ts@@ -10,8 +10,9 @@ interface PendingWebPushLaunch {}interface LaunchCache {- match(request: string): Promise<Response | undefined>;- delete(request: string): Promise<boolean>;+ keys(): Promise<readonly (Request | string)[]>;+ match(request: Request | string): Promise<Response | undefined>;+ delete(request: Request | string): Promise<boolean>;}interface LaunchCacheStorage {@@ -34,6 +35,46 @@ export function parsePendingWebPushLaunch(value: unknown, now: number): string |return normalizeRestorablePwaPath(url);}+async function consumePendingWebPushLaunch(+ environment: LaunchReaderEnvironment | null,+ expectedPath?: string,+): Promise<string | null> {+ if (!environment) return null;+ try {+ const cache = await environment.cacheStorage.open(CACHE_NAME);+ const requests = (await cache.keys()).filter((request) =>+ new URL(typeof request === 'string' ? request : request.url).pathname.startsWith(CACHE_ENTRY_PATH),+ );+ const now = environment.now();+ const entries = await Promise.all(requests.map(async (request) => {+ try {+ const response = await cache.match(request);+ const payload = response ? await response.json() : null;+ return {+ request,+ path: parsePendingWebPushLaunch(payload, now),+ createdAt: typeof payload?.createdAt === 'number' ? payload.createdAt : -1,+ };+ } catch {+ return { request, path: null, createdAt: -1 };+ }+ }));+ const latest = entries.reduce<(typeof entries)[number] | null>(+ (current, entry) => entry.path && (!current || entry.createdAt >= current.createdAt) ? entry : current,+ null,+ );+ // A newer notification may have replaced the handoff before a prior+ // message reaches the page. Do not consume that newer destination.+ if (expectedPath && latest?.path && latest.path !== normalizeRestorablePwaPath(expectedPath)) return null;+ // Delete only keys returned by this snapshot. A click written while JSON+ // was loading has its own key and must survive for the next resume.+ await Promise.all(entries.map((entry) => cache.delete(entry.request)));+ return latest?.path ?? null;+ } catch {+ return null;+ }+}+function browserEnvironment(): LaunchReaderEnvironment | null {if (typeof window === 'undefined' || !('caches' in window)) return null;return {@@ -53,23 +94,48 @@ export function createPendingWebPushLaunchReader(return () => {if (readPromise) return readPromise;- readPromise = (async () => {- try {- const environment = getEnvironment();- if (!environment) return null;-- const cache = await environment.cacheStorage.open(CACHE_NAME);- const entryUrl = new URL(CACHE_ENTRY_PATH, environment.origin).href;- const response = await cache.match(entryUrl);- if (!response) return null;- await cache.delete(entryUrl);- return parsePendingWebPushLaunch(await response.json(), environment.now());- } catch {- return null;- }- })();+ readPromise = consumePendingWebPushLaunch(getEnvironment());return readPromise;};}export const takePendingWebPushLaunchPath = createPendingWebPushLaunchReader();++// Unlike the initial-launch reader, this must read again for every resumed+// page: a notification can be tapped long after the document first mounted.+export function createResumedWebPushLaunchReader(+ getEnvironment: () => LaunchReaderEnvironment | null = browserEnvironment,+): (expectedPath?: string) => Promise<string | null> {+ return (expectedPath) => consumePendingWebPushLaunch(getEnvironment(), expectedPath);+}++export const takeResumedWebPushLaunchPath = createResumedWebPushLaunchReader();++// Worker clicks arrive in order, but a page's cache read can finish after a+// later click or another reactivation. Only the newest request may navigate.+export function createWebPushLaunchNavigation(+ read: (expectedPath?: string) => Promise<string | null>,+ navigate: (path: string) => void,+) {+ let generation = 0;+ let active = true;++ return {+ notificationClick(path: string) {+ if (!active) return;+ generation += 1;+ void read(path).catch(() => {});+ navigate(path);+ },+ reactivated() {+ if (!active) return;+ const current = ++generation;+ void read().then((path) => {+ if (active && current === generation && path) navigate(path);+ }).catch(() => {});+ },+ dispose() {+ active = false;+ },+ };+}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 9c192a7a6..666561853 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3083,6 +3083,11 @@ def renew_remote_access_cookie(response: Response) -> Response:# Logout handler explicitly clears the session cookie; never re-issue it.if getattr(g, "remote_session_logout", False):return response+ # A credentialed Push worker read is not an interactive visit. It may+ # arrive regularly while the app is closed and must not keep a remote+ # browser session alive merely by refreshing its icon badge.+ if request.path == "/api/inbox" and request.headers.get("X-Avibe-Background-Push") == "1":+ return responseif _is_current_immutable_static_asset_request():return responserenew = getattr(g, "remote_session_renew", None)