Skip to content

fix(ui): chat survives a busy, slow or dropped backend connection - #5316

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-webui-chat-stream
Oct 19, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-webui-chat-stream

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Before: a message the backend never started spun forever; a connection that went half-open (tunnel, laptop sleep, phone) or was cut (Wi-Fi switch, proxy reset, restart) froze the answer or ended in "send your message again", which then hit a 409 because the run was still alive; and a busy server ended in a raw HTTP 429: {"detail": ...}. After: the send is bounded and says it is waiting, a silent or cut stream reconnects on its own and shows "Reconnecting (attempt n of 3)", prompts the user already answered stay answered across a reconnect, an answer lost to a restart says so, and every one of these errors is a plain sentence with a next step. Lands after v0.25.0.

Reproduced by src/services/__tests__/api.streamReliability.test.ts and src/components/__tests__/ChatView.streamReliability.test.tsx: the API cases fail on main with the exact symptoms (no error after 30 s of silence, no end to an unanswered send, a cut stream reported as a generic network error, the 429 as a plain string), and pass here.

Test plan

  • npx vitest run in src/gaia/apps/webui: 896 passed; npx tsc --noEmit clean
  • api.streamReliability.test.ts (19) and ChatView.streamReliability.test.tsx (15): silent and cut streams re-attach with 0/3/10 s waits (about 13 s, to span a backend restart), Stop cancels a pending reconnect and closes a stopped turn locally, a replayed prompt keeps its answer, a prompt the run moved past is dismissed, the waiting notice clears when the backend answers, a 404 on re-attach loads the saved answer
  • Live, Vite :5319 against a fake backend with injected faults: a stream gone silent mid-answer was cut at 30.0 s and re-attached, and the whole answer appeared; a 429 read "GAIA is busy with another chat..."; a send never answered showed "Waiting for GAIA to start this answer…" at 3 s and a plain error at 90.0 s; a run lost to a "restart" read "The answer to your last message was lost..."
🔍 Technical details

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The chat view no longer hangs when the backend is busy, slow or silently disconnected. A send that never starts is cut off after 90 s with a plain message. A stream that goes quiet for 30 s reconnects on its own, up to 3 times, and the user sees it happening. A busy server now reads "GAIA is busy with another chat" instead of raw JSON. I found no blocking issues. The 30 s silence limit is safe because the backend sends a keepalive every ~5 s, and it sends it to re-attached viewers too, not only to the original sender.

Two small follow-ups, both optional:

  • How the code tells a "send never started" timeout apart from a "re-attach never answered" timeout is fragile. Give the error an explicit kind.
  • Nothing tests pressing Stop while a reconnect is in flight, or an attach that times out.

Real-world evidence

N/A here: no evidence bundle was produced for this run. This is an Agent-UI change, so the screenshot belongs to the strix-halo lane. The PR description includes a manual check (Vite against a fake backend with injected faults) that covers the stall-and-reconnect, 429, never-answered-send and lost-run cases. It also includes 19 new tests, and the 7 API tests among them fail on main. This verdict rests on static review plus that description. A before→after screenshot of the "Reconnecting (attempt n of 3)" status would still be good to add once the lane runs.

🔍 Technical details

What I checked

  • Keepalive reaches every subscriber. _stream_chat_impl yields : keepalive every 25 × 0.2 s. _run_chat_lifecycle pushes each yielded item through run.emit, which fans out to the /send subscriber and to /attach subscribers alike. So STREAM_IDLE_MS = 30_000 holds for both routes. Agent construction and model load happen inside the producer thread, so keepalives keep flowing during a cold load.
  • Errors are reported once. A stall throws out of consumeSSEResponse, gets past headers.timedOut() (false) and AbortError, and reaches callbacks.onError(err) exactly once. A stall after done or an error event returns quietly.
  • readWithin clears its timer in finally, so the losing stalled promise never rejects and can't cause an unhandled rejection.
  • Stop, stale-view and post-done paths skip the reconnect branch. They fall through to the existing wasStopping and isStale() handling, so the "went silent 4 times" text appears only after retries really run out.
  • The RUN_LOST_TEXT row survives the poll: lastMsgCountRef already equals the DB count, so the poll at ChatView.tsx:327 won't overwrite it.

Issues

🟢 Timeout kind is inferred from a duration (utils/streamErrors.ts:23). err.timeoutMs === SEND_HEADER_TIMEOUT_MS picks the send message over the attach message. If someone later sets both constants to the same value, or retunes one, attach timeouts get the wrong text without any error. Pass the route explicitly, e.g. new StreamTimeoutError(ms, 'send' | 'attach'), and switch on that.

🟢 Missing edge tests (ChatView.streamReliability.test.tsx). Two cases are worth a test each:

  • Stop pressed between a stall and the re-attach's first event. This is the stopRequestedRef guard plus abortRef being swapped to the new controller.
  • An attach that hits ATTACH_HEADER_TIMEOUT_MS during a reconnect. It should end the turn with the attach message, not loop.

🟢 A normal revisit attach can now show the "lost" message (ChatView.tsx:1034). Before this PR a 404 on attach was an error. Now it becomes done with empty content. So a user revisiting a chat whose run died before saving an answer (a server-side crash, not just a restart) also gets RUN_LOST_TEXT. That's probably the right message, but the wording "most often because GAIA restarted" makes the cause sound more certain than it is. Optional.

Strengths

  • The watchdog is reset by bytes rather than by parsed events, so the padded keepalive counts and no backend change is needed. The queued phase gets its own 10-minute limit instead of turning the watchdog off.
  • Reconnecting reuses the existing attach/replay path rather than building a second resume mechanism. It is capped per turn by a ref, so it can't loop.
  • consumeSSEResponse now returns a typed ApiError with the status code, so callers don't need to pick apart a "HTTP 429: {...}" string. The 409 and 422 details go through the existing parseErrorDetail.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 A reconnect while a permission prompt is open now hides that prompt, and the turn hangs until it times out and denies.

Reconnecting replays the whole run from the start. The earlier tool and answer events in that replay now clear every unanswered prompt in the session, including the one the agent is still waiting on. When that prompt's own event replays, the new "already known" check skips it, so it never comes back. The user sees no prompt, the agent stays blocked, and the call is eventually denied.

Fix: on a replayed permission_request whose id is already known, un-dismiss it if it has no response yet. Or clear prompts only on events that arrive after the prompt. Add a test: open a prompt, stall, then replay tool_start → permission_request with the same id, and expect the prompt to still be pending.

🔍 Technical details
  • ChatView.tsx (RESOLVES_PROMPTS branch and if (content) dismissSessionPrompts): during /chat/attach replay (routers/chat.py says the response "replays every event emitted so far"), any tool_start/tool_end/tool_result or content event from an earlier step calls dismissSessionPrompts(sessionId). That sets dismissed: true on every permission_request with !n.response, including the live one.
  • The replayed permission_request then returns early on notifications.some((n) => n.id === event.confirm_id), so dismissed stays true. notificationStore.ts:254 filters out n.dismissed from the pending prompt, so the inline prompt disappears while confirm_tool_execution keeps blocking server-side.
  • The existing test "clears a replayed prompt that the run already moved past" covers prompt → tool_start. It does not cover the reverse order, tool_start → prompt, with the prompt still open, which is what a mid-prompt reconnect produces.
                    if (event.confirm_id) {
                        const known = notifications.find((n) => n.id === event.confirm_id);
                        if (known) {
                            // Still open server-side: an earlier replayed event may have dismissed it.
                            if (!known.response && known.dismissed) {
                                useNotificationStore.setState((st) => ({
                                    notifications: st.notifications.map((n) => (n.id === known.id ? { ...n, dismissed: false } : n)),
                                }));
                            }
                            return;
                        }
                    }

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Review follow-up: a connection cut mid-answer now reconnects like a silent one, and a reconnect no longer brings back prompts that were already answered. Each change below has a test that fails without it.

  • Cut connection (Wi-Fi switch, proxy reset, restart) re-attaches instead of "send again" and the 409 that followed; retries wait 0, 1 and 3 s
  • Replayed prompts keep their answer; prompts the run moved past are dismissed
  • "Waiting for GAIA to start this answer…" clears when the backend answers
  • A non-recoverable agent_error ends the turn; a stream lost after Stop closes the turn locally instead of reconnecting
  • Bot suggestions: timeouts carry which endpoint timed out; added tests for Stop during a pending reconnect and for an attach that never answers
  • Nits: attach wording, a real Stop test, tests for a mid-stream cut and a 404 on re-attach

Not in this PR: making the server keep sending keepalives while it waits on producer.join after a stop. That code is the UI backend's (_chat_helpers.py), and I've passed it to the session that owns it. The client side above already copes without it.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Second review round: fixed two ways a turn could hang, each with a test that fails without the fix.

  • A reconnect replays earlier steps before the prompt the run is still blocked on. That prompt was being dismissed and then skipped as "already known"; it is now shown again. Answered prompts stay answered.
  • A fatal agent_error followed by a dropped or silent connection now ends the turn through onDone. An error event followed by a cut still closes the turn exactly once.
  • Leaving the chat and coming back during a reconnect wait no longer attaches twice; the timer lives in a ref that the session switch clears.
  • Stop during a reconnect wait closes the turn at once, not after the 15 s grace.
  • "Reconnecting…" clears as soon as the re-attach connects.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Third review round: the review's four repro tests pass on this branch and are now part of the suites. They checked out 3129ee86e; I confirmed all four fail there and pass from ba7c9fda8 on. That commit already fixed the hidden prompt, the fatal-error hang, the reconnect timer (now in a ref cleared on chat switch) and the leftover "Reconnecting…" line.

Backend side, owned by the UI-backend reliability session: #5337 bounds the post-Stop wait and always sends done with cancelled: true, and sends a keepalive every 5 s while a turn waits in line. Once #5242 and #5337 land, this PR's 10-minute "queued" exemption can be removed in a follow-up.

The red Windows CLI integration check was a rate limit in setup-ffmpeg, unrelated to this change. The new push re-runs it.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Round-3 optional item: reconnect waits are now 0, 3 and 10 s, about 13 s in all, so a backend restart can finish before the view gives up. The tests that wait on the delay now outlast it.

The remaining red checks are infra (Dependency Review, the setup-ffmpeg rate limit) and the known Python timing flake; this PR changes no Python. This push re-runs them.

A send the backend never answered spun forever, a half-open connection (tunnel, sleep, mobile) hung the answer with no end, and a busy server showed a raw "HTTP 429: {...}" dead end.

- /chat/send waits at most 90 s for the backend to start the turn (it holds a send up to 60 s for a chat slot), and after 3 s says "Waiting for GAIA to start this answer…".
- The stream drops after 30 s of silence (the backend sends a keepalive every 5 s) and re-attaches, which replays the run so far, up to 3 times with "Connection lost. Reconnecting (attempt n of 3)…". A turn waiting in the model queue gets 10 minutes, because the queue sends nothing until its place changes.
- A re-attach that finds the run already finished loads the saved answer; one that finds neither run nor answer says the answer was lost and to send again.
- 429, 409, header timeouts and stalls read as plain sentences with a next step.
…pts honest

A connection cut mid-answer (Wi-Fi switch, proxy reset, restart) fell through to "send your message again", and the resend then hit a 409 because the run was still alive. A reconnect also replayed permission prompts the user had already answered as pending again.

- A read that fails mid-stream, or an attach that cannot connect, is a dropped connection and re-attaches like a silent one. Attempts wait 0, 1 and 3 s so a restarting backend has time to come back, and Stop cancels a pending one.
- A stream lost after Stop closes the turn locally instead of reconnecting.
- A replayed prompt whose id is already known keeps its state, and tool or answer events dismiss prompts the run has moved past.
- "Waiting for GAIA to start this answer…" clears as soon as the backend answers.
- A non-recoverable agent_error ends the turn, so silence after it is not reported.
- Timeouts say which endpoint timed out, and the attach timeout reads as a reconnect that got no answer.
…al agent error always ends the turn

Review found two ways a turn could hang. A reconnect replays the run from the top, so earlier tool and answer events dismissed the prompt the run was still blocked on, and the replayed prompt was then skipped as already known. And a fatal agent_error followed by a dropped connection returned without onDone or onError, so the turn spun forever.

- A replayed prompt that is known but unanswered is shown again; an answered one is left as it is.
- After a fatal agent_error, a dead or silent connection ends the turn through onDone; after an error event (already reported) it ends quietly, so the turn closes exactly once.
- The delayed re-attach timer lives in a ref and is cleared when the chat changes, so leaving and coming back during the wait cannot attach twice.
- Stop during a reconnect wait closes the turn at once instead of after the 15 s grace.
- The "Reconnecting…" line clears as soon as the re-attach connects.
…uites

They fail on 3129ee8 and pass since ba7c9fd: a prompt still open survives a reconnect replay, the reconnect notice clears once the re-attach streams, and a fatal agent_error followed by a cut connection ends the turn exactly once.
The waits of 0, 1 and 3 s gave up about 4 s after the first drop, shorter than a real backend restart. They are now 0, 3 and 10 s, about 13 s in all, and the tests that wait on the delay outlast it so none pass vacuously.
@kovtcharov-amd
kovtcharov-amd force-pushed the claude/rel-webui-chat-stream branch from 83a68d3 to 6976723 Compare October 19, 2026 06:29
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 41ebf01 Oct 19, 2026
38 of 39 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-webui-chat-stream branch October 19, 2026 08:28
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…sy (amd#5344)

Before: when Lemonade didn't answer a connection in time, the Agent UI
showed "status unavailable", as if the server were busy, when nothing
was answering at all. A server that accepted the connection but never
answered held every `/api/system/status` request for the sum of its
probes' timeouts (up to about half a minute), so the UI's status poll
piled up. After: a refused connection, or a connect timeout to a remote
server, reads as "not running". A connect timeout to a Lemonade on this
machine reads as busy: it's up, just not accepting, so the UI no longer
tells you to start it. The probes share a 20-second budget, and a new
`lemonade_probe` field says how the probe ended, so clients can tell
"down" from "busy" from "error".

Reproduced by `tests/unit/chat/ui/test_status_probe_bounds.py`: on main,
a connect timeout sets `lemonade_error`, and a server that never answers
holds the request for 30 s. Here it's "down" with no error, and answers
in under 1 s with `timed_out`.

Asked for by the clients reliability work (amd#5316/amd#5317), which can now
drop its 60-second client wait.

## Test plan
- [x] `pytest tests/unit/chat/ui tests/unit/test_model_server_info.py`:
all pass
- [x] `npx tsc --noEmit` and `npx vitest run` in `src/gaia/apps/webui`
- [x] `python util/lint.py --black --isort --pylint --flake8
--test-lanes`

<details>
<summary>🔍 Technical details</summary>

- The Lemonade probe block in `system_status` moved into a nested
`_probe_lemonade()` and runs under `asyncio.wait_for(...,
_STATUS_PROBE_BUDGET_S=20)`. Fields it set before the budget ran out are
kept.
- `httpx.ConnectError` → `down`, no error. `ConnectTimeout` → `down` for
a remote URL, `timed_out` with an error for a loopback one (a wedged
local server with a full accept queue times out the same way). Any other
`httpx.TimeoutException` → `timed_out` plus an error. Anything else →
`error`. A completed probe → `ok`, or `error` when Lemonade answered
non-200.
- `SystemStatus.lemonade_probe` is new and optional, typed
`Literal["ok","down","timed_out","error"]`. If `/health` answered but
the slower probes ran out of budget, it stays `ok` with a probe warning.
The API schema and types are regenerated.
- Not LLM-affecting.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 21, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants