Repository navigation
fix(llm,ui): keep UTF-8 in model error messages and Agent UI JSON - #5563
Conversation
A failed scheduled run's error read back from GET /api/schedules showed "—" as "—" on Windows. The stored text was correct; the Agent UI served JSON without a charset, so clients applying HTTP's Latin-1 default (PowerShell 5.1's Invoke-RestMethod) misread it. Lemonade error bodies sent as text/plain without a charset were also decoded as ISO-8859-1 by requests' Response.text, mangling the same characters at the source. - Agent UI responses now declare application/json; charset=utf-8. - Lemonade, gateway, daemon-start and Fireworks error bodies are read with http_body_text(), which decodes UTF-8 unless the server names a charset. - The /responses SSE parser decodes lines as UTF-8 instead of relying on requests' text/event-stream default.
|
Verdict: Approve with suggestions On Windows, an em-dash in an error message reached users as "—". This PR fixes that in two places: where GAIA reads Lemonade and provider error bodies, and where the Agent UI API sends JSON. Both fixes are small and correct, and the tests use a real socket and fail when the fix is reverted. Nothing blocks the merge. Two optional follow-ups:
Real-world evidenceN/A: no evidence bundle was produced for this run. The PR description reports a manual end-to-end check: a schedule fired against a dead Lemonade, and the API then returned 🔍 Technical detailsIssues 🟢 Some responses skip the middleware ( 🟢 No test for the SSE decode change ( Strengths
|
The charset middleware sat inside the request guard and tunnel auth, so the 401s they build and the generic 500 handler went out without a charset. It now wraps every other middleware, and the 500 handler names its charset itself. Adds tests for both and for streamed /responses.
|
Both suggestions are in: every Agent UI JSON response now says 🔍 Technical details
|
…5610) Four timing-sensitive unit tests failed 8 unrelated PRs this week (#5537, #5539, #5562, #5563, #5564, #5565, #5566, #5568) and one of main's last 11 completed runs. Each still guards the same bug, but no longer races the clock on a busy runner. Every rewritten test was checked by breaking the code: it fails on the real bug and passes 50/50 runs, including under full CPU load. The PR also keeps three tests out of the developer's real `~/.gaia`. ## Test plan - [x] `pytest tests/unit/mcp/client/test_stdio_hung_server.py tests/unit/test_file_lock.py tests/unit/test_mcp_bridge_concurrency.py tests/unit/chat/ui/test_agent_model_override.py tests/integration/test_folder_indexing.py -n 4`: 316 passed, 3 skipped - [x] The four de-flaked tests, run 50x each: 250/250 serial, and 250/250 under xdist (32 workers) with all 32 cores also running busy loops. Main's versions in that same loaded run: redaction failed 10/50. - [x] Each test fails when its bug is put back in the code (see details) - [x] `tests/integration/test_folder_indexing.py -n 4`, 5 runs: all pass. Main's version fails 7 to 9 tests per run. - [x] Test 841 passes with `GAIA_HOME` set to a temp dir. Main's version fails. - [x] Electron `npx jest`: 1098 passed. The one failure, `test_electron_chat_installer.js` (component size 103,725 > 102,400), also fails on main and is unrelated. - [ ] CI green on Linux, macOS and Windows unit lanes <details> <summary>🔍 Technical details</summary> **`test_redaction_stays_fast_on_dense_escapes`** (Linux, 2.01 to 2.03 s against a 2 s limit) - Cause: an absolute 2 s bound. Locally the worst text takes 0.19 s. On a 4-worker, coverage-traced runner it took about 10x that. - Fix: time one 1M-char text against eight 125K texts with the same total length, on the same machine. Linear code scores about 1.0 and a quadratic scan scores 8, so the test asserts < 3. It takes the best of up to three paired runs, and uses the lower of the wall-clock and CPU (`thread_time`) ratios. Contention inflates wall time, and Windows samples CPU time on ticks. The test also fails if the 1M text takes more than 15 s of CPU, which catches a per-position rescan: that is linear but takes minutes. - Break checks: a quadratic prefix copy in `_candidate_windows` (`len(text[:start].rstrip("\\"))`) gives a ratio of 5.9x and the test fails. Main's 2 s test passed that same regression locally (1.57 s). A per-anchor rescan without merging takes 56 s and hits the 15 s ceiling. **`test_children_of_an_exited_server_are_still_stopped`** (Linux) - Cause: the test slept a fixed 2 s for the child watcher. The watcher backs off (0.5, 1, 2, 4 s…), so on a slow start its next scan came after the launcher had exited and the child was never recorded. - Fix: poll until `child_pid in transport._children`, with a deadline of 3 × `_CHILD_SCAN_MAX_S`. - Break checks: never recording children fails with "never recorded". Clearing `_children` before stopping fails with "kept running". Delaying the watcher's first scan by 2.5 s reproduces the CI failure on main's test, and the new test passes. - Note for the product side: a launcher that spawns a child and exits inside a backoff window still orphans that child. Real `npx`/`uvx` launchers outlive the window. **`test_the_next_waiter_takes_the_lock_within_milliseconds`** (macOS, median 6.5 to 8.1 ms against 5 ms) - Cause: macOS stretches `sleep(0.001)` under load, and the 5 ms median left no headroom. - Fix: the test wraps `_poll_interval`, which records each interval and signals the moment the waiter starts a poll's sleep. The lock is released right then, so the whole interval stands between the waiter and the lock. - Assertions: every interval the front waiter asks for is ≤ 2 ms, and the median hand-off is < 15 ms. A 20 ms poll always waits at least 20 ms, so it fails the median even with the bound widened. - Break checks: `_NEXT_POLL_SECONDS = 0.02` or `0.1` fails the interval assertion. Sleeping `_POLL_SECONDS` directly, so `_poll_interval` is bypassed, fails the median (20.8 ms). **`test_a_dropped_idle_connection_is_logged[True]`** (Linux) - Cause: the test asserted that `"Traceback"` was absent from the stderr captured by `capsys`. The traceback in that run came from a fake Lemonade server that `test_lemonade_shared_server.py` left running on the same xdist worker (`BrokenPipeError`). - Fix: the `serve` fixture records the bridge server's own `handle_error` calls, and the test asserts that list is empty. socketserver calls `handle_error` before it closes the connection, so the check doesn't race. A plugin that writes a traceback to stderr during the test fails main's version and passes the new one. - Break check: making `log_error` also call the base `log_error`, and reverting `str(args[0])`, raises `TypeError` in the handler, and the test fails. **Isolation fixes** - `test_folder_indexing.py`: `temp_folder` now lives in `isolated_gaia_home`, a per-test fake home, so `ensure_within_home` still admits it. Parallel workers no longer share or delete `~/.gaia/test_temp`. - `test_issue_841…`: the test now sets `GAIA_HOME` itself, so an inherited value can't override the patched `Path.home`. - `tests/electron/setup.js`: `os.homedir()` points at a per-file temp dir. It is assigned rather than spied, so `jest.restoreAllMocks()` can't undo it. Setting `HOME` would not work, because Jest's sandboxed `process.env` never reaches `os.homedir()`. - The "Ignoring invalid agents section in …\.gaia\tray-config.json" log came from `crash-loop-notification.test.cjs`, which mocks `fs` with a config the validator rejects. The real file was never read, but the path now names the temp home. </details>
When a scheduled run's model call failed, its error came back from the Agent UI API with "—" garbled into "—" on Windows. The stored text was fine. The API sent JSON without naming a charset, so Windows PowerShell 5.1 read the UTF-8 as Latin-1. Lemonade error bodies sent as
text/plainwith no charset were garbled the same way when GAIA read them. Both now arrive intact.Test plan
pytest tests/unit/test_utf8_error_bodies.py: a UTF-8 error body with an em-dash, served over a real socket, round-trips through_send_requestandchat_completions. The Agent UI's 503 detail decodes intact. Four of these tests fail with the fix reverted.pytest tests/unit -k "lemonade or schedule or error" -n 4: 3943 passed, 86 skipped, 1 failed. The failure istest_lemonade_embedded.py::TestArchiveSafety::test_a_tar_symlink_inside_the_tree_is_still_recreated, which is unrelated (tar symlink extraction) and skips when run alone.pytestontest_lemonade_client_http.py,chat/ui/test_server.py,test_scheduler.py,test_llm_retry_adversarial.py: 352 passed.python util/lint.py --black --isortGAIA_HOMEwithLEMONADE_BASE_URL=http://127.0.0.1:9/api/v1: created a schedule viaPOST /api/schedulesand let it fire. Before the fix,Invoke-RestMethod /api/schedulesshowed the garbled dash. After it, the header isapplication/json; charset=utf-8and the dash is intact.🔍 Technical details
\xe2\x80\x94. Starlette'sJSONResponsesendscontent-type: application/jsonwith no charset, and PowerShell 5.1 falls back to Latin-1 for that. Browsers and the Go TUI always decode JSON as UTF-8, sofetch().json()was not affected.Utf8JsonMiddlewareinserver.pyrewritesapplication/jsontoapplication/json; charset=utf-8on every response, including the ones built by exception handlers.requestsdecodes atext/*body with no charset as ISO-8859-1. The newretry.http_body_text()decodes UTF-8 unless the server names a charset. It replacesresponse.texton the Lemonade error paths inlemonade_client.py(chat/completions, completions, pull, responses,_send_request), and also ingateway.py,lemonade_service.pyand the Fireworks provider._parse_sse_stream(the/responsesstream) usediter_lines(decode_unicode=True), which decodestext/event-streamas ISO-8859-1. It now decodes each line as UTF-8.httpxcall sites (turn_insights.py,routers/system.py) already default to UTF-8. Subprocesstext=Truesites insrc/gaia/llmeither write to a log file or parse a version number, so they never reach this error path.