The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): widget clicks reach the agent as hidden user turns — the widget updating IS the response
Brooklyn Nicholson3ead0f8dc177
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 639f9924d38..998e5606a09 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -937,7 +937,12 @@ PLATFORM_HINTS = {"var(--muted-foreground), var(--accent), var(--border), var(--card) — ""the inherited app font, no body padding or margin, content flush ""left and filling the viewport width, no centering wrappers, decorative "- "backdrops, or page chrome. The frame auto-sizes to the content. Only "+ "backdrops, or page chrome. The frame auto-sizes to the content. "+ "Widgets can talk back: window.hermes.send(\"prompt\") — or a "+ "data-hermes-send=\"prompt\" attribute on any clickable element — sends "+ "that prompt to you as a hidden user turn (no chat bubble), so give "+ "interactive widgets buttons whose clicks mean something and answer "+ "them by updating the widget's file, not with prose. Only ""a standalone PAGE (a mockup, a poster, a game) should bring its own ""background and layout. ""When the user asks to add, enable, or authorize an MCP server (or a "diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.tsindex 8cd961b7f96..4ceefb5d3ae 100644--- a/apps/desktop/src/app/chat/composer/focus.ts+++ b/apps/desktop/src/app/chat/composer/focus.ts@@ -69,6 +69,9 @@ const cssEscape = (value: string): string => {interface SubmitDetail {target: ComposerTargettext: string+ /** `hidden` types the persisted user row so no bubble renders — the+ * off-screen path for widget intents. Omit for normal visible sends. */+ displayKind?: 'hidden'}let activeTarget: ComposerTarget = 'main'@@ -261,12 +264,16 @@ export const onComposerInsertRefsRequest = (handler: (detail: InsertRefsDetail)* the agent a task without the user round-tripping through the input. */export const requestComposerSubmit = (text: string,- { target = 'active' }: { target?: ComposerTarget | 'active' } = {}+ { target = 'active', displayKind }: { target?: ComposerTarget | 'active'; displayKind?: 'hidden' } = {}) => {const trimmed = text.trim()if (trimmed) {- dispatch<SubmitDetail>(SUBMIT_EVENT, { target: resolve(target), text: trimmed })+ dispatch<SubmitDetail>(SUBMIT_EVENT, {+ target: resolve(target),+ text: trimmed,+ ...(displayKind ? { displayKind } : {})+ })}}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.tsindex a6015fc9303..7cfa31a13e1 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts@@ -80,7 +80,7 @@ export function useComposerSubmit({// Shared send primitive: fire onSubmit, and if the gateway rejects (accepted// === false) or throws, re-load + re-stash the draft so the words survive.- const dispatchSubmit = (text: string, attachments?: ComposerAttachment[]) => {+ const dispatchSubmit = (text: string, attachments?: ComposerAttachment[], displayKind?: 'hidden') => {const submittedScope = activeQueueSessionKeyRef.currentconst submittedAttachments = attachments ?? []@@ -95,8 +95,8 @@ export function useComposerSubmit({void Promise.resolve(attachments- ? onSubmit(text, { attachments, composerScope: submittedScope })- : onSubmit(text, { composerScope: submittedScope })+ ? onSubmit(text, { attachments, composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })+ : onSubmit(text, { composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })).then(accepted => void (accepted === false ? restore() : clearSessionDraft(submittedScope))).catch(restore)@@ -110,9 +110,9 @@ export function useComposerSubmit({useEffect(() =>- onComposerSubmitRequest(({ target, text }) => {+ onComposerSubmitRequest(({ target, text, displayKind }) => {if (target === 'main' && !inputDisabled) {- dispatchSubmitRef.current(text)+ dispatchSubmitRef.current(text, undefined, displayKind)}}),[inputDisabled]diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex a4439a7122a..eb22a8d7c97 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -377,9 +377,16 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {// assistant bubble — settle any leftover (drop it when empty)// before appending, or a stale spinner gets stranded// mid-transcript above this message forever.+ //+ // Off-screen sends (displayKind 'hidden', widget intents) settle+ // leftovers but append NO bubble: an absent row can't become a+ // dead branch sibling in the runtime repository. The durable row+ // is typed hidden by the gateway, so resume stays bubble-free.messages: state.messages.some(m => m.id === optimisticId)? state.messages- : [...finalizeInterruptedMessages(state.messages, state.streamId), buildUserMessage()],+ : options?.displayKind === 'hidden'+ ? finalizeInterruptedMessages(state.messages, state.streamId)+ : [...finalizeInterruptedMessages(state.messages, state.streamId), buildUserMessage()],busy: true,awaitingResponse: true,pendingBranchGroup: null,@@ -688,6 +695,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {session_id: targetId,text,...(interrupted && { interrupted }),+ // Off-screen widget intent: the gateway types the persisted user+ // row display_kind=hidden so no client renders it as a bubble.+ ...(options?.displayKind === 'hidden' && { display_kind: 'hidden' }),// Typed into the floating HUD, so the user is looking at another app// rather than at Hermes. The gateway turns this into a per-turn hint// to read the window underneath and work in it.diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.tsindex 8c624fde191..35b783a11d0 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts@@ -663,6 +663,10 @@ export interface SubmitTextOptions {* body — model-facing scaffolding the UI must never render — so the slash* dispatcher passes the invocation (`/work fix the leak`) here. */displayText?: string+ /** `hidden` types the persisted user row (display_kind) so no bubble+ * renders anywhere — the off-screen path for widget intents. The agent+ * still receives the text as a normal user turn. */+ displayKind?: 'hidden'fromQueue?: boolean/** Runtime session id to submit into. Queue drains pass this so a* backgrounded/source session cannot be replaced by the current foregrounddiff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.tsindex be5b55566b2..e154e94237b 100644--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest'-import { directiveFrameHeight, frameSizeFromMessage, themePrelude, withInlineChrome } from './inline-preview-directive'+import {+ directiveFrameHeight,+ frameSizeFromMessage,+ intentFromMessage,+ themePrelude,+ withInlineChrome+} from './inline-preview-directive'describe('directiveFrameHeight', () => {it('returns null (auto-size) when absent or garbage', () => {@@ -93,3 +99,39 @@ describe('frameSizeFromMessage', () => {expect(frameSizeFromMessage('str', 'tok')).toBeNull()})})++describe('intentFromMessage', () => {+ const msg = (over: Record<string, unknown> = {}) => ({+ type: 'hermes-inline-preview-intent',+ token: 'tok',+ prompt: 'get-price eth',+ ...over+ })++ it('accepts our intent with our token, trimmed', () => {+ expect(intentFromMessage(msg(), 'tok')).toBe('get-price eth')+ expect(intentFromMessage(msg({ prompt: ' hi ' }), 'tok')).toBe('hi')+ })++ it('caps runaway prompts to a sentence-sized budget', () => {+ expect(intentFromMessage(msg({ prompt: 'x'.repeat(9000) }), 'tok')).toHaveLength(500)+ })++ it('rejects wrong token, wrong type, empty, and hostile shapes', () => {+ expect(intentFromMessage(msg({ token: 'stolen' }), 'tok')).toBeNull()+ expect(intentFromMessage(msg({ type: 'hermes-inline-preview-size' }), 'tok')).toBeNull()+ expect(intentFromMessage(msg({ prompt: ' ' }), 'tok')).toBeNull()+ expect(intentFromMessage(msg({ prompt: 42 }), 'tok')).toBeNull()+ expect(intentFromMessage(null, 'tok')).toBeNull()+ })+})++describe('withInlineChrome intent wiring', () => {+ it('injects hermes.send and the data-hermes-send click bridge', () => {+ const framed = withInlineChrome('<html><body><h1>w</h1></body></html>', 'tok', '')++ expect(framed).toContain('window.hermes={send:send}')+ expect(framed).toContain('data-hermes-send')+ expect(framed).toContain('hermes-inline-preview-intent')+ })+})diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsxindex 916312ef37f..b575de8f032 100644--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx@@ -1,6 +1,7 @@import { useStore } from '@nanostores/react'import { useEffect, useMemo, useState } from 'react'+import { requestComposerSubmit } from '@/app/chat/composer/focus'import { useSessionView } from '@/app/chat/session-view'import { useIsDark } from '@/components/assistant-ui/embeds/use-is-dark'import { PreviewAttachment } from '@/components/chat/preview-attachment'@@ -32,6 +33,13 @@ import { isRemoteGateway } from '@/lib/media'* app. The page's own styles override all of it, so a full page keeps its* own design.*+ * WIDGETS TALK BACK OFF-SCREEN. `window.hermes.send(prompt)` (or declarative+ * `data-hermes-send` on any clickable element) routes the prompt through the+ * composer's send path as a user turn typed `display_kind=hidden`: the agent+ * wakes and the durable row exists (context, resume, audit via the DB), but+ * no bubble renders — the widget updating is the visible response. Token-+ * gated, length-capped, throttled to human speed.+ ** Non-HTML targets and remote gateways (no local file access) fall back to* the standard preview-attachment card rather than a broken frame.*/@@ -59,6 +67,54 @@ export function directiveFrameHeight(raw: string | undefined): number | null {}const SIZE_MESSAGE_TYPE = 'hermes-inline-preview-size'+const INTENT_MESSAGE_TYPE = 'hermes-inline-preview-intent'++/** Prompt length cap for a widget intent — a sentence, not a payload dump. */+const MAX_INTENT_LENGTH = 500+/** One intent per frame per second; clicks are human-speed. */+const INTENT_THROTTLE_MS = 1000++/** The script that gives the widget its ONE voice: `hermes.send(prompt)`.+ * Posts the prompt up tagged with the mount token; the parent validates,+ * throttles, and routes it through the composer as a normal user message —+ * the widget speaks WITH the user's voice, visibly, never silently. Also+ * wires `data-hermes-send` so declarative HTML works with zero script:+ * `<button data-hermes-send="get-price eth">ETH</button>`. */+export function intentScript(token: string): string {+ return (+ '<script>(function(){var t=' ++ JSON.stringify(token) ++ ';function send(p){if(typeof p!=="string"||!p.trim())return false;' ++ 'parent.postMessage({type:' ++ JSON.stringify(INTENT_MESSAGE_TYPE) ++ ',token:t,prompt:p.slice(0,' ++ String(MAX_INTENT_LENGTH) ++ ')},"*");return true}' ++ 'window.hermes={send:send};' ++ 'addEventListener("click",function(e){var el=e.target&&e.target.closest?' ++ 'e.target.closest("[data-hermes-send]"):null;' ++ 'if(el)send(el.getAttribute("data-hermes-send")||"")},true)})()</script>'+ )+}++/** Parse a widget intent. Null unless it is OUR type with OUR token and a+ * non-empty string prompt — same trust boundary as size reports, because+ * this one turns into a user message. Trimmed and length-capped. */+export function intentFromMessage(data: unknown, token: string): string | null {+ if (typeof data !== 'object' || data === null) {+ return null+ }++ const message = data as { type?: unknown; token?: unknown; prompt?: unknown }++ if (message.type !== INTENT_MESSAGE_TYPE || message.token !== token || typeof message.prompt !== 'string') {+ return null+ }++ const prompt = message.prompt.trim().slice(0, MAX_INTENT_LENGTH)++ return prompt || null+}/** Semantic tokens handed into the frame, resolved to concrete values from* the LIVE theme. Friendly names, not internal ones — this is the contract@@ -139,10 +195,10 @@ export function measurementScript(token: string): string {}/** Assemble the srcdoc: theme prelude first (so the page's own styles win),- * measuring script before `</body>` when present so it runs after the- * page's own markup, appended otherwise. */+ * then the measuring + intent scripts before `</body>` when present so they+ * run after the page's own markup, appended otherwise. */export function withInlineChrome(doc: string, token: string, prelude: string): string {- const script = measurementScript(token)+ const script = measurementScript(token) + intentScript(token)const bodyClose = /<\/body\s*>/i.exec(doc)const framed = bodyClose ? doc.slice(0, bodyClose.index) + script + doc.slice(bodyClose.index) : doc + script@@ -261,7 +317,28 @@ function InlineHtmlFrame({}, [path, streaming])useEffect(() => {+ // Human-speed gate on widget intents. A closure local, not state: it's+ // a rate limiter read inside the handler, never rendered.+ let lastIntentAt = 0+const onMessage = (event: MessageEvent) => {+ const intent = intentFromMessage(event.data, token)++ if (intent !== null) {+ const now = Date.now()++ if (now - lastIntentAt >= INTENT_THROTTLE_MS) {+ lastIntentAt = now+ // Off-screen: the prompt reaches the agent as a normal user turn+ // through the composer's own send path (steer/queue rules apply),+ // but the row is typed hidden — no bubble, no UI space. The widget+ // updating IS the visible response.+ requestComposerSubmit(intent, { target: 'active', displayKind: 'hidden' })+ }++ return+ }+const next = frameSizeFromMessage(event.data, token)if (next === null) {diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.pyindex c4d5a6ae7c7..2cb60cf2038 100644--- a/tui_gateway/compute_host.py+++ b/tui_gateway/compute_host.py@@ -484,7 +484,13 @@ class ComputeHost:except Exception:passtext = frame.get("text") if "text" in frame else frame.get("prompt", "")- server._run_prompt_submit(request_id, sid, session, text)+ server._run_prompt_submit(+ request_id,+ sid,+ session,+ text,+ display_kind=frame.get("display_kind") or None,+ )run_thread = session.get("_run_thread")if run_thread is not None and hasattr(run_thread, "join"):run_thread.join()diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 745a855e3d6..bb8f329db3c 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -272,6 +272,10 @@ def _(rid, params: dict) -> dict:sid = params.get("session_id", "")raw_text = params.get("text", "")text = sanitize_user_prompt_text(raw_text) if isinstance(raw_text, str) else raw_text+ # Off-screen sends (widget intents): type the persisted user row so no+ # client renders it as a bubble. Whitelisted to "hidden" — display_kind+ # is a DB-only sidecar and this RPC must not mint arbitrary kinds.+ display_kind = "hidden" if params.get("display_kind") == "hidden" else None# Typed bare stop phrase while backend voice mode is active ends the# voice chat instead of sending "stop" to the agent — the typed twin of# the spoken stop phrase (PR #73106), applied at the ONE server-side@@ -707,7 +711,9 @@ def _(rid, params: dict) -> dict:_start_inflight_turn(session, text)if turn_isolation:- isolated_response = _submit_prompt_to_compute_host(rid, sid, session, text)+ isolated_response = _submit_prompt_to_compute_host(+ rid, sid, session, text, display_kind=display_kind+ )if not isolated_response.get("error"):if survivor_user_row_ids is not None:# The truncation already happened inline above (memory + DB),@@ -793,7 +799,7 @@ def _(rid, params: dict) -> dict:},)return- _run_prompt_submit(rid, sid, session, text)+ _run_prompt_submit(rid, sid, session, text, display_kind=display_kind)run_thread = threading.Thread(target=run_after_agent_ready, daemon=True)# Keep a handle so session.interrupt can tell a live turn from a stuckdiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex bd3c38ffde2..70213607c70 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1760,6 +1760,7 @@ def _compute_host_turn_frame(text: Any,image_paths: list[str] | None = None,queued_prompt_generation: int | None = None,+ display_kind: str | None = None,) -> dict:with session["history_lock"]:history = list(session.get("history", []))@@ -1775,6 +1776,7 @@ def _compute_host_turn_frame("request_id": rid,"session_key": session.get("session_key") or sid,"text": text,+ **({"display_kind": display_kind} if display_kind else {}),"history": history,"history_version": history_version,"cols": int(session.get("cols", 80) or 80),@@ -1863,6 +1865,7 @@ def _submit_prompt_to_compute_host(text: Any,image_paths: list[str] | None = None,queued_prompt_generation: int | None = None,+ display_kind: str | None = None,) -> dict:cfg = _load_dashboard_process_isolation_config()frame = _compute_host_turn_frame(@@ -1872,6 +1875,7 @@ def _submit_prompt_to_compute_host(text,image_paths=image_paths,queued_prompt_generation=queued_prompt_generation,+ display_kind=display_kind,)def _complete(done: dict) -> None:diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex ce670e1bb07..3c86a073432 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -394,6 +394,16 @@ its own design. Non-HTML targets and remote gateways fall back to theclassic preview card. Tell the agent about your directive in a skill (that'show it learns to emit it).+Previewed widgets can also **talk back**. Inside the frame,+`window.hermes.send('get-price eth')` (or a declarative+`<button data-hermes-send="get-price eth">` — no script needed) hands that+prompt to the agent as a user turn, off-screen: no bubble takes up the+transcript, the widget updating is the visible response. The turn is still+real — it wakes the agent, rides the composer's steer/queue rules, and+persists (typed `hidden`) so resume and the session DB keep the full record.+Prompts are trimmed, capped at 500 chars, and throttled to one per second+per frame.+### Mount-scoped chrome (`Contribute`)`ctx.register` is for **permanent** contributions. When chrome should live and