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
feat(show): integrate Show Pages with app windows (#1109)
Call Whiteb8555df6b665
diff --git a/README.md b/README.mdindex 771cf4ec1..e5adf3547 100644--- a/README.md+++ b/README.md@@ -88,6 +88,8 @@ Open **Runs** to see that collaboration as a graph: who started each backgroundWhen a picture beats a paragraph, your agent hands you a live web page — a flowchart, dashboard, diff, report, or small app. Comment on an element or screenshot, and the agent can rework the page or answer exactly where you pointed.+In Chat, click **Visualize** to switch the current session to its Show Page. Hover the button to open the page in a new app window or browser tab. You can also drag the button downward and release to place a new app window at the pointer, or drop it on **Apps** to pin that Show Page to the Dock.+<img src="assets/screenshots/v4/show-page-en.png" alt="Show Page review with anchored comments and Agent replies on the page" />### 🔐 Vaults — secret values stay out of Vault responsesdiff --git a/README_ZH.md b/README_ZH.mdindex 391e4541e..a0e998c30 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -88,6 +88,8 @@ Windows 上推荐用 WSL,兼容性最好——见 [从零用 WSL 跑 Avibe](do当一张图胜过一段话,Agent 直接给你一个实时网页——流程图、仪表盘、diff、报告或小应用。你可以对元素或截图原位评论,Agent 也能在你指的位置回答或直接改好页面。+在 Chat 中点击**可视化**,即可把当前 Session 切换到它的 Show Page。将鼠标悬停在按钮上,可以改为在新的应用窗口或浏览器标签页中打开;也可以向下拖拽后松开,在指针位置放置一个新窗口,或拖到**应用**按钮上,把该 Show Page 固定到 Dock。+<img src="assets/screenshots/v4/show-page-zh.png" alt="Show Page 审阅界面,包含原位评论与 Agent 页面内回复" />### 🔐 Vaults——Vault 响应不暴露密钥值diff --git a/ui/src/apps/ShowPageApp.tsx b/ui/src/apps/ShowPageApp.tsxindex a5199c290..dd468b5d1 100644--- a/ui/src/apps/ShowPageApp.tsx+++ b/ui/src/apps/ShowPageApp.tsx@@ -1,12 +1,11 @@-import { useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';import { MonitorX, PinOff } from 'lucide-react';-import { inTextEntrySurface } from '../components/apps/windowChords';-import { useApi } from '../context/ApiContext';+import { bindShowPageFrameCloseShortcut } from '../components/apps/windowChords';+import { useRequiredShowPageAnnotationHost } from '../components/workbench/ShowPageAnnotationHostContext';import { useDock } from '../context/DockContext';import { useWindowManager } from '../context/WindowManagerContext';-import { showPagePrivatePath } from './showPageAvatar';// A pinned Show Page opened as a workbench app. The body always frames the// PRIVATE /show/<session_id>/ surface (authenticated workbench context, live@@ -19,94 +18,32 @@ import { showPagePrivatePath } from './showPageAvatar';export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, unknown> }> = ({ windowId, params }) => {const { t } = useTranslation();- const api = useApi();- // Destructure the STABLE window-manager callbacks (useCallback-memoized) rather- // than the whole context value: the value object changes identity on every- // window focus/minimize/drag tick, and depending on it here would re-run this- // "read once" effect and re-hit /api/sessions on every such change (Codex).- const { setTitle, close, confirmClose } = useWindowManager();+ const { close, confirmClose } = useWindowManager();const { unpin } = useDock();- const iframeRef = useRef<HTMLIFrameElement | null>(null);+ const { annotation, src } = useRequiredShowPageAnnotationHost();+ const { setIframe: setAnnotationIframe, handleIframeLoad } = annotation;+ const shortcutCleanupRef = useRef<() => void>(() => undefined);+ const setIframe = useCallback(+ (iframe: HTMLIFrameElement | null) => {+ shortcutCleanupRef.current();+ shortcutCleanupRef.current = () => undefined;+ setAnnotationIframe(iframe);+ if (!iframe) return;+ shortcutCleanupRef.current = bindShowPageFrameCloseShortcut(iframe, () => {+ if (confirmClose(windowId)) close(windowId);+ });+ },+ [close, confirmClose, setAnnotationIframe, windowId],+ );const sessionId = typeof params?.sessionId === 'string' ? params.sessionId : '';- // 'loading' optimistically frames the page (the common case: it exists);- // 'missing' swaps to the placeholder once we learn the session is gone/archived.- const [state, setState] = useState<'loading' | 'ready' | 'missing'>(sessionId ? 'loading' : 'missing');-- // Read the session once (error-suppressed — a gone session must NOT toast) to- // upgrade the window title to the LIVE title and to detect missing/archived.- useEffect(() => {- if (!sessionId) return;- let cancelled = false;- api- .getSession(sessionId, { cache: true, handleError: false })- .then((session) => {- if (cancelled) return;- // handleError:false resolves (does not throw) on a 404, returning the raw- // error body — so a response without a real session id, or an archived- // session, is the "missing" signal, same as a rejection.- if (!session || typeof session.id !== 'string' || session.status === 'archived') {- setState('missing');- return;- }- setState('ready');- const live = (session.title ?? '').trim();- if (live) setTitle(windowId, live);- })- .catch(() => {- if (!cancelled) setState('missing');- });- return () => {- cancelled = true;- };- }, [sessionId, api, setTitle, windowId]);- // Bridge ⌥W (close window) into the same-origin Show Page iframe: a keydown- // inside the iframe dispatches to ITS document and never bubbles to the parent- // WindowLayer listener, so without this ⌥W could not close the window while the- // user is interacting with the page content (Codex §7.1f review). Re-attach on- // each (re)load; text-entry surfaces inside the page keep Option+W for char entry.- useEffect(() => {- const iframe = iframeRef.current;- if (!iframe) return;- const onKeyDown = (e: KeyboardEvent) => {- if (e.code !== 'KeyW' || !e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;- let active: Element | null = null;- try {- active = iframe.contentDocument?.activeElement ?? null;- } catch {- active = null;- }- if (inTextEntrySurface(active)) return;- e.preventDefault();- if (confirmClose(windowId)) close(windowId);- };- const attach = () => {- try {- // Capture phase (`true`) on the iframe's WINDOW — the EARLIEST target in the- // event path (window → document → element). A page that installs its own- // capture-phase keydown listener and calls stopPropagation() would run before- // a document-level capture listener and still swallow ⌥W; the window capture- // runs before that, so only the explicit text-entry exemption above can- // suppress the close shortcut (Codex §7.1g review).- iframe.contentWindow?.addEventListener('keydown', onKeyDown, true);- } catch {- // Cross-origin (should not happen for the same-origin /show/ surface).- }- };- attach();- iframe.addEventListener('load', attach);- return () => {- iframe.removeEventListener('load', attach);- try {- iframe.contentWindow?.removeEventListener('keydown', onKeyDown, true);- } catch {- // Document already torn down.- }- };- }, [close, confirmClose, windowId]);+ // Callback refs run whenever the lifecycle host recovers from missing to ready,+ // unlike an effect keyed by a stable ref object. The callback binds immediately;+ // this cleanup is a final backstop for teardown.+ useEffect(() => () => shortcutCleanupRef.current(), []);- if (!sessionId || state === 'missing') {+ if (!sessionId || !src) {return (<div className="grid h-full w-full place-items-center bg-surface px-6 text-center"><div className="flex max-w-[320px] flex-col items-center gap-3">@@ -141,9 +78,10 @@ export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, u// per the standing product decision we do NOT harden it here.return (<iframe- ref={iframeRef}+ ref={setIframe}+ onLoad={handleIframeLoad}title={t('chat.showPage.title')}- src={showPagePrivatePath(sessionId)}+ src={src}sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"allow="clipboard-write"className="h-full w-full border-0 bg-background"diff --git a/ui/src/apps/showPageAvatar.test.ts b/ui/src/apps/showPageAvatar.test.tsindex 654d3a174..20f3d8d96 100644--- a/ui/src/apps/showPageAvatar.test.ts+++ b/ui/src/apps/showPageAvatar.test.ts@@ -6,6 +6,7 @@ import {firstGrapheme,sessionChatPath,showPageAvatar,+ showPageEmbeddedPath,showPageIconUrl,showPagePrivatePath,} from './showPageAvatar';@@ -81,6 +82,18 @@ describe('showPagePrivatePath', () => {});});+describe('showPageEmbeddedPath', () => {+ it('marks a Show Page iframe as parent-controlled', () => {+ expect(showPageEmbeddedPath('/show/ses_1/')).toBe('/show/ses_1/?vibe-embed=1');+ });++ it('preserves existing query parameters and hashes', () => {+ expect(showPageEmbeddedPath('/p/share_1/report?tab=weekly#revenue')).toBe(+ '/p/share_1/report?tab=weekly&vibe-embed=1#revenue',+ );+ });+});+describe('showPageIconUrl', () => {it('puts the session id in the path and the server-issued token as ?v=', () => {// The token is an opaque cache key appended verbatim — the endpoint resolvesdiff --git a/ui/src/apps/showPageAvatar.ts b/ui/src/apps/showPageAvatar.tsindex 9aade2f5a..7b9688a6b 100644--- a/ui/src/apps/showPageAvatar.ts+++ b/ui/src/apps/showPageAvatar.ts@@ -46,6 +46,15 @@ export function showPagePrivatePath(sessionId: string): string {return `/show/${encodeURIComponent(sessionId)}/`;}+/** Mark a local Show Page route as framed by a parent-owned annotation control.+ * The injected overlay reads this parameter to hide its standalone floating FAB+ * and accept control messages from the workbench host instead. */+export function showPageEmbeddedPath(path: string): string {+ const url = new URL(path, 'http://avibe.local');+ url.searchParams.set('vibe-embed', '1');+ return `${url.pathname}${url.search}${url.hash}`;+}+/** The URL for a page's own HTML icon, served by the dedicated* `GET /api/show-pages/<sid>/icon` endpoint (§7.1f). ALL href resolution + policy* lives server-side; the URL carries the session id in the PATH plus thediff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex a77ec9606..ce4334fae 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -17,6 +17,7 @@ import { AppsLauncher } from './AppsLauncher';import { ErrorBoundary } from './ui/error-boundary';import { WindowManagerProvider } from '../context/WindowManagerContext';import { DockProvider } from '../context/DockContext';+import { ShowPageDragProvider } from '../context/ShowPageDragProvider';import { WindowLayer } from './apps/WindowLayer';import { MobileDockDrawer } from './apps/MobileDockDrawer';import { NewSessionSheet } from './workbench/NewSessionSheet';@@ -402,6 +403,7 @@ export const AppShell: React.FC = () => {// Desktop: normal document flow.<WindowManagerProvider><DockProvider>+ <ShowPageDragProvider><div className="flex h-[var(--app-shell-h)] flex-col overflow-hidden bg-background text-foreground md:block md:h-auto md:min-h-screen md:overflow-visible">{/* The sidebar forms its own stacking context BELOW the window layer (aside z-10 < windowlayer z-20), so a maximized window covers the WHOLE sidebar — including the Apps launcher.@@ -632,6 +634,7 @@ export const AppShell: React.FC = () => {the sidebar launcher. */}<WindowLayer /></div>+ </ShowPageDragProvider></DockProvider></WindowManagerProvider>);diff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsxindex c45f7c9e6..8281c688e 100644--- a/ui/src/components/AppsLauncher.tsx+++ b/ui/src/components/AppsLauncher.tsx@@ -6,6 +6,7 @@ import clsx from 'clsx';import { Dock } from './apps/Dock';import { ContextMenu, ContextMenuItem } from './ui/context-menu';import { useWindowManager } from '../context/WindowManagerContext';+import { useShowPageDrag } from '../context/showPageDrag';// The sidebar bottom-left "Apps" button that reveals the Dock.// - hover → the Dock floats up ABOVE the button (transient preview; the@@ -19,8 +20,10 @@ import { useWindowManager } from '../context/WindowManagerContext';export const AppsLauncher: React.FC = () => {const { t } = useTranslation();const wm = useWindowManager();+ const showPageDrag = useShowPageDrag();const [pinned, setPinned] = useState(false);const [hovering, setHovering] = useState(false);+ const [dragHovering, setDragHovering] = useState(false);// Cursor-positioned right-click menu, on the shared ContextMenu primitive.const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);const closeTimer = useRef<number | null>(null);@@ -28,7 +31,13 @@ export const AppsLauncher: React.FC = () => {// cleared once the cursor actually leaves the trigger+panel.const suppressHover = useRef(false);- const visible = pinned || hovering;+ const visible = pinned || hovering || (showPageDrag.active && dragHovering);++ useEffect(() => {+ const resetDragHover = () => setDragHovering(false);+ window.addEventListener('dragend', resetDragHover);+ return () => window.removeEventListener('dragend', resetDragHover);+ }, []);const openHover = () => {if (suppressHover.current) return;@@ -72,7 +81,43 @@ export const AppsLauncher: React.FC = () => {// The sidebar aside owns the stacking context (z-10, below the window layer z-20), so the Apps// button is covered by a maximized window like the rest of the sidebar. `relative` is just the// positioning context for the Dock popover below; the popover's z-50 is scoped to the sidebar.- <div className="relative flex-1" onMouseEnter={openHover} onMouseLeave={queueClose}>+ <div+ className="relative flex-1"+ data-show-page-dock-drop-target+ onMouseEnter={openHover}+ onMouseLeave={queueClose}+ onDragEnter={(event) => {+ if (!showPageDrag.active) return;+ event.preventDefault();+ setDragHovering(true);+ }}+ onDragOver={(event) => {+ if (!showPageDrag.active) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ setDragHovering(true);+ }}+ onDragLeave={(event) => {+ const next = event.relatedTarget;+ if (next instanceof Node && event.currentTarget.contains(next)) return;+ setDragHovering(false);+ }}+ onDrop={(event) => {+ if (!showPageDrag.active) return;+ event.preventDefault();+ event.stopPropagation();+ setDragHovering(false);+ // Keep the Dock visible just long enough for the optimistic pin to land+ // and be seen. Entering the Dock cancels this timer via openHover.+ setHovering(true);+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);+ closeTimer.current = window.setTimeout(() => {+ setHovering(false);+ closeTimer.current = null;+ }, 1200);+ showPageDrag.dropToDock();+ }}+ ><buttontype="button"onClick={onClick}diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsxindex 7411eeb0b..c77fb579c 100644--- a/ui/src/components/apps/AppWindow.tsx+++ b/ui/src/components/apps/AppWindow.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';import clsx from 'clsx';@@ -12,6 +12,8 @@ import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActimport { clampToLayer, resizeBounds, type ResizeDir } from '../../lib/windowBounds';import { WindowBodyGestureShield, shouldShieldWindowBody } from './windowGesture';import { ErrorBoundary } from '../ui/error-boundary';+import { ShowPageAnnotateControl } from '../workbench/ShowPageAnnotateControl';+import { useShowPageAnnotationHost } from '../workbench/ShowPageAnnotationHostContext';const RESIZE_HANDLES: { dir: ResizeDir; className: string }[] = [{ dir: 'n', className: 'left-2 right-2 top-0 h-1.5 cursor-ns-resize' },@@ -35,6 +37,7 @@ export const AppWindow: React.FC<{const { t } = useTranslation();const wm = useWindowManager();const navigate = useNavigate();+ const annotationHost = useShowPageAnnotationHost();// Gate the chat-bubble's SPA navigation through the same unsaved-changes guard the// sidebar uses, so a route-level dirty blocker can veto it (and the minimize) as one.const authorizeRouteAction = useUnsavedChangesActionGuard();@@ -50,6 +53,15 @@ export const AppWindow: React.FC<{// that changes the bounds — otherwise the geometry jumps before the transition class arrives and// maximize/restore don't animate at all.const [dragging, setDragging] = useState(false);+ const [annotateOpen, setAnnotateOpen] = useState(false);+ const focusWindow = wm.focus;+ const handleAnnotateOpenChange = useCallback(+ (open: boolean) => {+ if (open) focusWindow(win.id);+ setAnnotateOpen(open);+ },+ [focusWindow, win.id],+ );// Keep a visible window reachable when the geometry around it changes without a// drag: the layer shrinking, or the window being restored / un-maximized after the@@ -256,7 +268,7 @@ export const AppWindow: React.FC<{onDoubleClick={() => wm.toggleMaximize(win.id)}className="flex h-9 shrink-0 select-none items-center gap-3 border-b border-border px-3.5">- <div className="flex items-center gap-2">+ <div className={clsx('flex shrink-0 items-center gap-2', showpageSid ? 'w-20' : 'w-[52px]')}>{lights.map((l) => (<buttonkey={l.key}@@ -272,7 +284,7 @@ export const AppWindow: React.FC<{</button>))}</div>- <div className="flex flex-1 items-center justify-center gap-1.5 overflow-hidden">+ <div className="flex min-w-0 flex-1 items-center justify-center gap-1.5 overflow-hidden">{showpageSid && showpageAvatar ? (<spanaria-hidden@@ -292,10 +304,26 @@ export const AppWindow: React.FC<{)}<span className="truncate text-[13px] font-semibold text-foreground">{win.title ?? t(def.titleKey)}</span></div>- {/* Right cluster balances the traffic lights so the title stays centered; a- standalone-surface app (showpage) also gets a chat-bubble + open-in-new-tab- pair here — two size-6 buttons + gap-1 fill the 52px box exactly. */}- <div className="flex w-[52px] shrink-0 items-center justify-end gap-1">+ {/* Mirror the left cluster so the title stays centered. Show Page windows+ add a compact annotation control before chat + open-in-new-tab. */}+ <div className={clsx('flex shrink-0 items-center justify-end gap-1', showpageSid ? 'w-20' : 'w-[52px]')}>+ {showpageSid && annotationHost?.src && !win.minimized && exitKind === null && (+ <div+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ onDoubleClick={(e) => e.stopPropagation()}+ >+ <ShowPageAnnotateControl+ compact+ state={annotationHost.annotation.state}+ onEnable={annotationHost.annotation.enable}+ onDisable={annotationHost.annotation.disable}+ onSetMode={annotationHost.annotation.setMode}+ onPopoverOpenChange={handleAnnotateOpenChange}+ ownerWindowId={win.id}+ />+ </div>+ )}{chatHref && (<buttontype="button"@@ -348,6 +376,9 @@ export const AppWindow: React.FC<{transparent overlay so a gesture's pointer can't be stolen by the iframe and thecursor doesn't flicker over it — belt-and-braces with the gesture's pointer capture. */}<WindowBodyGestureShield active={shouldShieldWindowBody(wm.gestureActive, win.minimized)} />+ {annotateOpen && annotationHost?.src && (+ <div aria-hidden data-annotation-shield className="absolute inset-0 z-20" />+ )}</div>{!win.maximized &&diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsxindex 47429aac7..a7dd96527 100644--- a/ui/src/components/apps/WindowLayer.tsx+++ b/ui/src/components/apps/WindowLayer.tsx@@ -5,12 +5,62 @@ import { APP_REGISTRY, type AppId } from '../../apps/registry';import { dockIndexFromShortcut } from '../../apps/dockShortcuts';import { dockIdToSession, useDock } from '../../context/DockContext';import { useApi } from '../../context/ApiContext';-import { useWindowManager } from '../../context/WindowManagerContext';+import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';import { useShowPageInventory } from '../useShowPages';+import { ShowPageAnnotationHost } from '../workbench/ShowPageAnnotationHost';import { AppWindow } from './AppWindow';-import { inTerminalSurface, inTextEntrySurface } from './windowChords';+import {+ showPageWindowSource,+ showPageWindowStatusAfterRead,+ type ShowPageWindowStatus,+} from './showPageWindowState';+import { inTerminalSurface, inTextEntrySurface, windowIdForKeyboardTarget } from './windowChords';import { shouldGuardUnload } from './windowUnload';+const ShowPageWindow: React.FC<{+ archived: boolean;+ iconVersion: string | null;+ layerHeight: number;+ layerWidth: number;+ revalidateVersion: number;+ sessionId: string;+ win: WindowInstance;+}> = ({ archived, iconVersion, layerHeight, layerWidth, revalidateVersion, sessionId, win }) => {+ const api = useApi();+ const { setTitle } = useWindowManager();+ const [status, setStatus] = useState<ShowPageWindowStatus>(sessionId ? 'loading' : 'missing');++ useEffect(() => {+ if (!sessionId) return;+ let cancelled = false;+ api+ .getSessionResult(sessionId)+ .then((result) => {+ if (cancelled) return;+ setStatus((current) => showPageWindowStatusAfterRead(current, result));+ const session = result.session;+ if (!session || typeof session.id !== 'string' || session.status === 'archived') return;+ const liveTitle = (session.title ?? '').trim();+ if (liveTitle) setTitle(win.id, liveTitle);+ })+ .catch(() => {+ if (!cancelled) {+ setStatus((current) => showPageWindowStatusAfterRead(current, { status: null, session: null }));+ }+ });+ return () => {+ cancelled = true;+ };+ }, [api, revalidateVersion, sessionId, setTitle, win.id]);++ const src = showPageWindowSource(sessionId, status, archived);+ return (+ <ShowPageAnnotationHost src={src}>+ <AppWindow win={win} layerWidth={layerWidth} layerHeight={layerHeight} iconVersion={iconVersion} />+ </ShowPageAnnotationHost>+ );+};+// The portal layer that hosts app windows. Covers the workbench main area (right// of the 240px sidebar on desktop). The layer itself is pointer-events-none so// empty space passes clicks through to the workbench underneath; each AppWindow@@ -29,6 +79,8 @@ export const WindowLayer: React.FC = () => {const anyShown = shouldGuardUnload(windows);const ref = useRef<HTMLDivElement | null>(null);const [size, setSize] = useState({ w: 0, h: 0 });+ const [archivedSessionIds, setArchivedSessionIds] = useState<ReadonlySet<string>>(() => new Set());+ const [showPageRevalidateVersion, setShowPageRevalidateVersion] = useState(0);const windowsRef = useRef(windows);const dockRef = useRef({ order, pins, pages });@@ -61,10 +113,8 @@ export const WindowLayer: React.FC = () => {const onKeyDown = (e: KeyboardEvent) => {if (!(e.metaKey || e.ctrlKey) || e.altKey) return;const active = document.activeElement;- const winEl = active instanceof Element ? active.closest('[data-window-id]') : null;- if (!winEl || !ref.current?.contains(winEl)) return;if (e.ctrlKey && !e.metaKey && inTerminalSurface(active)) return;- const targetId = winEl.getAttribute('data-window-id');+ const targetId = windowIdForKeyboardTarget(active, ref.current);if (!targetId) return;const key = e.key.toLowerCase();if (key === 'w') {@@ -89,9 +139,7 @@ export const WindowLayer: React.FC = () => {if (e.code !== 'KeyW' || !e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;const active = document.activeElement;if (inTextEntrySurface(active)) return;- const winEl = active instanceof Element ? active.closest('[data-window-id]') : null;- if (!winEl || !ref.current?.contains(winEl)) return;- const targetId = winEl.getAttribute('data-window-id');+ const targetId = windowIdForKeyboardTarget(active, ref.current);if (!targetId) return;e.preventDefault();if (confirmClose(targetId)) close(targetId);@@ -173,13 +221,27 @@ export const WindowLayer: React.FC = () => {return () => window.removeEventListener('keydown', onKeyDown);}, [focus, openApp, restore, t]);- // Session PATCHes already broadcast `session.activity`. Keep every open- // Show Page window's persisted title/params live when a rename comes from the- // Library, chat header, CLI, or another browser tab.+ // Session mutations broadcast `session.activity`. Keep every open Show Page+ // window's title live, and treat archive as terminal for the frame plus every+ // parent-owned page control.useEffect(() =>api.connectWorkbenchEvents({+ onConnected: () => {+ // Re-read after EVERY subscription is established. This closes both+ // the initial GET-to-first-connect gap and any later reconnect gap.+ setShowPageRevalidateVersion((version) => version + 1);+ },onSessionActivity: (data) => {+ if (data.event === 'archived') {+ setArchivedSessionIds((current) => {+ if (current.has(data.session_id)) return current;+ const next = new Set(current);+ next.add(data.session_id);+ return next;+ });+ return;+ }if (data.event !== 'updated' || !Object.prototype.hasOwnProperty.call(data, 'title')) return;const title = data.title?.trim() || t('chat.untitled');windowsRef.current@@ -212,9 +274,23 @@ export const WindowLayer: React.FC = () => {{windows.map((w) => {// For a showpage window, join the inventory (already loaded above — no new// fetch) to hand its own HTML icon to the title-bar chip (§7.1f/g).- const sid = w.appId === 'showpage' ? (w.params?.sessionId as string | undefined) : undefined;+ const sid = w.appId === 'showpage' && typeof w.params?.sessionId === 'string' ? w.params.sessionId : undefined;const iconVersion = sid ? pages.find((p) => p.session_id === sid)?.icon_version ?? null : null;- return <AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} iconVersion={iconVersion} />;+ if (w.appId !== 'showpage') {+ return <AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} iconVersion={iconVersion} />;+ }+ return (+ <ShowPageWindow+ key={w.id}+ archived={Boolean(sid && archivedSessionIds.has(sid))}+ iconVersion={iconVersion}+ layerHeight={size.h}+ layerWidth={size.w}+ revalidateVersion={showPageRevalidateVersion}+ sessionId={sid ?? ''}+ win={w}+ />+ );})}</div>);diff --git a/ui/src/components/apps/showPageWindowState.test.ts b/ui/src/components/apps/showPageWindowState.test.tsnew file mode 100644index 000000000..fab6d682c--- /dev/null+++ b/ui/src/components/apps/showPageWindowState.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { showPageWindowSource, showPageWindowStatusAfterRead } from './showPageWindowState';++describe('showPageWindowStatusAfterRead', () => {+ it('keeps a ready frame through a non-authoritative read failure', () => {+ expect(showPageWindowStatusAfterRead('ready', { status: 500, session: null })).toBe('ready');+ expect(showPageWindowStatusAfterRead('ready', { status: null, session: null })).toBe('ready');+ });++ it('treats not-found and archived sessions as authoritative missing states', () => {+ expect(showPageWindowStatusAfterRead('ready', { status: 404, session: null })).toBe('missing');+ expect(+ showPageWindowStatusAfterRead('loading', {+ status: 200,+ session: { id: 'ses_1', status: 'archived' },+ }),+ ).toBe('missing');+ });++ it('accepts an active session and rejects a failed initial read', () => {+ expect(+ showPageWindowStatusAfterRead('loading', {+ status: 200,+ session: { id: 'ses_1', status: 'active' },+ }),+ ).toBe('ready');+ expect(showPageWindowStatusAfterRead('loading', { status: 500, session: null })).toBe('missing');+ });+});++describe('showPageWindowSource', () => {+ it('optimistically frames an active session while its row loads', () => {+ expect(showPageWindowSource('ses_1', 'loading', false)).toBe('/show/ses_1/?vibe-embed=1');+ expect(showPageWindowSource('ses_1', 'ready', false)).toBe('/show/ses_1/?vibe-embed=1');+ });++ it('withdraws the frame and parent controls for missing or archived sessions', () => {+ expect(showPageWindowSource('ses_1', 'missing', false)).toBeNull();+ expect(showPageWindowSource('ses_1', 'ready', true)).toBeNull();+ expect(showPageWindowSource('', 'ready', false)).toBeNull();+ });+});diff --git a/ui/src/components/apps/showPageWindowState.ts b/ui/src/components/apps/showPageWindowState.tsnew file mode 100644index 000000000..1d7e5bf59--- /dev/null+++ b/ui/src/components/apps/showPageWindowState.ts@@ -0,0 +1,26 @@+import { showPageEmbeddedPath, showPagePrivatePath } from '../../apps/showPageAvatar';++export type ShowPageWindowStatus = 'loading' | 'ready' | 'missing';++/** Apply a silent session read without withdrawing a working frame on transient errors. */+export function showPageWindowStatusAfterRead(+ current: ShowPageWindowStatus,+ result: { status: number | null; session: unknown },+): ShowPageWindowStatus {+ if (result.status === 404) return 'missing';+ const session = result.session;+ if (!session || typeof session !== 'object' || typeof (session as { id?: unknown }).id !== 'string') {+ return current === 'ready' ? 'ready' : 'missing';+ }+ return (session as { status?: unknown }).status === 'archived' ? 'missing' : 'ready';+}++/** The framed page and its parent-owned controls share one lifecycle source. */+export function showPageWindowSource(+ sessionId: string,+ status: ShowPageWindowStatus,+ archived: boolean,+): string | null {+ if (!sessionId || status === 'missing' || archived) return null;+ return showPageEmbeddedPath(showPagePrivatePath(sessionId));+}diff --git a/ui/src/components/apps/windowChords.test.ts b/ui/src/components/apps/windowChords.test.tsindex e4f20062d..5f046b028 100644--- a/ui/src/components/apps/windowChords.test.ts+++ b/ui/src/components/apps/windowChords.test.ts@@ -1,6 +1,29 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { inTerminalSurface, inTextEntrySurface } from './windowChords';+import {+ bindShowPageFrameCloseShortcut,+ inTerminalSurface,+ inTextEntrySurface,+ windowIdForKeyboardTarget,+} from './windowChords';++class ListenerHub {+ private listeners = new Map<string, Set<EventListener>>();++ addEventListener(type: string, listener: EventListener) {+ const listeners = this.listeners.get(type) ?? new Set<EventListener>();+ listeners.add(listener);+ this.listeners.set(type, listeners);+ }++ removeEventListener(type: string, listener: EventListener) {+ this.listeners.get(type)?.delete(listener);+ }++ emit(type: string, event: unknown) {+ this.listeners.get(type)?.forEach((listener) => listener(event as Event));+ }+}// Mock an Element by its closest() behavior alone — realm-agnostic and jsdom-free.// A PLAIN OBJECT is never `instanceof HTMLElement`, so it doubles as the cross-realm@@ -33,3 +56,78 @@ describe('inTerminalSurface', () => {expect(inTerminalSurface(null)).toBe(false);});});++describe('bindShowPageFrameCloseShortcut', () => {+ const shortcutEvent = () => ({+ code: 'KeyW',+ altKey: true,+ metaKey: false,+ ctrlKey: false,+ shiftKey: false,+ preventDefault: vi.fn(),+ });++ it('binds when a recovered iframe mounts and reattaches after frame load', () => {+ const iframeEvents = new ListenerHub();+ const firstWindow = new ListenerHub();+ const recoveredWindow = new ListenerHub();+ const frame = {+ contentDocument: { activeElement: null },+ contentWindow: firstWindow,+ addEventListener: iframeEvents.addEventListener.bind(iframeEvents),+ removeEventListener: iframeEvents.removeEventListener.bind(iframeEvents),+ } as unknown as HTMLIFrameElement;+ const close = vi.fn();+ const cleanup = bindShowPageFrameCloseShortcut(frame, close);++ firstWindow.emit('keydown', shortcutEvent());+ expect(close).toHaveBeenCalledTimes(1);++ Object.defineProperty(frame, 'contentWindow', { value: recoveredWindow });+ iframeEvents.emit('load', {});+ recoveredWindow.emit('keydown', shortcutEvent());+ expect(close).toHaveBeenCalledTimes(2);++ cleanup();+ recoveredWindow.emit('keydown', shortcutEvent());+ expect(close).toHaveBeenCalledTimes(2);+ });+});++describe('windowIdForKeyboardTarget', () => {+ const attributedElement = (attributes: Record<string, string>): Element =>+ ({ getAttribute: (name: string) => attributes[name] ?? null }) as unknown as Element;++ const targetWithClosest = (matches: Record<string, Element | null>): Element =>+ ({ closest: (selector: string) => matches[selector] ?? null }) as unknown as Element;++ const layerWithWindows = (windows: Element[], contained: Element[] = windows): Element =>+ ({+ contains: (candidate: Element) => contained.includes(candidate),+ querySelectorAll: () => windows,+ }) as unknown as Element;++ it('resolves a focused descendant of an in-layer window', () => {+ const root = attributedElement({ 'data-window-id': 'win-1' });+ const target = targetWithClosest({ '[data-window-id]': root });++ expect(windowIdForKeyboardTarget(target, layerWithWindows([root]))).toBe('win-1');+ });++ it('resolves a portalled control through its explicit window owner', () => {+ const root = attributedElement({ 'data-window-id': 'win-2' });+ const portal = attributedElement({ 'data-window-owner-id': 'win-2' });+ const target = targetWithClosest({ '[data-window-owner-id]': portal });++ expect(windowIdForKeyboardTarget(target, layerWithWindows([root]))).toBe('win-2');+ });++ it('rejects portal owners that do not name a window in this layer', () => {+ const root = attributedElement({ 'data-window-id': 'win-3' });+ const portal = attributedElement({ 'data-window-owner-id': 'other-window' });+ const target = targetWithClosest({ '[data-window-owner-id]': portal });++ expect(windowIdForKeyboardTarget(target, layerWithWindows([root]))).toBeNull();+ expect(windowIdForKeyboardTarget(target, null)).toBeNull();+ });+});diff --git a/ui/src/components/apps/windowChords.ts b/ui/src/components/apps/windowChords.tsindex 892a7432a..5c201b00a 100644--- a/ui/src/components/apps/windowChords.ts+++ b/ui/src/components/apps/windowChords.ts@@ -27,3 +27,72 @@ export function inTextEntrySurface(el: Element | null): boolean {'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], .monaco-editor, .xterm',);}++/** Bind the browser-safe close chord to one mounted same-origin Show Page frame. */+export function bindShowPageFrameCloseShortcut(+ iframe: HTMLIFrameElement,+ onClose: () => void,+): () => void {+ const onKeyDown = (event: KeyboardEvent) => {+ if (+ event.code !== 'KeyW' ||+ !event.altKey ||+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey+ ) {+ return;+ }+ let active: Element | null = null;+ try {+ active = iframe.contentDocument?.activeElement ?? null;+ } catch {+ active = null;+ }+ if (inTextEntrySurface(active)) return;+ event.preventDefault();+ onClose();+ };++ const attach = () => {+ try {+ // The WindowProxy can survive navigation, so remove before every load-time+ // attach to keep exactly one capture listener on the active document.+ iframe.contentWindow?.removeEventListener('keydown', onKeyDown, true);+ iframe.contentWindow?.addEventListener('keydown', onKeyDown, true);+ } catch {+ // Cross-origin frames are not expected for the private Show Page surface.+ }+ };++ attach();+ iframe.addEventListener('load', attach);+ return () => {+ iframe.removeEventListener('load', attach);+ try {+ iframe.contentWindow?.removeEventListener('keydown', onKeyDown, true);+ } catch {+ // The frame may already be torn down.+ }+ };+}++/** Resolve focused window chrome, including controls rendered in a body portal. */+export function windowIdForKeyboardTarget(target: Element | null, layer: Element | null): string | null {+ if (!target || !layer) return null;++ const windowRoot = target.closest?.('[data-window-id]');+ if (windowRoot && layer.contains(windowRoot)) {+ return windowRoot.getAttribute('data-window-id');+ }++ const portalledRoot = target.closest?.('[data-window-owner-id]');+ const ownerId = portalledRoot?.getAttribute('data-window-owner-id');+ if (!ownerId) return null;++ // A data attribute outside this layer cannot nominate an arbitrary window.+ for (const candidate of layer.querySelectorAll('[data-window-id]')) {+ if (candidate.getAttribute('data-window-id') === ownerId) return ownerId;+ }+ return null;+}diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsxindex 4d3d416ff..355d99288 100644--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx@@ -266,6 +266,7 @@ describe('read-only header withdraws the Show Page controls', () => {showPageMode={false}showPageBusy={false}onToggleShowPage={() => undefined}+ onPrepareShowPageLaunch={async () => false}annotation={{state: null,iframeRef: { current: null },@@ -401,6 +402,7 @@ describe('archived conflicts converge whatever the verb', () => {showPageMode={false}showPageBusy={false}onToggleShowPage={() => undefined}+ onPrepareShowPageLaunch={async () => false}annotation={{state: null,iframeRef: { current: null },diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 1ff9a6e78..cd6062f3b 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -1,7 +1,7 @@import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';-import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';+import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Pencil, Terminal, Undo2, UploadCloud, X } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';@@ -11,6 +11,7 @@ import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';import { apiFetch } from '../../lib/apiFetch';+import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessageTypes';@@ -18,6 +19,7 @@ import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../limport { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';+import { showPageEmbeddedPath } from '../../apps/showPageAvatar';import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';import {activityItemKind,@@ -37,6 +39,7 @@ import { mergeById, insertMessageOrdered } from '../../lib/transcriptOrder';import { AgentRoutePicker } from './AgentRoutePicker';import { ShowPageShareControl } from './ShowPageShareControl';import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';+import { ShowPageLaunchControl } from './ShowPageLaunchControl';import { useShowPageAnnotation, type AnnotationBridge } from './useShowPageAnnotation';import { SelectionQuoteToolbar } from './SelectionQuoteToolbar';import {@@ -80,15 +83,6 @@ import {type TurnActivityGroupWire,} from '../../lib/agentActivity';-// The chat host marks its Show Page iframe with ``vibe-embed=1`` (annotation-// contract §6) so the in-page overlay switches to embedded mode — floating-// toolbar hidden, controlled via postMessage from the header control. Applied-// wherever the iframe src is composed (first open + visibility re-point).-const SHOW_PAGE_EMBED_PARAM = 'vibe-embed=1';-function embedShowPageSrc(path: string): string {- return path.includes('?') ? `${path}&${SHOW_PAGE_EMBED_PARAM}` : `${path}?${SHOW_PAGE_EMBED_PARAM}`;-}-// While a turn is in flight, reconcile the working/Stop state against the// controller on this cadence (the backend ``GET /turn-state`` is authoritative).// This recovers a DROPPED ``turn.end`` without ever killing a live turn on a@@ -189,6 +183,24 @@ export const ChatPage: React.FC = () => {// before the composer bridge target, which depends on showPageMode.const [showPageMode, setShowPageMode] = useState(false);const [showPageBusy, setShowPageBusy] = useState(false);+ // One authority invalidates an in-flight restore/open when the user explicitly+ // chooses Chat (including a same-session ?view=chat navigation).+ const showPageRequestRef = useRef(0);+ useEffect(+ () => () => {+ // External launches resolve after an async ensure. Once this page has+ // unmounted, none of those prepared actions may still open or pin it.+ showPageRequestRef.current += 1;+ },+ [],+ );+ const showPageRestoreAttemptRef = useRef<string | null>(null);+ const selectChatView = useCallback((sid: string, remember: boolean) => {+ showPageRequestRef.current += 1;+ setShowPageMode(false);+ setShowPageBusy(false);+ if (remember) writeChatViewMode(sid, 'chat');+ }, []);// Sessions whose first-open visualize prompt failed to send — retry it on the// next toggle (the page row already exists, so `existed` alone won't re-prompt).const showPagePromptRetryRef = useRef<Set<string>>(new Set());@@ -222,12 +234,13 @@ export const ChatPage: React.FC = () => {// remounted overlay before it rebroadcasts. Re-points reset via the URL change.const annotation = useShowPageAnnotation(showPageActive ? showPageUrl : null);useEffect(() => {- // ChatPage is reused across :sessionId — clear all show-page state so the- // next chat starts in chat view with a live (not stuck-busy) toggle.- setShowPageMode(false);+ // ChatPage is reused across :sessionId. Clear the previous frame immediately;+ // once the new session row loads, the restore effect below applies its own+ // remembered view through the same open path as a user click.+ showPageRestoreAttemptRef.current = null;+ selectChatView(sessionId ?? '', false);setShowPageUrl(null);- setShowPageBusy(false);- }, [sessionId]);+ }, [selectChatView, sessionId]);// Honor the ?view=chat "show me the chat" signal ONCE: leave Show Page mode and strip// the param. This makes the intent work even for a same-session jump (where the@@ -235,11 +248,13 @@ export const ChatPage: React.FC = () => {// stripping it (like the ?msg jump below) keeps it a no-op on every render afterwards.useEffect(() => {if (!showChatSignal) return;- setShowPageMode(false);+ const sid = sessionId ?? '';+ showPageRestoreAttemptRef.current = sid || null;+ selectChatView(sid, true);const next = new URLSearchParams(window.location.search);next.delete('view');setSearchParams(next, { replace: true });- }, [showChatSignal, setSearchParams]);+ }, [selectChatView, sessionId, showChatSignal, setSearchParams]);// Publish this chat's composer to the ComposerBridge so the sidebar's// "reference this session" action can insert a #<session> mention into the@@ -672,6 +687,9 @@ export const ChatPage: React.FC = () => {// archive onto the chat now mounted (markSessionArchived guards the row// identity too; this also skips the needless refresh).if (archivedSessionId !== sessionIdRef.current) return;+ showPageRequestRef.current += 1;+ setShowPageBusy(false);+ writeChatViewMode(archivedSessionId, 'chat');setSession((prev) => markSessionArchived(prev, archivedSessionId));void refreshSessionRow();},@@ -1145,7 +1163,11 @@ export const ChatPage: React.FC = () => {onSessionActivity: (data) => {if (data.session_id === sessionIdRef.current && data.event === 'archived') {// The session you're viewing was archived (here or in another tab) —- // archive is terminal, so leave the chat.+ // archive is terminal, so cancel any prepared external launch before+ // leaving the chat.+ showPageRequestRef.current += 1;+ setShowPageBusy(false);+ writeChatViewMode(data.session_id, 'chat');goBack();return;}@@ -1394,64 +1416,102 @@ export const ChatPage: React.FC = () => {[api, sessionId],);- // Toggle the chat surface ↔ the session's Show Page (iframe). The first open- // ensures the page exists; if it was just created, ask the agent to build the- // visualization. Errors surface via the apiFetch toast layer.+ // One action path serves inline view changes and external launches. Every+ // target first ensures the page and sends the same first-build prompt; only+ // the inline target changes this chat's remembered surface.+ const performShowPageAction = useCallback(+ async (sid: string, target: 'inline' | 'prepare'): Promise<boolean> => {+ const request = ++showPageRequestRef.current;+ setShowPageBusy(true);+ try {+ const res = await api.ensureShowPage(sid);+ // Bail if the user switched chats or explicitly selected Chat while ensure+ // was in flight. The request id closes the same-session ?view=chat race.+ if (sessionIdRef.current !== sid || showPageRequestRef.current !== request) return false;+ if (res?.ok) {+ if (target === 'inline') {+ // Public pages are served under /p/<share_id>/; private under /show/<id>/.+ setShowPageUrl(+ showPageEmbeddedPath(+ res.visibility === 'public' && res.share_id+ ? `/p/${encodeURIComponent(res.share_id)}/`+ : `/show/${encodeURIComponent(sid)}/`,+ ),+ );+ setShowPageMode(true);+ writeChatViewMode(sid, 'show-page');+ }+ // First open (or a prior prompt that failed to send) asks the agent to+ // build the visualization. sendMessage returns false on a failed send;+ // track it so the NEXT toggle retries — the page row exists after this,+ // so `existed` alone would never re-prompt a created-but-unprompted page.+ // Never on a read-only (archived) session: the store refuses to CREATE a+ // page there, but a session archived after a failed prompt is still in the+ // retry set, and re-prompting it would only 409. The header no longer+ // offers the toggle at all once the session reads archived, so this is the+ // callback-level backstop for an invocation that raced that render.+ if (!readOnly && (res.existed === false || showPagePromptRetryRef.current.has(sid))) {+ void sendMessage(t('chat.showPage.prompt')).then((sent) => {+ if (sent === false) showPagePromptRetryRef.current.add(sid);+ else showPagePromptRetryRef.current.delete(sid);+ });+ }+ return true;+ }+ return false;+ } catch {+ // apiFetch already surfaced a toast; stay in chat view.+ return false;+ } finally {+ if (sessionIdRef.current === sid && showPageRequestRef.current === request) {+ setShowPageBusy(false);+ }+ }+ },+ [readOnly, api, sendMessage, t],+ );++ const openShowPage = useCallback(+ (sid: string) => performShowPageAction(sid, 'inline'),+ [performShowPageAction],+ );++ const prepareShowPageLaunch = useCallback(+ (sid: string) => performShowPageAction(sid, 'prepare'),+ [performShowPageAction],+ );+const toggleShowPage = useCallback(async () => {const sid = sessionId;if (!sid) return;if (showPageMode) {- setShowPageMode(false);+ selectChatView(sid, true);return;}- setShowPageBusy(true);- try {- const res = await api.ensureShowPage(sid);- // Bail if the user switched chats while ensure was in flight — otherwise a- // stale resolve would flip the NEW chat into iframe mode + send its prompt.- if (sessionIdRef.current !== sid) return;- if (res?.ok) {- // Public pages are served under /p/<share_id>/; private under /show/<id>/.- setShowPageUrl(- embedShowPageSrc(- res.visibility === 'public' && res.share_id- ? `/p/${encodeURIComponent(res.share_id)}/`- : `/show/${encodeURIComponent(sid)}/`,- ),- );- setShowPageMode(true);- // First open (or a prior prompt that failed to send) asks the agent to- // build the visualization. sendMessage returns false on a failed send;- // track it so the NEXT toggle retries — the page row exists after this,- // so `existed` alone would never re-prompt a created-but-unprompted page.- // Never on a read-only (archived) session: the store refuses to CREATE a- // page there, but a session archived after a failed prompt is still in the- // retry set, and re-prompting it would only 409. The header no longer- // offers the toggle at all once the session reads archived, so this is the- // callback-level backstop for an invocation that raced that render.- if (!readOnly && (res.existed === false || showPagePromptRetryRef.current.has(sid))) {- void sendMessage(t('chat.showPage.prompt')).then((sent) => {- if (sent === false) showPagePromptRetryRef.current.add(sid);- else showPagePromptRetryRef.current.delete(sid);- });- }- }- } catch {- // apiFetch already surfaced a toast; stay in chat view.- } finally {- // Always clear — the in-flight request is done regardless of which chat is- // now mounted (ChatPage is reused across sessions; a guarded clear would- // strand the shared busy flag on a session the user switched to).- setShowPageBusy(false);+ await openShowPage(sid);+ }, [openShowPage, selectChatView, sessionId, showPageMode]);++ // Restore a session's last selected surface after its authoritative row loads.+ // Explicit chat/message deep links win, and archived sessions permanently fall+ // back to Chat because their Show Page is offline.+ useEffect(() => {+ const sid = sessionId;+ if (!sid || session?.id !== sid || showPageRestoreAttemptRef.current === sid) return;+ showPageRestoreAttemptRef.current = sid;+ if (readOnly) {+ writeChatViewMode(sid, 'chat');+ return;}- }, [sessionId, showPageMode, readOnly, api, sendMessage, t]);+ if (showChatSignal || deepLinkMessageId || readChatViewMode(sid) !== 'show-page') return;+ void openShowPage(sid);+ }, [deepLinkMessageId, openShowPage, readOnly, session?.id, sessionId, showChatSignal]);// When the share control resolves the page (open) or flips its visibility, the// serving route changes (private → /show/, public → /p/). Re-point the iframe// so it never stays on a route that now 404s.const handleShowPagePayload = useCallback((next: ShowPageLinkInfo) => {const path = localPath(next);- if (path) setShowPageUrl(embedShowPageSrc(path));+ if (path) setShowPageUrl(showPageEmbeddedPath(path));}, []);// A quick-reply click sends the chosen label as a normal user turn, tagged with@@ -1607,7 +1667,7 @@ export const ChatPage: React.FC = () => {// Wait until THIS session's initial data is present (refresh resolved and// the loaded session matches the route) — before that the loaded-vs-around// decision and the scroll target wouldn't be meaningful.- if (loading || !session || session.id !== sessionId) return;+ if (loading || session?.id !== sessionId) return;handledJumpRef.current = targetMsg;const requestSessionId = sessionId;@@ -1616,7 +1676,8 @@ export const ChatPage: React.FC = () => {// surface (transcript) is hidden behind the iframe — a scroll + highlight// there would be unseen. Exit Show Page mode so the chat is visible for the// jump (the user came here from a search result, so they want the message).- setShowPageMode(false);+ showPageRestoreAttemptRef.current = sessionId;+ selectChatView(sessionId, true);// Clear only ``msg`` (preserve any other query params) so a re-render /// visibility gap-recovery can't re-fire the jump. Read the live URL so we@@ -1682,7 +1743,7 @@ export const ChatPage: React.FC = () => {// window is dropped and ``?msg`` stays unhandled (Codex P2). The closure// still reads ``session`` for the ``!session`` / ``session.id !== sessionId``// readiness checks; it only needs to re-run when the id changes.- }, [deepLinkMessageId, sessionId, loading, session?.id, api, startHighlight, setSearchParams]);+ }, [deepLinkMessageId, sessionId, loading, session?.id, api, selectChatView, startHighlight, setSearchParams]);// Re-arm the jump guard once ``?msg=`` is gone. ``clearParam`` (above) nulls// the param after handling, so without this re-selecting the SAME search hit@@ -1935,6 +1996,7 @@ export const ChatPage: React.FC = () => {showPageMode={showPageActive}showPageBusy={showPageBusy}onToggleShowPage={toggleShowPage}+ onPrepareShowPageLaunch={prepareShowPageLaunch}onShowPageVisibilityChange={handleShowPagePayload}onShareOpenChange={setShareOpen}annotation={annotation}@@ -1957,7 +2019,7 @@ export const ChatPage: React.FC = () => {// isolation isn't the security boundary anyway. We still drop the exotic// capabilities the page never needs (top navigation, pointer lock, etc.).<iframe- ref={annotation.iframeRef}+ ref={annotation.setIframe}onLoad={annotation.handleIframeLoad}title={t('chat.showPage.title')}src={showPageUrl}@@ -2479,6 +2541,7 @@ interface ChatHeaderBarProps {showPageMode: boolean;showPageBusy: boolean;onToggleShowPage: () => void;+ onPrepareShowPageLaunch: (sessionId: string) => Promise<boolean>;onShowPageVisibilityChange?: (payload: ShowPageLinkInfo) => void;onShareOpenChange?: (open: boolean) => void;annotation: AnnotationBridge;@@ -2493,7 +2556,7 @@ interface ChatHeaderBarProps {// which renders the header alone rather than mounting the whole page. Note the// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the// read-only rendering is reachable without an ApiProvider.-export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnly }) => {+export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnly }) => {const { t } = useTranslation();const showPageActions = showPageControlActions(readOnly, showPageMode);const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;@@ -2612,26 +2675,14 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, donPopoverOpenChange={onAnnotateOpenChange}/>)}- <Button- type="button"- variant={showPageMode ? 'secondary' : 'ghost'}- onClick={onToggleShowPage}- disabled={showPageBusy}- aria-label={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}- title={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}- className="h-7 shrink-0 gap-1.5 px-2"- >- {showPageBusy ? (- <Loader2 className="size-3.5 animate-spin" />- ) : showPageMode ? (- <MessageSquare className="size-3.5" />- ) : (- <Presentation className="size-3.5" />- )}- <span className="hidden text-xs font-medium md:inline">- {showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}- </span>- </Button>+ <ShowPageLaunchControl+ sessionId={session.id}+ title={session.title}+ showPageMode={showPageMode}+ busy={showPageBusy}+ onToggle={onToggleShowPage}+ onPrepareLaunch={onPrepareShowPageLaunch}+ />{showPageActions.share && (<ShowPageShareControlsessionId={session.id}diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.test.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.test.tsxnew file mode 100644index 000000000..b5c0fafb8--- /dev/null+++ b/ui/src/components/workbench/ShowPageAnnotateControl.test.tsx@@ -0,0 +1,37 @@+import { createInstance } from 'i18next';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { describe, expect, it, vi } from 'vitest';++import en from '../../i18n/en.json';+import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++const renderCompact = (enabled: boolean) =>+ renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ShowPageAnnotateControl+ compact+ state={{ enabled, mode: 'smart', available: true }}+ onEnable={vi.fn()}+ onDisable={vi.fn()}+ onSetMode={vi.fn()}+ />+ </I18nextProvider>,+ );++describe('ShowPageAnnotateControl compact presentation', () => {+ it.each([false, true])('keeps one title-bar button when enabled=%s', (enabled) => {+ const html = renderCompact(enabled);++ expect(html.match(/<button/g)).toHaveLength(1);+ expect(html).toContain('aria-label="Annotate"');+ });+});diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.tsxindex bf660a701..eb8d0f98b 100644--- a/ui/src/components/workbench/ShowPageAnnotateControl.tsx+++ b/ui/src/components/workbench/ShowPageAnnotateControl.tsx@@ -55,11 +55,14 @@ interface ShowPageAnnotateControlProps {onDisable: () => void;onSetMode: (mode: AnnotationMode) => void;/**- * Mobile popover open/close. The popover floats over the Show Page iframe, so- * ChatPage makes the iframe inert while it is open (an outside tap inside the- * iframe never reaches us) — same pattern as the share control.+ * Popover open/close for mobile chat and compact window chrome. The owner+ * shields its iframe while open so an outside tap can dismiss the popover.*/onPopoverOpenChange?: (open: boolean) => void;+ /** Keep a single icon trigger at every viewport size (window title bars). */+ compact?: boolean;+ /** Associate portalled popover focus with its owning app window. */+ ownerWindowId?: string;}export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = ({@@ -68,6 +71,8 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (onDisable,onSetMode,onPopoverOpenChange,+ compact = false,+ ownerWindowId,}) => {const { t } = useTranslation();const ready = state !== null;@@ -121,9 +126,9 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (return (<Buttontype="button"- variant="outline"+ variant={compact ? 'ghost' : 'outline'}size="icon"- className="size-7 shrink-0"+ className={clsx(compact ? 'size-6 shrink-0 border-0 shadow-none' : 'size-7 shrink-0')}disabledaria-label={t('chat.showPage.annotate.unavailable')}title={t('chat.showPage.annotate.unavailable')}@@ -136,76 +141,84 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (return (<>{/* Desktop ≥ md: collapsed icon button ⇄ mint pill (toggle + segments). */}- <div className="hidden items-center md:flex">- {enabled ? (- <div className="flex h-7 items-center gap-0.5 rounded-lg border border-mint/40 bg-mint/[0.06] p-0.5 shadow-[0_0_16px_-6px_rgba(91,255,160,0.5)]">- <button+ {!compact && (+ <div className="hidden items-center md:flex">+ {enabled ? (+ <div className="flex h-7 items-center gap-0.5 rounded-lg border border-mint/40 bg-mint/[0.06] p-0.5 shadow-[0_0_16px_-6px_rgba(91,255,160,0.5)]">+ <button+ type="button"+ onClick={onDisable}+ aria-label={offLabel}+ title={offLabel}+ aria-pressed+ className="grid size-6 shrink-0 place-items-center rounded-[5px] bg-mint text-primary-foreground transition hover:brightness-110"+ >+ <MessageSquarePlus className="size-3.5" />+ </button>+ <div+ role="radiogroup"+ aria-label={t('chat.showPage.annotate.modeTitle')}+ className="flex items-center gap-0.5"+ >+ {MODES.map(({ id, icon: Icon, labelKey }) => {+ const active = mode === id;+ return (+ <button+ key={id}+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => onSetMode(id)}+ className={clsx(+ 'flex h-6 items-center gap-1 rounded-[5px] px-2 text-[12px] transition-colors',+ active+ ? 'bg-mint-soft font-bold text-mint'+ : 'font-medium text-muted hover:text-foreground',+ )}+ >+ <Icon className="size-3.5" />+ {t(labelKey)}+ </button>+ );+ })}+ </div>+ </div>+ ) : (+ <Buttontype="button"- onClick={onDisable}- aria-label={offLabel}- title={offLabel}- aria-pressed- className="grid size-6 shrink-0 place-items-center rounded-[5px] bg-mint text-primary-foreground transition hover:brightness-110"+ variant="outline"+ size="icon"+ className="size-7 shrink-0"+ onClick={() => onEnable()}+ aria-label={toggleLabel}+ title={toggleLabel}><MessageSquarePlus className="size-3.5" />- </button>- <div- role="radiogroup"- aria-label={t('chat.showPage.annotate.modeTitle')}- className="flex items-center gap-0.5"- >- {MODES.map(({ id, icon: Icon, labelKey }) => {- const active = mode === id;- return (- <button- key={id}- type="button"- role="radio"- aria-checked={active}- onClick={() => onSetMode(id)}- className={clsx(- 'flex h-6 items-center gap-1 rounded-[5px] px-2 text-[12px] transition-colors',- active ? 'bg-mint-soft font-bold text-mint' : 'font-medium text-muted hover:text-foreground',- )}- >- <Icon className="size-3.5" />- {t(labelKey)}- </button>- );- })}- </div>- </div>- ) : (- <Button- type="button"- variant="outline"- size="icon"- className="size-7 shrink-0"- onClick={() => onEnable()}- aria-label={toggleLabel}- title={toggleLabel}- >- <MessageSquarePlus className="size-3.5" />- </Button>- )}- </div>+ </Button>+ )}+ </div>+ )}- {/* Mobile < md: single button that enables + opens a mode-picker popover. */}- <div className="md:hidden">+ {/* Mobile and compact window chrome: one trigger + mode-picker popover. */}+ <div className={clsx(!compact && 'md:hidden')}><Popover open={popoverOpen} onOpenChange={handlePopoverOpenChange}><PopoverTrigger asChild><Buttontype="button"- variant={enabled ? 'default' : 'outline'}+ variant={enabled ? 'default' : compact ? 'ghost' : 'outline'}size="icon"- className="size-7 shrink-0"+ className={clsx(compact ? 'size-6 shrink-0 rounded-md' : 'size-7 shrink-0')}aria-label={toggleLabel}title={toggleLabel}><MessageSquarePlus className="size-3.5" /></Button></PopoverTrigger>- <PopoverContent align="end" className="w-64 p-1.5">+ <PopoverContent+ align="end"+ className="w-64 p-1.5"+ data-window-owner-id={ownerWindowId}+ ><div className="flex items-center justify-between px-2 pb-1.5 pt-1"><span className="text-[13px] font-medium text-foreground">{t('chat.showPage.annotate.modeTitle')}</span><span className="text-[11px] text-muted">{t('chat.showPage.annotate.rememberHint')}</span>diff --git a/ui/src/components/workbench/ShowPageAnnotationHost.tsx b/ui/src/components/workbench/ShowPageAnnotationHost.tsxnew file mode 100644index 000000000..6e4b87e93--- /dev/null+++ b/ui/src/components/workbench/ShowPageAnnotationHost.tsx@@ -0,0 +1,13 @@+import type { ReactNode } from 'react';++import { ShowPageAnnotationHostContext } from './ShowPageAnnotationHostContext';+import { useShowPageAnnotation } from './useShowPageAnnotation';++export const ShowPageAnnotationHost: React.FC<{ src: string | null; children: ReactNode }> = ({ src, children }) => {+ const annotation = useShowPageAnnotation(src);+ return (+ <ShowPageAnnotationHostContext.Provider value={{ src, annotation }}>+ {children}+ </ShowPageAnnotationHostContext.Provider>+ );+};diff --git a/ui/src/components/workbench/ShowPageAnnotationHostContext.ts b/ui/src/components/workbench/ShowPageAnnotationHostContext.tsnew file mode 100644index 000000000..44f07fc32--- /dev/null+++ b/ui/src/components/workbench/ShowPageAnnotationHostContext.ts@@ -0,0 +1,20 @@+import { createContext, useContext } from 'react';++import type { AnnotationBridge } from './useShowPageAnnotation';++export interface ShowPageAnnotationHostValue {+ src: string | null;+ annotation: AnnotationBridge;+}++export const ShowPageAnnotationHostContext = createContext<ShowPageAnnotationHostValue | null>(null);++export function useShowPageAnnotationHost(): ShowPageAnnotationHostValue | null {+ return useContext(ShowPageAnnotationHostContext);+}++export function useRequiredShowPageAnnotationHost(): ShowPageAnnotationHostValue {+ const host = useShowPageAnnotationHost();+ if (!host) throw new Error('Show Page annotation host is missing');+ return host;+}diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsxnew file mode 100644index 000000000..bb1ad0da4--- /dev/null+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx@@ -0,0 +1,334 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import {+ AppWindow,+ ChevronRight,+ ExternalLink,+ Loader2,+ MessageSquare,+ Presentation,+ SquareArrowOutUpRight,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { showPagePrivatePath } from '../../apps/showPageAvatar';+import { showDockId, useDock } from '../../context/DockContext';+import { useShowPageDrag } from '../../context/showPageDrag';+import { useWindowManager } from '../../context/WindowManagerContext';+import {+ isShowPageWindowDrop,+ SHOW_PAGE_DOCK_DROP_SELECTOR,+ showPageWindowOrigin,+ type ViewportPoint,+} from '../../lib/showPageLaunch';+import { Button } from '../ui/button';+import { Popover, PopoverAnchor, PopoverContent } from '../ui/popover';++interface ShowPageLaunchControlProps {+ sessionId: string;+ title: string | null;+ showPageMode: boolean;+ busy: boolean;+ onToggle: () => void;+ /** Ensure the page and send the first-build prompt without changing chat view. */+ onPrepareLaunch: (sessionId: string) => Promise<boolean>;+}++interface ActiveDrag {+ start: ViewportPoint;+}++const HOVER_OPEN_DELAY_MS = 180;+const HOVER_CLOSE_DELAY_MS = 160;++/** Visualize toggle plus hover launch menu and native drag-to-window behavior. */+export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({+ sessionId,+ title,+ showPageMode,+ busy,+ onToggle,+ onPrepareLaunch,+}) => {+ const { t } = useTranslation();+ const { openApp, setGestureActive } = useWindowManager();+ const dock = useDock();+ const { begin: beginShowPageDrag, end: endShowPageDrag } = useShowPageDrag();+ const [menuOpen, setMenuOpen] = useState(false);+ const [dragCue, setDragCue] = useState<ViewportPoint | null>(null);+ const dragRef = useRef<ActiveDrag | null>(null);+ const suppressClickRef = useRef(false);+ const hoverTimerRef = useRef<number | null>(null);+ const menuRef = useRef<HTMLDivElement | null>(null);++ const canLaunch = !showPageMode && !busy && Boolean(sessionId);+ const windowTitle = title?.trim() || t('chat.untitled');++ const clearHoverTimer = useCallback(() => {+ if (hoverTimerRef.current === null) return;+ window.clearTimeout(hoverTimerRef.current);+ hoverTimerRef.current = null;+ }, []);++ const openHoverMenu = useCallback(() => {+ if (!canLaunch || dragRef.current) return;+ clearHoverTimer();+ hoverTimerRef.current = window.setTimeout(() => {+ hoverTimerRef.current = null;+ setMenuOpen(true);+ }, HOVER_OPEN_DELAY_MS);+ }, [canLaunch, clearHoverTimer]);++ const closeHoverMenu = useCallback(() => {+ clearHoverTimer();+ hoverTimerRef.current = window.setTimeout(() => {+ hoverTimerRef.current = null;+ setMenuOpen(false);+ }, HOVER_CLOSE_DELAY_MS);+ }, [clearHoverTimer]);++ useEffect(+ () => () => {+ clearHoverTimer();+ if (dragRef.current) {+ endShowPageDrag();+ setGestureActive(false);+ }+ },+ [clearHoverTimer, endShowPageDrag, setGestureActive],+ );++ const prepare = useCallback(() => onPrepareLaunch(sessionId), [onPrepareLaunch, sessionId]);++ const openWindow = useCallback(+ async (point?: ViewportPoint) => {+ clearHoverTimer();+ setMenuOpen(false);+ if (!(await prepare())) return;+ openApp('showpage', {+ title: windowTitle,+ bounds: point ? showPageWindowOrigin(point) : undefined,+ params: { sessionId, title: windowTitle },+ });+ },+ [clearHoverTimer, openApp, prepare, sessionId, windowTitle],+ );++ const openLink = useCallback(async () => {+ clearHoverTimer();+ setMenuOpen(false);+ // 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');+ if (!tab) return;+ try {+ tab.opener = null;+ } catch {+ // Some browser WindowProxy implementations expose a read-only opener.+ }+ if (!(await prepare())) {+ tab.close();+ return;+ }+ if (!tab.closed) tab.location.replace(showPagePrivatePath(sessionId));+ }, [clearHoverTimer, prepare, sessionId]);++ const pinToDock = useCallback(async () => {+ if (!(await prepare())) return;+ const dockId = showDockId(sessionId);+ if (dock.isPinned(sessionId)) await dock.dock(dockId);+ else await dock.pin(sessionId);+ }, [dock, prepare, sessionId]);++ useEffect(() => {+ const onDragOver = (event: DragEvent) => {+ const active = dragRef.current;+ if (!active) return;+ const target = event.target instanceof Element ? event.target : null;+ if (target?.closest(SHOW_PAGE_DOCK_DROP_SELECTOR)) {+ setDragCue(null);+ return;+ }+ const point = { x: event.clientX, y: event.clientY };+ if (!isShowPageWindowDrop(active.start, point)) {+ setDragCue(null);+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'none';+ return;+ }+ event.preventDefault();+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';+ setDragCue(point);+ };++ const onDrop = (event: DragEvent) => {+ const active = dragRef.current;+ if (!active) return;+ const target = event.target instanceof Element ? event.target : null;+ if (target?.closest(SHOW_PAGE_DOCK_DROP_SELECTOR)) return;+ const point = { x: event.clientX, y: event.clientY };+ if (!isShowPageWindowDrop(active.start, point)) return;+ event.preventDefault();+ dragRef.current = null;+ setDragCue(null);+ endShowPageDrag();+ setGestureActive(false);+ void openWindow(point);+ };++ window.addEventListener('dragover', onDragOver);+ window.addEventListener('drop', onDrop);+ return () => {+ window.removeEventListener('dragover', onDragOver);+ window.removeEventListener('drop', onDrop);+ };+ }, [endShowPageDrag, openWindow, setGestureActive]);++ const endDrag = () => {+ dragRef.current = null;+ setDragCue(null);+ endShowPageDrag();+ setGestureActive(false);+ window.setTimeout(() => {+ suppressClickRef.current = false;+ }, 0);+ };++ const label = showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open');++ return (+ <>+ <Popover open={canLaunch && menuOpen} onOpenChange={(next) => !next && setMenuOpen(false)}>+ <PopoverAnchor asChild>+ <Button+ type="button"+ variant={showPageMode ? 'secondary' : 'ghost'}+ onClick={() => {+ clearHoverTimer();+ if (suppressClickRef.current) return;+ setMenuOpen(false);+ onToggle();+ }}+ onKeyDown={(event) => {+ if (!canLaunch || event.key !== 'ArrowDown') return;+ event.preventDefault();+ clearHoverTimer();+ setMenuOpen(true);+ window.requestAnimationFrame(() => {+ menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus();+ });+ }}+ onMouseEnter={openHoverMenu}+ onMouseLeave={closeHoverMenu}+ onFocus={openHoverMenu}+ onBlur={(event) => {+ clearHoverTimer();+ const next = event.relatedTarget;+ if (next instanceof Node && menuRef.current?.contains(next)) return;+ setMenuOpen(false);+ }}+ draggable={canLaunch}+ onDragStart={(event) => {+ if (!canLaunch || !window.matchMedia?.('(min-width: 768px)').matches) {+ event.preventDefault();+ return;+ }+ clearHoverTimer();+ setMenuOpen(false);+ suppressClickRef.current = true;+ dragRef.current = {+ start: { x: event.clientX, y: event.clientY },+ };+ event.dataTransfer.effectAllowed = 'copy';+ event.dataTransfer.setData('application/x-avibe-show-page', sessionId);+ // Reuse the window gesture shield so a drop over an app iframe+ // still reaches this document's dragover/drop listeners.+ setGestureActive(true);+ beginShowPageDrag(pinToDock);+ }}+ onDragEnd={endDrag}+ disabled={busy}+ aria-label={label}+ title={label}+ aria-haspopup={canLaunch ? 'menu' : undefined}+ aria-expanded={canLaunch ? menuOpen : undefined}+ className="h-7 shrink-0 gap-1.5 px-2"+ >+ {busy ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : showPageMode ? (+ <MessageSquare className="size-3.5" />+ ) : (+ <Presentation className="size-3.5" />+ )}+ <span className="hidden text-xs font-medium md:inline">{label}</span>+ </Button>+ </PopoverAnchor>+ <PopoverContent+ align="end"+ side="bottom"+ sideOffset={6}+ className="w-44 p-1"+ onMouseEnter={clearHoverTimer}+ onMouseLeave={closeHoverMenu}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ >+ <div+ ref={menuRef}+ role="menu"+ aria-label={t('chat.showPage.launchMenu')}+ onBlur={(event) => {+ const next = event.relatedTarget;+ if (next instanceof Node && event.currentTarget.contains(next)) return;+ clearHoverTimer();+ setMenuOpen(false);+ }}+ onKeyDown={(event) => {+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;+ const items = Array.from(+ event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'),+ );+ if (items.length === 0) return;+ event.preventDefault();+ const current = items.indexOf(document.activeElement as HTMLElement);+ if (event.key === 'Home') items[0]?.focus();+ else if (event.key === 'End') items.at(-1)?.focus();+ else if (event.key === 'ArrowDown') items[(current + 1) % items.length]?.focus();+ else items[(current - 1 + items.length) % items.length]?.focus();+ }}+ >+ <button+ type="button"+ role="menuitem"+ onClick={() => void openWindow()}+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] text-foreground transition-colors hover:bg-cyan-soft"+ >+ <AppWindow className="size-3.5 shrink-0 text-cyan" />+ <span className="flex-1">{t('chat.showPage.newWindow')}</span>+ <ChevronRight className="size-3.5 shrink-0 text-muted" />+ </button>+ <button+ type="button"+ role="menuitem"+ onClick={() => void openLink()}+ className="flex w-full items-center gap-2 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 className="flex-1">{t('chat.showPage.newLink')}</span>+ <ChevronRight className="size-3.5 shrink-0 text-muted" />+ </button>+ </div>+ </PopoverContent>+ </Popover>++ {dragCue && (+ <span+ aria-hidden+ style={{ left: dragCue.x + 14, top: dragCue.y + 14 }}+ className="pointer-events-none fixed z-[80] grid size-8 place-items-center rounded-md border border-cyan/60 bg-surface-3 text-cyan shadow-lg"+ >+ <SquareArrowOutUpRight className="size-4" />+ </span>+ )}+ </>+ );+};diff --git a/ui/src/components/workbench/useShowPageAnnotation.ts b/ui/src/components/workbench/useShowPageAnnotation.tsindex 80b5a0db5..3a2abb1dc 100644--- a/ui/src/components/workbench/useShowPageAnnotation.ts+++ b/ui/src/components/workbench/useShowPageAnnotation.ts@@ -21,7 +21,7 @@ export interface AnnotationBridge {/** Last state reported by the overlay; null until the first state message. */state: AnnotationState | null;/** Attach to the Show Page iframe so the bridge can target its window. */- iframeRef: React.RefObject<HTMLIFrameElement | null>;+ setIframe: React.RefCallback<HTMLIFrameElement>;/** Attach to the iframe `onLoad` to re-sync after a (re)load / re-point. */handleIframeLoad: () => void;/** `enable` without a mode uses the overlay's remembered mode (§3). */@@ -56,33 +56,57 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {setState(null);}- useEffect(() => {- const onMessage = (event: MessageEvent) => {- // Same-origin iframe only: ignore other origins, and other windows (the- // Show Page is same-origin and may talk to the parent for other reasons —- // match by both source window and message type).- if (event.origin !== window.location.origin) return;- const frame = iframeRef.current;- if (!frame || event.source !== frame.contentWindow) return;- const data = event.data as- | { type?: unknown; enabled?: unknown; mode?: unknown; available?: unknown }- | null;- if (!data || data.type !== 'avibe:annotation:state') return;- setState({- enabled: data.enabled === true,- mode: data.mode === 'screenshot' ? 'screenshot' : 'smart',- available: data.available === true,- });- };- window.addEventListener('message', onMessage);- return () => window.removeEventListener('message', onMessage);+ const onMessage = useCallback((event: MessageEvent) => {+ // Same-origin iframe only: ignore other origins, and other windows (the+ // Show Page is same-origin and may talk to the parent for other reasons —+ // match by both source window and message type).+ if (event.origin !== window.location.origin) return;+ const frame = iframeRef.current;+ if (!frame || event.source !== frame.contentWindow) return;+ const data = event.data as+ | { type?: unknown; enabled?: unknown; mode?: unknown; available?: unknown }+ | null;+ if (!data || data.type !== 'avibe:annotation:state') return;+ setState({+ enabled: data.enabled === true,+ mode: data.mode === 'screenshot' ? 'screenshot' : 'smart',+ available: data.available === true,+ });}, []);+ const listeningRef = useRef(false);+ const startListening = useCallback(() => {+ if (listeningRef.current) return;+ window.addEventListener('message', onMessage);+ listeningRef.current = true;+ }, [onMessage]);+ const stopListening = useCallback(() => {+ if (!listeningRef.current) return;+ window.removeEventListener('message', onMessage);+ listeningRef.current = false;+ }, [onMessage]);++ // Keep the listener alive even while `src` is null. A restored/cached iframe+ // can report during its commit, before passive effects run; the callback ref+ // below attaches synchronously before that frame can finish loading.+ useEffect(() => {+ startListening();+ return stopListening;+ }, [startListening, stopListening]);+const post = useCallback((message: ControlMessage) => {const win = iframeRef.current?.contentWindow;if (win) win.postMessage(message, window.location.origin);}, []);+ const setIframe = useCallback<React.RefCallback<HTMLIFrameElement>>(+ (iframe) => {+ iframeRef.current = iframe;+ if (iframe) startListening();+ },+ [startListening],+ );+const enable = useCallback((mode?: AnnotationMode) =>post(@@ -101,5 +125,5 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {// listener is already attached, so we also query as a backstop (§3).const handleIframeLoad = useCallback(() => post({ type: 'avibe:annotation:query' }), [post]);- return { state, iframeRef, handleIframeLoad, enable, disable, setMode };+ return { state, setIframe, handleIframeLoad, enable, disable, setMode };}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 84481e634..6545a0a2a 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -577,6 +577,7 @@ export type ApiContextType = {createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;forkSession: (sessionId: string) => Promise<WorkbenchSession>;getSession: (sessionId: string, params?: { cache?: boolean; handleError?: boolean }) => Promise<WorkbenchSession>;+ getSessionResult: (sessionId: string) => Promise<WorkbenchSessionReadResult>;getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;archiveSession: (sessionId: string) => Promise<WorkbenchSession>;@@ -782,6 +783,11 @@ export type WorkbenchSession = {metadata: Record<string, unknown>;};+export type WorkbenchSessionReadResult = {+ status: number;+ session: WorkbenchSession | null;+};+export type WorkbenchSessionCreate = {project_id: string;// Optional: when omitted the server resolves the current default Agent.@@ -2748,6 +2754,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenparams?.cache === false? getJson(`/api/sessions/${encodeURIComponent(sessionId)}`, { handleError: params?.handleError }): getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`, undefined, { handleError: params?.handleError }),+ getSessionResult: async (sessionId) => {+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`);+ const payload = await res.json().catch(() => null);+ return {+ status: res.status,+ session: res.ok && payload && typeof payload.id === 'string' ? payload : null,+ };+ },getSessionBootstrap: (sessionId) =>getJson(`/api/sessions/${encodeURIComponent(sessionId)}/bootstrap`),updateSession: async (sessionId, payload) => {diff --git a/ui/src/context/ShowPageDragProvider.tsx b/ui/src/context/ShowPageDragProvider.tsxnew file mode 100644index 000000000..c2530fc69--- /dev/null+++ b/ui/src/context/ShowPageDragProvider.tsx@@ -0,0 +1,29 @@+import { useCallback, useMemo, useRef, useState } from 'react';++import { ShowPageDragContext, type DockDropAction } from './showPageDrag';++/** Coordinates one native drag between the chat header and the sidebar Dock. */+export const ShowPageDragProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [active, setActive] = useState(false);+ const dockDropRef = useRef<DockDropAction | null>(null);++ const begin = useCallback((onDropToDock: DockDropAction) => {+ dockDropRef.current = onDropToDock;+ setActive(true);+ }, []);++ const end = useCallback(() => {+ dockDropRef.current = null;+ setActive(false);+ }, []);++ const dropToDock = useCallback(() => {+ const action = dockDropRef.current;+ dockDropRef.current = null;+ setActive(false);+ if (action) void action();+ }, []);++ const value = useMemo(() => ({ active, begin, end, dropToDock }), [active, begin, dropToDock, end]);+ return <ShowPageDragContext.Provider value={value}>{children}</ShowPageDragContext.Provider>;+};diff --git a/ui/src/context/showPageDrag.ts b/ui/src/context/showPageDrag.tsnew file mode 100644index 000000000..85d5c0d3f--- /dev/null+++ b/ui/src/context/showPageDrag.ts@@ -0,0 +1,18 @@+import { createContext, useContext } from 'react';++export type DockDropAction = () => void | Promise<void>;++export interface ShowPageDragValue {+ active: boolean;+ begin: (onDropToDock: DockDropAction) => void;+ end: () => void;+ dropToDock: () => void;+}++export const ShowPageDragContext = createContext<ShowPageDragValue | null>(null);++export function useShowPageDrag(): ShowPageDragValue {+ const context = useContext(ShowPageDragContext);+ if (!context) throw new Error('useShowPageDrag must be used within ShowPageDragProvider');+ return context;+}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 7bd3a814c..6fd962471 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2919,6 +2919,9 @@"showPage": {"open": "Visualize","backToChat": "Back to chat",+ "launchMenu": "Open Show Page",+ "newWindow": "New window",+ "newLink": "New link","annotate": {"toggle": "Annotate","smart": "Smart",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 2d60a3072..ac8abd7ea 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2919,6 +2919,9 @@"showPage": {"open": "可视化","backToChat": "回聊天",+ "launchMenu": "打开 Show Page",+ "newWindow": "新窗口",+ "newLink": "新链接","annotate": {"toggle": "标注","smart": "Smart",diff --git a/ui/src/lib/chatViewMemory.test.ts b/ui/src/lib/chatViewMemory.test.tsnew file mode 100644index 000000000..6163dc693--- /dev/null+++ b/ui/src/lib/chatViewMemory.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest';++import {+ MAX_REMEMBERED_SHOW_PAGE_SESSIONS,+ readChatViewMode,+ writeChatViewMode,+} from './chatViewMemory';++function memoryStorage(initial: string | null = null) {+ let value = initial;+ return {+ storage: {+ getItem: vi.fn(() => value),+ setItem: vi.fn((_key: string, next: string) => {+ value = next;+ }),+ },+ value: () => value,+ };+}++describe('chat view memory', () => {+ it('defaults each session to chat and remembers Show Page independently', () => {+ const memory = memoryStorage();++ expect(readChatViewMode('ses_a', memory.storage)).toBe('chat');+ writeChatViewMode('ses_a', 'show-page', memory.storage);++ expect(readChatViewMode('ses_a', memory.storage)).toBe('show-page');+ expect(readChatViewMode('ses_b', memory.storage)).toBe('chat');+ });++ it('switching back to chat clears only that session preference', () => {+ const memory = memoryStorage();+ writeChatViewMode('ses_a', 'show-page', memory.storage);+ writeChatViewMode('ses_b', 'show-page', memory.storage);+ writeChatViewMode('ses_a', 'chat', memory.storage);++ expect(readChatViewMode('ses_a', memory.storage)).toBe('chat');+ expect(readChatViewMode('ses_b', memory.storage)).toBe('show-page');+ });++ it('bounds and deduplicates remembered sessions', () => {+ const oversized = Array.from(+ { length: MAX_REMEMBERED_SHOW_PAGE_SESSIONS + 2 },+ (_, index) => `ses_${index}`,+ );+ const memory = memoryStorage(JSON.stringify([...oversized, oversized.at(-1)]));++ writeChatViewMode('ses_latest', 'show-page', memory.storage);++ const stored = JSON.parse(memory.value() ?? '[]') as string[];+ expect(stored).toHaveLength(MAX_REMEMBERED_SHOW_PAGE_SESSIONS);+ expect(stored.at(-1)).toBe('ses_latest');+ expect(new Set(stored).size).toBe(stored.length);+ });++ it('tolerates corrupt or unavailable storage', () => {+ const corrupt = memoryStorage('{not json');+ expect(readChatViewMode('ses_a', corrupt.storage)).toBe('chat');+ expect(() => writeChatViewMode('ses_a', 'show-page', corrupt.storage)).not.toThrow();+ expect(readChatViewMode('ses_a', corrupt.storage)).toBe('show-page');++ const blocked = {+ getItem: () => {+ throw new Error('blocked');+ },+ setItem: () => {+ throw new Error('blocked');+ },+ };+ expect(readChatViewMode('ses_a', blocked)).toBe('chat');+ expect(() => writeChatViewMode('ses_a', 'show-page', blocked)).not.toThrow();+ });+});diff --git a/ui/src/lib/chatViewMemory.ts b/ui/src/lib/chatViewMemory.tsnew file mode 100644index 000000000..554e91b7e--- /dev/null+++ b/ui/src/lib/chatViewMemory.ts@@ -0,0 +1,47 @@+export type ChatViewMode = 'chat' | 'show-page';++const STORAGE_KEY = 'avibe.chat.show-page-sessions.v1';+export const MAX_REMEMBERED_SHOW_PAGE_SESSIONS = 200;++type ChatViewStorage = Pick<Storage, 'getItem' | 'setItem'>;++function browserStorage(storage?: ChatViewStorage): ChatViewStorage | undefined {+ return storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);+}++function readShowPageSessions(storage?: ChatViewStorage): string[] {+ try {+ const raw = browserStorage(storage)?.getItem(STORAGE_KEY);+ if (!raw) return [];+ const parsed = JSON.parse(raw) as unknown;+ if (!Array.isArray(parsed)) return [];+ return Array.from(+ new Set(parsed.filter((value): value is string => typeof value === 'string' && value.length > 0)),+ ).slice(-MAX_REMEMBERED_SHOW_PAGE_SESSIONS);+ } catch {+ return [];+ }+}++export function readChatViewMode(sessionId: string, storage?: ChatViewStorage): ChatViewMode {+ if (!sessionId) return 'chat';+ return readShowPageSessions(storage).includes(sessionId) ? 'show-page' : 'chat';+}++export function writeChatViewMode(+ sessionId: string,+ mode: ChatViewMode,+ storage?: ChatViewStorage,+): void {+ if (!sessionId) return;+ try {+ const remembered = readShowPageSessions(storage).filter((id) => id !== sessionId);+ if (mode === 'show-page') remembered.push(sessionId);+ browserStorage(storage)?.setItem(+ STORAGE_KEY,+ JSON.stringify(remembered.slice(-MAX_REMEMBERED_SHOW_PAGE_SESSIONS)),+ );+ } catch {+ // View memory is best-effort in private browsing and restricted storage contexts.+ }+}diff --git a/ui/src/lib/showPageLaunch.test.ts b/ui/src/lib/showPageLaunch.test.tsnew file mode 100644index 000000000..89bf029d9--- /dev/null+++ b/ui/src/lib/showPageLaunch.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import {+ isShowPageWindowDrop,+ SHOW_PAGE_WINDOW_DRAG_THRESHOLD_PX,+ showPageWindowOrigin,+} from './showPageLaunch';++describe('isShowPageWindowDrop', () => {+ const start = { x: 500, y: 80 };++ it('requires a deliberate downward drag', () => {+ expect(+ isShowPageWindowDrop(start, {+ x: start.x,+ y: start.y + SHOW_PAGE_WINDOW_DRAG_THRESHOLD_PX,+ }),+ ).toBe(true);+ expect(+ isShowPageWindowDrop(start, {+ x: start.x + 300,+ y: start.y + SHOW_PAGE_WINDOW_DRAG_THRESHOLD_PX - 1,+ }),+ ).toBe(false);+ expect(isShowPageWindowDrop(start, { x: start.x, y: start.y - 100 })).toBe(false);+ });+});++describe('showPageWindowOrigin', () => {+ it('anchors the title bar near the pointer and keeps it on-screen', () => {+ expect(showPageWindowOrigin({ x: 420, y: 260 })).toEqual({ x: 384, y: 246 });+ expect(showPageWindowOrigin({ x: 4, y: 3 })).toEqual({ x: 8, y: 8 });+ });+});diff --git a/ui/src/lib/showPageLaunch.ts b/ui/src/lib/showPageLaunch.tsnew file mode 100644index 000000000..d1f2369a6--- /dev/null+++ b/ui/src/lib/showPageLaunch.ts@@ -0,0 +1,20 @@+export interface ViewportPoint {+ x: number;+ y: number;+}++export const SHOW_PAGE_WINDOW_DRAG_THRESHOLD_PX = 48;+export const SHOW_PAGE_DOCK_DROP_SELECTOR = '[data-show-page-dock-drop-target]';++/** A free drop opens a window only after a deliberate downward drag. */+export function isShowPageWindowDrop(start: ViewportPoint, current: ViewportPoint): boolean {+ return current.y - start.y >= SHOW_PAGE_WINDOW_DRAG_THRESHOLD_PX;+}++/** Put the new window's title bar just above and left of the release point. */+export function showPageWindowOrigin(point: ViewportPoint): ViewportPoint {+ return {+ x: Math.max(8, Math.round(point.x - 36)),+ y: Math.max(8, Math.round(point.y - 14)),+ };+}