The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): expose composer draft API to plugins (host.composer)
Binshaoa874cee62544
diff --git a/apps/desktop/src/app/chat/composer/focus.test.ts b/apps/desktop/src/app/chat/composer/focus.test.tsindex dbb7292ba8f..26ba682b02e 100644--- a/apps/desktop/src/app/chat/composer/focus.test.ts+++ b/apps/desktop/src/app/chat/composer/focus.test.ts@@ -8,11 +8,14 @@ import {getActiveComposer,markActiveComposer,onComposerDictationRequest,+ onComposerDraftRequests,onComposerFocusRequest,onComposerModelMenuRequest,releaseActiveComposer,requestComposerDictation,requestComposerFocus,+ requestComposerGetDraft,+ requestComposerSetDraft,requestModelMenuToggle} from './focus'import { RICH_INPUT_SLOT } from './rich-editor'@@ -335,3 +338,80 @@ describe('requestComposerDictation', () => {expect(targets).toEqual(['tile:front'])})})++/**+ * The plugin SDK's draft read/write bus (`host.composer`). A mounted composer+ * answers for its own sessions and the active composer answers `active`+ * requests; unaddressed surfaces must stay silent so a plugin addressing one+ * session never reads or writes another's draft.+ */+describe('composer draft requests', () => {+ const disposer: (() => void)[] = []++ afterEach(() => {+ disposer.splice(0).forEach(off => off())+ })++ function mountDraft(id: string, text: string, active = false) {+ const state = { text, wrote: null as null | string }+ disposer.push(+ onComposerDraftRequests(+ { getIds: () => [id], isActive: () => active },+ {+ read: () => state.text,+ write: next => {+ if (next.trim() === '') {+ return false+ }++ state.wrote = next++ return true+ }+ }+ )+ )++ return state+ }++ it('reads the draft of the addressed session', async () => {+ mountDraft('sess-a', 'draft A')+ mountDraft('sess-b', 'draft B')++ expect(await requestComposerGetDraft(['sess-b'])).toEqual({ text: 'draft B' })+ })++ it('answers an active request only from the composer the bus routes to', async () => {+ markActiveComposer('main')+ mountSurface('main')+ const active = mountDraft('sess-live', 'on screen', true)+ mountDraft('sess-dead', 'buried', false)++ expect(active.wrote).toBeNull()+ expect(await requestComposerSetDraft([], 'type here', { active: true })).toBe(true)+ expect(active.wrote).toBe('type here')+ })++ it('writes only the addressed session and reports success', async () => {+ const a = mountDraft('sess-a', 'x')+ const b = mountDraft('sess-b', 'y')++ expect(await requestComposerSetDraft(['sess-a'], 'new text')).toBe(true)+ expect(a.wrote).toBe('new text')+ expect(b.wrote).toBeNull()+ })++ it('resolves null / false when no surface answers', async () => {+ mountDraft('sess-a', 'x')++ expect(await requestComposerGetDraft(['nobody'])).toBeNull()+ expect(await requestComposerSetDraft(['nobody'], 'hi')).toBe(false)+ })++ it('surfaces a write refused by the owner (a blank paint is a no-op)', async () => {+ mountDraft('sess-a', 'x')++ expect(await requestComposerSetDraft(['sess-a'], ' ')).toBe(false)+ })+})diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.tsindex 82b63748200..c5107f0e124 100644--- a/apps/desktop/src/app/chat/composer/focus.ts+++ b/apps/desktop/src/app/chat/composer/focus.ts@@ -318,6 +318,184 @@ export const requestComposerInsertRefs = (export const onComposerInsertRefsRequest = (handler: (detail: InsertRefsDetail) => void) =>subscribe<InsertRefsDetail>(INSERT_REFS_EVENT, handler)+// ── Draft read/write bus (plugin SDK `host.composer`) ─────────────────────+//+// A synchronous request/reply pair over the same CustomEvent bus as the+// mutations above: mounted composers answer for their own sessions, the+// requester times out to `null`/`false` when none does. Deferral is NOT used+// for the request (the reply path is already async for the caller); handlers+// run inline, matching the submit bus's preserve-the-visible-surface rule.++/** Durable or runtime ids a mounted composer answers for (primary: both;+ * tile: its stored id; plus the queue-edit key the draft stash is keyed by).+ * `active` addresses the composer the bus currently routes to, whatever+ * session it holds — the read/write cousin of the mutations' 'active' target. */+export interface DraftRequestDetail {+ token: number+ ids: string[]+ active?: boolean+ /** Set-draft payload; absent on read requests. */+ text?: string+}++interface DraftReplyDetail {+ ids?: string[]+ ok?: boolean+ text?: null | string+ token: number+}++const GET_DRAFT_EVENT = 'hermes:composer-get-draft'+const SET_DRAFT_EVENT = 'hermes:composer-set-draft'+const DRAFT_REPLY_EVENT = 'hermes:composer-draft-reply'+const DRAFT_REPLY_TIMEOUT_MS = 50++let draftToken = 0++const draftRequests =+ typeof window === 'undefined'+ ? null+ : {+ get: new Map<number, (reply: DraftReplyDetail | null) => void>(),+ set: new Map<number, (reply: DraftReplyDetail | null) => void>()+ }++const requestDraftOnce = (+ channel: 'get' | 'set',+ event: string,+ detail: DraftRequestDetail+): null | Promise<DraftReplyDetail | null> => {+ const pending = draftRequests?.[channel]++ if (!pending) {+ return null+ }++ return new Promise<DraftReplyDetail | null>(resolve => {+ pending.set(detail.token, resolve)++ window.dispatchEvent(new CustomEvent<DraftRequestDetail>(event, { detail }))++ // A subscriber that never replies (unmounted, input disabled, mid-teardown)+ // must not strand the promise: settle null, drop the slot.+ window.setTimeout(() => {+ if (pending.get(detail.token) === resolve) {+ pending.delete(detail.token)+ resolve(null)+ }+ }, DRAFT_REPLY_TIMEOUT_MS)+ })+}++if (typeof window !== 'undefined') {+ window.addEventListener(DRAFT_REPLY_EVENT, event => {+ const reply = (event as CustomEvent<DraftReplyDetail>).detail++ if (!reply?.token) {+ return+ }++ const channel = reply.text === undefined ? 'set' : 'get'+ const pending = draftRequests?.[channel]+ const resolve = pending?.get(reply.token)++ if (resolve) {+ pending?.delete(reply.token)+ resolve(reply)+ }+ })+}++/** Read a mounted composer's LIVE draft (the stash only holds the last+ * debounced persist). `ids` are the session ids to answer for; the first+ * relevant surface replies. Resolves null when no mounted composer answers —+ * callers fall back to `takeSessionDraft` for the persisted copy. */+export const requestComposerGetDraft = (+ ids: string[],+ opts?: { active?: boolean }+): Promise<null | { text: null | string }> => {+ const cleaned = [...new Set(ids.map(id => id?.trim()).filter(Boolean))] as string[]+ const active = opts?.active === true+ const token = ++draftToken++ const promise =+ cleaned.length || active+ ? requestDraftOnce('get', GET_DRAFT_EVENT, { active, ids: cleaned, token })+ : null++ if (!promise) {+ return Promise.resolve(null)+ }++ return promise.then(reply => (reply ? { text: reply.text ?? '' } : null))+}++/** Replace a mounted composer's draft (the app's own paint path — the text+ * re-renders through `renderComposerContents`, so `@`-ref / `/`-command+ * tokens hydrate as chips exactly like official paste). Returns false when+ * no mounted surface answers; never writes another session's composer. */+export const requestComposerSetDraft = (+ ids: string[],+ text: string,+ opts?: { active?: boolean }+): Promise<boolean> => {+ const cleaned = [...new Set(ids.map(id => id?.trim()).filter(Boolean))] as string[]+ const active = opts?.active === true+ const token = ++draftToken++ const promise =+ cleaned.length || active+ ? requestDraftOnce('set', SET_DRAFT_EVENT, { active, ids: cleaned, text, token })+ : null++ return promise ? promise.then(reply => reply?.ok === true) : Promise.resolve(false)+}++/** 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. */+export const onComposerDraftRequests = (+ address: { getIds: () => string[]; isActive: () => boolean },+ handlers: { read: () => null | string; write: (text: string) => boolean }+) => {+ if (typeof window === 'undefined') {+ return () => undefined+ }++ 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)))) {+ return+ }++ if (e.type === GET_DRAFT_EVENT) {+ window.dispatchEvent(+ new CustomEvent<DraftReplyDetail>(DRAFT_REPLY_EVENT, {+ detail: { text: handlers.read(), token: e.detail.token }+ })+ )+ } else if (e.type === SET_DRAFT_EVENT) {+ const ok = handlers.write(e.detail.text ?? '')++ window.dispatchEvent(new CustomEvent<DraftReplyDetail>(DRAFT_REPLY_EVENT, { detail: { ok, token: e.detail.token } }))+ }+ }++ window.addEventListener(GET_DRAFT_EVENT, listener)+ window.addEventListener(SET_DRAFT_EVENT, listener)++ return () => {+ window.removeEventListener(GET_DRAFT_EVENT, listener)+ window.removeEventListener(SET_DRAFT_EVENT, listener)+ }+}+/** Submit a prompt through a composer as if the user typed + sent it. Lets* external panels (e.g. the review pane's "let the agent ship it" button) hand* the agent a task without the user round-tripping through the input. */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.tsindex 3d6516c473a..cbafeade015 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@@ -18,6 +18,7 @@ import {adoptNewSessionDraft,type ComposerAttachment,type ComposerDraftSyncMode,+ NEW_SESSION_DRAFT_KEY,onComposerDraftSyncRequest,reloadPersistedDrafts,stashSessionDraft,@@ -38,6 +39,7 @@ import {focusComposerInput,getActiveComposer,markActiveComposer,+ onComposerDraftRequests,onComposerFocusRequest,onComposerInsertRefsRequest,onComposerInsertRequest,@@ -275,6 +277,55 @@ export function useComposerDraft({const stashAt = (scope: string | null, text = draftRef.current, attachments = attachmentScope.$attachments.get()) =>stashSessionDraft(scope, text, attachments)+ // Draft read/write bus (plugin SDK `host.composer`): answer for the sessions+ // this composer owns — the runtime id, the queue/stored key (tiles run with+ // sessionId = their stored id; the primary's queue key is the resolved+ // stored id), so a plugin addressing either identity reaches this surface.+ // Reads answer the live DOM text (the stash lags by the persist debounce);+ // writes go through paintDraft — the app's own programmatic-draft path, so+ // `@`-ref / `/` tokens hydrate as chips like official paste.+ useEffect(() => {+ if (inputDisabled) {+ return undefined+ }++ return onComposerDraftRequests(+ {+ getIds: () => {+ const ids = [sessionIdRef.current, activeQueueSessionKeyRef.current].filter(+ (id): id is string => Boolean(id)+ )++ // A surface with no session yet IS the new-chat draft (the stash keys+ // it '__new__'); once one opens, the new-chat draft belongs elsewhere.+ return ids.length ? ids : [NEW_SESSION_DRAFT_KEY]+ },+ isActive: () => getActiveComposer() === target+ },+ {+ read: () => {+ const editor = editorRef.current++ return editor ? composerPlainText(editor) : draftRef.current+ },+ write: text => {+ const editor = editorRef.current++ // Hidden keep-alive panes still answer: multi-session plugins route+ // to a specific session's composer, and paintDraft never steals the+ // caret of a non-visible surface.+ if (!editor || !editor.isConnected) {+ return false+ }++ paintDraft(text)++ return true+ }+ }+ )+ }, [inputDisabled, paintDraft, target])+const loadIntoComposer = (text: string, attachments: ComposerAttachment[]) => {// Diagnostic breadcrumb for #59305-class reports: identifies WHAT kind of// state got restored into the composer (session switch, queue-editdiff --git a/apps/desktop/src/sdk/index.test.ts b/apps/desktop/src/sdk/index.test.tsindex 5ad9ca2924c..a264bfe3b77 100644--- a/apps/desktop/src/sdk/index.test.ts+++ b/apps/desktop/src/sdk/index.test.ts@@ -263,3 +263,56 @@ describe('host workspace scope', () => {expect($workspaceNewSessionTarget.get()).toEqual({ kind: 'route', route })})})++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++ seen.push({ mode, target })+ }++ window.addEventListener('hermes:composer-insert', off)+ host.composer.insertText('sess-1', ' snippet ', { mode: 'inline' })+ host.composer.insertText(null, 'to active')+ await flush()+ window.removeEventListener('hermes:composer-insert', off)++ expect(seen).toEqual([+ { mode: 'inline', target: 'tile:sess-1' },+ { mode: 'block', target: 'main' }+ ])+ })++ it('reads the live draft through a bus reply', async () => {+ const reply = (event: Event) => {+ const { token } = (event as CustomEvent<{ token: number }>).detail++ window.dispatchEvent(new CustomEvent('hermes:composer-draft-reply', { detail: { text: 'live text', token } }))+ }++ window.addEventListener('hermes:composer-get-draft', reply)+ const text = await host.composer.getDraft(null)+ window.removeEventListener('hermes:composer-get-draft', reply)++ expect(text).toBe('live text')+ })++ it('falls back to the persisted stash when no surface answers', async () => {+ const { stashSessionDraft } = await import('@/store/composer')++ stashSessionDraft('sess-stash', 'stashed draft', [])++ await expect(host.composer.getDraft('sess-stash')).resolves.toBe('stashed draft')+ // Never-stashed + unanswered → null (timeout), never a wrong-session read.+ await expect(host.composer.getDraft('sess-never')).resolves.toBeNull()+ })++ it('reports a setDraft failure when no surface answers', async () => {+ await expect(host.composer.setDraft('sess-ghost', 'hello')).resolves.toBe(false)+ })+})diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 546ebf999a6..298657b5a99 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -22,6 +22,14 @@ import { atom, computed, type ReadableAtom } from 'nanostores'import type { ReactNode } from 'react'import { capabilityScoped } from '@/api/client'+import {+ type ComposerInsertMode,+ type ComposerTarget,+ requestComposerGetDraft,+ requestComposerInsert,+ requestComposerSetDraft,+ requestComposerSubmit+} from '@/app/chat/composer/focus'import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'import { openSession, type OpenSessionIntent } from '@/app/open-session'import { syncWorkspaceRoute } from '@/app/routes'@@ -48,6 +56,7 @@ import { registry } from '@/contrib/registry'import type { WorkspaceMode } from '@/contrib/types'import { deleteProfile, getLogs, getStatus, hermesApi, type HermesGateway } from '@/hermes'import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'+import { NEW_SESSION_DRAFT_KEY, takeSessionDraft } from '@/store/composer'import {$gateway,activeGatewayConnectionId,@@ -112,6 +121,42 @@ import { planPluginOpenSession } from './plugin-open-session-plan'const readonlyAtom = <T>(atomLike: ReadableAtom<T>): ReadableAtom<T> => atomLike+/**+ * Resolve a plugin's session address to the composer bus's target + the ids a+ * mounted surface answers draft requests for. `null` = the active composer+ * (bus-resolved, like the internal helpers). A draft chat with no session id+ * yet addresses it with the literal `'new'` — the same key the app stashes its+ * fresh draft under. A stored id routes to that session's tile when one is+ * open, else the primary composer (which renders that session); runtime ids+ * are also accepted and answered by the surface holding them.+ */+const resolveComposerAddress = (+ sessionId: null | string | undefined+): { ids: string[]; target: 'active' | ComposerTarget } => {+ const id = typeof sessionId === 'string' ? sessionId.trim() : ''++ if (!id) {+ return { ids: [], target: 'active' }+ }++ if (id === 'new') {+ return { ids: [NEW_SESSION_DRAFT_KEY], target: 'active' }+ }++ // A runtime id is accepted too: resolve it to the durable id the surfaces+ // address (session states map runtime → stored while a session is live).+ const stored = $sessionStates.get()[id]?.storedSessionId ?? id+ const ids = stored === id ? [id] : [id, stored]++ // The primary composer answers only for the session it is showing; a tile+ // answers for its own. Anything else stays `tile:<id>` — an absent tile+ // drops the request (fail-closed) rather than leaking it into whatever+ // session the primary is displaying.+ const shownInPrimary = ids.includes($selectedStoredSessionId.get() ?? '')++ return { ids, target: shownInPrimary ? 'main' : (`tile:${stored}` as ComposerTarget) }+}+/*** Turn flag for the FOCUSED chat — same semantics as the statusbar's busy* pulse. While the focused surface is the primary workspace (or a draft with@@ -1553,7 +1598,79 @@ export const host = {* components that take a `HermesGateway` prop directly (e.g. `ConnectorsTab`),* which need the instance, not just a JSON-RPC door. Re-read per use — the* active instance changes on a profile swap. */- getGateway: (): HermesGateway | null => $gateway.get()+ getGateway: (): HermesGateway | null => $gateway.get(),++ /** THE composer draft surface (#116305 item 1): read, write, insert, and+ * submit a session's input WITHOUT touching app DOM — mounted surfaces+ * answer for their own sessions over the app's focus bus, so a plugin+ * addressing one session can never reach another's composer. Addressing:+ * `null` = the active composer (what the user last clicked into); a+ * session id (stored or runtime) = that session's composer, whether it is+ * the primary surface or a tile; the literal `'new'` = the fresh draft+ * with no session id yet. Every method is async-safe: an address that+ * resolves to no live surface rejects/falses, it never broadcasts. */+ composer: {+ /** The live draft text of one composer, or null when nothing holds it.+ * Mounted surfaces answer with their in-DOM text (current, incl.+ * unsaved keystrokes); an unmounted session falls back to its debounced+ * persisted stash; `null` address = the active composer (no fallback —+ * nobody on screen is answering, which is reported as null). */+ getDraft: async (sessionId: null | string = null): Promise<null | string> => {+ const { ids } = resolveComposerAddress(sessionId === null ? undefined : sessionId)++ if (!ids.length) {+ const live = await requestComposerGetDraft([], { active: true })++ return live ? live.text : null+ }++ const live = await requestComposerGetDraft(ids)++ if (live) {+ return live.text+ }++ return takeSessionDraft(ids[0]).text || null+ },++ /** Replace a composer's whole draft. `@`-ref / `/` tokens in the text+ * hydrate into chips exactly like an official paste (the app owns the+ * markup). Returns false when no mounted surface answers for the+ * address — the draft of an unmounted session is never half-written. */+ setDraft: async (sessionId: null | string, text: string): Promise<boolean> => {+ if (typeof text !== 'string') {+ return false+ }++ const { ids } = resolveComposerAddress(sessionId === null ? undefined : sessionId)++ return requestComposerSetDraft(ids, text, ids.length ? undefined : { active: true })+ },++ /** 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. */+ insertText: (+ sessionId: null | string,+ text: string,+ opts?: { mode?: ComposerInsertMode }+ ): void => {+ const { target } = resolveComposerAddress(sessionId === null ? undefined : sessionId)++ requestComposerInsert(text, { mode: opts?.mode ?? 'block', target })+ },++ /** Send `text` as if the user typed it + pressed Enter, and return+ * whether a visible surface claimed it. Same fail-closed contract as+ * the internal bus: no exact visible composer for the address → false,+ * never a broadcast into whichever pane happens to be mounted. */+ submit: (sessionId: null | string, text: string): boolean => {+ const { target } = resolveComposerAddress(sessionId === null ? undefined : sessionId)++ return requestComposerSubmit(text, { target })+ }+ }}// -- react bridge -------------------------------------------------------------diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex 7a581b2272f..2407a12e27c 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -176,7 +176,7 @@ export const mainComposerScope = createComposerAttachmentScope($composerAttachme// localStorage; attachments are memory-only (blobs, upload state).export const SESSION_DRAFTS_STORAGE_KEY = 'hermes:composer-drafts:v3'-const NEW_SESSION_DRAFT_KEY = '__new__'+export const NEW_SESSION_DRAFT_KEY = '__new__'const MAX_PERSISTED_DRAFTS = 50const EMPTY_SESSION_DRAFT: SessionDraft = { attachments: [], text: '' }diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex 96452e7ebf8..2138553c7dd 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -412,6 +412,43 @@ plugin is the worked example (it is also a complete, installable disk plugin).attachment source, or transform a draft before it is sent (`ComposerMiddleware`with a `handler(draft) => draft | null`).+### Composer draft API — read and write the live input++For everything the composer areas can't do — put text INTO the input, replace+what's there, read the current draft, or send it — use `host.composer`. This+is the supported door; reaching for the ProseMirror DOM, `[data-composer-target]`+lookups, or synthetic `InputEvent`s is out of the plugin surface (catalog rule 8)+and breaks the moment the app's markup moves. Addressing: `null` = the composer+the user is typing in; a session id (stored or runtime) = that session's+composer, in the primary pane or a tile; `'new'` = the fresh draft that has no+session id yet.++```javascript+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' })++// Replace a session's whole draft — '@'-ref and '/command' tokens hydrate+// into chips exactly like an official paste. False when no mounted surface+// answers (an unmounted session is never half-written).+const ok = await host.composer.setDraft('sess-1', 'plan:\n- @file:src/app.ts')++// Read the live draft: the mounted surface's in-DOM text (unsaved keystrokes+// included), falling back to the debounced persisted stash. Null when nothing+// holds it.+const text = await host.composer.getDraft('sess-1')++// Send as if the user typed + pressed Enter. Fail-closed like the app's own+// panels: no visible surface for the address → false, never a broadcast.+const sent = host.composer.submit('sess-1', 'ship it')+```++A multi-session plugin keeps its per-session state on its side (which session+its panel is editing) and passes that id here; the bus guarantees one+plugin write can never land in another session's composer.+### Transcript directives — inline components the model addresses`TRANSCRIPT_DIRECTIVE_AREA` makes the transcript itself a contribution area.