Skip to content

The agent that grows with you

fix: preserve native prepared input and session destinations

Tekniume06671bd4cca
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 56342dfb5c2..953a9177146 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -296,6 +296,7 @@ import {
import { createPoolStopper } from './pool-stop'
import { poolTouchKeys } from './pool-touch-scope'
import { createKeepAwake } from './power-save'
+import { registerPreparedSubmissions } from './prepared-submissions'
import { capturePreviewContents } from './preview-capture'
import { PreviewReachRegistry } from './preview-reach'
import {
@@ -15146,6 +15147,8 @@ ipcMain.on('hermes:wake-indicator:set', (_event, state) => {
// --- Text size (zoom) -------------------------------------------------------
// The settings UI drives the same clamped zoom scale as the Ctrl/Cmd
// shortcuts and the View menu. Reads and writes target the asking window.
+registerPreparedSubmissions()
+
ipcMain.handle('hermes:zoom:get', event => {
const window = BrowserWindow.fromWebContents(event.sender)
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index ca8bb45a282..a4614c6f9ef 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -296,6 +296,10 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
setDefaultProjectDir: dir => ipcRenderer.invoke('hermes:setting:defaultProjectDir:set', dir),
pickDefaultProjectDir: () => ipcRenderer.invoke('hermes:setting:defaultProjectDir:pick')
},
+ preparedSubmissions: {
+ read: () => ipcRenderer.invoke('hermes:prepared-submissions:read'),
+ update: (key, entry) => ipcRenderer.invoke('hermes:prepared-submissions:update', key, entry)
+ },
zoom: {
// Current zoom of this window, as { level, percent }.
get: () => ipcRenderer.invoke('hermes:zoom:get'),
diff --git a/apps/desktop/electron/prepared-submissions.test.ts b/apps/desktop/electron/prepared-submissions.test.ts
new file mode 100644
index 00000000000..1ab0a73d55a
--- /dev/null
+++ b/apps/desktop/electron/prepared-submissions.test.ts
@@ -0,0 +1,25 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { expect, test, vi } from 'vitest'
+vi.mock('electron', () => ({ app: {}, ipcMain: {} }))
+import { preparedJournal } from './prepared-submissions'
+
+test('acknowledged journal mutations survive reopening with exact payload and origin isolation', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'prepared-journal-'))
+
+ try {
+ const origin = 'http://localhost:5174'
+ const key = JSON.stringify(['remote', 'profile-a', 'stored-a'])
+ const entry = { id: 'id-a', text: 'Ω 👩🏽‍💻 e\u0301\n []', attachments: [{ id: 'asset', path: '/tmp/Ω' }], params: { session_id: 'live-a' } }
+ preparedJournal(dir, origin).update(key, entry)
+ preparedJournal(dir, origin).update('other-profile', { id: 'id-b' })
+ expect(preparedJournal(dir, origin).read()[key]).toEqual(entry)
+ expect(preparedJournal(dir, 'http://other:5174').read()).toEqual({})
+ preparedJournal(dir, origin).update(key, null)
+ expect(preparedJournal(dir, origin).read()).toEqual({ 'other-profile': { id: 'id-b' } })
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/prepared-submissions.ts b/apps/desktop/electron/prepared-submissions.ts
new file mode 100644
index 00000000000..aeb5af19473
--- /dev/null
+++ b/apps/desktop/electron/prepared-submissions.ts
@@ -0,0 +1,52 @@
+import { createHash } from 'node:crypto'
+import fs from 'node:fs'
+import path from 'node:path'
+
+import { app, ipcMain } from 'electron'
+
+import { writeSecretFileAtomic } from './hardening'
+
+// Match localStorage's origin isolation; destination keys additionally carry
+// connection/profile/session authority. No renderer-provided filesystem paths.
+export function preparedJournal(userData: string, origin: string) {
+ const file = path.join(userData, `prepared-submissions-${createHash('sha256').update(origin).digest('hex')}.json`)
+
+ const read = (): Record<string, unknown> => {
+ try {
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {return {}}
+ throw error
+ }
+ }
+
+ return {
+ read,
+ update(key: string, entry: unknown | null) {
+ const journal = read()
+
+ if (entry === null) {delete journal[key]}
+ else {Object.defineProperty(journal, key, { value: entry, enumerable: true, configurable: true })}
+
+ fs.mkdirSync(userData, { recursive: true })
+ // Same private atomic replacement used for native connection settings.
+ // Return only after write+rename: process termination cannot lose an ACKed
+ // entry to Chromium's deferred localStorage commit. Not a power-loss promise.
+ writeSecretFileAtomic(file, JSON.stringify(journal), { encoding: 'utf8' })
+ }
+ }
+}
+
+export function registerPreparedSubmissions() {
+ const store = (event: Electron.IpcMainInvokeEvent) =>
+ preparedJournal(app.getPath('userData'), new URL(event.senderFrame!.url).origin)
+
+ ipcMain.handle('hermes:prepared-submissions:read', event => JSON.stringify(store(event).read()))
+ ipcMain.handle('hermes:prepared-submissions:update', (event, key: string, entry: string | null) => {
+ if (typeof key !== 'string' || (entry !== null && typeof entry !== 'string')) {
+ throw new Error('Invalid prepared submission')
+ }
+
+ store(event).update(key, entry === null ? null : JSON.parse(entry))
+ })
+}
diff --git a/apps/desktop/src/app/chat/composer/controls.test.tsx b/apps/desktop/src/app/chat/composer/controls.test.tsx
index d5694b6144d..9ecf77936cc 100644
--- a/apps/desktop/src/app/chat/composer/controls.test.tsx
+++ b/apps/desktop/src/app/chat/composer/controls.test.tsx
@@ -138,10 +138,10 @@ describe('ComposerControls shortcut tooltips', () => {
await expectShortcutTooltip('Send', '↵')
})
- it('keeps Send (not Steer) while a turn is running if there is a payload', async () => {
+ it('labels busy Send with the effective configured action', async () => {
renderControls({ busy: true, busyAction: 'steer' })
- await expectShortcutTooltip('Send', '↵')
+ await expectShortcutTooltip('Steer the current run', '↵')
})
it('shows Stop only when the composer is empty mid-turn', async () => {
@@ -151,7 +151,7 @@ describe('ComposerControls shortcut tooltips', () => {
})
it('shows Ctrl+Enter for Queue as the secondary mid-turn action', async () => {
- renderControls({ busy: true, busyAction: 'queue' })
+ renderControls({ busy: true, busyAction: 'interrupt' })
await expectShortcutTooltip('Queue message', 'Ctrl+↵')
})
diff --git a/apps/desktop/src/app/chat/composer/controls.tsx b/apps/desktop/src/app/chat/composer/controls.tsx
index 51ea823427a..682274d673a 100644
--- a/apps/desktop/src/app/chat/composer/controls.tsx
+++ b/apps/desktop/src/app/chat/composer/controls.tsx
@@ -46,11 +46,12 @@ export function ComposerControls({
voiceStatus,
onDictate,
onQueue,
+ onSteer,
onToggleAutoSpeak
}: {
autoSpeak: boolean
busy: boolean
- busyAction: 'steer' | 'queue' | 'stop'
+ busyAction: 'interrupt' | 'steer' | 'queue' | 'stop'
canSubmit: boolean
compactModelPill?: boolean
conversation: ConversationProps
@@ -62,6 +63,7 @@ export function ComposerControls({
voiceStatus: VoiceStatus
onDictate: () => void
onQueue: () => void
+ onSteer?: () => void
onToggleAutoSpeak: () => void
}) {
const { t } = useI18n()
@@ -76,7 +78,10 @@ export function ComposerControls({
// Steer is just send: a payload keeps the Send affordance mid-turn. Stop
// only when the composer is empty and a turn is running.
const showStop = busy && !hasComposerPayload
- const showQueueButton = busyAction !== 'stop' && hasComposerPayload
+ const 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
// 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
// narrow tile hits the same wall from the other direction and folds for the
@@ -111,6 +116,21 @@ 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}
{showQueueButton ? (
<Tip label={<TipKeybindLabel actionId="composer.queue" text={c.queueMessage} />}>
<Button
@@ -148,12 +168,12 @@ export function ComposerControls({
showStop ? (
<TipKeybindLabel actionId="composer.send" text={c.stop} />
) : (
- <TipKeybindLabel actionId="composer.send" text={c.send} />
+ <TipKeybindLabel actionId="composer.send" text={sendLabel} />
)
}
>
<Button
- aria-label={showStop ? c.stop : c.send}
+ aria-label={showStop ? c.stop : sendLabel}
className={PRIMARY_ICON_BTN}
disabled={disabled || !canSubmit}
type="submit"
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
index ad3328cae89..2d29d8b6b87 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
@@ -86,6 +86,9 @@ describe('useComposerQueue park integration', () => {
}
expect(onSubmit).toHaveBeenCalledTimes(MAX_AUTO_DRAIN_ATTEMPTS)
+ for (const [, options] of onSubmit.mock.calls) {
+ expect(options).toMatchObject({ submission_id: entry.id })
+ }
await act(async () => {
await vi.advanceTimersByTimeAsync(300_000)
})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
index 5787a54a5b8..51837070a6d 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
@@ -100,7 +100,7 @@ export function useComposerQueue({
const [drainRetryTick, setDrainRetryTick] = useState(0)
const beginQueuedEdit = (entry: QueuedPromptEntry) => {
- if (!activeQueueSessionKey || queueEdit) {
+ if (!activeQueueSessionKey || queueEdit || entry.serverStatus) {
return
}
@@ -207,7 +207,7 @@ export function useComposerQueue({
const drainQueueSessionKey = activeQueueSessionKey
const drainRuntimeSessionId = sessionId ?? null
- const entry = pickEntry(getQueuedPrompts(drainQueueSessionKey))
+ const entry = pickEntry(getQueuedPrompts(drainQueueSessionKey).filter(entry => !entry.serverStatus))
if (!entry) {
return false
@@ -221,12 +221,13 @@ export function useComposerQueue({
attachments: entry.attachments,
...(entry.displayText ? { displayText: entry.displayText } : {}),
fromQueue: true,
+ submission_id: entry.id,
sessionId: drainRuntimeSessionId,
storedSessionId: drainQueueSessionKey
})
)
- if (accepted === false) {
+ if (accepted !== true) {
return false
}
@@ -251,7 +252,7 @@ export function useComposerQueue({
(entries: QueuedPromptEntry[]) => {
const skip = queueEditRef.current?.entryId
- return skip ? entries.find(e => e.id !== skip) : entries[0]
+ return entries.find(e => !e.serverStatus && e.id !== skip)
},
[queueEditRef] // reads the edit id off a ref so the lock-holder always sees the latest
)
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index b05a47a5818..e37b2a5f852 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@ -22,6 +22,7 @@ import { useComposerSubmit } from './use-composer-submit'
interface SubmitHarnessOptions {
attachments?: ComposerAttachment[]
busy?: boolean
+ busyInputMode?: 'interrupt' | 'queue' | 'steer' | null
compacting?: boolean
inputDisabled?: boolean
scopeTarget?: ComposerTarget
@@ -37,6 +38,7 @@ let surfaceSequence = 0
function renderSubmitHook({
attachments = [],
busy = false,
+ busyInputMode = 'interrupt',
compacting = false,
inputDisabled = false,
scopeTarget = 'main',
@@ -97,6 +99,7 @@ function renderSubmitHook({
activeQueueSessionKeyRef: { current: sessionKey },
attachments,
busy,
+ busyInputMode,
compacting,
clearDraft,
disabled: false,
@@ -265,6 +268,35 @@ describe('useComposerSubmit external request routing', () => {
})
describe('useComposerSubmit busy-turn routing', () => {
+ it('honors configured busy mode while explicit steering and queueing override it on every surface', async () => {
+ for (const scopeTarget of ['main', 'tile:stored-session'] as const) {
+ for (const mode of ['interrupt', 'queue', 'steer', null] as const) {
+ const ordinary = renderSubmitHook({ busy: true, busyInputMode: mode, scopeTarget, text: 'change course' })
+ act(() => ordinary.hook.result.current.submitDraft())
+
+ if (mode === 'queue') {
+ expect(ordinary.queueCurrentDraft).toHaveBeenCalledOnce()
+ expect(ordinary.onSteer).not.toHaveBeenCalled()
+ } else if (mode === null) {
+ expect(ordinary.clearDraft).not.toHaveBeenCalled()
+ expect(ordinary.onSteer).not.toHaveBeenCalled()
+ expect(ordinary.queueCurrentDraft).not.toHaveBeenCalled()
+ } else {
+ await waitFor(() => expect(ordinary.onSteer).toHaveBeenCalledWith('change course', mode))
+ expect(ordinary.queueCurrentDraft).not.toHaveBeenCalled()
+ }
+
+ ordinary.hook.unmount()
+ const explicit = renderSubmitHook({ busy: true, busyInputMode: mode, scopeTarget, text: 'explicit guidance' })
+ act(() => explicit.hook.result.current.steerDraft('steer'))
+ await waitFor(() => expect(explicit.onSteer).toHaveBeenCalledWith('explicit guidance', 'steer'))
+ act(() => explicit.hook.result.current.queueDraft())
+ expect(explicit.queueCurrentDraft).toHaveBeenCalledOnce()
+ explicit.hook.unmount()
+ }
+ }
+ })
+
afterEach(() => {
cleanup()
vi.restoreAllMocks()
@@ -280,7 +312,7 @@ describe('useComposerSubmit busy-turn routing', () => {
hook.result.current.submitDraft()
})
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
+ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))
expect(queueCurrentDraft).not.toHaveBeenCalled()
expect(onCancel).not.toHaveBeenCalled()
expect(onSubmit).not.toHaveBeenCalled()
@@ -437,7 +469,7 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
hook.result.current.submitDraft()
})
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
+ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))
expect(gatewayRequest).toHaveBeenCalledWith('clarify.respond', { request_id: 'req-runtime-session', answer: '' })
})
@@ -545,7 +577,7 @@ describe('useComposerSubmit with a blocking prompt parked on the session', () =>
hook.result.current.submitDraft()
})
- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
+ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))
expect(queueCurrentDraft).not.toHaveBeenCalled()
})
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.ts
index 9435881b43d..72f1fc9fbf0 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
@@ -3,6 +3,7 @@ import { type RefObject, useLayoutEffect, useRef } from 'react'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
import { triggerHaptic } from '@/lib/haptics'
+import type { BusyInputMode } from '@/store/busy-input-mode'
import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
import { clearSessionDraft, type ComposerAttachment } from '@/store/composer'
import { resetBrowseState } from '@/store/composer-input-history'
@@ -22,6 +23,7 @@ interface UseComposerSubmitArgs {
activeQueueSessionKeyRef: RefObject<string | null>
attachments: ComposerAttachment[]
busy: boolean
+ busyInputMode?: BusyInputMode | null
compacting: boolean
clearDraft: () => void
disabled: boolean
@@ -57,6 +59,7 @@ export function useComposerSubmit({
activeQueueSessionKeyRef,
attachments,
busy,
+ busyInputMode = 'interrupt',
compacting,
clearDraft,
disabled,
@@ -203,10 +206,12 @@ export function useComposerSubmit({
clearDraft()
dispatchSubmit(text)
} else if (!compacting && !blockingPrompt && !attachments.length && text.trim()) {
- // Cursor-style stop-and-correct: interrupt the live turn and redirect
- // it with this text. redirect() preserves the shown reasoning/work; if
- // the turn already ended, steerDraft re-queues so nothing is lost.
- steerDraft()
+ // Unloaded policy must not turn an intended queue into an interrupt.
+ if (busyInputMode === 'queue') {
+ queueCurrentDraft()
+ } else if (busyInputMode !== null) {
+ steerDraft(busyInputMode)
+ }
} 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 on
@@ -236,7 +241,7 @@ export function useComposerSubmit({
// Redirect the live turn with a correction. The gateway either restarts the
// active model request with its displayed context or waits for the current
// tool boundary. If the turn already ended, queue the words instead.
- const steerDraft = () => {
+ const steerDraft = (mode: 'interrupt' | 'steer' = 'interrupt') => {
const text = draftRef.current.trim()
// Guard on live editor state, not the render-lagged `canSteer`: a redirect
@@ -248,7 +253,7 @@ export function useComposerSubmit({
triggerHaptic('submit')
clearDraft()
- void Promise.resolve(onSteer(text)).then(accepted => {
+ void Promise.resolve(onSteer(text, mode)).then(accepted => {
if (!accepted && activeQueueSessionKey) {
enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments: [] })
}
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index 371bf32b07d..69254f2d234 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -3,7 +3,9 @@ import { useStore } from '@nanostores/react'
import { type ClipboardEvent, type FormEvent, type KeyboardEvent, useCallback, useEffect, useMemo, useRef } from 'react'
import { useTourMarker } from '@/app/chat/tour-marker'
+import type { GatewayRequester } from '@/app/contrib/types'
import { useHudComposerDrag } from '@/app/hud/composer-drag'
+import { useBusyInputMode } from '@/app/session/hooks/use-busy-input-mode'
import { composerFill, composerFloatingStrip, composerSurfaceGlass } from '@/components/chat/composer-dock'
import { Button } from '@/components/ui/button'
import { Slot as ContribSlot } from '@/contrib/react/slot'
@@ -175,6 +177,17 @@ export function ChatBar({
const blockingPrompt = useStore(useMemo(() => sessionBlockingPrompt(sessionId ?? null), [sessionId]))
const activeQueueSessionKey = queueSessionKey || sessionId || null
+ const requestBusyConfig = useCallback<GatewayRequester>(
+ (method, params) => (gateway ? gateway.request(method, params) : Promise.reject(new Error('Gateway unavailable'))),
+ [gateway]
+ )
+
+ const busyInputMode = useBusyInputMode({
+ sessionId: sessionId ?? null,
+ storedSessionId: queueSessionKey ?? null,
+ requestGateway: requestBusyConfig
+ })
+
// Status items (subagents, background processes) are keyed by the RUNTIME
// session id — gateway events and process.list both speak that id. Only the
// queue uses the stored-session fallback key (prompts can queue pre-resume).
@@ -343,7 +356,9 @@ export function ChatBar({
})
const hasComposerPayload = hasText || attachments.length > 0
- const canSubmit = busy || hasComposerPayload
+ const canSubmit =
+ (busy || hasComposerPayload) &&
+ !(busy && isSteerableText && attachments.length === 0 && !compacting && !blockingPrompt && busyInputMode === null)
// Steer only makes sense mid-turn, text-only (the gateway can't carry images
// into a tool result) and never for a slash command (those execute inline).
@@ -351,10 +366,9 @@ export function ChatBar({
// is parked on the user, so a steer can't reach the model — text queues.
const canSteer = busy && !compacting && !blockingPrompt && !!onSteer && attachments.length === 0 && isSteerableText
- // While busy: text redirects the live turn (Cursor-style stop-and-correct),
- // attachments queue for the next turn, an empty composer stops.
- const busyAction: 'steer' | 'queue' | 'stop' = canSteer
- ? 'steer'
+ // Ordinary busy Send follows backend policy; attachments queue and empty stops.
+ const busyAction: 'interrupt' | 'steer' | 'queue' | 'stop' = canSteer
+ ? (busyInputMode ?? 'interrupt')
: compacting || hasComposerPayload
? 'queue'
: 'stop'
@@ -362,6 +376,7 @@ export function ChatBar({
// The submit engine — the orchestration seam where draft + queue meet. Owns
// the submit decision tree, the send-with-restore primitive, and steer.
const { queueDraft, steerDraft, submitDraft } = useComposerSubmit({
+ busyInputMode,
activeQueueSessionKey,
activeQueueSessionKeyRef,
attachments,
@@ -1029,6 +1044,7 @@ export function ChatBar({
minimal={minimal}
onDictate={dictate}
onQueue={queueDraft}
+ onSteer={canSteer ? () => steerDraft('steer') : undefined}
onToggleAutoSpeak={handleToggleAutoSpeak}
state={state}
voiceStatus={voiceStatus}
diff --git a/apps/desktop/src/app/chat/composer/queue-panel.tsx b/apps/desktop/src/app/chat/composer/queue-panel.tsx
index 6e568dd6242..f500586a72e 100644
--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx
@@ -86,7 +86,7 @@ export function QueuePanel({
)}
key={entry.id}
trailing={
- <>
+ !entry.serverStatus && <>
<Tip label={c.queueEdit}>
<Button
aria-label={c.queueEdit}
diff --git a/apps/desktop/src/app/chat/composer/types.ts b/apps/desktop/src/app/chat/composer/types.ts
index da6a463cd38..49ead6ef2e2 100644
--- a/apps/desktop/src/app/chat/composer/types.ts
+++ b/apps/desktop/src/app/chat/composer/types.ts
@@ -54,7 +54,7 @@ export interface ChatBarProps {
onPickFolders?: () => void
onPickImages?: () => void
onRemoveAttachment?: (id: string) => void
- onSteer?: (text: string) => Promise<boolean> | boolean
+ onSteer?: (text: string, mode?: 'interrupt' | 'steer') => Promise<boolean> | boolean
onSubmit: (value: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onTranscribeAudio?: (audio: Blob) => Promise<string>
}
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx
index 1b95bc769a2..f9f3be192c2 100644
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@ -101,7 +101,7 @@ interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
onPickFolders: () => void
onPickImages: () => void
onRemoveAttachment: (id: string) => void
- onSteer: (text: string) => Promise<boolean> | boolean
+ onSteer: (text: string, mode?: 'interrupt' | 'steer') => Promise<boolean> | boolean
onSubmit: (text: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onThreadMessagesChange: (messages: readonly ThreadMessage[]) => void
onEdit: (message: AppendMessage) => Promise<void>
diff --git a/apps/desktop/src/app/chat/session-tile-actions.test.ts b/apps/desktop/src/app/chat/session-tile-actions.test.ts
index 4f8f862b9b5..cd221ad8e54 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.test.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.test.ts
@@ -188,7 +188,7 @@ describe('useSessionTileActions sleep/wake session recovery', () => {
throw new Error('session not found')
}
- return {}
+ return { admission_id: params?.submission_id, status: 'started' }
}
if (method === 'session.resume') {
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 84648ed8159..2b4b79183de 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -364,7 +364,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
}, [bindRecoveredRuntime, copy.stopFailed, requestSessionGateway, update])
const steerPrompt = useCallback(
- async (rawText: string): Promise<boolean> => {
+ async (rawText: string, mode: 'interrupt' | 'steer' = 'interrupt'): Promise<boolean> => {
const text = rawText.trim()
const sessionId = runtimeIdRef.current
@@ -384,13 +384,13 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
// bubble above output the user had already read (#73793), and its
// last-assistant fallback could land it mid-thread when the stream id
// was missing or stale (#83151).
- mutate(state =>
- appendMidTurnUserMessage(state, {
- id: messageId,
- role: 'user' as const,
- parts: [textPart(text)]
- })
- )
+ mutate(state => {
+ const message = { id: messageId, role: 'user' as const, parts: [textPart(text)] }
+
+ return mode === 'interrupt'
+ ? appendMidTurnUserMessage(state, message)
+ : { ...state, messages: [...state.messages, message] }
+ })
const discardOptimisticMessage = () =>
mutate(state => ({
@@ -411,7 +411,11 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
const { result } = await withSessionNotFoundResume(
sessionId,
storedIdRef.current,
- liveId => requestSessionGateway<{ status?: string }>('session.redirect', { session_id: liveId, text }),
+ liveId =>
+ requestSessionGateway<{ status?: string }>(mode === 'steer' ? 'session.steer' : 'session.redirect', {
+ session_id: liveId,
+ text
+ }),
{
requestGateway: requestSessionGateway,
onRecovered: bindRecoveredRuntime
@@ -425,7 +429,9 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
}
if (result?.status === 'queued') {
- moveOptimisticMessageToEnd()
+ if (mode === 'interrupt') {
+ moveOptimisticMessageToEnd()
+ }
triggerHaptic('submit')
return true
diff --git a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
index 162c9dc6110..81f9bc8f05e 100644
--- a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
+++ b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
@@ -133,7 +133,7 @@ describe('session tile attachment occurrence ownership', () => {
const original = makeAttachment()
const attach = deferred<{ attached: boolean; path: string }>()
- requestGateway.mockImplementation(async (method: string) => {
+ requestGateway.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === 'image.attach_bytes') {
return attach.promise
}
@@ -142,7 +142,7 @@ describe('session tile attachment occurrence ownership', () => {
throw new Error('submit failed after staging')
}
- return {}
+ return method === 'prompt.submit' ? { admission_id: params.submission_id, status: 'started' } : {}
})
scope.attachments.add(original)
@@ -179,7 +179,7 @@ describe('session tile attachment occurrence ownership', () => {
const replacement = makeAttachment()
const attach = deferred<{ attached: boolean; path: string }>()
- requestGateway.mockImplementation(async (method: string) => {
+ requestGateway.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === 'image.attach_bytes') {
return attach.promise
}
@@ -188,7 +188,7 @@ describe('session tile attachment occurrence ownership', () => {
throw new Error('submit failed after staging')
}
- return {}
+ return method === 'prompt.submit' ? { admission_id: params.submission_id, status: 'started' } : {}
})
scope.attachments.add(original)
@@ -221,12 +221,12 @@ describe('session tile attachment occurrence ownership', () => {
const replacement = makeAttachment()
const attach = deferred<{ attached: boolean; path: string }>()
- requestGateway.mockImplementation(async (method: string) => {
+ requestGateway.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === 'image.attach_bytes') {
return attach.promise
}
- return {}
+ return method === 'prompt.submit' ? { admission_id: params.submission_id, status: 'started' } : {}
})
scope.attachments.add(original)
@@ -258,12 +258,14 @@ describe('session tile attachment occurrence ownership', () => {
const replacement = makeUrlAttachment('new')
const submit = deferred<Record<string, never>>()
- requestGateway.mockImplementation(async (method: string) => {
+ requestGateway.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === 'prompt.submit') {
- return submit.promise
+ await submit.promise
+
+ return { admission_id: params.submission_id, status: 'started' }
}
- return {}
+ return method === 'prompt.submit' ? { admission_id: params.submission_id, status: 'started' } : {}
})
scope.attachments.add(original)
@@ -295,7 +297,7 @@ describe('session tile attachment occurrence ownership', () => {
const scope = createScope()
const original = makeFileAttachment()
- requestGateway.mockImplementation(async (method: string) => {
+ requestGateway.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === 'file.attach') {
return {
attached: true,
@@ -304,7 +306,7 @@ describe('session tile attachment occurrence ownership', () => {
}
}
- return {}
+ return method === 'prompt.submit' ? { admission_id: params.submission_id, status: 'started' } : {}
})
scope.attachments.add(original)
diff --git a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
index c65106dff46..f72609bebfd 100644
--- a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
+++ b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx
@@ -140,7 +140,7 @@ function answer(socket: MockGateway, method: string, params: Record<string, unkn
}
if (method === 'prompt.submit') {
- return { ok: true }
+ return { admission_id: params.submission_id, status: 'started' }
}
if (method === 'session.resume' || method === 'session.activate') {
diff --git a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
index f9060982294..c44effd10e0 100644
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
@@ -78,13 +78,14 @@ describe('useBackgroundQueueDrain', () => {
const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn(async () => true)
- enqueueQueuedPrompt('stored-session-a', { text: 'continue in the background', attachments: [] })
+ const entry = enqueueQueuedPrompt('stored-session-a', { text: 'continue in the background', attachments: [] })!
clearAllSessionStates()
render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)
await waitFor(() => {
expect(submitText).toHaveBeenCalledWith('continue in the background', {
+ submission_id: entry.id,
attachments: [],
fromQueue: true,
sessionId: 'rt-session-a',
@@ -183,12 +184,13 @@ describe('useBackgroundQueueDrain', () => {
const runtimeMap = { current: new Map<string, string>() }
const submitText = vi.fn(async () => true)
- enqueueQueuedPrompt('stored-session-a', { text: 'resume then send', attachments: [] })
+ const entry = enqueueQueuedPrompt('stored-session-a', { text: 'resume then send', attachments: [] })!
render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)
await waitFor(() => {
expect(submitText).toHaveBeenCalledWith('resume then send', {
+ submission_id: entry.id,
attachments: [],
fromQueue: true,
sessionId: null,
diff --git a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
index 8573ab9c8aa..38faacc164c 100644
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
@@ -112,7 +112,7 @@ export function useBackgroundQueueDrain({
.then(async () => {
const liveEntry = getQueuedPrompts(sessionKey).find(candidate => candidate.id === entry.id)
- if (!liveEntry) {
+ if (!liveEntry || liveEntry.serverStatus) {
return true
}
@@ -122,12 +122,14 @@ export function useBackgroundQueueDrain({
submitTextRef.current(liveEntry.text, {
attachments: liveEntry.attachments,
fromQueue: true,
+ submission_id: liveEntry.id,
+ ...(liveEntry.displayText ? { displayText: liveEntry.displayText } : {}),
sessionId: runtimeSessionId,
storedSessionId: sessionKey
})
)
- if (accepted === false) {
+ if (accepted !== true) {
return false
}
@@ -179,7 +181,7 @@ export function useBackgroundQueueDrain({
continue
}
- const entry = entries[0]
+ const entry = entries.find(candidate => !candidate.serverStatus)
if (!entry || (drainFailuresRef.current.get(entry.id) ?? 0) >= MAX_AUTO_DRAIN_ATTEMPTS) {
continue
diff --git a/apps/desktop/src/app/session/hooks/use-busy-input-mode.test.tsx b/apps/desktop/src/app/session/hooks/use-busy-input-mode.test.tsx
new file mode 100644
index 00000000000..472804b9194
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-busy-input-mode.test.tsx
@@ -0,0 +1,59 @@
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { $busyInputConfig } from '@/store/busy-input-mode'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $gatewayState } from '@/store/session'
+
+import { useBusyInputMode } from './use-busy-input-mode'
+
+vi.mock('@/store/session-request-router', () => ({
+ requestForSessionProfile: (
+ _owner: unknown,
+ request: (method: string, params: unknown) => Promise<unknown>,
+ method: string,
+ params: unknown
+ ) => request(method, params)
+}))
+
+afterEach(() => {
+ cleanup()
+ $busyInputConfig.set(null)
+ $activeGatewayProfile.set('default')
+ $gatewayState.set('closed')
+})
+
+it('uses only the current owner config and ignores a late response from the previous profile', async () => {
+ $gatewayState.set('open')
+ let resolveOld!: (value: { value: string }) => void
+
+ const request = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ resolveOld = resolve
+ })
+ )
+ .mockResolvedValue({ value: 'steer' })
+
+ const hook = renderHook(() =>
+ useBusyInputMode({ sessionId: 'runtime', storedSessionId: null, requestGateway: request })
+ )
+
+ expect(hook.result.current).toBeNull()
+ act(() => $activeGatewayProfile.set('other'))
+ await waitFor(() => expect(hook.result.current).toBe('steer'))
+ await act(async () => resolveOld({ value: 'queue' }))
+ expect(hook.result.current).toBe('steer')
+ act(() =>
+ $busyInputConfig.set({
+ owner: JSON.stringify([$connection.get()?.connectionId ?? '', 'other']),
+ connection: $connection.get(),
+ mode: 'queue'
+ })
+ )
+ expect(hook.result.current).toBe('queue')
+ act(() => $busyInputConfig.set({ owner: 'foreign-owner', connection: $connection.get(), mode: 'interrupt' }))
+ expect(hook.result.current).toBe('steer')
+})
diff --git a/apps/desktop/src/app/session/hooks/use-busy-input-mode.ts b/apps/desktop/src/app/session/hooks/use-busy-input-mode.ts
new file mode 100644
index 00000000000..f53447d0e3e
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-busy-input-mode.ts
@@ -0,0 +1,82 @@
+import { useStore } from '@nanostores/react'
+import { useEffect, useState } from 'react'
+
+import type { GatewayRequester } from '@/app/contrib/types'
+import {
+ $busyInputConfig,
+ type BusyInputMode,
+ busyInputOwnerKey,
+ normalizeBusyInputMode
+} from '@/store/busy-input-mode'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $gatewayState, knownSessionOwner, ownerLookupSessionRows } from '@/store/session'
+import { requestForSessionProfile } from '@/store/session-request-router'
+import { sessionTileOwnerRoute } from '@/store/session-states'
+
+export function useBusyInputMode({
+ sessionId,
+ storedSessionId,
+ requestGateway
+}: {
+ sessionId: string | null
+ storedSessionId: string | null
+ requestGateway: GatewayRequester
+}): BusyInputMode | null {
+ const config = useStore($busyInputConfig)
+ const connection = useStore($connection)
+ const profile = useStore($activeGatewayProfile)
+ const gatewayState = useStore($gatewayState)
+
+ const route = storedSessionId
+ ? (sessionTileOwnerRoute(storedSessionId) ?? knownSessionOwner(ownerLookupSessionRows(), storedSessionId))
+ : undefined
+
+ const connectionId = route && typeof route === 'object' ? route.connectionId : connection?.connectionId
+ const ownerProfile = route && typeof route === 'object' ? route.profile : route || profile
+ const targetProfile = route && typeof route === 'object' ? route.targetProfile : undefined
+ const owner = busyInputOwnerKey(connectionId, targetProfile || ownerProfile)
+
+ const [loaded, setLoaded] = useState<{ owner: string; connection: typeof connection; mode: BusyInputMode } | null>(
+ null
+ )
+
+ const configured = config?.owner === owner && config.connection === connection ? config.mode : null
+
+ useEffect(() => {
+ if (configured !== null || !sessionId || gatewayState !== 'open') {
+ return
+ }
+ let cancelled = false
+ const ownerRoute = connectionId ? { connectionId, profile: ownerProfile, targetProfile } : ownerProfile
+ void requestForSessionProfile<{ value?: unknown }>(ownerRoute, requestGateway, 'config.get', {
+ key: 'busy',
+ session_id: sessionId
+ })
+ .then(result => {
+ if (!cancelled && result && Object.hasOwn(result, 'value')) {
+ setLoaded({ owner, connection, mode: normalizeBusyInputMode(result.value) })
+ }
+ })
+ .catch(() => undefined)
+
+ return () => {
+ cancelled = true
+ }
+ }, [
+ configured,
+ connection,
+ connectionId,
+ gatewayState,
+ owner,
+ ownerProfile,
+ requestGateway,
+ sessionId,
+ targetProfile
+ ])
+
+ if (gatewayState !== 'open') {
+ return null
+ }
+
+ return configured ?? (loaded?.owner === owner && loaded.connection === connection ? loaded.mode : null)
+}
diff --git a/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts b/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts
index 3cd5b72f85b..aa4e144f93d 100644
--- a/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts
@@ -24,6 +24,7 @@ import { useHermesConfig } from './use-hermes-config'
vi.mock('@/hermes', () => ({
getHermesConfig: vi.fn(),
+ setApiRequestProfile: vi.fn(),
getHermesConfigDefaults: vi.fn().mockResolvedValue({})
}))
diff --git a/apps/desktop/src/app/session/hooks/use-hermes-config.ts b/apps/desktop/src/app/session/hooks/use-hermes-config.ts
index c560ee0d5b3..1e89073a8d7 100644
--- a/apps/desktop/src/app/session/hooks/use-hermes-config.ts
+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.ts
@@ -4,7 +4,10 @@ import { setTerminalFontFamilyFromConfig } from '@/app/right-sidebar/terminal/te
import { getHermesConfig, getHermesConfigDefaults } from '@/hermes'
import { BUILTIN_PERSONALITIES, normalizePersonalityValue, personalityNamesFromConfig } from '@/lib/chat-runtime'
import { normalize } from '@/lib/text'
+import { $busyInputConfig, busyInputOwnerKey, normalizeBusyInputMode } from '@/store/busy-input-mode'
import { setDisplayTimestampsFromConfig } from '@/store/display-timestamps'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection } from '@/store/session'
import {
getComposerSelectionGeneration,
getCurrentModelSource,
@@ -63,6 +66,8 @@ export function useHermesConfig({ activeSessionIdRef }: HermesConfigOptions) {
const profileRefreshEpoch = profileRefreshEpochRef.current
const selectionGeneration = getComposerSelectionGeneration()
+ const connection = $connection.get()
+ const profile = $activeGatewayProfile.get()
try {
const [config, defaults] = await Promise.all([getHermesConfig(), getHermesConfigDefaults().catch(() => ({}))])
@@ -137,6 +142,14 @@ export function useHermesConfig({ activeSessionIdRef }: HermesConfigOptions) {
return
}
+ if ($connection.get() === connection && $activeGatewayProfile.get() === profile) {
+ $busyInputConfig.set({
+ owner: busyInputOwnerKey(connection?.connectionId, profile),
+ connection,
+ mode: normalizeBusyInputMode(config.display?.busy_input_mode)
+ })
+ }
+
setDisplayTimestampsFromConfig(config.display?.timestamps)
setTerminalFontFamilyFromConfig(config.terminal?.font_family)
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/execution-authority.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/execution-authority.test.tsx
new file mode 100644
index 00000000000..5f88c01104f
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/execution-authority.test.tsx
@@ -0,0 +1,34 @@
+import { act, cleanup } from '@testing-library/react'
+import { afterEach, expect, it } from 'vitest'
+
+import { renderMessageStream } from './test-harness'
+
+afterEach(cleanup)
+
+it('rejects stale snapshots and terminal frames across generations and owner epochs', () => {
+ const stream = renderMessageStream('authority-session')
+
+ const send = (type: string, execution_epoch: string | undefined, execution_generation: number | undefined, running?: boolean) =>
+ act(() => stream.handleEvent({ type, session_id: 'authority-session', payload: { execution_epoch, execution_generation, running } }))
+
+ send('message.start', 'owner-a', 9)
+ send('session.info', 'owner-a', 8, false)
+ expect(stream.state().busy).toBe(true)
+ send('message.complete', undefined, undefined)
+ expect(stream.state().busy).toBe(true)
+ send('session.info', 'owner-b', 1, true)
+ send('message.complete', 'owner-a', 10)
+ expect(stream.state().busy).toBe(true)
+ send('session.info', 'owner-b', 1, false)
+ expect(stream.state().busy).toBe(false)
+ send('session.info', 'owner-b', 1, true)
+ expect(stream.state().busy).toBe(false)
+})
+
+it('accepts a versioned terminal snapshot before optimistic pre-start grace expires', () => {
+ const stream = renderMessageStream('early-terminal')
+ stream.states.set('early-terminal', { ...stream.state(), busy: true, awaitingResponse: true, turnLive: false, turnStartedAt: Date.now() })
+ act(() => stream.handleEvent({ type: 'session.info', session_id: 'early-terminal', payload: { execution_epoch: 'owner', execution_generation: 1, execution_state: 'error', running: false } }))
+ expect(stream.state().busy).toBe(false)
+ expect(stream.state().awaitingResponse).toBe(false)
+})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
index 572e5c138e1..048b6c3f7fd 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
@@ -2,6 +2,7 @@ import { registryBackendScopeKey } from '@hermes/shared'
import { useCallback, useEffect, useRef } from 'react'
import type { GatewayEventPayload } from '@/lib/chat-messages'
+import { acceptExecutionEvent } from '@/lib/execution-authority'
import {
approvalReplaySessionId,
resolveGatewayEventSessionId,
@@ -95,6 +96,7 @@ const HANDLERS: GatewayEventHandler[] = [
/** The gateway-event dispatcher, extracted from useMessageStream. */
export function useGatewayEventHandler(deps: GatewayEventDeps) {
+ const executionAuthorities = useRef(new Map())
const { activeSessionIdRef, compactedTurnRef, refreshHermesConfig, sessionStateByRuntimeIdRef } = deps
const unscopedStreamSessionIdRef = useRef<string | null>(null)
@@ -170,6 +172,9 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
}
const sessionId = route.sessionId
+ const authorityKey = `${registryBackendScopeKey(event.connectionId ?? null, event.profile ?? null)}\u0000${sessionId}`
+
+ if (sessionId && !acceptExecutionEvent(executionAuthorities.current, authorityKey, event.type, payload)) {return}
// Late stragglers: an unscoped stream event attributed via the
// active-session fallback (no pin) to a session that has no live turn
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
index 29a7b629ddc..b42e9304534 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
@@ -3,6 +3,7 @@ import { modelOptionsQueryKey } from '@/lib/model-options'
import { reconcileApprovalModeForProfile } from '@/store/approval-mode'
import { reconcileSessionCompacting } from '@/store/compaction'
import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'
+import { reconcilePendingSubmissions } from '@/store/pending-submissions'
import { followActiveSessionCwd } from '@/store/projects'
import {
$activeSessionId,
@@ -151,6 +152,11 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// subsequent isActiveEvent gate keeps matching (#93942 scenario B).
const rebound = maybeRebindPaneToRebuiltRuntime(ctx)
+ if (sessionId) {
+ const storedId = payload?.stored_session_id ?? sessionStateByRuntimeIdRef.current.get(sessionId)?.storedSessionId ?? sessionId
+ reconcilePendingSubmissions(storedId, (payload as Record<string, unknown>)?.pending_submissions)
+ }
+
// Apply session-scoped fields when the event targets the active
// session, OR when it's a global broadcast and we have no session.
const apply = (explicitSid ? isActiveEvent : !activeSessionIdRef.current) || rebound
@@ -342,7 +348,10 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
const withinPreStartGrace =
typeof armedAt === 'number' && Date.now() - armedAt < PRE_TURN_LIVE_SETTLE_GRACE_MS
- if (state.awaitingResponse && !state.sawAssistantPayload && !state.turnLive && withinPreStartGrace) {
+ const authoritative = typeof (payload as Record<string, unknown>)?.execution_epoch === 'string' &&
+ typeof (payload as Record<string, unknown>)?.execution_generation === 'number'
+
+ if (!authoritative && state.awaitingResponse && !state.sawAssistantPayload && !state.turnLive && withinPreStartGrace) {
return state
}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
index 0673798c18e..02f5082d6b3 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
@@ -41,6 +41,7 @@ import { uploadComposerAttachment, usePromptActions } from '.'
// never-settling in-flight promise from one test into the next.
beforeEach(() => {
clearSingleFlightSessionResumeState()
+ window.localStorage.removeItem('hermes.desktop.preparedSubmissions.v1')
})
vi.mock('@/hermes', () => ({
@@ -124,6 +125,7 @@ function Harness({
seedMessages,
seedStreamId,
seedTurnStartedAt,
+ rawAdmissionReceipts = false,
selectedStoredSessionIdRef: selectedStoredSessionIdRefProp,
storedSessionId,
activeSessionId,
@@ -149,6 +151,7 @@ function Harness({
seedMessages?: unknown[]
seedStreamId?: null | string
seedTurnStartedAt?: null | number
+ rawAdmissionReceipts?: boolean
selectedStoredSessionIdRef?: MutableRefObject<string | null>
storedSessionId?: null | string
activeSessionId?: null | string
@@ -198,7 +201,19 @@ function Harness({
handleSkinCommand: () => '',
openMemoryGraph: openMemoryGraph ?? (() => undefined),
refreshSessions,
- requestGateway,
+ // Older fixture peers acknowledged successful submits with an empty object.
+ // Keep those peers successful under the durable protocol; receipt tests opt
+ // out so missing/mismatched acknowledgements still exercise production.
+ requestGateway: async (method, params, timeoutMs) => {
+ const result = await (timeoutMs === undefined ? requestGateway(method, params) : requestGateway(method, params, timeoutMs))
+
+ if (!rawAdmissionReceipts && method === 'prompt.submit' && result && typeof result === 'object' &&
+ (Object.keys(result).length === 0 || ('ok' in result && result.ok === true))) {
+ return { admission_id: params?.submission_id, status: 'started' } as never
+ }
+
+ return result as never
+ },
resumeStoredSession: resumeStoredSession ?? (() => undefined),
runtimeIdByStoredSessionIdRef,
selectedStoredSessionIdRef,
@@ -249,6 +264,52 @@ function Harness({
return null
}
+describe('durable submit acknowledgement', () => {
+ it('retains a failed slash kickoff and forwards queued admission intent on retry', async () => {
+ $sessions.set([])
+ $connection.set(null)
+ $composerAttachments.set([])
+
+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'slash.exec') {return { type: 'skill', name: 'private-skill', message: 'expanded skill' } as never}
+
+ return { admission_id: params?.submission_id, status: 'unknown' } as never
+ })
+
+ let handle: HarnessHandle | null = null
+ await actRender(<Harness onReady={h => (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} />)
+ expect(await handle!.submitText('/private-skill', { fromQueue: true, submission_id: 'queued-skill' })).toBe(false)
+ expect(requestGateway.mock.calls.find(call => call[0] === 'prompt.submit')?.[1]).toMatchObject({ queued: true, submission_id: 'queued-skill' })
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it.each([
+ [{}, false],
+ [{ admission_id: 'other', status: 'queued' }, false],
+ [{ admission_id: 'entry-id', status: 'queued' }, true],
+ [{ admission_id: 'entry-id', status: 'started' }, true],
+ [{ admission_id: 'entry-id', status: 'terminal' }, true],
+ [{ admission_id: 'entry-id', status: 'unknown' }, false]
+ ])('requires the matching authoritative receipt: %j', async (receipt, accepted) => {
+ const requestGateway = vi.fn(async () => receipt as never)
+ let handle: HarnessHandle | null = null
+ await actRender(
+ <Harness onReady={h => (handle = h)} rawAdmissionReceipts refreshSessions={async () => undefined} requestGateway={requestGateway} />
+ )
+ const options = { fromQueue: true, submission_id: 'entry-id' }
+ expect(await handle!.submitText('keep this input', options)).toBe(accepted)
+ expect(requestGateway).toHaveBeenCalledWith(
+ 'prompt.submit',
+ expect.objectContaining({ submission_id: 'entry-id', queued: true }),
+ expect.any(Number)
+ )
+ })
+})
+
describe('usePromptActions /title', () => {
beforeEach(() => {
setSessions(() => [sessionInfo()])
@@ -1236,7 +1297,7 @@ describe('usePromptActions exec fallback error reporting', () => {
await handle!.submitText('/status')
- expect(requestGateway).toHaveBeenCalledWith('session.status', expect.anything(), undefined)
+ expect(requestGateway).toHaveBeenCalledWith('session.status', expect.anything())
expect(requestGateway).toHaveBeenCalledWith('slash.exec', expect.objectContaining({ command: 'status' }))
expect(renderedSeedTexts(seeds).some(text => text.includes('session status from slash worker'))).toBe(true)
})
@@ -1362,6 +1423,7 @@ describe('usePromptActions slash.exec dispatch payloads', () => {
})
expect(calls[1]?.params).toEqual({
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: 'write the implementation plan'
})
@@ -1961,7 +2023,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
expect(await handle!.submitText('continue remotely')).toBe(true)
expect(ambientRequest).toHaveBeenCalledWith(
'prompt.submit',
- { session_id: 'runtime-remote', text: 'continue remotely' },
+ { submission_id: expect.any(String), session_id: 'runtime-remote', text: 'continue remotely' },
1_800_000
)
expect(requestGatewayForAgent).not.toHaveBeenCalled()
@@ -1992,6 +2054,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
'prompt.submit',
{
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: 'hello after a stop'
},
1_800_000
@@ -2068,6 +2131,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
'prompt.submit',
{
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: 'stop! rude interruption',
interrupted: true
},
@@ -2079,6 +2143,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
'prompt.submit',
{
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: 'follow-up without a barge'
},
1_800_000
@@ -2109,6 +2174,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
{
queued: true,
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: 'queued message'
},
1_800_000
@@ -2146,6 +2212,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
{
queued: true,
session_id: 'rt-session-a',
+ submission_id: expect.any(String),
text: 'queued for background session'
},
1_800_000
@@ -2201,6 +2268,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
{
queued: true,
session_id: 'rt-session-b',
+ submission_id: expect.any(String),
text: 'queued for B mid-switch'
},
1_800_000
@@ -2245,6 +2313,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
{
queued: true,
session_id: 'rt-session-b-live',
+ submission_id: expect.any(String),
text: 'queued for B, B already re-bound'
},
1_800_000
@@ -2287,6 +2356,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
'prompt.submit',
{
session_id: 'rt-tab',
+ submission_id: expect.any(String),
text: 'kickoff for the tab'
},
1_800_000
@@ -2339,6 +2409,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
{
queued: true,
session_id: 'rt-session-a-rebound',
+ submission_id: expect.any(String),
text: 'queued for background session'
},
1_800_000
@@ -2390,6 +2461,7 @@ describe('usePromptActions submit / queue drain semantics', () => {
{
queued: true,
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: 'please send me'
},
1_800_000
@@ -2911,6 +2983,7 @@ describe('usePromptActions file attachment sync', () => {
})
expect(calls[1]?.params).toEqual({
session_id: RUNTIME_SESSION_ID,
+ submission_id: expect.any(String),
text: '@file:.hermes/desktop-attachments/report.txt\n\nconvert this to epub'
})
})
@@ -2965,7 +3038,11 @@ describe('usePromptActions file attachment sync', () => {
})
expect(calls[1]).toEqual({
method: 'prompt.submit',
- params: { session_id: RUNTIME_SESSION_ID, text: '@file:.hermes/desktop-attachments/report.txt\n\nsummarize' }
+ params: {
+ submission_id: expect.any(String),
+ session_id: RUNTIME_SESSION_ID,
+ text: '@file:.hermes/desktop-attachments/report.txt\n\nsummarize'
+ }
})
})
@@ -3343,7 +3420,11 @@ describe('usePromptActions file attachment sync', () => {
expect(calls[0]?.params).not.toHaveProperty('data_url')
expect(calls[1]).toEqual({
method: 'prompt.submit',
- params: { session_id: RUNTIME_SESSION_ID, text: '@file:data/report.txt\n\nsummarize' }
+ params: {
+ submission_id: expect.any(String),
+ session_id: RUNTIME_SESSION_ID,
+ text: '@file:data/report.txt\n\nsummarize'
+ }
})
})
})
@@ -3465,7 +3546,11 @@ describe('usePromptActions sleep/wake session recovery', () => {
// First submit (stale id) → session.resume (stored id) → retry submit (fresh id).
expect(calls.map(c => c.method)).toEqual(['prompt.submit', 'session.resume', 'prompt.submit'])
expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop', omit_messages: true })
- expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID, text: 'message after wake' })
+ expect(calls[2]?.params).toEqual({
+ submission_id: expect.any(String),
+ session_id: RECOVERED_SESSION_ID,
+ text: 'message after wake'
+ })
})
it('publishes the recovered runtime binding before retrying through the remote owner router', async () => {
@@ -3515,7 +3600,11 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(await handle!.submitText('remote follow-up after reap')).toBe(true)
expect(bindingPublished).toBe(true)
expect(calls.map(call => call.method)).toEqual(['prompt.submit', 'session.resume', 'prompt.submit'])
- expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID, text: 'remote follow-up after reap' })
+ expect(calls[2]?.params).toEqual({
+ submission_id: expect.any(String),
+ session_id: RECOVERED_SESSION_ID,
+ text: 'remote follow-up after reap'
+ })
})
it('resumes the stored session and retries once when reloadFromMessage (regenerate) reports "session not found"', async () => {
@@ -3733,6 +3822,7 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(calls[0]?.params).toEqual({
queued: true,
session_id: 'rt-background-stale',
+ submission_id: expect.any(String),
text: 'queued background message after wake'
})
expect(calls[1]?.params).toEqual({
@@ -3743,6 +3833,7 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(calls[2]?.params).toEqual({
queued: true,
session_id: RECOVERED_SESSION_ID,
+ submission_id: expect.any(String),
text: 'queued background message after wake'
})
expect(handle!.activeSessionIdRef.current).toBe(RUNTIME_SESSION_ID)
@@ -3930,6 +4021,7 @@ describe('usePromptActions sleep/wake session recovery', () => {
})
expect(calls[2]?.params).toEqual({
session_id: RECOVERED_SESSION_ID,
+ submission_id: expect.any(String),
text: 'message during starved loop'
})
})
@@ -4051,7 +4143,11 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(createBackendSessionForSend).not.toHaveBeenCalled()
expect(requestGateway).toHaveBeenCalledWith(
'prompt.submit',
- { session_id: RECOVERED_SESSION_ID, text: 'follow-up while the profile route is rebinding' },
+ {
+ submission_id: expect.any(String),
+ session_id: RECOVERED_SESSION_ID,
+ text: 'follow-up while the profile route is rebinding'
+ },
1_800_000
)
})
@@ -4089,7 +4185,11 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(resumeStoredSession).toHaveBeenCalledWith(STORED_SESSION_ID)
expect(requestGateway).toHaveBeenCalledWith(
'prompt.submit',
- { session_id: RECOVERED_SESSION_ID, text: 'stay in the routed profile session' },
+ {
+ submission_id: expect.any(String),
+ session_id: RECOVERED_SESSION_ID,
+ text: 'stay in the routed profile session'
+ },
1_800_000
)
})
@@ -4121,7 +4221,7 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(resumeStoredSession).not.toHaveBeenCalled()
expect(requestGateway).toHaveBeenCalledWith(
'prompt.submit',
- { session_id: RECOVERED_SESSION_ID, text: 'normal follow-up' },
+ { submission_id: expect.any(String), session_id: RECOVERED_SESSION_ID, text: 'normal follow-up' },
1_800_000
)
})
@@ -4178,7 +4278,7 @@ describe('usePromptActions sleep/wake session recovery', () => {
expect(await handle!.submitText('retry after recovery')).toBe(true)
expect(requestGateway).toHaveBeenCalledWith(
'prompt.submit',
- { session_id: RECOVERED_SESSION_ID, text: 'retry after recovery' },
+ { submission_id: expect.any(String), session_id: RECOVERED_SESSION_ID, text: 'retry after recovery' },
1_800_000
)
})
@@ -4605,7 +4705,7 @@ describe('usePromptActions new-chat first-send delivery (#63078)', () => {
expect(calls).toEqual([
{
method: 'prompt.submit',
- params: { session_id: NEW_RUNTIME_ID, text: 'first message of a new chat' }
+ params: { submission_id: expect.any(String), session_id: NEW_RUNTIME_ID, text: 'first message of a new chat' }
}
])
})
@@ -4663,6 +4763,7 @@ describe('usePromptActions new-chat first-send delivery (#63078)', () => {
'prompt.submit',
{
session_id: NEW_RUNTIME_ID,
+ submission_id: expect.any(String),
text: 'hello'
},
1_800_000
@@ -4958,7 +5059,11 @@ describe('usePromptActions busy-gateway churn tolerance (#64327)', () => {
},
{
method: 'prompt.submit',
- params: { session_id: RESUMED_RUNTIME_ID, text: 'deliver despite lagging local publication' }
+ params: {
+ submission_id: expect.any(String),
+ session_id: RESUMED_RUNTIME_ID,
+ text: 'deliver despite lagging local publication'
+ }
}
])
})
@@ -5037,7 +5142,12 @@ describe('usePromptActions busy-gateway churn tolerance (#64327)', () => {
},
{
method: 'prompt.submit',
- params: { session_id: QUEUED_RUNTIME_ID, text: 'queued prompt for C', queued: true }
+ params: {
+ submission_id: expect.any(String),
+ session_id: QUEUED_RUNTIME_ID,
+ text: 'queued prompt for C',
+ queued: true
+ }
}
])
// No prompt or state write ever touches B, and no foreground
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.ts
index b82d28c0150..c8edbb2f157 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
@@ -66,6 +66,7 @@ import {
type SurvivorUserRowIds
} from './rewind'
import { useSlashCommand } from './slash'
+import { captureSubmissionDestination } from './submission-destination'
import { useSubmitPrompt } from './submit'
import {
blobToDataUrl,
@@ -131,7 +132,13 @@ export async function uploadComposerAttachment(
terminalBackend?: string
}
): Promise<ComposerAttachment> {
- const { backendCwd, remote, requestGateway, storedSessionId, onSessionRecovered, terminalBackend } = opts
+ const { backendCwd, remote, storedSessionId, onSessionRecovered, terminalBackend } = opts
+
+ const requestGateway = captureSubmissionDestination(
+ storedSessionId ?? opts.sessionId,
+ opts.requestGateway
+ ).requestGateway
+
const path = attachment.path ?? ''
const label = attachment.label || pathLabel(path)
const uploadBytes = remote || attachmentPathNeedsUpload(path, backendCwd, terminalBackend)
@@ -336,18 +343,34 @@ export function usePromptActions({
async (
sessionId: string,
attachments: ComposerAttachment[],
- options: { updateComposerAttachments?: boolean } = {}
+ options: {
+ updateComposerAttachments?: boolean
+ storedSessionId?: string | null
+ requestGateway?: GatewayRequest
+ } = {}
): Promise<{ attachments: ComposerAttachment[]; sessionId: string }> => {
const updateComposerAttachments = options.updateComposerAttachments ?? true
- const storedSessionId = selectedStoredSessionIdRef.current
+
+ const storedSessionId =
+ options.storedSessionId !== undefined ? options.storedSessionId : selectedStoredSessionIdRef.current
+
+ const uploadRequest =
+ options.requestGateway ??
+ captureSubmissionDestination(storedSessionId ?? sessionId, requestGateway).requestGateway
+
+ const backendCwd = $currentCwd.get()
+ const terminalBackend = $terminalBackend.get()
const remote = isSessionRemote(storedSessionId ?? sessionId)
let liveSessionId = sessionId
const synced: ComposerAttachment[] = []
const onSessionRecovered = (recoveredId: string) => {
liveSessionId = recoveredId
- activeSessionIdRef.current = recoveredId
- setActiveSessionId(recoveredId)
+
+ if (activeSessionIdRef.current === sessionId) {
+ activeSessionIdRef.current = recoveredId
+ setActiveSessionId(recoveredId)
+ }
}
for (const original of attachments) {
@@ -378,13 +401,13 @@ export function usePromptActions({
if (attachment.kind === 'image' || attachment.kind === 'file') {
const nextAttachment = await uploadComposerAttachment(attachment, {
- backendCwd: $currentCwd.get(),
+ backendCwd,
remote,
- requestGateway,
+ requestGateway: uploadRequest,
sessionId: liveSessionId,
storedSessionId,
onSessionRecovered,
- terminalBackend: $terminalBackend.get()
+ terminalBackend
})
// Update-only: never resurrect a chip the user removed mid-upload.
@@ -613,9 +636,7 @@ export function usePromptActions({
triggerHaptic('selection')
// Forward the explicit target (background queue drain, tile) — dropping
// it ran the command against whatever chat happened to be in front.
- await executeSlashCommand(visibleText, options?.sessionId ? { sessionId: options.sessionId } : undefined)
-
- return true
+ return await executeSlashCommand(visibleText, options)
}
return await submitPromptText(rawText, options)
@@ -734,7 +755,7 @@ export function usePromptActions({
// completed work intact. During a tool it waits for the safe result boundary.
// Returns false when the turn raced to completion so the composer can queue.
const redirectPrompt = useCallback(
- async (rawText: string): Promise<boolean> => {
+ async (rawText: string, mode: 'interrupt' | 'steer' = 'interrupt'): Promise<boolean> => {
const text = sanitizeComposerInput(rawText).trim()
// Ref, not the closure-captured prop — see cancelRun above. A redirect
// reaches the live model mid-turn, so a stale target delivers the user's
@@ -756,7 +777,9 @@ export function usePromptActions({
// gateway, in arrival order: sealed already-streamed output above,
// correction bubble below it, post-redirect deltas below that
// (#73793, #83151).
- const messageId = appendSessionTextMessage(id, 'user', text, undefined, { appendAfterActiveReply: true })
+ const messageId = appendSessionTextMessage(id, 'user', text, undefined, {
+ appendAfterActiveReply: mode === 'interrupt'
+ })
const discardOptimisticMessage = () =>
updateSessionState(id, state => ({
@@ -774,7 +797,10 @@ export function usePromptActions({
})
try {
- const result = await requestGateway<SessionRedirectResponse>('session.redirect', { session_id: id, text })
+ const result = await requestGateway<SessionRedirectResponse>(
+ mode === 'steer' ? 'session.steer' : 'session.redirect',
+ { session_id: id, text }
+ )
if (result?.status === 'redirected') {
triggerHaptic('submit')
@@ -785,7 +811,10 @@ export function usePromptActions({
if (result?.status === 'queued') {
// Build-window redirects become the next turn, not part of the
// active reply, so retain the optimistic row at the tail.
- moveOptimisticMessageToEnd()
+ if (mode === 'interrupt') {
+ moveOptimisticMessageToEnd()
+ }
+
triggerHaptic('submit')
return true
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts
new file mode 100644
index 00000000000..54dd1b1c1e4
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts
@@ -0,0 +1,30 @@
+import { afterEach, expect, test, vi } from 'vitest'
+
+import { type PreparedSubmission, readPreparedSubmission, removePreparedSubmission, writePreparedSubmission } from './prepared-submissions'
+
+afterEach(() => { vi.unstubAllGlobals(); localStorage.clear() })
+
+test('native preparation waits for acknowledgement and never downgrades a write failure to browser storage', async () => {
+ let ack!: () => void
+ const gate = new Promise<void>(resolve => { ack = resolve })
+ const entry = { id: 'a', text: 'Ω\n exact', attachments: [], params: { session_id: 'live' } } as unknown as PreparedSubmission
+ const native = { read: vi.fn(async () => JSON.stringify({ key: entry })), update: vi.fn(() => gate) }
+ vi.stubGlobal('hermesDesktop', { preparedSubmissions: native })
+ let finished = false
+ const writing = writePreparedSubmission('key', entry).then(() => { finished = true })
+ await Promise.resolve()
+ expect(finished).toBe(false)
+ expect(native.update).toHaveBeenCalledWith('key', JSON.stringify(entry))
+ ack(); await writing
+ expect(await readPreparedSubmission('key')).toEqual(entry)
+ native.update.mockRejectedValueOnce(new Error('disk full'))
+ await expect(writePreparedSubmission('key', entry)).rejects.toThrow('disk full')
+ expect(localStorage.length).toBe(0)
+ await removePreparedSubmission('key')
+ expect(native.update).toHaveBeenLastCalledWith('key', null)
+ vi.stubGlobal('hermesDesktop', undefined)
+ await writePreparedSubmission('key', entry)
+ expect(await readPreparedSubmission('key')).toEqual(entry)
+ await removePreparedSubmission('key')
+ expect(await readPreparedSubmission('key')).toBeUndefined()
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts
new file mode 100644
index 00000000000..c58ac013f32
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts
@@ -0,0 +1,87 @@
+import type { ComposerAttachment } from '@/store/composer'
+import type { SessionOwnerScope } from '@/store/session-request-router'
+
+import type { SubmissionDestination } from './submission-destination'
+import type { SubmitTextOptions } from './utils'
+
+const STORAGE_KEY = 'hermes.desktop.preparedSubmissions.v1'
+
+export interface PreparedSubmission {
+ id: string
+ owner: SessionOwnerScope
+ attachments: ComposerAttachment[]
+ text: string
+ displayText?: string
+ params: Record<string, unknown>
+ legacyAttempted?: boolean
+}
+
+// A journal, not an automatic outbox. Only an explicit retry may reuse an
+// uncertain admission. Read storage each time so a remount cannot lose it.
+async function readJournal(): Promise<Record<string, PreparedSubmission>> {
+ const native = window.hermesDesktop?.preparedSubmissions
+
+ const parsed: unknown = JSON.parse(native
+ ? await native.read()
+ : window.localStorage.getItem(STORAGE_KEY) || '{}')
+
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('Invalid prepared submission journal')
+ }
+
+ return parsed as Record<string, PreparedSubmission>
+}
+
+export function preparedSubmissionKey(
+ target: string | null | undefined,
+ destination: SubmissionDestination,
+ rawText: string,
+ attachments: ComposerAttachment[],
+ options?: SubmitTextOptions
+): string {
+ return JSON.stringify([
+ destination.scopeKey,
+ target,
+ options?.retryText ?? rawText,
+ attachments.map(a => a.occurrenceId ?? a.id),
+ options?.displayKind,
+ Boolean(options?.fromQueue),
+ // Slash expands once, then retries the prepared wire payload, not a new
+ // generated ID/expansion. Explicit queue IDs remain distinct intents.
+ options?.retryText && !options.fromQueue ? null : options?.submission_id
+ ])
+}
+
+export async function readPreparedSubmission(key: string): Promise<PreparedSubmission | undefined> {
+ return (await readJournal())[key]
+}
+
+export async function writePreparedSubmission(key: string, entry: PreparedSubmission): Promise<void> {
+ const native = window.hermesDesktop?.preparedSubmissions
+
+ if (native) {
+ await native.update(key, JSON.stringify(entry))
+
+ return
+ }
+
+ const journal: Record<string, PreparedSubmission> = JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}')
+ journal[key] = entry
+ // Browser-only clients retain reload recovery, not a process-crash guarantee.
+ // Native write failures never fall back here: sending requires their ACK.
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))
+}
+
+export async function removePreparedSubmission(key: string): Promise<void> {
+ const native = window.hermesDesktop?.preparedSubmissions
+
+ if (native) {
+ await native.update(key, null)
+
+ return
+ }
+
+ const journal: Record<string, PreparedSubmission> = JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}')
+ delete journal[key]
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))
+}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.test.ts
new file mode 100644
index 00000000000..08c5dcdfb2d
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.test.ts
@@ -0,0 +1,90 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { en } from '@/i18n/en'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import * as queue from '@/store/composer-queue'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $sessions } from '@/store/session'
+import { $sessionStates } from '@/store/session-states'
+
+import { queueKickoffIfSessionBusy } from './queue-if-busy'
+import { useSlashCommand } from './slash'
+import type { GatewayRequest } from './utils'
+
+beforeEach(() => {
+ $sessions.set([])
+ $connection.set(null)
+ $activeGatewayProfile.set('default')
+ $sessionStates.set({
+ 'runtime-a': { ...createClientSessionState(), busy: true, storedSessionId: 'stored-a' }
+ })
+ queue.$queuedPromptsBySession.set({})
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ queue.$queuedPromptsBySession.set({})
+ $sessionStates.set({})
+})
+
+it('forwards kickoff identity to queue admission and leaves idle targets alone', () => {
+ const enqueue = vi.spyOn(queue, 'enqueueQueuedPrompt')
+ const input = { id: 'caller-kickoff', sessionId: 'runtime-a', text: 'expanded skill', displayText: '/work' }
+
+ expect(queueKickoffIfSessionBusy(input)).toBe('queued')
+ expect(enqueue).toHaveBeenCalledWith('stored-a', {
+ id: input.id,
+ text: input.text,
+ displayText: input.displayText,
+ attachments: []
+ })
+ expect(queueKickoffIfSessionBusy({ ...input, sessionId: 'idle-target', foregroundBusy: true })).toBe('idle')
+ expect(enqueue).toHaveBeenCalledTimes(1)
+})
+
+it('keeps caller-provided and generated slash IDs when a busy target queues the expanded skill', async () => {
+ const enqueue = vi.spyOn(queue, 'enqueueQueuedPrompt')
+ const generatedId = 'a6c67295-d5e0-4edb-b6f0-8aeb144efb77'
+ vi.spyOn(crypto, 'randomUUID').mockReturnValue(generatedId)
+ const submitPromptText = vi.fn(async () => true)
+
+ const { result } = renderHook(() =>
+ useSlashCommand({
+ activeSessionIdRef: { current: 'runtime-a' },
+ selectedStoredSessionIdRef: { current: 'stored-a' },
+ busyRef: { current: false },
+ copy: en.desktop,
+ createBackendSessionForSend: async () => null,
+ getRoutedStoredSessionId: () => 'stored-a',
+ getRuntimeIdForStoredSession: () => 'runtime-a',
+ requestGateway: vi.fn(async () => ({ type: 'skill', name: 'work', message: 'expanded skill' })) as GatewayRequest,
+ resumeStoredSession: vi.fn(),
+ updateSessionState: vi.fn((_sid, updater) => updater(createClientSessionState())),
+ submitPromptText,
+ appendSessionTextMessage: vi.fn(),
+ branchCurrentSession: async () => true,
+ handleSkinCommand: () => '',
+ handoffSession: async () => ({ ok: true }),
+ openMemoryGraph: vi.fn(),
+ refreshSessions: async () => undefined,
+ startFreshSessionDraft: vi.fn()
+ })
+ )
+
+ for (const submissionId of ['caller-slash', undefined]) {
+ await act(async () => {
+ await result.current('/work', { submission_id: submissionId })
+ })
+ expect(enqueue).toHaveBeenLastCalledWith(
+ 'stored-a',
+ expect.objectContaining({
+ id: submissionId ?? generatedId,
+ text: 'expanded skill'
+ })
+ )
+ }
+
+ expect(submitPromptText).not.toHaveBeenCalled()
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.ts
index e0f8edebe05..dbcb57686cc 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.ts
@@ -5,6 +5,7 @@ import { $sessionStates } from '@/store/session-states'
import { isTargetSessionBusy } from './utils'
export interface QueueIfBusyInput {
+ id?: string
/** Runtime session the command was resolved against. */
sessionId: string
/** Stored session the composer queue is keyed by; defaults to the runtime id
@@ -28,6 +29,7 @@ export interface QueueIfBusyInput {
export function queueKickoffIfSessionBusy({
displayText,
foregroundBusy = false,
+ id,
sessionId,
storedSessionId,
text
@@ -41,5 +43,5 @@ export function queueKickoffIfSessionBusy({
const stored = storedSessionId ?? states[sessionId]?.storedSessionId ?? null
const queueKey = resolveComposerSessionKey(stored, $sessions.get()) || stored || sessionId
- return enqueueQueuedPrompt(queueKey, { attachments: [], displayText, text }) ? 'queued' : 'busy'
+ return enqueueQueuedPrompt(queueKey, { attachments: [], displayText, id, text }) ? 'queued' : 'busy'
}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index a54a7bdfb6c..f907259a235 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
@@ -17,7 +17,7 @@ import {
import { isMissingRpcMethod } from '@/lib/gateway-rpc'
import { setSessionYolo } from '@/lib/yolo-session'
import { openCommandPalettePage } from '@/store/command-palette'
-import { setComposerDraft } from '@/store/composer'
+import { $composerAttachments, setComposerDraft } from '@/store/composer'
import { applyGoalStatusText } from '@/store/goals'
import { dismissNotification, notify, notifyError } from '@/store/notifications'
import { setPetScale } from '@/store/pet-gallery'
@@ -33,6 +33,7 @@ import {
$connection,
$sessions,
$yoloActive,
+ resolveComposerSessionKey,
setActiveSessionId,
setCurrentUsage,
setModelPickerOpen,
@@ -59,8 +60,10 @@ import type {
SlashExecResponse
} from '../../../types'
+import { preparedSubmissionKey, readPreparedSubmission } from './prepared-submissions'
import { queueKickoffIfSessionBusy } from './queue-if-busy'
import { resolveTargetSessionId } from './resolve-target-session'
+import { captureSubmissionDestination } from './submission-destination'
import {
type GatewayRequest,
isSessionIdCandidate,
@@ -174,7 +177,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {
handoffSession,
openMemoryGraph,
refreshSessions,
- requestGateway,
+ requestGateway: ambientRequestGateway,
resumeStoredSession,
selectedStoredSessionIdRef,
startFreshSessionDraft,
@@ -185,7 +188,46 @@ export function useSlashCommand(deps: SlashCommandDeps) {
const compressInFlightRef = useRef(new Set<string>())
return useCallback(
- async (rawCommand: string, options?: { sessionId?: string; recordInput?: boolean }) => {
+ async (rawCommand: string, options?: SubmitTextOptions & { recordInput?: boolean }) => {
+ const initialRuntimeId = options?.sessionId ?? activeSessionIdRef.current
+ const initialSelectedId = selectedStoredSessionIdRef.current
+ const initialRoutedId = getRoutedStoredSessionId()
+
+ let submitted = true
+
+ const initialStoredId =
+ options?.storedSessionId ??
+ (options?.sessionId
+ ? ($sessionStates.get()[options.sessionId]?.storedSessionId ?? null)
+ : (initialRoutedId ?? initialSelectedId))
+
+ const destination =
+ options?.destination ?? captureSubmissionDestination(initialStoredId ?? initialRuntimeId, ambientRequestGateway)
+
+ const requestGateway = destination.requestGateway
+ const retryOptions = { ...options, retryText: rawCommand }
+
+ try {
+ 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
+ })
+ }
+ } catch (err) {
+ notifyError(err, copy.promptFailed)
+
+ return false
+ }
+
+ const submissionId = options?.submission_id ?? crypto.randomUUID()
+
// Resolve the session this command targets through the SHARED ladder that
// submit.ts uses. A slash command runs backend commands against a runtime
// session, and per-session state (`/goal`, `/usage`, `/status`) is keyed by
@@ -197,13 +239,13 @@ export function useSlashCommand(deps: SlashCommandDeps) {
// goal" for a goal that was live on the real chat.
const ensureSessionId = async (sessionHint?: string, preview?: null | string) =>
resolveTargetSessionId({
- activeRuntimeId: activeSessionIdRef.current,
+ activeRuntimeId: initialRuntimeId,
createSession: () => createBackendSessionForSend(preview),
explicitRuntimeId: sessionHint,
getRuntimeIdForStoredSession,
requestGateway,
- routedStoredSessionId: getRoutedStoredSessionId(),
- selectedStoredSessionId: selectedStoredSessionIdRef.current
+ routedStoredSessionId: initialRoutedId,
+ selectedStoredSessionId: initialSelectedId
})
// Resolve the target session plus a writer for inline slash output, or
@@ -232,7 +274,8 @@ 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 ?? selectedStoredSessionIdRef.current
+ const storedSessionId = $sessionStates.get()[sessionId]?.storedSessionId ?? initialStoredId ??
+ (!initialRuntimeId && activeSessionIdRef.current === sessionId ? selectedStoredSessionIdRef.current : null)
// Header carries the command token only. The full invocation would
// duplicate long args — `/goal <prose>` echoed the whole goal in the
@@ -348,13 +391,16 @@ export function useSlashCommand(deps: SlashCommandDeps) {
// rather than re-reading the globals — a session switch between
// dispatch and this branch would otherwise queue the kickoff on
// whichever chat is now in front (#63352).
- const queued = queueKickoffIfSessionBusy({
- displayText,
- foregroundBusy: busyRef.current,
- sessionId,
- storedSessionId,
- text: message
- })
+ const queued = options?.fromQueue
+ ? 'idle'
+ : queueKickoffIfSessionBusy({
+ displayText,
+ foregroundBusy: busyRef.current,
+ id: submissionId,
+ sessionId,
+ storedSessionId,
+ text: message
+ })
if (queued !== 'idle') {
renderSlashOutput(
@@ -374,7 +420,14 @@ export function useSlashCommand(deps: SlashCommandDeps) {
// its kickoff as a user message into whatever conversation was on
// screen. Every other target the dispatcher serves (tile, background
// queue drain, a session created by this very call) had the same leak.
- await submitPromptText(message, { sessionId, storedSessionId, displayText })
+ submitted = await submitPromptText(message, {
+ ...retryOptions,
+ sessionId,
+ storedSessionId,
+ displayText,
+ submission_id: submissionId,
+ destination
+ })
}
try {
@@ -1215,7 +1268,9 @@ export function useSlashCommand(deps: SlashCommandDeps) {
}
}
- await runSlash(rawCommand, options?.sessionId, options?.recordInput ?? true)
+ await runSlash(rawCommand, options?.sessionId ?? undefined, options?.recordInput ?? true)
+
+ return submitted
},
[
activeSessionIdRef,
@@ -1230,7 +1285,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {
handoffSession,
openMemoryGraph,
refreshSessions,
- requestGateway,
+ ambientRequestGateway,
resumeStoredSession,
selectedStoredSessionIdRef,
startFreshSessionDraft,
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsx
new file mode 100644
index 00000000000..32f6f7c51f7
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.test.tsx
@@ -0,0 +1,464 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { en } from '@/i18n/en'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $sessions } from '@/store/session'
+import { $sessionStates } from '@/store/session-states'
+
+import { useSlashCommand } from './slash'
+import { captureSubmissionDestination } from './submission-destination'
+import { useSubmitPrompt } from './submit'
+import type { GatewayRequest } from './utils'
+
+const wire = vi.hoisted(() => ({ request: vi.fn(), release: vi.fn() }))
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ requestGatewayForAgent: wire.request,
+ requestGatewayForProfile: wire.request,
+ retainGatewayForSessionTurn: vi.fn(async () => wire.release)
+}))
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+
+ const promise = new Promise<T>(done => {
+ resolve = done
+ })
+
+ return { promise, resolve }
+}
+
+function setup() {
+ const activeSessionIdRef = { current: 'runtime-a' as string | null }
+ const selectedStoredSessionIdRef = { current: 'stored-a' as string | null }
+
+ const requestGateway = vi.fn(
+ async (_method: string, params?: Record<string, unknown>) =>
+ ({ admission_id: params?.submission_id, status: 'started' }) as never
+ )
+
+ const busyRef = { current: false }
+ const state = createClientSessionState()
+
+ const deps = {
+ activeSessionIdRef,
+ selectedStoredSessionIdRef,
+ busyRef,
+ copy: en.desktop,
+ createBackendSessionForSend: vi.fn(async () => null),
+ getRoutedStoredSessionId: () => null,
+ getRuntimeIdForStoredSession: () => 'runtime-a',
+ getRouteToken: () => 'same-route',
+ requestGateway: requestGateway as GatewayRequest,
+ runtimeIdByStoredSessionIdRef: { current: new Map([['stored-a', 'runtime-a']]) },
+ resumeStoredSession: vi.fn(),
+ syncAttachmentsForSubmit: vi.fn(async (sessionId: string) => ({ sessionId, attachments: [] })),
+ updateSessionState: vi.fn((_sid, updater) => updater(state))
+ }
+
+ return { deps, requestGateway }
+}
+
+beforeEach(() => {
+ window.localStorage.clear()
+ $sessions.set([])
+ $sessionStates.set({})
+ $connection.set(null)
+ $activeGatewayProfile.set('default')
+ wire.request.mockReset()
+ wire.request.mockImplementation(async (_connection, _profile, _method, params) => ({
+ admission_id: params?.submission_id,
+ status: 'started'
+ }))
+})
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+describe('submission intent destinations', () => {
+ it('allows presentation and registry metadata replacement on the same authority', async () => {
+ const connection = {
+ baseUrl: 'http://localhost:1',
+ wsUrl: 'ws://localhost:1/ws',
+ token: 'secret',
+ connectionId: 'local',
+ mode: 'local',
+ profile: 'default'
+ }
+
+ $connection.set(connection as never)
+ const request = vi.fn(async () => ({ ok: true }))
+ const captured = captureSubmissionDestination(null, request as GatewayRequest)
+ $connection.set({ ...connection, registryScoped: true, isVisible: false } as never)
+ await expect(captured.requestGateway('prompt.submit', { text: 'hello' })).resolves.toEqual({ ok: true })
+ expect(request).toHaveBeenCalledOnce()
+ })
+
+ it('rejects actual endpoint, credential, connection and profile changes', async () => {
+ const connection = {
+ baseUrl: 'http://localhost:1',
+ wsUrl: 'ws://localhost:1/ws',
+ token: 'secret',
+ connectionId: 'local',
+ mode: 'local',
+ profile: 'default'
+ }
+
+ const request = vi.fn(async () => ({}))
+
+ for (const change of [
+ { baseUrl: 'http://other' },
+ { wsUrl: 'ws://other/ws' },
+ { token: 'other' },
+ { connectionId: 'other' },
+ { profile: 'other' },
+ { mode: 'remote' }
+ ]) {
+ $connection.set(connection as never)
+ const captured = captureSubmissionDestination(null, request as GatewayRequest)
+ $connection.set({ ...connection, ...change } as never)
+ await expect(captured.requestGateway('prompt.submit')).rejects.toThrow('Submission destination changed')
+ }
+
+ expect(request).not.toHaveBeenCalled()
+ })
+ it('reuses a prepared direct submission after ambiguous failure without restaging attachments', async () => {
+ const { deps, requestGateway } = setup()
+ requestGateway.mockRejectedValueOnce(new Error('connection closed'))
+ let hook = renderHook(() => useSubmitPrompt(deps))
+ await act(async () => {
+ expect(await hook.result.current('retry me')).toBe(false)
+ })
+ const journal = window.localStorage.getItem('hermes.desktop.preparedSubmissions.v1')
+ expect(journal).toContain('retry me')
+ hook.unmount()
+ window.localStorage.clear()
+ window.localStorage.setItem('hermes.desktop.preparedSubmissions.v1', journal!)
+ // A same-text send in another profile/session is a different intent; it
+ // must neither reuse nor retire the original uncertain admission.
+ $activeGatewayProfile.set('bob')
+ deps.selectedStoredSessionIdRef.current = 'stored-b'
+ deps.activeSessionIdRef.current = 'runtime-b'
+ deps.runtimeIdByStoredSessionIdRef.current.set('stored-b', 'runtime-b')
+ hook = renderHook(() => useSubmitPrompt(deps))
+ await act(async () => {
+ expect(await hook.result.current('retry me')).toBe(true)
+ })
+ expect(requestGateway.mock.calls[1][1]?.submission_id).not.toBe(requestGateway.mock.calls[0][1]?.submission_id)
+ hook.unmount()
+ $activeGatewayProfile.set('default')
+ deps.selectedStoredSessionIdRef.current = 'stored-a'
+ deps.activeSessionIdRef.current = 'runtime-a'
+ hook = renderHook(() => useSubmitPrompt(deps))
+ const { result } = hook
+ await act(async () => {
+ expect(await result.current('retry me')).toBe(true)
+ })
+
+ const calls = requestGateway.mock.calls.filter(
+ call => call[0] === 'prompt.submit' && call[1]?.session_id === 'runtime-a'
+ )
+
+ expect(calls).toHaveLength(2)
+ expect(calls[1][1]).toEqual(calls[0][1])
+ expect(deps.syncAttachmentsForSubmit).toHaveBeenCalledTimes(2)
+ await act(async () => {
+ expect(await result.current('retry me')).toBe(true)
+ })
+ expect(requestGateway.mock.calls.at(-1)?.[1]?.submission_id).not.toBe(calls[0][1]?.submission_id)
+ })
+
+ it.each([false, true])('keeps new-session %s kickoff identity and expansion across journal reload', async slash => {
+ const { deps, requestGateway } = setup()
+ deps.activeSessionIdRef.current = null
+ deps.selectedStoredSessionIdRef.current = null
+ $connection.set({ connectionId: 'local', profile: 'default', mode: 'local' } as never)
+ deps.createBackendSessionForSend.mockImplementation(async () => {
+ deps.activeSessionIdRef.current = 'runtime-a'
+ deps.selectedStoredSessionIdRef.current = 'stored-a'
+ $sessions.set([{ id: 'stored-a', connection_id: 'local', profile: 'default' }] as never)
+
+ return 'runtime-a' as never
+ })
+ const accepted = new Map<string, Record<string, unknown>>()
+ let loseAck = true
+ let expansions = 0
+ requestGateway.mockImplementation(async (method, params) => {
+ if (method === 'slash.exec') {
+ expansions++
+
+ return {
+ type: 'skill',
+ name: 'private-skill',
+ message: `expanded-${expansions}`,
+ display: '/private-skill'
+ } as never
+ }
+
+ if (method !== 'prompt.submit') {
+ return {} as never
+ }
+
+ const id = String(params?.submission_id)
+ const previous = accepted.get(id)
+
+ if (previous) {
+ expect(params).toEqual(previous)
+ } else {
+ accepted.set(id, params!)
+ }
+
+ if (loseAck) {
+ throw new Error('connection closed')
+ }
+
+ return { admission_id: id, status: 'terminal' } as never
+ })
+ wire.request.mockImplementation((_connection, _profile, method, params) => requestGateway(method, params))
+
+ const mount = () =>
+ renderHook(() => {
+ const submitPromptText = useSubmitPrompt(deps)
+
+ const runSlash = useSlashCommand({
+ ...deps,
+ submitPromptText,
+ appendSessionTextMessage: vi.fn(),
+ branchCurrentSession: async () => true,
+ handleSkinCommand: () => '',
+ handoffSession: async () => ({ ok: true }),
+ openMemoryGraph: vi.fn(),
+ refreshSessions: async () => undefined,
+ startFreshSessionDraft: vi.fn()
+ })
+
+ return slash ? runSlash : submitPromptText
+ })
+
+ const input = slash ? '/private-skill' : 'first prompt'
+ let hook = mount()
+ await act(async () => {
+ expect(await hook.result.current(input)).toBe(false)
+ })
+ const serialized = window.localStorage.getItem('hermes.desktop.preparedSubmissions.v1')
+ expect(serialized).toBeTruthy()
+ expect(Object.values(JSON.parse(serialized!))[0]).toMatchObject({ owner: { connectionId: 'local', profile: 'default' } })
+ hook.unmount()
+ window.localStorage.clear()
+ window.localStorage.setItem('hermes.desktop.preparedSubmissions.v1', serialized!)
+ loseAck = false
+ hook = mount()
+ await act(async () => {
+ expect(await hook.result.current(input)).toBe(true)
+ })
+ expect(accepted.size).toBe(1)
+ expect(deps.createBackendSessionForSend).toHaveBeenCalledTimes(1)
+ expect(deps.syncAttachmentsForSubmit).toHaveBeenCalledTimes(1)
+ expect(expansions).toBe(slash ? 1 : 0)
+ })
+
+ it.each(['missing', 'wrong', 'unknown', '4094', 'lost-legacy'])(
+ 'requires a matching receipt or one pre-admission legacy refusal: %s',
+ async mode => {
+ const { deps, requestGateway } = setup()
+ const refusal = Object.assign(new Error('durable admission unsupported'), { code: 4094 })
+ requestGateway.mockImplementation(async (_method, params) => {
+ if (mode === '4094' || mode === 'lost-legacy') {
+ if (params?.submission_id) {
+ throw refusal
+ }
+
+ if (mode === 'lost-legacy') {
+ throw new Error('connection closed')
+ }
+
+ return { ok: true } as never
+ }
+
+ if (mode === 'missing') {
+ return { ok: true } as never
+ }
+
+ return { admission_id: mode === 'wrong' ? 'wrong-id' : params?.submission_id, status: 'unknown' } as never
+ })
+ let hook = renderHook(() => useSubmitPrompt(deps))
+ await act(async () => {
+ expect(await hook.result.current('receipt')).toBe(mode === '4094')
+ })
+ hook.unmount()
+ hook = renderHook(() => useSubmitPrompt(deps))
+
+ if (mode !== '4094') {
+ await act(async () => {
+ expect(await hook.result.current('receipt')).toBe(false)
+ })
+ const attempts = requestGateway.mock.calls.filter(call => call[0] === 'prompt.submit')
+
+ if (mode === 'lost-legacy') { expect(attempts).toHaveLength(2) }
+ const identified = attempts.filter(call => call[1]?.submission_id)
+ expect(new Set(identified.map(call => call[1]?.submission_id)).size).toBe(1)
+ expect(attempts.filter(call => !call[1]?.submission_id)).toHaveLength(mode === 'lost-legacy' ? 1 : 0)
+ }
+ }
+ )
+
+ it('assigns one direct ID before preprocessing and keeps it through busy retries', async () => {
+ const { deps, requestGateway } = setup()
+ let attempts = 0
+ requestGateway.mockImplementation(async (_method, params) => {
+ if (++attempts === 1) {
+ throw new Error('session busy')
+ }
+
+ return { admission_id: params?.submission_id, status: 'started' } as never
+ })
+ const { result } = renderHook(() => useSubmitPrompt(deps))
+ await act(async () => {
+ expect(await result.current('hello')).toBe(true)
+ })
+ const ids = requestGateway.mock.calls.map(call => call[1]?.submission_id)
+ expect(ids.length).toBeGreaterThan(1)
+ expect(ids[0]).toEqual(expect.any(String))
+ expect(new Set(ids).size).toBe(1)
+ })
+
+ it('pins the exact owner before attachment preprocessing changes connection and profile', async () => {
+ const { deps, requestGateway } = setup()
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-a', profile: 'alice' }] as never)
+ const gate = deferred<{ sessionId: string; attachments: [] }>()
+ deps.syncAttachmentsForSubmit.mockImplementation(() => gate.promise)
+ const { result } = renderHook(() => useSubmitPrompt(deps))
+ let pending!: Promise<boolean>
+ act(() => {
+ pending = result.current('private text')
+ })
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-b', profile: 'bob' }] as never)
+ $activeGatewayProfile.set('bob')
+ await act(async () => {
+ gate.resolve({ sessionId: 'runtime-a', attachments: [] })
+ expect(await pending).toBe(true)
+ })
+ expect(deps.syncAttachmentsForSubmit).toHaveBeenCalledWith(
+ 'runtime-a',
+ [],
+ expect.objectContaining({
+ storedSessionId: 'stored-a',
+ requestGateway: expect.any(Function)
+ })
+ )
+ expect(requestGateway).not.toHaveBeenCalled()
+ expect(wire.request).toHaveBeenCalledWith(
+ 'owner-a',
+ 'alice',
+ 'prompt.submit',
+ expect.objectContaining({ session_id: 'runtime-a', text: 'private text', submission_id: expect.any(String) }),
+ expect.any(Number),
+ undefined
+ )
+ })
+
+ it('captures an attachment upload owner before native byte reading yields', async () => {
+ const { uploadComposerAttachment } = await import('.')
+ const gate = deferred<string>()
+ const original = window.hermesDesktop
+ window.hermesDesktop = { ...original, readFileDataUrl: vi.fn(() => gate.promise) } as never
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-a', profile: 'alice' }] as never)
+ wire.request.mockResolvedValue({ attached: true, ref_text: '@file:staged.txt' })
+ const ambient = vi.fn(async () => ({ attached: true, ref_text: '@file:wrong.txt' })) as GatewayRequest
+ const captured = captureSubmissionDestination('stored-a', ambient)
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-b', profile: 'bob' }] as never)
+
+ try {
+ const pending = uploadComposerAttachment(
+ { id: 'file-a', kind: 'file', label: 'private.txt', path: '/private.txt' },
+ {
+ remote: true,
+ sessionId: 'runtime-a',
+ storedSessionId: 'stored-a',
+ requestGateway: captured.requestGateway
+ }
+ )
+
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-b', profile: 'bob' }] as never)
+ $activeGatewayProfile.set('bob')
+ gate.resolve('data:text/plain;base64,cHJpdmF0ZQ==')
+ await pending
+ expect(wire.request).toHaveBeenCalledWith(
+ 'owner-a',
+ 'alice',
+ 'file.attach',
+ expect.objectContaining({
+ session_id: 'runtime-a',
+ data_url: 'data:text/plain;base64,cHJpdmF0ZQ=='
+ })
+ )
+ expect(ambient).not.toHaveBeenCalled()
+ } finally {
+ window.hermesDesktop = original
+ }
+ })
+
+ it('pins slash fallback and generated kickoff to the entry owner and stored session', async () => {
+ const { deps } = setup()
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-a', profile: 'alice' }] as never)
+ const gate = deferred<unknown>()
+ const requests: Array<[string, string, string]> = []
+ wire.request.mockImplementation(async (connection, profile, method) => {
+ requests.push([connection, profile, method])
+
+ if (method === 'slash.exec') {
+ return gate.promise
+ }
+
+ return { type: 'skill', name: 'private-skill', message: 'expanded private skill' }
+ })
+ deps.requestGateway = vi.fn(async (method: string) => {
+ if (method === 'slash.exec') {
+ return gate.promise
+ }
+
+ return { type: 'skill', name: 'private-skill', message: 'expanded private skill' }
+ }) as GatewayRequest
+ const submitPromptText = vi.fn(async () => true)
+
+ const { result } = renderHook(() =>
+ useSlashCommand({
+ ...deps,
+ submitPromptText,
+ appendSessionTextMessage: vi.fn(),
+ branchCurrentSession: async () => true,
+ handleSkinCommand: () => '',
+ handoffSession: async () => ({ ok: true }),
+ openMemoryGraph: vi.fn(),
+ refreshSessions: async () => undefined,
+ startFreshSessionDraft: vi.fn()
+ })
+ )
+
+ let pending!: Promise<boolean>
+ await act(async () => {
+ pending = result.current('/private-skill')
+ })
+ deps.activeSessionIdRef.current = 'runtime-b'
+ deps.selectedStoredSessionIdRef.current = 'stored-b'
+ $sessions.set([{ id: 'stored-a', connection_id: 'owner-b', profile: 'bob' }] as never)
+ $activeGatewayProfile.set('bob')
+ await act(async () => {
+ gate.resolve({ type: 'skill', name: 'private-skill', message: 'expanded private skill' })
+ await pending
+ })
+ expect(requests).toEqual([['owner-a', 'alice', 'slash.exec']])
+ expect(submitPromptText).toHaveBeenCalledWith(
+ 'expanded private skill',
+ expect.objectContaining({
+ sessionId: 'runtime-a',
+ storedSessionId: 'stored-a',
+ submission_id: expect.any(String),
+ destination: expect.any(Object)
+ })
+ )
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.ts
new file mode 100644
index 00000000000..998bf300bdf
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submission-destination.ts
@@ -0,0 +1,83 @@
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection } from '@/store/session'
+import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
+import { knownOwnerForSession } from '@/store/session-states'
+
+import type { GatewayRequest } from './utils'
+
+const capturedRequests = new WeakMap<GatewayRequest, SubmissionDestination>()
+
+export interface SubmissionDestination {
+ readonly scopeKey: string
+ readonly owner: SessionOwnerScope
+ readonly requestGateway: GatewayRequest
+}
+
+/** Capture before preprocessing, not when the prepared payload finally sends.
+ * Unknown legacy owners may use the existing dispatcher only while its ambient
+ * connection/profile is unchanged; a write must never fall to a new socket. */
+export function captureSubmissionDestination(
+ sessionId: string | null | undefined,
+ request: GatewayRequest,
+ restoredOwner?: { owner: SessionOwnerScope }
+): SubmissionDestination {
+ const captured = capturedRequests.get(request)
+
+ if (captured && !restoredOwner) {
+ return captured
+ }
+
+ const knownOwner = restoredOwner ? restoredOwner.owner : knownOwnerForSession(sessionId)
+ const owner = knownOwner && typeof knownOwner === 'object' ? Object.freeze({ ...knownOwner }) : knownOwner
+
+ // Window visibility, logs and registry discovery replace this descriptor.
+ // Only transport/auth authority may invalidate an in-flight write.
+ const authority = () => {
+ const connection = $connection.get()
+
+ return (
+ connection &&
+ JSON.stringify([
+ connection.baseUrl,
+ connection.wsUrl,
+ connection.token,
+ connection.connectionId,
+ connection.mode,
+ connection.profile,
+ connection.authMode
+ ])
+ )
+ }
+
+ const connectionAuthority = authority()
+ const profile = $activeGatewayProfile.get()
+
+ const guardedRequest: GatewayRequest = (method, params, timeoutMs) => {
+ if (connectionAuthority !== authority() || profile !== $activeGatewayProfile.get()) {
+ return Promise.reject(new Error('Submission destination changed; retry from the original session'))
+ }
+
+ return timeoutMs === undefined ? request(method, params) : request(method, params, timeoutMs)
+ }
+
+ const connection = $connection.get()
+
+ const scopeKey = JSON.stringify(
+ owner && typeof owner === 'object'
+ ? [owner.connectionId, owner.profile]
+ : [connection?.connectionId ?? connection?.baseUrl ?? null, profile]
+ )
+
+ const destination = Object.freeze({
+ scopeKey,
+ owner,
+ requestGateway: <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) =>
+ typeof owner === 'object' && owner !== null
+ ? requestForSessionProfile<T>(owner, guardedRequest, method, params, timeoutMs)
+ : guardedRequest<T>(method, params, timeoutMs)
+ })
+
+ capturedRequests.set(destination.requestGateway, destination)
+
+ return destination
+}
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.ts
index fc6115650b8..89948c9594e 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
@@ -21,6 +21,7 @@ import {
import { $hudMode } from '@/store/hud'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'
+import { trackPendingSubmission } from '@/store/pending-submissions'
import { isStoredTranscriptReadOnly } from '@/store/read-only-transcript'
import {
$sessions,
@@ -31,14 +32,21 @@ import {
setMessages,
touchSessionActivity
} from '@/store/session'
-import { $sessionStates } from '@/store/session-states'
+import { $sessionStates, knownOwnerForSession } from '@/store/session-states'
import type { ClientSessionState } from '../../../types'
import { sessionContextDrift } from '../session-context-drift'
import { resolveSessionProfile } from '../use-session-actions/utils'
+import {
+ preparedSubmissionKey,
+ readPreparedSubmission,
+ removePreparedSubmission,
+ writePreparedSubmission
+} from './prepared-submissions'
import { finalizeInterruptedMessages } from './rewind'
import { registerRecoveredRuntime, singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'
+import { captureSubmissionDestination } from './submission-destination'
import {
acquireSubmitInFlight,
type GatewayRequest,
@@ -69,7 +77,7 @@ interface SubmitPromptDeps {
syncAttachmentsForSubmit: (
sessionId: string,
attachments: ComposerAttachment[],
- options?: { updateComposerAttachments?: boolean }
+ options?: { updateComposerAttachments?: boolean; storedSessionId?: string | null; requestGateway?: GatewayRequest }
) => Promise<{ attachments: ComposerAttachment[]; sessionId: string }>
updateSessionState: (
sessionId: string,
@@ -109,7 +117,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
getRuntimeIdForStoredSession,
getRouteToken,
onRuntimeRecovered,
- requestGateway,
+ requestGateway: ambientRequestGateway,
runtimeIdByStoredSessionIdRef,
resumeStoredSession,
selectedStoredSessionIdRef,
@@ -296,6 +304,38 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
targetStartedInCurrentView = true
}
+ const captured =
+ options?.destination ?? captureSubmissionDestination(targetStoredSessionId ?? sessionId, ambientRequestGateway)
+
+ const retryKeyForTarget = () => preparedSubmissionKey(
+ resolveComposerSessionKey(targetStoredSessionId ?? sessionId, $sessions.get()),
+ captured, rawText, attachments, options
+ )
+
+ let startingRouteToken = getRouteToken()
+ let retained: Awaited<ReturnType<typeof readPreparedSubmission>>
+
+ try {
+ retained = await readPreparedSubmission(retryKeyForTarget())
+
+ // A legacy send has no deduplication identity. After an ambiguous ACK
+ // even an upgraded server cannot safely admit it under the saved ID.
+ if (retained?.legacyAttempted) {
+ return false
+ }
+ } catch (err) {
+ notifyError(err, copy.promptFailed)
+
+ return false
+ }
+
+ const destination = retained
+ ? captureSubmissionDestination(targetStoredSessionId ?? sessionId, ambientRequestGateway, retained)
+ : captured
+
+ const requestGateway = destination.requestGateway
+ const submissionId = retained?.id ?? options?.submission_id ?? crypto.randomUUID()
+
let startingStoredSessionId = routedSessionNeedsResume
? routedStoredSessionId
: (selectedStoredSessionId ?? routedStoredSessionId)
@@ -306,8 +346,6 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// switched chats while this submit was in flight.
let startingSelectedStoredSessionId = selectedStoredSessionId
- let startingRouteToken = getRouteToken()
-
// Reason string (or null) for why the session context genuinely drifted
// under this in-flight submit. sessionContextDrift ignores the churn a
// busy gateway produces (selection null-resets on a gateway/profile
@@ -358,7 +396,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
}
}
- const optimisticId = `user-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
+ const optimisticId = `user-${submissionId}`
// What the bubble shows. A `/skill` send carries the whole expanded
// skill body as its text — model-facing scaffolding — so the dispatcher
@@ -727,9 +765,13 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// first and submit's own recovery never runs — that asymmetry is why
// plain text survived sleep/wake but images reported "session not
// found". The attach path recovers and reports the live id back here.
- const attachResult = await syncAttachmentsForSubmit(sessionId, attachments, {
- updateComposerAttachments: usingComposerAttachments
- })
+ const attachResult = retained
+ ? { sessionId, attachments: retained.attachments }
+ : await syncAttachmentsForSubmit(sessionId, attachments, {
+ updateComposerAttachments: usingComposerAttachments,
+ storedSessionId: targetStoredSessionId,
+ requestGateway
+ })
const syncedAttachments = attachResult.attachments
// Always a live string; pin it so TS narrows past the outer
@@ -751,11 +793,18 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// Images keep their inline bounded thumbnail — see optimisticAttachmentRef.
attachmentRefs = syncedAttachments.map(optimisticAttachmentRef).filter((r): r is string => Boolean(r))
rewriteOptimistic(liveSessionId)
- const text = buildContextText(syncedAttachments)
+ const text = retained?.text ?? buildContextText(syncedAttachments)
+
+ trackPendingSubmission(targetStoredSessionId ?? liveSessionId, {
+ id: submissionId,
+ text,
+ displayText: options?.displayText
+ })
const submitParams = (targetId: string) => ({
session_id: targetId,
text,
+ submission_id: submissionId,
...(interrupted && { interrupted }),
// Off-screen widget intent: the gateway types the persisted user
// row display_kind=hidden so no client renders it as a bubble.
@@ -772,23 +821,69 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
...(options?.fromQueue && { queued: true })
})
+ // A fresh draft had no session owner at entry. Adopt its published
+ // route only if it is the SAME captured connection/profile authority.
+ const publishedDestination = captureSubmissionDestination(targetStoredSessionId, ambientRequestGateway, {
+ owner: knownOwnerForSession(targetStoredSessionId)
+ })
+
+ const prepared: NonNullable<typeof retained> = retained ?? {
+ id: submissionId,
+ owner: destination.owner ??
+ (publishedDestination.scopeKey === destination.scopeKey ? publishedDestination.owner : undefined),
+ displayText: options?.displayText,
+ attachments: syncedAttachments,
+ text,
+ params: submitParams(liveSessionId)
+ }
+
+ const retryKey = retryKeyForTarget()
+ await writePreparedSubmission(retryKey, prepared)
+
+ if (sessionDriftReason()) {return abortForSessionSwitch(liveSessionId)}
+
// On sleep/wake the gateway's in-memory session may have been cleared
// while the desktop app still holds the old session ID. The shared
// resolver re-registers the stored session and retries once; every
// other session-scoped RPC (attach, /compress, rewind, interrupt) goes
// through the same helper so one policy covers the whole bug class.
let submitErr: unknown = null
+ let legacyAccepted = false
try {
- const recoverStoredSessionId = targetStoredSessionId ?? selectedStoredSessionIdRef.current
+ const recoverStoredSessionId = targetStoredSessionId
- await withSessionNotFoundResume(
+ const { result } = await withSessionNotFoundResume<{ admission_id?: string; status?: string }>(
sessionId,
recoverStoredSessionId,
liveId =>
- withSessionBusyRetry(() =>
- requestGateway('prompt.submit', submitParams(liveId), PROMPT_SUBMIT_REQUEST_TIMEOUT_MS)
- ),
+ withSessionBusyRetry(async () => {
+ const params: Record<string, unknown> = { ...prepared.params, session_id: liveId }
+
+ try {
+ return await requestGateway<{ admission_id?: string; status?: string }>(
+ 'prompt.submit', params, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
+ )
+ } catch (error) {
+ // 4094 is an explicit PRE-admission capability refusal. Never
+ // downgrade on a timeout, malformed ACK or an ambiguous retry.
+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 4094 || prepared.legacyAttempted) {
+ throw error
+ }
+
+ prepared.legacyAttempted = true
+ await writePreparedSubmission(retryKey, prepared)
+ const { submission_id: _id, ...legacyParams } = params
+
+ const result = await requestGateway<{ admission_id?: string; status?: string }>(
+ 'prompt.submit', legacyParams, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
+ )
+
+ legacyAccepted = true
+
+ return result
+ }
+ }),
{
requestGateway,
driftReason: sessionDriftReason,
@@ -816,6 +911,29 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// instead of erroring out and losing the session binding.
{ alsoTimeout: true }
)
+
+ if (
+ !legacyAccepted &&
+ (result?.admission_id !== submissionId || !['queued', 'started', 'terminal'].includes(result?.status ?? ''))
+ ) {
+ dropOptimistic(sessionId)
+ releaseBusy()
+
+ return false
+ }
+
+ if (result?.admission_id === submissionId) {
+ trackPendingSubmission(targetStoredSessionId ?? liveSessionId, {
+ id: submissionId,
+ text,
+ displayText: options?.displayText,
+ status: result.status
+ })
+
+ if (result.status === 'queued') {
+ dropOptimistic(sessionId)
+ }
+ }
} catch (firstErr) {
if (firstErr instanceof SessionRecoveryAborted) {
console.warn('[submit-drift-abort]', firstErr.reason, { phase: 'post-resume-retry' })
@@ -830,6 +948,8 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
throw submitErr
}
+ await removePreparedSubmission(retryKey)
+
if (usingComposerAttachments) {
// A submit owns only the occurrences that actually reached the
// gateway. Tokenized chips match across staging clones; legacy chips
@@ -904,7 +1024,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
getRuntimeIdForStoredSession,
getRouteToken,
onRuntimeRecovered,
- requestGateway,
+ ambientRequestGateway,
runtimeIdByStoredSessionIdRef,
resumeStoredSession,
scope,
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.ts
index c5bfb83da70..cecc54f1af1 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
@@ -7,6 +7,7 @@ import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
import type { ComposerAttachment } from '@/store/composer'
import { registerRecoveredRuntime, singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'
+import type { SubmissionDestination } from './submission-destination'
export type GatewayRequest = <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
@@ -689,6 +690,12 @@ export function visibleUserIndexAtOrdinal(messages: readonly ChatMessage[], targ
}
export interface SubmitTextOptions {
+ /** Original slash invocation: retries must not re-expand a prepared prompt. */
+ retryText?: string
+ /** Captured by slash dispatch before asynchronous expansion. */
+ destination?: SubmissionDestination
+ /** Stable caller-owned identity; retain across uncertain admission retries. */
+ submission_id?: string
attachments?: ComposerAttachment[]
/** The composer scope key that was actually loaded when this text was
* submitted (see use-composer-draft's activeQueueSessionKeyRef). Compared
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index c3a38d46384..63c82ec572d 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -7,6 +7,7 @@ import { parseErrorSurface } from '@/lib/error-surface'
import { isMessagingSource, normalizeSessionSource } from '@/lib/session-source'
import { reconcileApprovalModeForProfile } from '@/store/approval-mode'
import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'
+import { reconcilePendingSubmissions } from '@/store/pending-submissions'
import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'
import { $projectTree } from '@/store/projects'
import {
@@ -1655,6 +1656,10 @@ export function applyRuntimeInfo(
return null
}
+ if (info.stored_session_id) {
+ reconcilePendingSubmissions(info.stored_session_id, info.pending_submissions)
+ }
+
// App/profile-level reporting is session-independent — a tile's runtime
// reports backend skew and credential warnings just as usefully.
reportBackendContract(info.desktop_contract)
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 641d7bfb6e9..68a2ea86bd0 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -350,6 +350,10 @@ declare global {
pickDefaultProjectDir: () => Promise<{ canceled: boolean; dir: null | string }>
setDefaultProjectDir: (dir: null | string) => Promise<{ dir: null | string }>
}
+ preparedSubmissions?: {
+ read: () => Promise<string>
+ update: (key: string, entry: string | null) => Promise<void>
+ }
zoom?: {
get: () => Promise<{ level: number; percent: number }>
/** Synchronous zoom factor of this window (1 = 100%). */
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 1ce7297289a..a2c1d6666f2 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -1903,6 +1903,7 @@ export const ar = defineLocale({
openDirective: 'فتح',
queueMessage: 'إضافة الرسالة للطابور',
steer: 'توجيه',
+ redirect: 'إعادة توجيه التشغيل الحالي',
stop: 'إيقاف',
send: 'إرسال',
speaking: 'يتحدث',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 4fe8bcb34fc..f1192032652 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -2579,6 +2579,7 @@ export const en: Translations = {
openDirective: 'Open',
queueMessage: 'Queue message',
steer: 'Steer the current run',
+ redirect: 'Redirect the current run',
stop: 'Stop',
send: 'Send',
speaking: 'Speaking',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 8e7afb5de4d..30013b880eb 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -2612,6 +2612,7 @@ export const ru = defineLocale({
openDirective: 'Открыть',
queueMessage: 'Вставить сообщение в очередь',
steer: 'Направить текущий запуск',
+ redirect: 'Перенаправить текущий запуск',
stop: 'Стоп',
send: 'Отправить',
speaking: 'Говорит',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index ae869d34352..087454d7ecb 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2203,6 +2203,7 @@ export interface Translations {
openDirective: string
queueMessage: string
steer: string
+ redirect: string
stop: string
send: string
speaking: string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 2fc5561b553..7a849d2c8e4 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -2742,6 +2742,7 @@ export const zh: Translations = {
openDirective: '打开',
queueMessage: '排队消息',
steer: '引导当前运行',
+ redirect: '重新定向当前运行',
stop: '停止',
send: '发送',
speaking: '讲话中',
diff --git a/apps/desktop/src/lib/execution-authority.ts b/apps/desktop/src/lib/execution-authority.ts
new file mode 100644
index 00000000000..bff4a9854cd
--- /dev/null
+++ b/apps/desktop/src/lib/execution-authority.ts
@@ -0,0 +1,41 @@
+interface ExecutionAuthority {
+ epoch: string
+ generation: number
+ terminal: boolean
+ retiredEpochs: Set<string>
+}
+
+/** Each transport consumer owns its map; epochs are opaque, never ordered. */
+export function acceptExecutionEvent(
+ authorities: Map<string, ExecutionAuthority>,
+ key: string,
+ type: string,
+ payload?: Record<string, unknown>
+): boolean {
+ if (!['session.info', 'message.start', 'message.complete', 'message.error'].includes(type)) {return true}
+ const previous = authorities.get(key)
+ const epoch = payload?.execution_epoch
+ const generation = payload?.execution_generation
+ const versioned = typeof epoch === 'string' && epoch.length > 0 && typeof generation === 'number' && Number.isSafeInteger(generation) && generation >= 0
+
+ if (!versioned) {return !previous}
+ const terminal = type === 'message.complete' || type === 'message.error' || payload?.running === false
+
+ if (previous) {
+ if (previous.retiredEpochs.has(epoch)) {return false}
+
+ if (previous.epoch === epoch) {
+ if (generation < previous.generation) {return false}
+
+ if (generation === previous.generation && previous.terminal && (type === 'message.start' || payload?.running === true)) {return false}
+ } else {
+ // Only an owner snapshot/start can establish a new epoch, not a late finalizer.
+ if (type !== 'session.info' && type !== 'message.start') {return false}
+ previous.retiredEpochs.add(previous.epoch)
+ }
+ }
+
+ authorities.set(key, { epoch, generation, terminal: terminal || Boolean(previous?.epoch === epoch && previous.generation === generation && previous.terminal), retiredEpochs: previous?.retiredEpochs ?? new Set() })
+
+ return true
+}
diff --git a/apps/desktop/src/store/busy-input-mode.ts b/apps/desktop/src/store/busy-input-mode.ts
new file mode 100644
index 00000000000..aad47d4f59f
--- /dev/null
+++ b/apps/desktop/src/store/busy-input-mode.ts
@@ -0,0 +1,16 @@
+import { atom } from 'nanostores'
+
+export type BusyInputMode = 'interrupt' | 'queue' | 'steer'
+
+export function normalizeBusyInputMode(value: unknown): BusyInputMode {
+ const mode = typeof value === 'string' ? value.trim().toLowerCase() : ''
+
+ return mode === 'steer' || mode === 'queue' ? mode : 'interrupt'
+}
+
+export function busyInputOwnerKey(connectionId?: string | null, profile?: string | null): string {
+ return JSON.stringify([connectionId ?? '', profile?.trim() || 'default'])
+}
+
+// A backend config snapshot, never a persisted Desktop-only preference.
+export const $busyInputConfig = atom<{ owner: string; connection: unknown; mode: BusyInputMode } | null>(null)
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index d53edca1d36..d5f1768544c 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -6,6 +6,7 @@ import type { ComposerAttachment } from './composer'
export interface QueuedPromptEntry {
id: string
+ serverStatus?: string
text: string
/** What the queue panel and the sent bubble show, when it differs from the
* text the agent receives. A queued `/skill` invocation carries the whole
@@ -18,10 +19,10 @@ export interface QueuedPromptEntry {
/** Whether a queued entry can ride a mid-turn redirect: text-only, non-empty,
* not a slash command — the same gate `steerDraft` applies to the live draft
* (attachments can't ride a redirect; slash commands execute, not steer). */
-export const isSteerableEntry = (entry: Pick<QueuedPromptEntry, 'attachments' | 'text'>): boolean => {
+export const isSteerableEntry = (entry: Pick<QueuedPromptEntry, 'attachments' | 'text' | 'serverStatus'>): boolean => {
const text = entry.text.trim()
- return Boolean(text) && entry.attachments.length === 0 && !SLASH_COMMAND_RE.test(text)
+ return !entry.serverStatus && Boolean(text) && entry.attachments.length === 0 && !SLASH_COMMAND_RE.test(text)
}
type QueueState = Record<string, QueuedPromptEntry[]>
@@ -88,7 +89,7 @@ const setParked = (sid: string, parked: boolean) => {
$parkedQueueSessions.set(next)
}
-const writeSession = (sid: string, queue: QueuedPromptEntry[]) => {
+export const writeSessionQueue = (sid: string, queue: QueuedPromptEntry[]) => {
const current = $queuedPromptsBySession.get()
const next = { ...current }
@@ -125,7 +126,7 @@ export const getQueuedPrompts = (key: string | null | undefined): QueuedPromptEn
export const enqueueQueuedPrompt = (
key: string | null | undefined,
- payload: { text: string; attachments: ComposerAttachment[]; displayText?: string }
+ payload: { id?: string; text: string; attachments: ComposerAttachment[]; displayText?: string }
): null | QueuedPromptEntry => {
const sid = sidOf(key)
@@ -134,14 +135,14 @@ export const enqueueQueuedPrompt = (
}
const entry: QueuedPromptEntry = {
- id: nextId(),
+ id: payload.id ?? nextId(),
text: payload.text,
...(payload.displayText ? { displayText: payload.displayText } : {}),
attachments: cloneAttachments(payload.attachments),
queuedAt: Date.now()
}
- writeSession(sid, [...queueFor(sid), entry])
+ writeSessionQueue(sid, [...queueFor(sid), entry])
// Queueing a new prompt is fresh intent to keep the conversation moving —
// a park from an earlier Stop must not hold this (or the entries ahead of
// it) back.
@@ -163,7 +164,7 @@ export const dequeueQueuedPrompt = (key: string | null | undefined): null | Queu
return null
}
- writeSession(sid, rest)
+ writeSessionQueue(sid, rest)
return head
}
@@ -176,13 +177,13 @@ export const removeQueuedPrompt = (key: string | null | undefined, id: string):
}
const queue = queueFor(sid)
- const next = queue.filter(e => e.id !== id)
+ const next = queue.filter(e => e.id !== id || e.serverStatus)
if (next.length === queue.length) {
return false
}
- writeSession(sid, next)
+ writeSessionQueue(sid, next)
return true
}
@@ -202,7 +203,7 @@ export const promoteQueuedPrompt = (key: string | null | undefined, id: string):
}
const entry = queue[index]!
- writeSession(sid, [entry, ...queue.slice(0, index), ...queue.slice(index + 1)])
+ writeSessionQueue(sid, [entry, ...queue.slice(0, index), ...queue.slice(index + 1)])
return true
}
@@ -246,7 +247,7 @@ export const updateQueuedPrompt = (
return false
}
- writeSession(sid, next)
+ writeSessionQueue(sid, next)
return true
}
@@ -261,7 +262,7 @@ export const clearQueuedPrompts = (key: string | null | undefined) => {
return
}
- writeSession(sid, [])
+ writeSessionQueue(sid, [])
}
/**
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index f9ce195cb10..89fbf3b2cff 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -1224,8 +1224,11 @@ export async function retainGatewayForAgent(connectionId: null | string, profile
return release
}
+import { acceptExecutionEvent } from '@/lib/execution-authority'
+
const turnLeaseKey = (scope: string, sessionId: string): string => `${scope}\u0000${sessionId}`
const TURN_LEASE_SETTLE_DELAY_MS = 500
+const turnExecutionAuthorities = new Map()
function cancelTurnLeaseRelease(key: string): void {
const timer = g.turnLeaseReleaseTimers.get(key)
@@ -1319,7 +1322,9 @@ function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {
const key = turnLeaseKey(scope, sessionId)
- if (event.type === 'message.start') {
+ if (!acceptExecutionEvent(turnExecutionAuthorities, key, event.type, event.payload as Record<string, unknown> | undefined)) {return}
+
+ if (event.type === 'message.start' || (event.type === 'session.info' && (event.payload as Record<string, unknown>)?.running === true)) {
// The gateway emits settled session.info before immediately chaining a
// queued/goal follow-up. Keep the same route alive for that next turn.
cancelTurnLeaseRelease(key)
diff --git a/apps/desktop/src/store/pending-submissions.test.ts b/apps/desktop/src/store/pending-submissions.test.ts
new file mode 100644
index 00000000000..49680d75c5f
--- /dev/null
+++ b/apps/desktop/src/store/pending-submissions.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, expect, it } from 'vitest'
+
+import { applyRuntimeInfo } from '@/app/session/hooks/use-session-actions/utils'
+import { isSteerableEntry } from '@/store/composer-queue'
+
+import { $queuedPromptsBySession, enqueueQueuedPrompt, getQueuedPrompts } from './composer-queue'
+import { reconcilePendingSubmissions, trackPendingSubmission } from './pending-submissions'
+
+beforeEach(() => {
+ window.localStorage.clear()
+ $queuedPromptsBySession.set({})
+})
+
+it('projects resumed runtime pending receipts under durable identity without making them sendable', () => {
+ const info = {
+ stored_session_id: 'durable',
+ pending_submissions: [
+ { admission_id: 'remote', status: 'queued', user: 'queued exact Ω' },
+ { admission_id: 'uncertain', status: 'unknown', user: 'unknown exact Ω' }
+ ]
+ }
+
+ applyRuntimeInfo(info)
+ applyRuntimeInfo(info)
+ expect(getQueuedPrompts('durable').map(({ id, text, serverStatus }) => ({ id, text, serverStatus })))
+ .toEqual(info.pending_submissions.map(({ admission_id, user, status }) => ({ id: admission_id, text: user, serverStatus: status })))
+ expect(getQueuedPrompts('durable').every(entry => !isSteerableEntry(entry))).toBe(true)
+ expect(getQueuedPrompts('runtime')).toEqual([])
+})
+
+it('reconciles server queue by identity without replaying or duplicating local entries', () => {
+ enqueueQueuedPrompt('chat', { id: 'one', text: 'same', attachments: [] })
+ enqueueQueuedPrompt('chat', { id: 'local', text: 'same', attachments: [] })
+ const snapshot = [{ admission_id: 'one', status: 'queued', user: 'same' }]
+ reconcilePendingSubmissions('chat', snapshot)
+ reconcilePendingSubmissions('chat', snapshot)
+ expect(getQueuedPrompts('chat').map(entry => entry.id)).toEqual(['one', 'local'])
+ expect(getQueuedPrompts('chat')[0]?.serverStatus).toBe('queued')
+ reconcilePendingSubmissions('chat', [{ ...snapshot[0], status: 'started' }])
+ expect(getQueuedPrompts('chat').map(entry => entry.id)).toEqual(['local'])
+ reconcilePendingSubmissions('chat', [{ admission_id: 'unknown', status: 'unknown', user: 'interrupted' }])
+ expect(getQueuedPrompts('chat').find(entry => entry.id === 'unknown')?.serverStatus).toBe('unknown')
+ reconcilePendingSubmissions('chat', [])
+ expect(getQueuedPrompts('chat').map(entry => entry.id)).toEqual(['local'])
+})
+
+it('recovers remote pending text into the queue and journal without a local submission', () => {
+ const snapshot = [
+ { admission_id: 'remote-queued', status: 'queued', user: 'queued elsewhere' },
+ { admission_id: 'remote-unknown', status: 'unknown', user: 'interrupted elsewhere' }
+ ]
+
+ reconcilePendingSubmissions('chat', snapshot)
+ reconcilePendingSubmissions('chat', snapshot)
+ expect(getQueuedPrompts('chat').map(({ id, text, serverStatus }) => ({ id, text, serverStatus })))
+ .toEqual(snapshot.map(({ admission_id, user, status }) => ({ id: admission_id, text: user, serverStatus: status })))
+ const journal = JSON.parse(window.localStorage.getItem('hermes.desktop.pendingSubmissions.v1')!)
+
+ for (const receipt of snapshot) {
+ expect(journal.chat[receipt.admission_id].text).toBe(receipt.user)
+ }
+})
+
+it('persists identified direct submissions independently of the automatic local queue', () => {
+ trackPendingSubmission('chat', { id: 'direct', text: 'hello' })
+ const stored = JSON.parse(window.localStorage.getItem('hermes.desktop.pendingSubmissions.v1')!)
+ expect(stored.chat.direct).toMatchObject({ id: 'direct', text: 'hello' })
+ expect(getQueuedPrompts('chat')).toEqual([])
+})
diff --git a/apps/desktop/src/store/pending-submissions.ts b/apps/desktop/src/store/pending-submissions.ts
new file mode 100644
index 00000000000..5bb828039ce
--- /dev/null
+++ b/apps/desktop/src/store/pending-submissions.ts
@@ -0,0 +1,62 @@
+import { getQueuedPrompts, type QueuedPromptEntry, writeSessionQueue } from './composer-queue'
+
+const STORAGE_KEY = 'hermes.desktop.pendingSubmissions.v1'
+interface PendingSubmission { id: string; text: string; displayText?: string; status?: string }
+type Journal = Record<string, Record<string, PendingSubmission>>
+
+const readJournal = (): Journal => {
+ try { return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}') as Journal }
+ catch { return {} }
+}
+
+// Not an outbox: an uncertain accepted input must never be replayed automatically.
+export function trackPendingSubmission(key: string, entry: PendingSubmission): void {
+ const journal = readJournal()
+ journal[key] = { ...journal[key], [entry.id]: entry }
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))
+}
+
+export function reconcilePendingSubmissions(key: string, value: unknown): void {
+ if (!Array.isArray(value)) { return }
+ const journal = readJournal()
+ const known = journal[key] ?? {}
+ const receipts = new Map<string, PendingSubmission>()
+
+ for (const raw of value) {
+ if (!raw || typeof raw.admission_id !== 'string' || !['queued', 'started', 'unknown'].includes(raw.status)) { continue }
+ const id = raw.admission_id
+ receipts.set(id, { ...known[id], id, text: typeof raw.user === 'string' ? raw.user : known[id]?.text ?? '', status: raw.status })
+ }
+
+ const current = getQueuedPrompts(key)
+ const next: QueuedPromptEntry[] = []
+
+ for (const entry of current) {
+ const receipt = receipts.get(entry.id)
+
+ if (receipt) {
+ if (receipt.status !== 'started') { next.push({ ...entry, serverStatus: receipt.status }) }
+ receipts.delete(entry.id)
+ } else if (!entry.serverStatus) { next.push(entry) }
+ }
+
+ for (const receipt of receipts.values()) {
+ if (receipt.status !== 'started') {
+ next.push({ id: receipt.id, text: receipt.text, displayText: receipt.displayText, attachments: [], queuedAt: Date.now(), serverStatus: receipt.status })
+ }
+ }
+
+ // Only observed server records may be retired by their later absence.
+ for (const [id, entry] of Object.entries(known)) {
+ if (entry.status && !value.some(raw => raw?.admission_id === id)) { delete known[id] }
+ }
+
+ for (const raw of value) {
+ if (typeof raw?.admission_id === 'string') { known[raw.admission_id] = { ...known[raw.admission_id], id: raw.admission_id, text: raw.user ?? known[raw.admission_id]?.text ?? '', status: raw.status } }
+ }
+
+ journal[key] = known
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))
+
+ if (JSON.stringify(current) !== JSON.stringify(next)) { writeSessionQueue(key, next) }
+}
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 16203d60525..708a85e2d03 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -346,6 +346,7 @@ export interface HermesConfig {
personality?: string
skin?: string
interim_assistant_messages?: boolean
+ busy_input_mode?: string
timestamps?: boolean
}
desktop?: {
@@ -716,6 +717,8 @@ export interface SessionResumeResponse {
}
export interface SessionRuntimeInfo {
+ stored_session_id?: string
+ pending_submissions?: unknown
approval_mode?: 'manual' | 'off' | 'smart'
branch?: string
config_warning?: string
diff --git a/ui-tui/src/__tests__/composerDestinationRenderer.test.tsx b/ui-tui/src/__tests__/composerDestinationRenderer.test.tsx
new file mode 100644
index 00000000000..f00944ac8e7
--- /dev/null
+++ b/ui-tui/src/__tests__/composerDestinationRenderer.test.tsx
@@ -0,0 +1,120 @@
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+import { useComposerState } from '../app/useComposerState.js'
+import { readClipboardText } from '../lib/clipboard.js'
+
+vi.mock('../lib/clipboard.js', () => ({
+ readClipboardText: vi.fn(),
+ isUsableClipboardText: (text: unknown) => typeof text === 'string' && text.length > 0
+}))
+
+function deferred() {
+ let resolve!: (value: any) => void
+
+ const promise = new Promise<any>(done => {
+ resolve = done
+ })
+
+ return { promise, resolve }
+}
+
+function mount(request: any) {
+ resetUiState()
+ patchUiState({ sid: 'owner', pasteCollapseChars: 5 })
+ let composer!: ReturnType<typeof useComposerState>
+ const sys = vi.fn()
+
+ function Harness() {
+ composer = useComposerState({ gw: { request } as any, submitRef: { current: () => {} }, sys })
+
+ return <Text>{composer.state.input}</Text>
+ }
+
+ const instance = renderSync(<Harness />, {
+ stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any,
+ patchConsole: false
+ })
+
+ return {
+ get composer() {
+ return composer
+ },
+ sys,
+ close() {
+ instance.unmount()
+ resetUiState()
+ }
+ }
+}
+
+it('captures hotkey destination before reading the clipboard, while preserving current-owner pastes', async () => {
+ vi.stubEnv('SSH_CONNECTION', '')
+ vi.stubEnv('SSH_CLIENT', '')
+ vi.stubEnv('SSH_TTY', '')
+ const request = vi.fn(async () => ({ name: 'shot', path: '/shot.png' }))
+ const h = mount(request)
+
+ try {
+ const gate = deferred()
+ vi.mocked(readClipboardText).mockReturnValueOnce(gate.promise)
+ const pending = h.composer.actions.handleTextPaste({ hotkey: true, text: '', value: '', cursor: 0 })
+ patchUiState({ sid: 'other' })
+ gate.resolve('/shot.png')
+ expect(await pending).toBeNull()
+ expect(request).not.toHaveBeenCalled()
+ expect(h.composer.refs.tokensRef.current).toEqual([])
+ vi.mocked(readClipboardText).mockResolvedValueOnce('/shot.png')
+ expect(await h.composer.actions.handleTextPaste({ hotkey: true, text: '', value: '', cursor: 0 })).toMatchObject({
+ value: '[[ Image 1 ]]'
+ })
+ expect(request).toHaveBeenCalledWith('image.attach', { path: '/shot.png', session_id: 'other' })
+ } finally {
+ h.close()
+ vi.unstubAllEnvs()
+ }
+})
+
+it('discards stale image, drop fallback and collapse completions without changing the new composer', async () => {
+ for (const mode of ['image', 'clipboard', 'drop', 'collapse']) {
+ const gate = deferred()
+ const request = vi.fn((method: string) => (method.startsWith('complete.') ? Promise.resolve({}) : gate.promise))
+ const h = mount(request)
+
+ try {
+ let pending: unknown
+
+ if (mode === 'image') {h.composer.actions.attachImagePath('/shot.png')}
+ else if (mode === 'clipboard') {h.composer.actions.attachClipboardImage()}
+ else
+ {pending = h.composer.actions.handleTextPaste({
+ text: mode === 'drop' ? '/file.txt' : 'long paste',
+ value: '',
+ cursor: 0
+ })}
+
+ await Promise.resolve()
+ const tokens = h.composer.refs.tokensRef.current.map(t => ({ ...t }))
+ patchUiState({ sid: 'other' })
+ h.composer.actions.setInput('new draft')
+ h.composer.actions.setComposerTokens(tokens)
+ gate.resolve(
+ mode === 'drop' ? { matched: true, text: 'wrong' } : { name: 'shot', attached: true, path: '/old-path' }
+ )
+ await pending
+ await new Promise<void>(resolve => setImmediate(resolve))
+ expect(h.composer.refs.tokensRef.current).toEqual(tokens)
+ expect(h.composer.state.input).toBe('new draft')
+ expect(request.mock.calls.filter(([method]) => method === 'input.detect_drop')).toHaveLength(0)
+ expect(h.sys).not.toHaveBeenCalled()
+ } finally {
+ h.close()
+ }
+ }
+})
diff --git a/ui-tui/src/__tests__/composerFreshnessRenderer.test.tsx b/ui-tui/src/__tests__/composerFreshnessRenderer.test.tsx
new file mode 100644
index 00000000000..376b34cacec
--- /dev/null
+++ b/ui-tui/src/__tests__/composerFreshnessRenderer.test.tsx
@@ -0,0 +1,53 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+import { useComposerState } from '../app/useComposerState.js'
+
+it('does not restore stale same-session paste results after editing away and back', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-composer-freshness-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'session' })
+ let finish!: (value: unknown) => void
+
+ const request = vi.fn((method: string) => method === 'clipboard.paste'
+ ? new Promise(resolve => { finish = resolve }) : Promise.resolve({}))
+
+ let composer!: ReturnType<typeof useComposerState>
+
+ function Harness() {
+ composer = useComposerState({ gw: { request }, submitRef: { current: vi.fn() }, sys: vi.fn() } as any)
+
+ return <Text>composer</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+
+ try {
+ composer.actions.setInput('old')
+ const pending = composer.actions.handleTextPaste({ bracketed: true, hotkey: false, text: '', value: 'old', cursor: 3 })
+ composer.actions.setInput('new')
+ composer.actions.setInput('old')
+ finish({ attached: true, name: 'image', path: '/tmp/owned-image.png' })
+ expect(await pending).toBeNull()
+ expect(composer.refs.tokensRef.current).toEqual([])
+ const fresh = composer.actions.handleTextPaste({ bracketed: true, hotkey: false, text: '', value: 'old', cursor: 3 })
+ finish({ attached: true, name: 'image', path: '/tmp/owned-image.png' })
+ expect(await fresh).toEqual(expect.objectContaining({ value: expect.stringContaining('Image') }))
+ expect(composer.refs.tokensRef.current).toHaveLength(1)
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index b6df3a23e94..1b45cecaf25 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@ -67,6 +67,54 @@ describe('createGatewayEventHandler', () => {
patchUiState({ showReasoning: true })
})
+ it('displays generic errors without settling versioned execution', () => {
+ const ctx = buildCtx([])
+ const onEvent = createGatewayEventHandler(ctx)
+ patchUiState({ sid: 'owner', busy: true, status: 'running…', info: { model: 'test', tools: {}, skills: {}, execution_epoch: 'owner-epoch', execution_generation: 2 } })
+ onEvent({ type: 'error', session_id: 'owner', payload: { message: 'build failed' } } as any)
+ expect(ctx.system.sys).toHaveBeenCalledWith('error: build failed')
+ expect(getUiState()).toMatchObject({ busy: true, status: 'running…' })
+ onEvent({ type: 'error', session_id: 'owner', payload: { message: 'turn failed', execution_epoch: 'owner-epoch', execution_generation: 2 } } as any)
+ expect(ctx.system.sys).toHaveBeenCalledWith('error: turn failed')
+ expect(getUiState().busy).toBe(false)
+ })
+
+ it('fences restarted owner lifecycle events until resume establishes the new epoch', () => {
+ const appended: Msg[] = []
+ const onEvent = createGatewayEventHandler(buildCtx(appended))
+
+ const info = { model: 'test', skills: {}, tools: {}, running: true,
+ execution_epoch: 'old-owner', execution_generation: 9 }
+
+ patchUiState({ sid: 'focused', info, busy: true })
+ const emit = (type: string, payload: any) => onEvent({ type, payload, session_id: 'focused' } as any)
+ emit('session.info', { execution_epoch: 'new-owner', execution_generation: 1, running: false })
+ expect(getUiState().busy).toBe(true)
+ // session.resume replaces info with the authoritative attachment snapshot.
+ patchUiState({ info: { ...info, execution_epoch: 'new-owner', execution_generation: 1 } })
+
+ for (const payload of [{}, { execution_epoch: 'old-owner', execution_generation: 99 },
+ { execution_epoch: 'new-owner', execution_generation: 0 }]) {
+ emit('message.complete', { ...payload, text: 'stale' })
+ emit('error', { ...payload, message: 'stale' })
+ emit('session.info', { ...payload, running: false })
+ expect(getUiState().busy).toBe(true)
+ }
+
+ expect(appended).toEqual([])
+ emit('message.complete', { execution_epoch: 'new-owner', execution_generation: 1, text: 'fresh' })
+ expect(getUiState().busy).toBe(false)
+ expect(appended.some(m => m.text === 'fresh')).toBe(true)
+ emit('message.start', { execution_epoch: 'new-owner', execution_generation: 2 })
+ emit('message.complete', { execution_epoch: 'new-owner', execution_generation: 1, text: 'late' })
+ expect(getUiState().busy).toBe(true)
+ expect(getUiState().info?.execution_generation).toBe(2)
+ emit('message.complete', { execution_epoch: 'new-owner', execution_generation: 4, text: 'missed start' })
+ emit('message.start', { execution_epoch: 'new-owner', execution_generation: 3 })
+ expect(getUiState().busy).toBe(false)
+ expect(getUiState().info?.execution_generation).toBe(4)
+ })
+
it('heals missed completion and blocking prompts only from the focused authoritative idle snapshot', () => {
patchUiState({ sid: 'focused' })
const onEvent = createGatewayEventHandler(buildCtx([]))
@@ -90,6 +138,24 @@ describe('createGatewayEventHandler', () => {
expect(getUiState().status).toBe('ready')
expect(getOverlayState().approval).toBeNull()
expect(getTurnState().tools).toEqual([])
+ onEvent({
+ session_id: 'focused',
+ payload: { ...snapshot, running: true, execution_generation: 2 },
+ type: 'session.info'
+ } as any)
+ onEvent({
+ session_id: 'focused',
+ payload: { running: false, execution_generation: 1 },
+ type: 'session.info'
+ } as any)
+ expect(getUiState().busy).toBe(true)
+ onEvent({
+ session_id: 'focused',
+ payload: { running: false, execution_generation: 2 },
+ type: 'session.info'
+ } as any)
+ expect(getUiState().busy).toBe(false)
+ expect(getUiState().info?.model).toBe('test')
})
it('archives incomplete todos into transcript flow at end of turn so they scroll up', () => {
diff --git a/ui-tui/src/__tests__/createSlashHandler.test.ts b/ui-tui/src/__tests__/createSlashHandler.test.ts
index 67f2609f916..bab7180e39b 100644
--- a/ui-tui/src/__tests__/createSlashHandler.test.ts
+++ b/ui-tui/src/__tests__/createSlashHandler.test.ts
@@ -33,6 +33,18 @@ describe('createSlashHandler', () => {
envState.dashboardTuiMode = false
})
+ it('does not execute a stale fallback command after switching destinations', async () => {
+ patchUiState({ sid: 'owner' })
+ const ctx = buildCtx()
+ let reject!: (error: unknown) => void
+ ctx.gateway.gw.request.mockReturnValueOnce(new Promise((_, fail) => { reject = fail }))
+ createSlashHandler(ctx)('/unknown-command')
+ patchUiState({ sid: 'other' })
+ reject(new Error('worker failed'))
+ await new Promise(resolve => setImmediate(resolve))
+ expect(ctx.gateway.gw.request).toHaveBeenCalledTimes(1)
+ })
+
it('opens the unified sessions overlay for /resume', () => {
const ctx = buildCtx()
@@ -534,7 +546,7 @@ describe('createSlashHandler', () => {
expect(ctx.session.newSession).toHaveBeenCalledWith('new session started', undefined)
})
- it('keeps visible scrollback when branching a TUI session', async () => {
+ it('hydrates a branch through session resume without prematurely replacing source state', async () => {
patchUiState({ sid: 'sid-parent' })
const rpc = vi.fn(() => Promise.resolve({ session_id: 'sid-branch', title: 'branch title' }))
const ctx = buildCtx({ gateway: { ...buildGateway(), rpc } })
@@ -543,12 +555,65 @@ describe('createSlashHandler', () => {
expect(rpc).toHaveBeenCalledWith('session.branch', { name: 'branch title', session_id: 'sid-parent' })
await vi.waitFor(() => {
- expect(getUiState().sid).toBe('sid-branch')
+ expect(ctx.session.resumeById).toHaveBeenCalledWith('sid-branch')
expect(ctx.transcript.sys).toHaveBeenCalledWith('branched → branch title')
})
+ expect(getUiState().sid).toBe('sid-parent')
+ expect(ctx.session.closeSession).not.toHaveBeenCalled()
expect(ctx.transcript.setHistoryItems).not.toHaveBeenCalled()
})
+ it('only applies compression snapshots while execution authority is fresh', async () => {
+ const source = {
+ model: 'test', tools: {}, skills: {}, execution_epoch: 'owner', execution_generation: 2,
+ execution_state: 'idle', running: false, stored_session_id: 'stored-source'
+ }
+ const flush = () => new Promise(resolve => setImmediate(resolve))
+
+ for (const change of [
+ { execution_generation: 3, execution_state: 'running', running: true },
+ { execution_epoch: 'replacement', execution_generation: 0 },
+ { execution_state: 'complete' },
+ { stored_session_id: 'other' }
+ ]) {
+ patchUiState({ sid: 'source', info: source, busy: false })
+ let resolve!: (value: any) => void
+ const rpc = vi.fn(() => new Promise<any>(done => { resolve = done }))
+ const ctx = buildCtx({ gateway: { ...buildGateway(), rpc } })
+ createSlashHandler(ctx)('/compress')
+ const current = { ...source, ...change }
+ patchUiState({ info: current, busy: current.running, usage: { calls: 8, input: 8, output: 8, total: 16 } })
+ resolve({ info: source, messages: [{ role: 'assistant', text: 'old summary' }], usage: { total: 1 } })
+ await flush()
+ expect(getUiState().info).toEqual(current)
+ expect(getUiState().usage.total).toBe(16)
+ expect(ctx.transcript.setHistoryItems).not.toHaveBeenCalled()
+ }
+
+ // Stale/missing snapshot versions cannot erase established authority either.
+ for (const info of [undefined, { ...source, execution_generation: 1 }, { ...source, execution_epoch: 'old' }]) {
+ patchUiState({ sid: 'source', info: source, busy: false })
+ const ctx = buildCtx({ gateway: { ...buildGateway(), rpc: vi.fn(async () => ({ info, messages: [] })) } })
+ createSlashHandler(ctx)('/compress')
+ await flush()
+ expect(getUiState().info).toEqual(source)
+ expect(ctx.transcript.setHistoryItems).not.toHaveBeenCalled()
+ }
+
+ // Ordinary metadata refresh is not a new execution; fresh partial info merges.
+ patchUiState({ sid: 'source', info: source, busy: false })
+ let resolve!: (value: any) => void
+ const ctx = buildCtx({ gateway: { ...buildGateway(), rpc: vi.fn(() => new Promise<any>(done => { resolve = done })) } })
+ createSlashHandler(ctx)('/compress')
+ patchUiState({ info: { ...source, model: 'refreshed' } })
+ resolve({ info: { execution_epoch: 'owner', execution_generation: 2 }, messages: [{ role: 'assistant', text: 'fresh summary' }] })
+ await flush()
+ expect(getUiState().info).toMatchObject({ ...source, model: 'refreshed' })
+ expect(ctx.transcript.setHistoryItems).toHaveBeenCalledWith(expect.arrayContaining([
+ expect.objectContaining({ role: 'assistant', text: 'fresh summary' })
+ ]))
+ })
+
it('reloads skills in the live gateway and refreshes the catalog', async () => {
const rpc = vi.fn((method: string) => {
if (method === 'skills.reload') {
diff --git a/ui-tui/src/__tests__/orchestratorPromptSession.test.ts b/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
index 2d670c4a5b8..cff6ac86cf0 100644
--- a/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
+++ b/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
@@ -1,8 +1,34 @@
import { describe, expect, it } from 'vitest'
+import { patchUiState } from '../app/uiStore.js'
import { startPromptLiveSession } from '../app/useMainApp.js'
describe('startPromptLiveSession', () => {
+ it('keeps the created target through a delayed model switch without publishing into the new focus', async () => {
+ patchUiState({ sid: 'created' })
+ let finish!: (value: { value: string }) => void
+ const dispatched: unknown[] = []
+ const notices: string[] = []
+
+ const pending = startPromptLiveSession({
+ dispatchSubmission: (text, destination) => dispatched.push({ text, destination }),
+ maybeWarn: () => notices.push('warn'),
+ modelArg: 'chosen',
+ newLiveSession: async () => 'created',
+ onModelSwitched: () => notices.push('model'),
+ prompt: 'private prompt',
+ rpc: () => new Promise(resolve => { finish = resolve }),
+ sys: text => notices.push(text)
+ })
+
+ await Promise.resolve()
+ patchUiState({ sid: 'other' })
+ finish({ value: 'chosen' })
+ await pending
+ expect(dispatched).toEqual([{ text: 'private prompt', destination: expect.objectContaining({ sid: 'created' }) }])
+ expect(notices).toEqual([])
+ })
+
it('starts a kept-live session with generated id/title, applies selected model, then dispatches the prompt', async () => {
const calls: Array<[string, unknown]> = []
@@ -13,6 +39,8 @@ describe('startPromptLiveSession', () => {
newLiveSession: async (message, title) => {
calls.push(['new', { message, title }])
+ patchUiState({ sid: 'abc123' })
+
return 'abc123'
},
onModelSwitched: (value, result) => calls.push(['model-switched', { result, value }]),
@@ -51,6 +79,8 @@ describe('startPromptLiveSession', () => {
newLiveSession: async () => {
calls.push('new')
+ patchUiState({ sid: 'abc123' })
+
return 'abc123'
},
prompt: ' ',
diff --git a/ui-tui/src/__tests__/pendingMigrationRenderer.test.tsx b/ui-tui/src/__tests__/pendingMigrationRenderer.test.tsx
new file mode 100644
index 00000000000..13f5d545779
--- /dev/null
+++ b/ui-tui/src/__tests__/pendingMigrationRenderer.test.tsx
@@ -0,0 +1,118 @@
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { captureDestination, isCurrentDestination } from '../app/submissionDestination.js'
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+import { useQueue } from '../hooks/useQueue.js'
+import * as pending from '../lib/pendingInputs.js'
+
+it('moves compression queues across cached successors without changing attempted receipts or losing settlement', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-migrate-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'old', info: { model: 'test', profile_name: 'alpha', skills: {}, tools: {} } })
+ let queue!: ReturnType<typeof useQueue>
+
+ function Harness() {
+ queue = useQueue()
+
+ return <Text>{queue.queuedDisplay.join('|')}</Text>
+ }
+
+ const options = {
+ stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any,
+ patchConsole: false
+ }
+
+ let instance = renderSync(<Harness />, options)
+
+ try {
+ const original = captureDestination()
+ const attempted = queue.stage('attempted')
+ const settle = attempted.settle
+ const waiting = queue.enqueue('waiting')
+ queue.setQueueEdit(1)
+ patchUiState({ sid: 'next' })
+ expect(queue.queueRef.current).toEqual([]) // cache successor before migration
+ const ownNext = queue.enqueue('already next')
+ patchUiState({ sid: 'old' })
+ pending.migratePendingInputs(original, 'next')
+ patchUiState({ sid: 'next' })
+ expect(queue.queueRef.current).toEqual([attempted, waiting, ownNext])
+ expect(queue.queueRef.current[0]).toBe(attempted)
+ expect(attempted.destination).toEqual(original)
+ expect(attempted.settle).toBe(settle)
+ expect(waiting.destination?.sid).toBe('next')
+ expect(queue.queueEditRef.current).toBe(1)
+ expect(pending.loadPendingInputs(original)).toEqual([])
+ expect(pending.loadPendingInputs(captureDestination())).toHaveLength(3)
+ const next = captureDestination()
+ pending.migratePendingInputs(next, 'last')
+ patchUiState({ sid: 'last' })
+ // Late completion must find the migrated queue even before a getter/render.
+ settle!(false)
+ expect(queue.queueRef.current[0]).toBe(attempted)
+ expect(queue.dequeue()).toBeUndefined()
+ instance.unmount()
+ instance = renderSync(<Harness />, options)
+ const restored = queue.queueRef.current[0]
+ expect(restored).toMatchObject({ destination: original, failed: true, submissionId: attempted.submissionId })
+ expect(queue.dequeue()).toBeUndefined()
+ queue.dequeue(true)!.settle!(true)
+ expect(queue.queueRef.current.map(item => item.text)).toEqual(['waiting', 'already next'])
+ expect(pending.loadPendingInputs(captureDestination())).toHaveLength(2)
+ const live = queue.stage('late success')
+ pending.migratePendingInputs(captureDestination(), 'later')
+ patchUiState({ sid: 'later' })
+ pending.migratePendingInputs(captureDestination(), 'latest')
+ patchUiState({ sid: 'latest' })
+ live.settle!(true)
+ expect(live.destination?.sid).toBe('last')
+ expect(queue.queueRef.current.map(item => item.text)).toEqual(['waiting', 'already next'])
+
+ patchUiState({ sid: 'unrelated' })
+ expect(queue.queueRef.current).toEqual([])
+ queue.enqueue('cold source')
+ const cold = captureDestination()
+ instance.unmount()
+ patchUiState({ sid: 'cold successor' })
+ instance = renderSync(<Harness />, options)
+ expect(queue.queueRef.current).toEqual([])
+ pending.migratePendingInputs(cold, 'cold successor')
+ expect(queue.queueRef.current.map(item => item.text)).toEqual(['cold source'])
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
+
+it('uses the canonical profile home through symlinks, including a missing descendant', () => {
+ const root = mkdtempSync(join(tmpdir(), 'ink-home-'))
+ const real = join(root, 'real')
+ const alias = join(root, 'alias')
+ mkdirSync(real)
+ symlinkSync(real, alias, 'junction')
+
+ try {
+ vi.stubEnv('HERMES_HOME', alias)
+ const captured = captureDestination()
+ expect(captured.profileHome).toBe(realpathSync(real))
+ vi.stubEnv('HERMES_HOME', real)
+ expect(isCurrentDestination(captured)).toBe(true)
+ vi.stubEnv('HERMES_HOME', join(alias, 'missing', 'nested'))
+ expect(captureDestination().profileHome).toBe(join(realpathSync(real), 'missing', 'nested'))
+ } finally {
+ vi.unstubAllEnvs()
+ rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/ui-tui/src/__tests__/promptResponseFreshness.test.ts b/ui-tui/src/__tests__/promptResponseFreshness.test.ts
new file mode 100644
index 00000000000..a9d949c68e0
--- /dev/null
+++ b/ui-tui/src/__tests__/promptResponseFreshness.test.ts
@@ -0,0 +1,27 @@
+import { expect, it } from 'vitest'
+
+import { capturePromptResponseGuard, patchOverlayState } from '../app/overlayStore.js'
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+
+it('allows only the original prompt in the original execution to publish a response', () => {
+ resetUiState()
+ const info = { model: 'test', tools: {}, skills: {}, execution_epoch: 'owner', execution_generation: 1 }
+ patchUiState({ sid: 'original', info })
+
+ for (const key of ['approval', 'clarify', 'sudo', 'secret'] as const) {
+ const prompt = { requestId: 'same-id' } as any
+ patchOverlayState({ [key]: prompt })
+ const fresh = capturePromptResponseGuard(key, prompt)
+ expect(fresh()).toBe(true)
+ patchUiState({ sid: 'other' })
+ expect(fresh()).toBe(false)
+ patchUiState({ sid: 'original', info: { ...info, execution_generation: 2 } })
+ expect(fresh()).toBe(false)
+ patchUiState({ info })
+ patchOverlayState({ [key]: { ...prompt } })
+ expect(fresh()).toBe(false)
+ patchOverlayState({ [key]: null })
+ }
+
+ resetUiState()
+})
diff --git a/ui-tui/src/__tests__/queueScopeRenderer.test.tsx b/ui-tui/src/__tests__/queueScopeRenderer.test.tsx
index 895114a8f81..3619ff57bd4 100644
--- a/ui-tui/src/__tests__/queueScopeRenderer.test.tsx
+++ b/ui-tui/src/__tests__/queueScopeRenderer.test.tsx
@@ -1,8 +1,11 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { PassThrough } from 'node:stream'
import { renderSync, Text } from '@hermes/ink'
import React from 'react'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { patchUiState, resetUiState } from '../app/uiStore.js'
import { useQueue } from '../hooks/useQueue.js'
@@ -16,6 +19,8 @@ describe('pending input destination', () => {
{ profile: 'alpha', sid: 'other-session' },
{ profile: 'beta', sid: 'same-session' }
])('does not drain or edit another destination: $profile/$sid', async destination => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-pending-'))
+ vi.stubEnv('HERMES_HOME', home)
patchUiState({ info: null, sid: null })
let queue!: ReturnType<typeof useQueue>
@@ -32,17 +37,31 @@ describe('pending input destination', () => {
output += String(chunk)
})
- const instance = renderSync(<Harness />, {
+ const renderOptions = {
patchConsole: false,
stdin: new PassThrough() as unknown as NodeJS.ReadStream,
stdout: stdout as unknown as NodeJS.WriteStream,
stderr: new PassThrough() as unknown as NodeJS.WriteStream
- })
+ }
+
+ let instance = renderSync(<Harness />, renderOptions)
try {
queue.enqueue('startup payload')
patchUiState({ info: info('alpha'), sid: 'same-session' })
- expect(queue.dequeue()).toBe('startup payload')
+ const pending = queue.dequeue()!
+ expect(pending).toMatchObject({ text: 'startup payload', submissionId: expect.any(String) })
+ expect(queue.queueRef.current).toContain(pending)
+ expect(queue.dequeue()).toBeUndefined()
+ pending.settle!(false)
+ expect(queue.dequeue()).toBeUndefined() // no automatic ambiguous replay
+ instance.unmount()
+ instance = renderSync(<Harness />, renderOptions)
+ expect(queue.dequeue()).toBeUndefined()
+ const restored = queue.dequeue(true)!
+ expect(restored).toMatchObject({ submissionId: pending.submissionId, text: pending.text })
+ restored.settle!(true)
+ expect(queue.queueRef.current).not.toContain(pending)
queue.enqueue('private payload', 'private preview')
queue.setQueueEdit(0)
patchUiState({ info: info(destination.profile), sid: destination.sid })
@@ -55,12 +74,14 @@ describe('pending input destination', () => {
expect(output).not.toContain('private preview|destination payload')
patchUiState({ info: info('alpha'), sid: 'same-session' })
expect(queue.queueEditRef.current).toBe(0)
- expect(queue.takeQ(0)).toEqual({ display: 'private preview', text: 'private payload' })
+ expect(queue.takeQ(0)).toMatchObject({ display: 'private preview', text: 'private payload' })
patchUiState({ info: info(destination.profile), sid: destination.sid })
- expect(queue.dequeue()).toBe('destination payload')
+ expect(queue.dequeue()).toMatchObject({ text: 'destination payload' })
expect(queue.dequeue()).toBeUndefined()
} finally {
instance.unmount()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
}
})
})
diff --git a/ui-tui/src/__tests__/resumeEpochRenderer.test.tsx b/ui-tui/src/__tests__/resumeEpochRenderer.test.tsx
new file mode 100644
index 00000000000..08e89abfb40
--- /dev/null
+++ b/ui-tui/src/__tests__/resumeEpochRenderer.test.tsx
@@ -0,0 +1,112 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
+import { useSessionLifecycle } from '../app/useSessionLifecycle.js'
+import { useQueue } from '../hooks/useQueue.js'
+
+it('only the newest attachment request may replace session authority', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-attachment-order-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'source' })
+ const pending: Array<{ method: string; resolve: (value: any) => void }> = []
+ const request = vi.fn((method: string) => new Promise(resolve => pending.push({ method, resolve })))
+ let lifecycle!: ReturnType<typeof useSessionLifecycle>
+
+ function Harness() {
+ lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() },
+ gw: { request }, rpc: request, scrollRef: { current: null }, panel: vi.fn(), sys: vi.fn(),
+ setHistoryItems: vi.fn(), setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(),
+ setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)
+
+ return <Text>session</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+
+ const flush = () => new Promise(resolve => setImmediate(resolve))
+
+ const result = (sid: string) => ({ session_id: sid, messages: [], info: {
+ model: 'test', tools: {}, skills: {}, stored_session_id: sid, execution_epoch: sid, execution_generation: 0 } })
+
+ try {
+ for (const start of [() => lifecycle.resumeById('old'), () => void lifecycle.newLiveSession(), () => lifecycle.activateLiveSession('old')]) {
+ start()
+ const old = pending.shift()!
+ lifecycle.activateLiveSession('new')
+ pending.shift()!.resolve(result('new'))
+ await flush()
+ expect(getUiState().sid).toBe('new')
+ old.resolve(old.method === 'setup.status' ? {} : result('old'))
+ await flush()
+ // Stale setup must not even dispatch a create/resume/close operation.
+ expect(pending).toHaveLength(0)
+ expect(getUiState().sid).toBe('new')
+ expect(getUiState().info?.execution_epoch).toBe('new')
+ }
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
+
+it('resumes a successor with a reset epoch while retaining original attempted admission targets', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-resume-epoch-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ const info = { model: 'test', skills: {}, tools: {}, stored_session_id: 'stored-old', execution_epoch: 'old', execution_generation: 9, running: true }
+ patchUiState({ sid: 'old-session', info, busy: true })
+ let queue!: ReturnType<typeof useQueue>
+ let lifecycle!: ReturnType<typeof useSessionLifecycle>
+
+ const request = vi.fn(async () => ({ session_id: 'successor', session_key: 'stored-successor', resumed: 'stored-successor', info: {
+ ...info, execution_epoch: 'new', execution_generation: 0, running: false
+ }, running: false, messages: [] }))
+
+ function Harness() {
+ queue = useQueue()
+ lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() },
+ gw: { request }, rpc: async () => ({}), scrollRef: { current: null }, panel: vi.fn(), sys: vi.fn(),
+ setHistoryItems: vi.fn(), setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(),
+ setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)
+
+ return <Text>{queue.queuedDisplay.join('|')}</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+
+ try {
+ const attempted = queue.stage('ambiguous')
+ attempted.settle!(false)
+ const waiting = queue.enqueue('not attempted')
+ lifecycle.resumeById('old-session')
+ await vi.waitFor(() => expect(getUiState().sid).toBe('successor'))
+ expect(getUiState().info?.execution_epoch).toBe('new')
+ expect(getUiState().busy).toBe(false)
+ expect(queue.queueRef.current.map(item => item.submissionId)).toEqual([attempted.submissionId, waiting.submissionId])
+ expect(queue.queueRef.current[0]?.destination?.sid).toBe('old-session')
+ expect(queue.queueRef.current[1]?.destination?.sid).toBe('successor')
+ expect(queue.queueRef.current[0]?.destination?.storedSid).toBe('stored-old')
+ expect(queue.queueRef.current[1]?.destination?.storedSid).toBe('stored-successor')
+ expect(getUiState().info?.stored_session_id).toBe('stored-successor')
+ expect(queue.dequeue()).toBeUndefined()
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
diff --git a/ui-tui/src/__tests__/slashSessionAuthority.test.tsx b/ui-tui/src/__tests__/slashSessionAuthority.test.tsx
new file mode 100644
index 00000000000..60f348bc0a9
--- /dev/null
+++ b/ui-tui/src/__tests__/slashSessionAuthority.test.tsx
@@ -0,0 +1,78 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { createSlashHandler } from '../app/createSlashHandler.js'
+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
+import { useSessionLifecycle } from '../app/useSessionLifecycle.js'
+
+it('branch hydration replaces source authority only after a successful destination attachment', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-slash-branch-'))
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_ACTIVE_SESSION_FILE', join(home, 'active'))
+ resetUiState()
+ const source = { model: 'test', skills: {}, tools: {}, stored_session_id: 'stored-source',
+ execution_epoch: 'source-owner', execution_generation: 9, running: true }
+ patchUiState({ sid: 'source', info: source, busy: true })
+ const pending: Array<{ method: string; resolve: (value: any) => void }> = []
+ const request = vi.fn((method: string) => method === 'session.close'
+ ? Promise.resolve({}) : new Promise(resolve => pending.push({ method, resolve })))
+ const setHistoryItems = vi.fn()
+ const sys = vi.fn()
+ let slash!: (command: string) => boolean
+
+ function Harness() {
+ const lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() },
+ gw: { request }, rpc: request, scrollRef: { current: null }, panel: vi.fn(), sys,
+ setHistoryItems, setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(),
+ setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)
+ slash = createSlashHandler({ slashFlightRef: { current: 0 }, gateway: { gw: { request }, rpc: request },
+ local: {}, session: { ...lifecycle, setSessionStartedAt: vi.fn() }, transcript: { sys, setHistoryItems } } as any)
+ return <Text>branch</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any,
+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+ const flush = () => new Promise(resolve => setImmediate(resolve))
+
+ try {
+ slash('/branch child')
+ pending.shift()!.resolve({ session_id: 'branch', title: 'child' })
+ await flush()
+ expect(getUiState().sid).toBe('source')
+ expect(request).not.toHaveBeenCalledWith('session.close', expect.anything())
+ expect(pending[0]?.method).toBe('setup.status')
+ pending.shift()!.resolve({ provider_configured: true })
+ await flush()
+ expect(pending[0]?.method).toBe('session.resume')
+ pending.shift()!.resolve({ session_id: 'branch', stored_session_id: 'stored-branch', running: false,
+ info: { ...source, stored_session_id: 'stored-branch', execution_epoch: 'branch-owner', execution_generation: 0, running: false },
+ messages: [{ role: 'user', text: 'inherited history' }] })
+ await flush()
+ expect(getUiState()).toMatchObject({ sid: 'branch', busy: false, info: {
+ stored_session_id: 'stored-branch', execution_epoch: 'branch-owner', execution_generation: 0 } })
+ expect(setHistoryItems).toHaveBeenLastCalledWith(expect.arrayContaining([
+ expect.objectContaining({ role: 'user', text: 'inherited history' })
+ ]))
+ expect(request).toHaveBeenCalledWith('session.close', { session_id: 'source' })
+
+ // A branch response for a destination the user has left must not attach.
+ slash('/branch stale')
+ patchUiState({ sid: 'other' })
+ pending.shift()!.resolve({ session_id: 'late-branch' })
+ await flush()
+ expect(pending).toHaveLength(0)
+ expect(getUiState().sid).toBe('other')
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
diff --git a/ui-tui/src/__tests__/submissionCore.test.ts b/ui-tui/src/__tests__/submissionCore.test.ts
index 90dfa5a9d1b..e3011a5d499 100644
--- a/ui-tui/src/__tests__/submissionCore.test.ts
+++ b/ui-tui/src/__tests__/submissionCore.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { isSessionBusyError, markSubmitting, submitPrompt, type SubmitPromptDeps } from '../app/submissionCore.js'
+import { captureDestination } from '../app/submissionDestination.js'
import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
import type { GatewayClient } from '../gatewayClient.js'
@@ -150,6 +151,96 @@ describe('submissionCore.submitPrompt — literal submissions (startup -q querie
})
})
+it('keeps the submit destination across preprocessing and never mutates the newly focused session', async () => {
+ resetUiState()
+ patchUiState({ sid: 'original' })
+ const { gw, resolveDrop } = makeDeferredGateway()
+ const deps = makeDeps(gw)
+ submitPrompt('private', deps)
+ patchUiState({ sid: 'other', busy: false, status: 'other ready' })
+ resolveDrop()
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(gw.request).toHaveBeenCalledWith(
+ 'prompt.submit',
+ expect.objectContaining({ session_id: 'original', text: 'private' })
+ )
+ expect(deps.appendMessage).not.toHaveBeenCalled()
+ expect(getUiState()).toMatchObject({ sid: 'other', busy: false, status: 'other ready' })
+})
+
+it('retains a queued submission on ambiguous response and retries the exact identity until durable acknowledgement', async () => {
+ resetUiState()
+ patchUiState({ sid: 'owner', info: { model: 'test', tools: {}, skills: {}, stored_session_id: 'stored-owner' } })
+ const settle = vi.fn()
+ const item = { text: 'private', display: 'private', submissionId: 'stable-id', settle }
+
+ const request = vi.fn().mockResolvedValueOnce({ status: 'streaming' }).mockResolvedValueOnce({
+ admission_id: 'stable-id',
+ target_session_id: 'stored-owner',
+ target_profile_home: captureDestination().profileHome,
+ status: 'queued'
+ })
+
+ const deps = makeDeps({ request } as unknown as GatewayClient)
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ await Promise.resolve()
+ expect(settle).toHaveBeenLastCalledWith(false)
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ await Promise.resolve()
+ expect(request.mock.calls.map(call => call[1])).toEqual([
+ { session_id: 'owner', text: 'private', submission_id: 'stable-id', queued: true },
+ { session_id: 'owner', text: 'private', submission_id: 'stable-id', queued: true }
+ ])
+ expect(settle).toHaveBeenLastCalledWith(true)
+
+ for (const stored_session_id of [undefined, 'wrong-target']) {
+ patchUiState({ info: { model: 'test', tools: {}, skills: {}, stored_session_id } })
+ request.mockResolvedValueOnce({ admission_id: 'stable-id', target_session_id: 'owner',
+ target_profile_home: captureDestination().profileHome, status: 'queued' })
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ await Promise.resolve()
+ expect(settle).toHaveBeenLastCalledWith(false)
+ }
+})
+
+it('preserves legacy isolated submission after explicit unsupported admission without repeating preprocessing', async () => {
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const settle = vi.fn()
+ const item = { text: 'private', display: 'private', submissionId: 'unsupported-id', queued: true, settle }
+ let reject!: (error: unknown) => void
+
+ const request = vi.fn().mockReturnValueOnce(new Promise((_, fail) => { reject = fail }))
+ .mockResolvedValueOnce({ status: 'queued' })
+
+ const deps = makeDeps({ request } as unknown as GatewayClient)
+ submitPrompt(item.text, deps, true, undefined, { skipDetectDrop: true, queueItem: item })
+ patchUiState({ sid: 'other', busy: false, status: 'other ready' })
+ reject(Object.assign(new Error('unsupported'), { code: 4094 }))
+ await vi.waitFor(() => expect(settle).toHaveBeenLastCalledWith(true))
+ expect(request.mock.calls.map(call => call[1])).toEqual([
+ { session_id: 'owner', text: 'private', submission_id: 'unsupported-id', queued: true },
+ { session_id: 'owner', text: 'private', queued: true }
+ ])
+ expect(deps.appendMessage).toHaveBeenCalledTimes(1)
+ expect(getUiState()).toMatchObject({ sid: 'other', busy: false, status: 'other ready' })
+})
+
+it('never downgrades ambiguous or conflicting durable submissions to legacy delivery', async () => {
+ for (const code of [undefined, 4093, 5071]) {
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const settle = vi.fn()
+ const item = { text: 'private', display: 'private', submissionId: 'retained-id', settle }
+ const request = vi.fn().mockRejectedValue(Object.assign(new Error('not admitted'), { code }))
+ submitPrompt(item.text, makeDeps({ request } as unknown as GatewayClient), true, undefined,
+ { skipDetectDrop: true, queueItem: item })
+ await vi.waitFor(() => expect(settle).toHaveBeenLastCalledWith(false))
+ expect(request).toHaveBeenCalledTimes(1)
+ }
+})
+
describe('submissionCore.markSubmitting', () => {
beforeEach(() => resetUiState())
diff --git a/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx b/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx
new file mode 100644
index 00000000000..97a1deed9aa
--- /dev/null
+++ b/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx
@@ -0,0 +1,99 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+import { useSubmission } from '../app/useSubmission.js'
+import { useQueue } from '../hooks/useQueue.js'
+
+it('submits interpolated queued input only to its captured owner and removes it only after the matching receipt', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-submit-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ const info = { model: 'test', profile_name: 'alpha', stored_session_id: 'stored-owner', skills: {}, tools: {} }
+ patchUiState({ sid: 'owner', info })
+ let resolveShell!: (value: unknown) => void
+ let resolveSubmit!: (value: unknown) => void
+
+ const request = vi.fn((method: string) => {
+ if (method === 'shell.exec') {
+ return new Promise(resolve => {
+ resolveShell = resolve
+ })
+ }
+
+ if (method === 'input.detect_drop') {
+ return Promise.resolve({ matched: false })
+ }
+
+ return new Promise(resolve => {
+ resolveSubmit = resolve
+ })
+ })
+
+ let queue!: ReturnType<typeof useQueue>
+ let submission!: ReturnType<typeof useSubmission>
+ const appended = vi.fn()
+
+ function Harness() {
+ queue = useQueue()
+ submission = useSubmission({
+ appendMessage: appended,
+ composerActions: { ...queue, prependQueue: queue.prependQ, takeQueue: queue.takeQ } as any,
+ composerRefs: { queueRef: queue.queueRef, queueEditRef: queue.queueEditRef, tokensRef: { current: [] } } as any,
+ composerState: { input: '', inputBuf: [], completions: [] } as any,
+ gw: { request } as any,
+ setLastUserMsg: vi.fn(),
+ slashRef: { current: () => true },
+ submitRef: { current: () => {} },
+ sys: vi.fn()
+ })
+
+ return <Text>{queue.queuedDisplay.join('|')}</Text>
+ }
+
+ const stdout = Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false })
+
+ const instance = renderSync(<Harness />, {
+ stdin: new PassThrough() as any,
+ stdout: stdout as any,
+ stderr: new PassThrough() as any,
+ patchConsole: false
+ })
+
+ try {
+ queue.enqueue('private {!printf data}')
+ const item = queue.dequeue()!
+ submission.sendQueued(item)
+ patchUiState({ sid: 'other', busy: false })
+ resolveShell({ stdout: 'data', code: 0 })
+ await expect.poll(() => request.mock.calls.filter(call => call[0] === 'prompt.submit').length).toBe(1)
+ expect(request).toHaveBeenCalledWith('prompt.submit', {
+ session_id: 'owner',
+ text: 'private data',
+ submission_id: item.submissionId,
+ queued: true
+ })
+ expect(appended).not.toHaveBeenCalled()
+ expect(queue.queueRef.current).toEqual([])
+ patchUiState({ sid: 'owner' })
+ expect(queue.queueRef.current).toContain(item)
+ resolveSubmit({
+ admission_id: item.submissionId,
+ target_session_id: 'stored-owner',
+ target_profile_home: home,
+ status: 'queued'
+ })
+ await expect.poll(() => queue.queueRef.current.length).toBe(0)
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index b0a4059d6d6..505dd0d9335 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -29,6 +29,7 @@ import { applyDelegationStatus, getDelegationState } from './delegationStore.js'
import type { GatewayEventHandlerContext } from './interfaces.js'
import { getOverlayState, patchOverlayState } from './overlayStore.js'
import { flashGoodVibes, flashPet } from './petFlashStore.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { getTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
@@ -431,7 +432,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
}
const { appendMessage, panel, setHistoryItems } = ctx.transcript
- const { setInput } = ctx.composer
+ const { setInput, enqueue } = ctx.composer
const { submitLiteralRef, submitRef } = ctx.submission
const { setProcessing: setVoiceProcessing, setRecording: setVoiceRecording, setVoiceEnabled } = ctx.voice
@@ -769,6 +770,31 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
return
}
+ // Lifecycle authority is local to an owner epoch. Only attachment RPC
+ // snapshots replace that epoch; delayed push events cannot reset it.
+ const current = getUiState().info
+ const execution = (ev.payload ?? {}) as { execution_epoch?: string; execution_generation?: number }
+ const genericError = ev.type === 'error' &&
+ execution.execution_epoch === undefined && execution.execution_generation === undefined
+ const lifecycle = !genericError && ['session.info', 'message.start', 'message.complete', 'error'].includes(ev.type)
+
+ if (lifecycle && current?.execution_generation !== undefined) {
+ const incoming = (ev.payload ?? {}) as { execution_epoch?: string; execution_generation?: number }
+
+ if (
+ incoming.execution_epoch !== current.execution_epoch ||
+ typeof incoming.execution_generation !== 'number' ||
+ !Number.isSafeInteger(incoming.execution_generation) ||
+ incoming.execution_generation < current.execution_generation
+ ) {
+ return
+ }
+
+ if (ev.type !== 'session.info') {
+ patchUiState({ info: { ...current, execution_generation: incoming.execution_generation } })
+ }
+ }
+
switch (ev.type) {
case 'gateway.ready':
handleReady(ev.payload?.skin)
@@ -782,11 +808,22 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
return
case 'session.info': {
- const info = ev.payload
+ const current = getUiState().info
+ const incoming = ev.payload
+
+ if (incoming.profile_name && current?.profile_name && incoming.profile_name !== current.profile_name) {
+ return
+ }
+
+ const info = { ...current, ...incoming }
// A replayed snapshot can be the only terminal signal after reconnect.
// Missing running on older gateways must not clear a live turn.
- if (info.running === false) {
+ if (incoming.running === true) {
+ patchUiState({ busy: true, status: 'running…' })
+ }
+
+ if (incoming.running === false) {
turnController.clearStatusTimer()
turnController.idle()
setStatus('ready')
@@ -1021,7 +1058,14 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
return
}
+ const destination = captureDestination()
void getFullConfigOnce().then(cfg => {
+ if (!isCurrentDestination(destination)) {
+ enqueue?.(text, text, destination)
+
+ return
+ }
+
const submitMode = normalizeVoiceSubmitMode(cfg?.config?.voice?.submit_mode)
if (submitMode === 'draft') {
@@ -1034,7 +1078,13 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
// is committed before submit reads it; invalid config also falls
// back to this established direct-submit behavior.
setInput('')
- setTimeout(() => submitRef.current(text), 0)
+ setTimeout(() => {
+ if (isCurrentDestination(destination)) {
+ submitRef.current(text)
+ } else {
+ enqueue?.(text, text, destination)
+ }
+ }, 0)
})
return
@@ -1510,6 +1560,13 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
}
case 'error':
+ // Build/RPC failures are not authority to settle a versioned turn.
+ if (genericError && current?.execution_generation !== undefined) {
+ sys(`error: ${String(ev.payload?.message || 'unknown error')}`)
+
+ return
+ }
+
turnController.recordError()
flashPet('failed')
diff --git a/ui-tui/src/app/createSlashHandler.ts b/ui-tui/src/app/createSlashHandler.ts
index 3a354c3ef20..41dc93ec3c5 100644
--- a/ui-tui/src/app/createSlashHandler.ts
+++ b/ui-tui/src/app/createSlashHandler.ts
@@ -8,6 +8,7 @@ import type { SlashHandlerContext } from './interfaces.js'
import { scoreSlashMenuItem } from './slash/fuzzyScore.js'
import { findSlashCommand } from './slash/registry.js'
import type { SlashRunCtx } from './slash/types.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { getUiState } from './uiStore.js'
export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => boolean {
@@ -19,10 +20,11 @@ export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => b
const flight = ++ctx.slashFlightRef.current
const ui = getUiState()
const sid = ui.sid
+ const destination = captureDestination()
const parsed = parseSlashCommand(cmd)
const argTail = parsed.arg ? ` ${parsed.arg}` : ''
- const stale = () => flight !== ctx.slashFlightRef.current || getUiState().sid !== sid
+ const stale = () => flight !== ctx.slashFlightRef.current || !isCurrentDestination(destination)
const guarded =
<T>(fn: (r: T) => void) =>
@@ -168,6 +170,7 @@ export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => b
long ? page(text, parsed.name[0]!.toUpperCase() + parsed.name.slice(1)) : sys(text)
})
.catch(() => {
+ if (stale()) {return}
gw.request('command.dispatch', { arg: parsed.arg, name: parsed.name, session_id: sid })
.then((raw: unknown) => {
if (stale()) {
diff --git a/ui-tui/src/app/interfaces.ts b/ui-tui/src/app/interfaces.ts
index 1aecedd70b8..f61f7621cb1 100644
--- a/ui-tui/src/app/interfaces.ts
+++ b/ui-tui/src/app/interfaces.ts
@@ -32,6 +32,8 @@ import type {
Usage
} from '../types.js'
+import type { SubmissionDestination } from './submissionDestination.js'
+
export interface StateSetter<T> {
(value: SetStateAction<T>): void
}
@@ -380,11 +382,12 @@ export interface ComposerActions {
/** Attach an image by path in as a token. */
attachImagePath: (path: string) => void
clearIn: () => void
- dequeue: () => string | undefined
- enqueue: (text: string, display?: string) => void
+ stage?: (text: string, display?: string, destination?: SubmissionDestination) => QueueItem
+ dequeue: (retry?: boolean) => QueueItem | undefined
+ enqueue: (text: string, display?: string, destination?: SubmissionDestination) => void
handleTextPaste: (event: PasteEvent) => MaybePromise<ComposerPasteResult | null>
openEditor: () => Promise<void>
- prependQueue: (item: QueueItem) => void
+ prependQueue: (item: QueueItem, destination?: SubmissionDestination) => void
pushHistory: (text: string) => void
removeQueue: (index: number) => void
setCompIdx: StateSetter<number>
@@ -435,7 +438,7 @@ export interface InputHandlerActions {
answerClarify: (answer: string) => void
appendMessage: (msg: Msg) => void
die: () => void
- dispatchSubmission: (full: string) => void
+ dispatchSubmission: (full: string | QueueItem) => void
guardBusySessionSwitch: (what?: string) => boolean
newSession: (msg?: string, title?: string) => void
sys: (text: string) => void
@@ -474,6 +477,7 @@ export interface InputHandlerResult {
export interface GatewayEventHandlerContext {
composer: {
+ enqueue?: ComposerActions['enqueue']
setInput: StateSetter<string>
}
gateway: GatewayServices
diff --git a/ui-tui/src/app/overlayStore.ts b/ui-tui/src/app/overlayStore.ts
index 92d52656545..aa350fc3a47 100644
--- a/ui-tui/src/app/overlayStore.ts
+++ b/ui-tui/src/app/overlayStore.ts
@@ -1,8 +1,22 @@
import { atom, computed } from 'nanostores'
import type { OverlayState } from './interfaces.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { $uiState } from './uiStore.js'
+export function capturePromptResponseGuard<K extends 'approval' | 'clarify' | 'sudo' | 'secret'>(
+ key: K,
+ prompt: OverlayState[K]
+): () => boolean {
+ const destination = captureDestination()
+ const info = $uiState.get().info
+
+ return () => Boolean(prompt) && isCurrentDestination(destination) &&
+ $uiState.get().info?.execution_epoch === info?.execution_epoch &&
+ $uiState.get().info?.execution_generation === info?.execution_generation &&
+ $overlayState.get()[key] === prompt
+}
+
const buildOverlayState = (): OverlayState => ({
agents: false,
agentsInitialHistoryIndex: 0,
diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.ts
index 5367b5a1b92..b4f2e5927c8 100644
--- a/ui-tui/src/app/slash/commands/session.ts
+++ b/ui-tui/src/app/slash/commands/session.ts
@@ -17,7 +17,7 @@ import type { PanelSection } from '../../../types.js'
import { applyConfiguredTuiTheme } from '../../createGatewayEventHandler.js'
import { DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES, type IndicatorStyle } from '../../interfaces.js'
import { patchOverlayState } from '../../overlayStore.js'
-import { patchUiState } from '../../uiStore.js'
+import { getUiState, patchUiState } from '../../uiStore.js'
import type { SlashCommand } from '../types.js'
const USAGE_CTA = 'Run /subscription to change plan · /topup to add to your balance'
@@ -246,14 +246,37 @@ export const sessionCommands: SlashCommand[] = [
})
.then(
ctx.guarded<SessionCompressResponse>(r => {
+ const current = getUiState()
+ const authorityKeys = ['stored_session_id', 'execution_epoch', 'execution_generation', 'execution_state', 'running'] as const
+
+ // Compression is not attachment: a delayed reply cannot replace a
+ // newer turn/owner, nor replace its transcript with an old snapshot.
+ if (
+ current.busy !== ctx.ui.busy ||
+ authorityKeys.some(key => current.info?.[key] !== ctx.ui.info?.[key])
+ ) {
+ return
+ }
+
+ if (
+ current.info?.execution_generation !== undefined &&
+ (r.info?.execution_epoch !== current.info.execution_epoch ||
+ !Number.isSafeInteger(r.info?.execution_generation) ||
+ (r.info?.execution_generation ?? -1) < current.info.execution_generation)
+ ) {
+ return
+ }
+
+ const info = r.info ? { ...current.info, ...r.info } : current.info
+
if (Array.isArray(r.messages)) {
const rows = toTranscriptMessages(r.messages)
- ctx.transcript.setHistoryItems(r.info ? [introMsg(r.info), ...rows] : rows)
+ ctx.transcript.setHistoryItems(info ? [introMsg(info), ...rows] : rows)
}
if (r.info) {
- patchUiState({ info: r.info })
+ patchUiState({ info })
}
if (r.usage) {
@@ -294,17 +317,15 @@ export const sessionCommands: SlashCommand[] = [
help: 'branch the session',
name: 'branch',
run: (arg, ctx) => {
- const prevSid = ctx.sid
-
ctx.gateway.rpc<SessionBranchResponse>('session.branch', { name: arg, session_id: ctx.sid }).then(
ctx.guarded<SessionBranchResponse>(r => {
if (!r.session_id) {
return
}
- void ctx.session.closeSession(prevSid)
- patchUiState({ sid: r.session_id })
- ctx.session.setSessionStartedAt(Date.now())
+ // Resume hydrates destination authority/history before closing the
+ // source; changing only sid would inherit the source owner's epoch.
+ ctx.session.resumeById(r.session_id)
ctx.transcript.sys(`branched → ${r.title ?? ''}`)
})
)
diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.ts
index 16406e0143e..5d96269b543 100644
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@ -1,9 +1,12 @@
import type { GatewayClient } from '../gatewayClient.js'
import type { InputDetectDropResponse, PromptSubmitResponse } from '../gatewayTypes.js'
+import type { QueueItem } from '../hooks/useQueue.js'
+import { savePendingInput } from '../lib/pendingInputs.js'
import type { Msg } from '../types.js'
+import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
-import { getUiState, patchUiState } from './uiStore.js'
+import { patchUiState } from './uiStore.js'
const SESSION_BUSY_RE = /session busy|waiting for model response/i
@@ -11,7 +14,7 @@ export const isSessionBusyError = (e: unknown) => e instanceof Error && SESSION_
export interface SubmitPromptDeps {
appendMessage: (msg: Msg) => void
- enqueue: (text: string) => void
+ enqueue: (text: string, display?: string, destination?: SubmissionDestination) => void
expand: (text: string) => string
gw: GatewayClient
setLastUserMsg: (value: string) => void
@@ -50,57 +53,139 @@ export function submitPrompt(
deps: SubmitPromptDeps,
showUserMessage = true,
displayOverride?: string,
- opts: { skipDetectDrop?: boolean } = {}
+ opts: { skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem } = {}
): void {
- const sid = getUiState().sid
+ const destination = opts.destination ?? captureDestination()
+ const { sid } = destination
+ const focused = () => isCurrentDestination(destination)
if (!sid) {
return deps.sys('session not ready yet')
}
// Close the async-busy gap up front, before the detect_drop round-trip.
- markSubmitting()
+ if (focused()) {
+ markSubmitting()
+ }
const startSubmit = (displayText: string, submitText: string, show = true) => {
- const liveSid = getUiState().sid
+ if (focused()) {
+ turnController.clearStatusTimer()
+ deps.setLastUserMsg(text)
+
+ if (show) {
+ deps.appendMessage({ role: 'user', text: displayOverride || displayText })
+ }
- if (!liveSid) {
- return deps.sys('session not ready yet')
+ patchUiState({ busy: true, status: 'running…' })
+ turnController.bufRef = ''
+ turnController.interrupted = false
}
- turnController.clearStatusTimer()
- deps.setLastUserMsg(text)
+ const item = opts.queueItem
- if (show) {
- deps.appendMessage({ role: 'user', text: displayOverride || displayText })
+ if (item) {
+ item.preparedText ??= submitText
+ savePendingInput(item)
}
- patchUiState({ busy: true, status: 'running…' })
- turnController.bufRef = ''
- turnController.interrupted = false
-
deps.gw
- .request<PromptSubmitResponse>('prompt.submit', { session_id: liveSid, text: submitText })
+ .request<PromptSubmitResponse>('prompt.submit', {
+ session_id: sid,
+ text: item?.preparedText ?? submitText,
+ ...(item ? { submission_id: item.submissionId, queued: item.queued !== false } : {})
+ })
.then(r => {
+ if (item) {
+ const accepted =
+ r?.admission_id === item.submissionId &&
+ Boolean(destination.storedSid) &&
+ r?.target_session_id === destination.storedSid &&
+ r?.target_profile_home === destination.profileHome &&
+ ['queued', 'started', 'terminal', 'unknown'].includes(r?.status ?? '')
+
+ item.settle?.(accepted)
+
+ if (!accepted && focused()) {
+ deps.sys('admission not confirmed — input retained; use Alt+K to retry with the same identity')
+ patchUiState({ status: 'admission unconfirmed' })
+ }
+ }
+
// The gateway consumed a typed voice stop phrase server-side (voice
// chat ended, no turn started) — release the busy latch; the
// voice.transcript {stop_phrase} event handles the mode flags + notice.
- if (r?.voice_stopped) {
+ if (r?.voice_stopped && focused()) {
patchUiState({ busy: false, status: 'ready' })
}
})
- .catch((e: Error) => {
+ .catch(async (e: Error & { code?: number }) => {
+ // 4094 is a pre-admission refusal, not an ambiguous write. Special
+ // compute modes still support legacy submit; retry only this refusal,
+ // keeping the prepared payload, destination and queue mode unchanged.
+ if (item && e.code === 4094) {
+ if (focused()) {deps.sys('durable admission unavailable for this session — using legacy delivery')}
+
+ try {
+ const r = await deps.gw.request<PromptSubmitResponse>('prompt.submit', {
+ session_id: sid,
+ text: item.preparedText ?? submitText,
+ queued: item.queued !== false
+ })
+
+ const accepted = Boolean(r?.voice_stopped || ['streaming', 'queued', 'steered', 'redirected'].includes(r?.status ?? ''))
+ item.settle?.(accepted)
+
+ if (focused()) {
+ if (r?.voice_stopped) {patchUiState({ busy: false, status: 'ready' })}
+ else if (!accepted) {
+ deps.sys('legacy delivery unconfirmed — input retained; retry may duplicate execution')
+ patchUiState({ status: 'delivery unconfirmed' })
+ }
+ }
+ } catch (error) {
+ item.settle?.(false)
+
+ if (focused()) {
+ deps.sys(`legacy delivery unconfirmed: ${error instanceof Error ? error.message : String(error)} — input retained; retry may duplicate execution`)
+ patchUiState({ status: 'delivery unconfirmed' })
+ }
+ }
+
+ return
+ }
+
+ if (item) {
+ item.settle?.(false)
+
+ if (focused()) {
+ deps.sys(`input retained: ${e.message} — Alt+K retries the same submission`)
+ patchUiState({ status: 'admission unconfirmed' })
+ }
+
+ return
+ }
+
// Defensive: prompt.submit no longer rejects a mid-turn send with
// "session busy" (the gateway queues it and returns success), but keep
// the re-queue path as a safety net for any future/legacy gateway that
// still errors, so a message is never silently dropped.
if (isSessionBusyError(e)) {
- deps.enqueue(submitText)
+ deps.enqueue(submitText, displayOverride, destination)
+
+ if (!focused()) {
+ return
+ }
+
patchUiState({ busy: true, status: 'queued for next turn' })
return deps.sys(`queued: "${submitText.slice(0, 50)}${submitText.length > 50 ? '…' : ''}"`)
}
+ if (!focused()) {
+ return
+ }
+
deps.sys(`error: ${e.message}`)
patchUiState({ busy: false, status: 'ready' })
})
@@ -115,6 +200,10 @@ export function submitPrompt(
// shows as an `[[ Image N ]]` token, and a matched non-image path is rewritten
// in place. Announcing it a second time above the status bar was the old
// out-of-band attachment UI.
+ if (opts.queueItem?.preparedText !== undefined) {
+ return startSubmit(text, opts.queueItem.preparedText, showUserMessage)
+ }
+
if (opts.skipDetectDrop) {
return startSubmit(text, deps.expand(text), showUserMessage)
}
diff --git a/ui-tui/src/app/submissionDestination.ts b/ui-tui/src/app/submissionDestination.ts
new file mode 100644
index 00000000000..904beea62f6
--- /dev/null
+++ b/ui-tui/src/app/submissionDestination.ts
@@ -0,0 +1,48 @@
+import { realpathSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { basename, dirname, join, resolve } from 'node:path'
+
+import { getUiState } from './uiStore.js'
+
+export interface SubmissionDestination {
+ readonly sid: string | null
+ readonly storedSid?: string | null
+ readonly profile: string
+ readonly profileHome: string
+}
+
+// Resolve existing ancestors too: a new profile may not have been created yet.
+function canonicalHome(path: string): string {
+ try {
+ return realpathSync(path)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ throw error
+ }
+
+ const parent = dirname(path)
+
+ return parent === path ? path : join(canonicalHome(parent), basename(path))
+ }
+}
+
+export function captureDestination(): SubmissionDestination {
+ const { sid, info } = getUiState()
+
+ return Object.freeze({
+ sid,
+ storedSid: info?.stored_session_id || null,
+ profile: info?.profile_name || 'default',
+ profileHome: canonicalHome(resolve(process.env.HERMES_HOME ?? join(homedir(), '.hermes')))
+ })
+}
+
+export function isCurrentDestination(destination: SubmissionDestination): boolean {
+ const current = captureDestination()
+
+ return (
+ current.sid === destination.sid &&
+ current.profile === destination.profile &&
+ current.profileHome === destination.profileHome
+ )
+}
diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.ts
index 8454ebd61fc..a4dd0300531 100644
--- a/ui-tui/src/app/useComposerState.ts
+++ b/ui-tui/src/app/useComposerState.ts
@@ -28,6 +28,7 @@ import type {
UseComposerStateResult
} from './interfaces.js'
import { $isBlocked } from './overlayStore.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { getUiState } from './uiStore.js'
const TOKEN_MAX_COUNT = 32
@@ -107,7 +108,12 @@ export function looksLikeDroppedPath(text: string): boolean {
export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions): UseComposerStateResult {
const [input, setInputState] = useState('')
- const [inputBuf, setInputBuf] = useState<string[]>([])
+ const [inputBuf, setInputBufState] = useState<string[]>([])
+ const composerRevision = useRef(0)
+ const setInputBuf = useCallback<StateSetter<string[]>>(next => {
+ composerRevision.current++
+ setInputBufState(next)
+ }, [])
const [tokens, setTokens] = useState<ComposerToken[]>([])
// Tokens and the input line are read from keystroke handlers that run several
// times before React re-renders, so the refs — not the state — are the source
@@ -116,6 +122,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const tokensRef = useRef<ComposerToken[]>([])
const setInput = useCallback<StateSetter<string>>(next => {
+ composerRevision.current++
inputRef.current = typeof next === 'function' ? next(inputRef.current) : next
setInputState(inputRef.current)
}, [])
@@ -129,6 +136,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const { querier } = useStdin() as { querier: Parameters<typeof readOsc52Clipboard>[0] }
const {
+ stage,
queueRef,
queueEditRef,
queuedDisplay,
@@ -151,7 +159,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
setQueueEdit(null)
setHistoryIdx(null)
historyDraftRef.current = ''
- }, [historyDraftRef, setComposerTokens, setHistoryIdx, setInput, setQueueEdit])
+ }, [historyDraftRef, setComposerTokens, setHistoryIdx, setInput, setInputBuf, setQueueEdit])
/**
* Deleting an `[[ Image N ]]` token IS how you unattach the image — there is
@@ -207,7 +215,9 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
*/
const pasteClipboardImage = useCallback(
async (value: string, cursor: number, quiet: boolean): Promise<ComposerPasteResult | null> => {
- const sid = getUiState().sid
+ const destination = captureDestination()
+ const revision = composerRevision.current
+ const { sid } = destination
if (!sid) {
return null
@@ -217,6 +227,8 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
.request<ClipboardPasteResponse & { path?: string }>('clipboard.paste', { session_id: sid })
.catch(() => null)
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+
if (r?.attached) {
return attachImageToken(r, value, cursor)
}
@@ -232,6 +244,8 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const handleResolvedPaste = useCallback(
async ({ bracketed, cursor, text, value }: Omit<PasteEvent, 'hotkey'>): Promise<ComposerPasteResult | null> => {
+ const destination = captureDestination()
+ const revision = composerRevision.current
const cleanedText = stripTrailingPasteNewlines(text)
if (!cleanedText || !/[^\n]/.test(cleanedText)) {
@@ -247,6 +261,8 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
session_id: sid
})
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+
if (attached?.name) {
// Drop an `[[ Image N ]]` token where the path was typed. The old
// path printed a notice above the status bar and left the composer
@@ -258,12 +274,16 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
// Fall back to generic file-drop detection below.
}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+
try {
const dropped = await gw.request<InputDetectDropResponse>('input.detect_drop', {
session_id: sid,
text: cleanedText
})
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+
if (dropped?.matched && dropped.text) {
return insertAtCursor(value, cursor, dropped.text)
}
@@ -272,6 +292,8 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
}
}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+
const lineCount = cleanedText.split('\n').length
const pasteCollapseLines = getUiState().pasteCollapseLines
const pasteCollapseChars = getUiState().pasteCollapseChars
@@ -288,18 +310,19 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const label = pasteTokenLabel(cleanedText, lineCount)
const inserted = insertAtCursor(value, cursor, label)
- setComposerTokens(prev => trimTokens([...prev, { kind: 'paste', label, text: cleanedText }]))
+ const token: ComposerToken = { kind: 'paste', label, text: cleanedText }
+ setComposerTokens(prev => trimTokens([...prev, token]))
void gw
.request<{ path?: string }>('paste.collapse', { text: cleanedText })
.then(r => {
const path = r?.path
- if (!path) {
+ if (!path || !isCurrentDestination(destination)) {
return
}
- setComposerTokens(prev => prev.map(t => (t.label === label ? { ...t, path } : t)))
+ setComposerTokens(prev => prev.map(t => (t === token ? { ...t, path } : t)))
})
.catch(() => {})
@@ -310,6 +333,10 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const handleTextPaste = useCallback(
({ bracketed, cursor, hotkey, text, value }: PasteEvent): MaybePromise<ComposerPasteResult | null> => {
+ // Clipboard reads can outlive a focus change, before any gateway RPC starts.
+ const destination = captureDestination()
+ const revision = composerRevision.current
+
if (hotkey) {
const preferOsc52 = isRemoteShellSession(process.env)
@@ -330,6 +357,8 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
})
return readPreferredText.then(async preferredText => {
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+
if (isUsableClipboardText(preferredText)) {
return handleResolvedPaste({ bracketed: false, cursor, text: preferredText, value })
}
@@ -350,10 +379,12 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
*/
const appendAttachment = useCallback(
(attach: (value: string, cursor: number) => Promise<ComposerPasteResult | null>) => {
+ const destination = captureDestination()
+ const revision = composerRevision.current
const current = inputRef.current
void attach(current, current.length).then(next => {
- if (next) {
+ if (next && (isCurrentDestination(destination) && revision === composerRevision.current)) {
setInput(next.value)
}
})
@@ -369,7 +400,9 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const attachImagePath = useCallback(
(path: string) =>
appendAttachment(async (value, cursor) => {
- const sid = getUiState().sid
+ const destination = captureDestination()
+ const revision = composerRevision.current
+ const { sid } = destination
if (!sid || !path.trim()) {
return null
@@ -378,17 +411,19 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const attached = await gw
.request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid })
.catch((e: Error) => {
- sys(`error: ${e.message}`)
+ if ((isCurrentDestination(destination) && revision === composerRevision.current)) {sys(`error: ${e.message}`)}
return null
})
- return attached?.name ? attachImageToken(attached, value, cursor) : null
+ return (isCurrentDestination(destination) && revision === composerRevision.current) && attached?.name ? attachImageToken(attached, value, cursor) : null
}),
[appendAttachment, attachImageToken, gw, sys]
)
const openEditor = useCallback(async () => {
+ const destination = captureDestination()
+ const revision = composerRevision.current
const dir = mkdtempSync(join(tmpdir(), 'hermes-'))
const file = join(dir, 'prompt.md')
const [cmd, ...args] = resolveEditor()
@@ -412,19 +447,26 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return
}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {
+ enqueue(text, text, destination)
+
+ return
+ }
+
setInput('')
setInputBuf([])
submitRef.current(text)
} finally {
rmSync(dir, { force: true, recursive: true })
}
- }, [input, inputBuf, setInput, submitRef])
+ }, [enqueue, input, inputBuf, setInput, setInputBuf, submitRef])
const actions = useMemo(
() => ({
attachClipboardImage,
attachImagePath,
clearIn,
+ stage,
dequeue,
enqueue,
handleTextPaste,
@@ -445,6 +487,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
attachClipboardImage,
attachImagePath,
clearIn,
+ stage,
dequeue,
enqueue,
handleTextPaste,
@@ -458,6 +501,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
setInput,
setQueueEdit,
takeQ,
+ setInputBuf,
syncTokens
]
)
diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.ts
index a5f258c1829..7eee3566218 100644
--- a/ui-tui/src/app/useInputHandlers.ts
+++ b/ui-tui/src/app/useInputHandlers.ts
@@ -26,7 +26,7 @@ import {
type InputHandlerResult,
type OverlayState
} from './interfaces.js'
-import { $isBlocked, $overlayState, patchOverlayState } from './overlayStore.js'
+import { $isBlocked, $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'
import { turnController } from './turnController.js'
import { patchTurnState } from './turnStore.js'
import { getUiState } from './uiStore.js'
@@ -219,9 +219,13 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {
}
if (overlay.approval) {
+ const fresh = capturePromptResponseGuard('approval', overlay.approval)
+ if (!fresh()) {
+ return
+ }
return gateway
.rpc<ApprovalRespondResponse>('approval.respond', { choice: 'deny', session_id: getUiState().sid })
- .then(r => r && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))
+ .then(r => r && fresh() && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))
}
if (overlay.sudo || overlay.secret) {
@@ -739,7 +743,7 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {
}
if (isAction(key, ch, 'k') && cRefs.queueRef.current.length && live.sid) {
- const next = cActions.dequeue()
+ const next = cActions.dequeue(true)
if (next) {
cActions.setQueueEdit(null)
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index 59c81427f45..f9991a95d51 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -53,9 +53,10 @@ import { createSlashHandler } from './createSlashHandler.js'
import { planGatewayRecovery } from './gatewayRecovery.js'
import { getInputSelection } from './inputSelectionStore.js'
import { type GatewayRpc, type StateSetter, type TranscriptRow } from './interfaces.js'
-import { $overlayState, patchOverlayState } from './overlayStore.js'
+import { $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'
import { $goodVibesTick } from './petFlashStore.js'
import { scrollWithSelectionBy } from './scroll.js'
+import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { patchTurnState, useTurnSelector } from './turnStore.js'
import { $uiState, getUiState, patchUiState } from './uiStore.js'
@@ -88,7 +89,7 @@ const statusColorOf = (status: string, t: { error: string; muted: string; ok: st
}
export interface PromptLiveSessionOptions {
- dispatchSubmission: (full: string) => void
+ dispatchSubmission: (full: string, destination: SubmissionDestination) => void
maybeWarn: (value: unknown) => void
modelArg?: string
newLiveSession: (msg?: string, title?: string) => Promise<null | string> | null | string | void
@@ -126,6 +127,7 @@ export async function startPromptLiveSession({
return null
}
+ const destination = Object.freeze({ ...captureDestination(), sid })
const requestedModel = modelArg ? sessionScopedModelArg(modelArg) : ''
if (requestedModel) {
@@ -137,12 +139,14 @@ export async function startPromptLiveSession({
return sid
}
- sys(`model → ${result.value}`)
- maybeWarn(result)
- onModelSwitched?.(result.value, result)
+ if (isCurrentDestination(destination)) {
+ sys(`model → ${result.value}`)
+ maybeWarn(result)
+ onModelSwitched?.(result.value, result)
+ }
}
- dispatchSubmission(trimmed)
+ dispatchSubmission(trimmed, destination)
return sid
}
@@ -700,13 +704,17 @@ export function useMainApp(gw: GatewayClient) {
return
}
+ const fresh = capturePromptResponseGuard('clarify', clarify)
+ if (!fresh()) {
+ return
+ }
const label = toolTrailLabel('clarify')
turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
patchTurnState({ turnTrail: turnController.turnTools })
rpc<ClarifyRespondResponse>('clarify.respond', { answer, request_id: clarify.requestId }).then(r => {
- if (!r) {
+ if (!r || !fresh()) {
return
}
@@ -749,12 +757,16 @@ export function useMainApp(gw: GatewayClient) {
return
}
+ const fresh = capturePromptResponseGuard('clarify', clarify)
+ if (!fresh()) {
+ return
+ }
rpc<ClarifyRespondResponse & { remaining?: string[] }>('clarify.respond', {
answer,
question_id: qid,
request_id: clarify.requestId
}).then(r => {
- if (!r) {
+ if (!r || !fresh()) {
return
}
@@ -859,7 +871,7 @@ export function useMainApp(gw: GatewayClient) {
const onEvent = useMemo(
() =>
createGatewayEventHandler({
- composer: { setInput: composerActions.setInput },
+ composer: { setInput: composerActions.setInput, enqueue: composerActions.enqueue },
gateway,
session: {
STARTUP_RESUME_ID,
@@ -884,6 +896,7 @@ export function useMainApp(gw: GatewayClient) {
appendMessage,
bellOnComplete,
bellOnPrompt,
+ composerActions.enqueue,
composerActions.setInput,
gateway,
panel,
@@ -1016,13 +1029,21 @@ export function useMainApp(gw: GatewayClient) {
)
const answerApproval = useCallback(
- (choice: string) =>
- respondWith('approval.respond', { choice, session_id: ui.sid }, () => {
+ (choice: string) => {
+ const fresh = capturePromptResponseGuard('approval', overlay.approval)
+ if (!fresh()) {
+ return
+ }
+ return respondWith('approval.respond', { choice, session_id: ui.sid }, () => {
+ if (!fresh()) {
+ return
+ }
patchOverlayState({ approval: null })
patchTurnState({ outcome: choice === 'deny' ? 'denied' : `approved (${choice})` })
patchUiState({ status: 'running…' })
- }),
- [respondWith, ui.sid]
+ })
+ },
+ [overlay.approval, respondWith, ui.sid]
)
const answerSudo = useCallback(
@@ -1031,6 +1052,10 @@ export function useMainApp(gw: GatewayClient) {
return
}
+ const fresh = capturePromptResponseGuard('sudo', overlay.sudo)
+ if (!fresh()) {
+ return
+ }
const requestId = overlay.sudo.requestId
if (!pw) {
@@ -1038,6 +1063,9 @@ export function useMainApp(gw: GatewayClient) {
}
return respondWith('sudo.respond', { password: pw, request_id: requestId }, () => {
+ if (!fresh()) {
+ return
+ }
patchOverlayState({ sudo: null })
patchUiState({ status: 'running…' })
})
@@ -1051,6 +1079,10 @@ export function useMainApp(gw: GatewayClient) {
return
}
+ const fresh = capturePromptResponseGuard('secret', overlay.secret)
+ if (!fresh()) {
+ return
+ }
const requestId = overlay.secret.requestId
if (!value) {
@@ -1058,6 +1090,9 @@ export function useMainApp(gw: GatewayClient) {
}
return respondWith('secret.respond', { request_id: requestId, value }, () => {
+ if (!fresh()) {
+ return
+ }
patchOverlayState({ secret: null })
patchUiState({ status: 'running…' })
})
@@ -1093,7 +1128,7 @@ export function useMainApp(gw: GatewayClient) {
const newPromptSession = useCallback(
(prompt: string, modelArg?: string) => {
void startPromptLiveSession({
- dispatchSubmission,
+ dispatchSubmission: (text, destination) => send(text, true, text, value => value, { destination }),
maybeWarn,
modelArg,
newLiveSession: session.newLiveSession,
@@ -1107,7 +1142,7 @@ export function useMainApp(gw: GatewayClient) {
sys
})
},
- [dispatchSubmission, maybeWarn, rpc, session.newLiveSession, sys]
+ [send, maybeWarn, rpc, session.newLiveSession, sys]
)
const hasReasoning = useTurnSelector(state => Boolean(state.reasoning.trim()))
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index cc6d29d162a..dc1ae14ca7d 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -17,12 +17,14 @@ import type {
SessionTitleResponse,
SetupStatusResponse
} from '../gatewayTypes.js'
+import { migratePendingInputs } from '../lib/pendingInputs.js'
import { asRpcResult } from '../lib/rpc.js'
import type { Msg, PanelSection, SessionInfo, Usage } from '../types.js'
import type { ComposerActions, GatewayRpc, StateSetter } from './interfaces.js'
import { patchOverlayState } from './overlayStore.js'
import { scheduleResumeScrollToBottom } from './sessionResumeView.js'
+import { captureDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { patchTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
@@ -141,6 +143,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
)
const cancelResumeScrollRef = useRef<null | (() => void)>(null)
+ const attachmentFlight = useRef(0)
const resetSession = useCallback(() => {
cancelResumeScrollRef.current?.()
@@ -160,6 +163,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
useEffect(
() => () => {
+ attachmentFlight.current++
cancelResumeScrollRef.current?.()
cancelResumeScrollRef.current = null
},
@@ -185,8 +189,12 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const startNewSession = useCallback(
async (msg?: string, title?: string, keepCurrent = false) => {
+ const flight = ++attachmentFlight.current
+ const previousSid = getUiState().sid
const setup = await rpc<SetupStatusResponse>('setup.status', {})
+ if (flight !== attachmentFlight.current) {return null}
+
if (setup?.provider_configured === false) {
panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
patchUiState({ status: 'setup required' })
@@ -194,21 +202,23 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
return null
}
- const previousSid = getUiState().sid
-
if (!keepCurrent) {
await closeSession(previousSid)
+
+ if (flight !== attachmentFlight.current) {return null}
}
const r = await rpc<SessionCreateResponse>('session.create', { cols: colsRef.current })
+ if (flight !== attachmentFlight.current) {return null}
+
if (!r) {
patchUiState({ status: 'ready' })
return null
}
- const info = r.info ?? null
+ const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null
const requestedTitle = title?.trim() ?? ''
resetSession()
@@ -286,11 +296,13 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const activateLiveSession = useCallback(
(id: string) => {
+ const flight = ++attachmentFlight.current
patchOverlayState({ sessions: false })
patchUiState({ status: 'switching session…' })
gw.request<SessionActivateResponse>('session.activate', { session_id: id })
.then(raw => {
+ if (flight !== attachmentFlight.current) {return}
const r = asRpcResult<SessionActivateResponse>(raw)
if (!r) {
@@ -299,9 +311,11 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
return patchUiState({ status: 'ready' })
}
- const info = r.info ?? null
+ const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null
const running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')
+ if (info) {info.stored_session_id = r.session_key || info.stored_session_id}
+
resetSession()
setSessionStartedAt(r.started_at ? r.started_at * 1000 : Date.now())
const transcript = [...toTranscriptMessages(r.messages), ...liveSessionInflightMessages(r.inflight)]
@@ -319,6 +333,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)
})
.catch((e: Error) => {
+ if (flight !== attachmentFlight.current) {return}
sys(`error: ${e.message}`)
patchUiState({ status: 'ready' })
})
@@ -328,10 +343,19 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const resumeById = useCallback(
(id: string) => {
+ const flight = ++attachmentFlight.current
+ const current = captureDestination()
+ const previousSid = current.sid
+
+ const destination = current.sid === id || current.storedSid === id
+ ? current : { ...current, sid: id, storedSid: id }
+
patchOverlayState({ sessions: false })
patchUiState({ status: 'resuming…' })
rpc<SetupStatusResponse>('setup.status', {}).then(setup => {
+ if (flight !== attachmentFlight.current) {return}
+
if (setup?.provider_configured === false) {
panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
patchUiState({ status: 'setup required' })
@@ -339,10 +363,9 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
return
}
- const previousSid = getUiState().sid
-
gw.request<SessionResumeResponse>('session.resume', { cols: colsRef.current, session_id: id })
.then(raw => {
+ if (flight !== attachmentFlight.current) {return}
const r = asRpcResult<SessionResumeResponse>(raw)
if (!r) {
@@ -351,9 +374,14 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
return patchUiState({ status: 'ready' })
}
- const info = r.info ?? null
+ const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null
const running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')
+ if (info) {info.stored_session_id = r.session_key || info.stored_session_id || r.resumed}
+
+ // A successful resume authorizes the requested source → canonical
+ // successor mapping; ordinary focus changes never migrate input.
+ migratePendingInputs(destination, r.session_id, info?.stored_session_id)
resetSession()
setSessionStartedAt(r.started_at ? r.started_at * 1000 : Date.now())
@@ -377,6 +405,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
}
})
.catch((e: Error) => {
+ if (flight !== attachmentFlight.current) {return}
sys(`error: ${e.message}`)
patchUiState({ status: 'ready' })
})
diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts
index 57ce9f60f9e..5bfb9134ca4 100644
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@ -4,7 +4,7 @@ import { TYPING_IDLE_MS } from '../config/timing.js'
import { expandTokens } from '../domain/attachments.js'
import { completionToApplyOnSubmit, looksLikeSlashCommand, parseSlashCommand } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
-import type { SessionSteerResponse, ShellExecResponse } from '../gatewayTypes.js'
+import type { ShellExecResponse } from '../gatewayTypes.js'
import { queueItem, type QueueItem } from '../hooks/useQueue.js'
import { asRpcResult } from '../lib/rpc.js'
import { hasInterpolation, INTERPOLATION_RE } from '../protocol/interpolation.js'
@@ -12,6 +12,7 @@ import type { Msg } from '../types.js'
import type { ComposerActions, ComposerRefs, ComposerState, ComposerToken } from './interfaces.js'
import { submitPrompt } from './submissionCore.js'
+import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { getUiState, patchUiState } from './uiStore.js'
@@ -102,12 +103,17 @@ export function useSubmission(opts: UseSubmissionOptions) {
showUserMessage = true,
displayText?: string,
expandOverride?: (value: string) => string,
- submitOpts: { skipDetectDrop?: boolean } = {}
+ submitOpts: { skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem } = {}
) => {
// Read tokens off the ref, not render state: a paste immediately followed
// by Enter submits before React has re-rendered with the new token.
const expand = expandOverride ?? expandTokens(composerRefs.tokensRef.current)
+ const destination = submitOpts.destination ?? captureDestination()
+
+ const item =
+ submitOpts.queueItem ?? (destination.sid ? composerActions.stage?.(text, displayText, destination) : undefined)
+
submitPrompt(
text,
{
@@ -120,20 +126,26 @@ export function useSubmission(opts: UseSubmissionOptions) {
},
showUserMessage,
displayText,
- submitOpts
+ { ...submitOpts, destination, queueItem: item }
)
},
[appendMessage, composerActions, composerRefs, gw, setLastUserMsg, sys]
)
const shellExec = useCallback(
- (cmd: string) => {
+ (cmd: string, destination = captureDestination(), item?: QueueItem) => {
+ const focused = () => isCurrentDestination(destination)
appendMessage({ role: 'user', text: `!${cmd}` })
patchUiState({ busy: true, status: 'running…' })
- gw.request<ShellExecResponse>('shell.exec', { command: cmd })
+ gw.request<ShellExecResponse>('shell.exec', { command: cmd, session_id: destination.sid })
.then(raw => {
const r = asRpcResult<ShellExecResponse>(raw)
+ item?.settle?.(Boolean(r))
+
+ if (!focused()) {
+ return
+ }
if (!r) {
return sys('error: invalid response: shell.exec')
@@ -149,21 +161,31 @@ export function useSubmission(opts: UseSubmissionOptions) {
sys(`exit ${r.code}`)
}
})
- .catch((e: Error) => sys(`error: ${e.message}`))
- .finally(() => patchUiState({ busy: false, status: 'ready' }))
+ .catch((e: Error) => {
+ item?.settle?.(false)
+
+ if (focused()) {
+ sys(`error: ${e.message}`)
+ }
+ })
+ .finally(() => {
+ if (focused()) {
+ patchUiState({ busy: false, status: 'ready' })
+ }
+ })
},
[appendMessage, gw, sys]
)
const interpolate = useCallback(
- (text: string, then: (result: string) => void) => {
+ (text: string, then: (result: string) => void, destination = captureDestination()) => {
patchUiState({ status: 'interpolating…' })
const matches = [...text.matchAll(new RegExp(INTERPOLATION_RE.source, 'g'))]
Promise.all(
matches.map(m =>
gw
- .request<ShellExecResponse>('shell.exec', { command: m[1]! })
+ .request<ShellExecResponse>('shell.exec', { command: m[1]!, session_id: destination.sid })
.then(raw => {
const r = asRpcResult<ShellExecResponse>(raw)
@@ -177,18 +199,30 @@ export function useSubmission(opts: UseSubmissionOptions) {
)
const sendQueued = useCallback(
- (text: string) => {
+ (input: string | QueueItem) => {
+ const item = typeof input === 'string' ? undefined : input
+ const text = item?.preparedText ?? (typeof input === 'string' ? input : input.text)
+ const destination = item?.destination ?? captureDestination()
+
+ if (item?.preparedText !== undefined) {
+ return send(text, true, item.display, value => value, { destination, queueItem: item, skipDetectDrop: true })
+ }
+
if (text.startsWith('!')) {
- return shellExec(text.slice(1).trim())
+ return shellExec(text.slice(1).trim(), destination, item)
}
if (hasInterpolation(text)) {
patchUiState({ busy: true })
- return interpolate(text, send)
+ return interpolate(
+ text,
+ result => send(result, true, undefined, value => value, { destination, queueItem: item }),
+ destination
+ )
}
- send(text)
+ send(text, true, undefined, value => value, { destination, queueItem: item })
},
[interpolate, send, shellExec]
)
@@ -207,50 +241,41 @@ export function useSubmission(opts: UseSubmissionOptions) {
const handleBusyInput = useCallback(
(item: QueueItem, opts: { fallbackToFront?: boolean } = {}) => {
const live = getUiState()
+ const destination = captureDestination()
const mode = live.busyInputMode
const enqueueText = () => {
if (opts.fallbackToFront) {
- composerActions.prependQueue(item)
+ composerActions.prependQueue(item, destination)
} else {
- composerActions.enqueue(item.text, item.display)
+ composerActions.enqueue(item.text, item.display, destination)
}
}
- const fallback = (note: string) => {
- enqueueText()
- sys(note)
- }
-
if (mode === 'queue') {
return enqueueText()
}
- if (mode === 'steer' && live.sid) {
- gw.request<SessionSteerResponse>('session.steer', { session_id: live.sid, text: item.text })
- .then(raw => {
- const r = asRpcResult<SessionSteerResponse>(raw)
-
- if (r?.status !== 'queued') {
- fallback('steer rejected — message queued for next turn')
- }
- })
- .catch(() => fallback('steer failed — message queued for next turn'))
-
- return
+ if (item.settle) {
+ item.queued = false
}
// The gateway owns the atomic redirect decision because it knows whether
// the agent is in model generation, tool execution, or an older runtime.
// Reuse the normal submit pipeline so the correction gets its user bubble
// and file-drop interpolation exactly once.
- send(item.text)
+ send(item.text, true, item.display, value => value, { destination, queueItem: item.settle ? item : undefined })
},
- [composerActions, gw, send, sys]
+ [composerActions, send]
)
const dispatchSubmission = useCallback(
- (full: string) => {
+ (input: string | QueueItem) => {
+ if (typeof input !== 'string') {
+ return sendQueued(input)
+ }
+ const full = input
+
if (!full.trim()) {
return
}
@@ -260,6 +285,7 @@ export function useSubmission(opts: UseSubmissionOptions) {
// nothing — a detached image can't be re-attached by recalling the text.
// Idempotent on token-free text, so re-submitting a recalled entry is
// stable.
+ const destination = captureDestination()
const submissionTokens = [...composerRefs.tokensRef.current]
const submission = prepareSubmission(full, submissionTokens)
const toHistory = submission.text
@@ -297,7 +323,7 @@ export function useSubmission(opts: UseSubmissionOptions) {
if (!live.sid) {
composerActions.pushHistory(toHistory)
- composerActions.enqueue(full)
+ composerActions.enqueue(submission.text, submission.display)
composerActions.clearIn()
return
@@ -325,20 +351,28 @@ export function useSubmission(opts: UseSubmissionOptions) {
return handleBusyInput(picked, { fallbackToFront: true })
}
- return sendQueued(picked.text)
+ return sendQueued(picked)
}
composerActions.pushHistory(toHistory)
if (getUiState().busy) {
- return handleBusyInput(queueItem(full))
+ return handleBusyInput(queueItem(submission.text, submission.display))
}
if (shouldInterpolateSubmission(full)) {
patchUiState({ busy: true })
- return interpolate(full, text =>
- send(prepareSubmission(text, submissionTokens).text, true, text, value => value)
+ const item = composerActions.stage?.(submission.text, submission.display, destination)
+
+ return interpolate(
+ full,
+ text =>
+ send(prepareSubmission(text, submissionTokens).text, true, text, value => value, {
+ destination,
+ queueItem: item
+ }),
+ destination
)
}
@@ -384,7 +418,7 @@ export function useSubmission(opts: UseSubmissionOptions) {
}
if (doubleTap && live.sid && composerRefs.queueRef.current.length) {
- const next = composerActions.dequeue()
+ const next = composerActions.dequeue(true)
if (next) {
composerActions.setQueueEdit(null)
diff --git a/ui-tui/src/gatewayTypes.ts b/ui-tui/src/gatewayTypes.ts
index 4b0b0be85cd..c785211beb7 100644
--- a/ui-tui/src/gatewayTypes.ts
+++ b/ui-tui/src/gatewayTypes.ts
@@ -182,11 +182,14 @@ export interface SystemBatteryResponse {
// ── Session lifecycle ────────────────────────────────────────────────
export interface SessionCreateResponse {
+ stored_session_id?: string
info?: SessionInfo & { config_warning?: string; credential_warning?: string }
session_id: string
}
export interface SessionResumeResponse {
+ stored_session_id?: string
+ session_key?: string
inflight?: null | SessionInflightTurn
info?: SessionInfo
message_count?: number
@@ -224,6 +227,7 @@ export interface SessionInflightTurn {
}
export interface SessionActivateResponse {
+ stored_session_id?: string
inflight?: null | SessionInflightTurn
info?: SessionInfo
message_count?: number
@@ -342,6 +346,11 @@ export interface SessionSteerResponse {
// ── Prompt / submission ──────────────────────────────────────────────
export interface PromptSubmitResponse {
+ status?: string
+ admission_id?: string
+ target_session_id?: string
+ target_profile_home?: string
+ outcome?: string | null
ok?: boolean
/** Set when the submitted text was a bare voice stop phrase consumed
* server-side to end the voice chat instead of starting a turn. */
diff --git a/ui-tui/src/hooks/useQueue.ts b/ui-tui/src/hooks/useQueue.ts
index 2e49b407fb2..63e87de1972 100644
--- a/ui-tui/src/hooks/useQueue.ts
+++ b/ui-tui/src/hooks/useQueue.ts
@@ -1,11 +1,31 @@
+import { randomUUID } from 'node:crypto'
+
import { useStore } from '@nanostores/react'
-import { useCallback, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { captureDestination, type SubmissionDestination } from '../app/submissionDestination.js'
import { $uiState, getUiState } from '../app/uiStore.js'
+import {
+ loadPendingInputs,
+ pendingDestinationKey,
+ pendingInputOwner,
+ pendingInputRevision,
+ removePendingInput,
+ savePendingInput
+} from '../lib/pendingInputs.js'
export interface QueueItem {
display: string
text: string
+ queued?: boolean
+ createdAt?: number
+ submissionId?: string
+ destination?: SubmissionDestination
+ ownerDestination?: SubmissionDestination
+ inFlight?: boolean
+ failed?: boolean
+ preparedText?: string
+ settle?: (accepted: boolean) => void
}
export const queueItem = (text: string, display = text): QueueItem => ({ display, text })
@@ -25,10 +45,9 @@ export function takeQueueItem(queue: QueueItem[], index: number, editedDisplay?:
return item
}
- return {
- display: editedDisplay,
- text: editedDisplay.includes(item.display) ? editedDisplay.replace(item.display, item.text) : editedDisplay
- }
+ const text = editedDisplay.includes(item.display) ? editedDisplay.replace(item.display, item.text) : editedDisplay
+
+ return text === item.text ? { ...item, display: editedDisplay } : { display: editedDisplay, text }
}
// Mutates `arr` in place; returned reference is the same input array, kept
@@ -44,36 +63,83 @@ export function removeAtInPlace<T>(arr: T[], i: number): T[] {
}
interface PendingQueue {
+ revision?: number
+ destination?: SubmissionDestination
edit: number | null
items: QueueItem[]
}
export function useQueue() {
- useStore($uiState)
+ const ui = useStore($uiState)
const queues = useRef(new Map<string, PendingQueue>())
const unbound = useRef<PendingQueue>({ edit: null, items: [] })
const [, refresh] = useState(0)
- const getQueue = useCallback(() => {
- const { sid, info } = getUiState()
+ const getQueue = useCallback((destination = captureDestination()) => {
+ // Apply compression before resolving a queue, including through stale callbacks.
+ for (const [oldKey, source] of queues.current) {
+ const owner = pendingInputOwner(source.destination!)
+ const newKey = pendingDestinationKey(owner)
+
+ if (newKey === oldKey) {
+ continue
+ }
+
+ const target = queues.current.get(newKey) ?? { destination: owner, edit: null, items: [] }
+ const edited = source.edit === null ? undefined : source.items[source.edit]
+
+ for (const item of source.items) {
+ item.ownerDestination = owner
+
+ if (!item.inFlight && !item.failed) {
+ item.destination = owner
+ }
+ }
+
+ const retained = new Map([...target.items, ...source.items].map(item => [item.submissionId, item]))
+ target.items = loadPendingInputs(owner).map(item => retained.get(item.submissionId) ?? item)
+
+ if (edited) {
+ target.edit = target.items.indexOf(edited)
+ }
+
+ queues.current.delete(oldKey)
+ queues.current.set(newKey, target)
+ }
+
+ destination = pendingInputOwner(destination)
+ const { sid } = destination
if (!sid) {
return unbound.current
}
- const key = JSON.stringify([info?.profile_name || 'default', sid])
+ const key = pendingDestinationKey(destination)
let queue = queues.current.get(key)
if (!queue) {
- queue = { edit: null, items: [] }
+ queue = { destination, edit: null, items: loadPendingInputs(destination) }
queues.current.set(key, queue)
}
+ if (queue.revision !== pendingInputRevision) {
+ const retained = new Map(queue.items.map(item => [item.submissionId, item]))
+ const edited = queue.edit === null ? undefined : queue.items[queue.edit]
+ queue.items = loadPendingInputs(destination).map(item => retained.get(item.submissionId) ?? item)
+ queue.edit = edited ? queue.items.indexOf(edited) : null
+ queue.revision = pendingInputRevision
+ }
+
// Input typed before any session exists belongs to the next attachment,
// unlike a bound session's queue, which must never migrate on navigation.
if (unbound.current.items.length) {
const offset = queue.items.length
- queue.items.push(...unbound.current.items)
+
+ for (const item of unbound.current.items) {
+ item.destination = destination
+ savePendingInput(item)
+ queue.items.push(item)
+ }
if (unbound.current.edit !== null) {
queue.edit = offset + unbound.current.edit
@@ -108,7 +174,11 @@ export function useQueue() {
[getQueue]
)
- const queuedDisplay = queueRef.current.map(item => item.display)
+ const queuedDisplay = [
+ ...queueRef.current.map(item => `${item.failed ? '[unconfirmed · Alt+K retry] ' : ''}${item.display}`),
+ ...(ui.info?.pending_submissions ?? []).map(item => `[${item.status} · ${item.admission_id}] ${item.user}`)
+ ]
+
const queueEditIdx = queueEditRef.current
const syncQueue = useCallback(() => refresh(version => version + 1), [])
@@ -121,50 +191,182 @@ export function useQueue() {
)
const enqueue = useCallback(
- (text: string, display = text) => {
- queueRef.current.push(queueItem(text, display))
+ (text: string, display = text, destination?: SubmissionDestination) => {
+ const owner = pendingInputOwner(destination ?? captureDestination())
+ const queue = getQueue(owner)
+
+ const item = {
+ ...queueItem(text, display),
+ submissionId: randomUUID(),
+ destination: owner,
+ createdAt: Math.max(Date.now(), (queue.items.at(-1)?.createdAt ?? 0) + 1)
+ }
+
+ savePendingInput(item)
+ queue.items.push(item)
syncQueue()
+
+ return item
},
- [queueRef, syncQueue]
+ [getQueue, syncQueue]
)
const prependQ = useCallback(
- (item: QueueItem) => {
- prependQueueItem(queueRef.current, item)
+ (item: QueueItem, destination?: SubmissionDestination) => {
+ const queue = getQueue(destination)
+ item.inFlight = false
+ item.submissionId ??= randomUUID()
+ item.destination ??= destination ?? captureDestination()
+ savePendingInput(item)
+
+ if (!queue.items.includes(item)) {
+ prependQueueItem(queue.items, item)
+ }
+
syncQueue()
},
- [queueRef, syncQueue]
+ [getQueue, syncQueue]
)
- const dequeue = useCallback(() => {
- const head = queueRef.current.shift()?.text
- syncQueue()
+ const claim = useCallback(
+ (queue: PendingQueue, item: QueueItem) => {
+ item.submissionId ??= randomUUID()
+ item.destination ??= captureDestination()
+ item.inFlight = true
+ item.failed = false
+ savePendingInput(item)
+ let confirmed = false
+
+ item.settle = accepted => {
+ if (confirmed) {
+ return
+ }
+
+ // Resolve migrations while the attempted state still protects the receipt target.
+ getQueue()
+ confirmed = accepted
+ item.inFlight = false
+ item.failed = !accepted
+
+ if (accepted) {
+ removePendingInput(item)
+
+ for (const pending of queues.current.values()) {
+ removeAtInPlace(pending.items, pending.items.indexOf(item))
+ }
+
+ removeAtInPlace(queue.items, queue.items.indexOf(item))
+ } else {
+ savePendingInput(item)
+ }
- return head
- }, [queueRef, syncQueue])
+ syncQueue()
+ }
+
+ syncQueue()
+
+ return item
+ },
+ [getQueue, syncQueue]
+ )
+
+ useEffect(() => {
+ const queue = getQueue()
+
+ for (const receipt of getUiState().info?.pending_submissions ?? []) {
+ const item = queue.items.find(
+ item =>
+ item.submissionId === receipt.admission_id &&
+ Boolean(item.destination?.storedSid) &&
+ item.destination?.storedSid === receipt.target_session_id &&
+ item.destination?.profileHome === receipt.target_profile_home
+ )
+
+ if (!item) {
+ continue
+ }
+
+ if (item.settle) {
+ item.settle(true)
+ } else {
+ removePendingInput(item)
+ removeAtInPlace(queue.items, queue.items.indexOf(item))
+ syncQueue()
+ }
+ }
+ }, [ui.info, getQueue, syncQueue])
+
+ const stage = useCallback(
+ (text: string, display = text, destination = captureDestination()) => {
+ const item = enqueue(text, display, destination)
+ item.queued = false
+
+ return claim(getQueue(destination), item)
+ },
+ [enqueue, claim, getQueue]
+ )
+
+ const dequeue = useCallback(
+ (retry = false) => {
+ const queue = getQueue()
+ const item = queue.items[0]
+
+ if (!item || item.inFlight || (item.failed && !retry)) {
+ return undefined
+ }
+
+ return claim(queue, item)
+ },
+ [getQueue, claim]
+ )
const takeQ = useCallback(
(i: number, editedDisplay?: string) => {
- const item = takeQueueItem(queueRef.current, i, editedDisplay)
+ const queue = getQueue()
- if (item) {
- syncQueue()
+ if (queue.items[i]?.inFlight) {
+ return undefined
}
- return item
+ const previous = queue.items[i]
+ const item = takeQueueItem(queue.items, i, editedDisplay)
+
+ if (!item) {
+ return undefined
+ }
+
+ if (previous && previous.submissionId !== item.submissionId) {
+ removePendingInput(previous)
+ }
+
+ queue.items.splice(i, 0, item)
+
+ return claim(queue, item)
},
- [queueRef, syncQueue]
+ [getQueue, claim]
)
const removeQ = useCallback(
(i: number) => {
- takeQ(i)
+ if (queueRef.current[i]?.inFlight) {
+ return
+ }
+
+ const item = queueRef.current[i]
+
+ if (item) {
+ removePendingInput(item)
+ }
+
+ removeAtInPlace(queueRef.current, i)
+ syncQueue()
},
- [takeQ]
+ [queueRef, syncQueue]
)
return {
dequeue,
+ stage,
enqueue,
prependQ,
queueEditIdx,
diff --git a/ui-tui/src/lib/pendingInputs.ts b/ui-tui/src/lib/pendingInputs.ts
new file mode 100644
index 00000000000..1bd4fea9199
--- /dev/null
+++ b/ui-tui/src/lib/pendingInputs.ts
@@ -0,0 +1,173 @@
+import {
+ closeSync,
+ existsSync,
+ fsyncSync,
+ mkdirSync,
+ openSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync
+} from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+import type { SubmissionDestination } from '../app/submissionDestination.js'
+import type { QueueItem } from '../hooks/useQueue.js'
+
+const directory = (home?: string) =>
+ join(home ?? process.env.HERMES_HOME ?? join(homedir(), '.hermes'), 'tui-pending-inputs')
+
+const recordName = /^[0-9a-f-]{36}\.json$/
+const successors = new Map<string, SubmissionDestination>()
+export let pendingInputRevision = 0
+
+export const pendingDestinationKey = (destination: SubmissionDestination) =>
+ JSON.stringify([destination.profileHome, destination.profile, destination.sid])
+
+export function pendingInputOwner(destination: SubmissionDestination): SubmissionDestination {
+ let current = destination
+ const seen = new Set<string>()
+
+ while (!seen.has(pendingDestinationKey(current))) {
+ const key = pendingDestinationKey(current)
+ seen.add(key)
+ const next = successors.get(key)
+
+ if (!next) {
+ break
+ }
+
+ current = next
+ }
+
+ return current
+}
+
+// Resume authorizes the source → successor mapping; navigation alone does not.
+export function migratePendingInputs(previous: SubmissionDestination, successorSid: string, successorStoredSid?: string): void {
+ if (!previous.sid || !successorSid || (previous.sid === successorSid && previous.storedSid === successorStoredSid)) {
+ return
+ }
+
+ const successor = Object.freeze({ ...previous, sid: successorSid, storedSid: successorStoredSid ?? null })
+
+ for (const item of loadPendingInputs(previous)) {
+ item.ownerDestination = successor
+
+ if (!item.failed) {
+ item.destination = successor
+ }
+
+ savePendingInput(item)
+ }
+
+ successors.set(pendingDestinationKey(previous), successor)
+ pendingInputRevision++
+}
+
+function syncDirectory(dir: string) {
+ if (process.platform === 'win32') {
+ return
+ }
+
+ const fd = openSync(dir, 'r')
+
+ try {
+ fsyncSync(fd)
+ } finally {
+ closeSync(fd)
+ }
+}
+
+// Separate files avoid read/modify/write loss between two native clients.
+export function savePendingInput(item: QueueItem): void {
+ if (!item.submissionId || !item.destination?.sid) {
+ return
+ }
+
+ const dir = directory(item.destination?.profileHome)
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ const path = join(dir, `${item.submissionId}.json`)
+ const temporary = `${path}.${process.pid}.tmp`
+ const ownerDestination = pendingInputOwner(item.ownerDestination ?? item.destination)
+ const { submissionId, display, text, preparedText, inFlight, failed, createdAt, queued } = item
+ const destination = inFlight || failed ? item.destination : ownerDestination
+ writeFileSync(
+ temporary,
+ JSON.stringify({
+ submissionId,
+ destination,
+ ownerDestination,
+ display,
+ text,
+ preparedText,
+ createdAt,
+ queued,
+ attempted: inFlight || failed
+ }),
+ { mode: 0o600, flush: true }
+ )
+ renameSync(temporary, path)
+ syncDirectory(dir)
+}
+
+export function removePendingInput(item: QueueItem): void {
+ if (!item.submissionId) {
+ return
+ }
+
+ const dir = directory(item.destination?.profileHome)
+
+ if (!existsSync(dir)) {
+ return
+ }
+
+ rmSync(join(dir, `${item.submissionId}.json`), { force: true })
+ syncDirectory(dir)
+}
+
+export function loadPendingInputs(destination: SubmissionDestination): QueueItem[] {
+ const dir = directory(destination.profileHome)
+
+ if (!existsSync(dir)) {
+ return []
+ }
+
+ return readdirSync(dir)
+ .filter(name => recordName.test(name))
+ .flatMap(name => {
+ // A missing record is a concurrent client's acknowledgement, not corruption.
+ let raw: string
+
+ try {
+ raw = readFileSync(join(dir, name), 'utf8')
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return []
+ }
+
+ throw error
+ }
+
+ const record = JSON.parse(raw)
+
+ if (
+ record.submissionId + '.json' !== name ||
+ typeof record.text !== 'string' ||
+ typeof record.display !== 'string'
+ ) {
+ throw new Error(`Invalid pending input record: ${name}`)
+ }
+
+ const owner = record.ownerDestination ?? record.destination
+
+ if (owner?.sid !== destination.sid || owner?.profile !== destination.profile) {
+ return []
+ }
+
+ return [{ ...record, inFlight: false, failed: Boolean(record.attempted) }]
+ })
+ .sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))
+}
diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.ts
index e9a425b9150..4fbdf5b67ac 100644
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@ -188,6 +188,7 @@ export interface ProjectInfo {
}
export interface SessionInfo {
+ stored_session_id?: string
cwd?: string
fast?: boolean
install_warning?: string
@@ -197,6 +198,17 @@ export interface SessionInfo {
profile_name?: string
project?: null | ProjectInfo
reasoning_effort?: string
+ pending_submissions?: Array<{
+ admission_id: string
+ target_session_id: string
+ target_profile_home: string
+ status: string
+ user: string
+ outcome?: string | null
+ }>
+ execution_epoch?: string
+ execution_generation?: number
+ execution_state?: string
running?: boolean
release_date?: string
service_tier?: string