Skip to content

The agent that grows with you

fix(desktop): ack inline-preview widget intents instead of truncating or dropping them

Austin Pickett426853ab6a39
diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts
index a0192b88091..3f14220dc9f 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,10 +1,14 @@
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
collectThemeBridge,
directiveFrameHeight,
+ evaluateIntent,
frameSizeFromMessage,
- intentFromMessage,
+ INTENT_THROTTLE_MS,
+ intentAckMessage,
+ intentScript,
+ MAX_INTENT_LENGTH,
themePrelude,
withInlineChrome
} from './inline-preview-directive'
@@ -142,28 +146,135 @@ describe('frameSizeFromMessage', () => {
})
})
-describe('intentFromMessage', () => {
+describe('evaluateIntent', () => {
const msg = (over: Record<string, unknown> = {}) => ({
type: 'hermes-inline-preview-intent',
token: 'tok',
+ id: 7,
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')
+ const NOW = 100_000
+
+ it('accepts our intent with our token, trimmed, carrying the call id', () => {
+ expect(evaluateIntent(msg(), 'tok', NOW, 0)).toEqual({ id: 7, kind: 'accept', prompt: 'get-price eth' })
+ expect(evaluateIntent(msg({ prompt: ' hi ' }), 'tok', NOW, 0)).toMatchObject({ kind: 'accept', prompt: 'hi' })
+ })
+
+ it('accepts a prompt exactly at the cap untouched', () => {
+ const prompt = 'x'.repeat(MAX_INTENT_LENGTH)
+
+ expect(evaluateIntent(msg({ prompt }), 'tok', NOW, 0)).toMatchObject({ kind: 'accept', prompt })
+ })
+
+ // #118973: a sliced JSON payload reached the agent as garbage while the
+ // widget believed it sent. Over-length is an explicit rejection now.
+ it('rejects an over-length prompt instead of truncating it', () => {
+ const payload = 'FC-FLUSH ' + JSON.stringify(Array.from({ length: 30 }, (_, i) => ({ card: i, rating: 3 })))
+
+ expect(payload.length).toBeGreaterThan(MAX_INTENT_LENGTH)
+ expect(evaluateIntent(msg({ prompt: payload }), 'tok', NOW, 0)).toEqual({
+ ack: { error: 'too_long', maxLength: MAX_INTENT_LENGTH, ok: false },
+ id: 7,
+ kind: 'reject'
+ })
+ })
+
+ it('rejects a throttled intent with a retry hint instead of dropping it', () => {
+ expect(evaluateIntent(msg(), 'tok', NOW, NOW - 300)).toEqual({
+ ack: { error: 'throttled', ok: false, retryAfterMs: INTENT_THROTTLE_MS - 300 },
+ id: 7,
+ kind: 'reject'
+ })
+ expect(evaluateIntent(msg(), 'tok', NOW, NOW - INTENT_THROTTLE_MS)).toMatchObject({ kind: 'accept' })
+ })
+
+ it('rejects an empty or non-string prompt from our frame as invalid', () => {
+ expect(evaluateIntent(msg({ prompt: ' ' }), 'tok', NOW, 0)).toMatchObject({ ack: { error: 'invalid' } })
+ expect(evaluateIntent(msg({ prompt: 42 }), 'tok', NOW, 0)).toMatchObject({ ack: { error: 'invalid' } })
+ })
+
+ it('drops a non-integer id so the ack cannot be aimed with a hostile value', () => {
+ expect(evaluateIntent(msg({ id: 'x' }), 'tok', NOW, 0)).toMatchObject({ id: null, kind: 'accept' })
+ expect(evaluateIntent(msg({ id: 1.5 }), 'tok', NOW, 0)).toMatchObject({ id: null })
+ })
+
+ it('ignores wrong token, wrong type, and hostile shapes without a reply', () => {
+ expect(evaluateIntent(msg({ token: 'stolen' }), 'tok', NOW, 0)).toBeNull()
+ expect(evaluateIntent(msg({ type: 'hermes-inline-preview-size' }), 'tok', NOW, 0)).toBeNull()
+ expect(evaluateIntent(null, 'tok', NOW, 0)).toBeNull()
+ expect(evaluateIntent('str', 'tok', NOW, 0)).toBeNull()
+ })
+})
+
+describe('intentScript', () => {
+ // Run the injected script against a fake parent so the frame side of the
+ // protocol is exercised for real: what it posts and what send() resolves.
+ function mountFrame() {
+ const posted: Array<Record<string, unknown>> = []
+ const listeners: Record<string, Array<(e: unknown) => void>> = {}
+ const parent = { postMessage: (data: Record<string, unknown>) => posted.push(data) }
+ const win: { hermes?: { maxLength: number; send: (p: unknown) => Promise<unknown> } } = {}
+
+ const addEventListener = (type: string, fn: (e: unknown) => void) => {
+ ;(listeners[type] ??= []).push(fn)
+ }
+
+ const body = intentScript('tok')
+ .replace(/^<script>/, '')
+ .replace(/<\/script>$/, '')
+
+ new Function('parent', 'addEventListener', 'window', body)(parent, addEventListener, win)
+
+ const reply = (data: unknown, source: unknown = parent) => listeners.message?.forEach(fn => fn({ data, source }))
+
+ return { posted, reply, send: win.hermes!.send, win }
+ }
+
+ it('posts the full prompt, never a truncated one', () => {
+ const { posted, send } = mountFrame()
+ const long = 'y'.repeat(3200)
+
+ void send(long)
+
+ expect(posted).toHaveLength(1)
+ expect(posted[0]).toMatchObject({ prompt: long, token: 'tok', type: 'hermes-inline-preview-intent' })
})
- it('caps runaway prompts to a sentence-sized budget', () => {
- expect(intentFromMessage(msg({ prompt: 'x'.repeat(9000) }), 'tok')).toHaveLength(500)
+ it('resolves send() with the parent ack for that call', async () => {
+ const { posted, reply, send } = mountFrame()
+ const pending = send('hello')
+ const id = posted[0].id as number
+
+ reply(intentAckMessage('tok', id, { error: 'too_long', maxLength: 500, ok: false }))
+
+ await expect(pending).resolves.toEqual({ error: 'too_long', maxLength: 500, ok: false })
+ })
+
+ it('ignores acks with the wrong token or from a non-parent source', async () => {
+ vi.useFakeTimers()
+
+ try {
+ const { posted, reply, send } = mountFrame()
+ const pending = send('hello')
+ const id = posted[0].id as number
+
+ reply(intentAckMessage('stolen', id, { ok: true }))
+ reply(intentAckMessage('tok', id, { ok: true }), {})
+ vi.advanceTimersByTime(5000)
+
+ await expect(pending).resolves.toEqual({ error: 'undelivered', ok: false })
+ } finally {
+ vi.useRealTimers()
+ }
})
- 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()
+ it('resolves invalid for an empty prompt without posting, and exposes the cap', async () => {
+ const { posted, send, win } = mountFrame()
+
+ await expect(send(' ')).resolves.toEqual({ error: 'invalid', ok: false })
+ expect(posted).toHaveLength(0)
+ expect(win.hermes?.maxLength).toBe(MAX_INTENT_LENGTH)
})
})
diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx
index 60e1cf56e39..0acf6e97564 100644
--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx
+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx
@@ -38,7 +38,10 @@ import { localPreviewTarget } from '@/lib/local-preview'
* 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.
+ * gated, length-capped, throttled to human speed. Nothing is lost silently:
+ * `send()` resolves a delivery ack, and an over-length, throttled, or
+ * undeliverable intent resolves `{ ok: false, error }` instead of being
+ * truncated or dropped behind the widget's back (#118973).
*
* Non-HTML targets and remote gateways (no local file access) fall back to
* the standard preview-attachment card rather than a broken frame.
@@ -68,52 +71,111 @@ 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
+const INTENT_ACK_MESSAGE_TYPE = 'hermes-inline-preview-intent-ack'
+
+/** Prompt length cap for a widget intent — a sentence, not a payload dump.
+ * Over-length intents are REJECTED back to the widget, never truncated: a
+ * sliced JSON payload reaches the agent as garbage while the widget thinks
+ * it sent. */
+export const MAX_INTENT_LENGTH = 500
+/** One intent per frame per second; clicks are human-speed. A faster intent
+ * is rejected with `retryAfterMs`, not dropped silently. */
+export const INTENT_THROTTLE_MS = 1000
+/** How long `hermes.send()` waits for the parent's ack before resolving
+ * `timeout` (the parent acks synchronously; this only fires if it's gone). */
+const INTENT_ACK_TIMEOUT_MS = 5000
+
+export type IntentError = 'invalid' | 'too_long' | 'throttled' | 'undelivered'
+
+/** What `hermes.send()` resolves to inside the frame. `ok` means the prompt
+ * was handed to the owning composer's send path — not that the agent has
+ * answered. */
+export type IntentAck = { ok: true } | { error: IntentError; maxLength?: number; ok: false; retryAfterMs?: number }
/** 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:
+ * Posts the prompt up tagged with the mount token and a per-call id; the
+ * parent validates, throttles, routes it through the composer, and posts an
+ * ack back, so `send()` returns a Promise of an `IntentAck` — a widget can
+ * show "saved" only when it was. 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;' +
+ ';var n=0,w={};' +
+ 'addEventListener("message",function(e){var d=e.data;' +
+ 'if(e.source!==parent||!d||d.type!==' +
+ JSON.stringify(INTENT_ACK_MESSAGE_TYPE) +
+ '||d.token!==t||!w[d.id])return;' +
+ 'var r=w[d.id];delete w[d.id];r(d.ack)});' +
+ 'function send(p){if(typeof p!=="string"||!p.trim())return Promise.resolve({ok:false,error:"invalid"});' +
+ 'var id=++n;return new Promise(function(res){' +
+ 'var done=function(a){clearTimeout(k);res(a)};' +
+ 'var k=setTimeout(function(){if(w[id]){delete w[id];res({ok:false,error:"undelivered"})}},' +
+ String(INTENT_ACK_TIMEOUT_MS) +
+ ');w[id]=done;' +
'parent.postMessage({type:' +
JSON.stringify(INTENT_MESSAGE_TYPE) +
- ',token:t,prompt:p.slice(0,' +
+ ',token:t,id:id,prompt:p},"*")})}' +
+ 'window.hermes={send:send,maxLength:' +
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 {
+export type IntentDecision =
+ | { id: number | null; kind: 'accept'; prompt: string }
+ | { ack: Extract<IntentAck, { ok: false }>; id: number | null; kind: 'reject' }
+
+/** The pure intent gate. Null unless it is OUR type with OUR token — same
+ * trust boundary as size reports, because an accepted intent turns into a
+ * user message; anything else is ignored without a reply. For our own
+ * messages every outcome is explicit: accept (trimmed, never truncated) or
+ * reject with a reason the frame gets back. `lastAcceptedAt` is the time
+ * of this frame's previous accepted intent (0 for none). */
+export function evaluateIntent(
+ data: unknown,
+ token: string,
+ now: number,
+ lastAcceptedAt: number
+): IntentDecision | null {
if (typeof data !== 'object' || data === null) {
return null
}
- const message = data as { type?: unknown; token?: unknown; prompt?: unknown }
+ const message = data as { id?: unknown; prompt?: unknown; token?: unknown; type?: unknown }
- if (message.type !== INTENT_MESSAGE_TYPE || message.token !== token || typeof message.prompt !== 'string') {
+ if (message.type !== INTENT_MESSAGE_TYPE || message.token !== token) {
return null
}
- const prompt = message.prompt.trim().slice(0, MAX_INTENT_LENGTH)
+ const id = typeof message.id === 'number' && Number.isSafeInteger(message.id) ? message.id : null
+ const prompt = typeof message.prompt === 'string' ? message.prompt.trim() : ''
+
+ if (!prompt) {
+ return { ack: { error: 'invalid', ok: false }, id, kind: 'reject' }
+ }
+
+ if (prompt.length > MAX_INTENT_LENGTH) {
+ return { ack: { error: 'too_long', maxLength: MAX_INTENT_LENGTH, ok: false }, id, kind: 'reject' }
+ }
+
+ const elapsed = now - lastAcceptedAt
+
+ if (lastAcceptedAt > 0 && elapsed < INTENT_THROTTLE_MS) {
+ return { ack: { error: 'throttled', ok: false, retryAfterMs: INTENT_THROTTLE_MS - elapsed }, id, kind: 'reject' }
+ }
+
+ return { id, kind: 'accept', prompt }
+}
- return prompt || null
+/** The ack posted back into the frame for intent `id`. */
+export function intentAckMessage(token: string, id: number, ack: IntentAck) {
+ return { ack, id, token, type: INTENT_ACK_MESSAGE_TYPE }
}
/** Semantic tokens handed into the frame, resolved to concrete values from
@@ -362,18 +424,32 @@ function InlineHtmlFrame({
let lastIntentAt = 0
const onMessage = (event: MessageEvent) => {
- const intent = intentFromMessage(event.data, token)
+ const decision = evaluateIntent(event.data, token, Date.now(), lastIntentAt)
- if (intent !== null) {
- const now = Date.now()
+ if (decision !== null) {
+ let ack: IntentAck
- if (now - lastIntentAt >= INTENT_THROTTLE_MS) {
- lastIntentAt = now
+ if (decision.kind === 'reject') {
+ ack = decision.ack
+ } else {
+ lastIntentAt = Date.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' })
+ // updating IS the visible response. `false` means no visible
+ // composer surface took it; the widget is told instead of assuming.
+ ack = requestComposerSubmit(decision.prompt, { target: 'active', displayKind: 'hidden' })
+ ? { ok: true }
+ : { error: 'undelivered', ok: false }
+ }
+
+ // Reply only to the sender that proved it holds this mount's token.
+ // The ack carries status, never app data; '*' because the sandboxed
+ // frame's origin is opaque.
+ const source = event.source as Window | null
+
+ if (decision.id !== null && source) {
+ source.postMessage(intentAckMessage(token, decision.id, ack), '*')
}
return
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index c16a953331b..081bbb9c3c8 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -796,8 +796,13 @@ 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.
+Prompts are trimmed, capped at 500 chars (`window.hermes.maxLength`), and
+throttled to one per second per frame. Nothing is truncated or dropped
+silently: `send()` returns a Promise that resolves `{ ok: true }` once the
+prompt reaches the chat's composer, or `{ ok: false, error }` where `error` is
+`too_long` (with `maxLength`), `throttled` (with `retryAfterMs`), `invalid`,
+or `undelivered` (no visible composer took it). Check it before showing a
+widget as saved.
### Mount-scoped chrome (`Contribute`)