Skip to content

test(webui): fail CI when the Agent UI's API types drift from the backend - #4345

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:claude/webui-api-type-drift-guard
Sep 26, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:claude/webui-api-type-drift-guard

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

The Agent UI's TypeScript API types are written by hand, and nothing checked them against what the backend actually sends. Five had already drifted: settings were missing the agent mode, system status was missing the active profile, schedules were missing their parsed config, and three fields were typed as never-null although the backend sends null. Now CI fails and names the field whenever a hand-written type and the backend disagree, and those five types are fixed. Nothing changes for users; no UI code read the missing fields yet.

This is the type-generation half of #4246. It also covers #3327's "snapshot the schema" and "check the TS types agree" items, but not its route response_model and conformance-test items.

Test plan

  • python -m pytest tests/unit/chat/ui/test_export_openapi.py tests/unit/chat/ui/test_models.py tests/unit/chat/ui/test_server.py tests/unit/test_webui_agent_info_contract.py -q: 170 passed
  • python -m gaia.ui.export_openapi --check exits 0, also from another working directory with different env
  • cd src/gaia/apps/webui && npx tsc --noEmit: clean. With main's types/index.ts restored it fails five times, naming agent_mode, active_profile, schedule_config, mail_provider, extension
  • cd src/gaia/apps/webui && npm test: 400 passed. Deleting one line from api.gen.ts fails the new generation test and node scripts/gen-api-types.mjs --check
  • npm run build succeeds
  • black, isort, pylint clean on the new Python files
  • CI: the Agent UI Vitest job's new Type-check step passes
🔍 Technical details

The pipeline: python -m gaia.ui.export_openapi writes src/types/api.schemas.json from create_app(":memory:").openapi(), then npm run gen:api-types writes src/types/api.gen.ts. Each step has a stale check: a pytest test for the JSON and a Vitest test for the TS. src/types/apiContract.ts then compares 18 hand-written wire types with their generated counterparts at compile time. It flags backend fields missing from TS, TS fields never sent, and kind mismatches (string/number/boolean/null/array/object). It also has a self-test so it can't pass vacuously. tsc runs in the PyPI build on every PR, and now in the Agent UI Vitest job too.

Why not openapi-typescript: it has a peer dependency on typescript@^5 and uses the TS 5 compiler API. The Agent UI is on TypeScript 7, the native port, which has no JS API, so npm refuses the install. Its 6.x line has no TS dependency but pulls a vulnerable undici. [email protected] is pinned exact and adds no new npm audit findings (still 6, all pre-existing). The lockfile was written with npm 11 to keep its libc fields.

Only the component schemas are snapshotted, not the full OpenAPI doc. Route docstring edits don't cause regenerations, since the types don't depend on them.

AgentInfo's 14 "TS-only" fields aren't drift. They're Hub catalog fields from merge_with_registry, and tests/unit/test_webui_agent_info_contract.py (#3846) already checks each one against its emitter. The contract allowlists exactly those 14.

Not covered: camelCase view models (Message, AgentStep, CommandOutput), and TS types whose routes have no response_model (tunnel, MCP, connectors). The latter are #3327's remaining work.

Things to know:

  • CI installs unpinned fastapi/pydantic, as the email agent's export_openapi --check already does. The committed snapshot matches the current latest (fastapi 0.141.1, pydantic 2.13.5), but a future release that changes schema output would need a regenerate.
  • A dependabot bump of json-schema-to-typescript or its prettier dependency may need npm run gen:api-types run on its PR.

Overlap:

Part of #4246

…kend

The Agent UI's TypeScript API types were hand-written against the backend's
pydantic models with nothing checking them, and five had already drifted:
Settings lacked agent_mode, SystemStatus lacked active_profile, Schedule lacked
schedule_config, and Session.mail_provider / FileEntry.extension+modified were
typed non-null although the backend sends null.

- python -m gaia.ui.export_openapi snapshots the backend's component schemas
  (built in-process, no server) to src/types/api.schemas.json; a unit test
  fails when the snapshot is stale.
- npm run gen:api-types generates src/types/api.gen.ts from that snapshot with
  json-schema-to-typescript (pinned); a Vitest test fails when it is stale.
  openapi-typescript was not usable: it needs the TypeScript 5 JS API, and the
  Agent UI is on TypeScript 7.
- src/types/apiContract.ts makes tsc fail, naming the field, when a
  hand-written wire type misses a backend field, declares one the backend
  never sends, or disagrees on its kind. The Agent UI Vitest job now runs tsc.
- The drifted types are reconciled; frontend behaviour is unchanged.

Part of amd#4246
@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes tests Test changes labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Approve with suggestions

This wires a real drift guard between the Agent UI's hand-written API types and the backend's pydantic models — a snapshot of the backend schemas, a generated TypeScript mirror, a compile-time comparison of 18 wire types, staleness checks on both generated artifacts, and a self-test so the guard can't pass vacuously. It's careful work and the five pre-existing drifts it uncovered justify it on their own.

One thing worth fixing before merge: the type comparison only catches drift in one direction. It flags a hand-written type that's missing a field or claims a value is never null when the backend does send null — which is what this PR set out to catch. It does not flag the mirror case, where the hand-written type says a value can be null but the backend never sends null. Two fields in this very PR are in that state, so the guard ships with a known blind spot while its own comment claims it catches any kind disagreement. Either make the comparison symmetric (two small type fixes fall out of it, plus a few test fixtures) or narrow the comment to say what it actually checks.

Two smaller things: a Windows checkout can make the local staleness check for the generated TypeScript file report a false failure, because the newline handling there isn't normalized the way the test's is; and because the backend's web framework dependencies have no upper version bound, a future release that changes schema output will fail the snapshot test on every unrelated PR until someone regenerates. Both are documented-and-acknowledged territory rather than blockers.

Real-world evidence

N/A — no evidence bundle was produced for this PR, and the change touches no user-facing surface: it adds generated types, a schema snapshot, tests, and a CI step, with no runtime behaviour change (the five corrected types are fields no UI code reads yet). The PR description already carries the relevant command output — the new pytest module, python -m gaia.ui.export_openapi --check, npx tsc --noEmit with the pre-fix failures named, npm test, and npm run build. The verdict rests on static review plus that reported output.

🔍 Technical details

🟡 Important

Kind comparison is one-directional; the file's own contract overstates it (src/gaia/apps/webui/src/types/apiContract.ts:57-72)

Kind<T> distributes over unions, and KindMismatch then asks [Kind<Wire[K]>] extends [Kind<Ts[K]>]. That is assignability, not equality, so a hand-written type whose kind set is a superset of the wire's passes silently:

field hand-written (index.ts) wire (api.gen.ts) flagged?
SystemStatus.lemonade_url string | null string no
SystemStatus.default_model_name string | null string no

Both are str with a default in src/gaia/ui/models.py (e.g. lemonade_url: str = "http://localhost:13305"), so the backend never sends null and the UI's null handling is dead. Meanwhile the header comment at line 8 promises the guard fires when "a shared field's kind … disagrees", which a reader will take as symmetric.

The file already has the Equals helper needed to close it:

type KindMismatch<Wire, Ts> = {
    [K in Shared<Wire, Ts>]-?: Equals<
        Kind<Exclude<Wire[K], undefined>>,
        Kind<Exclude<Ts[K], undefined>>
    > extends true
        ? never
        : K;
}[Shared<Wire, Ts>];

DriftSelfTest still passes under this (number | null vs number remains a mismatch). The tail is the two fields above plus the three test fixtures that set lemonade_url: null (SettingsPage.test.tsx:56, ModelDownloadStep.test.tsx:42, setupHints.test.ts:31). If you'd rather keep the asymmetry deliberately — a permissive TS type is harmless at runtime — then just tighten the comment to say the guard checks the wire's kinds are representable in the TS type, so the next reader doesn't over-trust it.

🟢 Minor

A CRLF checkout breaks gen-api-types.mjs --check (.gitattributes:37-39)

api.gen.ts is compared byte-for-byte in the --check path (scripts/gen-api-types.mjs:81-90), with no newline normalization — unlike apiGen.test.ts:11, which normalizes, and unlike the Python side, where read_text gets universal newlines for free. With core.autocrlf=true (the Windows default) the documented local check reports stale on a clean tree. There's no * text=auto in this repo, so the cheapest fix is to pin the two generated files, matching how the existing entries in this file handle exactly this class of bug:

# Generated from the Agent UI backend models; regenerate, never hand-edit.
# eol=lf: the --check paths compare bytes, so an autocrlf checkout reports stale.
src/gaia/apps/webui/src/types/api.gen.ts linguist-generated=true text eol=lf
src/gaia/apps/webui/src/types/api.schemas.json linguist-generated=true text eol=lf

Unpinned fastapi/pydantic makes the snapshot a repo-wide CI tripwire (tests/unit/chat/ui/test_export_openapi.py:12)

setup.py has pydantic>=2.9.2 and fastapi>=0.115.0 with no ceiling, and test_unit.yml triggers on src/** — so the first upstream release that changes JSON Schema emission turns every open PR red until someone regenerates. The PR description acknowledges this; the failure message does name the fix, which keeps it recoverable. Worth considering an upper bound, or a note in docs/reference/dev.mdx next to the regenerate block.

gen-api-types.d.mts can drift from the .mjs it describes (src/gaia/apps/webui/scripts/gen-api-types.d.mts:4-7)

Nothing checks the hand-written declaration against the module's real exports — renaming generateApiTypes would leave a stale declaration and a confusing type error in apiGen.test.ts rather than at the source. Low stakes at four exports; just don't grow it much further without a check.

Strengths

  • DriftSelfTest is the part that makes this durable — most compile-time contracts like this silently degrade to never after a refactor and pass forever. Asserting the guard's own output shape prevents exactly that.
  • Both generated artifacts have a staleness check on the side that owns them (pytest for the JSON, Vitest for the TS), so there's no half-regenerated state that type-checks.
  • CatalogOnlyAgentInfoFields allowlists the 14 Hub fields explicitly rather than loosening the comparison for AgentInfo, and points at the test that covers them instead — narrow escape hatch, documented reason.
  • Verified independently: create_app registers every router unconditionally and no schema default is derived from the environment (only static localhost literals), so the snapshot is reproducible across machines — which is what the whole scheme rests on.

KindMismatch compared kinds with assignability, so it only caught a TS type too
NARROW for the wire. A hand-written type whose kind set was a superset passed
silently -- SystemStatus.lemonade_url and default_model_name were both declared
string | null for fields the backend always sends as str, leaving dead null
handling in the UI and a guard whose own header claimed it caught any kind
disagreement.

Switch to Equals, fix the two types and the fixtures that set them null, and add
a self-test that pins BOTH directions so a regression to assignability fails the
build rather than quietly reopening the blind spot.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Confirmed the blind spot and made the kind check symmetric — the two fields are SystemStatus.lemonade_url and SystemStatus.default_model_name.

Both were hand-written as string | null for backend fields that are str with a default and can never be null, so the UI carried null handling that can't fire. The guard passed them because it compared kinds with assignability, which only catches a TS type too narrow for the wire.

Rather than just fix the two types, I switched KindMismatch to Equals so the reverse direction fails the build, and added a self-test pinning both directions — the existing DriftSelfTest only covered the narrowing case, so a future refactor back to assignability would have reopened this silently.

I could not run the project's tsc (no node_modules here, and npm can't reach the registry from this lane), so I type-checked the three type files directly with a standalone TypeScript 5.9.2 — they're self-contained, no imports. Results below.

Python side post-merge: test_export_openapi.py, test_models.py, test_server.py, test_webui_agent_info_contract.py → 170 passed, and export_openapi --check exits 0, so the snapshot is still fresh after merging origin/main (clean). black/isort clean.

🔍 Technical details

The blind spot, demonstrated four ways (all against the real index.ts / api.gen.ts / apiContract.ts):

guard TS types tsc
assignability (as in PR) string | null exit 0 — silent
Equals (this change) string | null fails, names default_model_name
Equals fixed (string) exit 0
assignability, with the new self-test present — fails — self-test is non-vacuous

Backend proof the fields are never null: src/gaia/ui/models.py — default_model_name: str = "Gemma-4-E4B-it-GGUF" and lemonade_url: str = "http://localhost:13305". Both surface as ?: string in api.gen.ts (optional from the default, never nullable).

Fixtures updated: SettingsPage.test.tsx (both fields) and ModelDownloadStep.test.tsx (lemonade_url). setupHints.test.ts already used real strings, so it needed no change. The default_model_name fixture now holds 'Gemma-4-E4B-it-GGUF', which is exactly what ?? DEFAULT_MODEL_NAME previously produced from null, so no assertion changes meaning.

Left alone: the ?? DEFAULT_MODEL_NAME call sites use optional chaining on a possibly-undefined systemStatus, so they're still needed. ConnectionBanner.tsx:356's ?? 'http://localhost:13305' is now unreachable but harmless; removing it is a behavior change without a test, so I left it.

Not addressed (🟢): the .gitattributes CRLF pin and the unbounded fastapi/pydantic versions.

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]>
amd#4354 added `truncated` to FileSearchResponse after this branch last
regenerated, so the committed artifacts were stale and this PR's own
drift check failed against them.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 2e0b6ab Sep 26, 2026
65 of 69 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/webui-api-type-drift-guard branch September 26, 2026 07:29
kovtcharov-amd added a commit that referenced this pull request Sep 26, 2026
Merging main's apiGen.test.ts (which opts into @vitest-environment
node via #4345) with this branch's scrollIntoView polyfill in
setup.ts broke that suite: HTMLElement doesn't exist in the node
environment, so the global setup file threw before any test ran.
Guard the polyfill so both coexist.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devops DevOps/infrastructure changes documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants