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(pwa): keep same-origin links in the installed app (#1240)
Call White25783613fa7a
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 7d044936a..efff86e4d 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -1054,6 +1054,9 @@ def test_private_show_page_injects_runtime_event_config(monkeypatch, tmp_path):assert '"streamPath":"/show/ses123/__show/events?stream=1"' in bodyassert '"writeToken":"token-ses123"' in bodyassert '"annotation":{"authenticated":true,"mePath":"__show/me"}' in body+ assert "__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__" in body+ assert "anchor.hasAttribute('download')" in body+ assert "target.origin!==window.location.origin" in bodyassert '<script type="module" src="/show/ses123/__show/annotation.js"></script>' in bodyassert body.index("globalThis.__AVIBE_SHOW__") < body.index('/src/main.tsx')assert body.index('/src/main.tsx') < body.index('/show/ses123/__show/annotation.js')@@ -1099,6 +1102,7 @@ def test_public_show_page_injects_auth_aware_annotation_config(monkeypatch, tmp_assert f'"streamPath":"{base_path}__show/events?stream=1"' in bodyexpected_auth = "true" if authenticated else "false"assert f'"annotation":{{"authenticated":{expected_auth},"mePath":"__show/me"}}' in body+ assert "__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__" in bodyassert f'<script type="module" src="{base_path}__show/annotation.js"></script>' in bodyassert '"writeToken"' not in bodyassert body.index('/src/main.tsx') < body.index(f'{base_path}__show/annotation.js')diff --git a/ui/src/apps/LibraryApp.tsx b/ui/src/apps/LibraryApp.tsxindex 6bf3efeff..302e6b738 100644--- a/ui/src/apps/LibraryApp.tsx+++ b/ui/src/apps/LibraryApp.tsx@@ -25,6 +25,7 @@ import { useShowPages, type ShowPage } from '../components/useShowPages';import { Badge } from '../components/ui/badge';import { Button } from '../components/ui/button';import { SearchField } from '../components/settings/SettingsPrimitives';+import { openLinkInNewContext } from '../lib/pwaNavigation';// The App Library: the app manager, itself a built-in app (§7.1). Two views over// the two-layer state (§7.1c): the INSTALLED set (Apps) and the full Show Pages@@ -62,7 +63,7 @@ function useOpenApp() {if (launch && appLaunchIntent(launch) === 'newTab') {const href = appTabHref({ appId, sessionId: opts?.sessionId });if (href) {- window.open(href, '_blank', 'noopener,noreferrer');+ openLinkInNewContext(href, 'noopener,noreferrer');return;}}diff --git a/ui/src/apps/appLaunch.test.ts b/ui/src/apps/appLaunch.test.tsindex a4f3f18e7..f08113b31 100644--- a/ui/src/apps/appLaunch.test.ts+++ b/ui/src/apps/appLaunch.test.ts@@ -118,6 +118,15 @@ describe('appTabHref', () => {expect(appTabHref({ appId: 'showpage', sessionId: ' ' })).toBeNull();expect(appTabHref({ appId: '' })).toBeNull();});++ it('keeps every internal app in the installed iOS PWA', () => {+ const iosPwa = { iosStandalone: true };++ expect(appTabHref({ appId: 'showpage', sessionId: 'abc123' }, iosPwa)).toBeNull();+ expect(appTabHref({ appId: 'files' }, iosPwa)).toBeNull();+ expect(appTabHref({ appId: 'terminal' }, iosPwa)).toBeNull();+ expect(appTabHref({ appId: 'editor' }, iosPwa)).toBeNull();+ });});describe('isStandaloneAppTab', () => {@@ -143,4 +152,11 @@ describe('appTabHrefForDockId', () => {expect(appTabHrefForDockId(showDockId('sess42'))).toBe('/show/sess42/');expect(appTabHrefForDockId('library')).toBeNull();});++ it('withdraws new-tab targets for every Dock app in the installed iOS PWA', () => {+ const iosPwa = { iosStandalone: true };++ expect(appTabHrefForDockId('terminal', iosPwa)).toBeNull();+ expect(appTabHrefForDockId(showDockId('sess42'), iosPwa)).toBeNull();+ });});diff --git a/ui/src/apps/appLaunch.ts b/ui/src/apps/appLaunch.tsindex fc1e203a5..c27d448ad 100644--- a/ui/src/apps/appLaunch.ts+++ b/ui/src/apps/appLaunch.ts@@ -4,7 +4,7 @@// results — shares ONE rule and one testable mapping instead of re-deriving it.import { dockIdToSession } from '../context/dockDoc';-import { IS_APPLE } from '../lib/platform';+import { IS_APPLE, isIosDevice, isStandalonePwa } from '../lib/platform';import { showPagePrivatePath } from './showPageAvatar';/**@@ -78,6 +78,14 @@ export interface AppTabTarget {sessionId?: string | null;}+export interface AppTabContext {+ iosStandalone: boolean;+}++function currentAppTabContext(): AppTabContext {+ return { iosStandalone: isIosDevice() && isStandalonePwa() };+}+/*** Built-ins whose `/apps/<id>` route really renders the app STANDALONE on desktop* (App.tsx: `AppsFileBrowserPage` / `AppsTerminalPage` / `AppsEditorPage`).@@ -105,8 +113,14 @@ const STANDALONE_BUILTIN_ROUTES = new Set(['files', 'terminal', 'editor']);export const APP_TAB_PARAM = 'standalone';/**- * The URL that shows an app on its OWN browser tab, or null when it has no- * standalone surface (so the caller can fall back to a window).+ * The URL that shows an app on its OWN browser tab, or null when it has no safe+ * standalone surface (so the caller can fall back to an in-app route/window).+ *+ * Installed iOS PWAs deliberately return null for every internal app. WebKit+ * opens `_blank` from a Home-Screen app in a secondary browser context and can+ * restore that context after process eviction, including its transient blank+ * document. Internal Avibe apps already have first-class in-shell routes and+ * windows, so there is no reason to expose that restoration failure mode.** - a Show Page → its private `/show/<sid>/` page, the SAME target as the tile's* "Open in New Tab" menu item and the window titlebar's external-open button@@ -115,9 +129,14 @@ export const APP_TAB_PARAM = 'standalone';* desktop (see `STANDALONE_BUILTIN_ROUTES`) — flagged with `APP_TAB_PARAM` so the* shell suppresses the restored window layer over it.*- * Pure.+ * Supplying `context` makes the policy deterministic in tests; production+ * callers default to the current display context.*/-export function appTabHref(target: AppTabTarget): string | null {+export function appTabHref(+ target: AppTabTarget,+ context: AppTabContext = currentAppTabContext(),+): string | null {+ if (context.iosStandalone) return null;if (target.appId === 'showpage') {const sessionId = (target.sessionId ?? '').trim();return sessionId ? showPagePrivatePath(sessionId) : null;@@ -143,8 +162,13 @@ export function isStandaloneAppTab(search: string): boolean {}}-/** `appTabHref` for a persisted Dock id (`files` / `show:<session_id>`). Pure. */-export function appTabHrefForDockId(dockId: string): string | null {+/** `appTabHref` for a persisted Dock id (`files` / `show:<session_id>`). */+export function appTabHrefForDockId(+ dockId: string,+ context?: AppTabContext,+): string | null {const sessionId = dockIdToSession(dockId);- return sessionId !== null ? appTabHref({ appId: 'showpage', sessionId }) : appTabHref({ appId: dockId });+ return sessionId !== null+ ? appTabHref({ appId: 'showpage', sessionId }, context)+ : appTabHref({ appId: dockId }, context);}diff --git a/ui/src/components/PwaLoopbackLinkGuard.tsx b/ui/src/components/PwaLoopbackLinkGuard.tsxindex 201b1ae2b..79831e1f7 100644--- a/ui/src/components/PwaLoopbackLinkGuard.tsx+++ b/ui/src/components/PwaLoopbackLinkGuard.tsx@@ -1,35 +1,64 @@import { useEffect } from 'react';import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';import { useToast } from '@/context/ToastContext';import { isIosDevice, isStandalonePwa } from '@/lib/platform';-import { shouldBlockPwaLoopbackLink } from '@/lib/pwaNavigation';+import { internalPwaLinkTarget, shouldBlockPwaLoopbackLink } from '@/lib/pwaNavigation';-// iOS opens out-of-scope links from a Home-Screen app in a dismissible browser-// sheet, and may restore that sheet after evicting the PWA process. A loopback-// URL in a chat reply can therefore strand the user on a dead "localhost" page:-// localhost is the iPhone, not the machine running Avibe. Catch every ordinary-// anchor at the app boundary so individual renderers cannot drift.+// iOS opens `_blank` links from a Home-Screen app in a secondary browser context+// and may restore that context after evicting the PWA process. Keep every+// same-origin navigation in this context, and keep blocking loopback URLs that+// point at the phone rather than the machine running Avibe. The global bridge is+// used by same-origin Show Page frames, whose clicks cannot bubble to this document.export const PwaLoopbackLinkGuard = () => {const { t } = useTranslation();const { showToast } = useToast();+ const navigate = useNavigate();useEffect(() => {if (!(isIosDevice() && isStandalonePwa())) return;+ const openSameOrigin = (href: string) => {+ const target = internalPwaLinkTarget(href, window.location.href);+ if (!target) return false;+ if (target.navigation === 'spa') navigate(target.path);+ else window.location.assign(target.path);+ return true;+ };+const onClick = (event: MouseEvent) => {if (!(event.target instanceof Element)) return;const anchor = event.target.closest<HTMLAnchorElement>('a[href]');- if (!anchor || !shouldBlockPwaLoopbackLink(anchor.href, window.location.href)) return;+ if (!anchor) return;++ const internalTarget =+ anchor.target.toLowerCase() === '_blank' && !anchor.hasAttribute('download')+ ? internalPwaLinkTarget(anchor.href, window.location.href)+ : null;+ if (internalTarget) {+ event.preventDefault();+ event.stopPropagation();+ openSameOrigin(anchor.href);+ return;+ }++ if (!shouldBlockPwaLoopbackLink(anchor.href, window.location.href)) return;event.preventDefault();event.stopPropagation();showToast(t('common.localLinkUnavailable'), 'warning');};+ window.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__ = openSameOrigin;document.addEventListener('click', onClick, true);- return () => document.removeEventListener('click', onClick, true);- }, [showToast, t]);+ return () => {+ document.removeEventListener('click', onClick, true);+ if (window.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__ === openSameOrigin) {+ delete window.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__;+ }+ };+ }, [navigate, showToast, t]);return null;};diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsxindex 88752d4dc..da8fd6d29 100644--- a/ui/src/components/ShowPagesPage.tsx+++ b/ui/src/components/ShowPagesPage.tsx@@ -23,6 +23,7 @@ import clsx from 'clsx';import { useDock } from '../context/DockContext';import { useWindowManager } from '../context/WindowManagerContext';import { copyTextToClipboard } from '../lib/utils';+import { internalPwaLinkTarget, openLinkInNewContext } from '../lib/pwaNavigation';import { copyHref, displayLink, type ShowPageLinkInfo } from '../lib/showPageLinks';import { type ShowPage, type ShowPagesController, type Visibility } from './useShowPages';import { appTabHref, isAppleContextClick, tabModifierLabel, type LaunchModifiers } from '../apps/appLaunch';@@ -109,6 +110,7 @@ function ShowPageRow({const href = copyHref(page);const shown = displayLink(page);+ const tabHref = appTabHref({ appId: 'showpage', sessionId: page.session_id });return (<div className={clsx('border-b border-border last:border-b-0', expanded && 'border-y border-mint/30')}>@@ -134,7 +136,7 @@ function ShowPageRow({// when this page really resolves to a tab surface (§7.1m).title={[t('showPages.openApp'),- appTabHref({ appId: 'showpage', sessionId: page.session_id })+ tabHref? t('apps.dock.newTabChord', { key: tabModifierLabel() }): null,]@@ -249,7 +251,17 @@ function ShowPageRow({variant="secondary"size="sm"disabled={!href}- onClick={() => href && window.open(href, '_blank', 'noopener')}+ onClick={() => {+ if (!href) return;+ const internalTarget = internalPwaLinkTarget(href, window.location.href);+ if (tabHref || !internalTarget) {+ openLinkInNewContext(href, 'noopener');+ } else if (internalTarget.navigation === 'spa') {+ onOpen();+ } else {+ window.location.assign(internalTarget.path);+ }+ }}><ExternalLink size={14} />{t('showPages.open')}diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsxindex a39957ccd..f6ac554ff 100644--- a/ui/src/components/apps/AppWindow.tsx+++ b/ui/src/components/apps/AppWindow.tsx@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';import clsx from 'clsx';import { ExternalLink, MessageCircle, Minus, Plus, X, type LucideIcon } from 'lucide-react';+import { appTabHref } from '../../apps/appLaunch';import { APP_REGISTRY } from '../../apps/registry';import { showPageAvatar, showPageIconUrl } from '../../apps/showPageAvatar';import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';@@ -167,6 +168,9 @@ export const AppWindow: React.FC<{// A standalone-surface app (v1: showpage) exposes an external URL for its own// browser tab; the title bar then shows an open-in-new-tab button.const externalHref = def.externalHref?.(win.params);+ const safeExternalHref = externalHref+ ? appTabHref({ appId: win.appId, sessionId: showpageSid })+ : null;// The same app may own a session chat (v1: showpage) — the title bar then also// shows a chat-bubble button that jumps there and minimizes this window.const chatHref = def.chatHref?.(win.params);@@ -350,9 +354,9 @@ export const AppWindow: React.FC<{<MessageCircle className="size-3.5" /></button>)}- {externalHref && (+ {safeExternalHref && (<a- href={externalHref}+ href={safeExternalHref}target="_blank"rel="noopener noreferrer"title={t('apps.window.openInNewTab')}diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsxindex 114072fec..500bb4549 100644--- a/ui/src/components/apps/Dock.tsx+++ b/ui/src/components/apps/Dock.tsx@@ -11,6 +11,7 @@ import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';import { useDock } from '../../context/DockContext';import { dockIdToSession } from '../../context/dockDoc';import { useWindowManager } from '../../context/WindowManagerContext';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { ContextMenu, ContextMenuItem } from '../ui/context-menu';import { useShowPageInventory } from '../useShowPages';import { isDragRelease } from './dragClick';@@ -151,7 +152,7 @@ export const Dock: React.FC = () => {const href = tabHrefFor(item);setMenu(null);if (!href) return false;- window.open(href, '_blank', 'noopener,noreferrer');+ openLinkInNewContext(href, 'noopener,noreferrer');return true;};diff --git a/ui/src/components/apps/ShowPageRoute.tsx b/ui/src/components/apps/ShowPageRoute.tsxindex 8fcce5843..b607851ad 100644--- a/ui/src/components/apps/ShowPageRoute.tsx+++ b/ui/src/components/apps/ShowPageRoute.tsx@@ -6,6 +6,7 @@ import { ArrowLeft, ExternalLink, MonitorX, PinOff } from 'lucide-react';import { useApi } from '../../context/ApiContext';import { useDock } from '../../context/DockContext';import { useWindowManager } from '../../context/WindowManagerContext';+import { appTabHref } from '../../apps/appLaunch';import { showPageAvatar, showPagePrivatePath } from '../../apps/showPageAvatar';import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';@@ -108,6 +109,7 @@ const MobileShowPage: React.FC<{ sessionId: string }> = ({ sessionId }) => {const avatar = sessionId ? showPageAvatar(sessionId, title) : null;const label = title || t('apps.showPage.label');const missing = !sessionId || state === 'missing';+ const externalHref = appTabHref({ appId: 'showpage', sessionId });return (<div className="flex h-[calc(100dvh-9.5rem)] min-h-[420px] flex-col overflow-hidden rounded-xl border border-border bg-surface">@@ -138,9 +140,9 @@ const MobileShowPage: React.FC<{ sessionId: string }> = ({ sessionId }) => {</span>)}<span className="min-w-0 flex-1 truncate text-[14px] font-semibold text-foreground">{label}</span>- {state === 'ready' && (+ {state === 'ready' && externalHref && (<a- href={showPagePrivatePath(sessionId)}+ href={externalHref}target="_blank"rel="noopener noreferrer"aria-label={t('apps.window.openInNewTab')}diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsxindex d73893802..f23d8b7e9 100644--- a/ui/src/components/steps/DiscordConfig.tsx+++ b/ui/src/components/steps/DiscordConfig.tsx@@ -19,6 +19,7 @@ import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { hasUsableSecret, secretInputValue, withSecretDraft } from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';@@ -129,7 +130,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa};const openDiscordDeveloperPortal = () => {- window.open('https://discord.com/developers/applications', '_blank');+ openLinkInNewContext('https://discord.com/developers/applications');};const copyInviteUrl = async () => {@@ -277,7 +278,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa<Buttonvariant="brand"size="sm"- onClick={() => inviteUrl && window.open(inviteUrl, '_blank')}+ onClick={() => inviteUrl && openLinkInNewContext(inviteUrl)}disabled={!inviteUrl}><ExternalLink size={14} strokeWidth={2.25} />diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsxindex 3e62394cf..895e5faf1 100644--- a/ui/src/components/steps/LarkConfig.tsx+++ b/ui/src/components/steps/LarkConfig.tsx@@ -27,6 +27,7 @@ import {withSecretDraft,} from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';@@ -35,7 +36,7 @@ import { Input } from '../ui/input';import { errorMessage } from '@/lib/errorMessage';const LinkButton: React.FC<{ url: string; label: string }> = ({ url, label }) => (- <Button variant="brand" size="sm" onClick={() => window.open(url, '_blank')} disabled={!url}>+ <Button variant="brand" size="sm" onClick={() => openLinkInNewContext(url)} disabled={!url}><ExternalLink size={14} strokeWidth={2.25} />{label}</Button>diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsxindex 07e4d21e8..6e0345434 100644--- a/ui/src/components/steps/PlatformSelection.tsx+++ b/ui/src/components/steps/PlatformSelection.tsx@@ -11,6 +11,7 @@ import {WORKBENCH_PLATFORM_ID,} from '../../lib/platforms';import { hasUsableSecret, secretInputValue } from '../../lib/secretFields';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { Button } from '../ui/button';import { Input } from '../ui/input';@@ -447,7 +448,7 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe{getExternalUrl(activeCredentialPlatform) ? (<buttontype="button"- onClick={() => window.open(getExternalUrl(activeCredentialPlatform), '_blank')}+ onClick={() => openLinkInNewContext(getExternalUrl(activeCredentialPlatform))}className="inline-flex h-7 items-center justify-center gap-1.5 rounded-md border border-border bg-surface-3 px-2.5 text-[10px] font-medium text-foreground hover:border-border-strong"><ExternalLink className="size-3" />diff --git a/ui/src/components/steps/SlackConfig.tsx b/ui/src/components/steps/SlackConfig.tsxindex 4645b399c..a76fcab3b 100644--- a/ui/src/components/steps/SlackConfig.tsx+++ b/ui/src/components/steps/SlackConfig.tsx@@ -6,6 +6,7 @@ import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { hasUsableSecret, secretInputValue, withSecretDrafts } from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';@@ -99,9 +100,9 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,const openSlackCreateApp = () => {if (manifestCompact) {const url = `https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(manifestCompact)}`;- window.open(url, '_blank');+ openLinkInNewContext(url);} else {- window.open('https://api.slack.com/apps?new_app=1', '_blank');+ openLinkInNewContext('https://api.slack.com/apps?new_app=1');}};diff --git a/ui/src/components/steps/TelegramConfig.tsx b/ui/src/components/steps/TelegramConfig.tsxindex 192d19954..879828c0d 100644--- a/ui/src/components/steps/TelegramConfig.tsx+++ b/ui/src/components/steps/TelegramConfig.tsx@@ -18,6 +18,7 @@ import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { hasUsableSecret, secretInputValue, withSecretDraft } from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';import { StepHeader, StepShell } from '../shared/WizardStep';@@ -87,7 +88,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, on};const openBotFather = () => {- window.open('https://t.me/BotFather', '_blank');+ openLinkInNewContext('https://t.me/BotFather');};const copyCommand = async (command: string) => {diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsxindex 935e49c5b..9e4ef8e50 100644--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx@@ -8,7 +8,7 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';-import { showPagePrivatePath } from '../../apps/showPageAvatar';+import { appTabHref } from '../../apps/appLaunch';import { useDock } from '../../context/DockContext';import { showDockId } from '../../context/dockDoc';import { useShowPageDrag } from '../../context/showPageDrag';@@ -60,6 +60,7 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({const canLaunch = !showPageMode && !busy && Boolean(sessionId);const windowTitle = title?.trim() || t('chat.untitled');+ const linkHref = appTabHref({ appId: 'showpage', sessionId });const clearHoverTimer = useCallback(() => {if (hoverTimerRef.current === null) return;@@ -114,6 +115,7 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({const openLink = useCallback(async () => {clearHoverTimer();setMenuOpen(false);+ if (!linkHref) return;// Open synchronously inside the click gesture, then navigate after ensure;// otherwise popup blockers reject window.open after the awaited request.const tab = window.open('about:blank', '_blank');@@ -127,8 +129,8 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({tab.close();return;}- if (!tab.closed) tab.location.replace(showPagePrivatePath(sessionId));- }, [clearHoverTimer, prepare, sessionId]);+ if (!tab.closed) tab.location.replace(linkHref);+ }, [clearHoverTimer, linkHref, prepare]);const pinToDock = useCallback(async () => {if (!(await prepare())) return;@@ -298,15 +300,17 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({<AppWindow className="size-3.5 shrink-0 text-cyan" /><span>{t('chat.showPage.newWindow')}</span></button>- <button- type="button"- role="menuitem"- onClick={() => void openLink()}- className="flex w-full items-center gap-2 whitespace-nowrap rounded-md px-2 py-1.5 text-left text-[12.5px] text-foreground transition-colors hover:bg-cyan-soft"- >- <ExternalLink className="size-3.5 shrink-0 text-mint" />- <span>{t('chat.showPage.newLink')}</span>- </button>+ {linkHref && (+ <button+ type="button"+ role="menuitem"+ onClick={() => void openLink()}+ className="flex w-full items-center gap-2 whitespace-nowrap rounded-md px-2 py-1.5 text-left text-[12.5px] text-foreground transition-colors hover:bg-cyan-soft"+ >+ <ExternalLink className="size-3.5 shrink-0 text-mint" />+ <span>{t('chat.showPage.newLink')}</span>+ </button>+ )}</div></PopoverContent></Popover>diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsxindex fe3b3c2a6..b85ebb4a0 100644--- a/ui/src/components/workbench/TerminalView.tsx+++ b/ui/src/components/workbench/TerminalView.tsx@@ -16,6 +16,7 @@ import {subscribeTerminalFontSize,} from '../../lib/terminalFontSize';import { IS_APPLE } from '../../lib/platform';+import { openLinkInNewContext } from '../../lib/pwaNavigation';import { useLatestRef } from '@/lib/useLatestRef';// xterm.js wired to the /api/terminal/{id} WebSocket. Protocol (locked with the@@ -180,11 +181,12 @@ export const TerminalView: React.FC<{// Persistent sessions run tmux with `mouse on`, so an unmodified click is meaningful input for// tmux/copy-mode and mouse-aware TUIs — gating on the modifier keeps plain clicks as terminal input// and matches how VS Code / iTerm / GNOME Terminal follow terminal links. noopener defeats reverse-- // tabnabbing (the addon's own typings call this out); window.open never navigates the app frame.+ // tabnabbing (the addon's own typings call this out). The shared opener keeps+ // same-origin URLs in an installed iOS PWA instead of creating a restorable sheet.term.loadAddon(new WebLinksAddon((event, uri) => {if (IS_APPLE ? event.metaKey : event.ctrlKey) {- window.open(uri, '_blank', 'noopener');+ openLinkInNewContext(uri, 'noopener');}}),);diff --git a/ui/src/components/workbench/search/useAppSearch.ts b/ui/src/components/workbench/search/useAppSearch.tsindex c4dd1e5c1..53f9432b1 100644--- a/ui/src/components/workbench/search/useAppSearch.ts+++ b/ui/src/components/workbench/search/useAppSearch.ts@@ -7,6 +7,7 @@ import { APP_LIST } from '../../../apps/registry';import { showAppRoutePath } from '../../apps/mobileDock';import { useShowPageInventory } from '../../useShowPages';import { useWindowManager } from '../../../context/WindowManagerContext';+import { openLinkInNewContext } from '../../../lib/pwaNavigation';import { filterAppSearchResults, type AppSearchResult } from './appSearch';export function useAppSearchResults(query: string, enabled = true) {@@ -56,7 +57,7 @@ export function useOpenSearchApp() {if (launch && appLaunchIntent(launch) === 'newTab') {const href = appTabHref({ appId: result.appId, sessionId: result.kind === 'showpage' ? result.sessionId : null });if (href) {- window.open(href, '_blank', 'noopener,noreferrer');+ openLinkInNewContext(href, 'noopener,noreferrer');return;}}diff --git a/ui/src/lib/applicationRoutes.test.ts b/ui/src/lib/applicationRoutes.test.tsnew file mode 100644index 000000000..e775347b5--- /dev/null+++ b/ui/src/lib/applicationRoutes.test.ts@@ -0,0 +1,29 @@+import { readFileSync } from 'node:fs';++import { describe, expect, it } from 'vitest';++import {+ APPLICATION_DYNAMIC_ROUTE_PATHS,+ APPLICATION_ROUTE_PATHS,+ isApplicationRouteHref,+} from './applicationRoutes';++describe('AppShell route policy', () => {+ it('matches every path declared by App.tsx', () => {+ const appSource = readFileSync(new URL('../App.tsx', import.meta.url), 'utf8');+ const declared = Array.from(appSource.matchAll(/<Route\s+path="([^"]+)"/g), (match) => match[1]);+ const catalog = [...APPLICATION_ROUTE_PATHS, ...APPLICATION_DYNAMIC_ROUTE_PATHS];++ expect([...declared].sort()).toEqual([...catalog].sort());+ });++ it('recognizes exact and dynamic routes without reserving their namespaces', () => {+ for (const path of APPLICATION_ROUTE_PATHS) {+ expect(isApplicationRouteHref(path), path).toBe(true);+ }+ expect(isApplicationRouteHref('/chat/session-123')).toBe(true);+ expect(isApplicationRouteHref('/apps/show/session-123')).toBe(true);+ expect(isApplicationRouteHref('/projects/report.md')).toBe(false);+ expect(isApplicationRouteHref('/admin/settings/custom.json')).toBe(false);+ });+});diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.tsnew file mode 100644index 000000000..2f80a53e0--- /dev/null+++ b/ui/src/lib/applicationRoutes.ts@@ -0,0 +1,81 @@+// Exact routes declared in App.tsx. Keep this as the shared policy for any+// feature that must distinguish an AppShell destination from another+// same-origin path, such as local-file Markdown links and iOS PWA navigation.+// Exact matching is deliberate: `/projects/report.md` may be a real local file.+export const APPLICATION_ROUTE_PATHS = [+ '/',+ '/setup',+ '/inbox',+ '/search',+ '/agents',+ '/skills',+ '/harness',+ '/vaults',+ '/projects',+ '/more',+ '/apps',+ '/apps/files',+ '/apps/terminal',+ '/apps/editor',+ '/apps/library',+ '/admin',+ '/admin/dashboard',+ '/admin/remote-access',+ '/admin/groups',+ '/admin/users',+ '/admin/show-pages',+ '/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/models',+ '/admin/settings/dependencies',+ '/admin/settings/memory',+ '/admin/settings/messaging',+ '/admin/settings/diagnostics',+ '/admin/settings/logs',+ '/dashboard',+ '/groups',+ '/channels',+ '/users',+ '/logs',+ '/settings',+ '/settings/service',+ '/settings/platforms',+ '/settings/backends',+ '/settings/backends/opencode',+ '/settings/backends/claude',+ '/settings/backends/codex',+ '/settings/models',+ '/settings/dependencies',+ '/settings/memory',+ '/settings/messaging',+ '/settings/diagnostics',+ '/settings/logs',+ '/remote-access',+ '/doctor',+ '/doctor/logs',+] as const;++export const APPLICATION_DYNAMIC_ROUTE_PATHS = [+ '/apps/show/:sessionId',+ '/chat/:sessionId',+] as const;++const APPLICATION_ROUTES = new Set<string>(APPLICATION_ROUTE_PATHS);+const APPLICATION_ROUTE_PATTERNS = APPLICATION_DYNAMIC_ROUTE_PATHS.map((path) => {+ const pattern = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/:[^/]+/g, '[^/]+');+ return new RegExp(`^${pattern}$`);+});++export function isApplicationRouteHref(href: string): boolean {+ const rawPathname = href.split(/[?#]/, 1)[0];+ const pathname = rawPathname.replace(/\/+$/, '') || '/';+ return (+ APPLICATION_ROUTES.has(pathname) ||+ APPLICATION_ROUTE_PATTERNS.some((pattern) => pattern.test(pathname))+ );+}diff --git a/ui/src/lib/localFileLinks.test.ts b/ui/src/lib/localFileLinks.test.tsindex 3b695be10..eb08f7afd 100644--- a/ui/src/lib/localFileLinks.test.ts+++ b/ui/src/lib/localFileLinks.test.ts@@ -95,7 +95,10 @@ describe('resolveLocalFileLink', () => {'/apps/files','/apps/files/','/admin/settings/backends/codex',+ '/admin/settings/models',+ '/admin/settings/memory','/settings/models?source=custom',+ '/settings/memory','/doctor/logs#latest',]) {expect(resolveLocalFileLink(href, '/workspace')).toBeNull();diff --git a/ui/src/lib/localFileLinks.ts b/ui/src/lib/localFileLinks.tsindex a97566e98..d52803a45 100644--- a/ui/src/lib/localFileLinks.ts+++ b/ui/src/lib/localFileLinks.ts@@ -1,3 +1,5 @@+import { isApplicationRouteHref } from './applicationRoutes';+export type LocalFileLinkTarget = {path: string;line?: number;@@ -5,77 +7,6 @@ export type LocalFileLinkTarget = {endColumn?: number;};-// Exact routes declared in App.tsx remain same-origin browser links even-// though their leading slash also looks like a POSIX path. Do not reserve an-// entire top-level namespace: `/projects/report.md` may be a real local file.-const APPLICATION_ROUTES = new Set([- '/',- '/setup',- '/inbox',- '/search',- '/agents',- '/skills',- '/harness',- '/vaults',- '/projects',- '/more',- '/apps',- '/apps/files',- '/apps/terminal',- '/apps/editor',- '/apps/library',- '/admin',- '/admin/dashboard',- '/admin/remote-access',- '/admin/groups',- '/admin/users',- '/admin/show-pages',- '/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/models',- '/admin/settings/dependencies',- '/admin/settings/messaging',- '/admin/settings/diagnostics',- '/admin/settings/logs',- '/dashboard',- '/groups',- '/channels',- '/users',- '/logs',- '/settings',- '/settings/service',- '/settings/platforms',- '/settings/backends',- '/settings/backends/opencode',- '/settings/backends/claude',- '/settings/backends/codex',- '/settings/models',- '/settings/dependencies',- '/settings/messaging',- '/settings/diagnostics',- '/settings/logs',- '/remote-access',- '/doctor',- '/doctor/logs',-]);--const APPLICATION_ROUTE_PATTERNS = [- /^\/apps\/show\/[^/]+$/,- /^\/chat\/[^/]+$/,-];--function isApplicationRouteHref(href: string): boolean {- const rawPathname = href.split(/[?#]/, 1)[0];- const pathname = rawPathname.replace(/\/+$/, '') || '/';- return APPLICATION_ROUTES.has(pathname)- || APPLICATION_ROUTE_PATTERNS.some((pattern) => pattern.test(pathname));-}-/** Windows drive and UNC paths are valid local destinations, not URL schemes.* Accept encoded separators because Markdown destinations commonly escape* backslashes before the URL sanitizer sees them. */diff --git a/ui/src/lib/pwaNavigation.test.ts b/ui/src/lib/pwaNavigation.test.tsindex 755c66ffe..81b18aa06 100644--- a/ui/src/lib/pwaNavigation.test.ts+++ b/ui/src/lib/pwaNavigation.test.ts@@ -1,6 +1,52 @@-import { describe, expect, it } from 'vitest';+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';-import { shouldBlockPwaLoopbackLink } from './pwaNavigation';+import * as ts from 'typescript';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ internalPwaLinkTarget,+ openLinkInNewContext,+ shouldBlockPwaLoopbackLink,+} from './pwaNavigation';++function sourceFiles(directory: URL): URL[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const child = new URL(`${entry.name}${entry.isDirectory() ? '/' : ''}`, directory);+ if (entry.isDirectory()) return sourceFiles(child);+ return /\.(ts|tsx)$/.test(entry.name) && !/\.test\.(ts|tsx)$/.test(entry.name) ? [child] : [];+ });+}++function directWindowOpenCount(url: URL): number {+ const path = fileURLToPath(url);+ const source = ts.createSourceFile(+ path,+ readFileSync(url, 'utf8'),+ ts.ScriptTarget.Latest,+ true,+ path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );+ let count = 0;+ const visit = (node: ts.Node) => {+ if (+ ts.isCallExpression(node) &&+ ts.isPropertyAccessExpression(node.expression) &&+ ts.isIdentifier(node.expression.expression) &&+ node.expression.expression.text === 'window' &&+ node.expression.name.text === 'open'+ ) {+ count += 1;+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return count;+}++afterEach(() => {+ vi.unstubAllGlobals();+});describe('PWA navigation', () => {const remotePage = 'https://alex-app.avibe.bot/chat/session-123';@@ -34,3 +80,116 @@ describe('PWA navigation', () => {).toBe(false);});});++describe('internalPwaLinkTarget', () => {+ const current = 'https://alex-app.avibe.bot/chat/session-123';++ it('keeps private Show Pages inside the AppShell route', () => {+ expect(internalPwaLinkTarget('/show/ses_123/', current)).toEqual({+ path: '/apps/show/ses_123',+ navigation: 'spa',+ });+ expect(internalPwaLinkTarget('https://alex-app.avibe.bot/show/a%20b%2Fc/', current)).toEqual({+ path: '/apps/show/a%20b%2Fc',+ navigation: 'spa',+ });+ });++ it('preserves private Show Page query, fragment, and nested route state', () => {+ expect(internalPwaLinkTarget('/show/ses_123/?tab=flow#top', current)).toEqual({+ path: '/show/ses_123/?tab=flow#top',+ navigation: 'document',+ });+ expect(internalPwaLinkTarget('/show/ses_123/projects/alpha?mode=edit#node-2', current)).toEqual({+ path: '/show/ses_123/projects/alpha?mode=edit#node-2',+ navigation: 'document',+ });+ });++ it('keeps public Show Pages in context while preserving their server document', () => {+ expect(internalPwaLinkTarget('/p/share_123/?theme=dark#chart', current)).toEqual({+ path: '/p/share_123/?theme=dark#chart',+ navigation: 'document',+ });+ expect(internalPwaLinkTarget('/p/share_123/projects/alpha?theme=dark#chart', current)).toEqual({+ path: '/p/share_123/projects/alpha?theme=dark#chart',+ navigation: 'document',+ });+ });++ it('keeps canonical app routes on the SPA path', () => {+ expect(internalPwaLinkTarget('/chat/session-456?msg=latest#reply', current)).toEqual({+ path: '/chat/session-456?msg=latest#reply',+ navigation: 'spa',+ });+ expect(internalPwaLinkTarget('/admin/settings/models?source=custom', current)).toEqual({+ path: '/admin/settings/models?source=custom',+ navigation: 'spa',+ });+ expect(internalPwaLinkTarget('/admin/settings/memory#profile', current)).toEqual({+ path: '/admin/settings/memory#profile',+ navigation: 'spa',+ });+ });++ it('keeps every other same-origin destination in the current document', () => {+ expect(internalPwaLinkTarget('/api/files/report.pdf?download=0#page=2', current)).toEqual({+ path: '/api/files/report.pdf?download=0#page=2',+ navigation: 'document',+ });+ expect(internalPwaLinkTarget('/custom/help?topic=pwa#recovery', current)).toEqual({+ path: '/custom/help?topic=pwa#recovery',+ navigation: 'document',+ });+ });++ it('leaves external and non-http destinations to their existing handlers', () => {+ expect(internalPwaLinkTarget('https://github.com/avibe-bot/avibe', current)).toBeNull();+ expect(internalPwaLinkTarget('https://alex-app.avibe.bot:8443/help', current)).toBeNull();+ expect(internalPwaLinkTarget('mailto:[email protected]', current)).toBeNull();+ });+});++describe('programmatic PWA navigation', () => {+ it('uses the installed-PWA bridge before opening a new context', () => {+ const bridge = vi.fn((href: string) => href.startsWith('/chat/'));+ const popup = {} as Window;+ const nativeOpen = vi.fn(() => popup);+ vi.stubGlobal('window', {+ __AVIBE_PWA_NAVIGATE_SAME_ORIGIN__: bridge,+ open: nativeOpen,+ });++ expect(openLinkInNewContext('/chat/session-456', 'noopener')).toBeNull();+ expect(nativeOpen).not.toHaveBeenCalled();++ expect(openLinkInNewContext('https://github.com/avibe-bot/avibe', 'noopener,noreferrer')).toBe(popup);+ expect(nativeOpen).toHaveBeenCalledWith(+ 'https://github.com/avibe-bot/avibe',+ '_blank',+ 'noopener,noreferrer',+ );+ });++ it('keeps direct window.open calls confined to the shared helper and the preallocated desktop tab', () => {+ const sourceRoot = new URL('../', import.meta.url);+ const directCalls = sourceFiles(sourceRoot)+ .map((url) => ({+ path: fileURLToPath(url).slice(fileURLToPath(sourceRoot).length),+ count: directWindowOpenCount(url),+ }))+ .filter(({ count }) => count > 0)+ .sort((left, right) => left.path.localeCompare(right.path));++ expect(directCalls).toEqual([+ { path: 'components/workbench/ShowPageLaunchControl.tsx', count: 1 },+ { path: 'lib/pwaNavigation.ts', count: 1 },+ ]);++ const preallocatedTab = readFileSync(+ new URL('../components/workbench/ShowPageLaunchControl.tsx', import.meta.url),+ 'utf8',+ );+ expect(preallocatedTab).toContain("window.open('about:blank', '_blank')");+ });+});diff --git a/ui/src/lib/pwaNavigation.ts b/ui/src/lib/pwaNavigation.tsindex 117be5972..34d97349e 100644--- a/ui/src/lib/pwaNavigation.ts+++ b/ui/src/lib/pwaNavigation.ts@@ -1,3 +1,11 @@+import { isApplicationRouteHref } from './applicationRoutes';++declare global {+ interface Window {+ __AVIBE_PWA_NAVIGATE_SAME_ORIGIN__?: (href: string) => boolean;+ }+}+function normalizeHostname(hostname: string): string {return hostname.trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');}@@ -29,3 +37,54 @@ export function shouldBlockPwaLoopbackLink(href: string, currentHref: string): breturn false;}}++/**+ * Resolve a same-origin `_blank` navigation to the target the installed iOS+ * PWA should open in its current browsing context.+ *+ * A private Show Page root uses the in-shell app route so the user keeps Avibe+ * chrome and back navigation. Canonical AppShell routes stay on the SPA path,+ * avoiding a reload and another auth pass. Every other same-origin destination+ * uses a current-context document navigation so WebKit never creates the+ * secondary context that iOS may incorrectly restore after process eviction.+ * Callers exclude download anchors before using this resolver.+ */+export interface InternalPwaLinkTarget {+ path: string;+ navigation: 'spa' | 'document';+}++export function internalPwaLinkTarget(+ href: string,+ currentHref: string,+): InternalPwaLinkTarget | null {+ try {+ const current = new URL(currentHref);+ const target = new URL(href, current);+ if (target.origin !== current.origin || !['http:', 'https:'].includes(target.protocol)) return null;++ const privateShowRoot = /^\/show\/([^/]+)\/?$/.exec(target.pathname);+ if (privateShowRoot && !target.search && !target.hash) {+ return { path: `/apps/show/${privateShowRoot[1]}`, navigation: 'spa' };+ }++ return {+ path: `${target.pathname}${target.search}${target.hash}`,+ navigation: isApplicationRouteHref(target.pathname) ? 'spa' : 'document',+ };+ } catch {+ return null;+ }+}++/**+ * Open a link that normally requests a new browsing context while honoring the+ * installed-PWA same-origin policy. The AppShell bridge returns true only when+ * it handled the destination in the current PWA context; desktop and external+ * destinations keep the browser's native `_blank` behavior.+ */+export function openLinkInNewContext(href: string, features?: string): Window | null {+ if (typeof window === 'undefined') return null;+ if (window.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__?.(href)) return null;+ return window.open(href, '_blank', features);+}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 2f5b454a6..efd207735 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -10992,6 +10992,32 @@ def _show_runtime_config_script("(function(){"f"var next={payload};""globalThis.__AVIBE_SHOW__=Object.assign({},globalThis.__AVIBE_SHOW__||{},next);"+ "function parentNavigate(){"+ "try{"+ "var candidate=window.parent!==window&&window.parent.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__;"+ "return typeof candidate==='function'?candidate:null;"+ "}catch(_){return null;}"+ "}"+ "function isIosStandalone(){"+ "var ua=navigator.userAgent||'';"+ "var ios=/iP(hone|ad|od)/.test(ua)||(navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1);"+ "return ios&&(navigator.standalone===true||(window.matchMedia&&window.matchMedia('(display-mode: standalone)').matches));"+ "}"+ "document.addEventListener('click',function(event){"+ "var bridge=parentNavigate();"+ "if(!bridge&&!isIosStandalone())return;"+ "var element=event.target instanceof Element?event.target:null;"+ "var anchor=element&&element.closest('a[href]');"+ "if(!anchor||String(anchor.target).toLowerCase()!=='_blank'||anchor.hasAttribute('download'))return;"+ "var target;try{target=new URL(anchor.href,window.location.href);}catch(_){return;}"+ "if(target.origin!==window.location.origin||!/^https?:$/.test(target.protocol))return;"+ "event.preventDefault();event.stopImmediatePropagation();"+ "var path=target.pathname+target.search+target.hash;"+ "var base=String(next.basePath||'');"+ "var withinShow=base&&(target.pathname===base.slice(0,-1)||target.pathname.indexOf(base)===0);"+ "if(window.parent!==window&&!withinShow&&bridge){bridge(target.href);return;}"+ "window.location.assign(path);"+ "},true);""}());""</script>")