The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): an overlay that shows what the agent is doing to the page
Brooklyn Nicholsonf262e684d801
diff --git a/apps/desktop/src/app/chat/right-rail/preview-act.test.ts b/apps/desktop/src/app/chat/right-rail/preview-act.test.tsindex b53e0463420..2b68b1eb994 100644--- a/apps/desktop/src/app/chat/right-rail/preview-act.test.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-act.test.ts@@ -4,6 +4,7 @@ import { $rightRailActiveTabId } from '@/store/layout'import { closeRightRail, openPreview, type PreviewTarget } from '@/store/preview'import { actOnActivePreview } from './preview-act'+import { registerPreviewInput } from './preview-input'import { registerPreviewNav } from './preview-nav'import { registerPreviewScriptRunner } from './preview-script-runner'@@ -11,7 +12,7 @@ function urlTarget(url: string): PreviewTarget {return { kind: 'url', label: 'Browser', source: url, url }}-describe('actOnActivePreview (act_preview tool)', () => {+describe('actOnActivePreview (drive_preview tool)', () => {// URL targets share the singleton Browser tab id, so anything a test// registers would answer the next one.let cleanups: Array<() => void> = []@@ -105,6 +106,192 @@ describe('actOnActivePreview (act_preview tool)', () => {expect((await actOnActivePreview({ kind: 'click', ref: '@e1' })).error).toContain('did not answer')})+ /** A pane that answers the locate trip with a fixed on-screen point, and the+ * read-back trip with an empty inventory. Returns the input spy. */+ const withDrivenPane = () => {+ const tabId = openBrowserTab()+ const send = vi.fn()++ cleanups.push(+ registerPreviewScriptRunner(tabId, async code =>+ code.includes('"kind":"locate"')+ ? JSON.stringify({ acted: 'looking at button "Save"', point: { x: 120, y: 80 }, success: true })+ : // `hit` is the page's witness that the real pointerdown arrived.+ JSON.stringify({ elements: [], hit: { tag: 'BUTTON', trusted: true }, success: true })+ )+ )+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send }))++ return send+ }++ const sentTypes = (send: ReturnType<typeof vi.fn>) => send.mock.calls.map(([event]) => event.type)++ it('clicks with real input, walking the pointer to where the page said', async () => {+ const send = withDrivenPane()++ const result = await actOnActivePreview({ kind: 'click', ref: '@e1' })+ const types = sentTypes(send)++ // Stepped rather than teleported: a page learns it is hovered from a stream+ // of moves, and one jump to the target skips everything in between.+ expect(types.filter(type => type === 'mouseMove').length).toBeGreaterThan(1)+ expect(types).toContain('mouseDown')+ expect(types).toContain('mouseUp')+ expect(send.mock.calls.map(([event]) => event).find(event => event.type === 'mouseDown')).toMatchObject({+ x: 120,+ y: 80+ })+ expect(result.acted).toBe('clicked button "Save"')+ })++ it('types by pressing keys, after selecting whatever the field held', async () => {+ const send = withDrivenPane()++ await actOnActivePreview({ kind: 'type', ref: '@e1', submit: true, text: 'hi' })++ const events = send.mock.calls.map(([event]) => event)+ const chars = events.filter(event => event.type === 'char').map(event => event.keyCode)++ // One click to focus, then select-all by keyboard — NOT the triple-click+ // this used to do. A triple-click is a pointer gesture, so it grabs the+ // paragraph under the cursor whenever the target turns out not to be a+ // field, and the agent was leaving pages with their body text highlighted.+ expect(events.filter(event => event.type === 'mouseDown').map(event => event.clickCount)).toEqual([1])+ expect(events.filter(event => event.type === 'keyDown' && event.keyCode === 'a')[0]).toMatchObject({+ modifiers: ['control', 'meta']+ })+ // The chord must not send a `char` phase, or select-all types a literal 'a'.+ expect(chars).toEqual(['h', 'i', 'Enter'])+ })++ it('hovers by walking the pointer over and leaving it there', async () => {+ const send = withDrivenPane()++ const result = await actOnActivePreview({ kind: 'hover', ref: '@e1' })+ const types = sentTypes(send)++ expect(types).toContain('mouseMove')+ // The whole request is "be on it" — a click here would open the dropdown the+ // agent was trying to reveal, or worse, activate it.+ expect(types).not.toContain('mouseDown')+ expect(result.acted).toBe('hovered over button "Save"')+ })++ // The witness only speaks for verbs that put the button down. Demanding one+ // from a key press reported every press as a failure.+ it('does not expect a click witness from a verb that never clicks', async () => {+ const tabId = openBrowserTab()++ cleanups.push(+ registerPreviewScriptRunner(tabId, async code =>+ code.includes('"kind":"locate"')+ ? JSON.stringify({ acted: 'looking at textbox "Search"', point: { x: 40, y: 20 }, success: true })+ : JSON.stringify({ elements: [], hit: null, success: true })+ )+ )+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send: vi.fn() }))++ for (const action of [+ { key: 'Escape', kind: 'press', ref: '@e1' },+ { kind: 'hover', ref: '@e1' }+ ]) {+ expect(await actOnActivePreview(action)).toMatchObject({ success: true })+ }+ })++ it('scrolls by wheeling for real, not by scripting the page', async () => {+ const tabId = openBrowserTab()+ const send = vi.fn()+ let scripted = false++ cleanups.push(+ registerPreviewScriptRunner(tabId, async code => {+ scripted ||= code.includes('"kind":"scroll"')++ return code.includes('scrollHeight')+ ? JSON.stringify({ page: 700, point: { x: 500, y: 400 }, span: 4_000, success: true })+ : JSON.stringify({ elements: [], success: true })+ })+ )+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send }))++ await actOnActivePreview({ kind: 'scroll' })++ const wheels = send.mock.calls.map(([event]) => event).filter(event => event.type === 'mouseWheel')++ // A stream of notches, not one delta: scroll-linked headers and lazy loaders+ // only react to the events, so a scripted scrollBy leaves them asleep.+ expect(wheels.length).toBeGreaterThan(1)+ // Electron's wheel delta is wheelDelta-signed, so scrolling DOWN is negative.+ expect(wheels.every(event => event.deltaY < 0)).toBe(true)+ expect(scripted).toBe(false)+ })++ it('says so plainly when the page has nothing to scroll', async () => {+ const tabId = openBrowserTab()++ cleanups.push(+ registerPreviewScriptRunner(tabId, async () =>+ JSON.stringify({ page: 700, point: { x: 500, y: 400 }, span: 0, success: true })+ )+ )+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send: vi.fn() }))++ expect(await actOnActivePreview({ kind: 'scroll' })).toMatchObject({ note: expect.stringContaining('nothing to scroll') })+ })++ it('fails loudly when the pointer input never reaches the page', async () => {+ const tabId = openBrowserTab()++ cleanups.push(+ registerPreviewScriptRunner(tabId, async code =>+ code.includes('"kind":"locate"')+ ? JSON.stringify({ acted: 'looking at button "Save"', point: { x: 12, y: 8 }, success: true })+ : JSON.stringify({ elements: [], hit: null, success: true })+ )+ )+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send: vi.fn() }))++ const result = await actOnActivePreview({ kind: 'click', ref: '@e1' })++ // Everything else about this action travels on the script channel and would+ // report success whether or not a single event landed.+ expect(result.success).toBe(false)+ expect(result.error).toContain('never reached the page')+ })++ it('says so when the overlay itself swallowed the click', async () => {+ const tabId = openBrowserTab()++ cleanups.push(+ registerPreviewScriptRunner(tabId, async code =>+ code.includes('"kind":"locate"')+ ? JSON.stringify({ acted: 'looking at button "Save"', point: { x: 12, y: 8 }, success: true })+ : JSON.stringify({ elements: [], hit: { tag: 'HERMES-WATCH', trusted: true }, success: true })+ )+ )+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send: vi.fn() }))++ expect((await actOnActivePreview({ kind: 'click', ref: '@e1' })).note).toContain('overlay intercepted')+ })++ it('falls back to scripted events when the pane exposes no input channel', async () => {+ let injected = ''++ withRunner(async code => {+ injected = code++ return JSON.stringify({ acted: 'clicked', success: true })+ })++ await actOnActivePreview({ kind: 'click', ref: '@e1' })++ // The one-trip shape: the engine both acts and re-reads, no locate handshake.+ expect(injected).toContain('"kind":"click"')+ expect(injected).not.toContain('"kind":"locate"')+ })+it('routes history verbs to the pane instead of the guest page', async () => {const back = vi.fn()const runner = vi.fn()diff --git a/apps/desktop/src/app/chat/right-rail/preview-act.ts b/apps/desktop/src/app/chat/right-rail/preview-act.tsindex 495ce45f0a7..bcef505fbcb 100644--- a/apps/desktop/src/app/chat/right-rail/preview-act.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-act.ts@@ -1,14 +1,23 @@/*** PREVIEW ACT — performs the agent's interactions inside the preview pane's- * guest page, so `act_preview` drives whatever web app is open in the in-app+ * guest page, so `drive_preview` drives whatever web app is open in the in-app* browser.** The guest page is out-of-process; nothing here can touch its DOM directly.- * Instead each action injects the engine SOURCE over `executeJavaScript` (see- * lib/preview-act/act-in-page.ts's self-containment contract), parked on a- * window global alongside the ref holder so '@e5' still resolves on the next- * call. Injection is idempotent and vanishes with the page — a navigation- * drops the refs, which the engine reports rather than clicking the wrong node.+ * Two separate channels reach it, and the split matters:+ *+ * - `executeJavaScript` injects the engine SOURCE (see+ * lib/preview-act/act-in-page.ts's self-containment contract) to RESOLVE+ * and READ — turn '@e5' into a node, measure it, inventory the page. It is+ * parked on a window global alongside the ref holder so refs survive+ * between calls, and it vanishes with the page, so a navigation drops the+ * refs and the engine reports that instead of clicking the wrong node.+ * - `sendInputEvent` (preview-drive.ts) does the ACTING, as real Chromium+ * input. Script can only dispatch synthetic events, which the page can tell+ * apart and which never move the browser's own hover or focus target.+ *+ * Panes with no input channel — a remote HTML preview — fall back to the+ * engine's synthetic events, which is worse but still works.** A mutating action settles briefly and returns a fresh inventory, so the* click → re-read → click loop costs one round trip instead of two.@@ -18,46 +27,461 @@*/import { actInPage, type PreviewActAction, type PreviewActResult } from '@/lib/preview-act/act-in-page'+import { watchInPage } from '@/lib/preview-act/watch-in-page'+import { clickAt, glideTo, pointerPlaced, pressKey, selectAll, typeText, wheelBy } from './preview-drive'+import { activePreviewInput, type PreviewInputHandle } from './preview-input'import { activePreviewNav, type PreviewNavHandle } from './preview-nav'-import { activePreviewScriptRunner } from './preview-script-runner'+import { activePreviewScriptRunner, type PreviewScriptRunner } from './preview-script-runner'/** Verbs the pane owns; a guest page cannot drive its own history. */const NAV_ACTIONS: readonly (keyof PreviewNavHandle)[] = ['back', 'forward', 'reload']/** How long a click/type is given to land before the page is re-inventoried.- * Long enough for a framework re-render, short enough not to stall the turn. */-const SETTLE_MS = 400+ * Long enough for a framework re-render, short enough not to stall the turn.+ * A render that misses this window is not lost — the NEXT action re-reads the+ * page anyway, so the cost of being early is a slightly stale inventory, not a+ * wrong one. That trade is worth several hundred ms on every single step. */+const SETTLE_MS = 220++/** Cap on one round trip into the guest page. A click that starts a navigation+ * tears the document down mid-settle, so the injected promise dies with it and+ * `executeJavaScript` never settles — without this the tool eats its whole+ * 45s bridge deadline for what was actually a successful click. */+const ACT_TIMEOUT_MS = 8_000++/** Verbs that get the look-then-act treatment: locate the target, walk the+ * pointer there, then send real input. Actions with no single target (scroll,+ * elements) are absent and skip it. */+const DRIVEN: readonly string[] = ['click', 'hover', 'press', 'type']++/** Verbs that put the mouse button down, and so are the only ones the pointerdown+ * witness can speak to. `press` and `hover` never click, so demanding a witness+ * from them would report every one of them as a failure. */+const CLICKS: readonly string[] = ['click', 'type']const NOTHING_OPEN = 'No live page is open in the in-app browser — open one with open_preview first.'-/** Build the idempotent inject-and-run script for one action. */-function buildActScript(action: PreviewActAction, settleMs: number): string {- return `(function () {- var w = window;- if (!w.__hermesAct) {- w.__hermesActHolder = {};- w.__hermesAct = (${actInPage.toString()});+const NAVIGATED = 'The page stopped answering right after — it is probably navigating. Call elements to see where you landed.'++/** A fingerprint of the overlay's source, so the guest page can tell that the+ * code it is running has changed underneath it.+ *+ * It needs one because the overlay memoizes its own chrome: the cursor, the+ * lock frame and the scan line are built ONCE per page and then reused, so an+ * edit to any of their styles lands in the injected source, gets injected, and+ * changes nothing — the layers it would have styled were built by the previous+ * version and are still on the page. In dev that reads as "HMR didn't pick up+ * my CSS"; in production it is a long-lived tab pinned to whichever build first+ * touched it, across an app upgrade.+ *+ * Content-addressed rather than a length or a version literal: the change that+ * exposed this was one hex colour for another, which is byte-for-byte the same+ * length, and a hand-maintained version is a step someone forgets. */+const WATCH_TAG = (() => {+ const source = watchInPage.toString()+ let hash = 5381++ for (let i = 0; i < source.length; i++) {+ hash = ((hash << 5) + hash + source.charCodeAt(i)) | 0}- var act = function (a) { return w.__hermesAct(document, w.__hermesActHolder, a); };++ return hash+})()++/** Injected once per page: the engine, the overlay, and the two helpers every+ * script below shares. Idempotent — re-running it on a live page is a no-op. */+const preamble = () => ` var w = window;+ // Reassigned on every trip rather than cached behind a guard: the source is in+ // this payload either way, so the guard saved nothing and pinned a long-lived+ // tab to whichever build first touched it. The holder is the exception — it+ // carries the aimed element from the locate trip to the act trip.+ w.__hermesActHolder = w.__hermesActHolder || {};+ w.__hermesAct = (${actInPage.toString()});+ w.__hermesWatch_fn = (${watchInPage.toString()});+ w.__hermesWatchTag = ${WATCH_TAG};+ var holder = w.__hermesActHolder;+ var act = function (a) { return w.__hermesAct(document, holder, a); };+ var watch = function (stage, label) {+ try { w.__hermesWatch_fn(document, holder, stage, label); } catch (err) {}+ };+ var wait = function (ms) { return new Promise(function (resolve) { setTimeout(resolve, ms); }); };+ // Sit out a smooth scroll so the pointer is aimed at a target that has stopped+ // moving. A scroll that never started fires no scrollend, so only wait on one+ // we can actually see happening; capture catches nested scrollers, whose+ // scrollend does not bubble.+ var restAfterScroll = function () {+ return new Promise(function (resolve) {+ var sc = document.scrollingElement || document.documentElement;+ var x0 = sc ? sc.scrollLeft : 0;+ var y0 = sc ? sc.scrollTop : 0;+ requestAnimationFrame(function () {+ if (!sc || (sc.scrollLeft === x0 && sc.scrollTop === y0)) { return resolve(); }+ var done = false;+ var finish = function () {+ if (done) { return; }+ done = true;+ document.removeEventListener('scrollend', finish, true);+ clearTimeout(timer);+ resolve();+ };+ var timer = setTimeout(finish, 350);+ document.addEventListener('scrollend', finish, true);+ });+ });+ };`++/** Bring the target on screen, mark it, and report where it came to rest. */+function buildLocateScript(action: PreviewActAction, focus: boolean): string {+ const locate = { focus, kind: 'locate', ref: action.ref, selector: action.selector }++ return `(function () {+${preamble()}+ var locate = ${JSON.stringify(locate)};+ var found = act(locate);+ if (!found.success) { return Promise.resolve(JSON.stringify(found)); }+ watch('aim');+ // Arm a witness for the real input that is about to arrive. Without it a+ // click that never reached the page is indistinguishable from one the page+ // ignored, and the agent would report success either way.+ w.__hermesHit = null;+ document.addEventListener('pointerdown', function (e) {+ w.__hermesHit = { tag: e.target ? e.target.tagName : '?', trusted: e.isTrusted === true };+ }, { capture: true, once: true });+ // Measure again once the scroll has stopped: real input is aimed at a fixed+ // viewport coordinate, so it has to be where the target ENDS UP.+ return restAfterScroll().then(function () {+ var settled = act(locate);+ var best = settled.success ? settled : found;+ var at = best.point;+ // Last line of defence before the pointer is sent somewhere real. An element+ // that is still outside the viewport after we scrolled to it is hidden, not+ // placed, and aiming at it would drive the cursor off into a corner and+ // click whatever happens to be under that coordinate.+ if (at && (at.x < 0 || at.y < 0 || at.x > window.innerWidth || at.y > window.innerHeight)) {+ return JSON.stringify({+ error: 'That element is still off-screen after scrolling to it, so it is hidden rather than clickable. Call elements again for what is really on the page.',+ success: false+ });+ }+ return JSON.stringify(best);+ });+})()`+}++/** Put up a mark that outlives the action that made it. Every other cue on the+ * overlay retires on a timer, which is right for narrating a click and no use+ * at all for holding a finding on screen while the agent keeps working. */+function buildPinScript(action: PreviewActAction, label: string): string {+ const locate = { kind: 'locate', ref: action.ref, selector: action.selector }++ return `(function () {+${preamble()}+ var found = act(${JSON.stringify(locate)});+ if (!found.success) { return JSON.stringify(found); }+ watch('pin', ${JSON.stringify(label)});+ return JSON.stringify({ acted: 'pinned ' + String(found.acted || 'it').replace(/^looking at /, ''), success: true });+})()`+}++/** Freeze the whole visible field as marks. Needs a fresh inventory first, so+ * the overlay has both the field to draw and the refs to number it by. */+function buildHoldScript(): string {+ return `(function () {+${preamble()}+ var found = act({ kind: 'elements' });+ if (!found.success) { return JSON.stringify(found); }+ watch('hold');+ return JSON.stringify({ acted: 'held the field', elements: found.elements, title: found.title, url: found.url, success: true });+})()`+}++/** Rattle through the field one box at a time. Needs a fresh inventory for the+ * overlay to pick from, and nothing else — the page is never touched. */+function buildStrobeScript(): string {+ return `(function () {+${preamble()}+ var found = act({ kind: 'elements' });+ if (!found.success) { return JSON.stringify(found); }+ watch('strobe');+ return JSON.stringify({ acted: 'strobed the field', elements: found.elements, title: found.title, url: found.url, success: true });+})()`+}++/** Take one mark down, or — with nothing to aim at — all of them. */+function buildUnpinScript(action: PreviewActAction): string {+ const locate = { kind: 'locate', ref: action.ref, selector: action.selector }+ const one = !!(action.ref || action.selector)++ return `(function () {+${preamble()}+${+ one+ ? ` var found = act(${JSON.stringify(locate)});+ if (!found.success) { return JSON.stringify(found); }+ var gone = 'unpinned ' + String(found.acted || 'it').replace(/^looking at /, '');`+ : ` holder.aimed = null;+ var gone = 'cleared every pin';`+}+ watch('unpin');+ return JSON.stringify({ acted: gone, success: true });+})()`+}++/** Mark the hit, let the page react, and hand back a fresh inventory. */+function buildFinishScript(settleMs: number): string {+ return `(function () {+${preamble()}+ watch('strike');+ return wait(${settleMs}).then(function () {+ // A rescan that throws must still answer — an unresolved promise here costs+ // the whole bridge deadline.+ try {+ var out = act({ kind: 'elements' });+ watch('sweep');+ out.hit = w.__hermesHit || null;+ return JSON.stringify(out);+ } catch (err) {+ return JSON.stringify({ note: 'The page changed before it could be re-read: ' + err, success: true });+ }+ });+})()`+}++/** The no-real-input fallback: the engine both acts and reads, in one trip.+ * Both reads mark the field — the explicit `elements` call and the re-read+ * every other verb does on its way out — so the page is marked after every+ * single action rather than only when the agent asks for an inventory outright.+ * They mark it differently, though, and the difference is what each one MEANS:+ * an outright `elements` is the agent reading the whole page, which is the+ * moment worth showing, so it strobes. The re-read after a click is+ * housekeeping, and strobing there would put five seconds of noise between+ * every step of a task, so it sweeps. The two never collide: an `elements` call+ * settles in 0ms and returns before the re-read. */+function buildScriptedScript(action: PreviewActAction, settleMs: number): string {+ return `(function () {+${preamble()}var result = act(${JSON.stringify(action)});- if (!result.success || ${settleMs} <= 0) {- return Promise.resolve(JSON.stringify(result));+ ${+ action.kind === 'elements'+ ? "if (result.success) { watch('strobe'); }"+ : ''}- // Re-inventory after the page has had a moment to react, so the agent's next- // ref is drawn from the DOM its own click produced.- return new Promise(function (resolve) {- setTimeout(function () {+ if (!result.success || ${settleMs} <= 0) { return Promise.resolve(JSON.stringify(result)); }+ return wait(${settleMs}).then(function () {+ try {var after = act({ kind: 'elements' });+ watch('sweep');result.elements = after.elements;result.url = after.url;result.title = after.title;- resolve(JSON.stringify(result));- }, ${settleMs});+ } catch (err) {+ result.note = 'The page changed before it could be re-read: ' + err;+ }+ return JSON.stringify(result);});})()`}+/** The outcome of one round trip into the page. `silent` is its own case on+ * purpose: a page that stops answering mid-action is navigating, whereas one+ * that answers with nothing is broken, and the agent needs to hear the+ * difference. */+type Trip = { error: string; kind: 'failed' } | { kind: 'answered'; result: PreviewActResult } | { kind: 'silent' }++async function runJson(run: PreviewScriptRunner, code: string): Promise<Trip> {+ const raw = await Promise.race([+ run(code).catch((error: unknown) => new Error(String(error))),+ new Promise<undefined>(resolve => setTimeout(resolve, ACT_TIMEOUT_MS))+ ])++ if (raw === undefined) {+ return { kind: 'silent' }+ }++ if (raw instanceof Error) {+ return { error: 'The page rejected the action: ' + raw.message, kind: 'failed' }+ }++ if (typeof raw !== 'string' || !raw) {+ return { error: 'The page did not answer the action.', kind: 'failed' }+ }++ return { kind: 'answered', result: JSON.parse(raw) as PreviewActResult }+}++/** Past tense of the verb the agent asked for, against what it actually hit. */+function describeDone(action: PreviewActAction, target: string): string {+ if (action.kind === 'type') {+ return 'typed into ' + target + (action.submit ? ' and submitted' : '')+ }++ if (action.kind === 'press') {+ return 'pressed ' + (action.key || '') + ' on ' + target+ }++ if (action.kind === 'hover') {+ return 'hovered over ' + target+ }++ return 'clicked ' + target+}++/** Look at the target, walk the pointer over, and act on it for real. */+async function driveAction(+ run: PreviewScriptRunner,+ input: PreviewInputHandle,+ action: PreviewActAction+): Promise<PreviewActResult> {+ // A key press must not be preceded by a click — that would activate the+ // control rather than type into it — so the page hands it focus instead.+ const trip = await runJson(run, buildLocateScript(action, action.kind === 'press'))++ if (trip.kind === 'failed') {+ return { error: trip.error, success: false }+ }++ if (trip.kind === 'silent') {+ return { acted: action.kind, note: NAVIGATED, success: true }+ }++ const found = trip.result++ if (!found.success) {+ return found+ }++ if (!found.point) {+ return { error: 'Could not work out where that element is on screen.', success: false }+ }++ await glideTo(input, found.point)++ if (action.kind === 'click') {+ await clickAt(input)+ } else if (action.kind === 'type') {+ if (found.typable === false) {+ return {+ error: `${String(found.acted || 'That').replace(/^looking at /, '')} is not a text field, so typing into it would only select the text under the pointer. Click it if it opens one, then type into that.`,+ success: false+ }+ }++ input.focus()+ await clickAt(input)+ // Select-all inside the now-focused field, so typing replaces what is there+ // the way it would for a person. NOT a triple-click: that is a pointer+ // gesture and selects the paragraph under the cursor whenever the target+ // turns out not to be a field.+ await selectAll(input)+ await typeText(input, action.text ?? '')++ if (action.submit) {+ await pressKey(input, 'Enter')+ }+ } else if (action.kind === 'press') {+ input.focus()+ await pressKey(input, action.key || 'Enter')+ }+ // hover is the glide and nothing else — the pointer is already sitting on the+ // target, which is the whole request.++ const target = String(found.acted || '').replace(/^looking at /, '')+ const after = await runJson(run, buildFinishScript(SETTLE_MS))+ const acted = describeDone(action, target)++ // The action itself already happened as real input, so a page that will not+ // answer the read-back is a page that navigated — never a failed click.+ if (after.kind !== 'answered') {+ return { acted, note: NAVIGATED, success: true }+ }++ const { hit, ...result } = after.result as PreviewActResult & { hit?: { tag: string; trusted: boolean } | null }++ // The witness the locate trip armed. No record means the input never reached+ // the document, which the agent must hear about — every other signal here+ // travels on the script channel and would report success regardless.+ if (!hit && CLICKS.indexOf(action.kind) !== -1) {+ return {+ ...result,+ error: 'The pointer input never reached the page, so nothing was ' + acted.split(' ')[0] + '.',+ success: false+ }+ }++ return { ...result, acted, note: hitNote(hit), success: true }+}++/** Flag a click the overlay intercepted, which would otherwise look like a page+ * that simply ignored it. */+function hitNote(hit?: { tag: string; trusted: boolean } | null): string | undefined {+ return hit && hit.tag === 'HERMES-WATCH'+ ? 'The action overlay intercepted the click instead of the page.'+ : undefined+}++/** How far a screenful is, whether there is anywhere to go, and a spot to wheel+ * over — the renderer cannot see the guest viewport to work any of it out. */+function buildScrollAnchorScript(): string {+ return `(function () {+${preamble()}+ var sc = document.scrollingElement || document.documentElement;+ var track = sc.clientHeight || window.innerHeight;+ return Promise.resolve(JSON.stringify({+ page: Math.round(window.innerHeight * 0.9),+ point: { x: Math.round(window.innerWidth / 2), y: Math.round(track / 2) },+ span: sc.scrollHeight - track,+ success: true+ }));+})()`+}++/** Scroll the page the way a hand does — wheel it. The scripted path calls+ * `scrollBy`, which moves the page without the page ever seeing an input+ * event, so scroll-linked headers, reveal animations and infinite-scroll+ * loaders all stay asleep through a scroll that looked like it happened. */+async function driveScroll(+ run: PreviewScriptRunner,+ input: PreviewInputHandle,+ action: PreviewActAction,+): Promise<PreviewActResult> {+ const far = action.amount ?? 0+ const trip = await runJson(+ run,+ buildScrollAnchorScript()+ )++ if (trip.kind === 'failed') {+ return { error: trip.error, success: false }+ }++ if (trip.kind === 'silent') {+ return { acted: 'scrolled', note: NAVIGATED, success: true }+ }++ const anchor = trip.result as PreviewActResult & { page?: number; span?: number }++ if (!anchor.span) {+ return { ...anchor, acted: 'scrolled the page', note: 'The page has nothing to scroll — it all fits already.' }+ }++ // A person does not move the mouse to scroll; the wheel turns wherever their+ // hand already is. Only send it somewhere if it has never been anywhere.+ if (!pointerPlaced() && anchor.point) {+ await glideTo(input, anchor.point)+ }++ await wheelBy(input, action.amount ?? anchor.page ?? 600)++ const after = await runJson(run, buildFinishScript(SETTLE_MS))++ if (after.kind !== 'answered') {+ return { acted: 'scrolled the page', note: NAVIGATED, success: true }+ }++ return { ...after.result, acted: 'scrolled the page', success: true }+}+/** Run one action against the ACTIVE preview tab's page. `kind` is a bare* string: the verb arrives off the wire, and the history ones never reach* the in-page engine. */@@ -87,12 +511,57 @@ export async function actOnActivePreview(}const typed = action as PreviewActAction++ // Annotation, not interaction: nothing is clicked, nothing settles, and the+ // page is not re-read, so these skip the whole act-then-inventory path.+ if (typed.kind === 'pin' || typed.kind === 'unpin' || typed.kind === 'hold' || typed.kind === 'strobe') {+ const mark =+ typed.kind === 'hold'+ ? buildHoldScript()+ : typed.kind === 'strobe'+ ? buildStrobeScript()+ : typed.kind === 'pin'+ ? buildPinScript(typed, typed.text || '')+ : buildUnpinScript(typed)+ const trip = await runJson(run, mark)++ if (trip.kind === 'failed') {+ return { error: trip.error, success: false }+ }++ return trip.kind === 'answered' ? trip.result : { acted: typed.kind, note: NAVIGATED, success: true }+ }++ const input = activePreviewInput()++ if (input && DRIVEN.indexOf(typed.kind) !== -1) {+ return driveAction(run, input, typed)+ }++ // A plain page scroll is a wheel gesture. Jumping to an end is not — no hand+ // wheels to the bottom of a long article — so `to` stays a scripted glide.+ const plain = typed.kind === 'scroll' && !typed.to && !typed.ref && !typed.selector++ if (plain && input) {+ return driveScroll(run, input, typed)+ }+const settle = typed.kind === 'elements' ? 0 : SETTLE_MS- const raw = await run(buildActScript(typed, settle))+ const scripted = await runJson(run, buildScriptedScript(typed, settle))- if (typeof raw !== 'string' || !raw) {- return { error: 'The page did not answer the action.', success: false }+ if (scripted.kind === 'failed') {+ return { error: scripted.error, success: false }}- return JSON.parse(raw) as PreviewActResult+ // The action almost certainly landed — a page that stops answering right+ // after a click is one that navigated. Say so instead of failing it.+ return scripted.kind === 'silent' ? { acted: typed.kind, note: NAVIGATED, success: true } : scripted.result+}++// Self-accept so an edit here, or to the in-page sources this module+// stringifies, doesn't reload the whole renderer out from under a live session.+// The bridge re-requests this module per action in dev, so it picks the change+// up without one (see loadPreviewEngine in gateway-event/desktop-bridge.ts).+if (import.meta.hot) {+ import.meta.hot.accept()}diff --git a/apps/desktop/src/app/chat/right-rail/preview-mind.ts b/apps/desktop/src/app/chat/right-rail/preview-mind.tsnew file mode 100644index 00000000000..3f7a1856c47--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-mind.ts@@ -0,0 +1,29 @@+/**+ * IDLE PULSE — keeps the preview overlay alive while the model reasons.+ *+ * Everything else the overlay draws is narration of an action, so the pane goes+ * dark for the gap between actions — which is most of the time the agent spends+ * on a page, and the part where it is deciding what to do with what it just+ * read. A page that stops responding the moment the agent is thinking hardest+ * reads as the agent having wandered off.+ *+ * This is deliberately NOT part of the act pipeline: a turn boundary only has+ * to poke the overlay the last action left behind. See preview-nudge.ts.+ */++import { $busy } from '@/store/session'++import { nudgeOverlay } from './preview-nudge'++// Module-level, matching how review.ts and coding-status.ts watch this edge. It+// is inert without a live pane, so there is nothing to mount or tear down.+let running = $busy.get()++$busy.subscribe(busy => {+ if (busy === running) {+ return+ }++ running = busy+ nudgeOverlay(busy ? 'think' : 'rest')+})diff --git a/apps/desktop/src/app/chat/right-rail/preview-nudge.ts b/apps/desktop/src/app/chat/right-rail/preview-nudge.tsnew file mode 100644index 00000000000..8a8f4199878--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-nudge.ts@@ -0,0 +1,38 @@+/**+ * OVERLAY NUDGE — the one way to say a stage to an overlay that is ALREADY on+ * the page.+ *+ * The act pipeline (preview-act.ts) injects the whole engine because it has to:+ * it needs to resolve a ref, measure a node and read the page back. The stages+ * that only narrate — the idle pulse, the read wipe — need none of that. They+ * are one function call against something the last action already left on the+ * page, so re-shipping the engine to make it would put the payload on the wire+ * on every turn boundary.+ *+ * A page the agent has never acted on has no overlay, and the nudge is a no-op+ * there. That is the right answer rather than a gap: chrome on a page the agent+ * never touched would be a lie about what it did.+ */++import type { WatchStage } from '@/lib/preview-act/watch-in-page'++import { activePreviewScriptRunner } from './preview-script-runner'++/** Run one stage against the active pane's overlay, if it has one. */+export function nudgeOverlay(stage: WatchStage): void {+ const run = activePreviewScriptRunner()++ if (!run) {+ return+ }++ void run(`(function () {+ var w = window;+ var fn = w.__hermesWatch_fn;+ if (!fn) { return 'cold'; }+ try { fn(document, w.__hermesActHolder || {}, ${JSON.stringify(stage)}); } catch (err) {}+ return 'ok';+})()`).catch(() => {+ // The page navigated out from under us. The next action re-injects.+ })+}diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex 076fc4a94f6..817cec638a5 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -1,3 +1,7 @@+// Side-effect import: watches the turn edge so the overlay keeps a pulse while+// the model reasons. Lives here because the pane is what makes it reachable.+import './preview-mind'+import { useStore } from '@nanostores/react'import type { PointerEvent as ReactPointerEvent } from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -28,7 +32,7 @@ import {import { type ConsoleEntry } from './preview-console-state'import { previewConsoleState } from './preview-console-store'import { LocalFilePreview, PreviewEmptyState } from './preview-file'-import { registerPreviewInput, type PreviewInputEvent } from './preview-input'+import { type PreviewInputEvent, registerPreviewInput } from './preview-input'import { PREVIEW_BROWSER_ATTR, registerPreviewNav } from './preview-nav'import { registerPreviewPageReader } from './preview-reader'import { registerPreviewScriptRunner } from './preview-script-runner'diff --git a/apps/desktop/src/app/chat/right-rail/preview-reader.ts b/apps/desktop/src/app/chat/right-rail/preview-reader.tsindex 7f48c8cbb15..97a372db182 100644--- a/apps/desktop/src/app/chat/right-rail/preview-reader.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-reader.ts@@ -15,6 +15,8 @@import { $rightRailActiveTabId } from '@/store/layout'import { $previewTabs } from '@/store/preview'+import { nudgeOverlay } from './preview-nudge'+export interface PreviewReadOptions {/** Characters to return from `start` (capped at PREVIEW_READ_MAX_CHARS). */count?: number@@ -89,6 +91,13 @@ export async function readActivePreview(opts: PreviewReadOptions = {}): Promise<try {const page = await reader()+ // Say it on the page. Reading is by far the cheapest thing the agent+ // does — a few hundredths of a second against a model round trip either+ // side of it — so a run of reads used to leave the pane dark for the+ // twenty seconds it took to page through a document, immediately after+ // the one moment that showed anything.+ nudgeOverlay('read')+return windowText({ kind: target.kind, path: target.path, title: page.title || target.label, url: page.url || target.url },page.text,diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.tsindex 1a8cee9d02e..227a4eb1288 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/desktop-bridge.ts@@ -11,6 +11,34 @@ import { setMessages } from '@/store/session'import type { GatewayEventContext } from './types'+/** The preview engine, loaded on demand so ~25KB of page-injectable source stays+ * off the boot path.+ *+ * In dev that lazy chunk is also a trap. The browser caches a dynamic import by+ * URL for the life of the page, so this bridge would hand every action to+ * whichever build of the engine loaded first, and no edit to it — or to the+ * overlay whose source it stringifies into the page — would reach the guest+ * until the whole window reloaded. Asking for a fresh copy is more reliable+ * than trusting hot-update propagation to reach a module nothing statically+ * imports; the dev server stamps the dependency URLs it has invalidated, so a+ * fresh engine pulls a fresh overlay down with it.+ *+ * The literal path is what a bare specifier can't be here, and it has to track+ * this module's real location — hence the fall back to the static import, which+ * is also the only branch production keeps, `import.meta.hot` being stripped+ * there along with everything it guards. */+const loadPreviewEngine = () => {+ const stable = () => import('@/app/chat/right-rail/preview-act')++ if (!import.meta.hot) {+ return stable().then(mod => mod.actOnActivePreview)+ }++ return import(/* @vite-ignore */ '/src/app/chat/right-rail/preview-act.ts?hot=' + Date.now())+ .catch(stable)+ .then(mod => mod.actOnActivePreview as Awaited<ReturnType<typeof stable>>['actOnActivePreview'])+}+/** Desktop-surface bridge events: read-back requests the agent blocks on* (terminal/preview/window), agent terminal streaming, pane reveal, and* message reactions. */@@ -57,7 +85,7 @@ export function handleDesktopBridgeEvent(ctx: GatewayEventContext): boolean {}if (event.type === 'preview.act.request') {- // act_preview tool: click/type/scroll/press inside the guest page, or+ // drive_preview tool: click/type/scroll/press inside the guest page, or// drive the pane's history. Dynamic import keeps the injected engine off// the boot path. Active session only: a background turn must never reach// into the page the user is working in (desktop AGENTS.md: offer, don't@@ -72,9 +100,9 @@ export function handleDesktopBridgeEvent(ctx: GatewayEventContext): boolean {})if (isActiveEvent) {- void import('@/app/chat/right-rail/preview-act')- .then(({ actOnActivePreview }) =>- actOnActivePreview({+ void loadPreviewEngine()+ .then(run =>+ run({amount: payload?.amount,key: payload?.key,kind: payload?.action ?? '',diff --git a/apps/desktop/src/lib/preview-act/act-in-page.test.ts b/apps/desktop/src/lib/preview-act/act-in-page.test.tsindex aa1985fb7a1..5fafdb91e89 100644--- a/apps/desktop/src/lib/preview-act/act-in-page.test.ts+++ b/apps/desktop/src/lib/preview-act/act-in-page.test.ts@@ -3,14 +3,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { actInPage, type PreviewActHolder } from './act-in-page'/** jsdom lays nothing out, so every rect is 0×0 and the engine's visibility- * check would reject the whole page. Give elements a plausible box and let+ * check would reject the whole page. Give elements a plausible box, honouring+ * an explicit width/height so a test can lay out a 1px one, and let* `display: none` (which jsdom DOES compute) carry the hiding. */function layOutTheDocument() {vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {- const hidden = getComputedStyle(this).display === 'none'- const size = hidden ? 0 : 40+ const style = getComputedStyle(this)+ const width = style.display === 'none' ? 0 : parseFloat(style.width) || 40+ const height = style.display === 'none' ? 0 : parseFloat(style.height) || 40+ const left = parseFloat(style.left) || 0- return { bottom: size, height: size, left: 0, right: size, top: 0, width: size, x: 0, y: 0 } as DOMRect+ return { bottom: height, height, left, right: left + width, top: 0, width, x: left, y: 0 } as DOMRect})}@@ -29,6 +32,33 @@ beforeEach(() => {vi.restoreAllMocks()layOutTheDocument()Element.prototype.scrollIntoView = vi.fn()+ // jsdom has no hit-testing at all, so the engine skips the occlusion check+ // here by default. Tests that stand one in must not leak it into the next.+ delete (document as Document & { elementFromPoint?: unknown }).elementFromPoint+})++describe('self-containment', () => {+ // The pane injects `actInPage.toString()` into the guest page, where module+ // scope does not exist. A single free identifier (a module-level constant, an+ // imported helper) is a ReferenceError on every call, and Electron reports it+ // only as "Script failed to execute" — so evaluate the source the way the+ // guest does and run a real action through it.+ it('runs after being stringified and eval’d with no module scope', () => {+ const page = document.createElement('div')+ page.innerHTML = '<button id="save">Save</button>'+ document.body.replaceChildren(page)++ const injected = new Function('return (' + actInPage.toString() + ')')() as typeof actInPage+ const holder: PreviewActHolder = {}++ expect(injected(document, holder, { kind: 'elements' }).elements?.[0].label).toBe('Save')++ const clicked = vi.fn()+ document.getElementById('save')!.addEventListener('click', clicked)++ expect(injected(document, holder, { kind: 'click', ref: '@e1' }).success).toBe(true)+ expect(clicked).toHaveBeenCalledOnce()+ })})describe('elements', () => {@@ -73,6 +103,82 @@ describe('elements', () => {expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Real'])})+ // The screen-reader-only recipe is a 1px box parked at the document origin,+ // and it passed a `width >= 1` check. Skip links and CSS-only menu toggles are+ // built this way and come FIRST in the document, so they landed on @e1 — the+ // agent would aim at one and the pointer would fly to the top-left corner and+ // click nothing.+ it('skips the visually-hidden controls that sit at the document origin', () => {+ const holder = page(`+ <a href="#content" style="width: 1px; height: 1px; clip: rect(0, 0, 0, 0)">Jump to content</a>+ <input aria-label="Toggle sidebar" style="width: 1px; height: 1px" type="checkbox" />+ <a href="#main" style="clip-path: inset(50%)">Skip navigation</a>+ <button id="real">Search</button>+ `)++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Search'])+ })++ it('skips a control parked off the left edge, which no scroll brings back', () => {+ const holder = page(`+ <button style="position: absolute; left: -9999px">Hidden</button>+ <button id="real">Search</button>+ `)++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Search'])+ })++ // Wikipedia and friends are full of these: decorative chrome and collapsed+ // menus that are perfectly solid boxes as far as layout is concerned, but+ // that the page has already declared are not for anyone to interact with.+ it('skips controls the page marked aria-hidden or inert', () => {+ const holder = page(`+ <div aria-hidden="true"><button>Decoration</button></div>+ <div inert><button>Collapsed menu</button></div>+ <button id="real">Search</button>+ `)++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Search'])+ })++ it('skips a control buried under another layer, which would take the click instead', () => {+ const holder = page(`+ <button style="left: 100px">Accept cookies</button>+ <button id="real" style="left: 300px">Search</button>+ `)+ const wall = document.createElement('div')+ document.body.append(wall)++ // Stand in for the hit-testing jsdom does not do: every element reports+ // itself except the buried one, which reports the sheet lying over it.+ document.elementFromPoint = (x: number) => (x === 120 ? wall : document.getElementById('real'))++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Search'])+ })++ it('keeps a control whose own child is what the hit test lands on', () => {+ const holder = page('<a href="/home" id="real"><svg id="icon"></svg> Home</a>')++ document.elementFromPoint = () => document.getElementById('icon')++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Home'])+ })++ // The overlay draws far more than the agent is told about, so the two lists+ // are collected separately: the field is every visible control, the inventory+ // is the describable subset that refs point into.+ it('parks the whole interactive field for the overlay, not just the inventory', () => {+ const holder = page(`+ <button id="named">Search</button>+ <button id="mystery"></button>+ <button id="gone" style="display: none">Gone</button>+ `)++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Search'])+ expect(holder.nodes).toEqual([document.getElementById('named')])+ expect(holder.field).toEqual([document.getElementById('named'), document.getElementById('mystery')])+ })+it('prefers an identity selector so the agent can re-find the node later', () => {const holder = page(`<div><button data-testid="submit">Send</button></div>@@ -288,7 +394,23 @@ describe('scroll', () => {const result = actInPage(document, holder, { kind: 'scroll' })expect(result.success).toBe(true)- expect(scrollBy).toHaveBeenCalledWith({ behavior: 'auto', top: Math.round(window.innerHeight * 0.9) })+ expect(scrollBy).toHaveBeenCalledWith({ behavior: 'smooth', top: Math.round(window.innerHeight * 0.9) })+ })++ it('drops the animation for a reader who asked for reduced motion', () => {+ const holder = page('<p>long page</p>')+ const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => {})++ // Passing 'smooth' explicitly overrides the OS preference, so the engine has+ // to opt back out itself rather than leaving it to the browser.+ vi.stubGlobal('matchMedia', () => ({ matches: true }))++ actInPage(document, holder, { kind: 'scroll' })+ vi.unstubAllGlobals()++ const [options] = scrollBy.mock.calls[0] as unknown as [ScrollToOptions]++ expect(options.behavior).toBe('auto')})it('jumps to the bottom', () => {@@ -312,7 +434,7 @@ describe('scroll', () => {const result = actInPage(document, holder, { amount: 200, kind: 'scroll', ref: '@e1' })- expect(list.scrollBy).toHaveBeenCalledWith({ behavior: 'auto', top: 200 })+ expect(list.scrollBy).toHaveBeenCalledWith({ behavior: 'smooth', top: 200 })expect(pageScroll).not.toHaveBeenCalled()expect(result.acted).toContain('Results')})diff --git a/apps/desktop/src/lib/preview-act/act-in-page.ts b/apps/desktop/src/lib/preview-act/act-in-page.tsindex f664f582993..0d78fccf2ae 100644--- a/apps/desktop/src/lib/preview-act/act-in-page.ts+++ b/apps/desktop/src/lib/preview-act/act-in-page.ts@@ -35,7 +35,24 @@ export interface PreviewActAction {/** scroll distance in px. Defaults to ~90% of the viewport height. */amount?: numberkey?: string- kind: 'click' | 'elements' | 'press' | 'scroll' | 'type'+ /** `pin`/`unpin`/`hold` never reach the engine — they resolve their targets+ * through `locate`/`elements` and then talk to the overlay — but they arrive+ * on the same wire. */+ kind:+ | 'click'+ | 'elements'+ | 'hold'+ | 'hover'+ | 'locate'+ | 'pin'+ | 'press'+ | 'scroll'+ | 'strobe'+ | 'type'+ | 'unpin'+ /** locate: also give the target keyboard focus, for a key press that must not+ * be preceded by a click (which would activate the control instead). */+ focus?: boolean/** Cap on the returned inventory. */max?: numberref?: string@@ -52,8 +69,12 @@ export interface PreviewActResult {elements?: PreviewElement[]error?: stringnote?: string+ /** Viewport centre of a located target, for aiming real pointer input at it. */+ point?: { x: number; y: number }success: booleantitle?: string+ /** locate: whether the target actually takes typed text. */+ typable?: boolean/** Live document URL after the action — a change means it navigated. */url?: string}@@ -61,18 +82,34 @@ export interface PreviewActResult {/** Where the surface keeps the last snapshot between actions (a window global* in the preview page), so '@e5' still means something on the next call. */export interface PreviewActHolder {+ /** Target of the action in flight, for the watch overlay to draw onto. */+ aimed?: Element | null+ /** The on-screen subset, for the overlay to outline. Diverges from `nodes` in+ * both directions: it drops what is below the fold, and it is not capped at+ * the inventory's size. */+ field?: Element[]nodes?: Element[]/** URL the snapshot was taken on; a navigation invalidates every ref. */url?: string}-const ACT_MAX_ELEMENTS = 120-/** Run one action against `doc`, resolving refs through `holder`. Self-contained. */export function actInPage(doc: Document, holder: PreviewActHolder, action: PreviewActAction): PreviewActResult {+ // Declared inside, not at module scope: this body is stringified and eval'd+ // in the guest page, where a module-level constant is simply not defined.+ const maxElements = 120+ // How many nodes the OVERLAY may draw, as opposed to how many the agent gets+ // told about. Far higher, because an extra mark costs one rect read where an+ // extra inventory row costs tokens on every single call.+ const maxMarks = 600const win = doc.defaultViewconst here = doc.location ? doc.location.href : ''+ // Passing 'smooth' explicitly OVERRIDES the user's OS-level reduce-motion+ // setting, so ask before animating over someone who opted out.+ const still = !!(win && win.matchMedia && win.matchMedia('(prefers-reduced-motion: reduce)').matches)+ const glide: ScrollBehavior = still ? 'auto' : 'smooth'+const cssEscape = (value: string) =>typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&')@@ -137,17 +174,118 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previreturn path.join(' > ')}- const visible = (el: Element): boolean => {+ /** On screen right now, and worth drawing a box around. The field is strictly+ * viewport-bound: a mark past the fold is one nobody can see, it spends the+ * budget that should have gone to what IS on screen, and the ones parked far+ * off to the side were landing as stray labels in the corner. */+ const onScreen = (el: Element): boolean => {+ if (!win) {+ return false+ }++ const box = el.getBoundingClientRect()++ if (box.right <= 0 || box.bottom <= 0 || box.left >= win.innerWidth || box.top >= win.innerHeight) {+ return false+ }++ // Page-sized wrappers. Outlining one draws a rectangle around the whole+ // screen, which says nothing and frames everything inside it as if it+ // mattered. Full-width banners are fine — it takes both dimensions.+ return !(box.width >= win.innerWidth * 0.95 && box.height >= win.innerHeight * 0.9)+ }++ /** Painted at all, ancestors included. */+ const shown = (el: Element): boolean => {+ // Folds in display/visibility/opacity/content-visibility inherited from an+ // ANCESTOR, which this element's own computed style does not report: inside+ // a parent at opacity 0, every child still reads back opacity 1.+ const seen = (el as Element & { checkVisibility?: (opts: object) => boolean }).checkVisibility++ if (typeof seen === 'function' && !seen.call(el, { checkOpacity: true, checkVisibilityCSS: true })) {+ return false+ }+const style = win && win.getComputedStyle ? win.getComputedStyle(el) : null- if (style && (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')) {+ if (style) {+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {+ return false+ }++ // The screen-reader-only recipe, both spellings: the deprecated `clip` and+ // the modern `clip-path: inset(50%)`. Neither exists for any purpose other+ // than hiding something visually while keeping it focusable.+ if ((style.clip && style.clip !== 'auto') || (style.clipPath || '').indexOf('inset(50%') !== -1) {+ return false+ }+ }++ return true+ }++ const visible = (el: Element): boolean => {+ if (!shown(el)) {+ return false+ }++ // Things the page itself declares are not for interacting with, neither of+ // which shows up in a computed style or a bounding box: an aria-hidden+ // subtree is invisible to every other assistive client, and `inert` cannot+ // be clicked at all. Disabled controls are deliberately NOT filtered here —+ // they stay in the inventory so the agent is told a button is disabled+ // rather than hunting for one that appears not to exist.+ if (el.closest('[aria-hidden="true"], [inert]')) {return false}const rect = el.getBoundingClientRect()- // Off-screen is fine (we scroll to it); collapsed to nothing is not.- return rect.width >= 1 && rect.height >= 1+ // Below the fold is fine — we scroll to it. Off to the LEFT or ABOVE is the+ // other half of the sr-only trick (`left: -9999px`, `top: -9999px`) and+ // scrolling never brings those back.+ if (rect.right <= 0 || rect.bottom <= 0) {+ return false+ }++ // Bigger than the 1px box sr-only collapses to. Nothing a person can aim at+ // is 2px across, and admitting those is what put the cursor in the corner:+ // they cluster at the document origin, so they sort to the FRONT of the+ // inventory and the agent reaches for one as @e1.+ if (rect.width < 3 || rect.height < 3) {+ return false+ }++ // Occlusion, and the last filter for a reason: everything above is cheap+ // and this one forces layout. If the middle of the element is on screen,+ // whatever the browser reports at that point has to BE this element — its+ // own descendant (an icon inside a link) or the box it paints inside are+ // fine, anything else means it is buried under a sticky header, a cookie+ // wall, or a transparent layer the page put on top. Those are exactly the+ // targets the agent aims at and then misses. Elements below the fold cannot+ // be hit-tested from here, so they are taken on trust and land back in this+ // function after the scroll.+ const midX = rect.left + rect.width / 2+ const midY = rect.top + rect.height / 2+ const under = (doc as Document & { elementFromPoint?: (x: number, y: number) => Element | null })+ .elementFromPoint++ if (+ typeof under === 'function' &&+ win &&+ midX >= 0 &&+ midY >= 0 &&+ midX < win.innerWidth &&+ midY < win.innerHeight+ ) {+ const over = under.call(doc, midX, midY)++ if (!over || !(over === el || el.contains(over) || over.contains(el))) {+ return false+ }+ }++ return true}const valueOf = (el: Element): string => {@@ -166,6 +304,7 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previconst collect = (max: number): PreviewElement[] => {const nodes: Element[] = []+ const field: Element[] = []const elements: PreviewElement[] = []const candidates = doc.querySelectorAll(@@ -177,7 +316,22 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previ)for (const el of candidates) {- if (elements.length >= max || nodes.indexOf(el) !== -1 || !visible(el)) {+ if (elements.length >= max && field.length >= maxMarks) {+ break+ }++ if (!visible(el)) {+ continue+ }++ // Drawable from here on. The two lists diverge deliberately: the field is+ // what is on screen to be outlined, the inventory is what the agent can+ // name and reach — which includes things below the fold it will scroll to.+ if (field.length < maxMarks && onScreen(el)) {+ field.push(el)+ }++ if (elements.length >= max) {continue}@@ -212,6 +366,7 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previ}holder.nodes = nodes+ holder.field = fieldholder.url = herereturn elements@@ -279,7 +434,7 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previ}if (action.kind === 'elements') {- const elements = collect(Math.max(1, Math.min(action.max || ACT_MAX_ELEMENTS, ACT_MAX_ELEMENTS)))+ const elements = collect(Math.max(1, Math.min(action.max || maxElements, maxElements)))return answer({elements,@@ -300,9 +455,9 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previconst by = action.to === 'top' ? -1e7 : action.to === 'bottom' ? 1e7 : (action.amount ?? page)if (scroller) {- scroller.scrollBy({ behavior: 'auto', top: by })+ scroller.scrollBy({ behavior: glide, top: by })} else if (win) {- win.scrollBy({ behavior: 'auto', top: by })+ win.scrollBy({ behavior: glide, top: by })}return answer({ acted: scroller ? 'scrolled ' + describe(scroller) : 'scrolled the page', success: true })@@ -316,12 +471,63 @@ export function actInPage(doc: Document, holder: PreviewActHolder, action: Previconst el = target.el as HTMLElement- if ((el as HTMLInputElement).disabled) {- return fail(describe(el) + ' is disabled.')+ // Park the target where the watch overlay can find it, before anything can+ // fail — a ring around the thing that turned out to be disabled is exactly+ // the feedback someone watching wants.+ holder.aimed = el++ // 'locate' is the look-before-you-act half of an action: it brings the target+ // on screen and names it, so the overlay has something to draw while the real+ // verb is still a beat away.+ if (action.kind === 'locate') {+ if (el.scrollIntoView) {+ el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'nearest' })+ }++ if (action.focus) {+ el.focus()+ }++ const spot = pointAt(el)+ const tag = el.tagName++ return answer({+ acted: 'looking at ' + describe(el),+ point: { x: spot.clientX, y: spot.clientY },+ success: true,+ // Real typing starts with a triple-click to clear the field. On anything+ // that is not a field that gesture selects the paragraph under it+ // instead, which is how the agent ended up highlighting whole pages.+ typable: tag === 'TEXTAREA' || tag === 'INPUT' || el.isContentEditable === true+ })}+ // Instant, unlike the `scroll` verb above. Getting a target on screen is+ // plumbing for the click that follows, not something anyone asked to watch —+ // and every millisecond of it is time the caller spends waiting for the page+ // to stop moving before it can aim real input at a fixed coordinate.if (el.scrollIntoView) {- el.scrollIntoView({ block: 'center', inline: 'nearest' })+ el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'nearest' })+ }++ // Hovering a disabled control is allowed — a disabled button with a tooltip+ // explaining WHY is exactly the thing worth hovering.+ if (action.kind === 'hover') {+ const init = { bubbles: true, cancelable: true, ...pointAt(el) }++ if (typeof PointerEvent === 'function') {+ el.dispatchEvent(new PointerEvent('pointerover', init))+ el.dispatchEvent(new PointerEvent('pointermove', init))+ }++ el.dispatchEvent(new MouseEvent('mouseover', init))+ el.dispatchEvent(new MouseEvent('mousemove', init))++ return answer({ acted: 'hovered over ' + describe(el), success: true })+ }++ if ((el as HTMLInputElement).disabled) {+ return fail(describe(el) + ' is disabled.')}if (action.kind === 'click') {diff --git a/apps/desktop/src/lib/preview-act/watch-in-page.test.ts b/apps/desktop/src/lib/preview-act/watch-in-page.test.tsnew file mode 100644index 00000000000..b51c62b7f07--- /dev/null+++ b/apps/desktop/src/lib/preview-act/watch-in-page.test.ts@@ -0,0 +1,363 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { type WatchHolder, watchInPage } from './watch-in-page'++/** jsdom has no layout engine, so every rect is zero and nothing would be+ * positioned. Give elements a plausible box the way the act-engine tests do. */+beforeEach(() => {+ // Never run the callback: the tracking loop re-arms itself every frame, so a+ // stub that invokes synchronously recurses until the stack gives out. The+ // first pass happens on the direct call, which is the one worth asserting on.+ vi.stubGlobal('requestAnimationFrame', () => 1)+ vi.stubGlobal('cancelAnimationFrame', () => {})++ Element.prototype.getBoundingClientRect = function () {+ return { bottom: 140, height: 40, left: 100, right: 300, toJSON: () => ({}), top: 100, width: 200, x: 100, y: 100 }+ }++ document.body.replaceChildren()+ // The host hangs off documentElement, so clearing body does not reach it.+ document.querySelector('hermes-watch')?.remove()+ delete (window as unknown as Record<string, unknown>).__hermesWatch+})++/** The overlay lives in a closed shadow root, so a test can only see the host. */+const host = () => document.querySelector('hermes-watch')++/** …except through the parts the engine parks on the window for its own reuse,+ * which is the only way to inspect what the overlay actually drew. */+const drawn = () =>+ (window as unknown as { __hermesWatch: { parts: Record<string, HTMLElement> & { shadow: ShadowRoot } } })+ .__hermesWatch.parts++/** Everything the overlay drew for this action. The cursor is the only fixed+ * layer — every box and pin is a mark that comes and goes. */+const marks = () => [...drawn().shadow.children].filter(child => child !== drawn().pointer)++describe('watchInPage', () => {+ it('mounts one host on documentElement and reuses it across stages', () => {+ const target = document.createElement('button')+ document.body.append(target)++ const holder: WatchHolder = { aimed: target }++ watchInPage(document, holder, 'aim')+ watchInPage(document, holder, 'strike')++ expect(document.querySelectorAll('hermes-watch')).toHaveLength(1)+ expect(host()?.parentElement).toBe(document.documentElement)+ })++ it('stays out of the page, out of the way, and out of the a11y tree', () => {+ const target = document.createElement('button')+ document.body.append(target)++ watchInPage(document, { aimed: target }, 'aim')++ const node = host() as HTMLElement++ // pointer-events keeps real clicks reaching the page; aria-hidden keeps a+ // screen reader from announcing decoration.+ expect(node.style.pointerEvents).toBe('none')+ expect(node.getAttribute('aria-hidden')).toBe('true')+ // The closed shadow root is what keeps the overlay out of the act engine's+ // own querySelectorAll inventory — there is nothing to exclude by hand.+ expect(node.shadowRoot).toBeNull()+ })++ it('does nothing when there is no target to draw on', () => {+ watchInPage(document, {}, 'aim')+ watchInPage(document, { aimed: document.createElement('div') }, 'strike')++ expect(host()).toBeNull()+ })++ // The cursor is placed, never interpolated. Beyond reading as a machine, a+ // transition here was an outright bug on the first paint: an unset transform+ // IS the origin, so the browser flew the cursor in from the top-left corner —+ // and every navigation is a fresh document, so a fresh first paint.+ it('cuts the marks straight to the target instead of travelling to it', () => {+ const target = document.createElement('button')+ document.body.append(target)++ watchInPage(document, { aimed: target }, 'aim', 'Clicking Save')++ const { pointer } = drawn()++ expect(pointer.style.transition).toBeFalsy()+ expect((marks()[0] as HTMLElement).style.transition).toBeFalsy()+ // Mocked rect is 200×40 at (100, 100), so the cursor belongs at its centre.+ expect(pointer.style.transform).toBe('translate3d(200px,120px,0)')+ })++ // The inventory pass is the one moment the agent is reading the whole page+ // rather than aiming at one thing, so the overlay has to be able to hold many+ // marks at once — not just the single ring every other stage draws.+ it('sweep lights up every catalogued element and holds them well past the sweep', () => {+ vi.useFakeTimers()++ const found = [document.createElement('button'), document.createElement('a'), document.createElement('input')]+ document.body.append(...found)++ watchInPage(document, { nodes: found }, 'sweep')+ expect(marks()).toHaveLength(found.length)++ // The point of the dwell: the grid is still up long after the pass that drew+ // it finished, so there is something to actually look at. jsdom has no Web+ // Animations, so this exercises the timed fallback, which holds for the same+ // beat as the animated path.+ vi.advanceTimersByTime(600)+ expect(marks()).toHaveLength(found.length)++ // …and then drains scattered rather than blinking off as one block, which is+ // the whole reason each box carries its own offset. Stepping through the+ // exit must therefore see the count come down in more than one tick.+ const drain = new Set<number>()++ for (let t = 0; t < 7_000; t += 100) {+ vi.advanceTimersByTime(100)+ drain.add(marks().length)+ }++ expect(drain.size).toBeGreaterThan(2)+ expect(marks()).toHaveLength(0)++ vi.useRealTimers()+ })++ // jsdom cannot run a Web Animation, but it can be handed one and asked what+ // it was given — and this particular option is worth pinning, because getting+ // it wrong is invisible rather than broken. `easing` in the options bag is the+ // ITERATION easing: it rewrites progress before any keyframe is consulted, so+ // a step function there holds progress at 0 for the whole duration. Every box+ // was created, animated and removed without painting a single frame.+ it('does not step the sweep’s iteration easing, which would stop it painting', () => {+ const timings: KeyframeAnimationOptions[] = []++ Element.prototype.animate = vi.fn(function (this: Element, _frames, options) {+ timings.push(options as KeyframeAnimationOptions)++ return { cancel: () => {}, finish: () => {} } as unknown as Animation+ }) as unknown as Element['animate']++ const found = [document.createElement('button'), document.createElement('a')]+ document.body.append(...found)++ watchInPage(document, { field: found }, 'sweep')++ // The cursor's idle sway is permanent and starts with the overlay, so it is+ // not one of the sweep's own animations.+ const sweep = timings.filter(timing => timing.iterations !== Infinity)++ expect(sweep).toHaveLength(found.length)++ for (const timing of sweep) {+ expect(String(timing.easing)).not.toMatch(/steps/)+ }+ })++ it('names each swept box after the element under it, not its ref', () => {+ const found = [document.createElement('button'), document.createElement('a'), document.createElement('input')]++ found[0].id = 'buy'+ found[1].className = 'nav wide'+ found[2].setAttribute('type', 'search')+ document.body.append(...found)++ // Every drawable box gets named, addressable or not — a ref number only ever+ // meant something for the subset that had one, and said nothing about what+ // the element actually is.+ watchInPage(document, { field: found, nodes: found.slice(0, 2) }, 'sweep')++ const { shadow } = drawn()+ const cells = [...shadow.children].slice(-found.length)++ expect(cells.map(cell => cell.textContent)).toEqual(['button#buy', 'a.nav', 'input[search]'])+ })++ // The case that made positions necessary: a list of links with no id, no+ // class and no type. Naming them by tag alone gives a whole page of boxes all+ // reading "a", which is what the ref numbers were replaced for.+ it('falls back to position so anonymous siblings are still told apart', () => {+ const row = document.createElement('td')++ row.className = 'subtext'+ row.innerHTML = '<a></a><a></a><a></a>'+ document.body.append(row)++ const found = [...row.children]++ watchInPage(document, { field: found }, 'sweep')++ const { shadow } = drawn()+ const cells = [...shadow.children].slice(-found.length)++ expect(cells.map(cell => cell.textContent)).toEqual(['a[1]', 'a[2]', 'a[3]'])+ })++ it('keeps a name short enough to sit on the box it names', () => {+ const found = [document.createElement('div')]++ found[0].id = 'a-genuinely-enormous-generated-identifier'+ document.body.append(...found)++ watchInPage(document, { field: found }, 'sweep')++ const name = marks()[0].textContent as string++ expect(name.length).toBeLessThanOrEqual(16)+ expect(name.startsWith('div#a-')).toBe(true)+ expect(name.endsWith('…')).toBe(true)+ })++ // A field past a couple of dozen boxes is a texture, not a list. Naming every+ // one buries the outlines — which ARE the readout at that size — under a wall+ // of tags that collide with each other and overhang their own rectangles.+ it('stops naming the boxes once the field is too dense to read', () => {+ const few = Array.from({ length: 4 }, () => document.createElement('button'))+ document.body.append(...few)++ watchInPage(document, { field: few }, 'sweep')+ expect(marks().every(mark => mark.textContent)).toBe(true)++ document.querySelector('hermes-watch')?.remove()+ delete (window as unknown as Record<string, unknown>).__hermesWatch++ const many = Array.from({ length: 40 }, () => document.createElement('button'))+ document.body.append(...many)++ watchInPage(document, { field: many }, 'sweep')+ expect(marks().some(mark => mark.textContent)).toBe(false)+ })++ // Every other mark on the page wears its label on the top edge. A box against+ // the top of the viewport has nowhere to put one, and a tab drawn off-screen+ // is a box that looks unlabelled next to boxes that aren't.+ it('flips the label under the box when there is no headroom above it', () => {+ const roomy = document.createElement('button')+ const flush = document.createElement('button')+ const huge = document.createElement('button')++ flush.getBoundingClientRect = () =>+ ({ bottom: 40, height: 40, left: 100, right: 300, toJSON: () => ({}), top: 0, width: 200, x: 100, y: 0 }) as DOMRect+ // Taller than the viewport: no room above it and none below it either, so+ // the tab has nowhere left to go but inside.+ huge.getBoundingClientRect = () =>+ ({ bottom: 900, height: 900, left: 100, right: 300, toJSON: () => ({}), top: 0, width: 200, x: 100, y: 0 }) as DOMRect+ document.body.append(roomy, flush, huge)++ watchInPage(document, { field: [roomy, flush, huge] }, 'sweep')++ const tags = marks().map(mark => mark.querySelector('div:last-child') as HTMLElement)++ expect(tags[0].style.bottom).toBe('100%')+ expect(tags[1].style.top).toBe('100%')+ expect(tags[2].style.top).toBe('0px')+ })++ // A label is routinely wider than the box it names, so it is the boxes near the+ // right edge that push their tab off screen. Whichever end it lands on, the+ // tab's edge sits exactly on the outline's — the two are the same colour and+ // meet at a corner, so a pixel of overhang reads as a misprint.+ it('hangs the label off the right edge when a left-anchored one would run off', () => {+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { configurable: true, get: () => 80 })++ const inboard = document.createElement('button')+ const edge = document.createElement('button')++ edge.getBoundingClientRect = () =>+ ({ bottom: 140, height: 40, left: 990, right: 1020, toJSON: () => ({}), top: 100, width: 30, x: 990, y: 100 }) as DOMRect+ document.body.append(inboard, edge)++ watchInPage(document, { field: [inboard, edge] }, 'sweep')++ const tags = marks().map(mark => mark.querySelector('div:last-child') as HTMLElement)++ expect(tags[0].style.left).toBe('0px')+ expect(tags[0].style.right).toBe('')+ expect(tags[1].style.right).toBe('0px')+ expect(tags[1].style.left).toBe('')+ })++ it('sweep draws nothing when the inventory came back empty', () => {+ watchInPage(document, { nodes: [] }, 'sweep')++ expect(host()).toBeNull()+ })++ // The field is swept after every action, and a sweep retires the lock. The+ // cursor must not go with it — a hand that blinks out a fraction of a second+ // after every single step reads as the agent having wandered off.+ it('keeps the cursor up when a sweep retires the lock', () => {+ const target = document.createElement('button')+ const found = [document.createElement('a')]+ document.body.append(target, ...found)++ watchInPage(document, { aimed: target }, 'aim')++ const { pointer } = drawn()+ const lock = marks()[0]++ expect(pointer.style.opacity).toBe('1')++ watchInPage(document, { field: found }, 'sweep')++ expect(lock.isConnected).toBe(false)+ expect(pointer.style.opacity).toBe('1')+ })++ // The chrome is memoized for the life of the page, so a style change to it+ // would otherwise be injected, run, and restyle nothing — the layers it+ // describes were built by the version before. Reads as "HMR isn't picking my+ // CSS up" in dev, and as a long-lived tab stuck on an old build in production.+ it('rebuilds its chrome when the injected source changes underneath it', () => {+ const target = document.createElement('button')+ document.body.append(target)++ const stamp = (value: number) => {+ ;(window as unknown as Record<string, unknown>).__hermesWatchTag = value+ }++ stamp(1)+ watchInPage(document, { aimed: target }, 'aim')++ const first = drawn().host++ stamp(1)+ watchInPage(document, { aimed: target }, 'aim')++ expect(drawn().host).toBe(first)++ stamp(2)+ watchInPage(document, { aimed: target }, 'aim')++ expect(drawn().host).not.toBe(first)+ // …and the old one goes with it, rather than stacking a second overlay.+ expect(document.querySelectorAll('hermes-watch')).toHaveLength(1)+ })++ it('clear releases the target so the tracking loop can stop', () => {+ const target = document.createElement('button')+ document.body.append(target)++ const holder: WatchHolder = { aimed: target }++ watchInPage(document, holder, 'aim')+ watchInPage(document, holder, 'clear')++ expect(holder.aimed).toBeNull()+ })++ // Same contract as the act engine: the pane injects `watchInPage.toString()`+ // into the guest page, where module scope does not exist. One free identifier+ // is a ReferenceError that Electron reports only as "Script failed to execute".+ it('runs after being stringified and eval’d with no module scope', () => {+ const target = document.createElement('button')+ document.body.append(target)++ const injected = new Function('return (' + watchInPage.toString() + ')')() as typeof watchInPage++ expect(() => injected(document, { aimed: target }, 'aim', 'Clicking Save')).not.toThrow()+ expect(host()).not.toBeNull()+ })+})diff --git a/apps/desktop/src/lib/preview-act/watch-in-page.ts b/apps/desktop/src/lib/preview-act/watch-in-page.tsnew file mode 100644index 00000000000..0395548d0db--- /dev/null+++ b/apps/desktop/src/lib/preview-act/watch-in-page.ts@@ -0,0 +1,1063 @@+/**+ * WATCH OVERLAY — paints the agent's actions onto the live preview page so a+ * person can follow along: the field of things it can reach, a box round the+ * one it is about to touch, and a cursor that goes there.+ *+ * There are exactly two things on screen, and everything the agent does is said+ * with one of them:+ *+ * - THE CURSOR — one arrow, built once, never removed. It is the+ * collaborative-editing kind, because that is exactly what this is: a second+ * party moving around a document you are also looking at. Arrow geometry is+ * Liveblocks' (Apache-2.0). Plain black or white against the guest's own+ * colour scheme rather than a brand colour: it stands for a hand, and a hand+ * is not a feature of this app.+ * - THE MARK — a rectangle glued to an element. A candidate, a lock, a hit+ * and a pin are all the same object with a different row in `kinds`: how+ * heavy the rule is, how long it lives, how it arrives. Marks are a design+ * tool's selection blue, deliberately NOT the+ * app's accent — this is chrome drawn on top of someone else's page, and+ * every design tool has trained people to read that blue as "a tool has+ * selected this", where a branded colour would read as part of the page.+ *+ * Every mark is two elements: a shell the tracker positions, and a skin that+ * carries the border and any animation. They are split because both want+ * `transform`, and a mark that animates the property the tracker rewrites every+ * frame either stops moving or stops animating.+ *+ * Injected as source (`watchInPage.toString()`) exactly like the act engine, so+ * the same rule holds: no imports, no closure references, no module-scope+ * constants — everything the body needs is declared inside it.+ *+ * Three constraints shape the implementation, each one learned from how+ * Playwright, Stagehand and browser-use solve the same problem:+ *+ * - A page can set `z-index: 2147483647` too, and the browser's top layer+ * (`<dialog>`, `popover`, fullscreen) outranks every z-index there is. So+ * the host joins the top layer via `popover="manual"` instead of trying to+ * outbid the page, and keeps the z-index only as a fallback.+ * - A strict CSP rejects `style-src` at CSS PARSE time, which kills+ * `cssText`, `setAttribute('style', …)` and any `<style>` we inject — but+ * never `style.setProperty()` or `element.animate()`. So every style here+ * is set per-property, and everything that moves is a Web Animation.+ * - The overlay must stay out of the agent's own element inventory. It lives+ * in a closed shadow root, which `document.querySelectorAll` does not+ * descend into, so `collect()` cannot reach it — no exclusion list to keep+ * in sync, and page scripts can't reach in either.+ */++/** Where the overlay reads its target from — the act engine's holder. */+export interface WatchHolder {+ /** The element the agent is currently working on, parked by `locate`. */+ aimed?: Element | null+ /** Every handle the agent holds on this page, so a mark can be labelled with+ * the name the agent actually calls that element by. */+ book?: { el: Element; ref: string }[]+ /** What is on screen right now, for the field to outline. */+ field?: Element[]+ /** The addressable subset, in document order. */+ nodes?: Element[]+}++/**+ * - `aim` — box the target and send the cursor to it (the agent is looking).+ * - `strike` — mark the target (the agent just acted).+ * - `sweep` — outline and name the whole field, scattered.+ * - `strobe` — rattle through the field one box at a time, out of order.+ * - `read` — wipe down the page's text, in the order a person would read it.+ * - `think` / `rest` — start and stop the idle pulse between actions.+ * - `clear` — pack the transients away. Pins survive it.+ * - `pin` / `unpin` — put up a mark that outlives the action, or take it down.+ * - `hold` — promote the whole field to pins, so the scan stops decaying.+ */+export type WatchStage =+ | 'aim'+ | 'clear'+ | 'hold'+ | 'pin'+ | 'read'+ | 'rest'+ | 'strike'+ | 'strobe'+ | 'sweep'+ | 'think'+ | 'unpin'++/** What a mark means. Everything else about it is shared. */+type WatchKind = 'candidate' | 'flash' | 'held' | 'hit' | 'lock'++interface WatchSpec {+ /** The element the mark is glued to, re-measured every frame. */+ a: Element+ /** Stagger, in ms, applied to both ends of its life. */+ beat?: number+ kind: WatchKind+ label?: string+ /** Overrides the kind's hold time, for marks that want an uneven rhythm. */+ life?: number+}++/** A spec plus whatever is on screen for it. The elements are optional because+ * a pin outlives the shadow tree it was drawn into and gets redrawn. */+interface WatchMark {+ cell?: HTMLElement+ skin?: HTMLElement+ /** Which corner the label is hanging off, so it is only re-styled on a flip. */+ slot?: string+ spec: WatchSpec+ tag?: HTMLElement+ /** The label's measured width, kept so the fit pass doesn't force a layout. */+ wide?: number+}++/** An element's rectangle in viewport coordinates. */+interface WatchSpot {+ height: number+ left: number+ top: number+ width: number+}++/** Draw one stage of the agent's action. `label` is only read by `pin`.+ * Self-contained. */+export function watchInPage(doc: Document, holder: WatchHolder, stage: WatchStage, label?: string): void {+ const win = doc.defaultView as (Window & { __hermesWatch?: Record<string, unknown> }) | null++ if (!win || !doc.documentElement) {+ return+ }++ // Process magenta. A selection blue is what every design tool uses, which is+ // the problem: half the pages this gets drawn over are already blue, and the+ // marks sink into them. Magenta is the one hue almost nothing on the web is,+ // so the chrome reads as chrome. Not #FF00FF — pure magenta is too light to+ // carry the white label text. One colour, deliberately: a hue per element was+ // tried and a page of marks in eight colours is unreadable — the outlines stop+ // reading as one tool's chrome and start competing with the content.+ const line = '#EC008C'+ // Field outlines are the hairline; whatever is actually locked gets the+ // heavier one, so the target is legible in a screen full of candidates.+ const weight = '1.5px'+ const heavy = '2px'+ const pad = 4+ // The label's side padding. The tab itself sits flush with the outline — the+ // two are the same colour and meet at a corner, so any offset between their+ // edges reads as a misprint. That puts the glyphs just inside the stroke,+ // which is where the box's own content starts anyway.+ const nudge = 2+ // How long a mark stays up. Far longer than the action that made it: the+ // input is instant on purpose, and a cue that lasts as long as the input is+ // one nobody can read. Marks hold at full strength and then cut.+ const dwell = 6_000+ // The window the field's arrivals and departures are spread across.+ const cascade = 900+ // The lock is the long one — a whole action happens underneath it.+ const hold = 7_500+ // The strobe. Every number here is a floor with a random span on top, because+ // an even interval is the one thing that stops this reading as a machine+ // chewing through a page — a fixed tempo is a progress bar. Hits come in+ // clumps of one to three, most gaps are inside a tenth of a second, and every+ // so often it stalls for a quarter of one, which is the beat that sells it.+ const blink = 90+ const flick = 200+ const tempo = 26+ const gasp = 210+ const burst = 5_000+ // The read. A beam down the page and a short hold under each block: reading+ // is the one thing the agent does to a page in an order a person could+ // follow, so it is the one stage that is allowed to be a wipe. Holding the+ // blocks the way a sweep holds its field would bury the text under the very+ // outlines that are supposed to be pointing at it.+ const wipe = 1_800+ const glance = 1_400+ // A ceiling on how many blocks one pass schedules. Past this the beam is+ // solid anyway and the only thing another hundred animations buys is jank.+ const page = 160+ // The idle pulse, which runs while the model is reasoning between actions.+ // Far sparser than the strobe: this is the page being held in mind, not read.+ // Most ticks fire nothing, which is what keeps it from reading as a spinner.+ const throb = 260+ const ponder = 240+ const quiet = 0.55++ // Big animated overlays are a vestibular hazard. Honour the user's setting by+ // keeping the marks and dropping the motion, rather than showing nothing.+ const still = !!(win.matchMedia && win.matchMedia('(prefers-reduced-motion: reduce)').matches)+ // The arrow reads against the PAGE, so it follows the guest's scheme, not the+ // app's: white on a dark page, black on a light one.+ const dark = !!(win.matchMedia && win.matchMedia('(prefers-color-scheme: dark)').matches)+ const ink = dark ? '#FFFFFF' : '#111111'+ // A grotesque, not the app's mono. Mono was the wrong instinct at label size:+ // its glyphs are uniformly wide, so the same string takes about a third more+ // box, and a field of tags that each overhang their own rectangle is most of+ // what makes a dense page unreadable. Installed OS faces only — the guest page+ // is a different document and never loads our @font-face, so naming a bundled+ // family here would just be a step the browser skips.+ const face = "-apple-system, 'Helvetica Neue', Arial, sans-serif"+ // Past this many boxes a field is a texture, not a list, and naming every one+ // of them buries the outlines under a wall of colliding tags. The outlines are+ // the readout at that size; the names are noise.+ const busy = 25+ const state = win.__hermesWatch || (win.__hermesWatch = {})++ // One row per kind of mark. `life` is how long it stays up; 0 means it stays+ // until the agent takes it down, which is the whole difference between a mark+ // that narrates an action and one that records a finding.+ const kinds = {+ candidate: { gap: 0, life: dwell, rule: weight },+ flash: { gap: pad, life: blink, rule: heavy },+ held: { gap: pad, life: 0, rule: heavy },+ hit: { gap: 0, life: dwell, rule: heavy },+ lock: { gap: pad, life: hold, rule: heavy }+ }++ const style = (el: Element, props: Record<string, string>) => {+ for (const name in props) {+ ;(el as HTMLElement).style.setProperty(name, props[name])+ }+ }++ // ── NAMING ────────────────────────────────────────────────────────────────++ /** Name one node: the most specific thing about it that fits in a few+ * characters. Position is the last resort but it is the one that saves the+ * label — a page of anonymous links is a page of boxes all reading "a". */+ const step = (node: Element) => {+ const tag = node.tagName.toLowerCase()+ const id = node.getAttribute('id')+ const cls = (node.getAttribute('class') || '').trim().split(/\s+/)[0]+ const kind = node.getAttribute('type') || node.getAttribute('name') || node.getAttribute('role')++ if (id) {+ return tag + '#' + id+ }++ if (cls) {+ return tag + '.' + cls+ }++ if (kind) {+ return tag + '[' + kind + ']'+ }++ const parent = node.parentElement++ if (!parent) {+ return tag+ }++ let kin = 0+ let mine = 0++ for (let i = 0; i < parent.children.length; i++) {+ if (parent.children[i].tagName !== node.tagName) {+ continue+ }++ kin++++ if (parent.children[i] === node) {+ mine = kin+ }+ }++ return kin > 1 ? tag + '[' + mine + ']' : tag+ }++ /** A short name for the element.+ *+ * The agent's own handle wins whenever it has one, because then the label on+ * the box and the word in the transcript are the same string — someone+ * watching can read `btn-sign-in` on screen and find that exact line in what+ * the model said. Falling back to the tag is for everything the agent has no+ * handle for: the field the overlay outlines is far wider than the inventory+ * the agent is given.+ *+ * The fallback is the leaf only. An ancestor path was tried and it is worse+ * than nothing on a real page: three rungs of `span.titleline/a` cut to fit a+ * box gives `…T/SPAN.SUBLINE/A` — wider than the box it sits on, severed+ * mid-word, and identical to its neighbour's. */+ const sniff = (el: Element) => {+ const held = holder.book || []++ for (const bound of held) {+ if (bound.el === el) {+ return bound.ref+ }+ }++ const name = step(el)++ return name.length > 16 ? name.slice(0, 15) + '…' : name+ }++ // ── GEOMETRY ──────────────────────────────────────────────────────────────++ const spot = (el: Element): WatchSpot => {+ const box = el.getBoundingClientRect()++ return { height: box.height, left: box.left, top: box.top, width: box.width }+ }++ const middle = (box: WatchSpot) => ({ x: box.left + box.width / 2, y: box.top + box.height / 2 })++ // ── THE CURSOR ────────────────────────────────────────────────────────────++ const build = () => {+ // A host from an earlier build of this function may still be on the page.+ // Clear it out rather than stacking a second.+ const stale = doc.querySelectorAll('hermes-watch')++ for (let i = 0; i < stale.length; i++) {+ stale[i].remove()+ }++ const host = doc.createElement('hermes-watch')++ host.setAttribute('aria-hidden', 'true')+ host.setAttribute('popover', 'manual')++ // The popover UA sheet ships its own border/padding/background and sizes to+ // fit-content, so every one of those has to be flattened back out.+ style(host, {+ background: 'transparent',+ border: '0',+ contain: 'layout style paint',+ display: 'block',+ height: '100%',+ inset: '0',+ margin: '0',+ overflow: 'visible',+ padding: '0',+ 'pointer-events': 'none',+ position: 'fixed',+ 'user-select': 'none',+ width: '100%',+ 'z-index': '2147483647'+ })++ const shadow = host.attachShadow({ mode: 'closed' })+ const pointer = doc.createElement('div')++ // Inherited from the host, but stated outright here too: an overlay that+ // swallows the agent's own click is a very quiet failure.+ style(pointer, { left: '0', opacity: '0', 'pointer-events': 'none', position: 'fixed', top: '0' })++ // Re-mounting the host must not teleport the cursor back to the corner, so+ // the last spot is restored before it is ever shown.+ const was = state.at as { x: number; y: number } | undefined++ if (was) {+ style(pointer, { transform: 'translate3d(' + was.x + 'px,' + was.y + 'px,0)' })+ }++ const cursor = doc.createElementNS('http://www.w3.org/2000/svg', 'svg')++ cursor.setAttribute('viewBox', '0 0 24 36')+ cursor.setAttribute('width', '28')+ cursor.setAttribute('height', '42')+ // The arrow's tip is at (0.5, 1.2) in viewBox units, ~(0.6, 1.4)px at this+ // scale, so pull it back to put the POINT on the target.+ style(cursor, { display: 'block', left: '-1px', position: 'absolute', top: '-1px' })++ const nib = doc.createElementNS('http://www.w3.org/2000/svg', 'path')++ nib.setAttribute(+ 'd',+ 'M5.65376 12.3673H5.46026L5.31717 12.4976L0.500002 16.8829L0.500002 1.19841L11.7841 12.3673H5.65376Z'+ )+ cursor.appendChild(nib)+ pointer.appendChild(cursor)+ shadow.appendChild(pointer)+ doc.documentElement.appendChild(host)++ // Idle drift. A cursor parked at exactly the same pixel for thirty seconds+ // reads as a screenshot; a couple of pixels of wander reads as something+ // waiting its turn. It rides the SVG rather than the wrapper because the+ // wrapper's transform is rewritten every frame by the tracking loop.+ if (!still && typeof cursor.animate === 'function') {+ cursor.animate(+ [+ { transform: 'translate(0px, 0px)' },+ { transform: 'translate(1.5px, -2px)' },+ { transform: 'translate(-1px, 1.5px)' },+ { transform: 'translate(0px, 0px)' }+ ],+ { duration: 5_200, easing: 'ease-in-out', iterations: Infinity }+ )+ }++ return { cursor, host, nib, pointer, shadow }+ }++ /** Put the hand somewhere and remember where that was. The cursor is never+ * interpolated: beyond reading as a machine, a transition here was an outright+ * bug on the first paint — an unset transform IS the origin, so the browser+ * flew the cursor in from the top-left corner of every fresh document. */+ const park = (at: { x: number; y: number }) => {+ const shown = state.parts as ReturnType<typeof build> | undefined++ state.at = at++ if (shown) {+ style(shown.pointer, { transform: 'translate3d(' + at.x + 'px,' + at.y + 'px,0)' })+ }+ }++ // ── THE MARK ──────────────────────────────────────────────────────────────++ const marks = (state.marks || (state.marks = [])) as WatchMark[]++ /** The overlay has one kind of label, so a pinned box and a swept box read the+ * same: a tab sitting on the box's top edge, exactly where a design tool puts+ * one. Filled, not coloured-glyph-on-whatever-is-under-it — these sit+ * directly on the page's own text, and an unbacked glyph there is illegible+ * against half the pages on the web, reading as a rendering fault rather than+ * a label. Solid, and the same colour as the outline it hangs off. */+ const caption = (text: string) => {+ const tag = doc.createElement('div')++ tag.textContent = text+ style(tag, {+ // Named outright, NOT `currentColor`. `currentColor` in a background+ // resolves against the element's own `color` — which is white here — so+ // the label came out white on white and vanished.+ background: line,+ color: '#FFFFFF',+ 'font-family': face,+ 'font-size': '8px',+ 'font-weight': '700',+ // Tracked OUT, not in. Tightening is for display sizes; at 8px, and in+ // caps especially — no ascenders or descenders to separate one letter from+ // the next — the glyphs need air or they read as a smear.+ 'letter-spacing': '0.04em',+ 'line-height': '1.4',+ // Capped in pixels, NOT at 100% of the box. A tab is allowed to be wider+ // than the thing it names — an icon button is 32px and would have had its+ // label clipped to three letters, which is worse than an overhang. The+ // ceiling is only here for a pin whose caption the agent wrote.+ 'max-width': '160px',+ overflow: 'hidden',+ padding: '0 ' + nudge + 'px',+ position: 'absolute',+ 'text-transform': 'uppercase',+ 'white-space': 'nowrap'+ })++ return tag+ }++ const paint = (spec: WatchSpec) => {+ const cell = doc.createElement('div')++ // The shell holds position and the colour, and nothing else. The tracker+ // rewrites its transform every frame, so anything that animates a transform+ // of its own has to be a layer inside it — and everything below inherits the+ // colour through `currentColor`, so a mark is tinted in exactly one place.+ style(cell, { color: line, left: '0', 'pointer-events': 'none', position: 'fixed', top: '0' })++ const skin = doc.createElement('div')++ style(skin, {+ border: kinds[spec.kind].rule + ' solid currentColor',+ inset: '0',+ overflow: 'hidden',+ position: 'absolute',+ 'transform-origin': 'center'+ })+ cell.appendChild(skin)++ // Only the lock is scanned. It is the one mark that stands for the agent+ // reading something rather than having already found it.+ if (spec.kind === 'lock') {+ const beam = doc.createElement('div')++ style(beam, {+ background: 'currentColor',+ height: heavy,+ left: '0',+ opacity: '0',+ position: 'absolute',+ right: '0',+ top: '0'+ })+ skin.appendChild(beam)+ }++ // On the shell rather than the skin, so a label neither scales with the+ // entrance nor gets clipped by the skin's own overflow.+ const tag = spec.label ? caption(spec.label) : undefined++ if (tag) {+ cell.appendChild(tag)+ }++ return { cell, skin, tag }+ }++ /** Re-measure a mark against the element it is glued to. Returns its centre,+ * so the one caller that cares where a mark ended up doesn't measure twice. */+ const fit = (mark: WatchMark) => {+ const cell = mark.cell as HTMLElement+ const from = spot(mark.spec.a)+ const gap = kinds[mark.spec.kind].gap++ style(cell, {+ height: from.height + gap * 2 + 'px',+ transform: 'translate3d(' + (from.left - gap) + 'px,' + (from.top - gap) + 'px,0)',+ width: from.width + gap * 2 + 'px'+ })++ // Which corner the tab hangs off. Decided here rather than at paint because+ // scrolling is what runs a box out of headroom, and re-styled only on the+ // frames where the answer actually changed.+ if (mark.tag) {+ // Above by default, below when the box is against the top of the viewport,+ // and inside its top edge only when it is pinned against both — which is a+ // box taller than the screen. Below beats inside because a tab laid over+ // the box covers the very thing it is naming.+ const tall = 13+ const row = from.top - gap >= tall ? 'up' : from.top + from.height + gap + tall <= win.innerHeight ? 'down' : 'in'+ // Measured once and kept: the text never changes after paint, and an+ // offsetWidth read is a forced layout, which is not something to do per+ // mark per frame.+ const wide = mark.wide || (mark.wide = mark.tag.offsetWidth)+ // Anchored to whichever end of the box keeps the tab on screen. A label is+ // routinely wider than the box it names, so a left-anchored one on+ // anything near the right edge is the case that runs off.+ const end = from.left - gap + wide > win.innerWidth ? 'end' : 'start'+ const slot = row + end++ if (mark.slot !== slot) {+ mark.slot = slot+ style(mark.tag, {+ bottom: row === 'up' ? '100%' : '',+ left: end === 'start' ? '0px' : '',+ right: end === 'end' ? '0px' : '',+ top: row === 'up' ? '' : row === 'down' ? '100%' : '0'+ })+ }+ }++ return middle(from)+ }++ /** How a mark arrives and when it leaves. Held marks do neither. */+ const enter = (mark: WatchMark) => {+ const spec = mark.spec+ const life = spec.life || kinds[spec.kind].life++ if (!life) {+ return+ }++ const cell = mark.cell as HTMLElement+ const skin = mark.skin as HTMLElement+ const beat = spec.beat || 0++ // Every transient leaves on a clock rather than on its animation, so the+ // reduced-motion path and the animated one retire in the same beat.+ win.setTimeout(() => cell.remove(), life + beat)++ // A mark comes and goes as ONE thing, so what fades is the CELL — which owns+ // the outline and the label both. Fading the skin instead left every tag+ // painted at full strength from the moment the mark was created: through its+ // whole delay, and past the box's exit. On a burst that is a hundred labels+ // up at once over five outlines, each one outliving the box it names.+ const blip = spec.kind === 'candidate' || spec.kind === 'flash'+ const mover = blip ? cell : skin++ if (still || typeof mover.animate !== 'function') {+ return+ }++ // Hard on, hard off. The cut comes from the OFFSETS — full strength is+ // reached in the first percent and held to the last — not from a step+ // easing. `easing` in the options bag is the ITERATION easing, applied to+ // progress before any keyframe is consulted, so `steps(1)` there pins+ // progress at 0 for the whole duration and the mark never paints at all.+ const frames = blip+ ? [+ { offset: 0, opacity: 0 },+ { offset: 0.01, opacity: 1 },+ { offset: 0.99, opacity: 1 },+ { offset: 1, opacity: 0 }+ ]+ : // A box snapping shut on a target, not a material-design tap. Scale is+ // the one thing that CAN'T move to the cell — the tracker rewrites the+ // cell's transform every frame — so it stays on the skin, where it only+ // has to not fight the opacity above.+ [+ { offset: 0, transform: spec.kind === 'hit' ? 'scale(1.35)' : 'scale(1.06)' },+ { offset: spec.kind === 'hit' ? 0.1 : 90 / life, transform: 'scale(1)' },+ { offset: 1, transform: 'scale(1)' }+ ]++ // `both`, not `forwards`. A delayed animation is in its BEFORE phase during+ // the delay, and `forwards` does not fill there — so every staggered box+ // rendered at its own natural opacity the instant it was painted, and only+ // then rewound to animate on its beat. The scatter was being drawn, and the+ // whole field was flashing up as one block before any of it ran.+ mover.animate(frames, { delay: beat, duration: life, easing: 'linear', fill: 'both' })++ // One slow pass down the lock. Repeating a fast sweep put a hard edge across+ // the element several times a second, which is both unreadable and a genuine+ // photosensitivity hazard; a single beam crossing slowly is what reads as+ // scanning anyway.+ const beam = spec.kind === 'lock' ? (skin.firstElementChild as HTMLElement | null) : null++ if (beam && typeof beam.animate === 'function') {+ beam.animate([{ opacity: 1, top: '-2px' }, { opacity: 1, top: '100%' }], {+ duration: dwell,+ easing: 'linear'+ })+ }+ }++ // Marks are glued to elements, not to coordinates, so they are re-measured for+ // as long as they are up. Overlapping fields are wanted — several actions'+ // worth of marks on screen at once IS the readout — but a mark that keeps its+ // original rectangle while the page scrolls under it stops being a mark and+ // becomes litter.+ const tick = () => {+ const shown = state.parts as ReturnType<typeof build> | undefined+ // Compacted in place rather than spliced, so the pass can run forwards: a+ // mark is drawn the first time it is seen here, and drawing them back to+ // front would put a field on screen in reverse.+ let keep = 0++ for (let i = 0; i < marks.length; i++) {+ const mark = marks[i]++ // A navigation or a re-render takes the element with it. The mark goes too+ // rather than hanging over whatever replaced it.+ if (!doc.contains(mark.spec.a)) {+ if (mark.cell) {+ mark.cell.remove()+ }++ continue+ }++ if (mark.cell && !mark.cell.isConnected) {+ // A transient retired itself on its own clock and is done. A held one+ // lost its shadow tree to a rebuild and has to come back.+ if (kinds[mark.spec.kind].life) {+ continue+ }++ mark.cell = undefined+ }++ marks[keep++] = mark++ if (!shown) {+ continue+ }++ if (!mark.cell) {+ const made = paint(mark.spec)++ mark.cell = made.cell+ mark.skin = made.skin+ mark.tag = made.tag+ mark.slot = undefined+ mark.wide = undefined+ shown.shadow.appendChild(made.cell)+ enter(mark)+ }++ const at = fit(mark)++ // The hand rides the lock. One mark owns where the cursor is, and it is+ // the one standing for the thing the agent is touching.+ if (mark.spec.kind === 'lock') {+ park(at)+ }+ }++ marks.length = keep+ state.raf = keep ? win.requestAnimationFrame(tick) : undefined+ }++ /** Draw everything outstanding now, then keep it measured. Restarting the loop+ * rather than waiting for the next frame is what makes a mark appear on the+ * call that added it. Called once per stage, never per mark: a pass measures+ * every mark on screen, and pumping inside `add` would make a field of two+ * hundred boxes two hundred passes over two hundred rectangles. */+ const pump = () => {+ if (state.raf) {+ win.cancelAnimationFrame(state.raf as number)+ state.raf = undefined+ }++ tick()+ }++ const add = (spec: WatchSpec) => marks.push({ spec })++ /** Outline a whole set. Shared by the sweep, the hold and the read, which+ * differ only in what the marks are made of and how they are spread. `beat`+ * is handed the rectangle as well as the index, because a wipe is timed off+ * where a box IS and a scatter off which one it is. */+ const outline = (all: Element[], kind: WatchKind, beat: (at: number, seen: WatchSpot) => number, life?: number) => {+ for (let i = 0; i < all.length; i++) {+ const seen = spot(all[i])++ if (seen.width < 1 || seen.height < 1) {+ continue+ }++ // Named only when there is room for the tag AND few enough boxes for a+ // name to be worth reading. A hundred outlines is a picture of what the+ // agent can reach; a hundred names on top of it is a wall.+ const named = all.length <= busy && seen.width >= 16 && seen.height >= 10++ add({ a: all[i], beat: beat(i, seen), kind, label: named ? sniff(all[i]) : undefined, life })+ }+ }++ const hush = () => {+ if (state.mind) {+ win.clearInterval(state.mind as number)+ state.mind = undefined+ }+ }++ /** Take down every mark the predicate claims. */+ const retire = (claims: (spec: WatchSpec) => boolean) => {+ for (let i = marks.length - 1; i >= 0; i--) {+ if (!claims(marks[i].spec)) {+ continue+ }++ if (marks[i].cell) {+ ;(marks[i].cell as HTMLElement).remove()+ }++ marks.splice(i, 1)+ }+ }++ // ── THE PAGE'S PROSE ──────────────────────────────────────────────────────++ /** Every block of text on screen, in document order.+ *+ * Deliberately not a tag list. `p, h1…h6, li, td` misses the single most+ * common shape on the modern web — a `div` with words directly inside it —+ * and a list long enough to catch that catches the wrappers too. What+ * actually separates a block of text from its container is owning a text+ * node outright, so that is the test. An ancestor that qualifies wins, which+ * keeps a paragraph whole instead of lighting up every `span` inside it. */+ const prose = () => {+ if (!doc.body) {+ return []+ }++ const all = doc.body.getElementsByTagName('*')+ // The chosen blocks, for the descendants of each to measure themselves+ // against. Document order guarantees an ancestor is decided before anything+ // under it asks, so one pass is enough.+ const bag = new Set<Element>()+ const found: Element[] = []++ for (let i = 0; i < all.length && found.length < page; i++) {+ const el = all[i]+ const tag = el.tagName++ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT' || tag === 'TEMPLATE' || tag === 'OPTION') {+ continue+ }++ let words = false++ for (let node = el.firstChild; node; node = node.nextSibling) {+ if (node.nodeType === 3 && (node.nodeValue || '').trim()) {+ words = true+ break+ }+ }++ if (!words) {+ continue+ }++ let up = el.parentElement+ let inside = false++ while (up) {+ if (bag.has(up)) {+ inside = true+ break+ }++ up = up.parentElement+ }++ if (inside) {+ continue+ }++ bag.add(el)++ // Catches what a rectangle can't: `opacity: 0`, `visibility: hidden`, and+ // anything an ancestor has hidden. Guarded because it is recent enough+ // that the test environment doesn't have it.+ const look = (el as Element & { checkVisibility?: (opts?: object) => boolean }).checkVisibility++ if (typeof look === 'function' && !look.call(el, { opacityProperty: true, visibilityProperty: true })) {+ continue+ }++ const seen = spot(el)++ // On screen and big enough to be text. Off-viewport blocks are most of a+ // long document and outlining them draws nothing anyone can see.+ if (+ seen.width < 16 ||+ seen.height < 6 ||+ seen.left + seen.width <= 0 ||+ seen.top + seen.height <= 0 ||+ seen.left >= win.innerWidth ||+ seen.top >= win.innerHeight+ ) {+ continue+ }++ found.push(el)+ }++ return found+ }++ // ── STAGES ────────────────────────────────────────────────────────────────++ // The cursor is built once and reused for the life of the page. That memo has+ // to break when the code that built it changes, or an edit to its styles is+ // injected, runs, and restyles nothing: the layers it describes were built by+ // the previous version and are still sitting on the page. Same failure across+ // an app upgrade under a long-lived tab; it just looks like "HMR isn't picking+ // this up" in dev.+ const stamp = (win as unknown as { __hermesWatchTag?: number }).__hermesWatchTag++ if (state.tag !== stamp) {+ state.tag = stamp+ state.parts = undefined+ // The pulse outlives an injection, so a rebuild has to stop the old one —+ // its ticks would keep firing against the overlay it was born in.+ hush()+ }++ const mounted = state.parts as ReturnType<typeof build> | undefined+ const target = holder.aimed++ if (stage === 'clear' || stage === 'rest') {+ hush()++ if (stage === 'rest') {+ // The turn is over, not the session. Whatever is up keeps its own clock —+ // the point of `rest` is only that the page stops being thought about.+ return+ }++ holder.aimed = null+ retire(spec => !!kinds[spec.kind].life)++ if (mounted) {+ style(mounted.pointer, { opacity: '0' })+ }++ return+ }++ // The gap between actions is most of the time the agent spends on a page, and+ // the overlay used to go dark for all of it — the marks decayed and nothing+ // said the page was still being held in mind. This taps one element at a time,+ // sparsely and unevenly, for as long as the turn runs.+ //+ // Started BEFORE the there-is-nothing-to-draw bail, because a turn begins when+ // the user hits send and the agent has usually not read the page yet: gating+ // the pulse on a field that only exists after the first inventory would mean+ // it never starts on the turn that matters. The tick is the guard instead — it+ // no-ops until there is an overlay and a field, so nothing is grafted onto a+ // page the agent never touched.+ if (stage === 'think') {+ // Called through `state.pulse` rather than closing over this invocation, so+ // an interval started by an older injection still runs the newest code.+ state.pulse = () => {+ const live = (holder.field && holder.field.length ? holder.field : holder.nodes || []) as Element[]++ if (!live.length || !state.parts || Math.random() < quiet) {+ return+ }++ const el = live[Math.floor(Math.random() * live.length)]+ const seen = spot(el)++ if (seen.width >= 1 && seen.height >= 1) {+ add({ a: el, kind: 'flash', label: sniff(el), life: ponder + Math.random() * ponder })+ pump()+ }+ }++ if (!state.mind && !still) {+ state.mind = win.setInterval(() => {+ const beat = state.pulse as (() => void) | undefined++ if (beat) {+ beat()+ }+ }, throb)+ }++ return+ }++ // Taking a pin down needs no overlay of its own — and with no target it means+ // all of them, so it runs before the there-is-nothing-to-draw bail.+ if (stage === 'unpin') {+ retire(spec => spec.kind === 'held' && (!target || spec.a === target))+ holder.aimed = null++ return+ }++ // These draw the whole field rather than one target.+ const wide = stage === 'sweep' || stage === 'hold' || stage === 'strobe'+ const field = holder.field && holder.field.length ? holder.field : holder.nodes || []+ // The read draws the page's PROSE instead. The two sets barely overlap: what+ // read_preview takes away is the text, and what the field is made of is the+ // controls. Gathered here rather than in the branch so the bail below can see+ // whether there was anything to read.+ const text = stage === 'read' ? prose() : []++ // Nothing to draw on. Bail before building, so a stage with an empty set+ // never gets an overlay host grafted onto a page for nothing.+ if (stage === 'read' ? !text.length : wide ? !field.length : !target || !doc.contains(target)) {+ return+ }++ const parts = mounted && mounted.host.isConnected ? mounted : build()++ state.parts = parts+ parts.nib.setAttribute('fill', ink)++ // Re-assert on every stage: `showPopover` appends to the BACK of the top+ // layer, so a dialog the page opened after us would otherwise cover the+ // overlay for the rest of the session.+ try {+ ;(parts.host as HTMLElement & { hidePopover: () => void }).hidePopover()+ ;(parts.host as HTMLElement & { showPopover: () => void }).showPopover()+ } catch {+ // No popover support, or the host is detached — the z-index fallback stands.+ }++ if (stage === 'pin') {+ // Pinning something already pinned relabels it, rather than stacking a+ // second box on the same rectangle.+ retire(spec => spec.kind === 'held' && spec.a === target)+ add({ a: target as Element, kind: 'held', label: label || sniff(target as Element) })+ holder.aimed = null+ } else if (stage === 'hold') {+ // Freeze the whole field: the same picture a sweep paints, promoted to pins+ // so it stops decaying. Everything a sweep draws is on a clock by design —+ // it narrates an action and gets out of the way — and this is the escape+ // hatch for when the picture IS the answer and has to stay up to be looked+ // at. Held twice means held once: re-running it after the page moved on+ // replaces the picture rather than layering a second over the first.+ retire(spec => spec.kind === 'held')+ outline(field, 'held', () => 0)+ holder.aimed = null+ } else if (stage === 'sweep') {+ // Only the lock goes. The previous field is deliberately left to run out its+ // own clock underneath this one — several sweeps' worth of boxes on screen+ // at once is the readout, not a glitch, and they stay honest because every+ // one of them is still tracking its own element.+ retire(spec => spec.kind === 'lock')+ holder.aimed = null+ // Scattered, not top-to-bottom. A document-order cascade reads as a wipe+ // passing over the page; firing all over it at once reads as the whole page+ // being taken in at once, which is what actually happened. Deterministic, so+ // a re-run of the same page looks the same twice.+ outline(field, 'candidate', at => {+ const noise = Math.sin((at + 1) * 12.9898) * 43758.5453++ return (noise - Math.floor(noise)) * cascade+ })+ } else if (stage === 'read') {+ // A beam down the page. Every other stage scatters on purpose — an+ // inventory happens all at once and saying it in document order would be a+ // lie about what the agent did. Reading is the exception: it genuinely goes+ // top to bottom, so the cue does too, and the two are told apart at a+ // glance. Timed off where a block SITS rather than its index, so two+ // columns light together and the beam stays straight.+ retire(spec => spec.kind === 'lock')+ holder.aimed = null+ outline(+ text,+ 'candidate',+ (_at, seen) => Math.max(0, Math.min(1, (seen.top + seen.height / 2) / win.innerHeight)) * wipe,+ glance+ )+ } else if (stage === 'strobe') {+ // A few boxes at a time, out of order, revisiting, at an uneven rhythm — a+ // machine ripping through the page rather than reading it top to bottom. A+ // sweep can't say this: it puts the field up as one picture and holds it.+ // The whole burst is scheduled here in one pass, because the alternative is+ // a bridge round-trip per box, and at ~100ms each the rhythm is the latency.+ retire(spec => spec.kind === 'lock')+ holder.aimed = null++ // Deterministic — the same page strobes the same way twice — but with a+ // fresh draw per call rather than one hash of the index, so the gaps, the+ // clump sizes and the picks are independent of each other. Read in a fixed+ // order below: reordering these calls changes the sequence.+ let seed = 0+ const roll = () => {+ const noise = Math.sin(++seed * 78.233) * 43758.5453++ return noise - Math.floor(noise)+ }++ if (still) {+ // Nothing about a strobe survives reduced motion, and the timed fallback+ // is worse than useless here: with no animation to hold a mark invisible+ // through its delay, every box in the burst would paint at once. Show the+ // field it was going to rattle through instead.+ outline(field, 'candidate', () => 0)+ } else {+ for (let at = 0; at < burst; ) {+ const clump = roll() < 0.62 ? 1 : roll() < 0.7 ? 2 : 3++ for (let k = 0; k < clump; k++) {+ // Drawn WITH replacement: hitting the same box twice in a run is the+ // point, not a flaw in the shuffle.+ const el = field[Math.floor(roll() * field.length)]+ const seen = spot(el)++ if (seen.width >= 1 && seen.height >= 1) {+ add({ a: el, beat: at, kind: 'flash', label: sniff(el), life: blink + roll() * flick })+ }+ }++ at += roll() < 0.85 ? tempo + roll() * tempo * 2 : gasp + roll() * gasp+ }+ }+ } else if (stage === 'strike') {+ add({ a: target as Element, kind: 'hit' })+ } else {+ // aim — box the target and put the hand on it.+ retire(spec => spec.kind === 'lock')++ // The lock is always named, however dense the field it is standing in. On a+ // page too busy to name the candidates it is the only tag on screen, which+ // is the right hierarchy: the outlines say what the agent can reach, and the+ // one name says what it is reaching for.+ add({ a: target as Element, kind: 'lock', label: sniff(target as Element) })+ style(parts.pointer, { opacity: '1' })+ }++ // One pass for the whole stage: draws whatever was just added, redraws any pin+ // that lost its shadow tree to a rebuild, and re-arms the tracking loop.+ pump()+}