Skip to content

fix(ui): clear a cached agent's stale cancel signal before reusing it - #4274

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/ui-fresh-cancel-event
Sep 25, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/ui-fresh-cancel-event

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

After one streaming turn on an Agent UI session, every later non-streaming turn on that session (including eval behavior-harness calls) and every background goal tick came back with "The request was stopped because it exceeded the allowed time" without doing any work, and tool confirmations were denied instantly. The streaming cleanup fires the agent's cancel event and SSE console, and both stayed on the cached agent. Now non-streaming cache hits start with no cancel event and a fresh silent console, and goal ticks clear the cancel event.

First of a four-PR stack (#4196 → #4197 → #4198 → #4199) on the Agent UI's cached-agent lifecycle. The later PRs build on this one.

Test plan

  • python -m pytest tests/unit/chat/ui/test_cached_agent_reuse.py -q: 2 failed before the fix, 2 pass after
  • python -m pytest tests/unit/chat/ui -q: 1023 passed
  • python util/lint.py --black --isort + pylint (errors-only config) on changed files: clean

Fixes #4196

After one streaming turn, every later non-streaming turn and background goal tick on the same Agent UI session stopped at step 0 with "The request was stopped because it exceeded the allowed time", and tool confirmations were denied instantly.

The streaming cleanup fires the agent's cancel event and SSE console, and both stayed attached to the cached agent. Non-streaming cache hits now start with no cancel event and a fresh silent console; goal ticks clear the cancel event (they already install their own console).

Fixes amd#4196
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The fix is right and lands in the right place: a finished streaming turn was leaving its fired "stop" signal and a dead output channel on the session's cached agent, so every later turn on that session bailed out at step zero with the timeout message. Clearing both on reuse is the correct cure, and the two new tests reproduce the symptom rather than the implementation.

Two things worth a look, neither blocking:

  • Nothing can stop a runaway turn on the non-streaming path now. Clearing the stop signal leaves the reused agent with no interrupt at all, so when the 600-second request timeout fires and the caller gets an answer back, the worker keeps grinding against the model indefinitely, holding the session's agent. Handing the agent a fresh stop signal and firing it from the timeout handler is a small change and closes the gap — the same applies to the background goal tick, whose timeout only reaches the agent mid-generation, not at a step boundary. (This gap is shared with the freshly-created-agent path, so it predates the PR; it's just now one line away from being fixed.)
  • Reuse rewrites state on an agent another turn may still be holding. A session has exactly one cached agent and nothing serializes turns against it. A background goal tick fires on a timer with no check for a live turn, so it can land mid-stream and disarm the in-flight turn's stop signal — after which the disconnect cleanup can no longer reap that worker. Worth a follow-up if it isn't already somewhere in the four-PR stack.

Real-world evidence

N/A — no evidence bundle was produced for this run, so the verdict rests on static review plus the unit-test results the PR reports (I couldn't re-run them; pytest isn't installed in this environment). The change is in the Agent UI chat backend, a user-visible surface, and the PR shows unit tests but no second-turn run against the real route. A /api/chat call with stream=false issued after a streaming turn, before and after, would show the actual symptom is gone; the rendered screenshot can reasonably defer to the strix-halo lane.

🔍 Technical details

🟡 The non-streaming path is left with no cancellation mechanism at all

src/gaia/ui/_chat_helpers.py:1590-1591 sets agent._cancel_event = None and agent.console = SilentConsole(). SilentConsole has no cancelled attribute, so Agent._console_cancelled() (agent.py:5404) is permanently False, and the step-boundary check at agent.py:5663 reads a None event. The asyncio.wait_for(..., timeout=600.0) at _chat_helpers.py:1809 abandons the executor thread without signalling it — the caller gets the "took too long" string while the agent thread runs on unbounded.

The minimal version:

            agent = cached_agent
            # A prior streaming turn leaves its fired cancel event and dead SSE console.
            agent._cancel_event = threading.Event()
            agent.console = SilentConsole()

…paired with agent._cancel_event.set() in the except asyncio.TimeoutError handler at _chat_helpers.py:1813 (the agent has to be reachable there — a nonlocal/holder, or hoisting the lookup).

Same shape in src/gaia/ui/agent_loop.py:396: after asyncio.TimeoutError the handler sets sse_handler.cancelled (agent_loop.py:457), which process_query only observes inside the token loop (agent.py:6080), never at a step boundary. A fresh event set alongside sse_handler.cancelled.set() would make _TICK_TIMEOUT actually bound the tick.

Both are pre-existing on the fresh-agent path, so this is a "while you're here" rather than a regression — but this PR is the place where _cancel_event lifecycle is now being managed.

🟡 Mutating a shared cached agent can disarm an in-flight turn

_agent_cache is one agent per session (_chat_helpers.py:201) and _agent_cache_lock guards only the dict, not the turn. AgentLoop._execute_tick has no busy check — _get_active_session() (agent_loop.py:308) just picks the most recently updated non-private session — so a tick can fire while a user's streaming turn is mid-flight on that same session. agent_loop.py:396 then nulls the event that _cleanup_stream's cancel_event.set() (_chat_helpers.py:1873) relies on, so producer.join(timeout=5.0) leaves a zombie.

The console swap at agent_loop.py:397 is pre-existing; the _cancel_event null is new, and _chat_helpers.py:1591 is a newly added console swap on the non-streaming path. Not worth blocking on, but a real window.

🟢 Prefer agent._create_console() over a hardcoded SilentConsole()

The cache is keyed by agent_type and also holds registry-created agents (_chat_helpers.py:1726), which may not be silent_mode=True and may override _create_console for a domain-specific console (the base declares that as an extension point, agent.py:1675-1685). Reconstructing the agent's own choice matches what Agent.__init__ does at agent.py:1321 and avoids discarding an override:

            agent = cached_agent
            # A prior streaming turn leaves its fired cancel event and dead SSE console.
            agent._cancel_event = None
            agent.console = agent._create_console()

(Drops the need for the local SilentConsole import too.) For ChatAgent this is byte-identical to the current line — silent_mode=True, output_dir unset → SilentConsole(silence_final_answer=False).

Strengths

  • The tests assert observable behaviour — what process_query sees when it runs — rather than the assignments themselves, so they'd still catch the bug if the fix were rewritten to use a fresh unset event. _RecordingAgent.__init__ seeds exactly the state a finished streaming turn leaves behind, which makes the reproduction self-documenting.
  • The module docstring names the issue and the mechanism in two sentences; test_agent_loop_tick_cache_hit_gets_clear_cancel explains the gaia_agent_chat stub with a comment on why a cache hit never touches it.
  • Both reuse sites were fixed together rather than just the one in the bug report, and the streaming path (_chat_helpers.py:2328) was correctly left alone since it reassigns a live event every turn.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit e6e32a8 Sep 25, 2026
29 of 30 checks passed
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 25, 2026
…amd#4275)

Stacked on amd#4274 — merge that first. Until then this diff also shows
that PR's commit; the change here is the top commit.

Background goal ticks used a session's cached agent without the session
lock. On a `gaia` session the tick evicted the user's agent and
disconnected its MCP tools, and on a `chat` session it could run
alongside the user's next turn on the same agent. Now ticks take the
session lock and chat semaphore, skip a busy session, and look up the
agent by the session's real agent type, model, and device, the same way
the chat path does.

- **Design choice: skip, don't wait.** A busy session is skipped, and
the next idle tick picks it up. The tick checks the lock without
queueing on it, because a queued tick would take the lock ahead of the
user's next message and turn it into a 409.
- **Followup grace.** A user-message followup is queued while the turn
that triggered it still holds the session. So it waits up to 10 s for
that turn to let go, matching `docs/spec/autonomous-agent-mode.md` §17.
Without the wait, followups after streaming turns would almost always be
skipped.
- **Side effect.** While a tick runs, the user's next message on that
session gets the existing 409 "already in progress" instead of racing
the tick on the same agent.

## Test plan
- [x] `python -m pytest
tests/unit/chat/ui/test_agent_loop_session_lock.py -q`: the 5 core tests
fail before the fix; all 7 pass after
- [x] `python -m pytest tests/unit/chat/ui -q`: 1030 passed
- [x] `python util/lint.py --black --isort` + pylint (errors-only
config) on changed files: clean

Fixes amd#4197

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…md#4276)

Stacked on amd#4275 — merge that first (it is itself stacked on amd#4274).
Until then this diff also shows those commits; the change here is the
top commit.

When an Agent UI turn timed out, the session lock was released while the
old worker thread was still running tools on the same cached agent, so
the next turn could run concurrently with it. Now a timed-out
non-streaming turn signals the agent to stop and waits for its thread
before it returns. The streaming cleanup also waits for the producer
thread, so the session lock, chat semaphore, and run registration stay
held until the worker is actually gone.

- **Goal ticks too.** amd#4275 gave ticks the session lock, so a timed-out
tick now also stops its agent and waits for the worker before releasing
it.
- **No more event-loop stall.** The streaming cleanup used to block the
event loop for up to 5 s in `producer.join`. The wait now runs off the
loop.
- **Trade-off.** A turn that ignores its cancel signal now keeps its
session busy until the worker exits, not just until the 600 s timeout.
The agent checks for cancel at every step boundary, and per-tool
timeouts bound each step.

## Test plan
- [x] `python -m pytest tests/unit/chat/ui/test_run_outlives_timeout.py
-q`: all 3 fail before the fix, all pass after
- [x] `python -m pytest tests/unit/chat/ui -q`: 1033 passed
- [x] `python -m pytest
tests/unit/agents/test_console_tool_confirmation.py
tests/integration/test_chat_ui_integration.py
tests/integration/eval/test_behavior_e2e.py -q`: 155 passed, 1 skipped
- [x] `python util/lint.py --black --isort` + pylint (errors-only
config) on changed files: clean

Fixes amd#4198

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…md#4277)

Stacked on amd#4276 — merge that first (stack: amd#4274 → amd#4275 → amd#4276).
Until then this diff also shows those commits; the change here is the
top commit.

Deleting a session, switching its agent, device, or mail provider, or
detaching a document mid-turn disconnected the running agent's MCP
tools. The turn's final save then failed against the deleted session
row, and the error was swallowed. Now a delete stops the running turn
and waits for it to finish before removing anything. The other changes
get a 409 while a turn is running.

- **Design choice: two answers, each following its endpoint's existing
pattern.**
- DELETE already cancelled the run, so it keeps doing that and then
waits on the session lock before deleting and evicting. Every turn and
goal tick holds that lock for its whole run. The sidebar deletes
optimistically, so the wait is invisible to the user. A 409 here would
make a deleted session reappear on the next poll.
- PUT (agent/device/mail provider) and document detach return 409, the
same answer `/api/chat/send` gives for a busy session. Renames are still
accepted, because auto-titling renames sessions mid-run.
- **Not in this PR: amd#4140.** The email-relay gap is still open. Until it
lands, deleting mid-email-turn waits for the relay to return (worst case
its 300 s read timeout) instead of racing it.
- **Docs.** The endpoint docs in `docs/sdk/sdks/agent-ui.mdx` now
describe the 409 and the wait.

## Test plan
- [x] `python -m pytest
tests/unit/chat/ui/test_session_mutation_during_run.py -q`: 7 failed
before the fix (the rename test passed, as it should); all 8 pass after
- [x] `python -m pytest tests/unit/chat/ui -q`: 1041 passed
- [x] `python -m pytest tests/unit/test_multi_device_wiring.py
tests/unit/test_chat_inline_web_ssrf.py
tests/unit/eval/test_scenario_agent_types.py
tests/unit/eval/test_scenario_agent_provenance.py
tests/integration/test_folder_indexing.py
tests/integration/test_chat_ui_integration.py -q` (plus the other
session-endpoint neighbours): 330 passed, 2 skipped
- [x] `python util/lint.py --black --isort` + pylint (errors-only
config) on changed files: clean
- [ ] Manual: in `gaia chat --ui`, delete a session while a turn is
streaming. It disappears and doesn't come back, and the server log has
no "Chat streaming error"

Fixes amd#4199

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(ui): cached agent keeps a fired cancel signal, so later non-streaming turns stop at step 0

2 participants