Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(ui): Show Page annotation header control + iframe bridge (Lane C) (#949)

Call White3a1fa3481bd5
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index e29a488d2..6064a835d 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -29,6 +29,8 @@ import { quoteText } from '../../lib/quoteText';
import { mergeById, insertMessageOrdered } from '../../lib/transcriptOrder';
import { AgentRoutePicker } from './AgentRoutePicker';
import { ShowPageShareControl } from './ShowPageShareControl';
+import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';
+import { useShowPageAnnotation, type AnnotationBridge } from './useShowPageAnnotation';
import { SelectionQuoteToolbar } from './SelectionQuoteToolbar';
import { InstallHint } from '../InstallHint';
import { Button } from '../ui/button';
@@ -61,6 +63,15 @@ 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
@@ -173,6 +184,17 @@ export const ChatPage: React.FC = () => {
// document so the (non-modal) popover dismisses, without modal-blocking the
// sibling header buttons (which would then need two taps).
const [shareOpen, setShareOpen] = useState(false);
+ // True while the mobile annotation mode-picker popover is open. Like the share
+ // popover it floats over the iframe, so it also makes the iframe inert.
+ const [annotateOpen, setAnnotateOpen] = useState(false);
+ // postMessage bridge to the Show Page iframe: sends annotation control
+ // messages and derives the header control's state from the overlay's state
+ // broadcasts (contract §3). Keyed off showPageMode+showPageUrl (null while the
+ // iframe is hidden) so leaving Show Page mode resets state to unknown — else
+ // closing then reopening the SAME session's page (showPageUrl unchanged) would
+ // show the stale enabled/mode and could send control messages to the freshly
+ // remounted overlay before it rebroadcasts. Re-points reset via the URL change.
+ const annotation = useShowPageAnnotation(showPageMode ? 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.
@@ -1293,9 +1315,11 @@ export const ChatPage: React.FC = () => {
if (res?.ok) {
// Public pages are served under /p/<share_id>/; private under /show/<id>/.
setShowPageUrl(
- res.visibility === 'public' && res.share_id
- ? `/p/${encodeURIComponent(res.share_id)}/`
- : `/show/${encodeURIComponent(sid)}/`,
+ 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
@@ -1324,7 +1348,7 @@ export const ChatPage: React.FC = () => {
// so it never stays on a route that now 404s.
const handleShowPagePayload = useCallback((next: ShowPageLinkInfo) => {
const path = localPath(next);
- if (path) setShowPageUrl(path);
+ if (path) setShowPageUrl(embedShowPageSrc(path));
}, []);
// A quick-reply click sends the chosen label as a normal user turn, tagged with
@@ -1803,6 +1827,8 @@ export const ChatPage: React.FC = () => {
onToggleShowPage={toggleShowPage}
onShowPageVisibilityChange={handleShowPagePayload}
onShareOpenChange={setShareOpen}
+ annotation={annotation}
+ onAnnotateOpenChange={setAnnotateOpen}
/>
{showPageMode && showPageUrl && (
@@ -1820,11 +1846,16 @@ 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}
+ onLoad={annotation.handleIframeLoad}
title={t('chat.showPage.title')}
src={showPageUrl}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"
allow="clipboard-write"
- className={clsx('min-h-0 w-full flex-1 border-0 bg-background', shareOpen && 'pointer-events-none')}
+ className={clsx(
+ 'min-h-0 w-full flex-1 border-0 bg-background',
+ (shareOpen || annotateOpen) && 'pointer-events-none',
+ )}
/>
)}
@@ -2256,9 +2287,11 @@ interface ChatHeaderBarProps {
onToggleShowPage: () => void;
onShowPageVisibilityChange?: (payload: ShowPageLinkInfo) => void;
onShareOpenChange?: (open: boolean) => void;
+ annotation: AnnotationBridge;
+ onAnnotateOpenChange?: (open: boolean) => void;
}
-const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange }) => {
+const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange }) => {
const { t } = useTranslation();
const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;
// Backend locks once a NATIVE conversation exists — a native can only be
@@ -2343,9 +2376,20 @@ const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultA
the page + prompts the agent. It shows its label on desktop and stays
icon-only on mobile. In Show Page mode a Share control sits beside the
back-to-chat button. */}
- {/* Back-to-chat (or Visualize when in chat) stays leftmost; the Share
- control sits to its right, only while the Show Page is open. */}
+ {/* In Show Page mode the order is: annotation control · back-to-chat ·
+ Share. The annotation control sits immediately left of back-to-chat;
+ the Share control stays rightmost. In chat mode only the Visualize
+ toggle shows. */}
<div className="ml-auto flex items-center gap-1.5">
+ {showPageMode && (
+ <ShowPageAnnotateControl
+ state={annotation.state}
+ onEnable={annotation.enable}
+ onDisable={annotation.disable}
+ onSetMode={annotation.setMode}
+ onPopoverOpenChange={onAnnotateOpenChange}
+ />
+ )}
<Button
type="button"
variant={showPageMode ? 'secondary' : 'ghost'}
diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
new file mode 100644
index 000000000..bf660a701
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
@@ -0,0 +1,265 @@
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { Camera, Check, type LucideIcon, MessageSquarePlus, MousePointerClick, X } from 'lucide-react';
+
+import { Button } from '../ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
+import type { AnnotationMode, AnnotationState } from './useShowPageAnnotation';
+
+// Show Page annotation control rendered in the chat header (only in Show Page
+// mode, immediately left of the back-to-chat button). It is purely
+// presentational: state comes from the `useShowPageAnnotation` bridge and every
+// action is a callback into it.
+//
+// - Desktop ≥ md: a collapsed icon button that expands, once enabled, to a mint
+// pill (toggle square + Smart/截图 segments).
+// - Mobile < md: a single button that both enables (remembered mode) and opens
+// a mode-picker popover.
+//
+// The Smart/截图 segments use the design system's mint segmented tone (see
+// ui/segmented.tsx) but are composed inline: the header needs a compact h-7,
+// per-segment icons, and the segments embedded in a single mint-glow pill
+// alongside a separate toggle square — a genuinely different visual unit than
+// the standalone SegmentedRadio primitive.
+
+interface ModeDef {
+ id: AnnotationMode;
+ icon: LucideIcon;
+ labelKey: string;
+ descKey: string;
+}
+
+const MODES: readonly ModeDef[] = [
+ {
+ id: 'smart',
+ // mouse-pointer-click (matches design.pen + Lane R overlay). Sparkles is
+ // reserved for AI-generate affordances elsewhere in the workbench.
+ icon: MousePointerClick,
+ labelKey: 'chat.showPage.annotate.smart',
+ descKey: 'chat.showPage.annotate.smartDesc',
+ },
+ {
+ id: 'screenshot',
+ icon: Camera,
+ labelKey: 'chat.showPage.annotate.screenshot',
+ descKey: 'chat.showPage.annotate.screenshotDesc',
+ },
+] as const;
+
+interface ShowPageAnnotateControlProps {
+ /** Overlay state from the bridge; null until the first state message. */
+ state: AnnotationState | null;
+ /** Enable with the remembered mode (no explicit mode). */
+ onEnable: () => void;
+ 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.
+ */
+ onPopoverOpenChange?: (open: boolean) => void;
+}
+
+export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = ({
+ state,
+ onEnable,
+ onDisable,
+ onSetMode,
+ onPopoverOpenChange,
+}) => {
+ const { t } = useTranslation();
+ const ready = state !== null;
+ const available = state?.available === true;
+ const enabled = state?.enabled === true;
+ const mode: AnnotationMode = state?.mode ?? 'smart';
+ // Until the overlay reports, or when writes aren't possible, the control is a
+ // disabled collapsed button with an explanatory tooltip.
+ const locked = !ready || !available;
+
+ const [popoverOpen, setPopoverOpen] = useState(false);
+ // If we unmount while open (leaving Show Page mode), Radix won't fire
+ // onOpenChange(false), so report closed here — otherwise ChatPage keeps the
+ // next Show Page's iframe inert.
+ useEffect(() => () => onPopoverOpenChange?.(false), [onPopoverOpenChange]);
+
+ // A state reset or `available=false` transition (iframe re-point, overlay
+ // reporting writes unavailable) swaps the picker subtree for the locked
+ // button below WITHOUT a Radix-driven close, so Radix never fires
+ // onOpenChange(false) and the unmount-only cleanup above doesn't run. Force
+ // the picker shut so ChatPage clears the iframe-inert flag and the Show Page
+ // stays clickable: reset our own flag during render (React's adjust-on-input
+ // pattern) and notify the parent from an effect (can't setState the parent
+ // during our render).
+ if (locked && popoverOpen) setPopoverOpen(false);
+ useEffect(() => {
+ if (locked) onPopoverOpenChange?.(false);
+ }, [locked, onPopoverOpenChange]);
+
+ const handlePopoverOpenChange = (next: boolean) => {
+ setPopoverOpen(next);
+ onPopoverOpenChange?.(next);
+ // Opening while off enables with the remembered mode — matches the design:
+ // "tapping enables (last mode) and pops up the picker". Re-opening while on
+ // never re-enables (or disables); "关闭标注" is the only off switch.
+ if (next && !enabled) onEnable();
+ };
+
+ const closeFromPopover = () => {
+ onDisable();
+ setPopoverOpen(false);
+ onPopoverOpenChange?.(false);
+ };
+
+ const toggleLabel = t('chat.showPage.annotate.toggle');
+ // The enabled desktop toggle square turns annotation OFF — label it as such
+ // (icon-only, so the tooltip/screen-reader name must describe the action).
+ const offLabel = t('chat.showPage.annotate.closeAnnotation');
+
+ if (locked) {
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="size-7 shrink-0"
+ disabled
+ aria-label={t('chat.showPage.annotate.unavailable')}
+ title={t('chat.showPage.annotate.unavailable')}
+ >
+ <MessageSquarePlus className="size-3.5" />
+ </Button>
+ );
+ }
+
+ 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
+ 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>
+ ) : (
+ <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>
+
+ {/* Mobile < md: single button that enables + opens a mode-picker popover. */}
+ <div className="md:hidden">
+ <Popover open={popoverOpen} onOpenChange={handlePopoverOpenChange}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant={enabled ? 'default' : 'outline'}
+ size="icon"
+ className="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">
+ <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>
+ </div>
+ <div role="radiogroup" aria-label={t('chat.showPage.annotate.modeTitle')}>
+ {MODES.map(({ id, icon: Icon, labelKey, descKey }) => {
+ const active = enabled && mode === id;
+ return (
+ <button
+ key={id}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ onClick={() => onSetMode(id)}
+ className="flex w-full items-center gap-2.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-surface-2"
+ >
+ <span
+ className={clsx(
+ 'grid size-8 shrink-0 place-items-center rounded-md',
+ active ? 'bg-mint-soft text-mint' : 'bg-foreground/[0.04] text-muted',
+ )}
+ >
+ <Icon className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span
+ className={clsx(
+ 'block text-[13px]',
+ active ? 'font-bold text-mint' : 'font-medium text-foreground',
+ )}
+ >
+ {t(labelKey)}
+ </span>
+ <span className="block text-[11px] text-muted">{t(descKey)}</span>
+ </span>
+ {active && <Check className="size-4 shrink-0 text-mint" />}
+ </button>
+ );
+ })}
+ </div>
+ <div className="my-1 border-t border-border" />
+ <button
+ type="button"
+ onClick={closeFromPopover}
+ className="flex w-full items-center gap-2.5 rounded-md px-2 py-2 text-left text-[13px] text-muted transition-colors hover:bg-surface-2 hover:text-foreground"
+ >
+ <span className="grid size-8 shrink-0 place-items-center">
+ <X className="size-4" />
+ </span>
+ {t('chat.showPage.annotate.closeAnnotation')}
+ </button>
+ </PopoverContent>
+ </Popover>
+ </div>
+ </>
+ );
+};
diff --git a/ui/src/components/workbench/useShowPageAnnotation.ts b/ui/src/components/workbench/useShowPageAnnotation.ts
new file mode 100644
index 000000000..80b5a0db5
--- /dev/null
+++ b/ui/src/components/workbench/useShowPageAnnotation.ts
@@ -0,0 +1,105 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+// postMessage bridge between the chat host and the annotation overlay running
+// inside the chat's Show Page iframe (plan show-page-annotation-phase1 §3).
+//
+// This hook is owned by ChatPage, where the iframe lives. It sends control
+// messages into the iframe and derives its `state` PURELY from the
+// `avibe:annotation:state` messages the overlay broadcasts — the header control
+// never optimistically flips itself, so it can't drift from the real overlay.
+
+export type AnnotationMode = 'smart' | 'screenshot';
+
+export interface AnnotationState {
+ enabled: boolean;
+ mode: AnnotationMode;
+ /** False = overlay mounted but writes impossible (anonymous public visitor). */
+ available: boolean;
+}
+
+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>;
+ /** 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). */
+ enable: (mode?: AnnotationMode) => void;
+ disable: () => void;
+ setMode: (mode: AnnotationMode) => void;
+}
+
+type ControlMessage =
+ | { type: 'avibe:annotation:control'; action: 'enable' | 'disable'; mode?: AnnotationMode }
+ | { type: 'avibe:annotation:control'; action: 'set-mode'; mode: AnnotationMode }
+ | { type: 'avibe:annotation:query' };
+
+/**
+ * `src` is the current iframe URL; changing it (first open, or a private↔public
+ * re-point, or a session switch that clears it) drops the derived state back to
+ * "unknown" so the control disables until the freshly loaded overlay reports —
+ * and so one session's state never briefly shows over another's page.
+ */
+export function useShowPageAnnotation(src: string | null): AnnotationBridge {
+ const iframeRef = useRef<HTMLIFrameElement | null>(null);
+ const [state, setState] = useState<AnnotationState | null>(null);
+ const [lastSrc, setLastSrc] = useState(src);
+
+ // The loaded page changed — the new overlay hasn't reported yet, so drop back
+ // to "unknown" until it does (and so one session's state never briefly shows
+ // over another's page). Adjusting state during render is React's recommended
+ // alternative to a reset-on-input effect (it re-renders before committing,
+ // with no extra paint). https://react.dev/reference/react/useState
+ if (src !== lastSrc) {
+ setLastSrc(src);
+ 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 post = useCallback((message: ControlMessage) => {
+ const win = iframeRef.current?.contentWindow;
+ if (win) win.postMessage(message, window.location.origin);
+ }, []);
+
+ const enable = useCallback(
+ (mode?: AnnotationMode) =>
+ post(
+ mode
+ ? { type: 'avibe:annotation:control', action: 'enable', mode }
+ : { type: 'avibe:annotation:control', action: 'enable' },
+ ),
+ [post],
+ );
+ const disable = useCallback(() => post({ type: 'avibe:annotation:control', action: 'disable' }), [post]);
+ const setMode = useCallback(
+ (mode: AnnotationMode) => post({ type: 'avibe:annotation:control', action: 'set-mode', mode }),
+ [post],
+ );
+ // On (re)load the overlay broadcasts its state on mount, but the parent
+ // 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 };
+}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index f9be93c45..03522df3b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2253,6 +2253,17 @@
"showPage": {
"open": "Visualize",
"backToChat": "Back to chat",
+ "annotate": {
+ "toggle": "Annotate",
+ "smart": "Smart",
+ "screenshot": "Screenshot",
+ "smartDesc": "Click elements · select text · box a region",
+ "screenshotDesc": "Box a region · numbered comments",
+ "closeAnnotation": "Turn off annotation",
+ "modeTitle": "Annotation mode",
+ "rememberHint": "Remembers last choice",
+ "unavailable": "Annotation not available yet"
+ },
"title": "Show Page",
"prompt": "Please visualize this session as a Show Page.",
"share": "Share",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 9ddfba549..1e7455094 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2253,6 +2253,17 @@
"showPage": {
"open": "可视化",
"backToChat": "回聊天",
+ "annotate": {
+ "toggle": "标注",
+ "smart": "Smart",
+ "screenshot": "截图",
+ "smartDesc": "点选元素 · 选文字 · 框选区域",
+ "screenshotDesc": "框选区域 · 多条编号评论",
+ "closeAnnotation": "关闭标注",
+ "modeTitle": "标注模式",
+ "rememberHint": "记住上次选择",
+ "unavailable": "标注暂不可用"
+ },
"title": "Show Page",
"prompt": "Please visualize this session as a Show Page.",
"share": "分享",