Skip to content

feat(tui): add the preflight readiness gate - #2486

Merged
kovtcharov-amd merged 7 commits into
claudia/task-fd276692from
claudia/task-a140d608
Jul 27, 2026
Merged

kovtcharov-amd merged 7 commits into
claudia/task-fd276692from
claudia/task-a140d608

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Every way the daemon path can fail — daemon down, token rotated, version gate, model missing, mailbox not connected — reached the user as a raw HTTP status, discovered one wall at a time. The gate reports all of it as checkable rows, each with a remedy.

Its own review found remedies that damaged what they claimed to fix: the mailbox rows named commands that overwrite an agent's existing scopes, so following the advice turned "connected, can read, cannot send" into "can send, cannot read" — and the row then went green over a mailbox that was strictly worse off. A relay 503 also decoded as "Lemonade unreachable", sending users to a component that was not the problem.

An unverifiable condition renders as unknown and keeps the check failing, but no longer demands a keypress the user cannot act on — a prompt shown on every launch that nobody can satisfy just trains people to dismiss prompts.

Test plan

  • cd tui && make lint && go test ./... -count=1 -race
  • Each row's remedy names a command that exists and does not reduce existing access
  • A version the server does not advertise renders as unknown, not as a pass
  • Renders inside 80x24

The daemon could install agents but the interface had no way to ask — the hub
listed email as Available with no key to act on it, and `gaia tui` had only
chat and hub. The hub can now install and uninstall, and the CLI gained
list/install/uninstall/run/status with a real non-interactive one-shot.

Installing a non-verified agent runs third-party code, so the 403 opens a
gate that names what is being trusted — agent, version, publisher, security
tier, download size, scopes — and only then retries. Trust is never assumed.

Also: switching tabs no longer leaves nothing selected (#2481), the hub fits
an 80x24 terminal, backspace no longer triggers uninstall, and a fresh
machine no longer opens on an empty screen.
Every way a TUI agent launch can fail — daemon down, token rotated, host
API skew, sidecar not started, Lemonade missing or too old, model not
downloaded, no mailbox connected, mailbox connected but not granted send —
currently reaches the user as a raw HTTP status. This adds the screen that
answers all of them: one row per precondition with a state, a human line,
and a remedy that names a real command, plus a keypress for the fixes that
are safe to run from here (start the daemon, start the sidecar, pull the
model, hand off to the connector flow).

Three things worth knowing about the implementation:

- `unknown` is its own state. GET /v1/<agent>/init reports
  `compatible: null` when Lemonade does not advertise a version; that is an
  indeterminate check, not a pass, so it renders as [?] and keeps the report
  from claiming ready — while still not blocking the launch, matching the
  sidecar's own policy.
- The error ladder is a standalone mapper from a failed call to
  {cause, remedy, where-to-look}, ported from the email playground's
  `diagnose` and extended with the daemon's typed errors. Chat can reuse it
  for mid-run failures rather than re-deriving it.
- The model pull's outcome comes from the final progress line's ✓/✗, never
  from the HTTP status: once the sidecar commits a streamed 200 the status
  can no longer change.

The four generic rows work for any sidecar agent that implements
GET /v1/<agent>/init; the mailbox row is email-specific and arrives through
an extras hook.

Not yet mounted — root/model.go is owned by another change in flight.
Review of the readiness gate found remedies that damage the state they
claim to fix, plus a set of lifecycle bugs. All verified against source
before changing:

- The mailbox remedies named `gaia connectors grants grant` and a
  send-only `--scopes` list. `grant_agent` OVERWRITES an agent's existing
  scopes (grants.py), and `connectors connect --scopes` REPLACES the
  provider defaults rather than adding to them (flow.py). Following either
  turned "connected, can read, cannot send" into "can send, cannot read" —
  and the row then went green over a mailbox that was worse off. Both now
  reconnect with the same default ∪ mail scope union the sidecar's own
  /configure builds.
- A relay 503 (`{"detail": ...}`, no readiness object) decoded into value
  structs as "Lemonade unreachable", so a sidecar that died mid-check told
  the user to start the model server. The readiness fields are pointers now
  and a body that is not a readiness answer fails loudly as one.
- The Go transport ladder answered "start lemonade-server" to a refused
  connection, but this process only ever dials the daemon — a daemon that
  restarted on a new port pointed the user at the one process not involved.
  Transport errors and service-authored bodies are separate ladders.

Lifecycle and concurrency:

- Cancel() only cancelled the download; check/start/ensure each held their
  own context, so leaving the screen could still spawn a sidecar minutes
  later.
- The provisioning result was delivered by a select that was also ready on
  ctx.Done(), so a pull finishing at its deadline lost its result half the
  time and produced "Download failed." with no cause and no remedy.
- A ready report's 800ms tick was never cancelled, so esc inside that window
  still launched the agent; esc during a download left the screen
  permanently "busy".
- The provisioning stream capped response headers at 120s, but the relay
  buffers non-SSE responses — no header arrives until the pull finishes, so
  every real download would have been aborted and blamed on a timeout.

Also: an indeterminate row now proceeds after a longer hold that names what
could not be verified, instead of demanding a keypress on every launch
against a Lemonade that does not advertise a version.
The gate caches the verified daemon instance between calls, and the client
token rotates on every daemon restart — so a sibling process restarting the
daemon mid-check is the failure mode most likely to resurface. It was only
ever confirmed by hand. These drive the REAL daemon client against a
daemon-shaped server plus its instance.json, so discovery, the two-check
trust rule, the version gate, and the 401 replay are all exercised:

- a restart between two calls of one check recovers silently, with exactly
  one 401 — more would mean the refreshed instance was thrown away and every
  later call re-discovered it
- the same rotation on a relayed call (the path a chat turn takes) recovers
- a second pass reports the NEW pid rather than the cached one
- a daemon that dies and does not come back fails with the daemon's own
  remedy, never a raw 401 and never blamed on Lemonade
- a daemon that moved to a new port recovers on the next attempt: a failed
  call invalidates the cache instead of poisoning every later one

Also adds the test that was missing behind Cancel(): an in-flight ensure now
has to observe cancellation when the user leaves, which is what stops a
sidecar spawning minutes after they walked away.

Every fix from the previous commit was mutation-verified — reverted one at a
time, with the named test confirmed to fail and the failure message shown to
name the real symptom.

Documents on Report why an indeterminate row does not block: Ready(),
Blocked(), and "does the launch stop" are three separate questions, and a
prompt the user cannot ever action is dismissed reflexively and devalues
every other prompt. Pinned by a test so the state cannot quietly become a
pass.
@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes mcp MCP integration changes cli CLI changes tests Test changes agents agent::email Email agent changes tui Go terminal UI (gaia-tui) daemon Daemon supervisor / sidecar control plane sidecar Agent sidecar contract / harness labels Jul 25, 2026
@kovtcharov
kovtcharov changed the base branch from main to claudia/task-fd276692 July 25, 2026 10:58

@kovtcharov-amd kovtcharov-amd left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving — the preflight readiness gate fails loudly as intended: StateFailed blocks the launch, StateUnknown is explicitly not a pass (row stays not-ready), and every remedy names cause + command + where-to-look. The transport reuses the existing daemon auth verbatim and the token never enters DaemonInfo/logs (with a rotation-recovery test). The ladder correctly distinguishes a Go transport error (always the daemon) from the same words in a response body (the sidecar reporting Lemonade).

The one failing check is the same unrelated SD/Lemonade Windows-runner infra flake (lemonade-server: CommandNotFoundException) — this PR only adds Go files under preflight/ and can't affect it; all Go gates are green.

The readiness gate was built, tested and merged — and nothing imported
it, so no user could reach it. Pressing enter on an installed agent
still went straight to chat, and the first sign of a missing model or a
disconnected mailbox was a failed turn mid-conversation. The gate now
sits on the launch path.

It runs on every launch and caches nothing: the daemon can be killed,
its token rotates on restart, the model server can unload the model and
a mailbox grant can be revoked from the web, so a remembered pass would
open a chat that cannot answer while claiming it had been verified.

Review caught the launch this seam exists to prevent — backing out of a
slow check and launching a second agent let the first agent's all-green
report hand off and open a chat for an agent nothing had probed. Reports
now name their agent and stale ones are dropped.

### Test plan
- [ ] `cd tui && make lint && go test ./... -count=1 -race`
- [ ] Launching an agent shows the gate, not chat; proceeding reaches
chat; cancelling returns to a hub with a valid selection
- [ ] Start a check, cancel, launch a different agent → the first
agent's report cannot green-light the second
- [ ] A failing precondition keeps the user on the gate with a runnable
command
)

`gaia tui run <id> --query "..."` is the scriptable, CI-friendly path.
With the local model server down it **hung indefinitely and printed
nothing at all** — no stdout, no stderr, no exit — so an automated job
wedged until its own timeout with an empty log. It now fails in under a
second, naming the unmet condition and a runnable remedy on stderr, exit
1, with stdout left untouched so redirecting still captures only the
answer.

Two parts, because a readiness check alone is not enough: the one-shot
runs the same headless check the interactive gate uses, so the two paths
cannot drift apart; and every phase gets a bounded context, so a
dependency that accepts the connection and then stalls has something to
fail against.

Closes #2483.

### Test plan
- [ ] With the model server stopped: `gaia tui run email --query "hi"`
exits 1 within seconds, stderr names the row and the command, stdout is
empty
- [ ] With everything healthy: the answer lands on stdout and exit is 0
- [ ] A dependency that accepts and then stalls hits the deadline rather
than hanging
- [ ] `cd tui && make lint && go test ./... -count=1 -race`
…outes (#2491)

Only one agent in the repo could tell you whether it was actually ready
to work. The email sidecar hand-wrote `GET`/`POST /v1/email/init`; the
other 18 hub agents had nothing, so a consumer could see the process was
up but had no way to learn the model it needs was never downloaded — the
failure surfaced later, mid-task, as a confusing error. Now an agent
*declares* what it needs (a model id, a minimum backend version) and
`AgentServer` serves both verbs for it. The response is byte-compatible
with email's existing endpoint, so the TUI preflight gate parses both
without a branch and email keeps serving unchanged until its swap-over
lands separately.

The boundary is enforced, not just documented: inherited init makes
*this agent's* requirements ready against a backend that is already
running. Installing the backend stays with `gaia init` — an agent
process cannot bootstrap the server it depends on, so an unreachable
backend fails loudly and names whose job the fix is instead of hanging
or half-succeeding.

## The failure this is designed against

**An agent that declares nothing gets no `/init` at all — not a cheerful
one.**

That is the whole design rule, and it is worth stating because the
cheerful version is the one that ships and then wastes somebody's
afternoon. A readiness endpoint built from an empty declaration would
answer `ready: true` the moment Lemonade happened to be up, having
verified nothing about the agent — and a consumer would believe it. So
the routes are only mounted when the agent actually declared something,
whether it passed an empty declaration object or a manifest with no
`models:`.

This is the same shape as several bugs already found in this project:
**something reports ready, and only fails when the user tries to use
it.** A mailbox row green over dead credentials; a transport reporting
"Connected" before `executable file not found`; a control file naming a
dead pid. A green light that was never wired to anything is worse than a
red one, because it costs a debugging session to disbelieve.

Three related distinctions the contract preserves for the same reason,
each with a different remedy: an unreadable model list is *"could not
tell"*, never *"missing"* (reporting it as missing sends the user to
re-download a model they may already have); a backend advertising no
version is indeterminate, never a pass; and a version-too-old is
reported *before* a missing model, so nobody downloads gigabytes an old
server may then refuse to serve.

## Test plan

- [x] `python -m pytest tests/unit/test_agent_readiness.py
tests/unit/test_agent_server.py` — 75 pass (48 new, 27 pre-existing, no
regressions)
- [x] `python util/lint.py --all` — exit 0
- [x] Live against `lemond` v10.10.0 on port 13305, serving a test agent
through `AgentServer`:
- `GET` with model present → `200 {"ready":true,...,"ctx_size":65536}`,
byte-identical to email's response for the same state
- `GET` with backend unreachable → `503`, hint names `lemonade-server
serve` and "host prerequisite"
- `POST` with model present → `200`, correctly no-ops instead of
re-pulling, final line `✓`
- `POST` with an unknown model → committed `200` with final line `✗
Provisioning failed: HTTPError: 400` — proves the final line, not the
status, carries the verdict
  - `POST` with backend unreachable → `503`, pulls nothing
- [x] A test fails the build if the model probe is ever reached on a
dead backend, so an installer cannot quietly grow here later

## Follow-ups (deliberately not in this PR)

- **Email swap-over** — sequenced after the in-flight #2469 onboarding
work to avoid two changes in `api_routes.py`. Email's `/init` serves
unchanged meanwhile, so nothing regresses mid-flight. The dead
`EmailAgentConfig.model_id or …` branch (that field is always `None`)
disappears with the swap rather than being patched in a file about to
change.
- **#2493 makes `requirements.min_lemonade_version` parse.** Email's
manifest declares it and `gaia.hub.manifest.Requirements` was dropping
it, so `AgentRequirements.from_manifest` currently reports the version
gate as indeterminate rather than fabricating a pass. Once #2493 merges
the value flows through automatically and the `NOTE` in that docstring
should be dropped.
@kovtcharov-amd
kovtcharov-amd merged commit 2aa08c0 into claudia/task-fd276692 Jul 27, 2026
14 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claudia/task-a140d608 branch July 27, 2026 09:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes agents cli CLI changes daemon Daemon supervisor / sidecar control plane devops DevOps/infrastructure changes documentation Documentation changes mcp MCP integration changes sidecar Agent sidecar contract / harness tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants