Skip to content

fix(ui): never stream the agent's JSON envelope into the chat - #5121

Merged
kovtcharov-amd merged 4 commits into
mainfrom
fix/no-raw-thought-json
Oct 15, 2026
Merged

kovtcharov-amd merged 4 commits into
mainfrom
fix/no-raw-thought-json

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

When a hosted model answered with a tool call carrying a long argument, such as a file write with the whole file in it, the chat showed a raw {"thought": …} line above the tool rows. The stream filter gave up on tool-call JSON past 2 KB and printed it as text, and a reply with a plan could leak its tail. Now the agent's response JSON is held until it closes and then dropped, however long it is and however it is split or fenced. An answer inside it still shows, and ordinary answers that are or contain JSON are left alone. This changes what streams from the model to the screen, so it needs the flagship eval. The combined eval on main will cover it.

Test plan

  • python -m pytest tests/unit/chat/ui/test_sse_handler.py tests/unit/messaging/test_slack_event_contract.py tests/unit/test_model_phase_progress.py passes. Fourteen of the new cases fail on main.
  • The new cases cover nested and escaped quotes, an envelope split mid-key and token by token, thought plus answer, fenced JSON, a truncated envelope, a { line that is not JSON, and real JSON answers, which must still show.
  • A 400 KB envelope streamed 4 characters at a time finishes in under a second.
  • cd tui && go test ./internal/ui/chat/ passes.
  • Flagship eval: covered by the combined run on main.

A reply that called a tool with a long argument (a write_file carrying a
whole file) reached the TUI as a raw {"thought": ...} line above the tool
rows. The stream filter flushed any tool-call JSON past 2 KB as text, and
a plan envelope whose head the cleanup regex ate leaked its tail.

The handler now recognises the response envelope at the head of the
stream (optionally fenced), holds it until its closing brace with a
string-aware, resumable scan, and drops it; an "answer" field is still
emitted as the answer. Ordinary JSON answers and text that merely starts
with "{" are untouched.
@github-actions github-actions Bot added the tests Test changes label Oct 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Long tool calls (a file write that carries the whole file) no longer show up as raw {"thought": …} text in the chat. The new filter holds the agent's reply JSON until it closes and then drops it, while JSON that is a real answer still shows. The live evidence confirms the fix, and the tests cover the hard cases: split keys, escapes, fences, truncation, and a 400 KB stream.

One gap is left, and it's worth a quick follow-up but doesn't block merge. If the model writes a long tool call that isn't strictly valid JSON (a \' escape is the common case), the new filter passes it to the old code. The old code still prints anything over 2 KB raw. This is how main already behaves, so nothing regresses, but it's the same leak this PR sets out to close.

The flagship eval is deferred to the combined run on main, as the description says. That run needs to happen, since this changes what streams to the screen.

Real-world evidence

On the real POST /api/chat/send route, with a stub model and the real agent loop and server, a ~4 KB tool-call reply streamed 0 raw text chunks on this PR. On the base commit, the same reply streamed 432.

# PR head 2d275330
$ grep -c '"type": "chunk"' send2.sse
0
data: {"type": "thinking", "content": "I need to read the file first, then write."}
data: {"type": "plan", "steps": ["write_file — file_path='a.md', content='# Answer\\n\\nCited fact, …
data: {"type": "tool_result", "title": "Tool Result", "summary": "denied: Tool 'write_file' was denied by the user.", "success": false, …}
data: {"type": "answer", "content": "The passphrase is violet-otter-92."}

# Base 71bed605
$ grep -c '"type": "chunk"' send_base.sse
432
data: {"type": "chunk", "content": "}], \"to"}
data: {"type": "chunk", "content": "ol\": \"n"}
# A real JSON answer still streams as text (PR head)
chunk text reassembled: 'The config is:\n```json\n{"name": "gaia", "port": 4200}\n```'

The adjacent cancel, confirm-tool, session-messages, and permissions routes all returned HTTP 200 with the expected results, and no saved message contained {"thought". The rendered Agent UI screenshot is pending the strix-halo lane, because this runner has no real inference.

🔍 Technical details

🟡 A malformed long envelope still leaks raw (src/gaia/ui/sse_handler.py:936-937)

_parse_envelope returns None for anything json.loads rejects. strict=False lets literal newlines through, but invalid escapes like \' or \_ still fail. _take_leading_envelopes then returns False, and the old Case 1 branch takes over (if len(self._stream_buffer) > 2048: self._emit({"type": "chunk", ...})), which emits the whole buffer as a chunk. The balanced-brace scan already proved the head object is closed and starts with a protocol key. When it also carries a marker key, drop it rather than falling through:

            envelope = _parse_envelope(self._stream_buffer[start:end])
            if envelope is None and not _ENVELOPE_MARKER_LEAD_RE.match(
                self._stream_buffer, start
            ):
                return False
            envelope = envelope or {}

The suggestion needs a module-level _ENVELOPE_MARKER_LEAD_RE = re.compile(r'\{\s*"(?:thought|tool_args|answer)"\s*:'), or any other test for whether the lead key is a marker key. It also needs a test with a \' inside a >2 KB tool_args.content. I confirmed this path by reading the code; I couldn't run it here because the review runner has no gaia deps installed.

🟢 A truncated real JSON answer is dropped silently (sse_handler.py:926-934)

At end of stream, any unclosed object whose first key is in _ENVELOPE_KEYS gets dropped. That includes a real answer like {"goal": "ship v1", … that hit max tokens, so the user sees nothing. It's rare and arguably correct for the protocol. If you want it tighter, you could limit the drop to buffers that contain a marker key.

🟢 Unexplained done content (from the evidence bundle)

In the plain-JSON run, the done event's content was missing the closing fence that the streamed chunks contained. The bundle didn't compare this against base, so it may predate this PR. It's worth a look so the persisted message matches what streamed.

Strengths

  • The resumable brace scan (_json_object_end with resume) plus the _envelope_head guard keep a huge streamed write linear in time, and they recover correctly when the buffer is rewritten or a stream is cancelled. Both cases are pinned by tests.
  • An answer inside an envelope is re-emitted as an answer event. The frontend treats that event as replace-not-append, so the repeated answer the bundle saw is harmless.
  • The tests check every partial state mid-stream, not just the final one, and include negative cases ({placeholder}, non-envelope JSON, fenced JSON) so the filter can't over-suppress.

# Conflicts:
#	src/gaia/ui/sse_handler.py
The envelope filter held every leading JSON object until its closing
brace, so an answer-first reply no longer streamed token by token as the
answer decoder on main does. Answer-first envelopes now go to that path;
every other envelope is still held and filtered.
@kovtcharov-amd
kovtcharov-amd merged commit 204d3a0 into main Oct 15, 2026
@kovtcharov-amd
kovtcharov-amd deleted the fix/no-raw-thought-json branch October 15, 2026 12:39
kovtcharov-amd added a commit that referenced this pull request Oct 15, 2026
Main's lint fails black on `sse_handler.py` since #5121: a module-level
regex sits one blank line above the class. This adds the second blank
line.

## Test plan
- [ ] `python -m black --check src/gaia/ui/sse_handler.py` passes
kovtcharov-amd added a commit that referenced this pull request Oct 15, 2026
…5131)

When a hosted model wrote its tool calls as text (DeepSeek's DSML
markup), every call streamed into the answer area while it was being
written: up to 50 times in one turn, with long Python mangled by
Markdown into headings. Long calls in GAIA's own JSON format either
leaked the same way or sat behind a bare "Reading the tool results ·
90s" timer. Now the call is held back and dropped, and the activity line
says what is being written and how big it is ("Writing Python code —
4,210 characters so far"), never its content. Markup quoted in a code
block, or a tag named in prose, still shows.

Stacked on #5121 (the JSON-envelope half of this filter); pairs with
#5103, which makes the agent run DSML calls instead of answering with
them. This changes what the LLM's output looks like to the user, not
what the LLM sees; the flagship eval that runs on main covers it.

## Test plan
- [x] `python -m pytest tests/unit/chat/ui/test_sse_tool_call_text.py
tests/unit/chat/ui/test_sse_handler.py
tests/unit/test_model_phase_progress.py
tests/unit/test_tool_call_progress.py`
- [x] Replayed the SSE streams captured from the affected Agent UI runs
through the new filter: no DSML, tool JSON or code reaches a `chunk`
event, and every final answer still streams
- [x] Drove the Agent UI with a scripted DSML `run_python` reply:
before, the code scrolled past as headings; after, only the narration
line and "Writing Python code — N characters so far" show
- [x] `python util/lint.py --black --isort`
kovtcharov-amd added a commit that referenced this pull request Oct 15, 2026
Main is red on three jobs and rc15 is blocked on it. Answers the model
wraps in `{"thought": ..., "answer": ...}` stopped streaming after #5121
held every envelope until it closed, so the chat sat blank through a
long answer and Stop kept nothing; they now stream from the first token
again while thoughts and tool calls stay hidden. The Chat Agent job
failed because the frozen `run_python` adversarial tests still
intercepted `subprocess.run` after #5104 moved Python jobs to `Popen`.
Code Quality failed on two pylint findings in the Agent UI MCP control
server; the unused `host` is now checked, so loopback-only transport
settings refuse a network address instead of silently applying.

## Test plan
- [x] `python -m pytest tests/unit/test_json_answer_decoding.py
tests/unit/chat/ui/test_sse_handler.py
tests/unit/chat/ui/test_sse_tool_call_text.py
tests/unit/test_model_phase_progress.py
tests/unit/test_tool_call_progress.py` (397 passed; the 5 streaming
cases fail on main)
- [x] Every test file touching `sse_handler`, JSON answers, or
`agent_ui_control` (2180 passed)
- [x] `tests/unit/test_run_python_frozen_adversarial.py
tests/unit/test_run_python_frozen.py` (103 passed; 19 fail on main)
- [x] `python util/lint.py --black --isort --pylint`
- [ ] CI: Unit Tests, Chat Agent Tests, Code Quality
- [ ] Flagship eval: this changes what streams to the chat; covered by
the combined run on main
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.

1 participant