The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): split prompt-action and composer branch helpers for code health
Tekniumab0e481abca6
diff --git a/apps/desktop/src/app/chat/composer/controls.tsx b/apps/desktop/src/app/chat/composer/controls.tsxindex 93a02d30177..9495475ccc3 100644--- a/apps/desktop/src/app/chat/composer/controls.tsx+++ b/apps/desktop/src/app/chat/composer/controls.tsx@@ -86,9 +86,7 @@ export function ComposerControls({const showStop = busy && !hasComposerPayloadconst showQueueButton = busy && busyAction !== 'stop' && busyAction !== 'queue' && hasComposerPayload- const sendLabel = busy- ? { interrupt: c.redirect, queue: c.queueMessage, steer: c.steer, stop: c.stop }[busyAction]- : c.send+ const sendLabel = composerSendLabel(busy, busyAction, c)// The HUD is a Spotlight bar a few hundred pixels wide, so the four separate// voice toggles fold into one menu there and leave the row to the input. A@@ -133,21 +131,7 @@ export function ComposerControls({{voiceControls}</>)}- {busy && busyAction !== 'steer' && onSteer ? (- <Tip label={c.steer}>- <Button- aria-label={c.steer}- className={GHOST_ICON_BTN}- disabled={disabled}- onClick={onSteer}- size="icon"- type="button"- variant="ghost"- >- <Codicon name="debug-step-over" size="0.875rem" />- </Button>- </Tip>- ) : null}+ {renderSteerButton(busy, busyAction, onSteer, disabled, c.steer)}{showQueueButton ? (<Tip label={<TipKeybindLabel actionId="composer.queue" text={c.queueMessage} />} placement="control"><Button@@ -203,6 +187,38 @@ export function ComposerControls({)}+function composerSendLabel(+ busy: boolean,+ busyAction: 'interrupt' | 'steer' | 'queue' | 'stop',+ c: { redirect: string; queueMessage: string; send: string; steer: string; stop: string }+): string {+ return busy ? { interrupt: c.redirect, queue: c.queueMessage, steer: c.steer, stop: c.stop }[busyAction] : c.send+}++function renderSteerButton(+ busy: boolean,+ busyAction: 'interrupt' | 'steer' | 'queue' | 'stop',+ onSteer: (() => void) | undefined,+ disabled: boolean,+ label: string+) {+ return busy && busyAction !== 'steer' && onSteer ? (+ <Tip label={label}>+ <Button+ aria-label={label}+ className={GHOST_ICON_BTN}+ disabled={disabled}+ onClick={onSteer}+ size="icon"+ type="button"+ variant="ghost"+ >+ <Codicon name="debug-step-over" size="0.875rem" />+ </Button>+ </Tip>+ ) : null+}+function HudWindowButtons() {const { t } = useI18n()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 b589186a1de..d248594823a 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@@ -278,15 +278,19 @@ export function useComposerSubmit({// command, so it falls back to the ordinary-message behavior.const isSideQuestion = !attachments.length && isSideTaskSlashCommand(text)- if (payloadPresent && !queueEdit && !isSideQuestion && hasClarifyRequest(sessionId)) {- void skipClarifyRequest(sessionId)- }+ const skipParkedCards = () => {+ if (payloadPresent && !queueEdit && !isSideQuestion && hasClarifyRequest(sessionId)) {+ void skipClarifyRequest(sessionId)+ }- // Same for a pending connection card: ordinary typing continues the operation.- if (payloadPresent && !queueEdit && !isSideQuestion && hasConnectionRequest(sessionId)) {- void skipConnectionRequest(sessionId)+ // Same for a pending connection card: ordinary typing continues the operation.+ if (payloadPresent && !queueEdit && !isSideQuestion && hasConnectionRequest(sessionId)) {+ void skipConnectionRequest(sessionId)+ }}+ skipParkedCards()+// Approval / sudo / secret prompts also park the turn inside a tool batch,// but typing CANNOT answer them (no message text approves a command or// supplies a password), so there is no skip-and-steer path: a steer would@@ -296,6 +300,14 @@ export function useComposerSubmit({// instead; the prompt stays answerable and the queue drains on settle.const blockingPrompt = !queueEdit && hasBlockingPromptRequest(sessionId)+ const routeBusyText = () => {+ if (busyInputMode === 'queue') {+ queueCurrentDraft()+ } else if (busyInputMode !== null) {+ steerDraft(busyInputMode)+ }+ }+if (queueEdit) {exitQueuedEdit('save')} else if (busy) {@@ -330,11 +342,7 @@ export function useComposerSubmit({// already ended, steerDraft re-queues so nothing is lost. Compaction is// the gateway's call: it answers `queued` under the compression lock.// Unloaded policy (null) must not turn an intended queue into an interrupt.- if (busyInputMode === 'queue') {- queueCurrentDraft()- } else if (busyInputMode !== null) {- steerDraft(busyInputMode)- }+ routeBusyText()} else if (payloadPresent) {// Attachments can't ride a redirect (no tool-result image carriage) —// queue the whole payload for the next turn. Same for a turn parked ondiff --git a/apps/desktop/src/app/chat/composer/queue-panel.tsx b/apps/desktop/src/app/chat/composer/queue-panel.tsxindex 0b2bcff708b..6c8f98ccf33 100644--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx@@ -135,67 +135,19 @@ export function QueuePanel({</Button></Tip>)}- {lost && onDiscardLost ? (- <Tip label={c.queueLostDiscardTip}>- <Button- aria-label={c.queueLostDiscard}- className="h-5 rounded-md px-1.5 text-[0.66rem]"- data-slot="queue-lost-discard"- onClick={() => onDiscardLost(entry.id)}- size="micro"- type="button"- variant="text"- >- {c.queueLostDiscard}- </Button>- </Tip>- ) : (- !entry.serverStatus && (- <>- <Tip label={c.queueEdit}>- <Button- aria-label={c.queueEdit}- className="size-5 rounded-md"- disabled={Boolean(editingId) && !isEditing}- onClick={() => onEdit(entry)}- size="icon-xs"- type="button"- variant="ghost"- >- <Pencil className={iconSize.xs} />- </Button>- </Tip>- {canSteer && (- <Tip label={c.queueSteer}>- <Button- aria-label={c.queueSteer}- className="size-5 rounded-md"- disabled={isEditing}- onClick={() => onSteerNow?.(entry.id)}- size="icon-xs"- type="button"- variant="ghost"- >- <SteeringWheel className={iconSize.xs} />- </Button>- </Tip>- )}- <Tip label={busy ? c.queueSendNext : c.queueSend}>- <Button- aria-label={busy ? c.queueSendNext : c.queueSend}- className="size-5 rounded-md"- disabled={isEditing}- onClick={() => onSendNow(entry.id)}- size="icon-xs"- type="button"- variant="ghost"- >- <CornerDownLeft className={iconSize.xs} />- </Button>- </Tip>- </>- )- )}+ {renderEntryActions({+ busy,+ c,+ editingId,+ entry,+ isEditing,+ lost,+ onDiscardLost,+ onEdit,+ onSendNow,+ onSteerNow,+ canSteer+ })}</>}trailingVisible={isEditing || lost}@@ -227,3 +179,94 @@ export function QueuePanel({</StatusSection>)}++interface EntryActionsArgs {+ busy: boolean+ c: Translations['composer']+ canSteer: boolean+ editingId: null | string+ entry: QueuedPromptEntry+ isEditing: boolean+ lost: boolean+ onDiscardLost?: (id: string) => void+ onEdit: (entry: QueuedPromptEntry) => void+ onSendNow: (id: string) => void+ onSteerNow?: (id: string) => void+}++/** Per-row trailing actions: discard for a lost row, else edit/steer/send for a local one. */+function renderEntryActions({+ busy,+ c,+ canSteer,+ editingId,+ entry,+ isEditing,+ lost,+ onDiscardLost,+ onEdit,+ onSendNow,+ onSteerNow+}: EntryActionsArgs) {+ return lost && onDiscardLost ? (+ <Tip label={c.queueLostDiscardTip}>+ <Button+ aria-label={c.queueLostDiscard}+ className="h-5 rounded-md px-1.5 text-[0.66rem]"+ data-slot="queue-lost-discard"+ onClick={() => onDiscardLost(entry.id)}+ size="micro"+ type="button"+ variant="text"+ >+ {c.queueLostDiscard}+ </Button>+ </Tip>+ ) : (+ !entry.serverStatus && (+ <>+ <Tip label={c.queueEdit}>+ <Button+ aria-label={c.queueEdit}+ className="size-5 rounded-md"+ disabled={Boolean(editingId) && !isEditing}+ onClick={() => onEdit(entry)}+ size="icon-xs"+ type="button"+ variant="ghost"+ >+ <Pencil className={iconSize.xs} />+ </Button>+ </Tip>+ {canSteer && (+ <Tip label={c.queueSteer}>+ <Button+ aria-label={c.queueSteer}+ className="size-5 rounded-md"+ disabled={isEditing}+ onClick={() => onSteerNow?.(entry.id)}+ size="icon-xs"+ type="button"+ variant="ghost"+ >+ <SteeringWheel className={iconSize.xs} />+ </Button>+ </Tip>+ )}+ <Tip label={busy ? c.queueSendNext : c.queueSend}>+ <Button+ aria-label={busy ? c.queueSendNext : c.queueSend}+ className="size-5 rounded-md"+ disabled={isEditing}+ onClick={() => onSendNow(entry.id)}+ size="icon-xs"+ type="button"+ variant="ghost"+ >+ <CornerDownLeft className={iconSize.xs} />+ </Button>+ </Tip>+ </>+ )+ )+}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex 59d7ba1d03b..2bbb765da5c 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@ -4,7 +4,6 @@ import { stripAnsi } from '@hermes/shared/ansi'import { useStore } from '@nanostores/react'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'-import { hermesApi } from '@/api/client'import { type ResolvedOwner, transcribeAudio } from '@/hermes'import { useI18n } from '@/i18n'import { attachmentPathNeedsUpload } from '@/lib/attachment-upload-policy'@@ -28,11 +27,9 @@ import { serverOwnsComposerQueue } from '@/store/composer-queue'import { resetSessionBackground } from '@/store/composer-status'import { clearNotifications, notify, notifyError } from '@/store/notifications'import { clearPreviewArtifacts } from '@/store/preview-status'-import { $activeGatewayProfile } from '@/store/profile'import { clearAllPrompts } from '@/store/prompts'import {$busy,- $connection,$currentCwd,$messages,$terminalBackend,@@ -77,6 +74,7 @@ import { useSlashCommand } from './slash'import { captureSteeringSession } from './steering-session'import { captureSubmissionDestination } from './submission-destination'import { useSubmitPrompt } from './submit'+import { uploadServerOwnedImage } from './upload-server-image'import {blobToDataUrl,delay,@@ -132,22 +130,7 @@ export async function uploadComposerAttachment(if (attachment.kind === 'image' && serverOwnsComposerQueue(storedSessionId ?? opts.sessionId)) {// Pin HTTP to the same owner before the native byte read yields. Images// are immutable admission payloads, never legacy agent.pending_images.- const owner = destination.owner- const connectionId = typeof owner === 'object' && owner ? owner.connectionId : $connection.get()?.connectionId- const profile = typeof owner === 'object' && owner ? owner.targetProfile || owner.profile : owner || $activeGatewayProfile.get()-- const dataUrl = attachment.previewUrl?.includes(';base64,')- ? attachment.previewUrl- : await window.hermesDesktop?.readFileDataUrl(path)-- if (!dataUrl) { throw new Error(`Could not read ${label}`) }-- const result = await hermesApi<{ path: string; mime_type: string }>({- method: 'POST', path: '/api/chat/image-upload', connectionId: connectionId ?? 'local', profile,- body: { data_url: dataUrl, filename: label }- })-- return { ...attachment, path: result.path, mime: result.mime_type, attachedSessionId: opts.sessionId, uploadState: undefined }+ return await uploadServerOwnedImage(attachment, destination, path, label, opts.sessionId)}// Read bytes/paths ONCE, outside the retry. Only the session-scoped RPC is@@ -890,7 +873,8 @@ export function usePromptActions({const message = state.messages.find(candidate => candidate.id === messageId)// A newer reply may precede this ACK; it already owns its boundary.- const hasNewReply = state.messages.slice(state.messages.findIndex(candidate => candidate.id === messageId) + 1)+ const hasNewReply = state.messages+ .slice(state.messages.findIndex(candidate => candidate.id === messageId) + 1).some(candidate => candidate.role === 'assistant')return message && state.streamId && !hasNewReplydiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex db2a2a64695..4b15f7a01cf 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -216,16 +216,24 @@ export function useSlashCommand(deps: SlashCommandDeps) {const retryOptions = { ...options, retryText: rawCommand }try {- const prepared = await readPreparedSubmission(preparedSubmissionKey(- resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),- destination, rawCommand, options?.attachments ?? $composerAttachments.get(), retryOptions- ))+ const prepared = await readPreparedSubmission(+ preparedSubmissionKey(+ resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),+ destination,+ rawCommand,+ options?.attachments ?? $composerAttachments.get(),+ retryOptions+ )+ )if (prepared) {return await submitPromptText(prepared.text, {- ...retryOptions, sessionId: initialRuntimeId ?? undefined,- storedSessionId: initialStoredId, displayText: prepared.displayText,- submission_id: prepared.id, destination+ ...retryOptions,+ sessionId: initialRuntimeId ?? undefined,+ storedSessionId: initialStoredId,+ displayText: prepared.displayText,+ submission_id: prepared.id,+ destination})}} catch (err) {@@ -282,7 +290,9 @@ export function useSlashCommand(deps: SlashCommandDeps) {// to updateSessionState re-keyed the tile's cache entry onto the// primary's stored session. Fall back to the selection only for a// session with no published state yet (a draft this call just created).- const storedSessionId = $sessionStates.get()[sessionId]?.storedSessionId ?? initialStoredId ??+ const storedSessionId =+ $sessionStates.get()[sessionId]?.storedSessionId ??+ initialStoredId ??(!initialRuntimeId && activeSessionIdRef.current === sessionId ? selectedStoredSessionIdRef.current : null)// Header carries the command token only. The full invocation would@@ -364,19 +374,23 @@ export function useSlashCommand(deps: SlashCommandDeps) {// that the backend wants shown as a system line before the message// is acted on. Mirrors the TUI's createSlashHandler — without it a// `/goal <text>` looked like it did nothing.- if ((dispatch.type === 'send' || dispatch.type === 'prefill') && dispatch.notice?.trim()) {- renderSlashOutput(dispatch.notice.trim())-- // `/goal <text>` returns its "⊙ Goal set …" notice here and kicks- // off the first turn immediately; the backend only emits a- // `status.update kind:"goal"` after that turn's post-turn judge- // runs. Seed the goal store from the notice so the indicator shows- // the active goal right away instead of after the first turn.- if (name === 'goal') {- applyGoalStatusText(sessionId, dispatch.notice.trim())+ const renderDispatchNotice = () => {+ if ((dispatch.type === 'send' || dispatch.type === 'prefill') && dispatch.notice?.trim()) {+ renderSlashOutput(dispatch.notice.trim())++ // `/goal <text>` returns its "⊙ Goal set …" notice here and kicks+ // off the first turn immediately; the backend only emits a+ // `status.update kind:"goal"` after that turn's post-turn judge+ // runs. Seed the goal store from the notice so the indicator shows+ // the active goal right away instead of after the first turn.+ if (name === 'goal') {+ applyGoalStatusText(sessionId, dispatch.notice.trim())+ }}}+ renderDispatchNotice()+const message = ('message' in dispatch ? dispatch.message : '')?.trim() ?? ''// /undo returns a prefill directive: drop the backed-up message intodiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/upload-server-image.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/upload-server-image.tsnew file mode 100644index 00000000000..3c379649ff5--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/upload-server-image.ts@@ -0,0 +1,49 @@+import { hermesApi } from '@/api/client'+import type { ComposerAttachment } from '@/store/composer'+import { $activeGatewayProfile } from '@/store/profile'+import { $connection } from '@/store/session'++import type { SubmissionDestination } from './submission-destination'++/**+ * Upload an image attachment over HTTP for a server-owned composer queue.+ * Pin HTTP to the same owner before the native byte read yields. Images are+ * immutable admission payloads, never legacy agent.pending_images.+ */+export async function uploadServerOwnedImage(+ attachment: ComposerAttachment,+ destination: SubmissionDestination,+ path: string,+ label: string,+ sessionId: string+): Promise<ComposerAttachment> {+ const owner = destination.owner+ const connectionId = typeof owner === 'object' && owner ? owner.connectionId : $connection.get()?.connectionId++ const profile =+ typeof owner === 'object' && owner ? owner.targetProfile || owner.profile : owner || $activeGatewayProfile.get()++ const dataUrl = attachment.previewUrl?.includes(';base64,')+ ? attachment.previewUrl+ : await window.hermesDesktop?.readFileDataUrl(path)++ if (!dataUrl) {+ throw new Error(`Could not read ${label}`)+ }++ const result = await hermesApi<{ path: string; mime_type: string }>({+ method: 'POST',+ path: '/api/chat/image-upload',+ connectionId: connectionId ?? 'local',+ profile,+ body: { data_url: dataUrl, filename: label }+ })++ return {+ ...attachment,+ path: result.path,+ mime: result.mime_type,+ attachedSessionId: sessionId,+ uploadState: undefined+ }+}