Skip to content

The agent that grows with you

fix: re-admit only a correction the owner marks undelivered

Tekniumb2c269f66520
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 2a599deca31..811f61b191a 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -5091,6 +5091,7 @@ export interface CanonicalCorrectionAck {
text: string
execution_generation: number
authority_epoch: number
+ delivered?: false | null
}
/** A bare stop phrase typed while the session's voice chat is on: the chat ended, nothing was admitted (TUI-26). */
export interface CanonicalVoiceStopped {
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 36e4b1e1323..bf0e80e9f20 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -8518,6 +8518,19 @@
"authority_epoch": {
"title": "Authority Epoch",
"type": "integer"
+ },
+ "delivered": {
+ "anyOf": [
+ {
+ "const": false,
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Delivered"
}
},
"required": [
diff --git a/gateway/session_busy_controls.py b/gateway/session_busy_controls.py
index e3b3676f6b4..1a97c51a22b 100644
--- a/gateway/session_busy_controls.py
+++ b/gateway/session_busy_controls.py
@@ -203,10 +203,11 @@ async def correct(connection, ref, params, *, verb):
# running), and a redirect in the build window has no agent to queue behind. Nothing live can
# take the text, so answer 'rejected' — the wire contract's "not corrected, queue it as the
# next prompt" (desktop SessionRedirectResponse, tui_gateway's idle-steer reply). Raising here
- # made clients discard the message (#141644).
+ # made clients discard the message (#141644). ``delivered: False`` is the confirmation a
+ # client may re-admit on: the live-agent 'rejected' below can follow delivery.
if agent is None:
return {'status': 'rejected', 'text': params['text'], 'execution_generation': generation,
- 'authority_epoch': authority.epoch}
+ 'authority_epoch': authority.epoch, 'delivered': False}
method = getattr(agent, verb, None)
if not callable(method):
raise RuntimeStoreError('execution_not_ready')
diff --git a/tests/gateway/test_session_steer_stale_busy_refusal.py b/tests/gateway/test_session_steer_stale_busy_refusal.py
index 6f9103ee25c..34261cbc261 100644
--- a/tests/gateway/test_session_steer_stale_busy_refusal.py
+++ b/tests/gateway/test_session_steer_stale_busy_refusal.py
@@ -8,8 +8,8 @@ optimistic row and drops the text, so the message is unrecoverable.
'Rejected' is the reply both ends already define for "not corrected — queue it as the next
prompt" (``SessionRedirectResponse`` in the Desktop, and tui_gateway's idle-steer answer), so
-the text survives as the next turn. A genuinely stale generation and an agent that cannot
-carry the verb keep their errors.
+the text survives as the next turn. Only that reply carries ``delivered: False``: a live agent's
+refusal can follow delivery (a Codex steer whose ACK timed out), so clients must not re-send it.
"""
import asyncio
from types import SimpleNamespace
@@ -17,7 +17,6 @@ from types import SimpleNamespace
import pytest
from gateway.session_busy_controls import correct
-from hermes_state_runtime import RuntimeStoreError
from tests.gateway.test_session_authority_cancel_settlement import (
ACTOR, REF, _authority, _submit, _wire_turn_agent)
@@ -50,57 +49,26 @@ async def test_redirect_for_a_claimed_turn_with_no_agent_is_rejected_not_errored
reply = await correct(connection, REF, {'session_id': 's', 'text': 'second thought',
'execution_generation': generation}, verb='redirect')
- assert reply == {'status': 'rejected', 'text': 'second thought',
+ assert reply == {'status': 'rejected', 'text': 'second thought', 'delivered': False,
'execution_generation': generation, 'authority_epoch': authority.epoch}
release.set()
await asyncio.wait_for(authority.sessions['s'].task, 5)
@pytest.mark.asyncio
-async def test_steer_in_the_build_window_still_latches_for_the_adopting_agent(tmp_path, monkeypatch):
- """The latch path is untouched: a steer that CAN reach the turn is not refused."""
+async def test_a_live_agents_refusal_is_not_marked_undelivered(tmp_path, monkeypatch):
+ """A live agent answering False may already hold the text (Codex turn/steer ACK timeout), so the
+ reply is a plain 'rejected' a client settles as refused, never one it re-admits as a prompt."""
db, authority = _authority(tmp_path, monkeypatch)
connection = SimpleNamespace(authority=authority, actor=ACTOR)
with db:
release = await _claim_without_agent(authority, monkeypatch)
generation = authority._handle(REF).execution_generation
+ _wire_turn_agent(authority, generation, SimpleNamespace(interrupted=0, redirect=lambda text: False))
- reply = await correct(connection, REF, {'session_id': 's', 'text': 'use the staging db',
- 'execution_generation': generation}, verb='steer')
-
- assert reply['status'] == 'queued'
- assert authority.pending_steers[REF.session_id][0] == generation
- release.set()
- await asyncio.wait_for(authority.sessions['s'].task, 5)
-
-
-async def test_a_stale_generation_still_raises(tmp_path, monkeypatch):
- db, authority = _authority(tmp_path, monkeypatch)
- connection = SimpleNamespace(authority=authority, actor=ACTOR)
- with db:
- release = await _claim_without_agent(authority, monkeypatch)
- generation = authority._handle(REF).execution_generation
-
- with pytest.raises(RuntimeStoreError, match='stale_generation'):
- await correct(connection, REF, {'session_id': 's', 'text': 'late',
- 'execution_generation': generation + 1}, verb='redirect')
- release.set()
- await asyncio.wait_for(authority.sessions['s'].task, 5)
-
-
-async def test_an_adopted_agent_that_cannot_carry_the_verb_still_raises(tmp_path, monkeypatch):
- """A live agent without ``steer`` is a capability error, not a stale busy belief."""
- db, authority = _authority(tmp_path, monkeypatch)
- connection = SimpleNamespace(authority=authority, actor=ACTOR)
- with db:
- release = await _claim_without_agent(authority, monkeypatch)
- generation = authority._handle(REF).execution_generation
- _wire_turn_agent(authority, generation, SimpleNamespace(interrupted=0))
+ reply = await correct(connection, REF, {'session_id': 's', 'text': 'maybe delivered',
+ 'execution_generation': generation}, verb='redirect')
- with pytest.raises(RuntimeStoreError, match='execution_not_ready'):
- await correct(connection, REF, {'session_id': 's', 'text': 'steer me',
- 'execution_generation': generation}, verb='steer')
+ assert reply['status'] == 'rejected' and 'delivered' not in reply, reply
release.set()
await asyncio.wait_for(authority.sessions['s'].task, 5)
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index 397b836ef8a..ed6356347c0 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -268,6 +268,9 @@ class CanonicalCorrectionAck(Result):
text: str
execution_generation: int
authority_epoch: int
+ # Only on a 'rejected' no agent ever saw (none was live): safe to admit as the next prompt. A plain
+ # 'rejected' may follow delivery (a Codex steer whose ACK timed out), so clients never re-send it.
+ delivered: Literal[False] | None = None
class CanonicalCorrectionResult(RootModel):
diff --git a/ui-tui/src/__tests__/submissionCoreUndeliveredCorrection.test.ts b/ui-tui/src/__tests__/submissionCoreUndeliveredCorrection.test.ts
index e42ed43a59d..0a4e3c6c29d 100644
--- a/ui-tui/src/__tests__/submissionCoreUndeliveredCorrection.test.ts
+++ b/ui-tui/src/__tests__/submissionCoreUndeliveredCorrection.test.ts
@@ -53,7 +53,7 @@ const refusals: Array<[string, () => Promise<unknown>]> = [
['execution_not_ready', async () => {
throw new JsonRpcGatewayError('execution_not_ready', { code: 4001, data: { reason: 'execution_not_ready' } })
}],
- ['rejected', async () => ({ status: 'rejected', text: 'next thought', execution_generation: 4 })]
+ ['rejected undelivered', async () => ({ status: 'rejected', delivered: false, text: 'next thought', execution_generation: 4 })]
]
it.each(refusals)('re-admits a correction refused undelivered (%s) as a prompt with the same submission_id', async (_name, refuse) => {
@@ -98,3 +98,26 @@ it('keeps an ambiguous transport failure as a retained control, never replayed a
await vi.waitFor(() => expect(settle).toHaveBeenCalledWith(false))
expect(calls).toEqual(['session.redirect'])
})
+
+it('settles a plain rejected correction as refused without re-sending it as a prompt', async () => {
+ // A live agent's refusal can follow delivery (Codex turn/steer whose ACK timed out): re-sending
+ // the words would run the correction twice.
+ const calls: string[] = []
+ const settle = vi.fn()
+
+ const request = vi.fn(async (method: string) => {
+ calls.push(method)
+
+ return { status: 'rejected', text: 'next thought', execution_generation: 4 }
+ })
+
+ submitPrompt('next thought', deps({ isCanonical: true, request } as unknown as GatewayClient), true, undefined, {
+ behindTurn: true,
+ queueItem: correction(settle),
+ skipDetectDrop: true
+ })
+
+ await vi.waitFor(() => expect(settle).toHaveBeenCalledWith(false))
+ await new Promise(resolve => setTimeout(resolve, 20))
+ expect(calls).toEqual(['session.redirect'])
+})
diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.ts
index d90aff90b63..9105a71da29 100644
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@ -168,10 +168,16 @@ function settleControlReply(
return true
}
- const control = r as PromptSubmitResponse & { execution_generation?: number }
-
- // 'rejected' is the owner's "not corrected, queue it as the next prompt" (no live agent took it).
- if (control?.status === 'rejected' && control.execution_generation === item.executionGeneration) {
+ const control = r as PromptSubmitResponse & { delivered?: false; execution_generation?: number }
+
+ // Only a 'rejected' the owner marks undelivered (no live agent took it) becomes the next prompt. A
+ // plain 'rejected' can follow delivery (a Codex steer whose ACK timed out): re-sending it would
+ // run the correction twice, so it settles as refused with the input retained.
+ if (
+ control?.status === 'rejected' &&
+ control.delivered === false &&
+ control.execution_generation === item.executionGeneration
+ ) {
return false
}