Skip to content

feat(daemon): start GAIA's Lemonade Server on demand - #4193

Merged
kovtcharov-amd merged 49 commits into
amd:mainfrom
kovtcharov:claude/daemon-owns-embedded-lemonade
Sep 26, 2026
Merged

kovtcharov-amd merged 49 commits into
amd:mainfrom
kovtcharov:claude/daemon-owns-embedded-lemonade

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #4192. Land after #4301, which stops unit tests from spawning real daemons. With this PR a daemon starts GAIA's Lemonade Server in the real ~/.gaia, so a test-spawned one would start and stop the developer's server. Until that merges, this diff includes its commit; review only the last commit here.

After a reboot, GAIA's own Lemonade Server is stopped, and every entry point said "Lemonade not running" until you re-ran gaia init. Now the daemon starts it when the daemon comes up, and again whenever a GAIA command finds it stopped. Agents, the TUI's first-launch check (gaia init --check) and the Agent UI just work after a restart.

The daemon is careful about what it stops. gaia daemon stop stops the server only if that daemon started it, so one started by gaia init, by hand, or by another daemon (a second one used for testing, say) keeps running. It never kills a server that is slow to answer (it may be loading a large model) and never replaces one running a different version: it reports both and points at gaia init. With LEMONADE_BASE_URL set it leaves Lemonade alone, and it never installs anything.

A daemon from before this change doesn't have the new endpoint. Instead of a bare 404, clients get "restart it with gaia daemon restart" (host API bumped to 1.2).

Test plan

  • pytest tests/unit/test_daemon_lemonade.py tests/unit/test_daemon_clock_wiring.py tests/unit/test_init_command.py tests/unit/test_daemon_agents_routes.py; go test ./internal/gaiainit/ ./internal/daemon/
  • With GAIA_HOME, GAIA_DAEMON_HOME and GAIA_CONFIG_DIR in a scratch dir and the server stopped: gaia init --check has a new daemon start it and prints READY (1.4 s); gaia daemon stop then stops it
  • Server started with gaia lemonade embedded start, then gaia daemon start / gaia daemon stop: the server keeps running
  • Server stopped: LemonadeManager.ensure_ready() gets it started through the daemon, loads Gemma and returns True
  • Windows and Linux: reboot, then launch gaia-tui without running gaia init; it should go straight to chat
Terminal output: the reboot case on Apple Silicon (GAIA set up, no daemon or server running)
$ gaia daemon status
GAIA daemon: not running
$ gaia lemonade embedded status
Running:   no

$ time gaia init --check --profile minimal
READY: profile 'minimal' is already set up
(exit 0, 1 s)
$ gaia lemonade embedded status
Running:   yes on http://localhost:59768/api/v1 (pid 88967)

$ time gaia daemon stop
✅ GAIA daemon stopped (pid 88966)
(5 s)
$ gaia lemonade embedded status
Running:   no

Kalin Ovtcharov added 6 commits September 24, 2026 16:51
A new user should install with npx, optionally run gaia init, and start
GAIA from the TUI, web UI, desktop app or Claude Code. Scopes GAIA's
embedded Lemonade replacing a system-wide install, start on demand from
every entry point, the removal of the system-Lemonade code, and the
follow-on PRs for npx install, TUI /init and the Claude Code plugin.
gaia opens the terminal UI, gaia web the web app and gaia app the desktop
app; gaia chat --ui and the top-level --ui/--cli flags are removed as
legacy. Adds this as its own PR in the sequence.
Records the decisions: the GAIA daemon starts and stops embedded Lemonade,
GAIA never falls back to another Lemonade on the default port and reports
the Lemonade app when it holds memory or the NPU, and a second PR removes
gaia chat and every command that is neither useful nor exercised by CI,
collapsing init profiles to gaia, npu and sd.
gaia init used to install Lemonade system-wide (MSI, PPA or .pkg, with an
admin prompt on macOS), upgrade or uninstall existing installs, and try to
start whatever it found. It now downloads GAIA's own Lemonade Server into
~/.gaia/lemonade (checksum-verified, no admin rights) and starts it on a
private port. Re-running init restarts a stopped server, replaces an older
one, and recovers one that stopped answering.

LEMONADE_BASE_URL still names another server; init then only checks that
it answers and meets the profile's minimum version. --remote now requires
it. gaia init --check reports the embedded server's real state and targets
it explicitly, so it can no longer call a profile ready because some other
Lemonade answered on the default port.

Removes --skip-lemonade (nothing used it), init's system install, upgrade
and auto-start paths, and catch-all handlers in the steps touched.
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes cli CLI changes tests Test changes performance Performance-critical changes tui Go terminal UI (gaia-tui) daemon Daemon supervisor / sidecar control plane labels Sep 25, 2026
@kovtcharov
kovtcharov force-pushed the claude/daemon-owns-embedded-lemonade branch from 5b9a02c to 9d9e245 Compare September 25, 2026 00:12
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

The daemon now owns GAIA's Lemonade Server — starting it at daemon startup and on demand, and stopping only a server it started itself. The ownership rules are careful and well tested; what needs another pass is the timeouts, which don't line up with the new, slower work.

Two things to fix:

  1. gaia daemon stop can hard-kill the daemon part-way through shutting down. Stopping Lemonade is now part of the daemon's shutdown, and that can take longer than the stop command is willing to wait — so the command gives up, prints "did not exit; terminating" and kills the daemon mid-teardown. It's most likely right after a start, when the server is still coming up, or when a large model takes a while to unload. Either give shutdown more room, or bound the Lemonade stop so it always fits in the existing window.

  2. The TUI's readiness check gives up before the server can finish starting. The Go side allows 90 seconds; the Python side it calls is allowed to spend well over two minutes on a cold start after a reboot. The user then sees "could not be checked" even though the start actually succeeded — which is exactly the reboot case this PR is meant to fix, and also the one test-plan item still unchecked. Raise the Go budget above the Python one, or lower the Python one to fit.

Neither is hard to fix, and the rest of the design is solid.

Real-world evidence

No evidence-bundle.md was produced for this PR, so the verdict rests on static review plus the manual results described in the PR description (a daemon start/stop cycle against a scratch GAIA_HOME, an init --check that reported READY in 1.4 s, and ensure_ready() starting the server). Those are described rather than pasted, and the reboot scenario the PR leads with — launch the TUI after a restart and land in chat — is the one unchecked box. Given finding #2 is specifically about that cold path, it's worth running before merge and pasting the result. I could not run the unit suite here (no pytest in the review environment), so the test-plan's green runs are taken as reported.

🔍 Technical details

🟡 Important

1. Daemon shutdown can now outrun the stop command's grace window (src/gaia/cli.py:7136)

_handle_daemon_stop waits wait_until_gone(inst, timeout=10.0) and then escalates to terminate_instance (psutil tree-kill). _build_deregister now calls lemonade_owner.stop() before custody_store.close(), and that call can exceed 10 s in two normal situations:

  • EmbeddedLemonade.stop() polls for up to _STOP_TIMEOUT = 20.0 s after a POSIX SIGTERM to the process group (lemonade_embedded.py:1019). A lemond with llama-server children unloading a large model is not guaranteed to be gone in 10 s.
  • EmbeddedLemonadeOwner.stop() takes self._lock (daemon/lemonade.py:160), which the startup ensure_in_background() thread holds for the whole of EmbeddedLemonade.start() — up to _START_TIMEOUT = 60.0 s. gaia daemon restart shortly after a start hits this directly.

On escalation the daemon is killed before custody_store.close() runs, so the custody SQLite store never closes cleanly, and the user sees a spurious "⚠️ daemon pid N did not exit; terminating" on a perfectly ordinary stop.

Simplest fix is to give the stop command room for the work the daemon now does:

    if client.wait_until_gone(inst, timeout=45.0):

Alternatively, bound the teardown inside _build_deregister (e.g. lemonade_owner.stop() with a non-blocking lock acquire, logging and skipping when a start is in flight) so shutdown stays inside the existing 10 s.

2. CheckTimeout is below the budget the Python side is allowed to spend (tui/internal/gaiainit/gaiainit.go:46)

Check bounds the whole gaia init --check subprocess at 90 s. That call can now reach client.ensure_lemonade(), whose own budget is start_or_attach() (_START_TIMEOUT = 30.0) plus a 120 s read timeout (daemon/client.py:53) — and a genuine cold start burns up to 60 s inside EmbeddedLemonade.start() alone, on top of interpreter startup. The Go side kills first, Check wraps ErrUnanswered, and checkModels renders StateUnknown / "could not be checked" (tui/internal/ui/preflight/local.go:468) even though the daemon went on to start the server successfully.

const CheckTimeout = 150 * time.Second

Whatever number you pick, it should be derived from — and stay above — the Python-side ceiling; a comment naming that relationship would keep the two from drifting apart again.

🟢 Minor

3. Stale comment on the ensure timeout (src/gaia/daemon/client.py:52) — it says the budget covers "stopping a stalled server (20s)", but EmbeddedLemonadeOwner.ensure() never stops a stalled server; it raises on unresponsive_pid and points at gaia init.

# Covers spawning the daemon plus a cold start's health wait (60s).

4. Misleading log when the server this daemon started has died (src/gaia/daemon/lemonade.py:167) — if lemond crashed, status() returns the stopped snapshot, recorded is None, and the daemon logs "leaving embedded Lemonade (pid None) running". _started_pid also stays set, so every subsequent stop() re-logs it. Worth special-casing recorded is None as "already gone" and clearing _started_pid.

5. --check's "no side effects" wording understates what it now does (src/gaia/cli.py:3169, docs/reference/cli.mdx:199) — the help and docs say a stopped Lemonade Server is started, but not that the call may also spawn a daemon process via start_or_attach(). Worth naming, since --check is what the TUI runs on every launch. (The guard in start_embedded_if_stopped means this only happens on a machine that already ran gaia init, which is the right call.)

Strengths

  • The ownership model is the right one and is stated once, clearly, in daemon/lemonade.py's module docstring: only stop what this daemon started, never kill a server that is merely slow to answer, never replace a different version, never install. Each of those rules has a test that names the behaviour rather than the implementation.
  • Bumping DAEMON_API_VERSION to 1.2 with a _REQUIRED_LEMONADE_MINOR floor turns "stale daemon" from a bare 404 into an actionable "restart it with gaia daemon restart" — consistent with the existing _check_agents_floor, and _minor is a clean extraction rather than a copy.
  • test_concurrent_callers_start_the_server_once tests the lock's actual purpose, and test_build_deregister_still_deregisters_when_lemonade_will_not_stop pins the "a daemon that cannot exit cleanly is worse" decision so a later refactor can't quietly drop it.

Kalin Ovtcharov added 2 commits September 24, 2026 17:17
…aged

gaia init --check could call a user-chosen Lemonade Server ready that gaia
init then refused as too old, so the TUI skipped setup and failed later.
Both now share one minimum-version rule, and a server that reports no
readable version is logged rather than silently passed.

A shell that sourced GAIA's own credentials file set LEMONADE_BASE_URL to
GAIA's server, which turned off init's management of it and kept a dead
port and key after a restart. The file now also exports
GAIA_LEMONADE_EMBEDDED=1, and GAIA follows its live state instead of
those values.

Also: --check reports a failure to list profile models instead of a
traceback, the Linux troubleshooting entry about the Lemonade PPA is
replaced with the embedded download's failure modes, and stale references
to removed init helpers are fixed.
After a reboot, GAIA's own Lemonade Server was stopped and every entry
point reported "Lemonade not running" until the user re-ran gaia init. The
daemon now starts it when it comes up and whenever a GAIA command finds it
stopped: LemonadeManager.ensure_ready() and gaia init --check ask the
daemon through a new POST /daemon/v1/lemonade/ensure (host API 1.2).

The daemon stops only a server it started itself, so one started by gaia
init, by hand, or by another daemon keeps running. It never kills a server
that is slow to answer (it may be loading a model) or replaces one running
a different version; it reports those and points at gaia init. With
LEMONADE_BASE_URL set it leaves Lemonade alone. It never installs anything.
@kovtcharov
kovtcharov force-pushed the claude/daemon-owns-embedded-lemonade branch from 9d9e245 to 6904ba4 Compare September 25, 2026 00:17
@github-actions github-actions Bot added the agent::email Email agent changes label Sep 25, 2026
…aits

`gaia daemon stop` waited 10 s, but the daemon's shutdown now also stops
the Lemonade Server it started (up to 20 s) and could wait up to 60 s
behind a start still in flight, so a normal stop printed "did not exit;
terminating" and killed the daemon before its custody store closed.
Shutdown now waits at most 5 s for an in-flight start and leaves that
server running, and the stop command waits 45 s.

The TUI's setup check allowed 90 s while the Python side could spend
over two minutes starting the daemon and the server after a reboot, so
a successful start read as "could not be checked". The ensure timeout
drops to 80 s (it never stops a stalled server) and the TUI allows
150 s, with a comment tying the two together.

Also: a server this daemon started that has since exited is forgotten
instead of logged as "pid None" on every stop, and --check's help and
docs say it may start the daemon.
Kalin Ovtcharov added 4 commits September 24, 2026 21:34
Unit tests block the network, so on a developer machine with GAIA set up
the real ~/.gaia Lemonade Server looked stopped, and every test that
called LemonadeManager.ensure_ready() asked a real daemon to start it:
tests failed on start-lock timeouts and left daemons running. CI never
saw it because nothing is installed there. An autouse fixture now stubs
the start; tests of the start itself opt back in with
@pytest.mark.embedded_start.
…ade-onboarding

# Conflicts:
#	tests/unit/test_init_command.py
Windows CI failed to reach Lemonade on a port GAIA's own server had used:
test_sd's `gaia init` now starts that server on a shared self-hosted
runner, the job ended without stopping it, and its state file stayed in
the runner's home. Every later client on that runner, in any job,
followed the record to a dead port instead of the system Lemonade the
job had started.

The resolver now ignores a record whose process no longer exists (a
standard-library check, cheap enough for every lookup). In CI, the
scripts that start the system Lemonade name it through LEMONADE_BASE_URL
for the rest of the job, and test_sd stops GAIA's server when it ends.
@github-actions github-actions Bot added installer Installer changes devops DevOps/infrastructure changes labels Sep 25, 2026
Kalin Ovtcharov added 22 commits September 25, 2026 18:06
…sion

Each version unpacks into its own directory, so the old binary on disk does not
count as installed and init downloads the new one before starting it. The
existing test mocked the install check and could not show that.
…r test

A client launched by an earlier test keeps a fake server handle, so when the
collector finalizes it mid-test its __del__ runs the port cleanup against that
test's patched listener list and trips the "kills nothing" assertion. Collect
before each test and keep the fake-launched clients alive.
On Windows the system temp dir lives under the user's home, so the "outside"
target was inside home, nothing escaped, and the 403 never fired. Use a private
home with the outside dir beside it.
Same Windows trap as the home-escape test: tmp_path sits inside the user's
profile, so the outside dir was readable on home's account and nothing escaped.
The message formats the path with %r, which doubles every backslash on Windows,
so a substring check against sys.executable could never match there.
Each version unpacks into its own dist dir, so is_installed() is false for a
new version even with the old binary on disk.
A Windows checkout converted install.sh to CRLF, and dash then rejected
`case ... in\r` as a syntax error, failing the Windows parse test and
breaking the script for anyone running it from such a checkout.
On Windows the models and Hugging Face caches resolve from LOCALAPPDATA/HF_HOME
before the home dir, so the purge-models test got the runner's real cache path
instead of the fake home's. Clear both in the fixture.
The expected substrings use "/" but Windows prints "\", so the dry-run
test could never pass there.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit ef861f9 Sep 26, 2026
83 of 84 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/daemon-owns-embedded-lemonade branch September 26, 2026 03:44
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
On a first run, callers that start at the same moment (Agent UI boot
plus the first chat, or several sidecars) each saw an idle Lemonade
server and sent their own `/load` — up to two parallel multi-GB
downloads and two cold loads of the same model. Now the first caller
loads the model and the rest wait for it, then pick up the result; if
that load fails, each waiter retries and reports its own error instead
of hanging.

The existing concurrency test couldn't catch this because its mock
returned "loaded" on the second status read; it now blocks in
`load_model` and keeps the server idle until the load finishes, so it
fails on `main` (2 loads) and passes here.

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

- `LemonadeManager._preload_in_flight` (a `threading.Event`) is set
before `_try_preload_with_ctx` releases the lock and cleared in its
`finally` after re-acquiring. `ensure_ready` waits on it, with the lock
released, at the top of its locked block.
- Overlap with open PRs: amd#4176 renames `DEFAULT_MODEL_NAME` → `model`
inside `_try_preload_with_ctx` and amd#4193 adds a daemon start call after
the "Initializing Lemonade" log in `ensure_ready`. Neither changes the
lock handling, so they shouldn't conflict beyond possible adjacent-line
rebases.
</details>

## Test plan
- [x] `pytest tests/unit/test_lemonade_manager_preload.py -k
concurrent`: fails on `origin/main` (`load_model` called 2 times),
passes with the fix (5/5 repeated runs)
- [x] `pytest tests/unit/test_lemonade_manager_preload.py`: 23 passed,
including the new `test_failed_preload_releases_waiting_callers`
- [x] Neighbouring `LemonadeManager` suites (`test_chat_preflight`,
`test_hardware_selection`, `test_llm`, `test_multi_device_wiring`,
`test_npu_device_support`, `test_base_agent_lemonade_api_key`,
`test_init_verify_ctx_display`, `chat/ui/test_server`,
`chat/ui/test_chat_helpers`): 333 passed
- [x] black / isort / pylint clean on the changed files

Fixes amd#4212

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
amd#4309)

**Stacked on amd#4193 (which is stacked on amd#4192).** Until those merge,
this diff includes their commits; review only the last commit here.

On a PC set up by `gaia init`, GAIA's own Lemonade Server runs on a
private port, but about 20 places still looked for Lemonade on the old
default port and found nothing. The Agent UI's status and onboarding
screens, the OpenAI-compatible API server's health check, the builder
agent and the email agent all reported the model server as missing. Now
every lookup goes through one resolver: `LEMONADE_BASE_URL` if set,
otherwise GAIA's own running server, otherwise the old default. With no
GAIA server recorded, nothing changes.

The email agent had a second problem on the same path: its readiness
check called GAIA's server without the API key, got a 401, and reported
the server's version as unknown. It now sends the key, as does the API
server's health check.

## Test plan
- [x] `pytest tests/unit` (14,472 passed; the one failure needs a live
transcription server) plus the email and flagship agents' own tests with
those packages on the path
- [x] New tests: the Agent UI's system and onboarding lookups follow
GAIA's recorded server, and a configured URL still wins. The API server
and email agent health probes send that server's key. The flagship's
health report names the URL the client would really have used.
- [x] With only GAIA's own Lemonade running (scratch `GAIA_HOME`, no
`LEMONADE_BASE_URL`): `gaia api start`, then `curl
localhost:8611/health` reports the model backend ready at GAIA's server
(output below)
- [ ] On a PC with only GAIA's own Lemonade (no system install): the
Agent UI's system status shows the model server as running, and the
email agent's `GET /v1/email/init` reports the server's version

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

- Removing the fallback to the default port, which the self-hosted CI
runners still rely on, is a separate change.
- Several email-agent messages still say `lemonade-server serve`, and
two tests assert them. They are left for a repo-wide sweep of that
command's mentions.
- Two tests that assumed the default port (flagship `test_stdio`, email
`test_model_select`) now pin an empty `GAIA_HOME`, so they no longer
depend on whether the developer's machine has GAIA set up.
</details>



<details>
<summary>API server health with only GAIA's own Lemonade running (Apple
Silicon)</summary>

```
$ gaia lemonade embedded status
Running:   yes on http://localhost:52461/api/v1 (pid 9670)
$ gaia api start --port 8611 &
$ curl -s localhost:8611/health
{"status":"ok","service":"gaia-api","components":{"api":{"status":"ready"},"llm":{"status":"ready","backend":"lemonade","model":"Gemma-4-E4B-it-GGUF","url":"http://localhost:52461/api/v1"},"rag":{"status":"not_configured"}}}
HTTP 200
```
</details>

---------

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

Labels

agent::email Email agent changes cli CLI changes daemon Daemon supervisor / sidecar control plane devops DevOps/infrastructure changes documentation Documentation changes installer Installer changes llm LLM backend changes performance Performance-critical changes tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants