The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(tools): drive_preview and annotate_preview — the agent can use the page it opened
Brooklyn Nicholsonc57581cd0d0d
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 4e097d6dfca..b839b355767 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -546,6 +546,7 @@ def init_agent(clarify_callback: callable = None,read_terminal_callback: callable = None,read_preview_callback: callable = None,+ drive_preview_callback: callable = None,read_window_below_callback: callable = None,setup_mcp_callback: callable = None,tour_callback: callable = None,@@ -843,6 +844,7 @@ def init_agent(agent.clarify_callback = clarify_callbackagent.read_terminal_callback = read_terminal_callbackagent.read_preview_callback = read_preview_callback+ agent.drive_preview_callback = drive_preview_callbackagent.read_window_below_callback = read_window_below_callbackagent.setup_mcp_callback = setup_mcp_callbackagent.tour_callback = tour_callbackdiff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 983c95b5d6e..2744c1b72da 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -99,7 +99,7 @@ def _ra():AGENT_RUNTIME_POST_HOOK_TOOL_NAMES = frozenset(- {"todo", "session_search", "memory", "clarify", "read_terminal", "read_preview", "read_window_below", "setup_mcp", "tour", "delegate_task"}+ {"todo", "session_search", "memory", "clarify", "read_terminal", "read_preview", "drive_preview", "annotate_preview", "read_window_below", "setup_mcp", "tour", "delegate_task"})@@ -3234,6 +3234,37 @@ def invoke_tool(agent, function_name: str, function_args: dict, effective_task_i),next_args,)+ elif function_name == "drive_preview":+ def _execute(next_args: dict) -> Any:+ from tools.drive_preview_tool import drive_preview_tool as _drive_preview_tool+ return _finish_agent_tool(+ _drive_preview_tool(+ action=next_args.get("action", ""),+ ref=next_args.get("ref"),+ selector=next_args.get("selector"),+ text=next_args.get("text"),+ key=next_args.get("key"),+ submit=next_args.get("submit"),+ amount=next_args.get("amount"),+ to=next_args.get("to"),+ limit=next_args.get("max"),+ callback=getattr(agent, "drive_preview_callback", None),+ ),+ next_args,+ )+ elif function_name == "annotate_preview":+ def _execute(next_args: dict) -> Any:+ from tools.annotate_preview_tool import annotate_preview_tool as _annotate_preview_tool+ return _finish_agent_tool(+ _annotate_preview_tool(+ action=next_args.get("action", "add"),+ ref=next_args.get("ref"),+ selector=next_args.get("selector"),+ label=next_args.get("label"),+ callback=getattr(agent, "drive_preview_callback", None),+ ),+ next_args,+ )elif function_name == "read_window_below":def _execute(next_args: dict) -> Any:from tools.read_window_tool import read_window_below_tool as _read_window_below_tooldiff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex 4a828477c36..e7bb9126db5 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -2202,6 +2202,57 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effetool_duration = time.time() - tool_start_timeif agent._should_emit_quiet_tool_messages():agent._vprint(f" {_get_cute_tool_message_impl('read_preview', function_args, tool_duration, result=function_result)}")+ elif function_name == "drive_preview":+ def _execute(next_args: dict) -> Any:+ from tools.drive_preview_tool import drive_preview_tool as _drive_preview_tool+ return _drive_preview_tool(+ action=next_args.get("action", ""),+ ref=next_args.get("ref"),+ selector=next_args.get("selector"),+ text=next_args.get("text"),+ key=next_args.get("key"),+ submit=next_args.get("submit"),+ amount=next_args.get("amount"),+ to=next_args.get("to"),+ limit=next_args.get("max"),+ callback=getattr(agent, "drive_preview_callback", None),+ )+ function_result, function_args, middleware_trace, _execution_blocked, _execution_dispatched = _managed_values(_run_agent_tool_execution_middleware(+ agent,+ function_name=function_name,+ function_args=function_args,+ effective_task_id=effective_task_id,+ tool_call_id=getattr(tool_call, "id", "") or "",+ execute=_execute,+ scope_block=_ts_scope_block,+ display_index=i,+ ))+ tool_duration = time.time() - tool_start_time+ if agent._should_emit_quiet_tool_messages():+ agent._vprint(f" {_get_cute_tool_message_impl('drive_preview', function_args, tool_duration, result=function_result)}")+ elif function_name == "annotate_preview":+ def _execute(next_args: dict) -> Any:+ from tools.annotate_preview_tool import annotate_preview_tool as _annotate_preview_tool+ return _annotate_preview_tool(+ action=next_args.get("action", "add"),+ ref=next_args.get("ref"),+ selector=next_args.get("selector"),+ label=next_args.get("label"),+ callback=getattr(agent, "drive_preview_callback", None),+ )+ function_result, function_args, middleware_trace, _execution_blocked, _execution_dispatched = _managed_values(_run_agent_tool_execution_middleware(+ agent,+ function_name=function_name,+ function_args=function_args,+ effective_task_id=effective_task_id,+ tool_call_id=getattr(tool_call, "id", "") or "",+ execute=_execute,+ scope_block=_ts_scope_block,+ display_index=i,+ ))+ tool_duration = time.time() - tool_start_time+ if agent._should_emit_quiet_tool_messages():+ agent._vprint(f" {_get_cute_tool_message_impl('annotate_preview', function_args, tool_duration, result=function_result)}")elif function_name == "read_window_below":def _execute(next_args: dict) -> Any:from tools.read_window_tool import read_window_below_tool as _read_window_below_tooldiff --git a/apps/desktop/src/app/chat/right-rail/preview-act.test.ts b/apps/desktop/src/app/chat/right-rail/preview-act.test.tsnew file mode 100644index 00000000000..b53e0463420--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-act.test.ts@@ -0,0 +1,127 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { $rightRailActiveTabId } from '@/store/layout'+import { closeRightRail, openPreview, type PreviewTarget } from '@/store/preview'++import { actOnActivePreview } from './preview-act'+import { registerPreviewNav } from './preview-nav'+import { registerPreviewScriptRunner } from './preview-script-runner'++function urlTarget(url: string): PreviewTarget {+ return { kind: 'url', label: 'Browser', source: url, url }+}++describe('actOnActivePreview (act_preview tool)', () => {+ // URL targets share the singleton Browser tab id, so anything a test+ // registers would answer the next one.+ let cleanups: Array<() => void> = []++ const openBrowserTab = () => {+ openPreview(urlTarget('https://example.com'), 'tool-result')++ return $rightRailActiveTabId.get()!+ }++ const withRunner = (runner: (code: string) => Promise<unknown>) =>+ cleanups.push(registerPreviewScriptRunner(openBrowserTab(), runner))++ beforeEach(() => {+ vi.useRealTimers()++ for (const cleanup of cleanups) {+ cleanup()+ }++ cleanups = []+ closeRightRail()+ window.localStorage.clear()+ })++ it('tells the agent to open a page when no live pane is behind the tab', async () => {+ const result = await actOnActivePreview({ kind: 'elements' })++ expect(result.success).toBe(false)+ expect(result.error).toContain('open_preview')+ })++ it('injects the engine and returns the page’s answer', async () => {+ let injected = ''++ withRunner(async code => {+ injected = code++ return JSON.stringify({ acted: 'clicked button "Save"', success: true })+ })++ const result = await actOnActivePreview({ kind: 'click', ref: '@e1' })++ expect(result).toMatchObject({ acted: 'clicked button "Save"', success: true })+ // Self-contained payload: the engine source and the action travel together,+ // and the holder keeps refs alive across calls on the same page.+ expect(injected).toContain('__hermesActHolder')+ expect(injected).toContain('"ref":"@e1"')+ })++ it('re-inventories after a mutating action so the next ref is current', async () => {+ const actions: string[] = []++ withRunner(code => {+ // Stand in for the guest page: run the script's own settle/rescan shape+ // by answering each act() call in order.+ actions.push(...(code.match(/"kind":"(\w+)"/g) ?? []))++ return Promise.resolve(+ JSON.stringify({+ acted: 'clicked',+ elements: [{ label: 'Log out', ref: '@e1', role: 'button', selector: '#out' }],+ success: true,+ url: 'https://example.com/app'+ })+ )+ })++ const result = await actOnActivePreview({ kind: 'click', ref: '@e1' })++ expect(result.elements?.[0].label).toBe('Log out')+ expect(result.url).toBe('https://example.com/app')+ })++ it('does not pay the settle delay for a plain inventory', async () => {+ let injected = ''+ withRunner(async code => {+ injected = code++ return JSON.stringify({ elements: [], success: true })+ })++ await actOnActivePreview({ kind: 'elements' })++ expect(injected).toContain('0 <= 0')+ })++ it('reports a page that answers with nothing', async () => {+ withRunner(async () => '')++ expect((await actOnActivePreview({ kind: 'click', ref: '@e1' })).error).toContain('did not answer')+ })++ it('routes history verbs to the pane instead of the guest page', async () => {+ const back = vi.fn()+ const runner = vi.fn()++ const tabId = openBrowserTab()+ cleanups.push(registerPreviewNav(tabId, { back, forward: vi.fn(), reload: vi.fn() }))+ cleanups.push(registerPreviewScriptRunner(tabId, runner))++ const result = await actOnActivePreview({ kind: 'back' })++ expect(back).toHaveBeenCalledOnce()+ expect(runner).not.toHaveBeenCalled()+ expect(result.success).toBe(true)+ expect(result.note).toContain('elements')+ })++ it('reports history verbs with no pane to drive', async () => {+ expect((await actOnActivePreview({ kind: 'reload' })).error).toContain('open_preview')+ })+})diff --git a/apps/desktop/src/app/chat/right-rail/preview-act.ts b/apps/desktop/src/app/chat/right-rail/preview-act.tsnew file mode 100644index 00000000000..495ce45f0a7--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-act.ts@@ -0,0 +1,98 @@+/**+ * 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+ * 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.+ *+ * A mutating action settles briefly and returns a fresh inventory, so the+ * click → re-read → click loop costs one round trip instead of two.+ *+ * Dynamic-imported by the gateway event handler so the engine payload stays+ * out of the boot path.+ */++import { actInPage, type PreviewActAction, type PreviewActResult } from '@/lib/preview-act/act-in-page'++import { activePreviewNav, type PreviewNavHandle } from './preview-nav'+import { activePreviewScriptRunner } 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++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()});+ }+ var act = function (a) { return w.__hermesAct(document, w.__hermesActHolder, a); };+ var result = act(${JSON.stringify(action)});+ if (!result.success || ${settleMs} <= 0) {+ return Promise.resolve(JSON.stringify(result));+ }+ // 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 () {+ var after = act({ kind: 'elements' });+ result.elements = after.elements;+ result.url = after.url;+ result.title = after.title;+ resolve(JSON.stringify(result));+ }, ${settleMs});+ });+})()`+}++/** 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. */+export async function actOnActivePreview(+ action: Omit<PreviewActAction, 'kind'> & { kind: string }+): Promise<PreviewActResult> {+ const nav = NAV_ACTIONS.find(verb => verb === action.kind)++ if (nav) {+ const handle = activePreviewNav()++ if (!handle) {+ return { error: NOTHING_OPEN, success: false }+ }++ handle[nav]()++ // Navigation is fire-and-forget through the webview; the new document has+ // its own refs, so the agent has to re-inventory either way.+ return { acted: nav, note: 'Page is loading — call elements to see what is on it.', success: true }+ }++ const run = activePreviewScriptRunner()++ if (!run) {+ return { error: NOTHING_OPEN, success: false }+ }++ const typed = action as PreviewActAction+ const settle = typed.kind === 'elements' ? 0 : SETTLE_MS+ const raw = await run(buildActScript(typed, settle))++ if (typeof raw !== 'string' || !raw) {+ return { error: 'The page did not answer the action.', success: false }+ }++ return JSON.parse(raw) as PreviewActResult+}diff --git a/apps/desktop/src/app/chat/right-rail/preview-nav.ts b/apps/desktop/src/app/chat/right-rail/preview-nav.tsindex 954c1a5e9b5..5e03db3005b 100644--- a/apps/desktop/src/app/chat/right-rail/preview-nav.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-nav.ts@@ -9,6 +9,9 @@* sitting in Hermes' own DOM, where `activeElement` is authoritative.*/+import { $rightRailActiveTabId } from '@/store/layout'+import { $previewTabs } from '@/store/preview'+/** Marks a live browser pane so a gesture can find the one holding focus. */export const PREVIEW_BROWSER_ATTR = 'data-preview-browser'@@ -31,6 +34,15 @@ export function registerPreviewNav(tabId: string, handle: PreviewNavHandle): ()}}+/** The ACTIVE preview tab's commands, for callers with no focus to key off —+ * the agent's drive_preview, which runs while focus is in the composer. */+export function activePreviewNav(): PreviewNavHandle | null {+ const tabs = $previewTabs.get()+ const tab = tabs.find(t => t.id === $rightRailActiveTabId.get()) ?? tabs[0]++ return (tab && handles.get(tab.id)) || null+}+/** Run `command` on the browser pane holding DOM focus. False = focus is* elsewhere in the app, so the caller falls back to the app-level meaning. */export function commandFocusedPreview(command: keyof PreviewNavHandle): boolean {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 dbb05085104..1a8cee9d02e 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@@ -2,6 +2,7 @@ import { readActivePreview } from '@/app/chat/right-rail/preview-reader'import { writeAgentTerminalChunk } from '@/app/right-sidebar/terminal/agent-terminal-stream'import { readActiveTerminal } from '@/app/right-sidebar/terminal/buffer'import { closeAgentTerminalByProc } from '@/app/right-sidebar/terminal/terminals'+import type { PreviewActAction } from '@/lib/preview-act/act-in-page'import type { TourAction, TourStep } from '@/lib/tour'import { $gateway } from '@/store/gateway'import { applyDesktopLayoutPreset, revealDesktopPane } from '@/store/pane-focus'@@ -55,6 +56,50 @@ export function handleDesktopBridgeEvent(ctx: GatewayEventContext): boolean {return true}+ if (event.type === 'preview.act.request') {+ // act_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+ // hijack).+ const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''++ if (requestId) {+ const answer = (result: unknown) =>+ $gateway.get()?.request('preview.act.respond', {+ request_id: requestId,+ text: result ? JSON.stringify(result) : ''+ })++ if (isActiveEvent) {+ void import('@/app/chat/right-rail/preview-act')+ .then(({ actOnActivePreview }) =>+ actOnActivePreview({+ amount: payload?.amount,+ key: payload?.key,+ kind: payload?.action ?? '',+ max: payload?.max,+ ref: payload?.ref,+ selector: payload?.selector,+ submit: payload?.submit,+ text: payload?.text,+ to: payload?.to as PreviewActAction['to']+ })+ )+ .then(answer, error =>+ answer({ error: error instanceof Error ? error.message : String(error), success: false })+ )+ } else {+ void answer({+ error: 'The in-app browser only takes actions in the session the user is looking at.',+ success: false+ })+ }+ }++ return true+ }+if (event.type === 'window.read.request') {// read_window_below tool: main owns native window enumeration, so ask// it over IPC and answer. Empty text = unavailable (no bridge, ordiff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex 2974b8d56a7..0706a730850 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -121,6 +121,15 @@ export type GatewayEventPayload = {side?: stringsteps?: unknownstep_index?: number+ // preview.act.request (drive_preview tool — agent clicking/typing/scrolling in+ // the in-app browser). `action` names the verb and `selector` is shared with+ // tour above; `ref` addresses an element from the last inventory.+ ref?: string+ submit?: boolean+ key?: string+ amount?: number+ to?: string+ max?: number// message.reaction (agent reacting via the react_to_message tool) — the// durable messages.id, that row's full reaction list after the write, and// the row's role so a live (not-yet-round-tripped) message can be matched.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.tsnew file mode 100644index 00000000000..aa1985fb7a1--- /dev/null+++ b/apps/desktop/src/lib/preview-act/act-in-page.test.ts@@ -0,0 +1,319 @@+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+ * `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++ return { bottom: size, height: size, left: 0, right: size, top: 0, width: size, x: 0, y: 0 } as DOMRect+ })+}++function page(html: string): PreviewActHolder {+ document.body.innerHTML = html++ return {}+}++/** Take the inventory the agent would take before acting. */+function inventory(holder: PreviewActHolder) {+ return actInPage(document, holder, { kind: 'elements' })+}++beforeEach(() => {+ vi.restoreAllMocks()+ layOutTheDocument()+ Element.prototype.scrollIntoView = vi.fn()+})++describe('elements', () => {+ it('numbers the interactive nodes with browser_*-style refs', () => {+ const holder = page(`+ <button id="save">Save</button>+ <a href="/help">Help</a>+ <input id="who" placeholder="Your name" />+ <p>Not interactive</p>+ `)++ const result = inventory(holder)++ expect(result.success).toBe(true)+ expect(result.elements?.map(e => [e.ref, e.label])).toEqual([+ ['@e1', 'Save'],+ ['@e2', 'Help'],+ ['@e3', 'Your name']+ ])+ })++ it('reports role, current value, and disabled state', () => {+ const holder = page(`+ <input id="email" aria-label="Email" type="email" value="[email protected]" />+ <button id="go" disabled>Go</button>+ `)++ const [email, go] = inventory(holder).elements!++ expect(email).toMatchObject({ label: 'Email', role: 'input:email', value: '[email protected]' })+ expect(go).toMatchObject({ disabled: true, label: 'Go' })+ expect(email.disabled).toBeUndefined()+ })++ it('skips hidden controls and unlabelled ones', () => {+ const holder = page(`+ <button id="real">Real</button>+ <button id="gone" style="display: none">Gone</button>+ <button id="mystery"></button>+ `)++ expect(inventory(holder).elements?.map(e => e.label)).toEqual(['Real'])+ })++ 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>+ <div><button>Plain</button></div>+ `)++ const [byTestId, positional] = inventory(holder).elements!++ expect(byTestId.selector).toBe('[data-testid="submit"]')+ expect(document.querySelector(positional.selector)).toBe(document.querySelectorAll('button')[1])+ })++ it('honours the cap', () => {+ const holder = page(Array.from({ length: 10 }, (_, i) => `<button>B${i}</button>`).join(''))++ expect(inventory(holder).elements).toHaveLength(10)+ expect(actInPage(document, holder, { kind: 'elements', max: 3 }).elements).toHaveLength(3)+ })+})++describe('click', () => {+ it('activates the element a ref points at', () => {+ const holder = page('<button id="save">Save</button>')+ inventory(holder)++ const clicked = vi.fn()+ document.getElementById('save')!.addEventListener('click', clicked)++ const result = actInPage(document, holder, { kind: 'click', ref: '@e1' })++ expect(result.success).toBe(true)+ expect(result.acted).toContain('Save')+ expect(clicked).toHaveBeenCalledOnce()+ })++ it('replays the pointer/mouse sequence frameworks bind to', () => {+ const holder = page('<button id="save">Save</button>')+ inventory(holder)++ const seen: string[] = []++ for (const type of ['pointerdown', 'mousedown', 'mouseup', 'pointerup', 'click']) {+ document.getElementById('save')!.addEventListener(type, () => seen.push(type))+ }++ actInPage(document, holder, { kind: 'click', ref: '@e1' })++ expect(seen).toContain('mousedown')+ expect(seen).toContain('mouseup')+ expect(seen.at(-1)).toBe('click')+ })++ it('takes a raw CSS selector when no ref fits', () => {+ const holder = page('<button id="save">Save</button>')+ const clicked = vi.fn()+ document.getElementById('save')!.addEventListener('click', clicked)++ expect(actInPage(document, holder, { kind: 'click', selector: '#save' }).success).toBe(true)+ expect(clicked).toHaveBeenCalledOnce()+ })++ it('refuses a disabled control instead of silently doing nothing', () => {+ const holder = page('<button id="save" disabled>Save</button>')+ inventory(holder)++ const result = actInPage(document, holder, { kind: 'click', ref: '@e1' })++ expect(result.success).toBe(false)+ expect(result.error).toContain('disabled')+ })++ it('reports the live url so a navigation is visible to the agent', () => {+ const holder = page('<button id="save">Save</button>')+ inventory(holder)++ expect(actInPage(document, holder, { kind: 'click', ref: '@e1' }).url).toBe(document.location.href)+ })+})++describe('stale refs', () => {+ it('names an unknown ref rather than clicking whatever sits at that index', () => {+ const holder = page('<button>Only</button>')+ inventory(holder)++ const result = actInPage(document, holder, { kind: 'click', ref: '@e9' })++ expect(result.success).toBe(false)+ expect(result.error).toContain('elements')+ })++ it('catches a node that was removed after the snapshot', () => {+ const holder = page('<button id="save">Save</button>')+ inventory(holder)+ document.getElementById('save')!.remove()++ expect(actInPage(document, holder, { kind: 'click', ref: '@e1' }).error).toContain('removed')+ })++ it('invalidates every ref when the page navigated under them', () => {+ const holder = page('<button>Save</button>')+ inventory(holder)+ holder.url = 'https://elsewhere.example/other'++ expect(actInPage(document, holder, { kind: 'click', ref: '@e1' }).error).toContain('navigated')+ })++ it('asks for a target when given neither', () => {+ expect(actInPage(document, page('<button>Save</button>'), { kind: 'click' }).error).toContain('selector')+ })++ it('reports a selector that matches nothing', () => {+ expect(actInPage(document, page(''), { kind: 'click', selector: '#nope' }).error).toContain('No element')+ })+})++describe('type', () => {+ it('enters text and fires the events a controlled input listens for', () => {+ const holder = page('<input id="who" placeholder="Your name" />')+ inventory(holder)++ const input = document.getElementById('who') as HTMLInputElement+ const events: string[] = []+ input.addEventListener('input', () => events.push('input'))+ input.addEventListener('change', () => events.push('change'))++ const result = actInPage(document, holder, { kind: 'type', ref: '@e1', text: 'Brooklyn' })++ expect(result.success).toBe(true)+ expect(input.value).toBe('Brooklyn')+ expect(events).toEqual(['input', 'change'])+ })++ it('bypasses the own-property shadow React installs on tracked inputs', () => {+ const holder = page('<input id="who" placeholder="Your name" />')+ inventory(holder)++ // React defines its own `value` accessor on the node to track what it last+ // wrote, and ignores an input event that agrees with it. Writing through+ // that shadow is exactly how typed text snaps back on the next render.+ const input = document.getElementById('who') as HTMLInputElement+ const nativeValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!+ const shadowWrites: string[] = []++ Object.defineProperty(input, 'value', {+ configurable: true,+ get: () => nativeValue.get!.call(input),+ set: (next: string) => {+ shadowWrites.push(next)+ }+ })++ actInPage(document, holder, { kind: 'type', ref: '@e1', text: 'Brooklyn' })++ expect(shadowWrites).toEqual([])+ expect(nativeValue.get!.call(input)).toBe('Brooklyn')+ })++ it('writes into a contenteditable host', () => {+ const holder = page('<div id="editor" contenteditable="true" aria-label="Body"></div>')+ inventory(holder)++ actInPage(document, holder, { kind: 'type', ref: '@e1', text: 'hello' })++ expect(document.getElementById('editor')!.textContent).toBe('hello')+ })++ it('submits the owning form when asked', () => {+ const holder = page('<form id="f"><input id="q" placeholder="Search" /></form>')+ inventory(holder)++ const form = document.getElementById('f') as HTMLFormElement+ form.requestSubmit = vi.fn()++ const result = actInPage(document, holder, { kind: 'type', ref: '@e1', submit: true, text: 'cats' })++ expect(form.requestSubmit).toHaveBeenCalledOnce()+ expect(result.acted).toContain('submitted')+ })++ it('refuses a target that has no text to type into', () => {+ const holder = page('<button id="b">Press</button>')+ inventory(holder)++ expect(actInPage(document, holder, { kind: 'type', ref: '@e1', text: 'x' }).error).toContain('not a text field')+ })+})++describe('press', () => {+ it('sends the key to the target', () => {+ const holder = page('<input id="q" placeholder="Search" />')+ inventory(holder)++ const keys: string[] = []+ document.getElementById('q')!.addEventListener('keydown', e => keys.push((e as KeyboardEvent).key))++ expect(actInPage(document, holder, { key: 'Enter', kind: 'press', ref: '@e1' }).success).toBe(true)+ expect(keys).toEqual(['Enter'])+ })++ it('needs a key', () => {+ const holder = page('<input id="q" placeholder="Search" />')+ inventory(holder)++ expect(actInPage(document, holder, { kind: 'press', ref: '@e1' }).error).toContain('key')+ })+})++describe('scroll', () => {+ it('scrolls the page by about a screen when given no distance', () => {+ const holder = page('<p>long page</p>')+ const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => {})++ const result = actInPage(document, holder, { kind: 'scroll' })++ expect(result.success).toBe(true)+ expect(scrollBy).toHaveBeenCalledWith({ behavior: 'auto', top: Math.round(window.innerHeight * 0.9) })+ })++ it('jumps to the bottom', () => {+ const holder = page('<p>long page</p>')+ const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(() => {})++ actInPage(document, holder, { kind: 'scroll', to: 'bottom' })++ const [options] = scrollBy.mock.calls[0] as unknown as [ScrollToOptions]++ expect(options.top).toBeGreaterThan(window.innerHeight)+ })++ it('scrolls a ref’d container instead of the page', () => {+ const holder = page('<div id="list" aria-label="Results" tabindex="0" style="overflow: auto"></div>')+ inventory(holder)++ const list = document.getElementById('list') as HTMLElement+ list.scrollBy = vi.fn()+ const pageScroll = vi.spyOn(window, 'scrollBy').mockImplementation(() => {})++ const result = actInPage(document, holder, { amount: 200, kind: 'scroll', ref: '@e1' })++ expect(list.scrollBy).toHaveBeenCalledWith({ behavior: 'auto', 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.tsnew file mode 100644index 00000000000..f664f582993--- /dev/null+++ b/apps/desktop/src/lib/preview-act/act-in-page.ts@@ -0,0 +1,414 @@+/**+ * PREVIEW ACT ENGINE — the one function that performs an interaction inside a+ * page, so the agent can drive the in-app browser instead of only reading it.+ *+ * `elements` hands back a numbered inventory of what can be interacted with+ * (`@e1`, `@e2`, … — the same ref shape the browser_* tools use, so a model+ * that knows one knows the other) and parks the matching nodes on a holder.+ * Every other verb resolves its target from that holder, falling back to a raw+ * CSS selector.+ *+ * Injected into the preview webview as source (`actInPage.toString()`), so it+ * MUST stay self-contained: no imports, no closure references, no renderer+ * globals — everything arrives as a parameter. The structural types below+ * erase at compile time, so the stringified function stays plain JS.+ */++/** One interactable node, as the agent sees it. */+export interface PreviewElement {+ /** Present and true only when the control is non-interactive right now. */+ disabled?: boolean+ /** Human-readable label (aria-label, text, placeholder, value …). */+ label: string+ /** Stable-for-this-snapshot handle: '@e1', '@e2', … */+ ref: string+ /** Explicit ARIA role, else the tag name. */+ role: string+ /** CSS selector that resolves back to this node, for re-finding it later. */+ selector: string+ /** Current value of a form control, truncated. */+ value?: string+}++/** A normalized action. `kind` is the verb; the rest is per-verb payload. */+export interface PreviewActAction {+ /** scroll distance in px. Defaults to ~90% of the viewport height. */+ amount?: number+ key?: string+ kind: 'click' | 'elements' | 'press' | 'scroll' | 'type'+ /** Cap on the returned inventory. */+ max?: number+ ref?: string+ selector?: string+ /** type: press Enter (and submit the owning form) after entering text. */+ submit?: boolean+ text?: string+ to?: 'bottom' | 'top'+}++export interface PreviewActResult {+ /** What the action landed on, for the agent's own log. */+ acted?: string+ elements?: PreviewElement[]+ error?: string+ note?: string+ success: boolean+ title?: string+ /** Live document URL after the action — a change means it navigated. */+ url?: string+}++/** 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 {+ 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 {+ const win = doc.defaultView+ const here = doc.location ? doc.location.href : ''++ const cssEscape = (value: string) =>+ typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&')++ const clamp = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)++ const labelOf = (el: Element): string => {+ const aria = el.getAttribute('aria-label')++ if (aria) {+ return clamp(aria, 80)+ }++ const labelledBy = el.getAttribute('aria-labelledby')+ const labelled = labelledBy ? doc.getElementById(labelledBy) : null+ const text = ((labelled || el).textContent || '').trim().replace(/\s+/g, ' ')++ if (text) {+ return clamp(text, 80)+ }++ for (const attr of ['placeholder', 'title', 'alt', 'name', 'value']) {+ const value = el.getAttribute(attr)++ if (value) {+ return clamp(value, 80)+ }+ }++ return ''+ }++ /** Identity-first selector, positional fallback — the caller re-finds nodes+ * with this once the refs have gone stale. */+ const selectorFor = (el: Element): string => {+ if (el.id) {+ return '#' + cssEscape(el.id)+ }++ const testId = el.getAttribute('data-testid')++ if (testId) {+ return '[data-testid="' + cssEscape(testId) + '"]'+ }++ const path: string[] = []+ let node: Element | null = el++ while (node && node !== doc.body && path.length < 8) {+ if (node.id) {+ path.unshift('#' + cssEscape(node.id))++ break+ }++ const parent: Element | null = node.parentElement+ const index = parent ? Array.prototype.indexOf.call(parent.children, node) : -1++ path.unshift(node.tagName.toLowerCase() + (index >= 0 ? ':nth-child(' + (index + 1) + ')' : ''))+ node = parent+ }++ return path.join(' > ')+ }++ const visible = (el: Element): boolean => {+ const style = win && win.getComputedStyle ? win.getComputedStyle(el) : null++ if (style && (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')) {+ 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+ }++ const valueOf = (el: Element): string => {+ const control = el as HTMLInputElement++ if (typeof control.value === 'string' && control.value) {+ return clamp(control.value, 60)+ }++ if (control.checked !== undefined && (el.tagName === 'INPUT' || el.getAttribute('role') === 'checkbox')) {+ return control.checked ? 'checked' : 'unchecked'+ }++ return ''+ }++ const collect = (max: number): PreviewElement[] => {+ const nodes: Element[] = []+ const elements: PreviewElement[] = []++ const candidates = doc.querySelectorAll(+ 'a[href], button, input:not([type="hidden"]), select, textarea, summary, label[for], ' ++ '[role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="tab"], ' ++ '[role="menuitem"], [role="switch"], [role="option"], [role="combobox"], [role="searchbox"], ' ++ '[role="textbox"], [contenteditable=""], [contenteditable="true"], [onclick], ' ++ '[tabindex]:not([tabindex="-1"])'+ )++ for (const el of candidates) {+ if (elements.length >= max || nodes.indexOf(el) !== -1 || !visible(el)) {+ continue+ }++ const tag = el.tagName.toLowerCase()+ const role = el.getAttribute('role') || (tag === 'input' ? 'input:' + ((el as HTMLInputElement).type || 'text') : tag)+ const label = labelOf(el)+ const value = valueOf(el)++ // A control with neither a label nor a value is not addressable in prose+ // — the agent could not tell it apart from its unlabelled neighbours.+ if (!label && !value) {+ continue+ }++ const entry: PreviewElement = {+ label,+ ref: '@e' + (elements.length + 1),+ role,+ selector: selectorFor(el)+ }++ if ((el as HTMLInputElement).disabled) {+ entry.disabled = true+ }++ if (value) {+ entry.value = value+ }++ nodes.push(el)+ elements.push(entry)+ }++ holder.nodes = nodes+ holder.url = here++ return elements+ }++ /** Resolve the action's target: a ref from the last snapshot, else a selector. */+ const resolve = (): { el?: Element; error?: string } => {+ const ref = (action.ref || '').trim()++ if (ref) {+ if (holder.url !== here) {+ return { error: 'The page navigated since the last snapshot, so ' + ref + ' no longer points anywhere. Call elements again.' }+ }++ const index = Number(ref.replace(/^@e/, '')) - 1+ const el = holder.nodes && holder.nodes[index]++ if (!el) {+ return { error: 'Unknown element ' + ref + '. Call elements to get current refs.' }+ }++ if (!doc.contains(el)) {+ return { error: ref + ' has been removed from the page since the last snapshot. Call elements again.' }+ }++ return { el }+ }++ const selector = (action.selector || '').trim()++ if (!selector) {+ return { error: 'Pass a ref from elements, or a CSS selector.' }+ }++ let el: Element | null = null++ try {+ el = doc.querySelector(selector)+ } catch {+ return { error: 'Not a valid CSS selector: ' + selector }+ }++ return el ? { el } : { error: 'No element matches ' + selector + '.' }+ }++ const describe = (el: Element) => {+ const label = labelOf(el)++ return el.tagName.toLowerCase() + (label ? ' "' + label + '"' : '')+ }++ const answer = (result: PreviewActResult): PreviewActResult => ({+ ...result,+ title: doc.title || '',+ url: doc.location ? doc.location.href : ''+ })++ const fail = (error: string) => answer({ error, success: false })++ /** Center of `el` in viewport coords, for pointer events that read position. */+ const pointAt = (el: Element) => {+ const rect = el.getBoundingClientRect()++ return { clientX: Math.round(rect.left + rect.width / 2), clientY: Math.round(rect.top + rect.height / 2) }+ }++ if (action.kind === 'elements') {+ const elements = collect(Math.max(1, Math.min(action.max || ACT_MAX_ELEMENTS, ACT_MAX_ELEMENTS)))++ return answer({+ elements,+ note: elements.length ? undefined : 'No interactive elements found — the page may still be loading.',+ success: true+ })+ }++ if (action.kind === 'scroll') {+ const target = action.ref || action.selector ? resolve() : {}++ if (target.error) {+ return fail(target.error)+ }++ const scroller = (target.el as HTMLElement | undefined) || null+ const page = Math.round((win ? win.innerHeight : 800) * 0.9)+ const by = action.to === 'top' ? -1e7 : action.to === 'bottom' ? 1e7 : (action.amount ?? page)++ if (scroller) {+ scroller.scrollBy({ behavior: 'auto', top: by })+ } else if (win) {+ win.scrollBy({ behavior: 'auto', top: by })+ }++ return answer({ acted: scroller ? 'scrolled ' + describe(scroller) : 'scrolled the page', success: true })+ }++ const target = resolve()++ if (target.error || !target.el) {+ return fail(target.error || 'No target.')+ }++ const el = target.el as HTMLElement++ if ((el as HTMLInputElement).disabled) {+ return fail(describe(el) + ' is disabled.')+ }++ if (el.scrollIntoView) {+ el.scrollIntoView({ block: 'center', inline: 'nearest' })+ }++ if (action.kind === 'click') {+ const init = { bubbles: true, cancelable: true, ...pointAt(el) }++ // Frameworks bind to the pointer/mouse pair as often as to click itself, so+ // replay the whole sequence; el.click() then runs the native activation+ // (following a link, toggling a checkbox, submitting a form) that a bare+ // synthetic MouseEvent would leave to chance.+ if (typeof PointerEvent === 'function') {+ el.dispatchEvent(new PointerEvent('pointerdown', init))+ el.dispatchEvent(new PointerEvent('pointerup', init))+ }++ el.dispatchEvent(new MouseEvent('mousedown', init))+ el.dispatchEvent(new MouseEvent('mouseup', init))+ el.click()++ return answer({ acted: 'clicked ' + describe(el), success: true })+ }++ if (action.kind === 'type') {+ const text = action.text ?? ''++ const editable = el.isContentEditable || (el.getAttribute('contenteditable') ?? 'false') !== 'false'++ el.focus()++ if (editable) {+ el.textContent = text+ } else if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {+ // Assign through the prototype's setter: React (and anything else that+ // tracks the DOM value) shadows `value` with its own accessor and ignores+ // an input event whose value it thinks it already wrote, so a plain+ // `el.value = …` types into a field that snaps back on the next render.+ const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set++ if (setter) {+ setter.call(el, text)+ } else {+ ;(el as HTMLInputElement).value = text+ }+ } else if (el.tagName === 'SELECT') {+ return fail(describe(el) + ' is a dropdown — click it and click the option you want.')+ } else {+ return fail(describe(el) + ' is not a text field.')+ }++ el.dispatchEvent(new Event('input', { bubbles: true }))+ el.dispatchEvent(new Event('change', { bubbles: true }))++ if (action.submit) {+ const enter = { bubbles: true, cancelable: true, code: 'Enter', key: 'Enter' }++ el.dispatchEvent(new KeyboardEvent('keydown', enter))+ el.dispatchEvent(new KeyboardEvent('keyup', enter))++ const form = (el as HTMLInputElement).form++ if (form) {+ if (form.requestSubmit) {+ form.requestSubmit()+ } else {+ form.submit()+ }+ }+ }++ return answer({ acted: 'typed into ' + describe(el) + (action.submit ? ' and submitted' : ''), success: true })+ }++ if (action.kind === 'press') {+ const key = action.key || ''++ if (!key) {+ return fail('Pass the key to press, e.g. "Enter" or "Escape".')+ }++ const init = { bubbles: true, cancelable: true, code: key.length === 1 ? 'Key' + key.toUpperCase() : key, key }++ el.focus()+ el.dispatchEvent(new KeyboardEvent('keydown', init))+ el.dispatchEvent(new KeyboardEvent('keyup', init))++ return answer({ acted: 'pressed ' + key + ' on ' + describe(el), success: true })+ }++ return fail('Unknown action: ' + String(action.kind))+}diff --git a/run_agent.py b/run_agent.pyindex a54bc9cf8f9..d3588f8f480 100644--- a/run_agent.py+++ b/run_agent.py@@ -470,6 +470,7 @@ class AIAgent:clarify_callback: callable = None,read_terminal_callback: callable = None,read_preview_callback: callable = None,+ drive_preview_callback: callable = None,read_window_below_callback: callable = None,setup_mcp_callback: callable = None,tour_callback: callable = None,@@ -560,6 +561,7 @@ class AIAgent:clarify_callback=clarify_callback,read_terminal_callback=read_terminal_callback,read_preview_callback=read_preview_callback,+ drive_preview_callback=drive_preview_callback,read_window_below_callback=read_window_below_callback,setup_mcp_callback=setup_mcp_callback,tour_callback=tour_callback,diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex a72da553be4..4688e125b6f 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -2421,6 +2421,8 @@ class TestAgentRuntimePostHookOwnershipSync:("clarify", {"question": "Continue?"}),("read_terminal", {}),("read_preview", {}),+ ("drive_preview", {"action": "elements"}),+ ("annotate_preview", {"action": "clear"}),("read_window_below", {}),("setup_mcp", {"server": "linear", "action": "install"}),("tour", {"action": "stop"}),@@ -2467,6 +2469,14 @@ class TestAgentRuntimePostHookOwnershipSync:"tools.read_preview_tool.read_preview_tool",lambda **kwargs: '{"ok":true}',)+ monkeypatch.setattr(+ "tools.drive_preview_tool.drive_preview_tool",+ lambda **kwargs: '{"ok":true}',+ )+ monkeypatch.setattr(+ "tools.annotate_preview_tool.annotate_preview_tool",+ lambda **kwargs: '{"ok":true}',+ )monkeypatch.setattr("tools.read_window_tool.read_window_below_tool",lambda **kwargs: '{"ok":true}',diff --git a/tests/tools/test_annotate_preview_tool.py b/tests/tools/test_annotate_preview_tool.pynew file mode 100644index 00000000000..bb6621a1c86--- /dev/null+++ b/tests/tools/test_annotate_preview_tool.py@@ -0,0 +1,88 @@+"""Tests for the GUI-surface ``annotate_preview`` tool."""++import json++import pytest++from tools import annotate_preview_tool as an+from tools.registry import registry+++def test_lives_in_the_gui_surface_toolset(monkeypatch):+ """Scoped by toolset, not by the backend's env — same as its siblings."""+ monkeypatch.delenv("HERMES_DESKTOP", raising=False)+ entry = registry.get_entry("annotate_preview")++ assert entry is not None+ assert entry.toolset == "desktop_ui"+ assert entry.check_fn is None+++def test_requires_callback():+ result = json.loads(an.annotate_preview_tool(ref="@e1", callback=None))+ assert "desktop" in result["error"]+++def test_rejects_an_unknown_action():+ result = json.loads(an.annotate_preview_tool(action="scribble", callback=lambda _p: "{}"))+ assert "action must be one of" in result["error"]++[email protected]("verb", ["add", "remove"])+def test_marking_one_thing_needs_a_target(verb):+ """A mark with nothing to attach to is a mistake worth naming early."""+ result = json.loads(an.annotate_preview_tool(action=verb, callback=lambda _p: "{}"))+ assert "ref" in result["error"]+++def test_speaks_the_renderer_s_verbs():+ """The overlay knows pin/unpin; the model gets words it can guess at."""+ sent = []++ def cb(payload):+ sent.append(payload)+ return json.dumps({"acted": "pinned Buy now", "success": True})++ an.annotate_preview_tool(action="add", ref="@e4", label="cheapest", callback=cb)+ an.annotate_preview_tool(action="remove", ref="@e4", callback=cb)++ assert sent[0] == {"action": "pin", "ref": "@e4", "text": "cheapest"}+ assert sent[1] == {"action": "unpin", "ref": "@e4"}+++def test_clear_sends_no_target_so_the_overlay_drops_them_all():+ """`clear` IS an untargeted unpin — a ref left on it would take down one."""+ sent = []++ def cb(payload):+ sent.append(payload)+ return json.dumps({"acted": "cleared every pin", "success": True})++ an.annotate_preview_tool(action="clear", ref="@e4", selector="a", callback=cb)++ assert sent == [{"action": "unpin"}]+++def test_defaults_to_adding():+ sent = []++ def cb(payload):+ sent.append(payload)+ return json.dumps({"success": True})++ an.annotate_preview_tool(ref="@e2", callback=cb)++ assert sent[0]["action"] == "pin"+++def test_passes_the_renderer_s_answer_straight_through():+ out = json.loads(+ an.annotate_preview_tool(ref="@e1", callback=lambda _p: json.dumps({"acted": "pinned Save", "success": True}))+ )++ assert out == {"acted": "pinned Save", "success": True}+++def test_reports_a_silent_bridge():+ result = json.loads(an.annotate_preview_tool(ref="@e1", callback=lambda _p: ""))+ assert "open_preview" in result["error"]diff --git a/tests/tools/test_drive_preview_tool.py b/tests/tools/test_drive_preview_tool.pynew file mode 100644index 00000000000..e7c0a06db3d--- /dev/null+++ b/tests/tools/test_drive_preview_tool.py@@ -0,0 +1,117 @@+"""Tests for the GUI-surface ``drive_preview`` tool."""++import json++from tools import drive_preview_tool as ap+from tools.registry import registry+++def test_lives_in_the_gui_surface_toolset(monkeypatch):+ """Mirrors read_preview: scoped by toolset, not by the backend's env."""+ monkeypatch.delenv("HERMES_DESKTOP", raising=False)+ entry = registry.get_entry("drive_preview")++ assert entry is not None+ assert entry.toolset == "desktop_ui"+ assert entry.check_fn is None+++def test_requires_callback():+ """Outside the desktop GUI there is no bridge — a clear error, no crash."""+ result = json.loads(ap.drive_preview_tool(action="elements", callback=None))+ assert "desktop" in result["error"]+++def test_rejects_an_unknown_action():+ result = json.loads(ap.drive_preview_tool(action="teleport", callback=lambda _p: "{}"))+ assert "action must be one of" in result["error"]+++def test_interaction_verbs_need_a_target():+ """A click with nowhere to land is a mistake worth naming before the bridge."""+ for verb in ("click", "type", "press"):+ result = json.loads(ap.drive_preview_tool(action=verb, text="x", key="Enter", callback=lambda _p: "{}"))+ assert "ref" in result["error"], verb+++def test_type_needs_text_and_press_needs_a_key():+ calls = []++ def cb(payload):+ calls.append(payload)+ return json.dumps({"success": True})++ assert "text" in json.loads(ap.drive_preview_tool(action="type", ref="@e1", callback=cb))["error"]+ assert "key" in json.loads(ap.drive_preview_tool(action="press", ref="@e1", callback=cb))["error"]+ assert calls == []+++def test_typing_an_empty_string_is_allowed():+ """Clearing a field is a real intent — only a missing `text` is an error."""+ seen = {}+ ap.drive_preview_tool(action="type", ref="@e1", text="", callback=lambda p: seen.update(p) or "{}")++ assert seen["text"] == ""+++def test_scroll_needs_no_target_and_validates_its_destination():+ seen = {}++ def cb(payload):+ seen.clear()+ seen.update(payload)+ return json.dumps({"success": True})++ ap.drive_preview_tool(action="scroll", callback=cb)+ assert seen == {"action": "scroll"}++ result = json.loads(ap.drive_preview_tool(action="scroll", to="sideways", callback=cb))+ assert "to must be one of" in result["error"]+++def test_payload_forwards_only_what_was_given():+ seen = {}+ ap.drive_preview_tool(+ action="type",+ ref="@e5",+ text="hunter2",+ submit=True,+ callback=lambda p: seen.update(p) or json.dumps({"success": True}),+ )++ assert seen == {"action": "type", "ref": "@e5", "text": "hunter2", "submit": True}+++def test_numeric_arguments_are_validated():+ result = json.loads(ap.drive_preview_tool(action="scroll", amount="lots", callback=lambda _p: "{}"))+ assert "integers" in result["error"]+++def test_empty_answer_means_nothing_open():+ result = json.loads(ap.drive_preview_tool(action="elements", callback=lambda _p: ""))+ assert "open_preview" in result["error"]+++def test_passes_the_renderer_answer_through():+ payload = {+ "success": True,+ "acted": 'clicked button "Sign in"',+ "url": "https://example.com/app",+ "elements": [{"ref": "@e1", "role": "button", "label": "Log out", "selector": "#out"}],+ }+ result = json.loads(ap.drive_preview_tool(action="click", ref="@e2", callback=lambda _p: json.dumps(payload)))++ assert result == payload+++def test_wraps_non_json_text():+ result = json.loads(ap.drive_preview_tool(action="elements", callback=lambda _p: "plain words"))+ assert result == {"text": "plain words"}+++def test_callback_failure_is_reported():+ def _boom(_payload):+ raise RuntimeError("renderer went away")++ result = json.loads(ap.drive_preview_tool(action="elements", callback=_boom))+ assert "renderer went away" in result["error"]diff --git a/tests/tui_gateway/test_gui_surface_toolsets.py b/tests/tui_gateway/test_gui_surface_toolsets.pyindex ceebe004a3f..6942a67f3df 100644--- a/tests/tui_gateway/test_gui_surface_toolsets.py+++ b/tests/tui_gateway/test_gui_surface_toolsets.py@@ -18,7 +18,9 @@ import tui_gateway.server as serverfrom toolsets import TOOLSETS, resolve_toolsetGUI_TOOLS = {+ "annotate_preview","close_preview",+ "drive_preview","close_terminal","focus_pane","open_preview",diff --git a/tools/annotate_preview_tool.py b/tools/annotate_preview_tool.pynew file mode 100644index 00000000000..59919394e30--- /dev/null+++ b/tools/annotate_preview_tool.py@@ -0,0 +1,151 @@+#!/usr/bin/env python3+"""Leave a mark on the page in the Hermes desktop GUI's in-app browser.++``drive_preview`` already draws every move it makes — the field it can reach,+a box round its target, the cursor going there — but those are transients:+each one stands for a single action and retires itself. That is right for+narrating a click and no use at all for holding a finding on screen.++This is the deliberate one. An annotation outlines an element — or, with+``hold``, the entire visible field at once — and stays until the agent takes it+down, so it can show the user what it found, flag the fields+it is about to fill, or keep its place while it works elsewhere on the page.+Named for TouchDesigner's Annotate — the labelled box you drop around part of a+network to call it out.++Annotations are bound to elements, not coordinates: they ride scrolls and+reflows, and they go when their element does, so a navigation clears them+without the agent having to.++Rides the same ``preview.act`` bridge as ``drive_preview`` rather than opening+a second channel — the renderer already resolves ``@e`` refs and owns the+overlay, so this is one more verb on a wire that exists.++Lives in the ``desktop_ui`` toolset, which the GUI gateway enables only for+desktop-sourced sessions.+"""++import json+from typing import Callable, Optional++from tools.registry import registry, tool_error++ACTIONS = ("add", "hold", "remove", "clear")++# Verbs the renderer knows, keyed by ours. `clear` is `unpin` with nothing to+# aim at, which the overlay reads as "all of them".+WIRE = {"add": "pin", "hold": "hold", "remove": "unpin", "clear": "unpin"}+++def annotate_preview_tool(+ action: str = "add",+ ref: Optional[str] = None,+ selector: Optional[str] = None,+ label: Optional[str] = None,+ callback: Optional[Callable] = None,+) -> str:+ """Put one annotation up, take one down, or clear them all."""+ if callback is None:+ return tool_error("annotate_preview is only available in the Hermes desktop app.")++ verb = (action or "add").strip().lower()+ if verb not in ACTIONS:+ return tool_error(f"action must be one of: {', '.join(ACTIONS)}.")++ if verb in ("add", "remove") and not (ref or selector):+ return tool_error(+ f"{verb} needs a ref from drive_preview action='elements' "+ "(e.g. '@e5') or a CSS selector."+ )++ payload = {+ name: val+ for name, val in (+ ("action", WIRE[verb]),+ ("ref", None if verb in ("clear", "hold") else ref),+ ("selector", None if verb in ("clear", "hold") else selector),+ ("text", label),+ )+ if val is not None+ }++ try:+ raw = callback(payload)+ except Exception as exc:+ return tool_error(f"Failed to annotate the in-app browser: {exc}")++ if not raw:+ return tool_error(+ "The annotation timed out, or no GUI window answered. "+ "Open a page with open_preview first."+ )++ try:+ return json.dumps(json.loads(raw), ensure_ascii=False)+ except (TypeError, ValueError):+ return json.dumps({"text": str(raw)}, ensure_ascii=False)+++ANNOTATE_PREVIEW_SCHEMA = {+ "name": "annotate_preview",+ "description": (+ "Draw a lasting mark on the page open in the in-app browser / preview "+ "pane of the Hermes desktop GUI. Everything drive_preview draws as it "+ "works fades on its own; an annotation STAYS until you remove it, so "+ "this is how you point at something. Use it to show the user what you "+ "found ('here are the three cheapest'), flag what you are about to "+ "change before you change it, or keep your place while you work "+ "elsewhere on the page. Address elements by the same '@e5' refs "+ "drive_preview action='elements' hands back. action='add' outlines an "+ "element and gives it an optional short label; 'hold' freezes the WHOLE "+ "visible field at once — every element the page offers, outlined and "+ "named — which is the "+ "picture drive_preview flashes as it works, made to stay; 'remove' "+ "takes one down; 'clear' takes them all down. Annotations follow their element "+ "as the page scrolls and disappear if it does, so a navigation clears "+ "them for you. Keep labels to a word or two — they are drawn on the "+ "page, not read aloud."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": list(ACTIONS),+ "description": (+ "'add' marks one element, 'hold' freezes the whole visible "+ "field, 'remove' takes one down, 'clear' takes them all "+ "down. Defaults to 'add'."+ ),+ },+ "ref": {+ "type": "string",+ "description": "Element reference from drive_preview action='elements' (e.g. '@e5').",+ },+ "selector": {+ "type": "string",+ "description": "CSS selector, as a fallback when no ref fits. Prefer ref.",+ },+ "label": {+ "type": "string",+ "description": "Short caption drawn on the mark, e.g. 'cheapest'. Optional.",+ },+ },+ "required": [],+ },+}+++registry.register(+ name="annotate_preview",+ toolset="desktop_ui",+ schema=ANNOTATE_PREVIEW_SCHEMA,+ handler=lambda args, **kw: annotate_preview_tool(+ action=args.get("action", "add"),+ ref=args.get("ref"),+ selector=args.get("selector"),+ label=args.get("label"),+ callback=kw.get("callback"),+ ),+ emoji="🔖",+)diff --git a/tools/drive_preview_tool.py b/tools/drive_preview_tool.pynew file mode 100644index 00000000000..7bdb1207a50--- /dev/null+++ b/tools/drive_preview_tool.py@@ -0,0 +1,211 @@+#!/usr/bin/env python3+"""Interact with the in-app browser / preview pane in the Hermes desktop GUI.++``open_preview`` shows a page and ``read_preview`` reads it; this tool is the+third leg — clicking, typing, scrolling, and history — so the agent can drive+the same page the user is looking at instead of narrating from the outside.++Elements are addressed by ``@e1``-style refs from ``action="elements"``, the+same shape the ``browser_*`` tools use, so what the model knows about one+transfers to the other. Refs are only valid until the page navigates; the+renderer says so rather than clicking whatever now sits at that index.++Round-trips through the gateway's blocking-prompt bridge like ``read_preview``:+tui_gateway emits ``preview.act.request``, the renderer injects the interaction+engine into the pane's webview and answers ``preview.act.respond`` with the+outcome plus a fresh inventory. This module is just schema + a thin dispatcher+over the platform-injected callback.++Lives in the ``desktop_ui`` toolset, which the GUI gateway enables only for+desktop-sourced sessions.+"""++import json+from typing import Callable, Optional++from tools.registry import registry, tool_error++ACTIONS = (+ "elements",+ "click",+ "hover",+ "type",+ "scroll",+ "press",+ "strobe",+ "back",+ "forward",+ "reload",+)+SCROLL_TO = ("top", "bottom")++# Verbs that need something to act on — a ref from the last inventory, or a+# raw CSS selector. `scroll` is deliberately absent: bare, it scrolls the page.+NEEDS_TARGET = ("click", "hover", "type", "press")+++def drive_preview_tool(+ action: str = "",+ ref: Optional[str] = None,+ selector: Optional[str] = None,+ text: Optional[str] = None,+ key: Optional[str] = None,+ submit: Optional[bool] = None,+ amount: Optional[int] = None,+ to: Optional[str] = None,+ limit: Optional[int] = None,+ callback: Optional[Callable] = None,+) -> str:+ """Dispatch one interaction to the desktop renderer and return its outcome."""+ if callback is None:+ return tool_error("drive_preview is only available in the Hermes desktop app.")++ verb = (action or "").strip().lower()+ if verb not in ACTIONS:+ return tool_error(f"action must be one of: {', '.join(ACTIONS)}.")++ if verb in NEEDS_TARGET and not (ref or selector):+ return tool_error(+ f"{verb} needs a ref from action='elements' (e.g. '@e5') or a CSS selector."+ )++ if verb == "type" and text is None:+ return tool_error("type needs the text to enter.")++ if verb == "press" and not key:+ return tool_error("press needs a key, e.g. 'Enter' or 'Escape'.")++ if to is not None and to not in SCROLL_TO:+ return tool_error(f"to must be one of: {', '.join(SCROLL_TO)}.")++ try:+ payload = {+ name: val+ for name, val in (+ ("action", verb),+ ("ref", ref),+ ("selector", selector),+ ("text", text),+ ("key", key),+ ("submit", submit),+ ("to", to),+ ("amount", None if amount is None else int(amount)),+ ("max", None if limit is None else int(limit)),+ )+ if val is not None+ }+ except (TypeError, ValueError):+ return tool_error("amount and max must be integers.")++ try:+ raw = callback(payload)+ except Exception as exc:+ return tool_error(f"Failed to act on the in-app browser: {exc}")++ if not raw:+ return tool_error(+ "The action timed out, or no GUI window answered. "+ "Open a page with open_preview first."+ )++ # The renderer answers with a JSON object; pass it through, else wrap it.+ try:+ return json.dumps(json.loads(raw), ensure_ascii=False)+ except (TypeError, ValueError):+ return json.dumps({"text": str(raw)}, ensure_ascii=False)+++ACT_PREVIEW_SCHEMA = {+ "name": "drive_preview",+ "description": (+ "Interact with the page open in the in-app browser / preview pane of "+ "the Hermes desktop GUI — the pane open_preview opens beside this "+ "chat. This is how you USE a web app the user is looking at: log in, "+ "fill a form, click through a flow, page a long document. ALWAYS call "+ "action='elements' first to get the current inventory of clickable and "+ "typable things — each carries a ref like '@e5' plus its role, label, "+ "and value — then act with that ref instead of guessing a selector. "+ "Every action answers with a refreshed inventory and the live url/"+ "title, so a click that navigated is visible immediately and you can "+ "chain the next step without re-reading. Refs are invalidated by a "+ "navigation; when told they are stale, call elements again. The mouse "+ "and keyboard are real: the pointer travels to its target and the page "+ "sees genuine input, so hover menus open and hover-only controls work. "+ "Actions: 'elements' (inventory), 'click', 'hover' (move the pointer "+ "onto something and leave it there — use it to open a dropdown or "+ "reveal a tooltip before clicking inside it), 'type' (set a field's "+ "text; submit=true also presses Enter and submits the form), 'scroll' "+ "(the page, or a ref'd scrollable), 'press' (a named key), 'strobe' "+ "(touch nothing — just rattle the highlight through the page again; "+ "'elements' already does this once, so reach for it only when asked to "+ "flick, flash, or bounce around the page some more, and note one call "+ "runs a whole multi-second burst, so never loop it per element), and "+ "'back'/'forward'/'reload' for history. The pane draws every move as "+ "it happens so the user can follow along; those marks fade on their "+ "own, and annotate_preview is how you leave one up on purpose. Use "+ "read_preview when you only "+ "need the page's text, and the browser_* tools when the work belongs "+ "in a separate automated browser rather than the user's own pane."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": list(ACTIONS),+ "description": "What to do. Start with 'elements'.",+ },+ "ref": {+ "type": "string",+ "description": "Element reference from the last elements call (e.g. '@e5').",+ },+ "selector": {+ "type": "string",+ "description": "CSS selector, as a fallback when no ref fits. Prefer ref.",+ },+ "text": {"type": "string", "description": "For 'type': the text to enter."},+ "submit": {+ "type": "boolean",+ "description": "For 'type': press Enter and submit the owning form afterwards.",+ },+ "key": {+ "type": "string",+ "description": "For 'press': the key name, e.g. 'Enter', 'Escape', 'ArrowDown'.",+ },+ "amount": {+ "type": "integer",+ "description": "For 'scroll': pixels to scroll (negative scrolls up). Defaults to about one screen.",+ },+ "to": {+ "type": "string",+ "enum": list(SCROLL_TO),+ "description": "For 'scroll': jump to the top or bottom instead of a distance.",+ },+ "max": {+ "type": "integer",+ "description": "For 'elements': cap the inventory. Defaults to the per-call maximum.",+ },+ },+ "required": ["action"],+ },+}+++registry.register(+ name="drive_preview",+ toolset="desktop_ui",+ schema=ACT_PREVIEW_SCHEMA,+ handler=lambda args, **kw: drive_preview_tool(+ action=args.get("action", ""),+ ref=args.get("ref"),+ selector=args.get("selector"),+ text=args.get("text"),+ key=args.get("key"),+ submit=args.get("submit"),+ amount=args.get("amount"),+ to=args.get("to"),+ limit=args.get("max"),+ callback=kw.get("callback"),+ ),+ emoji="🖱️",+)diff --git a/toolsets.py b/toolsets.pyindex 7c5d032ad8c..23eacf088af 100644--- a/toolsets.py+++ b/toolsets.py@@ -276,7 +276,7 @@ TOOLSETS = {"description": "Desktop GUI affordances — in-app terminal/browser panes, pane focus, reactions (GUI sessions only)","tools": ["read_terminal", "close_terminal",- "open_preview", "close_preview", "read_preview",+ "open_preview", "close_preview", "read_preview", "drive_preview", "annotate_preview","read_window_below","focus_pane", "react_to_message","setup_mcp", "tour",diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 115fd140475..6cae7b49e04 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -1423,6 +1423,15 @@ def _(rid, params: dict) -> dict:return _respond(rid, params, "text", allow_expired=True)+@method("preview.act.respond")+def _(rid, params: dict) -> dict:+ # `text` is a JSON string with the interaction's outcome (drive_preview+ # tool) — what it acted on, the live url/title, and a refreshed element+ # inventory. allow_expired=True for the same reason as preview.read: the+ # settle-and-rescan can lose the race with the tool's bounded wait.+ return _respond(rid, params, "text", allow_expired=True)++@method("window.read.respond")def _(rid, params: dict) -> dict:# `text` is a JSON string describing the OS window underneath the Hermesdiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 6bb356201c8..e8e76e0f299 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -3548,6 +3548,7 @@ def _block("clarify.request","terminal.read.request","preview.read.request",+ "preview.act.request","window.read.request","mcp.setup.request","tour.request",@@ -6367,6 +6368,20 @@ def _agent_cbs(sid: str) -> dict:{k: v for k, v in (("start", start), ("count", count)) if v is not None},timeout=45,),+ # drive_preview tool (desktop GUI): the renderer injects the interaction+ # engine into the preview pane's webview (or drives the pane's history)+ # and answers preview.act.respond with the outcome plus a refreshed+ # element inventory. Same budget as the preview read, which it ends+ # with — a click on a slow page pays for the settle and the re-scan.+ # annotate_preview rides this same callback: it resolves a target+ # through the same engine and differs only in the verb it sends, so it+ # needs a tool of its own but not a channel of its own.+ "drive_preview_callback": lambda payload: _block(+ "preview.act.request",+ sid,+ dict(payload),+ timeout=45,+ ),# read_window_below tool (desktop GUI): the renderer asks its main# process (which owns native window enumeration) which OS window sits# directly underneath the Hermes window, and answersdiff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 721ffb91ac2..9ccfe87e256 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -8,7 +8,7 @@ description: "Authoritative reference for Hermes built-in tools, grouped by toolThis page documents Hermes' built-in tools, grouped by toolset. Availability varies by platform, credentials, and enabled toolsets.-**Quick counts (current registry):** ~84 tools — 10 browser tools (core) + 2 CDP-gated browser tools, 4 file tools, 4 Home Assistant tools, 2 terminal tools (`terminal`, `process`), 9 desktop-GUI tools (`read_terminal`, `close_terminal`, `open_preview`, `close_preview`, `read_preview`, `read_window_below`, `focus_pane`, `react_to_message`, `tour` — desktop-app sessions only), 2 web tools, 5 Feishu tools, 7 Spotify tools (registered by the bundled `spotify` plugin), 5 Yuanbao tools, 12 kanban tools (registered when the kanban dispatcher spawns the agent), 3 project tools (desktop/GUI sessions), 2 Discord tools, 3 video tools (`video_generate`, `xai_video_edit`, `xai_video_extend`), and a handful of standalone tools (`memory`, `clarify`, `delegate_task`, `execute_code`, `cronjob`, `session_search`, `skill_view`/`skill_manage`/`skills_list`, `text_to_speech`, `image_generate`, `vision_analyze`, `video_analyze`, `todo`, `computer_use`, `x_search`).+**Quick counts (current registry):** ~86 tools — 10 browser tools (core) + 2 CDP-gated browser tools, 4 file tools, 4 Home Assistant tools, 2 terminal tools (`terminal`, `process`), 11 desktop-GUI tools (`read_terminal`, `close_terminal`, `open_preview`, `close_preview`, `read_preview`, `drive_preview`, `annotate_preview`, `read_window_below`, `focus_pane`, `react_to_message`, `tour` — desktop-app sessions only), 2 web tools, 5 Feishu tools, 7 Spotify tools (registered by the bundled `spotify` plugin), 5 Yuanbao tools, 12 kanban tools (registered when the kanban dispatcher spawns the agent), 3 project tools (desktop/GUI sessions), 2 Discord tools, 3 video tools (`video_generate`, `xai_video_edit`, `xai_video_extend`), and a handful of standalone tools (`memory`, `clarify`, `delegate_task`, `execute_code`, `cronjob`, `session_search`, `skill_view`/`skill_manage`/`skills_list`, `text_to_speech`, `image_generate`, `vision_analyze`, `video_analyze`, `todo`, `computer_use`, `x_search`).:::tip MCP ToolsIn addition to built-in tools, Hermes can load tools dynamically from MCP servers. MCP tools appear with the prefix `mcp__<server>__` (e.g., `mcp__github__create_issue` for the `github` MCP server). See [MCP Integration](/user-guide/features/mcp) for configuration.@@ -199,6 +199,8 @@ messaging, and cron sessions.| `open_preview` | Open a web URL, localhost dev-server URL, or file path in the preview pane beside the chat in the Hermes desktop app. | — || `close_preview` | Close the preview pane beside the chat, or one tab inside it. Omit `url` to close the whole pane; pass a URL or file path to close that tab. | — || `read_preview` | Read what's currently shown in the preview pane of the Hermes desktop GUI — the in-app Browser's page text (URL + title + rendered text, pageable with `start`/`count`), or a file/artifact tab's identity. | — |+| `drive_preview` | Interact with the page open in the in-app browser: `elements` inventories what's clickable and typable (each with an `@e1`-style ref, role, label, and value), then `click`, `hover`, `type`, `scroll`, and `press` act on a ref, and `back`/`forward`/`reload` drive the pane's history. The pointer and keyboard are real input, so hover menus open. Every action answers with the live URL and a refreshed inventory. | — |+| `annotate_preview` | Outline an element in the in-app browser and leave the mark up until it's removed — the deliberate counterpart to the transient cues `drive_preview` draws as it works. `add` marks a ref with an optional short label, `remove` takes one down, `clear` takes them all. Marks follow their element and vanish with it, so a navigation clears them. | — || `read_window_below` | Identify the OS window directly underneath the Hermes desktop window — app name, title, bounds (metadata only, never pixels). On macOS, other apps' titles appear only when Screen Recording is already granted; the tool never prompts for it. | — || `focus_pane` | Reveal and focus a pane in the Hermes desktop app (chat, files, terminal, review, sessions). | — || `react_to_message` | React to a message with a single emoji, iMessage-tapback style. Opt-in via Settings → Appearance (`display.message_reactions`). | — |diff --git a/website/docs/reference/toolsets-reference.md b/website/docs/reference/toolsets-reference.mdindex f71c2eeb1e6..5904f1a9f71 100644--- a/website/docs/reference/toolsets-reference.md+++ b/website/docs/reference/toolsets-reference.md@@ -71,7 +71,7 @@ Or in-session:| `video_gen` | `video_generate`, `xai_video_edit`, `xai_video_extend` | Text-to-video and image-to-video via plugin-registered backends (xAI Grok-Imagine, FAL.ai Veo 3.1 / Pixverse v6 / Kling O3). Pass `image_url` to animate an image; omit it for text-to-video. `xai_video_edit` / `xai_video_extend` are provider-specific edit/extend tools, gated on xAI Imagine credentials. || `kanban` | `kanban_attach`, `kanban_attach_url`, `kanban_attachments`, `kanban_block`, `kanban_comment`, `kanban_complete`, `kanban_create`, `kanban_heartbeat`, `kanban_link`, `kanban_list`, `kanban_request_changes`, `kanban_request_review`, `kanban_show`, `kanban_unblock` | Multi-agent coordination tools. Registered for dispatcher-spawned task workers (`HERMES_KANBAN_TASK`) and for profiles that explicitly list the `kanban` toolset by name (the `all`/`*` wildcard does **not** enable it). Workers mark tasks done, request first-class review, block, heartbeat, comment, and create/link follow-up tasks; orchestrator profiles additionally get board-routing tools like list/unblock. `delegate_task` children are not Kanban run owners: their schema strips/disables this toolset and runtime guards reject direct board mutations, even if parent `HERMES_KANBAN_*` env vars are present. || `memory` | `memory` | Persistent cross-session memory management. |-| `desktop_ui` | `close_preview`, `close_terminal`, `focus_pane`, `open_preview`, `react_to_message`, `read_preview`, `read_terminal`, `read_window_below`, `tour` | Affordances that act on the Hermes desktop app itself — read/close the embedded terminal pane, open/read/close the in-app browser, identify the OS window behind the app, reveal a pane, react to a message, run a guided tour (highlight + narrate UI elements in the app or the preview pane). Enabled for sessions whose source is the desktop app, whichever backend it's connected to (local, SSH, URL, or Hermes Cloud). Never present on CLI, TUI, messaging, or cron sessions. |+| `desktop_ui` | `annotate_preview`, `close_preview`, `close_terminal`, `drive_preview`, `focus_pane`, `open_preview`, `react_to_message`, `read_preview`, `read_terminal`, `read_window_below`, `tour` | Affordances that act on the Hermes desktop app itself — read/close the embedded terminal pane, open, read, close, interact with, and annotate the in-app browser, identify the OS window behind the app, reveal a pane, react to a message, run a guided tour (highlight + narrate UI elements in the app or the preview pane). Enabled for sessions whose source is the desktop app, whichever backend it's connected to (local, SSH, URL, or Hermes Cloud). Never present on CLI, TUI, messaging, or cron sessions. || `project` | `project_create`, `project_list`, `project_switch` | Create and switch desktop [Projects](../user-guide/cli.md) (named, multi-folder workspaces). GUI / desktop sessions only. || `safe` | `image_generate`, `vision_analyze`, `web_extract`, `web_search` (via `includes`) | Read-only research + media generation. No file writes, no terminal, no code execution. || `search` | `web_search` | Web search only (without extract). |