Skip to content

feat(ui): side rail with each answer's sources, files and data flow - #5246

Merged
kovtcharov-amd merged 9 commits into
amd:mainfrom
kovtcharov:claude/ui-side-rail-ledger-4ef9df
Oct 19, 2026
Merged

kovtcharov-amd merged 9 commits into
amd:mainfrom
kovtcharov:claude/ui-side-rail-ledger-4ef9df

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Nothing in a conversation showed whether a turn stayed on this PC, which pages or document passages an answer drew on, or where the files it wrote went. GAIA's main promise is local work, and a cloud model quietly changes that. Now a rail beside the latest answer lists the pages and documents it used (by the attached file's name, not the upload ID). It also lists the files it wrote, with Open and Show in folder, and shows where the model ran: This PC or the named provider. It covers whether documents stayed local, which sites were contacted and the cost. When every web lookup fails, the answer is labelled "Couldn't get live data". Everything comes from the turn's tool calls and the model that actually answered; a location the backend can't determine reads "Not reported", never "This PC".

Local turn (rail beside the answer; a file deleted after the turn shows as "No longer on disk"):

Side rail, local turn

Cloud turn (provider named, passages marked as sent, list-price estimate):

Side rail, cloud turn

At 1000 px the rail folds to a "Sources & details" button:

Side rail folded

Captured with Playwright against the real Agent UI server and built frontend, in an isolated GAIA_HOME. Each turn's summary was built by the real ledger from tool-shaped results and saved to the database, so the rail is the reloaded view. Only the first-run setup check was stubbed, because no local model server was running.

Lands after v0.25.0.

Closes #5222. Closes #5255. Covers #5183 and #5185 for the rail; the UI half of #890.

🔍 Technical details
  • The backend builds a turn_summary from the SSE handler's tool events plus the agent's live _inference_location(). It rides the done event and is persisted in a new nullable messages.turn_summary column, so it survives a reload. If it can't be built, the rail shows the error and the answer is still saved.
  • Open is a new launch mode on POST /api/files/open. It runs after the existing home, symlink and exists checks, and only for documents, data and images. Scripts, programs and HTML/SVG are refused with 400.
  • The ChatView.tsx change is 5 lines: the slot, plus mapping the summary onto live and reloaded messages. AgentActivity is untouched.
  • Cost is a list-price estimate only for Fireworks models (the one rate card GAIA carries); otherwise "Not known".

Test plan

  • pytest tests/unit/chat/ui tests/integration/test_files_router.py (1,667 passed), including the new test_turn_summary.py and the launch-mode tests
  • Full pytest tests/unit: same failures as a clean origin/main run on the same files, apart from one that comes from a local node_modules (wheel package scan)
  • python util/lint.py --all
  • npx tsc --noEmit and npx vitest run (868 passed), including SideRail.test.tsx and ChatView.sideRail.test.tsx
  • Running app: a local turn's summary built by the real backend shows This PC after a reload
  • Running app: a cloud turn (Fireworks AI) via a mocked SSE stream lists pages, documents and files, names the provider and shows the estimate; the rail folds to a button at 1000 px and Open errors are shown
  • Running app: while a turn runs, the rail shows it in progress instead of the previous answer (fix(ui): the side rail shows stale information #5255)
  • Running app: a file deleted after its turn shows as "No longer on disk" with no Open, through the real /api/files/status (fix(ui): the side rail shows stale information #5255)
  • Trial merges of this branch with feat(agent,ui): undo the file changes from a turn #5239, feat(ui): type while GAIA works, see context fill, retry with another model #5241 and feat(ui): chat list shows what needs you, chats queue for the GPU, notification settings #5242, one at a time: tsc, vitest and the UI pytest suites pass. With feat(agent,ui): undo the file changes from a turn #5239, _chat_helpers.py conflicts: keep both helpers, keep its link warning, and use this branch's done_event (with turn_summary) instead of the plain _done_event(...)
  • pytest tests/unit/chat/ui/test_turn_summary.py tests/integration/test_files_router.py and npx vitest run SideRail: page links are http(s) only (backend and frontend), a passage two queries return is counted once, .xml is not openable
  • Running app: a real web-research turn listing its pages. Not run here, because the shared local model server was unavailable; the epic's integration testing of the merged build saw it list duckduckgo.com and nps.gov
  • Running app: a real cloud-model turn. Not run, because no cloud provider is connected and switching would change the global default model

Nothing in a conversation showed whether a turn stayed on this PC, which pages
or document passages an answer drew on, or where the files it wrote went. A
collapsible rail beside the latest answer now shows that, built from the
turn's tool calls and the location of the model that actually answered.

- Sources: pages read (search hits when it only searched) and document
  passages named by the attached file, not the upload copy's ID (amd#5183).
- Files created or changed, with Open and Show in folder (amd#5185). Open uses a
  new launch mode on /api/files/open, limited to documents, data and images.
- This turn: This PC or the named cloud provider, whether documents stayed
  local, sites the web tools contacted, and cost (list-price estimate for
  Fireworks models). An unknown location reads "Not reported", never local.
- "Couldn't get live data" when every web lookup failed.
- The summary rides the done event and is saved per message, so it survives a
  reload; a summary that cannot be built is shown as an error, not dropped.
- Hidden until a turn has a summary; folds into a button below ~1,100 px.

Refs amd#5222, amd#890.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes electron Electron app changes labels Oct 17, 2026
While a new turn ran, the rail kept the previous answer's sources and data
flow under "This answer", and files an Undo removed stayed listed with Open.
Now a running turn shows as in progress, and the rail re-checks the files it
lists (on show, on focus, every few seconds) through a new
POST /api/files/status: a deleted file shows as no longer on disk with no
actions, and one changed since the turn says so.

The ChatView rail test gives every unmocked API call a pending promise, so
views that add calls don't break it.

Refs amd#5255.
The test sent two turns, and a message refetch between them could wipe the
first, so it failed now and then under a full run. It now opens a chat that
already has a finished turn and sends once.
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes (evidence only). The code is ready to merge. The one thing missing is a screenshot of the rail on the PR.

The PR adds a side rail beside the latest answer. It lists the pages and documents the answer used and the files it wrote, and says whether the model ran on this PC or in the cloud. Each answer's summary is built from what its tools actually did, so a model location the backend can't determine reads "Not reported", never "This PC". The summary is saved with the message. The new Open button runs only after the existing home-folder and symlink checks, and it refuses scripts, programs and HTML.

  • Add a screenshot of the rail. This is a new Agent UI surface. The test plan says it was checked in the running app (local turn, mocked cloud turn, folded layout, deleted file), but the PR shows no screenshot of any of those. Embed one or two Playwright captures (a local turn and a cloud turn) in the description.

Real-world evidence

N/A: no evidence bundle was produced for this run. For the backend and the Open/status endpoints, this verdict rests on static review plus the PR's own tests. I couldn't run pytest here because the runner has no Python test environment. The rendered rail and a real web or cloud turn are still unverified; the author lists both as not run.

🔍 Technical details

Issues

🟡 No screenshot evidence for a new Agent UI surface. Under the rubric, Agent UI changes need rendered before/after captures embedded in the description. Checked boxes and vitest results don't substitute for them. The two unchecked items (a real web-research turn and a real cloud turn) can stay deferred if the description says so.

🟢 Page links skip the app's URL allow-list (SideRail.tsx:623). p.url can come from a fetched page's result (data.get("url") in turn_summary.py:389). _host() doesn't check the scheme, so javascript://host/... gets through. React 19 and Electron's setWindowOpenHandler already block it, but MessageBubble runs every link through safeUrlTransform, and this should too:

                            <a href={safeUrlTransform(p.url)} target="_blank" rel="noopener noreferrer" className="side-rail-link" title={p.url}>

(import safeUrlTransform from ../utils/markdown). Alternatively, keep only http/https in _pages().

🟢 Passage counts can double-count (turn_summary.py:435). Every successful tool result that has chunks adds to passages. When two RAG queries in one turn return the same chunk, it is counted twice, so the rail overstates "N passages". You could dedupe on (source_file, page, chunk text or id).

🟢 .xml and .json in OPENABLE_SUFFIXES. On many Windows machines the default app for these is the browser. That is safe in practice, but it is the one place where "Open" can land in a browser, which the HTML/SVG exclusion was meant to avoid. Consider dropping .xml, since the rail rarely needs to open it directly.

Strengths

  • The model location comes from the agent's live _inference_location(), not from configuration. When it is unknown, the rail shows "Not reported" and a "Not known" cost. That is the fail-loudly rule applied to a user-facing claim.
  • Launch mode runs after the existing home, symlink and exists checks, and is_openable checks the resolved path, so a renamed symlink target can't get around the suffix allow-list.
  • Good tests: ledger aggregation, unknown-location handling, persistence across reloads, launch refusals, the status endpoint's out-of-home and max_length cases, plus the rail's busy/stale-turn behaviour (fix(ui): the side rail shows stale information #5255).

# Conflicts:
#	src/gaia/ui/_chat_helpers.py
#	src/gaia/ui/sse_handler.py
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
amd#5266)

**Held until after v0.25.0.**

During a long turn the Agent UI gave little sign it was working, and its
motion was 84 hand-picked timings that reduced motion only partly
stopped. Now one live status line carries a subtle sweep while the model
works. Plan steps tick over, the side rail slides in, and queued
messages ease into place. Every timing comes from a small set of tokens,
reduced motion stops all of it (including the status typewriter and
smooth scrolling), and an idle window runs no animation at all.

- **Expect a merge-order conflict with the checklist, rail and queue PRs
(amd#5245, amd#5246, amd#5241, amd#5242).** Their motion lives in `motion.css` and
keys on their class names, so their files are untouched. Whichever lands
second must reconcile two things. The new lint fails on amd#5242's literal
`sb-dot-pulse 1.4s ease-in-out`, which becomes `var(--duration-pulse)
var(--ease-in-out)`. And a class renamed there would quietly switch this
motion off, so recheck the `motion.css` selectors once each of those PRs
merges.
- **Small visible changes from the token move:** spinners now share one
0.9 s turn (were 0.7–1 s), the typing cursor blinks at 1 s (was 0.6 s),
and the old 300–400 ms panel timings share 320 ms.

**Live status line, before and after, from real local turns** (main vs
this branch, same backend and prompt; reduced motion emulated in the
page):

![Live status line: before and after, normal and reduced
motion](https://raw.githubusercontent.com/kovtcharov/gaia/pr-assets/5266/live-status-before-after.gif)

- Before: only the cursor blinks, and with reduced motion on the label
still types itself out.
- After: a slow highlight sweeps the label while the model works. With
reduced motion on, the label appears whole, has no sweep, and
`document.getAnimations()` reports nothing running.
- The GIF is stitched from frames captured about 0.3 s apart, so the
sweep looks steppier than it does live.

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

- Tokens:
`--duration-fast|--duration|--duration-slow|--duration-spin|--duration-blink|--duration-pulse|--duration-shimmer`,
`--ease|--ease-in-out|--ease-linear|--ease-step`, `--stagger`,
`--toast-hold`.
- The shimmer is an alpha `mask-image` sweep, not a gradient fill (the
design language bans those). Its dim stop is 80%, which keeps the 11 px
label above AA in both themes.
- The global reduced-motion rule keeps 0.01 ms rather than `none`, so
`forwards` fills and toast holds still land. It now also forces
`scroll-behavior: auto`. JS motion reads `prefersReducedMotion()` from
`utils/motion.ts`.
- `motion.test.ts` rejects literal times, raw easings, `var()` fallbacks
and non-motion variables in any `animation*`/`transition*` declaration.
It also requires every loop to sit on a live-state selector.
- Queue-place changes animate only on remount. Adding `key={place}` on
amd#5242's `.sb-row-queue` span makes each change replay.
- With amd#5245 merged there are two live lines (`Thinking… · 24s` in the
bubble, `Waiting on the model · 8s` in the summary). Only the bubble
line shimmers. Folding the two into one is a product follow-up.
</details>

## Test plan
- [ ] `cd src/gaia/apps/webui && npx vitest run`: 857 pass, including
`styles/__tests__/motion.test.ts` and
`MessageBubble.liveMotion.test.tsx`
- [ ] `npx tsc --noEmit` is clean
- [ ] Run a multi-step turn in the Agent UI and send a second message
while it works. Check that the status line sweeps, the queued row drops
in, the rail slides in, and once the turn ends
`document.getAnimations().filter(a => a.playState === 'running')` is
empty.
- [ ] Turn on reduced motion in the OS (or emulate it in DevTools) and
repeat. The label appears whole with no sweep, spinners stand still, and
the rail and queue appear without movement.

Verified locally on main merged with amd#5245, amd#5246 and amd#5241 (backend
:4309, Vite :5309, real local turns), with reduced motion emulated in
the page.
A page whose address was not http(s) could still become a clickable rail
link, and a passage two RAG queries both returned was counted twice.

- The ledger keeps only http(s) pages, and the rail runs every page link
  through the same URL allow-list as answer text.
- Passages are deduplicated per document by page and text.
- XML is no longer openable from the rail, since it often opens in a browser.
A page title wider than the rail was cut mid-letter, because a flex item's bare
text never gets an ellipsis. The title now has its own box.
@kovtcharov-amd kovtcharov-amd added ready_for_ci Run CI workflows on draft PR without requesting review and removed ready_for_ci Run CI workflows on draft PR without requesting review labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This adds a side rail next to the latest answer. It shows the pages and documents the answer used, the files it wrote (with Open and Show in folder), where the model ran, which sites were contacted and the cost. It is built from the turn's real tool calls and the agent's live inference location. When the location is unknown the rail says "Not reported" instead of assuming "This PC". The design follows the project rules: the summary is saved with the message, a failure to build it shows an error instead of costing the answer, and Open only accepts an allowlist of non-executable file types, after the existing home-folder and symlink checks.

One gap to close before merge:

  • The new file-status endpoint has no backend test. The rail polls it to mark files as deleted or changed, and it has its own rules: paths outside home are reported unchecked, a folder counts as not existing, a null byte is refused, and there is a 50-path cap. Only the frontend mock covers it. Add a few integration tests next to the new launch-mode tests.

Real-world evidence

N/A here. No evidence bundle was produced for this run, so this verdict comes from static review. The PR description embeds Playwright screenshots against the real Agent UI server for the local, cloud and folded rail. The two items the author left unchecked (a real web-research turn and a real cloud-model turn) are still pending live inference.

🔍 Technical details

🟡 Important

  • POST /api/files/status untested on the backend (src/gaia/ui/routers/files.py:406). tests/integration/test_files_router.py adds launch tests only. Cases to cover:

    • an existing file under home returns exists: true with an mtime
    • a missing path returns exists: false
    • a directory returns exists: false
    • a path outside home returns exists: null
    • \x00 returns 400
    • 51 paths return 422

    The docs (docs/sdk/sdks/agent-ui.mdx) promise every one of these behaviours.

🟢 Minor

  • The retry path reuses the ledger (_chat_helpers.py ~3312). result_holder["agent"] = agent is set before process_query. When the first attempt raises and the query is retried, sse_handler.turn_ledger still holds the failed attempt's tool calls. Those calls can inflate live_data.attempted/failed and trigger "Couldn't get live data" for a turn whose retry succeeded. Consider resetting sse_handler.turn_ledger = TurnLedger() before the retry.
  • _turn_summary uses a broad except (_chat_helpers.py:2137). It is acceptable as a boundary because it logs with exc_info and the error reaches the user through error. Narrowing it to (OSError, ValueError, TypeError, KeyError) would keep a programming bug from being dressed up as a rail message.
  • Windows path matching in upload_display_names (turn_summary.py:338). target.startswith(root) compares against uploads_dir().resolve(), which uses backslashes on Windows. A composer link written with forward slashes would miss and show the UUID name. Normalising both sides (os.path.normcase(os.path.normpath(...))) avoids that.

Strengths

  • The Open allowlist is conservative: it excludes HTML, SVG and XML along with scripts. It runs after the existing home, symlink and exists checks, and has tests for both the refuse and folder cases.
  • Location comes from the agent's live _inference_location(), never from the configured model id. None turns into "Not reported", which follows the no-silent-fallback rule.
  • Page links are limited to http(s) on both the backend (_web_url) and the frontend (safeUrlTransform). The SDK docs were updated for the done event, the launch flag and the new endpoint.

…pelled

A local link to an upload written with forward slashes or different letter
case on Windows fell back to the upload ID, and a sibling folder such as
"uploads-evil" counted as the uploads folder. Both sides are now normalised
and the match needs the folder separator.

Also covers the file-status endpoint's edges: an empty path or null byte,
exactly 50 paths, a path that climbs out of home, and a link out of home.
# Conflicts:
#	docs/guides/agent-ui.mdx
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ter (amd#5290)

The Agent UI looked developer-built: copper on cool blue-grey, 19 font
sizes, labels in spaced-out monospace capitals, and buttons in three
different shapes. This lands the foundation of the approved redesign
(amd#1001). It brings warm gray neutrals and muted brass for actions and
focus only. Inter replaces DM Sans and Space Mono. Controls are soft
tinted, rise slightly on hover and settle on press, and dialogs use calm
sentence-case titles. Every token keeps its name, so the open feature
PRs pick up the new look without edits. With no saved theme, the app now
follows the OS instead of defaulting to dark, so a light-mode user who
never picked a theme opens it in light.

**Decided: brass on both the Agent UI and the TUI.** This PR moves the
Agent UI first. The TUI keeps copper only until amd#5291 lands a
terminal-safe brass, because the light brass `#7A5A22` rounds to
`#875F00` on a 256-colour terminal, which is the TUI's Warning and
Selected entry. Until then the cross-surface test pins the TUI's copper
on its own, and amd#5291 restores the shared-accent assertion. The commit
marked `[decision pending]` predates the decision.

**Stacked on amd#5266.** This branch includes amd#5266's motion commit,
because its tokens are the motion base; review the commits after it.
Lands after v0.25.0.

| Before (`main`) | After |
|---|---|
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/ui-redesign-1001-before/finished-answer-light-win32.png)
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/5eb5f66b5ff11ed138c04b692443ee044caa5352/src/gaia/apps/webui/visual/__screenshots__/finished-answer-light-win32.png)
|
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/ui-redesign-1001-before/scheduled-tasks-light-win32.png)
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/5eb5f66b5ff11ed138c04b692443ee044caa5352/src/gaia/apps/webui/visual/__screenshots__/scheduled-tasks-light-win32.png)
|
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/ui-redesign-1001-before/documents-dark-win32.png)
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/5eb5f66b5ff11ed138c04b692443ee044caa5352/src/gaia/apps/webui/visual/__screenshots__/documents-dark-win32.png)
|
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/ui-redesign-1001-before/new-chat-dark-win32.png)
|
![](https://raw.githubusercontent.com/kovtcharov/gaia/5eb5f66b5ff11ed138c04b692443ee044caa5352/src/gaia/apps/webui/visual/__screenshots__/new-chat-dark-win32.png)
|

**Defaulted, easy to change.** The four round-3 design questions went
unanswered, so the recommended answers stand: a green tick for a
finished step, neutral markers for the selected chat and current
chapter, a small dark dot for an unread answer, and an icon shadow that
falls only outside each shape. They apply in the follow-ups below, which
own those components.

## Test plan

- [ ] `npm test` in `src/gaia/apps/webui`: 899 pass, including new
contrast cases for the raw brass and the switch knob on it
- [ ] `npx tsc --noEmit -p .` and `npx tsc --noEmit -p visual` in
`src/gaia/apps/webui` are clean
- [ ] `npx vitest run` in `website/`: 236 pass
- [ ] `go test ./internal/ui/theme/...` in `tui/` passes against the
updated spec
- [ ] `npm run test:visual` in `src/gaia/apps/webui`: 12 snapshots, six
screens in light and dark, match on Windows (set `GAIA_VISUAL_CHROMIUM`
to a local Chromium if `npx playwright install chromium` can't download)
- [ ] `gaia chat --ui`: switch Light, Dark and Match system in Settings
› General. The composer shows a brass focus ring, buttons lift on hover,
the warning notice shows its icon, and Settings switches are brass when
on.

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

**What moved**
- `index.css` tokens: warm-gray palette in both themes; brass `--accent`
(`#7A5A22` / `#D4B47E`); soft-tinted `--accent-fill`; new
`--accent-solid`, `--accent-ring`, `--shadow-press`, `--ease-spring`,
`--duration-spring`, `--duration-press` and `--fs-*`. The layered
`--shadow-sm/md/lg` carry a light top rim. None of them is a glow, and
the no-glow guard passes.
- Each place that used `--accent-fill` as a solid mark moved to a role
that stays visible on the new pale wash: switch tracks, native
checkboxes and progress bars, the suggested permission button, and the
count badges in `Sidebar.css` and `NotificationCenter.css`.
- `ScheduleManager.css` redefined `.btn-primary` and `.btn-secondary`
unscoped. Once its lazy chunk loaded, every button in the app changed
shape. Those rules are removed.
- Labels that were uppercase or monospace in stylesheets no other open
PR touches are now sentence-case Inter. Paths, keys and code stay
monospace.
- `--bg-active` rejoins the contrast matrix. The pinned copper used to
fail on it; the brass clears every floor.
- The Electron mirrors (`main.cjs`, the installer dialog), `index.html`
`theme-color` and `utils/theme.ts` follow the new canvas.

**Visual suite** (`src/gaia/apps/webui/visual/`): `vite preview` of the
production build, every `/api` call answered from fixtures, a frozen
clock, animations off, and at most 50 differing pixels. An API call
without a fixture fails the test by name. Baselines are Windows-only and
no CI job runs the suite yet; follow-up below.

**Follow-ups once these PRs merge** (each restyle goes through tokens;
no code here depends on them)
- amd#5242: sidebar rich rows (status, preview line, time), titles that
fade instead of truncating, borderless search.
- amd#5240: 28px greeting, raised suggestion cards that lift, first-run
stepper. `SetupScreen.css` gets a one-line change here, outside amd#5240's
hunks.
- amd#5243: Memory with neutral stat figures, brass switches instead of
green, and no per-tile hues.
- amd#5245: live checklist with each step's time, a shimmering live step,
and sans labels.
- amd#5269 / amd#5266: a raised user bubble, 15px answer prose, path chips and
the answer footer.
- amd#5244: AdvancedSettings headings in sentence case, and warning status
text with its icon.
- amd#5246, amd#5241, amd#5275, amd#5283, amd#5239: side rail, queue rows, context
panel, session panel and turn changes adopt the type and elevation
tokens.
- New behaviour, each its own PR: resizable panes, chapter bars (amd#5271),
the outer-only icon shadow wrapper, and Linux baselines plus a CI job
for `test:visual`.
- TUI: brass that survives 256-colour rounding, re-unifying the accent
(amd#5291).
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
# Conflicts:
#	src/gaia/apps/webui/src/types/api.gen.ts
#	src/gaia/apps/webui/src/types/api.schemas.json
#	src/gaia/ui/_chat_helpers.py
github-merge-queue Bot pushed a commit that referenced this pull request Oct 19, 2026
… limit (#5270)

Choosing Fireworks AI or the AMD LLM Gateway said only "Usage may incur
charges", and you found out what a chat cost only after spending it. Now
setup and Settings › Model show each cloud model's list price per
million tokens before you pick it, from the same rate card the per-turn
cost estimate reads, and a model with no known price says "price
unknown", never $0. Settings › Model also shows this month's cloud
spending with an optional monthly limit: it warns near the limit, and
once it's reached GAIA stops before sending a chat to the cloud and says
how to go on. Lands after v0.25.0.

Closes #5258

- **Overlap:** #5244 also edits Settings › Model, the composer's model
chip and the providers router; expect small conflicts in those files,
nothing structural. #5246 estimates each turn's cost from the same
`gaia.eval.bench.metering` rate card, so the price before a pick and the
cost after a turn agree; this PR adds no second price table.
- **Limits of the estimate:** the total counts Agent UI chats at list
price without cache discounts, so it can read higher than the bill;
turns that fail or are stopped before a reply aren't counted, so it can
also read lower. Both are stated in Settings and the docs. The AMD LLM
Gateway's prices are set by the organization that runs it, so its turns
are counted apart rather than as $0; they are still stopped once the
limit is reached.

## Screenshots

From the running app (a throwaway GAIA home with a seeded $0.50 spend,
so nothing went to a cloud provider).

| Fireworks prices, before connecting | Gateway: price unknown, and why
|
|---|---|
| <img
src="https://raw.githubusercontent.com/kovtcharov/gaia/pr-5270-screenshots/prices-before-connecting.png"
width="460"> | <img
src="https://raw.githubusercontent.com/kovtcharov/gaia/pr-5270-screenshots/gateway-price-unknown.png"
width="460"> |

| Limit reached in Settings › Model | A cloud chat stopped at the limit
|
|---|---|
| <img
src="https://raw.githubusercontent.com/kovtcharov/gaia/pr-5270-screenshots/settings-limit-reached.png"
width="460"> | <img
src="https://raw.githubusercontent.com/kovtcharov/gaia/pr-5270-screenshots/chat-stopped-at-limit.png"
width="460"> |

## Test plan

- [x] `python -m pytest tests/unit/chat/ui` (1,581 passed, including the
new `test_spending.py`: prices from the shared rate card, unknown prices
never $0, the monthly total, the limit states, and both chat paths
stopping before a cloud turn)
- [x] `npx vitest run` and `npx tsc --noEmit` in `src/gaia/apps/webui`
(859 passed); Electron `npx jest` in `tests/electron` (847 passed)
- [x] `python util/lint.py --black --isort --flake8 --pylint`
- [x] Running app (fresh GAIA home, backend on 4305): Fireworks prices
shown before connecting; with $0.50 spent against a $0.50 limit, a chat
on a Fireworks model is answered with the stop message and nothing is
sent; Settings shows the total, the stopped state and "Allow more this
month"; the gateway tab says "Price unknown" and why
- [ ] A real paid Fireworks turn records its cost in the month's total
(not run; the recording path is unit-tested)
- [ ] Setup's cloud step shows prices before the key (covered by vitest;
the running app's setup check could not run in this test setup)

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

- `src/gaia/ui/spending.py`: `price_card` / `price_list` read
`gaia.eval.bench.metering.rate_card`/`RATES`; `record_turn` writes a
`cloud_spend` row (new table in the chat DB, `usd` NULL when unpriced)
after each streamed turn; `limit_refusal` runs right after the turn's
model is resolved, in both `_stream_chat_impl` and `_get_chat_response`.
A refused streamed turn is saved as the assistant's reply and closes
with the normal `answer` and `done` events.
- Limit and the allowed month live in the Agent UI settings table; a
non-numeric saved limit is a 500 that names the fix.
- New routes: `GET /api/spending`, `PUT /api/spending/limit`, `POST
/api/spending/allow-month`, `GET /api/spending/prices/{provider}`. Cloud
models from `GET /api/providers/{provider}/models` carry `price`.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit fd40993 Oct 19, 2026
44 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/ui-side-rail-ledger-4ef9df branch October 19, 2026 12:27
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
amd#5337)

Builds on amd#5242's turn queue (now merged); the diff is this change
alone.

Before: one chat could hold the model away from every other chat. A
permission prompt left unanswered in a background tab blocked all chats
for up to 10 minutes; Stop couldn't end a turn whose agent thread was
stuck in a tool or MCP call; a non-streamed message waited 60 s, got a
429 and was never saved; scheduled runs skipped the line, and a
timed-out one (or autonomous tick) kept running and piling up. After: a
turn waiting on you steps out of line and comes back at the front once
answered, Stop ends the turn and frees the model within 5 s, a busy
model queues a message instead of dropping it, and scheduled runs and
ticks wait their turn and stop when they time out.

- **Back from a prompt, the model is checked again.** Another chat may
have changed the loaded model while you were deciding; if it can't be
loaded, the turn ends with the reason before the approved tool runs.

- **Waiting on you doesn't hold the GPU.** Other chats run while a
prompt or question is open; the answered turn goes ahead of chats that
arrived meanwhile.
- **Stop really stops.** If the agent thread can't see the Stop, the
turn still ends and the model is freed; only that chat stays busy, with
a 409 that says it's still stopping, until the thread exits.
- **Nothing silent.** A turn waiting on the start-up warm-up says what
it's waiting on, and Stop ends the wait. Agent setup that waits on
another chat's setup says so, frees the model meanwhile, and fails with
a reason after 2 minutes.

Reproduced by `tests/unit/chat/ui/test_turn_slot_reliability.py`,
`test_scheduled_run_slot.py` and
`test_agent_loop_session_lock.py::test_timed_out_tick_frees_the_model_while_its_thread_winds_down`;
they fail on amd#5242's branch and pass here.

Overlaps amd#5242 (builds on it), amd#5241, amd#5239 and amd#5246 (all edit
`_chat_helpers.py` / `routers/chat.py`; no shared hunks with this change
when I checked).

**Merging with amd#5336:** the two PRs conflict in one hunk of
`_chat_helpers.py` next to `model_load_lock`. Both sides only add code
there, so keep both.
`test_non_streaming_timeout_holds_session_until_worker_exits` used to
race amd#5336's pre-flight stop check (about 1 run in 4). It now lowers the
no-progress limit only once the agent is running, and passed 8 of 8 in a
local trial merge.

## Test plan
- [x] `pytest tests/unit/chat/ui tests/unit/test_ui_warmup.py
tests/unit/test_chat_preflight.py tests/unit/test_relay_*.py`: all pass
- [x] `python util/lint.py --black --isort --pylint --flake8
--test-lanes`
- [x] Stuck-thread, open-tab Stop, question and permission waits,
front-of-line resume: each a failing test first
- [x] Live: two chats against the Agent UI server on this branch
(Gemma-4-E4B on Lemonade, GPU), one left on a permission prompt while
the other answers. `/api/chat/active` at each step:
1. A on its prompt:
`{"session_ids":["A"],"queued":[],"awaiting_user":{"A":"permission"}}`
2. B sent while A waits, B answers `51` without queuing:
`{"session_ids":["A","B"],"queued":[],"awaiting_user":{"A":"permission"}}`
3. A answered while B streams a long reply; A goes back in line and
stops showing "needs you":
`{"session_ids":["A","B"],"queued":["A"],"awaiting_user":{}}`, and A's
stream shows `Waiting for the GPU — 1st in line`
  4. Both finish: `{"session_ids":[],"queued":[],"awaiting_user":{}}`

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

- `TurnSlot` (turn_queue.py) is a turn's handle on the queue.
`SSEOutputHandler._away_from_model` calls `step_away()` around the
confirm/question waits and `come_back()` to re-enter with `front=True`.
A Stop while waiting there withdraws it, and the handler marks the turn
cancelled so it never calls the model unheld.
- `_stream_chat_impl` breaks its event loop 5 s after Stop when the
producer is still alive. `_cleanup_stream` closes the slot (a late
`come_back` can't retake it) and records the thread in
`_stopping_sessions`. `routers/chat.py` releases the session lock only
when that thread exits, by polling, not `to_thread(join)`, so it doesn't
pin a shared-executor worker.
- `tool_registry_lock` (`writing_tool_registry`) now guards every agent
build and `_register_tools()` call: UI turns, agent loop, scheduled runs
and warm-up. These write the process-global `_TOOL_REGISTRY` and then
snapshot it, so before this lock, a stopped turn's lingering thread
could interleave with the next turn's build.
- A timed-out scheduled run stops its agent (a streaming reply included,
via its console's `cancelled`) and keeps its turn-queue slot until its
thread has stopped, so it never shares the GPU with the next turn;
waiting chats see their place in line.
- A turn waiting in line sends `: keepalive` every 5 s.
- `wait_for_warm_up` no longer sends the turn anyway after 300 s; it
raises with the reason.
- Ticks and scheduled runs run on their own daemon threads
(`agent_threads.run_in_own_thread`), not the default executor that the
SSE loop polls with.
- Removed: the non-streamed 429. Its test now lives in the new file as
"saved, then waits in line".
- Known gap: a lingering autonomous tick shows the generic "already in
progress" 409 rather than "still stopping". The chat is still protected;
only the wording differs.
- LLM-affecting? No prompt, tool, or classification changes; no eval
categories needed.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 20, 2026
… the time goes) (amd#5275)

After one question, a local chat was already 30% full and nobody could
see why, or why a turn took 70 seconds. The meter's new **Details**
panel shows the cause: on Gemma-4-E4B at 64K, **tool definitions take
14K tokens (21%)** before you type anything. It breaks the window into
system prompt, tool definitions, skills, memory, documents and messages,
counted with the loaded model's own tokenizer (marked **approx.** with
the reason when it can't be). It also splits each turn into time in the
model vs time in GAIA (these add up to the wall time), plus first word,
reading and writing speed, cache reuse, tool calls, model loads, model
memory and cost. Anything unmeasured says "unknown".

Instead of "start a new chat when full", the panel shows what is live in
the window and how many older tool results were moved out of the prompt
(still readable). The near-full warning says only what happens today:
the oldest turns may drop out of the model's view but stay saved. A
"Summarized" row appears only if an agent reports folded turns, which
none does yet.

- **Context-state contract:** agents report put-away and summarized
context through an optional `context_state()` method (`put_away:
{results, tokens}`, `summarized: {turns, tokens, summary_tokens}`).
Nothing implements it on this base yet, so the panel claims nothing. The
proactive-eviction session is implementing `put_away`; `summarized`
stays null until turn folding exists.
- **Timing recorder:** timing comes from the always-on step timer and
each call's backend stats. It doesn't turn on the opt-in `turn_metrics`
recorder, which re-tokenizes the whole prompt on every call.
`turn_insights.summarize_turn` is the one place to swap onto it once
that recorder is always on.
- **Known gap:** the per-part counts run ~9% above the server's count of
the whole prompt (19.3K vs 17.8K), mostly from tool schemas. Lemonade
exposes no template-rendering endpoint, so the panel shows the server's
own number next to them.
- **Agent-loop change:** a step whose tool failed now records its stats,
so it also reports its prompt size to context eviction. That can change
when older tool results are put away, so watch `error_recovery` and
`rag_quality` on the next RC eval. No prompts, tools or history
selection changed. Lands after v0.25.0. The side-rail entry (amd#5246) can
mount `<ContextPanel>` once both land.

## Test plan
- [x] `npx vitest run`: 885 passed. `tsc --noEmit` is clean.
- [x] `pytest tests/unit/chat/ui tests/unit/agents …`: 5,207 passed.
`python util/lint.py --all` is clean.
- [x] `pytest tests/integration/test_lemonade_tokenize.py` against a
real Lemonade: tokenizes and leaves the loaded model unchanged.
- [x] Real local turns in the running app (isolated `GAIA_HOME`, backend
:4313, Vite :5313, Gemma already loaded, no model loads): categories sum
to the meter total (18,900 = 18,900), and 10.077 s model + 1.001 s GAIA
= 11.078 s wall. The panel refreshes itself when a reply ends, and makes
no requests while closed. Light, dark and 375 px checked.
- [ ] Reviewer: open a chat, click the context meter, then **Details:
context & performance**.

Closes amd#5262

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes electron Electron app changes ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(ui): the side rail shows stale information feat(ui): a side rail for sources, files, and where each turn's data went

2 participants