Skip to content

The agent that grows with you

fix(desktop): route pop-out browser annotations to origin

Miguel Chaves809b1aa50b43
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index ad3ed938808..09bd7958b8a 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -15454,6 +15454,20 @@ ipcMain.handle('hermes:window:openBrowser', async (_event, tabId) => {
return { ok: true }
})
+// Browser Comment Mode handoff between renderer windows. The Browser pop-out
+// and the chat that opened it are separate renderers; packaged `file://`
+// windows must not depend on BroadcastChannel origin semantics. Main only
+// relays opaque payloads to the other Hermes windows. Destination validation
+// and ACK correlation remain renderer-side, so a stale target still fails
+// closed rather than falling through to another composer.
+ipcMain.on('hermes:preview-annotate:relay', (event, payload) => {
+ for (const other of BrowserWindow.getAllWindows()) {
+ if (!other.isDestroyed() && other.webContents.id !== event.sender.id) {
+ other.webContents.send('hermes:preview-annotate:relay', payload)
+ }
+ }
+})
+
// Hand a session to the user's OWN terminal emulator, running the TUI against
// it (`hermes --tui --resume <id>`). Not the in-app terminal pane: the point is
// to continue the chat in the terminal they already live in.
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index ecb076b4028..6e4a45ab8e3 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -52,6 +52,15 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
openSessionInTerminal: (sessionId, opts) => ipcRenderer.invoke('hermes:window:openInTerminal', sessionId, opts),
openWindow: (options?: DesktopProfileRoute) => ipcRenderer.invoke('hermes:window:openInstance', options),
openBrowserWindow: tabId => ipcRenderer.invoke('hermes:window:openBrowser', tabId),
+ previewAnnotate: {
+ send: payload => ipcRenderer.send('hermes:preview-annotate:relay', payload),
+ onMessage: callback => {
+ const listener = (_event, payload) => callback(payload)
+ ipcRenderer.on('hermes:preview-annotate:relay', listener)
+
+ return () => ipcRenderer.removeListener('hermes:preview-annotate:relay', listener)
+ }
+ },
onBrowserPopoutClosed: callback => {
const listener = (_event, tabId) => callback(tabId)
ipcRenderer.on('hermes:browser-popout:closed', listener)
diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.ts
index 5ce7895965d..3c7f5a20da8 100644
--- a/apps/desktop/src/app/chat/composer/focus.ts
+++ b/apps/desktop/src/app/chat/composer/focus.ts
@@ -12,6 +12,8 @@
import { isElementInHiddenPane, queryAllVisible, queryVisible } from '@/components/pane-shell/pane-visibility'
import { $hoveredTreeGroup } from '@/components/pane-shell/tree/store'
+import { subscribePreviewAnnotateHandoff } from '@/lib/preview-annotate/handoff'
+import { dataUrlToBlob } from '@/lib/preview-annotate/pack'
import { $floatingComposerOwner } from './floating-state'
import type { InlineRefInput } from './inline-refs'
@@ -632,6 +634,33 @@ export const requestComposerSubmit = (
return true
}
+// A popped-out Browser is a separate renderer, so its Comment Mode cannot use
+// this file's window-local CustomEvent bus directly. The source renderer pins
+// an exact target + surface id before opening the pop-out; accept the batch only
+// while that exact surface is still visible. Never fall through to `active`.
+subscribePreviewAnnotateHandoff(async request => {
+ if (request.destination.kind !== 'composer') {
+ return null
+ }
+
+ const { surfaceId, target } = request.destination
+ const typedTarget = target as ComposerTarget
+ const surface = queryVisible<HTMLElement>(`[data-composer-target="${cssEscape(typedTarget)}"]`)
+
+ if (!surface || surface.dataset.composerSurfaceId !== surfaceId) {
+ return { error: 'The original chat composer is no longer visible.', ok: false }
+ }
+
+ for (const image of request.images) {
+ requestComposerAttachImages([dataUrlToBlob(image.dataUrl)], { target: typedTarget })
+ }
+
+ requestComposerInsert(request.prompt, { mode: 'block', target: typedTarget })
+ requestComposerFocus(typedTarget)
+
+ return { ok: true }
+})
+
export const onComposerSubmitRequest = (handler: (detail: SubmitDetail) => void) =>
subscribe<SubmitDetail>(SUBMIT_EVENT, handler)
diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
index 0ab3a94b6cb..f16d0618a77 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
@@ -26,6 +26,7 @@ import {
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'
@@ -555,17 +556,34 @@ export function PreviewPane({
const guest = annotateGuest()
- await flushAnnotateStack(
- pins,
- {
- attachImage: blob => {
- requestComposerAttachImages([blob])
+ 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' })
},
- insertText: text => requestComposerInsert(text, { mode: 'block' })
- },
- currentUrl
- )
- requestComposerFocus()
+ currentUrl
+ )
+ requestComposerFocus()
+ }
+
setAnnotate(session => ({ ...session, draft: null, stack: clearAnnotatePins(session.stack) }))
setDraftNote('')
@@ -573,7 +591,7 @@ export function PreviewPane({
await hideAnnotateDraft(guest).catch(() => undefined)
await syncAnnotatePins(guest, []).catch(() => undefined)
}
- }, [annotateGuest, currentUrl])
+ }, [annotateGuest, copy.annotate, currentUrl, tabId])
const startAnnotate = useCallback(async () => {
const guest = annotateGuest()
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 9beb8e2d39a..f4a3ad7611f 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -95,6 +95,13 @@ declare global {
// `tabId` is the `$previewTabs` id; closing the window fires
// `onBrowserPopoutClosed` so the caller can dock the tab again.
openBrowserWindow: (tabId: string) => Promise<{ ok: boolean; error?: string }>
+ // Cross-window Browser Comment Mode transport. Electron main relays
+ // payloads to the other Hermes renderer windows; renderer code keeps the
+ // destination exact and rejects anything not addressed to its window.
+ previewAnnotate?: {
+ send: (payload: unknown) => void
+ onMessage: (callback: (payload: unknown) => void) => () => void
+ }
onBrowserPopoutClosed: (callback: (tabId: string) => void) => () => void
// Claim a one-shot cross-window ambient cue (turn-end sound / spoken
// reply). Resolves true for the first window to claim a key, false for
diff --git a/apps/desktop/src/lib/preview-annotate/handoff.test.ts b/apps/desktop/src/lib/preview-annotate/handoff.test.ts
new file mode 100644
index 00000000000..5dd80e9bb9d
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/handoff.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { $workspaceOwnerKey } from '@/components/pane-shell/workspace-scope'
+
+import { capturePreviewAnnotateDestination } from './handoff'
+
+const groupSurface = (group: string, composerKey: string, ownerKey: string) => {
+ const element = document.createElement('div')
+ element.dataset.previewAnnotateDestination = 'group'
+ element.dataset.previewAnnotateGroup = group
+ element.dataset.previewAnnotateComposerKey = composerKey
+ element.dataset.previewAnnotateOwnerKey = ownerKey
+ document.body.append(element)
+
+ return element
+}
+
+const withRect = (element: Element, left: number, top: number, width: number, height: number) => {
+ Object.defineProperty(element, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({
+ bottom: top + height,
+ height,
+ left,
+ right: left + width,
+ top,
+ width,
+ x: left,
+ y: top,
+ toJSON: () => ({})
+ })
+ })
+}
+
+beforeEach(() => {
+ document.body.innerHTML = ''
+ window.sessionStorage.clear()
+ $workspaceOwnerKey.set(null)
+})
+
+describe('capturePreviewAnnotateDestination', () => {
+ it('pins the group owned by the active workspace when multiple groups are visible', () => {
+ groupSurface('Sales', 'id:sales', 'group:sales')
+ groupSurface('Design', 'id:design', 'group:design')
+ $workspaceOwnerKey.set('group:design')
+
+ const destination = capturePreviewAnnotateDestination()
+
+ expect(destination).toMatchObject({
+ composerKey: 'id:design',
+ group: 'Design',
+ kind: 'group'
+ })
+ })
+
+ it('pins the visible group nearest the Browser pop-out control when rooms are side by side', () => {
+ const sales = groupSurface('Sales', 'id:sales', 'group:sales')
+ const design = groupSurface('Design', 'id:design', 'group:design')
+ const popOut = document.createElement('button')
+
+ document.body.append(popOut)
+ withRect(sales, 100, 0, 500, 700)
+ withRect(design, 620, 0, 500, 700)
+ withRect(popOut, 1160, 40, 24, 24)
+ $workspaceOwnerKey.set('group:sales')
+
+ const destination = capturePreviewAnnotateDestination(popOut)
+
+ expect(destination).toMatchObject({
+ composerKey: 'id:design',
+ group: 'Design',
+ kind: 'group'
+ })
+ })
+
+ it('fails closed instead of choosing the first group when several are visible and no owner matches', () => {
+ groupSurface('Sales', 'id:sales', 'group:sales')
+ groupSurface('Design', 'id:design', 'group:design')
+
+ expect(capturePreviewAnnotateDestination()).toBeNull()
+ })
+})
diff --git a/apps/desktop/src/lib/preview-annotate/handoff.ts b/apps/desktop/src/lib/preview-annotate/handoff.ts
new file mode 100644
index 00000000000..5841eb6ede1
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/handoff.ts
@@ -0,0 +1,524 @@
+import { queryAllVisible, queryVisible } from '@/components/pane-shell/pane-visibility'
+import { $workspaceOwnerKey } from '@/components/pane-shell/workspace-scope'
+
+import { annotateFlushPrompt, packageAnnotateStack } from './pack'
+import type { AnnotatePin } from './stack'
+
+/**
+ * Cross-window handoff for Browser Comment Mode.
+ *
+ * A popped-out Browser is a separate Electron renderer. The ordinary composer
+ * bus is intentionally window-local, so an annotation saved in that renderer
+ * cannot reach the chat/group composer that opened the Browser. This bridge
+ * pins the destination at pop-out time and relays payload/ack messages through
+ * Electron IPC when available, with BroadcastChannel as a browser/dev fallback. The destination is exact and fail-closed:
+ * a stale/missing owner never falls through to whatever composer happens to be
+ * active later.
+ */
+
+export const PREVIEW_ANNOTATE_HANDOFF_CHANNEL = 'hermes.desktop.preview-annotate-handoff.v1'
+export const PREVIEW_ANNOTATE_WINDOW_ID_KEY = 'hermes.desktop.previewAnnotate.windowId'
+
+const DESTINATION_PREFIX = 'hermes.desktop.previewAnnotate.destination.v1:'
+const DESTINATION_MAX_AGE_MS = 24 * 60 * 60 * 1000
+
+export interface PreviewAnnotateComposerDestination {
+ kind: 'composer'
+ surfaceId: string
+ target: string
+ windowId: string
+}
+
+export interface PreviewAnnotateGroupDestination {
+ composerKey: string
+ group: string
+ kind: 'group'
+ windowId: string
+}
+
+export type PreviewAnnotateDestination = PreviewAnnotateComposerDestination | PreviewAnnotateGroupDestination
+
+interface StoredDestination {
+ at: number
+ destination: PreviewAnnotateDestination
+ version: 1
+}
+
+export interface PreviewAnnotateHandoffImage {
+ dataUrl: string
+ name: string
+ number: number
+}
+
+export interface PreviewAnnotateHandoffRequest {
+ count: number
+ destination: PreviewAnnotateDestination
+ images: PreviewAnnotateHandoffImage[]
+ prompt: string
+ requestId: string
+ tabId: string
+ type: 'preview-annotate-handoff'
+}
+
+export interface PreviewAnnotateHandoffAck {
+ error?: string
+ ok: boolean
+ requestId: string
+ type: 'preview-annotate-handoff-ack'
+}
+
+export interface PreviewAnnotateHandoffResult {
+ error?: string
+ ok: boolean
+}
+
+const randomId = () =>
+ globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
+
+/** One id per renderer window. sessionStorage is deliberately window-scoped. */
+export function previewAnnotateWindowId(): string {
+ if (typeof window === 'undefined') {
+ return 'server'
+ }
+
+ try {
+ const existing = window.sessionStorage.getItem(PREVIEW_ANNOTATE_WINDOW_ID_KEY)?.trim()
+
+ if (existing) {
+ return existing
+ }
+
+ const created = randomId()
+ window.sessionStorage.setItem(PREVIEW_ANNOTATE_WINDOW_ID_KEY, created)
+
+ return created
+ } catch {
+ // sessionStorage can be disabled. Keep the id stable for this module load.
+ return fallbackWindowId
+ }
+}
+
+const fallbackWindowId = randomId()
+
+/**
+ * Capture the exact surface that should receive Browser comments.
+ * Group rooms opt in with data attributes because their New Thread composer is
+ * not part of the ordinary chat composer bus.
+ */
+function rectDistance(a: DOMRect, b: DOMRect): number {
+ const dx = Math.max(a.left - b.right, b.left - a.right, 0)
+ const dy = Math.max(a.top - b.bottom, b.top - a.bottom, 0)
+
+ if (dx || dy) {
+ return Math.hypot(dx, dy)
+ }
+
+ const ax = (a.left + a.right) / 2
+ const ay = (a.top + a.bottom) / 2
+ const bx = (b.left + b.right) / 2
+ const by = (b.top + b.bottom) / 2
+
+ return Math.hypot(ax - bx, ay - by)
+}
+
+function nearestGroupToAnchor(groups: HTMLElement[], anchor: Element | null): HTMLElement | undefined {
+ if (!anchor || groups.length < 2 || typeof anchor.getBoundingClientRect !== 'function') {
+ return undefined
+ }
+
+ const anchorRect = anchor.getBoundingClientRect()
+
+ if (!anchorRect.width && !anchorRect.height) {
+ return undefined
+ }
+
+ return groups
+ .map(group => ({ distance: rectDistance(group.getBoundingClientRect(), anchorRect), group }))
+ .sort((a, b) => a.distance - b.distance)[0]?.group
+}
+
+export function capturePreviewAnnotateDestination(anchor: Element | null = null): PreviewAnnotateDestination | null {
+ if (typeof document === 'undefined') {
+ return null
+ }
+
+ const visibleGroups = queryAllVisible<HTMLElement>('[data-preview-annotate-destination="group"]')
+ const workspaceOwnerKey = $workspaceOwnerKey.get()
+
+ // The Browser lives in its own right-rail zone, while multiple group rooms
+ // can be visible side by side. The global workspace owner can therefore
+ // still point at the *other* room when the user clicks the Browser's Pop out
+ // glyph. Prefer the room physically nearest that glyph; this binds the
+ // Browser to the pane it is actually sitting beside. Fall back to the
+ // workspace owner for keyboard/context-menu opens where no useful anchor is
+ // available, and fail closed rather than picking the first visible room.
+ const group =
+ nearestGroupToAnchor(visibleGroups, anchor) ??
+ (workspaceOwnerKey
+ ? visibleGroups.find(item => item.dataset.previewAnnotateOwnerKey === workspaceOwnerKey)
+ : undefined) ??
+ (visibleGroups.length === 1 ? visibleGroups[0] : undefined)
+
+ const groupName = group?.dataset.previewAnnotateGroup?.trim()
+ const composerKey = group?.dataset.previewAnnotateComposerKey?.trim()
+
+ if (groupName && composerKey) {
+ return {
+ composerKey,
+ group: groupName,
+ kind: 'group',
+ windowId: previewAnnotateWindowId()
+ }
+ }
+
+ const composer = queryVisible<HTMLElement>('[data-composer-target]')
+ const target = composer?.dataset.composerTarget?.trim()
+ const surfaceId = composer?.dataset.composerSurfaceId?.trim()
+
+ if (target && surfaceId) {
+ return {
+ kind: 'composer',
+ surfaceId,
+ target,
+ windowId: previewAnnotateWindowId()
+ }
+ }
+
+ return null
+}
+
+const destinationKey = (tabId: string) => `${DESTINATION_PREFIX}${tabId}`
+
+export function rememberPreviewAnnotateDestination(tabId: string, destination: PreviewAnnotateDestination | null) {
+ if (typeof window === 'undefined' || !tabId) {
+ return
+ }
+
+ try {
+ if (!destination) {
+ window.localStorage.removeItem(destinationKey(tabId))
+
+ return
+ }
+
+ const record: StoredDestination = { at: Date.now(), destination, version: 1 }
+ window.localStorage.setItem(destinationKey(tabId), JSON.stringify(record))
+ } catch {
+ // The pop-out still opens; Add comments will fail closed with guidance.
+ }
+}
+
+export function clearPreviewAnnotateDestination(tabId: string) {
+ if (typeof window === 'undefined' || !tabId) {
+ return
+ }
+
+ try {
+ window.localStorage.removeItem(destinationKey(tabId))
+ } catch {
+ /* storage unavailable */
+ }
+}
+
+function isDestination(value: unknown): value is PreviewAnnotateDestination {
+ if (!value || typeof value !== 'object') {
+ return false
+ }
+
+ const row = value as Record<string, unknown>
+
+ if (row.kind === 'group') {
+ return (
+ typeof row.windowId === 'string' &&
+ typeof row.group === 'string' &&
+ typeof row.composerKey === 'string' &&
+ Boolean(row.windowId.trim() && row.group.trim() && row.composerKey.trim())
+ )
+ }
+
+ return (
+ row.kind === 'composer' &&
+ typeof row.windowId === 'string' &&
+ typeof row.target === 'string' &&
+ typeof row.surfaceId === 'string' &&
+ Boolean(row.windowId.trim() && row.target.trim() && row.surfaceId.trim())
+ )
+}
+
+export function readPreviewAnnotateDestination(tabId: string): PreviewAnnotateDestination | null {
+ if (typeof window === 'undefined' || !tabId) {
+ return null
+ }
+
+ try {
+ const raw = window.localStorage.getItem(destinationKey(tabId))
+
+ if (!raw) {
+ return null
+ }
+
+ const record = JSON.parse(raw) as Partial<StoredDestination>
+
+ if (
+ record.version !== 1 ||
+ typeof record.at !== 'number' ||
+ Date.now() - record.at > DESTINATION_MAX_AGE_MS ||
+ !isDestination(record.destination)
+ ) {
+ clearPreviewAnnotateDestination(tabId)
+
+ return null
+ }
+
+ return record.destination
+ } catch {
+ return null
+ }
+}
+
+const isAck = (value: unknown): value is PreviewAnnotateHandoffAck => {
+ if (!value || typeof value !== 'object') {
+ return false
+ }
+
+ const row = value as Record<string, unknown>
+
+ return row.type === 'preview-annotate-handoff-ack' && typeof row.requestId === 'string' && typeof row.ok === 'boolean'
+}
+
+export function isPreviewAnnotateHandoffRequest(value: unknown): value is PreviewAnnotateHandoffRequest {
+ if (!value || typeof value !== 'object') {
+ return false
+ }
+
+ const row = value as Record<string, unknown>
+
+ return (
+ row.type === 'preview-annotate-handoff' &&
+ typeof row.requestId === 'string' &&
+ typeof row.tabId === 'string' &&
+ typeof row.prompt === 'string' &&
+ typeof row.count === 'number' &&
+ Array.isArray(row.images) &&
+ isDestination(row.destination)
+ )
+}
+
+/** Register one exact destination receiver in this renderer window. */
+export function subscribePreviewAnnotateHandoff(
+ handler: (
+ request: PreviewAnnotateHandoffRequest
+ ) => PreviewAnnotateHandoffResult | null | Promise<PreviewAnnotateHandoffResult | null>
+): () => void {
+ const desktopBridge = typeof window !== 'undefined' ? window.hermesDesktop?.previewAnnotate : undefined
+
+ if (desktopBridge?.onMessage && desktopBridge.send) {
+ return desktopBridge.onMessage(payload => {
+ if (!isPreviewAnnotateHandoffRequest(payload)) {
+ return
+ }
+
+ const request = payload
+
+ if (request.destination.windowId !== previewAnnotateWindowId()) {
+ return
+ }
+
+ void Promise.resolve(handler(request))
+ .then(result => {
+ if (!result) {
+ return
+ }
+
+ const ack: PreviewAnnotateHandoffAck = {
+ ...(result.error ? { error: result.error } : {}),
+ ok: result.ok,
+ requestId: request.requestId,
+ type: 'preview-annotate-handoff-ack'
+ }
+
+ desktopBridge.send(ack)
+ })
+ .catch(error => {
+ desktopBridge.send({
+ error: error instanceof Error ? error.message : String(error),
+ ok: false,
+ requestId: request.requestId,
+ type: 'preview-annotate-handoff-ack'
+ } satisfies PreviewAnnotateHandoffAck)
+ })
+ })
+ }
+
+ if (typeof BroadcastChannel === 'undefined') {
+ return () => undefined
+ }
+
+ const channel = new BroadcastChannel(PREVIEW_ANNOTATE_HANDOFF_CHANNEL)
+
+ const listener = (event: MessageEvent<unknown>) => {
+ if (!isPreviewAnnotateHandoffRequest(event.data)) {
+ return
+ }
+
+ const request = event.data
+
+ if (request.destination.windowId !== previewAnnotateWindowId()) {
+ return
+ }
+
+ void Promise.resolve(handler(request))
+ .then(result => {
+ if (!result) {
+ return
+ }
+
+ const ack: PreviewAnnotateHandoffAck = {
+ ...(result.error ? { error: result.error } : {}),
+ ok: result.ok,
+ requestId: request.requestId,
+ type: 'preview-annotate-handoff-ack'
+ }
+
+ channel.postMessage(ack)
+ })
+ .catch(error => {
+ const ack: PreviewAnnotateHandoffAck = {
+ error: error instanceof Error ? error.message : String(error),
+ ok: false,
+ requestId: request.requestId,
+ type: 'preview-annotate-handoff-ack'
+ }
+
+ channel.postMessage(ack)
+ })
+ }
+
+ channel.addEventListener('message', listener)
+
+ return () => {
+ channel.removeEventListener('message', listener)
+ channel.close()
+ }
+}
+
+/** Send one saved comment batch back to the renderer that owned the pop-out. */
+export async function handoffPreviewAnnotateStack(
+ tabId: string,
+ pins: readonly AnnotatePin[],
+ pageUrl?: string
+): Promise<PreviewAnnotateHandoffResult> {
+ if (!pins.length) {
+ return { ok: true }
+ }
+
+ const destination = readPreviewAnnotateDestination(tabId)
+
+ if (!destination) {
+ return {
+ error:
+ 'The Browser pop-out has no pinned chat destination. Pop it back in, open it again from the target chat, and retry.',
+ ok: false
+ }
+ }
+
+ if (typeof BroadcastChannel === 'undefined') {
+ return { error: 'Cross-window comment handoff is unavailable in this renderer.', ok: false }
+ }
+
+ const items = packageAnnotateStack(pins)
+ const requestId = randomId()
+
+ const request: PreviewAnnotateHandoffRequest = {
+ count: items.length,
+ destination,
+ images: items
+ .filter(item => Boolean(item.imageDataUrl))
+ .map(item => ({ dataUrl: item.imageDataUrl, name: `Comment_${item.number}.png`, number: item.number })),
+ prompt: annotateFlushPrompt(items, pageUrl),
+ requestId,
+ tabId,
+ type: 'preview-annotate-handoff'
+ }
+
+ const desktopBridge = typeof window !== 'undefined' ? window.hermesDesktop?.previewAnnotate : undefined
+
+ if (desktopBridge?.onMessage && desktopBridge.send) {
+ return new Promise(resolve => {
+ let settled = false
+
+ const finish = (result: PreviewAnnotateHandoffResult) => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ window.clearTimeout(timer)
+ stop()
+ resolve(result)
+ }
+
+ const stop = desktopBridge.onMessage(payload => {
+ if (!isAck(payload) || payload.requestId !== requestId) {
+ return
+ }
+
+ finish({ ...(payload.error ? { error: payload.error } : {}), ok: payload.ok })
+ })
+
+ const timer = window.setTimeout(
+ () =>
+ finish({
+ error: 'The original chat did not accept the comments. Keep the annotations and reopen the target chat.',
+ ok: false
+ }),
+ 4000
+ )
+
+ try {
+ desktopBridge.send(request)
+ } catch (error) {
+ finish({ error: error instanceof Error ? error.message : String(error), ok: false })
+ }
+ })
+ }
+
+ return new Promise(resolve => {
+ const channel = new BroadcastChannel(PREVIEW_ANNOTATE_HANDOFF_CHANNEL)
+ let settled = false
+
+ const finish = (result: PreviewAnnotateHandoffResult) => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ window.clearTimeout(timer)
+ channel.close()
+ resolve(result)
+ }
+
+ channel.addEventListener('message', event => {
+ if (!isAck(event.data) || event.data.requestId !== requestId) {
+ return
+ }
+
+ finish({ ...(event.data.error ? { error: event.data.error } : {}), ok: event.data.ok })
+ })
+
+ const timer = window.setTimeout(
+ () =>
+ finish({
+ error: 'The original chat did not accept the comments. Keep the annotations and reopen the target chat.',
+ ok: false
+ }),
+ 4000
+ )
+
+ try {
+ channel.postMessage(request)
+ } catch (error) {
+ finish({ error: error instanceof Error ? error.message : String(error), ok: false })
+ }
+ })
+}
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
index 2a9aafe9b68..434c29f2bd0 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
@@ -622,6 +622,124 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
pendingAttachments: typeof value === 'function' ? value(current.pendingAttachments || {}) : value
}))
+ // Browser Comment Mode can live in its own Electron pop-out on another
+ // monitor. The ordinary composer bus is window-local and this room uses its
+ // own New Thread composer anyway, so accept only batches explicitly pinned to
+ // THIS room + THIS renderer. Packaged Electron windows use the preload IPC
+ // relay; BroadcastChannel stays only as a browser/dev fallback. The protocol
+ // strings remain literal here to preserve the plugin fence (Bot Mode imports
+ // only the SDK + its own files). A stale route gets no ACK, leaving the
+ // annotations intact.
+ useEffect(() => {
+ if (typeof window === 'undefined') {
+ return
+ }
+
+ const desktopBridge = window.hermesDesktop?.previewAnnotate
+
+ const channel =
+ !desktopBridge && typeof BroadcastChannel !== 'undefined'
+ ? new BroadcastChannel('hermes.desktop.preview-annotate-handoff.v1')
+ : null
+
+ if (!desktopBridge && !channel) {
+ return
+ }
+
+ const send = (payload: unknown) => {
+ if (desktopBridge) {
+ desktopBridge.send(payload)
+ } else {
+ channel?.postMessage(payload)
+ }
+ }
+
+ const onMessage = (data: unknown) => {
+ if (!data || typeof data !== 'object') {
+ return
+ }
+
+ const request = data as {
+ count?: unknown
+ destination?: { composerKey?: unknown; group?: unknown; kind?: unknown; windowId?: unknown }
+ images?: unknown
+ prompt?: unknown
+ requestId?: unknown
+ type?: unknown
+ }
+
+ const destination = request.destination
+ const sourceWindowId = window.sessionStorage.getItem('hermes.desktop.previewAnnotate.windowId')?.trim()
+
+ if (
+ !sourceWindowId ||
+ request.type !== 'preview-annotate-handoff' ||
+ typeof request.requestId !== 'string' ||
+ typeof request.prompt !== 'string' ||
+ !Array.isArray(request.images) ||
+ destination?.kind !== 'group' ||
+ destination.windowId !== sourceWindowId ||
+ destination.group !== group ||
+ destination.composerKey !== composerKeyRef.current
+ ) {
+ return
+ }
+
+ try {
+ const prompt = request.prompt
+
+ const attachments: Attachment[] = request.images
+ .filter((image): image is { dataUrl: string; name: string; number?: number } =>
+ Boolean(
+ image &&
+ typeof image === 'object' &&
+ typeof (image as { dataUrl?: unknown }).dataUrl === 'string' &&
+ typeof (image as { name?: unknown }).name === 'string'
+ )
+ )
+ .map(image => ({ data: image.dataUrl, kind: 'image' as const, name: image.name }))
+
+ const next = updateGroupComposerDraft(composerKeyRef.current, current => ({
+ ...current,
+ activeReplyThread: null,
+ main: current.main.trim() ? `${current.main.trimEnd()}\n\n${prompt}` : prompt,
+ pendingAttachments: {
+ ...(current.pendingAttachments || {}),
+ main: [...(current.pendingAttachments?.main || []), ...attachments]
+ }
+ }))
+
+ setComposerDraft(next)
+ host.notify({
+ kind: 'success',
+ message: `${Number(request.count) || attachments.length} Browser comment${Number(request.count) === 1 ? '' : 's'} added to ${group}. Review the New Thread draft before sending.`
+ })
+ send({
+ ok: true,
+ requestId: request.requestId,
+ type: 'preview-annotate-handoff-ack'
+ })
+ } catch (error) {
+ send({
+ error: error instanceof Error ? error.message : String(error),
+ ok: false,
+ requestId: request.requestId,
+ type: 'preview-annotate-handoff-ack'
+ })
+ }
+ }
+
+ const stopDesktop = desktopBridge?.onMessage(onMessage)
+ const onBroadcast = (event: MessageEvent<unknown>) => onMessage(event.data)
+ channel?.addEventListener('message', onBroadcast)
+
+ return () => {
+ stopDesktop?.()
+ channel?.removeEventListener('message', onBroadcast)
+ channel?.close()
+ }
+ }, [composerKey, group])
+
const [confirmDisband, setConfirmDisband] = useState(false)
const [settingsOpen, setSettingsOpen] = useState(false)
const [memberPickerOpen, setMemberPickerOpen] = useState(false)
@@ -1313,6 +1431,10 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
return (
<div
className="relative flex h-full flex-col"
+ data-preview-annotate-composer-key={composerKey}
+ data-preview-annotate-destination="group"
+ data-preview-annotate-group={group}
+ data-preview-annotate-owner-key={groupWorkspaceOwnerKey(group)}
onDragLeave={event => {
// Only clear when leaving the room container itself, not when the
// cursor moves between its children. React types relatedTarget as a
diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.ts
index bd8ef32fce1..5377eb529a6 100644
--- a/apps/desktop/src/store/preview.ts
+++ b/apps/desktop/src/store/preview.ts
@@ -1,6 +1,11 @@
import { atom, computed } from 'nanostores'
import { dismissTreePane, isPaneVisible } from '@/components/pane-shell/tree/store'
+import {
+ capturePreviewAnnotateDestination,
+ clearPreviewAnnotateDestination,
+ rememberPreviewAnnotateDestination
+} from '@/lib/preview-annotate/handoff'
import { readJson, writeKey } from '@/lib/storage'
import { normalize } from '@/lib/text'
@@ -492,6 +497,13 @@ export function popOutBrowserTab(tabId: string) {
const page = $browserPages.get()[tabId]
+ // Pin the exact chat/group surface that owns this Browser before the new
+ // renderer opens. Comment Mode in the pop-out uses this route to hand its
+ // saved batch back without guessing from whichever composer is active later.
+ const anchor =
+ typeof document !== 'undefined' && document.activeElement instanceof Element ? document.activeElement : null
+
+ rememberPreviewAnnotateDestination(tabId, capturePreviewAnnotateDestination(anchor))
markBrowserTabPopped(tabId, true)
commitBrowserTabLocation(tabId, page?.url || tab.target.url, page?.title)
void openBrowserInNewWindow(tabId).then(ok => {
@@ -519,6 +531,7 @@ export function markBrowserTabPopped(tabId: string, popped: boolean) {
next.add(tabId)
} else {
next.delete(tabId)
+ clearPreviewAnnotateDestination(tabId)
}
$poppedBrowserTabIds.set(next)