Skip to content

The agent that grows with you

fix(composer): gate active draft requests on isActive and acknowledge SDK inserts

Binshao6b3c0de462cd
diff --git a/apps/desktop/src/app/chat/composer/focus.test.ts b/apps/desktop/src/app/chat/composer/focus.test.ts
index 26ba682b02e..4d52e9c491f 100644
--- a/apps/desktop/src/app/chat/composer/focus.test.ts
+++ b/apps/desktop/src/app/chat/composer/focus.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it } from 'vitest'
import { $hoveredTreeGroup } from '@/components/pane-shell/tree/store'
import {
+ ackComposerInsert,
blurComposerInput,
focusComposerInput,
getActiveComposer,
@@ -10,11 +11,14 @@ import {
onComposerDictationRequest,
onComposerDraftRequests,
onComposerFocusRequest,
+ onComposerInsertRequest,
onComposerModelMenuRequest,
releaseActiveComposer,
requestComposerDictation,
requestComposerFocus,
requestComposerGetDraft,
+ requestComposerInsert,
+ requestComposerInsertAcked,
requestComposerSetDraft,
requestModelMenuToggle
} from './focus'
@@ -386,11 +390,26 @@ describe('composer draft requests', () => {
markActiveComposer('main')
mountSurface('main')
const active = mountDraft('sess-live', 'on screen', true)
- mountDraft('sess-dead', 'buried', false)
+ const dead = mountDraft('sess-dead', 'buried', false)
expect(active.wrote).toBeNull()
+ expect(dead.wrote).toBeNull()
expect(await requestComposerSetDraft([], 'type here', { active: true })).toBe(true)
expect(active.wrote).toBe('type here')
+ // Without the isActive() gate the buried surface also writes (registered
+ // after active so its reply loses the race, but the write still fires).
+ expect(dead.wrote).toBeNull()
+ })
+
+ it('reads from the bus-routed composer on active access, not the first registered', async () => {
+ markActiveComposer('main')
+ mountSurface('main')
+ // Register the inactive surface FIRST — without the isActive() gate its
+ // listener answered by registration order and the wrong draft won.
+ mountDraft('sess-dead', 'buried', false)
+ mountDraft('sess-live', 'on screen', true)
+
+ expect(await requestComposerGetDraft([], { active: true })).toEqual({ text: 'on screen' })
})
it('writes only the addressed session and reports success', async () => {
@@ -415,3 +434,55 @@ describe('composer draft requests', () => {
expect(await requestComposerSetDraft(['sess-a'], ' ')).toBe(false)
})
})
+
+describe('insert acknowledgement', () => {
+ const disposer: (() => void)[] = []
+
+ afterEach(() => {
+ disposer.splice(0).forEach(off => off())
+ })
+
+ function mountInsert(target: string, seen: string[]) {
+ disposer.push(
+ onComposerInsertRequest(detail => {
+ if (detail.target === target) {
+ seen.push(detail.text)
+
+ if (detail.token !== undefined) {
+ ackComposerInsert(detail.token, true)
+ }
+ }
+ })
+ )
+ }
+
+ it('resolves true when the addressed composer claims the insert', async () => {
+ const seen: string[] = []
+
+ mountInsert('tile:sess-a', seen)
+ await expect(requestComposerInsertAcked(' snippet ', { target: 'tile:sess-a' })).resolves.toBe(true)
+ expect(seen).toEqual(['snippet'])
+ })
+
+ it('resolves false when no surface claims it', async () => {
+ await expect(requestComposerInsertAcked('hello', { target: 'tile:gone' })).resolves.toBe(false)
+ })
+
+ it('resolves false for blank text without dispatching', async () => {
+ const seen: string[] = []
+
+ mountInsert('main', seen)
+ await expect(requestComposerInsertAcked(' ')).resolves.toBe(false)
+ expect(seen).toEqual([])
+ })
+
+ it('leaves the internal fire-and-forget insert path untracked', async () => {
+ const seen: string[] = []
+
+ mountInsert('main', seen)
+ requestComposerInsert('untracked', { target: 'main' })
+ await new Promise(resolve => window.setTimeout(resolve, 5))
+
+ expect(seen).toEqual(['untracked'])
+ })
+})
diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.ts
index c5107f0e124..80ecaa70a5c 100644
--- a/apps/desktop/src/app/chat/composer/focus.ts
+++ b/apps/desktop/src/app/chat/composer/focus.ts
@@ -32,6 +32,10 @@ interface InsertDetail {
mode: ComposerInsertMode
target: ComposerTarget
text: string
+ /** Present when the caller wants an acknowledgement (plugin SDK
+ * `host.composer.insertText`); the claiming subscriber echoes it back on
+ * {@link INSERT_REPLY_EVENT}. Internal fire-and-forget inserts omit it. */
+ token?: number
}
interface InsertRefsDetail {
@@ -39,6 +43,12 @@ interface InsertRefsDetail {
target: ComposerTarget
}
+/** Reply the claiming surface sends for a tokened insert. */
+interface InsertReplyDetail {
+ ok: boolean
+ token: number
+}
+
interface AttachImagesDetail {
blobs: Blob[]
target: ComposerTarget
@@ -46,6 +56,7 @@ interface AttachImagesDetail {
const FOCUS_EVENT = 'hermes:composer-focus'
const INSERT_EVENT = 'hermes:composer-insert'
+const INSERT_REPLY_EVENT = 'hermes:composer-insert-reply'
const ATTACH_IMAGES_EVENT = 'hermes:composer-attach-images'
const INSERT_REFS_EVENT = 'hermes:composer-insert-refs'
const SUBMIT_EVENT = 'hermes:composer-submit'
@@ -282,6 +293,73 @@ export const requestComposerInsert = (
dispatch<InsertDetail>(INSERT_EVENT, { mode, target: resolve(target), text: trimmed })
}
+/** Acked insert for the plugin SDK (`host.composer.insertText`).
+ *
+ * Same trim + deferred dispatch as {@link requestComposerInsert}, plus a
+ * token the claiming surface echoes on {@link INSERT_REPLY_EVENT}. Resolves
+ * false when the text trims to nothing, when no mounted surface claims the
+ * address, or when none answers within the settle window — so a plugin gets
+ * the same fail-closed success signal as `setDraft`/`submit` instead of a
+ * silent no-op. Internal callers keep the fire-and-forget form above. */
+export const requestComposerInsertAcked = (
+ text: string,
+ { mode = 'block', target = 'active' }: { mode?: ComposerInsertMode; target?: ComposerTarget | 'active' } = {}
+): Promise<boolean> => {
+ const trimmed = text.trim()
+ const pending = insertReplies
+
+ if (!trimmed || !pending) {
+ return Promise.resolve(false)
+ }
+
+ const token = ++insertToken
+ const resolvedTarget = resolve(target)
+
+ return new Promise<boolean>(resolve => {
+ pending.set(token, resolve)
+
+ dispatch<InsertDetail>(INSERT_EVENT, { mode, target: resolvedTarget, text: trimmed, token })
+
+ // No claimant (unmounted address, input disabled, mid-teardown) must not
+ // strand the promise: settle false and drop the slot.
+ window.setTimeout(() => {
+ if (pending.get(token) === resolve) {
+ pending.delete(token)
+ resolve(false)
+ }
+ }, INSERT_REPLY_TIMEOUT_MS)
+ })
+}
+
+/** Subscriber-side ack for {@link requestComposerInsertAcked}: the surface that
+ * appended the text reports success so the plugin's promise settles. A token-less
+ * insert (the internal bus) is a no-op here. */
+export const ackComposerInsert = (token: number | undefined, ok: boolean) => {
+ if (token === undefined || typeof window === 'undefined') {
+ return
+ }
+
+ window.dispatchEvent(new CustomEvent<InsertReplyDetail>(INSERT_REPLY_EVENT, { detail: { ok, token } }))
+}
+
+const INSERT_REPLY_TIMEOUT_MS = 50
+
+let insertToken = 0
+
+const insertReplies = typeof window === 'undefined' ? null : new Map<number, (ok: boolean) => void>()
+
+if (typeof window !== 'undefined') {
+ window.addEventListener(INSERT_REPLY_EVENT, event => {
+ const reply = (event as CustomEvent<InsertReplyDetail>).detail
+ const resolve = reply && insertReplies?.get(reply.token)
+
+ if (resolve) {
+ insertReplies?.delete(reply.token)
+ resolve(reply.ok === true)
+ }
+ })
+}
+
export const onComposerFocusRequest = (handler: (detail: FocusDetail) => void) =>
subscribe<FocusDetail>(FOCUS_EVENT, handler)
@@ -454,10 +532,10 @@ export const requestComposerSetDraft = (
/** Subscribe one mounted composer to draft read/write requests. `getIds` is
* consulted per request (the surface's session identity changes as the user
* navigates); `isActive` reports whether the focus bus currently routes to
- * this composer. Requests this surface owns — it is the active target, or
- * they name one of its ids — are answered; the rest are ignored so N mounted
- * composers coexist on the bus. `read` answers with the live text; `write`
- * replaces the draft and reports success. */
+ * this composer. An `active` request is answered only by the surface the bus
+ * routes to; an id-addressed request only by a surface owning one of its ids
+ * — the rest stay ignored so N mounted composers coexist on the bus. `read`
+ * answers with the live text; `write` replaces the draft and reports success. */
export const onComposerDraftRequests = (
address: { getIds: () => string[]; isActive: () => boolean },
handlers: { read: () => null | string; write: (text: string) => boolean }
@@ -468,12 +546,28 @@ export const onComposerDraftRequests = (
const listener = (event: Event) => {
const e = event as CustomEvent<DraftRequestDetail>
- const ids = address.getIds()
- if (!e.detail || (!e.detail.active && !e.detail.ids?.some(id => ids.includes(id)))) {
+ if (!e.detail) {
return
}
+ // `active` requests belong to exactly ONE surface — the composer the focus
+ // bus routes to. Every mounted surface claiming them (the previous
+ // behavior) let listener registration order decide instead: with keep-alive
+ // tabs in the stack a buried composer answered the read, and a `set`
+ // painted onto every mounted draft.
+ if (e.detail.active) {
+ if (!address.isActive()) {
+ return
+ }
+ } else {
+ const ids = address.getIds()
+
+ if (!e.detail.ids?.some(id => ids.includes(id))) {
+ return
+ }
+ }
+
if (e.type === GET_DRAFT_EVENT) {
window.dispatchEvent(
new CustomEvent<DraftReplyDetail>(DRAFT_REPLY_EVENT, {
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
index cbafeade015..4b76081d483 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
@@ -35,6 +35,7 @@ import {
type QueueEditState
} from '../composer-utils'
import {
+ ackComposerInsert,
type ComposerInsertMode,
focusComposerInput,
getActiveComposer,
@@ -183,11 +184,11 @@ export function useComposerDraft({
)
const appendExternalText = useCallback(
- (text: string, mode: ComposerInsertMode) => {
+ (text: string, mode: ComposerInsertMode): boolean => {
const value = text.trim()
if (!value) {
- return
+ return false
}
// 'prefix' puts the value at the START of the draft — slash commands
@@ -197,13 +198,15 @@ export function useComposerDraft({
paintDraft(`${value} ${rest}`.trimEnd())
- return
+ return true
}
const base = mode === 'inline' ? draftRef.current.trimEnd() : draftRef.current
const sep = mode === 'inline' ? (base ? ' ' : '') : base && !base.endsWith('\n') ? '\n\n' : ''
paintDraft(`${base}${sep}${value}`)
+
+ return true
},
[paintDraft]
)
@@ -262,9 +265,11 @@ export function useComposerDraft({
setFocusRequestId(id => id + 1)
})
- const offInsert = onComposerInsertRequest(({ mode, target: requested, text }) => {
+ const offInsert = onComposerInsertRequest(({ mode, target: requested, text, token }) => {
if (requested === target) {
- appendExternalText(text, mode)
+ // A tokened insert came from the plugin SDK — echo whether the text
+ // actually landed, so its promise never settles on a silent no-op.
+ ackComposerInsert(token, appendExternalText(text, mode))
}
})
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
index 185e70abce6..fcc665a7a8b 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
@@ -16,6 +16,7 @@ import {
import { ComposerDirectiveActions } from '@/app/chat/composer/directive-actions'
import { COMPOSER_DROP_ACTIVE_CLASS, COMPOSER_DROP_FADE_CLASS } from '@/app/chat/composer/drop-affordance'
import {
+ ackComposerInsert,
type ComposerInsertMode,
focusComposerInput,
markActiveComposer,
@@ -188,11 +189,11 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
}, [])
const appendExternalText = useCallback(
- (text: string, mode: ComposerInsertMode) => {
+ (text: string, mode: ComposerInsertMode): boolean => {
const value = text.trim()
if (!value) {
- return
+ return false
}
rememberInitialDraft()
@@ -211,6 +212,8 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
}
setFocusRequestId(id => id + 1)
+
+ return true
},
[aui, rememberInitialDraft]
)
@@ -248,9 +251,11 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
}
})
- const offInsert = onComposerInsertRequest(({ mode, target, text }) => {
+ const offInsert = onComposerInsertRequest(({ mode, target, text, token }) => {
if (target === 'edit') {
- appendExternalText(text, mode)
+ // Tokened inserts come from the plugin SDK: acknowledge whether the
+ // text landed instead of reporting success unconditionally.
+ ackComposerInsert(token, appendExternalText(text, mode))
}
})
diff --git a/apps/desktop/src/sdk/index.test.ts b/apps/desktop/src/sdk/index.test.ts
index a264bfe3b77..bbe0cf20129 100644
--- a/apps/desktop/src/sdk/index.test.ts
+++ b/apps/desktop/src/sdk/index.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ackComposerInsert } from '@/app/chat/composer/focus'
import { createClientSessionState } from '@/lib/chat-runtime'
import { host } from '@/sdk'
import { setActiveSessionId, setAwaitingResponse, setBusy } from '@/store/session'
@@ -265,29 +266,42 @@ describe('host workspace scope', () => {
})
describe('host.composer draft facade', () => {
- const flush = () => new Promise(resolve => setTimeout(resolve, 0))
-
it('routes insertText by address: tile for a session, resolved-active for null', async () => {
const seen: { mode: string; target: string }[] = []
const off = (event: Event) => {
- const { mode, target } = (event as CustomEvent).detail
+ const { mode, target, token } = (event as CustomEvent).detail
seen.push({ mode, target })
+
+ // A mounted surface acknowledges the insert like the real composer does.
+ ackComposerInsert(token, true)
}
window.addEventListener('hermes:composer-insert', off)
- host.composer.insertText('sess-1', ' snippet ', { mode: 'inline' })
- host.composer.insertText(null, 'to active')
- await flush()
+
+ const [tileOk, activeOk] = await Promise.all([
+ host.composer.insertText('sess-1', ' snippet ', { mode: 'inline' }),
+ host.composer.insertText(null, 'to active')
+ ])
+
window.removeEventListener('hermes:composer-insert', off)
+ expect(tileOk).toBe(true)
+ expect(activeOk).toBe(true)
expect(seen).toEqual([
{ mode: 'inline', target: 'tile:sess-1' },
{ mode: 'block', target: 'main' }
])
})
+ it('reports insertText failure on blank text or when no surface answers', async () => {
+ await expect(host.composer.insertText('sess-1', ' ')).resolves.toBe(false)
+ // Nothing listens on the insert bus here → the ack settles false, never
+ // a silent success the plugin would act on.
+ await expect(host.composer.insertText(null, 'to nobody')).resolves.toBe(false)
+ })
+
it('reads the live draft through a bus reply', async () => {
const reply = (event: Event) => {
const { token } = (event as CustomEvent<{ token: number }>).detail
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 298657b5a99..2f4be7be719 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -26,7 +26,7 @@ import {
type ComposerInsertMode,
type ComposerTarget,
requestComposerGetDraft,
- requestComposerInsert,
+ requestComposerInsertAcked,
requestComposerSetDraft,
requestComposerSubmit
} from '@/app/chat/composer/focus'
@@ -1649,16 +1649,18 @@ export const host = {
/** Append text to a composer's draft through the app's own insert modes
* ('block' = paragraph at end, 'inline' = same line, 'prefix' = start —
- * the slash-command seat). Fire-and-forget like the internal bus; text
- * is trimmed by the app, empty is a no-op. */
+ * the slash-command seat). Acknowledged like `setDraft`: resolves true
+ * when a mounted surface claimed and applied the text, false when the
+ * text trims to nothing or no surface answers for the address within the
+ * bus settle window — never a silent no-op. */
insertText: (
sessionId: null | string,
text: string,
opts?: { mode?: ComposerInsertMode }
- ): void => {
+ ): Promise<boolean> => {
const { target } = resolveComposerAddress(sessionId === null ? undefined : sessionId)
- requestComposerInsert(text, { mode: opts?.mode ?? 'block', target })
+ return requestComposerInsertAcked(text, { mode: opts?.mode ?? 'block', target })
},
/** Send `text` as if the user typed it + pressed Enter, and return
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 2138553c7dd..eb62c73f77d 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -427,8 +427,10 @@ session id yet.
import { host } from '@hermes/plugin-sdk'
// Append to the active composer (modes: 'block' | 'inline' | 'prefix';
-// 'prefix' seats a slash command at the start).
-host.composer.insertText(null, 'draft note', { mode: 'inline' })
+// 'prefix' seats a slash command at the start). Acknowledged like setDraft:
+// true when a mounted surface applied the text, false when the text is blank
+// or no live surface answers for the address.
+const inserted = await host.composer.insertText(null, 'draft note', { mode: 'inline' })
// Replace a session's whole draft — '@'-ref and '/command' tokens hydrate
// into chips exactly like an official paste. False when no mounted surface