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.

feat(pwa): restore the last visited page after cold launch (#925)

Call Whitef8e526c96fda
diff --git a/ui/public/push-sw.js b/ui/public/push-sw.js
index 0b9640117..05c50eb20 100644
--- a/ui/public/push-sw.js
+++ b/ui/public/push-sw.js
@@ -15,6 +15,24 @@ function syncAppBadge(count) {
return op && typeof op.catch === 'function' ? op.catch(() => {}) : null;
}
+const WEB_PUSH_LAUNCH_CACHE = 'avibe.web-push-launch.v1';
+const WEB_PUSH_LAUNCH_ENTRY_PATH = '/__avibe/web-push-launch';
+
+// iOS may honor an installed PWA's manifest start URL instead of the path passed
+// to openWindow(). Leave a short-lived launch handoff in Cache Storage so the
+// 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() }), {
+ headers: { 'content-type': 'application/json' },
+ });
+ return self.caches
+ .open(WEB_PUSH_LAUNCH_CACHE)
+ .then((cache) => cache.put(entryUrl, response))
+ .catch(() => {});
+}
+
self.addEventListener('push', (event) => {
let payload = {};
try {
@@ -69,7 +87,16 @@ self.addEventListener('notificationclick', (event) => {
}
}
if (self.clients.openWindow) {
- return self.clients.openWindow(href);
+ return rememberPendingNotificationLaunch(message.url)
+ .then(() => self.clients.openWindow(href))
+ .then((openedClient) => {
+ try {
+ openedClient?.postMessage(message);
+ } catch {
+ // Cache Storage remains as the cold-launch fallback.
+ }
+ return openedClient;
+ });
}
return undefined;
}),
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index dc949ec2a..0e3883705 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -67,6 +67,14 @@ const ShowPageRoute = lazy(() =>
import('./components/apps/ShowPageRoute').then((m) => ({ default: m.ShowPageRoute })),
);
import { hasConfiguredPlatformCredentials } from './lib/platforms';
+import { isIosDevice, isStandalonePwa } from './lib/platform';
+import {
+ readLastPwaPath,
+ resolvePwaLaunchPath,
+ shouldRestorePwaLaunch,
+ writeLastPwaPath,
+} from './lib/pwaRouteMemory';
+import { takePendingWebPushLaunchPath } from './lib/webPushLaunch';
import { applyAppTitle } from './lib/documentTitle';
import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';
@@ -376,11 +384,62 @@ const DocumentTitle = () => {
return null;
};
+// Installed iOS PWAs launch at the manifest's `/` start URL after iOS has
+// evicted the process. Restore the last canonical app route only for that cold
+// launch; later in-app navigation to `/` must still reach the workbench canvas.
+const PwaRouteMemory = () => {
+ const location = useLocation();
+ const [launch] = useState(() => {
+ const iosStandalone = isIosDevice() && isStandalonePwa();
+ return {
+ iosStandalone,
+ locationKey: location.key,
+ location,
+ pendingNotificationPath: iosStandalone
+ ? takePendingWebPushLaunchPath()
+ : Promise.resolve<string | null>(null),
+ };
+ });
+ const [launchRestorePath, setLaunchRestorePath] = useState<string | null | undefined>(
+ launch.iosStandalone ? undefined : null,
+ );
+ const restoringLaunch =
+ launchRestorePath !== undefined &&
+ shouldRestorePwaLaunch(launchRestorePath, launch.locationKey, location);
+ const restorePath = restoringLaunch ? launchRestorePath : null;
+
+ useEffect(() => {
+ if (!launch.iosStandalone) return;
+ let active = true;
+ launch.pendingNotificationPath.then((pendingPath) => {
+ if (!active) return;
+ setLaunchRestorePath(
+ resolvePwaLaunchPath(true, launch.location, pendingPath ?? readLastPwaPath()),
+ );
+ });
+ return () => {
+ active = false;
+ };
+ }, [launch]);
+
+ useEffect(() => {
+ if (!launch.iosStandalone || launchRestorePath === undefined) return;
+ // Do not overwrite the remembered destination while <Navigate> is still
+ // replacing the manifest start URL (including StrictMode's second effect).
+ if (restoringLaunch) return;
+
+ writeLastPwaPath(location.pathname);
+ }, [launch.iosStandalone, launchRestorePath, location.pathname, restoringLaunch]);
+
+ return restorePath ? <Navigate to={restorePath} replace /> : null;
+};
+
function RouterRoot() {
return (
<UnsavedChangesProvider>
<DocumentTitle />
<WebPushNotificationNavigator />
+ <PwaRouteMemory />
<Outlet />
</UnsavedChangesProvider>
);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fa11363e3..858c3a543 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1656,8 +1656,8 @@
"metricPlatformsHint": "connected across the catalog",
"metricGroups": "Active groups",
"metricGroupsHint": "{{count}} discovered total",
- "metricUsers": "Bound users",
- "metricUsersHint": "authorized to access this node",
+ "metricUsers": "Bound direct chats",
+ "metricUsersHint": "allowed IM direct-message users",
"metricCloud": "Avibe Cloud",
"metricCloudConnected": "Connected",
"metricCloudConfigured": "Configured",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 0849d2d59..758da9343 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1656,8 +1656,8 @@
"metricPlatformsHint": "已连接的平台数 / 平台目录总数",
"metricGroups": "活跃群组",
"metricGroupsHint": "总共发现了 {{count}} 个群组",
- "metricUsers": "已绑定用户",
- "metricUsersHint": "允许访问当前节点的用户数",
+ "metricUsers": "已绑定的私聊",
+ "metricUsersHint": "允许的 IM 私聊用户",
"metricCloud": "Avibe Cloud",
"metricCloudConnected": "已连接",
"metricCloudConfigured": "已配置",
diff --git a/ui/src/lib/pushServiceWorker.test.ts b/ui/src/lib/pushServiceWorker.test.ts
new file mode 100644
index 000000000..cf2063f01
--- /dev/null
+++ b/ui/src/lib/pushServiceWorker.test.ts
@@ -0,0 +1,53 @@
+import { readFile } from 'node:fs/promises';
+import { runInNewContext } from 'node:vm';
+
+import { describe, expect, it, vi } from 'vitest';
+
+describe('push service worker notification launches', () => {
+ 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>();
+ let storedPayload: unknown;
+ const cache = {
+ put: vi.fn(async (_request: string, response: Response) => {
+ storedPayload = await response.json();
+ }),
+ };
+ const openedClient = { postMessage: vi.fn() };
+ const openWindow = vi.fn(async () => openedClient);
+ const worker = {
+ location: { origin: 'https://avibe.local' },
+ caches: { open: vi.fn(async () => cache) },
+ clients: { matchAll: vi.fn(async () => []), openWindow },
+ registration: { showNotification: vi.fn() },
+ 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;
+ const notification = {
+ close: vi.fn(),
+ data: { url: '/chat/session-3' },
+ };
+ handlers.get('notificationclick')?.({
+ notification,
+ waitUntil: (promise: Promise<unknown>) => {
+ completion = promise;
+ },
+ });
+ await completion;
+
+ expect(notification.close).toHaveBeenCalledOnce();
+ expect(cache.put).toHaveBeenCalledWith(
+ 'https://avibe.local/__avibe/web-push-launch',
+ expect.any(Response),
+ );
+ expect(storedPayload).toMatchObject({ url: '/chat/session-3', createdAt: expect.any(Number) });
+ expect(openWindow).toHaveBeenCalledWith('https://avibe.local/chat/session-3');
+ expect(openedClient.postMessage).toHaveBeenCalledWith({
+ type: 'vibe.notification-click',
+ url: '/chat/session-3',
+ });
+ });
+});
diff --git a/ui/src/lib/pwaRouteMemory.test.ts b/ui/src/lib/pwaRouteMemory.test.ts
new file mode 100644
index 000000000..f3a3d9812
--- /dev/null
+++ b/ui/src/lib/pwaRouteMemory.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ normalizeRestorablePwaPath,
+ readLastPwaPath,
+ resolvePwaLaunchPath,
+ shouldRestorePwaLaunch,
+ writeLastPwaPath,
+} from './pwaRouteMemory';
+
+describe('PWA route memory', () => {
+ it('restores canonical and dynamic app pages while dropping URL state', () => {
+ expect(normalizeRestorablePwaPath('/inbox')).toBe('/inbox');
+ expect(normalizeRestorablePwaPath('/chat/session-123?from=push#latest')).toBe('/chat/session-123');
+ expect(normalizeRestorablePwaPath('/admin/settings/backends/codex')).toBe(
+ '/admin/settings/backends/codex',
+ );
+ });
+
+ it('rejects setup, retired, unknown, and cross-origin paths', () => {
+ expect(normalizeRestorablePwaPath('/setup')).toBeNull();
+ expect(normalizeRestorablePwaPath('/more')).toBeNull();
+ expect(normalizeRestorablePwaPath('/unknown')).toBeNull();
+ expect(normalizeRestorablePwaPath('//example.com/inbox')).toBeNull();
+ expect(normalizeRestorablePwaPath('https://example.com/inbox')).toBeNull();
+ });
+
+ it('restores only an installed PWA launched at the manifest root', () => {
+ const root = { pathname: '/', search: '', hash: '' };
+ expect(resolvePwaLaunchPath(true, root, '/chat/session-123')).toBe('/chat/session-123');
+ expect(resolvePwaLaunchPath(false, root, '/chat/session-123')).toBeNull();
+ expect(resolvePwaLaunchPath(true, { ...root, pathname: '/inbox' }, '/chat/session-123')).toBeNull();
+ expect(resolvePwaLaunchPath(true, { ...root, search: '?login=1' }, '/chat/session-123')).toBeNull();
+ expect(resolvePwaLaunchPath(true, root, '/')).toBeNull();
+ });
+
+ it('does not hijack a later in-app navigation back to the workbench root', () => {
+ expect(shouldRestorePwaLaunch('/inbox', 'default', { key: 'default', pathname: '/' })).toBe(true);
+ expect(shouldRestorePwaLaunch('/inbox', 'default', { key: 'later', pathname: '/' })).toBe(false);
+ });
+
+ it('reads and writes through best-effort storage', () => {
+ const getItem = vi.fn(() => '/apps/files');
+ const setItem = vi.fn();
+
+ expect(readLastPwaPath({ getItem })).toBe('/apps/files');
+ writeLastPwaPath('/chat/session-456?ignored=1', { setItem });
+
+ expect(getItem).toHaveBeenCalledOnce();
+ expect(setItem).toHaveBeenCalledWith('avibe.pwa.last-route.v1', '/chat/session-456');
+ });
+
+ it('tolerates unavailable browser storage', () => {
+ expect(
+ readLastPwaPath({
+ getItem: () => {
+ throw new Error('blocked');
+ },
+ }),
+ ).toBeNull();
+ expect(() =>
+ writeLastPwaPath('/inbox', {
+ setItem: () => {
+ throw new Error('blocked');
+ },
+ }),
+ ).not.toThrow();
+ });
+});
diff --git a/ui/src/lib/pwaRouteMemory.ts b/ui/src/lib/pwaRouteMemory.ts
new file mode 100644
index 000000000..be478dcd0
--- /dev/null
+++ b/ui/src/lib/pwaRouteMemory.ts
@@ -0,0 +1,100 @@
+const STORAGE_KEY = 'avibe.pwa.last-route.v1';
+
+type ReadableStorage = Pick<Storage, 'getItem'>;
+type WritableStorage = Pick<Storage, 'setItem'>;
+
+const RESTORABLE_EXACT_PATHS = new Set([
+ '/',
+ '/inbox',
+ '/search',
+ '/agents',
+ '/skills',
+ '/harness',
+ '/vaults',
+ '/projects',
+ '/apps/files',
+ '/apps/terminal',
+ '/apps/editor',
+ '/apps/library',
+ '/admin/dashboard',
+ '/admin/remote-access',
+ '/admin/groups',
+ '/admin/users',
+ '/admin/logs',
+ '/admin/settings/service',
+ '/admin/settings/platforms',
+ '/admin/settings/backends',
+ '/admin/settings/backends/opencode',
+ '/admin/settings/backends/claude',
+ '/admin/settings/backends/codex',
+ '/admin/settings/dependencies',
+ '/admin/settings/messaging',
+ '/admin/settings/diagnostics',
+ '/admin/settings/logs',
+]);
+
+const RESTORABLE_DYNAMIC_PATHS = [/^\/chat\/[^/]+$/, /^\/apps\/show\/[^/]+$/];
+
+export function normalizeRestorablePwaPath(value: unknown): string | null {
+ if (typeof value !== 'string' || !value.startsWith('/')) return null;
+
+ try {
+ const base = new URL('https://avibe.local');
+ const parsed = new URL(value, base);
+ if (parsed.origin !== base.origin) return null;
+
+ const { pathname } = parsed;
+ const restorable =
+ RESTORABLE_EXACT_PATHS.has(pathname) ||
+ RESTORABLE_DYNAMIC_PATHS.some((pattern) => pattern.test(pathname));
+ return restorable ? pathname : null;
+ } catch {
+ return null;
+ }
+}
+
+export function readLastPwaPath(storage?: ReadableStorage): string | null {
+ try {
+ const target = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
+ return target ? normalizeRestorablePwaPath(target.getItem(STORAGE_KEY)) : null;
+ } catch {
+ return null;
+ }
+}
+
+export function writeLastPwaPath(pathname: string, storage?: WritableStorage): void {
+ const normalized = normalizeRestorablePwaPath(pathname);
+ if (!normalized) return;
+
+ try {
+ const target = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
+ target?.setItem(STORAGE_KEY, normalized);
+ } catch {
+ // Route persistence is best-effort in private browsing and restricted storage contexts.
+ }
+}
+
+interface PwaLaunchLocation {
+ pathname: string;
+ search: string;
+ hash: string;
+}
+
+export function resolvePwaLaunchPath(
+ standalone: boolean,
+ location: PwaLaunchLocation,
+ rememberedPath: unknown,
+): string | null {
+ if (!standalone || location.pathname !== '/' || location.search || location.hash) return null;
+
+ const normalized = normalizeRestorablePwaPath(rememberedPath);
+ return normalized && normalized !== '/' ? normalized : null;
+}
+
+export function shouldRestorePwaLaunch(
+ restorePath: string | null,
+ launchLocationKey: string,
+ location: { pathname: string; key: string },
+): boolean {
+ return Boolean(restorePath) && location.key === launchLocationKey && location.pathname === '/';
+}
diff --git a/ui/src/lib/webPushLaunch.test.ts b/ui/src/lib/webPushLaunch.test.ts
new file mode 100644
index 000000000..2a44a9f05
--- /dev/null
+++ b/ui/src/lib/webPushLaunch.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createPendingWebPushLaunchReader,
+ parsePendingWebPushLaunch,
+ WEB_PUSH_LAUNCH_MAX_AGE_MS,
+} from './webPushLaunch';
+
+describe('pending web-push launches', () => {
+ 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(
+ '/chat/session-1',
+ );
+ expect(
+ parsePendingWebPushLaunch(
+ { url: '/chat/session-1', createdAt: now - WEB_PUSH_LAUNCH_MAX_AGE_MS - 1 },
+ now,
+ ),
+ ).toBeNull();
+ expect(parsePendingWebPushLaunch({ url: '//example.com/inbox', createdAt: now }, now)).toBeNull();
+ });
+
+ 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 cache = {
+ match: vi.fn(async () => new Response(JSON.stringify({ url: '/chat/session-2', createdAt: now }))),
+ delete: vi.fn(async () => true),
+ };
+ const open = vi.fn(async () => cache);
+ const read = createPendingWebPushLaunchReader(() => ({
+ cacheStorage: { open },
+ origin: 'https://avibe.local',
+ now: () => now,
+ }));
+
+ await expect(Promise.all([read(), read()])).resolves.toEqual(['/chat/session-2', '/chat/session-2']);
+ expect(open).toHaveBeenCalledOnce();
+ expect(cache.match).toHaveBeenCalledWith(entryUrl);
+ expect(cache.delete).toHaveBeenCalledWith(entryUrl);
+ });
+
+ it('falls back safely when Cache Storage is unavailable', async () => {
+ const read = createPendingWebPushLaunchReader(() => null);
+ await expect(read()).resolves.toBeNull();
+ });
+});
diff --git a/ui/src/lib/webPushLaunch.ts b/ui/src/lib/webPushLaunch.ts
new file mode 100644
index 000000000..e734fbfa7
--- /dev/null
+++ b/ui/src/lib/webPushLaunch.ts
@@ -0,0 +1,75 @@
+import { normalizeRestorablePwaPath } from './pwaRouteMemory';
+
+const CACHE_NAME = 'avibe.web-push-launch.v1';
+const CACHE_ENTRY_PATH = '/__avibe/web-push-launch';
+export const WEB_PUSH_LAUNCH_MAX_AGE_MS = 5 * 60 * 1000;
+
+interface PendingWebPushLaunch {
+ url: unknown;
+ createdAt: unknown;
+}
+
+interface LaunchCache {
+ match(request: string): Promise<Response | undefined>;
+ delete(request: string): Promise<boolean>;
+}
+
+interface LaunchCacheStorage {
+ open(cacheName: string): Promise<LaunchCache>;
+}
+
+interface LaunchReaderEnvironment {
+ cacheStorage: LaunchCacheStorage;
+ origin: string;
+ now: () => number;
+}
+
+export function parsePendingWebPushLaunch(value: unknown, now: number): string | null {
+ if (!value || typeof value !== 'object') return null;
+ const { url, createdAt } = value as PendingWebPushLaunch;
+ if (typeof createdAt !== 'number' || !Number.isFinite(createdAt)) return null;
+
+ const age = now - createdAt;
+ if (age < 0 || age > WEB_PUSH_LAUNCH_MAX_AGE_MS) return null;
+ return normalizeRestorablePwaPath(url);
+}
+
+function browserEnvironment(): LaunchReaderEnvironment | null {
+ if (typeof window === 'undefined' || !('caches' in window)) return null;
+ return {
+ cacheStorage: window.caches,
+ origin: window.location.origin,
+ now: Date.now,
+ };
+}
+
+// The memoized promise matters in React StrictMode: both mount effects must see
+// the same consumed launch record instead of the first effect deleting it before
+// the second effect can use it.
+export function createPendingWebPushLaunchReader(
+ getEnvironment: () => LaunchReaderEnvironment | null = browserEnvironment,
+): () => Promise<string | null> {
+ let readPromise: Promise<string | null> | null = null;
+
+ 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;
+ }
+ })();
+ return readPromise;
+ };
+}
+
+export const takePendingWebPushLaunchPath = createPendingWebPushLaunchReader();