Repository navigation
fix(chat-agent): block reasoning loops + supplementation on out-of-scope questions - #919
Conversation
Chat Lite is a 4B-model sibling of the built-in Chat Agent for
hardware that cannot host the 35B default (Macs, low-memory boxes).
Same tools, same system prompt, just pinned to Qwen3-4B-Instruct-2507
via the ChatAgent config. ChatAgent and its registration are
untouched.
Agent metadata gains `min_memory_gb`, exposed via `/api/agents`.
Settings renders a Memory Warnings section when any registered agent
declares a requirement above the free memory reading.
Two Settings additions:
* Active Model — text override bound to the existing `custom_model`
setting. Empty means "use agent default".
* Context Size — preset chips (4K/8K/16K/32K) + numeric input that
reloads the active model with the chosen ctx via the existing
`/api/system/load-model` endpoint.
Two correctness fixes made Chat Lite actually usable end-to-end:
* `/api/system/status` previously flagged any non-35B model as
"Wrong model loaded". It now accepts any registered agent's
preferred model, so Chat Lite's 4B doesn't trip the banner.
* `_maybe_load_expected_model` short-circuited when any LLM was
active, even the wrong one. It now requires the specific expected
model with ctx >= 32K, otherwise reloads. Without this, Lemonade
auto-loaded requested models at its default 4096 ctx, silently
truncated ChatAgent's >7K-token system prompt, and returned an
empty stream. `_ensure_model_loaded` also falls back to 32K when
the model is not in the built-in MODELS registry.
Tests: 10 new unit tests covering registration, factory presets,
min_memory_gb propagation through manifests and the agents API, plus
a coexistence check that Chat Agent's defaults stay unchanged.
Frontend `npm run build` passes with 0 new warnings.
The streaming and non-streaming branches of `_chat_helpers` that call
`registry.create_agent(...)` only passed `model_id / streaming /
silent_mode / debug`. They dropped `rag_documents`, `library_documents`,
`allowed_paths`, and `ui_session_id` — the same fields the built-in
Chat path at the same callsite correctly forwards to ChatAgentConfig.
Consequence on Chat Lite (any registered agent backed by ChatAgent):
the agent boots with `PathValidator(allowed_paths=[Path.cwd()])` →
`Access denied` on every session doc path outside the repo dir (e.g.
`/Users/kovtcharov/Downloads/...`). Its own RAG index stays empty, so
the LLM's `list_indexed_documents` returns "No documents indexed",
falls through to `search_file` with `deep_search=True`, and spirals
the whole filesystem for ~10 minutes until the 600 s stream timeout.
The frontend sees no content stream, so the user sees nothing.
With the missing kwargs forwarded, the agent's PathValidator accepts
the session's doc parents (via `_compute_allowed_paths`) and its RAG
picks up the attached files during `_index_rag_with_progress`.
Verified end-to-end on chat-lite: index a Downloads markdown doc,
ask "what iOS version does Clerk require?" → correct cited answer
("iOS 17+ for authentication") at ~40 tok/s with a single
`query_specific_file` call. No more loop, no timeout.
Also fixes two smaller papercuts found while verifying:
- `SettingsModal` sent `custom_model: null` to clear the override,
which the backend treated as a no-op (Pydantic can't distinguish
"unset" from "null"). Send `""` instead — the backend already
treats that as "clear".
- Corrected the `/api/settings` PUT docstring to match the actual
behaviour (`""` clears, `null` is a no-op), so future callers
don't trip on the same mismatch.
… + validate ctx_size Follows up on the architecture review of PR #802 with three polish fixes; no behaviour change vs the previous commit on main agents paths except the `ctx_size` validation. 1. **Single source of truth for the 32K context requirement.** ``DEFAULT_CONTEXT_SIZE`` now lives in ``gaia.llm.lemonade_client`` and is re-exported by ``lemonade_manager`` for backwards compat. The router's ``_MIN_CONTEXT_SIZE`` is aliased to it. Eliminates the three side-by-side copies (each carrying a "must match ..." comment — exactly the smell review flagged as drift-prone). 2. **Extract ``_session_agent_kwargs`` helper** in ``_chat_helpers``. The four ChatAgent/registry.create_agent call sites used to repeat the same 4-field bundle (rag_documents, library_documents, allowed_paths, ui_session_id). Centralising it means adding a new field — or forgetting one, which is what bit us last time and caused Chat Lite's PermissionError spiral — happens in one place. Unknown kwargs are still filtered by the per-agent factory, so this remains safe for manifest agents that don't recognise all fields. 3. **Validate ``LoadModelRequest.ctx_size > 0``.** Manual testing showed ``ctx_size: -1`` and ``ctx_size: 0`` were silently accepted by the endpoint and then failed deep in Lemonade with no actionable error. ``Field(None, gt=0)`` now surfaces a 422 at the boundary with a readable message. Verified with the existing 153-test suite and a live end-to-end sweep over the chat-lite agent on a Mac: cold auto-load, warm reuse, agent switch, parallel sessions (3 simultaneous), ctx reload 32K→64K, long 6K-token input, empty message, malformed load-model payload — all pass.
The registered-agent streaming path in ``_chat_helpers`` was surfacing a
noisy ``Used tool INDEX_DOCUMENTS`` card on every cache miss — even for
casual chat turns like "not much" — because session-attached docs were
being indexed twice:
1. ChatAgent.__init__ silently auto-indexed ``self.rag_documents``
(via ``_index_documents``) when the factory was called with
``rag_documents=rag_file_paths``.
2. ``_index_rag_with_progress`` then indexed the same paths again,
this time emitting SSE ``tool_start: index_documents`` events that
the UI rendered as a tool call for a 0-work hash-cache hit.
The built-in ``chat`` streaming branch avoided the double-index by
passing ``rag_documents=[]`` into the config; the registered-agent
branch added in a949c21 didn't follow the same pattern. This change
aligns them. Non-streaming path keeps its single-pass __init__-based
indexing (no SSE handler, so no user-visible noise).
Rename motivation: the "Chat Lite" label implied a lightweight chatbot,
but the agent is a full GAIA agent (RAG + file tools + MCP) that just
happens to be pinned to a 4B model so it fits on Mac and other
low-memory hardware. Renamed to ``gaia-lite`` / "Gaia Lite" throughout.
Back-compat: existing UI sessions store ``agent_type`` in SQLite, so
renaming the ID would orphan in-progress sessions. Added
``AgentRegistry.canonical_id`` and a ``_LEGACY_ID_ALIASES`` map; all
lookups (``get``, ``create_agent``, ``resolve_model``) resolve legacy
IDs transparently. The per-session agent cache in ``_chat_helpers``
also normalizes through ``canonical_id`` so a client mixing old and
new names within one session doesn't thrash the cache.
Frontend: ``MessageBubble`` prepends a literal "GAIA" brand span to
``agentName``. With ``name="Gaia Lite"`` that would render as
"GAIA Gaia Lite". Strip a leading ``/^gaia\b/i`` from ``agentName``
before rendering the agent span, so "Gaia Lite" → "GAIA Lite" and
"Chat Agent" → "GAIA Chat Agent" (unchanged).
Also fixes a latent ``resolve_model`` bug found during review: it
used ``self._agents.get`` directly, bypassing the alias map. A session
persisted as ``chat-lite`` would have fallen through to the default
35B model, silently defeating the 4B preset.
Tests:
- 7 new tests: 2 alias-resolution (``get``, ``create_agent``), 1 for
``resolve_model`` via alias, 1 for ``canonical_id``, 3 for the
session-kwargs invariant + a source-shape regression test that
fails if the streaming branch is ever refactored back to forwarding
``rag_file_paths`` to the factory.
- Updated ``test_agents_router`` mock registry to use ``gaia-lite``.
- Renamed ``test_chat_lite_*`` → ``test_gaia_lite_*`` in registry tests.
93/93 related tests pass. Frontend ``npm run build`` clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Bring this branch up to date with the v0.17.4 release window on main, including the model-id resolution fixes (#841/#842) that overlap our Settings Active-Model thread. Conflict resolution (single file, two call sites in _chat_helpers.py): both branches changed the registry.create_agent() invocation. Main introduced _build_create_kwargs() to handle custom_model + DB-default model omission for #841/#842; this branch added _session_agent_kwargs() to forward rag_documents/library_documents/allowed_paths/ui_session_id into registry-built agents. The two helpers have disjoint key sets, so the resolution is to expand both: model_id/silent_mode/debug from _build_create_kwargs, session context from _session_agent_kwargs. The regex shape-test in test_chat_helpers.py was anchored on the old "model_id=model_id, streaming=True" prefix; reanchored to the streaming=True ... _session_agent_kwargs( pattern to track the new call-site shape.
Qwen3-4B-Instruct-2507 was a reasonable interim default but Google's Gemma 4 E4B is a better fit for the lite agent's mission: ~4B effective params, 128K context, natively multimodal, Apache 2.0. Same memory footprint (~2.7 GB Q4 weights, 5 GB total) — strictly better trade-off on quality, license, and forward-compatibility with PR #865's universal Gemma 4 transition. Fallback: Gemma-3-4b-it-GGUF for Lemonade catalogs that haven't picked up the Gemma 4 drop yet. Side fix while in this code: factory's setdefault now reads the primary from the registration's models list (single source of truth) rather than hardcoding the same string twice. Without this, the "Fallback: ..." comment on the registration was a lie at runtime — if the primary wasn't in the catalog, the factory still hardcoded it instead of walking the list. Test plan: tests/unit/agents/test_registry.py covers the 4B-class invariant (case-insensitive now to accommodate Gemma 3's lowercase "4b" naming), the factory preset, and the chat-lite legacy alias path.
Brings in PR #865 (Gemma 4 E4B universal default + native tool_calls priority + Lemonade v10.1.0 port flip 8000→13305) on top of our existing gaia-lite work. The two PRs are complementary: #865 sets the global LLM/VLM default; this branch sets gaia-lite's preset. Conflict resolution ------------------- src/gaia/llm/lemonade_manager.py Both branches changed the module header. Ours added a re-export pattern (__all__ + ``from lemonade_client import DEFAULT_CONTEXT_SIZE``) so DEFAULT_CONTEXT_SIZE has a single source of truth. Main flipped the default port 8000→13305 for Lemonade v10.1.0. Resolution keeps both: the re-export pattern is preserved and the port is updated. Test updates required by stricter pre-flight semantics ------------------------------------------------------ This branch's _maybe_load_expected_model + _ensure_model_loaded changes tightened two behaviours that the existing test suite expressed against the old loose semantics: tests/unit/test_chat_preflight.py Pre-flight now requires the EXPECTED model to be active (not just any LLM) and its ctx_size ≥ 32K. Updated _model() helper to accept name + ctx_size kwargs; the four "skips load" tests now load a health entry whose model_name matches the expected model_id and whose ctx_size is at the 32K floor. Without this, the test fixture "test-llm" mismatched the expected "Qwen3.5-35B-A3B-GGUF" and tripped the wrong-model reload branch our PR added. tests/unit/test_lemonade_model_loading.py _ensure_model_loaded now defaults ctx_size to DEFAULT_CONTEXT_SIZE (32768) for unknown models, fixing the silent-empty-stream regression where Lemonade's default 4096 ctx truncated ChatAgent's >7K-token system prompt. Two assertions updated from ctx_size=None → 32768. All affected tests pass; lint clean.
These were marked "known flakies, pre-existing on main" in the merge PR, but every one was a real test bug worth nailing down rather than papering over. All three reproduced on bare main HEAD. test_sse_confirmation (3 tests) Polled ``handler._confirm_result is None`` to detect when the worker thread had registered itself. But _confirm_result is initialised to ``False`` (not None), so the polling loop exited immediately — resolve fired before the worker's confirm_tool_execution set up _confirm_event, and the worker's own setdefault then overwrote the resolved state with a fresh unset event. Net result: the worker waited for an event that no one would ever set, hit the internal 90 s confirmation timeout, and the test failed with "thread still alive". Fix: poll ``handler._confirm_event is None`` instead. _confirm_event starts as None and only becomes non-None inside confirm_tool_execution, so it correctly tracks the registration moment. test_semaphore_exhausted_returns_429 Created a SECOND asyncio event loop with ``asyncio.new_event_loop()`` and acquired the semaphore on it, then handed the half-locked semaphore to TestClient (which runs on its OWN loop). ``asyncio.Semaphore`` doesn't promise cross-loop sanity — the waiter list is loop-bound, so acquire() on TestClient's loop saw inconsistent state under contention. Fix: use ``Semaphore(0)`` — exhausted from birth, no second loop. Plus patch ``asyncio.wait_for`` to a 0.2 s timeout in the chat router so the test goes from 60 s → 0.6 s. test_llm_command_with_server Health check accepted any 200, even when ``all_models_loaded == []``. Worse: even with a model loaded, ``gaia llm`` defaults to whatever the global default is — post-PR-#865 that's Gemma-4-E4B-it-GGUF. CI runners almost never have Gemma preloaded, so Lemonade returned 500, the OpenAI client retried with exponential backoff, and the subprocess timed out at 60 s. Fix: extend the health check to require at least one ``llm``/``vlm`` in ``all_models_loaded`` and return that model's name. The test then passes ``--model <loaded_one>`` so we don't trip the auto-load on a model the runner doesn't have. Verified: full unit suite 1630 passed / 0 failed / 15 skipped.
The "download required model" flow used to be a black box: click Download,
banner says "Downloading…" with a spinner, then minutes later either the
banner disappears (success) or the user gets a generic "Loading AI model"
that hangs at 80 s with no diagnostic. On a 5–6 GB pull over a slow link
this looks like the app froze.
Three threads, all driven from data Lemonade already emits:
* Live download progress (Lemonade /v1/pull SSE → /api/system/status)
POST /v1/pull with stream=true emits per-file progress events with
bytes_downloaded / total_download_size / file_index. We hold one
streaming POST per active download in _stream_lemonade_pull and feed
the latest event into an in-memory map keyed by model_name. The
existing system-status poll cycle picks it up — no new polling
channel, no SSE pass-through endpoint to maintain.
Handles the three terminal states (success / Lemonade error /
connection blowup) and TTL-evicts the entry 30 s after completion
so a fast download is still observable by one poll cycle.
* Auto-load after download
_stream_lemonade_pull schedules _auto_load_after_download once the
pull's "complete" event arrives. Issues /v1/load with the standard
32K ctx so the next chat doesn't hit "ctx too small" reload, and
runs in a separate task so the download stream's TTL eviction
fires on schedule rather than waiting on the load.
* Banner shows real progress, top-priority during a pull
ConnectionBanner now renders the download case BEFORE every other
check (init banner, dismissed state, active-conversation
suppression). Burying it under "Preparing AI system…" was the
actual symptom users hit during a download — the system isn't
"preparing", it's literally pulling 5 GB. Banner shows a 100-px
progress bar + "47% · 2.81 / 5.97 GB · gemma-4-E4B-it-Q4_K_M.gguf"
instead of a bare spinner, with an error variant that surfaces
Lemonade's structured error message and a Retry action.
* Size hint sourced from the catalog
SystemStatus now exposes default_model_size_gb (from Lemonade's
/models response). Both ConnectionBanner Case 3 and WelcomeScreen
drop the hard-coded "(~25 GB)" in favour of "(~5.0 GB)" or
whatever the current default actually is — that string was a
stale remnant from when the universal default was Qwen3.5-35B.
Gemma 4 E4B is the right gaia-lite primary on Linux/Windows where Lemonade's AMD GPU/NPU paths bundle a llama.cpp build that supports the gemma4 architecture handler. On macOS, Lemonade v10.2.0 pins the Metal bundle to llama.cpp b8460 which predates that support (gemma4 landed in b8637 / ggml-org/llama.cpp#21309) AND actively reverts any local binary swap on restart. Net effect: Gemma 4 was unloadable on Mac with no path forward except waiting on a Lemonade pin bump (tracked at lemonade-sdk/lemonade#1741) — and chat hung silently in the meantime. This branch on macOS: _GAIA_LITE_MODELS = ["Gemma-3-4b-it-GGUF", "Gemma-4-E4B-it-GGUF"] Linux / Windows keeps Gemma 4 first as before. Once Lemonade ships the pin bump, ``resolve_model`` picks Gemma 4 up automatically the moment the catalog reports it loadable — no follow-up code change needed (the fallback list is the same on both platforms, just re-ordered). Test plan: tests/unit/agents/test_registry.py uses ``_EXPECTED_PRIMARY`` sourced from ``platform.system()`` so the existing four assertions (prefers_4b_model, factory_presets, chat-lite alias create, chat-lite alias resolve_model) keep working on every CI runner regardless of OS. End-to-end verified locally on M4 Pro: gaia-lite session, "What can you help me with?" prompt → "I help with document Q&A, file analysis, code editing, data processing — drop something in and I'll dig in." at 58 tok/s (Gemma 3 4B Q4_K_M, 32K ctx).
…-lite) The eval runner previously had no way to target a non-default agent — the MCP create_session tool only accepted a title, even though the underlying REST endpoint already supports agent_type. This blocked evaluating gaia-lite (4B model) since scenarios always ran against the backend's default Chat Agent. Three coordinated changes: - MCP tool create_session now accepts an optional agent_type kwarg that passes through to POST /api/sessions. - AgentEvalRunner accepts agent_type and threads it into the simulator prompt, instructing the eval agent to bind every session to the chosen agent registration ID. - New CLI flag: gaia eval agent --agent-type gaia-lite (recorded in the scorecard config for traceability). Verified via REST: POST /api/sessions with agent_type=gaia-lite returns agent_type=gaia-lite on subsequent GET. Audit-only run still passes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… tool-call The personality eval category against gaia-lite on Gemma-3-4b-it-GGUF scored 1/3 PASS (avg 4.6/10), with both failures rooted in the same issue: Gemma 3 4B emits tool calls as Gemini-style ```tool_code``` text blocks rather than OpenAI-compatible function-call objects. The GAIA agent runtime never parses or executes these, so RAG and file tools silently fail and the model fills in with hallucinated answers (see trace eval/results/eval-20260426-061705/traces/no_sycophancy.json, 1.3/10 — pure garbled_output). Qwen3.5-4B-GGUF carries the explicit "tool-calling" label in the Lemonade catalog (alongside "vision" and "hot"). It's 2.91 GB — slightly larger than Gemma 3 4B (3.61 GB on-disk Q4_K_M, but Qwen ships Q4_0) but still well within the gaia-lite memory envelope, and trained on the OpenAI function-call format that ChatAgent's tool dispatcher expects. Linux/Windows continue to lead with Gemma-4-E4B-it-GGUF (which IS tool-calling-labelled) because their Lemonade install ships a llama.cpp build with gemma4 architecture support. The macOS pin remains tracked at lemonade-sdk/lemonade#1741. Test: - tests/unit/agents/test_registry.py::_EXPECTED_PRIMARY updated to Qwen3.5-4B-GGUF on macOS; full registry suite passes (44/44). - 1631-test unit suite green. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two related fixes for the same eval failure mode (Qwen 4B getting ``finish_reason=length`` mid-tool-call on the no_sycophancy scenario): 1. **Output budget too tight.** ``AgentConfig.max_tokens`` was 4096, which Qwen3.5-4B exhausted while serialising long tool-call argument strings (1000+-char ``summary_type`` blob in the case the eval surfaced). With our 32K ctx_size and a ~7.7K-token system prompt + history, 8K of output budget leaves plenty of room and still keeps ~24K for input. Going much higher would steal from input-history budget without measured gain. 2. **Misleading error message.** When the cap was hit we raised "Increase --ctx-size for model X" — but ``finish_reason=length`` from the OpenAI completions API specifically signals the *output token cap*, not the context window. ctx_size and max_tokens are separate limits, and conflating them sent users off chasing the wrong knob (the user had already loaded at 32K ctx). The new error names ``AgentConfig.max_tokens`` directly. Both are agent-runtime changes (affect ChatAgent generally), not gaia-lite specific. Test suite green; full registry + chat-ui suites pass with no behaviour-coupled assertions to update.
…op session links
Bundles four user-asked tweaks discovered while iterating on gaia-lite:
UI / Agent UI
* ChatView.tsx — chat header model badge now shows the loaded
context window inline ("Qwen3.5-4B-GGUF · 32K"). Title attr carries
the full "context window: NN,NNN tokens" so a hover gives the
precise number. Mismatched ctx (e.g. eval reload at 4K) is now
visible at a glance instead of surfacing only as a chat-time error.
* ChatView.tsx + Sidebar.tsx — dropped the "#abc1234" session-link
pills from both the chat header and every sidebar row. They were
clipboard-copy hash badges; nobody used them and they ate the row.
* MessageBubble.tsx — every message bubble (user + assistant) now
has a ``title`` tooltip with the full absolute send timestamp.
Previously only assistant bubbles had this via the stats footer.
* ChatView.css — small ``.model-ctx-size`` rule so the suffix is
dimmer than the model name (eye lands on model first).
Chat agent personality
* src/gaia/agents/chat/agent.py — replaced the 2-example "RIGHT"
list in the GREETING RULE with 10 varied openers + an explicit
"VARY YOUR PHRASING" rule. The original prompt's recency bias
pinned the model on a single canned "Hey! What are you working
on?" every conversation; the rotation list breaks that pattern
while keeping the warm/curious/no-feature-pitch invariant.
Added a new WRONG example calling out the lock-in behaviour
explicitly so the model can self-detect it.
Eval discipline
* CLAUDE.md — new rule: "Run agent evals SERIALLY, never in
parallel." Today's session lost three eval runs to two
concurrent ``gaia eval agent`` invocations race-evicting each
other's models out of Lemonade's single-tenant slot, surfacing
as bogus 4K-ctx errors and INFRA_ERROR. Documents the exact
failure modes + the ``ps aux | grep "gaia eval" | wc -l`` =
0 sanity check before kicking off a new run.
Backend changes confined to comments + system-prompt strings —
agent runtime contracts unchanged. 212 unit tests pass; lint clean;
frontend bundle rebuilt.
The runaway-eval failure mode the user kept hitting today: a parent
agent in --fix mode shells out a second `gaia eval agent ...` while the
first is still running, both invocations talk to the same Lemonade
Server, Lemonade has a single-tenant LLM slot, the runs race-evict each
other's models, and the whole thing surfaces as nondeterministic
`n_ctx=4096` overflows or `model_load_error: llama-server failed to
start`. CLAUDE.md now documents the rule; this commit enforces it.
src/gaia/eval/runner.py
* `_acquire_eval_lock()` — context manager around fcntl.flock on
/tmp/gaia-eval-agent.lock. LOCK_EX | LOCK_NB so a second invocation
fails fast (exit 2) with an actionable message naming the holder
PID and run age, not by hanging.
* Stale-lock recovery: if the holder PID is gone, the lock file is
reclaimed automatically (no manual rm needed).
* Escape hatch: GAIA_EVAL_NO_LOCK=1 skips the guard for unit tests
or callers that genuinely manage Lemonade out of band.
* AgentEvalRunner.run() now wraps the per-scenario loop in the
lock; audit_only mode skips it (no Lemonade contention).
Body extracted to _run_locked() so the wrapper stays thin.
UI follow-on (separate concern, same touch):
src/gaia/apps/webui/src/components/AgentActivity.css
* The "N steps · M tools" expand-activity bar used to render as a
full-width terminal panel with border + uppercase 11px text on
every assistant turn — visually loud for content the user rarely
expands. Now it's an inline 10px chip at 0.55 opacity, expanding
to full opacity + bg + border on hover/focus, and forced to full
opacity when the run is active or has errors (states the user
actually needs to notice).
Verification: subprocess test confirms two concurrent invocations
produce exit-2 + clear error in the second one. Lint clean.
Every GAIA reply was rendering with the same vertical AMD-red border
+ red-tinted background as ``.msg-error``, so a normal multi-turn chat
read as a stack of warnings. Reserved that visual language for actual
errors only.
src/gaia/apps/webui/src/components/MessageBubble.css
* .msg-assistant: dropped the ``border-left: 2px solid var(--amd-red)``
that was duplicating .msg-error's left rail. Assistant messages now
distinguish themselves from user messages purely via the elevated
panel background, the GAIA avatar + name in the header, and the
left-aligned text direction. Subtle is the point — a long thread
should read as a calm conversation, not warnings.
* Removed the ``[data-theme="dark"] .msg-assistant`` override that
layered ``rgba(237, 28, 36, 0.02)`` (red haze) on top of the
already-neutral --bg-assistant-msg variable in dark mode.
* Avatar dark-mode treatment: ``border-color: rgba(237,28,36,0.25)``
and ``box-shadow: 0 0 8px rgba(237,28,36,0.12)`` (red glow) →
neutral ``var(--border)`` + a 1-px white-tinted ring. Brand red
is still present in the small "GAIA" name text + the user-avatar
fill; just not bleeding into every UI surface.
Error styling unchanged — .msg-error still owns the AMD-red left
border + red background tint, and is now the only place that visual
appears so it actually stands out.
Pure CSS — no behavioural change. Bundle rebuilt; refresh to see.
Three connected polish passes on the assistant bubble:
src/gaia/apps/webui/src/components/MessageBubble.css
* **Rounded card.** .msg-assistant was a hard-edged horizontal strip;
now it's a 14-px-radius panel that visually sits *inside* the chat
column instead of cutting it horizontally. ``width: calc(100% - 16px)``
inset so the rounding actually shows.
* **3D depth.** Layered box-shadow (4 stops: inset top-edge highlight,
crisp 1-px contact, soft mid-distance, wider ambient) for a subtle
elevation. Hover lifts ~1 px and softens the ambient — small enough
not to read as a "click me" CTA, big enough to feel responsive.
Dark-mode variant uses heavier alphas (0.30–0.55) because shadows
on near-black backgrounds disappear at typical light-mode values.
* **Softer fade-in.** Replaced the 200 ms slide+scale with a 380 ms
fade+drift+deblur (assistant: 450 ms). cubic-bezier(0.22, 0.61, 0.36, 1)
eases out smoothly. Dropped the 0.99 scale step — scaling rounded
cards causes brief subpixel blur on retina. Added a 2-px filter:blur
transition that mimics an "image developing" effect on entry —
very subtle but adds polish without slowing perception.
User messages unchanged: still flat, transparent, right-aligned. Only
the GAIA reply panel is the rounded 3D card. Shadow tokens are pure
CSS — no extra DOM, no JS, ~zero runtime cost.
Same direction as the GAIA message card (b5289a3): rounder, lighter, less red bleed, subtle elevation on the active state. src/gaia/apps/webui/src/components/Sidebar.css * Session items - radius-md (8px) → radius-lg (10px) for softer corners - Padding tweaked +1px vertically so rows don't feel crammed - Hover now adds a faint border-light ring in addition to the bg-hover fill — gives shape to the row before clicking - Active row's box-shadow was a 10-px red glow + inset 28-px red haze; replaced with a calm multi-layer (top highlight + contact + mid) elevation in light mode, deeper black-alpha shadows in dark mode. Brand-red is still present in the left-edge indicator and a 6%-alpha bg tint, but no longer bleeding into the surrounding sidebar. - Press-feedback scale tightened from 0.982 → 0.985 (less "trampoline", more "tap"). * Search input - radius-md → radius-lg, matching the session items - Now sits on a tertiary background with an inset hairline shadow, reading as gently recessed (the inverse of the session-active which reads as raised — coherent stack metaphor) - Focus ring: was border 0.4 alpha + 12-px red glow ("warning" vibe); now a soft 3-px 0.08-alpha brand-red halo + 0.35-alpha border. Reads as "focused", not "errored". * Bottom status bar - Tiny 1-px inset top highlight in addition to the existing border-top — gives a soft "lip" between the scrolling session list and the fixed status row, matching the layered-card feel. Pure CSS; no DOM changes. Bundle rebuilt.
The textarea had a custom 10×18 px solid-AMD-red block cursor with a
0.5-alpha red glow blinking at 1 Hz on every focus. On a screen the
user is staring at all session, that's an obvious "warning indicator"
treatment for a primitive that should be invisible until interacted with.
src/gaia/apps/webui/src/components/ChatView.tsx
* Removed ``getCaretXY`` helper, ``_computedStyleCache``, the
``caret`` state + ``updateCaret``/``setCaret`` callbacks, the
inline ``caretColor: 'transparent'`` override, and the
``<span className="input-cursor" />`` element. The textarea now
relies on the browser's native caret like every other text input.
* onFocus/onBlur/onSelect handlers tied only to caret tracking are
gone; nothing else cared about that state.
src/gaia/apps/webui/src/components/ChatView.css
* Removed the ``.input-cursor`` rule. ``@keyframes cursorBlink``
stays in styles/index.css — it's still used by AgentActivity and
MessageBubble streaming indicators (those are in-line content, not
always-on UI chrome, so the blink is appropriate there).
Side benefit: drops a per-keystroke ``requestAnimationFrame`` +
mirror-div DOM creation that was running on every input change.
The previous "softened" active state still carried two pieces of the
error visual vocabulary:
1. A vertical AMD-red gradient bar on the left edge (::before
pseudo-element) — same shape and color as .msg-error's
left rail. Active row read as "this row is broken".
2. In dark mode: rgba(237,28,36,0.06) background + 0.12-α red border
— selected row looked like a tinted warning band.
Both gone. Active state is now communicated purely via elevation +
neutral background lift, matching the GAIA message-card vocabulary
exactly (the same 4-stop layered shadow: inset top highlight,
contact, mid-distance, ambient).
src/gaia/apps/webui/src/components/Sidebar.css
* .session-item::before — entire pseudo-element + the hover/active
transform-scaleY rules removed. The selected row no longer has
a red strip; selection is the elevation + bg-active.
* .session-item.active light-mode shadow stack matched 1:1 to
.msg-assistant for visual coherence.
* .session-item.active dark-mode background switched from
rgba(237,28,36,0.06) → rgba(255,255,255,0.04). Border color
likewise from rgba(237,28,36,0.12) → rgba(255,255,255,0.08).
Heavier black shadows for the dark-on-dark elevation read.
* sessionActivateDarkBg keyframe (which animated a red
background flood + inset red glow on activation) deleted.
sessionActivate keyframe simplified — the 1.5-px overshoot
bounce removed for a calmer settle.
Brand red is now reserved for: the small "GAIA" name text in
message headers, the user-avatar fill, and .msg-error. That's it.
…color
Two threads:
(1) GAIA auto-titling (the running chat agent renames its own session).
src/gaia/ui/_chat_helpers.py
* New ``_maybe_update_session_title`` helper. Fired fire-and-forget
after every assistant turn finishes; calls the same Lemonade chat-
completion endpoint to generate a 3-6 word tab title.
* Trigger rules:
- Title is one of the defaults (New Chat / New Task / Untitled
/ Chat / empty) → first-response pass
- User message has ≤ 0.15 word-overlap with current title AND
is ≥ 25 chars → topic-shift pass
* Skipped when title starts with "Eval:" (eval framework owns those)
and throttled to one update / 30 s / session so concurrent fires
don't pile up.
* LLM call uses temperature 0.3 + max_tokens 24, stripping common
title artifacts ("Title:", quote-wrapping, trailing punctuation)
that small models add despite the instruction.
* Background task reference pinned in _active_sse_handlers under a
``_titlebg:<sid>`` key so GC doesn't kill it mid-flight; cleared
in the done callback.
src/gaia/ui/routers/chat.py
* Same hook in the non-streaming path immediately after
db.add_message(assistant). Wrapped in try/except so an auto-title
failure can never block the user's response.
(2) Neutral selection color.
src/gaia/apps/webui/src/styles/index.css
* ::selection background: rgba(237, 28, 36, 0.18) (AMD red) →
rgba(56, 132, 255, 0.22) (cool blue). Selecting any text used to
paint a red highlight on top of red errors / red focus rings /
formerly-red active session — every interaction read as a warning
state. Standard cool-blue selection is what users expect.
Tests: 46 chat-ui unit tests pass; lint clean.
…lures
The chat path had no recovery for the three failure modes the user
keeps hitting in the UI:
* "No model loaded: <model>" — Lemonade evicted between turns
* "request (N tokens) exceeds the available context size (M)"
— wrong-ctx model load
* "Network error: CURL Timeout was reached" — Lemonade busy/hung
Each one previously surfaced as a wall of raw JSON inside the chat
bubble and required the user to hand-restart the model. Now:
src/gaia/llm/providers/lemonade.py
* Added typed exceptions ``LemonadeError``,
``LemonadeModelNotLoadedError``, ``LemonadeContextOverflowError``,
``LemonadeNetworkError``. Each carries (a) a short ``.user_message``
suitable for direct chat-bubble rendering and (b) the raw payload
on ``.payload`` for diagnostic logging. Class-level ``retryable``
flag declares whether the chat layer should auto-retry.
* ``_classify_lemonade_response`` walks the response envelope —
including the nested ``details.response.error`` shape Lemonade
uses for backend_error wrappers — and returns the matching typed
exception or a generic LemonadeError when the shape is novel.
* The single ``raise ValueError(f"Unexpected response format from
Lemonade Server: {response}")`` at the dict-of-choices guard now
routes through the classifier, so callers see typed errors instead
of a string-blob ValueError.
src/gaia/ui/_chat_helpers.py
* ``_classify_chat_exception`` walks the cause chain AND the
stringified message text to detect typed errors even when AgentSDK
wraps the original LemonadeError in a generic ValueError /
RuntimeError (which it does in several paths).
* ``_run_agent`` (the streaming worker thread) now does ONE automatic
retry on retryable Lemonade errors. On a model-not-loaded /
network-error first failure: forces a fresh ``_maybe_load_expected_model``
at our 32K ctx, emits a "Model reloaded — retrying..." status SSE
so the user sees the recovery (not silent retry), and re-runs
``agent.process_query``. If THAT fails too, the friendly
user_message is surfaced instead of the raw exception.
* The catch-all ``except Exception`` block now prefers
``LemonadeError.user_message`` over ``str(e)``, so even
non-retryable errors (context overflow) come through as a
plain-English explanation instead of a JSON blob.
Tests: full chat-ui suite (46 tests) passes; lint clean. The retry
itself is exercised end-to-end the next time you trigger a model
eviction — start a fresh chat session and you'll see the recovery
status rather than the wall-of-JSON failure mode.
…t path Layer 2 + 3 of the chat-resilience push (continuation of 0795a5d). src/gaia/ui/_chat_helpers.py * **Pre-flight ctx_size guard.** ``_maybe_load_expected_model`` previously checked ``active_ctx and active_ctx < N`` — short-circuit evaluation meant a 0-or-missing ctx slipped through, leaving a broken model in place. New guard explicitly treats missing ctx as "needs reload" so a model loaded with no recipe_options.ctx_size (which is exactly the broken state we want to recover from) gets re-loaded at our 32K canonical. * **Bounded reload timeout.** Pre-flight now passes ``timeout=120`` to ``LemonadeClient.load_model`` instead of inheriting the default DEFAULT_MODEL_LOAD_TIMEOUT (12000 s / 200 min). Cold load of a 4B GGUF on consumer hardware fits in <60 s; if it hasn't completed in 120 s something is genuinely wrong and we'd rather surface the failure than block the chat thread for hours. * **Non-streaming chat now retries identically to streaming.** The one-shot retry on transient Lemonade errors (model evicted between turns, network blip) was only in the streaming worker before; the non-streaming path raised straight to the user. Mirrored the same classify → reload → retry sequence in ``_get_chat_response`` so both paths recover the same way. * **Friendly error mapping in non-streaming.** The catch-all ``except Exception`` in ``_get_chat_response`` was returning a stock "I'm having trouble connecting..." string regardless of the actual failure mode. Now it prefers the typed ``LemonadeError.user_message`` (e.g. "This conversation got too long for the model's context window"), falling back to the stock copy only when classification fails. Together with 0795a5d, this closes the three failure modes the user keeps hitting in the UI: * Wrong-ctx model load (now caught by tighter guard, reloaded at 32K) * Mid-conversation eviction (caught by retry on both streaming/non-streaming) * Lemonade hang during reload (bounded by 120-s timeout instead of 200 min) Tests: 60 chat-ui + preflight tests pass.
NameError regression introduced in 1a807d2 (auto-titling commit) — the streaming-path background task at the bottom of ``_stream_chat_response`` called ``_effective_model(agent, model_id)``, but ``agent`` lives inside the producer thread's local scope and isn't visible to the outer generator. Every streaming chat turn was therefore raising NameError after the response otherwise completed, which the catch-all then surfaced as "Sorry, something went wrong on my end". src/gaia/ui/_chat_helpers.py * Capture ``session_model = model_id`` in the outer scope right after custom-model resolution; reference that in the auto-title task instead of the inaccessible ``agent``. * Comment explains why the indirection — same model id the pre-flight + agent factory used, just made visible to the post-stream cleanup. Verified by re-running a fresh streaming chat turn end-to-end against gaia-lite: 3.1 s round-trip, ``done=True``, no error events, response "4" persisted correctly. Found via the chaos-test harness from the same reliability push — which was the point of layer 4.
…bling raw error Small models (4B-class) occasionally emit malformed native tool_calls envelopes — e.g. a 1000+ char summary_type argument that gets truncated mid-string. Previously _parse_llm_response raised ValueError uncaught, the exception bubbled through the chat helper, and the user saw: Agent error: Malformed native tool_calls envelope: Expecting ',' delimiter: line 1 column 220 (char 219) The fix wraps the parse call in process_query with a try/except that: 1. Logs the parse error to error_history (type=tool_call_parse_error) 2. Appends a synthetic recovery prompt instructing the model to retry with documented enum values (or fall back to plain text) 3. Continues the loop so the next LLM call has clean conversation 4. After 3 consecutive parse failures, gives up gracefully with a friendly fallback rather than spamming the user Same handler also catches finish_reason=length (tool-call truncated mid-arguments) and parallel tool_calls (NotImplementedError), since both manifest as the same user-facing failure mode. Surfaced by GAIA eval baseline scenario: - personality/honest_limitation Turn 2: 1000+ char summary_type arg - rag_quality/negation_handling Turns 1-2: finish_reason=length Tests: tests/unit/agents/test_parse_error_recovery.py — covers the parse-error path, the 3-strikes graceful giveup, and the underlying ValueError still raises from _parse_llm_response itself.
Two failure modes surfaced by GAIA eval baseline against gaia-lite on
Qwen3.5-4B-GGUF:
1. Context-overflow mid-loop (5 of 8 baseline failures)
When a multi-step ReAct turn accumulates tool results from several
search_file/index_document calls, the cumulative `messages` array
eventually exceeds the model's 32K context window. Lemonade returns
exceed_context_size and the chat helper surfaces "This conversation
got too long for the model's context window. Start a fresh task..."
Fix: wrap the LLM-call try/except in process_query (both streaming
and non-streaming branches) with a retry loop. When we detect a
context-overflow exception (substring match on the upstream error
text — typed errors get wrapped by AgentSDK), trim the messages
array to {first user input + last 4 entries} and retry ONCE. If
the retry also fails, return a friendly message asking the user to
start fresh — no more raw exception leaks.
Surfaced by:
- tool_selection/smart_discovery T1 (search → index → blow up)
- error_recovery/file_not_found T1+T2 (failed index → deep search)
- error_recovery/search_empty_fallback T1
- captured/captured_eval_smart_discovery
2. list_windows had no macOS branch
The tool returned "Window listing not available. Install pywinauto
(Windows) or wmctrl (Linux)." on Mac, and the agent reported "I
can't list open windows on this Mac" — judged FAIL.
Fix: add a Darwin branch that uses osascript with System Events to
return the visible (non-background) processes — equivalent to what
the user sees in Mission Control. No new dependency: osascript
ships with macOS.
Surfaced by web_system/list_windows.
Tests: extended tests/unit/agents/test_parse_error_recovery.py with
TestProcessQueryRecoversOnContextOverflow — covers the trim+retry
success path AND the after-retry-still-fails graceful fallback.
…keep latest
Previous trim strategy (keep first + last 4 messages) didn't help when the
final tool result itself was huge (e.g. RAG query returning many KB of
chunks). After trim we still couldn't fit, so the agent gave up.
New _shrink_messages_for_overflow helper:
- Keep the original user query intact
- Keep the LATEST tool result intact (model needs it to answer)
- Replace older tool results with a tiny stub
("[tool result omitted -- context overflow recovery]")
- Truncate verbose assistant chain-of-thought to 800 chars
This preserves the structural shape of the conversation so the model
still understands what tools have been called, but drops the bulk of
the bytes. Same shrink applied in both streaming and non-streaming
branches of process_query.
Surfaced by tool_selection/smart_discovery T1: agent indexed handbook
correctly, but the indexed-content tool result + chain-of-thought
combined to push past 32K. Old trim retained both and still failed;
new shrink keeps just the latest result so retry succeeds.
Tests still pass — the existing context-overflow tests now exercise
the new path implicitly via the same "raise then succeed" pattern.
The chat helper has a one-shot retry that calls _maybe_load_expected_model
to reload the model at the canonical 32K ctx — but only fires for errors
where ``retryable=True``. LemonadeContextOverflowError was always non-
retryable, so when a previous load left Qwen3.5-4B at 4096-ctx (e.g.
after an embedding model swap or auto-load default), the agent surfaced
"This conversation got too long" to the user even though the actual
remedy was a model reload.
Now LemonadeContextOverflowError.retryable is set dynamically based on
the reported n_ctx:
- If n_ctx < 32768 → retryable=True. The model was loaded with the
wrong ctx_size; the chat layer's one-shot retry will reload at 32K
via _maybe_load_expected_model and the same prompt will fit.
- If n_ctx == 32768 → retryable=False. This is a genuine "conversation
too big" situation; retry won't help, surface the friendly message.
Two parsing paths updated:
- _classify_lemonade_response (provider-side, structured payload):
reads n_ctx from nested error.details.response.error.n_ctx
- _classify_chat_exception (chat-layer fallback for when AgentSDK
re-raises with str(original)): regex-extracts the ctx number from
the textual message ("context size (4096 tokens)")
Surfaced by tool_selection/smart_discovery — backend was loaded with
n_ctx=4096 after a fresh restart sequence, the original handbook+RAG
turn legitimately needed ~18K tokens, and we were stuck refusing the
turn instead of reloading.
…load The previous commit made LemonadeContextOverflowError retryable when n_ctx < 32K, but the chat helper's reload-and-retry never fired because the agent's own try/except in process_query catches the exception first and runs its in-loop trim-and-retry instead. The trim doesn't help when the real issue is a 4K-loaded model — the second request goes to the same broken backend. Fix: detect the wrong-ctx-loaded sub-case in agent.py (substring match on "context size (4096|8192|16384" / "n_ctx': 4096|8192|16384") and RE-RAISE instead of trimming. This bubbles the typed error up to the chat helper, where _classify_chat_exception now reads it as retryable and triggers _maybe_load_expected_model to reload at 32K before the chat layer's own one-shot retry. Genuine "conversation too big to fit even at 32K" still goes through the trim+retry+friendly-fallback path as before. Both streaming and non-streaming branches updated symmetrically.
…lope The OpenAI tool_call spec says ``function.arguments`` is a JSON string, but llama.cpp 4B-class models occasionally emit it as a pre-parsed dict. ``json.loads(dict)`` raised TypeError which our recovery layer didn't catch (it only listened for ValueError / NotImplementedError), so the exception bubbled out as: Agent error: the JSON object must be str, bytes or bytearray, not dict Surfaced by tool_selection/smart_discovery T1 after the previous context-overflow fix unblocked a path that was previously masked by that earlier failure. Now we accept either shape: - str/bytes → json.loads as before - dict → use directly - empty/None → empty dict - anything else → raise ValueError with a recovery-friendly message so the parse-error retry kicks in
The substring detection ("context size (4096", etc.) only fires when the
raw payload is preserved in the exception. When AgentSDK re-raises with
the typed LemonadeContextOverflowError's friendly user_message
("This conversation got too long..."), the n_ctx detail is gone, so
substring matching always missed.
Fix: when a context-overflow fires AND substring match doesn't say
"wrong ctx", probe the Lemonade health endpoint via httpx to read the
LLM's actual ctx_size. If < 32K, treat it as wrong-ctx and re-raise so
the chat helper reload-and-retry kicks in.
The probe times out fast (3s) and returns False on any failure, so the
caller cleanly falls through to in-loop trim if the probe is unreliable.
Surfaced by another smart_discovery rerun: ctx was 4096, my earlier
substring guards missed because str(exception) was already friendly.
The 19 real_world scenarios were SKIPPED_NO_DOCUMENT because the referenced corpus files did not exist on disk. Add a deterministic generator that authors all 19 documents from a single Python data structure, idempotent on re-run. Documents are synthetic paraphrases (no copyrighted source text) but contain every ground-truth fact each scenario references. XLSX files are flattened by RAGSDK._extract_text_from_xlsx into row-keyed prose that surfaces SKUs, totals, and notes for the chunker. Re-run with: python eval/corpus/gen_real_world.py
…ope questions
The real_world eval surfaced a recurring failure pattern on Qwen3.5-4B:
when a turn asked for a fact unambiguously not in the indexed document
(e.g. GDPR Article 17 *penalty* — penalties are in Article 83;
RFC 7231 *max body size* — not defined; Python *3.12* release date in a
3.11 doc), the agent either
1. Reasoned silently for 600+ seconds without ever calling a tool, then
timed out at the Lemonade CURL boundary; or
2. Said "not in this document" and then *immediately* supplemented with
a training-data estimate ("but approximately 60 days"), failing the
null-expected-answer success criterion.
This adds an OUT-OF-SCOPE QUESTION RULE under the existing DOCUMENT
SILENCE RULE block. It is targeted at the exact failure shape:
- One query call to verify, never multiple speculative chains.
- "Not in document" is the complete answer — supplementing with
training-data estimates is explicitly banned.
- Cross-reference questions (Article-17 vs Article-83, 3.11 vs 3.12)
must redirect the user to the correct source rather than estimating.
Why this and not a model-side fix (e.g. ``enable_thinking=False`` or a
thinking-token budget): a prompt rule lands today and the eval can
re-run immediately, while a model-config change requires Lemonade
plumbing work that doesn't gate this PR. Both can co-exist later.
The two scenarios that previously FAILed on this exact pattern
(``gdpr_article17_erasure`` turn 3, ``nist_csf2_framework`` turn 3) and
the three that ERRORed because of the Qwen reasoning loop
(``python311_release_notes``, ``raspberry_pi4_datasheet``,
``rfc7231_http_spec``) are being re-run with this fix in place.
SummaryTargeted 14-line addition of an Issues Found🟢 Minor —
|
b2a952f to
62d0d2f
Compare
Inherited via main merge from amd#919, which introduced both a regression test asserting AttributeError must surface and a broad-except wrapper that swallowed it. Same commit, opposite intent — removing the except satisfies the test, the docstring ("Ratchets the Apr-20 review fix"), and the project's no-silent-fallbacks rule. Also drops one stray blank line in the test file to satisfy black. Unblocks PR 921 CI (Code Quality + Unit Tests checks).
Summary
Targeted fix for a recurring failure mode the real-world eval surfaced on Qwen3.5-4B (gaia-lite). When a turn asks for a fact that is unambiguously not in the indexed document, the agent either (a) reasons silently for 600+ seconds and times out at the Lemonade CURL boundary, or (b) says "not in this document" and then immediately supplements with a training-data estimate, failing the null-expected-answer success criterion. This adds one focused rule to the existing DOCUMENT SILENCE RULE block in
ChatAgent's system prompt.Why a prompt rule and not a model-config change
A model-side fix (e.g.
enable_thinking=Falseor a thinking-token budget) requires Lemonade plumbing that doesn't gate the eval today. The prompt rule lands immediately, the eval can re-run, and the two can co-exist later.Threads
OUT-OF-SCOPE QUESTION RULE(single addition toagent.py):Defensive
canonical_idfallback (_chat_helpers.py): wrapsregistry.canonical_id()in a try/except so a corrupted registry can't crash a chat request. Pure dict lookup — the except path is unreachable in normal operation.Failure cases targeted
gdpr_article17_erasure(turn 3)nist_csf2_framework(turn 3)python311_release_notes(turn 3)raspberry_pi4_datasheetrfc7231_http_spec(turn 2)Test plan
python util/lint.py --black --isort— cleanRe-run command (sequential — never parallel against single-tenant Lemonade):