Repository navigation
fix(agent): preserve tool evidence across TUI turns and restarts - #3666
Conversation
|
Request changes — the feature itself is well built, but one edge case turns a long message into a failed turn, and the eval this change requires hasn't run yet. This makes the chat agent remember its actual tool calls and results across turns (and across restarts) instead of replaying five truncated text pairs. That's a real capability win, and the persistence, migration and restart paths are carefully tested. Three things to settle before merge:
There's also a performance cost worth a look: every streaming turn now reads and JSON-parses the whole session's stored traces twice, then token-counts every turn including ones that will be evicted. Real-world evidenceNo 🔍 Technical details🟡 Important1. Negative history budget raises instead of dropping history (
Dropping history is the correct degradation and already has a warning channel; the loud failure should stay with the model's own context-overflow classification. 2. Native tool history replayed into a non-tool-calling model (
3. Whole-session read + parse twice per streaming turn (
Related: 4. Missing mandated eval for an LLM-affecting change Per 🟢 Minor5. 6. 7. 8. The Also noting without flagging: removing the policy-block dedup in Strengths
|
On every non-Claude backend, the history sent to the model before each
request rewrote each tool-call turn as an assistant message whose content
was the word "None", and dropped the call. _structure_history_message
normalised content with str(), msg.get("content", "") returns None when
the key exists, and only the Claude branch kept tool_calls. The model
never saw which tools it had called or with what arguments.
minimax-m3 copied it: on 2 of 4 coding tasks it replied "None", which
became the final answer. No other model printed it across ~90 runs, but
all of them received the same history.
A tool-call turn is now rendered as "[Tool call: name(args)]", the same
text convention tool results already use, with any text the model sent
alongside it kept. None content becomes an empty string, never "None".
The Claude path is unchanged.
Closes amd#3757
Co-Authored-By: Claude Opus 5 <[email protected]>
Replaying a tool-call turn as "[Tool call: name(args)]" taught non-Claude models to write calls in that text format instead of calling tools, so the parser rejected them and the turn gave up. On the same 144-run battery that went from 0 to 58 runs ending in "I had trouble formatting my tool call". The turn is now just its own text (empty when it had none). The None -> "" guard stays, so the word "None" is still never replayed. Co-Authored-By: Claude Opus 5 <[email protected]>
# Conflicts: # src/gaia/agents/base/agent.py # tests/unit/test_sdk_history_tool_calls.py
|
Merged Both conflicts turned out to be easy. The one in the agent was two unrelated additions landing on the same line, so both are kept. The test file was an add/add: main had already landed #3758 on its own, with a fuller version of the same tests than the copy this branch carried, so main's won. 🔍 Technical details
Verified against a baseline rather than eyeballed: Plain merge commits, no rebase or force-push. |
…ol-history
One conflicted file, src/gaia/llm/lemonade_client.py: both sides added a
different context helper at the same spot. Kept both — they answer different
questions and each has live callers.
resolve_ctx_size() decides what window to REQUEST at startup and on
reload; honors the GAIA_CTX_SIZE override.
active_profile_ctx_size() REPORTS the device profile's window with no
override applied, for the overflow classifiers.
Collapsing them would have either made the classifiers follow a user override
(so a deliberately small window reads as a broken load) or dropped the override
from startup entirely.
cli.py, agents/base/agent.py and ui/_chat_helpers.py auto-merged; audited in
both directions. The branch's history/evidence work and main's move of the
Lemonade error classifier into providers/lemonade.py touch disjoint regions and
both survive intact.
# Conflicts: # hub/agents/gaia/python/tests/test_stdio.py
|
Reviewed this end-to-end. It's real work and it's close — the remaining blockers are the conflict, the bundled #3669 lines, and the eval, and only one of those needs a judgement call from you. The conflict is trivial. Only two files actually conflict, and none of the hard parts do — Every review-bot finding is addressed except one, and that one is yours to call. The per-turn history read is unbounded — The eval still hasn't run, and not for lack of trying. 🔍 Technical detailsVerified against head The three conflict hunks1. 2. 3. Bot findings, adjudicated at
|
| Finding | Status |
|---|---|
| Negative budget raises instead of dropping history | Fixed — history.py:92-97 warns and returns [] |
| Native tool history into a non-tool-calling model | Fixed — gated on _uses_native_tool_calls() (_chat_helpers.py:1059-1065) |
| Double read per streaming turn | Half fixed — pairs build now gated on agent_type == "email" (_chat_helpers.py:1805-1809); the unbounded read remains |
Over-wide except Exception in run_turn |
Fixed — stdio.py:1084-1090, 1109-1114 wrap only _record_turn |
| Migration idempotency + test isolation | Fixed in 7029ca71 |
Two nits still open, neither user-visible: finish() indexes call["id"]/call["function"]["name"] (history.py:54-57) — unreachable, since _build_assistant_message raises a frame earlier; and resolve_ctx_size re-reads ~/.gaia/config.json per turn when device is None (lemonade_client.py:329-332).
One inherited issue, not introduced here: get_context_messages has no role filter, so autonomous rows still reach _build_history_pairs, which only pairs a user immediately followed by an assistant — an interleaved tick silently drops the pair around it. Main's get_recent_messages didn't filter either.
Three things worth a follow-up
- TUI transcripts accumulate without bound.
~/.gaia/tui/history/<uuid4>.sqlite3, a new file per launch, carrying full tool output including local file contents. Mode 0600, but nothing prunes them. - The title overstates the shipped behaviour. "across restarts" holds only with
--history-file/GAIA_HISTORY_FILE; the default starts a fresh session each launch, which the docs say but the title doesn't. text_tool_history's[Recorded tool calls]branch is reachable only on a cross-model replay — turns recorded under a native model, then the session switched togemma4-it-e2b-FLM(the only chat-capable model withtool_calling=False). It can't fire from same-model history, since_build_assistant_messageonly attachestool_callson the native path. The tool-result branch is main's ownsdk.py:238fallback relocated, so nothing to change there. Narrow and unmeasured either way; deleting the one line to matchsdk.py:238would settle it.
On the eval
eval/mcp-config.json → mcp_server_launcher.py → from mcp.server import MCPServer (agent_ui_mcp.py:282) → ModuleNotFoundError → the gaia-agent-ui server dies → claude -p gets zero tools → INFRA_ERROR on all four scenarios in 10–17s each. The judge itself authenticates fine, so that's not the issue.
Worth noting for whenever it does run: --agent-type chat exercises the UI path (agent_loop.py, _chat_helpers.py, routers/chat.py — all in this PR) but not hub/agents/gaia/python/gaia_agent/stdio.py, which carries the headline budgeted-replay change. That surface stays unmeasured by this category.
The committed baseline is 4/4 PASS, avg 9.25 — scored on the old 5-pair clamp, so it can only move.
|
Correcting my earlier comment, and posting the eval it was missing. The eval passes — but I was wrong that this introduces no user-visible defect, and that correction matters more than the eval does. The regression: a heavy turn can wipe the whole conversationAfter a document- or code-heavy turn, the agent can lose the entire conversation, not just its oldest part. The new selector admits whole turns. When the newest turn alone doesn't fit the budget, it throws away everything — including short earlier exchanges that fit fine. Main always re-injected the last 5 exchanges truncated to 2000 chars, so the previous turn was guaranteed to survive. Nothing guarantees that now. This was reproduced against the merged tree by running the real There's a deterministic variant too. A turn that overflowed mid-run and was rescued by shrinking persists its pre-shrink trace, which by construction exceeds the whole window — so the very next turn wipes history every time. That makes long, valuable sessions the most likely to hit it. What the user sees: they ask a follow-up and the agent has forgotten the task, the file under discussion, and their name. The only trace is a log warning that never reaches the UI. NPU users hit it first, and it's close to unreportable from the field. Related, same place: resolving the negative-budget finding by returning an empty history instead of raising swaps a loud error for a silent total loss, which reads against the no-silent-fallbacks rule. The eval passes
The absolute scores are not comparable and the apparent +0.6 should not be read as an improvement: the committed baseline was scored by Sonnet 4.6 and this run by Opus 5, so the delta mixes a judge change with any behaviour change. Two limits on that evidence. It was measured on a local, never-pushed merge of this PR with main, so it isn't reproducible from any ref here. And Also correcting: my "lint clean, 1311 passed" overstated its coverageBoth statements were true of what they covered, but they read as covering the whole PR, and they exclude the hub half of it.
Both hub gaps are worth a follow-up issue on their own — adding 🔍 Technical detailsThe wipe
if used > budget:
target = budget // 2
while len(retained) > 1 and used > target:
_, removed = retained.popleft()
used -= removed
if used > budget:
retained.clear()Measured with the real Only fires when the oversized turn is the most recent one; with it earlier, later small turns survive.
One caveat on the numbers: the estimator is Coverage gaps
Corrections to line citations in my earlier comment
|
|
Two things from the review, with the numbers behind them. The eval is clean. The history wipe is real, and it is one branch. When a single turn is over the history budget on its own, history selection returns an empty list — it discards the oversized turn and the earlier turns that would have fit. On an NPU box (32K context, a 16,384-token budget) three tool results at the repo's own truncation target is enough; on a GPU box it takes four. That size is not a worst case picked to make it fire: a single Worth saying plainly, because it makes the ask smaller than the headline: the code degrades correctly right up to that point. At GPU with three results — 32,557 tokens against a 32,768 budget — it drops the five earlier turns and keeps the newest turn whole, which is what it is designed to do. Only the last resort is wrong: it should return the newest turn alone, or the earlier turns that fit, instead of clearing both. One thing the existing unit test misses: it places the oversized turn in the middle of the history, which is the one position where this branch is harmless because a later turn gets appended after it. Move that turn to the newest position — the only position a just-completed turn ever occupies — and it fails. And one correction to my own earlier framing: this is not like-for-like with main. Main's floor kept five user/assistant pairs truncated to 2,000 chars each and never carried tool results at all. "Main could not return an empty history" is literally true, but what main guaranteed to survive was ~5K tokens of prose, not a tool-bearing turn. Repro from a checkout of this branch — no server, no model, runs in a second: # save as mini_repro.py at the repo root, then: python mini_repro.py
import sys
sys.path.insert(0, "src")
from gaia.agents.base.history import select_history
from gaia.llm.lemonade_client import NPU_CTX_SIZE
budget = NPU_CTX_SIZE // 2 # what history_budget() returns on an NPU box
result = "log line\n" * 2500 # 20,000 chars = one truncated tool result
earlier = [[{"role": "user", "content": f"q{i}"},
{"role": "assistant", "content": f"a{i}"}] for i in range(5)]
newest = [{"role": "user", "content": "compare the three reports"},
{"role": "assistant", "content": "", "tool_calls": [
{"id": f"c{i}", "type": "function",
"function": {"name": "search_documents", "arguments": "{}"}}
for i in range(3)]}]
newest += [{"role": "tool", "tool_call_id": f"c{i}", "name": "search_documents",
"content": result} for i in range(3)]
newest += [{"role": "assistant", "content": "here you go"}]
kept = select_history(earlier + [newest], budget)
print("budget :", budget, "tokens")
print("messages in :", sum(len(t) for t in earlier) + len(newest))
print("messages kept :", len(kept))🔍 Technical detailsWhere the wipe comes from
There is no compensating floor downstream. The budget, and why the harness could not have rigged it
Measured on both profiles: NPU Correcting a label in my own outputThe driver script prints Sensitivity — it is not knife-edge on one fillerSwept through the real It wipes in all eight cells; only the trigger count moves. Sweeping turn size continuously puts the NPU boundary at roughly 62,000 chars of turn content — and since one result contributes at most ~30,000 chars before truncation, three is the arithmetic minimum, not a chosen number. Input-size provenance: Position is decisive, and the test picks the benign one
The size-independent variant
The caveat that cuts the other wayA plain long assistant answer does not realistically trigger this — it needs ~100,000 chars (18,538 tokens) on NPU, and What main actually did
Eval — full compare outputThe tool rounds for display. JSON values: current Run identity, since earlier attempts existed: four other runs that session were infra-error runs ( Full driver script behind the sweep numbersThe import json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent / "src"))
from gaia.agents.base.history import select_history, history_budget
from gaia.agents.base.turn_metrics import count_tokens
from gaia.llm.lemonade_client import (
DEFAULT_MODEL_NAME, GPU_CTX_SIZE, NPU_CTX_SIZE,
budget_for_ctx, resolve_ctx_size,
)
QUERY = "Compare the three reports you just read and tell me which one to act on."
PROMPT_CHARS = 28957 # turn_metrics.py:52 — the flagship's measured prompt size
class _Cfg: max_tokens = 8192 # agent.py:1403
class _Chat: config = _Cfg(); llm_client = None
class _Agent: # attribute bag only — computes nothing
def __init__(self, device, prompt):
self.model_id, self.device = DEFAULT_MODEL_NAME, device
self.system_prompt, self._openai_tools = prompt, []
self.chat, self._use_claude = _Chat(), False
def sweep(device):
ctx = resolve_ctx_size(DEFAULT_MODEL_NAME, device)
_, target = budget_for_ctx(ctx) # post-truncation size of one result
budget = history_budget(_Agent(device, "…" * PROMPT_CHARS), QUERY)
earlier = [[{"role": "user", "content": f"q{i}"},
{"role": "assistant", "content": f"a{i}"}] for i in range(5)]
for n in (1, 2, 3, 4):
calls = [{"id": f"c{i}", "type": "function",
"function": {"name": "search_documents", "arguments": "{}"}}
for i in range(n)]
newest = ([{"role": "user", "content": QUERY},
{"role": "assistant", "content": "", "tool_calls": calls}]
+ [{"role": "tool", "tool_call_id": f"c{i}",
"name": "search_documents", "content": "x" * target}
for i in range(n)]
+ [{"role": "assistant", "content": "done"}])
cost = count_tokens(json.dumps(newest, ensure_ascii=False))
kept = select_history(earlier + [newest], budget)
print(f"{device} N={n} newest={cost:>6} budget={budget} kept={len(kept)}")
sweep("npu"); sweep("gpu")Substituting prose filler for |
A turn whose tool evidence is larger than the whole history budget wiped the entire conversation instead of just itself. The eviction loop popped every earlier turn chasing half the budget for a turn that could never get under it, and the clear() that followed dropped the oversized turn left standing alone -- on a 32K-ctx NPU box, a turn carrying three ~20,000-char tool results left the agent with zero replayed messages while five short earlier turns were sitting there. A turn that cannot fit alone is now skipped before any eviction runs, so the budget is never spent evicting for a turn that can never be replayed. Replay still stays contiguous: turns before a dropped one are released only once a later turn is admitted, which is what keeps an oversized turn in the middle from stitching a hole into the transcript. The warning now reports both counts, so an empty replay is always accounted for.
Eviction works on whole turns today, so a tool call and its result can never be separated -- but nothing held that line. Move eviction to per-message and the replay window can open on a tool result whose call was evicted out behind it, which models either reject outright or hallucinate around. The neighbouring block-eviction test does not cover this. Its expectations encode turn granularity, so the same refactor that introduces the bug also breaks that test for an unrelated reason and gets it updated as expected churn; rewrite it to match per-message output and this test is the only one still failing. Sweeps real budgets with the real tokenizer rather than pinning one. Under per-message eviction only 38 of the 100 overflowing budgets in the swept range land the cut between a call and its result, so a single pinned budget passes by luck more often than not. A constant-cost mock would be worse still -- it makes a partial turn cost the same as a full one, erasing the only dimension this can go wrong in.
|
Pushed three commits to your branch — the conflict is cleared and the history-wipe regression is fixed. Revert any of it freely if you'd rather take a different line; the code is yours.
Correcting myself: my earlier description of the cause was wrong. I said And a second correction: I implied the hub Two things that are yours to call, neither blocking:
🔍 Technical detailsHead is now The fix
Worth noting: The warning now reports evicted and unreplayable counts separately. Minor wart: turns released by the contiguity branch are counted as On the corrected causeInstrumented the pre-fix body over 19,530 cost sequences (lengths 1–6 from {10, 40, 60, 101, 1000}, budget 100): 44,922 firings, length 1 every time. It also falls out of the guard: after the loop, Same harness also settles a question I'd raised and got wrong — whether a mid-history oversized turn behaves differently now. It doesn't: VerificationThe guard test was re-proved non-vacuous in a copy of this tree: under a message-granular eviction mutation it fails naming the orphaned call id, and reverts clean. It sweeps
Merge auditEvery line you added between merge-base |
|
🟡 The gaia flagship agent loses conversation context on session eviction in the Agent UI. The streaming path now builds Previously the UI always pushed up to 5 truncated text pairs (one call to 🔍 Technical details
history_pairs = (
_build_history_pairs(db.get_context_messages(request.session_id))
if (request.agent_type or session.get("agent_type")) == "email"
else []
)
elif _should_relay_to_sidecar(agent_type, _agent_registry):
_dispatch_sidecar_query(..., history_pairs, ...) # history_pairs=[]
return # ← never reaches _restore_model_history at line 2302
if request.context and hasattr(agent, "conversation_history"):
agent.conversation_history = [...] # never runs with context=[]
Fix: extend the |
|
Real-world proof that the fix works, on hardware, through the real API — everything before this was synthetic. Same machine, same model, same script, two arms differing by exactly one file (
The logs show which branch actually ran, so this isn't inferred from the answers: Before drops turn 1 along with the oversized turn. After drops only the oversized turn. Memory is ruled out as an explanation: all four runs were private sessions, turn 1's One limitation, stated plainly: turn 2 was oversized by a large user paste, not by oversized tool evidence. Same branch, same trigger, and the log fingerprint proves the branch executed — but it isn't the literal scenario in the title. Driving tool evidence past the budget wasn't reachable here: one tool result caps at 40,000 chars, and the turns that would have needed several didn't persist tool messages. By the time control reaches the selector the only input is the turn's token cost, so the paths converge — but that's an argument, not a measurement, and worth saying so. Separately, and possibly bigger than the bug this PR fixes: the history budget is computed with a cl100k estimator while the model is Gemma. On one measured prompt Gemma counted 78,736 tokens where the estimator said ~38K — roughly 2×. If that ratio is systematic, the budget is wrong for every Gemma user, and a turn can overflow a window the budget math believes has room. Filing separately; it predates this PR. 🔍 Technical detailsRyzen AI box, Turn 2 persisted at 38,443–38,603 estimated tokens against that 32,768 budget — 17% over. Turn 1 was ~290–300 tokens, comfortably fitting, which is the whole point: it was discarded despite fitting. Both arms are the PR head Note on environment: Turn 2 itself returned 500 ( Artifacts: CI42 passed, 14 skipped, 3 failed — none caused by this PR:
|
itomek
left a comment
There was a problem hiding this comment.
Conflict cleared, history-wipe regression fixed with a guard test, and verified end-to-end on hardware: the planted fact survives an over-budget turn after the fix and is lost before it, with the selector's own log line confirming which branch ran. Eval 4/4 with no status changes. The three red checks are infrastructure or a non-blocking soft job — details in the comments above.
|
Post-merge addendum: the same A/B was repeated on a second Ryzen AI machine and reproduces cleanly. Turn 2 succeeded in all four runs there, so the arms are matched with no failed-turn confound — this run is tighter than the one posted above.
Same log fingerprint as before: the pre-fix arm reports Two things this second run turned up that are worth having, neither a problem with this PR: The first attempt didn't meet its own precondition, and is reported as-is. An 80,000-char paste persisted at only 21,048 tokens — under the 32,768 budget — so no eviction happened, no warning fired, and the pre-fix arm recalled correctly. That's the expected result when the turn fits; the payload was then sized to actually cross the budget, identically for both arms. The budget on that machine is 32,768, not the 16,384 its device profile implies — filed as #4287. 🔍 Technical detailsTurn 2 measured 38,425–39,240 estimated tokens against the 32,768 budget (+17–20%). Timings: turn 1 ~54 s, turn 2 198–250 s, turn 3 33–48 s. On the first turn GAIA reloaded the pre-loaded model by itself: The limitation from the earlier comment is unchanged: turn 2 is oversized by user paste, not by tool evidence. One tool result caps at 40,000 chars and this agent persists no tool messages on the turns that would have needed several, so the literal tool-evidence scenario still hasn't been driven end-to-end. The branch and trigger are the same and the fingerprint confirms the branch ran. Artifacts: |
…amd#4370) `main` has been red since 2026-09-25 18:29, so nothing can leave the merge queue. Three separate regressions landed within minutes of each other; this clears all three. The worst is a literal `SyntaxError` — `ChatAgentConfig(...)` was passed `device=` twice, so the Agent UI backend and everything importing it failed at module load, taking out the Linux, Windows and macOS unit-test jobs. Nobody wrote that duplicate: amd#3666 and amd#4275 each added the same kwarg a few lines apart, neither diff conflicted textually, and the merge queue merged both cleanly into a file that does not parse. The other two are one-liners: amd#3402 re-imported `tool_cancelled` over a name the module already imports (failing the pylint gate) and shipped `wait_for_condition` with no UI label, and amd#4271 landed an over-long assertion (failing the black gate). **Worth knowing:** the ~13 "new pylint errors" that appear in the failing job's log are not pylint errors. They are the first 20 lines of the **non-blocking MyPy** output (1224 warnings, truncated for display) and have never gated anything. Only one pylint hit was real. No dependency or tool-version drift was involved — pylint 4.0.9 and black 26.5.1 both predate the last green run. ## Test plan - [ ] `python util/lint.py --black` — clean (1180 files unchanged) - [ ] `uvx pylint src/gaia --rcfile .pylintrc --disable C0103,C0301,W0246,W0221,E1102,R0401,E0401,W0718,W0212` — clean on Linux - [ ] `python -m compileall -q src/gaia tests` — no syntax errors - [ ] `python -m pytest tests/unit/test_schedule_daemon.py -q` — 28 passed - [ ] `python -m pytest tests/unit/chat/ui -q` — 1040 passed (was 17 collection errors) <details> <summary>🔍 Technical details</summary> **`src/gaia/ui/agent_loop.py`** — the two `device=session.get("device")` lines were textually identical, so deleting the later one restores exactly the intended call. `git blame` attributes line 461 to `1caad2ade5` (amd#4275) and line 465 to `7a8fea58b1` (amd#3666); amd#3666 is an ancestor of the last green commit `69f76ab57`, so amd#4275 is the one that created the duplicate. **`src/gaia/agents/tools/shell_tools.py`** — `gaia.agents.base.tools.tool_cancelled` is a pure re-export of `gaia.tool_cancellation.tool_cancelled`, which the module already imports at line 31. Verified the bindings are the same object, so dropping the function-local import is a no-op rather than a behaviour change. **Follow-up worth a maintainer's eye, deliberately not bundled here:** `wait_for_condition` executes arbitrary commands against the same allowlist as `run_shell_command`, but unlike `run_shell_command` it is not in `_GAIA_MUTATING_TOOLS`. By that set's own stated criterion ("or execute code") it looks like it belongs there, and omitting it means the tool skips the confirmation gating its sibling gets. That is a behaviour change, not a CI fix, so it should be reviewed on its own rather than smuggled into an unblock PR. **Also noted:** `.pylintrc` uses `disable = all` plus an explicit `enable` list that does not include `syntax-error`, which is why the pylint gate walked past a file it could not parse. Enabling `E0001` would have caught this at PR time. </details>
GAIA can now answer follow-ups using prior tool evidence in the TUI, including after reopening its transcript. Previously the saved conversation could retain only the final prose, losing facts the tools had read. Complete turns are archived locally and replayed within a budget that reserves room for the current prompt, tools, and answer.
Closes #3628. Depends on #3669 (included here); also includes the SDK null-content normalization from #3758 with original authorship.
🔍 Technical details
The TUI stores its transcript under
GAIA_TUI_HOME/history/;--history-fileorGAIA_HISTORY_FILEreopens an explicit transcript. Whole tool groups stay intact when older turns leave the active window. Persistence completes before the terminal response, and clearing the history deletes its archive. Legacy chat persistence uses the same budget calculation.Test plan
7319, which appeared only in the deleted file's tool result.