[Feature]: Queue and steer semantics for active AG-UI runs
Is your feature request related to a problem? Please describe.
In an AG-UI deployment, a user may send a second message while a run is still active. AguiResumeCoordinator.beginRun intentionally serializes runs per thread and rejects a second run with an error ("Thread already has an active run; wait for run ... to finish"), so today the client has to keep a local FIFO and resubmit after the terminal event. That works, but it has no server-side ordering or idempotency and is fragile across reconnects.
There is also no documented way to steer an active run: apply a user correction at the next safe point without cancelling the run. What we found on main:
- The durable runtime has the full control plane:
DurableTurn.steer/inject/withdraw(pluscancel/respond/pause/resume) inagentscope-durable/durable-runtime/.../DurableTurn.java. - On the non-durable path,
InterruptContextcarries auserMessageand the run can be interrupted with one, butReActAgent.handleInterruptdoes not consume it — it reconciles pending tool calls and appends a canned recovery message, so interrupt-with-message is effectively a cancel. InboxMiddlewarecan inject aHintBlock, butHintBlockis documented as guidance for reasoning "without being part of the conversation history" — it is not a user message in the transcript.- For AG-UI specifically, the only inbound control we found is
RunAgentInput.resume, which resolves already-open (paused) interrupts such as permission confirmations; we could not find an inbound contract that queues or steers an active run. On the harness gateway side,TurnBusyExceptionis mapped to skip, so concurrent inbound requests for a session are dropped rather than queued.
The README mentions introducing "AgentSession ... queue while busy or resume after interruption", but we could not find an AgentSession class or a queue-while-busy API on main (the session-log doc points background queues to the Durable runtime). If queue-while-busy already exists, please point us to the API and semantics.
Describe the solution you'd like
A documented, opt-in contract for active runs, for example:
enqueue(threadId, runId, userMessage): stable FIFO, idempotency key, survives reconnect;steer(threadId, runId, userMessage): applied at a safe point before the next model call, recorded as a user message in the transcript;- defined interaction with cancel/pause/HITL and with the existing one-active-run-per-thread guard.
We are not asking for a full implementation in this issue. We would like to know:
- Is this intended to be solved only by the durable runtime?
- Is there a planned API for the AG-UI / non-durable
ReActAgentpath? - If we prepare a minimal, opt-in prototype with tests for the smallest acceptable slice, would a PR be welcome? What semantics would you prefer?
Describe alternatives you've considered
- Client-side FIFO + resubmit after the terminal event (works today; loses server-side ordering and idempotency).
- Interrupt the active run and start a new one (loses the in-flight turn's user message and can duplicate work).
- Durable runtime only (has
steer/inject/withdraw, but requires journaling/leases and may not fit existing AG-UI deployments).
Additional context
Reviewed against main@5525ac1aa. Relevant code: AguiResumeCoordinator.beginRun (one-active-run guard), DurableTurn.steer/inject/withdraw, InboxMiddleware + HintBlock, ReActAgent.handleInterrupt, InterruptContext.userMessage. Related: #1436 reports the same busy-session pain for IM gateways; #2437 reported the missing inbound HITL path, whose resume channel has since landed. We searched open issues and PRs (queue / queued message / message queue / steer / interrupt / durable / AG-UI / run while running / pending message / follow-up / inject / InboxMiddleware) and found no duplicate. We can prepare a minimal prototype and tests if the direction is agreed.
One distinction on main@5525ac1aa: HarnessGateway defaults to LocalSessionTurnGate, whose fair semaphore waits for the previous subscription to release its lease; that implementation never throws TurnBusyException. The skip-on-busy branches apply when a different gate rejects acquisition. That gives local serialization, but not an accepted-message queue with IDs, bounded capacity or reconnect/restart guarantees. The AG-UI active-run rejection is a separate boundary.
For your prototype, I would separate enqueue from steer and make the first slice enqueue-only. An acknowledgement should identify the accepted message independently of the active run; define FIFO at acceptance, duplicate-ID behavior (including same ID/different payload), a capacity limit, and cancellation of a queued message. Please also state whether disconnect cancels accepted work and whether “survives reconnect” means the same server process or restart/multi-node recovery—the latter needs a persistent ownership contract.
HITL needs an explicit rule: AguiResumeCoordinator records unresolved interrupts even after a RUN_FINISHED event and rejects ordinary input until matching resume entries resolve them. Advancing the FIFO on every RUN_FINISHED would therefore be wrong; the pending ordinary messages must wait while the interrupt response has a separate route. A useful acceptance case is active run → permission pause → queued user message → permission response → resumed turn → queued turn, with duplicate submissions and disconnects at the transitions.
Steer can remain a later contract for transcript insertion and a safe point before the next model call; it should not be implemented by routing user input through the existing cancel/recovery path. These are source-reading observations, not runtime validation of a new queue implementation.
Thanks — this is very helpful, and good catch on the default.
You are right: we re-read the source — HarnessGateway defaults to LocalSessionTurnGate (fair semaphore, acquire() blocks, never throws TurnBusyException), so the default is in-process waiting without accepted-message ids, capacity limits, or restart guarantees. Our "dropped rather than queued" wording only describes the rejecting-gate branches, and no gate shipped in this repo throws that exception — those branches are reachable only with a custom gate. We'll keep that distinction precise and treat the AG-UI one-active-run rejection as the boundary the proposal targets.
For the prototype we agree with enqueue-only as the first slice, with steer deferred and not routed through the cancel/recovery path. Concretely, we would propose:
- an acknowledgement carries its own message id, independent of any run;
- FIFO order is fixed at acceptance; a duplicate id is an idempotent no-op, while the same id with a different payload is rejected with a typed error;
- bounded capacity (configurable), rejecting with a typed error when full;
- a queued message can be cancelled by id;
- disconnect semantics are stated per lifecycle: the existing
interruptOnDisconnectoption (defaulttrueinAguiPropertiesand both the MVC and WebFlux builders) interrupts the active run when the SSE connection is cancelled or breaks, while accepted-but-queued messages are not cancelled by disconnect. In the first slice "survives reconnect" means the same server process; restart/multi-node recovery (persistent ownership) stays a later slice; - queue advancement is driven by thread state, not by observing
RUN_FINISHEDalone: it requires the thread to be idle, no unresolved interrupts (they also survive aRUN_ERROR, matchingAguiResumeCoordinator), and a client attached — a queued run is never auto-started into a disconnected session, so a reconnecting client finds its message either still pending or on the resumed stream.
Your acceptance case (active run → permission pause → queued user message → permission response → resumed turn → queued turn, with duplicate submissions and disconnects at the transitions) will be the core scenario test. We'll prepare this as an opt-in prototype with tests once the scope above sounds right to you.
For a same-process, enqueue-only prototype, that addresses the scope concerns I raised. Keeping permission responses on a separate route and requiring an attached client before dispatch are useful boundaries.
Two observable behaviors would help pin down the remaining contract:
- What is the duplicate-ID lifetime? Is an ID protected only while queued/active, or also after completion or cancellation? A retry after a lost acknowledgement should return the retained message state rather than silently execute again. If completed IDs expire, document the retention boundary and bound that history separately from pending queue capacity; this slice need not promise deduplication across process restarts.
- Please recheck idle / no unresolved interrupt / attached-client state when claiming the next queued message, not just when accepting it. A deterministic test can pause dispatch after observing idle, then disconnect the client or register an interrupt before releasing dispatch. The message should remain pending without a new model invocation, then run once when the required state is restored. A second concurrent dispatch trigger should not claim it twice.
Those cases should fit the proposed opt-in prototype without adding steer or durable multi-node ownership.
Thanks — agreed on both, and we'll fold them into the prototype contract:
- Duplicate-ID lifetime: an id stays protected after completion and cancellation, not only while queued/active. A retry with an id inside the retention window returns the retained message state instead of executing again; the same id with a different payload is rejected for as long as the id is retained. Retention is bounded per thread (a configurable number of retained terminal ids, tracked separately from pending queue capacity) and documented as an explicit boundary; expired ids are treated as new. This slice does not deduplicate across process restarts.
- Claim-time recheck: dispatch re-evaluates idle / no unresolved interrupts / attached-client at claim time, not only at accept time, and the claim is atomic — a second concurrent dispatch trigger cannot claim the same message twice. We'll write the deterministic test you described: pause dispatch after idle is observed, disconnect or register an interrupt before release, assert the message stays pending with no new model invocation, then restore state and assert it runs exactly once.
With these two added, we'll start on the opt-in prototype and tests.
Hi @CryoThrust — the enqueue-only slice is done, and I'd like to open the PR. Two things worth putting in front of you first.
What it does, against the contract we agreed: one queue per thread with a configurable capacity, an acknowledgement that carries its own message id, FIFO fixed at acceptance, duplicate ids treated as retries (same id with a different payload is rejected), cancellation by id, and the claim-time recheck you asked for. Idle, no unresolved interrupts and an attached client are all re-evaluated when the next message is claimed, not only when it is accepted, and the claim is atomic, so two concurrent triggers cannot take the same message. On your acceptance case: a queued message is not delivered while a confirmation is outstanding and goes out once it is answered, with separate tests for duplicate submissions, a client that goes away and comes back, and two concurrent claims.
What is not in this slice: reordering or prioritising a queued message, clearing the whole queue at once, and editing a queued message in place. Cancellation by id is in, but a cancelled message that is submitted again goes to the back of the queue, so it cannot be moved forward. Those three are the actions we left out of the first slice; say which you want and I can add them here or as a follow-up.
The design call I want to flag: claim and execution are two requests. A claim hands the message to the client, which then posts it as a run. Between those two the thread genuinely is idle, and a second claim in that gap would hand out the next message, which the active-run check would then reject after it had already left the queue. So after a hand-off the queue stays closed until it sees the run id it handed out, or observes the thread busy afterwards; five seconds is the fallback when neither arrives.
The docs state the two boundaries you asked about: this slice is same-process, and delivery is at most once, with no redelivery.
If you would rather the queue advanced inside the runtime instead of being claimed by the client, say so and I will change the shape before opening. Otherwise I will open the PR.
PR is open: https://github.com/agentscope-ai/agentscope-java/pull/4281
It is the enqueue-only slice we agreed on. On the two points you raised: a withdrawn or completed id stays protected for the retention window, bounded per thread and tracked separately from pending capacity; and the claim re-checks idle, unresolved interrupts and an attached client under the same lock, so a second concurrent trigger cannot take the same message. The PR body lists the covering tests. Steer is not in this slice.
PR is open: https://github.com/agentscope-ai/agentscope-java/pull/4281
It is the enqueue-only slice we agreed on. On the two points you raised: a claimed or withdrawn id stays protected for the retention window, bounded per thread and tracked separately from pending capacity; and the claim re-reads idle and unresolved interrupts under the same striped thread-state lock that a run start takes. If the thread is still busy at that recheck — an active run or an unresolved interrupt — the claim returns 204 and the message stays queued.
One correction to what I wrote before opening the PR: this implementation has no attached-client state, so it does not perform the connected-client recheck I said it would. The queue never starts a run, and a claim request is the only way a message is delivered to a client; that prevents server-side dispatch into a disconnected session, but a claim already in flight when the client disconnects can still consume a message. The PR body states that boundary. If you want an explicit connection registry and a disconnect gate, that is a separate piece of work; tell me and I will scope it.
The deterministic pause-after-idle test is in, in two forms: a run that is still active at the recheck, and an unresolved interrupt registered between the idle observation and the release. Both leave the message queued and invoke no model; after the state is restored the message is claimed and replayed once. The disconnect half of your sentence is not expressible server-side in this pull model, because there is no connection state to observe, so I have not claimed that it is covered.
Steer is not in this slice.
Thanks for correcting the delivery model. With client-pulled claims, I would keep a connection registry out of the enqueue-only slice. My earlier attached-client check assumed server-side dispatch, so it does not apply directly to this shape.
The important distinction is claim versus receipt: a request can dequeue a message even if its response never reaches the client. Under the stated at-most-once policy, that loss is an explicit boundary. Retaining the claimed ID should still prevent a retry from becoming another execution, even when no run was subsequently created. The five-second hand-off gate expiring should reopen progress for later messages, without implying that the earlier payload was delivered or should be replayed.
If the community later wants recovery from a lost claim response, I would discuss a separate claim/ack protocol with a lease and fencing token. Redelivery alone would allow a delayed original client and a replacement client to submit the same work. That is a different delivery contract, so I would leave it out of this first slice rather than add a connection registry to approximate it. This is a response to the semantics described here, not a review of the PR implementation.
Thanks — agreed on all of it. The lost-claim-response case is documented as an intentional boundary ("Message Queue For Busy Threads" in the AG-UI page, included in #4281), and neither a connection registry nor a claim/ack protocol goes into this slice.
On your two expectations:
- A claimed id is recorded as
CLAIMED. Re-submitting it to the accept endpoint with the same trailing message gets200withstatus=DUPLICATE,state=CLAIMEDandposition=-1, so it is not queued again, whether or not a run was started after the claim. This holds while the id is in the per-thread ledger (up toidempotency-retentionids); once evicted, the same id is accepted as a new message. - A retried
claimdoes not get that message back: the claim removed it from the queue and nothing re-queues it. The retry gets204while the hand-off gate is closed, then the next queued message once the gate has passed and the thread is idle. The five seconds are the wait when no run follows the delivery.
These are pinned by unit tests on the queue class: ThreadMessageQueueTest.shouldReportClaimedStateForRetryAfterClaim, shouldKeepTheWindowForAnyOtherRun and shouldClaimInAcceptanceOrderAndHoldTheHandOff.