Skip to content

fix(tui): keystroke-free one-shot remedies and synchronous abandon cancel - #2490

Closed
github-actions[bot] wants to merge 48 commits into
mainfrom
autofix/issue-2489
Closed

github-actions[bot] wants to merge 48 commits into
mainfrom
autofix/issue-2489

Conversation

@github-actions

Copy link
Copy Markdown
Contributor

A one-shot failing its readiness check printed remedies that told the reader to press r / press f — keys that do not exist in a process that has already exited. And a one-shot that gave up at its deadline left the sidecar running: the relay cancel was fired in a goroutine while the CLI was exiting, so it usually never landed, burning a model slot (and, for the email agent, letting a mutation complete with nobody watching). After this change the shared readiness report is keystroke-free — the interactive gate still offers r/f/d in its footer — and the abandon cancel is delivered before the process exits.

Follows up on #2489 (both items the #2488 one-shot fix deliberately left alone). Based on claudia/task-5fcce79e (PR #2488), not main — the one-shot readiness code and SSEClient only exist on that branch, so this stacks on it and should merge after / into it.

Closes #2489

Test plan

  • cd tui && go test ./... passes (adds TestSSEClientCloseCancelsInFlightRunSynchronously and a keystroke-free assertion in TestEveryFailedRowIsActionable)
  • cd tui && go vet ./... && gofmt -l internal test clean
  • A one-shot failing on readiness (gaia tui run email --query "…" with Lemonade down) prints no press r/press f instruction; the run: line remains
  • The interactive gate still shows r re-check / f fix in its footer
  • A one-shot abandoned at its deadline (a wedged sidecar) results in the relay cancel actually being delivered, and the sidecar shows no orphaned run after the CLI exits
🔍 Technical details

1. Keystroke-free remedies (internal/ui/preflight/)

The one-shot renders the same preflight.Report the interactive gate does (via Report.String() / ReportReadiness), but the shared Remedy.Action / Diagnosis.Remedy strings baked in "then press r to re-check" and "press f to …". Stripped the keystroke wording from all shared strings in check.go, ladder.go, model.go, provision.go. The gate's own footer (view.go footer()) already lists r re-check, f <fix>, d details independently, so the interactive affordance is unchanged — only the baked-in wording is gone.

2. Synchronous abandon cancel (internal/client/sse.go)

On the deadline path, RunOneShot returns and app.go's defer c.Close() runs, after which cobra calls os.Exit. Close() only called active.cancel(), which unblocked consume() to fire go s.cancelRun(handle) — async, and the process exited first, so the POST rarely landed.

  • Added cancelOnce sync.Once to runHandle; cancelRun now wraps doCancelRun in it, so consume() and Close() cannot double-send and a second caller blocks until the first finishes.
  • Close() now calls s.cancelRun(active) synchronously after active.cancel(), bounded by the existing cancelTimeout (10s). On a clean turn s.active is already nil, so this is a no-op; it only does work when a run is genuinely in flight.

No change to RunOneShot was needed — the deferred Close() already runs on the abandon path; making it synchronous is what lands the cancel before exit.

Verified with go test -race ./internal/client/... and the full go test ./... suite (green). TestSSEClientCloseCancelsInFlightRunSynchronously asserts the cancel is recorded immediately after Close() with no polling.

The TUI can only talk to agents over a stdin/stdout pipe, but the email
agent has been a daemon-managed HTTP sidecar since #2191 — so it shows up
in the hub greyed out and unusable. This plan scopes what it takes to make
it a first-class TUI agent: install/run/uninstall from the hub and the
command line, interactive-and-autonomous by default, and a settings screen.

Also records two findings that shape the design: the CLI console
auto-approves every gated tool (send, forward, permanent delete), and the
canonical /query SSE contract cannot complete a confirmation-gated action.
Once the TUI can install, run, and configure the email agent, the gaia email
subcommand is a second front door to the same sidecar with none of the UI.
Scopes its removal, and pins the sequencing risk: it must land last, after the
replacement is verified, or we delete the only working entry point first.

Only the email subcommand is in scope — the rest of the legacy Python CLI is
retired separately.
The user-journey design challenged ten points in the port plan; seven are
accepted here. The biggest: preflight was scoped as late polish, but without
it every transport failure reaches the user as a raw HTTP status — so it
becomes Phase 1's exit test instead.

Also drops 'always allow' on irreversible actions, replaces the three-level
autonomy enum with fixed approval behaviour plus a background-work checklist,
and moves background scanning from a TUI timer to launch time. Settings
shrink to what actually persists, with the config and jobs APIs filed as
#2470 and #2471.
…rt plan

The plan told the decommission phase to keep src/gaia/daemon/agent_query.py
because it was 'the generic daemon thin-client used by more than email'.
That is false: run_query and ConsoleRenderer have exactly two callers, both
inside the email handler being deleted, so removing the subcommand orphans
all 346 lines. Left uncorrected, that phase would have kept dead code on a
premise nobody would re-check.

Reframed as an explicit choice — keep it as the reference implementation the
Go transport mirrors (and say so in the module), or delete it with the
subcommand — rather than a false statement of fact.

Also ignores .claudia-worktrees/, which held six full checkouts one 'git add
-A' away from being committed, and fixes two drifted line references.
The sidecar's QueryRequest.context is a required List with extras forbidden,
so a null is a 422. A Go nil slice marshals to null, which means the obvious
implementation fails on the very first turn — the one case with no history —
and works on every turn after. A mocked 200 hides it entirely.

Calls for initializing the slice and asserting the serialized body contains
"context":[] rather than asserting the mock was called.
The TUI could only talk to agents it spawned itself as a subprocess, so the
email agent — a long-lived HTTP sidecar the GAIA daemon starts, supervises and
reverse-proxies — was visible in the hub but unreachable. The TUI is now a
second thin client of the same relay `gaia email` uses: it discovers the daemon,
ensures the sidecar, and streams the canonical seven-event `/query` contract.
The subprocess transport is untouched, so the bash agent keeps working.

Daemon discovery mirrors src/gaia/daemon: instance.json is trusted only after
BOTH the recorded pid is alive AND a token-authed /daemon/v1/status probe
answers with our service id and that same pid (a recycled port after a crash is
a real case). Start-or-attach takes the same flock so two callers yield one
daemon. The client token is re-read on any 401 — it rotates on every daemon
restart — and never cached, logged, or printed; the sidecar's own bearer is
discarded with the ensure response and never leaves the daemon.

A stream that ends without a terminal final/error is reported as a failure, not
an empty answer, and a turn is appended to the pushed transcript only when it
terminated in `final` so a failed turn cannot poison the next one. Unknown event
types and unparseable frames are surfaced instead of dropped.

Also fixes three latent bugs found while in here:
- an agent path containing a space was re-split on whitespace and never found;
- cancelling a turn abandoned the read without stopping the child, so the tail
  of that turn's output surfaced as the next turn's events;
- ChatModel held its streaming buffer in a strings.Builder, which panics the
  moment a copied non-zero Builder is written again — that would have crashed
  the TUI on the second streamed token of every answer.
Found by pointing the new client at a real running GAIA daemon rather than the
test fake. Three fixes, none of which the fake server could surface:

`Client.Do` defaulted to the status-probe HTTP client, whose 1.5s timeout is
deliberately tiny because a live daemon answers loopback in milliseconds. Any
relay call taking longer than that timed out: `GET /v1/email/init` does real
work (probing Lemonade, the model and connectors) and failed with a misleading
"context deadline exceeded" instead of returning its readiness report. Nothing
shipped today relied on the default — every current caller passes its own
client — but the Phase 2 install/catalog calls and the Phase 5 preflight screen
would each have walked straight into it. Do() now defaults to a general 60s
client and the probe timeout is confined to the probe.

A cancel POST for a run that is no longer in flight answers 404 by design, which
is exactly the case when we abandon a stream that already ended. That was being
logged as a failed cancel; it is now reported as "already finished".

Also: a `data` line with no colon carries an empty value per the SSE spec, which
the reference implementation's str.partition yields but strings.Cut discarded;
and Close() landing while a query request is in flight no longer registers an
un-cancellable run.
…try point

Two independent reviews of the Phase 1 transport, plus a run against a real
daemon. Everything below was found after the first commit was already green on
106 tests, which is the argument for the review pass rather than against it.

Cancelling a subprocess turn emitted a spurious "agent process exited with code
-1" bubble under the "cancelled" line about half the time: killing the child made
the reader see a non-zero exit and a closed pipe, and it reported both as agent
failures. A deliberate kill is not an error. The `emit` helper also selected over
a ready channel send and a ready ctx.Done() simultaneously, so Go picked at
random — it is now deterministic. Reproduced at 5/12 runs before the fix; a
regression test now runs the cancel path eight times.

The same cancel path could panic the TUI. `Send` read the stdin pipe outside the
mutex while the cancel goroutine nil'd it, so a turn started right after a cancel
could write to a nil pipe or scan a nil scanner. Turn state is now captured under
one lock acquisition. Relatedly, killing also reaped the child while the reader
was still reading its stdout pipe, which os/exec explicitly forbids — reaping is
now the reader's job alone. A second test drives ten cancel-then-send cycles.

The turn after a cancel could also silently produce nothing: the early-return
paths skipped the reset, so the next turn reused the child that had just been
killed. Found by the new test, not by review.

A late-arriving event from a cancelled turn could tear down whichever turn was
running by then — Bubble Tea cannot cancel a dispatched Cmd, so the old
waitForEvent goroutine delivers whenever its channel finally closes. Events now
carry the channel they came from and a superseded turn is ignored. The SSE client
no longer holds that channel open behind a 10s cancel POST either.

Nothing bounded the wait for response headers, so a daemon that accepted the
connection and never answered hung the caller forever with a spinning cursor —
the Python reference gets this for free from its read timeout. A recycled pid
whose port was answered by an unrelated process permanently blocked daemon start,
even though the probe had already proved the record was garbage; stale records are
now classified so only our own wedged daemon is left alone. A 401 from a relayed
call now blames the sidecar instead of sending the user to restart the daemon.

Finally, the transport had no user-reachable entry point at all — roughly 1,700
lines that a reviewer could not exercise, and that Phase 2 would have been the
first thing to drive. `gaia tui chat --agent <id>` now runs any catalog agent over
whatever transport it declares, and with `--query` it is a genuine one-shot:
answer on stdout, progress on stderr, exit 0/1, no alt screen. Driving it against
the live daemon showed a bare "HTTP 404", so that case now explains that the
installed sidecar predates the canonical /query contract.

Transport selection moved off the Bubble Tea model into client.ForAgent so the
headless paths do not need a UI, and the cancel path moved out of the daemon
control-plane client into the SSE transport that owns the agent wire contract.
The legacy event vocabulary is now marked frozen so new UI features are not
built twice.

Correcting the first commit's message: it said the daemon token is "never
cached", which is stronger than the code. The token is re-read on every 401,
never logged and never printed, and the sidecar bearer is discarded — but the
last verified instance is held in memory so a run can be cancelled.
Teaches the TUI to reach agents through the daemon relay instead of only
spawning a local binary over a pipe — the prerequisite for the email agent,
which has been a daemon-managed sidecar since #2191 and so could never work
over the subprocess path.
There was no way to exercise the TUI without a human at the keyboard, and no
way for a user to watch an assistant use it. `gaia tui --control` now exposes a
loopback HTTP API that injects keys into the *running* Bubble Tea program and
serves back the frame it just rendered, and an MCP server wraps that as tools —
so Claude Code can navigate the hub, filter, type, and launch agents while the
user watches the same terminal update in real time.

Go side (tui/internal/control/): a Recorder wraps the root model so every
View() is cached, and named keys map to real tea.KeyMsg values. The existing
smoke tests send tea.KeyMsg{Type: KeyRunes, Runes: []rune("tab")} — three
letters, not the Tab key — so the mapping is contract-tested by asserting
KeyMsgFor(name).String() round-trips to the name the handlers switch on.

POST /wait is what makes automation reliable: it blocks on a broadcast channel
until the screen or the reported model state matches, and a timeout reports
what the screen actually contained. Callers no longer busy-poll.

Injection is synchronous end-to-end: tea.Program.Send only queues, so a
trailing sentinel message is used to answer /keys only once every key in the
batch has been handled and drawn. Without it a four-key batch returned with one
key applied.

Python side (gaia.mcp.servers.tui_mcp, `gaia mcp tui`): discovery reads
~/.gaia/tui/control.json (0600) and trusts it only when the recorded pid is
alive and a token-authed probe answers with a matching pid — a recycled port
after a crash is a real case. Loopback-only hosts are enforced client-side too,
since the bearer token rides every request.

Test plan:
- cd tui && make lint && go test ./... -race
- pytest tests/unit/test_tui_mcp.py
- pytest tests/integration/test_tui_control_e2e.py  (boots the real Go server
  and drives it with the real Python client; skips without a Go toolchain)
Rebasing onto the transport work collided two same-named helpers in package
ui — the one-shot test's local run() and the control server's run(). Renamed
the test helper to captureOneShot; the production name stays.

Also corrects which server owns port 8766 (the MCP bridge, not agent_ui_mcp).
Lets an assistant drive the live TUI the user is watching — read the rendered
screen, send keys and text, wait on conditions — so the terminal UI can finally
be exercised and regression-tested without a human at the keyboard.

Its own review pass caught six real bugs, including a key batch that was
acknowledged before it was applied and stdio logging that corrupted the
JSON-RPC stream (the latter also affects the shipped Agent UI MCP — #2472).
Before: an agent driven from a CLI or a subprocess executed every
confirmation-gated tool with no prompt at all. `OutputHandler.confirm_tool_execution`
returned True unconditionally and no CLI console overrode it, so the entire
mechanism was inert outside the Agent UI. In practice that meant `gaia email -i`
could send, forward, RSVP to, and permanently delete mail on the model's say-so,
and any agent could run shell commands and overwrite files, with no prompt and no
event the user could see.

After: gated tools prompt on the terminal — the tool name, its literal arguments,
and a yes/no answer that defaults to no (Ctrl-C and EOF also mean no). "Always
allow" is per tool and per console, and is not offered for run_shell_command /
run_cli_command, where the name says nothing about the next call. With no terminal
to ask on — piped stdin, redirected stdout, CI, a subprocess host — the tool is
denied with an actionable error naming both ways forward, instead of running
silently. The agent loop still returns {"status": "denied"}, so the model can
explain itself rather than the run crashing.

Details worth knowing:

- Silence covers narration, not consent. `gaia chat` builds a SilentConsole even
  for a user sitting at a terminal, so the prompt lives in a mixin shared by both
  CLI consoles; otherwise the flagship path would have gone from "runs gated tools
  unasked" to "refuses them unasked".
- The gate itself never raises. A malformed tool_args from the model, a detached
  tty that errors on read, or a closed stdout all resolve to a logged denial —
  because the tool used to just run, an exception escaping here would be a new way
  to kill a working session, and `Agent._execute_tool`'s callers do not catch.
- The unattended opt-in (GAIA_AUTO_APPROVE_TOOLS=1, or auto_approve_gated_tools on
  the console) is read from the environment as it was at startup, so a
  project-local .env cannot switch off a user's prompts. Every approval taken that
  way is logged with the tool name.
- The Agent UI path is untouched: it still emits permission_request, blocks on the
  modal, and denies on timeout; a new test pins that end to end through the gate.
  Background/autonomous ticks keep their existing auto-deny.
- The OpenAI-compatible API server and scheduled UI runs have no channel to ask a
  human, so they now deny rather than approve. Documented in the CLI reference,
  troubleshooting, the console spec, and the API-server and output-handler pages.

Denial reasons are bound to the tool they belong to, so a handler that denies
without recording one can never report another tool's explanation. Argument
shortening is display-only — an approved write receives the full content.
Confirmation-gated tools — send, forward, permanent delete, RSVP, shell,
file write — executed with no prompt and no record whenever an agent was
driven from a CLI or subprocess, because the base handler answered yes on
the user's behalf. It now denies by default and the terminal console
genuinely asks.

Unattended hosts opt in with GAIA_AUTO_APPROVE_TOOLS=1, which deliberately
cannot be granted by a .env file — a project file travelling with a
directory is not an operator's decision. The SSE approval path is
unchanged.
`gaia_agent_email/cli.py` was an in-process argparse entry point that
nothing imported and no console script exposed. Its docstring still claimed
`gaia.cli.handle_email_command` invoked it, which stopped being true at
#2191 when that handler became a thin daemon relay — so the file was both
dead and actively misleading about how a query reaches the agent.

The sidecar (`gaia-agent-email serve` -> POST /query) is the only supported
entry point; an in-process CLI would bypass its caller auth, trust gate, and
SSE translation. Adds a guard test so the module can't creep back silently.
…orecard

The npm package shipped two different scores for the same version: README and
EVALUATION advertised 83.4/100 while the co-located SCORECARD.md — machine-
generated from a real 3-run eval for v0.5.0 — reported 84.53. 83.4 is the
0.3.0-era number; the prose was never refreshed when the scorecard was
regenerated, so an integrator comparing the two pages saw the package
contradict itself about its own benchmark.

SCORECARD.md's aggregate.value is the source of truth, so the prose moves to
it. The CHANGELOG's 83.4 under 0.3.0 stays as-is: per-version entries are a
historical record, and rewriting one would falsify the release history.

Adds a guard that fails whenever a prose score claim drifts from the generated
aggregate again, since prose does not regenerate with the eval.
…f hardcoding it

The generated capability matrix contradicted itself inside one file: the
Definitions section said the REST API has "16 functional verbs" while the
matrix header five lines below computed 21 from the live OpenAPI spec. Anyone
reading the doc to size the REST surface got the wrong number from the more
prominent of the two.

The 16 was a literal inside TOOLS_COUNT_DEFINITION, so the existing
byte-identical drift guard could never catch it — regeneration reproduced the
same stale literal. The blurb is now a template fed by the derived counts, and
the two stale literals that had spread to a module comment and the
gaia-agent.yaml comment are gone with it. Regenerated: 16 -> 21.
…nswer

Two swallowed failures on the same SSE path made an internal crash look like
the agent simply had nothing to say. The queue drain caught bare `Exception`
where it meant `queue.Empty`, so any non-Empty error read as "queue drained";
the stream then synthesized `{"type": "run_complete", "answer": ""}` — a
well-formed *successful* completion — whenever the worker thread had died
without emitting a terminal event. A client could not tell the two apart.

The drain now catches `queue.Empty` only, matching the sibling query route,
and a dead worker emits an `error` event naming the failure and the sidecar log
to check before the stream closes.
…profile

Two degradations that left no trace at all.

A malformed GAIA_EMAIL_TRIAGE_MAX_MESSAGES silently reverted to the
100-message default, and a negative or zero value was clamped to 1. The eval
harness sets that variable to cover the whole labelled corpus, so a typo
produced a quietly smaller scan and therefore a quietly different score with
nothing to notice — exactly the regression-hiding the rule exists to stop. It
now raises ConfigurationError naming the bad value and the way out, matching
config._undo_window_seconds, which already handled the identical shape this way.

An unreadable sender-profile row was reset to an empty record with no log,
throwing away the reply-latency and interaction history that drives
priority-sender promotion, while the sibling read paths log the same
corruption class. The reset stays fail-soft — one bad row must not kill
behavioral learning — but now says which sender lost what.
…CLI claim

CONTRACT.md — the doc that calls itself the contract reference — declared
schema 2.3 while contract.py has been on 2.5 since #2154. Both additive bumps
(2.4's /v1/email/query agent loop, 2.5's /v1/connections OAuth intake) shipped
without a history row, and every copy-pasteable JSON example told integrators
to send the stale version. The same file still explained that the interactive
CLI loads the model at 32K via an `agent_context_sizes` registry in
src/gaia/cli.py; that registry no longer exists and no CLI loads a model at all
since #2191 made every front-door relay to the sidecar.

npm/SPEC.md stated the contract version as 2.4 without saying whose — true of
the client, wrong for the sidecar it documents. Now says both and why 2.4
requests still work.

Adds guards tying CONTRACT.md's headline, examples, and history table to
contract.SCHEMA_VERSION, so the next bump cannot land doc-less.
…tops startup

Follow-up to the fail-loudly pass: raising from _inbox_scan_ceiling() achieved
nothing. Both scanning tools call it inside their own
`except Exception -> _envelope_err`, so the ConfigurationError was caught two
lines later and handed to the LLM as a per-call error string. An eval run with
a typo'd GAIA_EMAIL_TRIAGE_MAX_MESSAGES would have failed every triage call,
apologised, and still written a scorecard — worse than the silent default it
replaced.

The resolver moves to config.py beside default_undo_window_seconds and becomes
an EmailAgentConfig field, so a bad value fails construction, where an operator
sees it. Blank now means "unset" on both, matching that precedent.

Also from review: the profile-reset warnings logged a raw sender address at
WARNING, which gaia diagnostics bundles into user-attached bug reports — they
log the store row id instead. CONTRACT.md's new version-policy sentence
contradicted the 2.3 row it introduced (a breaking change shipped as a MINOR,
which clients gate on MAJOR alone and never saw), and its ctx note overreached:
gaia eval benchmark does still build the agent in-process. The docs site
repeated the stale 2.3 schema claim and is now guarded with CONTRACT.md.
… environment

The config field added in the previous commit was validated at construction and
then never read: both scanning tools still called the env resolver on every
invocation. `EmailAgentConfig(inbox_scan_ceiling=500)` was accepted and
silently ignored, and because the resolution happened per call the ceiling
could move underneath a live agent when the environment changed mid-run.

The registrar now resolves it once, preferring the config and falling back to
the same env resolution for the duck-typed configs some hosts pass (the
existing `debug` flag reads the same way). Tests cover all three: explicit
config wins, a config without the field still works, and the value is stable
across calls.

Also drops the ✅ the debug playground printed on an empty `run_complete` —
a dead worker now emits an error event immediately before it, and a green
check after that read as success.

Reverts drive-by reformatting of 13 untouched files from a whole-tree black run.
Fixes a case where the agent could stream a blank answer as success after
its worker had died, and makes a bad inbox scan ceiling stop startup rather
than degrade quietly.

Also settles two doc contradictions at the source: the package advertised an
eval score its own scorecard disagreed with, and the capability matrix
hardcoded a verb count that its own generated table contradicted. Deletes
the dead in-package CLI module retired by #2191.
The email→TUI port had an engineering scope but no user experience: a list of
capabilities, not a journey. This walks all eleven stages a person actually
passes through — from `gaia tui` on a bare machine to a triaged inbox — with
ASCII mockups for every screen state, a keybinding map checked against what the
hub and chat models already bind, and an explicit build order.

The finding it argues: the port's hard problem is the four-precondition
readiness gate (local LLM, model, daemon, mailbox), not the transport. Every one
of those is already reported by an existing endpoint with an actionable hint, so
seven of the ten highest-value fixes need no backend change at all.

Pushes back on the engineering plan in ten places, notably: preflight is Phase
1's acceptance criterion rather than later polish, "always allow" on irreversible
actions should not ship, the three-level autonomy enum should be two plain
controls, and background timers do not belong inside a foreground TUI.
Review pass against the code found four things the doc asserted that aren't
true as written, each of which would have sent an implementer down a dead end:

- `ctrl+b` and `ctrl+t` were proposed as free chat keybindings. Both are taken
  by bubbles/textarea's default keymap, which receives every key the chat model
  doesn't handle. Moved to `ctrl+g` / `ctrl+r` and documented the full set of
  chords the textarea reserves, since checking only chat/model.go misses them.
- The quit message told users to stop the background service with `gaia kill`,
  which kills a process by port and cannot stop the daemon. It is
  `gaia daemon stop`.
- `GET /daemon/v1/catalog` was referenced as if it exists; it is proposed in the
  engineering plan's Phase 2.
- `gaia tui` itself does not exist — no `tui` subparser in the CLI, and the Go
  binary's cobra root is already named `gaia`, so installing both yields two
  different `gaia` commands.

Adds a "what exists today vs. what this design assumes" table so every proposed
surface is labelled in one place, and tightens the `diagnose()` line range.
Defines the end-to-end experience the port is building toward, using email as
the driving case: what a first-time user sees, where the walls are, and which
fixes are worth the most per hour. Its pushback reshaped the engineering plan
— most importantly, the readiness gate moved from late polish to Phase 1's
exit test, because without it every transport failure surfaces as a raw HTTP
status.
The plan's email paths predated the #2060 restructure, so every reference
pointed at a directory that no longer exists. Also splits the bug list by
status: two are fixed and merged, two remain open, and four are closed as
moot because they are flag behaviour on the subcommand Phase 5b deletes —
reading them as open would send someone to fix a command being removed.

Adds the hub tab-cursor bug found while the control API drove the TUI.
Until now the only way to install a GAIA agent was the web UI's FastAPI
server on port 4200 — no CLI, no daemon API, so the TUI and any scripted
setup were blocked. The daemon now owns install, which means the TUI, the
CLI and the Agent UI share one installer, one SHA-256 check and one
install lock instead of three forks of the logic.

New routes (all behind the existing daemon client token):

  GET    /daemon/v1/catalog                     hub catalog + installed state
  POST   /daemon/v1/agents/{id}/install         202, queue an install
  GET    /daemon/v1/agents/{id}/install-status  progress + terminal error
  DELETE /daemon/v1/agents/{id}                 stop, verify, remove the dir

Safety semantics that are not negotiable and are covered by tests:

- The install dir IS the sidecar's binary cache, so install and uninstall
  stop the sidecar first and hold it stopped for the whole mutation via a
  new SidecarRegistry.hold_for_mutation(): an ensure arriving mid-download
  waits instead of respawning the process from the directory being
  rewritten. A pid that survives the tree-kill aborts the operation.
- Install and uninstall of one id share a slot, so a DELETE can never
  report success while a download is still writing into that directory.
- Integrity is the hub manifest's server-computed SHA-256, verified before
  anything is written; a mismatch leaves nothing installed and there is no
  "use it anyway" path.
- Reserved built-ins are refused, and ids are validated before they become
  a path segment under ~/.gaia/agents.
- The catalog only offers agents the daemon has a sidecar spec for, and
  reports the ids it hid rather than dropping them silently.

Also drops the daemon's dead dependency on the committed
binaries.lock.json (placeholder SHAs, and not shipped in the wheel): a
missing lock now means "not installed yet" and names `gaia hub install`
as the remedy instead of blaming a broken install.
There was no way to install an agent from a terminal at all — setup meant
opening the Agent UI. `gaia hub` drives the daemon's install routes, so a
scripted or headless machine can now provision agents, and it shares the
UI's installer rather than forking it.

`list` shows the catalog with installed versions and an update marker;
`--installed` answers from the local .installed sentinels and needs no
network; `--refresh` bypasses the 5-minute catalog cache. `install` polls
and prints each phase, exiting 1 with the reason on failure. `uninstall`
stops the agent's sidecar and verifies its pid is gone before removing
anything. None of these renderers can print the sidecar bearer token.
The registry only verifies the pid it still tracks, so a sidecar the
daemon lost track of would have its binary replaced underneath it. That
is not hypothetical: on this machine a daemon-spawned email sidecar
(pid 31647, port 57920) has been serving /health for an hour while
`GET /daemon/v1/agents` reports the agent as `stopped` — the daemon
spawned a second process 12 seconds after the first without killing it
and dropped the reference.

Install and uninstall now also ask the OS what is actually running out of
the agent's directory and abort with the surviving pids and a remedy if
anything is. exe/argv[0]/argv[1] only, so a log path passed to another
tool cannot block an install.
kovtcharov and others added 18 commits July 24, 2026 20:23
`ensure(mode=...)` replaces a stopped agent's manager object, so
hold_for_mutation could stop a stale manager — is_running already False —
while the manager that replaced it was live. The install/uninstall then
proceeded against a running sidecar, which is exactly what the hold
exists to prevent. Re-read the holder under the per-agent lock (the lock
object is stable across a manager swap, which is what makes that safe).

The directory scan added in aabd1c69 masked this for the case that
matters most (a user-mode sidecar runs from the install dir), but the
primary guarantee has to hold on its own.
Upstream's installer gained a trust gate: any agent outside the `verified`
security tier now needs `trusted=True`, because installing it runs
third-party code on the user's machine. The daemon install path did not
pass it, so `POST /daemon/v1/agents/email/install` and `gaia hub install
email` failed for every user — email is `experimental`.

The opt-in is threaded end to end: a `trusted` field on the install body,
`--trust` on `gaia hub install` (matching `gaia agent install`), and
`trusted=` into `installer.install`. It defaults to FALSE everywhere and
is never inferred — an absent body, an empty body and an explicit false
are all refusals.

A missing opt-in is refused synchronously with 403 (not a generic 500, and
not an opaque background failure), naming the exact remedy, so a TUI or UI
can render "Trust & Install" and retry. The id checks run first, so an
unknown or reserved id still answers 404/400 rather than prompting for
trust on an agent that cannot exist.
Installing an agent previously required the web UI — there was no CLI path and
no daemon API, so a headless machine had no way to provision a sidecar. Adds
catalog, install, install-status and uninstall to the daemon, with `gaia hub
list|install|uninstall` on top, so the TUI, the CLI and the web UI share one
implementation and one integrity check.

Installing a non-verified agent runs third-party code, so it requires an
explicit trust opt-in: an omitted, empty, false or loosely-truthy body is
refused with a 403 naming `--trust`, before anything is downloaded.

Also refuses to mutate an install directory a live process is using, and stops
the manager that is actually registered rather than the first one read.
The guide still said send confirmation happens 'in the UI', which stopped
being true when the CLI gained a real terminal prompt and non-interactive
hosts started being refused outright. Names all three outcomes.
…-scan

"Triage my inbox" produced one vague sentence. That was never a prompt
problem: the email agent already emits `render: "email_pre_scan"` on
`tool_result` with the full structured payload, and the tool's docstring
deliberately tells the model NOT to describe the results in prose because
it expects the client to draw a card. The TUI ignored `render`, so the
data arrived and nobody drew it.

Adds `internal/ui/cards`, which turns a `tool_result`'s declared card key
into terminal text, and wires it into the chat transcript as a new
RoleCard message drawn inline where the tool returned.

Three of the contract's five generic primitives are built — table,
key_value, list. `image` is base64 raster and degrades to a caption line;
`diff` has no producer and rides the unsupported-card fallback. Per
contract §7 an unknown `render` becomes a visible generic card with a
bounded raw dump, and a schema-invalid payload names the decode failure.
Never blank, never dropped.

Honesty properties the card is built around:
- `totals` is pre-cap, the lists are not, so headers read "3 of 7" and a
  trailing "+N more" accounts for every hidden row — whether the agent
  capped it or the card's own row budget did.
- Every urgent/actionable row carries its rationale (`reason ?? why`).
- `mailbox_errors` becomes a per-account warning banner instead of
  surfacing nowhere; results from the healthy accounts still render.
- Cards are height-bounded so a 500-row payload cannot bury the
  transcript, and the budget costs wrapped lines, not strings.

Also grows the chat live region from two collapsing lines into a bounded
work log (5 lines, consecutive repeats folded to "name xN", elapsed
clock, and a "still working" note after 20s). A 60-90s local-model triage
touching dozens of messages was indistinguishable from a hang, and the
discarded steps are the evidence the card is read against.

Status markers are ASCII and section headers are words, so nothing
depends on colour or an emoji font.

Removes `/init`, which printed "Initializing X..." and did nothing. No
init call is wired into the TUI client, and a slash command that lies is
worse than a missing one.
…render

Review of the render-card work turned up a reachable freeze and several
ways a payload could produce a confidently wrong card.

wrap() never terminated on a word carrying an ANSI reset: ansi.Truncate
re-emits the terminating sequence, so the truncated head was not a literal
prefix, TrimPrefix made no progress and the loop spun. A JSON string can
carry a real ESC via the � escape, so any agent string could reach
it, and the loop runs on the Bubble Tea update goroutine — the symptom is
a frozen terminal, which is worse than the blank card the contract forbids.

The fix is one choke point rather than a patch at the loop: card values
are plain text per §4.3, never a styling channel, so ANSI escapes and C0
controls are stripped before anything measures or prints them. That also
closes the newline and tab shears — a subject line is a MIME header value
and could carry either, splitting a border in two — and stops control
sequences reaching the terminal at all. The loop keeps a no-progress
guard regardless.

Also fixed, each of which rendered something plainly untrue:
- null and {} decoded into the zero pre-scan envelope and drew "Nothing
  needs you" — a malformed payload telling the user their inbox is clear.
  The envelope now has to actually be one.
- Numbers round-tripped through float64, so 1234567890123456789 rendered
  as …768, MinInt64 as "-", and 1e-7 as 0. The literal token is kept;
  §4.3 says the value renders as text, so the token is the text.
- key_value / list treated an absent `items` as an empty one, drawing an
  empty card where the schema requires the field.
- Narrow widths clamped the frame up to 24 columns instead of degrading,
  overflowing any viewport narrower than that. Below the minimum the card
  now drops its border, which is what the comment already claimed.
- A table with more columns than fit rendered every cell as a bare "…".
- A footer line dropped for space left no marker, unlike every other
  truncation on the card.

Cards are memoized per width: updateViewport re-renders every message on
each streamed token, so a card was re-parsing its JSON per token.

Adds an adversarial suite over every card type — newlines, tabs, ANSI,
OSC, NUL, CJK, ZWJ emoji, 400-char words at several widths — asserting
the render terminates, every line is exactly the requested width, and no
control character survives. It reproduces all of the above.
"Triage my inbox" produced one vague sentence. The agent already emits a
structured pre-scan payload and is deliberately prompt-engineered NOT to
describe the results in prose, because it expects the client to draw a card —
so a client that ignores the render hint gets the terse fallback and nothing
else. The card is now drawn, alongside three generic primitives so future
agent cards render without TUI changes.

Also fixes a reachable freeze: text wrapping never terminated on a word
carrying an ANSI escape, spinning on the update goroutine. Any agent-supplied
string could reach it — JSON carries an escape as \u001b — so model output
could hang the user's terminal. Card values are plain text per the contract,
so escapes are now stripped at the boundary.
The daemon's Agent Hub routes landed with no way to reach them: the hub
footer had no install key, `gaia tui` had only chat/hub/version, and the
email agent sat in Available where it could be looked at and nothing else.
Now `i` installs, `d` uninstalls, and `gaia tui list|install|uninstall|run|
status` do the same from a script.

Installing an agent GAIA has not verified runs third-party code, so the
daemon answers 403 until it gets an explicit opt-in. That refusal opens a
confirmation naming the agent, version, publisher, security tier, download
size, and requested access — and only an explicit yes re-sends with the
opt-in. Nothing retries on the user's behalf, in the UI or the CLI.

Also fixes, all on the first-run path:

- The hub rendered 34 lines into an 80x24 terminal with the footer wrapping
  mid-line. Chrome is now measured rather than assumed, the ASCII logo
  collapses to a wordmark below 32 rows, and every row is clipped to the
  terminal width — one over-long row used to widen the whole frame.
- `tab, down, down, shift+tab` left nothing selected and enter silently did
  nothing (#2481). The cursor resets on a tab switch and is clamped when the
  `/` filter narrows the visible set.
- `backspace` no longer triggers uninstall. Every user presses it meaning
  "go back".
- The hub opens on a tab that has content, and an empty tab renders a real
  empty state instead of bubbles' "No items."
- `ctrl+c` quits from inside every modal.
- Agents the daemon cannot fetch or start are labelled "not out" instead of
  sitting in Available promising an install that would fail.
- `findBinaryInRepo` only ever looked for `cpp/build/*/<name>.exe`, so it
  could not find a Python or frozen agent on macOS or Linux. It now searches
  the hub install root and honours platform executable names.
- `TestHubTabSwitching` / `TestHubSearch` sent the three runes t-a-b instead
  of the Tab key and asserted only "didn't panic".

`run --query` is a genuine one-shot: no alt screen, answer on stdout,
progress on stderr, exit 0/1. Verified end to end against the mock agent.
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.
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 now reports all of it as
checkable rows with a remedy per failure.

Its own review caught remedies that damaged what they claimed to fix: the
mailbox fixes named commands that OVERWRITE existing scopes, turning
'can read, cannot send' into 'can send, cannot read' — and the row then went
green over a mailbox that was worse off. A relay 503 also decoded as
'Lemonade unreachable', sending users to the wrong component entirely.
The preflight gate was built, tested and merged, but nothing imported it, so
no user could reach it: pressing enter on an installed agent 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 — the four
generic checks plus the agent's extras run, an all-green screen holds ~800ms
and hands off to the same launch path the hub used to call directly, and a
proved-broken row keeps the user on a screen with a command they can run.

Two decisions worth naming:

The gate runs on EVERY launch and nothing is cached. Every row is a fact with
no expiry notice — the daemon can be killed, its token rotates on restart,
Lemonade can unload the model, 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. A pass costs one attach plus two relayed GETs.

ConnectMailboxMsg becomes an instruction screen, not a connector flow. The TUI
has no OAuth screen and half of one would fork the flow that owns tokens,
scopes and grants (`gaia connectors`), so the host shows the exact command the
mailbox row already computed — scope union and agent grant included — and
re-checks on `r`. With no provider connected the choice stays the user's: the
Gmail command is copy-pasteable and Outlook points at its one-time Microsoft
setup, because that provider needs an app registration first and the Gmail
scopes are wrong for it.

Subprocess-transport agents are not gated: every precondition is probed through
the daemon relay, so the gate could only answer "not installed" — four wrong
rows with four wrong remedies over a launch that works.

The control snapshot reports the new view so automation can wait on it instead
of racing the render.
… agent

Review found the launch this seam was supposed to make impossible. The gate's
async results are unexported types, so root forwards them blind to whichever
gate is mounted: back out of a slow check on Email, launch a second hub agent,
and Email's report lands on that gate — five rows for the wrong agent, and if
that report is all-green the gate hands off and opens a chat for an agent
nothing ever probed. The report is exported and names its agent, so root now
drops any result that belongs to a gate the user already left.

The regression test reproduces it end to end (it fails with "a stale report
launched chat" without the guard), and replaces a test that could not see the
bug: after esc the view is already the hub, so its guard short-circuited before
the agent id was ever compared.

Also from the review:

The mailbox hand-off gave up the wrong lines when the terminal was too short.
The command sits in the middle of the screen, so trimming by position — from
either end — could keep the paragraph explaining the problem and drop the one
command that fixes it. Lines are now dropped by what they are: explanation
first, then the alternative path, never the command or the way out. Verified at
24, 16, 12 and 10 rows.

`closeGate`'s comment claimed it cancelled everything the screen started. It
does not: preflight.Model.Init has a value receiver, so the first probe's cancel
func dies with the call and only a pointer-receiver initialiser in that package
can fix it. The comment now says so instead of vouching for a guarantee that
isn't there.

Smaller: the fits test measured the chat view for its own "all ready" case and
asserted only a row count both views satisfy by self-truncating, so it could
pass while dropping the content it existed to protect — every case now names
what must survive at 80x24. A reconnect command that names a different provider
than the mailbox it is for is flagged rather than presented under a title that
vouches for it. ctrl+c out of the hand-off no longer leaves the view pointing at
a torn-down model. And the fake transport's start/ensure counters are asserted:
a blocked gate must start nothing, and `f` on a stopped sidecar must start it
exactly once.
The gate was built and merged but nothing imported it, so 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. It now sits
on the launch path.

It runs every launch and caches nothing: the daemon can be killed, its token
rotates on restart, Lemonade can unload the model and a 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.
`gaia tui run <id> --query "…"` is the path that exists for scripts and CI,
and with the local model server down it hung indefinitely printing nothing at
all — no stdout, no stderr, no exit. A CI job wedged until its own timeout with
nothing in the log to say why. It now refuses in about a second, naming the
unmet precondition and the command that fixes it.

Two changes, and the second matters even with the first:

- The one-shot runs the existing headless readiness check before sending
  anything. The interactive gate is deliberately not rendered — a script has
  nobody to press a key — but the blocked report is rendered from the same
  preflight.Report the gate draws, so the two paths cannot drift. It refuses
  only on a proved failure; an indeterminate row is named and the run
  continues, matching the gate. The daemon and sidecar are still started first,
  so a cold machine keeps working the way it did.
- The turn is bounded (15m default, `--timeout`), and RunOneShot honours the
  deadline. A readiness check cannot catch a dependency that accepts the query
  and then goes quiet: the relay's read watchdog is reset by every heartbeat,
  so a wedged sidecar can hold the stream open forever. Events already buffered
  when the deadline fires are still taken, so an answer that lands in the same
  instant is not thrown away.

Only daemon-transport agents are checked — a subprocess agent has no
/v1/<agent>/init route, so the rows could only say "not installed" over a
launch that works. `gaia tui chat --agent <id> --query` gets both changes; it
runs through the same entry point.
…cancel

The one-shot prints the readiness report on failure, but the shared remedy
strings told the reader to "press r"/"press f" — keys that do not exist in a
process that has already exited. Strip the keystroke wording from the shared
Diagnosis/Remedy text; the interactive gate already re-adds each affordance in
its footer, so nothing is lost on screen.

When a one-shot gives up at its deadline, SSEClient fired the relay cancel POST
in a goroutine while the CLI was exiting, so it usually never landed and the
sidecar kept working for a client that was gone. Make the cancel idempotent
(sync.Once) and deliver it synchronously from Close(), bounded by cancelTimeout,
so the deferred Close in the one-shot path lands the cancel before os.Exit.

Closes #2489
Base automatically changed from claudia/task-5fcce79e to claudia/task-a140d608 July 27, 2026 09:03
Base automatically changed from claudia/task-a140d608 to claudia/task-fd276692 July 27, 2026 09:08
Base automatically changed from claudia/task-fd276692 to main July 27, 2026 09:18
@kovtcharov

Copy link
Copy Markdown
Contributor

Closing rather than merging: this is superseded and would regress work already on main.

The remedy text here reinstates lemonade-server serve, which does not exist on a modern Lemonade install — the daemon is lemond. main already replaced that with lemonadeRestartRemedy(), which resolves the real launcher per platform and tells the user to stop the running server first when one holds the port. Merging this would put the dead command back in front of users.

The branch also predates the mailbox-usability probe and the readiness-gate work that has since landed, so its one-shot remedy path no longer matches the gate it is written against — 52 files conflict with main.

The underlying issue (#2489) is addressed: one-shot remedies are keystroke-free and the gate hands off synchronously. If anything specific here was missed, it is easier to raise it fresh against current main than to rebase this.

@kovtcharov kovtcharov closed this Jul 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(tui): one-shot remedy text says "press r", and an abandoned turn is never cancelled

1 participant