Skip to content

feat(agent,ui): undo the file changes from a turn - #5239

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:claude/undo-turn-file-changes-c97918
Oct 19, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:claude/undo-turn-file-changes-c97918

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Once you approved an edit, GAIA had no way back: a bad change to a real file could only be fixed by hand. Now GAIA saves a copy of every file before an agent tool writes, edits, creates or deletes it. A turn that changed files shows Review changes, a diff fed by those copies, and Undo this turn, which puts every file back exactly, or changes nothing and says why. Undo still works after a restart. When a turn ran a shell command, a Python snippet or an MCP tool that could have changed files GAIA can't see, the answer says Undo may be incomplete and lists them. Settings → Privacy → Undo history sets how long copies are kept (7 days) and how much disk they may use (500 MB), and shows current use.

Closes #5225. Lands after v0.25.0. The review view also gives #3710's unused DiffCard real data in the Agent UI; the inline diff after an approved edit and the TUI side of #3710 are still open.

🔍 Technical details
  • The copies live with the agent under <GAIA_HOME>/snapshots/<session>/<turn>/, so the TUI can call the same endpoints for a later /undo: GET /api/sessions/{id}/changes, GET …/changes/{turn}/diff, POST …/changes/{turn}/undo, GET/PUT /api/settings/undo.
  • Undo is all or nothing. It checks every copy's checksum first. A file changed after the turn is a 409 that names it; force overwrites. Each restored file is re-checked as it is written. A failed write or a mismatch puts back every file already touched, from safety copies kept on disk.
  • Files are keyed by their real path, so a file written once through a link or an 8.3 short name and once through its long name is one entry, not two.
  • An end state over 8 MB keeps only a checksum, and a review diff skips files over 2 MB. Trimming for space never removes a turn that is still running. A write from a tool that outlived its turn marks that turn incomplete without clearing a past undo.
  • Recorded paths: both write_file/edit_file implementations, write_python_file, edit_python_file, replace_function, write_markdown_file, update_gaia_md, dump_document, transcripts, download_file, screenshots, generated images and TTS. A copy that can't be saved blocks the write.
  • Marked incomplete instead: shell lines outside the read-only tier (full access, approved, or a skill-granted CLI), run_python, execute_python_file, install_cli, and MCP tools not proven read-only.
  • Not recorded yet: TUI turns, scheduled prompts and goal-loop ticks, because they don't run through the Agent UI chat path.
  • Eval categories to watch on the next RC: tool_selection, error_recovery, mcp_reliability, gaia_tool_selection, gaia_core, gaia_shell. No prompt or tool-schema text changed. A failed snapshot now turns a write into a tool error.

Test plan

  • pytest tests/unit/agents/test_file_snapshots.py tests/unit/chat/ui/test_changes_router.py tests/unit/chat/ui/test_turn_changes_recording.py tests/unit/test_shell_undo_marks.py. Covers edited, created and deleted files, restore in a fresh process, conflicts, rollback, retention, the real write/edit tools, and the streaming and non-streaming chat paths.
  • pytest tests/unit/chat/ui tests/unit/agents tests/unit/test_shell_guardrails.py tests/unit/test_cli_config.py tests/unit/mcp
  • npx vitest run in src/gaia/apps/webui (all files), plus npx tsc --noEmit
  • python util/lint.py --all
  • Running app (backend 4306, Vite 5306, local Qwen3-30B): the agent edited a scratch file, Review changes showed the diff, and Undo restored it. sha256 matched the original. The local Lemonade is one version behind main, so only the setup check was stubbed for this run.
  • Restarted the backend, then undid a two-file turn (recorded by a script, not the model: one edit, one new file and folder) from the UI. The bytes matched and the new file and folder were removed.
  • Changed the file by hand after a turn. Undo refused, named the file and changed nothing.
  • A turn that wrote the file under its 8.3 short name and then its long name listed one file, and Undo restored the original bytes.
  • Deleting the chat removed its undo copies.
  • Next RC eval on the categories above

Once an edit was approved there was no way back. GAIA now saves a copy of
every file before an agent tool writes, edits, creates or deletes it, per
session and turn under <GAIA_HOME>/snapshots. A turn that changed files
offers "Review changes" (a diff from the saved copies) and "Undo this
turn", which restores every file exactly or changes nothing and says why.
Undo survives a restart. Shell lines outside the read-only tier,
run_python, execute_python_file, install_cli and non-read-only MCP tools
mark the turn "undo may be incomplete" instead of claiming coverage.

- file_snapshots: realpath-keyed capture, end-state checksums, all-or-
  nothing restore with on-disk rollback, time and size retention that
  never drops a running turn
- list / diff / undo endpoints and /api/settings/undo, usable by the TUI
- Agent UI turn footer, review dialog (DiffCard gains badge and note),
  Settings > Privacy > Undo history
- undo_retention_days / undo_max_mb config keys

Closes amd#5225
@github-actions github-actions Bot added documentation Documentation changes mcp MCP integration changes tests Test changes electron Electron app changes agents labels Oct 16, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

The red "Unit Tests (Windows, py3.12)" check is not caused by this PR. The job hit its 90-minute limit and was cancelled; no test failed. main times out the same way at the commit this PR is based on.

🔍 Technical details
  • This PR, run 38983276528: Windows job cancelled at step "Run unit tests (Windows)" after 1h30m. Linux and macOS unit tests passed, as did offline integration and the import check.
  • main at fdb2c9c6e (this PR's base), run 38976700477: Windows job cancelled after 1h30m (22:36 to 00:07 UTC).
  • Last green main, run 38920715304 at 04542d63c: the Windows job alone took 1h10m, already close to the timeout-minutes: 90 in test_unit.yml.
  • Other PRs opened today were also cancelled at about 1h30 on the Windows job, for example run 38985651131.
  • The four new test files run in about 25 s on Windows locally (52 passed, 1 skipped: the symlink case needs a privilege the machine lacks).
  • pr-review is red because the review budget is used up until 21 Oct.

"In use" broke onto two lines once the snapshot folder path got long.
Opened from an answer, its backdrop covered only a rectangle of the chat column.
@kovtcharov-amd kovtcharov-amd added the ready_for_ci Run CI workflows on draft PR without requesting review label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Undo for a turn's file changes looks correct. Undo checks every saved copy and every conflict before it touches a file, rolls back if a write fails part-way, and every write path checks permission before it saves a copy. A failed copy blocks the write instead of letting it go ahead without undo. I found no blocking bugs. Tests cover restoring from a fresh process, conflicts, rollback and retention.

🟡 No screenshots of the new UI on the PR. Review changes, Undo this turn, Undo may be incomplete and the Undo history settings panel are all new Agent UI surface. The test plan says they were run in the app but shows no image. Please embed a before/after screenshot of a turn with changes, the review modal and the settings panel.

🟢 Four small items, details below:

  • A failed copy of the optional timings file now fails the whole transcription.
  • A late write after a turn ends can lose its "incomplete" flag.
  • The docs say "the newest turn is always kept", but the age limit can still delete it.
  • The MCP client now loads the whole agent framework at import time.
🔍 Technical details
  • src/gaia/agents/tools/audio_tools.py (_write_timings): before_change is inside a try that only catches OSError. SnapshotError is a RuntimeError, so a failed copy of the .timings.json sidecar escapes. The comment there says losing timings is non-fatal.

        except (OSError, SnapshotError) as e:
    

    (import SnapshotError alongside before_change).

  • file_snapshots.py TurnRecorder.link_message: on the streaming path, close() runs in the worker and link_message runs afterwards in the generator. If a tool abandoned at its timeout writes in between, _note_late appends to the on-disk manifest. link_message then _save()s the in-memory manifest over it, and the "after the turn ended" entry is lost, so incomplete goes back to false. Do a read-modify-write on disk once _closed, the same way _note_late does.

  • prune(): the expired branch ignores keep, so the newest turn is deleted once it is older than retention_days. docs/reference/cli.mdx, docs/sdk/sdks/agent-ui.mdx and the GaiaConfig docstring say "the newest is always kept". Either say "kept by the size limit" or exempt keep from expiry.

  • src/gaia/mcp/client/mcp_client.py: from gaia.agents.base.file_snapshots import … runs gaia/agents/base/__init__.py, which imports Agent and MCPAgent. The low-level MCP client now depends on the agent framework, so agent.py can never import the MCP client without an import cycle. file_snapshots only needs gaia.config. Moving it to a leaf package (e.g. gaia/filesystem/) would keep the dependency pointing the right way.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This PR adds per-turn undo. GAIA saves a copy of each file before an agent tool writes it, shows a diff under the answer, and can put every file back all at once, even after a restart. The core is careful: it checks every saved copy before touching anything, refuses when a file changed after the turn, rolls back a failed undo, and marks shell, Python and MCP work as "undo may be incomplete". I found no correctness blockers.

  • Missing screenshot: this adds new Agent UI controls (Review changes, Undo this turn, Settings → Undo history). The test plan describes manual runs but has no before/after screenshot and no captured request/response for the new endpoints. Please embed at least one screenshot of the Undo row and the review dialog.
  • Small undo gap: when a turn creates a new folder and then a subfolder inside it, undo can leave the outer folder behind, empty. It then says the folder was kept "because it holds other files", which isn't true.

Real-world evidence

N/A: no evidence bundle was produced for this run. For the Agent UI and the new /api/sessions/{id}/changes routes, this verdict rests on static review alone. The author's test plan lists manual runs (edit → review → undo, undo after a restart, conflict refusal, 8.3 short names), but the PR shows no output or screenshot from them.

🔍 Technical details

🟡 Important

  • Agent UI change without rendered evidence. TurnChanges.tsx, ChangesReview.tsx and UndoHistorySettings.tsx are new user-visible UI. The rubric asks for a Playwright before→after screenshot embedded as a raw.githubusercontent.com image. If the screenshot has to wait for the strix-halo lane, posting the real GET …/changes, GET …/diff and POST …/undo (including the 409 conflict body) is enough for merge-time CI.

🟢 Minor

  • Nested created folders aren't removed deepest-first (src/gaia/agents/base/file_snapshots.py:638-646). created_dirs is stored per entry, and the folders are removed entry by entry. Take a turn that writes new/a.txt and then new/sub/b.txt: entry 1 records [new] and entry 2 records [new/sub]. rmdir(new) fails first because new/sub still exists, so new lands in kept_folders and survives empty. The UI then says it holds other files. Collecting all the folders and removing them deepest-first fixes this:
        kept_dirs = []
        created = {d for e in entries for d in (e.get("created_dirs") or [])}
        for folder in sorted(created, key=lambda d: len(Path(d).parts), reverse=True):
            path = Path(folder)
            if not path.is_dir():
                continue
            try:
                path.rmdir()
            except OSError:
                kept_dirs.append(folder)
    
  • link_message overwrites the on-disk manifest from memory (file_snapshots.py:283-289). It runs after finish(). If an abandoned tool thread calls _note_late in between, the "after the turn ended" note on disk is lost. The window is narrow, but losing that note hides exactly the case the incomplete-undo marker exists for. You could re-read the manifest from disk before setting message_id, as _note_late does.
  • The non-streaming path drops the link warning (src/gaia/ui/routers/chat.py:220). link_message() returns a warning there that nobody logs or returns, unlike the streaming path. A logger.error(...) would match how close() is handled a few lines up in _get_chat_response.

Strengths

  • The restore logic is solid. It verifies every blob's checksum before any write, checks for conflicts, writes atomically through a temp file and os.replace, re-checks the checksum after each write, and rolls back from on-disk safety copies with an actionable message if rollback itself fails.
  • The recorder reaches tool bodies through a contextvar, which rides the existing copy_context() in the agent's tool runner. A write from a thread abandoned at its time limit marks the turn incomplete instead of being lost silently. Session and turn ids are validated against a strict regex before they touch a path.
  • The tests cover the real write/edit tools, restore in a fresh process, conflicts, rollback, retention, and both chat paths.

Undo could leave an empty folder behind when a turn made nested new
folders, and could lose the "undo may be incomplete" mark when a timed-out
tool wrote between the turn ending and the answer being saved.

- Remove every folder the turn created deepest-first across all files
- link_message re-reads the manifest on disk once the turn has closed
- A failed copy of the optional transcript timings file stays non-fatal
- The MCP client imports the snapshot module lazily, keeping it off the
  agent framework
- Docs and settings say what retention does: the size limit never removes
  the newest turn; the age limit still can
# Conflicts:
#	src/gaia/ui/_chat_helpers.py
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]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 0d61f0d Oct 19, 2026
63 of 64 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/undo-turn-file-changes-c97918 branch October 19, 2026 10:23
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…md#5246)

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](https://raw.githubusercontent.com/kovtcharov/gaia/pr-assets-5246/rail-local.png)

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

![Side rail, cloud
turn](https://raw.githubusercontent.com/kovtcharov/gaia/pr-assets-5246/rail-cloud.png)

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

![Side rail
folded](https://raw.githubusercontent.com/kovtcharov/gaia/pr-assets-5246/rail-folded-1000px.png)

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 amd#5222. Closes amd#5255. Covers amd#5183 and amd#5185 for the rail; the UI
half of amd#890.

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

- 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".
</details>

## Test plan

- [x] `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
- [x] 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)
- [x] `python util/lint.py --all`
- [x] `npx tsc --noEmit` and `npx vitest run` (868 passed), including
`SideRail.test.tsx` and `ChatView.sideRail.test.tsx`
- [x] Running app: a local turn's summary built by the real backend
shows **This PC** after a reload
- [x] 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
- [x] Running app: while a turn runs, the rail shows it in progress
instead of the previous answer (amd#5255)
- [x] Running app: a file deleted after its turn shows as "No longer on
disk" with no Open, through the real `/api/files/status` (amd#5255)
- [x] Trial merges of this branch with amd#5239, amd#5241 and amd#5242, one at a
time: tsc, vitest and the UI pytest suites pass. With amd#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(...)`
- [x] `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

---------

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

Labels

agents documentation Documentation changes electron Electron app changes mcp MCP integration 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.

feat(agent,ui): undo the file changes from a turn

2 participants