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
chore(merge): sync org into show page access
Max8efecbb6025e
diff --cc ui/src/components/workbench/ChatPage.tsxindex 8d786a57c,fe0c32cc1..090d27d38--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@@ -10,18 -11,25 +11,29 @@@ import { useToast } from '../../contextimport { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';+ import { useWindowManager } from '../../context/WindowManagerContext';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 { isNotifyMessageType, isTerminalAgentMessage } from '../../lib/chatMessageTypes';+ import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';+ import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessageTypes';+ import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';+ import { isVaultApprovalRequest, placeVaultProvisionRequests } from '../../lib/vaultRequestPlacement';import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';+import {+ showPageHeaderAccess,+ type ShowPageAccess,+} from '../../lib/showPageAccess';+ import { showPageEmbeddedPath } from '../../apps/showPageAvatar';+ import { downloadFile, fileMeta } from '../../lib/filesApi';+ import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/filePreview';+ import { recentPathLabel } from '../../lib/editorRecents';+ import type { LocalFileLinkTarget } from '../../lib/localFileLinks';import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';+ import { resultFooterParts } from '../../lib/resultFooter';import {activityItemKind,activityKindI18nKey,@@@ -160,19 -193,7 +197,21 @@@ export const ChatPage: React.FC = () =const { capabilities } = useInstanceAuthorization();const [sessionCanChat, setSessionCanChat] = useState(false);const canChat = capabilities.can_chat && sessionCanChat;- const canManageShowPage = capabilities.can_manage_instance;+ const [showPageAccessResult, setShowPageAccessResult] = useState<{+ sessionId: string;+ access: ShowPageAccess | null;+ } | null>(null);+ const showPageAccessProbeGenerationRef = useRef(0);+ const showPageAccess = capabilities.can_use_show_pages+ && showPageAccessResult?.sessionId === sessionId+ ? showPageAccessResult?.access ?? null+ : null;++ const showPageAccessResolved = capabilities.can_manage_instance++ || showPageAccessResult?.sessionId === sessionId;+ const { canOpen: canOpenShowPage, canManage: canManageShowPage } = showPageHeaderAccess(+ capabilities.can_manage_instance,+ showPageAccess,+ );const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox();// The mobile chat surface is a fixed full-screen flex column; this keeps the// composer glued to the iOS keyboard (settle-then-correct; see the hook).@@@ -217,33 -284,28 +302,46 @@@// 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);+ const annotation = useShowPageAnnotation(showPageActive ? showPageUrl : null);+ const probeShowPageAccess = useCallback(async (targetSessionId: string) => {+ const generation = ++showPageAccessProbeGenerationRef.current;+ try {+ const nextAccess = await api.probeShowPageAccess(targetSessionId);+ if (generation !== showPageAccessProbeGenerationRef.current) return;+ setShowPageAccessResult({ sessionId: targetSessionId, access: nextAccess });+ } catch {+ if (generation !== showPageAccessProbeGenerationRef.current) return;+ setShowPageAccessResult({ sessionId: targetSessionId, access: null });+ }+ }, [api]);+ useEffect(() => {+ if (!sessionId || !capabilities.can_use_show_pages) return undefined;+ void probeShowPageAccess(sessionId);+ return () => {+ showPageAccessProbeGenerationRef.current += 1;+ };+ }, [capabilities.can_use_show_pages, probeShowPageAccess, sessionId]);-+ // The mounted Show Page frame, so parent-level chords can also be bound inside+ // its document (see the ⌘⇧D effect). Stable callback + ref, never state: a ref+ // callback that set state would re-create itself on every commit and re-attach+ // forever. Effects run after refs are attached, so the frame is here in time.+ const showPageFrameRef = useRef<HTMLIFrameElement | null>(null);+ const annotationSetIframe = annotation.setIframe;+ const setShowPageIframe = useCallback<React.RefCallback<HTMLIFrameElement>>(+ (node) => {+ showPageFrameRef.current = node;+ annotationSetIframe(node);+ },+ [annotationSetIframe],+ );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@@@ -1362,53 -1514,96 +1553,105 @@@[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> => {- if (!canManageShowPage || readOnly) return false;++ if (!canOpenShowPage || readOnly) return false;+ 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);+ }+ }+ },- [canManageShowPage, readOnly, api, sendMessage, t],++ [canOpenShowPage, 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;}- if (!canOpenShowPage) 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.- if (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) {++ showPageRestoreAttemptRef.current = sid;++ writeChatViewMode(sid, 'chat');++ return;+ }- }, [sessionId, showPageMode, canOpenShowPage, api, sendMessage, t]);++ if (showChatSignal || deepLinkMessageId || readChatViewMode(sid) !== 'show-page') {++ showPageRestoreAttemptRef.current = sid;++ return;++ }++ if (!showPageAccessResolved) return;++ showPageRestoreAttemptRef.current = sid;++ if (!canOpenShowPage) {+ writeChatViewMode(sid, 'chat');+ return;+ }- if (showChatSignal || deepLinkMessageId || readChatViewMode(sid) !== 'show-page') return;+ void openShowPage(sid);- }, [deepLinkMessageId, openShowPage, readOnly, session?.id, sessionId, showChatSignal]);++ }, [canOpenShowPage, deepLinkMessageId, openShowPage, readOnly, session?.id, sessionId, showChatSignal, showPageAccessResolved]);// When the share control resolves the page (open) or flips its visibility, the// serving route changes (private → /show/, public → /p/). Re-point the iframe@@@ -1896,13 -2163,14 +2211,16 @@@onShareOpenChange={setShareOpen}annotation={annotation}onAnnotateOpenChange={setAnnotateOpen}- readOnly={!canChat}+ readOnlyReason={readOnlyReason}+ writable={writable}+ showPageAccess={showPageAccess}+ canOpenShowPage={canOpenShowPage}canManageShowPage={canManageShowPage}+ sessionActions={sessionActions}+ titleFieldRef={titleFieldRef}/>- {showPageMode && showPageUrl && (+ {showPageActive && showPageUrl && (// The session's Show Page (same-origin /show/<id>/ private or /p/<share>/// public; URL resolved from ensureShowPage) fills the chat area while the// header bar stays. The chat surface below is kept mounted but hidden.@@@ -1975,9 -2246,15 +2296,15 @@@onToggleTools: toggleToolCalls,}}footer={- sessionId && capabilities.can_manage_instance ? (+ // Archive expires every pending vault request for the session in the+ // same transaction that flips the status, so these cards are already+ // empty for a freshly-loaded archived chat. A tab that loaded them+ // BEFORE the archive still holds them in state, though — the same+ // stale-tab case that reaches the archived 409 — and their+ // approve/deny buttons would write to a session that can't accept it.- sessionId && !readOnly && canManageShowPage ? (++ sessionId && !readOnly && capabilities.can_manage_instance ? (<VaultChatRequests- requests={vaultRequests}+ requests={transcriptTailVaultRequests}onResolved={refreshVaultRequests}onOffscreenApprovalsChange={setOffscreenApprovals}/>@@@ -1989,10 -2266,14 +2316,14 @@@sessionId={sessionId ?? ''}enabled={bannerEnabled === true}/>- {canChat && (+ {/* Archive reclaims all unsent input (queued rows, pending rows, draft),+ so an archived chat loads with an empty queue. A stale tab can still be+ holding pre-archive rows, and every button here writes: Send now POSTs+ the flush, Recall appends into the disabled composer. */}+ {writable && (<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />)}- {sessionId && capabilities.can_manage_instance && pendingApprovals.length > 0 ? (- {sessionId && !readOnly && canManageShowPage && pendingApprovals.length > 0 ? (++ {sessionId && !readOnly && capabilities.can_manage_instance && pendingApprovals.length > 0 ? (<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />) : null}{/* key by session so the composer remounts per session — its draft-seeding@@@ -2377,15 -2740,37 +2790,43 @@@ interface ChatHeaderBarPropsonShareOpenChange?: (open: boolean) => void;annotation: AnnotationBridge;onAnnotateOpenChange?: (open: boolean) => void;- readOnly: boolean;- showPageAccess: ShowPageAccess | null;- canOpenShowPage: boolean;- canManageShowPage: boolean;+ // Read-only session: the title and the agent route render as static text — the+ // server refuses both edits (409 archived / 403 reserved) — and the Show Page action+ // cluster is withdrawn entirely (see showPageControlActions). The REASON, not a+ // boolean, because it also picks the badge: a runtime-owned row is not "Archived".+ readOnlyReason: SessionReadOnlyReason | null;+ writable?: boolean;++ showPageAccess?: ShowPageAccess | null;++ canOpenShowPage?: boolean;+ canManageShowPage?: boolean;+ // Shared session actions, rendered behind the mobile-only ⋯ at the far right.+ // Empty (or absent) withdraws the trigger — which is what a read-only session+ // yields, since every one of those writes is refused.+ sessionActions?: SessionActionDescriptor[];+ // Lets the menu's Rename row focus the title field that already lives here.+ titleFieldRef?: React.Ref<TitleFieldHandle>;}- const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnly, showPageAccess, canOpenShowPage, canManageShowPage }) => {+ // Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),+ // 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, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, canManageShowPage = true, sessionActions, titleFieldRef }) => {++export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, showPageAccess = null, canOpenShowPage = true, canManageShowPage = true, sessionActions, titleFieldRef }) => {const { t } = useTranslation();+ const readOnly = !writable;+ const sessionReadOnly = readOnlyReason !== null;+ const showPageActions = showPageControlActions(sessionReadOnly, showPageMode);++ const showLaunchControl = showPageActions.visualize && (showPageMode || canOpenShowPage);++ const showShareControl = !sessionReadOnly++ && canManageShowPage++ && (showPageMode || showPageAccess !== null);+ // ``!readOnly`` twice over: useSessionActions already yields an empty list for a+ // read-only session, and the withdrawal is re-stated here so this header cannot+ // grow a ⋯ full of guaranteed-409 rows if a future caller passes actions anyway.+ const mobileSessionActions = sessionActions ?? [];+ const hasMobileSessionActions = writable && mobileSessionActions.length > 0;const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;+ const sessionAgentLabel = sessionAgentDisplayName(session, agents);// Backend locks once a NATIVE conversation exists — a native can only be// resumed by the backend that created it — or while a turn is RUNNING (the// in-flight turn binds its native on the current route any moment); mirrors@@@ -2468,50 -2878,55 +2934,49 @@@the page + prompts the agent. It shows its label on desktop and staysicon-only on mobile. In Show Page mode a Share control sits beside theback-to-chat button. */}-- {/* 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 resource managers can- open Share without receiving access to the page content. */}- {(showPageMode || canOpenShowPage || canManageShowPage) && <div className="ml-auto flex items-center gap-1.5">- {showPageMode && !readOnly && (- <ShowPageAnnotateControl- state={annotation.state}- onEnable={annotation.enable}- onDisable={annotation.disable}- onSetMode={annotation.setMode}- onPopoverOpenChange={onAnnotateOpenChange}- />- )}- {(showPageMode || canOpenShowPage) && <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" />- the Share control stays rightmost. In chat mode only the Visualize- toggle shows.-- The whole cluster is withdrawn on an archived session — archive takes- its Show Page offline and refuses to create a missing one, so none of- the three can do anything but 409 or frame a dead page. There is no- read-only page-serving path to offer instead; see- showPageControlActions for the per-control reasoning. */}- {((showPageActions.visualize && (showPageMode || canManageShowPage)) || hasMobileSessionActions) && (++ {/* In Show Page mode the order is: annotation control, launch/back, Share.++ Access-only managers can open Share from chat without receiving page use. */}++ {(showLaunchControl || showShareControl || hasMobileSessionActions) && (+ <div className="ml-auto flex items-center gap-1.5">+ {showPageActions.annotate && writable && (+ <ShowPageAnnotateControl+ state={annotation.state}+ onEnable={annotation.enable}+ onDisable={annotation.disable}+ onSetMode={annotation.setMode}+ onPopoverOpenChange={onAnnotateOpenChange}+ />)}- <span className="hidden text-xs font-medium md:inline">- {showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}- </span>- </Button>}- {canManageShowPage && (showPageMode || showPageAccess) && (- <ShowPageShareControl- key={session.id}- sessionId={session.id}- initialAccess={showPageAccess}- onPayloadChange={onShowPageVisibilityChange}- onOpenChange={onShareOpenChange}- />- )}- </div>}- {showPageActions.visualize && (showPageMode || canManageShowPage) && (++ {showLaunchControl && (+ <ShowPageLaunchControl+ sessionId={session.id}+ title={session.title}+ showPageMode={showPageMode}+ busy={showPageBusy}+ onToggle={onToggleShowPage}+ onPrepareLaunch={onPrepareShowPageLaunch}+ />+ )}- {showPageActions.share && canManageShowPage && (++ {showShareControl && (+ <ShowPageShareControl++ key={session.id}+ sessionId={session.id}++ initialAccess={showPageAccess}+ onPayloadChange={onShowPageVisibilityChange}+ onOpenChange={onShareOpenChange}+ />+ )}+ {/* The chat-level session menu is a compact-mobile affordance. Desktop+ keeps these operations in the sidebar instead of duplicating a- second ⋯ in the page header. */}++ second menu in the page header. */}+ {hasMobileSessionActions && (+ <MobileChatSessionActionMenu+ actions={mobileSessionActions}+ label={t('workbench.sessionActions')}+ />+ )}+ </div>+ )}</div></div>);diff --cc ui/src/components/workbench/ShowPageShareControl.tsxindex 473b11758,a0a55c613..c43df7aed--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@@ -5,9 -5,11 +5,10 @@@ import { Check, Copy, LayoutGrid, Loadeimport { Button } from '../ui/button';import { Input } from '../ui/input';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';-import { Select } from '../ui/select';import { Switch } from '../ui/switch';import { useApi } from '../../context/ApiContext';- import { showDockId, useDock } from '../../context/DockContext';+ import { useDock } from '../../context/DockContext';+ import { showDockId } from '../../context/dockDoc';import { copyTextToClipboard } from '../../lib/utils';import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';diff --cc ui/src/context/ApiContext.tsxindex 06138609f,d05e36d6f..79c1e6037--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@@ -6,17 -6,16 +6,18 @@@ import { isAuthorizationSensitiveReadPaimport type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';+ import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';+import type { ShowPageAccess } from '../lib/showPageAccess';import {WorkbenchEventReconnectLoop,type WorkbenchEventConnectionState,} from '../lib/workbenchEventConnection';- import type { DockDoc } from './DockContext';- import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';+ import type { DockDoc } from './dockDoc';+ import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';export type { InstanceCapabilities, SessionInfo };+export type { ShowPageAccess };// The workbench Dock API response shape ({ ok, dock }); the Dock document type// itself lives with the DockProvider that owns reconciliation.diff --cc vibe/authorization.pyindex 14534abdb,678a06069..7c314f0be--- a/vibe/authorization.py+++ b/vibe/authorization.py@@@ -318,6 -340,184 +351,189 @@@ _EDITOR_HTTP_RULES = tuple))+ _REMOTE_LOCAL_ONLY_HTTP_RULES = tuple(+ (method, re.compile(pattern))+ for method, pattern in (+ ("DELETE", r"^/api/sessions/[^/]+(?:/queue/[^/]+)?$"),+ ("POST", r"^/api/sessions/[^/]+/fork$"),+ (+ "POST",+ r"^/api/sessions/[^/]+/(?:messages|attachments|cancel|queue/[^/]+/send-now)$",+ ),+ ("POST", r"^/api/asr/transcribe$"),+ ("POST", r"^/api/show/sessions/[^/]+/(?:events|prewarm)$"),+ ("GET", r"^/api/settings$"),+ ("HEAD", r"^/api/settings$"),+ ("POST", r"^/api/settings$"),+ ("POST", r"^/api/settings/thread$"),+ ("DELETE", r"^/api/settings/thread$"),+ ("GET", r"^/api/bind-codes$"),+ ("DELETE", r"^/api/projects/[^/]+$"),+ )+ )++ _REMOTE_PAYLOAD_FILTERED_HTTP_RULES = tuple(+ (method, re.compile(pattern))+ for method, pattern in (+ (+ "POST",+ r"^/api/(?:config|projects|sessions)$",+ ),+ ("PATCH", r"^/api/(?:projects|sessions)/[^/]+$"),+ )+ )++ # Positive allowlist for remote-safe owner surfaces. Any route that mutates+ # local Agent, IM, Vault, or other execution state must stay absent here and+ # therefore use the fail-closed local-only default below.+ _REMOTE_OWNER_ALLOWED_HTTP_RULES = tuple(+ (methods, re.compile(pattern))+ for methods, pattern in (+ (frozenset({"GET", "HEAD", "POST"}), r"^/api/agent-onboarding$"),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/agents/[^/]+$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/vault/(?:pubkey|agent/pubkey|sandbox/root-metadata|settings|vmk|requests|requests/[^/]+|provision-requests/[^/]+|provision-requests/by-id/[^/]+|grants|audit)$",+ ),+ (+ frozenset({"POST"}),+ r"^/api/show-pages/[^/]+/(?:ensure|rotate-share|share-id|visibility)$",+ ),+ (frozenset({"GET", "HEAD"}), r"^/api/dock$"),+ (frozenset({"POST"}), r"^/api/dock/pins$"),+ (frozenset({"DELETE"}), r"^/api/dock/pins/[^/]+$"),+ (frozenset({"PUT"}), r"^/api/dock/order$"),+ (frozenset({"PUT"}), r"^/api/workbench/prefs$"),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/web-push/(?:status|vapid-public-key)$",+ ),+ (+ frozenset({"POST"}),+ r"^/api/web-push/(?:status|subscriptions|test)$",+ ),+ (frozenset({"DELETE"}), r"^/api/web-push/subscriptions$"),+ (+ frozenset({"PUT"}),+ r"^/api/resource-policies/[^/]+/[^/]+$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/(?:projects/[^/]+/agents-md|global-prompts)$",+ ),+ (frozenset({"GET", "HEAD"}), r"^/api/skills/(?:check|find)$"),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/models/(?:sources|agents|events|runtime/status)$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/models/agents/[^/]+/(?:sources|chain)$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/models/(?:turns/[^/]+/provenance|oauth/status/[^/]+)$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/backend/(?:[^/]+/runtime|(?:claude|codex)/auth|[^/]+/auth/oauth/status/[^/]+)$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/(?:opencode/permission-status|remote-access/status)$",+ ),+ (+ frozenset({"GET", "HEAD"}),+ r"^/api/harness/(?:counts|tasks|watches|runs|bootstrap|runs/[^/]+)$",+ ),+ (frozenset({"GET", "HEAD"}), r"^/api/users$"),+ )+ )+++ def _http_rule_matches(+ method: str,+ path: str,+ rules: tuple[tuple[str, re.Pattern[str]], ...],+ ) -> bool:+ return any(rule_method == method and pattern.fullmatch(path) for rule_method, pattern in rules)+++ def _owner_http_rule_matches(method: str, path: str) -> bool:+ return any(+ method in methods and pattern.fullmatch(path)+ for methods, pattern in _REMOTE_OWNER_ALLOWED_HTTP_RULES+ )+++ def http_authorization_policy(method: str, path: str) -> HttpAuthorizationPolicy:+ """Return role and remote-exposure policy for one HTTP request.++ Explicit viewer/editor and owner-management routes keep their approved remote+ behavior. Unknown API routes fail closed to trusted-local callers so adding a+ new owner-only endpoint cannot silently expose local machine capabilities.+ """++ normalized_method = method.upper()+ # Organization management is an explicit Cloud proxy namespace. Cloud user+ # identity and object authorization are re-evaluated by that boundary.+ if path.startswith("/api/cloud-management/"):+ return HttpAuthorizationPolicy("viewer")+ if path.startswith("/show/"):+ is_read = normalized_method in {"GET", "HEAD", "OPTIONS"}+ # The server-owned event endpoint does not proxy into Show Runtime. Its+ # handler rejects any remote request that would dispatch an Agent turn+ # before the event store can reserve a delivery.+ is_safe_human_event = normalized_method == "POST" and re.fullmatch(+ r"^/show/[^/]+/(?:__show/events|__events)$",+ path,+ )+ minimum_role = "viewer" if is_read else "editor"+ remote_access = (+ REMOTE_HTTP_ALLOWED+ if is_read or is_safe_human_event+ else REMOTE_HTTP_LOCAL_ONLY+ )+ return HttpAuthorizationPolicy(minimum_role, remote_access)+ if not path.startswith("/api/"):+ return HttpAuthorizationPolicy(None)++ minimum_role = "owner"- for rule_method, pattern in _EDITOR_HTTP_RULES:- if normalized_method == rule_method and pattern.fullmatch(path):- minimum_role = "editor"- break++ if _http_rule_matches(normalized_method, path, _VIEWER_HTTP_MUTATION_RULES):++ # These mutations enforce Show Page ownership and Organization authority++ # in the resource service. Admit a viewer to that final authorization gate.++ minimum_role = "viewer"+ else:- if normalized_method in {"GET", "HEAD", "OPTIONS"} and any(- pattern.fullmatch(path) for pattern in _VIEWER_HTTP_RULES- ):- minimum_role = "viewer"++ for rule_method, pattern in _EDITOR_HTTP_RULES:++ if normalized_method == rule_method and pattern.fullmatch(path):++ minimum_role = "editor"++ break++ else:++ if normalized_method in {"GET", "HEAD", "OPTIONS"} and any(++ pattern.fullmatch(path) for pattern in _VIEWER_HTTP_RULES++ ):++ minimum_role = "viewer"++ if _http_rule_matches(normalized_method, path, _REMOTE_LOCAL_ONLY_HTTP_RULES):+ remote_access = REMOTE_HTTP_LOCAL_ONLY+ elif _http_rule_matches(+ normalized_method,+ path,+ _REMOTE_PAYLOAD_FILTERED_HTTP_RULES,+ ):+ remote_access = REMOTE_HTTP_PAYLOAD_FILTERED+ elif minimum_role in {"viewer", "editor"} or _owner_http_rule_matches(+ normalized_method,+ path,+ ):+ remote_access = REMOTE_HTTP_ALLOWED+ else:+ remote_access = REMOTE_HTTP_LOCAL_ONLY+ return HttpAuthorizationPolicy(minimum_role, remote_access)+def required_instance_role(method: str, path: str) -> str | None:"""Return the minimum role for a remote HTTP request.