Skip to content

The agent that grows with you

feat(gateway): steer and edit a canonical queued prompt from Desktop

unsupportedpastels98efa9dfad26
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 0a47553f444..02e7d45269d 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -43,7 +43,17 @@ export const GATEWAY_NOT_CONNECTED_MESSAGE = 'Hermes gateway is not connected'
// the same `onRequest` registry as a request whose `respond` issues the RPC.
const CANONICAL_PROMPT_EVENTS: Record<string, 'approval' | 'clarify'> = { 'approval.request': 'approval', 'clarify.request': 'clarify' }
-const ATTACH_REQUIRED = new Set(['prompt.submit', 'approval.respond', 'clarify.respond', 'session.interrupt', 'prompt.cancel', 'session.rewind'])
+const ATTACH_REQUIRED = new Set([
+ 'prompt.submit',
+ 'approval.respond',
+ 'clarify.respond',
+ 'session.interrupt',
+ 'prompt.cancel',
+ 'session.rewind',
+ 'prompt.steer_queued',
+ 'prompt.replace_queued'
+])
+
// A branch is a CAS mutation on the PARENT: an un-attached parent (right-click on a sidebar row
// that was never opened) has no cached revision, so attach it first to learn one. Move to project
// (`session_key`) is the same CAS mutation on a sidebar row.
diff --git a/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts b/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts
index 36b6675345f..b88fab2e661 100644
--- a/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts
+++ b/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts
@@ -31,3 +31,35 @@ export async function cancelQueuedPrompt(
admission_id: admissionId
})
}
+
+/** Deliver a server-queued admission as a steer into the running turn. The authority consumes the
+ * admission (it never also runs) and its pending fanout retires the card; a refusal
+ * (admission_started, session_idle) leaves it queued. */
+export async function steerQueuedPrompt(
+ sessionId: string | null | undefined,
+ queueSessionKey: string,
+ admissionId: string,
+ request: GatewayRequest
+): Promise<unknown> {
+ return requestForOwnedSession(queueSessionKey, request, 'prompt.steer_queued', {
+ session_id: sessionId ?? queueSessionKey,
+ admission_id: admissionId
+ })
+}
+
+/** Replace a server-queued admission with edited text: the authority cancels it and admits the
+ * edit as a new admission at the back of the FIFO, in one write. */
+export async function replaceQueuedPrompt(
+ sessionId: string | null | undefined,
+ queueSessionKey: string,
+ admissionId: string,
+ text: string,
+ request: GatewayRequest
+): Promise<unknown> {
+ return requestForOwnedSession(queueSessionKey, request, 'prompt.replace_queued', {
+ session_id: sessionId ?? queueSessionKey,
+ admission_id: admissionId,
+ submission_id: crypto.randomUUID(),
+ text
+ })
+}
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 f25788dfb0a..433dace7f50 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
@@ -16,6 +16,7 @@ import {
simulateComposerQueueReloadForTests
} from '@/store/composer-queue'
import { $notifications, clearNotifications } from '@/store/notifications'
+import { reconcilePendingSubmissions } from '@/store/pending-submissions'
import { $connection, setSessionsLoading } from '@/store/session'
import type { QueueEditState } from '../composer-utils'
@@ -32,7 +33,13 @@ import { useComposerQueue } from './use-composer-queue'
const SESSION_KEY = 'stored-session-queue-hook'
function renderQueueHook(
- overrides: { busy?: boolean; draft?: string; onCancel?: () => void; onSteer?: ChatBarProps['onSteer'] } = {}
+ overrides: {
+ busy?: boolean
+ draft?: string
+ onCancel?: () => void
+ onSteer?: ChatBarProps['onSteer']
+ replaceServerQueued?: (admissionId: string, text: string) => Promise<unknown>
+ } = {}
) {
const onSubmit = vi.fn<ChatBarProps['onSubmit']>(async () => true)
const onCancel = overrides.onCancel ?? vi.fn()
@@ -59,6 +66,7 @@ function renderQueueHook(
onSubmit,
queueEditRef,
queueSessionKey: SESSION_KEY,
+ replaceServerQueued: overrides.replaceServerQueued,
sessionId: 'rt-session-queue-hook'
}),
{ initialProps: { busy: overrides.busy ?? false } }
@@ -533,4 +541,81 @@ describe('useComposerQueue scope', () => {
expect(hook.result.current.queuedPrompts).toEqual([])
expect(getQueuedPrompts('session-a').map(entry => entry.text)).toEqual(['for A'])
})
+
+ // RT-35: a server-queued row is an admission in the owner's FIFO. Saving its edit asks the owner
+ // to replace it; the owner's pending fanout then repaints the card (no client-side edit).
+ it('saving an edit of a server-queued row replaces its admission at the owner', async () => {
+ reconcilePendingSubmissions(SESSION_KEY, [
+ { admission_id: 'adm-1', status: 'queued', user: 'old words', controls: ['steer', 'replace'] }
+ ])
+ const replaceServerQueued = vi.fn(async () => ({}))
+ const { draftRef, hook } = renderQueueHook({ busy: true, draft: 'my draft', replaceServerQueued })
+
+ act(() => hook.result.current.beginQueuedEdit(getQueuedPrompts(SESSION_KEY)[0]!))
+ expect(draftRef.current).toBe('old words')
+ draftRef.current = 'new words'
+ act(() => {
+ expect(hook.result.current.exitQueuedEdit('save')).toBe(true)
+ })
+
+ expect(replaceServerQueued).toHaveBeenCalledWith('adm-1', 'new words')
+ expect(getQueuedPrompts(SESSION_KEY).map(entry => entry.text)).toEqual(['old words'])
+ // The pre-edit draft comes back once the owner accepted the replacement.
+ await waitFor(() => expect(draftRef.current).toBe('my draft'))
+ expect(hook.result.current.queueEdit).toBeNull()
+ })
+
+ it('a refused replacement keeps the edited text as an unsent draft and says why', async () => {
+ reconcilePendingSubmissions(SESSION_KEY, [
+ { admission_id: 'adm-1', status: 'queued', user: 'old words', controls: ['steer', 'replace'] }
+ ])
+ clearNotifications()
+
+ const replaceServerQueued = vi.fn(async () => {
+ throw new Error('admission_started')
+ })
+
+ const { draftRef, hook } = renderQueueHook({ busy: true, draft: 'my draft', replaceServerQueued })
+
+ act(() => hook.result.current.beginQueuedEdit(getQueuedPrompts(SESSION_KEY)[0]!))
+ draftRef.current = 'new words'
+ act(() => {
+ expect(hook.result.current.exitQueuedEdit('save')).toBe(true)
+ })
+
+ await waitFor(() => expect(hook.result.current.queueEdit).toBeNull())
+ // Nothing typed is lost: the edit, then the draft it interrupted.
+ expect(draftRef.current).toBe('new words\n\nmy draft')
+ expect($notifications.get().some(n => n.kind === 'warning')).toBe(true)
+ })
+
+ it('a started-row snapshot arriving mid-edit keeps the edit as a draft', () => {
+ reconcilePendingSubmissions(SESSION_KEY, [
+ { admission_id: 'adm-1', status: 'queued', user: 'old words', controls: ['steer', 'replace'] }
+ ])
+ clearNotifications()
+ const replaceServerQueued = vi.fn(async () => ({}))
+ const { draftRef, hook } = renderQueueHook({ busy: true, replaceServerQueued })
+
+ act(() => hook.result.current.beginQueuedEdit(getQueuedPrompts(SESSION_KEY)[0]!))
+ draftRef.current = 'half-typed edit'
+ // The owner claimed the row: the next pending snapshot carries it as started.
+ act(() =>
+ reconcilePendingSubmissions(SESSION_KEY, [{ admission_id: 'adm-1', status: 'started', user: 'old words' }])
+ )
+
+ expect(hook.result.current.queueEdit).toBeNull()
+ expect(draftRef.current).toBe('half-typed edit')
+ expect(replaceServerQueued).not.toHaveBeenCalled()
+ expect($notifications.get().some(n => n.kind === 'warning')).toBe(true)
+ })
+
+ it('a server-queued row whose owner serves no replace stays read-only', () => {
+ reconcilePendingSubmissions(SESSION_KEY, [{ admission_id: 'adm-1', status: 'queued', user: 'old words' }])
+ const { hook } = renderQueueHook({ busy: true, replaceServerQueued: vi.fn(async () => ({})) })
+
+ act(() => hook.result.current.beginQueuedEdit(getQueuedPrompts(SESSION_KEY)[0]!))
+
+ expect(hook.result.current.queueEdit).toBeNull()
+ })
})
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 9e0b71a7d32..c8c2546832e 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
@@ -26,10 +26,12 @@ import {
updateQueuedPrompt,
withQueueDrainClaim
} from '@/store/composer-queue'
+import { activeGateway } from '@/store/gateway'
import { notify } from '@/store/notifications'
import { $sessionsLoading } from '@/store/session'
import { cloneAttachments, type QueueEditState } from '../composer-utils'
+import { replaceQueuedPrompt } from '../discard-lost-prompt'
import { useComposerScope } from '../scope'
import type { ChatBarProps } from '../types'
@@ -83,6 +85,9 @@ interface UseComposerQueueArgs {
onSubmit: ChatBarProps['onSubmit']
queueEditRef: RefObject<QueueEditState | null>
queueSessionKey: ChatBarProps['queueSessionKey']
+ /** Ask the owner to replace a server-queued admission with edited text (default: through the
+ * active gateway, routed to the session's owner). */
+ replaceServerQueued?: (admissionId: string, text: string) => Promise<unknown>
sessionId: string | null | undefined
}
@@ -108,7 +113,20 @@ export function useComposerQueue({
onSubmit,
queueEditRef,
queueSessionKey,
- sessionId
+ sessionId,
+ replaceServerQueued = (admissionId, text) => {
+ const gateway = activeGateway()
+
+ return gateway
+ ? replaceQueuedPrompt(
+ sessionId,
+ activeQueueSessionKey ?? admissionId,
+ admissionId,
+ text,
+ gateway.request.bind(gateway)
+ )
+ : Promise.reject(new Error('Gateway unavailable'))
+ }
}: UseComposerQueueArgs) {
const { t } = useI18n()
const scope = useComposerScope()
@@ -137,6 +155,25 @@ export function useComposerQueue({
)
const editingQueuedPrompt = queueEdit ? (queuedPrompts.find(entry => entry.id === queueEdit.entryId) ?? null) : null
+ // A server row's edit: its id while editing, and while the owner answers its save. Presentation
+ // only: the owner's FIFO keeps running (it may claim the row mid-edit), so the composer keeps
+ // the edited text until the owner accepts the replacement.
+ const serverEditRef = useRef<string | null>(null)
+ const savingServerEditRef = useRef<string | null>(null)
+
+ // The owner refused the replacement or started the row: nothing typed is lost. The edit stays
+ // in the composer as an unsent draft (followed by the draft it interrupted), with the reason.
+ const keepServerEditAsDraft = (edit: QueueEditState, text: string) => {
+ serverEditRef.current = null
+ setQueueEditSnapshot(null)
+ const previous = edit.draft.trim() && edit.draft !== text ? edit.draft : ''
+ loadIntoComposer(previous ? `${text}\n\n${previous}` : text, edit.attachments)
+ notify({
+ kind: 'warning',
+ title: t.promptNotices.sessionCommands.queueEditKeptTitle,
+ message: t.promptNotices.sessionCommands.queueEditKept
+ })
+ }
const currentQueueKeyRef = useRef(activeQueueSessionKey)
currentQueueKeyRef.current = activeQueueSessionKey
@@ -146,10 +183,12 @@ export function useComposerQueue({
const [drainRetryTick, setDrainRetryTick] = useState(0)
const beginQueuedEdit = (entry: QueuedPromptEntry) => {
- if (!activeQueueSessionKey || queueEdit || entry.serverStatus) {
+ // A server row is editable only when its owner serves `replace` for it.
+ if (!activeQueueSessionKey || queueEdit || (entry.serverStatus && !entry.serverControls?.includes('replace'))) {
return
}
+ serverEditRef.current = entry.serverStatus ? entry.id : null
setQueueEditSnapshot({
attachments: cloneAttachments(attachments),
draft: draftRef.current,
@@ -171,6 +210,11 @@ export function useComposerQueue({
return false
}
+ // A server row's text lives in the owner's FIFO: only an explicit save replaces it.
+ if (editingQueuedPrompt?.serverStatus) {
+ return true
+ }
+
const index = queuedPrompts.findIndex(e => e.id === queueEdit.entryId)
const target = index + direction
@@ -241,18 +285,74 @@ export function useComposerQueue({
return false
}
- const saved = updateQueuedPrompt(queueEdit.sessionKey, queueEdit.entryId, {
- attachments: next,
- text: frozen.text,
- displayText: frozen.displayText ?? null,
- frozenTransport: frozen.frozenTransport ?? null
- })
+ if (editingQueuedPrompt?.serverStatus) {
+ // The owner replaces the admission and its pending fanout repaints the card. Text only,
+ // like the row it replaces: the owner serves `replace` only for text-only rows.
+ if (next.length > 0 || !text.trim()) {
+ return false
+ }
+
+ const edited = frozen.frozenTransport ?? frozen.text
+ const entryId = editingQueuedPrompt.id
+
+ if (savingServerEditRef.current === entryId) {
+ return true // its save is already with the owner
+ }
+
+ if (edited !== editingQueuedPrompt.text) {
+ // The edit stays open until the owner answers: only an accepted replacement restores the
+ // pre-edit draft; a refusal (started, queue full, transport) keeps the edited text.
+ const edit = queueEdit
+ savingServerEditRef.current = entryId
+
+ const settle = (accepted: boolean) => {
+ if (savingServerEditRef.current !== entryId) {
+ return
+ }
+
+ savingServerEditRef.current = null
+
+ if (queueEditRef.current?.entryId !== entryId) {
+ return
+ }
- triggerHaptic(saved ? 'success' : 'selection')
+ if (!accepted) {
+ keepServerEditAsDraft(edit, text)
+
+ return
+ }
+
+ serverEditRef.current = null
+ setQueueEditSnapshot(null)
+ loadIntoComposer(edit.draft, edit.attachments)
+ focusInput()
+ }
+
+ replaceServerQueued(entryId, edited).then(
+ () => settle(true),
+ () => settle(false)
+ )
+ triggerHaptic('success')
+
+ return true
+ }
+
+ triggerHaptic('success')
+ } else {
+ const saved = updateQueuedPrompt(queueEdit.sessionKey, queueEdit.entryId, {
+ attachments: next,
+ text: frozen.text,
+ displayText: frozen.displayText ?? null,
+ frozenTransport: frozen.frozenTransport ?? null
+ })
+
+ triggerHaptic(saved ? 'success' : 'selection')
+ }
} else {
triggerHaptic('cancel')
}
+ serverEditRef.current = null
setQueueEditSnapshot(null)
loadIntoComposer(queueEdit.draft, queueEdit.attachments)
focusInput()
@@ -640,7 +740,18 @@ export function useComposerQueue({
}
if (queueEdit.sessionKey === activeQueueSessionKey) {
- if (editingQueuedPrompt) {
+ // A server row the owner started (or retired) is no longer editable.
+ if (editingQueuedPrompt && (!editingQueuedPrompt.serverStatus || editingQueuedPrompt.serverStatus === 'queued')) {
+ return
+ }
+
+ if (savingServerEditRef.current === queueEdit.entryId) {
+ return // our own replacement retired it: the owner's answer settles the edit
+ }
+
+ if (serverEditRef.current === queueEdit.entryId) {
+ keepServerEditAsDraft(queueEdit, draftRef.current)
+
return
}
diff --git a/apps/desktop/src/app/chat/composer/queue-panel.tsx b/apps/desktop/src/app/chat/composer/queue-panel.tsx
index 6c8f98ccf33..ca3a83f1a90 100644
--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx
@@ -95,9 +95,15 @@ export function QueuePanel({
{entries.map(entry => {
const isEditing = editingId === entry.id
const attachmentsCount = entry.attachments.length
+
// Steer only surfaces where it can actually deliver: a live turn to
// redirect and an entry the redirect can carry (text-only, no slash).
- const canSteer = busy && Boolean(onSteerNow) && isSteerableEntry(entry)
+ // A server row can be steered only when its owner serves the verb for it.
+ const canSteer =
+ busy &&
+ Boolean(onSteerNow) &&
+ (entry.serverStatus ? Boolean(entry.serverControls?.includes('steer')) : isSteerableEntry(entry))
+
// The owner died mid-turn and recovered this row as `unknown`: the
// FIFO behind it is paused until someone acknowledges the loss.
const lost = entry.serverStatus === 'unknown'
@@ -194,7 +200,9 @@ interface EntryActionsArgs {
onSteerNow?: (id: string) => void
}
-/** Per-row trailing actions: discard for a lost row, else edit/steer/send for a local one. */
+/** Per-row trailing actions: discard for a lost row, else edit/steer/send for a local one. A
+ * server row gets only the edit/steer its owner serves, never send-next: reordering it would
+ * break the owner's one FIFO. */
function renderEntryActions({
busy,
c,
@@ -223,8 +231,8 @@ function renderEntryActions({
</Button>
</Tip>
) : (
- !entry.serverStatus && (
- <>
+ <>
+ {(!entry.serverStatus || entry.serverControls?.includes('replace')) && (
<Tip label={c.queueEdit}>
<Button
aria-label={c.queueEdit}
@@ -238,21 +246,23 @@ function renderEntryActions({
<Pencil className={iconSize.xs} />
</Button>
</Tip>
- {canSteer && (
- <Tip label={c.queueSteer}>
- <Button
- aria-label={c.queueSteer}
- className="size-5 rounded-md"
- disabled={isEditing}
- onClick={() => onSteerNow?.(entry.id)}
- size="icon-xs"
- type="button"
- variant="ghost"
- >
- <SteeringWheel className={iconSize.xs} />
- </Button>
- </Tip>
- )}
+ )}
+ {canSteer && (
+ <Tip label={c.queueSteer}>
+ <Button
+ aria-label={c.queueSteer}
+ className="size-5 rounded-md"
+ disabled={isEditing}
+ onClick={() => onSteerNow?.(entry.id)}
+ size="icon-xs"
+ type="button"
+ variant="ghost"
+ >
+ <SteeringWheel className={iconSize.xs} />
+ </Button>
+ </Tip>
+ )}
+ {!entry.serverStatus && (
<Tip label={busy ? c.queueSendNext : c.queueSend}>
<Button
aria-label={busy ? c.queueSendNext : c.queueSend}
@@ -266,7 +276,7 @@ function renderEntryActions({
<CornerDownLeft className={iconSize.xs} />
</Button>
</Tip>
- </>
- )
+ )}
+ </>
)
}
diff --git a/apps/desktop/src/app/chat/composer/queue-slot.test.tsx b/apps/desktop/src/app/chat/composer/queue-slot.test.tsx
index 6734b96ce1c..26e625be6cf 100644
--- a/apps/desktop/src/app/chat/composer/queue-slot.test.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-slot.test.tsx
@@ -1,42 +1,124 @@
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { HermesGateway } from '@/hermes'
import { I18nProvider } from '@/i18n/context'
import { en } from '@/i18n/en'
-import { $queuedPromptsBySession, getQueuedPrompts } from '@/store/composer-queue'
+import { $queuedPromptsBySession, enqueueQueuedPrompt, getQueuedPrompts } from '@/store/composer-queue'
import { reconcilePendingSubmissions } from '@/store/pending-submissions'
import { renderComposerQueueSlot } from './queue-slot'
afterEach(() => { cleanup(); $queuedPromptsBySession.set({}); localStorage.clear() })
-it('Delete on a server-queued card cancels its admission at the authority', async () => {
- reconcilePendingSubmissions('stored', [{ admission_id: 'adm-1', status: 'queued', user: 'later please' }])
- const request = vi.fn(async () => ({ admission_id: 'adm-1', status: 'terminal', outcome: 'cancelled' }))
+function renderSlot(
+ request = vi.fn(async () => ({})),
+ overrides: Partial<Parameters<typeof renderComposerQueueSlot>[0]> = {}
+) {
+ const inputs = {
+ activeQueueSessionKey: 'stored',
+ beginQueuedEdit: vi.fn(),
+ busy: true,
+ drainNextQueued: vi.fn(async () => undefined),
+ exitQueuedEdit: vi.fn(),
+ gateway: { request } as unknown as HermesGateway,
+ queueEdit: null,
+ queueParked: false,
+ queuedPrompts: getQueuedPrompts('stored'),
+ sendQueuedNow: vi.fn(),
+ sessionId: 'runtime-1',
+ steerQueuedNow: vi.fn(),
+ t: en,
+ ...overrides
+ }
render(
<I18nProvider configClient={{ getConfig: async () => ({}), saveConfig: async () => ({ ok: true }) }}>
- {renderComposerQueueSlot({
- activeQueueSessionKey: 'stored',
- beginQueuedEdit: vi.fn(),
- busy: true,
- drainNextQueued: vi.fn(async () => undefined),
- exitQueuedEdit: vi.fn(),
- gateway: { request } as unknown as HermesGateway,
- queueEdit: null,
- queueParked: false,
- queuedPrompts: getQueuedPrompts('stored'),
- sendQueuedNow: vi.fn(),
- sessionId: 'runtime-1',
- steerQueuedNow: vi.fn(),
- t: en
- })}
+ {renderComposerQueueSlot(inputs)}
</I18nProvider>
)
+ return inputs
+}
+
+async function expand() {
+ fireEvent.click(await screen.findByRole('button', { name: /queued/i }))
+}
+
+function rowButtons(text: string) {
+ let row: HTMLElement | null = screen.getByText(text)
+
+ while (row && !row.querySelector(`[aria-label="${en.composer.queueDelete}"]`)) {
+ row = row.parentElement
+ }
+
+ return within(row as HTMLElement)
+}
+
+const labels = (row: ReturnType<typeof within>) =>
+ row
+ .queryAllByRole('button')
+ .map((button: HTMLElement) => button.getAttribute('aria-label'))
+ .filter(Boolean)
+
+it('Delete on a server-queued card cancels its admission at the authority', async () => {
+ reconcilePendingSubmissions('stored', [{ admission_id: 'adm-1', status: 'queued', user: 'later please' }])
+ const request = vi.fn(async () => ({ admission_id: 'adm-1', status: 'terminal', outcome: 'cancelled' }))
+ renderSlot(request)
+
fireEvent.click(await screen.findByRole('button', { name: /queued/i }))
fireEvent.click(screen.getByRole('button', { name: en.composer.queueDelete }))
await vi.waitFor(() => expect(request).toHaveBeenCalledWith('prompt.cancel', { session_id: 'runtime-1', admission_id: 'adm-1' }))
})
+
+it('a server-queued card shows the Steer and Edit its owner serves, and never Next (RT-35)', async () => {
+ reconcilePendingSubmissions('stored', [
+ { admission_id: 'adm-1', status: 'queued', user: 'later please', controls: ['steer', 'replace'] }
+ ])
+ enqueueQueuedPrompt('stored', { text: 'local words', attachments: [] })
+ renderSlot()
+
+ await expand()
+ expect(labels(rowButtons('later please')).sort()).toEqual(
+ [en.composer.queueDelete, en.composer.queueEdit, en.composer.queueSteer].sort()
+ )
+ // The local row keeps its own controls, Next included.
+ expect(labels(rowButtons('local words'))).toContain(en.composer.queueSendNext)
+})
+
+it('a server-queued card from an owner without the queued-row verbs keeps only Delete', async () => {
+ reconcilePendingSubmissions('stored', [{ admission_id: 'adm-1', status: 'queued', user: 'later please' }])
+ renderSlot()
+ await expand()
+
+ expect(labels(rowButtons('later please'))).toEqual([en.composer.queueDelete])
+})
+
+it('Steer on a server-queued card asks the authority to steer that admission', async () => {
+ reconcilePendingSubmissions('stored', [
+ { admission_id: 'adm-1', status: 'queued', user: 'later please', controls: ['steer', 'replace'] }
+ ])
+ const request = vi.fn(async () => ({ admission_id: 'adm-1', status: 'terminal', outcome: 'steered' }))
+ const inputs = renderSlot(request)
+ await expand()
+
+ fireEvent.click(rowButtons('later please').getByRole('button', { name: en.composer.queueSteer }))
+
+ await vi.waitFor(() =>
+ expect(request).toHaveBeenCalledWith('prompt.steer_queued', { session_id: 'runtime-1', admission_id: 'adm-1' })
+ )
+ expect(inputs.steerQueuedNow).not.toHaveBeenCalled()
+})
+
+it('Edit on a server-queued card opens it in the composer', async () => {
+ reconcilePendingSubmissions('stored', [
+ { admission_id: 'adm-1', status: 'queued', user: 'later please', controls: ['steer', 'replace'] }
+ ])
+ const inputs = renderSlot()
+ await expand()
+
+ fireEvent.click(rowButtons('later please').getByRole('button', { name: en.composer.queueEdit }))
+
+ expect(inputs.beginQueuedEdit).toHaveBeenCalledWith(expect.objectContaining({ id: 'adm-1', serverStatus: 'queued' }))
+})
diff --git a/apps/desktop/src/app/chat/composer/queue-slot.tsx b/apps/desktop/src/app/chat/composer/queue-slot.tsx
index 3c4c90b8446..2bc9eab4fad 100644
--- a/apps/desktop/src/app/chat/composer/queue-slot.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-slot.tsx
@@ -9,7 +9,7 @@ import { $activeSessionId, $selectedStoredSessionId } from '@/store/session'
import { $sessionStates, $sessionTiles, storedSessionIdForRuntimeId } from '@/store/session-states'
import type { QueueEditState } from './composer-utils'
-import { cancelQueuedPrompt, discardLostPrompt } from './discard-lost-prompt'
+import { cancelQueuedPrompt, discardLostPrompt, steerQueuedPrompt } from './discard-lost-prompt'
import { QueuePanel } from './queue-panel'
export interface ComposerQueueSlotInputs {
@@ -132,7 +132,21 @@ export function renderComposerQueueSlot({
}
}}
onSendNow={id => void sendQueuedNow(id)}
- onSteerNow={id => void steerQueuedNow(id)}
+ onSteerNow={id => {
+ // A server row is steered by its owner, which consumes the admission so it never also runs;
+ // the pending fanout retires the card.
+ if (queuedPrompts.find(entry => entry.id === id)?.serverStatus) {
+ if (gateway) {
+ steerQueuedPrompt(sessionId, activeQueueSessionKey, id, gateway.request.bind(gateway)).catch(
+ (error: unknown) => notifyError(error, t.composer.queueStuckTitle)
+ )
+ }
+
+ return
+ }
+
+ void steerQueuedNow(id)
+ }}
parked={queueParked}
/>
) : null
diff --git a/apps/desktop/src/i18n/ar_session_commands.ts b/apps/desktop/src/i18n/ar_session_commands.ts
index 5f1a0c63904..b4354407538 100644
--- a/apps/desktop/src/i18n/ar_session_commands.ts
+++ b/apps/desktop/src/i18n/ar_session_commands.ts
@@ -13,5 +13,7 @@ export const arSessionCommands = {
queued: (preview: string) => `في قائمة الانتظار: "${preview}"`,
queueFailed: 'تعذّرت إضافة الرسالة إلى قائمة الانتظار',
countOne: (count: string) => `${count} رسالة في قائمة الانتظار`,
- countOther: (count: string) => `${count} رسائل في قائمة الانتظار`
+ countOther: (count: string) => `${count} رسائل في قائمة الانتظار`,
+ queueEditKeptTitle: 'لم تتغير الرسالة في قائمة الانتظار',
+ queueEditKept: 'بدأت أو رُفضت قبل حفظ تعديلك. نصك المعدّل موجود في مربع الكتابة.'
}
diff --git a/apps/desktop/src/i18n/de_session_commands.ts b/apps/desktop/src/i18n/de_session_commands.ts
index 414ee66eb4d..f37c41446b4 100644
--- a/apps/desktop/src/i18n/de_session_commands.ts
+++ b/apps/desktop/src/i18n/de_session_commands.ts
@@ -14,5 +14,8 @@ export const deSessionCommands = {
queued: (preview: string) => `eingereiht: „${preview}“`,
queueFailed: 'Die Nachricht konnte nicht eingereiht werden',
countOne: (count: string) => `${count} eingereihte Nachricht`,
- countOther: (count: string) => `${count} eingereihte Nachrichten`
+ countOther: (count: string) => `${count} eingereihte Nachrichten`,
+ queueEditKeptTitle: 'Eingereihte Nachricht nicht geändert',
+ queueEditKept:
+ 'Sie wurde gestartet oder abgelehnt, bevor deine Änderung gespeichert war. Dein bearbeiteter Text steht im Eingabefeld.'
}
diff --git a/apps/desktop/src/i18n/en_session_commands.ts b/apps/desktop/src/i18n/en_session_commands.ts
index 345289b1dd9..34d6f495ab1 100644
--- a/apps/desktop/src/i18n/en_session_commands.ts
+++ b/apps/desktop/src/i18n/en_session_commands.ts
@@ -15,5 +15,7 @@ export const enSessionCommands: SessionCommandNotices = {
queued: (preview: string) => `queued: "${preview}"`,
queueFailed: 'could not queue the message',
countOne: (count: string) => `${count} queued message`,
- countOther: (count: string) => `${count} queued messages`
+ countOther: (count: string) => `${count} queued messages`,
+ queueEditKeptTitle: 'Queued message not changed',
+ queueEditKept: 'It started or was refused before your edit was saved. Your edited text is in the composer.'
}
diff --git a/apps/desktop/src/i18n/es_session_commands.ts b/apps/desktop/src/i18n/es_session_commands.ts
index 7b3ce1c5bef..018b2e87c99 100644
--- a/apps/desktop/src/i18n/es_session_commands.ts
+++ b/apps/desktop/src/i18n/es_session_commands.ts
@@ -13,5 +13,7 @@ export const esSessionCommands = {
queued: (preview: string) => `en cola: "${preview}"`,
queueFailed: 'No se pudo poner el mensaje en cola',
countOne: (count: string) => `${count} mensaje en cola`,
- countOther: (count: string) => `${count} mensajes en cola`
+ countOther: (count: string) => `${count} mensajes en cola`,
+ queueEditKeptTitle: 'Mensaje en cola sin cambios',
+ queueEditKept: 'Empezó o fue rechazado antes de guardar tu edición. Tu texto editado está en el editor.'
}
diff --git a/apps/desktop/src/i18n/fr_session_commands.ts b/apps/desktop/src/i18n/fr_session_commands.ts
index 72bbbbcc8e5..dd55069d9de 100644
--- a/apps/desktop/src/i18n/fr_session_commands.ts
+++ b/apps/desktop/src/i18n/fr_session_commands.ts
@@ -13,5 +13,8 @@ export const frSessionCommands = {
queued: (preview: string) => `en file : « ${preview} »`,
queueFailed: 'Impossible de mettre le message en file',
countOne: (count: string) => `${count} message en file`,
- countOther: (count: string) => `${count} messages en file`
+ countOther: (count: string) => `${count} messages en file`,
+ queueEditKeptTitle: 'Message en file non modifié',
+ queueEditKept:
+ "Il a démarré ou a été refusé avant l'enregistrement de ta modification. Ton texte modifié est dans la zone de saisie."
}
diff --git a/apps/desktop/src/i18n/ja_session_commands.ts b/apps/desktop/src/i18n/ja_session_commands.ts
index e83275310ca..78eeb7c3780 100644
--- a/apps/desktop/src/i18n/ja_session_commands.ts
+++ b/apps/desktop/src/i18n/ja_session_commands.ts
@@ -13,5 +13,7 @@ export const jaSessionCommands = {
queued: (preview: string) => `キューに追加: 「${preview}」`,
queueFailed: 'メッセージをキューに追加できませんでした',
countOne: (count: string) => `キュー内のメッセージ ${count} 件`,
- countOther: (count: string) => `キュー内のメッセージ ${count} 件`
+ countOther: (count: string) => `キュー内のメッセージ ${count} 件`,
+ queueEditKeptTitle: 'キュー内のメッセージは変更されていません',
+ queueEditKept: '編集を保存する前に開始されたか、拒否されました。編集したテキストは入力欄にあります。'
}
diff --git a/apps/desktop/src/i18n/ru_session_commands.ts b/apps/desktop/src/i18n/ru_session_commands.ts
index 843cc3048d7..5221934bd42 100644
--- a/apps/desktop/src/i18n/ru_session_commands.ts
+++ b/apps/desktop/src/i18n/ru_session_commands.ts
@@ -13,5 +13,7 @@ export const ruSessionCommands = {
queued: (preview: string) => `в очереди: «${preview}»`,
queueFailed: 'Не удалось поставить сообщение в очередь',
countOne: (count: string) => `сообщений в очереди: ${count}`,
- countOther: (count: string) => `сообщений в очереди: ${count}`
+ countOther: (count: string) => `сообщений в очереди: ${count}`,
+ queueEditKeptTitle: 'Сообщение в очереди не изменено',
+ queueEditKept: 'Оно началось или было отклонено до сохранения правки. Отредактированный текст остался в поле ввода.'
}
diff --git a/apps/desktop/src/i18n/types_notices.ts b/apps/desktop/src/i18n/types_notices.ts
index 6e9302fa943..93275f646fd 100644
--- a/apps/desktop/src/i18n/types_notices.ts
+++ b/apps/desktop/src/i18n/types_notices.ts
@@ -42,4 +42,7 @@ export interface SessionCommandNotices {
queueFailed: string
countOne: (count: string) => string
countOther: (count: string) => string
+ /** A canonical queued row's edit the owner refused, or whose row started mid-edit. */
+ queueEditKeptTitle: string
+ queueEditKept: string
}
diff --git a/apps/desktop/src/i18n/zh-hant_session_commands.ts b/apps/desktop/src/i18n/zh-hant_session_commands.ts
index 17867792154..e1203c8e91a 100644
--- a/apps/desktop/src/i18n/zh-hant_session_commands.ts
+++ b/apps/desktop/src/i18n/zh-hant_session_commands.ts
@@ -13,5 +13,7 @@ export const zhHantSessionCommands = {
queued: (preview: string) => `已排入佇列:「${preview}」`,
queueFailed: '無法將訊息排入佇列',
countOne: (count: string) => `${count} 則排隊訊息`,
- countOther: (count: string) => `${count} 則排隊訊息`
+ countOther: (count: string) => `${count} 則排隊訊息`,
+ queueEditKeptTitle: '排隊訊息未變更',
+ queueEditKept: '在儲存編輯之前它已開始或被拒絕。編輯後的文字仍在輸入框中。'
}
diff --git a/apps/desktop/src/i18n/zh_session_commands.ts b/apps/desktop/src/i18n/zh_session_commands.ts
index 114fd2d5c64..413511a0b40 100644
--- a/apps/desktop/src/i18n/zh_session_commands.ts
+++ b/apps/desktop/src/i18n/zh_session_commands.ts
@@ -13,5 +13,7 @@ export const zhSessionCommands = {
queued: (preview: string) => `已排队:“${preview}”`,
queueFailed: '无法将消息加入队列',
countOne: (count: string) => `${count} 条排队消息`,
- countOther: (count: string) => `${count} 条排队消息`
+ countOther: (count: string) => `${count} 条排队消息`,
+ queueEditKeptTitle: '排队消息未更改',
+ queueEditKept: '在保存编辑之前它已开始或被拒绝。编辑后的文本仍在输入框中。'
}
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index ade99a83e8b..e3240c6f851 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -38,6 +38,9 @@ export interface RemoveQueuedPromptOptions {
export interface QueuedPromptEntry {
id: string
serverStatus?: string
+ /** The queued-row verbs the owner serves for a server row (`steer`, `replace`); none from an
+ * owner that predates them. Projected from the pending snapshot, never set locally. */
+ serverControls?: 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
diff --git a/apps/desktop/src/store/pending-submissions.test.ts b/apps/desktop/src/store/pending-submissions.test.ts
index c1ecc9b9b12..84c6a36bde6 100644
--- a/apps/desktop/src/store/pending-submissions.test.ts
+++ b/apps/desktop/src/store/pending-submissions.test.ts
@@ -33,6 +33,19 @@ it('projects resumed runtime pending receipts under durable identity without mak
expect(getQueuedPrompts('runtime')).toEqual([])
})
+it('carries the queued-row controls the owner lists onto the card, and none when it lists none (RT-35)', () => {
+ reconcilePendingSubmissions('chat', [
+ { admission_id: 'served', status: 'queued', user: 'edit me', controls: ['steer', 'replace'] },
+ { admission_id: 'older', status: 'queued', user: 'older owner' }
+ ])
+
+ expect(getQueuedPrompts('chat').map(({ id, serverControls }) => ({ id, serverControls }))).toEqual([
+ { id: 'served', serverControls: ['steer', 'replace'] },
+ { id: 'older', serverControls: undefined }
+ ])
+ expect(Object.values(readPendingSubmissions('chat')).some(entry => 'controls' in entry)).toBe(false)
+})
+
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: [] })
diff --git a/apps/desktop/src/store/pending-submissions.ts b/apps/desktop/src/store/pending-submissions.ts
index 9c2685f9db9..660985d1cbd 100644
--- a/apps/desktop/src/store/pending-submissions.ts
+++ b/apps/desktop/src/store/pending-submissions.ts
@@ -15,6 +15,8 @@ interface PendingSubmission {
status?: string
/** Where in the session's event order the owner last listed this admission as pending. */
seen?: PendingSnapshotFence
+ /** The snapshot's queued-row controls; carried to the card only, never journaled. */
+ controls?: string[]
}
/** A canonical pending snapshot's place in its session's event order: the replay epoch and the
@@ -193,7 +195,8 @@ function collectReceipts(value: RawReceipts, known: Record<string, PendingSubmis
...known[id],
id,
text: typeof raw.user === 'string' ? raw.user : (known[id]?.text ?? ''),
- status: stale ? known[id].status : raw.status
+ status: stale ? known[id].status : raw.status,
+ ...(Array.isArray(raw.controls) ? { controls: raw.controls.filter((c: unknown) => typeof c === 'string') } : {})
})
}
@@ -221,7 +224,7 @@ function projectQueue(
if (receipt) {
if (receipt.status !== 'started') {
- next.push({ ...entry, id: receipt.id, serverStatus: receipt.status })
+ next.push({ ...entry, id: receipt.id, serverStatus: receipt.status, serverControls: receipt.controls })
}
receipts.delete(receipt.id)
@@ -238,7 +241,8 @@ function projectQueue(
displayText: receipt.displayText,
attachments: [],
queuedAt: Date.now(),
- serverStatus: receipt.status
+ serverStatus: receipt.status,
+ serverControls: receipt.controls
})
}
}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 4dac1767312..8ce17873fc7 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4941,6 +4941,7 @@ export interface CanonicalPendingAdmission {
execution_generation: number | null
input_id: string
text: string
+ controls?: ('steer' | 'replace')[] | null
}
export interface CanonicalPendingPrompt {
kind: 'approval' | 'clarify'
@@ -5124,6 +5125,22 @@ export interface CanonicalApprovalParams {
prompt_id: string
choice: string
}
+export interface CanonicalSteerQueuedParams {
+ profile?: string | null
+ session_id: string
+ admission_id: string
+}
+/** The edited prompt: admitted as a NEW admission (``submission_id``) at the FIFO tail. */
+export interface CanonicalReplaceQueuedParams {
+ profile?: string | null
+ session_id: string
+ admission_id: string
+ submission_id: string
+ text: string
+ attachments?: CanonicalAttachment[] | null
+ display_kind?: 'hidden' | null
+ title_preview?: string | null
+}
export interface CanonicalConfigGetResult {
value?: string | null
display?: string | null
@@ -6723,8 +6740,12 @@ export interface CanonicalRpcMethods {
'prompt.cancel': { params: PromptCancelParams; result: AdmissionStatus }
/** Current receipt of one admission the caller submitted (or controls). */
'prompt.receipt': { params: PromptReceiptParams; result: PromptReceiptResult }
+ /** Cancel a still-queued admission and admit the edited prompt as a new admission at the back of the FIFO, in one write bound to the replaced admission. Refusals: admission_started, admission_conflict (the submission_id replaced another admission), queue_full, unsupported_control, not_found. */
+ 'prompt.replace_queued': { params: CanonicalReplaceQueuedParams; result: AdmissionStatus }
/** Acknowledge a turn lost across an owner restart; the FIFO behind it resumes. Never requeues the lost input. */
'prompt.resolve_unknown': { params: PromptResolveUnknownParams; result: AdmissionStatus }
+ /** Hand a still-queued admission's text to the running turn's agent as a steer. The admission reads 'started' with that turn and never runs on its own; it settles terminal 'steered' when the turn completes, else 'interrupted'. Refusals: admission_started, session_idle, steer_unavailable (no agent to take it: the admission stays queued), unsupported_control, not_found. */
+ 'prompt.steer_queued': { params: CanonicalSteerQueuedParams; result: AdmissionStatus }
'prompt.submit': { params: CanonicalSubmitParams; result: AdmissionStatus }
/** The classic CLI's /diff session: everything changed since the session's earliest retained checkpoint, as data for its terminal renderer. */
'rollback.session_diff': { params: RollbackSessionDiffParams; result: RollbackSessionDiffResult }
@@ -6784,7 +6805,9 @@ export const CANONICAL_RPC_METHODS = [
'profiles.list',
'prompt.cancel',
'prompt.receipt',
+ 'prompt.replace_queued',
'prompt.resolve_unknown',
+ 'prompt.steer_queued',
'prompt.submit',
'rollback.session_diff',
'runtime.describe',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index a9489bc19e3..40946493f2e 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -9118,6 +9118,25 @@
"text": {
"title": "Text",
"type": "string"
+ },
+ "controls": {
+ "anyOf": [
+ {
+ "items": {
+ "enum": [
+ "steer",
+ "replace"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Controls"
}
},
"required": [
@@ -9422,6 +9441,88 @@
"title": "CanonicalProfilesResult",
"type": "object"
},
+ "CanonicalReplaceQueuedParams": {
+ "additionalProperties": false,
+ "description": "The edited prompt: admitted as a NEW admission (``submission_id``) at the FIFO tail.",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "admission_id": {
+ "title": "Admission Id",
+ "type": "string"
+ },
+ "submission_id": {
+ "title": "Submission Id",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ },
+ "attachments": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/CanonicalAttachment"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Attachments"
+ },
+ "display_kind": {
+ "anyOf": [
+ {
+ "const": "hidden",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Display Kind"
+ },
+ "title_preview": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Title Preview"
+ }
+ },
+ "required": [
+ "session_id",
+ "admission_id",
+ "submission_id",
+ "text"
+ ],
+ "title": "CanonicalReplaceQueuedParams",
+ "type": "object"
+ },
"CanonicalReplayEvent": {
"additionalProperties": false,
"properties": {
@@ -10973,6 +11074,37 @@
"title": "CanonicalSnapshotInfo",
"type": "object"
},
+ "CanonicalSteerQueuedParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "admission_id": {
+ "title": "Admission Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "session_id",
+ "admission_id"
+ ],
+ "title": "CanonicalSteerQueuedParams",
+ "type": "object"
+ },
"CanonicalSubmitParams": {
"additionalProperties": false,
"properties": {
@@ -47111,6 +47243,24 @@
}
}
},
+ {
+ "name": "prompt.replace_queued",
+ "summary": "Cancel a still-queued admission and admit the edited prompt as a new admission at the back of the FIFO, in one write bound to the replaced admission. Refusals: admission_started, admission_conflict (the submission_id replaced another admission), queue_full, unsupported_control, not_found.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalReplaceQueuedParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/AdmissionStatus"
+ }
+ }
+ },
{
"name": "prompt.resolve_unknown",
"summary": "Acknowledge a turn lost across an owner restart; the FIFO behind it resumes. Never requeues the lost input.",
@@ -47129,6 +47279,24 @@
}
}
},
+ {
+ "name": "prompt.steer_queued",
+ "summary": "Hand a still-queued admission's text to the running turn's agent as a steer. The admission reads 'started' with that turn and never runs on its own; it settles terminal 'steered' when the turn completes, else 'interrupted'. Refusals: admission_started, session_idle, steer_unavailable (no agent to take it: the admission stays queued), unsupported_control, not_found.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSteerQueuedParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/AdmissionStatus"
+ }
+ }
+ },
{
"name": "prompt.submit",
"summary": "",
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 4a41f0c4b26..0c7a8d9b6c8 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -20,7 +20,7 @@ from gateway.session_contract import (
from gateway.session_events import SessionEvents
from gateway.session_pending_controls import PendingControls
from hermes_state_runtime import (
- RuntimeStoreError, admit_session_input, begin_runtime_epoch,
+ STEERING, RuntimeStoreError, admit_session_input, begin_runtime_epoch,
cancel_session_input, claim_session_input, get_session_admission,
list_session_admissions, recover_session_inputs, resolve_unknown_session_input,
)
@@ -101,6 +101,9 @@ class SessionAuthority:
# session -> (generation, [steer text]) accepted before that generation adopted an agent;
# adopt_agent hands it to that agent (never a later generation's), the drain drops the rest.
self.pending_steers = {}
+ # session -> (generation, {admission_id: delivered}): queued admissions prompt.steer_queued handed
+ # to that running claim (gateway/session_queued_controls.py); its settlement decides each one.
+ self.steer_transfers = {}
# session -> generation of the last Stop delivered to a live agent. A repeated
# Stop can land on the session's reusable cached agent after that turn's finalizer
# cleared it; the next generation's adopt_agent drops it instead of starting interrupted.
@@ -315,9 +318,11 @@ class SessionAuthority:
raise RuntimeStoreError('not_found')
def _receipt(self, row):
+ status, outcome = row['status'], row['outcome']
+ if outcome == STEERING: # handed to the running claim: it reads as that execution until settled
+ status, outcome = 'started', None
return AdmissionReceipt(row['admission_id'], SessionRef(self.profile_id, row['target_session_id']),
- row['seq'], row['status'], row['outcome'],
- row['owner_epoch'] or self.epoch, row['generation'])
+ row['seq'], status, outcome, row['owner_epoch'] or self.epoch, row['generation'])
def _pending_receipt(self, row):
# Only public input text crosses the viewer boundary, never the
@@ -326,7 +331,9 @@ class SessionAuthority:
text = payload.get('text')
if text is None:
text = payload.get('native_text_v1', {}).get('event', {}).get('text', '')
- return PendingAdmission(**vars(self._receipt(row)), input_id=row['request_id'], text=text)
+ from gateway.session_queued_controls import queued_controls
+ return PendingAdmission(**vars(self._receipt(row)), input_id=row['request_id'], text=text,
+ controls=queued_controls(self, row))
def _publish_pending(self, ref):
live = self.sessions[ref.session_id]
@@ -499,7 +506,8 @@ class SessionAuthority:
results[sid] = exc.reason
return results
- async def submit(self, actor: Principal, request: Submission, *, _authorize_write=None, queue_while_restarting=False):
+ async def submit(self, actor: Principal, request: Submission, *, _authorize_write=None, queue_while_restarting=False,
+ _replay_guard=None):
"""``queue_while_restarting``: the caller is an interactive client attached to a restart's
after-turn wait, which commits the input queued for the next owner. Machine callers (a2a,
kanban, hosted rooms) keep the plain ``runtime_draining`` refusal and retry against the next
@@ -511,9 +519,9 @@ class SessionAuthority:
from gateway.session_ingress_media import capture_lease
with capture_lease(): # captured bytes are held from capture until commit or refusal
return await self._submit(actor, request, _authorize_write=_authorize_write,
- queue_only=queue_while_restarting is True)
+ queue_only=queue_while_restarting is True, _replay_guard=_replay_guard)
- async def _submit(self, actor, request, *, _authorize_write=None, queue_only=False):
+ async def _submit(self, actor, request, *, _authorize_write=None, queue_only=False, _replay_guard=None):
self._require_admission_open(queue_only=queue_only)
if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {
'text', 'attachments', 'finite', 'unattended', 'surface', 'voice_context', 'interrupted',
@@ -548,7 +556,7 @@ class SessionAuthority:
try:
return admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,
session_id=request.ref.session_id, request_id=request.request_id,
- payload=payload, intent=request.intent,
+ payload=payload, intent=request.intent, _replay_guard=_replay_guard,
_authorize_write=self._admission_gate(_authorize_write, queue_only=queue_only))
except Exception:
self._release_refused_capture(request, payload)
@@ -635,7 +643,7 @@ class SessionAuthority:
self._publish_pending(ref)
return row
- def _settle_cancelled(self, ref, admission_id):
+ def _settle_cancelled(self, ref, admission_id, outcome='cancelled'):
# The only place a queued row becomes terminal: every observer kind that waits on
# the admission (native delivery, API/webhook/hosted waiters, ACP and viewer streams)
# settles here, or a cancelled row that never reaches _drain blocks them forever.
@@ -648,7 +656,7 @@ class SessionAuthority:
live.event_stream.execution = {'authority_epoch': self.epoch, 'admission_id': admission_id}
try:
live.event_stream.publish(ref.session_id, {
- 'text': '', 'content': '', 'admission_id': admission_id, 'outcome': 'cancelled'})
+ 'text': '', 'content': '', 'admission_id': admission_id, 'outcome': outcome})
finally:
live.event_stream.execution = running
# Published once: a later exact retry re-collects media but never repeats the completion.
@@ -1112,6 +1120,8 @@ class SessionAuthority:
self.pending_stops.pop(ref.session_id, None)
self.pending_steers.pop(ref.session_id, None)
self.adopted.pop(ref.session_id, None)
+ from gateway.session_queued_controls import publish_transfers
+ publish_transfers(self, ref, row['generation'])
if settled is None:
# Uncommitted (unknown or discarded): the user is not told an answer the FIFO lost.
self.pending_deliveries.pop(admission_id, None)
diff --git a/gateway/session_contract.py b/gateway/session_contract.py
index d896cab15d3..43f648e8204 100644
--- a/gateway/session_contract.py
+++ b/gateway/session_contract.py
@@ -1,6 +1,6 @@
"""Public session authority contract; live execution state never crosses this boundary."""
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import Literal, Mapping, Protocol
JsonObject = Mapping[str, object]
@@ -64,6 +64,8 @@ class AdmissionReceipt:
class PendingAdmission(AdmissionReceipt):
input_id: str
text: str
+ # The queued-row verbs this owner serves for the row (``steer`` / ``replace``); empty otherwise.
+ controls: list[str] = field(default_factory=list)
@dataclass(frozen=True)
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 81b513ee05b..1e01a6ee901 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -89,6 +89,7 @@ _END_REASON = re.compile(r'[a-z][a-z_]{0,31}')
# Verbs whose param sets are closed and never carried a ``profile`` key.
_PROFILE_IMPLICIT = frozenset({'session.create', 'session.list', 'session.info', 'session.resume', 'session.detach',
'prompt.submit', 'prompt.receipt', 'prompt.cancel', 'prompt.resolve_unknown',
+ 'prompt.steer_queued', 'prompt.replace_queued',
'session.interrupt', 'session.events.since', 'session.mutate', 'session.stats',
'approval.respond', 'clarify.respond'})
@@ -185,6 +186,8 @@ class AuthorityConnection:
'approval.respond': self.respond, 'clarify.respond': self.respond_clarify}
from gateway.session_busy_controls import handlers as busy_handlers
handlers.update(busy_handlers(self))
+ from gateway.session_queued_controls import handlers as queued_handlers
+ handlers.update(queued_handlers(self))
from gateway.session_config import handlers as config_handlers
handlers.update(config_handlers(self))
from gateway.session_tui_config import handlers as tui_config_handlers
@@ -661,6 +664,13 @@ class AuthorityConnection:
return self.authority.sessions[ref.session_id].event_stream.since(epoch, sequence)
async def submit(self, ref, params):
+ # The interactive WS is the one surface a restart's after-turn wait admits (#139041).
+ receipt = await self.authority.submit(self.actor, self.submission(ref, params),
+ queue_while_restarting=self._operator is True)
+ return asdict(receipt)
+
+ def submission(self, ref, params):
+ """The admission a ``prompt.submit``-shaped request asks for (``prompt.replace_queued`` too)."""
if ref.session_id not in self.subscriptions:
raise RuntimeStoreError('permission_denied')
forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued', 'attachments', 'finite', 'unattended',
@@ -679,10 +689,7 @@ class AuthorityConnection:
**submit_display_fields(params), **submit_cli_turn_fields(params)}
if 'attachments' in params:
payload['attachments'] = params['attachments']
- # The interactive WS is the one surface a restart's after-turn wait admits (#139041).
- receipt = await self.authority.submit(self.actor, Submission(request_id, ref, payload, 'queue'),
- queue_while_restarting=self._operator is True)
- return asdict(receipt)
+ return Submission(request_id, ref, payload, 'queue')
async def mutate(self, ref, params):
from gateway.session_mutations import mutate_session
diff --git a/gateway/session_queued_controls.py b/gateway/session_queued_controls.py
new file mode 100644
index 00000000000..ed3becd6c82
--- /dev/null
+++ b/gateway/session_queued_controls.py
@@ -0,0 +1,205 @@
+"""Steer and Edit of a still-queued admission: ``prompt.steer_queued`` / ``prompt.replace_queued``.
+
+Both consume the queued row inside one owner write transaction, so it can never also run as its own
+queued turn, and a retry replays the recorded outcome. There is no reorder verb: one FIFO per session.
+
+A steer is a TRANSFER to the running claim, not an outcome: the row goes queued -> terminal
+``steering`` bound to the claim's generation, and settles with that claim (``steered`` once the claim
+completes with the text delivered, ``interrupted`` otherwise; queued again in its own FIFO place when
+the text never reached the claim's agent). The fence is ``authority.steer_transfers``, changed only
+under the session's ``event_stream.lock`` (the lock the drain clears ``executing`` under): no storage
+wait ever happens under that lock, which loop-side receipts, attaches and publication take.
+"""
+import asyncio
+from dataclasses import asdict
+from functools import partial
+
+from hermes_state_runtime import (
+ STEERING, RuntimeStoreError, check_replaced_input, find_session_admission, get_session_admission,
+ replacement_binding, retire_replaced_input, revert_steer_input, steer_session_input,
+)
+
+# A steer carries plain text and its presentation only. Attachments, finite runs, classic-CLI turns,
+# native envelopes and automation rows are whole turns: neither verb may drop what they carry.
+_TEXT_ONLY = frozenset({'text', 'surface_v1', 'display_v1', 'local_operator_v1'})
+# Sessions launched from an interactive local surface (classic CLI, TUI, Desktop, ACP editor): their
+# plain-text rows are prompt.submit input, whose observers settle a ``steered``/``cancelled`` row.
+# cron, kanban, a2a and hosted-room (bot_room) producers read a saved result for every outcome they
+# do not name, so a transfer or replacement would strand them: never offered, refused by name.
+_INTERACTIVE_SOURCES = frozenset({'cli', 'tui', 'gui', 'acp'})
+
+
+def handlers(connection):
+ return {'prompt.steer_queued': partial(steer_queued, connection),
+ 'prompt.replace_queued': partial(replace_queued, connection)}
+
+
+def _interactive(authority, session_id):
+ """The session's frozen launch source (a local session's row records it) names a local surface.
+ Callers hold the stream lock: a plain read (``get_session`` flushes token counts, a write)."""
+ sources = authority.__dict__.setdefault('_launch_sources', {})
+ if session_id not in sources:
+ with authority.db._read_ctx() as conn:
+ found = conn.execute('SELECT source FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if found is None:
+ return False
+ sources[session_id] = found[0]
+ return sources[session_id] in _INTERACTIVE_SOURCES
+
+
+def queued_controls(authority, row):
+ """The queued-row verbs this owner serves for ``row``: a client shows only these (an older owner
+ lists none, so its clients show none)."""
+ payload = row.get('payload') or {}
+ text = payload.get('text')
+ if (row.get('status') != 'queued' or set(payload) - _TEXT_ONLY or not isinstance(text, str) or not text.strip()
+ or (payload.get('display_v1') or {}).get('kind') == 'hidden'
+ or not _interactive(authority, row['target_session_id'])):
+ return []
+ return ['steer', 'replace']
+
+
+async def _queued(connection, ref, admission_id):
+ receipt = await connection.authority.receipt(connection.actor, ref, admission_id)
+ return receipt, get_session_admission(connection.authority.db, admission_id=admission_id)
+
+
+def steer_transfers(authority, session_id, generation):
+ """``{admission_id: delivered}`` handed to this claim; the caller holds the stream lock. Read by
+ the claim's settlement after its execution returned, when no transfer can still be delivered."""
+ entry = authority.steer_transfers.get(session_id)
+ return dict(entry[1]) if entry is not None and entry[0] == generation else None
+
+
+def _register(authority, session_id, generation, admission_id):
+ entry = authority.steer_transfers.get(session_id)
+ if entry is None or entry[0] != generation:
+ entry = authority.steer_transfers[session_id] = (generation, {})
+ entry[1].setdefault(admission_id, False) # a concurrent duplicate never resets a delivery
+
+
+def _unregister(authority, session_id, generation, admission_id):
+ entry = authority.steer_transfers.get(session_id)
+ if entry is not None and entry[0] == generation and entry[1].get(admission_id) is False:
+ del entry[1][admission_id]
+
+
+def _receiving_agent(authority, session_id, generation):
+ """The agent the running claim adopted, while that claim still executes. None before adoption (a
+ latched text would be dropped if construction then failed) and for a turn with no steer seam."""
+ adopted_generation, agent = authority.adopted.get(session_id, (None, None))
+ if (adopted_generation != generation or authority.executing.get(session_id) != generation
+ or not callable(getattr(agent, 'steer', None))):
+ return None
+ return agent
+
+
+def _deliver(authority, session_id, generation, agent, admission_id, text):
+ """Hand the committed text to the claim's agent; the caller holds the stream lock. False once the
+ claim stopped executing (its settlement then decides the row) or its agent refused the text."""
+ entry = authority.steer_transfers.get(session_id)
+ if (entry is None or entry[0] != generation or admission_id not in entry[1]
+ or _receiving_agent(authority, session_id, generation) is not agent):
+ return False
+ if not entry[1][admission_id]:
+ entry[1][admission_id] = bool(agent.steer(text))
+ return entry[1][admission_id]
+
+
+async def steer_queued(connection, ref, params):
+ authority, admission_id = connection.authority, params['admission_id']
+ authority.authorize(connection.actor, ref, 'session:control')
+ receipt, row = await _queued(connection, ref, admission_id)
+ if row['status'] == 'terminal' and row['outcome'] in (STEERING, 'steered'):
+ return asdict(receipt) # an exact retry replays the committed transfer
+ if receipt.status != 'queued':
+ raise RuntimeStoreError('admission_started')
+ if 'steer' not in queued_controls(authority, row):
+ raise RuntimeStoreError('unsupported_control')
+ handle = authority._handle(ref)
+ if handle.execution_state != 'running':
+ raise RuntimeStoreError('session_idle')
+ generation, text, live = handle.execution_generation, row['payload']['text'], authority.sessions[ref.session_id]
+ session_id = ref.session_id
+ with live.event_stream.lock:
+ agent = _receiving_agent(authority, session_id, generation)
+ if agent is None:
+ # Refused before the row is touched: it stays queued and runs in FIFO order.
+ raise RuntimeStoreError('steer_unavailable', field='admission_id',
+ detail='the running turn has no agent to take a steer yet')
+ _register(authority, session_id, generation, admission_id)
+ from gateway.session_runtime_workers import tracked_write
+ try:
+ # The storage wait runs with no lock held; the registration above is the claim's fence.
+ committed, fresh = await tracked_write(authority, partial(
+ steer_session_input, authority.db, epoch=authority.epoch, admission_id=admission_id, generation=generation))
+ except BaseException:
+ with live.event_stream.lock:
+ _unregister(authority, session_id, generation, admission_id)
+ raise
+ if fresh:
+ with live.event_stream.lock:
+ delivered = _deliver(authority, session_id, generation, agent, admission_id, text)
+ if not delivered:
+ # The claim ended first: the text reached nobody, so the admission is queued again.
+ await tracked_write(authority, partial(revert_steer_input, authority.db, epoch=authority.epoch,
+ admission_id=admission_id, generation=generation))
+ with live.event_stream.lock:
+ _unregister(authority, session_id, generation, admission_id)
+ authority._publish_pending(ref)
+ authority._schedule(ref)
+ raise RuntimeStoreError('steer_unavailable', field='admission_id',
+ detail='the running turn ended before the steer reached it')
+ authority._publish_pending(ref) # the card leaves the queue: its text is in the running turn
+ return asdict(authority._receipt(committed))
+
+
+def publish_transfers(authority, ref, generation):
+ """After the claim's settlement: each admission it carried publishes the outcome it settled to
+ (``steered``, or ``cancelled`` for an interrupted transfer, as a turn's completion reports it)."""
+ live = authority.sessions.get(ref.session_id)
+ entry = authority.steer_transfers.get(ref.session_id)
+ if live is None or entry is None or entry[0] != generation:
+ return
+ with live.event_stream.lock:
+ authority.steer_transfers.pop(ref.session_id, None)
+ for admission_id in entry[1]:
+ row = get_session_admission(authority.db, admission_id=admission_id)
+ if row is not None and row['status'] == 'terminal' and row['outcome'] in ('steered', 'interrupted'):
+ authority._settle_cancelled(ref, admission_id,
+ outcome='steered' if row['outcome'] == 'steered' else 'cancelled')
+ authority._publish_pending(ref) # an undelivered transfer is queued again
+
+
+async def replace_queued(connection, ref, params):
+ """Cancel the queued admission and admit the edit at the FIFO tail under a new identity, in one
+ write. The replacement is bound to the admission it retired: an exact retry (same old admission,
+ same new ``submission_id``) answers the same new admission; any other old admission under that
+ ``submission_id`` is ``admission_conflict``, decided inside the admission's own transaction."""
+ authority, actor, old_id = connection.authority, connection.actor, params['admission_id']
+ request = connection.submission(ref, {key: value for key, value in params.items() if key != 'admission_id'})
+ receipt, row = await _queued(connection, ref, old_id)
+ replacement = await asyncio.to_thread(find_session_admission, authority.db, principal_id=actor.subject,
+ session_id=ref.session_id, request_id=request.request_id)
+ if replacement is None:
+ if receipt.status != 'queued':
+ raise RuntimeStoreError('admission_started')
+ if 'replace' not in queued_controls(authority, row):
+ raise RuntimeStoreError('unsupported_control')
+ authority.cancel_obligations.add(old_id) # owed from before the write, like prompt.cancel
+ elif (receipt.status, receipt.outcome) != ('terminal', 'cancelled'):
+ raise RuntimeStoreError('admission_conflict') # that request id names other work
+ binding = replacement_binding(actor.subject, ref.session_id, request.request_id)
+ try:
+ admitted = await authority.submit(actor, request, queue_while_restarting=connection._operator is True,
+ _authorize_write=partial(retire_replaced_input, admission_id=old_id, binding=binding),
+ _replay_guard=partial(check_replaced_input, admission_id=old_id, binding=binding))
+ finally:
+ old = get_session_admission(authority.db, admission_id=old_id)
+ if old_id in authority.cancel_obligations and (old['status'], old['outcome']) == ('terminal', 'cancelled'):
+ authority._settle_cancelled(ref, old_id)
+ elif old['status'] == 'queued':
+ authority.cancel_obligations.discard(old_id) # refused: nothing committed
+ from gateway.session_ingress_media import release_admission_media
+ await asyncio.to_thread(release_admission_media, authority.db, old_id)
+ return asdict(admitted)
diff --git a/gateway/session_results.py b/gateway/session_results.py
index e10481cbefa..9bcf86dcb40 100644
--- a/gateway/session_results.py
+++ b/gateway/session_results.py
@@ -63,12 +63,13 @@ def prepare_result(row, response, outcome, result=None):
return outcome, _redacted(compact_result(result, user_message=row['payload'].get('text')))
-def finish_result(db, *, epoch, row, response, outcome, result=None, prepared=None):
+def finish_result(db, *, epoch, row, response, outcome, result=None, prepared=None, transfers=None):
"""Delivery failure cannot rewrite an already committed execution outcome.
`result` is the exact structured result captured in-process; the managed
worker path commits its own before this runs and is read back here.
`prepared` is ``prepare_result``'s output computed before the caller took a lock.
+ `transfers` are the queued steers handed to this claim; they settle in the same write.
"""
with db._read_ctx() as conn:
_epoch(conn, epoch)
@@ -84,7 +85,7 @@ def finish_result(db, *, epoch, row, response, outcome, result=None, prepared=No
return dict(current), result['result'].get('final_response') or ''
outcome, stored = prepared or prepare_result(row, response, outcome, result)
settled = settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],
- generation=row['generation'], outcome=outcome, result=stored)
+ generation=row['generation'], outcome=outcome, result=stored, _transfers=transfers)
return settled, response
diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.py
index c78ae3422b5..d5ae8120470 100644
--- a/gateway/session_settlement_recovery.py
+++ b/gateway/session_settlement_recovery.py
@@ -3,12 +3,14 @@ import asyncio
import logging
import sqlite3
-from hermes_state_runtime import RuntimeStoreError, _admission, _epoch
+from hermes_state_runtime import RuntimeStoreError, _admission, _epoch, settle_steer_transfers
logger = logging.getLogger(__name__)
def _mark_unknown(authority, row):
+ transfers = _transfers(authority, authority.sessions.get(row['target_session_id']), row)
+
def write(conn):
_epoch(conn, authority.epoch)
current = _admission(conn, row['admission_id'])
@@ -19,11 +21,23 @@ def _mark_unknown(authority, row):
if current['status'] != 'started':
raise RuntimeStoreError('stale_generation')
conn.execute("UPDATE session_admissions SET status='unknown' WHERE admission_id=?", (row['admission_id'],))
+ # A steer it carried is never replayed: interrupted if delivered, else queued again.
+ settle_steer_transfers(conn, epoch=authority.epoch, generation=row['generation'],
+ transfers=transfers, outcome='unknown')
conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
return 'unknown'
return authority.db._execute_write(write)
+def _transfers(authority, live, row):
+ """The steers handed to this claim (``prompt.steer_queued``), read once its execution returned."""
+ if live is None:
+ return None
+ from gateway.session_queued_controls import steer_transfers
+ with live.event_stream.lock:
+ return steer_transfers(authority, row['target_session_id'], row['generation'])
+
+
async def recover_failed_settlement(authority, row):
# A full disk or held SQLite writer may also block the recovery stamp. Retain this owner
# and its captured result until the storage fence can commit; never manufacture a reply.
@@ -115,10 +129,11 @@ def commit_and_publish(authority, live, ref, row, response, outcome, captured, s
# already have dropped it from ``authority.sessions``.
with live.event_stream.lock:
live.settling[admission_id] = row
+ transfers = _transfers(authority, live, row)
try:
settlement['settled'], settlement['response'] = finish_result(
authority.db, epoch=authority.epoch, row=row, response=response, outcome=outcome,
- result=captured, prepared=prepared)
+ result=captured, prepared=prepared, transfers=transfers)
with live.event_stream.lock:
live.settling.pop(admission_id, None)
_publish_completion(authority, live, ref, row, settlement['settled'], settlement['response'], captured)
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 1d2a4de330d..1a54a9e5207 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -116,12 +116,14 @@ ADMISSION_QUEUE_MAX = 32
def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
request_id: str, payload: dict, intent: str = 'queue',
- _authorize_write=None) -> dict:
+ _authorize_write=None, _replay_guard=None) -> dict:
"""Admit input; the trusted private guard raises to refuse a NEW write.
The guard receives the owning transaction connection, must not commit it or
perform external effects, and may run again on SQLite retry. Exact existing
and terminal replays bypass it: they cannot create or change accepted work.
+ ``_replay_guard(conn)`` runs on the exact live replay instead, inside the same
+ transaction (a replacement's binding to the admission it retired).
"""
for value in (principal_id, session_id, request_id):
_text(value)
@@ -142,6 +144,8 @@ def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
if old is not None:
if old['payload_digest'] != digest:
raise RuntimeStoreError('admission_conflict')
+ if _replay_guard is not None:
+ _replay_guard(conn)
return _row(old)
queued = conn.execute('''SELECT COUNT(*) FROM session_admissions WHERE target_session_id=?
AND status='queued' ''', (session_id,)).fetchone()[0]
@@ -221,7 +225,7 @@ def claim_session_input(db, *, epoch: int, session_id: str, _guard=None, head=_A
def settle_session_input(db, *, epoch: int, admission_id: str, generation: int, outcome: str,
- result: dict | None = None) -> dict:
+ result: dict | None = None, _transfers=None) -> dict:
if outcome not in ('completed', 'interrupted', 'rejected', 'failed'):
raise RuntimeStoreError('invalid_params')
from hermes_state_terminal import compact_result, encode_result
@@ -241,6 +245,7 @@ def settle_session_input(db, *, epoch: int, admission_id: str, generation: int,
'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
(RESULT_PREFIX + admission_id, encoded))
conn.execute("UPDATE session_admissions SET status='terminal',outcome=? WHERE admission_id=?", (outcome, admission_id))
+ settle_steer_transfers(conn, epoch=epoch, generation=generation, transfers=_transfers, outcome=outcome)
conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
return _row(_admission(conn, admission_id))
return db._execute_write(write)
@@ -260,6 +265,87 @@ def cancel_session_input(db, *, epoch: int, admission_id: str) -> dict:
return db._execute_write(write)
+# A queued admission handed to its FIFO's running claim: terminal (never claimable, outside the queue
+# cap) but not yet an outcome. It is bound to that claim's ``(owner_epoch, generation)`` and settles
+# with it: ``steered`` once the claim completes with the text delivered, ``interrupted`` otherwise, or
+# back to ``queued`` (its own FIFO place) when the text never reached the claim's agent.
+STEERING = 'steering'
+
+
+def steer_session_input(db, *, epoch: int, admission_id: str, generation: int) -> tuple[dict, bool]:
+ """Hand a still-queued admission to its FIFO's running claim: queued -> terminal ``steering``
+ bound to ``generation`` in one write, only while ``generation`` is the started claim this owner
+ holds, so the drain can never also claim it. ``(row, True)`` when this call committed the
+ transfer, ``(row, False)`` for an exact retry of one already committed (never delivered twice)."""
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ if row['status'] == 'terminal' and row['outcome'] in (STEERING, 'steered'):
+ return _row(row), False
+ if row['status'] != 'queued':
+ raise RuntimeStoreError('admission_started')
+ if type(generation) is not int or conn.execute(
+ "SELECT 1 FROM session_admissions WHERE target_session_id=? AND status='started' "
+ "AND owner_epoch=? AND generation=?", (row['target_session_id'], epoch, generation)).fetchone() is None:
+ raise RuntimeStoreError('session_idle')
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome=?,owner_epoch=?,generation=? "
+ "WHERE admission_id=?", (STEERING, epoch, generation, admission_id))
+ return _row(_admission(conn, admission_id)), True
+ return db._execute_write(write)
+
+
+def settle_steer_transfers(conn, *, epoch: int, generation: int, transfers, outcome: str) -> None:
+ """In the receiving claim's terminal write: each admission bound to it settles ``steered`` only if
+ its text reached the claim's agent (``transfers[id]``) and the claim completed; a delivered text
+ under any other ending is ``interrupted`` (never replayed); an undelivered one is queued again."""
+ for admission_id, delivered in (transfers or {}).items():
+ bound = ("WHERE admission_id=? AND status='terminal' AND outcome=? AND owner_epoch=? AND generation=?",
+ (admission_id, STEERING, epoch, generation))
+ if delivered:
+ final = 'steered' if outcome == 'completed' else 'interrupted'
+ conn.execute('UPDATE session_admissions SET outcome=? ' + bound[0], (final, *bound[1]))
+ else:
+ conn.execute("UPDATE session_admissions SET status='queued',outcome=NULL,generation=NULL " + bound[0], bound[1])
+
+
+def revert_steer_input(db, *, epoch: int, admission_id: str, generation: int) -> bool:
+ """A transfer whose text never reached the claim's agent: the admission is queued again, in its
+ original FIFO place (its ``seq``). False when the claim's settlement already decided it."""
+ def write(conn):
+ _epoch(conn, epoch)
+ changed = conn.execute("UPDATE session_admissions SET status='queued',outcome=NULL,generation=NULL "
+ "WHERE admission_id=? AND status='terminal' AND outcome=? AND owner_epoch=? "
+ "AND generation=?", (admission_id, STEERING, epoch, generation)).rowcount
+ return changed == 1
+ return db._execute_write(write)
+
+
+REPLACEMENT_PREFIX = 'gateway.queued_replacement.v1.'
+
+
+def replacement_binding(principal_id: str, session_id: str, request_id: str) -> str:
+ """The durable key binding a replacement's identity to the admission it retired."""
+ return REPLACEMENT_PREFIX + admission_fingerprint(canonical_target=session_id,
+ payload={'principal': principal_id, 'request': request_id})
+
+
+def retire_replaced_input(conn, admission_id: str, binding: str) -> None:
+ """Inside the replacement's own admission write: the replaced row, still queued, is cancelled
+ in the same transaction that admits its successor at the FIFO tail, which is bound to it."""
+ row = _admission(conn, admission_id)
+ if row['status'] != 'queued':
+ raise RuntimeStoreError('admission_started')
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='cancelled' WHERE admission_id=?", (admission_id,))
+ conn.execute('INSERT OR REPLACE INTO state_meta(key,value) VALUES(?,?)', (binding, json.dumps(admission_id)))
+
+
+def check_replaced_input(conn, admission_id: str, binding: str) -> None:
+ """The exact replay of a replacement answers only the request that retired ``admission_id``."""
+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (binding,)).fetchone()
+ if saved is None or json.loads(saved[0]) != admission_id:
+ raise RuntimeStoreError('admission_conflict')
+
+
def rehome_queued_inputs(db, *, epoch: int, old_session_id: str, new_session_id: str,
principal_prefix: str) -> list[str]:
"""Re-target the old owner's still-queued ``principal_prefix*`` admissions onto
@@ -296,6 +382,9 @@ def recover_session_inputs(db, *, epoch: int) -> int:
def write(conn):
_epoch(conn, epoch)
conn.execute("UPDATE worker_executions SET status='unknown' WHERE status IN ('registered','running') AND owner_epoch!=?", (epoch,))
+ # A steer handed to a lost claim may or may not have reached its agent: never replayed.
+ conn.execute("UPDATE session_admissions SET outcome='interrupted' WHERE status='terminal' AND outcome=? "
+ "AND owner_epoch!=?", (STEERING, epoch))
return conn.execute("UPDATE session_admissions SET status='unknown' WHERE status='started' AND owner_epoch!=?", (epoch,)).rowcount
return db._execute_write(write)
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 06f05d75bde..42803510f9c 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -2437,6 +2437,8 @@
"promptNotices.mcpReloadUnavailable",
"promptNotices.sessionCommands.countOne",
"promptNotices.sessionCommands.countOther",
+ "promptNotices.sessionCommands.queueEditKept",
+ "promptNotices.sessionCommands.queueEditKeptTitle",
"promptNotices.sessionCommands.queueFailed",
"promptNotices.sessionCommands.queued",
"promptNotices.sessionCommands.retryNothing",
diff --git a/tests/gateway/test_prompt_queued_controls.py b/tests/gateway/test_prompt_queued_controls.py
new file mode 100644
index 00000000000..836acd5d31c
--- /dev/null
+++ b/tests/gateway/test_prompt_queued_controls.py
@@ -0,0 +1,251 @@
+"""prompt.steer_queued / prompt.replace_queued: Desktop's Steer and Edit on a canonical queued row
+(RT-35). Both verbs consume the still-queued admission in the owner's own write transaction, so it
+can never both run as a queued turn and be steered or replaced, and a retry replays the outcome."""
+import asyncio
+from dataclasses import asdict
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_authority import LiveSession, SessionAuthority
+from hermes_state_runtime import (
+ begin_runtime_epoch, claim_session_input, find_session_admission, list_session_admissions,
+ recover_session_inputs,
+)
+from tests.gateway.test_session_authority_cancel_settlement import REF, _authority, _submit
+
+
+class Agent:
+ def __init__(self):
+ self.steers = []
+
+ def steer(self, text):
+ self.steers.append(text)
+ return True
+
+ def clear_interrupt(self, *args, **kwargs):
+ pass
+
+
+class Turn:
+ """Every turn the drain claims adopts one agent and runs until ``release`` (``fail``: that turn's
+ text raises after adoption, so its execution fails)."""
+
+ def __init__(self, monkeypatch, fail=None):
+ from gateway import session_finite
+ self.agent, self.claimed, self.release, self.ran = Agent(), asyncio.Event(), asyncio.Event(), []
+
+ async def execute(authority, ref, row):
+ self.ran.append(row['payload']['text'])
+ authority.adopt_agent(ref.session_id, row['generation'], self.agent)
+ self.claimed.set()
+ await asyncio.wait_for(self.release.wait(), 5)
+ if row['payload']['text'] == fail:
+ raise RuntimeError('the receiving turn failed')
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+
+
+def interactive(db, sid='s', source='gui'):
+ """The session was launched from an interactive local surface (Desktop by default): a local
+ session's row records its frozen launch policy's source."""
+ db._execute_write(lambda conn: conn.execute('UPDATE sessions SET source=? WHERE id=?', (source, sid)))
+
+
+def _connection(authority):
+ from gateway.session_controls import AuthorityConnection
+ conn = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ conn.subscriptions['s'] = 'attached' # prompt.replace_queued admits like prompt.submit
+ return conn
+
+
+async def _call(conn, method, **params):
+ return await conn.dispatch({'id': 1, 'method': method, 'params': {'session_id': 's', **params}})
+
+
+def _ledger(db):
+ return [(row['request_id'], row['status'], row['outcome'])
+ for row in list_session_admissions(db, session_id='s', pending_only=False)]
+
+
+def _completions(frames):
+ return [(f['params']['payload'].get('admission_id'), f['params']['payload'].get('outcome'))
+ for f in frames if f['params']['type'] == 'message.complete']
+
+
+async def test_steer_queued_delivers_the_queued_text_into_the_running_turn_exactly_once(tmp_path, monkeypatch):
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ turn, frames = Turn(monkeypatch), []
+ authority.sessions['s'].event_stream.observers.add(frames.append)
+ with db:
+ await _submit(authority, 'running')
+ await asyncio.wait_for(turn.claimed.wait(), 5)
+ queued = await _submit(authority, 'follow-up')
+ conn = _connection(authority)
+
+ reply = await _call(conn, 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert 'error' not in reply, reply
+ # Transferred into the running turn: it reads as that execution until the turn settles.
+ assert (reply['result']['status'], reply['result']['outcome']) == ('started', None), reply
+ assert turn.agent.steers == ['follow-up']
+ assert (queued.admission_id, 'steered') not in _completions(frames)
+
+ # A retry of the same request replays the recorded transfer and steers nothing twice.
+ again = await _call(conn, 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert again.get('result') == reply['result'], again
+ assert turn.agent.steers == ['follow-up']
+
+ turn.release.set()
+ await asyncio.wait_for(authority.sessions['s'].task, 5)
+ settled = await _call(conn, 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert (settled['result']['status'], settled['result']['outcome']) == ('terminal', 'steered'), settled
+ assert (queued.admission_id, 'steered') in _completions(frames)
+ assert turn.ran == ['running'], 'the steered admission also ran as its own queued turn'
+ assert _ledger(db) == [('running', 'terminal', 'completed'), ('follow-up', 'terminal', 'steered')]
+
+
+async def test_steer_queued_refuses_by_name_and_leaves_the_admission_queued(tmp_path, monkeypatch):
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ with db:
+ idle = await _submit(authority, 'waiting')
+ conn = _connection(authority)
+ reply = await _call(conn, 'prompt.steer_queued', admission_id=idle.admission_id)
+ assert reply['error']['data']['reason'] == 'session_idle', reply
+
+ missing = await _call(conn, 'prompt.steer_queued', admission_id='no-such-admission')
+ assert missing['error']['data']['reason'] == 'not_found', missing
+
+ # The drain claimed it first: it runs as its own turn and is never also steered.
+ claim_session_input(db, epoch=authority.epoch, session_id='s')
+ started = await _call(conn, 'prompt.steer_queued', admission_id=idle.admission_id)
+ assert started['error']['data']['reason'] == 'admission_started', started
+ assert _ledger(db) == [('waiting', 'started', None)]
+
+
+def test_the_steer_transaction_fences_on_the_queued_row_and_the_running_generation(tmp_path, monkeypatch):
+ """Atomic in the store: queued -> steered only while the named generation is the running one."""
+ import hermes_state_runtime as store
+ from hermes_state_runtime import RuntimeStoreError, admit_session_input
+ assert hasattr(store, 'steer_session_input'), 'no store transaction steers a queued admission'
+ steer_session_input = store.steer_session_input
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ with db:
+ for request_id in ('running', 'follow-up'):
+ admit_session_input(db, epoch=authority.epoch, principal_id='human', session_id='s',
+ request_id=request_id, payload={'text': request_id})
+ running = claim_session_input(db, epoch=authority.epoch, session_id='s')
+ follow = find_session_admission(db, principal_id='human', session_id='s', request_id='follow-up')
+ with pytest.raises(RuntimeStoreError) as stale:
+ steer_session_input(db, epoch=authority.epoch, admission_id=follow['admission_id'],
+ generation=running['generation'] + 1)
+ assert stale.value.reason == 'session_idle'
+ with pytest.raises(RuntimeStoreError) as own:
+ steer_session_input(db, epoch=authority.epoch, admission_id=running['admission_id'],
+ generation=running['generation'])
+ assert own.value.reason == 'admission_started'
+ row, fresh = steer_session_input(db, epoch=authority.epoch, admission_id=follow['admission_id'],
+ generation=running['generation'])
+ # Bound to the receiving claim until that execution settles (never claimable, never steered yet).
+ assert (row['status'], row['outcome'], row['generation'], fresh) == (
+ 'terminal', 'steering', running['generation'], True)
+ replay, fresh = steer_session_input(db, epoch=authority.epoch, admission_id=follow['admission_id'],
+ generation=running['generation'])
+ assert (replay['outcome'], fresh) == ('steering', False)
+
+
+async def test_replace_queued_retires_the_old_admission_and_admits_the_edit_at_the_back(tmp_path, monkeypatch):
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ frames = []
+ authority.sessions['s'].event_stream.observers.add(frames.append)
+ with db:
+ first = await _submit(authority, 'first')
+ await _submit(authority, 'second')
+ conn = _connection(authority)
+ edit = {'admission_id': first.admission_id, 'submission_id': 'first-edited', 'text': 'first, edited'}
+
+ reply = await _call(conn, 'prompt.replace_queued', **edit)
+ assert 'error' not in reply, reply
+ new_id = reply['result']['admission_id']
+ assert new_id != first.admission_id and reply['result']['status'] == 'queued'
+ assert (first.admission_id, 'cancelled') in _completions(frames)
+ queued = [r for r in list_session_admissions(db, session_id='s') if r['status'] == 'queued']
+ assert [(r['request_id'], r['payload']['text']) for r in queued] == [
+ ('second', 'second'), ('first-edited', 'first, edited')], 'the edit must join the back of the FIFO'
+
+ # Exact retry: the same new admission, nothing admitted twice; the old id stays cancelled.
+ again = await _call(conn, 'prompt.replace_queued', **edit)
+ assert again.get('result', {}).get('admission_id') == new_id, again
+ old = await _call(conn, 'prompt.cancel', admission_id=first.admission_id)
+ assert (old['result']['status'], old['result']['outcome']) == ('terminal', 'cancelled')
+ assert _ledger(db) == [('first', 'terminal', 'cancelled'), ('second', 'queued', None),
+ ('first-edited', 'queued', None)]
+
+
+async def test_replace_queued_refuses_a_started_admission_and_admits_nothing(tmp_path, monkeypatch):
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ with db:
+ first = await _submit(authority, 'first')
+ claim_session_input(db, epoch=authority.epoch, session_id='s')
+ conn = _connection(authority)
+ reply = await _call(conn, 'prompt.replace_queued', admission_id=first.admission_id,
+ submission_id='too-late', text='edited')
+ assert reply['error']['data']['reason'] == 'admission_started', reply
+ missing = await _call(conn, 'prompt.replace_queued', admission_id='no-such-admission',
+ submission_id='orphan', text='edited')
+ assert missing['error']['data']['reason'] == 'not_found', missing
+ assert find_session_admission(db, principal_id='human', session_id='s', request_id='too-late') is None
+ assert _ledger(db) == [('first', 'started', None)]
+
+
+async def test_a_queued_admission_survives_an_owner_restart_and_is_steered_by_the_next_owner(tmp_path, monkeypatch):
+ db, before = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(before, '_schedule', lambda ref: None)
+ with db:
+ await _submit(before, 'head')
+ follower = await _submit(before, 'follower')
+ # Owner restart: a new epoch over the same store; both rows were still queued.
+ epoch = begin_runtime_epoch(db, instance_id='next')
+ recover_session_inputs(db, epoch=epoch)
+ after = SessionAuthority(before.runner, profile_id='owned', instance_id='next', db=db, epoch=epoch)
+ after.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human'), 'route')
+ turn = Turn(monkeypatch)
+ after._schedule(REF)
+ await asyncio.wait_for(turn.claimed.wait(), 5)
+
+ reply = await _call(_connection(after), 'prompt.steer_queued', admission_id=follower.admission_id)
+ assert 'error' not in reply, reply
+ assert turn.agent.steers == ['follower']
+ turn.release.set()
+ await asyncio.wait_for(after.sessions['s'].task, 5)
+ assert turn.ran == ['head']
+ assert _ledger(db) == [('head', 'terminal', 'completed'), ('follower', 'terminal', 'steered')]
+
+
+async def test_pending_rows_name_the_controls_the_owner_serves(tmp_path, monkeypatch):
+ """Desktop shows Steer / Edit only for rows that list them: an older owner lists none."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ with db:
+ await _submit(authority, 'head')
+ await _submit(authority, 'follower')
+ claim_session_input(db, epoch=authority.epoch, session_id='s')
+ pending = {row['input_id']: row for row in (asdict(authority._pending_receipt(r))
+ for r in authority._pending_rows(REF))}
+ assert pending['follower'].get('controls') == ['steer', 'replace']
+ assert not pending['head'].get('controls'), 'a started row has no queued-row controls'
diff --git a/tests/gateway/test_prompt_queued_transfer.py b/tests/gateway/test_prompt_queued_transfer.py
new file mode 100644
index 00000000000..66d44332e7e
--- /dev/null
+++ b/tests/gateway/test_prompt_queued_transfer.py
@@ -0,0 +1,299 @@
+"""prompt.steer_queued / prompt.replace_queued failure windows (RT-35 review): a durable queued prompt
+is never reported steered unless its text reached the turn that settled, the steer's storage wait
+never holds a lock the owner loop takes, a replacement is bound to the admission it replaced, and
+only interactive local producers are offered (or served) either verb."""
+import asyncio
+import sqlite3
+import threading
+import time
+
+import pytest
+
+from gateway import session_finite, session_queued_controls
+from gateway.session_contract import SessionRef
+from hermes_state_runtime import (
+ begin_runtime_epoch, claim_session_input, find_session_admission, get_session_admission,
+ recover_session_inputs,
+)
+from tests.gateway.test_prompt_queued_controls import Turn, _call, _completions, _connection, _ledger, interactive
+from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit
+
+
+async def _drained(authority):
+ task = authority.sessions['s'].task
+ if task is not None:
+ await asyncio.wait_for(task, 5)
+
+
+async def test_a_steer_before_the_turn_adopts_its_agent_is_refused_and_the_prompt_still_runs(tmp_path, monkeypatch):
+ """Reviewer repro: execution held before adoption, steer, then agent construction fails. The text
+ must not be reported steered; the durable queued prompt stays queued and runs in FIFO order."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ held, release, ran = asyncio.Event(), asyncio.Event(), []
+
+ async def execute(authority, ref, row):
+ ran.append(row['payload']['text'])
+ if row['payload']['text'] == 'running':
+ held.set()
+ await asyncio.wait_for(release.wait(), 5)
+ raise RuntimeError('agent construction failed')
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ with db:
+ await _submit(authority, 'running')
+ await asyncio.wait_for(held.wait(), 5)
+ queued = await _submit(authority, 'follow-up')
+ reply = await _call(_connection(authority), 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert reply.get('error', {}).get('data', {}).get('reason') == 'steer_unavailable', reply
+ assert get_session_admission(db, admission_id=queued.admission_id)['status'] == 'queued'
+ assert not authority.pending_steers, 'nothing may be latched for an agent that does not exist yet'
+ release.set()
+ await _drained(authority)
+ assert ran == ['running', 'follow-up'], 'the queued prompt must still run as its own turn'
+ assert _ledger(db) == [('running', 'terminal', 'failed'), ('follow-up', 'terminal', 'completed')]
+
+
+async def test_a_steer_into_a_turn_that_then_fails_settles_interrupted_not_steered(tmp_path, monkeypatch):
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ turn, frames = Turn(monkeypatch, fail='running'), []
+ authority.sessions['s'].event_stream.observers.add(frames.append)
+ with db:
+ await _submit(authority, 'running')
+ await asyncio.wait_for(turn.claimed.wait(), 5)
+ queued = await _submit(authority, 'follow-up')
+ conn = _connection(authority)
+ reply = await _call(conn, 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert 'error' not in reply, reply
+ # Transferred into the running turn, not yet steered: it settles with that turn.
+ assert (reply['result']['status'], reply['result']['outcome']) == ('started', None), reply
+ assert turn.agent.steers == ['follow-up']
+ turn.release.set()
+ await _drained(authority)
+ receipt = await _call(conn, 'prompt.receipt', admission_id=queued.admission_id)
+ assert (receipt['result']['status'], receipt['result']['outcome']) == ('terminal', 'interrupted'), receipt
+ assert (queued.admission_id, 'steered') not in _completions(frames)
+ assert turn.ran == ['running'], 'a steered prompt is never replayed on its own'
+
+
+async def test_a_turn_that_ends_between_the_steer_commit_and_delivery_gets_its_prompt_back(tmp_path, monkeypatch):
+ """The receiving execution returns after the steer committed but before the text reached its agent:
+ the admission is put back in its FIFO place (never reported steered) and runs as its own turn."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ turn = Turn(monkeypatch)
+ loop = asyncio.get_running_loop()
+ original = session_queued_controls.steer_session_input
+
+ def committed_then_turn_ends(*args, **kwargs):
+ committed = original(*args, **kwargs)
+ loop.call_soon_threadsafe(turn.release.set)
+ deadline = time.monotonic() + 3
+ while authority.executing.get('s') is not None and time.monotonic() < deadline:
+ time.sleep(0.01)
+ return committed
+ monkeypatch.setattr(session_queued_controls, 'steer_session_input', committed_then_turn_ends)
+ with db:
+ await _submit(authority, 'running')
+ await asyncio.wait_for(turn.claimed.wait(), 5)
+ queued = await _submit(authority, 'follow-up')
+ reply = await _call(_connection(authority), 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert reply.get('error', {}).get('data', {}).get('reason') == 'steer_unavailable', reply
+ await _drained(authority)
+ for _ in range(100): # the restored row's own drain
+ if turn.ran == ['running', 'follow-up']:
+ break
+ await asyncio.sleep(0.02)
+ await _drained(authority)
+ assert turn.agent.steers == []
+ assert turn.ran == ['running', 'follow-up']
+ assert _ledger(db) == [('running', 'terminal', 'completed'), ('follow-up', 'terminal', 'completed')]
+
+
+def test_an_owner_restart_mid_transfer_settles_the_steered_admission_interrupted(tmp_path, monkeypatch):
+ """Committed but not confirmed consumed when the owner died: interrupted, never auto-replayed."""
+ from hermes_state_runtime import admit_session_input
+ db, authority = _authority(tmp_path, monkeypatch)
+ with db:
+ for request_id in ('running', 'follow-up'):
+ admit_session_input(db, epoch=authority.epoch, principal_id='human', session_id='s',
+ request_id=request_id, payload={'text': request_id})
+ running = claim_session_input(db, epoch=authority.epoch, session_id='s')
+ follow = find_session_admission(db, principal_id='human', session_id='s', request_id='follow-up')
+ session_queued_controls.steer_session_input(db, epoch=authority.epoch, admission_id=follow['admission_id'],
+ generation=running['generation'])
+ epoch = begin_runtime_epoch(db, instance_id='next')
+ recover_session_inputs(db, epoch=epoch)
+ assert _ledger(db) == [('running', 'unknown', None), ('follow-up', 'terminal', 'interrupted')]
+
+
[email protected]('verb', ['steer', 'replace'])
+async def test_a_held_sqlite_writer_never_stalls_the_owner_loop_behind_a_queued_control(tmp_path, monkeypatch, verb):
+ """Reviewer repro: another connection holds BEGIN IMMEDIATE while a steer/replace waits on the writer.
+ A loop-side receipt (which takes the session's stream lock) and an unrelated ticker stay responsive."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ turn = Turn(monkeypatch)
+ with db:
+ await _submit(authority, 'running')
+ await asyncio.wait_for(turn.claimed.wait(), 5)
+ queued = await _submit(authority, 'follow-up')
+ other = await _submit(authority, 'other')
+ holding, release, done, writing = threading.Event(), threading.Event(), threading.Event(), threading.Event()
+
+ def hold_writer():
+ blocker = sqlite3.connect(str(db.db_path), isolation_level=None, timeout=10)
+ try:
+ blocker.execute('BEGIN IMMEDIATE')
+ holding.set()
+ release.wait(timeout=2) # bounded: a stalled loop cannot release it itself
+ blocker.execute('ROLLBACK')
+ finally:
+ blocker.close()
+ done.set()
+ # The control's own store write starts (and then waits on the held writer).
+ from gateway import session_authority
+ target, name = ((session_queued_controls, 'steer_session_input') if verb == 'steer'
+ else (session_authority, 'admit_session_input'))
+ original = getattr(target, name)
+
+ def announced(*args, **kwargs):
+ writing.set()
+ return original(*args, **kwargs)
+ monkeypatch.setattr(target, name, announced)
+ threading.Thread(target=hold_writer, daemon=True).start()
+ assert await asyncio.to_thread(holding.wait, 5)
+ gaps, ticking = [], True
+
+ async def ticker():
+ last = time.monotonic()
+ while ticking:
+ await asyncio.sleep(0.02)
+ now = time.monotonic()
+ gaps.append(now - last)
+ last = now
+ ticks = asyncio.create_task(ticker())
+ params = ({'admission_id': queued.admission_id} if verb == 'steer' else
+ {'admission_id': queued.admission_id, 'submission_id': 'edited', 'text': 'edited'})
+ control = asyncio.create_task(_call(_connection(authority), f'prompt.{verb}_queued', **params))
+ assert await asyncio.to_thread(writing.wait, 5)
+ started = time.monotonic()
+ await authority.receipt(ACTOR, REF, other.admission_id)
+ receipt_latency = time.monotonic() - started
+ release.set()
+ reply = await asyncio.wait_for(control, 30)
+ ticking = False
+ await ticks
+ assert await asyncio.to_thread(done.wait, 5)
+ turn.release.set()
+ await _drained(authority)
+ assert 'error' not in reply, reply
+ assert receipt_latency < 0.5, f'a loop-side receipt waited {receipt_latency:.2f}s on the held writer'
+ assert max(gaps) < 0.5, f'the owner loop stalled {max(gaps):.2f}s'
+
+
+async def test_concurrent_replacements_of_different_rows_under_one_submission_id_replace_exactly_one(tmp_path, monkeypatch):
+ """Reviewer repro: both initial lookups see no replacement; one replacement is admitted and binds the
+ row it retired, the other is refused admission_conflict and its row stays queued."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ barrier = threading.Barrier(2, timeout=5)
+ original = session_queued_controls.find_session_admission
+
+ def synchronized(*args, **kwargs):
+ found = original(*args, **kwargs)
+ barrier.wait()
+ return found
+ monkeypatch.setattr(session_queued_controls, 'find_session_admission', synchronized)
+ with db:
+ a, b = await _submit(authority, 'a'), await _submit(authority, 'b')
+ replies = await asyncio.gather(*(
+ _call(_connection(authority), 'prompt.replace_queued', admission_id=old.admission_id,
+ submission_id='edit', text='same words') for old in (a, b)))
+ succeeded = [reply for reply in replies if 'error' not in reply]
+ refused = [reply['error']['data']['reason'] for reply in replies if 'error' in reply]
+ assert len(succeeded) == 1 and refused == ['admission_conflict'], replies
+ ledger = dict((request_id, (status, outcome)) for request_id, status, outcome in _ledger(db))
+ assert sorted([ledger['a'], ledger['b']]) == [('queued', None), ('terminal', 'cancelled')], ledger
+ assert ledger['edit'] == ('queued', None)
+
+
+async def test_a_replacement_retry_naming_another_admission_is_a_conflict(tmp_path, monkeypatch):
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ with db:
+ a, b = await _submit(authority, 'a'), await _submit(authority, 'b')
+ conn = _connection(authority)
+ edit = {'submission_id': 'edit', 'text': 'same words'}
+ first = await _call(conn, 'prompt.replace_queued', admission_id=a.admission_id, **edit)
+ assert 'error' not in first, first
+ # An exact retry (same old admission) answers the same replacement.
+ again = await _call(conn, 'prompt.replace_queued', admission_id=a.admission_id, **edit)
+ assert again.get('result', {}).get('admission_id') == first['result']['admission_id'], again
+ # Another row, independently cancelled, never borrows that replacement's receipt.
+ await _call(conn, 'prompt.cancel', admission_id=b.admission_id)
+ other = await _call(conn, 'prompt.replace_queued', admission_id=b.admission_id, **edit)
+ assert other.get('error', {}).get('data', {}).get('reason') == 'admission_conflict', other
+
+
+def test_a_hosted_room_queued_row_is_offered_no_controls_and_both_verbs_refuse_it(hosted_owner):
+ """A hosted-room settlement has no ``steered`` (or replaced) result: its rows are never offered either
+ verb and the verbs refuse them by name, so the room's terminal/results reads stay healthy."""
+ from dataclasses import asdict
+ from gateway.hosted_room_driver import TaskIdentity
+ from gateway.session_contract import Principal
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_hosted_rpc import HostedRoomAuthorityRPC
+ authority, loop, principal, _ = hosted_owner
+ rpc = HostedRoomAuthorityRPC(authority, loop, room_id='room', member_id='member', profile='default',
+ principal=principal, authorize=lambda *args: True)
+ coords = dict(profile='default', source='bot_room')
+ sid = rpc.create(**coords, title='Group: room')['session_id']
+ callbacks = []
+ rows = [rpc.submit(**coords, session_id=sid, prompt=text, task=TaskIdentity('room', text, 'thread', text),
+ execution_generation=1, on_terminal=callbacks.append) for text in ('first', 'second')]
+ claim_session_input(authority.db, epoch=authority.epoch, session_id=sid)
+ ref = SessionRef(authority.profile_id, sid)
+
+ def run(coro):
+ return asyncio.run_coroutine_threadsafe(coro, loop).result(10)
+
+ async def pending():
+ return [asdict(authority._pending_receipt(row)) for row in authority._pending_rows(ref)]
+ assert [row['controls'] for row in run(pending())] == [[], []]
+
+ conn = AuthorityConnection(authority, object(), {'user_id': principal.subject})
+ conn.actor = Principal(principal.subject, authority.profile_id, principal.capabilities, conn.actor.transport_id)
+ conn.subscriptions[sid] = 'attached'
+ for method, params in (('prompt.steer_queued', {}),
+ ('prompt.replace_queued', {'submission_id': 'edited', 'text': 'edited'})):
+ reply = run(conn.dispatch({'id': 1, 'method': method, 'params': {
+ 'session_id': sid, 'admission_id': rows[1]['admission_id'], **params}}))
+ assert reply.get('error', {}).get('data', {}).get('reason') == 'unsupported_control', (method, reply)
+ assert get_session_admission(authority.db, admission_id=rows[1]['admission_id'])['status'] == 'queued'
+ # The room's reads stay healthy over its ledger.
+ assert isinstance(rpc.history(**coords, session_id=sid), list)
+ assert isinstance(rpc.info(**coords, session_id=sid), dict)
+
+
+def test_only_interactive_local_sessions_are_offered_queued_controls(tmp_path, monkeypatch):
+ """cron, kanban, a2a and bot_room rows settle without a ``steered``/replaced result: never offered."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ row = {'status': 'queued', 'target_session_id': 's', 'payload': {'text': 'hello'}}
+ with db:
+ assert session_queued_controls.queued_controls(authority, row) == [], 'no launch policy: not interactive'
+ for source, offered in (('gui', True), ('tui', True), ('cli', True), ('acp', True), ('cron', False),
+ ('kanban', False), ('a2a', False), ('bot_room', False)):
+ authority._launch_sources = {}
+ interactive(db, source=source)
+ controls = session_queued_controls.queued_controls(authority, row)
+ assert controls == (['steer', 'replace'] if offered else []), (source, controls)
diff --git a/tests/hermes_cli/test_gateway_chat_pending_preview.py b/tests/hermes_cli/test_gateway_chat_pending_preview.py
index 307d6e8c1a9..f72054a263b 100644
--- a/tests/hermes_cli/test_gateway_chat_pending_preview.py
+++ b/tests/hermes_cli/test_gateway_chat_pending_preview.py
@@ -8,6 +8,7 @@ def test_resume_lists_pending_admission_text_capped_and_terminal_safe(capsys):
authority = object.__new__(SessionAuthority)
authority.profile_id, authority.epoch = "profile", 3
+ authority._launch_sources = {"stored": "cli"} # the resumed classic CLI's launch source
row = {"target_session_id": "stored", "outcome": None, "owner_epoch": 3}
hostile = "\x1b]0;pwned\x07\x1b[2Jdeploy\rhidden\x08\u202e\x9b31m now " + "x" * 200
rows = [
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index 947c756bb2b..9d2e65912ec 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -82,6 +82,9 @@ class CanonicalSessionHandle(Result):
class CanonicalPendingAdmission(AdmissionStatus):
input_id: str
text: str
+ # The queued-row verbs the owner serves for this row: ``steer`` (``prompt.steer_queued``) and
+ # ``replace`` (``prompt.replace_queued``). Absent from an owner that predates them.
+ controls: list[Literal['steer', 'replace']] | None = None
class CanonicalPendingPrompt(Result):
@@ -211,6 +214,21 @@ class CanonicalSubmitParams(CanonicalSessionParams):
clarify_batch: bool = False
+class CanonicalSteerQueuedParams(CanonicalSessionParams):
+ admission_id: str
+
+
+class CanonicalReplaceQueuedParams(CanonicalSessionParams):
+ """The edited prompt: admitted as a NEW admission (``submission_id``) at the FIFO tail."""
+
+ admission_id: str
+ submission_id: str
+ text: str
+ attachments: list[CanonicalAttachment] | None = None
+ display_kind: Literal['hidden'] | None = None
+ title_preview: str | None = None
+
+
class CanonicalControlParams(CanonicalSessionParams):
execution_generation: int
@@ -271,3 +289,15 @@ for _name, _params, _result in (
('approval.respond', CanonicalApprovalParams, PromptResponseResult),
):
canonical_method(_name, params=_params, result=_result)
+
+canonical_method('prompt.steer_queued', params=CanonicalSteerQueuedParams, result=AdmissionStatus,
+ doc="Hand a still-queued admission's text to the running turn's agent as a steer. "
+ "The admission reads 'started' with that turn and never runs on its own; it "
+ "settles terminal 'steered' when the turn completes, else 'interrupted'. "
+ "Refusals: admission_started, session_idle, steer_unavailable (no agent to take "
+ "it: the admission stays queued), unsupported_control, not_found.")
+canonical_method('prompt.replace_queued', params=CanonicalReplaceQueuedParams, result=AdmissionStatus,
+ doc="Cancel a still-queued admission and admit the edited prompt as a new admission "
+ "at the back of the FIFO, in one write bound to the replaced admission. "
+ "Refusals: admission_started, admission_conflict (the submission_id replaced "
+ "another admission), queue_full, unsupported_control, not_found.")