Repository navigation
fix(ui): one chat no longer holds the model away from every other chat - #5337
Conversation
…tification settings
Chats waiting on a permission or a question now move to a "Needs you" group at the top of the list, every row carries a running / waiting / done / failed dot with unread and pin, and eval and scheduled runs sit behind a filter. A second chat sent during a turn now waits visibly ("Waiting for the GPU — 1st in line") and runs after, instead of blocking silently and failing with 429 after 60 s. Alerts arrive with the notification panel closed, can be set per event, and the desktop app stays awake while a chat works.
- Backend: a FIFO turn queue replaces the hidden one-slot semaphore. Streamed turns wait inside their detached run and announce their place; Stop withdraws a waiting turn. /api/chat/active reports queued chats and chats paused on the user. Sessions gain pinned, unread, last_run_status and kind, with pin and mark-read endpoints.
- Agent UI: Needs you / Pinned groups, status dots, unread, pin, eval/scheduled filter; Settings > Notifications with banner / badge / off per event, sound, taskbar flash, keep-awake and a battery floor.
- Desktop app: Electron notifications are subscribed once at app level with cleanup (amd#4813), OS banners open their chat, the taskbar flashes when unfocused, the tray badge counts chats that need you, and a powerSaveBlocker holds off idle sleep during a turn.
Closes amd#5221
Closes amd#5226
Closes amd#4813
…one idle-friendly active-runs poll A chat waiting for approval lost its prompt and Stop button when you left it for another chat that was still streaming, or reloaded, so it could not be answered and every chat queued behind it waited forever. Re-attaching now follows state instead of firing once: whenever the server reports the chat running and this view isn't streaming it, the view re-attaches and the replay brings the prompt back. A replayed prompt no longer adds a second copy to the bell, and a run that finishes between the poll and the attach closes cleanly instead of showing an error. The sidebar now loads every chat by paging through /api/sessions, so chats past the first 50 come back and the hidden-runs count covers them all. /api/chat/active is polled from one shared poller: every second while a chat runs, backing off to every 15 s when idle, and waking at once when a turn starts or the window regains focus. Closes amd#5247 Closes amd#5254 Closes amd#5256
"Show 1 eval and scheduled run" put developer jargon in front of people who only ever schedule tasks.
A queued turn's stream went silent between position changes, so a client watching for a dead stream had to special-case queued chats. While waiting, the run now repeats its "Waiting for the GPU — Nth in line" status every 10 s with the current position and how long it has waited (queue_waited_s), and stops as soon as the turn gets the GPU.
A permission prompt left unanswered in a background chat blocked every other chat for up to 10 minutes, Stop could not end a turn whose agent thread was stuck, a non-streamed message waited 60 s and got a 429 without being saved, and scheduled runs and autonomous ticks bypassed the line or held it after timing out. - A turn waiting on the user steps out of the GPU line and comes back at its front once answered (TurnSlot). - Stop ends the turn within 5 s even when the agent thread is stuck; the model is freed and only that chat stays busy, with a 409 that says why, until its thread exits. - A non-streamed message is saved first and waits in line; no 429. - Scheduled runs wait in the same line; a timed-out run is told to stop and the next one refuses to start while a stuck one is still running. - A timed-out autonomous tick frees the model after a bounded grace. - A turn waiting on the start-up warm-up says what it is waiting on, and Stop ends that wait. - Agent construction and tool re-registration take tool_registry_lock, the one guard for the process-global tool registry. - Ticks and scheduled runs use their own threads, not the shared executor the SSE stream loop needs.
…he tab open Review follow-ups on the turn-slot change: - With the chat still open, Stop on a stuck turn released the chat at once, so a new turn could start on an agent the old thread still drove. The chat now stays busy until that thread exits, whichever way the stream ends. - Waiting for another chat's agent setup gives the model to other chats and gives up after 2 minutes with a reason, instead of waiting forever. - A turn that ended can't retake the model through a late come-back, and a turn that can't hand the model back is stopped, not left running without it. - Waiting for a stuck thread polls instead of holding a shared executor worker; a non-streamed message whose client left gets its "Cancelled." - The turn tests no longer wait on a dead /stats port, which made them slow and flaky on Windows.
A streamed turn waiting for the GPU sent only its place-in-line status, so a client watching for silence could not tell it from a dead stream. It now sends the same keepalive frame the stream loop does, every 5 s.
… run's slot Review follow-ups on the turn-slot change: - While a turn waited on a permission prompt, another chat could unload or reload the model. Once the turn has its place back, it now runs the pre-flight again; if the model can't be loaded, the turn ends with the reason before the approved tool runs. - A timed-out scheduled run freed the model after 10 s while its agent could still be generating on the GPU. Its agent is now stopped, a streaming reply included, and the run keeps its place until the thread has actually stopped; chats wait in line and see that they wait. - On server shutdown a running tick keeps its session until its thread stops. A long wait for a stopped chat's thread is logged. The warm-up wait no longer sends the turn anyway after 300 s: it fails with the reason. agent_threads uses gaia.logger.
|
Verdict: Request changes This replaces the single chat semaphore with a visible turn queue. A turn waiting on a permission prompt or question now gives up the model, Stop frees the model within 5 s even if the agent thread is stuck, and non-streamed messages, scheduled runs and autonomous ticks wait in line instead of failing or piling up. The design holds up and the tests cover the hard races. One lock-ordering gap can still stall another chat for two minutes and then fail it with a misleading error.
Real-world evidenceN/A: no evidence bundle was produced for this run, so this verdict rests on static review alone. The Agent UI queue and "needs you" states, and the Stop-on-stuck-thread path, have not been exercised live here. 🔍 Technical details🟡 Setup lock held across In
Sequence: streamed turn B finds the lock held (by the warm-up or a stuck stopped thread) and steps away. A non-streamed turn D takes the model. The lock frees and B takes it. B blocks in The fix is to get back on the model before taking the lock: after a contended wait, release the lock, 🟢 Warm-up timeout remedy ( 🟢 Known gap acknowledged: a lingering autonomous tick returns the generic "already in progress" 409 rather than "still stopping". That's fine as documented, but a follow-up issue would keep it from being forgotten. Strengths
|
…odel call runs Second-round review follow-ups on the turn-slot change: - A timed-out autonomous tick freed the GPU 10 s after it was told to stop, while its model call could still be generating; and the scheduled-run fix held the GPU with no limit, so a run stuck in a tool locked every chat out. Both now share one rule: after the stop, the run keeps the GPU while it may be in a model call (the call ends at the next token once its console is cancelled) and frees it as soon as it is inside a tool. Told to stop, it calls the model no more. - Scheduled runs get a background-mode SSE console, which reports running tools and denies gated ones, as before. - Tests cover a tick stuck in a tool, a tick mid model call, and a tick cancelled at shutdown.
The real daemon spawn was refused only inside each test, so a thread a test left running (an app's start-up job, a worker) could reach it between tests and leave a daemon behind after the session; unit runs from this branch did, about every hour or two. The spawn is now refused for the whole session, and the session fails naming the test that was running when a stray attempt came. The scheduled-run tests now drive the scheduler's executor directly instead of starting the whole app, whose start-up jobs outlived them.
|
🟡 A timed-out autonomous tick that hangs before it calls a tool now holds the model forever, and every chat waits in line behind it. The "free the model once it's inside a tool" rule assumes a stopped run is either in a model call or in a tool. A tick stuck while building its agent (for example on an MCP server that does not answer, the case the setup-lock timeout message names) is in neither, so it never gives the model back. Before this push it was freed 10 s after the stop. Scheduled runs share the same blind spot. Fix: keep an upper bound on the wait, or treat "not in a model call" as the release condition rather than "in a tool". 🔍 Technical details
A deadline that frees the slot after N seconds (or an explicit "in model call" flag set around the LLM request, used as the hold condition) restores the bound. A test with a worker blocked before any tool, where the tick times out and the queue must still hand the model on, would pin it. |
A chat that gave the model up while it waited for the agent-setup lock took the lock, then waited to get the model back, while a tick, scheduled run or non-streamed turn held the model and waited for that lock: neither could move. It now releases the lock before waiting for the model, then tries the lock again, giving the model up again if the lock is taken. Also tests that a timed-out scheduled run cancels its console, which is what ends a streaming reply mid-token.
A chat that gave the model up while it waited for the agent-setup lock kept one deadline across the whole wait, including its time in line for the model. Back from a long queue, one brief collision on the lock failed it with 'another chat has been setting up its agent for over 120s'. The limit now restarts once the chat has its turn on the model again.
… starts Its 0.1 s no-progress limit could fire before the worker reached the agent; with the pre-flight's stop check (amd#5336) the turn then ended early and the test waited on an agent that never started, about 1 run in 4. The limit now drops to 0.1 s only once the agent is running.
A timed-out autonomous tick or scheduled run that hung before it called a tool (stuck building its agent on an MCP server that never answers, or in a model request that never yields a token) kept its place on the model with no limit, so every chat waited behind it. It now gives the model up 60 s after the stop wherever it is stuck; a model call that is still generating ends at its next token well inside that.
Before: two Agent UI chats on different models swapped models on every turn, and starting a turn unloaded models that other apps sharing Lemonade were answering with. When GAIA couldn't get the model (lease timeout, not enough memory, server not answering), it showed a warning and answered anyway, so Lemonade loaded the model itself and skipped the free-memory check. Settings → Load and the auto-title went straight to Lemonade with no lease or lock, so either could evict a model mid-answer, and a title could load a second model. After: GAIA only ever unloads models it loaded itself, and only to make room. A turn that can't get its model fails and says why. Titles run on the side slot and never load anything. Load asks before interrupting a chat that's answering. - **Shared server, shared rules.** Settings → Load, the post-download auto-load and titles take the same lease and lock a chat turn does, in the same order. - **Stop is honoured before a load.** A turn stopped while waiting for the model slot or another chat's load ends there: no load, no query. The wait for another chat's load is shown. - **A restart still knows GAIA's own models.** Chat models already on GAIA's own Lemonade at startup count as its own, so they can be unloaded to make room; on a server you run, nothing is. Reproduced by `tests/unit/chat/ui/test_model_slot_discipline.py`; each case fails on main and passes here, including a whole turn stopped during the pre-flight. Overlaps amd#5241 and amd#5275 (both edit `_chat_helpers.py`; different functions). Builds on the amd#4772 discussion without fixing amd#4772 itself: the title still uses the model it's given, but it can no longer load it. **Merging with amd#5328:** whichever of the two lands second also carries, as agreed with that PR's author: - `except LeaseWaitCancelled` (quiet) in `_preflight_load`, ahead of its catch-all; - the chat title's wait for the model wrapped in `lease_wait_limit(30)`, with the 504 logged at info and the title skipped that turn, plus a test that it gives up. - keep this PR's own raises of `InsufficientMemoryError` and `ModelInUseError` ahead of that clause. **Merging with amd#5337:** the two PRs conflict in one hunk of `_chat_helpers.py` next to `model_load_lock`. Both sides only add code there, so keep both. I ran a trial merge of the two locally: the UI suite and amd#5337's non-streamed timeout test passed 8 times out of 8. That test was racy with amd#5336's stop check, and amd#5337 now fixes it. ## Test plan - [x] `pytest tests/unit/chat/ui tests/unit/test_chat_preflight.py tests/unit/test_model_server_info.py tests/unit/test_users_lemonade_untouched.py tests/unit/test_ui_warmup.py tests/unit/test_broker_wiring.py`: all pass - [x] `npx vitest run` in `src/gaia/apps/webui`: all pass, new `api.loadModel.test.ts` - [x] `python util/lint.py --black --isort --pylint --flake8` - [ ] Live: two chats on two models that both fit, and confirm neither is unloaded between turns <details> <summary>🔍 Technical details</summary> - `_maybe_load_expected_model` no longer unloads other resident chat models. On `InsufficientMemoryError` it unloads only models in `_models_loaded_here` (pre-flight and Settings loads record there, with names normalized), says so in a status event, and loads once more. Otherwise it raises. - Exceptions now raised instead of a warning status: `BrokerUnavailableError` (with the model and what to check), `InsufficientMemoryError` (unchanged text), and `RuntimeError` for anything else, including a non-200 `/health`. The streaming and non-streamed paths both show the reason. The non-streamed path used to substitute "make sure Lemonade is running" for every unclassified error. - `_maybe_load_expected_model` wraps `_preflight_load`: any exception raised while the turn's Stop flag or its own cancel event is set is read as the Stop. That covers turns that pass those in, which the streamed turn does. A non-streamed turn's Stop reaches the wait only through amd#5328's `interactive_turn(cancel=...)`, so there only the `except LeaseWaitCancelled` clause above keeps it quiet. amd#5328's `test_stop_during_a_queued_preflight_stays_quiet_on_the_non_streaming_path` guards that. - A failed Settings or post-download load shows in `/api/system/status` `probe_warnings` until a load succeeds. - `model_load_lock` is taken with `_take_model_load_lock` (polls, shows status, returns on Stop) after the lease. `_load_through_the_slot` in `routers/system.py` uses the same lease-then-lock order. - Title: `LemonadeClient.chat_completions` under one background-priority `model_lease` spanning the residency check and the call; `id_slot=SIDE_SLOT` when the model has two slots; `auto_download=False`. - Ownership: the UI keeps a record of the models it loaded (`<GAIA home>/ui/loaded_models.json`, written whole under a lock): pre-flight and Settings loads, and any load its own agents make (a `LemonadeClient` load listener). Models Lemonade no longer has loaded drop out of it. A same-name copy at too small a window is reloaded only if the UI loaded it or it is an auto-load (Lemonade's 4096 default or the supervisor's profile window); otherwise `ModelInUseError` says another app has it. - `/api/system/load-model` gains `force`. Without it the endpoint returns 409 while any run is active. `loadModelAskingFirst` turns that into a `confirm()` in Settings. The API schema and types are regenerated. - Updated tests that pinned the old behaviour: unload-before-load (amd#1382's double-load case is now covered by the free-memory check), swallowed pre-flight failures, and raw-HTTP titles. - Not changed here: the retry-on-error path that re-runs the whole query is amd#5338. - LLM-affecting? Error surfacing only; prompts and tools are unchanged. Categories to watch on the next RC: `rag_quality`, `gaia_core`. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
Before: every SSE frame a chat turn sent stayed in that run's replay buffer: each text chunk padded to 512 bytes, plus a keepalive every 5 seconds. A long turn grew the buffer without limit, and every time the user switched back to the chat, the whole thing was replayed. After: the buffer keeps only what a re-attaching client needs to rebuild the reply, so a normal reply stays at tens of kilobytes. It's capped at 8 MB; past that the oldest progress is trimmed behind a note that says so. Reproduced by `tests/unit/chat/ui/test_replay_buffer_bounds.py`: on main, a 3,000-chunk reply keeps all 3,601 frames and nothing caps the size. Here it keeps about 600 merged frames and replays the identical answer text. Overlaps amd#5242 and amd#5337, which also edit `run_manager.py` (`Run.__init__`, `cancel()`), in different lines. ## Test plan - [x] `pytest tests/unit/chat/ui`: all pass - [x] `python util/lint.py --black --isort --pylint --flake8 --test-lanes` <details> <summary>🔍 Technical details</summary> - `Run._record` drops non-`data:` frames (keepalives, padding comments), stores frames unpadded, merges consecutive `{"type","content"}`-only chunks, and replaces a `status: working` that directly follows another. That matches how ChatView consolidates them. - `subscribe()` pads replayed frames back to 512 bytes, the Chromium flush rule the producer already follows. - Live subscribers still get every frame exactly as emitted; only the replay copy changes. - Not LLM-affecting. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
amd#5355) `test_rate_limit_wait_is_capped` failed at random, most often on macOS CI (e.g. on amd#5337). The `own_sleeps` fixture patched `time.sleep` for every module. When logging on the test's thread waited on the log-rotation file lock, that lock's 5 ms retry landed in the list. The fixture now records only sleeps called from `gaia.agents.base.agent`, the code under test. Reproduced by the new `test_own_sleeps_ignores_sleeps_from_other_code_on_this_thread`: it fails with the old fixture and passes here. ## Test plan - [x] `pytest tests/unit/agents/test_loop_guard_correction.py`: 42 passed - [x] `python util/lint.py --black --isort --pylint --flake8`
Keep main's stream reconnect alongside the re-attach gate: a lost stream re-attaches first, and only a real end stamps streamEndedAt. The new sidebar pulse takes the motion tokens, and the stream-reliability test seeds a fresh active-runs poll as the re-attach gate requires.
A chat answered through the non-streamed API path never got a status dot or an unread mark, because only the streamed run recorded its outcome. It now records done or failed the same way; a turn refused before it ran (429/409) records nothing. Also drops the removed chat_semaphore from five test fixtures.
# Conflicts: # src/gaia/apps/webui/src/services/api.ts
With main merged, the session paging and pin/read calls take api.ts to 51.4 KB, past the 50 KB size check. Raise it to 56 KB and say to split the module next time.
… into wf3-5337 # Conflicts: # src/gaia/ui/_chat_helpers.py # src/gaia/ui/warmup.py
On 3.10 concurrent.futures.TimeoutError is not the builtin TimeoutError, so a hand-back the event loop never ran escaped the confirm/question wait instead of stopping the turn. TurnSlot now raises the builtin with the reason. The plain-API "refused before it ran" test from the chat-list work assumed the non-streamed 429, which this branch replaces with waiting in line; it now checks that a message stopped while in line records no outcome.
…waits in line Once answered, a turn whose model was taken by another chat waits in line to get back on it, and the prompt stayed registered until then, so the chat list kept showing it as needing the user. waiting_on() now ignores prompts that have an answer.
|
Verdict: Approve with suggestions The model is now held only while a turn is actually using it. A chat waiting on a permission prompt or a question steps out of line and comes back at the front once answered. Stop frees the model within 5 s even when the agent thread is stuck. A busy model queues a non-streamed message instead of returning a 429. Scheduled runs and autonomous ticks now wait in the same line. I traced the hand-back, cancel and stuck-thread paths and didn't find a blocking bug. Two small things worth a follow-up:
Real-world evidenceN/A here: no evidence bundle was produced for this run, and I couldn't run the tests on this runner (pytest isn't installed). The PR description has a live two-chat run against the Agent UI server (Gemma-4-E4B on Lemonade). It shows the 🔍 Technical details🟢 Minor
Checked and fine: the queue's cancel-after-handover branch releases the slot when Strengths
|
…ession A shutdown cancel that landed while a timed-out tick waited for its model call to stop skipped recording the still-running thread, so the session was released under it. Both waits now share one cancel handler. Also drops a monkeypatch of a setting that no longer exists from two tick tests, and notes that a tool which calls the model itself can overlap the next turn after a stop.
Main's amd#5337 saves a non-streamed question before it waits for the model. That save now opens the turn, and every way the wait can end closes it: a Stop or a client that left saves "Cancelled." as the turn's reply, and any other failure drops the marker. The streamed run keeps its turn journal through main's turn slot.
…ming them (amd#5409) Two unit tests failed whenever a CI runner was busy, so unrelated PRs went red (the envelope test on amd#5282 and amd#5337; the ping test timed out on loaded machines). Before: the envelope "not quadratic" test raced a 5 s wall clock, and the ping test needed a ping to land in a 0.5 s window that the stub's own start-up ate into. After: both assert what they claim directly, so they pass or fail the same way on any machine. Under a 40-process CPU burn they went from 16/16 and 10/16 failing to 0 of 120. The third test from the report, `test_turn_waiting_on_the_user_lets_other_chats_run`, was already fixed on main by amd#5396. Both of its CI failures predate that fix, and it passed 325/325 under the same burn. <details> <summary>🔍 Technical details</summary> - **Envelope test:** the test now counts the characters `_json_object_end` examines. A 400,089-char envelope scans exactly 400,089 characters. A per-token rescan scans ~2e10 and fails the `≤ 2×len` bound; I checked this on a 20 KB envelope, where a rescan was 2,500× over. - **Ping test:** the stub is now warmed with a first request so its boot time sits outside the deadline window. The test spies `_write` and asserts the ping reply gets the same deadline as the request. If the product gives the ping reply a fresh `self.timeout`, the test fails deterministically. - **Not a product race:** the remaining superlinear cost in the envelope path is `self._stream_buffer += chunk` copying the held buffer per token. That is microseconds per token at real generation rates. - **Follow-ups:** other tests in `test_stdio_hung_server.py` also fail under heavy load. `test_redaction_stays_fast_on_dense_escapes` and `..._linear_on_long_non_ascii_secrets` use a `< 0.25 s` wall-clock assert. `test_a_server_that_misses_the_connect_deadline_is_stopped` and `test_a_timed_out_request_is_cancelled_on_the_server` read marker files before the stub writes them. </details> ## Test plan - [x] `pytest -p no:randomly --count 60 -n 8` on both fixed tests: 120/120 idle, 120/120 under a 40-process CPU burn (before: 16/16 and 10/16 failing under the same burn) - [x] Adversarial: dropping the scanner's resume or giving the ping reply a fresh timeout makes the respective test fail - [x] `test_sse_handler.py`, `test_stdio_hung_server.py`, `test_turn_slot_reliability.py` in full: 521 passed - [x] `python util/lint.py --black --isort`
Before: if the Agent UI backend restarted, crashed or shut down mid-answer, the question sat in the chat with no reply and no explanation, forever, and a document caught mid-index read "indexing" forever. After: the next start shows the reply as far as it got, which tools it had started, then "This answer was interrupted when GAIA closed. Send again to retry.", and the document shows **Failed** with **Retry**. A scheduled run cut short says the same in its chat. Nothing is re-run on its own, since a half-finished turn may already have run tools. Lands after v0.25.0. Reproduced by `tests/unit/chat/ui/test_restart_recovery.py`: on main, `test_app_start_runs_the_recovery` finds no reply after a restart and the document still "indexing"; the other cases fail for want of the turn marker. All pass here. ## Test plan - [x] `pytest tests/unit/chat/ui/test_restart_recovery.py` (22 cases): streamed, non-streamed and scheduled turns cut off; a shutdown mid-turn; a turn that ends on an error; a policy block saved mid-turn; two servers with turns in one chat; another server's reply not ending this turn; the 30 s sweep closing a turn once its server exits; tools named in the recovered reply; a clock step on Linux; indexing cut off - [x] The two-server case on the previous head (6940982), with the reviewer's `two_servers.py`: B's question got A's streamed text plus the notice. Here each turn keeps its own text. - [x] `pytest tests/unit/chat/ui tests/unit/test_chat_preflight.py tests/unit/test_ui_warmup.py tests/integration/test_chat_ui_integration.py tests/unit/test_scheduler.py tests/unit/test_scheduler_api.py tests/integration/test_scheduler_e2e.py` with an isolated `GAIA_HOME`: all pass except `test_issue_841_custom_python_agent_model_id_respected` and `test_custom_agent_model_id_honored_through_api` (they patch `HOME`, and fail the same way on main whenever `GAIA_HOME` is set), and three folder-indexing tests that fail on main too under `-n 6` and pass run on their own - [x] `python util/lint.py --black --isort --pylint --flake8 --test-lanes` - [x] Live, with Gemma 4 E4B on Lemonade and the built web UI against a fresh `GAIA_HOME`: force-killed the backend mid-answer (145 chunks in) and mid-index (6.2 MB file), restarted it, and reopened the chat. The reply shows its streamed text plus the interrupted notice, the chat is marked failed and unread, and the document shows Failed / Retry (screenshots in the PR comments). Not run through the desktop app's own Quit. <details> <summary>🔍 Technical details</summary> - `unfinished_turns`: one row per question (`question_id` primary key, cascading from the message), written with the question in one transaction (`begin_turn`). `TurnJournal` saves the cleaned streamed text and the tools started every 2 s into this process's own row. Saving the reply (`add_message`/`upsert_message(ends_turn=True)`) deletes the row in the same transaction, so a row left behind is always a turn that never saved a reply; there is no "is there a later assistant message" guess. - Every update and delete is scoped to the row's owner. Another server closes a row only once its owner has exited (`recover_interrupted_work`, at `create_app` and every 30 s). - An owner is `pid:start:token` (`gaia.utils.process_owner`, shared with amd#5390's session history; both PRs add the identical file). On Linux, *start* is the boot id plus the start tick from `/proc/<pid>/stat`, so an NTP step can't make a live server look gone; on Windows and macOS it is `create_time()`, which those keep as recorded. - A turn that ends without saving a reply is closed with what it showed: its final `answer` as is, or its text plus the last error it showed, or else "This answer ended before GAIA could save a reply." A non-streamed turn whose request is cancelled gets "This answer was interrupted before it finished." - Scheduled runs: `_execute_task` saves the prompt with `begin_turn` and the reply with `ends_turn=True`. This touches a different part of `scheduler.py` from amd#5391. - Builds on amd#5316: after a restart its re-attach gets a 404 and loads the saved chat, which now holds the interrupted reply. - Merging with amd#5337: - It moves the non-streamed question save ahead of the turn queue. Save it with `question_id = db.begin_turn(sid, request.message)` there, and on its "Cancelled." replies use `add_message(..., ends_turn=True)`. - Its `except BaseException` branch should `db.discard_turn(question_id)` before releasing the lock. - If `journal.observe` moves into its `_emit`, keep the `TurnJournal` per run. Its `_RunOutcome`/`TurnCancelled` path must not close the turn on a shutdown cancel, or the next start can't report it. - Main's chat-list state (`last_run_status`, unread) is set by recovery too: a recovered turn's chat shows failed and unread. A turn withdrawn from the turn queue, or stopped by the spending limit, saves its reply as the turn's end. - Docs: a "PC sleeps" row in the Close/Quit table belongs with amd#5387, which also edits `agent-ui.mdx`, so expect a textual conflict there. - Not LLM-affecting: no prompt, tool or model change. A recovered reply enters the model's history cleaned the same way a finished one is. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
…er (amd#5404) The proactive Claude reviews were failing about half the time, and each failure was lost. The code and security audits failed 5 of the last 10 nights, and the doc walkthrough failed 4 of its last 5 runs. Running three audits every night used up both Claude accounts' weekly limit by mid-week, so most of those runs stopped before reviewing anything and blamed a missing file. The next run never went back for the missed work. Now one audit runs each night between 2 and 4am Pacific, so each audit runs every third night. Each run checks Claude is available before starting, and says plainly when it isn't. It picks up everything since its last successful run, starts from what merged since then, and checks against the bug types past audits missed. The dedup pass no longer re-files duplicates that were already closed: 34 of them were closed alongside this change. ## Test plan - [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py tests/unit/test_require_claude.py tests/unit/test_recent_changes.py tests/unit/test_miss_analysis.py tests/unit/test_claude_audit_workflow_contract.py tests/unit/test_closed_duplicates.py -q` passes (277 tests) - [ ] After merge: `gh workflow run claude-audit-rotation.yml -R amd/gaia -f dry_run=true`. The summary names tonight's audit and the next five nights, and nothing is dispatched. - [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia -f dry_run=true`. Check the preflight summary: the mode, a window reading "since this audit's last successful run", the Claude probe passing, and "Recent changes read first". At the end, "Dry run confirmed: no issue created". - [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide is walked, "Using bash.exe from …" appears, and the dry-run watermark step passes (it crashed before this change). - [ ] After merge: `gh workflow run claude-security-audit.yml -R amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and the SARIF uploads. - [ ] First scheduled night (10:13 UTC): the dispatched run is titled "… rotation night N", files at most what's new, and an issue it files carries `audit-cluster` / `audit-key` markers. <details> <summary>🔍 Technical details</summary> **Root causes (last ~2 weeks)** - Code and security audits, Oct 7/10/12/13/14/17: every lens returned `is_error` in under a second with "You've hit your weekly limit". The primary account ran out on Oct 10, the secondary on Oct 12–14, both on Oct 17. The account switch fired correctly; both accounts were spent. - Walkthrough Oct 12: same weekly limit on every guide, queued over 57 hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp` images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5, the executor step's `GITHUB_OUTPUT` got UTF-16 appended by `start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application Control blocked `LemonadeServer.exe` and the job landed on Strix Halo machines; both were fixed by the move to the `xsj-dispatch` pool on Oct 1. - The walkthrough's two dry-run steps had a literal `\n` mid-command, so `dry_run=true` always failed. **Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only 10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days since epoch mod 3 → code audit, security audit, doc walkthrough. The audits lost their own crons; `workflow_dispatch` still runs any of them on demand. Deep code sweep: whenever the last successful one is over 8 days old (every third turn, retried on the next turn if it fails). **Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass: the run checked out main 7 hours before amd#3310 merged. Three duplicate pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414, amd#5199/amd#4875). Backlog matching compared findings against issue titles only, so a same-section duplicate worded differently scored 0.05–0.15, below the 0.18 threshold. Now matching includes each audit issue's own markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their keys to the open canonical, so consolidating into amd#1077/amd#4331 does not trigger re-filing. Both syntheses share the `claude-audit-issue-filing` concurrency group. The security audit files to private code scanning, not issues, so it cannot duplicate the other two. **Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466 amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442 amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436 amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064, amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875. **Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%) closed an issue an audit filed first. Missed, by title: no deadline 90 (amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27 (amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951 amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which a static read rarely catches. Noise: of the audit issues closed as duplicate or not planned, 31 were duplicates of amd#1077, 12 of the test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a checklist per class and a "Don't report" list, and all three prompts read it at run time. The code audit gets a deterministic list of calls with no deadline. The security audit's semgrep run and worklist now cover TypeScript, Go, the installer and the workflows. `scripts/audit/miss_analysis.py` refreshes the evidence monthly. **Recent changes.** Each audit's first job writes `recent-changes.md`: first-parent commits since the commit its last successful run checked out, read from the run history, with PR title, a short body excerpt and the paths each touched, capped at 30 KB. If that commit is unknown it covers 3 days and says so. </details>
Builds on #5242's turn queue (now merged); the diff is this change alone.
Before: one chat could hold the model away from every other chat. A permission prompt left unanswered in a background tab blocked all chats for up to 10 minutes; Stop couldn't end a turn whose agent thread was stuck in a tool or MCP call; a non-streamed message waited 60 s, got a 429 and was never saved; scheduled runs skipped the line, and a timed-out one (or autonomous tick) kept running and piling up. After: a turn waiting on you steps out of line and comes back at the front once answered, Stop ends the turn and frees the model within 5 s, a busy model queues a message instead of dropping it, and scheduled runs and ticks wait their turn and stop when they time out.
Back from a prompt, the model is checked again. Another chat may have changed the loaded model while you were deciding; if it can't be loaded, the turn ends with the reason before the approved tool runs.
Waiting on you doesn't hold the GPU. Other chats run while a prompt or question is open; the answered turn goes ahead of chats that arrived meanwhile.
Stop really stops. If the agent thread can't see the Stop, the turn still ends and the model is freed; only that chat stays busy, with a 409 that says it's still stopping, until the thread exits.
Nothing silent. A turn waiting on the start-up warm-up says what it's waiting on, and Stop ends the wait. Agent setup that waits on another chat's setup says so, frees the model meanwhile, and fails with a reason after 2 minutes.
Reproduced by
tests/unit/chat/ui/test_turn_slot_reliability.py,test_scheduled_run_slot.pyandtest_agent_loop_session_lock.py::test_timed_out_tick_frees_the_model_while_its_thread_winds_down; they fail on #5242's branch and pass here.Overlaps #5242 (builds on it), #5241, #5239 and #5246 (all edit
_chat_helpers.py/routers/chat.py; no shared hunks with this change when I checked).Merging with #5336: the two PRs conflict in one hunk of
_chat_helpers.pynext tomodel_load_lock. Both sides only add code there, so keep both.test_non_streaming_timeout_holds_session_until_worker_exitsused to race #5336's pre-flight stop check (about 1 run in 4). It now lowers the no-progress limit only once the agent is running, and passed 8 of 8 in a local trial merge.Test plan
pytest tests/unit/chat/ui tests/unit/test_ui_warmup.py tests/unit/test_chat_preflight.py tests/unit/test_relay_*.py: all passpython util/lint.py --black --isort --pylint --flake8 --test-lanes/api/chat/activeat each step:{"session_ids":["A"],"queued":[],"awaiting_user":{"A":"permission"}}51without queuing:{"session_ids":["A","B"],"queued":[],"awaiting_user":{"A":"permission"}}{"session_ids":["A","B"],"queued":["A"],"awaiting_user":{}}, and A's stream showsWaiting for the GPU — 1st in line{"session_ids":[],"queued":[],"awaiting_user":{}}🔍 Technical details
TurnSlot(turn_queue.py) is a turn's handle on the queue.SSEOutputHandler._away_from_modelcallsstep_away()around the confirm/question waits andcome_back()to re-enter withfront=True. A Stop while waiting there withdraws it, and the handler marks the turn cancelled so it never calls the model unheld._stream_chat_implbreaks its event loop 5 s after Stop when the producer is still alive._cleanup_streamcloses the slot (a latecome_backcan't retake it) and records the thread in_stopping_sessions.routers/chat.pyreleases the session lock only when that thread exits, by polling, notto_thread(join), so it doesn't pin a shared-executor worker.tool_registry_lock(writing_tool_registry) now guards every agent build and_register_tools()call: UI turns, agent loop, scheduled runs and warm-up. These write the process-global_TOOL_REGISTRYand then snapshot it, so before this lock, a stopped turn's lingering thread could interleave with the next turn's build.cancelled) and keeps its turn-queue slot until its thread has stopped, so it never shares the GPU with the next turn; waiting chats see their place in line.: keepaliveevery 5 s.wait_for_warm_upno longer sends the turn anyway after 300 s; it raises with the reason.agent_threads.run_in_own_thread), not the default executor that the SSE loop polls with.