Skip to content

The agent that grows with you

feat(desktop): add comment mode to the in-app browser

Adolanium10f2a209660a
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index e2b76819726..ea8f06a894d 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -31,6 +31,7 @@ import {
} from 'electron'
import { classifyActiveRuntime } from './active-runtime-state'
+import { capturePreviewContents } from './preview-capture'
import { destroyKeepaliveAgents, downloadAgentFor, jsonAgentFor, withRetry } from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate } from './backend-child'
@@ -5854,7 +5855,7 @@ async function saveImageFromUrl(rawUrl) {
return true
}
-async function writeComposerImage(buffer, ext = '.png') {
+async function writeComposerImage(buffer, ext = '.png', name = '') {
const rawExt = String(ext || '.png')
.trim()
.toLowerCase()
@@ -5865,7 +5866,16 @@ async function writeComposerImage(buffer, ext = '.png') {
await fs.promises.mkdir(dir, { recursive: true })
const stamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').replace('Z', '')
const random = crypto.randomBytes(3).toString('hex')
- const filePath = path.join(dir, `composer_${stamp}_${random}${safeExt}`)
+ const baseName = String(name || '')
+ .split(/[\\/]/)
+ .pop()
+ ?.replace(/\.[^.]+$/, '')
+ const safeName = (baseName || '')
+ .replace(/[^\p{L}\p{N}._-]+/gu, '_')
+ .replace(/^[._-]+|[._-]+$/g, '')
+ .slice(0, 80)
+ const fileName = safeName ? `${safeName}_${random}${safeExt}` : `composer_${stamp}_${random}${safeExt}`
+ const filePath = path.join(dir, fileName)
await fs.promises.writeFile(filePath, buffer)
return filePath
@@ -16393,6 +16403,12 @@ ipcMain.handle('hermes:context-menu:guest-add-word', (_event, payload) => {
}
})
+ipcMain.handle('hermes:capturePreview', async (_event, payload) => {
+ const guest = electronWebContents.fromId(Number(payload?.webContentsId))
+
+ return capturePreviewContents(guest, payload?.rect, payload?.viewport)
+})
+
ipcMain.handle('hermes:saveImageBuffer', async (_event, payload) => {
const data = payload?.data
@@ -16402,7 +16418,7 @@ ipcMain.handle('hermes:saveImageBuffer', async (_event, payload) => {
const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data)
- return writeComposerImage(buffer, payload?.ext || '.png')
+ return writeComposerImage(buffer, payload?.ext || '.png', payload?.name)
})
ipcMain.handle('hermes:saveClipboardImage', async () => {
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index b257007338e..03915d13e7f 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -249,7 +249,8 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
return () => ipcRenderer.removeListener('hermes:context-menu-spellcheck', listener)
},
- saveImageBuffer: (data, ext) => ipcRenderer.invoke('hermes:saveImageBuffer', { data, ext }),
+ saveImageBuffer: (data, ext, name) => ipcRenderer.invoke('hermes:saveImageBuffer', { data, ext, name }),
+ capturePreview: payload => ipcRenderer.invoke('hermes:capturePreview', payload),
saveClipboardImage: () => ipcRenderer.invoke('hermes:saveClipboardImage'),
getPathForFile: file => {
try {
diff --git a/apps/desktop/electron/preview-capture.test.ts b/apps/desktop/electron/preview-capture.test.ts
new file mode 100644
index 00000000000..43f2457f294
--- /dev/null
+++ b/apps/desktop/electron/preview-capture.test.ts
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import { capturePreviewContents, mapViewportRectToImage, normalizeCaptureRect } from './preview-capture'
+
+test('normalizeCaptureRect floors origin and ceils size, never zero', () => {
+ assert.deepEqual(normalizeCaptureRect({ height: 10.2, width: 0.4, x: -3.2, y: 1.8 }), {
+ height: 11,
+ width: 1,
+ x: 0,
+ y: 1
+ })
+})
+
+test('mapViewportRectToImage scales CSS pixels onto a DPR bitmap and clamps', () => {
+ assert.deepEqual(
+ mapViewportRectToImage({ height: 20, width: 40, x: 10, y: 8 }, { height: 100, width: 200 }, { height: 200, width: 400 }),
+ { height: 40, width: 80, x: 20, y: 16 }
+ )
+ assert.equal(
+ mapViewportRectToImage({ height: 20, width: 40, x: 500, y: 8 }, { height: 100, width: 200 }, { height: 200, width: 400 }),
+ null
+ )
+})
+
+test('capturePreviewContents captures the visible page then crops in bitmap space', async () => {
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47])
+ const dataUrl = await capturePreviewContents(
+ {
+ capturePage: async rect => {
+ assert.equal(rect, undefined)
+
+ return {
+ crop: mapped => {
+ assert.deepEqual(mapped, { height: 40, width: 80, x: 4, y: 8 })
+
+ return { isEmpty: () => false, toPNG: () => png }
+ },
+ getSize: () => ({ height: 200, width: 400 }),
+ isEmpty: () => false,
+ toPNG: () => {
+ throw new Error('should crop first')
+ }
+ }
+ },
+ isDestroyed: () => false
+ },
+ { height: 20, width: 40, x: 2, y: 4 },
+ { height: 100, width: 200 }
+ )
+
+ assert.equal(dataUrl, `data:image/png;base64,${png.toString('base64')}`)
+})
+
+test('capturePreviewContents keeps the visible page when the CSS rect misses the bitmap', async () => {
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47])
+ const dataUrl = await capturePreviewContents(
+ {
+ capturePage: async () => ({
+ crop: () => {
+ throw new Error('should not crop an off-screen rect')
+ },
+ getSize: () => ({ height: 200, width: 400 }),
+ isEmpty: () => false,
+ toPNG: () => png
+ }),
+ isDestroyed: () => false
+ },
+ { height: 20, width: 40, x: 10, y: 800 },
+ { height: 100, width: 200 }
+ )
+
+ assert.equal(dataUrl, `data:image/png;base64,${png.toString('base64')}`)
+})
+
+test('capturePreviewContents fails closed on a destroyed guest', async () => {
+ await assert.rejects(
+ capturePreviewContents({
+ capturePage: async () => {
+ throw new Error('should not run')
+ },
+ isDestroyed: () => true
+ }),
+ /gone/
+ )
+})
diff --git a/apps/desktop/electron/preview-capture.ts b/apps/desktop/electron/preview-capture.ts
new file mode 100644
index 00000000000..dddc7506f9b
--- /dev/null
+++ b/apps/desktop/electron/preview-capture.ts
@@ -0,0 +1,131 @@
+/**
+ * Crop a preview webview via webContents.capturePage.
+ *
+ * Electron's rect argument is unreliable on guest webviews (empty NativeImage
+ * on Windows, DPI-shifted crops). Capture the visible viewport, then crop in
+ * bitmap space from CSS viewport coordinates.
+ *
+ * Missing/destroyed guests fail closed — never a blank PNG that would look
+ * like a successful shot of nothing.
+ */
+
+export interface CaptureRect {
+ height: number
+ width: number
+ x: number
+ y: number
+}
+
+export interface CaptureViewport {
+ height: number
+ width: number
+}
+
+export interface CaptureGuest {
+ capturePage: (rect?: CaptureRect) => Promise<CaptureImage>
+ isDestroyed: () => boolean
+}
+
+export interface CaptureImage {
+ crop?: (rect: CaptureRect) => CaptureImage
+ getSize?: () => CaptureViewport
+ isEmpty: () => boolean
+ toPNG: () => Buffer
+}
+
+export function normalizeCaptureRect(rect?: CaptureRect): CaptureRect | undefined {
+ if (!rect) {
+ return undefined
+ }
+
+ return {
+ height: Math.max(1, Math.ceil(rect.height)),
+ width: Math.max(1, Math.ceil(rect.width)),
+ x: Math.max(0, Math.floor(rect.x)),
+ y: Math.max(0, Math.floor(rect.y))
+ }
+}
+
+/** Map a CSS-pixel viewport rect onto a (possibly DPR-scaled) bitmap. */
+export function mapViewportRectToImage(
+ rect: CaptureRect,
+ viewport: CaptureViewport,
+ image: CaptureViewport
+): CaptureRect | null {
+ const viewW = Math.max(1, viewport.width)
+ const viewH = Math.max(1, viewport.height)
+ const scaleX = image.width / viewW
+ const scaleY = image.height / viewH
+ const left = rect.x * scaleX
+ const top = rect.y * scaleY
+ const right = (rect.x + rect.width) * scaleX
+ const bottom = (rect.y + rect.height) * scaleY
+ const x = Math.max(0, Math.floor(left))
+ const y = Math.max(0, Math.floor(top))
+ const maxX = Math.min(image.width, Math.ceil(right))
+ const maxY = Math.min(image.height, Math.ceil(bottom))
+ const width = maxX - x
+ const height = maxY - y
+
+ if (width < 1 || height < 1) {
+ return null
+ }
+
+ return { height, width, x, y }
+}
+
+function toDataUrl(image: CaptureImage): string {
+ if (!image || image.isEmpty()) {
+ throw new Error('preview capture was empty')
+ }
+
+ return `data:image/png;base64,${image.toPNG().toString('base64')}`
+}
+
+export async function capturePreviewContents(
+ guest: CaptureGuest | null | undefined,
+ rect?: CaptureRect,
+ viewport?: CaptureViewport
+): Promise<string> {
+ if (!guest || guest.isDestroyed()) {
+ throw new Error('preview guest is gone')
+ }
+
+ const image = await guest.capturePage()
+
+ if (!image || image.isEmpty()) {
+ throw new Error('preview capture was empty')
+ }
+
+ const crop = normalizeCaptureRect(rect)
+
+ if (!crop) {
+ return toDataUrl(image)
+ }
+
+ const size = image.getSize?.()
+ const view = viewport && viewport.width > 0 && viewport.height > 0 ? viewport : size
+
+ if (size && view && typeof image.crop === 'function') {
+ const mapped = mapViewportRectToImage(crop, view, size)
+
+ if (mapped) {
+ const cropped = image.crop(mapped)
+
+ if (cropped && !cropped.isEmpty()) {
+ return toDataUrl(cropped)
+ }
+ }
+
+ // Off-screen CSS rects (document Y after scroll, DPI mismatch) used to
+ // throw here and the composer kept the stale pick-time crop. The visible
+ // page is a better fallback than the wrong slice of the article.
+ return toDataUrl(image)
+ }
+
+ try {
+ return toDataUrl(await guest.capturePage(crop))
+ } catch {
+ return toDataUrl(image)
+ }
+}
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
index eaddeec15e8..ce1c2df44c6 100644
--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
@@ -308,7 +308,7 @@ describe('useComposerActions native image drops', () => {
})
expect(attached).toBe(true)
- expect(saveImageBuffer).toHaveBeenCalledOnce()
+ expect(saveImageBuffer).toHaveBeenCalledWith(expect.any(Uint8Array), '.png', 'Screen Shot 2026-08-11.png')
expect(readFileDataUrl).toHaveBeenCalledWith(durablePath)
expect(readFileDataUrl).not.toHaveBeenCalledWith(transientPath)
// The bounded-preview pipeline no longer retains the full-resolution data
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
index 814ce524937..f6e47fbd785 100644
--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
@@ -518,7 +518,8 @@ export function useComposerActions({
try {
const buffer = await blob.arrayBuffer()
const data = new Uint8Array(buffer)
- const savedPath = await window.hermesDesktop?.saveImageBuffer(data, blobExtension(blob))
+ const name = blob instanceof File ? blob.name : undefined
+ const savedPath = await window.hermesDesktop?.saveImageBuffer(data, blobExtension(blob), name)
if (!savedPath) {
notify({ kind: 'error', title: copy.imageAttach, message: copy.imageWriteFailed })
diff --git a/apps/desktop/src/app/chat/right-rail/preview-annotate-card.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-annotate-card.test.tsx
new file mode 100644
index 00000000000..a3f2ee236e2
--- /dev/null
+++ b/apps/desktop/src/app/chat/right-rail/preview-annotate-card.test.tsx
@@ -0,0 +1,67 @@
+import { cleanup, fireEvent, render } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { ANNOTATE_CARD_WIDTH } from '@/lib/preview-annotate'
+
+import { placeAnnotateCard, PreviewAnnotateCard } from './preview-annotate-card'
+
+afterEach(cleanup)
+
+describe('placeAnnotateCard', () => {
+ it('sits to the right of the pin instead of past a full-width selection', () => {
+ const placed = placeAnnotateCard({
+ paneHeight: 640,
+ paneWidth: 420,
+ rect: { height: 220, width: 400, x: 8, y: 48 }
+ })
+
+ expect(placed.left).toBeLessThan(80)
+ expect(placed.left).toBeGreaterThan(12)
+ expect(placed.top).toBeGreaterThanOrEqual(12)
+ })
+
+ it('stays inside the pane when the pin is on the right edge', () => {
+ const placed = placeAnnotateCard({
+ paneHeight: 400,
+ paneWidth: 360,
+ rect: { height: 40, width: 80, x: 300, y: 20 }
+ })
+
+ expect(placed.left + ANNOTATE_CARD_WIDTH).toBeLessThanOrEqual(360)
+ expect(placed.left).toBeGreaterThanOrEqual(12)
+ expect(placed.top).toBeGreaterThanOrEqual(12)
+ })
+})
+
+describe('PreviewAnnotateCard', () => {
+ it('shows a dark comment pill with a send control and no microphone', () => {
+ const onSave = vi.fn()
+ const onCancel = vi.fn()
+ const onChange = vi.fn()
+ const rendered = render(
+ <PreviewAnnotateCard
+ left={24}
+ note=""
+ number={3}
+ onCancel={onCancel}
+ onChange={onChange}
+ onSave={onSave}
+ placeholder="Add a comment..."
+ saveLabel="Save"
+ title="Comment 3"
+ top={40}
+ />
+ )
+
+ const card = rendered.container.querySelector('[data-annotate-card="true"]') as HTMLElement
+ expect(card.style.background.replace(/\s/g, '').toLowerCase()).toMatch(
+ /#2a2a2a|rgb\(42,42,42\)/
+ )
+ expect(rendered.getByPlaceholderText('Add a comment...')).toBeTruthy()
+ expect(rendered.container.querySelector('.codicon-mic')).toBeNull()
+ expect(rendered.container.querySelector('.codicon-unmute')).toBeNull()
+
+ fireEvent.click(rendered.getByRole('button', { name: 'Save' }))
+ expect(onSave).toHaveBeenCalledOnce()
+ })
+})
diff --git a/apps/desktop/src/app/chat/right-rail/preview-annotate-card.tsx b/apps/desktop/src/app/chat/right-rail/preview-annotate-card.tsx
new file mode 100644
index 00000000000..977650b6575
--- /dev/null
+++ b/apps/desktop/src/app/chat/right-rail/preview-annotate-card.tsx
@@ -0,0 +1,121 @@
+import { useEffect, useRef } from 'react'
+
+import { Codicon } from '@/components/ui/codicon'
+import {
+ ANNOTATE_CARD_HEIGHT,
+ ANNOTATE_CARD_WIDTH,
+ ANNOTATE_MARKER_SIZE,
+ ANNOTATE_PILL_BG,
+ ANNOTATE_PILL_FG,
+ ANNOTATE_PILL_SEND
+} from '@/lib/preview-annotate'
+
+const PAD = 12
+const GAP = 8
+
+interface AnnotateCardPlacement {
+ left: number
+ top: number
+}
+
+interface PlaceAnnotateCardInput {
+ paneHeight: number
+ paneWidth: number
+ rect: { height: number; width: number; x: number; y: number }
+}
+
+interface PreviewAnnotateCardProps extends AnnotateCardPlacement {
+ note: string
+ number: number
+ onCancel: () => void
+ onChange: (note: string) => void
+ onSave: () => void
+ placeholder: string
+ saveLabel: string
+ title: string
+}
+
+export function placeAnnotateCard({
+ paneHeight,
+ paneWidth,
+ rect
+}: PlaceAnnotateCardInput): AnnotateCardPlacement {
+ const width = Math.min(ANNOTATE_CARD_WIDTH, Math.max(0, paneWidth - PAD * 2))
+ const maxLeft = Math.max(PAD, paneWidth - width - PAD)
+ const maxTop = Math.max(PAD, paneHeight - ANNOTATE_CARD_HEIGHT - PAD)
+ const pinRight = rect.x + ANNOTATE_MARKER_SIZE / 2
+ const preferRight = pinRight + GAP
+ const preferLeft = rect.x - ANNOTATE_MARKER_SIZE / 2 - GAP - width
+ const left =
+ preferRight + width + PAD <= paneWidth || preferLeft < PAD
+ ? Math.min(Math.max(PAD, preferRight), maxLeft)
+ : Math.min(Math.max(PAD, preferLeft), maxLeft)
+ const top = Math.min(Math.max(PAD, rect.y - ANNOTATE_CARD_HEIGHT / 2), maxTop)
+
+ return { left, top }
+}
+
+export function PreviewAnnotateCard({
+ left,
+ note,
+ number,
+ onCancel,
+ onChange,
+ onSave,
+ placeholder,
+ saveLabel,
+ title,
+ top
+}: PreviewAnnotateCardProps) {
+ const field = useRef<HTMLInputElement>(null)
+
+ useEffect(() => {
+ field.current?.focus()
+ }, [number])
+
+ return (
+ <form
+ aria-label={title}
+ className="absolute z-20 flex h-11 w-[min(17.5rem,calc(100%-1.5rem))] items-center gap-1 rounded-full pl-4 pr-1 shadow-nous"
+ data-annotate-card="true"
+ data-annotate-number={number}
+ onSubmit={event => {
+ event.preventDefault()
+ onSave()
+ }}
+ style={{
+ background: ANNOTATE_PILL_BG,
+ boxShadow: '0 10px 28px rgba(0, 0, 0, 0.32), 0 0 0 1px rgba(255, 255, 255, 0.08)',
+ color: ANNOTATE_PILL_FG,
+ left,
+ top
+ }}
+ >
+ <input
+ aria-label={placeholder}
+ autoComplete="off"
+ className="min-w-0 flex-1 bg-transparent text-[0.8125rem] leading-5 outline-none placeholder:text-white/45"
+ onChange={event => onChange(event.target.value)}
+ onKeyDown={event => {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ onCancel()
+ }
+ }}
+ placeholder={placeholder}
+ ref={field}
+ spellCheck
+ style={{ caretColor: ANNOTATE_PILL_FG, color: ANNOTATE_PILL_FG, colorScheme: 'dark' }}
+ value={note}
+ />
+ <button
+ aria-label={saveLabel}
+ className="grid size-8 shrink-0 place-items-center rounded-full text-white/85 hover:text-white"
+ style={{ background: ANNOTATE_PILL_SEND }}
+ type="submit"
+ >
+ <Codicon name="arrow-up" size="0.875rem" />
+ </button>
+ </form>
+ )
+}
diff --git a/apps/desktop/src/app/chat/right-rail/preview-annotate-host.test.ts b/apps/desktop/src/app/chat/right-rail/preview-annotate-host.test.ts
new file mode 100644
index 00000000000..d399bfa9f19
--- /dev/null
+++ b/apps/desktop/src/app/chat/right-rail/preview-annotate-host.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { ANNOTATE_CROP_PAD } from '@/lib/preview-annotate'
+
+import {
+ bindPreviewExecuteJavaScript,
+ captureAnnotateCrop,
+ installAnnotateOverlay,
+ overlayInstallScript
+} from './preview-annotate-host'
+
+describe('preview annotate host', () => {
+ it('does not evaluate guest template interpolations while wrapping the overlay source', () => {
+ const snippet = '${rect.height}'
+ const source = '(function(){return `' + snippet + '`})(document)'
+ const script = overlayInstallScript(source)
+
+ expect(script).toContain(snippet)
+ expect(() => overlayInstallScript(source)).not.toThrow()
+ })
+
+ it('injects the guest overlay source', async () => {
+ const executeJavaScript = vi.fn(async (code: string) => {
+ expect(code).toContain('hermes-annotate')
+ expect(code).toContain('#2F80ED')
+ expect(code).toContain('api.install()')
+ expect(code).toContain('window.__hermesAnnotate')
+ })
+
+ await installAnnotateOverlay({ executeJavaScript })
+ expect(executeJavaScript).toHaveBeenCalledOnce()
+ })
+
+ it('calls executeJavaScript as a method so Electron can read this.getWebContentsId', async () => {
+ const webview = {
+ executeJavaScript(this: { getWebContentsId: () => number }, code: string) {
+ expect(this.getWebContentsId()).toBe(7)
+ expect(code).toBe('1+1')
+
+ return Promise.resolve(2)
+ },
+ getWebContentsId: () => 7
+ }
+
+ await expect(bindPreviewExecuteJavaScript(webview)('1+1')).resolves.toBe(2)
+ })
+
+ it('pads the element crop before capture', async () => {
+ const capture = vi.fn(async () => 'data:image/png;base64,AA==')
+
+ await captureAnnotateCrop({ capture, executeJavaScript: vi.fn() }, { height: 16, width: 40, x: 10, y: 20 })
+
+ expect(capture).toHaveBeenCalledWith({
+ height: 16 + ANNOTATE_CROP_PAD * 2,
+ width: 40 + ANNOTATE_CROP_PAD * 2,
+ x: 0,
+ y: 20 - ANNOTATE_CROP_PAD
+ })
+ })
+})
diff --git a/apps/desktop/src/app/chat/right-rail/preview-annotate-host.ts b/apps/desktop/src/app/chat/right-rail/preview-annotate-host.ts
new file mode 100644
index 00000000000..a13ecd61117
--- /dev/null
+++ b/apps/desktop/src/app/chat/right-rail/preview-annotate-host.ts
@@ -0,0 +1,107 @@
+/**
+ * Drive the guest overlay and crop capture from the preview pane.
+ * Overlay I/O only — stack/pack/flush live in lib/preview-annotate.
+ */
+
+import {
+ annotateInPageSource,
+ ANNOTATE_CROP_PAD,
+ type AnnotatePageEvent,
+ type AnnotatePinChrome
+} from '@/lib/preview-annotate'
+
+export interface PreviewAnnotateGuest {
+ capture?: (rect: { height: number; width: number; x: number; y: number }) => Promise<string>
+ executeJavaScript: (code: string) => Promise<unknown>
+}
+
+/**
+ * Electron's `<webview>.executeJavaScript` reads `this.getWebContentsId()`.
+ * Pulling the method off the element and calling it unbound throws
+ * "Cannot read properties of undefined (reading 'getWebContentsId')".
+ */
+export function bindPreviewExecuteJavaScript(webview: {
+ executeJavaScript?: (code: string) => Promise<unknown>
+}): (code: string) => Promise<unknown> {
+ return code => {
+ if (typeof webview.executeJavaScript !== 'function') {
+ return Promise.reject(new Error('preview webview is not ready'))
+ }
+
+ return webview.executeJavaScript(code)
+ }
+}
+
+const padRect = (rect: { height: number; width: number; x: number; y: number }) => ({
+ height: rect.height + ANNOTATE_CROP_PAD * 2,
+ width: rect.width + ANNOTATE_CROP_PAD * 2,
+ x: Math.max(0, rect.x - ANNOTATE_CROP_PAD),
+ y: Math.max(0, rect.y - ANNOTATE_CROP_PAD)
+})
+
+/**
+ * Build the guest install script by concatenation, never a template literal.
+ * `annotateInPage.toString()` contains `${...}` (Vite leaves those in the
+ * renderer). Wrapping that source in `` `...${source}...` `` evaluates those
+ * interpolations in the host — `rect is not defined` — and Annotate looks
+ * like a dead button.
+ */
+export function overlayInstallScript(source: string): string {
+ return '(function(){var api=' + source + ';window.__hermesAnnotate=api;api.install();})()'
+}
+
+export async function installAnnotateOverlay(guest: PreviewAnnotateGuest): Promise<void> {
+ await guest.executeJavaScript(overlayInstallScript(annotateInPageSource()))
+}
+
+export async function teardownAnnotateOverlay(guest: PreviewAnnotateGuest): Promise<void> {
+ await guest.executeJavaScript(`
+ (function () {
+ if (window.__hermesAnnotate && window.__hermesAnnotate.teardown) {
+ window.__hermesAnnotate.teardown();
+ }
+ window.__hermesAnnotate = null;
+ })()
+ `)
+}
+
+export async function waitAnnotateEvent(guest: PreviewAnnotateGuest): Promise<AnnotatePageEvent> {
+ const event = await guest.executeJavaScript(`
+ window.__hermesAnnotate ? window.__hermesAnnotate.wait() : Promise.resolve({ type: 'end' })
+ `)
+
+ return event as AnnotatePageEvent
+}
+
+export async function syncAnnotatePins(guest: PreviewAnnotateGuest, pins: AnnotatePinChrome[]): Promise<void> {
+ await guest.executeJavaScript(`
+ window.__hermesAnnotate && window.__hermesAnnotate.showPins(${JSON.stringify(pins)})
+ `)
+}
+
+export async function showAnnotateDraft(
+ guest: PreviewAnnotateGuest,
+ rect: AnnotatePinChrome['rect'],
+ number: number
+): Promise<void> {
+ await guest.executeJavaScript(`
+ window.__hermesAnnotate && window.__hermesAnnotate.showDraft(${JSON.stringify(rect)}, ${number})
+ `)
+}
+
+export async function hideAnnotateDraft(guest: PreviewAnnotateGuest): Promise<void> {
+ await guest.executeJavaScript(`
+ window.__hermesAnnotate && window.__hermesAnnotate.hideDraft()
+ `)
+}
+
+export async function captureAnnotateCrop(
+ guest: PreviewAnnotateGuest,
+ rect: AnnotatePinChrome['rect']
+): Promise<string> {
+ if (!guest.capture) {
+ throw new Error('preview capture is unavailable')
+ }
+
+ return guest.capture(padRect(rect))
+}
diff --git a/apps/desktop/src/app/chat/right-rail/preview-browser-bar.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-browser-bar.test.tsx
index 7bd51099aa9..32d347eee1b 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-browser-bar.test.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-browser-bar.test.tsx
@@ -92,6 +92,27 @@ describe('PreviewBrowserBar', () => {
expect(address(rendered)).toBeTruthy()
})
+ it('renders the Annotate control and a blue Commenting status while the mode is on', () => {
+ const onToggleAnnotate = vi.fn()
+ const rendered = render(<PreviewBrowserBar {...baseProps} annotateMode onToggleAnnotate={onToggleAnnotate} />)
+
+ const toggle = rendered.getByRole('button', { name: 'Stop annotating' })
+ expect(toggle.getAttribute('aria-pressed')).toBe('true')
+ fireEvent.click(toggle)
+ expect(onToggleAnnotate).toHaveBeenCalledOnce()
+ expect(rendered.getByText('Commenting').getAttribute('data-annotate-status')).toBe('commenting')
+ })
+
+ it('flushes stacked comments from the bar without implying a send on save', () => {
+ const onFlushComments = vi.fn()
+ const rendered = render(
+ <PreviewBrowserBar {...baseProps} commentCount={2} onFlushComments={onFlushComments} onToggleAnnotate={vi.fn()} />
+ )
+
+ fireEvent.click(rendered.getByRole('button', { name: 'Add 2 comments' }))
+ expect(onFlushComments).toHaveBeenCalledOnce()
+ })
+
it('disables back and forward when there is no history', () => {
const rendered = render(<PreviewBrowserBar {...baseProps} />)
diff --git a/apps/desktop/src/app/chat/right-rail/preview-browser-bar.tsx b/apps/desktop/src/app/chat/right-rail/preview-browser-bar.tsx
index ec7b87f0d00..662ca8464d7 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-browser-bar.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-browser-bar.tsx
@@ -21,21 +21,26 @@ import { CopyButton } from '@/components/ui/copy-button'
import { Input } from '@/components/ui/input'
import { PaneStripGlyph } from '@/components/ui/pane-tab'
import { useI18n } from '@/i18n'
+import { ANNOTATE_BLUE } from '@/lib/preview-annotate'
import { cn } from '@/lib/utils'
interface PreviewBrowserBarProps {
+ annotateMode?: boolean
canGoBack: boolean
canGoForward: boolean
+ commentCount?: number
consoleOpen: boolean
devToolsOpen: boolean
loading: boolean
onBack: () => void
+ onFlushComments?: () => void
onForward: () => void
onNavigate: (url: string) => void
onOpenExternal?: () => void
onPopIn?: () => void
onPopOut?: () => void
onReload: () => void
+ onToggleAnnotate?: () => void
onToggleConsole: () => void
onToggleDevTools: () => void
/** The page's CURRENT address (it moves as the user navigates), not the
@@ -89,18 +94,22 @@ export function normalizePreviewAddress(value: string): null | string {
}
export function PreviewBrowserBar({
+ annotateMode = false,
canGoBack,
canGoForward,
+ commentCount = 0,
consoleOpen,
devToolsOpen,
loading,
onBack,
+ onFlushComments,
onForward,
onNavigate,
onOpenExternal,
onPopIn,
onPopOut,
onReload,
+ onToggleAnnotate,
onToggleConsole,
onToggleDevTools,
url
@@ -206,6 +215,33 @@ export function PreviewBrowserBar({
text={url}
/>
</div>
+ {onToggleAnnotate ? (
+ <PaneStripGlyph
+ active={annotateMode}
+ icon={<Codicon name="comment" size="0.8125rem" />}
+ label={annotateMode ? copy.annotateOn : copy.annotate}
+ onSelect={onToggleAnnotate}
+ />
+ ) : null}
+ {annotateMode ? (
+ <span
+ className="hidden shrink-0 items-center rounded-full px-2 py-0.5 text-[0.625rem] font-semibold tracking-wide text-white uppercase sm:inline-flex"
+ data-annotate-status="commenting"
+ style={{ background: ANNOTATE_BLUE }}
+ >
+ {copy.commenting}
+ </span>
+ ) : null}
+ {commentCount > 0 && onFlushComments ? (
+ <button
+ className="shrink-0 rounded-full px-2 py-0.5 text-[0.6875rem] font-semibold text-white"
+ onClick={onFlushComments}
+ style={{ background: ANNOTATE_BLUE }}
+ type="button"
+ >
+ {copy.addComments(commentCount)}
+ </button>
+ ) : null}
{onPopIn ? (
<PaneStripGlyph
icon={<Codicon name="screen-normal" size="0.8125rem" />}
diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx
index 7050940666d..056bd9d59e8 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx
@@ -1,7 +1,8 @@
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { $connection } from '@/store/session'
+import { onComposerAttachImagesRequest } from '@/app/chat/composer/focus'
+import { $connection, $selectedStoredSessionId } from '@/store/session'
import { forgetPreviewConsole, previewConsoleState } from './preview-console-store'
import { PreviewPane } from './preview-pane'
@@ -34,6 +35,7 @@ describe('PreviewPane console state', () => {
afterEach(() => {
cleanup()
$connection.set(null)
+ $selectedStoredSessionId.set(null)
vi.unstubAllGlobals()
})
@@ -191,6 +193,78 @@ describe('PreviewPane console state', () => {
expect(webview.getAttribute('src')).toBe('http://localhost:5174')
})
+ it('continues comment numbering in one conversation and resets it when the conversation changes', async () => {
+ $selectedStoredSessionId.set('session-one')
+ const selectedCrop = 'data:image/png;base64,c2VsZWN0ZWQ='
+ const scrolledCrop = 'data:image/png;base64,ZGlmZmVyZW50LXZpc2libGU='
+ const savedRect = { height: 20, width: 40, x: 10, y: 20 }
+ const attached = new Promise<Blob>(resolve => {
+ const unsubscribe = onComposerAttachImagesRequest(({ blobs }) => {
+ unsubscribe()
+ resolve(blobs[0]!)
+ })
+ })
+ const previousDesktop = window.hermesDesktop
+ let captureCount = 0
+
+ window.hermesDesktop = {
+ ...previousDesktop,
+ capturePreview: vi.fn(async () => {
+ captureCount += 1
+
+ return captureCount === 1 ? selectedCrop : scrolledCrop
+ })
+ }
+
+ let rendered!: ReturnType<typeof render>
+ await act(async () => {
+ rendered = render(
+ <PreviewPane
+ target={{ kind: 'url', label: 'Preview', source: 'http://localhost:5174', url: 'http://localhost:5174' }}
+ />
+ )
+ })
+
+ const webview = rendered.container.querySelector('webview') as HTMLElement & Record<string, unknown>
+ let waitCount = 0
+ let releaseNextPick: ((event: unknown) => void) | undefined
+ Object.assign(webview, {
+ executeJavaScript: vi.fn(async (code: string) => {
+ if (code.includes('.wait()')) {
+ waitCount += 1
+
+ if (waitCount === 1) {
+ return { rect: savedRect, type: 'pick-area' }
+ }
+
+ return new Promise(resolve => {
+ releaseNextPick = resolve
+ })
+ }
+
+ return undefined
+ }),
+ getWebContentsId: () => 7
+ })
+
+ fireEvent.click(rendered.getByRole('button', { name: 'Annotate' }))
+ fireEvent.click(await rendered.findByRole('button', { name: 'Save' }))
+ fireEvent.click(await rendered.findByRole('button', { name: 'Add 1 comment' }))
+
+ expect(await (await attached).text()).toBe('selected')
+ await act(async () => {
+ releaseNextPick?.({ rect: { ...savedRect, y: 80 }, type: 'pick-area' })
+ })
+ expect(await rendered.findByRole('form', { name: 'Comment 2' })).toBeTruthy()
+
+ act(() => {
+ $selectedStoredSessionId.set('session-two')
+ })
+ await waitFor(() => expect(rendered.queryByRole('form', { name: 'Comment 2' })).toBeNull())
+ expect(rendered.queryByRole('button', { name: 'Add 1 comment' })).toBeNull()
+ window.hermesDesktop = previousDesktop
+ })
+
// The webview always runs on THIS machine, so a remote agent's localhost is
// a different computer's localhost. The failure is honest but baffling
// without saying so.
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 cfbfc8beb61..bc4510e9f80 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
@@ -6,6 +6,7 @@ import { useStore } from '@nanostores/react'
import type { 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 { Tip } from '@/components/ui/tooltip'
@@ -15,6 +16,16 @@ import { guardGuestPointers } from '@/lib/guest-pointer-guard'
import { openPreviewTargetInBrowser, remoteHtmlPreviewDocument } from '@/lib/local-preview'
import { isRemoteGateway } from '@/lib/media'
import { reachablePreviewUrl } from '@/lib/preview-reach'
+import {
+ addAnnotatePin,
+ beginAnnotateMode,
+ clearAnnotatePins,
+ compactIdentity,
+ emptyAnnotateSession,
+ emptyAnnotateStack,
+ endAnnotateMode,
+ flushAnnotateStack
+} from '@/lib/preview-annotate'
import { rafCoalesce } from '@/lib/raf-coalesce'
import { cn } from '@/lib/utils'
import { notify, notifyError } from '@/store/notifications'
@@ -27,8 +38,21 @@ import {
popOutBrowserTab,
type PreviewTarget
} 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,
+ showAnnotateDraft,
+ syncAnnotatePins,
+ teardownAnnotateOverlay,
+ waitAnnotateEvent,
+ type PreviewAnnotateGuest
+} from './preview-annotate-host'
import { ArtifactPreview } from './preview-artifact'
import { PreviewBrowserBar } from './preview-browser-bar'
import {
@@ -235,6 +259,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
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
@@ -243,6 +268,12 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
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
// Artifacts have no URL to load — they render from the registry, never in a
// webview.
@@ -369,6 +400,221 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
}
}, [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])
+
+ useEffect(() => {
+ if (annotateConversationRef.current === selectedStoredSessionId) {
+ return
+ }
+
+ annotateConversationRef.current = selectedStoredSessionId
+ annotateLoopRef.current += 1
+ setDraftNote('')
+ setAnnotate(emptyAnnotateSession())
+
+ const guest = annotateGuest()
+ if (guest) {
+ void teardownAnnotateOverlay(guest).catch(() => undefined)
+ }
+ }, [annotateGuest, 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()
+
+ 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, currentUrl])
+
+ 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)
@@ -961,6 +1207,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
webviewRef.current = webview
return () => {
+ annotateLoopRef.current += 1
webview.removeEventListener('console-message', onConsole)
webview.removeEventListener('context-menu', onGuestContextMenu)
webview.removeEventListener('devtools-closed', onDevToolsClosed)
@@ -972,6 +1219,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
webview.removeEventListener('did-stop-loading', onStop)
webview.removeEventListener('page-title-updated', notePage)
webview.remove()
+ setAnnotate(session => (session.mode ? { ...endAnnotateMode(session), stack: emptyAnnotateStack() } : session))
}
}, [appendConsoleEntry, consoleState, copy, isRemoteHtml, isWebPreview, tabId, target.kind, target.url])
@@ -1023,12 +1271,15 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
{isWebPreview && !isRemoteHtml && (
<PreviewBrowserBar
+ annotateMode={annotate.mode}
canGoBack={history.back}
canGoForward={history.forward}
+ commentCount={annotate.stack.pins.length}
consoleOpen={consoleOpen}
devToolsOpen={devtoolsOpen}
loading={loading}
onBack={goBack}
+ onFlushComments={() => void flushComments()}
onForward={goForward}
onNavigate={navigateTo}
onOpenExternal={
@@ -1041,6 +1292,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
isBrowserWindow() || !tabId || !canOpenBrowserWindow() ? undefined : () => popOutBrowserTab(tabId)
}
onReload={reloadPreview}
+ onToggleAnnotate={toggleAnnotate}
onToggleConsole={() => consoleState.setOpen(open => !open)}
onToggleDevTools={toggleDevTools}
url={currentUrl}
@@ -1088,6 +1340,24 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
/>
)}
+ {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}
+
{isWebPreview && !isRemoteHtml && consoleOpen && (
<PreviewConsolePanel
consoleBodyRef={consoleBodyRef}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index b2c4fea7f4e..3c0bc4de937 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -278,7 +278,13 @@ declare global {
onContextMenuSpellcheck?: (
callback: (payload: { misspelledWord: string; suggestions: string[] }) => void
) => () => void
- saveImageBuffer: (data: ArrayBuffer | Uint8Array, ext: string) => Promise<string>
+ saveImageBuffer: (data: ArrayBuffer | Uint8Array, ext: string, name?: string) => Promise<string>
+ /** Crop the in-app browser guest. `rect` is CSS pixels in the page viewport. */
+ capturePreview?: (payload: {
+ rect?: { height: number; width: number; x: number; y: number }
+ viewport?: { height: number; width: number }
+ webContentsId: number
+ }) => Promise<string>
saveClipboardImage: () => Promise<string>
getPathForFile: (file: File) => string
normalizePreviewTarget: (target: string, baseDir?: string) => Promise<HermesPreviewTarget | null>
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 1a1eacab30c..b34f0313461 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3111,7 +3111,17 @@ export const en: Translations = {
loadFailedConsole: (code, message) => `Load failed${code ? ` (${code})` : ''}: ${message}`,
unreachableDescription: 'The preview page could not be reached.',
openTarget: url => `Open ${url}`,
- fallbackTitle: 'Preview'
+ fallbackTitle: 'Preview',
+ annotate: 'Annotate',
+ annotateOn: 'Stop annotating',
+ annotateNeedPage: 'Open a page in the in-app browser first.',
+ annotateFailed: 'Could not start annotation mode',
+ commenting: 'Commenting',
+ addComments: count => (count === 1 ? 'Add 1 comment' : `Add ${count} comments`),
+ commentPlaceholder: 'Add a comment...',
+ commentTitle: n => `Comment ${n}`,
+ saveComment: 'Save',
+ cancelComment: 'Cancel comment'
}
},
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 361adbd0102..4d5e375e329 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2674,6 +2674,16 @@ export interface Translations {
unreachableDescription: string
openTarget: (url: string) => string
fallbackTitle: string
+ annotate: string
+ annotateOn: string
+ annotateNeedPage: string
+ annotateFailed: string
+ commenting: string
+ addComments: (count: number) => string
+ commentPlaceholder: string
+ commentTitle: (n: number) => string
+ saveComment: string
+ cancelComment: string
}
}
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index c151641964a..cba510b25bc 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3272,7 +3272,17 @@ export const zh: Translations = {
loadFailedConsole: (code, message) => `加载失败${code ? ` (${code})` : ''}: ${message}`,
unreachableDescription: '无法访问预览页面。',
openTarget: url => `打开 ${url}`,
- fallbackTitle: '预览'
+ fallbackTitle: '预览',
+ annotate: '标注',
+ annotateOn: '停止标注',
+ annotateNeedPage: '请先在内置浏览器中打开页面。',
+ annotateFailed: '无法开始标注',
+ commenting: '标注中',
+ addComments: count => (count === 1 ? '添加 1 条批注' : `添加 ${count} 条批注`),
+ commentPlaceholder: '添加批注…',
+ commentTitle: n => `批注 ${n}`,
+ saveComment: '保存',
+ cancelComment: '取消批注'
}
},
diff --git a/apps/desktop/src/lib/preview-annotate/flush.ts b/apps/desktop/src/lib/preview-annotate/flush.ts
new file mode 100644
index 00000000000..e7cfea3c8e0
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/flush.ts
@@ -0,0 +1,41 @@
+import { annotateFlushPrompt, dataUrlToFile, packageAnnotateStack } from './pack'
+import type { AnnotatePin } from './stack'
+
+export interface AnnotateFlushPorts {
+ attachImage: (blob: Blob) => void | Promise<void>
+ insertText: (text: string) => void
+ send?: () => void
+}
+
+export interface AnnotateFlushResult {
+ count: number
+ prompt: string
+ sent: false
+}
+
+/**
+ * Attach every pin to the composer as a numbered crop plus the packed prompt.
+ * Saving / flushing never submits a turn — `send` is accepted so tests can
+ * prove it stays untouched.
+ */
+export async function flushAnnotateStack(
+ pins: readonly AnnotatePin[],
+ ports: AnnotateFlushPorts,
+ pageUrl?: string
+): Promise<AnnotateFlushResult> {
+ const items = packageAnnotateStack(pins)
+
+ for (const item of items) {
+ if (item.imageDataUrl) {
+ await ports.attachImage(dataUrlToFile(item.imageDataUrl, `Comment_${item.number}.png`))
+ }
+ }
+
+ const prompt = annotateFlushPrompt(items, pageUrl)
+
+ if (prompt.trim()) {
+ ports.insertText(prompt)
+ }
+
+ return { count: items.length, prompt, sent: false }
+}
diff --git a/apps/desktop/src/lib/preview-annotate/identity.ts b/apps/desktop/src/lib/preview-annotate/identity.ts
new file mode 100644
index 00000000000..2c4da1c3b73
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/identity.ts
@@ -0,0 +1,78 @@
+import { ANNOTATE_CSS_KEYS } from './tokens'
+
+export interface ElementSnapshot {
+ className?: string
+ css: Record<string, string>
+ id?: string
+ role?: string
+ selector: string
+ tag: string
+ text: string
+}
+
+export interface CompactIdentity {
+ css: Record<string, string>
+ selector: string
+ tag: string
+ text: string
+}
+
+const MAX_TEXT = 80
+const MAX_SELECTOR = 180
+const MAX_CSS_VALUE = 80
+const SEMANTIC_TAGS = new Set([
+ 'a',
+ 'button',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'img',
+ 'input',
+ 'label',
+ 'select',
+ 'textarea'
+])
+
+function clip(value: string, max: number): string {
+ const trimmed = value.replace(/\s+/g, ' ').trim()
+
+ if (trimmed.length <= max) {
+ return trimmed
+ }
+
+ return `${trimmed.slice(0, max - 1)}…`
+}
+
+/** Keep only the curated CSS snapshot, drop empties and the whole document. */
+export function compactIdentity(snapshot: ElementSnapshot): CompactIdentity {
+ const css: Record<string, string> = {}
+
+ for (const key of ANNOTATE_CSS_KEYS) {
+ const raw = snapshot.css[key] || snapshot.css[key.replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase())]
+
+ if (!raw || raw === 'normal' || raw === 'none' || raw === 'auto' || raw === '0px') {
+ continue
+ }
+
+ css[key] = clip(raw, MAX_CSS_VALUE)
+ }
+
+ const tag = (snapshot.tag || 'div').toLowerCase()
+ const selector = clip(snapshot.selector || tag, MAX_SELECTOR)
+ const text = clip(snapshot.text || '', MAX_TEXT)
+
+ return { css, selector, tag, text }
+}
+
+export function formatIdentityLine(identity: CompactIdentity): string {
+ if (!identity.text) {
+ return identity.selector || identity.tag
+ }
+
+ const label = `"${identity.text}"`
+
+ return SEMANTIC_TAGS.has(identity.tag) ? `${identity.tag} ${label}` : label
+}
diff --git a/apps/desktop/src/lib/preview-annotate/in-page.test.ts b/apps/desktop/src/lib/preview-annotate/in-page.test.ts
new file mode 100644
index 00000000000..0abe344a1a8
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/in-page.test.ts
@@ -0,0 +1,166 @@
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { annotateInPage } from './in-page'
+
+afterEach(() => {
+ document.body.replaceChildren()
+ document.querySelectorAll('hermes-annotate').forEach(node => node.remove())
+})
+
+describe('annotateInPage overlay', () => {
+ it('installs a host and tears it down completely', () => {
+ const api = annotateInPage(document)
+ api.install()
+
+ expect(api.isInstalled()).toBe(true)
+ expect(document.querySelector('hermes-annotate')).toBeTruthy()
+
+ api.teardown()
+
+ expect(api.isInstalled()).toBe(false)
+ expect(document.querySelector('hermes-annotate')).toBeNull()
+ })
+
+ it('paints a blue outline and numbered markers for stacked pins', () => {
+ const api = annotateInPage(document)
+ api.install()
+ api.showPins([
+ { kind: 'element', number: 1, rect: { height: 24, width: 80, x: 10, y: 10 } },
+ { kind: 'area', number: 2, rect: { height: 40, width: 120, x: 20, y: 80 } }
+ ])
+
+ expect(api.getMarkerNumbers()).toEqual([1, 2])
+ expect(api.getOutlineColor().replace(/\s/g, '').toLowerCase()).toMatch(/#2f80ed|rgb\(47,128,237\)/)
+ })
+
+ it('keeps a pin glued to its element after the element moves', () => {
+ const word = document.createElement('span')
+ word.id = 'target-word'
+ word.textContent = 'hello'
+ document.body.appendChild(word)
+ let top = 40
+ word.getBoundingClientRect = () => ({
+ bottom: top + 20,
+ height: 20,
+ left: 10,
+ right: 90,
+ toJSON: () => ({}),
+ top,
+ width: 80,
+ x: 10,
+ y: top
+ })
+
+ const api = annotateInPage(document)
+ api.install()
+ api.showPins([
+ { kind: 'element', number: 1, rect: { height: 20, width: 80, x: 10, y: 40 }, selector: '#target-word' }
+ ])
+
+ const pin = () =>
+ document.querySelector('hermes-annotate')!.shadowRoot!.querySelector('[data-annotate-pin="1"]') as HTMLElement
+
+ expect(pin().style.top).toBe('40px')
+ top = 200
+ api.relocate()
+ expect(pin().style.top).toBe('200px')
+ api.teardown()
+ })
+
+ it('keeps the picked element when the draft becomes a pin, even if the selector is wrong', () => {
+ const word = document.createElement('span')
+ word.id = 'target-word'
+ word.textContent = 'hello'
+ document.body.appendChild(word)
+ let top = 40
+ word.getBoundingClientRect = () => ({
+ bottom: top + 20,
+ height: 20,
+ left: 10,
+ right: 90,
+ toJSON: () => ({}),
+ top,
+ width: 80,
+ x: 10,
+ y: top
+ })
+ document.elementFromPoint = () => word
+
+ const api = annotateInPage(document)
+ api.install()
+ const host = document.querySelector('hermes-annotate') as HTMLElement
+ host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 20, clientY: 48 }))
+ host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 21, clientY: 49 }))
+
+ api.showPins([
+ { kind: 'element', number: 1, rect: { height: 20, width: 80, x: 10, y: 40 }, selector: '#does-not-exist' }
+ ])
+
+ const pin = () =>
+ document.querySelector('hermes-annotate')!.shadowRoot!.querySelector('[data-annotate-pin="1"]') as HTMLElement
+
+ expect(pin().style.top).toBe('40px')
+ top = 180
+ api.relocate()
+ expect(pin().style.top).toBe('180px')
+ api.teardown()
+ })
+
+ it('emits pick-element with compact identity on click', async () => {
+ const button = document.createElement('button')
+ button.id = 'go'
+ button.textContent = 'Go'
+ document.body.appendChild(button)
+ button.getBoundingClientRect = () => ({
+ bottom: 34,
+ height: 24,
+ left: 10,
+ right: 90,
+ toJSON: () => ({}),
+ top: 10,
+ width: 80,
+ x: 10,
+ y: 10
+ })
+ document.elementFromPoint = () => button
+
+ const api = annotateInPage(document)
+ api.install()
+ const pending = api.wait()
+ const host = document.querySelector('hermes-annotate') as HTMLElement
+
+ host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 20, clientY: 20 }))
+ host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 21, clientY: 21 }))
+
+ const event = await pending
+
+ expect(event.type).toBe('pick-element')
+ if (event.type === 'pick-element') {
+ expect(event.identity.tag).toBe('button')
+ expect(event.identity.selector).toContain('go')
+ expect(event.identity.text).toBe('Go')
+ }
+ })
+
+ it('owns wheel scrolling instead of also allowing the native wheel action', () => {
+ const scroller = document.createElement('div')
+ scroller.style.overflowY = 'auto'
+ Object.defineProperties(scroller, {
+ clientHeight: { configurable: true, value: 100 },
+ scrollHeight: { configurable: true, value: 500 }
+ })
+ document.body.appendChild(scroller)
+ document.elementFromPoint = () => scroller
+
+ const api = annotateInPage(document)
+ api.install()
+ const host = document.querySelector('hermes-annotate') as HTMLElement
+ const wheel = new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: 30 })
+
+ host.dispatchEvent(wheel)
+
+ expect(wheel.defaultPrevented).toBe(true)
+ expect(scroller.scrollTop).toBe(30)
+ api.teardown()
+ })
+})
diff --git a/apps/desktop/src/lib/preview-annotate/in-page.ts b/apps/desktop/src/lib/preview-annotate/in-page.ts
new file mode 100644
index 00000000000..bd402e255e8
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/in-page.ts
@@ -0,0 +1,709 @@
+/**
+ * Guest-page comment overlay. Injected as source into the preview webview —
+ * no imports, no module constants, every value the body needs lives inside
+ * `annotateInPage`. Same contract as `watchInPage`.
+ *
+ * pointer-events on the host capture clicks while mode is on; hit-testing
+ * briefly disables them so elementFromPoint sees the real page. Teardown
+ * removes the host entirely so nothing can stick over the page.
+ */
+
+export const ANNOTATE_HOST_TAG = 'hermes-annotate'
+
+export interface AnnotatePageRect {
+ height: number
+ width: number
+ x: number
+ y: number
+}
+
+export interface AnnotatePageIdentity {
+ css: Record<string, string>
+ selector: string
+ tag: string
+ text: string
+}
+
+export type AnnotatePageEvent =
+ | { identity: AnnotatePageIdentity; rect: AnnotatePageRect; type: 'pick-element' }
+ | { rect: AnnotatePageRect; type: 'pick-area' }
+ | { rect: AnnotatePageRect; type: 'reposition' }
+ | { type: 'end' }
+
+export interface AnnotatePinChrome {
+ kind: 'area' | 'element'
+ number: number
+ page?: AnnotatePageRect
+ rect: AnnotatePageRect
+ selector?: string
+}
+
+export interface AnnotateInPage {
+ getMarkerNumbers: () => number[]
+ getOutlineColor: () => string
+ hideDraft: () => void
+ install: () => void
+ isInstalled: () => boolean
+ relocate: () => void
+ showDraft: (rect: AnnotatePageRect, number: number) => void
+ showPins: (pins: AnnotatePinChrome[]) => void
+ teardown: () => void
+ wait: () => Promise<AnnotatePageEvent>
+}
+
+export function annotateInPage(doc: Document): AnnotateInPage {
+ const win = doc.defaultView
+ // Literals, not imports: this function is stringified into the guest page.
+ const blue = '#2F80ED'
+ const fill = 'rgba(47, 128, 237, 0.14)'
+ const markerSize = 22
+ const stroke = '2px'
+ const cssKeys = [
+ 'color',
+ 'background-color',
+ 'font-size',
+ 'font-family',
+ 'font-weight',
+ 'line-height',
+ 'letter-spacing',
+ 'text-align',
+ 'display',
+ 'position',
+ 'width',
+ 'height',
+ 'padding',
+ 'margin',
+ 'border-radius',
+ 'opacity',
+ 'flex-direction',
+ 'gap',
+ 'justify-content',
+ 'align-items'
+ ]
+
+ let host: HTMLElement | null = null
+ let shadow: ShadowRoot | null = null
+ let hoverBox: HTMLElement | null = null
+ let draftBox: HTMLElement | null = null
+ let marquee: HTMLElement | null = null
+ let pinsLayer: HTMLElement | null = null
+ let waiting: ((event: AnnotatePageEvent) => void) | null = null
+ const queued: AnnotatePageEvent[] = []
+ let drag: { x: number; y: number } | null = null
+ let areaForced = false
+ let liveDraft: { el: Element | null; page: AnnotatePageRect } | null = null
+ let livePins: { el: Element | null; number: number; page: AnnotatePageRect; wrap: HTMLElement }[] = []
+ let raf = 0
+ let lastDraftKey = ''
+
+ const style = (el: HTMLElement, props: Record<string, string>) => {
+ for (const name of Object.keys(props)) {
+ el.style.setProperty(name, props[name])
+ }
+ }
+
+ const emit = (event: AnnotatePageEvent) => {
+ if (waiting) {
+ const resolve = waiting
+ waiting = null
+ resolve(event)
+
+ return
+ }
+
+ queued.push(event)
+ }
+
+ const box = (el: Element): AnnotatePageRect => {
+ const rect = el.getBoundingClientRect()
+
+ return { height: rect.height, width: rect.width, x: rect.left, y: rect.top }
+ }
+
+ const pageOffset = () => {
+ const scrolling = doc.scrollingElement || doc.documentElement
+
+ return {
+ x: win?.scrollX ?? scrolling.scrollLeft ?? 0,
+ y: win?.scrollY ?? scrolling.scrollTop ?? 0
+ }
+ }
+
+ const cssEscape = (value: string): string => {
+ const CSS = win && win.CSS
+
+ if (CSS && CSS.escape) {
+ return CSS.escape(value)
+ }
+
+ return value.replace(/([^\w-])/g, '\\$1')
+ }
+
+ const canScroll = (node: Element, axis: 'x' | 'y') => {
+ if (!win) {
+ return false
+ }
+
+ const style = win.getComputedStyle(node)
+ const overflow = axis === 'y' ? style.overflowY : style.overflowX
+ const scrollable = overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay'
+
+ if (!scrollable) {
+ return false
+ }
+
+ return axis === 'y' ? node.scrollHeight > node.clientHeight + 1 : node.scrollWidth > node.clientWidth + 1
+ }
+
+ const toPage = (rect: AnnotatePageRect): AnnotatePageRect => {
+ const offset = pageOffset()
+
+ return { height: rect.height, width: rect.width, x: rect.x + offset.x, y: rect.y + offset.y }
+ }
+
+ const toView = (pageRect: AnnotatePageRect): AnnotatePageRect => {
+ const offset = pageOffset()
+
+ return { height: pageRect.height, width: pageRect.width, x: pageRect.x - offset.x, y: pageRect.y - offset.y }
+ }
+
+ const viewOf = (track: { el: Element | null; page: AnnotatePageRect }): AnnotatePageRect => {
+ if (track.el && track.el.isConnected) {
+ return box(track.el)
+ }
+
+ return toView(track.page)
+ }
+
+ const cssPath = (el: Element): string => {
+ const parts: string[] = []
+ let node: Element | null = el
+
+ while (node && node.nodeType === 1 && parts.length < 5) {
+ const tag = node.tagName.toLowerCase()
+
+ if (node.id) {
+ parts.unshift(`#${cssEscape(node.id)}`)
+ break
+ }
+
+ const cls = (node.getAttribute('class') || '')
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map(name => `.${cssEscape(name)}`)
+ .join('')
+ let sel = tag + cls
+ const parent: Element | null = node.parentElement
+
+ if (parent) {
+ const same = Array.from(parent.children).filter(child => child.tagName === node!.tagName)
+
+ if (same.length > 1) {
+ sel += `:nth-of-type(${same.indexOf(node) + 1})`
+ }
+ }
+
+ parts.unshift(sel)
+ node = parent
+ if (node && (node === doc.documentElement || tag === 'body')) {
+ break
+ }
+ }
+
+ return parts.join('>')
+ }
+
+ const readCss = (el: Element): Record<string, string> => {
+ const computed = win?.getComputedStyle(el)
+ const out: Record<string, string> = {}
+
+ if (!computed) {
+ return out
+ }
+
+ for (const key of cssKeys) {
+ const value = computed.getPropertyValue(key).trim()
+
+ if (!value || value === 'normal' || value === 'none' || value === 'auto' || value === '0px') {
+ continue
+ }
+
+ out[key] = value.length > 80 ? `${value.slice(0, 79)}…` : value
+ }
+
+ return out
+ }
+
+ const identityOf = (el: Element): AnnotatePageIdentity => {
+ const text = (el.textContent || '').replace(/\s+/g, ' ').trim()
+
+ return {
+ css: readCss(el),
+ selector: cssPath(el),
+ tag: el.tagName.toLowerCase(),
+ text: text.length > 80 ? `${text.slice(0, 79)}…` : text
+ }
+ }
+
+ const underPoint = (x: number, y: number): Element | null => {
+ if (!host) {
+ return doc.elementFromPoint(x, y)
+ }
+
+ const previous = host.style.getPropertyValue('pointer-events')
+ host.style.setProperty('pointer-events', 'none')
+ const hit = doc.elementFromPoint(x, y)
+ host.style.setProperty('pointer-events', previous || 'auto')
+
+ if (!hit || hit === host || hit === doc.documentElement || hit === doc.body) {
+ return null
+ }
+
+ return hit
+ }
+
+ const place = (el: HTMLElement, rect: AnnotatePageRect) => {
+ style(el, {
+ height: `${Math.max(1, rect.height)}px`,
+ left: `${rect.x}px`,
+ top: `${rect.y}px`,
+ width: `${Math.max(1, rect.width)}px`
+ })
+ }
+
+ const relocate = () => {
+ for (let i = 0; i < livePins.length; i++) {
+ const pin = livePins[i]
+ if (pin.el && pin.el.isConnected) {
+ pin.page = toPage(box(pin.el))
+ }
+ place(pin.wrap, viewOf(pin))
+ }
+
+ if (liveDraft && draftBox && draftBox.style.getPropertyValue('display') !== 'none') {
+ if (liveDraft.el && liveDraft.el.isConnected) {
+ liveDraft.page = toPage(box(liveDraft.el))
+ }
+ const rect = viewOf(liveDraft)
+ place(draftBox, rect)
+ const key = [rect.x, rect.y, rect.width, rect.height].join(',')
+ if (key !== lastDraftKey) {
+ lastDraftKey = key
+ emit({ rect, type: 'reposition' })
+ }
+ }
+ }
+
+ const loop = () => {
+ if (!host || !host.isConnected) {
+ raf = 0
+
+ return
+ }
+
+ relocate()
+ if (win) {
+ raf = win.requestAnimationFrame(loop)
+ }
+ }
+
+ const ensureLoop = () => {
+ if (win && !raf) {
+ raf = win.requestAnimationFrame(loop)
+ }
+ }
+
+ const paintOutline = (el: HTMLElement, heavy: boolean) => {
+ style(el, {
+ background: heavy ? fill : 'transparent',
+ border: `${stroke} solid ${blue}`,
+ 'border-radius': '4px',
+ 'box-shadow': heavy ? `0 0 0 1px ${blue}, 0 8px 24px rgba(15, 23, 42, 0.18)` : `0 0 0 1px ${blue}`,
+ 'box-sizing': 'border-box',
+ 'pointer-events': 'none',
+ position: 'fixed'
+ })
+ }
+
+ const makeMarker = (number: number): HTMLElement => {
+ const mark = doc.createElement('div')
+ mark.setAttribute('data-annotate-marker', String(number))
+ mark.textContent = String(number)
+ style(mark, {
+ 'align-items': 'center',
+ background: blue,
+ border: '2px solid #fff',
+ 'border-radius': '999px',
+ 'box-shadow': '0 2px 8px rgba(15, 23, 42, 0.28)',
+ color: '#fff',
+ display: 'flex',
+ 'font-family': "-apple-system, 'Segoe UI', sans-serif",
+ 'font-size': '11px',
+ 'font-weight': '700',
+ height: `${markerSize}px`,
+ 'justify-content': 'center',
+ left: `${-markerSize / 2}px`,
+ 'letter-spacing': '0',
+ 'line-height': '1',
+ 'pointer-events': 'none',
+ position: 'absolute',
+ top: `${-markerSize / 2}px`,
+ width: `${markerSize}px`,
+ 'z-index': '2'
+ })
+
+ return mark
+ }
+
+ const ensure = () => {
+ if (host && shadow && hoverBox && draftBox && marquee && pinsLayer) {
+ return
+ }
+
+ const stale = doc.querySelectorAll('hermes-annotate')
+
+ for (let i = 0; i < stale.length; i++) {
+ stale[i].remove()
+ }
+
+ host = doc.createElement('hermes-annotate')
+ host.setAttribute('aria-hidden', 'true')
+ host.setAttribute('data-annotate-host', 'true')
+ style(host, {
+ background: 'transparent',
+ border: '0',
+ cursor: 'crosshair',
+ display: 'block',
+ height: '100%',
+ inset: '0',
+ margin: '0',
+ overflow: 'visible',
+ padding: '0',
+ 'pointer-events': 'auto',
+ position: 'fixed',
+ 'user-select': 'none',
+ width: '100%',
+ 'z-index': '2147483000'
+ })
+
+ shadow = host.attachShadow({ mode: 'open' })
+ hoverBox = doc.createElement('div')
+ hoverBox.setAttribute('data-annotate-outline', 'hover')
+ paintOutline(hoverBox, false)
+ style(hoverBox, { display: 'none', opacity: '0.85' })
+
+ draftBox = doc.createElement('div')
+ draftBox.setAttribute('data-annotate-outline', 'draft')
+ paintOutline(draftBox, true)
+ style(draftBox, { display: 'none' })
+ draftBox.appendChild(makeMarker(1))
+
+ marquee = doc.createElement('div')
+ marquee.setAttribute('data-annotate-marquee', 'true')
+ style(marquee, {
+ background: fill,
+ border: `1.5px dashed ${blue}`,
+ 'border-radius': '2px',
+ display: 'none',
+ 'pointer-events': 'none',
+ position: 'fixed'
+ })
+
+ pinsLayer = doc.createElement('div')
+ style(pinsLayer, { inset: '0', 'pointer-events': 'none', position: 'fixed' })
+
+ shadow.appendChild(hoverBox)
+ shadow.appendChild(draftBox)
+ shadow.appendChild(marquee)
+ shadow.appendChild(pinsLayer)
+ doc.documentElement.appendChild(host)
+ }
+
+ const onMove = (event: MouseEvent) => {
+ if (!hoverBox) {
+ return
+ }
+
+ if (drag && marquee) {
+ const x = Math.min(drag.x, event.clientX)
+ const y = Math.min(drag.y, event.clientY)
+ const width = Math.abs(event.clientX - drag.x)
+ const height = Math.abs(event.clientY - drag.y)
+ style(marquee, { display: 'block' })
+ place(marquee, { height, width, x, y })
+ style(hoverBox, { display: 'none' })
+
+ return
+ }
+
+ const hit = underPoint(event.clientX, event.clientY)
+
+ if (!hit) {
+ style(hoverBox, { display: 'none' })
+
+ return
+ }
+
+ style(hoverBox, { display: 'block' })
+ place(hoverBox, box(hit))
+ }
+
+ const onDown = (event: MouseEvent) => {
+ if (event.button !== 0) {
+ return
+ }
+
+ event.preventDefault()
+ event.stopPropagation()
+ drag = { x: event.clientX, y: event.clientY }
+ areaForced = event.shiftKey
+ }
+
+ const onUp = (event: MouseEvent) => {
+ if (!drag) {
+ return
+ }
+
+ event.preventDefault()
+ event.stopPropagation()
+
+ const start = drag
+ drag = null
+ const width = Math.abs(event.clientX - start.x)
+ const height = Math.abs(event.clientY - start.y)
+ const isArea = areaForced || width > 8 || height > 8
+ areaForced = false
+
+ if (marquee) {
+ style(marquee, { display: 'none' })
+ }
+
+ if (isArea) {
+ const rect = {
+ height: Math.max(8, height),
+ width: Math.max(8, width),
+ x: Math.min(start.x, event.clientX),
+ y: Math.min(start.y, event.clientY)
+ }
+ liveDraft = { el: null, page: toPage(rect) }
+ lastDraftKey = ''
+ emit({ rect, type: 'pick-area' })
+
+ return
+ }
+
+ const hit = underPoint(event.clientX, event.clientY)
+
+ if (!hit) {
+ return
+ }
+
+ const rect = box(hit)
+ liveDraft = { el: hit, page: toPage(rect) }
+ lastDraftKey = ''
+ emit({ identity: identityOf(hit), rect, type: 'pick-element' })
+ }
+
+ const onWheel = (event: WheelEvent) => {
+ event.preventDefault()
+ host?.style.setProperty('pointer-events', 'none')
+ const under = doc.elementFromPoint(event.clientX, event.clientY)
+ host?.style.setProperty('pointer-events', 'auto')
+ let scroller: Element | null = under
+
+ while (scroller) {
+ if (canScroll(scroller, 'y') || canScroll(scroller, 'x')) {
+ scroller.scrollTop += event.deltaY
+ scroller.scrollLeft += event.deltaX
+ relocate()
+
+ return
+ }
+
+ scroller = scroller.parentElement
+ }
+
+ if (win) {
+ win.scrollBy(event.deltaX, event.deltaY)
+ } else {
+ const root = doc.scrollingElement || doc.documentElement
+ root.scrollTop += event.deltaY
+ root.scrollLeft += event.deltaX
+ }
+ relocate()
+ }
+
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ emit({ type: 'end' })
+ }
+ }
+
+ const bind = () => {
+ if (!host) {
+ return
+ }
+
+ host.addEventListener('mousedown', onDown, true)
+ host.addEventListener('mousemove', onMove, true)
+ host.addEventListener('mouseup', onUp, true)
+ host.addEventListener('wheel', onWheel, { passive: false })
+ win?.addEventListener('keydown', onKey, true)
+ win?.addEventListener('scroll', relocate, true)
+ win?.addEventListener('resize', relocate)
+ doc.addEventListener('scroll', relocate, true)
+ win?.visualViewport?.addEventListener('scroll', relocate)
+ win?.visualViewport?.addEventListener('resize', relocate)
+ }
+
+ const unbind = () => {
+ host?.removeEventListener('mousedown', onDown, true)
+ host?.removeEventListener('mousemove', onMove, true)
+ host?.removeEventListener('mouseup', onUp, true)
+ host?.removeEventListener('wheel', onWheel)
+ win?.removeEventListener('keydown', onKey, true)
+ win?.removeEventListener('scroll', relocate, true)
+ win?.removeEventListener('resize', relocate)
+ doc.removeEventListener('scroll', relocate, true)
+ win?.visualViewport?.removeEventListener('scroll', relocate)
+ win?.visualViewport?.removeEventListener('resize', relocate)
+ if (win && raf) {
+ win.cancelAnimationFrame(raf)
+ raf = 0
+ }
+ }
+
+ const showPins = (pins: AnnotatePinChrome[]) => {
+ ensure()
+
+ if (!pinsLayer) {
+ return
+ }
+
+ const previous = livePins
+ pinsLayer.replaceChildren()
+ livePins = []
+
+ for (const pin of pins) {
+ let el: Element | null = null
+ const old = previous.find(item => item.number === pin.number)
+
+ if (old && old.el && old.el.isConnected) {
+ el = old.el
+ } else if (liveDraft && liveDraft.el && liveDraft.el.isConnected) {
+ el = liveDraft.el
+ }
+
+ if (!el && pin.selector) {
+ try {
+ el = doc.querySelector(pin.selector)
+ } catch {
+ el = null
+ }
+ }
+
+ const page = el ? toPage(box(el)) : pin.page || old?.page || toPage(pin.rect)
+ const wrap = doc.createElement('div')
+ wrap.setAttribute('data-annotate-pin', String(pin.number))
+ paintOutline(wrap, true)
+ place(wrap, el ? box(el) : toView(page))
+ wrap.appendChild(makeMarker(pin.number))
+ pinsLayer.appendChild(wrap)
+ livePins.push({ el, number: pin.number, page, wrap })
+ }
+
+ liveDraft = null
+ lastDraftKey = ''
+ ensureLoop()
+ }
+
+ const showDraft = (rect: AnnotatePageRect, number: number) => {
+ ensure()
+
+ if (!draftBox) {
+ return
+ }
+
+ if (!liveDraft) {
+ liveDraft = { el: null, page: toPage(rect) }
+ }
+
+ draftBox.replaceChildren(makeMarker(number))
+ style(draftBox, { display: 'block' })
+ place(draftBox, liveDraft.el && liveDraft.el.isConnected ? box(liveDraft.el) : viewOf(liveDraft))
+ if (hoverBox) {
+ style(hoverBox, { display: 'none' })
+ }
+ ensureLoop()
+ }
+
+ const hideDraft = () => {
+ liveDraft = null
+ lastDraftKey = ''
+ if (draftBox) {
+ style(draftBox, { display: 'none' })
+ }
+ }
+
+ const teardown = () => {
+ unbind()
+ emit({ type: 'end' })
+ host?.remove()
+ host = null
+ shadow = null
+ hoverBox = null
+ draftBox = null
+ marquee = null
+ pinsLayer = null
+ drag = null
+ liveDraft = null
+ livePins = []
+ waiting = null
+ queued.length = 0
+ }
+
+ return {
+ getMarkerNumbers: () => {
+ if (!shadow) {
+ return []
+ }
+
+ return Array.from(shadow.querySelectorAll('[data-annotate-pin] [data-annotate-marker]')).map(node =>
+ Number(node.getAttribute('data-annotate-marker') || '0')
+ )
+ },
+ getOutlineColor: () => {
+ const outline = shadow?.querySelector('[data-annotate-outline], [data-annotate-pin]') as HTMLElement | null
+
+ return outline?.style.getPropertyValue('border-color') || outline?.style.borderColor || blue
+ },
+ hideDraft,
+ install: () => {
+ ensure()
+ bind()
+ ensureLoop()
+ },
+ isInstalled: () => Boolean(host && host.isConnected),
+ relocate,
+ showDraft,
+ showPins,
+ teardown,
+ wait: () => {
+ if (queued.length) {
+ return Promise.resolve(queued.shift() as AnnotatePageEvent)
+ }
+
+ return new Promise(resolve => {
+ waiting = resolve
+ })
+ }
+ }
+}
+
+/** Source for `executeJavaScript` — the guest page has no module graph. */
+export function annotateInPageSource(): string {
+ return `(${annotateInPage.toString()})(document)`
+}
diff --git a/apps/desktop/src/lib/preview-annotate/index.ts b/apps/desktop/src/lib/preview-annotate/index.ts
new file mode 100644
index 00000000000..72ee7e58550
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/index.ts
@@ -0,0 +1,50 @@
+export { compactIdentity, formatIdentityLine, type CompactIdentity, type ElementSnapshot } from './identity'
+export { flushAnnotateStack, type AnnotateFlushPorts, type AnnotateFlushResult } from './flush'
+export {
+ annotateInPage,
+ annotateInPageSource,
+ ANNOTATE_HOST_TAG,
+ type AnnotateInPage,
+ type AnnotatePageEvent,
+ type AnnotatePinChrome
+} from './in-page'
+export {
+ annotateFlushPrompt,
+ dataUrlToBlob,
+ dataUrlToFile,
+ packageAnnotatePin,
+ packageAnnotateStack,
+ type ComposerReadyAnnotation
+} from './pack'
+export {
+ addAnnotatePin,
+ beginAnnotateMode,
+ clearAnnotatePins,
+ clearAnnotateStack,
+ emptyAnnotateSession,
+ emptyAnnotateStack,
+ endAnnotateMode,
+ removeAnnotatePin,
+ updateAnnotatePinNote,
+ type AnnotateIdentity,
+ type AnnotatePin,
+ type AnnotatePinDraft,
+ type AnnotatePinKind,
+ type AnnotateRect,
+ type AnnotateSession,
+ type AnnotateStack
+} from './stack'
+export {
+ ANNOTATE_BLUE,
+ ANNOTATE_BLUE_FILL,
+ ANNOTATE_BLUE_RING,
+ ANNOTATE_CARD_HEIGHT,
+ ANNOTATE_CARD_WIDTH,
+ ANNOTATE_CROP_PAD,
+ ANNOTATE_CSS_KEYS,
+ ANNOTATE_MARKER_SIZE,
+ ANNOTATE_OUTLINE_WIDTH,
+ ANNOTATE_PILL_BG,
+ ANNOTATE_PILL_FG,
+ ANNOTATE_PILL_SEND
+} from './tokens'
diff --git a/apps/desktop/src/lib/preview-annotate/pack.test.ts b/apps/desktop/src/lib/preview-annotate/pack.test.ts
new file mode 100644
index 00000000000..b96fccd46a0
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/pack.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { flushAnnotateStack } from './flush'
+import { compactIdentity } from './identity'
+import { annotateFlushPrompt, packageAnnotatePin, packageAnnotateStack } from './pack'
+import { addAnnotatePin, emptyAnnotateStack, type AnnotatePin } from './stack'
+
+const png =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
+
+function pin(partial: Partial<AnnotatePin> = {}): AnnotatePin {
+ return {
+ id: 'annotate-1',
+ imageDataUrl: png,
+ kind: 'element',
+ note: 'This button overflows on mobile.',
+ number: 1,
+ pageTitle: 'Pricing',
+ pageUrl: 'http://127.0.0.1:4173/',
+ rect: { height: 40, width: 120, x: 8, y: 8 },
+ identity: {
+ css: { color: 'rgb(24, 24, 24)', 'font-size': '14px' },
+ selector: 'button.plan',
+ tag: 'button',
+ text: 'Select plan'
+ },
+ ...partial
+ }
+}
+
+describe('packageAnnotatePin', () => {
+ it('describes text in a generic container without exposing DOM and style internals', () => {
+ const text = 'גם בקיבוץ חולית הקטן יש ילד שעושה את הצעד הראשון במערכת החינוך'
+ const packed = packageAnnotatePin(
+ pin({
+ identity: {
+ css: { color: 'rgb(0, 0, 0)', 'font-family': 'Moses, NarkisBlock', 'font-size': '18px' },
+ selector:
+ 'div.DraftEditor-editorContainer>div.public-DraftEditor-content>div>div.text_editor_paragraph.rtl:nth-of-type(9)',
+ tag: 'div',
+ text
+ },
+ note: 'תסכם את זה'
+ })
+ )
+
+ expect(packed.prompt).toContain(`Target: "${text}"`)
+ expect(packed.prompt).toContain('Note: תסכם את זה')
+ expect(packed.prompt).not.toContain('div')
+ expect(packed.prompt).not.toContain('DraftEditor')
+ expect(packed.prompt).not.toContain('font-size')
+ })
+
+ it('packs a numbered crop, compact identity, and the note', () => {
+ const packed = packageAnnotatePin(pin())
+
+ expect(packed.number).toBe(1)
+ expect(packed.imageDataUrl).toBe(png)
+ expect(packed.note).toContain('overflows')
+ expect(packed.prompt).toContain('Comment 1')
+ expect(packed.prompt).toContain('Target: button "Select plan"')
+ expect(packed.prompt).toContain('Image 1 marks the target in blue.')
+ expect(packed.prompt).toContain('Note: This button overflows on mobile.')
+ expect(packed.prompt).not.toContain('button.plan')
+ expect(packed.prompt).not.toContain('font-size')
+ expect(packed.prompt).not.toContain('<html')
+ })
+
+ it('keeps a selector when an element has no readable text', () => {
+ const packed = packageAnnotatePin(
+ pin({
+ identity: {
+ css: { display: 'block' },
+ selector: '#sales-chart',
+ tag: 'div',
+ text: ''
+ },
+ note: 'Use the same scale as the chart above.'
+ })
+ )
+
+ expect(packed.prompt).toContain('Target: #sales-chart')
+ expect(packed.prompt).not.toContain('display: block')
+ })
+
+ it('packages an area pin without pretending it has a selector', () => {
+ const packed = packageAnnotatePin(pin({ identity: undefined, kind: 'area', note: 'too tight' }))
+
+ expect(packed.prompt).toContain('area')
+ expect(packed.prompt).toContain('120×40px')
+ expect(packed.prompt).toContain('too tight')
+ })
+})
+
+describe('compactIdentity', () => {
+ it('never keeps the whole document and clips long text', () => {
+ const compact = compactIdentity({
+ css: { color: 'red', display: 'none', margin: '0px' },
+ selector: 'html>body>div>div>button.submit',
+ tag: 'BUTTON',
+ text: 'x'.repeat(200)
+ })
+
+ expect(compact.tag).toBe('button')
+ expect(compact.text.endsWith('…')).toBe(true)
+ expect(compact.text.length).toBeLessThanOrEqual(80)
+ expect(compact.css.display).toBeUndefined()
+ expect(compact.css.margin).toBeUndefined()
+ expect(compact.css.color).toBe('red')
+ })
+})
+
+describe('flushAnnotateStack', () => {
+ it('attaches one composer item per pin and does not invoke send', async () => {
+ const first = pin()
+ const second = pin({ id: 'annotate-2', kind: 'area', identity: undefined, note: 'align the chart', number: 2 })
+ let stack = emptyAnnotateStack()
+ stack = addAnnotatePin(stack, {
+ imageDataUrl: first.imageDataUrl,
+ identity: first.identity,
+ kind: first.kind,
+ note: first.note,
+ pageTitle: first.pageTitle,
+ pageUrl: first.pageUrl,
+ rect: first.rect
+ })
+ stack = addAnnotatePin(stack, {
+ imageDataUrl: second.imageDataUrl,
+ kind: 'area',
+ note: second.note,
+ pageTitle: second.pageTitle,
+ pageUrl: second.pageUrl,
+ rect: second.rect
+ })
+
+ const attachImage = vi.fn()
+ const insertText = vi.fn()
+ const send = vi.fn()
+ const result = await flushAnnotateStack(stack.pins, { attachImage, insertText, send }, 'http://127.0.0.1:4173/')
+
+ expect(result.sent).toBe(false)
+ expect(result.count).toBe(2)
+ expect(send).not.toHaveBeenCalled()
+ expect(attachImage).toHaveBeenCalledTimes(2)
+ expect(attachImage.mock.calls[0]?.[0]).toBeInstanceOf(File)
+ expect((attachImage.mock.calls[0]?.[0] as File).name).toBe('Comment_1.png')
+ expect((attachImage.mock.calls[1]?.[0] as File).name).toBe('Comment_2.png')
+ expect(insertText).toHaveBeenCalledOnce()
+ expect(insertText.mock.calls[0]?.[0]).toContain('I left 2 comments')
+ expect(insertText.mock.calls[0]?.[0]).toContain('Comment 1')
+ expect(insertText.mock.calls[0]?.[0]).toContain('Comment 2')
+ })
+
+ it('a pin save is stacking, not flushing', () => {
+ const stacked = packageAnnotateStack([pin(), pin({ id: 'annotate-2', number: 2, note: 'second' })])
+
+ expect(stacked).toHaveLength(2)
+ expect(annotateFlushPrompt(stacked)).toContain('2 comments')
+ })
+})
diff --git a/apps/desktop/src/lib/preview-annotate/pack.ts b/apps/desktop/src/lib/preview-annotate/pack.ts
new file mode 100644
index 00000000000..34a3b7a49f6
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/pack.ts
@@ -0,0 +1,75 @@
+import { formatIdentityLine, type CompactIdentity } from './identity'
+import type { AnnotatePin } from './stack'
+
+export interface ComposerReadyAnnotation {
+ identity?: CompactIdentity
+ imageDataUrl: string
+ note: string
+ number: number
+ prompt: string
+}
+
+function identityBlock(pin: AnnotatePin): string {
+ if (!pin.identity) {
+ return `area on the page (${Math.round(pin.rect.width)}×${Math.round(pin.rect.height)}px)`
+ }
+
+ return formatIdentityLine(pin.identity)
+}
+
+export function packageAnnotatePin(pin: AnnotatePin): ComposerReadyAnnotation {
+ const target = identityBlock(pin)
+ const note = pin.note.trim()
+ const prompt = [
+ `Comment ${pin.number}`,
+ `Target: ${target}`,
+ note ? `Note: ${note}` : '',
+ `Image ${pin.number} marks the target in blue.`
+ ]
+ .filter(Boolean)
+ .join('\n')
+
+ return {
+ identity: pin.identity,
+ imageDataUrl: pin.imageDataUrl,
+ note,
+ number: pin.number,
+ prompt
+ }
+}
+
+export function packageAnnotateStack(pins: readonly AnnotatePin[]): ComposerReadyAnnotation[] {
+ return pins.map(packageAnnotatePin)
+}
+
+export function annotateFlushPrompt(items: readonly ComposerReadyAnnotation[], pageUrl?: string): string {
+ const where = pageUrl ? ` on ${pageUrl}` : ''
+ const count = items.length
+ const header =
+ count === 1
+ ? `I left a comment${where} in the in-app browser. Address it and keep the scope narrow.`
+ : `I left ${count} comments${where} in the in-app browser. Address them and keep the scope narrow.`
+
+ return [header, '', ...items.map(item => item.prompt)].join('\n')
+}
+
+export function dataUrlToBlob(dataUrl: string): Blob {
+ const comma = dataUrl.indexOf(',')
+ const head = comma >= 0 ? dataUrl.slice(0, comma) : 'data:image/png;base64'
+ const body = comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl
+ const mime = /data:([^;]+)/.exec(head)?.[1] || 'image/png'
+ const binary = atob(body)
+ const bytes = new Uint8Array(binary.length)
+
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i)
+ }
+
+ return new Blob([bytes], { type: mime })
+}
+
+export function dataUrlToFile(dataUrl: string, name: string): File {
+ const blob = dataUrlToBlob(dataUrl)
+
+ return new File([blob], name, { type: blob.type })
+}
diff --git a/apps/desktop/src/lib/preview-annotate/stack.test.ts b/apps/desktop/src/lib/preview-annotate/stack.test.ts
new file mode 100644
index 00000000000..b73862b4ad6
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/stack.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ addAnnotatePin,
+ beginAnnotateMode,
+ clearAnnotateStack,
+ clearAnnotatePins,
+ emptyAnnotateSession,
+ emptyAnnotateStack,
+ endAnnotateMode,
+ removeAnnotatePin,
+ updateAnnotatePinNote,
+ type AnnotatePinDraft
+} from './stack'
+
+const png = 'data:image/png;base64,AAAA'
+
+function draft(note: string, kind: 'area' | 'element' = 'element'): AnnotatePinDraft {
+ return {
+ imageDataUrl: png,
+ kind,
+ note,
+ pageTitle: 'Demo',
+ pageUrl: 'http://localhost:5174/',
+ rect: { height: 24, width: 80, x: 10, y: 12 },
+ identity:
+ kind === 'element'
+ ? { css: { 'font-size': '14px' }, selector: 'button.go', tag: 'button', text: 'Go' }
+ : undefined
+ }
+}
+
+describe('annotate pin stack', () => {
+ it('numbers click and area pins 1..N as they accumulate', () => {
+ let stack = emptyAnnotateStack()
+ stack = addAnnotatePin(stack, draft('fix overflow'))
+ stack = addAnnotatePin(stack, draft('align this', 'area'))
+
+ expect(stack.pins.map(pin => pin.number)).toEqual([1, 2])
+ expect(stack.pins[0]?.kind).toBe('element')
+ expect(stack.pins[1]?.kind).toBe('area')
+ expect(stack.nextNumber).toBe(3)
+ })
+
+ it('keeps numbers stable when a pin is removed', () => {
+ let stack = emptyAnnotateStack()
+ stack = addAnnotatePin(stack, draft('one'))
+ stack = addAnnotatePin(stack, draft('two'))
+ stack = addAnnotatePin(stack, draft('three'))
+ stack = removeAnnotatePin(stack, stack.pins[1]!.id)
+ stack = addAnnotatePin(stack, draft('four'))
+
+ expect(stack.pins.map(pin => pin.number)).toEqual([1, 3, 4])
+ })
+
+ it('updates a note without sending anything', () => {
+ let stack = emptyAnnotateStack()
+ stack = addAnnotatePin(stack, draft(''))
+ stack = updateAnnotatePinNote(stack, stack.pins[0]!.id, 'make the label wrap')
+
+ expect(stack.pins[0]?.note).toBe('make the label wrap')
+ })
+
+ it('clear resets numbering', () => {
+ let stack = addAnnotatePin(emptyAnnotateStack(), draft('x'))
+ stack = clearAnnotateStack(stack)
+ stack = addAnnotatePin(stack, draft('fresh'))
+
+ expect(stack.pins[0]?.number).toBe(1)
+ })
+
+ it('clearing sent pins preserves numbering for the next comment batch', () => {
+ let stack = emptyAnnotateStack()
+ stack = addAnnotatePin(stack, draft('one'))
+ stack = addAnnotatePin(stack, draft('two'))
+ stack = clearAnnotatePins(stack)
+ stack = addAnnotatePin(stack, draft('three'))
+
+ expect(stack.pins.map(pin => pin.number)).toEqual([3])
+ })
+})
+
+describe('annotate session mode', () => {
+ it('ending mode tears overlay state down and does not auto-send', () => {
+ let session = beginAnnotateMode(emptyAnnotateSession())
+ session = {
+ ...session,
+ draft: draft('pending'),
+ stack: addAnnotatePin(session.stack, draft('saved'))
+ }
+ session = endAnnotateMode(session)
+
+ expect(session.mode).toBe(false)
+ expect(session.overlayLive).toBe(false)
+ expect(session.draft).toBeNull()
+ expect(session.stack.pins).toHaveLength(1)
+ })
+})
diff --git a/apps/desktop/src/lib/preview-annotate/stack.ts b/apps/desktop/src/lib/preview-annotate/stack.ts
new file mode 100644
index 00000000000..2c0a2ea152e
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/stack.ts
@@ -0,0 +1,102 @@
+/**
+ * Numbered pin stack for comment mode. Saving a pin only appends — it never
+ * sends a turn. Numbers are assigned 1..N in add order and stay put if a pin
+ * is removed, so Comment 3 in the composer still matches marker 3 on the page.
+ */
+
+export type AnnotatePinKind = 'area' | 'element'
+
+export interface AnnotateRect {
+ height: number
+ width: number
+ x: number
+ y: number
+}
+
+export interface AnnotateIdentity {
+ css: Record<string, string>
+ selector: string
+ tag: string
+ text: string
+}
+
+export interface AnnotatePin {
+ id: string
+ identity?: AnnotateIdentity
+ imageDataUrl: string
+ kind: AnnotatePinKind
+ note: string
+ number: number
+ pageTitle: string
+ pageUrl: string
+ rect: AnnotateRect
+}
+
+export interface AnnotateStack {
+ nextNumber: number
+ pins: AnnotatePin[]
+}
+
+export type AnnotatePinDraft = Omit<AnnotatePin, 'id' | 'number'> & { id?: string }
+
+export function emptyAnnotateStack(): AnnotateStack {
+ return { nextNumber: 1, pins: [] }
+}
+
+export function addAnnotatePin(stack: AnnotateStack, draft: AnnotatePinDraft): AnnotateStack {
+ const pin: AnnotatePin = {
+ ...draft,
+ id: draft.id || `annotate-${stack.nextNumber}`,
+ number: stack.nextNumber
+ }
+
+ return {
+ nextNumber: stack.nextNumber + 1,
+ pins: [...stack.pins, pin]
+ }
+}
+
+export function updateAnnotatePinNote(stack: AnnotateStack, id: string, note: string): AnnotateStack {
+ return {
+ ...stack,
+ pins: stack.pins.map(pin => (pin.id === id ? { ...pin, note } : pin))
+ }
+}
+
+export function removeAnnotatePin(stack: AnnotateStack, id: string): AnnotateStack {
+ return {
+ ...stack,
+ pins: stack.pins.filter(pin => pin.id !== id)
+ }
+}
+
+export function clearAnnotateStack(stack: AnnotateStack): AnnotateStack {
+ void stack
+
+ return emptyAnnotateStack()
+}
+
+/** Clear a flushed batch while keeping comment numbers unique in this page session. */
+export function clearAnnotatePins(stack: AnnotateStack): AnnotateStack {
+ return { ...stack, pins: [] }
+}
+
+export interface AnnotateSession {
+ /** In-progress pick that has a crop but no saved note yet. */
+ draft: AnnotatePinDraft | null
+ mode: boolean
+ overlayLive: boolean
+ stack: AnnotateStack
+}
+
+export function emptyAnnotateSession(): AnnotateSession {
+ return { draft: null, mode: false, overlayLive: false, stack: emptyAnnotateStack() }
+}
+
+export function beginAnnotateMode(session: AnnotateSession): AnnotateSession {
+ return { ...session, mode: true, overlayLive: true }
+}
+
+export function endAnnotateMode(session: AnnotateSession): AnnotateSession {
+ return { ...session, draft: null, mode: false, overlayLive: false }
+}
diff --git a/apps/desktop/src/lib/preview-annotate/tokens.ts b/apps/desktop/src/lib/preview-annotate/tokens.ts
new file mode 100644
index 00000000000..cafbbbb427f
--- /dev/null
+++ b/apps/desktop/src/lib/preview-annotate/tokens.ts
@@ -0,0 +1,47 @@
+/**
+ * Visual tokens for in-app browser comment mode.
+ *
+ * Drawn onto the GUEST page, which does not load our CSS variables, so these
+ * are real colors — the same reason the agent overlay uses a hex. Codex's
+ * comment chrome is a design-tool selection blue, not the app accent: the
+ * outline has to read as "a reviewer marked this" on someone else's page.
+ */
+
+export const ANNOTATE_BLUE = '#2F80ED'
+export const ANNOTATE_BLUE_FILL = 'rgba(47, 128, 237, 0.14)'
+export const ANNOTATE_BLUE_RING = 'rgba(47, 128, 237, 0.35)'
+export const ANNOTATE_MARKER_SIZE = 22
+export const ANNOTATE_OUTLINE_WIDTH = '2px'
+export const ANNOTATE_CROP_PAD = 12
+
+/** Host comment pill sits on the guest page, so it uses real colors like the pin. */
+export const ANNOTATE_PILL_BG = '#2A2A2A'
+export const ANNOTATE_PILL_FG = '#F4F4F4'
+export const ANNOTATE_PILL_SEND = '#3D3D3D'
+export const ANNOTATE_CARD_WIDTH = 280
+export const ANNOTATE_CARD_HEIGHT = 44
+
+export const ANNOTATE_CSS_KEYS = [
+ 'color',
+ 'background-color',
+ 'font-size',
+ 'font-family',
+ 'font-weight',
+ 'line-height',
+ 'letter-spacing',
+ 'text-align',
+ 'display',
+ 'position',
+ 'width',
+ 'height',
+ 'padding',
+ 'margin',
+ 'border-radius',
+ 'opacity',
+ 'flex-direction',
+ 'gap',
+ 'justify-content',
+ 'align-items'
+] as const
+
+export type AnnotateCssKey = (typeof ANNOTATE_CSS_KEYS)[number]