Skip to content

The agent that grows with you

54.6 KB
Raw Blame
// Side-effect import: watches the turn edge so the overlay keeps a pulse while
// the model reasons. Lives here because the pane is what makes it reachable.
import './preview-mind'

import { useStore } from '@nanostores/react'
import type { ComponentProps, PointerEvent as ReactPointerEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'

import { requestComposerAttachImages, requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'
import { openGuestContextMenu } from '@/app/context-menu/store'
import { PanelEmpty } from '@/app/overlays/panel'
import { PreviewDocumentFrame } from '@/components/ui/preview-document-frame'
import { Tip } from '@/components/ui/tooltip'
import { type Translations, useI18n } from '@/i18n'
import { isDesktopFsRemoteMode, isReadFileErrorResult } from '@/lib/desktop-fs'
import { guardGuestPointers } from '@/lib/guest-pointer-guard'
import { hostHas } from '@/lib/host-capabilities'
import { isLoopbackPreviewUrl, openPreviewTargetInBrowser, remoteHtmlPreviewDocument } from '@/lib/local-preview'
import { isRemoteGateway } from '@/lib/media'
import {
  addAnnotatePin,
  beginAnnotateMode,
  clearAnnotatePins,
  compactIdentity,
  emptyAnnotateSession,
  emptyAnnotateStack,
  endAnnotateMode,
  flushAnnotateStack
} from '@/lib/preview-annotate'
import { handoffPreviewAnnotateStack } from '@/lib/preview-annotate/handoff'
import { admitPreviewExternalUrl, PREVIEW_EXTERNAL_CHANNEL } from '@/lib/preview-external'
import { reachablePreviewUrl } from '@/lib/preview-reach'
import { rafCoalesce } from '@/lib/raf-coalesce'
import { cn } from '@/lib/utils'
import { notify, notifyError } from '@/store/notifications'
import {
  $browserPages,
  $previewServerRestart,
  commitBrowserTabLocation,
  failPreviewServerRestart,
  noteBrowserPage,
  popOutBrowserTab,
  type PreviewRenderMode,
  type PreviewTarget,
  setPreviewRenderMode
} from '@/store/preview'
import { $selectedStoredSessionId } from '@/store/session'
import { canOpenBrowserWindow, isBrowserWindow } from '@/store/windows'

import { placeAnnotateCard, PreviewAnnotateCard } from './preview-annotate-card'
import {
  bindPreviewExecuteJavaScript,
  captureAnnotateCrop,
  hideAnnotateDraft,
  installAnnotateOverlay,
  type PreviewAnnotateGuest,
  showAnnotateDraft,
  syncAnnotatePins,
  teardownAnnotateOverlay,
  waitAnnotateEvent
} from './preview-annotate-host'
import { ArtifactPreview } from './preview-artifact'
import { PreviewBrowserBar } from './preview-browser-bar'
import { mountBrowserPreviewFrame, type PreviewNavigationSurface } from './preview-browser-frame'
import { PreviewBrowserFrameHint } from './preview-browser-frame-hint'
import {
  clampConsoleHeight,
  compactUrl,
  formatLogLine,
  isNearConsoleBottom,
  PreviewConsolePanel
} from './preview-console'
import { type ConsoleEntry } from './preview-console-state'
import { previewConsoleState } from './preview-console-store'
import { usePreviewDriveChannels } from './preview-drive-channels'
import { LocalFilePreview, PreviewEmptyState, PreviewModeSwitcher } from './preview-file'
import { usePreviewGuestOffscreen } from './preview-guest-offscreen'
import { type PreviewInputEvent } from './preview-input'
import { PREVIEW_BROWSER_ATTR, registerPreviewNav } from './preview-nav'
import { registerPreviewPageReader } from './preview-reader'
import { RealProfileConsentDialog } from './real-profile-consent-dialog'

type PreviewWebview = HTMLElement &
  PreviewNavigationSurface & {
    canGoBack?: () => boolean
    canGoForward?: () => boolean
    closeDevTools?: () => void
    copy?: () => void
    cut?: () => void
    executeJavaScript?: (code: string) => Promise<unknown>
    getTitle?: () => string
    getURL?: () => string
    getWebContentsId?: () => number
    goBack?: () => void
    goForward?: () => void
    inspectElement?: (x: number, y: number) => void
    isDevToolsOpened?: () => boolean
    openDevTools?: () => void
    paste?: () => void
    reloadIgnoringCache?: () => void
    replaceMisspelling?: (word: string) => void
    selectAll?: () => void
    sendInputEvent?: (event: PreviewInputEvent) => void
    getZoomFactor?: () => number
  }

/** Electron throws if getURL/getTitle run before attach + dom-ready, or after
 *  the guest has been removed. Optional chaining does not help — the method
 *  exists, it just refuses. */
function guestPage(webview: PreviewWebview | null | undefined, fallbackUrl = ''): { title: string; url: string } {
  try {
    return {
      title: webview?.getTitle?.() ?? '',
      url: webview?.getURL?.() || fallbackUrl
    }
  } catch {
    return { title: '', url: fallbackUrl }
  }
}

/** The live surface a web preview mounts: Electron's `<webview>`, or a plain
 *  iframe when Desktop is served to a browser, which has no webview tag.
 *  Remote HTML renders from its data URL instead, so it gets neither. */
function webPreviewSurface(isWebPreview: boolean, isRemoteHtml: boolean): 'iframe' | 'webview' | null {
  if (!isWebPreview || isRemoteHtml) {
    return null
  }

  return hostHas('webviewPreview') ? 'webview' : 'iframe'
}

/** The raw Chromium params riding the webview tag's `context-menu` event. */
interface GuestContextMenuParams {
  dictionarySuggestions?: string[]
  editFlags?: {
    canCopy?: boolean
    canCut?: boolean
    canPaste?: boolean
    canSelectAll?: boolean
  }
  hasImageContents?: boolean
  isEditable?: boolean
  linkURL?: string
  misspelledWord?: string
  selectionText?: string
  srcURL?: string
  x: number
  y: number
}

interface PreviewPaneProps {
  embedded?: boolean
  /** Closes this preview's tab. Offered by body states that are a dead end
   *  (a file that no longer exists) so the way out is not only the strip. */
  onClose?: () => void
  onRestartServer?: (url: string, context?: string) => Promise<string>
  reloadRequest?: number
  /** The session that owns the tab; a file it names resolves in that session's workspace. */
  sessionId?: string
  /** The preview tab this pane renders. Keys the per-tab console store the
   *  browser bar's console toggle and the console panel both read. */
  tabId?: string
  target: PreviewTarget
}

interface PreviewLoadErrorState {
  code?: number
  description: string
  url: string
}

const FILE_RELOAD_DEBOUNCE_MS = 200
const SERVER_RESTART_TIMEOUT_MS = 45_000

function loadErrorTitle(error: PreviewLoadErrorState, copy: Translations['preview']['web']): string {
  const description = error.description.toLowerCase()

  if (description.includes('module script') || description.includes('mime type')) {
    return copy.appFailedToBoot
  }

  if (description.includes('connection') || description.includes('refused') || description.includes('not found')) {
    return copy.serverNotFound
  }

  return copy.failedToLoad
}

/**
 * True when this address can't mean what the agent meant.
 *
 * The `<webview>` always runs on the user's own machine, never on the gateway
 * host. So against a remote gateway, an agent's `localhost:5173` resolves here
 * — where that port is usually nothing, or worse, somebody else's service. The
 * URL isn't wrong, it's just addressed to a different computer.
 */
function isRemoteLoopbackUrl(url: string): boolean {
  return isRemoteGateway() && isLoopbackPreviewUrl(url)
}

function isModuleMimeError(message: string): boolean {
  const lower = message.toLowerCase()

  return lower.includes('failed to load module script') && lower.includes('mime type')
}

/**
 * #101880: a guest page's `window.print()` (e.g. a Google Doc's Print
 * button) reaches the macOS native print panel, whose construction
 * segfaults inside PrintCore — the whole app dies before any dialog
 * appears. Stub `print` in the guest so the native panel is never built;
 * the warn surfaces in the preview console via the existing pipe. The
 * `__hermesPrintGuard` flag keeps re-arms idempotent. Full print-to-PDF
 * routing is the follow-up; this stops the crash.
 */
const PREVIEW_PRINT_GUARD_SCRIPT =
  '(function(){if(window.__hermesPrintGuard)return;window.__hermesPrintGuard=true;' +
  'window.print=function(){console.warn("[Hermes] Printing is disabled in the in-app preview. ' +
  'Open the page in your browser to print.");};})()'

function PreviewLoadError({
  consoleHeight = 0,
  error,
  onRestartServer,
  onRetry,
  restarting
}: {
  consoleHeight?: number
  error: PreviewLoadErrorState
  onRestartServer?: () => void
  onRetry: () => void
  restarting?: boolean
}) {
  const { t } = useI18n()
  const copy = t.preview.web

  return (
    <PreviewEmptyState
      body={
        <>
          <a
            className="pointer-events-auto block font-mono text-muted-foreground/90 underline decoration-current/20 underline-offset-4 transition-colors hover:text-foreground"
            href={error.url}
            onClick={event => {
              event.preventDefault()
              void window.hermesDesktop?.openExternal(error.url)
            }}
          >
            {compactUrl(error.url)}
            {error.code ? ` (${error.code})` : ''}
          </a>
          <div className="mt-1 text-[0.6875rem] text-muted-foreground/70">{error.description}</div>
          {isRemoteLoopbackUrl(error.url) && (
            <div className="mt-2 text-[0.6875rem] leading-relaxed text-muted-foreground/70">{copy.remoteLoopback}</div>
          )}
        </>
      }
      consoleHeight={consoleHeight}
      primaryAction={{ label: copy.tryAgain, onClick: onRetry }}
      secondaryAction={
        onRestartServer
          ? {
              disabled: restarting,
              label: restarting ? copy.restarting : copy.askRestart,
              onClick: onRestartServer
            }
          : undefined
      }
      title={loadErrorTitle(error, copy)}
    />
  )
}

/** The body of a tab that is not a web page: a generated artifact or a file. */
function PreviewDocumentBody(props: ComponentProps<typeof LocalFilePreview>) {
  return props.target.kind === 'artifact' ? (
    <ArtifactPreview onClose={props.onClose} target={props.target} />
  ) : (
    <LocalFilePreview {...props} />
  )
}

export function PreviewPane({
  embedded = false,
  onClose,
  onRestartServer,
  reloadRequest = 0,
  sessionId,
  tabId,
  target
}: PreviewPaneProps) {
  const { t } = useI18n()
  const copy = t.preview.web
  // The console store belongs to the TAB, not this render: the toggles live on
  // the tab and must read the same logs this pane appends to.
  const consoleState = previewConsoleState(tabId ?? target.url)
  const consoleBodyRef = useRef<HTMLDivElement | null>(null)
  const consoleShouldStickRef = useRef(true)
  const hostRef = useRef<HTMLDivElement | null>(null)
  const lastReloadRequestRef = useRef(reloadRequest)
  const lastRestartEventRef = useRef('')
  const navigationRef = useRef<PreviewNavigationSurface | null>(null)
  const previewContentRef = useRef<HTMLDivElement | null>(null)
  const webviewRef = useRef<PreviewWebview | null>(null)
  const noteGuestReady = usePreviewGuestOffscreen(webviewRef, tabId)
  const previewServerRestart = useStore($previewServerRestart)
  const consoleHeight = useStore(consoleState.$height)
  const consoleOpen = useStore(consoleState.$open)
  const selectedStoredSessionId = useStore($selectedStoredSessionId)
  const [currentUrl, setCurrentUrl] = useState(target.url)
  const liveUrlRef = useRef(currentUrl)
  liveUrlRef.current = currentUrl
  // The guest-creation effect below deliberately omits target.url from its
  // deps (it reuses the guest across navigations — see #120265), so it reads
  // the live address through this mirror instead of a stale closure.
  const targetUrlRef = useRef(target.url)
  targetUrlRef.current = target.url
  const [devtoolsOpen, setDevtoolsOpen] = useState(false)
  const [history, setHistory] = useState({ back: false, forward: false })
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<PreviewLoadErrorState | null>(null)
  const [localReloadKey, setLocalReloadKey] = useState(0)
  const [annotate, setAnnotate] = useState(emptyAnnotateSession)
  const [draftNote, setDraftNote] = useState('')
  const annotateRef = useRef(annotate)
  const annotateLoopRef = useRef(0)
  const annotateConversationRef = useRef(selectedStoredSessionId)
  annotateRef.current = annotate

  const renderMode = target.renderMode

  // Artifacts have no URL to load — they render from the registry, never in a
  // webview.
  const isWebPreview =
    target.kind !== 'artifact' && (target.kind === 'url' || (target.previewKind === 'html' && renderMode !== 'source'))

  const isRemoteHtmlTarget =
    target.kind === 'file' && target.previewKind === 'html' && Boolean(target.dataUrl || target.transient)

  // The mode lives on the store tab, so only a tab-backed pane can flip it. A
  // remote HTML file whose data URL failed validation arrives as a source-only
  // transient target; it has no rendered path to offer.
  const canRenderHtmlFile =
    Boolean(tabId) &&
    target.kind === 'file' &&
    target.previewKind === 'html' &&
    (!target.transient || Boolean(target.dataUrl))

  const selectRenderMode = (next: PreviewRenderMode) => {
    if (tabId) {
      setPreviewRenderMode(tabId, next)
    }
  }

  // Hand the live address to storage when this guest is about to go away
  // (pop-out, dock-back, tab close). The other renderer builds from
  // `target.url`; without this it would reopen the tab's original page.
  useEffect(() => {
    if (target.kind !== 'url' || !tabId) {
      return
    }

    const persist = () => {
      const page = $browserPages.get()[tabId]
      commitBrowserTabLocation(tabId, page?.url || liveUrlRef.current, page?.title)
    }

    window.addEventListener('pagehide', persist)

    return () => {
      window.removeEventListener('pagehide', persist)
      persist()
    }
  }, [tabId, target.kind])

  const isRemoteHtml = isRemoteHtmlTarget && renderMode !== 'source' && Boolean(target.dataUrl)

  const webSurface = webPreviewSurface(isWebPreview, isRemoteHtml)
  const usesBrowserIframe = webSurface === 'iframe'
  const usesWebview = webSurface === 'webview'

  const remoteHtmlDocument = useMemo(
    () => (isRemoteHtml ? remoteHtmlPreviewDocument(target.dataUrl!) : null),
    [isRemoteHtml, target.dataUrl]
  )

  const currentLabel = compactUrl(currentUrl)

  // Nothing loaded: no address yet, or the blank page itself. A webview on
  // `about:blank` paints a white void that reads as broken next to the app's
  // dark chrome, so the pane says what it is instead.
  const isBlankPage = isWebPreview && !isRemoteHtml && (!currentUrl || /^about:blank\/?$/i.test(currentUrl))

  const previewLabel =
    target.label && target.label.replace(/\/$/, '') !== currentLabel.replace(/\/$/, '') ? target.label : currentLabel

  const restartingServer =
    previewServerRestart?.status === 'running' &&
    (previewServerRestart.url === target.url || previewServerRestart.url === currentUrl)

  const startConsoleResize = useCallback(
    (event: ReactPointerEvent<HTMLDivElement>) => {
      event.preventDefault()

      const handle = event.currentTarget
      const pointerId = event.pointerId
      const startY = event.clientY
      const startHeight = consoleHeight
      const previousCursor = document.body.style.cursor
      const previousUserSelect = document.body.style.userSelect
      let active = true

      handle.setPointerCapture?.(pointerId)

      document.body.style.cursor = 'row-resize'
      document.body.style.userSelect = 'none'
      // The webview above the console must not swallow the gesture.
      const releaseGuests = guardGuestPointers()

      // pointermove outpaces 60fps and each setHeight reflows the webview +
      // console split, so coalesce to one apply per frame (commits on cleanup).
      const resize = rafCoalesce((height: number) => consoleState.setHeight(height))

      const handleMove = (moveEvent: PointerEvent) => {
        if (!active) {
          return
        }

        resize.push(clampConsoleHeight(startHeight + startY - moveEvent.clientY))
      }

      const cleanup = () => {
        if (!active) {
          return
        }

        active = false
        resize.finish()
        releaseGuests()
        document.body.style.cursor = previousCursor
        document.body.style.userSelect = previousUserSelect
        handle.releasePointerCapture?.(pointerId)
        window.removeEventListener('pointermove', handleMove, true)
        window.removeEventListener('pointerup', cleanup, true)
        window.removeEventListener('pointercancel', cleanup, true)
        window.removeEventListener('blur', cleanup)
        handle.removeEventListener('lostpointercapture', cleanup)
      }

      window.addEventListener('pointermove', handleMove, true)
      window.addEventListener('pointerup', cleanup, true)
      window.addEventListener('pointercancel', cleanup, true)
      window.addEventListener('blur', cleanup)
      handle.addEventListener('lostpointercapture', cleanup)
    },
    [consoleHeight, consoleState]
  )

  const reloadPreview = useCallback(() => {
    setLoadError(null)

    if (!isWebPreview) {
      setLocalReloadKey(key => key + 1)

      return
    }

    if (webviewRef.current?.reloadIgnoringCache) {
      webviewRef.current.reloadIgnoringCache()
    } else {
      navigationRef.current?.reload?.()
    }
  }, [isWebPreview])

  const annotateGuest = useCallback((): null | PreviewAnnotateGuest => {
    const webview = webviewRef.current

    if (!webview?.executeJavaScript) {
      return null
    }

    return {
      capture: async rect => {
        const webContentsId = webview.getWebContentsId?.()

        if (typeof webContentsId !== 'number') {
          throw new Error('preview guest has no webContents')
        }

        const viewport = (await bindPreviewExecuteJavaScript(webview)(
          '({ width: window.innerWidth, height: window.innerHeight })'
        )) as { height: number; width: number }

        const dataUrl = await window.hermesDesktop.capturePreview?.({ rect, viewport, webContentsId })

        if (!dataUrl) {
          throw new Error('preview capture is unavailable')
        }

        return dataUrl
      },
      executeJavaScript: bindPreviewExecuteJavaScript(webview)
    }
  }, [])

  const stopAnnotate = useCallback(async () => {
    annotateLoopRef.current += 1
    const guest = annotateGuest()

    if (guest) {
      await teardownAnnotateOverlay(guest).catch(() => undefined)
    }

    setDraftNote('')
    setAnnotate(endAnnotateMode)
  }, [annotateGuest])

  // Not an atom mirror: the ref records the last conversation the annotate
  // stack was reset for, so the reset runs once per switch. Extracted into a
  // callback so the effect body carries no `.current` writes (lint contract).
  const resetAnnotateForConversation = useCallback(
    (sessionId: typeof selectedStoredSessionId) => {
      annotateConversationRef.current = sessionId
      annotateLoopRef.current += 1
      setDraftNote('')
      setAnnotate(emptyAnnotateSession())

      const guest = annotateGuest()

      if (guest) {
        void teardownAnnotateOverlay(guest).catch(() => undefined)
      }
    },
    [annotateGuest]
  )

  useEffect(() => {
    if (annotateConversationRef.current !== selectedStoredSessionId) {
      resetAnnotateForConversation(selectedStoredSessionId)
    }
  }, [resetAnnotateForConversation, selectedStoredSessionId])

  const saveAnnotateDraft = useCallback(async () => {
    const session = annotateRef.current

    if (!session.draft) {
      return
    }

    const draft = { ...session.draft, note: draftNote.trim() }
    const guest = annotateGuest()

    const stack = addAnnotatePin(session.stack, draft)
    setAnnotate({ ...session, draft: null, stack })
    setDraftNote('')

    if (guest) {
      await syncAnnotatePins(
        guest,
        stack.pins.map(pin => ({
          kind: pin.kind,
          number: pin.number,
          rect: pin.rect,
          selector: pin.identity?.selector
        }))
      ).catch(() => undefined)
      await hideAnnotateDraft(guest).catch(() => undefined)
    }
  }, [annotateGuest, draftNote])

  const cancelAnnotateDraft = useCallback(async () => {
    setDraftNote('')
    setAnnotate(session => ({ ...session, draft: null }))

    const guest = annotateGuest()

    if (guest) {
      await hideAnnotateDraft(guest).catch(() => undefined)
    }
  }, [annotateGuest])

  const flushComments = useCallback(async () => {
    const pins = annotateRef.current.stack.pins

    if (!pins.length) {
      return
    }

    const guest = annotateGuest()

    if (isBrowserWindow()) {
      const result = tabId
        ? await handoffPreviewAnnotateStack(tabId, pins, currentUrl)
        : { error: 'This Browser window has no tab identity.', ok: false }

      if (!result.ok) {
        notify({
          kind: 'warning',
          message: result.error || 'Could not add Browser comments to the original chat.',
          title: copy.annotate
        })

        return
      }
    } else {
      await flushAnnotateStack(
        pins,
        {
          attachImage: blob => {
            requestComposerAttachImages([blob])
          },
          insertText: text => requestComposerInsert(text, { mode: 'block' })
        },
        currentUrl
      )
      requestComposerFocus()
    }

    setAnnotate(session => ({ ...session, draft: null, stack: clearAnnotatePins(session.stack) }))
    setDraftNote('')

    if (guest) {
      await hideAnnotateDraft(guest).catch(() => undefined)
      await syncAnnotatePins(guest, []).catch(() => undefined)
    }
  }, [annotateGuest, copy.annotate, currentUrl, tabId])

  const startAnnotate = useCallback(async () => {
    const guest = annotateGuest()

    if (!guest) {
      notify({ kind: 'warning', title: copy.annotate, message: copy.annotateNeedPage })

      return
    }

    const generation = ++annotateLoopRef.current
    setAnnotate(beginAnnotateMode)

    try {
      await installAnnotateOverlay(guest)
      await syncAnnotatePins(
        guest,
        annotateRef.current.stack.pins.map(pin => ({
          kind: pin.kind,
          number: pin.number,
          rect: pin.rect,
          selector: pin.identity?.selector
        }))
      )
    } catch (error) {
      setAnnotate(endAnnotateMode)
      notifyError(error, copy.annotateFailed)

      return
    }

    while (annotateLoopRef.current === generation) {
      let event

      try {
        event = await waitAnnotateEvent(guest)
      } catch {
        break
      }

      if (annotateLoopRef.current !== generation) {
        break
      }

      if (event.type === 'end') {
        await stopAnnotate()

        break
      }

      if (event.type === 'reposition') {
        setAnnotate(session =>
          session.draft ? { ...session, draft: { ...session.draft, rect: event.rect } } : session
        )

        continue
      }

      const page = guestPage(webviewRef.current, liveUrlRef.current)
      const nextNumber = annotateRef.current.stack.nextNumber
      await showAnnotateDraft(guest, event.rect, nextNumber).catch(() => undefined)

      let imageDataUrl = ''

      try {
        imageDataUrl = await captureAnnotateCrop(guest, event.rect)
      } catch {
        imageDataUrl = ''
      }

      const draft = {
        imageDataUrl,
        identity: event.type === 'pick-element' ? compactIdentity(event.identity) : undefined,
        kind: event.type === 'pick-element' ? ('element' as const) : ('area' as const),
        note: '',
        pageTitle: page.title,
        pageUrl: page.url,
        rect: event.rect
      }

      setDraftNote('')
      setAnnotate(session => ({ ...session, draft }))
    }
  }, [annotateGuest, copy.annotate, copy.annotateFailed, copy.annotateNeedPage, stopAnnotate])

  const toggleAnnotate = useCallback(() => {
    if (annotateRef.current.mode) {
      void stopAnnotate()
    } else {
      void startAnnotate()
    }
  }, [startAnnotate, stopAnnotate])

  const appendConsoleEntry = useCallback(
    (entry: Omit<ConsoleEntry, 'id'>) => {
      consoleShouldStickRef.current = isNearConsoleBottom(consoleBodyRef.current)
      consoleState.append(entry)
    },
    [consoleState]
  )

  const restartServer = useCallback(async () => {
    if (!onRestartServer) {
      return
    }

    // Auto-open the preview console so the user can see progress events
    // streaming back from the background agent. Without this, clicking
    // "Ask Hermes to restart the server" looked like it did nothing —
    // the work was happening, but in a collapsed pane.
    consoleState.setOpen(true)

    try {
      const context = consoleState.$logs.get().slice(-12).map(formatLogLine).join('\n')
      const taskId = await onRestartServer(currentUrl, context || undefined)

      appendConsoleEntry({
        level: 1,
        message: copy.lookingRestart(taskId)
      })

      notify({
        kind: 'info',
        title: copy.restartingTitle,
        message: copy.restartingMessage,
        durationMs: 4000
      })
    } catch (error) {
      appendConsoleEntry({
        level: 2,
        message: copy.startRestartFailed(error instanceof Error ? error.message : String(error))
      })
      notifyError(error, copy.restartFailed)
    }
  }, [appendConsoleEntry, consoleState, copy, currentUrl, onRestartServer])

  const toggleDevTools = useCallback(() => {
    const webview = webviewRef.current

    if (!webview?.openDevTools) {
      return
    }

    if (webview.isDevToolsOpened?.()) {
      webview.closeDevTools?.()

      return
    }

    webview.openDevTools()
  }, [])

  const navigateTo = useCallback(
    (url: string) => {
      setLoadError(null)
      // The reach probe below is a round-trip of its own, and `did-start-loading`
      // can't fire until it resolves — so own the loading state from the moment
      // we accept the address, or the bar sits idle over a request in flight.
      setLoading(true)
      // Typed addresses get the same loopback reach as agent-opened ones — on a
      // remote gateway `localhost:5173` is usually the dev server the user is
      // there to look at, not something on their own laptop.
      void reachablePreviewUrl(url)
        .then(reached =>
          // loadURL, not a `src` swap: `src` only reloads when the value CHANGES,
          // so re-entering the address you're already on would do nothing. A
          // rejected load is a real navigation failure the user has to see —
          // `did-fail-load` doesn't fire for every rejection (a bad scheme
          // rejects outright).
          navigationRef.current?.loadURL?.(reached)
        )
        .catch((error: unknown) => {
          setLoadError({
            description: error instanceof Error ? error.message : copy.unreachableDescription,
            url
          })
          setLoading(false)
        })
    },
    [copy.unreachableDescription]
  )

  const goBack = useCallback(() => {
    const webview = webviewRef.current

    if (webview?.canGoBack?.()) {
      webview.goBack?.()
    }
  }, [])

  const goForward = useCallback(() => {
    const webview = webviewRef.current

    if (webview?.canGoForward?.()) {
      webview.goForward?.()
    }
  }, [])

  // Escape is the universal "leave where I am" key, and a preview webview that
  // navigated away from the original page (a report's in-page links) is a
  // dead end without it. Only the pane that holds DOM focus backs up, so two
  // side-by-side panes never fight, and only when the webview actually has
  // history — a remote-HTML report (data: document, no webview) or a
  // first-page preview claims no back at all. While focus sits in an editable
  // surface inside the pane (the browser bar's address input, an annotate
  // note), Escape keeps its native meaning for that control and does not
  // also navigate.
  const onPaneKeyDown = useCallback((event: React.KeyboardEvent<HTMLElement>) => {
    if (event.key !== 'Escape') {
      return
    }

    const target = event.target as HTMLElement | null

    if (target?.closest?.('input, textarea, [contenteditable="true"], [contenteditable=""]')) {
      return
    }

    const webview = webviewRef.current

    if (!webview?.canGoBack?.()) {
      return
    }

    event.preventDefault()
    webview.goBack?.()
  }, [])

  // Gestures that land on the app's chrome (⌘R from the address bar, a mouse
  // button over the frame). A gesture made INSIDE the page is answered by main
  // against the focused guest — this renderer can't see into a webview.
  useEffect(() => {
    if (!usesWebview || !tabId) {
      return
    }

    return registerPreviewNav(tabId, { back: goBack, forward: goForward, reload: reloadPreview })
  }, [goBack, goForward, reloadPreview, tabId, usesWebview])

  // Publish the PAGE reader for this tab (the read_preview tool): extract the
  // rendered page's title + visible text from the webview. innerText (not
  // textContent) so hidden nodes and script/style bodies stay out, matching
  // what the user actually sees.
  useEffect(() => {
    if (!usesWebview || !tabId) {
      return
    }

    return registerPreviewPageReader(tabId, async () => {
      const webview = webviewRef.current

      if (!webview?.executeJavaScript) {
        throw new Error('preview webview is not ready')
      }

      const text = await webview.executeJavaScript('document.body ? document.body.innerText : ""')

      return {
        text: typeof text === 'string' ? text : '',
        ...guestPage(webview)
      }
    })
  }, [tabId, usesWebview])

  usePreviewDriveChannels(webviewRef, tabId, usesWebview)

  // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
  useEffect(() => {
    if (!consoleOpen) {
      return
    }

    consoleShouldStickRef.current = true

    const handle = window.requestAnimationFrame(() => {
      const consoleBody = consoleBodyRef.current
      consoleBody?.scrollTo({ top: consoleBody.scrollHeight })
    })

    return () => window.cancelAnimationFrame(handle)
  }, [consoleOpen])

  // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
  useEffect(() => {
    if (
      !previewServerRestart ||
      !previewServerRestart.message ||
      (previewServerRestart.url !== target.url && previewServerRestart.url !== currentUrl)
    ) {
      return
    }

    const eventKey = `${previewServerRestart.taskId}:${previewServerRestart.status}:${previewServerRestart.message || ''}`

    if (eventKey === lastRestartEventRef.current) {
      return
    }

    lastRestartEventRef.current = eventKey
    appendConsoleEntry({
      level: previewServerRestart.status === 'error' ? 2 : 1,
      message:
        previewServerRestart.status === 'running'
          ? previewServerRestart.message
          : previewServerRestart.status === 'complete'
            ? copy.finishedRestarting(previewServerRestart.message)
            : copy.failedRestarting(previewServerRestart.message || copy.unknownError)
    })

    if (previewServerRestart.status === 'complete') {
      reloadPreview()
      notify({
        kind: 'success',
        title: copy.restartedTitle,
        message: previewServerRestart.message?.slice(0, 160) || copy.reloadingNow,
        durationMs: 3500
      })
    } else if (previewServerRestart.status === 'error') {
      notify({
        kind: 'warning',
        title: copy.restartFailedTitle,
        message: previewServerRestart.message?.slice(0, 200) || copy.restartFailedMessage,
        durationMs: 6000
      })
    }
  }, [appendConsoleEntry, copy, currentUrl, previewServerRestart, reloadPreview, target.url])

  useEffect(() => {
    if (!restartingServer || !previewServerRestart) {
      return
    }

    const taskId = previewServerRestart.taskId

    const timer = window.setTimeout(() => {
      failPreviewServerRestart(taskId, copy.stillWorking)
    }, SERVER_RESTART_TIMEOUT_MS)

    return () => window.clearTimeout(timer)
  }, [copy.stillWorking, previewServerRestart, restartingServer])

  // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
  useEffect(() => {
    if (reloadRequest === lastReloadRequestRef.current) {
      return
    }

    lastReloadRequestRef.current = reloadRequest

    // An agent's file edit can only change a page a local dev server serves.
    // Reloading any other site just throws away the user's page state.
    if (target.kind !== 'url' || !isLoopbackPreviewUrl(currentUrl)) {
      return
    }

    appendConsoleEntry({
      level: 1,
      message: copy.workspaceReloading
    })
    reloadPreview()
  }, [appendConsoleEntry, copy.workspaceReloading, currentUrl, reloadPreview, reloadRequest, target.kind])

  useEffect(() => {
    if (
      target.kind !== 'file' ||
      isDesktopFsRemoteMode() ||
      !window.hermesDesktop?.watchPreviewFile ||
      !window.hermesDesktop?.onPreviewFileChanged
    ) {
      return
    }

    let active = true
    let pendingReloadCount = 0
    let pendingReloadUrl = ''
    let reloadTimer: ReturnType<typeof setTimeout> | null = null
    let watchId = ''

    const flushReload = () => {
      if (!active || pendingReloadCount === 0) {
        return
      }

      const changedCount = pendingReloadCount
      const changedUrl = pendingReloadUrl

      pendingReloadCount = 0
      pendingReloadUrl = ''

      appendConsoleEntry({
        level: 1,
        message:
          changedCount === 1
            ? copy.fileChanged(compactUrl(changedUrl))
            : copy.filesChanged(changedCount, compactUrl(changedUrl))
      })

      reloadPreview()
    }

    const unsubscribe = window.hermesDesktop.onPreviewFileChanged(payload => {
      if (!active || payload.id !== watchId) {
        return
      }

      pendingReloadCount += 1
      pendingReloadUrl = payload.url

      if (reloadTimer) {
        clearTimeout(reloadTimer)
      }

      reloadTimer = setTimeout(() => {
        reloadTimer = null
        flushReload()
      }, FILE_RELOAD_DEBOUNCE_MS)
    })

    void window.hermesDesktop
      .watchPreviewFile(target.url)
      .then(watch => {
        // The file was already gone when the watch was requested (a restored
        // tab probing a deleted path): structured data, not a rejection. The
        // read below surfaces the tombstone; nothing to watch.
        if (isReadFileErrorResult(watch)) {
          return
        }

        if (!active) {
          void window.hermesDesktop?.stopPreviewFileWatch?.(watch.id)

          return
        }

        watchId = watch.id
      })
      .catch(error => {
        appendConsoleEntry({
          level: 2,
          message: copy.watchFailed(error instanceof Error ? error.message : String(error))
        })
      })

    return () => {
      active = false
      unsubscribe()

      if (reloadTimer) {
        clearTimeout(reloadTimer)
      }

      if (watchId) {
        void window.hermesDesktop?.stopPreviewFileWatch?.(watchId)
      }
    }
  }, [appendConsoleEntry, copy, reloadPreview, target.kind, target.url])

  // The guest is created ONCE per preview kind and reused across URL changes
  // within the session (#120265): an external target.url change steers the
  // live guest with loadURL() in the sync effect below, instead of destroying
  // the webview and rebuilding it (which dropped JS state, cookies, form
  // data, scroll, refs, and detached the console/annotate channels).
  // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
  useEffect(() => {
    const host = hostRef.current

    if (!host) {
      return
    }

    const initialUrl = targetUrlRef.current
    host.replaceChildren()
    navigationRef.current = null
    webviewRef.current = null
    setCurrentUrl(initialUrl)
    setDevtoolsOpen(false)
    setHistory({ back: false, forward: false })
    setLoadError(null)
    consoleState.reset()
    setLoading(true)

    if (!isWebPreview || isRemoteHtml) {
      setLoading(false)

      return
    }

    // A browser host has no `<webview>` tag: past the guard above, this is
    // exactly `usesBrowserIframe`, so the iframe mounts instead.
    if (!hostHas('webviewPreview')) {
      return mountBrowserPreviewFrame({
        host,
        navigationRef,
        onError: url => setLoadError({ description: copy.unreachableDescription, url }),
        setCurrentUrl,
        setLoading,
        url: initialUrl
      })
    }

    const webview = document.createElement('webview') as PreviewWebview
    // A page with no background of its own shows white, as in a browser and the remote HTML frame below.
    webview.className = 'flex h-full w-full flex-1 bg-white'
    webview.setAttribute('partition', 'persist:hermes-preview')
    webview.setAttribute('src', initialUrl)
    webview.setAttribute('webpreferences', 'contextIsolation=yes,nodeIntegration=no,sandbox=yes')

    // The guest preload (main.ts installs it on this partition) forwards a
    // clicked `_blank` anchor here. Admission is our side of the contract —
    // http/https only, so a guest page can never reach the local-file
    // opener — and the open itself goes through the audited
    // `hermes:openExternal` channel, never a popup side effect.
    const onGuestExternal = (event: Event) => {
      const detail = event as Event & { args?: unknown[]; channel?: string }

      if (detail.channel !== PREVIEW_EXTERNAL_CHANNEL) {
        return
      }

      const url = String(detail.args?.[0] ?? '')

      if (admitPreviewExternalUrl(url)) {
        void window.hermesDesktop?.openExternal?.(url)
      }
    }

    const onConsole = (event: Event) => {
      const detail = event as Event & {
        level?: number
        line?: number
        message?: string
        sourceId?: string
      }

      const message = detail.message || ''

      appendConsoleEntry({
        level: detail.level ?? 0,
        line: detail.line,
        message,
        source: detail.sourceId
      })

      if ((detail.level ?? 0) >= 3 && isModuleMimeError(message)) {
        setLoadError({
          description: copy.moduleMimeDescription,
          url: guestPage(webview, liveUrlRef.current).url
        })
        setLoading(false)
      }
    }

    const syncHistory = () => {
      try {
        setHistory({ back: webview.canGoBack?.() ?? false, forward: webview.canGoForward?.() ?? false })
      } catch {
        // Same attach / dom-ready rule as getURL.
      }
    }

    // Tell the strip what this Browser is showing, so its tab renames itself
    // like a tab anywhere else. Deliberately NOT written back into the tab's
    // target: the guest is built from `target.url`, so that would rebuild the
    // webview mid-navigation and throw away the history.
    const notePage = () => {
      if (target.kind !== 'url' || !tabId) {
        return
      }

      noteBrowserPage(tabId, guestPage(webview, liveUrlRef.current))
    }

    const onNavigate = (event: Event) => {
      const detail = event as Event & { url?: string }

      if (detail.url) {
        setLoadError(null)
        setCurrentUrl(detail.url)
      }

      notePage()

      // Ask the webview rather than counting navigations: the guest page can
      // move itself (redirects, history.pushState, a link into a new document),
      // so it is the only thing that knows what its history holds. Wired to
      // `did-navigate-in-page` too, or SPA route changes never update it.
      syncHistory()
    }

    const onFail = (event: Event) => {
      const detail = event as Event & {
        errorCode?: number
        errorDescription?: string
        isMainFrame?: boolean
        validatedURL?: string
      }

      const errorCode = detail.errorCode

      // Electron emits did-fail-load for subframes too. A blocked ad or
      // tracking iframe must not replace an otherwise healthy top-level page.
      if (detail.isMainFrame === false || errorCode === -3) {
        return
      }

      appendConsoleEntry({
        level: 3,
        message: copy.loadFailedConsole(errorCode, detail.errorDescription || detail.validatedURL || copy.unknownError)
      })
      setLoadError({
        code: errorCode,
        description: detail.errorDescription || copy.unreachableDescription,
        url: detail.validatedURL || guestPage(webview, liveUrlRef.current).url
      })
      setLoading(false)
    }

    const onStart = () => setLoading(true)

    const onStop = () => {
      setLoading(false)
      // A load that ends without a `did-navigate` (an in-place reload, a
      // cancelled navigation) still settles the history — resync so the
      // buttons can't be left stale.
      syncHistory()
      notePage()
    }

    // #101880: arm the print guard for every new guest document — a fresh
    // load gets a fresh window object, so the stub must be re-injected.
    const armPrintGuard = () => {
      void webview.executeJavaScript?.(PREVIEW_PRINT_GUARD_SCRIPT)?.catch(() => {
        // Guest tore down mid-arm (a navigation raced the injection) — the
        // next dom-ready arms it again.
      })
    }

    // The WEBVIEW is the source of truth for DevTools, not our click handler:
    // closing the DevTools window itself fires devtools-closed with no click,
    // and the glyph was left stuck "on" when we tracked it locally.
    const onDevToolsOpened = () => setDevtoolsOpen(true)
    const onDevToolsClosed = () => setDevtoolsOpen(false)

    // Right-clicks INSIDE the guest page. The tag surfaces Chromium's full
    // context-menu params (link, image, editable, selection, spellcheck), so
    // the app coordinator renders the same translated menu it shows
    // everywhere else.
    //
    // Coordinates: params.x/y are WINDOW-relative device-independent pixels
    // — the guest offset is already included, and CSS values are multiplied
    // by the window zoom factor. Measured live (zoom 0.9): a click whose
    // true window CSS point was (901, 272) arrived as params (811, 246) =
    // (901*0.9, 272*0.9). Dividing by the zoom factor recovers CSS
    // coordinates; adding the webview rect on top double-counted the offset
    // and dropped the menu far right+below the click.
    const onGuestContextMenu = (event: Event) => {
      const detail = event as Event & { params?: GuestContextMenuParams }
      const params = detail.params

      if (!params) {
        return
      }

      const zoom = window.hermesDesktop?.zoom?.factor?.() || 1
      // Window CSS point of the click (the menu anchors here).
      const windowX = params.x / zoom
      const windowY = params.y / zoom
      // Guest CSS point (inspectElement wants coordinates INSIDE the page):
      // subtract the webview's own offset from the window point.
      const rect = webview.getBoundingClientRect()
      const guestX = Math.max(0, Math.round(windowX - rect.left))
      const guestY = Math.max(0, Math.round(windowY - rect.top))

      openGuestContextMenu(
        windowX,
        windowY,
        {
          dictionarySuggestions: Array.isArray(params.dictionarySuggestions) ? params.dictionarySuggestions : [],
          // Chromium's availability verdict for the edit verbs. Absent only
          // if a future Electron drops it — then everything stays enabled,
          // which is the pre-editFlags behavior, not a lockout.
          editFlags: {
            canCopy: params.editFlags?.canCopy ?? true,
            canCut: params.editFlags?.canCut ?? true,
            canPaste: params.editFlags?.canPaste ?? true,
            canSelectAll: params.editFlags?.canSelectAll ?? true
          },
          hasImageContents: Boolean(params.hasImageContents),
          isEditable: Boolean(params.isEditable),
          linkURL: params.linkURL || '',
          misspelledWord: params.misspelledWord || '',
          selectionText: params.selectionText || '',
          srcURL: params.srcURL || ''
        },
        {
          addToDictionary: (word: string) => {
            const webContentsId = webview.getWebContentsId?.()

            if (typeof webContentsId === 'number') {
              void window.hermesDesktop?.contextMenuGuestAddWord?.({ webContentsId, word })
            }
          },
          copyImage: () => void window.hermesDesktop?.contextMenuCopyImage?.(),
          // The tag's edit commands act on the focused webContents, and the
          // menu click just parked focus on the HOST body — measured live:
          // selectAll() with host focus selected the address bar + chat
          // instead of the page. Focus the webview first, every verb.
          editCommand: (command: 'copy' | 'cut' | 'paste' | 'selectAll') => {
            webview.focus()
            webview[command]?.()
          },
          inspectElement: () => webview.inspectElement?.(guestX, guestY),
          replaceMisspelling: (word: string) => webview.replaceMisspelling?.(word)
        }
      )
    }

    webview.addEventListener('console-message', onConsole)
    webview.addEventListener('ipc-message', onGuestExternal)
    webview.addEventListener('context-menu', onGuestContextMenu)
    webview.addEventListener('devtools-closed', onDevToolsClosed)
    webview.addEventListener('devtools-opened', onDevToolsOpened)
    webview.addEventListener('did-fail-load', onFail)
    webview.addEventListener('did-navigate', onNavigate)
    webview.addEventListener('did-navigate-in-page', onNavigate)
    webview.addEventListener('did-start-loading', onStart)
    webview.addEventListener('did-stop-loading', onStop)
    // SPAs title themselves long after the load settles, and a route change
    // renames the page without navigating at all.
    webview.addEventListener('page-title-updated', notePage)
    // #101880: never let a guest reach the native print panel.
    webview.addEventListener('dom-ready', armPrintGuard)
    webview.addEventListener('dom-ready', noteGuestReady)
    host.appendChild(webview)
    navigationRef.current = webview
    webviewRef.current = webview

    return () => {
      annotateLoopRef.current += 1

      if (navigationRef.current === webview) {
        navigationRef.current = null
      }

      if (webviewRef.current === webview) {
        webviewRef.current = null
      }

      webview.removeEventListener('console-message', onConsole)
      webview.removeEventListener('ipc-message', onGuestExternal)
      webview.removeEventListener('context-menu', onGuestContextMenu)
      webview.removeEventListener('devtools-closed', onDevToolsClosed)
      webview.removeEventListener('devtools-opened', onDevToolsOpened)
      webview.removeEventListener('did-fail-load', onFail)
      webview.removeEventListener('did-navigate', onNavigate)
      webview.removeEventListener('did-navigate-in-page', onNavigate)
      webview.removeEventListener('did-start-loading', onStart)
      webview.removeEventListener('did-stop-loading', onStop)
      webview.removeEventListener('page-title-updated', notePage)
      webview.removeEventListener('dom-ready', armPrintGuard)
      webview.removeEventListener('dom-ready', noteGuestReady)
      webview.remove()
      setAnnotate(session => (session.mode ? { ...endAnnotateMode(session), stack: emptyAnnotateStack() } : session))
    }
  }, [appendConsoleEntry, consoleState, copy, isRemoteHtml, isWebPreview, noteGuestReady, tabId, target.kind])

  // Steers the LIVE guest when the session opens a new URL (#120265): loadURL
  // keeps the webview instance (JS state, cookies, form data, scroll, refs,
  // console/annotate channels) where the effect above used to destroy and
  // rebuild it. Per-page state (annotate pins, console log, history) resets
  // around the load so nothing bleeds across pages. Skipped when the guest
  // already shows the address (an in-page navigation got there first).
  // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
  useEffect(() => {
    if (!isWebPreview || isRemoteHtml) {
      return
    }

    const navigation = navigationRef.current

    if (!navigation?.loadURL) {
      return
    }

    const nextUrl = targetUrlRef.current

    if (liveUrlRef.current === nextUrl) {
      return
    }

    annotateLoopRef.current += 1
    const guest = annotateGuest()

    if (guest) {
      void teardownAnnotateOverlay(guest).catch(() => undefined)
    }

    setDraftNote('')
    setAnnotate(emptyAnnotateSession())
    setLoadError(null)
    consoleState.reset()
    setHistory({ back: false, forward: false })
    setLoading(true)
    setCurrentUrl(nextUrl)
    void navigation.loadURL?.(nextUrl)?.catch((error: unknown) => {
      setLoadError({
        description: error instanceof Error ? error.message : copy.unreachableDescription,
        url: nextUrl
      })
      setLoading(false)
    })
  }, [annotateGuest, consoleState, copy.unreachableDescription, isRemoteHtml, isWebPreview, target.url])

  return (
    <aside
      className="relative flex h-full w-full min-w-0 flex-col overflow-hidden bg-transparent text-muted-foreground"
      onKeyDown={onPaneKeyDown}
      // Buttons 3/4 are a mouse's back/forward. Chromium delivers them to
      // the renderer as a normal mouse event inside the app's own chrome (the
      // guest page gets its own via `app-command` in main), and unhandled they
      // walk the HOST document's history. A browser tab keeps its own back button.
      onMouseDown={event => {
        if (!hostHas('appMouseHistoryButtons') || (event.button !== 3 && event.button !== 4)) {
          return
        }

        event.preventDefault()

        if (event.button === 3) {
          goBack()
        } else {
          goForward()
        }
      }}
      {...(usesWebview && tabId ? { [PREVIEW_BROWSER_ATTR]: tabId } : {})}
    >
      <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
        {!embedded && (
          <div className="pointer-events-none flex min-h-(--titlebar-height) items-center gap-1.5 border-b border-border/60 bg-background px-2 py-1">
            <div className="min-w-0 flex-1">
              <Tip label={copy.openTarget(currentUrl)}>
                <a
                  className="pointer-events-auto inline max-w-full truncate text-left text-xs font-medium text-foreground underline-offset-4 decoration-current/20 transition-colors hover:text-primary hover:underline"
                  href={isRemoteHtmlTarget ? undefined : currentUrl}
                  onClick={event => {
                    if (isRemoteHtmlTarget) {
                      event.preventDefault()
                      void openPreviewTargetInBrowser(target).catch(error => notifyError(error, t.preview.unavailable))
                    }
                  }}
                  rel="noreferrer"
                  target={isRemoteHtmlTarget ? undefined : '_blank'}
                >
                  {previewLabel || copy.fallbackTitle}
                </a>
              </Tip>
            </div>
          </div>
        )}

        {canRenderHtmlFile && renderMode !== 'source' && (
          <PreviewModeSwitcher
            active="rendered"
            modes={['rendered', 'source']}
            onSelect={mode => selectRenderMode(mode === 'source' ? 'source' : 'preview')}
          />
        )}

        {usesBrowserIframe && !isBlankPage && <PreviewBrowserFrameHint target={target} />}

        {usesWebview && (
          <PreviewBrowserBar
            annotateMode={annotate.mode}
            canGoBack={history.back}
            canGoForward={history.forward}
            commentCount={annotate.stack.pins.length}
            consoleOpen={consoleOpen}
            devToolsOpen={devtoolsOpen}
            loading={loading}
            onBack={goBack}
            onClose={onClose}
            onFlushComments={() => void flushComments()}
            onForward={goForward}
            onNavigate={navigateTo}
            onOpenExternal={
              !isBrowserWindow() && !canOpenBrowserWindow()
                ? () => void window.hermesDesktop?.openExternal(currentUrl)
                : undefined
            }
            onPopIn={isBrowserWindow() ? () => window.close() : undefined}
            onPopOut={
              target.kind !== 'url' || isBrowserWindow() || !tabId || !canOpenBrowserWindow()
                ? undefined
                : () => popOutBrowserTab(tabId)
            }
            onReload={reloadPreview}
            onToggleAnnotate={toggleAnnotate}
            onToggleConsole={() => consoleState.setOpen(open => !open)}
            onToggleDevTools={toggleDevTools}
            url={currentUrl}
          />
        )}

        {/* First-open real-profile consent offer — Browser tabs only (URL
            vessels the user browses with), never file/HTML previews. */}
        {target.kind === 'url' && tabId && <RealProfileConsentDialog tabId={tabId} />}

        <div
          className="pointer-events-auto relative min-h-0 flex-1 overflow-hidden bg-transparent"
          ref={previewContentRef}
        >
          <div
            className={cn(
              'absolute inset-0 flex bg-transparent',
              (isRemoteHtml || !isWebPreview || loadError) && 'pointer-events-none opacity-0'
            )}
            ref={hostRef}
          />
          {isRemoteHtml && (
            <PreviewDocumentFrame
              className="absolute inset-0 size-full border-0 bg-white"
              referrerPolicy="no-referrer"
              sandbox=""
              srcDoc={remoteHtmlDocument || ''}
              title={target.label || copy.fallbackTitle}
            />
          )}
          {!isWebPreview && (
            <PreviewDocumentBody
              onClose={onClose}
              onSelectRendered={canRenderHtmlFile ? () => selectRenderMode('preview') : undefined}
              reloadKey={localReloadKey}
              sessionId={sessionId}
              target={target}
            />
          )}
          {isBlankPage && (
            <div className="absolute inset-0 grid bg-background">
              <PanelEmpty description={copy.blankPageBody} icon="globe" />
            </div>
          )}
          {isWebPreview && loadError && (
            <PreviewLoadError
              consoleHeight={consoleOpen ? consoleHeight : 0}
              error={loadError}
              onRestartServer={target.kind === 'url' && onRestartServer ? () => void restartServer() : undefined}
              onRetry={reloadPreview}
              restarting={restartingServer}
            />
          )}

          {isWebPreview && annotate.draft ? (
            <PreviewAnnotateCard
              {...placeAnnotateCard({
                paneHeight: previewContentRef.current?.clientHeight || 360,
                paneWidth: previewContentRef.current?.clientWidth || 360,
                rect: annotate.draft.rect
              })}
              note={draftNote}
              number={annotate.stack.nextNumber}
              onCancel={() => void cancelAnnotateDraft()}
              onChange={setDraftNote}
              onSave={() => void saveAnnotateDraft()}
              placeholder={copy.commentPlaceholder}
              saveLabel={copy.saveComment}
              title={copy.commentTitle(annotate.stack.nextNumber)}
            />
          ) : null}

          {usesWebview && consoleOpen && (
            <PreviewConsolePanel
              consoleBodyRef={consoleBodyRef}
              consoleShouldStickRef={consoleShouldStickRef}
              consoleState={consoleState}
              startConsoleResize={startConsoleResize}
            />
          )}
        </div>
      </div>
    </aside>
  )
}