Skip to content

fix(ui): store uploads and managed documents under GAIA_HOME - #4348

Merged
kovtcharov-amd merged 19 commits into
amd:mainfrom
kovtcharov:claude/ui-router-tests-gaia-home
Sep 26, 2026
Merged

kovtcharov-amd merged 19 commits into
amd:mainfrom
kovtcharov:claude/ui-router-tests-gaia-home

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

The Agent UI ignored GAIA_HOME and always saved Document Library uploads and chat attachments under the real ~/.gaia. So a run of the document and file router tests left files in the developer's own GAIA home, and those files could change the next run's results. Both folders now live under $GAIA_HOME (default is still ~/.gaia). The router tests run under a fake home and fail if anything lands in <home>/.gaia. A GAIA_HOME set to your home directory or one of its parents is now rejected, because the server deletes files in <GAIA_HOME>/documents as its own, and there that would be your real Documents folder.

Merge #4343 first. It fixes three reindex tests in test_documents_router that fail on main right now because they call real RAG indexing without Lemonade. I checked this branch with #4343's changes applied: both router files pass (89 passed, 1 skipped). This PR edits different lines of that file, so the two won't conflict. It also adds nothing to the unit conftest that #4301 changes.

Test plan

  • pytest tests/unit/chat/ui/test_gaia_home_storage.py: fails on main (4 failed, 2 errors), passes here (6 passed)
  • pytest tests/unit/chat/ui tests/integration/test_files_router.py tests/integration/test_documents_router.py: 1127 passed. The only failures are the 3 reindex tests that test: repair the unwired test files that drifted into failure #4343 fixes
  • Same two router files with test: repair the unwired test files that drifted into failure #4343's test changes applied: 89 passed, 1 skipped
  • Same run with GAIA_HOME unset and a fake HOME: default ~/.gaia layout unchanged
  • black, isort and pylint on the changed files (the one pylint warning in documents.py is already on main)

Fixes #4347

Kalin Ovtcharov added 3 commits September 25, 2026 00:40
Nine test files no CI lane runs had been failing silently against APIs and
contracts that changed underneath them. This brings them back to green
against current main so the next change can put them in a lane.

- test_sdk.py: assert the SDK surface that exists today (process_query via
  Agent.chat, the tool registry instead of the never-public execute_tool,
  openai_server's module-level app, Agent.STATE_* class constants, current
  RAGSDK/AudioClient/KokoroTTS methods, LLMClient as an ABC); drop the
  xfail DatabaseMixin block (it ships as gaia.database.mixin) and the
  placeholder docs-exist check.
- test_multi_caller_equivalence.py: send the X-Gaia-UI header on mutating
  calls and read /api/connectors' "connectors" shape.
- test_memory_integration.py: fresh installs are schema v4.
- test_memory_api_integration.py: consolidation is 503 until a chat session
  registers a consolidator, and runs it once one has.
- test_documents_router.py: two fixtures indexed for real and needed Lemonade.
- test_tui_control_e2e.py: give the pty a size and a TERM like a terminal.
- test_ui_email_scope_consent.py: the agent now declares microsoft_work too;
  drop three tests of the in-process /v1/email mount the UI no longer has.
- test_lemonade_embedded_lifecycle.py: llamacpp:cpu has no macOS build.
- test_email_mcp_stdio_parity.py: docstring said no Lemonade; triage uses it.
- test_vlm_integration.py: deleted. A script that returned booleans instead
  of asserting, so it could not fail, and it called a removed constructor arg.

Refs amd#4205
…blocking

43 test files ran in no CI lane, so they looked green on every PR whether
they worked or not, and nothing stopped the count from growing. Now every
test file is either run by a lane or listed with the reason CI can't run it,
and lint fails the moment a new file is neither.

- test_unit.yml gains an offline-integration job for the 23 files that need
  no Lemonade, live account or AMD hardware (with Go for the TUI e2e and the
  [mcp] extra for the SDK and MCP-server tests).
- test_email_agent_unit.yml runs test_ui_email_scope_consent.py.
- util/test_lane_allowlist.yml lists the 18 that need a live Lemonade
  Server, a real Gmail account, a self-hosted model runner, npm-fetched MCP
  servers, or are hand-run scripts, each with its reason.
- util/lint.py runs check_test_lane_coverage.py as a blocking check
  (--test-lanes, and part of --all); lint.yml re-runs when the allowlist
  changes.

Fixes amd#4205
The Agent UI wrote Document Library uploads and chat attachments to the real
~/.gaia even when GAIA_HOME pointed elsewhere, so the document and file router
tests left files in the developer's GAIA home on every run.

- The documents dir, the uploads dir and the static uploads mount now resolve
  GAIA_HOME at call time; the agent's writable scope follows the same dir.
- A relocated documents dir is added as a document root so reindexing a
  dropped file still works when GAIA_HOME is outside the home directory.
- A GAIA_HOME that is the home directory or above it is refused: the server
  deletes files in <GAIA_HOME>/documents as its own, and there that is the
  user's real Documents folder.
- The router tests run under a fake home with GAIA_HOME set elsewhere, and
  fail if anything appears under <home>/.gaia.

Fixes amd#4347
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The Agent UI now stores Document Library uploads and chat attachments under GAIA_HOME instead of always in the real ~/.gaia, which is what stops a test run from dropping files in the developer's own GAIA home. Default behaviour is unchanged, the docs were updated in step, and the new tests fail loudly if any code path sneaks back to the hard-coded home. Nothing here blocks merge.

One thing worth resolving before merge: GAIA already refuses a GAIA_HOME that is your home directory or above it — the uninstall path has that exact guard, with the same reasoning about documents colliding with the real Documents folder on Windows and macOS. This PR adds a second, independent copy of it in the UI layer rather than reusing the existing one, and the copy reports the problem as a web error, so pointing GAIA_HOME at your home makes the UI die at startup with a raw traceback instead of the clean message the uninstall command already prints for the same mistake. Extracting the check into one shared helper keeps the two from drifting.

Smaller follow-ups: the same test fixture is written twice (once for the integration tests, once for the unit tests) and could be shared; the document-root tests now quietly depend on whether the developer has GAIA_HOME exported; anyone who already had GAIA_HOME set will find their old uploads no longer recognised as GAIA-owned, so removing those library entries leaves the files behind; and GAIA_HOME is still only honoured for these two folders inside the UI — the chat database and several other UI paths remain pinned to the real home.

Merge order: the author notes this needs #4343 first, which is still open.

Real-world evidence

No evidence-bundle.md was produced for this PR. The evidence that does exist is in the PR description as pytest runs, including a run with GAIA_HOME unset confirming the default layout is untouched. I treat that as adequate for the surface this touches: the new tests drive the real upload endpoints through the app and assert where the bytes land on disk, rather than asserting a mock was called. I could not re-run them here — this review environment has no pytest installed — so the passing counts in the description are the author's, not mine, and the Agent UI's rendered behaviour under a relocated GAIA_HOME has not been exercised anywhere.

🔍 Technical details

🟡 Important

Duplicate GAIA_HOME safety guard, raising an HTTP error from a startup path (src/gaia/ui/utils.py:401)

_ui_gaia_home() reimplements the structural half of _assert_purgeable_home() in src/gaia/installer/uninstall_command.py:228 — same resolved == user_home or user_home.is_relative_to(resolved) test, same Windows/APFS documents rationale, nearly the same error text. CLAUDE.md asks for reuse before reimplementation, and two copies of a safety check drift: the uninstall version also rejects a filesystem root and carries the GAIA_HOME is set to … / came from Path.home() hint, which the new one drops.

The exception type is the practical problem. uploads_dir() is called from create_app() (src/gaia/ui/server.py:668), which is not a request context, so an HTTPException there surfaces as an unhandled fastapi.exceptions.HTTPException: 500: … traceback out of gaia chat --ui. The same applies to _managed_documents_dir() reached via _compute_allowed_paths in _chat_helpers.py:989, and to _is_server_owned() (src/gaia/ui/routers/documents.py:111), whose except (OSError, ValueError) no longer covers everything managed_documents_dir() can raise.

Suggested shape: move the structural check next to gaia_home() (or a shared gaia.paths-style module) raising a plain UnsafeGaiaHomeError, have uninstall_command keep its identity/marker check on top, and let the UI translate that exception to a 500 only at the request boundary — the pattern CLAUDE.md describes for "translating exceptions at a system boundary".

🟢 Minor

Duplicated fixture — isolated_gaia_home (tests/integration/conftest.py:12) and homes (tests/unit/chat/ui/test_gaia_home_storage.py:28) are the same fixture with different names and return shapes. Both are useful; hoisting one into the root conftest.py would let the unit test drop its copy.

Document-root tests now read the ambient GAIA_HOME (tests/unit/chat/ui/test_utils_helpers.py:509) — test_empty_value_is_home_only pins it, but its siblings in TestDocumentRoots and TestEnsureWithinHome do not, so a developer with GAIA_HOME exported gets an extra root that those tests never accounted for. An autouse fixture on the class is cheaper than remembering per test:

    @pytest.fixture(autouse=True)
    def _no_relocated_gaia_home(self, monkeypatch):
        """Pin GAIA_HOME off so an exported one can't add a root."""
        monkeypatch.delenv("GAIA_HOME", raising=False)

    def test_empty_value_is_home_only(self, monkeypatch):
        monkeypatch.setenv(DOCUMENT_ROOTS_ENV, "")
        assert set(document_roots()) <= {Path.home(), Path.home().resolve()}

Existing blob uploads become orphans under a relocated GAIA_HOME — _is_server_owned() compares against the new location, so documents already recorded at ~/.gaia/documents/… return False and DELETE /api/documents/{id} no longer unlinks them (src/gaia/ui/routers/documents.py:111). No data loss and the blast radius is users who already had GAIA_HOME set, but it is a behaviour change worth a line in the PR description or the install guide.

GAIA_HOME is honoured for two folders only — the rest of src/gaia/ui/ still hard-codes Path.home() / ".gaia": database.py:23 (the chat DB that stores the rows pointing at the relocated uploads), routers/mcp.py:70, routers/onboarding.py:57, routers/system.py:730, routers/agents.py:253,336, agent_loop.py:252. The docs added here are careful to scope the claim to the two folders, so nothing is misleading — but the split leaves the database in the real home while the files it references move, and the <home>/.gaia stray-file assertion in the new fixtures will not catch those sites because the module-level constants are evaluated at import time, before the monkeypatch. Worth a follow-up issue.

Strengths

  • document_roots() gaining the relocated managed dir (src/gaia/ui/utils.py:474) is the non-obvious part of this change, and it is handled correctly: reindex_document goes through safe_open_document, which would 403 on a managed doc living outside home. The lifecycle test covers upload → reindex → delete, so that path is actually exercised rather than assumed.
  • The fixtures assert the absence of <home>/.gaia at teardown, which turns "some code path still hard-codes the home" into a test failure instead of a silent stray file. That is a better guard than checking the happy path.
  • The upload tests moved from "the directory exists" to "the bytes are at this path" (tests/integration/test_files_router.py:316) — the assertion that would have caught this bug.
  • except (OSError, KeyError): pass in the upload race check became a logged warning (src/gaia/ui/routers/documents.py:505), retiring one of the Fail-Loudly violations CLAUDE.md flags as tech debt in src/gaia/ui/.

The file-search tests walked the real home directory, so on a developer
machine one test ran past two minutes, and the results depended on what
that user owned. Most assertions were hedged with "if found" because the
fixture lived under ~/.gaia, which the search skips as hidden.

The search tests now point HOME/USERPROFILE at a temp dir and write their
files into its Documents folder, so each one asserts the exact result.
The file runs in about 4 seconds with the real HOME set.

Refs amd#4205
# Conflicts:
#	tests/test_vlm_integration.py
…free box

Both files this PR repairs still failed in the offline lane, so the "534
passed" claim held only on the author's machine.

The memory test built its URL by interpolating a local-timezone stamp. At
a negative UTC offset the "-" is URL-safe and it passes; on a UTC runner
the "+00:00" decodes to a space, fromisoformat rejects it, and the
endpoint correctly 422s. Passing the stamp through the client's params
lets it percent-encode, and a second pinned +00:00 case means the test
now catches this from any timezone rather than only from UTC.

The TUI test set TERM to get color, but termenv treats any environment
with CI set as "not a TTY" before it looks at TERM or the pty, so
lipgloss dropped to the Ascii profile and rendered no escapes at all for
format=ansi to return. CLICOLOR_FORCE is the documented override, and
NO_COLOR outranks it, so both it and CLICOLOR are cleared.

Also resolves the merge with main: amd#4290 removed only one of this file's
three fallback_model uses, and VLMClient no longer takes that argument,
so the deletion stands.
…ew live-Lemonade suite

tests/test_ui_email_scope_consent.py was added to the email lane's pytest
command but not to its paths filters, so a PR editing only that file
still ran it nowhere -- while the new checker counted it as covered,
because the checker asks whether a lane names a file, not whether any
trigger reaches that lane. Listed in both the push and pull_request
blocks, next to the other individually-named tests/test_email_* entry.

Merging main brought tests/integration/test_lemonade_predownload_checks.py,
which the gate correctly flagged as run by no lane. It takes
require_lemonade, so it is allowlisted rather than wired offline.
uploads_dir() runs inside create_app(), which is not a request context, so
the new guard's HTTPException surfaced as a raw
"fastapi.exceptions.HTTPException: 500: ..." out of `gaia chat --ui`. The
user sees a stack trace for a mistake they could have fixed in one step.

It now raises UnsafeGaiaHomeError, and both launch paths -- `gaia chat --ui`
and `python -m gaia.ui.server` -- print the message and exit 64 (EX_USAGE,
the code gaia uninstall already uses for the same misconfiguration).

The structural test itself moves to gaia.config as
unsafe_gaia_home_reason(), which uninstall_command now calls instead of
keeping a second copy. Its messages, tiers and exit codes are unchanged;
it keeps its own identity/marker check on top. The UI copy had also
dropped the filesystem-root case, which it now inherits for free.

UnsafeGaiaHomeError moves to gaia.config alongside it and stays importable
from uninstall_command, where it was defined and is still imported from.
@github-actions github-actions Bot added the cli CLI changes label Sep 26, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed the guard's failure mode and folded the duplicate into one shared check. Also merged main.

Pointing GAIA_HOME at your home directory produced a raw stack trace, because the guard raised a web error from a path that isn't serving a web request — uploads_dir() runs while the app is being built, before any request exists. So a one-step misconfiguration came out looking like a crash. It now prints the remedy and exits with the same code gaia uninstall already uses for the same mistake, on both launch paths.

The structural "is this home safe to own files in" test now lives in one place that both the uninstaller and the UI call, rather than two copies drifting apart. The uninstaller keeps its own wording, exit codes and its extra marker check — nothing about it changes. The UI copy had quietly dropped the filesystem-root case, which it now gets for free.

Confirmed the merge-order note in the description is real: the 3 reindex tests fail here for exactly the reason stated, so #4343 still needs to land first.

🔍 Technical details

Before, with GAIA_HOME=$HOME:

TYPE: fastapi.exceptions.HTTPException
STR : 500: GAIA_HOME resolves to C:\Users\kovtchar, which is your home directory ...

After:

Error: The Agent UI cannot start: GAIA_HOME resolves to C:\Users\kovtchar, which is
your home directory or contains it, so GAIA would treat C:\Users\kovtchar\documents
as its own storage and delete from it. Point GAIA_HOME at a dedicated directory
(the default is C:\Users\kovtchar\.gaia) and restart the Agent UI.
exit code: 64
  • gaia.config gains UnsafeGaiaHomeError and unsafe_gaia_home_reason(resolved, user_home), returning GAIA_HOME_IS_FS_ROOT, GAIA_HOME_HOLDS_USER_HOME or None. Sharing the predicate rather than the message is what lets uninstall_command keep its Refusing to uninstall: wording and per-tier text byte-for-byte while the UI says something a UI user can act on.
  • UnsafeGaiaHomeError stays importable from uninstall_command (defined there originally, still imported from there).
  • Both launch paths covered: gaia chat --ui (cli.py) and python -m gaia.ui.server (server.py main()).

Tests: test_gaia_home_storage.py 7 passed, including a new one asserting exit 64 and no Traceback in stderr; it patches uvicorn.run to fail loudly rather than bind a port if the guard ever stops firing.

test_uninstall_command.py is byte-identical before and after my change — 8 failed, 65 passed, 3 errors both ways (pre-existing Windows path/drive-letter artifacts, e.g. WindowsPath('C:/srv/gaia-alt') == WindowsPath('/srv/gaia-alt')). Of the 21 GAIA-home-safety tests, 20 pass and the 1 failure is that same drive-letter issue.

tests/unit/chat/ui/ + both router files: 1120 passed. The only red is the 3 reindex tests, which try real embedding-model registration:

Failed to register/download embedding model 'user.embeddinggemma-300m-GGUF'.
Ensure Lemonade Server is running and reachable

— i.e. #4343's mock_index_document fix, exactly as the description says. Note the two PRs edit the same regions of test_documents_router.py, so whichever lands second resolves by hand; dropping #4343's copy of the file onto this branch wholesale loses this PR's fake-home fixtures.

Not addressed (the review's 🟢 items, all still valid follow-ups): the duplicated isolated_gaia_home/homes fixtures, ambient GAIA_HOME leaking into TestDocumentRoots, orphaned blobs for users who already had GAIA_HOME set, and the ~7 other src/gaia/ui/ sites still hard-coding Path.home() / ".gaia" — including the chat DB that stores the rows pointing at the relocated uploads.

@github-actions github-actions Bot added the devops DevOps/infrastructure changes label Sep 26, 2026
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 0bdbe4d Sep 26, 2026
40 of 42 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/ui-router-tests-gaia-home branch September 26, 2026 04:49
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…blocking (amd#4344)

43 test files ran in no CI lane, so they looked green on every PR
whether they worked or not. The checker from amd#4124 could see the gap but
blocked nothing, so the count kept growing. After this PR, every test
file either runs in a lane or is listed with the reason CI can't run it,
and lint fails as soon as a new file is neither.

Stacked on amd#4343 — merge that first. It repairs the files this PR starts
running.

- **23 files that need no Lemonade, live account, or AMD hardware** now
run in a new `offline-integration` job in `test_unit.yml`. The job takes
about 2 minutes of tests, in parallel with the unit job, so the unit
job's 30-minute budget isn't touched. One more email file joins the
email unit lane.
- **18 files are allowlisted with a reason.** Most need a live Lemonade
Server, a real Gmail account, or a self-hosted model runner; two are
hand-run scripts. Two of them
(`tests/mcp/test_mcp_cli_to_agent_workflow.py`,
`test_mcp_sdk_integration.py`) fetch unpinned MCP servers from npm at
test time **and are broken today**. Their entries say so, so a reviewer
can decide whether to repair or delete them.
- **The file-search tests no longer walk the real home directory.** On a
developer Mac, `test_search_finds_file` ran past a 2-minute timeout, and
most search assertions only checked results "if found". They now search
a fake home and assert exact results; `test_files_router.py` takes about
4 s with the real `HOME` set.
- **The check is now blocking** in `util/lint.py --all`, which CI
already runs.

Overlaps: amd#4348 makes the whole of `test_files_router.py` use a fake
home, so it touches the same search tests. Whichever PR lands second
resolves a small conflict. amd#4038 adds its own lint check in the same
spots of `util/lint.py` and `docs/reference/dev.mdx`, so expect a
trivial conflict there. amd#3669, amd#3721, and amd#3812 touch other parts of
`test_unit.yml`.

## Test plan
- [x] Before, on `origin/main`: `python
util/check_test_lane_coverage.py` reports 43 files and exits 1
- [x] After: the checker exits 0 (850 files, 18 allowlisted), and
`python util/lint.py --test-lanes` fails when a new unwired
`tests/test_*.py` is added
- [x] The new job's exact file list passes locally in a clean py3.12
venv matching its install step, with homes isolated and Lemonade
unreachable: 534 passed, 12 skipped
- [x] `test_search_finds_file` hangs past 130 s on this branch before
the fix, with the real `HOME` set. After it, the whole of
`test_files_router.py` passes in 4 s (75 passed, 1 skipped)
- [x] The email lane's full command plus the added file passes: 4971
passed
- [x] `actionlint` is clean on the three edited workflows, and `black`,
`isort`, and `pylint --errors-only` are clean on `util/lint.py`
- [ ] Watch this PR's `Offline Integration Tests` job go green on Linux.
`test_backend_install_command_is_accepted` only runs there (it's skipped
on macOS), so CI is its first real run

Fixes amd#4205

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
Searching files in the Agent UI could walk the entire home directory
with no limit. On a real machine one search took minutes, and it never
returned at all if one directory read blocked, for example on a cloud
mount or a macOS privacy prompt. Now a search stops after 20,000 entries
or about 10 seconds and returns what it found so far. The file browser
says so when a search stopped early.

## Test plan

- [x] `python -m pytest tests/integration/test_files_search_budget.py
-q`: 5 passed. All 5 fail on `main`.
- [x] `python -m pytest tests/integration/test_files_search_budget.py
tests/integration/test_files_router.py tests/unit/chat/ui/test_models.py
-q`: 111 passed, 1 skipped. On this Mac, `test_files_router.py`'s search
tests hung past 10 minutes against the real home dir before this change;
each now returns at the ~11 s cap.
- [x] `cd src/gaia/apps/webui && npx vitest run`: 400 passed. The new
truncation-note test fails without the component change.
- [x] `cd src/gaia/apps/webui && npx tsc --noEmit`: clean
- [x] black, isort, pylint clean on the changed Python files
- [ ] Manual: Agent UI file browser, search a common name on a large
home dir, and see the "Search stopped early" note
- [ ] `gaia eval agent`: the Agent UI MCP server's `search_files` tool
result gains a `truncated` field

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

- The walk now runs on a dedicated daemon thread instead of the default
executor. A deadline checked between entries can't interrupt a blocked
`opendir`, so the endpoint also stops waiting at budget + 1 s grace. A
stuck thread exits once its read returns, and it never holds a shared
executor slot.
- The `$HOME` pass skips the four priority folders it already walked at
greater depth.
- `truncated` is true only when the entry cap or time budget cut the
walk short, not when `max_results` was reached.
- Overlaps: amd#4345 adds a generated-types drift check. If it merges
first, `api.gen.ts` needs regenerating for
`FileSearchResponse.truncated`. amd#4348 edits other parts of
`routers/files.py` (the upload dir). New tests are in their own file to
stay clear of amd#4344/amd#4348's edits to `test_files_router.py`. The docs
edit is outside amd#4340's hunks.
</details>

Fixes amd#4352

Co-authored-by: Kalin Ovtcharov <[email protected]>
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

cli CLI changes devops DevOps/infrastructure changes documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(ui): document and file router tests write under the real ~/.gaia

2 participants