Repository navigation
fix(ui): keep a session busy until its timed-out worker thread exits - #4276
Conversation
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
Background goal ticks used a session's cached agent without the session lock or chat semaphore, and looked it up as a "chat" agent with the raw model id. On a gaia session that evicted the user's agent and disconnected its MCP tools; on a chat session the tick could run alongside the user's next turn on the same agent. Ticks now take the session lock and chat semaphore, skip the session while it is busy (never queueing on the lock, so they can't stall the user's next message), and resolve agent type, model, and device the way the chat path does. A user-message followup waits up to 10 s for the turn that enqueued it to release the session, as docs/spec/autonomous-agent-mode.md section 17 describes. Fixes amd#4197
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. Non-streaming turns and goal ticks now signal the agent's cancel event on timeout and wait for the worker thread before returning, so the session lock and chat semaphore stay held until it is gone. The streaming cleanup waits for the producer thread the same way (off the event loop, replacing a 5 s join that blocked it), so the run stays registered and the lock held until the producer exits. Fixes amd#4198
|
Verdict: Request changes — one fixable hole in the very invariant this PR establishes, plus a trade-off the stack introduces that needs a maintainer's call. The change is right in shape: a timed-out chat turn now tells its agent to stop and keeps the session reserved until the worker thread is actually gone, so the next turn can't run concurrently on the same cached agent. The streaming path also stops blocking the event loop while it waits. What needs fixing
Real-world evidenceN/A — no evidence bundle was produced for this run, so the verdict rests on static review plus the author's reported test results. This is an Agent-UI-backed change: the listed unit and integration runs gate the concurrency logic, not the surface, and no Agent UI screenshot or HTTP-route capture is attached. Worth adding the 🔍 Technical detailsNote: the PR is stacked (top commit Issues🟡
No production caller cancels 🟡 A goal tick holds
Taking the lock is the right fix for the shared-agent corruption; what's missing is preemption. Two options worth a maintainer's call: register the tick as a 🟡 The extended wait after a timeout is unbounded and unlogged ( The streaming path logs before it waits without a bound; the non-streaming path doesn't. A turn stuck past the timeout now produces a request that never returns, with no log line distinguishing it from a slow one. The trade-off is deliberate, but make it observable: Nits🟢 The unbounded join occupies a thread from the same pool as chat workers ( 🟢 The tick's cache-miss path still builds a Strengths
|
Fixes a duplicate device= keyword argument the auto-merge produced: this branch and main both added a device= line to ChatAgentConfig(...) at slightly different positions, so git's 3-way merge kept both instead of flagging a conflict -- a SyntaxError that broke collection for every test importing gaia.ui.agent_loop. Also folds in main's cancel-lock handling alongside this branch's own worker-exit fix.
Same duplicate device= keyword the sibling branch's merge produced (this PR and amd#4276 both independently added a device= line to ChatAgentConfig, at different diff positions, so git kept both instead of flagging a conflict). Also combines this branch's cancel_event assignment with main's result_holder capture.
|
🟡 The The new push correctly makes The previous review's suggested fix was to move the joins outside the guard so re-entry always waits. That change wasn't made. The new test ( 🔍 Technical details
async def _cleanup_stream():
nonlocal cleanup_done
if not cleanup_done:
cleanup_done = True
cancel_event.set()
if sse_handler is not None:
sse_handler.cancelled.set()
sse_handler.close_active_relay_response()
_active_sse_handlers.pop(session_id, None)
# Always re-waited: an interrupted join must not leave the producer
# alive after the run (and so the session lock) is released.
if producer is not None:
await asyncio.to_thread(producer.join, 5.0)
if producer.is_alive():
logger.warning(
"Producer thread still running after stream ended; "
"holding the session until it exits"
)
await asyncio.to_thread(producer.join) |
…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]>
Stacked on #4275 — merge that first (it is itself stacked on #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.
producer.join. The wait now runs off the loop.Test plan
python -m pytest tests/unit/chat/ui/test_run_outlives_timeout.py -q: all 3 fail before the fix, all pass afterpython -m pytest tests/unit/chat/ui -q: 1033 passedpython -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 skippedpython util/lint.py --black --isort+ pylint (errors-only config) on changed files: cleanFixes #4198